repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
nabsboss/CouchPotatoServer | libs/guessit/language.py | Python | gpl-3.0 | 13,102 | 0.003207 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2011 Nicolas Wack <[email protected]>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free ... |
'català': ('cat', None),
'cz': ('cze', None),
'ua': ('ukr', None),
'cn': ('chi', None),
'chs': ('chi', None),
'jp': ('jpn', None),
| 'scr': ('hrv', None)
}
def is_iso_language(language):
return language.lower() in lng_all_names
def is_language(language):
return is_iso_language(language) or language in lng_exceptions
def lang_set(languages, strict=False):
"""Return a set of guessit.Language created from ... |
rcbops/nova-buildpackage | nova/api/openstack/compute/contrib/server_start_stop.py | Python | apache-2.0 | 2,721 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Midokura Japan K.K.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... | ller):
def __init__(self, *args, **kwargs):
super(ServerStartStopActionController, self).__init__(*args, **kwargs)
self.compute_api = compute.API()
@wsgi.action('os-start')
def _start_server(self, req, id, body):
"""Start an instance. """
context = req.environ['nova.context'... | id)
instance = self.compute_api.get(context, id)
self.compute_api.start(context, instance)
except exception.ApiError, e:
raise webob.exc.HTTPBadRequest(explanation=e.message)
except exception.NotAuthorized, e:
raise webob.exc.HTTPUnauthorized()
re... |
mod2/momentum | momentum/migrations/0010_target_data_migration.py | Python | mit | 517 | 0.003868 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
d | ef populate_target_amount(apps, schema_editor):
Entry = apps.get_model("momentum", "Entry")
for entry in Entry.objects.all():
entry.target_amount = entry.goal.target_amount
entry.save()
class Migration(migrations.Migration):
dependencies = [
('momentum', '0009_entry_target_amount'... | ations = [
migrations.RunPython(populate_target_amount),
]
|
scopatz/regolith | regolith/sorters.py | Python | cc0-1.0 | 2,389 | 0.002093 | """Builder for websites."""
import string
from regolith.dates import date_to_float
doc_date_key = lambda x: date_to_float(
x.get("year", 1970), x.get("month", "jan")
)
ene_date_key = lambda x: date_to_float(
x.get("end_year", 4242), x.get("end_month", "dec")
)
category_val = lambda x: x.get("category", "<unca... | sor": 8,
"assistant physicist": 8,
"associate professor": 9,
"associate physicist": 9,
"professor emeritus": 9,
"visiting professor": 9,
"manager": 10,
"director": 10,
"scientist": 10,
"engineer": 10,
"physicist": 10,
"professor": 11,
"president": 10,
"distinguished p... | ch group."""
pos = x.get("position", "").lower()
first_letter_last = x.get("name", "zappa").rsplit(None, 1)[-1][0].upper()
backward_position = 26 - string.ascii_uppercase.index(first_letter_last)
return POSITION_LEVELS.get(pos, -1), backward_position
|
pism/pism | doc/acknowledge.py | Python | gpl-3.0 | 3,113 | 0.004497 | #!/usr/bin/env python3
header = """
..
DO NOT EDIT: This file was automatically generated by running doc/acknowledge.py
Edit doc/acknowledge.py, doc/funding.csv, and doc/citing-pism.bib
"""
acknowledgement = """
Acknowledging PISM funding sources
----------------------------------
If you use PISM in a publica... | 1])
else:
return join(["{}, {}".format(strings[0], strings[1]),
join(strings[2:])])
grants = []
for k, v in funding.items():
grant = "grant"
if len(v) > 1:
grant = "grants"
grants.append("{agency} {grant} {number}".format(agency=k,
... | manual:
print(header)
print("""
Development of PISM is supported by {grants}.""".format(grants=join(grants)))
else:
print(header)
print(acknowledgement)
print("""
Development of PISM is supported by {grants}.
""".format(grants=join(grants)))
print(citing)
with open("citing-pism.bib") as ... |
be-cloud-be/horizon-addons | server-tools/database_cleanup/tests/test_database_cleanup.py | Python | agpl-3.0 | 4,939 | 0 | # -*- coding: utf-8 -*-
# © 2016 Therp BV <http://therp.nl>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from psycopg2 import ProgrammingError
from openerp.modules.registry import RegistryManager
from openerp.tools import config
from openerp.tests.common import TransactionCase, at_install, post_... | purge_all()
with self.assertRaises(ProgrammingError):
with self.registry.cursor() as cr:
self.env.cr.execute('select * from database_cleanup_test')
def tearDown(self):
super(TestDatabaseCleanup, self).tearDown()
with self.registry.cursor() as cr2:
# R... | ollback()
if self.module:
cr2.execute(
"DELETE FROM ir_module_module WHERE id=%s",
(self.module.id,))
if self.model:
cr2.execute(
"DELETE FROM ir_model WHERE id=%s",
(self.model.id,))
... |
gleitz/howdoi | howdoi/__main__.py | Python | mit | 63 | 0 | f | rom .howdoi import command_line_runner
command_line | _runner()
|
dev-coop/meancoach | meancoach_project/apps/meancoach/tests/smoke_tests.py | Python | mit | 258 | 0 | from django.core.urlresolvers import r | everse
from django.test import TestCase
class SmokeTestMeanCoach(TestCase):
def test_index_page_returns_200(self):
resp = self.client.get(reverse('meancoach:index' | ))
assert resp.status_code == 200
|
antoinedube/numeric-cookiecutter | {{cookiecutter.namespace+'.'+cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/commands/configure.py | Python | gpl-3.0 | 571 | 0.003503 | #!/usr/bin/python
# coding: utf8
import os
import subprocess
from '{% if cookiecutter.namespace %}{{ cookiecu | tter.namespace }}.{{ cookiecutter.project_slug }}{% else %}{{ cookiecutter.project_slug }}{% endif %}'.commands.base import BaseCommand
from '{% if cookiecutter.namespace %}{{ cookiecutter.namespace }}.{{ cookiecutter.project_slug }}{% else %}{{ cookiecutter.project_slug }}{% endif %}' import | PROJECT_DIR
class Configure(BaseCommand):
def execute(self):
os.chdir(os.path.join(PROJECT_DIR, 'build'))
subprocess.run(['cmake', PROJECT_DIR])
|
QCaudron/ivanatrumpalot | code/train_lstm.py | Python | mit | 5,169 | 0.003289 | import sys
import re
import numpy as np
import json
import pickle
from string import ascii_letters
from keras.models import S | equential, model_from_json
from keras.layers import Dense, Activation, Dropout
from keras.layers import LSTM
from ivanatrumpalot import clean_text, predict, sample
# This code is heavily influenced by the Keras example code on LSTM for text generation :
# https://github.com/fchollet/keras/blob/master/examples/lstm_t... | AGE :
# python train_lstm.py [mode]
# If no arguments are passed, this will train a new model, saving the model's architecture
# to model.json and its weights to weights.h5.
# If [mode] is passed, valid options are "extend" and "predict".
# If the string "extend" is passed, they must be the files saved by train_lstm.py... |
hksonngan/pynopticon | src/pynopticon/link_to_orange.py | Python | gpl-3.0 | 628 | 0.012739 | import os.path
import shutil
try:
import OWGUI
except ImportError:
print "Orange could not be imported."
try:
import pynopticon
except ImportError:
print "Pynopticon could not be imported, you need to install it first."
def link_to_orange():
orangeWidgetsPath = os.path.join(os.path.spli... | tsPath)
print "Successfull"
if __name__=='__main__':
link_to_orange( | )
|
Krigu/python_fun | Pland1/Parser.py | Python | gpl-3.0 | 1,456 | 0.000687 | from collections import defaultdict
def check_for_hits(planets, counts | ):
total = 0
for planet in planets():
| if counts(planet):
total += 1
return total
def parse():
actions = {"U": (lambda: map_x[x], lambda j: j > y),
"D": (lambda: map_x[x], lambda j: j < y),
"L": (lambda: map_y[y], lambda j: j < x),
"R": (lambda: map_y[y], lambda j: j > x) }
for x in r... |
stonestone/stonefreedomsponsors | djangoproject/core/views/watch_views.py | Python | agpl-3.0 | 558 | 0.003584 | # Create your views here.
from django.contrib.auth.decorators import login_required
from core.models import *
from django.http import HttpResponse
from core.s | ervices import watch_services
from django.utils.translation import ugettext as _
@l | ogin_required
def watchIssue(request, issue_id):
watch_services.watch_issue(request.user, int(issue_id), Watch.WATCHED)
return HttpResponse('WATCHING')
@login_required
def unwatchIssue(request, issue_id):
watch_services.unwatch_issue(request.user, int(issue_id))
return HttpResponse('NOT_WATCHING')
|
gitsimon/spadup-lyra | abstract_domains/numerical/interval_domain.py | Python | mpl-2.0 | 13,333 | 0.001876 | from copy import deepcopy
from math import inf
from numbers import Number
from typing import List, Union
from abstract_domains.lattice import BottomMixin
from abstract_domains.numerical.numerical import NumericalMixin
from abstract_domains.state import State
from abstract_domains.store import Store
from core.expressio... | k_types
def sub(self, other: Union['Interval', int]) -> 'Interval':
if self.empty() or other.empty():
return self.set_empty() |
else:
self.interval = (self.lower - other.upper, self.upper - other.lower)
return self
@_auto_convert_numbers
@_check_types
def mult(self, other: Union['Interval', int]) -> 'Interval':
if self.empty() or other.empty():
return self.set_empty()
els... |
tylertian/Openstack | openstack F/glance/glance/__init__.py | Python | apache-2.0 | 733 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache... | by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import g... | ttext
gettext.install('glance', unicode=1)
|
Bringing-Buzzwords-Home/bringing_buzzwords_home | visualize/views.py | Python | mit | 8,056 | 0.005462 | import operator
import json
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from .models import County, GuardianCounted, Geo, Item, Station, Crime, State
from .utilities import states, get_dollars_donated_by_year, format_money
from .utilities import get_... | te_deaths['2015 {} Fatal Encounters'.format(states[state])],
'average': state_deaths['2015 Average Fatal Encounters'],
'long_state_n | ame': states[state],
'counties_list': create_counties_list(state),
'categories': categories,
'twenty_fourteen_violent': format_integer(state_obj.total_violent_crime),
'twenty_fourteen_property': format_integer(state_obj.total_property_crime),
't... |
gallandarakhneorg/autolatex | src/autolatex2/cli/commands/showconfigfiles.py | Python | lgpl-3.0 | 2,465 | 0.017039 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 1998-2021 Stephane Galland <[email protected]>
#
# This program | is free library; you can redistribute it and/or modify
# it under the terms of the GNU L | esser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or any later version.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE... |
DHLabs/keep | keep_backend/organizations/models.py | Python | mit | 2,600 | 0.018846 | import hashlib
from django.contrib.auth.models import Group
from django.db import models
USER_MODEL = 'auth.User'
class Organization( Group ):
| '''
Umbrella object with which users are associated.
An organization can have multiple users.
'''
gravatar = models.EmailField( blank=True )
owner = models.ForeignKey( USER_MOD | EL )
users = models.ManyToManyField( USER_MODEL,
through='OrganizationUser',
related_name='organization_users' )
class Meta:
ordering = [ 'name' ]
verbose_name = 'organization'
verbose_name_plural = 'organizations'
... |
pypa/virtualenv | tests/unit/activation/test_nushell.py | Python | mit | 816 | 0.001225 | from __future__ import absolute_import, unicode_literals
import sys
if sys.version_info > (3,):
from shutil import which
else:
from distutils.spawn import find_executable as which
from virtualenv.activation import NushellActivator
from virtualenv.info import IS_WIN
def test_nushell(activation_tester_class... | cmd = "c:\\program files\\nu\\bin\\nu.exe"
super(Nushell, self).__init__(NushellActivator, session, cmd, "activate.nu", "nu")
self.unix_line_ending = | not IS_WIN
def print_prompt(self):
return r"echo $virtual_prompt; printf '\n'"
activation_tester(Nushell)
|
foligny/browsershots-psycopg2 | throxy/throxy.py | Python | gpl-3.0 | 19,293 | 0.001451 | #! /usr/bin/env python
# throxy.py - HTTP proxy to simulate dial-up access
# Copyright (c) 2007 Johann C. Rocholl <[email protected]>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software w... | cript on your local machine and adjust your
browser settings to use 127.0.0.1:8080 as HTTP proxy.
* Simulate a slow connection (like dial-up).
* Adjustable bandwidth limit for download and upload.
* Optionally dump HTTP headers and content for debugging.
* Decompress gzip content encoding for debugging.
* Multiple con... | s (uses asyncore).
* Only one source file, written in pure Python.
Simulate analog modem connection:
$ python throxy.py -u28.8 -d57.6
Show all HTTP headers (request & reply):
$ python throxy.py -qrs
Dump HTTP headers and content to a file, without size limits:
$ python throxy.py -rsRS -l0 -L0 -g0 > dump.txt
Tell co... |
jaesivsm/pyAggr3g470r | jarr/controllers/abstract.py | Python | agpl-3.0 | 5,796 | 0.000173 | import logging
from datetime import timezone
import dateutil.parser
from sqlalchemy import and_, or_
from werkzeug.exceptions import Forbidden, NotFound, Unauthorized
from jarr.bootstrap import Base, session
logger = logging.getLogger(__name__)
def cast_to_utc(dt_obj):
dt_obj = dateutil.parser.parse(dt_obj)
... | elf, obj_id):
if not self.user_id:
raise ValueError("%r user_id can't be None" % self)
rows = self.__ | class__().read(id=obj_id).with_entities(
getattr(self._db_cls, self._user_id_key)).first()
if not rows:
raise NotFound()
if not rows[0] == self.user_id:
raise Forbidden()
|
chubbymaggie/miasm | setup.py | Python | gpl-2.0 | 6,252 | 0.006718 | #! /usr/bin/env python
from distutils.core import setup, Extension
from distutils.util import get_platform
import shutil
import os, sys
def buil_all():
packages=['miasm2',
'miasm2/arch',
'miasm2/arch/x86',
'miasm2/arch/arm',
'miasm2/arch/aarch64',
... | ,
# data_files = [('toto', ['miasm2/tools/emul_lib/queue.h'])],
# Metadata
author = 'Fabrice Desclaux',
author_email = '[email protected]',
description = 'Machine code manipulation library',
license = 'GPLv2',
# keywords = '',
# url = '',
)
... | build with libtcc!, trying without it"
print "Miasm will not be able to emulate code"
buil_no_tcc()
"""
try_build()
|
NavarraBiomed/seguimientoPacientes | ictus/migrations/0029_auto_20161212_1316.py | Python | gpl-2.0 | 852 | 0.00235 | # -*- cod | ing: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('ictus', '0028_auto_20161212_1316'),
]
operations = [
migrations.A | lterField(
model_name='basal',
name='alcohol',
field=models.IntegerField(null=True, choices=[('00', 'No'), ('01', 'A diario'), ('02', 'Ocasionalmente'), ('03', 'Exhabito enólico')], blank=True, verbose_name='Alcohol'),
),
migrations.AlterField(
model_name=... |
LastAvenger/labots | labots/common/message.py | Python | gpl-3.0 | 223 | 0.004484 | fr | om typing import List
class Message(object):
class Origin(object):
servername: str
nickname: str
username: str
hostname: str
command: str
| origin: Origin
params: List[str]
|
zstackio/zstack-woodpecker | integrationtest/vm/e2e_mini/volume/test_volume_backup.py | Python | apache-2.0 | 1,389 | 0.00432 | # -*- coding:utf-8 -*-
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
volume = test_lib.lib_get_specific_stub('e2e_mini/volume', 'volume')
volume_ops = None
vm_ops = None
volume_name = 'volume-' + volume.get_time_postfix()
backup_name = 'backup-' + volume.get_time_postfix... | s.uri, initialized=True)
vm_ops.create_vm()
volume_ops.create_volume(volume_name)
volume_ops.volume_attach_to_vm(vm_ops.vm_name)
volume_ops.create_backup(volume_na | me, 'volume', backup_name)
vm_ops.vm_ops(vm_ops.vm_name, action='stop')
volume_ops.restore_backup(volume_name, 'volume', backup_name)
volume_ops.delete_backup(volume_name, 'volume', backup_name)
volume_ops.check_browser_console_log()
test_util.test_pass('Test Volume Create, Restore and Delete Backup... |
Sotera/aggregate-micro-paths | hive-streaming/conf/config.py | Python | apache-2.0 | 3,321 | 0.016561 | # Copyright | 2016 Sotera Defense Solutions Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | r the specific language governing permissions and
# limitations under the License.
import math
import six
if six.PY2
from ConfigParser import SafeConfigParser
else
from configparser import SafeConfigParser
class AggregateMicroPathConfig:
config_file = ""
table_name = ""
table_schema_id = ""
... |
xualex/DjangoTutorial | alex/alex/wsgi.py | Python | mit | 386 | 0 | """
WSGI config for alex project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproj | ect.co | m/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "alex.settings")
application = get_wsgi_application()
|
CCI-Tools/cate-core | cate/conf/template.py | Python | mit | 5,327 | 0.007509 | ################################################################################
# This is a Cate configuration file. #
# #
# If this file is "~/.cate/conf.py", it is the active Cate configuration. ... | #
# If this file is named "conf.py.template" you can rename it and move #
# it "~/.cate/conf.py" to make it the active Cate configuration file. #
# #... | use any Python code to compute #
# the settings provided here. #
# #
# Please find the configuration template for a given Cate VERSION at #
# https://github.com/CCI-Tools/cate/blo... |
superstack/nova | nova/api/openstack/users.py | Python | apache-2.0 | 3,531 | 0.000283 | # Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | under the License.
from webob import exc
from nova import exception
from nova imp | ort flags
from nova import log as logging
from nova.api.openstack import common
from nova.api.openstack import faults
from nova.auth import manager
FLAGS = flags.FLAGS
LOG = logging.getLogger('nova.api.openstack')
def _translate_keys(user):
return dict(id=user.id,
name=user.name,
... |
charanpald/APGL | apgl/graph/SparseGraph.py | Python | bsd-3-clause | 19,320 | 0.008023 |
from apgl.graph.AbstractMatrixGraph import AbstractMatrixGraph
from apgl.graph.AbstractVertexList import AbstractVertexList
from apgl.graph.GeneralVertexList import GeneralVertexList
from apgl.graph.VertexList import VertexList
from apgl.util.Util import Util
from apgl.util.SparseUtils import SparseUtils
fro... | ng
those vertices only, and edges between them. The subgraph indices correspond
to the sorted input indices.
:param vertexIndices: the indices of the subgraph vertices.
:type vertexIndices: :class:`list`
:returns: A new SparseGraph containing only vertices and edges fro... | s
"""
Parameter.checkList(vertexIndices, Parameter.checkIndex, (0, self.getNumVertices()))
vertexIndices = numpy.unique(numpy.array(vertexIndices)).tolist()
vList = self.vList.subList(vertexIndices)
subGraph = SparseGraph(vList, self.undirected)
if len(v... |
shiquanwang/numba | numba/asdl/common/asdl.py | Python | bsd-2-clause | 13,170 | 0.001974 | # -*- coding: utf-8 -*-
"""An implementation of the Zephyr Abstract Syntax Definition Language.
See http://asdl.sourceforge.net/ and
http://www.cs.princeton.edu/research/techreps/TR-554-97
Only supports top level module decl, not view. I'm guessing that view
is intended to support the browser and I'm not interested ... | , definitions, None)
def p_version(self, xxx_todo_changeme2):
"version ::= Id String"
(ve | rsion, V) = xxx_todo_changeme2
if version.value != "version":
raise ASDLSyntaxError(version.lineno,
msg="expected 'version', found %" % version)
return V
def p_definition_0(self, xxx_todo_changeme3):
" definitions ::= definition "
(definit... |
khosrow/luma-devel | luma/base/gui/design/ServerDialogDesign.py | Python | gpl-2.0 | 36,277 | 0.003556 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/mnt/debris/devel/repo/git/luma-fixes/resources/forms/ServerDialogDesign.ui'
#
# Created: Wed May 25 21:41:09 2011
# by: PyQt4 UI code generator 4.8.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, Q... | zePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.networkIcon.sizePolicy().hasHeightForWidth())
self.networkIcon.setSizePolicy(sizePolicy)
self | .networkIcon.setMinimumSize(QtCore.QSize(48, 48))
self.networkIcon.setText(_fromUtf8(""))
self.networkIcon.setObjectName(_fromUtf8("networkIcon"))
self.gridlayout.addWidget(self.networkIcon, 0, 0, 1, 1)
self.networkOptGrid = QtGui.QGridLayout()
self.networkOptGrid.setObjectName(_... |
scheib/chromium | third_party/blink/web_tests/external/wpt/cookies/resources/dropSecure.py | Python | bsd-3-clause | 501 | 0.001996 | from cookies. | resources.helpers import makeDropCookie, setNoCacheAndCORSHeaders
def main(request, response):
"""Respond to `/cookie/drop/secure` by dropping the two cookie set by
`setSecureTestCookies()`"""
headers = setNoCacheAndCORSHeaders(request, response)
# Expire the cookies, and return a JSON-encoded success... | ess": true}'
|
pandastrail/InfoEng | scripting/exercises/p06_2.py | Python | gpl-3.0 | 1,641 | 0.007932 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 18 16:28:59 2017
@author: hase
2. Credit Card Number Check
Suppose you have been hired by MeisterCard to write a function
which checks if a given credit card number is valid.
Your function check(card_number) should take a string card_number as in... | n False.
- Then, if the sum of the digits is divisible by 10 (a "checksum" method),
then the procedure should return True, o | therwise it should return False.
For example, if card_number is the string "9384 3495 3297 0123" then although
the format is correct, the digit’s sum is 72 so you should return False.
Hints:
- You can split a string at a specific character using the function split().
parts = my_string.split('a')
- You can test if a s... |
danielvdende/incubator-airflow | airflow/api/auth/backend/default.py | Python | apache-2.0 | 1,051 | 0 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | cense for the
# specific language governing permissions and limitations
# under the License.
from functools import wraps
client_auth = None
def init_app(app):
pass
def requires_authentication(function):
@wraps(function)
def decorated(*args, **kwargs):
return function(*args, **kwargs)
retu... | ecorated
|
teirce/game-valet | app/startup/common_settings.py | Python | bsd-2-clause | 957 | 0.00209 | import os
# ***********************************
# Settings common to all environments
# ***********************************
# Application settings
APP_NAME = "Game Valet"
APP_SYSTEM_ERROR_SUBJECT_LINE = APP_NA | ME + " system error"
# Flask settings
CSRF_ENABLED = True
# Flask-User settings
USER_APP_NAME = APP_NAME
USER_ENABLE_CHANGE_PASSWORD = True # Allow users to change their password
USER_ENABLE_CHANGE_USERNAME = False # Allow users to change their username
USER_ENABLE_CONFIRM_EMAIL = True # Force u | sers to confirm their email
USER_ENABLE_FORGOT_PASSWORD = True # Allow users to reset their passwords
USER_ENABLE_EMAIL = True # Register with Email
USER_ENABLE_REGISTRATION = True # Allow new users to register
USER_ENABLE_RETYPE_PASSWORD = True # Prompt for `retype password` in:
USER_ENABLE_USERNAME = False # Reg... |
dmschreiber/tapiriik | tapiriik/web/email.py | Python | apache-2.0 | 963 | 0.015576 | from djan | go.template.loader import get_template
from django.template import Context
from django.core.mail import EmailMultiAltern | atives
from django.conf import settings
def generate_message_from_template(template, context):
context["STATIC_URL"] = settings.STATIC_URL
# Mandrill is set up to inline the CSS and generate a plaintext copy.
html_message = get_template(template).render(Context(context)).strip()
context["plaintext"] = True
plaint... |
JNero/Machine-Learning-in-action | DicisionTree/trees.py | Python | apache-2.0 | 3,852 | 0.003375 | import matplotlib.pyplot as plt
import operator
from math import log
import pickle
def calcShannonEnt(dataSet):
numEntries = len(dataSet)
labelCounts = {}
for fv in dataSet:
currentLabel = fv[-1]
if currentLabel not in labelCounts.keys():
labelCounts[currentLabel] = 0
l... | alue in uniqueVals:
subLabels = labels[:]
myTree[bestFeatLabel][value] = createTree(
splitDataSet(dataSet, bestFeat, value), subLabels)
return myTree
def classify(in | putTree, featLabels, testVec):
firstStr = list(inputTree.keys())[0]
# print('firstStr is : ',firstStr)
secondDict = inputTree[firstStr]
# print('secondDict is :',secondDict)
featIndex = featLabels.index(firstStr)
# print('featIndex is :',featIndex)
# print(type(featIndex))
for key in secondDict.keys():
... |
iohannez/gnuradio | gr-comedi/python/comedi/qa_comedi.py | Python | gpl-3.0 | 1,256 | 0.001592 | #!/usr/bin/env python
#
# Copyright 2005,2007,2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your ... | t even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Fra... | 0-1301, USA.
#
from gnuradio import gr, gr_unittest, comedi
class test_comedi(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_000_nop(self):
"""Just see if we can import the module...
They may not have COMEDI ... |
all-of-us/raw-data-repository | rdr_service/dao/resource_dao.py | Python | bsd-3-clause | 2,900 | 0.001034 | #
# This file is subject to the terms and conditions defined in the
# file 'LICENSE', which is part of this source code package.
#
from collections import OrderedDict
from sqlalchemy import inspect
from sqlalchemy.engine import ResultProxy
from rdr_service.dao.base_dao import UpsertableDao
from rdr_service.model.reso... | ) == EnumInteger:
value = int(_field.enum(value))
data[key] = value
# Automatically generate an integer field for enum/string fields that have a paire | d _id integer field
# E.g.: status/status_id, code_type/code_type_id, etc.
if int_id_value:
data[key + '_id'] = int_id_value
return data
|
dschien/PyExcelModelingHelper | tests/test_DataSeriesLoader.py | Python | mit | 3,547 | 0.003383 | import unittest
from datetime import datetime
import numpy as np
import pandas as pd
from excel_helper.helper import DataSeriesLoader
class TestDataFrameWithCAGRCalculation(unittest.TestCase):
def test_simple_CAGR(self):
"""
Basic test case, applying CAGR to a Pandas Dataframe.
:return:... | )
# equivalent to dfl['test_ref_date_before_start']
self.assertRaises(AssertionError, dfl.__getitem__, 'test_ref_date_after_end')
def test_simple_CAGR_from_pandas(sel | f):
times = pd.date_range('2009-01-01', '2009-04-01', freq='MS')
xls = pd.ExcelFile('test.xlsx')
df = xls.parse('Sheet1')
ldr = DataSeriesLoader.from_dataframe(df, times, size=2)
res = ldr['static_one']
assert res.loc[[datetime(2009, 1, 1)]][0] == 1
assert np.ab... |
gmangavin/PyMegle | Other Py/PyMegleTwo.py | Python | mit | 5,053 | 0.014843 | '''
View the coding live on Twitch @ https://www.twitch.tv/gmangavin and look at the github @ https://github.com/gmangavin/PyWeb
chromedriver for gui view, phantomjs for ghost view.
'''
import selenium.webdriver #Imports module
import time #Imports time
import threading #Imports threading, used to have multiple things... | e N == False:
EngineChoice = input('Would you like a visual of the bot? (Y/N): ') #Part one for the web driver choice
YN = (EngineChoice.lower()) #Prevents capatalization error.
if YN == ('y'):
while N == False:
VarChoice = input('Would you like Fi | refox or Chrome? (F/C): ') #Part two for the web driver choice
FC = (VarChoice.lower()) #Prevents capatalization error.
if FC == ('f'):
try:
WebVar = selenium.webdriver.Firefox()
N = True
except selenium.common.exceptions.We... |
hms-dbmi/clodius | clodius/tiles/hitile.py | Python | mit | 10,847 | 0.001106 | import base64
import h5py
import math
import numpy as np
import os
import os.path as op
def array_to_hitile(
old_data, filename, zoom_step=8, chunks=(1e6,), agg_function=np.sum
):
"""
Downsample a dataset so that it's compatible with HiGlass (filetype: hitile, datatype: vector)
Parameters
-------... | 1,), dtype="f")
meta.attrs["tile-size"] = tile_size
meta.attrs["zoom-step"] = zoom_step
meta.attrs["max-length"] = max_pos
meta.attrs["max-zoom"] = max_zoom
meta.attrs["max-width"] = tile_size * 2 ** max_zoom
min_data = da.from_array(old_data, chunks)
max_data = da.from_array(old_data, chu... | "values_" + str(z), (len(old_data),), dtype="f", compression="gzip"
)
mins_dset = f_new.require_dataset(
"mins_" + str(z), (len(old_data),), dtype="f", compression="gzip"
)
maxs_dset = f_new.require_dataset(
"maxs_" + str(z), (len(old_data),), dtype="f", c... |
eevee/cocos2d-mirror | test/test_spawn.py | Python | bsd-3-clause | 1,024 | 0.030273 | # This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "s, t 5, s, t 10.1, s, t 10.2, s, q"
tags = "spawn, Reverse"
import cocos
from cocos.director import director
from cocos.actions import Rotate, R... | self.sprite.do( seq )
self.sprite | 2.do( Reverse( seq ) )
def main():
director.init()
test_layer = TestLayer ()
main_scene = cocos.scene.Scene (test_layer)
director.run (main_scene)
if __name__ == '__main__':
main()
|
Coaxis-ASP/opt | backend/api/tests/factories.py | Python | gpl-3.0 | 1,150 | 0 | import factory
from api import models
class ClientFactory(factory.DjangoModelFactory):
class Meta:
model = models.Client
name = 'Coaxis'
@factory.django.mute_signals(models.post_save)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = models.MyUser
email = factory.... | Factory(factory.DjangoModelFactory):
| class Meta:
model = models.Employee
user = factory.SubFactory(UserFactory)
is_technician = False
@factory.post_generation
def clients(self, create, extracted, **kwargs):
if not create: # Simple build, do nothing.
return
if extracted: # A list of objects were p... |
openaid-IATI/OIPA | OIPA/api/generics/views.py | Python | agpl-3.0 | 6,974 | 0.000143 | import copy
from django.db.models.fields.related import ForeignKey, OneToOneField
from rest_framework import mixins
from rest_framework.generics import (
GenericAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView,
RetrieveUpdateDestroyAPIView
)
from api.generics.serializers import (
DynamicFieldsMode... | fields = list(self.fields)
try:
fields.remove('aggregations')
except ValueError:
pass
# Assign it again
self.fields = tuple(fields)
return getattr(self, 'fields', ())
def filter_queryset(self, queryset, *args, **kwargs):
... | ' in filter_fields:
filter_fields.pop('fields')
if 'format' in filter_fields:
filter_fields.pop('format')
if 'page' in filter_fields:
filter_fields.pop('page')
if 'page_size' in filter_fields:
filter_fields.pop('page_size')
if 'ordering' in... |
nmahlangu/cs263-project-one | exploit-2c.py | Python | mit | 1,279 | 0.016419 | #!/usr/bin/python
import sys
import socket
import traceback
import urllib
import struct
def build_exploit(shellcode):
req = "GET / HTTP/1.0\r\n" + \
"Evil: {evil}\r\n" + \
"Host: birk105.studby.uio.no:81\r\n\r\n"
# 536 is first address that causes the server to not return a valid response
req = req.rep... | socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting to %s:%d..." % (host, port))
sock.connect((host, port))
print("Connected, sending request...")
sock.send(req)
print("Request sent, waiting for reply...")
rbuf = sock.recv(1024)
resp = ""
while len(rbuf):
resp = re... |
if len(sys.argv) != 3:
print("Usage: " + sys.argv[0] + " host port")
exit()
try:
shellfile = open("shellcode.bin", "r")
shellcode = shellfile.read()
req = build_exploit(shellcode)
print("HTTP request:")
print(req)
resp = send_req(sys.argv[1], int(sys.argv[2]), req)
print("HTTP res... |
zenn1989/scoria-interlude | L2Jscoria-Game/data/scripts/quests/269_InventionAmbition/__init__.py | Python | gpl-3.0 | 2,003 | 0.044433 | # Rewritten by RayzoR
import sys
from com.l2scoria.gameserver.model.quest import State
from com.l2scoria.gameserver.model.quest import QuestState
from com.l2scoria.gameserver.model.quest.jython import QuestJython as JQuest
qn = "269_InventionAmbition"
class Quest (JQuest) :
def __init__(self,id,name,descr):
J... | "32486-05.htm" :
st.exitQuest(1)
st.playSound("ItemSound.quest_finish")
return htmlt | ext
def onTalk (self,npc,player):
htmltext = "<html><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>"
st = player.getQuestState(qn)
if not st : return htmltext
npcId = npc.getNpcId()
id = st.getState()
EnergyOres = st... |
jiangzhw/Beebeeto-framework | utils/payload/webshell/php.py | Python | gpl-2.0 | 400 | 0.005 | #author: fyth
from | webshell import *
class PhpShell(Webshell):
_password = 'cmd'
_content = "<?php var_dump(md5(123));@assert($_REQUEST['{0}']);?>"
_check_statement = 'var_dump(md5(123));'
_keyword = '202cb962ac59075b964b07152d234b70'
class PhpVerify(VerifyShell):
_content = "<?php var_dum | p(md5(123));unlink(__FILE__);?>"
_keyword = '202cb962ac59075b964b07152d234b70'
|
revarbat/epubber | epubber/views/main.py | Python | bsd-2-clause | 2,968 | 0.003706 | from __future__ import absolute_import
import re, os, sys
from clay import app
import clay.config
from flask import make_response, request, redirect, render_template, url_for
from epubber.fimfic_epubgen import FimFictionEPubGenerator
site_epub_classes = [
FimFictionEPubGenerator
]
accesslog = clay.config.get... | ke shorter URLs for CSS files.
'''
path = re.sub(r'[^ | A-Za-z0-9_+.-]', r'_', path)
return redirect(url_for('static', filename=os.path.join('css', path)))
#####################################################################
# Main
#####################################################################
def main():
# Make templates copacetic with UTF8
reload(s... |
PrayAndGrow/server | patrons/apps.py | Python | lgpl-3.0 | 89 | 0 | from django.apps import AppConfig
class PatronsConf | ig(AppConfig) | :
name = 'patrons'
|
dotskapes/dotSkapes | models/003_data_manager.py | Python | mit | 10,267 | 0.019382 | import pymongo
from pymongo.objectid import ObjectId
import pymongo.cursor
class MongoWrapper:
def __init__ (self, cursor, model = None):
if model:
if not cursor['public']:
if not auth.user.id == cursor['owner']:
raise HTTP (401)
self.__dict__['cursor... | '$or': query
})
return data
def local_load (self, datatype, keywords = None):
user = dm.user ()
if not user.has_key (datatype):
user[datatype] | = []
mongo.users.update ({'_id': user['_id']}, {'$set': {datatype: []}})
ids = user[datatype]
#data = mongo[datatype].find ({'_id': {'$in': ids}})
data = self.collections[datatype].find ({'_id': {'$in': map (lambda x: ObjectId (x), ids)}})
return data
def load_keyworded... |
tmerrick1/spack | var/spack/repos/builtin/packages/cuda/package.py | Python | lgpl-2.1 | 3,901 | 0.001794 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | 'dd6e33e10d32a29914b7700c7b3d1ca0', expand=False,
url="https:// | developer.nvidia.com/compute/cuda/9.2/Prod/local_installers/cuda_9.2.88_396.26_linux")
version('9.1.85', '67a5c3933109507df6b68f80650b4b4a', expand=False,
url="https://developer.nvidia.com/compute/cuda/9.1/Prod/local_installers/cuda_9.1.85_387.26_linux")
version('9.0.176', '7a00187b2ce5c5e350e68882f... |
thomec/tango | accounts/authentication.py | Python | gpl-2.0 | 1,296 | 0.003086 | # accounts/authentication.py
import requests
import logging
from django.conf import settings
from django.contrib.auth import get_user_model
logger = logging.getLogger(__name__)
User = get_user_model()
PERSONA_VERIFY_URL = 'https://verifier.login.persona.org/verify'
#DOMAIN = 'localhost'
#DOMAIN = 'http://hotzenplot... | se.json()['email']
try:
return User.objects.get(email=email)
except User.DoesNotExist: |
return User.objects.create(email=email)
else:
logger.warning(
'Persona says no. Json was: {}'.format(response.json())
)
def get_user(self, email):
try:
return User.objects.get(email=email)
except User.DoesNotExist:
... |
jmmauricio/pypstools | dev/colormaps.py | Python | gpl-3.0 | 214 | 0.037383 | import nump | y as np
import matplotlib.pyplot as plt
x = np.arange(4)
y = x
t = [1. | 0,0.9,0.95,1.05]
s = np.array([1.0,0.9,0.95,1.05])*100
plt.scatter(x, y, c=t, s=s, alpha = 0.5)
plt.colorbar()
plt.show()
|
amyth/django-instapush | instapush/models/base.py | Python | mit | 2,928 | 0.006489 | from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .fields import HexIntegerField
from .managers import APNSDeviceManager, GCMDeviceManager
try:
instapush_settings = settings.INSTAPUSH_SETTINGS
except AttributeError:
raise ImproperlyCon... | ge(self, message, **kwargs):
"""
Sends a push notification to this device | via GCM
"""
from ..libs.gcm import gcm_send_message
data = kwargs.pop("extra", {})
if message is not None:
data["message"] = message
return gcm_send_message(registration_id=self.registration_id,
data=data, **kwargs)
class APNSDevice(BaseDevice):
... |
kratman/psi4public | psi4/driver/qcdb/periodictable.py | Python | gpl-2.0 | 78,237 | 0.013434 | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2017 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of ... | 186, 292.199786, 291.206564, 293.214670]
_temp_iso_sy | mbol = [
"H", "H1", "H2", "D", "H3", "T", "H4", "H5", "H6", "H7", "HE", "HE3", "HE4",
"HE5", "HE6", "HE7", "HE8", "HE9", "HE10", "LI", "LI3", "LI4", "LI5", "LI6",
"LI7", "LI8", "LI9", "LI10", "LI11", "LI12", "BE", "BE5", "BE6", "BE7", "BE8",
"BE9", "BE10", "BE11", "BE12", "BE13", "BE14", "BE15", "BE16", "B", "B6", "B7"... |
KatjaT/Thermodynamics | katja_thermo.py | Python | mit | 3,325 | 0.010827 | # -* | - coding: utf-8 -*-
"""
calculate thermodynamics for Katja
"""
from component_contribution.kegg_reaction import KeggReaction
from component_contribution.kegg_model import KeggModel
from component_contribution.component_contribution import ComponentContribution
from component_contribution.thermodynamic_constants import ... | dG0 of a list of a reaction.
Uses the component-contribution package (Noor et al) to estimate
the standard Gibbs Free Energy of reactions based on
component contribution approach and measured values (NIST and Alberty)
Arguments:
List of reaction strings
Ret... |
alexforencich/python-ivi | ivi/agilent/agilentMSOX92804A.py | Python | mit | 1,692 | 0.004728 | """
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2017 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Softwa | re"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subjec | t to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY
FITNESS FOR A... |
fyabc/MiniGames | HearthStone2/MyHearthStone/ai/standard.py | Python | mit | 265 | 0 | #! /usr/bin/python
# -*- coding: | utf-8 -*-
from . import agent
# Import them to register agents.
from .rule_based import basic
__author__ = 'fyabc'
def get_agent_by_name(name):
return agent.Agent.AgentClasses[name]
_ | _all__ = [
'get_agent_by_name',
]
|
AugurProject/augur-core | tests/libraries/test_reentrancy_guard.py | Python | gpl-3.0 | 855 | 0.005848 | #!/usr/bin/env python
from ethereum.tools import tester
from ethereum.tools.tester import TransactionFailed
from pytest import fixture, mark, raises
@fixture(scope='session')
def testerSnapshot(sessionFixture):
sessionFixture.uploadAndAddToController('solidity_test_helpers/ReentrancyGuardHelper.sol')
Reentran... | _nonReentrant(testerContractsFixture):
ReentrancyGuardHelper = testerContractsFixture.contracts['ReentrancyGuardHelper']
assert ReentrancyGuardHe | lper.testerCanReentrant()
with raises(TransactionFailed):
ReentrancyGuardHelper.testerCanNotReentrant()
|
phobson/bokeh | bokeh/command/__init__.py | Python | bsd-3-clause | 340 | 0.005882 | ''' P | rovides a command line application for Bokeh.
The following subcommands are available:
'''
from __future__ import absolute_import
def _build_docstring():
global __doc__
from . import subcommands
for cls in subcommands.all:
__doc__ += "%8s : %s\n" % (cls.name, cls.help)
_build_docstring()
del _b... | cstring
|
CartoDB/bigmetadata | tests/us/census/test_lodes.py | Python | bsd-3-clause | 423 | 0.004728 | '''
Test ACS columns
'''
from tasks.u | til import shell
# TODO clean this up in a more general init script
try:
shell('createdb test')
except:
pass
from nose.tools import with_setup
from tasks.us.census.lodes import WorkplaceAreaCharacteristicsColumns
from tests.util import runt | ask, setup, teardown
@with_setup(setup, teardown)
def test_wac_columns_run():
runtask(WorkplaceAreaCharacteristicsColumns())
|
datapythonista/pandas | pandas/tests/io/test_html.py | Python | bsd-3-clause | 40,117 | 0.000773 | from functools import partial
from importlib import reload
from io import (
BytesIO,
StringIO,
)
import os
from pathlib import Path
import re
import threading
from urllib.error import URLError
import numpy as np
import pytest
from pandas.compat import is_platform_windows
from pandas.errors import ParserError
... | r"\{" + flavor + r"\} is not | a valid set of flavors"
with pytest.raises(ValueError, match=msg):
read_html(url, match="google", flavor=flavor)
@td.skip_if_no("bs4")
@td.skip_if_no("lxml")
@td.skip_if_no("html5lib")
def test_same_ordering(datapath):
filename = datapath("io", "data", "html", "valid_markup.html")
dfs_lxml = rea... |
CiscoSystems/nova-solver-scheduler | nova/scheduler/solvers/constraints/num_instances_constraint.py | Python | apache-2.0 | 2,244 | 0.001337 | # Copyright (c) 2014 Cisco Systems Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | , variables, hosts, filter_properties):
num_hosts = len(hosts)
num_instances = filter_properties.get('num_instances')
var_matrix = variables.host_instance_matrix
max_instances = CONF.max_instances_per_host
for i in xrange(num_hosts):
num_host_instances = hosts[i].n... | acceptable_num_instances = int(max_instances - num_host_instances)
if acceptable_num_instances < 0:
acceptable_num_instances = 0
if acceptable_num_instances < num_instances:
for j in xrange(acceptable_num_instances, num_instances):
sel... |
justasabc/kubernetes-ubuntu | ke/images/python/backup/backup_cluster.py | Python | apache-2.0 | 4,855 | 0.036663 |
class Cluster:
"""
a cluster has N simulators
"""
def __init__(self,region_pool):
self.region_pool = region_pool
self.filepath = CLUSTER_DATA_DIR+"cluster"
# simulator list
self.simulator_list = []
def get_simulator_list(self):
return self.simulator_list
def get_simulator_count(self):
return len(s... | return SIM_START_PORT+(sim_count+1)
#============================================== | ======================================
# create default cluster
#====================================================================================
def __create_default_cluster(self):
self.simulator_list = []
region_pool = self.region_pool
global_region_data = self.region_pool.get_global_region_data()
#... |
Geoportail-Luxembourg/qgis-pag-plugin | widgets/stylize/stylize.py | Python | mit | 2,046 | 0.012219 | '''
Created on 22 sept. 2015
@author: arxit
'''
import os
from qgis.core import *
from PyQt4.QtCore import QCoreApplication
import PagLuxembourg.main
class StylizeProject(object):
'''
Main class for the layers stylize widget
'''
def __init__(self):
'''
Constructor
'''
... | yers()
# Iterates through XSD types
for type in PagLuxembourg.main.xsd_schema.types:
if type.geometry_type is None:
continue
uri = project.getTypeUri(type)
found = False
# Check whether a layer with type d... | Is(v.source(), uri):
found = True
layer = v
break
if not found:
continue
self.stylizeLayer(layer, type)
PagLuxembourg.main.qgis_interface.messageBar().pushSuccess(QCoreApplicati... |
markovmodel/PyEMMA | pyemma/coordinates/transform/tica.py | Python | lgpl-3.0 | 11,423 | 0.004465 | # This file is part of PyEMMA.
#
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
#
# PyEMMA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either versi... | of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have... | t, see <http://www.gnu.org/licenses/>.
'''
Created on 19.01.2015
@author: marscher
'''
import numpy as np
from pyemma._base.serialization.serialization import SerializableMixIn
from pyemma._ext.variational.solvers.direct import eig_corr
from pyemma._ext.variational.util import ZeroRankError
from pyemma.coordinates.... |
DavidSantamaria/Om | contrib/spendfrom/spendfrom.py | Python | mit | 10,053 | 0.005968 | #!/usr/bin/env python
#
# Use the raw transactions API to spend bitcoins received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a bitcoind or Bit... | ts = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(bitcoind, fromaddresses, toaddress, amount, fee):
... | inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["total"]
if total_available < needed:
sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_av... |
zouyapeng/horizon-newtouch | openstack_dashboard/dashboards/identity/groups/tables.py | Python | apache-2.0 | 7,450 | 0 | # Copyright 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | verbose_name = _("Groups")
row_acti | ons = (ManageUsersLink, EditGroupLink, DeleteGroupsAction)
table_actions = (GroupFilterAction, CreateGroupLink,
DeleteGroupsAction)
class UserFilterAction(tables.FilterAction):
def filter(self, table, users, filter_string):
"""Naive case-insensitive search."""
q = ... |
schilli/MOPS | MOPS/demo/demo_mean.py | Python | gpl-3.0 | 1,694 | 0.013577 | #!/usr/bin/env python
# This is a demonstration of how to compute S2 order parameters from bond vector correlation functions.
# The S2 estimation is done with the method described in:
# Trbovic et al. Proteins (2008). doi:10.1002/prot.21750
from __future__ import print_function, division
import sys, os, glob
import M... | fter running test_corr.py
corrpath = "./MOPS_test_corr_fit"
if not os.path.isdir(corrpath):
print("No correlation functions found.")
print("Please run test_corr_fit.py first.")
sys.exit(1)
# load correlation functions
corrFilenames = glob.glob(corrpath + '/*.zip')
op = mops.OrderParameter(corrfilenames=co... | tion
S2 = op.S2mean
S2_std = op.S2std
S2_err = op.S2error # = S2.std / <number subtrajectories>
avgcorr = op.avgcorr # correlation function object with averaged correlation functions over all subtrajectories
corr = avgcorr.corr # numerical correlation functions, array of shape = (nresidues, ... |
srcc-msu/job_statistics | tagit.py | Python | mit | 1,689 | 0.03138 | from optparse import OptionParser
from application.database import global_db
from application.setup import create_app, setup_database, register_blueprints, load_cluster_config
from core.job.models import Job
from core.monitoring.models import JobPerformance
from core.tag.models import JobTag, Tag
from modules.autotag.... | .before_first_request
def tagit():
print("starting tagging")
conditions = []
for autotag in AutoTag.query.all():
conditions.append((autotag.compile_condition(), Tag.query.get(autotag.fk_tag_id).label))
query = global_db.session \
.query(Job, JobPerformance, JobTag) \
.filter(Job.t_end > | options.t_end) \
.join(JobPerformance)\
.join(JobTag)
for job,perf,job_tag in query.all():
tags = ""
for condition, label in conditions:
try:
if condition(job, perf):
tags += ";{0}".format(label)
except:
pass
print("{0},{1}".format(job.id, tags))
ap... |
stczhc/neupy | examples/gd/mnist_cnn.py | Python | mit | 1,657 | 0 | import theano
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn import cross_validation, metrics, datasets
from neupy import algorithms, layers, environment
environment.reproducible()
theano.config.floatX = 'float32'
mnist = datasets.fetch_mldata('MNIST original')
target_scaler = OneHo... | s=0)
n_samples = data.shape[0]
data = data.reshape((n_samples, 1, 28, 28))
x_train, x_test, y_train, y_test = cross_validation.train_test_split(
data.astype(np.float32),
target.astype(np.float32),
train_size=(6 / 7.)
)
network = algorithms.Adadelta(
[
layers.Convolution((32, 1, 3, 3)),
... | ),
layers.MaxPooling((2, 2)),
layers.Dropout(0.2),
layers.Reshape(),
layers.Relu(48 * 12 * 12),
layers.Dropout(0.3),
layers.Softmax(200),
layers.ArgmaxOutput(10),
],
error='categorical_crossentropy',
step=1.0,
verbose=True,
shuffle_data=True... |
ceph/ceph-deploy | ceph_deploy/tests/unit/hosts/test_altlinux.py | Python | mit | 379 | 0.002639 | from ceph_deploy.hosts.alt.install import map_components, NON_SPLIT_PACKAGES
class TestALTMapComponents | (object):
def test_valid(self):
pkgs = map_components(NON_SPLIT_PACKAGES, ['ceph-osd', 'ceph-common', 'ceph-ra | dosgw'])
assert 'ceph' in pkgs
assert 'ceph-common' in pkgs
assert 'ceph-radosgw' in pkgs
assert 'ceph-osd' not in pkgs
|
blaze/distributed | distributed/deploy/tests/test_local.py | Python | bsd-3-clause | 29,495 | 0.000712 | import asyncio
from functools import partial
import gc
import subprocess
import sys
from time import sleep
from threading import Lock
import unittest
import weakref
from distutils.version import LooseVersion
from tornado.ioloop import IOLoop
import tornado
from tornado.httpclient import AsyncHTTPClient
import pytest
... | ervices
assert any(
all(
word in str(msg.message).lower()
for word in ["9876", "running", "already in use"]
)
for msg in info.list
)
await c1.close()
| await c2.close()
def test_Client_kwargs(loop):
with Client(loop=loop, processes=False, n_workers=2, silence_logs=False) as c:
assert len(c.cluster.workers) == 2
assert all(isinstance(w, Worker) for w in c.cluster.workers.values())
assert c.cluster.status == "closed"
def test_Client_unused... |
robclewley/compneuro | Ch9_HH_compare.py | Python | bsd-3-clause | 1,267 | 0.007893 | """
Human cortical neuron using A-current model in reduced, 2D version of Hodgkin-Huxley model
Section 9.5
"""
from __future__ import division
from PyDSTool import *
from PyDSTool.Toolbox.phaseplane import *
from common_lib import *
import Ch9_HH_red
import Ch9_HH
gentype='vode' # dopri, euler, etc.
# Parameter An =... | As = sine wave amplitude
# f = frequency, should be >= 50 Hz
par_args = {'tau_v': 1, 'tau_r': 5.6,
'As': 0, 'f': 700, 'An': 0., 'Iapp': 0.8}
ic_args = {'v':-0.8, 'r': 0.25}
def test_I(gen, Iapp, tmax=300, silent=False):
geb.set(pars={'Iapp': Iapp},
tdata=[0,tmax])
traj = gen.c... | aj)
if not silent:
plt.clf()
plt.plot(pts['t'], pts['v'], 'b')
plt.ylim([-0.85, 0.4])
print "Frequency response was:", f
return f
# original version
HH = Ch9_HH.makeHHneuron('HH', par_args, ic_args, const_I=True,
gentype=gentype)
# 2D reduced version
HHred = C... |
Rhombik/rhombik-object-repository | searchsettings/templatetags/addSearchContext.py | Python | agpl-3.0 | 669 | 0.014948 | from django import template
from filemanager.models import fileobject
from django.shortcuts import get_object_or_404, render_to_response
from django.template.loader import render_to_string
from django.contrib.contenttypes.models import ContentTyp | e
register = template.Library()
def raw_text(context):
project=context['object']
object_type = ContentType.objects.get_for_model(project)
projectfiles = fileobject.objects.filter(content_type=object_type,object_id=project.id, filetype="text")
textlist = "" |
for i in projectfiles:
textlist = textlist+i.filename.read()
return textlist
register.simple_tag(takes_context=True)(raw_text)
|
adamchainz/django-mysql | src/django_mysql/operations.py | Python | mit | 5,386 | 0.000928 | from __future__ import annotations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.operations.base import Operation
from django.db.migrations.state import ModelState
from django.utils.functional import cached_property
class InstallPlugin(Operation):
reduces_to_sql = ... |
def references_model(self, name: str, app_label: str | None = None) -> bool:
return name.lower() == self.name_lower
def describe(self) -> str:
if self.from_engine:
from_clause = f" from {self.from_engine}"
else:
from_clause = ""
return "Alter storage eng... | =self.name, from_clause=from_clause, engine=self.engine
)
|
hanya/BookmarksMenu | pythonpath/bookmarks/env/mate.py | Python | apache-2.0 | 42 | 0 |
OP | EN = "mate-open"
FILE_MANAGER = "caj | a"
|
qrsforever/workspace | python/learn/base/module/l1/pack/__init__.py | Python | mit | 78 | 0.012821 | #!/usr/bin/python2 | .7
print | "__init__"
# __all__ = ['p2']
from big import *
|
shaggytwodope/progeny | validators.py | Python | gpl-3.0 | 3,149 | 0 | PROJECT_DEFAULTS = 'Project Defaults'
PATHS = 'Paths'
_from_config = {
'author': None,
'email': None,
'license': None,
'language': None,
'type': None,
'parent': None,
'vcs': None,
'footprints': None
}
_from_args = {
'name': None,
'author': None,
'email': None,
'license'... |
def solo_args_requires(args):
required = ['name', 'parent', 'language', 'type']
passed = 0
pass_requires = len(required)
for r in required:
if r in args.keys():
if args[r] is not None:
passed += 1
return passed == pass_requires
def validate_ar | gs(args, config):
if config is not None:
configged = load_config(config)
argged = load_args(args)
merged = merge_configged_argged(configged, argged)
# If footprint is provided, we only need name and parent
if merged['footprint'] is not None:
return footprint_requi... |
sharadagarwal/autorest | AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/operations/http_retry.py | Python | mit | 13,601 | 0.000588 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | l = '/http/retry/503'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_ | headers:
header_parameters.update(custom_headers)
# Construct body
if boolean_value is not None:
body_content = self._serialize.body(boolean_value, 'bool')
else:
body_con |
centic9/subversion-ppa | subversion/tests/cmdline/svntest/main.py | Python | apache-2.0 | 78,919 | 0.01219 | #
# main.py: a shared, automated test suite for Subversion
#
# Subversion is a tool for revision control.
# See http://subversion.tigris.org for more information.
#
# ====================================================================
# Licensed to the Apache Software Foundation (ASF) under one
# or more cont... |
general_wc_dir = os.path.join(work_dir, "working_copies")
# temp directory in which we will create our 'pristine' local
# repository and other scratch data. This should be removed when we
# quit and when we startup.
temp_dir = os.path.join(work_dir, 'local_tmp')
# (derivatives of the tmp dir.)
pristine_greek_repos_... | tree state.
#
# If a test wishes to create an "expected" working-copy tree, it should
# call main.greek_state.copy(). That method will return a copy of this
# State object which can then be edited.
#
_item = svntest.wc.StateItem
greek_state = svntest.wc.State('', {
'iota' : _item("This is the file 'iota'.\n")... |
partofthething/home-assistant | homeassistant/components/subaru/sensor.py | Python | apache-2.0 | 7,898 | 0.000886 | """Support for Subaru sensors."""
import subarulink.const as sc
from homeassistant.components.sensor import DEVICE_CLASSES
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
LENGTH_KILOMETERS,
LENGTH_MILES,
PERCENTAGE,
PRESSURE_HPA,
T... | alse
return last_update_success
def get_current_val | ue(self):
"""Get raw value from the coordinator."""
value = self.coordinator.data[self.vin][VEHICLE_STATUS].get(self.data_field)
if value in sc.BAD_SENSOR_VALUES:
value = None
if isinstance(value, str):
if "." in value:
value = float(value)
... |
andela-bojengwa/talk | venv/lib/python2.7/site-packages/django_filters/__init__.py | Python | mit | 485 | 0.002062 | # flake8 | : noqa
from __future__ import absolute_import
from .filterset import FilterSet
from .filters import *
__version__ = '0.9.2'
def parse_version(version):
'''
'0.1.2-dev' -> (0, 1, 2, 'dev')
'0.1.2' -> (0, 1, 2)
'''
v = version.split('.')
v = v[:-1] + v[-1].split('-')
ret = []
for p in v... | else:
ret.append(p)
return tuple(ret)
VERSION = parse_version(__version__)
|
sclarke/adventofcode2016 | d07.py | Python | bsd-3-clause | 1,196 | 0.001672 | import re
with open('d07.txt') as f:
raw_input = f.readlines()
test_input = """abba[mnop]qrst
abcd[bddb]xyyx
aaaa[qwer]tyui
ioxxoj[asdfgh]zxcvbn
asdfasdf[qwerqwer]asdffdsa[12341234]zcxvzcv""".splitlines()
def group_finder(s):
head, _, tail = s.partition('[')
yield head
if tail:
yield from gr... | n re_aba.findall(ip, overlapped=True):
| if any(b + a + b in hn for hn in hns):
match = True
if match:
total += 1
print(total)
|
XianliangJ/collections | CNUpdates/updates/update_lib.py | Python | gpl-3.0 | 49,836 | 0.00602 | ################################################################################
# The Frenetic Project #
# [email protected] #
#############################################################################... | ANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #
# LICENSE file distributed with this wo | rk for specific language governing #
# permissions and limitations under the License. #
################################################################################
# /updates/update_lib.py #
# Update Library Functions ... |
michal-ruzicka/archivematica | src/dashboard/src/components/mcp/views.py | Python | agpl-3.0 | 1,507 | 0.005309 | # This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the ... | uuid = request.REQUEST.get('uuid', '')
choice = request.REQUEST.get('choice', '')
uid = request | .REQUEST.get('uid', '')
result = client.execute(uuid, choice, uid)
return HttpResponse(result, mimetype = 'text/plain')
def list(request):
client = MCPClient()
jobs = etree.XML(client.list())
response = ''
if 0 < len(jobs):
for job in jobs:
response += etree.tostring(job... |
saintleva/limited-apt | src/limitedapt/enclosure.py | Python | gpl-3.0 | 8,559 | 0.008062 | # Copyright (C) Anton Liaukevich 2011-2020 <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.... | def clear(self):
self.__packages.clear()
def add_package(self, name, arch_and_versions):
if name in self.__packages:
raise CannotAddExistingPackage("Package '{0}' is already in the eclosure".format(name))
self.__packages[name] = arch_and_versions
def add_v... | name].add_single(versioned.version, versioned.architecture)
except KeyError:
arch_and_versions = ArchAndVersions()
arch_and_versions.add_single(versioned.version, versioned.architecture)
self.__packages[versioned.name] = arch_and_versions
def export_to_xml(self, ... |
googleapis/python-dialogflow | samples/generated_samples/dialogflow_v2_generated_conversation_datasets_delete_conversation_dataset_sync.py | Python | apache-2.0 | 1,640 | 0.001829 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRA | NTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for DeleteConversationDataset
# NOTE: This snippet has been automatically generated for illustrative purposes on... |
qilicun/python | python2/PyMOTW-1.132/PyMOTW/EasyDialogs/EasyDialogs_AskYesNoCancel.py | Python | gpl-3.0 | 390 | 0.012821 | #!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2008 Dou | g Hellmann All rights reserved.
#
"""
"""
__version__ = "$Id$"
#end_pymotw_header
i | mport EasyDialogs
valid_responses = { 1:'yes',
0:'no',
-1:'cancel',
}
response = EasyDialogs.AskYesNoCancel('Select an option')
print 'You selected:', valid_responses[response]
|
we-inc/mms-snow-white-and-the-seven-pandas | webserver/apps/payments/views.py | Python | mit | 3,518 | 0.002558 | from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets, mixins
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.decorators import api_view, permission_classes
from apps.payments.models import Installment, RentalPaymentIn... | markets.models import Market
from apps.booths.models import Booth
from apps.payments.serializers import | InstallmentSerializer, UploadReceiptSerializer, VerifyReceiptSerializer
class PaymentViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
"""
### Pay with bank account
{\n
"payment_type": 1,
"market": 1,
"payment_method": 2,
"amount": 2000
}
### Pay with cred... |
ricardodeazambuja/BrianConnectUDP | examples/OutputNeuronGroup_brian.py | Python | cc0-1.0 | 2,857 | 0.014351 | '''
Example of a spike receiver (only receives spikes)
In this example spikes are received and processed creating a raster plot at the end of the simulation.
'''
from brian import *
import numpy
from brian_multiprocess_ | udp import BrianConnectUDP
# The main function with the NeuronGroup(s) and Synapse(s) must be named "main_NeuronGroup".
# It will receive two objects: input_Neuron_Group and the simulation_clock. The input_Neuron_Group
# will s | upply the input spikes to the network. The size of the spike train received equals NumOfNeuronsInput.
# The size of the output spike train equals NumOfNeuronsOutput and must be the same size of the NeuronGroup who is
# going to interface with the rest of the system to send spikes.
# The function must return all the Neu... |
dp0h/marketdata | marketdata/update.py | Python | mit | 1,099 | 0.00364 | # coding:utf-8
'''
Market data update functionality
'''
from __future__ import print_function
from datetime import datetime, timedelta
from symbols import Symbols
import yahoo
def update_marketdata(from_date=None, to_date=None, sym=Symbols()):
'''
Fetch latest market data and upate it in db
'... | [0], x[1], x[2], x[3], x[4], x[5], x[6]) for x in data])
else:
# Th | ere are several reasons update can fail: 1. No new data; 2. wrong symbol; 3. Other reason.
print('Failed updating symbol %s' % s)
|
charmoniumQ/EDGAR-research | edgar_code/cache.py | Python | mit | 9,951 | 0.001306 | from __future__ import annotations
import abc
import shutil
import functools
from pathlib import Path
import urllib.parse
from typing import (
Callable, Any, TypeVar, cast, Tuple, Dict, Optional,
Union, Hashable,
)
import logging
from edgar_code.types import PathLike, Serializer, UserDict
from edgar_code.util.p... | if self.cache_path.exists():
print('deleting ', self.cache_path)
self.cache_path.unlink()
def __setitem__(self, key: Hashable, obj: Any) -> None:
self.load_if_not_loaded()
super().__setitem__(key, obj)
self.commit()
def __delitem__(self, key: Hash... | ef clear(self) -> None:
self.load_if_not_loaded()
super().clear()
self.commit()
class DirectoryStore(ObjectStore[PathLike, Any]):
'''Stores objects at ./${CACHE_PATH}/${FUNCTION_NAME}/${urlencode(args)}.pickle'''
def __init__(
self, object_path: PathLike, name: str,
... |
marplaa/SerialBus | python_lib/test_script/echo.py | Python | gpl-3.0 | 294 | 0.010204 | from Serial | Bus import SerialBus
serialbus = SerialBus(baud = 19200, serialnum="ABCD")
while True:
cmd = input('Send: ')
answer = serialbus.send_request_wait(10, bytes(cmd, 'ascii'))
answer_str = "";
for char in answer:
answer_str | += (chr(char))
print(answer_str)
|
mbayon/TFG-MachineLearning | venv/lib/python3.6/site-packages/sklearn/neighbors/regression.py | Python | mit | 10,967 | 0 | """Nearest Neighbor Regression"""
# Authors: Jake Vanderplas <[email protected]>
# Fabian Pedregosa <[email protected]>
# Alexandre Gramfort <[email protected]>
# Sparseness support by Lars Buitinck
# Multi-output support by Arnaud Joly <[email protected]... | for the Minkowski metric. When p = 1, this is
equivalent to using manhattan_distance (l1), and euclidean_distance
(l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.
metric : string or callable, default 'minkowski'
the distance metric to use for the tree. The default metric ... | p=2 is equivalent to the standard Euclidean
metric. See the documentation of the DistanceMetric class for a
list of available metrics.
metric_params : dict, optional (default = None)
Additional keyword arguments for the metric function.
n_jobs : int, optional (default = 1)
The ... |
0x1997/webassets | src/webassets/utils.py | Python | bsd-2-clause | 6,584 | 0.001367 | from webassets import six
import contextlib
import os
import sys
from itertools import takewhile
from .exceptions import BundleError
__all__ = ('md5_constructor', 'pickle', 'set', 'StringIO',
'common_path_prefix', 'working_directory')
if sys.version_info >= (2, 5):
import hashlib
md5_constructor... | asattr(self, 'id') else repr(self))
class Metaclass(type):
REGISTRY = {}
def __new__(mcs, name, bases, attrs):
if not '__eq__' in attrs:
attrs['__eq__'] | = eq
if not '__unicode__' in attrs:
attrs['__unicode__'] = unicode
if not '__str__' in attrs:
attrs['__str__'] = unicode
new_klass = type.__new__(mcs, name, bases, attrs)
if hasattr(new_klass, 'id'):
mcs.REGISTRY[new_klass.... |
linkedin/WhereHows | metadata-ingestion/tests/integration/azure_ad/test_azure_ad.py | Python | apache-2.0 | 7,798 | 0.002949 | import json
import pathlib
from unittest.mock import patch
from freezegun import freeze_time
from datahub.ingestion.run.pipeline import Pipeline
from datahub.ingestion.source.identity.azure_ad import AzureADConfig
from tests.test_helpers import mce_helpers
FROZEN_TIME = "2021-08-24 09:00:00"
def test_azure_ad_conf... | with patch(
"datahub.ingestion.source.identity.azure_ad.AzureADSource.get_token"
) as mock_token, patch(
"datahub.ingestion.source.identity.azure_ad.AzureADSource._get_azure_ad_users"
) as mock_users, patch(
"datahub.ingestion.source.identity.azure_ad.AzureADSource._get_azure_ad_grou... | test_resources_dir, mock_token, mock_users, mock_groups, mock_group_users
)
# Run an azure usage ingestion run.
pipeline = Pipeline.create(
{
"run_id": "test-azure-ad",
"source": {
"type": "azure-ad",
... |
MicroPyramid/django-mfa | django_mfa/tests/test_models.py | Python | mit | 2,572 | 0.001166 | from django_mfa.models import *
from django.test import TestCase, Client
from django.contrib.auth.models import User
from django.contrib import auth
class Test_Models_Mfa_U2f(TestCase):
def setUp(self):
self.client = Client()
self.user = User.objects.create_user(
username='djangomfa@m... | tEqual(self.u2f_keys.key_handle, user_u2f.key_handle)
self.assertEqual(self.u2f_keys.app_id, user_u2f.app_id)
def test_u2f_to_json_function(self):
user_u2f = U2FKey.objects.filter(
user=auth.get_user(self.client)).first()
self.assertEqual(self.u2f_keys.to_json(), user_u2f.to_jso... | user=auth.get_user(self.client)).first()).first()
self.assertEqual(self.user_codes, user_codes)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.