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 |
|---|---|---|---|---|---|---|---|---|
revolutionaryG/androguard | androgui.py | Python | apache-2.0 | 1,817 | 0.001101 | #!/usr/bin/env python2
'''Androguard Gui'''
import argparse
import sys
from androguard.core import androconf
from androguard.session import Session
from androguard.gui.mainwindow import MainWindow
from androguard.misc import init_print_colors
from PySide import QtCore, QtGui
from threading import Thread
class Ipyt... | ("-c", "--console", action="store_true", default=False)
args = parser.parse_args()
if args.debug:
androconf.set_debug()
# We need that to save huge sessions when leaving and avoid
# RuntimeError: maximum recursion depth exceeded while pickling an object
# or
# RuntimeError: maximum re... | Session(export_ipython=args.console)
console = None
if args.console:
console = IpythonConsole()
console.start()
app = QtGui.QApplication(sys.argv)
window = MainWindow(session=session, input_file=args.input_file)
window.resize(1024, 768)
window.show()
sys.exit(app.exec_())
|
christianurich/VIBe2UrbanSim | 3rdparty/opus/src/biocomplexity/examples/estimation_lccm_specification_ub91to95.py | Python | gpl-2.0 | 10,640 | 0.083177 | # Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
specification = {}
specification = {
2:
{
"equation_ids":(1,2),
"constant":(0, "act_2_2"),
"blmz":("blmz_2_1", 0),
"cd1":("cd1_2_1", 0),
"dag":("dag_2_1", 0),
"d... |
5:
{
"equation_ids":(1,2,3,5,6,7), # note: this is the to_id's
"constant":("act_5_1","act_5_2","act_5_3","act_5_5",0,0),
"aai":(0,"aai_5_2","aai_5_3", 0,"aai_5_6","aai_5_7"),
"amps":("amps_5_1","amps_5_2",0, 0,0,"amps_5_7"),
# # "blmz":(0,0,0, 0,"blmz_5_6",0),
# # "c750":("c750_5_1",0,0... | "),
# # "dc":(0,0,0, 0,0,"dc_5_7"),
# # "dcbd":("dcbd_5_1",0,0, 0,0,0),
"dcri":("dcri_5_1",0,0, 0,0,0),
"de":("de_5_1","de_5_2","de_5_3", 0,0,0),
"dloc":("dloc_5_1","dloc_5_2","dloc_5_3", 0,0,0),
"dnlr":(0,"dnlr_5_2","dnlr_5_3", 0,0,0),
"dos":("dos_5_1",0,0, 0,0,0),
"dprd":("dprd_5_1"... |
catharsis/bugger | bugger/exceptions.py | Python | bsd-2-clause | 191 | 0.026178 | class NoPaging(Exception): pass
class BuggerLoginError(Exception): pass
class BugNo | tFound(Exception): pass
class BugRenderError(Exception): pass
class BackendConne | ctionError(Exception): pass
|
indashnet/InDashNet.Open.UN2000 | android/external/chromium_org/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/run_webkit_tests.py | Python | apache-2.0 | 18,696 | 0.007863 | # Copyright (C) 2010 Google Inc. All rights reserved.
# Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
# Copyright (C) 2011 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following ... | exceptions"),
optparse.make_option("--reset-results" | , action="store_true",
default=False, help="Reset expectations to the "
"generated results in their existing location."),
optparse.make_option("--no-new-test-results", action="store_false",
dest="new_test_results", default=True,
help="Don't create new baselin... |
e0ne/python-brickagentclient | brickclient/tests/test_service_catalog.py | Python | apache-2.0 | 10,473 | 0 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | "id": "235",
"name": "object-store:admin",
"tenantId": "1",
}
],
"roles_links": [],
},
"serviceCatalo | g": [
{
"name": "Cloud Servers",
"type": "compute",
"endpoints": [
{
"tenantId": "1",
"publicURL": "https://compute1.host/v1/1234",
"internalURL": "https://compute1.hos... |
beav/pulp | server/test/unit/server/content/sources/test_container.py | Python | gpl-2.0 | 34,946 | 0.000286 | # Copyright (c) 2014 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or implied,
# including the impl... | e int']
@patch('pulp.server.content.sources. | container.ContentSource.load_all')
@patch('pulp.server.content.sources.container.managers.content_catalog_manager')
def test_forced_refresh(self, fake_manager, fake_load):
sources = {}
canceled = Mock()
canceled.is_set.return_value = False
for n in range(3):
s = Conte... |
emmett9001/schema.to | schemato/distillery.py | Python | apache-2.0 | 1,053 | 0 | from .distillers import Distill, Distiller
class NewsDistiller(Distiller):
site = Distill("og:site_name")
title = Distill("s:headline", "og:title")
image_url = Distill("s:associatedMedia.ImageObject/url", "og:image")
pub_date = Distill("s:datePublished")
author = Distill("s:creator.Person/name", "... | still("s:articleSection")
description = Distill("s:description", "og:description")
link = Distill("s:url", "og:url")
id = Distill("s:identifier")
class ParselyDistiller(Distiller):
site = Distill("og:site_name")
title = Distill("pp:title", "s:headline", "og:title")
image_url = Distill(
... | rson/name", "s:author")
section = Distill("pp:section", "s:articleSection")
link = Distill("pp:link", "og:url", "s:url")
post_id = Distill("pp:post_id", "s:identifier")
page_type = Distill("pp:type")
|
rombie/contrail-controller | src/nodemgr/common/windows_process_mem_cpu.py | Python | apache-2.0 | 1,375 | 0.001455 | #
# Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.
#
import psutil
import time
from sandesh.nodeinfo.cpuinfo.ttypes import ProcessCpuInfo
class WindowsProcessMemCpu | UsageData(object):
def __init__(self, pid, last_cpu, last_time):
self.last_cpu = last_cpu
self.last_time = last_time
self.pid = pid
def _get_process_cpu_share(self, current_cpu):
last_cpu = self.last_cpu
last_time = self.last_time
current_time = time.time()
... | time = current_time - last_time
self.last_cpu = current_cpu
self.last_time = current_time
if interval_time > 0:
usage_percent = 100 * usage_time / interval_time
cpu_share = round(usage_percent / psutil.cpu_count(), 2)
return cpu_share
else:
... |
zonca/petsc4py | test/test_sys.py | Python | bsd-2-clause | 1,904 | 0.002626 | import unittest
from petsc4py import PETSc
# --------------------------------------------------------------------
class TestVersion(unittest.TestCase):
def testGetVersion(self):
version = PETSc.Sys.getVersion()
self.assertTrue(version > (0, 0, 0))
v, patch = PETSc.Sys.getVersion(patch=Tru... | LD)
PETSc.Sys.setDefaultComm(PETSc.COMM_SELF)
c = PETSc.Sys.getDefaultComm()
self.assertEqual(c, PETSc.COMM_SELF)
| PETSc.Sys.setDefaultComm(PETSc.COMM_WORLD)
c = PETSc.Sys.getDefaultComm()
self.assertEqual(c, PETSc.COMM_WORLD)
f = lambda : PETSc.Sys.setDefaultComm(PETSc.COMM_NULL)
self.assertRaises(ValueError, f)
# --------------------------------------------------------------------
if __na... |
xow/mdk | mdk/commands/plugin.py | Python | gpl-3.0 | 7,095 | 0.001269 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Moodle Development Kit
Copyright (c) 2013 Frédéric Massart - FMCorz.net
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 Lic... | ['name'],
{
'default': None,
'help': 'name of the instance to work on',
'metavar': 'name',
'nargs': '?'
... | }
),
(
['-s', '--strict'],
{
'action': 'store_true',
'help': 'prevent the download of a parent vers... |
ted-ross/qpid-dispatch | tools/scraper/amqp_detail.py | Python | apache-2.0 | 50,089 | 0.003094 | #!/usr/bin/env python
#
# 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
# ... | /th>"
@classmethod
def show_table_heads2(cls):
return "<th><span title=\"Unsettled transfers\">UNSTL</span></th>" \
"<th><span title=\"Presettled transfers\">PRE</span></th>" \
"<th><span title=\"Disposition: accepted\">ACCPT</span></th>" \
"<th><span title=... | "<th><span title=\"Disposition: modified\">MDFD</span></th>" \
"<th><span title=\"Transfer abort=true\">ABRT</span></th>" \
"<th><span title=\"Transfer: more=true\">MOR</span></th>" \
"<th><span title=\"Transfer: incomplete; all frames had more=true\">INC</span></th>" \
... |
TouK/vumi | vumi/dispatchers/simple/dispatcher.py | Python | bsd-3-clause | 1,295 | 0 |
from twisted.python import log
from twisted.internet.defer import inlineCallbacks
from vumi.service import Worker
class MessageHandler(object):
def __init__(self, worker, queue_name, publisher, publish_keys):
self.worker = worker
self.queue_name = queue_name
self.publisher = publisher
... | ublish_to("simpledispatcher.fallback")
for queue_name, publish_keys in self.config['route_mappings'].items():
h = MessageHandler(self, queue_name, self.publisher, publish_keys)
yield self.consume(queue_name, h.consume_message)
def s | topWorker(self):
log.msg("Stopping SimpleDispatcher")
|
gibil5/openhealth | models/order/commons/acc_lib.py | Python | agpl-3.0 | 2,687 | 0.037588 | # -*- coding: utf-8 -*-
"""
Acc Lib
- Used by
account contasis pre
account line pre
Created: 11 oct 2020
Last up: 29 mar 2021
"""
import datetime
class AccFuncs:
@staticmethod
def static_method():
# the static method gets passed nothing
return "I am a static method"
@classmethod
def class_meth... | , date_end),
],
#order='x_serial_nr asc',
#limit=1,
)
return orders, count
# get_orders_filter
# ------------------------------------------------------ Get Net and Tax -------
# Get Net and Tax
@classmethod
def get_net_tax(cls, amount):
# Net
x = amount / ... | Tax
x = amount * 0.18
tax = float("{0:.2f}".format(x))
return net, tax
# get_net_tax
|
Ramyak/CodingPractice | algo_practice/sort/binary_search.py | Python | gpl-2.0 | 4,558 | 0 | #!/usr/bin/env python
a = [5, 3, 6, 4, 1, 2, 0, 8, 9]
class Node(object):
def __init__(self, value, left, right):
self.value, self.left, self.right = value, left, right
def __repr__(self):
return str(self.value)
class BTree(object):
def __init__(self, value):
self.root_node = N... | ')
if cur_node.right:
self.print_nodes(cur_node.right, print_array, cur_depth + 1)
else:
print_array[cur_depth + 1].append(' ')
if is_root_node:
for i in range(len(print_array)):
| print '{}{}'.format(''.join(' ' * (total_depth - i + 1)),
' '.join(print_array[i]))
def find_node(self, value, cur_node=None):
if cur_node is None:
cur_node = self.root_node
if cur_node.value == value:
return cur_node
... |
CCI-MOC/GUI-Backend | service/quota.py | Python | apache-2.0 | 8,295 | 0.000723 | from threepio import logger
from django.core.exceptions import ValidationError
from core.models import IdentityMembership, Identity
from core.models.quota import (
has_floating_ip_count_quota,
has_port_count_quota,
has_instance_count_quota,
has_cpu_quota,
has_mem_quota,
has_storage_quota,
... | 'snapshots': user_quota.snapshot_count,
}
username = identity.created_by.username
logger.info("Updating quota for %s to %s" % (username, volume_values))
driver = get_cached_driver(identity=identity)
username = driver._connection._get_username()
ad = get_account_driver(identity.provider)
ad... | ute_quota(user_quota, identity):
# Use THESE values...
compute_values = {
'cores': user_quota.cpu,
'ram': user_quota.memory * 1024, # NOTE: Value is stored in GB, Openstack (Liberty) expects MB
'floating_ips': user_quota.floating_ip_count,
'fixed_ips': user_quota.port_count,
... |
SamiHiltunen/invenio-accounts | invenio_accounts/forms.py | Python | gpl-2.0 | 2,117 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016 CERN.
| #
# Invenio is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published b | y the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio 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 L... |
ssorgatem/pulsar | galaxy/tools/deps/brew_exts.py | Python | apache-2.0 | 19,588 | 0.002297 | #!/usr/bin/env python
# % brew vinstall samtools 1.0
# % brew vinstall samtools 0.1.19
# % brew vinstall samtools 1.1
# % brew env samtools 1.1
# PATH=/home/john/.linuxbrew/Cellar/htslib/1.1/bin:/home/john/.linuxbrew/Cellar/samtools/1.1/bin:$PATH
# export PATH
# LD_LIBRARY_PATH=/home/john/.linuxbrew/Cellar/htslib/1.1/... | raise Exception(CANNOT_DETERMINE_TAP_ERROR_MESSAGE)
from_url_parts = from_url.split("/")
bl | ob_index = from_url_parts.index("blob") # comes right after username and repository
if blob_index < 2:
raise Exception(CANNOT_DETERMINE_TAP_ERROR_MESSAGE)
username = from_url_parts[blob_index - 2]
repository = from_url_parts[blob_index - 1]
else:
... |
phihag/adhocracy | src/adhocracy/migration/versions/008_add_tagging.py | Python | agpl-3.0 | 2,241 | 0.003124 | from datetime import datetime
from sqlalchemy import *
from migrate import *
import migrate.changeset
meta = MetaData()
user_table = Table('user', meta,
Column('id', Integer, primary_key=True),
Column('user_name', Unicode(255), nullable=False, unique=True, index=True),
Column('display_name', Unicode(255)... | te=datetime.utcnow),
Column('delete_time', DateTime, nullable=True),
Column('creator_id', Integer, ForeignKey('user.id'), nullable=False),
Column('instance_id', Intege | r, ForeignKey('instance.id'), nullable=False)
)
tag_table = Table('tag', meta,
Column('id', Integer, primary_key=True),
Column('create_time', DateTime, default=datetime.utcnow),
Column('name', Unicode(255), nullable=False)
)
tagging_table = Table('tagging', meta,
Column('id', Integer, primary_... |
geertj/draco2 | draco2/draco/robot.py | Python | mit | 2,805 | 0 | # vi: ts=8 sts=4 sw=4 et
#
# robot.py: web robot detection
#
# This file is part of Draco2. Draco2 is free software and is made available
# under the MIT license. Consult the file "LICENSE" that is distributed
# together with this file for the exact licensing terms.
#
# Draco2 is copyright (c) 1999-2007 by the Draco2 a... | _callback(self._change_callback)
def _change_callback(self, api):
"""Change manager | callback (when files in the ctx change)."""
self.m_robots = []
for fname in self.m_files:
self._parse_file(fname)
logger = logging.getLogger('draco2.draco.robot')
logger.debug('Reloaded robot signatures (change detected).')
def add_file(self, fname):
"""Load robo... |
pzread/judge | StdChal.py | Python | mit | 33,830 | 0.003547 | '''Standard challenge module.'''
import os
import shutil
import fcntl
from cffi import FFI
from tornado import gen, concurrent, process
from tornado.stack_context import StackContext
from tornado.ioloop import IOLoop
import PyExt
import Privilege
import Config
from Utils import FileUtils
STATUS_NONE = 0
STATUS_AC = ... |
dict: Challenge result.
'''
cache_hash = None
cache_gid = None
# Check if special judge needs to rebuild.
if self.judge_typ in ['ioredir']:
hashproc = process.Subprocess( \
['./Hash | Dir.py', self.res_path + '/check'], \
stdout=process.Subprocess.STREAM)
dirhash = yield hashproc.stdout.read_until(b'\n')
dirhash = int(dirhash.decode('utf-8').rstrip('\n'), 16)
ret = StdChal.build_cache_find(self.res_path)
if ret is not None and ret[0] =... |
kumy/pycaching | test/test_utfgrid.py | Python | lgpl-3.0 | 7,914 | 0.000379 | #!/usr/bin/env python3
import os
import json
import logging
import unittest
from pycaching import Geocaching
from pycaching.utfgrid import UTFGrid, GridCoordinateBlock
from pycaching.errors import Error
from test.test_geocaching import _username, _password
_this_folder = os.path.dirname(__file__)
sample_files = {i... | re to expected results"""
expected_caches = {}
with open(sample_files["sample_caches.csv"]) as f:
for row in f:
wp, lat, lon = row.split(',')
expected_caches[wp] = | (float(lat), float(lon))
with open(sample_files["sample_utfgrid.json"]) as f:
j = json.loads(f.read())
caches = self.grid._parse_utfgrid(j)
for c in caches:
with self.subTest("Cache " + wp):
self.assertIn(c.wp, expected_caches)
self.assertA... |
tensorflow/tensorflow | tensorflow/python/data/experimental/kernel_tests/counter_test.py | Python | apache-2.0 | 1,927 | 0.003114 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | ], dataset_ops.get_legacy_output_shapes(dataset).as_list())
self.assertEqual(dtypes.int64, dataset_ops.get_legacy_output_types(dataset))
get_next = self.getNext(dataset)
for expect | ed in expected_output:
self.assertEqual(expected, self.evaluate(get_next()))
if __name__ == "__main__":
test.main()
|
jbrendel/RESTx | src/python/restx/components/_ResourceCreateForm.py | Python | gpl-3.0 | 9,666 | 0.009518 | """
RESTx: Sane, simple and effective data publishing and integration.
Copyright (C) 2010 MuleSoft Inc. http://www.mulesoft.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version... | alues is None:
values = []
else:
values = [ values ]
param_fields_html | += \
"""<tr>
<td valign=top id="%s_name">%s<br><small>(%s%s)</small></td>
<td valign=top>%s</td>
</tr>""" % (pname, pname, pdef.desc, opt_str, pdef.html_type("params__"+pname, values))
if message:
msg = "<b><i><font color=red>%s</font></i></b><br><p>" % message
else:
msg... |
rs-dev/Test-Secretary | test_secretary/celery_setup.py | Python | isc | 446 | 0 | import os
from celery | import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_secretary.settings')
app = Celery('test_secretary')
# Using a string here means the worker will not have to
# pickle the object when using Windo | ws.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
|
efogliatto/multiphaseLB | src/tools/mesh/salomesh/io/write_boundaries.py | Python | gpl-3.0 | 649 | 0.040062 | import sys
import os
import salome
import numpy
from salome.geom import geomtools
def write_boundaries( geompy, bd ):
directory = "lattice"
if not os.path.exists(directory):
os.makedirs(directory)
file = open(directory + "/bound | ary", 'w')
# Number of points
file.write( str(len(bd.keys())) )
file.write( "\n" )
for key, value in bd.iteritems() :
file.write( "\n" )
file.write( key )
file.write( "\n" )
file.write( str(len(value)) )
file.write( "\n" )
| for id in value:
file.write("%d\n" % id)
file.close()
|
ercanezin/ce888labs | lab8/imdb.py | Python | gpl-3.0 | 2,192 | 0.011861 |
from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.preprocessing import sequence
from keras.models import Model
from keras.layers import Dense, Activation, Embedding, GlobalMaxPooling1D,Convolution1D, Input,LSTM,merge
from keras.datasets import imdb
max_fe... | SING
print('Loading data...')
(X_train, y_train), (X_test, y_test) = imdb.load_data(nb_words | =max_features)
print(len(X_train), 'train sequences')
print(len(X_test), 'test sequences')
print (X_train[0])
print('Pad sequences (samples x time)')
X_train = sequence.pad_sequences(X_train, maxlen=maxlen)
X_test = sequence.pad_sequences(X_test, maxlen=maxlen)
print('X_train shape:', X_train.shape)
print('X_test sha... |
crabmanX/m4baker | src/mainWindow.py | Python | gpl-2.0 | 21,163 | 0.007041 | # -*- coding: utf-8 -*-
#
# M4Baker
# Copyright (C) 2010 Kilian Lackhove
#
# 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 versio | n 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# ME | RCHANTABILITY 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
... |
Mathih13/IS-105_2016_Gruppe-5 | Uke-15-ICA-9/ICA-8-Python/Model/river.py | Python | mit | 16,055 | 0.015967 | # -*- coding: utf-8 -*-
# OBS! Dårlig kodingstil! For eksempel, kommentarer skal høre til funksjoner og være mellom '''disse'''
from sm import SM
import sys
class River(SM):
river_db = [] # En klønete måte å definere database på, bør være i egen klasse og kanskje ikke en liste?
# Blir kalt hve... | asen
def statusCheck(self):
| #All At Left
if 'man isat left' in self.river_db and 'boat isat left' in self.river_db and 'fox isat left' in self.river_db and 'chicken isat left' in self.river_db and 'grain isat left' in self.river_db:
print self.s1
return "s1"
#All at left, chicken in boa... |
uSpike/raspberry-api-server | raspberry_api/server/version.py | Python | mit | 531 | 0.00565 |
from flask_restplus import Res | ource, Namespace, reqparse, fields, marshal_with
from .gpio import GPIO
api = Namespace('version')
version_model = | api.model('version', {
'product': fields.String,
'rev': fields.String
})
version_list = api.model('version_list', {
'host': fields.Nested(version_model),
})
@api.route('/')
class Version(Resource):
@api.marshal_with(version_list)
def get(self):
return {
'host': {'product': 'ras... |
treyhunner/django-simple-history | simple_history/tests/tests/test_signals.py | Python | bsd-3-clause | 1,806 | 0 | from datetime import datetime
from django.test import TestCase
from simple_history.signals import (
post_create_historical_record,
pre_create_historical_record,
)
from ..models import Poll
today = datetime(2021, 1, 1, 10, 0)
cl | ass PrePostCr | eateHistoricalRecordSignalTest(TestCase):
def setUp(self):
self.signal_was_called = False
self.signal_instance = None
self.signal_history_instance = None
self.signal_sender = None
def test_pre_create_historical_record_signal(self):
def handler(sender, instance, **kwargs)... |
zackmdavis/swift | test/unit/account/test_server.py | Python | apache-2.0 | 94,681 | 0.000011 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# 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 agree... | icense 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 errno
import os
import mock
import unittest
from tempfile import mkdtemp
from shutil impo... | m swift import __version__ as swift_version
from swift.common.swob import Request
from swift.common import constraints
from swift.account.server import AccountController
from swift.common.utils import normalize_timestamp, replication, public
from swift.common.request_helpers import get_sys_meta_prefix
from test.unit im... |
deepmind/optax | setup.py | Python | apache-2.0 | 2,830 | 0.001413 | # Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. 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
#
# ... | :: 5 - Production/Stable',
'Environment :: Console',
'Intended Audience :: Science/Research',
'Intended Audience :: D | evelopers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Software Development ::... |
chelseawinfree/symantecssl | tests/unit/utils.py | Python | apache-2.0 | 623 | 0 | from __future__ import absolute_import, division, print_function
from lxml import etree
import os
def open_xml_file(filename, mode):
"""Opens an XML file for use.
:param filename: XML file to create fi | le from
:param mode: file mode for open
:return:
"""
base = os.path.dirname(__file__) + '/xml_test_files/'
return open(os.path.join(base, filename), mode)
def create_node_from_file(filename):
"""Creates an xml node from a given XML file.
:param filename: XML file to create node from
| :return: node
"""
node = etree.parse(open_xml_file(filename, 'r'))
return node
|
sburnett/seattle | repy/tests/ut_repytests_testinit.py | Python | mit | 67 | 0.059701 | #pragma out
#pragma repy
if callfunc=='initialize':
prin | t 'OK! | '
|
zwy1135/z_idea | graph.py | Python | mit | 4,756 | 0.034192 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 04 17:51:20 2014
@author: wy
"""
import numpy as np
def sigmoid(x):
x = np.sum(x)
return 1./(np.e**-x + 1)
class Graph(object):
def __init__(self,vs = [],es = []):
self.vs = set()
self.es = set()
for v in vs:
self.add_... | dom()<p:
#print '<'
removelist.append(e)
| for e in removelist:
self.remove_edge(e)
v1,v2 = np.random.choice(vs,2,replace = False)
self.add_edge(Edge(v1,v2))
def findPathLength(s,t):
fringe = [s]
length = 0
visited = set()
while(len(fringe)):
length ... |
DC23/cookiecutter-dcpypackage | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}.py | Python | mit | 662 | 0.006042 | # -*- coding: utf-8 -*-
# Ensure backwards compatibility with Python 2
from __future__ import (
absolute_import,
division,
print_function,
unicode_l | iterals)
from builtins import *
def {{cookiecutter.cli_entry_point_funct | ion_name }}():
""" Command-line entry point for {{ cookiecutter.repo_name }} """
print('{{ cookiecutter.repo_name }} placeholder CLI entry point')
def {{cookiecutter.gui_entry_point_function_name }}():
""" GUI entry point for {{ cookiecutter.repo_name }} """
print('{{ cookiecutter.repo_name }} placeho... |
depet/scikit-learn | examples/svm/plot_separating_hyperplane.py | Python | bsd-3-clause | 1,252 | 0.002396 | """
=========================================
SVM: Maximum margin separating hyperplane
=========================================
Plot the maximum margin separating hyperplane within a two-class
separable dataset using a Support Vector Machines classifier with
linear kernel.
"""
print(__doc__)
import numpy as np
impo... | 5)
yy = a * xx - (clf.intercept_[0]) / w[1]
# plot the parallels to the separating hyperplane that pass through the
# support vectors
b = clf.support_vectors | _[0]
yy_down = a * xx + (b[1] - a * b[0])
b = clf.support_vectors_[-1]
yy_up = a * xx + (b[1] - a * b[0])
# plot the line, the points, and the nearest vectors to the plane
pl.plot(xx, yy, 'k-')
pl.plot(xx, yy_down, 'k--')
pl.plot(xx, yy_up, 'k--')
pl.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1],
... |
hkrist/ratatoskr | ratatoskr/__init__.py | Python | mit | 843 | 0 | import utils
import operation_registry
import operatio | n_wrappers.base_wrappers as base_wrappers
import types
import exceptions
from protectron import protectron
@utils.doublewrap
def register_operation(func, operation_wrapper=base_wrappers.LocalOperation):
if isinstance(operation_wrapper, types.ClassType):
operation_wrapper_instance = operation_wrapper()
... | istry.OperationRegistry
operation_registry_cls.register_operation(operation_wrapper_instance)
@utils.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def dispatch_event(event):
return operation_registry.OperationRegistry.call(event)
|
armab/st2contrib | packs/rackspace/actions/create_dns_zone.py | Python | apache-2.0 | 452 | 0 | from lib.action import PyraxBaseAction
from lib.formatters import to_dns_zone_dict
__all__ = [
'CreateDNSZoneAction'
]
class CreateDNSZoneAction(PyraxBaseAction):
def run(self, name, email_address, ttl=None, comment=None):
cdns = self.pyrax.cloud_dns
zone = cdns. | create(name=name, emailAddres | s=email_address, ttl=ttl,
comment=comment)
result = to_dns_zone_dict(zone)
return result
|
python-daisychain/daisychain | test/test_executor.py | Python | mit | 9,094 | 0.004948 | import daisychain.steps.input
from daisychain.executor import Executor, Execution, ExecutorAborted, ConsoleInput, CheckStatusException
from . import test_step
from mock import patch
import py3compat
if py3compat.PY2:
input_function = 'daisychain.steps.input.input'
else:
import builtins
input_function = 'bu... | encies=[parent, successful_parent])
e.execution = Execution(executor=e)
e.execution.aborted = True
e.execute()
assert dep.status.pending
assert dep2 | .status.pending
assert successful_dep.status.pending
assert parent.status.pending
assert successful_parent.status.pending
def test_prompting_during_execution():
with patch(input_function) as mock_raw_input:
dep = test_step.MockStep(name='mock_step |
sanghviharshit/script.kodi.lifx.ambilight | resources/lib/lifxlan/products.py | Python | gpl-2.0 | 4,906 | 0.000815 | # coding=utf-8
product_map = {1: "Original 1000",
3: "Color 650",
10: "White 800 (Low Voltage)",
11: "White 800 (High Voltage)",
18: "White 900 BR30 (Low Voltage)",
20: "Color 1000 BR30",
22: "Color 1000",
27: "LIFX... | e,
"temperature": True,
"infrared": False,
"multizone": True},
32: {"color": True,
"temperature": True,
"infrared": False,
"multizone": True},
36: {"color": True,... | False,
"multizone": False},
37: {"color": True,
"temperature": True,
"infrared": False,
"multizone": False},
43: {"color": True,
"temperature": True,
"infrared":... |
osuripple/pep.py | events/setAwayMessageEvent.py | Python | agpl-3.0 | 743 | 0.020188 | from common.log import logUtils as log
from constants import clientPackets
from constants import serverPackets
def handle(userToken, packetData):
# get token data
username = userToken.username
# Read packet data
packetData = clientPackets.setAwayMessage(packetData)
# Set token away message
userToken.awayMessa... | ssage"]
# Send private message from fokabot
if packetData["awayMessage"] == "":
fokaMessage = "Your away message has been reset"
else:
fokaMessage = "Your away message is now: {}".f | ormat(packetData["awayMessage"])
userToken.enqueue(serverPackets.sendMessage("FokaBot", username, fokaMessage))
log.info("{} has changed their away message to: {}".format(username, packetData["awayMessage"]))
|
mikkokeskinen/tunnistamo | yletunnus/urls.py | Python | mit | 171 | 0 | fr | om allauth.socialaccount.providers.oauth2.urls import default_urlpatterns
from .provider import YleTunnusProvider
urlpatterns = default_urlpatterns(YleTun | nusProvider)
|
vinutah/apps | tools/vulfi/master/scripts/driver.py | Python | gpl-3.0 | 20,628 | 0.046878 | import os,sys,math,pdb,filecmp,logging,argparse,subprocess
from argparse import RawTextHelpFormatter
import time
import numpy as np
import imp
retry_count=3
# Check if OpenCV library is available
# Abort further execution if image handling is required
cv2_flag = True
try:
imp.find_module("cv2")
except:
print "WARN... | axfile1:
maxfile1=max(img1[i][j])
mse = np.sum((img1.astype("float") - img2.astype("float")) ** 2)
mse = mse / float(img1.size)
print "Image resolution: " + str(x)+"x"+str(y)
print "MSE: "+str(mse)
print "MAX_I: "+str(maxfile1)
if mse > 0:
maxsqr = maxfile1**2
ratio = maxsqr / mse
if ratio > 0.0:
... | int "Info: psnr is above threshold!"
return [True,psnr]
else:
print "Info: psnr is below threshold!"
return [False,psnr]
else:
print "Warning: ratio of maxi and mse should always be gt 0"
return [True,-1.0]
print "Info: The two images are identical!"
return [True,0.0]
def printg(txt):
lin... |
acsone/website | website_sale_collapse_categories/__init__.py | Python | agpl-3.0 | 289 | 0 | # -*- encoding: utf-8 -*-
############################################## | ################################
# For copyright and license notices, see __ope | nerp__.py file in root directory
##############################################################################
from . import controllers
|
seleznev/firefox-complete-theme-build-system | tests/test_addonconf.py | Python | mpl-2.0 | 1,050 | 0.006667 | import sys
import unittest
sys.path.insert(0, "../src/build")
import addonconf
class AddonConfModuleTestCase(unittest.TestCase):
def test_load(self):
# act
config = addonconf.load("configs/config.json")
# assert
self.assertEqual(config, None, "Wrong return value for not exists con... | :
# act
config = addonconf.load("configs/config.json.1")
# assert
self.assertEqual(config, None, "Wrong return value for unvalide config")
def test_load3(self):
# arrange
correct_config = {'version': '0.1', 'xpi': {'theme': 'firefox-theme-test.xpi', 'package': 'fire... | est.xpi'}, 'max-version': '31.0a1', 'directory-structure': {'shared-dir': 'chrome'}, 'min-version': '29.0'}
# act
config = addonconf.load("configs/config.json.2")
# assert
self.assertEqual(config, correct_config, "Uncorrect load config")
if __name__ == '__main__':
unittest.main()
... |
jeremiak/regulations-site | regulations/tests/node_types_tests.py | Python | cc0-1.0 | 3,720 | 0.000269 | #vim: set encoding=utf-8
from unittest import TestCase
from regulations.generator.node_types import *
class NodeTypesTest(TestCase):
def test_change_appendix(self):
node_parts_before = ['243', 'A', '30(a)']
node_parts_after = to_markup_id(node_parts_before)
node_string = "-".join(node_par... | abel(self):
self.assertEqual(REGTEXT, type_from_label(['250', '5', 'A']))
self.assertEqual(APPENDIX, type_from_label(['250', 'A2']))
self.assertEqual(APPENDIX, type_from_label(['250', 'A']))
self.assertEqual(APPENDIX, type_from_label(['250', 'A', '3(b)']))
self.assertEqual(REGTEX... | , '5', 'a', 'i', 'C']))
self.assertEqual(EMPTYPART, type_from_label(['250', 'Subpart']))
self.assertEqual(SUBPART, type_from_label(['250', 'Subpart', 'C']))
self.assertEqual(INTERP, type_from_label(['250', 'Interp']))
self.assertEqual(INTERP, type_from_label(['250', 'A', 'Interp']))
... |
intel-analytics/BigDL | python/nano/src/bigdl/nano/quantization/neural_compressor/quantization.py | Python | apache-2.0 | 7,996 | 0.003252 | #
# Copyright 2016 The BigDL Authors.
#
# 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 ... | el.framework:
from torch.utils.data.dataloader import default_collate
if calib_dataloader:
calib_data | loader.collate_fn = default_collate
if val_dataloader:
val_dataloader.collate_fn = default_collate
if quantized:
return quantized
else:
raise RuntimeError("Found no quantized model satisfying accuracy criterion.")
def check(self, calib_dataloader... |
rfmcpherson/killerbee | killerbee/GoodFETatmel128.py | Python | bsd-3-clause | 9,329 | 0.016615 | # GoodFETclient to interface zigduino/atmel128 radio
# forked by bx from code by neighbor Travis Goodspeed
from GoodFETAVR import GoodFETAVR
import sys, binascii, os, array, time, glob, struct
fmt = ("B", "<H", None, "<L")
class GoodFETatmel128rfa1(GoodFETAVR):
ATMELRADIOAPP = 0x53
autocrc = 0
verbose = F... | #Do nothing, just wait so there's no timeout.
print "# NOP.";
return ""
else:
self.data=self.serialport.read(self.count);
return self.data;
def RF_setchannel(self, chan):
if (chan < 11) or (chan > 26):
| print "Channel out of range"
else:
self.poke(0x8, chan)
def peek(self,reg,bytes=1):
"""Read a Register. """
#Automatically calibrate the len.
if bytes != 1:
print "Warning, currently cannot poke more than 1 byte"
bytes = 1
data ... |
andpp/cherrymusic | backport/collections/_backported.py | Python | gpl-3.0 | 4,139 | 0.000483 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009 Raymond Hettinger
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the r... | serDict import DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clea | r()
self.update(*args, **kwds)
def clear(self):
self.__end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.__map = {} # key --> [key, prev, next]
dict.clear(self)
def __setitem__(self, key, value):
if key no... |
quanvm009/codev7 | openerp/tools/translate.py | Python | agpl-3.0 | 45,384 | 0.003944 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | pool = getattr(s, 'pool', None)
(cr, dummy) = self._get_cr(frame, allow_create=False)
uid = self._get_uid(frame)
if pool and cr an | d uid:
lang = pool.get('res.users').context_get(cr, uid)['lang']
return lang
def __call__(self, source):
res = source
cr = None
is_new_cr = False
try:
frame = inspect.currentframe()
if frame is None:
return source
... |
vileopratama/vitech | src/openerp/service/wsgi_server.py | Python | mit | 8,202 | 0.003292 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
"""
WSGI stack, common code.
"""
import httplib
import urllib
import xmlrpclib
import StringIO
import errno
import logging
import platform
import socket
import sys
import threading
import traceback
import werkzeug.s... | mlrpclib.loads(data)
retur | n xmlrpc_return(start_response, service, method, params, string_faultcode)
def application_unproxied(environ, start_response):
""" WSGI entry point."""
# cleanup db/uid trackers - they're set at HTTP dispatch in
# web.session.OpenERPSession.send() and at RPC dispatch in
# openerp.service.web_services.o... |
nemonik/Intellect | intellect/grammar/PolicyParser.py | Python | bsd-3-clause | 180,891 | 0.013804 | # $ANTLR 3.1.3 Mar 17, 2009 19:23:44 /Users/walsh/Development/workspace/Intellect/intellect/grammar/Policy.g 2013-03-25 15:29:47
import sys
from antlr3 import *
from antlr3.compat import set, frozenset
from intellect.Node import *
# for convenience in actions
HIDDEN = BaseRecognizer.HIDDEN
# token types
... | lf, 61,
eot = self.DFA61_eot,
eof = self.DFA61_eof,
min = self.DFA61_min,
max = s | elf.DFA61_max,
accept = self.DFA61_accept,
special = self.DFA61_special,
transition = self.DFA61_transition
)
# $ANTLR start "file"
# /Users/walsh/Development/workspace/Intellect/intellect/grammar/Policy.g:61:1: file returns [o... |
feredean/cs313 | notes/test_recursivity-nope.py | Python | mit | 976 | 0.052254 |
def find_words(letters):
""" find_words from scrabble transformation to
recursive """
results = set()
for a in letters:
if a in WORDS: results.add(a)
if a not in PREFIXES: continue
for b in removed(letters, a):
w = a + b
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for c in remov... | ):
w = a + b + c
if w i | n WORDS: results.add(w)
if w not in PREFIXES: continue
for d in removed(letters, w)
w = a + b + c + d
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for e in removed(letters, w)
w = a + b + c + d + e
if w in WORDS: results.add(w)
if w not in PREFIXES: continue... |
ytyng/django-elasticindex | elasticindex/managers.py | Python | bsd-3-clause | 9,274 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import copy
import logging
import time
from collections import OrderedDict
from contextlib import contextmanager
import six
from django.u | tils.functional import cached_property
from .client import get_es_client
logger = logging.getLogger('elasticindex')
class ElasticQuerySet(object):
def __init__(self, model_cls, body=None, **kwargs):
self.model_cls = model_cls
self.body = body or {"query": { | "match_all": {}}}
self.kwargs = kwargs or {}
self.latest_total_count = None
self.latest_raw_result = None
self.query_finished = False
def __len__(self):
return len(self.result_list)
def __iter__(self):
return iter(self.result_list)
def __bool__(self):
... |
hagabbar/pycbc_copy | pycbc/waveform/pycbc_phenomC_tmplt.py | Python | gpl-3.0 | 14,998 | 0.008668 | # Copyright (C) 2012 Prayush Kumar
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distribut... | a5 * v5 +
(xdota6 + xdota6log * log(v2)) * v6 + xdota7 * v7;
xdo | t *= (xdotaN * v5 * v5);
double omgdot = 0.0, ampfac = 0.0;
double ampSPA = 0.0, ampSPAre = 0.0, ampSPAim = 0.0;
/* If xdot becomes negative, take ampSPA = 0.0 */
/* This is valid because it becomes negative much after ISCO */
if( xdot > 0.0 )
{
omgdot = 1.5 * v * xdot;
ampfac ... |
david-caro/jenkins-job-builder | jenkins_jobs/modules/triggers.py | Python | apache-2.0 | 68,792 | 0 | # Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# 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... |
for project in data['projects']:
convert_dict(project, [
'projectCompareType',
'projectPattern',
'branchCompareType',
'branchPattern',
])
old_format_events = OrderedDict(
| (key, should_register) for key, should_register in six.iteritems(data)
if key.startswith('trigger-on-'))
trigger_on = data.setdefault('trigger-on', [])
if old_format_events:
logger.warn("The events: %s; which you used is/are deprecated. "
"Please use 'trigger-on' instead."... |
tectronics/admiral-jiscmrd | test/FileShare/tests/TestConfig.py | Python | mit | 984 | 0.022358 | # $Id: $
#
# Test configuration parameters
#
class TestConfig:
#hostname = "zoo-admiral-behav.zoo.ox.ac.uk"
#hostname = "zoo-admiral-silk.zoo.ox.ac.uk"
#hostname = "zoo-admiral-devel.zoo.ox.ac.uk"
hostname = "zoo-admiral-ibrg.zoo.ox.ac.uk"
#hostname = "z... | l"
webdavmountpoint = "mountadmiralwebdav"
webdavbaseurl = "http://"+hostname+"/data/"
readmefile = "ADMIRAL.README"
readmetext = "This directory is the root of the ADMIRAL shared file system.\n"
userAname = "TestUser1"
userApass = "user1"
userBname = "Tes... | s = "userd"
userRGleadername = "TestLeader"
userRGleaderpass = "leader"
collabname = "TestCollab"
collabpass = "collab"
# End.
|
Flavoured/CodinGamePuzzles | Easy/TheDescent/TheDescent.py | Python | unlicense | 455 | 0.002198 | import sys
import math
while True:
tallest_inde | x = -1
tallest_height = -1
for i in range(8):
mountain_h = int(input()) # represents the height of one mountain.
if(tallest_height != -1):
if(mountain_h > tallest_height):
tallest | _index = i
tallest_height = mountain_h
else:
tallest_index = i
tallest_height = mountain_h
print(tallest_index)
|
autotest/virt-test | virttest/libvirt_xml/vm_xml.py | Python | gpl-2.0 | 84,182 | 0.000154 | """
Module simplifying manipulation of XML described at
http://libvirt.org/formatdomain.html
"""
import logging
from autotest.client.shared import error
from virttest import xml_utils
from virttest.libvirt_xml import base, accessors, xcepts
from virttest.libvirt_xml.devices import librarian
class VMXMLDevices(list):... | ="vm_name",
libvirtxml=self,
forbidden=None,
parent_xpath='/',
tag_name='name')
accessors.XMLElementText(property_name="uuid",
libvirtxml=self,
| forbidden=None,
parent_xpath='/',
tag_name='uuid')
accessors.XMLElementInt(property_name="iothreads",
libvirtxml=self,
forbidden=None,
... |
xavi783/u-tad | Modulo4/ejercicio3/reducer.py | Python | gpl-3.0 | 915 | 0.020765 | #! /usr/bin/python
import sys
sys.path.append('../')
from toolbox.hreaders import token_readers as reader
from toolbox.hreducers import list_reducer as reducer
SOLO_FACTURA = False
def reduction(x, | y):
v1 = x.split(',')
v2 = y.split(',')
r = x if int(v1[1])>=int(v2[1]) else y
return r
_reader = reader.Token_reader("\t",1)
_reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element
if SOLO_FACTURA:
for line in sys.stdin:
key, value = _reader.read_all(line... | [1])
else:
for line in sys.stdin:
key, value = _reader.read_all(line)
K,V = _reducer.reduce(key,value)
if K:
print '{}\t{}'.format(K,V)
print '{}\t{}'.format(key,V) |
JelteF/Flask-Migrate | tests/app.py | Python | mit | 518 | 0.001931 | #!/bin/env python
from flask import Flask
fr | om flask_sqlalchemy import SQLAlchemy
from fla | sk_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
class User(db.Model):
id = db.Column(db.In... |
OneTraTown/douban_group | doubangroup/spiders/rotate_useragent.py | Python | gpl-3.0 | 2,788 | 0.001435 | from scrapy.utils.log import configure_logging
import random
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
class RotateUserAgentMiddleware(UserAgentMiddleware):
def __init__(self,user_agent=''):
self.user_agent = user_agent
def process_request(self, request, spider):
... | 6.3 "
"(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "
"(KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "
"(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
... | "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 "
"(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 "
"(KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
"Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 "
"(KHTML, li... |
AdamantLife/alcustoms | alcustoms/sql/tests/sqltest__depricated__.py | Python | gpl-3.0 | 8,816 | 0.010776 |
#########################################################################
""" SQL TOOLS """
#########################################################################
"""
SQL Tools
Tools provided for parsing sql statements using regex. For each function, a precom... | ## Capture All Data (Handling it separately)
(?:,|$) ## Declaration ends with comma or end-of-string
)
"""
ColumnDefinition = re.compile(ColumnDefinition_regex, re.VERBOSE | re.IGNORECASE)
TableDefinition_regex = f"""
(?P<multiline_comment>/\*\s*(?P<mc | _text>[\s\S]*?)\s*\*/) ## /* Multiline Comment */
| (?P<comment>--(?P<commenttext>.*)) ## -- Regular Comment
| (?P<table_constraint> ## Table Constraints
(?P<tablecon_type> ## Viable Table Constraints
PRIMARY\ KEY
| UNIQUE
... |
dlebauer/plantcv | lib/plantcv/logical_xor.py | Python | gpl-2.0 | 460 | 0.023913 | ### Join images (XOR)
import cv2
from . import print_image
def logical_xor(img1, img2, device, debug=False):
# Join two images using the bitwise XOR operator
# img1, img2 = ima | ge objects, grayscale
# device = device number. Used to count steps in the pipeline
# debug = True/False. If True, print image
device += 1
merged = cv2.bitwise_xor(img1, img2)
if debug:
print_image(merged, (str(de | vice) + '_xor_joined.png'))
return device, merged |
ctrlaltdel/neutrinator | vendor/urllib3/util/ssl_.py | Python | gpl-3.0 | 13,786 | 0.000435 | from __future__ import absolute_import
import errno
import warnings
import hmac
import re
from binascii import hexlify, unhexlify
from hashlib import md5, sha1, sha256
from ..exceptions import SSLError, InsecurePlatformWarning, SNIMissingWarning
from ..packages import six
from ..packages.rfc3986 import abnf_regexp
... | ead of `CERT_REQUIRED`.
If it's neither `None` nor a string we assume it is already the numeric
constant which can directly be passed to wrap_s | ocket.
"""
if candidate is None:
return CERT_REQUIRED
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'CERT_' + candidate)
return res
return candidate
def resolve_ssl_version(candidate):
"""
lik... |
mercadopago/px-android | scripts/rename_resources.py | Python | mit | 559 | 0.039356 | import os
import sys
import fnmatch
directory | = os.path.dirname(os.path.r | ealpath(sys.argv[0])) #get the directory of your script
for subdir, dirs, files in os.walk(directory):
print(files)
for filename in files:
if fnmatch.fnmatch(filename,'mpsdk_*') > 0:
subdirectoryPath = os.path.relpath(subdir, directory) #get the path to your subdirectory
filePath = os.path.join(subdirectoryPa... |
sssllliang/edx-analytics-pipeline | edx/analytics/tasks/tests/acceptance/test_user_activity.py | Python | agpl-3.0 | 5,050 | 0.00297 | """Ensure we can compute activity for a set of events"""
import datetime
from edx.analytics.tasks.tests.acceptance import AcceptanceTestCase
class UserActivityAcceptanceTest(AcceptanceTestCase):
"""Ensure we can compute activity for a set of events"""
INPUT_FILE = 'user_activity_tracking.log'
END_DATE ... | LAYED_VIDEO', 3),
(self.COURSE_ID, datetime.date(2014, 6, 12), 'ACTIVE', 1),
(self.COURSE_ID, datetime.date(2014, 6, 12), 'PLAYED_VIDEO', 1),
(self.COURSE_ID, datetime.date(2014, 6, 19), 'ACTIVE', 4),
(self.COURSE_ID, datetime.date(2014, 6, 19), 'ATTEMPTED_PROBLEM', 2),
... | 6, 19), 'PLAYED_VIDEO', 3),
])
self.task.launch([
'CourseActivityMonthlyTask',
'--source', self.test_src,
'--end-date', self.END_DATE.isoformat(),
'--months', str(2),
'--credentials', self.export_db.credentials_file_url,
'--n-reduc... |
howthebodyworks/pelican-plugins | liquid_tags/notebook.py | Python | agpl-3.0 | 10,596 | 0.002926 | """
Notebook Tag
------------
This is a liquid-style tag to include a static html rendering of an IPython
notebook in a blog post.
Syntax
------
{% notebook filename.ipynb [ cells[start:end] language[language] ]%}
The file should be specified relative to the ``notebooks`` subdirectory of the
content directory. Optio... | t open
from .mdx_liquid_tags import LiquidTags
import | IPython
IPYTHON_VERSION = IPython.version_info[0]
try:
import nbformat
except:
pass
if not IPYTHON_VERSION >= 1:
raise ValueError("IPython version 1.0+ required for notebook tag")
if IPYTHON_VERSION > 1:
warnings.warn("Pelican plugin is not designed to work with IPython "
"versions... |
edisonlz/fruit | web_project/base/site-packages/django/http/cookie.py | Python | apache-2.0 | 3,531 | 0.001982 | from __future__ import absolute_import, unicode_literals
from django.utils.encoding import force_str
from django.utils import six
from django.utils.six.moves import http_cookies
# Some versions of Python 2.7 and later won't need this encoding bug fix:
_cookie_encodes_correctly = http_cookies.SimpleCookie().value_enc... | dict.__setitem__(self, key, http_cookies.Morsel())
def parse_cookie(cookie):
if cookie == '':
return {}
if not isinstance(cookie, http_cookies.B | aseCookie):
try:
c = SimpleCookie()
c.load(cookie)
except http_cookies.CookieError:
# Invalid cookie
return {}
else:
c = cookie
cookiedict = {}
for key in c.keys():
cookiedict[key] = c.get(key).value
return cookiedict
|
sasongko26/sideka-desktop | login_indikator_kemiskinan.py | Python | gpl-2.0 | 2,727 | 0.013935 | import wx
import input_indikator_kemiskinan
import peringatan
import frm_sideka_menu
def create(parent):
return Dialog1(parent)
[wxID_DIALOG1, wxID_DIALOG1BUTTON1, wxID_DIALOG1BUTTON2,
wxID_DIALOG1STATICLINE1, wxID_DIALOG1STATICTEXT1, wxID_DIALOG1STATICTEXT2,
wxID_DIALOG1TEXTCTRL1,
] = [wx.NewId() for _init... | 25),
style=wx.TE_PASSWORD, value='')
self.staticText2 = wx.StaticText(id=wxID_DIALOG1STATICTEXT2,
label=u'MASUKAN PASSWORD DAHULU', name='staticText2', parent=self,
pos=wx.Point(104, 16), size=wx.Size(203, 17), style=0)
self.button1 = wx.But | ton(id=wxID_DIALOG1BUTTON1, label=u'Lanjutkan',
name='button1', parent=self, pos=wx.Point(208, 96),
size=wx.Size(184, 30), style=0)
self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
id=wxID_DIALOG1BUTTON1)
self.button2 = wx.Button(id=wxID_DIALOG1BUTTON2,
... |
Thierry46/CalcAl | gui/PatientFrame.py | Python | gpl-3.0 | 15,036 | 0.004123 | # -*- coding: utf-8 -*-
"""
************************************************************************************
Class : PatientFrame
Author : Thierry Maillard (TMD)
Date : 26/11/2016 - 1/12/2016
Role : Define Patient frame content.
Licence : GPLv3
Copyright (c) 2016 - Thierry Maillard
This file is part of CalcAl... | sticky=tkinter.E)
self.currentYear = datetime.datetime.now().year
self.oldestPatient = int(self.configApp.get('Patient', 'oldestPatient'))
self.birthYearCombobox = Combobox(patientDefinitionFrame, exportselection=0,
state="readonly",
... | estPatient)),
values=list(range(self.currentYear-self.oldestPatient,
self.currentYear+1)))
self.birthYearCombobox.bind('<<ComboboxSelected>>', self.modifyPatient)
self.birthYearCombobox.grid(row=1, colu... |
schlueter/ansible-lint | lib/ansiblelint/__init__.py | Python | mit | 6,392 | 0.000626 | # Copyright (c) 2013-2014 Will Thames <will@thames.id.au>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify... | NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOF... | intRule(object):
def __repr__(self):
return self.id + ": " + self.shortdesc
def verbose(self):
return self.id + ": " + self.shortdesc + "\n " + self.description
def match(self, file="", line=""):
return []
def matchlines(self, file, text):
matches = []
# arra... |
JioCloud/python-openstackclient | openstackclient/volume/client.py | Python | apache-2.0 | 2,241 | 0 | # Copyright 2012-2013 OpenStack, 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 ... | lume-api-version',
metavar='<volume-api-version>',
default=utils.env(
'OS_VOLUME_API_VERSION',
default=DEFAULT_VOLUME_API_VERSION),
help='Volume API version, default=' +
DEFAULT_VOLUME_API | _VERSION +
' (Env: OS_VOLUME_API_VERSION)')
return parser
|
luma/filterchain | tools/cpplint.py | Python | mit | 234,744 | 0.008703 | #!/usr/bin/python
#
# Copyright (c) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of ... | sity levels.
filter=-x,+y,...
Specify a comma-separated list of category-filters to apply: only
error messages whose category names pass the filters will be printed.
(Category names are printed with the message and look like
"[whitespace/indent]".) Filters are evaluated left to right.
... | at start with FOO".
Examples: --filter=-whitespace,+whitespace/braces
--filter=whitespace,runtime/printf,+runtime/printf_format
--filter=-,+build/include_what_you_use
To see a list of all the categories used in cpplint, pass no arg:
--filter=
counting=total|to... |
DeadSix27/python_cross_compile_script | tools/split.py | Python | mpl-2.0 | 1,806 | 0.048173 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os,re,sys,pprint,shutil
from pathlib import Path
PACKAGES_DIR = "../packages"
def errorExit(msg):
print(msg)
sys.exit(1)
def isPathDisabled(path):
for part in path.parts:
if part.lower().startswith("_disabled"):
return True
return False
depsFolder = P... | ot exist")
if not os.path.isfile(merged_prods):
errorExit("Merged products file does not exist")
if not os.path.isdir(depsFolder):
os.makedirs(depsFolder)
else:
print("Clearing old split folder:" + str(depsFolder))
shutil.rmtree(depsFolder)
os.makedirs(depsFolder)
if not os.path.isdir(prodFolder):
os.makedirs... | " : depsFolder, "merged_prods.py" : prodFolder, }
for mergefile_name in things:
mergedFile = None
enableWrite = False
curFile = None
print("Splitting " +mergefile_name+ " into seperate files in " + str(things[mergefile_name]))
with open(mergefile_name, "r", encoding="utf-8") as f:
mergedFile = f.read().spl... |
pombredanne/invenio | modules/bibformat/lib/elements/bfe_comments.py | Python | gpl-2.0 | 2,111 | 0.008527 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either ve... | ln=bfo.lang,
nb_comments=nb_comments,
nb_reviews=nb_reviews,
| voted=-1,
reported=-1,
user_info=bfo.user_info)
return comments + reviews
def escape_values(bfo):
"""
Called by BibFormat in order to check if ... |
clovertrail/cloudinit-bis | tests/unittests/test_datasource/test_digitalocean.py | Python | gpl-3.0 | 11,493 | 0 | #
# Copyright (C) 2014 Neal Shrader
#
# Author: Neal Shrader <neal@digitalocean.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distribute... | ": "private"
}
],
"public": [
{
"ipv4": {
"ip_address": "192.0.0.20",
"netmask": "255.255.255.0",
"gateway": "104.236.0.1"
},
" | ipv6": {
"ip_address": "2604:A880:0800:0000:1000:0000:0000:0000",
"cidr": 64,
"gateway": "2604:A880:0800:0000:0000:0000:0000:0001"
},
"anchor_ipv4": {
"ip_address": "10.0.0.5",
"netmask": "255.255.0.0",
"gateway": "10.0.0.1"
},
... |
iulian787/spack | var/spack/repos/builtin/packages/py-easybuild-framework/package.py | Python | lgpl-2.1 | 1,174 | 0.003407 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyEasybuildFramework(PythonPackage):
"""The core of EasyBuild, a software build and instal... | 'python@2.6:2.8,3.5:', when='@4:', type=('build', 'run'))
depends_on('py-setuptools', when='@:3', type=('build' | , 'run'))
depends_on('py-vsc-base@2.5.4:', when='@2.9:3', type='run')
# Only required for tests (python -O -m test.framework.suite)
depends_on('py-vsc-install', when='@:3', type='test')
|
rprichard/rust | src/etc/htmldocck.py | Python | apache-2.0 | 14,476 | 0.002141 | # Copyright 2015 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://... | attr is `impl`.
- `//h1[@class="fqn"]/span[1]/a[last()]/@class` matches a value of
`class` attribu | te in the last `a` element (can be followed by more
elements that are not `a`) inside the first `span` in the `h1` with
a class of `fqn`. Note that there cannot be no additional elements
between them due to the use of `/` instead of `//`.
Do not try to use non-absolute paths, it won't work due to the fla... |
SRabbelier/Melange | tests/new_views/test_document.py | Python | apache-2.0 | 2,777 | 0.001801 | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# 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 applic... | c.providers.string imp | ort DocumentKeyNameProvider
class EditProgramTest(DjangoTestCase):
"""Tests program edit page.
"""
def setUp(self):
self.init()
properties = {
'prefix': 'site',
'scope': self.site,
'read_access': 'public',
'key_name': DocumentKeyNameProvider(),
}
self.document =... |
kljensen/viff | viff/test/__init__.py | Python | gpl-3.0 | 764 | 0 | # Copyright 2007, 2008, 2009 VIFF Development Team.
#
# This file is part of VIFF, the Virtual Ideal Functionality Framework.
#
# VIFF is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser Gene | ral Public License (LGPL) as
# published by the Free Software Foundation, either version 3 o | f the
# License, or (at your option) any later version.
#
# VIFF 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 Lesser General
# Public License for more details.
#
# You should have re... |
anupamaloke/Dell-EMC-Ansible-Modules-for-iDRAC | library/dellemc_idrac_export_tsr.py | Python | gpl-3.0 | 5,134 | 0.001364 | #! /usr/bin/python
# _*_ coding: utf-8 _*_
#
# Dell EMC OpenManage Ansible Modules
#
# Copyright © 2017 Dell Inc. or its subsidiaries. All rights reserved.
# Dell, EMC, and other trademarks are trademarks of Dell Inc. or its
# subsidiaries. Other trademarks may be trademarks of their respective owners.
#
# This progra... | g_mgr.export_tsr(tsr_file_name)
if "Status" in msg['msg | '] and msg['msg']['Status'] != "Success":
msg['failed'] = True
except Exception as e:
err = True
msg['msg'] = "Error: %s" % str(e)
msg['failed'] = True
return msg, err
# Main
def main():
module = AnsibleModule(
argument_spec=dict(
# iDRAC Handle
... |
bigfatpanda-training/pandas-practical-python-primer | training/level-2-command-line-interfaces/bfp-reference/exercise_07/file_ops.py | Python | artistic-2.0 | 593 | 0.001686 | """
This modules provides various functions for operating on files.
Functions:
copy_files: Copy file(s) to a specified location.
"""
import subproce | ss
def copy_files(files: list, destination: str):
"""
Copy files to a given destination.
Args:
files: A list of files to copy.
destination: A str specifying the destination for copied
files.
"""
for file in files:
operation_result = subprocess.check_output(
... | ult) |
SteveViss/readthedocs.org | readthedocs/rtd_tests/tests/test_version_windows.py | Python | mit | 3,398 | 0.000589 | import unittest
from readthedocs.projects.version_handling import version_windows
class TestVersionWindows(unittest.TestCase):
def setUp(self):
self.versions = [
'0.1.0',
'0.2.0',
'0.2.1',
'0.3.0',
'0.3.1',
'1.1.0',
'1.2.... | ns = version_windows(self.versions,
major=1, minor=2, point=3)
self.assertEqual(final_versions, ['2.2.0', | '2.3.1', '2.3.2', '2.3.3'])
final_versions = version_windows(['2.3.2', '2.2.0', '2.3.0', '2.3.3', '2.3.1'],
major=1, minor=2, point=3)
self.assertEqual(final_versions, ['2.2.0', '2.3.1', '2.3.2', '2.3.3'])
if __name__ == '__main__':
unittest.main()
|
ithinksw/philo | philo/models/fields/__init__.py | Python | isc | 4,971 | 0.033394 | from django import forms
from django.core.exceptions import ValidationError
from django.core.validators import validate_slug
from django.db import models
from django.utils import simplejson as json
from django.utils.text import capfirst
from django.utils.translatio | n import ugettext_lazy as _
from philo.forms.fields import JSONFormField
from phi | lo.utils.registry import RegistryIterator
from philo.validators import TemplateValidator, json_validator
#from philo.models.fields.entities import *
class TemplateField(models.TextField):
"""A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be pa... |
leighpauls/k2cro4 | tools/telemetry/telemetry/platform.py | Python | bsd-3-clause | 672 | 0.010417 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class Platform(object):
"""The platform that the target browser | is running on.
Provides a limited interface to obtain stats from the platform itself, where
possible.
"""
def GetSurfaceCollector(self, trace_tag):
"""Platforms may be able to collect GL surface stats."""
class StubSurfaceCollector(object):
def __init__(self, trace_tag):
pass
def _... | llector(trace_tag)
|
gabriel-detassigny/kodi-synology-download | resources/lib/kodiutils.py | Python | mit | 1,657 | 0.000604 | # -*- coding: utf-8 -*-
import xbmc
import xbmcaddon
import re
import sys
import logging
if sys.version_info >= (2, 7):
import json as json
else:
import simplejson as json
# read settings
ADDON = xbmcaddon.Addon()
logger = logging.getLogger(__name__)
def notification(header, message, ti... | message, icon, time, sound)
def show_settings():
ADDON.openSettings()
def get_setting(setting):
return ADDON.getSetting(setting).strip().decode('utf-8')
def set_setting(setting, value):
ADDON.setSetting(setting, str(value))
def get_setting_as_bool(setting):
return get_setting(se... | tting(setting))
except ValueError:
return 0
def get_setting_as_int(setting):
try:
return int(get_setting_as_float(setting))
except ValueError:
return 0
def get_string(string_id):
return ADDON.getLocalizedString(string_id).encode('utf-8', 'ignore')
def kodi_j... |
OCA/account-invoicing | account_invoice_pricelist/models/account_move.py | Python | agpl-3.0 | 9,635 | 0.000623 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class AccountMove(models.Model):
_inherit = "account.move"
pricelist_id = fields.Many2one(
comodel_name="product.pricelist",
string="Pricelist",
... | ist_id
):
f | ield_name = "price"
product = product.with_context(
pricelist=pricelist_item.base_pricelist_id.id
)
product_currency = pricelist_item.base_pricelist_id.currency_id
currency_id = pricelist_item.pricelist_id.currency_id
if not curren... |
daniel-j/lutris | lutris/installer/__init__.py | Python | gpl-3.0 | 42 | 0 | """Install scri | pt interpreter package.""" | |
eri-trabiccolo/exaile | xlgui/panel/radio.py | Python | gpl-2.0 | 20,745 | 0.00294 | # Copyright (C) 2008-2010 Adam Olsen
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that... | General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
# The developers of the Exaile media player hereby grant permission
# for non-GPL compatible GStreamer and Exaile plugins to be used and
# distribut... | Exaile. This permission is
# above and beyond the permissions granted by the GPL license by which
# Exaile is covered. If you modify this code, you may extend this
# exception to your version of the code, but you are not obligated to
# do so. If you do not wish to do so, delete this exception statement
# from your ver... |
noisy/steemprojects.com | profiles/urls.py | Python | mit | 1,096 | 0.009124 | from django.conf.urls import url
from profiles import views
urlpatterns = [
url(
regex=r"^edit/$",
view=v | iews.ProfileEditUpdateView.as_view() | ,
name="profile_edit"
),
url(
regex="^confirm_role/(?P<membership_id>[-\w]+)/(?P<action>verify|deny)/$",
view=views.profile_confirm_role,
name="profile_confirm_role",
),
url(
regex="^deny_account/(?P<type_name>[\w]+)/(?P<account_name>[-\.\w]+)/$",
view=vie... |
danielSbastos/gistified | migrations/versions/ace8d095a26b_.py | Python | mit | 769 | 0.006502 | """empty message
Revision ID: ace8d095a26b
Revises:
Create Date: 2017-10-01 20:39:54.984192
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ace8d095a26b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | 'id')
)
# | ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('gist')
# ### end Alembic commands ###
|
github/codeql | python/ql/test/query-tests/Security/CWE-326-WeakCryptoKey/weak_crypto.py | Python | mit | 2,155 | 0.003248 | from cryptography.hazmat import backends
from cryptography.hazmat.primitives.asymmetric import ec, dsa, rsa
# Crypto and Cryptodome have same API
if random():
from Crypto.PublicKey import DSA
from Crypto.PublicKey import RSA
else:
from Cryptod | ome.PublicKey impo | rt DSA
from Cryptodome.PublicKey import RSA
RSA_WEAK = 1024
RSA_OK = 2048
RSA_STRONG = 3076
DSA_WEAK = 1024
DSA_OK = 2048
DSA_STRONG = 3076
BIG = 10000
EC_WEAK = ec.SECT163K1() # has key size of 163
EC_OK = ec.SECP224R1()
EC_STRONG = ec.SECP384R1()
EC_BIG = ec.SECT571R1()
dsa_gen_key = dsa.generate_private_ke... |
liqd/a4-meinberlin | meinberlin/apps/budgeting/migrations/0008_auto_20170529_1302.py | Python | agpl-3.0 | 663 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import ckeditor.fields
from django | .db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
('meinberlin_budgeting', '0007_update-strings'),
]
operations = [
migrations.AlterField(
model_name='proposal',
name='description',
field=ckedito... | name='name',
field=models.CharField(max_length=120, verbose_name='Name'),
),
]
|
bogobog/hierarchy_config_parser | bin/config_variable_processor/range_list.py | Python | gpl-2.0 | 299 | 0.070234 |
def range_list( parser, | *args ):
if len( args ) < 2:
raise Exception( 'Insufficient arguments.' )
if len( args ) == 3:
sep = args[2]
else:
sep = ' '
items = list( str( i ) for i in range( int( | args[0] ), int( args[1] ) + 1 ) )
return sep.join( items )
|
bairdj/beveridge | src/create_model.py | Python | mit | 3,408 | 0.006455 | import argparse
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.feature_selection import RFECV
from sklearn.ensemble import RandomForestClassifier
from beveridge.models import ModelStorage
import pickle
parser = argparse.ArgumentParser(description="Create model from CSV stats data.... | domForestClassifier(n_estimators=100, min_samples_split=0.02, class_weight='balanced')
rf.fit(data[trainColumns], data['win'])
print("Random forest accuracy: {:%}".form | at(rf.score(data[trainColumns], data['win'])))
#Save random forest model to given filename
with open(args.outfile, 'wb') as file:
storage = ModelStorage(trainColumns, rf)
pickle.dump(storage, file) |
mhbu50/erpnext | erpnext/manufacturing/doctype/production_plan_sales_order/production_plan_sales_order.py | Python | gpl-3.0 | 222 | 0.004505 | # Copyright (c) 2015, Frappe | Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from frappe.model.document import Document
class Produc | tionPlanSalesOrder(Document):
pass
|
shadowjig/ponos | initalize_db.py | Python | gpl-3.0 | 127 | 0 | from Ponos import init_db
from env_vars import *
import sql | ite3
import os
print(DB_PATH)
open | (DB_PATH, 'w').close()
init_db()
|
mauroalberti/simSurf | geosurf_pure/spatial.py | Python | gpl-3.0 | 67,189 | 0.037553 | # -*- coding: utf-8 -*-
from __future__ import division
from math import sqrt, floor, ceil, sin, cos, tan, radians, asin, acos, atan, atan2, degrees
import numpy as np
import copy
from .utils import array_from_function, almost_zero
from array_utils import point_solution, formula_to_grid
from .errors i... | crs_project( self, srcCrs, destCrs ):
points = []
for point in self._pts:
destCrs_point = point.crs_project( srcCrs, destCrs )
points.append( destCrs_point )
return Line2D( points )
... |
def __init__( self, lines_list = [] ):
self._lines = [ line_2d.clone() for line_2d in lines_list ]
def add( self, line ):
return MultiLine2D( self._lines + [ line ] )
def clone( self ):
return MultiLine2D( self._lines )
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.