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
kubernetes-client/python
kubernetes/client/models/v1_rule_with_operations.py
Python
apache-2.0
9,436
0
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.23 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import si...
e api_versions of this V1RuleWithOperations. # noqa: E501
:rtype: list[str] """ return self._api_versions @api_versions.setter def api_versions(self, api_versions): """Sets the api_versions of this V1RuleWithOperations. APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length ...
whtsky/parguments
parguments/cli.py
Python
mit
3,906
0
# Copyright (c) 2010 by Dan Jacob. # # Some rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and t...
e and converts to boolean value. :param name: prompt text :param default: default value if no input provided. :param yes_choices: default 'y', 'yes', '1', 'on', 'true', 't' :param no_choices: default 'n', 'no', '0', 'off', 'false', 'f' """ yes_choices = yes_choices or ('y', 'yes', '1', 'on...
o', '0', 'off', 'false', 'f') while True: rv = prompt(name + '?', default and yes_choices[0] or no_choices[0]) if rv.lower() in yes_choices: return True elif rv.lower() in no_choices: return False def prompt_choices(name, choices, default=None, no_choice=('none',))...
JamesLinEngineer/RKMC
addons/script.navi-x/src/CLogin.py
Python
gpl-2.0
3,203
0.01561
############################################################################# # # Copyright (C) 2013 Navi-X # # This file is part of Navi-X. # # Navi-X 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 Fou...
atetime, traceback import shutil import os from libs2 import * try: Emulating = xbmcgui.Emulating except: Emulating = False LABEL_USRNAME = 141 LABEL_PASSWORD = 142 BUTTON_USRNAME = 143 BUTTON_PASSWORD = 1144 BUTTON_LOGIN = 145 BUTTON_CANCEL = 146 class CDialogLogin(xbmcgui.WindowXMLDialog): def...
# self.bg = xbmcgui.ControlImage(100,100,520,376, imageDir + "background_txt.png") # self.addControl(self.bg) self.userloggedin = False #read user ID from file self.user_id='' pass def onAction(self, action): if (action == ACTION_PREVIOUS_MENU) or (ac...
mtlchun/edx
common/lib/xmodule/xmodule/lti_module.py
Python
agpl-3.0
37,531
0.002771
""" Learning Tools Interoperability (LTI) module. Resources --------- Theoretical background and detailed specifications of LTI can be found on: http://www.imsglobal.org/LTI/v1p1p1/ltiIMGv1p1p1.html This module is based on the version 1.1.1 of the LTI specifications by the IMS Global authority. For authenticat...
oauthlib/oauth1/rfc5849/signature.py#L136 """ display_name = String( display_name=_("Display Name"), help=_( "Enter the name that students see for this component. " "Analytics reports may also use the di
splay name to identify this component." ), scope=Scope.settings, default="LTI", ) lti_id = String( display_name=_("LTI ID"), help=_( "Enter the LTI ID for the external LTI provider. " "This value must be the same LTI ID that you entered in the " ...
jtpaasch/simplygithub
simplygithub/internals/merges.py
Python
mit
1,433
0
# -*- coding: utf-8 -*- """Utilities for performing merges.""" from . import api def prepare(data): """Restructure/prepare data about merges for output.""" sha = data.get("sha") commit = data.get("commit") message = commit.get("message")
tree = commit.get
("tree") tree_sha = tree.get("sha") return {"message": message, "sha": sha, "tree": {"sha": tree_sha}} def merge(profile, head, base, commit_message=None): """Merge the head of a branch into the base branch. Args: profile A profile generated from ``simplygithub.authentication.pro...
pawhewitt/Dev
SU2_PY/SU2/run/geometry.py
Python
lgpl-2.1
3,794
0.011861
#!/usr/bin/env python ## \file geometry.py # \brief python package for running geometry analyses # \author T. Lukaczyk, F. Palacios # \version 5.0.0 "Rav
en" # # SU2 Original Developers
: Dr. Francisco D. Palacios. # Dr. Thomas D. Economon. # # SU2 Developers: Prof. Juan J. Alonso's group at Stanford University. # Prof. Piero Colonna's group at Delft University of Technology. # Prof. Nicolas R. Gauger's group at Kaiserslautern University of Tech...
hadim/pygraphml
pygraphml/tests/__init__.py
Python
bsd-3-clause
93
0
def
run_all(): import nose2 nose2.discover(module='pygraphml') __al
l__ = [run_all]
bcarroll/splunk_samltools
bin/splunksaml.py
Python
apache-2.0
6,313
0.011722
import re, sys, time, splunk.Intersplunk import urllib, zlib, base64 import logging, logging.handlers try: import xml.etree.cElementTree as xml except ImportError: import xml.etree.ElementTree as xml def setup_logger(LOGGER_NAME,LOGFILE_NAME): logger = logging.getLogger(LOGGER_NAME) file_handler ...
saml_message = base64_decode(saml_message) saml_message = zlib_decompress(saml_message) saml_message_dict = xml2dict(saml_message,'SAML') if saml_message_dict is not None:
logger.debug(repr(saml_message_dict)) _result.update(saml_message_dict) # create new fields with SAML attributes #append extracted_saml_fields to results splunk.Intersplunk.outputResults(results) except: import traceback stack = trac...
ganeti/ganeti
test/py/ganeti.rapi.testutils_unittest.py
Python
bsd-2-clause
7,060
0.005949
#!/usr/bin/python3 # # Copyright (C) 2012 Google 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: # # 1. Redistributions of source code must retain the above copyright notice, # this list o...
sertRaises(rapi.testutils.VerificationError, voi, opcodes.OpClusterRe
name.OP_ID, { "name": object(), }) def testSuccess(self): voi = rapi.testutils.VerifyOpInput voi(opcodes.OpClusterRename.OP_ID, { "name": "new-name.example.com", }) class TestVerifyOpResult(unittest.TestCase): def testSuccess(self): vor = rapi.testutils.VerifyOpResult vor...
lesina/labs2016
contests_1sem/6-7/E.py
Python
gpl-3.0
443
0.006772
a, b = list(map(int, input().split())) array = [] for i in range(a): array.append([]) for j in range(b): if (i+j) % 2: array[i].append('*') else: array[i].a
ppend('.') #for i in range(n): # for j in range(
n): # if i == j or i == n//2 or j == n//2 or i == n-j-1: # array[i][j] = "*" for i in range(a): for j in range(b): print(array[i][j], end = " ") print()
1tush/reviewboard
reviewboard/reviews/tests.py
Python
mit
108,697
0.000037
from __future__ import print_function, unicode_literals from datetime import timedelta import logging import os from django.conf import settings from django.contrib.auth.models import AnonymousUser, User from django.core.exceptions import ValidationError from django.core.files.uploadedfile import SimpleUploadedFile f...
ig.models import SiteConfiguration from djblets.testing.decorators import add_fixtures from kgb import SpyAgency from reviewboard.accounts.models import Profile, LocalSiteProfile from reviewboard.attachments.models import FileAttachment from reviewboard.reviews.forms import DefaultReviewerForm, GroupForm from reviewbo...
t (markdown_escape, markdown_unescape) from reviewboard.reviews.models import (Comment, DefaultReviewer, Group, ReviewRequest, ...
yaroslav-tarasov/avango
avango-skelanim/examples/skeletal_character_control/main_animation_config.py
Python
lgpl-3.0
13,239
0.001586
import avango import avango.script import avango.gua.skelanim from examples_common.GuaVE import GuaVE import examples_common.navigator from avango.gua.skelanim.CharacterControl import CharacterControl from avango.gua.skelanim.AnimationControl import AnimationConfig ### CAMERA CONTROL VIA XBOX CONTROLLER: def camera_c...
+ \ "UnrealTournament/UniversalAnimations/Idle_Ready_Rif.FBX" path_run = "/opt/project_animation/Assets/" + \ "UnrealTournament/UniversalAnimations/Run_Fwd_Rif.FBX" bob_loop.load_animation(path_idle, "idle") bob_loop.load_animation(path_idle, "idle2") bob_loop.load_animation(path_run, "r...
ation(path_run, "run_fwd2") #character control character_control_loop = CharacterControl() character_control_loop.my_constructor(bob_loop, bob_loop, AnimationConfig("idle"), window) character_control_loop.on_animation_end("idle", ...
oiertwo/vampyr
flask/index.py
Python
mit
1,592
0.014447
__author__ = 'oier' import json from flask import Flask
, make_response app = Flask(__name__) import seaborn as sns import numpy as np import pandas as pd import os from datetime import datetime import matplotlib.pyplot as plt import sys from matplotlib.figure import Figure from matplotlib.backends.backend_agg import FigureCanvasAgg a
s FigureCanvas from io import StringIO from sklearn import linear_model from models import InputForm, ValueSelector from flask import Flask, render_template, request from compute import compute, load_data, line_plot @app.route('/') def index(): return 'Hello World!' def form_values(request): data = load_...
ziima/django-multilingual-ds9
multilingual/models/sql/__init__.py
Python
mit
44
0
""" Sql support f
or multilingual models "
""
openstack/tacker
tacker/db/migration/alembic_migrations/versions/13ecc2dd6f7f_change_nullable_value_of_path_id.py
Python
apache-2.0
1,218
0.004926
# Copyright 2018 OpenStack Foundation # # 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 ...
alembic import op import sqlalchemy as sa def upgrade(active_plugins=None, options=None): op.alter_column('vnffgchains', 'path_id', existing_type=sa.String(length=255), nullable=True) op.alter_column('vnffgnfps', 'path_id', existing_ty
pe=sa.String(length=255), nullable=True)
Copper-Head/the-three-stooges
conll2hdf5.py
Python
mit
3,576
0.004754
import argparse from collections import Counter from itertools import chain from numpy import save, array from os import listdir from os import path import re import sys import dataproc as dp parser = argparse.ArgumentParser() parser.add_argument('-d', '--dir', type=str, help='Source directory to conll-data.') parser...
: seq = [] for line in sentence.split('\n'): if line.strip(): word = filter_punc(transform(line.split('\t')[1])) if word: seq.append(word) if len(
seq) <= len_upper_limit and len(seq) >= len_lower_limit: seq.append(EOS) seqs.append(seq) else: drop_seqs.append(seq) counter = Counter(list(chain(*seqs))) ix_seq = [] ix_seqs = [] tok2ix = {} if args.removeunknown or args.wordfreq == 1 else {'<UNKNOWN>': 0} ix = len(tok2ix)...
skyoo/jumpserver
apps/perms/api/application/__init__.py
Python
gpl-2.0
153
0
from
.user_permission import * from .application_permission import * from .application_permission_relat
ion import * from .user_group_permission import *
kellogg76/ArduinoTelescopeDustCover
open.py
Python
mit
507
0.003945
## Open a serial connection with Arduino. import time import serial ser = serial.Serial("COM9", 9600) # Open serial port that Arduino is using time.sleep(3) # Wait 3 seconds for Arduino to reset pr
int ser # Print serial config print "Sending serial command to OPEN the dust cover." ser.write("O") print "Closing serial connecti
on." ser.close() # Reminder to close the connection when finished if(ser.isOpen()): print "Serial connection is still open."
proversity-org/edx-platform
common/lib/calc/calc/calc.py
Python
agpl-3.0
13,906
0.000791
""" Parser and evaluator for FormulaResponse and NumericalResponse Uses pyparsing to parse. Main function as of now is evaluator(). """ import math import numbers import operator import numpy import scipy.constants from pyparsing import ( CaselessLiteral, Combine, Forward, Group, Literal, Mat...
m. In the case of parenthesis, ignore them. """ # Find first number in the list result = next(k for k in parse_result if isinstance(k, numbers.Number)) return result def eval_power(parse_result): """ Take a list of numbers and exponentiate them, right to left. e.g. [ 2, 3, 2 ] -> 2^3...
(not to be interpreted (2^3)^2 = 64) """ # `reduce` will go from left to right; reverse the list. parse_result = reversed( [k for k in parse_result if isinstance(k, numbers.Number)] # Ignore the '^' marks. ) # Having reversed it, raise `b` to the power of `a`. power = reduce(la...
eugenekolo/project-euler
euler025.py
Python
mit
856
0.008216
#!/usr/bin/python3 # -*- coding: utf-8 -*- ################################################################################ # Euler 25 # 1000-digit Fibonacci number # Author: Eugene Kolo - 2014 # Contact: www.eugenekolo.com # The Fibonacci sequence is defined by the recurrence relation: # Fn = Fn−1 + Fn−2, where F1 = ...
first 12 terms will be: F1 = 1 F2 = 1 F3 = 2 F4 = 3 F5 = 5 F6 = 8 F7 = 13 # F8 = 21 F9 = 34 F10 = 55 F11 = 89 F12 = 144 # The 12th term, F12, is the first term to contain three digits. # What is the f
irst term in the Fibonacci sequence to contain 1000 digits? ################################################################################ def solve(): from eulerlib import fib n = 0 while (len(str(fib(n))) < 1000): n +=1 return n if __name__ == '__main__': print(solve())
ekristen/mythboxee
mythtv/MythStatic.py
Python
mit
261
0.011494
# -*- coding: utf-8 -*- """ Contains any static and global variables for MythTV Python Bindings """ OWN_VERSION = (0,23,1,0) SCHEMA_VE
RSION = 1254 MVSCHEMA_VERSION = 1032 NVSC
HEMA_VERSION = 1004 PROTO_VERSION = 23056 PROGRAM_FIELDS = 47 BACKEND_SEP = '[]:[]'
JarbasAI/jarbas-core
mycroft/jarbas-skills/LILACS_core/question_parser.py
Python
gpl-3.0
5,535
0.003433
import re import spotlight from requests import ConnectionError, HTTPError class EnglishQuestionParser(): """ Poor-man's english question parser. Not even close to conclusive, but appears to construct some decent w|a queries and responses. __author__ = 'seanfitz' """ def __init__(...
"(?P<Query1>.*) (?P<QuestionVerb>is|are|was|were) " "(?P<Query2>.*)"), re.compile( ".*(?P<QuestionWord>are|is) " "(?P<Query1>.*) (?P<QuestionVerb>an|a|an example off|an instance off) " "(?P<Query2>.*)"), re.compile( ...
b>and) " "(?P<Query2>.*) (?P<QuestionWord>in common)"), re.compile( ".*(?P<QuestionWord>talk|rant|think) " "(?P<QuestionVerb>\w+) (?P<Query>.*)"), re.compile( ".*(?P<QuestionWord>who|what|when|where|why|which|how|example|examples) "...
mverzett/rootpy
rootpy/extern/hep/pdg.py
Python
gpl-3.0
31,391
0.00051
# # $Id: PDG.py,v 1.5 2009-01-26 03:05:43 ssnyder Exp $ # File: PDG.py # Created: sss, Mar 2005 # Purpose: Define PDG ID codes. # """ This module contains names for the various PDG particle
ID codes. The names are the same as in EventKernel/PdtPdg.h. This module also contains a dictionary
pdgid_names mapping ID codes back to printable strings, and a function pdgid_to_name to do this conversion. Similarly, root_names and pdgid_to_root_name translate to strings with root markup. """ from __future__ import absolute_import from ROOT import TDatabasePDG from pkg_resources import resource_filename import o...
theosotr/netxanal
mvc/controller/visualization.py
Python
apache-2.0
21,545
0.001439
""" This module contains classes for data and graph visualization. For that purpose, there are classes for the creation of simple graph's images, images with path (critical, shortest, strongest) depiction and giving to a user the chance to customize images and the way nodes and edges are depicted. Apart from this, th...
:return Position of nodes. """ pos = nx.get_node_attributes(self.graph.graph, 'position') return pos def draw_edge_weights(self, pos): """ Draws edge weights. For undirected graphs, weight label is positioned at the center of edge. For directed
graphs, weight label is positioned at the side of target node. For example, is there is an edge between nodes A and B as the following A --> B with weight C, label C is going to be depicted at the side of node B. :param pos Position of nodes. """ if self.graph.graphtype...
TeamODrKnow/doctor-know
haigha/frames/frame.py
Python
mit
4,107
0.000243
''' Copyright (c) 2011-2014, Agora Games, LLC All rights reserved. https://github.com/agoragames/haigha/blob/master/LICENSE.txt ''' import struct import sys from collections import deque from haigha.reader import Reader class Frame(object): ''' Base class for a frame. ''' # Exceptions class Fr...
se MissingFooter if there's a problem reading the footer byte. ''' frame_type = reader.read_octet() channel_id = reader.read_short() size = reader.read_long() payload = Reader(reader, reader.tell(), size) # Seek to end of paylo
ad reader.seek(size, 1) ch = reader.read_octet() # footer if ch != 0xce: raise Frame.FormatError( 'Framing error, unexpected byte: %x. frame type %x. channel %d, payload size %d', ch, frame_type, channel_id, size) frame_class = cls._frame_t...
pretsell/PokemonGo-Map
pogom/app.py
Python
agpl-3.0
19,025
0.002628
#!/usr/bin/python # -*- coding: utf-8 -*- import calendar import logging from flask import Flask, abort, jsonify, render_template, request from flask.json import JSONEncoder from flask_compress import Compress from datetime import datetime from s2sphere import LatLng from pogom.utils import get_args from datetime imp...
_control(self, control): self.search_control = control def set_heartbeat_control(self, heartb): self.heartbeat = heartb def set_location_queue(self, queue): self.location_queue = queue def set_current
_location(self, location): self.current_location = location def get_search_control(self): return jsonify({'status': not self.search_control.is_set()}) def post_search_control(self): args = get_args() if not args.search_control or args.on_demand_timeout > 0: return '...
OscaRoa/api-cats
cats/urls.py
Python
mit
475
0
from django.conf.urls import url from cats.views.cat import ( CatList, CatDetail ) from cats.views.breed import ( BreedList, Bree
dDetail ) urlpatterns = [ # Cats URL's url(r'^cats/$', CatList.as_view(), name='list'), url(r'^cats/(?P<pk>\d+)/$', CatDetail.as_view(), name='detail'),
# Breeds URL's url(r'^breeds/$', BreedList.as_view(), name='list_breeds'), url(r'^breeds/(?P<pk>\d+)/$', BreedDetail.as_view(), name='detail_breed'), ]
adobe-flash/avmplus
build/buildbot/slaves/android/scripts/shell-client-android.py
Python
mpl-2.0
1,874
0.026147
#!/usr/bin/env python # -*- python -*- # ex: set syntax=python: # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import sys,socket,os,time,re port=None host=None if ...
ellserver=',sys.argv[1]): shellserver=sys.argv[1][14:] if shellserver.find(':')>-1: host
=shellserver[0:shellserver.find(':')] try: port=int(shellserver[shellserver.find(':')+1:]) except: True sys.argv=sys.argv[1:] if (host==None or port==None): print("error: SHELLPORT and SHELLSERVER must be set") sys.exit(1) args="" for item in sys.argv[1:]: a...
samueljackson92/major-project
src/tests/regression_tests/intensity_regression_test.py
Python
mit
780
0
import unittest import pandas as pd import nose.tools from mia.features.blobs import detect_blobs from mia.features.intensity import detect_intensity from mia.utils import preprocess_image from ..test_utils import get_file_path class IntensityTests(unittest.TestCase): @classmethod def setupClass(cls): ...
g, blobs) # # nose.tools.assert_true(isinstance(intensity, pd.DataFrame)) # nose.tools.assert_equal(intensi
ty.shape[1], 10)
idea4bsd/idea4bsd
python/testData/psi/NotClosedBraceSet.py
Python
apache-2.0
10
0.2
a =
{'b',
]
xc0ut/PokeAlarm
PokeAlarm/Utils.py
Python
agpl-3.0
11,971
0.00259
# Standard Library Imports import configargparse from datetime import datetime, timedelta from glob import glob import json import logging from math import radians, sin, cos, atan2, sqrt, degrees import os import sys import re # 3rd Party Imports # Local Imports from . import config log = logging.getLogger('Utils') ...
module with pip def pip_install(module, version): import subprocess target = "{}=={}".format(module, version) log.info("Attempting to pip install %s..." % target) subprocess.call(['pip', 'install', target]) log.info("%s install com
plete." % target) # Used to exit when leftover parameters are founds def reject_leftover_parameters(dict_, location): if len(dict_) > 0: log.error("Unknown parameters at {}: ".format(location)) log.error(dict_.keys()) log.error("Please consult the PokeAlarm documentation for accepted param...
lycantropos/cetus
cetus/data_access/connectors.py
Python
mit
5,800
0
from asyncio import AbstractEventLoop import aiomysql.sa import asyncpg from asyncio_extras import async_contextmanager from cetus.types import (ConnectionType, MySQLConnectionType, PostgresConnectionType) from sqlalchemy.engine.url import URL DEFAULT_MYSQL_PORT = 330...
out: float = DEFAULT_CONNECTION_TIMEOUT, loop: AbstractEventLoop): # `None` port causes exceptions port = db_uri.port or DEFAULT_MYSQL_PORT # we use engine-based connection # instead of plain connection # because `aiomysql` has transactions API # only for engine-based connections asy...
user=db_uri.username, password=db_uri.password, db=db_uri.database, charset='utf8', connect_timeout=timeout, # TODO: check if `asyncpg` connections # are autocommit by default autocommit=True, minsize=1, ...
HybridF5/tempest_debug
tempest/api/orchestration/stacks/test_templates_negative.py
Python
apache-2.0
1,954
0
# Copyright 2014 NEC Corporation. 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 t
he License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required 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 th...
nd limitations # under the License. from tempest.api.orchestration import base from tempest.lib import exceptions as lib_exc from tempest import test class TemplateYAMLNegativeTestJSON(base.BaseOrchestrationTest): template = """ HeatTemplateFormatVersion: '2012-12-12' Description: | Template which creates o...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/t/too/too_many_branches.py
Python
mit
1,099
0.00273
""" Test for too many branches. """ # pylint: disable=using-constant-test def wrong(): # [too-many-branches] """ Has too many branches. """ if 1: pass elif 1: pass elif 1: pass elif 1: pass elif 1: pass elif 1: pass try: ...
pass elif 4: pass nested_1() try:
pass finally: pass try: pass finally: pass if 1: pass elif 2: pass elif 3: pass elif 4: pass elif 5: pass elif 6: pass elif 7: pass
marscher/bhmm
bhmm/hidden/impl_c/__init__.py
Python
lgpl-3.0
59
0.016949
__author__ = 'noe' from
bhmm.hidden.impl_c.hi
dden import *
lucadealfaro/crowdranker
controllers/feedback.py
Python
bsd-3-clause
10,966
0.005471
# -*- coding: utf-8 -*- import access import util @auth.requires_login() def index(): """Produces a list of the feedback obtained for a given venue, or for all venues.""" venue_id = request.args(0) if venue_id == 'all': q = (db.submission.user == get_user_email()) else: q = ((db.su...
""" if len(request.args) == 0: redirect(URL('default', 'index')) if request.args(0) == 's': # submission_id n_args = 2 subm = db.submission(request.args(1)) or redirect(URL('default', 'index')) c = db.venue(subm.venue_id) or redirect(URL('default', 'index')) ...
id n_args = 2 c = db.venue(request.args(1)) or redirect(URL('default', 'index')) username = get_user_email() subm = db((db.submission.user == username) & (db.submission.venue_id == c.id)).select().first() else: # venue_id, username n_args = 3 c = db.venue(requ...
AntonKhorev/spb-budget-db
3-db/testFileLists.py
Python
bsd-2-clause
1,567
0.051053
#!/usr/bin/env python3 import unittest import fileLists class TestFileLists(unittest.TestCase): def testOneEntry(self): l=fileLists.listTableFiles([ '2014.3765.1.1.department.diff.csv', ]) self.assertEqual(len(l),1) t=l[0] self.assertEqual(t.stageYear,2014) self.assertEqual(t.documentNumber,3765) s...
action,fileLists.SetAction) self.assertEqual(l[0].action.fiscalYears,{2015,2016}) def testDiffset(self): l=fileLists.listTableFiles([ '2014.3765.1.1.department.diffset(1234,2015,2016).csv', ]) self.assertEqual(len(l),1) self.assertIsInstance(l[0].action,fileLists.DiffsetAction) self.assertEqual(l[0].act...
assertEqual(l[0].action.fiscalYears,{2015,2016}) if __name__=='__main__': unittest.main()
autotest/virt-test
tools/github/github_issues.py
Python
gpl-2.0
29,542
0.000609
""" Classes to cache and read specific items from github issues in a uniform way """ from functools import partial as Partial import datetime import time import shelve # Requires PyGithub version >= 1.13 for access to raw_data attribute import github # Needed to not confuse cached 'None' objects class Nothing(object...
'with args=%s and dargs=%s' % (self.fetch.func, self.fetch.args, self.fetch.keywords)) else: raise if fetched_obj is None:
fetched_obj = Nothing() klass = fetched_obj.__class__ # github.PaginatedList.PaginatedList need special handling if isinstance(fetched_obj, github.PaginatedList.PaginatedList): raw_data = [item.raw_data for item in fetched_obj] inside_klass = fetched_obj[0].__cla...
davjohnst/fundamentals
fundamentals/backtracking/all_permutations.py
Python
apache-2.0
772
0.001295
#!/usr/bin/env python class AllPermutations(object): def __init__(self, arr)
: self.arr = arr def all_permutations(self): results = [] used = [] self._all_permutations(self.arr, used, results) return re
sults def _all_permutations(self, to_use, used, results): if len(to_use) == 0: results.append(used) for i, x in enumerate(to_use): new_used = used + [x] new_to_use = to_use[:i] + to_use[i+1:] self._all_permutations(new_to_use, new_used, results) de...
kkaarreell/ci-dnf-stack
dnf-behave-tests/features/steps/repo.py
Python
gpl-3.0
3,594
0.004174
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function import behave import os import parse from common import * @behave.step("I use the repository \"{repo}\"") def step_repo_condition(context, repo): if "repos" not in context.dnf: context.dnf["repos"] = []...
'certificates/testcerts/ca/cert.pem') cert = os.path.join(context.dnf.fixturesdir,
'certificates/testcerts/server/cert.pem') key = os.path.join(context.dnf.fixturesdir, 'certificates/testcerts/server/key.pem') client_ssl = context.dnf._get(context, "client_ssl") if client_ssl: client_cert = client_ssl["certifi...
MarxMustermann/OfMiceAndMechs
src/itemFolder/military/shocker.py
Python
gpl-3.0
1,603
0.004991
import src import random class Shocker(src.items.Item): """ ingame item used as ressource to build bombs and stuff should have the habit to explode at inconvienent times """ type = "Shocker" def __init__(self): """ set up internal state """ super().__init__(di...
haracter.addMessage("this room is fully charged")
else: character.addMessage("this room can't be charged") else: character.addMessage("no room found") else: character.addMessage("no crystal compressor found in inventory") src.items.addType(Shocker)
LucidWorks/fusion-seed-app
pipelines.py
Python
mit
151
0.039735
#!/usr/bin/python impor
t sys #what is the command command = sys.argv[1]; source = sys.argv[2]; print "Command: ", command; print "Source: ", sourc
e;
PKRoma/python-for-android
pythonforandroid/recipes/six/__init__.py
Python
mit
236
0
from pythonforandroid.recipe import PythonRecipe class SixRecipe(PythonRecipe): version = '1.15.0' url =
'htt
ps://pypi.python.org/packages/source/s/six/six-{version}.tar.gz' depends = ['setuptools'] recipe = SixRecipe()
joostrijneveld/eetvoudig
meals/migrations/0002_auto_20161006_1640.py
Python
cc0-1.0
576
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrati
ons class Migration(migrations.Migration): dependencies = [ ('meals', '0001_initial'), ] operations = [ migrations.AlterField( model_name='wbw_list', name='list_id', field=models.CharF
ield(max_length=40, unique=True), ), migrations.AlterField( model_name='participant', name='wbw_id', field=models.CharField(max_length=40, unique=True), ), ]
mozilla/zamboni
mkt/purchase/management/commands/post_bluevia_payment.py
Python
bsd-3-clause
2,183
0
import calendar from optparse import make_option import time from urllib import urlencode from
django.core.management.base import BaseCommand import jwt import requests class Command(BaseCommand): help = 'Simulate a BlueVia postback to mark a payment as complete.' option_list = BaseCommand.option_list + ( make_option('--trans-id', action='store', help='BlueVia transaction I...
etplace secret for signature verification'), make_option('--contrib', action='store', help='Contribution UUID'), make_option('--addon', action='store', help='ID of addon that was purchased'), make_option('--url', action='store', help='P...
beiko-lab/gengis
bin/Lib/site-packages/numpy/version.py
Python
gpl-3.0
238
0
# THIS FILE IS GENERAT
ED FROM NUMPY SETUP.PY short_version = '1.7.2' version = '1.7.2' full_version = '1.7.2' git_revision = 'f3ee0735c1c372dfb9e0efcaa6846bd05e53b836' release = True if not release:
version = full_version
paulharter/fam
src/fam/tests/test_couchdb/test_mapping.py
Python
mit
535
0.011215
import unittest from fam.tests.models.test01 import Dog, Cat, Person, JackRussell, Monarch from fam.mapper import Class
Mapper class MapperTests(unittest.TestCase): def setUp(self): self.mapper = ClassMapper([Dog, Cat, Person, JackRussell, Monarch]) def tearDown(self):
pass def test_sub_class_refs(self): self.assertEqual(set(Monarch.fields.keys()), set(["name", "country", "cats", "dogs", "animals", "callbacks"])) self.assertEqual(set(Monarch.cls_fields.keys()), {"country"})
ria-ee/X-Road
src/systemtest/op-monitoring/integration/testcases/test_zero_buffer_size.py
Python
mit
5,787
0.003283
#!/usr/bin/env python3 # The MIT License # Copyright (c) 2016 Estonian Information System Authority (RIA), Pop
ulation Register Centre (VRK) # # 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 without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute...
ht 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 PARTICULAR PURPOSE AND NONINFRINGEMENT...
jhakonen/wot-teamspeak-mod
test/fute/test_helpers/constants.py
Python
lgpl-2.1
199
0.040201
PLUGIN_INFO = { "versions": [ { "plugin_version": 1, "supported_mod_versions": ["0.6"], "download_url": "https://www.myteamspeak.com/addons/01a0f828-894c-45b7-a85
2-937b4
7ceb1ed" } ] }
allembedded/python_web_framework
WebApplication/Controllers/ControllerMain.py
Python
gpl-3.0
630
0.007937
""" Main controller. """ import json from Server.Importer import ImportFromModule class ControllerMain(ImportFromModu
le("Server.ControllerBase", "ControllerBase")): """ Main controller. """ def ShowPage(self, uriParameters, p
ostedParameters): """ Shows the home page. """ webPage = ImportFromModule("WebApplication.Views.PageView", "PageView")("Main") self.SetOutput(webPage.GetContent()) def EchoText(self, uriParameters, postedParameters): """ Echo the incomming text. """...
techlover10/StochasticSoundscape
src/audio.py
Python
mit
1,411
0.007092
#!/usr/bin/python3 # # Copyright © 2017 jared <jared@jared-devstation> # from pydub import AudioSegment, scipy_effects, effects import os import settings, util # combine two audio samples with a crossfade def combine_samples(acc, file2, CROSSFADE_DUR=100): util.debug_print('combining ' + file2) sample2 = Audi...
ade=CROSSFADE_DUR) return output # split an audio file into low, mid, high bands def split_file(fname): curr_file = AudioSegment.from_file(fname) low_seg = scipy_effects.low_pass_filter(cu
rr_file, settings.LOW_FREQUENCY_LIM).export(fname + '_low.wav', 'wav') mid_seg = scipy_effects.band_pass_filter(curr_file, settings.LOW_FREQUENCY_LIM, settings.HIGH_FREQUENCY_LIM).export(fname + '_mid.wav', 'wav') high_seg = scipy_effects.high_pass_filter(curr_file, settings.HIGH_FREQUENCY_LIM).export(fname + '...
cloudbase/nova-virtualbox
nova/api/openstack/compute/plugins/v3/keypairs.py
Python
apache-2.0
7,665
0.000261
# Copyright 2011 OpenStack Foundation # 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 requ...
t = req.environ['nova.context'] if 'servers' in resp_obj.obj and soft_authorize(context): servers = resp_obj.obj['servers'] self._add_key_name(req, servers) class Keypairs(extensions.V3APIExtensionBase): """Keypair Support.""" name = "Keypairs" alias = ALIAS version = ...
eturn resources def get_controller_extensions(self): controller = Controller() extension = extensions.ControllerExtension(self, 'servers', controller) return [extension] # use nova.api.extensions.server.extensions entry point to modify # server create kwargs # NOTE(gmann): This...
carlmod/Analys24h
a24tim/tests/test_models.py
Python
agpl-3.0
7,591
0.001188
# -*- coding: utf-8 -*- """ a24tim.tests.test_models ************************ The model tests for the a24tim app. :copyright: (c) 2012 by Carl Modén :licence: AGPL3, see LICENSE for more details. """ from datetime import date import math import urllib2 from django.test import TestCase import a24...
_protocol(self): """If the protocol is updated a status 203 will be sent.""" self.mock_urlopen.return_value.code = 203 forecast = self.allegro.forecast() self.assertIsNotNone(forecast[0]) def test_forcast_is
_rendered(self): """Sees that a parsable prognosis is rendered""" forecast = self.allegro.forecast() # Check some sample values self.assertEqual(forecast[1]['wind_direction'], 'NE') self.assertEqual(str(forecast[1]['pressure']), str(1012.4)) def test_forcast_is_not_xml(self)...
bonnieblueag/farm_log
core/urls.py
Python
gpl-3.0
158
0.006329
from django.conf.urls import url from core.
views import add_feedback urlpatterns = [ u
rl('^add/core/feedback', name='add_feedback', view=add_feedback), ]
rahulpalamuttam/weld
examples/python/nditer/nditer_test.py
Python
bsd-3-clause
3,542
0.006494
import weldnumpy as wn import numpy as np def assert_correct(np_a, z): ''' common part of the check. ''' shape = [] for s in z.shape: shape.append(s) shape = tuple(shape) np_a = np.reshape(np_a, shape) for i in range((z.shape[0])): for j in range(z.shape[1]): ...
r({arr}, {start}L, {end}L, 1L, {shapes}, {strides}), appender, \ |b, i, e| merge(b,exp(e))))'.format(shapes=shapes, strides=strides, end=str(end), start=str(start), arr=orig.name) orig.weldobj.weld_code = iter_code np_a = orig._eval() assert_correct(np_a, z) def test_zip():
''' Has a different start from the base array. ''' orig = np.random.rand(20,20) orig2 = np.random.rand(20,20) a = orig[5:20:1,3:20:2] b = orig2[5:20:1,3:20:2] start = (wn.addr(a) - wn.addr(orig)) / a.itemsize orig = wn.array(orig) # copying so we can test them later. z = np....
andrebellafronte/stoq
stoq/gui/calendar.py
Python
gpl-2.0
17,713
0.000847
# -*- Mode: Python; coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2011 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## This program 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 Sof...
-calls'] = self._show_events['client_calls'] events['client-birthdays'] = self._show_events['client_birthdays'] events['work-orders'] = self._show_events['work_orders'] def _up
date_calendar_size(self, width, height): self._calendar_run('option', 'aspectRatio', float(width) / height) def _update_title(self): # Workaround to get the current calendar date view = self.get_view() view.execute_script("document.title = $('.fc-header-title').text()") titl...
vprusso/us_patent_scraper
patent_spider/patent_spider/models.py
Python
gpl-2.0
80
0.0125
# -*- coding: utf-8 -*
- """Models for database connection""" import
settings
AunShiLord/Tensor-analysis
tensor_analysis/tests/test_tensor_fields.py
Python
mit
17,326
0.006065
# -*- coding: utf-8 -*- from sympy.matrices import Matrix from tensor_analysis.arraypy import Arraypy, TensorArray, list2arraypy, list2tensor from tensor_analysis.tensor_fields import df, grad, curl, diverg, lie_xy, dw, \ lie_w, inner_product, g_tensor, g_wedge from sympy import symbols, cos, sin def test_df_var...
assert grad(f, var1, b, 'a') == res_ar assert isinstance(grad(f, var1, b, 'a'), Arraypy) assert grad(f, k1, output_type='a') == res_ar1 assert isinstance(grad(f, k1, output_type='a'), Arraypy) assert grad(f, var1, b, 't') == res_ten assert isinstance(grad(f, var1, b, 't'), TensorArray) as...
assert grad(f, var1, b) == res_ten assert isinstance(grad(f, var1, b, 't'), TensorArray) assert grad(f, var1, b, 't').type_pq == (1, 0) def test_grad_gm_vl(): x1, x2, x3 = symbols('x1 x2 x3') f = x1**2 * x2 + sin(x2 * x3 - x2) var1 = [x1, x2, x3] g = Matrix([[2, 1, 0], [1, 3, 0], [0, 0, 1]...
peap/djarzeit
djarzeit/wsgi.py
Python
mit
1,425
0.000702
""" WSGI config for djarzeit 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`` setting. Usually you will
have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import...
DavidLutton/EngineeringProject
labtoolkit/SignalGenerator/AgilentN5182A.py
Python
mit
417
0
from .SCPISignalGenerator imp
ort SCPISignalGenerator from .helper import SignalGenerator, amplitudelimiter class AgilentN5182A(SCPISignalGenerator, SignalGenerator): """Agilent N5182A 100e3, 6e9. .. figure:: images/SignalGenerator/AgilentN5182A.jpg """ def __init__(self, inst): super().__init__(inst) self.inst....
self.inst.write_termination = '\n'
nikhilpanicker/SecureVault
tools/modified/androguard/core/binaries/idapipe.py
Python
gpl-3.0
6,602
0.010906
# This file is part of Androguard. # # Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr> # 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...
ENSE-2.0 # # Unless required 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. from subprocess import Popen, PIPE, STDOUT import os, sys import xmlrpclib import cPickle class _Method(object): def __init__(self, proxy, name): self.proxy = proxy self.name = name def __call__(self, *args): #print "CALL", self.name, args z = getattr( self.proxy, s...
elin-moco/ffclub
ffclub/person/migrations/0005_auto__add_field_person_education__add_field_person_birthday.py
Python
bsd-3-clause
5,302
0.007922
# -*- 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 'P
erson.education' db.add_column('person_person', 'education', self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True), keep_default=False) # Adding field 'Person.birthday' db.add_column('person_person', 'birthday', ...
# Deleting field 'Person.education' db.delete_column('person_person', 'education') # Deleting field 'Person.birthday' db.delete_column('person_person', 'birthday') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.model...
rickyrish/rickyblog
build/lib.linux-i686-2.7/publicaciones/urls.py
Python
gpl-2.0
226
0.00885
from django.conf.urls impor
t patterns, url from publicaciones import views urlpatterns = patterns('', url(r'^$', views.index, name='index'),
url(r'^(?P<articulo_id>\d+)/$', views.ver_articulo, name='ver_articulo'), )
calpaterson/recall
src/recall/people.py
Python
agpl-3.0
3,665
0.00191
# Recall is a program for storing bookmarks of different things # Copyright (C) 2012 Cal Paterson # # This program 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 License, or # ...
"email", "firstName", "pseudonym" ]) except TypeError: logger.warn("Asked about {email}, but that is not a user".format( email=who)) abort(404, "User not found") @app.get("/<who>/self") def _self(who, user): if who != user["email"]...
"pseudonym", "firstName", "surname", "email", "private_email"]) @app.post("/<who>/") def request_invite(who): # FIXME: Don't allow the pseudonym "public" user = whitelist(request.json...
apagac/cfme_tests
sprout/appliances/migrations/0008_appliance_uuid.py
Python
gpl-2.0
493
0.002028
# -*- coding: utf-8 -*- from django.db import models, migrations class Migration(migrations.Migration): dependencies = [
('appliances', '0007_provider_num_simultaneous_configuring'), ] operations = [ migrations.AddField( model_name='appliance', name='uuid', field=models.CharField( help_text=b'UUID of the machine', max_length=36, null=True, blank=True
), preserve_default=True, ), ]
yasharmaster/scancode-toolkit
src/packagedcode/phpcomposer.py
Python
apache-2.0
11,144
0.001884
# # Copyright (c) 2015 nexB Inc. and others. All rights reserved. # http://nexb.com and https://github.com/nexB/scancode-toolkit/ # The ScanCode software is licensed under the Apache License version 2.0. # Data generated with ScanCode require an acknowledgment. # ScanCode is a trademark of nexB Inc. # # You may not use...
odels.AssertedLicense(license=licenses)) elif isinstance(licenses, list): """ "license": [ "LGPL-2.1",
"GPL-3.0+" ] """ for lic in licenses: if isinstance(lic, basestring): package.asserted_licenses.append(models.AssertedLicense(license=lic)) else: # use the bare repr if lic: package.asserted_licenses...
317070/kaggle-heart
configurations/je_ss_smcrps_nrmsc_dropoutput.py
Python
mit
8,198
0.009758
"""Single slice vgg with normalised scale. """ import functools import lasagne as nn import numpy as np import theano import theano.tensor as T import data_loader import deep_learning_layers import layers import preprocess import postprocess import objectives import theano_printer import updates # Random params rng ...
linearities.rectify) l5b = nn.layers.dnn.Conv2DDNNLayer(l5a, W=nn.init.Orthogonal("relu"), filter_size=(3,3), num_filters=512, stride=(1,1), pad="same", nonlinearity=nn.nonlinearities.rectify
) l5c = nn.layers.dnn.Conv2DDNNLayer(l5b, W=nn.init.Orthogonal("relu"), filter_size=(3,3), num_filters=512, stride=(1,1), pad="same", nonlinearity=nn.nonlinearities.rectify) l5 = nn.layers.dnn.MaxPool2DDNNLayer(l5c, pool_size=(2,2), stride=(2,2)) # Systole Dense layers ldsys1 = nn.layers.DenseLayer(l5,...
Geekly/framepy
pump.py
Python
gpl-2.0
68
0.014706
__author__ = 'ENG-5 USER' from numpy import * import nu
mpy as
np
richardingham/octopus
octopus/blocktopus/blocks/logic.py
Python
mit
2,889
0.039114
from ..workspace import Block from twisted.internet import defer from .variables import lexical_variable import operator class logic_null (Block): def eval (self): return defer.succeed(None) class logic_boolean (Block): def eval (self): return defer.succeed(self.fields['BOOL'] == 'TRUE') class logic_negate...
result == False self._complete = self.getInputValue('BOOL').addCallback(negate) return self._comple
te _operators_map = { "EQ": operator.eq, "NEQ": operator.ne, "LT": operator.lt, "LTE": operator.le, "GT": operator.gt, "GTE": operator.ge } def _compare (lhs, rhs, op_id): if lhs is None or rhs is None: return None op = _operators_map[op_id] return op(lhs, rhs) # Emit a warning if bad op given class l...
kenorb-contrib/BitTorrent
twisted/web/_version.py
Python
gpl-3.0
175
0
# This is an auto-generated file. Use admin/chang
e-versions to update. from twisted.python import versions version = versions.Version(__name__[:__name__.rfind(
'.')], 0, 6, 0)
ramwin1/environment_spider
weather/getCountryList.py
Python
gpl-2.0
1,285
0.012451
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'wangx' import urllib2 from bs4 import BeautifulSoup import getProvinceList provinceList = getProvinceList.main() global coun coun=[] def get(net): result = [] try: html = urllib2.urlopen(net,timeout=10).read() except: html='' ...
rint len(temp) for i in temp: city = i.td.text j = i.find_all('tr')
for k in j: result.append((city,k.a.text,k.a.get('href'))) coun.append(k.a.text) return result def gettotal(): totalCountryList = [] for i in provinceList.keys(): net = provinceList[i] temp = get(net) for j in temp: row = (i,)+j ...
bslatkin/8-bits
appengine-mapreduce/python/test/mapreduce/output_writers_end_to_end_test.py
Python
apache-2.0
7,023
0.004129
#!/usr/bin/env python # # Copyright 2011 Google Inc. All Rights Reserved. import unittest from google.appengine.api import files from google.appengine.ext import db from mapreduce import control from mapreduce import model from mapreduce import output_writers from mapreduce import test_support from testlib impor...
l_empty(self.taskqueue) mapreduce_state = model.MapreduceState.get_by_job_id(mapreduce_id) filenames = output_writers.BlobstoreOutputWriter.get_filenames( mapreduce_state) self.assertEqual(4, len(filenames)) file_lengths = [] for filename in filenames: s
elf.assertTrue(filename.startswith("/blobstore/")) self.assertFalse(filename.startswith("/blobstore/writable:")) with files.open(filename, "r") as f: data = f.read(10000000) file_lengths.append(len(data.strip().split("\n"))) # these numbers are totally random and depend on our sharding...
buxx/synergine
tests/src/event/test_actions.py
Python
apache-2.0
337
0.026706
from synergine.synergy.event.Action import Action class A(Action): _depend = [] class B(Action): _depend = [A] class C(Action): _depend = [B] class D(Action): _depend = [] class F(Action): _depend = [C] class E(Action): _depend = [B, F] class G(
Action): _depend =
[] class H(Action): _depend = [B]
tiregram/algo-E3FI
tp4/exo1.py
Python
gpl-3.0
1,042
0.028791
import fifo import random import time def insertion_sort(elemToTry): tab = [] for a in elemToTry: tab.append(a); place(tab , len(tab)-1) return tab def invertPlace(tableau,indiceOne,indiceTwo): tableau[indiceTwo], tableau[indiceOne] = tableau[indiceOne],tableau[indiceTw...
tSort(table, index = lambda a : a>>6): tab = [None] for a in table: if len(tab)-1 < index(a): tab = tab + [None] * (index(a) - len(tab)+1) if tab[index(a)] == None: tab[index(a)] = fifo.Deque(a) else: tab[index(a)].push_las...
n_sort(a) return tabret
npilon/planterbox
planterbox/util.py
Python
mit
236
0
def clean_dict_repr(mw): """Produce a repr()-like output o
f dict mw with ordered ke
ys""" return '{' + \ ', '.join('{k!r}: {v!r}'.format(k=k, v=v) for k, v in sorted(mw.items())) +\ '}'
kwilliams-mo/iris
lib/iris/fileformats/grib/grib_phenom_translation.py
Python
gpl-3.0
12,009
0.000167
# (C) British Crown Copyright 2013, Met Office # # This file is part of Iris. # # Iris 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 ve...
If not, see <http://www.gnu.org/licenses/>. ''' Provide grib 1 and 2 phenomenon translations to + from CF terms. This is done by wrapping '_grib_cf_map.py', which is in a format provided by the metadata translation p
roject. Currently supports only these ones: * grib1 --> cf * grib2 --> cf * cf --> grib2 ''' import collections import warnings import numpy as np from iris.fileformats.grib import _grib_cf_map as grcf import iris.std_names import iris.unit class LookupTable(dict): """ Specialised dictionary object for ...
purduerov/XX-Core
rov/movement/controls/PID_Tuner.py
Python
mit
174
0
#
Ill attempt to research and see the practicality of making a pid tuner # possib
ly hard coding and using error # or maybe using tensor flow # but just an idea at the moment
Galithil/genologics_sql
tests/test_default.py
Python
mit
308
0.019481
import genolo
gics_sql.utils from genologics_sql.tables import * def test_connection(): session=genologics_sql.utils.get_session() assert(session is not None) def test_project_query(): session=genologics_sql.utils.get_session() pj=session.query(Project).limit(1)
assert(pj is not None)
yoshiweb/keras-mnist
keras-mnist/mnist_cnn/mnist_cnn_train.py
Python
mit
2,369
0
'''Trains a simple convnet on the MNIST dataset. Gets to 99.25% test accuracy after 12 epochs (there is still a lot of margin for parameter tuning). 16 seconds per epoch on a GRID K520 GPU. ''' from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from...
yers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras import backend as K from keras.models import load_model batch_size = 128 num_classes = 10 epochs = 12 # input image dimensions img_rows, img_cols = 28, 28 # the data, shuffled and split between train and test sets (x_train, ...
f K.image_data_format() == 'channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_te...
Rhilip/PT-help-server
modules/infogen/__init__.py
Python
mit
1,231
0.000812
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Copyright (c) 2017-2020 Rhilip <rhilipruan@gmail.com> import time from flask import Blueprint, request, jsonify, redirect from app import cache from .gen import Gen getinfo_blueprint = Blueprint('infogen', __name__, url_prefix="/movieinfo") docs_url = "https://github.co...
, "POST"]) def gen(): url = get_key("url") if url is None: site = get_key('site')
sid = get_key('sid') if site is not None and sid is not None: url = {'site': site, 'sid': sid} if url: t0 = time.time() @cache.memoize(timeout=86400) def gen_data(uri): return Gen(url=uri).gen() nocache = get_key("nocache") if nocache:...
alxgu/ansible
lib/ansible/modules/cloud/azure/azure_rm_servicebusqueue.py
Python
gpl-3.0
12,400
0.002581
#!/usr/bin/python # # Copyright (c) 2018 Yuwei Zhou, <yuwzho@microsoft.com> # # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
g_on_message_expiration=dict(type='bool'), default_message_time_to_live_seconds=dict(type='int'), duplicate_detection_time_in_seconds=dict(type='int'), enable_batched_operations=dict(type
='bool'), enable_express=dict(type='bool'), enable_partitioning=dict(type='bool'), forward_dead_lettered_messages_to=dict(type='str'), forward_to=dict(type='str'), lock_duration_in_seconds=dict(type='int'), max_delivery_count=dict(type='int'), ...
partofthething/home-assistant
homeassistant/components/zha/core/const.py
Python
apache-2.0
10,279
0.000292
"""All constants related to the ZHA component.""" import enum import logging from typing import List import bellows.zigbee.application from zigpy.config import CONF_DEVICE_PATH # noqa: F401 # pylint: disable=unused-import import zigpy_cc.zigbee.application import zigpy_deconz.zigbee.application import zigpy_xbee.zigb...
ONFIG_MAX_INT_BATTERY_SAVE, REPORT_CONFIG_RPT_CHANGE, ) REPORT_CONFIG_IMMEDIATE = ( REPORT_CONFIG_MIN_INT_IMMEDIATE, REPORT_CONFIG_MAX_INT, REPORT_CONFIG_RPT_CHANGE, ) REPORT_CONFIG_OP = ( REPORT_CONFIG_MIN_INT_OP, REPORT_CONFIG_MAX_INT, REPORT_CONFIG_RPT_CHANGE, ) SENSOR_ACCELERATION = "ac...
" SENSOR_BATTERY = "battery" SENSOR_ELECTRICAL_MEASUREMENT = CHANNEL_ELECTRICAL_MEASUREMENT SENSOR_GENERIC = "generic" SENSOR_HUMIDITY = CHANNEL
all-of-us/raw-data-repository
rdr_service/lib_fhir/fhirclient_4_0_0/models/composition.py
Python
bsd-3-clause
13,565
0.007667
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Composition) on 2019-05-07. # 2019, SMART Health IT. from . import domainresource class Composition(domainresource.DomainResource): """ A set of resources composed into a single coher...
""" self.encounter = None """ Context of the Composition. Type `FHIRReference` (represented as `dict` in JSON). """ self.event = None """ The clinical service(s) being documented. List of `CompositionEvent` items (represented as `dict` in JSON). """ ...
self.relatesTo = None """ Relationships to other compositions/documents. List of `CompositionRelatesTo` items (represented as `dict` in JSON). """ self.section = None """ Composition is broken into sections. List of `CompositionSection` items (represented as `dict...
edwardbadboy/vdsm-ubuntu
tests/fileUtilTests.py
Python
gpl-2.0
8,296
0
# # Copyright 2012 Red Hat, Inc. # # This program 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 2 of the License, or # (at your option) any later version. # # This program is distributed in th...
ontes, ut taci
ti orci ridiculus facilisis nunc. Donec. Risus adipiscing habitant donec vehicula non vitae class, porta vitae senectus. Nascetur felis laoreet integer, tortor ligula. Pellentesque vestibulum cras nostra. Ut sollicitudin posuere, per accumsan curabitur id, nisi fermentum vel, eget netus ...
fishtown-analytics/dbt
core/dbt/contracts/graph/compiled.py
Python
apache-2.0
7,700
0
from dbt.contracts.graph.parsed import ( HasTestMetadata, ParsedNode, ParsedAnalysisNode, ParsedDataTestNode, ParsedHookNode, ParsedModelNode, ParsedResource, ParsedRPCNode, ParsedSchemaTestNode, ParsedSeedNode, ParsedSnapshotNode, ParsedSourceDefinition, SeedConfig, ...
aTestNode(CompiledNode):
resource_type: NodeType = field(metadata={'restrict': [NodeType.Test]}) config: TestConfig = field(default_factory=TestConfig) @dataclass class CompiledSchemaTestNode(CompiledNode, HasTestMetadata): resource_type: NodeType = field(metadata={'restrict': [NodeType.Test]}) column_name: Optional[str] = None ...
nathankrueger/ncmd
ncmd_server.py
Python
gpl-2.0
4,429
0.031836
#!/usr/bin/python import socket import os import time import shutil import sys import re import datetime import argparse # NCMD Libs import ncmd_print as np from ncmd_print import MessageLevel as MessageLevel import ncmd_commands as ncmds import ncmd_fileops as nfops MAX_TRANSFER_BYTES=2048 QUIT_CMD = "quit now" HOS...
Remove(ncmd): # The naming here isn't ideal, but this code gets the job done! for src in srcs: if not nfops.remove(src): cmd_success = False if not nfops.remove(dest): cmd_success = False return quit, cmd_success # Deal with the current connection, getting, sending, and closing def proc...
ds.MAX_CMD_SIZE) quit, cmd_success = processCmd(ncmd, args) resp = processResponse(ncmd, cmd_success) if len(resp) > 0: try: conn.send(resp) except Exception as err: np.print_msg(msg, MessageLevel.ERROR) conn.close() return quit def getArgs(): parser = argparse.ArgumentParser(description='Copy, move,...
chris-statzer/knuckle-python
game/game_state.py
Python
mit
339
0
i
mport knuckle class GameState(knuckle.State): def on_keyup(self, e): pass def on_keydown(se
lf, e): if e == 'Escape': self.window.pop_state() def on_draw(self): self.window.clear() self.batch.draw() self.window.flip() def __str__(self): return 'GameState()'
SheffieldML/GPyOpt
GPyOpt/core/task/cost.py
Python
bsd-3-clause
2,686
0.00484
# Copyright (c) 2016, the GPyOpt Authors # Licensed under the BSD 3-clause license (see LICENSE.txt) from ...models import GPModel import numpy as np class CostModel(object): """ Class to handle the cost of evaluating the function. param cost_withGradients: function that returns the cost of evaluating ...
l.model.Y,cost_evals)) self.num_updates += 1 self.cost_model.updateModel(X_all, costs_all, None, Non
e) def constant_cost_withGradients(x): """ Constant cost function used by default: cost = 1, d_cost = 0. """ return np.ones(x.shape[0])[:,None], np.zeros(x.shape)
firstflamingo/python_utilities
markup.py
Python
apache-2.0
13,400
0.007687
# coding=utf-8 # # Copyright (c) 2011-2015 First Flamingo Enterprise B.V. # # 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 requi...
save the imported objects. Must be overwritten in subclasses """ pass # ====== Generic HTML Classes ========================================================================================== class HTMLDocument(XMLDocument): def __init__(self, title, language='en', charset='UTF-8'): ...
ead = XMLElement('head') self.head.add(title_tag(title)) self.head.add(meta('charset', charset)) self.root.add(self.head) self.body = XMLElement('body') self.root.add(self.body) self.root.set_attribute('lang', language) def doctype(self): return '<!doctyp...
zegnus/self-driving-car-machine-learning
p13-final-project/ros/src/twist_controller/dbw_test.py
Python
mit
3,850
0.002857
#!/usr/bin/env python import os import csv import rospy from std_msgs.msg import Bool from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport ''' You can use this file to test your DBW code against a bag recorded with a reference implementation. The bag can be found at https://s3-us-west-1.a...
self.dbw_enabled = msg.data def steer_cb(self, msg): self.steer = msg.steering_wheel_angle_cmd def throttle_cb(self, msg): self.throt
tle = msg.pedal_cmd def brake_cb(self, msg): self.brake = msg.pedal_cmd def actual_steer_cb(self, msg): if self.dbw_enabled and self.steer is not None: self.steer_data.append({'actual': msg.steering_wheel_angle_cmd, 'proposed': self.steer}) ...
praekelt/jmbo-music
music/tests/__init__.py
Python
bsd-3-clause
3,379
0
from django.test import TestCase from django.conf import settings from django.contrib.sites.models import Site from django.db.models.query import QuerySet from preferences import preferences from music.models import TrackContributor, Credit, Track, Album, CreditOption from music.utils import wikipedia, lastfm class...
apers'] = ['wikipedia'] wikipedia(self.wikipedia_artist) wikipedia(self.wikipedia_album)
wikipedia(self.wikipedia_track) wikipedia(self.iartist) wikipedia(self.ialbum) wikipedia(self.itrack) self.failUnless(self.wikipedia_artist.image) self.failUnless(self.wikipedia_album.image) self.failUnless(self.wikipedia_track.image) self.failIf(self.iar...
Tomsod/gemrb
gemrb/GUIScripts/pst/MessageWindow.py
Python
gpl-2.0
3,926
0.033367
# -*-python-*- # GemRB - Infinity Engine Emulator # Copyright (C) 2003 The GemRB Project # # This program 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 2 # of the License, or (at your option) ...
en 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 this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # MessageWind...
ckan/ckanext-deadoralive
ckanext/deadoralive/tests/test_config.py
Python
agpl-3.0
572
0
import ckanext.deadoralive.config as config import c
kanext.deadoralive.tests.helpers as custom_helpers class TestConfig(custom_helpers.FunctionalTestBaseClass): def test_that_it_reads_settings_from_config_file(self): """Test that non-default config settings in the config file work.""" # These non-default settings are in the
test.ini config file. assert config.recheck_resources_after == 48 assert config.resend_pending_resources_after == 12 # TODO: Test falling back on defaults when there's nothing in the config # file.
SpeedMe/leihuang.org
config.py
Python
apache-2.0
665
0.022556
# -*- coding: utf-8 -*- import os basedir=os.path.abspath(os.path.dirname(__file__))#get basedir of the project WTF_CSRF_ENABLED = True SECRET_KEY = 'you-will-guess' #for database # SQLALCHEMY_DATABASE_URI = 'mysql:///' + os.path.join(basedir, 'app.db') SQLALCHEMY_DATABASE_URI = "mysql://username:password@server_ip:...
hould use basedir MAX_CONTENT_LENGTH=2*1024*1024 ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg
'])#TODO:make user aware #for upload excel UPLOAD_EXCEL = basedir+'/app/static/add_info/' #should use basedir
markdrago/banter
banter/banter.py
Python
mit
3,421
0.004969
from __future__ import print_function import readline import sys import argparse from . import crucible, config, config_ui, utils, patch def main(): parser = argparse.ArgumentParser(description='Create Code Reviews') parser.add_argument('--setup', action='store_true', help='setup banter configuration') p...
viewer_list = [r.strip() for r in reviewers.split(',')]
r = crucible_conn.add_reviewers(auth_token, review_id, reviewer_list) def setup(): conf = config.Config() conf.load_from_file() updated_conf = config_ui.get_config_from_user(conf.as_dict()) set_crucible_token(updated_conf) conf.set_from_dict(updated_conf) conf.save() def set_crucible_to...
nict-isp/uds-sdk
uds/data/check.py
Python
gpl-2.0
4,491
0.004035
# -*- coding: utf-8 -*- """ uds.data.check ~~~~~~~~~~~~~~
:copyright: Copyright (c) 2015, National Institute of Information and Communications Technology.All rights reserved. :license: GPL2, see LICENSE for more details. """ import re import datetime import dateutil
.parser import pytz import uds.logging from uds.data import M2MDataVisitor class M2MDataChecker(M2MDataVisitor): """M2MDataChecker check validity of M2M Data object. """ def __init__(self): pass def visit_v101(self, m2m_data): """Check v1.01 M2M Data. :param M2MDataV101 m2m...
chiesax/sandbox
sandbox/install_project/venv_inspect.py
Python
mit
1,009
0.003964
# -*- coding: utf-8 -*- """ Created by chiesa on 18.01.16 Copyright 2015 Alpes Lasers SA, Neuchatel, Switzerland """ import json import subprocess from tempfile import NamedTemporaryFile __author__ = 'chiesa' __copyright__ = "Copyright 2015, Alpes Lasers SA" def get_entry_points(venv_python_path, project_name): ...
False) f.write('import pkg_resources\n') f.write('import json\n\n') f.write('print json.dumps(pkg_resources.get_entry_map(\'{0}\').get(\'console_scripts\', {{
}}).keys())\n'.format(project_name)) f.close() return json.loads(subprocess.check_output([venv_python_path, f.name])) def get_project_version(venv_python_path, project_name): f = NamedTemporaryFile(delete=False) f.write('import pkg_resources\n') f.write('import json\n\n') f.write('print json.d...
cozy/python_cozy_management
cozy_management/helpers.py
Python
lgpl-3.0
2,238
0.000447
''' Some helpers ''' import os import pwd import time import requests import subprocess def get_uid(username): return int(pwd.getpwnam(username).pw_uid) def file_rights(filepath, mode=None, uid=None, gid=None): ''' Change file rights ''' file_handle = os.open(filepath, os.O_RDONLY) ...
http://127.0.0.1:9101/', 'Cozy data sytem OK', interval) def wait_cozy_home(interval=10): wait_http('http://127.0.0.1:9103/', 'Cozy home OK', interval) def wait_cozy_proxy(interval=10): wait_http('http://127.0.0.1:9104/', 'Cozy proxy
OK', interval) def wait_cozy_stack(interval=10): wait_couchdb(interval) wait_cozy_controller(interval) wait_cozy_datasytem(interval) wait_cozy_home(interval) wait_cozy_proxy(interval)
compstak/selenium
py/selenium/webdriver/remote/command.py
Python
apache-2.0
5,188
0.000771
# Copyright 2010 WebDriver committers # Copyright 2010 Google 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 ap...
ource" GET_TITLE = "getTitle" EXECUTE_SCRIPT = "executeScript" SET_BROWSER_VISIBLE = "setBrowserVisible" IS_BROWSER_VISIBLE = "isBrowserVisible" GET_ELEMENT_TEXT = "getElementText" GET_ELEMENT_VALUE = "getElementValue" GET_ELEMENT_TAG_NAME = "getElementTagName" SET_ELEMENT_SELECTED = "se...
d" GET_ELEMENT_LOCATION = "getElementLocation" GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW = "getElementLocationOnceScrolledIntoView" GET_ELEMENT_SIZE = "getElementSize" GET_ELEMENT_ATTRIBUTE = "getElementAttribute" GET_ELEMENT_VALUE_OF_CSS_PROPERTY = "getElementValueOfCssProperty" ELEMENT_EQUA...
rdkit/rdkit
Code/GraphMol/Descriptors/test3D_old.py
Python
bsd-3-clause
3,537
0.035341
from rdkit import Chem from rdkit import rdBase from rdkit.Chem import rdMolDescriptors as rdMD from rdkit.Chem import AllChem from rdkit.Chem.EState import EStateIndices from rdkit.Chem.EState import AtomTypes import time print rdBase.rdkitVersion print rdBase.boostVersion def getEState(mol): return EStat...
tSMWHIM.txt', 'w') writer = Chem.SDWriter('3Dsmallmol.sdf') A=['[H][H]','B','O=O','C','CC','CCC','CCCC','CCCCC','CCCCCC','CO','CCO','CCCO','CCCCO','CCCCCO','CCCCCCO','CCl','CCCl','CCCCl','CCCCCl','CCCCCCl','CCCCCCCl','CBr','CCBr','CCCBr','CCCCBr','CCCCCBr','CCCCCCBr','CI','CCI','CCCI','CCCCI','CCCCCI','CCCCCCI','CF','C...
.MolFromSmiles(smi) m=localopt(m,100) #r=get3D(m,True) print smi print "---------" r=rdMD.CalcWHIM(m) print "Ei:"+str(r[0])+ "," + str(r[1]) + "," + str(r[2])+ "\n" print "Gi:"+str(r[5])+ "," + str(r[6]) + "," + str(r[7])+ "\n" print "SI:"+str(rdMD.CalcSpherocityIndex(m)) print "AS:"...