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
xrg/openerp-server
bin/service/web_services.py
Python
agpl-3.0
41,970
0.005742
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
.execute('UPDATE res_users SE
T password=%s, context_lang=%s, active=True WHERE login=%s', ( user_password, lang, 'admin')) cr.execute('SELECT login, password, name ' \ ' FROM res_users ' \ ' ORDER BY login') serv.actions[i...
chrisjsewell/ipypublish
ipypublish/sphinx/tests/conftest.py
Python
bsd-3-clause
2,432
0.000411
""" Uses sphinx's pytest fixture to run builds usage: .. code-block:: python from ipypublish.sphinx.tests import get_test_source_dir @pytest.mark.sphinx( buildername='html', srcdir=get_test_source_dir('notebook')) def test_basic(app, status, warning, get_sphinx_app_output): app....
uild() assert 'build succeeded' in status.getvalue() # Build succeeded warnings = warning.getvalue().strip() assert warnings == "" output = get_sphinx_app_output(app, buildername='html') parameters available to parse to ``@pytest.mark.
sphinx``: - buildername='html' - srcdir=None - testroot='root' (only used if srcdir not set) - freshenv=False - confoverrides=None - status=None - warning=None - tags=None - docutilsconf=None """ import os import shutil import re import pytest from sphinx.testing.path import path try: import pathlib except Impo...
MediaSapiens/wavesf
djangoappengine/boot.py
Python
bsd-3-clause
7,691
0.00091
import logging import os import sys PROJECT_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) # Overrides for os.environ env_ext = {'DJANGO_SETTINGS_MODULE': 'settings'} def setup_env(): """Configures app engine environment for command-line apps.""" # Try to import the appengine code from the...
continue path = os.path.expanduser(path) path = os.path.realpath(path) if os.path.exists(path): sdk_path = path break if sdk_path is None: # The SDK could not be found in any known location. sys.stderr.write(...
.\n") sys.exit(1) # Add the SDK and the libraries within it to the system path. extra_paths = [sdk_path] lib = os.path.join(sdk_path, 'lib') # Automatically add all packages in the SDK's lib folder: for dir in os.listdir(lib): path = os.path.join(lib, dir)...
MiroK/dolfin
test/unit/python/parameter/test_parameters.py
Python
gpl-3.0
4,019
0.002488
#!/usr/bin/env py.test """Unit tests for parameter library""" # Copyright (C) 2011 Anders Logg # # This file is part of DOLFIN. # # DOLFIN is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either versio...
assert p1["sub0"]["tolerance"] == 0.001 assert p1["sub0"]["monitor_convergence"] == True @skip_in_parallel def test_nested_read_existing(tempdir): """Test that we can read in a nested parameter database into an existing (and matching) parameter database""" file =
File(os.path.join(tempdir, "test_parameters.xml")) file << parameters p = Parameters("test") file >> p file >> p @skip_in_parallel def test_solver_parameters(): "Test that global parameters are propagated to solvers" # Record default values so we can change back absolute_tolerance = param...
nguyentran/openviber
tools/swtoolkit/site_scons/site_tools/atlmfc_vc80.py
Python
mit
2,627
0.004187
#!/usr/bin/python2.4 # Copyright 2009, Google 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 code must retain the abo
ve copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * N
either the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NO...
thisisshi/cloud-custodian
tools/c7n_mailer/c7n_mailer/azure_mailer/deploy.py
Python
apache-2.0
5,823
0.003091
# Copyright The Cloud Custodian Authors. # SPDX-License-Identifier: Apache-2.0 import copy import json import logging import os import jmespath from c7n_mailer.deploy import CORE_DEPS try: from c7n.mu import generate_requirements from c7n_azure.constants import AUTH_TYPE_EMBED from c7n_azure.function_pack...
me': rg_name}) app_insights = AzureFunctionMode.extract_properties(function_properties, 'appInsights', {'na
me': service_plan['name'], 'location': location, 'resource_group_name': rg_name}) function_app_name = FunctionAppUtilities.get_function_name( '-'.join([service_plan['name'], function_name]), suffix) ...
Erotemic/hotspotter
_graveyard/oldhotspotter/__init__.py
Python
apache-2.0
46
0.021739
__all__
= ['H
otSpotterAPI', 'Facade', 'tpl']
GeoDaCenter/CAST
stars/visualization/plots/SigTrendGraphLocalG.py
Python
gpl-3.0
28,985
0.015146
""" """ __author__ = "Xun Li <[email protected]> " __all__ = ['SigTrendGraphLocalG', 'SigTrendGraphLocalGQueryDialog','ShowSigTrendGraphLocalG'] import os import wx import numpy as np from scipy.spatial import cKDTree import pysal import stars from stars.visualization.maps.DynamicLisaMap import DynamicLISAQueryDialog f...
super(SigTrendGraphLocalG, self).DoDraw(dc) # draw y axis at ea
ch time interval dc.SetFont(wx.Font(self.font_size_y_axis,wx.NORMAL,wx.NORMAL,wx.NORMAL)) dc.SetPen(wx.Pen(wx.Color(200,200,200))) for i in range(self.x_min, self.x_max+1): if i == self.x_min or i == self.x_max: self.enable_axis_labels = True else: ...
avanzosc/avanzosc6.1
nan_stock_purchase_price/__openerp__.py
Python
agpl-3.0
486
0.063786
{ "name" : "Purchase Price on Input Material", "versi
on" : "0.1", "description" : """Include facilities to enter purchase price in pickings of incomming products.""", "author" : "NaN Projectes de Programari Lliure, S.L.", "website" : "http://www.NaN-tic.com", "depends" : [ 'stock', 'purchase_discount', ], "category" : "Cust
om Modules", "init_xml" : [], "demo_xml" : [], "update_xml" : [ 'product_view.xml','stock_view.xml' ], "active": False, "installable": True }
arthurprs/aerospike-client-python
test/test_scan.py
Python
apache-2.0
8,729
0.001833
# -*- coding: utf-8 -*- import pytest import sys from test_base_class import TestBaseClass aerospike = pytest.importorskip("aerospike") try: from aerospike.exception import * except: print "Please install aerospike python client." sys.exit(1) class TestScan(TestBaseClass): def setup_method(self, met...
pt ParamError as exception: assert exception.code == -2L assert exception.msg == "Callb
ack function contains an error" def test_scan_with_callback_returning_false(self): """ Invoke scan() with callback function returns false """ ns = 'test' st = 'demo' records = [] scan_obj = None def callback((key, meta, bins)): if l...
ikoz/mitmproxy
pathod/pathod.py
Python
mit
16,060
0.000747
import copy import logging import os import sys import threading import urllib from netlib import tcp, http, certutils, websockets from netlib.exceptions import HttpException, HttpReadDisconnect, TcpTimeout, TcpDisconnect, \ TlsException from . import version, app, language, utils, log, protocols import language....
elf.server.craftanchor )]) if anchor_gen: spec = anchor_gen.next() if self.use_http2 and isinstance(spec, language.http2.Response): spec.stream_id = req.stream_id lg("crafting spec: %s" % spec) nex...
lg ) if nexthandler and websocket_key: self.protocol = protocols.websockets.WebsocketsProtocol(self) return self.protocol.handle_websocket, retlog else: return nexthandler, retlog else: ...
LudumDareProject/CppGameEngine
build/bakefiles/bakefile_gen.py
Python
apache-2.0
4,899
0.047561
import os, configparser, sys, string, re from fnmatch import fnmatch def writeMakefile(type): config = Config('bakefile.ini') settings = ProjectSettings(config, type) bakefile = Bakefile(settings) bf = open('generated-bakefile.bkl', 'w', newline='') bf.write(bakefile.generateProgram(type)) bf.close() def runBa...
ir(self, path): self._libDir.append(path) def _writeBody(self, type): self._write(type + ' ' + self._settings.config.projectName) self._writeDependencies() self._write(' {\n') self._indent(1) self._writeIncludes() self._writeHeaders() self._writeSources() self._indent(-
1) self._write('\n}') return self._buffer def _format(self, s): ind = '' for i in range(0, self._indents): ind += '\t' newlines = [m.start() for m in re.finditer('\n', s)] if (not newlines): return ind + s for n in range(0, len(newlines)): s = s[:newlines[n]] + ind + s[newlines[n]:] ...
fiete201/qutebrowser
qutebrowser/misc/editor.py
Python
gpl-3.0
10,070
0
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2021 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser 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 S...
except OSError as e: # NOTE: Do not replace this with "raise CommandError" as it's # executed async. message.error("Failed to delete tempfile... ({})".format(e)) @pyqtSlot(int, QProcess.ExitStatus) def _on_proc_closed(self, _exitcode, exitstatus): """Write the edi...
""" if sip.isdeleted(self): # pragma: no cover log.procs.debug("Ignoring _on_proc_closed for deleted editor") return log.procs.debug("Editor closed") if exitstatus != QProcess.NormalExit: # No error/cleanup here, since we already handle this in ...
gajim/gajim
gajim/gtk/message_input.py
Python
gpl-3.0
10,223
0
# Copyright (C) 2003-2014 Yann Leboulanger <asterix AT lagaule.org> # Copyright (C) 2005-2007 Nikos Kouremenos <kourem AT gmail.com> # Copyright (C) 2006 Dimitur Kirov <dkirov AT gmail.com> # Copyright (C) 2008-2009 Julien Pivotto <roidelapluie AT gmail.com> # # This file is part of Gajim. # # Gajim is free software; y...
Pango from gajim.common import app from gajim.common.styling import process from gajim.common.styling import PlainBlock from .util import scroll_to_end if app.is_installed('GSPELL
'): from gi.repository import Gspell # pylint: disable=ungrouped-imports UNDO_LIMIT: int = 20 FORMAT_CHARS: dict[str, str] = { 'bold': '*', 'italic': '_', 'strike': '~', 'pre': '`', } class MessageInputTextView(Gtk.TextView): """ A Gtk.Textview for chat message input """ def __i...
BeeeOn/server
t/xmlui/t2007-parameter-create-update-delete.py
Python
bsd-3-clause
8,043
0.036802
#! /usr/bin/env python3 import config config.import_libs() import unittest from xmlui import Connector, Logout from xmlui import GatewayRegister, GatewayUnregister from xmlui import DeviceParameterGet from xmlui import DeviceParameterCreate, DeviceParameterUpdate, DeviceParameterDelete class TestCRUDeviceParameter(...
f.session )) self.assertTrue(response.is_ok()) response = self.c.request(Devic
eParameterGet( config.gateway_id, "0xa335d00019f5234e", "password", self.session )) self.assertTrue(response.is_data()) self.assertEqual("*****", response.root[0].get("parametervalue")) response = self.c.request(DeviceParameterDelete( config.gateway_id, "0xa335d00019f5234e", "password", ...
Labgoo/google-analytics-for-python
gap/tracker.py
Python
mit
2,493
0.001604
__author__ = 'minhtule' from request import * class Tracker(object): """ """ def __init__(self, tracking_id, visitor): self.__tracking_id = tracking_id self.__visitor = visitor self.__debug_enabled = False @property def tracking_id(self): return self.__tracking_...
tem_price, item_quantity=item_quantity, item_code=item_code, item_category=item_category, currency_code=currency_code ).send() class CustomVariable(object): @property def index(self): return self.__index @property def value(self): ...
ndex, value): self.__index = index self.__value = value
alazanman/py_epg_tests
utils/file_util.py
Python
apache-2.0
535
0.005607
# -*- coding: utf-8 -*- import os import base64 from
random import choice def random_file_from_dir(relative_path): random_file = choice(os.listdir(os.path.join(os.getcwd(), relativ
e_path))) return abs_path_to_file(os.path.join(relative_path, random_file)) def abs_path_to_file(relative_path): # print os.getcwd() return os.path.abspath(os.path.join(os.getcwd(), relative_path)) def encode_base64(abs_path): print "abs_path", abs_path with open(abs_path, 'rb') as f: retu...
yamt/neutron
quantum/plugins/cisco/l2device_plugin_base.py
Python
apache-2.0
5,260
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 Cisco Systems, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache...
"""Get subnet. :returns: :raises: """ pass def
update_subnet(self, tenant_id, net_id, subnet_id, **kwargs): """Update subnet. :returns: :raises: """ pass def delete_subnet(self, tenant_id, net_id, subnet_id, **kwargs): """Delete subnet. :returns: :raises: """ pass @classmeth...
yamstudio/Codeforces
000/1A - Theatre Square.py
Python
gpl-3.0
177
0.00565
from math import * inp = raw
_input() spl = inp.split() n = int(spl[0]) m =
int(spl[1]) a = int(spl[2]) i = int(ceil(n * 1.0 / a)) j = int(ceil(m * 1.0 / a)) print max(1, i * j)
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_runtime_features/os_system_example.py
Python
apache-2.0
45
0
import os # Simple command os.system('pw
d')
ebbkrdrcn/rexp
test/compiler.py
Python
apache-2.0
790
0.002532
import unittest, re from rexp.compiler import PatternCompiler class
CompilerTestMethods(unittest.TestCase): def test_compile_1(self): compiler = PatternCompiler(pattern_set=dict( TEST=r'\w+' )) try: c1 = compiler.compile('$1{TEST}') except Exception as exc: self.assertTrue(1) c1 = compiler.compile(
'$1{TEST}', ['test']) self.assertEqual(c1, r'(?:(?P<test>(\w+)))') def test_compile_2(self): compiler = PatternCompiler(pattern_set=dict( TEST=r'\w+' )) try: c1 = compiler.compile('$1{TEST}') except: self.assertTrue(1) c1 = compi...
JulienMcJay/eclock
windows/kivy/kivy/adapters/listadapter.py
Python
gpl-2.0
17,276
0.001679
''' ListAdapter ================= .. versionadded:: 1.5 .. warning:: This code is still experimental, and its API is subject to change in a future version. A :class:`ListAdapter` is an adapter around a python list. Selection operations are a main concern for the class. From an :class:`Adapter`, a :class:`...
be enforced. :attr:`selection_limit` is a :class:`~kivy.properties.NumericProperty` and defaults to -1 (no limit). ''' cached_views = DictProperty({}) '''View instances for data items are instantiated and managed by the adapter. Here we maintain a dictionary containing the view instances ...
the adapter if one is not already stored for the requested index. :attr:`cached_views` is a :class:`~kivy.properties.DictProperty` and defaults to {}. ''' __events__ = ('on_selection_change', ) def __init__(self, **kwargs): super(ListAdapter, self).__init__(**kwargs) self.bind(s...
elmadjian/mac0499
coletas/user_5_OK/detector.py
Python
mit
4,312
0.009511
#!/usr/bin/env python # -*- coding: utf-8 -*- #---------------------- #Criado por Cadu #---------------------- import re, sys, time, threading #Detector de leitura (Campbell, 2001) #------------------------------------ class Detector (threading.Thread): def __init__(self, thresh, cv): threading.Thread....
if self.ant_saccade: self.state += 5 else: self.state = 0 self.ant_saccade = False de
f analyze_y(self, prev_y, avg_y): y = prev_y - avg_y #short up: if -0.05 <= y < -0.015: self.state -= 5 #long and medium up: elif y < -0.05: self.state = 0 #short down: if 0.015 <= y < 0.05: self.ant_saccade = True #medi...
amal029/DataStructuresAndAlgorithmsInPython
Tree/binaryTree.py
Python
mit
6,263
0
class BinaryTree: """This is the binary tree ADT """ def __init__(self, root=None): self._root = root def element(self): return self.element def root(self): return self._root def setRoot(self, r): self._root = r def parent(self, v): if v == self....
rais
e RuntimeError('Node:', v, 'already has a left sub-tree') else: raise RuntimeError('Node:', v, 'not in the tree') def insertRight(self, v, e): vv = BinaryTree._getNode(self._tree.root(), v) if vv is not None: if vv.getRightSubTree() is None: # Add ...
csxeba/brainforge
brainforge/gradientcheck/raw_gradients.py
Python
gpl-3.0
1,211
0.000826
import numpy as np def analytical_gradients(network, X, Y): print("Calculating analytical gradients...") print("Forward pass:", end=" ") preds = network.predict(X) print("done! Backward pass:", end=" ") delta = network.cost.derivative(preds, Y) network.backpropagate(delta) print("done!") ...
return network.get_gradients(unfold=True) def numerical_gradients(network, X, Y, epsilon): ws = network.layers.get_weights(unfold=True) numgrads
= np.zeros_like(ws) perturb = np.zeros_like(ws) nparams = ws.size lstr = len(str(nparams)) print("Calculating numerical gradients...") for i in range(nparams): print("\r{0:>{1}} / {2}".format(i + 1, lstr, nparams), end=" ") perturb[i] += epsilon network.layers.set_weights(w...
CINPLA/expipe-dev
python-neo/neo/test/__init__.py
Python
gpl-3.0
137
0
# -*- coding: utf-8 -*- """ The subdirectory coretest contains tests for neo.core
The subdirectory iotest contains tests
for neo.io """
StephanDollberg/stephandollberg.github.io
transform.py
Python
apache-2.0
441
0.002268
#!/usr/bin/env python #transforms jekyll dir structure to directory servable structure import os import sys import shutil for root, subdirs, files in os.walk('.'): if len(subdirs) == 0 and len
(files) == 1 and files[0] == 'index.html': with open(root + '/' + files[0]) as f: data = f.read() shutil.rmtree(root) with open(root, 'w') as f: f.write(data)
print('replaced', root)
khs26/pele
playground/native_code/tests/__init__.py
Python
gpl-3.0
206
0
from _test_lbfgs_cpp import * from _test_lj_cpp import * from _test_lj_interaction_list import * from _test_frozen_atoms import * fro
m _test_bljcut import * if __name__ =
= "__main__": unittest.main()
qilicun/python
python2/PyMOTW-1.132/PyMOTW/smtpd/smtpd_debug.py
Python
gpl-3.0
255
0.003922
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id$" #end_pymotw_header import smtpd import asyncore server = smtpd.DebuggingServer(('127.0.0.1', 1
025), No
ne) asyncore.loop()
ptone/BirdFish
examples/pulse_duo.py
Python
bsd-3-clause
2,578
0.008146
import sys from birdfish.input.midi import MidiDispatcher from birdfish.lights import RGBLight, PulseChase, LightShow from birdfish.output.lumos_network import LumosNetwork from birdfish import tween # create a light show - manages the updating of all lights show = LightShow() # Create a network - in this case, uni...
r i in range(1,360,3): elementid += 1 l = RGBLight( start_channel=i, name="pulse_%s" % elementid, attack_duration=0, release_duration=0, sustain_val
ue=1, ) # l.hue = random.random() * 255 l.hue = .24 l.saturation = 1 l.update_rgb() # l.simple = True # add the light to the network dmx3.add_element(l) pp.elements.append(l) pp.start_pos = 12 # p.left_width = p.right_width = 10 pp.left_width = 15 pp.right_width = 15 pp.left_...
Tattiuss/python_training
test/test_add_group.py
Python
apache-2.0
1,283
0.006235
# -*- coding: utf-8 -*- from model.group import Group def test_add_group(app, db, json_groups, check_ui): group = json_groups old_groups = db.get_group_list() app.group.create(group) # assert len(old_groups) + 1 == app.group.count() new_groups = db.get_group_list() old_groups.append(group) as...
w_groups, key=Group.id_or_max) #def test_add_empty_group(app): # old_groups = app.group.get_group_list() # group = Group(name="", header="", footer="") # app.group.create(group) # new_groups = app.group.get_group_list() # assert len(old_groups) + 1 == len(new_groups) # old_
groups.append(group) # assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
stormi/tsunami
src/primaires/scripting/fonctions/memoires.py
Python
bsd-3-clause
5,094
0.000396
# -*-coding:Utf-8 -* # Copyright (c) 2014 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 n
otice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above 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 copyright ho...
mixdesign/radioice-track
workflow/workflow.py
Python
mit
75,352
0.000187
# encoding: utf-8 # # Copyright (c) 2014 Dean Jackson <[email protected]> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2014-02-15 # """ The :class:`Workflow` object is the main interface to this library. See :ref:`setup` in the :ref:`user-manual` for an example of how to set up your Pyth...
# 'ᴍ': '', # 'ᴎ': '', # 'ᴏ': '',
# 'ᴐ': '', # 'ᴑ': '', # 'ᴒ': '', # 'ᴓ': '', # 'ᴔ': '', # 'ᴕ': '', # 'ᴖ': '', # 'ᴗ': '', # 'ᴘ': '', # 'ᴙ': '', # 'ᴚ': '', # 'ᴛ': '', # 'ᴜ': '', # 'ᴝ': '', # 'ᴞ': '', # 'ᴟ': '', # 'ᴠ': '', # 'ᴡ': '', # 'ᴢ': '', # 'ᴣ': '', # 'ᴤ': '', # '...
Zorro666/renderdoc
docs/python_api/examples/renderdoc_intro.py
Python
mit
853
0.001172
import renderdoc as rd rd.InitialiseReplay(rd.GlobalEnvironment(), []) # Open a capture file handle cap = rd.OpenCaptureFile() # Open a particular file - see also Open
Buffer to load from memory status = cap.OpenFile('test.rdc', '', None) # Make sure the file
opened successfully if status != rd.ReplayStatus.Succeeded: raise RuntimeError("Couldn't open file: " + str(status)) # Make sure we can replay if not cap.LocalReplaySupport(): raise RuntimeError("Capture cannot be replayed") # Initialise the replay status,controller = cap.OpenCapture(rd.ReplayOptions(), None)...
FireClaw/HackerRank
Python/py-collections-namedtuple.py
Python
mit
382
0.002618
count, index = int(input()), input().split().index('MARKS') print('%.2f' % (sum([float(input().split()[index]) for _ in range(count)]) / count)) # from collections import namedtuple # count, Student = int(in
put()), namedtuple('Student', input()) # students = (Student(*input().split()) for _
in range(count)) # print('%.2f' % (sum(map(lambda s: float(s.MARKS), students)) / count))
npuichigo/voicenet
src/models/tf_model.py
Python
apache-2.0
13,402
0.001418
# Copyright 2016 ASLP@NPU. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
if self._rnn_cell == 'fused_lstm': output_sequence = tf.transpose(output_sequence, [1, 0, 2])
new_states = [] for cell in self._rnns: output_sequence, new_state = cell( inputs=output_sequence, sequence_length=input_length, dtype=tf.float32) new_states.append(new_state) ...
showerst/openstates
openstates/nc/__init__.py
Python
gpl-3.0
5,650
0.007965
import datetime import lxml.html from billy.utils.fulltext import text_after_line_numbers from .bills import NCBillScraper from .legislators import NCLegislatorScraper from .committees import NCCommitteeScraper from .votes import NCVoteScraper metadata = dict( name='North Carolina', abbreviation='nc', capi...
'display_name': '2016 Extra Session 1', '_scraped_name': '2016 Extra Session 1', }, '2015E2': {'type': '
special', 'display_name': '2016 Extra Session 2', '_scraped_name': '2016 Extra Session 2', }, '2015E3': {'type': 'special', 'display_name': '2016 Extra Session 3', '_scraped_name': '2016 Extra Session 3', }, ...
vgrem/Office365-REST-Python-Client
office365/directory/applications/public_client_application.py
Python
mit
110
0
from office365.runtime.client_val
ue import ClientValue class PublicClientApplication(ClientValue):
pass
janelia-flyem/neuroglancer
python/neuroglancer/google_credentials.py
Python
apache-2.0
3,476
0.002014
# @license # Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
elf._credentials.token) return run_on_new_thread(func) _global_google_application_default_credentials_provider = None _global_google_application_default_credentials_provider_lock = thre
ading.Lock() def get_google_application_default_credentials_provider(): global _global_google_application_default_credentials_provider with _global_google_application_default_credentials_provider_lock: if _global_google_application_default_credentials_provider is None: _global_google_appli...
akhilman/cement
examples/load_extensions_via_config/myapp.py
Python
bsd-3-clause
1,189
0.002523
from cement.core.foundation import CementApp class MyApp(CementApp): class Meta: label = 'myapp' config_files = [ './myapp.conf', ] def validate_config(self): if 'extensions' in self.config.keys('myapp'): exts = self.config.get('myapp', 'extensions...
type(exts) is list: ext_list = exts for ext in ext_list: # load the extension self.ext.load_extension(ext) # add to meta data self._meta.extensions.append(ext) def main(): app = MyApp() try: app.setup
() app.run() finally: app.close() if __name__ == '__main__': main()
geospatial-services-framework/gsfpyarc
gsfarc/test/test_datatype_stringarray.py
Python
mit
803
0.008717
""" """ import unittest import arcpy from gsfarc.test import config class TestDataTypeStringArray(unittest.TestCase): """Tests the string array task datatype""" @classmethod def setUpClass(cls): config.setup_idl_toolbox('test_datatype_stringarray','qa_idltaskengine_datatype_stringarray') @...
def test_datatype_stringarray_one_dimension(self): """Verify a one dimensional array of strings returns a semicolon separated string list.""" input = ['foo', 'bar', 'baz'] expect_dims = [len(input)] result = arcpy.QA_IDLTaskEngine_DataType_St
ringArray_GSF(input, expect_dims) self.assertEqual(result[0], ';'.join(str(i) for i in input)) if __name__ == '__main__': unittest.main()
jackTheRipper/iotrussia
web_server/src/server/server/wsgi.py
Python
gpl-2.0
1,419
0.000705
""" WSGI config for server project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` s...
GI middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites
in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon process, or use # os.environ["DJANGO_SETTINGS_MODULE"] = "server.settings" os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") # This application object is used by any WSGI server configured to use th...
ctogle/dilapidator
test/geometry/tform_tests.py
Python
mit
1,264
0.051424
from dilap.geometry.vec3 import vec3 from dilap.geometry.quat import quat from dilap.geometry.tform import tform import dilap.geometry.tools as dpr import matplotlib.pyplot as plt import unittest,numpy,math import pdb #python3 -m unittest discover -v ./ "*tests.py" class test_tform(unittest.TestCase): def s...
(self.tf1 == self.tf1.cp
()) self.assertFalse(self.tf1 is self.tf2) self.assertTrue(self.tf1 == self.tf2) def test_true(self): tf4 = self.tf1.true(self.tf2) self.assertEqual(self.tf4,tf4) if __name__ == '__main__': unittest.main()
jokajak/itweb
data/env/lib/python2.6/site-packages/ToscaWidgets-0.9.11-py2.6.egg/tw/core/command.py
Python
gpl-3.0
26,579
0.002257
import errno import re import operator import shutil import sys import os import tempfile import subprocess try: from hashlib import md5 as hash_constructor except ImportError: from md5 import new as hash_constructor import mimetypes try: from cStringIO import StringIO except ImportError: from ...
deploy = archive_tw_resources --force install This way you can run:: $ python setup.py deploy To install a new version of your app and copy/compress resources. """ descr
iption = "Copies ToscaWidgets static resources into a directory where"\ " a fast web-server can serve them." user_options = [ ("output=", "o", "Output directory. If it doesn't exist it will be created."), ("force", "f", "If output dir exists, it will be ovewritten"), ...
okfn/spendingstories
webapp/context_processors.py
Python
gpl-3.0
471
0.006369
from django.conf import settings def i18n(request):
from django.utils import translation def get_language_code(): base_code = translation.get_language() sub_codes = base_code.split('-') if len(sub_codes) > 1: sub_codes[1] = sub_codes[1].upper() return "_".join(sub_codes) else: return base_code ...
de() return context_extras
seckcoder/lang-learn
python/sklearn/sklearn/covariance/shrunk_covariance_.py
Python
unlicense
17,960
0.000445
""" Covariance estimators using shrinkage. Shrinkage corresponds to regularising `cov` using a convex combination: shrunk_cov = (1-shrinkage)*cov + shrinkage*structured_estimate. """ # Author: Alexandre Gramfort <[email protected]> # Gael Varoquaux <[email protected]> # Virgile ...
entity(n_features) where mu = trace(cov) / n_features """ emp_cov = array2d(emp_c
ov) n_features = emp_cov.shape[0] mu = np.trace(emp_cov) / n_features shrunk_cov = (1. - shrinkage) * emp_cov shrunk_cov.flat[::n_features + 1] += shrinkage * mu return shrunk_cov class ShrunkCovariance(EmpiricalCovariance): """Covariance estimator with shrinkage Parameters --------...
aevum/moonstone
src/moonstone/ilsa/plugins/measure/gui/qt/widget/rulerproperties_ui.py
Python
lgpl-3.0
6,860
0.003061
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/home/igor/Desenvolvimento/neppo/moonstone/src/moonstone/ilsa/plugins/measure/resources/ui/qt/rulerproperties.ui' # # Created: Fri Feb 21 10:22:36 2014 # by: pyside-uic 0.2.14 running on PySide 1.1.2 # # WARNING! All changes made in thi...
tCore, QtGui class Ui_RulerProperties(object): def setupUi(self, RulerProperties): RulerProperties.setObjectName("RulerProperties") RulerProperties.resize(212, 284) RulerProperties.setMinimumSize(QtCore.QSize(0, 0)) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/static...
rticalLayout = QtGui.QVBoxLayout(RulerProperties) self.verticalLayout.setObjectName("verticalLayout") self.widget = QtGui.QWidget(RulerProperties) self.widget.setMinimumSize(QtCore.QSize(0, 0)) self.widget.setObjectName("widget") self.gridLayout_4 = QtGui.QGridLayout(self.widget)...
KelvinLu/octo-marklog
marklog/marklog_ext/__init__.py
Python
agpl-3.0
39
0
from extension import M
arklogExte
nsion
Johnetordoff/osf.io
addons/wiki/migrations/0011_auto_20180415_1649.py
Python
apache-2.0
590
0
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-04-
15 21:49 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('addons_wiki', '0010_migrate_node_wiki_pages'), ] operations = [ migrations.RemoveField( model_name='nodewikipage', name='no...
), migrations.DeleteModel( name='NodeWikiPage', ), ]
pspacek/freeipa
ipatests/test_ipaserver/test_otptoken_import.py
Python
gpl-3.0
5,751
0.001043
# Authors: # Nathaniel McCallum <[email protected]> # # Copyright (C) 2014 Red Hat # see file 'COPYING' for use and warranty information # # 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, ...
hm': u'sha1', 'ipatokenvendor': u'iana.dummy', 'description': u'FriendlyName', 'ipatokentotptimestep': 200, 'ipatokenhotpcounter': 0, 'ipatokenmodel': u'Model', 'ipatokenotpdigits': 8,
'type': u'hotp', })] finally: nss.nss_shutdown()
dcorbacho/libcloud
docs/examples/compute/openstack/force_base_url.py
Python
apache-2.0
680
0
from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver import libcloud.security # This assumes you don't have SSL set up. # Note: Code
like this poses a security risk (MITM attack) and # that's the reason why you should never us
e it for anything else # besides testing. You have been warned. libcloud.security.VERIFY_SSL_CERT = False OpenStack = get_driver(Provider.OPENSTACK) driver = OpenStack('your_auth_username', 'your_auth_password', ex_force_auth_url='http://192.168.1.101:5000', ex_force_auth_version=...
dan4ik95dv/housemanagement
tsj/admin.py
Python
mit
317
0
from django.contrib import admin from tsj.models import * admi
n.site.register(Company) admin.site.register(Resident) admin.site.register(House) admin.site.register(ServiceCom
pany) admin.site.register(MeterType) admin.site.register(MeterReadingHistory) admin.site.register(Employer) admin.site.register(Notification)
ff0000/red-fab-deploy
fab_deploy/joyent/postgres.py
Python
mit
5,514
0.004534
import os import sys import tempfile from fabric.api import run, sudo, env, local, hide, settings from fabric.contrib.files import append, sed, exists, contains from fabric.context_managers import prefix from fabric.operations import get, put from fabric.context_managers import cd from fabric.tasks import Task from ...
_username(self, section=None): try: names = env.config_object.get_list(section, env.config_object.USERNAME) u
sername = names[0] except: print ('You must first set up a database server on this machine, ' 'and create a database user') raise return username def run(self, section=None): """ """ sudo('mkdir -p /opt/pkg/bin') sudo("ln -...
denfromufa/mipt-course
demos/python/2_variables_and_types.py
Python
bsd-3-clause
694
0
#!/usr/bin/python # Code is executed top-to-bottom on load. # Variables are defined at the first assignment a =
2 # defines `a` b = 2 # 'print' operator, simple form: just prints out human-readable representation # of the argument. NOTE: no \n! print a + b # Types in Python are dynamic! v = 42 # `v` is an integer print v v = 0.42 # now it's a float print v v = 2**76 # NEW: Loooong integers are supported! print v v = 4 + 0....
wo") # non-optimal equivalent: print str(42) + " " + str(4.2) + " forty two"
dmlc/tvm
tests/python/contrib/test_ethosu/cascader/test_ethosu_part_performance.py
Python
apache-2.0
6,531
0.001837
# 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...
u55-32", (2, 1, 6, 3, 3)), ], ) def test_device_config_cycles(acc_config, expected): device
_config = cs.EthosuDeviceConfig(acc_config) conv_type = "ethosu_conv2d" conv_str = None conv_ifm_dtype = "int8" conv_ofm_dtype = "int8" conv_activation = "LUT" conv_cycles = device_config._get_output_cycles( conv_type, conv_str, conv_ifm_dtype, conv_ofm_dtype, conv_activation ) ...
mbedmicro/pyOCD
pyocd/target/builtin/target_lpc800.py
Python
apache-2.0
4,050
0.008395
# pyOCD debugger # Copyright (c) 2006-2013 Arm Limited # SPDX-License-Identifier: Apache-2.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...
0x68004448, 0x462860e8, 0x696847b0, 0xd00028
00, 0xbdf82001, 0x4614b5f8, 0xd11e0006, 0x0180200b, 0x6bc11820, 0x42814823, 0x4823d038, 0xd0354281, 0x42814822, 0x4822d032, 0xd02f4281, 0x68206861, 0x184068e2, 0x188968a1, 0x69211840, 0x69611840, 0x69a11840, 0x42401840, 0x4d1461e0, 0x444d0ab0, ...
SuperTux/flexlay
flexlay/color.py
Python
gpl-3.0
2,408
0.000831
# Flexlay - A Generic 2D Game Editor # Copyright (C) 2014 Ingo Ruhnke <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General
Public License as
published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GN...
EVEprosper/ProsperDatareader
prosper/datareader/__init__.py
Python
mit
72
0
import prosper.datare
ader.exceptions import prosper.datare
ader._version
joshwatson/binaryninja-api
python/examples/cli_lift.py
Python
mit
2,801
0.017494
#!/usr/bin/env python # # command-line BinaryNinja lifter # # BinaryNinja multiplatform version of Z0MBIE's PE_STAT for opcode frequency # statistics http://z0mbie.dreamhosters.com/opcodes.html # # Copyright (c) 2020-2021 Vector 35 Inc # # Permission is hereby granted, free of charge, to any person obtaining a copy # o...
SOFTWARE. import sys import binaryninja from binaryninja import core from binaryninja import binaryview from binaryninja import lowlevelil RED = '\x1B[31m' NORMAL = '\x1B[0m' def traverse_IL(il, indent): if isinstance(il, lowlevelil.LowLevelILInstruction): print('\t'*indent + il.operation.name) for o in il.ope...
il)) if __name__ == '__main__': if not sys.argv[2:]: print('usage: %s <platform> <bytes>' % sys.argv[0]) print('') print('examples:') print(' eg: %s linux-armv7 14 d0 4d e2 01 20 a0 e1 00 30 a0 e1 00 c0 a0 e3' % sys.argv[0]) print('') print('platforms:') print('\t' + '\n\t'.join(map(str, list(binaryn...
googleapis/python-spanner
google/cloud/spanner_admin_database_v1/services/database_admin/__init__.py
Python
apache-2.0
765
0
# -*- 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...
NS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from .client import DatabaseAdminClient from .async_client import Data
baseAdminAsyncClient __all__ = ( "DatabaseAdminClient", "DatabaseAdminAsyncClient", )
ChyauAng/DNN-Composer
src/Preprocess/globalConstant.py
Python
mit
1,770
0.003955
#global declaration global index0 global index1 global index2 global index3 global index4 global index5 global index6 global index7 global index8 global index9 global index10 global index11 global index12 global index13 global index14 global index15 global index16 global index17 global index18 globa...
rat
ionBase = 1.0 pitch_train = [] pitch_test = [] duration_train = [] duration_test = []
Horta/limix
limix/qc/test/test_qc.py
Python
apache-2.0
922
0.001085
from __future__ import division from dask.array import from_array from numpy.random import RandomState from numpy.testing import assert_allclose, assert_equal from limix.qc import compute_maf, indep_pairwise def test_qc_indep_p
airwise(): random = RandomState(0) X = random.randn(3,
100) head = [True, True, False, True, False] tail = [True, True, False, False] assert_equal(indep_pairwise(X, 4, 2, 0.5, verbose=False)[:5], head) assert_equal(indep_pairwise(X, 4, 2, 0.5, verbose=False)[-4:], tail) X = from_array(X, chunks=(2, 10)) assert_equal(indep_pairwise(X, 4, 2, 0.5, v...
twonds/healthmonger
healthmonger/log.py
Python
mit
1,181
0
"""Simple log functions """ import sys import traceback import config def debug(msg):
"""Display messages to stderr only when L{config.debug} is True @param msg: The message to write to stderr. It can be anything that can be turned into a string.
""" if config.debug: error(msg) def error(msg): """Write a message to stderr @param msg: The message to write to stderr. It can be anything that can be turned into a string. """ sys.stderr.write(str(msg)) sys.stderr.write("\n") def info(msg): """Write a message t...
KFPA/ScrapyNews
IPProxyPool-master/test/testsql.py
Python
apache-2.0
339
0.006042
# coding:utf-
8 from db.SqlHelper import SqlHelper from util.exception import Con_DB_Fail try: sqlhelper = SqlHelper()
sqlhelper.init_db() except Exception: raise Con_DB_Fail proxy = {'ip': '192.168.1.1', 'port': int('80'), 'type': 0, 'protocol': 0, 'country': u'中国', 'area': u'四川', 'speed': 0} sqlhelper.insert(proxy)
Xicnet/burnstation
decoder.py
Python
gpl-3.0
3,770
0.010875
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from ErrorsHandler import * from string import strip, find, split, lower, rjust, atoi, atof, replace, digits, zfill, join from tools import cleanlist, which, filecopy, mkdirtree, touch, listmatch, rm, escapedfilename from too
ls import get
_username, get_tempdir, cmdexec import os, os.path import mp3info, ogg.vorbis logfile = 'decoder.log' logger.InitAll(logfile, '') sys.stdout.save = False class Decoder: def __init__(self): """ Converts mp3/ogg-files to wav-files. """ #logger.debug2("Decoder class instantiated") pass ...
whitehorse-io/encarnia
pyenv/lib/python2.7/site-packages/PIL/PSDraw.py
Python
mit
6,841
0.000146
# # The Python Imaging Library # $Id$ # # simple postscript graphics interface # # History: # 1996-04-20 fl Created # 1999-01-10 fl Added gsave/grestore to image method # 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge) # # Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved. # ...
"" # default resolution depends on mode if not dpi: if im.mode == "1": dpi = 200 # fax else: dpi = 100 # greyscale
# image size (on paper) x = float(im.size[0] * 72) / dpi y = float(im.size[1] * 72) / dpi # max allowed size xmax = float(box[2] - box[0]) ymax = float(box[3] - box[1]) if x > xmax: y = y * xmax / x x = xmax if y > ymax: x = ...
PyThaiNLP/pythainlp
pythainlp/tag/__init__.py
Python
apache-2.0
573
0
# -*- coding: utf-8 -*- """ Linguistic and other taggers. Tagging each token in a sentence with supplementary information, such as its part-of-speech (POS) tag, and named entity (NE) tag. """ __all__ = [ "PerceptronTagger", "pos_tag", "pos_tag_sents", "tag_provinces", "chunk_parse", "NER", ] ...
hainlp.tag._tag_perceptron import PerceptronTagger from pythainlp.tag.chunk import chunk_parse from pythainlp.tag.named_entity import N
ER
zsulocal/pycoin
pycoin/message/make_parser_and_packer.py
Python
mit
8,636
0.0022
import io import struct from pycoin.encoding import double_sha256 from pycoin.serialize import b2h_rev, bitcoin_streamer from .InvItem import InvItem from .PeerAddress import PeerAddress # definitions of message structures and types # L: 4 byte long integer # Q: 8 byte long integer # S: unicode string encoded using ...
rse( level_wid
ths, level_index+1, node_index*2, hashes, flags, flag_index, tx_acc) # is there a right? if node_index*2+1 < level_widths[level_index+1]: right_hash, flag_index = _recurse( level_widths, level_index+1, node_index*2+1, hashes, flags, flag_index, tx_acc) if left_hash == right_hash: ...
lehmannro/pootle
local_apps/pootle_app/urls.py
Python
gpl-2.0
1,109
0.003607
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008 Zuza Software Foundation # # This file is part of translate.
# # trans
late 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. # # translate is distributed in the hope that it will be useful, # but WITHOUT AN...
undergroundtheater/gameheart
gameheart/urls.py
Python
mit
12,257
0.011096
# gameheart.urls from django.conf.urls import patterns, include, url from django.views.generic import RedirectView from django.contrib import admin #from paypay.standard.ipn import urls from gameheart.entities import views from gameheart.entities import forms admin.autodiscover() urlpatterns = patterns('', # Exa...
ws.UserResetView, name='UserReset'), url(r'^account/detail/', views.UserAccountView, name='Account'), url(r'^account/password/', views.UserPasswordView, name='UserPassword
'), # PORTAL url(r'^portal/', views.Portal, name='Portal'), url(r'^account/favorites/index/', views.UserFavoriteView, name='UserFavorites'), ### ##Create Views## ### # Chapter Type url(r'^types/chapters/new/', views.FlexFormCreateView, kwargs=dict(nform=forms.ChapterTypeForm), name='ChapterTypeCre...
lavjain/incubator-hawq
tools/bin/pythonSrc/pychecker-0.8.18/test_input/test96.py
Python
apache-2.0
387
0.020672
'''test using string.find() in if s
tatement as a boolean. it returns an int''' class X: '''check string.find() usage''' def foo(self): s = 'abc' if s.find('ab'): print 'this is a bug' if not s.find('ab'): print 'this is also a bug' if s.find('ab'
) >= 0: print 'this is not a bug' if s.find('ab') < 0: print 'this also is not a bug'
ENCODE-DCC/snovault
src/snovault/schema_graph.py
Python
mit
3,775
0.001854
import logging from subprocess import ( Popen, PIPE, call as subprocess_call ) from collections import defaultdict from past.builtins import basestring from pyramid.response import Response from pyramid.view import view_config from xml.sax.saxutils import quoteattr, escape from snovault import TYPES log ...
set=
'utf-8') @view_config(route_name='graph_svg', request_method='GET') def schema_svg(request): try: return_code = subprocess_call(['which', 'dot']) if return_code == 0: dot = digraph(request.registry[TYPES].by_item_type, request.params.getall('exclude')) p = Popen(['dot', '-T...
silverbulleters/vanessa-behavoir
tools/Sikuli/FeatureLoadMany.sikuli/FeatureLoadMany.py
Python
apache-2.0
77
0.012987
cli
ck("Sarnvzsm.png") sleep(1.5) hover("iarpvambqmai.png") sleep(1.5) ex
it(0)
SPlanzer/AIMS
ElectoralAddress/Upload.py
Python
bsd-3-clause
4,556
0.016023
from getpass import getuser from Job import Job from datetime import datetime import os.path import time import re import Database class Upload( object ): @classmethod def CreateUpload( cls, filename=None ): if not filename: filename = Upload.defaultNewFilename() ...
execute('select upl_id, created_by, creation_time, filename, n_insert, n_delete from elc_GetUploadDetails(NULL)'): created_date = r[2].strftime('%d-%b-%Y')
uploads.append(dict( upl_id=r[0], created_by=r[1], creation_time=r[2], created_date=created_date, filename=r[3], n_insert=r[4], n_delete=r[5] )) return uploads ...
DenL/pogom-webhook
pogom/pgoapi/protos/POGOProtos/Inventory/AppliedItem_pb2.py
Python
mit
3,946
0.007603
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: POGOProtos/Inventory/AppliedItem.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf im...
_APPLIEDITEM.fields_by_name['item_id'].enum_type = POGOProtos_dot_Inventory_dot_Item_dot_ItemId__pb2._ITEMID _APPLIEDITEM.fields_by_name['item_type'].enum_type = POGOProtos_dot_Inventory_d
ot_Item_dot_ItemType__pb2._ITEMTYPE DESCRIPTOR.message_types_by_name['AppliedItem'] = _APPLIEDITEM AppliedItem = _reflection.GeneratedProtocolMessageType('AppliedItem', (_message.Message,), dict( DESCRIPTOR = _APPLIEDITEM, __module__ = 'POGOProtos.Inventory.AppliedItem_pb2' # @@protoc_insertion_point(class_scope...
wuhaochen/multinet
multinet/tests/test_classes.py
Python
mit
11,570
0.001642
""" Test the Multinet Class. """ import multinet as mn import networkx as nx class TestMultinet(object): def test_build_multinet(self): """ Test building Multinet objects. """ mg = mn.Multinet() assert mg.is_directed() == False mg.add_edge(0, 1, 'L1') mg...
d]['L1'] == 15 mg.aggregate_edge(2, 3, 'L2', weight=7) assert mg[2][3][mg.cid]['L2'] == 7 def test_sub_layer(self): mg = mn.DiMultinet() mg.add_edge(0, 1, 'L1', weight=5) mg.add_edge(1, 2, 'L2', weight=6) sg = mg.sub_layer('L1')
assert type(sg) == nx.DiGraph assert sg.number_of_nodes() == 3 assert sg.number_of_edges() == 1 sg = mg.sub_layer('L2', remove_isolates=True) assert type(sg) == nx.DiGraph assert sg.number_of_nodes() == 2 assert sg.number_of_edges() == 1 def test_sub_layers(sel...
hhauer/myinfo
CustomUser/admin.py
Python
mit
1,737
0.003454
from django import forms from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin from CustomUser.models import PSUCustomUser # Register your models here. class UserChangeForm(forms.ModelForm): class Meta: model = PSUCustomUser f...
username', 'is_active')}), ('Permissions', {'fields': ('is_admin',)}), ) search_fields = ('username',) ordering = ('username',) filter_horizontal = () # Now register the new UserAdmin... admin.site.register(PSUCustomUser, MyUserAdmin) # ... and, since we're not using Django's built-in permissi...
model from admin. admin.site.unregister(Group)
Quva/sparkplug
sparkplug/helpers/helpers.py
Python
apache-2.0
339
0.020649
import sy
s def dictContains(D, key): if sys.version_info[0] == 2: return D.has_key(key) elif sys.version_info[0] == 3: return key in D else: raise Exception("No support for self.__dictContains for python major " +
"version: {}".format(sys.version_info[0]))
jtoppins/beaker
LabController/src/bkr/labcontroller/provision.py
Python
gpl-2.0
14,901
0.003624
# 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 sys import os, os.path import errno import logging import time ...
get('fqdn') last_command_finished_at = self.last_command_datetime.get(system_fqdn) if last_command_fin
ished_at: # Get the difference between the time now and the number of # seconds until we can run another command seconds_to_wait = total_seconds((last_command_finished_at + datetime.timedelta(seconds=quiescent_period)) - dateti...
dilworm/pytest
base/client.py
Python
gpl-2.0
3,292
0.027992
# -*- coding=utf8 -*- import os, sys import select, threading, Queue import configparser as cf from mysocket import MySocket g_messageQueues = {} #每个scoket分配一个队列用于读写 g_messageQueues['main'] = Queue.Queue() #主队列用于接收服务器的返回消息 svrSockets = [] #MySocket 列表,对应每一个服务器 class MsgItem: def __init__(self, msgType, socket, da...
len(serverList), u'个服务器地址:' for addr in serverList: print addr print '' for addr in serverList: try: s = MySocket() s.connect(addr[0], addr[1]) svrSockets.append(s) except: print u'Error: 连接', addr, u'失败' # print 'golbal queue:', g_messageQueues # print 'gl
obal socket list size', len(svrSockets) # print 'svrsocklist ', svrSockets network_thread = threading.Thread(target = networkThreadHandler, args = (g_messageQueues, svrSockets)) userInput_thread = threading.Thread(target = userInputThreadHandler, args =(g_messageQueues, svrSockets)) network_thread.start() user...
jcberquist/sublimetext-cfml
src/component_parser/regex.py
Python
mit
2,805
0.000713
import re from collections import namedtuple component = r""" (?:/\*\*((?:\*(?!/)|[^*])*)\*/\s+)? ( (?:<cf)? component\b ) ([^>{]*) """ component = re.compile(component, re.I | re.X | re.S) Component = namedtuple('Component', 'script docblock attributes') script_function = r""" (?:/\*\*((?:\*(?!/)|[^*])*)\*...
docblock = r""" \n\s*(?:\*\s*)?(?:@(\w+)(?:\.(\w+))?)?\s*(\S.*) """ docblock = re.compile(docblock, re.I | re.X) Docblock = namedtuple('Dockblock', 'key subkey value') strings = r""" "[^"]*"|'[^']*' """ strings = re.compile(strings, re.X) function_attributes = r""" \)([^)]*)$ """ function_attributes = re.compile(f...
X | re.I | re.S) function_start_tag = r""" <cffunction([^>]*)> """ function_start_tag = re.compile(function_start_tag, re.X | re.I) function_end_tag = r""" </cffunction> """ function_end_tag = re.compile(function_end_tag, re.X | re.I) argument_tag = r""" <cfargument([^>]*)> """ argument_tag = re.compile(argument_tag...
atmark-techno/atmark-dist
user/python/Lib/encodings/cp866.py
Python
gpl-2.0
7,002
0.040703
""" Python Character Mapping Codec generated from 'CP866.TXT'. Written by Marc-Andre Lemburg ([email protected]). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(in...
): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = { 0x0080: 0x0410, # CYRILLIC CAPITAL LETTER A 0x0081: 0x0411, # CYRILLIC CAPITAL LETTER BE 0x0082: 0x0412, # CYRILLIC CAPITAL LETTER VE 0x0083: 0x0413, # CYRILLIC CAPITAL LETTER GHE 0x0084: 0x0414, # CYRILLI...
L LETTER IE 0x0086: 0x0416, # CYRILLIC CAPITAL LETTER ZHE 0x0087: 0x0417, # CYRILLIC CAPITAL LETTER ZE 0x0088: 0x0418, # CYRILLIC CAPITAL LETTER I 0x0089: 0x0419, # CYRILLIC CAPITAL LETTER SHORT I 0x008a: 0x041a, # CYRILLIC CAPITAL LETTER KA 0x008b: 0x041b, # CYRILLIC CAPITAL LETTER EL 0x008c: 0x041c, # CYRILLIC...
sven-hm/pythonocc-generator
src/Modules.py
Python
gpl-3.0
30,110
0.001627
##Copyright 2008-2015 Thomas Paviot ([email protected]) # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program...
### ### TKernel ('Dico', [], []), ('FSD', [], ['*']), ('MMgt', [], []), ('Message', [], ['Message_Msg']), ('NCollection', [], ['*']), ('OSD', [], ['*']), ('Plugin', [], ['*']), ('Quantity', [], []), ('Resourc...
('Standard', [], ['Standard_AncestorIterator', 'Standard_Persistent', 'Standard_Static_Assert', 'Standard_CLocaleSentry', 'Standard_Failure'], {'Standard_MMgrOpt': 'SetCallBackFunction', 'Standard': 'Free'...
sysbot/cloudenvy
cloudenvy/commands/dotfiles.py
Python
apache-2.0
1,933
0
import logging import tarfile import tempfile import os import fabric.api import fabric.operations import cloudenvy.envy class Dotfiles(cloudenvy.envy.Command): def _build_subparser(self, subparsers): help_str = 'Upload dotfiles from your local machine to an Envy.' subparser = subparsers.add_pa...
else: dotfiles = config['defaults']['dotfiles'].split(',') dotfiles = [dotfile.strip() for dotfile in dotfiles] with tarfile.open(temp_tar.n
ame, 'w') as archive: for dotfile in dotfiles: path = os.path.expanduser('~/%s' % dotfile) if os.path.exists(path): if not os.path.islink(path): archive.add(path, arcname=dotfile) ...
Cahersan/SexySignOn
multilogger/multilogger/api/utils.py
Python
bsd-3-clause
622
0.003215
from datetime import datetime from redis import Redis from redis_sessions.session import SessionStore from multilogger.users.models import User def get_logged_users(): # Query all non-expired sessions redconn = Redis() store = SessionStore() s
essions = [redconn.get(key) for key in
redconn.keys()] uid_list = [] # Build a list of user ids from that query for session_data in sessions: data = store.decode(session_data) uid_list.append(data.get('_auth_user_id', None)) # Query all logged in users based on id list return User.objects.filter(id__in=uid_list)
jyejare/robottelo
tests/foreman/ui/test_hostcollection.py
Python
gpl-3.0
28,395
0.001585
"""Test class for Host Collection UI :Requirement: Hostcollection :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: HostCollections :Assignee: swadeley :TestType: Functional :CaseImportance: High :Upstream: No """ import time import pytest from broker import VMBroker from nailgun import entitie...
.search(query={'search': f'name={settings.server.hostname}'})[0] .read() ) smart_proxy.location.append(entities.Location(id=module_loc.id)) smart_proxy.update(['location']) yield clients @pytest.fixture def vm_host_collection(module_org, vm_content_hosts): host_ids = [ ...
ion(host=host_ids, organization=module_org).create() return host_collection @pytest.fixture def vm_host_collection_module_stream(module_org, vm_content_hosts_module_stream): host_ids = [ entities.Host().search(query={'search': f'name={host.hostname}'})[0].id for host in vm_content_hosts_module...
alimony/django
django/db/backends/oracle/base.py
Python
bsd-3-clause
23,451
0.001109
""" Oracle database backend for Django. Requires cx_Oracle: http://cx-oracle.sourceforge.net/ """ import datetime import decimal import os import platform from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import utils from django.db.backends.base.base import BaseD...
# NOQA isort:skip from .utils import Oracle_datetime # NOQA isort:skip class _UninitializedOperatorsDescriptor: def __get__(self, instance, cls=None): # If connection.operators is looked up before a connection has been # created, transparently initialize connecti...
watson-developer-cloud/discovery-starter-kit
notebooks/scripts/upload_training_data.py
Python
mit
3,238
0.000309
import json import os import glob import sys import logging from watson_developer_cloud import WatsonException if '__file__' in globals(): sys.path.insert(0, os.path.join(os.path.abspath(__file__), 'scripts')) else: sys.path.insert(0, os.path.join(os.path.abspath(os.getcwd()), 'scripts')) from discovery_setup...
xception) def upload_training_data(training_directory): print("Training directory: %s" % training_directory) files = glob.glob(os.path.join(training_directory, '*.json')) total_files = len(files) print("Number of files to process: %d" % total_files) training_data_uploaded = 0 done_percent = 0...
e, 'rb') as file_object: logging.info("Processing file: %s", file_object.name) upload_training_doc( json.loads(file_object.read()), discovery_constants['environment_id'], discovery_constants['collection_id']['trained'] ) training_...
martin-ejdestig/sork
sork/tests/test_case_with_tmp_dir.py
Python
gpl-3.0
3,027
0.000661
# This file is part of Sork. # # Copyright (C) 2017-2019 Martin Ejdestig <[email protected]> # # Sork 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 ...
mp_file(self.comp_db_path(build_path), content) def create_tmp_build_dir(self, build_path: str, comp_db: Optional[List[Dict[str, Any]]] = None) -> None: se
lf.create_tmp_comp_db(build_path, comp_db or '[]') @contextlib.contextmanager def cd_tmp_dir(self, sub_dir: Optional[str] = None) -> Iterator[None]: orig_work_dir = os.getcwd() os.chdir(self.tmp_path(sub_dir) if sub_dir else self.tmp_dir.name) try: yield finally: ...
danielstp/gestionAgua
aguaEmbotellada/clientes/models.py
Python
gpl-3.0
842
0.010689
from django.db import models class Cliente(models.Model): nombre = models.CharField(max_length=200) apellidos = models.CharField(max_length=200) primerServicio = models.DateField('fecha primer Servicio') class Venta(models.Model): CONTADO = 'CONTADO' CREDITO = '
CREDITO' OPCIONES_VENTA = ((CONTADO,'Contado'),(CREDITO,'Credito')) cliente = models.ForeignKey(Cliente) Fecha = models.DateField('fecha venta') contado = models.CharField(max_length=20, choices=OPCIONES_VENTA, d...
mal_places=2) cantidad = models.PositiveSmallIntegerField() class Cobro(models.Model): Cliente = models.ForeignKey(Cliente)
miltonruelas/cursotecnico
branch/pos_report/__init__.py
Python
agpl-3.0
1,405
0.000712
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (c) 2013 Cubic ERP - Teradata SAC. (http://cubicerp.com). # # WARNING: This program as such is intended to be used by professional # programmers who take t...
; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - ...
######################################################### import point_of_sale
napjon/moocs_solution
ml-udacity/feature_selection/poi_flag_email.py
Python
mit
1,941
0.015456
#!/usr/bin/python ### ### in poiFlagEmail() below, write code that returns a boolean ### indicating if a given emails is from a POI ### import sys import reader import poi_emails def getToFromStrings(f): f.seek(0) to_string, from_string, cc_string = reader.getAddresses(f) to_emails =
reader.parseAddresses( to_string ) from_emails = reader.parseAddresses( from_string ) cc_emails = reader.parseAddresses( cc_string ) return to_emails, from_e
mails, cc_emails ### POI flag an email def poiFlagEmail(f): """ given an email file f, return a trio of booleans for whether that email is to, from, or cc'ing a poi """ to_emails, from_emails, cc_emails = getToFromStrings(f) ### list of email addresses of all the POIs poi_email_list...
futureneer/simple_ur
simple_ur_driver/src/simple_ur_driver/ur_driver_study.py
Python
bsd-2-clause
19,251
0.005506
#!/usr/bin/env python # ROS IMPORTS import roslib; roslib.load_manifest('simple_ur_driver') import rospy import tf; import tf_conversions as tf_c import PyKDL # MSGS and SERVICES from simple_ur_msgs.srv import * from sensor_msgs.msg import JointState from geometry_msgs.msg import PoseStamped from predicator_msgs.msg im...
while (True): if (Socket_Closed == True): # Keep Checking socket to see if opening it failed r = socket_open("192.168.1.5", 30000) if r == True: global Socket_Closed = False else: textmsg("Socket Failed to Open") end end data = socket_read_asc
ii_float(6) if data[0] == 1: textmsg("Got Command") if data[1] == MSG_QUIT: textmsg("Recieved Quit Command ... DONE") break elif data[1] == MSG_TEST: textmsg("Recieved Test Message") end elif data[0] == 6: set_pid_setpoint(data) # else: # textmsg(...
rockwyc992/monkey-pdns
monkey_pdns/app/models.py
Python
mit
1,285
0.018677
from django.db import models from django.contrib.auth.models import User class Zone(models.Model): name
= models.CharField(max_length = 64) created = models.DateTimeField(auto_now_add = True) def __str__(self): return self.name class Sub_Zone(models.Model)
: owner = models.ForeignKey(User) prefix = models.CharField(max_length = 32) super_zone = models.ForeignKey(Zone) created = models.DateTimeField(auto_now_add = True) def __str__(self): if self.prefix == '@': return str(self.super_zone) return self.prefix + '.' + str(self...
SB-Technology-Holdings-International/WateringWebClient
regen.py
Python
bsd-3-clause
5,942
0.001178
#!/usr/bin/python -u # coding=utf-8 """ Generate certificates via Let's Encrypt """ import re from subprocess import check_output, check_call from os import path import click from colorama import Fore import pexpect # Extract the file/challenge from the LetsEncrypt output e.g. CREX = re.compile( ".well-known\/acm...
tr(v) + Fore.RESET for k, v in locals().items() })) CERT_PATH = acm
e_path KEY_PATH = acme_path CHAIN_PATH = acme_path FULLCHAIN_PATH = acme_path CONFIG_DIR = acme_path WORK_DIR = path.join(acme_path, 'tmp') LOG_DIR = path.join(acme_path, 'logs') cmd = [ 'letsencrypt', 'certonly', '--rsa-key-size', '2048', '--manual',...
Wooble/devnullunique
app/main.py
Python
mit
5,223
0.001149
"""devnull nethack tournament unique deaths""" from google.appengine.api import urlfetch from google.appengine.ext import ndb import collections import csv import re import os from cStringIO import StringIO import logging import webapp2 import jinja2 BLOCK_SIZE = 1024 * 400 JINJA_ENVIRONMENT = jinja2.Environment( ...
iled for line %s [%s]", i, line) raise posstmp = possibledeaths[:] for death in mydeaths: # the tournament seems
to do this; if so it's a bug... #death = death.replace('(with the Amulet)', '') for i, exp in enumerate(possibledeaths): if exp and exp.search(death.replace('\\', '').replace(' *', '')): done[exp] += 1 possibledeaths[i] = None ...
rolando-contrib/scrapy
scrapy/shell.py
Python
bsd-3-clause
7,530
0.000531
"""Scrapy Shell See documentation in docs/topics/shell.rst """ from __future__ import print_function import os import signal import warnings from twisted.internet import reactor, threads, defer from twisted.python import threadable from w3lib.url import any_to_uri from scrapy.crawler import Crawler from scrapy.exc...
lled. """ request_callback = request.callback request_errback = request.errback def _restore_callbacks(result): request.callback = request_callback request.errback = request_er
rback return result d = defer.Deferred() d.addBoth(_restore_callbacks) if request.callback: d.addCallbacks(request.callback, request.errback) request.callback, request.errback = d.callback, d.errback return d class _SelectorProxy(object): def __init__(self, response): ...
playingaround2017/test123
gamera/confidence.py
Python
gpl-2.0
7,363
0.030151
# -*- mode: python; indent-tabs-mode: nil; tab-width: 3 -*- # vim: set tabstop=3 shiftwidth=3 expandtab: # # Copyright (C) 2003 Karl MacMillan # # 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; e...
(v) return new_glyphs def test(): glyphs = gamera_xml.glyphs_from_xml(r"C:\Documents and Settings\Karl MacMillan\Desktop\test\prod.xml") glyphs = strip_small_categories(glyphs) from gamera.plugins import features k
= knn.kNN() print k.features features.generate_features_list(glyphs, k.feature_functions) print "Getting gstats" graph_stats = get_graph_stats(glyphs, k) gstats = knn.get_glyphs_stats(glyphs) max_dist = max_distance(glyphs, k) print max_dist file = open("results.txt", "w") global_max = [[],...
erangre/Dioptas
dioptas/controller/integration/OptionsController.py
Python
gpl-3.0
5,126
0.003316
# -*- coding: utf-8 -*- # Dioptas - GUI program for fast processing of 2D X-ray diffraction data # Principal author: Clemens Prescher ([email protected]) # Copyright (C) 2014-2019 GSECARS, University of Chicago, USA # Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany ...
able_full_cake_range() def cake_azimuth_range_changed(self): range_min = float(self.options_widget.cake_azimuth_min_txt.text()) range_max = float(self.options_widget.cake_azimuth_max_txt.text()) self.model.current_configuration.cake_azimuth_range = (range_min, range_max) def cake_azimu...
th_points_sb.value()) def cake_full_toggled_btn_changed(self): if self.options_widget.cake_full_toggle_btn.isChecked(): self.enable_full_cake_range() self.model.current_configuration.cake_azimuth_range = None elif not self.options_widget.cake_full_toggle_btn.isChecked(): ...
Kupoman/blendergltf
blendergltf/extension_exporters/khr_technique_webgl.py
Python
apache-2.0
14,656
0.000887
import base64 import os import re import bpy import gpu LAMP_TYPES = [ gpu.GPU_DYNAMIC_LAMP_DYNVEC, gpu.GPU_DYNAMIC_LAMP_DYNCO, gpu.GPU_DYNAMIC_LAMP_DYNIMAT, gpu.GPU_DYNAMIC_LAMP_DYNPERSMAT, gpu.GPU_DYNAMIC_LAMP_DYNENERGY, gpu.GPU_DYNAMIC_LAMP_DYNENERGY, gpu.GPU_DYNAMIC_LAMP_DYNCOL, gp...
ivatives: enable\n' header += precision_block src = src.replace('#version 130', header) src = re.sub(r'\bin\b', 'varying', src) src = src.replace('out vec4 frag_color;\n', '') src =
re.sub(r'\bfrag_color\b', 'gl_FragColor', src) # TODO: This should be fixed in Blender src = src.replace('blend = (normalize(vec).z + 1)', 'blend = (normalize(vec).z + 1.0)') # TODO: This likely breaks shadows src = src.replace('sampler2DShadow', 'sampler2D') src = src.replace('shadow2DProj', 'tex...