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
Eric89GXL/vispy
examples/basics/plotting/grid_x_y_viewbox.py
Python
bsd-3-clause
1,194
0
# -*- coding: utf-8 -*- # vispy: gallery 2 # ----------------------------------------------------------------------------- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ------------------------------------------------------------...
| | | | +----+-------------+ | sp | x | +----+-------------+ """ import sys from vispy import scene, app canvas = scene.SceneCanvas(keys='interactive') canvas.size = 600, 600 canvas.show() grid = canvas.central_widget.add_grid() widget_y_axis = grid.add_widget(row=0, col=0) widget_y_axi...
_spacer_bottom = grid.add_widget(row=1, col=0) widget_spacer_bottom.bgcolor = "#efefef" widget_x_axis = grid.add_widget(row=1, col=1) widget_x_axis.bgcolor = "#0000dd" widget_y_axis.width_min = 50 widget_y_axis.width_max = 50 widget_x_axis.height_min = 50 widget_x_axis.height_max = 50 if __name__ == '__main__' and s...
wallnerryan/quantum_migrate
quantum/tests/unit/test_l3_plugin.py
Python
apache-2.0
80,012
0.000087
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Nicira Networks, 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.apac...
st')] config.parse(args=args) # Update the plugin and extensions path cfg.CONF.set_override('core_plugin', plugin) cfg.CONF.set_override('allow_pagination', True) cfg.CONF.
set_override('allow_sorting', True) self._plugin_patcher = mock.patch(plugin, autospec=True) self.plugin = self._plugin_patcher.start() instances = self.plugin.return_value instances._RouterPluginBase__native_pagination_support = True instances._RouterPluginBase__native_sorting_...
mgadi/naemonbox
sources/psdash/gevent-1.0.1/greentest/test__loop_callback.py
Python
gpl-2.0
161
0.006211
from gevent.core import loop count = 0 def incr(): global count count += 1 loop = loop()
loop.run_callback(incr) loop.run() assert count ==
1, count
googleapis/python-analytics-data
samples/snippets/run_report_with_property_quota.py
Python
apache-2.0
3,462
0.0026
#!/usr/bin/env python # Copyright 2021 Google 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 require...
{response.property_quota.concurrent_requests.consumed}, " f"remaining: {response.property_quota.concurrent_requests.remaining}." ) print( f"Server errors per project per hour quota consumed: {response.property_quota.server_errors_per_project_per_hour.consumed}, " f"...
ng: {response.property_quota.server_errors_per_project_per_hour.remaining}." ) print( f"Potentially thresholded requests per hour quota consumed: {response.property_quota.potentially_thresholded_requests_per_hour.consumed}, " f"remaining: {response.property_quota.potentially_thre...
hanmichael/Pyrumpetroll
urls.py
Python
mit
153
0.026144
__author__ = 'Xsank' from handlers import IndexH
andler from handlers import WSHandler
handlers=[ (r"/",IndexHandler), (r"/ws",WSHandler), ]
canaryhealth/RobotS2LScreenshot
test/test_robots2lscreenshot.py
Python
mit
1,787
0.007834
# -*- coding: utf-8 -*- ''' Nose wrapper that runs the test files using robot and then compare the screenshots using perceptualdiff. ''' import glob import os import subprocess import string import sys import unittest from robot.running.builder import TestSuiteBuilder class TestRobotS2LScreenshot(unittest.TestCase)...
ue, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) sys.stdout.write(p.communicate()[0]) self.assertEqual( p.returncode, 0, msg='Robot test case failed to complete successfully: %r' % p.returncode) # diff screenshots with baseline curr_img = test_case + '.png' ...
_img, '-output', diff_img], close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) sys.stdout.write(d.communicate()[0]) self.assertEqual( d.returncode, 0, msg='Screenshots are different: %r' % d.returncode) ...
dajohnso/cfme_tests
cfme/tests/configure/test_version.py
Python
gpl-2.0
641
0.00312
# -*- coding: utf-8 -*- import pytest from cfme.configure import about from utils impo
rt version @pytest.mark.tier(3) @pytest.mark.sauce def test_version(): """Check version presented in UI against version retrieved directly from the machine. Version retrieved from appliance is in this format: 1.2.3.4 Version in the UI is always: 1.2.3.4.2014
0505xyzblabla So we check whether the UI version starts with SSH version """ ssh_version = str(version.current_version()) ui_version = about.get_detail(about.VERSION) assert ui_version.startswith(ssh_version), "UI: {}, SSH: {}".format(ui_version, ssh_version)
sintrb/SVNOnline
setup.py
Python
apache-2.0
1,012
0.000988
# -*- coding: utf-8 -*- import os, io from setuptools import setup from SVNOnline.SVNOnline import __version__ here = os.path.abspath(os.path.dir
name(__file__)) README = io.open(os.path.join(here, 'README.rst'), encoding='UTF-8').read() CHANGES = io.open(os.path.join(here, 'CHANGES.rst'), encoding='UTF-8').read() setup(name='SVNOnline', version=__version__, description='A svn online client.', keywords=('svn', 'svn client', 'svn online'), ...
s=[ 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', ], author='sintrb', author_email='sintrb@gmail.com', license='Apache', packages=['SVNOnline'], scripts=['SVNOnline/SVNOnline', 'SVNOnlin...
baudm/sg-ski
sg-ski.py
Python
mit
3,012
0.002988
#!/usr/bin/env python import sys def parse_map_file(path): map_grid = [] # Create a two-dimensiona
l list based on the input data with open(path, 'r') as f: width, height = map(int, f.readline().split()) for line in f: row = map(int, line.split()) map_grid.append(row) # Input checking if height < 1 or width < 1: raise ValueError('grid height and width shoul...
t match declared map dimensions') return width, height, map_grid def make_grid(width, height, initial_value): return [width*[initial_value] for i in range(height)] def get_length_and_elevation(x, y, map_grid, path_lengths, final_elevations): path_length = path_lengths[y][x] if path_length != -1: ...
arpruss/plucker
plucker_desktop/installer/osx/application_bundle_files/Resources/parser/python/vm/PIL/ImagePath.py
Python
gpl-2.0
1,472
0.000679
# # The Python Imaging Library # $Id: ImagePath.py,v 1.2 2007/06/17 14:12:15 robertoconnor Exp $ # # path interface # # History: # 1996-11-04 fl Created # 2002-04-14 fl Added documentation stub class # # Copyright (c) Secret Labs AB 1997. # Copyright (c) Fredrik Lundh 1996. # # See the README file for ...
# # @param flat By default, this function returns a list of 2-tuples # [(x, y), ...]. If this argument is true, it returns a flat # list [x,
y, ...] instead. # @return A list of coordinates. def tolist(self, flat=0): pass ## # Transforms the path. def transform(self, matrix): pass # override with C implementation Path = Image.core.path
unitedstates/python-us
us/tests/test_us.py
Python
bsd-3-clause
3,729
0.000268
from itertools import chain import jellyfish # type: ignore import pytest # type: ignore import pytz import us # attribute def test_attribute(): for state in us.STATES_AND_TERRITORIES: assert state == getattr(us.states, state.abbr) def test_valid_timezones(): for state in us.STATES_AND_TERRITO...
t_name(): assert us.states.lookup("Maryland") == us.states.MD assert us.state
s.lookup("maryland") == us.states.MD assert us.states.lookup("Maryland", field="name") == us.states.MD assert us.states.lookup("maryland", field="name") is None assert us.states.lookup("murryland") == us.states.MD assert us.states.lookup("Virginia") != us.states.MD # lookups def test_abbr_lookup(): ...
lausser/coshsh
tests/test_logging.py
Python
agpl-3.0
4,032
0.010665
import unittest import os import sys import shutil import string from optparse import OptionParser import ConfigParser import logging sys.dont_write_bytecode = True sys.path.insert(0, os.path.abspath("..")) sys.path.insert(0, os.path.abspath(os.path.join("..", "coshsh"))) import coshsh from coshsh.generator import G...
# read the datasources self.generator.recipes['test4'].collect() self.generator.recipes['test4'].assemble() # for each host, application get the corresponding template files # get the template files and cache them in a struct owned by the recipe # resolve the templates...
der() self.assert_(hasattr(self.generator.recipes['test4'].objects['hosts']['test_host_0'], 'config_files')) self.assert_('host.cfg' in self.generator.recipes['test4'].objects['hosts']['test_host_0'].config_files['nagios']) # write hosts/apps to the filesystem self.generator.recipes['te...
bboozzoo/jhbuild
jhbuild/commands/bot.py
Python
gpl-2.0
37,964
0.003293
# jhbuild - a tool to ease building collections of source packages # Copyright (C) 2001-2006 James Henstridge # Copyright (C) 2008 Frederic Peters # # bot.py: buildbot control commands # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as p...
_('start as daemon')), make_option('--pidfile', metavar='PIDFILE', action='store', dest='pidfile', default=None, help=_('PID file location')), make_option('--logfile', metavar='LOGFILE', action='store', dest='logfile', defau...
help=_('log file location')), make_option('--slaves-dir', metavar='SLAVESDIR', action='store', dest='slaves_dir', default=None, help=_('directory with slave files (only with --start-server)')), make_option('--buildbot-dir', metavar='...
sharestack/sharestack-api
sharestackapi/members/serializers.py
Python
mit
1,298
0
from django.contrib.contenttypes.models import ContentType from django.contrib.auth.models import Permission, Group from rest_framework import serializers from .models import User, Company # Django models class ContentTypeSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ContentType...
linkedModelSerializer): class Meta: model = Group fields = ("id", "name", "permis
sions") # Our models class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ("id", "password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined", "url", "...
laplacesdemon/django-youtube
django_youtube/admin.py
Python
bsd-3-clause
684
0
import models from django.contrib import admin class ThumbnailInline(admin.StackedInline): model = models.Thumbnail fk_name = 'vid
eo' extra = 0 class VideoAdmin(admin.ModelAdmin): readonly_fields = ('video_id', 'youtube_url', 'swf_url',) inlines = [ThumbnailInline] list_filter = ('title', 'user__username',) search_fields = ['title', 'user__first_name', 'user__email', 'user__username', 'keywords', ] ...
f.allow_tags = True admin.site.register(models.Video, VideoAdmin)
perfalle/smartbox
common/utils.py
Python
gpl-3.0
1,360
0.005147
"""Utility functions""" import os import difflib def get_diff(str1, str2): """Returns git-diff-like diff between two strings""" expected = str1.splitlines(1) actual = str2.splitlines(1) diff = difflib.unified_diff(expected, actual, lineterm=-0, n=0) return ''.join(diff) def ensure_directory(path)...
lid""" service_name_errors = get_service_name_errors(service_name) if service_name_errors: raise Exception('errors: %s' % str(service_name_errors)) def get_service_name_errors(service_name): """Checks if service_name is valid and returns errors if it is not. Returns None if service_name is vali...
ors = [] legal_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\\' for index in range(len(service_name)): if not service_name[index] in legal_characters: errors.append('Illegal character in service name: %s at position %s' % (service_name...
QISKit/qiskit-sdk-py
qiskit/visualization/interactive/iplot_cities.py
Python
apache-2.0
3,026
0.00033
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
ualization"], function(qVisualizations) { data = { real: $real, titleReal: "Real.[rho]", imaginary: $imag, titleImaginary: "Im.[rho]", qbits: $qbits }; qVisualizations.plotState("cities_$divNumber", ...
$options); }); </script> """) rho = _validate_input_state(rho) if figsize is None: options = {} else: options = {'width': figsize[0], 'height': figsize[1]} # Process data and execute real = [] imag = [] for xvalue in rho: row_real = [] ...
jornada/DOENDO
rename.py
Python
gpl-3.0
2,180
0.037156
# DOENDO - A Python-Based Fortran Refactoring Tool # Copyright (C) 2011 Felipe H. da Jornada <jornada@civet.berkeley.edu> import re import xml.dom.minidom import analyze import common def rename(lines, doc, ren_dict, block=None): ''' Rename a variable in a particular block lines: line-oriented buffer to be al...
yTagName('block') el=None for el_ in els: if el_.getAttribute('name')==block: el=el_ break if el is None: print 'Could not find block '+block return for var0, new_var in ren_dict.iteritems(): if isinstance(var0, str): orig_var = var0 _vars = el.getElementsByTagName('var') var=None f...
if var_.getAttribute('name')==orig_var: var=var_ break else: var = var0 el = var.parentNode orig_var = var.getAttribute('name') if var is None: print 'Could not find variable '+orig_var+' in block '+block sys.exit(1) #get the initial and final lines start = int(el.getAttribute('start'...
idkwim/pysmt
examples/efsmt.py
Python
apache-2.0
2,475
0.00202
# EF-SMT solver implementation # # This example shows: # 1. How to combine 2 different solvers # 2. How to extract information from a model # from pysmt.shortcuts import Solver, get_model from pysmt.shortcuts import Symbol, Bool, Real, Implies, And, Not, Equals from pysmt.shortcuts import GT, LT, LE, Minus, Times fro...
esolver.add_assertion(sub_phi) raise SolverReturnedUnknownResultError def run_test(y, f): print("Testing " + str(f)) try: res = efsmt(y, f, logic=QF_LRA, maxl
oops=20, verbose=True) if res == False: print("unsat") else: print("sat : %s" % str(res)) except SolverReturnedUnknownResultError: print("unknown") print("\n\n") def main(): x,y = [Symbol(n, REAL) for n in "xy"] f_sat = Implies(And(GT(y, Real(0)), LT(y, ...
mcdickenson/python-washu-2014
day2/polymorphism.py
Python
mit
771
0.035019
class Animal(object): def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return self.meo...
return 'Woof! Woof!' class Fish(Animal): def swim(self): pass def __str__(self
): return "I am a fish!" animals = [Cat('Foo'), Dog('Bar'), Fish('nemo')] for animal in animals: print animal.name + ': ' + animal.talk() # f = Fish("foo") # print "Hi, " + str(f)
tillahoffmann/tensorflow
tensorflow/python/framework/constant_op.py
Python
apache-2.0
9,632
0.007164
# Copyright 2015 The TensorFlow Authors. 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 applica...
s)." % (num_t, shape, shape.num_elements())) g = ops.get_default_graph() tensor_value = attr_value_pb2.AttrValue() tensor_value.tensor.CopyFrom( tensor_util.make_tensor_proto( value, dtype=dtype, shape=shape, verify_sh
ape=verify_shape)) dtype_value = attr_value_pb2.AttrValue(type=tensor_value.tensor.dtype) const_tensor = g.create_op( "Const", [], [dtype_value.type], attrs={"value": tensor_value, "dtype": dtype_value}, name=name).outputs[0] return const_tensor def is_constant(tensor_or_op): if...
eunchong/build
third_party/buildbot_8_4p1/buildbot/schedulers/filter.py
Python
bsd-3-clause
851
0.001175
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that i
t will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS #
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have 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. # # Copyright Buildbot Te...
Speedy1991/Flask-FileUpload
flask_fileupload/storage/storage.py
Python
mit
1,614
0.003098
import os from werkzeug.utils import secure_filename from flask import url_for from .utils import convert_to_snake_case from . import AbstractStorage, StorageExists, StorageNotExists, StorageNotAllowed class LocalStorage(AbstractStorage): def __init__(self, app): super(LocalStorage, self).__init__(app) ...
nfig.get("FILEUPLOAD_LOCALSTORAGE_IMG_FOLDER", "upload") self.img_folder = self.img_folder if self.img_folder.endswith("/") else self.img_folder + "/" self.abs_img_folder = os.path.join(app.root_path, "static", self.img_folde
r) if not os.path.exists(self.abs_img_folder): os.makedirs(self.abs_img_folder) def get_existing_files(self): return [f for f in os.listdir(self.abs_img_folder)] def get_base_path(self): return url_for("static", filename=self.img_folder) def store(self, filename, file_...
annayqho/TheCannon
code/lamost/xcalib_5labels/cont_norm_test_obj.py
Python
mit
747
0.005355
import numpy as np import pickle import glob from matplotlib import rc from lamost import load_spectra, load_labels from TheC
annon import continuum_normalization from TheCannon import dataset from TheCannon import model rc('text', usetex=True) rc(
'font', family='serif') with np.load("test_data_raw.npz") as data: test_IDs = data['arr_0'] wl = data['arr_1'] test_flux = data['arr_2'] test_ivar = data['arr_3'] data = dataset.Dataset( wl, test_IDs[0:10], test_flux[0:10,:], test_ivar[0:10,:], [1], test_IDs, test_flux, test_ivar) data.set_la...
tboyce021/home-assistant
homeassistant/components/stream/fmp4utils.py
Python
apache-2.0
5,317
0.001128
"""Utilities to help convert mp4s to fmp4s.""" import io def find_box(segment: io.BytesIO, target_type: bytes, box_start: int = 0) -> int: """Find location of first box (or sub_box if box_start provided) of given type.""" if box_start == 0: box_end = segment.seek(0, io.SEEK_END) segment.seek(0...
from fragmented mp4.""" moof_location = next(find_box(segment, b"moof")) segment.seek(0) return segment.read(moof_location) def get_m4s(segment: io.BytesIO, sequence: int) -> byt
es: """Get m4s section from fragmented mp4.""" moof_location = next(find_box(segment, b"moof")) mfra_location = next(find_box(segment, b"mfra")) segment.seek(moof_location) return segment.read(mfra_location - moof_location) def get_codec_string(segment: io.BytesIO) -> str: """Get RFC 6381 code...
Aplopio/rip
rip/filter_operators.py
Python
mit
831
0.001203
EQUALS = 'equals' GT = 'gt' LT = 'lt' IN = 'in' OPERA
TOR_SEPARATOR = '__' REVERSE_ORDER = '-' ALL_OPERATORS = {EQUALS: 1, GT: 1, LT: 1, IN: 1} def split_to_field_and_filter_type(filter_name): filter_split = filter_name.split(OPERATOR_SEPARATOR) filte
r_type = filter_split[-1] if len(filter_split) > 0 else None if filter_type in ALL_OPERATORS: return OPERATOR_SEPARATOR.join(filter_split[:-1]), filter_type else: return filter_name, None def split_to_field_and_order_type(field_name_with_operator): if field_name_with_operator.startswith(R...
sunfall/giles
giles/games/tanbo/tanbo.py
Python
agpl-3.0
15,089
0.00106
# Giles: tanbo.py # Copyright 2012 Phil Bordelon # # 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 (at your option) any later version. # This progra...
def __init__(self, server, table_name): super(Tanbo, self).__init__(server, table_name) self.game_display_name = "Tanbo"
self.game_name = "tanbo" self.seats = [ Seat("Black"), Seat("White"), ] self.min_players = 2 self.max_players = 2 self.state = State("need_players") self.prefix = "(^RTanbo^~): " self.log_prefix = "%s/%s: " % (self.table_display_name, s...
benschmaus/catapult
devil/devil/android/tools/provision_devices.py
Python
bsd-3-clause
23,798
0.00832
#!/usr/bin/env python # # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Provisions Android devices with settings required for bots. Usage: ./provision_devices.py [-d <device serial number>] """ ...
blacklist.', str(device)) if blacklist: blacklist.Extend([str(device)], reason='provision_failure') def Wipe(device, adb_key_files=None): if (device.IsUserBuild() or device.build_version_sdk >= version_codes.MARSHMALLOW): WipeChromeData(device) package = 'com.google.and...
gger.info('Version name for %s is %s', package, version_name) else: logger.info('Package %s is not installed', package) else: WipeDevice(device, adb_key_files) def WipeChromeData(device): """Wipes chrome specific data from device (1) uninstall any app whose name matches *chrom*, except com....
Thraxis/pymedusa
sickbeard/clients/deluge_client.py
Python
gpl-3.0
9,733
0.001952
# coding=utf-8 # Author: Mr_Orange <mr_orange@hotmail.it> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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 versi...
}) self._request(method='post', data=post_data) result.hash = self.response.json()['result'] return self.response.json()['result'] def _add_torrent_file(self, result): post_data = json.dumps({
'method': 'core.add_torrent_file', 'params': [ '{name}.torrent'.format(name=result.name), b64encode(result.content), {}, ], 'id': 2, }) self._request(method='post', data=post_data) result.hash = self.r...
nttks/edx-platform
lms/djangoapps/ga_operation/forms/search_by_email_and_period_date_form.py
Python
agpl-3.0
1,730
0.001877
# -*- coding: utf-8 -*- from datetime import date from django import forms from django.forms.util import ErrorList from openedx.core.djangoapps.ga_operation.ga_operation_base_form import (GaOperationEmailField, FIELD_NOT_INPUT, INVALID_EMAIL) ...
val def clean_end_date(self): val = self.cleaned_data['end_date'] if not val: return date.today()
if val > date.today(): raise forms.ValidationError(u"集計終了日は本日以前の日付を入力してください。") return val def clean(self): """ Checks multi fields correlation :return: clean data """ cleaned_data = self.cleaned_data # check inputs start_date = cleaned_...
FrancoisRheaultUS/dipy
dipy/align/tests/test_transforms.py
Python
bsd-3-clause
8,834
0
from dipy.align.transforms import regtransforms, Transform import numpy as np from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal, assert_equal, assert_raises) def test...
nary (the base class is not contained there) # If for some reason the user instantiates it and attempts to
use it, # however, it will raise exceptions when attempting to retrieve its # Jacobian, identity parameters or its matrix representation. It will # return -1 if queried about its dimension or number of parame
ytlai4851/Uva
Python/Q538.py
Python
gpl-2.0
392
0.076531
N = 46340 table = list(range(N)) for i in range(2,int(N**0.5)+1): if table[i]: for mult in range(i**2,N,i): table[mult] = False primetable= [p for p in table if p][1:] p=0 a=196 if a<0: p=1 a*=-1
b='' while True: if a in primetable: b+=str(a) break for i in p
rimetable: if a % i ==0: a=a/i b+=str(i)+' x ' break if p : b='-1 x '+b print(b)
Tayamarn/socorro
socorro/unittest/cron/jobs/test_featured_versions_automatic.py
Python
mpl-2.0
9,704
0.000309
import datetime import json import mock from socorro.cron.crontabber_app import CronTabberApp from socorro.lib.datetimeutil import utc_now from socorro.unittest.cron.jobs.base import IntegrationTestBase from socorro.external.postgresql.dbapi2_util import ( execute_no_results, execute_query_fetchall, ) class...
s_code = status_code def json(self): return json.loads(self.content) class IntegrationTestFeaturedVersionsAutomatic(IntegrationTestBase): def setUp(self): super(IntegrationTestFeaturedVersionsAutomatic, self).setUp() self.__truncate() now = utc_now() build_date = now...
self.conn, """ INSERT INTO products (product_name, sort, release_name) VALUES ('Firefox', 1, 'firefox'), ('Fennec', 1, 'mobile') """ ) execute_no_results( self.conn, """ INSERT INTO...
poliastro/poliastro
src/poliastro/twobody/angles.py
Python
mit
6,419
0.000156
"""Angles and anomalies. """ from astropy import units as u from poliastro.core.angles import ( D_to_M as D_to_M_fast, D_to_nu as D_to_nu_fast, E_to_M as E_to_M_fast, E_to_nu as E_to_nu_fast, F_to_M as F_to_M_fast, F_to_nu as F_to_nu_fast, M_to_D as M_to_D_fast, M_to_E as M_to_E_fast, ...
""" return (nu_to_E_fast(nu.
to_value(u.rad), ecc.value) * u.rad).to(nu.unit) @u.quantity_input(nu=u.rad, ecc=u.one) def nu_to_F(nu, ecc): """Hyperbolic eccentric anomaly from true anomaly. Parameters ---------- nu : ~astropy.units.Quantity True anomaly. ecc : ~astropy.units.Quantity Eccentricity (>1). R...
EdwardJKim/nbgrader
nbgrader/tests/formgrader/test_gradebook_navigation.py
Python
bsd-3-clause
12,452
0.004096
import pytest from six.moves.urllib.parse import quote from ...api import MissingEntry from .base import BaseTestFormgrade from .manager import HubAuthNotebookServerUserManager @pytest.mark.formgrader @pytest.mark.usefixtures("all_formgraders") class TestGradebook(BaseTestFormgrade): def _click_element(self, n...
ge("students/{}/Problem Set 1".format(student.id)) def test_switch_views(self): # load the main page self._load_gradebook_page("assignments") # click the "Change View" button self._click_link("Change View", partia
l=True) # click the "Students" option self._click_link("Students") self._wait_for_gradebook_page("students") # click the "Change View" button self._click_link("Change View", partial=True) # click the "Assignments" option self._click_link("Assignments") ...
abetusk/dev
projects/pcbcnc/src/cnc3018pro.py
Python
agpl-3.0
8,180
0.025672
#!/usr/bin/python # # Copyright (C) 2020 abetusk # # 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 # (at your option) any later version. # # This pro...
m.group(1) m = re.match('.*[yY]\s*(-?\d+(\.\d+)?)', l) if m: is_move = 1 cur_y = m.group(1)
m = re.match('.*[zZ]\s*(-?\d+(\.\d+)?)', l) if m: is_move = 1 cur_z = m.group(1) if ( float(cur_z) >= z_threshold ): z_pos = 'up' else: z_pos = 'down' if is_move and (not g_mode): return None if not is_move: lines.append(l) continue if (z_po...
Selen93/ProjectEuler
Python/Problem 15/Problem 15.py
Python
mit
349
0.014327
# how many routes are in a 20x20 lattice grid? import time start_time
= time.clock() field = [] sum = 0 for n in range(0,21): field.append([1]) for i in range(1,21): sum = field[n][i-1] if n>0: sum += field[n-1][i] field[n].append(sum) print(field[20][20]) print("--- %s seconds ---" % (tim
e.clock() - start_time))
atom/crashpad
util/net/http_transport_test_server.py
Python
apache-2.0
6,017
0.010316
#!/usr/bin/env python # coding: utf-8 # Copyright 2014 The Crashpad Authors. 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/LICEN...
: import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) # Start the server. server = BaseHTTPServer.HTTPServer(('127.0.0.1', 0), RequestHandler) # Write the port as an unsigned short to the parent process. sys.stdout.write(struct.pack('=H', server.server_address[1])) sy
s.stdout.flush() # Read the desired test response code as an unsigned short and the desired # response body as a 16-byte string from the parent process. RequestHandler.response_code, RequestHandler.response_body = \ struct.unpack('=H16s', sys.stdin.read(struct.calcsize('=H16s'))) # Handle the request. ...
thesealion/writelightly
writelightly/utils.py
Python
mit
3,963
0.005551
import datetime import os import re class WLError(Exception): """Base class for all Writelightly exceptions.""" class WLQuit(WLError): """Raised when user sends a quit command.""" def lastday(*args): """Return the last day of the given month. Takes datetime.date or year and month, returns an integer...
y>\d{2}).(?P<month>\d{2}).(?P<year>\d{4})']: m = re.match(p, date) if m: d = m.groupdict() return datetime.date(int(d['year']), int(d['month']), int(d['day'])) return None def get_char(win): """Use win.getch() to get a character even if it's multibyte. A magic funct...
get_check_next_byte(): c = win.getch() if 128 <= c <= 191: return c else: raise UnicodeError bytes = [] c = win.getch() if c <= 127: return c elif 194 <= c <= 223: bytes.append(c) bytes.append(get_check_next_byte()) elif 224 <...
kelvinhammond/beets
test/test_keyfinder.py
Python
mit
2,610
0.000383
# -*- coding: utf-8 -*- # This file is part of beets. # Copyright 2015, Thomas Scholtes. # # 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 ...
mport(self): self.command_output.return_value = 'dbm' importer = self.create_importer() importer.run() item = self.lib.items().get() self.asse
rtEqual(item['initial_key'], 'C#m') def test_force_overwrite(self): self.config['keyfinder']['overwrite'] = True item = Item(path='/file', initial_key='F') item.add(self.lib) self.command_output.return_value = 'C#m' self.run_command('keyfinder') item.load() ...
dc3-plaso/dfvfs
tests/path/vshadow_path_spec.py
Python
apache-2.0
2,586
0.00232
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the VSS path specification implementation.""" import unittest from dfvfs.path import vshadow_path_spec from tests.path import test_lib class VShadowPathSpecTest(test_lib.PathSpecTestCase): """Tests for the VSS path specification implementation.""" def tes...
self.assertIsNotNone(path_spec) expected_comparable = u'\n'.join([ u'type: TEST', u'type: VSHADOW', u'']) self.assertEqual(path_spec.comparable, expected_comparable) path_spec = vshadow_path_spec.VSh
adowPathSpec( location=u'/vss2', parent=self._path_spec) self.assertIsNotNone(path_spec) expected_comparable = u'\n'.join([ u'type: TEST', u'type: VSHADOW, location: /vss2', u'']) self.assertEqual(path_spec.comparable, expected_comparable) path_spec = vshadow_path_spe...
chinfeng/gumpy
plugins/web_console/__init__.py
Python
lgpl-3.0
110
0.009091
# -*- coding: utf-8 -*-
__author__ = 'chinfeng' __gum__ = 'web_console' from .server import Web
ConsoleServer
google/clusterfuzz
src/clusterfuzz/_internal/tests/appengine/libs/crash_access_test.py
Python
apache-2.0
4,900
0.002653
# Copyright 2019 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, ...
helpers as test_helpers from libs import crash_access from libs import helpers from libs.query import base def _has_access(need_privil
eged_access=False): return not need_privileged_access class AddScopeTest(unittest.TestCase): """Test add_scope.""" def setUp(self): Query = base.Query # pylint: disable=invalid-name test_helpers.patch(self, [ 'clusterfuzz._internal.base.external_users._allowed_entities_for_user', 'lib...
natetrue/ReplicatorG
skein_engines/skeinforge-35/fabmetheus_utilities/geometry/solids/cube.py
Python
gpl-2.0
3,514
0.016221
""" This page is in the table of contents. The xml.py script is an import translator plugin to get a carving from an Art of Illusion xml file. An import plugin is a script in the interpret_plugins folder which has the function getCarving. It is meant to be run from the interpret tool. To ensure that the plugin works...
inradius'], Vector3(1.0, 1.0, 1.0), self.xmlElement ) self.inradius = evaluate.getVector3ByMultiplierPrefix( 2.0, 'size', self.inradius, self.xmlElement ) self.xmlEl
ement.attributeDictionary['inradius.x'] = self.inradius.x self.xmlElement.attributeDictionary['inradius.y'] = self.inradius.y self.xmlElement.attributeDictionary['inradius.z'] = self.inradius.z self.createShape()
ywangd/pybufrkit
pybufrkit/mdquery.py
Python
mit
1,958
0.003064
""" pybufrkit.mdquery ~~~~~~~~~~~~~~~~~ """ from __future__ import absolute_import from __future__ import print_function import logging from pybufrkit.errors import MetadataExprParsingError __all__ = ['MetadataExprParser', 'MetadataQuerent', 'METADATA_QUERY_INDICATOR_CHAR'] log = logging.getLogger(__file__) METADA...
for parameter in section: if parameter
.name == metadata_name: return parameter.value return None
Oliver2213/Queriet
queriet/keyboard_handler/linux.py
Python
gpl-2.0
2,059
0.000486
from main import KeyboardHandler import threading import thread import pyatspi def parse(s): """parse a string like control+f into (modifier, key). Unknown modifiers will return ValueError.""" m = 0 lst = s.split('+') if not len(lst): return (0, s) # Are these right? d = { "shif...
if len(lst) > 1: # more than one key, parse error raise ValueError('unknown modifier %s' % lst[0]) return (m, lst[0].lower()) class AtspiThread(threading.Thread): def run(self): pyatspi.Registry.registerKeystrokeListener(handler, kin
d=( pyatspi.KEY_PRESSED_EVENT,), mask=pyatspi.allModifiers()) pyatspi.Registry.start() # the keys we registered keys = {} def handler(e): m, k = e.modifiers, e.event_string.lower() # not sure why we can't catch control+f. Try to fix it. if (not e.is_text) and e.id >= 97 <= 126: k =...
nevil-brownlee/pypy-libtrace
lib/pldns/build-cpldns.py
Python
gpl-3.0
3,848
0.001559
# 1222, Fri 18 Dec 2015 (NZDT) # # build-cpldns.py: makes pypy cpldns module # # Copyright (C) 2016 by Nevil Brownlee, U Auckland | WAND # # This program is free software: you can redistribute it and/or modify # it und
er the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty
of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from cffi import FFI ffi = FFI() # Our C functions ffi.cdef...
robertjoosten/rjSkinningTools
scripts/skinningTools/utils/api/selection.py
Python
gpl-3.0
1,916
0.000522
from maya import OpenMaya __all__ = [ "getSoftSelection" ] def getSoftSelection(): """ Query the soft selection in the scene. If no soft selection is made empty lists will be returned. The active selection will be returned for easy reselection. The data structure of the soft selection weight is ...
if obj.apiType() == OpenMaya.MFn.kMeshVertComponent: components = OpenMaya.MFnSingleIndexedC
omponent(obj) count = components.elementCount() # store index and weight for i in range(count): index = components.element(i) weight = components.weight(i).influence() data[path][index] = weight selIter.next() return act...
IECS/MansOS
tools/lib/tests/configtest.py
Python
mit
1,154
0.001733
#!/usr/bin/python # # Config file test app (together with test.cfg file) # import os, sys sys.path.append("..") import configfile cfg = configfile.ConfigFile("test.cfg") cfg.setCfgValue("name1", "value1") cfg.setCfgValue("name2", "value2") cfg.selectSection("user") cfg.setCfgValue("username", "janis") cfg.setCfgV...
ueAsList("list_in_list") cfg.selectSection("main") print cfg.getCfgValueAsInt("a_number") print type(cfg.getCfgValueAsInt("a_number")) print cfg.getCfgValueAs
Bool("a_bool") print type(cfg.getCfgValueAsBool("a_bool")) cfg.filename = "test-mod.cfg" cfg.selectSection("main") cfg.setCfgValue("name1", "value1mod2") cfg.setCfgValue("a_number", 14) cfg.selectSection("user") cfg.setCfgValue("acceptable_names", ["john", "janis", "ivan"]) cfg.setCfgValue("list_in_list2", ["[baz]", "...
atakan/Complex_Coeff_RKN
testing/timing_runs/400body_CPUtime_plot.py
Python
gpl-3.0
3,030
0.023432
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division, print_function import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import Circle, P
olygon from matplotlib import rc from matplotlib.ticker imp
ort MultipleLocator, FormatStrFormatter from matplotlib.ticker import LogLocator P = 8.0*np.arctan(1.0)*4.0*np.sqrt(2.0) #rc('font',**{'family':'serif','serif':['Palatino']}) rc('text', usetex=True) #rc('font',**{'family':'serif','serif':['Computer Modern Roman']}) rc('font', family='serif') mpl.rcParams['ps.usedisti...
rjw57/componentsdb
manage.py
Python
mit
717
0.001395
""" CLI management script. (Requires flask-script.) """ import os # pylint: disable=no-name-in-module,import-error from flask.ext.script import Manager from flask.ext.migrate import MigrateCommand, Migr
ate from componentsdb.app import default_app from componentsdb.model import db # Default to development environment settings unless told otherwise if 'COMPONENTSDB_SETTINGS' not in os.environ: os.environ['COMPONENTSDB_SE
TTINGS'] = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'devsettings.py' ) app = default_app() manager = Manager(app) migrate = Migrate(app, db, directory='alembic') manager.add_command('migrate', MigrateCommand) if __name__ == "__main__": manager.run()
Azure/azure-sdk-for-python
sdk/resources/azure-mgmt-resource/azure/mgmt/resource/policy/v2016_12_01/operations/_policy_assignments_operations.py
Python
mit
38,695
0.004032
# 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 ...
URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Authorization/policyAssignments') path_format_arguments = { "resourceG
roupName": _SERIALIZER.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1, pattern=r'^[-\w\._\(\)]+$'), "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters ...
Jorge-Rodriguez/ansible
lib/ansible/modules/windows/win_find.py
Python
gpl-3.0
9,583
0.002087
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # this is a windows documentation stub. actual code lives in the .ps1 # file of the same name ANSIBLE_METADATA = {'metadata_version': '1.1', ...
ription: The checksum of a file based on checksum_algorithm specified. returned: success, path exists, path is a file, get_checksum == True typ
e: str sample: 09cb79e8fc7453c84a07f644e441fd81623b7f98 creationtime: description: The create time of the file represented in seconds since epoch. returned: success, path exists type: float sample: 1477984205.15 extension: descripti...
jonathanverner/brython
www/src/Lib/turtle.py
Python
bsd-3-clause
53,120
0.004085
# A revised version of CPython's turtle module written for Brython # # Note: This version is not intended to be used in interactive mode, # nor use help() to look up methods/functions definitions. The docstrings # have thus been shortened considerably as compared with the CPython's version. # # All public methods/fu...
_canvas <=rect def _convert_coordinates(self, x, y): """In the browser, the
increasing y-coordinate is towards the bottom of the screen; this is the opposite of what is assumed normally for the methods in the CPython turtle module. This method makes the necessary orientation. It should be called just prior to creating any SVG element. """...
a0xnirudh/hackademic
ContainerManager/install.py
Python
gpl-3.0
4,749
0.000421
#!/usr/bin/env python2 """ :Synopsis: Specialized Class for installing essential components. :Install-logs: All logs are saved in the directory **hackademic-logs**. """ import os import sys import subprocess from logging_manager import LoggingManager sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(_...
self.pip_install_tools = self.file_location + "/pip.txt" return def run_command(self, command): print "[+] Running the command: %s" % command os.system(command) def install_docker(self): """ This function will install docker and if docker is already installed,it ...
ll.logs """ print("[+] Installing Docker and necessary supporting plugins") print("[+] This could take some time. Please wait ...") try: subprocess.check_call("docker -v", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) ...
TeamEOS/external_chromium_org
content/test/gpu/gpu_tests/webgl_robustness.py
Python
bsd-3-clause
2,603
0.002305
# Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import test from telemetry.page import page from telemetry.page import page_set from telemetry.page import page_test # pylint: disable=W0401,W0...
false; } window.webglRobustnessTestHarness = robustnessTestHarness; """ class WebglRobustnessPage(page.Page): def __init__(self, page_set, base_dir): super(WebglRobustnessPage, self).__init__( url='file://extra/lots-of-polys-example.html', page_set=page_set, base_dir=base_dir) self.scri...
ptCondition('webglTestHarness._finished') class WebglRobustness(test.Test): test = WebglConformanceValidator def CreatePageSet(self, options): ps = page_set.PageSet( file_path=conformance_path, user_agent_type='desktop', serving_dirs=['']) ps.AddPage(WebglRobustnessPage(ps, ps.base_dir))...
jalavik/inspire-next
inspire/modules/harvester/definitions.py
Python
gpl-2.0
1,759
0
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014, 2015 CERN. # # INSPIRE 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. # # INSPIRE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILIT...
You should have received a copy of the GNU General Public License # along with INSPIRE. If not, see <http://www.gnu.org/licenses/>. # # In applying this licence, CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization # or submit itself to any juris...
mbiciunas/nix
src/utility/nix_error.py
Python
gpl-3.0
1,070
0.001869
# Nix # Copyright (c) 2017 Mark Biciunas. # # 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 3 of the License, or # (at your option) any later version. # # This program is distrib...
rror): def _
_init__(self, message: str, exception: Exception=None) -> None: self._message = message self._exception = exception def get_message(self) -> str: return self._message def get_exception(self) -> Exception: return self._exception
zeraien/django-url-framework
tests/test_controller_action_renderers.py
Python
mit
11,896
0.010592
import json import unittest from io import BytesIO import yaml from django.http import HttpRequest from django.test import RequestFactory, SimpleTestCase from django.utils.encoding import force_bytes from .duf_test_case import DUFTestCase from django_url_framework.decorators import auto, json_action, yaml_action from...
def test_action(self, request): return self._as_yaml(input, default_flow_style=True) self._request_and_test(TestAsYamlController, "test_action", expected_response=yaml.dump(input, default_flow_style=True)) def test_as_json(self): input = {'ab':"C",1:"2",None:False} ...
): return self._as_json(input) self._request_and_test(TestAsJsonController, "test_action", expected_response=json.dumps(input)) def test_redirect_action(self): class RedirectController(ActionController): @json_action() def second_action(self, request): ...
undu/query-bot
wolfram/wolfram.py
Python
mpl-2.0
4,435
0.006764
#encoding: utf-8 from responsemodule import IModule import urllib import httplib2 import socket import xmltodict import re ''' Example config [walpha] app_id=1LALAL-2LALA3LAL4 timeout=6 ''' settings_name_g = u'walpha' api_key_g = u'app_id' timeout_g = u'timeout' class Wolfram(IModule): def __init__(self): ...
f.settings[timeout_g]) # construct the url and shorten it if we can url = u'http://www.wolframalpha.com/input/?i={q}'.format(q = query) if not self.shorten_url is None: url = self.shorten_url(url) try: sock = httplib2.Http(timeout=self.settings[timeout_g]) ...
e = sock.request(queryurl) if headers[u'status'] in (200, '200'): response = xmltodict.parse(xml_response) int_found = False res_found = False interpretation = u'' result = u'' # This statement throws an Index...
orion-42/numerics-physics-stuff
knapsack.py
Python
mit
1,976
0.004049
from collections import namedtuple knapsack_item = namedtuple("knapsack_item", ["weight", "value"]) max_weight = 15 items = [ knapsack_item(weight=2, value=2), knapsack_item(weight=1, value=2), knapsack_item(weight=12, value=4), knapsack_item(weight=1, value=1), knapsack_item(weight=4, value=10),...
n optimal_solution: print(row) print("optimal value:", optimal_solution[-1][-1]) print("items to take:") for item i
n items_to_take: print(item)
spvkgn/youtube-dl
youtube_dl/extractor/jwplatform.py
Python
unlicense
1,720
0.002326
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import unsmuggle_url class JWPlatformIE(InfoExtractor): _VALID_URL = r'(?:https?://(?:content\.jwplatform|cdn\.jwplayer)\.com/(?:(?:feed|player|thumb|preview)s|jw6|v2/media)/|jwplatform:)(?P<id>[a-zA...
e) def _real_extract(self, url): url, smuggled_data = unsmuggle_url(url, {}) self._initialize_geo_bypass({ 'countries': smuggled_data.get('geo_countries'), }) video_id = self._match_id(url) json_data = self._download_json('https://cdn.jwplayer.com/v2/media/' + vi...
) return self._parse_jwplayer_data(json_data, video_id)
drpngx/tensorflow
tensorflow/contrib/opt/python/training/multitask_optimizer_wrapper_test.py
Python
apache-2.0
5,436
0.011038
# Copyright 2017 The TensorFlow Authors. 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 applica...
# Step 2: momentum update that changes only slot1 but not slot0. self.evaluate(mom_update_partial) # Check that only the relevant momentum accumulator has been updated. self.assertAllCloseAccordingToType( np.array([0.1, 0.1]), self.evaluate(slot0)) self.assertAllCloseAccordingToType(...
um update that does not change anything. self.evaluate(mom_update_no_action) # Check that the momentum accumulators have *NOT* been updated. self.assertAllCloseAccordingToType( np.array([0.1, 0.1]), self.evaluate(slot0)) self.assertAllCloseAccordingToType( np.array([(0.9 * 0....
uber/pyro
pyro/distributions/__init__.py
Python
apache-2.0
5,185
0.000193
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import pyro.distributions.torch_patch # noqa F403 from pyro.distributi
ons.torch import * # noqa F403 # isort: split from pyro.distributions.affine_beta import AffineBeta from pyro.distributions.asymmetriclaplace import ( AsymmetricLaplace, SoftAsymmetricLaplace, ) from pyro.distributions.avf_mvn import AVFMultivariateNormal from pyro.distributions.coalescent import ( Coale...
CoalescentTimesWithRate, ) from pyro.distributions.conditional import ( ConditionalDistribution, ConditionalTransform, ConditionalTransformedDistribution, ConditionalTransformModule, ) from pyro.distributions.conjugate import ( BetaBinomial, DirichletMultinomial, GammaPoisson, ) from pyro.di...
proactivity-lab/python-moteconnection
moteconnection/packet.py
Python
mit
1,781
0.001684
"""packet.py: Raw packet object.""" import logging import struct from codecs import encode from moteconnection.connection import Dispatcher log = logging.getLogger(__name__) __author__ = "Raido Pahtma" __license__ = "MIT" class Packet(object): def __init__(self, dispatch=0): self._dispatch = dispatc...
encode(self._pay
load, "hex").upper()) @staticmethod def deserialize(data): if len(data) == 0: raise ValueError("At least 1 byte is required to deserialize a Packet!") p = Packet(dispatch=ord(data[0:1])) p.payload = data[1:] return p class PacketDispatcher(Dispatcher): def __i...
victorywang80/Maintenance
saltstack/src/salt/modules/mine.py
Python
apache-2.0
6,869
0.000291
# -*- coding: utf-8 -*- ''' The function cache system allows for data to be stored on the master so it can be easily read by other minions ''' # Import python libs import copy import logging # Import salt libs import salt.crypt import salt.payload log = logging.getLogger(__name__) def _auth(): ''' Return ...
__salt__[func](*m_data[func]) else: data[func] = __salt__[func]() except Exception: log.error('
Function {0} in mine_functions failed to execute' .format(func)) continue if __opts__['file_client'] == 'local': if not clear: old = __salt__['data.getval']('mine_cache') if isinstance(old, dict): old.update(data) data...
neillc/memberdb-ng
backend/tests/test_load_user.py
Python
gpl-2.0
330
0
from unittest import TestCase class TestLoadUser(TestCase): def test_find_user(self): from backend import load_user user = load_user('Neill', 'password') self.assertIsNot
None(user) self.assertEqual(user.password, "Password") user = load_user("Tony") self.assertIsNone(user)
kwailamchan/programming-languages
python/django/polls/pollsite/polls/urls.py
Python
mit
374
0.005348
from django.conf.url
s import patterns, url from polls import views urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'), url(r'^(?P<question_id>\d+)/vot...
ame='vote'), )
vialette/binreconfiguration
binreconfiguration/strategy/minaverageitemsize.py
Python
mit
205
0.014634
from .ascendinggaugedstrategy import AscendingGaugedStrategy from .gauge
import AverageItemSize class MinAverageItemSize(AscendingGaugedStrategy): def _gaug
e(self, item): return AverageItemSize(item)
edx/ecommerce
ecommerce/enterprise/management/commands/backfill_opportunity_ids.py
Python
agpl-3.0
9,523
0.00231
""" Backfill opportunity ids for Enterprise Coupons, Enterprise Offers and Manual Order Offers. """ import csv import logging from collections import Counter, defaultdict from time import sleep from uuid import UUID from django.core.management import BaseCommand from ecommerce.core.constants import COUPON_PRODUCT_C...
P_ID']) # condition the data so that at the end we have only one opportunity id for each coupon/offer for __, category_data in data.items(): for category_object_id, opportunity_ids in category_data.items(): if len(opportunity_ids) > 1: most_common_opportu...
category_data[category_object_id] = opportunity_ids[0] return data def get_enterprise_coupons_batch(self, coupon_filter, start, end): logger.info('Fetching new batch of enterprise coupons from indexes: %s to %s', start, end) return Product.objects.filter(**coupon_filter)[start:end] ...
dorzheh/sysstat
SysUsage.py
Python
mit
5,469
0.017188
#!/usr/bin/env python # ########################### # Sysusage info: # 1) memory/swap usage # 2) disk usage # 3) load avarage ########################### import re import os class MemoryUsage: """MEMORY USAGE STATISTICS: memused - Total size of used memory in kilobytes. memfree - T...
percent. swaptotal - Total size of swap space in kilobytes. The following statistics are only available by kernels from 2.6. slab - Total size of memory in kilobytes that used by kernel for the data structure allocations. dirty - Total size of ...
waits to be written back to disk. mapped - Total size of memory in kilbytes that is mapped by devices or libraries with mmap. writeback - Total size of memory that was written back to disk. USAGE: newObj = SysUsage.MemoryUsage() ## Creat...
yosefm/tracer
tests/test_boundary_surface.py
Python
gpl-3.0
4,024
0.012177
# Unit tests for the boundary shape class and the boundary sphere class. import unittest import numpy as N from tracer.spatial_geometry import generate_transform, rotx from tracer.boundary_shape import * class TestInBounds(unittest.TestCase): def setUp(self): self.points = N.array([ [0.,0.,0....
lf.at_origin_yz) self.failUnlessEqual(extents, (-2., 2., -
2., 2.)) extents = sphere.bounding_rect_for_plane(self.at_origin_slant) self.failUnlessEqual(extents, (-2., 2., -2., 2.)) sqrt_3 = N.sqrt(3) extents = sphere.bounding_rect_for_plane(self.parallel_xy) self.failUnlessEqual(extents, (-sqrt_3, sqrt_3, -sqrt_3, sqrt_...
aaronzhang1990/workshare
test/python/restore_hotel_2000w_data.py
Python
gpl-2.0
2,060
0.004369
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, MySQLdb, csv table_sql = """drop table if exists hotel; create table hotel( id int primary key, Name varchar(255), CardNo varchar(255), Descriot varchar(255), CtfTp varchar(255), CtfId varchar(255), Gender varchar(255), Birthday v...
fId', 'Gender', 'Birthday', 'Address', 'Zip', 'Dirty', 'District1', 'District2', 'District3', 'District4', 'District5', 'District6', 'FirstNm', 'LastNm', 'Duty', 'Mobile', 'Tel', 'Fax', 'EMail', 'Nation', '
Taste', 'Education', 'Company', 'CTel', 'CAddress', 'CZip', 'Family', 'Version', 'id') values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" cursor = db.cursor() cursor.execute(table_sql) #db.commit() cursor = db.cursor() reader = csv.reader(open...
Scille/umongo
umongo/fields.py
Python
mit
19,389
0.001238
"""umongo fields""" import collections import datetime as dt from bson import DBRef, ObjectId, Decimal128 import marshmallow as ma # from .registerer import retrieve_document from .document import DocumentImplementation from .exceptions import NotRegisteredDocumentError, DocumentDefinitionError from .template import ...
'BoolField', 'IntField', 'DictField', 'ListField', 'ConstantField', # 'PluckField' 'ObjectIdField', 'ReferenceField', 'GenericReferenceField', 'EmbeddedField' ) # Republish supported marshmallow fields # class RawField(BaseField, ma.field
s.Raw): # pass class StringField(BaseField, ma.fields.String): pass class UUIDField(BaseField, ma.fields.UUID): pass class NumberField(BaseField, ma.fields.Number): pass class IntegerField(BaseField, ma.fields.Integer): pass class DecimalField(BaseField, ma.fields.Decimal): def _serial...
Cynerva/jttcotm
end.py
Python
bsd-3-clause
3,326
0.001503
import pygame from pygame.locals import * from math import sin import states class EndEvent(object): text = [ "Ah, hello there. Welcome to the center of the moon!", "Oh, me? I'm just the man in the moon. I live here.", "Don't act so shocked! It's rude you know.", "I don't g...
k I hear them coming. They must really like you!" ] texture = None font = None def __init__(self, pos): self.pos = pos self.start_time = None self.time = 0.0 self.fade = None def update(self, delta, pos, player_pos): self.time += delta pos = (pos[0...
self.start_time = self.time if self.fade != None: self.fade += delta / 4.0 if self.fade > 1.0: raise states.StateChange(states.MainMenuState()) elif self.start_time: count = int((self.time - self.start_time) / 0.05) i = 0 ...
zuck/prometeo-erp
core/registration/models.py
Python
lgpl-3.0
1,316
0.003799
#!/usr/bin/env python # -*- coding: utf-8 -*- """This file is part of the prometeo project. This program is free software: you can redistribute it and/or modify it under the terms o
f the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A P...
ense along with this program. If not, see <http://www.gnu.org/licenses/> """ __author__ = 'Emanuele Bertoldi <emanuele.bertoldi@gmail.com>' __copyright__ = 'Copyright (c) 2011 Emanuele Bertoldi' __version__ = '0.0.5' from django.utils.translation import ugettext_lazy as _ from django.db import models class Activati...
DemocracyClub/UK-Polling-Stations
polling_stations/apps/data_importers/management/commands/import_falkirk.py
Python
bsd-3-clause
1,748
0.001144
from data_importers.ems_importers import BaseHalaroseCsvImporter FAL_ADMINAREAS = ( "Bo'ness", "Bonnybridge", "Denny", "Falkirk Ward 1", "Falkirk Ward 2", "Falkirk Ward 3", "Falkirk Ward 4", "Falkirk Ward 5", "Falkirk Ward 6", "Falkirk Ward 7", "Falkirk Ward 8", "Falkirk...
rd):
if ( (record.adminarea not in FAL_ADMINAREAS) and (record.pollingstationname not in FAL_INCLUDE_STATIONS) or (record.pollingstationname in FAL_EXCLUDE_STATIONS) ): return None return super().station_record_to_dict(record) def address_record_to_dict(...
Huyuwei/tvm
vta/tests/python/integration/test_benchmark_topi_conv2d.py
Python
apache-2.0
10,351
0.003188
# 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 u...
wl.height + 2 * wl.hpad - wl.hkernel) // wl.hstride + 1 fout_width = (wl.width + 2 * wl.wpad - wl.wkernel) // wl.wstride + 1 num_ops = 2 * wl.batch * fout_height * fout_width * wl.hkernel * wl.wkernel * wl.out_filter * wl.in_filter # @memoize("vta.tests.test_benchmark_topi.conv2d.verify_nhwc") def get_
ref_data(): # derive min max for act, wgt, and bias types (max non inclusive) a_min, a_max = 0 - (1 << (env.INP_WIDTH - 1)), (1 << (env.INP_WIDTH - 1)) w_min, w_max = 0 - (1 << (env.WGT_WIDTH - 1)), (1 << (env.WGT_WIDTH - 1)) b_min, b_max = 0 - 1 << (env.INP_WIDTH + env.WGT_WIDTH - 2), 1...
lafranceinsoumise/api-django
agir/people/management/commands/createsuperperson.py
Python
agpl-3.0
6,404
0.001093
import sys import os import getpass from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS from django.core import exceptions from django.utils.text import capfirst from django.utils.encoding import force_str from django.contrib.auth.password_validation import validate...
) def add_arguments(self, parser): parser.add_argument( "--email", dest="email", default=None, help="Specifies the login for the superuser.", ) parser.add_argument( "--noinput", "--no-input", action="store_f...
pt the user for input of any kind. " "You must use --email with --noinput, along with an option for " "any other required field. Superusers created with --noinput will " "not be able to log in until they're given a valid password." ), ) parser....
tpltnt/SimpleCV
SimpleCV/Tracking/__init__.py
Python
bsd-3-clause
355
0.002817
from SimpleCV.Tracking.TrackClass import Track, CAMShiftTrack, SURFTrack, LKTrack, MFTrack from SimpleCV.Tracking.CAMShiftTracker i
mport camshiftTracker from SimpleCV.Tracking.LKTracker import lkTracker from Simpl
eCV.Tracking.SURFTracker import surfTracker from SimpleCV.Tracking.MFTracker import mfTracker from SimpleCV.Tracking.TrackSet import TrackSet
Kuniwak/vint
vint/linting/policy/prohibit_missing_scriptencoding.py
Python
mit
1,557
0.001927
import chardet from vint.ast.node_type import NodeType from vint.ast.traversing import traverse, SKIP_CHILDREN from vint.linting.level import Level from vint.linting.lint_target import AbstractLintTarget from vint.linti
ng.policy.abstract_policy import AbstractPolicy from vint.linting.policy_registry import register_policy @register_policy class ProhibitMissingScriptEncoding(AbstractPolicy): description = 'Use scriptencoding when multibyte char exists' reference = ':help :scriptencoding' level = Level.WARNING has_sc...
alse def listen_node_types(self): return [NodeType.TOPLEVEL] def is_valid(self, node, lint_context): """ Whether the specified node is valid. This policy prohibit scriptencoding missing when multibyte char exists. """ traverse(node, on_enter=self._check_scriptencoding...
abalkin/numpy
numpy/lib/tests/test_utils.py
Python
bsd-3-clause
3,769
0.001061
import inspect import sys import pytest from numpy.core import arange from numpy.testing import assert_, assert_equal, assert_raises_regex from numpy.lib import
deprecate import numpy.lib.utils as utils from io import StringIO @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO") def test_lookfor(): out = StringIO() utils.lookfor('eigenvalue', module='numpy', output=out, import_modules=False) out = out.getvalue() assert_...
c2") def old_func2(self, x): return x def old_func3(self, x): return x new_func3 = deprecate(old_func3, old_name="old_func3", new_name="new_func3") def old_func4(self, x): """Summary. Further info. """ return x new_func4 = deprecate(old_func4) def old_func5(self, x): """Summary. ...
makaimc/pycontacts
morepath_jinja_sqlalchemy/app.py
Python
mit
417
0
import morepath from more.jinja2 import Jinja2App class App(Jinja2App): pass @App.path(path='') class Root(object): pass @App.view(model=Root) def hello_world(self, request): return "Hello world!" @App.html(template='base.html') def main(request): return {'name': 'matt'
} if __name__ == '__ma
in__': config = morepath.setup() config.scan() config.commit() morepath.run(App())
colaftc/webtool
top/api/rest/AreasGetRequest.py
Python
mit
285
0.031579
''' Created by auto_sdk on 2015.09.17 ''' from top.api.base import RestApi class AreasGetRequest(RestApi): def __init__(s
elf,domain='gw.api.taobao.c
om',port=80): RestApi.__init__(self,domain, port) self.fields = None def getapiname(self): return 'taobao.areas.get'
edespino/gpdb
src/test/tinc/tincrepo/mpp/models/regress/mpp_tc/regress_mpp_test_case.py
Python
apache-2.0
6,282
0.004935
""" Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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....
1) test_suite.run(test_result) self.assertEqual(test_result.testsRun, 1) self.assertEqual(len(test_result.errors), 0) self.assertEqual(len(test_result.skipped), 0) self
.assertEqual(len(test_result.failures), 1) def test_failure_gather_logs(self): test_loader = tinctest.TINCTestLoader() test_suite = test_loader.loadTestsFromName('mpp.models.regress.mpp_tc.regress_mpp_test_case.MockMPPTestCase.test_gather_logs') self.assertIsNotNone(test_suite) sel...
xyryx/SentimentAnalysis
tests/AnalyzerTests.py
Python
mit
425
0.009412
import unittest from src.Analyz
er import plot_word_embeddings from src.Labels import Labels class AnalyzerTests(unittest.TestCase): def test_plot_word_embeddings(self): plot_word_embeddings("Doc2Vec", "Test", "Objective", "Subjective", [[-3.99940408, -1.43488923],[ 3.51106635, -2.01347499], [-1.14695001, -2.10861514]],
[Labels.strong_pos, Labels.strong_pos, Labels.strong_neg])
MTG/pycompmusic
compmusic/extractors/imagelib/wav2png.py
Python
agpl-3.0
3,050
0.005246
#!/usr/bin/env python # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # # Freesound 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 (at your ...
_s.jpg)") parser.add_option("-w", "--width", action="store", dest="image_width", type="int", help="image width in pixels (default %default)") parser.add_option("-h", "--height", action="store", dest="image_height", type="int", help="image height in pixels (default %default)") parser.add_option("-f", "--fft", action="st...
action="store_true", dest="profile", help="run profiler and output profiling information") parser.set_defaults(output_filename_w=None, output_filename_s=None, image_width=500, image_height=171, fft_size=2048) (options, args) = parser.parse_args() if len(args) == 0: parser.print_help() parser.error("not enou...
itdxer/neupy
tests/plots/test_hinton.py
Python
mit
1,732
0
import pytest import numpy as np import matplotlib.pyplot as plt from neupy import plots from base import BaseTestCase class HintonDiagramTestCase(BaseTestCase): single_thread = True @pytest.mark.mpl_image_compare def test_simple_hinton(self): fig
= plt.figure() ax = fig.add_subplot(1, 1, 1) plt.sca(ax) # To test the case when ax=None weight = np.random.randn(20, 20) plots.hinton(weight, add_legend=True) return fig @pytest.mark.mpl_image_compare def test_max_weight(self): fig = plt.figure() ax ...
return fig @pytest.mark.mpl_image_compare def test_hinton_without_legend(self): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) weight = np.random.randn(20, 20) plots.hinton(weight, ax=ax, add_legend=False) return fig @pytest.mark.mpl_image_compare ...
MTG/essentia
test/src/unittests/rhythm/test_superfluxextractor.py
Python
agpl-3.0
4,892
0.00879
#!/usr/bin/env python # Copyright (C) 2006-2021 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia 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 (FSF), e...
self.assertConfigureFails(SuperFluxExtractor(), { 'combine': -1}) self.assertConfigureFails(SuperFluxExtr
actor(), { 'frameSize': -1}) self.assertConfigureFails(SuperFluxExtractor(), { 'hopSize': -1}) self.assertConfigureFails(SuperFluxExtractor(), { 'ratioThreshold': -1}) self.assertConfigureFails(SuperFluxExtractor(), { 'sampleRate': -1}) self.assertConfigureFails(SuperFluxExtractor(), { '...
tiankangkan/paper_plane
k_util/hash_util.py
Python
gpl-3.0
257
0
# -*- cod
ing: UTF-8 -*- """ Desc: django util. Note: --------------------------------------- # 2016/04/30 kangtian created """ from hashlib import md5 def gen_md5(content_str): m = md5() m.update(c
ontent_str) return m.hexdigest()
Solanar/CMPUT410-Project
DisSoNet/DisSoNet/urls.py
Python
apache-2.0
2,954
0.003385
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings admin.autodiscover() from front.views import * from front.views import views as front_views from django.views.decorators.csrf import csrf_exempt if not settings.DEBUG: s = {'SSL': settings.ENABL...
(r'^accounts/view/', Use
rView.as_view(), s, name='user_view'), url(r'^accounts/register/', RegisterView.as_view(), s, name='register'), url(r'^accounts/reset/$', front_views.reset, s, name='reset'), url(r'^accounts/reset/e/(?P<email>[\w-]+)/$', front_views.reset, s, name='reset'), url(r'^accounts/reset/done/$', front_v...
xaedes/canopen_301_402
src/canopen_301_402/can402/ops/set_target.py
Python
mit
1,247
0.022454
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from funcy import partial from canopen_301_402.constants import * from canopen_301_402.async.async_chain import AsyncChain from canopen_301_402.asyn
c.sdo_write_object import SdoWriteObject from canopen_301_402.can402.ops.notify_new_target import NotifyNewTarget import struct class SetTarget(AsyncChain): """docstring for SetTarget""" def __init__(sel
f, node, value, relative=False, immediatly=False, target_type="Position", *args, **kwargs): parameter_name = "Target " + target_type self.node = node self.value = value self.relative = relative self.immediatly = immediatly set_target = partial(SdoWriteObject, ...
Aluriak/24hducode2016
src/source_tourinsoft/request_data.py
Python
unlicense
2,237
0.000447
""" This module contains tools used to get data using tourinsoft's API. Request outputs JSON which is converted to a dictionary. """ import requests URL = 'http://wcf.tourinsoft.com/Syndication/3.0/cdt72/' EVENT_URL = 'e9a8e2bf-c933-4831-9ebb-87eec559a21a/' PLACES_URL = '969e24f9-75a2-4cc6-a46c-db1f6ebbfe97/' # sh...
tead of values (doesn't seem to matter in practice) - event: search in events DB (if False, will search in places DB) Output: a tuple of dictionaries (one dictionary for one object) containing the properties of each object. """ filters_str = ('&$filter=' + key + " eq '" + value + "'" ...
collection, '?$format=json', ''.join(filters_str), '&metadata' if metadata else '')) # Values field contains a list of all objects (other fields are useless) # Flatten dictionary formats nested dictionaries (see modul...
markgw/jazzparser
bin/models/chordlabel/admin.py
Python
gpl-3.0
5,587
0.00698
#!/usr/bin/env ../../jazzshell """ Supplies a set of admin operations for trained models. ============================== License ======================================== Copyright (C) 2008, 2010-12 University of Edinburgh, Mark Granroth-Wilding This file is part of The Jazz Parser. The Jazz Parser is free softw...
% command_args[0] print commands[command_args[0]][1] sys.exit(0) elif command in commands: # Run the command commands[command][0](command_args) else: # The command wasn't found in our defined commands
raise CommandError, "unknown command '%s'. Available "\ "commands are: %s" % (command, ", ".join(all_commands)) except CommandError, err: print "Error running command: %s" % err sys.exit(1) except ModelLoadError, err: print "Error loading the model: %s" % err ...
KuttKatrea/sublime-toolrunner
test/print.py
Python
mit
32
0
prin
t("Salutations, Universe!")
shobhitmishra/CodingProblems
LeetCode/Session3/testMoveZero.py
Python
mit
422
0.021327
class Solution: def moveZeroes(nums): j=1 for i in range(len(nums)-1): if nums[i] == 0: while j < len(nums): if nums[j] == 0: j+=1 else: #swap nums[i], nums[j]...
s p
rint(Solution.moveZeroes([0,1,2,3]))
watchdogpolska/feder
feder/institutions/migrations/0011_auto_20170808_0308.py
Python
mit
211
0
# Generated by Django 1.11.2 on 2017-08-08 03:08 from django.db import migrations class Migrati
on(migrations.M
igration): dependencies = [("institutions", "0010_auto_20170808_0252")] operations = []
deets/pyCamBam
tests/base.py
Python
gpl-2.0
295
0.00678
# import os import unittest
class TestBase(unittest.TestCase): @classmethod def datafilename(cls, name): fname = os.path.join( os.path.dirname(__file__), "data
", name, ) assert os.path.exists(fname) return fname
Andr3iC/juriscraper
opinions/united_states/state/washctapp_p.py
Python
bsd-2-clause
397
0
import wash class Si
te(wash.Site): def __init__(self, *args, **kwargs): super(Site, self).__init__(*args, **kwargs) self.court_id = self.__module__ self.courtLevel = 'C' self.pubStatus = 'PUB' self._set_parameters() def _get_case_names(self): path = "{base}/td[4]/text()".format(base...
MSchuwalow/StudDP
studdp/picker.py
Python
mit
5,867
0.002045
#!/usr/bin/python3 # This code is available for use under CC0 (Creative Commons 0 - universal). # You can copy, modify, distribute and perform the work, even for commercial # purposes, all without asking permission. For more information, see LICENSE.md or # https://creativecommons.org/publicdomain/zero/1.0/ # usage: ...
c = stdscr.getch() if c == ord('q') or c == ord('Q'): self.aborted = True break elif c == curses.KEY_UP: self.cursor = self.cursor - 1
elif c == curses.KEY_DOWN: self.cursor = self.cursor + 1 #elif c == curses.KEY_PPAGE: #elif c == curses.KEY_NPAGE: elif c == ord(' '): self.all_options[self.selected]["selected"] = \ not self.all_options[self.selected]["se...