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 |
|---|---|---|---|---|---|---|---|---|
rsmith-nl/scripts | make-flac.py | Python | mit | 3,732 | 0.000538 | #!/usr/bin/env python
# file: make-flac.py
# vim:fileencoding=utf-8:fdm=marker:ft=python
#
# Copyright © 2012-2018 R.F. Smith <rsmith@xs4all.nl>.
# SPDX-License-Identifier: MIT
# Created: 2012-12-22T00:12:03+01:00
# Last modified: 2020-04-01T00:19:43+0200
"""
Encodes WAV files from cdparanoia (“trackNN.cdda.wav”) to FL... | annot be found")
sys.exit(1)
def runflac(idx, data):
"""
Use the flac(1) program to convert a music file to FLAC format.
Arguments:
idx: track index (starts from 0)
data: album data dictionary
Returns:
A tuple contain | ing the track index and return value of flac.
"""
num = idx + 1
ifn = f"track{num:02d}.cdda.wav"
args = [
"flac",
"--best",
"--totally-silent",
"-TARTIST=" + data["artist"],
"-TALBUM=" + data["title"],
"-TTITLE=" + data["tracks"][idx],
"-TDATE=" + ... |
gengjiawen/migratetogradle | file_util.py | Python | apache-2.0 | 440 | 0 | import os
import shutil
def copytree(src, dst, symlinks=False, ignore=None):
for item in os.listdir(src):
s = os.path.join(src, item)
d = os.path.join(dst, item)
if os.path.isdir(s):
shutil.copytree(s, d, symlinks, ignore)
else:
shutil.copy2(s | , d)
def get_immediate_dir(folder):
file_list = [os.path.join(folder, i) for i in next( | os.walk(folder))[1]]
return file_list
|
JediStuart/PythonFirst | src/ElectronMass.py | Python | gpl-2.0 | 4,226 | 0.006626 | __author__ = 'sjp1'
import math
CONVERT_TO_MILLI = 1e3
CONVERT_M_TO_CM = 1e2
print('Circuit:')
voltage = 5 # V
print('Voltage source:', voltage)
resistor = 50 # ohm
print('Resistor:', resistor)
I = voltage / resistor # A
print('Current:', I, 'C/s')
q = 1.602e-19 # C
print('Charge on electron:', q, 'C')
electron_per_... | e: %.4g atoms' % atoms_across_wire)
electrons_per_atom = 1
electron_dista | nce_per_second = drift_velocity
print('Electron distance per second: %.4g m' % electron_distance_per_second)
linear_electron_density = electrons_per_atom * atoms_per_vol**(1/3)
print('Linear electron density: %.4g electrons/m' % linear_electron_density)
linear_electron_swept_per_second = linear_electron_density * elect... |
MartinPaulEve/meTypeset | bin/frontmatterparser.py | Python | gpl-2.0 | 3,339 | 0.030848 | #!/usr/bin/env python
__author__ = "Dulip Withanage"
__email__ = "dulip.withanage@gmail.com"
import re
import string
import sys
import operator
import globals as gv
import os
import subprocess
import shutil
#from django.utils.encoding import smart_str
class FrontMatterParser:
def __init__(self, gv):
self.gv =... | , equations tables, laddering, neoliberalism, snowball, valuechain, sodium
name = re.findall(r'(\n|<p>|<bold>|<italic>)(([A-Za-z\-\.]+)\*?\s){2,5}(&|and|et|und)\s(([A-Za-z\-\.]+)\*?\s?){2,5}(</p>|</bold>|</italic>|\n)',filestring)
if len(name) == 0:
# this works for racialprofiling, antiseptics, eeg_comicsans, l... | way too many authors and that affects the string
# would work for rating.doc but need to fix linebreak comments from output
name2 = re.findall(r'(<p>|<bold>|<italic>)(([A-Za-z\-\.]+)(,?\s)){1,20}([A-Za-z\-\.]+)?(</p>|</bold>|</italic>)',filestring)
# this loops through strings and prefers those that occur earli... |
plwhite/libcalico | calico_containers/pycalico/datastore.py | Python | apache-2.0 | 41,654 | 0.000264 | # Copyright 2015 Metaswitch 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 law or agreed to in w... | os.path.isfile(etcd_ca) and
os.access(etcd_ca, os.R_OK)):
raise DataStoreError("Invalid %s. Certificate Authority "
"cert is required and must be a "
"readable file path. Value provided: "
... | elif etcd_scheme != "http":
raise DataStoreError("Invalid %s. Value must be one of: \"\", "
"\"http\", \"https\". Value provided: %s" %
(ETCD_SCHEME_ENV, etcd_scheme))
# Set CA value to None if it is a None-value string
... |
ArmedGuy/pyircbot | pyircbot.py | Python | mit | 15,149 | 0.008911 | import socket, threading, thread, os, sys, time
def create(settings):
return IrcBot(settings)
# Revision, yolo
class IrcBot:
_settings = {}
_debug = None
_client = "ArmedGuys IRC Bot"
_version = "0.5"
_env = "Python"
_socket = None
# Channels the bot is in
_channels = []
# Messag... | t(self):
if "host" in self._settings and "port" in self._settings:
self._socket = socket.create_connection((self._settings['host'], self._settings['port']))
| # Register events
self._queue.RegisterHandler(IrcEvent.PacketRecieved, self.onpacket)
self._queue.RegisterHandler(IrcEvent.MessageRecieved, self.onmessage)
self._queue.RegisterHandler(IrcEvent.PingRecieved, self.onping)
# before sending, create message & queue loops
... |
antoinecarme/pyaf | tests/periodicities/Second/Cycle_Second_25_S_120.py | Python | bsd-3-clause | 82 | 0.04878 | import tests.periodi | cities.peri | od_test as per
per.buildModel((120 , 'S' , 25));
|
sebastian-software/jasy | jasy/build/Script.py | Python | mit | 9,074 | 0.003306 | #
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
# Copyright 2013-2014 Sebastian Werner
#
import os
import jasy
import jasy.core.Console as Console
from jasy.item.Script import ScriptError
from jasy.item.Script import ScriptItem
import jasy.script.Resolver as ScriptResolver
from jasy.script.Resolve... | ionPath()
def buildKernel(self, fileId):
if not fileId:
return
self.__profile.setWorkingPath(self.getWorkingPath())
self.storeKernelScript("kernel.js", bootCode="%s.boot() | ;" % fileId)
def buildPart(self, partId, fileId):
if not fileId:
return
Console.info("Generating script (%s)...", fileId)
Console.indent()
self.__profile.setWorkingPath(self.getWorkingPath())
ScriptItems = ScriptResolver.Resolver(self.__profile).add(fileId).ge... |
rileymcdowell/genomic-neuralnet | genomic_neuralnet/methods/lasso_regression.py | Python | mit | 270 | 0.007407 | from sklearn.linear_model import Lasso
def get_lasso_prediction(train_data, train_truth, test_data, test_truth, alpha=1.0, iter_id=0):
clf = Lasso(alpha=alpha)
| clf.fit(train_data, train | _truth)
predicted = clf.predict(test_data)
return predicted.ravel()
|
itachigiotto/flasky | manage.py | Python | mit | 2,224 | 0.002248 | #!/usr/bin/env python
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
from app import create_app, db
from app.models import User, Follow, Role, Permission, Post, Comment
from flask_script import Manager, Shell
from ... | unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosi | ty=2).run(tests)
if COV:
COV.stop()
COV.save()
print('Coverage Summary:')
COV.report()
basedir = os.path.abspath(os.path.dirname(__file__))
covdir = os.path.join(basedir, 'tmp/coverage')
COV.html_report(directory=covdir)
print('HTML version: file://%s/... |
mariodebian/tcosmonitor | tcosmonitor/extensions/sendfiles.py | Python | gpl-2.0 | 12,245 | 0.019437 | # -*- coding: UTF-8 -*-
# TcosMonitor version __VERSION__
#
# Copyright (c) 2006-2011 Mario Izquierdo <mariodebian@gmail.com>
#
# This package 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 ... | _name("All files")
filter.add_pattern(" | *")
dialog.add_filter(filter)
if not os.path.isdir("/tmp/tcos_share"):
shared.info_msg( _("TcosMonitor: FTP+TLS server is not running.") )
return
for filename in os.listdir("/tmp/tcos_share/"):
if os.path.isfile("/tmp/tcos_share/%s" ... |
saopicc/killMS | killMS/__init__.py | Python | gpl-2.0 | 1,298 | 0.00077 | #!/usr/bin/env python
"""
killMS, a package for calibration in radio interferometry.
Copyright (C) 2013-2017 Cyril Tasse, l'Observatoire de Paris,
SKA South Africa, Rhodes University
This program is free software; you can redistribute i | t and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either | version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have re... |
gonesurfing/Quisk_rpi_remote | quisk_widgets.py | Python | gpl-2.0 | 29,159 | 0.016393 | # These are Quisk widgets
import sys, re
import wx, wx.lib.buttons, wx.lib.stattext
from types import *
# The main script will alter quisk_conf_defaults to include the user's config file.
import quisk_conf_defaults as conf
def FreqFormatter(freq): # Format the string or integer frequency by adding blanks
freq = int... | play, None, None)
#font = wx.Font(10, wx.FONTFAMILY_SWISS, wx.NORMAL, wx.FONTWEIGHT_NORMAL, face=conf.quisk_typeface)
#self.text_ctrl.SetFont(font)
self.Add(self.text_ctrl, 0, wx.ALIGN_CENTER)
self.Add(self.slider, 1, wx.ALIGN_CENTER)
class SliderBoxV(wx.BoxSizer):
"""A vertical box containing a slid... | wx slider has the max value at the bottom. This is
# reversed for this control.
def __init__(self, parent, text, init, themax, handler, display=False):
wx.BoxSizer.__init__(self, wx.VERTICAL)
self.slider = wx.Slider(parent, -1, init, 0, themax, style=wx.SL_VERTICAL)
self.slider.Bind(wx.EVT_SCROLL, han... |
NullHypothesis/tor-dns-tools | dns-pcap-to-csv.py | Python | gpl-3.0 | 1,724 | 0 | #!/usr/bin/env python2
#
# Copyright 2016 Philipp Winter <phw@nymity.ch>
#
# 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 versio... | pcap into csv file.
Extract timestamp, source IP address, and query name of all DNS queries in the
given pcap, and turn it into a CSV.
"""
import sys
import scapy.all as scapy
# We exclude the following two me | asurement hosts.
MEASUREMENT_HOSTS = frozenset(["92.243.1.186", "198.83.85.34"])
def process_file(pcap_file):
packets = scapy.rdpcap(pcap_file)
for packet in packets:
if not packet.haslayer(scapy.IP):
continue
if not packet.haslayer(scapy.DNSQR):
continue
q... |
jruizgit/rules | testpy/waltzdb.py | Python | mit | 44,448 | 0.071027 | from durable.lang import *
import math
import datetime
import json
_fact_count = 0
def create_and_post(fact):
global _fact_count
fact['id'] = _fact_count
fact['sid'] = 1
post('waltzdb', fact)
_fact_count += 1
def create_and_assert(fact):
global _fact_count
fact['id'] = _fact_count
fact... | ) - get_x(p1)
delta_y = get_y(p2) - get_y(p1)
if delta_x == 0:
if delta_y > 0:
return math.pi / 2
elif delta_y < 0:
return -math.pi / 2
elif delta_y == 0:
if delta_x > 0:
retur | n 0
elif delta_x < 0:
return math.pi
else:
return math.atan2(delta_y, delta_x)
def get_inscribable_angle(base_point, p1, p2):
angle1 = get_angle(base_point, p1)
angle2 = get_angle(base_point, p2)
temp = math.fabs(angle1 - angle2)
if temp > math.pi:
return math.fa... |
PressStartandSelect/jux-discovery | util/item_name_gen.py | Python | unlicense | 758 | 0 | '''Script to help generate item names.'''
def int_to_str(num, alphabet):
'''Convert integer to string.'''
# http://stackoverflow.com/a/1119769/1524507
if (num == 0):
return alphabet[0]
arr = []
base = len(alphabet)
while num:
rem = num % base
num = num // base
a... | :
lower = counter
upper = min(counter + pics_per_item - 1, end_num)
print('image:{0}-{1}'.format(lower, upper))
cou | nter += 1000
if counter > end_num:
break
if __name__ == '__main__':
main()
|
oihane/odoo-addons | fleet_route/models/fleet_route_stop.py | Python | agpl-3.0 | 3,444 | 0 | # Copyright 2019 Mentxu Isuskitza - AvanzOSC
# Copyright 2019 Oihana Larrañaga - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import api, fields, models
from odoo.models import expression
from odoo.tools.safe_eval import safe_eval
class FleetRouteStop(models.Model):
_name = ... | mobile",
store=True)
| @api.onchange("location_id")
def _onchange_location_id(self):
self.ensure_one()
if not self.name:
self.name = self.location_id.display_name
@api.multi
def open_map(self):
self.ensure_one()
return self.location_id.open_map()
@api.multi
def button_open_... |
ta2-1/pootle | pootle/apps/pootle_language/models.py | Python | gpl-3.0 | 5,908 | 0 | # -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
from collections import OrderedDict
from dj... | from pootle_app.models.directory import Directory
self.directory = Directory.objects.root.get_or_make_subdir(self.code)
# Do not repeat special chars.
self.specialchars = u"".join(
OrderedDict([
((specialchar
if isinstanc | e(specialchar, unicode)
else specialchar.decode("unicode_escape")),
None)
for specialchar
in self.specialchars]).keys())
super(Language, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
directory = self.directory
... |
sarvex/tensorflow | tensorflow/python/data/experimental/kernel_tests/parse_example_dataset_test.py | Python | apache-2.0 | 43,653 | 0.002245 | # 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... | rted(dict_tensors.items()):
expected_v = expected_tensors[k]
self.assertValuesEqual(expected_v, v)
def _test(self,
input_tensor,
feature_val,
expected_values=None,
expected_err=None,
create_iterator_twice=Fal | se):
if expected_err:
with self.assertRaisesWithPredicateMatch(expected_err[0],
expected_err[1]):
dataset = dataset_ops.Dataset.from_tensors(input_tensor).apply(
contrib_parsing_ops.parse_example_dataset(feature_val))
get_next = self.... |
wasit7/tutorials | arduino_python/04_sciweather/sciweather/myapp/models.py | Python | mit | 393 | 0.038168 | from __future__ import unicode_literals
from django.db import models
class Weather(models.Model):
time=models.DateTimeField(auto_now_add=True)
nodeid=models.CharField(max_length= | 3, blank=False)
temp=models.FloatFie | ld(default=0.0)
humi=models.FloatField(default=0.0)
israin=models.BooleanField(default=False)
def __repr__(self):
return "<nodeid:%s, time:%s>"%(self.nodeid, self.time) |
bigswitch/nova | nova/conf/consoleauth.py | Python | apache-2.0 | 1,156 | 0.00346 | # Copyright (c) 2016 Intel, Inc.
# Copyright (c) 2013 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/li... | plicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_conf... | ole auth proxy nodes listen on')
console_token_ttl = cfg.IntOpt('console_token_ttl',
default=600,
help='How many seconds before deleting tokens')
CONSOLEAUTH_OPTS = [consoleauth_topic_opt, console_token_ttl]
def register_opts(conf):
conf.register_opts(CONSOLEAUTH_OPTS)
def list_opts():
return {'DE... |
CedricGatay/alerta-jul | src/log4tailer/LogColors.py | Python | gpl-3.0 | 2,339 | 0.004703 | # Log4Tailer: A multicolored python tailer for log4J logs
# Copyright (C) 2008 Jordi Carrillo Bosch
# This file is part of Log4Tailer Project.
#
# Log4Tailer 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, ei... | COLORS[COLOR_GREEN], "finer": COLORS[COLOR_GREEN],
"debug": COLORS[COLOR_BLACK], "config": COLORS[COLOR_BLACK],
"finest": COLORS[COLOR_BLACK], "fatal": COLORS[COLOR_RED],
"severe": COLORS[COLOR_RED], "critical": COLORS[COLOR_RED]}
self.reset ... | ndemph
def parse_config(self, properties):
for (level, color) in properties.get_color_items():
code = self.color.getCode(color)
if not code:
continue
self.colors[level] = code
def getLogColor(self, color):
return self.color.getCode(color)
... |
anthonyfok/frescobaldi | frescobaldi_app/guistyle.py | Python | gpl-2.0 | 1,666 | 0.003601 | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 by Wilbert Berendsen
#
# 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
... | .
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Ge | neral Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
# See http://www.gnu.org/licenses/ for more information.
"""
Sets the user interface style.
"""
from PyQt5.QtCore import QSettings
from PyQt5.QtWidgets impo... |
nvazquez/Turtlebots | plugins/butia/pybot/__init__.py | Python | mit | 1,171 | 0.000856 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2014 Alan Aguiar alanjas@hotmail.com
# Copyright (c) 2012-2014 Butiá Team butia@fing.edu.uy
# Butia is a free and open robotic platform
# www.fing.edu.uy/inco/proyectos/butia
# Facultad de Ingeniería - Universidad de la República - Uruguay
#
# This p... |
import sys
# Make sure that can import all files
abs_pa | th = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, abs_path)
# version = 0.turtlebots_version.secondary_number
__version__ = '0.27.0'
|
aptana/Pydev | bundles/org.python.pydev/pysrc/pydevconsole.py | Python | epl-1.0 | 7,910 | 0.006321 | try:
from code import InteractiveConsole
except ImportError:
from pydevconsole_code_for_ironpython import InteractiveConsole
import os
import sys
try:
False
True
except NameError: # version < 2.3 -- didn't have the True/False builtins
import __builtin__
setattr(__builtin__, 'True', 1) # Pyth... | =====
class InterpreterInterface(BaseInterpreterInterface):
'''
The methods in this class should be registered in the xml-rpc server.
'''
def __init__(self, host | , client_port, server):
BaseInterpreterInterface.__init__(self, server)
self.client_port = client_port
self.host = host
try:
import pydevd # @UnresolvedImport
if pydevd.GetGlobalDebugger() is None:
raise RuntimeError() # Work as if the debugger d... |
funkybob/django-email-template | setup.py | Python | mit | 433 | 0 | from s | etuptools import setup, find_packages
DESCRIPTION = """
Send emails based on a Django template
See:
https://github.com/prestontimmons/django-email-template
"""
setup(
name="django-email-template",
version="1.0.2",
description="Send emails based on a Django template",
long_description=DESCRIPTION,
... | |
bionikspoon/Annotation-Tool | server/annotation_tool/pubmed/management/commands/fake_data.py | Python | bsd-3-clause | 1,179 | 0.003393 | from django.core.management.base import BaseCommand
from ...factories import PubmedFactory
from ...models import Pubmed
from ....users.factories import UserFactory
from ....users.models import User
class Command(BaseCommand):
"""Populate fake data."""
help = __doc__
def add_arguments(self, parser):
... | arser.add_argument('--scale', '-s', default=1, type=int, help="Multiplier for record generation.")
def handle(self, *args, **options):
scale = options.get('scale') * 10
user_multiplier = 1
pubmed_multiplier = 3
admin = User.objects.filter(username='admin').first()
if not ad... | in@anno.com', 'secret')
print('Admin user created:', admin)
users = UserFactory.create_batch(scale * user_multiplier)
entries = PubmedFactory.create_batch(scale * pubmed_multiplier)
print('%s random users created. %s Total' % (len(users), User.objects.count()))
print('%s p... |
maxime-beck/compassion-modules | onramp_simulator/tools/onramp_connector.py | Python | agpl-3.0 | 2,626 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | og_message('POST', url, headers, body)
r = self._session.post(url, headers=headers,
json=simplejson.loads(body))
sta | tus = r.status_code
log_message(status, 'RESULT', message=r.text)
test_message.write({
'result': r.text,
'result_code': r.status_code
})
|
mr-justin/open-conference-data | iswc-metadata/src/todo/task_link_dbpedia.py | Python | mit | 3,427 | 0.037642 | from dbpedia_api import DbpediaApi
from libx import UnicodeReader, UtilSyntax
import json
import os
#UtilLinkDbpedia.linkDbpedia("DERI galway","organisation")
#UtilLinkDbpedia.linkDbpedia("Linkoping University","organisation")
#UtilLinkDbpedia.linkDbpedia("MIT CSAIL","organisation")
#UtilLinkDbpedia.linkDbpedia("Univer... | n (filename_new) as f:
csvreader = UnicodeReader(f)
cnt_row = 0
for row in csvreader:
cnt_row+=1
| if len(row)==0:
continue
names = row[0].strip()
if len(names)==0:
continue
if names in map_name:
row = map_name[names]
else:
if len(names)>10:
names =names.replace(" and ", ";")
names =names.replace(" & ", ";")
list_name = names.split(";")
if len(list_name)>1:
... |
HFTrader/BleedingEdge | config/clang-svn.py | Python | lgpl-2.1 | 1,115 | 0.01435 | #!/usr/bin/python
# clang has an awkward tree configuration so we have to implement
# a custom builder to override the default downloader
import pkgbuild
class CustomBuilder( pkgbuild.Builder ):
def __init__( self, buildmgr, pkgname, version ):
| pkgbuild.Builder.__init__( self, buildmgr, pkgname, version )
def checkout( self ):
cmd = """
rm -rf {builddir}/clang-{version} || exit 1
cd {builddir} || exit 1
svn co http://llvm.org/svn/llvm-project/llvm/trunk clang-{version} || exit 1
cd {builddir}/cla | ng-{version}/tools || exit 1
svn co http://llvm.org/svn/llvm-project/cfe/trunk clang || exit 1
cd {builddir}/clang-{version}/tools/clang/tools || exit 1
svn co http://llvm.org/svn/llvm-project/clang-tools-extra/trunk extra || exit 1
cd {builddir}/clang-{version}/projects || exit 1
... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_algorithms/itertools_compress.py | Python | apache-2.0 | 156 | 0 | from ite | rtools import *
every_third = cycle([False, False, True])
data = range(1, 10)
for i i | n compress(data, every_third):
print(i, end=' ')
print()
|
znick/anytask | dependencies/django-registration/registration/backends/default/__init__.py | Python | mit | 5,257 | 0.001712 | from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from registration import signals
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile
class DefaultBackend(object):
"""
A registration backend which follows a simple wor... | )`` for
information about these templates and the contexts provided to
| them.
After the ``User`` and ``RegistrationProfile`` are created and
the activation email is sent, the signal
``registration.signals.user_registered`` will be sent, with
the new ``User`` as the keyword argument ``user`` and the
class of this backend as the sender.
"""
... |
Vagab0nd/SiCKRAGE | lib3/beekeeper/variable_handlers.py | Python | gpl-3.0 | 4,051 | 0.003703 | """
This module provides methods that parse variables into
one of the three base level variable types. We map the
variable type names to meth | ods that can handle them. Each
method consumes a Request object 'rq' as the first positional
argument, and does its work | by calling one of the variable-setting
methods on rq.
"""
from __future__ import absolute_import, division
from __future__ import unicode_literals, print_function
from uuid import uuid4
from functools import partial
from base64 import b64encode
from beekeeper.data_handlers import encode
from beekeeper.exceptions im... |
wm4/boringlang | run_tests.py | Python | isc | 5,430 | 0.002762 | #!/usr/bin/env python
import os
import re
import subprocess
import sys
import tempfile
CC = "gcc"
CFLAGS = "-fmax-errors=4 -std=c99 -pipe -D_POSIX_C_SOURCE=200809L -W -Wall -Wno-unused-variable -Wno-unused-parameter -Wno-unused-label -Wno-unused-value -Wno-unused-but-s | et-variable -Wno-unused-function -Wno-main".split(" ")
class Table():
pass
class TestMode():
pass_ = 0
fail_compile_parse = 1
fail_compile_sem = 2
fail_compile_ice = 3
fail_c = 4
fail_run = 5
fail_output = 6
fail_other = 7
disable = 8
test_modes = [TestMode.pass_, TestMode.fai... | de.fail_compile_ice,
TestMode.fail_c, TestMode.fail_run, TestMode.fail_output,
TestMode.fail_other, TestMode.disable]
test_mode_names = {
TestMode.pass_: ("pass", "Passed"),
TestMode.fail_compile_parse: ("fail_compile_parse", "Compilation failed (parsing)"),
TestMode.fail_compil... |
jaygoswami2303/course_dashboard_api | v2/DiscussionAPI/views.py | Python | mit | 5,468 | 0.002012 | from rest_framework import generics
from api import *
from serializers import StudentDiscussionSerializer, CourseDiscussionSerializer
from rest_framework.permissions import IsAdminUser
from django.http import Http404
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from oauth2_provid... | f discussions by the student
* question: Count of questions asked by the student
**ERROR RESPONSES**
* Response Code <404> STUDEN | T NOT FOUND
* Response Code <403> FORBIDDEN
"""
serializer_class = StudentDiscussionSerializer
permission_classes = (IsAdminUser, IsStudent, )
authentication_classes = (SessionAuthentication, BasicAuthentication, OAuth2Authentication)
def get_object(self):
try:
... |
jweste/odoo-addons-cpo | product_average_consumption/model/__init__.py | Python | agpl-3.0 | 1,096 | 0 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Product - Average Consumption Module for Odoo
# Copyright (C) 2013-Today GRAP (http://www.grap.coop)
# @author Julie | n WESTE
# @author Sylvain LE GAL (https://twitter.com/legalsylvain)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option)... | ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/l... |
jrmanrique/ekalay-finance | finance/migrations/0013_auto_20161020_1428.py | Python | mit | 1,422 | 0.004219 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-20 06:28
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('finance', '0012_auto_20161020_0243'),
]
operations... | .ChartOfAccounts', verbose_name='Account Title')),
],
),
migrations.AlterField(
model_name='cashinflow',
name='account_title',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='finance.ChartOfAccounts', verbose_name='Ac | count Title'),
),
migrations.AlterField(
model_name='cashoutflow',
name='account_title',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='finance.ChartOfAccounts', verbose_name='Account Title'),
),
]
|
spcartman/mantis_tests | data/project.py | Python | mit | 699 | 0.004292 | import random
import string
from model.project import Project
def rand_string(prefix, maxlen):
chars = string.ascii_letters + string.digits + string.punctuation + " " * 10
return prefix + "".join([random.choice(chars) for i in range(random.randrange(maxlen))])
def generate_project_data(n):
return [Proje... | ce(("public", "private")),
descrip | tion=rand_string("descr", 30))
for i in range(int(n))]
test_data = generate_project_data(2)
|
FedoraScientific/salome-paravis | src/PV_SWIG/paravis.py | Python | lgpl-2.1 | 3,020 | 0.006291 | # Copyright (C) 2010-2014 CEA/DEN, EDF R&D
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library ... | stributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License | for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
#... |
JMoravec/unkRadnet | fitToCurve/pyeq2/Models_2D/Peak.py | Python | bsd-3-clause | 66,908 | 0.009012 | # pyeq2 is a collection of equations expressed as Python classes
#
# Copyright (C) 2012 James R. Phillips
# 2548 Vera Cruz Drive
# Birmingham, AL 35235 USA
#
# email: zunzun@zunzun.com
# web: http://zunzun.com
#
# License: BSD-style (see LICENSE.txt in main source directory)
# Version info: $Id:... | ons(self, functionList)
def CalculateModelPredictions(self, inCoeffs, inDataCacheDictionary):
x_in = inDataCacheDictionary['X'] # only need to perform this dictionary look-up once
a = inCoeffs[0]
b = inCoeffs[1]
c = inCoeffs[2]
d = inCoeffs[3]
f = inCoeffs[... | ower((numpy.log(x_in-f)-b) / c, 2.0))) / (d * (x_in-g))
return self.extendedVersionHandler.GetAdditionalModelPredictions(temp, inCoeffs, inDataCacheDictionary, self)
except:
return numpy.ones(len(inDataCacheDictionary['DependentData'])) * 1.0E300
def SpecificCodeCPP(self):
... |
rwl/puddle | puddle/resource/action/up_action.py | Python | mit | 3,878 | 0.003352 | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restrictio... | 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.
#-----------------------------------------------------------... | ---------------------------------------------
# Imports:
#------------------------------------------------------------------------------
from os.path import dirname
from enthought.traits.api import Bool, Instance
from enthought.pyface.api import ImageResource
from enthought.pyface.action.api import Action
from entho... |
afrolov1/nova | nova/virt/hyperv/vhdutilsv2.py | Python | apache-2.0 | 9,112 | 0.000329 | # Copyright 2013 Cloudbase Solutions Srl
# 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 r... | _TYPE_DIFFERENCING:
raise vmutils.HyperVException(_("Differencing VHDX images "
"are n | ot supported"))
else:
try:
with open(vhd_path, 'rb') as f:
hs = VHDX_HEADER_SECTION_SIZE
bes = VHDX_BAT_ENTRY_SIZE
lss = vhd_info['LogicalSectorSize']
bs = self._get_vhdx_bloc... |
heitorschueroff/ctci | ch1/1.07_Rotate_Matrix/rotate_matrix.py | Python | mit | 2,061 | 0 | import unittest
def rotate_matrix(matrix):
end = len(matrix) - 1 # The index of the last row
# Rotating the matrix layer by layer
for row in range((end + 1) / 2):
for col in range(row, end - row):
temp = matrix[row][col]
matrix[row][col] = matrix[end - col][row]
... | 7, 11, 5],
[36, 30, 24, 18, 12, 6]]
rotate_matrix(matrix)
self.assertEquals(matrix, rotated)
if __name__ == '__main__ | ':
unittest.main()
|
robinson96/GRAPE | vine/mergeDevelop.py | Python | bsd-3-clause | 20,224 | 0.00628 | import os
import ConfigParser
import grapeGit as git
import grapeMenu
import grapeConfig
import resumable
import utility
# pull and merge in an up-to-date development branch
class MergeDevelop(resumable.Resumable):
"""
grape md (Merge Down)
merge changes from a public branch into your current topic branc... | conflictedFiles = self.progress["conflictedFiles"]
else:
conflictedFiles = []
# take note of whether all submodules are currently present, assume user wants to add any new submodules to WS if so
activeSubmodulesCheck0 = git.getActiveSubmodules()
self.progress["allActive"] = ... | # checking for a consistent workspace before doing a merge
utility.printMsg("Checking for a consistent workspace before performing merge...")
ret = grapeMenu.menu().applyMenuChoice("status", ['--failIfInconsistent'])
if ret is False:
utility.printMsg("Workspace inconsistent! ... |
dyoung418/tensorflow | tensorflow/contrib/estimator/python/estimator/logit_fns.py | Python | apache-2.0 | 3,764 | 0.003188 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ============================
"""Aliases for logit_fn builders used by canned (core) tf.Estimator's.
A logit_fn is an abstraction within model_fn that factors out the logit
construction logic. Its output can be fed into Heads or otherwise composed. It
should follow the following signature:
Args:
`features`: This is ... | o
`train`, `evaluate`, and `predict`. This should be a single
`Tensor` or `dict` of same, and is the only required argument.
`mode`: Optional. Specifies if this training, evaluation or prediction. See
`ModeKeys`.
`params`: Optional `dict` of hyperparameters. Will receive what is passed ... |
Kolguyev/samples | law_of_demeter/law_of_demeter_bad_example.py | Python | gpl-2.0 | 738 | 0.004065 |
class City(object):
def __init__(self, name):
self.name = name
def Name(self):
return self.name
class Home(object):
def __ini | t__(self, name, city):
self.name = name
self.city = city
def Name(self):
return self.name
def City(self):
return self.city
class Person(object):
def __init__(self, name, home):
self.name = name
self.home = home
def Name(self):
return self... | person.Name(), person.Home().Name(), person.Home().City().Name())
|
EverlyWell/redash | redash/tasks/general.py | Python | bsd-2-clause | 1,915 | 0.001044 | import requests
from celery.utils.log import get_task_logger
from flask_mail import Message
from redash import mail, models, settings
from redash.version_check import run_version_check
from redash.worker import celery
logger = get_task_logger(__name__)
@celery.task(name="redash.tasks.record_event")
def record_event... | exception("Failed posting to %s", hook)
@celery.task(name="redash.tasks.version_check")
def version_check():
run_version_check()
@celery.task(name="redash.tasks.subscribe")
def subscribe(form):
logger.info("Subscribing to: [security notification | s=%s], [newsletter=%s]", form['security_notifications'], form['newsletter'])
data = {
'admin_name': form['name'],
'admin_email': form['email'],
'org_name': form['org_name'],
'security_notifications': form['security_notifications'],
'newsletter': form['newsletter']
}
r... |
kobolabs/calibre | src/calibre/library/database2.py | Python | gpl-3.0 | 168,238 | 0.003204 | from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal kovid@kovidgoyal.net'
__docformat__ = 'restructuredtext en'
'''
The database used to store ebook metadata
'''
import os, sys, shutil, cStringIO, glob, time, functools, traceback, re, \
json, uuid, hashlib, copy
fr... | his library. As long as the user only operates'
' on libraries with calibre, it will be unique')
def fget(self):
if self._library_id_ is None:
ans = self.conn.get('SELECT uuid FROM library_id', all=False)
if ans is None:
ans = str(... | self.library_id = ans
else:
self._library_id_ = ans
return self._library_id_
def fset(self, val):
self._library_id_ = unicode(val)
self.conn.executescript('''
DELETE FROM library_id;
... |
mate-desktop/pluma | plugins/quickopen/quickopen/popup.py | Python | gpl-2.0 | 17,500 | 0.000914 | # -*- coding: utf-8 -*-
# Copyright (C) 2009 - Jesse van den Kieboom
# Copyright (C) 2012-2021 MATE Developers
#
# 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 Lic... | lipsizeMode.MIDDLE)
self._info_label = lbl
vbox.pack_start(lbl, False, False, 0)
# Initial selection
self.on_selection_changed(tv.get_selection())
vbox.show_all()
def | on_cell_data_cb(self, column, cell, model, piter, user_data):
path = model.get_path(piter)
if self._cursor and path == self._cursor.get_path():
style = self._treeview.get_style()
bg = style.bg[Gtk.StateType.PRELIGHT]
cell.set_property('cell-background-gdk', bg)
... |
edx-solutions/edx-platform | openedx/core/process_warnings.py | Python | agpl-3.0 | 9,556 | 0.002198 | """
Script to process pytest warnings output by pytest-json-report plugin and output it as a html
"""
from __future__ import absolute_import
from __future__ import print_function
import json
import os
import io
import re
import argparse
from collections import Counter
import pandas as pd
from write_to_html import (
... | atform/cms/.*\.py": "cms", # noqa pylint: disable=W1401
".*/edx-platform/common/.*\.py": "common", # noqa pylint: disable=W1401
}
# separate into locations flow:
# - iterate through each wanring_object, see if its filename matches any regex in warning locations.
# - If so, change high_locat... | on warnings_object to location name
for warnings_object in warnings_data:
warning_origin_located = False
for key in warnings_locations:
if (
re.search(key, warnings_object[columns_index_dict["filename"]])
is not None
):
warnings... |
HailStorm32/Q.bo_stacks | qbo_arduqbo/src/qbo_arduqbo/msg/_Mic.py | Python | lgpl-2.1 | 7,186 | 0.01656 | """autogenerated by genpy from qbo_arduqbo/Mic.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
class Mic(genpy.Message):
_md5sum = "53acd43451f96e661169eddc90448bdc"
_type = "qbo_arduqbo/Mic"
_has_header = True #flag to mark... |
end += 12
(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs,) = _struct_3I.unpack(str[start:end])
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.header.frame_id = str[start:end].decode('utf-8... | else:
self.header.frame_id = str[start:end]
start = end
end += 1
(self.mic,) = _struct_B.unpack(str[start:end])
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
s... |
eteq/astropy-helpers | astropy_helpers/git_helpers.py | Python | bsd-3-clause | 3,411 | 0.000293 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Utilities for retrieving revision information from a project's git repository.
"""
# Do not remove the following comment; it is used by
# astropy_helpers.version_helpers to determine the beginning of the code in
# this module
# BE | GIN
import os
import subprocess
import warnings
def update_git_devstr(version, path=None):
"""
Updates the git revision string if and only if the path is being imported
directly from a git working copy. This ensures that the revision number in
the version string is accurate.
"""
try:
... | ot - returns '' if not
devstr = get_git_devstr(sha=True, show_warning=False, path=path)
except OSError:
return version
if not devstr:
# Probably not in git so just pass silently
return version
if 'dev' in version: # update to the current git revision
version_base =... |
Vauxoo/e-commerce | website_snippet_product_category/controllers/__init__.py | Python | agpl-3.0 | 22 | 0 | fr | om . import website
| |
raoanirudh/oq-risklib | openquake/commonlib/writers.py | Python | agpl-3.0 | 9,835 | 0.000102 | # Copyright (c) 2010-2014, GEM Foundation.
#
# NRML is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# NRML is distributed in t... |
shape = col[-1]
h.append(':'.join([name, numpytype, ':'.join(map(str, shape))]))
return h
def extract_from(data, fields):
"""
Extract data from numpy arrays with nested records.
>>> imt_dt = numpy.dtype([('PGA', float, 3), ('PGV', float, 4)])
> | >> a = numpy.array([([1, 2, 3], [4, 5, 6, 7])], imt_dt)
>>> extract_from(a, ['PGA'])
array([[ 1., 2., 3.]])
|
metronotes-beta/metroblockd | lib/components/dex.py | Python | mit | 24,335 | 0.005835 | from datetime import datetime
import logging
import decimal
import base64
import json
import time
from lib import config, util
decimal.setcontext(decimal.Context(prec=8, rounding=decimal.ROUND_HALF_EVEN))
D = decimal.Decimal
def calculate_price(base_quantity, quote_quantity, base_divisibility, quote_divisibility, o... | (backward_asset || '/' || forward_asset)
END) AS pair,
(CASE
WHEN forward_asset = ? THEN backward_quantity
| ELSE forward_quantity
END) AS bq,
(CASE
WHEN backward_asset = ? THEN backward_quantity
ELSE forward_quantity
END) AS qq '''
if from_time:
sql += ''', block_time '''
sql += ... |
hickeroar/project-euler | 020/solution026-1.py | Python | mit | 1,244 | 0.004019 | """
A unit fraction contains 1 in the numerator.
The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recur... | checkLength-1:-1] == testVal[-checkLength-1-checkLength:-1-checkLength]:
repLength = checkLength
break
checkLength += 1
if None == repLength:
raise Exception("Precision is inadequa | te. Raise it!")
if repLength > winningLength:
winningNumber = d
winningLength = repLength
print winningNumber
|
JulienMcJay/eclock | windows/Python27/Lib/site-packages/pygame/examples/fastevents.py | Python | gpl-2.0 | 2,890 | 0.006574 | #!/usr/bin/env python
""" This is a stress test for the fastevents module.
*Fast events does not appear faster!*
So far it looks like normal pygame.event is faster by up to two times.
So maybe fastevent isn't fast at all.
Tested on windowsXP sp2 athlon, and freebsd.
However... on my debian duron 850 machine fastev... | n
self.done.append(1)
import time as pytime
def main():
init()
if use_fast_events:
fastevent.init()
c = time.Clock()
win = display.set_mode((640, 480), RESIZABLE)
display.set_caption("fastevent Workout")
poster = post_them()
t1 = pytime.time()
poster.start()
... | # ee = event.Event(USEREVENT)
# r = event_module.post(ee)
# print (r)
#for e in event_module.get():
event_list = []
event_list = event_module.get()
for e in event_list:
if e.type == QUIT:
print (c.get_fps())
poste... |
ecuvelier/P3MVEOS | script.py | Python | apache-2.0 | 5,241 | 0.021183 | # -*- coding: utf-8 -*-
"""
Created on 2017
Author : Edouard Cuvelier
Affiliation : Université catholique de Louvain - ICTEAM - UCL Crypto Group
Address : Place du Levant 3, 1348 Louvain-la-Neuve, BELGIUM
email : firstname.lastname@uclouvain.be
"""
import mathTools.field as field
import mathTools.ellipticCurve as ell... | fp6_1 = Fp6.one()
fp6_xi = Fp6.elem(xi) # xi in Fp6
##### Fp12 #####
poly6 = field.polynom(Fp6,[fp6_1,fp6_0,-fp6_xi]) # X**2-xi
Fp12 = field.ExtensionField(Fp6,poly6)
print Fp12, " ...done"
fp12_0 = Fp12.zero()
fp12_1 = Fp12.one()
C12 = ellipticCurve.Curve(fp12_0,b*fp12_1,Fp12) # Y**2 = X | **3+b
PInf12 = ellipticCurve.ECPoint(infty = True)
EFp12 = ellipticCurve.ECGroup(Fp12,C12,PInf12)
Qpr = oEC.psi(EFp12,Q) # Qpr lives in E[Fp12b]
Pair = pairing.Pairing(EFp,EFp12,C,P,Q,n,Qpr,oEC.frobenius,oEC.prec_gamma(Fp12,u,c,d))
poly_deg = 3
alpha = Fp.random().val
#alpha = 5
pC_SK = pC.PCommitment_Secret_Key(alph... |
detiber/lib_openshift | lib_openshift/models/v1beta1_replica_set_spec.py | Python | apache-2.0 | 6,193 | 0.001615 | # coding: utf-8
"""
OpenAPI spec version:
Generated by: https://github.com/swagger-api/swagger-codegen.git
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
... | S" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from pprint im | port pformat
from six import iteritems
import re
class V1beta1ReplicaSetSpec(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
operations = [
]
# The key is attribute name
# and the value is attribute type.
... |
chop-dbhi/biorepo-portal | accounts/utils.py | Python | bsd-2-clause | 4,673 | 0.00214 | import re
import logging
from django.template.loader import get_template
from django.core.cache import cache
from django.core.mail import mail_admins
from django.contrib.auth import get_user_model
from django.views.decorators.debug import sensitive_variables
MAX_LOGIN_ATTEMPTS = 5
MAX_LOGIN_ATTEMPTS_KEY = '%s_%s_logi... | }\.\d{1,3}\.\d{1,3}')
log = logging.getLogger('portal')
UserModel = get_user_model()
def get_ip_address(request):
ip_address = request.META.get(
'HTTP_X_FOR | WARDED_FOR', request.META.get('REMOTE_ADDR', None))
if ip_address:
ip_match = IP_RE.match(ip_address)
if ip_match is not None:
return ip_match.group()
@sensitive_variables('password')
def throttle_login(request):
"""
Throttles a client by keeping track of the number of failed ... |
Lazea/TensorFlow | classification/classification_train.py | Python | apache-2.0 | 3,781 | 0.004232 | """Classification training"""
import os, sys
sys.path.append('../')
sys.path.append('../models/')
sys.path.append('../util/')
import t | ime
import json
import importlib
import argparse
import tensorflow as tf
import numpy as np
from in | put_data import Data
def optimization(learning_rate, loss):
"""Defines the optimization operation"""
return tf.train.AdamOptimizer(learning_rate).minimize(loss)
def cross_entropy(logits, labels):
"""Defines loss function"""
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=... |
sosy-lab/benchexec | benchexec/tools/esbmc.py | Python | apache-2.0 | 2,560 | 0.000781 | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import os
from benchexec.tools.sv_benchmarks_util import get_data_model_ | from_task, ILP32, LP64
import benchexec.tools.template
| import benchexec.result as result
class Tool(benchexec.tools.template.BaseTool2):
"""
This class serves as tool adaptor for ESBMC (http://www.esbmc.org/)
"""
def executable(self, tool_locator):
return tool_locator.find_executable("esbmc-wrapper.py")
def working_directory(self, executable... |
ne-sachirou/segzi-tools | segzify/tests/__init__.py | Python | bsd-3-clause | 20 | 0 | """T | est segzify." | ""
|
mtford90/silk | project/tests/test_config_meta.py | Python | mit | 1,493 | 0.00067 | from django.test import TestCase
from mock import NonCallableMock
from silk.collector import DataCollector
from silk.middleware import SilkyMiddleware
from .util import delete_all_models
from silk.config import SilkyConfig
from silk.models import Request
def fake_get_response():
def fake_response():
retu... | objs = Request.objects.all()
self.assertEqual(objs.count(), 1)
r = objs[0]
return r
def test_enabled(self):
SilkyConfig().SILKY_META = True
r = self._execut | e_request()
self.assertTrue(r.meta_time is not None or
r.meta_num_queries is not None or
r.meta_time_spent_queries is not None)
def test_disabled(self):
SilkyConfig().SILKY_META = False
r = self._execute_request()
self.assertFalse(r.me... |
gjr80/weewx | bin/weewx/tests/test_daily.py | Python | gpl-3.0 | 20,233 | 0.003759 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2009-2020 Tom Keffer <tkeffer@gmail.com>
#
# See the file LICENSE.txt for your full rights.
#
"""Unit test module weewx.wxstats"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import with_statement
import datetime
import l... | random day, say 15 March:
start_ts = int(time.mktime((2010, 3, 15, 0, 0, 0, 0, 0, -1)))
stop_ts = int(time.mktime((2010, 3, 16, 0, 0, 0, 0, 0, -1)))
# Sanity check that this is truly the start of day:
self.assertEqual(start_ts, weeutil.weeutil.startOfDay(start_ts))
... | gregate == 'max':
res = manager.getSql("SELECT MAX(windGust) FROM archive WHERE dateTime>? AND dateTime <=?;",
(start_ts, stop_ts))
else:
res = manager.getSql(
"SELECT %s(windSpeed) FROM archive WHER... |
vivisect/synapse | synapse/tools/easycert.py | Python | apache-2.0 | 3,093 | 0.004526 | import sys
import argparse
import synapse.common as s_common
import synapse.lib.output as s_output
import synapse.lib.certdir as s_certdir
descr = '''
Command line tool to generate simple x509 certs
'''
def main(argv, outp=None):
if outp is None: # pragma: no cover
outp = s_output.OutPut()
pars =... | dir.genClientCert(opts.name, outp=outp)
return 0
if opts.sign_csr:
if opts.signas is None:
outp.printf('--sign-csr requires --signas')
return -1
xcsr = cdir._loadCsrPath(opts.name)
if xcsr is None:
outp.printf('cs... | return 0
cdir.signUserCsr(xcsr, opts.signas, outp=outp)
return 0
if opts.csr:
if opts.ca:
raise NotImplementedError('CSR for CA cert not supported (yet)')
if opts.server:
cdir.genHostCsr(opts.name, outp=outp)
... |
myrdd/firefox-ui-tests | firefox_ui_tests/functional/security/test_no_certificate.py | Python | mpl-2.0 | 3,597 | 0.00278 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from urlparse import urlparse
from marionette_driver import expected, Wait
from firefox_ui_harness.decorators import s... | al(self.identity_popup.element.get_attribute('connection'), 'not-secure')
# The expander for the security view does not exist
expected.element_not_present(lambda m: self.identity_popup.main.expander)
# Only the insecure label is visible
secure_label = self.i | dentity_popup.view.main.secure_connection_label
self.assertEqual(secure_label.value_of_css_property('display'), 'none')
insecure_label = self.identity_popup.view.main.insecure_connection_label
self.assertNotEqual(insecure_label.value_of_css_property('display'), 'none')
self.identity_po... |
nicolashainaux/mathmaker | tests/00_libs/test_database.py | Python | gpl-3.0 | 21,413 | 0 | # -*- coding: utf-8 -*-
# Mathmaker creates automatically maths exercises sheets
# with their answers
# Copyright 2006-2017 Nicolas Hainaux <nh.techn@gmail.com>
# This file is part of Mathmaker.
# Mathmaker is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | y_packs():
r = IntspansProduct('1,2×1,2×3,4×5,6')
assert r._group_by_packs(r.spans, '2_2') == \
[[[intspan('1-2'), intspan('1-2')], [intspan('3-4'), intspan('5-6')]],
[[intspan('1-2'), intspan('3-4')], [intspan('1-2'), intspan('5-6')]],
[[intspan('1-2 | '), intspan('5-6')], [intspan('1-2'), intspan('3-4')]]]
assert r._group_by_packs(r.spans, '3_1') == \
[[[intspan('1-2'), intspan('1-2'), intspan('3-4')], [intspan('5-6')]],
[[intspan('1-2'), intspan('1-2'), intspan('5-6')], [intspan('3-4')]],
[[intspan('1-2'), intspan('3-4'), intspan('5-6'... |
NikolaYolov/invenio_backup | modules/miscutil/lib/invenio_connector_regression_tests.py | Python | gpl-2.0 | 3,515 | 0.007112 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2010, 2011 CERN.
##
## Invenio 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 opt... | """
server = InvenioConnector(CFG_SITE_URL)
result = server.search(p='ellis', of='id')
self.assertTrue(len(result) > 0, \
'did not get local search results.')
def test_remote_search(self):
"""InvenioConnector - remote search"""
server = Inveni | oConnector("http://inspirebeta.net")
result = server.search(p='ellis', of='id')
self.assertTrue(len(result) > 0, \
'did not get remote search results from http://inspirebeta.net.')
def test_search_collections(self):
"""InvenioConnector - collection search"""
... |
Forage/Gramps | gramps/gui/selectors/selectplace.py | Python | gpl-2.0 | 2,617 | 0.003821 | #
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2003-2006 Donald N. Allingham
# Copyright (C) 2009-2010 Gary Burton
# Copyright (C) 2010 Nick Hall
#
# 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
#... | lector.TEXT, 2),
(_('Locality'), 75, BaseSelector.TEXT, 3),
(_('City'), 75, BaseSelector.TEXT, 4),
(_('County'), 75, BaseSelector.TEXT, 5),
(_('State'), 75, Bas | eSelector.TEXT, 6),
(_('Country'), 75, BaseSelector.TEXT, 7),
(_('Parish'), 75, BaseSelector.TEXT, 9),
]
def get_from_handle_func(self):
return self.db.get_place_from_handle
|
isaachenrion/jets | src/architectures/utils/layer_norm.py | Python | bsd-3-clause | 446 | 0.002242 | import torch
import torch.nn as nn
class LayerNorm( | nn.Module):
def __init__(self, features, eps=1e-6):
super().__init__()
self.gamma = nn.Parameter(torch.ones(features))
self.beta = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean(-1, keepdim=Tru | e)
std = x.std(-1, keepdim=True)
return self.gamma * (x - mean) / (std + self.eps) + self.beta
|
Rogentos/argent-anaconda | tests/storage/devicelibs/lvm.py | Python | gpl-2.0 | 6,895 | 0.007832 | import baseclass
import unittest
import storage.devicelibs.lvm as lvm
class LVMTestCase(baseclass.DevicelibsTestCase):
def testLVM(self):
##
## pvcreate
##
# pass
for dev, file in self._LOOP_DEVICES:
self.assertEqual(lvm.pvcreate(dev), None)
# fail
... | est-lv")
self.assertRaises(lvm.LVMError, lvm.lvremove, "wrong-vg-name", "wrong-lv-name")
# lv already removed
self.assertRaises(lvm.LVMError, lvm.lvremove, "test-vg", "test-lv")
##
## vgremove
##
# pass
self.assertEqual(lvm.vgremove("test-v | g"), None)
# fail
self.assertRaises(lvm.LVMError, lvm.vgremove, "wrong-vg-name")
# vg already removed
self.assertRaises(lvm.LVMError, lvm.vgremove, "test-vg")
##
## pvremove
##
# pass
for dev, file in self._LOOP_DEVICES:
self.assertEq... |
unterweg/peanoclaw | supermucOpenMPIConfiguration.py | Python | bsd-3-clause | 296 | 0.023649 | #
# Definitions for compiling with Open | MPI on SuperMUC
#
def getMPIIncludes():
return ['/lrz/sys/parallel/openmpi/1.6.5/intel13_ib_sles11_ll/include']
def getMPILibrarypaths():
| return ['/lrz/sys/parallel/openmpi/1.6.5/intel13_ib_sles11_ll/lib']
def getMPILibraries():
return ['mpi']
|
khchine5/xl | lino_xl/lib/contacts/roles.py | Python | bsd-2-clause | 269 | 0.011152 | # Co | pyright 2015-2017 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
from lino.core.roles import UserRole
class SimpleContactsUser(UserRole):
pass
class ContactsUser(SimpleContactsUser):
pass
class ContactsStaff(Co | ntactsUser):
pass
|
dimkal/mne-python | mne/gui/_kit2fiff_gui.py | Python | bsd-3-clause | 18,716 | 0.000053 | """Mayavi/traits GUI for conv | erting data from KIT systems"""
# Authors: Christian Brodbeck <christianbrodbeck@nyu.edu>
#
# License: BSD (3-clause)
import os
import numpy as np
from scipy.linalg import inv
from threading import Thread
from ..externals.six.moves import queue
from ..io.meas_info import _read_dig_points, _make_dig_points
from ..io.... | Scene
from mayavi.tools.mlab_scene_model import MlabSceneModel
from pyface.api import confirm, error, FileDialog, OK, YES, information
from traits.api import (HasTraits, HasPrivateTraits, cached_property,
Instance, Property, Bool, Button, Enum, File, Int,
... |
openprocurement/openprocurement.search | openprocurement/search/index_worker.py | Python | apache-2.0 | 4,585 | 0.000872 | # -*- coding: utf-8 -*-
import os
import sys
import fcntl
import signal
import logging
import logging.config
from ConfigParser import ConfigParser
from openprocurement.search.version import __version__
from openprocurement.search.engine import IndexEngine, logger
from openprocurement.search.utils import decode_bool_... |
DgfLotInde | x(engine, source, config)
engine.run()
except Exception as e:
logger.exception("Unhandled Exception: %s", str(e))
finally:
lock_file.close()
os.remove(lock_filename)
if engine and hasattr(engine, 'stop_childs'):
engine.stop_childs()
logger.info("Shutdo... |
elena/django | tests/file_uploads/uploadhandler.py | Python | bsd-3-clause | 1,171 | 0 | """
Upload handlers to test the upload API.
"""
from django.core.files.uploadhandler import (
FileUploadHandler, StopUpload, TemporaryFileUploadHandler,
)
class QuotaUploadHandler(FileUploadHandler):
"""
This test upload handler terminates the connection if more than a quota
(5MB) is uploaded.
""... | , file_size):
return None
class StopUploadTemporaryFileHandler(TemporaryFileUploadHandler):
"""A handler that raises a StopUpload exception."""
def receive_data_chunk(self, raw_data, start):
raise StopUpload()
class CustomUploadError(Exception):
pass
class E | rroringUploadHandler(FileUploadHandler):
"""A handler that raises an exception."""
def receive_data_chunk(self, raw_data, start):
raise CustomUploadError("Oops!")
|
yaybu/touchdown | touchdown/aws/vpc/subnet.py | Python | apache-2.0 | 5,439 | 0.000735 | # Copyright 2014 Isotoma Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# yo | u may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CO... | e License for the specific language governing permissions and
# limitations under the License.
from touchdown.core import argument, errors, serializers
from touchdown.core.plan import Plan, Present
from touchdown.core.resource import Resource
from ..common import SimpleApply, SimpleDescribe, SimpleDestroy, TagsMixin
... |
calpeyser/google-cloud-python | storage/tests/unit/test_batch.py | Python | apache-2.0 | 22,603 | 0 | # Copyright 2014 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 writing, ... | tch._make_request(
'PATCH', url, data={'foo': 1}, target_object=target)
self.assertEqual(response.status_code, 204)
self.assertIsInstance(response.content, _FutureDict)
self.assertIs(target._properties, response.content)
# The real http request should not have been called y... | quest = batch._requests[0]
request_method, request_url, _, request_data = request
self.assertEqual(request_method, 'PATCH')
self.assertEqual(request_url, url)
self.assertEqual(request_data, data)
def test__make_request_DELETE_normal(self):
from google.cloud.storage.batch imp... |
ewiger/hobbit | sagecase.py | Python | mit | 388 | 0.007732 | import conf | ig
import novaclient.client
#import novaclient.v1_1.client
nova = novaclient.client.Client(
2,
config.USERNAME,
config.PASSWORD,
project_id=config.TENANT_ID,
auth_url=config.AUTH_URL,
insecure=True,
http_log_debug=True,
)
#print nova.verify_cert
nova.set_management_url('https://hobbes.gc3... | nt nova.servers.list()
|
etesync/journal-manager | journal/migrations/0004_journal_modified.py | Python | agpl-3.0 | 451 | 0 | # -*- coding: utf-8 -*-
# Gene | rated by Django 1.11 on 2017-04-06 22:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('journal', '0003_journal_version'),
]
operations = [
migrations.AddField(
model_name='journal',
... | e),
),
]
|
mfsteen/CIQTranslate-Kristian | openpyxl/compat/functools.py | Python | gpl-3.0 | 6,980 | 0.003009 | from __future__ import absolute_import
# Copyright (c) 2010-2016 openpyxl
# lru_cache backport copyright Raymong Hettinger
# http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/?in=user-178123
from collections import namedtuple
from functools import update_wrapper
from threading ... | nly return the
| # computed result and update the count of misses.
pass
elif _len(cache) >= maxsize:
# use the old root to store the new key and result
oldroot = root
oldroot[KEY] = key
oldro... |
edermartioli/ExoplanetLight | src/test/test-orbit.py | Python | mit | 13 | 0 | i | mport or | bit
|
jsafrane/dbusmock-gen | scan.py | Python | lgpl-2.1 | 8,094 | 0.002965 | # Copyright (C) 2014 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distri... | method name="CreatePartition">
# <arg type="t" name="offset" direction="in"/>
# <arg type="t" name="size" direction="in"/>
# ...
# </method>
methodnodes = ifnode.findall('met | hod')
if methodnodes:
print "%s_methods = ''' [" % (prefix)
for methodnode in methodnodes:
methodname = methodnode.attrib['name']
insig = self.get_signature(methodnode, "in");
outsig = self.get_signature(methodnode, ... |
jordij/nzhuts | nzhuts/core/migrations/0003_auto_20170810_0719.py | Python | mit | 3,429 | 0.001458 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-10 07:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0019_delete_filter'),
('core', '00... | model_name='hutpage',
name='meta_image',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image'),
),
migrations.AddField(
| model_name='hutpage',
name='meta_title',
field=models.CharField(blank=True, max_length=200),
),
]
|
papercapp/django-feedmapper | feedmapper/settings.py | Python | bsd-3-clause | 283 | 0 | from django.conf import settings
FEEDMAPPER = {
'DATA_DIR': '',
'PARSER_CHOICES': (
('feedmapper.parsers.AtomParser', 'Atom'),
('feedmapper.parsers.XML | Parser', 'XML'),
),
}
if hasattr(settin | gs, 'FEEDMAPPER'):
FEEDMAPPER.update(settings.FEEDMAPPER)
|
gnrhxni/CS542 | weighthistograms.py | Python | gpl-3.0 | 380 | 0.034211 | #!/usr/bin/python
import pickle
import numpy as np
import glob
stems = 'weights.forgi | ving_1_1 weights.forgiving_0_0'.sp | lit();
for s in stems:
files = glob.glob('%s*' % s);
a = np.zeros(0);
for f in files:
w = pickle.load(open(f));
a = np.append(a,w);
h = np.histogram(a,range(-20,20,2));
print("histogram for %s" % s);
print(h);
|
OpenVZ/vcmmd | setup.py | Python | lgpl-2.1 | 1,789 | 0.003354 | from distutils.core import setup, Extension
from distutils.command.install import install
import sys
import brand
import re
import os
with open('Makefile.version') as f:
version = f.read().strip()
f.close()
servicefile = 'vcmmd.service'
systemd_unitdir = '/usr/lib/systemd/system'
systemd_unit = systemd_unitd... | license='GPLv2',
packages=['vcmmd',
'vcmmd.util',
'vcmmd.cgroup',
'vcmmd.rpc',
'vcmmd.rpc.dbus',
'vcmmd.ldmgr',
'vcmmd.ldmgr.policies',
'vcmmd.ve'],
data_files=[('/etc/dbus-1/system.d', ['dbu... | e.d', ['logrotate/vcmmd']),
('/etc/vz', ['vcmmd.conf', 'vstorage-limits.conf']),
('/usr/lib/tmpfiles.d/', ['vcmmd-tmpfiles.conf']),
(systemd_unitdir, ['systemd/{}'.format(servicefile)])],
scripts=['bin/vcmmd', 'bin/vcmmdctl'])
if len(sys.argv) < 2 or (len(sys... |
project-rig/nengo_spinnaker | nengo_spinnaker/operators/sdp_transmitter.py | Python | mit | 3,555 | 0 | from rig.place_and_route import Cores, SDRAM
import struct
from nengo_spinnaker.builder.ports import InputPort
from nengo_spinnaker.builder.netlist import netlistspec
from nengo_spinnaker.netlist import Vertex
from nengo_spinnaker.regions import Region
from nengo_spinnaker.regions.filters import make_filter_regions
fr... | emRegion(Region):
"""System region for SDP Tx."""
def __init__(self, machine_timestep, size_in, delay):
self.machine_timestep = machine_timestep
self.size_in = size_in
self.transmission_delay = delay
def sizeof(self, *args, **kwargs):
return 12
def write_region_to_file(... | .machine_timestep,
self.transmission_delay))
|
prophet-roshak/iotkit-lib-c | tests/python/device_management-create_a_device.py | Python | mit | 679 | 0.019146 | import iotkit;
print 'iotkit library version:', iotkit.iotkit_get_version();
createDeviceObj = iotkit.createDeviceCreationObject("02-a0-a7-8a-77-ff", "02-a0-a7-8a-77-ff", " | anddre79");
iotkit.addLocInfo(createDeviceObj, "45.540164", "-122.926048", "55.0");
iotkit.addTagInfo(createDeviceObj, "United States");
iotkit.addTagInfo(createDeviceObj, "Oregon");
iotkit.addTagInfo(createDeviceObj, "Hillsboro");
iotkit.addAttributesInfo(createDeviceObj, "vendor", "Intel");
iotkit.addAttributesInfo(c... | sponse received: ', response;
|
FederatedAI/FATE | python/federatedml/transfer_variable/transfer_class/hetero_kmeans_transfer_variable.py | Python | apache-2.0 | 1,974 | 0.006079 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE 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/lic... | tol = self._create_variable(name='host_tol', src=['host'], dst=['arbiter'])
self.centroid_list = self._create_variable(name='centroid_list', | src=['guest'], dst=['host']) |
PyCQA/pylint | pylint/checkers/imports.py | Python | gpl-2.0 | 39,331 | 0.001144 | # Copyright (c) 2006-2015 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
# Copyright (c) 2012-2014 Google, Inc.
# Copyright (c) 2013 buck@yelp.com <buck@yelp.com>
# Copyright (c) 2014-2020 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2014 Brett Cannon <brett@python.org>
# Copyright (c) 2014 Arun Persaud <aru... | rysinger <vapier@gmail.com>
# Copyright (c) 2018 Sushobhi | t <31987769+sushobhit27@users.noreply.github.com>
# Copyright (c) 2018 Marianna Polatoglou <mpolatoglou@bloomberg.net>
# Copyright (c) 2019-2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
# Copyright (c) 2019, 2021 Nick Drozd <nicholasdrozd@gmail.com>
# Copyright (c) 2019 Hugo van Kemenade <hugovk@users.noreply.gith... |
soerendip42/rdkit | rdkit/DataStructs/VectCollection.py | Python | bsd-3-clause | 6,300 | 0.020635 | # $Id$
#
# Copyright (C) 2005-2006 greg landrum and Rational Discovery LLC
#
# @@ All Rights Reserved @@
# This file is part of the RDKit.
# The contents are covered by th | e terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
from __future__ import print_function
| import copy,struct,sys
from rdkit.six.moves import cPickle
from rdkit.six import iterkeys
from rdkit import six
from rdkit import DataStructs
class VectCollection(object):
"""
>>> vc = VectCollection()
>>> bv1 = DataStructs.ExplicitBitVect(10)
>>> bv1.SetBitsFromList((1,3,5))
>>> vc.AddVect(1,bv1)
>>> bv1... |
rcbops/glance-buildpackage | glance/tests/unit/test_s3_store.py | Python | apache-2.0 | 11,404 | 0.000175 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack, LLC
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this s3 except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/li... | .connection.S3Connection,
'__init__', fake_connection_constructor)
stubs.Set(boto.s3.connection.S3Connection,
'get_bucket', fake_get_bucket)
def format_s3_location(user, key, authurl, bucket, obj):
"""
Helper method that returns a S3 store URI given
the component pieces.
... |
authurl = authurl[7:]
authurl = authurl.strip('/')
return "%s://%s:%s@%s/%s/%s" % (scheme, user, key, authurl,
bucket, obj)
class TestStore(unittest.TestCase):
def setUp(self):
"""Establish a clean test environment"""
self.stubs = stubout.StubO... |
xthan/polyvore | polyvore/fashion_compatibility.py | Python | apache-2.0 | 6,651 | 0.011577 | # Copyright 2017 Xintong Han. 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 ... | "lstm/b_state_feed:0":zero_state})
outputs.append(lstm_output)
for step in ran | ge(int(num_images)-1):
input_feed = np.reshape(emb_seqs[int(num_images)-2-step], [1,-1])
[lstm_state, lstm_output] = sess.run(
fetches=["lstm/b_state:0","b_logits/b_logits/BiasAdd:0"],
feed_dict={"lstm/b_input_feed:0":input_feed,
"lstm/b_state_feed:... |
vadivelmurugank/calltree | calltree/__main__.py | Python | mit | 259 | 0.003861 | """
apiparse
Parse API and API groups from sources. List the API occurences from all
directories and sub directories
"""
|
# Main Routine
if __name__ == "__main__":
import calltree
f = calltree.calltree.calltree()
f.showtree()
f.s | howgraph()
|
keisetsu/joblist | get_jobs.py | Python | mit | 1,182 | 0.00423 | import pprint
from datetime import timedelta
from indeed import IndeedJobList
from kansasworks import WorksJobList
from jobview import JobView
result = []
one_week_ago = timedelta(days=7)
one_day_ago = timedelta(days=1)
two_days_ago = timedelta(days=2)
indeed = IndeedJobList()
# result.extend(indeed.collect_results(... | r, oldest=two_days_ago))
# result.extend(indeed.collect_results(' | ', '80020', '25', oldest=one_week_ago))
works = WorksJobList()
result.extend(works.collect_results('python', '66046', '35'))
view = JobView()
with_seen = view.transform(result, include_seen=False)
view.render(with_seen, mark_seen=True)
|
Jumpscale/docker | install/bootstrap_js.py | Python | apache-2.0 | 978 | 0.023517 | #BOOTSTRAP CODE
try:
from urllib3.request import urlopen
except ImportError:
from url | lib import urlopen
import random
handle = urlopen("https://raw.githubusercontent.com/Jumpscale/jumpscale_core7/master/install/InstallTools.py?%s"%random.randint(1, 10000000)) #this is to protect against caching proxy servers
exec(handle.read())
#look at methods in https://github.com/Jumpscale/jumpscale_core7/blob/mas... | execution of items
#there are many more functions available in jumpscale
print "prepare jumpscale docker"
do.installDocker()
url="https://github.com/Jumpscale/docker"
do.pullGitRepo(url,dest=None,login=None,passwd=None,depth=None,ignorelocalchanges=False,reset=False,branch="master")
cmd="cd /opt/code/github/jump... |
pombredanne/click-log | tests/test_basic.py | Python | mit | 448 | 0 | import logging
import click
from c | lick.testing import CliRunner
import click_log
import pytest
test_logger = logging.getLogger(__name__)
@pytest.fixture
def runner():
return CliRunner()
def test_basic(runner):
@click.command()
@click_log.init()
def cli():
test_logger.error('damn')
result = runner.invoke(cli, catch_e... | sult.output == 'error: damn\n'
|
NixaSoftware/CVis | venv/lib/python2.7/site-packages/pandas/tests/indexes/datetimes/test_construction.py | Python | apache-2.0 | 25,835 | 0 | import pytest
import pytz
import numpy as np
from datetime import timedelta
import pandas as pd
from pandas import offsets
import pandas.util.testing as tm
from pandas._libs import tslib, lib
from pandas._libs.tslib import OutOfBoundsDatetime
from pandas import (DatetimeIndex, Index, Timestamp, datetime, date_range,
... | etimeIndex)
result = Index([Timestamp('2011-01-01 10:00', tz='Asia/Tokyo'),
Timestamp('2011-01-02 10:00', tz='US/Eastern')],
name='idx')
exp = Index([Timestamp('2011-01-01 10:00', tz='Asia/Tokyo'),
Timestamp('2011-01-02 10:00', tz='US/... | _index_equal(result, exp, exact=True)
assert not isinstance(result, DatetimeIndex)
# length = 1
result = Index([Timestamp('2011-01-01')], name='idx')
exp = DatetimeIndex([Timestamp('2011-01-01')], name='idx')
tm.assert_index_equal(result, exp, exact=True)
assert isinstan... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.