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 |
|---|---|---|---|---|---|---|---|---|
0x19/werkzeug | setup.py | Python | bsd-3-clause | 2,732 | 0 | # -*- coding: utf-8 -*-
"""
Werkzeug
========
Werkzeug started as simple collection of various utilities for WSGI
applications and has become one of the most advanced WSGI utility
modules. It includes a powerful debugger, full featured request and
response objects, HTTP utilities to handle entity tags, cache control
... | ion=__doc__,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Pr... | ],
packages=['werkzeug', 'werkzeug.debug', 'werkzeug.contrib',
'werkzeug.testsuite', 'werkzeug.testsuite.contrib'],
include_package_data=True,
test_suite='werkzeug.testsuite.suite',
zip_safe=False,
platforms='any'
)
|
elijahc/ml_v1 | load_data.py | Python | mit | 4,089 | 0.023233 | import scipy.io as sio
import numpy as np
import pandas as pd
from tqdm import tqdm
import argparse
def main():
parser = argparse.ArgumentParser(description='RNN for modeling neuron populations')
parser.add_argument('infile', metavar='infile', type=str,
help='Input data file path')
... | 'image': image_id-1
}
x_on = np.zeros(stim_len, dtype=np.uint8) + 1
x_off= np.zeros(blank_len, dtyp | e=np.uint8) + 0
x = np.concatenate((x_on, x_off))
trial_vec = np.zeros_like(x,dtype=np.uint8) + r
image_vec = np.zeros_like(x,dtype=np.uint8) + image_id-1
y = resp[:,image_id-1, r,:]
i = i+1
image_bin.extend([x])
image_ids.extend([imag... |
teatimesoft/sugarscape | sim/grids.py | Python | gpl-3.0 | 2,389 | 0.001674 | class SquareGrid:
N = (0, 1)
E = (1, 0)
S = (0, -1)
W = (-1, 0)
PRINCIPAL_DIRECTIONS = (N, E, S, W)
def __init__(self, length, height, wraparound=True):
self.length = length
self.height = height
self.wraparound = wraparound
def get_circle(self, center, radius, *, p):... | se:
return None
def get_all_points(self):
return ((x, y) for x in range(self.length) for y in range(self.height))
def __repr__(self):
return | self.__class__.__name__ + (' no' if not self.wraparound else '') + ' wraparound' + ': {} x {}'.format(self.length, self.height)
class CircularVision:
def __init__(self, distance, *, p):
self.distance = distance
self.p = p
def get_visible_points(self, grid, position):
return grid.get_c... |
agry/NGECore2 | scripts/loot/lootItems/rarelootchest/corellian_seaside.py | Python | lgpl-3.0 | 196 | 0.05102 |
def itemTemplate():
return ['object/tangible/painting/shared_painting_corl_02.iff']
|
def STFparams():
return ['static_item_n','item_painting_corl_02','sta | tic_item_d','item_painting_corl_02'] |
allure-framework/allure-python | allure-pytest/test/acceptance/status/xfail_call_status_test.py | Python | apache-2.0 | 4,151 | 0.003854 | from hamcrest import assert_that
from allure_commons_test.report import has_test_case
from allure_commons_test.result import with_status
from allure_commons_test.result import has_status_details
from allure_commons_test.result import with_message_contains
from allure_commons_test.result import with_trace_contains
def... | ... def test_xfail_do_not_raise_mentioned_exception_example():
... pass
"""
assert_that(executed_docstring_source.allure_report,
has_test_case("test_xfail_ | do_not_raise_mentioned_exception_example",
with_status("passed"),
has_status_details(with_message_contains("XPASS"),
)
)
)
def test_xfail_with_reason_do_not_raise_... |
NiklasRosenstein/localimport | setup.py | Python | mit | 1,978 | 0.0091 | import io
import os
import re
import sys
from setuptools import setup
def restify():
if os.path.isfile('README.md'):
if os.system('pandoc -s README.md -o README.rst') != 0:
print('----------------------------------------------------------')
print('WARNING: pandoc command failed, could not restify R... | ="[email protected]",
url='https://github.com/NiklasRosenstein/localimport',
py_modules=["localimport"],
keywords=["import", "embedded", "modules", "packages"],
classifiers=[
'Development Status :: 5 - Production/Stab | le',
'Environment :: Other Environment', 'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: I... |
arnaudblois/to_do_list | to_do_list/users/apps.py | Python | mit | 276 | 0 | from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'to_do_list.users'
verbose_name = "Users"
def ready(self):
"""Override this to put | in:
Users system checks
Users signal registration
"""
| pass
|
schilduil/suapp | suapp/jandw.py | Python | mit | 11,304 | 0.000885 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (C), 2013, The Schilduil Team. All rights reserved.
"""
import sys
import pony.orm
import suapp.orm
from suapp.logdecorator import loguse, logging
__all__ = ["Wooster", "Drone", "Jeeves"]
class FlowException(Exception):
pass
class ApplicationClos... | imarykey are those from the object having the
foreign key and be | have the same as with do_fetch. The extra parameter
link is the foreign key that is pointing to the set.
"""
origin = self.do_fetch(module, table, primarykey)
result = getattr(origin, link)
return (suapp.orm.UiOrmObject.uize(r) for r in result)
@loguse
def do_fetch(self,... |
fredsmith/will | will/plugins/web/__init__.py | Python | mit | 33 | 0 | MODULE_DESCRIPTION = "Web page | s"
| |
brakhane/panda3d | direct/src/distributed/DistributedCartesianGridAI.py | Python | bsd-3-clause | 5,309 | 0.003014 |
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNo... | strictId, 1000)
# Remove grid parent for this av
avId = av.doId
if avId in self.gridObjects:
del self.gridObjects[avId]
# Stop task if there are no more av's being managed
if len(self.gridObjects) == 0:
self.stopUpdateGridTask()
####################... | ########################
# updateGridTask
# This task is similar to the processVisibility task for the local client.
# A couple differences:
# - we are not doing setInterest on the AI (that is a local client
# specific call).
# - we assume that the moving objects on the grid are parented to... |
wufangjie/leetcode | 745. Prefix and Suffix Search.py | Python | gpl-3.0 | 2,102 | 0.016175 | from utils import memo
import bisect
class WordFilter(object):
def __init__(self, words):
"""
:type words: List[str]
"""
self.n = len(words)
self.words = words
self.seq_w = sorted(range(self.n), key=lambda i: words[i])
self.seq = [words[i] for i in self.seq_... | "abcaccbcaa | "],["a","aa"],["cabaaba","abaaaa"],["cacc","accbbcbab"],["ccbcab","bac"],["bac","cba"],["ac","accabaccaa"],["bcbb","aa"],["ccbca","cbcababac"]]:
print(obj.f(p, s))
print(time.time() - tic)
|
meeb/txmailgunrelay | txmailgunrelay/__init__.py | Python | apache-2.0 | 882 | 0.002268 | # -*- coding: utf-8 -*-
'''
Copyright 2013 Joe Harris
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtai | n 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 implied.
See the License f... | ilgunrelay.smtp import SmtpTransport
def smtp_relay(api_key, testing, sender_domains):
return SmtpTransport(api_key, testing, sender_domains)
'''
EOF
'''
|
knarfeh/print_logs | print_log.py | Python | mit | 2,118 | 0.000944 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import threading
import time
import sys
import logging
__author__ = "[email protected]"
TOTAL = 0
MAXTIME = 0
MINTIME = 0
EXCEPT = 0
logger = logging.getLogger(name=__name__)
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler("/var/log/mathilde/print_debug.log")
... | pt Exception as e:
print("Error: {}".format(e))
EXCEPT += 1
finally:
TOTAL += 1
| def maxtime(self, time_span):
global MAXTIME
if time_span > MAXTIME:
MAXTIME = time_span
def mintime(self, time_span):
global MINTIME
if time_span < MINTIME:
MINTIME = time_span
def test(thread_count):
global TOTAL
global MAXTIME
global MINTI... |
dimitdim/GetARoom | Main/flask/Scripts/easy_install-2.7-script.py | Python | gpl-2.0 | 346 | 0.00578 | #!C:\Users\Mitko\Docum | ents\GitHub\GetARoom\Main\flask\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c11','console_scripts','easy_install-2.7'
__requires__ = 'setuptools==0.6c11'
import sys
from pkg_resources import load_entry_point
sys.exit(
load_entry_point('setuptools==0.6c11', 'console_scr | ipts', 'easy_install-2.7')()
)
|
CyberLabs-BR/face_detect | pyimagesearch/utils/agegenderhelper.py | Python | mit | 5,618 | 0.028124 | # import the necessary packages
import numpy as np
import glob
import cv2
import os
class AgeGenderHelper:
def __init__(self, config):
# store the configuration object and build the age bins used
# for constructing class labels
self.config = config
self.ageBins = self.buildAgeBins()
def buildAgeBins(self):
... | anvas
@staticmethod
def visualizeGender(genderPreds, le):
# initialize the canvas and sort the predictions according
# to their probability
canvas = np.zeros((100, 310, 3), dtype="uint8")
idxs = np.argsort(genderPreds)[::-1]
# loop over the gender predictions in ascending order
for (i, j) in enumerate(i... | male"
text = "{}: {:.2f}%".format(gender, genderPreds[j] * 100)
# draw the label + probability bar on the canvas
w = int(genderPreds[j] * 300) + 5
cv2.rectangle(canvas, (5, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX... |
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/astroid/__pkginfo__.py | Python | apache-2.0 | 2,173 | 0.001841 | # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <[email protected]>
# Copyright (c) 2014-2016 Claudiu Popa <[email protected]>
# Copyright (c) 2014 Google, Inc.
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/master/... | see: https://setuptools.readthedocs.io/en/latest/history.html#id113
"""
return parse_version(setuptools_version) >= parse_version('17.1')
if has_environment_marker_range_operators_support():
extras_require[':python_version<"3.4"'] = ['enum34>=1.1.3', 'singledispatch']
extras_require[':python_version<"... | 4):
install_requires.extend(['enum34', 'singledispatch'])
if py_version < (3, 3):
install_requires.append('backports.functools_lru_cache')
# pylint: disable=redefined-builtin; why license is a builtin anyway?
license = 'LGPL'
author = 'Python Code Quality Authority'
author_email = 'code-quality@... |
a-ro/preimage | preimage/learners/structured_krr.py | Python | bsd-2-clause | 3,990 | 0.002005 | __author__ = 'amelie'
import numpy
from scipy import linalg
from sklearn.base import BaseEstimator
class StructuredKernelRidgeRegression(BaseEstimator):
"""Structured Kernel Ridge Regression.
Attributes
----------
alpha : float
Regularization term.
kernel : Callable
Kernel functi... | eds
.
Attributes
----------
weights : array, shape = [n_samples, n_samples]
Learned weights, where n_samples is the number of training samples.
gram_matrix : array, shape = [n_samples, n_samples]
Gram_matrix | of the training samples.
Y_train : array, shape = [n_samples, ]
Training strings.
y_lengths : array, shape = [n_samples]
Length of each training string in Y_train.
"""
def __init__(self, weights, gram_matrix, Y, y_lengths):
self.weights = weights
self.gram_matrix = gram_m... |
shinymud/ShinyMUD | src/shinymud/models/shiny_types.py | Python | mit | 2,852 | 0.01087 | from shinymud.lib.world import World
import json
world = World.get_world()
def to_bool(val):
"""Take a string representation of true or false and convert it to a boolean
value. Returns a boolean value or None, if no corresponding boolean value
exists.
"""
bool_states = {'true': True, 'false': False... | plit(',')
def write_list(val):
if not val:
ret | urn None
return ','.join(map(str,val))
def copy_list(val):
return val[:]
def read_area(val):
if isinstance(val, basestring):
return world.get_area(val)
return val
def write_area(val):
if isinstance(val, basestring):
return val
return val.name
def read_merchandise(val):
re... |
zerolab/wagtail | wagtail/sites/views.py | Python | bsd-3-clause | 1,799 | 0.001112 | from django.utils.translation import gettext_lazy as _
from wagtail.admin.ui.tables import Column, StatusFlagColumn, TitleColumn
from wagtail.admin.views import generic
from wagtail.admin.viewsets.model import ModelViewSet
from wagtail.core.models import Site
from wagtail.core.permissions import site_permission_policy... | ect_name = 'site'
template_name = 'wagtailsites/edit.html'
class DeleteView(generic.DeleteView):
success_message = _("Site '{0}' deleted.")
page_title = _("Delete site")
confirmation_message = _("Are you sure you want to delete this site?")
class SiteViewSet(ModelViewSet):
icon = 'site'
mode... | n_policy
index_view_class = IndexView
add_view_class = CreateView
edit_view_class = EditView
delete_view_class = DeleteView
def get_form_class(self, for_update=False):
return SiteForm
|
lynxis/pkpgcounter | setup.py | Python | gpl-3.0 | 2,361 | 0.015248 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# pkpgcounter : a generic Page Description Language parser
#
# (c) 2003-2009 Jerome Alet <[email protected]>
# This pr | ogram 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 ve | rsion.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License... |
rtevans/tacc_stats_old | analyze/process_pickles/htrate.py | Python | lgpl-2.1 | 2,109 | 0.045993 | #!/usr/bin/env python
import sys
sys.path.append('../../monitor')
import datetime, glob, job_stats, os, subprocess, time
import matplotlib
if not 'matplotlib.pyplot' in sys.modules:
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy
import scipy, scipy.stats
import argparse
import tspl, tspl_utils
c... | t=tspl_utils.getfilelist(n.filearg)
for file in filelist:
try:
full=''
ts=tspl.TSPLBase(file,['amd64_sock', 'amd64_sock', 'amd64_sock'],
['HT0', 'HT1', 'HT2'])
except tspl.TSPLException as e:
continue
if not tspl_utils.checkjob(ts,3600,16): # 1 hour, 16way on... | f ts.numhosts < 2: # At least 2 hosts
print ts.j.id + ': 1 host'
continue
print ts.j.id
tmid=(ts.t[:-1]+ts.t[1:])/2.0
dt=numpy.diff(ts.t)
fig,ax=plt.subplots(1,1,figsize=(8,6),dpi=80)
ax.hold=True
xmin,xmax=[0.,0.]
c=Colors()
for k in ts.j.hosts.keys():
h=ts.j.hosts[k... |
NORDUnet/opennsa | opennsa/backends/force10.py | Python | bsd-3-clause | 10,163 | 0.009544 | """
Force10 Backend.
This backend will only work with SSH version 2 capable Force10 switches.
This excludes most, if not all, of the etherscale series.
The backend has been developed for the E series.
The backend has been developed and tested on a Terascale E300 switch.
The switch (or router, depending on your leve... | sword):
self.ssh_connection_creator = ssh_connection_creator
self.enable_password = enable_password
@defer.inline | Callbacks
def sendCommands(self, commands):
# Note: FTOS does not allow multiple channels in an SSH connection,
# so we open a connection for each request. Party like it is 1988.
# The "correct" solution for this would be to create a connection pool,
# but that won't happen just no... |
ProgressiveFX/pyblish-pfx | pyblish_pfx/plugins/maya/modeling/_validate_displaylayer.py | Python | lgpl-3.0 | 692 | 0 | import pyblish.api
import maya.cmds as cmds
import pymel
class ValidateDisplaylayer(pyblish.api.Validator):
""" Ensure no construction history exists on the nodes in the instance """
families = ['scene']
optional = True
label = 'Modeling - Display Layers'
def process(self, instance):
"""... | ls(type='displayLayer'):
# skipping references
if pymel.core.PyNode(layer).isReferenced():
return
if layer != 'defaultLayer':
layers.append(layer)
assert not layers, 'Scene ha | s displayLayers: %s' % layers
|
vwc/agita | src/vwcollective.simplecontact/vwcollective/simplecontact/tests/test_contactsportlet.py | Python | mit | 3,908 | 0.003582 | from zope.component import getUtility, getMultiAdapter
from plone.portlets.interfaces import IPortletType
from plone.portlets.interfaces import IPortletManager
from plone.portlets.interfaces import IPortletAssignment
from plone.portlets.interfaces import IPortletDataProvider
from plone.portlets.interfaces import IPort... | mmy form inputs from the add form
addview.createAndAdd(data={})
self.assertEquals(len(mapping), 1)
self.failUnless(isinstance(mapping.values()[0], contactsportlet.Assignment))
# NOTE: This test can be re | moved if the portlet has no edit form
def test_invoke_edit_view(self):
mapping = PortletAssignmentMapping()
request = self.folder.REQUEST
mapping['foo'] = contactsportlet.Assignment()
editview = getMultiAdapter((mapping['foo'], request), name='edit')
self.failUnless(isinstan... |
mambocab/python-driver | tests/unit/cython/test_types.py | Python | apache-2.0 | 1,042 | 0 | # Copyright DataStax, 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, softwa... | r the specific language governing permissions and
# limitations under the License.
from tests.unit.cython.utils | import cyimport, cythontest
types_testhelper = cyimport('tests.unit.cython.types_testhelper')
try:
import unittest2 as unittest
except ImportError:
import unittest # noqa
class TypesTest(unittest.TestCase):
@cythontest
def test_datetype(self):
types_testhelper.test_datetype(self.assertEqua... |
obnam-mirror/cliapp | cliapp/pluginmgr_tests.py | Python | gpl-2.0 | 3,602 | 0 | # Copyright (C) 2009-2012 Lars Wirzenius
#
# 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... | ble_version('1'))
def test_accepts_one_two_three(self):
self.ass | ertTrue(self.pm.compatible_version('1.2.3'))
|
Fenugreek/tamarind | functions.py | Python | gpl-3.0 | 4,617 | 0.006065 | """
Some useful utility functions missing from numpy/scipy.
Copyright 2016 Deepak Subburam
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 la... | ype is None:
dtype = data.dtype
if 'int' in str(dtype): dtype = np.float32
data = data / (np.percentile(abs(data), soft_clip) if soft_clip
else np.max(abs(data)))
if eps: data *= 1. - eps
if soft_clip: data = np.clip(data, -1.0, 1.0)
return data.astype(dt... | ata, axis=axis)[:, None].swapaxes(-1, axis)
def sigmoid(data):
"""Sigmoid activation function."""
return 1 / (1 + np.exp(-data))
def logit(data, eps=1e-8):
"""Inverse of the sigmoid function."""
return -np.log(1 / (data + eps) - 1 + eps)
def elu(data, alpha=1.0, copy=True):
"""Exponential LU... |
Gabotero/GNURadioNext | gr-digital/python/qa_ofdm_txrx.py | Python | gpl-3.0 | 5,471 | 0.004387 | #!/usr/bin/env python
#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
... | samples = (0,) * prepend_zeros + tuple(samples)
src = blocks.vector_source_c(tuple(samples) + (0,) * 1000)
self.rx = ofdm_rx(frame_length_tag_key=len_tag_key, debug_log=LOG_DEBUG_INFO)
if channel is not None:
self.connect(src, channel, self.rx)
else:
self.co... | self.sink = blocks.vector_sink_b()
self.connect(self.rx, self.sink)
def get_rx_bytes(self):
return self.sink.data()
class test_ofdm_txrx (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_tx (s... |
thinkopensolutions/odoo-saas-tools | oauth_provider/models/oauth_provider.py | Python | lgpl-3.0 | 3,090 | 0.002265 | # -*- coding: utf-8 -*-
from odoo import models, fields, api
from datetime import datetime, timedelta
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
try:
from oauthlib import common as oauthlib_common
except:
pass
import uuid
class OauthApplication(models.Model):
CLIENT_ID_CHARACTER_SET = r'_-.:;... | string='User', required=True)
expires = fields.Datetime('Expires', required=True)
scope = fields.Char('Scope')
@api.multi
def is_valid(self, scopes=None):
"""
Checks if the access token is valid.
:param scopes: An iterable containing the scopes to check or None
"""
... | > datetime.strptime(self.expires, DEFAULT_SERVER_DATETIME_FORMAT)
@api.multi
def _allow_scopes(self, scopes):
self.ensure_one()
if not scopes:
return True
provided_scopes = set(self.scope.split())
resource_scopes = set(scopes)
return resource_scopes.issubse... |
alexshepard/aledison | text.py | Python | mit | 877 | 0.011403 | #!/usr/bin/python
import yaml
config = yaml.safe_load(open("config.yml"))
twilio_account_sid = config["twilio"]["account_sid"]
twilio_auth_token = config["twilio"]["auth_token"]
twilio_from_number = config["t | wilio"]["from_number"] |
from twilio.rest import TwilioRestClient
twilio_client = TwilioRestClient(twilio_account_sid, twilio_auth_token)
from contacts import Contacts, Contact
c = Contacts()
# syntax: text.py <contact> <message>
import sys
script_name = sys.argv.pop(0)
name = sys.argv.pop(0)
msg = " ".join([str(x) for x in sys.argv])
con... |
LaurentClaessens/mazhe | src_yanntricks/yanntricksASHYooUVHkak.py | Python | gpl-3.0 | 1,071 | 0.063492 | # -*- coding: utf8 -*-
from yanntricks import *
def ASHYooUVHkak():
pspict,fig = SinglePicture("ASHYooUVHkak")
pspict.dilatation_X(1)
pspict.dilatation_Y(1)
delta=1.2
t1=2
t2=-1.5
s1=Segment( Point(t2-0.4,delta),Point(t1+1,delta) )
s1.parameters.style="dashed"
P=Point(0,delta) |
P.put_m | ark(0.2,45,"\( \delta\)",pspict=pspict,position="corner")
v=Vector(0.3,-0.2)
Q=Point(t1,delta)
R=Point(t2,delta)
m1=Segment( P.translate(-v),P.translate(v) )
m2=Segment( Q.translate(-v),Q.translate(v) )
m3=Segment( R.translate(-v),R.translate(v) )
T=Point(t1,0)
T.put_mark(0.2,t... |
auvsi-suas/interop | server/auvsi_suas/models/access_log.py | Python | apache-2.0 | 4,701 | 0.000851 | """Model for an access log."""
import functools
import logging
import numpy as np
from django.conf import settings
from django.db import models
from django.utils import timezone
logger = logging.getLogger(__name__)
class AccessLogMixin(models.Model):
"""Base class which logs access of information."""
# The ... | where each AccessLogMixin sequence contains all | AccessLogMixins
corresponding to the related TimePeriod. If None, will obtain
by calling by_time_period().
Returns:
A (max, avg) tuple. The max is the max time between logs, and avg
is the avg time between logs.
"""
# Check that time p... |
saicoco/leetcode | array/414_Third_Max_Num.py | Python | gpl-3.0 | 325 | 0.003077 | class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
new_nums = set(nums)
if len(new_nums)<3:
return max(new_nums)
new_nums.remove(max(new_nums))
new_nums.remove(max(new_nums)) |
return max(new_nums)
| |
luogangyi/bcec-nova | nova/virt/libvirt/driver.py | Python | apache-2.0 | 229,211 | 0.000358 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright (c) 2011 Piston Cloud Computing, Inc
# Copyright (c) 2012 University Of Minho
# (c) Copyright 2013 Hewlett-Pa... | deprecated_group='DEFAULT'),
cfg.StrOpt('rescue_ramdisk_id',
help='Rescue ari image',
deprecated_group='DEFAULT'),
cfg.StrOpt('virt_type',
default='kvm',
| help='Libvirt domain type (valid options are: '
'kvm, lxc, qemu, uml, xen)',
deprecated_group='DEFAULT',
deprecated_name='libvirt_type'),
cfg.StrOpt('connection_uri',
default='',
help='Override the default libvirt URI '
... |
sergiomt/centorion | vagrant-setup/cassandra/cqlshlib/cqlhandling.py | Python | apache-2.0 | 27,443 | 0.004409 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | (rulename, symname):
def registrator(f):
def completerwrapper(ctxt):
cass = ctxt.get_binding('cassandra_conn', None)
if cass is None:
return ()
return f(ctxt, cass)
completerwrapper.func_name = 'completerwrapper_on_' + f.func_name
special_c... | urn registrator
def explain_completion(rulename, symname, explanation=None):
if explanation is None:
explanation = '<%s>' % (symname,)
@completer_for(rulename, symname)
def explainer(ctxt, cass):
return [Hint(explanation)]
return explainer
def is_counter_col(cfdef, colname):
col_in... |
jeremyherbert/TumblrServ | tumblrserv.py | Python | gpl-2.0 | 3,373 | 0.013638 | #!/usr/bin/env python
## tumblrserv.py implements a Tumblr (http://www.tumblr.com) markup parsing
## engine and compatible webserver.
##
## Version: 0.2 final
##
## Copyright (C) 2009 Jeremy Herbert
## Contact mailto:[email protected]
##
## This program is free software; you can redistribute i... | r the flag
pull_data( next_arg(arguments, '--pull-data') )
if contains(arguments, '--theme'):
if not os.path.exists("themes/" + next_arg(arguments, '--theme') + '.thtml'):
err_exit("The theme file %s.thtml does not exist in the themes\
direct | ory." % next_arg(arguments, '--theme'))
config['defaults']['theme_name'] = next_arg(arguments, '--theme')
if contains(arguments, '--publish'):
if not has_keys(config['publishing_info'], \
( 'url', 'username', 'password' )):
err_exit('The configuration file is missing some critical publishing\
i... |
ohmu/poni | poni/errors.py | Python | apache-2.0 | 1,028 | 0.016537 | """
error types
Copyright (c) 2010-2012 Mika Eloranta
See LICENSE for details.
"""
class Error(Exception):
"""error"""
class InvalidProperty(Error):
"""invalid property"""
class MissingProperty(Error):
"""missing property"""
class UserError(Error):
"""user error"""
class InvalidRange(Error):
... | invalid range"""
class SettingsError(Error):
"""settings error"""
class VerifyError(Error):
"""verify error"""
class TemplateError(Error):
"""template rendering error"""
class CloudError(Error):
"""cloud error"""
class RemoteError(Error):
"""remote error"""
class RemoteFileDoesNotExist(RemoteE... | """missing library error"""
class RequirementError(Error):
"""requirement error"""
class ControlError(Error):
"""control error"""
class OperationError(Error):
"""operation error"""
|
mozilla-services/FunkLoad | src/funkload/Recorder.py | Python | gpl-2.0 | 15,749 | 0.000889 | # (C) Copyright 2005 Nuxeo SAS <http://nuxeo.com>
# Author: [email protected]
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it wil... | t."""
def __init__(self, file_path):
"""Load a tcpwatch request file."""
self.file_path = file_path
f = open(file_path, 'rb')
line = f.readline().split(None, 2)
if not line:
trace('# Warning: empty first line on %s\n' % self.file_path)
line = f.readlin... | + host
self.rurl = url[len(self.host):]
self.url = url
self.path = path
self.version = line[2].strip()
self.headers = dict(rfc822.Message(f).items())
self.body = f.read()
f.close()
def extractParam(self):
"""Turn muti part encoded form into params."""... |
yosshy/nova | nova/tests/functional/api_samples_test_base.py | Python | apache-2.0 | 15,165 | 0.001912 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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... | except NoMatch:
pass
else:
extra.append(res_obj)
error = []
if expected:
error.append('Extra list items in template:')
error.extend([repr(o) for o in expected])
if extra:
... | _str})
error.extend([repr(o) for o in extra])
if error:
raise NoMatch('\n'.join(error))
elif isinstance(expected, six.string_types) and '%' in expected:
# NOTE(vish): escape stuff for regex
for char in '[]<>?':
expected = expec... |
fifoforlifo/pynja | test2/code/java1/java1.py | Python | apache-2.0 | 331 | 0.003021 | import os
import pynja
import repo
@pynja.project
class java | 1(repo.JavaProject):
def emit(self):
sources = [
"com/java1/Counte | r.java",
]
with self.java_compile_ex(sources) as task:
task.workingDir = os.path.join(self.projectDir, "source")
self.jar_create("java1.jar")
|
pburdet/hyperspy | hyperspy/tests/signal/test_kramers_kronig_transform.py | Python | gpl-3.0 | 6,051 | 0.000331 | # Copyright 2007-2011 The HyperSpy developers
#
# This file is part of HyperSpy.
#
# HyperSpy 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 ... | n=10 | 00.,
full_output=True)
assert_true(np.allclose(self.thickness.data,
output['thickness'].data, rtol=0.01))
@raises(ValueError)
def test_thicness_input_array(self):
cdf = self.s.kramers_kronig_analysis(zlp=self.z... |
pmghalvorsen/gramps_branch | gramps/gen/filters/rules/person/_hasidof.py | Python | gpl-2.0 | 1,631 | 0.005518 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2006 Donald N. Allingham
#
# 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 you... | blic License for more details.
#
# You should have received a copy of the GNU Gener | al 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.
#
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#---------------------------------------------------... |
jtopjian/st2 | st2common/tests/unit/test_isotime.py | Python | apache-2.0 | 5,334 | 0.001687 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | self.assertEqual(isotime.parse('2000-01-01 12:00:00+0000'), dt)
self.assertEqual(isotime.parse('2000-01-01 12:00:00+00:00'), dt)
self.assertEqual(isotime.parse('2000-01-01 12:00:00.000000Z'), dt)
self.assertEqual(isotime.parse('2000-01-01 12:00:00.000000+00'), dt)
self.assertEqual(isot | ime.parse('2000-01-01 12:00:00.000000+0000'), dt)
self.assertEqual(isotime.parse('2000-01-01 12:00:00.000000+00:00'), dt)
self.assertEqual(isotime.parse('2000-01-01T12:00:00Z'), dt)
self.assertEqual(isotime.parse('2000-01-01T12:00:00+00:00'), dt)
self.assertEqual(isotime.parse('2000-01-0... |
eadgarchen/tensorflow | tensorflow/contrib/gan/python/features/python/conditioning_utils_impl.py | Python | apache-2.0 | 3,816 | 0.005241 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | echniques from
https://arxiv.org/abs/1609.03499.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.layers.python.layers import | layers
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import embedding_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import variable_scope
__all__ = [
'condition_tensor',
'condition_tensor_from_onehot',
]
... |
rfadams/python-cvxopt | examples/book/chap6/huber.py | Python | gpl-3.0 | 1,874 | 0.017076 | # Figure 6.5, page 300.
# Robust regression.
from cvxopt import solvers, lapack, matrix, spmatrix
from pickle import load
#solvers.options['show_progress'] = 0
data = l | oad(open('huber.bin','rb'))
u, v = data['u'], data['v']
m, n = len(u), 2
A = matrix( [m*[1.0], [u]] )
b = +v
# Least squares solution.
xls = +b
lapack.gels(+A, xls)
xls = xls[:2]
# Rob | ust least squares.
#
# minimize sum( h( A*x-b ))
#
# where h(u) = u^2 if |u| <= 1.0
# = 2*(|u| - 1.0) if |u| > 1.0.
#
# Solve as a QP (see exercise 4.5):
#
# minimize (1/2) * u'*u + 1'*v
# subject to -u - v <= A*x-b <= u + v
# 0 <= u <= 1
# v >= 0
#
# Variables x (n... |
django-bmf/django-bmf | djangobmf/migrations/0003_auto_20160511_1609.py | Python | bsd-3-clause | 4,122 | 0.005822 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import djangobmf.fields.file
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('djangobmf', '0002_remove_old_report'),
]
ope... | ry_key=True)),
('name', models.CharField(verbose_name='Name', max_length=20)),
('size', models.CharField(verbose_name='Size', max_length=10, default='A4')),
('form', models.CharField(verbose_name='Size', max_length=10, | default='A')),
('template_extends', models.CharField(null=True, verbose_name='Template Extends', blank=True, max_length=40)),
('letter', models.BooleanField(verbose_name='Letter', default=True)),
('letter_margin_top', models.PositiveIntegerField(verbose_name='Letter margi... |
clara-labs/imaplib3 | imaplib3/response.py | Python | mit | 513 | 0 | import re
list_re = re.compile(r'\((.*)\) \"(.*)\" \"(.*)\"')
class Response(object):
# There are three possible server completion responses
OK = "OK" # indicates success
NO = "NO" # indicates failure
| BAD = "BAD" # indicates a protocol error
class ListResponse(object):
def __init__(self, list_response):
match = list_re.match(list_response)
self.attributes = match.group(1).split()
self.hierarchy_delimiter = match.group(2)
| self.name = match.group(3)
|
dante092/Mega-Bus-Web-Crawler | megabus_request.py | Python | mit | 8,077 | 0.0026 | import webtools
import re
class Trip():
""" Models a megabus trip."""
def __init__(self, data, number, mode, crawling_day):
""" Initializes basic trip Data."""
self.data = data
self.trip_number = number
self.mode = mode
self.day = crawling_day
def pric... | date = month + '%2f' + day + '%2f' + year
return date
def format(origin, destination, crawling_date, passengers='2'):
""" Formats a Megabus URL with the destination information."""
base = 'http://us.megabus.com/JourneyResults.aspx?'
origincode = 'originCode=' + generate_city_code(origin)
... | e = '&destinationCode=' + generate_city_code(destination) # Crawling date is provided twice
departuredate = '&outboundDepartureDate=' + generate_date(crawling_date) # This is done to get both outgoing
coming_back = '&inboundDepartureDate=' + generate_date(crawling_date) # and ingoing trips with the same U... |
hhstore/learning-notes | python/src/project/py27/flask_base/flask_online_calculator/server/base.py | Python | mit | 165 | 0.007092 | # -*- coding:utf-8 | -*-
from flask import Flask
app = Flask(__name__)
app.config.from_object('config') # 告诉 Flask 去读取,并使用c | onfig.py配置参数
|
imgmix/django-avatar | avatar/migrations/__init__.py | Python | bsd-3-clause | 608 | 0 | """
Django migrations for django-avatar app
This package does not contain South migrations. South migrations can be found
in the ``south_migrations`` package.
"""
SOUTH_ERROR_MESSAGE = """\n
For South support, customize the SOUTH_MIGRATION_MODULE | S setting like | so:
SOUTH_MIGRATION_MODULES = {
'django-avatar': 'avatar.south_migrations',
}
"""
# Ensure the user is not using Django 1.6 or below with South
try:
from django.db import migrations # noqa
except ImportError:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigu... |
cartwheelweb/packaginator | apps/apiv1/__init__.py | Python | mit | 448 | 0 | """Restful api for the packaginator, based on ``django-tastypie``
(`docs <http://django-tastypie.readthedocs.org/>`_
|
`pypi <http://pyp | i.python.org/pypi/django-tastypie/>`_
|
`repo <https://github.com/toastdriven/django-tastypie/>`_).
This module consists of two components - module :mod:`~apps.apiv1.a | pi`
and the resource definition module :mod:`~apps.apiv1.resources`.
The api urls are exposed in project's main :mod:`urls.py <urls>` file
"""
|
WarwickFilmSoc/WWW-V4 | config.py | Python | gpl-3.0 | 799 | 0.007509 | import os
class Config(object):
# Where to find the templates to build the pages from
TEMPLATE_ROOT = 'templates/default/' # folder containing current template relative to app folder
DEBUG = True
DEVELOPMENT = True
# Secret key
SECRET_KEY = os.urandom(24)
# Flask-SSO Configuration
SS... | GIN_ENDPOINT = '/login/sso'
class ProductionConfig(Config):
DEVELOPMENT = Fals | e
DEBUG = False
SECRET_KEY = open('/opt/secretkey').read() |
ganeshnalawade/ansible | lib/ansible/modules/yum.py | Python | gpl-3.0 | 68,822 | 0.00279 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Red Hat, Inc
# Written by Seth Vidal <skvidal at fedoraproject.org>
# Copyright: (c) 2014, Epic Games, Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, p... | nd the transaction.
type: list
elements: str
version_added: "2.5"
releasever:
description:
- Specifies an alternative release from which all packages will be
installed.
type: str
version_added: "2.7"
autoremove:
description:
- If C(yes), removes all "leaf" packages f | rom the system that were originally
installed as dependencies of user-installed packages but which are no longer
required by any such package. Should be used alone or when state is I(absent)
- "NOTE: This feature requires yum >= 3.4.3 (RHEL/CentOS 7+)"
type: bool
default: "no"
version_... |
trachelr/mne-python | mne/surface.py | Python | bsd-3-clause | 39,201 | 0.000204 | # Authors: Alexandre Gramfort <[email protected]>
# Matti Hamalainen <[email protected]>
# Denis A. Engemann <[email protected]>
#
# License: BSD (3-clause)
import os
from os import path as op
import sys
from struct import pack
from glob import glob
import numpy as... | s not exist'
% path)
files = sorted(glob(op.join(path, '%s*%s.fif'
% (subject, this_source))))
for this_head in files:
try:
surf = read_bem_surfaces(this_head, True,
... | not None:
break
if surf is None:
raise IOError('No file matching "%s*%s" and containing a head '
'surface found' % (subject, this_source))
return surf
def get_meg_helmet_surf(info, trans=None):
"""Load the MEG helmet associated with the MEG sensors
Paramete... |
chjp2046/fbthrift | thrift/test/py/UTF8StringTest.py | Python | apache-2.0 | 2,919 | 0.003083 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | t
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TCompactProtocol
from thrift.util import Serializer
import unittest
import sys
if sys.version_info[0] < 3:
chr = unichr
class AbstractTest():
def setUp(self):
self. | obj = ListTypeVersioningV2(
strings=["plain thing", chr(40960) + 'fun' + chr(1972)],
hello=u"hello\xac\u1234\u20ac\U00008000"
)
def _serialize(self, obj):
return Serializer.serialize(self.protocol_factory, obj)
def _deserialize(self, objtype, data):
return Seria... |
dc3-plaso/plaso | plaso/lib/timelib.py | Python | apache-2.0 | 30,598 | 0.006242 | # -*- coding: utf-8 -*-
"""Time manipulation functions and variables.
This module contain common methods that can be used to convert timestamps
from various formats into number of micro seconds since January 1, 1970,
00:00:00 UTC that is used internally to store timestamps.
It also contains various functions to repre... | mp that represents the timestamp representing not
# a date and time value.
# TODO: replace this with a real None implementation.
NONE_TIMESTAMP = 0
# The days per month of a non leap year
DAYS_PER_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# The number of seconds in a day
SECONDS_PER_DAY =... | s.
MILLI_SECONDS_TO_MICRO_SECONDS = 1000
# The difference between Jan 1, 1980 and Jan 1, 1970 in seconds.
FAT_DATE_TO_POSIX_BASE = 315532800
# The difference between Jan 1, 1601 and Jan 1, 1970 in micro seconds
WEBKIT_TIME_TO_POSIX_BASE = 11644473600 * 1000000
# The difference between Jan 1, 1601 and Jan... |
anthill-services/anthill-common | anthill/common/social/xsolla.py | Python | mit | 4,007 | 0.000998 |
from tornado.httpclient import HTTPRequest, HTTPError
import ujson
import abc
import socket
from urllib import parse
from .. import admin as a
from .. social import SocialNetworkAPI, APIError, SocialPrivateKey
class XsollaAPI(SocialNetworkAPI, metaclass=abc.ABCMeta):
XSOLLA_API = "https://api.xsolla.com"
... | ujson.loads(result.body)
except (KeyError, ValueError):
raise APIError(500, "Corrupted xsolla response")
return response_object
def has_private_key(self):
return True
def new_private_key(self, data) | :
return XsollaPrivateKey(data)
class XsollaPrivateKey(SocialPrivateKey):
def __init__(self, key):
super(XsollaPrivateKey, self).__init__(key)
self.api_key = self.data["api_key"] if self.data else None
self.project_key = self.data["project_key"] if self.data else None
self... |
dpo/opal | opal/core/datamanager.py | Python | lgpl-3.0 | 3,673 | 0.003539 | import os
import string
import types
import time
import shutil
import log
import copy
#import logging
#import utility
from testproblem import TestProblem
from mafrw import Agent
from .. import config
class DataManager(Agent):
"""
An object of this class is responsable to collect data,
support access to... | f.id,
performative='inform',
content={'proposition':{'what':'data-availability',
'how':'complete',
| 'data':dataEntry}
}
)
else:
msg = Message(sender=self.id,
performative='inform',
content={'proposition':{'what':'data-availability',
... |
tigeraniya/django-allauth | test_settings.py | Python | mit | 4,239 | 0.000236 | # -*- coding: utf-8 -*-
import django
SEC | RET_KEY = 'psst'
SITE_ID = 1
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'USER': '',
'PASSWORD': '',
| 'HOST': '',
'PORT': '',
}
}
ROOT_URLCONF = 'allauth.urls'
if django.VERSION >= (1, 8):
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors':... |
maparent/virtuoso-python | virtuoso/vstore.py | Python | bsd-3-clause | 29,332 | 0.002864 | """
"""
__dist__ = __import__("pkg_resources").get_distribution("rdflib")
from builtins import (next, chr, zip, range, object)
from future import standard_library
standard_library.install_aliases()
from builtins import (next, chr, zip, range, object)
import threading
from io import StringIO
import os
import sys
from s... | seed
from string import ascii_letters, digits
seed(time())
__bnode_old_new__ = BNode.__new__
def __bnode_new__(cls, value=None, *av, **kw):
| if value is None:
value = choice(ascii_letters) + \
"".join(choice(ascii_letters + digits) for x in range(7))
return __bnode_old_new__(cls, value, *av, **kw)
BNode.__new__ = staticmethod(__bnode_new__)
## end hack
import re
_ws_re = r'(\s*#[^\n]*\n)*\s*'
_start_re = r'^SPARQL\s+' \
... |
youtube/cobalt | third_party/blink/Tools/Scripts/webkitpy/style/filter.py | Python | bsd-3-clause | 11,780 | 0.00034 | # Copyright (C) 2010 Chris Jerdonek ([email protected])
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions... | th('-')):
raise ValueError('Invalid filter rule "%s": every rule '
'must start with + or -.' % rule)
for category in all_categories:
if category.startswith(rule[1:]):
break
else:
raise ValueError('Suspected incorrect filte... | ning '
'of any category name.' % rule)
class _CategoryFilter(object):
"""Filters whether to check style categories."""
def __init__(self, filter_rules=None):
"""Create a category filter.
Args:
filter_rules: A list of strings that are filter rules, whic... |
esikachev/scenario | sahara/openstack/common/periodic_task.py | Python | apache-2.0 | 8,319 | 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
# ... | riodic_last_run[task_name]
# Check if due, if not skip
idle_for = min(idle_for, spacing)
if last_run is not None:
delta = last_run + spacing - time.time()
if delta > 0:
idle_for = min(idle_for, delta)
continue
... | ask_name] = _nearest_boundary(
last_run, spacing)
try:
task(self, context)
except Exception as e:
if raise_on_error:
raise
LOG.exception(_LE("Error during %(full_task_nam |
asottile/setuptools-golang | testing/internal_imports/setup.py | Python | mit | 478 | 0 | from __future__ import annotations
fr | om setuptools import Extension
from setuptools import setup
setup(
name='internal_imports',
ext_modules=[Extension('hello_lib', ['hello_lib/main.go'])],
build_golang={'root': 'github.com/asottile/fake'},
# Would do this, but we're testing *our* implementation and this would
# install from pypi. W... | equires=['setuptools-golang'],
)
|
lukas-hetzenecker/home-assistant | tests/components/kraken/test_sensor.py | Python | apache-2.0 | 9,736 | 0.000308 | """Tests for the kraken sensor platform."""
from datetime import timedelta
from unittest.mock import patch
from pykrakenapi.pykrakenapi import KrakenAPIError
from homeassistant.components.kraken.const import (
CONF_TRACKED_ASSET_PAIRS,
DEFAULT_SCAN_INTERVAL,
DEFAULT_TRACKED_ASSET_PAIR,
DOMAIN,
)
from ... | PAIR_TICKER_INFORMATION_RESPONSE,
MISSING_PAIR_TRADEABLE_ASSET_PAIR_RESPONSE,
TICKER_INFORMATION_RESPONSE,
TRADEABLE_ASSET_PAIR_RESPONSE,
)
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_sensor(hass):
"""Test that sensor has a value."""
utcnow = dt_util.utcnow()
... | tcnow' to gain more control over the timed update.
with patch("homeassistant.util.dt.utcnow", return_value=utcnow), patch(
"pykrakenapi.KrakenAPI.get_tradable_asset_pairs",
return_value=TRADEABLE_ASSET_PAIR_RESPONSE,
), patch(
"pykrakenapi.KrakenAPI.get_ticker_information",
retur... |
namccart/pybombs | pybombs/package_manager.py | Python | gpl-3.0 | 12,528 | 0.002395 | #
# Copyright 2015 Free Software Foundation, Inc.
#
# This file is part of PyBOMBS
#
# PyBOMBS 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, or (at your option)
# any later version.
#
# PyB... | g_flag and self.check_package_flag(pkgname, 'forcebuild')
if force_build:
self.log.debug("Package {pkg} is requesting a source build.".format(pkg=pkgname))
if install_type == "source" or (install_type == "any" and force_build):
return [self.src,]
if install_type == "binar... | uild is requested."
)
return []
return self.binary_pkgrs
# if install_type == "any":
return [self.src,] + self.binary_pkgrs
def exists(self, name, return_pkgr_name=False):
"""
Check to see if this package is available on this platform.
... |
vex1023/vxData | vxData/exception.py | Python | mit | 585 | 0.003527 | # endcoding = utf-8
'''
author : vex1023
email : [email protected]
'''
ERROR_TEMPLATE = '''{"error_code": "%s", "error_msg": "%s", "reason": "%s"}'''
class APIError(Exception):
'''
交易错误和代码定义
'''
ERROR_CODE = '0 | '
ERROR_MSG = 'Success'
| def __init__(self, reason):
super(APIError, self).__init__(ERROR_TEMPLATE % (self.ERROR_CODE, self.ERROR_MSG, reason))
class InternalError(APIError):
ERROR_CODE = '999'
ERROR_MSG = 'Internal Error'
class NotSupportError(APIError):
ERROR_CODE = '-1'
ERROR_MSG = 'Not Support APIs'
|
ollie314/kafka | tests/kafkatest/sanity_checks/test_console_consumer.py | Python | apache-2.0 | 4,449 | 0.003372 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | l=['PLAINTEXT', 'SSL'])
@cluster(num_nodes=4)
@matrix(security_protocol=['SASL_SSL'], sasl_mechanism=['PLAIN', 'SCRAM-SHA-256', 'SCRAM-SHA-512'])
@matrix(security_protocol=['SASL_PLAINTEXT', 'SASL_SSL'])
def test_lifecycle(self, security_protocol, sasl_mechanism='GSSAPI'):
"""Check that console ... | nism = sasl_mechanism
self.kafka.interbroker_sasl_mechanism = sasl_mechanism
self.kafka.start()
self.consumer.security_protocol = security_protocol
t0 = time.time()
self.consumer.start()
node = self.consumer.nodes[0]
wait_until(lambda: self.consumer.alive(node)... |
openqt/algorithms | leetcode/python/lc993-cousins-in-binary-tree.py | Python | gpl-3.0 | 1,692 | 0.007092 | # coding=utf-8
import unittest
"""993. Cousins in Binary Tree
https://leetcode.com/problems/cousins-in-binary-tree/description/
In a binary tree, the root node is at depth `0`, and children of each depth
`k` node are at depth `k+1`.
Two nodes of a binary tree are _cousins_ if they have the same depth, but have
**dif... | ot = [1,2,3,null,4,null,5], x = 5, y = 4
**Output:** true
**Example 3:**
****
**Input:** root = [1,2,3,null,4], x = 2, y = 3
| **Output:** false
**Note:**
1. The number of nodes in the tree will be between `2` and `100`.
2. Each node has a unique integer value from `1` to `100`.
Similar Questions:
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.... |
collective/cyn.in | src/ubify.viewlets/ubify/viewlets/browser/spaceicon.py | Python | gpl-3.0 | 3,414 | 0.009666 | ###############################################################################
#cyn.in is an open source Collaborative Knowledge Management Appliance that
#enables teams to seamlessly work together on files, documents and content in
#a secure central environment.
#
#cyn.in v2 an open source appliance is distributed un... | w.gnu.org/licenses/>.
#
#You can contact Cynapse at [email protected] with any problems with cyn.in.
#For any queries regarding the licensing, please send your mails to
# [email protected]
#
#You can also contact Cynapse at:
#802, Building No. 1,
#Dh | eeraj Sagar, Malad(W)
#Mumbai-400064, India
###############################################################################
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.viewlets.common import ViewletBase
from zope.component import getMultiAdapter
class SpaceIconViewlet(... |
lehinevych/cfme_tests | utils/tests/test_simple_locators.py | Python | gpl-2.0 | 1,500 | 0.001333 | import pytest
@pytest.fixture(scope='module')
def test_page(browser, datafile):
test_page_html = datafile('elements.html').read()
pytest.sel.get('data:text/html;base64,{}'.format(test_page_html.encode('base64')))
pytestmark = pytest.mark.usefixtures('test_page')
def assert_len(locator, required_len):
a... | id():
# should exist
assert_len('h1#id1', 1)
assert_len('h2#id2', 1)
# shouldn't exist
assert_len('h1#id2', 0)
assert_len('h2#id1', 0)
def test_by_element_with_class():
# should exist
assert_len('h1.class1', 1)
asser | t_len('h2.class1', 1)
assert_len('h2.class2', 1)
# shouldn't exist
assert_len('h1.class3', 0)
def test_by_element_with_id_and_class():
# should exist
assert_len('h1#id1.class1', 1)
assert_len('h2#id2.class2', 1)
assert_len('h2#id2.class2', 1)
# shouldn't exist
assert_len('h1#id1.... |
naphthalene/hubcave | hubcave/core/mixins/tables.py | Python | mit | 4,047 | 0.002224 | from __future__ import absolute_import, unicode_literals
from django.core.paginator import Paginator
from django.core import urlresolvers
from django.utils.html import mark_safe, escape
import django_tables2 as tables
from django_tables2.tables import Table
from django_tables2.utils import Accessor as A, AttributeDic... | that will form an Action Column
"""
empty_values = ()
links = None
delimiter = None
def __init__(self, links=None, delimiter=' | ', **kwargs) | :
super(ActionsColumn, self).__init__(**kwargs)
self.orderable = False
self.delimiter = delimiter
if links is not None:
self.links = links
def render(self, value, record, bound_column):
if not self.links:
raise NotImplementedError('Links not assigned.... |
jodal/pykka | tests/test_future.py | Python | apache-2.0 | 6,910 | 0.000289 | import asyncio
import sys
import traceback
import pytest
from pykka import Future, Timeout, get_all
def run_async(coroutine):
loop = asyncio.get_event_loop()
f = asyncio.ensure_future(coroutine, loop=loop)
return loop.run_until_complete(f)
def test_base_future_get_is_not_implemented():
future = Fu... | ted():
future = Future()
with pytest.raises(NotImplementedError):
future.set_exception(None)
def test_set_multiple_times_fails(future):
future.set(0)
with pytest.raises(Exception):
future.set(0)
def test_get_all_blocks_until_ | all_futures_are_available(futures):
futures[0].set(0)
futures[1].set(1)
futures[2].set(2)
result = get_all(futures)
assert result == [0, 1, 2]
def test_get_all_raises_timeout_if_not_all_futures_are_available(futures):
futures[0].set(0)
futures[1].set(1)
# futures[2] is unset
wit... |
sassoftware/catalog-service | catalogService_test/mockedModules/mint/db/schema.py | Python | apache-2.0 | 8,225 | 0.001945 | #
# Copyright (c) SAS Institute 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 w... | Key])
if cu.fetchall():
continue
inserts.append(tuple(row[c] for c in tableCols))
if not inserts:
| return False
sql = "INSERT INTO %s (%s) VALUES (%s)" % (table,
','.join(tableCols), ','.join('?' for c in tableCols))
cu.executemany(sql, inserts)
return True
def _createInventorySchema(db):
cu = db.cursor()
changed = False
if 'inventory_managed_system' not in db.tables:
cu.exe... |
zenshade/vim_config | bundle/UltiSnips-2.1/plugin/UltiSnips/text_objects/_shell_code.py | Python | mit | 1,117 | 0.001791 | #!/usr/bin/env python
# encoding: utf-8
import os
import subprocess
import stat
import tempfile
from UltiSnips.compatibility import as_unicode
from UltiSnips.text_objects._base import NoneditableTextObject
class ShellCode(NoneditableTextObject):
def __init__(self, parent, token):
NoneditableTextObject.__... | (text=True)
os.write(handle, self._code.encode("utf-8"))
os.close(handle)
os.chmod(path, stat.S_IRWXU)
# Execute the file and read stdout
proc = subprocess.Popen(path, shell=True, stdout=subprocess.PIPE)
proc.wait()
output = as_unicode(proc.stdout.read())
... | put) and output[-1] == '\n':
output = output[:-1]
if len(output) and output[-1] == '\r':
output = output[:-1]
os.unlink(path)
self.overwrite(output)
self._parent._del_child(self)
return True
|
sidv1993/Graph-Traversal-and-Game-Playing | Graph-Traversal/GraphTraversal.py | Python | apache-2.0 | 13,929 | 0.031948 |
# Defining the goal state
goal_items = [1, 2, 3, 8, 0, 4, 7, 6, 5]
visited_vertices = []
# Defining imput states with increasing levels of difficulty
easy_initial_state = [1, 3, 4, 8, 6, 2, 7, 0, 5]
medium_initial_state = [2, 8, 1, 0, 4, 3, 7, 6, 5]
hard_initial_state = [5, 6, 7, 4, 0, 8, 3, 2, 1]
max = 0
import sys
... | "
output = idastar( easy_initial_state, goal_items )
elif(n == 17):
print_vertices(medium_initial_state)
print "\nGoal Puzzle State: "
output = idastar( medium_initial_state, goal_items )
elif(n == 18):
print_vertices(hard_initial_state)
print "\nGoal Puzzle State: "
| output = idastar( hard_initial_state, goal_items )
else:
print "Wrong Input!"
print "Direction of Moves:"
print output
print "Moves taken: ", len(output)
print "Nodes visited: ", len(visited_vertices) - 1
print "Max. length of Node List: ", max
print "Time taken: ", time.clock() - start... |
open-craft/xblock-poll | tests/integration/test_submit_button.py | Python | agpl-3.0 | 2,450 | 0.001224 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2015 McKinsey Academy
#
# Authors:
# Jonathan Piacenti <[email protected]>
#
# This software's license gives you freedom; you can copy, convey,
# propagate, redistribute and/or modify this program under the terms of
# the GNU Affero General Public License (AGPL) a... | the submit
button was disabled (because of js) and then re-enabled (because of
ajax request).
"""
self.go_to_page('Poll Submit Button')
# Find all the radio choices
answer_elements = self.browser.find_elements_by_css_selector('label.poll-answer-text')
# Select th... | first choice
answer_elements[1].click()
# When an answer is selected, make sure submit is enabled.
self.wait_until_exists('input[name=poll-submit]:enabled')
submit_button = self.get_submit()
submit_button.click()
# Make sure that submit button is disabled right away
... |
botswana-harvard/edc-map | edc_map/admin.py | Python | gpl-2.0 | 1,678 | 0 | from django.contrib import admin
from django_revision.modeladmin_mixin import ModelAdminRevisionMixin
from edc_base.modeladmin_mixins import (
ModelAdminNextUrlRedirectMixin, ModelAdminFormInstructionsMixin,
ModelAdminFormAutoNumberMixin,
ModelAdminReadOnlyMixin, ModelAdminAuditFieldsMixin)
from .admin_si... | ',
'modified',
'map_area',
'map_area',
'hostname_modified')
search_fields = ('map_area', 'id')
@admin.register(InnerContainer, site=edc_map_admin)
class InnerContainerAdmin(ModelAdminMixin):
form = InnerContainerForm
list_per_page = 10
list_display = ('map_area', 'de | vice_id', 'name', 'created', 'modified')
list_filter = (
'created',
'modified',
'map_area',
'container__name',
'name',
'hostname_modified')
search_fields = ('device_id', 'name', 'id')
|
wendlers/usherpa-pysherpa | test-src/packet.py | Python | lgpl-2.1 | 2,349 | 0.022563 | ##
# This file is part of the uSherpa Python Library project
#
# Copyright (C) 2012 Stefan Wendler <[email protected]>
#
# The uSherpa Python Library 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; eithe... | = Packet()
p3.fromFields(0x24, 0x04, 0x02, None)
print "p3: " + p3.__str__()
except PacketException as e:
print e
# again from byte array
try:
p4 = Packet()
p4.fromByteArray(array('B', [0x24, 0x07, 0x06, 0x22, 0x20, 0x4e, 0xc1]))
print "p4: " + p4.__str__()
except PacketException as e:
print e
# consume ... | 0xc1, 0xFF, 0x24, 0x06, 0x05, 0x13, 0x03, 0x45, ])
p5 = Packet()
for b in data:
p5.addByte(b)
if p5.isComplete() :
print "Found packet in stream: " + p5.__str__()
p5.clear()
except PacketException as e:
print e
# from single parameters, including WRONG CRC
try:
p6 = Packet()
p6.fromFields(0x24, 0... |
ownport/ansiblite | src/ansiblite/parsing/splitter.py | Python | gpl-3.0 | 10,657 | 0.001971 | # (c) 2014 James Cammarata, <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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 late... | uote_char = cur_char
return quote_char
def _count_jinja2_blocks(token, cur_depth, open_token, close_token):
'''
this fun | ction counts the number of opening/closing blocks for a
given opening/closing type and adjusts the current depth for that
block based on the difference
'''
num_open = token.count(open_token)
num_close = token.count(close_token)
if num_open != num_close:
cur_depth += (num_open - num_clos... |
ericholscher/django | django/contrib/contenttypes/views.py | Python | bsd-3-clause | 3,355 | 0.001192 | from __future__ import unicode_literals
from django import http
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site, get_current_site
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
def shortcut(request, conte... | (_("Content type %(ct_id)s object has no associated model") %
{'ct_id': content_type_id})
obj = content_type.get_object_for_this_type(pk=object_id)
except (ObjectDo | esNotExist, ValueError):
raise http.Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") %
{'ct_id': content_type_id, 'obj_id': object_id})
try:
get_absolute_url = obj.get_absolute_url
except AttributeError:
raise http.Http404(_("%(ct_name)s obj... |
didrocks/quickly | data/templates/ubuntu-application/project_root/tests/test_lint.py | Python | gpl-3.0 | 1,023 | 0.013685 | #!/usr/bin/python
# -*- Mode: Python; coding: utf-8; indent-ta | bs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# This file is in the public domain
### END LICENSE
import unittest
import subprocess
class TestPylint(unittest.TestCase):
def test_project_errors_only(self):
'''run pylint in error only mode
your code may well work even with pylint errors
... | s.call(["pylint", '-E', 'python_name'])
# not needed because nosetests displays pylint console output
#self.assertEqual(return_code, 0)
# un-comment the following for loads of diagnostics
#~ def test_project_full_report(self):
#~ '''Only for the brave
#~
#~ you will have to ... |
BD2KGenomics/slugflow | src/toil/test/src/workerTest.py | Python | apache-2.0 | 4,647 | 0.002152 | # Copyright (C) 2015-2021 Regents of the University of California
#
# 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... | f.config)
self.jobNumber = 0
@travis_test
def testNextChainable(self):
"""Make sure chainable/non-chainable jobs are identified correctly."" | "
def createTestJobDesc(memory, cores, disk, preemptable, checkpoint):
"""
Create a JobDescription with no command (representing a Job that
has already run) and return the JobDescription.
"""
name = 'job%d' % self.jobNumber
self.jobNumber +... |
kn45/RNNRegressor | rnn_regressor/mlfutil.py | Python | mit | 3,971 | 0.000252 | # -*- coding=utf-8 -*-
import cPickle
import numpy as np
import os
import sys
"""Common tools for this project.
Utils are defined in this module for sharing.
"""
PROJ_DIR = os.path.split(os.path.realpath(__file__))[0]
def draw_progress(iteration, total, pref='Progr | ess:', suff='',
decimals=1, barlen=50):
"""Call in a loop to create terminal progress bar
"""
formatStr = "{0:." + str(decimals) + "f}"
pcts = formatStr.format(100 * (iteration / float(total)))
filledlen = int(round(barlen * iteration / float(total)))
bar = '█' * filledlen + '-... | sys.stdout.write(out_str),
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
class CatEncoder(object):
"""Transform category to global uniq index
"""
def __init__(self):
self.cats = {}
def build_dict(self, ifnames, columns):
"""need override
ifna... |
edx/edx-platform | common/djangoapps/student/tests/test_userstanding.py | Python | agpl-3.0 | 4,098 | 0.002928 | """
These are tests for disabling and enabling student accounts, and for making sure
that students with disabled accounts are unable to access the courseware.
"""
import unittest
from django.conf import settings
from django.test import Client, TestCase
from django.urls import reverse
from common.djangoapps.student.... | )
assert response.status_code == 404
@unittest.sk | ipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
def test_non_staff_cant_disable_account(self):
response = self.non_staff_client.post(reverse('disable_account_ajax'), {
'username': self.good_user.username,
'user': self.non_staff,
'account_action': '... |
srikrishna3118/Lora_GW | PythonFiles/Config.py | Python | gpl-3.0 | 632 | 0.015823 | _author_ = 'Srikrishna'
import ConfigParser
import sys
import logging
logger = logging.getLogger(__name__)
sections = 'Connection','Configuration','Testing'
class MyConfiguration(object):
def __init__(self, *file_names):
parser = ConfigParser.ConfigParser()
parser.optionxform = str # make opti... | found = parser.read(file_names)
if not found:
raise ValueError('No config file found!')
for names in section | s:
self.__dict__.update(parser.items(names))
#config = MyConfiguration('lora.conf') # define the configurations in this file
|
hankcs/HanLP | plugins/hanlp_restful/hanlp_restful/__init__.py | Python | apache-2.0 | 14,166 | 0.004078 | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-11-29 17:48
import json
from typing import Union, List, Optional, Dict, Any, Tuple
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from hanlp_common.document import Document
try:
# noinspection Py... | ``code`` and ``msg``
of the exception for more details. A list of common errors :
- ``400 Bad Request`` indicates that the server cannot process the request due to a client
fault (e.g., text too long, language unsupported).
- ``401 Unauthorized`` indicates that the request lac... | ndicates that the content type of the request entity is not in
proper json format.
- ``429 Too Many Requests`` indicates the user has sent too many requests in a given
amount of time ("rate limiting").
"""
assert text or tokens, 'At least one of text or tokens has to be spec... |
vecnet/om | website/apps/ts_om/tests/utils/test_scenario_name_with_next_number.py | Python | mpl-2.0 | 1,719 | 0.004654 | # -*- coding: utf-8 -*-
#
# This file is part of the VecNet Open | Malaria Portal.
# For copyright and licensing information about this package, see the
# NOTICE.txt and LICENSE.txt files in its top-level directory; they are
# available at ht | tps://github.com/vecnet/om
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
from django.test.testcases import TestCase
from website.apps.ts_om.utils impor... |
kilikkuo/py_simple_host_target | simple_host_target/simple_host_target/server.py | Python | mit | 6,080 | 0.006743 | import os
import sys
import time
import select
import socket
import traceback
import threading
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
from simple_host_targ... | received completely
if self.__extract_specific_task(c, a):
self.clients.pop(c)
| read_list.remove(c)
c.close()
print(" REMOVED & CLOSE a socket client !!!!!!! ")
time.sleep(0.01)
except:
traceback.print_exc()
print("[Exception] during server's loop for connections... |
JoshStegmaier/django-nimbus | nimbus/filehandling/fileupload.py | Python | mit | 295 | 0.00678 | import os.path
def handle_uploaded_file(f, path, new_name=Non | e):
if new_name:
file_name = new_name
else:
file_name = f.name
destination = open(os.path.join(path, file_name), 'wb+')
for chunk in f.chunks():
d | estination.write(chunk)
destination.close() |
mozilla/kitsune | kitsune/users/backends.py | Python | bsd-3-clause | 294 | 0 | from django.contrib.auth.backends import ModelBackend
# | Live sessions will still be using | this backend for a while.
# TODO: Remove after there are no more sessions using this in prod.
class Sha256Backend(ModelBackend):
"""Overriding the Django model backend without changes."""
pass
|
Aarononomous/SwitchCSSColorModel | switch_css_color_model.py | Python | mit | 11,674 | 0.00257 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sublime
import sublime_plugin
import re
SETTINGS_FILE = 'SwitchCSSColorModel.sublime-settings'
class F:
"""Formats rgba values into output string"""
# default for hex values is lowercase --
# change in SwitchColorModel.sublime-settings
lower = Fa... | , a):
return ('rgba(' + F.to_pct(r/255*100) + '%,' +
F.to_pct(g/255*100) + '%,' + F.to_pct(b/2 | 55*100) + '%,' +
F.to_pct(a) + ')')
def hsl(r, g, b, a):
h, s, l = F.rgb_to_hsl(r, g, b)
return ('hsl(' + F.to_pct(h) + ',' + F.to_pct(s) + '%,' +
F.to_pct(l) + '%)')
def hsla(r, g, b, a):
h, s, l = F.rgb_to_hsl(r, g, b)
return ('hsla(' + F.to_pc... |
zerobuzz/js.socialshareprivacy | js/socialshareprivacy/__init__.py | Python | bsd-3-clause | 398 | 0 | from fanstatic import Library, Resource
import js.jquery
library = Library('jquery.socialshareprivacy', 'resourc | es')
css = Resource(library, 'socialshareprivacy/socialshareprivacy.css')
socialshareprivacy = Resource(library, 'jquery.socialshareprivacy.js',
| minified='jquery.socialshareprivacy.min.js',
depends=[js.jquery.jquery, css])
|
rwl/PyCIM | CIM15/IEC61970/Wires/Fuse.py | Python | mit | 1,856 | 0.001616 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | CT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CON | NECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
from CIM15.IEC61970.Wires.Switch import Switch
class Fuse(Switch):
"""An overcurrent protective device with a circuit opening fusible part that is heated and severed by the passage of overcurrent through it. A fuse is considered a switching... |
adel-qod/zipper | zipper.py | Python | bsd-2-clause | 6,014 | 0.012305 | #!/usr/bin/python2.7 -tt
"""
Copyright (c) 2013, Adel Qodmani
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of con... | compression
import os # For everything related to path
import logging
import sys # For the argv an | d exit
import datetime
def main():
""" zipper source-dir-full-path dest-dir-full-path
Tars and zips the source-dir and put it in the dest-dir with the name:
source-dir-name_date_time.tar.gz
"""
check_args()
source_path = sys.argv[1]
source_path = source_path.rstrip('/')
logging.debug("source_pa... |
rspavel/spack | var/spack/repos/builtin/packages/argp-standalone/package.py | Python | lgpl-2.1 | 1,235 | 0.002429 | # 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 ArgpStandalone(AutotoolsPackage):
"""Standalone version of the argp interface from glibc ... | homepage = "https://www.lysator.liu.se/~nisse/misc"
url = "https://www.lysator.liu.se/~nisse/misc/argp-standalone-1.3.tar.gz"
version('1.3', sha256='dec79694da1319acd2238ce95df57f3680fea2482096e483323fddf3d818d8be')
# Homebrew (https://github.com/Homebrew/homebrew-core) patches
# argp-standalo... | fmtstream.h
patch('argp-fmtstream.h.patch', 0, 'platform=darwin', '.')
def install(self, spec, prefix):
make('install')
make('check')
mkdirp(self.spec.prefix.lib)
install('libargp.a', join_path(self.spec.prefix.lib, 'libargp.a'))
mkdirp(self.spec.prefix.include)
... |
111pontes/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ncs5500_coherent_portmode_oper.py | Python | apache-2.0 | 6,344 | 0.022541 | """ Cisco_IOS_XR_ncs5500_coherent_portmode_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR ncs5500\-coherent\-portmode package operational data.
This module contains definitions
for the following management objects\:
controller\-port\-mode\: Coherent PortMode operational data
Copyrig... | (self):
''' Returns True if this instance represents config data else returns False '''
return False
def _has_data(self):
if not self.is_config():
return False
if self.optics_name is not None:
for child_ref in self.optics_name:
if child_ref._h... | return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ncs5500_coherent_portmode_oper as meta
return meta._meta_table['ControllerPortMode']['meta_info']
|
selfbus/software-arm-incubation | sensors/misc/raincenter-bim112/Phyton Raincenter Tests/test.py | Python | gpl-3.0 | 309 | 0.029126 | import sched, time
s = sched.scheduler(t | ime.time, time.sleep)
def pr | int_time():
print ("From print_time", time.time())
def print_some_times():
print (time.time())
s.enter(5, 1, print_time, ())
s.enter(10, 1, print_time, ())
s.run()
print (time.time())
print_some_times() |
netheosgithub/pcs_api | python/pcs_api/cexceptions.py | Python | apache-2.0 | 3,661 | 0.002185 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Netheos (http://www.netheos.net)
#
# 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 req... | pected_blob, message=None):
""":param c_path: the problematic path
:param expected_blob: if True, a blob was expected but a folder was found.
if False, a folder was expected but a blob was found
:param message: optional message"""
if not message:
... | (c_path, 'blob' if expected_blob else 'folder')
super(CInvalidFileTypeError, self).__init__(message)
self.path = c_path
self.expected_blob = expected_blob
class CRetriableError(CStorageError):
"""Raised by RequestInvoker validation method, when request
has failed but should be... |
stb-tester/stb-tester | stbt_run.py | Python | lgpl-2.1 | 2,110 | 0 | #!/usr/bin/python3
"""
Copyright 2012-2013 YouView TV Ltd.
2014-2017 stb-tester.com Ltd.
License: LGPL v2.1 or (at your option) any later version (see
https://github.com/stb-tester/stb-tester/blob/master/LICENSE for details).
"""
import argparse
import sys
import _stbt.core
from _stbt import imgproc_cache
... | s.argv)')
args = parser.parse_args(argv[1:])
deb | ug("Arguments:\n" + "\n".join([
"%s: %s" % (k, v) for k, v in args.__dict__.items()]))
dut = _stbt.core.new_device_under_test_from_config(args)
with sane_unicode_and_exception_handling(args.script), \
video(args, dut), \
imgproc_cache.setup_cache(filename=args.cache):
te... |
dasseclab/dasseclab | clones/routersploit/tests/creds/cameras/acti/test_telnet_default_creds.py | Python | gpl-2.0 | 672 | 0.002976 | from routersploit.modules.creds.cameras.acti.telnet_default_creds import Exploit
def test_check_success(generic_target):
""" Test scena | rio - testing against Telnet server """
exploit = Exploit()
assert exploit.target == ""
assert exploit.port == 23
assert exploit.threads == 1
assert exploit.defaults == ["admin:12345", "admin:123456", "Admin:12345", "Admin:123456"]
assert exploit.stop_on_success | is True
assert exploit.verbosity is True
exploit.target = generic_target.host
exploit.port = generic_target.port
assert exploit.check() is True
assert exploit.check_default() is not None
assert exploit.run() is None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.