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 |
|---|---|---|---|---|---|---|---|---|
raphaelvalentin/Utils | spectre/syntax/smu.py | Python | gpl-2.0 | 4,809 | 0.021418 | from spectre.syntax import *
class SMU2P(Netlist):
__name__ = "SMU2P"
__type__ = "netlist"
def __init__(self, name='SMU2P', nodes=('1', '2'), V1=0, V2=0):
Netlist.__init__(self)
self.name = name
self.nodes = nodes
self.V1 = V1; self.V2 = V2
save = dict(V1=nodes[0], V... | odes=() | , **parameters):
Netlist.__init__(self)
self.name = name
self.nodes = nodes
save = {}
for node in nodes:
if 'V{node}'.format(node=node) in parameters:
dc = parameters['V{node}'.format(node=node)]
self.append( Vsource(name='V{node}'.form... |
pkimber/compose | compose/tests/test_header.py | Python | apache-2.0 | 291 | 0 | # -*- encoding: utf-8 -*-
# from django.test import TestCase
# from block.tests.helper import check_content
# from compose.tests.factories import HeaderFactory
# class TestHeader(TestCase):
#
# def test_content_methods(self) | :
# c = HeaderFactory()
# | check_content(c)
|
Shadow5523/zabbix_api | lib/auth.py | Python | gpl-2.0 | 669 | 0.014948 | # -*- coding: utf-8 -*-
import json
import urllib2
def get_authkey(zabbix_server, zabbix_user, zab | bix_pass, head):
url = "http://" + zabbix_server + "/zabbix/api_jsonrpc.php"
pdata = json.dumps({"jsonrpc" : "2.0",
| "method" : "user.login",
"params" : {
"user" : zabbix_user,
"password" : zabbix_pass},
"auth" : None,
"id" : 1})
result = urllib2.urlopen(urllib2.Request(url, p... |
commaai/openpilot | selfdrive/car/subaru/values.py | Python | mit | 11,405 | 0.001841 | from selfdrive.car import dbc_dict
from cereal import car
Ecu = car.CarParams.Ecu
class CarControllerParams:
def __init__(self, CP):
if CP.carFingerprint == CAR.IMPREZA_2020:
self.STEER_MAX = 1439
else:
self.STEER_MAX = 2047
self.STEER_STEP = 2 # how often we update the steer c... | 40: 8, 1617: 8, 1632: 8, 1650: 8, 1677: 8, 1697: 8, 1722: 8, 1743: 8, 1759: 8, 1786: 5, 1787: 5, 1788: 8, 1809: 8, 1813: 8, 1817: 8, 1821: 8, 1840: 8, 1848: 8, 19 | 24: 8, 1932: 8, 1952: 8, 1960: 8, 1968: 8, 1976: 8, 2015: 8, 2016: 8, 2024: 8
},
{
2: 8, 64: 8, 65: 8, 72: 8, 73: 8, 280: 8, 281: 8, 282: 8, 290: 8, 312: 8, 313: 8, 314: 8, 315: 8, 316: 8, 326: 8, 544: 8, 545: 8, 546: 8, 554: 8, 557: 8, 576: 8, 577: 8, 801: 8, 802: 8, 803: 8, 805: 8, 808: 8, 816: 8, 826: 8, 837... |
neumerance/deploy | openstack_dashboard/dashboards/project/firewalls/views.py | Python | apache-2.0 | 10,365 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013, Big Switch Networks, 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/... | request, 'Deleted rule %s' % obj_id)
except Exception as e:
exceptions.handle(request,
_('Unable to delete rule. %s' % e))
if obj_type == 'policy':
for obj_id in obj_ids:
try:
api.fwaas.poli... | ndle(request,
_('Unable to delete policy. %s' % e))
if obj_type == 'firewall':
for obj_id in obj_ids:
try:
api.fwaas.firewall_delete(request, obj_id)
messages.success(request, 'Deleted firewall %s' % obj_id... |
BackupTheBerlios/pixies-svn | pixies/reportlab/pdfgen/textobject.py | Python | gpl-2.0 | 14,031 | 0.005274 | #Copyright ReportLab Europe Ltd. 2000-2004
#see license.txt for license details
#history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/reportlab/pdfgen/textobject.py
__version__=''' $Id$ '''
__doc__="""
PDFTextObject is an efficient way to add text to a Canvas. Do not
instantiate directly, obtai... | # Output the move text cursor call.
self._code.append('%s Td' % fp_str(dx, -dy))
# Keep track of the new line offsets and the cursor position
self._x0 += dx
self._y0 += dy
self. | _x = self._x0
self._y = self._y0
def setXPos(self, dx):
"""Starts a new line dx away from the start of the
current line - NOT from the current point! So if
you call it in mid-sentence, watch out."""
self.moveCursor(dx,0)
def getCursor(self):
"""Returns current t... |
takeshineshiro/nova | nova/tests/functional/v3/test_console_auth_tokens.py | Python | apache-2.0 | 2,711 | 0 | # Copyright 2013 Cloudbase Solutions Srl
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | TokensSampleJsonTests(test_servers.ServersSampleBase):
ADMIN_API = True
extension_name = "os-conso | le-auth-tokens"
extra_extensions_to_load = ["os-remote-consoles", "os-access-ips"]
# TODO(gmann): Overriding '_api_version' till all functional tests
# are merged between v2 and v2.1. After that base class variable
# itself can be changed to 'v2'
_api_version = 'v2'
def _get_flags(self):
... |
khizkhiz/swift | utils/split_file.py | Python | apache-2.0 | 1,030 | 0.000971 | #!/usr/bin/env python
"""
split_file.py [-o <dir>] <path>
Take the file at <path> and write it to multiple files, switching to a new file
every time an annotation of the form "// BEGIN file1.swift" is encountered. If
<dir> is specified, place the files in <dir>; otherwise, put them in the
current directory.
"""
impo... |
fp_out = None
dest_dir = '.'
try:
opts, args = getopt.getopt(sys.argv[1:], 'o:h')
for (opt, arg) in opts:
if opt == '-o':
dest_dir = arg
elif opt == '-h':
usage()
except getopt.GetoptError:
usage()
if len(args) != 1:
usage()
fp_in = open(args[0], 'r')
f | or line in fp_in:
m = re.match(r'^//\s*BEGIN\s+([^\s]+)\s*$', line)
if m:
if fp_out:
fp_out.close()
fp_out = open(os.path.join(dest_dir, m.group(1)), 'w')
elif fp_out:
fp_out.write(line)
fp_in.close()
if fp_out:
fp_out.close()
|
crazyleen/msp430-gdb-7.2a | gdb/testsuite/gdb.python/py-prettyprint.py | Python | gpl-2.0 | 7,344 | 0.012527 | # Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Thi... | pile ('^struct container$')] = ContainerPrinter
pret | ty_printers_dict[re.compile ('^struct justchildren$')] = NoStringContainerPrinter
pretty_printers_dict[re.compile ('^string_repr$')] = string_print
pretty_printers_dict[re.compile ('^container$')] = ContainerPrinter
pretty_printers_dict[re.compile ('^justchildren$')] = NoStringContainerPrinter
pret... |
playandbuild/scrapy-history-middleware | history/middleware.py | Python | mit | 3,854 | 0.002076 | from datetime import datetime
from parsedatetime import parsedatetime, Constants
from scrapy import signals
from scrapy.xlib.pydispatch import dispatcher
from scrapy.exceptions import NotConfigured, IgnoreRequest
from scrapy.utils.misc import load_object
class HistoryMiddleware(object):
DATE_FORMAT = '%Y%m%d'
... | self.stats.set_value('history/cached', True, spider=spider)
return response
def parse_epoch(self, epoch):
"""
bool => bool
datetime => datetime
str => datetime
"""
if isinstance(epoch, bool) or isinstance(epoch, datetime):
re... | ch
elif epoch == 'True':
return True
elif epoch == 'False':
return False
try:
return datetime.strptime(epoch, self.DATE_FORMAT)
except ValueError:
pass
parser = parsedatetime.Calendar(Constants())
time_tupple = parser.pars... |
d120/pyofahrt | workshops/migrations/0028_auto_20161110_1931.py | Python | agpl-3.0 | 795 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016- | 11-10 18:31
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workshops', '0027_auto_20161110_0311'),
]
operations = [
migrations.AlterField(
model_name='slot',
... | default=datetime.datetime(2016, 11, 11, 0, 0),
verbose_name='Start'),
),
migrations.AlterField(
model_name='slot',
name='end',
field=models.DateTimeField(
default=datetime.datetime(2016, 11, 11, 0, 0),
verb... |
ANR-COMPASS/shesha | shesha/constants.py | Python | gpl-3.0 | 5,648 | 0.003718 | ## @package shesha.constants
## @brief Numerical constants for shesha and config enumerations for safe-typing
## @author COMPASS Team <https://github.com/ANR-COMPASS>
## @version 5.2.1
## @date 2022/01/24
## @copyright GNU Lesser General Public License
#
# This file is part of COMPASS <https://anr-comp... | AO of the E-ELT (such as wavefront analysis device with a pyramid or elongated Laser star), and
# various systems configurations such as multi-conjugate AO.
#
# COMPASS is distrib | uted 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 COMPASS.... |
ufieeehw/IEEE2015 | ros/ieee2015_simulator/nodes/mecanum_simulation.py | Python | gpl-2.0 | 7,968 | 0.009538 | #!/usr/bin/python
from __future__ import division
## Math
import numpy as np
import math
## Display
import pygame
import time
## Ros
import rospy
import os, sys
from geometry_msgs.msg import Twist, Pose, PoseStamped, Point, Quaternion
from tf import transformations as tf_trans
from std_msgs.msg import Header
from ie... | self.pose_pub = rospy.Publisher('pose', PoseStamped, queue_size=10)
self.height = height
self.width = width
a = +(self.width / 2)
b = -(self.width / 2)
c = +(self.height / 2)
d = -(self.height / 2)
self.pointlist = map(lambda vector: np.ar... | heelSpeeds, self.set_wheel_speed_service)
def set_wheel_speed_service(self, ws_req):
if abs(ws_req.wheel1) > .00000000001 and abs(ws_req.wheel2) > .00000000000001 and abs(ws_req.wheel3) > .00000000000001 and abs(ws_req.wheel4) > .00000000000001:
self.mecanum[0] = ws_req.wheel1
... |
powerds/python-tacoclient | tacoclient/shell.py | Python | apache-2.0 | 904 | 0.002212 | import sys
from cliff import app
from cliff import commandmanager as cm
from conf import default
import tacoclient
class TacoClientApp(app.App):
def __init__(self, **kwargs):
super(TacoClientApp, self).__init__(
description='tacoclient - CLI client for TACO(SKT All Container \
Ope... | configure_logging(self):
super(TacoClientApp, self).configure_logging()
default.register_opts()
def main(argv=None) | :
if argv is None:
argv = sys.argv[1:]
return TacoClientApp().run(argv)
|
jalr/privacyidea | privacyidea/lib/eventhandler/base.py | Python | agpl-3.0 | 2,637 | 0 | # -*- coding: utf-8 -*-
#
# 2016-05-04 Cornelius Kölbel <cornelius.koelbel@netknights.it>
# Initial writup
#
# License: AGPLv3
# (c) 2016. Cornelius Kölbel
#
# This code is free software; you can redistribute it and/or
# modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
# License as publi... | be used in all events.
:return: list of events
"""
events = ["*"]
return events
def check_condition(self):
"""
TODO
:return:
"""
# TODO
return True
def do(self, action, options=None):
"""
This method executes... | :return:
"""
log.info("In fact we are doing nothing, be we presume we are doing"
"{0!s}".format(action))
return True
|
MediaKraken/MediaKraken_Deployment | source/web_app_sanic/blueprint/user/bp_user_metadata_periodical.py | Python | gpl-3.0 | 4,831 | 0.006417 | from common import common_global
from common import common_isbn
from common import common_logging_elasticsearch_httpx
from common import common_pagination_bootstrap
from sanic import Blueprint
blueprint_user_metadata_periodical = Blueprint('name_blueprint_user_metadata_periodical',
... | html')
@common_global.auth.login_required
async def url_bp_user_metadata_periodical_detail(request, guid):
"""
Display periodical detail page
"""
db_connection = await request.app.db_pool.acquire()
json_metadata = await request.app.db_functions.db_meta_periodical_by_uuid(guid,
... | ait request.app.db_pool.release(db_connection)
try:
data_name = json_metadata['mm_metadata_book_json']['title']
except KeyError:
data_name = 'NA'
try:
data_isbn = common_isbn.com_isbn_mask(json_metadata['mm_metadata_book_json']['isbn10'])
except KeyError:
data_isbn = 'NA'... |
cshallue/models | research/cognitive_planning/embedders.py | Python | apache-2.0 | 19,820 | 0.006105 | # Copyright 2018 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 applicab... | ams.is_train:
mean, variance = tf.nn.moments(x, [0, 1, 2], name='moments')
moving_mean = tf.get_variable(
'moving_mean',
params_shape,
tf.float32,
initializer=tf.constant_initializer(0.0, tf.float32),
trainable=False)
moving_variance =... | f.float32,
initializer=tf.constant_initializer(1.0, tf.float32),
trainable=False)
self._extra_train_ops.append(
tf.assign_moving_average(moving_mean, mean, 0.9))
self._extra_train_ops.append(
tf.assign_moving_average(moving_variance, variance, 0.9))
... |
googleapis/python-dataplex | samples/generated_samples/dataplex_v1_generated_dataplex_service_delete_task_sync.py | Python | apache-2.0 | 1,521 | 0.000657 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# [START dataplex_v1_ | generated_DataplexService_DeleteTask_sync]
from google.cloud import dataplex_v1
def sample_delete_task():
# Create a client
client = dataplex_v1.DataplexServiceClient()
# Initialize request argument(s)
request = dataplex_v1.DeleteTaskRequest(
name="name_value",
)
# Make the request
... |
Venturi/cms | env/lib/python2.7/site-packages/aldryn_people/south_migrations/0013_auto__add_field_person_vcard_enabled.py | Python | gpl-2.0 | 14,400 | 0.007917 | # -*- 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 'Person.vcard_enabled'
db.add_column(u'aldryn_people_person', 'vcard_enabled',
... | ault': 'False'}),
'style': ('django.db.models.fields.CharField', [], {'default': "'standard'", 'max_length': '50'})
},
u'aldryn_people.person': {
'Meta': {'object_name': 'Person'},
'email': ('django.db.models.fields.Em | ailField', [], {'default': "''", 'max_length': '75', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['aldryn_people.Group']", 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mob... |
hongquan/saleor | saleor/product/models/products.py | Python | bsd-3-clause | 1,423 | 0 | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import pgettext_lazy
from .base import Product
from .variants import (ProductVariant, PhysicalProduct, ColoredVariant,
StockedProduct)... | app_label = 'product'
@python | _2_unicode_compatible
class ShirtVariant(ProductVariant, StockedProduct):
SIZE_CHOICES = (
('xs', pgettext_lazy('Variant size', 'XS')),
('s', pgettext_lazy('Variant size', 'S')),
('m', pgettext_lazy('Variant size', 'M')),
('l', pgettext_lazy('Variant size', 'L')),
('xl', pge... |
jmlong1027/multiscanner | analytics/ssdeep_analytics.py | Python | mpl-2.0 | 10,551 | 0.001516 | #!/usr/bin/env python
'''
Set of analytics based on ssdeep hash.
- compare
Simple implementation of ssdeep comparisions using a few optimizations
described at the links below
https://www.virusbulletin.com/virusbulletin/2015/11/optimizing-ssdeep-use-scale
http://www.intezer.com/intezer-community-tip-s... | get('chunksize')
chunk = new_ssdeep_hit_src.get('ssdeep').get('chunk')
double_chunk = new | _ssdeep_hit_src.get('ssdeep').get('double_chunk')
new_sha256 = new_ssdeep_hit_src.get('SHA256')
# build new query for docs that match our optimizations
# https://github.com/intezer/ssdeep-elastic/blob/master/ssdeep_elastic/ssdeep_querying.py#L35
opti_query = {
... |
RDFLib/PyRDFa | pyRdfa/rdfs/cache.py | Python | bsd-3-clause | 15,733 | 0.038075 | # -*- coding: utf-8 -*-
"""
Managing Vocab Caching.
@summary: RDFa parser (distiller)
@requires: U{RDFLib<http://rdflib.net>}
@organization: U{World Wide Web Consortium<http://www.w3.org>}
@author: U{Ivan Herman<a href="http://www.w3.org/People/Ivan/">}
@license: This software is available for use under the
U{W3C® SOF... | rwise.
The return value is a tuple: file name, modification date, and expiration date
@param uri: the URI that serves as a key in the index directory
"""
if uri in self.indeces :
return tuple(self.indeces[uri])
else :
return None
def _give_preference_path(self) :
"""
Find the vocab cache dire... | IR_VAR]
else :
# find the preference path on the architecture
platform = sys.platform
if platform in self.architectures :
system = self.architectures[platform]
else :
system = "unix"
if system == "win" :
# there is a user variable set for that purpose
app_data = os.path.expandvars("%A... |
kyleabeauchamp/DBayes | dbayes/analysis/test_moe.py | Python | gpl-2.0 | 1,864 | 0.004292 | import moe
from moe.easy_interface.experiment import Experiment
from moe.easy_interface.simple_endpoint import gp_next_points, gp_hyper_opt
import pymbar
import seaborn as sns
import scipy.interpolate
import pymc
import sklearn.gaussian_process
import os
import pandas as pd
import glob
keys = ["q0", "sigma0"]
data = p... | ma0_val, value)
error = 0.001
exp.historical_data.append_sample_points([[(q0_val, sigma0 | _val), value, error]])
covariance_info = gp_hyper_opt(exp.historical_data.to_list_of_sample_points())
next_point_to_sample = gp_next_points(exp, covariance_info=covariance_info)
print next_point_to_sample
|
wrongu/AlphaGo | AlphaGo/models/value.py | Python | mit | 1,711 | 0.01052 | from keras.models import Sequential
from keras.layers import convolutional
from keras.layers.core import Dense, Flatten
from SGD_exponential_decay import SGD_exponential_decay as SGD
### Parameters obtained from paper ###
K = 152 # depth of convolutional layers
LEARNING_RATE = .003 # ini... | odel.add(convolutional.Convolution2D(nb_filter=1, nb_row=1, nb_col=1,
init='uniform', activation='linear', border_mode='same'))
self.model.add(Flatten())
self.model.add(Dense(256,init='uniform'))
self.model.add(Dense(1,init='uniform',activation="tanh... | self.model.compile(loss='mean_squared_error', optimizer=sgd)
def get_samples(self):
# TODO non-terminating loop that draws training samples uniformly at random
pass
def train(self):
# TODO use self.model.fit_generator to train from data source
pass
if __name__ == '__main__':
... |
ministryofjustice/opg-docker | mongodb/docker/opt/reindex_database.py | Python | mit | 784 | 0.019133 | #!/usr/bin/env python
import os
import argparse
from subprocess import call
admin_username = 'admin'
admin_password = os.environ['MONGO_ADMIN_PASSWORD']
parser= | argparse.ArgumentParser()
parser.add_argument("-d", "--db-name", help="the DB to create the user in", required=True)
parser.add_argument("-c", "--collection", help="the collection to index", required=True)
parser.add_argument("-i", "--index-definition", help="the index definition", required=True)
args = parser.parse_a... | gDB('" + args.db_name + "').getCollection('" + args.collection + "').ensureIndex( " + args.index_definition + " );"
print 'Creating index'
call(["/usr/bin/mongo","admin","-u",admin_username,"-p",admin_password,"--authenticationDatabase","admin","--eval",reindex_js])
|
endlessm/chromium-browser | third_party/llvm/clang/bindings/python/tests/cindex/test_linkage.py | Python | bsd-3-clause | 1,175 | 0.001702 | import os
from clang.cindex import Config
if 'CLANG_LIBRARY_PATH' in os.environ:
Config.set_library_path(os.environ['CLANG_LIBRARY_PATH'])
from clang.cindex import LinkageKind
from clang.cindex import Cursor
from clang.cindex import TranslationUnit
from .util import get_cursor
from .util import get_tu
import uni... | .INTERNAL)
unique_external = get_cursor(tu.cursor, 'unique_ | external')
self.assertEqual(unique_external.linkage, LinkageKind.UNIQUE_EXTERNAL)
external = get_cursor(tu.cursor, 'external')
self.assertEqual(external.linkage, LinkageKind.EXTERNAL)
|
bxlab/bx-python | lib/bx/seqmapping.py | Python | mit | 2,856 | 0 | """
Classes for char-to-int mapping and int-to-int mapping.
:Author: James Taylor (james@bx.psu.edu)
The char-to-int mapping can be used to translate a list of strings
over some alphabet to a single int array (example for encoding a multiple
sequence alignment).
The int-to-int mapping is particularly useful for crea... | nt oriented problems.
This code was originally written for the `ESPERR`_ project which includes
software for searcing for alignment encodings that work well for specific
classification problems using | various Markov chain classifiers over the
reduced encodings.
Most of the core implementation is in the pyrex/C extension
"_seqmapping.pyx" for performance reasons (specifically to avoid the
excessive bounds checking that would make a sequence/array lookup heavy
problem like this slow in pure python).
.. _ESPERR: htt... |
10n1z3d/YAVD | setup.py | Python | gpl-3.0 | 391 | 0.046036 | from distutils.core import setup
import yavd
setup (
name = 'YAVD',
version = y | avd.__version__,
description= 'Download videos from Youtube and others.',
author = '10n1z3d',
author_email = '10n1z3d@w.cn',
url = '',
| license = 'GPLv3',
packages = ['YAVD'],
data_files = [('YAVD/', ['README', 'COPYING', 'TODO'])]
)
|
denverfoundation/storybase | apps/storybase_geo/migrations/0004_auto.py | Python | mit | 7,705 | 0.007787 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db impor | t models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding index on 'Place', fields ['place_id']
db.create_index('storybase_geo_place', ['place_id'])
# Adding index on 'Location', fields ['location_id']
db.create_index('storybase_geo_location', ['locatio... | ackwards(self, orm):
# Removing index on 'Location', fields ['location_id']
db.delete_index('storybase_geo_location', ['location_id'])
# Removing index on 'Place', fields ['place_id']
db.delete_index('storybase_geo_place', ['place_id'])
models = {
'auth.group': {
... |
sebrandon1/neutron | neutron/tests/unit/services/trunk/drivers/openvswitch/test_driver.py | Python | apache-2.0 | 2,829 | 0 | # Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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 o... | ron.plugins.ml2.drivers.openvswitch.agent.common import (
constants as agent_consts)
from neutron.services.trunk.drivers.openvswitch import driver
from neutron.tests import base
GEN_TRUNK_BR_NAME_PATCH = (
'neutron.services.trunk.drivers.openvswitch.utils.gen_trunk_br_name')
class OVSDriverTestCase(base.Base... | ovs_driver = driver.OVSDriver.create()
self.assertFalse(ovs_driver.is_loaded)
self.assertEqual(driver.NAME, ovs_driver.name)
self.assertEqual(driver.SUPPORTED_INTERFACES, ovs_driver.interfaces)
self.assertEqual(driver.SUPPORTED_SEGMENTATION_TYPES,
ovs_driver.... |
dfm/python-finufft | tests/test_1d.py | Python | apache-2.0 | 1,814 | 0.000551 | # -*- coding: utf-8 -*-
from __future__ import division, print_function
import finufft
from finufft import interface
import numpy as np
import pytest
__all__ = [
"test_nufft1d1", "test_nufft1d2", "test_nufft1d3",
]
def test_nufft1d1(seed=42, iflag=1):
np.random.seed(seed)
ms = int(1e3)
n = int(2e... | g, fftw=100)
f0 = interface.dirft1d1(x, c, ms, iflag=iflag)
assert np.all(np.abs((f - f0) / f0) < 1e-6)
def test_nufft1d2(seed=42, iflag=1):
np.random.seed(seed)
ms = int(1e3)
n = int(2e3)
tol = 1.0e-9
x = np.random.uniform(-np.pi, np.pi, n)
c = np.random.uniform(-1.0, 1.0, n) + 1.0... | f, eps=tol, iflag=iflag)
c0 = interface.dirft1d2(x, f, iflag=iflag)
assert np.all(np.abs((c - c0) / c0) < 1e-6)
def test_nufft1d3(seed=42, iflag=1):
np.random.seed(seed)
ms = int(1e3)
n = int(2e3)
tol = 1.0e-9
x = np.random.uniform(-np.pi, np.pi, n)
c = np.random.uniform(-1.0, 1.0, n... |
RobinCPC/algorithm-practice | LinkedList/deleteNode.py | Python | mit | 1,861 | 0.005911 | # Write a function to delete a node (except the tail) in a singly linked list,
# given only access to that node.
#
# Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node
# with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
#
# time: O(1)
# space: O(1)
# Defini... | ass Solution(object):
def deleteNode2(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
curt = node
prev = None
while curt.next is not None:
curt.val = curt.next. | val
prev = curt
curt = curt.next
if prev is not None:
prev.next = None
return
def deleteNode1(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
curt = node
w... |
editorsnotes/editorsnotes | editorsnotes/api/urls.py | Python | agpl-3.0 | 3,744 | 0.006143 | # vim: set tw=0:
from django.conf.urls import url, include
from django.core.urlresolvers import RegexURLPattern
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework.authtoken.views import obtain_auth_token
from . import views
def format_patterns(urlpatterns):
"If a URL pattern ends i... | ew(), name='topics-confirm-delete'),
### Notes ###
url(r'^notes/$', views.NoteList.as_view(), name='notes-list'),
url(r'^notes/(?P<pk>\d+)/$', views.NoteDetail.as_view(), name='notes-detail'),
url(r'^notes/(?P<pk>\d+)/confirm_delete$', views.NoteConfirmDelete.as_view(), name='notes-confirm-delete'),
... | ), name='documents-list'),
url(r'^documents/(?P<pk>\d+)/$', views.DocumentDetail.as_view(), name='documents-detail'),
url(r'^documents/(?P<pk>\d+)/confirm_delete$', views.DocumentConfirmDelete.as_view(), name='documents-confirm-delete'),
url(r'^documents/(?P<document_id>\d+)/scans/$', views.ScanList.as_view... |
sounak98/coala-bears | tests/java/InferBearTest.py | Python | agpl-3.0 | 585 | 0 | from bears.java.InferBear import InferBear
from tests.Lo | calBearTestHelper import verify_local_bear
good_file = """
class InferGood {
int test() {
String s = null;
return s == null ? 0 : s.length();
| }
}
"""
bad_file = """
class InferBad {
int test() {
String s = null;
return s.length();
}
}
"""
InferBearTest = verify_local_bear(InferBear,
valid_files=(good_file,),
invalid_files=(bad_file,),
... |
palladius/gcloud | packages/gcutil-1.7.1/lib/google_api_python_client/apiclient/discovery.py | Python | gpl-3.0 | 26,209 | 0.008623 | # Copyright (C) 2010 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 writ... | ('features', [])
model = JsonModel('dataWrapper' in features)
resource = _createResource(http, base, model, requestBuilder, developerKey,
service, service, schema)
return resource
def _cast(value, schema_type):
"""Convert value to a string based on JSON Schema type.
See http://too... | alue: any, the value to convert
schema_type: string, the type that value should be interpreted as
Returns:
A string representation of 'value' based on the schema_type.
"""
if schema_type == 'string':
if type(va |
GadgeurX/NetworkLiberator | Daemon/AttackProcess.py | Python | gpl-3.0 | 586 | 0.001706 | from threading import Thread
import time
from scapy.all import *
class AttackProcess(Thread):
def __init__(self, main):
Thread.__init__(self)
self.main = main
self.selected_hosts = []
self.is_attacking = False
def run(self):
while True:
while self.is_at | tacking:
packets = []
for host in self.main.HostMgr.hosts:
if host.is_selected:
packets.append(host.packet)
| time.sleep(1)
send(packets)
time.sleep(5) |
7Pros/circuit | circuit/wsgi.py | Python | gpl-2.0 | 391 | 0 | """
WSGI conf | ig for circuit project.
It exposes the WSGI callable as a module- | level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "circuit.settings")
application = get_wsgi_application()
|
jabaier/iic1103.20152.s4 | estriangulo_prueba.py | Python | unlicense | 428 | 0.063084 | def estriangulo(a,b,c):
print("el primer argumento es:",a)
print("el segundo argumento es:",b)
print("el tercer argumento es:",c)
return a+b>c and a+c>b and c+b>a
def espitagorico(a,b,c):
| return a**2+b**2==c**2 or a**2+c* | *2==b**2 or b**2+c**2==a**2
def esisosceles(a,b,c):
return a==b or a==c or b==c
print(estriangulo(int(input("numero? ")),4,5))
print(espitagorico(3,4,5))
print(esisosceles(3,4,5))
|
UBayouski/RaspberryPiPowerButton | power_button.py | Python | mit | 315 | 0 | #!/usr/bin/python
import RPi.GPIO as GPIO
import subprocess
# St | arting | up
GPIO.setmode(GPIO.BCM)
GPIO.setup(3, GPIO.IN)
# Wait until power button is off
# Recommended to use GPIO.BOTH for cases with switch
GPIO.wait_for_edge(3, GPIO.BOTH)
# Shutting down
subprocess.call(['shutdown', '-h', 'now'], shell=False)
|
protochron/aurora | src/test/python/apache/aurora/client/cli/test_quota.py | Python | apache-2.0 | 4,844 | 0.0064 | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... | west/bozo'])
assert fake_context.get_err() == ['Error retrieving quota for role bozo', '\tWhoops']
def _get_quota(self, include_c | onsumption, command_args):
mock_context = FakeAuroraCommandContext()
if include_consumption:
self.setup_mock_quota_call_with_consumption(mock_context)
else:
self.setup_mock_quota_call_no_consumption(mock_context)
return self._call_get_quota(mock_context, command_args)
def _call_get_quota... |
kdebrab/pandas | pandas/core/arrays/__init__.py | Python | bsd-3-clause | 325 | 0 | from .base import (ExtensionArray, # noqa
ExtensionScalarOpsMixin)
from .categorical i | mport Categorical # noqa
from .datetimes import DatetimeArrayMixin # noqa
from .interval import IntervalArray # noqa
from .period import Peri | odArrayMixin # noqa
from .timedeltas import TimedeltaArrayMixin # noqa
|
vejeshv/main_project | knockknock/MacFailedException.py | Python | gpl-3.0 | 790 | 0 | # Copyright (c) 2009 Moxie Marlinspike
#
# 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 opt | ion) 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 received a | copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
#
class MacFailedException(Exception):
pass
|
gamesun/MyTerm-for-YellowStone | setup.py | Python | bsd-3-clause | 4,648 | 0.010327 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2013, gamesun
# 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 copyr... | compiled_files.append(os.path.join(folder, name))
def copy_extensions(self, extensions):
#super(MediaCollector, self).copy_extensions(extensions)
build_exe.copy_extensions(self, extensions)
for folder in CONTENT_DIRS:
self.addDirectoryToZip(folder)
for fileName in EXTR... | Name, os.path.join(self.collect_dir, name))
self.compiled_files.append(name)
myOptions = {
"py2exe":{
"compressed": 1,
"optimize": 2,
"ascii": 1,
# "includes":,
"dll_excludes": ["MSVCP90.dll","w9xpopen.exe"],
"bundle_files": 2
}
}
RT_MANIFEST = 24
... |
emencia/emencia_paste_djangocms_3 | emencia_paste_djangocms_3/django_buildout/project/mods_available/admin_tools/dashboard.py | Python | mit | 3,336 | 0.014688 | # -*- coding: utf-8 -*-
"""
Dashboard stuff for admin_tools
"""
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from admin_tools.dashboard import modules, Dashboard, AppIndexDashboard
from admin_tools.utils import get_admin_site_name
class CustomIndexDashboard(Dash... | om index dashboard for project.
"""
def init_with_context(self, context):
site_name = get_admin_site_name(context)
# append a link list module for "quick links"
self.children.append(modules.LinkList(
_('Quick links'),
layout='inline',
| draggable=False,
deletable=False,
collapsible=False,
children=[
[_('Return to site'), '/'],
[_('Change password'),
reverse('%s:password_change' % site_name)],
[_('Log out'), reverse('%s:logout' % site_name)],
... |
mudbungie/NetExplorer | Host.py | Python | mit | 17,053 | 0.002346 | # Class for a network object.
from NetworkPrimitives import Ip, Mac
from Config import config
from Exceptions import *
import Toolbox
import easysnmp
import requests
import json
import time
from datetime import datetime
import uuid
import geocoder
# Disable security warnings.
from requests.packages.urllib3.exception... | on', ip, 'with', community)
return responses
except easysnmp.exceptions.EasySNMPNoSuchNameError:
# Probably means that you're hitting the wrong kind of device.
self.community = None
self.setmgmntip(ip, | False)
raise
except easysnmp.exceptions.EasySNMPTimeoutError:
# Either the community string is wrong, or the address is dead.
print('No response on', ip, 'with', community)
self.community = None
self.setmgmntip(ip, False)
... |
iftekeriba/softlayer-python | SoftLayer/CLI/virt/upgrade.py | Python | mit | 1,538 | 0 | """Upgrade a virtual server."""
# :license: MIT, see LICENSE for more details.
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
from SoftLayer.CLI import formatting
from SoftLayer.CLI import helpers
from SoftLayer.CLI import virt
import click
@click.command(epilog="""Note:... | ts the VS once
upgrade request is placed. The VS is halted until the Upgrade transaction is
completed. However for Network, no reboot is req | uired.""")
@click.argument('identifier')
@click.option('--cpu', type=click.INT, help="Number of CPU cores")
@click.option('--private',
is_flag=True,
help="CPU core will be on a dedicated host server.")
@click.option('--memory', type=virt.MEM_TYPE, help="Memory in megabytes")
@click.option('-... |
wakermahmud/sync-engine | inbox/models/message.py | Python | agpl-3.0 | 22,094 | 0.000181 | import datetime
import itertools
from hashlib import sha256
from collections import defaultdict
from flanker import mime
from sqlalchemy import (Column, Integer, BigInteger, String, DateTime,
Boolean, Enum, ForeignKey, Index)
from sqlalchemy.dialects.mysql import LONGBLOB
from sqlalchemy.orm im... | ompacted_body = Column(LONGBLOB, nullable=True)
snippet = Column(String(191), nullable=False)
SNIPPET_LENGTH = 191
# A reference to the block holding the full contents of the message
full_body_id = Column(ForeignKey('block.id', name='full_body_id_fk'),
| nullable=True)
full_body = relationship('Block', cascade='all, delete')
# this might be a mail-parsing bug, or just a message from a bad client
decode_error = Column(Boolean, server_default=false(), nullable=False,
index=True)
# In accordance with JWZ (http:/... |
ael-code/libreant | setup.py | Python | agpl-3.0 | 4,963 | 0.002015 | import os
import sys
import msgfmt
from setuptools import setup
from setuptools.command.install_lib import install_lib as _install_lib
from setuptools.command.develop import develop as _develop
from distutils.command.build import build as _build
from setuptools.command.test import test as TestCommand
from distutils.cm... | def run(self):
self.run_command('compile_translations')
_develop.run(self)
class NoseTestCommand(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_te | sts(self):
# Run nose ensuring that argv simulates running nosetests directly
import nose
nose.run_exit(argv=['nosetests'])
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as buf:
return buf.read()
conf = dict(
name='libreant',
version='... |
kaushik94/sympy | sympy/polys/factortools.py | Python | bsd-3-clause | 34,338 | 0.00067 | """Polynomial factorization routines in characteristic zero. """
from __future__ import print_function, division
from sympy.polys.galoistools import (
gf_from_int_poly, gf_to_int_poly,
gf_ | lshift, gf_add_mul, gf_mul,
gf_div, gf_rem,
gf_gcdex,
gf_sqf_p,
gf_factor_sqf, gf_factor)
from sympy.polys.densebasic import (
dup_LC, dmp_LC, dmp_ground_LC,
dup_TC,
dup_convert, dmp_convert,
dup_degree, dmp_degree,
dmp_degree_in, dmp_degree_list,
dmp_from_dict,
dmp_zero_p,
... | dup_terms_gcd, dmp_terms_gcd)
from sympy.polys.densearith import (
dup_neg, dmp_neg,
dup_add, dmp_add,
dup_sub, dmp_sub,
dup_mul, dmp_mul,
dup_sqr,
dmp_pow,
dup_div, dmp_div,
dup_quo, dmp_quo,
dmp_expand,
dmp_add_mul,
dup_sub_mul, dmp_sub_mul,
dup_lshift,
dup_max... |
dhermes/google-cloud-python | vision/google/cloud/vision_v1/types.py | Python | apache-2.0 | 2,315 | 0 | # -*- coding: utf-8 -*-
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | le in _shared_modules:
for name, message in get_messages(module).items():
setattr(sys.modules[__name__], name, message)
names.append(name)
for module in _local_modules:
for name, message in get_messages(module).items():
message.__module__ = "google.cloud.vision_v1 | .types"
setattr(sys.modules[__name__], name, message)
names.append(name)
__all__ = tuple(sorted(names))
|
reshadh/Keepnote-LaTeX | keepnote/extensions/new_file/__init__.py | Python | gpl-2.0 | 17,272 | 0.004805 | """
KeepNote Extension
new_file
Extension allows adding new filetypes to a notebook
"""
#
# KeepNote
# Copyright (c) 2008-2011 Matt Rasmussen
# Author: Matt Rasmussen <rasmus@mit.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Publi... | ort gettext
import os
import re
import shutil
import sys
import time
import xml.etree.cElementTr | ee as etree
#_ = gettext.gettext
import keepnote
from keepnote import unicode_gtk
from keepnote.notebook import NoteBookError
from keepnote import notebook as notebooklib
from keepnote import tasklib
from keepnote import tarfile
from keepnote.gui import extension
from keepnote.gui import dialog_app_options
# pygtk ... |
hschovanec-usgs/magpy | magpy/lib/format_iaga02.py | Python | gpl-3.0 | 20,820 | 0.011479 | """
MagPy
IAGA02 input filter
Written by Roman Leonhardt June 2012
- contains test, read and write function
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from io import open
from magpy.stream import *
#global va... | = '3'
elif val[0] in ['p','P']:
stream.header['DataPublicationLevel'] = '2'
else:
stream.header['DataPublicationLevel'] = '1'
if key.find('Publication Date') > -1:
if not val == '... | tionDate'] = val
elif line.startswith('DATE'):
# data header
colsstr = line.lower().split()
varstr = ''
for it, elem in enumerate(colsstr):
if it > 2:
varstr += elem[-1]
varstr = varst... |
HailStorm32/Q.bo_stacks | qbo_webi/build/catkin_generated/generate_cached_setup.py | Python | lgpl-2.1 | 1,266 | 0.004739 | from __future__ import print_function
import argparse
import os
import stat
import sys
# find the import for catkin's python package - either from source space or from an installed underlay
if os.path.exists(os.path.join('/opt/ros/hydro/share/catkin/cmake', 'catkinConfig.cmake.in')):
sys.path.insert(0, os.path.joi... | che import generate_environment_script
except ImportError:
# search for catkin package in all workspaces and prepend to path
for workspace in "/opt/ros/hydro".split(';'):
python_path = os.path.join(workspace, 'lib/python2.7/dist-packages')
if os.path.isdir(os.path.join(python_path, 'catkin')):
... | bo_webi/build/devel/env.sh')
output_filename = '/opt/ros/hydro/stacks/qbo_webi/build/catkin_generated/setup_cached.sh'
with open(output_filename, 'w') as f:
#print('Generate script for cached setup "%s"' % output_filename)
f.write('\n'.join(code))
mode = os.stat(output_filename).st_mode
os.chmod(output_filena... |
tomturner/django-tenants | django_tenants/models.py | Python | mit | 9,732 | 0.001747 | from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.management import call_command
from django.db import models, connections, transaction
from django.urls import reverse
from django_tenants.clone import CloneSchema
from .postgresql_backend.base import _check_sc... | n jobs, and other scripts
Usage:
with Tenant.objects.get(schema_name='test') as tenant:
# run some code in tenant test
# run some code in previous tenant (public probably)
"""
connection = connections[get_tenant_database_alias()]
self._previous_te... | ion.tenant)
self.activate()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
connection = connections[get_tenant_database_alias()]
connection.set_tenant(self._previous_tenant.pop())
def activate(self):
"""
Syntax sugar that helps at django shell with... |
GbalsaC/bitnamiP | venv/lib/python2.7/site-packages/sympy/utilities/tests/test_lambdify.py | Python | agpl-3.0 | 11,262 | 0.010478 | from sympy.utilities.pytest import XFAIL, raises
from sympy import (symbols, lambdify, sqrt, sin, cos, pi, atan, Rational, Float,
Matrix, Lambda, exp, Integral, oo, I)
from sympy.printing.lambdarepr import LambdaPrinter
from sympy import mpmath
from sympy.utilities.lambdify import implemented_function
import ma... | =============== Test Translations =====================
# We can only check if all translated functions are valid. It has to be checked
# by hand if they | are complete.
def test_math_transl():
from sympy.utilities.lambdify import MATH_TRANSLATIONS
for sym, mat in MATH_TRANSLATIONS.iteritems():
assert sym in sympy.__dict__
assert mat in math.__dict__
def test_mpmath_transl():
from sympy.utilities.lambdify import MPMATH_TRANSLATIONS
for s... |
jeh/mopidy-gmusic | mopidy_gmusic/__init__.py | Python | apache-2.0 | 976 | 0 | from __future__ import unicode_literals
import os
from mopidy import config, exceptions, ext
__version__ = '0.2.2'
class GMusicExtension(ext.Extension):
dist_name = 'Mopidy-GMusic'
ext_name = 'gmusic'
version = __version__
def get_default_config(self):
conf_file = os.path.join(os.path.di... | ef get_config_schema(self):
schema = super(GMusicExtension, self).get_config_schema()
schema['username'] = config.String()
schema['password'] = config.Secret()
schema['deviceid'] = config.Str | ing(optional=True)
return schema
def validate_environment(self):
try:
import gmusicapi # noqa
except ImportError as e:
raise exceptions.ExtensionError('gmusicapi library not found', e)
pass
def get_backend_classes(self):
from .actor import GMusi... |
muxiaobai/CourseExercises | python/kaggle/competition/house-price/house.py | Python | gpl-2.0 | 4,162 | 0.010591 |
# coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
# In[2]:
train_df = pd.read_csv('./input/train.csv', index_col=0)
test_df = pd.read_csv('./input/test.csv', index_col=0)
# In[4]:
train_df.head()
# In[6]:
#label本身并不平滑。为了我们分类器的学习更加准确,我们会首先把label给“平滑化”(正态化)
import matplotlib.pyplot as plt
pr... | test = dummy_test_df.values
# ### Ridge
# In[25]:
alphas = np.logspace(-3, 2, 50)
test_scores = []
for alpha in alphas:
clf = Ridge(alpha)
test_score = np.sq | rt(-cross_val_score(clf, X_train, y_train, cv=10, scoring='neg_mean_squared_error'))
test_scores.append(np.mean(test_score))
# In[27]:
plt.plot(alphas, test_scores)
plt.title("Alpha vs CV Error");
plt.show()
# 15最佳
#
# ### RandomForestRegressor
# In[28]:
from sklearn.ensemble import RandomForestRegressor
... |
Turgon37/SMSShell | SMSShell/commands/help.py | Python | gpl-3.0 | 1,862 | 0.001611 | # -*- coding: utf8 -*-
# This file is a part of SMSShell
#
# Copyright (c) 2016-2018 Pierre GINDRAUD
#
# SMSShell 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... | or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SMSShell. If not, see <http://www.gnu.org/licenses/>. |
"""Help command
This command return some help string in function of the given input parameters
* If call without parameter : return the list of all available commands
* If call with a command name as first parameter, return the usage string of this function
In this case you can pass some other parameter that will... |
tfiers/arenberg-online | polls/migrations/0005_auto_20150428_0016.py | Python | mit | 510 | 0.001961 | # - | *- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('polls', '0004_pollanswer_zaventemtransport'),
]
operations = [
migrations.AlterField(
model_name='zaventemtransport... | |
kervi/kervi | kervi-hal-win/kervi/platforms/windows/gpio.py | Python | mit | 1,575 | 0.000635 | from kervi.hal.gpio import IGPIODeviceDriver
class GPIODriver(IGPIODeviceDriver):
def __init__(self, gpio_id="generic_gpio"):
IGPIODeviceDriver.__init__(self, gpio_id)
pass
def _get_channel_type(self, channel):
from kervi.hal.gpio import CHANNEL_TYPE_GPIO, CHANNEL_TYPE_ANALOG_IN, CHA... | :
print("define pin in")
def define_as_output(self, pin):
print("define pin out")
def define_as_pwm(self, pin, frequency, duty_cycle):
print("define pwm")
def set(self, pin, sta | te):
print("set pin", state)
def get(self, pin):
print("get pin")
return 0
def pwm_start(self, channel, duty_cycle=None, frequency=None):
print("start pwm")
def pwm_stop(self, pin):
print("stop pwm")
def listen(self, pin, callback, bounce_time=0):
prin... |
arizona-phonological-imaging-lab/autotres | a3/constants.py | Python | apache-2.0 | 43 | 0.046512 | #!/usr/bin/env | python3
_version = (0,4, | 0)
|
orviz/ooi | ooi/tests/fakes.py | Python | apache-2.0 | 17,912 | 0 | # -*- coding: utf-8 -*-
# Copyright 2015 Spanish National Research Council
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# | http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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.
import json
import re
import uuid
import webob.dec
import webob.exc
from ooi import utils
import ooi.wsgi
application_url = "https://foo.example.org:8774/ooiv1"
tenants = {
"foo": {"id": uuid.uuid4(... |
Kaarel94/Ozobot-Python | ozopython/__init__.py | Python | mit | 1,375 | 0.004364 | from tkinter import ttk
from ozopython.colorLanguageTranslator import ColorLanguageTranslator
from .ozopython import *
from tkinter import *
def run(filename):
code = ozopython.compile(filename)
colorcode = ColorLanguageTranslator.translate(code)
def load(prog, prog_bar):
colormap = {
... | }
head, *t | ail = prog
canvas.itemconfig(circle, fill=colormap[head])
prog = tail
prog_bar["value"] = len(colorcode) - len(prog)
if len(prog) != 0:
canvas.after(50, lambda: load(prog, prog_bar))
window = Tk()
progress = ttk.Progressbar(window, orient="horizontal", length='5c', ... |
odoousers2014/odoo_addons-2 | clv_batch/history/__init__.py | Python | agpl-3.0 | 1,429 | 0.011896 | # -*- encoding: utf-8 -*-
################################################################################
# | #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# #
# This program is free software: you can redistribute it and/or modify #
# it un... | nse, 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 war... |
rcocetta/kano-profile | tools/print_needed_variables.py | Python | gpl-2.0 | 1,082 | 0.000924 | #!/usr/bin/env python
# print_needed_variables.py
#
# Copyright (C) 2014, 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
import os
import sys
if __name__ == '__main__' and __package__ is None:
dir_path = os.path.abspath(os.path.join(os.path.dirname(__f... | import write_json, uniqify_list
all_rules = load_badge_rules()
variables_needed = dict()
for category, subcats in all_ | rules.iteritems():
for subcat, items in subcats.iteritems():
for item, rules in items.iteritems():
targets = rules['targets']
for target in targets:
app = target[0]
variable = target[1]
variables_needed.setdefault(app, list()).append(va... |
borisbabic/browser_cookie3 | setup.py | Python | lgpl-3.0 | 632 | 0.003165 | from distutils.core import setup
setup(
name='browser-cookie3',
version='0.13.0',
packages=['browser_cookie3'],
# look for package contents in current directory
package_dir={'browser_cookie3': '.'},
author='Boris Babic',
author_email='boris. | ivan.babic@gmail.com',
| description='Loads cookies from your browser into a cookiejar object so can download with urllib and other libraries the same content you see in the web browser.',
url='https://github.com/borisbabic/browser_cookie3',
install_requires=['pyaes', 'pbkdf2', 'keyring', 'lz4', 'pycryptodome', 'SecretStorage'],
... |
dana-i2cat/felix | ofam/src/src/ext/sfa/trust/gid.py | Python | apache-2.0 | 9,265 | 0.004425 | #----------------------------------------------------------------------
# Copyright (c) 2008 Board of Trustees, Princeton University
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work without restriction, i... | rents:
result += " "*indent + "parent:\n"
| result += self.parent.dump_string(indent+4, dump_parents)
return result
##
# Verify the chain of authenticity of the GID. First perform the checks
# of the certificate class (verifying that each parent signs the child,
# etc). In addition, GIDs also confirm that the parent's HRN is a... |
UMD-DRASTIC/drastic | drastic/DrasticLoader/FileNameSource.py | Python | agpl-3.0 | 7,914 | 0.006444 | # coding=utf-8
"""Ingest workflow management tool
FileNameSource Class
"""
__copyright__ = "Copyright (C) 2016 University of Maryland"
__license__ = "GNU AFFERO GENERAL PUBLIC LICENSE, Version 3"
import abc
import os
import sys
import psycopg2
class FileNameSource:
def __init__(self): pass
def __ite... |
for v in self.cs1: print '{0:-10s}\t{1:,}'.format(*v)
except Excep | tion as e:
print e
def _setup_db(self, table):
cs = self.cnx.cursor()
# Create the status Enum
try:
cs.execute("CREATE TYPE resource_status AS ENUM ('READY','IN-PROGRESS','DONE','BROKEN','VERIFIED')")
except:
cs.connection.rollback()
#
... |
ULHPC/modules | easybuild/easybuild-framework/test/framework/utilities.py | Python | mit | 14,540 | 0.002682 | ##
# Copyright 2012-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | path.dirname(os.path.abspath(__file__))
self.test_sourcepath = os.path.join(testdir, 'sandbox', 'sources')
os.environ['EASYBUILD_SOURCEPATH'] = self.test_sourcepath
os. | environ['EASYBUILD_PREFIX'] = self.test_prefix
self.test_buildpath = tempfile.mkdtemp()
os.environ['EASYBUILD_BUILDPATH'] = self.test_buildpath
self.test_installpath = tempfile.mkdtemp()
os.environ['EASYBUILD_INSTALLPATH'] = self.test_installpath
# make sure that the tests only ... |
MoroGasper/client | client/plugins/ui/tk/animate.py | Python | gpl-3.0 | 1,581 | 0.003163 | import io
import base64
import gevent
from Tkinter import Label
from PIL import ImageTk, Image
class AnimatedImgLabel(Label):
# http://stackoverflow.com/questions/7960600/python-tkinter-display-animated-gif-using-pil
def __init__(self, master, data, encoding='base64', **kwargs):
if encoding == 'base64... | st()
for frame in seq:
#frame = frame.convert('RGBA')
self.frames.append(ImageTk.PhotoImage(frame))
self.idx = 0
self.first = self.frames[0]
Label.__init__(self, master, image=self.first, **kwargs)
self.greenlet = gevent.spawn_later(self.delay, self.pla... | Label.destroy(self)
def play(self):
try:
self.config(image=self.frames[self.idx])
self.master.update()
self.idx += 1
if self.idx == len(self.frames):
self.idx = 0
self.greenlet = gevent.spawn_later(self.delay, self.play)
... |
theno/fabsetup | fabsetup/fabfile/setup/powerline.py | Python | mit | 5,053 | 0.00099 | import os.path
from fabric.api import env
from fabsetup.fabutils import checkup_git_repo_legacy, needs_packages
from fabsetup.fabutils import needs_repo_fabsetup_custom, suggest_localhost
from fabsetup.fabutils import install_file_legacy, run, subtask, subsubtask, task
from fabsetup.utils import flo, update_or_append... | _powerline():
'''
More infos:
https://powerline.readthedocs.io/en/latest/installation.html#pip-installation
'''
checkup_git_repo_legacy('https://github.com/powerline/powerline.git')
path_to_powerline = os.path.expanduser('~/repos/powerline')
run(flo('pip install --user --editable={path_to_... | rline/powerline/bindings'
scripts_dir = '~/repos/powerline/scripts'
return bindings_dir, scripts_dir
@subtask
def set_up_powerline_fonts():
checkup_git_repo_legacy('https://github.com/powerline/fonts.git',
name='powerline-fonts')
# install fonts into ~/.local/share/fonts
... |
janezhango/BigDataMachineLearning | py/testdir_ec2/test_rf_iris.py | Python | apache-2.0 | 2,017 | 0.011403 | import unittest
import random, sys
sys.path.extend(['.','..','py'])
import h2o, h2o_cmd, h2o_rf, h2o_hosts, h2o_import as h2i
# RF train parameters
paramsTrainRF = {
'ntree' : 100,
'depth' : 300,
'bin_limit' : 20000,
'ignore' : None,
'stat_ty... | # we don't need to specify. But put this here and (ab | ove if used)
# in case a dataset doesn't use last col
'response_variable': None,
'out_of_bag_error_estimate': 0,
'timeoutSecs': 14800,
}
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def se... |
kaplun/inspire-next | tests/integration/test_latex_exporting.py | Python | gpl-3.0 | 2,222 | 0.0027 | # -*- coding: utf-8 -*-
#
# This file is part of INSPIRE.
# Copyright (C) 2014-2017 CERN.
#
# INSPIRE 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 ... | w.gnu.org/licenses/>.
# |
# In applying this license, CERN does not waive the privileges and immunities
# granted to it by virtue of its status as an Intergovernmental Organization
# or submit itself to any jurisdiction.
from __future__ import absolute_import, division, print_function
from datetime import date
from inspirehep.utils.latex im... |
pvagner/orca | test/keystrokes/oowriter/ui_role_list_item.py | Python | lgpl-2.1 | 1,384 | 0.001445 | #!/usr/bin/python
"""Test to verify presentation of selectable list items."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(KeyComboAction("<Control><Shift>n"))
sequence.append(KeyComboAction("Tab"))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAct... | list item",
["BRAILLE LINE: 'soffice application Template Manager frame Template Manager dialog Drawings page tab list | Presentation Backgrounds list item'",
" VISIBLE: 'Presentation Backgrounds list it', cursor=1",
"SPEECH OUTPUT: 'Presentation Backgrounds'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("Left"))
sequence.append(utils.AssertPresentationAction(
"3. Left to previous l... |
dougthor42/GDWCalc | archive/GDWCalc_Lite v1.3.py | Python | gpl-2.0 | 8,852 | 0.001695 | """
@name: GDWCalc_Lite.py
@vers: 1.3
@author: Douglas Thor
@created: 2013-04-19
@modified: 2013-10-08
@descr: Calcualtes Gross Die per Wafer (GDW), accounting for
wafer flat, edge exclusion, and front-side-scribe (FSS)
... | h.ceil(dia/dieY))
# I | f we're centered on the wafer, we need to add one to the axis count
if centerType[0] == "odd": nX += 1
if centerType[1] == "odd": nY += 1
# make a list of (x, y) center coordinate pairs
centers = []
for i in range(nX):
for j in range(nY):
centers.append(((i-nX/2) * dieX + dieCen... |
JulyKikuAkita/PythonPrac | cs15211/WallsandGates.py | Python | apache-2.0 | 8,470 | 0.002597 | __source__ = 'https://leetcode.com/problems/walls-and-gates/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/walls-and-gates.py
# Time: O(m * n)
# Space: O(g)
#
# Description: Leetcode # 286. Walls and Gates
#
# You are given a m x n 2D grid initialized with these three possible values.
#
# -1 -... | stack.append((ii, jj+1, dist + 1))
stack.append((ii, jj-1, dist + 1))
#BFS -2
class Solution2(object):
def wallsAndGates(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: void Do not return anything, modify rooms in-place instead.
"""
... | if rooms[i][j] == 0:
stack.append([i*n +j, 0])
cube = [0, 1, 0, -1, 0]
while stack:
digit, dis = stack.pop()
x = digit / n
y = digit % n
for k in xrange(4):
p = x + cube[k]
q = y + cube[k+1]
... |
doraemonext/DEOnlineJudge | api/account/urls.py | Python | mit | 541 | 0.005545 | # -*- coding: utf-8 -*-
from django.conf.urls import url
from api.account.views import RegistrationAPI, LoginAPI, LogoutAPI, UpdatePasswordAPI, Upd | ateProfileAPI
urlpatterns = [
url(r'^registration/$', Registratio | nAPI.as_view(), name='registration'),
url(r'^login/$', LoginAPI.as_view(), name='login'),
url(r'^logout/$', LogoutAPI.as_view(), name='logout'),
url(r'^update_password/$', UpdatePasswordAPI.as_view(), name='update_password'),
url(r'^update_profile/$', UpdateProfileAPI.as_view(), name='update_profile'),
... |
nikdoof/test-auth | app/conf/celeryschedule.py | Python | bsd-3-clause | 1,084 | 0 | from datetime i | mport timedelta
CELERYBEAT_SCHEDULE = {
"reddit-validations": {
"task": "reddit.tasks.process_validations",
"schedule": timedelta(minutes=10),
},
| "eveapi-update": {
"task": "eve_api.tasks.account.queue_apikey_updates",
"schedule": timedelta(minutes=10),
},
"alliance-update": {
"task": "eve_api.tasks.alliance.import_alliance_details",
"schedule": timedelta(hours=6),
},
"api-log-clear": {
"task": "eve_prox... |
sfinucane/deviceutils | deviceutils/action/query.py | Python | apache-2.0 | 2,510 | 0.004382 | #!/usr/bin/env python
"""
"""
# Python 2.6 and newer support
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from future.builtins import (
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
... | self.io = io
self.send_encoding = send_encoding
self.receive_encoding = receive_encoding
self.receive_count = receive_count
self.__response = None
@property
def value(self):
"""The most recently retrieved response.
"""
return self.__res... | Any arguments and/or keyword arguments will be passed to ``format``,
which is called on the command message before sending.
"""
if isinstance(self.send_encoding, DefaultEncoding):
with channel(self.device, self.io) as dev:
dev.send(self.message.format(*args, **kwa... |
hybrid-storage-dev/cinder-fs-111t-hybrid-cherry | volume/drivers/hitachi/hbsd_iscsi.py | Python | apache-2.0 | 16,385 | 0 | # Copyright (C) 2014, Hitachi, Ltd.
#
# Licensed under the Apache License, Version | 2.0 (the "License"); you may
# not use this file except in compliance with the Li | cense. 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 CONDITIONS OF ANY KIND, either express o... |
pmisik/buildbot | master/buildbot/test/util/changesource.py | Python | gpl-2.0 | 3,747 | 0.000267 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | ng:
yield self.changesource.stopService()
yield self.changesource.disownServiceParent()
return
@defer.inlineCallbacks
def attachChangeSource(self, cs):
"Set up a change source for testing; sets its .master attribute"
self.changesource = cs
# FIXME some change... | ce.master = self.master
except AttributeError:
yield self.changesource.setServiceParent(self.master)
# configure the service to let secret manager render the secrets
try:
yield self.changesource.configureService()
except NotImplementedError: # non-reconfigurable... |
jyi/ITSP | prophet-gpl/tools/libtiff-prepare-test.py | Python | mit | 1,700 | 0.018235 | # Copyright (C) 2016 Fan Long, Martin Rianrd and MIT CSAIL
# Prophet
#
# This file is part of Prophet.
#
# Prophet 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 y... | Public License
# along with Prophet. If not, see <http://www.gnu.org/licenses/>.
#!/usr/bin/env python
from os import system, chdir, getcwd
from sys import argv
import subprocess
build_cmd = argv[1];
dep_dir = argv[2];
src_dir = argv[3];
test_dir = argv[4];
rev = argv[5];
if (len(argv) < 7):
out_dir = test_dir + ... | " + rev);
system("git clean -f -d");
chdir(ori_dir);
system(build_cmd + " -p " + dep_dir + " " + work_dir);
system("mv " + work_dir + "/test " + work_dir+"/ori_test");
system("cp -rf " + test_dir + " " + work_dir + "/test");
chdir(work_dir + "/test");
system("GENEXPOUT=1 CMPEXPOUT=0 make check");
chdir(ori_dir);
pri... |
UpYou/relay | usrp_transmit_path.py | Python | gpl-3.0 | 3,809 | 0.006563 | #
# Copyright 2009 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#... | HANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-130... | #
from gnuradio import gr
import usrp_options
import transmit_path
from pick_bitrate import pick_tx_bitrate
from gnuradio import eng_notation
def add_freq_option(parser):
"""
Hackery that has the -f / --freq option set both tx_freq and rx_freq
"""
def freq_callback(option, opt_str, value, parser):
... |
b3yond/ticketfrei | session.py | Python | isc | 1,063 | 0.001881 | from bottle import redirect, request, abort, response
from db import db
from functools import wraps
from inspect import Signature
from user import User
class SessionPlugin(object):
name = 'SessionPlugin'
keyword = 'user'
api = 2
def __init__(self, loginpage):
self.loginpage = loginpage
d... | callback).parameters:
@wraps(callback)
def wrapper(*args, **kwargs):
uid = request.get_cookie('uid', secret=db.get_secret())
if uid is None:
return redirect(self.loginpage)
kwargs[self.keyword] = User(uid)
if req... | secret=db.get_secret()):
abort(400)
return callback(*args, **kwargs)
return wrapper
else:
return callback
|
jkonecny12/anaconda | pyanaconda/modules/payloads/payload/dnf/initialization.py | Python | gpl-2.0 | 1,604 | 0.000623 | #
# Copyright (C) 2020 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be... | replicated with the express permission of
# Red Hat, Inc.
#
import dnf.logging
import logging
import libdnf
DNF_LIBREPO_LOG = "/tmp/dnf.librepo.log"
DNF_LOGGER = "dnf"
def configure_dnf_logging():
"""Configure the DNF logging."""
# Set up librepo.
# This is still required even when the librepo has a sep... | f.repo.LibrepoLog.addHandler(DNF_LIBREPO_LOG)
# Set up DNF. Increase the log level to the custom DDEBUG level.
dnf_logger = logging.getLogger(DNF_LOGGER)
dnf_logger.setLevel(dnf.logging.DDEBUG)
|
rtts/qqq | qqq/templatetags/customfilters.py | Python | gpl-3.0 | 807 | 0.032218 | from django import template
register = template.Library()
@register.filter
def multiplyby(value, arg):
return in | t(value * arg)
@register.filter
def subtractfrom(value, arg):
return arg - value
@register.filter
def plus(value, arg):
return value + arg
@register. | filter
def appears_in(value, arg):
for name in arg:
if name == value: return True
return False
@register.filter
def length(value):
return len(value)
@register.filter
def user_can_downvote(votes, id):
if id not in votes: return True
if votes[id].is_downvote(): return False
return True
@register.filter... |
sajuptpm/neutron-ipam | neutron/tests/unit/services/loadbalancer/agent/test_api.py | Python | apache-2.0 | 4,901 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 New Dream Network, LLC (DreamHost)
#
# 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... | get_logical_device(self):
self.assertEqual(
self.api.get_logical_device('pool_id'),
self.mock_call.return_value
)
self.make_msg.assert_called_once_with(
'get_logical_device',
pool_id='pool_id')
self.mock_call.assert_called_once_with(
... | turn_value,
topic='topic'
)
def test_pool_destroyed(self):
self.assertEqual(
self.api.pool_destroyed('pool_id'),
self.mock_call.return_value
)
self.make_msg.assert_called_once_with(
'pool_destroyed',
pool_id='pool_id')
... |
redondomarco/useradm | src/models/unificada.py | Python | gpl-3.0 | 16,421 | 0.015982 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb, sys
# for ide
if False:
from gluon import *
def clumusuario(email):
"""consulto usuario tabla clave unificada"""
dbmysql = MySQLdb.connect(
host=myconf.take('datos.clum_srv'),
port=int(myconf.take('datos.clum_port')),
... | passwd=myconf.take('datos.clum_pass'),
db=myconf.take('datos.clum_db'))
cursor = dbmysql.cursor()
cursor.execute("""select email from auth_user where username='%s';"""%(usuario))
registro=cursor.fetchall()
#log("mailalt: "+str(registro))
dbmysql.close()
... | registro:
salida=['error','no creado']
elif registro[0][0]=='':
salida=['error','no configurado']
else:
salida=['ok',str(registro[0][0])]
return salida
def consulta_autogestion(usuario):
"""consulto email tabla clave unificada"""
try:
dbmysql = MySQLdb.connect(
... |
jgreener64/pdb-benchmarks | checkwholepdb/checkwholepdb.py | Python | mit | 2,107 | 0.004271 | # Test which PDB entries error on PDB/mmCIF parsers
# Writes output to a file labelled with the week
import os
from datetime import datetime
from math import ceil
from Bio.PDB import PDBList
from Bio.PDB.PDBParser import PDBParser
from Bio.PDB.MMCIFParser import MMCIFParser
start = datetime.now()
basedir = "."
pdbl =... | rmat(basedir, p)):
try:
s = pdb_parser.get_structure("", "{}/pdb{}.ent".format(basedir, p))
except:
outstrs.append("{} - PDB parsing error".format(pu))
os.remove("{}/pdb{}.ent".format(basedir, p))
try:
pdbl.retrieve_pdb_file(p, pdir=basedir, file_format="mmCif... | .append("{} - no mmCIF download".format(pu))
if os.path.isfile("{}/{}.cif".format(basedir, p)):
try:
s = mmcif_parser.get_structure("", "{}/{}.cif".format(basedir, p))
except:
outstrs.append("{} - mmCIF parsing error".format(pu))
os.remove("{}/{}.cif".format(basedir, ... |
DigitalMockingbird/EULAThingy | eulathingy/urls.py | Python | mit | 637 | 0.006279 | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('dashboard.urls', namespa | ce='dashboard')),
url(r'^admin/', include(admin.site.urls)),
url(r'^dashboard/', include('dashboard.urls', namespace='dashboard')),
# url(r'^uploads/', include('uploads.urls', namespace='uploads')),
) + s | tatic(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
|
heathseals/CouchPotatoServer | libs/pyutil/PickleSaver.py | Python | gpl-3.0 | 8,932 | 0.002799 | # Copyright (c) 2001 Autonomous Zone Industries
# Copyright (c) 2002-2009 Zooko Wilcox-O'Hearn
# This file is part of pyutil; see README.rst for licensing terms.
"""
An object that makes some of the attributes of your class persistent, pickling
them and lazily writing them to a file.
"""
# from the Python Standard... | self.valstr = None # the pickled (serialized, string) contents of the attributes that should be saved
def _save_to_disk(self):
if self.valstr is not None:
log.msg("%s._save_to_disk(): fname: %s" % (self.objname, self.fname,))
of = open( | self.fname + ".tmp", "wb")
of.write(self.valstr)
of.flush()
of.close()
of = None
fileutil.remove_if_possible(self.fname)
fileutil.rename(self.fname + ".tmp", self.fname)
log.msg("%s._save_to_disk(): now, havi... |
Tatsh-ansible/ansible | lib/ansible/modules/cloud/google/gce_instance_template.py | Python | gpl-3.0 | 19,433 | 0.000412 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | .com"
credentials_file: "/path/to/your-key.json"
project_id: "your-project-name"
tasks:
| - name: create instance template
gce_instance_template:
name: foo
size: n1-standard-1
state: present
project_id: "{{ project_id }}"
credentials_file: "{{ credentials_file }}"
service_account_email: "{{ service_account_email }}"
disks_gce_struct:
... |
arnavd96/Cinemiezer | myvenv/lib/python3.4/site-packages/music21/romanText/rtObjects.py | Python | mit | 48,702 | 0.004312 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: romanText/rtObjects.py
# Purpose: music21 objects for processing roman numeral analysis text files
#
# Authors: Christopher Ariza
# Michael Scott Cuthbert
#
# Copyright: Co... | True
>>> tag = romanText.rtObjects.RTTagged('Nothing: Nothing at all.')
>>> tag.isTimeSignature()
False
TimeSignature header data can be found intermingled with measures.
'''
if self.tag.lower() in ['timesignature', 'time signature']:
return True
... | ag = romanText.rtObjects.RTTagged('KeySignature: This is a key signature.')
>>> tag.isKeySignature()
True
>>> tag = romanText.rtObjects.RTTagged('Nothing: Nothing at all.')
>>> tag.isKeySignature()
False
KeySignatures are a type of tagged data found outside of measures,... |
lmazuel/azure-sdk-for-python | azure-mgmt-monitor/azure/mgmt/monitor/models/webhook_receiver_py3.py | Python | mit | 1,347 | 0 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ver. Names must be
unique ac | ross all receivers within an action group.
:type name: str
:param service_uri: Required. The URI where webhooks should be sent.
:type service_uri: str
"""
_validation = {
'name': {'required': True},
'service_uri': {'required': True},
}
_attribute_map = {
'name': {'k... |
bbreslauer/PySciPlot | src/ui/Ui_ExportData.py | Python | gpl-3.0 | 13,612 | 0.004187 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Ui_ExportData.ui'
#
# Created: Sat May 28 00:16:57 2011
# by: PyQt4 UI code generator 4.8.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except A... | .delimiterButt | onGroup.addButton(self.delimitedCommaRadio)
self.horizontalLayout.addWidget(self.delimitedCommaRadio)
self.delimitedTabRadio = QtGui.QRadioButton(self.delimitedDelimiterGroupBox)
self.delimitedTabRadio.setObjectName(_fromUtf8("delimitedTabRadio"))
self.delimiterButtonGroup.addButton(self... |
vileopratama/vitech | src/addons/point_of_sale/report/pos_receipt.py | Python | mit | 2,154 | 0.003714 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import time
from openerp.osv import osv
from openerp.report import report_sxw
def titlize(journal_name):
words = journal_name.split()
while words.pop() != 'journal':
continue
return ' '.join(words)
... | 'net': self.netamount,
'get_journal_amt': self._get_journal_amt,
'address': partner or False,
'titlize': titlize
})
def netamount(self, order_line_id):
sql = 'select (qty*price_unit) as net_price from pos_order_line where id = %s'
self.cr.execute(sql, (or... | |
Oreder/PythonSelfStudy | TestModule/Tmin.py | Python | mit | 122 | 0 | de | f Tmin(arg0, *args):
_min = arg0
for arg in args:
if arg < _min:
_min = | arg
return _min
|
netkicorp/addressimo | addressimo/config.py | Python | bsd-3-clause | 2,378 | 0.002103 | __author__ = 'mdavid'
from attrdict import AttrDict
import os
# Addressimo Configuration
config = AttrDict()
# General Setup
config.site_url = 'addressimo.netki.com'
config.cache_loader_process_pool_size = 4
config.cache_loader_blocktx_pool_size = 15
config.bip32_enabled = True
config.bip70_enabled = True
config.bip... | _threshold = 2
config.payment_submit_tx_retries = 5
# Admin public key for authenticating signatures for signed reques | ts to get_branches endpoint (hex encoded).
# That endpoint is used for HD wallets to retrieve which branches Addressimo has served addresses for
config.admin_public_key = 'ac79cd6b0ac5f2a6234996595cb2d91fceaa0b9d9a6495f12f1161c074587bd19ae86928bddea635c930c09ea9c7de1a6a9c468f9afd18fbaeed45d09564ded6'
#config.signer_ap... |
sauloal/cnidaria | scripts/venv/lib/python2.7/site-packages/cogent/app/ilm.py | Python | mit | 3,567 | 0.017101 | #!/usr/bin/env python
from cogent.app.util import CommandLineApplication,\
CommandLineAppResult, ResultPath
from cogent.app.parameters import Parameter,ValuedParameter,Parameters
__author__ = "Shandy Wikman"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__contributors__ = ["Shandy Wikman"]
__license__... |
Main options:
-L l: minimum loop length (default=3)
-V v: minimum virtual loop length (default=3)
-H h: minimum helix length (default=3)
-N n: number of helices selected per iteration (default=1)
-I i: number of iterations before termination(default=unlimited)
"""
... | ',Name='V',Delimiter=' '),
'-H':ValuedParameter(Prefix='-',Name='H',Delimiter=' '),
'-N':ValuedParameter(Prefix='-',Name='N',Delimiter=' '),
'-I':ValuedParameter(Prefix='-',Name='I',Delimiter=' ')}
_command = 'ilm'
_input_handler = '_input_as_string'
class hlxplot(CommandLineApplicatio... |
ankurjimmy/catawampus | tr/vendor/tornado/maint/appengine/py27/cgi_runtests.py | Python | apache-2.0 | 25 | 0.04 | ../ | common/cgi_runtests.p | y |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.