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 |
|---|---|---|---|---|---|---|---|---|
tkammer/infrared | tools/ksgen/ksgen/settings.py | Python | gpl-3.0 | 15,945 | 0.000815 | from configure import Configuration, ConfigurationError
from ksgen import docstring, yaml_utils, utils
from ksgen.tree import OrderedTree
from ksgen.yaml_utils import LookupDirective
from docopt import docopt, DocoptExit
import logging
import os
import re
import yaml
VALUES_KEY = '!value'
DEFAULTS_TAG = 'defaults'
lo... | rules_file)
def _parse(self):
# create the settings tree and preserve the order in which arguments
# are passed. Convert all args into an ordered tree so that
# --foo fooz --too moo --foo-bar baaz --foo-arg | vali
# will be like the ordered tree below
# foo:
# <special-key>: fooz
# bar: ### <-- foo-bar is not foo/bar
# <special-key>: baaz
# arg: ### <-- arg comes after bar
# <special-key>: val
# too:
# <special-key>: moo
... |
rob-smallshire/cartouche | cartouche/parser.py | Python | bsd-3-clause | 17,022 | 0.001646 | # -*- cod | ing: utf-8 -*-
from __future__ import print_function
from contextlib import contextmanager
import re
from cartouche._portability import u
from .errors import CartoucheError
from .nodes import (Node, Raises, Except, Note, Warning | , Returns, Arg, Yields,
Attribute, Usage, ensure_terminal_blank)
OPTIONAL_BULLET_PATTERN = u(r'(?:[\*\+\-\•\‣\⁃]\s+)?')
ARGS_PATTERN = u(r'(\*{0,2}\w+)(\s+\(([\.\w]+)\))?\s*:\s*(.*)')
ATTRIBUTES_PATTERN = u(r'(\*{0,2}\w+)(\s+\(([\.\w]+)\))?\s*:\s*(.*)')
RAISES_PATTERN = u(r'([\w\.]+)\s*:\s*(.*)')
... |
bugcrowd/vulnerability-rating-taxonomy | lib/generate_artifacts.py | Python | apache-2.0 | 228 | 0 | from utils import utils
fr | om artifacts import scw_artifact
url_mapping = {}
current_v | rt = utils.get_json(utils.VRT_FILENAME)
scw_artifact.write_artifact_file(
scw_artifact.generate_urls(current_vrt['content'], url_mapping)
)
|
ktan2020/legacy-automation | win/Lib/encodings/rot_13.py | Python | mit | 2,697 | 0.011123 | #!/usr/bin/env python
""" Python Character Mapping Codec for ROT13.
See http://ucsub.colorado.edu/~kominek/rot13/ for details.
Written by Marc-Andre Lemburg ([email protected]).
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
... | 0045,
0x0053: 0x0046,
0x0054: 0x0047,
0x0055: 0x0048,
0x0056: 0x0049,
0x0057: 0x004a,
0x0058: 0x004b,
0x0059: 0x004c,
0x005a: 0x004d,
0x0061: 0x006e,
0x0062: 0x006f,
0x0063: 0x0070,
0x0064: 0x0071,
0x0065: 0x0072,
0x0066: 0x0073,
0x0067: 0x0074,
0x0068: 0x... |
0x006e: 0x0061,
0x006f: 0x0062,
0x0070: 0x0063,
0x0071: 0x0064,
0x0072: 0x0065,
0x0073: 0x0066,
0x0074: 0x0067,
0x0075: 0x0068,
0x0076: 0x0069,
0x0077: 0x006a,
0x0078: 0x006b,
0x0079: 0x006c,
0x007a: 0x006d,
})
### Encoding Map
encoding_map = codecs.make_encod... |
Connexions/cnx-upgrade | cnxupgrade/tests/__init__.py | Python | agpl-3.0 | 2,755 | 0.001452 | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2013, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from __future__ import print_function
import os
import sys
import psycopg2
__all__ = ('DB_CONNECTION_STR... | ': self.connection_string}
initdb(settings)
def tearDown(self):
# Drop all tables.
self._drop_all()
postgresql_fixture = PostgresqlFixture()
def db_connect(method):
"""Decorator for methods that need to use the database
Example:
@db_connect
def setUp(self, cursor):
... |
"""
def wrapped(self, *args, **kwargs):
with psycopg2.connect(DB_CONNECTION_STRING) as db_connection:
with db_connection.cursor() as cursor:
return method(self, cursor, *args, **kwargs)
db_connection.commit()
return wrapped
|
dayatz/taiga-back | tests/integration/resources_permissions/test_auth_resources.py | Python | agpl-3.0 | 2,107 | 0 | # -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <[email protected]>
# Copyright (C) 2014-2017 Jesús Espino <[email protected]>
# Copyright (C) 2014-2017 David Barragán <[email protected]>
# Copyright (C) 2014-2017 Alejandro Alonso <[email protected]>
# Copyright (C) 2014-2017 Anler Hernández ... | ": "test",
"email": "[email protected]",
| })
result = client.post(url, register_data, content_type="application/json")
assert result.status_code == 201
|
mitdbg/mdindex | scripts/fabfile/utils.py | Python | mit | 2,214 | 0.006775 | from fabric.api import *
from fabric.contrib.files import exists
import fabric
counter = 0
@roles('master')
def start_spark():
run('/home/mdindex/scripts/startSystems.sh')
@roles('master')
def stop_spark():
run('/home/mdindex/scripts/stopSystems.sh')
@roles('master')
def start_zookeeper():
run('/home/md... | XX` {}".format(sockname, cmd)
if use_sudo:
return sudo(cmd)
else:
return run(cmd)
@runs_once
def build_jar():
local('cd /Users/anil/Dev/repos/mdindex/; gradle shadowJar')
@parallel
def update_jar():
if not exists('/data/mdindex/jars'):
run('mkdir -p /data/mdindex/jars')
put... | x/jars/')
@roles('master')
def update_master_jar():
if not exists('/data/mdindex/jars'):
run('mkdir -p /data/mdindex/jars')
put('../build/libs/amoeba-all.jar', '/data/mdindex/jars/')
@serial
def update_config():
global counter
put('server/server.properties', '/home/mdindex/amoeba.properties')
... |
j00bar/django-widgy | widgy/contrib/form_builder/south_migrations/0010_auto__add_field_emailuserhandler_to_ident__chg_field_formsubmission_cr.py | Python | apache-2.0 | 9,301 | 0.007526 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'EmailUserHandler.to_ident'
db.add_column('form_builder_emailuserhandler', 'to_ident',
... | '})
},
'form_builder.choicefield': {
'Meta': {'object_name': 'ChoiceField'},
'choices': ('django.db.models.fields.TextField', [], {}),
'help_text': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', []... | ry_key': 'True'}),
'ident': ('django.db.models.fields.CharField', [], {'max_length': '36', 'blank': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'required': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'type': ... |
Endika/l10n-spain | l10n_es_aeat_mod303/models/mod303.py | Python | agpl-3.0 | 9,035 | 0 | # -*- coding: utf-8 -*-
# © 2013 - Guadaltech - Alberto Martín Cortada
# © 2015 - AvanzOSC - Ainara Galdona
# © 2014-2016 - Serv. Tecnol. Avanzados - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields, api, _
class L10nEsAeatMod303Report(models.Mode... | a casilla el "
"100%", default=100)
atribuible | _estado = fields.Float(
string="[66] Atribuible a la Administración", readonly=True,
compute="_compute_atribuible_estado", store=True)
cuota_compensar = fields.Float(
string="[67] Cuotas a compensar", default=0,
states={'done': [('readonly', True)]},
help="Cuota a compensar d... |
siwells/teaching_set09103 | code/topic_11/decrypt.py | Python | gpl-3.0 | 616 | 0.00487 | from Crypto.PublicKey import RSA
from C | rypto.Cipher import AES, PKCS1_OAEP
file_in = open("encrypted_data.bin", "rb")
private_key = RSA.import_key(open("private.pem").read())
enc_session_key, nonce, tag, ciphertext = [ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]
# Decrypt the session key with the private RSA key
cipher_rsa = PKC... | er_aes.decrypt_and_verify(ciphertext, tag)
print(data.decode("utf-8"))
|
jplusplus/thenmap-v0 | generators/utils/convert-csv-to-json.py | Python | gpl-2.0 | 2,991 | 0.030181 | # coding=utf-8
#Converts a csv contining country codes and numerical values, to json
#Years should be given in the header, like this:
#
# land, 1980, 1981, 1982
# se, 12, 13, 11
# fi 7, 10, 14
import csv
import json
import argparse
import os.path
import sys
import math
#Check if file exists
def is_... | ol in row:
currentHeader = headers[i]
if isYear(currentHeader):
if is_number(col):
if (args.decimals > -1):
outdata[currentNation].append(doRounding(col,args.decimals))
else:
outdata[currentNation].append(col)
else:
outdata[currentNation].append(None)
i +=... | int ("Could not open input file")
print "Writing %s..." % outputFile
with open(outputFile, 'w') as outfile:
json.dump(outdata, outfile)
print "done"
|
Amandil/django-tech-test | loans/tests/tests_model_business.py | Python | bsd-3-clause | 5,699 | 0.031409 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth.models import User
from django.db.utils import IntegrityError
from django.core.exceptions import ValidationError
from loans.models import Business
class BusinessTestCase(TestCase):
'''
Cr... | self.john.save()
# self.jane = User.objects.create(username="janedoe", first_name="Jane", last_name="Doe")
# self.jane.borrower.is_borrower | = True
# self.jane.borrower.telephone_number = '+40 745 497 778'
# self.jane.save()
'''
We must be able to create a business
'''
def test_model_create(self):
acme = Business.objects.create(
crn = '09264172',
owner = self.john,
name = "ACME In... |
diogo149/treeano | treeano/core/variable.py | Python | apache-2.0 | 7,794 | 0 | from __future__ import division, absolute_import
from __future__ import print_function, unicode_literals
import toolz
import numpy as np
import theano
import theano.tensor as T
from .. import utils
from .inits import ZeroInit
ENABLE_TEST_VALUE = theano.config.compute_test_value != "off"
VALID_TAGS = set("""
input
o... | .broadcastable_
is_shared = self.is_shared_
tags = self.tags_
ndim = self.ndim_
variable = self.variable_
if ndim is not | None and shape is not None:
assert len(shape) == ndim
if ndim is not None and variable is not None:
assert ndim == variable.ndim
if broadcastable is not None and variable is not None:
assert broadcastable == variable.broadcastable
if is_shared is not None and ... |
spcui/avocado-vt | selftests/unit/test_utils_params.py | Python | gpl-2.0 | 3,700 | 0.001622 | #!/usr/bin/python
import unittest
import os
import sys
# simple magic for using scripts within a source tree
basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if os.path.isdir(os.path.join(basedir, 'virttest')):
sys.path.append(basedir)
from virttest import utils_params
BASE_DICT = {
'im... | ])
def testGetItemMissing(self):
try:
self.params['bogus']
raise ValueError("Did not get a ParamNotFound error when trying "
"to access a non-existing param")
# pylint: disable=E0712
except utils_params.ParamNotFound:
pass
... | f __name__ == "__main__":
unittest.main()
|
soerendip42/rdkit | rdkit/Chem/Subshape/testCombined.py | Python | bsd-3-clause | 1,702 | 0.03349 | from __future__ import print_function
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem.PyMol import MolViewer
from rdkit.Chem.Subshape import SubshapeBuilder,SubshapeObjects,SubshapeAligner
from rdkit.six.moves import cPickle
import copy
m1 = Chem.MolFromMolFile('test_data/square1.mol')
m2 = Chem.... | m2)
cPickle.dump(s2,file('test_data/square2.shp.pkl','wb+'))
ns1 = b.CombineSubshapes(s1,s2)
b.GenerateSubshapeSkeleton(ns1)
cPickle.dump(ns1,file('test_data/combined.shp.pkl','wb+'))
else:
s1 = | cPickle.load(file('test_data/square1.shp.pkl','rb'))
s2 = cPickle.load(file('test_data/square2.shp.pkl','rb'))
#ns1 = cPickle.load(file('test_data/combined.shp.pkl','rb'))
ns1=cPickle.load(file('test_data/combined.shp.pkl','rb'))
v = MolViewer()
SubshapeObjects.DisplaySubshape(v,s1,'shape1')
SubshapeObjects.Disp... |
chitr/neutron | neutron/plugins/ml2/drivers/openvswitch/agent/ovs_neutron_agent.py | Python | apache-2.0 | 89,243 | 0.000179 | # Copyright 2011 VMware, 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 required by ... | rk_type, self.physical_network,
self.segmentation_id))
class OVSPluginApi(agent_rpc.PluginApi):
pass
def has_zero_prefixlen_address(ip_addresses):
return any(netaddr.IPNetwork(ip).prefixlen == 0 for ip in ip_addresses)
class OVSNeutronAgent(sg_rpc.SecurityGroupAgentRpcCallbackMixin,
... | '''Implements OVS-based tunneling, VLANs and flat networks.
Two local bridges are created: an integration bridge (defaults to
'br-int') and a tunneling bridge (defaults to 'br-tun'). An
additional bridge is created for each physical network interface
used for VLANs and/or flat networks.
All VM ... |
tanmaykm/edx-platform | openedx/core/djangoapps/oauth_dispatch/tests/constants.py | Python | agpl-3.0 | 97 | 0 | """
Constants for testing purposes
| """
DUMMY_REDIRECT_URL = u'https://example.com/edx/re | direct'
|
belokop-an/agenda-tools | code/htdocs/confAbstractBook.py | Python | gpl-2.0 | 233 | 0.017167 | from MaKaC.webinterface.rh import conferenceDisplay
def index(req,**params):
return conferenceDisplay.RHAbstractBook(req).process(params)
def test(req,**params): |
return conferenceDisplay.RHAbstractBook(req) | .process(params)
|
ahmad88me/PyGithub | github/GithubException.py | Python | lgpl-3.0 | 5,277 | 0.007391 | ############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <[email protected]> #
# Copyright 2012 Zearin <[email protected]> ... | .
"""
def __init__(self, status, data):
super().__init__()
self.__status = | status
self.__data = data
self.args = [status, data]
@property
def status(self):
"""
The status returned by the Github API
"""
return self.__status
@property
def data(self):
"""
The (decoded) data returned by the Github API
"""
... |
neuropoly/axonsegpy | axonsegpy/GUI.py | Python | mit | 4,301 | 0.016043 | import tkinter as tk
import sys
import json
import sys
from tkinter import filedialog
from tkinter import Spinbox
from tkinter import Canvas
from tkinter import RIGHT
from tkinter import ttk
from PIL import Image, ImageTk
from core.readAlgoFile import readAlgo
from core.readAlgoFile import getAlgoList
from core.ConfigP... | )
photo = ImageTk.PhotoImage(image)
#self.w.create_image(photo)
def popUpAlgo(self,algo,nameAlgo):
"""
:param algo: a list of algo
:return:
"""
button_opt = {'fill': 'both | ', 'padx': 5, 'pady': 5}
popup=tk.Tk()
popup.wm_title("Select your parameters")
labelList=[]
entryList=[]
paramAlgo=algo[0]["params"]
keyAlgo=list(paramAlgo.keys())
nbrParam=len(paramAlgo)
for i in range(nbrParam):
labelList.append(tk.Label(popup,text=keyAlgo[i]))
entryList.... |
sveetch/recalbox-manager | project/manager_frontend/forms/bios.py | Python | mit | 3,935 | 0.009911 | # -*- coding: utf-8 -*-
"""
Thread forms
"""
import os, hashlib
from django.conf import settings
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.files.storage import FileSystemStorage
from project.manager_frontend.forms import CrispyFormMixin
from project.utils.import... | self.manifest.items()}
name = os.path.basename(bios.name)
if name not in simple_manifest:
raise forms.ValidationError(_("Your file does not seem to be a supported Bios"))
else:
bios_chec | ksum = hashfile(bios, hashlib.md5())
if bios_checksum != simple_manifest[name]:
raise forms.ValidationError(_("Your file does not have a correct MD5 checksum"))
return bios
def save(self):
bios = self.cleaned_data["bios"]
# Remove the previ... |
AugurProject/augur-core | tests/trading/test_tradingEscapeHatch.py | Python | gpl-3.0 | 2,511 | 0.007168 | #!/usr/bin/env python
from ethereum.tools import tester
from ethereum.tools.tester import TransactionFailed
from pytest import raises
from utils import fix, longTo32Bytes
from constants import LONG, YES, NO
def test_escapeHatch(contractsFixture, cash, market):
controller = contractsFixture.contracts['Controller'... | .address, sender = tester.k2)
# assert final values (should be a zero sum game)
assert contractsFixture.chain.head_state.get_balance(tester.a1) == initialTester1ETH
assert contractsFixture.chain.head_state.get_balance(tester.a2 | ) == initialTester2ETH
assert cash.balanceOf(market.address) == 0
assert noShareToken.balanceOf(tester.a1) == 0
assert yesShareToken.balanceOf(tester.a2) == 0
|
alfiyansys/a-reconsidered-sign | algorithms/__init__.py | Python | gpl-3.0 | 18 | 0.055556 | _ | _all__ = ["core"] | |
USGSDenverPychron/pychron | pychron/pyscripts/contexts.py | Python | apache-2.0 | 1,376 | 0 | # ===============================================================================
# Copyright 2019 ross
#
# 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/LICE... |
# See the License for the specific language governing permissions and
# limitations under the License.
# ===============================================================================
class CTXObject(object):
def update(self, ctx):
self.__dict__.update(**ctx)
class EXPObject(CTXObject):
pass
cla... | "multicollect",
"peakcenter",
"equilibration",
"whiff",
"peakhop",
):
try:
c = CTXObject()
c.update(yd[k])
setattr(self, k, c)
except KeyError:
pass
# ============= EOF ===... |
ncliam/serverpos | openerp/custom_modules/school_link/school.py | Python | agpl-3.0 | 39,903 | 0.00599 | # -*- coding: utf-8 -*-
#################################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013 Julius Network Solutions SARL <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under th... | '=', True),
('company_id','=', company_id)], context=context)
if not parent_ids or len(parent_ids) == 0:
# search parent not in school
parent_ids = self.pool.get('r... | ('customer', '=', True)], context=context)
parent_id = parent_ids and parent_ids[0] or None
|
taget/libvirt | docs/index.py | Python | lgpl-2.1 | 37,181 | 0.007504 | #!/usr/bin/python -u
#
# imports the API description and fills up a database with
# name relevance to modules, functions or web pages
#
# Operation needed:
# =================
#
# install mysqld, the python wrappers for mysql and libxml2, start mysqld
# - mysql-server
# - mysql
# - php-mysql
# - MySQL-python
# Chan... | enMySQL()
if DB is None:
return -1
if name is None:
return -1
if module is None:
return -1
if type is None:
return -1
try:
desc = string.replace(desc, "'", " ")
l = string.split(desc, ".")
desc = l[0]
desc = desc[0:99]
except:
... | ret = c.execute(
"""INSERT INTO symbols (name, module, type, descr) VALUES ('%s','%s', '%s', '%s')""" %
(name, module, type, desc))
except:
try:
ret = c.execute(
"""UPDATE symbols SET module='%s', type='%s', descr='%s' where name='%s'""" %
(module, type, ... |
jhprinz/openpathsampling | openpathsampling/tests/test_toy_dynamics.py | Python | lgpl-2.1 | 12,227 | 0.005561 | '''
@author: David W.H. Swenson
'''
from __future__ import division
from __future__ import absolute_import
from builtins import zip
from past.utils import old_div
from builtins import object
import os
from nose.tools import (assert_equal, assert_not_equal, assert_almost_equal)
from nose.plugins.skip import SkipTest
... | _minv, [old_div(1 | .0,m_i) for m_i in sys_mass])
assert_equal(self.sim.n_steps_per_frame, 10)
def test_snapshot_timestep(self):
assert_equal(self.sim.snapshot_timestep, 0.02)
def test_snapshot_get(self):
snapshot = self.sim.current_snapshot
assert_items_equal(snapshot.velocities[0],
... |
soarlab/FPTuner | examples/primitives/doppler-1.py | Python | mit | 477 | 0.020964 |
import tft_ir_api as IR
var_u = IR.RealVE("u", 0, (-100.0 - 0.0000001), (100.0 + 0.0000001))
var_v = IR.RealVE("v", 1, (20.0 - 0.000000001), (20000.0 + 0.000000001))
var_T = IR.RealVE("T", 2, (-30.0 - 0.000001), (50.0 + 0.000001))
t1 = IR.BE("+", 4, IR.FConst(331.4), IR.BE("*", 3, IR.FConst(0.6), var_T))
t... | E("*", 8, temp, temp)
r = IR.BE("/", 9, IR.BE("*", 7, IR.UE("-", 6, t1), var_v), tem | p)
IR.TuneExpr(r)
|
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/map_unlock_codec.py | Python | apache-2.0 | 1,021 | 0.002938 | from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer
from hazelcast.protocol.builtin import StringCodec
from hazelcast.protocol.builtin import DataCodec
# hex: 0x011... | (_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE)
FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_OFFSET, thread_id)
FixSizedTypesCodec.encode_long(buf, _REQUEST_REFERENCE_ID_OFFSET, reference_id)
StringCodec.encode(buf, name)
DataCodec.encode(buf, key, True)
r | eturn OutboundMessage(buf, True)
|
r26zhao/django_blog | blog/migrations/0026_auto_20170629_1342.py | Python | mit | 467 | 0.002179 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-29 05:42
from __future__ import unicode_literals
from dja | ngo.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0025_auto_20170626_0008'),
]
| operations = [
migrations.AlterModelOptions(
name='category',
options={'ordering': ['-id'], 'verbose_name': '分类', 'verbose_name_plural': '分类'},
),
]
|
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/google/appengine/_internal/django/core/management/__init__.py | Python | bsd-3-clause | 17,576 | 0.001707 | import os
import sys
from optparse import OptionParser, NO_DEFAULT
import imp
import django
from google.appengine._internal.django.core.management.base import BaseCommand, CommandError, handle_default_options
from google.appengine._internal.django.utils.importlib import import_module
# For backwards compatibility: ge... | module can be placed in the
dictionary in place of the application name.
The dictionary is cached on the first call and reused on subsequent
calls.
"""
| global _commands
if _commands is None:
_commands = dict([(name, 'django.core') for name in find_commands(__path__[0])])
# Find the installed apps
try:
from google.appengine._internal.django.conf import settings
apps = settings.INSTALLED_APPS
except (Attribu... |
xstrengthofonex/code-live-tutorials | python_web_development/templating/router.py | Python | mit | 1,680 | 0.002976 | from webob import Request, Response
import re
def not_found(request, response):
response.status = 404
response.write("404 Not Found")
class Route(object):
default_methods = ['GET']
def __init__(self, path, handler, methods=None):
self.path = path
self.handler = handler
if meth... | routes:
if route.match(request):
return route.handler
return None
def dispatch(self, request):
handler = self.match(request)
return handler
def __call__(self, environ, start_response):
request = Request(environ)
response = Response()
... | return response(environ, start_response) |
stephenbalaban/keras | keras/layers/recurrent.py | Python | mit | 29,818 | 0.001375 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np
from .. import activations, initializations
from ..utils.theano_utils import shared_scalar, shared_zeros, alloc_zeros_matrix
from ..layers.core import Layer, MaskedLayer
from six.moves import range... | truncate_gradient=-1, return_sequences=False):
super(SimpleRNN, self).__init__()
self.init = initializations.get(init)
self.inner_init = initializations.get(inner_init)
self.input_dim = input_dim
self.output_dim = output_dim
self.truncate_gradient = truncate... | self.activation = activations.get(activation)
self.return_sequences = return_sequences
self.input = T.tensor3()
self.W = self.init((self.input_dim, self.output_dim))
self.U = self.inner_init((self.output_dim, self.output_dim))
self.b = shared_zeros((self.output_dim))
... |
nivekkagicom/uncrustify | tests/test_uncrustify/utilities.py | Python | gpl-2.0 | 7,537 | 0.000133 | # Logic for listing and running tests.
#
# * @author Ben Gardner October 2009
# * @author Guy Maurel October 2015
# * @author Matthew Woehlke June 2018
#
import argparse
import os
import subprocess
import sys
from .ansicolor import printc
from .config import config, all_tests, FAIL_ATTRS, PASS_AT... | --------------------------------
def add_format_tests_arguments(parser):
_add_common_arguments(parser)
parser.add_argu | ment('-p', '--show-all', action='store_true',
help='show passed/skipped tests')
parser.add_argument('-r', '--select', metavar='CASE(S)', type=str,
help='select tests to be executed')
parser.add_argument('tests', metavar='TEST', type=str, nargs='*',
... |
AllTheWayDown/turgles | turgles/tests/test_buffers.py | Python | mit | 11,668 | 0.000086 | import itertools
from unittest import TestCase
from turgles.buffer import ChunkBuffer, ShapeBuffer, BufferManager
from turgles.memory import TURTLE_MODEL_DATA_SIZE, TURTLE_COLOR_DATA_SIZE
MODEL_ZEROS = [0] * TURTLE_MODEL_DATA_SIZE
MODEL_ONES = [1] * TURTLE_MODEL_DATA_SIZE
MODEL_TWOS = [2] * TURTLE_MODEL_DATA_SIZE
MOD... | buffer = ChunkBuffer(4, TURTLE_MODEL_DATA_SIZE)
buffer.new(MODEL_ONES)
buffer.new(MODEL_TWOS)
buffer.new(MODEL_THREES)
moved = buffer.remove(0)
self.assertEqual(buffer.count, 2)
self.assertEqual(moved, 2)
self.assert_turtle_data(buffer, 0, MODEL_THREES)
... | test_remove_middle(self):
buffer = ChunkBuffer(4, TURTLE_MODEL_DATA_SIZE)
buffer.new(MODEL_ONES)
buffer.new(MODEL_TWOS)
buffer.new(MODEL_THREES)
moved = buffer.remove(1)
self.assertEqual(buffer.count, 2)
self.assertEqual(moved, 2)
self.assert_turtle_data(b... |
kailIII/emaresa | trunk.pe/account_financial_report/wizard/__init__.py | Python | agpl-3.0 | 1,490 | 0.000671 | # -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
###############Credits############################################... | m 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 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 o... |
pplu/botocore | tests/__init__.py | Python | apache-2.0 | 17,369 | 0.000058 | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | ecorator
de | f requires_crt(reason=None):
if reason is None:
reason = "Test requires awscrt to be installed"
def decorator(func):
return unittest.skipIf(not HAS_CRT, reason)(func)
return decorator
def random_chars(num_chars):
"""Returns random hex characters.
Useful for creating resources wit... |
simodalla/pygmount | pygmount/utils/utils.py | Python | bsd-3-clause | 2,197 | 0 | # -*- coding: UTF-8 -*-
from __future__ import unicode_literals, absolute_import
import os
import platform
try:
from ConfigParser import ConfigParser
except ImportError:
from configparser import ConfigParser
def get_sudo_username():
"""
Check 'SUDO_USER' var if in environment and return a tuple with ... | di sistema")
def read_config(filename=None):
"""
Read a config filename into .ini format and return dict of shares.
Ke | yword arguments:
filename -- the path of config filename (default None)
Return dict.
"""
if not os.path.exists(filename):
raise IOError('Impossibile trovare il filename %s' % filename)
shares = []
config = ConfigParser()
config.read(filename)
for share_items in [config.items(sha... |
hydralabs/plasma | plasma/test/util.py | Python | mit | 354 | 0 | # Copyright The Plasma Project.
# See LI | CENSE.txt for details.
"""
Test helpers and classes
"""
import inspect
def dict_for_slots(obj):
"""
"""
slots = []
for cls in inspect.getmro(obj.__class__):
if hasattr(cls, '__slots__'):
| slots += cls.__slots__
return dict(zip(slots, [getattr(obj, x) for x in slots]))
|
gloryofrobots/obin | arza/runtime/routine/routine.py | Python | gpl-2.0 | 2,553 | 0.001567 | from arza.misc.platform import jit
from arza.types.space import isany
from arza.runtime import error
from arza.runtime.routine.code_routine import CodeRoutine
from arza.runtime.routine.native_routine import NativeRoutine
from arza.types import api, space
def complete_or_interrupt_native_routine(func):
def func_wr... | a.runtime.routine.callback_routine import CallbackRoutine
return CallbackRoutine(stack, on_resul | t, on_complete, function, args)
def create_module_routine(name, stack, code, env):
return jit.promote(CodeRoutine(space.newvoid(), stack, None, name, code, env))
def create_function_routine(stack, func, args, outer_env):
code = func.bytecode
scope = code.scope
name = func.name
env = create_func... |
ercchy/coding-events | web/processors/user.py | Python | mit | 2,185 | 0.026545 | from django.contrib.auth.models import User
from django_countries import countries
def get_user(user_id):
user = User.objects.get(id=user_id)
return user
def get_user_profile(user_id):
user = User.objects.get(id=user_id)
return user.profile
def get_ambassadors(country_code=None):
ambassadors = []
a... | sador.profile.country == country_code:
ambassadors.append(ambassador.profile)
else:
ambassadors.append(ambassador.profile)
return ambassadors
def get_ambassadors_for_countries():
ambassadors = get_ambassadors()
countries_ambassadors = []
# list countries minus two CUSTOM_COUNTRY_ENTRIES
for code, name in... | ries)[2:]:
readable_name = unicode(name)
main_ambassadors = get_main_ambassadors(code)
found_ambassadors = get_not_main_ambassadors(code)
countries_ambassadors.append((code, readable_name,found_ambassadors, main_ambassadors))
countries_ambassadors.sort()
return countries_ambassadors
def get_ambassadors_for_... |
deviantenigma/Savegame-backup-Utility | ignore_fortestingpurposesonly.py | Python | gpl-3.0 | 1,345 | 0.007435 | import tkinter
import string
from ctypes import windll
import os
'''
for d in string.ascii_uppercase:
if os.path.exists("%s:\\" % (d)):
print("Drive letter '%s' is in use." % (d))
'''
'''
def get_drives():
drives = []
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.ascii_uppe... | et(x) for x in Lb1.curselection()]
print(', '.join(values))
onlybutton = tk | inter.Button(text='test', command=btnclick)
Lb1.pack()
onlybutton.pack()
top.mainloop()
|
Canas/kaftools | examples/klms_pretrained.py | Python | mit | 1,192 | 0.004195 | import matplotlib.pyplot as plt
import numpy as np
from kaftools.filters import KlmsFilter
from kaftools.kernels import GaussianKernel
from kaftools.utils.shortcuts import plot_series, plot_squared_error
from kaftools.sparsifiers import NoveltyCriter | ion
if __name__ == "__main__":
# Cargar datos
data = np.load('./data/pretrained_data_lorentz.npz')
# sparsify lorentz : lr(1e-2), novelty(0.99919, 1.0)
# sparsify wind: lr(1e-2), novelty(0.9934, 1.0)
# Con | figurar KLMS
klms_params = {
'kernel': GaussianKernel(sigma=float(data['sigma_k_post'])),
'learning_rate': 1e-1,
'delay': int(data['delay']),
#'sparsifiers': [NoveltyCriterion(0.99919, 1.0)]
'coefs': data['a_post'],
'dict': data['s_post'].T,
'freeze_dict': Tru... |
redhat-cip/numeter | web-app/numeter_webapp/core/tests/group_restriction.py | Python | agpl-3.0 | 1,907 | 0.003146 | from django.test import TestCase
from core.models import User, Group, Host
class Access_Test(TestCase):
fixtures = ['test_users.json','test_groups','test_hosts.json']
def test_superuser_can_all(self):
admin = User.objects.get(pk=1)
# Access to host
host = Host.objects.get(pk=1)
... | bjects.get(pk=1)
r = user.has_access(group)
self.assertTrue(r, "Simple user can't access to his groups.")
def test_access_to_other_group(self):
user = User.objects.get(pk=2)
# Access to host
host = Host.objects.get(pk=2)
| r = user.has_access(host)
self.assertFalse(r, "Simple user can access to other group's hosts.")
# Access to user
user2 = User.objects.get(pk=3)
r = user.has_access(user2)
self.assertFalse(r, "Simple user can access to users.")
# Access to group
grou... |
shubhamshuklaer/compiler_main | main_window_ui.py | Python | gpl-3.0 | 1,476 | 0.001355 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_window.ui'
#
# Created: Wed Jan 7 16:57:08 2015
# by: PyQt5 UI code generator 5.2.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi... | self.menubar.setObjectName("menubar")
MainWindo | w.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow... |
apache/incubator-airflow | airflow/providers/google/cloud/example_dags/example_translate_speech.py | Python | apache-2.0 | 3,199 | 0.00125 | #
# 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
# "License"); you may not use this file except in compliance
# with the License. You may obtain a... | istributed 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 os
from airflow import models
from airflow.providers.google.cloud... |
pelikanchik/edx-platform | lms/envs/cms/preview_dev.py | Python | agpl-3.0 | 430 | 0 | """
Settings for the LMS that runs alongside the CMS on AWS
"""
# We intentionally define lots of variables that aren't used, and
# w | ant | to import all variables from base settings files
# pylint: disable=W0401, W0614
from .dev import *
MODULESTORE = {
'default': {
'ENGINE': 'xmodule.modulestore.draft.DraftModuleStore',
'DOC_STORE_CONFIG': DOC_STORE_CONFIG,
'OPTIONS': modulestore_options
},
}
|
teemulehtinen/a-plus | external_services/migrations/0011_menuitem_menu_url.py | Python | gpl-3.0 | 1,720 | 0.003488 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from urllib.parse import urljoin, urlsplit
from django.db import migrations, models
def forwards(apps, schema_editor):
MenuItem = apps.get_model('external_services', 'MenuItem')
items = (MenuItem.objects.all()
.exclude(service=None)
... | ', netloc='').geturl()
item.menu_url = url
item.save(update_fields=['menu_url'])
def backwards(apps, schema_editor):
MenuItem = apps.get_model('extern | al_services', 'MenuItem')
for item in MenuItem.objects.all():
item.menu_url = urljoin(item.service.url, item.menu_url)
item.save(update_fields=['menu_url'])
class Migration(migrations.Migration):
atomic = False
dependencies = [
('external_services', '0010_auto_20180918_1916'),
... |
simphony/simphony-remote | remoteappmanager/docker/async_docker_client.py | Python | bsd-3-clause | 2,391 | 0 | from concurrent.futures import ThreadPoolExecutor
import docker
import functools
# Common threaded executor for asynchronous jobs.
# Required for the AsyncDockerClien | t to operate.
_executor = ThreadPoolExecutor(1)
class AsyncDockerClient:
"""Provides an asynchronous interface to dockerpy.
All Client interface is available as methods returning a future
ins | tead of the actual result. The resulting future can be yielded.
This class is thread safe. Note that all instances use the same
executor.
"""
def __init__(self, *args, **kwargs):
"""Initialises the docker async client.
The client uses a single, module level executor to submit
... |
PyBossa/pybossa | alembic/versions/7927d63d556_n_answers_migration.py | Python | agpl-3.0 | 1,841 | 0.008691 | """n_answers migration
Revision ID: 7927d63d556
Revises: 1eb5febf4842
Create Date: 2014-08-08 14:02:36.738460
Delete the "n_answers" field from the "info" attribute/column as it is not used.
"""
# revision identifiers, used by Alembic.
revision = '7927d63d556'
down_revision = '1eb5febf4842'
from alembic import op
i... | olumn('id'),
column('info')
)
conn = op.get_bind()
query = select([task.c.id, task.c.info])
tasks = conn.execute(query)
update_values = []
for row in tasks:
info_data = row.info
info_dict | = json.loads(info_data)
if info_dict.get('n_answers'):
del info_dict['n_answers']
update_values.append({'task_id': row.id, 'new_info': json.dumps(info_dict)})
task_update = task.update().\
where(task.c.id == bindparam('task_id')).\
values... |
GoogleCloudPlatform/covid-19-open-data | src/pipelines/epidemiology/de_covid_19_germany_gae.py | Python | apache-2.0 | 2,120 | 0.000943 | # Copyright 2020 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 agreed to in writing, ... | ither express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
from typing import Dict
from numpy import unique
from pandas import DataFrame
from lib.data_source import DataSource
class Covid19GermanyDataSource(DataSource):
def par... | DataFrame], aux: Dict[str, DataFrame], **parse_opts
) -> DataFrame:
# Rename the appropriate columns
data = dataframes[0].rename(columns={"time_iso8601": "date"})
# Convert dates to ISO format
data["date"] = data["date"].apply(
lambda x: datetime.datetime.fromisoformat(... |
eduNEXT/edx-platform | lms/djangoapps/course_goals/migrations/0001_initial.py | Python | agpl-3.0 | 1,064 | 0.00282 | from django.db import migrations, models
from django.conf import settings
from opaque_keys.edx.django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
migrations | .swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CourseGoal',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
| ('course_key', CourseKeyField(max_length=255, db_index=True)),
('goal_key', models.CharField(default='unsure', max_length=100, choices=[('certify', 'Earn a certificate.'), ('complete', 'Complete the course.'), ('explore', 'Explore the course.'), ('unsure', 'Not sure yet.')])),
('user... |
DoubleNegativeVisualEffects/gaffer | python/GafferUITest/ProgressBarTest.py | Python | bsd-3-clause | 2,664 | 0.034535 | ##########################################################################
#
# Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# ... | ; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF TH | E POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import unittest
import GafferUI
import GafferUITest
class ProgressBarTest( GafferUITest.TestCase ) :
def testConstructor( self ) :
b = GafferUI.ProgressBar()
self.assertEqual( b.getRange(), ( 0,... |
riverrun/aiourlstatus | tests/parse_test.py | Python | gpl-3.0 | 990 | 0.008081 | import unittest
from aiourlstatus import app
class TestEmpty(unittest.TestCase):
def test_no_urls(self):
data = ''
urls, len_urls = app.find_sort_urls(data)
self.assertEqual(urls, [])
self.assertEqual(len_urls, 0)
class TestTXT(unittest.TestCase):
def test_parse_text(self):
... | /wiki/Self-esteem'],
['http://www.bbc.com/sport/0/'], ['http://www.haskell.org/'], ['http://lxer.com/'],
['http://ww | w.find-happiness.com/definition-of-happiness.html'],
['http://www.wikihow.com/Elevate-Your-Self-Esteem']]
self.assertCountEqual(urls, url_list)
if __name__ == '__main__':
unittest.main()
|
addition-it-solutions/project-all | addons/account_followup/account_followup.py | Python | agpl-3.0 | 28,847 | 0.010122 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | context=context,
toolbar=toolbar, submenu=submenu)
context = context or {}
if view_type == 'form' and context.get('Followupfirst'):
doc = etree.XML(res['arch'], parser=None, base_url=None)
first_node = doc.xpath("//page[@name... | tostring(doc, encoding="utf-8")
return res
def _get_latest(self, cr, uid, ids, names, arg, context=None, company_id=None):
res={}
if company_id == None:
company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
else:
company = self... |
sondree/Master-thesis | Python MOEA/utility.py | Python | gpl-3.0 | 592 | 0.015203 |
import os
import traceback,sys
CONFIG_FOLDER = "Configs"
def lo | ad_config(name):
try:
module = __import__("%s.%s" % (CONFIG_FOLDER,name), fromlist=["Config"])
except ImportError:
# Display error message
traceback.print_exc(file=sys.stdout)
raise ImportError("Failed to import module {0} from folder {1} using fromlist {2}".format(name,CONFIG_FO... | Loading config %s. Loading completed" % name
return conf
|
jesseengel/magenta | magenta/models/gansynth/lib/train_util.py | Python | apache-2.0 | 18,904 | 0.006083 | # Copyright 2019 The Magenta Authors.
#
# 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 ... | .
| 'discriminator_learning_rate': A float of disc |
interactiveaudiolab/nussl | nussl/separation/primitive/melodia.py | Python | mit | 15,856 | 0.006244 | import numpy as np
from scipy.ndimage.filters import convolve
from scipy.ndimage import maximum_filter, gaussian_filter
from .. import MaskSeparationBase, SeparationException
from ..benchmark import HighLowPassFilter
from ... import AudioSignal
from ... import vamp_imported
import numpy as np
import scipy.signal
if v... | reshold=mask_threshold
)
self.high_pass_cutoff = high_pass_cutoff
self.minimum_frequency = float(minimum_frequency)
self.maximum_frequency = float(maximum_frequency)
self.voicing_toler | ance = float(voicing_tolerance)
self.minimum_peak_salience = float(minimum_peak_salience)
self.compression = compression
self.apply_vowel_filter = apply_vowel_filter
self.add_lower_octave = add_lower_octave
self.melody = None
self.melody_signal = None
self.timest... |
xklakoux/spock2kotlin | unroller.py | Python | mit | 6,026 | 0.002489 | import re
from enum import Enum
from context import ParsingContext
class UnrollerState(Enum):
START = 0
NAMES = 1
VALUES = 2
END = 3
class Unroller(object):
should_unroll_big = False
def __init__(self, unroll_big):
self.brackets_stack = []
self.names = []
self.value... | method_name = method_name.replace('\\', ' [slash] ')
return method_name
@staticmethod
def parse(spock):
state = ParsingContext.INDETERMINATE
unroller = Unroller(Unroller.should_unroll_big)
new_lines = []
parameterized_lines = []
for line in spock:
i... | == ParsingContext.UNROLLING:
if unroller.record(line):
new_tests = unroller.unroll_tests()
state = ParsingContext.INDETERMINATE
if not unroller.was_parameterized:
new_lines.extend(new_tests)
else:
... |
eicher31/compassion-modules | logging_compassion/wizards/subscribe_logs.py | Python | agpl-3.0 | 789 | 0 | # -*- coding: utf-8 -*-
################################ | ##############################################
#
# Copyright (C) 2016 Compassion CH (http://www. | compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import api, models
class SubscribeLogs(models.TransientModel):
_name = 'auditlo... |
pfnet/chainer | tests/chainer_tests/functions_tests/activation_tests/test_prelu.py | Python | mit | 1,845 | 0 | import numpy
import chainer
from chainer import functions
from chainer import testing
@testing.parameterize(*testing.product({
'shape': [(4, 3, 2), (1,), (1, 2, 3, 4, 5, 6)],
'Wdim': [0, 1, 3],
'dtype': [numpy.float16, numpy.float32, numpy.float64],
}))
@testing.fix_random()
@chainer.testing.backend.inje... | ard_options = {}
if self.dtype == numpy.float16:
self.check_backward_options.update({'atol': 5e-4, 'rtol': 5e-3})
self.check_double_backward_options = {'atol': 5e-4, 'rtol': 5e-3}
if self.dtyp | e == numpy.float16:
self.check_double_backward_options.update(
{'atol': 5e-3, 'rtol': 5e-2})
def generate_inputs(self):
x = numpy.random.uniform(-1, 1, self.shape).astype(self.dtype)
x[(-0.05 < x) & (x < 0.05)] = 0.5
W = numpy.random.uniform(
-1, 1, s... |
django-oscar/django-oscar-paymentexpress | tests/facade_tests.py | Python | bsd-3-clause | 7,334 | 0.001364 | from django.test import TestCase
from mock import Mock, patch
from paymentexpress.facade import Facade
from paymentexpress.gateway import AUTH, PURCHASE
from paymentexpress.models import OrderTransaction
from tests import (XmlTestingMixin, CARD_VISA, SAMPLE_SUCCESSFUL_RESPONSE,
SAMPLE_DECLINED_RESPO... | ssue_date_is_allowed(se | lf):
with patch('requests.post') as post:
post.return_value = self.create_mock_response(
SAMPLE_SUCCESSFUL_RESPONSE)
card = Bankcard(card_number=CARD_VISA,
expiry_date='1015',
name="Frankie", cvv="123")
t... |
rackerlabs/heat-pyrax | pyrax/cloudcdn.py | Python | apache-2.0 | 7,833 | 0.000766 | # -*- coding: utf-8 -*-
# Copyright (c)2013 Rackspace US, 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/LIC... | f, changes):
self.manager.patch(self.id, changes)
def delete(self):
self.manager.delete(self)
def delete_assets(self, url=None, all=False):
self.manager.delete_assets(self.id, url, all)
class CloudCDNServiceManager(BaseManager):
def create(self, name, flavor_id, domains, origins... | vor_id,
"domains": domains,
"origins": origins,
"restrictions": restrictions or [],
"caching": caching or [],
"log_delivery": {"enabled": bool(log_delivery)}}
resp, resp_body = self.api.method_post("/%s" % self.uri_base,
... |
inonit/wagtail | wagtail/tests/settings.py | Python | bsd-3-clause | 4,667 | 0.000429 | import os
WAGTAIL_ROOT = os.path.dirname(__file__)
STATIC_ROOT = os.path.join(WAGTAIL_ROOT, 'test-static')
MEDIA_ROOT = os.path.join(WAGTAIL_ROOT, 'test-media')
MEDIA_URL = '/media/'
DATABASES = {
'default': {
'ENGINE': os.environ.get('DATABASE_ENGINE', 'django.db.backends.sqlite3'),
'NAME': os.... | E_HOST', None),
'TEST': {
'NAME': os.environ.get('DATABASE_NAME', None),
}
}
}
SECRET_KEY = 'not needed'
ROOT_URLCONF = 'wagtail.tests.urls'
STATIC_URL = '/static/'
STATIC_ROOT = STATIC_ROOT
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
U... | 'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages... |
syunkitada/fabkit-repo | fabscript/openstack/mongodb.py | Python | mit | 163 | 0 | # coding: utf-8
from fabkit import task
from fablib.mongodb import MongoDB
mongodb = MongoD | B()
@task
def setup():
mongodb.setup()
return {'status': | 1}
|
mcbor/adventofcode | 2016/day07/day07-pt1.py | Python | mit | 1,067 | 0.00656 | #!/usr/bin/env python3
# Advent of Code 2016 - Day 7, Part One
import sys
import re
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> ( | s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def has_abba(string):
for s in window(string, 4):
if s[:2] ... | return 1
valid = 0
with open(argv[1]) as f:
for line in f:
nets = re.split('[\[\]]', line.strip())
if any(has_abba(s) for s in nets[::2]) \
and not any(has_abba(h) for h in nets[1::2]):
valid += 1
print(valid)
return 0
if __name__ == '... |
wwfifi/uliweb | uliweb/utils/_compat.py | Python | bsd-2-clause | 10,959 | 0.00365 | """
Compatible with py2 and py3, inspired by jinjin2, future, etc
common types & functions:
name 2.x 3.x
------------ ----------- -----------
unichr unichr chr
unicode unicode str
range xrange range
string_types (str, unicode)... | om urllib2 import (
# AbstractBasicAuthHandler,
# AbstractDigestAuthHandler,
# BaseHandler,
# CacheFTPHandler,
# FileHandler,
# FTPHa | ndler,
# HTTPBasicAuthHandler,
# HTTPCookieProcessor,
# HTTPDefaultErrorHandler,
# HTTPDigestAuthHandler,
# HTTPErrorProcessor,
# HTTPHandler,
# ... |
PascalSteger/gravimage | programs/gi_mc_errors.py | Python | gpl-2.0 | 2,025 | 0.011852 | #!/usr/bin/env python3
## Estimates errors using Monte Carlo sampling
# Hamish Silverwood, GRAPPA, UvA, 23 February 2015
import numpy as np
import gl_helper as gh
import pdb
import pickle
import sys
import numpy.random as rand
import matplotlib.pyplot as plt
#TEST this will eventually go outside
def ErSamp_gauss_l... | , binmax, jter_z_data, np.ones(len(jter_z_data)))
nu_vectors.append(jter_nu)
#Calculate standard deviations of nu
nu_vectors = np.array(nu_vectors)
nu_stdevs = []
nu_means = []
nu_media | ns = []
for pter in range(0, len(binmin)):
nu_stdevs.append(np.std(nu_vectors[:, pter]))
nu_means.append(np.mean(nu_vectors[:, pter]))
nu_medians.append(np.median(nu_vectors[:, pter]))
#pdb.set_trace()
#fig = plt.figure()
#ax = fig.add_subplot(111)
#no, bins, patches = ax.h... |
dzimine/mistral | mistral/api/controllers/v1/execution.py | Python | apache-2.0 | 4,285 | 0.000233 | # -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, 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 requir... | makhotkin) we should use thing such a decorator here
abort(400, e.message)
return Execution.from_dict(values)
@wsme_pecan.wse | xpose(None, wtypes.text, wtypes.text, status_code=204)
def delete(self, workbook_name, id):
LOG.debug("Delete execution [workbook_name=%s, id=%s]" %
(workbook_name, id))
db_api.execution_delete(workbook_name, id)
@wsme_pecan.wsexpose(Executions, wtypes.text)
def get_all(s... |
zephyrplugins/zephyr | zephyr.plugin.jython/jython2.5.2rc3/Lib/encodings/cp855.py | Python | epl-1.0 | 34,106 | 0.019615 | """ Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP855.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
... | s,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
| return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp855',
encode=Codec().encode,
deco... |
samiunn/incubator-tinkerpop | gremlin-python/src/main/jython/tests/structure/test_graph.py | Python | apache-2.0 | 4,417 | 0.001132 | '''
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
"License"); you may not use this ... | on("Accessing using slices should throw a type error")
except TypeError:
pass
#
assert path == path
assert hash(path) == hash(path)
path2 = Path([set(["a", "b"]), set(["c", "b"]), set([])], [1, Vertex(1), "hello"])
assert path == path2
assert hash(path... | set([])], [3, Vertex(1), "hello"])
if __name__ == '__main__':
unittest.main()
|
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_05_01/operations/_route_filters_operations.py | Python | mit | 27,222 | 0.004629 | # 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 may ... | :type resource_group_name: str
:param route_filter_name: The name of the route filter.
:type route_filter_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller fro... | oll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of... |
jwren/intellij-community | python/testData/refactoring/inlineFunction/removingTypeComment/main.py | Python | apache-2.0 | 81 | 0.037037 | def foo():
# type: () -> int
p | rint(42)
return 42
re | s = fo<caret>o() |
nachtmaar/androlyze | androlyze/celery/CeleryConstants.py | Python | mit | 1,276 | 0.003135 |
# encoding: utf-8
__author__ = "Nils Tobias Schmidt"
__email__ = "schmidt89 at informatik.uni-marburg.de"
'''
Holds some constants/settings related to celery.
'''
from androlyze.settings import *
############################################################
#---Max retry wait time
##################################... | ELERY_DATABASE_STORE_RETRY_MAX_TIME = 120
############################################################
#---Result backend constants
# used to get information from callback handlers
############################################################
CELERY_RESULT_BACKEND_KEY_RESULT = "result"
CELERY_RESULT_BACKEND_KEY_TRACEB... | ############################################################
#---Other
############################################################
# value for retrying until success
CELERY_RETRY_INFINITE = None
def get_analyze_task_name():
from androlyze.analyze.distributed.tasks.AnalyzeTask import AnalyzeTask
return Analyz... |
manuelbua/gitver | gitver/commands.py | Python | apache-2.0 | 15,445 | 0.000129 | #!/usr/bin/env python2
# coding=utf-8
"""
Defines gitver commands
"""
import re
import os
import sys
from string import Template
from termcolors import term, bold
from git import get_repo_info
from gitver.storage import KVStore
from sanity import check_gitignore
from defines import CFGDIR, PRJ_ROOT, CFGDIRNAME
from ... | """
Builds the formatting arguments by processing the specified repository
information and returns them.
If a tag defines pre-release metadata, this will have the precedence
over any existing user-defined string.
"""
in_next = repo_info['count'] > 0
has_next_custom = next_custom is not None... | ['maj']
vmin = repo_info['min']
vpatch = repo_info['patch']
vrev = repo_info['rev']
vcount = repo_info['count']
vpr = repo_info['pr']
vbuildid = repo_info['build-id']
has_pr = vpr is not None
has_rev = vrev is not None
# pre-release metadata in a tag has precedence over user-specifi... |
NiceCircuits/pcbLibraryManager | src/pcbLibraryManager/symbols/symbolsIC.py | Python | cc0-1.0 | 3,334 | 0.013197 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 2 19:02:52 2015
@author: piotr at nicecircuits.com
"""
from libraryManager.symbol import symbol
from libraryManager.symbolPrimitive import *
from libraryManager.defaults import defaults
from libraryManager.common import *
class symbolIC(symbol):
"""
IC symbol g... | ght/2-100+offset
for p in pins[x]:
if p:
| if isinstance(p[2],str):
p[2]=pinType.fromStr[p[2]]
self.pins.append(symbolPin(str(p[0]), str(p[1]), [(width/2+pinLength)*(1 if x>0 else -1),y],\
pinLength, p[2], rotation=180 if x>0 else 0))
y = y-100
self.nameObject... |
phihes/sds-models | sdsModels/models.py | Python | mit | 12,892 | 0.000853 | import sklearn.cross_validation as cv
import sklearn.dummy as dummy
from sklearn.mixture import GMM
from sklearn.hmm import GMMHMM
from sklearn import linear_model, naive_bayes
import collections
import itertools
import pandas as pd
from testResults import TestResults
from counters import *
import utils as utils
cla... | with current state label
d = data[data.rating == state]
# prepare data shape
d = np.array(zip(*[d[f].values for f in features]))
# init GMM
gmm = GMM(num_mixc, cov_type)
# train
gmm.fit(d)
mixes.append(gmm)
# train... | model.transmat_ = mle.transition
model.startprob_ = mle.initial
return model
class Ols(Model):
""" Ordinary least squares regression """
_name = "OLS"
isSklearn = True
def _train(self, data):
features = self.params['features']
X = np.array(zip(*[data[f].values... |
Polychart/builder | server/polychart/wsgi.py | Python | agpl-3.0 | 1,058 | 0 | """
WSGI config for polychart project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`... | gi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from hellowo | rld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
|
mobiledayadmin/DenyHosts | scripts/restricted_from_invalid.py | Python | gpl-2.0 | 884 | 0.013575 | #!/ | bin/env python
import os, sys
def usage():
print "%s WORK_DIR [num_results]" % sys.argv[0]
sys.exit(1)
try:
work_dir = sys.argv[1]
except:
print "you must specify your DenyHosts WORK_DIR"
usage()
try:
num = int(sys.argv[2])
except:
num = 10
fname = os.path.join(work_dir, "users-invalid"... | username = foo[0]
attempts = int(foo[1])
# timestamp = foo[2].strip()
except:
continue
l = d.get(attempts, [])
l.append(username)
d[attempts] = l
fp.close()
keys = d.keys()
keys.sort()
keys.reverse()
i = 0
for key in keys:
l = d.get(key)
for username in l:
... |
saisankargochhayat/algo_quest | leetcode/106. Construct Binary Tree from Inorder and Postorder Traversal/soln.py | Python | apache-2.0 | 978 | 0.00818 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# We use the inorder to find which elements are left and right of the curr element.
# And the post order to start with the fir... | r: List[int]) -> TreeNode:
def helper(inorderL, inorderR):
# base case
if inorderL >= inorderR:
return None
nonlocal postorder
curr = postorder.pop()
root = TreeNode(curr)
currPos = inorderMap[curr]
root.right = ... | merate(inorder)}
return helper(0, len(inorder)) |
moneta-project/moneta-2.0.1.0 | contrib/devtools/update-translations.py | Python | mit | 6,780 | 0.00649 | #!/usr/bin/python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the follo... | at_specifiers(source, translation, errors):
source_f = split_format_specifiers(find_format_spec | ifiers(source))
# assert that no source messages contain both Qt and strprintf format specifiers
# if this fails, go change the source as this is hacky and confusing!
assert(not(source_f[0] and source_f[1]))
try:
translation_f = split_format_specifiers(find_format_specifiers(translation))
ex... |
Ahmad31/Web_Flask_Cassandra | flask/lib/python2.7/site-packages/pony/orm/tests/testutils.py | Python | apache-2.0 | 4,752 | 0.008207 | from __future__ import absolute_import, print_function, division
from pony.py23compat import basestring
from functools import wraps
from contextlib import contextmanager
from pony.orm.core import Database
from pony.utils import import_module
def raises_exception(exc_class, msg=None):
def decorator(func... | TestProvider.server_version = server_version
kwargs['pony_check_connection'] = False
kwargs['pony_pool_mockup'] = TestPool(self)
Database.bind(self, TestProvider, *args, **kwargs)
def _execute(database, sql, globals, locals, frame_depth):
assert False # pragma: no cove... | assert type(arguments) is not list and not returning_id
database.sql = sql
database.arguments = arguments
return test_cursor
def generate_mapping(database, filename=None, check_tables=True, create_tables=False):
return Database.generate_mapping(database, filename, create_tab... |
christi3k/zulip | zerver/tornado/descriptors.py | Python | apache-2.0 | 821 | 0.00609 | from __future__ import absolute_import
from __future__ import print_function
from typing import Any, Dict, Optional
if False:
import zerver.tornado.event_queue
descriptors_by_handler_id | = {} # type: Dict[int, zerver.tornado.event_queue.ClientDescriptor]
def get_descriptor_by_handler_id(handler_id):
# type: (int) -> zerver.tornado.event_queue | .ClientDescriptor
return descriptors_by_handler_id.get(handler_id)
def set_descriptor_by_handler_id(handler_id, client_descriptor):
# type: (int, zerver.tornado.event_queue.ClientDescriptor) -> None
descriptors_by_handler_id[handler_id] = client_descriptor
def clear_descriptor_by_handler_id(handler_id, cl... |
SINGROUP/pycp2k | pycp2k/classes/_basis4.py | Python | lgpl-3.0 | 328 | 0.006098 | from pycp2k.inputsection import InputSection
class _basis4(InputSec | tion):
def __init__(self):
| InputSection.__init__(self)
self.Default_keyword = []
self._name = "BASIS"
self._repeated_default_keywords = {'Default_keyword': 'DEFAULT_KEYWORD'}
self._attributes = ['Default_keyword']
|
WoLpH/python-progressbar | tests/test_stream.py | Python | bsd-3-clause | 2,391 | 0 | import io
import sys
import pytest
import progressbar
def test_nowrap():
# Make sure we definitely unwrap
for i in range(5):
progressbar.streams.unwrap(stderr=True, stdout=True)
stdout = sys.stdout
stderr = sys.stderr
progressbar.streams.wrap()
assert stdout == sys.stdout
assert... | _stderr__])
def test_fd_as_standard_streams(strea | m):
with progressbar.ProgressBar(fd=stream) as pb:
for i in range(101):
pb.update(i)
|
jenhantao/preRNA-seq_OligoDesigner | makeAllOligos.py | Python | bsd-2-clause | 2,270 | 0.031718 | '''
Designs oligos for a pre RNA-seq selection method
'''
### imports ###
import sys
import os
import numpy as np
def readFastaFile(fastaFilePath):
'''
Given a path to a multiline fasta file, reads the file, returning two lists - one containing the sequences, the other containing the headers
inputs: path to a fas... | + "\n")
outFile.write(oligos[i] + "\n")
outFile.close()
if __name__ == "__main__":
targetDirectoryPath = sys.argv[1] # path to a directory containing fasta files giving the sequences we want the oligos to hybridize to
targetLength = int(sys.argv[2]) # desired length of oligos
outputPath = sys.argv[3] # path... | ]
allTargetHeaders = []
# read in sequences
print("reading target files")
for targetFile in os.listdir(targetDirectoryPath):
print(targetFile)
targetSequences, targetHeaders = readFastaFile(targetDirectoryPath + "/" + targetFile)
allTargetSequences += targetSequences
allTargetHeaders += targetHeaders
pr... |
saltstack/salt | tests/pytests/unit/engines/test_engines.py | Python | apache-2.0 | 595 | 0.003361 | import pytest
| import salt.engines
from tests.support.mock import MagicMock, patch
d | ef test_engine_module_name():
engine = salt.engines.Engine({}, "foobar.start", {}, {}, {}, {}, name="foobar")
assert engine.name == "foobar"
def test_engine_title_set():
engine = salt.engines.Engine({}, "foobar.start", {}, {}, {}, {}, name="foobar")
with patch("salt.utils.process.appendproctitle", Mag... |
jcu-eresearch/climas-ng | webapp/climasng/data/datafinder.py | Python | apache-2.0 | 2,719 | 0.004046 |
import os
import re
import json
def createSpeciesJson(source_data_path):
# create the species.json file using data from the specified path
# traverse directories looking for dirs named "1km". If it's
# path matches this pattern:
# .../<taxon-name>/models/<species-name>/1km
# then record that as ... | h.join(os.path.dirname(__file__), 'all_species.json')
try:
# try reading in the list of sci-to-common species names
with open(cn_file) as f:
commo | n_names = json.load(f)
except:
# give up on common names if we can't read them
common_names = {}
#
# okay, ready to check for modelled species
#
species_list = {}
for dir, subdirs, files in os.walk(source_data_path):
match = one_km_regex.search(dir)
if match:
... |
MDAnalysis/mdanalysis | testsuite/MDAnalysisTests/coordinates/test_dms.py | Python | gpl-2.0 | 3,032 | 0.00033 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#... | Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Com | put. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
import MDAnalysis as mda
import numpy as np
import pytest
from numpy.testing import assert_equal
from MDAnalysis.lib.mdamath import triclinic_vectors
from MDAnalysisTests.datafiles import (DMS)
class TestDMSReader(object):
@pytest.fixture()
def univ... |
parrisha/raspi-visualizer | samples/WavGenerator.py | Python | mit | 1,233 | 0.024331 | #############
# ECE 612 Spring 2017
# Joe Parrish
#
# Use the same logic from SpectrumTester.py to generate multiple sine waves
# but write that output to a .wav file for file based testing of the project code
#############
import wave
import argparse
import numpy as np
def generate_sample_file(test_freqs, test_amps... | x in range(0,8):
wave_writer.writeframes(y)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Write a wave file containing Numpy generated sine waves')
parser.add_argument('--freqs', nargs='+', type=int)
parser.add_argument('--amps', nargs='+', type=int)
| args = parser.parse_args()
generate_sample_file(args.freqs, args.amps)
|
Atothendrew/XcodeBuildIncrementer | XcodeBuildIncrementer/__init__.py | Python | mit | 60 | 0 | __auth | or__ = 'Andrew Williamson <axwilliamson@godad | dy.com>'
|
a25kk/dpf | src/dpf.sitetheme/dpf/sitetheme/__init__.py | Python | mit | 217 | 0 | # -*- coding: utf-8 -*-
"""Init and utils."""
from zope.i18nmessageid import MessageFactory
_ = MessageFactory('dpf.sitethem | e')
def initializ | e(context):
"""Initializer called when used as a Zope 2 product."""
|
joaormatos/anaconda | mmfparser/data/chunkloaders/extdata.py | Python | gpl-3.0 | 1,201 | 0.004163 | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of Anaconda.
# Anaconda 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 of the License, or
# (at your option) any later version.
# ... |
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with Anaconda. If not, see <http://ww | w.gnu.org/licenses/>.
from mmfparser.bytereader import ByteReader
from mmfparser.loader import DataLoader
class ExtData(DataLoader):
name = None
data = None
def read(self, reader):
if self.settings.get('old', False):
self.filename = reader.readString()
self.data = reader.re... |
GeoMatDigital/django-geomat | geomat/users/models.py | Python | bsd-3-clause | 493 | 0 | # -*- coding: utf-8 -*-
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.encoding import python_2_unicode_co | mpatible
from django.utils.translation import ugettext_lazy as _
@python_2_unicode_compatible
class User(AbstractUser):
# First Name and Last Name do not cover name patterns
# around the globe.
name = models.Char | Field(_("Name of User"), blank=True, max_length=255)
def __str__(self):
return self.username
|
Spasley/python | generator/record.py | Python | apache-2.0 | 1,285 | 0.005447 | __author__ = 'Volodya'
from model.recordfields import RecordFields
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ['number of records', 'file'])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f... | 'lastname', 10), middlename=random_string('middlename', 10),
nickname=random_string('nickname', 10), company=random_string('company', 10), address=random_string('middlename', 10))
for i in range(n)
]
file = os.path.join(os.path.dirname(os.path.abspath(__file | __)), "..", f)
with open(file, 'w') as out:
jsonpickle.set_encoder_options('json', indent=2)
out.write(jsonpickle.encode(testdata)) |
luisen14/treatment-tracking-project | treatment_tracker/researchers/apps.py | Python | apache-2.0 | 97 | 0 | from django.apps impo | rt AppConfig
class ResearchersConfig(AppConfig):
name = 'researcher | s'
|
encukou/freeipa | ipatests/test_ipaserver/test_install/test_installutils.py | Python | gpl-3.0 | 7,877 | 0.000127 | #
# Copyright (C) 2017 FreeIPA Contributors. See COPYING for license
#
from __future__ import absolute_import
import binascii
import os
import psutil
import re
import subprocess
import textwrap
import pytest
from unittest.mock import patch, mock_open
from ipaplatform.paths import paths
from ipapython import ipaut... | _in_container):
"""Not a container and insufficient RAM"""
mock_in_container.return_value = False
fake_memory = psutil._pslinux.svmem
fake_memory.available = int(RAM_NOT_OK)
mock_psutil.return_value = fake_memory
with pytest.raises(ScriptError):
installutils.check_available_memory(True)... |
"""Not a container and sufficient RAM"""
mock_in_container.return_value = False
fake_memory = psutil._pslinux.svmem
fake_memory.available = int(RAM_OK)
mock_psutil.return_value = fake_memory
installutils.check_available_memory(True)
|
Jolopy/MizzyChan | mizzychan/app/crawl/rucrawler.py | Python | gpl-3.0 | 67,999 | 0.018721 | import requests
from bs4 import BeautifulSoup
def getMemes():
memep1URL="http://www.quickmeme.com/page/1/"
memep2URL="http://www.quickmeme.com/page/2/"
memep3URL="http://www.quickmeme.com/page/3/"
memep4URL="http://www.quickmeme.com/page/4/"
memep5URL="http://www.quickmeme.com/page/5/"
memep6UR... | l("a")
memep8Links=memep8Soup.find_all("a")
memep9Links=memep9Soup.find_all("a")
memep10Links=memep10Soup.find_all("a")
linkList=[memep1Links,memep2Links,memep3Links,memep4Links,memep5Links,memep6Links,memep7Links,
memep8Links,memep9Links,memep10Links]
mem | eLinks=[]
pointer=0
listLength=len(linkList)
for i in range(listLength):
for link in linkList[pointer]:
tempURL=link.get("href")
if tempURL is None:
continue
if tempURL.startswith("/p/"):
memeFix='http://www.quic... |
thaim/ansible | lib/ansible/module_utils/network/checkpoint/checkpoint.py | Python | mit | 19,463 | 0.003853 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | time.sleep(2) # Wait for t | wo seconds
if not task_complete:
module.fail_json(msg="ERROR: Timeout.\nTask-id: {0}.".format(task_id_payload['task-id']))
# handle publish command, and wait for it to end if the user asked so
def handle_publish(module, connection, version):
if module.params['auto_publish_session']:
publish_co... |
RocketRedNeck/PythonPlayground | pidSim.py | Python | mit | 18,070 | 0.008356 | # -*- coding: utf-8 -*-
"""
pidSim.py
A simulation of a vision control to steering PID loop accounting for communication and
processing latency and variation; demonstrates the impact of variation
to successful control when the control variable (CV) has direct influence on
the process variable (PV)
This allows student... | er_sec = 0.000 # Maximum Random task jitter
pidMaxJitter_index = round(pidMaxJitter_sec / dt_sec)
pidMeanJitter_index = round((pidMaxJitter_index + pidMinJitter_index)/2)
pidStdDevJitter_index = round((pidMaxJitter_index - pidMinJitter_index) / 3)
cvPid = np.zeros(nmax) # Initial value of cv coming from PID | calculation
# The first communication link is assumed to be a CAN bus
# The bus overhead is assumed to be a total fixed time
# not exceeding about 1 ms for up to four (4) messages going to four (4)
# separate motors (including any increases for bit stuffing); in other words
# we assume something like 100 bits per mes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.