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
silenci/neutron
neutron/plugins/ml2/drivers/mech_sriov/agent/sriov_nic_agent.py
Python
apache-2.0
17,661
0.001019
# Copyright 2014 Mellanox Technologies, Ltd # # 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 t...
evice_info['updated'] = updated_devices & curr_devices # we need to clean up after devices are removed device_info['removed'] = registered_devices - curr_devices
return device_info def _device_info_has_changes(self, device_info): return (device_info.get('added') or device_info.get('updated') or device_info.get('removed')) def process_network_devices(self, device_info): resync_a = False resync_b = False ...
chimmu/hailuo
acceptor.py
Python
gpl-2.0
474
0.006329
from conn import Connection import dispatch import socket class Acceptor(Connection): def __init__(self, port): self.dispatcher = dispatch.Dispatch(1) self.dispatcher.start() self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM, 0) self.sock
.bind(("127.0.0.1", port)) self.sock.listen(1024) def handleRead(self): cli, addr = self.sock.accept() # cli.setblocking(0) self.dispatcher.dispatch(cli)
xuehao/stickpython
Flask_Web_Development/chapter_02/2c/hello_2c.py
Python
mit
320
0.003125
from flask import Flask from flask.ext.script import Manager app = Flask(__name__) manager = Manager(ap
p) @app.route('/') def index(): return '<h1>Hello World!</h1>' @app.route('/user/<name>') def user(name): return '<h1>Hello, {name}!</h1>'.format(**locals())
if __name__ == '__main__': manager.run()
sugimotokun/VirtualCurrencySplunk
bin/scripts/vc_usd_nt.py
Python
apache-2.0
1,321
0.004542
# # Copyright (c) 2017 Sugimoto Takaaki # # 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 i...
tps://api.cryptonator.com/api/ticker/doge-usd' d['xrp']='https://api.cryptonator.com/api/ticker/xrp-usd' d['eth']='https://api.cryptonator.com/api/ticker/eth-usd' d['mona']='https://api.cryptonator.com/api/ticker/mona-usd' outputString = "" for url in d.values(): sock = urllib.urlopen(url)
jsonString = sock.read() sock.close() jsonCurrency = json.loads(jsonString) price = jsonCurrency['ticker']['price'] outputString = outputString + price + " " print outputString
tanglei528/nova
nova/tests/api/openstack/compute/contrib/test_simple_tenant_usage.py
Python
apache-2.0
19,168
0.000313
# 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...
'root_gb': ROOT_GB, 'ephemeral_gb': EPHEMERAL_GB, 'memory_mb': MEMORY_MB, 'name': 'fakeflavor', 'flavorid': 'foo', 'rxtx_factor': 1.0, 'vcpu_weight': 1, 'swap': 0,
'created_at': None, 'updated_at': None, 'deleted_at': None, 'deleted': 0, 'disabled': False, 'is_public': True, 'extra_specs': {'foo': 'bar'}} def get_fake_db_instance(start, end, instance_id, tena...
jorvis/biocode
sandbox/jorvis/correct_RNAs_missing_genes.py
Python
mit
2,324
0.009897
#!/usr/bin/env python3 """ This housekeeping script reads a GFF3 file and writes a new one, adding a 'gene' row for any RNA feature which doesn't have one. The coordinates of the RNA will be copied. The initial use-case here was a GFF file dumped from WebApollo which had this issue. In this particular use case, the...
As which lack them') ## output file to be written parser.add_argument('-i', '--input', type=str, required=True, help='Path to the input GFF3 file' ) parser.add_argument('-o', '--output', type=str, required=True, help='Output GFF3 file to write' ) args = parser.parse_args() infile = open(args.input...
e: if line.startswith('#'): ofh.write(line) continue line = line.rstrip() cols = line.split("\t") if len(cols) != 9: ofh.write("{0}\n".format(line) ) continue id = gff.column_9_value(cols[8], 'ID') pa...
aeklant/scipy
scipy/stats/tests/test_rank.py
Python
bsd-3-clause
7,448
0.000403
import numpy as np from numpy.testing import assert_equal, assert_array_equal from scipy.stats import rankdata, tiecorrect class TestTieCorrect(object): def test_empty(self): """An empty array requires no correction, should return 1.0.""" ranks = np.array([], dtype=np.float64) c = tiecor...
ys with no ties require no correction.""" ranks = np.arange(2.0) c = tiecorrect(ranks) assert_e
qual(c, 1.0) ranks = np.arange(3.0) c = tiecorrect(ranks) assert_equal(c, 1.0) def test_basic(self): """Check a few basic examples of the tie correction factor.""" # One tie of two elements ranks = np.array([1.0, 2.5, 2.5]) c = tiecorrect(ranks) T = 2...
iamahuman/angr
angr/analyses/propagator/engine_base.py
Python
bsd-2-clause
1,026
0.001949
import logging from ...engines.light import SimEngineLight from ...errors import SimEngineError l = logging.getLogger(name=__name__) class SimEnginePropagatorBase(SimEngineLight): # pylint:disable=abstract-method def __init__(self, stack_pointer_tracker=None, project=None): super().__init__() ...
engine self._stack_pointer_tracker = stack_pointer_tracker def process(self, state, *args, **kwargs): self.project = kwargs.pop('project', None) self.base_state = kwargs.pop('base_state', None) self._load_callback = kwargs.pop('load_callback', None) try: self._pr...
l.error(ex, exc_info=True) return self.state
gangadhar-kadam/verve_test_erp
erpnext/manufacturing/doctype/production_order/test_production_order.py
Python
agpl-3.0
5,084
0.023013
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import unittest import frappe from frappe.utils import flt, get_datetime from erpnext.stock.doctype.purchase_receipt.test_purchase_receipt import set_p...
) s.submit() # from wip to fg s = frappe.get_doc(make_stock_entry(pro_doc.name, "Manufacture", 4)) s.fiscal_year = "_Test Fiscal Yea
r 2013" s.posting_date = "2013-01-03" s.insert() s.submit() self.assertEqual(frappe.db.get_value("Production Order", pro_doc.name, "produced_qty"), 4) planned1 = frappe.db.get_value("Bin", {"item_code": "_Test FG Item", "warehouse": "_Test Warehouse 1 - _TC"}, "planned_qty") self.assertEqual(planned1 -...
chaowu2009/stereo-vo
tools/test_ORB.py
Python
mit
621
0.022544
i
mport numpy as np import cv2 from matplotlib import pylab as plt # Ref: http://www.pyimagesearch.com/2015/07/16/where-did-sift-and-surf-go-in-opencv-3/ picNumber = 1 filename = "/home/cwu/project/stereo-calibration/calib_imgs/3/left/left_" + str(picNumber) +".jpg" img = cv2.imread(filename) gray = cv2.cvtColor(img...
(img,None) # compute the descriptors with BRIEF kp, des = orb.compute(img, kp) img = cv2.drawKeypoints(img,kp,None,(0,255,0),4) cv2.imshow('img',img) cv2.waitKey(1000) cv2.imwrite('orb_keypoints.jpg',img)
christianwgd/mezzanine
mezzanine/galleries/migrations/0001_initial.py
Python
bsd-2-clause
1,889
0.004235
# -*- coding: utf-8 -*- from __future__ import unicode_literals
from django.db import models, migrations import mezzanine.core.fields class Migration(migrations.Migration): dependencies = [ ('pages', '__fi
rst__'), ] operations = [ migrations.CreateModel( name='Gallery', fields=[ ('page_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='pages.Page', on_delete=models.CASCADE)), ('content', mezzanine...
jbzdarkid/Random
mismatched.py
Python
apache-2.0
1,737
0.011514
# -*- coding: utf-8 -*- from wikitools.api import APIRequest from wikitools.wiki import Wiki from wikitools.page import Page from urllib2 import quote pairs = [ ['"', '"'], ['(', ')'], ['[', ']'], ['{', '}'], ['<!--', '-->'], ['<', '>'], ['<gallery', '</gallery>'], ['<includeonly>', '</includeonly>'], ...
) print 'Found', len(titles), 'pages' for title in titles: page = Page(wiki, title) page.getWikiText() text
= page.getWikiText().lower() printed_link = False for pair in pairs: if text.count(pair[0]) != text.count(pair[1]): if not printed_link: print '='*80 print 'https://wiki.teamfortress.com/w/index.php?action=edit&title=%s' % quote(title.encode('utf-8')) printed_link = True indi...
js850/pele
pele/takestep/displace.py
Python
gpl-3.0
2,126
0.01317
''' Created on Jun 6, 2012 @author: vr274 ''' import numpy as np from generic import TakestepSlice, TakestepInterface from pele.utils import rotations __all__ = ["RandomDisplacement", "UniformDisplacement", "RotationalDisplacement", "RandomCluster"] class RandomDisplacement(TakestepSlice): '''Random...
= self.stepsize * rotations.vector_random_uniform_hypersphere(3) class RotationalDisplacement(TakestepSlice): '''Random rotation for angle axis vector RotationalDisplacement performs a proper random rotation. If the coordinate array contains positions and orientations, make sure to specify the cor
rect slice for the angle axis coordinates. ''' def takeStep(self, coords, **kwargs): """ take a random orientational step """ c = coords[self.srange] for x in c.reshape(c.size/3,3): rotations.takestep_aa(x, self.stepsize) class Ra...
plotly/python-api
packages/python/plotly/plotly/validators/scatterpolar/marker/_sizemode.py
Python
mit
537
0.001862
import _plotly_utils.basevalidators class SizemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__(
self, plotly_name="sizemode", parent_name="scatterpolar.marker", **kwargs ): super(SizemodeValidat
or, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "info"), values=kwargs.pop("values", ["diameter", "area"]), **kwargs )
joaormatos/anaconda
Anaconda/pyglet/canvas/win32.py
Python
gpl-3.0
3,404
0.00235
#!/usr/bin/python # $Id:$ from base import Display, Screen, ScreenMode, Canvas from pyglet.libs.win32 import _kernel32, _user32, types, constants from pyglet.libs.
win32.constants import * from pyglet.libs.win32.types import * class Win32Display(Display): def get_screens(self): screens = [] def enum_proc(hMonitor, hdcMonitor, lprcMonitor, dwData): r = lprcMonitor.contents width = r.right - r.left height = r.bottom - r.top ...
eturn True enum_proc_type = WINFUNCTYPE(BOOL, HMONITOR, HDC, POINTER(RECT), LPARAM) enum_proc_ptr = enum_proc_type(enum_proc) _user32.EnumDisplayMonitors(NULL, NULL, enum_proc_ptr, 0) return screens class Win32Screen(Screen): _initial_mode = None def __init__(self, display, han...
cadyyan/codeeval
python/40_self_describing_numbers.py
Python
gpl-3.0
379
0.007916
import re import sys def is_s
elf_describing(n): for i in range(len(n)): c = n[i] if int(c) != len(re.fin
dall(str(i), n)): return False return True with open(sys.argv[1], 'r') as fh: for line in fh.readlines(): line = line.strip() if line == '': continue print 1 if is_self_describing(line) else 0
anhstudios/swganh
data/scripts/templates/object/mobile/shared_dressed_rebel_brigadier_general_rodian_female_01.py
Python
mit
476
0.046218
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_rebel_brigadier_general_rodian_female_01.iff" result.a...
me("npc_name","rodian_base_female") #### BEGIN MODIFICATIONS #### #### END MOD
IFICATIONS #### return result
glidernet/ogn-python
app/main/matplotlib_service.py
Python
agpl-3.0
1,400
0.002857
from app import db from app.model import DirectionStatistic import random import numpy as np import matplotlib.pyplot as plt from
matplotlib.figure import Figure def create_range_figure2(sender_id): fig = Figure() axis = fig.add_subplot(1, 1, 1) xs = range(100) ys = [random.randint(1, 50) for x in xs] axis.plot(xs, ys) return fig def create_range_figure(sender_id): sds = db.session.query(DirectionStatistic) \ ...
ig = Figure() direction_data = sds.direction_data max_range = max([r['max_range'] / 1000.0 for r in direction_data]) theta = np.array([i['direction'] / 180 * np.pi for i in direction_data]) radii = np.array([i['max_range'] / 1000 if i['max_range'] > 0 else 0 for i in direction_data]) width = np.ar...
souravbadami/oppia
core/domain/visualization_registry.py
Python
apache-2.0
2,447
0
# coding: utf-8 # # Copyright 2014 The Oppia 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 requi...
return cls.visua
lizations_dict[visualization_id] @classmethod def get_all_visualization_ids(cls): """Gets a visualization class by its id (which is also its class name). """ if not cls.visualizations_dict: cls._refresh_registry() return cls.visualizations_dict.keys()
OptimoJoe/Optizelle
src/python/Optizelle/Unconstrained/Algorithms.py
Python
bsd-2-clause
863
0.011587
__all__ = [ "getMin" ] __doc__ = "Different algorithms used for optimization" import Optizelle.Unconstrained.State import Optizelle.Unconstrained.Functions from Optizelle.Utility import * from Optizelle.Properties import * from Optizelle.Functions import
* def getMin(X, msg, fns, state, smanip=None): """Solves an unconstrained optimization problem Basic solve: getMin(X,msg,fns,state) Solve with a state manipulator: getMin(X,msg,fns,state,smanip) """ if smanip is None: smanip = StateManipulator() # Check the arguments checkVectorSpa...
aging("msg",msg) Optizelle.Unconstrained.Functions.checkT("fns",fns) Optizelle.Unconstrained.State.checkT("state",state) checkStateManipulator("smanip",smanip) # Call the optimization UnconstrainedAlgorithmsGetMin(X,msg,fns,state,smanip)
google/timesketch
api_client/python/timesketch_api_client/user.py
Python
apache-2.0
3,300
0
# Copyright 2020 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 required by applicable law or a...
""" if not new_password: raise ValueError('No new password supplied.') if not isinstance(new_password, str): raise ValueError('Password needs to be a string value.') data = {'password': new_password} resource_url = f
'{self.api.api_root}/{self.resource_uri}' response = self.api.session.post(resource_url, json=data) return error.check_return_status(response, logger) @property def groups(self): """Property that returns the groups the user belongs to.""" data = self._get_data() groups =...
LaurentCabaret/pyVhdl2Sch
tools/tools.py
Python
bsd-2-clause
177
0
#!/usr/bin/python # -*- coding: utf-8 -*- import
os import sys class Options: def __init__(self): self.color =
"black" self.verbose = False pass
Prashant-Surya/addons-server
src/olympia/stats/tests/test_views.py
Python
bsd-3-clause
38,979
0
# -*- coding: utf-8 -*- import csv import datetime import os import shutil import json from django.http import Http404 from django.test.client import RequestFactory import mock from pyquery import PyQuery as pq from olympia import amo from olympia.amo.tests import TestCase from olympia.amo.urlresolvers import revers...
ogin_as_visitor() self._check_it(self.public_views_gen(format='json'), 200)
self._check_it(self.private_views_gen(format='json'), 403) def test_private_addon_contrib_stats_group(self): # Logged in with stats and contrib stats group. user = UserProfile.objects.get(email='nobodyspecial@mozilla.com') group1 = Group.objects.create(name='Stats', rules='Stats:View') ...
hultberg/ppinnlevering
core/migrations/0016_auto_20151001_0714.py
Python
apache-2.0
843
0.001186
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('core', '0015_auto_20150928_0850'), ] ...
operations = [ migrations.CreateModel( name='UserVote', fields=[ ('id', models.AutoField(auto_created=True, verbose_name='ID', serialize=False, primary_key=True)), ('bidrag', models.ForeignKey(to='core.Bidrag')),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)), ], ), migrations.AlterUniqueTogether( name='uservote', unique_together=set([('bidrag', 'user')]), ), ]
gunan/tensorflow
tensorflow/python/keras/layers/preprocessing/discretization.py
Python
apache-2.0
4,879
0.005329
# Copyright 2019 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...
ensorflow.python.keras.engine.base_layer import Layer from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops.ragged import ragged_functional_ops from tensorflow.python.ops.ragged import ragged_tensor INTEGER = "int" BINARY = "binary" class Discretization(Lay...
ex or a one-hot vector indicating which range each element was placed in. What happens in `adapt()`: The dataset is examined and sliced. Input shape: Any `tf.Tensor` or `tf.RaggedTensor` of dimension 2 or higher. Output shape: The same as the input shape if `output_mode` is 'int', or `[output_s...
rays/ipodderx-core
khashmir/khash.py
Python
mit
3,533
0.01019
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
30) ### Test Cases ### import unittest class NewID(unittest.TestCase): def testLength(self): self.assertEqual(len(newID()), 20) def t
estHundreds(self): for x in xrange(100): self.testLength class Intify(unittest.TestCase): known = [('\0' * 20, 0), ('\xff' * 20, 2L**160 - 1), ] def testKnown(self): for str, value in self.known: self.assertEqual(intify(str), value) def test...
dbaynard/pynomo
examples/ex_compound_nomo_1.py
Python
gpl-3.0
4,466
0.031572
""" ex_compound_nomo_1.py Compound nomograph: (A+B)/E=F/(CD) Copyright (C) 2007-2009 Leif Roschier 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 L...
s':0, 'tick_text_levels':
0, 'tick_side':'right', 'title_draw_center':True, 'title_opposite_tick':False, 'tag':'r1' } E_params={ 'u_min':1.0, 'u_max':10.0, 'function':lambda u:u, 'title':r'$E$', 'tick_levels':3, 'tick_text_levels':1, 'tick_si...
Gargamel1989/Seasoning-old
Seasoning/general/admin.py
Python
gpl-3.0
103
0.009709
from django.
contrib import admin from general.models import StaticPage admin.site.register(StaticP
age)
imk1/IMKTFBindingCode
getSequencesForSNPs.py
Python
mit
2,698
0.021497
import sys from Bio import SeqIO SNPTOPEAKFILENAME = sys.argv[1] GENOMEFILENAME = sys.argv[2] DISTANCE = int(sys.argv[3]) BINDALLELESEQFILENAME = sys.argv[4] NONBINDALLELEFILENAME = sys.argv[5] FIRSTPEAKCOL = int(sys.argv[6]) # 0-INDEXED def getSNPInfo(SNPToPeakLine): # Get the SNP and peak location from ...
ion[1]) - 1 bindAlleleSeq[SNPLocationInSeq] = SNPAlleles[0] nonBindAlleleSeq[SNPLocationInSeq] = SNPAlleles[1] lastPeakLocation =
peakLocation [SNPLocation, SNPAlleles, peakLocation] = getSNPInfo(SNPToPeakFile.readline().strip()) print numSharingPeak bindAlleleSeqFile.write("".join(bindAlleleSeq).upper() + "\n") nonBindAlleleSeqFile.write("".join(nonBindAlleleSeq).upper() + "\n") SNPToPeakFile.close() bindAlleleSeqFile.close() no...
matbra/radio_fearit
build/lib/python3.3/site-packages/pocketsphinx-0.0.9-py3.3-linux-x86_64.egg/pocketsphinx/pocketsphinx.py
Python
gpl-3.0
17,246
0.010495
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.10 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. """ This documentation was automatically generated using original comments in Doxygen format. As some C types and d...
name, description = imp.find_module('_pocketsphinx', [dirname(__file__)]) except ImportError: import _pocketsphinx return _pocketsphinx if fp is not None: try: _mod = imp.load_module('_pocket
sphinx', fp, pathname, description) finally: fp.close() return _mod _pocketsphinx = swig_import_helper() del swig_import_helper else: import _pocketsphinx del version_info try: _swig_property = property except NameError: pass # Python < 2.2 doesn't have 'prope...
pagarme/pagarme-python
tests/resources/dictionaries/subscription_dictionary.py
Python
mit
1,513
0
from pagarme import card from pagarme import plan from tests.resources import pagarme_test from tests.resources.dictionaries import card_dictionary from tests.resources.dictionaries import customer_dictionary from tests.resources.dictionaries import plan_dictionary from tests.resources.dictionaries import transaction_d...
", "postback_url": POSTBACK_URL } CHARGES = { "charges": "1" } CREDIT_CARD_PERCENTAGE_SPLIT_RULE_SUBSCRIPTION = { "plan_id": NO_TRIAL_PLAN['id'], "customer": customer_dictionary.CUSTOMER, "card_id": CARD['id'], "payment_method": "credit_card", "postback_url": POSTBACK_URL, "split_rules...
tionary.CUSTOMER, "card_id": CARD['id'], "payment_method": "credit_card", "postback_url": POSTBACK_URL } UPDATE = { "payment_method": "boleto" }
etingof/pyasn1-modules
tests/test_rfc7292.py
Python
bsd-2-clause
8,295
0.000362
# # This file is part of pyasn1-modules software. # # Created by Russ Housley # Copyright (c) 2019, Vigil Security, LLC # License: http://snmplabs.com/pyasn1/license.html # import sys import unittest from pyasn1.codec.der.decoder import decode as der_decoder from pyasn1.codec.der.encoder import encode as der_encoder f...
ters'].hasValue()) authsafe, rest = der_decoder( asn1Object['authSafe']['content'], asn1Spec=rfc7292.AuthenticatedSafe(), decodeOpenTypes=True) self.assertFalse(rest) self.assertTrue(authsafe.prettyPrint()) self.assertEqual( asn1Object['a...
r(authsafe)) for ci in authsafe: self.assertEqual(rfc5652.id_data, ci['contentType']) sc, rest = der_decoder( ci['content'], asn1Spec=rfc7292.SafeContents(), decodeOpenTypes=True) self.assertFalse(rest) self.assertTrue(sc.prettyPr...
jigarkb/CTCI
LeetCode/070-E-ClimbingStairs.py
Python
mit
877
0.00114
# You are climbing a stair case. It takes n steps to reach to the top. # # Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? # # Note: Given n will be a positive integer. # # Example 1: # # Input: 2 # Output: 2 # Explanation: There are two ways to climb to the top. #
1. 1 step + 1 step # 2. 2 steps # # Example 2: # # Input: 3 # Output: 3 # Explanation: There are three ways to climb to the top. # 1. 1 step + 1 step + 1 step # 2. 1 step + 2 steps # 3. 2 steps + 1 step class Solution(object): def climbStairs(self, n): """
:type n: int :rtype: int """ table = [1, 2] i = 2 while i < n: table.append(table[i-1] + table[i-2]) i += 1 return table[n-1] # Note: # Generate two trees one with 1 step and other with 2 step and add both
xyloeric/pi
piExp/pi/views.py
Python
bsd-3-clause
101
0.029703
from
django.http import HttpResponse def hello_world(request): return HttpResponse("Hello, w
orld.")
if1live/easylinker
easylinker/cli.py
Python
mit
658
0.004559
#-*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import print_function import sys if sys.version_info[0] == 2: reload(sys) sys.setdefaultencoding('utf-8') from . import config from . import parsers def main(): if len(sys.argv) == 2: filename = sys.argv[1] fi...
else: msg = 'Usage: {} <metadata>'.format(sys.argv[0]) print(msg) pri
nt('\nPredefined Variables') for k, v in config.PREDEFINED_VARIABLE_TABLE.items(): print('{}\t: {}'.format(k, v)) if __name__ == '__main__': main()
masayukig/tempest
tempest/api/image/v2/admin/test_images.py
Python
apache-2.0
2,341
0
# Copyright 2018 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
) @decorators.idempotent_id('646a6eaa-135f-4493-a0af-12583021224e') def test_create_image_owner_param(self): # NOTE: Create image with owner different from tenant owner by # using "owner" parameter requires an admin privileges. random_id = data_utils.rand_uuid_hex() image = self....
self.addCleanup(self.admin_client.delete_image, image['id']) image_info = self.admin_client.show_image(image['id']) self.assertEqual(random_id, image_info['owner']) @decorators.related_bug('1420008') @decorators.idempotent_id('525ba546-10ef-4aad-bba1-1858095ce553') def test_update_i...
mccdaq/mcculw
examples/ui/DaqDevDiscovery01.py
Python
mit
5,694
0
""" File: DaqDevDiscovery01.py Library Call Demonstrated: mcculw.ul.get_daq_device_inventory() mcculw.ul.create_daq_device() mcculw.ul.release_daq_device() Purpose: Discovers DAQ devices and assigns board number to ...
mcculw.ul.flash_led() """ from __future__ import absolute_import, division, print_function from builtins import * # @UnusedWildImport import tkinter as tk from tkinter import StringVar from tkinter.ttk import Combobox # @UnresolvedImport from mcculw import ul from mcculw.enums import InterfaceType from mcc...
i_examples_util import UIExample, show_ul_error class DaqDevDiscovery01(UIExample): def __init__(self, master): super(DaqDevDiscovery01, self).__init__(master) self.board_num = 0 self.device_created = False # Tell the UL to ignore any boards configured in InstaCal ul.ign...
culturagovbr/sistema-nacional-cultura
apiv2/filters.py
Python
agpl-3.0
6,975
0.001434
from django.db.models import Q from django_filters import rest_framework as filters from adesao.models import SistemaCultura, UFS from planotrabalho.models import Componente class SistemaCulturaFilter(filters.FilterSet): ente_federado = filters.CharFilter( field_name='ente_federado__nome__unaccent', loo...
', lookup_expr=('gte')) data_fundo_cultura_cnpj_max = filters.DateFilter( field_name='fundo_cultura__comprovante_cnpj__data_en
vio', lookup_expr=('lte')) data_plano_min = filters.DateFilter( field_name='plano__data_publicacao', lookup_expr=('gte')) data_plano_max = filters.DateFilter( field_name='plano__data_publicacao', lookup_expr=('lte')) data_plano_meta_min = filters.DateFilter( field_name='plano__metas_...
yephper/django
django/db/models/query_utils.py
Python
bsd-3-clause
13,827
0.000579
""" Various data structures used in query construction. Factored out from django.db.models.query to avoid making the main module very large and/or so that they can be used by other modules without getting into circular import difficulties. """ from __future__ import unicode_literals import inspect from coll...
def register_lookup(cls, lookup, lookup_name=None): if lookup_name is None: lookup_name = lookup.lookup_name if
'class_lookups' not in cls.__dict__: cls.class_lookups = {} cls.class_lookups[lookup_name] = lookup return lookup @classmethod def _unregister_lookup(cls, lookup, lookup_name=None): """ Remove given lookup from cls lookups. For use in tests only as it's ...
googleinterns/audio_synthesis
experiments/representation_study/train_spec_gan.py
Python
apache-2.0
3,424
0.003505
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
h, real, generated:\ save_helper.save_wav_data( epoch, real, generated, SAMPLING_RATE, RESULT_DIR, get_waveform ) spec_gan_model = wgan.WGAN( normalized_raw_dataset, generator, [discriminator], Z_DIM, generator_optimizer, discriminator_optimizer, discriminator_trainin
g_ratio=D_UPDATES_PER_G, batch_size=BATCH_SIZE, epochs=EPOCHS, checkpoint_dir=CHECKPOINT_DIR, fn_save_examples=save_examples ) spec_gan_model.restore('ckpt-129', 1290) spec_gan_model.train() if __name__ == '__main__': main()
spektom/incubator-airflow
airflow/providers/google/marketing_platform/operators/search_ads.py
Python
apache-2.0
7,440
0.00121
# # 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...
n # "AS IS" BASIS, WITHOUT WARRANTIES OR CO
NDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """ This module contains Google Search Ads operators. """ from tempfile import NamedTemporaryFile from typing import Any, Dict, Optional from airflow import Airflow...
Painatalman/python101
sources/101_test.py
Python
apache-2.0
519
0.003854
from fruits import validate_fruit fruits = ["banana", "lemon", "apple", "orange", "batman"] print fruits def list_fruits(fruits, byName=True): if byName: # WARNING: this won't make a copy of the list and return it. It
will change the list FOREVER fruits.sort() for index, fruit in enumerate(fruits): if validate_fruit(fruit): print "Fruit nr %d is %s" % (index, fruit) else: print "This %s is no fr
uit!" % (fruit) list_fruits(fruits) print fruits
epssy/hue
desktop/libs/libzookeeper/src/libzookeeper/models.py
Python
apache-2.0
1,274
0.007064
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
read_only=True): zk = KazooClient(hosts=ensemble, read_only=read_only, sasl_server_principal=PRINCIPAL_NAME.get()) zk.start() children_data = [] children = zk.get_children(namespace) for node in children: data, stat = zk.get("%s/%s" % (namespace, node)) children_data.append(data) zk.stop() ...
children_data
tlevine/django-inplaceedit
testing/run_tests.py
Python
lgpl-3.0
1,189
0.000841
#!/usr/bin/env python # Copyright (c) 2010-2013 by Yaco Sistemas <goinnn@gmail.com> or <pmartin@yaco.es> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License...
neral Public License # along with this programe. If not, see <http://www.gnu.org/licenses/>. import django import os import sys from django.conf import ENVIRONMENT_VARIABLE from django.core import management if len(sys.argv) == 1: os.environ[ENVIRONMENT_VARIABLE] = 'testing.settings' else: os.environ[ENVIRO...
') else: management.call_command('test', 'testing.unit_tests')
seanxwzhang/LeetCode
Airbnb/preference_list.py
Python
mit
788
0.007003
# 每个人都有一个preference的排序,在不违反
每个人的preference的情况下得到总体的preference的排序 拓扑排序解决(https://instant.1point3acres.com/thread/207601) import itertools import collections def preferenceList1(prefList): # topological sort 1 pairs = [] for lis in prefList: for left, right in zip(lis, lis[1:]): pairs
+= (left, right), allItems, res = set(itertools.chain(*pairs)), [] while pairs: free = allItems - set(zip(*pairs)[1]) if not free: None res += list(free) pairs = filter(free.isdisjoint, pairs) allItems -= free return res + list(allItems) print(preference...
pattisdr/osf.io
api_tests/nodes/views/test_view_only_query_parameter.py
Python
apache-2.0
15,854
0.000442
import pytest from api.base.settings.defaults import API_BASE from osf_tests.factories import ( ProjectFactory, AuthUserFactory, PrivateLinkFactory, ) from osf.utils import permissions @pytest.fixture() def admin(): return AuthUserFactory() @pytest.fixture() def base_url(): return '/{}nodes/'.fo...
contributors = res.json['data']['embeds']['contributors']['data'] for contributor in contributors: assert contributor['id'].split('-')[1] in valid_contributors # test_public
_node_with_link_anonymous_does_not_expose_user_id res = app.get(public_node_one_url, { 'view_only': public_node_one_anonymous_link.key, 'embed': 'contributors', }) assert res.status_code == 200 embeds = res.json['data'].get('embeds', None) assert embeds is...
mosajjal/mitmproxy
test/mitmproxy/net/test_wsgi.py
Python
mit
3,186
0.000942
from io import BytesIO import sys from mitmproxy.net import wsgi from mitmproxy.net.http import Headers def tflow(): headers = Headers(test=b"value") req = wsgi.Request("http", "GET", "/", "HTTP/1.1", headers, "") return wsgi.Flow(("127.0.0.1", 8888), req) class ExampleApp: def __init__(self): ...
')] start_response(status, response_headers) start_response(status, response_headers) assert b"Internal Server Error" in self._serve(app) def test_serve_single_err(self): def app(environ, start_response): try: raise ValueError("foo") e...
pe', 'text/plain')] start_response(status, response_headers, ei) yield b"" assert b"Internal Server Error" in self._serve(app) def test_serve_double_err(self): def app(environ, start_response): try: raise ValueError("foo") except: ...
mgrygoriev/CloudFerry
cloudferrylib/os/actions/transport_ephemeral.py
Python
apache-2.0
7,851
0
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the License); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
ee the License for the specific language governing permissions and# # limitations under the License. import copy import hashlib import os from fabric.api import env from fabric.api import run from fabric.api import settings from oslo_config import cfg from cloudferrylib.base.action import action from cloudferrylib....
ONF = cfg.CONF CLOUD = 'cloud' BACKEND = 'backend' CEPH = 'ceph' ISCSI = 'iscsi' COMPUTE = 'compute' INSTANCES = 'instances' INSTANCE_BODY = 'instance' INSTANCE = 'instance' DIFF = 'diff' EPHEMERAL = 'ephemeral' DIFF_OLD = 'diff_old' EPHEMERAL_OLD = 'ephemeral_old' PATH_DST = 'path_dst' HOST_DST = 'host_dst' PATH_SRC...
rexthompson/axwx
axwx/wu_metadata_scraping.py
Python
mit
5,613
0
""" Weather Underground PWS Metadata Scraping Module Code to scrape PWS network metadata """ import pandas as pd import urllib3 from bs4 import BeautifulSoup as BS import numpy as np import requests # import time def scrape_station_info(state="WA"): """ A script to scrape the station information published ...
url = 'https://api.wunderground.com/weatherstation/' \ 'WXDailyHistory.asp?ID={0}&format=XML'.format(stationID) r = http.request('GET', url, preload_content=False) soup = BS(r, 'xml') lat =
soup.find_all('latitude')[0].get_text() long = soup.find_all('longitude')[0].get_text() elev = soup.find_all('elevation')[0].get_text() return(lat, long, elev) except Exception as err: lat = 'NA' long = 'NA' elev = 'NA' return(lat, long, elev) def subset_s...
nophead/Skeinforge50plus
skeinforge_application/skeinforge_plugins/craft_plugins/export.py
Python
agpl-3.0
20,837
0.017853
""" This page is in the table of contents. Export is a craft tool to pick an export plugin, add information to the file name, and delete comments. The export manual page is at: http://fabmetheus.crsndoo.com/wiki/index.php/Skeinforge_Export ==Operation== The default 'Activate Export' checkbox is on. When it is on, th...
rocedureDoneOrFileIsEmpty( gcodeText, 'export'): return gcodeText if repository == None: repository = settings.getReadRepository(ExportRepository()) if not repository.activateExport.value: return gcodeText return ExportSkein().getCraftedGcode(repository, gcodeText) def getDescriptionCarve(lines): 'Get the de...
sString != None: descriptionCarve += layerThicknessString.replace('.', '') + 'h' edgeWidthString = getSettingString(lines, 'carve', 'Edge Width over Height') if edgeWidthString != None: descriptionCarve += 'x%sw' % str(float(edgeWidthString) * float(layerThicknessString)).replace('.', '') return descriptionCarve...
ModernMT/MMT
cli/utils/osutils.py
Python
apache-2.0
2,402
0.001665
import logging import os import shutil import subprocess DEVNULL = open(os.devnull, 'wb') class ShellError(Exception): def __init__(self, command, err_no, message=None): self.command = command self.errno = err_no self.message = message def __str__(self): string = "Command '%s...
e) return string def __repr__(self): return self.__str__() def shell_exec(cmd, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, background=False, env=None): str_cmd = cmd if isinstance(cmd, str) else ' '.join(cmd) logging.getLogger('shell_exec').debug(str_c
md) message = None if background: if stdout == subprocess.PIPE: stdout = DEVNULL if stderr == subprocess.PIPE: stderr = DEVNULL elif stdin is not None and isinstance(stdin, str): message = stdin stdin = subprocess.PIPE process = subprocess.Popen(...
rezoo/chainer
chainer/optimizers/rmsprop.py
Python
mit
4,921
0
import numpy from chainer.backends import cuda from chainer import optimizer _default_hyperparam = optimizer.Hyperparameter() _default_hyperparam.lr = 0.01 _default_hyperparam.alpha = 0.99 _default_hyperparam.eps = 1e-8 _default_hyperparam.eps_inside_sqrt = False class RMSpropRule(optimizer.UpdateRule): """Up...
""" def __init__(self, parent_hyperparam=None, lr=None, alpha=None, eps=None, eps_inside_sqrt=None): super(RMSpropRule, self).__init__( parent_hyperparam or _default_hyperparam) if lr is not None: self.hyper
param.lr = lr if alpha is not None: self.hyperparam.alpha = alpha if eps is not None: self.hyperparam.eps = eps if eps_inside_sqrt is not None: self.hyperparam.eps_inside_sqrt = eps_inside_sqrt def init_state(self, param): xp = cuda.get_array_modu...
TheWardoctor/Wardoctors-repo
script.module.urlresolver/lib/urlresolver/plugins/tudou.py
Python
apache-2.0
2,082
0.004803
""" Kodi urlresolver plugin Copyright (C) 2016 tknorris 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...
import re import urllib from urlresolver import common from urlresolver.resolver import UrlResolver, ResolverError class TudouResolver(UrlResolver): name = 'Tudou' domains = ['tudou.com'] pattern = '(?://|\.)(tudou\.com)/programs/view/([0-9a-zA-Z]+)' def __init__(self): self.net = common.Net()...
swf = re.findall('(http.+?\.swf)', html)[0] sid = re.findall('areaCode\s*:\s*"(\d+)', html)[0] oid = re.findall('"k"\s*:\s*(\d+)', html)[0] f_url = 'http://v2.tudou.com/f?id=%s&sid=%s&hd=3&sj=1' % (oid, sid) headers = {'User-Agent': common.FF_USER_AGENT, 'Referer': swf} htm...
zonca/pycfitsio
pycfitsio/__init__.py
Python
gpl-3.0
234
0.012821
import warnings from .file import File, open, read, create,
write, CfitsioError try: from healpix import read_map, read_mask except: warnings.warn('Cannot import read_map and read_mask if healpy is not install
ed') pass
pwil3058/darning
darning/cli/subcmd_select.py
Python
gpl-2.0
1,953
0.00768
### Copyright (C) 2010 Peter Williams <peter_ono@users.sourceforge.net> ### ### 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; version 2 of the License only. ### ### This program is distribut...
o the Free Software ### Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
110-1301 USA """Select/display which patch guards are in force.""" import sys from . import cli_args from . import db_utils from . import msg PARSER = cli_args.SUB_CMD_PARSER.add_parser( "select", description=_("Display/select which patch guards are in force."), epilog=_("""When invoked with no argument...
mahak/neutron
neutron/privileged/agent/linux/__init__.py
Python
apache-2.0
1,208
0
# Copyright 2020 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
s and limitations # under the License. import ctype
s from ctypes import util as ctypes_util _CDLL = None def get_cdll(): global _CDLL if not _CDLL: # NOTE(ralonsoh): from https://docs.python.org/3.6/library/ # ctypes.html#ctypes.PyDLL: "Instances of this class behave like CDLL # instances, except that the Python GIL is not released d...
asedunov/intellij-community
python/testData/refactoring/unwrap/tryUnwrap_before.py
Python
apache-2.0
61
0.081967
try: #comment x = 1<car
et> y = 2 except: pass
polyanskiy/refractiveindex.info-scripts
scripts/Djurisic 1999 - Graphite-o.py
Python
gpl-3.0
2,735
0.025077
# -*- coding: utf-8 -*- # Author: Mikhail Polyanskiy # Last modified: 2017-04-02 # Original data: Djurišić and Li 1999, https://doi.org/10.1063/1.369370 import numpy as np import matplotlib.pyplot as plt # LD model parameters - Normal polarization (ordinary) ωp = 27 εinf = 1.070 f0 = 0.014 Γ0 = 6.365 ω0 = 0 ...
t.xlabel('Photon energy (eV)') plt.ylabel('ε') plt.legend(bbox_to_anchor=(0,1.02,1,0),loc=3,ncol=2,borderaxespad=0) #plot n,k vs eV plt.figure(2) plt.plot(eV, n, label="n") plt.plot(eV, k, label="k") plt.xlabel('Photon energy (eV)') plt.ylabel('n, k') plt.legend(bbox_to_anchor=(0,1.02,1,0),loc=3,ncol=2,borderaxespad=0...
(μm, k, label="k") plt.xlabel('Wavelength (μm)') plt.ylabel('n, k') plt.xscale('log') plt.yscale('log') plt.legend(bbox_to_anchor=(0,1.02,1,0),loc=3,ncol=2,borderaxespad=0)
alazo/ase
pec/migrations/0007_auto_20170601_1557.py
Python
agpl-3.0
653
0.001531
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-06-01 15:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pec', '0006_auto_20170601_0719'), ] operations = [ migrations.AddField( ...
model_name='cours', name='type', field=models.CharField(blank=True, max_length=30), ), migrations.AlterField( model_name='cours',
name='objectifs_evaluateurs', field=models.ManyToManyField(blank=True, to='pec.ObjectifEvaluateur'), ), ]
drtyrsa/django-cached-modelforms
cached_modelforms/tests/test_fields.py
Python
bsd-2-clause
6,699
0.001941
# -*- coding:utf-8 -*- from django import forms try: from django.utils.encoding import smart_unicode as smart_text except ImportError: from django.utils.encoding import smart_text from cached_modelforms.tests.utils import SettingsTestCase from cached_modelforms.tests.models import SimpleModel from cached_mode...
make sure all of the ``choices`` attrs are the same self.assertTrue( as_list.choices == as_iterable.choices == as_list_of_tuples.choices == as_dict.choices ) # same for ``objects`` self.assertTrue( as_list.objects == ...
..}`` self.assertEqual( set(as_list.objects.keys()), set(smart_text(x.pk) for x in self.cached_list) ) self.assertEqual(set(as_list.objects.values()), set(self.cached_list)) # ``choices`` should be a list as ``[(smart_text(pk1), smart_text(obj1)), ...]`` ...
gmist/gae-de-init
main/apps/user/views.py
Python
mit
7,664
0.010569
# coding: utf-8 import copy from google.appengine.ext import ndb import flask from apps import auth from apps.auth import helpers from core import task from core import util import config import forms import models bp = flask.Blueprint( 'user', __name__, url_prefix='/user', template_folder='templates...
n flask.redirect(flask.url_for('pages.welcome')) return flask.r
ender_template( 'user/profile/update.html', title=user_db.name, html_class='profile', form=form, user_db=user_db, ) @bp.route('/profile/password/', methods=['GET', 'POST']) @auth.login_required def profile_password(): if not config.CONFIG_DB.has_email_authentication: flask.abor...
iuscommunity/dmirr
src/dmirr.hub/dmirr/hub/lib/geo.py
Python
gpl-2.0
735
0.013605
from django.conf import settings from geopy import distance, geocoders import pygeoip def get_geodata_by_ip(addr): gi = pygeoip.GeoIP(settings.GEO_CIT
Y_FILE, pygeoip.MEMORY_CACHE) geodata = gi.record_by_addr(addr) return geodata def get_geodata_by_region(*args): gn = geocoders.GeoNames() return gn.geocode(' '.join(args), exactly_one=False)[0] def get_distance(location1, location2): """ Calculate distance between two locations
, given the (lat, long) of each. Required Arguments: location1 A tuple of (lat, long). location2 A tuple of (lat, long). """ return distance.distance(location1, location2).miles
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/admin/modules_handler.py
Python
bsd-3-clause
934
0.001071
#!/usr/bin/env python # # Copyright 2007 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 applicable law o...
"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. # """A handler that displays servers and their instances.""" from google.appengine.tools.devappserver2.admin import admin_request_handler class ModulesHandler(admin_request_handler.AdminRequestHandler): def get(self): values = {'modules': self.dispatcher.modules} self.respo...
rck109d/projectEuler
src/euler/p3.py
Python
lgpl-3.0
433
0
def isPrime(num): if num <= 1: return False i = 2 while i < num / 2 + 1: if num % i == 0: return False i += 1 return True big = 600851475143 test = 1 while test < big: test += 1 if big % test == 0: print(test, ' divides evenly') div = big / t...
break
ajpotato214/Finance-Data-Scraper-API
finance_data_scraper/scrapers/finviz.py
Python
mit
4,390
0.0082
#!/usr/bin/python3 from scrapers.scrape import scrape_page # if you want to use this scraper without the RESTful api webservice then # change this import: from scrape import scrape_page import re try: import pandas as pd pandasImported = True except ImportError: pandasImported = False BASE_URL = "http://...
.append(get_all_statistics_series(s)) return pd.DataFr
ame(series,index=symbol_list) if __name__ == "__main__": # Test Cases print(get_statistic("AAPL", "P/E")) print(get_statistic("AAPL", "Inst Own")) print(get_statistic("AAPL", "Change")) print(get_statistic("AAPL", "This should return None")) print(get_all_statistics("AAPL"))
tomekby/miscellaneous
jira-invoices/calculator.py
Python
mit
6,443
0.003889
from w3lib.html import remove_tags from requests import session, codes from bs4 import BeautifulSoup # Net/gross calculator for student under 26 years class Student: _hours = 0 _wage = 0 _tax_rate = 18 _cost = 20 def __init__(self, hours, wage, cost): self._hours = hours ...
self._
data['cost'] def get_tax(self): if self._data == None: return self._calculator.get_tax() return self._data['tax'] def get_cost_percentage(self): return self._cost # Bot finding invoice values on wfirma.pl calculator page class WfirmaPlBot: _url = 'htt...
Arkapravo/morse-0.6
src/morse/middleware/socket_mw.py
Python
bsd-3-clause
6,797
0.00206
import logging; logger = logging.getLogger("morse." + __name__) import socket import select import json import morse.core.middleware from functools import partial from morse.core import services class MorseSocketServ: def __init__(self, port, component_name): # List of socket clients self._client_s...
tream_ports(self): """ Get stream ports for all streams. """ return self._component_nameservice def register_component(self, component_name, component_instance, mw_data): """ Open the port used to communicate by the specified component. """ # Create a socket server ...
ver_dict[self._base_port] = serv self._component_nameservice[component_name] = self._base_port self._base_port = self._base_port + 1 # Extract the information for this middleware # This will be tailored for each middleware according to its needs function_name = mw_data[1] ...
nanomolina/MusicWeb
src/Music/apps/interpreter/migrations/0011_auto_20141215_0030.py
Python
mit
600
0.001667
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('interpreter', '0010_auto_20141215_0027'), ] operations = [ migrations.RemoveField( model_name='band', ...
', name='band', field=models.ManyToManyField(related_name='members', nu
ll=True, to='interpreter.Band', blank=True), preserve_default=True, ), ]
miur/miur
OLD/miur/cursor/dispatch.py
Python
gpl-3.0
1,733
0.000577
# # SPDX-FileCopyrightText: 2016 Dmytro Kolomoiets <amerlyq@gmail.com> and contributors. # # SPDX-License-Identifier: GPL-3.0-only # from miur.cursor import state, update, message as msg class Dispatcher: """Apply actions to any unrelated global states""" def _err_wrong_cmd(self): # Move err processi...
pdate.py' (make more symmetrical) # _log.error("Wrong cmd: {}".format(cmd)) raise NotImplementedError def focus_node_next(self): if state.cursor is not None and state.entries is not None: state.cursor = min(state.cursor + 1, len(state.entries) - 1) def focus_node_prev(self)...
te.entries is not None: state.cursor = max(state.cursor - 1, 0) def focus_node_beg(self): if state.entries is not None: state.cursor = 0 def focus_node_end(self): if state.entries is not None: state.cursor = len(state.entries) - 1 def shift_node_parent(...
sl0/adm6
tests/test_03_filter6.py
Python
gpl-3.0
102,052
0.003439
#!/usr/bin/env python #encoding:utf8 # # file: filter6_tests.py # author: sl0 # date: 2013-03-06 # import unittest from adm6.filter6 import IP6_Filter, Ip6_Filter_Rule from sys import stdout from os.path import expanduser as homedir from ipaddr import IPv6Network from os import getenv as get_env home_dir_replac...
fr['Destin'] = "2001:db8
:2::1" fr['Protocol'] = "tcp" fr['dport'] = "22" fr['System-Forward'] = True fr['i_am_s'] = False fr['i_am_d'] = False fr['travers'] = True fr['source-if'] = "eth0" fr['destin-if'] = "eth0" fr['src-linklocal'] = ...
pomarec/core
arkos/connections.py
Python
gpl-3.0
3,011
0
""" Classes and functions for interacting with system management daemons. arkOS Core (c) 2016 CitizenWeb Written by Jacob Cook Licensed under GPLv3, see LICENSE.md """ import ldap import ldap.modlist import xmlrpc.client from .utilities import errors from d
bus import SystemBus, Interface class ConnectionsManager: """Manages arkOS connections to system-level processes via their APIs.""" def __init__(self, config, secrets): self.config = config self.secrets = secrets def connect(self): """Initialize the connec
tions.""" self.connect_services() self.connect_ldap() def connect_services(self): self.DBus = SystemBus() self.SystemD = self.SystemDConnect( "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager") self.Supervisor = supervisor_connect() def connect_...
lab132/PyBake
PyBake/commands/basketCommand.py
Python
mit
1,990
0.009045
"""Commands for argparse for basket command""" import textwrap from PyBake import Path from PyBake.commands import command @command("basket") class BasketModuleManager: """Module Manager for Basket""" longDescription = textwrap.dedent( """ Retrieves pastries from the shop. """) def createArguments(self...
help="Download all required pastries, whether they exist locally already or not.") basketParser.add_argument("--force-install", dest="force", action="append_const", const="install", help="Perform ...
ivanamihalek/tcga
icgc/60_nextgen_production/65_reactome_tree.py
Python
gpl-3.0
5,057
0.024916
#! /usr/bin/python3 # # This source code is part of icgc, an ICGC processing pipeline. # # Icgc 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 ...
characterize_subtree(cursor, graph, pthwy_id, gene_groups, depth, verbose=True): # this is the whole subtree # children = [node for node in nx.dfs_preorder_nodes(graph, pthwy_id)] # A successor of n is a
node m such that there exists a directed edge from n to m. children = [node for node in graph.successors(pthwy_id)] if len(children)==0: return False node_id_string = ",".join([quotify(z) for z in children]) qry_template = "select * from reactome_pathways where reactome_pathway_id in (%s)" children_names = hard_l...
chromium2014/src
tools/telemetry/telemetry/util/find_dependencies.py
Python
bsd-3-clause
9,256
0.010372
# Copyright 2014 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. import fnmatch import imp import logging import modulefinder import optparse import os import sys import zipfile from telemetry import benchmark from teleme...
attern)): return True return False # Collect filters we're going to use to exclude files. exclude_conditions = [ IsHidden, IsPyc, IsInCloudStorage, MatchesExcludeOptions, ] # Check all the files against the filters. for path in files: if MatchesC
onditions(path, exclude_conditions): yield path def FindDependencies(paths, options): # Verify arguments. for path in paths: if not os.path.exists(path): raise ValueError('Path does not exist: %s' % path) dependencies = path_set.PathSet() # Including __init__.py will include Telemetry and it...
rcmorano/gecosws-config-assistant
firstboot/serverconf/ServerConf.py
Python
gpl-2.0
5,970
0.00067
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- # This file is part of Guadalinex # # This software 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, ...
self.set_organization(conf['organization']) except KeyError as e: print msg % ('organization',) try: self.set_notes(conf['notes']) except KeyError as e: print msg % ('notes',) try: self.set_gem_repo(conf['gem_repo']) except KeyErr...
try: self._gcc_conf.load_data(conf['gcc']) except KeyError as e: print msg % ('gcc',) try: self._auth_conf.load_data(conf['auth']) except KeyError as e: print msg % ('auth',) try: self._ntp_conf.load_data(conf['uri_ntp']) ...
axlt2002/script.light.imdb.ratings.update
resources/core/update_main.py
Python
gpl-3.0
10,373
0.050998
# -*- coding: utf-8 -*- ############################# # Light IMDb Ratings Update # # by axlt2002 # ############################# # changes by dziobak # ############################# import xbmc, xbmcgui import sys if sys.version_info >= (2, 7): import json as jSon else: import simplejson as jSon...
tes, TVDB, TMDB, season, episode global nu
m_threads if IMDb == None or IMDb == "" or "tt" not in IMDb: IMDb = None Top250 = None if dType == "movie": Top250 = TVDB if Top250 == None: Top250 = 0 TVDB = None defaultLog( addonLanguage(32507) % ( Title, IMDb, TVDB, TMDB ) ) if IMDb == None: if dType == "tvshow" or dType == "episode": (IMDb, statusI...
fintech-circle/edx-platform
lms/envs/bok_choy.py
Python
agpl-3.0
8,553
0.002923
""" Settings for Bok Choy tests that are used when running LMS. Bok Choy uses two different settings files: 1. test_static_optimized is used when invoking collectstatic 2. bok_choy is used when running the tests Note: it isn't possible to have a single settings file, because Django doesn't support both generating sta...
t here to use # a simpler security model FEATURES['ENFORCE_PASSWORD_POLICY'] = False FEATURES['ENABLE_MAX_FAILED_LOGIN_ATTEMPTS'] = False FEATURES['SQUELCH_PII_IN_LOGS'] = False FEATURES['PREVENT_CONCURRENT_LOGINS'] = False FEATURES['ADVANCED_SECURITY'] = False FEATURES['ENABLE_MOBILE_REST_API'] = True # Show video b...
# Enable courseware search for tests FEATURES['ENABLE_COURSEWARE_SEARCH'] = True # Enable dashboard search for tests FEATURES['ENABLE_DASHBOARD_SEARCH'] = True # discussion home panel, which includes a subscription on/off setting for discussion digest emails. FEATURES['ENABLE_DISCUSSION_HOME_PANEL'] = True # Enabl...
gonczor/ServerPy
Setup/settings.py
Python
gpl-2.0
142
0
import os ADDRESS = '127.0.0.1' PORT =
12345 BACKUP_DIR = 'Backup' BASE
_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
Drakulix/knex
evalData/testdata_insertion.py
Python
mit
897
0.00223
import os import requests if __name__ == "__main__": session = requests.Session() data = {"email": "admin@knex.com", "password": "admin"} session.post("http://localhost:5000/api/users/login", data=data) for file in os.listdir("."): if file.endswith(".json"): text = open(file, "r")...
elif file.endswith(".j
son5"): text = open(file, "r").read() res = session.post("http://localhost:5000/api/projects", data=text.encode('utf-8'), headers={'Content-Type': 'application/json5'}) print(file + " " + str(res)) session.get("http://localhost:5000/api/users/logou...
danimajo/pineapple_pdf
werkzeug/wrappers.py
Python
mit
76,131
0.000276
# -*- coding: utf-8 -*- """ werkzeug.wrappers ~~~~~~~~~~~~~~~~~ The wrappers are simple request and response objects which you can subclass to do whatever you want them to do. The request object contains the information transmitted by the client (webbrowser) and the response object contains al...
Here an example for such subclasses:: from werkzeug.wrappers import BaseRequest, ETagRequestMixin
class Request(BaseRequest, ETagRequestMixin): pass Request objects are **read only**. As of 0.5 modifications are not allowed in any place. Unlike the lower level parsing functions the request object will use immutable objects everywhere possible. Per default the request object will a...
sbesson/snoopycrimecop
test/integration/Sandbox.py
Python
gpl-2.0
5,211
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2012-2013 University of Dundee & Open Micr
oscopy Environment # 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 Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distribu...
TICULAR 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. from builtins import str from buil...
sokanu/frame
images/storage.py
Python
mit
3,547
0.004229
from django.conf import settings from images.models import S3Connection from shutil import copyfileobj import tinys3 import os import urllib class LocalStorage(object): def __init__(self, filename): self.filename = filename def get_file_data(self): """ Returns the raw data for the spec...
string that can be stored in a filename """ # TODO: is there a possible bug if an invalid key/value is presented? args_list = ['%s-%s' % (key, value) for key, value in arguments_dict.items()] return '--'.join(args_list) class S3Storage(LocalStorage
): def __init__(self, *args, **kwargs): """ Overrides the LocalStorage and initializes a shared S3 connection """ super(S3Storage, self).__init__(*args, **kwargs) self.conn = tinys3.Connection(self.S3_ACCESS_KEY, self.S3_SECRET_KEY, default_bucket=self.S3_BUCKET, tls=True) ...
new-player/share_projects
share_projects/profiles/models.py
Python
mit
1,201
0.000833
import os import uuid from django.db import models from django.utils import timezone from django.contrib.auth.models import User def avatar_upload(instance, filename): ext = filename.split(".")[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join("avatars", filename) class Profile(models.M...
ield("Twitter Username", max_length=100, blank=True) created_at = models.DateTimeField(default=timezone.now) modif
ied_at = models.DateTimeField(default=timezone.now) def save(self, *args, **kwargs): self.modified_at = timezone.now() return super(Profile, self).save(*args, **kwargs) @property def display_name(self): if self.name: return self.name else: return sel...
greatfireball/PorthoMCL
porthomclPairsBestHit.py
Python
gpl-3.0
10,894
0.026161
#!/usr/bin/python from datetime import datetime from collections import namedtuple import sys, os import gzip import random, math from optparse import OptionParser options = None ## User for Orthology best_query_taxon_score = {} ## Used for the Paralogy BestInterTaxonScore = {} BetterHit = {} # class SimilarSeque...
column[2]), int(column[3]), float(column[4])) result = new(cls, iterable) if len(result) != 9: raise TypeError('Expected 9 arguments, got %d' % len(result)) return result
def readTaxonList(filename): taxon_list = [] taxon_list_file = open(filename) for line in taxon_list_file: line = line.strip() if line: taxon_list += [line] taxon_list_file.close() return taxon_list def memory_usage_resource(): import resource rusage_denom = 1024. if sys.platform == 'darwin': # .....
fonnesbeck/geopandas
geopandas/plotting.py
Python
bsd-3-clause
10,488
0.003337
from __future__ import print_function import numpy as np from six import next from six.moves import xrange def plot_polygon(ax, poly, facecolor='red', edgecolor='black', alpha=0.5, linewidth=1): """ Plot a single Polygon geometry """ from descartes.patch import PolygonPatch a = np.asarray(poly.exterior) ...
s import Line2D from matplotlib.colors import Normalize from matplotlib import cm if column is None: return plot_series(s.geometry, colormap=colormap, alpha=alpha, linewidth=linewidth, axes=axes) else: if s[column].dtype is np.dtype('O'): categor...
= 'Set1' categories = list(set(s[column].values)) categories.sort() valuemap = dict([(k, v) for (v, k) in enumerate(categories)]) values = [valuemap[k] for k in s[column]] else: values = s[column] if scheme is not None: values = __p...
NetApp/manila
manila/tests/share/drivers/test_ganesha.py
Python
apache-2.0
13,337
0
# Copyright (c) 2014 Red Hat, 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...
st_exist_false(self): self.mock_object( ganesha.os, 'listdir', mock.Mock(side_effect=OSError(errno.ENOENT, os.strerror(errno.ENOENT)))) self.mock_object(ganesha.LOG, 'info') self.mock_object(ganesha.ganesha_manager, 'parseconf')
self.mock_object(ganesha.ganesha_utils, 'patch') with mock.patch('six.moves.builtins.open', mock.mock_open(read_data='fakeconf')) as mockopen: ret = self._helper._load_conf_dir(self.fake_conf_dir_path, must_exist=False) ...
adamnovak/hgvm-builder
setup.py
Python
apache-2.0
2,450
0.003673
# setup.py: based off setup.py for toil-vg, modified to install this pipeline # instead. import sys import os # Get the local version.py and not any other version module execfile(os.path.join(os.path.dirname(os.path.realpath(__file__)), "version.py")) from setuptools import find_packages, setup from setuptools.comman...
v[1:] = [] errno = pytest.main(self.pytest_args) sys.exit(errno) kwargs['cmdclass'] = {'test': PyTest} setup(**kwargs) # Wen we run setup, tell the user they need a good Toil with cloud support print(""" Thank you for installing the hgvm-builder pipeline! If you want to run this Toil-based pipeline ...
ster in a cloud, please install Toil with the appropriate extras. For example, To install AWS/EC2 support for example, run pip install toil[aws,mesos]{} on every EC2 instance. For Microsoft Azure, deploy your cluster using the Toil template at https://github.com/BD2KGenomics/toil/tree/master/contrib/azure For more ...
pblottiere/QGIS
tests/src/python/test_qgsmultiedittoolbutton.py
Python
gpl-2.0
2,332
0
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsMultiEditToolButton. .. note:: 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 Found
ation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Nyall Dawson' __date__ = '16/03/2016' __copyright__ = 'Copyright 2016, The QGIS Project' import qgis # NOQA switch sip api from qgis.gui import QgsMultiEditToolButton from qgis.testing import start_app, unittest start_...
DarKnight24/owtf
framework/db/mapping_manager.py
Python
bsd-3-clause
3,644
0.001647
import os import json import logging import ConfigParser from framework.db import models from framework.dependency_management.dependency_resolver import BaseComponent from framework.dependency_management.interfaces import MappingDBInterface from framework.lib.exceptions import InvalidMappingReference class MappingDB...
t(obj.__dict__)
pdict.pop("_sa_instance_state", None) # If output is present, json decode it if pdict.get("mappings", None): pdict["mappings"] = json.loads(pdict["mappings"]) return pdict def DeriveMappingDicts(self, obj_list): dict_list = [] for obj in obj_...
wary/zeppelin
python/src/main/resources/python/zeppelin_python.py
Python
apache-2.0
9,381
0.012685
# # 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 us...
if fmt == "png": img = BytesIO() p.savefig(img, format=fmt) img_str = b"data:image/png;base64," img_str += base64.b64encode(img.getvalue().strip()) img_tag = "<img src={img} style='width=
{width};height:{height}'>" # Decoding is necessary for Python 3 compability img_str = img_str.decode("ascii") img_str = img_tag.format(img=img_str, width=width, height=height) elif fmt == "svg": img = StringIO() p.savefig(img, format=fmt) img_str = img.getvalue() else: ...
c3nav/c3nav
src/c3nav/editor/models/__init__.py
Python
apache-2.0
200
0
from c3nav.edit
or.models
.changedobject import ChangedObject # noqa from c3nav.editor.models.changeset import ChangeSet # noqa from c3nav.editor.models.changesetupdate import ChangeSetUpdate # noqa
hzlf/openbroadcast.ch
app/remoteauth/migrations/0001_initial.py
Python
gpl-3.0
3,171
0.00473
# -*- coding: utf-8 -*
- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone impor
t django.core.validators import django.contrib.auth.models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(ve...
CSE-SOE-CUSAT/NOSLab
CSA/unsorted/username/client.py
Python
mit
1,125
0.013333
import socket from heapq import heappush, heappop, heapify from collections
import defaultdict ##defbig def encode(symb2freq): """Huffman encode the giv
en dict mapping symbols to weights""" heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()] heapify(heap) while len(heap) > 1: lo = heappop(heap) hi = heappop(heap) for pair in lo[1:]: pair[1] = '1' + pair[1] for pair in hi[1:]: pair[1] = '0' + pai...
hail-is/hail
auth/auth/auth.py
Python
mit
25,475
0.002198
import asyncio import json import logging import os from typing import List, Optional import aiohttp import aiohttp_session import uvloop from aiohttp import web from prometheus_async.aio.web import server_stats # type: ignore from gear import ( Database, Transaction, check_csrf_token, create_session...
username if c.isalnum()): raise InvalidUsername(username) existing_users = await users_with_username_or_login_id(tx, username, login_id) if len(existing_users) > 1: raise MultipleExistingUsers(username, login_id) if len(existing_users) == 1: existing_user = existing_users[0
] expected_username = existing_user['username'] expected_login_id = existing_user['login_id'] if username != expected_username: raise DuplicateLoginID(expected_username, login_id) if login_id != expected_login_id: raise DuplicateUsername(username, expected_login_i...
postvakje/sympy
sympy/physics/vector/frame.py
Python
bsd-3-clause
31,125
0.001157
from sympy import (diff, trigsimp, expand, sin, cos, solve, Symbol, sympify, eye, symbols, Dummy, ImmutableMatrix as Matrix, MatrixBase) from sympy.core.compatibility import string_types, range from sympy.physics.vector.vector import Vector, _check_vector __all__ = ['CoordinateSym', 'ReferenceFrame'...
instance(ind, str): if ind < 3: return s
elf.varlist[ind] else:
paolodedios/pybuilder
src/main/python/pybuilder/_vendor/pkg_resources/_vendor/packaging/_musllinux.py
Python
apache-2.0
4,378
0.000457
"""PEP 656 support. This module implements logic to detect if the currently running Python is linked against musl, and what musl version is used. """ import contextlib import functools import operator import os import re import struct import subprocess import sys from typing import IO, Iterator, NamedTuple, Optional,...
return for minor in range(sys_musl.minor, -1, -1): yield f"musllinux_{sys_musl.major}_{minor}_{arch}" if __name__ == "__main__": # pragma: no cover import sysconfig plat = sysconfig.get_platform() assert plat.startswith("linux-"), "not linux" print("plat:", plat) print("musl:", _g...
1])): print(t, end="\n ")
pblottiere/QGIS
tests/src/python/test_qgssettings.py
Python
gpl-2.0
23,013
0.003525
# -*- coding: utf-8 -*- """ Test the QgsSettings class Run with: ctest -V -R PyQgsSettings .. note:: 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 opti...
tings/names/namèé↓1', 'qgisrocks↓1') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓1') self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'), 'qgisrocks↓2') self...
isrocks↓-1') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓-1') def test_groups(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1') self.addToDefaults('testqgissettings/names/name2...
riking/youtube-dl
youtube_dl/downloader/http.py
Python
unlicense
8,667
0.002308
import os import time from .common import FileDownloader from ..utils import ( compat_urllib_request, compat_urllib_error, ContentTooShortError, encodeFilename, sanitize_open, format_bytes, ) class HttpFD(FileDownloader): _TEST_FILE_SIZE = 10241 def real_download(self, filename, inf...
l # block size when downloading a file. if is_test and (data_len is None or int(data_len) > self._TEST_FILE_SIZE): data_len = self._TEST_FILE_SIZE if data_len is not None: data_len = int(data_len) + resume_len min_data_len = self.params.get("min_filesize", No...
max_data_len = self.params.get("max_filesize", None) if min_data_len is not None and data_len < min_data_len: self.to_screen(u'\r[download] File is smaller than min-filesize (%s bytes < %s bytes). Aborting.' % (data_len, min_data_len)) return False if max_data_l...
klahnakoski/SpotManager
vendor/jx_elasticsearch/es52/painless/__init__.py
Python
mpl-2.0
3,355
0.000596
from jx_elasticsearc
h.es52.painless._utils import Painless, LIST_TO_PIPE from jx_ela
sticsearch.es52.painless.add_op import AddOp from jx_elasticsearch.es52.painless.and_op import AndOp from jx_elasticsearch.es52.painless.basic_add_op import BasicAddOp from jx_elasticsearch.es52.painless.basic_eq_op import BasicEqOp from jx_elasticsearch.es52.painless.basic_index_of_op import BasicIndexOfOp from jx_ela...
teichopsia-/python_practice
old_class_material/MITPerson_class.py
Python
mpl-2.0
903
0.026578
# Building inheritance class MITPerson(Person): nextIdNum = 0 #next ID number to assing def __init__(self, name): Person.__init__(self, name) #initialize Person attributes # new MITPerson atrribute: a unique ID number self.idNum = MITPerson.nextIdNum MITPerson.nextIdNum += ...
method return self.year class Grad(Student): ##---- pass class TransferStudent(Student): pass def isStudent
(obj): return isinstance(obj, Student)