blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
7e6c17b5762d01ec1cdc2acbbd3e68c9af681cc0
494051ad9bac642175cbe57ecafeafa4a6b01dc8
/observing_scripts/180527/lmircam_unsats.py
47541dd4eff6f9a2b454680fd76fb98a4630ebf2
[]
no_license
mwanakijiji/LMIRcam_scripts
c80f8123d1c7ca78df69068fb4136dacc3802071
48d88cde6a4d428b2f08b0f50c05045d4927fb4d
refs/heads/master
2021-07-10T00:35:18.852627
2019-04-18T04:56:12
2019-04-18T04:56:12
109,775,920
0
0
null
null
null
null
UTF-8
Python
false
false
1,329
py
from lmircam_tools import pi from lmircam_tools.exposures import get_lmircam_frames from lmircam_tools.utils import nod, rawbg, setFLAG ################################################# # USER DEFINED PARAMETERS # ################################################# #camera dit = 1.3 coadds = 1 # this should probably be 1 nseqs = 10 inner_loop_max = 10 #telesecope reverse = False nod_x = 0 #arcseconds in detector coords nod_y = 7 side = 'left' # can be both, left, right N_cycles = 2 ################################################# # COMPUTATIONS/DEFINITIONS # ################################################# if reverse: nod_x = -1.0*nod_x nod_y = -1.0*nod_y if reverse: nod_names = ('NOD_B','NOD_A') else: nod_names = ('NOD_A','NOD_B') ################################################# # COMMAND SEQUENCE # ################################################# for ii in xrange(N_cycles): setFLAG(nod_names[0]) get_lmircam_frames(dit, coadds, nseqs, inner_loop_max=inner_loop_max) #rawbg() print 'nodding' nod(nod_x, nod_y, side) setFLAG(nod_names[1]) get_lmircam_frames(dit, coadds, nseqs, inner_loop_max=inner_loop_max) #rawbg() print 'nodding' nod(-1*nod_x, -1*nod_y, side) setFLAG('')
[ "spalding@email.arizona.edu" ]
spalding@email.arizona.edu
58297a472053a0f9ee3c0a37d5b700b520deb1e9
674013162755a57e258156832d7fdc645ab55c0d
/No0433-minimum-genetic-mutation-medium.py
1c7eea1f761d6538290d9038d8cc860b564b3078
[]
no_license
chenxy3791/leetcode
cecd6afb0a85e5563ba2d5ae8eb2562491f663e0
1007197ff0feda35001c0aaf13382af6869869b2
refs/heads/master
2023-06-25T13:54:12.471419
2023-06-12T05:02:03
2023-06-12T05:02:03
229,204,520
0
0
null
null
null
null
UTF-8
Python
false
false
1,958
py
# -*- coding: utf-8 -*- """ Created on Tue Apr 19 07:34:05 2022 @author: Dell """ from typing import List from collections import deque class Solution: def minMutation(self, start: str, end: str, bank: List[str]) -> int: def diff_is_one(s1,s2)->bool: cnt=0 for k in range(len(s1)): if s1[k]!=s2[k]: cnt+=1 return cnt==1 if end not in bank: return -1 if start not in bank: bank.insert(0, start) for k in range(len(bank)): if bank[k]==end: end_idx=k adjlist = [ [] for k in range(len(bank)) ] for k in range(len(bank)): for j in range(k,len(bank)): if diff_is_one(bank[k], bank[j]): adjlist[k].append(j) adjlist[j].append(k) # print(bank,adjlist) q = deque([(0,0)]) visited = set([0]) while len(q)>0: node,layer = q.popleft() if node == end_idx: return layer for nxt in adjlist[node]: if nxt not in visited: q.append((nxt,layer+1)) visited.add(nxt) return -1 if __name__ == "__main__": sln = Solution() start= "AACCGGTT" end= "AACCGGTA" bank= ["AACCGGTA"] print(sln.minMutation(start, end, bank)) start= "AACCGGTT" end= "AAACGGTA" bank= ["AACCGGTA", "AACCGCTA", "AAACGGTA"] print(sln.minMutation(start, end, bank)) start= "AAAAACCC" end= "AACCCCCC" bank= ["AAAACCCC", "AAACCCCC", "AACCCCCC"] print(sln.minMutation(start, end, bank)) start= "AACCGGTT" end= "AACCGGTA" bank= [] print(sln.minMutation(start, end, bank)) start= "AACCGGTT" end= "AACCGGTA" bank= ["AACCGGTA","AACCGCTA","AAACGGTA"] print(sln.minMutation(start, end, bank))
[ "chenxy@bwave.cc" ]
chenxy@bwave.cc
6a90371c674ee10ed4e7b1aad1604babdba2d592
794cac199162c496cc0727932e0326d5d8cb48d9
/byte/executors/pysqlite/models/transaction.py
535e7de5b10f44c70e8558e26bf3c12a03f933fe
[]
no_license
fuzeman/byte-pysqlite
6f259a17e8a8faf5a705015f55c34530b3beb021
72e72058957779536571059990376f3ec68318d4
refs/heads/master
2021-01-21T11:36:58.252030
2017-05-23T02:42:29
2017-05-23T02:42:29
91,747,570
0
0
null
null
null
null
UTF-8
Python
false
false
868
py
"""byte-pysqlite - executor transaction module.""" from __future__ import absolute_import, division, print_function from byte.executors.core.models.database import DatabaseTransaction from byte.executors.pysqlite.models.cursor import PySqliteCursor class PySqliteTransaction(DatabaseTransaction, PySqliteCursor): """PySQLite transaction class.""" def begin(self): """Begin transaction.""" self.instance.execute('BEGIN;') def commit(self): """Commit transaction.""" self.connection.instance.commit() def rollback(self): """Rollback transaction.""" self.connection.instance.rollback() def close(self): """Close transaction.""" # Close cursor self.instance.close() self.instance = None # Close transaction super(PySqliteTransaction, self).close()
[ "me@dgardiner.net" ]
me@dgardiner.net
645c89f4e0e5649c7ab97eddc0afc696ae5c8ed0
ac5e52a3fc52dde58d208746cddabef2e378119e
/exps-gsn-edf/gsn-edf_ut=2.0_rd=0.5_rw=0.04_rn=4_u=0.075-0.35_p=harmonic-2/sched=RUN_trial=35/sched.py
d665efe4468546c4f7ae91e8e871e66bb65f0ab3
[]
no_license
ricardobtxr/experiment-scripts
1e2abfcd94fb0ef5a56c5d7dffddfe814752eef1
7bcebff7ac2f2822423f211f1162cd017a18babb
refs/heads/master
2023-04-09T02:37:41.466794
2021-04-25T03:27:16
2021-04-25T03:27:16
358,926,457
0
0
null
null
null
null
UTF-8
Python
false
false
209
py
-X FMLP -Q 0 -L 3 79 400 -X FMLP -Q 0 -L 3 79 400 -X FMLP -Q 1 -L 1 65 300 -X FMLP -Q 1 -L 1 34 175 -X FMLP -Q 2 -L 1 33 175 -X FMLP -Q 3 -L 1 31 150 26 125 16 100 16 125 12 100 11 100 9 125
[ "ricardo.btxr@gmail.com" ]
ricardo.btxr@gmail.com
003d75e323d2f48d6eef690bf9dfce0df01c0fba
77d9e584576c76236d4e1eed6011df5b12a92ead
/code_for_training.py
f5830c0f7d434f5a93966ad9dc8f8841ffe4059f
[]
no_license
ObinnaObeleagu/datasets
ba9747ecd7b6fe3b22566222a6752d62e7c8ca23
61ca10d3c88d666bf3a9e2c471a270fec00d0521
refs/heads/master
2022-04-04T11:23:48.631874
2019-12-22T02:00:06
2019-12-22T02:00:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,957
py
import keras from keras.layers import * from keras.models import * from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import LearningRateScheduler import os from keras.callbacks import ModelCheckpoint from keras.optimizers import Adam #The Linear Bottleneck increases the number of channels going into the depthwise convs def LinearBottleNeck(x,in_channels,out_channels,stride,expansion): #Expand the input channels out = Conv2D(in_channels*expansion,kernel_size=1,strides=1,padding="same",use_bias=False)(x) out = BatchNormalization()(out) out = Activation(relu6)(out) #perform 3 x 3 depthwise conv out = DepthwiseConv2D(kernel_size=3,strides=stride,padding="same",use_bias=False)(out) out = BatchNormalization()(out) out = Activation(relu6)(out) #Reduce the output channels to conserve computation out = Conv2D(out_channels,kernel_size=1,strides=1,padding="same",use_bias=False)(out) out = BatchNormalization()(out) #Perform resnet-like addition if input image and output image are same dimesions if stride == 1 and in_channels == out_channels: out = add([out,x]) return out #Relu6 is the standard relu with the maximum thresholded to 6 def relu6(x): return K.relu(x,max_value=6) def MobileNetV2(input_shape,num_classes=2,multiplier=1.0): images = Input(shape=input_shape) net = Conv2D(int(32*multiplier),kernel_size=3,strides=2,padding="same",use_bias=False)(images) net = BatchNormalization()(net) net = Activation("relu")(net) #First block with 16 * multplier output with stride of 1 net = LinearBottleNeck(net, in_channels=int(32 * multiplier), out_channels=int(16 * multiplier), stride=1, expansion=1) #Second block with 24 * multplier output with first stride of 2 net = LinearBottleNeck(net, in_channels=int(32 * multiplier), out_channels=int(24 * multiplier), stride=2, expansion=6) net = LinearBottleNeck(net, in_channels=int(24 * multiplier), out_channels=int(24 * multiplier), stride=1, expansion=6) #Third block with 32 * multplier output with first stride of 2 net = LinearBottleNeck(net, in_channels=int(24 * multiplier), out_channels=int(32 * multiplier), stride=2, expansion=6) net = LinearBottleNeck(net, in_channels=int(32 * multiplier), out_channels=int(32 * multiplier), stride=1, expansion=6) net = LinearBottleNeck(net, in_channels=int(32 * multiplier), out_channels=int(32 * multiplier), stride=1, expansion=6) #Fourth block with 64 * multplier output with first stride of 2 net = LinearBottleNeck(net, in_channels=int(32 * multiplier), out_channels=int(64 * multiplier), stride=2, expansion=6) net = LinearBottleNeck(net, in_channels=int(64 * multiplier), out_channels=int(64 * multiplier), stride=1, expansion=6) net = LinearBottleNeck(net, in_channels=int(64 * multiplier), out_channels=int(64 * multiplier), stride=1, expansion=6) net = LinearBottleNeck(net, in_channels=int(64 * multiplier), out_channels=int(64 * multiplier), stride=1, expansion=6) #Fifth block with 96 * multplier output with first stride of 1 net = LinearBottleNeck(net, in_channels=int(64 * multiplier), out_channels=int(96 * multiplier), stride=1, expansion=6) net = LinearBottleNeck(net, in_channels=int(96 * multiplier), out_channels=int(96 * multiplier), stride=1, expansion=6) net = LinearBottleNeck(net, in_channels=int(96 * multiplier), out_channels=int(96 * multiplier), stride=1, expansion=6) #Sixth block with 160 * multplier output with first stride of 2 net = LinearBottleNeck(net, in_channels=int(96 * multiplier), out_channels=int(160 * multiplier), stride=2, expansion=6) net = LinearBottleNeck(net, in_channels=int(160 * multiplier), out_channels=int(160 * multiplier), stride=1, expansion=6) net = LinearBottleNeck(net, in_channels=int(160 * multiplier), out_channels=int(160 * multiplier), stride=1, expansion=6) #Seventh block with 320 * multplier output with stride of 1 net = LinearBottleNeck(net, in_channels=int(160 * multiplier), out_channels=int(320 * multiplier), stride=1, expansion=6) #Final number of channels must be at least 1280 if multiplier > 1.0: final_channels = int(1280 * multiplier) else: final_channels = 1280 #Expand the output channels net = Conv2D(final_channels,kernel_size=1,padding="same",use_bias=False)(net) net = BatchNormalization()(net) net = Activation(relu6)(net) net = Dropout(0.3)(net) #Final Classification is by 1 x 1 Conv net = AveragePooling2D(pool_size=(7,7))(net) net = Conv2D(num_classes,kernel_size=1,use_bias=False)(net) net = Flatten()(net) net = Activation("softmax")(net) return Model(inputs=images,outputs=net) ##Training on Custom Image Dataset # Directory in which to create models save_direc = os.path.join(os.getcwd(), 'oranges_models') # Name of model files model_name = 'oranges_weight_model.{epoch:03d}-{val_acc}.h5' # Create Directory if it doesn't exist if not os.path.isdir(save_direc): os.makedirs(save_direc) # Join the directory with the model file modelpath = os.path.join(save_direc, model_name) # Checkpoint to save best model checkpoint = ModelCheckpoint(filepath=modelpath, monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=True, period=1) # Function for adjusting learning rate def lr_schedule(epoch): """ Learning Rate Schedule """ lr = 0.001 if epoch > 30: lr = lr / 100 elif epoch > 20: lr = lr / 50 elif epoch > 10: lr = lr / 10 print('Learning rate: ', lr) return lr #learning rate schedule callback lr_scheduler = LearningRateScheduler(lr_schedule) optimizer = Adam(lr=0.001, decay=0.0005) BATCH_SIZE = 32 NUM_CLASSES = 2 EPOCHS = 50 model = MobileNetV2(input_shape=(224, 224, 3), num_classes=NUM_CLASSES) model.compile(loss="categorical_crossentropy", optimizer=optimizer, metrics=["accuracy"]) model.summary() #Data augmentation train_datagen = ImageDataGenerator( rescale=1. / 255, horizontal_flip=True) test_datagen = ImageDataGenerator( rescale=1. / 255) train_generator = train_datagen.flow_from_directory("Oranges2/train", target_size=(224, 224), batch_size=BATCH_SIZE, class_mode="categorical") test_generator = test_datagen.flow_from_directory("Oranges2/test", target_size=(224, 224), batch_size=BATCH_SIZE, class_mode="categorical") model.fit_generator(train_generator, steps_per_epoch=int(600 / BATCH_SIZE), epochs=EPOCHS, validation_data=test_generator, validation_steps=int(200 / BATCH_SIZE), callbacks=[checkpoint, lr_scheduler])
[ "noreply@github.com" ]
ObinnaObeleagu.noreply@github.com
96f02c283b1bea8c44deb683c011fe267a8e10aa
da34b4fd9a6523d374ce754cad272dddc769a1c1
/test.py
27c14a4ef9bf96f2e029a8a294c8fbf59bdf52bd
[]
no_license
shish/apache2rrd
82b3f595699961edf0f3e488b12242bca8f38676
7bbb66e18c06a0ae9a495617053be582953a8f1e
refs/heads/master
2020-04-06T06:21:17.203612
2014-08-26T14:01:17
2014-08-26T14:01:17
511,553
6
1
null
2014-08-26T13:03:50
2010-02-10T16:45:58
Python
UTF-8
Python
false
false
851
py
#!/usr/bin/env python import os import a2r import unittest class Test_A2R(unittest.TestCase): def tearDown(self): if os.path.exists("test.rrd"): os.unlink("test.rrd") def test_init(self): a = a2r.ApacheToRRD("test.rrd") self.assertEqual(a.gecko, 0) self.assertEqual(a.other, 0) self.assertEqual(a.bandwidth, 0) def test_parse_date(self): a = a2r.ApacheToRRD("test.rrd") self.assertEqual(a.parse_date("01/Jan/1970:00:00:00"), 0) # this works on my system, but if the above is returning -3600 # because timezones, then the number I chose here is wrong... #self.assertEqual(a.parse_date("21/Aug/2014:15:30:27"), 1408631427) class Test_Usage(unittest.TestCase): def test(self): # just check it doesn't crash a2r.usage()
[ "shish@shishnet.org" ]
shish@shishnet.org
b78a2ceae0b90656d776440a4214132a3ee9a7e2
b586cec578da0e1904d07468a7f49dacc0af5e99
/chapter_10/QASystem/util/utils.py
f07ff8da94b2fdbdfe7b5eabc1173bdf591fc19d
[ "MIT" ]
permissive
LifeOfGame/mongodb_redis
bf21b989eeb95eeb39f684363f9436677252a63e
834fbdd65d4ea9e1e0056b711781e5f27a40333b
refs/heads/master
2021-06-22T17:01:19.497132
2019-08-20T06:54:21
2019-08-20T06:54:21
203,295,895
0
0
MIT
2021-03-20T01:37:02
2019-08-20T03:53:06
Jupyter Notebook
UTF-8
Python
false
false
1,278
py
from bson import ObjectId def check_answer_valid(answer): author = answer.get('author', '') question_id = answer.get('question_id', '') answer = answer.get('answer', '') if not all([author, question_id, answer]): return {'success': False, 'reason': 'author/question_id/answer 三个参数不完整'} if not ObjectId.is_valid(question_id): return {'success': False, 'reason': 'question_id不合法!'} return {'success': True} def check_question_valid(question): author = question.get('author', '') title = question.get('title', '') if not all([author, title]): return {'success': False, 'reason': 'author/title/detail不能为空!'} return {'success': True} def check_vote(vote_data): value = vote_data.get('value', '') doc_type = vote_data.get('doc_type', '') object_id = vote_data.get('doc_id', '') if value not in ['vote_up', 'vote_down']: return {'success': False, 'reason': 'value只能说`vote_up`或者`vote_down`!'} if not doc_type: return {'success': False, 'reason': 'for需要填写`question`或者`answer`!'} if not ObjectId.is_valid(object_id): return {'success': False, 'reason': f'{doc_type}_id不合法!'} return {'success': True}
[ "greensouth@foxmail.com" ]
greensouth@foxmail.com
021a8ba558176ead7f8644458a9289bf9b5a284c
88849505c8d71c5fcc8d18fe2da3aa93a97f1e0e
/pages/003.py
a9816cc7d7e040683c9265092a73056e0ff58be1
[ "MIT" ]
permissive
mscroggs/KLBFAX
5322e025c41b30c6f160699e742c988c9e47ea88
3aaaa0cfe3b9772caa0a87e639efd9bce5b6adf4
refs/heads/master
2021-04-09T16:38:08.581934
2018-06-25T12:18:23
2018-06-25T12:18:26
31,314,664
5
1
null
2017-07-26T19:21:13
2015-02-25T13:26:38
Python
UTF-8
Python
false
false
630
py
from page import Page class LiPage(Page): def __init__(self): super(LiPage, self).__init__("003") self.in_index = False self.is_enabled = False self.title = "License" def generate_content(self): from random import randrange self.add_title("License",font="size4") from file_handler import load_file li = load_file("../LICENSE.txt") c = load_file("../contributors.txt").split("\n") while "" in c: c.remove("") li = li.replace("The KLBFAX contributors",", ".join(c)) self.add_wrapped_text(li) sub_page = LiPage()
[ "matthew.w.scroggs@gmail.com" ]
matthew.w.scroggs@gmail.com
93f17a0e7749edd09542c1cb17ae3f994e7e4689
c8e481e914a3bf455c3e1d85b6031f76d1ce0794
/tests/050_conf/002_base_backend/004_parse.py
9006e9028704c3ac33d1fa6ec21d6d0f4962aede
[ "MIT" ]
permissive
dansamara/boussole
c6db8c9e2964bf57d113cfcfb4441c08dcdf67f6
07bbca09190e568d288ed07773a47bf31dafa3ab
refs/heads/master
2021-09-24T01:26:48.840541
2018-10-01T00:33:05
2018-10-01T00:33:05
116,189,796
0
0
null
2018-01-03T22:50:11
2018-01-03T22:50:11
null
UTF-8
Python
false
false
464
py
# -*- coding: utf-8 -*- import os import pytest from boussole.conf.base_backend import SettingsBackendBase def test_ok_001(settings): """conf.base_backend.SettingsBackendBase: Dummy content parsing""" backend = SettingsBackendBase(basedir=settings.fixtures_path) path, filename = backend.parse_filepath() filepath = backend.check_filepath(path, filename) content = backend.open(filepath) assert backend.parse(filepath, content) == {}
[ "sveetch@gmail.com" ]
sveetch@gmail.com
ef889db2724a63e8aa459d671114d155862c3b02
5b810b5b59eb66e564b84d4627a81afb72bb769c
/app.py
23dae30029c1fe2fd3a11e2bdd23ddbc890fefe3
[]
no_license
wangyitao/microfilm
402d6c61aa8e4f41749829c96a742487c88d9f75
3cbee7b599483b117283359de9e7bec9d945ff53
refs/heads/master
2020-03-23T04:19:19.797404
2018-08-02T01:38:14
2018-08-02T01:38:14
141,076,259
0
0
null
null
null
null
UTF-8
Python
false
false
238
py
# -*- coding: utf-8 -*- # @Author : Felix Wang # @time : 2018/7/9 21:47 from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return 'ddd' if __name__ == '__main__': app.run()
[ "1403179190@qq.com" ]
1403179190@qq.com
60d899681bd0e175af2faf5d08a2cdf089eb2e2a
974d04d2ea27b1bba1c01015a98112d2afb78fe5
/python/paddle/text/datasets/imikolov.py
5aead1c2d9cf53d2fcb4c2e973a4d550140b7f56
[ "Apache-2.0" ]
permissive
PaddlePaddle/Paddle
b3d2583119082c8e4b74331dacc4d39ed4d7cff0
22a11a60e0e3d10a3cf610077a3d9942a6f964cb
refs/heads/develop
2023-08-17T21:27:30.568889
2023-08-17T12:38:22
2023-08-17T12:38:22
65,711,522
20,414
5,891
Apache-2.0
2023-09-14T19:20:51
2016-08-15T06:59:08
C++
UTF-8
Python
false
false
6,040
py
# Copyright (c) 2020 PaddlePaddle 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. import collections import tarfile import numpy as np from paddle.dataset.common import _check_exists_and_download from paddle.io import Dataset __all__ = [] URL = 'https://dataset.bj.bcebos.com/imikolov%2Fsimple-examples.tgz' MD5 = '30177ea32e27c525793142b6bf2c8e2d' class Imikolov(Dataset): """ Implementation of imikolov dataset. Args: data_file(str): path to data tar file, can be set None if :attr:`download` is True. Default None data_type(str): 'NGRAM' or 'SEQ'. Default 'NGRAM'. window_size(int): sliding window size for 'NGRAM' data. Default -1. mode(str): 'train' 'test' mode. Default 'train'. min_word_freq(int): minimal word frequence for building word dictionary. Default 50. download(bool): whether to download dataset automatically if :attr:`data_file` is not set. Default True Returns: Dataset: instance of imikolov dataset Examples: .. code-block:: python import paddle from paddle.text.datasets import Imikolov class SimpleNet(paddle.nn.Layer): def __init__(self): super().__init__() def forward(self, src, trg): return paddle.sum(src), paddle.sum(trg) imikolov = Imikolov(mode='train', data_type='SEQ', window_size=2) for i in range(10): src, trg = imikolov[i] src = paddle.to_tensor(src) trg = paddle.to_tensor(trg) model = SimpleNet() src, trg = model(src, trg) print(src.shape, trg.shape) """ def __init__( self, data_file=None, data_type='NGRAM', window_size=-1, mode='train', min_word_freq=50, download=True, ): assert data_type.upper() in [ 'NGRAM', 'SEQ', ], f"data type should be 'NGRAM', 'SEQ', but got {data_type}" self.data_type = data_type.upper() assert mode.lower() in [ 'train', 'test', ], f"mode should be 'train', 'test', but got {mode}" self.mode = mode.lower() self.window_size = window_size self.min_word_freq = min_word_freq self.data_file = data_file if self.data_file is None: assert ( download ), "data_file is not set and downloading automatically disabled" self.data_file = _check_exists_and_download( data_file, URL, MD5, 'imikolov', download ) # Build a word dictionary from the corpus self.word_idx = self._build_work_dict(min_word_freq) # read dataset into memory self._load_anno() def word_count(self, f, word_freq=None): if word_freq is None: word_freq = collections.defaultdict(int) for l in f: for w in l.strip().split(): word_freq[w] += 1 word_freq['<s>'] += 1 word_freq['<e>'] += 1 return word_freq def _build_work_dict(self, cutoff): train_filename = './simple-examples/data/ptb.train.txt' test_filename = './simple-examples/data/ptb.valid.txt' with tarfile.open(self.data_file) as tf: trainf = tf.extractfile(train_filename) testf = tf.extractfile(test_filename) word_freq = self.word_count(testf, self.word_count(trainf)) if '<unk>' in word_freq: # remove <unk> for now, since we will set it as last index del word_freq['<unk>'] word_freq = [ x for x in word_freq.items() if x[1] > self.min_word_freq ] word_freq_sorted = sorted(word_freq, key=lambda x: (-x[1], x[0])) words, _ = list(zip(*word_freq_sorted)) word_idx = dict(list(zip(words, range(len(words))))) word_idx['<unk>'] = len(words) return word_idx def _load_anno(self): self.data = [] with tarfile.open(self.data_file) as tf: filename = f'./simple-examples/data/ptb.{self.mode}.txt' f = tf.extractfile(filename) UNK = self.word_idx['<unk>'] for l in f: if self.data_type == 'NGRAM': assert self.window_size > -1, 'Invalid gram length' l = ['<s>'] + l.strip().split() + ['<e>'] if len(l) >= self.window_size: l = [self.word_idx.get(w, UNK) for w in l] for i in range(self.window_size, len(l) + 1): self.data.append(tuple(l[i - self.window_size : i])) elif self.data_type == 'SEQ': l = l.strip().split() l = [self.word_idx.get(w, UNK) for w in l] src_seq = [self.word_idx['<s>']] + l trg_seq = l + [self.word_idx['<e>']] if self.window_size > 0 and len(src_seq) > self.window_size: continue self.data.append((src_seq, trg_seq)) else: raise AssertionError('Unknow data type') def __getitem__(self, idx): return tuple([np.array(d) for d in self.data[idx]]) def __len__(self): return len(self.data)
[ "noreply@github.com" ]
PaddlePaddle.noreply@github.com
0627c37670137bb356e5ac3476c7fbff81aaa893
bd4812ba7af196d2e866cbf2935b2e7308d95066
/python/leetcode/027_remove_element.py
69bc6bb96bf324dd9fcb29c92e93359aefcc38d6
[ "Apache-2.0" ]
permissive
yxun/notebook
f507201e15c4376f0655121724254c0d5275c3b1
00eb1953d872a9a93a13d7cf23d8e4ed641d1ce7
refs/heads/master
2023-09-01T03:50:48.142295
2023-08-17T12:11:25
2023-08-17T12:11:25
207,569,654
2
2
Apache-2.0
2023-08-17T12:11:26
2019-09-10T13:38:49
Java
UTF-8
Python
false
false
654
py
#%% """ - Remove Element - https://leetcode.com/problems/remove-element/ - Easy Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. """ #%% class S: def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ while val in nums: nums.remove(val) return len(nums) #%%
[ "yuanlin.yxu@gmail.com" ]
yuanlin.yxu@gmail.com
503a6990773f84900941ddfa619be90e6d517e93
60cfb6a5effedfd65b804f09b68b446a2bb6f8a6
/Q6_SortStack.py
6f91cae14eb9e382c4dbbe3e874a1622e00ab098
[]
no_license
rjayswal-pythonista/DSA_Python
c85d7d8527dab169d58afec1103e78875705f27f
5ab169dac5f46d5cce2938cdba180f0f2133ac63
refs/heads/master
2023-07-05T12:50:31.973648
2021-08-07T18:51:04
2021-08-07T18:51:04
389,362,148
1
0
null
null
null
null
UTF-8
Python
false
false
1,878
py
# Created by Roshan Jayswal on 02/06/2020. # Copyright © 2021. All rights reserved. # Sort a stack with the smallest on top using only a single temporary stack. def sort_stack(stack): previous = stack.pop() current = stack.pop() temp = Stack() while current: if previous < current: temp.push(previous) previous = current current = stack.pop() else: temp.push(current) current = stack.pop() if current == None and previous: temp.push(previous) sorted = True previous = temp.pop() current = temp.pop() while current: if previous > current: stack.push(previous) previous = current current = temp.pop() else: stack.push(current) current = temp.pop() sorted = False if current == None and previous: stack.push(previous) if sorted: return stack else: return sort_stack(stack) class Stack(): def __init__(self): self.top = None def __str__(self): return str(self.top) def push(self, item): self.top = current(item, self.top) def pop(self): if not self.top: return None item = self.top self.top = self.top.next return item.data class current(): def __init__(self, data=None, next=None): self.data, self.next = data, next def __str__(self): return str(self and self.data) + ',' + str(self and self.next) import unittest class Test(unittest.TestCase): def test_sort_stack(self): self.assertEqual(str(sort_stack(Stack())), "None") stack = Stack() stack.push(10) stack.push(30) stack.push(70) stack.push(40) stack.push(80) stack.push(20) stack.push(90) stack.push(50) stack.push(60) self.assertEqual(str(stack), "60,50,90,20,80,40,70,30,10,None") self.assertEqual(str(sort_stack(stack)), "10,20,30,40,50,60,70,80,90,None") unittest.main()
[ "roshanjayswal15@cisco.com" ]
roshanjayswal15@cisco.com
99cee0d58499bc4397e829cec7dc424326750fc7
f4b60f5e49baf60976987946c20a8ebca4880602
/lib64/python2.7/site-packages/acimodel-1.3_2j-py2.7.egg/cobra/modelimpl/vns/absfunccfg.py
d2d4bcf6c3e4c4109778afdcd0b0da20219872d8
[]
no_license
cqbomb/qytang_aci
12e508d54d9f774b537c33563762e694783d6ba8
a7fab9d6cda7fadcc995672e55c0ef7e7187696e
refs/heads/master
2022-12-21T13:30:05.240231
2018-12-04T01:46:53
2018-12-04T01:46:53
159,911,666
0
0
null
2022-12-07T23:53:02
2018-12-01T05:17:50
Python
UTF-8
Python
false
false
7,972
py
# coding=UTF-8 # ********************************************************************** # Copyright (c) 2013-2016 Cisco Systems, Inc. All rights reserved # written by zen warriors, do not modify! # ********************************************************************** from cobra.mit.meta import ClassMeta from cobra.mit.meta import StatsClassMeta from cobra.mit.meta import CounterMeta from cobra.mit.meta import PropMeta from cobra.mit.meta import Category from cobra.mit.meta import SourceRelationMeta from cobra.mit.meta import NamedSourceRelationMeta from cobra.mit.meta import TargetRelationMeta from cobra.mit.meta import DeploymentPathMeta, DeploymentCategory from cobra.model.category import MoCategory, PropCategory, CounterCategory from cobra.mit.mo import Mo # ################################################## class AbsFuncCfg(Mo): """ The configuration for a function. This configuration can be shared across multiple functions. """ meta = ClassMeta("cobra.model.vns.AbsFuncCfg") meta.moClassName = "vnsAbsFuncCfg" meta.rnFormat = "absFuncCfg" meta.category = MoCategory.REGULAR meta.label = "L4-L7 Services Function Config" meta.writeAccessMask = 0x2000000000000001 meta.readAccessMask = 0x6000000000000001 meta.isDomainable = False meta.isReadOnly = False meta.isConfigurable = True meta.isDeletable = True meta.isContextRoot = False meta.childClasses.add("cobra.model.fault.Counts") meta.childClasses.add("cobra.model.health.Inst") meta.childClasses.add("cobra.model.vns.AbsFolder") meta.childClasses.add("cobra.model.vns.GFolder") meta.childClasses.add("cobra.model.vns.AbsParam") meta.childClasses.add("cobra.model.vns.CFolder") meta.childClasses.add("cobra.model.vns.GRel") meta.childClasses.add("cobra.model.vns.CRel") meta.childClasses.add("cobra.model.vns.CfgRelInst") meta.childClasses.add("cobra.model.vns.AbsCfgRel") meta.childClasses.add("cobra.model.vns.ParamInst") meta.childClasses.add("cobra.model.vns.CParam") meta.childClasses.add("cobra.model.vns.FolderInst") meta.childClasses.add("cobra.model.vns.GParam") meta.childClasses.add("cobra.model.fault.Delegate") meta.childNamesAndRnPrefix.append(("cobra.model.vns.CfgRelInst", "CfgRelInst-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.AbsFolder", "absFolder-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.ParamInst", "ParamInst-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.AbsParam", "absParam-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.GFolder", "gFolder-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.CFolder", "cFolder-")) meta.childNamesAndRnPrefix.append(("cobra.model.fault.Counts", "fltCnts")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.AbsCfgRel", "absRel-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.CParam", "cParam-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.GParam", "gParam-")) meta.childNamesAndRnPrefix.append(("cobra.model.health.Inst", "health")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.GRel", "gRel-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.CRel", "cRel-")) meta.childNamesAndRnPrefix.append(("cobra.model.vns.FolderInst", "FI_C-")) meta.childNamesAndRnPrefix.append(("cobra.model.fault.Delegate", "fd-")) meta.parentClasses.add("cobra.model.vns.AbsFuncProf") meta.parentClasses.add("cobra.model.vns.AbsNode") meta.superClasses.add("cobra.model.naming.NamedObject") meta.superClasses.add("cobra.model.pol.Obj") meta.superClasses.add("cobra.model.pol.Def") meta.rnPrefixes = [ ('absFuncCfg', False), ] prop = PropMeta("str", "childAction", "childAction", 4, PropCategory.CHILD_ACTION) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("deleteAll", "deleteall", 16384) prop._addConstant("deleteNonPresent", "deletenonpresent", 8192) prop._addConstant("ignore", "ignore", 4096) meta.props.add("childAction", prop) prop = PropMeta("str", "descr", "descr", 5579, PropCategory.REGULAR) prop.label = "Description" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 128)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("descr", prop) prop = PropMeta("str", "dn", "dn", 1, PropCategory.DN) prop.label = "None" prop.isDn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("dn", prop) prop = PropMeta("str", "lcOwn", "lcOwn", 9, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "local" prop._addConstant("implicit", "implicit", 4) prop._addConstant("local", "local", 0) prop._addConstant("policy", "policy", 1) prop._addConstant("replica", "replica", 2) prop._addConstant("resolveOnBehalf", "resolvedonbehalf", 3) meta.props.add("lcOwn", prop) prop = PropMeta("str", "modTs", "modTs", 7, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop.defaultValue = 0 prop.defaultValueStr = "never" prop._addConstant("never", "never", 0) meta.props.add("modTs", prop) prop = PropMeta("str", "monPolDn", "monPolDn", 14812, PropCategory.REGULAR) prop.label = "Monitoring policy attached to this observable object" prop.isImplicit = True prop.isAdmin = True meta.props.add("monPolDn", prop) prop = PropMeta("str", "name", "name", 4991, PropCategory.REGULAR) prop.label = "Name" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 64)] prop.regex = ['[a-zA-Z0-9_.:-]+'] meta.props.add("name", prop) prop = PropMeta("str", "ownerKey", "ownerKey", 15230, PropCategory.REGULAR) prop.label = "None" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 128)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("ownerKey", prop) prop = PropMeta("str", "ownerTag", "ownerTag", 15231, PropCategory.REGULAR) prop.label = "None" prop.isConfig = True prop.isAdmin = True prop.range = [(0, 64)] prop.regex = ['[a-zA-Z0-9\\!#$%()*,-./:;@ _{|}~?&+]+'] meta.props.add("ownerTag", prop) prop = PropMeta("str", "rn", "rn", 2, PropCategory.RN) prop.label = "None" prop.isRn = True prop.isImplicit = True prop.isAdmin = True prop.isCreateOnly = True meta.props.add("rn", prop) prop = PropMeta("str", "status", "status", 3, PropCategory.STATUS) prop.label = "None" prop.isImplicit = True prop.isAdmin = True prop._addConstant("created", "created", 2) prop._addConstant("deleted", "deleted", 8) prop._addConstant("modified", "modified", 4) meta.props.add("status", prop) prop = PropMeta("str", "uid", "uid", 8, PropCategory.REGULAR) prop.label = "None" prop.isImplicit = True prop.isAdmin = True meta.props.add("uid", prop) # Deployment Meta meta.deploymentQuery = True meta.deploymentType = "Ancestor" meta.deploymentQueryPaths.append(DeploymentPathMeta("AbsFuncProfContrToNwIf", "Physical Interfaces", "cobra.model.nw.If")) meta.deploymentQueryPaths.append(DeploymentPathMeta("AbsNodeToNwIf", "Physical Interfaces", "cobra.model.nw.If")) meta.deploymentQueryPaths.append(DeploymentPathMeta("AbsFuncProfContrToCompVNic", "Virtual Nics", "cobra.model.comp.VNic")) meta.deploymentQueryPaths.append(DeploymentPathMeta("AbsNodeToCompVNic", "Virtual Nics", "cobra.model.comp.VNic")) def __init__(self, parentMoOrDn, markDirty=True, **creationProps): namingVals = [] Mo.__init__(self, parentMoOrDn, markDirty, *namingVals, **creationProps) # End of package file # ##################################################
[ "collinsctk@qytang.com" ]
collinsctk@qytang.com
b4ce141db0565838c5eb91fd85bdfe5c95d8426b
e05215ef0f9c4ec8b964ac4e3b8f9ac7da72f062
/0x0F-python-object_relational_mapping/11-model_state_insert.py
2cf00633d96831dde34c11fa7b2ffe4e3110649c
[]
no_license
BrianFs04/holbertonschool-higher_level_programming
2fcb639b354e12a82e205a4c0beaaf29b18cec9d
9d0ebf054b26707a1ba8f21a3a8f307e906ca8df
refs/heads/master
2020-09-29T01:43:30.361544
2020-08-30T22:38:09
2020-08-30T22:38:09
226,911,398
0
0
null
null
null
null
UTF-8
Python
false
false
668
py
#!/usr/bin/python3 ''' Script that adds the State object “Louisiana” to the database hbtn_0e_6_usa via SQLAlchemy ''' import sys from sqlalchemy import (create_engine) from model_state import Base, State from sqlalchemy.orm import sessionmaker if __name__ == '__main__': engine = create_engine('mysql+mysqldb://{}:{}@localhost:3306/{}'. format(sys.argv[1], sys.argv[2], sys.argv[3]), pool_pre_ping=True) Session = sessionmaker() Session.configure(bind=engine) session = Session() newState = State(name='Louisiana') session.add(newState) session.commit() print(newState.id)
[ "brayanflorezsanabria@gmail.com" ]
brayanflorezsanabria@gmail.com
13dc161a7fcd0c32cd486eb437f78c8ea981ef80
f5159d881896475375c9218f9d06b5324975d106
/Day-6_Majority_Element.py
c5a17c8ea30dc612b4895e9b45fda863ff44e121
[]
no_license
Gangadharbhuvan/31-Day-Leetcode-May-Challenge
93327cc749cd77a7579c4ab7f2a1826e59b1c14b
95be5ece107f1181c261d88ccb344c7c8f6f7a83
refs/heads/master
2022-09-21T23:27:21.855715
2020-05-31T14:49:04
2020-05-31T14:49:04
260,307,749
1
0
null
null
null
null
UTF-8
Python
false
false
670
py
''' Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,1,2,2] Output: 2 ''' class Solution: def majorityElement(self, nums: List[int]) -> int: d=dict() for num in nums: if(num in d): d[num]+=1 else: d[num]=1 n=len(nums) for key,value in d.items(): if(value> n//2): return (key)
[ "noreply@github.com" ]
Gangadharbhuvan.noreply@github.com
214bd7d718d94b5188dc860bd4ea65f717cdeb15
3fc00c49c6b5a5d3edb4f5a97a86ecc8f59a3035
/grais/migrations/0005_auto_20210324_0829.py
d4c1c9e2118f96de3869e6510ed5d2ee5c692748
[]
no_license
yc-hu/dm_apps
9e640ef08da8ecefcd7008ee2d4f8f268ec9062e
483f855b19876fd60c0017a270df74e076aa0d8b
refs/heads/master
2023-04-07T13:13:55.999058
2021-04-12T10:19:21
2021-04-12T10:19:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
368
py
# Generated by Django 3.1.6 on 2021-03-24 11:29 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('grais', '0004_auto_20210324_0805'), ] operations = [ migrations.RenameField( model_name='station', old_name='latitude_n', new_name='latitude', ), ]
[ "davjfish@gmail.com" ]
davjfish@gmail.com
c8a5c08cc8be510b83622461e4e9bfc27681fbae
3032448a477f6f89716d3cb6fd47bc79211ae820
/mowdie/updates/migrations/0005_update_favorited_users.py
88996fbc5b4c72eb5dfd70d7876f11f887122b90
[]
no_license
Callus4815/mowdie
663e035dcc1b51c5c21deb7c43006c81008ac43d
5650d422c33a50d58c7bbac5be77db2e8001fd83
refs/heads/master
2020-12-14T08:56:05.599949
2015-06-17T19:25:32
2015-06-17T19:25:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
591
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('updates', '0004_auto_20150611_0319'), ] operations = [ migrations.AddField( model_name='update', name='favorited_users', field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, related_name='favorited_updates', through='updates.Favorite'), ), ]
[ "clinton@dreisbach.us" ]
clinton@dreisbach.us
5f7d3420dc72f9d24ee5077434ba2b43b24f1c9f
ebbfdb7cc1cd33e195ccc830c2ff87bdce2c024e
/simple-social-network/chat/migrations/0001_initial.py
a68615dd6ae099d8ed9c9b3c74873e785e2310e3
[]
no_license
bateternal/simple-social-network
a399be4fcf48ce495d3f2004130ffc88723d2d4c
8f888580493c31c44113825d5eb82349cf977c20
refs/heads/master
2023-04-06T09:32:45.529327
2022-06-06T09:37:46
2022-06-06T09:37:46
231,631,113
1
0
null
2023-03-31T14:38:36
2020-01-03T17:08:34
Python
UTF-8
Python
false
false
4,764
py
# Generated by Django 3.2.5 on 2021-10-24 15:30 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserInformations', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('firstname', models.CharField(max_length=50)), ('lastname', models.CharField(max_length=50)), ('username', models.CharField(db_index=True, max_length=20, unique=True)), ('email', models.CharField(max_length=40, unique=True)), ('profile_picture', models.CharField(max_length=100, null=True)), ('bio', models.CharField(default='', max_length=200)), ('verified', models.BooleanField(default=False)), ('owner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='owner', to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'user_information', }, ), migrations.CreateModel( name='Posts', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=20)), ('content', models.TextField(null=True)), ('file', models.CharField(max_length=100, null=True)), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='postsowner', to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'post', }, ), migrations.CreateModel( name='Messages', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('create', models.DateTimeField(auto_now_add=True)), ('timestamp', models.CharField(max_length=20)), ('text', models.TextField(null=True)), ('date', models.CharField(max_length=20, null=True)), ('seeing', models.BooleanField(default=False)), ('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sender', to=settings.AUTH_USER_MODEL)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='target', to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'message', }, ), migrations.CreateModel( name='Conversations', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('text', models.TextField(null=True)), ('date', models.CharField(max_length=20, null=True)), ('create_date', models.DateTimeField(auto_now_add=True)), ('seeing', models.BooleanField(default=False)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='targetchat', to=settings.AUTH_USER_MODEL)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='userowner', to=settings.AUTH_USER_MODEL)), ], options={ 'db_table': 'conversation', }, ), migrations.CreateModel( name='ConfirmToken', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('token', models.CharField(db_index=True, max_length=100, unique=True)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user', to='chat.userinformations')), ], options={ 'db_table': 'confirm_token', }, ), migrations.AddIndex( model_name='messages', index=models.Index(fields=['sender', 'target', 'timestamp'], name='message_sender__c8cdda_idx'), ), migrations.AddIndex( model_name='conversations', index=models.Index(fields=['user', 'target', 'create'], name='conversatio_user_id_0a86c9_idx'), ), migrations.AlterUniqueTogether( name='conversations', unique_together={('user', 'target')}, ), ]
[ "bateternali@gmail.com" ]
bateternali@gmail.com
71c1136a6ab54949103064970f3cc6705338ff20
5ff7fa0fe26f8d5f4dcc53dc3f2f423046d07aaf
/theme_left_side_menu_bottom/theme_left_side_menu_bottom.py
b5eb1d70eb0eab27988982aa0b8694e441e8e06c
[]
no_license
cikupamart/odoo-theme-vertel
8eb17cb0bbe6eff9677aae3c345ca8b3db59ad05
fde27670894c7701b58712f35752570a809732f7
refs/heads/master
2023-05-30T21:32:52.079706
2018-12-17T09:56:42
2018-12-17T09:56:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,778
py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution, third party addon # Copyright (C) 2004-2015 Vertel AB (<http://vertel.se>). # # 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 <http://www.gnu.org/licenses/>. # ############################################################################## from openerp import models, fields, api, _ from openerp import http from openerp.http import request from datetime import datetime from lxml import html import werkzeug class website(models.Model): _inherit = 'website' def get_news(self, text, length=0): if text: result_text = ' '.join(html.fromstring(text).text_content().split()) if 0 < length < len(result_text): return result_text[:length] return result_text return '' def get_season(self): if datetime.today().month in [3, 4, 5]: return 'spring' if datetime.today().month in [6, 7, 8]: return 'summer' if datetime.today().month in [9, 10, 11]: return 'autumn' if datetime.today().month in [1, 2, 12]: return 'winter' return '' class LeftSideMenuBottom(http.Controller): @http.route(['/logo500.png'], type='http', auth="public", cors="*") def company_logo500(self): user = request.registry['res.users'].browse(request.cr, request.uid, request.uid) response = werkzeug.wrappers.Response() return request.registry['website']._image(request.cr, request.uid, 'res.company', user.company_id.id, 'logo', response, max_width=500, max_height=None, ) @http.route(['/logo1024.png'], type='http', auth="public", cors="*") def company_logo1024(self): user = request.registry['res.users'].browse(request.cr, request.uid, request.uid) response = werkzeug.wrappers.Response() return request.registry['website']._image(request.cr, request.uid, 'res.company', user.company_id.id, 'logo', response, max_width=1024, max_height=None, )
[ "apollo_zhj@msn.com" ]
apollo_zhj@msn.com
6bd4db8f055f1d127a9660863738b466df1a8216
b9f79352353f2445c54a5e55def2058513b2c43d
/python/read_seis.py
d0b26298e7442acee5add5006aa09b56a04a4823
[]
no_license
ganlubbq/Compressed-Sensing-Delay-Estimation
07d1ebbc6079ff5f9867521ffbf87b6af66ab899
db4fe86d551efcaf59deb9c1a15c36ea225a5f71
refs/heads/master
2021-06-19T03:39:11.611976
2017-07-06T08:38:40
2017-07-06T08:38:40
110,315,515
1
0
null
2017-11-11T03:40:25
2017-11-11T03:40:25
null
UTF-8
Python
false
false
1,866
py
import array from ctypes import * CSIZE = 1800000 FTSIZE = 1048576 class SEIS_HEADER(Structure): """ struct seis_header { int nt; int id; int rline; /* receiver line # */ int rpt; /* index on receiver line */ char name[8]; double x, y, z; double t0; double dt; }; """ _fields_ = [('nt', c_int), ('id', c_int), ('rline', c_int), ('rpt', c_int), ('name', c_char * 8), ('x', c_double), ('y', c_double), ('z', c_double), ('t0', c_double), ('dt', c_double)] class SEIS_DATA(Structure): _fields_ = [('data', c_float * CSIZE)] def seis_reader(file_path): with open(file_path, 'rb') as file: # Init the data structures header_struct = SEIS_HEADER() data_struct = SEIS_DATA() # Read the seis header file.readinto(header_struct) header = [header_struct.nt, header_struct.id, \ header_struct.rline, header_struct.rpt, header_struct.name, \ header_struct.x, header_struct.y, header_struct.z, \ header_struct.t0, header_struct.dt] # Read the seis data if header_struct.nt < CSIZE: # break exit(0) file.readinto(data_struct) data = data_struct.data # Another way for extracting seis data # data = array.array('f', file.read()) return header, data if __name__ == '__main__': import sys # Exp. '/Users/woodie/Desktop/Georgia-Tech-ISyE-Intern/xcorr_hongao/data/4001-0000/20140801000000.4001-0000.seis' file_path = sys.argv[1] header, data = seis_reader(file_path) # print '\t'.join(map(str, header)) print '\n'.join(map(str, data))
[ "woodielove@163.com" ]
woodielove@163.com
20cbd2d350769fcb76a391136b859b317ddf5056
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_omnivore.py
cc5ddfea19e0284252fbde14485df2059cf5ad5a
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
344
py
#calss header class _OMNIVORE(): def __init__(self,): self.name = "OMNIVORE" self.definitions = [u'an animal that is naturally able to eat both plants and meat'] self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.specie = 'nouns' def run(self, obj1 = [], obj2 = []): return self.jsondata
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
f611798c3579ff98814760ba37e7aca00e3d0016
a8d68074db5c2b2697650ed0281979d3e00cf5a8
/Nyspider/dianping/memberlist.py
3aafd55eb50320b3a9501d67f401ba5c404872db
[]
no_license
15807857476/bogdata-2
9595609ea2ae5ae0a48c511f911df2498456467e
1934cdfa234b77ca91e349b84688db113ff39e8c
refs/heads/master
2023-05-26T19:10:18.439269
2019-05-24T02:50:41
2019-05-24T02:50:41
188,327,526
3
1
null
2023-05-22T21:37:27
2019-05-24T00:53:28
Python
UTF-8
Python
false
false
8,186
py
import requests from bs4 import BeautifulSoup import time from proxy import * import datetime import openpyxl headers = { 'Host':'www.dianping.com', 'User-Agent':"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0", 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive'} def get_memberlist(): page=1 while True: url='http://www.dianping.com/memberlist/4/10?pg='+str(page) html=requests.get(url,headers=headers).text table=BeautifulSoup(html,'lxml').find('table',{'class':'rankTable'}).find('tbody').find_all('tr') f=open('memberlist.txt','a') for item in table: try: tds=item.find_all('td') name=tds[0].find('a').get_text() url=tds[0].find('a').get('href') comment_num=tds[1].get_text() reply_num=tds[3].get_text() flower_num=tds[4].get_text() f.write(str([name,url,comment_num,reply_num,flower_num])+'\n') except: continue f.close() page+=1 if page==7: break def get_comments(usrid): baseurl='http://www.dianping.com/member/{}/reviews?pg={}&reviewCityId=0&reviewShopType=10&c=0&shopTypeIndex=1' page=1 html=requests.get(baseurl.format(usrid,page),headers=headers,proxies=get_proxies()).text soup=BeautifulSoup(html,'lxml').find('div',{'class':'main'}) citys=soup.find('div',{'class':'p-term-list'}).find_all('li')[1].find_all('span') city_num=len(citys) city_text='' for span in citys: city_text+=span.get_text()+'\t' table=soup.find('div',id='J_review').find_all('div',{'class':'J_rptlist'}) result=[] for item in table: title=item.find('a').get_text() url=item.find('a').get('href') try: address=item.find('div',{'class':'addres'}).get_text() except: address='' try: star=item.find('div',{'class':'comm-rst'}).find('span').get('class')[1].replace('irr-star','') except: star='' content=item.find('div',{'class':'comm-entry'}).get_text() date=item.find('div',{'class':"info"}).find('span').get_text().replace("发表于",'') line=[city_num,city_text,title,url,address,star,content,date] result.append(line) page+=1 while True: print(page) html=requests.get(baseurl.format(usrid,page),headers=headers,proxies=get_proxies()).text soup=BeautifulSoup(html,'lxml').find('div',{'class':'main'}) table=soup.find('div',id='J_review').find_all('div',{'class':'J_rptlist'}) for item in table: title=item.find('a').get_text() url=item.find('a').get('href') try: address=item.find('div',{'class':'addres'}).get_text() except: address='' try: star=item.find('div',{'class':'comm-rst'}).find('span').get('class')[1].replace('irr-star','') except: star='' content=item.find('div',{'class':'comm-entry'}).get_text() date=item.find('div',{'class':"info"}).find('span').get_text().replace("发表于",'') line=[city_num,city_text,title,url,address,star,content,date] result.append(line) if len(result)==100: return result page+=1 return result def shop_infor(shopurl): while True: try: html=requests.get(shopurl,headers=headers,proxies=get_proxies(),timeout=30).text if '您使用的IP访问网站过于频繁,为了您的正常访问,请先输入验证码' in html: switch_ip() continue break except: switch_ip() continue soup=BeautifulSoup(html,'lxml').find('div',{'class':'body-content'}) try: types=soup.find('div',{'class':'breadcrumb'}).find_all('a') shop_type=types[2].get_text() except: shop_type='' base_infor=soup.find('div',id='basic-info').find('div',{'class':'brief-info'}) try: star=base_infor.find('span',{'class':'mid-rank-stars'}).get('class')[1].replace('mid-str','') except: star='' line=['']*4 for item in base_infor.find_all('span'): if '人均' in str(item): text=item.get_text() line[0]=text if '口味' in str(item): text=item.get_text() line[1]=text if '环境' in str(item): text=item.get_text() line[2]=text if '服务' in str(item): text=item.get_text() line[3]=text return [shop_type,star]+line def get_fans(usrid): url='http://www.dianping.com/member/{}/fans?pg={}' page=1 fans=[] while True: try: html=requests.get(url.format(usrid,page),headers=headers,timeout=30,proxies=get_proxies()).text if '您使用的IP访问网站过于频繁,为了您的正常访问,请先输入验证码' in html: switch_ip() continue except: continue try: table=BeautifulSoup(html,'lxml').find('div',{'class':'main'}).find('div',{'class':'pic-txt'}).find_all("li") except: break for item in table: try: name=item.find('h6').get_text() fans.append(name) except: continue page+=1 print(usrid,page) return [len(fans),fans] def get_week_day(date_str): date=datetime.datetime.strptime(date_str,'%Y-%m-%d') week_day_dict={ 0 : '星期一', 1 : '星期二', 2 : '星期三', 3 : '星期四', 4 : '星期五', 5 : '星期六', 6 : '星期天', } day = date.weekday() return week_day_dict[day] def main(): ''' usrs=[eval(line) for line in open('./memberlist.txt','r')] for usr in usrs: usrid=usr[1].split('/')[-1] try: result=get_comments(usrid) except: failed=open('failed.txt','a') failed.write(str(usr)+'\n') failed.close() print(usr,'failed') continue f=open('comments.txt','a') for item in result: f.write(str(usr+item)+'\n') f.close() switch_ip() print(usr,'ok') for line in open('./shop_failed.txt','r'): item=eval(line) date_str='20'+item[-1] try: weekday=get_week_day(date_str) except: weekday='' try: shopinfor=shop_infor(item[8]) except: failed=open('failed.txt','a') failed.write(str(item)+'\n') failed.close() continue f=open('shops.txt','a') f.write(str(item+[weekday]+shopinfor)+'\n') f.close() print(item[0],'ok') ''' users={} for line in open('./shops.txt','r'): item=eval(line) usrid=item[1].split('/')[-1] try: length=users[usrid] except: result=get_fans(usrid) length=result[0] users[usrid]=length f=open('fans.txt','a') f.write(str([item[0]]+result[1])+'\n') f.close() f=open('result.txt','a') f.write(str(item+[length])+'\n') f.close() print(item[0],'ok') def write_to_excel(): excel=openpyxl.Workbook(write_only=True) sheet=excel.create_sheet() for line in open('result.txt','r'): item=eval(line) try: item[10]=int(item[10])/10 except: pass try: item[-6]=int(item[-6])/10 except: pass sheet.append(item) sheet=excel.create_sheet() for line in open('fans.txt','r'): item=eval(line) sheet.append(item) excel.save('result.xlsx') write_to_excel()
[ "2397955090@qq.com" ]
2397955090@qq.com
2a431ab76c91f331c775d63f85dc46ca25b64bae
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03401/s135565011.py
7af11a4492d262bd746c0ac261ce6fc9e68553bf
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
526
py
n = int(input()) s = list(map(int,input().split())) ans = 0 tmp = 0 for i in range(n): ans += abs(s[i] - tmp) tmp = s[i] ans += abs(tmp) s.insert(0,0) s.insert(n+1,0) for i in range(1,n+1):#とばす番号 tmp_ans = ans a = s[i-1] tmp = s[i] b = s[i+1] if (b >= tmp and tmp >= a) or (b <= tmp and tmp <= a): pass else: if (a >= b and tmp > a) or (a <= b and tmp < a): tmp_ans -= abs(2*(tmp-a)) else: tmp_ans -= abs(2*(tmp-b)) print(tmp_ans)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
55b8c9bb105cf92e5f7fba91742cec07dc7f102c
400b0cb1f25cc2fbe80a3037c06102f40c4d2d89
/number59.py
9e5990a700479ac7e3765a971bd68b65742a6585
[]
no_license
Prithamprince/Python-programming
4c747d306829de552e3b0c6af67cfe534a2dc2e1
79a0953084a01978e75d2be4db0d35ba1cf29259
refs/heads/master
2020-05-30T06:29:26.134906
2019-12-13T06:33:49
2019-12-13T06:33:49
189,580,341
0
4
null
null
null
null
UTF-8
Python
false
false
141
py
l=input() l=l.split(" ") n=l[0] k=l[1] m=input() m=m.split() for i in m: if(i==k): a=m.index(i) b=a+1 print(b)
[ "noreply@github.com" ]
Prithamprince.noreply@github.com
58728fcd6507f4d087c5f3194611b685872a2621
71e3c041cb4911df0fd9f4444d8e07fb4e17d38c
/agent/DQN_agent.py
bcd98445f17bb6e6dbe4fab6202d0190fd882b61
[ "Apache-2.0" ]
permissive
w1368027790/DeepRL
8e713da32e2465f20a4966cf7d7aeb69f35aa074
51f125c01eb013b77ebf3a78795ae87dc9ffb9f9
refs/heads/master
2021-07-08T06:23:41.095226
2017-10-08T03:23:02
2017-10-08T03:23:02
106,264,458
1
0
null
2017-10-09T09:38:19
2017-10-09T09:38:19
null
UTF-8
Python
false
false
5,989
py
####################################################################### # Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) # # Permission given to modify the code as long as you keep this # # declaration at the top # ####################################################################### from network import * from component import * from utils import * import numpy as np import time import os import pickle import torch class DQNAgent: def __init__(self, config): self.config = config self.learning_network = config.network_fn(config.optimizer_fn) self.target_network = config.network_fn(config.optimizer_fn) self.target_network.load_state_dict(self.learning_network.state_dict()) self.task = config.task_fn() self.replay = config.replay_fn() self.policy = config.policy_fn() self.total_steps = 0 self.history_buffer = None def episode(self, deterministic=False): episode_start_time = time.time() state = self.task.reset() if self.history_buffer is None: self.history_buffer = [np.zeros_like(state)] * self.config.history_length else: self.history_buffer.pop(0) self.history_buffer.append(state) state = np.vstack(self.history_buffer) total_reward = 0.0 steps = 0 while True: value = self.learning_network.predict(np.stack([self.task.normalize_state(state)]), False) value = value.cpu().data.numpy().flatten() if deterministic: action = np.argmax(value) elif self.total_steps < self.config.exploration_steps: action = np.random.randint(0, len(value)) else: action = self.policy.sample(value) next_state, reward, done, info = self.task.step(action) done = (done or (self.config.max_episode_length and steps > self.config.max_episode_length)) self.history_buffer.pop(0) self.history_buffer.append(next_state) next_state = np.vstack(self.history_buffer) if not deterministic: self.replay.feed([state, action, reward, next_state, int(done)]) self.total_steps += 1 total_reward += np.sum(reward * self.config.reward_weight) steps += 1 state = next_state if done: break if not deterministic and self.total_steps > self.config.exploration_steps: experiences = self.replay.sample() states, actions, rewards, next_states, terminals = experiences states = self.task.normalize_state(states) next_states = self.task.normalize_state(next_states) if self.config.hybrid_reward: q_next = self.target_network.predict(next_states, True) target = [] for q_next_ in q_next: if self.config.target_type == self.config.q_target: target.append(q_next_.detach().max(1)[0]) elif self.config.target_type == self.config.expected_sarsa_target: target.append(q_next_.detach().mean(1)) target = torch.cat(target, dim=1).detach() terminals = self.learning_network.to_torch_variable(terminals).unsqueeze(1) rewards = self.learning_network.to_torch_variable(rewards) target = self.config.discount * target * (1 - terminals.expand_as(target)) target.add_(rewards) q = self.learning_network.predict(states, True) q_action = [] actions = self.learning_network.to_torch_variable(actions, 'int64').unsqueeze(1) for q_ in q: q_action.append(q_.gather(1, actions)) q_action = torch.cat(q_action, dim=1) loss = self.learning_network.criterion(q_action, target) else: q_next = self.target_network.predict(next_states, False).detach() if self.config.double_q: _, best_actions = self.learning_network.predict(next_states).detach().max(1) q_next = q_next.gather(1, best_actions) else: q_next, _ = q_next.max(1) terminals = self.learning_network.to_torch_variable(terminals).unsqueeze(1) rewards = self.learning_network.to_torch_variable(rewards).unsqueeze(1) q_next = self.config.discount * q_next * (1 - terminals) q_next.add_(rewards) actions = self.learning_network.to_torch_variable(actions, 'int64').unsqueeze(1) q = self.learning_network.predict(states, False) q = q.gather(1, actions) loss = self.learning_network.criterion(q, q_next) self.learning_network.zero_grad() loss.backward() self.learning_network.optimizer.step() if not deterministic and self.total_steps % self.config.target_network_update_freq == 0: self.target_network.load_state_dict(self.learning_network.state_dict()) if not deterministic and self.total_steps > self.config.exploration_steps: self.policy.update_epsilon() episode_time = time.time() - episode_start_time self.config.logger.debug('episode steps %d, episode time %f, time per step %f' % (steps, episode_time, episode_time / float(steps))) return total_reward, steps def save(self, file_name): with open(file_name, 'wb') as f: pickle.dump(self.learning_network.state_dict(), f)
[ "zhangshangtong.cpp@icloud.com" ]
zhangshangtong.cpp@icloud.com
ac21789371720cde990ea04ef4fa6a4949c11fbf
75374c8dce2d1ea64b91307b84f4676bf3294f91
/venv/lib/python3.7/site-packages/bokeh/core/property/validation.py
540914d565f13ef73a35288bac5732fbfe1b1adc
[]
no_license
emmaloutaylor/Dissertation-Predictive-Model-Django
6f8425f99bda7dea93716d76aee3f826efa6002e
cd94a4bc3268ace2a4d4a918c91690f437a45078
refs/heads/master
2023-08-08T00:25:11.481090
2019-04-03T20:39:34
2019-04-03T22:58:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,433
py
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- ''' Provide the Instance property. The Instance property is used to construct object graphs of Bokeh models, where one Bokeh model refers to another. ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function, unicode_literals import logging log = logging.getLogger(__name__) #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- # Standard library imports from functools import wraps # External imports # Bokeh imports from .bases import Property #----------------------------------------------------------------------------- # Globals and constants #----------------------------------------------------------------------------- __all__ = ( 'validate', 'without_property_validation', ) #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- class validate(object): ''' Control validation of Bokeh properties This can be used as a context manager, or as a normal callable Args: value (bool) : Whether validation should occur or not Example: .. code-block:: python with validate(False): # do no validate while within this block pass validate(False) # don't validate ever See Also: :func:`~Bokeh.core.property.bases.validation_on`: check the state of validation :func:`~Bokeh.core.properties.without_property_validation`: function decorator ''' def __init__(self, value): self.old = Property._should_validate Property._should_validate = value def __enter__(self): pass def __exit__(self, typ, value, traceback): Property._should_validate = self.old def without_property_validation(input_function): ''' Turn off property validation during update callbacks Example: .. code-block:: python @without_property_validation def update(attr, old, new): # do things without validation See Also: :class:`~Bokeh.core.properties.validate`: context mangager for more fine-grained control ''' @wraps(input_function) def func(*args, **kwargs): with validate(False): return input_function(*args, **kwargs) return func #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
[ "emmataylor223@gmail.com" ]
emmataylor223@gmail.com
d7207a576dddf97b7f43418a59a28b71bbe49f54
cd18d3142548ff264ec9a64f5887ebfb05a55aeb
/pyefun/progiterUtil.py
f5467840bc1b85be5d28550b1dcff6f1ef1f1b64
[ "Apache-2.0" ]
permissive
kingking888/pyefun
a035670c704f3ae4c431badd9e25d47929713163
afdf5acc3ab51f83d462e44bc2e974dafe173524
refs/heads/master
2023-05-09T15:01:56.783958
2021-05-31T14:47:55
2021-05-31T14:47:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,890
py
# 进度显示 使您可以测量和打印迭代过程的进度。这可以通过可迭代的界面或使用手动API来完成。使用可迭代的接口是最常见的。 from ubelt.util_format import * import ubelt as ub def 调试输出(obj): # data = repr2(obj, nl=2, precision=2) data = repr2(obj) print(data) class 进度显示(ub.ProgIter): def __init__(self, 迭代对象=None, 描述="", 总数=None, 信息级别=3, 显示速率=False, 显示时间=False, 起始索引=0, 进度大小=None, 启用=True, 输出在同一行=True ): "显示 0 不显示 1结束显示 2概率显示 3全部显示" # ProgIter(iterable=迭代对象,total=总数, desc=描述, show_times=False, verbose=显示) super().__init__(iterable=迭代对象, total=总数, desc=描述, show_times=显示速率, show_wall=显示时间, verbose=信息级别, initial=起始索引, chunksize=进度大小, enabled=启用, clearline=输出在同一行 ) def 下一步(self, 步数=1, 强制显示=False): self.step(inc=步数, force=强制显示) def 完成(self, 步数=1, 强制显示=False): self.end() def 开始(self): self.begin() def 取进度(self): data = self.format_message() return data def 换行(self): self.ensure_newline() def 输出(self, obj): self.ensure_newline() print(obj) def 附加输出(self, obj): self.set_extra(obj)
[ "ll@163.com" ]
ll@163.com
0e5b404689e9316c3c3e34f1c16d24c80aa0329a
7f4886802e83352f37d35509b7775c93c2756105
/festival/models.py
5b717ff85b6e7b325ed9187c1b2e7146a4146ef2
[]
no_license
JihyeKim0923/lion10
c23a019c3725de2d9f70556993db1ed3e8d6ae2e
2b76dc9290bec6f4d827a625b2f0b1e92c85ed53
refs/heads/master
2020-06-19T02:56:24.746341
2019-07-11T15:40:17
2019-07-11T15:40:17
196,539,639
0
0
null
null
null
null
UTF-8
Python
false
false
826
py
from django.db import models from django.utils import timezone # Create your models here. class Post(models.Model): author=models.ForeignKey('auth.User',on_delete=models.CASCADE) title=models.CharField(max_length=200) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) published_date=models.DateTimeField(blank=True,null=True) def published(self): self.published_date=timezone.now() self.save() def __str__(self): return self.title class Comment(models.Model): post=models.ForeignKey('festival.Post',related_name='comments', on_delete=models.CASCADE) nickname=models.CharField(max_length=200) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) def __str__(self): return self.text
[ "sos13313@naver.com" ]
sos13313@naver.com
39019e8fd9d7dda66abf8358c2697ed9f94c110f
e56953de3a962d5ca67907c6e68ec3c987fb8d30
/algorithms/dynamic_programming(DP)/11726_2n타일링.py
a38ade59004e4a6bb02368308f01a6181a98db04
[]
no_license
alb7979s/datastructuresAndAlgorithms
f2b337b460b989a9a04faafd3d41e08b9d424a3c
c9304733c87019952b8eb4261e62521e79cbe484
refs/heads/main
2023-08-18T00:11:42.332265
2021-09-23T09:18:23
2021-09-23T09:18:23
325,931,004
3
1
null
null
null
null
UTF-8
Python
false
false
191
py
def dp(x): if x <= 2: return x if mem[x] != -1: return mem[x] mem[x] = (dp(x-2) + dp(x-1))%DIV return mem[x] DIV = int(1e4) + 7 n=int(input()) mem = [-1] * (n+1) print(dp(n))
[ "alb7979s@naver.com" ]
alb7979s@naver.com
6963a9a71e656ace2ac1da7c4dd74fe1faf80cf9
5a0a4e019e438c31ac8264b662b92de50c8ed3e9
/SearchingAndSorting/search_in_rotated_array.py
cd0129d2fb37f85e89b9f5209e56b3ae9a901947
[ "MIT" ]
permissive
BharaniSri10/DSA-Together-HacktoberFest
d30b8c0f67869e2e12b21a346b0455ba6d133d42
ae245528fc07702f5fa9e4badf6e478c57ec2faa
refs/heads/main
2023-09-04T03:19:11.362265
2021-10-02T20:35:27
2021-10-02T20:35:27
412,903,744
1
0
MIT
2021-10-02T20:22:09
2021-10-02T20:22:08
null
UTF-8
Python
false
false
378
py
# Leetcode - 33 # https://leetcode.com/problems/search-in-rotated-sorted-array/ class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ op = -1 for i in range(0 , len(nums)): if (nums[i] == target): op = i return op
[ "dsrao0712@gmail.com" ]
dsrao0712@gmail.com
d20f333f05936b0ed82b6b6615a7d342703e63cf
79080c853292c9cd7f41e6fd4357e3a4736f75bc
/300-/384.py
6fe168d804abdfef8ecaa10fd88684490e125a17
[ "MIT" ]
permissive
yshshadow/Leetcode
d5476ff36b8c76213dacb01c252480e0539f37a7
5097f69bb0050d963c784d6bc0e88a7e871568ed
refs/heads/master
2020-03-23T21:32:39.227875
2019-01-15T17:46:19
2019-01-15T17:46:19
142,114,616
0
0
null
null
null
null
UTF-8
Python
false
false
1,404
py
# Shuffle a set of numbers without duplicates. # # Example: # # // Init an array with set 1, 2, and 3. # int[] nums = {1,2,3}; # Solution solution = new Solution(nums); # # // Shuffle the array [1,2,3] and return its result. Any permutation of [1,2,3] must equally likely to be returned. # solution.shuffle(); # # // Resets the array back to its original configuration [1,2,3]. # solution.reset(); # # // Returns the random shuffling of array [1,2,3]. # solution.shuffle(); import random class Solution: def __init__(self, nums): """ :type nums: List[int] """ self.origin = list(nums) self.array = nums def reset(self): """ Resets the array to its original configuration and return it. :rtype: List[int] """ self.array = self.origin self.origin = list(self.origin) return self.array def shuffle(self): """ Returns a random shuffling of the array. :rtype: List[int] """ for i in range(len(self.array)): swap = random.randint(i, len(self.array) - 1) self.array[swap], self.array[i] = self.array[i], self.array[swap] return self.array # Your Solution object will be instantiated and called as such: # obj = Solution(nums) # param_1 = obj.reset() # param_2 = obj.shuffle()
[ "=" ]
=
aa500f52835e95b292f603b05ba2d67174fa9c15
e123c7b93a4f9eea4d509aee619bf49576e14e74
/lib/logging.py
b63380889a6be7c7ff4007d298e01d9c7caf7e2b
[]
no_license
rx007/pubsubdemo
31d3edb44fd45dddac73ef225f0575d3e2bc0c95
ca2d21970aa61f3c69b0d8b3b8990452788dab33
refs/heads/master
2023-09-01T09:25:09.069213
2015-10-19T05:59:46
2015-10-19T05:59:46
44,574,349
1
0
null
2023-09-04T15:04:42
2015-10-20T01:27:05
Python
UTF-8
Python
false
false
361
py
import logging class BaseLoggingMixin: _logger = None @property def logger(self): if not self._logger: FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(level=logging.DEBUG, format=FORMAT) self._logger = logging.getLogger() return self._logger # logging.debug("1ssss")
[ "fortable1999@gmail.com" ]
fortable1999@gmail.com
a15934509c9bce80a887eef83c8f8d8a45909cfc
5b771c11e8967038025376c6ec31962ca90748dd
/django_by_example_book/02_Social_website/images/models.py
df3cbeb23a5169757c72e949d7bd314300cfab24
[]
no_license
AsemAntar/Django_Projects
7135eca3b4bcb656fc88e0838483c97d7f1746e1
4141c2c7e91845eec307f6dd6c69199302eabb16
refs/heads/master
2022-12-10T06:32:35.787504
2020-05-26T14:43:01
2020-05-26T14:43:01
216,863,494
0
0
null
2022-12-05T13:31:53
2019-10-22T16:47:28
Python
UTF-8
Python
false
false
1,016
py
from django.db import models from django.conf import settings from django.urls import reverse from django.utils.text import slugify class Image(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE ) title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, blank=True) url = models.URLField() image = models.ImageField(upload_to='images/%Y/%m/%d') description = models.TextField(blank=True) created = models.DateField(auto_now_add=True, db_index=True) users_likes = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name='images_liked', blank=True ) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args, **kwargs) def get_absolute_url(self): return reverse("image:detail", args=[self.id, self.slug])
[ "asemantar@gmail.com" ]
asemantar@gmail.com
cebece4c71231bb01593d9f810c520429f8ec289
904b0d81152649ccd3349f94f88e7b89a7b5c76a
/Sandbox/nightrange_ELG_LOPnotqsosuccess.py
e2f965e3851cf476ee67c5a637a83c744dcedf20
[ "BSD-3-Clause" ]
permissive
desihub/LSS
ec33538a0e7280ad1c6b257368cc009ed4b39cbb
5645461929172d327ed30389d76e7e887043c9bf
refs/heads/main
2023-08-18T23:17:13.123605
2023-08-18T20:08:22
2023-08-18T20:08:22
36,753,969
14
28
BSD-3-Clause
2023-09-13T18:37:35
2015-06-02T18:42:51
Jupyter Notebook
UTF-8
Python
false
false
7,408
py
#right now, requires source /project/projectdirs/desi/software/desi_environment.sh master from astropy.table import Table import numpy as np import os import argparse import fitsio from desitarget.targetmask import zwarn_mask,desi_mask from matplotlib.backends.backend_pdf import PdfPages parser = argparse.ArgumentParser() parser.add_argument("--min_night")#, help="use this if you want to specify the night, rather than just use the last one",default=None) parser.add_argument("--max_night")#, help="use this if you want to specify the night, rather than just use the last one",default=None) parser.add_argument("--plottsnr2",default='y') parser.add_argument("--plotnz",default='y') parser.add_argument("--vis",default='n',help="whether to display plots when you run") parser.add_argument("--outdir",default='/global/cfs/cdirs/desi/survey/catalogs/main/LSS/daily/plots/tests/') args = parser.parse_args() #one list for each petal for total targets gz = np.zeros(10) tz = np.zeros(10) tsnrlsg = {x: [] for x in range(0,10)} tsnrls = {x: [] for x in range(0,10)} nzls = {x: [] for x in range(0,10)} nzla = [] ss = Table.read('/global/cfs/cdirs/desi/survey/ops/surveyops/trunk/ops/tiles-specstatus.ecsv') nights = np.unique(ss['LASTNIGHT']) sel = nights >= int(args.min_night) sel &= nights <= int(args.max_night) nights = nights[sel] bit = desi_mask['ELG_LOP'] for night in nights:# range(int(args.min_night),int(args.max_night)+1): month = str(night)[:6] #get the right tileids exps = Table.read('/global/cfs/cdirs/desi/spectro/redux/daily/exposure_tables/'+month+'/exposure_table_'+str(night)+'.csv') print('number of exposures found:') print(len(exps)) #cut to dark tiles sel = exps['FAPRGRM']=='dark' print('number that are dark time:') print(len(exps[sel])) exps = exps[sel] #get the list of tileids observed on the last night tidl = np.unique(exps['TILEID']) #get total exposure time for tiles exptl = np.zeros(len(tidl)) for ii in range(0, len(tidl)): w = exps['TILEID'] == tidl[ii] expt = np.sum(exps[w]['EFFTIME_ETC']) exptl[ii] = expt sel = exptl > 850 tidl = tidl[sel] print('number bright tiles that have EFFTIME_ETC/goal > 0.85 during the night:') print(len(tidl)) print('looking at LRG redshift results from the night '+str(night)) print('the tileids are:') print(tidl) zdir = '/global/cfs/cdirs/desi/spectro/redux/daily/tiles/cumulative/' for tid in tidl: for pt in range(0,10): zmtlff = zdir+str(tid)+'/'+str(night)+'/zmtl-'+str(pt)+'-'+str(tid)+'-thru'+str(night)+'.fits' rrf = zdir+str(tid)+'/'+str(night)+'/redrock-'+str(pt)+'-'+str(tid)+'-thru'+str(night)+'.fits' emf = zdir+str(tid)+'/'+str(night)+'/emline-'+str(pt)+'-'+str(tid)+'-thru'+str(night)+'.fits' if os.path.isfile(zmtlff): zmtlf = fitsio.read(zmtlff) rr = fitsio.read(rrf,ext='TSNR2') em = fitsio.read(emf) nodata = zmtlf["ZWARN"] & zwarn_mask["NODATA"] != 0 num_nod = np.sum(nodata) print('looking at petal '+str(pt)+' on tile '+str(tid)) print('number with no data '+str(num_nod)) badqa = zmtlf["ZWARN"] & zwarn_mask.mask("BAD_SPECQA|BAD_PETALQA") != 0 num_badqa = np.sum(badqa) print('number with bad qa '+str(num_badqa)) nomtl = nodata | badqa wfqa = ~nomtl wlrg = ((zmtlf['DESI_TARGET'] & bit) > 0) wlrg &= ((zmtlf['DESI_TARGET'] & 4) == 0) zlrg = zmtlf[wfqa&wlrg] if len(zlrg) > 0: #drz = (10**(3 - 3.5*zmtlf['Z'])) #mask_bad = (drz>30) & (zmtlf['DELTACHI2']<30) #mask_bad |= (drz<30) & (zmtlf['DELTACHI2']<drz) #mask_bad |= (zmtlf['DELTACHI2']<10) #wz = zmtlf['ZWARN'] == 0 #wz &= zmtlf['Z']<1.4 #wz &= (~mask_bad) #mask_bad = (zmtlf['DELTACHI2']<15) #wz = zmtlf['ZWARN'] == 0 #wz &= zmtlf['Z']<1.5 #wz &= (~mask_bad) o2c = np.log10(em['OII_FLUX'] * np.sqrt(em['OII_FLUX_IVAR']))+0.2*np.log10(zmtlf['DELTACHI2']) wz = o2c > 0.9 wzwarn = wz#zmtlf['ZWARN'] == 0 gzlrg = zmtlf[wzwarn&wlrg&wfqa] print('The fraction of good ELG_LOPnotqso is '+str(len(gzlrg)/len(zlrg))+' for '+str(len(zlrg))+' considered spectra') gz[pt] += len(gzlrg) tz[pt] += len(zlrg) nzls[pt].append(zmtlf[wzwarn&wlrg]['Z']) nzla.append(zmtlf[wzwarn&wlrg]['Z']) tsnrlsg[pt].append(rr[wzwarn&wlrg&wfqa]['TSNR2_ELG']) tsnrls[pt].append(rr[wfqa&wlrg]['TSNR2_ELG']) else: print('no good elg data') else: print(zmtlff+' not found') print('the total number of ELG_LOPnotqso considered per petal for the nights is:') print(tz) tzs = gz/tz print('the total fraction of good ELG_LOPnotqso z per petal for the nights is:') print(tzs) if args.plotnz == 'y': from matplotlib import pyplot as plt figs = [] all = fitsio.read('/global/cfs/cdirs/desi/survey/catalogs/main/LSS/daily/LSScats/test/ELG_LOPnotqso_full.dat.fits') sel = all['o2c'] > 0.9 sel &= all['ZWARN'] != 999999 #sel &= all['Z_not4clus'] < 1.5 all = all[sel] nza = np.concatenate(nzla) for pt in range(0,10): #plt.clf() if len(nzls[pt]) > 0: fig = plt.figure() nzp = np.concatenate(nzls[pt]) a = plt.hist(nzp,range=(0.1,1.6),bins=75,density=True,label='petal '+str(pt),histtype='step') plt.hist(nza,bins=a[1],density=True,histtype='step',label='all petals for selected nights') plt.hist(all['Z_not4clus'],bins=a[1],density=True,histtype='step',label='all archived in daily',color='k') plt.title('ELG_LOPnotqso for nights '+args.min_night+' through '+args.max_night) plt.xlabel('Z') plt.legend(loc='lower center') figs.append(fig) #plt.savefig(args.outdir+'LRG'+args.min_night+args.max_night+'_'+str(pt)+'.png') #if args.vis == 'y': # plt.show() with PdfPages(args.outdir+'ELG_LOPnotqso'+args.min_night+args.max_night+'_nzpetal.pdf') as pdf: for fig in figs: pdf.savefig(fig) plt.close() if args.plottsnr2 == 'y': from matplotlib import pyplot as plt for pt in range(0,10): if len(tsnrlsg[pt]) > 0: gz = np.concatenate(tsnrlsg[pt]) az = np.concatenate(tsnrls[pt]) a = np.histogram(gz) b = np.histogram(az,bins=a[1]) bc = a[1][:-1]+(a[1][1]-a[1][0])/2. err = np.sqrt(b[0]-a[0])/b[0] plt.errorbar(bc,a[0]/b[0],err,label='petal '+str(pt)) plt.legend() plt.xlabel('TSNR2_ELG') plt.ylabel('redshift success rate') plt.savefig(args.outdir+'ELG_LOPnotqso'+args.min_night+args.max_night+'_vstsnr2.png') if args.vis == 'y': plt.show()
[ "ashley.jacob.ross@gmail.com" ]
ashley.jacob.ross@gmail.com
53a23e14ac999c557c7dba20208c195194ec2dd9
7f5dca89315a869b2f30d39a9ed3d3c848960bd0
/basic_cms/models.py
16d25452ba2196b1fcc4e2f0e67cbe1021272de8
[]
no_license
ljean/balafon_standalone_example
6df5f3252a9ec3fcc180ced2ee3301f5ca42f196
bde12ee9c1f1735a0a3c63271fab1a5caee9ecf9
refs/heads/master
2021-01-10T08:10:35.437568
2016-03-24T11:31:42
2016-03-24T11:31:42
54,129,145
0
0
null
null
null
null
UTF-8
Python
false
false
223
py
# -*- coding: utf-8 -*- """models""" from coop_cms.models import BaseArticle, BaseNavTree class Article(BaseArticle): # pylint: disable=W5101 """basic_cms.Article is equal to the BaseArticle abstract""" pass
[ "ljean@apidev.fr" ]
ljean@apidev.fr
9c98dbdfa22f606247a9bc1c21dc28985e60310f
2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02
/PyTorch/contrib/cv/detection/GFocalV2/mmcv_need/builder.py
7beeeca018755b5083d9da1a6acf02197fa0f71b
[ "GPL-1.0-or-later", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Ascend/ModelZoo-PyTorch
4c89414b9e2582cef9926d4670108a090c839d2d
92acc188d3a0f634de58463b6676e70df83ef808
refs/heads/master
2023-07-19T12:40:00.512853
2023-07-17T02:48:18
2023-07-17T02:48:18
483,502,469
23
6
Apache-2.0
2022-10-15T09:29:12
2022-04-20T04:11:18
Python
UTF-8
Python
false
false
2,523
py
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # 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 copy import inspect import torch import apex from ...utils import Registry, build_from_cfg OPTIMIZERS = Registry('optimizer') OPTIMIZER_BUILDERS = Registry('optimizer builder') def register_torch_optimizers(): torch_optimizers = [] for module_name in dir(torch.optim): if module_name.startswith('__'): continue _optim = getattr(torch.optim, module_name) if hasattr(torch.optim, 'NpuFusedOptimizerBase') and \ inspect.isclass(_optim) and \ issubclass(_optim, torch.optim.NpuFusedOptimizerBase): continue if inspect.isclass(_optim) and issubclass(_optim, torch.optim.Optimizer): OPTIMIZERS.register_module()(_optim) torch_optimizers.append(module_name) # add npu optimizer from apex for module_name in dir(apex.optimizers): if module_name.startswith('__'): continue _optim = getattr(apex.optimizers, module_name) if inspect.isclass(_optim) and issubclass(_optim, torch.optim.Optimizer): OPTIMIZERS.register_module()(_optim) torch_optimizers.append(module_name) return torch_optimizers TORCH_OPTIMIZERS = register_torch_optimizers() def build_optimizer_constructor(cfg): return build_from_cfg(cfg, OPTIMIZER_BUILDERS) def build_optimizer(model, cfg): optimizer_cfg = copy.deepcopy(cfg) constructor_type = optimizer_cfg.pop('constructor', 'DefaultOptimizerConstructor') paramwise_cfg = optimizer_cfg.pop('paramwise_cfg', None) optim_constructor = build_optimizer_constructor( dict( type=constructor_type, optimizer_cfg=optimizer_cfg, paramwise_cfg=paramwise_cfg)) optimizer = optim_constructor(model) return optimizer
[ "wangjiangben@huawei.com" ]
wangjiangben@huawei.com
e608eabea228cd68009cd427ef30957f38bfcb0e
b68b43162dcf7d3a739144f55087b1795c235194
/nplook/shell.py
0a4b0769164f24724d392d587a5d1afd11b32b30
[]
no_license
gustavla/nplook
5970b40163e83e5aaab64947bb32437b6cd22908
1556b6e0d0c5f0255cc7b4712b778d8a97fd217e
refs/heads/master
2021-01-01T15:51:31.342797
2013-01-19T19:44:30
2013-01-19T19:44:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,100
py
from __future__ import print_function import sys import nplook import glob from optparse import OptionParser def main(): examples = [] examples.append(("data.npy", "summarizes the ndarray in data.npy")) examples.append(("data.npz", "summarizes the dictionary in data.npz")) examples.append(("*.npz", "summarizes all npz files in the directory")) examples.append(("", "summarizes all files in the directory")) ex_str = "\n".join([" %prog {0:<18}{1}".format(tup[0], tup[1]) for tup in examples]) usage = "Usage: %prog [options] <file> [<file> ...]\n\nExamples:\n{0}".format(ex_str) parser = OptionParser(usage=usage, version="%prog {0}".format(nplook.__version__)) (options, args) = parser.parse_args() if args: filenames = args else: filenames = glob.glob("*") i = 0 for filename in filenames: summary = nplook.summarize(filename) if summary: if i != 0: print() print(summary) i += 1 if i == 0: print("No files that can be summarized matched your query")
[ "gustav.m.larsson@gmail.com" ]
gustav.m.larsson@gmail.com
7222ec080a830e56ff98e948ca2d6cd24f9bd216
5cbb2c7378dda2ffb06b02c3bc6deb8451e4fbbf
/B/conanfile.py
81aff2b31c949af77dbc635599002de28f519ccf
[ "MIT" ]
permissive
objectx/conan-project-example
b6a09bd289ded49e66a0af2ad14c9cd0502dc7d3
cf632ea60c15e5676fdc188f4ff7ced5fd7eb074
refs/heads/master
2020-03-09T02:11:20.555017
2018-04-06T15:50:50
2018-04-06T15:50:50
128,534,407
0
0
null
2018-04-07T14:09:22
2018-04-07T14:09:22
null
UTF-8
Python
false
false
578
py
from conans import ConanFile, CMake class Pkg(ConanFile): settings = "os", "compiler", "arch", "build_type" requires = "HelloC/0.1@lasote/stable" generators = "cmake" exports_sources = "src/*" def build(self): cmake = CMake(self) cmake.configure(source_folder="src") cmake.build() def package(self): self.copy("*.h", src="src", dst="include") self.copy("*.lib", dst="lib", keep_path=False) self.copy("*.a", dst="lib", keep_path=False) def package_info(self): self.cpp_info.libs = ["helloB"]
[ "james@conan.io" ]
james@conan.io
61fde401a97dbd3149c813d4d27c95761241d04e
75fa11b13ddab8fd987428376f5d9c42dff0ba44
/metadata-ingestion/examples/library/lineage_job_dataflow_new_api_verbose.py
67a8ce2059679a70f95a9c29b4be5b9de0e1a6b5
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause", "MIT" ]
permissive
RyanHolstien/datahub
163d0ff6b4636919ed223ee63a27cba6db2d0156
8cf299aeb43fa95afb22fefbc7728117c727f0b3
refs/heads/master
2023-09-04T10:59:12.931758
2023-08-21T18:33:10
2023-08-21T18:33:10
246,685,891
0
0
Apache-2.0
2021-02-16T23:48:05
2020-03-11T21:43:58
TypeScript
UTF-8
Python
false
false
3,864
py
import time import uuid from datahub.api.entities.corpgroup.corpgroup import CorpGroup from datahub.api.entities.corpuser.corpuser import CorpUser from datahub.api.entities.datajob.dataflow import DataFlow from datahub.api.entities.datajob.datajob import DataJob from datahub.api.entities.dataprocess.dataprocess_instance import ( DataProcessInstance, InstanceRunResult, ) from datahub.emitter.rest_emitter import DatahubRestEmitter emitter = DatahubRestEmitter("http://localhost:8080") jobFlow = DataFlow(env="prod", orchestrator="airflow", id="flow2") jobFlow.emit(emitter) # Flowurn as constructor dataJob = DataJob(flow_urn=jobFlow.urn, id="job1", name="My Job 1") dataJob.properties["custom_properties"] = "test" dataJob.emit(emitter) dataJob2 = DataJob(flow_urn=jobFlow.urn, id="job2", name="My Job 2") dataJob2.upstream_urns.append(dataJob.urn) dataJob2.tags.add("TestTag") dataJob2.owners.add("testUser") dataJob2.emit(emitter) dataJob3 = DataJob(flow_urn=jobFlow.urn, id="job3", name="My Job 3") dataJob3.upstream_urns.append(dataJob.urn) dataJob3.emit(emitter) dataJob4 = DataJob(flow_urn=jobFlow.urn, id="job4", name="My Job 4") dataJob4.upstream_urns.append(dataJob2.urn) dataJob4.upstream_urns.append(dataJob3.urn) dataJob4.group_owners.add("testGroup") dataJob4.emit(emitter) # Hello World jobFlowRun: DataProcessInstance = DataProcessInstance( orchestrator="airflow", cluster="prod", id=f"{jobFlow.id}-{uuid.uuid4()}" ) jobRun1: DataProcessInstance = DataProcessInstance( orchestrator="airflow", cluster="prod", id=f"{jobFlow.id}-{dataJob.id}-{uuid.uuid4()}", ) jobRun1.parent_instance = jobFlowRun.urn jobRun1.template_urn = dataJob.urn jobRun1.emit_process_start( emitter=emitter, start_timestamp_millis=int(time.time() * 1000), emit_template=False ) jobRun1.emit_process_end( emitter=emitter, end_timestamp_millis=int(time.time() * 1000), result=InstanceRunResult.SUCCESS, ) jobRun2: DataProcessInstance = DataProcessInstance( orchestrator="airflow", cluster="prod", id=f"{jobFlow.id}-{dataJob2.id}-{uuid.uuid4()}", ) jobRun2.template_urn = dataJob2.urn jobRun2.parent_instance = jobFlowRun.urn jobRun2.upstream_urns = [jobRun1.urn] jobRun2.emit_process_start( emitter=emitter, start_timestamp_millis=int(time.time() * 1000), emit_template=False ) jobRun2.emit_process_end( emitter=emitter, end_timestamp_millis=int(time.time() * 1000), result=InstanceRunResult.SUCCESS, ) jobRun3: DataProcessInstance = DataProcessInstance( orchestrator="airflow", cluster="prod", id=f"{jobFlow.id}-{dataJob3.id}-{uuid.uuid4()}", ) jobRun3.parent_instance = jobFlowRun.urn jobRun3.template_urn = dataJob3.urn jobRun3.upstream_urns = [jobRun1.urn] jobRun3.emit_process_start( emitter=emitter, start_timestamp_millis=int(time.time() * 1000), emit_template=False ) jobRun3.emit_process_end( emitter=emitter, end_timestamp_millis=int(time.time() * 1000), result=InstanceRunResult.SUCCESS, ) jobRun4: DataProcessInstance = DataProcessInstance( orchestrator="airflow", cluster="prod", id=f"{jobFlow.id}-{dataJob4.id}-{uuid.uuid4()}", ) jobRun4.parent_instance = jobFlowRun.urn jobRun4.template_urn = dataJob4.urn jobRun4.upstream_urns = [jobRun2.urn, jobRun3.urn] jobRun4.emit_process_start( emitter=emitter, start_timestamp_millis=int(time.time() * 1000), emit_template=False ) jobRun4.emit_process_end( emitter=emitter, end_timestamp_millis=int(time.time() * 1000), result=InstanceRunResult.SUCCESS, ) user1 = CorpUser( id="testUser", display_name="Test User", email="test-user@test.com", groups=["testGroup"], ) user1.emit(emitter) group1 = CorpGroup( id="testGroup", display_name="Test Group", email="test-group@test.com", slack="#test-group", overrideEditable=True, ) group1.emit(emitter)
[ "noreply@github.com" ]
RyanHolstien.noreply@github.com
b9f133f64096954e8bfacbb8dcf6ecfe838d4062
d3ce58c4576431df14de0990f45cfd574f0aa45f
/.history/user/forms_20201012030941.py
86918f6244ab2c67add33605548b6ea388226b00
[]
no_license
rahulsolankib/portfolio
fe93f0e6b0b28990f0b9fad84dbf7c3aa07243c4
281ed429e2590376aee4649b2ea7b3e8facaf6f1
refs/heads/master
2023-01-02T06:55:21.319094
2020-10-26T08:55:22
2020-10-26T08:55:22
305,586,595
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
from django import forms from django.contrib.auth.models import user.admin from django.contrib.auth.forms import UserCreationForm
[ "rahulsolankib@gmail.com" ]
rahulsolankib@gmail.com
26dc331b0da91a2c867c26f7ec760a49d3b79681
3d388dccb14373bedb85d43851bc8eeb74a3eb18
/main.py
6476c66a90cc6db2e0f89497af03df52e9401883
[ "MIT" ]
permissive
dileep1996/sentence-similarity
416917641963f5fa1af76204c681389771d2187c
37a99a11ac97774928affb30cf75f6222cfdabaf
refs/heads/master
2020-04-10T01:45:46.503849
2018-12-06T20:26:44
2018-12-06T20:26:44
160,724,751
0
0
null
2018-12-06T19:55:52
2018-12-06T19:55:52
null
UTF-8
Python
false
false
3,053
py
""" Driver program for training and evaluation. """ import argparse import logging import numpy as np import random import torch import torch.optim as O from datasets import get_dataset, get_dataset_configurations from models import get_model from runners import Runner if __name__ == '__main__': parser = argparse.ArgumentParser(description='Sentence similarity models') parser.add_argument('--model', default='sif', choices=['sif', 'mpcnn', 'mpcnn-lite', 'bimpm'], help='Model to use') parser.add_argument('--dataset', default='sick', choices=['sick', 'wikiqa'], help='Dataset to use') parser.add_argument('--batch-size', type=int, default=64, help='Batch size') parser.add_argument('--epochs', type=int, default=15, help='Number of epochs') parser.add_argument('--lr', type=float, default=2e-4, help='Learning rate') parser.add_argument('--regularization', type=float, default=3e-4, help='Regularization') parser.add_argument('--seed', type=int, default=1234, help='Seed for reproducibility') parser.add_argument('--device', type=int, default=0, help='Device, -1 for CPU') parser.add_argument('--log-interval', type=int, default=50, help='Device, -1 for CPU') # Special options for SIF model parser.add_argument('--unsupervised', action='store_true', default=False, help='Set this flag to use unsupervised mode.') parser.add_argument('--alpha', type=float, default=1e-3, help='Smoothing term for smooth inverse frequency baseline model') parser.add_argument('--no-remove-special-direction', action='store_true', default=False, help='Set to not remove projection onto first principal component') parser.add_argument('--frequency-dataset', default='enwiki', choices=['train', 'enwiki']) args = parser.parse_args() random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.device != -1: torch.cuda.manual_seed(args.seed) logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(levelname)s - %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) dataset_cls, train_loader, dev_loader, test_loader, embedding = get_dataset(args) model = get_model(args, dataset_cls, embedding) if args.model == 'sif': model.populate_word_frequency_estimation(train_loader) total_params = 0 for param in model.parameters(): size = [s for s in param.size()] total_params += np.prod(size) logger.info('Total number of parameters: %s', total_params) loss_fn, metrics, y_to_score, resolved_pred_to_score = get_dataset_configurations(args) optimizer = O.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, weight_decay=args.regularization) runner = Runner(model, loss_fn, metrics, optimizer, y_to_score, resolved_pred_to_score, args.device, None) runner.run(args.epochs, train_loader, dev_loader, test_loader, args.log_interval)
[ "tuzhucheng@outlook.com" ]
tuzhucheng@outlook.com
f962b3f9fba5cc65564b9ab52e8be9a87e39ae37
32ed2a60ebf03127c317e71d7632362bddf04769
/src/Object_finder.py
9b2132e8226f4e5c749f1270fb5c4a6ada283416
[]
no_license
OMARI1988/fyp
59cf94857e2708d0577b8e22493b2270796deae9
ce74b732aec9809639314cf5b72f808bfb107da8
refs/heads/master
2021-01-10T16:00:45.830974
2015-11-18T11:43:22
2015-11-18T11:43:22
46,409,208
0
1
null
null
null
null
UTF-8
Python
false
false
4,649
py
#! /usr/bin/env python2.7 # this node is used to save the colors of the different objects so that we can track them later import roslib #roslib.load_manifest('graphs') import sys import inspect, os from optparse import OptionParser import rospy import sensor_msgs.msg from cv_bridge import CvBridge import cv import cv2 import numpy as np #import scipy.ndimage.morphology as morphology #--------------------------------------------------------------------------------------# global x,y,z,rgb_flag,f,obj_count,r1,b1,g1,r2,b2,g2,size x = 0 y = 0 z = 0 rgb_flag = 0 r1=0 b1=0 g1=0 r2=0 b2=0 g2=0 size=1 directory = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) f = open(directory+'/objects.txt', 'w') obj_count = 1 #--------------------------------------------------------------------------------------# if __name__ == '__main__': #--------------------------------------------------------------------------------------# def nothing(x): pass #--------------------------------------------------------------------------------------# def obj(x): global f,obj_count,r1,b1,g1,r2,b2,g2,size if cv2.getTrackbarPos('object','toolbar')==1: f.write(str(obj_count)+','+str(r1)+','+str(b1)+','+str(g1)+','+str(r2)+','+str(b2)+','+str(g2)+','+str(size)+'\n') print 'object'+str(obj_count)+' is saved' obj_count = obj_count + 1 cv2.setTrackbarPos('object','toolbar',0) #--------------------------------------------------------------------------------------# def finish(x): global f f.write('END') f.close() cv2.destroyAllWindows() #pkgdir = roslib.packages.get_pkg_dir("opencv2") #haarfile = os.path.join(pkgdir, "opencv/share/opencv/haarcascades/haarcascade_frontalface_alt.xml") br = CvBridge() # Create a black image, a window #--------------------------------------------------------------------------------------# def detect_and_draw(imgmsg): global x,y,rgb_flag,r1,b1,g1,r2,b2,g2,size img = br.imgmsg_to_cv2(imgmsg, desired_encoding="passthrough") # Take each frame simg = cv2.GaussianBlur(img,(5,5),0) # Convert BGR to HSV hsv = cv2.cvtColor(simg, cv2.COLOR_BGR2HSV) #1 #lower_blue = np.array([8,185,114]) #upper_blue = np.array([13,249,169]) # get current positions of four trackbars r1 = cv2.getTrackbarPos('R1','toolbar') g1 = cv2.getTrackbarPos('G1','toolbar') b1 = cv2.getTrackbarPos('B1','toolbar') r2 = cv2.getTrackbarPos('R2','toolbar') g2 = cv2.getTrackbarPos('G2','toolbar') b2 = cv2.getTrackbarPos('B2','toolbar') size = cv2.getTrackbarPos('Size','toolbar') if size<1: size = 1 lower_blue = np.array([r1,b1,g1]) upper_blue = np.array([r2,b2,g2]) # Threshold the HSV image to get only orange colors mask = cv2.inRange(hsv, lower_blue, upper_blue) # filter and fill the mask kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(size,size)) mask2 = cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernel) moments = cv2.moments(mask2) area = moments['m00'] #there can be noise in the video so ignore objects with small areas if(area > 10000): #determine the x and y coordinates of the center of the object #we are tracking by dividing the 1, 0 and 0, 1 moments by the area x = moments['m10'] / area y = moments['m01'] / area x = int(x) y = int(y) cv2.line(hsv,(x,0),(x,480),(255,50,100),3) cv2.line(hsv,(0,y),(640,y),(255,50,100),3) rgb_flag = 1 cv2.imshow('RGB',hsv) cv2.imshow('Mask',mask2) k = cv2.waitKey(5) & 0xFF #--------------------------------------------------------------------------------------# cv2.namedWindow('toolbar', flags=0) cv2.moveWindow('toolbar', 1000, 0) # create trackbars for color change cv2.createTrackbar('R1','toolbar',0,255,nothing) cv2.createTrackbar('G1','toolbar',0,255,nothing) cv2.createTrackbar('B1','toolbar',0,255,nothing) cv2.createTrackbar('R2','toolbar',0,255,nothing) cv2.createTrackbar('G2','toolbar',0,255,nothing) cv2.createTrackbar('B2','toolbar',0,255,nothing) cv2.createTrackbar('Size','toolbar',1,30,nothing) cv2.createTrackbar('object','toolbar',0,1,obj) cv2.createTrackbar('finish','toolbar',0,1,finish) rospy.init_node('rosColordetect') image_topic = rospy.resolve_name("/cameras/left_hand_camera/image") #depth_topic = rospy.resolve_name("/camera/depth_registered/image_raw") rospy.Subscriber(image_topic, sensor_msgs.msg.Image, detect_and_draw) #rospy.Subscriber(depth_topic, sensor_msgs.msg.Image, depth_calculation) #talker() rospy.spin()
[ "omari.1988@gmail.com" ]
omari.1988@gmail.com
66c3e604eb35a488c5e705a5b98ad504c3a1d1f0
8cc6c175a11d0d100747a355e9fdabad8123fb63
/level_1/index.py
8f53a848bee2af6b46ad7afe05f5d2d954b9dbae
[]
no_license
fdetun/hodor
99b5003214631e1aec1fe097abfa234010e28e14
95597385bab86eee2b90976803e077d3e4ee6a9e
refs/heads/master
2022-11-06T11:56:51.027717
2020-06-08T00:01:09
2020-06-08T00:01:09
270,452,512
0
0
null
null
null
null
UTF-8
Python
false
false
563
py
#!/usr/bin/python3 import requests URL = "http://158.69.76.135/level1.php" s = requests.Session() payload = {"id": "1324", 'holdthedoor': 'submit', "key":""} for i in range(0, 4096): r = s.get('http://158.69.76.135/level1.php') fde=r.headers['set-cookie'] print(r.headers) inp=r.headers['set-cookie'].index("=") ind=r.headers['set-cookie'].index(";") payload["key"] = fde[(inp + 1):ind] r = s.post(URL, data=payload) if r.status_code == 200: print("vote nb {}".format(i)) else: print("faile nb {}".format(i))
[ "fouedads@gmail.com" ]
fouedads@gmail.com
c19cde248ac8570298965a02bc5aaa1894882581
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_078/ch147_2020_09_28_14_11_18_724789.py
57c33c4f6aaef647f987a6317890314f4074fb6e
[]
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
326
py
def mais_frequente(lista): dicionario_palavras = conta_ocorrencias(lista) i=0 maior = dicionario_palavras[0] while i < len(dicionario_palavras): if dicionario_palavras[i+1] > dicionario_palavras[i]: maior = dicionario_palavras[i].keys() i+=1 return maior
[ "you@example.com" ]
you@example.com
034b0155c23dcb07240435bc0d83f14d35d72593
1f13c189fc3d97f3fec0805910c7e0e5115ea6e8
/tests/test_interface.py
26dff170493c2db7e355eba19ce2aa8131fe5fc3
[]
no_license
schalekamp/ishares
26ffde8af27d671c8cbaa938eaaa1454ec9936a1
671978587cc3a55da655141ad7b317d55716ab94
refs/heads/master
2020-03-19T22:47:51.042065
2018-06-01T10:15:05
2018-06-01T10:15:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
526
py
from pytest import raises from ishares.interface import iShares all_etfs = None def test_interface(): global all_etfs all_etfs = iShares() all_etfs.report() def test_interface_isin(): global all_etfs fund = all_etfs.get_fund(isin='IE0032895942') fund.report() def test_interface_nofund(): global all_etfs with raises(ValueError): all_etfs.get_fund('XXXXXXX') def test_interface_manyfund(): global all_etfs with raises(ValueError): all_etfs.get_fund('LQDA')
[ "github@gpiantoni.com" ]
github@gpiantoni.com
23492d4e41c3c292ff5df3adda5db1ec0bfa9e68
6032498a2829b4e9c3515e7c15476866be8f9112
/17_classes_and_objects_basics/17.9.instances_as_return_values.py
b194bc3225942b00fad3a075be39490f4d18a922
[]
no_license
KenjaminButton/runestone_thinkcspy
de3d7b8250be3c281a769baf392d31fc623403b8
ff5973cf5514c13019c4e970d9a6e8c0e1482a44
refs/heads/master
2023-06-08T07:42:19.927968
2019-11-09T15:47:35
2019-11-09T15:47:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,966
py
# Instances as Return Values ''' Functions and methods can return objects. This is actually nothing new since everything in Python is an object and we have been returning values for quite some time. The difference here is that we want to have the method create an object using the constructor and then return it as the value of the method. Suppose you have a point object and wish to find the midpoint halfway between it and some other target point. We would like to write a method, call it halfway that takes another Point as a parameter and returns the Point that is halfway between the point and the target ''' # Used for square root function import math class Point: def __init__(self, initX, initY): self.x = initX self.y = initY def getX(self): return self.x def getY(self): return self.y def distanceFromOrigin(self): # Same as setting the power of this equation to ^ 0.5 or ** 0.5 return math.sqrt((self.x ** 2) + (self.y ** 2)) def __str__(self): return "x=" + str(self.x) + ", y=" + str(self.y) def halfway(self, target): mx = (self.x + target.x) / 2 my = (self.y + target.y) / 2 return Point(mx, my) p = Point(3, 4) q = Point(5, 12) mid = p.halfway(q) # These print statements below add extra lines of work for codeLens to process print("\nMidpoint values of both (x and y) for both (p and q).") print(mid) print("\nMidpoint values of X for both (p and q).") print(mid.getX()) print("\nMidpoint values of Y for both (p and q).") print(mid.getY()) ''' The resulting Point, mid, has an x value of 4 and a y value of 8. We can also use any other methods since mid is a Point object. In the definition of the method halfway see how the requirement to always use dot notation with attributes disambiguates the meaning of the attributes x and y: We can always see whether the coordinates of Point self or target are being referred to. '''
[ "kennethpchang@gmail.com" ]
kennethpchang@gmail.com
2a2720a4faea2b3424185730fb0814d5e957f5e3
98c6ea9c884152e8340605a706efefbea6170be5
/examples/data/Assignment_2/chmtin004/question2.py
3caa28f28064ed5055afe02dd831a174b8636b55
[]
no_license
MrHamdulay/csc3-capstone
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
refs/heads/master
2021-03-12T21:55:57.781339
2014-09-22T02:22:22
2014-09-22T02:22:22
22,372,174
0
0
null
null
null
null
UTF-8
Python
false
false
3,224
py
#Program for 30 second rule #Tinotenda Chemvura (CHMTIN004) #08 March 2014 #__________________program starts here_______________ def game(): print("Welcome to the 30 Second Rule Expert") print("------------------------------------") print("Answer the following questions by selecting from among the options.") ans1=str(input("Did anyone see you? (yes/no)\n")) if ans1=="yes": ans2=str(input("Was it a boss/lover/parent? (yes/no)\n")) if ans2=="no": print("Decision: Eat it.") elif ans2=="yes": ans3=str(input("Was it expensive? (yes/no)\n")) if ans3=="yes": ans4=str(input("Can you cut off the part that touched the floor? (yes/no)\n")) if ans4=="no": print("Decision: Your call.") elif ans4=="yes": print("Decision: Eat it.") elif ans3=="no": ans5=str(input("Is it chocolate? (yes/no)\n")) if ans5=="yes": print("Decision: Eat it.") elif ans5=="no": print("Decision: Don't eat it.") elif ans1=="no": ans6=str(input("Was it sticky? (yes/no)\n")) if ans6=="no": ans7=str(input("Is it an Emausaurus? (yes/no)\n")) if ans7=="yes": ans8=str(input("Are you a Megalosaurus? (yes/no)\n")) if ans8=="yes": print("Decision: Eat it.") elif ans8=="no": print("Decision: Don't eat it.") elif ans7=="no": ans9=str(input("Did the cat lick it? (yes/no)\n")) if ans9=="no": print("Decision: Eat it.") elif ans9=="yes": ans10=(input("Is your cat healthy? (yes/no)\n")) if ans10=="no": print("Decision: Your call.") elif ans10=="yes": print("Decision: Eat it.") elif ans6=="yes": ans11=str(input("Is it a raw steak? (yes/no)\n")) if ans11=="no": ans12=str(input("Did the cat lick it? (yes/no)\n")) if ans12=="no": print("Decision: Eat it.") elif ans12=="yes": ans13=(input("Is your cat healthy? (yes/no)\n")) if ans13=="no": print("Decision: Your call.") elif ans13=="yes": print("Decision: Eat it.") elif ans11=="yes": ans14=str(input("Are you a puma? (yes/no)\n")) if ans14=="yes": print("Decision: Eat it.") elif ans14=="no": print("Decision: Don't eat it.") #_____________End of the program________________* game()
[ "jarr2000@gmail.com" ]
jarr2000@gmail.com
c8342a916b55a541090e50e88a78e91faea7d30c
67b3ac97f8ef13aa5caea25de99ef055c0b7cc97
/Python/test.py
79962fa6b3f85af8c2097b4558d70c4d88f22526
[]
no_license
enningxie/Coolixz
f181cd1087db9c0d4ad4f7ab80029b88dde82e24
fc51dc894906b2fb7f72ab77511f6daedf00cf0e
refs/heads/master
2021-01-19T05:24:28.569706
2018-02-05T02:28:36
2018-02-05T02:28:36
100,577,964
0
0
null
null
null
null
UTF-8
Python
false
false
240
py
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ if __name__ == '__main__': a = Solution() print(a.twoSum([3, 2, 4], 6))
[ "enningxie@163.com" ]
enningxie@163.com
7d3629f1c0d12a1e3a32eb86aaba950738c69bcf
06ee743cab3e27a68863e69eeff53acc6a7a5b16
/Section 8/mod1.py
e1868e52f4a7b1b2107c86da25146382afaa1ad1
[ "MIT" ]
permissive
buratina/Learning-Python-v-
a424ddeb896dee6d3c37028ec7c1d6e20e5af541
09100a2b5a23a572cb7cdb882197d56e507e3521
refs/heads/master
2022-01-27T01:48:37.459162
2019-05-20T05:30:45
2019-05-20T05:30:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
137
py
#Import module1, module2, module import module1 x = 12 y = 34 print "Sum is ", module1.sum1(x,y) print "Multiple is ", module1.mul1(x,y)
[ "sonalis@packtpub.com" ]
sonalis@packtpub.com
b41c07cadfe74f2c029d6dc4f3735e854d8f72b9
1415fa90c4d86e76d76ead544206d73dd2617f8b
/venv/Lib/site-packages/ursina/collider.py
2e9faf1d9e8b030cc74cb04be91b73ec52f2a709
[ "MIT" ]
permissive
Darpra27/Juego-senales
84ea55aea7c61308ec1821dac9f5a29d2e0d75de
e94bc819e05eff1e0126c094d21ae1ec2a1ef46d
refs/heads/main
2023-04-04T07:27:53.878785
2021-04-09T00:00:44
2021-04-09T00:00:44
353,472,016
0
1
MIT
2021-04-09T00:04:31
2021-03-31T19:46:14
Python
UTF-8
Python
false
false
4,986
py
from panda3d.core import CollisionNode, CollisionBox, CollisionSphere, CollisionPolygon from panda3d.core import NodePath from ursina.vec3 import Vec3 class Collider(NodePath): def __init__(self): super().__init__('box_collider') def show(self): self.visible = True def hide(self): self.visible = False def remove(self): self.node_path.removeNode() @property def visible(self): return self._visible @visible.setter def visible(self, value): if value: self.node_path.show() else: self.node_path.hide() pass class BoxCollider(Collider): def __init__(self, entity, center=(0,0,0), size=(1,1,1)): super().__init__() size = [e/2 for e in size] size = [max(0.001, e) for e in size] # collider needs to have thickness self.shape = CollisionBox(Vec3(center[0], center[1], center[2]), size[0], size[1], size[2]) # self.remove() self.collision_node = CollisionNode('CollisionNode') self.node_path = entity.attachNewNode(self.collision_node) self.node_path.node().addSolid(self.shape) self.visible = False # self.node_path.show() # for some reason self.node_path gets removed after this and can't be shown. class SphereCollider(Collider): def __init__(self, entity, center=(0,0,0), radius=.5): super().__init__() self.shape = CollisionSphere(center[0], center[1], center[2], radius) self.node_path = entity.attachNewNode(CollisionNode('CollisionNode')) self.node_path.node().addSolid(self.shape) self.visible = False class MeshCollider(Collider): def __init__(self, entity, mesh=None, center=(0,0,0)): super().__init__() center = Vec3(center) if mesh == None and entity.model: mesh = entity.model # print('''auto generating mesh collider from entity's mesh''') # from ursina import Mesh # this part is obsolete if I use the old obj loading # if not isinstance(mesh, Mesh): # from ursina import mesh_importer # mesh = eval(mesh_importer.obj_to_ursinamesh(name=mesh.name, save_to_file=False)) # flipped_verts = [v*Vec3(-1,1,1) for v in mesh.vertices] # have to flip it on x axis for some reason # mesh.vertices = flipped_verts self.node_path = entity.attachNewNode(CollisionNode('CollisionNode')) self.node = self.node_path.node() self.collision_polygons = list() if mesh.triangles: for tri in mesh.triangles: if len(tri) == 3: poly = CollisionPolygon( Vec3(mesh.vertices[tri[2]]), Vec3(mesh.vertices[tri[1]]), Vec3(mesh.vertices[tri[0]]), ) self.collision_polygons.append(poly) elif len(tri) == 4: poly = CollisionPolygon( Vec3(mesh.vertices[tri[2]]), Vec3(mesh.vertices[tri[1]]), Vec3(mesh.vertices[tri[0]])) self.collision_polygons.append(poly) poly = CollisionPolygon( Vec3(mesh.vertices[tri[0]]), Vec3(mesh.vertices[tri[3]]), Vec3(mesh.vertices[tri[2]])) self.collision_polygons.append(poly) elif mesh.mode == 'triangle': for i in range(0, len(mesh.vertices), 3): poly = CollisionPolygon( Vec3(mesh.vertices[i+2]), Vec3(mesh.vertices[i+1]), Vec3(mesh.vertices[i]), ) self.collision_polygons.append(poly) else: print('error: mesh collider does not support', mesh.mode, 'mode') return None for poly in self.collision_polygons: self.node.addSolid(poly) self.visible = False if __name__ == '__main__': from ursina import * app = Ursina() e = Entity(model='sphere', x=2) e.collider = 'box' # add BoxCollider based on entity's bounds. e.collider = 'sphere' # add SphereCollider based on entity's bounds. e.collider = 'mesh' # add MeshCollider based on entity's bounds. e.collider = BoxCollider(e, center=Vec3(0,0,0), size=Vec3(1,1,1)) # add BoxCollider at custom positions and size. e.collider = SphereCollider(e, center=Vec3(0,0,0), radius=.75) # add SphereCollider at custom positions and size. e.collider = MeshCollider(e, mesh=e.model, center=Vec3(0,0,0)) # add MeshCollider with custom shape and center. m = Prismatoid(base_shape=Circle(6), thicknesses=(1, .5)) e = Button(parent=scene, model=m, collider='mesh', color=color.red, highlight_color=color.yellow) EditorCamera() app.run()
[ "daviricado08@gmail.com" ]
daviricado08@gmail.com
d09448fdd16e978eecb236531ca79cccec83ff44
87129f66724ab3cc5f2fa8154512eda3b8db527e
/backend/src/zac_lite/wsgi.py
4b5a26ddf95ff2d1630c88b81b431f63734322a9
[]
no_license
GemeenteUtrecht/zac-lite
b6333f5e4f4381f7407af40ceb20e49822f23cee
b4780f0bb7c79d08bef3419ea349c6ef6f328505
refs/heads/main
2023-04-10T16:25:04.172830
2021-04-12T08:24:11
2021-04-12T08:24:11
327,653,824
0
0
null
2021-04-12T08:24:12
2021-01-07T15:38:58
Python
UTF-8
Python
false
false
373
py
""" WSGI config for zac_lite project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from zac_lite.setup import setup_env setup_env() application = get_wsgi_application()
[ "sergei@maykinmedia.nl" ]
sergei@maykinmedia.nl
7bda7a6003400eca0f3f39e23d440fb8177a1306
3a6d4ce215de76616761483d6c77cbcd8c512c85
/navx-examples/navx-rotate-to-angle/robot.py
e40290fc1dedd03bd22f2034262e8b8f82c1ff50
[]
no_license
ThunderDogs5613/examples
133c0d35b72083684b8855a5fb12409e92e89a45
3cb480f22bc3f706d2d93165ae79a228f07b2a41
refs/heads/master
2021-09-29T02:24:39.473867
2018-11-22T20:58:05
2018-11-22T20:58:05
112,538,972
0
1
null
2018-01-22T05:57:19
2017-11-29T23:17:31
Python
UTF-8
Python
false
false
5,867
py
#!/usr/bin/env python3 import wpilib from navx import AHRS class MyRobot(wpilib.SampleRobot): """This is a demo program showing the use of the navX MXP to implement a "rotate to angle" feature. This demo works in the pyfrc simulator. This example will automatically rotate the robot to one of four angles (0, 90, 180 and 270 degrees). This rotation can occur when the robot is still, but can also occur when the robot is driving. When using field-oriented control, this will cause the robot to drive in a straight line, in whatever direction is selected. This example also includes a feature allowing the driver to "reset" the "yaw" angle. When the reset occurs, the new gyro angle will be 0 degrees. This can be useful in cases when the gyro drifts, which doesn't typically happen during a FRC match, but can occur during long practice sessions. Note that the PID Controller coefficients defined below will need to be tuned for your drive system. """ # The following PID Controller coefficients will need to be tuned */ # to match the dynamics of your drive system. Note that the */ # SmartDashboard in Test mode has support for helping you tune */ # controllers by displaying a form where you can enter new P, I, */ # and D constants and test the mechanism. */ # Often, you will find it useful to have different parameters in # simulation than what you use on the real robot if wpilib.RobotBase.isSimulation(): # These PID parameters are used in simulation kP = 0.06 kI = 0.00 kD = 0.00 kF = 0.00 else: # These PID parameters are used on a real robot kP = 0.03 kI = 0.00 kD = 0.00 kF = 0.00 kToleranceDegrees = 2.0 def robotInit(self): # Channels for the wheels frontLeftChannel = 2 rearLeftChannel = 3 frontRightChannel = 1 rearRightChannel = 0 self.myRobot = wpilib.RobotDrive(frontLeftChannel, rearLeftChannel, frontRightChannel, rearRightChannel) self.myRobot.setExpiration(0.1) self.stick = wpilib.Joystick(0) # # Communicate w/navX MXP via the MXP SPI Bus. # - Alternatively, use the i2c bus. # See http://navx-mxp.kauailabs.com/guidance/selecting-an-interface/ for details # self.ahrs = AHRS.create_spi() #self.ahrs = AHRS.create_i2c() turnController = wpilib.PIDController(self.kP, self.kI, self.kD, self.kF, self.ahrs, output=self) turnController.setInputRange(-180.0, 180.0) turnController.setOutputRange(-1.0, 1.0) turnController.setAbsoluteTolerance(self.kToleranceDegrees) turnController.setContinuous(True) self.turnController = turnController self.rotateToAngleRate = 0 # Add the PID Controller to the Test-mode dashboard, allowing manual */ # tuning of the Turn Controller's P, I and D coefficients. */ # Typically, only the P value needs to be modified. */ wpilib.LiveWindow.addActuator("DriveSystem", "RotateController", turnController) def operatorControl(self): """Runs the motors with onnidirectional drive steering. Implements Field-centric drive control. Also implements "rotate to angle", where the angle being rotated to is defined by one of four buttons. Note that this "rotate to angle" approach can also be used while driving to implement "straight-line driving". """ tm = wpilib.Timer() tm.start() self.myRobot.setSafetyEnabled(True) while self.isOperatorControl() and self.isEnabled(): if tm.hasPeriodPassed(1.0): print("NavX Gyro", self.ahrs.getYaw(), self.ahrs.getAngle()) rotateToAngle = False if self.stick.getRawButton(1): self.ahrs.reset() if self.stick.getRawButton(2): self.turnController.setSetpoint(0.0) rotateToAngle = True elif self.stick.getRawButton(3): self.turnController.setSetpoint(90.0) rotateToAngle = True elif self.stick.getRawButton(4): self.turnController.setSetpoint(179.9) rotateToAngle = True elif self.stick.getRawButton(5): self.turnController.setSetpoint(-90.0) rotateToAngle = True if rotateToAngle: self.turnController.enable() currentRotationRate = self.rotateToAngleRate else: self.turnController.disable() currentRotationRate = self.stick.getTwist() # Use the joystick X axis for lateral movement, # Y axis for forward movement, and the current # calculated rotation rate (or joystick Z axis), # depending upon whether "rotate to angle" is active. self.myRobot.mecanumDrive_Cartesian(self.stick.getX(), self.stick.getY(), currentRotationRate, self.ahrs.getAngle()) wpilib.Timer.delay(0.005) # wait for a motor update time def pidWrite(self, output): """This function is invoked periodically by the PID Controller, based upon navX MXP yaw angle input and PID Coefficients. """ self.rotateToAngleRate = output if __name__ == '__main__': wpilib.run(MyRobot)
[ "dustin@virtualroadside.com" ]
dustin@virtualroadside.com
b344f74d00a2db534e6c33965881aa0ad9faf2f5
52a4d282f6ecaf3e68d798798099d2286a9daa4f
/ccmodel/Log.py
f96eae930277139a7ae19462bede266443bd1529
[ "MIT" ]
permissive
bkovitz/FARGish
f0d1c05f5caf9901f520c8665d35780502b67dcc
3dbf99d44a6e43ae4d9bba32272e0d618ee4aa21
refs/heads/master
2023-07-10T15:20:57.479172
2023-06-25T19:06:33
2023-06-25T19:06:33
124,162,924
5
1
null
null
null
null
UTF-8
Python
false
false
3,836
py
# Log.py from __future__ import annotations from dataclasses import dataclass, replace, field, InitVar from typing import Union, List, Tuple, Dict, Set, FrozenSet, Iterator, \ Iterable, Any, NewType, Type, ClassVar, Sequence, Callable, Hashable, \ Collection, Sequence, Literal, Protocol, Optional, TypeVar, IO, \ runtime_checkable from abc import ABC, abstractmethod import csv import sys from contextlib import contextmanager import functools from FMTypes import ADict, Pred, as_pred from Indenting import Indenting, indent from util import short, dict_str, pr, pts _logfile = Indenting(sys.stdout) enabled_for_logging: Set[Callable[[Any], bool]] = set() # TODO Set this up so enabled_for_logging won't get cleared if FARGModel.py # gets imported after you call lenable(). class Loggable(ABC): '''Mix-in for classes that know how to print their own log entries.''' @abstractmethod def log(self, f: Indenting, **kwargs) -> None: '''Called by the 'logging()' context manager to indicate that self should make a log entry. Must print to 'f'.''' pass class LogKwargs(Loggable): name: str = 'LogKwargs' # override def log(self, f: Indenting, **kwargs) -> None: print(self.name, file=f) with indent(f): for k, v in kwargs.items(): if isinstance(v, dict): print(f'{short(k)}=', file=f) with indent(f): pr(v, key=short, file=f) else: print(f'{short(k)}={short(v)}', file=f) def lo(*args, **kwargs) -> None: '''Prints args to log file, at current indentation level.''' print( *(short(a) for a in args), dict_str(kwargs, xform=short), file=logfile() ) def log_to(f: IO) -> None: '''Set logfile to f. Wraps f with Indenting.''' global _logfile _logfile = Indenting(f) def logfile() -> Indenting: global _logfile return _logfile @contextmanager def logging(lg: Union[Loggable, None], *args, **kwargs): # TODO Document how to use this in a 'with' statement. try: if lg is None: lo(*args, **kwargs) elif logging_is_enabled(lg): lg.log(_logfile, *args, **kwargs) with indent(_logfile): yield _logfile finally: pass def lenable(*args: Pred) -> None: '''Enables logging for args.''' for arg in args: enabled_for_logging.add(as_pred(arg)) def ldisable(*args: Pred) -> None: '''Disables logging for args.''' for arg in args: enabled_for_logging.discard(as_pred(arg)) def ldisable_all() -> None: '''Disables all logging.''' enabled_for_logging.clear() def logging_is_enabled(arg: Any) -> bool: '''Is logging enabled for arg?''' return any(pred(arg) for pred in enabled_for_logging) """ pred = as_pred(arg) print('PRED', pred, enabled_for_logging) return ( any(pred(a) for a in enabled_for_logging) or arg in enabled_for_logging ) """ def trace(func): '''Function decorator: prints the name and arguments of the function each time it is called, and prints its return value when it returns. Caution: 'trace' will read generators all the way to their end.''' @functools.wraps(func) def wrapper(*args, **kwargs) -> None: argstring = '' if args: argstring += ', '.join(repr(a) for a in args) if kwargs: if argstring: argstring += ', ' argstring += ', '.join( f'{name}={value}' for name, value in kwargs.items() ) with logging(None, f'{func.__name__}({argstring})'): result = func(*args, **kwargs) lo(f'-> {result}') return result return wrapper
[ "bkovitz@indiana.edu" ]
bkovitz@indiana.edu
c45bf85604631610515f9028eb85fe46ee3a49ea
5c533e2cf1f2fa87e55253cdbfc6cc63fb2d1982
/python/anyons/tree_basis.py
d57797ce89cd2283274045033e722a7aa8cbd6b2
[]
no_license
philzook58/python
940c24088968f0d5c655e2344dfa084deaefe7c6
6d43db5165c9bcb17e8348a650710c5f603e6a96
refs/heads/master
2020-05-25T15:42:55.428149
2018-05-14T03:33:29
2018-05-14T03:33:29
69,040,196
0
1
null
null
null
null
UTF-8
Python
false
false
2,228
py
import numpy as np #Some things to do # 1. implement solovay-ktaev # 2. Try adding poisition information and winding # 3. stratified basis pursuit Id = 0 Tau = 1 amp = 1. vacuumtree = { leaves : [Id] , stalk: [Id,Id] } # _|_ # Stalk always has one more element than leaf examplevector = [( amp , exampletree )] def N(a,b,c): # number of ways a and b can combine into c. We'll work with ising for now where always 0 or 1 pass ''' def split(tree, n, a, b): #anyonic Splitting at leaf n into particle a nd b c = tree.leaves[n] if N(a,b,c): return [(1., {leaves: } )] else: return [(0, {leaves:[], stalk: []} )] pass def fuse(tree, n, c): #anyonic fusing of n and n+1 into c. be careful about the end pass def braidover(tree, n): #braid leaf n and n+1, with n going over n+1 pass def braidunder(tree, n):# braid leaf n and n+1 with n going under n+1 pass def fmove(subtree): #subtree is a -> b,c, ''' def split(tree, n, a, b): c = tree.leaves[n] if N(a,b,c): tree.leaves[n] = a tree.leaves.insert(n+1, b) F = fmatrix(a,b, tree.stalk[n], tree.stalk[n+1]) qamp = F[c,:] # return qamp list with q taking on the vairous value in tree q = Tau tree.stalk.insert(n+1, q) # we insert a new stalk edge before the former n+1 # The actual implementation will be a sum over possible q given by F moves. return tree else: return None def fuse(tree, n , c): stalkparticle = tree.stalk.pop(n+1) #The stalkparticle is changed in the fmove a = tree.leaves.pop(n) b = tree.leaves[n] tree.leaves[n] = c #This is the opposite f-move reuiqred to split return tree def braidover(tree, n): #B - matrix pass def fmatrix(a,b,c,d): #Returns a mtrix in terms of the inner particle. I believe that a is the top man # and that b c fuse first into e which then fuses with d to make a # How in the hell can you do this without getting confused? tau = 0.618 rttau = np.sqrt(tau) if a == Id and b == Tau and c == Tau and d == Tau: return np.array(1) elif a == Tau and b == Tau and c == Tau and d == Tau: return np.array([[tau, rttau], [rttau, -1 * tau]]) # good start would be to build up a tree with splits and then join together in reverse order and see if we get 1.
[ "philip@FartMachine7.local" ]
philip@FartMachine7.local
c7db857cc80d39129ed2c6608d7040403fd984b9
5499e8b91353ef910d2514c8a57a80565ba6f05b
/scripts/component_graph/server/graph/component_graph.py
e792a25bcce753555f21a7253b349da098a6751e
[ "BSD-3-Clause" ]
permissive
winksaville/fuchsia
410f451b8dfc671f6372cb3de6ff0165a2ef30ec
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
refs/heads/master
2022-11-01T11:57:38.343655
2019-11-01T17:06:19
2019-11-01T17:06:19
223,695,500
3
2
BSD-3-Clause
2022-10-13T13:47:02
2019-11-24T05:08:59
C++
UTF-8
Python
false
false
1,281
py
#!/usr/bin/env python3 # Copyright 2019 The Fuchsia Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ComponentGraph is a graph that holds component relationships. Typical example usage: graph = ComponentGraph() graph.add_node(node) graph.add_link(link) graph["node_name"].add_uses(...) graph.export() """ class ComponentGraph: """ A simple graph structure capable of exporting to JSON """ def __init__(self): self.nodes = {} self.links = [] def add_node(self, node): """ Adds a new ComponentNode to the graph. """ self.nodes[node.id] = node def add_link(self, link): """ Adds a new ComponentLink to the graph. """ self.links.append(link) def __getitem__(self, node_id): """ Returns the node in the graph """ return self.nodes[node_id] def export(self): """ Converts the graph structure into a JSON adjacency matrix. """ export_data = {"nodes": [], "links": []} for _, node in self.nodes.items(): export_data["nodes"].append(node.export()) for link in self.links: export_data["links"].append(link.export()) return export_data
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
375c25ad0955bac2eb62c7123fa3445ba179e7c4
89193c99ba40472a376df61a30ae687ca550e813
/verification/src/referee.py
e70efddd011800bdfd79f9e764554ee009e09e8c
[]
no_license
oduvan/crystal-test
d463f206348d5951b7bfcec389e6d55a7623a304
0be4248a2d350bf42a2a8f34f2ae144b49ace26d
refs/heads/master
2021-01-13T02:15:25.189518
2015-05-19T11:27:00
2015-05-19T11:27:00
35,878,207
0
0
null
null
null
null
UTF-8
Python
false
false
221
py
from checkio_referee import RefereeBase import settings_env from tests import TESTS class Referee(RefereeBase): TESTS = TESTS ENVIRONMENTS = settings_env.ENVIRONMENTS DEFAULT_FUNCTION_NAME = "check_line"
[ "bvv.mag@gmail.com" ]
bvv.mag@gmail.com
f913c8d11307552a530ecb452177b6a6b446f154
62179a165ec620ba967dbc20016e890978fbff50
/nncf/telemetry/__init__.py
8219f26d6bd2e2221eceb6fd2bb86a9e1ceb0775
[ "Apache-2.0" ]
permissive
openvinotoolkit/nncf
91fcf153a96f85da166aacb7a70ca4941e4ba4a4
c027c8b43c4865d46b8de01d8350dd338ec5a874
refs/heads/develop
2023-08-24T11:25:05.704499
2023-08-23T14:44:05
2023-08-23T14:44:05
263,687,600
558
157
Apache-2.0
2023-09-14T17:06:41
2020-05-13T16:41:05
Python
UTF-8
Python
false
false
737
py
# Copyright (c) 2023 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 nncf.telemetry.decorator import tracked_function from nncf.telemetry.extractors import TelemetryExtractor from nncf.telemetry.wrapper import telemetry
[ "noreply@github.com" ]
openvinotoolkit.noreply@github.com
01212c407ad4c53e70b18e0f02bde4e24b1e5fbb
3e9bc0c3b8c842fb0c4bb6aa826ec228ce8c3eea
/tenable/cs/usage.py
37cdb7ebaebf303a4d0c88456c60231874da800c
[ "MIT" ]
permissive
starblast/pyTenable
f2f7604ce31c1621cb8fa49effafd046eb2a6cf6
bd6c5b87b0cafe135bfb416dcc94017b135be37b
refs/heads/master
2023-08-05T04:27:08.309535
2021-09-27T15:12:46
2021-09-27T15:12:46
288,222,919
0
0
MIT
2020-08-17T15:54:52
2020-08-17T15:54:51
null
UTF-8
Python
false
false
559
py
''' usage ===== The usage methods allow interaction into ContainerSecurity usage API. Methods available on ``cs.usage``: .. rst-class:: hide-signature .. autoclass:: UsageAPI .. automethod:: stats ''' from .base import CSEndpoint class UsageAPI(CSEndpoint): def stats(self): ''' Returns the usage statistics for ContainerSecurity Returns: dict: The usage statistics information. Examples: >>> stats = cs.usage.stats() ''' return self._api.get('organization-stats').json()
[ "steve@chigeek.com" ]
steve@chigeek.com
f5ba095041d842d48384162dec01056f1ff55719
868ea7968754f77277ce092d318acce58a2ba034
/miragecore/codable/encorder_decorder.py
f9cb343a5c6cf481521b15f97857ba162c36e163
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
shotastage/mirage-django
7bc3cd604166bab2cb9f17757fc0dbef082e9e8a
afdc1ca1fa6db01af174cf31310b6ef690d9254a
refs/heads/master
2021-08-02T04:18:31.461275
2021-07-19T01:53:24
2021-07-19T01:53:24
136,008,405
0
0
Apache-2.0
2021-07-19T01:53:25
2018-06-04T10:20:18
Python
UTF-8
Python
false
false
320
py
""" Mirage Framework decodable.py Created by Shota Shimazu on 2018/07/18 Copyright (c) 2018-2020 Shota Shimazu All Rights Reserved. This software is released under the Apache License, see LICENSE for detail. https://github.com/shotastage/mirageframework/blob/master/LICENSE """ from typing import Callable, NoReturn
[ "hornet.live.mf@gmail.com" ]
hornet.live.mf@gmail.com
5410b6d3b9e08b0e76a90562c24533d867fa65d9
8eeef7742573a8b671648d94e448d5614272c5d6
/core2web/Week4/Day21/octal.py
1d930a000ed7f219c1da6cbc50eafb52a161887d
[]
no_license
damodardikonda/Python-Basics
582d18bc9d003d90b1a1930c68b9b39a85778ea7
fd239722fc6e2a7a02dae3e5798a5f1172f40378
refs/heads/master
2023-01-28T16:22:19.153514
2020-12-11T06:36:49
2020-12-11T06:36:49
270,733,918
0
0
null
null
null
null
UTF-8
Python
false
false
608
py
''' Write a Program to Convert entered Binary Number to Octal Number Input: Binary Number: 1011 Output: Octal Number: 13 ''' num=int(input("enter the number")) if num==0000: print(0) elif num==0001: print(1) elif num==0010: print(2) elif num==0011: print(3) elif num==0100: print(4) elif num==0101: print(5) elif num==0110: print(6) elif num==0100: print(7) elif num==0101: print(8) elif num==0110: print(9) elif num==0111: print("A") elif num==1000: print("B") elif num==1001: print("C") elif num==1010: print("D") elif num==1011: print("E")
[ "damodar2dikonda@gmail.com" ]
damodar2dikonda@gmail.com
b3f407228b3bf4a2bafe117fcb404ee16d24a9e4
485cf3c70fcaa68689a2b690b6465f1d6bcf21bd
/Python_Coding_Tips/Code_py/Code(实例源码及使用说明)/01/09/2.列表中出现次数最多的数字/demo.py
a708aacda0b845533ca5f8d17298971032aac673
[]
no_license
lxz0503/study_20190608
5ffe08c4704bb00ad8d1980baf16b8f5e7135ff4
47c37798140883b8d6dc21ec5da5bc7a20988ce9
refs/heads/master
2022-12-23T17:23:45.039015
2021-06-23T14:50:19
2021-06-23T14:50:19
190,884,812
1
3
null
2022-12-15T23:17:33
2019-06-08T12:22:56
Python
UTF-8
Python
false
false
1,678
py
# *_* coding : UTF-8 *_* # 开发团队 :明日科技 # 开发人员 :Administrator # 开发时间 :2019/7/2 16:43 # 文件名称 :demo.py # 开发工具 :PyCharm listcar = [[837624, "RAV4"], [791275, "途观"], [651090, "索罗德"], [1080757, "福特F系"], [789519, "高尔夫"], [747646, "CR-V"], [1181445, "卡罗拉"]] listcha2 = ['莱科宁 236', '汉密尔顿 158', '维泰尔 214', '维斯塔潘 216', '博塔斯 227'] listcha3 = ['236 莱科宁', '358 汉密尔顿', '294 维泰尔','216 维斯塔潘','227 博塔斯'] listnba = [['哈登', 78, 36.8, 36.1], ['乔治', 77, 36.9, 28.0], ['阿德托昆博', 72, 32.8, 27.7], ['恩比德', 64, 33.7, 27.5], ['詹姆斯', 55, 35.2, 27.4], ['库里',69, 33.8, 27.3]] listnum = [[2, 141, 126, 277, 323], [3, 241, 171, 404, 296], [1, 101, 128, 278, 123]] print(max(listcha2, key=lambda x: x[-3:])) # 输出结果为:莱科宁 236,从字符串倒数第三位开始往后取数值 print(max(listcar)) # 输出结果为:[1181445, '卡罗拉'] print(max(listcar, key=lambda x: x[1])) # 输出结果为:[789519, '高尔夫'] print(max(listnba, key=lambda x: x[3])) # 输出结果为: ['哈登', 78, 36.8, 36.1] print(max(listnba, key=lambda x: (x[2], x[1], x[3]))) # 输出结果为: ['乔治', 77, 36.9, 28.0] print(max(listnba, key=lambda x: x[3]*x[1])) # 输出结果为: ['哈登', 78, 36.8, 36.1] print(max(listnba, key=lambda x: (str(x[3]))[1:])) # 输出结果为:['乔治', 77, 36.9, 28.0] ,8.0 is the max num print(max(listnum, key=lambda x: x[1]+x[2]+x[3]+x[4])) # 输出结果为:[3, 241, 171, 404, 296]
[ "lxz_20081025@163.com" ]
lxz_20081025@163.com
03b75f443fe0c74b0584e2c186ff6af113b969e0
054b665faf3c099efb3e24768b4dcb24e054b011
/flask/bin/migrate
c853a4bffd15a0a7631168ff3f0db0fdb27c76eb
[]
no_license
linqili2006/mywebsite
8cbec2c32e8a38db2e7d5e0e6745800dd09f239a
4ff202d75cab59d507755f48020d02c2ec0a6eb7
refs/heads/master
2020-03-15T11:14:24.543491
2018-05-10T08:31:59
2018-05-10T08:31:59
132,116,788
0
0
null
null
null
null
UTF-8
Python
false
false
178
#!/root/website/flask/bin/python # PBR Generated from u'console_scripts' import sys from migrate.versioning.shell import main if __name__ == "__main__": sys.exit(main())
[ "root@localhost.localdomain" ]
root@localhost.localdomain
f5566764898099ac51713c2da78ad81dc00b50a7
72244ac24e86f9cc57fdd0a123beaa9e262cc620
/assemblyHub/alignabilityTrack.py
6707ce4e9252a7a4d3314a7750616181c3ca63ae
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
lukeping/hal
7defb8e1421fa3c1b56fb77ec3dd146eab4828bc
bb053f7d58bdef7f24e3a0d1eababe0e622219c0
refs/heads/master
2020-12-25T19:58:13.929088
2014-11-07T14:55:55
2014-11-07T14:55:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,069
py
#!/usr/bin/env python #Copyright (C) 2013 by Ngan Nguyen # #Released under the MIT license, see LICENSE.txt """Creating Alignability track for the hubs """ import os from sonLib.bioio import system from jobTree.scriptTree.target import Target class GetAlignability( Target ): def __init__(self, genomedir, genome, halfile): Target.__init__(self) self.genomedir = genomedir self.genome = genome self.halfile = halfile def run(self): outfile = os.path.join(self.genomedir, "%s.alignability.bw" %self.genome) tempwig = os.path.join(self.genomedir, "%s.alignability.wig" %self.genome) system("halAlignability %s %s > %s" %(self.halfile, self.genome, tempwig)) chrsizefile = os.path.join(self.genomedir, "chrom.sizes") system("wigToBigWig %s %s %s" %(tempwig, chrsizefile, outfile)) system("rm -f %s" %tempwig) def writeTrackDb_alignability(f, genome, genomeCount): f.write("track alignability\n") f.write("longLabel Alignability\n") f.write("shortLabel Alignability\n") f.write("type bigWig 0 %d\n" %genomeCount) f.write("group map\n") f.write("visibility dense\n") f.write("windowingFunction Mean\n") f.write("bigDataUrl %s.alignability.bw\n" %genome) f.write("priority 2\n") f.write("autoScale On\n") f.write("maxHeightPixels 128:36:16\n") f.write("graphTypeDefault Bar\n") f.write("gridDefault OFF\n") f.write("color 0,0,0\n") f.write("altColor 128,128,128\n") f.write("viewLimits 0:%d\n" %genomeCount) f.write("html ../documentation/alignability\n") f.write("\n") def addAlignabilityOptions(parser): from optparse import OptionGroup #group = OptionGroup(parser, "ALIGNABILITY", "Alignability: the number of genomes aligned to each position.") group = OptionGroup(parser, "ALIGNABILITY") group.add_option('--alignability', dest='alignability', action='store_true', default=False, help='If specified, make Alignability tracks. Default=%default') parser.add_option_group(group)
[ "nknguyen@soe.ucsc.edu" ]
nknguyen@soe.ucsc.edu
174492e1a8fc7497bcfbb8979de002d22b5437b9
437e905d8c214dc25c559b1dc03eaf9f0c85326f
/is28/makshaev28/Python3/zad6/6.1.py
30b634e6efbbc814074c3373f472ce314eee591f
[]
no_license
AnatolyDomrachev/karantin
542ca22c275e39ef3491b1c0d9838e922423b5a9
0d9f60207e80305eb713fd43774e911fdbb9fbad
refs/heads/master
2021-03-29T03:42:43.954727
2020-05-27T13:24:36
2020-05-27T13:24:36
247,916,390
0
1
null
null
null
null
UTF-8
Python
false
false
286
py
def readData(pathway): dictArr = [] with open(pathway) as file: for line in file: key, *val = line.split() dictArr.append({}.fromkeys(key,val)) return dictArr pathway = "data.txt" dictArr = readData(pathway) for dictionary in dictArr: print(dictionary)
[ "you@example.com" ]
you@example.com
17bba0cb7d382ec41db8243e21d2c386f7efde7a
68adda25dff4b3650e88c495928ecd36b8c037b4
/.vscode/extensions/ms-python.python-2020.7.96456/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_signature.py
268d94417fd908bc56cefc42a054b3d632443649
[ "MIT" ]
permissive
jaeyholic/portfolio-v2
28614ce9ce0a7a450aaa58f36393b95ad3155464
f9cfdd250e0fbde9e91e36d46826700a7c08df62
refs/heads/master
2023-06-24T04:18:27.269996
2020-08-11T14:28:12
2020-08-11T14:28:12
228,602,441
0
0
MIT
2023-06-10T00:47:09
2019-12-17T11:32:20
JavaScript
UTF-8
Python
false
false
7,163
py
from _pydev_bundle import pydev_log try: import trace except ImportError: pass else: trace._warn = lambda *args: None # workaround for http://bugs.python.org/issue17143 (PY-8706) import os from _pydevd_bundle.pydevd_comm import CMD_SIGNATURE_CALL_TRACE, NetCommand from _pydevd_bundle import pydevd_xml from _pydevd_bundle.pydevd_constants import xrange, dict_iter_items from _pydevd_bundle.pydevd_utils import get_clsname_for_code class Signature(object): def __init__(self, file, name): self.file = file self.name = name self.args = [] self.args_str = [] self.return_type = None def add_arg(self, name, type): self.args.append((name, type)) self.args_str.append("%s:%s" % (name, type)) def set_args(self, frame, recursive=False): self.args = [] code = frame.f_code locals = frame.f_locals for i in xrange(0, code.co_argcount): name = code.co_varnames[i] class_name = get_type_of_value(locals[name], recursive=recursive) self.add_arg(name, class_name) def __str__(self): return "%s %s(%s)" % (self.file, self.name, ", ".join(self.args_str)) def get_type_of_value(value, ignore_module_name=('__main__', '__builtin__', 'builtins'), recursive=False): tp = type(value) class_name = tp.__name__ if class_name == 'instance': # old-style classes tp = value.__class__ class_name = tp.__name__ if hasattr(tp, '__module__') and tp.__module__ and tp.__module__ not in ignore_module_name: class_name = "%s.%s" % (tp.__module__, class_name) if class_name == 'list': class_name = 'List' if len(value) > 0 and recursive: class_name += '[%s]' % get_type_of_value(value[0], recursive=recursive) return class_name if class_name == 'dict': class_name = 'Dict' if len(value) > 0 and recursive: for (k, v) in dict_iter_items(value): class_name += '[%s, %s]' % (get_type_of_value(k, recursive=recursive), get_type_of_value(v, recursive=recursive)) break return class_name if class_name == 'tuple': class_name = 'Tuple' if len(value) > 0 and recursive: class_name += '[' class_name += ', '.join(get_type_of_value(v, recursive=recursive) for v in value) class_name += ']' return class_name def _modname(path): """Return a plausible module name for the path""" base = os.path.basename(path) filename, ext = os.path.splitext(base) return filename class SignatureFactory(object): def __init__(self): self._caller_cache = {} self.cache = CallSignatureCache() def create_signature(self, frame, filename, with_args=True): try: _, modulename, funcname = self.file_module_function_of(frame) signature = Signature(filename, funcname) if with_args: signature.set_args(frame, recursive=True) return signature except: pydev_log.exception() def file_module_function_of(self, frame): # this code is take from trace module and fixed to work with new-style classes code = frame.f_code filename = code.co_filename if filename: modulename = _modname(filename) else: modulename = None funcname = code.co_name clsname = None if code in self._caller_cache: if self._caller_cache[code] is not None: clsname = self._caller_cache[code] else: self._caller_cache[code] = None clsname = get_clsname_for_code(code, frame) if clsname is not None: # cache the result - assumption is that new.* is # not called later to disturb this relationship # _caller_cache could be flushed if functions in # the new module get called. self._caller_cache[code] = clsname if clsname is not None: funcname = "%s.%s" % (clsname, funcname) return filename, modulename, funcname def get_signature_info(signature): return signature.file, signature.name, ' '.join([arg[1] for arg in signature.args]) def get_frame_info(frame): co = frame.f_code return co.co_name, frame.f_lineno, co.co_filename class CallSignatureCache(object): def __init__(self): self.cache = {} def add(self, signature): filename, name, args_type = get_signature_info(signature) calls_from_file = self.cache.setdefault(filename, {}) name_calls = calls_from_file.setdefault(name, {}) name_calls[args_type] = None def is_in_cache(self, signature): filename, name, args_type = get_signature_info(signature) if args_type in self.cache.get(filename, {}).get(name, {}): return True return False def create_signature_message(signature): cmdTextList = ["<xml>"] cmdTextList.append('<call_signature file="%s" name="%s">' % (pydevd_xml.make_valid_xml_value(signature.file), pydevd_xml.make_valid_xml_value(signature.name))) for arg in signature.args: cmdTextList.append('<arg name="%s" type="%s"></arg>' % (pydevd_xml.make_valid_xml_value(arg[0]), pydevd_xml.make_valid_xml_value(arg[1]))) if signature.return_type is not None: cmdTextList.append('<return type="%s"></return>' % (pydevd_xml.make_valid_xml_value(signature.return_type))) cmdTextList.append("</call_signature></xml>") cmdText = ''.join(cmdTextList) return NetCommand(CMD_SIGNATURE_CALL_TRACE, 0, cmdText) def send_signature_call_trace(dbg, frame, filename): if dbg.signature_factory and dbg.in_project_scope(frame): signature = dbg.signature_factory.create_signature(frame, filename) if signature is not None: if dbg.signature_factory.cache is not None: if not dbg.signature_factory.cache.is_in_cache(signature): dbg.signature_factory.cache.add(signature) dbg.writer.add_command(create_signature_message(signature)) return True else: # we don't send signature if it is cached return False else: dbg.writer.add_command(create_signature_message(signature)) return True return False def send_signature_return_trace(dbg, frame, filename, return_value): if dbg.signature_factory and dbg.in_project_scope(frame): signature = dbg.signature_factory.create_signature(frame, filename, with_args=False) signature.return_type = get_type_of_value(return_value, recursive=True) dbg.writer.add_command(create_signature_message(signature)) return True return False
[ "gabsco208309@hotmail.com" ]
gabsco208309@hotmail.com
3af64a7476817d44f5c1c389ecec2619a855f37c
e3bdb7844f634efd89109079d22cade713c4899d
/openapi_client/models/china_domestic_payment_method_all_of.py
d1e85677f22b75217f6b845c0fdcc171142030b4
[]
no_license
pc-coholic/Python
5170c27da09b066c353e09539e404961f7ad50b7
b7251c31339b579f71fb7ee9db05be51e9e43361
refs/heads/master
2023-04-19T02:42:02.914726
2021-04-26T16:07:37
2021-04-26T16:07:37
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,597
py
# coding: utf-8 """ Payment Gateway API Specification. The documentation here is designed to provide all of the technical guidance required to consume and integrate with our APIs for payment processing. To learn more about our APIs please visit https://docs.firstdata.com/org/gateway. # noqa: E501 The version of the OpenAPI document: 21.2.0.20210406.001 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six class ChinaDomesticPaymentMethodAllOf(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'china_domestic': 'ChinaDomestic', 'brand': 'str' } attribute_map = { 'china_domestic': 'chinaDomestic', 'brand': 'brand' } def __init__(self, china_domestic=None, brand=None): # noqa: E501 """ChinaDomesticPaymentMethodAllOf - a model defined in OpenAPI""" # noqa: E501 self._china_domestic = None self._brand = None self.discriminator = None self.china_domestic = china_domestic self.brand = brand @property def china_domestic(self): """Gets the china_domestic of this ChinaDomesticPaymentMethodAllOf. # noqa: E501 :return: The china_domestic of this ChinaDomesticPaymentMethodAllOf. # noqa: E501 :rtype: ChinaDomestic """ return self._china_domestic @china_domestic.setter def china_domestic(self, china_domestic): """Sets the china_domestic of this ChinaDomesticPaymentMethodAllOf. :param china_domestic: The china_domestic of this ChinaDomesticPaymentMethodAllOf. # noqa: E501 :type: ChinaDomestic """ if china_domestic is None: raise ValueError("Invalid value for `china_domestic`, must not be `None`") # noqa: E501 self._china_domestic = china_domestic @property def brand(self): """Gets the brand of this ChinaDomesticPaymentMethodAllOf. # noqa: E501 :return: The brand of this ChinaDomesticPaymentMethodAllOf. # noqa: E501 :rtype: str """ return self._brand @brand.setter def brand(self, brand): """Sets the brand of this ChinaDomesticPaymentMethodAllOf. :param brand: The brand of this ChinaDomesticPaymentMethodAllOf. # noqa: E501 :type: str """ if brand is None: raise ValueError("Invalid value for `brand`, must not be `None`") # noqa: E501 allowed_values = ["ALIPAY_DOMESTIC", "CUP_DOMESTIC", "WECHAT_DOMESTIC"] # noqa: E501 if brand not in allowed_values: raise ValueError( "Invalid value for `brand` ({0}), must be one of {1}" # noqa: E501 .format(brand, allowed_values) ) self._brand = brand def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ChinaDomesticPaymentMethodAllOf): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "emargules@bluepay.com" ]
emargules@bluepay.com
e066c3f04af4c6772b63993fed55c0647861a4b5
343bdaddfc66c6316e2cee490e9cedf150e3a5b7
/0901_1000/0951/0951.py
e7f9fed9f28d15532af5a4160d9d71a6b7d91a5c
[]
no_license
dm-alexi/acmp
af7f6b4484b78f5922f3b464406a0ba5dea0d738
3fa0016d132adfeab7937b3e8c9687a34642c93a
refs/heads/master
2021-07-09T15:14:25.857086
2020-10-20T19:08:54
2020-10-20T19:08:54
201,908,038
0
0
null
null
null
null
UTF-8
Python
false
false
765
py
def dist(a, b): return (a[0] - b[0] if a[0] > b[0] else b[0] - a[0]) + (a[1] - b[1] if a[1] > b[1] else b[1] - a[1]) with open("input.txt", "r") as f, open("output.txt", "w") as q: n, m = (int(x) for x in f.readline().split()) tmp = [int(x) for x in f.readline().split()] s = [] for i in range(tmp[0]): s.append((tmp[2 * i + 1], tmp[2 * i + 2])) r = 0 for i in range(1, n + 1): for j in range(1, m + 1): p = dist((i, j), s[0]) if p <= r: continue for k in s[1:]: t = dist((i, j), k) if t < p: p = t if p <= r: break if p > r: r = p q.write(str(r))
[ "dm2.alexi@gmail.com" ]
dm2.alexi@gmail.com
e6af55d946feb8f98d965fcf13999cb498a2ad98
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/127/usersdata/215/35797/submittedfiles/ex11.py
5080aba3b97c0e3a2eedcdeb5b76a3d52f524f79
[]
no_license
rafaelperazzo/programacao-web
95643423a35c44613b0f64bed05bd34780fe2436
170dd5440afb9ee68a973f3de13a99aa4c735d79
refs/heads/master
2021-01-12T14:06:25.773146
2017-12-22T16:05:45
2017-12-22T16:05:45
69,566,344
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
# -*- coding: utf-8 -*- d1=int(input('digite o dia 1')) m1=int(input('digite o mes 1')) a1=int(input('digite o ano 1')) d2=int(input('digite o dia 2')) m2=int(input('digite o mes 1')) a2=int(input('digite o ano 2')) if a1>=a2 and m1>=m2 and d1>=d2: print ('DATA 1') elif a1>=a2 and m2>=m1 and d1>=d2: print ('DATA 1') elif a1>=a2 and m2>=m1 and d2>=d1: print ('DATA 1') else: print ('DATA')
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
e2e289556271d1d8f6936dbf1d0fbfd0537d64f4
f92e2e45fb0b074e16ec1cd97123544c9252b94e
/TF/mnist.py
13ea98e4340590c1a5cd57d70f81235f76e31bc7
[]
no_license
CosmosShadow/ResidualOnMnist
10ef771140bac6b68765030028e31adcec301025
73659a66212e1bc6e0b9cd8cfa45642e4f2560db
refs/heads/master
2021-01-21T15:04:36.162028
2016-10-22T04:31:37
2016-10-22T04:31:37
56,119,484
1
0
null
null
null
null
UTF-8
Python
false
false
3,272
py
# coding: utf-8 import time import tensorflow as tf import prettytensor as pt import numpy as np import cmtf.data.data_mnist as data_mnist @pt.Register def leaky_relu(input_pt): return tf.select(tf.greater(input_pt, 0.0), input_pt, 0.01*input_pt) # 数据 mnist = data_mnist.read_data_sets(one_hot=True) x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None,10]) dropout = tf.placeholder(tf.float32, [1]) x_reshape = tf.reshape(x, [-1, 28, 28, 1]) seq = pt.wrap(x_reshape).sequential() # CNN # seq.conv2d(6, 16) # seq.max_pool(2, 2) # seq.conv2d(6, 16) # seq.max_pool(2, 2) def residual(seq, stride, output): with seq.subdivide_with(2, tf.add_n) as towers: towers[0].conv2d(3, output, stride=stride) towers[1].conv2d(3, output, stride=stride).leaky_relu().conv2d(3, output) seq.leaky_relu() return seq def residual_with_bt(seq, stride, output): with seq.subdivide_with(2, tf.add_n) as towers: towers[0].conv2d(3, output, stride=stride).batch_normalize() towers[1].conv2d(3, output, stride=stride).batch_normalize().leaky_relu().conv2d(3, output).batch_normalize() seq.leaky_relu() return seq # residual with pt.defaults_scope(activation_fn=None, l2loss=1e-3): seq.conv2d(3, 16) seq = residual_with_bt(seq, 2, 16) seq = residual_with_bt(seq, 1, 16) seq = residual_with_bt(seq, 2, 16) seq = residual_with_bt(seq, 1, 16) seq = residual_with_bt(seq, 2, 32) seq.average_pool(4, 4) # seq.dropout(dropout[0]) seq.flatten() seq.fully_connected(10) #TODO: network加上activation_fn=None softmax, loss = seq.softmax_classifier(10, labels=y) accuracy = softmax.evaluate_classifier(y) batch = tf.Variable(0, dtype=tf.float32) learning_rate = tf.train.exponential_decay(0.05, batch * 64, 64*100, 0.995, staircase=True) train_op = tf.train.MomentumOptimizer(learning_rate, 0.9, use_nesterov=True).minimize(loss, global_step=batch) # 正确率 def right_rate(sess, data): accuracy_arr = [] for _ in range(int(data.num_examples/64)): test_x, test_y = data.next_batch(64) acc = sess.run(accuracy, feed_dict={x:test_x, y:test_y, dropout: [1.0]}) accuracy_arr.append(acc) return np.mean(np.array(accuracy_arr)) # GPU使用率 config = tf.ConfigProto() config.gpu_options.per_process_gpu_memory_fraction = 0.6 #固定比例 config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: sess.run(tf.initialize_all_variables()) for epoch in range(50): start_time = time.time() lr = 0 loss_arr = [] for _ in range(100): batch_xs, batch_ys = mnist.train.next_batch(64) _, loss_val, lr = sess.run([train_op, loss, learning_rate], feed_dict={x: batch_xs, y: batch_ys, dropout: [0.7]}) loss_arr.append(loss_val) time_cost = time.time() - start_time accuracy_value = right_rate(sess, mnist.test) loss_mean = np.mean(np.array(loss_arr)) print("epoch: %2d time: %5.3f loss: %5.4f lr: %5.4f right: %5.3f%%" %(epoch, time_cost, loss_mean, lr, accuracy_value*100)) # CNN # time: 2.466 right: 0.365 # time: 1.860 right: 0.605 # time: 1.830 right: 0.745 # time: 1.852 right: 0.86 # time: 1.857 right: 0.885 # Residual # time: 2.199 right: 0.385 # time: 1.596 right: 0.67 # time: 1.592 right: 0.805 # time: 1.621 right: 0.845 # time: 1.634 right: 0.86
[ "lichenarthurml@gmail.com" ]
lichenarthurml@gmail.com
3e4e5112d6660577b0cd6b30656234fba02f0527
27abeacadc88a05b54210ee65c203f967712d71e
/03. Square of Stars.py
b4896e59c44a26a2c894fa03d4eeb70b9df50d5e
[]
no_license
antondelchev/Drawing-Figures-with-Loops---More-Exercises
68952179e35147e2c9e5daccfe72e1d17012675b
0aee91ce01cb697ab6c69773438cae59c6e5983d
refs/heads/main
2023-04-05T15:23:22.021184
2021-04-07T13:19:28
2021-04-07T13:19:28
352,978,303
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
n = int(input()) for rows in range(1, n + 1): for columns in range(1, n + 1): print("*", end=" ") print()
[ "noreply@github.com" ]
antondelchev.noreply@github.com
11f9a1b87a463c583ddae9e86ac7688b707ab299
b46f5825b809c0166622149fc5561c23750b379c
/AppImageBuilder/app_dir/runtimes/wrapper/runtime.py
4b43e5aaed631afe2e5319e816d31fd2f838b053
[ "MIT" ]
permissive
gouchi/appimage-builder
22b85cb682f1b126515a6debd34874bd152a4211
40e9851c573179e066af116fb906e9cad8099b59
refs/heads/master
2022-09-28T09:46:11.783837
2020-06-07T19:44:48
2020-06-07T19:44:48
267,360,199
0
0
MIT
2020-05-27T15:42:25
2020-05-27T15:42:24
null
UTF-8
Python
false
false
2,400
py
# Copyright 2020 Alexis Lopez Zubieta # # 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, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. import logging import os from AppImageBuilder.app_dir.metadata.loader import AppInfoLoader from AppImageBuilder.recipe import Recipe from .app_run import WrapperAppRun from .helpers.factory import HelperFactory class WrapperRuntimeError(RuntimeError): pass class WrapperRuntime(): def __init__(self, recipe: Recipe): self._configure(recipe) self.app_run_constructor = WrapperAppRun self.helper_factory_constructor = HelperFactory def _configure(self, recipe): self.app_dir = recipe.get_item('AppDir/path') self.app_dir = os.path.abspath(self.app_dir) app_info_loader = AppInfoLoader() self.app_info = app_info_loader.load(recipe) self.env = recipe.get_item('AppDir/runtime/env', {}) def generate(self): app_run = self.app_run_constructor(self.app_dir, self.app_info.exec, self.app_info.exec_args) self._configure_runtime(app_run) self._add_user_defined_settings(app_run) app_run.deploy() def _configure_runtime(self, app_run): app_dir_files = self._get_app_dir_file_list() factory = self.helper_factory_constructor(self.app_dir, app_dir_files) for id in factory.list(): h = factory.get(id) h.configure(app_run) def _get_app_dir_file_list(self): app_dir_files = [] for root, dirs, files in os.walk(self.app_dir): for file in files: app_dir_files.append(os.path.join(root, file)) return app_dir_files def _add_user_defined_settings(self, app_run: WrapperAppRun) -> None: for k, v in self.env.items(): if k in app_run.env: logging.info('Overriding runtime env: %s' % k) app_run.env[k] = v
[ "contact@azubieta.net" ]
contact@azubieta.net
6022e6c6abf0a35dedccd7143a06f18591791089
5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d
/alipay/aop/api/domain/AlipayDataDataserviceAdPrincipalCreateormodifyModel.py
9c4e9f5ad05e64e1a503a377d7ce5a54c7482637
[ "Apache-2.0" ]
permissive
alipay/alipay-sdk-python-all
8bd20882852ffeb70a6e929038bf88ff1d1eff1c
1fad300587c9e7e099747305ba9077d4cd7afde9
refs/heads/master
2023-08-27T21:35:01.778771
2023-08-23T07:12:26
2023-08-23T07:12:26
133,338,689
247
70
Apache-2.0
2023-04-25T04:54:02
2018-05-14T09:40:54
Python
UTF-8
Python
false
false
4,120
py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.OuterAttachment import OuterAttachment class AlipayDataDataserviceAdPrincipalCreateormodifyModel(object): def __init__(self): self._alipay_pid = None self._attachment_list = None self._biz_token = None self._principal_id = None self._trade_id = None self._user_id = None @property def alipay_pid(self): return self._alipay_pid @alipay_pid.setter def alipay_pid(self, value): self._alipay_pid = value @property def attachment_list(self): return self._attachment_list @attachment_list.setter def attachment_list(self, value): if isinstance(value, list): self._attachment_list = list() for i in value: if isinstance(i, OuterAttachment): self._attachment_list.append(i) else: self._attachment_list.append(OuterAttachment.from_alipay_dict(i)) @property def biz_token(self): return self._biz_token @biz_token.setter def biz_token(self, value): self._biz_token = value @property def principal_id(self): return self._principal_id @principal_id.setter def principal_id(self, value): self._principal_id = value @property def trade_id(self): return self._trade_id @trade_id.setter def trade_id(self, value): self._trade_id = value @property def user_id(self): return self._user_id @user_id.setter def user_id(self, value): self._user_id = value def to_alipay_dict(self): params = dict() if self.alipay_pid: if hasattr(self.alipay_pid, 'to_alipay_dict'): params['alipay_pid'] = self.alipay_pid.to_alipay_dict() else: params['alipay_pid'] = self.alipay_pid if self.attachment_list: if isinstance(self.attachment_list, list): for i in range(0, len(self.attachment_list)): element = self.attachment_list[i] if hasattr(element, 'to_alipay_dict'): self.attachment_list[i] = element.to_alipay_dict() if hasattr(self.attachment_list, 'to_alipay_dict'): params['attachment_list'] = self.attachment_list.to_alipay_dict() else: params['attachment_list'] = self.attachment_list if self.biz_token: if hasattr(self.biz_token, 'to_alipay_dict'): params['biz_token'] = self.biz_token.to_alipay_dict() else: params['biz_token'] = self.biz_token if self.principal_id: if hasattr(self.principal_id, 'to_alipay_dict'): params['principal_id'] = self.principal_id.to_alipay_dict() else: params['principal_id'] = self.principal_id if self.trade_id: if hasattr(self.trade_id, 'to_alipay_dict'): params['trade_id'] = self.trade_id.to_alipay_dict() else: params['trade_id'] = self.trade_id if self.user_id: if hasattr(self.user_id, 'to_alipay_dict'): params['user_id'] = self.user_id.to_alipay_dict() else: params['user_id'] = self.user_id return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayDataDataserviceAdPrincipalCreateormodifyModel() if 'alipay_pid' in d: o.alipay_pid = d['alipay_pid'] if 'attachment_list' in d: o.attachment_list = d['attachment_list'] if 'biz_token' in d: o.biz_token = d['biz_token'] if 'principal_id' in d: o.principal_id = d['principal_id'] if 'trade_id' in d: o.trade_id = d['trade_id'] if 'user_id' in d: o.user_id = d['user_id'] return o
[ "ben.zy@antfin.com" ]
ben.zy@antfin.com
fb50698f2e658a2c8b2bbdef48d05d351cae9ab8
3b15dc211cb6c034f4d843b1bbc540f1699182f7
/tkinter/Menu单选获取值.py
7d58e46e55f5da2c6c97dd4fc968a7e39d4f800f
[]
no_license
Hanlen520/-
eea27d5a1272272a2f47f9070f285e44300ab0d2
308d3401ff368cd11f4aeac7949d57c3136f2b6e
refs/heads/master
2023-03-15T19:18:25.168665
2020-07-05T14:39:41
2020-07-05T14:39:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
353
py
from tkinter import * root=Tk() menubar=Menu(root) vLang = StringVar() def printItem(): print(vLang.get()) filemenu=Menu(menubar,tearoff=0) for k in ['Python', 'PHP', 'CPP', 'C']: filemenu.add_radiobutton(label=k, command=printItem, variable=vLang) menubar.add_cascade(label='Language', menu=filemenu) root['menu']=menubar root.mainloop()
[ "admiwj@outlook.com" ]
admiwj@outlook.com
8a82008b3ed0ad1d9605193ca8d043dfcd68a0f8
40e29b3ff5699826b8cb0468456beb4aec7d8068
/py_convert_cgi_form_to_array_with_mapping.py
1e3fbb289cd8715ef0f39d66ec93b3a8969daad9
[]
no_license
bahmany/PythonPurePaperless
e52497ef38bb2b51918d83d6f70da7828880e7f8
120e7fcbb79929e80054ce56c6acb8f1da7a7ae0
refs/heads/master
2016-08-12T01:57:39.663947
2015-10-05T06:58:40
2015-10-05T06:58:40
43,624,649
0
0
null
null
null
null
UTF-8
Python
false
false
557
py
def _map(array,Objname,dbname): ar=[] for objar in array: if objar[0]==Objname: objar.append(dbname) ar.append(objar) array=ar def _find_from_field_name(array,fieldname): a="" for obj in array: if len(obj)==3: if obj[2]==fieldname: a=obj[1] return a def _change_array_value(array,ObjectName,newValue): ar=[] for objar in array: if objar[0]==ObjectName: objar[1]==newValue ar.append(objar) array=ar
[ "bahmanymb@gmail.com" ]
bahmanymb@gmail.com
76de469c09aefb57475401227a52fa98bb05a2e6
e01c5d1ee81cc4104b248be375e93ae29c4b3572
/Sequence5/CTCI/4-tree-graph/main/trie.py
4717197d857d5735d2b31cd78b1cbc42fd5a0012
[]
no_license
lalitzz/DS
7de54281a34814601f26ee826c722d123ee8bd99
66272a7a8c20c0c3e85aa5f9d19f29e0a3e11db1
refs/heads/master
2021-10-14T09:47:08.754570
2018-12-29T11:00:25
2018-12-29T11:00:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,066
py
class Node: def __init__(self, data = None): self.data = data self.isEndOfWord = False self.children = [None] * 26 def is_it_free(self): for i in self.data: if self.children is not None: return False return True class Trie: def __init__(self): self.root = Node() def char_to_index(self, c): return ord(c) - ord('a') def insert(self, s): self._insert(self.root, s) def _insert(self, root, s): level = 0 n = len(s) crawler = root for level in range(n): index = self.char_to_index(s[level]) if not crawler.children[index]: crawler.children[index] = Node(s[level]) crawler = crawler.children[index] crawler.isEndOfWord = True def search(self, s): crawler = self.root n = len(s) for level in range(n): index = self.char_to_index(s[level]) if crawler.children[index] is None: return False crawler = crawler.children[index] return crawler is not None and crawler.isEndOfWord def delete(self, s): n = len(s) if n > 0: self._delete(self.root, s, 0, n) def _delete(self, root, s, level, n): if root: if level == n: if root.isEndOfWord: root.isEndOfWord = False return root.is_it_free() else: index = self.char_to_index(s[level]) if self._delete(root.children[index], s, level + 1, n): root.children[index] = None return root.isEndOfWord and root.is_it_free() return False def main(): keys = ["the","a","there","anaswe","any", "by","their"] output = ["Not present in trie", "Present in tire"] t = Trie() for key in keys: t.insert(key) t.delete("the") # Search for different keys print("{} ---- {}".format("the",output[t.search("the")])) print("{} ---- {}".format("these",output[t.search("these")])) print("{} ---- {}".format("their",output[t.search("their")])) print("{} ---- {}".format("thaw",output[t.search("thaw")])) if __name__ == '__main__': main()
[ "lalit.slg007@gmail.com" ]
lalit.slg007@gmail.com
fcf0093fe09b43356fb7b8184253abd384200e97
84f9ae843bbc37a18145840fa4da348a915af1c3
/renpy/versions.py
ec23077062ba1061b8bc251d74930e1814858373
[]
no_license
SpikyCaterpillar/renpy
c25b28c37be46f28ce413f09754f60eb63cca1f1
a33f891d65d3fd2b59a533c365800a59f8e15f0c
refs/heads/master
2023-06-22T18:02:57.826729
2023-06-03T22:39:11
2023-06-07T23:55:48
37,309,831
0
0
null
2015-06-12T08:01:01
2015-06-12T08:01:01
null
UTF-8
Python
false
false
5,115
py
# Copyright 2004-2023 Tom Rothamel <pytom@bishoujo.us> # # 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, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following 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 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from __future__ import division, absolute_import, with_statement, print_function, unicode_literals from renpy.compat import PY2, basestring, bchr, bord, chr, open, pystr, range, round, str, tobytes, unicode # * py_branch_to_version = { } import sys import os class Version(object): def __init__(self, branch, python, version, name): """ `branch` The name of the branch, as a string. `python` The version of python, 2 or 3. `version` The Ren'Py version number, a string. `name` The Ren'Py version name. """ self.branch = branch self.python = python self.version = version self.name = name py_branch_to_version[(python, branch)] = self Version("main", 3, "8.2.0", "TBD") Version("main", 2, "7.7.0", "TBD") Version("fix", 3, "8.1.1", "Where No One Has Gone Before") Version("fix", 2, "7.6.1", "To Boldy Go") def make_dict(branch, suffix="00000000", official=False, nightly=False): """ Returns a dictionary that contains the information usually stored in vc_version.py. `branch` The branch. `suffix` The suffix, normally the YYMMDDCC code. `official` True if this is an official release. `nightly` True if this is a nightly release. """ py = sys.version_info.major version = py_branch_to_version.get((py, branch)) or py_branch_to_version[(py, "main")] return { "version" : version.version + "." + str(suffix), "version_name" : version.name, "official" : official, "nightly" : nightly, "branch" : branch, } def get_version(): """ Tries to return a version dict without using the information in vc_version. """ import re git_head = os.path.join(os.path.dirname(__file__), "..", ".git", "HEAD") branch = "main" try: for l in open(git_head, "r"): l = l.rstrip() m = re.match(r"ref: refs/heads/(.*)", l) if m: branch = m.group(1) break except: import traceback traceback.print_exc() return make_dict(branch) def generate_vc_version(nightly=False): """ Generates the vc_version.py file. `nightly` If true, the nightly flag is set. """ import subprocess import collections import socket import time try: branch = subprocess.check_output([ "git", "branch", "--show-current" ]).decode("utf-8").strip() s = subprocess.check_output([ "git", "describe", "--tags", "--dirty", ]).decode("utf-8").strip() parts = s.strip().split("-") dirty = "dirty" in parts commits_per_day = collections.defaultdict(int) for i in subprocess.check_output([ "git", "log", "-99", "--pretty=%cd", "--date=format:%Y%m%d" ]).decode("utf-8").split(): commits_per_day[i[2:]] += 1 if dirty: key = time.strftime("%Y%m%d")[2:] vc_version = "{}{:02d}".format(key, commits_per_day[key] + 1) else: key = max(commits_per_day.keys()) vc_version = "{}{:02d}".format(key, commits_per_day[key]) except Exception: branch = "main" vc_version = "00000000" official = False version_dict = make_dict( branch, suffix=vc_version, official=socket.gethostname() == "eileen", nightly=nightly) vc_version_fn = os.path.join(os.path.dirname(__file__), "vc_version.py") with open(vc_version_fn, "w") as f: for k, v in sorted(version_dict.items()): f.write("{} = {!r}\n".format(k, v)) return version_dict def main(): import argparse ap = argparse.ArgumentParser() ap.add_argument("--nightly", action="store_true", help="Set the nightly flag.") args = ap.parse_args() generate_vc_version(nightly=args.nightly) if __name__ == "__main__": main()
[ "pytom@bishoujo.us" ]
pytom@bishoujo.us
25e4b04edb8e34498ca234163aa276d6638a1f1d
5e2dddce9c67d5b54d203776acd38d425dbd3398
/spacy/tests/lang/nb/test_tokenizer.py
277df5cf27b18b206764e63c2f05bf7d532341b1
[ "MIT" ]
permissive
yuxuan2015/spacy_zh_model
8164a608b825844e9c58d946dcc8698853075e37
e89e00497ab3dad0dd034933e25bc2c3f7888737
refs/heads/master
2020-05-15T11:07:52.906139
2019-08-27T08:28:11
2019-08-27T08:28:11
182,213,671
1
0
null
2019-04-19T06:27:18
2019-04-19T06:27:17
null
UTF-8
Python
false
false
653
py
# coding: utf8 from __future__ import unicode_literals import pytest NB_TOKEN_EXCEPTION_TESTS = [ ('Smørsausen brukes bl.a. til fisk', ['Smørsausen', 'brukes', 'bl.a.', 'til', 'fisk']), ('Jeg kommer først kl. 13 pga. diverse forsinkelser', ['Jeg', 'kommer', 'først', 'kl.', '13', 'pga.', 'diverse', 'forsinkelser']) ] @pytest.mark.parametrize('text,expected_tokens', NB_TOKEN_EXCEPTION_TESTS) def test_tokenizer_handles_exception_cases(nb_tokenizer, text, expected_tokens): tokens = nb_tokenizer(text) token_list = [token.text for token in tokens if not token.is_space] assert expected_tokens == token_list
[ "yuxuan2015@example.com" ]
yuxuan2015@example.com
0131f9573ecd5c64254a626cb149b58db8e87cd1
3a891a79be468621aae43defd9a5516f9763f36e
/desktop/core/ext-py/Django-1.11/tests/migrate_signals/custom_migrations/0001_initial.py
6e969d29ed9eadeeb6d1d1f49bb1697fb1219836
[ "BSD-3-Clause", "Python-2.0", "Apache-2.0" ]
permissive
oyorooms/hue
b53eb87f805063a90f957fd2e1733f21406269aa
4082346ef8d5e6a8365b05752be41186840dc868
refs/heads/master
2020-04-15T20:31:56.931218
2019-01-09T19:02:21
2019-01-09T19:05:36
164,998,117
4
2
Apache-2.0
2019-01-10T05:47:36
2019-01-10T05:47:36
null
UTF-8
Python
false
false
327
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): operations = [ migrations.CreateModel( "Signal", [ ("id", models.AutoField(primary_key=True)), ], ), ]
[ "ranade@cloudera.com" ]
ranade@cloudera.com
a79c7d60c970db8fa04bb018814a199f3284ebf0
c7adccf0aeb52a3fba4345c6b9ca5e627718065a
/tactics/heartbeat/config.py
aa30fa8885be2b8aa2154062376d8161a730e136
[]
no_license
2020saurav/cs654
b23349f07cf45b44f0de3a2fc204b46b3b3f06ff
c8d7bb19480b0e2b7471adc41d3782e5ed2ee176
refs/heads/master
2021-01-21T03:37:47.715145
2016-04-12T08:12:07
2016-04-12T08:12:07
49,427,568
0
0
null
null
null
null
UTF-8
Python
false
false
330
py
slaves = [ {'name': 'S01', 'ip': '172.17.0.2', 'alive': True, 'lastSeen': 0, 'info': ''}, {'name': 'S02', 'ip': '172.17.0.3', 'alive': True, 'lastSeen': 0, 'info': ''}, {'name': 'S03', 'ip': '172.17.0.4', 'alive': True, 'lastSeen': 0, 'info': ''}, {'name': 'S04', 'ip': '172.24.1.62', 'alive': True, 'lastSeen': 0, 'info': ''}, ]
[ "2020saurav@gmail.com" ]
2020saurav@gmail.com
3cba78a67581f98314362474a956c39ec5647590
0f224fb062a50179db3ab146704807c24b9e8adb
/semana_4/cajero.py
fe4beeece4bd7f448af951f57fd4eaf71b197353
[]
no_license
Ingrid-Nataly-Cruz-Espinosa/POO1719110501
a893b12044dac096f73749c49abde5063dbfd921
dbb56d7824d474141e901c210269924c3b054f40
refs/heads/master
2022-11-15T16:03:38.826941
2020-06-29T03:12:28
2020-06-29T03:12:28
266,243,940
0
0
null
null
null
null
UTF-8
Python
false
false
1,331
py
class cajero: funciones= 10 confidencial= "si" impreciondebaucher= "si" depositobilletes= 1 depositodemonedas= 1 lectordetarjeta= 1 funcional= "si" def deposito(self): print("Realiza depositos") def retiros(self): print("Permite realizar retiros") def movimientos(self): print("Realiza movimientos bancarios") def __init__(self): pass class BBVA(cajero): retiro= "sin tarjeta" def electricidad(self): print("Necesita electricidad") def dinero(self): print("Necesita dinero para funcionar") def __init__(self): print("BBVA") def deposito(self): print("Realiza depositos de manera rapida") def retiros(self): print("Realiza retiros con nostros") def electricidad(self): print("Nesitamos de lectricidad para funcionar") def dinero(self): print("Necesito de tu dinero para funcionar") objeto =BBVA() print("Funciones: "+str(objeto.funciones)) print("Confidencial: "+str(objeto.confidencial)) print("Imprenta de baucher: "+str(objeto.impreciondebaucher)) print("Deposito billetes: "+str(objeto.depositobilletes)) print("Lector de tarjetas:"+str(objeto.lectordetarjeta)) print("Funciones"+str(objeto.funcional)) print("Retiro"+str(objeto.retiro)) objeto.deposito() objeto.retiros() objeto.movimientos() objeto.electricidad() objeto.dinero()
[ "replituser@example.com" ]
replituser@example.com
863139dcbef24e57d9a46b5fe974f2272961c565
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p02642/s367328349.py
5d60772f5492037165490a21e9755fd531c94352
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
252
py
from collections import Counter N = int(input()) A = list(map(int, input().split())) counter = Counter(A) B = [1] * (max(A) + 1) for a in A: for k in range(a * 2,len(B),a): B[k] = 0 print(sum(B[a] == 1 and counter[a] == 1 for a in A))
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
32895f795a3465ccedef0e785819901ee601174c
0809673304fe85a163898983c2cb4a0238b2456e
/src/lesson_the_internet/http_server_send_header.py
fe77556ead80b5ae58e996feb8c3af57f6a53556
[ "Apache-2.0" ]
permissive
jasonwee/asus-rt-n14uhp-mrtg
244092292c94ff3382f88f6a385dae2aa6e4b1e1
4fa96c3406e32ea6631ce447db6d19d70b2cd061
refs/heads/master
2022-12-13T18:49:02.908213
2018-10-05T02:16:41
2018-10-05T02:16:41
25,589,776
3
1
Apache-2.0
2022-11-27T04:03:06
2014-10-22T15:42:28
Python
UTF-8
Python
false
false
665
py
from http.server import BaseHTTPRequestHandler import time class GetHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header( 'Content-Type', 'text/plain; charset=utf-8', ) self.send_header( 'Last-Modified', self.date_time_string(time.time()) ) self.end_headers() self.wfile.write('Response body\n'.encode('utf-8')) if __name__ == '__main__': from http.server import HTTPServer server = HTTPServer(('localhost', 8080), GetHandler) print('Starting server, use <Ctrl-C> to stop') server.serve_forever()
[ "peichieh@gmail.com" ]
peichieh@gmail.com
0fc244e503959adb19c98295dfc7bd871d07a4ed
b501a5eae1018c1c26caa96793c6ee17865ebb2d
/data_persistence_and_exchange/xml_etree_ElementTree/ElementTree_entity_references.py
9cfbbe80d1b38676bed2848c70993ab57864cb5c
[]
no_license
jincurry/standard_Library_Learn
12b02f9e86d31ca574bb6863aefc95d63cc558fc
6c7197f12747456e0f1f3efd09667682a2d1a567
refs/heads/master
2022-10-26T07:28:36.545847
2018-05-04T12:54:50
2018-05-04T12:54:50
125,447,397
0
1
null
2022-10-02T17:21:50
2018-03-16T01:32:50
Python
UTF-8
Python
false
false
245
py
from xml.etree import ElementTree with open('data.xml', 'rt') as f: tree = ElementTree.parse(f) node = tree.find('entity_expansion') print(node.tag) print(' in attribute:', node.attrib['attribute']) print(' in text :', node.text.strip())
[ "jintao422516@gmail.com" ]
jintao422516@gmail.com
86c41feb00f7326194e0094ff9aefcf96757f082
f3b233e5053e28fa95c549017bd75a30456eb50c
/bace_input/L7I/7I-24_wat_20Abox/set_1ns_equi_m.py
0f8487b5991bd7e15bf5f7e09c94cbac671bc3da
[]
no_license
AnguseZhang/Input_TI
ddf2ed40ff1c0aa24eea3275b83d4d405b50b820
50ada0833890be9e261c967d00948f998313cb60
refs/heads/master
2021-05-25T15:02:38.858785
2020-02-18T16:57:04
2020-02-18T16:57:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
923
py
import os dir = '/mnt/scratch/songlin3/run/bace/L7I/wat_20Abox/ti_one-step/7I_24/' filesdir = dir + 'files/' temp_equiin = filesdir + 'temp_equi_m.in' temp_pbs = filesdir + 'temp_1ns_equi_m.pbs' lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078] for j in lambd: os.system("rm -r %6.5f" %(j)) os.system("mkdir %6.5f" %(j)) os.chdir("%6.5f" %(j)) os.system("rm *") workdir = dir + "%6.5f" %(j) + '/' #equiin eqin = workdir + "%6.5f_equi_m.in" %(j) os.system("cp %s %s" %(temp_equiin, eqin)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, eqin)) #PBS pbs = workdir + "%6.5f_1ns_equi.pbs" %(j) os.system("cp %s %s" %(temp_pbs, pbs)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs)) #top os.system("cp ../7I-24_merged.prmtop .") os.system("cp ../0.5_equi_0_3.rst .") #submit pbs os.system("qsub %s" %(pbs)) os.chdir(dir)
[ "songlin3@msu.edu" ]
songlin3@msu.edu
f75968f315b047d150424d9582045e1dc5e996c1
83d67edb5dfcfdc202098a55a3ff7579ca976f16
/paperboy/resources/login.py
82b6be4b2520d6e2d07e930cdab1acc2eb48d5de
[ "Apache-2.0" ]
permissive
huxh/paperboy
2e5e4042d3dcf13f0233995bf6df6ac2af7903c9
1efb62d3493f8816c625764b6afed178ca26c6b2
refs/heads/master
2020-05-19T09:45:16.791969
2019-04-24T13:17:43
2019-04-24T13:17:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,043
py
import falcon import jinja2 from .base import BaseResource from .html import read class LoginResource(BaseResource): '''Falcon resource for user authentication''' auth_required = False def __init__(self, *args, **kwargs): super(LoginResource, self).__init__(*args, **kwargs) def on_get(self, req, resp): resp.content_type = 'text/html' file = read('login.html') tpl = jinja2.Template(file).render(baseurl=self.config.baseurl, apiurl=self.config.apiurl, loginurl=self.config.loginurl, include_register=self.config.include_register, registerurl=self.config.registerurl, include_password=self.config.include_password) resp.body = tpl def on_post(self, req, resp): token = self.db.users.login(None, req.params, self.session) user = self.db.users.detail(token, req.params, self.session) if token and user: req.context['auth_token'] = token req.context['user'] = user resp.set_cookie('auth_token', token, max_age=self.config.token_timeout, path='/', secure=not self.config.http) resp.status = falcon.HTTP_302 resp.set_header('Location', self.config.baseurl) else: resp.content_type = 'text/html' file = read('login.html') tpl = jinja2.Template(file).render(baseurl=self.config.baseurl, apiurl=self.config.apiurl, loginurl=self.config.loginurl, include_register=self.config.include_register, registerurl=self.config.registerurl, include_password=self.config.include_password) resp.body = tpl
[ "t.paine154@gmail.com" ]
t.paine154@gmail.com
37eb684d780cc12846b20ae5ebb7667e8aa07fb7
2951174fd6d8a7cf9a71e0663ae3b22bd309be5a
/LianJia/LianJia/items.py
dc87d5a8c3eb890a29768662baa7d86e9e41b799
[]
no_license
WhiteBrownBottle/Python-
c76045a3127723666083cee4b4c20b08491e4067
92fcaba555a566eae829ea401a20f459b4f39dfe
refs/heads/master
2021-07-18T21:17:45.677091
2017-10-24T06:47:38
2017-10-24T06:47:38
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,629
py
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class XiaoquItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() 建筑年代 = scrapy.Field() 建筑类型 = scrapy.Field() 物业费用 = scrapy.Field() 物业公司 = scrapy.Field() 开发商 = scrapy.Field() 楼栋总数 = scrapy.Field() 房屋总数 = scrapy.Field() 附近门店 = scrapy.Field() 小区 = scrapy.Field() 小区均价 = scrapy.Field() 小区坐标 = scrapy.Field() 小区链接 = scrapy.Field() 大区 = scrapy.Field() 片区 = scrapy.Field() class ZaishouItem(scrapy.Item): 标题 = scrapy.Field() 总价 = scrapy.Field() 单价 = scrapy.Field() 链家编号 = scrapy.Field() 小区 = scrapy.Field() 房屋链接 = scrapy.Field() 关注 = scrapy.Field() 带看 = scrapy.Field() 房屋户型 = scrapy.Field() 所在楼层 = scrapy.Field() 建筑面积 = scrapy.Field() 户型结构 = scrapy.Field() 套内面积 = scrapy.Field() 建筑类型 = scrapy.Field() 房屋朝向 = scrapy.Field() 建筑结构 = scrapy.Field() 装修情况 = scrapy.Field() 梯户比例 = scrapy.Field() 配备电梯 = scrapy.Field() 产权年限 = scrapy.Field() 挂牌时间 = scrapy.Field() 交易权属 = scrapy.Field() 上次交易 = scrapy.Field() 房屋用途 = scrapy.Field() 房屋年限 = scrapy.Field() 产权所属 = scrapy.Field() 抵押信息 = scrapy.Field() 房本备件 = scrapy.Field() class ChengjiaoItem(scrapy.Item): 标题 = scrapy.Field() 总价 = scrapy.Field() 单价 = scrapy.Field() 小区 = scrapy.Field() 成交日期 = scrapy.Field() 房屋链接 = scrapy.Field() 关注 = scrapy.Field() 带看 = scrapy.Field() 房屋户型 = scrapy.Field() 所在楼层 = scrapy.Field() 建筑面积 = scrapy.Field() 户型结构 = scrapy.Field() 套内面积 = scrapy.Field() 建筑类型 = scrapy.Field() 房屋朝向 = scrapy.Field() 建成年代 = scrapy.Field() 装修情况 = scrapy.Field() 建筑结构 = scrapy.Field() 供暖方式 = scrapy.Field() 梯户比例 = scrapy.Field() 产权年限 = scrapy.Field() 配备电梯 = scrapy.Field() 链家编号 = scrapy.Field() 交易权属 = scrapy.Field() 挂牌时间 = scrapy.Field() 房屋用途 = scrapy.Field() 房屋年限 = scrapy.Field() 房权所属 = scrapy.Field()
[ "958255724@qq.com" ]
958255724@qq.com
fc8a5843e331c76bd095b8a976be36be7caf658e
99b0631baa2fd9ab2455d848b47febf581916272
/zhijieketang/chapter22/ch22.1.3.py
d2996eaa8d2b7a385f87b94d7e118c08e5dd0876
[]
no_license
seceast/PyProjects
a934e366cb619f2610d75b9a0fb47d818814a4de
7be7193b4126ce920a3d3ffa4ef5d8743b3fa7d1
refs/heads/master
2023-03-07T22:23:21.229489
2021-02-25T05:37:58
2021-02-25T05:37:58
265,480,151
0
0
null
null
null
null
UTF-8
Python
false
false
546
py
# coding=utf-8 # 代码文件:chapter22/ch22.1.3.py import matplotlib.pyplot as plt # 设置中文字体 plt.rcParams['font.family'] = ['SimHei'] x = [5, 4, 2, 1] # x轴坐标数据 y = [7, 8, 9, 10] # y轴坐标数据 # 绘制线段 plt.plot(x, y, 'b', label='线1', linewidth=2) plt.title('绘制折线图') # 添加图表标题 plt.ylabel('y轴') # 添加y轴标题 plt.xlabel('x轴') # 添加x轴标题 plt.legend() # 设置图例 # 以分辨率 72 来保存图片 plt.savefig('折线图', dpi=72) plt.show() # 显示图形
[ "yangyadong25@163.com" ]
yangyadong25@163.com
0653a8f2b6b26645f6a51c85216908117628aa4e
6a256c5a3506b333c3020be45e38d11b4a81a181
/dbcrud_setupdb.py
8dcff83d9332aa3df409cc51f6a1fa2ab78180b2
[]
no_license
courses-learning/python-and-flask-bootcamp
892992d65ee0758f6c9a4339374b60c7928f47b7
887bf917659ea6cefba53b78ba433599626baaf6
refs/heads/master
2020-06-13T02:52:57.408008
2019-08-20T19:51:26
2019-08-20T19:51:26
194,508,905
1
0
null
null
null
null
UTF-8
Python
false
false
292
py
from dbcrud_practice import db, Animal db.create_all() polar_bear = Animal('Polar Bear', 'Rex', 12) elephant = Animal('Elephant', 'Ethel', 23) print(polar_bear.id) print(elephant.id) db.session.add_all([polar_bear, elephant]) db.session.commit() print(polar_bear.id) print(elephant.id)
[ "david_weatherspoon@hotmail.com" ]
david_weatherspoon@hotmail.com
119bfbbf3b103a5a63f75ab0d96133ad3b9a07a6
0836b2b426d39fbcdde073eca4cab0de74452ff3
/config/urls.py
05e68bdc5d869bff17bd586a56862f154a665d68
[ "MIT" ]
permissive
vaibhav-rbs/mordern-django
89d6d78ce472bd1b6bd895bccb579507119446e9
a8badd950860bfcf44b9fa9256fe52f810461cd9
refs/heads/master
2020-03-19T10:01:46.739749
2018-06-06T14:16:42
2018-06-06T14:16:42
136,337,130
0
0
null
null
null
null
UTF-8
Python
false
false
818
py
"""config URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]
[ "vaibhav.rbs@gmail.com" ]
vaibhav.rbs@gmail.com
348b1ed480ccec8944ce408b739ca93db447c81c
92925ea36a241156c923262f7aeea86ce53cb356
/dashboard/network/urls.py
8a44d0af6cc46e843bb9faf8af663c6e61994aa3
[]
no_license
greshem/openstack_bootstrap_dashboard
c839bfb86f8b1f0b8fee602c1363f061ca65ef55
7dfda640740507199b291d01cb8304df570f2664
refs/heads/master
2021-07-10T00:44:10.875699
2017-10-08T15:39:43
2017-10-08T15:39:43
106,177,117
0
0
null
null
null
null
UTF-8
Python
false
false
342
py
from django.conf.urls import include, url, patterns #from dashboard.admin.urls import * from dashboard.network import views urlpatterns = patterns('network.views', #url(r'^admin/accounts', 'account_manage',name='account_manage'), url(r'^floating_ips/$', views.FloatingView.as_view(), name='floating_ips'), )
[ "qianzhongjie@gmail.com" ]
qianzhongjie@gmail.com
1128f2bae873af1b8e095dcb14155fd61dc444a3
343bdaddfc66c6316e2cee490e9cedf150e3a5b7
/0001_0100/0049/0049.py
c1cb09e0bcced0985fff970a4b142c6c54f11df6
[]
no_license
dm-alexi/acmp
af7f6b4484b78f5922f3b464406a0ba5dea0d738
3fa0016d132adfeab7937b3e8c9687a34642c93a
refs/heads/master
2021-07-09T15:14:25.857086
2020-10-20T19:08:54
2020-10-20T19:08:54
201,908,038
0
0
null
null
null
null
UTF-8
Python
false
false
383
py
with open("input.txt", "r") as f, open("output.txt", "w") as q: s = f.readline().strip() t = f.readline().strip() d = {str(a) : {a} for a in range(0, 10)} d.update({x : {i, i + 1, i + 2, i + 3} for i, x in enumerate("abcdefg")}) d['?'] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} k = 1 for i in range(len(s)): k *= len(d[s[i]] & d[t[i]]) q.write(str(k))
[ "dm2.alexi@gmail.com" ]
dm2.alexi@gmail.com
57e0e3b6981025edaa853be0c370f512a118861a
2da6133f3cd5c5fc19355292d60253b8c0dbcd49
/.history/antz/models_20200403232431.py
47e39abe702fb2fcc845de299cd35ceef9e0de34
[]
no_license
mirfarzam/python-advance-jadi-maktabkhooneh
b24f5c03ab88e3b12c166a439b925af92f50de49
d9bcecae73fd992f1290c6fd76761683bb512825
refs/heads/master
2021-05-25T21:33:37.782734
2020-04-07T22:39:28
2020-04-07T22:39:28
253,927,960
0
0
null
null
null
null
UTF-8
Python
false
false
237
py
from django.db import models class CardBrand(models.Model): name = models.charField(max_length=128) class CarModel(models.Model): name = models.charField(max_length=128) brand = models.ForeignKey(CarBrand, on_delete =)
[ "farzam.mirmoeini@gmail.com" ]
farzam.mirmoeini@gmail.com
f372b331e72a115fd209f4b9a9dd9c9996435f7f
d7b9b490c954c7a9160b69f8ce2c907ef4681ecb
/sponsors/migrations/0082_auto_20220729_1613.py
116b4a011a7c19ecaadc2eb8825056540ddd92d6
[ "Apache-2.0" ]
permissive
python/pythondotorg
00db93a4b1789a4d438806d106d9cee3349ad78c
c4ee749942227ca75c8e670546afe67232d647b2
refs/heads/main
2023-08-28T20:04:24.735314
2023-08-03T19:12:29
2023-08-03T19:12:29
6,127,047
1,131
646
Apache-2.0
2023-08-24T15:57:04
2012-10-08T16:00:15
Python
UTF-8
Python
false
false
388
py
# Generated by Django 2.2.24 on 2022-07-29 16:13 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sponsors', '0081_sponsorship_application_year'), ] operations = [ migrations.RenameField( model_name='sponsorship', old_name='application_year', new_name='year', ), ]
[ "noreply@github.com" ]
python.noreply@github.com
ab3f40580aa1e1501a9141f7756798def857e807
43d8fd08c95ab0b7d73c4ab78529fdd5b0278892
/kubernetes/client/models/v1_replica_set_condition.py
ba8505dd99ac2b58ebae2875dff7b1c285eedd6b
[ "Apache-2.0" ]
permissive
btaba/python
7d160b26ea02f668e599857bb3913276213a54f7
08561d6477e9be1b39d67ea51dc024a4899fcc07
refs/heads/master
2020-04-01T11:47:59.498995
2018-10-13T19:03:25
2018-10-13T19:03:25
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,580
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.12.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class V1ReplicaSetCondition(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'last_transition_time': 'datetime', 'message': 'str', 'reason': 'str', 'status': 'str', 'type': 'str' } attribute_map = { 'last_transition_time': 'lastTransitionTime', 'message': 'message', 'reason': 'reason', 'status': 'status', 'type': 'type' } def __init__(self, last_transition_time=None, message=None, reason=None, status=None, type=None): """ V1ReplicaSetCondition - a model defined in Swagger """ self._last_transition_time = None self._message = None self._reason = None self._status = None self._type = None self.discriminator = None if last_transition_time is not None: self.last_transition_time = last_transition_time if message is not None: self.message = message if reason is not None: self.reason = reason self.status = status self.type = type @property def last_transition_time(self): """ Gets the last_transition_time of this V1ReplicaSetCondition. The last time the condition transitioned from one status to another. :return: The last_transition_time of this V1ReplicaSetCondition. :rtype: datetime """ return self._last_transition_time @last_transition_time.setter def last_transition_time(self, last_transition_time): """ Sets the last_transition_time of this V1ReplicaSetCondition. The last time the condition transitioned from one status to another. :param last_transition_time: The last_transition_time of this V1ReplicaSetCondition. :type: datetime """ self._last_transition_time = last_transition_time @property def message(self): """ Gets the message of this V1ReplicaSetCondition. A human readable message indicating details about the transition. :return: The message of this V1ReplicaSetCondition. :rtype: str """ return self._message @message.setter def message(self, message): """ Sets the message of this V1ReplicaSetCondition. A human readable message indicating details about the transition. :param message: The message of this V1ReplicaSetCondition. :type: str """ self._message = message @property def reason(self): """ Gets the reason of this V1ReplicaSetCondition. The reason for the condition's last transition. :return: The reason of this V1ReplicaSetCondition. :rtype: str """ return self._reason @reason.setter def reason(self, reason): """ Sets the reason of this V1ReplicaSetCondition. The reason for the condition's last transition. :param reason: The reason of this V1ReplicaSetCondition. :type: str """ self._reason = reason @property def status(self): """ Gets the status of this V1ReplicaSetCondition. Status of the condition, one of True, False, Unknown. :return: The status of this V1ReplicaSetCondition. :rtype: str """ return self._status @status.setter def status(self, status): """ Sets the status of this V1ReplicaSetCondition. Status of the condition, one of True, False, Unknown. :param status: The status of this V1ReplicaSetCondition. :type: str """ if status is None: raise ValueError("Invalid value for `status`, must not be `None`") self._status = status @property def type(self): """ Gets the type of this V1ReplicaSetCondition. Type of replica set condition. :return: The type of this V1ReplicaSetCondition. :rtype: str """ return self._type @type.setter def type(self, type): """ Sets the type of this V1ReplicaSetCondition. Type of replica set condition. :param type: The type of this V1ReplicaSetCondition. :type: str """ if type is None: raise ValueError("Invalid value for `type`, must not be `None`") self._type = type def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, V1ReplicaSetCondition): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
[ "haoweic@google.com" ]
haoweic@google.com
58a9801d0ccc4688645b9e09360eda2f4a5df932
272f75fb678ec4cd09e712d9db3621d274434743
/example/restaurants/admin.py
1d31184a1ced627f4e7793858a0e905fc6fce2eb
[ "MIT" ]
permissive
vintasoftware/django-zombodb
537c4eadad1eaf8f956db06bd7f7a8e39abd25c5
2391f27709819bd135e3d0dd571ef42e6996a201
refs/heads/master
2023-09-01T18:21:09.543287
2022-12-28T15:22:38
2022-12-28T15:22:38
168,772,360
153
13
MIT
2022-12-28T15:24:22
2019-02-01T23:15:22
Python
UTF-8
Python
false
false
528
py
from django.contrib import admin from django_zombodb.admin_mixins import ZomboDBAdminMixin from restaurants.models import Restaurant @admin.register(Restaurant) class RestaurantAdmin(ZomboDBAdminMixin, admin.ModelAdmin): model = Restaurant list_display = ( 'name', '_zombodb_score', 'street', 'zip_code', 'city', 'state', 'phone', 'categories', ) max_search_results = 100 class Media: js = ('django_zombodb/js/hide_show_score.js',)
[ "flaviojuvenal@gmail.com" ]
flaviojuvenal@gmail.com
98bfcf96f97b7f08cae75adb821c3c32e9db84ef
043baf7f2cd8e40150bbd4c178879a5dd340348d
/accommodation/migrations/0001_initial.py
77466847493b5372e234d29decf716663bdbf2ae
[]
no_license
tjguk/ironcage
1d6d70445b1da9642e1c70c72832c2738f9a942e
914b8e60819be7b449ecc77933df13f8b100adb0
refs/heads/master
2021-05-06T10:20:35.486184
2017-11-20T16:34:17
2017-11-20T16:34:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,112
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-09-07 23:15 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Booking', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('room_key', models.CharField(max_length=100)), ('stripe_charge_id', models.CharField(max_length=80)), ('stripe_charge_created', models.DateTimeField(null=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('guest', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
[ "peter.inglesby@gmail.com" ]
peter.inglesby@gmail.com
04d75ce4060f2df692f227b1bd328708277c8897
72e81080f6809c0528a3836be9cd3c75733b5c3d
/rlkit/envs/reacher_goal.py
205fcce8479b26dd518653ecfbfef2ddff09b1d8
[]
no_license
NagisaZj/mbpo_pytorch
986214ed729a4d98d60e761fac8fd06a9d66e651
12d7e24480b0b0c1a5bbccdf5d8fc434574695b9
refs/heads/main
2023-07-13T10:08:57.937163
2021-08-23T15:12:58
2021-08-23T15:12:58
390,729,140
0
0
null
2021-07-29T13:14:12
2021-07-29T13:14:12
null
UTF-8
Python
false
false
2,481
py
import numpy as np from rlkit.envs.ant_multitask_base import MultitaskAntEnv from . import register_env from gym.envs.mujoco.reacher import ReacherEnv as ReacherEnv_ # Copy task structure from https://github.com/jonasrothfuss/ProMP/blob/master/meta_policy_search/envs/mujoco_envs/ant_rand_goal.py @register_env('reacher-goal-sparse') class ReacherGoalEnv_sparse(ReacherEnv_): def __init__(self, task={}, n_tasks=2, randomize_tasks=True, **kwargs): self.goals = self.sample_tasks(n_tasks) self.goal_radius = 0.09 self._goal = [0,0,0.01] super(ReacherGoalEnv_sparse, self).__init__() self.reset_task(0) def get_all_task_idx(self): #print(self.action_space.low,self.action_space.high) print(len(self.goals)) return range(len(self.goals)) def step(self, action): tmp_finger = self.get_body_com("fingertip") vec = self.get_body_com("fingertip") - self._goal reward_dist = - np.linalg.norm(vec) #print(vec,reward_dist) reward_ctrl = - np.square(action).sum() sparse_reward = self.sparsify_rewards(reward_dist) reward = reward_dist + reward_ctrl sparse_reward = sparse_reward + reward_ctrl reward = sparse_reward self.do_simulation(action, self.frame_skip) ob = self._get_obs() done = False env_infos = dict(finger=tmp_finger.tolist(),reward_dist=reward_dist, reward_ctrl=reward_ctrl,sparse_reward=sparse_reward,goal=self._goal) #print(env_infos['finger']) return ob, reward, done, env_infos def sparsify_rewards(self, r): ''' zero out rewards when outside the goal radius ''' if r<-self.goal_radius: sparse_r = 0 else: sparse_r = r + 0.2 return sparse_r def sample_tasks(self, num_tasks): np.random.seed(1337) radius = np.random.uniform(0.2,0.25) angles = np.linspace(0, np.pi, num=num_tasks) xs = radius * np.cos(angles) ys = radius * np.sin(angles) heights = np.ones((num_tasks,), dtype=np.float32) * 0.01 #print(xs.shape,heights.shape) goals = np.stack([xs, ys,heights], axis=1) #goals = np.stack([goals, heights], axis=1) np.random.shuffle(goals) goals = goals.tolist() return goals def reset_task(self, idx): ''' reset goal AND reset the agent ''' self._goal = self.goals[idx] self.reset()
[ "1170863106@qq.com" ]
1170863106@qq.com
304e9513584c6511814989653d9015a56f83c020
3fe272eea1c91cc5719704265eab49534176ff0d
/scripts/item/consume_2437856.py
8a3b3f5cc263666730c7d8df70b774d8ca808a76
[ "MIT" ]
permissive
Bratah123/v203.4
e72be4843828def05592298df44b081515b7ca68
9cd3f31fb2ef251de2c5968c75aeebae9c66d37a
refs/heads/master
2023-02-15T06:15:51.770849
2021-01-06T05:45:59
2021-01-06T05:45:59
316,366,462
1
0
MIT
2020-12-18T17:01:25
2020-11-27T00:50:26
Java
UTF-8
Python
false
false
219
py
# Created by MechAviv # Frigid Ice Damage Skin | (2437856) if sm.addDamageSkin(2437856): sm.chat("'Frigid Ice Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
[ "pokesmurfuwu@gmail.com" ]
pokesmurfuwu@gmail.com
09b2e4c65d1dcb2dc611b927bb1cdaac37630ee2
90c6262664d013d47e9a3a9194aa7a366d1cabc4
/tests/storage/cases/test_KT1LpdwVxAQUvL5g1HzVeHoaGgkxukPkCBEv_babylon.py
d020a05a3bead9a715f57a4c5f5f239d515c7104
[ "MIT" ]
permissive
tqtezos/pytezos
3942fdab7aa7851e9ea81350fa360180229ec082
a4ac0b022d35d4c9f3062609d8ce09d584b5faa8
refs/heads/master
2021-07-10T12:24:24.069256
2020-04-04T12:46:24
2020-04-04T12:46:24
227,664,211
1
0
MIT
2020-12-30T16:44:56
2019-12-12T17:47:53
Python
UTF-8
Python
false
false
1,170
py
from unittest import TestCase from tests import get_data from pytezos.michelson.converter import build_schema, decode_micheline, encode_micheline, micheline_to_michelson class StorageTestKT1LpdwVxAQUvL5g1HzVeHoaGgkxukPkCBEv_babylon(TestCase): @classmethod def setUpClass(cls): cls.maxDiff = None cls.contract = get_data('storage/mainnet/KT1LpdwVxAQUvL5g1HzVeHoaGgkxukPkCBEv_babylon.json') def test_storage_encoding_KT1LpdwVxAQUvL5g1HzVeHoaGgkxukPkCBEv_babylon(self): type_expr = self.contract['script']['code'][1] val_expr = self.contract['script']['storage'] schema = build_schema(type_expr) decoded = decode_micheline(val_expr, type_expr, schema) actual = encode_micheline(decoded, schema) self.assertEqual(val_expr, actual) def test_storage_schema_KT1LpdwVxAQUvL5g1HzVeHoaGgkxukPkCBEv_babylon(self): _ = build_schema(self.contract['script']['code'][0]) def test_storage_format_KT1LpdwVxAQUvL5g1HzVeHoaGgkxukPkCBEv_babylon(self): _ = micheline_to_michelson(self.contract['script']['code']) _ = micheline_to_michelson(self.contract['script']['storage'])
[ "mz@baking-bad.org" ]
mz@baking-bad.org