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 |
|---|---|---|---|---|---|---|---|---|
pearsonlab/thunder | thunder/utils/context.py | Python | apache-2.0 | 36,355 | 0.004924 | """ Simple wrapper for a Spark Context to provide loading functionality """
import os
from thunder.utils.common import checkParams, handleFormat, raiseErrorIfPathExists
from thunder.utils.datasets import DataSets
from thunder.utils.params import Params
class ThunderContext():
"""
Wrapper for a SparkContext ... |
minPartitions: int, optional, default = SparkContext.m | inParallelism
Minimum number of Spark partitions to use, only for text.
maxPartitionSize : int, optional, default = '32mb'
Maximum size of partitions as a Java-style memory string, e.g. '32mb' or '64mb',
indirectly controls the number of Spark partitions, only for binary.
... |
ProjectQ-Framework/ProjectQ | projectq/cengines/_main_test.py | Python | apache-2.0 | 7,119 | 0.000421 | # -*- coding: utf-8 -*-
# Copyright 2017, 2021 ProjectQ-Framework (www.projectq.ch)
#
# 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.... | id(eng.main_engine) == id(eng)
assert not eng.is_last_engine
assert id(ceng1.next_engine) == id(ceng2)
assert id(ceng1.mai | n_engine) == id(eng)
assert not ceng1.is_last_engine
assert id(ceng2.next_engine) == id(test_backend)
assert id(ceng2.main_engine) == id(eng)
assert not ceng2.is_last_engine
assert test_backend.is_last_engine
assert id(test_backend.main_engine) == id(eng)
assert not test_backend.next_engine
... |
BT-ojossen/website | website_logo/models/company.py | Python | agpl-3.0 | 1,095 | 0 | # -*- coding: utf-8 -*-
############ | ##################################################################
#
# Copyright (C) 2015 Agile Business Group sagl (<http://www.agilebg.com>)
#
# 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 Sof... | l,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <h... |
scjrobertson/xRange | kalman/gaussian.py | Python | gpl-3.0 | 4,271 | 0.012409 | '''Module containing a DensityFunc abstract class, with common probability densities
@since: Jan 10, 2013
@author: kroon
'''
from __future__ import division
import numpy as np
class Gaussian(object):
'''
Class for representing a multi-dimensional Gaussian distribution of dimension d,
given mean and c... | -------
val : scalar
The value of the normal distribution at x.
'''
return np.exp(self.logf(x))
def logf(self, x):
'''
Calculate the log-density at x
Parameters
----------
x : (d,) ndarra | y
Evaluate the log-normal distribution at a single d-dimensional
sample x
Returns
-------
val : scalar
The value of the log of the normal distribution at x.
'''
#x = x[:,np.newaxis]
trans = x - self._mean
mal = -tran... |
ntthuy11/CodeFights | Arcade/04_Python/05_ComplexityOfComprehension/coolPairs.py | Python | mit | 853 | 0.014068 | """ A pair of numbers is considered to be cool if their product is divisible by their sum. More formally,
a pair (i, j) is cool if and only if (i * j) % (i + j) = 0.
Given two lists a and b, find cool pairs with the first number in the pair from a, and the second one from b.
Return the number of different sums of el... | [4, 5, 6, 7, 8] and b = [8, 9, 10, 11, 12], the output should be
coolPairs(a, b) = 2.
There are th | ree cool pairs that can be formed from these arrays: (4, 12), (6, 12) and (8, 8). Their respective
sums are 16, 18 and 16, which means that there are just 2 different sums: 16 and 18. Thus, the output should be
equal to 2.
"""
def coolPairs(a, b):
uniqueSums = {i+j for i in a for j in b if i*j%(i+j) == 0} # ... |
MJuddBooth/pandas | pandas/core/computation/ops.py | Python | bsd-3-clause | 16,387 | 0 | """Operator classes for eval.
"""
from datetime import datetime
from distutils.version import LooseVersion
from functools import partial
import operator as op
import numpy as np
from pandas._libs.tslibs import Timestamp
from pandas.compat import PY3, string_types, text_type
from pandas.core.dtypes.common import is_... | def __unicode__(self):
"""Print a generic n-ary operator and its operands using infix
notation"""
# recurse over the operands
parened = ('({0})'.format(pprint_thing(opr))
for opr in self.operands)
return pprint_thing(' {0} '.format(self.op).join(parened))
... | a boolean operator
if self.op in (_cmp_ops_syms + _bool_ops_syms):
return np.bool_
return _result_type_many(*(term.type for term in com.flatten(self)))
@property
def has_invalid_return_type(self):
types = self.operand_types
obj_dtype_set = frozenset([np.dtype('objec... |
flyingpoops/kaggle-digit-recognizer-team-learning | plot.py | Python | apache-2.0 | 1,298 | 0.008475 | import sys, os, math
import time
import numpy as np
from pandas.io.parsers import read_csv
from sklearn.decomposition import PCA
fro | m sklearn.cross_validation import StratifiedShuffleSplit
from sklearn import metrics
import sklearn.svm as svm
from sklearn.naive_bayes import MultinomialNB
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.lda import LDA
from sklearn.cross_validation import | train_test_split
import matplotlib.pyplot as plt
cut_pt = 1
print ("Reading the file...")
input_res = read_csv(os.path.expanduser("input/train.csv"), nrows=3000) # load pandas dataframe
input_res = input_res.as_matrix()
shape = input_res.shape
number_of_rows = shape[0]
number_of_columns = shape[1]
number_of_fv = nu... |
github/codeql | python/ql/test/query-tests/Security/lib/fabric/__init__.py | Python | mit | 113 | 0 | from .connect | ion import Connection
from .group import Group, SerialGroup, ThreadingGroup
from .tasks i | mport task
|
thonkify/thonkify | src/lib/libfuturize/fixes/fix_order___future__imports.py | Python | mit | 830 | 0 | """
UNFINISHED
Fixer for turning multiple lines like these:
from __future__ impo | rt division
from __future__ import absolute_import
from __future__ import print_function
into a single line like this:
from __future__ import (absolute_import, division, print_function)
This helps with testing of ``futurize``.
"""
from lib2to3 import fixer_base
from libfuturize.fixer_util import future_... | ode):
# """
# Match only once per file
# """
# if hasattr(node, 'type') and node.type == syms.file_input:
# return True
# return False
def transform(self, node, results):
# TODO # write me
pass
|
ruishihan/R7-with-notes | src/python/ioread.py | Python | apache-2.0 | 82 | 0.012195 | import | axi2s_c
import sys
uut = axi2s_c.axi2s_c()
uut.read(sys.argv[1 | ])
|
dergraaf/xpcc | tools/system_design/xmlparser/event.py | Python | bsd-3-clause | 1,538 | 0.048114 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import utils
import xml_utils
from parser_exce | ption import ParserException
class Event(object):
def __init__(self, node):
""" Constructor
Keyword arguments:
node -- | XML node defining this event
"""
self.node = node
self.name = node.get('name')
utils.check_name(self.name)
self.id = None
self.description = None
self.rate = None
self.type = None
def evaluate(self, tree):
if self.node is None:
return
self.id = xml_utils.get_identifier(self.node)
... |
MyRookie/SentimentAnalyse | venv/lib/python2.7/site-packages/numpy/testing/utils.py | Python | mit | 66,431 | 0.001114 | """
Utility function to facilitate testing.
"""
from __future__ import division, absolute_import, print_function
import os
import sys
import re
import operator
import warnings
from functools import partial
import shutil
import contextlib
from tempfile import mkdtemp, mkstemp
from .nosetester import import_nose
from ... | rd library, so it is useful for testing purposes.
"""
import random
from numpy.core import zeros, float64
results | = zeros(args, float64)
f = results.flat
for i in range(len(f)):
f[i] = random.random()
return results
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
inum=-1, format=None, mac... |
ishahid/django-blogg | source/blogg/migrations/0002_comment.py | Python | mit | 1,206 | 0.004146 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blogg', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
... | rue, blank=True)),
('user_agent', models.CharField(max_length=500L, blank=True)),
('published', models.BooleanField(default=True)),
('created', models.DateTimeField(auto_now_add=True)),
('modified', mo | dels.DateTimeField(auto_now=True, auto_now_add=True)),
('post', models.ForeignKey(related_name='comments', to='blogg.Post')),
],
options={
'ordering': ['-created'],
},
bases=(models.Model,),
),
]
|
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/astroid/raw_building.py | Python | apache-2.0 | 15,733 | 0.001525 | # Copyright (c) 2006-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
# Copyright (c) 2014-2016 Claudiu Popa <pcmanticore@gmail.com>
# Copyright (c) 2014 Google, Inc.
# Copyright (c) 2015-2016 Cara Vinson <ceridwenv@gmail.com>
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
... | case such as Exception.args,
# OSError.errno
if issubclass(member, Exception):
instdict = member().__dict__
else:
raise TypeError
except: # pylint: disable=bare-except
pass
else:
for item_name, obj in instdict.items():
valnode = nodes.... | lnode.object = obj
valnode.parent = klass
valnode.lineno = 1
klass.instance_attrs[item_name] = [valnode]
return klass
def _build_from_function(node, name, member, module):
# verify this is not an imported function
try:
code = six.get_function_code(member)
ex... |
autosub-team/autosub | src/plugins/vels_ob/test/test_task.py | Python | gpl-2.0 | 776 | 0 | # coding: utf-8
"""
HDL Testing Platform
REST API for HDL TP # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import | absolute_import
import unittest
import swagger_client
from swagger_client.models.task import Task # noqa: E501
from swagger_client.rest import ApiException
class TestTask(unittest.TestCase):
"""Task unit test stubs"""
def setUp(se | lf):
pass
def tearDown(self):
pass
def testTask(self):
"""Test Task"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.task.Task() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
ZackYovel/studybuddy | server/studybuddy/discussions/migrations/0005_auto_20150430_1645.py | Python | mit | 459 | 0.002179 | # -*- coding: utf-8 | -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('discussions', '0004_auto_20150430_1641'),
]
operations = [
migrations.AlterField(
model_name='discussion',
name='origina... | related_name='OP'),
),
]
|
Scoudem/audiolyze | inputhandler.py | Python | mit | 1,620 | 0 | '''
File: input.py
Author: Tristan van Vaalen
Handles user input
'''
import signal
import sys
import verbose
v = verbose.Verbose()
class InputHandler():
def __init__(self):
v.debug('Initializing input handler').indent()
self.running = True
self.signal_level = 0
| v.debug('Registering signal handler').unindent()
signal.signal(signal.SIGINT, self.signal_handler)
def test(self):
pass
def signal_handler(self, signal, frame):
self.signal_level += 1
if self.signal_level == 1:
| self.running = False
else:
sys.exit(0)
def output_options(self):
v.write(
'Available options:\n' +
' - help: prints this message\n' +
' - exit: exit program'
' - test: magic'
)
def get(self):
v.debug('Entering... |
CSB-IG/natk | ninnx/pruning/mi_triangles.py | Python | gpl-3.0 | 1,793 | 0.026771 | import networkx as nx
import itertools
import matplotlib.pyplot as plt
fig = plt.figure()
fig.subpl | ots_adjust(left=0.2, wspace=0.6)
G = nx.Graph()
G.add_edges_from([(1,2,{'w': 6}),
(2,3,{'w': 3}),
(3,1,{'w': 4}),
(3,4,{' | w': 12}),
(4,5,{'w': 13}),
(5,3,{'w': 11}),
])
import pprint
# detect triangles
triangles = []
for trio in itertools.combinations(G.nodes(), 3):
vertices = []
for v in itertools.combinations(trio, 2):
vertice = G.get_edge_data(*v)
if vertic... |
dboddie/python-diana | configure.py | Python | gpl-2.0 | 5,321 | 0.008081 | #!/usr/bin/env python
import glob, os, sys
import sipconfig
from PyQt4 import pyqtconfig
def get_diana_version():
depends = filter(lambda line: line.startswith("Depends:"),
open("debian/control").readlines())
for line in depends:
pieces = line.split()
for piece in pi... | .exit(1)
# Create the Makefile (within the diana directory).
makefile = pyqtconfig.QtGuiModuleMakef | ile(
config, build_file, dir=output_dir,
install_dir=dest_pkg_dir,
qt=["QtCore", "QtGui", "QtNetwork", "QtXml", "QtXmlPatterns"]
)
if module == "diana":
makefile.extra_include_dirs += [
diana_inc_dir,
os.path.jo... |
heitorschueroff/ctci | ch5/5.03_Flip_Bit_To_Win/test_flip_bit_to_win.py | Python | mit | 269 | 0 | import | unittest
from flip_bit_to_win import flip_bit
class TestFlipBit(unittest.TestCase):
def test_flip_bit(self):
self.assertEquals(flip_bit(0b1011100101), 4)
self.assertEquals(flip_bit(1775), 8)
if __name__ == '__main__':
unittest.main( | )
|
mvdroest/RTLSDR-Scanner | src/misc.py | Python | gpl-3.0 | 6,123 | 0.000327 | #
# rtlsdr_scan
#
# http://eartoearoak.com/software/rtlsdr-scanner
#
# Copyright 2012 - 2015 Al Brown
#
# A frequency scanning GUI for the OsmoSDR rtl-sdr library at
# http://sdr.osmocom.org/trac/wiki/rtl-sdr
#
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gene... | sin, cos, asin, sqrt
import math
import os
import socket
import sys
from threading import Thread
import time
import urllib
import serial.tools.list_ports
from constants import SAMPLE_RATE, TIMESTAMP_FILE
class RemoteControl(object):
def __init__(self):
self.connected = False
self.socket = No | ne
def __connect(self):
if not self.connected:
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.settimeout(1)
self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.socket.connect(('l... |
gpospelov/BornAgain | Tests/Functional/PyFit/minimizer_api.py | Python | gpl-3.0 | 2,947 | 0.000679 | """
Testing python specific API for M | inimizer related classes.
"""
import sys
import os
import unittest
import bornagain as ba
class TestMinimizerHelper:
def __init__(self):
self.m_ncalls = 0
self.m_pars = | None
def objective_function(self, pars):
self.m_ncalls += 1
self.m_pars = pars
return 42.0
class MinimizerAPITest(unittest.TestCase):
def test_ParameterAttribute(self):
"""
Testing p.value attribute
"""
par = ba.Parameter("par", 1.0)
self.asser... |
ar4s/django | tests/messages_tests/base.py | Python | bsd-3-clause | 14,187 | 0.000705 | from django.contrib.messages import constants, get_level, set_level, utils
from django.contrib.messages.api import MessageFailure
from django.contrib.messages.constants import DEFAULT_LEVELS
from django.contrib.messages.storage import base, default_storage
from django.contrib.messages.storage.base import Message
from d... | repr(storage),
f'<{self.storage_class.__qualname__}: request=<HttpRequest>>',
)
def test_add(self):
storage = self.get_storage()
self.assertFalse | (storage.added_new)
storage.add(constants.INFO, 'Test message 1')
self.assertTrue(storage.added_new)
storage.add(constants.INFO, 'Test message 2', extra_tags='tag')
self.assertEqual(len(storage), 2)
def test_add_lazy_translation(self):
storage = self.get_storage()
re... |
endlessm/chromium-browser | chrome/updater/win/installer/create_installer_archive.py | Python | bsd-3-clause | 13,828 | 0.011065 | # Copyrig | ht 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script to create the Chrome Updater Installer archive.
This script is used to create a | n archive of all the files required for a
Chrome Updater install in appropriate directory structure. It reads
updater.release file as input, creates updater.7z ucompressed archive, and
generates the updater.packed.7z compressed archive.
"""
import ConfigParser
import glob
import optparse
import os
import shutil... |
juan-cardelino/matlab_demos | ipol_demo-light-1025b85/app_available/75/app.py | Python | gpl-2.0 | 17,698 | 0.00825 | """"
Meaningful Scales Detection: an Unsupervised Noise Detection Algorithm for \
Digital Contours
Demo Editor: B. Kerautret
"""
from lib import base_app, build, http, image, config
from lib.misc import app_expose, ctime
from lib.base_app import init_app
import cherrypy
from cherrypy import TimeoutError
import os.path... | img = image(self.work_dir + 'input_0.png')
img.save(self.work_dir + 'input_0_selection.png')
img.save(self.work_dir + 'input_0_selection.pgm')
# initialize subimage parameters
self.cfg['param'] = {'x1 | ':-1, 'y1':-1, 'x2':-1, 'y2':-1}
self.cfg.save()
return self.tmpl_out('params.html')
@cherrypy.expose
@init_app
def wait(self, **kwargs):
"""
params handling and run redirection
"""
# save and validate the parameters
# handle image crop if used
... |
shreya2111/Recommender-System | outgoing_call_count.py | Python | gpl-2.0 | 1,175 | 0.095319 | import json
import os
import datetime
for i in range(9):
try:
os.chdir('../call_record/')
with open('callsSortedperson_'+str(i)+'.json','r') as f:
data=json.load(f)
print 'User: ',i
#print len(data)
friends=[]
for j in range(len(data)):
#print data[j][0]
friends.append(data[j][0])
... | =0
for j in range(len(data)):
if data[j][1]==2:
#In 86400 seconds all outgoing calls to one person
if k==data[j][0]:
#if da | ta[j][2]<=(float(time)+86400):
t=datetime.datetime.fromtimestamp(data[j][2]).strftime("%Y-%m-%d %H:%M:%S") #IST
#print t
c+=1
#print c,k
calls.append(c)
#print len(calls)
k=[]
c=0
for j in range(len(friends)):
k.append(j+1)
if calls[j]==0:
c+=1
print c
#print z... |
Jelby/Hatalogico | ledKnightRider16.py | Python | mit | 9,635 | 0.019512 | #!/usr/bin/python
# ===========================================================================
# Hatalogico KNIGHT RIDER for 8 LEDs - powered by Adafruit's Libraries
# -------------------------------------------------
# Date: 12/4/2015
# Author: John Lumley
#
# BIG THANKS TO ADAFRUIT INDUSTRIES FOR MAKING THIS POSSIB... | D FOLDER OF REQUIRED LIBRARY
sys.path.append("Adafruit/Adafruit_PWM_Servo_Driver")
# FINALLY LOAD THE LIBRARY
from Adafruit_PWM_Servo_Driver import PWM
LED_PIN_0 = 0
LED_PIN_1 = 2
LED_PIN_2 = 4
LED_PIN_3 = 6
LED_PIN_4 = 8
LED_PIN_5 = 10
LED_PIN_6 = 12
LED_PIN_7 = 14
LED_PIN_8 = 1
LED_PIN_9 = 3
LED_PIN_10 = 5
LED_PIN_1... | GHT_5=3800
BRIGHT_6=4000
BRIGHT_7=4095
# BUILD 16 ARRAYS OF 8 POSITIONS/VALUES FOR PWM LOOP
position = {}
position[0] = [ BRIGHT_0, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7 ]
position[1] = [ BRIGHT_1, BRIGHT_0,... |
pradeepnazareth/NS-3-begining | src/lte/bindings/callbacks_list.py | Python | gpl-2.0 | 6,324 | 0.006167 | callback_classes = [
['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['... | 3::empty'],
['void', 'unsigned short', 'unsigned short', 'double', 'double', 'bool', 'unsigned char', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::Socket>', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['bool', 'ns3::P... | empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::Socket>', 'const ns3::Address &', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'],
['void', 'ns3::Ptr<ns3::Socket>', 'unsigned int', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'... |
torchmed/torchmed | torchmed/views.py | Python | mit | 364 | 0.002747 | from django.shortcuts import render
from djan | go.utils.translation import activate
def inde | x(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
# context = {'latest_question_list': latest_question_list}
# activate('pt-br')
# print(request.LANGUAGE_CODE)
context = {}
return render(request, 'index.html', context)
|
yoshinarikou/MilleFeuilleRaspberryPi | milpython/MoistureTest.py | Python | mit | 835 | 0.027545 | ########################################################################
# MCU Gear(R) system Sample Code
# Auther:y.kou.
# web site: http://www.milletool.com/
# Date : 8/OCT/2016
#
########################################################################
#Revision Information
#
#########################################... | mil
from milpy import milMod
from milpy import wiringdata
from milpy import Moisuture
import time
wiringdata.initIO()
modA = milMod.milMod(Moisuture.getIn | fo(0))
if __name__=='__main__':
try:
while(1):
modA.connect()
readData = Moisuture.read(modA)
print "readData = ",readData
time.sleep(1)
modA.disconnect()
except KeyboardInterrupt:
print("detect key interrupt [ctrl]+ [C] \n")
mil.cleanup()
wiringdata.cleanup()
|
arnavd96/Cinemiezer | myvenv/lib/python3.4/site-packages/botocore/retryhandler.py | Python | mit | 13,631 | 0.000147 | # Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/
# Copyright 2012-2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http... | ig = policies[key]
checkers.append(_create_single_checker(current_config))
retry_exception = _extract_retryable_exception(current_config)
if retry_exception is not None:
retryable_exceptions.extend(retry_excep | tion)
if operation_name is not None and config.get(operation_name) is not None:
operation_policies = config[operation_name]['policies']
for key in operation_policies:
checkers.append(_create_single_checker(operation_policies[key]))
retry_exception = _extract_retryable_excepti... |
hyoklee/siphon | siphon/cdmr/ncstream.py | Python | mit | 5,147 | 0.000971 | from __future__ import print_function
import zlib
import numpy as np
from . import ncStream_pb2 as stream # noqa
MAGIC_HEADER = b'\xad\xec\xce\xda'
MAGIC_DATA = b'\xab\xec\xce\xba'
MAGIC_VDATA = b'\xab\xef\xfe\xba'
MAGIC_VEND = b'\xed\xef\xfe\xda'
MAGIC_ERR = b'\xab\xad\xba\xda'
def read_ncstream_messages(fobj):
... | data.ParseFromString(read_block(fobj))
if data.dataType in (stream.STRING, stream.OPAQUE) or data.vdata:
dt = _dtypeLookup.get(data.dataType, np.object_)
num_obj = read_var_int(fobj)
| blocks = np.array([read_block(fobj) for _ in range(num_obj)], dtype=dt)
messages.append(blocks)
elif data.dataType in _dtypeLookup:
data_block = read_numpy_block(fobj, data)
messages.append(data_block)
elif data.dataType in (stream.STR... |
Eigenstate/msmbuilder | runtests.py | Python | lgpl-2.1 | 6,293 | 0.000953 | #!/usr/bin/env python
"""
runtests.py [OPTIONS] [-- ARGS]
Run tests, building the project first.
Examples::
$ python runtests.py
$ python runtests.py -t {SAMPLE_TEST}
"""
from __future__ import division, print_function
PROJECT_MODULE = "msmbuilder"
PROJECT_ROOT_FILES = ['msmbuilder', 'LICENSE', 'setup.py']
... | --ipython", action='store_true', default=False,
help="Launch an ipython shell instead of nose")
parser.add_argument("args", metavar="ARGS", default=[], nargs=REMAINDER,
help="Arguments to pass to Nose")
args = parser.parse_args(argv)
if not | args.no_build:
site_dir, dst_dir = build_project(args)
sys.path.insert(0, site_dir)
os.environ['PYTHONPATH'] = site_dir
os.environ['PATH'] = dst_dir + "/bin:" + os.environ['PATH']
if args.build_only:
sys.exit(0)
if args.ipython:
commands = ['ipython']
else:
... |
izapolsk/integration_tests | cfme/tests/cloud/test_tag_mapping.py | Python | gpl-2.0 | 9,719 | 0.001338 | import fauxfactory
import pytest
from widgetastic.utils import partial_match
from wrapanapi.exceptions import ImageNotFoundError
from cfme import test_requirements
from cfme.cloud.provider.azure import AzureProvider
from cfme.cloud.provider.ec2 import EC2Provider
from cfme.exceptions import ItemNotFound
from cfme.mark... | msg = 'Failed looking up template [{}] from CFME on provider: {}'.format(name, provider)
logger.exception(msg) |
pytest.skip(msg)
return collection.instantiate(name=name, provider=provider), mgmt_item, entity_type
def tag_components():
# Return tuple with random tag_label and tag_value
return (
fauxfactory.gen_alphanumeric(15, start="tag_label_"),
fauxfactory.gen_alphanumeric(15, start="tag_... |
jawilson/home-assistant | tests/components/metoffice/const.py | Python | apache-2.0 | 2,161 | 0.000463 | """Helpers for testing Met Office DataPoint."""
from homeassistant.components.metoffice.const import DOMAIN
from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME
TEST_DATETIME_STRING = "2020-04-25T12:00:00+00:00"
TEST_API_KEY = "test-metoffice-api-key"
TEST_LATITUDE_WAVERTREE = 53.3... | "uv_index", "6"),
"precipitation": ("probability_of_precipitation", "0"),
"wind_direction": ("w | ind_direction", "E"),
"wind_gust": ("wind_gust", "7"),
"wind_speed": ("wind_speed", "2"),
"humidity": ("humidity", "60"),
}
WAVERTREE_SENSOR_RESULTS = {
"weather": ("weather", "sunny"),
"visibility": ("visibility", "Good"),
"visibility_distance": ("visibility_distance", "10-20"),
"temperatu... |
mikebsg01/Contests-Online | UVa/12015-GoogleisFeelingLucky.py | Python | mit | 604 | 0.038079 | from sys import stdin
def readLine():
return stdin.readline().strip()
def readInt():
return int(readLine())
def readInts():
return list(map(int, readLine().split()))
def main():
T = readInt()
for i in range(T):
pages = [{'url': None, 'v': 0} for j in range(10)]
for j in range(10):
pages[j]['url'], pag... | es, key=lambda x: x['v'])['v']
pages = list(filter(lambda x: x['v'] == maxVal, pages))
print('Case #%d:' %(i + 1))
for p i | n pages:
print(p['url'])
if __name__ == '__main__':
main()
|
Gibbsdavidl/miergolf | src/corEdges.py | Python | bsd-3-clause | 3,914 | 0.020184 | import sys
import numpy as np
from copy import copy, deepcopy
import multiprocessing as mp
from numpy.random import shuffle, random, normal
from math import log, sqrt, exp, pi
import itertools as it
from scipy.stats import gaussian_kde, pearsonr
from scipy.stats import ttest_1samp
from itertools import product
try:
... | else:
return( ([],[]) )
def corEdges(exprfile, genefile, fileout, reps, cpus, g1, g2):
genes = open(genefile,'r').read().strip().split("\n")
dat = open(exprfile,'r').read().strip().split("\n")
dats = map(lambda x: x.split("\t"), dat)
fout = open(fileout,'w')
(fromx,toy) = prepGene... | \t"+ "\t".join(map(str,res0)) +"\n")
fout.close()
def maxLagCorEdges(exprfile, genefile, fileout, reps, cpus, ylmax, g1, g2):
genes = open(genefile,'r').read().strip().split("\n")
dat = open(exprfile,'r').read().strip().split("\n")
dats = map(lambda x: x.split("\t"), dat)
fout = open(fileo... |
CharlesGust/django-imagr | imagr_site/imagr_app/migrations/0001_initial.py | Python | mit | 5,413 | 0.00388 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [... | ('date_modified', models.DateField(auto_now=True)),
('date_published', models.DateField()),
| ('published', models.CharField(default=b'private', max_length=7, choices=[(b'private', b'Private Photo'), (b'shared', b'Shared Photo'), (b'public', b'Public Photo')])),
('image_url', models.CharField(default=b'Photo Not Found', max_length=1024)),
('user', models.ForeignKe... |
geobricks/geobricks_raster_correlation | geobricks_raster_correlation/cli/cli_argh.py | Python | gpl-2.0 | 493 | 0.006085 | from argh import dispatch_commands
from argh.decorators import named, arg
from geobricks_raster_correlation.core.raster_correlation_core import get_correlation
@named('corr')
@arg('--bins', default=150, help='Bins')
def cli_get_correlation(file1, file2, **kwargs): |
corr = get_correlation(file1, file2, kwargs['bins'])
print "Series: ", corr['series']
print "Stats: ", corr['stats']
def main():
dispatch_commands([cli_get_correlation])
if __name__ == '__main__':
main() | |
icloudrnd/automation_tools | openstack_dashboard/dashboards/groups/instances/panel.py | Python | apache-2.0 | 250 | 0.004 | from django.utils.translation import ugettext_ | lazy as _
import horizon
from openstack_dashboard.dashboards.groups import dashboard
class Instances(horizon.Panel):
name = _("Groups") |
slug = "instances"
dashboard.Groups.register(Instances)
|
ateska/striga2-sampleapp | app/appweb/context.py | Python | unlicense | 58 | 0.034483 | import striga
class Cust | omContext(striga.context):
| pass
|
ryfeus/lambda-packs | HDF4_H5_NETCDF/source2.7/h5py/tests/old/test_h5f.py | Python | mit | 2,360 | 0.002119 | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement. |
from __future__ import absolute_import
import tempfile
import shutil
import os
from h5py import File
from ..common import TestCase
| class TestFileID(TestCase):
def test_descriptor_core(self):
with File('TestFileID.test_descriptor_core', driver='core', backing_store=False) as f:
with self.assertRaises(NotImplementedError):
f.id.get_vfd_handle()
def test_descriptor_sec2(self):
dn_tmp = tempfile.mkd... |
isaac-s/cloudify-manager | tests/integration_tests/tests/agentless_tests/scale/test_scale_in.py | Python | apache-2.0 | 9,915 | 0 | ########
# Copyright (c) 2013 GigaSpaces Technologies Ltd. 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... | e(self):
expectations = self.deploy_app('scale5')
expectations['compute']['new']['install'] = 2
expectations['db']['new']['install'] = 4
expectations['db']['new']['rel_install'] = 8
self.deployment_assertions(expectations)
expectations = self.scale(parameters={
... | expectations['compute']['existing']['install'] = 1
expectations['compute']['removed']['install'] = 1
expectations['compute']['removed']['uninstall'] = 1
expectations['db']['existing']['install'] = 2
expectations['db']['existing']['rel_install'] = 4
expectations['db']['removed... |
woodenbrick/mtp-lastfm | mtplastfm/webservices.py | Python | gpl-3.0 | 7,361 | 0.01277 | # Copyright 2009 Daniel Woodhouse
#
#This file is part of mtp-lastfm.
#
#mtp-lastfm 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.
#
#mtp... | rl, data=post_values)
try:
url_handle = urllib2.urlopen(req)
response = url_handle.readlines()[1]
l = response.find('"') + 1
r = response.rf | ind('"')
response = response[l:r]
return response
except urllib2.URLError, error:
return error
except httplib.BadStatusLine, error:
return error
def get_user_top_tags(self, username, limit=15):
#method user.getTopTags
#Params
... |
jiangzhuo/kbengine | kbe/src/lib/python/Lib/test/test_random.py | Python | lgpl-3.0 | 31,638 | 0.002497 | import unittest
import unittest.mock
import random
import time
import pickle
import warnings
from functools import partial
from math import log, exp, pi, fsum, sin
from test import support
class TestBasicOps:
# Superclass with tests common to all generators.
# Subclasses must arrange for self.gen to retrieve t... | ertEqual(len(un | iq), k)
self.assertTrue(uniq <= set(population))
self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
# Exception raised if size of sample exceeds that of population
self.assertRaises(ValueError, self.gen.sample, population, N+1)
def test_sample_distribution(se... |
hzlf/openbroadcast.org | website/apps/ac_tagging/widgets.py | Python | gpl-3.0 | 4,147 | 0.001206 | from django.forms.widgets import TextInput
from django.core.urlresolvers import reverse
from django.conf import settings
from django.utils.safestring import mark_safe
class TagAutocompleteTagIt(TextInput):
def __init__(self, max_tags, *args, **kwargs):
self.max_tags = (
max_tags
if... | n.js"
)
jqueryui_file = getattr(
settings, "TAGGING_AUTOCOMPLETE_JQUERY_UI_FILE", jqueryui_default
)
# if a custom jquery ui file has been specified
if jqueryui_file != jqueryui_default:
# determine path
jqueryui_file = "%s%s" % (js_base_url, j... | jqueryui_file,
"%sjquery.tag-it.js" % js_base_url,
)
# custom css can also be overriden in settings
css_list = getattr(
settings,
"TAGGING_AUTOCOMPLETE_CSS",
["%scss/ui-autocomplete-tag-it.css" % js_base_url],
)
# check ... |
sinnwerkstatt/landmatrix | apps/grid/forms/deal_action_comment_form.py | Python | agpl-3.0 | 3,733 | 0.001607 | from django import forms
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
from apps.grid.fields import TitleField, UserModelChoiceField
from apps.grid.widgets import CommentInput
from .base_form import BaseForm
class DealActionCommentForm(BaseForm):
exclude_i... | lly_updated_history = forms.CharField(
# required=False, label=_("Fully updated history"),
# widget=forms.Textarea(attrs={"readonly":True, "cols": 80, "rows": 5}))
tg_not_public = TitleField(required=False, label="", initial=_("P | ublic deal"))
not_public = forms.BooleanField(
required=False,
label=_("Not public"),
help_text=_("Please specify in additional comment field"),
)
not_public_reason = forms.ChoiceField(
required=False, label=_("Reason"), choices=NOT_PUBLIC_REASON_CHOICES
)
tg_not_publ... |
microdee/IronHydra | src/IronHydra/Lib/tarfile.py | Python | mit | 88,997 | 0.001888 | #!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#-------------------------------------------------------------------
# tarfile.py
#-------------------------------------------------------------------
# Copyright (C) 2002 Lars Gustäbel <lars@gustaebel.de>
# All rights reserved.
#
# Permission is hereby granted, fre... | _IFDIR = 0040000 # directory
S_IFCHR = 0020000 # character device
S_IFIFO = 0010000 # fifo
TSUID = 04000 # set UID on e | xecution
TSGID = 02000 # set GID on execution
TSVTX = 01000 # reserved
TUREAD = 0400 # read by owner
TUWRITE = 0200 # write by owner
TUEXEC = 0100 # execute/search by owner
TGREAD = 0040 # read by group
TGWRITE = 0020 # write by group
TGEXEC =... |
python-control/python-control | control/tests/config_test.py | Python | bsd-3-clause | 12,736 | 0.000157 | """config_test.py - test config module
RMM, 25 may 2019
This test suite checks the functionality of the config module
"""
from math import pi, log10
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import cleanup as mplcleanup
import numpy as np
import pytest
import control as ct
@pytest.mark.u... | def test_custom_bode_default(self):
ct.config.defaults['freqplot.dB'] = True
ct.config.defaults['freqplot.deg'] = True
ct.config.defaults['freqplot.Hz'] = True
# Generate a Bode plot
plt.figure()
omega = np.logspace(-3, 3, 100)
ct.bode_plot(self.sys, omega, dB... | (plt.gcf().axes[0]).get_lines())[0]).get_data()
np.testing.assert_almost_equal(mag_y[0], 20*log10(10), decimal=3)
# Override defaults
plt.figure()
ct.bode_plot(self.sys, omega, Hz=True, deg=False, dB=True)
mag_x, mag_y = (((plt.gcf().axes[0]).get_lines())[0]).get_data()
... |
auto-mat/klub | local_migrations/migrations_helpdesk/0028_auto_20190826_2034.py | Python | gpl-3.0 | 2,149 | 0.002792 | # Generated by Django 2.2.4 on 2019-08-26 18:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('helpdesk', '0027_auto_20190826_0700'),
]
operations = [
migrations.AlterFi... | fault_owner', to=settings.AUTH_USER_MODEL, verbose_name='Default owner'),
),
migrations.AlterField(
model_name='savedsearch',
name | ='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='User'),
),
migrations.AlterField(
model_name='ticket',
name='assigned_to',
field=models.ForeignKey(blank=True, null=True, on_delete=dja... |
ksetyadi/Sahana-Eden | models/delphi.py | Python | mit | 9,575 | 0.014413 | # coding: utf8
"""
Delphi decision maker
"""
module = "delphi"
if deployment_settings.has_module(module):
########
# Groups
########
resourcename = "group"
tablename = module + "_" + resourcename
table = db.define_table(tablename, timestamp,
Field("name", notnu... | ########
resourcename = "problem"
tablename = module + "_" + resourcename
table = db.define_table(tablename,
Field("group_id", db.delphi_group, notnull=True),
Field("name", notnull=True),
Field("description", "text"),
... | Field("criteria", "text", notnull=True),
Field("active", "boolean", default=True),
Field("created_by", db.auth_user, writable=False, readable=False),
Field("last_modification", "datetime", default=request.now, writable=... |
Djabbz/wakatime | tests/utils.py | Python | bsd-3-clause | 1,355 | 0.002214 | # -*- coding: utf-8 -*-
import logging
from wakatime.compat import u
try:
import mock
except ImportError:
import unittest.mock as mock
try:
# Python 2.6
import unittest2 as unittest
except ImportError:
# Python >= 2.7
import unittest
class TestCase(unittest.TestCase):
patch_thes | e = []
def setUp(self):
# disable logging while testing
logging.disable(logging.CRITICAL)
self.patched = {}
if hasattr(self, 'patch_these'):
for patch_this in self.patch_these:
namespace = patch_this[0] if isinstance(patch_this, (list, set)) else patch_t... | amespace)
mocked = patcher.start()
mocked.reset_mock()
self.patched[namespace] = mocked
if isinstance(patch_this, (list, set)) and len(patch_this) > 0:
retval = patch_this[1]
if callable(retval):
... |
CKPalk/ProbabilisticMethods | A5/hw5_start.py | Python | mit | 4,767 | 0.064821 | # CIS 410/510pm
# Homework 5 beta 0.0.1
# Cameron Palk
# May 2016
#
# Special thanks to Daniel Lowd for the skeletor code
import sys
import tokenize
from functools import reduce
global_card = []
num_vars = 0
''' Calc Strides
'''
def calcStrides( scope ):
rev_scope = list( reversed( scope ) )
res = [ 1 ] + [ 0 ] *... | ors, possibleVariables ):
return { v: factorCountWithVar(factors,v) for v in range( num_vars ) if v in possibleVariables }
''' Compute Partition Function
@input factors An array of Factor objects representing the graph
@return [float] The partition function ( why is it called a function? )
'''
def computePartit... | um( f.vals )
return z
#
''' Main '''
def main():
# Read file
factors = read_model()
# Computer partition function
z = computePartitionFunction( factors )
# Print results
print( "Z =", z )
return
# Run main if this module is being run directly
if __name__ == '__main__':
main()
|
mlperf/training_results_v0.7 | NVIDIA/benchmarks/maskrcnn/implementations/pytorch/demo/predictor.py | Python | apache-2.0 | 15,180 | 0.000791 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import cv2
import torch
from torchvision import transforms as T
from maskrcnn_benchmark.modeling.detector import build_detection_model
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
from maskrcnn_benchmark.structures.image_l... | on = predictions[0]
# reshape prediction (a BoxList) into the original image size
height, width = original_image.shape[:-1]
prediction = prediction.resize((width | , height))
if prediction.has_field("mask"):
# if we have masks, paste the masks in the right position
# in the image, as defined by the bounding boxes
masks = prediction.get_field("mask")
# always single image is passed at a time
masks = self.masker([... |
simpeg/simpeg | SimPEG/electromagnetics/utils/EMUtils.py | Python | mit | 149 | 0.006711 | from ...utils.code_utils import deprecate_module
deprecate_mod | ule("EMUtils", "waveform_utils", "0.16.0", error= | True)
from .waveform_utils import *
|
aLaix2/O-Nes-Sama | DebuggerClient/Breakpoint.py | Python | gpl-3.0 | 1,060 | 0.00283 | class Breakpoint():
def __init__(self, breakpointNumber):
self.breakpointNumber = breakpointNumber
class BreakpointPPUByTime(Breakpoint):
def __init__(self, breakpointNumber, scanline, tick):
Breakpoint.__init__(self, breakpointNumber)
self._scanline = scanline
self._t... | ck
def toString(self):
| return 'Scanline = {self._scanline:s}, Tick = {self._tick:s}'.format(**locals())
class BreakpointPPUByAddress(Breakpoint):
def __init__(self, breakpointNumber, address):
Breakpoint.__init__(self, breakpointNumber)
self._address = address
def toString(self):
return 'Addr... |
mattiasgiese/squeezie | app/master.py | Python | mit | 476 | 0.021008 | #!/usr/bin/env python
from flask import Flask, jsonify, request, abort, render_template
app = Flask(__name__)
@app.route("/",methods=['GET'])
def index() | :
if request.method == 'GET':
return render_template('index.html')
else:
abort(400)
@app.route("/devices",methods=['GET'])
def devices():
if request.method == 'GET':
return render_template('devices.html')
else:
abort(400)
if __name__ == "__ | main__":
app.debug = True
app.run(host='0.0.0.0')
|
ConeyLiu/spark | python/pyspark/ml/tests/test_param.py | Python | apache-2.0 | 16,252 | 0.002031 | # -*- coding: utf-8 -*-
#
# 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 "L... | self.assertTrue(all([type(v) == int for v in vs.getIndices()]))
self.assertRaises(TypeError, lambda: VectorSlicer(indices=["a", "b"]))
| def test_list_float(self):
b = Bucketizer(splits=[1, 4])
self.assertEqual(b.getSplits(), [1.0, 4.0])
self.assertTrue(all([type(v) == float for v in b.getSplits()]))
self.assertRaises(TypeError, lambda: Bucketizer(splits=["a", 1.0]))
def test_list_list_float(self):
b = Bu... |
iemejia/incubator-beam | sdks/python/apache_beam/io/external/xlang_kafkaio_it_test.py | Python | apache-2.0 | 4,950 | 0.005253 | #
# 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 us... | anguage governing permissions and
# limitations under the License.
#
"""Integrat | ion test for Python cross-language pipelines for Java KafkaIO."""
from __future__ import absolute_import
import contextlib
import logging
import os
import socket
import subprocess
import time
import typing
import unittest
import apache_beam as beam
from apache_beam.io.external.kafka import ReadFromKafka
from apache_... |
ManiacalLabs/BiblioPixelAnimations | BiblioPixelAnimations/circle/swirl.py | Python | mit | 586 | 0 | from bibliopixel.animation.circle import Circle
from bibliopixel.colors import palettes
|
class Swirl(Circle):
COLOR_DEFAULTS = ('palette', palettes.get('three_sixty')),
def __init__(self, layout, angle=12, **kwds):
super().__init__(layout, **kwds)
self.angle = angle
def pre_run(self):
self._step = 0
def step(self, amt=1):
for a in range(0, ... |
self._step += amt
|
cbentes/texta | dataset_importer/document_preprocessor/preprocessors/text_tagger.py | Python | gpl-3.0 | 3,426 | 0.007589 | from task_manager.tag_manager.tag_manager import TaggingModel
from task_manager.models import Task
import numpy as np
import json
enabled_tagger_ids = [tagger.pk for tagger in Task.objects.filter(task_type='train_tagger').filter(status='completed')]
enabled_taggers = {}
# Load Tagger models
for _id in enabled_tagger... | gger_descriptions.append(tagger.description)
result_vector = tagger.tag(texts)
results.append(result_vector)
results_transposed = np.array(results).transpose()
for i,tagger_ids in enumerate(res | ults_transposed):
positive_tag_ids = np.nonzero(tagger_ids)
positive_tags = [tagger_descriptions[positive_tag_id] for positive_tag_id in positive_tag_ids[0]]
texta_facts = []
if positive_tags:
if 'texta_facts' ... |
kmahyyg/learn_py3 | adv_feature/adv_feature_iterable.py | Python | agpl-3.0 | 894 | 0.001119 | #!/usr/bin/env python3
# -*- coding : utf-8 -*-
from coll | ections import I | terable
from collections import Iterator
isinstance([], Iterable)
isinstance({}, Iterable)
isinstance((), Iterable)
isinstance('abc', Iterable)
isinstance((x for x in range(10)), Iterable)
isinstance(100, Iterable)
# Iterable but not Iterator
isinstance([], Iterator)
isinstance({}, Iterator)
isinstance((), Iterator)
... |
ctmunwebmaster/huxley | huxley/utils/zoho.py | Python | bsd-3-clause | 1,767 | 0.01245 | # Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import json
import requests
from django.conf import settings
def get_contact(school):
if not settings.ZOHO_CREDENTIALS:
return
list_url = 'https://invoic... | /contacts?organization_id=' + settings.ORGANIZATION_ID + '&authtoken=' + settings.AUTHTOKEN
contact = {
"company_name_contains": school.name
}
return requests.get(list_url, params=contact).json()["contacts"][0]["contact_id"]
def generate_contact_ | attributes(school):
return {
"contact_name": school.primary_name,
"company_name": school.name,
"payment_terms": "",
"payment_terms_label": "Due on Receipt",
"currency_id": "",
"website": "",
"custom_fields": [
],
"billing_address": {
"a... |
yterauchi/primecloud-controller | iaas-gw/src/iaasgw/controller/ec2/ec2VolumController.py | Python | gpl-2.0 | 17,993 | 0.013944 | # coding: UTF-8
#
# Copyright 2014 by SCSK Corporation.
#
# This file is part of PrimeCloud Controller(TM).
#
# PrimeCloud Controller(TM) 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 versi... | return;
try :
# ボリュームのデ | タッチ
self.detachVolume(instanceNo, volumeNo)
# ボリュームのデタッチ待ち
self.waitDetachVolume(instanceNo, volumeNo)
except Exception, e:
self.logger.error(traceback.format_exc())
# 情報が不整合(インスタンス異常終了時など)の場合、警告ログと後始末のみ行う
self.logger.warn(e.massage);
... |
nextsmsversion/macchina.io | platform/JS/V8/v8-3.28.4/PRESUBMIT.py | Python | apache-2.0 | 7,096 | 0.008737 | # Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... | return results
def CheckChangeOnCommit(input_api, output_api):
results = []
results.extend(_CommonChecks(input_api, output_api))
results.extend(_CheckChangeLogFlag(input_api, output_api))
results.extend(input_api.canned_checks.CheckChangeHasDescription(
input_api, output_api))
i | f not _SkipTreeCheck(input_api, output_api):
results.extend(input_api.canned_checks.CheckTreeIsOpen(
input_api, output_api,
json_url='http://v8-status.appspot.com/current?format=json'))
return results
def GetPreferredTryMasters(project, change):
return {
'tryserver.v8': {
'v8_linux_r... |
subeax/grab | grab/spider/cache_backend/postgresql.py | Python | mit | 6,990 | 0.001001 | """
CacheItem interface:
'_id': string,
'url': string,
'response_url': string,
'body': string,
'head': string,
'response_code': int,
'cookies': None,#grab.response.cookies,
"""
from hashlib import sha1
import zlib
import logging
import marshal
import time
from grab.response import Response
from grab.cookie import Cook... | INSERT INTO cache (id, timestamp, data)
SELECT %s, %s, %s WHERE NOT EXISTS (SELECT 1 FROM cache WHERE id = %s);
'''
res = self.cursor.ex | ecute(sql, (ts, psycopg2.Binary(data), _hash, _hash, ts, psycopg2.Binary(data), _hash))
self.cursor.execute('COMMIT')
def pack_database_value(self, val):
dump = marshal.dumps(val)
return zlib.compress(dump)
def clear(self):
self.cursor.execute('BEGIN')
self.cursor.exec... |
spacemeowx2/remote-web | client/client.py | Python | mit | 1,269 | 0.01576 | import websocket
import package
import thread
import time
import run
import random
import config
import dht
import logging
logging.basicConfig()
def on_message(ws, message):
#d = package.LoadPackage(message)
#res = run.PackageParser(d)
#ws.send(package.DumpPackage(res))
print message
def on_error(ws... |
#print HSPackage,123
ws.send(HSPackage)
def SendRandomData(*args):
while True:
humdi, temp = dht.GetData()
if ( humdi == -1 or temp == -1):
continue
dump = package.SensorDump(0, temp)
dump1 = package.SensorDump(1, humdi)
w... | e__ == "__main__":
ws = websocket.WebSocketApp("ws://ali.imspace.cn:3000/device",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
|
harshilasu/LinkurApp | y/google-cloud-sdk/platform/gcutil/lib/google_compute_engine/gcutil_lib/firewall_cmds.py | Python | gpl-3.0 | 12,747 | 0.005021 | # Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | ribed by the \'--allowed\' '
'flag. If no IP or tag sources are listed, all sources '
'will be allowed.',
flag_values=flag_values)
flags.DEFINE_list('allowed_tag_sources',
[],
'Specifies a list of instance ... | 'talk to instances within the network, through the '
'<protocols>:<ports> described by the \'--allowed\' '
'flag. If specifying multiple tags, provide them as '
'comma-separated entries. For example, '
'\'--allowed_tag_sources=w... |
getsentry/freight | freight/vcs/base.py | Python | apache-2.0 | 1,987 | 0 | import os
import os.path
from freight.constants import PROJECT_ROOT
from freight.exceptions import CommandError
class UnknownRevision(CommandError):
pass
class Vcs(object):
ssh_connect_path = os.path.join(PROJECT_ROOT, "bin", "ssh-connect")
def __init__(self, workspace, url, username=None):
se... | t("cwd", None)
env = kwargs.pop("env", {})
for key, value in self.get_default_env().items():
env.setdefault(key, va | lue)
env.setdefault("FREIGHT_SSH_REPO", self.url)
kwargs["env"] = env
if capture:
handler = workspace.capture
else:
handler = workspace.run
rv = handler(command, *args, **kwargs)
if isinstance(rv, bytes):
rv = rv.decode("utf8")
... |
hillscottc/quiz2 | quiz2/urls.py | Python | agpl-3.0 | 1,275 | 0.002353 | """Top level site urls."""
from | django.conf.urls import pattern | s, include, url
from quiz2 import views
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', views.home, name='home'),
url(r'^register/$', views.register, name='register'),
url(r'^login/$', views.user_login, name='login'),
url(r'^logout/$', 'django.contrib... |
simontakite/sysadmin | pythonscripts/practicalprogramming/functions/days_bad.py | Python | gpl-2.0 | 1,684 | 0.000594 | def get_weekday(current_weekday, days_ahead):
""" (int, int) -> int
Return which day of the week it will be days_ahead days from
current_weekday.
current_weekday is the current day of the week and is in the range 1-7,
indicating whether today is Sunday (1), Monday (2), ..., Saturday (7).
days... | current_weekday is the current day of the week and is in the range 1-7,
indicating whether today is Sunday (1), Monday (2), ..., Saturday (7).
current_day and birthday_day are both in the range 1-365.
>>> get_birthday_weekday(5, 3, 4)
6
>>> get_birthday_weekday(5, 3, 116)
6
>>> get_birthd... | et_weekday(current_weekday, days_diff)
|
kingsdigitallab/kdl-django | kdl/settings/liv.py | Python | mit | 1,127 | 0 | from .base import * # noqa
INTERNAL_IPS = INTERNAL_IPS + ('', )
ALLOWED_HOSTS = []
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'app_kdl_liv',
'USER': 'app_kdl',
'PASSWORD': '',
'HOST': ''
},
}
# ------------------------------... | ---------------------------
# Django Extensions
# http://django-extensions.readthedocs.org/en/latest/
# -----------------------------------------------------------------------------
try:
import django_extensions # noqa
INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',)
except ImportError:
pa | ss
# -----------------------------------------------------------------------------
# Local settings
# -----------------------------------------------------------------------------
try:
from .local import * # noqa
except ImportError:
pass
|
XeryusTC/projman | projects/urls.py | Python | mit | 1,477 | 0 | # -*- coding: utf-8 -*-
from django.conf.urls import url
from projects import views
urlpatterns = [
url(r'^$', views.MainPageView.as_view(), name='main'),
# Inlist
url(r'^inlist/$', views.InlistView.as_view(), name='inlist'),
url(r'^inlist/(?P<pk>[0-9]+)/delete/$', views.InlistItemDelete.as_view(),
... |
url(r'^actions/(?P<pk>[0-9]+)/edit/$', views.EditActionView.as_view(),
name='edit_action'),
# Projects
url(r'^project/(?P<pk>[0-9]+)/$', views.Projec | tView.as_view(),
name='project'),
url(r'^project/create/$', views.CreateProjectView.as_view(),
name='create_project'),
url(r'project/(?P<pk>[0-9]+)/edit/$', views.EditProjectView.as_view(),
name='edit_project'),
url(r'project/(?P<pk>[0-9]+)/delete/$', views.DeleteProjectView.as_view(... |
QJonny/spin_emulator | pydevin/devinManager.py | Python | lgpl-2.1 | 2,573 | 0.026817 | from pydevin import *
import math
# ball parameters definitions
BALL_POS_Y_MAX = 115
BALL_POS_Y_MIN = 5
BALL_POS_Y_CENTER = (BALL_POS_Y_MAX + BALL_POS_Y_MIN) / 2.0
BALL_POS_X_MAX = 125
BALL_POS_X_MIN = 20
BALL_POS_X_CENTER = (BALL_POS_X_MAX + BALL_POS_X_MIN) / 2.0
A_X = -1.0/(BALL_POS_X_MAX - BALL_POS_X_CENTER)
B_... | um_y - y_buffer[curr_index] + y_cur
y_buffer[curr_index] = y_cur
x_pos = total_sum | _x >> 4 # division by 16
y_pos = total_sum_y >> 4
normalize_ball_params()
if(pos_computed == 0 and curr_index == 15):
pos_computed = 1
curr_index = (curr_index + 1) % 16
def cameraEvent():
global pdev
key = pdev.get_camera()
# raw position extraction
y_cur = ((key & 0x7F))
x_cur = (((key >> 8... |
houssine78/addons | mrp_bom_dismantling/models/res_config.py | Python | agpl-3.0 | 1,008 | 0 | # -*- coding: utf-8 -*-
# © 2016 Cyril Gaudin (Camptocamp)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
| from openerp import api, fields, models
class MrpConfigSettings(models.TransientModel):
""" Add settings for dismantling BOM.
"""
_inherit = 'mrp.config.settings'
dismantling_product_choice = fields.Selecti | on([
(0, "Main BOM product will be set randomly"),
(1, "User have to choose which component to set as main BOM product")
], "Dismantling BOM")
@api.multi
def get_default_dismantling_product_choice(self, fields):
product_choice = self.env["ir.config_parameter"].get_param(
... |
hosseinoliabak/learningpy | 09_5_dictionary.py | Python | gpl-3.0 | 877 | 0.004561 | '''
9.5 First, you have to resolve assignment9_3. This is slightly different.
This program records the domain name (instead of the address) where the message
was sent from instead of who the mail came from (i.e., the whole email address).
At the end of the program, prin | t out the contents of your dictionary.
Sample:
python assignment9_5_dictionary.py
{'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7,
'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8}
'''
dDomain = dict()
try:
flHand = open("mbox-short.txt")
except:
print('There is no "mbox-short.txt" file in the sam... | sLine.startswith('From '):
continue
lWords = sLine.split()
lEmailDomain = lWords[1].split('@')
dDomain[lEmailDomain[1]] = dDomain.get(lEmailDomain[1], 0) + 1
print (dDomain)
|
jonathanmorgan/django_reference_data | migrations/0005_auto__add_field_reference_domain_external_id__add_field_reference_doma.py | Python | gpl-3.0 | 5,852 | 0.00769 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Reference_Domain.external_id'
db.add_column(u'django_reference_data_reference_domain', 'exte... | # Deleting field 'Reference_Domain.external_id'
db.delete_column(u'django_reference_data_reference_domain', 'external_id')
# Deleting field 'Reference_Domain.guid'
db.delete_column(u'django_reference_data_reference_domain', | 'guid')
models = {
u'django_reference_data.postal_code': {
'Meta': {'object_name': 'Postal_Code'},
'admin_code1': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'admin_code2': ('django.db.models.fields.CharField', [],... |
SpheMakh/Stimela | stimela/utils/__init__.py | Python | gpl-2.0 | 11,642 | 0.002233 | import os
import sys
import json
import yaml
import time
import tempfile
import inspect
import warnings
import re
import math
import codecs
class StimelaCabRuntimeError(RuntimeError):
pass
class StimelaProcessRuntimeError(RuntimeError):
pass
CPUS = 1
from .xrun_poll import xrun
def assign(key, value):
... | ]
run_cmd = """ """
for kw in mult:
task_cmds = []
for key, val in kw.items():
if isinstance(val, (str, unicode)):
val = '"%s"' % val
task_cmds .append('%s=%s' % (key, val))
task_cmds = ", ".join(task_cmds)
run_cmd += """
%s
os.chdir('%s... | mds)
tf = tempfile.NamedTemporaryFile(suffix='.py')
tf.write(run_cmd)
tf.flush()
t0 = time.time()
# all logging information will be in the pyxis log files
print("Running {}".format(run_cmd))
xrun("cd", [td, "&& casa --nologger --log2term --nologfile -c", tf.name])
# log taskname.last
... |
eawerbaneth/Scoreboard | achievs/admin.py | Python | bsd-3-clause | 1,116 | 0.031362 | from django.contrib import admin
from achievs.models import Achievement
# from achievs.models import Gold
# from achievs.models import Silver
# from achievs.models import Bronze
# from achievs.models import Platinum
from achievs.models import Level
# class PlatinumInline(admin.StackedInline):
# model=Platinum
# cla... | admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['name']}),
('Date information', {'fields': ['pub_date']}),
]
#inlines=[GoldInline, SilverInline, BronzeInline, PlatinumInline]
inlines=[LevelInline]
list_display = ('name', 'pub_date')
list_filter=['pub_date']
search_fiel | ds=['name']
date_hierarchy='pub_date'
# admin.site.register(Gold)
# admin.site.register(Silver)
# admin.site.register(Bronze)
# admin.site.register(Platinum)
admin.site.register(Level)
admin.site.register(Achievement, AchievementAdmin) |
Integral-Technology-Solutions/ConfigNOW | wlst/persist.py | Python | mit | 8,036 | 0.015928 | # ============================================================================
#
# Copyright (c) 2007-2010 Integral Technology Solutions Pty Ltd,
# All Rights Reserved.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL... | if file.mkdirs():
log.info('File store directory [' + str(fileStoreLocation) + '] has been created successfully.')
| fileStore.setDirectory(fileStoreLocation)
except Exception, error:
cancelEdit('y')
raise ScriptError, 'Unable to create filestore [' + str(fileStoreName) + '] for target server [' + str(targetServerName) + '] : ' + str(error)
|
kikocorreoso/brython | www/speed/benchmarks/add_dict.py | Python | bsd-3-clause | 124 | 0 | d = {}
for i in range(100000):
| d[i] = i
JS_CODE = '''
var d = {};
for (var i = 0; i < 100000; i++) {
d[i] = i | ;
}
'''
|
linkingcharities/linkingcharities | Linking_Charities/payment/apps.py | Python | mit | 128 | 0 | from __future__ import unicode_literals
from django.apps import AppConfig
class PaypalConfig(App | Config):
name = ' | paypal'
|
CoolProp/CoolProp | Web/scripts/logo_2013.py | Python | mit | 1,263 | 0.005542 | import matplotlib
matplotlib.use('WXAgg')
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import CoolProp
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(2, 2))
ax = fig.add_subplot(111, projection='3d')
NT = 1000
NR = 1000
rho, t = np.logspace(np.log10(2e-3), np.log10(1... | np.log(P), cmap=cm.jet, edgecolor='none')
ax.plot(np.log(rhoL), Tsat, np.log(psat), color='k', lw=2)
ax.plot(np.log(rhoV), Tsat, np.log(psat), color='k', lw=2)
ax.text(0.3, 800, 22, "CoolProp", size=12)
ax.set_frame_on(False)
ax.set_axis_off()
ax.view_init(22, -13 | 6)
ax.set_xlabel(r'$\ln\rho$ ')
ax.set_ylabel('$T$')
ax.set_zlabel('$p$')
plt.tight_layout()
plt.savefig('_static/PVTCP.png', transparent=True)
plt.savefig('_static/PVTCP.pdf', transparent=True)
plt.close()
|
thedrow/cython | Cython/Build/Cythonize.py | Python | apache-2.0 | 6,882 | 0.001453 | #!/usr/bin/env python
from __future__ import absolute_import
import os
import shutil
import tempfile
from distutils.core import setup
from .Dependencies import cythonize, extended_iglob
from ..Utils import is_package_dir
from ..Compiler import Options
try:
import multiprocessing
parallel_compiles = int(mult... |
parser.add_option('-q', '--quiet', dest='quiet', action='store_true',
help | ='be less verbose during compilation')
parser.add_option('--lenient', dest='lenient', action='store_true',
help='increase Python compatibility by ignoring some compile time errors')
parser.add_option('-k', '--keep-going', dest='keep_going', action='store_true',
help=... |
JonasWallin/BayesFlow | examples/flowcymetry_normalMixture.py | Python | gpl-2.0 | 5,242 | 0.014117 | # -*- coding: utf-8 -*-
"""
Running the Gibbs sampler on flowcymetry data
http://www.physics.orst.edu/~rubin/nacphy/lapack/linear.html
matlab time: Elapsed time is 1.563538 seconds.
improve sample_mu:
python: 0.544 0.005 0.664
cython_admi: 0.469 0.005 0.493
moved_index_in_cyt... | {numpy.core.multiarray.array}
1 0.101 0.101 0.223 0.223 npyio.py:628(loadtxt)
100 0.048 0.000 0.048 0.000 {method 'cumsum' o | f 'numpy.ndarray' objects}
59998/29999 0.038 0.000 0.041 0.000 npyio.py:772(pack_items)
Created on Fri Jun 20 16:52:31 2014
@author: jonaswallin
"""
from __future__ import division
import numpy as np
from BayesFlow import mixture
import BayesFlow.PurePython.GMM as GMM
from matplotlib import pyplot as ... |
fossevents/fossevents.in | fossevents/users/migrations/0005_auto_20170212_1138.py | Python | mit | 504 | 0 | # -*- coding: utf-8 -*-
# Generated by | Django 1.9.4 on 2017-02-12 06:08
from __future__ import unicode_literals
from django.db import migrations
import fossevents.users.models
class Migration(migrations.Migration):
de | pendencies = [
('users', '0004_user_is_moderator'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
('objects', fossevents.users.models.CustomUserManager()),
],
),
]
|
rileymjohnson/fbla | app/main.py | Python | mit | 3,324 | 0.008724 | # -*- coding: utf-8 -*-
"""The app module, containing the app factory function."""
from flask imp | ort Flask, render_template, Markup
from . import public, admin |
from .extensions import *
from .config import Config
#extensions
def getPackage(num):
packages = {
"0": "No Package",
"1": "Basic Package",
"2": "Deluxe Package",
"3": "Ultimate Blast Package",
"4": "Party Package",
"5": "Holiday Package",
"6": "Behind the S... |
dstockwell/catapult | tracing/third_party/tvcm/tvcm/module_unittest.py | Python | bsd-3-clause | 3,914 | 0.005876 | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for the module module, which contains Module and related classes."""
import os
import unittest
from tvcm import fake_fs
from... | eFS()
fs.AddFile('/src/x.html', """
<!DOCTYPE html>
<link rel="import" href="/y.html" | >
<link rel="import" href="/z.html">
<script>
'use strict';
</script>
""")
fs.AddFile('/src/y.html', """
<!DOCTYPE html>
<link rel="import" href="/z.html">
""")
fs.AddFile('/src/z.html', """
<!DOCTYPE html>
""")
fs.AddFile('/src/tvcm.html', '<!DOCTYPE html>')
with fs:
project = project_module.Proj... |
richard-willowit/odoo | addons/account/models/account_payment.py | Python | gpl-3.0 | 35,920 | 0.004928 | # -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
MAP_INVOICE_TYPE_PARTNER_TYPE = {
'out_invoice': 'customer',
'out_refund': 'customer',
'in_invoice': 'supplier',
'in_refund': 'supplier',
}
# Since invoice amounts are unsigned, this ... | return total
@api.model
def default_get(self, fields):
rec = super(account_register_payments, self).default_get(fields)
active_ids = self._context.get('active_ids')
# Check for selected invoices ids
if not active_ids:
raise UserError(_("Programmation error: wizard... | en
if any(invoice.state != 'open' for invoice in invoices):
raise UserError(_("You can only register payments for open invoices"))
# Check all invoices have the same currency
if any(inv.currency_id != invoices[0].currency_id for inv in invoices):
raise UserError(_("In ord... |
pabulumm/neighbors | lib/python3.4/site-packages/django_extensions/db/fields/json.py | Python | bsd-3-clause | 3,459 | 0.000289 | "" | "
JSONField automatically serializes most Python terms to JSON data.
Creates a TEXT field with a default value of "{}". See test_json.py for
more information.
from django.db import models
from django_extensions.db.fields import json
class LOL(models.Model):
extra = json.JSONField()
"""
from __future__ import... | rom django.db import models
try:
# Django >= 1.7
import json
except ImportError:
# Django <= 1.6 backwards compatibility
from django.utils import simplejson as json
def dumps(value):
return DjangoJSONEncoder().encode(value)
def loads(txt):
value = json.loads(
txt,
parse_floa... |
franckinux/django-openzoom | setup.py | Python | gpl-3.0 | 925 | 0.035676 | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""setup
(C) Franck Barbenoire <fbarbenoire@yahoo.fr>
License : GPL v3"""
from distutils.core import setup
from setuptools import find_packages
setup(name = "django-openzoom",
version = "0.1.1",
description = "Django application for disp | laying very high resolution images",
author = "Franck Barbenoire",
author_email = "fbarbenoire@yahoo.fr",
url = "https://github.com/franckinux/django-openzoom",
packages = find_packages(),
include_package_data = True,
zip_ | safe = False,
classifiers = ['Development Status :: 3 - Alpha',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Framework :: Django',
... |
boyska/libreant | libreantdb/api.py | Python | agpl-3.0 | 7,780 | 0.002314 | from __future__ import print_function
def validate_book(body):
'''
This does not only accept/refuse a book. It also returns an ENHANCED
version of body, with (mostly fts-related) additional fields.
This function is idempotent.
'''
if '_language' not in body:
raise ValueError('language... | tStrings(value))
return strings
else:
return strings
class DB(object):
'''
| this class contains every query method and every operation on the index
'''
# Setup {{{2
def __init__(self, es, index_name):
self.es = es
self.index_name = index_name
# book_validator can adjust the book, and raise if it's not valid
self.book_validator = validate_book
... |
etsinko/oerplib | oerplib/rpc/xmlrpclib_custom.py | Python | lgpl-3.0 | 5,967 | 0.000168 | # -*- coding: UTF-8 -*-
##############################################################################
#
# OERPLib
# Copyright (C) 2012-2013 Sébastien Alix.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# ... | port = None
self._se | tup(self._connection_class(
host, port, key_file, cert_file, strict, timeout))
self.key_file = key_file
self.cert_file = cert_file
class TimeoutSafeTransportPy26(xmlrpclib.SafeTransport):
def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
... |
toastedcornflakes/scikit-learn | sklearn/feature_selection/univariate_selection.py | Python | bsd-3-clause | 25,381 | 0.000394 | """Univariate features selection."""
# Authors: V. Michel, B. Thirion, G. Varoquaux, A. Gramfort, E. Duchesnay.
# L. Buitinck, A. Joly
# License: BSD 3 clause
import numpy as np
import warnings
from scipy import special, stats
from scipy.sparse import issparse
from ..base import BaseEstimator
from ..prepr... | -------
chi2 : array, shape = (n_features,)
chi2 statistics of each feature.
pval : array, shape = (n_features,)
p-values of each feature.
Notes
-----
Complexity of this algorithm is O(n_classes * n_features).
See also
--------
f_classif: ANOVA F-value between label/fe... | ant to do some of the following in logspace instead for
# numerical stability.
X = check_array(X, accept_sparse='csr')
if np.any((X.data if issparse(X) else X) < 0):
raise ValueError("Input X must be non-negative.")
Y = LabelBinarizer().fit_transform(y)
if Y.shape[1] == 1:
Y = np.ap... |
Gerapy/Gerapy | setup.py | Python | mit | 3,683 | 0.000544 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import join, isfile
from os import walk
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
def read_file(filename):
with open(filename) as fp:
return fp.read().strip()
def read_requirem... | options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
... | s
self.status('Building Source and Wheel (universal) distribution…')
os.system(
'{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPI via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git ta... |
openstack/networking-odl | networking_odl/tests/unit/ceilometer/network/statistics/opendaylight_v2/test_driver.py | Python | apache-2.0 | 25,998 | 0 | #
# Copyright 2017 Ericsson India Global Services Pvt Ltd. 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 ... | 'client.SwitchStatisticsAPIClient.get_statistics',
return_value=self.switch_data).start()
def | _test_for_meter(self, meter_name, expected_data):
sample_data = self.driver.get_sample_data(meter_name,
self.fake_odl_url,
self.fake_params,
{})
self.ass... |
andrewsomething/libcloud | libcloud/test/dns/test_route53.py | Python | apache-2.0 | 14,213 | 0.000211 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | Route53MockHttp.type = 'ZONE_DOES_NOT_EXIST'
try:
self.driver.get_zone(zone_id='47234')
except ZoneDoesNotExistError as e:
self.assertEqual(e.zone_id, '47234')
else:
self.fail('Exception was not thrown')
def test_get_record_zone_does_not_exist(self):
... | self.driver.get_record(zone_id='4444', record_id='28536')
except ZoneDoesNotExistError:
pass
else:
self.fail('Exception was not thrown')
def test_get_record_record_does_not_exist(self):
Route53MockHttp.type = 'RECORD_DOES_NOT_EXIST'
rid = 'CNAME:doe... |
the-zebulan/CodeWars | katas/kyu_7/sum_of_all_arguments.py | Python | mit | 42 | 0 | de | f sum_args(*args):
| return sum(args)
|
boltnev/iktomi | iktomi/utils/i18n.py | Python | mit | 2,033 | 0.001476 | # i18n markers
def N_(msg):
'''
Single translatable string marker.
Does nothing, just a marker for \\*.pot file compilers.
Usage::
n = N_('translate me')
translated = env.gettext(n)
'''
return msg
class M_(object):
'''
Marker for translatable string with plural form.
... | m.count
| ) % m.format_args
'''
def __init__(self, single, plural, count_field='count', format_args=None):
self.single = single
self.plural = plural
self.count_field = count_field
self.format_args = format_args
def __mod__(self, format_args):
'''
Returns a c... |
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/imp.py | Python | gpl-3.0 | 10,631 | 0.000094 | """This module provides the components needed to build your own __import__
function. Undocumented functions are obsolete.
In most cases it is preferred you consider using the importlib module's
functionality over this module.
"""
# (Probably) need to stay in _imp
from _imp import (lock_held, acquire_lock, release_lo... | file does not need to exist; this simply returns the path to
the .py file calculated to correspond to the .pyc file. If path does
not conform to PEP 3147 format, ValueError will be raised. If
sys.implementation.cache_tag is None then NotImplementedError is raised.
"""
return util.source_from_cache... | s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES]
bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES]
return extensions + source + bytecode
class NullImporter:
"""**DEPRECATED**
Null import object.
"""
def __init__(self, path):
if path == '':
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.