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 |
|---|---|---|---|---|---|---|---|---|
oliver-sanders/cylc | cylc/flow/flow_mgr.py | Python | gpl-3.0 | 2,831 | 0 | # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# 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 Licen... | 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, see <http://www.gnu.org/licenses/>.
"""Manage flow counter and flow metadata."""
from typing import Dict, Set, Optional
import datetime
from cylc... | ef __init__(self, db_mgr: "WorkflowDatabaseManager") -> None:
"""Initialise the flow manager."""
self.db_mgr = db_mgr
self.flows: Dict[int, Dict[str, str]] = {}
self.counter: int = 0
def get_new_flow(self, description: Optional[str] = None) -> int:
"""Increment flow counter,... |
hayderimran7/tempest | tempest/api/network/test_extra_dhcp_options.py | Python | apache-2.0 | 4,057 | 0.000246 | # Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | # Create a port with Extra DHCP Options
body = self.client.create_port(
network_id=self.network['id'],
extra_dhcp_opts=self.extra_dhcp_opts)
port_id = body['port']['id']
self.addCleanup(self.client.delete_port, port_id)
| # Confirm port created has Extra DHCP Options
body = self.client.list_ports()
ports = body['ports']
port = [p for p in ports if p['id'] == port_id]
self.assertTrue(port)
self._confirm_extra_dhcp_options(port[0], self.extra_dhcp_opts)
@test.idempotent_id('9a6aebf4-86ee-4... |
xmeng17/Malicious-URL-Detection | host/http_proxy/helper.py | Python | mit | 1,790 | 0.009497 | import codecs
import logging
import random
def import_url(path,lo,hi):
with codecs.open(path,encoding='utf-8') as f:
string = f.read()
arr = string.split('\n')
if not lo:
lo=0
if not hi:
hi=len(arr)
arr=arr[lo:hi]
url_arr = []
want = range(lo,hi)
# returns url an... | :
console_logger = logging.getLogger('consoleLogger')
hdlr = logging.FileHandler('./console.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(formatter)
console_logger... | vel(logging.DEBUG)
result_logger = logging.getLogger('resultLogger')
hdlr2 = logging.FileHandler('./'+path,encoding='utf-8')
formatter2 = logging.Formatter('%(message)s')
hdlr2.setFormatter(formatter2)
result_logger.addHandler(hdlr2)
result_logger.setLevel(logging.DEBUG)
return console_log... |
daviddoria/itkHoughTransform | Wrapping/WrapITK/Languages/SwigInterface/idx.py | Python | apache-2.0 | 1,236 | 0.01699 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
sys.path.append(sys.path[0]+os.sep+'pygccxml-1.0.0')
import pygccxml, sys, cStringIO
# the output file
outputFile = cStringIO.StringIO()
# init the pygccxml stuff
pygccxml.declarations.scopedef_t.RECURSIVE_DEFAULT = False
pygccxml.declarations.scopedef_t.A... | ]))[0]
# iterate over all the typedefs in the _cable_::wrappers namespace
for typedef in wrappers_ns.typedefs():
n = typedef.name
s = typedef.type.decl_string
# drop the :: prefix - it make swig prod | uce invalid code
if s.startswith("::"):
s = s[2:]
print >> outputFile, "{%s} {%s} {%s}" % (s, n, module)
content = outputFile.getvalue()
if sys.argv[2] != '-':
f = file( sys.argv[2], "w" )
f.write( content )
f.close()
else:
sys.stdout.write( content )
|
harshilasu/GraphicMelon | y/google-cloud-sdk/platform/gsutil/third_party/boto/boto/pyami/copybot.py | Python | gpl-3.0 | 4,262 | 0.002112 | # Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# 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, modi... | key.name)
| new_key.set_contents_from_filename(path)
self.copy_key_acl(key, new_key)
os.unlink(path)
except:
boto.log.exception('Error copying key: %s' % key.name)
def copy_log(self):
key = self.dst.new_key(self.log_file)
key.set_contents_from_filenam... |
sdgdsffdsfff/py-trace-parser | traceback_parser.py | Python | mit | 7,757 | 0.015227 | #coding=utf-8
'''
Created on 2015年5月18日
python traceback parser
@author: hzwangzhiwei
'''
import json
import re
def str_is_empty(s):
if s == None or s == '' or s.strip().lstrip().rstrip('') == '':
return True
return False
class TracebackParser(object):
'''
parser
'''
tb_is_trace = Tru... | #2. 解析不成功,尝试以错误类型解析,解析不成功在下一行
self._try_tb_type_msg(line)
return True
def trace_code_info(self):
if self.tb_is_trace:
if self.tb_files and len(self.tb_files) > 0:
return se | lf.tb_files[len(self.tb_files) - 1]
return ('', '', '')
def trace_msg(self):
return (self.tb_type, self.tb_type)
def tostring(self):
rst = ''
rst += self.tb_header
rst += '\n'
for f in self.tb_files:
rst += json.dumps(f, default = l... |
CRLab/curvox | src/curvox/mesh_comparisons.py | Python | mit | 5,606 | 0.001784 | import math
import meshlabxml
import os
import tempfile
import plyfile
import numpy as np
import numba
import binvox_rw
import subprocess
def print_hausdorff(hausdorff_distance):
for key, value in hausdorff_distance.items():
print('{}: {}'.format(key, value))
@numba.njit
def minmax(array):
# Ravel t... | = process.communicate()
with open(binvox0_filepath, 'r') as mesh0_binvox_file:
mesh0_binvox = binvox_rw.read_as_3d_array(mesh0_binvox_file)
with open(binvox1_filepath, 'r') as mesh1_binvox_file:
mesh1_binvox = binvox_rw.read_as_3d_array(mesh1_binvox_file)
jaccard = _jaccard_distance(mesh0_... | remove(temp_mesh1_filepath)
if os.path.exists(binvox0_filepath):
os.remove(binvox0_filepath)
if os.path.exists(binvox1_filepath):
os.remove(binvox1_filepath)
return jaccard
|
jeroanan/GameCollection | Tests/TestPlatform.py | Python | gpl-3.0 | 1,844 | 0.003254 | # Copyright (c) David Wilson 2015
# Icarus 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.
# Icarus is distributed in the hope that it... | id": "id",
"_Platform__name": "name",
"_Platform__description": "description"}
p = Platform.from_mongo_result(d)
self.assertEqual(d["_id"], p.id)
| self.assertEqual(d["_Platform__name"], p.name)
self.assertEqual(d["_Platform__description"], p.description)
|
tejasjadhav/django-scheduler | examples/basic/apple/urls.py | Python | gpl-3.0 | 747 | 0 | """apple URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import vi | ews
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
... | admin.site.urls),
]
|
graphql-python/graphql-core | tests/execution/test_sync.py | Python | mit | 7,073 | 0.001555 | from gc import collect
from inspect import isawaitable
from pytest import mark, raises
from graphql import graphql_sync
from graphql.execution import execute, execute_sync
from graphql.language import parse
from graphql.type import GraphQLField, GraphQLObjectType, GraphQLSchema, GraphQLString
from graphql.validation ... | {
"message": "Syntax Error: Expected Name, found '{'.",
"locations": [(1, 29)],
}
],
)
def does_not_return_an_awaitable_for_validation_errors():
doc = "fragment Example on Query { unknownField }"
... | urn_an_awaitable_for_sync_execution():
doc = "query Example { syncField }"
assert graphql_sync(schema, doc, "rootValue") == (
{"syncField": "rootValue"},
None,
)
def does_not_throw_if_not_encountering_async_operation_with_check_sync():
... |
OpenTrons/opentrons-api | update-server/otupdate/buildroot/__main__.py | Python | apache-2.0 | 4,273 | 0 | """
Entrypoint for the buildroot update server
"""
import argparse
import asyncio
import logging
import logging.config
from . import (get_app, BR_BUILTIN_VERSION_FILE,
config, constants, name_management)
from aiohttp import web
LOG = logging.getLogger(__name__)
try:
# systemd journal is available,... | etup_hostname())
LOG.info(f"Set hostname to {hostname}")
LOG.info('Building buildroot update server')
app = get_app(args.version_file, args.config_file)
name = app[constants.DEVICE_NAME_VARNAME]
LOG.info(f"Setting advertised name to {name}")
loop.run_until_complet | e(name_management.set_name(name))
LOG.info('Notifying systemd')
_notify_up()
LOG.info(
f'Starting buildroot update server on http://{args.host}:{args.port}')
web.run_app(app, host=args.host, port=args.port)
if __name__ == '__main__':
main()
|
Johnetordoff/osf.io | scripts/create_fakes.py | Python | apache-2.0 | 19,763 | 0.006274 | # -*- coding: utf-8 -*-
"""Fake data generator.
To use:
1. Install fake-factory.
pip install fake-factory
2. Create your OSF user account
3. Run the script, passing in your username (email).
::
python3 -m scripts.create_fakes --user fred@cos.io
This will create 3 fake public projects, each with 3 fake co... | will create a project with 4 components.
python3 -m scripts.create_fakes -u fred@cos --components '4' --nprojects 1
...will create a project with a series of components, 4 levels deep.
python3 -m scripts.create_fakes -u fred@cos --com | ponents '[1, [1, 1]]' --nprojects 1
...will create a project with two top level components, and one with a depth of 2 components.
python3 -m scripts.create_fakes -u fred@cos --nprojects 3 --preprint True
...will create 3 preprints with the default provider osf
python3 -m scripts.create_fakes -u fred@cos --nproj... |
pythonvietnam/pbc082015 | NguyenCongDuc/QuanLySV-JSON.py | Python | gpl-2.0 | 2,031 | 0.034466 | #Chuong trinh Quan ly hoc sinh. Xay dung ham tim kiem, them moi
#haind
#python
import json
import os
#tao menu lua chon
def menu():
print '''
Chao mung ban den voi chuong trinh Quan ly hoc sinh!
Su dung:
1. Them moi hoc sinh
2. Tim kiem hoc sinh
3. Thoat chuong trinh (quit)
'''
return input("Moi ban lu... | n Them moi hoc sinh"
hs = dict()
name = raw_input("Ho va ten: ")
birth = raw_input("Ngay sinh: ")
addr = raw_input("Dia chi: ")
global ds
#Tao dict
hs['Ho ten'] = name
hs['Ngay sinh'] = birth
hs['Dia chi'] = addr
|
#Them hoc sinh vao danh sach
ds.append(hs)
print ""
print "Thong tin hoc sinh vua duoc them vao: %s"%(ds)
print ""
#chuc nang tim kiem hoc sinh
def timHS():
print "Ban da lua chon Tim kiem hoc sinh"
timkiem = raw_input("Moi ban nhap ten hoc sinh muon tim: ")
ketquatim = list()
for i in ds:
if i['Ho ten'] ... |
irmen/Pyro4 | examples/gui_eventloop/gui_nothreads.py | Python | mit | 5,532 | 0.001627 | """
This example shows a Tkinter GUI application that uses event loop callbacks
to integrate Pyro's event loop into the Tkinter GUI mainloop.
No threads are used. The Pyro event callback is called every so often
to check if there are Pyro events to handle, and handles them synchronously.
"""
import time
import select
... | ct
daemon = Pyro4.Daemon()
obj = MessagePrinter(gui)
uri = daemon.register(obj, "pyrogui.message")
gui.add_message("Pyro server started. Not using threads.")
gui.add_message("Use the command line client to send messages.")
urimsg = "Pyro object uri = {0}".format(uri)
gui.add_message(urimsg)... | ui.mainloop()
if __name__ == "__main__":
main()
|
VROOM-Project/vroom-scripts | src/mdvrp_to_json.py | Python | bsd-2-clause | 3,918 | 0.000766 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import sys
from utils.benchmark import get_matrix
# Generate a json-formatted problem from a MDVRP file.
# Those benchmarks use double precision for matrix costs and results
# are usually reported with 2 decimal places. As a workaround, we
# multiply all costs... | location_index = len(coords)
coords.append(depot_coords)
for v in range(1, 1 + meta["VEHICLES_PER_DEPOT"]):
vehicles.append(
{
"id": 100 * depot_id + v,
"profile": "euc_2D",
"start": depot_coords,
... | ty": [meta["CAPACITY"]],
}
)
meta["VEHICLES"] = len(vehicles)
if meta["MAX_ROUTE_DURATION"] != 0:
for vehicle in vehicles:
vehicle["time_window"] = [0, CUSTOM_PRECISION * meta["MAX_ROUTE_DURATION"]]
matrix = get_matrix(coords, CUSTOM_PRECISION)
return ... |
xzturn/caffe2 | caffe2/python/predictor/predictor_py_utils.py | Python | apache-2.0 | 4,921 | 0.000203 | ## @package predictor_py_utils
# Module caffe2.python.predictor.predictor_py_utils
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, scope
def create_predict_net(predictor_export_meta):
... | _type is not None:
net.Proto().type = predictor_export_meta.net_type
if predictor_export_meta.num_workers is not None:
net.Proto().num_workers = predictor_export_meta.num_workers
return net.Proto()
def create_predict_init_net(ws, predictor_export_meta):
"""
Return an initialization net... | inference functionality in Caffe2.
"""
net = core.Net("predict-init")
def zero_fill(blob):
shape = predictor_export_meta.shapes.get(blob)
if shape is None:
if blob not in ws.blobs:
raise Exception(
"{} not in workspace but needed for shape: {... |
Ircam-Web/mezzanine-organization | organization/network/migrations/0100_organization_slug.py | Python | agpl-3.0 | 594 | 0.001684 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2017-04-07 | 12:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('organization_network', '0099_organization_validation_status'),
]
operations = [
migrations.AddField( |
model_name='organization',
name='slug',
field=models.CharField(blank=True, help_text='Leave blank to have the URL auto-generated from the name.', max_length=2000, null=True, verbose_name='URL'),
),
]
|
mwbetrg/englishdb | send-email.py | Python | cc0-1.0 | 315 | 0.009524 | import smtplib
fromaddr = 'mwbetrg@gmail.com'
toaddrs | = 'awangjangok@gmail.com'
msg = 'Why,Oh why!'
username = 'mwbetrg@gmail.com'
password = '5147mwbe'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls | ()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit() |
jeryfast/piflyer | piflyer/elevons.py | Python | apache-2.0 | 5,001 | 0.002799 | from servo_handler import servo_handler
import number_range as n
TILT_UP_LIMIT = 90
TILT_DOWN_LIMIT = -90
class elevons:
def __init__(self):
self.left = servo_handler(1)
self.right = servo_handler(2)
self.multiplier = 2
# mobile devide tilt limits
self.pitchUpLimit = 45
... | 45, 45)
self.setPitchRoll(pitch, roll)
# manual - raw control
def setAngle(self, pitch, roll):
#print("pitch,roll: %d %d"%(pitch,roll))
self.setPitchRollFromInput(pitch, roll)
# print("servo L, R: %d %d"%(self.left.getPosition(),self.right.getPosition()))
## Stabilize and A... | left.sub(val)
self.right.add(val)
def pullUp(self):
self.left.add()
self.right.add()
def pullDown(self):
self.left.sub()
self.right.sub()
"""
# stabilize mode algorithm
def stabilize(self, target_pitch, target_roll, pitch, roll):
# idea: map target-... |
JudTown17/solutions-geoprocessing-toolbox | capability/test/test_erg_tools/TestERGTools.py | Python | apache-2.0 | 6,160 | 0.001948 |
# -----------------------------------------------------------------------------
# Copyright 2015 Esri
# 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/LICEN... | eate an in_memory feature class to initially contain the input point
fc = arcpy.CreateFeatureclass_management("in_memory", "tempfc", "POINT",
| None, "DISABLED", "DISABLED",
sr)[0]
# open and insert cursor
with arcpy.da.InsertCursor(fc, ["SHAPE@"]) as cursor:
cursor.insertRow([inWGS84Point])
# create a featureset object and load th... |
avinassh/learning-tornado | tornado-book/extending-templates/basic_templates/main.py | Python | mit | 1,328 | 0.030873 | #!/usr/bin/env python
import os.path
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help= | "run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render(
"index.html",
| header_text = "Hi! I am the header",
footer_text = "the copyright stuff"
)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", IndexHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "templates"),
debug=True,
autoescape=None
)
... |
rcoup/traveldash | traveldash/gtfs/migrations/0011_auto__add_fare__add_unique_fare_source_fare_id__add_unique_shape_sourc.py | Python | bsd-3-clause | 16,927 | 0.007266 | # encoding: 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 model 'Fare'
db.create_table('gtfs_fare', (
('id', self.gf('django.db.models.fields.AutoFiel... | 'payment_method')
# Deleting field 'FareRule.price'
db.delete_column('gtfs_farerule', 'price')
# Deleting field 'FareRule.currency_type'
db.delete_column('gtfs_farerule', 'currency_type')
# Deleting field 'FareRule.transfer_duration'
db.delete_column('gtfs_farerule', ... | ting field 'FareRule.transfers'
db.delete_column('gtfs_farerule', 'transfers')
# Deleting field 'FareRule.farerule_id'
db.delete_column('gtfs_farerule', 'farerule_id')
# Deleting field 'FareRule.agency'
db.delete_column('gtfs_farerule', 'agency_id')
# Adding field 'Far... |
sebastian-code/django-surveys | setup.py | Python | bsd-3-clause | 2,169 | 0.000461 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def get_version(*file_paths):
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
v... | sys.exit()
if sys.argv[-1] == 'tag':
print("Tagging the version on github:")
os.system("g | it tag -a %s -m 'version %s'" % (version, version))
os.system("git push --tags")
sys.exit()
readme = open('README.md').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='django-surveys',
version=version,
description="""Surveys for django""",
long_description... |
johncbolton/amcpy | 111815001.py | Python | gpl-2.0 | 2,105 | 0.060333 | import random
import math
import sympy
from sympy import latex, fraction, Symbol, Rational
localid =11181500100000
letter=["a","b","c","d"]
n=[0,0,0,0,0,0]
m=[0,0,0,0,0]
f = open("111815001.tex","w") #opens file with name of "test.txt"
for x in range(0, 1000):
localid = localid +1
writewrong=["\correctchoice{... | latex(Rational(m[4],m[3]))
n[5]=random.randint(0,10)
if n[2]==n[4]:
letter[0]='undefined'
elif n[5]==8:
zz=random.randint(1,3)
letter[zz]='undefined'
if(len(letter)==4):
for z in range (0, 4):
writewrong[z]=writewrong[z]+str(letter[z])
random... |
f.write("\\begin{question}{")
f.write(str(localid))
f.write("}")
f.write("\n")
f.write("Find the slope using points: (")
f.write(str(n[1]))
f.write(",")
f.write(str(n[2]))
f.write(") and (")
f.write(str(n[3]))
f.write(",")
f.write(str(n[4]))
f.write("):")
f.wri... |
Azure/azure-sdk-for-python | sdk/recoveryservices/azure-mgmt-recoveryservicessiterecovery/azure/mgmt/recoveryservicessiterecovery/operations/_replication_recovery_services_providers_operations.py | Python | mit | 38,715 | 0.005321 | # 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 may ... | deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._ | config = config
def list_by_replication_fabrics(
self,
fabric_name, # type: str
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.RecoveryServicesProviderCollection"]
"""Gets the list of registered recovery services providers for the fabric.
Lists the... |
shelan/collectl-monitoring | plotter.py | Python | apache-2.0 | 3,847 | 0.00208 | from distutils.dir_util import copy_tree
from operator import itemgetter
import pandas as pd
import sys
from jinja2 import Environment, FileSystemLoader
import os
def generate_reports(folder):
hosts = []
# get all the paths o | f the root folder
files = [os.path.join(folder, fn) for fn in next(os.walk(folder))[2] if not fn.startswith(".")]
for logfile in files:
try:
data = pd.read_csv(logfile, delim_whitespace=True, comment='#', header=-1, index_col='timestamp',
parse_dates={'timesta... | "duplicate index occured in " + logfile
print "There are two similar timestamps in the log." \
" To correct that error remove the duplicate entry from " + logfile
hostname = os.path.basename(logfile).replace('.tab', "")
host_data = {}
host_data['name'] = hostnam... |
pdef/pdef-python | python/src/pdef/tests/test_descriptors.py | Python | apache-2.0 | 7,220 | 0.000416 | # encoding: utf-8
from __future__ import unicode_literals
import unittest
from mock import Mock
from pdef.tests.inheritance.protocol import *
from pdef.tests.interfaces.protocol import *
from pdef.tests.messages.protocol import *
class TestMessageDescriptor(unittest.TestCase):
def test(self):
descriptor ... | tor
def test_args(self):
method = TestInterface.descriptor.find_method('method')
assert len(method.args) == 2
assert method.args[0].name == 'arg0'
assert method.args[1].name == 'arg1'
assert method.args[0].type is descriptors.int32
assert method.args[1].type is desc... | find_method('post')
interface = descriptor.find_method('interface0')
assert method.is_terminal
assert not method.is_post
assert post.is_terminal
assert post.is_post
assert not interface.is_terminal
assert not interface.is_post
def test_invoke(self):
... |
1T/harlib | harlib/objects/request.py | Python | lgpl-3.0 | 3,945 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# harlib
# Copyright (c) 2014-2017, Andrew Robbins, All rights reserved.
#
# This library ("it") is free software; it is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY; you can redistribute it and/or
# modify it under the terms of LGPLv3 <https... | from typing import Any, Dict, List, NamedTuple, Optional
except ImportError:
pass
class HarRequestBody(HarMessageBody):
# <postData>
_required = [
'mimeType',
]
_optional = {
| '_size': -1,
'text': '', # HAR-1.2 required
'comment': '',
'_compression': -1,
'_encoding': '',
'params': [],
}
_types = {
'_size': int,
'_compression': int,
'params': [HarPostDataParam],
}
def __init__(self, obj=None):
# type:... |
mmetak/streamlink | src/streamlink/plugins/artetv.py | Python | bsd-2-clause | 3,541 | 0.000565 | """Plugin for Arte.tv, bi-lingual art and culture channel."""
import re
from itertools import chain
from streamlink.compat import urlparse
from streamlink.plugin import Plugin
from streamlink.plugin.api import http, validate
from streamlink.stream import HDSStream, HLSStream, HTTPStream, RTMPStream
SWF_URL = "http:... | [],
{
validate.text: {
"height": int,
"mediaType": validate.text,
| "url": validate.text,
validate.optional("streamer"): validate.text
},
},
),
"VTY": validate.text
}
})
class ArteTV(Plugin):
@classmethod
def can_handle_url(self, url):
return _url_re.match(url)
def _create_stream(self, s... |
dbentley/pants | src/python/pants/subsystem/subsystem.py | Python | apache-2.0 | 6,819 | 0.010412 | # coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under t | he Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
| unicode_literals, with_statement)
from twitter.common.collections import OrderedSet
from pants.option.optionable import Optionable
from pants.option.scope import ScopeInfo
from pants.subsystem.subsystem_client_mixin import SubsystemClientMixin, SubsystemDependency
class SubsystemError(Except... |
1905410/Misago | misago/users/models/rank.py | Python | gpl-2.0 | 1,966 | 0 | from django.core.urlresolvers import reverse
from djang | o.db import models, transaction
from django.utils.encoding import python_2_unicode_compatible
from misago.acl import version as acl_version
from misago.core.utils import slugify
_ | _all__ = ['Rank']
class RankManager(models.Manager):
def get_default(self):
return self.get(is_default=True)
def make_rank_default(self, rank):
with transaction.atomic():
self.filter(is_default=True).update(is_default=False)
rank.is_default = True
rank.save... |
vabs22/zulip | zerver/lib/test_classes.py | Python | apache-2.0 | 24,636 | 0.001624 | from __future__ import absolute_import
from __future__ import print_function
from contextlib import contextmanager
from typing import (cast, Any, Callable, Dict, Iterable, Iterator, List, Mapping, Optional,
Sized, Tuple, Union, Text)
from django.core.urlresolvers import resolve
from django.conf imp... | ckfile):
with open(cls.lockfile, 'w'): # nocoverage - | rare locking case
pass
super(UploadSerializeMixin, cls).setUpClass(*args, **kwargs)
class ZulipTestCase(TestCase):
# Ensure that the test system just shows us diffs
maxDiff = None # type: Optional[int]
'''
WRAPPER_COMMENT:
We wrap calls to self.client.{patch,put,get,pos... |
GzkV/bookstore_project | bookstore_project/urls.py | Python | mit | 1,408 | 0.003551 | """book | store_projec | t URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
... |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_04_01/aio/operations/_express_route_gateways_operations.py | Python | mit | 22,615 | 0.005218 | # 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 may ... | .models.ExpressRouteGatewayList
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.ExpressRouteGatewayList"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}... | p('error_map', {}))
api_version = "2020-04-01"
accept = "application/json"
# Construct URL
url = self.list_by_resource_group.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name,... |
erthalion/django-postman | postman/utils.py | Python | bsd-3-clause | 4,047 | 0.003706 | from __future | __ import unicode_literals
import re
import sys
from textwrap import TextWrapper
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.encoding import force_un | icode
from django.utils.translation import ugettext, ugettext_lazy as _
# make use of a favourite notifier app such as django-notification
# but if not installed or not desired, fallback will be to do basic emailing
name = getattr(settings, 'POSTMAN_NOTIFIER_APP', 'notification')
if name and name in settings.INSTALLED... |
kawamon/hue | desktop/core/ext-py/celery-4.2.1/t/unit/concurrency/test_concurrency.py | Python | apache-2.0 | 4,669 | 0 | from __future__ import absolute_import, unicode_literals
import os
from itertools import count
import pytest
from case import Mock, patch
from celery.concurrency.base import BasePool, apply_target
from celery.exceptions import WorkerShutdown, WorkerTerminate
class test_BasePool:
def test_apply_target(self):
... | :
target = Mock(name='target')
target.side_effect = KeyError()
with pytest.raises(KeyError):
apply_target(target, propagate=(KeyError,))
def test_apply_target__raises(self):
target = Mock(name='target')
target.side_effect | = KeyError()
with pytest.raises(KeyError):
apply_target(target)
def test_apply_target__raises_WorkerShutdown(self):
target = Mock(name='target')
target.side_effect = WorkerShutdown()
with pytest.raises(WorkerShutdown):
apply_target(target)
def test_appl... |
grpc/grpc-ios | native_src/third_party/googletest/googletest/test/googletest-env-var-test.py | Python | apache-2.0 | 4,173 | 0.005272 | #!/usr/bin/env python
#
# Copyright 2008, 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... | int(' Actual: %s' % (actual,))
raise AssertionError
def SetEnvVar(env_var, value):
"""Sets the env variable to 'value'; unsets it when 'value' is None."""
if value is not None:
environ[env_var] = v | alue
elif env_var in environ:
del environ[env_var]
def GetFlag(flag):
"""Runs googletest-env-var-test_ and returns its output."""
args = [COMMAND]
if flag is not None:
args += [flag]
return gtest_test_utils.Subprocess(args, env=environ).output
def TestFlag(flag, test_val, default_val):
"""Verif... |
stefpiatek/mdt-flask-app | tests/unit/test_main_forms.py | Python | mit | 10,190 | 0.000196 | import pytest
from wtforms.validators import ValidationError
from mdt_app.main.forms import *
from mdt_app.models import *
@pytest.mark.usefixtures('db_session', 'populate_db')
class TestQuerySelectFunctions:
def test_get_meetings(self):
"""returns future meetings that are not cancelled in order"""
... | mdt_vcmg='MDT',
medical_history='medical history here',
question='question here')
def test_validate_meeting(self):
"""
Custom validation failures:
- Case already exists for that patient on that date
- m... |
- no meeting or add_meeting data
"""
existing_date = Meeting.query.filter_by(date='2050-10-30').first()
existing_case = CaseForm(data=self.form.data,
meeting=existing_date)
double_meeting_in = CaseForm(data=self.form.data,
... |
rlabbe/filterpy | filterpy/kalman/mmae.py | Python | mit | 6,370 | 0.000471 | # -*- coding: utf-8 -*-
# pylint: disable=invalid-name,too-many-instance-attributes
"""Copyright 2015 Roger R Labbe Jr.
FilterPy library.
http://github.com/rlabbe/filterpy
Documentation at:
https://filterpy.readthedocs.org
Supporting book at:
https://github.com/rlabbe/Kalman-and-Bayesia | n-Filters-in-Python
This is licensed under an MIT license. See the readme.MD file
for more information.
"""
from __future__ import absolute_import, division
from copy import deepcopy
import numpy as np
from filterpy | .common import pretty_str
class MMAEFilterBank(object):
"""
Implements the fixed Multiple Model Adaptive Estimator (MMAE). This
is a bank of independent Kalman filters. This estimator computes the
likelihood that each filter is the correct one, and blends their state
estimates weighted by their li... |
RasaHQ/rasa_nlu | rasa/nlu/featurizers/sparse_featurizer/lexical_syntactic_featurizer.py | Python | apache-2.0 | 21,849 | 0.001968 | from __future__ import annotations
import logging
from collections import OrderedDict
import scipy.sparse
import numpy as np
from typing import (
Any,
Dict,
Text,
List,
Tuple,
Callable,
Set,
Optional,
Type,
Union,
)
from rasa.engine.graph import ExecutionContext, GraphComponent... | ],
}
def __init__(
self,
config: Dict[Text, Any],
model_storage: ModelStorage,
resource: Resource,
execution_context: ExecutionContext,
feature_to_idx_dict: Optional[Dict[Tuple[int, Text], Dict[Text, int]]] = None,
) -> None:
"""Instantiates ... | t.node_name, config)
# graph component
self._model_storage = model_storage
self._resource = resource
self._execution_context = execution_context
# featurizer specific
self._feature_config = self._config[FEATURES]
self._set_feature_to_idx_dict(
feature_... |
NiuXWolf/Introduction-to-Algorithms | B/BitArray/BitArray.py | Python | mit | 2,972 | 0.023217 | #BitArray
#Yu.Yang
#
class bitarray():
def __init__(self,length,defaultValue=False):
if (length < 0):
raise Exception("Length param error")
self.array=[]
self.length=length
fillValue=defaultValue
for i in range(self.length):
self.array.append(defaultV... | range(self.length):
self.array[i]|=value.Get(i)
self.version+=1
return self
def Xor (self,value):
if(isinstance(value,BitArray)==False):
raise Exception("value is not a BitArray")
if (value is None or len(value)!=self.length):
raise Exception("Arg... | entException if value == null or value.Length != this.Length.")
for i in range(self.length):
self.array[i]^=value.Get(i)
self.version+=1
return self
def Not (self):
for i in range(self.length):
self.array[i] =not self.array[i]
self.version+=1
... |
jawilson/home-assistant | homeassistant/components/integration/sensor.py | Python | apache-2.0 | 7,671 | 0.001043 | """Numeric integration of data coming from a source sensor over time."""
from decimal import Decimal, DecimalException
import logging
import voluptuous as vol
from homeassistant.components.sensor import (
DEVICE_CLASS_ENERGY,
DEVICE_CLASS_POWER,
PLATFORM_SCHEMA,
STATE_CLASS_TOTAL,
SensorEntity,
)
... | TIME_SECONDS,
)
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.restore_state import RestoreEntity
# mypy: allow-untyped-defs, no-check-untyped-defs
_LOGGER = logging.getL... | ame__)
ATTR_SOURCE_ID = "source"
CONF_SOURCE_SENSOR = "source"
CONF_ROUND_DIGITS = "round"
CONF_UNIT_PREFIX = "unit_prefix"
CONF_UNIT_TIME = "unit_time"
CONF_UNIT_OF_MEASUREMENT = "unit"
TRAPEZOIDAL_METHOD = "trapezoidal"
LEFT_METHOD = "left"
RIGHT_METHOD = "right"
INTEGRATION_METHOD = [TRAPEZOIDAL_METHOD, LEFT_METH... |
ZiTAL/zpy | private/lib/env.py | Python | agpl-3.0 | 439 | 0.047836 | #!/usr/b | in/python2
# -*- coding: utf-8 -*-
import json, web
from lib.log import Log
class Env(object):
@staticmethod
def get(key):
if key and key in web.ctx.env:
return web.ctx.env[key]
else:
return web.ctx.env
@staticmethod
def set(key, value):
web.ctx.env[key] = value
@staticmethod
def setFromFile(fi... | e |
phenoxim/cinder | cinder/tests/unit/api/v3/test_workers.py | Python | apache-2.0 | 8,104 | 0 | # Copyright (c) 2016 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... | rue '}, {'disabled': ' false '})
@mock.patch('cinder.scheduler.rpcapi.SchedulerAPI.work_cleanup')
def test_cleanup_wrong_param(self, body, rpc_mock):
res = self._get_resp_post(body)
self.assertEqual(http_client.BAD_REQUEST, res.status_code)
expected = 'Invalid input'
self.ass... | y': 'value'})
@mock.patch('cinder.scheduler.rpcapi.SchedulerAPI.work_cleanup')
def test_cleanup_with_additional_properties(self, body, rpc_mock):
res = self._get_resp_post(body)
self.assertEqual(http_client.BAD_REQUEST, res.status_code)
expected = 'Additional properties are not allowed'
... |
clips/pattern | examples/04-search/02-constraint.py | Python | bsd-3-clause | 2,667 | 0.002625 | from __future__ import print_function
from __future__ import unicode_literals
from builtins import str, bytes, dict, int
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from patt | ern.search import search, Pattern, Con | straint
from pattern.en import parsetree, parse, Sentence
# What we call a "search word" in example 01-search.py
# is actually called a constraint, because it can contain different options.
# Options are separated by "|".
# The next search pattern retrieves words that are a noun OR an adjective:
s = parsetree("big whi... |
wiredrive/wtframework | wtframework/wtf/testobjects/testcase.py | Python | gpl-3.0 | 8,295 | 0.001085 | ##########################################################################
# This file is part of WTFramework.
#
# WTFramework 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 L... | for test_watcher in self.__wtf_test_watchers__:
test_watcher.before_test(self, result)
| # Run our test
testMethod()
# Run our test watcher post test actions.
for test_watcher in self.__wtf_test_watchers__:
test_watcher.on_test_pass(self, result)
except self.failureException as e:
... |
popovsn777/new_training | test/__init__.py | Python | apache-2.0 | 22 | 0 | __author__ = 'Elm | ira | '
|
holocronweaver/wanikani2anki | scripts/webdriver.py | Python | mpl-2.0 | 1,795 | 0.001671 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import mimetypes
from selenium import webdriver
import selenium.common.exception | s
class WebDriver:
"""Use a Selenium web driver to ease login, navigation, and access of
HTTPS sites.
WARNING: Always use a dummy Firefox profile for scraping, never
your main profile! This avoids possibility of corrupting your main
profile.
"""
def __init__(self, firefox_profile,
... | elf._configure_downloads(download_path, download_types)
self.driver = webdriver.Firefox(self.fp)
self.driver.set_page_load_timeout(5)
def _configure_downloads(self, path, types):
"""WARNING: Changes profile settings.
Examples of types include audio/mpeg and text/csv. See Firefox opt... |
EwanC/pyProc | proc_scraper/proc_maps.py | Python | mit | 600 | 0 | #!/usr/bin/env python3
from .proc_base import ProcBase
class ProcMaps(ProcBase):
| '''Object represents the /proc/[pid]/maps file.'''
def __init__(self, pid):
'''
Read file by callin | g base class constructor
which populates self.content. This file is
already ASCII printable, so no further
parsing is needed.
'''
super().__init__('/proc/{0}/maps'.format(pid))
def dump(self):
'''Print information gathered to stdout.'''
super().dump() # Prin... |
andersroos/rankedftw | tasks/delete_data_for_sample.py | Python | agpl-3.0 | 2,383 | 0.007134 | #!/usr/bin/env python3
# noinspection PyUnresolvedReferences
import init_django
from django.db import transaction
from common.utils import utcnow
from main.archive import DataArchiver
from main.delete import DataDeleter
from main.models import Ranking
from main.purge import purge_player_data
from tasks.base import C... | nfo(f"archiving ranking {ranking.id}")
data_archiver.archive_ranking(ranking, self.check_stop)
else:
logger.info("DRY RUN no archiving of rankings")
# Delete ladders that are no longer needed.
keep_season_ids = {r.season_id for r in Ranking.objec... | data_deleter.delete_ladders(tuple(keep_season_ids))
# Delete cache data that is unused.
data_deleter.agressive_delete_cache_data()
# Purge players and teams.
if args.delete:
purge_player_data(check_stop=self.check_stop)
else:
logger.inf... |
rspavel/spack | var/spack/repos/builtin/packages/r-reprex/package.py | Python | lgpl-2.1 | 1,861 | 0.002149 | # 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 RReprex(RPackage):
"""Convenience wrapper that uses the 'rmarkdown' package to render smal... | a9376c031d734d9e75c237efb24d047f35b5ba4b')
depends_on('r@3.0.2:', when='@:0.1.2', type=('build', 'run'))
depends_on('r@3.1:', when='@0.2.0:', type=('build', 'run') | )
depends_on('r-callr@2.0.0:', type=('build', 'run'))
depends_on('r-clipr@0.4.0:', type=('build', 'run'))
depends_on('r-knitr', when='@:0.1.9', type=('build', 'run'))
depends_on('r-rmarkdown', type=('build', 'run'))
depends_on('r-whisker', type=('build', 'run'))
depends_on('r-rlang', when='@0.2.... |
lucemia/gcloud-python | gcloud/datastore/test_query.py | Python | apache-2.0 | 25,434 | 0 | # Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | l(que | ry.kind, _KIND_AFTER)
def test_ancestor_setter_w_non_key(self):
_DATASET = 'DATASET'
query = self._makeOne(_DATASET)
def _assign(val):
query.ancestor = val
self.assertRaises(TypeError, _assign, object())
self.assertRaises(TypeError, _assign, ['KIND', 'NAME'])
... |
Psycojoker/cocktailator | cocktails/urls.py | Python | gpl-3.0 | 1,074 | 0.005597 | # encoding: utf-8
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib import admin
from data import get_ingredients, get_cocktails
admin.autodiscover()
def ingredients(request):
... | s ingrédients</p>")
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="home.html"), name='home'),
url(r'^in | gredients/$', ingredients, name='ingredients'),
url(r'^cocktails/$', cocktails, name='cocktails'),
# url(r'^cocktails/', include('cocktails.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
veltzer/demos-python | src/exercises/basic/digits_report/solution9.py | Python | gpl-3.0 | 433 | 0 | #!/usr/bin/env p | ython
digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
found = True
while found:
input_string = input('Please give me some digits... \n')
found = False
for character in input_string:
if character not in digits:
# we have a non digit!
print('Error, you gave me non ... | rk on', input_string)
|
jk0/pyhole | pyhole/core/version.py | Python | apache-2.0 | 1,788 | 0 | # Copyright 2011-2016 Josh Kearney
#
# 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 agre... |
# | 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.
"""Pyhole Version Handling"""
import os
import sys
__VERSION__ = "0.8.9"
def current_git_hash():
"""Return the current git hash."... |
eufat/gender-ml | src/gender_last_two.py | Python | mit | 1,327 | 0.009043 | import nltk
from read_lineByLine_toList import read_line_by_line
from find_consonants import count_consonants
import random
male_list = read_line_by_line('datasets/male.csv')
female_list = read_line_by_line('datasets/female.csv')
# ambil kata pertama dari kalimat
def get_first_word(words):
words_list = words.spli... | f 2 kata terakhir
labeled_names = (
[(name, 'male' | ) for name in male_list] +
[(name, 'female') for name in female_list]
)
random.shuffle(labeled_names)
featuresets = [(gender_features_last_two(n), gender) for (n, gender) in labeled_names]
train_set = featuresets[500:]
test_set = featuresets[:500]
classifier = nltk.NaiveBayesClassifier.train(train_set)
print ... |
EvanK/ansible | test/integration/targets/vault/faux-editor.py | Python | gpl-3.0 | 1,212 | 0 | #!/usr/bin/env python
#
# 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 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 ... | iles. See
# https://docs.ansible.com/playbooks_vault.html for more details.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import time
import os
def main(args):
path = os.path.abspath(args[1])
fo = open(path, 'r+')
content = fo.readlines()
conte... |
eadgarchen/tensorflow | tensorflow/contrib/slim/python/slim/nets/resnet_v2.py | Python | apache-2.0 | 14,548 | 0.003299 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Versi | on 2.0 (the "License");
# you may not use this file except in compliance wit | h 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 implie... |
Vaidyanath/tempest | tempest/api/volume/test_volumes_extend.py | Python | apache-2.0 | 1,453 | 0 | # Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ | ired 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.
from tempest.api.volume import base
from tempest import config
from tempest import test
CONF = config.CONF
class VolumesV2ExtendTest(base.BaseVolumeTest):
@classmethod
def setup_clients(cls):
super(... |
Fokko/incubator-airflow | tests/models/test_variable.py | Python | apache-2.0 | 3,100 | 0.00129 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... | lf.assertEqual(test_var.val, 'value')
def test_var_with_encryption_rotate_fernet_key(self):
"""
Tests rotating encrypted variables.
"""
key1 = Fernet.generate_key()
| key2 = Fernet.generate_key()
with conf_vars({('core', 'fernet_key'): key1.decode()}):
Variable.set('key', 'value')
session = settings.Session()
test_var = session.query(Variable).filter(Variable.key == 'key').one()
self.assertTrue(test_var.is_encrypted)
... |
skladsec/facebookFriendSaver | facebookFriendSaver.py | Python | isc | 3,504 | 0.041952 | #!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys, getopt, re, os
try:
from splinter import Browser
except:
print "Please install Splinter: http://splinter.readthedocs.org/en/latest/install.html"
sys.exit();
import getpass
from splinter.request_handler.status_code import HttpResponseError
def main(argv):
em... | /mbasic/","%s"%profile,"%s"%self]
for fr | iend in friends:
if all([x not in friend['href'] for x in notList ]):
fileopt.write('%s\n' % friend['href'])
print '%s' % friend.value
while browser.is_element_present_by_css("#m_more_friends"):
browser.find_by_css('#m_more_friends a').first.click()
friends = browser.find_by_css('a')
for friend... |
morrillo/oerp_migrator | oerp_migrator.py | Python | gpl-2.0 | 9,295 | 0.049828 | #!/usr/bin/python
# -*- coding: latin-1 -*-
import yaml
import xmlrpclib
import sys
import ConfigParser
import pdb
import logging
from datetime import date
from datetime import datetime
def get_model_id(oerp_destino,model=None):
""" Return model processed ID """
if model == None:
return_id = 0
else:
sock = oe... | (dict_parms['port'])+'/xmlrpc/common')
# import pdb;pdb.set_trace()
uid = sock_common.login(dict_parms['dbname'], dict_parms['username'], dict_parms['password'])
#replace localhost with the address of the server
sock = xmlrpclib.ServerProxy('http://'+dict_parms['hostname']+':'+str(dict_parms['port'])+'/xmlrpc/obje... | e']
dict_connection['sock'] = sock
return dict_connection
def migrate_model(oerp_origen = None, oerp_destino = None, model = None, fields = None, filter_parm = ''):
if not oerp_origen or not oerp_destino or not model or not fields:
exit(1)
logging.info("Migrando modelo %s"%(model))
# data_obj = oerp_origen.ge... |
npalko/uRPC | examples/python/client.py | Python | bsd-3-clause | 385 | 0.038961 | import sys
sys.path.append('../../python/')
import urpc
import randexample_pb2
if __name__ == '__main__':
client = urpc.client.SingleThreadClient()
request = randexample_pb2.Request | ()
reply = randexample_pb2.Reply()
request.nMessage = 1
request.nSample = 10
client.sendRequest('some service',8,request)
reply.ParseFromString(client.getReply())
print r | eply
|
kzcashteam/kzcash | qa/rpc-tests/multi_rpc.py | Python | mit | 4,593 | 0.005225 | #!/usr/bin/env python2
# Copyright (c) 2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test mulitple rpc user config option rpcauth
#
from test_framework.test_framework import BitcoinTestFrame... | #################################
url = urlparse.urlparse(self.nodes[0].url)
#Old authpair
authpair = url.username + ':' + url.password
#New authpair generated via share/rpcuser tool
rpcauth = "rpcauth=rt:93648e835a54c573682c2eb19f882535$7681e9c5b74bdd85e78166031d2058e1069b3ed7... | different username
rpcauth2 = "rpcauth=rt2:f8607b1a88861fac29dfccf9b52ff9f$ff36a0c23c8c62b4846112e50fa888416e94c17bfd4c42f88fd8f55ec6a3137e"
password2 = "8/F3uMDw4KSEbw96U3CA1C4X05dkHDN2BPFjTgZW4KI="
authpairnew = "rt:"+password
headers = {"Authorization": "Basic " + str_to_b64str(authp... |
studio1247/gertrude | document_dialog.py | Python | gpl-3.0 | 13,966 | 0.002794 | # -*- coding: utf-8 -*-
# This file is part of Gertrude.
#
# Gertrude 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.
#... | xt step is the most important, it turns this Python
# object into the real wrapper of the dialog (instead of pre)
# as far as the wxPython extension is concerned.
self.PostCreate(pre)
self.sizer = wx.BoxSizer(wx.VERTICAL)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(wx.... | hoices=["Texte"])
elif sys.platform == 'win32':
self.format = wx.Choice(self, -1, choices=["LibreOffice", "PDF"])
else:
self.format = wx.Choice(self, -1, choices=["LibreOffice"])
self.format.SetSelection(0)
self.Bind(wx.EVT_CHOICE, self.onFormat, self.format)
... |
rjferrier/fluidity | tools/optimality.py | Python | lgpl-2.1 | 32,527 | 0.017647 | #!/usr/bin/python
# Copyright (C) 2006 Imperial College London and others.
#
# Please see the AUTHORS file in the main source directory for a full list
# of copyright holders.
#
# Prof. C Pain
# Applied Modelling and Computation Group
# Department of Earth Science and Engineering
# Imperial College... | != 0:
print "Model execution failed."
print "The error | was:"
print outerr
exit()
if verbose:
print "Model output: "
print out
# Intialises the custom controls using the supplied python code.
def get_custom_controls(opt_options):
nb_controls = superspud(opt_options, "libspud.option_count('/control_io/control')")
m = {}
for i in range(nb_controls):
... |
alexalv-practice/topoml | modules/root.py | Python | mit | 532 | 0 | # -*- coding: utf-8 -*-
import cherrypy
class Root(object):
exposed = True
@cherrypy.tools.json_out()
def GET(self, id=None):
return ["Hello", "world", "!"]
if __name__ == '__main__':
conf = {
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'... | 'tools.response_headers.headers': [('Content-Type', 'text/plain')],
}
}
cherrypy.quick | start(Root(), '/', conf)
|
cgranade/qutip | qutip/tests/test_cy_structs.py | Python | bsd-3-clause | 1,816 | 0 | import pytest
import numpy as np
import scipy.sparse
import qutip
from qutip.fastsparse import fas | t_csr_matrix
from qutip.cy.checks import (_test_sorting, _test_ | coo2csr_inplace_struct,
_test_csr2coo_struct, _test_coo2csr_struct)
from qutip.random_objects import rand_jacobi_rotation
def _unsorted_csr(N, density=0.5):
M = scipy.sparse.diags(np.arange(N), 0, dtype=complex, format='csr')
nvals = N**2 * density
while M.nnz < 0.95*nvals:
... |
lugensa/js.dynatree | js/dynatree/__init__.py | Python | bsd-3-clause | 362 | 0.005525 | from fanstatic import Library, Resource
import js.jquery
import js.jqueryui
library = Library('dynatree', 'resources')
dynatree_css = Resource(library, 'src/skin-vista/ui.dynatree.css')
dynatree = Resource(library, 'src/jquery.dynatree.js',
mi | nified='src/jquery.dynatree.min.js',
depends=[dyn | atree_css, js.jquery.jquery, js.jqueryui.jqueryui])
|
viveksck/author-dedupe | src/flln_partition.py | Python | gpl-3.0 | 4,607 | 0.001519 | # Copyright 2008, Jeffrey Regier, jeff [at] stat [dot] berkeley [dot] edu
# This file is part of Author-Dedupe.
#
# Author-Dedupe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the... | num_changes += 1
return num_changes
def merge(self):
self.merge_iter(self.target_equivalent)
#iteratively merge the parts into the stricter parts,
#when there is only one stricter part
while self.merge_iter(self.target_sole_stricter):
pass
#TODO: why... | a.merged_name = merged_name
|
ibamacsr/painelmma_api | restApp/tests.py | Python | mit | 8,630 | 0.000579 | #from django.test import TestCase
from datetime import date
from decimal import *
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from rest_framework.test import APITestCase
from rest_framework.authtoken.models import Token
from .models import *
from .mommy_recipes import *
... | se = get_response(self.client, self.url, self.params)
data_received = response.data[0]['data']
self.assertEqual(len(data_rece | ived), 2)
self.assertEqual(data_received[1]['dia'], 12)
self.assertEqual(data_received[1]['total'], Decimal('0.29'))
deter_awifs_1.make(data_imagem=date(2015, 10, 12), area_km2=0.31)
response = get_response(self.client, self.url, self.params)
data_received = response.data[0]['da... |
nonZero/demos-python | src/examples/long/reading_a_static_file_from_inside_a_package/mypack/mymod.py | Python | gpl-3.0 | 731 | 0.001368 | # CHECK_WITH python2
import pkg_resources
import os.path # for dir | name, join
import pkgutil # for get_data
static_file_content = pkg_resources.resource_string(
'mypack', 'static_file.html').decode()
print('static_file_content is [{0}]'.format(static_file_content))
def get_real_filename(filename):
return os.path.join(os.path.dirname(__file__), filename)
def get_data(file... |
return open(get_real_filename(filename), 'rb').read()
static_file_content2 = get_data('static_file.html').decode()
print('static_file_content2 is [{0}]'.format(static_file_content2))
static_file_content3 = pkgutil.get_data('mypack', 'static_file.html').decode()
print('static_file_content3 is [{0}]'.format(static_... |
turbokongen/home-assistant | homeassistant/components/motion_blinds/__init__.py | Python | apache-2.0 | 4,571 | 0.000875 | """The motion_blinds component."""
import asyncio
from datetime import timedelta
import logging
from socket import timeout
from motionblinds import MotionMulticast
from homeassistant import config_entries, core
from homeassistant.const import CONF_API_KEY, CONF_HOST, EVENT_HOMEASSISTANT_STOP
from homeassistant.except... | otionGateway(hass, multicast)
if not await connect_gateway_class.async_connect_gateway(host, key):
raise ConfigEntryNotReady
motion_gateway = connect_gateway_class.gateway_device
def update_gateway():
"""Call all updates using one async_add_executor_job."""
motion_gateway.Update()
... | meout:
# let the error be logged and handled by the motionblinds library
pass
async def async_update_data():
"""Fetch data from the gateway and blinds."""
try:
await hass.async_add_executor_job(update_gateway)
except timeout:
# let the... |
VagrantApe/flaskMicroblog | tests.py | Python | bsd-3-clause | 5,133 | 0.054744 | #!flask/bin/python
import os
import unittest
from coverage import coverage
cov = coverage(branch = True, omit = ['flask/*', 'tests.py'])
cov.start()
from config import basedir
from app import app, db
from app.models import User
from datetime import datetime, timedelta
from app.models import User, Post
class TestCase... | = 'john@example.com')
db.session.add(u)
db.session.commit()
assert u.is_authenticated() == True
assert u.is_active() == Tr | ue
assert u.is_anonymous() == False
assert u.id == int(u.get_id())
def __repr__(self):
return '<User %r>' % (self.nickname)
if __name__ == '__main__':
try:
unittest.main()
except:
pass
cov.stop()
cov.save()
print "\n\nCoverage Report:\n"
cov.report()
print "HTML version: " + os.path.join(based... |
andurilhuang/Movie_Income_Prediction | paper/historycode/toAnna/get_test.py | Python | mit | 1,236 | 0.006472 | import os
import requests
import json
import pandas as pd
import numpy as np
import time
| from datetime import datetime
TMDB_KEY = "60027f35df522f00e57a79b9d35 | 68423"
"""
def get_tmdb_id_list():
#function to get all Tmdb_id between 06-16
import requests
import json
# from year 1996-2016
year = range(2006,2017)
## 50 pages
page_num = range(1,50)
id_list = []
tmdb_id_query = "https://api.themoviedb.org/3/discover/movie?" \
... |
automl/paramsklearn | ParamSklearn/components/data_preprocessing/balancing.py | Python | bsd-3-clause | 4,086 | 0.000245 | import numpy as np
from HPOlibConfigSpace.configuration_space import ConfigurationSpace
from HPOlibConfigSpace.hyperparameters import CategoricalHyperparameter
from ParamSklearn.components.base import \
ParamSklearnPreprocessingAlgorithm
from ParamSklearn.constants import *
class Balancing(ParamSklearnPreproces... | , return_counts=True)
cw = 1. / counts
cw = cw / np.mean(cw)
for i, ue in enumerate(unique):
class_weights[ue] = cw[i]
if classifier in clf_:
init_params['classifier:class_weight'] = class_weights
return init_params, fit_params
... | ethod
def get_properties(dataset_properties=None):
return {'shortname': 'Balancing',
'name': 'Balancing Imbalanced Class Distributions',
'handles_missing_values': True,
'handles_nominal_values': True,
'handles_numerical_features': True,
... |
yephper/django | tests/template_tests/filter_tests/test_rjust.py | Python | bsd-3-clause | 1,060 | 0.00283 | from django.template.defaultfilters import rjust
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class | RjustTests(SimpleTestCase):
@setup({'rjust01': '{% autoescape off %}.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.{% endautoescape %}'})
def test_rjust01(self):
output = self.engine.render_to_str | ing('rjust01', {"a": "a&b", "b": mark_safe("a&b")})
self.assertEqual(output, ". a&b. . a&b.")
@setup({'rjust02': '.{{ a|rjust:"5" }}. .{{ b|rjust:"5" }}.'})
def test_rjust02(self):
output = self.engine.render_to_string('rjust02', {"a": "a&b", "b": mark_safe("a&b")})
self.assertE... |
wavefrontHQ/python-client | wavefront_api_client/models/response_container_paged_maintenance_window.py | Python | apache-2.0 | 4,929 | 0.000203 | # coding: utf-8
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the W... | ):
return F | alse
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, ResponseContainerPagedMaintenanceWindow):
return True
return self.to_dict() != other.to_dict()
|
savoirfairelinux/partner-addons | partner_multi_relation_extended/models/res_partner.py | Python | lgpl-3.0 | 1,635 | 0 | # -*- coding: utf-8 -*-
# © 2017 Savoir-faire Linux
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import _, api, fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
@api.onchange('parent_id')
def onchange_parent_id(self):
res = super(ResPartner, s... | _('You cannot set a parent entity, as there is '
'not any partner relation type flagged as '
'"Work Relation".')
}
self.parent_id = False
return res
@api.model
def create(self, vals):
"""
... | e a relation between a contact and its parent only when the
parent is a company.
"""
res = super(ResPartner, self).create(vals)
if res.parent_id and res.parent_id.is_company:
work_relation_type = self.env['res.partner.relation.type'].search([
('is_work_rel... |
python-krasnodar/python-krasnodar.ru | src/lessons/admin.py | Python | mit | 248 | 0.004032 | from d | jango.contrib import admin
from .models import Lesson, Series
class LessonAdmin(admin.ModelAdmin):
pass
class SeriesAdmin(admin.ModelAdmin):
pass
admin.site.register(Lesson, LessonAdmin)
admin.sit | e.register(Series, SeriesAdmin) |
kjaym/pypif | pypif/obj/common/reference.py | Python | apache-2.0 | 8,674 | 0.001268 | from six import string_types
from pypif.obj.common.display_item import DisplayItem
from pypif.obj.common.name import Name
from pypif.obj.common.pages import Pages
from pypif.obj.common.pio import Pio
class Reference(Pio):
"""
Information about a referenced publication.
"""
def __init__(self, doi=None... | ns.setter
def affiliations(self, affiliations):
self | ._validate_list_type('affiliations', affiliations, string_types)
self._affiliations = affiliations
@affiliations.deleter
def affiliations(self):
self._affiliations = None
@property
def acknowledgements(self):
return self._acknowledgements
@acknowledgements.setter
def a... |
hyms/academicControl | manage.py | Python | gpl-2.0 | 273 | 0 | #!/usr/bin/env python
import os
import sys
import MySQLdb
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "academicControl.settings")
from django.core.m | anagement import execute_from_command_line
exec | ute_from_command_line(sys.argv)
|
endlessm/chromium-browser | third_party/angle/third_party/VK-GL-CTS/src/scripts/khr_util/format.py | Python | bsd-3-clause | 3,242 | 0.029611 | # -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# drawElements Quality Program utilities
# --------------------------------------
#
# Copyright 2015 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use t... | suffix = 'll'
elif value >= 1 << 31:
suffix = 'u'
else:
suffix = ''
return constant + suffix
def commandParams (command):
if len(command.params) > 0:
return ", ".join(param.declaration for param in command.params)
| else:
return "void"
def commandArgs (command):
return ", ".join(param.name for param in command.params)
|
colinmarc/python-spdy | python-spdy/context.py | Python | bsd-2-clause | 6,954 | 0.039977 | from spdy.frames import *
from spdy._zlib_stream import Inflater, Deflater
from bitarray import bitarray
SERVER = 'SERVER'
CLIENT = 'CLIENT'
class SpdyProtocolError(Exception):
pass
def _bitmask(length, split, mask=0):
invert = 1 if mask == 0 else 0
b = str(mask)*split + str(invert)*(length-split)
return int(b, ... | = bitarray(bin(value)[2:])
zeroes = bitarray(num_bits - len(chunk))
zeroes.setall(False)
chunk = zeroe | s + chunk #pad with zeroes
bits += chunk
if num_bits == -1:
break
data = bits.tobytes()
#sixth, seventh and eighth bytes: length
out.extend(len(data).to_bytes(3, 'big'))
# the rest is data
out.extend(data)
else: #data frame
#first four bytes: stream_id
out.extend(frame.st... |
fritz0705/lglass | contrib/grs-import/grs-import-sqlid.py | Python | mit | 2,771 | 0.003609 | #!/bin/python
# coding: utf-8
import argparse
import sys
import signal
import traceback
import datetime
import lglass.object
import lglass_sql.nic
def objects(lines):
obj = []
for line in lines:
if isinstance(line, bytes):
line = line.decode("iso-8859-15")
if not line.strip() and... | local objects...", end='', flush=True)
current_objects = set(session.all_ids())
print(" Done.")
stats = dict(create | d=0,
updated=0,
deleted=0,
ignored=0,
start=datetime.datetime.now())
def report():
global stats
global current_objects
print("Created {} / Updated {} / Deleted {} / "
"Ignored {} objects in {}".format(stats["created"],
stats["updated"],
... |
AMOboxTV/AMOBox.LegoBuild | plugin.program.super.favourites/utils.py | Python | gpl-2.0 | 18,265 | 0.010183 | #
# Copyright (C) 2014-2015
# Sean Poyser (seanpoyser@gmail.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 2, or (at your option)
# any later version.
#
# ... | ndation, 675 Mass Ave, Cambridge, MA 02139, USA.
# http://www.gnu.org/copyleft/gpl.html
#
import xbmc
import xbmcaddon
import xbmcgui
import os
import re
import sfile
def GetXBMCVersion():
#xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "me | thod": "Application.GetProperties", "params": {"properties": ["version", "name"]}, "id": 1 }')
version = xbmcaddon.Addon('xbmc.addon').getAddonInfo('version')
version = version.split('.')
return int(version[0]), int(version[1]) #major, minor eg, 13.9.902
ADDONID = 'plugin.program.super.favourites'
ADDON ... |
karllessard/tensorflow | tensorflow/python/keras/layers/normalization_test.py | Python | apache-2.0 | 30,233 | 0.006648 | # Copyright 2016 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... | BatchNormalizationTest(kera | s_parameterized.TestCase):
@keras_parameterized.run_all_keras_modes
def test_basic_batchnorm(self):
testing_utils.layer_test(
keras.layers.BatchNormalization,
kwargs={
'momentum': 0.9,
'epsilon': 0.1,
'gamma_regularizer': keras.regularizers.l2(0.01),
... |
99designs/colorific | colorific/script.py | Python | isc | 4,123 | 0 | # -*- coding: utf-8 -*-
#
# script.py
# colorific
#
import sys
import optparse
from colorific import config
from colorific.palette import (
extract_colors, print_colors, save_palette_as_image, color_stream_mt,
color_stream_st)
class Application(object):
def __init__(self):
self.parser = self.c... |
action='store',
dest='min_prominence',
type='float | ',
default=config.MIN_PROMINENCE,
help="The minimum proportion of pixels needed to keep a color "
"[%.02f]" % config.MIN_PROMINENCE)
parser.add_option(
'--n-quantized',
action='store',
dest='n_quantized',
type='int',
... |
yashi/debbindiff | debbindiff/comparators/text.py | Python | gpl-3.0 | 1,446 | 0 | # -*- coding: utf-8 -*-
#
# debbindiff: highlight differences between two builds of Debian packages
#
# Copyright © 2014-2015 Jérémy Bobbio <lunar@debian.org>
#
# debbindiff 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... | compare_binary_files
from debbindiff.difference import Difference
def compare_text_files(path1, path2, encoding, source=None):
if encoding is None:
encoding = 'utf-8'
try:
file1 = codecs.open(path1, 'r | ', encoding=encoding)
file2 = codecs.open(path2, 'r', encoding=encoding)
difference = Difference.from_file(file1, file2, path1, path2, source)
except (LookupError, UnicodeDecodeError):
# unknown or misdetected encoding
return compare_binary_files(path1, path2, source)
if not diff... |
reverie/seddit.com | redditchat/core/permissions.py | Python | mit | 2,122 | 0.004241 | import functools
from common.tornado_cookies import get_secure_cookie, generate_secure_cookie
from core import cookies
class Perms(object):
NONE = None
READ = 'r'
WRITE = 'w'
def _permission_level(user, room):
"""
`user`'s permission level on `room`, ignoring cookies
"""
if not user.is_au... | ie(request, cookie_name)
if not perm:
return
assert perm in ('r', 'w')
return perm
def _set_cached_perm_level(response, cookie_name, perm_level):
assert perm_level | in ('r', 'w')
cookie_val = generate_secure_cookie(cookie_name, perm_level)
response.set_cookie(cookie_name, cookie_val)
def _perm_level_satisfies(perm_val, perm_req):
"""
If a user has permission level `perm_val`,
and is requesting access level `perm_req`.
"""
if perm_req == perm_val:
... |
salomax/livremarketplace | app_test/supplier_test.py | Python | apache-2.0 | 5,758 | 0.000521 | #!/usr/bin/env python
# coding: utf-8
#
# Copyright 2016, Marcos Salomão.
#
# 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 require... | estSave()
request = SupplierSearchMessage(name='Test')
list = self.search(request)
self.assertIsNotNone(list)
self.assertIsNo | tNone(list.items)
self.assertTrue(len(list.items) == 1)
request = SupplierSearchMessage(name='Yyy')
list = self.search(request)
self.assertIsNotNone(list)
self.assertIsNotNone(list.items)
self.assertTrue(len(list.items) == 0)
def testList(self):
""" List al... |
stackforge/tacker | tacker/objects/common.py | Python | apache-2.0 | 2,537 | 0 | # Copyright (C) 2021 NEC Corp
# 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 ... | filters = {'and': [
{'field': 'name', 'model': 'Foo', 'value': 'foo',
'op': '=='},
{'field': 'id', 'model': 'Bar', 'value': 'bar',
'op': '=='}
]}
| """
def apply_filter(query, filter):
value = filter.get('value')
op = filter.get('op')
model = getattr(models, filter.get('model'))
column_attr = getattr(model, filter.get('field'))
if 'in' == op:
query = query.filter(column_attr.in_(value))
elif 'not_in... |
hwoods723/script.gamescenter | resources/lib/eventdetails.py | Python | gpl-2.0 | 22,677 | 0.033558 | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match ... | join(addon_path,"resources","img","nokit_placeholder.png"))
else:
self.getControl(32501).setImage(os.path.join(addo | n_path,"resources","img","nobadge_placeholder.png"))
self.getControl(32502).setImage(os.path.join(addon_path,"resources","img","nokit_placeholder.png"))
#Default values for team names. It depends if it is a live object or simple a past event
if ("HomeTeam" in self.match.__dict__.keys() and "AwayTeam" in self.ma... |
dbbhattacharya/kitsune | vendor/packages/pylint/test/input/func_w0611.py | Python | bsd-3-clause | 378 | 0.005291 | """check un | used import
"""
__revision__ = 1
import os
import sys
class NonRegr:
"""???"""
def __init__(self):
print 'initialized'
def sys(self):
"""should not get sys from there..."""
print self, sys
def dummy(self, truc):
"""yo"""
return self, truc
def blop(self... | """yo"""
print self, 'blip'
|
1st1/uvloop | examples/bench/echoserver.py | Python | mit | 6,317 | 0 | import argparse
import asyncio
import gc
import os.path
import pathlib
import socket
import ssl
PRINT = 0
async def echo_server(loop, address, unix):
if unix:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.... | ):
os.remove(addr)
else:
addr = args.addr.split(':')
addr[1] = int(addr[1])
addr = tuple(addr)
print('serving on: {}'.format(addr))
server_context = None
| if args.ssl:
print('with SSL')
if hasattr(ssl, 'PROTOCOL_TLS'):
server_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
else:
server_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
server_context.load_cert_chain(
(pathlib.Path(__file__).parent.parent.parent... |
KernelAnalysisPlatform/KlareDbg | extra/parseida/parseidb.py | Python | gpl-3.0 | 553 | 0.009042 | impor | t sys
from hexdump import hexdump
# name.id0 - contains contents of B-tree style database
# name.id1 - contains flags that describe each program byte
# name.nam - contains index information related to named program locations
# name.til - contains information about local type definitions
BTREE_PAGE_SIZE = 8192
#dat =... | 0, len(dat), BTREE_PAGE_SIZE):
hexdump(dat[i:i+0xC0])
print ""
|
jkwill87/mapi | tests/endpoints/test_endpoints_tmdb.py | Python | mit | 4,908 | 0 | # coding=utf-8
"""Unit tests for mapi/endpoints/tmdb.py."""
import pytest
from mapi.endpoints import tmdb_find, tmdb_movies, tmdb_search_movies
from mapi.exceptions import MapiNotFoundException, MapiProviderException
from tests import JUNK_TEXT
GOONIES_IMDB_ID = "tt0089218"
GOONIES_TMDB_ID = 9340
JUNK_IMDB_ID = "tt... | vies__success(tmdb_api_key):
expected_top_level_keys = {
"adult",
"backdrop_path",
"belongs_to_collection",
"budget",
"genres",
"homepage",
"id",
"imdb_id",
"original_language",
"original_title",
"overview",
"popularity"... | er_path",
"production_companies",
"production_countries",
"release_date",
"revenue",
"runtime",
"spoken_languages",
"status",
"tagline",
"title",
"video",
"vote_average",
"vote_count",
}
result = tmdb_movies(tmdb_api... |
eli261/jumpserver | apps/common/__init__.py | Python | gpl-2.0 | 150 | 0.006667 | from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app | .
| |
rew4332/tensorflow | tensorflow/contrib/slim/python/slim/model_analyzer.py | Python | apache-2.0 | 3,218 | 0.007147 | # Copyright 2016 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... | e specific language governing permissions and
# limitations under the License.
# ======================== | ======================================================
"""Tools for analyzing the operations and variables in a TensorFlow graph.
To analyze the operations in a graph:
images, labels = LoadData(...)
predictions = MyModel(images)
slim.model_analyzer.analyze_ops(tf.get_default_graph(), print_info=True)
To analy... |
saai/codingbitch | DP/largestRectangleArea.py | Python | mit | 597 | 0.005025 | cla | ss Solution:
# @param {integer[]} height
# @return {integer}
def largestRectangleArea(self, height):
n = len(height)
ma = 0
stack = [-1]
for i in xrange(n):
while(stack[-1] > -1):
if height[i]<height[stack[-1]]:
top = stack.pop... | ma = max(ma, height[top]*(i-1-stack[-1]))
else:
break
stack.append(i)
while(stack[-1] != -1):
top = stack.pop()
ma = max(ma, height[top]*(n-1-stack[-1]))
return ma |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.