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
glidernet/python-ogn-client
ogn/parser/aprs_comment/tracker_parser.py
Python
agpl-3.0
3,367
0.012177
from ogn.parser.pattern import PATTERN_TRACKER_POSITION_COMMENT, PATTERN_TRACKER_STATUS_COMMENT from ogn.parser.utils import FPM_TO_MS, HPM_TO_DEGS from .base import BaseParser class TrackerParser(BaseParser): def __init__(self): self.beacon_type = 'tracker' self.position_pattern = PATTERN_TRACKE...
level'] = float(match.group('flight_level')) if match.group('signal_quality'): result['signal_quality'] = float(match.group('signal_quality')) if match.group('error_count'): result['error_count'] = int(match.group('error_count')) if match.group('frequency_offset'): result[
'frequency_offset'] = float(match.group('frequency_offset')) if match.group('gps_quality'): result.update({ 'gps_quality': { 'horizontal': int(match.group('gps_quality_horizontal')), 'vertical': int(match.group('gps_quality_vertical')) ...
JR--Chen/flasky
app/spider/decorators.py
Python
mit
641
0.00156
from functools import wraps def retry_task(f): @wraps(f) def decorated_function(*args, **kwargs): retry = kwargs.get('retry', False) if retry == 0: return f(*args, **kwargs) elif retry > 0: for x in range(0, retry): result = f(*args, **kwargs) ...
if result
['status'] != 500: return result return f(*args, **kwargs) elif retry == -1: while retry: result = f(*args, **kwargs) if result['status'] != 500: return result return decorated_function
viaict/viaduct
app/models/user.py
Python
mit
5,021
0
from datetime import datetime from flask_login import UserMixin, AnonymousUserMixin from typing import List from app import db, constants from app.models.base_model import BaseEntity from app.models.education import Education from app.models.group import Group class AnonymousUser(AnonymousUserMixin): """ Has...
lumn(db.Boolean, default=False) education = db.relationship(Education, backref=db.backref('user', lazy='dynamic')) cope
rnica_id = db.Column(db.Integer(), nullable=True) avatar_file_id = db.Column(db.Integer, db.ForeignKey('file.id')) student_id_confirmed = db.Column(db.Boolean, default=False, nullable=False) def __init__(self, email=None, password=None, first_name=None, last_name=None, student_id=None, ed...
cjlux/Poppy-ENSAM-Talence
Environnement_programmation/Codes Xavier Mariot/codes test.py
Python
gpl-3.0
1,215
0.009959
# -*- coding: utf-8 -*- """ Éditeur de Spyder Ce script temporaire est sauvegardé ici : /home/poppy/.spyder2/.temp.py """ # bibliothèques nécessaires au fonctionnement de Poppy humanoide import pypot from poppy.creatures import PoppyHumanoid import kinematics as kin # démmarrer la simulation poppy dans vrep. Il f...
print "-------------" print "
nom du moteur: ", m.name print "position actuelle du moteur: ", m.present_position, "degrès" # Poppy dit oui for i in range(2): poppy.head_y.goal_position = -20 poppy.head_y.goal_position = +20 poppy.head_y.goal_position = 0 poppy.l_shoulder_y.goal_position = -45 poppy.l_shoulder_x.goal_posi...
michaelmior/freudiancommits
freudiancommits/settings.py
Python
gpl-3.0
6,595
0.00091
# Django settings for freudiancommits project. import os DEBUG = True if os.environ.get('DJANGO_DEBUG', None) == '1' else False TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS import dj_database_url DATABASES = {'default': dj_database_url.config()} # Local time ...
# calendars according
to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from ME...
michaelhowden/eden
modules/s3/s3aaa.py
Python
mit
357,874
0.002582
# -*- coding: utf-8 -*- """ Authentication, Authorization, Accouting @requires: U{B{I{gluon}} <http://web2py.com>} @copyright: (c) 2010-2015 Sahana Software Foundation @license: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated docum...
- __init__ - define_tables - login_bare - set_cookie - login - register - email_reset_password - verify_email - profile - has_membership - requires_membership - S3 extension for user reg...
- configure_user_fields - s3_verify_user - s3_approve_user - s3_link_user - s3_user_profile_onaccept - s3_link_to_person - s3_link_to_organisation - s3_link_to_human_resource - s3_link_to_member - s3_...
shtripat/gluster_bridge
tendrl/gluster_bridge/gevent_util.py
Python
lgpl-2.1
1,785
0
from contextlib import contextmanager from functools import wraps from gevent import getcurrent class ForbiddenYield(Exception): pass @contextmanager def nosleep_mgr(): old_switch_out = getattr(getcurrent(), 'switch_out', None) def asserter(): raise ForbiddenYield("Context switch during `noslee...
s should raise an exception when we try push to a fixed size queue try: smallq = gevent.queue.Queue(1) with nosleep_mgr(): smallq.put(1) smallq.put(2) except ForbiddenYield: pass else: raise AssertionError("Failed") # This should raise no exceptio...
with nosleep_mgr(): for i in range(0, 10000): bigq.put(i) # This should raise an exception on sleep # FIXME!!!! try: sleep(0.1) except ForbiddenYield: pass else: raise AssertionError("Failed")
andrwng/kudu
build-support/run_dist_test.py
Python
apache-2.0
5,863
0.013133
#!/usr/bin/env python2 # # 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 # ...
p.parse_args() if len(args) < 1: p.print_help(sys.stderr) sys.exit(1) test_exe = args[0] test_name, _ = os.path.splitext(os.path.basename(test_exe)) test_dir = os.path.dirname(test_exe) env = os.environ.copy() for env_pair in options.env: (k, v) = env_pair.split("=", 1) env[k] = v # Fix...
ve so that we can run it on the new location. # # It's important to do this rather than just putting all of the thirdparty # lib directories into $LD_LIBRARY_PATH below because we need to make sure # that non-TSAN-instrumented runtime tools (like 'llvm-symbolizer') do _NOT_ # pick up the TSAN-instrumented lib...
jnayak1/cs3240-s16-team16
upload/models.py
Python
mit
726
0.002755
from django.db import models # Create your models here. class SignUp(models.Model):
email = models.EmailField() full_name = models.CharField(max_length=120, blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.email class PublicKey(models.Mod...
= models.CharField(max_length=50) key = models.CharField(max_length=32) def __str__(self): return self.file # class UploadFile(models.Model): # name = models.CharField(max_length=120, blank=True) # file = models.FileField() # # def __str__(self): # return self.name
EarToEarOak/RTLSDR-Scanner
rtlsdr_scanner/devices.py
Python
gpl-3.0
4,603
0.000434
# # rtlsdr_scan # # http://eartoearoak.com/software/rtlsdr-scanner # # Copyright 2012 -2015 Al Brown # # A frequency scanning GUI for the OsmoSDR rtl-sdr library at # http://sdr.osmocom.org/trac/wiki/rtl-sdr # # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gener...
serial.EIGHTBITS] PARITIES = [serial.PARITY_NONE, s
erial.PARITY_EVEN, serial.PARITY_ODD, serial.PARITY_MARK, serial.PARITY_SPACE] STOPS = [serial.STOPBITS_ONE, serial.STOPBITS_ONE_POINT_FIVE, serial.STOPBITS_TWO] def __init__(self): self.name = 'GPS' self.type = self.GPSD self.resource = 'localhost:2947' ...
rlowrance/find_best_mall
yelp_crawler/filter.py
Python
mit
4,773
0.020113
# filter the store data # remove the redundant store's name import csv import re import unicodedata import sys reload(sys) import operator sys.setdefaultencoding("utf-8") root = "/Users/lily/workspace/find_best_mall/yelp_crawler" dir = root + "/dataset" file = dir + "/store.csv" final_file = dir + "/tmp_yelp.csv" def...
rule_to = rule[1].strip() name = re.sub(rule_from, rule_to, name) # if the name just have spaces, ignore if(len(re.sub("\s*", "", name)) <= 0): continue if(len(re.sub("\s*", "", name)) > 0): # create unique id for stores if not(name in stores...
mall_id]) store_file.close() with open(final_file, 'wb') as file: writer = csv.writer(file, delimiter=',') my_list = sorted(stores_list, key=operator.itemgetter(1)) writer.writerow(["store_name", "store_new_id", "mall_id"]) for val in my_list: writer.writerow(val) file.close() with open(store...
leeping/mdtraj
tests/test_reporter.py
Python
lgpl-2.1
7,439
0.001613
############################################################################## # MDTraj: A Python Library for Loading, Saving, and Manipulating # Molecular Dynamics Trajectories. # Copyright 2012-2017 Stanford University and the Authors # # Authors: Robert McGibbon # Contributors: # # MDTraj is free software: y...
rm from simtk.openmm.app import PDBFile, ForceField, Simulation, CutoffNonPeriodic, CutoffPeriodic, HBonds HAVE_OPENMM = True except ImportError: HAVE_OPENMM = False # special pytest global to mark
all tests in this module pytestmark = pytest.mark.skipif(not HAVE_OPENMM, reason='test_reporter.py needs OpenMM.') def test_reporter(tmpdir, get_fn): pdb = PDBFile(get_fn('native.pdb')) forcefield = ForceField('amber99sbildn.xml', 'amber99_obc.xml') # NO PERIODIC BOUNDARY CONDITIONS system = forcefiel...
FFMG/myoddweb.piger
monitor/api/python/Python-3.7.2/Lib/test/test_unicode_identifiers.py
Python
gpl-2.0
891
0.004635
import unittest class PEP3131Test(unittest.TestCase): def test_valid(self): class T: ä = 1 µ = 2 # this is a compatibility character 蟒 = 3 x󠄀 = 4 self.assertEqual(getattr(T, "\xe4"), 1) self.assertEqual(getattr(T, "\u03bc"), 2) self....
self.assertEqual(getattr(T, 'x\U000E0100'), 4) def test_non_bmp_normalized(self): 𝔘𝔫𝔦𝔠𝔬𝔡𝔢 = 1 self.assertIn("Unicode", dir()) def test_invalid(self): try
: from test import badsyntax_3131 except SyntaxError as s: self.assertEqual(str(s), "invalid character in identifier (badsyntax_3131.py, line 2)") else: self.fail("expected exception didn't occur") if __name__ == "__main__": unittest.main()
harpolea/advent_of_code_2016
day20.py
Python
mit
1,397
0.006442
import re def firewall(in_file): # read file f = open(in_file, 'r') ranges = [] for l in f: m = re.match('(\d+)-(\d+)', l) ranges.append([int(m.group(1)), int(m.group(2))]) ranges.sort() lowest = 0 upper_lim = 0 for r in ranges: if lowest < r[0]: pri...
ound lowest-valued unblocked IP: {}'.format(lowest)) return else: if r[1] > upper_lim: upper_lim = r[1] lowest = upper_lim+1 # all are blocked if lowest > 4294967295: print
('All IPs are blocked :(') else: print('Found lowest-valued unblocked IP: {}'.format(lowest)) return def firewall_part2(in_file): # read file f = open(in_file, 'r') ranges = [] for l in f: m = re.match('(\d+)-(\d+)', l) ranges.append([int(m.group(1)), int(m.group(2))]) ...
jaejun1679-cmis/jaejun1679-cmis-cs2
cs2quiz3.py
Python
cc0-1.0
1,995
0.02406
#Section 1: Terminology # 1) What is a recursive function? #A recursive function is a defined function that calls itself and only is completed when the requirements of the base case is met. Usually a parameter is used # # # 2) What happens if there is no base case defined in a recursive function? #The recursive functi...
e first thing to consider w
hen designing a recursive function? #Make sure to have a base case for the recursive function. # # # 4) How do we put data into a function call? #We can use parameters in your function call. # # 5) How do we get data out of a function call? #The return function allows the program to spit out data back out by using ret...
394954369/horizon
openstack_dashboard/dashboards/project/volumes/backups/tests.py
Python
apache-2.0
7,167
0.00014
# 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, software # distributed under t...
ons.cinder) self.mox.ReplayAll() url = reverse('horizon:project:volumes:backups:detail', args=[backup.id]) res = self.client.get(url) self.assertNoFormErrors(res) self.assertMessageCount(error=1) self.assertRedir
ectsNoFollow(res, INDEX_URL) @test.create_stubs({api.cinder: ('volume_list', 'volume_backup_restore',)}) def test_restore_backup(self): backup = self.cinder_volume_backups.first() volumes = self.cinder_volumes.list() api.cinder.volume_list(IsA(http....
antepsis/anteplahmacun
sympy/core/expr.py
Python
bsd-3-clause
114,108
0.000578
from __future__ import print_function, division from .sympify import sympify, _sympify, SympifyError from .basic import Basic, Atom from .singleton import S from .evalf import EvalfMixin, pure_complex from .decorators import _sympifyit, call_highest_priority from .cache import cacheit from .compatibility import reduce...
hat it evalf'ed to # a number. result = self.eval
f() if result.is_Number: return float(result) if result.is_number and result.as_real_imag()[1]: raise TypeError("can't convert complex to float") raise TypeErro
will-Do/tp-libvirt_v2v
lvsb/tests/src/lvsb_date.py
Python
gpl-2.0
2,928
0
""" Simple test that executes date command in a sanbox and verifies it is correct """ import datetime from autotest.client.shared import error from virttest.lvsb import make_sandboxes def verify_datetime(start_time, stop_time, result_list): """ Return the number of sandboxes which reported incorrect date ...
ro exit codes if failed > 0: return True return False def run(test, params, env): """ Executes date command in a sanbox and verifies it is correct 1) Gather parameters 2) Create configured sandbox aggregater(s) 3) Run and stop all sandboxes in all agregators 4) Handle ...
time for comparison when finished start_time = datetime.datetime.now() status_error = bool('yes' == params.get('status_error', 'no')) # list of sandbox agregation managers (list of lists of list of sandboxes) sb_agg_list = make_sandboxes(params, env) # Number of sandboxes for each aggregate type ...
olivierverdier/sfepy
tests/test_functions.py
Python
bsd-3-clause
4,539
0.013439
# c: 14.04.2008, r: 14.04.2008 import numpy as nm from sfepy import data_dir filename_mesh = data_dir + '/meshes/2d/square_unit_tri.mesh' def get_pars(ts, coors,
mode=None, region=None, ig=None, extra_arg=None): if mode =
= 'special': if extra_arg == 'hello!': ic = 0 else: ic = 1 return {('x_%s' % ic) : coors[:,ic]} def get_p_edge(ts, coors, bc=None): if bc.name == 'p_left': return nm.sin(nm.pi * coors[:,1]) else: return nm.cos(nm.pi * coors[:,1]) def get_circle(c...
JakeWimberley/Weathredds
rtr/urls.py
Python
gpl-3.0
1,521
0
""" Copyright 2016 Jake Wimberley. This file is part of RunToRun. RunToRun 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 v...
ort Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^
blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('tracker.urls')), ]
kmp3325/linguine-python
test/remove_stopwords_test.py
Python
mit
446
0.022422
import unittest import sys from li
nguine.ops.remove_stopwords import RemoveStopwords class RemoveStopwordsTest(unittest.TestCase): def setUp(self): self.op = RemoveStopwords() def test_run(self): self.op = RemoveStopwords() self.test_data = [] self.assertEqual(self.op.run(se
lf.test_data), ['quick,','brown','fox','jumps','over','lazy','dogs'] ) if __name__ == '__main__': unittest.main()
josiah-wolf-oberholtzer/supriya
supriya/ugens/beq.py
Python
mit
5,478
0.000548
import collections from supriya import CalculationRate from supriya.ugens.filters import Filter class BEQSuite(Filter): """ Abstract base class of all BEQSuite UGens. """ class BAllPass(BEQSuite): """ An all-pass filter. :: >>> source = supriya.ugens.In.ar(0) >>> ball_pass...
ya.ugens.BBandPass.ar( ... bandwidth=1, ... frequency=1200, ... source=source, ... ) >>> bband_pass BBandPass.ar() """ _ordered_input_names = collections.OrderedDict( [("source", None), ("frequency", 1200), ("bandwidth", 1)] )
_valid_calculation_rates = (CalculationRate.AUDIO,) class BBandStop(BEQSuite): """ A band-stop filter. :: >>> source = supriya.ugens.In.ar(0) >>> bband_stop = supriya.ugens.BBandStop.ar( ... bandwidth=1, ... frequency=1200, ... source=source, ....
rob-b/django-tagcon
setup.py
Python
mit
783
0.002554
import os from distutils.core import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name='django-tagcon', version='0.1alpha1', description="A template tag constructor library for Django.", long_description=read('README.rst'), author='Tom Tobin'...
[email protected]', license='MIT', url='http://github.com/korpios/django-tagcon', py_modules=['tagcon'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: O
SI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], )
spreg-git/pysal
pysal/core/util/tests/test_shapefile.py
Python
bsd-3-clause
16,445
0.001034
import unittest from cStringIO import StringIO from pysal.core.util.shapefile import noneMax, noneMin, shp_file, shx_file, NullShape, Point, PolyLine, MultiPoint, PointZ, PolyLineZ, PolygonZ, MultiPointZ, PointM, PolyLineM, PolygonM, MultiPointM, MultiPatch import os import pysal class TestNoneMax(unittest.TestCase):...
'Shape Type': 1}, {'Y': -0.43558951965065495, 'X': 0.11233624454148461, 'Shape Type': 1}, {'Y': -0.40578602620087334, 'X': 0.13984716157205224, 'Shape Type': 1}] assert points == expected def test___len__(self): shp = shp_file(pysal.ex...
= [{'Shape Type': 1, 'X': 0, 'Y': 0}, {'Shape Type': 1, 'X': 1, 'Y': 1}, {'Shape Type': 1, 'X': 2, 'Y': 2}, {'Shape Type': 1, 'X': 3, 'Y': 3}, {'Shape Type': 1, 'X': 4, 'Y': 4}] for pt in points: shp.add_shape(pt) shp.cl...
annegentle/magnum
magnum/common/rpc.py
Python
apache-2.0
4,371
0
# Copyright 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 required by...
ods() TRANSPORT = messaging.get_transport(conf, allowed_remote_exmods=exmods, aliases=TRANSPORT_ALIASES) serializer = RequestContextSerializer(JsonPayloadSerializer()) NOTIFIER = messaging.Notifier(TRANSPORT, serializer=serializ...
assert NOTIFIER is not None TRANSPORT.cleanup() TRANSPORT = NOTIFIER = None def set_defaults(control_exchange): messaging.set_transport_defaults(control_exchange) def add_extra_exmods(*args): EXTRA_EXMODS.extend(args) def clear_extra_exmods(): del EXTRA_EXMODS[:] def get_allowed_exmods()...
mph-/lcapy
lcapy/tests/test_statespace.py
Python
lgpl-2.1
4,517
0.008634
from lcapy import * import numpy as np import unittest class LcapyTester(unittest.TestCase): """Unit tests for lcapy state space analysis """ def assertEqual2(self, ans1, ans2, comment): ans1 = ans1.canonical() ans2 = ans2.canonical() try: self.assertEqual(ans1,...
self.assertEqual(ss.x0[1], 0, "x0[1]") self.assertEqual(ss.y[0], expr('v_1(t)'), "y[0]")
self.assertEqual(ss.u[0], expr('v(t)'), "u[0]") self.assertEqual(ss.A[0, 0], expr('-R1/L'), "A[0, 0]") def test_transfer(self): Z = (s**2 + 3) / (s**3 + 2 * s + 10) ss = Z.state_space() self.assertEqual(ss.Nx, 3, "Nx") self.assertEqual(ss.Ny, 1, "...
aelkikhia/pyduel_engine
pyduel_gui/widgets/board_select_widget.py
Python
apache-2.0
957
0.00209
#!/usr/bin/python # -*- coding: utf-8 -*- from PyQt4 import QtGui # from pyduel_engine.content.engine_states import BoardType class BoardSelectWidget(QtGui.QComboBox)
: def __init__(self, board_types, parent=None): super(BoardSelectWidget, self).__init__(parent) self.board_types = board_types # dimensions policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred,
QtGui.QSizePolicy.Preferred) self.setSizePolicy(policy) # populate for name, member in self.board_types.__members__.items(): self.addItem(name.title(), member) def getBoard(self): """Return BoardType selection""" return self.curren...
edac-epscor/nmepscor-data-collection-form
application/base/urls.py
Python
mit
945
0.004233
from django.conf
.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns
= patterns('', (r'^$', 'builder.views.metadataIdx'), # Approot, not listview (r'^submissions/', include('builder.urls')), (r'^keepAlive$', 'builder.views.revalidate'), (r'^signin$', 'builder.views.authDrupal'), (r'^logout$', 'builder.views.signout'), (r'^users/', include('userprofiles.urls')), ...
Endika/hr
hr_employee_education/__openerp__.py
Python
agpl-3.0
1,451
0.000689
# -*- coding:utf-8 -*- # # # Copyright (C) 2011,2013 Michael Telahun Makonnen <[email protected]>. # All Rights Reserved. # # 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 Foundat
ion, either version 3 of the License, or # (at your option) any later version. # # This program is dist
ributed 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # ...
jwg4/qual
tools/compare_navy_day_numbers.py
Python
apache-2.0
1,862
0.004834
import logging import re import requests from datetime import timedelta, date as vanilla_date from calexicon.calendars import JulianDayNumber logging.basicConfig(level=logging.INFO) URL = "http://aa.usno.navy.mil/cgi-bin/aa_jdconv.pl?form=1&year=%d&month=%d&day=%d&era=1&hr=0&min=0&sec=0.0" def get_navy_day_number(...
esponse: %s" % content) match = re.search('JD ([0-9]+)[.]', content) if not match: raise Exception("Could not parse a Julian day number from the response") return int(match.group(1)) def get_calexicon_number(year, month, day): vd = van
illa_date(year, month, day) d = JulianDayNumber().from_date(vd) return d.native_representation()['day_number'] def compare(vd): year = vd.year month = vd.month day = vd.day navy_number = get_navy_day_number(year, month, day) calexicon_number = get_calexicon_number(year, month, day) logg...
SciTools/iris
lib/iris/tests/test_intersect.py
Python
lgpl-3.0
3,364
0.000297
# Copyright Iris contributors # # This file is part of Iris and is released under the LGPL license. # See COPYING and COPYING.LESSER in the root of the repository for full # licensing details. """ Test the intersection of Coords """ # import iris tests first so that some things can be initialised before importing any...
, 5, 6, 7, 8], [5, 6, 7, 8, 50], ], dtype=np.int32, ) ) lonlat_cs = iris.coord_systems.RotatedGeogCS(10, 20) cube2.add_dim_coord( iris.coords.DimCoord( np.arange(5, dtype=np.float32) * 90, ...
d( np.arange(5, dtype=np.float32) * 45 - 90, "latitude", units="degrees", coord_system=lonlat_cs, ), 0, ) cube2.add_aux_coord( iris.coords.DimCoord( points=np.int32(11), long_name="pressur...
TechWritingWhiz/indy-node
indy_common/test/types/test_get_attrib_schema.py
Python
apache-2.0
725
0.001379
import pytest from indy_common.types import ClientGetAttribOperation from collections import OrderedDict from plenum.common.messages.fields import ConstantField, LimitedLengthStringField, IdentifierField EXPECTED_ORDERED_FIELDS = OrderedDict([ ("type", ConstantField), ("dest", IdentifierField), ("raw", Li...
ict(ClientGetAttribOperation.schema).keys() assert actual_field_names == EXPECTED_ORDERED_FIELDS.keys() def test
_has_expected_validators(): schema = dict(ClientGetAttribOperation.schema) for field, validator in EXPECTED_ORDERED_FIELDS.items(): assert isinstance(schema[field], validator)
ImEmJay/AlexaPi
src/alexapi/tunein.py
Python
mit
13,267
0.000151
from __future__ import unicode_literals import ConfigParser as configparser import logging import re import time import urlparse from collections import OrderedDict from contextlib import closing import requests try: import cStringIO as StringIO except ImportError: import StringIO as StringIO try: impo...
for entry in element.findall('entry[@href]'):
yield fix_asf_uri(entry.get('href', '').strip()) except elementtree.ParseError: return def parse_asx(data): if 'asx' in data.getvalue()[0:50].lower(): return parse_new_asx(data) else: return parse_old_asx(data) # This is all broken: mopidy/mopidy#225 # from gi.repository i...
wandb/client
wandb/vendor/pygments/lexers/r.py
Python
mit
23,755
0.000168
# -*- coding: utf-8 -*- """ pygments.lexers.r ~~~~~~~~~~~~~~~~~ Lexers for the R/S languages. :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import Lexer, RegexLexer, include, words, do_insertions from ...
er.POSIXt', 'as.character.condition', 'as.character.default', 'as.character.error', 'as.character.factor', 'as.character.hexmode', 'as.character.numeric_version', 'as.character.octmode', 'as.character.srcref', 'as.complex', 'as.data.frame', 'as.data.frame.AsIs
', 'as.data.frame.Date', 'as.data.frame.POSIXct', 'as.data.frame.POSIXlt', 'as.data.frame.array', 'as.data.frame.character', 'as.data.frame.complex', 'as.data.frame.data.frame', 'as.data.frame.default', 'as.data.frame.difftime', 'as.data.frame.factor', 'as.data.frame.integer', 'a...
provegard/airpnp
airpnp/device_builder.py
Python
bsd-3-clause
5,271
0
# -*- coding: utf-8 -*- # Copyright (c) 2011, Per Rovegård <[email protected]> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright #...
se or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY A
ND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BU...
coxmediagroup/googleads-python-lib
examples/dfp/v201411/placement_service/update_placements.py
Python
apache-2.0
2,284
0.007443
#!/usr/bin/python # # Copyright 2014 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 b...
missions and # limitations under the License. """This code example updates a single placement to allow for AdSense targeting. To determine which placements exist, run get_all_placements.py. """ __author__ = ('Nicholas Chen', 'Joseph DiLallo') # Import appropriate modules from the client library. from ...
e appropriate service. placement_service = client.GetService('PlacementService', version='v201411') # Create query. values = [{ 'key': 'placementId', 'value': { 'xsi_type': 'NumberValue', 'value': placement_id } }] query = 'WHERE id = :placementId' statement = dfp.FilterS...
ramezquitao/pyoptools
pyoptools/raytrace/calc/calc.py
Python
gpl-3.0
25,857
0.026221
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Method collection to obtain optical system information This module contains a method collection to obtain information, and analyze optical systems ''' __all__=["intersection", "nearest_points", "chief_ray_search", "pupil_location", "paraxial_location", "find...
dist=sqrt(square(x)+square(y))
except: #log.info("CCD not hitted by ray") dist=inf if p_dist>dist: #Select this ray as new generator ray btx=rx bty=ry p_dist=dist nt=0 retray=tray #log.info("distance to aperture ce
klebercode/pmsal
pmsal/bid/models.py
Python
mit
1,391
0
# coding: utf-8 from django.db import models from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ import uuid import os class Entry(models.Model): def g
et_file_path(instance, filename): ext = filename.split('.')[-1] filename = "%s.%s" % (uuid.uuid4(), ext) return os.path.join('licitacao', filename) created = models.DateTi
meField(_(u'Data de Criação'), auto_now_add=True) modified = models.DateTimeField(_(u'Data de Modificação'), auto_now=True) description = models.TextField(_(u'Objeto da Licitação')) process = models.CharField(_(u'Processo Licitatório Nº'), max_length=20) price = models.CharField(_(u'Tomada de Preços Nº'...
survey-methods/samplics
src/samplics/utils/hadamard.py
Python
mit
6,813
0.002643
"""computes Hadamard matrices. A Hadamard matrix is a square matrix whose entries are either +1 or −1 and whose rows are mutually orthogonal.The Hadamard matrix is used to derive the BRR replicate weights. It is conjectured that a Hadamard matrix exist for all n divisible by 4. However, the *hadarmard(n)* functions f...
4 = np.ones((24, 24)) row1_c1 = np.array([1, 3, 7, 8, 9, 11]) row1_c2 = np.array([13, 15, 19, 20, 21, 23]) for r1 in range(0, 11): for c1 in row1_c1: hadamard24[r1 + 1, c1] = -1 row1_c1 = (row1_c1 + 1) % 12 if row1_c1[5] == 0: row1_c1[5] = 1 row1_...
1_c2[5] == 0: row1_c2[5] = 13 row1_c2 = np.sort(row1_c2) row2_c1 = np.array([1, 3, 7, 8, 9, 11]) row2_c2 = np.array([14, 16, 17, 18, 22]) for r2 in range(12, 23): for c1 in row2_c1: hadamard24[r2 + 1, c1] = -1 row2_c1 = (row2_c1 + 1) % 12 if row2_...
hcs/mailman
src/mailman/rest/templates.py
Python
gpl-3.0
2,043
0.000489
# Copyright (C) 2012 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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 opt...
# Use mimetypes.guess_all_extensions()? EXTENSIONS = { 'text/plain': '.txt', 'text/html': '.html', } class TemplateFinder(resource.
Resource): """Template finder resource.""" def __init__(self, mlist, template, language, content_type): self.mlist = mlist self.template = template self.language = language self.content_type = content_type @resource.GET() def find_template(self, request): # XXX ...
cp16net/trove
trove/extensions/mgmt/instances/service.py
Python
apache-2.0
8,014
0
# 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...
if selected_action is not None: msg = _("Only one action can be specified per request.") raise exception.BadRequest(msg) sel
ected_action = _actions[key] else: msg = _("Invalid instance action: %s") % key raise exception.BadRequest(msg) if selected_action: return selected_action(context, instance, body) else: raise exception.BadRequest(_("Invalid request bod...
richardcornish/timgorin
jobboardscraper/jobboardscraper/wsgi.py
Python
bsd-3-clause
408
0
""" WSGI config for jobboardscraper project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see http
s://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jobboardscraper.settings") application = get_wsgi_application()
opnsense/core
src/opnsense/scripts/shaper/lib/__init__.py
Python
bsd-2-clause
7,689
0.004292
""" Copyright (c) 2020 Ad Schellevis <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, ...
int(parts[1]) if parts[1].isdigit() else 0, 'bytes': int(parts[2]) if parts[2].isdigit() else 0, 'accessed': datetime.datetime.fromtimestamp(int(parts[3])).isoformat() if parts[3].isdigit() else '', 'accessed_epoch': int(par
ts[3]) if parts[3].isdigit() else 0, 'attached_to': parts[5], 'rule_uuid': None } if line.find('//') > -1: rule_uuid = line[line.find('//')+3:].strip().split()[0] if rule_uuid.count('-') == 4: rule['rule_uuid'] =...
XerxesDGreat/library-app
library/urls.py
Python
apache-2.0
2,235
0.008054
from django.conf.urls import patterns, url from library import views from django.views.generic.base import TemplateView urlpatterns = patterns('', # author urls url(r'^authors/create/', views.AuthorCreateView.as_view(), name='author_add'), url(r'^authors/search/$', views.author_
search, name='author_search'), url(r'^authors/$', views.AuthorIndexView.as_view(), name='author_index'), # book urls url(r'^books/(?P<pk>\d+)/update/$', views.BookUpdateView.as_view(), name='book_update'), url(r'^books/(?P<pk>\d+)/$', views.BookDetailView.as_view(), name='book_detail'), url(r'^books...
title/$', views.book_title_search, name='book_search'), url(r'^books/$', views.BookIndexView.as_view(), name='book_index'), # patron urls url(r'^patrons/(?P<pk>\d+)/$', views.PatronDetailView.as_view(), name='patron_detail'), url(r'^patrons/(?P<pk>\d+)/update/$', views.PatronUpdateView.as_view(), name='...
pywikibot-catfiles/file-metadata
tests/image/jpeg_file_test.py
Python
mit
1,837
0
# -*- coding: utf-8 -*- from __future__ import (division, absolute_import, unicode_literals, print_function) import os from file_metadata.image.jpeg_file import JPEGFile from tests import fetch_file, unittest class JPEGFileTest(unittest.TestCase): def test_filename_zxing(self): ...
hough no barcode is detected, this test is to ensure that the # "Unsupported File Form
at" error doesn't occur for CMYK files. def test_jpeg_unknown_cmyk(self): with JPEGFile(fetch_file('unknown_cmyk.jpg')) as uut: data = uut.analyze_barcode_zxing() self.assertNotIn('zxing:Barcodes', data) # Although no barcode is detected, this test is to ensure that the ...
kingvuplus/Test-OBH
lib/python/Components/Ipkg.py
Python
gpl-2.0
5,412
0.032336
import os from enigma import eConsoleAppContainer from Components.Harddisk import harddiskmanager opkgDestinations = [] opkgStatusPath = '' def opkgExtraDestinations(): global opkgDestinations return ''.join([" --dest %s:%s" % (i,i) for i in opkgDestinations]) def opkgAddDestination(mountpoint): pass #global opk...
cache = data else:
self.cache += data if '\n' in data: splitcache = self.cache.split('\n') if self.cache[-1] == '\n': iteration = splitcache self.cache = None else: iteration = splitcache[:-1] self.cache = splitcache[-1] for mydata in iteration: if mydata != '': self.parseLine(mydata) def pars...
chromium/chromium
third_party/android_deps/libs/com_android_support_documentfile/3pp/fetch.py
Python
bsd-3-clause
2,497
0
#!/usr/bin/env python3 # Copyright 2021 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. # This is generated, do not edit. Update BuildConfigGenerator.groovy and # 3ppFetch.template instead. import argparse import json imp...
d xmls. Only use regular expression parsing to be # safe. RE should be enough to handle what we need to extract. match = re.search('<latest>([^<]+)</latest>', metadata) if match: l
atest = match.group(1) else: # if no latest info was found just hope the versions are sorted and the # last one is the latest (as is commonly the case). latest = re.findall('<version>([^<]+)</version>', metadata)[-1] print(latest + f'.{_PATCH_VERSION}') def get_download_url(version): ...
carlosmccosta/Electric-Dipole
Source code/Electric dipole field lines.py
Python
mit
5,205
0.013336
from __future__ import division #Para não truncar a divisão de inteiros from visual import * #Módulo com as funções gráficas do VPython from math import * scene_range = 15 scene.width = 1920 scene.height = 1080 scene.fullscreen = True scene.autoscale = False scene.range = (scene_range, scene_range, scen...
olo_pos.pos dist_particulas_neg = array_particulas_emf[i].pos - polo_neg.pos Eqp = ((9*10**9 * carga_polo_pos * 1.602*10**-19) / mag(dist_particulas_pos)**2) * norm(dist_particulas_pos) Eqn = ((9*10**9 * carga_polo_neg * 1.602*10**-19) / mag(dist_particul...
eg)**2) * norm(dist_particulas_neg) E = Eqp + Eqn #x = x0 + v*t #Como se está a desenhar as linhas de campo, está-se a percorrer o espaço usando E como vector director (análogo à velocidade de uma partícula) pos = array_particulas_emf[i].pos + E * dt ...
adalke/rdkit
rdkit/Chem/AtomPairs/UnitTestDescriptors.py
Python
bsd-3-clause
2,805
0.029947
# $Id$ # # Copyright (C) 2007 greg Landrum # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # from __future__ import print_function import unittest...
[i]) self.assertTrue(tt!=torsions[i-1]) def testGithub334(self): m1 = Chem.MolFromSmiles('N#C') self.assertEqual(Utils.NumPiElectrons(m1.GetAtomWithIdx(0)),2) self.assertEqual(Utils.NumPiElectrons(m1.GetAtomWithIdx(1)),2) m1 = Chem.Mol
FromSmiles('N#[CH]') self.assertEqual(Utils.NumPiElectrons(m1.GetAtomWithIdx(0)),2) self.assertEqual(Utils.NumPiElectrons(m1.GetAtomWithIdx(1)),2) if __name__ == '__main__': unittest.main()
iulian787/spack
var/spack/repos/builtin/packages/r-rgexf/package.py
Python
lgpl-2.1
1,241
0.001612
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRgexf(RPackage): """Create, read and write GEXF (Graph Exchange
XML Format) graph files (used in Gephi and others). Using the XML package, it allows the user to easily build/read graph files including attributes, GEXF viz attributes (such as color, size, and position), network dynamics (for both edges and nodes) and edge weighting. Users can build/handle graphs ele...
interact with the igraph package.""" homepage = "http://bitbucket.org/gvegayon/rgexf" url = "https://cloud.r-project.org/src/contrib/rgexf_0.15.3.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/rgexf" version('0.15.3', sha256='2e8a7978d1fb977318e6310ba65b70a9c8890185c819a7...
mcxiaoke/python-labs
labs/photos_walker_00.py
Python
apache-2.0
1,959
0.001585
# -*- coding: UTF-8 -*- # Created by mcxiaoke on 2015/7/6 22:20. __author__ = 'mcxiaoke' import sys, os from os import path from datetime import datetime print 'curren dir is', os.getcwd() print 'command line args is', sys.argv if len(sys.argv) < 2: sys.exit(1) # 批量重命名照片文件 # 根据文件修改日期重命名文件,然后移动到目标文件夹 FILE_NAME_...
_path) if not path.isfile(file_path): continue _, ext = path.splitext(file)
file_st = os.stat(file_path) fm = datetime.fromtimestamp(file_st.st_mtime) print 'file modified time is', fm.strftime("%Y-%m-%d %H:%M:%S"), fm.microsecond src_name = file dest_name = fm.strftime(FILE_NAME_FORMAT) + ext print 'src name is %s' % src_name print 'dest na...
rlucioni/project-euler
euler/solutions/solution_11.py
Python
mit
6,618
0.002419
"""Largest product in a grid In the 20×20 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 8
7 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60
99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 (26) 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 (63) 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 (78) 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 (14) 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67...
RyanWolfe/cloud-custodian
tests/test_vpc.py
Python
apache-2.0
16,157
0.000124
# Copyright 2016 Capital One Services, 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...
ToPort=62000, CidrIp='10.2.0.0/16') p = self.load_policy({ 'name': 'sg-find', 'resource': 'security-group', 'filters': [ {'type': 'ingress', '
IpProtocol': 'tcp', 'FromPort': 60000}, {'GroupName': 'web-tier'}] }, session_factory=factory) resources = p.run() self.assertEqual(len(resources), 1) self.assertEqual(resources[0]['GroupName'], 'web-tier') self.assertEqual( resour...
Azure/azure-sdk-for-python
sdk/cognitiveservices/azure-cognitiveservices-search-visualsearch/azure/cognitiveservices/search/visualsearch/models/filters_py3.py
Python
mit
1,058
0.002836
# 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 cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------...
est.serialization import Model class Filters(Model): """A key-value object consisting of filters that may be specified to limit the results returned by the API. Current available filters: site. :param site: The URL of the site to return similar images and similar products from. (e.g., "www.bing.com"...
Alaxe/judgeSystem
users/migrations/0015_auto_20151217_1932.py
Python
gpl-2.0
694
0.002882
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-17 17:32 from __future__ import un
icode_literals from django.db import migrations, models import users.models class Migration(migrations.Migration): dependencies = [ ('users', '0014_auto_20150930_2125'), ] operations = [ migrations.AlterField( model_name='confirmati
on', name='code', field=models.CharField(default=users.models.gen_randcode, max_length=32), ), migrations.AlterField( model_name='passreset', name='code', field=models.CharField(default=users.models.gen_randcode, max_length=32), ), ...
gwn/dsql
setup.py
Python
mit
832
0
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with ope
n(path.join(here, 'README.rst'), encod
ing='utf-8') as f: long_description = f.read() setup( name='dsql', version='0.4.1', description='Dead simple RDBMS handling lib', long_description=long_description, url='https://github.com/gwn/dsql', author='gwn', author_email='[email protected]', license='MIT', classifiers=[ ...
sheeshmohsin/FaceDetection
webapp/manage.py
Python
mit
804
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "webapp.settings") try: from django.core.management import execute_from_command_line except ImportError:
# The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except I
mportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.ar...
jessekl/flixr
venv/lib/python2.7/site-packages/webassets/filter/rjsmin/__init__.py
Python
mit
631
0
from __future__ import absolute_import try: import rjsmin except ImportError: from . import rjsmin from webassets.filter import Filter __all__ = ('RJSMin',) class RJSMin(Filter): """Minifies Javascript by removing whitespace, comments, etc. Uses the `rJSmin library <http://opensource.perlig.de/rj...
used instead. You may want to do this to get access to the faster C-extension. """ name = 'rjsmin' def output(self, _in, out, **kw):
out.write(rjsmin.jsmin(_in.read()))
NHebrard/ham-multisite
ham/utils/hamtask.py
Python
gpl-3.0
1,998
0.005506
# -*- coding: utf-8 -*- from ..provider.g5k import G5K from constants import SYMLINK_NAME from functools import wraps
import os import yaml import logging def load_env(): env = {
'config' : {}, # The config 'resultdir': '', # Path to the result directory 'config_file' : '', # The initial config file 'nodes' : {}, # Roles with nodes 'phase' : '', # Last phase that have been run 'user' : '', # User id for this job 'kolla_...
Azure/azure-sdk-for-python
sdk/storage/azure-mgmt-storage/azure/mgmt/storage/v2016_01_01/models/_models_py3.py
Python
mit
35,290
0.004307
# 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 ...
None self.reason = None self.message = None class CustomDomain(msrest.serialization.Model): """The custom domain assigned to this storage account. This can be set via Update. All required parameters must be populated in order to send to Azure. :ivar name: Required. Gets or sets the cust...
m domain name assigned to the storage account. Name is the CNAME source. :vartype name: str :ivar use_sub_domain_name: Indicates whether indirect CName validation is enabled. Default value is false. This should only be set on updates. :vartype use_sub_domain_name: bool """ _validation = {...
shaurz/ome
ome/instructions.py
Python
mit
4,080
0.004902
# ome - Object Message Expressions # Copyright (c) 2015-2016 Luke McCarthy <[email protected]> def format_instruction_args(args): return ', '.join('%{}'.format(x) for x in args) class Instruction(object): args = () is_leaf = True check_error = False dest_from_heap = False load_list = () s...
(self, d
est, source): self.dest = dest self.args = [source] def __str__(self): return '%{} = %{}'.format(self.dest, self.source) @property def source(self): return self.args[0]
mollyproject/mollyproject
molly/apps/places/migrations/0009_auto__add_journey__add_scheduledstop.py
Python
apache-2.0
13,531
0.007686
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Journey' db.create_table('places_journey', ( ('id', self.gf('django.db.models....
'False', 'related_name': "'entities'", 'blank': 'True', 'to': "orm['places.EntityType']"}), 'all_types_completion': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'entities_completion'", 'blank': 'True', 'to': "orm['places.EntityType']"}), 'geom...
yToManyField', [], {'to': "orm['places.EntityGroup']", 'symmetrical': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identifier_scheme': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'identifier_value': ('django.db.models.fiel...
madhusudancs/pytask
pytask/profile/tests.py
Python
agpl-3.0
1,307
0.002295
#!/usr/bin/env python # # Copyright 2011 Authors of PyTask. # # This file is part of PyTask. # # PyTask 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 opt...
ven 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 PyTask. If not, see <http://www.gnu.org/licenses/>. """ This file demonstrates two different sty...
one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ __authors__ = [ '"Madhusudan.C.S" <[email protected]>', ] from django.test import TestCase class SimpleTest(TestCase): def test_basic_addition(self): """...
anomaly/vishnu
tests/backend/client/memcache/test_pymemcache.py
Python
apache-2.0
1,393
0
from vishnu.session import Session from vishnu.backend import PyMemcache def memcache_client(sid=None): if sid is None: sid = Session.generate_sid() config = PyMemcache() client = config.client_from_config(sid) return client def test_load(): sid = Session.generate_sid() client_a = ...
is True # clear client.clear() # try to load (not started yet) assert client.load() is False def test_save(): sid = Session.generate_sid() client_a = memcache_client(sid) assert client_a.load() is False client_a.save() assert client_a.load() is True # save some data to t...
assert client_b.load() is True assert client_b.get("key") == "value"
tristanfisher/ffi4wd
config.py
Python
agpl-3.0
755
0.006623
from easyos import easyos import random import string def return_or_make_secret_key(secret_key_file): # If we don't have a secret access key for signing sessions, make one try: with open(secret_key_file, "r") as f: return f.read() except IOError:
print("Creating secret_key file") l = random.randint(25, 50) _rand = "".join(random.choice(string.printable) for i in range(l)) with open(secret_key_file, "w+") as f: f.write(_rand) return f.read() class BaseConfig: LISTEN_HOST = '127.0.0.1' LISTEN_PORT ...
SECRET_KEY = return_or_make_secret_key(easyos["tmp_dir"] + "ffi4wd_development_csrf_key")
deepmind/deepmind-research
physics_inspired_models/models/deterministic_vae.py
Python
apache-2.0
23,158
0.00652
# Copyright 2020 DeepMind Technologies Limited. # # # 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 agre...
[str], encoder_kwargs: Dict[str, Any], decoder_kwargs: Dict[str, Any], num_inference_steps: int, num_target_steps: int, latent_training_type: str, training_data_split: str, obje
ctive_type: str, dt: float = 0.125, render_from_q_only: bool = True, prior_type: str = "standard_normal", use_analytical_kl: bool = True, geco_kappa: float = 0.001, geco_alpha: Optional[float] = 0.0, elbo_beta_delay: int = 0, elbo_beta_final: float = 1.0, name: Opti...
Wyn10/Cnchi
cnchi/installation/download/metalink.py
Python
gpl-3.0
16,922
0.001123
#!/usr/bin/env python # -*- coding: utf-8 -*- # # metalink.py # # Code from pm2ml Copyright (C) 2012-2013 Xyne # Copyright © 2013-2016 Antergos # # This file is part of Cnchi. # # Cnchi is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by #...
dentity'] metalink_info[
key] = element.copy() element.clear() elem.clear() if os.path.exists(temp_file.name): os.remove(temp_file.name) return metalink_info def create(alpm, package_name, pacman_conf_file): """ Creates a metalink to download package_name and its dependencies """ # o...
skuda/client-python
kubernetes/test/test_v1_subject_access_review_spec.py
Python
apache-2.0
943
0.004242
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.6.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
ApiException from kubernetes.client.models.v1_subject_acce
ss_review_spec import V1SubjectAccessReviewSpec class TestV1SubjectAccessReviewSpec(unittest.TestCase): """ V1SubjectAccessReviewSpec unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1SubjectAccessReviewSpec(self): """ Test V1SubjectAccessR...
qstokkink/py-ipv8
ipv8/dht/provider.py
Python
lgpl-3.0
2,972
0.004038
import logging from binascii import hexlify from socket import inet_aton, inet_ntoa from struct import pack, unpack_from from . import DHTError from ..messaging.anonymization.tunnel import IntroductionPoint, PEER_SOURCE_DHT from ..peer import Peer from ..util import cast_to_bin class DHTCommunityProvider(object): ...
ookup(self, mid): try: await self.dht_community.connect_peer(mid) except DHTError as e: self.logger.debug("Failed to connect %s using the DHTCommunity (error: %s)", hexlify(mid), e) return async def lookup(self,
info_hash): try: values = await self.dht_community.find_values(info_hash) except DHTError as e: self.logger.info("Failed to lookup %s on the DHTCommunity (error: %s)", hexlify(info_hash), e) return results = [] for value, _ in values: try:...
gooddata/zuul
zuul/reporter/gerrit.py
Python
apache-2.0
1,929
0
# Copyright 2013 Rackspace Australia # # 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 ...
orter") def report(self, source, pipeline, item, message=None): """Send a message to gerrit.""" if not message: message = self._formatItemReport(pipeline, item) self.log.debug("Report change %s, params %s, message: %s" % (item.change, self.reporter_config...
tchset) item.change._ref_sha = source.getRefSha( item.change.project.name, 'refs/heads/' + item.change.branch) return self.connection.review(item.change.project.name, changeid, message, self.reporter_config) def getSubmitAllowNeeds(self): "...
saymedia/python-simpledb
django/management/commands/sdb_syncdomains.py
Python
bsd-3-clause
914
0.001094
from django.core.management.base import BaseCommand, CommandError from djang
o.db.models.loading import AppCache from django.conf import settings import simpledb class Command(BaseCommand): help = ("Sync all of the SimpleDB domains.") def handle(self, *args, **options): apps = AppCache() check = [] for module in apps.get_apps(): for d in module.__d...
taclass): domain = ref.Meta.domain.name if domain not in check: check.append(domain) sdb = simpledb.SimpleDB(settings.AWS_KEY, settings.AWS_SECRET) domains = [d.name for d in list(sdb)] for c in check: if c not in domai...
fnp/edumed
wtem/admin.py
Python
agpl-3.0
8,331
0.010447
# -*- coding: utf-8 -*- import os from django.contrib import admin from django import forms from django.utils import simplejson from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from django.conf.urls import url, patterns from django.shortcuts import render from django.contrib....
get_user_exercises(user) user_marks = submission.marks.get(str(user.id), {}) return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()]) todo.short_description =
'Twoje nieocenione zadania' def examiners_repr(self, submission): return ', '.join([u.username for u in submission.examiners.all()]) examiners_repr.short_description = 'Przypisani do zgłoszenia' def save_model(self, request, submission, form, change): for name, value in form.cleaned_data....
saintdragon2/python-3-lecture-2015
pygame_study/first_race_game.py
Python
mit
3,830
0.001571
__author__ = 'saintdragon2' import pygame import time import random pygame.init() display_width = 800 display_height = 600 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) green = (0, 255, 0) block_color = (53, 115, 255) carImg = pygame.image.load('car.png') car_width = carImg.get_rect().size[0] game...
e.KEYDOWN: if event.key == pygame.K_LEFT: x_change = -5 elif event.key == pygame.K_RIGHT: x_change = 5 if even
t.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change gameDisplay.fill(white) things(thing_startx, thing_starty, thing_width, thing_height, block_color) thing_starty += thing_speed ...
kubeflow/pipelines
samples/core/resource_spec/resource_spec_test.py
Python
apache-2.0
1,529
0
# Copyright 2021 The Kubeflow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
*kwargs): """confirms a sample test case is failing, because of OOM.""" assert run.status == 'Failed' run_
pipeline_func([ TestCase( pipeline_func=my_pipeline_v2, mode=kfp.dsl.PipelineExecutionMode.V2_ENGINE, ), TestCase( pipeline_func=my_pipeline_v2, mode=kfp.dsl.PipelineExecutionMode.V2_ENGINE, arguments={'n': 21234567}, verify_func=EXPECTED_OOM, ), TestC...
sdispater/eloquent
eloquent/utils/__init__.py
Python
mit
773
0
# -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: long = long unicode = unicode basestring = basestring from urllib import quote_plus, unquote_plus, quote, unquote from urlparse import parse_qsl else: long = int unicode = str basestring = str from urllib....
sl, quote, unquote) class Null(object): def __bool__(self): return False def __eq__(self, other): return other is None def decode(s, encodings=('utf8', 'ascii', 'latin1')): for encoding in encodings: try: return s.decode(encoding) except UnicodeDecodeError: ...
de('utf8', 'ignore')
zhangyage/Python-oldboy
python-auto/p_ssh2/baolei_command.py
Python
apache-2.0
2,237
0.019566
#!/usr/bin/env python # -*- coding:utf-8 -*- #通过堡垒机跳转时间命令传输 import paramiko import os import sys import time blip = "121.42.191.190" #定义的堡垒机信息 bluser = "zhangyage" blpasswd = "MCya9B7ewPoTeNT8" hostname = "116.196.69.47" #定义的业务主机信息 username = "root" password = "Zhangyage" port = 22 passinfo =...
出串是#号表明校验已经通过,退出w
hile resp = channel.recv(9999) if not resp.find(passinfo) ==-1: #输出串含有password说明密码错误 print 'Error info:Autentical failed.' channel.close() #关闭链接对象后退出 ssh.close() sys.exit() buff += resp channel.send('ifconfig\n') #认证通过后发送ufconfig命令...
profgiuseppe/graph-tool-tests
src/graph_tool/all.py
Python
gpl-3.0
2,008
0
#! /usr/bin/env python # -*- coding: utf-8 -*- # # graph_tool -- a general graph manipulation python module # # Copyright (C) 2006-2013 Tiago de Paula Peixoto <[email protected]> # # 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...
port, print_function from graph_tool import * import graph_tool from graph_tool.correlations import * import graph_tool.correlations from graph_tool.centrality import * import graph_tool.centrality try: from graph_tool.draw import * import graph_tool.draw except ImportError: # Proceed despite errors with c...
t * import graph_tool.generation from graph_tool.stats import * import graph_tool.stats from graph_tool.clustering import * import graph_tool.clustering from graph_tool.community import * import graph_tool.community from graph_tool.run_action import * import graph_tool.run_action from graph_tool.topology import * impor...
azariven/BioSig_SEAS
bin/test/test_SEAS_import.py
Python
gpl-3.0
1,357
0.018423
#!/usr/bin/env python # # Copyright (C) 2017 - Massachusetts Institute of Technology (MIT) # # 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...
EAS_Utils.common_utils.timer import si
mple_timer #dbm import SEAS_Utils.common_utils.db_management2 as dbm #config import SEAS_Utils.common_utils.configurable as config #DIR from SEAS_Utils.common_utils.DIRs import Simulation_DB #constants from SEAS_Utils.common_utils.constants import * if __name__ == "__main__": pass ...
clemense/cortex-py
cortex-py/test/test_cortex.py
Python
mit
2,711
0.004795
import time from cortex import * class MyDataHandler: def __init__(self): self.alldata = [] def MyErrorHandler(self, iLevel, msg): print("ERROR: ") print(iLevel, msg.contents) return 0 def MyDataHandler(self, Frame): print("got called") try...
tents.nBodies print "BodyData: ", Frame.contents.BodyData[0].szName print "Number of Markers of Body[0]: ", Frame.contents.BodyData[0].nMarkers for i in range(Frame.contents.BodyData[0].nMarkers):
print "MarkerX ", Frame.contents.BodyData[0].Markers[i][0] print "MarkerY ", Frame.contents.BodyData[0].Markers[i][1] print "MarkerZ ", Frame.contents.BodyData[0].Markers[i][2] print "BodyMarker[2].x: ", Frame.contents.BodyData[0].Markers[3][0] prin...
saltstack/salt
tests/pytests/unit/pillar/test_sql_base.py
Python
apache-2.0
1,158
0
import pytest import salt.pillar.sql_base as sql_base from tests.support.mock import MagicMock class FakeExtPillar(sql_base.SqlBaseExtPillar): """ Mock SqlBaseExtPillar implementation for testing purpose """ @classmethod def _db_name(cls): return "fake" def _get_cursor(self): ...
@pytest.mark.parametrize("as_list", [True, False]) def test_process_results_as_json(as_list): """ Validates merging of dict values returned from JSON datatype. """ return_data = FakeExtPillar() return_data.as_list = as_list return_data.as_json = True return_data.with_lists = None return_...
({"b": [2, 3]},), ({"a": [4]},), ({"c": {"d": [4, 5], "e": 6}},), ({"f": [{"g": 7, "h": "test"}], "c": {"g": 8}},), ] return_data.process_results(test_dicts) assert return_data.result == { "a": [1, 4] if as_list else [4], "b": [2, 3], "c": {"d": [4, 5]...
luotao1/Paddle
python/paddle/fluid/dygraph/dygraph_to_static/static_analysis.py
Python
apache-2.0
15,858
0.000694
# Copyright (c) 2019 PaddlePaddle 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 app...
nce(node_var_type, set): var_type.update(node_var_type) else: var_type.add(node_var_type) def set_var_type(self, var_name, node_var_type): if var_name in self.name_to_id: num_id = self.name_to_id[var_name] else: num_id = self.cur_i...
self.cur_id += 1 self.name_to_id[var_name] = num_id self.id_to_type[num_id] = node_var_type if isinstance( node_var_type, set) else {node_var_type} def get_var_type(self, var_name): if var_name in self.name_to_id: num_id = self.name_to_id[var_name] ...
ejona86/grpc
tools/run_tests/xds_k8s_test_driver/tests/authz_test.py
Python
apache-2.0
12,850
0.000078
# Copyright 2021 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
"principals": [ f"spiffe://{self.project}.svc.id.goog/not/th
e/client", f"spiffe://{self.project}.svc.id.goog/ns/" f"{self.client_namespace}/sa/{self.client_name}", ], }], "destinations": { "hosts": [f"*:{self.server_xds_port}"], "ports": [s...
migonzalvar/mfs2011-practicum-saas
server/agenda.py
Python
isc
10,947
0.001096
import json import redis from interval import interval_overlaps, slots_in_interval, Interval from dataobjects import (Agenda, Shift, Appointment, CollectionDataobjectMixin, ParentkeyDataobjectMixin) class ConcurrencyWarning(Exception): pass class OverlappingIntervalWarning(Exception): ...
_rkey = k(obj.parent_class, obj.parent_key, cls) self._rds.zrem(parent_rkey, key) self._rds.zrem(k(parent_rkey, "end"), key) if issubclass(cls, CollectionDataobjectMixin): if not obj: obj = self.get(cls, key) collection_rkey = k(cls, key, obj.colle...
X: raise specific exception raise ShiftNotEmptyError self._rds.delete(rkey) return def get(self, cls, key): rkey = k(cls, key) payload = self._rds.get(rkey) if payload == None: raise KeyError d = json.loads(payload) obj = cls.from_...
ychen820/microblog
y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/db/transaction.py
Python
bsd-3-clause
10,043
0.002589
""" This module implements a transaction manager that can be used to define transaction handling in a request or view function. It is used by transaction control middleware and decorators. The transaction manager can be in managed or in auto state. Auto state means the system is using a commit-on-save strategy (actual...
tion = connections[using] connection.rollback() def savepoint(using=None): """ Creates a savepoint (if supported and required by the backend) inside the current transaction. Returns an identifier for the savepoint that will be used for the subsequent rollback or commit. """ if using is None...
oint (if one exists). Does nothing if savepoints are not supported. """ if using is None: using = DEFAULT_DB_ALIAS connection = connections[using] connection.savepoint_rollback(sid) def savepoint_commit(sid, using=None): """ Commits the most recent savepoint (if one exists). Does no...
FedoraScientific/salome-smesh
src/Tools/blocFissure/CasTests/fissureCoude_10.py
Python
lgpl-2.1
4,425
0.02815
# -*- coding: utf-8 -*- from blocFissure.gmu.fissureCoude import fissureCoude class fissureCoude_10(fissureCoude): # cas test ASCOU17 # --------------------------------------------------------------------------- def setParamGeometrieSaine(self): """ Paramètres géométriques du tuyau coudé sain: angl...
° : longitudinale, 90° : circonférentielle, autre : uniquement fissures elliptiques lgInfluence : distance autour de la shape de fissure a remailler (si 0, pris égal à profondeur. A ajuster selon le maillage) elliptique :
True : fissure elliptique (longueur/profondeur = grand axe/petit axe); False : fissure longue (fond de fissure de profondeur constante, demi-cercles aux extrémites) pointIn_x : optionnel coordonnées x d'un point dans le solide, pas trop loin du centre du fond de fissure (idem y,z) externe : True : fissure...
Cuuuurzel/KiPyCalc
sympy_old/physics/quantum/state.py
Python
mit
26,583
0.001542
"""Dirac notation for states.""" from sympy import Expr, Symbol, Function, integrate, Expr from sympy import Lambda, oo, conjugate, Tuple, sqrt, cacheit from sympy.printing.pretty.stringpict import prettyForm from sympy.physics.quantum.operator import Operator from sympy.physics.quantum.qexpr import ( QExpr, dis...
. Parameters ========== op : Operator The Operator that is acting on the Ket. options : dict A dict of key/value pairs that control how the operator is applied to the Ket. """ return dispatch_method(self, '_apply_operator', op, **optio...
l property and the brackets for printing. This is an abstract base class and you should not instantiate it directly, instead use Bra. """ lbracket = '<' rbracket = '|' lbracket_pretty = prettyForm(_lbracket) rbracket_pretty = prettyForm(_straight_bracket) lbracket_latex = r'\left\langle...
wclark3/dsge-models
dsf_mfiles/save_results.py
Python
mit
1,975
0.006076
# argv[1] - file path to main folder (like $HOME/dsge-models) # argv[2] - name of model (e.g. 'dsf' or 'nk' or 'ca') from scipy.io import loadmat from sys import argv from json import load TT = 30 # how many periods of results to send model = argv[2] fpath = argv[1] + '/' + model + '_mfiles/' jso...
at') #endo_names = mat['M_']['endo_names'].tolist()[0][0] #endo_simul = mat['oo_']['endo_simul'].tolist()[0][0] # make string of JSON-looking data out of numpy lists #for name, simul in zip(end
o_names, endo_simul): # json += '"' + name.strip() + '":' # json += '[' + ','.join(['%2f' % jj for jj in simul[0:TT]]) + '],' #### 2 - load extra plot vars # load results from mat file and convert to numpy lists (new format though) mat = loadmat(fpath + 'plot_vars.mat') plot_names = mat['plot_vars'].dtype.names...
zqfan/leetcode
algorithms/172. Factorial Trailing Zeroes/solution.py
Python
gpl-3.0
234
0
class Solution(object): def trailingZer
oes(self, n): """ :type n: int :rtype: int """ count_5 = 0 while n > 0: count_5 += n / 5 n /= 5 return co
unt_5
openstack/keystone
keystone/common/rbac_enforcer/enforcer.py
Python
apache-2.0
22,030
0
# 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, software # distributed under t...
s = True # NOTE(cmurphy) Tests may explicitly disable these warnings to # prevent an explosion of test logs if self.suppress_deprecation_warnings: self.__ENFORCER.suppress_deprecation_warnings = True self.register_rules(self.__ENFORCER) self.__...
arning_emitted = False return self.__ENFORCER @staticmethod def _extract_filter_values(filters): """Extract filter data from query params for RBAC enforcement.""" filters = filters or [] target = {i: flask.request.args[i] for i in filters if i in flask.request....
intel-analytics/analytics-zoo
pyzoo/docs/doc-web.py
Python
apache-2.0
942
0.001062
#!/usr/bin/env python # # Copyright 2018 Analytics Zoo Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complia
nce 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or...
/(.*)', 'router' ) app = web.application(urls, globals()) class router: def GET(self, path): if path == '': path = 'index.html' f = open('_build/html/'+path) return f.read() if __name__ == "__main__": app = web.application(urls, globals()) app.run()
ProfessorX/Config
.PyCharm30/system/python_stubs/-1247971765/readline.py
Python
gpl-2.0
6,031
0.010778
# encoding: utf-8 # module readline # from /usr/lib/python3.4/lib-dynload/readline.cpython-34m-x86_64-linux-gnu.so # by generator 1.135 """ Importing this module enables command line editing using GNU readline. """ # no imports # functions def add_history(string): # real signature unknown; restored from __doc__ "...
begidx() -> int get the beginning index of the readline tab-com
pletion scope """ return 0 def get_completer(): # real signature unknown; restored from __doc__ """ get_completer() -> function Returns current completer function. """ pass def get_completer_delims(): # real signature unknown; restored from __doc__ """ get_completer_delims() -...
declankenny/XBMC_datasync
resources/lib/functions.py
Python
mit
2,067
0.014998
import os import pickle import xbmc import urllib2 def getFilesAsDic(FilePath,TrimPath): ''' Based on a passed path build a dictionary of files and update times ''' file_list = {} FilePath = xbmc.validatePath(FilePath) if os.path.isdir(FilePath): for root, dirs, files in os....
outfile) outfile.close() def getDicFromURL(URLPath): try: f = urllib2.urlopen(URLPath) dic = pickle.load(f) f.close() except: dic={} xbmc.log("Data Sync Service:: Cannot Connect to Server, please check IP Address and Port Number") return dic def dow...
r): os.makedirs(local_dir) URLPath = RemoteRoot+FileName.replace("\\","/") f = open(local_path,'wb') try: f.write(urllib2.urlopen(URLPath).read()) temp = 1 except: temp = 0 f.close() return temp
thethythy/Mnemopwd
mnemopwd/client/uilayer/uicomponents/InputBox.py
Python
bsd-2-clause
5,588
0.000716
# -*- coding: utf-8 -*- # Copyright (c) 2016-2017, Thierry Lemeunier <thierry at lemeunier dot net> # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of source code must reta...
r_y, self.cursor_x) self.editorbox.clrtoeol() self.editorbox.refresh() def has_focus(self): """Does the component have the focus""" return self.focus def clear(self): """Clean up the editor content""" self.value = None self.cursor_x = 0 self.focu...
"""Change the content""" self.value = label self.window.clear() self.show() def show(self): """Show the editor""" self.showOrHide = True if self.value is not None: self.editor.populate(self.value) self.cursor_x = len(self.value) ...
fairyzoro/python
JiYouMCC/0003/0003.py
Python
mit
176
0.008772
#
-*- coding: utf-8 -*- # 第 0003 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。 # fail to install redis,
skip it
biosustain/marsi
marsi/alembic/env.py
Python
apache-2.0
1,993
0
from __future__ import with_statement from logging.config import fileConfig from alembic import context from sqlalchemy import engine_from_config, pool # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # Interpret the config file for Pyth...
el # target_metadata = mymodel.Base.metadata target_metadata = None # other values from the config, defined by the needs of env.py, # can be acquired: # my_important_option = config.get_main_option("my_important_option") # ... etc. d
ef run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the gi...
jpurma/Kataja
kataja/runner.py
Python
gpl-3.0
1,380
0.004354
import os import subprocess # This is an example for using Kataja to launch a visualisation from a python script that doesn't use kataja # structures, but can output bracket trees. Kataja is launched as a separate process so it doesn't stop the # main script. def send_to_kataja(tree, image_file=''): # return os...
[.V happen ] ] ]" # tree = """[.{CP} [.{DP(0)} [.{D'} [.{D} which ] [.{NP} [.{N'} [.N wine ] ] ] ] ] [.{C'} [.C \epsilon [.{VP} [.{DP} [.{D'} [.D the ] [.{NP} [.{N'} [.N que
en ] ] ] ] ] [.{V'} [.V prefers ] [.{DP} t(0) ] ] ] ] ] ] # """ tree = """[.{FP} {Graham Greene_i} [.{F'} on_j [.{TP} t_i [.{T'} t_j [.{AuxP} t_j [.{PrtP} kirjoittanut_k [.{VP} t_i [.{V'} t_k [.{DP} tämän kirjan ] ] ] ] ] ] ] ] ] """ send_to_kataja(tree, 'test.pdf') print(f"I just sent {tree} to kataja.") print("th...
eternalfame/django_admin_monitoring
setup.py
Python
mit
1,092
0.001832
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme: README = readme.read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='djang
o_admin_monitoring', version='0.1.3', packages=find_packages(), include_package_data=True, license='MIT License', description='A simple Django app that provides ability to monitor such things as user feedback in admin',
long_description=README, url='https://github.com/eternalfame/django_admin_monitoring', author='Vyacheslav Sukhenko', author_email='[email protected]', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License...
beni55/SimpleCV
SimpleCV/examples/display/qt-example.py
Python
bsd-3-clause
2,247
0.006231
#!/usr/bin/env python ''' This example shows how to display a SimpleCV image in a QT window the code was taken from the forum post here: http://help.simplecv.org/question/1866/any-simple-pyqt-sample-regarding-ui-or-display/ Author: Rodrigo gomes ''' import os import sys import signal from PyQt4 import uic, QtGui, Qt...
eUi(Dialog) QtCore.QMetaObject.connectSlotsByName(Dialog) def retranslateUi(self, Dialog): Dialog.setWindowTitle(_translate("Dialog", "Dialog", None)) class Webcam(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self,parent) self.MainWindow...
self.webcam = Camera(0,{ "width": 640, "height": 480 }) self.timer = QtCore.QTimer() self.connect(self.timer, QtCore.SIGNAL('timeout()'), self.show_frame) self.timer.start(1); def show_frame(self): ipl_image = self.webcam.getImage() ipl_image.dl().circle((150, 75)...
pracedru/pyDesign
PyDesignModel/PyDesignAnalysisItem.py
Python
mit
5,100
0.001373
from PyQt5.QtCore import * from PyDesignData.PyDesignObject import * from PyDesignModel.PyDesignCalcSheetsItem import PyDesignCalcSheetsItem from PyDesignModel.PyDesignIcons import * from PyDesignModel.PyDesignMaterialsItem import PyDesignMaterialsItem from PyDesignModel.PyDesignModelItem import PyDesignModelItem from ...
ren.append(PyDesignMeshesItem(py_design_analysis, self)) self._children.append(PyDesignMaterialsItem(py_design_analysis, self)) self._children.append(PyDesignSolversItem(py_design_analysis, self)) self._type = "PyDesignAnalysisModelItem" self._context_menu = QMenu() add_prop_menu...
ddAction("Add calculation sheet") add_prop_menu.triggered.connect(self.on_add_sheet) add_prop_menu = self._context_menu.addAction("Add geometry") add_prop_menu.triggered.connect(self.on_add_geometry) add_prop_menu = self._context_menu.addAction("Add mesh") add_prop_menu.triggered...
sserrot/champion_relationships
venv/Lib/site-packages/networkx/algorithms/minors.py
Python
mit
17,564
0.000057
# minors.py - functions for computing minors of graphs # # Copyright 2015 Jeffrey Finkelstein <[email protected]>. # Copyright 2010 Drew Conway <[email protected]> # Copyright 2010 Aric Hagberg <[email protected]> # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICEN...
st represent an edge relation on the *blocks* of `G` in the partition induced by `node_relation`. It must take two arguments, *B*
and *C*, each one a set of nodes, and return True exactly when there should be an edge joining block *B* to block *C* in the returned graph. If `edge_relation` is not specified, it is assumed to be the following relation. Block *B* is related to block *C* if and only if some no...