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
885ab0e81a4c8b85a9a027b63a65dd41a961590c
63eae9dff408b3b8e3fa22fcfcbb012b025854bf
/shop/templatetags/app_filters.py
a440fed183a07d8b1b47772206ced7f0bffbd742
[]
no_license
adityasam1994/dlw
2fe88858ea80e1d04cd3c9349ecdbcf41f24bb30
e0bc5a0b8f52e1deaa655d3d95d4860285a059bb
refs/heads/master
2020-08-09T03:40:31.143100
2019-10-16T09:51:16
2019-10-16T10:00:07
213,988,198
0
0
null
null
null
null
UTF-8
Python
false
false
6,382
py
from django import template from django.template.defaultfilters import stringfilter import datetime from django.utils import timezone register = template.Library() @register.filter(name='getimage') @stringfilter def getimage(string): from shop.models import Image im = Image.objects.filter(product_id=int(string)) return im[0] @register.filter(name='getallimages') @stringfilter def getallimages(string): from shop.models import Image im = Image.objects.filter(product_id=int(string)) return im @register.filter(name="getreviews") @stringfilter def getreviews(string): from shop.models import Review re = Review.objects.filter(product_id=int(string)) return re @register.filter(name="getcustomer") @stringfilter def getcustomer(string): from django.contrib.auth.models import User u = User.objects.get(id=int(string)) return u @register.filter(name='times') def times(number): num=0 if(number <=5 ): num=number else: num=5 return range(num) @register.filter(name="get_average_stars") def get_average_stars(number): from shop.models import Review re = Review.objects.filter(product_id=number) if len(re) != 0: total=0 for r in re: total=total+r.rating average=total/len(re) return int(round(average)) else: return 0 @register.filter(name="get_star_count") def get_star_count(number): from shop.models import Review re = Review.objects.filter(product_id=number) return len(re) @register.filter(name="checkcart") def checkcart(number, uid): from shop.models import Customer from shop.models import Product product=Product.objects.get(id=number) mycart = Customer.objects.get(id=uid).cart if mycart != "" and mycart is not None: pp=1 cartsplit = mycart.split(",") for c in cartsplit: cc= c.split("/") if int(cc[0]) == number: pp=int(cc[1]) return pp else: return 1 @register.filter(name="checkcartbtn") def checkcartbtn(number, uid): from shop.models import Customer from shop.models import Product product=Product.objects.get(id=number) mycart = Customer.objects.get(customer_id=uid).cart if mycart != "" and mycart is not None: pp=1 cartsplit = mycart.split(",") for c in cartsplit: cc= c.split("/") if int(cc[0]) == number: pp=int(cc[1]) return True else: return False @register.filter(name="get_item_name") @stringfilter def get_item_name(string): from shop.models import Product sp=string.split("/") pro=Product.objects.get(id=int(sp[0])).name return pro @register.filter(name="get_item_price") @stringfilter def get_item_price(string): from shop.models import Product from shop.models import Offer per=0 sp=string.split("/") off = Offer.objects.filter(percent_discount=True) for o in off: pros = o.product.all() for pro in pros: if pro.id == int(sp[0]): per = o.percent pro=Product.objects.get(id=int(sp[0])).price prod = pro - (pro*per/100) return prod @register.filter(name="get_item_qty") @stringfilter def get_item_qty(string): from shop.models import Product sp=string.split("/") return sp[1] @register.filter(name="get_total_price") @stringfilter def get_total_price(string): from shop.models import Product sp=string.split("/") pr = Product.objects.get(id=int(sp[0])).price total=pr*int(sp[1]) return total @register.filter(name="get_item_image") @stringfilter def get_item_image(string): from shop.models import Image sp=string.split("/") pr = Image.objects.filter(product_id=int(sp[0])) return pr[0] @register.filter(name="get_cart_total") def get_cart_total(list): from shop.models import Product from shop.models import Offer tot=0 for s in list: per=0 spp = s.split("/") off = Offer.objects.filter(percent_discount=True) for o in off: pros = o.product.all() for pro in pros: if pro.id == int(spp[0]): per = o.percent prd = Product.objects.get(id=int(spp[0])).price pr = prd - (prd*per/100) tot=tot+(pr*int(spp[1])) return tot @register.filter(name="get_pid") @stringfilter def get_pid(string): sp=string.split("/") return int(sp[0]) @register.filter(name="splitorder") def splitorder(number): from shop.models import Order orde = Order.objects.get(id=number).product_id sp=orde.split(",") return sp @register.filter(name="checkoffer") def checkoffer(number): from shop.models import Offer off = Offer.objects.filter(percent_discount=True) ooo = None for o in off: pros = o.product.all() for p in pros: if p.id==number: ooo= o.id return ooo @register.filter(name="get_off_price") def get_off_price(number,oid): from shop.models import Offer off = Offer.objects.get(id=oid) dis = off.percent newprice = int(number * (100-dis)/100) return newprice @register.filter(name="get_off_percent") def get_off_percent(number): from shop.models import Offer off = Offer.objects.get(id=number) dis = int(off.percent) return dis @register.filter(name="get_item_count") def get_item_count(number): from shop.models import Customer cus = Customer.objects.get(customer_id = number) cart = cus.cart cartsplit = cart.split(",") return len(cartsplit) @register.filter(name="get_total") def get_total(number): from shop.models import Customer from shop.models import Product cus = Customer.objects.get(customer_id = number) cart = cus.cart cartsplit = cart.split(",") tot=0 for c in cartsplit: cc=c.split("/") price = Product.objects.get(id=int(cc[0])).price tot = tot + price*int(cc[1]) return tot @register.filter(name="canceldate") def canceldate(number): from shop.models import Shop_detail cp = Shop_detail.objects.get(id=1).cancellation_period number += datetime.timedelta(days=cp) if timezone.now() > number: return True else: return False
[ "adityanath1994@outlook.com" ]
adityanath1994@outlook.com
3a12ef11cb456aa1655cff4b35934ba431905c60
f09e98bf5de6f6c49df2dbeea93bd09f4b3b902f
/google-cloud-sdk/lib/surface/kms/__init__.py
0d7325c69d646db4cfbaff6358f3574909329d0a
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Peterfeng100/notepal
75bfaa806e24d85189bd2d09d3cb091944dc97e6
d5ba3fb4a06516fec4a4ae3bd64a9db55f36cfcd
refs/heads/master
2021-07-08T22:57:17.407571
2019-01-22T19:06:01
2019-01-22T19:06:01
166,490,067
4
1
null
2020-07-25T04:37:35
2019-01-19T00:37:04
Python
UTF-8
Python
false
false
1,892
py
# -*- coding: utf-8 -*- # # Copyright 2017 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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. """The command group for all of the Cloud KMS API.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import base @base.ReleaseTracks(base.ReleaseTrack.ALPHA, base.ReleaseTrack.BETA, base.ReleaseTrack.GA) class CloudKms(base.Group): """Manage cryptographic keys in the cloud. The gcloud kms command group lets you generate, use, rotate and destroy Google Cloud KMS keys. Cloud KMS is a cloud-hosted key management service that lets you manage encryption for your cloud services the same way you do on-premises. You can generate, use, rotate and destroy AES256 encryption keys. Cloud KMS is integrated with IAM and Cloud Audit Logging so that you can manage permissions on individual keys, and monitor how these are used. Use Cloud KMS to protect secrets and other sensitive data which you need to store in Google Cloud Platform. More information on Cloud KMS can be found here: https://cloud.google.com/kms/ and detailed documentation can be found here: https://cloud.google.com/kms/docs/ """ category = 'Identity and Security' def Filter(self, context, args): del context, args base.DisableUserProjectQuota()
[ "kevinhk.zhang@mail.utoronto.ca" ]
kevinhk.zhang@mail.utoronto.ca
59126b8ece1459e9fd42f05f6d93addec62fcf95
8698757521458c2061494258886e5d3cdfa6ff11
/word_embeddings/test/cross_validation_similarity.py
d138d4f193b83f117eac6f5e0a6ce69b794d605a
[ "MIT" ]
permissive
ricvo/argo
546c91e84d618c4bc1bb79a6bc7cba01dca56d57
a10c33346803239db8a64c104db7f22ec4e05bef
refs/heads/master
2023-02-25T01:45:26.412280
2020-07-05T22:55:35
2020-07-05T22:55:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,995
py
# export LC_ALL=en_US.UTF-8. import pickle from core.measures import evaluate_similarity_on_reverse_split import numpy as np import pandas as pd import argparse import os def evaluate_cross_sim_and_org(dictionary, dataset, i_split, dataset_split, method, couples_data, ntop=1, cvcorrs={}): p, I_inv, DV, I_norm, I_prod = methods_args[method] sorted_data = sorted(couples_data, reverse=True, key=lambda x: x[1]) top_alphas, top_sims = zip(*sorted_data[:ntop]) if cvcorrs.get(dataset_split, None) is None: cvcorrs[dataset_split] = {} if cvcorrs[dataset_split].get(method, None) is None: cvcorrs[dataset_split][method] = [] for alpha in top_alphas: simeval = make_simeval(p_embeddings, dictionary, alpha, I_inv, DV, p, I_norm, I_prod, method="cos") corr = evaluate_similarity_on_reverse_split(dictionary, simeval, dataset, i_split) cvcorrs[dataset_split][method].append([alpha, corr]) print("{} alpha {}:".format(dataset_split, alpha)) print('SPEARMAN CORR: %.2f ' % corr) def make_simeval(p_embeddings, dictionary, alpha, I_inv, DV, p, I_norm, I_prod, method="cos"): def simeval(words1, words2): return similarity_logmap_Esubmodel_trick(p_embeddings, dictionary, words1, words2, alpha, I_inv, DV, p, I_prod, I_norm=I_norm, method=method) return simeval def load_from_dir(simdir): alphas = np.load(simdir + "/alphas.npy") I0 = np.load(simdir + "/fisher-0.npy") # I0_inv = np.linalg.inv(I0) Iu = np.load(simdir + "/fisher-u.npy") # Iu_inv = np.linalg.inv(Iu) with open(simdir+"/base-similarities.pkl", 'rb') as f: base_similarities = pickle.load(f) with open(simdir+"/alpha-similarities.pkl", 'rb') as f: alpha_similarities = pickle.load(f) return alphas, I0, Iu, base_similarities, alpha_similarities def main(): parser = argparse.ArgumentParser(description='Make cross-validation correlations.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('simdir', type=str, help="directory where to find similarity results") parser.add_argument('--ntop', '-t', type=int, help="how many top") args = parser.parse_args() simdir = args.simdir wemb_id = os.path.basename(os.path.normpath(simdir)) corpus, vstr, nstr = wemb_id.split('-') vecsize = int(vstr[1:]) nepoch = int(nstr[1:]) ntop = args.ntop alphas, I0, Iu, base_similarities, alpha_similarities = load_from_dir(simdir) outputname = os.path.join(simdir, "alpha-similarities-cross-val-top{}.json".format(ntop)) datasets = ["wordsim353", "mc", "rg", "scws", "wordsim353sim", "wordsim353rel", "men", "mturk287", "rw", "simlex999" ] n_splits = 3 cvcorrs = {} for d in datasets: for m in methods_args: curves = [] for n in range(n_splits): all_couples = [] ds = d + "-split_{:}".format(n) # load small, mid and large and merge for key in data: all_couples += list(zip(alphas[key], data[key][ds][m])) all_couples.sort(key=lambda x: x[0]) all_couples = [(a, v) for a, v in all_couples if np.abs(a)<=70.1] all_couples = [(a,v) for a,v in all_couples if not np.isnan(v)] #find best top alphas # calculate reverse for the selected alpha # store results in the form {m: [(a1, s1), (a2, s2),...]} evaluate_cross_sim_and_org(v_dictionary, d, n, ds, m, all_couples, ntop, cvcorrs=cvcorrs) df = pd.DataFrame(cvcorrs) df.to_csv(outputname, sep=' ') if __name__ == "__main__": main()
[ "volpi@rist.ro" ]
volpi@rist.ro
61ed638564f28791b24b7cd7c21897b32fe62fd0
c93080264201fe6d0c84a79ae435022981d8ccf6
/panoptic/panoptic/doctype/facial_recognition_system/facial_recognition_system.py
85576d855955e672d0df3ef2428a5befc108e3a5
[ "MIT" ]
permissive
wisharya/panoptic
100e733e9aad33d087851fc4ea9bd064e81954f2
7c9a0eeb6bd5d9032087ccb7c805a3e65a357ba8
refs/heads/master
2023-07-09T14:20:45.377441
2021-08-25T06:58:45
2021-08-25T06:58:45
null
0
0
null
null
null
null
UTF-8
Python
false
false
289
py
# -*- coding: utf-8 -*- # Copyright (c) 2020, Internet Freedom Foundation and contributors # For license information, please see license.txt from __future__ import unicode_literals # import frappe from frappe.model.document import Document class FacialRecognitionSystem(Document): pass
[ "scm.mymail@gmail.com" ]
scm.mymail@gmail.com
71227b941e2809759abccb685f70469423fba4e5
431a1f738b1edfba7dad8d10a6b7520d51d917cb
/Samples/UserSamples/2017/xH_Differential_Reco/xH_NJETS_0_Config.py
4e0a6fdf11273f15866df7c41142cd35efb04132
[]
no_license
aloeliger/DatacardCreator
5ce702e46fbb77e843b44d8fe088c2645a4a8f66
5c7e890276a5be079ed3b677a471c1dcadcba52d
refs/heads/master
2022-02-26T19:52:30.563747
2022-02-16T20:24:48
2022-02-16T20:24:48
215,602,523
0
1
null
null
null
null
UTF-8
Python
false
false
2,623
py
from Samples.SampleDefinition import Sample from Samples.Uncertainties.UserUncertainties.TES import TESUncertainty from Samples.Uncertainties.UserUncertainties.Signal_JES_17 import JES17Uncertainty from Samples.Uncertainties.UserUncertainties.JER import JERUncertainty from Samples.Uncertainties.UserUncertainties.MetRecoil import MetRecoilUncertainty from Samples.Uncertainties.UserUncertainties.MuonES import MuonESUncertainty from Samples.Uncertainties.UserUncertainties.Prefiring import PrefiringUncertainty from Samples.Uncertainties.UserUncertainties.TauID import TauIDUncertainty from Samples.Uncertainties.UserUncertainties.Trigger17_18 import Trigger1718Uncertainty #from Samples.Uncertainties.UserUncertainties.qqHTheory import qqHTheoryUncertainty from Samples.Uncertainties.UserUncertainties.QCDAcceptanceUncertainties.DifferentialUncertainties.NJets_QCD_Uncertainties.GGZH_NJets_Differential_QCDScale_Uncertainty import GGZH_NJets_Differential_QCDScale_Uncertainty from Samples.Uncertainties.UserUncertainties.QCDAcceptanceUncertainties.DifferentialUncertainties.NJets_QCD_Uncertainties.VH_NJets_Differential_QCDScale_Uncertainty import VH_NJets_Differential_QCDScale_Uncertainty from Samples.Uncertainties.UserUncertainties.QCDAcceptanceUncertainties.DifferentialUncertainties.NJets_QCD_Uncertainties.qqH_NJets_Differential_QCDScale_Uncertainty import qqH_NJets_Differential_QCDScale_Uncertainty from Samples.Uncertainties.UserUncertainties.QCDAcceptanceUncertainties.DifferentialUncertainties.NJets_QCD_Uncertainties.ttH_NJets_Differential_QCDScale_Uncertainty import ttH_NJets_Differential_QCDScale_Uncertainty from Samples.EventDefinition.UserEventDictionaries.MuTauEventDictionary import MuTauEventDictionary VBFSample = Sample() VBFSample.name = 'xH_recoNJ_0' VBFSample.path = '/data/aloeliger/SMHTT_Selected_2017_Deep/' VBFSample.files = ['VBF.root','WHPlus.root','WHMinus.root','ZH.root','GGZHLLTT.root','GGZHNNTT.root','GGZHQQTT.root','ttH.root'] VBFSample.definition = 'is_Fiducial == 1.0 && njets == 0' VBFSample.uncertainties = [ TESUncertainty(), JES17Uncertainty(), JERUncertainty(), MetRecoilUncertainty(), MuonESUncertainty(), PrefiringUncertainty(), TauIDUncertainty(), Trigger1718Uncertainty(), #qqHTheoryUncertainty(), GGZH_NJets_Differential_QCDScale_Uncertainty(), VH_NJets_Differential_QCDScale_Uncertainty(), qqH_NJets_Differential_QCDScale_Uncertainty(), ttH_NJets_Differential_QCDScale_Uncertainty(), ] VBFSample.eventDictionaryInstance = MuTauEventDictionary VBFSample.CreateEventWeight = VBFSample.CreateEventWeight_Standard
[ "aloelige@cern.ch" ]
aloelige@cern.ch
8564fae4ea4edaef15f390a4f927ccfa825c49e8
f45cc0049cd6c3a2b25de0e9bbc80c25c113a356
/LeetCode/机器学习(ML)/plot_feature_transformation.py
c4a45b398f7482bac992a174a2f4a2381777a1fa
[]
no_license
yiming1012/MyLeetCode
4a387d024969bfd1cdccd4f581051a6e4104891a
e43ee86c5a8cdb808da09b4b6138e10275abadb5
refs/heads/master
2023-06-17T06:43:13.854862
2021-07-15T08:54:07
2021-07-15T08:54:07
261,663,876
2
0
null
null
null
null
UTF-8
Python
false
false
5,090
py
""" =============================================== Feature transformations with ensembles of trees =============================================== Transform your features into a higher dimensional, sparse space. Then train a linear model on these features. First fit an ensemble of trees (totally random trees, a random forest, or gradient boosted trees) on the training set. Then each leaf of each tree in the ensemble is assigned a fixed arbitrary feature index in a new feature space. These leaf indices are then encoded in a one-hot fashion. Each sample goes through the decisions of each tree of the ensemble and ends up in one leaf per tree. The sample is encoded by setting feature values for these leaves to 1 and the other feature values to 0. The resulting transformer has then learned a supervised, sparse, high-dimensional categorical embedding of the data. """ # Author: Tim Head <betatim@gmail.com> # # License: BSD 3 clause # print(__doc__) from sklearn import set_config set_config(display='diagram') # %% # First, we will create a large dataset and split it into three sets: # # - a set to train the ensemble methods which are later used to as a feature # engineering transformer; # - a set to train the linear model; # - a set to test the linear model. # # It is important to split the data in such way to avoid overfitting by leaking # data. from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split X, y = make_classification(n_samples=80000, random_state=10) X_full_train, X_test, y_full_train, y_test = train_test_split( X, y, test_size=0.5, random_state=10) X_train_ensemble, X_train_linear, y_train_ensemble, y_train_linear = \ train_test_split(X_full_train, y_full_train, test_size=0.5, random_state=10) # %% # For each of the ensemble methods, we will use 10 estimators and a maximum # depth of 3 levels. n_estimators = 10 max_depth = 3 # %% # First, we will start by training the random forest and gradient boosting on # the separated training set from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier random_forest = RandomForestClassifier( n_estimators=n_estimators, max_depth=max_depth, random_state=10) random_forest.fit(X_train_ensemble, y_train_ensemble) gradient_boosting = GradientBoostingClassifier( n_estimators=n_estimators, max_depth=max_depth, random_state=10) _ = gradient_boosting.fit(X_train_ensemble, y_train_ensemble) # %% # The :class:`~sklearn.ensemble.RandomTreesEmbedding` is an unsupervised method # and thus does not required to be trained independently. from sklearn.ensemble import RandomTreesEmbedding random_tree_embedding = RandomTreesEmbedding( n_estimators=n_estimators, max_depth=max_depth, random_state=0) # %% # Now, we will create three pipelines that will use the above embedding as # a preprocessing stage. # # The random trees embedding can be directly pipelined with the logistic # regression because it is a standard scikit-learn transformer. from sklearn.linear_model import LogisticRegression from sklearn.pipeline import make_pipeline rt_model = make_pipeline( random_tree_embedding, LogisticRegression(max_iter=1000)) rt_model.fit(X_train_linear, y_train_linear) # %% # Then, we can pipeline random forest or gradient boosting with a logistic # regression. However, the feature transformation will happen by calling the # method `apply`. The pipeline in scikit-learn expects a call to `transform`. # Therefore, we wrapped the call to `apply` within a `FunctionTransformer`. from sklearn.preprocessing import FunctionTransformer from sklearn.preprocessing import OneHotEncoder def rf_apply(X, model): return model.apply(X) rf_leaves_yielder = FunctionTransformer( rf_apply, kw_args={"model": random_forest}) rf_model = make_pipeline( rf_leaves_yielder, OneHotEncoder(handle_unknown="ignore"), LogisticRegression(max_iter=1000)) rf_model.fit(X_train_linear, y_train_linear) # %% def gbdt_apply(X, model): return model.apply(X)[:, :, 0] gbdt_leaves_yielder = FunctionTransformer( gbdt_apply, kw_args={"model": gradient_boosting}) gbdt_model = make_pipeline( gbdt_leaves_yielder, OneHotEncoder(handle_unknown="ignore"), LogisticRegression(max_iter=1000)) gbdt_model.fit(X_train_linear, y_train_linear) # %% # We can finally show the different ROC curves for all the models. import matplotlib.pyplot as plt from sklearn.metrics import plot_roc_curve fig, ax = plt.subplots() models = [ ("RT embedding -> LR", rt_model), ("RF", random_forest), ("RF embedding -> LR", rf_model), ("GBDT", gradient_boosting), ("GBDT embedding -> LR", gbdt_model), ] model_displays = {} for name, pipeline in models: model_displays[name] = plot_roc_curve( pipeline, X_test, y_test, ax=ax, name=name) _ = ax.set_title('ROC curve') # %% fig, ax = plt.subplots() for name, pipeline in models: model_displays[name].plot(ax=ax) ax.set_xlim(0, 0.2) ax.set_ylim(0.8, 1) _ = ax.set_title('ROC curve (zoomed in at top left)')
[ "1129079384@qq.com" ]
1129079384@qq.com
58eb34d13830641c05a389e7f32d562c587efb98
e79fb97c06e3a75bd0cf6135fbbd6c1ac08492cb
/cnn/vgg16net.py
1c14e72e799125617b2cdc37f77caf322527616b
[ "MIT" ]
permissive
nocotan/chainer-examples
b1021e98654a6d377cc4669c7cedd57bca4f692d
d2b736231c6a6c2ba1effa3ddeb90770d7e020d9
refs/heads/master
2021-09-11T12:42:31.612581
2018-04-07T05:40:22
2018-04-07T05:40:22
78,973,921
13
3
null
null
null
null
UTF-8
Python
false
false
2,288
py
# -*- coding: utf-8 -*- import chainer import chainer.functions as F import chainer.links as L class VGG16Net(chainer.Chain): def __init__(self, num_class, train=True): super(VGG16Net, self).__init__() with self.init_scope(): self.conv1=L.Convolution2D(None, 64, 3, stride=1, pad=1) self.conv2=L.Convolution2D(None, 64, 3, stride=1, pad=1) self.conv3=L.Convolution2D(None, 128, 3, stride=1, pad=1) self.conv4=L.Convolution2D(None, 128, 3, stride=1, pad=1) self.conv5=L.Convolution2D(None, 256, 3, stride=1, pad=1) self.conv6=L.Convolution2D(None, 256, 3, stride=1, pad=1) self.conv7=L.Convolution2D(None, 256, 3, stride=1, pad=1) self.conv8=L.Convolution2D(None, 512, 3, stride=1, pad=1) self.conv9=L.Convolution2D(None, 512, 3, stride=1, pad=1) self.conv10=L.Convolution2D(None, 512, 3, stride=1, pad=1) self.conv11=L.Convolution2D(None, 512, 3, stride=1, pad=1) self.conv12=L.Convolution2D(None, 512, 3, stride=1, pad=1) self.conv13=L.Convolution2D(None, 512, 3, stride=1, pad=1) self.fc14=L.Linear(None, 4096) self.fc15=L.Linear(None, 4096) self.fc16=L.Linear(None, num_class) def __call__(self, x): h = F.relu(self.conv1(x)) h = F.max_pooling_2d(F.local_response_normalization( F.relu(self.conv2(h))), 2, stride=2) h = F.relu(self.conv3(h)) h = F.max_pooling_2d(F.local_response_normalization( F.relu(self.conv4(h))), 2, stride=2) h = F.relu(self.conv5(h)) h = F.relu(self.conv6(h)) h = F.max_pooling_2d(F.local_response_normalization( F.relu(self.conv7(h))), 2, stride=2) h = F.relu(self.conv8(h)) h = F.relu(self.conv9(h)) h = F.max_pooling_2d(F.local_response_normalization( F.relu(self.conv10(h))), 2, stride=2) h = F.relu(self.conv11(h)) h = F.relu(self.conv12(h)) h = F.max_pooling_2d(F.local_response_normalization( F.relu(self.conv13(h))), 2, stride=2) h = F.dropout(F.relu(self.fc14(h))) h = F.dropout(F.relu(self.fc15(h))) h = self.fc16(h) return h
[ "noconoco.lib@gmail.com" ]
noconoco.lib@gmail.com
f3097de81d59a4155e526536d2ae31e634e087bb
ddaa20f2ff0aaed4c6beeba888c4213405fdd586
/pypi_server/timeit.py
fe647520cadd0075e0453b61ab33572b87994218
[ "MIT" ]
permissive
mosquito/pypi-server
689fb84dd0cc56a70c7bfa6157b8defa76d774d8
825571aae6fd17616e404ad8a9b72ef791a4fc46
refs/heads/master
2023-08-17T14:17:50.177008
2021-11-14T17:11:52
2021-11-14T17:11:52
47,583,364
129
58
MIT
2021-11-14T17:11:53
2015-12-07T22:30:53
Python
UTF-8
Python
false
false
899
py
# encoding: utf-8 import logging from functools import wraps from time import time from concurrent.futures import Future log = logging.getLogger(__name__) def timeit(func): def log_result(start_time): log.debug( 'Time of execution function "%s": %0.6f', ".".join(filter( None, ( func.__module__, func.__class__.__name__ if hasattr(func, '__class__') else None, func.__name__ ) )), time() - start_time ) @wraps(func) def wrap(*args, **kwargs): start_time = time() result = func(*args, **kwargs) if isinstance(result, Future): result.add_done_callback(lambda x: log_result(start_time)) else: log_result(start_time) return result return wrap
[ "me@mosquito.su" ]
me@mosquito.su
70af007d7f7ce4b7ee0a57b362e9ffa3749b1eb9
f0d713996eb095bcdc701f3fab0a8110b8541cbb
/pAFxfge35bT3zj4Bs_24.py
fbbbfecf880247970104edc5a6cad8636470e2df
[]
no_license
daniel-reich/turbo-robot
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
a7a25c63097674c0a81675eed7e6b763785f1c41
refs/heads/main
2023-03-26T01:55:14.210264
2021-03-23T16:08:01
2021-03-23T16:08:01
350,773,815
0
0
null
null
null
null
UTF-8
Python
false
false
643
py
""" Write a function that accepts `base` (decimal), `height` (decimal) and `shape` ("triangle", "parallelogram") as input and calculates the area of that shape. ### Examples area_shape(2, 3, "triangle") ➞ 3 area_shape(8, 6, "parallelogram") ➞ 48 area_shape(2.9, 1.3, "parallelogram") ➞ 3.77 ### Notes * Area of a triangle is `0.5 * b * h` * Area of a parallelogram is `b * h` * Assume triangle and parallelogram are the only inputs for `shape`. """ def area_shape(base, height, shape): area =() if shape == "triangle": area = 0.5*base*height else: area = base*height return area
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
1a2055c82f8b2b3d858e86a5931e89220f739c3f
c3a84a07539c33040376f2c1e140b1a1041f719e
/wagtail-stubs/users/utils.pyi
6e8f3c6034fd36111d79271ece10284a95e4e72c
[]
no_license
tm-kn/tmp-wagtail-stubs
cc1a4434b7142cb91bf42efb7daad006c4a7dbf4
23ac96406610b87b2e7751bc18f0ccd27f17eb44
refs/heads/master
2023-01-20T14:41:33.962460
2020-11-30T23:15:38
2020-11-30T23:15:38
317,332,280
0
0
null
null
null
null
UTF-8
Python
false
false
293
pyi
from typing import Any from wagtail.core.compat import AUTH_USER_APP_LABEL as AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME as AUTH_USER_MODEL_NAME delete_user_perm: Any def user_can_delete_user(current_user: Any, user_to_delete: Any): ... def get_gravatar_url(email: Any, size: int = ...): ...
[ "hi@tmkn.org" ]
hi@tmkn.org
e3a39fc46f0ee31bcf4cbf6f4eef75379c9eb87e
8242f7c33e37db242a6a839cccd6a48b79ddbfa9
/erase/main.py
71861978925ebc25fc1531a3c889e94202072e29
[]
no_license
elitan/open-kattis
d2be23868f3be6613bcbf4e9381a30f283199082
7bec84b054c639ed3d534671bfc0f57dee289d27
refs/heads/master
2021-01-17T08:51:46.340776
2016-10-10T19:17:52
2016-10-10T19:17:52
65,326,686
0
0
null
null
null
null
UTF-8
Python
false
false
400
py
import fileinput import sys n = int(raw_input()) # we dont need this one s_1 = map(int, list(raw_input().rstrip())) s_2 = map(int, list(raw_input().rstrip())) zero = (0 + n) % 2 one = (1 + n) % 2 converter = {0: zero, 1: one} c = 0 s_len = len(s_1) while c < s_len: if converter[s_1[c]] != s_2[c]: print("Deletion failed") sys.exit() c += 1 print("Deletion succeeded")
[ "johan@eliasson.me" ]
johan@eliasson.me
5ecce4c7bc6f82cb036331ca45fb67166154c4e5
bbe53d0171efbc78ca43f409b4a5235df51f36fa
/learning/djangoLearning/django-start/mysite/dev_settings.py
24dea2919335488abf7ac20fb0a273ed26c2b821
[]
no_license
brianwang/gftop
2758ec93e326ba5e801af48f951c73b5761bb25d
12a48eafb5114da325515fce4b97e744638e6faf
refs/heads/master
2021-01-12T08:16:43.816679
2012-12-12T16:25:29
2012-12-12T16:25:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
784
py
from os import getcwd MYSITE_BASE_DIR = getcwd() DEBUG = True TEMPLATE_DEBUG = DEBUG SUPER_USER_NAME = 'admin' SUPER_USER_EMAIL = 'admin@test.com' SUPER_USER_PASSWORD = 'admin' SITE_URL = '127.0.0.1:8000' SITE_NAME = 'MySite' DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mysite.db' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. EMAIL_HOST = 'localhost' # EMAIL_PORT = # EMAIL_HOST_USER = # EMAIL_HOST_PASSWORD =
[ "gaofeitop@0700f6e2-4af4-11de-a39b-05eb13f3dc65" ]
gaofeitop@0700f6e2-4af4-11de-a39b-05eb13f3dc65
8e9763cb78dec4a5b44a07cf246af0b20cd8087e
cf5b2850dc9794eb0fc11826da4fd3ea6c22e9b1
/xlsxwriter/test/worksheet/test_write_sheet_views2.py
e53240875a8168457b6d934d3a2a907b87e127ae
[ "BSD-2-Clause" ]
permissive
glasah/XlsxWriter
bcf74b43b9c114e45e1a3dd679b5ab49ee20a0ec
1e8aaeb03000dc2f294ccb89b33806ac40dabc13
refs/heads/main
2023-09-05T03:03:53.857387
2021-11-01T07:35:46
2021-11-01T07:35:46
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,446
py
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org # import unittest from io import StringIO from ...worksheet import Worksheet class TestWriteSheetViews(unittest.TestCase): """ Test the Worksheet _write_sheet_views() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_sheet_views1(self): """Test the _write_sheet_views() method with freeze panes""" self.worksheet.select() self.worksheet.freeze_panes(1, 0) self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/><selection pane="bottomLeft"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_sheet_views2(self): """Test the _write_sheet_views() method with freeze panes""" self.worksheet.select() self.worksheet.freeze_panes(0, 1) self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="1" topLeftCell="B1" activePane="topRight" state="frozen"/><selection pane="topRight"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_sheet_views3(self): """Test the _write_sheet_views() method with freeze panes""" self.worksheet.select() self.worksheet.freeze_panes(1, 1) self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="1" ySplit="1" topLeftCell="B2" activePane="bottomRight" state="frozen"/><selection pane="topRight" activeCell="B1" sqref="B1"/><selection pane="bottomLeft" activeCell="A2" sqref="A2"/><selection pane="bottomRight"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_sheet_views4(self): """Test the _write_sheet_views() method with freeze panes""" self.worksheet.select() self.worksheet.freeze_panes('G4') self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="6" ySplit="3" topLeftCell="G4" activePane="bottomRight" state="frozen"/><selection pane="topRight" activeCell="G1" sqref="G1"/><selection pane="bottomLeft" activeCell="A4" sqref="A4"/><selection pane="bottomRight"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(got, exp) def test_write_sheet_views5(self): """Test the _write_sheet_views() method with freeze panes""" self.worksheet.select() self.worksheet.freeze_panes(3, 6, 3, 6, 1) self.worksheet._write_sheet_views() exp = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="6" ySplit="3" topLeftCell="G4" activePane="bottomRight" state="frozenSplit"/><selection pane="topRight" activeCell="G1" sqref="G1"/><selection pane="bottomLeft" activeCell="A4" sqref="A4"/><selection pane="bottomRight"/></sheetView></sheetViews>' got = self.fh.getvalue() self.assertEqual(got, exp)
[ "jmcnamara@cpan.org" ]
jmcnamara@cpan.org
76659e18cdb1432d1c91a30be7eeb85f667e9f96
2befb6f2a5f1fbbd5340093db43a198abdd5f53b
/pythonProject/FBVPermission/FBVPermission/settings.py
a64ea42a4ed445c5878381f3f08aa7ccabac8eb3
[]
no_license
JanardanPandey/RestAPI
1956d3529782d18ef2118961f6286e3213665aad
654933a4d9687076a00c6f4c57fc3dfee1a2c567
refs/heads/master
2023-06-14T07:02:31.702000
2021-07-02T07:50:59
2021-07-02T07:50:59
382,357,537
0
0
null
null
null
null
UTF-8
Python
false
false
3,298
py
""" Django settings for FBVPermission project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-)ys_5umafpe$al@h)y*&q^gt$#m-=d%%fztc=rfl!2xykh(@n*' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.api', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'FBVPermissionApp', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.api.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'FBVPermission.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.api.context_processors.api', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'FBVPermission.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.api.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.api.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.api.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.api.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
[ "janardanpandey0510@gmail.com" ]
janardanpandey0510@gmail.com
9a12029623af66c700d989ba7253121601a4f6d5
2d27444b26de173ed1b7454f72d102050c7a6b07
/Tuples/tuples04.py
bfb1b4cb89f5c12608af7a77689cf38b9a60a51a
[]
no_license
imrishuroy/Python-Projects
6b93454dcb30c307aece07d611855f8b718fb8e8
f15a0e7da702a30618658ce4f4650807daaae759
refs/heads/master
2023-04-17T04:33:38.889592
2021-05-08T08:35:09
2021-05-08T08:35:09
335,221,000
0
0
null
null
null
null
UTF-8
Python
false
false
140
py
# Tuples and Dictionary d = dict() d['Rishu'] = 91 d['Prince'] = 100 for k , v in d.items(): print(k,v) tups = d.items() print(tups)
[ "rishukumar.prince@gmail.com" ]
rishukumar.prince@gmail.com
618f83793b61456aa8298f3a72b371b921d7f30a
293db74378eb425d54ae2ea4735d442d594cc0b8
/myapp/migrations/0004_auto_20160517_0559.py
665ada23577a4d573d90b4f6498924033b5b5e4e
[]
no_license
ajithkjames/contactsmanager
6c5944ee126411db71bcb43a274a6de92c5c236d
c546e4fd53e835d85f66aef0890f9a46e945d275
refs/heads/master
2020-07-03T00:33:56.353982
2016-11-19T12:48:18
2016-11-19T12:48:18
74,207,861
0
0
null
null
null
null
UTF-8
Python
false
false
601
py
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-17 05:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0003_members_contact_member'), ] operations = [ migrations.RemoveField( model_name='group', name='id', ), migrations.AlterField( model_name='group', name='group_code', field=models.CharField(max_length=30, primary_key=True, serialize=False, unique=True), ), ]
[ "you@example.com" ]
you@example.com
ee4d0edf66d7a8c4ddce1c673e56b805bace6794
039c5187dd45b8dd2c960c1570369d6eb11eae83
/soufang/config.py
efd983939f003ba81021d15df92d8a15a3eca8df
[]
no_license
huazhicai/spider
5636951c1e0db4dc7b205cacfe8e881a08ff2015
d72ce471b0388d6d594853120c8e8f93694015a6
refs/heads/master
2021-07-24T23:01:15.124742
2017-11-04T09:05:46
2017-11-04T09:05:46
107,860,473
1
0
null
null
null
null
UTF-8
Python
false
false
7,411
py
# 爬取房天下的楼盘的评论 # 获取城市名称 import re import requests from bs4 import BeautifulSoup def get_city(): url = 'http://www.fang.com/SoufunFamily.htm' html_content = requests.get(url) # <a href="http://gaoling.fang.com/" target="_blank">高陵</a> pattern = re.compile(r'<a href="http://(\w+)\.fang\.com/" target="_blank">.+?</a>', re.S) items = re.findall(pattern, html_content.text) print(len(set(items))) print(set(items)) # get_city() CITYS = ['yt', 'zaozhuang', 'zhongwei', 'qianxi', 'boluo', 'hegang', 'yl', 'yunfu', 'meishan', 'fq', 'yangchun', 'linzhi', 'rudong', 'mengjin', 'feicheng', 'zhucheng', 'bengbu', 'huainan', 'dongxing', 'xinmi', 'linqu', 'luanxian', 'jingmen', 'wenan', 'zb', 'huzhou', 'yuzhong', 'xf', 'fenghua', 'us', 'longkou', 'lijiang', 'ganzi', 'hbjz', 'sz', 'tl', 'hbzy', 'minqing', 'gongzhuling', 'laiwu', 'gxby', 'qingzhen', 'zz', 'anqing', 'linfen', 'ruian', 'xinghua', 'feixi', 'lujiang', 'njgc', 'anning', 'jxfc', 'tongshan', 'anyang', 'luoning', 'pingtan', 'shiyan', 'chengde', 'wuzhong', 'zhouzhi', 'liaozhong', 'qingxu', 'zhaotong', 'jm', 'jiaozhou', 'taishan', 'tc', 'hechi', 'whhn', 'anshun', 'xinyi', 'wuhan', 'huaiyuan', 'xj', 'yingtan', 'jlys', 'ruijin', 'lyg', 'xlglm', 'changge', 'changli', 'honghe', 'huaibei', 'bazhong', 'longhai', 'chifeng', 'ld', 'macau', 'heyuan', 'mudanjiang', 'yilan', 'xiangxiang', 'zjfy', 'panzhihua', 'jiujiang', 'tieling', 'xiuwen', 'faku', 'jinxian', 'hbyc', 'benxi', 'hlbe', 'jiaonan', 'deqing', 'shaoyang', 'bijie', 'shangrao', 'heihe', 'suizhou', 'nanjing', 'alaer', 'germany', 'jimo', 'anqiu', 'wujiaqu', 'baoji', 'qinzhou', 'wuzhishan', 'guan', 'jiangdu', 'yuxian', 'liyang', 'xinjin', 'jiayuguan', 'huizhou', 'tongling', 'haiyang', 'jintan', 'gaomi', 'kuitun', 'yc', 'ruyang', 'erds', 'shangyu', 'xiaogan', 'xinyu', 'dz', 'tmsk', 'zjxs', 'huangshan', 'baishan', 'yongcheng', 'huidong', 'pengzhou', 'lnta', 'hengxian', 'taizhou', 'ly', 'luanchuan', 'ziyang', 'anshan', 'huadian', 'qingyang', 'datong', 'st', 'kelamayi', 'tulufan', 'tonghua', 'jiande', 'qianan', 'zhoukou', 'guangrao', 'yongkang', 'chuzhou', 'liupanshui', 'changdu', 'ny', 'zs', 'huangshi', 'xianning', 'kaifeng', 'spain', 'diqing', 'ruzhou', 'hbbz', 'jh', 'sf', 'tongchuan', 'dengfeng', 'wafangdian', 'yuncheng', 'cd', 'aj', 'zhangye', 'pulandian', 'laizhou', 'jinhu', 'changchun', 'zigong', 'qiannan', 'loudi', 'sdpy', 'ali', 'gaobeidian', 'dengzhou', 'kaiyang', 'jiaozuo', 'yiyang', 'xinmin', 'dujiangyan', 'dingxing', 'ytcd', 'yueyang', 'yongtai', 'penglai', 'cangzhou', 'huoqiu', 'shihezi', 'huaihua', 'jieyang', 'fanchang', 'jn', 'linqing', 'tengzhou', 'nujiang', 'cswc', 'lf', 'pingliang', 'wg', 'zy', 'bazhou', 'tianshui', 'pizhou', 'dehui', 'malaysia', 'weinan', 'xiantao', 'tj', 'lnzh', 'changshu', 'fuyang', 'sansha', 'hbwj', 'dh', 'yuxi', 'taixing', 'meizhou', 'xm', 'zhangzhou', 'linan', 'ahsuzhou', 'zoucheng', 'yinchuan', 'chizhou', 'heze', 'peixian', 'jinchang', 'ganzhou', 'funing', 'jingdezhen', 'wuzhou', 'bh', 'huaian', 'xuchang', 'chaoyang', 'jz', 'lvliang', 'yk', 'qz', 'la', 'anda', 'dianpu', 'cq', 'ksys', 'chicago', 'gaoyang', 'shuyang', 'gdlm', 'sh', 'hz', 'gz', 'songyuan', 'nc', 'dongtai', 'changle', 'sg', 'cqnanchuan', 'leiyang', 'nanan', 'zhangjiajie', 'greece', 'shunde', 'guangyuan', 'baoshan', 'tongren', 'linxia', 'dangtu', 'huludao', 'wz', 'yongdeng', 'hetian', 'xingtai', 'haiyan', 'sdjy', 'boston', 'donggang', 'jy', 'rz', 'yuhuan', 'wuan', 'guzhen', 'dali', 'ningde', 'neijiang', 'fangchenggang', 'sdsh', 'xn', 'nanyang', 'tongcheng', 'nn', 'hnyz', 'jixi', 'chuxiong', 'emeishan', 'laixi', 'betl', 'chaozhou', 'deyang', 'sdcl', 'xz', 'dongfang', 'gongyi', 'pinghu', 'jl', 'qd', 'sanming', 'xt', 'maoming', 'zhijiang', 'haimen', 'lianjiang', 'xinjian', 'sq', 'yanbian', 'guyuan', 'hami', 'qianjiang', 'yongning', 'suining', 'yibin', 'jxja', 'wlcb', 'dayi', 'sxly', 'dangyang', 'haining', 'lantian', 'lc', 'hd', 'puyang', 'qitaihe', 'quanshan', 'dingxi', 'jx', 'weihai', 'dy', 'chaohu', 'bozhou', 'bj', 'kashi', 'yili', 'jiuquan', 'ningxiang', 'ahcf', 'xuancheng', 'xinji', 'luzhou', 'heshan', 'shangzhi', 'zjtl', 'alsm', 'baicheng', 'wuchang', 'chunan', 'kaili', 'zhaoqing', 'cqliangping', 'lasa', 'cqchangshou', 'haian', 'qujing', 'hbjs', 'huian', 'liling', 'yangquan', 'jingjiang', 'jianyang', 'jiyuan', 'zhenjiang', 'hbql', 'shanwei', 'wuhu', 'zj', 'rikaze', 'feidong', 'daqing', 'pingxiang', 'cqwulong', 'xianyang', 'aba', 'zhangjiakou', 'agent', 'byne', 'pingdu', 'shizuishan', 'wuhe', 'jinzhou', 'my', 'liuyang', 'huxian', 'zhoushan', 'tianmen', 'qixia', 'zhaoyuan', 'zhuji', 'jizhou', 'enshi', 'cqtongliang', 'jncq', 'hezhou', 'yangqu', 'zhongmou', 'fengcheng', 'tz', 'yuyao', 'bulgaria', 'dxal', 'fushun', 'yichun', 'jr', 'qingyuan', 'baoying', 'baise', 'xingyang', 'haidong', 'yixing', 'pingdingshan', 'hanzhong', 'lhk', 'yanshi', 'cqzhongxian', 'zh', 'xinyang', 'hengyang', 'au', 'youxian', 'guilin', 'hbys', 'renqiu', 'putian', 'luan', 'nt', 'mianyang', 'xishuangbanna', 'gaoyou', 'shangluo', 'quangang', 'puer', 'xam', 'yangjiang', 'qionglai', 'yizheng', 'wuwei', 'jiamusi', 'yutian', 'zhangqiu', 'haixi', 'shannan', 'hnyy', 'cn', 'xinzheng', 'portugal', 'jiangyan', 'enping', 'bt', 'liuzhou', 'kangping', 'luannan', 'jc', 'longyan', 'dandong', 'zunyi', 'hailin', 'sxyulin', 'wushan', 'hebi', 'laiyang', 'hailaer', 'changyi', 'rugao', 'yanling', 'cyprus', 'zouping', 'hbzx', 'xintai', 'scjt', 'hbps', 'xx', 'nanping', 'luoyuan', 'xinle', 'fengdu', 'hblt', 'changde', 'cz', 'wanning', 'sx', 'yz', 'laishui', 'huangnan', 'xilinhaote', 'zhaodong', 'zhuozhou', 'liangshan', 'jxfuzhou', 'yidu', 'wenling', 'yanan', 'fs', 'hnxa', 'zunhua', 'dl', 'fuan', 'binzhou', 'liaoyang', 'jinzhong', 'xiangxi', 'sjz', 'leshan', 'yueqing', 'bayan', 'xinzhou', 'nanchong', 'jssn', 'huanggang', 'hljyichun', 'chongzuo', 'guoluo', 'ninghai', 'bd', 'fuling', 'yancheng', 'quzhou', 'yiwu', 'nb', 'nongan', 'fjax', 'zhumadian', 'donghai', 'cs', 'qhd', 'dazhou', 'cixi', 'ezhou', 'puning', 'gannan', 'guigang', 'zhaozhou', 'taian', 'yongqing', 'haicheng', 'dehong', 'sanmenxia', 'shuozhou', 'zhenhai', 'qidong', 'wuxi', 'siping', 'abazhou', 'sy', 'danzhou', 'dingzhou', 'jsfx', 'tongxiang', 'ls', 'qianxinan', 'yaan', 'fuxin', 'shishi', 'linhai', 'shangqiu', 'zjg', 'chongzhou', 'luohe', 'huairen', 'shaoguan', 'cqkaixian', 'xian', 'naqu', 'yushu', 'akesu', 'xiangyang', 'ankang', 'fz', 'kuerle', 'qj', 'suzhou', 'baiyin', 'cqjiangjin', 'jian', 'dg', 'kzls', 'kaiping', 'longnan', 'wenshan', 'panjin', 'ks', 'songxian', 'haibei', 'changxing', 'chenzhou', 'linyi', 'jingzhou', 'hn', 'qingzhou', 'ya', 'guangan', 'laibin', 'qiqihaer', 'yongchun', 'wf', 'zhongxiang', 'binxian', 'lincang', 'changzhi', 'gaoling', 'yongzhou', 'lankao', 'zhuzhou', 'hs', 'qiandongnan', 'wuhai', 'yichuan', 'shennongjia', 'shuangyashan', 'suihua', 'jining', 'liaoyuan', 'mas']
[ "936844218@qq.com" ]
936844218@qq.com
e6cfad498bd1578ed61cc72f6ff9f0afede40cf4
c651ea919f24fcf51cbe27d1c336b9324fda74e6
/crypto/500-john-pollard/solve.py
b84ac8258c6a01329b9083966cb61303ce369c20
[]
no_license
paiv/picoctf2019
31f611b21bcab0d1c84fd3cb246c7dd58f6949df
90b1db56ac8c5b47ec6159d45c8decd6b90d06d5
refs/heads/master
2020-08-11T03:38:55.580861
2019-10-11T20:48:44
2019-10-11T20:48:44
214,483,178
1
0
null
null
null
null
UTF-8
Python
false
false
385
py
#!/usr/bin/env python from Crypto.PublicKey import RSA from Crypto.Util.number import inverse as modinv def solve(): N = 4966306421059967 P = 73176001 Q = 67867967 E = 65537 assert N == P * Q D = modinv(E, (P - 1) * (Q - 1)) key = RSA.construct((N, E, D, P, Q)) return key.exportKey().decode('ascii') if __name__ == '__main__': print(solve())
[ "pavels.code@gmail.com" ]
pavels.code@gmail.com
44e421c442c37ca6f99ea92a51ed39af07a99133
ee7ca0fed1620c3426fdfd22e5a82bba2a515983
/dsn_product_category_etc/__openerp__.py
1f8392a509a4099e8874d1954698391fad0dd020
[]
no_license
disna-sistemas/odoo
318d0e38d9b43bea56978fe85fc72850d597f033
0826091462cc10c9edc3cc29ea59c417f8e66c33
refs/heads/8.0
2022-03-08T19:01:21.162717
2022-02-15T13:06:26
2022-02-15T13:06:26
99,210,381
0
5
null
2019-07-24T08:49:58
2017-08-03T08:36:55
Python
UTF-8
Python
false
false
1,560
py
########################################################################## # Copyright (C) 2014 Victor Martin # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # ########################################################################## { "name": "Disna - Product Category Etc", "version": "0.1", "author": "Disna, S.A.", "contributors": [], "website": "", "category": "", "depends": ['product'], "description": """ - Adds mrp_report_order field to category """, "data": ['views/category.xml'], "installable": True, "auto_install": False, }
[ "sistemas@disna.com" ]
sistemas@disna.com
8b2ab66af68481455a92b01c01544ecda55282c0
a8d4f5601272a7f3ced564ac822745ca460e77d8
/learn_prophet/outlier.py
13adf79c7421a190ce97e45f0dd70ca070938919
[]
no_license
631068264/learn_science
cc2962e54e61e7d2d5a338b19c2046aa92743edf
6bf33da5d40b1d8d72bb63d4a7b11031dd74329b
refs/heads/master
2022-10-08T18:14:08.281828
2022-09-24T13:00:53
2022-09-24T13:00:53
82,647,091
0
0
null
2022-09-09T17:58:48
2017-02-21T06:55:43
Python
UTF-8
Python
false
false
865
py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author = 'wyx' @time = 2017/6/22 11:20 @annotation = '' """ import numpy as np import pandas as pd from fbprophet import Prophet from matplotlib import pyplot as plot df = pd.read_csv('example_wp_R_outliers1.csv') df['y'] = np.log(df['y']) print df.head() print df.tail() m = Prophet() # df.loc[(df['ds'] > '2010-01-01') & (df['ds'] < '2011-01-01'), 'y'] = None m.fit(df) """ 解决过度离散值 The best way to handle outliers is to remove them - Prophet has no problem with missing data. If you set their values to NA in the history but leave the dates in future, then Prophet will give you a prediction for their values. """ future = m.make_future_dataframe(periods=365) # print future.tail() forecast = m.predict(future) print forecast.head() # m.plot(forecast) m.plot_components(forecast) plot.show()
[ "l631068264@gmail.com" ]
l631068264@gmail.com
cdc4ca08ae44286d2d239b72735acddccf8aac07
350db570521d3fc43f07df645addb9d6e648c17e
/0338_Counting_Bits/solution_test.py
7724ba269c5cf844f2d1619dfea305095cf3e247
[]
no_license
benjaminhuanghuang/ben-leetcode
2efcc9185459a1dd881c6e2ded96c42c5715560a
a2cd0dc5e098080df87c4fb57d16877d21ca47a3
refs/heads/master
2022-12-10T02:30:06.744566
2022-11-27T04:06:52
2022-11-27T04:06:52
236,252,145
1
1
null
null
null
null
UTF-8
Python
false
false
360
py
''' 338. Counting Bits Level: Medium https://leetcode.com/problems/counting-bits ''' import unittest class TestSum(unittest.TestCase): def test_sum(self): self.assertEqual(sum([1, 2, 3]), 6, "Should be 6") def test_sum_tuple(self): self.assertEqual(sum((1, 2, 2)), 6, "Should be 6") if __name__ == '__main__': unittest.main()
[ "bhuang@rms.com" ]
bhuang@rms.com
641ddc30ca583d7d31b730a032de503e692c58cd
e580a8ccad49c20a6a8ca924369a7ed7c7b85274
/nbgrader/preprocessors/base.py
5fb73f68151a0649c54a0fc66fc10a07d3fe33bd
[ "BSD-3-Clause" ]
permissive
jdfreder/nbgrader
b06cec1ca7dc7633a36ee18859c9509fafbf63d5
a6773f27ad2be44505071bbfbfacbbbffe1b0d0d
refs/heads/master
2021-01-18T11:53:18.017422
2015-04-09T22:17:56
2015-04-09T22:17:56
32,471,870
1
0
null
2015-03-25T16:08:14
2015-03-18T16:53:33
Python
UTF-8
Python
false
false
376
py
from IPython.nbconvert.preprocessors import Preprocessor from IPython.utils.traitlets import List, Unicode, Bool class NbGraderPreprocessor(Preprocessor): default_language = Unicode('ipython') display_data_priority = List(['text/html', 'application/pdf', 'text/latex', 'image/svg+xml', 'image/png', 'image/jpeg', 'text/plain']) enabled = Bool(True, config=True)
[ "jhamrick@berkeley.edu" ]
jhamrick@berkeley.edu
027e34753a5633d392d90e6a3351c2c1ee646140
0fd66a4a28bdc7d967ec18d90eca5cc54b5cbdd4
/middleware/legato/library/plugins/scripts/generator/fontsource.py
85e614f4f6ad2d71a1b35a15aabe28e38d391989
[ "LicenseRef-scancode-unknown-license-reference", "ISC", "LicenseRef-scancode-public-domain" ]
permissive
fb321/gfx
b865539ea6acd9c99d11a3968424ae03b5dea438
e59a8d65ef77d4b017fdc523305d4d29a066d92a
refs/heads/master
2020-06-27T14:20:24.209933
2019-07-31T22:01:05
2019-07-31T22:01:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,638
py
def generateFontSourceFile(font): name = font.getName() antialias = font.getAntialias() height = font.getAdjustedHeight() baseline = font.getBaseline() style = "" if antialias == True: style += "Antialias" if len(style) == 0: style = "Plain" if style.endswith(",") == True: style = style[:-1] fontData = font.generateFontData() if fontData.glyphs.size() == 0: return fntSrc = File("generated/font/le_gen_font_" + name + ".c") fntSrc.write('#include "gfx/legato/generated/le_gen_assets.h"') fntSrc.writeNewLine() fntSrc.write("/*********************************") fntSrc.write(" * Legato Font Asset") fntSrc.write(" * Name: %s" % (name)) fntSrc.write(" * Height: %d" % (height)) fntSrc.write(" * Baseline: %d" % (baseline)) fntSrc.write(" * Style: %s" % (style)) fntSrc.write(" * Glyph Count: %d" % (fontData.glyphs.size())) fntSrc.write(" * Range Count: %d" % (fontData.ranges.size())) fntSrc.writeNoNewline(" * Glyph Ranges: ") idx = 0 for range in fontData.ranges: start = range.getStartOrdinal() end = range.getEndOrdinal() if idx == 0: if start != end: fntSrc.write("0x%02X-0x%02X" % (start, end)) else: fntSrc.write("0x%02X" % (start)) else: if start != end: fntSrc.write(" 0x%02X-0x%02X" % (start, end)) else: fntSrc.write(" 0x%02X" % (start)) idx += 1 fntSrc.write(" *********************************/") locIdx = font.getMemoryLocationIndex() kerningData = fontData.getKerningDataArray() kerningDataLength = len(kerningData) fntSrc.write("/*********************************") fntSrc.write(" * font glyph kerning table description") fntSrc.write(" *") fntSrc.write(" * unsigned int - number of glyphs") fntSrc.write(" * for each glyph:") fntSrc.write(" * unsigned short - codepoint * the glyph's codepoint") fntSrc.write(" * short - width * the glyph's width in pixels") fntSrc.write(" * short - height * the glyph's height in pixels") fntSrc.write(" * short - advance * the glyph's advance value in pixels") fntSrc.write(" * short - bearingX * the glyph's bearing value in pixels on the X axis") fntSrc.write(" * short - bearingY * the glyph's bearing value in pixels on the Y axis") fntSrc.write(" * unsigned short - flags * status flags for this glyph") fntSrc.write(" * unsigned short - data row width * the size of a row of glyph data in bytes") fntSrc.write(" * unsigned int - data table offset * the offset into the corresponding font data table") fntSrc.write(" ********************************/") if locIdx == 0: # internal flash = const fntSrc.writeNoNewline("const ") fntSrc.write("uint8_t %s_glyphs[%d] =" % (name, kerningDataLength)) fntSrc.write("{") writeBinaryData(fntSrc, kerningData, kerningDataLength) fntSrc.write("};") fntSrc.writeNewLine() if locIdx < 2: glyphData = fontData.getGlyphDataArray() glyphDataLength = len(glyphData) fntSrc.write("/*********************************") fntSrc.write(" * raw font glyph data") fntSrc.write(" ********************************/") if locIdx == 0: # internal flash = const fntSrc.writeNoNewline("const ") fntSrc.write("uint8_t %s_data[%d] =" % (name, glyphDataLength)) fntSrc.write("{") writeBinaryData(fntSrc, glyphData, glyphDataLength) fntSrc.write("};") fntSrc.writeNewLine() antialias = font.getAntialias() bpp = 1 if antialias == True: bpp = 8 memLocName = "" if locIdx < 2: memLocName = "LE_STREAM_LOCATION_ID_INTERNAL" else: memLocName = font.getMemoryLocationName() fntSrc.write("leRasterFont %s =" % (name)) fntSrc.write("{") fntSrc.write(" {") fntSrc.write(" {") fntSrc.write(" %s, // data location id" % (memLocName)) fntSrc.write(" (void*)%s_data, // data address pointer" % (name)) fntSrc.write(" %d, // data size" % (glyphDataLength)) fntSrc.write(" },") fntSrc.write(" LE_RASTER_FONT,") fntSrc.write(" },") fntSrc.write(" %d," % (fontData.getMaxHeight())) fntSrc.write(" %d," % (fontData.getMaxBaseline())) fntSrc.write(" LE_FONT_BPP_%d, // bits per pixel" % (bpp)) fntSrc.write(" %s_glyphs, // glyph table" % (name)) fntSrc.write("};") fntSrc.close() global fileDict fileDict[fntSrc.name] = fntSrc
[ "http://support.microchip.com" ]
http://support.microchip.com
198ed41b5675e5534cc3b177590fa2b0b589576d
de24f83a5e3768a2638ebcf13cbe717e75740168
/moodledata/vpl_data/10/usersdata/132/9933/submittedfiles/testes.py
7261bb0dd0a251c9ed449627f60c5cd59e8963a4
[]
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
213
py
# -*- coding: utf-8 -*- from __future__ import division maior=0 dia=1 for i in range(1,31,1): n=input('numero de discos vendidos') if n>maior: maior=n dia=i print(dia) print(maior)
[ "rafael.mota@ufca.edu.br" ]
rafael.mota@ufca.edu.br
0a30aaf77f75e4687957aa58e4ba2fd7b68f29b2
058d94f394a985627d3953fc06d8581edea886fd
/src/dvtests/__init__.py
3d3d923c67fecaf20093ae106634d6f866795b51
[ "MIT" ]
permissive
gdcc/dataverse_tests
7c3d01158a4ba8f519509b312decaf81dbea5441
d37791f588969973f1bb651e83154247ffdb9d49
refs/heads/master
2023-04-15T08:48:32.037168
2022-07-20T08:18:42
2022-07-20T08:18:42
233,846,862
2
4
MIT
2022-07-20T08:08:31
2020-01-14T13:24:51
Python
UTF-8
Python
false
false
494
py
"""Find out more at https://github.com/AUSSDA/dataverse_tests. Copyright 2022 Stefan Kasberger Licensed under the MIT License. """ from requests.packages import urllib3 urllib3.disable_warnings() # noqa __author__ = "Stefan Kasberger" __email__ = "mail@stefankasberger.at" __copyright__ = "Copyright (c) 2022 Stefan Kasberger" __license__ = "MIT License" # __version__ = "0.1.0" __url__ = "https://github.com/gdcc/dataverse_tests" __description__ = "Dataverse tests." __name__ = "dvtests"
[ "mail@stefankasberger.at" ]
mail@stefankasberger.at
98ba95f8dbff24f9396d835c83b3232a91d917cc
83dab2b5adaf537c525a04584e21501871fc8a4e
/model/write_data.py
e0fff521dd14697fc28f71a5ea1191330a5d6955
[]
no_license
Najah-Shanableh/lead-public
7852e2371d186c9e097fde01b3e0d7c1b2fc044e
f538249c43e0444b45b5ef4e58aa46811e825a58
refs/heads/master
2021-05-30T06:47:44.511409
2015-04-21T15:33:08
2015-04-21T15:33:08
null
0
0
null
null
null
null
UTF-8
Python
false
false
403
py
#!/usr/bin/python import sys import yaml import util import os directory = sys.argv[1] if not os.path.exists(directory): os.makedirs(directory) with open(sys.argv[2]) as f: params = yaml.load(f) params['data']['directory'] = directory engine = util.create_engine() data_name = params['data'].pop('name') data = util.get_class(data_name)(**params['data']) data.read_sql() data.write()
[ "eric@k2co3.net" ]
eric@k2co3.net
0b5bbe3d5d84622d94ea279b1eb39216ea4a5707
c49a6e67a63a541f8d420e725af155505d1e7f84
/Design/lru-cache*.py
8d4594e47dd5afbac9564423dc042919a58233fb
[]
no_license
wttttt-wang/leetcode_withTopics
b41ed0f8a036fd00f3b457e5b56efe32f872ca13
e2837f3d6c23f012148a2d1f9d0ef6d34d4e6912
refs/heads/master
2021-09-05T05:03:47.519344
2018-01-24T08:28:58
2018-01-24T08:28:58
112,893,345
0
0
null
null
null
null
UTF-8
Python
false
false
1,800
py
""" LRU Cache @ Design: 1. Two hashMap + One linkedList 2. should be careful when dealing with hashMap in case of 'keyError' 3. reminder to update self.tail """ class ListNode(object): def __init__(self, val): self.val, self.next = val, None class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.k2v, self.k2node = {}, {} self.head, self.capacity = ListNode(0), capacity self.tail = self.head def get(self, key): """ :type key: int :rtype: int """ if key not in self.k2v: return -1 val = self.k2v[key] node = self.removeNode(self.k2node[key].next) self.addAhead(node, val) return val def put(self, key, value): """ :type key: int :type value: int :rtype: void """ if key in self.k2v: node = self.removeNode(self.k2node[key].next) self.addAhead(node, value) return if len(self.k2v) == self.capacity: self.removeNode(self.tail) self.addAhead(ListNode(key), value) def removeNode(self, node): if node.next: self.k2node[node.next.val] = self.k2node[node.val] else: self.tail = self.k2node[node.val] self.k2node[node.val].next = node.next self.k2node.pop(node.val) self.k2v.pop(node.val) return node def addAhead(self, node, value): if self.head.next: self.k2node[self.head.next.val] = node else: self.tail = node node.next = self.head.next self.head.next = node self.k2node[node.val] = self.head self.k2v[node.val] = value
[ "wttttt@Wttttt-de-MacBookPro.local" ]
wttttt@Wttttt-de-MacBookPro.local
90db8927ca3b2e6e98fbb58229d85981f53b2c12
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03583/s935139311.py
7cb09551156a49be9231f099550afb736cbc3172
[]
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
362
py
N = int(input()) flag = 0 for a in range(1,3501): if flag ==1: break for b in range(1,3501): if 4*a*b - a*N - b*N != 0: if a*b*N // (4*a*b - a*N - b* N) > 0 and a*b*N % (4*a*b - a*N - b* N) ==0: c = int(a*b*N / (4*a*b - a*N - b* N)) print(a, b, c) flag = 1 break
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
720b5a826589b2a2d5604841f4151d6cc8627e71
0c4309d55acb30fb3270400ba9243764193573a0
/parte_2/semana_3/tipo_triangulo.py
41c2700a6416da1c51e7a021d3d6f6a33feaa62f
[]
no_license
mwoitek/python-coursera
8936e39eece19bb40caa1dab98b14529dc836db7
90d5d390868d0d0147d837939ee0fab2450c646c
refs/heads/master
2022-04-25T20:02:45.984640
2020-04-30T01:16:57
2020-04-30T01:16:57
244,276,342
0
0
null
null
null
null
UTF-8
Python
false
false
537
py
class Triangulo: def __init__(self, lado1, lado2, lado3): self.a = lado1 self.b = lado2 self.c = lado3 def perimetro(self): return self.a + self.b + self.c def tipo_lado(self): teste1 = self.a == self.b teste2 = self.a == self.c teste3 = self.b == self.c if teste1 and teste2 and teste3: return "equilátero" elif (not teste1) and (not teste2) and (not teste3): return "escaleno" else: return "isósceles"
[ "woitek@usp.br" ]
woitek@usp.br
8fe3bd1dd3226d26dac5e8615714e7b61fbb87a2
261fa90a0ab6b844682465356fee1d5f490774d7
/02_matplotlib/06_axis.py
7a085813afb58ff177ab889e8c38e236fd44e6b6
[]
no_license
lofues/Data_Science
85d7fcd6e2e7f3dad6392010b30272bb8ca9d1b3
d91a05325bf597f641d9af1afcf26575489c4960
refs/heads/master
2020-09-03T12:43:01.998302
2019-11-07T09:17:19
2019-11-07T09:17:19
219,464,996
0
0
null
null
null
null
UTF-8
Python
false
false
421
py
import numpy as np import matplotlib.pyplot as mp ax = mp.gca() ax.xaxis.set_major_locator(mp.MultipleLocator(1)) ax.xaxis.set_minor_locator(mp.MultipleLocator(0.1)) # 只查看x轴的1 到 10 mp.xlim(1,10) # 不查看y轴 mp.yticks([]) ax.spines['left'].set_color('none') ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.spines['bottom'].set_position(('data',0.5)) mp.tight_layout() mp.show()
[ "junfuwang@163.com" ]
junfuwang@163.com
466f0141c621c5aa74cf85f313b58d9f62a6e995
6ab9a3229719f457e4883f8b9c5f1d4c7b349362
/leetcode/00098_validate_binary_search_tree.py
68b7dceaba479602951e0e5e99a36a25a8abc2fc
[]
no_license
ajmarin/coding
77c91ee760b3af34db7c45c64f90b23f6f5def16
8af901372ade9d3d913f69b1532df36fc9461603
refs/heads/master
2022-01-26T09:54:38.068385
2022-01-09T11:26:30
2022-01-09T11:26:30
2,166,262
33
15
null
null
null
null
UTF-8
Python
false
false
569
py
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def isValidBST(self, root: TreeNode, left: int = None, right: int = None) -> bool: if not root: return True if left is not None and root.val <= left: return False if right is not None and root.val >= right: return False return self.isValidBST(root.left, left, root.val) and self.isValidBST(root.right, root.val, right)
[ "mistermarin@gmail.com" ]
mistermarin@gmail.com
18665ea34c033295b8e4700a027f68063c854ab4
dc99adb79f15b3889a7ef6139cfe5dfc614889b8
/Aplikace_1_0/Source/libs/datastore/permanent_datastore.py
6935c3ec09a6f86e8c847f2670ed1d8ef4f13de6
[]
no_license
meloun/ew_aplikace
95d1e4063a149a10bb3a96f372691b5110c26b7b
f890c020ad8d3d224f796dab3f1f222c1f6ba0eb
refs/heads/master
2023-04-28T06:43:12.252105
2023-04-18T19:59:36
2023-04-18T19:59:36
2,674,595
0
2
null
null
null
null
UTF-8
Python
false
false
3,752
py
# -*- coding: utf-8 -*- import libs.datastore.datastore as datastore import libs.db.db_json as db_json class PermanentDatastore(datastore.Datastore): def __init__(self, filename, default_data): #create datastore, default dictionary datastore.Datastore.__init__(self, default_data) #create db, restore: permanents from default dict self.db = db_json.Db(filename, self.GetAllPermanents()) #update datastore from db self.Update(self.db.load()) #consistency check, if not consistent then update the datastore self.consistency_check = self.UpdateConsistencyDict(self.data, default_data) print "I: Dstore: consistency check: ", self.consistency_check if(self.consistency_check == False): self.db.dump(self.GetAllPermanents()) def Update(self, update_dict): #update data datastore.Datastore.Update(self, update_dict) #update file with permanents datapoints self.db.dump(self.GetAllPermanents()) #update consistency def UpdateConsistencyDict(self, destination, source): ret = True for k,v in source.iteritems(): if isinstance(v, dict): #print "UCD----UCL", k, v if self.UpdateConsistencyDict(destination[k], v) == False: ret = False elif isinstance(v, list): if self.UpdateConsistencyList(destination[k], v) == False: ret = False else: if k not in destination: print "----NOT MATCH", k, v destination[k] = v ret = False #else: # print "-MATCH", k, v return ret def UpdateConsistencyList(self, destination, source): ret = True for i in range(len(source)): if isinstance(source[i], dict): #print "UCL----UCD", source[i] if self.UpdateConsistencyDict(destination[i], source[i]) == False: ret = False elif isinstance(source[i], list): #print "UCL----UCL", source[i] if self.UpdateConsistencyList(destination[i], source[i]) == False: ret = False return ret def Set(self, name, value, section = "GET_SET", permanent = True): #update data changed = datastore.Datastore.Set(self, name, value, section) #update file if changed and permanent and self.IsPermanent(name): #print "zapis", name, value self.db.dump(self.GetAllPermanents()) def SetItem(self, name, keys, value, section = "GET_SET", permanent = True, changed = True): if(value == datastore.Datastore.GetItem(self, name, keys, section)): return #set item datastore.Datastore.SetItem(self, name, keys, value, section, changed) #store permanents to the file if permanent and self.IsPermanent(name): #print "zapis", name, keys, value, section self.db.dump(self.GetAllPermanents()) if __name__ == "__main__": mydatastore = PermanentDatastore('conf/conf_work.json', {"a":1, "b":2})
[ "lubos.melichar@gmail.com" ]
lubos.melichar@gmail.com
db04e4251289a2b13df6f327d687283cde1e585e
aaa762ce46fa0347cdff67464f56678ea932066d
/AppServer/lib/django-0.96/django/core/mail.py
b9966c2af023eea017e2bf5a0f22fe9c3067243a
[ "Apache-2.0", "LGPL-2.1-or-later", "BSD-3-Clause", "MIT", "GPL-2.0-or-later", "MPL-1.1" ]
permissive
obino/appscale
3c8a9d8b45a6c889f7f44ef307a627c9a79794f8
be17e5f658d7b42b5aa7eeb7a5ddd4962f3ea82f
refs/heads/master
2022-10-01T05:23:00.836840
2019-10-15T18:19:38
2019-10-15T18:19:38
16,622,826
1
0
Apache-2.0
2022-09-23T22:56:17
2014-02-07T18:04:12
Python
UTF-8
Python
false
false
4,253
py
# Use this module for e-mailing. from django.conf import settings from email.MIMEText import MIMEText from email.Header import Header from email.Utils import formatdate import smtplib import socket import time import random # Cache the hostname, but do it lazily: socket.getfqdn() can take a couple of # seconds, which slows down the restart of the server. class CachedDnsName(object): def __str__(self): return self.get_fqdn() def get_fqdn(self): if not hasattr(self, '_fqdn'): self._fqdn = socket.getfqdn() return self._fqdn DNS_NAME = CachedDnsName() class BadHeaderError(ValueError): pass class SafeMIMEText(MIMEText): def __setitem__(self, name, val): "Forbids multi-line headers, to prevent header injection." if '\n' in val or '\r' in val: raise BadHeaderError, "Header values can't contain newlines (got %r for header %r)" % (val, name) if name == "Subject": val = Header(val, settings.DEFAULT_CHARSET) MIMEText.__setitem__(self, name, val) def send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None): """ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. """ if auth_user is None: auth_user = settings.EMAIL_HOST_USER if auth_password is None: auth_password = settings.EMAIL_HOST_PASSWORD return send_mass_mail([[subject, message, from_email, recipient_list]], fail_silently, auth_user, auth_password) def send_mass_mail(datatuple, fail_silently=False, auth_user=None, auth_password=None): """ Given a datatuple of (subject, message, from_email, recipient_list), sends each message to each recipient list. Returns the number of e-mails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. """ if auth_user is None: auth_user = settings.EMAIL_HOST_USER if auth_password is None: auth_password = settings.EMAIL_HOST_PASSWORD try: server = smtplib.SMTP(settings.EMAIL_HOST, settings.EMAIL_PORT) if auth_user and auth_password: server.login(auth_user, auth_password) except: if fail_silently: return raise num_sent = 0 for subject, message, from_email, recipient_list in datatuple: if not recipient_list: continue from_email = from_email or settings.DEFAULT_FROM_EMAIL msg = SafeMIMEText(message, 'plain', settings.DEFAULT_CHARSET) msg['Subject'] = subject msg['From'] = from_email msg['To'] = ', '.join(recipient_list) msg['Date'] = formatdate() try: random_bits = str(random.getrandbits(64)) except AttributeError: # Python 2.3 doesn't have random.getrandbits(). random_bits = ''.join([random.choice('1234567890') for i in range(19)]) msg['Message-ID'] = "<%d.%s@%s>" % (time.time(), random_bits, DNS_NAME) try: server.sendmail(from_email, recipient_list, msg.as_string()) num_sent += 1 except: if not fail_silently: raise try: server.quit() except: if fail_silently: return raise return num_sent def mail_admins(subject, message, fail_silently=False): "Sends a message to the admins, as defined by the ADMINS setting." send_mail(settings.EMAIL_SUBJECT_PREFIX + subject, message, settings.SERVER_EMAIL, [a[1] for a in settings.ADMINS], fail_silently) def mail_managers(subject, message, fail_silently=False): "Sends a message to the managers, as defined by the MANAGERS setting." send_mail(settings.EMAIL_SUBJECT_PREFIX + subject, message, settings.SERVER_EMAIL, [a[1] for a in settings.MANAGERS], fail_silently)
[ "root@lucid64.hsd1.ca.comcast.net" ]
root@lucid64.hsd1.ca.comcast.net
6818fa3cae3acad1fdf03d2dc50d5db778b3fdb6
ad10f4d1530fe4ededfbb93ee31042c9e5c24e9a
/Data Structure/dataframe/21_dataframe에 현재 시간 기준 column 추가하기.py
ca7472dc6d67464724dfd8b9ff597bcc767ee050
[]
no_license
WinterBlue16/Function-for-work
0d76ea2c326e547ad0cc3171f4a5a09d02de5a58
38603549b448198c12b48c95147516dbbc3f28f2
refs/heads/master
2022-07-15T20:30:26.178739
2022-07-04T13:42:01
2022-07-04T13:42:01
238,364,618
0
0
null
null
null
null
UTF-8
Python
false
false
189
py
""" dataframe에 현재 시간을 기준으로 한 column을 추가합니다. """ import pandas as pd def add_datetime_col(df): df['created_at'] = pd.to_datetime('now') return df
[ "leekh090163@gmail.com" ]
leekh090163@gmail.com
bbb18f7782294604bc2614f3e8036877cec6f4c2
09e57dd1374713f06b70d7b37a580130d9bbab0d
/benchmark/startCirq1646.py
a4be0a640c12c3a50a9fd916217514b0b775b2e0
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
4,350
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=5 # total number=63 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for the rotation angles in the QAOA circuit. def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=3 c.append(cirq.H.on(input_qubit[1])) # number=4 c.append(cirq.H.on(input_qubit[0])) # number=57 c.append(cirq.CZ.on(input_qubit[4],input_qubit[0])) # number=58 c.append(cirq.H.on(input_qubit[0])) # number=59 c.append(cirq.Z.on(input_qubit[4])) # number=55 c.append(cirq.CNOT.on(input_qubit[4],input_qubit[0])) # number=56 c.append(cirq.H.on(input_qubit[2])) # number=50 c.append(cirq.CZ.on(input_qubit[4],input_qubit[2])) # number=51 c.append(cirq.H.on(input_qubit[2])) # number=52 c.append(cirq.H.on(input_qubit[2])) # number=5 c.append(cirq.H.on(input_qubit[3])) # number=6 c.append(cirq.H.on(input_qubit[4])) # number=21 for i in range(2): c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=7 c.append(cirq.H.on(input_qubit[3])) # number=8 c.append(cirq.H.on(input_qubit[0])) # number=17 c.append(cirq.H.on(input_qubit[1])) # number=18 c.append(cirq.H.on(input_qubit[2])) # number=19 c.append(cirq.H.on(input_qubit[3])) # number=20 c.append(cirq.H.on(input_qubit[0])) # number=28 c.append(cirq.Z.on(input_qubit[3])) # number=42 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=29 c.append(cirq.H.on(input_qubit[0])) # number=30 c.append(cirq.H.on(input_qubit[0])) # number=43 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=44 c.append(cirq.H.on(input_qubit[0])) # number=45 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=35 c.append(cirq.H.on(input_qubit[0])) # number=60 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=61 c.append(cirq.H.on(input_qubit[0])) # number=62 c.append(cirq.X.on(input_qubit[0])) # number=39 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=40 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=37 c.append(cirq.H.on(input_qubit[0])) # number=46 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=47 c.append(cirq.H.on(input_qubit[0])) # number=48 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=27 c.append(cirq.X.on(input_qubit[1])) # number=10 c.append(cirq.X.on(input_qubit[2])) # number=11 c.append(cirq.X.on(input_qubit[3])) # number=12 c.append(cirq.X.on(input_qubit[0])) # number=13 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=22 c.append(cirq.Y.on(input_qubit[2])) # number=41 c.append(cirq.X.on(input_qubit[1])) # number=23 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=24 c.append(cirq.rx(1.0398671683382215).on(input_qubit[2])) # number=31 c.append(cirq.X.on(input_qubit[2])) # number=15 c.append(cirq.X.on(input_qubit[3])) # number=16 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 5 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq1646.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
3c6920fd556e9c8e818a39d2f5644c70aa619222
a8e8ae98c26a54a99ea840a10140e4c5c4080f27
/external/workload-automation/wa/workloads/stress_ng/__init__.py
9cf1a7d70eb25e29226a15e28fdd39399af418d4
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "GPL-2.0-only" ]
permissive
ARM-software/lisa
c51ea10d9f1ec1713a365ca0362f176c6a333191
be8427f24d7565c0668cd51ed7ed55867fcec889
refs/heads/main
2023-08-30T20:55:20.646965
2023-08-29T15:15:12
2023-08-29T16:19:20
47,548,304
200
131
Apache-2.0
2023-09-14T11:03:27
2015-12-07T11:32:56
Jupyter Notebook
UTF-8
Python
false
false
5,840
py
# Copyright 2015, 2018 ARM Limited # # 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. # pylint: disable=attribute-defined-outside-init import os from wa import Workload, Parameter, ConfigError, Executable from wa.framework.exception import WorkloadError from wa.utils.exec_control import once from wa.utils.serializer import yaml class StressNg(Workload): name = 'stress-ng' description = """ Run the stress-ng benchmark. stress-ng will stress test a computer system in various selectable ways. It was designed to exercise various physical subsystems of a computer as well as the various operating system kernel interfaces. stress-ng can also measure test throughput rates; this can be useful to observe performance changes across different operating system releases or types of hardware. However, it has never been intended to be used as a precise benchmark test suite, so do NOT use it in this manner. The official website for stress-ng is at: http://kernel.ubuntu.com/~cking/stress-ng/ Source code are available from: http://kernel.ubuntu.com/git/cking/stress-ng.git/ """ parameters = [ Parameter('stressor', kind=str, default='cpu', allowed_values=['cpu', 'io', 'fork', 'switch', 'vm', 'pipe', 'yield', 'hdd', 'cache', 'sock', 'fallocate', 'flock', 'affinity', 'timer', 'dentry', 'urandom', 'sem', 'open', 'sigq', 'poll'], description=''' Stress test case name. The cases listed in allowed values come from the stable release version 0.01.32. The binary included here compiled from dev version 0.06.01. Refer to man page for the definition of each stressor. '''), Parameter('extra_args', kind=str, default="", description=''' Extra arguments to pass to the workload. Please note that these are not checked for validity. '''), Parameter('threads', kind=int, default=0, description=''' The number of workers to run. Specifying a negative or zero value will select the number of online processors. '''), Parameter('duration', kind=int, default=60, description=''' Timeout for test execution in seconds ''') ] @once def initialize(self, context): if not self.target.is_rooted: raise WorkloadError('stress-ng requires root premissions to run') resource = Executable(self, self.target.abi, 'stress-ng') host_exe = context.get_resource(resource) StressNg.binary = self.target.install(host_exe) def setup(self, context): self.log = self.target.path.join(self.target.working_directory, 'stress_ng_output.txt') self.results = self.target.path.join(self.target.working_directory, 'stress_ng_results.yaml') self.command = ('{} --{} {} {} --timeout {}s --log-file {} --yaml {} ' '--metrics-brief --verbose' .format(self.binary, self.stressor, self.threads, self.extra_args, self.duration, self.log, self.results)) self.timeout = self.duration + 10 def run(self, context): self.output = self.target.execute(self.command, timeout=self.timeout, as_root=True) def extract_results(self, context): self.host_file_log = os.path.join(context.output_directory, 'stress_ng_output.txt') self.host_file_results = os.path.join(context.output_directory, 'stress_ng_results.yaml') self.target.pull(self.log, self.host_file_log) self.target.pull(self.results, self.host_file_results) context.add_artifact('stress_ng_log', self.host_file_log, 'log', "stress-ng's logfile") context.add_artifact('stress_ng_results', self.host_file_results, 'raw', "stress-ng's results") def update_output(self, context): with open(self.host_file_results, 'r') as stress_ng_results: results = yaml.load(stress_ng_results) try: metric = results['metrics'][0]['stressor'] throughput = results['metrics'][0]['bogo-ops'] context.add_metric(metric, throughput, 'ops') # For some stressors like vm, if test duration is too short, stress_ng # may not able to produce test throughput rate. except TypeError: msg = '{} test throughput rate not found. Please increase test duration and retry.' self.logger.warning(msg.format(self.stressor)) def validate(self): if self.stressor == 'vm' and self.duration < 60: raise ConfigError('vm test duration needs to be >= 60s.') @once def finalize(self, context): if self.uninstall: self.target.uninstall('stress-ng')
[ "douglas.raillard@arm.com" ]
douglas.raillard@arm.com
88b3e6880ce673410ca83591864b5b4b37ea19a7
81407be1385564308db7193634a2bb050b4f822e
/the-python-standard-library-by-example/socket/socket_socketpair.py
8ad13087f52f0fcdc2e9f9dab9e50f2b5dca1853
[ "MIT" ]
permissive
gottaegbert/penter
6db4f7d82c143af1209b4259ba32145aba7d6bd3
8cbb6be3c4bf67c7c69fa70e597bfbc3be4f0a2d
refs/heads/master
2022-12-30T14:51:45.132819
2020-10-09T05:33:23
2020-10-09T05:33:23
305,266,398
0
0
MIT
2020-10-19T04:56:02
2020-10-19T04:53:05
null
UTF-8
Python
false
false
630
py
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2010 Doug Hellmann. All rights reserved. # """Parent/child communication through a socket pair. """ #end_pymotw_header import socket import os parent, child = socket.socketpair() pid = os.fork() if pid: print 'in parent, sending message' child.close() parent.sendall('ping') response = parent.recv(1024) print 'response from child:', response parent.close() else: print 'in child, waiting for message' parent.close() message = child.recv(1024) print 'message from parent:', message child.sendall('pong') child.close()
[ "350840291@qq.com" ]
350840291@qq.com
1fff82cd038d8994320954689957150347257e93
48cbea4784808788e1df99662c2e9d305aa27526
/AppImageBuilder/app_dir/builder.py
be9ac9ce6583bcd849094c8efb15c3f995677f82
[ "MIT" ]
permissive
blanksteer/appimage-builder
5bc0aaecf5db89c3f496c2bd7808cfbf9d9a422c
377cb8bba7d7972c0bb695b9c7c13ecdf28a83a3
refs/heads/master
2022-12-24T17:18:10.265744
2020-09-30T18:15:24
2020-09-30T18:15:24
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,750
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.runtime.generator import RuntimeGenerator from AppImageBuilder.app_dir.bundlers.file_bundler import FileBundler from .app_info.bundle_info import BundleInfo from .app_info.desktop_entry_generator import DesktopEntryGenerator from .app_info.icon_bundler import IconBundler from .app_info.loader import AppInfoLoader from AppImageBuilder.app_dir.bundlers.factory import BundlerFactory class BuilderError(RuntimeError): pass class Builder: def __init__(self, recipe): self.recipe = recipe self.bundlers = [] self.generator = None self._load_config() def _load_config(self): self.app_dir_conf = self.recipe.get_item('AppDir') self.cache_dir = os.path.join(os.path.curdir, 'appimage-builder-cache') self._load_app_dir_path() self._load_app_info_config() bundler_factory = BundlerFactory(self.app_dir_path, self.cache_dir) bundler_factory.runtime = self.recipe.get_item('AppDir/runtime/generator', "wrapper") for bundler_name in bundler_factory.list_bundlers(): if bundler_name in self.app_dir_conf: bundler_settings = self.app_dir_conf[bundler_name] bundler = bundler_factory.create(bundler_name, bundler_settings) self.bundlers.append(bundler) self.file_bundler = FileBundler(self.recipe) def _load_app_dir_path(self): self.app_dir_path = os.path.abspath(self.recipe.get_item('AppDir/path')) os.makedirs(self.app_dir_path, exist_ok=True) def _load_app_info_config(self): loader = AppInfoLoader() self.app_info = loader.load(self.recipe) def build(self): logging.info("=================") logging.info("Generating AppDir") logging.info("=================") self._bundle_dependencies() self._generate_runtime() self._write_bundle_information() def _bundle_dependencies(self): logging.info("") logging.info("Bundling dependencies") logging.info("---------------------") for bundler in self.bundlers: bundler.run() def _generate_runtime(self): logging.info("") logging.info("Generating runtime") logging.info("__________________") runtime = RuntimeGenerator(self.recipe) runtime.generate() def _write_bundle_information(self): logging.info("") logging.info("Generating metadata") logging.info("___________________") self._bundle_app_dir_icon() self._generate_app_dir_desktop_entry() self._generate_bundle_info() def _bundle_app_dir_icon(self): icon_bundler = IconBundler(self.app_dir_path, self.app_info.icon) icon_bundler.bundle_icon() def _generate_app_dir_desktop_entry(self): desktop_entry_editor = DesktopEntryGenerator(self.app_dir_path) desktop_entry_editor.generate(self.app_info) def _generate_bundle_info(self): info = BundleInfo(self.app_dir_path, self.bundlers) info.generate()
[ "contact@azubieta.net" ]
contact@azubieta.net
86f23652ca781acfd6d1f493185c442a6d2bd25b
9ebd37765d98c245f9e90b719b03680bbf2f69e1
/sources/BadParser.py
fa3d4a388a31e1061161f341926078be69666e09
[]
no_license
icYFTL/ShadowServants-Brute-Python
e25964ad1e819f3185a7c55916fcb374153245c0
ee5d0e2fdd6dfdad57bf03e8f99607c25a2bc3c1
refs/heads/master
2020-04-23T17:38:01.912148
2019-03-15T14:07:08
2019-03-15T14:07:08
171,338,283
0
0
null
null
null
null
UTF-8
Python
false
false
1,524
py
# Version 1.2 alpha ''' How to use: Example: type_of_proxy = 1 # 1 - http, 2 - https, 3 - socks4, 4 - socks5 proxycount = 5000 # There's a limit. Read https://www.proxy-list.download/ a = BadParser(type_of_proxy,proxycount) data = a.Grab() # data = [1.1.1.1:8000, ...] ''' import requests class BadParser: def __init__(self, kind, count): print('[BadParser v.1.2 alpha]\n') if kind == 1: self.kind = 'http' elif kind == 2: self.kind = 'https' elif kind == 3: self.kind = 'socks4' elif kind == 4: self.kind = 'socks5' self.count = count self.handled = 0 self.proxy_list = [] def Grab(self): print('Work initiated. Getting data from server.') r = requests.get('https://www.proxy-list.download/api/v1/get?type={}&anon=elite'.format(self.kind)) print('Getting done. Parsing started.') r = r.text.split('\r\n') for i in r: if self.count == 'max': if i != '': self.proxy_list.append(i) self.handled += 1 else: if int(self.handled) < int(self.count): if i != '': self.proxy_list.append(i) self.handled += 1 else: break print('\nTotal parsed: {}\nWork done.\n'.format(self.handled)) return self.proxy_list
[ "savap0@yandex.ru" ]
savap0@yandex.ru
a63330c736bf3f049319c6b98f4b620ef70fc6f8
0393de557686f3a7c81d1a60bbfb3895d1e18cb1
/StreamLink/usr/lib/python3.8/site-packages/streamlink/plugins/albavision.py
6ee7957f8ee4687e5df8a97c396b32b3a77bf92b
[]
no_license
yazidzebiri/eePlugins
e91193b419ab34131a952da00e2f8e1b08cad420
36fa3dd9a8d10b4a452a33962add68f1a12d6b58
refs/heads/master
2023-06-17T16:02:37.079183
2021-07-07T12:44:05
2021-07-07T12:44:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,926
py
""" Support for the live streams on Albavision sites - http://www.tvc.com.ec/envivo - http://www.rts.com.ec/envivo - http://www.elnueve.com.ar/en-vivo - http://www.atv.pe/envivo/ATV - http://www.atv.pe/envivo/ATVMas """ import logging import re import time from streamlink import PluginError from streamlink.compat import quote, range, urlencode, urlparse from streamlink.plugin import Plugin from streamlink.stream import HLSStream from streamlink.utils import update_scheme log = logging.getLogger(__name__) class Albavision(Plugin): _url_re = re.compile(r"https?://(?:www\.)?(tvc.com.ec|rts.com.ec|elnueve.com.ar|atv.pe)/en-?vivo(?:/ATV(?:Mas)?)?") _token_input_re = re.compile(r"Math.floor\(Date.now\(\) / 3600000\),'([a-f0-9OK]+)'") _live_url_re = re.compile(r"LIVE_URL = '(.*?)';") _playlist_re = re.compile(r"file:\s*'(http.*m3u8)'") _token_url_re = re.compile(r"https://.*/token/.*?\?rsk=") _channel_urls = { 'ATV': 'http://dgrzfw9otv9ra.cloudfront.net/player_atv.html?iut=', 'ATVMas': 'http://dgrzfw9otv9ra.cloudfront.net/player_atv_mas.html?iut=', 'Canal5': 'http://dxejh4fchgs18.cloudfront.net/player_televicentro.html?iut=', 'Guayaquil': 'http://d2a6tcnofawcbm.cloudfront.net/player_rts.html?iut=', 'Quito': 'http://d3aacg6baj4jn0.cloudfront.net/reproductor_rts_o_quito.html?iut=', } def __init__(self, url): super(Albavision, self).__init__(url) self._page = None @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) is not None @property def page(self): if not self._page: self._page = self.session.http.get(self.url) return self._page def _get_token_url(self, channelnumber): token = self._get_live_url_token(channelnumber) if token: m = self._token_url_re.findall(self.page.text) token_url = m and m[channelnumber] if token_url: return token_url + token else: log.error("Could not find site token") @staticmethod def transform_token(token_in, date): token_out = list(token_in) offset = len(token_in) for i in range(offset - 1, -1, -1): p = (i * date) % offset # swap chars at p and i token_out[i], token_out[p] = token_out[p], token_out[i] token_out = ''.join(token_out) if token_out.endswith("OK"): return token_out[:-2] else: log.error("Invalid site token: {0} => {1}".format(token_in, token_out)) def _get_live_url_token(self, channelnumber): m = self._token_input_re.findall(self.page.text) log.debug("Token input: {0}".format(m[channelnumber])) if m: date = int(time.time() // 3600) return self.transform_token(m[channelnumber], date) or self.transform_token(m[channelnumber], date - 1) def _get_token(self, channelnumber): token_url = self._get_token_url(channelnumber) if token_url: res = self.session.http.get(token_url) data = self.session.http.json(res) if data['success']: return data['token'] def _get_streams(self): m = self._live_url_re.search(self.page.text) playlist_url = m and update_scheme(self.url, m.group(1)) player_url = self.url live_channel = None p = urlparse(player_url) channelnumber = 0 if p.netloc.endswith("tvc.com.ec"): live_channel = "Canal5" elif p.netloc.endswith("rts.com.ec"): live_channel = "Guayaquil" elif p.netloc.endswith("atv.pe"): if p.path.endswith(("ATVMas", "ATVMas/")): live_channel = "ATVMas" channelnumber = 1 else: live_channel = "ATV" token = self._get_token(channelnumber) log.debug("token {0}".format(token)) if playlist_url: log.debug("Found playlist URL in the page") else: if live_channel: log.debug("Live channel: {0}".format(live_channel)) player_url = self._channel_urls[live_channel] + quote(token) page = self.session.http.get(player_url, raise_for_status=False) if "block access from your country." in page.text: raise PluginError("Content is geo-locked") m = self._playlist_re.search(page.text) playlist_url = m and update_scheme(self.url, m.group(1)) else: log.error("Could not find the live channel") if playlist_url: stream_url = "{0}?{1}".format(playlist_url, urlencode({"iut": token})) return HLSStream.parse_variant_playlist(self.session, stream_url, headers={"referer": player_url}) __plugin__ = Albavision
[ "zdzislaw22@windowslive.com" ]
zdzislaw22@windowslive.com
f370e68f5f151f81a8bdc822000422bb3a00eb2f
20f951bd927e4e5cde8ef7781813fcf0d51cc3ea
/fossir/modules/events/payment/testing/fixtures.py
cd8ec800a3c8878de5cf225e634d8c0ddd435ece
[]
no_license
HodardCodeclub/SoftwareDevelopment
60a0fbab045cb1802925d4dd5012d5b030c272e0
6300f2fae830c0c2c73fe0afd9c684383bce63e5
refs/heads/master
2021-01-20T00:30:02.800383
2018-04-27T09:28:25
2018-04-27T09:28:25
101,277,325
0
2
null
null
null
null
UTF-8
Python
false
false
714
py
import pytest from fossir.modules.events.payment.models.transactions import PaymentTransaction, TransactionStatus @pytest.fixture def create_transaction(): """Returns a callable which lets you create transactions""" def _create_transaction(status, **params): params.setdefault('amount', 10) params.setdefault('currency', 'USD') params.setdefault('provider', '_manual') params.setdefault('data', {}) return PaymentTransaction(status=status, **params) return _create_transaction @pytest.fixture def dummy_transaction(create_transaction): """Gives you a dummy successful transaction""" return create_transaction(status=TransactionStatus.successful)
[ "hodardhazwinayo@gmail.com" ]
hodardhazwinayo@gmail.com
877389eadf5431f86cce9536338e7780b5b6f092
090324db0c04d8c30ad6688547cfea47858bf3af
/tests/test_sokorule.py
d0e02c22a7085d11f93f4eebbaa8548dce508f8b
[]
no_license
fidlej/sokobot
b82c4c36d73e224d0d0e1635021ca04485da589e
d3d04753a5043e6a22dafd132fa633d8bc66b9ea
refs/heads/master
2021-01-21T13:14:29.523501
2011-06-12T07:34:14
2011-06-12T07:34:14
32,650,745
1
0
null
null
null
null
UTF-8
Python
false
false
2,035
py
from nose.tools import assert_equal from soko.struct.rules.sokorule import PushRule, SokobanGoalRule from soko.struct import modeling def test_get_children(): rule = PushRule() s = ( "# #", "#@. #", " $ #", " #", "#####", ) used_cells = set() children = rule.get_children(s, used_cells) assert_equal(3, len(children)) _assert_contains(children, ("# #", "# + #", " $ #", " #", "#####", )) _assert_contains(children, ("#@ #", "# . #", " $ #", " #", "#####", )) _assert_contains(children, ("# #", "# . #", " @ #", " $ #", "#####", )) used_s = modeling.mutablize(s) for pos in used_cells: x, y = pos used_s[y][x] = "!" assert_equal(modeling.immutablize( ( "#! #", "!!! #", " ! #", " ! #", "#####", )), modeling.immutablize(used_s)) def test_get_children_from_end_state(): s = modeling.immutablize("""\ #$ # @ .# # # #####""".splitlines()) rule = PushRule() used_cells = set() children = rule.get_children(s, used_cells) assert_equal(None, children) assert_equal(set(), used_cells) def test_is_goaling(): rule = SokobanGoalRule() s = ( "# #", "# .#", " $#", " @#", "#####", ) next_s = ( "# #", "# *#", " @#", " #", "#####", ) assert_equal(True, rule.is_goaling(s, next_s)) assert_equal(False, rule.is_goaling(next_s, s)) assert_equal(False, rule.is_goaling(next_s, next_s)) def _assert_contains(childern, s): s = modeling.immutablize(s) assert s in childern
[ "ivo@danihelka.net" ]
ivo@danihelka.net
e2ec8e1807b2ada32487f68445c59d81a1985ee4
ccf94dcb6b1500fcbbd56964ae8c4832a496b8b3
/python/baiduads-sdk-auto/test/test_update_material_bind_response_wrapper_body.py
0b1aeca6da72b0508699b95f4a1b46ff5039dc1e
[ "Apache-2.0" ]
permissive
baidu/baiduads-sdk
24c36b5cf3da9362ec5c8ecd417ff280421198ff
176363de5e8a4e98aaca039e4300703c3964c1c7
refs/heads/main
2023-06-08T15:40:24.787863
2023-05-20T03:40:51
2023-05-20T03:40:51
446,718,177
16
11
Apache-2.0
2023-06-02T05:19:40
2022-01-11T07:23:17
Python
UTF-8
Python
false
false
996
py
""" dev2 api schema 'dev2.baidu.com' api schema # noqa: E501 Generated by: https://openapi-generator.tech """ import sys import unittest import baiduads from baiduads.materialbindmod.model.material_bind_update_response import MaterialBindUpdateResponse globals()['MaterialBindUpdateResponse'] = MaterialBindUpdateResponse from baiduads.materialbindmod.model.update_material_bind_response_wrapper_body import UpdateMaterialBindResponseWrapperBody class TestUpdateMaterialBindResponseWrapperBody(unittest.TestCase): """UpdateMaterialBindResponseWrapperBody unit test stubs""" def setUp(self): pass def tearDown(self): pass def testUpdateMaterialBindResponseWrapperBody(self): """Test UpdateMaterialBindResponseWrapperBody""" # FIXME: construct object with mandatory attributes with example values # model = UpdateMaterialBindResponseWrapperBody() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "v_wangzichen02@baidu.com" ]
v_wangzichen02@baidu.com
c94623fa4a303341d2a14bd2502ddbb12809ef67
75fa11b13ddab8fd987428376f5d9c42dff0ba44
/metadata-ingestion/tests/integration/ldap/test_ldap.py
3e76f13fc823d2cba27669df218aeac46589492f
[ "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
5,662
py
import time import pytest from datahub.ingestion.run.pipeline import Pipeline from tests.test_helpers import mce_helpers from tests.test_helpers.docker_helpers import wait_for_port @pytest.mark.integration def test_ldap_ingest(docker_compose_runner, pytestconfig, tmp_path, mock_time): test_resources_dir = pytestconfig.rootpath / "tests/integration/ldap" with docker_compose_runner( test_resources_dir / "docker-compose.yml", "ldap" ) as docker_services: # The openldap container loads the sample data after exposing the port publicly. As such, # we must wait a little bit extra to ensure that the sample data is loaded. wait_for_port(docker_services, "openldap", 389) # without this ldap server can provide empty results time.sleep(5) pipeline = Pipeline.create( { "run_id": "ldap-test", "source": { "type": "ldap", "config": { "ldap_server": "ldap://localhost", "ldap_user": "cn=admin,dc=example,dc=org", "ldap_password": "admin", "base_dn": "dc=example,dc=org", "group_attrs_map": { "members": "memberUid", }, "custom_props_list": ["givenName"], }, }, "sink": { "type": "file", "config": { "filename": f"{tmp_path}/ldap_mces.json", }, }, } ) pipeline.run() pipeline.raise_from_status() mce_helpers.check_golden_file( pytestconfig, output_path=tmp_path / "ldap_mces.json", golden_path=test_resources_dir / "ldap_mces_golden.json", ) @pytest.mark.integration def test_ldap_memberof_ingest(docker_compose_runner, pytestconfig, tmp_path, mock_time): test_resources_dir = pytestconfig.rootpath / "tests/integration/ldap" with docker_compose_runner( test_resources_dir / "docker-compose.yml", "ldap" ) as docker_services: # The openldap container loads the sample data after exposing the port publicly. As such, # we must wait a little bit extra to ensure that the sample data is loaded. wait_for_port(docker_services, "openldap", 389) # without this ldap server can provide empty results time.sleep(5) pipeline = Pipeline.create( { "run_id": "ldap-test", "source": { "type": "ldap", "config": { "ldap_server": "ldap://localhost", "ldap_user": "cn=admin,dc=example,dc=org", "ldap_password": "admin", "base_dn": "dc=example,dc=org", "filter": "(memberOf=cn=HR Department,dc=example,dc=org)", "attrs_list": ["+", "*"], "group_attrs_map": { "members": "member", }, }, }, "sink": { "type": "file", "config": { "filename": f"{tmp_path}/ldap_memberof_mces.json", }, }, } ) pipeline.run() pipeline.raise_from_status() mce_helpers.check_golden_file( pytestconfig, output_path=tmp_path / "ldap_memberof_mces.json", golden_path=test_resources_dir / "ldap_memberof_mces_golden.json", ) @pytest.mark.integration def test_ldap_ingest_with_email_as_username( docker_compose_runner, pytestconfig, tmp_path, mock_time ): test_resources_dir = pytestconfig.rootpath / "tests/integration/ldap" with docker_compose_runner( test_resources_dir / "docker-compose.yml", "ldap" ) as docker_services: # The openldap container loads the sample data after exposing the port publicly. As such, # we must wait a little bit extra to ensure that the sample data is loaded. wait_for_port(docker_services, "openldap", 389) time.sleep(5) pipeline = Pipeline.create( { "run_id": "ldap-test", "source": { "type": "ldap", "config": { "ldap_server": "ldap://localhost", "ldap_user": "cn=admin,dc=example,dc=org", "ldap_password": "admin", "base_dn": "dc=example,dc=org", "user_attrs_map": {"email": "mail"}, "group_attrs_map": { "members": "memberUid", "email": "mail", }, "use_email_as_username": True, "custom_props_list": ["givenName"], }, }, "sink": { "type": "file", "config": { "filename": f"{tmp_path}/ldap_mces.json", }, }, } ) pipeline.run() pipeline.raise_from_status() mce_helpers.check_golden_file( pytestconfig, output_path=tmp_path / "ldap_mces.json", golden_path=test_resources_dir / "ldap_mces_golden.json", )
[ "noreply@github.com" ]
RyanHolstien.noreply@github.com
400ac17153480a63df98dda5dac0d88bf318c97e
508321d683975b2339e5292202f3b7a51bfbe22d
/Userset.vim/ftplugin/python/CompletePack/PySide2/QtWidgets/QGraphicsPixmapItem.py
0b913af111c321403b7dbad1da4f899c98fdb78f
[]
no_license
cundesi/vimSetSa
4947d97bcfe89e27fd2727423112bb37aac402e2
0d3f9e5724b471ab21aa1199cc3b4676e30f8aab
refs/heads/master
2020-03-28T05:54:44.721896
2018-08-31T07:23:41
2018-08-31T07:23:41
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,254
py
# encoding: utf-8 # module PySide2.QtWidgets # from C:\Program Files\Autodesk\Maya2017\Python\lib\site-packages\PySide2\QtWidgets.pyd # by generator 1.145 # no doc # imports import PySide2.QtCore as __PySide2_QtCore import PySide2.QtGui as __PySide2_QtGui import Shiboken as __Shiboken from QGraphicsItem import QGraphicsItem class QGraphicsPixmapItem(QGraphicsItem): # no doc def boundingRect(self, *args, **kwargs): # real signature unknown pass def contains(self, *args, **kwargs): # real signature unknown pass def extension(self, *args, **kwargs): # real signature unknown pass def isObscuredBy(self, *args, **kwargs): # real signature unknown pass def offset(self, *args, **kwargs): # real signature unknown pass def opaqueArea(self, *args, **kwargs): # real signature unknown pass def paint(self, *args, **kwargs): # real signature unknown pass def pixmap(self, *args, **kwargs): # real signature unknown pass def setOffset(self, *args, **kwargs): # real signature unknown pass def setPixmap(self, *args, **kwargs): # real signature unknown pass def setShapeMode(self, *args, **kwargs): # real signature unknown pass def setTransformationMode(self, *args, **kwargs): # real signature unknown pass def shape(self, *args, **kwargs): # real signature unknown pass def shapeMode(self, *args, **kwargs): # real signature unknown pass def transformationMode(self, *args, **kwargs): # real signature unknown pass def type(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass BoundingRectShape = None # (!) real value is '' HeuristicMaskShape = None # (!) real value is '' MaskShape = None # (!) real value is '' ShapeMode = None # (!) real value is ''
[ "noreply@github.com" ]
cundesi.noreply@github.com
23d781e34d8d2f3ae61620fd43b6f47b75e59a5b
5b0ff689a3e14f42bdf688864cae40c931a5f685
/msa/core/armve/tests/test_multi_write.py
b2424dcb0537e0251c93404cf4c3107e15a472cd
[]
no_license
prometheus-ar/vot.ar
cd7012f2792a2504fb7f0ee43796a197fc82bd28
72d8fa1ea08fe417b64340b98dff68df8364afdf
refs/heads/2017-ago-salta
2021-01-02T22:19:41.591077
2017-08-25T11:55:49
2017-08-25T11:55:49
37,735,555
171
110
null
2020-06-30T13:33:49
2015-06-19T17:15:52
JavaScript
UTF-8
Python
false
false
1,712
py
#!/usr/bin/env python # coding: utf-8 from __future__ import division from serial import Serial from msa.core.armve.constants import DEV_PRINTER, CMD_PRINTER_PAPER_START, \ CMD_PRINTER_MOVE, EVT_PRINTER_PAPER_INSERTED, CMD_PRINTER_PRINT, \ CMD_PRINTER_PAPER_REMOVE, DEV_RFID, EVT_RFID_NEW_TAG,\ CMD_PRINTER_LOAD_COMP_BUFFER, MSG_EV_PUB from msa.core.armve.protocol import Printer, RFID, Device, Agent, \ PowerManager, PIR from msa.core.armve.settings import SERIAL_PORT def init_channel(): channel = Serial(SERIAL_PORT, timeout=3) if not channel.isOpen(): channel.open() channel.flushInput() channel.flushOutput() return channel def test_boleta(): channel = init_channel() agent = Agent(channel) init = agent.initialize() printer = Printer(channel) rfid = RFID(channel) device = Device(channel) #esperar_evento(device, DEV_PRINTER, EVT_PRINTER_PAPER_INSERTED) #print rfid.get_multitag_data() tags_data = rfid.get_tags()[0] serial_number = tags_data['serial_number'][0] rfid.write_tag(serial_number, 4, "1C", "--00--01--02--03--04--05--06--07--08--09--10--11--12" "--13--14--15--16--17--18--19--20--21--22--23--24--25" "--26--27--28--29--30--31--32--33--34--35--36--37--38" "--39--40--41--42--43--44--45--46--47--48--49--50--51" ) rfid.get_multitag_data() def esperar_evento(device, device_id, event): print("esperando evento", device_id, event) esperando = True while esperando: ret = device.read(True) if ret is not None and ret[1:] == (device_id, event, MSG_EV_PUB): esperando = False if __name__ == "__main__": test_boleta()
[ "prometheus@olympus.org" ]
prometheus@olympus.org
ea6e913cfb0bfbdeae407ef6826a14197f46c3c5
805a795ea81ca8b5cee1dec638585011da3aa12f
/MAIN/2.79/python/lib/site-packages/OpenGL/GLES2/EXT/float_blend.py
b15df56ee4bf4fa5dd71042d1b67ad8dbacc6e7d
[ "Apache-2.0" ]
permissive
josipamrsa/Interactive3DAnimation
5b3837382eb0cc2ebdee9ee69adcee632054c00a
a4b7be78514b38fb096ced5601f25486d2a1d3a4
refs/heads/master
2022-10-12T05:48:20.572061
2019-09-26T09:50:49
2019-09-26T09:50:49
210,919,746
0
1
Apache-2.0
2022-10-11T01:53:36
2019-09-25T19:03:51
Python
UTF-8
Python
false
false
750
py
'''OpenGL extension EXT.float_blend This module customises the behaviour of the OpenGL.raw.GLES2.EXT.float_blend to provide a more Python-friendly API The official definition of this extension is available here: http://www.opengl.org/registry/specs/EXT/float_blend.txt ''' from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GLES2 import _types, _glgets from OpenGL.raw.GLES2.EXT.float_blend import * from OpenGL.raw.GLES2.EXT.float_blend import _EXTENSION_NAME def glInitFloatBlendEXT(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
[ "jmrsa21@gmail.com" ]
jmrsa21@gmail.com
72c6b5820ec2373fc5c053015b127eae12ba7b5d
74fb05c7b5eddf2b368e181f38b9423a711bf2e0
/real_python_tutorails/iterators/iterators_example.py
ae43af08beec8d63c2765d453574e4ff98b5c5cb
[]
no_license
musram/python_progs
426dcd4786e89b985e43284ab5a5b1ba79cb285e
ad1f7f2b87568ba653f839fe8fa45e90cbde5a63
refs/heads/master
2022-11-10T09:53:29.993436
2020-06-21T00:21:23
2020-06-21T00:21:23
264,607,509
0
0
null
null
null
null
UTF-8
Python
false
false
1,387
py
if __name__ == "__main__": names = ['sai', 'asi', 'isa'] for name in names: print(name) #what actuall happens internally is this: it = names.__iter__() print(next(it)) #similalry f = open('/etc/passwd', 'r') it = f.__iter__() print(next(it)) #writing generator #(1) def countDown(n): print('Counting from' , n) while (n > 0): yield n n -= 1 print('Done') for x in countDown(5): print(x) #this is same as c = countDown(5) it = c.__iter__() print(next(it)) #writing genertor #(2) it = ( x for x in range(5,0,-1)) print(next(it)) #writing generator #(3) class CountDown: def __init__(self, n): self.n = n def __iter__(self): n = self.n while (n > 0): yield n n -= 1 c = CountDown(5) for x in c: print(x) import os import time def follow(filename): f = open(filename, 'r') f.seek(0, os.SEEK_END) while True: line = f.readline() if not line: time.sleep(0.1) continue yield line for line in follow('/etc/passwd'): row = line.split(',') print(row)
[ "musram@gmail.com" ]
musram@gmail.com
dd5fbc68c39d3c24641b9f746e2812d44fa78e62
e6d4a87dcf98e93bab92faa03f1b16253b728ac9
/algorithms/python/destinationCity/destinationCity.py
1b55d8c23b19986d5f6d1359d7af30216a4080a4
[]
no_license
MichelleZ/leetcode
b5a58e1822e3f6ef8021b29d9bc9aca3fd3d416f
a390adeeb71e997b3c1a56c479825d4adda07ef9
refs/heads/main
2023-03-06T08:16:54.891699
2023-02-26T07:17:47
2023-02-26T07:17:47
326,904,500
3
0
null
null
null
null
UTF-8
Python
false
false
510
py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # Source: https://leetcode.com/problems/destination-city/ # Author: Miao Zhang # Date: 2021-05-06 class Solution: def destCity(self, paths: List[List[str]]) -> str: ind = collections.defaultdict(int) out = collections.defaultdict(int) for u, v in paths: ind[v] += 1 out[u] += 1 for city, val in ind.items(): if val == 1 and out[city] == 0: return city return ''
[ "zhangdaxiaomiao@163.com" ]
zhangdaxiaomiao@163.com
441e3e75fd6b5ef8cc403e0b4b73843eb432393c
62c6e50d148f1ccd51001abedbfe748fda94427e
/backend/cookieapp/views.py
65b7b4217bfa0991bcd696807104284c0951ead4
[]
no_license
i7-Ryzen/django-jwt-httponly-cookie
be27936d0d7111688a0b2d5811edd891c2b5c925
bb21ae75b05f7b42e98da6a69f9280c51a1171fd
refs/heads/main
2023-05-06T15:30:01.870387
2021-05-24T05:35:10
2021-05-24T05:35:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,870
py
from rest_framework_simplejwt.tokens import RefreshToken from django.middleware import csrf from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth import authenticate from django.conf import settings from rest_framework import status def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } class LoginView(APIView): def post(self, request, format=None): data = request.data response = Response() username = data.get('username', None) password = data.get('password', None) user = authenticate(username=username, password=password) if user is not None: if user.is_active: data = get_tokens_for_user(user) response.set_cookie( key = settings.SIMPLE_JWT['AUTH_COOKIE'], value = data["access"], expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'], secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'], httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'], samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE'] ) csrf.get_token(request) response.data = {"Success" : "Login successfully","data":data} return response else: return Response({"No active" : "This account is not active!!"}, status=status.HTTP_404_NOT_FOUND) else: return Response({"Invalid" : "Invalid username or password!!"}, status=status.HTTP_404_NOT_FOUND)
[ "abhishekk580@gmail.com" ]
abhishekk580@gmail.com
afa792b926c2ea3c9563b1ca60d34e69bc4fc2bc
b2ba78fb1e53f92efdc3b6e0be50c81e5dd036ed
/plot_f/plot_offline_mbl_5M_all.py
ef16bbcfd8943228d88a28c336263fa8c582ed91
[ "MIT" ]
permissive
ShuoZ9379/Integration_SIL_and_MBL
2dcfae10cb5929c4121a3a8bfceebae8c0b6ba08
d7df6501a665d65eb791f7fd9b8e85fd660e6320
refs/heads/master
2020-07-23T20:04:17.304302
2019-09-23T18:58:57
2019-09-23T18:58:57
207,690,584
0
0
null
null
null
null
UTF-8
Python
false
false
3,634
py
import os, argparse, subprocess import matplotlib.pyplot as plt import numpy as np from baselines.common import plot_util as pu def arg_parser(): return argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) def filt(results,name,name_2=''): ls=[r for r in results if name in r.dirname and name_2 in r.dirname] return ls def filt_or(results,name,name_2): ls=[r for r in results if name in r.dirname or name_2 in r.dirname] return ls def filt_or_or_or(results,name,name_2,name_3,name_4): ls=[r for r in results if name in r.dirname or name_2 in r.dirname or name_3 in r.dirname or name_4 in r.dirname] return ls def main(): parser = arg_parser() parser.add_argument('--env', help='environment ID', type=str, default='HalfCheetah-v2') parser.add_argument('--dir', type=str, default='logs') parser.add_argument('--thesis', type=str, default='Offline_V0') args = parser.parse_args() # dirname = '~/Desktop/carla_sample_efficient/data/bk/bkup_EXP2_FINAL/'+args.extra_dir+args.env dirname = '~/Desktop/logs/'+args.dir+'/EXP_OFF_24_5M_V0/'+args.env results = pu.load_results(dirname) r_copos1_nosil,r_copos2_nosil,r_trpo_nosil,r_ppo_nosil=filt(results,'copos1-'),filt(results,'copos2-'),filt(results,'trpo-'),filt(results,'ppo-') r_copos1_sil,r_copos2_sil,r_trpo_sil,r_ppo_sil=filt(results,'copos1+sil-'),filt(results,'copos2+sil-'),filt(results,'trpo+sil-'),filt(results,'ppo+sil-') r_mbl_sil=filt(results,'mbl+','sil-') # r_mbl_nosil_tmp=[r for r in results if r not in r_mbl_sil] r_mbl_nosil=filt_or_or_or(results,'mbl+copos1-','mbl+copos2-','mbl+trpo-','mbl+ppo-') r_copos1_comp, r_copos2_comp, r_trpo_comp, r_ppo_comp=filt_or(results,'mbl+copos1','copos1+sil'),filt_or(results,'mbl+copos2','copos2+sil'),filt_or(results,'mbl+trpo','trpo+sil'),filt_or(results,'mbl+ppo','ppo+sil') dt={'copos1_nosil':r_copos1_nosil,'copos2_nosil':r_copos2_nosil, 'trpo_nosil':r_trpo_nosil, 'ppo_nosil':r_ppo_nosil, 'copos1_sil':r_copos1_sil,'copos2_sil':r_copos2_sil, 'trpo_sil':r_trpo_sil, 'ppo_sil':r_ppo_sil, 'mbl_nosil':r_mbl_nosil, 'mbl_sil':r_mbl_sil, 'copos1_comp':r_copos1_comp,'copos2_comp':r_copos2_comp, 'trpo_comp':r_trpo_comp, 'ppo_comp':r_ppo_comp} for name in dt: pu.plot_results(dt[name],xy_fn=pu.progress_mbl_vbest_xy_fn,average_group=True,name=name,split_fn=lambda _: '',shaded_err=True,shaded_std=False) plt.xlabel('Number of Timesteps [M]') plt.ylabel('Best Average Return [-]') plt.tight_layout() fig = plt.gcf() fig.set_size_inches(9, 7.5) # fig.savefig("/Users/zsbjltwjj/Desktop/carla_sample_efficient/plot_f/OFFLINE/"+args.extra_dir+args.env+'/'+name+'.pdf',format="pdf") fig.savefig("/Users/zsbjltwjj/Desktop/thesis/img/"+args.thesis+"/"+args.env+'/'+name+'.pdf', format="pdf") if name=='mbl_nosil' or name=='mbl_sil': pu.plot_results(dt[name],xy_fn=pu.progress_default_entropy_xy_fn,average_group=True,name=name,split_fn=lambda _: '',shaded_err=True,shaded_std=False,legend_entropy=1) plt.xlabel('Number of Timesteps [M]') plt.ylabel('Entropy [-]') plt.tight_layout() fig = plt.gcf() fig.set_size_inches(9, 7.5) # fig.savefig("/Users/zsbjltwjj/Desktop/carla_sample_efficient/plot_f/OFFLINE/"+args.extra_dir+args.env+'/'+name+'_entropy.pdf',format="pdf") fig.savefig("/Users/zsbjltwjj/Desktop/thesis/img/"+args.thesis+"/"+args.env+'/'+name+'_entropy.pdf', format="pdf") if __name__ == '__main__': main()
[ "zhangshuo19930709@gmail.com" ]
zhangshuo19930709@gmail.com
0b459f2956f8b32f62c231644e0df079e662cadd
5a82795c3860745112b7410d9060c5ef671adba0
/leetcode/Network Delay Time.py
0ead9c6fd14d36b87d1e6aaa9d1e5ac0d91d18eb
[]
no_license
ashishvista/geeks
8e09d0f3a422c1c9a1c1b19d879ebafa31b62f44
1677a304fc7857a3054b574e8702491f5ce01a04
refs/heads/master
2023-03-05T12:01:03.911096
2021-02-15T03:00:56
2021-02-15T03:00:56
336,996,558
0
0
null
null
null
null
UTF-8
Python
false
false
1,335
py
class Graph: v = None def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] self.weights = {} def addEdge(self, u, v, w): self.adj[u].append(v) self.weights[str(u) + "-" + str(v)] = w class Solution: def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int: graph = Graph(N) dist = [float("+inf") for i in range(N)] dist[K - 1] = 0 visited = {} for uv in times: graph.addEdge(uv[0] - 1, uv[1] - 1, uv[2]) varr = {K - 1: 1} while varr: su = self.getLowestCostV(varr, dist) del varr[su] visited[su] = 1 for v in graph.adj[su]: new_dist = dist[su] + graph.weights[str(su) + "-" + str(v)] if new_dist < dist[v]: dist[v] = new_dist if v not in visited: varr[v] = 1 largest = float("-inf") if len(visited) != N: return -1 for d in dist: largest = max(largest, d) return largest def getLowestCostV(self, varr, dist): sw = float("inf") sv = None for v in varr: if sw > dist[v]: sw = dist[v] sv = v return sv
[ "ashish@groomefy.com" ]
ashish@groomefy.com
e04c0bf21ef6ef4a8ce6e6a89f934139e335a5d8
f098c361ee79bb8b7a8402fcf20b37f17fb36983
/Back-End/Python/Basics/Part -1 - Functional/04 - First-Class-Functions/send_email_partial.py
f536c40a3c3798957ca6c45af1bfb96feb7036ee
[ "Apache-2.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
rnsdoodi/Programming-CookBook
4d619537a6875ffbcb42cbdaf01d80db1feba9b4
9bd9c105fdd823aea1c3f391f5018fd1f8f37182
refs/heads/master
2023-09-05T22:09:08.282385
2021-10-31T11:57:40
2021-10-31T11:57:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,291
py
from functools import partial def sendmail(to, subject, body): # code to send email print('To:{0}, Subject:{1}, Body:{2}'.format(to, subject, body)) email_admin = 'palin@python.edu' email_devteam = 'idle@python.edu;cleese@python.edu' # Now when we want to send emails we would have to write things like: # Email 1 sendmail(email_admin, 'My App Notification', 'the parrot is dead.') # Email 2 sendmail(';'.join((email_admin, email_devteam)), 'My App Notification', 'the ministry is closed until further notice.') # Email 1 # To:palin@python.edu, # Subject:My App Notification, # Body:the parrot is dead. # Email 2 # To:palin@python.edu;idle@python.edu;cleese@python.edu, # Subject:My App Notification, # Body:the ministry is closed until further notice. # Partial # Email 1 send_admin = partial(sendmail, email_admin, 'For you eyes only') # Email 2 send_dev = partial(sendmail, email_devteam, 'Dear IT:') # Email 3 send_all = partial(sendmail, ';'.join((email_admin, email_devteam)), 'Loyal Subjects') send_admin('the parrot is dead.') send_all('the ministry is closed until further notice.') def sendmail(to, subject, body, *, cc=None, bcc=email_devteam): # code to send email print('To:{0}, Subject:{1}, Body:{2}, CC:{3}, BCC:{4}'.format(to, subject, body, cc, bcc)) # Email 1 send_admin = partial(sendmail, email_admin, 'General Admin') # Email 2 send_admin_secret = partial(sendmail, email_admin, 'For your eyes only', cc=None, bcc=None) send_admin('and now for something completely different') #To:palin@python.edu, # Subject:General Admin, # Body:and now for something completely different, # CC:None, # BCC:idle@python.edu;cleese@python.edu send_admin_secret('the parrot is dead!') #To:palin@python.edu, # Subject:For your eyes only, # Body:the parrot is dead!, # CC:None, # BCC:None send_admin_secret('the parrot is no more!', bcc=email_devteam) # To:palin@python.edu, # Subject:For your eyes only, # Body:the parrot is no more!, # CC:None, # BCC:idle@python.edu;cleese@python.edu
[ "58447627+Koubae@users.noreply.github.com" ]
58447627+Koubae@users.noreply.github.com
8864c5625cee7be5cd7ac66b57768f555f562984
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/chrome/browser/resources/PRESUBMIT.py
e7a3e430986f0a2d2062a15497b6b5e3e4784501
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
Python
false
false
5,423
py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for files in chrome/browser/resources. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ import re ACTION_XML_PATH = '../../../tools/metrics/actions/actions.xml' def CheckUserActionUpdate(input_api, output_api, action_xml_path): """Checks if any new user action has been added.""" if any('actions.xml' == input_api.os_path.basename(f) for f in input_api.change.LocalPaths()): # If actions.xml is already included in the changelist, the PRESUBMIT # for actions.xml will do a more complete presubmit check. return [] file_filter = lambda f: f.LocalPath().endswith('.html') action_re = r'(^|\s+)metric\s*=\s*"([^ ]*)"' current_actions = None for f in input_api.AffectedFiles(file_filter=file_filter): for line_num, line in f.ChangedContents(): match = input_api.re.search(action_re, line) if match: # Loads contents in tools/metrics/actions/actions.xml to memory. It's # loaded only once. if not current_actions: with open(action_xml_path) as actions_f: current_actions = actions_f.read() metric_name = match.group(2) is_boolean = IsBoolean(f.NewContents(), metric_name, input_api) # Search for the matched user action name in |current_actions|. if not IsActionPresent(current_actions, metric_name, is_boolean): return [output_api.PresubmitPromptWarning( 'File %s line %d: %s is missing in ' 'tools/metrics/actions/actions.xml. Please run ' 'tools/metrics/actions/extract_actions.py to update.' % (f.LocalPath(), line_num, metric_name), [])] return [] def IsActionPresent(current_actions, metric_name, is_boolean): """Checks if metric_name is defined in the actions file. Checks whether there's matching entries in an actions.xml file for the given |metric_name|, depending on whether it is a boolean action. Args: current_actions: The content of the actions.xml file. metric_name: The name for which the check should be done. is_boolean: Whether the action comes from a boolean control. """ if not is_boolean: action = 'name="{0}"'.format(metric_name) return action in current_actions action_disabled = 'name="{0}_Disable"'.format(metric_name) action_enabled = 'name="{0}_Enable"'.format(metric_name) return (action_disabled in current_actions and action_enabled in current_actions) def IsBoolean(new_content_lines, metric_name, input_api): """Check whether action defined in the changed code is boolean or not. Checks whether the action comes from boolean control based on the HTML elements attributes. Args: new_content_lines: List of changed lines. metric_name: The name for which the check should be done. """ new_content = '\n'.join(new_content_lines) html_element_re = r'<(.*?)(^|\s+)metric\s*=\s*"%s"(.*?)>' % (metric_name) type_re = (r'datatype\s*=\s*"boolean"|type\s*=\s*"checkbox"|' 'type\s*=\s*"radio".*?value\s*=\s*("true"|"false")') match = input_api.re.search(html_element_re, new_content, input_api.re.DOTALL) return (match and any(input_api.re.search(type_re, match.group(i)) for i in (1, 3))) def CheckHtml(input_api, output_api): return input_api.canned_checks.CheckLongLines( input_api, output_api, 80, lambda x: x.LocalPath().endswith('.html')) def RunOptimizeWebUiTests(input_api, output_api): presubmit_path = input_api.PresubmitLocalPath() tests = [input_api.os_path.join(presubmit_path, 'optimize_webui_test.py')] return input_api.canned_checks.RunUnitTests(input_api, output_api, tests) def _CheckWebDevStyle(input_api, output_api): results = [] try: import sys old_sys_path = sys.path[:] cwd = input_api.PresubmitLocalPath() sys.path += [input_api.os_path.join(cwd, '..', '..', '..', 'tools')] import web_dev_style.presubmit_support results += web_dev_style.presubmit_support.CheckStyle(input_api, output_api) finally: sys.path = old_sys_path return results def _CheckChangeOnUploadOrCommit(input_api, output_api): results = CheckUserActionUpdate(input_api, output_api, ACTION_XML_PATH) affected = input_api.AffectedFiles() if any(f for f in affected if f.LocalPath().endswith('.html')): results += CheckHtml(input_api, output_api) if any(f for f in affected if f.LocalPath().endswith('optimize_webui.py')): results += RunOptimizeWebUiTests(input_api, output_api) results += _CheckWebDevStyle(input_api, output_api) results += input_api.canned_checks.CheckPatchFormatted(input_api, output_api, check_js=True) return results def CheckChangeOnUpload(input_api, output_api): return _CheckChangeOnUploadOrCommit(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return _CheckChangeOnUploadOrCommit(input_api, output_api) def PostUploadHook(cl, change, output_api): return output_api.EnsureCQIncludeTrybotsAreAdded( cl, [ 'master.tryserver.chromium.linux:closure_compilation', ], 'Automatically added optional Closure bots to run on CQ.')
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
c709879b1fee60eecdc644534c5f072428a76609
31eaed64b0caeda5c5fe3603609402034e6eb7be
/python_zumbi/py_functions/ler_e_gravar_arquivo_CSV.py
e8d6a926b35a01ceccefbd8155a6cdd818c3a912
[]
no_license
RaphaelfsOliveira/workspace_python
93657b581043176ecffb5783de208c0a00924832
90959697687b9398cc48146461750942802933b3
refs/heads/master
2021-01-11T17:39:49.574875
2017-06-28T20:55:43
2017-06-28T20:55:43
79,814,783
0
0
null
null
null
null
UTF-8
Python
false
false
307
py
import csv arq_name = "test" title = 'perfumes' name_prod = 'perfume-feminino' url_prod = 'http://www.epocacosmeticos.com.br/perfumes/perfume-feminino' rows = ['teste','teste'] def save_urls(arq_name, rows): arq = csv.writer(open(arq_name + '.csv', "w")) arq.writerow(rows) print(rows) #print(arq)
[ "raphaelbrf@gmail.com" ]
raphaelbrf@gmail.com
3be5e6031a6351f732e4aa3e3ecf6dc74d11eb6c
f5c62bab2e95bb2dc6986ba271662ade8cae4da0
/docs/PythonSAI/LineProperties.py
c3e7401f40524540e570646be946433183820cfd
[]
no_license
Has3ong/X3DViewer
d211b159c29523e61158eddc015bb320e4ba7c9d
c629305c24b5c25fd41d3a46816efbf1f74d0092
refs/heads/master
2021-06-25T16:36:46.278469
2021-01-03T11:26:02
2021-01-03T11:26:02
180,564,246
0
0
null
null
null
null
UTF-8
Python
false
false
1,729
py
from . import * # LineProperties defines a concrete node interface that extends interface X3DAppearanceChildNode. class CLineProperties(CX3DAppearanceChildNode): m_strNodeName = "LineProperties" def __init__(self): self.m_strNodeName = "LineProperties" self.m_Parent = [None] self.children = [] self.DEF = "" self.USE = "" self.n_Count = -1 self.depth = 0 # Return boolean result from SFBool inputOutput field named "applied" def getApplied (self): pass # Assign boolean value to SFBool inputOutput field named "applied" def setApplied (self, value): pass # Return int result [] from SFInt32 inputOutput field named "linetype" def getLinetype (self): pass # Assign int value [] to SFInt32 inputOutput field named "linetype" def setLinetype (self, value): pass # Return float result [] from SFFloat inputOutput field named "linewidthScaleFactor" def getLinewidthScaleFactor (self): pass # Assign float value [] to SFFloat inputOutput field named "linewidthScaleFactor" def setLinewidthScaleFactor (self, value): pass # ===== methods for fields inherited from parent interfaces ===== # Return X3DMetadataObject result (using a properly typed node or X3DPrototypeInstance) from SFNode inputOutput field named "metadata" def getMetadata (self): pass # Assign X3DMetadataObject value (using a properly typed node) to SFNode inputOutput field named "metadata" def setMetadata1 (self, node): pass # Assign X3DMetadataObject value (using a properly typed protoInstance) def setMetadata2 (self, protoInstance): pass
[ "khsh5592@naver.com" ]
khsh5592@naver.com
4dc0710a308eb43121ff85c314929338cc1ad68d
f98c45d0079479b10c8276693dc31c704ccc087f
/api/apps/goods/models.py
9f7696a669fbacebb0c26a81978d4226843c2828
[ "MIT" ]
permissive
TasHole/tokyo
b78c84d31b5c459a8a508fd671151a825db55835
d4e0b2cce2aae53d93cb2bbbd2ca12ff0aa6a219
refs/heads/master
2020-12-21T13:29:31.626154
2019-10-12T03:03:34
2019-10-12T03:03:34
236,445,029
0
0
null
null
null
null
UTF-8
Python
false
false
5,857
py
from datetime import datetime from django.db import models class GoodsCategory(models.Model): """ 商品カテゴリー """ CATEGORY_TYPE = ( (1, "一級カテゴリー"), (2, "二級カテゴリー"), (3, "三級カテゴリー") ) name = models.CharField(default="", max_length=50, verbose_name="カテゴリー名", help_text="カテゴリー名") code = models.CharField(default="", max_length=30, verbose_name="カテゴリーコード", help_text="カテゴリーコード") desc = models.TextField(default="", verbose_name="カテゴリー説明", help_text="カテゴリー説明") category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="カテゴリーレベル", help_text="カテゴリーレベル") parent_category = models.ForeignKey("self", null=True, blank=True, verbose_name="親カテゴリー", help_text="親カテゴリー", on_delete=models.CASCADE, related_name="sub_cat") is_tab = models.BooleanField(default=False, verbose_name="ナビなのか", help_text="ナビなのか") add_time = models.DateTimeField(default=datetime.now, verbose_name="挿入時間") class Meta: verbose_name = "商品カテゴリー" verbose_name_plural = verbose_name def __str__(self): return self.name class GoodsCategoryBrand(models.Model): """ ブランド名 """ category = models.ForeignKey(GoodsCategory, related_name="brands", null=True, blank=True, verbose_name="商品カテゴリー名", on_delete=models.CASCADE) name = models.CharField(default="", max_length=30, verbose_name="ブランド名", help_text="ブランド名") desc = models.CharField(default="", max_length=200, verbose_name="ブランド説明", help_text="ブランド説明") image = models.ImageField(max_length=200, upload_to="brands/") add_time = models.DateTimeField(default=datetime.now, verbose_name="挿入時間") class Meta: verbose_name = "ブランド" verbose_name_plural = verbose_name db_table = "goods_goodsbrand" def __str__(self): return self.name class Goods(models.Model): """ 商品 """ category = models.ForeignKey(GoodsCategory, null=True, blank=True, verbose_name="商品カテゴリー", on_delete=models.CASCADE) goods_sn = models.CharField(max_length=50, default="", verbose_name="商品識別番号") name = models.CharField(max_length=100, verbose_name="商品名") click_num = models.IntegerField(default=0, verbose_name="クリック数") sold_num = models.IntegerField(default=0, verbose_name="販売数") fav_num = models.IntegerField(default=0, verbose_name="お気に入り登録数") goods_num = models.IntegerField(default=0, verbose_name="在庫数") market_price = models.FloatField(default=0, verbose_name="原価") shop_price = models.FloatField(default=0, verbose_name="販売値段") goods_brief = models.TextField(max_length=500, verbose_name="商品説明") ship_free = models.BooleanField(default=True, verbose_name="送料負担") goods_front_image = models.ImageField(max_length=200, upload_to="goods/images/", null=True, blank=True, verbose_name="表紙") is_new = models.BooleanField(default=False, verbose_name="新品なのか") is_hot = models.BooleanField(default=False, verbose_name="売れているのか") add_time = models.DateTimeField(default=datetime.now, verbose_name="挿入時間") class Meta: verbose_name = "商品" verbose_name_plural = verbose_name def __str__(self): return self.name class GoodsImage(models.Model): """ 商品swiperImages """ goods = models.ForeignKey(Goods, verbose_name="商品", related_name="images", on_delete=models.CASCADE) image = models.ImageField(upload_to="", verbose_name="画像", null=True, blank=True) add_time = models.DateTimeField(default=datetime.now, verbose_name="挿入時間") class Meta: verbose_name = "商品swiperImages" verbose_name_plural = verbose_name def __str__(self): return self.goods.name class Banner(models.Model): """ swiper用の商品image """ goods = models.ForeignKey(Goods, verbose_name="商品", on_delete=models.CASCADE) image = models.ImageField(upload_to="banner", verbose_name="ホームページswiper用画像") index = models.IntegerField(default=0, verbose_name="swiper順番") add_time = models.DateTimeField(default=datetime.now, verbose_name="挿入時間") class Meta: verbose_name = "swiper用の商品image" verbose_name_plural = verbose_name def __str__(self): return self.goods.name class IndexAd(models.Model): category = models.ForeignKey(GoodsCategory, related_name="category", verbose_name="商品カテゴリー", on_delete=models.CASCADE) goods = models.ForeignKey(Goods, related_name='goods', on_delete=models.CASCADE) class Meta: verbose_name = "ホームページ商品カテゴリー広告" verbose_name_plural = verbose_name def __str__(self): return self.goods.name class HotSearchWords(models.Model): """ 人気キーワード """ keywords = models.CharField(default="", max_length=20, verbose_name="人気キーワード") index = models.IntegerField(default=0, verbose_name="並び順") add_time = models.DateTimeField(default=datetime.now, verbose_name="挿入時間") class Meta: verbose_name = "人気キーワード" verbose_name_plural = verbose_name def __str__(self): return self.keywords
[ "txy1226052@gmail.com" ]
txy1226052@gmail.com
88fd6306ddf23894d2552a4e2bc87e2b89a734df
e489172f6e49e1239db56c047a78a29a6ffc0b36
/via_code_decode/code_category.py
ab1f0d754b5245b8d99d0e949b26421de5effc09
[]
no_license
eksotama/prln-via-custom-addons
f05d0059353ae1de89ccc8d1625a896c0215cfc7
f2b44a8af0e7bee87d52d258fca012bf44ca876f
refs/heads/master
2020-03-25T19:49:08.117628
2015-12-01T07:29:43
2015-12-01T07:29:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,052
py
# -*- encoding: utf-8 -*- ############################################################################## # # Vikasa Infinity Anugrah, PT # Copyright (c) 2011 - 2013 Vikasa Infinity Anugrah <http://www.infi-nity.com> # # 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 osv import osv, fields from tools.translate import _ class code_category(osv.osv): _name = 'code.category' _description = 'Code Category' _columns = { 'name': fields.char('Code Category', size=64, readonly=False, required=True, translate=True, select=True, help="Register Code Category"), 'pinned': fields.boolean('Pinned', readonly=True, help="This is to mark whether the code category is 'pinned', i.e. cannot be deleted. Can be used by modules to force existence of the code category."), } _defaults = { 'pinned' : False, } ## unlink # # unlink intercepts the main unlink function to prevent deletion of pinned record. # def unlink(self, cr, uid, ids, context=None): for _obj in self.pool.get('code.category').browse(cr, uid, ids, context=context): if _obj.pinned: raise osv.except_osv(_('Error !'), _('Pinned Code Category cannot be deleted.')) return super(code_category, self).unlink(cr, uid, ids, context=context) code_category()
[ "aero@aero.(none)" ]
aero@aero.(none)
386d526236ceef1e4accd80ace256f69374c7b69
266f073facf1754763af372f3b4433337161f91a
/memegen/domain/template.py
4c61cdbd88b6c6134c5c7f14b2935ed1e4fbc5d5
[ "MIT" ]
permissive
jkloo/memegen
7717104eedc0db1cad15673b426f1ebdb5119445
9360486066b52ede528f0c45671f81ebb168e3b3
refs/heads/master
2020-04-05T18:55:54.182899
2015-06-19T13:47:24
2015-06-19T13:47:24
37,665,345
0
0
null
2015-06-18T14:46:22
2015-06-18T14:46:22
null
UTF-8
Python
false
false
950
py
import os from .text import Text class Template: """Blank image to generate a meme.""" DEFAULTS = ("default.png", "default.jpg") def __init__(self, key, name=None, lines=None, aliases=None, link=None, root=None): self.key = key self.name = name or "" self.lines = lines or [] self.aliases = aliases or [] self.link = link or "" self.root = root def __eq__(self, other): return self.key == other.key def __ne__(self, other): return not self == other def __lt__(self, other): return self.name < other.name @property def path(self): for default in self.DEFAULTS: path = os.path.join(self.root, self.key, default) if os.path.isfile(path): return path return None @property def default(self): text = Text('/'.join(self.lines)) return text.path
[ "jacebrowning@gmail.com" ]
jacebrowning@gmail.com
b941f4fec6db3324f517391c833d36bd9deb602e
1a114943c92a5db40034470ff31a79bcf8ddfc37
/stdlib_exam/unicodedata-example-1.py
8ab800f4c75d0ac65e9f6fbc5d28206808558553
[]
no_license
renwl/mylinux
1924918599efd6766c266231d66b2a7ed6f6cdd1
0602fc6d2b0d254a8503e57310f848fc3e1a73b4
refs/heads/master
2020-07-10T22:12:03.259349
2017-01-02T12:32:04
2017-01-02T12:32:04
66,467,007
0
0
null
null
null
null
WINDOWS-1252
Python
false
false
396
py
import unicodedata for char in [u"A", u"-", u"1", u"\N{LATIN CAPITAL LETTER O WITH DIAERESIS}"]: print repr(char), print unicodedata.category(char), print repr(unicodedata.decomposition(char)), print unicodedata.decimal(char, None), print unicodedata.numeric(char, None) ## u'A' Lu '' None None ## u'-' Pd '' None None ## u'1' Nd '' 1 1.0 ## u'Ö' Lu '004F 0308' None None
[ "wenliang.ren@quanray.com" ]
wenliang.ren@quanray.com
b73000ba07270793015730c3be257dec3a98ded0
4bb1a23a62bf6dc83a107d4da8daefd9b383fc99
/work/abc032_c2.py
45cd9b0ea7fccb2e9ffe3042836077ee7d77a58a
[]
no_license
takushi-m/atcoder-work
0aeea397c85173318497e08cb849efd459a9f6b6
f6769f0be9c085bde88129a1e9205fb817bb556a
refs/heads/master
2021-09-24T16:52:58.752112
2021-09-11T14:17:10
2021-09-11T14:17:10
144,509,843
0
0
null
null
null
null
UTF-8
Python
false
false
328
py
n,k = map(int, input().split()) al = [int(input()) for _ in range(n)] if 0 in al: print(n) exit() r = 0 l = 0 m = 1 res = 0 while l<n: while r<n and m*al[r]<=k: m *= al[r] r += 1 res = max(res, r-l) if r==l: r += 1 else: m //= al[l] l += 1 print(res)
[ "takushi-m@users.noreply.github.com" ]
takushi-m@users.noreply.github.com
71619690ce1315a1467d2da14697223edb31bfb4
195915dab8406c2e934d0ffa8c500b1317c5e6f1
/bestrestra/settings.py
220f1de76ec4f3342e69561c80dc947ed02197e7
[]
no_license
theparadoxer02/bestrestra
28c2e46ae124a7496d889933daefe3c36dbbe9a2
13dccc988ee78eebc685111cb486a8c1342deb3c
refs/heads/master
2020-12-24T19:51:07.521744
2017-03-26T08:09:18
2017-03-26T08:09:18
86,217,158
0
0
null
null
null
null
UTF-8
Python
false
false
3,586
py
""" Django settings for bestrestra project. Generated by 'django-admin startproject' using Django 1.10.6. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'na-%mmzwa4(a%9erh$fsqxs_)4ur_-$sbeof6u!2%ptq)u4xn&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'bestrestra.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'bestresta/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'bestrestra.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'clashhacks', 'USER': 'abhi' } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['*'] DEBUG = False try: from .local_settings import * except ImportError: pass
[ "abhimanyu98986@gmail.com" ]
abhimanyu98986@gmail.com
d78b8ac24c093f12b1ac5b5411620c0f589fe4cc
89a90707983bdd1ae253f7c59cd4b7543c9eda7e
/fluent_python/attic/strings-bytes/plane_count.py
dac414b93c5d84ddd35ad15b932051af53a9aa7a
[]
no_license
timothyshull/python_reference_code
692a7c29608cadfd46a6cc409a000023e95b9458
f3e2205dd070fd3210316f5f470d371950945028
refs/heads/master
2021-01-22T20:44:07.018811
2017-03-17T19:17:22
2017-03-17T19:17:22
85,346,735
0
0
null
null
null
null
UTF-8
Python
false
false
349
py
import sys from unicodedata import name total_count = 0 bmp_count = 0 for i in range(sys.maxunicode): char = chr(i) char_name = name(char, None) if char_name is None: continue total_count += 1 if i <= 0xffff: bmp_count += 1 print(total_count, bmp_count, bmp_count / total_count, bmp_count / total_count * 100)
[ "timothyshull@gmail.com" ]
timothyshull@gmail.com
065653bd83e3294aa3c38f6cf48f8ece93f51edd
854da1bbabc83d4506febe01932177f54f163399
/extapps/xadmin/plugins/ueditor.py
745f7814a207baf3ee53f697922cb502bb541560
[]
no_license
RainysLiu/XinJuKe
abdefbf67513f5192e5716ebf547e0797a86af6f
9decde1fe5e6020d31e18264795d640c9ff77383
refs/heads/master
2021-07-18T13:59:05.414626
2020-07-01T12:36:22
2020-07-01T12:36:22
188,654,087
3
0
null
null
null
null
UTF-8
Python
false
false
1,388
py
import xadmin from xadmin.views import ( BaseAdminPlugin, CreateAdminView, ModelFormAdminView, UpdateAdminView, ) from DjangoUeditor.models import UEditorField from DjangoUeditor.widgets import UEditorWidget from django.conf import settings class XadminUEditorWidget(UEditorWidget): def __init__(self, **kwargs): self.ueditor_options = kwargs self.Media.js = None super(XadminUEditorWidget, self).__init__(kwargs) class UeditorPlugin(BaseAdminPlugin): def get_field_style(self, attrs, db_field, style, **kwargs): if style == "ueditor": if isinstance(db_field, UEditorField): widget = db_field.formfield().widget param = {} param.update(widget.ueditor_settings) param.update(widget.attrs) return {"widget": XadminUEditorWidget(**param)} return attrs def block_extrahead(self, context, nodes): js = '<script type="text/javascript" src="%s"></script>' % ( settings.STATIC_URL + "ueditor/ueditor.config.js" ) js += '<script type="text/javascript" src="%s"></script>' % ( settings.STATIC_URL + "ueditor/ueditor.all.min.js" ) nodes.append(js) xadmin.site.register_plugin(UeditorPlugin, UpdateAdminView) xadmin.site.register_plugin(UeditorPlugin, CreateAdminView)
[ "1072799939@qq.com" ]
1072799939@qq.com
dc51cca1327c27bef64e3434b98898b1bda20d4d
62e58c051128baef9452e7e0eb0b5a83367add26
/edifact/D03B/CUSEXPD03BUN.py
15e7b3ed5e7dda7f9d69367842f3c0e6d1a041dc
[]
no_license
dougvanhorn/bots-grammars
2eb6c0a6b5231c14a6faf194b932aa614809076c
09db18d9d9bd9d92cefbf00f1c0de1c590fe3d0d
refs/heads/master
2021-05-16T12:55:58.022904
2019-05-17T15:22:23
2019-05-17T15:22:23
105,274,633
0
0
null
2017-09-29T13:21:21
2017-09-29T13:21:21
null
UTF-8
Python
false
false
2,519
py
#Generated by bots open source edi translator from UN-docs. from bots.botsconfig import * from edifact import syntax from recordsD03BUN import recorddefs structure = [ {ID: 'UNH', MIN: 1, MAX: 1, LEVEL: [ {ID: 'BGM', MIN: 1, MAX: 1}, {ID: 'DTM', MIN: 0, MAX: 5}, {ID: 'LOC', MIN: 0, MAX: 5}, {ID: 'CNT', MIN: 0, MAX: 9}, {ID: 'NAD', MIN: 1, MAX: 1, LEVEL: [ {ID: 'CTA', MIN: 0, MAX: 5, LEVEL: [ {ID: 'COM', MIN: 0, MAX: 5}, ]}, ]}, {ID: 'TDT', MIN: 1, MAX: 1, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 1}, {ID: 'LOC', MIN: 0, MAX: 9, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 9}, ]}, ]}, {ID: 'EQD', MIN: 0, MAX: 99, LEVEL: [ {ID: 'SEL', MIN: 0, MAX: 9}, ]}, {ID: 'RFF', MIN: 0, MAX: 999, LEVEL: [ {ID: 'NAD', MIN: 0, MAX: 2}, {ID: 'CNT', MIN: 0, MAX: 1}, {ID: 'CNI', MIN: 1, MAX: 9999, LEVEL: [ {ID: 'SGP', MIN: 0, MAX: 9}, {ID: 'CNT', MIN: 0, MAX: 9}, {ID: 'MEA', MIN: 0, MAX: 1}, {ID: 'LOC', MIN: 0, MAX: 2}, {ID: 'NAD', MIN: 0, MAX: 5}, {ID: 'GDS', MIN: 0, MAX: 1, LEVEL: [ {ID: 'FTX', MIN: 0, MAX: 1}, ]}, {ID: 'PAC', MIN: 0, MAX: 999, LEVEL: [ {ID: 'PCI', MIN: 0, MAX: 1}, ]}, {ID: 'TOD', MIN: 0, MAX: 1, LEVEL: [ {ID: 'LOC', MIN: 0, MAX: 1}, {ID: 'FTX', MIN: 0, MAX: 1}, ]}, {ID: 'MOA', MIN: 0, MAX: 10, LEVEL: [ {ID: 'CUX', MIN: 0, MAX: 1, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 1}, ]}, ]}, {ID: 'TAX', MIN: 0, MAX: 9, LEVEL: [ {ID: 'MOA', MIN: 0, MAX: 1}, {ID: 'GEI', MIN: 0, MAX: 1}, ]}, {ID: 'DOC', MIN: 0, MAX: 9, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 1}, {ID: 'LOC', MIN: 0, MAX: 1}, ]}, {ID: 'CST', MIN: 0, MAX: 99, LEVEL: [ {ID: 'FTX', MIN: 0, MAX: 1}, {ID: 'LOC', MIN: 1, MAX: 1}, {ID: 'MEA', MIN: 0, MAX: 9}, {ID: 'TAX', MIN: 0, MAX: 9, LEVEL: [ {ID: 'MOA', MIN: 0, MAX: 1}, {ID: 'GEI', MIN: 0, MAX: 1}, ]}, ]}, ]}, ]}, {ID: 'AUT', MIN: 0, MAX: 1, LEVEL: [ {ID: 'DTM', MIN: 0, MAX: 1}, ]}, {ID: 'UNT', MIN: 1, MAX: 1}, ]}, ]
[ "jason.capriotti@gmail.com" ]
jason.capriotti@gmail.com
f0ac7f36ebe9a2ecc3df8f36c5b37c55347462fa
cec10c52b4f879161928da88ed9294007874f50f
/libs/configs/cfgs_fcos_coco_res50_1x_v3.py
a950340aa0304fd7c7051b6c4b5437e073af1639
[ "MIT" ]
permissive
g-thebest/FCOS_Tensorflow
676ea7ec358de248860238c0c00817dd6176bfb7
b39b621c9a84dcb4baad25637e7758dcd31707f5
refs/heads/master
2021-11-04T21:39:47.093239
2019-04-28T09:25:26
2019-04-28T09:25:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,115
py
# -*- coding: utf-8 -*- from __future__ import division, print_function, absolute_import import os import math import tensorflow as tf import numpy as np # ------------------------------------------------ VERSION = 'FCOS_Res50_20190427' NET_NAME = 'resnet50_v1d' # 'resnet_v1_50' ADD_BOX_IN_TENSORBOARD = True # ---------------------------------------- System_config ROOT_PATH = os.path.abspath('../') print(20*"++--") print(ROOT_PATH) GPU_GROUP = "0,1,2,3,4,5,6,7" NUM_GPU = len(GPU_GROUP.strip().split(',')) SHOW_TRAIN_INFO_INTE = 10 SMRY_ITER = 100 SAVE_WEIGHTS_INTE = 80000 SUMMARY_PATH = ROOT_PATH + '/output/summary' TEST_SAVE_PATH = ROOT_PATH + '/tools/test_result' INFERENCE_IMAGE_PATH = ROOT_PATH + '/tools/inference_image' INFERENCE_SAVE_PATH = ROOT_PATH + '/tools/inference_results' if NET_NAME.startswith("resnet"): weights_name = NET_NAME elif NET_NAME.startswith("MobilenetV2"): weights_name = "mobilenet/mobilenet_v2_1.0_224" else: raise NotImplementedError PRETRAINED_CKPT = ROOT_PATH + '/data/pretrained_weights/' + weights_name + '.ckpt' TRAINED_CKPT = os.path.join(ROOT_PATH, 'output/trained_weights') EVALUATE_DIR = ROOT_PATH + '/output/evaluate_result_pickle/' # ------------------------------------------ Train config FIXED_BLOCKS = 1 # allow 0~3 FREEZE_BLOCKS = [True, False, False, False, False] # for gluoncv backbone USE_07_METRIC = False MUTILPY_BIAS_GRADIENT = None # 2.0 # if None, will not multipy GRADIENT_CLIPPING_BY_NORM = None # 10.0 if None, will not clip BATCH_SIZE = 1 EPSILON = 1e-5 MOMENTUM = 0.9 LR = 5e-4 * NUM_GPU * BATCH_SIZE DECAY_STEP = [SAVE_WEIGHTS_INTE*12, SAVE_WEIGHTS_INTE*16, SAVE_WEIGHTS_INTE*20] MAX_ITERATION = SAVE_WEIGHTS_INTE*20 WARM_SETP = int(0.125 * SAVE_WEIGHTS_INTE) # -------------------------------------------- Data_preprocess_config DATASET_NAME = 'coco' PIXEL_MEAN = [123.68, 116.779, 103.939] # R, G, B. In tf, channel is RGB. In openCV, channel is BGR PIXEL_MEAN_ = [0.485, 0.456, 0.406] PIXEL_STD = [0.229, 0.224, 0.225] IMG_SHORT_SIDE_LEN = 800 IMG_MAX_LENGTH = 1333 CLASS_NUM = 80 # --------------------------------------------- Network_config SUBNETS_WEIGHTS_INITIALIZER = tf.random_normal_initializer(mean=0.0, stddev=0.01, seed=None) SUBNETS_BIAS_INITIALIZER = tf.constant_initializer(value=0.0) FINAL_CONV_WEIGHTS_INITIALIZER = tf.random_normal_initializer(mean=0.0, stddev=0.01, seed=None) PROBABILITY = 0.01 FINAL_CONV_BIAS_INITIALIZER = tf.constant_initializer(value=-np.log((1.0 - PROBABILITY) / PROBABILITY)) WEIGHT_DECAY = 0.00004 if NET_NAME.startswith('Mobilenet') else 0.0001 # ---------------------------------------------Anchor config USE_CENTER_OFFSET = True LEVLES = ['P3', 'P4', 'P5', 'P6', 'P7'] BASE_ANCHOR_SIZE_LIST = [32, 64, 128, 256, 512] ANCHOR_STRIDE_LIST = [8, 16, 32, 64, 128] SET_WIN = np.asarray([0, 64, 128, 256, 512, 1e5]) * IMG_SHORT_SIDE_LEN / 800 # --------------------------------------------FPN config SHARE_HEADS = True ALPHA = 0.25 GAMMA = 2 NMS = True NMS_IOU_THRESHOLD = 0.5 NMS_TYPE = 'NMS' MAXIMUM_DETECTIONS = 300 FILTERED_SCORES = 0.15 SHOW_SCORE_THRSHOLD = 0.2
[ "yangxue@megvii.com" ]
yangxue@megvii.com
addc002a7f3d8d394abb90d6c6298ef91d7d0c55
a075b20c2c7bee1655c30bd5d2c1c3634755bd48
/utils.py
8bb0b9c56833eab7a2fa5d85081e2c4f9b7a83fd
[]
no_license
gitter-badger/style-transfer
96d4b337c662055cb275dadf3846c58ab5227252
e7518d6a718d06c5f537602307ffa37abaa58a15
refs/heads/master
2021-01-20T10:18:32.335649
2017-08-28T06:45:13
2017-08-28T06:45:13
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,890
py
import scipy.misc, numpy as np, os, sys from shutil import rmtree, move import tensorflow as tf from PIL import Image import glob, random, bcolz from six.moves import urllib as six_urllib try: import urllib2 as urllib except ImportError: import urllib.request as urllib from collections import OrderedDict import tarfile _RESIZE_SIDE_MIN = 320 class OrderedDefaultListDict(OrderedDict): def __missing__(self, key): self[key] = value = [] return value def _central_crop(image, side): image_height = tf.shape(image)[0] image_width = tf.shape(image)[1] offset_height = (image_height - side) / 2 offset_width = (image_width - side) / 2 original_shape = tf.shape(image) cropped_shape = tf.stack([side, side, 3]) offsets = tf.to_int32(tf.stack([offset_height, offset_width, 0])) image = tf.slice(image, offsets, cropped_shape) return tf.reshape(image, cropped_shape) def _smallest_size_at_least(height, width, smallest_side): smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32) height = tf.to_float(height) width = tf.to_float(width) smallest_side = tf.to_float(smallest_side) scale = tf.cond(tf.greater(height, width), lambda: smallest_side / width, lambda: smallest_side / height) new_height = tf.to_int32(height * scale) new_width = tf.to_int32(width * scale) return new_height, new_width def _aspect_preserving_resize(image, smallest_side): smallest_side = tf.convert_to_tensor(smallest_side, dtype=tf.int32) shape = tf.shape(image) height, width = shape[0], shape[1] new_height, new_width = _smallest_size_at_least(height, width, smallest_side) image = tf.expand_dims(image, 0) resized_image = tf.image.resize_bilinear(image, [new_height, new_width], align_corners=False) resized_image = tf.squeeze(resized_image, [0]) resized_image.set_shape([None, None, 3]) return resized_image def preprocess_image(image, side, resize_side=_RESIZE_SIDE_MIN, is_training=False): image = _aspect_preserving_resize(image, resize_side) if(is_training): image = tf.random_crop(image, [side, side, 3]) else: image = _central_crop(image, side) return image class data_pipeline: def __init__(self, train_path, sq_size=256, batch_size=4, subset_size=None): self.sq_size = sq_size filenames = glob.glob(train_path+'/*/*.jpg') random.shuffle(filenames) with tf.device('/cpu:0'): filenames = tf.constant(filenames[:subset_size]) dataset = tf.contrib.data.Dataset.from_tensor_slices(filenames) dataset = dataset.filter(self._filter_function) dataset = dataset.map(self._parse_function) # Parse the record into tensors. dataset = dataset.batch(batch_size) self.iterator = dataset.make_initializable_iterator() def _filter_function(self, filename): image_string = tf.read_file(filename) img = tf.image.decode_jpeg(image_string) shp = tf.shape(img) return tf.logical_and(tf.equal(tf.rank(img), 3), tf.equal(shp[2], 3)) def _parse_function(self, filename): image_string = tf.read_file(filename) image = tf.image.decode_jpeg(image_string) image = preprocess_image(image, self.sq_size, is_training=True) return image def open_bcolz_arrays(root_dir, keys, arrs, mode='a', attr_dict={}): bcolz_arrs_dict = {} for key, arr in zip(keys, arrs): bcolz_path = os.path.join(root_dir, key) bcolz_arr = bcolz.carray(arr, rootdir=bcolz_path, mode=mode) for k,v in attr_dict.items(): bcolz_arr.attrs[k] = v bcolz_arrs_dict[key] = bcolz_arr return bcolz_arrs_dict class features_pipeline: def __init__(self, root_dir, keys, batch_size=16, attr_dict={}): bcolz_paths = [os.path.join(root_dir, key) for key in keys] with tf.device('/cpu:0'): bcolz_datasets = [self._bcolz_dataset(bcolz_path) for bcolz_path in bcolz_paths] dataset = tf.contrib.data.Dataset.zip(tuple(bcolz_datasets)) dataset = dataset.batch(batch_size) self.iterator = dataset.make_initializable_iterator() def _bcolz_dataset(self, bcolz_path, attr_dict={}): arr = bcolz.open(rootdir=bcolz_path, mode='r') for k,v in attr_dict.items(): assert arr.attrs[k]==v, "loss network mismatch" dataset = tf.contrib.data.Dataset.range(len(arr)) py_func = lambda y: self._parse_function(y, arr) dataset = dataset.map(lambda x: tf.py_func(py_func, [x], [tf.float32])) dataset = dataset.map(lambda x: tf.reshape(x, arr.shape[1:])) return dataset def _parse_function(self, i, arr): elem = arr[i] return elem def crop_and_resize(img, side=None): if(side==None): img = np.asarray(img) return img shortest = float(min(img.width,img.height)) resized = np.round(np.multiply(side/shortest, img.size)).astype(int) img = img.resize(resized, Image.BILINEAR) left = (img.width - side)/2 top = (img.height - side)/2 img = np.asarray(img) img = img[top:top+side, left:left+side, :] return img def save_image(out_path, img): img = np.clip(img, 0, 255).astype(np.uint8) scipy.misc.imsave(out_path, img) def load_images(path, image_size=None): valid_exts = ['.jpeg', '.jpg'] image_names = [] images = [] if(os.path.isdir(path)): for file_name in os.listdir(path): base, ext = os.path.splitext(file_name) if ext in valid_exts: image_names.append(base) image = Image.open(os.path.join(path, file_name)) image = crop_and_resize(image, image_size) images.append(image) assert len(images) > 0 elif(os.path.isfile(path)): folder_name, file_name = os.path.split(path) base, ext = os.path.splitext(file_name) assert ext in valid_exts image_names = [base] image = Image.open(os.path.join(path)) image = crop_and_resize(image, image_size) images = [image] else: raise ValueError('Uninterpretable path') return image_names, images def create_subfolder(super_folder, folder_name): new_folder_path = os.path.join(super_folder, folder_name) os.makedirs(new_folder_path) def load_image(src, image_size=None): image = Image.open(os.path.join(src)) image = crop_and_resize(image, image_size) return image def exists(p, msg): assert os.path.exists(p), msg def create_folder(dir_name, msg): assert not(os.path.exists(dir_name)), msg os.makedirs(dir_name) def tensor_shape(tensor): shp = tf.shape(tensor) return shp[0], shp[1], shp[2], shp[3] def download_model(model_url, model_dir, model_name): """Downloads the `model_url`, uncompresses it, saves the model file with the name model_name (default if unspecified) in the folder model_dir. Args: model_url: The URL of the model tarball file. model_dir: The directory where the model files are stored. model_name: The name of the model checkpoint file """ model_name = model_name + '.ckpt' model_path = os.path.join(model_dir, model_name) if os.path.exists(model_path): return tmp_dir = os.path.join(model_dir, 'tmp') if not os.path.exists(tmp_dir): os.makedirs(tmp_dir) filename = model_url.split('/')[-1] filepath = os.path.join(tmp_dir, filename) def _progress(count, block_size, total_size): sys.stdout.write('\r>> Downloading %s %.1f%%' % ( filename, float(count * block_size) / float(total_size) * 100.0)) sys.stdout.flush() filepath, _ = six_urllib.request.urlretrieve(model_url, filepath, _progress) print() statinfo = os.stat(filepath) print('Successfully downloaded', filename, statinfo.st_size, 'bytes.') tarfile.open(filepath, 'r:gz').extractall(tmp_dir) ckpt_files = glob.glob(os.path.join(tmp_dir, '*.ckpt')) + glob.glob(os.path.join(tmp_dir, '*/*.ckpt')) assert len(ckpt_files)==1 folder_name, file_name = os.path.split(ckpt_files[0]) move(ckpt_files[0], os.path.join(model_dir, model_name)) rmtree(tmp_dir)
[ "noreply@github.com" ]
gitter-badger.noreply@github.com
a039c87a5a88189abe2b4e273680d7baae5b9f8b
17268419060d62dabb6e9b9ca70742f0a5ba1494
/pp/samples/21_add_fiber_array.py
36357d855e4a117e710cb118a97380217da53c98
[ "MIT" ]
permissive
TrendingTechnology/gdsfactory
a19124423b12cbbb4f35b61f33303e9a012f82e5
c968558dba1bae7a0421bdf49dc192068147b776
refs/heads/master
2023-02-22T03:05:16.412440
2021-01-24T03:38:00
2021-01-24T03:38:00
null
0
0
null
null
null
null
UTF-8
Python
false
false
365
py
"""Connecting a component with I/O. """ import pp from pp.samples.big_device import big_device def test_big_device(): component = big_device(N=10) bend_radius = 5.0 c = pp.routing.add_fiber_array( component, bend_radius=bend_radius, fanout_length=50.0 ) return c if __name__ == "__main__": c = test_big_device() pp.show(c)
[ "noreply@github.com" ]
TrendingTechnology.noreply@github.com
8f6eb903f27861c546fd13331fa65729abc6dc37
1c5fdabf183c5eb3a9d6577049e674c3757c00db
/Блэк_Джек_4/Lucky_Jack_4_3.py
88c2918e249e7140b7b03160d396b46a1c59a2c4
[]
no_license
Bhaney44/Blackjack
b997b46bb92fc71f1471cf6d82048df72a32d342
ca64e41af0669f2e364d80a206682481c2951771
refs/heads/master
2022-12-11T06:58:16.716447
2020-09-15T01:03:47
2020-09-15T01:03:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,628
py
#LuckyJack #Copyright Brian S. Haney 2020 #Import Random #Import Prototype GUI and Data Storage Library from tkinter import * from tkinter.messagebox import * import csv #Factor Labels master = Tk() #Dealer #Labels label0 = Label(master, text = 'Dealer', relief = 'groove', width = 20) label1 = Label(master, text = 'Open Card', relief = 'groove', width = 20) label3 = Label(master, text = 'Secret Card', relief = 'groove', width = 20) label4 = Label(master, text = 'Hit', relief = 'groove', width = 20) label5 = Label(master, text = 'Hit', relief = 'groove', width = 20) label6 = Label(master, text = 'Hit', relief = 'groove', width = 20) label7 = Label(master, text = 'Dealer Total', relief = 'groove', width = 20) #Blanks blank1 = Entry(master, relief = 'groove', width = 20) blank2 = Entry(master, relief = 'groove', width = 20) blank3 = Entry(master, relief = 'groove', width = 20) blank4 = Entry(master, relief = 'groove', width = 20) blank5 = Entry(master, relief = 'groove', width = 20) blank6 = Entry(master, relief = 'groove', width = 20) blank7 = Entry(master, relief = 'groove', width = 20) #Player #Labels label8 = Label(master, text = 'Player', relief = 'groove', width = 20) label9 = Label(master, text = 'Card 0', relief = 'groove', width = 20) label10 = Label(master, text = 'Card 1', relief = 'groove', width = 20) label11 = Label(master, text = 'Hit', relief = 'groove', width = 20) label12 = Label(master, text = 'Player Total', relief = 'groove', width = 20) #Blanks blank8 = Entry(master, relief = 'groove', width = 20) blank9 = Entry(master, relief = 'groove', width = 20) blank10 = Entry(master, relief = 'groove', width = 20) blank11 = Entry(master, relief = 'groove', width = 20) #Scoreboard #Labels label13 = Label(master, text = 'Chips', relief = 'groove', width = 20) label14 = Label(master, text = 'Cost', relief = 'groove', width = 20) label15 = Label(master, text = 'Return', relief = 'groove', width = 20) label16 = Label(master, text = 'Lucky Jack', relief = 'groove', width = 20) label17 = Label(master, text = 'Scoreboard', relief = 'groove', width = 20) label18 = Label(master, text = 'Dealer Score', relief = 'groove', width = 20) label19 = Label(master, text = 'Player Score', relief = 'groove', width = 20) #Blanks blank12 = Entry(master, relief = 'groove', width = 20) blank13 = Entry(master, relief = 'groove', width = 20) blank14 = Entry(master, relief = 'groove', width = 20) blank15 = Entry(master, relief = 'groove', width = 20) blank16 = Entry(master, relief = 'groove', width = 20) #Functions def deal(): print(deal) def hit(): print(hit) #Buttons button0 = Button(master, text = 'Hit', relief = 'groove', width = 20, command = hit) button1 = Button(master, text = 'Deal', relief = 'groove', width = 20, command = deal) #Geometry #Dealer label0.grid( row = 11, column = 1, padx = 10 ) label1.grid( row = 12, column = 1, padx = 10 ) label3.grid( row = 13, column = 1, padx = 10 ) label4.grid( row = 14, column = 1, padx = 10 ) label5.grid( row = 15, column = 1, padx = 10 ) label6.grid( row = 16, column = 1, padx = 10 ) label7.grid( row = 17, column = 1, padx = 10 ) blank1.grid( row = 12, column = 2, padx = 10 ) blank2.grid( row = 13, column = 2, padx = 10 ) blank3.grid( row = 14, column = 2, padx = 10 ) blank4.grid( row = 15, column = 2, padx = 10 ) blank5.grid( row = 16, column = 2, padx = 10 ) blank6.grid( row = 16, column = 2, padx = 10 ) blank7.grid( row = 17, column = 2, padx = 10 ) #Player label8.grid( row = 18, column = 1, padx = 10 ) label9.grid( row = 19, column = 1, padx = 10 ) label10.grid( row = 20, column = 1, padx = 10 ) label11.grid( row = 21, column = 1, padx = 10 ) label12.grid( row = 22, column = 1, padx = 10 ) blank8.grid( row = 18, column = 2, padx = 10 ) blank9.grid( row = 19, column = 2, padx = 10 ) blank10.grid( row = 20, column = 2, padx = 10 ) blank11.grid( row = 21, column = 2, padx = 10 ) #Scoreboard label13.grid( row = 4, column = 2, padx = 10 ) label14.grid( row = 6, column = 2, padx = 10 ) label15.grid( row = 8, column = 2, padx = 10 ) label16.grid( row = 1, column = 1, padx = 40 ) label17.grid( row = 2, column = 1, padx = 30 ) label18.grid( row = 3, column = 1, padx = 10 ) label19.grid( row = 3, column = 3, padx = 10 ) blank12.grid( row = 7, column = 2, padx = 10 ) blank13.grid( row = 8, column = 2, padx = 10 ) blank14.grid( row = 4, column = 1, padx = 10 ) blank15.grid( row = 4, column = 3, padx = 10 ) blank16.grid( row = 5, column = 2, padx = 10 ) button0.grid( row = 9, column = 1, columnspan = 1) button1.grid( row = 10, column = 1, columnspan = 1) #Static Properties master.title('LuckyJack')
[ "noreply@github.com" ]
Bhaney44.noreply@github.com
ccd137343ed60e23598ec8c8ad814ccd1564fa22
15d5c79bc5094ab25a9d3f286bb99d30b2598cfa
/network/smurfcoin.py
65c6b19e7bba2ca327a36fa4bfa8bfa33e4274ad
[]
no_license
jabef/clove_bounty
1d4f660969e905fc5fc50e10273d2f2d55df0723
b58bc10b46ba983b890d8e599fb548c7aea2695b
refs/heads/master
2021-04-27T21:41:29.952341
2018-02-19T17:14:15
2018-02-19T17:14:15
122,404,779
0
0
null
2018-02-21T23:01:22
2018-02-21T23:01:21
null
UTF-8
Python
false
false
373
py
from clove.network.bitcoin import Bitcoin class SmurfCoin(Bitcoin): """ Class with all the necessary SmurfCoin network information based on https://github.com/smurfscoin/smf/blob/master/src/net.cpp (date of access: 02/18/2018) """ name = 'smurfcoin' symbols = ('SMF', ) seeds = ("45.55.83.96") port = 43221 # no testnet
[ "noreply@github.com" ]
jabef.noreply@github.com
d4760ff4c833f78ede6feab4c7e69ea26fb96a7c
586a67650102938663f79290f02467ad8a683b43
/invoice/views/invoices.py
5042e0fa85e79d4a9192a039b308238a037e447c
[]
no_license
Shokr/yalla_invoice
64956d886a5056455e519f7c1cfaf364138609d3
5a668963f4cb2a42e4111d855543a680ceec90c4
refs/heads/master
2022-10-04T09:50:32.517524
2021-05-03T20:06:42
2021-05-03T20:06:42
241,491,107
1
0
null
2022-09-23T22:36:00
2020-02-18T23:38:39
Python
UTF-8
Python
false
false
4,101
py
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.contrib.auth.decorators import login_required from django.contrib.auth.decorators import login_required, user_passes_test import datetime # Local Applications imports from ..forms import * @login_required def index(request): invoices = Invoice.objects.all().order_by('-date_created') context = { 'title': 'Recent Invoices', 'invoice_list': invoices, } return render(request, 'invoice/index.html', context) # Show big list of all invoices @login_required def all_invoices(request): invoices = Invoice.objects.order_by('-date_created') context = { 'title': 'All Invoices', 'invoice_list': invoices, } return render(request, 'invoice/all_invoice.html', context) # Show invalid invoices @login_required def invalid_invoices(request): invoices = Invoice.objects.filter(valid='False').order_by('-date_created') context = { 'title': 'Invalid Invoices', 'invoice_list': invoices, } return render(request, 'invoice/invalid_invoices.html', context) # Display a specific invoice @login_required def invoice(request, invoice_id): invoice = get_object_or_404(Invoice, pk=invoice_id) itemformset = ItemFormset() context = { 'title': 'Invoice ' + str(invoice_id), 'invoice': invoice, 'formset': itemformset, } return render(request, 'invoice/invoice.html', context) # Search for invoice @login_required def search_invoice(request): id = request.POST['id'] return HttpResponseRedirect(reverse('invoice:view_invoice', args=(id,))) # Create new invoice @login_required def new_invoice(request): # If no customer_id is defined, create a new invoice if request.method == 'POST': customer_id = request.POST.get("customer_id", "None") user = request.user.username if customer_id == 'None': customers = Customer.objects.order_by('name') context = { 'title': 'New Invoice', 'customer_list': customers, 'error_message': 'Please select a customer.', } return render(request, 'invoice/new_invoice.html', context) else: customer = get_object_or_404(Customer, pk=customer_id) i = Invoice(customer=customer, user=user) i.save() return HttpResponseRedirect(reverse('invoice:invoice', args=(i.id,))) else: # Customer list needed to populate select field customers = Customer.objects.order_by('name') context = { 'title': 'New Invoice', 'customer_list': customers, } return render(request, 'invoice/new_invoice.html', context) # View invoice @login_required def view_invoice(request, invoice_id): invoice = get_object_or_404(Invoice, pk=invoice_id) context = { 'title': "Invoice " + str(invoice_id), 'invoice': invoice, } return render(request, 'invoice/view_invoice.html', context) # # edit invoice # @login_required # def edit_invoice(request, invoice_id): # invoice = get_object_or_404(Invoice, pk=invoice_id) # context = { # 'title': "Invoice " + str(invoice_id), # 'invoice': invoice, # } # return render(request, 'invoice/invoice.html', context) # Print invoice @login_required def print_invoice(request, invoice_id): invoice = get_object_or_404(Invoice, pk=invoice_id) context = { 'title': "Invoice " + str(invoice_id), 'invoice': invoice, } return render(request, 'invoice/print_invoice.html', context) # Invalidate an invoice @login_required # @user_passes_test(lambda u: u.groups.filter(name='xmen').count() == 0, login_url='invoice/all_invoice.html') def invalidate_invoice(request, invoice_id): invoice = get_object_or_404(Invoice, pk=invoice_id) invoice.valid = False invoice.save() return HttpResponseRedirect(reverse('invoice:index'))
[ "mohammedshokr2014@gmail.com" ]
mohammedshokr2014@gmail.com
75a6d5e4fa9d09bca96df632809baf921651227a
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/verbs/_arousing.py
40991d3cd0e5d6d4556cec52531935097102e368
[ "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
240
py
from xai.brain.wordbase.verbs._arouse import _AROUSE #calss header class _AROUSING(_AROUSE, ): def __init__(self,): _AROUSE.__init__(self) self.name = "AROUSING" self.specie = 'verbs' self.basic = "arouse" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
41c70e9309c3776bec2dea935e8102a58ae2d215
cfb4e8721137a096a23d151f2ff27240b218c34c
/mypower/matpower_ported/lib/mpoption_info_fmincon.py
072799309556c4b95076795f10756ceb343dc4ee
[ "Apache-2.0" ]
permissive
suryo12/mypower
eaebe1d13f94c0b947a3c022a98bab936a23f5d3
ee79dfffc057118d25f30ef85a45370dfdbab7d5
refs/heads/master
2022-11-25T16:30:02.643830
2020-08-02T13:16:20
2020-08-02T13:16:20
null
0
0
null
null
null
null
UTF-8
Python
false
false
176
py
def mpoption_info_fmincon(*args,nout=1,oc=None): if oc == None: from ...oc_matpower import oc_matpower oc = oc_matpower() return oc.mpoption_info_fmincon(*args,nout=nout)
[ "muhammadyasirroni@gmail.com" ]
muhammadyasirroni@gmail.com
1b72274245ff18b5551db7c3c249ebc482c5838a
1bdbcc3954ed75574eea1af5bf49f03cce4af198
/class_work_problems/num_to_letter.py
815b33cda3e3d34cf20083c0ba916bd11eead0bc
[]
no_license
skreynolds/uta_cse_1309x
d73bbadb012147e6196e2320d4d635bee81d28f4
40c1221fdcc192fe66c7e60c636b08a8cfbebb2d
refs/heads/master
2020-12-22T20:19:31.977554
2020-01-29T06:50:24
2020-01-29T06:50:24
236,921,284
0
0
null
null
null
null
UTF-8
Python
false
false
1,664
py
# Type your code here n=int(input('please enter an integer between 1 and 9999: ')) units = ['','one','two','three','four','five','six','seven','eight','nine'] teens = ['','eleven','twelve','thirteen','fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'] tens = ['','ten','twenty','thirty','forty','fifty','sixty','seventy', 'eighty','ninety'] num_list = [] nums = 0 for i in range(len(str(n))): num_list.append(n%10) n = n//10 nums += 1 num_list.reverse() #print(num_list) i = 5 - nums for iteration in range(nums): e = num_list[iteration] if i == 1: if num_list[iteration + 1] == 0 and num_list[iteration + 2] == 0 and num_list[iteration + 3] == 0: print(units[e], end = " ") print("thousand", end = "") else: print(units[e], end = " ") print("thousand", end = " ") elif i == 2: if e != 0: if num_list[iteration + 1] == 0 and num_list[iteration + 2] == 0: print(units[e], end = " ") print("hundred", end = "") else: print(units[e], end = " ") print("hundred", end = " ") elif i == 3: if e > 1: if num_list[iteration + 1] == 0: print(tens[e], end = "") else: print(tens[e], end = " ") elif e == 1: if num_list[iteration + 1] != 0: print(teens[num_list[iteration + 1]]) break elif num_list[iteration + 1] == 0: print(tens[1]) break else: print(units[e]) # Incement counter i += 1
[ "shane.k.reynolds@gmail.com" ]
shane.k.reynolds@gmail.com
62e40235228c53143cd46bc282718e6f767e019d
c3dc08fe8319c9d71f10473d80b055ac8132530e
/challenge-107/roger-bell-west/python/ch-1.py
e638dd33c91314e47cd0245efcf95f3d3d7ef792
[]
no_license
southpawgeek/perlweeklychallenge-club
d4b70d9d8e4314c4dfc4cf7a60ddf457bcaa7a1e
63fb76188e132564e50feefd2d9d5b8491568948
refs/heads/master
2023-01-08T19:43:56.982828
2022-12-26T07:13:05
2022-12-26T07:13:05
241,471,631
1
0
null
2020-02-18T21:30:34
2020-02-18T21:30:33
null
UTF-8
Python
false
false
703
py
#! /usr/bin/python3 def sdn(count): r=list() n=10 while len(r) < count: ns=[int(i) for i in "{:d}".format(n)] d=[0]*10 for i in ns: d[i]+=1 sd=True for i in range(len(ns)): if d[i] != ns[i]: sd=False break if sd and len(ns)<10: for i in range(len(ns),10): if d[i] != 0: sd=False break if sd: r.append(n) n+=10 return r import unittest class TestSdn(unittest.TestCase): def test_ex1(self): self.assertEqual(sdn(3),[1210, 2020, 21200],'example 1') unittest.main()
[ "roger@firedrake.org" ]
roger@firedrake.org
af04626fbf64b19bf1abe99c30b6144727cd2489
51ce07a419abe50f49e7bb6a6c036af291ea2ef5
/3.Algorithm/08. 비트&진수/이진수.py
672c8c01e566a544904cc9057c3b3d923e469569
[]
no_license
salee1023/TIL
c902869e1359246b6dd926166f5ac9209af7b1aa
2905bd331e451673cbbe87a19e658510b4fd47da
refs/heads/master
2023-03-10T09:48:41.377704
2021-02-24T10:47:27
2021-02-24T10:47:27
341,129,838
0
0
null
null
null
null
UTF-8
Python
false
false
332
py
T = int(input()) for tc in range(1, 1+T): N, numbers = input().split() N = int(N) print(f'#{tc} ', end='') for n in range(N): t = format(int(numbers[n], 16), '03b') # if len(t) < 4: # print('0'*(4-len(t)), end='') print(t, end='') print() ''' 3 4 47FE 5 79E12 8 41DA16CD '''
[ "dltmddk1023@gmail.com" ]
dltmddk1023@gmail.com
76e82c15daa30b0a37073c20c9abe4c4c7c2b4dd
9023909d2776e708755f98d5485c4cffb3a56000
/oneflow/compatible_single_client_python/eager/interpreter_callback.py
4295829ee25c69fc8856e2d0462ad1e2a31c31cd
[ "Apache-2.0" ]
permissive
sailfish009/oneflow
f6cf95afe67e284d9f79f1a941e7251dfc58b0f7
4780aae50ab389472bd0b76c4333e7e0a1a56ef7
refs/heads/master
2023-06-24T02:06:40.957297
2021-07-26T09:35:29
2021-07-26T09:35:29
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,285
py
""" Copyright 2020 The OneFlow 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. """ from __future__ import absolute_import from oneflow.compatible.single_client.python.eager import gradient_util as gradient_util from oneflow.compatible.single_client.python.eager import op_executor as op_executor from oneflow.compatible.single_client.core.operator import ( op_attribute_pb2 as op_attribute_pb, ) from oneflow.compatible.single_client.core.job import scope_pb2 as scope_pb from oneflow.compatible.single_client.core.job import placement_pb2 as placement_pb from google.protobuf import text_format from oneflow.compatible.single_client.python.framework import scope_util as scope_util from oneflow.compatible.single_client.python.eager import ( symbol_storage as symbol_storage, ) import oneflow._oneflow_internal def MakeScopeSymbol(job_conf, parallel_conf, is_mirrored): parallel_hierarchy = None if parallel_conf.has_hierarchy(): parallel_hierarchy = oneflow._oneflow_internal.Size( tuple(parallel_conf.hierarchy().dim()) ) return scope_util.MakeInitialScope( job_conf, parallel_conf.device_tag(), list(parallel_conf.device_name()), parallel_hierarchy, is_mirrored, ).symbol_id def MakeParallelDescSymbol(parallel_conf): symbol_id = None def BuildInstruction(builder): nonlocal symbol_id symbol_id = builder.GetParallelDescSymbol(parallel_conf).symbol_id oneflow._oneflow_internal.deprecated.LogicalRun(BuildInstruction) return symbol_id def MirroredCast(op_attribute_str, parallel_conf): op_attribute = text_format.Parse(op_attribute_str, op_attribute_pb.OpAttribute()) blob_register = oneflow._oneflow_internal.GetDefaultBlobRegister() is_cast_to_mirrored = op_attribute.op_conf.HasField("cast_to_mirrored_conf") is_cast_from_mirrored = op_attribute.op_conf.HasField("cast_from_mirrored_conf") assert is_cast_to_mirrored or is_cast_from_mirrored _MirroredCastAndAddOutputBlobReleaser(op_attribute, blob_register) bw_blob_register = gradient_util.GetDefaultBackwardBlobRegister() gradient_util.TrySetBackwardUsedBlobObject( op_attribute, blob_register, bw_blob_register ) def InterpretCompletedOp(op_attribute_str, parallel_conf): op_attribute = text_format.Parse(op_attribute_str, op_attribute_pb.OpAttribute()) blob_register = gradient_util.GetDefaultBackwardBlobRegister() _InterpretCompletedOp(op_attribute, parallel_conf, blob_register) gradient_util.ReleaseUnusedBlobObject(op_attribute, blob_register) def _InterpretCompletedOp(op_attribute, parallel_conf, blob_register): return op_executor.Interpret(op_attribute, parallel_conf, blob_register) def _MirroredCastAndAddOutputBlobReleaser(op_attribute, blob_register): op_executor.MirroredCast(op_attribute, blob_register) _AddOutputBlobObjectReleaser4InputBlobObject(op_attribute, blob_register) def _AddOutputBlobObjectReleaser4InputBlobObject(op_attribute, blob_register): in_lbi = op_attribute.arg_signature.bn_in_op2lbi["in"] in_lbn = "%s/%s" % (in_lbi.op_name, in_lbi.blob_name) in_blob_object = blob_register.GetObject4BlobName(in_lbn) release = _MakeReleaser4MirroredCastBlobObject(op_attribute, blob_register) in_blob_object.add_releaser(release) def _MakeReleaser4MirroredCastBlobObject(op_attribute, blob_register): def ReleaseMirroredBlobObject(obj): for obn in op_attribute.output_bns: lbi = op_attribute.arg_signature.bn_in_op2lbi[obn] lbn = "%s/%s" % (lbi.op_name, lbi.blob_name) blob_object = blob_register.GetObject4BlobName(lbn) blob_register.ClearObject4BlobName(lbn) return ReleaseMirroredBlobObject
[ "noreply@github.com" ]
sailfish009.noreply@github.com
5fa8083c771b118d03d567b6878554f82c71120c
bd187ecc8a94460cd17d3c13aa469c25a3f3be3a
/mainsite/migrations/0006_auto_20191127_0915.py
75e8efb19fdb91c2f6c2a2354e86433dc4c9a946
[]
no_license
ozkilim/DinosaurDating
3226acb3f4987534ce5ceed7649d76d47b51065e
44bb4583f50e7a5c903040ab80a63ba390330d35
refs/heads/master
2021-11-06T16:18:25.192520
2019-12-10T14:47:22
2019-12-10T14:47:22
224,671,044
0
0
null
2021-09-08T01:28:17
2019-11-28T14:30:07
Python
UTF-8
Python
false
false
389
py
# Generated by Django 2.2.7 on 2019-11-27 09:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainsite', '0005_atendee_event'), ] operations = [ migrations.AlterField( model_name='atendee', name='looking_for', field=models.CharField(max_length=100), ), ]
[ "ozkilim@hotmail.co.uk" ]
ozkilim@hotmail.co.uk
7d201b6089d5c2d7d4f81efd39e2d8b13d4eb4b8
bb33e6be8316f35decbb2b81badf2b6dcf7df515
/source/res/scripts/client/circularflyer.py
9a0d228924714e4ed8bf49c022803e589020bcde
[]
no_license
StranikS-Scan/WorldOfTanks-Decompiled
999c9567de38c32c760ab72c21c00ea7bc20990c
d2fe9c195825ececc728e87a02983908b7ea9199
refs/heads/1.18
2023-08-25T17:39:27.718097
2022-09-22T06:49:44
2022-09-22T06:49:44
148,696,315
103
39
null
2022-09-14T17:50:03
2018-09-13T20:49:11
Python
UTF-8
Python
false
false
4,298
py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/CircularFlyer.py import math import BigWorld import AnimationSequence from Math import Matrix, Vector3 from debug_utils import LOG_CURRENT_EXCEPTION from vehicle_systems.stricted_loading import makeCallbackWeak import SoundGroups class CircularFlyer(BigWorld.UserDataObject): def __init__(self): BigWorld.UserDataObject.__init__(self) self.__prevTime = BigWorld.time() self.__angularVelocity = 2 * math.pi / self.rotationPeriod if not self.rotateClockwise: self.__angularVelocity *= -1 self.__currentAngle = 0.0 self.__updateCallbackId = None self.__model = None self.__modelMatrix = None self.__sound = None self.__animator = None BigWorld.loadResourceListBG((self.modelName, self.pixieName), makeCallbackWeak(self.__onResourcesLoaded)) return def __del__(self): self.__clear() def __clear(self): if self.__updateCallbackId is not None: BigWorld.cancelCallback(self.__updateCallbackId) self.__updateCallbackId = None if self.__sound is not None: self.__sound.stop() self.__sound.releaseMatrix() self.__sound = None if self.__model is not None: self.__animator = None BigWorld.delModel(self.__model) self.__model = None return def __onResourcesLoaded(self, resourceRefs): if self.guid not in BigWorld.userDataObjects: return else: self.__clear() if self.modelName in resourceRefs.failedIDs: return try: self.__model = resourceRefs[self.modelName] self.__modelMatrix = Matrix() self.__modelMatrix.setIdentity() servo = BigWorld.Servo(self.__modelMatrix) self.__model.addMotor(servo) BigWorld.addModel(self.__model) if self.actionName != '': clipResource = self.__model.deprecatedGetAnimationClipResource(self.actionName) if clipResource: spaceID = BigWorld.player().spaceID loader = AnimationSequence.Loader(clipResource, spaceID) animator = loader.loadSync() animator.bindTo(AnimationSequence.ModelWrapperContainer(self.__model, spaceID)) animator.start() self.__animator = animator if self.pixieName != '' and self.pixieName not in resourceRefs.failedIDs: pixieNode = self.__model.node(self.pixieHardPoint) pixieNode.attach(resourceRefs[self.pixieName]) if self.soundName != '': self.__sound = SoundGroups.g_instance.getSound3D(self.__modelMatrix, self.soundName) except Exception: LOG_CURRENT_EXCEPTION() self.__model = None return self.__prevTime = BigWorld.time() self.__update() return def __update(self): self.__updateCallbackId = None self.__updateCallbackId = BigWorld.callback(0.0, self.__update) curTime = BigWorld.time() dt = curTime - self.__prevTime self.__prevTime = curTime self.__currentAngle += self.__angularVelocity * dt if self.__currentAngle > 2 * math.pi: self.__currentAngle -= 2 * math.pi elif self.__currentAngle < -2 * math.pi: self.__currentAngle += 2 * math.pi radialPosition = Vector3(self.radius * math.sin(self.__currentAngle), 0, self.radius * math.cos(self.__currentAngle)) modelYaw = self.__currentAngle if self.rotateClockwise: modelYaw += math.pi / 2 else: modelYaw -= math.pi / 2 localMatrix = Matrix() localMatrix.setRotateY(modelYaw) localMatrix.translation = radialPosition self.__modelMatrix.setRotateYPR((self.yaw, self.pitch, self.roll)) self.__modelMatrix.translation = self.position self.__modelMatrix.preMultiply(localMatrix) return
[ "StranikS_Scan@mail.ru" ]
StranikS_Scan@mail.ru
48a73da0886034bf90716950527d561d32bbab82
dce8531d0e9665a09205f70a909ac1424f7e09eb
/preprocess.py
d6a53884fddf97d075c2264cc801f41dff0d4b95
[ "MIT" ]
permissive
keonlee9420/Comprehensive-Tacotron2
40a6e5fcecf55ee02a8523a7e2701b6124748bee
1eff7f08c41a2127bbe300b6d66ce5c966422b25
refs/heads/main
2023-08-07T16:10:15.133301
2022-02-20T14:30:07
2022-02-20T14:44:36
388,990,172
39
17
MIT
2023-07-31T13:08:05
2021-07-24T03:36:08
Python
UTF-8
Python
false
false
640
py
import argparse from utils.tools import get_configs_of from preprocessor import ljspeech, vctk def main(config): if "LJSpeech" in config["dataset"]: preprocessor = ljspeech.Preprocessor(config) if "VCTK" in config["dataset"]: preprocessor = vctk.Preprocessor(config) preprocessor.build_from_path() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--dataset", type=str, required=True, help="name of dataset", ) args = parser.parse_args() preprocess_config, *_ = get_configs_of(args.dataset) main(preprocess_config)
[ "keonlee9420@gmail.com" ]
keonlee9420@gmail.com
13ba32c6e2a103795a5cafba7f437334176ac67e
d5fbb40c8fa95970a6b1dd10920071a3330c6de8
/src_d21c/in_theta.py
428938d97f7d9d9e57abdd3f26b45e3ee98844aa
[]
no_license
Pooleyo/theta.py
622000e04a7834a7b12d371337992f6063c3f332
7bdf96f7494db7fda8dbe8d1e8bb536a5b39e39d
refs/heads/master
2021-06-18T06:03:47.176742
2019-09-18T16:02:02
2019-09-18T16:02:02
137,497,437
0
0
null
null
null
null
UTF-8
Python
false
false
1,561
py
test_mode = True image_files = ['3x3_pixel_value_1.tif'] # "PSL_plate4_s10257_BBXRD.tif"#"3x3_white_test_image.tif"##"Nb_test_image.png" # #"PSL_plate4_s10257_BBXRD.tif"#"Nb_test_image.png"# source_position = [[50.0, 0.0, 49.8]] # In mm normal = [[-25.6, 0.0, 12.7078]] # [-10.0, 0.0, 10.0] # The normal to the plane of the image plate with units mm. sample_normal = [[0.0, 0.0, 1.0]] # This is used to correct for attenuation in the diffracting sample. offset = [[0.0, 12.0, 0.0]] # X offset (mm), Y offset (mm), rotation (degrees); note that rotation is not actually used # in this code, it is included simply to indicate which sonOfHoward parameters are being reference here. x_scale = [56] # In mm y_scale = [44] # In mm view_x = [[0.01, 1.0, 0.02]] # [-0.71, 0.0, -0.71] # "normalised" view_y = [[0.44, -0.02, 0.90]] # [0.0, 1.0, 0.0] # "normalised" wavelength = 1.378 # In Angstroms a_lattice = 3.3 # In Angstroms filter_thickness = [[10.0, 6.0]] filter_attenuation_length = [[34.1, 109.7]] # The attenuation length(s) of filter(s) used, in microns. Enter a new list # element for each filter; the order doesn't matter. Zn, at 9 keV, has attenuation length of 34.1 microns. Al, at 9 keV, # has attenuation length of 109.7 microns. phi_0_definer = [0.0, 0.0, 1.0] phi_limit = [-180.0, 180.0] gsqr_limit = [0.0, 18.0] theta_phi_n_pixels_width = 1 theta_phi_n_pixels_height = 1 num_width_subpixels = 1 num_height_subpixels = 1 plot = True debug = False name_plot_integrated_intensity = 'integrated_intensity_vs_gsqr.png'
[ "ajp560@york.ac.uk" ]
ajp560@york.ac.uk
377b54e77c82a1e6af952880cf1817eb944f7fe3
ea7f0b643d6e43f432eb49ef7f0c62899ebdd026
/conans/test/util/output_test.py
65a29d32d1f4ccfd5bd5c286a3c2e77fba71b7c3
[ "MIT" ]
permissive
jbaruch/conan
0b43a4dd789547bd51e2387beed9095f4df195e4
263722b5284828c49774ffe18d314b24ee11e178
refs/heads/develop
2021-01-19T21:15:37.429340
2017-04-18T14:27:33
2017-04-18T14:27:33
88,635,196
0
1
null
2017-04-18T14:34:03
2017-04-18T14:34:02
null
UTF-8
Python
false
false
2,625
py
# -*- coding: utf-8 -*- import unittest from conans.client.output import ConanOutput from six import StringIO from conans.client.rest.uploader_downloader import print_progress from conans.test.utils.test_files import temp_folder from conans import tools import zipfile import os from conans.util.files import save, load import sys from conans.test.utils.tools import TestClient class OutputTest(unittest.TestCase): def simple_output_test(self): stream = StringIO() output = ConanOutput(stream) output.rewrite_line("This is a very long line that has to be truncated somewhere, " "because it is so long it doesn't fit in the output terminal") self.assertIn("This is a very long line that ha ... esn't fit in the output terminal", stream.getvalue()) def error_test(self): client = TestClient() conanfile = """ # -*- coding: utf-8 -*- from conans import ConanFile from conans.errors import ConanException class PkgConan(ConanFile): def source(self): self.output.info("TEXT ÑÜíóúéáàèòù абвгдежзийкл 做戏之说 ENDTEXT") """ client.save({"conanfile.py": conanfile}) client.run("source") self.assertIn("TEXT", client.user_io.out) self.assertIn("ENDTEXT", client.user_io.out) def print_progress_test(self): stream = StringIO() output = ConanOutput(stream) for units in range(50): print_progress(output, units) output_str = stream.getvalue() self.assertNotIn("=", output_str) self.assertNotIn("[", output_str) self.assertNotIn("]", output_str) def unzip_output_test(self): tmp_dir = temp_folder() file_path = os.path.join(tmp_dir, "example.txt") save(file_path, "Hello world!") zip_path = os.path.join(tmp_dir, 'example.zip') zipf = zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) for root, _, files in os.walk(tmp_dir): for f in files: zipf.write(os.path.join(root, f), f) zipf.close() output_dir = os.path.join(tmp_dir, "output_dir") new_out = StringIO() old_out = sys.stdout try: sys.stdout = new_out tools.unzip(zip_path, output_dir) finally: sys.stdout = old_out output = new_out.getvalue() self.assertRegexpMatches(output, "Unzipping [\d]+ bytes, this can take a while") content = load(os.path.join(output_dir, "example.txt")) self.assertEqual(content, "Hello world!")
[ "lasote@gmail.com" ]
lasote@gmail.com
6938f0bc75372893e1b90af44297d7efdbdabe3c
2d2ef049d450ef9ac6459bcdd1ea25fccc0305d5
/loadTimeEstimator.py
b1f03e7172b7ba44449aeb4afa1aa99899599ebb
[]
no_license
iotmember/code-fights
fc119f53cc42f9fea8a40f43335d93d076c92e9d
e7f1fdb9d5068bd2ed67d9df07541f306097bd19
refs/heads/master
2021-05-31T06:03:41.497371
2016-04-08T05:40:39
2016-04-08T05:40:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,074
py
import sys def loadTimeEstimator(sizes, uploadingStart, V): finish_time = [x for x in uploadingStart] t = [0 for x in uploadingStart] c = len(sizes) time_ = 0 curr_time = uploadingStart[0] while (c > 0): index_of_uploading_start = [i for i, x in enumerate(uploadingStart) if x == curr_time + time_ and sizes[i] != 0 ] if len(index_of_uploading_start): speed = V/float(len(index_of_uploading_start)) else: speed = V #print index_of_uploading_start for i in index_of_uploading_start: if sizes[i] > 0: sizes[i] = sizes[i] - speed finish_time[i] = finish_time[i] + 1 t[i] = t[i] + 1 uploadingStart[i] = uploadingStart[i] + 1 time_ += 1 c = len([x for x in sizes if x > 0]) return finish_time sizes = [21, 10] uploadingStart = [100, 105] V = 2 #print loadTimeEstimator(sizes, uploadingStart, V) print loadTimeEstimator([20, 10], [1, 1], 1) #print loadTimeEstimator([1, 1, 1], [10, 20, 30], 3)
[ "nasa.freaks@gmail.com" ]
nasa.freaks@gmail.com
6251d68f138a9b14476759cfdce97fd773872ec8
12123592a54c4f292ed6a8df4bcc0df33e082206
/py3/pgms/sec8/Extend/ctypes/convs.py
616830fa1e5821bc2a04d9cde8ded2752fa0ab67
[]
no_license
alvinooo/advpython
b44b7322915f832c8dce72fe63ae6ac7c99ef3d4
df95e06fd7ba11b0d2329f4b113863a9c866fbae
refs/heads/master
2021-01-23T01:17:22.487514
2017-05-30T17:51:47
2017-05-30T17:51:47
92,860,630
0
0
null
null
null
null
UTF-8
Python
false
false
354
py
#!/usr/bin/env python3 # convs.py - ctype conversions from ctypes import * # load shared library mylib = CDLL("./mylib.so") # double mult(double, double) mylib.mult.argtypes = (c_double, c_double) mylib.mult.restype = c_double # call C mult() function print(mylib.mult(2.5, 3.5)) ##################################### # # $ convs.py # 8.75 #
[ "alvin.heng@teradata.com" ]
alvin.heng@teradata.com
c625c91f36b9023bdda7ad7f8346b9bde769ae1b
63b0fed007d152fe5e96640b844081c07ca20a11
/ABC/ABC300~ABC399/ABC300/e.py
9ba33d532fb2e724f862b0ad868328126a7e1249
[]
no_license
Nikkuniku/AtcoderProgramming
8ff54541c8e65d0c93ce42f3a98aec061adf2f05
fbaf7b40084c52e35c803b6b03346f2a06fb5367
refs/heads/master
2023-08-21T10:20:43.520468
2023-08-12T09:53:07
2023-08-12T09:53:07
254,373,698
0
0
null
null
null
null
UTF-8
Python
false
false
718
py
from functools import lru_cache def modinv(a: int, m: int) -> int: ''' モジュラ逆元 ax mod m =1の解x=a^(-1)を返す Parameters ---------- a:int m:int ''' x, y, u, v = 1, 0, 0, 1 M = m while m > 0: k = a//m x -= k*u y -= k*v x, u = u, x y, v = v, y a, m = m, a % m assert a == 1, "a and m aren't relatively prime numbers" if x < 0: x += M return x N = int(input()) MOD = 998244353 P = modinv(5, MOD) @lru_cache(maxsize=None) def f(n): if n >= N: return 1 if n == N else 0 res = 0 for i in range(2, 7): res += f(i*n) return res*P % MOD ans = f(1) print(ans)
[ "ymdysk911@gmail.com" ]
ymdysk911@gmail.com
1eb48a906c41d240228e260d96f74a91e308d423
2afb1095de2b03b05c8b96f98f38ddeca889fbff
/web_scrapping/try_steam_parse.py
f76504a9eb079147e18d2455c67b424ba847329a
[]
no_license
draganmoo/trypython
187316f8823296b12e1df60ef92c54b7a04aa3e7
90cb0fc8626e333c6ea430e32aa21af7d189d975
refs/heads/master
2023-09-03T16:24:33.548172
2021-11-04T21:21:12
2021-11-04T21:21:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,267
py
import glob import pandas as pd from bs4 import BeautifulSoup df = pd.DataFrame() df1 = pd.DataFrame() df2 = pd.DataFrame() for one_file in glob.glob("steam_html_file/*.html"): f = open(one_file, "r", encoding= "utf-8") soup = BeautifulSoup(f.read(),"html.parser") items = soup.find("div", id = "search_result_container") for item in items.find_all("a"): try: ###因价格修改统一标签下存在多个子标签,打乱整体标签排列结构。 price_change = item.find("div",class_="col search_price discounted responsive_secondrow") if not price_change: ###价格无变动的游戏的价格 original_price = item.find("div", class_="col search_price_discount_combined responsive_secondrow").get_text().strip() else: ###注意,如果发现有价格变动时,虽然不去,但是也要输出空值占位置,为后面合并数据做准备! original_price = "" df1 = df1.append({ "3.original price": original_price }, ignore_index=True) if price_change: ##价格有变动的游戏现在的价格 changed_price = price_change.get_text().strip() else: changed_price = "" df2 = df2.append({ "4.changed price":changed_price },ignore_index=True) # print(changed_price) ###价格信息提取完成 ######???待寻找如何将变动后价格拼接到没有价格变动的那一列中,查寻方向:合并多个df时如何填补同一列中的空缺值 name = item.find("div", class_="col search_name ellipsis").find("span").get_text().strip() release_time = item.find("div", class_="col search_released responsive_secondrow").get_text().strip() df = df.append({ "1.name": name, "2.release_time":release_time, },ignore_index=True) except: pass df2 = df1.join(df2) df = df.join(df2) print (df) df.to_csv("steam_html_file/steam_fps_game.csv", encoding="utf-8-sig") ####
[ "13701304462@163.com" ]
13701304462@163.com
44b8b15712428540ec8bb8881ed03e41fb5bbabc
09e57dd1374713f06b70d7b37a580130d9bbab0d
/benchmark/startQiskit2167.py
0d743940a6f806b63db35149af9e8542d6728277
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
4,035
py
# qubit number=4 # total number=37 import cirq import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2 import numpy as np import networkx as nx def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() return oracle def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=16 prog.cz(input_qubit[0],input_qubit[3]) # number=17 prog.rx(-0.5686282702997527,input_qubit[3]) # number=32 prog.h(input_qubit[3]) # number=18 prog.h(input_qubit[3]) # number=26 prog.cz(input_qubit[0],input_qubit[3]) # number=27 prog.h(input_qubit[3]) # number=28 prog.x(input_qubit[3]) # number=21 prog.rx(0.4241150082346221,input_qubit[2]) # number=33 prog.h(input_qubit[3]) # number=34 prog.cz(input_qubit[0],input_qubit[3]) # number=35 prog.h(input_qubit[3]) # number=36 prog.cx(input_qubit[0],input_qubit[3]) # number=12 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.h(input_qubit[0]) # number=5 oracle = build_oracle(n-1, f) prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]]) prog.h(input_qubit[1]) # number=6 prog.h(input_qubit[2]) # number=23 prog.cz(input_qubit[1],input_qubit[2]) # number=24 prog.h(input_qubit[2]) # number=25 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=8 prog.cx(input_qubit[2],input_qubit[0]) # number=29 prog.z(input_qubit[2]) # number=30 prog.cx(input_qubit[2],input_qubit[0]) # number=31 prog.h(input_qubit[0]) # number=9 prog.y(input_qubit[0]) # number=14 prog.y(input_qubit[0]) # number=15 # circuit end for i in range(n): prog.measure(input_qubit[i], classical[i]) return prog if __name__ == '__main__': a = "111" b = "0" f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b) prog = make_circuit(4,f) backend = BasicAer.get_backend('qasm_simulator') sample_shot =8000 info = execute(prog, backend=backend, shots=sample_shot).result().get_counts() backend = FakeVigo() circuit1 = transpile(prog,backend,optimization_level=2) writefile = open("../data/startQiskit2167.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.__len__(),file=writefile) print(circuit1,file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
96a2513a19ec5ef5b4cef589ef45c1624ee248cb
117f066c80f3863ebef74463292bca6444f9758a
/data_pulling/crypto/do.py
33e917485159521a9e506bfcba5606efbf76ad82
[]
no_license
cottrell/notebooks
c6de3842cbaeb71457d270cbe6fabc8695a6ee1b
9eaf3d0500067fccb294d064ab78d7aaa03e8b4d
refs/heads/master
2023-08-09T22:41:01.996938
2023-08-04T22:41:51
2023-08-04T22:41:51
26,830,272
3
1
null
2023-03-04T03:58:03
2014-11-18T21:14:23
Python
UTF-8
Python
false
false
1,908
py
import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import os import glob import inspect def get_pandas_read_csv_defaults(): # probably fragile i = inspect.getfullargspec(pd.read_csv) v = i.defaults k = i.args[-len(v):] kwargs = dict(zip(k, v)) return kwargs _mydir = os.path.dirname(os.path.realpath('__file__')) def load_raw(): # note manually removed some bad row kwargs = get_pandas_read_csv_defaults() kwargs['thousands'] = ',' # always do this kwargs['parse_dates'] = ['Date'] kwargs['na_values'] = ['-'] kwargs['dtype'] = 'str' dtype = { 'Close': 'float', 'High': 'float', 'Low': 'float', 'Market Cap': 'float', 'Open': 'float', 'Volume': 'float' } meta = pd.read_csv(os.path.join(_mydir, 'Top100Cryptos/data/100 List.csv')) names = meta.Name.tolist() files = [os.path.join(_mydir, 'Top100Cryptos/data/{}.csv'.format(x)) for x in names] # files = glob.glob(os.path.join(_mydir, 'Top100Cryptos/data/*.csv')) dfs = list() datadir = os.path.join(_mydir, 'parsed') if not os.path.exists(datadir): os.makedirs(datadir) for i, (name, f) in enumerate(zip(names, files)): mtime = os.path.getmtime(f) dirname = os.path.join(datadir, 'name={}/mtime={}'.format(name, mtime)) filename = os.path.join(dirname, 'data.parquet') if not os.path.exists(filename): df = pd.read_csv(f, **kwargs) df = pa.Table.from_pandas(df) if not os.path.exists(dirname): os.makedirs(dirname) print('writing {}'.format(filename)) pq.write_table(df, filename) pq.read_table('./parsed') # test else: print('{} exists'.format(filename)) return pq.read_table('./parsed') # test # id big ups big downs df = load_raw() df = df.sort_values('Date')
[ "cottrell@users.noreply.github.com" ]
cottrell@users.noreply.github.com
7c4ca5b5dfae96a3696b405eff6c615b26b86332
4c873560c66ce3b84268ad2abcd1ffcada32e458
/examples/scripts/csc/gwnden_clr.py
d382225550d6ce93e6a690716a2697b9e384579a
[ "BSD-3-Clause" ]
permissive
wangjinjia1/sporco
d21bf6174365acce614248fcd2f24b72d5a5b07f
c6363b206fba6f440dd18de7a17dadeb47940911
refs/heads/master
2023-04-02T01:10:02.905490
2021-03-29T14:20:57
2021-03-29T14:20:57
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,966
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the SPORCO package. Details of the copyright # and user license can be found in the 'LICENSE.txt' file distributed # with the package. """ Gaussian White Noise Restoration via CSC ======================================== This example demonstrates the removal of Gaussian white noise from a colour image using convolutional sparse coding :cite:`wohlberg-2016-convolutional`, $$\mathrm{argmin}_\mathbf{x} \; (1/2) \sum_c \left\| \sum_m \mathbf{d}_{m} * \mathbf{x}_{c,m} -\mathbf{s}_c \right\|_2^2 + \lambda \sum_m \| \mathbf{x}_m \|_1 + \mu \| \{ \mathbf{x}_{c,m} \} \|_{2,1}$$ where $\mathbf{d}_m$ is the $m^{\text{th}}$ dictionary filter, $\mathbf{x}_{c,m}$ is the coefficient map corresponding to the $c^{\text{th}}$ colour band and $m^{\text{th}}$ dictionary filter, and $\mathbf{s}_c$ is colour band $c$ of the input image. """ from __future__ import print_function from builtins import input import pyfftw # See https://github.com/pyFFTW/pyFFTW/issues/40 import numpy as np from sporco import util from sporco import signal from sporco import fft from sporco import metric from sporco import plot from sporco.cupy import (cupy_enabled, np2cp, cp2np, select_device_by_load, gpu_info) from sporco.cupy.admm import cbpdn """ Boundary artifacts are handled by performing a symmetric extension on the image to be denoised and then cropping the result to the original image support. This approach is simpler than the boundary handling strategies that involve the insertion of a spatial mask into the data fidelity term, and for many problems gives results of comparable quality. The functions defined here implement symmetric extension and cropping of images. """ def pad(x, n=8): if x.ndim == 2: return np.pad(x, n, mode='symmetric') else: return np.pad(x, ((n, n), (n, n), (0, 0)), mode='symmetric') def crop(x, n=8): return x[n:-n, n:-n] """ Load a reference image and corrupt it with Gaussian white noise with $\sigma = 0.1$. (The call to ``numpy.random.seed`` ensures that the pseudo-random noise is reproducible.) """ img = util.ExampleImages().image('monarch.png', zoom=0.5, scaled=True, idxexp=np.s_[:, 160:672]) np.random.seed(12345) imgn = img + np.random.normal(0.0, 0.1, img.shape).astype(np.float32) """ Highpass filter test image. """ npd = 16 fltlmbd = 5.0 imgnl, imgnh = signal.tikhonov_filter(imgn, fltlmbd, npd) """ Load dictionary. """ D = util.convdicts()['G:8x8x128'] """ Set solver options. See Section 8 of :cite:`wohlberg-2017-convolutional2` for details of construction of $\ell_1$ weighting matrix $W$. """ imgnpl, imgnph = signal.tikhonov_filter(pad(imgn), fltlmbd, npd) W = fft.irfftn(np.conj(fft.rfftn(D[..., np.newaxis, :], imgnph.shape[0:2], (0, 1))) * fft.rfftn(imgnph[..., np.newaxis], None, (0, 1)), imgnph.shape[0:2], (0, 1)) W = 1.0/(np.maximum(np.abs(W), 1e-8)) lmbda = 1.5e-2 mu = 2.7e-1 opt = cbpdn.ConvBPDNJoint.Options({'Verbose': True, 'MaxMainIter': 250, 'HighMemSolve': True, 'RelStopTol': 3e-3, 'AuxVarObj': False, 'L1Weight': cp2np(W), 'AutoRho': {'Enabled': False}, 'rho': 1e3*lmbda}) """ Initialise a ``sporco.cupy`` version of a :class:`.admm.cbpdn.ConvBPDNJoint` object and call the ``solve`` method. """ if not cupy_enabled(): print('CuPy/GPU device not available: running without GPU acceleration\n') else: id = select_device_by_load() info = gpu_info() if info: print('Running on GPU %d (%s)\n' % (id, info[id].name)) b = cbpdn.ConvBPDNJoint(np2cp(D), np2cp(pad(imgnh)), lmbda, mu, opt, dimK=0) X = cp2np(b.solve()) """ The denoised estimate of the image is just the reconstruction from the coefficient maps. """ imgdp = cp2np(b.reconstruct().squeeze()) imgd = np.clip(crop(imgdp) + imgnl, 0, 1) """ Display solve time and denoising performance. """ print("ConvBPDNJoint solve time: %5.2f s" % b.timer.elapsed('solve')) print("Noisy image PSNR: %5.2f dB" % metric.psnr(img, imgn)) print("Denoised image PSNR: %5.2f dB" % metric.psnr(img, imgd)) """ Display the reference, noisy, and denoised images. """ fig = plot.figure(figsize=(21, 7)) plot.subplot(1, 3, 1) plot.imview(img, title='Reference', fig=fig) plot.subplot(1, 3, 2) plot.imview(imgn, title='Noisy', fig=fig) plot.subplot(1, 3, 3) plot.imview(imgd, title='CSC Result', fig=fig) fig.show() """ Plot functional evolution during ADMM iterations. """ its = b.getitstat() plot.plot(its.ObjFun, xlbl='Iterations', ylbl='Functional') """ Plot evolution of ADMM residuals and ADMM penalty parameter. """ plot.plot(np.vstack((its.PrimalRsdl, its.DualRsdl)).T, ptyp='semilogy', xlbl='Iterations', ylbl='Residual', lgnd=['Primal', 'Dual']) plot.plot(its.Rho, xlbl='Iterations', ylbl='Penalty Parameter') # Wait for enter on keyboard input()
[ "brendt@ieee.org" ]
brendt@ieee.org
d038c06c6c4f20653a17f5fb33b4d16d637fb9be
66acbd1f601e00f311c53a9ce0659e5b56c87fef
/pre_analysis/observable_analysis/topc4mcintervalanalyser.py
508e973104b53d9e4245701856db48d1f55c9b6c
[ "MIT" ]
permissive
hmvege/LatticeAnalyser
fad3d832190f4903642a588ed018f6cca3858193
6c3e69ab7af893f23934d1c3ce8355ac7514c0fe
refs/heads/master
2021-05-25T11:46:30.278709
2019-04-11T14:14:23
2019-04-11T14:14:23
127,303,453
0
1
null
2018-10-12T21:09:58
2018-03-29T14:29:14
Python
UTF-8
Python
false
false
601
py
from pre_analysis.core.flowanalyser import FlowAnalyser class Topc4MCIntervalAnalyser(FlowAnalyser): """Class for topological charge with quartic topological charge.""" observable_name = r"$\langle Q^4 \rangle$" observable_name_compact = "topc4MC" x_label = r"$\sqrt{8t_{f}}$ [fm]" y_label = r"$\langle Q^4 \rangle$" def __init__(self, *args, **kwargs): super(Topc4MCIntervalAnalyser, self).__init__(*args, **kwargs) self.y **= 4 def main(): exit("Module Topc4MCIntervalAnalyser not intended for standalone usage.") if __name__ == '__main__': main()
[ "hmvege@ulrik.uio.no" ]
hmvege@ulrik.uio.no
37b0f73442e6b0db42d0419136e19faef5f2f973
d272b041f84bbd18fd65a48b42e0158ef6cceb20
/catch/datasets/tacaribe_mammarenavirus.py
7f62021e43d0f87c81e26077042b3721995eee6d
[ "MIT" ]
permissive
jahanshah/catch
bbffeadd4113251cc2b2ec9893e3d014608896ce
2fedca15f921116f580de8b2ae7ac9972932e59e
refs/heads/master
2023-02-19T13:30:13.677960
2021-01-26T03:41:10
2021-01-26T03:41:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,231
py
"""Dataset with 'Tacaribe mammarenavirus' sequences. A dataset with 5 'Tacaribe mammarenavirus' sequences. The virus is segmented and has 2 segments. Based on their strain and/or isolate, these sequences were able to be grouped into 4 genomes. Many genomes may have fewer than 2 segments. THIS PYTHON FILE WAS GENERATED BY A COMPUTER PROGRAM! DO NOT EDIT! """ import sys from catch.datasets import GenomesDatasetMultiChrom def seq_header_to_chr(header): import re c = re.compile(r'\[segment (L|S)\]') m = c.search(header) if not m: raise Exception("Unknown or invalid segment in header %s" % header) seg = m.group(1) return "segment_" + seg def seq_header_to_genome(header): import re c = re.compile(r'\[genome (.+)\]') m = c.search(header) if not m: raise Exception("Unknown genome in header %s" % header) return m.group(1) chrs = ["segment_" + seg for seg in ['L', 'S']] ds = GenomesDatasetMultiChrom(__name__, __file__, __spec__, chrs, seq_header_to_chr, seq_header_to_genome=seq_header_to_genome) ds.add_fasta_path("data/tacaribe_mammarenavirus.fasta.gz", relative=True) sys.modules[__name__] = ds
[ "hmetsky@gmail.com" ]
hmetsky@gmail.com
47b0fad3467437ec0622fddde5ff65dbed7f685e
a306e621d15d6287f75c8e4f22329da810408605
/tests/test_distance.py
2500daf3774b7e965c5bd7d243e4f01b24e8e026
[ "MIT" ]
permissive
moble/quaternionic
c6175a8e5ff57fbb9d2f2462bc761368f3b4fa66
074b626d0c63aa78479ff04ed41638931ca6693a
refs/heads/main
2023-06-08T08:21:46.827232
2023-02-07T17:36:31
2023-02-07T17:36:38
286,745,519
73
7
MIT
2023-05-27T12:19:43
2020-08-11T13:00:26
Python
UTF-8
Python
false
false
3,116
py
import warnings import numpy as np import quaternionic import pytest @pytest.mark.parametrize("rotor,rotation,slow", [ # pragma: no branch (quaternionic.distance.rotor, quaternionic.distance.rotation, True), quaternionic.distance.CreateMetrics(lambda f: f, quaternionic.utilities.pyguvectorize) + (False,) ], ids=["jit metrics", "non-jit metrics"]) def test_metrics(Rs, array, rotor, rotation, slow): metric_precision = 4.e-15 Rs = array(Rs.ndarray) one = array(1, 0, 0, 0) intrinsic_funcs = (rotor.intrinsic, rotation.intrinsic) chordal_funcs = (rotor.chordal, rotation.chordal) metric_funcs = intrinsic_funcs + chordal_funcs rotor_funcs = (rotor.intrinsic, rotor.chordal) rotation_funcs = (rotation.intrinsic, rotation.chordal) distance_dict = {func: func(Rs, Rs[:, np.newaxis]) for func in metric_funcs} # Check non-negativity for mat in distance_dict.values(): assert np.all(mat >= 0.) # Check discernibility for func in metric_funcs: if func in chordal_funcs: eps = 0 else: eps = 5.e-16 if func in rotor_funcs: target = Rs != Rs[:, np.newaxis] else: target = np.logical_and(Rs != Rs[:, np.newaxis], Rs != - Rs[:, np.newaxis]) assert ((distance_dict[func] > eps) == target).all() # Check symmetry for mat in distance_dict.values(): assert np.allclose(mat, mat.T, atol=metric_precision, rtol=0) # Check triangle inequality for mat in distance_dict.values(): assert ((mat - metric_precision)[:, np.newaxis, :] <= mat[:, :, np.newaxis] + mat).all() # Check distances from self or -self for func in metric_funcs: # All distances from self should be 0.0 if func in chordal_funcs: eps = 0 else: eps = 5.e-16 assert (np.diag(distance_dict[func]) <= eps).all() # Chordal rotor distance from -self should be 2 assert (abs(rotor.chordal(Rs, -Rs) - 2.0) < metric_precision).all() # Intrinsic rotor distance from -self should be 2pi assert (abs(rotor.intrinsic(Rs, -Rs) - 2.0 * np.pi) < metric_precision).all() # Rotation distances from -self should be 0 assert (rotation.chordal(Rs, -Rs) == 0.0).all() assert (rotation.intrinsic(Rs, -Rs) < 5.e-16).all() # We expect the chordal distance to be smaller than the intrinsic distance (or equal, if the distance is zero) assert np.logical_or(rotor.chordal(one, Rs) < rotor.intrinsic(one, Rs), Rs == one).all() if slow: # Check invariance under overall rotations: d(R1, R2) = d(R3*R1, R3*R2) = d(R1*R3, R2*R3) for func in rotor.chordal, rotation.intrinsic: rotations = Rs[:, np.newaxis] * Rs right_distances = func(rotations, rotations[:, np.newaxis]) assert (abs(distance_dict[func][:, :, np.newaxis] - right_distances) < metric_precision).all() left_distances = func(rotations[:, :, np.newaxis], rotations[:, np.newaxis]) assert (abs(distance_dict[func] - left_distances) < metric_precision).all()
[ "michael.oliver.boyle@gmail.com" ]
michael.oliver.boyle@gmail.com
818fb09f8f5de94bdddf44acd471f366bfd04c70
eb463217f001a8ff63243208dc2bb7e355793548
/src/richie/plugins/section/migrations/0002_add_template_field.py
d3c83581c472881596481d657675e6d9f2744e84
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
phuoclhb/richie
25020254b635c41648d65a30b3f2405007bd8a39
328167d02f9596c8b1d428655f0de1bed7fb277d
refs/heads/master
2020-08-13T07:14:22.006472
2019-10-11T15:31:02
2019-10-11T15:58:48
214,930,515
1
0
MIT
2019-10-14T02:27:14
2019-10-14T02:27:13
null
UTF-8
Python
false
false
631
py
# Generated by Django 2.1.7 on 2019-02-22 01:57 from django.db import migrations, models from ..defaults import SECTION_TEMPLATES class Migration(migrations.Migration): dependencies = [("section", "0001_initial")] operations = [ migrations.AddField( model_name="section", name="template", field=models.CharField( choices=SECTION_TEMPLATES, default=SECTION_TEMPLATES[0][0], help_text="Optional template for custom look.", max_length=150, verbose_name="Template", ), ) ]
[ "sveetch@gmail.com" ]
sveetch@gmail.com
d6758b1214e18affacc304004dfb23d732194dc0
07cf86733b110a13224ef91e94ea5862a8f5d0d5
/taum_and_bday/taum_and_bday.py
2dca00a8c687bce30c4615338d881eba6f673268
[]
no_license
karsevar/Code_Challenge_Practice
2d96964ed2601b3beb324d08dd3692c3d566b223
88d4587041a76cfd539c0698771420974ffaf60b
refs/heads/master
2023-01-23T17:20:33.967020
2020-12-14T18:29:49
2020-12-14T18:29:49
261,813,079
1
0
null
null
null
null
UTF-8
Python
false
false
851
py
def taumBday(b, w, bc, wc, z): # Write your code here # create a variable named black_cost # create a variable named white_cost # check if bc + z is less than wc: # if so overwrite white_cost with b * (bc + z) # overwrite black_cost with b * (bc) # elif wc + z is less than bc: # if so overwrite black_cost with w * (wc + z) # overwrite white_cost with w * (wc) # else # overwrite black_cost with b * (bc + z) # overwrite white_cost with w * (wc + z) black_cost = 0 white_cost = 0 if (bc + z) < wc: white_cost = w * (bc + z) black_cost = b * bc elif (wc + z) < bc: white_cost = w * wc black_cost = b * (wc + z) else: white_cost = w * wc black_cost = b * bc return white_cost + black_cost
[ "masonkarsevar@gmail.com" ]
masonkarsevar@gmail.com
1b0b4bc4e5b5b0bc77020ca601dd1f1dabbccc3a
23e74e0d5bd42de514544917f7b33206e5acf84a
/alumnos/58003-Martin-Ruggeri/copia.py
eb8dc2774c2bf67e0fdfa336f443d85570aba882
[]
no_license
Martin-Ruggeri-Bio/lab
2e19015dae657bb9c9e86c55d8355a04db8f5804
9a1c1d8f99c90c28c3be62670a368838aa06988f
refs/heads/main
2023-08-01T07:26:42.015115
2021-09-20T20:21:31
2021-09-20T20:21:31
350,102,381
0
0
null
2021-03-21T19:48:58
2021-03-21T19:48:58
null
UTF-8
Python
false
false
279
py
#!/bin/python3 def copiaArchivos(): archi_org = open(input("ingrese archivo de origen:\n"), "r") archi_des = open(input("ingrese archivo de destino:\n"), "w") with archi_org: archi_des.write(archi_org.read()) if __name__ == '__main__': copiaArchivos()
[ "martinruggeri18@gmail.com" ]
martinruggeri18@gmail.com
85dfa9657bf5f1207e0b7cd837ff3661aa12b093
2dd560dc468af0af4ca44cb4cd37a0b807357063
/Leetcode/2. Add Two Numbers/solution1.py
78df80bb3d9a1d82a8d444589710b5f138669603
[ "MIT" ]
permissive
hi0t/Outtalent
460fe4a73788437ba6ce9ef1501291035c8ff1e8
8a10b23335d8e9f080e5c39715b38bcc2916ff00
refs/heads/master
2023-02-26T21:16:56.741589
2021-02-05T13:36:50
2021-02-05T13:36:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
712
py
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: dummy_head = curr_head = ListNode() p, q = l1, l2 carry = 0 while p or q: if p: carry += p.val p = p.next if q: carry += q.val q = q.next curr_head.next = ListNode(carry % 10) curr_head = curr_head.next carry //= 10 if carry > 0: curr_head.next = ListNode(carry) return dummy_head.next
[ "info@crazysquirrel.ru" ]
info@crazysquirrel.ru
2fd7e86a0345548fe89a360c898f938f9227bdb2
5b38dd549d29322ae07ad0cc68a28761989ef93a
/cc_lib/_util/_logger.py
fc66aac68804a599831a0405e5eaf400e78fd1cb
[ "Apache-2.0" ]
permissive
SENERGY-Platform/client-connector-lib
d54ea800807892600cf08d3b2a4f00e8340ab69c
e365fc4bed949e84cde81fd4b5268bb8d4f53c12
refs/heads/master
2022-09-03T00:03:29.656511
2022-08-24T11:18:22
2022-08-24T11:18:22
159,316,125
1
2
Apache-2.0
2020-05-27T07:47:14
2018-11-27T10:15:38
Python
UTF-8
Python
false
false
784
py
""" Copyright 2019 InfAI (CC SES) 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. """ __all__ = ('get_logger',) import logging logger = logging.getLogger('connector') logger.propagate = False def get_logger(name: str) -> logging.Logger: return logger.getChild(name)
[ "42994541+y-du@users.noreply.github.com" ]
42994541+y-du@users.noreply.github.com
74b4ed23694523deb7002963f183afb60094dad0
fb1e852da0a026fb59c8cb24aeb40e62005501f1
/decoding/GAD/fairseq/modules/scalar_bias.py
c96247c75914fabb8a2b7ff731bb82b588f72690
[ "LGPL-2.1-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
microsoft/unilm
134aa44867c5ed36222220d3f4fd9616d02db573
b60c741f746877293bb85eed6806736fc8fa0ffd
refs/heads/master
2023-08-31T04:09:05.779071
2023-08-29T14:07:57
2023-08-29T14:07:57
198,350,484
15,313
2,192
MIT
2023-08-19T11:33:20
2019-07-23T04:15:28
Python
UTF-8
Python
false
false
888
py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import torch class ScalarBias(torch.autograd.Function): """ Adds a vector of scalars, used in self-attention mechanism to allow the model to optionally attend to this vector instead of the past """ @staticmethod def forward(ctx, input, dim, bias_init): size = list(input.size()) size[dim] += 1 output = input.new(*size).fill_(bias_init) output.narrow(dim, 1, size[dim] - 1).copy_(input) ctx.dim = dim return output @staticmethod def backward(ctx, grad): return grad.narrow(ctx.dim, 1, grad.size(ctx.dim) - 1), None, None def scalar_bias(input, dim, bias_init=0): return ScalarBias.apply(input, dim, bias_init)
[ "tage@microsoft.com" ]
tage@microsoft.com
79331affbc571e2fd6380690621972ed904a93b2
33836016ea99776d31f7ad8f2140c39f7b43b5fe
/fip_collab/2015_11_15_5deg_FIP_db/check_db_symm_v3.py
02760a80bd14513da9f994e3a337517bca50323a
[]
no_license
earthexploration/MKS-Experimentation
92a2aea83e041bfe741048d662d28ff593077551
9b9ff3b468767b235e7c4884b0ed56c127328a5f
refs/heads/master
2023-03-17T23:11:11.313693
2017-04-24T19:24:35
2017-04-24T19:24:35
null
0
0
null
null
null
null
UTF-8
Python
false
false
7,154
py
import numpy as np import matplotlib.pyplot as plt import euler_func as ef import h5py """ check whether the database exhibits hexagonal-triclinic crystal symmetry first find 12 symmetric orientations in triclinic FZ (0<=phi1<2*pi, 0<=Phi<=pi, 0<=phi2<2*pi) for each deformation mode sample (theta), check if the value of interest is the same for all symmetric orientations """ inc = 5 # degree increment for angular variables np.random.seed() # generate seed for random symhex = ef.symhex() r2d = 180./np.pi d2r = np.pi/180. r2s = r2d/inc n_th_max = 120/inc # number of theta samples in FOS n_max = 360/inc # number of phi1, Phi and phi2 samples in FOS n_hlf = 180/inc # half n_max n_th = (60/inc)+1 # number of theta samples for FZ n_p1 = 360/inc # number of phi1 samples for FZ n_P = (90/inc)+1 # number of Phi samples for FZ n_p2 = 60/inc # number of phi2 samples for FZ print "angle space shape: %s" % str(np.array([n_th, n_p1, n_P, n_p2])) # only look at last in series for value of interest db = np.load("pre_fft.npy")[:n_th, ..., -1] print "db shape: %s" % str(db.shape) # n_FZ: total number of sampled orientations in FZ n_FZ = n_p1*n_P*n_p2 # FZ_indx: vector of linear indices for sampled orientations in FZ FZ_indx = np.arange(n_FZ) print "FZ_indx shape: %s" % str(FZ_indx.shape) # FZ_subs: array of subscripts of sampled orientations in FZ FZ_subs = np.unravel_index(FZ_indx, (n_p1, n_P, n_p2)) FZ_subs = np.array(FZ_subs).transpose() print "FZ_subs shape: %s" % str(FZ_subs.shape) # FZ_euler: array of euler angles of sampled orientations in FZ FZ_euler = np.float64(FZ_subs*inc*d2r) # g: array of orientation matrices (sample to crystal frame rotation # matrices) for orientations in fundamental zone g = ef.bunge2g(FZ_euler[:, 0], FZ_euler[:, 1], FZ_euler[:, 2]) print "g shape: %s" % str(g.shape) # FZ_euler_sym: array of euler angles of sampled orientations in # FZ and their symmetric equivalents FZ_euler_sym = np.zeros((12, n_FZ, 3)) # find the symmetric equivalents to the euler angle within the FZ for sym in xrange(12): op = symhex[sym, ...] # g_sym: array of orientation matrices transformed with a # hexagonal symmetry operator g_sym = np.einsum('ik,...kj', op, g) tmp = np.array(ef.g2bunge(g_sym)).transpose() if sym == 0: print "g_sym shape: %s" % str(g_sym.shape) print "tmp shape: %s" % str(tmp.shape) del g_sym FZ_euler_sym[sym, ...] = tmp del tmp # convert euler angles to subscripts FZ_subs_sym = np.int64(np.round(FZ_euler_sym*r2s)) # # make sure all of the euler angles within the appropriate # # ranges (eg. not negative) for ii in xrange(3): lt = FZ_subs_sym[..., ii] < 0.0 FZ_subs_sym[..., ii] += n_max*lt print np.sum(FZ_subs_sym < 0) # determine the deviation from symmetry by finding the value of # the function for symmetric locations and comparing these values f = h5py.File('symm_check.hdf5', 'w') error = f.create_dataset("error", (n_th, 12, n_FZ, 5)) for th in xrange(n_th): for sym in xrange(12): error[th, sym, :, 0:3] = FZ_subs_sym[sym, ...]*inc origFZ = db[th, FZ_subs_sym[0, :, 0], FZ_subs_sym[0, :, 1], FZ_subs_sym[0, :, 2]] symFZ = db[th, FZ_subs_sym[sym, :, 0], FZ_subs_sym[sym, :, 1], FZ_subs_sym[sym, :, 2]] if th == 0 and sym == 0: print "origFZ shape: %s" % str(origFZ.shape) print "symFZ shape: %s" % str(symFZ.shape) if th == 0: print "operator number: %s" % sym idcheck = np.all(FZ_euler_sym[0, ...] == FZ_euler_sym[sym, ...]) print "are Euler angles in different FZs identical?: %s" % str(idcheck) orig_0sum = np.sum(origFZ == 0.0) sym_0sum = np.sum(symFZ == 0.0) if orig_0sum != 0 or sym_0sum != 0: print "number of zero values in origFZ: %s" % orig_0sum print "number of zero values in symFZ: %s" % sym_0sum error[th, sym, :, 3] = symFZ error[th, sym, :, 4] = np.abs(origFZ-symFZ) error_sec = error[...] f.close() # perform error analysis # generate random deformation mode and euler angle # th_rand = np.int64(np.round((n_th-1)*np.random.rand())) # g_rand = np.int64(np.round((n_FZ-1)*np.random.rand())) badloc = np.argmax(error_sec[..., 4]) badloc = np.unravel_index(badloc, error_sec[..., 3].shape) th_rand = badloc[0] g_rand = badloc[2] print "\nexample comparison:" print "deformation mode: %s degrees" % str(np.float(th_rand*inc)) for sym in xrange(12): print "operator number: %s" % sym eul_rand = error_sec[th_rand, sym, g_rand, 0:3] print "euler angles: %s (degrees)" % str(eul_rand) val_rand = error_sec[th_rand, sym, g_rand, 3] print "value of interest: %s" % str(val_rand) errvec = error_sec[..., 4].reshape(error_sec[..., 4].size) print "\noverall error metrics:" print "mean database value: %s" % np.mean(db) print "mean error: %s" % np.mean(errvec) print "maximum error: %s" % np.max(errvec) print "standard deviation of error: %s" % np.std(errvec) print "total number of locations checked: %s" % (errvec.size) err_count = np.sum(errvec != 0.0) # plot the error histograms error_indx = errvec != 0.0 print error_indx.shape loc_hist = errvec[error_indx] print loc_hist.shape err_count = np.sum(loc_hist != 0.0) print "number of locations with nonzero error: %s" % err_count errvec_p1 = error_sec[..., 0].reshape(error_sec[..., 0].size)[error_indx] plt.figure(num=4, figsize=[10, 6]) plt.hist(errvec_p1, 361) errvec_P = error_sec[..., 1].reshape(error_sec[..., 1].size)[error_indx] plt.figure(num=5, figsize=[10, 6]) plt.hist(errvec_P, 361) errvec_p2 = error_sec[..., 0].reshape(error_sec[..., 0].size)[error_indx] plt.figure(num=6, figsize=[10, 6]) plt.hist(errvec_p2, 361) # plot the error histograms plt.figure(num=1, figsize=[10, 6]) error_hist = error_sec[..., 4] plt.hist(error_hist.reshape(error_hist.size), 100) # plot the symmetric orientations in euler space plt.figure(2) plt.plot(np.array([0, 360, 360, 0, 0]), np.array([0, 0, 180, 180, 0]), 'k-') plt.plot(np.array([0, 360]), np.array([90, 90]), 'k-') plt.xlabel('$\phi_1$') plt.ylabel('$\Phi$') sc = 1.05 plt.axis([-(sc-1)*360, sc*360, -(sc-1)*180, sc*180]) plt.figure(3) plt.plot(np.array([0, 180, 180, 0, 0]), np.array([0, 0, 360, 360, 0]), 'k-') plt.plot(np.array([90, 90]), np.array([0, 360]), 'k-') plt.plot(np.array([0, 180]), np.array([60, 60]), 'k-') plt.plot(np.array([0, 180]), np.array([120, 120]), 'k-') plt.plot(np.array([0, 180]), np.array([180, 180]), 'k-') plt.plot(np.array([0, 180]), np.array([240, 240]), 'k-') plt.plot(np.array([0, 180]), np.array([300, 300]), 'k-') plt.xlabel('$\Phi$') plt.ylabel('$\phi2$') sc = 1.05 plt.axis([-(sc-1)*180, sc*180, -(sc-1)*360, sc*360]) eul_plt = error_sec[th_rand, :, g_rand, 0:3] plt.figure(2) plt.plot(eul_plt[:, 0], eul_plt[:, 1], c='b', marker='o', linestyle='none') plt.figure(3) plt.plot(eul_plt[:, 1], eul_plt[:, 2], c='b', marker='o', linestyle='none') plt.show()
[ "noahhpaulson@gmail.com" ]
noahhpaulson@gmail.com
61094d5d3babcb4ac784998ee52b573967471ac0
7fc22330d96b48a425894311441c4e83cb4d2447
/code/snakeeyes/tests/__init__.py
e207e34b2b0db2f98b137a14327de8cf795330f9
[]
no_license
tangentstorm/snakeeyes
5c23791adfe4511a3a97a35d725d1b2769552000
a036884e39fe7989e8101c7f96cae8d4f3c507ea
refs/heads/master
2021-01-22T08:23:27.661057
2020-11-22T05:08:56
2020-11-22T05:08:56
10,516,815
3
2
null
null
null
null
UTF-8
Python
false
false
299
py
""" Created on Aug 1, 2009 @author: michal """ import sys; sys.path.append("..") # for testloop.sh import unittest from snakeeyes.tests.img_test import * from snakeeyes.tests.ocr_test import * from snakeeyes.tests.scrape_test import * if __name__ == '__main__': unittest.main()
[ "michal.wallace@gmail.com" ]
michal.wallace@gmail.com