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 |
|---|---|---|---|---|---|---|---|---|
skosukhin/spack | lib/spack/spack/cmd/clone.py | Python | lgpl-2.1 | 3,972 | 0 | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
| # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser Genera... | February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have receiv... |
JoakimLindbom/agocontrol | devices/squeezeboxserver/slimtest.py | Python | gpl-3.0 | 443 | 0.002257 | import squeezeboxserver
import time
squeezebox = squeezeboxserver.SqueezeboxServer("192.168.1.65:9000")
players = squeezebox.players()
for p in players:
print ("MAC: | %s" % p['playerid'])
time.sleep(10)
squ | eezebox.power("00:04:20:06:8c:55", "on")
squeezebox.playlist("00:04:20:06:8c:55", "play")
time.sleep(10)
squeezebox.playlist("00:04:20:06:8c:55", "stop")
time.sleep(3)
squeezebox.power("00:04:20:06:8c:55", "off")
|
houzhenggang/hiwifi-openwrt-HC5661-HC5761 | staging_dir/host/lib64/scons-2.1.0/SCons/Tool/MSCommon/__init__.py | Python | gpl-2.0 | 2,107 | 0.000949 | #
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 The SCons Foundation
#
# 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
# with... | CULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = ... | 011/09/09 21:31:03 bdeegan"
__doc__ = """
Common functions for Microsoft Visual Studio and Visual C/C++.
"""
import copy
import os
import re
import subprocess
import SCons.Errors
import SCons.Platform.win32
import SCons.Util
from SCons.Tool.MSCommon.sdk import mssdk_exists, \
mss... |
kakaba2009/MachineLearning | python/src/algorithm/coding/regex/email.py | Python | apache-2.0 | 614 | 0.004886 | import re
def fun(s):
# return True if s is a valid email, else return False
f = "^[a-zA-Z][\w-]*@[a-zA-Z0-9]+\.[a- | zA-Z]{1,3}$"
if not re.match(f, s):
return False
usernam | e, after = re.split(r'[@]', s)
websitename, extension = re.split(r'[.]', after)
if(len(extension) > 3):
return False
return True
def filter_mail(emails):
return list(filter(fun, emails))
if __name__ == '__main__':
n = int(input())
emails = []
for _ in range(n):
emails.appe... |
feinheit/feincms-elephantagenda | elephantagenda/views.py | Python | mit | 403 | 0 |
from models import Event
from django.views.gen | eric import DetailView, ListView
class EventListView(ListView):
template_name = 'agenda/event_list.html'
queryset = Event.objects.upcoming()
paginate_by = 20
class EventArchiveview(EventListView):
queryset = Event.objects.past()
class EventDetailView(DetailView):
model = Event |
template_name = 'agenda/event_detail.html'
|
keras-team/keras | keras/layers/merging/maximum.py | Python | apache-2.0 | 2,842 | 0.001759 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | = inputs[0]
for i in range(1, len(inputs)):
output = tf.maximum(output, inputs[i])
return output
@keras_export('keras.layers.maximum')
def maximum(inputs, **kwargs):
"""Functional interface to compute maximum (element-wise) list of `inputs`.
This is equivalent to the `tf.keras.layers.Maximum` laye... | t(shape=(16,))
x1 = tf.keras.layers.Dense(8, activation='relu')(input1) #shape=(None, 8)
input2 = tf.keras.layers.Input(shape=(32,))
x2 = tf.keras.layers.Dense(8, activation='relu')(input2) #shape=(None, 8)
max_inp=tf.keras.layers.maximum([x1,x2]) #shape=(None, 8)
out = tf.keras.layers.Dense(4)(max_inp)
mod... |
lthurlow/Network-Grapher | proj/external/matplotlib-1.2.1/lib/mpl_examples/user_interfaces/embedding_in_gtk3.py | Python | mit | 834 | 0.014388 | #!/usr/bin/env python
"""
demonstrate adding a FigureCanvasGTK3Agg widget to a Gtk.ScrolledWindow
using GTK3 accessed via pygobject
"""
from gi.repository import Gtk
from matplotlib.figure import Figure
from numpy import arange, sin, pi
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanv... | request(800, | 600)
sw.add_with_viewport (canvas)
win.show_all()
Gtk.main()
|
fxb22/BioGUI | plugins/Tools/ETOOLSPlugins/ESummary.py | Python | gpl-2.0 | 3,669 | 0.016898 | import os
import sys
from Bio import Entrez
import wx
from xml.dom import minidom
import re
class etPlugin():
def GetName(self):
'''
Method to return name of tool
'''
return "ESummary"
def GetBMP(self, dirH):
'''
Method to return identifying image
''... | if not re.search('.*<Item Name= | "?',line) == None:
if not re.search('.*<.*>.*<.*>',line) == None:
e = re.sub('.*<Item Name="?','',line)
alpha = re.sub('" Type=".*">?','\n',e)
beta = re.sub('<.*','\n',alpha)
parent.text2.write(str(beta))
... |
giannotr/misc-python | twelvetone.py | Python | gpl-2.0 | 1,207 | 0.014085 | #!/usr/bin/env
import subprocess, os, random, copy
output_filename = "twelvetone_ex.ly"
output_file = open(output_filename, "w")
notes = ['c','cis','d','dis','e','f','fis','g','gis','a','ais','b']
temp_tt_array = []
def twelvetone_gen():
notes_svd = cop | y.copy(notes)
a = 11
while len(temp_tt_array) < 12:
r = random.randint(0,a)
temp_tt_array.append(notes_svd[r])
notes_svd.remove(notes_svd[r])
a = a-1
return temp_tt_array
output_file.write(r'''\version "2.16.0"\header{tagline=""}\paper{indent=0 line-width=130 top-margin=13}\... | "Time_signature_engraver" \override Stem #'transparent = ##t}}\score{\transpose c c' << \new Staff''')
temp_tt_string = ''
for x in range(0, 16):
output_file.write('\n' + r'{ \time 12/4 ')
twelvetone_gen()
for element in temp_tt_array:
temp_tt_string+=element + ' '
output_file.write(temp_tt_st... |
etingof/pyasn1-modules | tests/test_rfc4043.py | Python | bsd-2-clause | 4,870 | 0.000411 | #
# This file is part of pyasn1-modules software.
#
# Created by Russ Housley
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import encode as der_encoder
f... | self.assertTrue(permanent_identifier_found)
suit | e = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
if __name__ == '__main__':
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(not result.wasSuccessful())
|
jmbeuken/abinit | scripts/post_processing/ElectronPhononCoupling/ElectronPhononCoupling/data/LiF_g2_2/__init__.py | Python | gpl-3.0 | 668 | 0 | """
Filenames of the tests
"""
import os
from os.path import join as pjoin
from .. impor | t LiF_g4
# This is a 2x2x2 q-point grid. The weights can be | obtained from abinit.
nqpt = 3
wtq = [0.125, 0.5, 0.375]
# Indices of the q-points in the 4x4x4 grid.
iqpt_subset = [0, 2, 6]
dirname = os.path.dirname(__file__)
fnames = dict(
eigk_fname=LiF_g4.fnames['eigk_fname'],
eigq_fnames=list(),
ddb_fnames=list(),
eigr2d_fnames=list(),
gkk_fnames=list()... |
kk9599/vy | vyapp/notevi.py | Python | mit | 2,502 | 0.003597 | """
"""
from Tkinter import *
from areavi import AreaVi
from ttk import Notebook
class PanedHorizontalWindow(PanedWindow):
| """
"""
def __init__(self, *args, **kwargs):
"""
"""
PanedWindow.__init__(self, orient=HORIZONTAL, *args, **kwargs)
def create_area(self):
"""
"""
frame = Frame(master=self)
scrollbar = Scrollbar(master=frame)
area = AreaVi(... | yscrollcommand=scrollbar.set)
scrollbar.config(command=area.yview)
scrollbar.pack(side='right', fill=Y)
from vyapp.plugins import INSTALL, HANDLE
for plugin, args, kwargs in INSTALL:
plugin.install(area, *args, **kwargs)
for handle, args, k... |
plantigrade/geni-tools | src/gcf/omnilib/frameworks/framework_base.py | Python | mit | 14,946 | 0.004416 | #----------------------------------------------------------------------
# Copyright (c) 2011-2015 Raytheon BBN Technologies
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, including ... | ile
cred = None
if opts.usercredfile and os.path.exists(opts.usercredfile) and os.path.isfile(opts.userc | redfile) and os.path.getsize(opts.usercredfile) > 0:
# read the user cred from the given file
if hasattr(self, 'logger'):
logger = self.logger
else:
logger = logging.getLogger("omni.framework")
logger.info("Getting user credential from file... |
bio-tools/biotoolsregistry | backend/elixirapp/wsgi.py | Python | gpl-3.0 | 487 | 0.004107 | """
WSGI config for elixirapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os, sys
from django.core.wsgi import get_wsgi_application
os.envir | on.setdefault("DJANGO_SETTINGS_MODULE", "elixirapp.settings")
os.environ["CELERY_LOADER"] = "django"
sys.path.insert(0,'/elixir/application/backend')
application = get_wsgi_applica | tion()
|
fengsp/flask-snippets | database/use_tornado_database.py | Python | bsd-3-clause | 1,247 | 0.004812 | # -*- coding: utf-8 -*-
"""
database.use_tornado_database
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Using tornado.database with MySQL
http://flask.pocoo.org/snippets/11/
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from tornado.database import Connectio... | t_db():
g.db = Connection(config.DB_HOST,
config.DB_NAME,
config.DB_USER,
config.DB_PASSWD)
@app.after_request
def close_connection(response):
g.db.close()
return response
@app.route("/")
def index():
newsitems = g.db.iter("select * f... | m.title }}</h3>
{% endfor %}
You can get much of the same functionality in SQLAlchemy 0.6 using NamedTuples, without using the ORM:
from sqlalchemy import create_engine
@app.before_request
def connect_db():
g.db = create_engine(config.DB_URI)
@app.route("/")
def index():
newsitems = g.db.execute("select * fr... |
pranjan77/narrative | src/biokbase/narrative/clients.py | Python | mit | 1,813 | 0.002758 | from biokbase.workspace.client import Workspace
from biokbase.narrative_method_store.client import NarrativeMethodStore
from biokbase.userandjobstate.client import UserAndJobState
from biokbase.catalog.Client import Catalog
from biokbase.service.Client import Client as ServiceClient
from biokbase.execution_engine2.exec... | job_mock.che | ck_jobs', [params])[0]
|
glibin/tortik | tortik_tests/util_test.py | Python | mit | 7,001 | 0.00432 | # _*_ coding: utf-8 _*_
import os
try:
from cStringIO import StringIO # python 2
except ImportError:
from io import StringIO # python 3
from collections import OrderedDict
import unittest
from tornado.escape import to_unicode
from tortik.util import make_qs, update_url, real_ip
from tortik.util.xml_etree im... | ))}
self.assertQueriesEqual(make_qs(query_args), 'a=1&a=2&b=1&b=2&c=1&c=2&d=1&d=2')
def test_make_qs_none(self):
query_args = {'a': None, 'b': None}
self.assertQueriesEqual(make_qs(query_args), '')
def test_make_qs_encode(self):
query_args = {'a': u'тест', 'b': 'тест'}
... | %D0%B5%D1%81%D1%82')
def test_from_ordered_dict(self):
qs = make_qs(OrderedDict([('z', 'я'), ('г', 'd'), ('b', ['2', '1'])]))
self.assertIsInstance(qs, str)
self.assertEqual(qs, 'z=%D1%8F&%D0%B3=d&b=2&b=1')
def test_unicode_params(self):
self.assertQueriesEqual(
mak... |
vlegoff/tsunami | src/primaires/pnj/commandes/chemin/voir.py | Python | bsd-3-clause | 3,490 | 0.000287 | # -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... | == 0:
msg += "\n Aucune"
else:
for salle, direction in chemin.salles.items():
msg += "\n " + salle.ident.ljust(20 | ) + " "
msg += direction.ljust(10)
if salle in chemin.salles_retour and \
chemin.salles_retour[salle]:
msg += " (retour " + chemin.salles_retour[salle] + ")"
personnage << msg
|
synsun/robotframework | src/robot/utils/normalizing.py | Python | apache-2.0 | 3,790 | 0.000264 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 l... | _REGEXP.sub('', string)
if caseless:
string = lower(string)
ignore = [lower(i) for i in ignore]
for ign in ignore:
if ign in string: # performance optimization
string = string.replace(ign, '')
return string
# http://ironpython.codeplex.com/workitem/33133
if sys.platfor... | def lower(string):
return string.lower()
class NormalizedDict(MutableMapping):
"""Custom dictionary implementation automatically normalizing keys."""
def __init__(self, initial=None, ignore=(), caseless=True, spaceless=True):
"""Initializes with possible initial value and normalizing spec.... |
schettino72/serveronduty | websod/database.py | Python | mit | 1,071 | 0.002801 | import os
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
metadata = MetaData()
def get_sa_db_uri(driver='', username='', password='', host='', port='', database=''):
"""get SQLAlchemy DB URI: driver://username:password@host:port/database"""
assert driv... | gine(db_uri, convert_unicode=True)
self.session = scoped_session(
sessionmaker(autocommit=False,
autoflush=False,
bind=self.engine))
def init_database(self):
metadata.create_all(bi | nd=self.engine)
|
hehongliang/tensorflow | tensorflow/python/training/optimizer_test.py | Python | apache-2.0 | 12,617 | 0.00959 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | 'No gradients provided for any variable'):
sgd_op.minimize(loss, var_list=[var0, var1])
@test_util.run_in_graph_and_eager_modes
def testNoGradientsForAnyVariables_ApplyGradients(self):
for i, dtype in enumerate([dtypes.half, dtypes.float32, dtypes.float64]):
# Note th... | les don't
# seem to be getting deleted at the end of the loop.
var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype,
name='a_%d' % i)
v |
shinpeimuraoka/ryu | ryu/lib/netdevice.py | Python | apache-2.0 | 4,034 | 0.002231 | # Copyright (C) 2017 Nippon Telegraph and Telephone Corporation.
#
# 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 appli... | # IPvlan slave device.
IFF_L3MDEV_MASTER = 1 << 20 # device is an L3 master device.
IFF_NO_QUEUE = 1 << 21 # device can run without qdisc attached.
IFF_OPENVSWITCH = 1 << 22 # device is a Open vSwitch master.
IFF_L3MDEV_SLAVE | = 1 << 23 # device is enslaved to an L3 master device.
IFF_TEAM = 1 << 24 # device is a team device.
IFF_RXFH_CONFIGURED = 1 << 25 # device has had Rx Flow indirection table configured.
IFF_PHONY_HEADROOM = 1 << 26 # the headroom value is controlled by an external entity. (i.e... |
robinson96/GRAPE | keyring/demo/keyring_demo.py | Python | bsd-3-clause | 2,347 | 0.005113 | """
keyring_demo.py
|
This demo shows how to create a new keyring and enable it in keyring lib.
Created by Kang Zhang on 2009-07-12
"""
import os
KEYRINGRC = "keyringrc.cfg"
def load_keyring_by_config():
"""This function shows how to enable a keyring using config file
"""
# create the config file
config_file = open(KEY... | eyring-path= %s\n" % str(os.path.abspath(__file__))[:-16],
# the name of the keyring class
"default-keyring=simplekeyring.SimpleKeyring\n" ])
config_file.close()
# import the keyring lib, the lib will automaticlly load the
# config file and load the user defined module
... |
pymber/algorithms | tests/run-test-sort-selection.py | Python | mit | 154 | 0.006494 | #!/usr/bin/env python
from algorithms.sorting.selec | tion_sort import | *
from __prototype__ import *
if __name__ == '__main__':
test_all(selection_sort) |
chrox/RealTimeElectrophy | Experimenter/DataProcessing/Fitting/Fitters.py | Python | bsd-2-clause | 7,874 | 0.04318 | # Data fitting wrappers with optimized parameters.
#
# Copyright (C) 2010-2011 Huang Xin
#
# See LICENSE.TXT that came with this file.
from __future__ import division
import math
import numpy as np
import scipy.ndimage as nd
from sinusoidfitter import onedsinusoidfit,onedsinusoid
from gaussfitter import gaussfit,oned... | sort(data)[:3].mean()
params=[0,(data.max()-data.min())*0.5,0,width*0.2]
fixed=[False,False,False,False]
limitedmin=[False,Tr | ue,True,True]
limitedmax=[True,True,True,True]
minpars=[0,(data.max()-data.min())*0.5,xax.min()-width,width*0.05]
maxpars=[lower_bound*1.5,data.max()-data.min(),xax.max(),width*3.0]
params,_model,errs,chi2 = onedloggaussfit(xax,data,params=params,fixed=fixed,\
... |
frreiss/tensorflow-fred | tensorflow/python/distribute/collective_util.py | Python | apache-2.0 | 8,799 | 0.002842 | # coding=utf-8
# Copyright 2020 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 requ... | .
Examples:
```python
options = tf.distribute.experimental.CommunicationOptions(
bytes_per_pack=50 * 1024 * 1024,
timeout_seconds=120,
implementation=tf.distribute.experimental.CommunicationImplementation.NCCL
)
grads = tf.distribute.get_replica_context().all_reduce(
'sum', grads, op... | , *args, **kwargs):
# We expose a dummy class so that we can separate internal and public APIs.
# Note that __init__ won't be called on the returned object if it's a
# different class [1].
# [1] https://docs.python.org/3/reference/datamodel.html#object.__new__
return Options(*args, **kwargs)
def ... |
rustychris/stompy | test/test_exact_delaunay2.py | Python | mit | 2,185 | 0.040732 | from __future__ import print_function
import numpy as np
from stompy.grid import exact_delaunay, unstructured_grid
Triangulation=exact_delaunay.Triangulation
from stompy.spatial import robust_predicates
def test_gen_intersected_elements():
dt = Triangulation()
pnts = [ [0,0],
[5,0],
... | ntersected_elements(pA=[0,-1],pB=[0,1]))
assert len(elts)==1
assert elts[0][0]=='node'
elts=list(dt.gen_intersected_elements(pA=[0,-1],pB=[1,1]))
assert len(elts)==1
assert elts[0][0]=='edge'
def test_gen_int_elts_dim0( | ):
dt = Triangulation()
assert len(list(dt.gen_intersected_elements(pA=[-1,0],pB=[1,0])))==0
dt.add_node(x=[0,0])
assert len(list(dt.gen_intersected_elements(pA=[-1,0],pB=[1,0])))==1
assert len(list(dt.gen_intersected_elements(pA=[-1,0],pB=[1,1])))==0
|
shawnadelic/shuup | shuup/simple_supplier/admin_module/views.py | Python | agpl-3.0 | 6,626 | 0.002717 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.http import JsonRespons... | elta,
"unit_short_name": stock_adjustment.product.sales_unit.short | _name,
"product_name": stock_adjustment.product.name,
"supplier_name": stock_adjustment.supplier.name
}
if stock_adjustment.delta > 0:
return _(
"Added %(delta)s %(unit_short_name)s for product %(product_name)s stock (%(supplier_name)s)"
) % arguments
else:
... |
fcvarela/beerprogress | beerprogress/__init__.py | Python | bsd-3-clause | 3,534 | 0.001698 | import os
import psutil
import sys
__all__ = [
'BeerProgress'
]
_default_display = {
'cpu': True,
'mem': True,
'progressbar': True,
'percent': True,
'tasks_ratio': True,
'skipped_tasks': True,
'fd_count': True,
'context_switches': True
}
class BeerProgress(object):
def __in... | y = display
self.proc = psutil.Process(os.getpid())
self.metrics = {
'cpu': 0,
'mem': 0,
'percent': 0,
'fds': 0,
'ctxv': 0,
'ctxi': 0
}
@property
def completed_tasks(self):
return self._completed_tasks
... | property
def total_tasks(self):
return self._total_tasks
@total_tasks.setter
def total_tasks(self, total_tasks):
self._total_tasks = total_tasks
@property
def skipped_tasks(self):
return self._skipped_tasks
@skipped_tasks.setter
def skipped_tasks(self, skipped_task... |
SulavKhadka/Sorting-Algorithms | sort_algos.py | Python | mit | 4,236 | 0.004013 | import random
import sys
sys.setrecursionlimit(7000)
def selection_sort(array, counter):
for i in range(0,len(array)):
min_val = array[i:len(array)+1][0]
for j in array[i:l | en(array)+1]:
counter += 1
if j < min_val:
min_val = j
k = array[i:len(array)+1].index(min_val)+i
counter += 2
array[k], array[i] = array[i], array[k]
return [array, counter]
def insertion_sort(array, counter):
for i in range(1, len(array)):
... | y[i]
counter += 1
while k >= 0 and x < array[k]:
counter += 1
array[k+1] = array[k]
k -= 1
array[k+1] = x
return [array, counter]
def quick_sort_random(array, counter):
n = len(array)
if n <= 50:
return insertion_sort(array, counter)
... |
awsdocs/aws-doc-sdk-examples | python/example_code/apigateway/aws_service/test/conftest.py | Python | apache-2.0 | 311 | 0.003215 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Contains common test fixture | s used to run unit tests.
"""
import sys
# This is needed so Python can find test_tools | on the path.
sys.path.append('../../..')
from test_tools.fixtures.common import *
|
chromium/chromium | ppapi/generators/idl_diff.py | Python | bsd-3-clause | 9,131 | 0.02048 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import glob
import os
import subprocess
import sys
from idl_option import GetOption, Option... | C style
#
def IsToCppComment(change):
if not len(change.now) or len(change.now) != len(change.was):
return False
for index in range(len(change.now)):
was = change.was[index].strip()
if was[:2] != '//':
return False
was = was[2:].strip()
no | w = change.now[index].strip()
if now[:2] != '/*':
return False
now = now[2:-2].strip()
if now != was:
return False
return True
return True
def IsMergeComment(change):
if len(change.was) != 1: return False
if change.was[0].strip() != '*': return False
for line in change.now:
stri... |
subhrm/google-code-jam-solutions | solutions/2017/1B/B/B_small.py | Python | mit | 1,604 | 0.01808 | # Problem B
# Small dataset
# O = G = V = 0. (Each unicorn has only one hair color in its mane.)
def solve(N, R, Y, B):
res = ""
imp = "IMPOSSIBLE "
if sum((R,Y,B)) == 0:
return ""
if max(R,Y,B) > N//2 :
return imp
if (R==Y) and (Y==B):
return "RYB"*R
elif (R==Y) and... | da x:x[1], reverse=True)
sum_arr = lambda x : x[0][1] + x[1][1] + x[2][1]
while(sum_arr(arr) > 0 ):
if (arr[0][1] == arr[1][1]) and (arr[1][1] == arr[2][1]):
m = arr[0][1]
s = set(["B","R","Y"])
s.remove(res[-1])
first = min(s)
s.add(res[-1])... | "R","Y"])
s.remove(first)
s.remove(last)
mid = list(s)[0]
r0 = first+mid+last
r = r0*m
res += r
break
if arr[0][1] > 0:
res += arr[0][0]
arr[0][1] -= 1
if arr[1][1] > 0 :
res += arr[1... |
sociateru/django-iprestrict | iprestrict/migrations/__init__.py | Python | bsd-3-clause | 117 | 0.008547 | # -*- coding: utf-8 -*-
from __future__ import (
absolute_import, division, print_function, unicode_literals
| )
| |
xstreck1/TREMPPI | python/tremppi/server_errors.py | Python | gpl-3.0 | 1,278 | 0.000782 | class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
... | not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
| rv['message'] = self.message
return rv
|
CameronLonsdale/lantern | tests/analysis/test_frequency.py | Python | mit | 2,466 | 0.001622 | """Tests for the frequency module in analysis"""
import pytest
from lantern.analysis import frequency
def test_frequency_analyze():
"""Testing frequency analyze works for ngram = 1"""
assert frequency.frequency_analyze("abb") == {'a': 1, 'b': 2}
def test_frequency_analyze_bigram():
"""Testing frequenc... | ': 3}, {'a': 1, 'b': 2}) == 0.1
def test_chi_squared_different_symbols():
"""Testing different symbols are handled appropriately"""
assert frequency.chi_squared({'a': 1, 'd': 3}, {'a': 1}) == 0
def test_languagefrequency_attribute_access():
"""Testing | correct attributes are found, incorrect attributes raise AttributeErrors"""
frequency.english.unigrams
with pytest.raises(AttributeError):
frequency.english.invalid
|
hypergravity/hrs | twodspec/normalization.py | Python | bsd-3-clause | 8,493 | 0.000118 | # -*- coding: utf-8 -*-
"""
Author
------
Bo Zhang
Email
-----
bozhang@nao.cas.cn
Created on
----------
- Sat Sep 03 12:00:00 2016
Modifications
-------------
- Sat Sep 03 12:00:00 2016
Aims
----
- normalization
Notes
-----
This is migrated from **SLAM** package
"""
from __future__ import division
import numpy... | wave_flux_tuple_list: list[n_obs]
a list of (wa | ve, flux) tuple
norm_range: tuple
a tuple consisting (wave_start, wave_stop)
dwave: float
binning width
p: tuple of 2 ps
smoothing parameter between 0 and 1:
0 -> LS-straight line
1 -> cubic spline interpolant
q: float in range of [0, 100]
percentile, betw... |
nturaga/tools-iuc | data_managers/data_manager_bowtie_index_builder/data_manager/bowtie_index_builder.py | Python | mit | 4,124 | 0.023763 | #!/usr/bin/env python
import json
import optparse
import os
import subprocess
import sys
import tempfile
CHUNK_SIZE = 2**20
DEFAULT_DATA_TABLE_NAME = "bowtie_indexes"
def get_id_name( params, dbkey, fasta_description=None):
# TODO: ensure sequence_id is unique and does not already appear in location file
se... | data_manager_dict['data_tables'][ data_table_name ].append( data_table_entry )
return data_manager_dict
def main():
# Parse Command Line
parser = optparse.OptionParser()
parser.add_option | ( '-f', '--fasta_filename', dest='fasta_filename', action='store', type="string", default=None, help='fasta_filename' )
parser.add_option( '-d', '--fasta_dbkey', dest='fasta_dbkey', action='store', type="string", default=None, help='fasta_dbkey' )
parser.add_option( '-t', '--fasta_description', dest='fasta_desc... |
minhphung171093/GreenERP_V9 | openerp/addons/mail/tests/test_mail_followers.py | Python | gpl-3.0 | 7,126 | 0.004491 | # -*- coding: utf-8 -*-
from psycopg2 import IntegrityError
from openerp.addons.mail.tests.common import TestMail
class TestMailFollowers(TestMail):
def setUp(self):
super(TestMailFollowers, self).setUp()
Subtype = self.env['mail.message.subtype']
self.mt_mg_def = Subtype.create({'name':... | set([self.mt_mg_nodef.id, self.mt_al_nodef.id]))
def test_m2o_command_update_selec | tive(self):
test_channel = self.env['mail.channel'].create({'name': 'Test'})
groups = self.group_pigs | self.group_public
self.env['mail.followers'].create({'partner_id': self.user_employee.partner_id.id, 'res_model': 'mail.channel', 'res_id': self.group_pigs.id})
generic, specific = sel... |
google/clusterfuzz | src/clusterfuzz/_internal/bot/minimizer/html_minimizer.py | Python | apache-2.0 | 7,964 | 0.005399 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | current_token_start = index
current_token_type = HTMLMinimizer.Token.TYPE_HTML
state = HTMLMinimizer.TokenizerState.SEARCHING_FOR | _SCRIPT
token = HTMLMinimizer.Token(data[current_token_start:], current_token_type)
tokens.append(token)
return tokens
@staticmethod
def combine_worker_tokens(tokens, prefix=b'', suffix=b''):
"""Combine tokens for a worker minimizer."""
# The Antlr tokenizer decodes the bytes objects we origin... |
setten/pymatgen | pymatgen/analysis/chemenv/coordination_environments/tests/test_coordination_geometries.py | Python | mit | 14,930 | 0.004488 | #!/usr/bin/env python
__author__ = 'waroquiers'
import unittest
from pymatgen.util.testing import PymatgenTest
from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import ExplicitPermutationsAlgorithm
from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import... | .0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
[[0.0, 0.0, -1.0], [1.0, 0.0, 0.0], [0.0, -1.0, 0.0]],
[[0.0, 0.0, -1.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
[[0.0, 0.0, -1.0], | [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]]]
self.assertArrayAlmostEqual(cg_oct.faces(sites=sites), faces)
edges = [[[0.0, 0.0, 1.0], [1.0, 0.0, 0.0]],
[[0.0, 0.0, 1.0], [0.0, 1.0, 0.0]],
[[0.0, 0.0, 1.0], [0.0, -1.0, 0.0]],
[[0.0, 0.0, 1.0], [0.0, 0.0, -1.0]]... |
XianwuLin/AsynMongo | __init__.py | Python | mit | 33 | 0 | f | rom AsynMongo import Collection
| |
rory/osm-find-first | tests/test_osm_find_first.py | Python | gpl-3.0 | 3,556 | 0.002812 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_osm_find_first
----------------------------------
Tests for `osm-find-first` module.
"""
import unittest
import tempfile
import re
import httpretty
import osm_find_first
def v(string):
return string.format(version=osm_find_first.__version__)
class Test... |
body='<osm><relation id="1" uid="123" user="testuser" timestamp="2000-01-01 115:24:02"></relation></osm>',
content_type="text/xml")
|
result = osm_find_first.find_first(
[], [{'osm_type': 'relation', 'osm_id': '1'}])
self.assertEqual(
result, [{'osm_timestamp': '2000-01-01 115:24:02', 'osm_type': 'relation', 'osm_uid': '123', 'osm_user': 'testuser', 'osm_id': '1'}])
self.assertEqual(httpretty.last_requ... |
RevansChen/online-judge | Codewars/8kyu/find-out-whether-the-shape-is-a-cube/Python/test.py | Python | mit | 579 | 0.01209 | # Python - 3.6.0
Test.assert_equals(cube_checker(-12,2), False)
Test.assert_e | quals(cube_checker(8, 3), False)
Test.assert_equals(cube_checker(8, 2), True)
Test | .assert_equals(cube_checker(-8,-2), False)
Test.assert_equals(cube_checker(0, 0), False)
Test.assert_equals(cube_checker(27, 3), True)
Test.assert_equals(cube_checker(1, 5), False)
Test.assert_equals(cube_checker(125, 5),True)
Test.assert_equals(cube_checker(125,-5),False)
Test.assert_equals(cube_checker(0, 12), Fals... |
Francis-Liu/animated-broccoli | nova/scheduler/host_manager.py | Python | apache-2.0 | 32,388 | 0.000494 | # Copyright (c) 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 ... | ""Update information about a host from a ComputeNode object. | """
if (self.updated and compute.updated_at
and self.updated > compute.updated_at):
return
all_ram_mb = compute.memory_mb
# Assume virtual size is all consumed by instances if use qcow2 disk.
free_gb = compute.free_disk_gb
least_gb = compute.disk_avai... |
skeledrew/web-dl | cookies.py | Python | agpl-3.0 | 10,859 | 0.000829 | # -*- coding: utf-8 -*-
"""
Cookie handling module. (Ripped from coursera-dl)
TODO: Convert to Hy and make generic.
"""
import logging
import os
import ssl
import tempfile
import getpass
import requests
from requests.adapters import HTTPAdapter
try: # Workaround for broken Debian/Ubuntu packages? (See issue #331)
... | enough:
raise AuthenticationFailed('Did not find necessary cookies.')
logging.in | fo('Found authentication cookies.')
def do_we_have_enough_cookies(cj, class_name):
"""
Check whether we have all the required cookies
to authenticate on class.coursera.org.
"""
domain = 'class.coursera.org'
path = "/" + class_name
return cj.get('csrf_token', domain=domain, path=path) is n... |
persepolisdm/translation-API | pdm_api/settings/__init__.py | Python | gpl-3.0 | 688 | 0.001453 | from .settings import info
class get_settings:
def __init__(self):
self.settings = info()
self.repo = self.settings['repo']
self.repo_path = self.repo['repo_path']
self | .repo_url = self.repo['repo_url']
self.key = self.repo['ssh_key']
self.slack = self.settings['slack']
self.slack_token = self.slack['token']
def repo(self):
return(self.repo)
def repo_url(self):
| return(self.repo_url)
def repo_path(self):
return(self.repo_path)
def ssh_key(self):
return(self.key)
def slack(self):
return(self.slack)
def slack_token(self):
return(self.slack_token)
|
adrifloresm/sssweep | setup.py | Python | bsd-3-clause | 2,611 | 0.003064 | """
* Copyright (c) 2012-2017, Nic McDonald and Adriana Flores
* 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, t... | ort re
import os
import sys
try:
from setuptools import setup
except:
print('please install setuptools via pip:')
print(' pip3 install setuptools') |
sys.exit(-1)
def find_version(*file_paths):
version_file = codecs.open(os.path.join(os.path.abspath(
os.path.dirname(__file__)), *file_paths), 'r').read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
... |
vovanbo/aiohttp_json_api | punch_version.py | Python | mit | 31 | 0 | major = 0
minor = 3 | 7
patch = | 0
|
Bioto/Huuey-python | huuey/requester.py | Python | mit | 809 | 0.001236 | import json
from requests import Request, Session
class Requester:
@staticmethod
def verifyconnection(url="http://google.com"):
return Requester.request(url, method='GET', decode=False)
@staticmethod
def request(url, method=None, data=None, decode=True):
if not url.startswith('http://... | url = 'http://' + url
request = Request(method, url)
if data:
request.data = json.dumps(data)
with Session() as session:
prepped = session.prepare_request(request)
try:
| response = session.send(prepped)
except:
return False
if decode:
return json.loads(response.text)
else:
return response
|
stefanseefeld/synopsis | Synopsis/Formatters/HTML/Views/FileListing.py | Python | lgpl-2.1 | 2,722 | 0.019471 | #
# Copyright (C) 2000 Stephen Davies
# Copyright (C) 2000 Stefan Seefeld
# All rights reserved.
# Licensed to the public under the terms of the GNU LGPL (>= 2),
# see the file COPYING for details.
#
from Synopsis.Processor import Parameter
from Synopsis import FileTree
from Synopsis.Formatters.HTML.View import View
f... | oot(self):
return self.filename(), self.title()
def register_filenames(self):
"""Registers a view for each file indexed."""
self.processor.register_filename(self.filename(), self, None)
def process(self):
"""Creates the listing using the recursive process_file_tree_node method"""
... | recursively visit all nodes
self.process_file_tree_node(self.processor.file_tree.root())
self.write('</ul>')
self.end_file()
def _node_sorter(self, a, b):
"""Compares file nodes a and b depending on whether they are leaves
or not"""
a_leaf = isinstance(a, FileTree.File)
b_... |
theapricot/oppapp2 | app.py | Python | mit | 13,357 | 0.013626 | mustBeAdmin = ['You must be the webadmin to access this page.','danger']
mustBeStudentCoord = ['You must be a student coordinator to access this page.','danger']
from sockdefs import *
print("forming routes...")
monkey.patch_all()
# MAIN EVENTS PAGE #
@app.route('/', methods=['GET', 'POST'])
def index():
if requ... | srid, frmid, toid] =r | equest.form['movetoevent'].split(',')
usr = Users.query.get(int(usrid))
frm = Opps.query.get(int(frmid))
to = Opps.query.get(int(toid))
if usr in frm.usersPreferred:
usr.preferredOpps.remove(frm)
else:
usr.opps.remove(frm)
... |
MarcosCommunity/odoo | comunity_modules/costing_method_settings/__openerp__.py | Python | agpl-3.0 | 1,761 | 0 | #!/usr/bin/python
###############################################################################
# Module Writen to OpenERP, Open Source Managem | ent Solution
# Copyright (C) OpenERP Venezuela (<http://www.vauxoo.com>).
# All Right | s Reserved
###############################################################################
# Credits:
# Coded by: Katherine Zaoral <kathy@vauxoo.com>
# Planified by: Katherine Zaoral <kathy@vauxoo.com>
# Audited by: Katherine Zaoral <kathy@vauxoo.com>
########################################################... |
googleapis/python-error-reporting | google/cloud/errorreporting_v1beta1/services/error_group_service/client.py | Python | apache-2.0 | 25,457 | 0.001453 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from google.api_core import gapic_v1
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualT... | lRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError: # pragma: NO COVER
OptionalRetry = Union[retries.Retry, object] # type: ignore
from google.cloud.errorreporting_v1beta1.types import common
from google.cloud.errorreporting_v1beta1.types import error_group_service
from .transpor... |
standage/tag | tag/__init__.py | Python | bsd-3-clause | 1,438 | 0 | #!/usr/bin/env python
#
# -----------------------------------------------------------------------------
# Copyright (C) 2015 Daniel Standage <daniel.standage@gmail.com>
#
# This file is part of tag (http://github.com/sta | ndage/tag) and is licensed
# under the BSD 3-clause license: see LICENSE.
# -----------------------------------------------------------------------------
"""Package-wide configuration"""
try:
import __builtin__ as builtins
except ImportError: # pragma: no cover
import builtins
from tag.comment import Comment
... | mport GFF3Reader
from tag.writer import GFF3Writer
from tag.score import Score
from tag import bae
from tag import cli
from tag import index
from tag import locus
from tag import select
from tag import transcript
from gzip import open as gzopen
import sys
from ._version import get_versions
__version__ = get_versions()... |
jobec/django-auth-adfs | tests/settings.py | Python | bsd-2-clause | 2,308 | 0 | SECRET_KEY = 'secret'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
... | ontrib. | sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_auth_adfs',
'tests',
)
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
'django_auth_adfs.backend.AdfsAuthCodeBackend',
'django_auth_adfs.backend.AdfsAccessTokenBackend',
)
ROOT_URLCONF = '... |
zhangyage/Python-oldboy | day14/BBS/web/models.py | Python | apache-2.0 | 1,693 | 0.022011 | # -*- coding:utf-8 -*-
from django.db import models
# Create your models here.
class UserType(models.Model):
display = models.CharField(max_length=50)
def __unicode__(self):
return self.display
class Admin(models.Model):
username = models.CharField(max_length=50)
password = models.Cha... | eld(max_length=256)
url = models.URLField()
favor_count = models.IntegerField(default=0)
#点赞数
replay_count = models.IntegerField(default=0)
#评论数
news_type = models.ForeignKey('NewType')
user = models.ForeignKey('Adm | in')
create_date = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
class Reply(models.Model):
content = models.TextField()
user = models.ForeignKey('Admin')
new = models.ForeignKey('News')
create_date = models.DateTimeField... |
Darkkey/hartinsecurity | hart_change_longtag.py | Python | bsd-2-clause | 1,068 | 0.015918 | import serial,time,socket
import hart_protocol
import sys
port = 3
if len(sys.argv) < 4:
print "Error, usage " + sys.argv[0] + " port long_address new_longtag"
print "Usage hex string (5 hex digits) as address and LATIN-1 string as new long tag"
quit()
address = sys.argv[2].decode('hex')
if len(addr... | , address should be 5 bytes long!"
longtag = sys.argv[3]
if len(longtag) != 32:
print "Error, long tag should be 32 bytes long!"
port = int(sys.argv[1]) - 1
print "Opening COM" + str(port + 1) + "..."
preambles ... | ngtag
packet = '\xff' * preambles + pack + hart_protocol.get_checksum(pack)
ser = serial.Serial(port, 1200)
print "writing: " + hart_protocol.dump_hex(packet)
ser.write(packet)
print "packet sent succesfully!" |
tortib/nzbToMedia | nzbtomedia/linktastic/linktastic.py | Python | gpl-3.0 | 4,260 | 0.00493 | # Linktastic Module
# - A python2/3 compatible module that can create hardlinks/symlinks on windows-based systems
#
# Linktastic is distributed under the MIT License. The follow are the terms and conditions of using Linktastic.
#
# The MIT License (MIT)
# Copyright (c) 2012 Solipsis Development
#
# Permission is here... | pports nt systems as well
def link(src, dest):
if os.name == 'nt':
_link_windows(src, dest)
else:
os.link(src, dest)
# Create a symlink to src named as dest, but don't fail if yo | u're on nt
def symlink(src, dest):
if os.name == 'nt':
_symlink_windows(src, dest)
else:
os.symlink(src, dest)
# Create a symlink to src named as dest, but don't fail if you're on nt
def dirlink(src, dest):
if os.name == 'nt':
_dirlink_windows(src, dest)
else:
os.symlink... |
angr/angr | angr/analyses/decompiler/peephole_optimizations/remove_redundant_nots.py | Python | bsd-2-clause | 531 | 0 | from ailment.expression import UnaryOp
from .base import P | eepholeOptimizationExprBase
class RemoveRedundantNots(PeepholeOptimizationExprBase):
__slots__ = ()
name = "Remove redundant Nots"
expr_classes = (UnaryOp, ) # all expressions are allowed
def optimize(self, expr: UnaryOp):
# Not(Not(expr)) ==> expr
if expr.op == "Not" \
... | ance(expr.operand, UnaryOp) \
and expr.operand.op == "Not":
return expr.operand.operand
return None
|
RudolfCardinal/crate | crate_anon/nlp_webserver/views.py | Python | gpl-3.0 | 30,270 | 0 | #!/usr/bin/env python
r"""
crate_anon/nlp_webserver/views.py
===============================================================================
Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com).
This file is part of CRATE.
CRATE is free software: you can redistribute it and/or modify
it under... | EDIS_PORT = 6379 # https://redis.io/t | opics/quickstart
DEFAULT_REDIS_DB_NUMBER = 0 # https://redis.io/commands/select
REDIS_HOST = SETTINGS.get(NlpServerConfigKeys.REDIS_HOST, DEFAULT_REDIS_HOST)
REDIS_PORT = SETTINGS.get(NlpServerConfigKeys.REDIS_PORT, DEFAULT_REDIS_PORT)
REDIS_DB_NUMBER = SETTINGS.get(NlpServerConfigKeys.REDIS_DB_NUMBER,
... |
scheib/chromium | third_party/blink/web_tests/external/wpt/resource-timing/resources/multi_redirect.py | Python | bsd-3-clause | 2,682 | 0.003356 | import urllib.parse
from wptserve.utils import isomorphic_encode
def main(request, response):
"""Handler that causes multiple redirections. Redirect chain is as follows:
1. Initial URL containing multi-redirect.py
2. Redirect to cross-origin URL
3. Redirect to same-origin URL
4. Fin... | *"
if b"tao_value" in request.GET:
tao_value = request.GET.first(b"tao_value")
tao_steps = 0
if b"tao_steps" in request.GET:
tao_steps = int(request.GET.first(b"tao_steps"))
| next_tao_steps = tao_steps - 1
redirect_url_path = b"/resource-timing/resources/multi_redirect.py?"
redirect_url_path += b"page_origin=" + page_origin
redirect_url_path += b"&cross_origin=" + cross_origin
redirect_url_path += b"&final_resource=" + urllib.parse.quote(final_resource).encode('ascii')
... |
Ideabin/Ideabin | server/login.py | Python | gpl-3.0 | 197 | 0 | f | rom flask | _login import LoginManager
from server.users.models import User
login_manager = LoginManager()
@login_manager.user_loader
def load_user(user_id):
return User.get(user_id=user_id)
|
indictranstech/reciphergroup-frappe | frappe/permissions.py | Python | mit | 13,272 | 0.026597 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe, copy, json
from frappe import _, msgprint
from frappe.utils import cint
import frappe.share
rights = ("read", "write", "create", "delete", "submit", "cancel", "ame... | ared:
if verbose: print "Shared"
if ptype in ("read", "write", "share") or meta.permissions[0].get(ptype):
return True
elif shared:
# if atleast one shared d | oc of that type, then return True
# this is used in db_query to check if permission on DocType
if verbose: print "Has a shared document"
return True
return False
role_permissions = get_role_permissions(meta, user=user, verbose=verbose)
if not role_permissions.get(ptype):
return false_if_not_shared(... |
JeffHoogland/qAndora | playerGst/__init__.py | Python | bsd-3-clause | 24 | 0 | fro | m playerGst | import *
|
VISTAS-IVES/pyvistas | source/vistas/ui/windows/legend.py | Python | bsd-3-clause | 8,666 | 0.001154 | import wx
from PIL import Image
from vistas.core.threading import Thread
from vistas.ui.controls.static_image import StaticImage
from vistas.ui.utils import make_window_transparent
LegendRenderEvent, EVT_LEGEND_RENDERED = wx.lib.newevent.NewEvent()
class LegendWindow(wx.Frame):
""" A window for showing a render... | parent = parent.GetParent()
event.Skip()
def OnLegendRendered(self, event: LegendRenderEvent):
self.legend_image.image = event.image
self.Refresh()
def CalculateProportions(self):
canvas_size = self.canvas.GetSize()
size = self.GetSize()
center = wx.Point(self... | art_pos.y + size.y / 2)
min_x = (size.x / 2) / canvas_size.x
min_y = (size.y / 2) / canvas_size.y
max_x = (canvas_size.x - size.x / 2) / canvas_size.x
max_y = (canvas_size.y - size.y / 2) / canvas_size.y
self.width = center.x / canvas_size.x
if self.width <= min_x:
... |
VRaviTheja/SDN-policy | flowgenerator/random_priority.py | Python | apache-2.0 | 180 | 0.005556 | import random
def prio():
ac | tion_lst = []
lim = 1000
for _ in range(lim):
k = random.randint(1, 201)
action_lst.append(k)
return action_ls | t
|
tb-animator/tbtools | updater.py | Python | mit | 5,495 | 0.008735 | __author__ = 'Tom'
import pickle
import urllib2
import os
import pymel.core as pm
import project_data as prj
reload(prj)
class updater():
def __init__(self):
self.master_url = 'https://raw.githubusercontent.com/tb-animator/tbtools/master/'
self.realPath = os.path.realpath(__file__)
self.ba... | self.file_text = pm.text(label="")
self.progress_bar = pm.progressBar(maxValue=len(self.project_data.scripts)-1)
# pm.button( label='Delete all', parent=layout)
pm.button( label='Update',
command=lambda *args : updater().download_project_files(self),
pare... | parent=layout)
pm.button( label='Close', command=('cmds.deleteUI(\"' + window + '\", window=True)') , parent=layout)
pm.setParent( '..' )
pm.showWindow(window)
def update_hotkeys():
try:
import tb_keyCommands as tb_hotKeys
reload(tb_hotKeys)
tb_hotKeys.hotkey_t... |
oicr-ibc/cssscl | cssscl/configure.py | Python | gpl-3.0 | 1,425 | 0.006316 | import pymongo
import getpass
import os
import base64
import ConfigParser
import sys
from database import *
from pymongo.errors import DuplicateKeyError
db, logger = None, None
def setup_config(args):
'''Saves MongoDB settings to a configuration file'''
config = ConfigParser.SafeConfigParser()
config.a... | gs.username or raw_input('Username [none]: '))
#config.set('MongoDB', 'password', args.password or getpass.getpass('Password [none]: '))
# Writing our configuration file
with open(os.path.expanduser('~/.cssscl/cssscl.cfg'), 'wb') as configfile:
config.write(configfile)
def main(args): |
'''Setup MongoDB for use by cssscl'''
global db, logger
logger = args.logging.getLogger(__name__)
# Setup config files
setup_config(args)
db = connect(args)
logger.info('Done!')
if __name__ == '__main__':
print 'This program should be run as part of the cssscl package:\n\t$ csssc... |
Mellthas/quodlibet | quodlibet/ext/songsmenu/website_search.py | Python | gpl-2.0 | 6,154 | 0.000163 | # Copyright 2011-2018 Nick Boultbee
#
# 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.
import os
from urllib.parse impor... | connect_obj(configure, 'activate', self.edit_patterns, configure)
submenu.append(SeparatorMenuItem())
submenu.append(configure)
if submenu.get_children():
self.set_submenu(submenu)
| else:
self.set_sensitive(False)
def plugin_songs(self, songs):
# Check this is a launch, not a configure
if self.chosen_site:
url_pat = self.get_url_pattern(self.chosen_site)
pat = Pattern(url_pat)
# Remove Nones, and de-duplicate collection
... |
cbartz/git-lfs-swift-server | git_lfs_swift_server/__init__.py | Python | apache-2.0 | 637 | 0 | # coding=utf-8
# Copyright 2017 Christopher Bartz <bartz@dkrz.de>
#
# 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... | OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions | and
# limitations under the License.
from .server import app
|
guiandmag/scrum-django | board/forms.py | Python | apache-2.0 | 1,021 | 0 | import django_filters
from django.contrib.auth import get_user_model
from .models import Sprint | , Task
User = get_user_model()
class NullFilter(django_filters.BooleanFilter):
"""Filter on a field set as null or not."""
def filter(self, qs, value):
if value is not None:
return qs.filter(**{'%s__isnull' % self.name: value})
retu | rn qs
class SprintFilter(django_filters.FilterSet):
end_min = django_filters.DateFilter(name='end', lookup_type='gte')
end_max = django_filters.DateFilter(name='end', lookup_type='lte')
class Meta:
model = Sprint
fields = ('end_min', 'end_max', )
class TaskFilter(django_filters.FilterS... |
Ezetowers/AppEngine_EventsManagement | load_tests/QueryGuest_Case/query_guests.py | Python | mit | 1,268 | 0.002366 | from lxml import etree
import sys
REQUEST_BODY_PART_1 = '<![CDATA[actualEvent='
REQUEST_BODY_PART_2 = '&queryEmail='
REQUEST_BODY_PART_3 = ']]>'
CONTENT_TYPE = 'Content-type: application/x-www-form-urlencoded'
def usage():
print "python create_test_case [URL]"\
" [EVENT_NAME] [AMOUNT_CASES] [TEST_CASE_FI... | T'
body = REQUEST_BODY_PART_1 + event + REQUEST_BODY_PART_2 + "Email" + str(case) + REQUEST_BODY_PART_3
etree.SubElement(case_node, 'body').text = body
etree.SubElement(case_node, 'add_header').text = CONTENT_TYPE
root.append(case_node)
etree.ElementTree(root).write(test_case_filena... | ncoding='iso-8859-1')
# Line to indicate that this is the main
if __name__ == "__main__":
main()
|
inspectorbean/spat | reqs/apps.py | Python | gpl-3.0 | 83 | 0 | from django.apps import AppConfig
class ReqsConfig(AppCo | nfig):
name = 'reqs'
| |
jeffbuttars/pcm | pcmpy/cmds/__init__.py | Python | mit | 876 | 0.001142 | import sys
import os
import importlib
import glob
# Imoprt and instantiate each Cmd object.
_this_dir = os.path.dirname(__file__)
_this_mod = os.path.basename(_this_dir)
def build_cmds(sub_parser):
cmd_objs = {}
imlist = glob.glob(os.path.join(_this_dir, "*.py"))
imlist.remove(os.path.join(_this_dir, "... | rt_module("pcm." + _this_mod + '.' + im)
if hasattr(mod, 'Cmd'):
# print("Found Command: ", mod.Cmd.name)
cmd_objs[mod.Cmd.name] = mod.Cmd(sub_parser)
cmd_objs[mod.Cmd.name].build()
# end for im in imlist
| # print(cmd_objs)
return cmd_objs
#build_cmds()
|
nateprewitt/werkzeug | werkzeug/serving.py | Python | bsd-3-clause | 25,464 | 0.000589 | # -*- coding: utf-8 -*-
"""
werkzeug.serving
~~~~~~~~~~~~~~~~
There are many ways to serve a WSGI application. While you're developing
it you usually don't want a full blown webserver like Apache but a simple
standalone one. From Python 2.5 onwards there is the `wsgiref`_ server in
the standa... | ne can be a pain in the ass in some situations.
The easiest way is creating a small ``start-myproject.py`` that runs the
application::
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from myproject import make_app
from werkzeug.serving import run_simple
app = make_app(..... | e('localhost', 8080, app, use_reloader=True)
You can also pass it a `extra_files` keyword argument with a list of
additional files (like configuration files) you want to observe.
For bigger applications you should consider using `werkzeug.script`
instead of a simple start file.
:copyright: (c) 2... |
tu-darmstadt-ros-pkg/hector_diagnostics | hector_computer_monitor/scripts/cpu_monitor.py | Python | bsd-3-clause | 31,998 | 0.013938 | #!/usr/bin/env python
#
# Software License Agreement (BSD License)
#
# Copyright (c) 2009, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source co... | the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the a | bove
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the Willow Garage nor the names of its
# contributors may be used to endorse or promote products derived
# from this softw... |
SickGear/SickGear | lib/simplejson/__init__.py | Python | gpl-3.0 | 24,480 | 0.001348 | r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`simplejson` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of ... | 1+2j)
>>> from decimal import Decim | al
>>> json.loads('1.1', parse_float=Decimal) == Decimal('1.1')
True
Specializing JSON object encoding::
>>> import simplejson as json
>>> def encode_complex(obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... raise TypeError('Object of type %s is not... |
jabber-at/hp | hp/core/tests/base.py | Python | gpl-3.0 | 8,383 | 0.002863 | # -*- coding: utf-8 -*-
#
# This file is part of the jabber.at homepage (https://github.com/jabber-at/hp).
#
# This project 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... | ssertTaskCount(self, mocked, count):
"""Assert that `count` Celery tasks h | ave been called."""
self.assertEqual(mocked.call_count, count)
def assertNoTasks(self, mocked):
self.assertTaskCount(mocked, 0)
def assertTaskCall(self, mocked, task, *args, **kwargs):
self.assertTrue(mocked.called)
a, k = mocked.call_args
self.assertEqual(k, {}) # app... |
devoid/nova | nova/tests/integrated/v3/test_lock_server.py | Python | apache-2.0 | 1,568 | 0 | # 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 by applicable law or agreed t... | ed.v3 import test_servers
class LockServerSamplesJsonTest(test_servers.ServersSampleBase):
extension_name = "os-lock-server"
def setUp(self):
"""setUp Method for LockServer api samples extension
This method creates the server that will be used | in each tests
"""
super(LockServerSamplesJsonTest, self).setUp()
self.uuid = self._post_server()
def test_post_lock_server(self):
# Get api samples to lock server request.
response = self._do_post('servers/%s/action' % self.uuid,
'lock-server... |
noxora/flask-base | flask/lib/python3.4/site-packages/Crypto/__init__.py | Python | mit | 1,836 | 0.001089 | # -*- coding: utf-8 -*-
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# non-exclusive license to e... | aphy Toolkit
A collection of cryptographic modules implementing various algorithms
and protocols.
Subpackages:
Crypto.Cipher
Secret-key (AES, TDES, Salsa20, ChaCha20, CAST, Blowfish, ARC4) and public- | key encryption (RSA PKCS#1) algorithms
Crypto.Hash
Hashing algorithms (SHA-1, SHA-2, SHA-3, BLAKE2, HMAC, MD5)
Crypto.IO
Encodings useful for cryptographic data (PEM, PKCS#8)
Crypto.Protocol
Cryptographic protocols (key derivation functions, Shamir's Secret Sharing scheme)
Crypto.PublicKey
Public-key generation, im... |
vileopratama/vitech | src/addons/hr_recruitment/models/hr_job.py | Python | mit | 5,037 | 0.003574 | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp import _, api, fields, models
class Job(models.Model):
_inherit = "hr.job"
_name = "hr.job"
_inherits = {'mail.alias': 'alias_id'}
@api.model
def _default_address_id(self):
return self.env.user.compan... | (data['job_id'][0], data['job_id_count']) for data in read_group_result)
for job in self:
job.application_count = result.get(job.id, 0)
@api.model
def create(self, vals):
job = super(Job, self.with_context(alias_model_name='hr.applicant',
m... | alias_parent_model_name=self._name)).create(vals)
job.alias_id.write({'alias_parent_thread_id': job.id, "alias_defaults": {'job_id': job.id}})
return job
@api.multi
def unlink(self):
# Cascade-delete mail aliases as well, as they should not exist without the job position.
ali... |
spigwitmer/mysqlproxy | mysqlproxy/packet.py | Python | bsd-3-clause | 7,817 | 0.001407 | """
Wire-level packet handling
"""
from mysqlproxy.types import FixedLengthInteger, \
FixedLengthString, LengthEncodedInteger, \
RestOfPacketString
from mysqlproxy import capabilities
from StringIO import StringIO
__all__ = [
'PacketMeta', 'IncomingPacketChain', 'OutgoingPacketChain',
'Packet',... | ength(self):
"""
Amount of packets needed to be read to retrieve
the entire payload
"""
return len(self.packet_meta)
@property
def total_length(self):
"""
Total payload length
"""
return sum([x.length for x in self.packet_meta])
class Ou... | rt_seq_id
def add_field(self, field, label='<unlabeled>'):
"""
Add field to payload
"""
self.fields.append((label, field))
def _write_packet_header(self, length, seq, fde):
"""
Write out packet header with given length
and sequence id to file-like fde
... |
openergy/openergy | ovbpclient/rest_client.py | Python | mit | 4,045 | 0.002472 | import time
import requests
from .exceptions import HttpError
from .json import json_loads
def check_rep(rep):
if (rep.status_code // 100) != 2:
raise HttpError(rep.text, rep.status_code)
def rep_to_json(rep):
check_rep(rep)
# we use our json loads for date parsing
return json_loads(rep.tex... | heck_rep(rep)
return rep.content
def destroy(self, path, resource_id, params=None):
rep = self.session.delete(
f"{self.base_url}/{path}/{resource_id}/",
params=params,
verify=self.verify_ssl)
if rep.status_code == 204:
return
retu | rn rep_to_json(rep)
def wait_for_on(self, timeout=10, freq=1):
start = time.time()
if timeout <= 0:
raise ValueError
while True:
if (time.time() - start) > timeout:
raise TimeoutError
try:
rep = self.session.get(
... |
marratj/ansible | lib/ansible/modules/packaging/language/maven_artifact.py | Python | gpl-3.0 | 18,975 | 0.005586 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2014, Chris Schmidt <chris.schmidt () contrastsecurity.com>
#
# Built using https://github.com/hamnis/useful-scripts/blob/master/python/download-maven-artifact
# as a reference and starting point.
#
# GNU General Public License v3.0+ (see COPYING or https://www... | rsion_added: "2.4"
extends_documentation_fragment:
- files
'''
EXAMPLES = '''
# Download the latest version of the JUnit framework artifact from Maven Central
- maven_artifact:
group_id: junit
artifact_id: junit
dest: /tmp/junit-latest.jar
# Download JUnit 4.11 from Maven Central
- maven_artifact:
... | .jar
# Download an artifact from a private repository requiring authentication
- maven_artifact:
group_id: com.company
artifact_id: library-name
repository_url: 'https://repo.company.com/maven'
username: user
password: pass
dest: /tmp/library-name-latest.jar
# Download a WAR File to the Tomcat... |
Enether/python_wow | models/creatures/creature_template.py | Python | mit | 3,514 | 0.002846 | from sqlalchemy import Column, Integer, String, Text, Boolean, ForeignKey
from sqlalchemy.orm import relationship
from database.main import Base
class CreatureTemplateSchema(Base):
"""
This table holds the information about each creature in the game
entry - the unique ID of this creature
creature_nam... | gossip, respawnable
1, Zimbab, "monster" 1, 10, 10, 50, 2, 4 1, 1, "Hey there", False
type is "monster" meaning this | is a hostile NPC
Creature Level: 1 Zimbab, HP: 10, MANA: 10, Damage: 2-4.
He is needed to complete quest with ID 1 and the loot he drops is from the row in the loot_table DB table with
entry 1. If talking to him is enabled, he would say "Hey there".
"""
__tablename__ = 'creature_templat... |
commontk/ctk-cli-indexer | ctk_cli_indexer/indexer.py | Python | apache-2.0 | 2,583 | 0.02168 | import sys, datetime
import elasticsearch
INDEX = 'cli'
DOC_TYPE = 'cli'
def create_elasticsearch_index(es):
"""es should be an elasticsearch.Elasticsearch instance"""
es.indices.create(index = INDEX, ignore = 400) # ignore already existing index
es.indices.put_mapping(index = INDEX, doc_type = DOC_TYPE, ... | new document '%s'.\n" % doc_id)
else:
existing.remove(old['_id'])
if old['_source'] != doc:
es.index(INDEX, DOC_TYPE, body = doc, id = doc_id, timestamp = timestamp)
sys.stdout.write("changed document '%s'.\ | n" % doc_id)
else:
sys.stdout.write("leaving '%s' alone, no change...\n" % doc_id)
# finally, remove existing documents that were not contained in `docs`:
for doc_id in existing:
sys.stdout.write("removing '%s', which is no longer in the '%s' JSON...\n" % (doc_id, source))
... |
FibercorpLabs/FibercorpDevops | cisco/aci/addUserDomain.py | Python | gpl-3.0 | 1,791 | 0.003908 | from cobra.model.aaa import User, UserDomain
from createLocalUser import input_key_args as input_local_user
from createMo import *
def input_key_args(msg='\nPlease Specify User Domain:'):
print msg
return input_raw_input("User Domain Name", required=True)
def add_user_domain(parent_mo, user_domain):
""... | self.local_user = self.args.pop('local_user')
self.user_domain = self.args.pop('user_domain')
def wizard_mode_input_args(self):
self.args['local_user'] = input_local_user('\nPlease Specify User Domain:', user_only=True, delete_function=self.delete)[0]
self.args['user_domain'] = input_key_... | user-' + self.local_user + '/userdomain-', self.user_domain, UserDomain, description='User Domain')
super(AddSecurityDomain, self).delete_mo()
def main_function(self):
self.check_if_mo_exist('uni/userext/user-', self.local_user, User, 'User')
add_user_domain(self.mo, self.user_domain)
if _... |
mozilla-services/FindMyDevice | test/buildAssert.py | Python | mpl-2.0 | 303 | 0 | #! /usr/bin/python
impor | t base64
import sys
f = open(sys.argv[1], "r")
items = []
for line in f.readlines():
if len(line.strip()) == 0:
continue
if line[0] == "{":
items.append(base64.b64encode(line.strip()))
else:
items.append(line.strip())
print ".".joi | n(items)
|
glennmatthews/cot | COT/tests/test_doctests.py | Python | mit | 1,224 | 0 | #!/usr/bin/env python
#
# test_doctests.py - test runner for COT doctests
#
# July 2016, Glenn F. Matthews
# Copyright (c) 2016-2017 the COT project developers.
# See the COPYRIGHT.txt file at the top-level directory of this distribution
# and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt.
#
# This ... | For the parameters, see :mod:`unittest`. The parameters are unused here | .
"""
suite = TestSuite()
suite.addTests(DocTestSuite('COT.data_validation'))
suite.addTests(DocTestSuite('COT.utilities'))
return suite
|
enthought/traitsgui | enthought/pyface/timer/do_later.py | Python | bsd-3-clause | 2,116 | 0.014178 | #------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
| # This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
# Thanks fo | r using Enthought open source!
#
# Author: Enthought, Inc.
# Description: <Enthought util package component>
#------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
#
# Provides a simple function for scheduling som... |
damoxc/vsmtpd | plugins/ident/geoip.py | Python | gpl-3.0 | 1,203 | 0.000831 | #
# ident/geoio.py
#
# Copyright (C) 2011 Damien Churchill <damoxc@gmail.com>
#
# 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, or (at your option)
# any later version.
#
# Thi... | uld have received a copy of the GNU General Public License
# along with this program. If not, write to:
# The Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor
# Boston, MA 02110-1301, USA.
#
import GeoIP
import logging
from vsmtpd.hooks import hook
from vsmtpd.plugins.plugin import Plugin... | self, connection):
country = self.gi.country_code_by_addr(connection.remote_ip)
connection.notes['geoip_country'] = country
|
Thoronador/ArxLibertatis | plugins/blender/arx_addon/dataFts.py | Python | gpl-3.0 | 10,486 | 0.005531 | # Copyright 2014-2020 Arx Libertatis Team (see the AUTHORS file)
#
# This file is part of Arx Libertatis.
#
# Arx Libertatis 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
... | er.playerpos.y, ftsHeader.playerpos.z))
self.log.debug("Fts Header Mscenepos: %f,%f,%f" % (ftsHeader.Mscenepos.x, ftsHeader.Mscenepos.y, ftsHeader.Mscenepos.z))
sceneOffset = (ftsHeader.Mscenepos.x, ftsHeader.Mscenepos.y, ftsHeader.Mscenepos.z)
texturesType = FAST_TEXTURE_CONTAINER * ftsHeader.... | xtures))
#for i in textures:
# log.info(i.fic.decode('iso-8859-1'))
cells = [[None for x in range(ftsHeader.sizex)] for x in range(ftsHeader.sizez)]
for z in range(ftsHeader.sizez):
for x in range(ftsHeader.sizex):
cellHeader = FAST_SCENE_INFO.fro... |
Armored-Dragon/goldmine | default_cogs/web.py | Python | mit | 1,742 | 0.003444 | """Web dashboard."""
import os
import sys
import json
import aiohttp
from discord.ext import commands
import util.dynaimport as di
from .cog import Cog
japronto = di.load('japronto')
sanic = di.load('sanic')
response = di.load('sanic.response')
root_dir = os.path.dirname(os.path.abspath(sys.modules['__main__'].core_fi... | ng web server on %s:%s!', self.host, str(self.port))
app = sanic.Sanic()
await self.init_app(app)
self.app = app
self.server = app | .create_server(host=self.host, port=self.port)
self.server_task = self.loop.create_task(self.server)
async def init_app(self, app):
self.logger.info('Initializing app...')
@app.route('/')
async def test(req):
self.logger.info('Got request at /')
return respon... |
JulienMcJay/eclock | windows/Python27/Lib/Cookie.py | Python | gpl-2.0 | 25,844 | 0.010447 | #!/usr/bin/env python
#
####
# Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>
#
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software
# and its documentation for any purpose and without fee is hereby
# granted, provided that the above copyright notice appear in ... | t any Python object to a
value, and recover the exact same object when the cookie ha | s been
returned. (SerialCookie can yield some strange-looking cookie
values, however.)
>>> C = Cookie.SerialCookie()
>>> C["number"] = 7
>>> C["string"] = "seven"
>>> C["number"].value
7
>>> C["string"].value
'seven'
>>> C.output()
'Set-Cookie: number="I7\\012."\r\nSet-Cookie: string="S\'se... |
ESGF/esgf-drslib | drslib/exceptions.py | Python | bsd-3-clause | 73 | 0.027397 | """
drslib exceptions
"""
class TranslationError( | Exception):
pass | |
cloudbase/maas | src/maasserver/models/node.py | Python | agpl-3.0 | 32,077 | 0.000717 | # Copyright 2012, 2013 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Node objects."""
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
str = None
__metaclass__ = type
__all__ = [
"NODE_TRA... | h related
data where appropriate.
:param user: The user that should be used in the permission check.
:type user: User_
:param perm: The permission to check.
:type perm: a permission string from NODE_PERMISSION
:param ids: If given, limit result to nodes with these system... | :param from_nodes: Optionally, restrict the answer to these nodes.
:type from_nodes: Query set of `Node`.
.. _User: https://
docs.djangoproject.com/en/dev/topics/auth/
#django.contrib.auth.models.User
"""
if from_nodes is None:
from_nodes = self.all(... |
dealien/Red-Magician | cogs/survey.py | Python | gpl-3.0 | 27,575 | 0.000544 | import asyncio
from collections import defaultdict
from datetime import datetime, timedelta
from itertools import zip_longest
import os
from typing import Any, Dict, List
try:
from dateutil import parser as dp
dateutil_available = True
except:
dateutil_available = False
import discord
from discord.ext imp... | = 1:
opts[opt_s[0]] = {
"limit": None, "reprompt": None, "link": None}
elif len(opt_s) > 1:
if opt_s[1] == "":
opts[opt_s[0]] = {"limit": None}
else:
| try:
int(opt_s[1])
except ValueError:
await self.bot.reply(cf.error(
"A limit you provided was not a number."))
return "return"
opts[opt_s[0]] = {"limit": o... |
AlexStarov/Shop | applications/discount/migrations/0006_auto_20160517_2147.py | Python | apache-2.0 | 1,256 | 0.002389 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
import applications.discount.models
class Migration(migrations.Migration):
dependencies = [
('discount', '0005_auto_20160507_2145'),
]
operations = [
migrations.Alter... | model_name='action',
name='datetime_start',
field=models.DateTimeField(default=datetime.datetime.now, verbose_name='\u0414\u0430\u0442\u0430 \u043d\u0430\u0447\u0430\u043b\u0430 \u0430\u043a\u0446\u0438\u0438'),
),
migrations.AlterField(
model_name='a | ction',
name='name',
field=models.CharField(default=applications.discount.models.default_action_name, max_length=256, verbose_name='\u041d\u0430\u0438\u043c\u0435\u043d\u043e\u0432\u0430\u043d\u0438\u0435 \u0430\u043a\u0446\u0438\u0438'),
),
]
|
darthcloud/cube64-dx | notes/poll.py | Python | gpl-2.0 | 6,079 | 0.023195 | #!/usr/bin/env python3
#
# Script for polling N64/GC SI bus devices
#
# This script uses the serial bridge and pool in loops
# for the buttons status.
#
# It currently supports N64 controllers, N64 mouses & GameCube controllers.
#
# --Jacques Gagnon <darthcloud@gmail.com>
#
from bus import Bus
from collections import ... | stem):
if system == NUS:
reply = self.bridge.write(bytes([STATUS]), 4)[1]
return status_resp._make(struct.unpack('>H2b', reply))
elif system == DOL:
reply = self.bridge.write(struct.pack(">BH", DOL_STATUS, 0x0300), 8)[1]
return dol_status_resp._make(struct.unpack(... | pack(">BBB", WB_INIT, (id[0] | 0x20) & 0x10, id[1]), 3)[1]
def poll():
os.system('setterm -cursor off')
interface = Bus()
device = interface.identify()
time.sleep(0.02)
while device['system'] == WB_DOWN:
device = interface.identify()
time.sleep(1)
if device['system'] == WB_AUTH:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.