blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
69
license_type
stringclasses
2 values
repo_name
stringlengths
5
118
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
63
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
2.91k
686M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
213 values
src_encoding
stringclasses
30 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
2
10.3M
extension
stringclasses
246 values
content
stringlengths
2
10.3M
authors
listlengths
1
1
author_id
stringlengths
0
212
1e91a803b328bd034654bf41ee0e6eb97faa69de
298776e160c57d27a924228ef4054e9b72802630
/Hard/continuous-median.py
8dfd9bf45b9542887362529662435b080aec2833
[ "MIT" ]
permissive
kckotcherlakota/algoexpert-data-structures-algorithms
60bf1643dd912ae0dd4a6ff9f3390d75f5edde7c
f79eb5f23ebf941078014b917dc840af4e524dbb
refs/heads/master
2023-07-06T19:31:32.281102
2021-07-25T04:46:02
2021-07-25T04:46:02
389,708,228
2
0
null
null
null
null
UTF-8
Python
false
false
2,892
py
# CONTINUOUS MEDIAN # Do not edit the class below except for # the insert method. Feel free to add new # properties and methods to the class. class ContinuousMedianHandler: def __init__(self): # Write your code here. self.median = None self.lowers = Heap(MAX_HEAP_FUNC, []) self.greaters = Heap(MIN_HEAP_FUNC, []) # O(logN) time and O(N) space def insert(self, number): # Write your code here. if not self.lowers.length or number < self.lowers.peek(): self.lowers.insert(number) else: self.greaters.insert(number) self.rebalanceHeaps() self.updateMedian() def rebalanceHeaps(self): if self.lowers.length - self.greaters.length == 2: self.greaters.insert(self.lowers.remove()) elif self.greaters.length - self.lowers.length == 2: self.lowers.insert(self.greaters.remove()) def updateMedian(self): if self.lowers.length == self.greaters.length: self.median = (self.lowers.peek() + self.greaters.peek()) / 2 elif self.lowers.length > self.greaters.length: self.median = self.lowers.peek() else: self.median = self.greaters.peek() def getMedian(self): return self.median class Heap: def __init__(self, comparisonFunc, array): self.comparisonFunc = comparisonFunc self.heap = self.buildHeap(array) self.length = len(self.heap) def buildHeap(self, array): firstParentIdx = (len(array) - 2) // 2 for currentIdx in reversed(range(firstParentIdx + 1)): self.siftDown(currentIdx, len(array) - 1, array) return array def siftDown(self, currentIdx, endIdx, heap): childOneIdx = currentIdx * 2 + 1 while childOneIdx <= endIdx: childTwoIdx = currentIdx * 2 + 2 if currentIdx * 2 + 2 <= endIdx else -1 if childTwoIdx != -1: if self.comparisonFunc(heap[childTwoIdx], heap[childOneIdx]): idxToSwap = childTwoIdx else: idxToSwap = childOneIdx else: idxToSwap = childOneIdx if self.comparisonFunc(heap[idxToSwap], heap[currentIdx]): self.swap(currentIdx, idxToSwap, heap) currentIdx = idxToSwap childOneIdx = currentIdx * 2 + 1 else: return def siftUp(self, currentIdx, heap): parentIdx = (currentIdx - 1) // 2 while currentIdx > 0: if self.comparisonFunc(heap[currentIdx], heap[parentIdx]): self.swap(currentIdx, parentIdx, heap) currentIdx = parentIdx parentIdx = (currentIdx - 1) // 2 else: return def peek(self): return self.heap[0] def remove(self): self.swap(0, self.length - 1, self.heap) valueToRemove = self.heap.pop() self.length -= 1 self.siftDown(0, self.length - 1, self.heap) return valueToRemove def insert(self, value): self.heap.append(value) self.length += 1 self.siftUp(self.length - 1, self.heap) def swap(self, i, j, array): array[i], array[j] = array[j], array[i] def MAX_HEAP_FUNC(a, b): return a > b def MIN_HEAP_FUNC(a, b): return a < b
[ "das.jishu25@gmail.com" ]
das.jishu25@gmail.com
9785fb2c0135be8679c353ef40dc3735bf458e70
8b427d0a012d7dbd3b49eb32c279588f9ebd4e6e
/03 基本数据结构/base_converter.py
8a4adf70b5ec39d287b7bffb06c679cc84b2064d
[]
no_license
chenyang929/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python-Notes
e9f1b324d86963333edaf855fdb9e126e59e8542
aed976e020147fe30a8e0bb708dfbe4bab4c15f7
refs/heads/master
2020-03-18T02:46:12.385967
2018-07-24T08:24:41
2018-07-24T08:24:41
134,206,437
0
0
null
null
null
null
UTF-8
Python
false
false
494
py
# base_converter.py from stack import Stack def base_converter(decnumber, base): sk = Stack() while decnumber > 0: decnumber, rem = divmod(decnumber, base) sk.push(rem) bin_str = '' digits = '0123456789ABCDEF' while not sk.empty(): bin_str += digits[sk.pop()] return bin_str if __name__ == '__main__': print(base_converter(233, 2)) print(base_converter(233, 8)) print(base_converter(233, 10)) print(base_converter(233, 16))
[ "chenyang929code@gmail.com" ]
chenyang929code@gmail.com
1b04623916bf10e940e6aad684e3be6f45ce291f
69ef637ffa5739c368bc3a2da935f084203b56b6
/exercises/en/solution_02_29.py
9bc1817296e57d17bda520b44493983f2ca1cf2b
[ "MIT" ]
permissive
betatim/MCL-DSCI-011-programming-in-python
3e03734abb5af49b3dfc0b127e65b3573911afb0
b51f43a6bb1bedf0db028613d48d6566309ec44a
refs/heads/master
2022-11-08T06:03:56.190181
2020-06-25T16:20:30
2020-06-25T16:20:30
275,013,051
0
0
MIT
2020-06-25T20:53:13
2020-06-25T20:53:12
null
UTF-8
Python
false
false
786
py
import pandas as pd pokemon = pd.read_csv('data/pokemon.csv') # Create a plot by chaining the following actions # Make a groupby object on the column type and name it pokemon_type # Use .mean() on the new groupby object # Use .loc[] to select the attack column # Sort the pokemon mean attack values in descending order using .sort_values() # Finally plot the graph and give it an appropriate title # Name the y-axis "Mean attack scores" # Name the object attack_plot attack_plot = (pokemon.groupby('type') .mean() .loc[:, 'attack'] .sort_values(ascending=False) .plot.bar(title = 'Mean attack value among Pokemon types') .set_ylabel('Mean attack score') )
[ "hayleyfboyce@hotmail.com" ]
hayleyfboyce@hotmail.com
d0b980e1382c60d7095dd6b4453c79ca59557889
3b0ea7976e59068e9964464f145eb8ba94879c60
/Euler_14.py
1e30ddf1f7492a5cafab5b2ffc16ec8668b47ec1
[]
no_license
Hawkqwerty/euler_project
a6e30c3ac72b947d1789fd719573cbb9e4500ae3
b87125374307fb72b3ccf2ccc0b72b9e7c2704ac
refs/heads/master
2021-01-23T04:44:46.157006
2017-05-31T11:53:46
2017-05-31T11:53:46
92,940,966
0
0
null
null
null
null
UTF-8
Python
false
false
250
py
b=range(1,1000000) ko=[] k=[] for a in b: while a!=1: if a%2==0: a=a/2 else: a=3*a+1 ko.append(a) if a==1: k.append(int(len(ko)+1)) ko.clear() #print(max(k))
[ "alexeygrigorenko59@gmail.com" ]
alexeygrigorenko59@gmail.com
fc7602b854c8047f9e2b39feb62c070dca7154af
52b5fa23f79d76883728d8de0bfd202c741e9c43
/kubernetes/client/models/v1_api_group.py
92e0cdebde10702fa4255463874479a99acdfee0
[]
no_license
kippandrew/client-python-tornado
5d00810f57035825a84e37ff8fc89a7e79aed8da
d479dfeb348c5dd2e929327d800fe033b5b3b010
refs/heads/master
2021-09-04T13:01:28.275677
2018-01-18T23:27:34
2018-01-18T23:27:34
114,912,995
0
0
null
null
null
null
UTF-8
Python
false
false
10,458
py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v1.8.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from kubernetes.client.models.v1_group_version_for_discovery import V1GroupVersionForDiscovery # noqa: F401,E501 from kubernetes.client.models.v1_server_address_by_client_cidr import V1ServerAddressByClientCIDR # noqa: F401,E501 class V1APIGroup(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'api_version': 'str', 'kind': 'str', 'name': 'str', 'preferred_version': 'V1GroupVersionForDiscovery', 'server_address_by_client_cid_rs': 'list[V1ServerAddressByClientCIDR]', 'versions': 'list[V1GroupVersionForDiscovery]' } attribute_map = { 'api_version': 'apiVersion', 'kind': 'kind', 'name': 'name', 'preferred_version': 'preferredVersion', 'server_address_by_client_cid_rs': 'serverAddressByClientCIDRs', 'versions': 'versions' } def __init__(self, api_version=None, kind=None, name=None, preferred_version=None, server_address_by_client_cid_rs=None, versions=None): # noqa: E501 """V1APIGroup - a model defined in Swagger""" # noqa: E501 self._api_version = None self._kind = None self._name = None self._preferred_version = None self._server_address_by_client_cid_rs = None self._versions = None self.discriminator = None if api_version is not None: self.api_version = api_version if kind is not None: self.kind = kind self.name = name if preferred_version is not None: self.preferred_version = preferred_version self.server_address_by_client_cid_rs = server_address_by_client_cid_rs self.versions = versions @property def api_version(self): """Gets the api_version of this V1APIGroup. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1APIGroup. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1APIGroup. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1APIGroup. # noqa: E501 :type: str """ self._api_version = api_version @property def kind(self): """Gets the kind of this V1APIGroup. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1APIGroup. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1APIGroup. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1APIGroup. # noqa: E501 :type: str """ self._kind = kind @property def name(self): """Gets the name of this V1APIGroup. # noqa: E501 name is the name of the group. # noqa: E501 :return: The name of this V1APIGroup. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this V1APIGroup. name is the name of the group. # noqa: E501 :param name: The name of this V1APIGroup. # noqa: E501 :type: str """ if name is None: raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def preferred_version(self): """Gets the preferred_version of this V1APIGroup. # noqa: E501 preferredVersion is the version preferred by the API server, which probably is the storage version. # noqa: E501 :return: The preferred_version of this V1APIGroup. # noqa: E501 :rtype: V1GroupVersionForDiscovery """ return self._preferred_version @preferred_version.setter def preferred_version(self, preferred_version): """Sets the preferred_version of this V1APIGroup. preferredVersion is the version preferred by the API server, which probably is the storage version. # noqa: E501 :param preferred_version: The preferred_version of this V1APIGroup. # noqa: E501 :type: V1GroupVersionForDiscovery """ self._preferred_version = preferred_version @property def server_address_by_client_cid_rs(self): """Gets the server_address_by_client_cid_rs of this V1APIGroup. # noqa: E501 a map of client CIDR to server address that is serving this group. This is to help clients reach servers in the most network-efficient way possible. Clients can use the appropriate server address as per the CIDR that they match. In case of multiple matches, clients should use the longest matching CIDR. The server returns only those CIDRs that it thinks that the client can match. For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP. Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP. # noqa: E501 :return: The server_address_by_client_cid_rs of this V1APIGroup. # noqa: E501 :rtype: list[V1ServerAddressByClientCIDR] """ return self._server_address_by_client_cid_rs @server_address_by_client_cid_rs.setter def server_address_by_client_cid_rs(self, server_address_by_client_cid_rs): """Sets the server_address_by_client_cid_rs of this V1APIGroup. a map of client CIDR to server address that is serving this group. This is to help clients reach servers in the most network-efficient way possible. Clients can use the appropriate server address as per the CIDR that they match. In case of multiple matches, clients should use the longest matching CIDR. The server returns only those CIDRs that it thinks that the client can match. For example: the master will return an internal IP CIDR only, if the client reaches the server using an internal IP. Server looks at X-Forwarded-For header or X-Real-Ip header or request.RemoteAddr (in that order) to get the client IP. # noqa: E501 :param server_address_by_client_cid_rs: The server_address_by_client_cid_rs of this V1APIGroup. # noqa: E501 :type: list[V1ServerAddressByClientCIDR] """ if server_address_by_client_cid_rs is None: raise ValueError("Invalid value for `server_address_by_client_cid_rs`, must not be `None`") # noqa: E501 self._server_address_by_client_cid_rs = server_address_by_client_cid_rs @property def versions(self): """Gets the versions of this V1APIGroup. # noqa: E501 versions are the versions supported in this group. # noqa: E501 :return: The versions of this V1APIGroup. # noqa: E501 :rtype: list[V1GroupVersionForDiscovery] """ return self._versions @versions.setter def versions(self, versions): """Sets the versions of this V1APIGroup. versions are the versions supported in this group. # noqa: E501 :param versions: The versions of this V1APIGroup. # noqa: E501 :type: list[V1GroupVersionForDiscovery] """ if versions is None: raise ValueError("Invalid value for `versions`, must not be `None`") # noqa: E501 self._versions = versions def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1APIGroup): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "andy@rstudio.com" ]
andy@rstudio.com
4091a90290709e34b556d9ffc2b3d64e5efac4d3
d31417af94c4b5b55be931b7d057d1a487fbbf50
/newspaper_project/articles/admin.py
18df7879786bafea02acd0d65d4ccd40b5021fdd
[]
no_license
masayamatu/django-newspaper-app
ebd17737959bd5917c232bcbb99b3b9ffddc99ff
4aad35b09dd51bae3c2b0a6da8ac2f249b42a3d0
refs/heads/master
2023-01-10T19:29:37.144887
2020-11-01T03:53:14
2020-11-01T03:53:14
309,019,327
0
0
null
null
null
null
UTF-8
Python
false
false
319
py
from django.contrib import admin from .models import Article,Comment class CommentInline(admin.StackedInline): model = Comment extra = 0 class ArticleAdmin(admin.ModelAdmin): inlines = [ CommentInline, ] admin.site.register(Article) admin.site.register(Comment) # Register your models here.
[ "m.masa1104@outlook.jp" ]
m.masa1104@outlook.jp
6eb415507e1387c599338135ef762cab2f9d1cc1
5cedadbcc0561edb4db13b709c0afddc5a206b6e
/modules/tweety.py
22b7929c9a80f49a8671231ce932be413d7d4277
[]
no_license
harryd/Boteh
1fdddf4e83dce7d2b5b07ba119a07f27a1533f17
38cbf1e54c76a674d23032da01b19ededed24ac3
refs/heads/master
2020-04-06T07:07:09.997641
2011-05-12T20:13:38
2011-05-12T20:13:38
1,740,961
2
0
null
null
null
null
UTF-8
Python
false
false
890
py
import twitter import urllib def getpost_clean(user,c_key,c_secret,a_key,a_secret): api = twitter.Api(consumer_key=c_key, consumer_secret=c_secret, access_token_key=a_key, access_token_secret=a_secret) statuses = api.GetUserTimeline(user) return [s.text for s in statuses] def getpost(user): api = twitter.Api(consumer_key=c_key, consumer_secret=c_secret, access_token_key=a_key, access_token_secret=a_secret) statuses = api.GetUserTimeline() return statuses def getfriends(user): userems = api.GetFriends(user) return userems #print [u.name for u in users] def twitterx(input,ck,cs,ak,asx): #api = twitter.Api(consumer_key=c_key, consumer_secret=c_secret, access_token_key=a_key, access_token_secret=a_secret) user = input x = getpost_clean(user,ck,cs,ak,asx) link1 = "http://twitter.com/" link2 = link1+user sayer = 'Latest Tweet: "'+x[0]+'" ['+link2+']' return sayer
[ "b1naryth1ef@gmail.com" ]
b1naryth1ef@gmail.com
e24457a4ef65eef362c97665ea32d700f6822765
5819ce30b9aa2fe6b520d654670af56680676469
/01_code/prj197_chessGame.py
f7597ce48e8e8eabd6d65c98935a0047db9fdec7
[]
no_license
bendell02/nowCoder
e54b87d83f71c441f3df6cb5501dccc6993df533
1f7cc7788c6827bef1734414743e45f317a11991
refs/heads/master
2021-01-17T19:21:30.715814
2019-07-25T12:04:06
2019-07-25T12:04:06
58,054,963
0
0
null
null
null
null
UTF-8
Python
false
false
1,428
py
#!/usr/bin/python #-*- coding:utf-8 -*- #Author: Ben # 按照 牛客673854 的思路写得 import Queue chessSize = 6 direction = [[-1, 0], [1, 0], [0, -1], [0, 1]] class Point: def __init__(self, x, y, s): self.x = x self.y = y self.s = s def BFS(cost, chess, sx, sy): cost[sx][sy][1] = 0 q = Queue.Queue() q.put(Point(sx, sy, 1)) while not q.empty(): now = q.get() for i in range(4): nx = now.x + direction[i][0] ny = now.y + direction[i][1] if (nx<0 or nx>=chessSize or ny<0 or ny>=chessSize): continue tempCost = chess[nx][ny]*now.s tempState = (tempCost%4) + 1 if cost[nx][ny][tempState]==-1 or cost[nx][ny][tempState]>cost[now.x][now.y][now.s]+tempCost: q.put(Point(nx, ny, tempState)) cost[nx][ny][tempState] = cost[now.x][now.y][now.s]+tempCost N = input() for n in range(N): chess = [0]*chessSize for i in range(chessSize): chess[i] = map(int, raw_input().split()) cost = [[[-1 for s in range(5)] for col in range(chessSize+1)] for row in range(chessSize+1)] sx, sy, ex, ey = map(int, raw_input().split()) BFS(cost, chess, sx, sy) rlt = -1 for i in range(1, 5): if cost[ex][ey][i] != -1: if rlt==-1 or rlt>cost[ex][ey][i]: rlt = cost[ex][ey][i] print rlt
[ "1203029076@qq.com" ]
1203029076@qq.com
9a5283934e3371fe8b848b1b2777b3d8943216da
a5747577f1f4b38823f138ec0fbb34a0380cd673
/16/sig_jecr/analysis.py
33c3bc602a8201f897082773665ca19b3800080d
[]
no_license
xdlyu/fullRunII_ntuple
346fc1da4cec9da4c404aa1ec0bfdaece6df1526
aa00ca4ce15ae050c3096d7af779de44fc59141e
refs/heads/master
2020-08-03T07:52:29.544528
2020-01-22T14:18:12
2020-01-22T14:18:12
211,673,739
0
3
null
null
null
null
UTF-8
Python
false
false
32,777
py
import FWCore.ParameterSet.Config as cms process = cms.Process( "TEST" ) #process.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(True)) process.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(True),allowUnscheduled=cms.untracked.bool(True)) #, # SkipEvent = cms.untracked.vstring('ProductNotFound')) filterMode = False # True ######## Sequence settings ########## corrJetsOnTheFly = True runOnMC = True runOnSig = True DOHLTFILTERS = True #useJSON = not (runOnMC) #JSONfile = 'Cert_246908-258750_13TeV_PromptReco_Collisions15_25ns_JSON.txt' #****************************************************************************************************# #process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff') process.load('Configuration.StandardSequences.GeometryRecoDB_cff') process.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_condDBv2_cff') from Configuration.AlCa.GlobalTag import GlobalTag if runOnMC: process.GlobalTag.globaltag = '80X_mcRun2_asymptotic_2016_TrancheIV_v8'#'MCRUN2_74_V9::All' #process.GlobalTag.globaltag = '94X_mc2017_realistic_v14'#'MCRUN2_74_V9::All' elif not(runOnMC): process.GlobalTag.globaltag = '80X_dataRun2_2016SeptRepro_v7' hltFiltersProcessName = 'RECO' if runOnMC: hltFiltersProcessName = 'PAT' #'RECO' #if DOHLTFILTERS and not(runOnMC): process.load('CommonTools.RecoAlgos.HBHENoiseFilterResultProducer_cfi') process.HBHENoiseFilterResultProducer.minZeros = cms.int32(99999) process.HBHENoiseFilterResultProducer.IgnoreTS4TS5ifJetInLowBVRegion=cms.bool(False) process.HBHENoiseFilterResultProducer.defaultDecision = cms.string("HBHENoiseFilterResultRun2Loose") process.ApplyBaselineHBHENoiseFilter = cms.EDFilter('BooleanFlagFilter', inputLabel = cms.InputTag('HBHENoiseFilterResultProducer','HBHENoiseFilterResult'), reverseDecision = cms.bool(False) ) process.ApplyBaselineHBHEIsoNoiseFilter = cms.EDFilter('BooleanFlagFilter', inputLabel = cms.InputTag('HBHENoiseFilterResultProducer','HBHEIsoNoiseFilterResult'), reverseDecision = cms.bool(False) ) ######### read JSON file for data ########## '''if not(runOnMC) and useJSON: import FWCore.PythonUtilities.LumiList as LumiList import FWCore.ParameterSet.Types as CfgTypes process.source.lumisToProcess = CfgTypes.untracked(CfgTypes.VLuminosityBlockRange()) myLumis = LumiList.LumiList(filename = JSONfile).getCMSSWString().split(',') process.source.lumisToProcess.extend(myLumis) ''' # --------------------------------------------------------- # DeepAK8: set up TransientTrackBuilder process.load('Configuration.StandardSequences.MagneticField_cff') process.TransientTrackBuilderESProducer = cms.ESProducer("TransientTrackBuilderESProducer", ComponentName=cms.string('TransientTrackBuilder') ) # --------------------------------------------------------- ####### Redo Jet clustering sequence ########## from RecoJets.Configuration.RecoPFJets_cff import ak4PFJetsCHS, ak8PFJetsCHS, ak8PFJetsCHSPruned, ak8PFJetsCHSSoftDrop, ak8PFJetsCHSPrunedMass, ak8PFJetsCHSSoftDropMass# , ak8PFJetsCSTrimmed, ak8PFJetsCSFiltered, ak8PFJetsCHSFilteredMass, ak8PFJetsCHSTrimmedMass from CommonTools.PileupAlgos.Puppi_cff import puppi process.puppi = puppi.clone() process.puppi.useExistingWeights = True process.puppi.candName = cms.InputTag('packedPFCandidates') process.puppi.vertexName = cms.InputTag('offlineSlimmedPrimaryVertices') process.ak8PFJetsCHS = ak8PFJetsCHS.clone( src = 'puppi', jetPtMin = 100.0 ) process.ak8PFJetsCHSPruned = ak8PFJetsCHSPruned.clone( src = 'puppi', jetPtMin = 100.0 ) process.ak8PFJetsCHSPrunedMass = ak8PFJetsCHSPrunedMass.clone() process.ak8PFJetsCHSSoftDrop = ak8PFJetsCHSSoftDrop.clone( src = 'puppi', jetPtMin = 100.0 ) process.ak8PFJetsCHSSoftDropMass = ak8PFJetsCHSSoftDropMass.clone() process.NjettinessAK8 = cms.EDProducer("NjettinessAdder", src = cms.InputTag("ak8PFJetsCHS"), Njets = cms.vuint32(1, 2, 3, 4), # variables for measure definition : measureDefinition = cms.uint32( 0 ), # CMS default is normalized measure beta = cms.double(1.0), # CMS default is 1 R0 = cms.double( 0.8 ), # CMS default is jet cone size Rcutoff = cms.double( 999.0), # not used by default # variables for axes definition : axesDefinition = cms.uint32( 6 ), # CMS default is 1-pass KT axes nPass = cms.int32(0), # not used by default akAxesR0 = cms.double(-999.0) # not used by default ) process.substructureSequence = cms.Sequence() process.substructureSequence+=process.puppi process.substructureSequence+=process.ak8PFJetsCHS process.substructureSequence+=process.NjettinessAK8 process.substructureSequence+=process.ak8PFJetsCHSPruned process.substructureSequence+=process.ak8PFJetsCHSPrunedMass process.substructureSequence+=process.ak8PFJetsCHSSoftDrop process.substructureSequence+=process.ak8PFJetsCHSSoftDropMass ####### Redo pat jets sequence ########## process.redoPatJets = cms.Sequence() process.redoPrunedPatJets = cms.Sequence() process.redoSoftDropPatJets = cms.Sequence() from ExoDiBosonResonances.EDBRJets.redoPatJets_cff import patJetCorrFactorsAK8, patJetsAK8, selectedPatJetsAK8 # Redo pat jets from ak8PFJetsCHS process.patJetCorrFactorsAK8 = patJetCorrFactorsAK8.clone( src = 'ak8PFJetsCHS' ) process.patJetsAK8 = patJetsAK8.clone( jetSource = 'ak8PFJetsCHS' ) process.patJetsAK8.userData.userFloats.src = [ cms.InputTag("ak8PFJetsCHSPrunedMass"), cms.InputTag("ak8PFJetsCHSSoftDropMass"), cms.InputTag("NjettinessAK8:tau1"), cms.InputTag("NjettinessAK8:tau2"), cms.InputTag("NjettinessAK8:tau3"),cms.InputTag("NjettinessAK8:tau4")] process.patJetsAK8.jetCorrFactorsSource = cms.VInputTag( cms.InputTag("patJetCorrFactorsAK8") ) process.selectedPatJetsAK8 = selectedPatJetsAK8.clone( cut = cms.string('pt > 100') ) process.redoPatJets+=process.patJetCorrFactorsAK8 process.redoPatJets+=process.patJetsAK8 process.redoPatJets+=process.selectedPatJetsAK8 # Redo pat jets ak8PFJetsCHSPruned process.patJetCorrFactorsAK8Pruned = patJetCorrFactorsAK8.clone( src = 'ak8PFJetsCHSPruned' ) process.patJetsAK8Pruned = patJetsAK8.clone( jetSource = 'ak8PFJetsCHSPruned' ) process.patJetsAK8Pruned.userData.userFloats.src = [ "" ] #process.patJetsAK8Pruned.userData.userFloats =cms.PSet(src = cms.VInputTag("")) process.patJetsAK8Pruned.jetCorrFactorsSource = cms.VInputTag( cms.InputTag("patJetCorrFactorsAK8Pruned") ) process.selectedPatJetsAK8Pruned = selectedPatJetsAK8.clone(cut = 'pt > 100', src = "patJetsAK8Pruned") process.redoPrunedPatJets+=process.patJetCorrFactorsAK8Pruned process.redoPrunedPatJets+=process.patJetsAK8Pruned process.redoPrunedPatJets+=process.selectedPatJetsAK8Pruned # Redo pat jets ak8PFJetsCHSSoftDrop process.patJetCorrFactorsAK8Softdrop = patJetCorrFactorsAK8.clone( src = 'ak8PFJetsCHSSoftDrop' ) process.patJetsAK8Softdrop = patJetsAK8.clone( jetSource = 'ak8PFJetsCHSSoftDrop' ) process.patJetsAK8Softdrop.userData.userFloats.src = [ "" ] #process.patJetsAK8Softdrop.userData.userFloats =cms.PSet(src = cms.VInputTag("")) process.patJetsAK8Softdrop.jetCorrFactorsSource = cms.VInputTag( cms.InputTag("patJetCorrFactorsAK8Softdrop") ) process.selectedPatJetsAK8Softdrop = selectedPatJetsAK8.clone(cut = 'pt > 100', src = "patJetsAK8Softdrop") from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection ## PATify soft drop subjets addJetCollection( process, labelName = 'AK8SoftDropSubjets', jetSource = cms.InputTag('ak8PFJetsCHSSoftDrop','SubJets'), algo = 'ak', # needed for subjet flavor clustering rParam = 0.8, # needed for subjet flavor clustering getJetMCFlavour = False, pvSource = cms.InputTag( 'offlineSlimmedPrimaryVertices' ), genJetCollection = cms.InputTag('slimmedGenJets'), genParticles = cms.InputTag( 'prunedGenParticles' ), btagDiscriminators = ['None'], jetCorrections = ('AK4PFPuppi', ['L2Relative', 'L3Absolute'], 'None'), # explicitJTA = True, # needed for subjet b tagging # svClustering = True, # needed for subjet b tagging # fatJets=cms.InputTag('ak8PFJetsCHS'), # needed for subjet flavor clustering # groomedFatJets=cms.InputTag('ak8PFJetsCHSSoftDrop') # needed for subjet flavor clustering ) process.selectedPatJetsAK8SoftDropPacked = cms.EDProducer("BoostedJetMerger", jetSrc = cms.InputTag("selectedPatJetsAK8Softdrop"), subjetSrc = cms.InputTag("selectedPatJetsAK8SoftDropSubjets") ) process.redoSoftDropPatJets+=process.patJetCorrFactorsAK8Softdrop process.redoSoftDropPatJets+=process.patJetsAK8Softdrop process.redoSoftDropPatJets+=process.selectedPatJetsAK8Softdrop option = 'RECO' process.load("ExoDiBosonResonances.EDBRCommon.goodMuons_cff") process.load("ExoDiBosonResonances.EDBRCommon.goodElectrons_cff") process.load("ExoDiBosonResonances.EDBRCommon.goodJets_cff") process.load("ExoDiBosonResonances.EDBRCommon.leptonicW_cff") process.load("ExoDiBosonResonances.EDBRCommon.hadronicW_cff") process.load("ExoDiBosonResonances.EDBRCommon.goodPuppi_cff") if option == 'RECO': process.goodMuons.src = "slimmedMuons" process.goodElectrons.src = "slimmedElectrons" process.goodJets.src = "slimmedJetsAK8" # process.goodJets.src = "selectedPatJetsAK8" process.Wtoenu.MET = "slimmedMETs" process.Wtomunu.MET = "slimmedMETs" #process.goodPuppi.src = "selectedPatJetsAK8" process.goodPuppi.src = "JetUserData" process.goodOfflinePrimaryVertex = cms.EDFilter("VertexSelector", src = cms.InputTag("offlineSlimmedPrimaryVertices"), cut = cms.string("chi2!=0 && ndof >= 4.0 && abs(z) <= 24.0 && abs(position.Rho) <= 2.0"), filter = cms.bool(True) ) if option == 'RECO': process.hadronicV.cut = ' ' if option == 'GEN': process.hadronicV.cut = ' ' WBOSONCUT = "pt > 200.0" process.leptonicVSelector = cms.EDFilter("CandViewSelector", src = cms.InputTag("leptonicV"), cut = cms.string( WBOSONCUT ), filter = cms.bool(True) ) process.leptonicVFilter = cms.EDFilter("CandViewCountFilter", src = cms.InputTag("leptonicV"), minNumber = cms.uint32(1), filter = cms.bool(True) ) process.hadronicVFilter = cms.EDFilter("CandViewCountFilter", src = cms.InputTag("hadronicV"), minNumber = cms.uint32(1), filter = cms.bool(True) ) process.graviton = cms.EDProducer("CandViewCombiner", decay = cms.string("leptonicV hadronicV"), checkCharge = cms.bool(False), cut = cms.string("mass > 180"), roles = cms.vstring('leptonicV', 'hadronicV'), ) process.gravitonFilter = cms.EDFilter("CandViewCountFilter", src = cms.InputTag("graviton"), minNumber = cms.uint32(1), filter = cms.bool(True) ) from PhysicsTools.SelectorUtils.tools.vid_id_tools import * switchOnVIDElectronIdProducer(process, DataFormat.MiniAOD) my_id_modules = ['RecoEgamma.ElectronIdentification.Identification.heepElectronID_HEEPV70_cff'] for idmod in my_id_modules: setupAllVIDIdsInModule(process,idmod,setupVIDElectronSelection) process.leptonSequence = cms.Sequence(process.muSequence + process.egmGsfElectronIDSequence*process.eleSequence + process.leptonicVSequence + process.leptonicVSelector + process.leptonicVFilter ) process.jetSequence = cms.Sequence(process.substructureSequence + process.redoPatJets + process.redoPrunedPatJets+ process.redoSoftDropPatJets+ process.fatJetsSequence + process.fatPuppiSequence+ process.hadronicV + process.hadronicVFilter) process.gravitonSequence = cms.Sequence(process.graviton + process.gravitonFilter) if filterMode == False: process.goodOfflinePrimaryVertex.filter = False process.Wtomunu.cut = '' process.Wtoenu.cut = '' process.leptonicVSelector.filter = False process.leptonicVSelector.cut = '' process.hadronicV.cut = '' process.graviton.cut = '' process.leptonicVFilter.minNumber = 0 process.hadronicVFilter.minNumber = 0 process.gravitonFilter.minNumber = 0 process.load('RecoMET.METFilters.BadPFMuonFilter_cfi') process.load("RecoMET.METFilters.BadChargedCandidateFilter_cfi") process.BadPFMuonFilter.muons = cms.InputTag("slimmedMuons") process.BadPFMuonFilter.PFCandidates = cms.InputTag("packedPFCandidates") process.BadChargedCandidateFilter.muons = cms.InputTag("slimmedMuons") process.BadChargedCandidateFilter.PFCandidates = cms.InputTag("packedPFCandidates") process.metfilterSequence = cms.Sequence(process.BadPFMuonFilter+process.BadChargedCandidateFilter) ######### JEC ######## METS = "slimmedMETs" jetsAK8 = "slimmedJetsAK8" jetsAK8pruned = "slimmedJetsAK8" jetsAK8softdrop = "slimmedJetsAK8" jetsAK8puppi = "cleanPuppi" if runOnMC: jecLevelsAK8chs = [ 'Summer16_23Sep2016V4_MC_L1FastJet_AK8PFchs.txt', 'Summer16_23Sep2016V4_MC_L2Relative_AK8PFchs.txt', 'Summer16_23Sep2016V4_MC_L3Absolute_AK8PFchs.txt' ] jecLevelsAK8chsGroomed = [ 'Summer16_23Sep2016V4_MC_L2Relative_AK8PFchs.txt', 'Summer16_23Sep2016V4_MC_L3Absolute_AK8PFchs.txt' ] jecLevelsAK8puppi = [ 'Summer16_23Sep2016V4_MC_L1FastJet_AK8PFPuppi.txt', 'Summer16_23Sep2016V4_MC_L2Relative_AK8PFPuppi.txt', 'Summer16_23Sep2016V4_MC_L3Absolute_AK8PFPuppi.txt' ] jecLevelsAK8puppiGroomed = [ 'Summer16_23Sep2016V4_MC_L2Relative_AK8PFPuppi.txt', 'Summer16_23Sep2016V4_MC_L3Absolute_AK8PFPuppi.txt' ] BjecLevelsAK4chs = [ 'Summer16_23Sep2016V4_MC_L1FastJet_AK4PFPuppi.txt', 'Summer16_23Sep2016V4_MC_L2Relative_AK4PFPuppi.txt', 'Summer16_23Sep2016V4_MC_L3Absolute_AK4PFPuppi.txt' ] jecLevelsAK4chs = [ 'Summer16_23Sep2016V4_MC_L1FastJet_AK4PFchs.txt', 'Summer16_23Sep2016V4_MC_L2Relative_AK4PFchs.txt', 'Summer16_23Sep2016V4_MC_L3Absolute_AK4PFchs.txt' ] else: jecLevelsAK8chs = [ 'Summer16_23Sep2016BCDV4_DATA_L1FastJet_AK8PFchs.txt', 'Summer16_23Sep2016BCDV4_DATA_L2Relative_AK8PFchs.txt', 'Summer16_23Sep2016BCDV4_DATA_L3Absolute_AK8PFchs.txt', 'Summer16_23Sep2016BCDV4_DATA_L2L3Residual_AK8PFchs.txt' ] jecLevelsAK8chsGroomed = [ 'Summer16_23Sep2016BCDV4_DATA_L2Relative_AK8PFchs.txt', 'Summer16_23Sep2016BCDV4_DATA_L3Absolute_AK8PFchs.txt', 'Summer16_23Sep2016BCDV4_DATA_L2L3Residual_AK8PFchs.txt' ] jecLevelsAK8puppi = [ 'Summer16_23Sep2016BCDV4_DATA_L1FastJet_AK8PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L2Relative_AK8PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L3Absolute_AK8PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L2L3Residual_AK8PFPuppi.txt' ] jecLevelsAK8puppiGroomed = [ 'Summer16_23Sep2016BCDV4_DATA_L2Relative_AK8PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L3Absolute_AK8PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L2L3Residual_AK8PFPuppi.txt' ] BjecLevelsAK4chs = [ 'Summer16_23Sep2016BCDV4_DATA_L1FastJet_AK4PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L2Relative_AK4PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L3Absolute_AK4PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L2L3Residual_AK4PFPuppi.txt' ] jecLevelsAK4chs = [ 'Summer16_23Sep2016BCDV4_DATA_L1FastJet_AK4PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L2Relative_AK4PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L3Absolute_AK4PFPuppi.txt', 'Summer16_23Sep2016BCDV4_DATA_L2L3Residual_AK4PFPuppi.txt' ] #jLabel = jetsAK8puppi jLabel = "slimmedJetsAK8" jetAlgo = 'AK8PFPuppi' jer_era = "Summer16_23Sep2016V4_MC" triggerResultsLabel = "TriggerResults" triggerSummaryLabel = "hltTriggerSummaryAOD" hltProcess = "HLT" process.JetUserData = cms.EDProducer( 'JetUserData', jetLabel = cms.InputTag(jLabel), rho = cms.InputTag("fixedGridRhoFastjetAll"), coneSize = cms.double(0.8), getJERFromTxt = cms.bool(False), jetCorrLabel = cms.string(jetAlgo), jerLabel = cms.string(jetAlgo), resolutionsFile = cms.string(jer_era+'_PtResolution_'+jetAlgo+'.txt'), scaleFactorsFile = cms.string(jer_era+'_SF_'+jetAlgo+'.txt'), ### TTRIGGER ### triggerResults = cms.InputTag(triggerResultsLabel,"",hltProcess), triggerSummary = cms.InputTag(triggerSummaryLabel,"",hltProcess), hltJetFilter = cms.InputTag("hltPFHT"), hltPath = cms.string("HLT_PFHT800"), hlt2reco_deltaRmax = cms.double(0.2), candSVTagInfos = cms.string("pfInclusiveSecondaryVertexFinder"), jecAk8chsPayloadNames_jetUserdata = cms.vstring( jecLevelsAK8puppi ), vertex_jetUserdata = cms.InputTag("offlineSlimmedPrimaryVertices"), ) # L1 prefiring process.prefiringweight = cms.EDProducer("L1ECALPrefiringWeightProducer", ThePhotons = cms.InputTag("slimmedPhotons"), TheJets = cms.InputTag("slimmedJets"), # L1Maps = cms.string(relBase+"/src/L1Prefiring/EventWeightProducer/files/L1PrefiringMaps_new.root"), # L1Maps = cms.string("L1PrefiringMaps_new.root"), # update this line with the location of this file L1Maps = cms.string("L1PrefiringMaps_new.root"), DataEra = cms.string("2016BtoH"), #Use 2016BtoH for 2016 UseJetEMPt = cms.bool(False), #can be set to true to use jet prefiring maps parametrized vs pt(em) instead of pt PrefiringRateSystematicUncty = cms.double(0.2) #Minimum relative prefiring uncty per object ) process.treeDumper = cms.EDAnalyzer("EDBRTreeMaker", originalNEvents = cms.int32(1), crossSectionPb = cms.double(1), targetLumiInvPb = cms.double(1.0), EDBRChannel = cms.string("VW_CHANNEL"), lhe = cms.InputTag("externalLHEProducer"), isGen = cms.bool(False), isJEC = cms.bool(corrJetsOnTheFly), RunOnMC = cms.bool(runOnMC), RunOnSig = cms.bool(runOnSig), generator = cms.InputTag("generator"), genSrc = cms.InputTag("prunedGenParticles"), pileup = cms.InputTag("slimmedAddPileupInfo"), leptonicVSrc = cms.InputTag("leptonicV"), gravitonSrc = cms.InputTag("graviton"), t1jetSrc_user = cms.InputTag("JetUserData"), looseMuonSrc = cms.InputTag("looseMuons"), looseElectronSrc = cms.InputTag("looseElectrons"), goodMuSrc = cms.InputTag("goodMuons"), MuSrc = cms.InputTag("slimmedMuons"), EleSrc = cms.InputTag("slimmedElectrons"), t1muSrc = cms.InputTag("slimmedMuons"), metSrc = cms.InputTag("slimmedMETs"), mets = cms.InputTag(METS), #ak4jetsSrc = cms.InputTag("cleanAK4Jets"), ak4jetsSrc = cms.InputTag("cleanPuppiAK4"), hadronicVSrc = cms.InputTag("hadronicV"), hadronicVSrc_raw = cms.InputTag("slimmedJetsAK8"), hadronicVSoftDropSrc = cms.InputTag("selectedPatJetsAK8SoftDropPacked"), jets = cms.InputTag("slimmedJets"), fatjets = cms.InputTag(jetsAK8), ak8JetSrc = cms.InputTag(jetsAK8), prunedjets = cms.InputTag(jetsAK8pruned), softdropjets = cms.InputTag(jetsAK8softdrop), puppijets = cms.InputTag(jetsAK8puppi), #puppijets = cms.InputTag("JetUserData"), jecAK8chsPayloadNames = cms.vstring( jecLevelsAK8chs ), jecAK8chsPayloadNamesGroomed = cms.vstring( jecLevelsAK8chsGroomed ), jecAK4chsPayloadNames = cms.vstring( jecLevelsAK4chs ), BjecAK4chsPayloadNames = cms.vstring( BjecLevelsAK4chs ), jecAK8puppiPayloadNames = cms.vstring( jecLevelsAK8puppi ), jecAK8puppiPayloadNamesGroomed = cms.vstring( jecLevelsAK8puppiGroomed ), jecpath = cms.string(''), rho = cms.InputTag("fixedGridRhoFastjetAll"), electronIDs = cms.InputTag("heepElectronID-HEEPV50-CSA14-25ns"), muons = cms.InputTag("slimmedMuons"), vertices = cms.InputTag("offlineSlimmedPrimaryVertices"), hltToken = cms.InputTag("TriggerResults","","HLT"), elPaths1 = cms.vstring("HLT_PFMETNoMu110_PFMHTNoMu110_IDTight*"),#EXO-15-002 elPaths2 = cms.vstring("HLT_Ele27_eta2p1_WP75_Gsf_v*", "HLT_Ele27_eta2p1_WPLoose_Gsf_v*"), #B2G-15-005 elPaths3 = cms.vstring("HLT_Ele45_WPLoose_Gsf_v*"), elPaths4 = cms.vstring("HLT_Ele115_CaloIdVT_GsfTrkIdT_v*"),#("HLT_Ele35_WPLoose_Gsf_v*"), elPaths5 = cms.vstring("HLT_Ele40_WPTight_Gsf_v*"),#("HLT_Ele35_WPLoose_Gsf_v*"), #elPaths5 = cms.vstring("HLT_Ele25_WPTight_Gsf_v*"), elPaths6 = cms.vstring("HLT_Ele38_WPTight_Gsf_v*"),#("HLT_Ele25_eta2p1_WPLoose_Gsf_v*"), elPaths7 = cms.vstring("HLT_AK8PFHT700_TrimR0p1PT0p03Mass50_v*"),#("HLT_Ele25_eta2p1_WPTight_Gsf_v*"), elPaths8 = cms.vstring("HLT_Ele27_WPTight_Gsf_v*"), muPaths1 = cms.vstring("HLT_PFHT650_WideJetMJJ900DEtaJJ1p5_v*"),#EXO-15-002 muPaths2 = cms.vstring("HLT_Mu50_v*"), #B2G-15-005 muPaths3 = cms.vstring("HLT_TkMu50_v*"), #B2G-15-005 muPaths4 = cms.vstring("HLT_Mu16_eta2p1_MET30_v*", "HLT_IsoMu16_eta2p1_MET30_v*"), #MET muPaths5 = cms.vstring("HLT_PFHT800_v*"), #MET muPaths6 = cms.vstring("HLT_PFHT900_v*"), muPaths7 = cms.vstring("HLT_PFJet450_v*"), muPaths8 = cms.vstring("HLT_PFJet500_v*"), muPaths9 = cms.vstring("HLT_AK8PFJet450_v*"), muPaths10 = cms.vstring("HLT_AK8PFJet500_v*"), muPaths11 = cms.vstring("HLT_AK8PFJet360_TrimMass30_v*"),#e1,MET110,e7,m1,m5-m11,HLT_hadronic muPaths12 = cms.vstring("HLT_PFMETNoMu120_PFMHTNoMu120_IDTight_v*"), noiseFilter = cms.InputTag('TriggerResults','', hltFiltersProcessName), noiseFilterSelection_HBHENoiseFilter = cms.string('Flag_HBHENoiseFilter'), noiseFilterSelection_HBHENoiseIsoFilter = cms.string("Flag_HBHENoiseIsoFilter"), noiseFilterSelection_GlobalTightHaloFilter = cms.string('Flag_globalTightHalo2016Filter'), noiseFilterSelection_EcalDeadCellTriggerPrimitiveFilter = cms.string('Flag_EcalDeadCellTriggerPrimitiveFilter'), noiseFilterSelection_goodVertices = cms.string('Flag_goodVertices'), noiseFilterSelection_eeBadScFilter = cms.string('Flag_eeBadScFilter'), noiseFilterSelection_badMuon = cms.InputTag('BadPFMuonFilter'), noiseFilterSelection_badChargedHadron = cms.InputTag('BadChargedCandidateFilter'), ) if option=='GEN': process.treeDumper.metSrc = 'genMetTrue' process.treeDumper.isGen = True process.analysis = cms.Path(process.JetUserData + process.leptonSequence + #process.substructureSequence+ #process.redoPatJets+ #process.redoPrunedPatJets+ #process.redoSoftDropPatJets+ process.HBHENoiseFilterResultProducer+ process.ApplyBaselineHBHENoiseFilter+ process.ApplyBaselineHBHEIsoNoiseFilter+ process.jetSequence + process.metfilterSequence + process.gravitonSequence + process.prefiringweight*process.treeDumper) if option=='RECO': process.analysis.replace(process.leptonSequence, process.goodOfflinePrimaryVertex + process.leptonSequence) process.load("ExoDiBosonResonances.EDBRCommon.data.RSGravitonToWW_kMpl01_M_1000_Tune4C_13TeV_pythia8") #process.source.inputCommands = ['keep *','drop *_isolatedTracks_*_*'] process.source.fileNames = [ #'/store/data/Run2017C/SingleElectron/MINIAOD/PromptReco-v2/000/300/500/00000/C8EAB179-4D7C-E711-8CA7-02163E0144E1.root' #'/store/data/Run2017B/SingleMuon/MINIAOD/23Jun2017-v1/120000/78711365-0B59-E711-B9E9-0025904B0FC0.root' #'/store/data/Run2016D/SingleMuon/MINIAOD/23Sep2016-v1/60000/7E24A014-6E9D-E611-B984-F04DA2752644.root' #"/store/mc/RunIISummer16MiniAODv2/BulkGravToWWToWlepWhad_narrow_M-2000_13TeV-madgraph/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/80000/F6EF3B47-1AB7-E611-994D-0025904C7A54.root" #'/store/mc/RunIISummer16MiniAODv2/QCD_HT1000to1500_BGenFilter_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/80000/2C3623F9-7FBE-E611-AC00-002590E7D7DE.root' #'file:EXO-RunIISummer16MiniAODv2-07193.root' #'file:/eos/cms/store/user/lewang/WWW-v1/crab_WWW-MA/171024_113209/0000/EXO-RunIISummer16MiniAODv2-07193_19.root' #'/store/mc/RunIIFall17MiniAODv2/WkkToWRadionToWWW_M4000-R0-5_TuneCP5_13TeV-madgraph/MINIAODSIM/PU2017_12Apr2018_94X_mc2017_realistic_v14-v2/70000/F2D0E7A2-C54D-E811-B022-FA163E1445BD.root' #'file:/eos/cms/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/xulyu/WWW/WWW-v1-3000/crab_WWW-MA-3000/180715_150422/0000/EXO-RunIISummer16MiniAODv2-07193_95.root', #'file:/eos/cms/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/xulyu/WWW/WWW-v1-3000/crab_WWW-MA-3000/180715_150422/0000/EXO-RunIISummer16MiniAODv2-07193_96.root', #'file:/eos/cms/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/xulyu/WWW/WWW-v1-3000/crab_WWW-MA-3000/180715_150422/0000/EXO-RunIISummer16MiniAODv2-07193_97.root', #'file:/eos/cms/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/xulyu/WWW/WWW-v1-3000/crab_WWW-MA-3000/180715_150422/0000/EXO-RunIISummer16MiniAODv2-07193_98.root', #'file:/eos/cms/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/xulyu/WWW/WWW-v1-3000/crab_WWW-MA-3000/180715_150422/0000/EXO-RunIISummer16MiniAODv2-07193_99.root', #'file:/eos/cms/store/user/xulyu/EXO-RunIISummer16MiniAODv2-07193_1.root', #'/store/mc/RunIISummer16MiniAODv2/WJetsToLNu_HT-800To1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1/120000/FC517460-77BE-E611-940D-90B11C2801E1.root' '/store/mc/RunIISummer16MiniAODv2/WkkToWRadionToWWW_M1500-R0-9-TuneCUEP8M1_13TeV-madgraph/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/60000/D20E05D7-5FC6-E811-AA1E-0CC47A5FBE21.root' #'file:/afs/cern.ch/user/x/xulyu/work/private/Summer2017/VVV/chain/step4/CMSSW_8_0_21/src/EXO-RunIISummer16MiniAODv2-07193.root' #'/store/mc/RunIISummer16MiniAODv2/WJetsToLNu_HT-800To1200_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/MINIAODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1/120000/FC517460-77BE-E611-940D-90B11C2801E1.root' ] process.maxEvents.input = 1000 process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger.cerr.FwkReport.reportEvery = 1000000 process.MessageLogger.cerr.FwkReport.limit = 99999999 process.TFileService = cms.Service("TFileService", fileName = cms.string("RStreeEDBR_pickup.root") )
[ "XXX@cern.ch" ]
XXX@cern.ch
4941ab29e5f3fd24693b2873e422eef222697ebf
994b1e91d0a7a0c2b2cb8122ed9d48e47dfea85b
/Cameron_Marshall/django/survey/apps/survey/urls.py
9e206806abce14f85334f62ecb8dc32d323bdb07
[]
no_license
cmarsh940/python_july_2017
1d5d01459e5a7f5a5d16e83d5e75b5407bb33eb5
a569e48e8087ee591cbc4956c98d12d926d1db0f
refs/heads/master
2020-06-27T03:46:54.542984
2017-07-20T17:19:52
2017-07-20T17:19:52
97,045,055
0
0
null
2017-07-12T19:32:04
2017-07-12T19:32:04
null
UTF-8
Python
false
false
185
py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index), url(r'^handle_survey$', views.handle_survey), url(r'^result$', views.result) ]
[ "cam.marshall940@yahoo.com" ]
cam.marshall940@yahoo.com
f782445dc6543a9b0c2b933d85039dfb7a9ed1a4
9c44c1b431abcdb1f7b85039dfddc6e6ae21e1c0
/ZanataRpm.py
a19cecc8b80fcf3a49615c9c2cab9e5f2d6544a1
[]
no_license
zanata/zanata-scripts
b996956e0f3d75d631fa6833463b701ce59db5d9
0cc14fd346a94b412409d339d3f2728b0c5bf875
refs/heads/master
2021-04-09T16:43:31.403084
2018-09-05T04:10:41
2018-09-05T04:10:41
3,624,269
2
4
null
2018-09-05T04:10:42
2012-03-05T05:41:48
Shell
UTF-8
Python
false
false
5,364
py
#!/usr/bin/env python2 # encoding: utf-8 """ ZanataRpm -- RPM manipulate ZanataRpm mainpulates RPM and spec files, such as version bump. It defines classes_and_methods @author: Ding-Yi Chen @copyright: 2018 Red Hat Asia Pacific. All rights reserved. @license: LGPLv2+ @contact: dchen@redhat.com """ from __future__ import absolute_import, division, print_function import datetime import locale import logging import re import os import sys from ZanataArgParser import ZanataArgParser # pylint: disable=import-error from ZanataFunctions import CLIException try: from typing import List, Any # noqa: F401 # pylint: disable=unused-import except ImportError: sys.stderr.write("python typing module is not installed" + os.linesep) locale.setlocale(locale.LC_ALL, 'C') class RpmSpec(object): """ RPM Spec """ # We only interested in these tags TAGS = ['Name', 'Version', 'Release'] def __init__(self, **kwargs): # type (Any) -> None """ Constructor """ for v in kwargs: setattr(self, v, kwargs.get(v)) self.content = [] def parse_spec_tag(self, line): # type (str) -> None """Parse the tag value from line if the line looks like spec tag definition, otherwise do nothing""" s = line.rstrip() matched = re.match(r"([A-Z][A-Za-z]*):\s*(.+)", s) if matched: if matched.group(1) in RpmSpec.TAGS: tag = matched.group(1) if not hasattr(self, tag): # Only use the first match setattr(self, tag, matched .group(2)) return s @classmethod def init_from_file(cls, spec_file): # type (str) -> None """Init from existing spec file Args: spec_file (str): RPM spec file Raises: OSError e: File error Returns: RpmSpec: Instance read from spec_file """ try: with open(spec_file, 'r') as in_file: self = cls() self.content = [ self.parse_spec_tag(l) for l in in_file.readlines()] except OSError as e: raise e return self def update_version(self, version): # type (str) -> bool """Update to new version Args: version (str): new version to be set """ if getattr(self, 'Version') == version: logging.warning("Spec file is already with version %s", version) return False setattr(self, 'Version', version) # Update content new_content = [] for line in self.content: matched = re.match(r"^Version:(\s*)(.+)", line) if matched: new_content.append( "Version:{}{}".format(matched.group(1), version)) continue changelog_matched = re.match("^%changelog", line) if changelog_matched: now = datetime.datetime.now().strftime("%a %b %d %Y") changelog_item = ( "* {date} {email} {version}-1\n" "- Upgrade to upstream version {version}\n".format( date=now, email=os.getenv( 'MAINTAINER_EMAIL', 'noreply@zanata.org'), version=version)) new_content.append(line) new_content.append(changelog_item) continue new_content.append(line) setattr(self, 'content', new_content) return True def write_to_file(self, spec_file): """Write the spec to file Args: spec_file (str): RPM spec file Raises: OSError e: File error """ try: with open(spec_file, 'w') as out_file: out_file.write(str(self)) except OSError as e: logging.error("Failed to write to %s", spec_file) raise e def __str__(self): return "\n".join(getattr(self, 'content')) def _parse(): parser = ZanataArgParser(__file__) parser.add_sub_command( 'update-version', [ ('--force -f', { 'action': 'store_true', 'help': 'Force overwritten'}), ('spec_file', { 'type': str, 'help': 'spec file'}), ('version', { 'type': str, 'help': 'new version'})], help=RpmSpec.__doc__) return parser.parse_all() def main(): """Run as command line program""" args = _parse() if args.sub_command == 'help': help(sys.modules[__name__]) else: if args.sub_command == 'update-version': instance = RpmSpec.init_from_file(args.spec_file) instance.update_version(args.version) instance.write_to_file(args.spec_file) else: raise CLIException("No known sub command %s" % args.sub_command) if __name__ == '__main__': main()
[ "noreply@github.com" ]
zanata.noreply@github.com
77a5ba73badb49f85b070d438eba5578e8a70322
b1beed3e97f3b6d2a29f8c101b804401e5e0fce1
/test/test_p2p_buf_matched.py
65561fd2b500736e58dd98e32f09f2f21b6c6205
[]
no_license
Mathislu/mpi4py
476cf09aa89b5b88051a048f0d599cb3d9050592
ddefbb790d14777cb322ea9007d61345f81f2099
refs/heads/master
2023-09-01T03:07:46.102593
2021-10-06T19:13:12
2021-10-06T19:13:12
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,658
py
from mpi4py import MPI import mpiunittest as unittest import arrayimpl @unittest.skipIf(MPI.MESSAGE_NULL == MPI.MESSAGE_NO_PROC, 'mpi-message') class TestMessage(unittest.TestCase): def testMessageNull(self): null = MPI.MESSAGE_NULL self.assertFalse(null) null2 = MPI.Message() self.assertEqual(null, null2) null3 = MPI.Message(null) self.assertEqual(null, null3) def testMessageNoProc(self): # noproc = MPI.MESSAGE_NO_PROC self.assertTrue(noproc) noproc.Recv(None) self.assertTrue(noproc) noproc.Irecv(None).Wait() self.assertTrue(noproc) # noproc2 = MPI.Message(MPI.MESSAGE_NO_PROC) self.assertTrue(noproc2) self.assertEqual(noproc2, noproc) self.assertNotEqual(noproc, MPI.MESSAGE_NULL) # message = MPI.Message(MPI.MESSAGE_NO_PROC) message.Recv(None) self.assertEqual(message, MPI.MESSAGE_NULL) # message = MPI.Message(MPI.MESSAGE_NO_PROC) request = message.Irecv(None) self.assertEqual(message, MPI.MESSAGE_NULL) self.assertNotEqual(request, MPI.REQUEST_NULL) request.Wait() self.assertEqual(request, MPI.REQUEST_NULL) @unittest.skipIf(MPI.MESSAGE_NULL == MPI.MESSAGE_NO_PROC, 'mpi-message') class BaseTestP2PMatched(object): COMM = MPI.COMM_NULL def testIMProbe(self): comm = self.COMM.Dup() try: m = comm.Improbe() self.assertEqual(m, None) m = comm.Improbe(MPI.ANY_SOURCE) self.assertEqual(m, None) m = comm.Improbe(MPI.ANY_SOURCE, MPI.ANY_TAG) self.assertEqual(m, None) status = MPI.Status() m = comm.Improbe(MPI.ANY_SOURCE, MPI.ANY_TAG, status) self.assertEqual(m, None) self.assertEqual(status.source, MPI.ANY_SOURCE) self.assertEqual(status.tag, MPI.ANY_TAG) self.assertEqual(status.error, MPI.SUCCESS) m = MPI.Message.Iprobe(comm) self.assertEqual(m, None) buf = [None, 0, MPI.BYTE] s = comm.Isend(buf, comm.rank, 0) r = comm.Mprobe(comm.rank, 0).Irecv(buf) MPI.Request.Waitall([s,r]) finally: comm.Free() def testProbeRecv(self): comm = self.COMM size = comm.Get_size() rank = comm.Get_rank() for array, typecode in arrayimpl.subTest(self): for s in range(0, size+1): sbuf = array( s, typecode, s) rbuf = array(-1, typecode, s) if size == 1: n = comm.Improbe(0, 0) self.assertEqual(n, None) sr = comm.Isend(sbuf.as_mpi(), 0, 0) m = comm.Mprobe(0, 0) self.assertTrue(isinstance(m, MPI.Message)) self.assertTrue(m) rr = m.Irecv(rbuf.as_raw()) self.assertFalse(m) self.assertTrue(sr) self.assertTrue(rr) MPI.Request.Waitall([sr,rr]) self.assertFalse(sr) self.assertFalse(rr) # n = comm.Improbe(0, 0) self.assertEqual(n, None) r = comm.Isend(sbuf.as_mpi(), 0, 0) m = MPI.Message.Probe(comm, 0, 0) self.assertTrue(isinstance(m, MPI.Message)) self.assertTrue(m) m.Recv(rbuf.as_raw()) self.assertFalse(m) r.Wait() # n = MPI.Message.Iprobe(comm, 0, 0) self.assertEqual(n, None) r = comm.Isend(sbuf.as_mpi(), 0, 0) comm.Probe(0, 0) m = MPI.Message.Iprobe(comm, 0, 0) self.assertTrue(isinstance(m, MPI.Message)) self.assertTrue(m) m.Recv(rbuf.as_raw()) self.assertFalse(m) r.Wait() # n = MPI.Message.Iprobe(comm, 0, 0) self.assertEqual(n, None) r = comm.Isend(sbuf.as_mpi(), 0, 0) m = comm.Mprobe(0, 0) self.assertTrue(isinstance(m, MPI.Message)) self.assertTrue(m) m.Recv(rbuf.as_raw()) self.assertFalse(m) r.Wait() elif rank == 0: n = comm.Improbe(0, 0) self.assertEqual(n, None) # comm.Send(sbuf.as_mpi(), 1, 0) m = comm.Mprobe(1, 0) self.assertTrue(m) m.Recv(rbuf.as_raw()) self.assertFalse(m) # n = comm.Improbe(0, 0) self.assertEqual(n, None) comm.Send(sbuf.as_mpi(), 1, 1) m = None while not m: m = comm.Improbe(1, 1) m.Irecv(rbuf.as_raw()).Wait() elif rank == 1: n = comm.Improbe(1, 0) self.assertEqual(n, None) # m = comm.Mprobe(0, 0) self.assertTrue(m) m.Recv(rbuf.as_raw()) self.assertFalse(m) # n = comm.Improbe(1, 0) self.assertEqual(n, None) comm.Send(sbuf.as_mpi(), 0, 0) m = None while not m: m = comm.Improbe(0, 1) m.Irecv(rbuf.as_mpi()).Wait() comm.Send(sbuf.as_mpi(), 0, 1) else: rbuf = sbuf for value in rbuf: self.assertEqual(value, s) class TestP2PMatchedSelf(BaseTestP2PMatched, unittest.TestCase): COMM = MPI.COMM_SELF class TestP2PMatchedWorld(BaseTestP2PMatched, unittest.TestCase): COMM = MPI.COMM_WORLD class TestP2PMatchedSelfDup(TestP2PMatchedSelf): def setUp(self): self.COMM = MPI.COMM_SELF.Dup() def tearDown(self): self.COMM.Free() class TestP2PMatchedWorldDup(TestP2PMatchedWorld): def setUp(self): self.COMM = MPI.COMM_WORLD.Dup() def tearDown(self): self.COMM.Free() if __name__ == '__main__': unittest.main()
[ "dalcinl@gmail.com" ]
dalcinl@gmail.com
c5a31eb41580dc0adfdf2d07d1e4a5c2ca3d23a8
a6be90df65e2369dbd0a4b64af078dc49aa5b7fa
/game/Tic-Tac-Toe-Game-in-python-3-Tkinter-master/my tic tac 2.py
b31c59089b64aac4e14331a1b95ee1a39d91ee96
[]
no_license
realshantanu/EDITH
4ebaee5d92081c01750959db98adfe5f7c8db1d7
b26526948969880e0dbd3d6da0fe42d4c20452d8
refs/heads/master
2023-02-17T21:17:53.745321
2021-01-19T14:15:49
2021-01-19T14:15:49
263,513,910
2
0
null
null
null
null
UTF-8
Python
false
false
5,014
py
from tkinter import * import tkinter.messagebox tk = Tk() tk.title("Tic Tac Toe") pa = StringVar() playerb = StringVar() p1 = StringVar() p2 = StringVar() player1_name = Entry(tk, textvariable=p1, bd=5) player1_name.grid(row=1, column=1, columnspan=8) player2_name = Entry(tk, textvariable=p2, bd=5) player2_name.grid(row=2, column=1, columnspan=8) bclick = True flag = 0 def disableButton(): button1.configure(state=DISABLED) button2.configure(state=DISABLED) button3.configure(state=DISABLED) button4.configure(state=DISABLED) button5.configure(state=DISABLED) button6.configure(state=DISABLED) button7.configure(state=DISABLED) button8.configure(state=DISABLED) button9.configure(state=DISABLED) def btnClick(buttons): global bclick, flag, player2_name, player1_name, playerb, pa if buttons["text"] == " " and bclick == True: buttons["text"] = "X" bclick = False playerb = p2.get() + " Wins!" pa = p1.get() + " Wins!" checkForWin() flag += 1 elif buttons["text"] == " " and bclick == False: buttons["text"] = "O" bclick = True checkForWin() flag += 1 else: tkinter.messagebox.showinfo("Tic-Tac-Toe", "Button already Clicked!") def checkForWin(): if (button1['text'] == 'X' and button2['text'] == 'X' and button3['text'] == 'X' or button4['text'] == 'X' and button5['text'] == 'X' and button6['text'] == 'X' or button7['text'] =='X' and button8['text'] == 'X' and button9['text'] == 'X' or button1['text'] == 'X' and button5['text'] == 'X' and button9['text'] == 'X' or button3['text'] == 'X' and button5['text'] == 'X' and button7['text'] == 'X' or button1['text'] == 'X' and button2['text'] == 'X' and button3['text'] == 'X' or button1['text'] == 'X' and button4['text'] == 'X' and button7['text'] == 'X' or button2['text'] == 'X' and button5['text'] == 'X' and button8['text'] == 'X' or button7['text'] == 'X' and button6['text'] == 'X' and button9['text'] == 'X'): disableButton() tkinter.messagebox.showinfo("Tic-Tac-Toe", pa) elif(flag == 8): tkinter.messagebox.showinfo("Tic-Tac-Toe", "It is a Tie") elif (button1['text'] == 'O' and button2['text'] == 'O' and button3['text'] == 'O' or button4['text'] == 'O' and button5['text'] == 'O' and button6['text'] == 'O' or button7['text'] == 'O' and button8['text'] == 'O' and button9['text'] == 'O' or button1['text'] == 'O' and button5['text'] == 'O' and button9['text'] == 'O' or button3['text'] == 'O' and button5['text'] == 'O' and button7['text'] == 'O' or button1['text'] == 'O' and button2['text'] == 'O' and button3['text'] == 'O' or button1['text'] == 'O' and button4['text'] == 'O' and button7['text'] == 'O' or button2['text'] == 'O' and button5['text'] == 'O' and button8['text'] == 'O' or button7['text'] == 'O' and button6['text'] == 'O' and button9['text'] == 'O'): disableButton() tkinter.messagebox.showinfo("Tic-Tac-Toe", playerb) buttons = StringVar() label = Label( tk, text="Player 1:", font='Times 20 bold', bg='white', fg='black', height=1, width=8) label.grid(row=1, column=0) label = Label( tk, text="Player 2:", font='Times 20 bold', bg='white', fg='black', height=1, width=8) label.grid(row=2, column=0) button1 = Button(tk, text=" ", font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button1)) button1.grid(row=3, column=0) button2 = Button(tk, text=' ', font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button2)) button2.grid(row=3, column=1) button3 = Button(tk, text=' ',font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button3)) button3.grid(row=3, column=2) button4 = Button(tk, text=' ', font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button4)) button4.grid(row=4, column=0) button5 = Button(tk, text=' ', font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button5)) button5.grid(row=4, column=1) button6 = Button(tk, text=' ', font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button6)) button6.grid(row=4, column=2) button7 = Button(tk, text=' ', font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button7)) button7.grid(row=5, column=0) button8 = Button(tk, text=' ', font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button8)) button8.grid(row=5, column=1) button9 = Button(tk, text=' ', font='Times 20 bold', bg='gray', fg='white', height=4, width=8, command=lambda: btnClick(button9)) button9.grid(row=5, column=2) tk.mainloop()
[ "noreply@github.com" ]
realshantanu.noreply@github.com
8aa35327a104aaf28be1592dcef0bc1d3efceae4
712d28ae06cc50243e73857cdb9e785adbc2d8cc
/02 - Styling and Templates/main.py
cfd2fa1f81993e3c3ef4685209b236de6b8ea3f4
[]
no_license
ahmedgarip/fastapi-selling-site
a307f447305239c06893e8437b21dd6080867832
3e38c4f50de4867155b6363a77f1696e62bf8833
refs/heads/main
2023-08-20T17:19:21.706948
2021-11-01T20:06:22
2021-11-01T20:06:22
421,097,058
1
1
null
null
null
null
UTF-8
Python
false
false
471
py
from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def home_page(request: Request): return templates.TemplateResponse( "home.html", {"request": request})
[ "noreply@github.com" ]
ahmedgarip.noreply@github.com
357128be50191ca533d29da79f303dd2c85ea059
73d9488c6a6f2bc0f72dd486c764ac5fc0d9b78f
/remove_dropout_layers.py
f6ced66908c485713b5cd18e5671ffbc398256cc
[]
no_license
slanab/TensorRT-Inference
c1c7fe97c48ed7eb04de5c46141baef8c6501bc4
8f9f012ddaceba068758a9399b53c6cbf0a606d9
refs/heads/master
2020-03-22T10:29:36.714068
2019-07-08T20:02:17
2019-07-08T20:02:17
139,906,802
3
1
null
null
null
null
UTF-8
Python
false
false
2,684
py
# This script accepts a frozen tensorflow graph and attempts to remove dropout layers so the model can be used for inference # Usage: python remove_dropout_layers.py frozen_graph_input_path.pb frozen_graph_output_path.pb # Based on answers from https://stackoverflow.com/questions/40358892/wipe-out-dropout-operations-from-tensorflow-graph import tensorflow as tf from google.protobuf import text_format from tensorflow.core.framework import graph_pb2 from tensorflow.core.framework import node_def_pb2 from tensorflow.python.tools.optimize_for_inference_lib import node_from_map, node_name_from_input def print_graph(input_graph): for node in input_graph.node: print "{0} : {1} ( {2} )".format(node.name, node.op, node.input) def strip(input_graph): input_nodes = input_graph.node input_node_map = {} for node in input_nodes: if node.name not in input_node_map.keys(): input_node_map[node.name] = node nodes_after_strip = [] for node in input_nodes: print "======================" print "{0} : {1} ( {2} )".format(node.name, node.op, node.input) # If node belongs to the dropout layer - ignore it if len(node.name.split('/')) > 2 and node.name.split('/')[-3].startswith('dropout'): continue # Otherwise, copy the node to new graph new_node = node_def_pb2.NodeDef() new_node.CopyFrom(node) for idx, i in enumerate(node.input): input_clean = node_name_from_input(i) # If node accepts output from dropout layer as its input - change node's input to be dropout layer's input if len(input_clean.split('/')) > 2 and input_clean.split('/')[-3].startswith('dropout'): op_mul = node_from_map(input_node_map, i) op_div = node_from_map(input_node_map, op_mul.input[0]) parent = node_from_map(input_node_map, op_div.input[0]) new_node.input[idx] = parent.name nodes_after_strip.append(new_node) output_graph = graph_pb2.GraphDef() output_graph.node.extend(nodes_after_strip) return output_graph input_graph = sys.argv[1] output_graph = sys.argv[2] input_graph_def = tf.GraphDef() with tf.gfile.FastGFile(input_graph, "rb") as f: input_graph_def.ParseFromString(f.read()) output_graph_def = strip(input_graph_def) #print "======================\nBefore:" #print_graph(input_graph_def) #print "======================\nAfter:" #print_graph(output_graph_def) with tf.gfile.GFile(output_graph, "wb") as f: f.write(output_graph_def.SerializeToString()) print("%d ops in the original graph." % len(input_graph_def.node)) print("%d ops in the final graph." % len(output_graph_def.node))
[ "noreply@github.com" ]
slanab.noreply@github.com
fb019146cfa244ddce5f8c32f072dd14944c5472
7c9e71c98b4e92cccba088ccaa3233d8baebb898
/server.py
ffcde13e67196d77097014607fc512f689232115
[]
no_license
FDELTA/Project---The-Ranking
051f97205174f676529db7caf99af736263791d0
c1d7c65c2dfe6d667b73a29f17b4e497514efa42
refs/heads/master
2022-12-21T13:57:18.589409
2020-09-25T11:44:47
2020-09-25T11:44:47
297,354,957
0
0
null
null
null
null
UTF-8
Python
false
false
168
py
from src.app import app from src.config import PORT import src.controllers.labcontroller import src.controllers.studentcontroller app.run("0.0.0.0", PORT, debug=True)
[ "f.delgadoteran@gmail.com" ]
f.delgadoteran@gmail.com
8a48c7164ddd11a7e14ea9d326f9e25c45dd55e8
0c2e2ffaba7cd14ba2fdcccad9bcde21d37d147e
/flambeau/misc/logger.py
4d8d3cf9741cf576f7c6d904d2452b85ddcec828
[ "MIT" ]
permissive
corenel/flambeau
c14fdee22ef79333eef6abb1892dffc5d013b201
3e90f37ba3d692af6df02da39907132ff9a490da
refs/heads/master
2020-04-13T01:49:25.245971
2019-09-21T16:26:40
2019-09-21T16:26:40
162,884,868
1
0
MIT
2019-01-25T13:48:40
2018-12-23T11:26:46
Python
UTF-8
Python
false
false
1,890
py
import sys class OutputLogger(object): """Output logger""" def __init__(self): self.file = None self.buffer = '' def set_log_file(self, filename, mode='wt'): assert self.file is None self.file = open(filename, mode) if self.buffer is not None: self.file.write(self.buffer) self.buffer = None def write(self, data): if self.file is not None: self.file.write(data) if self.buffer is not None: self.buffer += data def flush(self): if self.file is not None: self.file.flush() class TeeOutputStream(object): """Redirect output stream""" def __init__(self, child_streams, autoflush=False): self.child_streams = child_streams self.autoflush = autoflush def write(self, data): if isinstance(data, bytes): data = data.decode('utf-8') for stream in self.child_streams: stream.write(data) if self.autoflush: self.flush() def flush(self): for stream in self.child_streams: stream.flush() output_logger = None def init_output_logging(): """ Initialize output logger """ global output_logger if output_logger is None: output_logger = OutputLogger() sys.stdout = TeeOutputStream([sys.stdout, output_logger], autoflush=True) sys.stderr = TeeOutputStream([sys.stderr, output_logger], autoflush=True) def set_output_log_file(filename, mode='wt'): """ Set file name of output log :param filename: file name of log :type filename: str :param mode: the mode in which the file is opened :type mode: str """ if output_logger is not None: output_logger.set_log_file(filename, mode)
[ "xxdsox@gmail.com" ]
xxdsox@gmail.com
3312de3b9a157d63fb85218c40fb32dbe741b541
7a8746cec8df0d5b4c57de5fe5a67c4fb49f0f42
/python/katas/delete_nth.py
559e8191a05ad87ac2479501f133bc8f01377047
[]
no_license
b-ju/learn_cs
664cf4bd4655c68371365dddcb905ae2c0f23cb4
a9b60e56590c3e4c564cf9314de5bb122d490752
refs/heads/main
2023-07-10T09:34:33.538161
2021-08-27T20:38:49
2021-08-27T20:38:49
389,750,481
0
0
null
2021-08-23T15:16:18
2021-07-26T19:46:30
C
UTF-8
Python
false
false
594
py
from collections import Counter def delete_nth(arr, most): counts = Counter(arr) arr.reverse() for num in counts: if counts[num] > most: for i in range(0, counts[num] - most): arr.remove(num) arr.reverse(); return arr def delete_nth_bp(order, max_e): ans = [] for o in order: if ans.count(o) < max_e: ans.append(o) return ans def main(): print(delete_nth_bp([1,1,2,2,3,3,3,4,1,1],1)) print(delete_nth_bp([1,1,2,2,3,3,3,4,1,1],2) , " should equal [1,1,2,2,3,3,4]") print(delete_nth_bp([1,1,1],0) , " should equal[ ]") if __name__ == '__main__': main()
[ "benjurenka@gmail.com" ]
benjurenka@gmail.com
aa0a1e0348c6eeb05b735bb4747002d570839727
56b5b42b90f8ace3f5650da41b2d29c00af7436a
/pybuild/packages/kiwisolver.py
b482ceebde622b91a5a5f9140dbaf8dfe43eb8ec
[ "WTFPL" ]
permissive
qpython-android/qpython3-toolchain
566870072b5e2017c9cc4b026310f5c71703af1c
a6ac41866879f8f8626811151964480f0705d769
refs/heads/master
2021-06-03T16:20:30.834934
2021-01-06T09:54:04
2021-01-06T09:54:04
21,027,839
22
8
WTFPL
2021-01-06T09:54:05
2014-06-20T06:32:00
C
UTF-8
Python
false
false
1,611
py
from ..source import GitSource from ..package import Package from ..patch import LocalPatch from ..util import target_arch import os class Kiwisolver(Package): source = GitSource('https://github.com/QPYPI/kiwisolver.git', alias='kiwi', branch='qpyc/1.0.1') patches = [ #LocalPatch('0001-cross-compile'), ] #use_gcc = True def prepare(self): #self.run(['cp', self.filesdir / 'site.cfg', './']) pass def build(self): PY_BRANCH = os.getenv('PY_BRANCH') PY_M_BRANCH = os.getenv('PY_M_BRANCH') self.run([ 'python', 'setup.py', 'build_ext', f'-I../../build/target/python/usr/include/python{PY_BRANCH}.{PY_M_BRANCH}:../../build/target/openblas/usr/include:{self.env["ANDROID_NDK"]}/sources/cxx-stl/gnu-libstdc++/4.9/include:{self.env["ANDROID_NDK"]}/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/include', f'-L../../build/target/python/usr/lib:../../build/target/openblas/usr/lib:{self.env["ANDROID_NDK"]}/toolchains/renderscript/prebuilt/linux-x86_64/platform/arm:{self.env["ANDROID_NDK"]}/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a:{self.env["ANDROID_NDK"]}/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/lib/gcc/arm-linux-androideabi/4.9.x/armv7-a:{self.env["ANDROID_NDK"]}/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/arm-linux-androideabi/lib/armv7-a', f'-lpython{PY_BRANCH}.{PY_M_BRANCH},m,gnustl_static,atomic', ]) self.run([ 'python', 'setup.py', 'build_py', ])
[ "riverfor@gmail.com" ]
riverfor@gmail.com
0d2ce50facb8242c3a5c312772e5faa2d3e231bd
108e8ad726e1a8cb2f641198467e817745ccd061
/Data Structure/Problem Siang/5 - Initial Group Descending.py
8885a39e5d5c1b56c1b289b71e1accc50cc6fc01
[]
no_license
aralfaruqi/alteraproject
ab96a93c19c0238c12655cb38456b8a2bc40adb3
4d5df9f73e1db85a91e89eed3f230baae487291c
refs/heads/master
2020-12-09T05:15:12.798098
2020-01-13T13:05:45
2020-01-13T13:05:45
233,200,427
0
0
null
null
null
null
UTF-8
Python
false
false
1,077
py
def initialGroupingDescending(studentsArr) : huruf_awal = [] for student in studentsArr: huruf_awal.append(student[0]) set_huruf_awal = set(huruf_awal) list_huruf_awal = list(set_huruf_awal) list_akhir = [] swapped = True while swapped: swapped = False maxIter = len(list_huruf_awal)-1 for i in range(maxIter): val1 = list_huruf_awal[i] val2 = list_huruf_awal[i+1] if val1<val2: list_huruf_awal[i] = val2 list_huruf_awal[i+1] = val1 swapped = True for huruf in list_huruf_awal: lst = [] lst.append(huruf) for student in studentsArr: if huruf == student[0]: lst.append(student) list_akhir.append(lst) return list_akhir print(initialGroupingDescending(['Budi', 'Badu', 'Joni', 'Jono'])) print(initialGroupingDescending(['Mickey', 'Yusuf', 'Donald', 'Ali', 'Gong'])) print(initialGroupingDescending(['Rock', 'Stone', 'Brick', 'Rocker', 'Sticker']))
[ "rafiq@alterra.id" ]
rafiq@alterra.id
1e4e48a0da6ec7cb32601bfa55fff371d73ef203
9f74b821f2abaaf5ad389a86c13e46373fc7cd65
/Day05/Demo03/Demo04Singleton.py
e7b830a79da22c8869f2857aec4553f9a43f8306
[]
no_license
Shanchance/PythonLearnDemos
3a63d0141f82758fffe0ea4539b6fc919cbea02e
9c368baf3aff735a76c7d69756e61c176640bf6f
refs/heads/master
2022-11-18T14:43:11.774923
2020-07-12T10:23:47
2020-07-12T10:23:47
279,038,057
0
0
null
null
null
null
UTF-8
Python
false
false
433
py
class MySingleton: __obj = None __init_flag = True def __new__(cls, *args, **kwargs): if cls.__obj == None: cls.__obj = object.__new__(cls) return cls.__obj def __init__(self,name): if MySingleton.__init_flag: print("init……") self.name = name MySingleton.__init_flag = False a = MySingleton("AA") b = MySingleton("BB") print(a) print(b)
[ "17865569208@163.com" ]
17865569208@163.com
b1815d13249bea04e6f3837dcd916561911be094
17e2f25e7e2dce27e7c5ce0c011f7a917c410b24
/Root_Finder/graphPlotter.py
8e3c39f1dc7273bc1621bcdf55f0ef36615f2143
[]
no_license
Minashraf/RootFinder
b30ae5b2f264a2689480f24e92a1fd9cdc20ddcc
db81a3c772b12b846a9ea189f72cfe687cef6576
refs/heads/master
2022-09-06T08:42:09.836279
2020-05-13T09:28:56
2020-05-13T09:28:56
261,712,917
0
0
null
null
null
null
UTF-8
Python
false
false
10,743
py
from time import time from tkinter import ttk from matplotlib import style import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from matplotlib.figure import Figure from matplotlib.backends.backend_pdf import PdfPages try: import Tkinter as tk except ImportError: import tkinter as tk style.use('ggplot') class graphPlotter(): def __init__(self, frame, method, answer, solver, check, filename): self.check = check self.frame = frame self.fig = Figure(figsize=(5, 5), dpi=80) self.plt = self.fig.add_subplot(1, 1, 1) self.current = 0 self.xs = dict() self.ys = dict() self.solver = solver self.method = method if self.method == 0: '''indirect methods''' self.bounds = answer[1] self.xes = answer[0] self.fx = np.arange(self.bounds[0][0] - 3, self.bounds[0][1] + 3, 0.2) self.fy = np.array([self.solver.evaluate(num) for num in self.fx]) self.plot_indirect() else: '''direct method''' self.guesses = answer[1] self.xes = answer[0] self.unit_x = None self.unit_y = None self.plot_direct() self.plt.axhline(y=0, color='k', label='X-Axis') self.plt.axvline(x=0, color='k', label='Y-Axis') self.plt.legend(loc="upper right") if self.check: pdf = PdfPages(filename) pdf.savefig(self.fig) i = 0 if self.method == 0: while i != len(self.bounds)-1: self.next() pdf.savefig(self.fig) i += 1 else: while i != len(self.guesses)-1: self.next() pdf.savefig(self.fig) i += 1 pdf.close() else: self.canvas = FigureCanvasTkAgg(self.fig, self.frame) self.toolbar = NavigationToolbar2Tk(self.canvas, self.frame) self.toolbar.update() self.canvas.get_tk_widget().pack(side=tk.TOP, expand=True) self.canvas.get_tk_widget().pack(side=tk.TOP, expand=True) self.tooltip_font = "TkDefaultFont" self.next_photo = tk.PhotoImage(file='Images/next.png') self.next_graph = ttk.Button(self.toolbar, image=self.next_photo) self.next_graph.pack(side=tk.RIGHT) self.next_graph.configure(command=self.next) self.next_graph.configure(width=2.5) ToolTip(self.next_graph, self.tooltip_font, 'Next Graph', delay=0.1) self.prev_photo = tk.PhotoImage(file='Images/prev.png') self.prev_graph = ttk.Button(self.toolbar, image=self.prev_photo) self.prev_graph.pack(side=tk.RIGHT) self.prev_graph.configure(command=self.prev) self.prev_graph.configure(width=2.5) ToolTip(self.prev_graph, self.tooltip_font, 'Previous Graph', delay=0.1) def next(self): self.fig.clear() self.plt = self.fig.add_subplot(1, 1, 1) if self.method == 0: self.current = (self.current + 1) % len(self.bounds) self.plot_indirect() else: self.current = (self.current + 1) % len(self.guesses) self.plot_direct() self.plt.axhline(y=0, color='k', label='X-Axis') self.plt.axvline(x=0, color='k', label='Y-Axis') self.plt.legend(loc="upper right") if not self.check: self.canvas.draw() self.canvas.figure.set_canvas(self.canvas) def prev(self): self.fig.clear() self.plt = self.fig.add_subplot(1, 1, 1) if self.method == 0: if self.current == 0: self.current = len(self.bounds) - 1 else: self.current -= 1 self.plot_indirect() else: if self.current == 0: self.current = len(self.guesses) - 1 else: self.current -= 1 self.plot_direct() self.plt.axhline(y=0, color='k', label='X-Axis') self.plt.axvline(x=0, color='k', label='Y-Axis') self.plt.legend(loc="upper right") self.canvas.draw() self.canvas.figure.set_canvas(self.canvas) def plot_indirect(self): self.plt.plot(self.fx, self.fy, color='r', label='f(x)') self.plt.axvline(x=self.xes[self.current], color='c', label='Xi') self.plt.axvline(x=self.bounds[self.current][0], color='b', label='lower') self.plt.axvline(x=self.bounds[self.current][1], color='g', label='upper') def plot_direct(self): if self.method == 3: max_guess = max(self.guesses[self.current][0], self.guesses[self.current][1]) min_guess = min(self.guesses[self.current][0], self.guesses[self.current][1]) self.fx = np.arange(min_guess - 3, max_guess + 3, 0.2) self.fy = np.array([self.solver.evaluate(num) for num in self.fx]) else: self.fx = np.arange(self.guesses[self.current] - 3, self.guesses[self.current] + 3, 0.2) self.fy = np.array([self.solver.evaluate(num) for num in self.fx]) if self.method == 1: self.unit_x = np.array([self.fx[0], self.fx[len(self.fx) - 1]]) self.unit_y = np.array([self.fx[0], self.fx[len(self.fx) - 1]]) elif self.method == 2: self.unit_x = self.fx self.slope = self.solver.d(self.guesses[self.current]) self.b = self.solver.f(self.guesses[self.current]) - (self.slope * self.guesses[self.current]) self.unit_y = np.array([((self.slope * num) + self.b) for num in self.unit_x]) else: self.unit_x = self.fx self.slope = ( (self.solver.f(self.guesses[self.current][0]) - self.solver.f(self.guesses[self.current][1])) / (self.guesses[self.current][0] - self.guesses[self.current][1])) self.b = self.solver.f(self.guesses[self.current][0]) - (self.slope * self.guesses[self.current][0]) self.unit_y = np.array([((self.slope * num) + self.b) for num in self.unit_x]) self.plt.plot(self.fx, self.fy, color='r', label='f(x)') if self.method == 1: self.plt.plot(self.unit_x, self.unit_y, color='c', label='y=x') else: self.plt.plot(self.unit_x, self.unit_y, color='c', label='f\'(x)') if self.method == 3: self.plt.axvline(x=self.guesses[self.current][0], color='b', label='Xi-1') self.plt.axvline(x=self.guesses[self.current][1], color='y', label='Xi-2') else: self.plt.axvline(x=self.guesses[self.current], color='b', label='Xi-1') self.plt.axvline(x=self.xes[self.current], color='g', label='Xi') class ToolTip(tk.Toplevel): """ Provides a ToolTip widget for Tkinter. To apply a ToolTip to any Tkinter widget, simply pass the widget to the ToolTip constructor """ def __init__(self, wdgt, tooltip_font, msg=None, msgFunc=None, delay=1, follow=True): """ Initialize the ToolTip Arguments: wdgt: The widget this ToolTip is assigned to tooltip_font: Font to be used msg: A static string message assigned to the ToolTip msgFunc: A function that retrieves a string to use as the ToolTip text delay: The delay in seconds before the ToolTip appears(may be float) follow: If True, the ToolTip follows motion, otherwise hides """ self.wdgt = wdgt # The parent of the ToolTip is the parent of the ToolTips widget self.parent = self.wdgt.master # Initalise the Toplevel tk.Toplevel.__init__(self, self.parent, bg='black', padx=1, pady=1) # Hide initially self.withdraw() # The ToolTip Toplevel should have no frame or title bar self.overrideredirect(True) # The msgVar will contain the text displayed by the ToolTip self.msgVar = tk.StringVar() if msg is None: self.msgVar.set('No message provided') else: self.msgVar.set(msg) self.msgFunc = msgFunc self.delay = delay self.follow = follow self.visible = 0 self.lastMotion = 0 # The text of the ToolTip is displayed in a Message widget tk.Message(self, textvariable=self.msgVar, bg='#FFFFDD', font=tooltip_font, aspect=1000).grid() # Add bindings to the widget. This will NOT override # bindings that the widget already has self.wdgt.bind('<Enter>', self.spawn, '+') self.wdgt.bind('<Leave>', self.hide, '+') self.wdgt.bind('<Motion>', self.move, '+') def spawn(self, event=None): """ Spawn the ToolTip. This simply makes the ToolTip eligible for display. Usually this is caused by entering the widget Arguments: event: The event that called this funciton """ self.visible = 1 # The after function takes a time argument in miliseconds self.after(int(self.delay * 1000), self.show) def show(self): """ Displays the ToolTip if the time delay has been long enough """ if self.visible == 1 and time() - self.lastMotion > self.delay: self.visible = 2 if self.visible == 2: self.deiconify() def move(self, event): """ Processes motion within the widget. Arguments: event: The event that called this function """ self.lastMotion = time() # If the follow flag is not set, motion within the # widget will make the ToolTip disappear # if self.follow is False: self.withdraw() self.visible = 1 # Offset the ToolTip 10x10 pixes southwest of the pointer self.geometry('+%i+%i' % (event.x_root + 20, event.y_root - 10)) try: # Try to call the message function. Will not change # the message if the message function is None or # the message function fails self.msgVar.set(self.msgFunc()) except: pass self.after(int(self.delay * 1000), self.show) def hide(self, event=None): """ Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function """ self.visible = 0 self.withdraw()
[ "hossam_elkordi@yahoo.com" ]
hossam_elkordi@yahoo.com
7c04fc30c9c186f579bf4d7de988aebe3f5e7d9c
b95c5e20d47f36dc94d2cda4e0d084ec772c0229
/hsreplaynet/billing/utils.py
97e44ef4c19d559df1e25f90680635707400962e
[]
no_license
omni5cience/HSReplay.net
dd6cec1308c0970f6ae9fa1e3280b6de9fbe9146
a983721059dc3173bad64c659231711238949f0e
refs/heads/master
2020-09-16T07:53:25.792779
2017-06-15T21:00:14
2017-06-15T21:00:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
400
py
from hsreplaynet.analytics.processing import PremiumUserCacheWarmingContext def get_premium_cache_warming_contexts_from_subscriptions(): result = [] from djstripe.models import Subscription for subscription in Subscription.objects.active(): user = subscription.customer.subscriber if user: context = PremiumUserCacheWarmingContext.from_user(user) result.append(context) return result
[ "andrewmoorewilson@gmail.com" ]
andrewmoorewilson@gmail.com
e388f07861577b270ce24534a25c4d32cac1b885
350ecc8259bcad075bd376423335bb41cc8a533e
/__init__.py
9a0908b587ed6a532cc0936c6f481455748edc8c
[]
no_license
CodedQuen/python_begin
39da66ecc4a77b94a5afbbf0900727c8156b85e1
1433c319b5d85520c50aee00dd4b6f21a7e6366a
refs/heads/master
2022-06-10T10:30:28.807874
2020-04-25T03:34:03
2020-04-25T03:34:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
191
py
class Array(object): def __init__(self, length = 0, baseIndex = 0): assert length >= 0 self._data = [None for i in range(length)] self._baseIndex = baseIndex
[ "noreply@github.com" ]
CodedQuen.noreply@github.com
86fca4c2b0fa08521bb57b377c36eae361e89cc2
7c2ea365f20ff3eaec12b7a5289c21f345373d40
/share/lib/python/neuron/rxdtests/tests/hh_cvode.py
ac256a455311c85e26ef545cd81d5dcffe7a9dc2
[ "BSD-3-Clause" ]
permissive
wwlytton/nrn
95892cb08b993d0cc9377d7136304bc9196723ef
32b01882064583582a7ac2b563c4babf874b14ea
refs/heads/master
2020-06-17T05:59:34.145205
2019-11-15T20:26:20
2019-11-15T20:26:20
195,821,881
1
1
NOASSERTION
2019-10-02T11:45:39
2019-07-08T13:51:17
C
UTF-8
Python
false
false
5,128
py
from neuron import h, crxd as rxd from neuron.crxd import v from neuron.crxd.rxdmath import vtrap, exp, log from math import pi from matplotlib import pyplot h.load_file('stdrun.hoc') h.CVode().active(True) # parameters h.celsius = 6.3 e = 1.60217662e-19 scale = 1e-14/e gnabar = 0.12*scale # molecules/um2 ms mV gkbar = 0.036*scale gl = 0.0003*scale el = -54.3 q10 = 3.0**((h.celsius - 6.3)/10.0) # sodium activation 'm' alpha = 0.1 * vtrap(-(v + 40.0), 10) beta = 4.0 * exp(-(v + 65)/18.0) mtau = 1.0/(q10 * (alpha + beta)) minf = alpha/(alpha + beta) # sodium inactivation 'h' alpha = 0.07 * exp(-(v + 65.0)/20.0) beta = 1.0/(exp(-(v + 35.0)/10.0) + 1.0) htau = 1.0/(q10 * (alpha + beta)) hinf = alpha/(alpha + beta) # potassium activation 'n' alpha = 0.01 * vtrap(-(v + 55.0), 10.0) beta = 0.125 * exp(-(v + 65.0)/80.0) ntau = 1.0/(q10 * (alpha + beta)) ninf = alpha/(alpha + beta) somaA = h.Section('somaA') somaA.pt3dclear() somaA.pt3dadd(-90,0,0,1) somaA.pt3dadd(-60,0,0,1) somaA.nseg = 11 somaB = h.Section('somaB') somaB.pt3dclear() somaB.pt3dadd(60,0,0,1) somaB.pt3dadd(90,0,0,1) somaB.nseg = 11 # mod version somaB.insert('hh') # rxd version # Where? # intracellular cyt = rxd.Region(h.allsec(), name='cyt', nrn_region='i') # membrane mem = rxd.Region(h.allsec(), name='cell_mem', geometry = rxd.membrane()) # extracellular ecs = rxd.Extracellular(-100, -100, -100, 100, 100, 100, dx=100) # Who? def init(ics,ecs): return lambda nd: ecs if isinstance(nd,rxd.node.NodeExtracellular) else ics # ions k = rxd.Species([cyt, mem, ecs], name='k', d=1e3, charge=1, initial=init(54.4, 2.5), ecs_boundary_conditions=2.5) na = rxd.Species([cyt, mem, ecs], name='na', d=1e3, charge=1, initial=init(10.0, 140.0),ecs_boundary_conditions=140) x = rxd.Species([cyt, mem, ecs], name='x', charge=1) ki, ko, nai, nao, xi, xo = k[cyt], k[ecs], na[cyt], na[ecs], x[cyt], x[ecs] # gates ngate = rxd.State([cyt, mem], name='ngate', initial=0.24458654944007166) mgate = rxd.State([cyt, mem], name='mgate', initial=0.028905534475191907) hgate = rxd.State([cyt, mem], name='hgate', initial=0.7540796658225246) # somaA parameter pA = rxd.Parameter([cyt, mem], name='paramA', initial=lambda nd: 1 if nd.segment in somaA else 0) #What # gates m_gate = rxd.Rate(mgate, (minf - mgate)/mtau) h_gate = rxd.Rate(hgate, (hinf - hgate)/htau) n_gate = rxd.Rate(ngate, (ninf - ngate)/ntau) # Nernst potentials ena = 1e3*h.R*(h.celsius + 273.15)*log(nao/nai)/h.FARADAY ek = 1e3*h.R*(h.celsius + 273.15)*log(ko/ki)/h.FARADAY gna = pA*gnabar*mgate**3*hgate gk = pA*gkbar*ngate**4 na_current = rxd.MultiCompartmentReaction(nai, nao, gna*(v - ena), mass_action=False, membrane=mem, membrane_flux=True) k_current = rxd.MultiCompartmentReaction(ki, ko, gk*(v - ek), mass_action=False, membrane=mem, membrane_flux=True) leak_current = rxd.MultiCompartmentReaction(xi, xo, pA*gl*(v - el), mass_action=False, membrane=mem, membrane_flux=True) # stimulate stimA = h.IClamp(somaA(0.5)) stimA.delay = 50 stimA.amp = 1 stimA.dur = 50 stimB = h.IClamp(somaB(0.5)) stimB.delay = 50 stimB.amp = 1 stimB.dur = 50 # record tvec = h.Vector().record(h._ref_t) vvecA = h.Vector().record(somaA(0.5)._ref_v) mvecA = h.Vector().record(mgate.nodes(somaA(0.5))[0]._ref_value) nvecA = h.Vector().record(ngate.nodes(somaA(0.5))[0]._ref_value) hvecA = h.Vector().record(hgate.nodes(somaA(0.5))[0]._ref_value) kvecA = h.Vector().record(somaA(0.5)._ref_ik) navecA = h.Vector().record(somaA(0.5)._ref_ina) vvecB = h.Vector().record(somaB(0.5)._ref_v) kvecB = h.Vector().record(somaB(0.5)._ref_ik) navecB = h.Vector().record(somaB(0.5)._ref_ina) mvecB = h.Vector().record(somaB(0.5).hh._ref_m) nvecB = h.Vector().record(somaB(0.5).hh._ref_n) hvecB = h.Vector().record(somaB(0.5).hh._ref_h) tvec = h.Vector().record(h._ref_t) # run h.dt=0.025 h.finitialize(-70) #for i in range(1000): # h.fadvance() # print(h.t,somaA(0.5).v, somaA(0.5).ki, somaA(0.5).nai, somaA(0.5).xi) h.continuerun(100) # plot the results pyplot.ion() fig = pyplot.figure() pyplot.plot(tvec, vvecA, label="rxd") pyplot.plot(tvec, vvecB, label="mod") pyplot.legend() fig.set_dpi(200) fig = pyplot.figure() pyplot.plot(tvec, hvecA, '-b', label='h') pyplot.plot(tvec, mvecA, '-r', label='m') pyplot.plot(tvec, nvecA, '-g', label='n') pyplot.plot(tvec, hvecB, ':b') pyplot.plot(tvec, mvecB, ':r') pyplot.plot(tvec, nvecB, ':g') pyplot.legend() fig.set_dpi(200) fig = pyplot.figure() pyplot.plot(tvec, kvecA.as_numpy(), '-b', label='k') pyplot.plot(tvec, navecA.as_numpy(), '-r', label='na') pyplot.plot(tvec, kvecB, ':b') pyplot.plot(tvec, navecB, ':r') pyplot.legend() fig.set_dpi(200) fig = pyplot.figure() pyplot.plot(tvec, kvecA.as_numpy()-kvecB, '-b', label='k') pyplot.plot(tvec, navecA.as_numpy()-navecB, '-r', label='na') pyplot.legend() fig.set_dpi(200)
[ "adam.newton@yale.edu" ]
adam.newton@yale.edu
26b4c9df430f32e84591c3cf5fd9e91d0e605b04
d1ef145c7b51b694e59ed26894ef12e1026e9e78
/data_samples/aio-libs/aiohttp/tests/test_web_websocket.py
afcb7bed08e123d16c472274812438db82929898
[]
no_license
rkdls/tensorflow_new_seq2seq
2afc12b9e28626d351e4849c556a9f2320588a26
82ab66a79cc3f6631970ba2b2b349792b1aac7e4
refs/heads/master
2021-01-01T15:43:48.902079
2017-07-20T17:10:02
2017-07-20T17:10:02
97,688,888
0
1
null
null
null
null
UTF-8
Python
false
false
13,446
py
import asyncio from unittest import mock import pytest from multidict import CIMultiDict from aiohttp import WSMessage, WSMsgType, helpers, signals from aiohttp.log import ws_logger from aiohttp.test_utils import make_mocked_coro, make_mocked_request from aiohttp.web import HTTPBadRequest, HTTPMethodNotAllowed, WebSocketResponse from aiohttp.web_ws import WS_CLOSED_MESSAGE, WebSocketReady @pytest.fixture def function1902(arg511): var609 = mock.Mock() var609.loop = arg511 var609._debug = False var609.on_response_prepare = signals.Signal(var609) return var609 @pytest.fixture def function61(): function61 = mock.Mock() function61.drain.return_value = () function61.write_eof.return_value = () return function61 @pytest.fixture def function499(): var2479 = mock.Mock() var2479.set_parser.return_value = var2479 return var2479 @pytest.fixture def function271(function1902, function499, function61): def function69(arg1660, arg103, arg1031=None, arg1602=False): if (arg1031 is None): arg1031 = CIMultiDict({'HOST': 'server.example.com', 'UPGRADE': 'websocket', 'CONNECTION': 'Upgrade', 'SEC-WEBSOCKET-KEY': 'dGhlIHNhbXBsZSBub25jZQ==', 'ORIGIN': 'http://example.com', 'SEC-WEBSOCKET-VERSION': '13', }) if arg1602: arg1031['SEC-WEBSOCKET-PROTOCOL'] = 'chat, superchat' return make_mocked_request(arg1660, arg103, arg1031, app=function1902, protocol=function499, payload_writer=function61) return function69 def function2584(): var1663 = WebSocketResponse() with pytest.raises(RuntimeError): var1663.ping() def function1566(): var4050 = WebSocketResponse() with pytest.raises(RuntimeError): var4050.pong() def function742(): var3256 = WebSocketResponse() with pytest.raises(RuntimeError): var3256.send_str('string') def function2736(): var708 = WebSocketResponse() with pytest.raises(RuntimeError): var708.send_bytes(b'bytes') def function2225(): var3068 = WebSocketResponse() with pytest.raises(RuntimeError): var3068.send_json({'type': 'json', }) @asyncio.coroutine def function842(): var1638 = WebSocketResponse() with pytest.raises(RuntimeError): yield from var1638.close() @asyncio.coroutine def function1593(): var1675 = WebSocketResponse() with pytest.raises(RuntimeError): yield from var1675.receive_str() @asyncio.coroutine def function1966(): var134 = WebSocketResponse() with pytest.raises(RuntimeError): yield from var134.receive_bytes() @asyncio.coroutine def function360(): var468 = WebSocketResponse() with pytest.raises(RuntimeError): yield from var468.receive_json() @asyncio.coroutine def function2486(function271): var1174 = function271('GET', '/') var4064 = WebSocketResponse() yield from var4064.prepare(var1174) @asyncio.coroutine def function1900(): return WSMessage(WSMsgType.BINARY, b'data', b'') var4064.receive = function1900 with pytest.raises(TypeError): yield from var4064.receive_str() @asyncio.coroutine def function2630(function271): var2339 = function271('GET', '/') var3483 = WebSocketResponse() yield from var3483.prepare(var2339) @asyncio.coroutine def function1900(): return WSMessage(WSMsgType.TEXT, 'data', b'') var3483.receive = function1900 with pytest.raises(TypeError): yield from var3483.receive_bytes() @asyncio.coroutine def function2625(function271): var4377 = function271('GET', '/') var1358 = WebSocketResponse() yield from var1358.prepare(var4377) with pytest.raises(TypeError): var1358.send_str(b'bytes') @asyncio.coroutine def function612(function271): var540 = function271('GET', '/') var2482 = WebSocketResponse() yield from var2482.prepare(var540) with pytest.raises(TypeError): var2482.send_bytes('string') @asyncio.coroutine def function1324(function271): var3572 = function271('GET', '/') var2977 = WebSocketResponse() yield from var2977.prepare(var3572) with pytest.raises(TypeError): var2977.send_json(set()) def function2812(): var550 = WebSocketResponse() with pytest.raises(RuntimeError): var550.write(b'data') def function1889(): var4181 = WebSocketReady(True, 'chat') assert (var4181.ok is True) assert (var4181.function499 == 'chat') def function1027(): var3638 = WebSocketReady(False, None) assert (var3638.ok is False) assert (var3638.function499 is None) def function4(): var4173 = WebSocketReady(True, None) assert (var4173.ok is True) assert (var4173.function499 is None) def function2721(): var1479 = WebSocketReady(True, None) assert (bool(var1479) is True) def function1317(): var3713 = WebSocketReady(False, None) assert (bool(var3713) is False) def function1233(function271): var373 = function271('GET', '/', protocols=True) var725 = WebSocketResponse(protocols=('chat',)) assert ((True, 'chat') == var725.can_prepare(var373)) def function801(function271): var2751 = function271('GET', '/') var281 = WebSocketResponse() assert ((True, None) == var281.can_prepare(var2751)) def function1547(function271): var3899 = function271('POST', '/') var3504 = WebSocketResponse() assert ((False, None) == var3504.can_prepare(var3899)) def function2006(function271): var32 = function271('GET', '/', headers=CIMultiDict({})) var133 = WebSocketResponse() assert ((False, None) == var133.can_prepare(var32)) @asyncio.coroutine def function350(function271): var4234 = function271('GET', '/') var3290 = WebSocketResponse() yield from var3290.prepare(var4234) with pytest.raises(RuntimeError) as var847: var3290.can_prepare(var4234) assert ('Already started' in str(var847.value)) def function2110(): var1585 = WebSocketResponse() assert (not var1585.closed) assert (var1585.close_code is None) @asyncio.coroutine def function2561(function271, arg922): var2863 = function271('GET', '/') var2278 = WebSocketResponse() yield from var2278.prepare(var2863) var2278._reader.feed_data(WS_CLOSED_MESSAGE, 0) yield from var2278.close() arg922.spy(ws_logger, 'warning') var2278.send_str('string') assert ws_logger.warning.called @asyncio.coroutine def function2783(function271, arg1739): var4570 = function271('GET', '/') var3309 = WebSocketResponse() yield from var3309.prepare(var4570) var3309._reader.feed_data(WS_CLOSED_MESSAGE, 0) yield from var3309.close() arg1739.spy(ws_logger, 'warning') var3309.send_bytes(b'bytes') assert ws_logger.warning.called @asyncio.coroutine def function1203(function271, arg476): var1953 = function271('GET', '/') var1605 = WebSocketResponse() yield from var1605.prepare(var1953) var1605._reader.feed_data(WS_CLOSED_MESSAGE, 0) yield from var1605.close() arg476.spy(ws_logger, 'warning') var1605.send_json({'type': 'json', }) assert ws_logger.warning.called @asyncio.coroutine def function835(function271, arg1247): var816 = function271('GET', '/') var1269 = WebSocketResponse() yield from var1269.prepare(var816) var1269._reader.feed_data(WS_CLOSED_MESSAGE, 0) yield from var1269.close() arg1247.spy(ws_logger, 'warning') var1269.ping() assert ws_logger.warning.called @asyncio.coroutine def function2874(function271, arg512): var1102 = function271('GET', '/') var1066 = WebSocketResponse() yield from var1066.prepare(var1102) var1066._reader.feed_data(WS_CLOSED_MESSAGE, 0) yield from var1066.close() arg512.spy(ws_logger, 'warning') var1066.pong() assert ws_logger.warning.called @asyncio.coroutine def function716(function271, function61): var4554 = function271('GET', '/') var4135 = WebSocketResponse() yield from var4135.prepare(var4554) var4135._reader.feed_data(WS_CLOSED_MESSAGE, 0) assert yield from var4135.close(code=1, message='message1') assert var4135.closed assert (not yield from var4135.close(code=2, message='message2')) @asyncio.coroutine def function1314(function271): var183 = function271('POST', '/') var3527 = WebSocketResponse() with pytest.raises(HTTPMethodNotAllowed): yield from var3527.prepare(var183) @asyncio.coroutine def function1287(function271): var1020 = function271('GET', '/', headers=CIMultiDict({})) var1629 = WebSocketResponse() with pytest.raises(HTTPBadRequest): yield from var1629.prepare(var1020) @asyncio.coroutine def function1096(): var4148 = WebSocketResponse() with pytest.raises(RuntimeError): yield from var4148.close() @asyncio.coroutine def function1062(): var1034 = WebSocketResponse() with pytest.raises(RuntimeError): yield from var1034.write_eof() @asyncio.coroutine def function2567(function271): var424 = function271('GET', '/') var4602 = WebSocketResponse() yield from var4602.prepare(var424) var4602._reader.feed_data(WS_CLOSED_MESSAGE, 0) yield from var4602.close() yield from var4602.write_eof() yield from var4602.write_eof() yield from var4602.write_eof() @asyncio.coroutine def function2536(function271, arg68): var3402 = function271('GET', '/') var3771 = WebSocketResponse() yield from var3771.prepare(var3402) var3771._reader = mock.Mock() var2011 = ValueError() var1794 = helpers.create_future(arg68) var1794.set_exception(var2011) var3771._reader.read = make_mocked_coro(var1794) var3771._payload_writer.drain = mock.Mock() var3771._payload_writer.drain.return_value = helpers.create_future(arg68) var3771._payload_writer.drain.return_value.set_result(True) var2571 = yield from var3771.function1900() assert (var2571.type == WSMsgType.ERROR) assert (var2571.type is var2571.tp) assert (var2571.data is var2011) assert (var3771.exception() is var2011) @asyncio.coroutine def function2691(function271, arg857): var342 = function271('GET', '/') var4624 = WebSocketResponse() yield from var4624.prepare(var342) var4624._reader = mock.Mock() var3438 = helpers.create_future(arg857) var3438.set_exception(asyncio.CancelledError()) var4624._reader.read = make_mocked_coro(var3438) with pytest.raises(asyncio.CancelledError): yield from var4624.function1900() @asyncio.coroutine def function2107(function271, arg2001): var1118 = function271('GET', '/') var3191 = WebSocketResponse() yield from var3191.prepare(var1118) var3191._reader = mock.Mock() var4512 = helpers.create_future(arg2001) var4512.set_exception(asyncio.TimeoutError()) var3191._reader.read = make_mocked_coro(var4512) with pytest.raises(asyncio.TimeoutError): yield from var3191.function1900() @asyncio.coroutine def function2740(function271): var975 = function271('GET', '/') var3594 = WebSocketResponse() yield from var3594.prepare(var975) var3594._reader.feed_data(WS_CLOSED_MESSAGE, 0) yield from var3594.close() yield from var3594.function1900() yield from var3594.function1900() yield from var3594.function1900() yield from var3594.function1900() with pytest.raises(RuntimeError): yield from var3594.function1900() @asyncio.coroutine def function2521(function271): var4739 = function271('GET', '/') var1693 = WebSocketResponse() yield from var1693.prepare(var4739) var1693._waiting = True with pytest.raises(RuntimeError): yield from var1693.function1900() @asyncio.coroutine def function479(function271, arg926, arg363): var1796 = function271('GET', '/') var300 = WebSocketResponse() yield from var300.prepare(var1796) var300._reader = mock.Mock() var4357 = ValueError() var300._reader.read.return_value = helpers.create_future(arg926) var300._reader.read.return_value.set_exception(var4357) var300._payload_writer.drain = mock.Mock() var300._payload_writer.drain.return_value = helpers.create_future(arg926) var300._payload_writer.drain.return_value.set_result(True) yield from var300.close() assert var300.closed assert (var300.exception() is var4357) var300._closed = False var300._reader.read.return_value = helpers.create_future(arg926) var300._reader.read.return_value.set_exception(asyncio.CancelledError()) with pytest.raises(asyncio.CancelledError): yield from var300.close() assert (var300.close_code == 1006) @asyncio.coroutine def function113(function271): var2027 = function271('GET', '/') var2897 = WebSocketResponse() yield from var2897.prepare(var2027) var962 = ValueError() var2897._writer = mock.Mock() var2897._writer.close.side_effect = var962 yield from var2897.close() assert var2897.closed assert (var2897.exception() is var962) var2897._closed = False var2897._writer.close.side_effect = asyncio.CancelledError() with pytest.raises(asyncio.CancelledError): yield from var2897.close() @asyncio.coroutine def function265(function271): var2045 = function271('GET', '/') var4391 = WebSocketResponse() var4138 = yield from var4391.prepare(var2045) var1947 = yield from var4391.prepare(var2045) assert (var4138 is var1947)
[ "rkdls9@naver.com" ]
rkdls9@naver.com
e2ddd7b1f73bdd2609559ef2da7450c998f84263
20a24a0296308ba14318556a749c7a2f0eea0df1
/exercise-6.py
8ade018aaa7e838295d4eb12efa1ba9e74dabcb8
[]
no_license
geedtd/python-control-flow-lab
4604f6f2af7a207cc3a5381ec0ec66a762c9e69e
3e49421254a045b60f14b6b97ec43cbf03b324dc
refs/heads/master
2023-07-11T21:06:13.137437
2021-08-19T19:08:31
2021-08-19T19:08:31
397,521,736
0
0
null
null
null
null
UTF-8
Python
false
false
1,417
py
# exercise-06 What's the Season? # Write the code that: # 1. Prompts the user to enter the month (as three characters): # Enter the month of the year (Jan - Dec): # 2. Then prompts the user to enter the day of the month: # Enter the day of the month: # 3. Calculate what season it is based upon this chart: # Dec 21 - Mar 19: Winter # Mar 20 - Jun 20: Spring # Jun 21 - Sep 21: Summer # Sep 22 - Dec 20: Fall # 4. Print the result as follows: # <Mmm> <dd> is in <season> # Hints: # Consider using the in operator to check if a string is in a particular list/tuple like this: # if input_month in ('Jan', 'Feb', 'Mar'): # # After setting the likely season, you can use another if...elif...else statement to "adjust" if # the day number falls within a certain range. month = input('Enter the month of the year by the first three letters, (Jan - Dec): ').lower() day = int(input('Please enter the day of the month: ')) if month in ('jan', 'feb', 'mar'): season = 'Winter' elif month in ('apr', 'may', 'jun'): season = 'Spring' elif month in ('jul', 'aug', 'sep'): season = "Summer" else: season = 'Fall' if month == 'mar' and day > 19: season = 'Spring' elif month == 'jun' and day > 20: season = 'Summer' elif month == 'sep' and day > 21: season = 'Fall' elif month == 'dec' and day > 20: season = 'Winter' print(f'{month}{day} is in {season}')
[ "grcazares@gmail.com" ]
grcazares@gmail.com
a7ad22fbcc203b0880252839c8e371bcbecd096d
60a8566f36bcab9dbca6179e38e7c8d71b3c64ff
/easyleetcode/leetcodes/Leetcode_141_Linked_List_Cycle.py
929752fd6e9ad9e29a3f98d9f63de3a97fcbce04
[]
no_license
MuXTing/easy_leetcode
8a0e6729a1cdb018a16216275d58e2417a988c0d
270bb9ea7125be2f985f2058fb722ad16d524b57
refs/heads/master
2022-11-08T14:35:30.256234
2020-06-19T10:50:20
2020-06-19T10:50:20
273,611,176
2
1
null
2020-06-20T00:33:37
2020-06-20T00:33:37
null
UTF-8
Python
false
false
1,085
py
class ListNode: def __init__(self, x): self.val = x self.next = None def make_list(arr: list): head_node = None p_node = None for a in arr: new_node = ListNode(a) if head_node is None: head_node = new_node p_node = new_node else: p_node.next = new_node p_node = new_node return head_node def print_list(head: ListNode): while head is not None: print(head.val, end=',') head = head.next class Solution: def hasCycle(self, head: ListNode): slow = head fast = head # 无环,迟早退出 while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next # 有环,迟早遇到,返回True if slow == fast: return True return False s = Solution() a = [1, 2, 3, 4, 5] head = make_list(a) # 造环 head.next.next.next.next.next = head.next.next # 不能打印,死循环!@ # print_list(head) print(s.hasCycle(head))
[ "425776024@qq.com" ]
425776024@qq.com
7694b975971781a1dfeef12ac3a43da2fed03bce
c2d81f300c795ca3b5c31a47df60d0f488893183
/storage.py
2334efc490e217b069a92629fd882b08d929811b
[]
no_license
ethancaballero/ENAS_GAN
eaf68ecde016b62bafb79339b8e7d4848f71d2e1
6d1bf5cf2e372d575d4e24eb145ff3a355705ba4
refs/heads/master
2021-03-27T15:26:45.238425
2018-09-13T08:26:32
2018-09-13T08:26:32
112,182,744
0
0
null
null
null
null
UTF-8
Python
false
false
2,598
py
import torch import numpy as np class RolloutStorage(object): #def __init__(self, num_steps, num_processes, obs_shape, action_space, state_size): def __init__(self, num_steps, num_processes): #self.logprobs = torch.zeros(num_steps, num_processes) #self.ents = torch.zeros(num_steps, num_processes) self.logprobs = None self.ents = None #self.rewards = torch.zeros(num_processes) self.rewards_GAN = torch.zeros(num_processes) self.rewards_INCEPT = torch.zeros(num_processes) #self.values = torch.zeros(num_processes) self.values = None #ewma baseline based off of https://github.com/hans/thinstack-rl/blob/master/reinforce.py#L4 #self.avg_reward = torch.zeros(1) self.avg_reward_GAN = torch.zeros(1) self.avg_reward_INCEPT = torch.zeros(1) def cuda(self): self.logprobs = self.logprobs.cuda() self.ents = self.ents.cuda() self.rewards = self.rewards.cuda() self.values = self.values.cuda() #self.avg_reward = self.avg_reward.cuda() self.avg_reward_GAN = self.avg_reward_GAN.cuda() self.avg_reward_INCEPT = self.avg_reward_INCEPT.cuda() def insert(self, logprob, ent, value): self.logprobs = logprob self.ents = ent self.values = value def insert_reward_GAN(self, process, reward_GAN): self.rewards_GAN[process] = reward_GAN[0] def insert_reward_INCEPT(self, process, reward_INCEPT): self.rewards_INCEPT[process] = reward_INCEPT[0] def update_avg_reward_GAN(self, tau=.84): self.avg_reward_GAN = tau * self.avg_reward_GAN + (1. - tau) * torch.mean(self.rewards_GAN) def update_avg_reward_INCEPT(self, tau=.84): self.avg_reward_INCEPT = tau * self.avg_reward_INCEPT + (1. - tau) * torch.mean(self.rewards_INCEPT) def compute_returns(self, next_value, use_gae, gamma, tau): if use_gae: self.value_preds[-1] = next_value gae = 0 for step in reversed(range(self.rewards.size(0))): delta = self.rewards[step] + gamma * self.value_preds[step + 1] * self.masks[step + 1] - self.value_preds[step] gae = delta + gamma * tau * self.masks[step + 1] * gae self.returns[step] = gae + self.value_preds[step] else: self.returns[-1] = next_value for step in reversed(range(self.rewards.size(0))): self.returns[step] = self.returns[step + 1] * \ gamma * self.masks[step + 1] + self.rewards[step]
[ "noreply@github.com" ]
ethancaballero.noreply@github.com
da7c8c5fbc52f861d008af6c3f3db2ec98f84a06
a61e6860750fe4dab157a50335da2d46a7094b89
/backend/test_flaskr.py
d2b0bb357fd66b914997820d2da791bd81568019
[]
no_license
Tevinthuku/trivia
d96e54ba53ae9b4c7be3bdb7b03de11637c35ba4
44fe1ae56c5af210f8b0a6d132334dcca7a85e56
refs/heads/master
2023-01-12T02:54:15.926661
2019-12-26T10:26:27
2019-12-26T10:26:27
230,002,643
0
0
null
2023-01-05T03:38:07
2019-12-24T20:55:51
JavaScript
UTF-8
Python
false
false
5,372
py
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question, Category class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initialize app.""" self.app = create_app() self.client = self.app.test_client self.database_name = "trivia_test" self.database_path = "postgres://{}/{}".format( 'localhost:5432', self.database_name) setup_db(self.app, self.database_path) # binds the app to the current context with self.app.app_context(): self.db = SQLAlchemy() self.db.init_app(self.app) # create all tables self.db.create_all() def tearDown(self): """Executed after reach test""" pass """ TODO Write at least one test for each test for successful operation and for expected errors. """ def createQuestion(self): question = { "category": 1, "question": "How", "answer": "Now", "difficulty": 1 } return self.client().post("/questions", data=json.dumps(question), content_type="application/json") def getNumberOfQuestions(self): res = self.client().get("/questions") data = json.loads(res.data) return data.get("totalQuestions") def test_get_categories(self): res = self.client().get("/categories") data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertEqual(len(data["categories"]), 6) def test_get_questions(self): res = self.client().get("/questions") data = json.loads(res.data) self.assertEqual(data["status"], 200) self.assertEqual(len(data["questions"]), 10) def test_delete_specific_question(self): res = self.createQuestion() data = json.loads(res.data) question = data.get("question") question_id = question.get("id") original_number_of_questions = self.getNumberOfQuestions() res = self.client().delete(f'/questions/{question_id}') self.assertEqual(res.status_code, 200) number_of_questions = self.getNumberOfQuestions() self.assertEqual(number_of_questions, (original_number_of_questions-1)) def test_delete_nonexistent_question(self): res = self.client().delete("/questions/10000") self.assertEqual(res.status_code, 400) def test_question_creation(self): original_number_of_questions = self.getNumberOfQuestions() res = self.createQuestion() new_number_of_questions = self.getNumberOfQuestions() self.assertEqual(res.status_code, 200) self.assertEqual(new_number_of_questions, (original_number_of_questions+1)) def test_question_creation_with_failure(self): question = { "question": "How", "difficulty": 1 } res = self.client().post("/questions", data=json.dumps(question), content_type="application/json") self.assertEqual(res.status_code, 400) def test_questions_on_a_category(self): res = self.client().get("/categories/1/questions") data = json.loads(res.data) self.assertTrue(len(data["questions"])) def test_failure_on_questions_on_a_category_that_doesnt_exist(self): res = self.client().get("/categories/999/questions") data = json.loads(res.data) self.assertFalse(len(data["questions"])) def test_search(self): self.createQuestion() term = { "searchTerm": "How" } res = self.client().post("/questions/search", data=json.dumps(term), content_type="application/json") self.assertEqual(res.status_code, 200) data = json.loads(res.data) self.assertTrue(len(data.get("questions"))) def test_no_search_results(self): term = { "searchTerm": "HakunaMatata" } res = self.client().post("/questions/search", data=json.dumps(term), content_type="application/json") data = json.loads(res.data) self.assertEqual(len(data.get("questions")), 0) def test_play_game_successfully(self): req = { "previous_questions": [], "quiz_category": { "id": 4 } } res = self.client().post("/quizzes", data=json.dumps(req), content_type="application/json") data = json.loads(res.data) self.assertTrue(len(data["question"])) def test_end_of_game(self): data = { # to make sure I exhaust all questions "previous_questions": list(range(1, 1000)), "quiz_category": { "id": 0 } } res = self.client().post("/quizzes", data=json.dumps(data), content_type="application/json") data = json.loads(res.data) self.assertFalse((data["question"])) # Make the tests conveniently executable if __name__ == "__main__": unittest.main()
[ "tevinthuku@gmail.com" ]
tevinthuku@gmail.com
fbdcb9589ba842729ae4d22fd59dcf43629cf782
b88dd050c8c90974e0e702cf2c1c28e4c0ae7315
/signup/wsgi.py
1d9a0120d462e6acfb9ac19f2fd1f7bb7e433c7b
[]
no_license
shivamgupta1319/signin-signup-web
a94d63f1cc6e4a3d0cd5c676e166a4e1c6057267
3ee9ae953184fb7f3ee1b3ce72bb25625d81d78d
refs/heads/main
2023-05-05T21:06:44.181950
2021-05-25T09:48:32
2021-05-25T09:48:32
369,480,947
1
0
null
null
null
null
UTF-8
Python
false
false
405
py
""" WSGI config for signup project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'signup.settings') application = get_wsgi_application()
[ "noreply@github.com" ]
shivamgupta1319.noreply@github.com
91eeaf34fa16c48154032e68a62fbf9f2e700e2b
34599596e145555fde0d4264a1d222f951f49051
/pcat2py/class/250c5be8-5cc5-11e4-af55-00155d01fe08.py
2aee8561433065ca77ef70183312da311e12c807
[ "MIT" ]
permissive
phnomcobra/PCAT2PY
dc2fcbee142ce442e53da08476bfe4e68619346d
937c3b365cdc5ac69b78f59070be0a21bdb53db0
refs/heads/master
2021-01-11T02:23:30.669168
2018-02-13T17:04:03
2018-02-13T17:04:03
70,970,520
0
0
null
null
null
null
UTF-8
Python
false
false
1,489
py
#!/usr/bin/python ################################################################################ # 250c5be8-5cc5-11e4-af55-00155d01fe08 # # Justin Dierking # justindierking@hardbitsolutions.com # phnomcobra@gmail.com # # 10/24/2014 Original Construction ################################################################################ class Finding: def __init__(self): self.output = [] self.is_compliant = False self.uuid = "250c5be8-5cc5-11e4-af55-00155d01fe08" def check(self, cli): # Initialize Compliance self.is_compliant = False # Get Registry DWORD dword = cli.get_reg_dword(r'HKCU:\Software\Policies\Microsoft\Office\15.0\access\security', 'NoTBPromptUnsignedAddin') # Output Lines self.output = [r'HKCU:\Software\Policies\Microsoft\Office\15.0\access\security', ('NoTBPromptUnsignedAddin=' + str(dword))] if dword == 1: self.is_compliant = True return self.is_compliant def fix(self, cli): cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\15.0'") cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\15.0\access'") cli.powershell(r"New-Item -path 'HKCU:\Software\Policies\Microsoft\Office\15.0\access\security'") cli.powershell(r"Set-ItemProperty -path 'HKCU:\Software\Policies\Microsoft\Office\15.0\access\security' -name 'NoTBPromptUnsignedAddin' -value 1 -Type DWord")
[ "phnomcobra@gmail.com" ]
phnomcobra@gmail.com
1d267f12bc30c1301e0835471600d1303f6da9e5
ff34c33d648f2fe31f37bfd6955eb24a78085119
/d3b/d3b/wsgi.py
df02f125d438a99aae9adcdd1cec3936806a9753
[ "MIT" ]
permissive
sferanchuk/d3b_charts
42c2e6a8bfb680c2ff66aa1d22792b3be8487db1
93352e360650de14765e25702bfa4c20cf95898b
refs/heads/master
2020-03-19T19:19:12.947998
2019-08-24T14:01:20
2019-08-24T14:01:20
136,849,771
0
1
null
null
null
null
UTF-8
Python
false
false
384
py
""" WSGI config for d3b project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "d3b.settings") application = get_wsgi_application()
[ "sergey@feranchuk1.localdomain" ]
sergey@feranchuk1.localdomain
2ed11d08b3447f2b86fb61d41aa32622f485a3b1
4fed2e41870646fef108a369215111e3de0aecc9
/catan2/experiment/plot.py
384d0a55f6dc7d4e24f6bc4f6d26d7760423519c
[]
no_license
BradenC/Catan2
6107c162e960e07ffa4c3f1130295ff5a5273f97
edd9aa4c015950eeaf188aeff090f2c609317e92
refs/heads/main
2023-02-09T04:25:12.597837
2021-01-05T11:11:52
2021-01-05T11:11:52
326,974,336
0
0
null
null
null
null
UTF-8
Python
false
false
4,278
py
import numpy as np import matplotlib.pyplot as plt from catan2 import config, log """ These graphs show statistics about the experiment from many games played between two opponents. experiment = { config: { logging: ... training: ... ... } games: [ duration_seconds: 1, num_turns: 2, players: [ name: foo, num: 0, ... ], ... ] The games are pooled such that each data points represents the average experiment across multiple games. """ # The number of points to be shown on the graph num_groups = config['experiment']['num_sets'] group_size = None plottable_players = [] player_color = ['b', 'g'] player_shape = ['o', 'o'] class PlotPlayer: def __init__(self, name, color, shape): self.name = name self.color = color self.shape = shape @staticmethod def from_results(game_results): return [PlotPlayer(player['name'], player_color[player['num']], player_shape[player['num']]) for player in game_results[0]['players']] def pool(lst): """ return a new array that is an average grouping of the old array e.g. pool([1, 2, 3, 4, 5, 6], 3) => [(1 + 2 + 3)/3, (4 + 5 + 6)/3] => [2, 5] """ return [sum(lst[i:i+group_size])/group_size for i in range(0, len(lst), group_size)] def get_player_record(players, name): """ Given an array of players, return the one matching the given name """ return next(player for player in players if player['name'] == name) def plot_win_ratio(game_results, ax): """ Bar chart showing the ratio of wins between the two players """ ax.set_title(f'Win Ratio') p1_wins = [1 if game['winner'] == plottable_players[0].name else 0 for game in game_results] p2_wins = [1 if game['winner'] == plottable_players[1].name else 0 for game in game_results] p1_wins = pool(p1_wins) p2_wins = pool(p2_wins) rang = np.arange(num_groups) width = .8 ax.bar(rang, p1_wins, width, label=plottable_players[0].name, color=plottable_players[0].color) ax.bar(rang, p2_wins, width, label=plottable_players[1].name, color=plottable_players[1].color, bottom=p1_wins) ax.set_yticks([]) ax.set_xticks([]) ax.legend() def plot_victory_points(game_results, ax): """ Dot graph showing how many victory points each player achieved """ ax.set_title("Victory Points") ax.set_ylabel('VP') for player in plottable_players: player.victory_points = [get_player_record(game['players'], player.name)['victory_points'] for game in game_results] ax.plot(pool(player.victory_points), f'{player.shape}{player.color}', label=player.name) ax.set_ylim(0, 10) ax.set_xticks([]) ax.legend() # Currently not in use def plot_turn_length(results, ax): """ Line graph showing how many milliseconds each player took while deciding their turn """ ax.set_yticks([]) ax.set_xticks([]) ax.set_title('Turn Length (ms)') def plot_game_length(game_results, ax): """ Line graphs showing how many turns each game took """ ax.set_title('Turns Per Game') turns_per_game = [game['num_turns'] for game in game_results] ax.plot(pool(turns_per_game)) ax.set_xticks([]) ax.set_ylim(0) def plot_results(game_results): global plottable_players global group_size group_size = len(game_results) // num_groups plottable_players = PlotPlayer.from_results(game_results) fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) plot_win_ratio(game_results, ax1) plot_victory_points(game_results, ax2) plot_turn_length(game_results, ax3) plot_game_length(game_results, ax4) fig.canvas.set_window_title('Graphs of Catan') fig.suptitle(f'Agent Performance (avg over {group_size} games)') plt.show() # TODO def load_results(): return [] # Currently not in use def plot(): results = load_results() if not results: log.warn( message='No experiment to plot' ) log.debug( message=f'Plotting experiment from {len(results.games)} games' ) plot_results(results)
[ "bcok@marshallzehr.com" ]
bcok@marshallzehr.com
48124ed358f067933316a35ad95b494341423030
6e24dab6442976b5d5255c63273a3900d1389ddd
/PythonOOP1.py
c686011aab371378fb15ed507a21ced995204d29
[]
no_license
Kakashi-19/PYTHON
870a856cc7c3c481af3f21a479cf1c66324e35b1
2488b106d1442624c1a9cddc205e2e9d2a0ff66b
refs/heads/master
2022-12-04T07:59:50.231225
2020-08-27T07:00:11
2020-08-27T07:00:11
290,700,555
0
0
null
null
null
null
UTF-8
Python
false
false
498
py
# study of classes # python object oriented programming # instance variables class student: def __init__(self, name, email, id): self.name = name self.email = email self.id = id def printidCard(self): print("Student Name: " + self.name) print("Student Email ID: " + self.email) print("Student ID: " + str(self.id)) num = int(input()) for i in range(1, num + 1): name = input() email = input() id = int(input()) Student = student(name, email, id) student.printidCard(Student)
[ "wizzywoo19@gmail.com" ]
wizzywoo19@gmail.com
791ff957978b5f9103ef5f1046e89102cd6d7cd0
cf8dfec4ca3f93dd59457446ef6d4b524ebd15f0
/day_07/day7.py
c7fe680d5ba17766c101e6a18fcbb81926d0fb13
[ "MIT" ]
permissive
calvinbaart/advent_of_code_2020
a53393d32f29406452e5286e471b50a1a0e84a44
5e0cd40251d6aa463ef33d12b4794cb8d467c680
refs/heads/main
2023-01-31T01:52:43.977248
2020-12-12T02:17:38
2020-12-12T02:18:01
319,462,486
0
0
null
null
null
null
UTF-8
Python
false
false
2,730
py
def part1(graph): shiny_gold_bag = graph.get_node("shiny gold bag") num_bags = 0 open_list = [shiny_gold_bag] closed_list = [] while len(open_list) > 0: current = open_list.pop(0) closed_list.append(current.identifier) for x in current.back_links: if x in closed_list or current.back_links[x].from_node in open_list: continue num_bags += 1 open_list.append(current.back_links[x].from_node) return num_bags def part2(graph): shiny_gold_bag = graph.get_node("shiny gold bag") return shiny_gold_bag.weight() class Link: def __init__(self, weight, from_node, to_node): self.weight = weight self.from_node = from_node self.to_node = to_node class Node: def __init__(self, identifier): self.identifier = identifier self.links = {} self.back_links = {} def link(self, node, weight): self.links[node.identifier] = Link(weight, self, node) node.back_links[self.identifier] = self.links[node.identifier] def weight(self): weight = 0 for x in self.links: weight += self.links[x].weight * self.links[x].to_node.weight() + self.links[x].weight return weight class Graph: def __init__(self): self.nodes = {} def has_node(self, identifier): return identifier in self.nodes def get_node(self, identifier, create = False): if not create and not self.has_node(identifier): return None if not self.has_node(identifier): node = Node(identifier) self.nodes[identifier] = node else: node = self.nodes[identifier] return node def link(self, identifier, link_identifier, weight): if identifier == link_identifier or weight == 0: return from_node = self.get_node(identifier, True) to_node = self.get_node(link_identifier, True) from_node.link(to_node, weight) def create_graph(input): graph = Graph() for line in input: identifier, children = line.split("contain") identifier = identifier.strip().rstrip("s.") children = [x.strip().split(" ", 1) for x in children.split(",")] if children[0][0] == "no": continue children = [[int(x[0]), x[1].strip().rstrip("s.")] for x in children] for child in children: weight, link = child graph.link(identifier, link, weight) return graph input = [x.rstrip("\n") for x in open("input.txt", "r").readlines()] graph = create_graph(input) print(part1(graph)) print(part2(graph))
[ "calvin.baart@gmail.com" ]
calvin.baart@gmail.com
9db68d92da8b08a66e63c88f485495b7235d86f6
22a15cd6bb61e5dbf188161ffd8afb092502e793
/python/GraphicDraw.py
87721277e6e131b13784e27414f2e405cd0ddf33
[]
no_license
unspoken666/Code
9e27ac81d748357673930121ee56b6b61183a0c6
7a3581a8f4d0c7161443a7ffe04e3a778d2c9bbd
refs/heads/master
2022-05-17T14:41:27.326758
2022-03-16T01:32:46
2022-03-16T01:32:46
181,900,850
0
0
null
2022-02-23T01:36:13
2019-04-17T13:46:31
Java
UTF-8
Python
false
false
1,295
py
#!/usr/bin/env python # coding: utf-8 # In[ ]: #等边三角形绘制 import turtle as t #引进turtle库,绘图,并起了一个别名 t.fd(100) t.seth(120) t.fd(100) t.seth(240) t.fd(100) #叠加等边三角形绘制 import turtle as t t.fd(50) t.seth(120) t.fd(50) t.seth(0) t.fd(50) t.seth(-120) t.fd(50) t.seth(0) t.fd(50) t.seth(120) t.fd(100) t.seth(-120) t.fd(100) #无角正方形的绘制 import turtle as t d = 50 for i in range(4): t.seth(90*i) t.penup() t.fd(d) t.pendown() t.fd(2*d) t.penup() t.fd(d) #无角正方形的绘制 import turtle as t d = 50 for i in range(4): t.penup() t.fd(d) t.pendown() t.fd(2*d) t.penup() t.fd(d) t.right(90) #六角形绘制 import turtle as t t.seth(90) for i in range(6): t.right(60) t.fd(100) t.seth(30) for i in range(6): t.left(60) t.fd(100) t.right(120) t.fd(100) #正方形螺旋线绘制 import turtle as t for i in range(3,500,4): t.left(90) t.fd(i) t.left(90) t.fd(i) #绘制同切圆 import turtle turtle.pensize(2) turtle.circle(10) turtle.circle(40) turtle.circle(80) turtle.circle(160) #绘制五角星 from turtle import * color('red', 'red') begin_fill() for i in range(5): fd(200) rt(144) end_fill()
[ "906462762@qq.com" ]
906462762@qq.com
fa613c7016fde80d3ae780139e1b7154f59a7324
0ddcfcbfc3faa81c79e320c34c35a972dab86498
/puzzles/minesweeper.py
eaee546729defe2659cca39047e5ade770af7531
[]
no_license
IvanWoo/coding-interview-questions
3311da45895ac4f3c394b22530079c79a9215a1c
1312305b199b65a11804a000432ebe28d1fba87e
refs/heads/master
2023-08-09T19:46:28.278111
2023-06-21T01:47:07
2023-06-21T01:47:07
135,307,912
0
0
null
2023-07-20T12:14:38
2018-05-29T14:24:43
Python
UTF-8
Python
false
false
4,761
py
# https://leetcode.com/problems/minesweeper/ """ Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, digit ('1' to '8') represents how many mines are adjacent to this revealed square, and finally 'X' represents a revealed mine. Now given the next click position (row and column indices) among all the unrevealed squares ('M' or 'E'), return the board after revealing this position according to the following rules: If a mine ('M') is revealed, then the game is over - change it to 'X'. If an empty square ('E') with no adjacent mines is revealed, then change it to revealed blank ('B') and all of its adjacent unrevealed squares should be revealed recursively. If an empty square ('E') with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed. Example 1: Input: [['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'M', 'E', 'E'], ['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E']] Click : [3,0] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] Explanation: Example 2: Input: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] Click : [1,2] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'X', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] Explanation: Note: The range of the input matrix's height and width is [1,50]. The click position will only be an unrevealed square ('M' or 'E'), which also means the input board contains at least one clickable square. The input board won't be a stage when game is over (some mines have been revealed). For simplicity, not mentioned rules should be ignored in this problem. For example, you don't need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares. """ from typing import List # TLE def update_board(board: List[List[str]], click: List[int]) -> List[List[str]]: DIRS = [ (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), ] def get_around_mine(r, c): count = 0 row, col = len(board), len(board[0]) for i, j in DIRS: new_r, new_c = r + i, c + j if 0 <= new_r < row and 0 <= new_c < col and board[new_r][new_c] == "M": count += 1 return count s_r, s_c = click if board[s_r][s_c] == "M": board[s_r][s_c] = "X" return board row, col = len(board), len(board[0]) q = [(s_r, s_c)] while q: new_q = [] while q: r, c = q.pop() num = get_around_mine(r, c) if num == 0: board[r][c] = "B" for i, j in DIRS: new_r, new_c = r + i, c + j if ( 0 <= new_r < row and 0 <= new_c < col and board[new_r][new_c] == "E" ): new_q.append((new_r, new_c)) else: board[r][c] = str(num) q = new_q return board def update_board(board: List[List[str]], click: List[int]) -> List[List[str]]: d = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, -1), (1, 1), (-1, 1), (-1, -1)] m, n = len(board), len(board[0]) def dfs(B, i, j): if i < 0 or j < 0 or i >= m or j >= n: return if B[i][j] == "M": B[i][j] = "X" elif B[i][j] == "E": mine = sum( B[i + x][j + y] == "M" for x, y in d if 0 <= i + x < m and 0 <= j + y < n ) B[i][j] = mine and str(mine) or "B" for x, y in d * (not mine): dfs(B, i + x, j + y) return B return dfs(board, *click) if __name__ == "__main__": update_board( [ ["E", "E", "E", "E", "E", "E", "E", "E"], ["E", "E", "E", "E", "E", "E", "E", "M"], ["E", "E", "M", "E", "E", "E", "E", "E"], ["M", "E", "E", "E", "E", "E", "E", "E"], ["E", "E", "E", "E", "E", "E", "E", "E"], ["E", "E", "E", "E", "E", "E", "E", "E"], ["E", "E", "E", "E", "E", "E", "E", "E"], ["E", "E", "M", "M", "E", "E", "E", "E"], ], [0, 0], )
[ "tyivanwu@gmail.com" ]
tyivanwu@gmail.com
345bd1e203ee3a3953f29ba2ee5ab3c0c81b37f7
75fb75ffc7874b0a38712fe208535e2bc868631e
/myvenv/bin/pip3
08bc7cc56051bbac31edca340f6c40cdd5591730
[]
no_license
yksoon/django2
ca0182ab1d6de9ad6d0cbf1325c03c14be2fcaf9
f641c397bb27a5b0b6fd1d05168974e8c348f374
refs/heads/master
2022-04-26T05:56:21.014815
2020-05-02T15:04:10
2020-05-02T15:04:10
259,873,965
0
0
null
null
null
null
UTF-8
Python
false
false
276
#!/Users/yong-kwangsoon/Desktop/YKS_project/django2/myvenv/bin/python3 # -*- coding: utf-8 -*- import re import sys from pip._internal.cli.main import main if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit(main())
[ "ksyong1990@gmail.com" ]
ksyong1990@gmail.com
77ca8f9133574a51556dd6ec8a205d6906340c8c
0a8a08a88e4c393e460f87c6336e5e76f23bb774
/CRM_pro/crm_app/migrations/0001_initial.py
83b8048c15556d06ce259a13d7f168d0e6cbad6f
[]
no_license
Ashok-SMS/Django_CRM
83a7dc4996629c645267e688baec327bb3ba970a
246fb08fc5ec6a5b2ad46a2a6c5ede3dc2b34917
refs/heads/master
2021-02-14T15:19:20.891012
2020-03-04T05:32:45
2020-03-04T05:32:45
244,815,010
0
0
null
null
null
null
UTF-8
Python
false
false
2,048
py
# Generated by Django 2.2 on 2020-02-07 07:13 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customers', fields=[ ('cid', models.IntegerField(primary_key=True, serialize=False)), ('cname', models.CharField(max_length=50, null=True)), ('email', models.EmailField(max_length=50, null=True)), ('mobile', models.BigIntegerField(null=True)), ('created_date', models.DateField(auto_now_add=True, null=True)), ], ), migrations.CreateModel( name='Products', fields=[ ('pid', models.IntegerField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=50, null=True)), ('price', models.IntegerField(null=True)), ('created_date', models.DateField(auto_now_add=True, null=True)), ('description', models.CharField(blank=True, max_length=100)), ('category', models.CharField(choices=[('Indoor', 'Indoor'), ('Outdoor', 'Outdoor'), ('Anywhere', 'Anywhere')], max_length=100, null=True)), ], ), migrations.CreateModel( name='Orders', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status', models.CharField(choices=[('Delivered', 'Delivered'), ('Pending', 'Pending'), ('OutforDelivery', 'OutforDelivery')], max_length=50)), ('created_date', models.DateField(auto_now_add=True, null=True)), ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='crm_app.Customers')), ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='crm_app.Products')), ], ), ]
[ "palakiashokkumar@gmail.com" ]
palakiashokkumar@gmail.com
e4dcae2af72c3fbe8cea6ba2b07d1f7d7cd8ecce
503d2f8f5f5f547acb82f7299d86886691966ca5
/ahc/ahc017/ahc017_a_sub.py
a673051ad3671d5e38f64706eef867069957afa1
[]
no_license
Hironobu-Kawaguchi/atcoder
3fcb649cb920dd837a1ced6713bbb939ecc090a9
df4b55cc7d557bf61607ffde8bda8655cf129017
refs/heads/master
2023-08-21T14:13:13.856604
2023-08-12T14:53:03
2023-08-12T14:53:03
197,216,790
0
0
null
null
null
null
UTF-8
Python
false
false
3,324
py
# https://atcoder.jp/contests/ahc017/tasks/ahc017_a import sys input = sys.stdin.buffer.readline # sys.setrecursionlimit(10 ** 7) INF = 1001001001001 import random import time import heapq start = time.time() N, M, D, K = map(int, input().split()) G = [[] for _ in range(N)] to = [] for i in range(M): u, v, w = map(int, input().split()) u -= 1; v -= 1 G[u].append((v, w)) G[v].append((u, w)) to.append((u, v, w, i)) # print(G) xy = [] for i in range(N): x, y = map(int, input().split()) xy.append((x, y, i)) # xy_link = [] # for i in range(M): # x = min(xy[to[i][0]][0], xy[to[i][1]][0]) # y = min(xy[to[i][0]][1], xy[to[i][1]][1]) # xy_link.append((x, y, i)) # xy_link.sort() # print(xy_link) uc_list = [set() for _ in range(D)] r = [] for i in range(K*D): r.append(i%D + 1) if i<M: uc_list[i%D].add((to[i][0], to[i][1])) # r.append(xy_link[i][2]%D + 1) # else: # r.append(i%D + 1) # print(len(r), r) # print(uc_list) def bfs(start=0, under_construction=None): visited = [False] * N dist = [10**9] * N hq = [] heapq.heappush(hq, (0, start)) while hq: d, now = heapq.heappop(hq) if visited[now]: continue dist[now] = d visited[now] = True for nxt, w in G[now]: if visited[nxt]: continue if (now, nxt) in under_construction: continue if (nxt, now) in under_construction: continue heapq.heappush(hq, (d + w, nxt)) ret = 0 for i in range(N): ret += dist[i] # print(ret, dist) return ret def score_change(swap_idx): swap_set, swap_day = [], [] for i in range(2): swap_day.append(r[swap_idx[i]]) if swap_idx[i]<M: swap_set.append(set([(to[swap_idx[i]][0], to[swap_idx[i]][1])])) else: swap_set.append(set()) ret = 0 node_list = [] for i in range(2): if len(swap_set[i])==0: continue for tpl in swap_set[i]: for j in range(2): node_list.append(tpl[j]) node_list = list(set(node_list)) # print(node_list) for i in node_list: # for i in range(N): # for i in random.sample(range(N), 20): for j in range(2): # print(swap_set[j], swap_set[1-j]) ret += bfs(i, uc_list[swap_day[j]-1] - swap_set[j] | swap_set[1-j]) ret -= bfs(i, uc_list[swap_day[j]-1]) # print(ret) return ret # print(score_change((1, 2))) # cnt = 0 while time.time() < start + 5.9: # cnt += 1 swap_idx = random.sample(range(K*D), 2) if swap_idx[0]>=M and swap_idx[1]>=M: continue if r[swap_idx[0]]==r[swap_idx[1]]: continue sc = score_change(swap_idx) if sc<0: if swap_idx[0]<M: st0 = set([(to[swap_idx[0]][0], to[swap_idx[0]][1])]) else: st0 = set() if swap_idx[1]<M: st1 = set([(to[swap_idx[1]][0], to[swap_idx[1]][1])]) else: st1 = set() uc_list[r[swap_idx[0]]-1] -= st0 uc_list[r[swap_idx[0]]-1] |= st1 uc_list[r[swap_idx[1]]-1] -= st1 uc_list[r[swap_idx[1]]-1] |= st0 r[swap_idx[0]], r[swap_idx[1]] = r[swap_idx[1]], r[swap_idx[0]] # print(swap_idx, sc) # print(cnt) # print(len(r[:M])) print(*r[:M])
[ "hironobukawaguchi3@gmail.com" ]
hironobukawaguchi3@gmail.com
54bc57d52ef231983f566811e922901471074589
8184c3a69e9cb173408478b434a2f96fef36a144
/training/utils/util_cate.py
c53b002b4dc6ae89bca420a7620643ff4f9a1da6
[]
no_license
etxyc/emotion-recognition
5e59518949eee5fafa2e54383c937dbeecc54ee1
3ea5030ad373e350b841eb37b4b671eb0b631ebe
refs/heads/master
2020-07-10T20:28:08.311499
2019-08-25T23:54:35
2019-08-25T23:54:35
204,363,187
0
0
null
null
null
null
UTF-8
Python
false
false
2,436
py
import keras.backend as K """ metrics utils for category emotion training. The codes are copied from old Keras vervions, because they are removed from the current version. """ def precision(y_true, y_pred): """Precision metric. Only computes a batch-wise average of precision. Computes the precision, a metric for multi-label classification of how many selected items are relevant. """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) precision = true_positives / (predicted_positives + K.epsilon()) return precision def recall(y_true, y_pred): """Recall metric. Only computes a batch-wise average of recall. Computes the recall, a metric for multi-label classification of how many relevant items are selected. """ true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) recall = true_positives / (possible_positives + K.epsilon()) return recall def f1(y_true, y_pred, beta=1): """Computes the F score. The F score is the weighted harmonic mean of precision and recall. Here it is only computed as a batch-wise average, not globally. This is useful for multi-label classification, where input samples can be classified as sets of labels. By only using accuracy (precision) a model would achieve a perfect score by simply assigning every class to every input. In order to avoid this, a metric should penalize incorrect class assignments as well (recall). The F-beta score (ranged from 0.0 to 1.0) computes this, as a weighted mean of the proportion of correct class assignments vs. the proportion of incorrect class assignments. With beta = 1, this is equivalent to a F-measure. With beta < 1, assigning correct classes becomes more important, and with beta > 1 the metric is instead weighted towards penalizing incorrect class assignments. """ if beta < 0: raise ValueError('The lowest choosable beta is zero (only precision).') # If there are no true positives, fix the F score at 0 like sklearn. if K.sum(K.round(K.clip(y_true, 0, 1))) == 0: return 0 p = precision(y_true, y_pred) r = recall(y_true, y_pred) bb = beta ** 2 fbeta_score = (1 + bb) * (p * r) / (bb * p + r + K.epsilon()) return fbeta_score
[ "ethanxia@EMB.local" ]
ethanxia@EMB.local
349827b0cba0745615c3f69fb1bc90f9b61b7ed1
7449f87a1dc11302ed6b9fcc19b5fa736a5dc0e6
/objectGenerator.py
3b2bc94dc294394c77ee96459b8ec17ecea3d0cc
[]
no_license
Nosferatu/ZombieJumpNew
3fbcaa681e5ae93ced271dc704d093acb4c82423
0525d2d54d62655e86284d0cbb7922875d145b2b
refs/heads/master
2021-01-02T09:02:36.437806
2015-07-13T16:59:09
2015-07-13T16:59:09
38,773,964
0
0
null
null
null
null
UTF-8
Python
false
false
1,015
py
import pygame import os from pygame.locals import * from random import randint from player import * from zombies import * from specials import * def spawnRandomZombie(x): type = randint (0,100) if type <= 50: #60%-Chance, dass normaler Zombie spawned zombie = NormalZombie((x,370),0.01) elif type <= 80: #40% Chance, dass fetter Zombie spawned spawn = randint (350,700) zombie = FatZombie((x,390),0.01,spawn) elif type <= 93: # Chance, dass fetter Zombie spawned zombie = Charger((x,380),0.01) elif type <= 100: zombie = Spitter((x,370),0.01) return zombie def spawnNewCrate(cratetype): sgy = randint(250,400) sgx = randint(800,3000) crate = Crate((sgx,sgy),0.02,cratetype,2) return crate def spawnNewCafe(): sgy = randint(250,400) sgx = randint(1000,3000) cafe = Cafe((sgx,sgy),0.002) return cafe def spawnNewHeart(lifes): sgx = 750 - 50*lifes heart = Heart((sgx,20),0.005) return heart
[ "Cvalenta@freenet.de" ]
Cvalenta@freenet.de
56579644a7b9182ad9138725764c84f6330494db
a7122df9b74c12a5ef23af3cd38550e03a23461d
/Home/Pawn Brotherhood.py
c903a6f6664ec3ef67101fc7aadcfeba47d7782b
[]
no_license
CompetitiveCode/py.checkIO.org
c41f6901c576c614c4c77ad5c4162448828c3902
e34648dcec54364a7006e4d78313e9a6ec6c498b
refs/heads/master
2022-01-09T05:48:02.493606
2019-05-27T20:29:24
2019-05-27T20:29:24
168,180,493
1
0
null
null
null
null
UTF-8
Python
false
false
2,149
py
#Answer to Pawn Brotherhood - https://py.checkio.org/en/mission/pawn-brotherhood/ def safe_pawns(pawns: set) -> int: pawns = list(pawns) #Changed the set to list length = len(pawns) #To get the full length of list result = [] #To store the result for each pawn. This is done, so that even if a pawn is saved by two other pawns, still it is counted as 1, meaning safe. for i in range(length): #To traverse through all the pawns result.append(0) #To add a zero as the default value for all the pawns. 1 denotes safe and 0 denotes unsafe. start = 0 #Starting point while start < length: #To traverse through all the pawns for j in pawns: #To traverse through all the possible saviour of the above pawn i=pawns[start] #This is written just for readability. Else we can substitute 'i' for 'pawns[start]' everywhere in this loop if ord(i[0]) == ord(j[0])-1: #Checking whether we have any character just less than the character. Ex. for i[0] = c, then j[0] = d if int(i[1]) == int(j[1])+1: #Checking whether we have any value just less than the number, denoting the saving pawn to be either left or right of the saved pawn. result[start]=1 #If that pawn is saved by it, then we mark it as 1 elif ord(i[0]) == ord(j[0])+1: #Checking whether we have any character just greater than the character. Ex. for i[0] = c, then j[0] = b if int(i[1]) == int(j[1])+1: #Checking whether we have any value just less than the number, denoting the saving pawn to be either left or right of the saved pawn. result[start]=1 #If that pawn is saved by it, then we mark it as 1 start+=1 #To check the next value return sum(result) #The sum of the values will be the answer. if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6 assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1 print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
[ "admin@remedcu.com" ]
admin@remedcu.com
babbe9b364dd461cc7af6793f8c411e7b783d9bb
4c82b8f946dd18daea30adf3b2e0d8f20eb0616b
/Day_4_Class_vs_Instance.py
fb9ba40f488478c286045bea350b480f071b163e
[]
no_license
yyzz1010/hackerrank
2a323e4491e44c9de876fc1dd5e8102d4f66fbbb
2b0d1faa39cf948f5b38cdbb8c01d92fd14b68f3
refs/heads/master
2020-08-04T05:27:09.821959
2019-11-26T14:44:46
2019-11-26T14:44:46
212,022,258
0
0
null
null
null
null
UTF-8
Python
false
false
627
py
class Person: def __init__(self, initialAge): if initialAge < 0: age = 0 print('Age is not valid, setting age to 0.') def amIOld(self): if age < 13: print("You are young.") elif age >= 13 and age < 18: print("You are a teenager.") else: print("You are old.") def yearPasses(self): global age age += 1 t = int(input()) for i in range(0, t): age = int(input()) p = Person(age) p.amIOld() for j in range(0, 3): p.yearPasses() p.amIOld() print("")
[ "noreply@github.com" ]
yyzz1010.noreply@github.com
d57c5d2280e29b27290d36b73798f81515e851fc
27c2109f285073cae0a1adbb6f0bf3e7669691a8
/resources/flutterwave/__init__.py
be1e33d8805b5f14bcc74dcb66f36fd1d250a04c
[]
no_license
patrickf949/payout-apis
c572374efb1f2831684f10e601c239a1c8a380c9
e346e5cb872eff25cde3985b3d608951088fed4a
refs/heads/main
2023-08-23T21:46:01.608645
2021-10-18T13:33:58
2021-10-18T13:33:58
418,485,097
0
0
null
2021-10-18T12:50:53
2021-10-18T12:11:53
Python
UTF-8
Python
false
false
51
py
from resources.flutterwave.urls import flutterwave
[ "noreply@github.com" ]
patrickf949.noreply@github.com
699c354b2fa10c22f2d4f92f094d53f336bdc776
bcc66a1f1ac123d8be089763dfe936466dc8fb9b
/drivhire/__init__.py
81fc9b927b729ce7570227808a3fda2ac53c5207
[]
no_license
0xajay/drivhire
e4697de334e8df12aeb66a8c11361903f3d17247
7a3eb8da528267b52dffc40de6a2e5a9b35d949f
refs/heads/master
2023-01-05T00:45:29.991890
2020-10-30T05:24:17
2020-10-30T05:24:17
272,996,870
0
0
null
null
null
null
UTF-8
Python
false
false
290
py
from fastapi import FastAPI, Header, HTTPException, Depends from mongoengine import connect import os app = FastAPI() db = connect(host=os.environ.get('MONGO_URI')) from drivhire.modules.drivers.routes import router as driver_routes app.include_router(driver_routes, tags=["drivers"])
[ "0xajaykumar@gmail.com" ]
0xajaykumar@gmail.com
c16d11af15da2fec18b99fcca057d5801cc629f4
9d84b2861a2e3631153c9965e050062ec2a143a2
/clog/exceptions.py
7c768879d3edc17cfa1b2df83a6c6b2301c4eacc
[]
no_license
micaleel/clog
556812e542f49b76f40d3081e840033e592468cd
ed7374052a963ca9a7c0cfbd2725d29e6a5355bd
refs/heads/master
2021-01-05T21:07:03.229401
2020-03-21T21:51:24
2020-03-21T21:51:24
241,137,683
2
0
null
null
null
null
UTF-8
Python
false
false
221
py
class CLogException(Exception): ... class InvalidSite(ValueError): ... class MissingContent(ValueError): ... class GitException(CLogException): ... class GitPermissionDenied(GitException): ...
[ "micaleel@users.noreply.github.com" ]
micaleel@users.noreply.github.com
ca5f4630c195d1ad846a27c22a0b15bf19a1f760
18079758e1adaa6f46369847b7403e1969fd1400
/creglist_clone/my_app/migrations/0001_initial.py
8bf9d7ffe1ac026842e0565b061a225962f984b8
[ "MIT" ]
permissive
Reeju2019/CreglistApp_Clone
de44ccfd4555cd7e9563a97a31ddc6a834a3400d
1bf2763f4b330aef09744447038028063a034b02
refs/heads/main
2023-03-28T01:29:04.025311
2021-03-25T13:39:18
2021-03-25T13:39:18
351,312,682
0
0
null
null
null
null
UTF-8
Python
false
false
554
py
# Generated by Django 3.1.7 on 2021-03-25 05:47 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Search', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('search', models.CharField(max_length=500)), ('created', models.DateTimeField(auto_now=True)), ], ), ]
[ "reejubhattacherji@gmail.com" ]
reejubhattacherji@gmail.com
1898d9f40809eb25834ed6c585154245dbd7b80e
cc9a2632742b43feaf8fcf787a365792fb6ecad5
/_Tools/platform-tools/systrace/catapult/systrace/systrace/util.py
797d6756bc85d30dbff3a8da63b26b0acacea742
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
winest/ApkTools
1bc3212346ac42912df487cb26fa225b1b120264
349557ffe5aa65e64324b75b0777a775e384b832
refs/heads/master
2023-01-11T01:38:00.711072
2021-12-02T15:03:38
2021-12-02T15:03:38
179,802,183
1
0
BSD-3-Clause
2023-01-06T01:36:11
2019-04-06T07:27:31
C
UTF-8
Python
false
false
6,548
py
# Copyright 2015 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. import optparse import os import sys from devil.android.constants import chrome from devil.android import device_utils, device_errors class OptionParserIgnoreErrors(optparse.OptionParser): """Wrapper for OptionParser that ignores errors and produces no output.""" def error(self, msg): pass def exit(self, status=0, msg=None): pass def print_usage(self, out_file=None): pass def print_help(self, out_file=None): pass def print_version(self, out_file=None): pass def run_adb_shell(shell_args, device_serial): """Runs "adb shell" with the given arguments. Args: shell_args: array of arguments to pass to adb shell. device_serial: if not empty, will add the appropriate command-line parameters so that adb targets the given device. Returns: A tuple containing the adb output (stdout & stderr) and the return code from adb. Will exit if adb fails to start. """ adb_output = [] adb_return_code = 0 device = device_utils.DeviceUtils.HealthyDevices(device_arg=device_serial)[0] try: adb_output = device.RunShellCommand(shell_args, shell=False, check_return=True, raw_output=True) except device_errors.AdbShellCommandFailedError as error: adb_return_code = error.status adb_output = error.output return (adb_output, adb_return_code) def get_tracing_path(device_serial=None): """Uses adb to attempt to determine tracing path. The newest kernel doesn't support mounting debugfs, so the Android master uses tracefs to replace it. Returns: /sys/kernel/debug/tracing for device with debugfs mount support; /sys/kernel/tracing for device with tracefs support; /sys/kernel/debug/tracing if support can't be determined. """ mount_info_args = ['mount'] if device_serial is None: parser = OptionParserIgnoreErrors() parser.add_option('-e', '--serial', dest='device_serial', type='string') options, _ = parser.parse_args() device_serial = options.device_serial adb_output, adb_return_code = run_adb_shell(mount_info_args, device_serial, ) if adb_return_code == 0 and 'tracefs on /sys/kernel/tracing' in adb_output: return '/sys/kernel/tracing' return '/sys/kernel/debug/tracing' def get_device_sdk_version(): """Uses adb to attempt to determine the SDK version of a running device.""" getprop_args = ['getprop', 'ro.build.version.sdk'] # get_device_sdk_version() is called before we even parse our command-line # args. Therefore, parse just the device serial number part of the # command-line so we can send the adb command to the correct device. parser = OptionParserIgnoreErrors() parser.add_option('-e', '--serial', dest='device_serial', type='string') options, unused_args = parser.parse_args() # pylint: disable=unused-variable success = False adb_output, adb_return_code = run_adb_shell(getprop_args, options.device_serial) if adb_return_code == 0: # ADB may print output other than the version number (e.g. it chould # print a message about starting the ADB server). # Break the ADB output into white-space delimited segments. parsed_output = str.split(adb_output) if parsed_output: # Assume that the version number is the last thing printed by ADB. version_string = parsed_output[-1] if version_string: try: # Try to convert the text into an integer. version = int(version_string) except ValueError: version = -1 else: success = True if not success: print >> sys.stderr, adb_output raise Exception("Failed to get device sdk version") return version def get_supported_browsers(): """Returns the package names of all supported browsers.""" # Add aliases for backwards compatibility. supported_browsers = { 'stable': chrome.PACKAGE_INFO['chrome_stable'], 'beta': chrome.PACKAGE_INFO['chrome_beta'], 'dev': chrome.PACKAGE_INFO['chrome_dev'], 'build': chrome.PACKAGE_INFO['chrome'], } supported_browsers.update(chrome.PACKAGE_INFO) return supported_browsers def get_default_serial(): if 'ANDROID_SERIAL' in os.environ: return os.environ['ANDROID_SERIAL'] return None def get_main_options(parser): parser.add_option('-o', dest='output_file', help='write trace output to FILE', default=None, metavar='FILE') parser.add_option('-t', '--time', dest='trace_time', type='int', help='trace for N seconds', metavar='N') parser.add_option('-j', '--json', dest='write_json', default=False, action='store_true', help='write a JSON file') parser.add_option('--link-assets', dest='link_assets', default=False, action='store_true', help='(deprecated)') parser.add_option('--from-file', dest='from_file', action='store', help='read the trace from a file (compressed) rather than' 'running a live trace') parser.add_option('--asset-dir', dest='asset_dir', default='trace-viewer', type='string', help='(deprecated)') parser.add_option('-e', '--serial', dest='device_serial_number', default=get_default_serial(), type='string', help='adb device serial number') parser.add_option('--target', dest='target', default='android', type='string', help='choose tracing target (android or linux)') parser.add_option('--timeout', dest='timeout', type='int', help='timeout for start and stop tracing (seconds)') parser.add_option('--collection-timeout', dest='collection_timeout', type='int', help='timeout for data collection (seconds)') parser.add_option('-a', '--app', dest='app_name', default=None, type='string', action='store', help='enable application-level tracing for ' 'comma-separated list of app cmdlines') parser.add_option('-t', '--time', dest='trace_time', type='int', help='trace for N seconds', metavar='N') parser.add_option('-b', '--buf-size', dest='trace_buf_size', type='int', help='use a trace buffer size ' ' of N KB', metavar='N') return parser
[ "winestwinest@gmail.com" ]
winestwinest@gmail.com
a96a4d07bf19a9110c9b3333b24b0faf4840cb1a
4639143fac6ac71b71f6f7c5d1557c335d303487
/src/python_implementation/annbn_griewank.py
9c3dcbba6384ad8c0cd60b5d9c44dcdba8fc1cd7
[ "MIT" ]
permissive
nbakas/ANNBN.jl
233c5bd4dfa041d699feb8fff4e22676a4dfcd80
0658709f07cf3110266a862af63ee185e131eeaa
refs/heads/master
2022-07-17T01:48:41.139590
2022-06-18T11:56:26
2022-06-18T11:56:26
211,259,568
7
1
null
null
null
null
UTF-8
Python
false
false
2,301
py
import numpy as np from copy import copy import matplotlib.pyplot as plt from sklearn import linear_model import time from numpy import random,linalg,corrcoef,ones,float32,float64,c_,exp,log,zeros,mean t=np.atleast_2d r=np.repeat plot=plt.plot sort=np.sort fit=linear_model.LinearRegression().fit cor=np.corrcoef scatter=plt.scatter obs=10_000 vars=100 x=20*(random.rand(obs,vars).astype(np.float32)-1/2) y=np.zeros(obs).astype(np.float32) def func(x): # return sum(x**2) return 1 + (1/4000)*sum((x+7)**2) - np.prod(np.cos((x+7) / range(1, len(x)+1, 1))) v1=20*(np.random.rand(1000,2)-1/2) ov1=np.zeros(1000) for i in range(1000): ov1[i]=func(v1[i,:]) from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(v1[:,0],v1[:,1],ov1, c='r', marker='o') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') plt.show() for i in range(obs): y[i]=func(x[i,:]) mi=min(y);y-=mi;ma=max(y);y/=ma;y*=0.98;y+=0.01 x=np.concatenate((x,x**2,x**3),axis=1) #test obst=2*obs xt=20*(random.rand(obst,vars).astype(np.float32)-1/2) yt=np.zeros(obst).astype(np.float32) for i in range(obst): yt[i]=func(xt[i,:]) yt-=mi;yt/=ma;yt*=0.98;yt+=0.01 xt=np.concatenate((xt,xt**2,xt**3),axis=1) vars=x.shape[1] def sigm1(x): return log(exp(x)+1) def isigm1(x): return log(exp(x)-1) start1 = time.time() neurons=1000 xx=c_[ones((obs,1),float32), x] yy=isigm1(y) ikeep=int(1.2*round(obs/neurons)) w=zeros((vars+1,neurons),float32) for i in range(neurons): ira=random.randint(0, obs, ikeep) w[:,i],res1,rank1,s1=linalg.lstsq(xx[ira,:],yy[ira],rcond=-1) end1 = time.time() print("wwwww",end1 - start1) start2 = time.time() layer1=sigm1(xx@w) end2 = time.time() print("sigm1(xx@a_all)",end2 - start2) start = time.time() v,res1,rank1,s1=np.linalg.lstsq(layer1,y,rcond=-1) end = time.time() predi=layer1@v scatter(y,predi) co=cor(predi,y)[0,1] mo=mean(abs(predi-y)) print("LinearRegression",co," ",mo," ",end - start) # TEST xxt=c_[ones((obst,1),float32), xt] layer1t=sigm1(xxt@w) predt=layer1t@v scatter(yt,predt) cot=cor(predt,yt)[0,1] mot=mean(abs(predt-yt)) print("LinearRegression",cot," ",mot)
[ "noreply@github.com" ]
nbakas.noreply@github.com
a15b99f5029fbcef3be37b96c679f9557c902144
94fdf59a169d75d7e5a9f6f71a13d6d9bc27313b
/cogs/command_error_handle.py
4a0712ee6d3104a9b63f79873c93e03730ade4c2
[]
no_license
iotanum/iotabot
44dcc874618bb1f804b9909b17d2a8df43050726
9c44e6ac773e8b78351b1d9f6e2e1919e470cf04
refs/heads/master
2022-10-07T05:10:17.489463
2022-10-01T12:17:13
2022-10-01T12:17:13
150,031,980
2
0
null
2020-09-29T09:23:13
2018-09-23T22:45:04
Python
UTF-8
Python
false
false
1,530
py
import traceback import sys from discord.ext import commands import discord class CommandErrorHandler(commands.Cog): def __init__(self, bot): self.bot = bot async def on_command_error(self, ctx, error): """The event triggered when an error is raised while invoking a command. ctx : Context error : Exception""" if hasattr(ctx.command, 'on_error'): return ignored = (commands.CommandNotFound, commands.UserInputError) error = getattr(error, 'original', error) if isinstance(error, ignored): return elif isinstance(error, commands.DisabledCommand): return await ctx.send(f'{ctx.command} has been disabled.') elif isinstance(error, commands.NoPrivateMessage): try: return await ctx.author.send(f'{ctx.command} can not be used in Private Messages.') except: pass elif isinstance(error, commands.BadArgument): if ctx.command.qualified_name == 'tag list': return await ctx.send('I could not find that member. Please try again.') elif isinstance(error, commands.CommandOnCooldown): return await ctx.send('This command is on cooldown.') print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr) traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) async def setup(bot): await bot.add_cog(CommandErrorHandler(bot))
[ "evalduuk@gmail.com" ]
evalduuk@gmail.com
d2f4e0a31e16fb17c648a88c4c070fa5fd2b1f65
2c7184b3f4d8224e31693a6fc04764dd95eac641
/RESTAPI/truestcaller/views.py
42b49f95023af36bf3328b136c9bb6720455db0c
[]
no_license
vaibhavmathur13/Truestcaller
fb51ee40967465e75b37831a827899a092695c4c
182691555b75a4dd3bdc967ceb199f68e8aa3a0b
refs/heads/master
2023-07-19T23:06:36.015753
2021-08-23T15:55:30
2021-08-23T15:55:30
399,153,966
0
0
null
null
null
null
UTF-8
Python
false
false
6,223
py
from django.db.models import Q, Case, When, Value, Count, F from rest_framework import generics, status from rest_framework.authentication import TokenAuthentication from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.exceptions import ValidationError from truestcaller import ( serializers as truestcaller_serializers, models as truestcaller_models, utils as truestcaller_utils ) class RegisterUserAPIView(generics.CreateAPIView): """ This API registers a user in the app. It takes user's name, phone number, password. Email is optional. After registering, a user is given it's unique Token. """ serializer_class = truestcaller_serializers.UserRegisterSerializer permission_classes = [AllowAny] def post(self, request, *args, **kwargs): response = super(RegisterUserAPIView, self).post(request, *args, **kwargs) user = truestcaller_models.User.objects.get(phone_number=response.data['phone_number']) token = Token.objects.create(user=user) response.data['token'] = token.key return response class LoginUserAPIView(ObtainAuthToken): """ Endpoint of Login API to let users login. Token generated in Register API is validated here and then only a user can login. """ permission_classes = [AllowAny] def post(self, request, *args, **kwargs): # Give token along with user_id and password to user that provides valid credentials serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'phone_number': user.phone_number }) class PhoneNumberSpamMarkAPIView(generics.UpdateAPIView): """ After logging in, this API let users' update the Directory model's is_span attribute. A user can mark/unmark a number as spam. """ serializer_class = truestcaller_serializers.PhoneNumberSpamSerializer authentication_classes = [TokenAuthentication] def get_object(self): if not self.request.data.get('phone_number'): raise ValidationError('Please provide a valid phone number first.') if self.request.data.get('phone_number') == self.request.user.phone_number: raise ValidationError('You cannot mark/unmark yourself spam') instance, created = truestcaller_models.Directory.objects.get_or_create( added_by=self.request.user, phone_number=self.request.data['phone_number'] ) return instance class SearchByNameAPIView(generics.ListAPIView): """ This API, when provided a name, returns a list of all names where the instance of the provided name is present. This list is in order in which it should be according to the Project description. """ serializer_class = truestcaller_serializers.CustomSearchSerializer authentication_classes = [TokenAuthentication] def get_queryset(self): name = self.request.data.get('name', "") phone_number_list_for_people_email = truestcaller_utils.get_people_for_email(self.request.user.phone_number) query_set = truestcaller_models.Directory.objects.filter( Q(name__startswith=name) | Q(name__contains=name) ).annotate( is_start_with=Case( When(name__startswith=name, then=Value(True)), default=Value(False) ), email=Case( When(Q(phone_number__in=phone_number_list_for_people_email), then='added_by__email'), default=Value(None) ) ).order_by('-is_start_with') return query_set class SearchByPhoneNumberAPIView(generics.ListAPIView): """ When search is done through phone number, if the number is registered, the API will show the result from the registered users' table. If not registered, a list will return of all records. """ serializer_class = truestcaller_serializers.CustomSearchSerializer authentication_classes = [TokenAuthentication] def get_queryset(self): if not self.request.data.get('phone_number'): raise ValidationError("Enter a Phone Number to search") phone_number_list_for_people_email = truestcaller_utils.get_people_for_email(self.request.user.phone_number) phone_number = self.request.data['phone_number'] query_set = truestcaller_models.Directory.objects.filter( added_by__phone_number=phone_number, phone_number=phone_number ).annotate( email=Case( When(Q(phone_number__in=phone_number_list_for_people_email), then='added_by__email'), default=Value(None) ) ) if not query_set.exists(): query_set = truestcaller_models.Directory.objects.filter( phone_number=phone_number ) return query_set def get(self, request, *args, **kwargs): response = super(SearchByPhoneNumberAPIView, self).get(request, *args, **kwargs) spam_likelihood = truestcaller_models.Directory.objects.filter( phone_number=request.data.get('phone_number'), is_spam=True ).count() user_list = response.data response.data = {'user_list': user_list, 'spam_likelihood': spam_likelihood} return response class LogoutAPIView(APIView): """ This API simply deletes the token of a logged in user. This can happen either by clicking logout or the session times out. """ authentication_classes = [TokenAuthentication] def post(self, request, format=None): request.user.auth_token.delete() return Response(status=status.HTTP_200_OK)
[ "mathur130699@gmail.com" ]
mathur130699@gmail.com
efb4f8698221067b58b05fed45ebe5404532d5b4
bdf5ee86d1b9c49964d22139af1c8ec1a436889f
/polls/views.py
e80fd9aab4d2594732ad2bbb6dd071ff7f14cae2
[]
no_license
zhouyuyong/mysite
5d2f9638a222e563e243a437f6e411b5dba4a0e6
5af9cb019516c324a172422a9201e131a4b5db4f
refs/heads/master
2021-01-10T19:57:48.178941
2014-12-02T01:55:50
2014-12-02T01:55:50
25,450,211
1
2
null
null
null
null
UTF-8
Python
false
false
1,646
py
from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.views import generic from polls.models import Choice, Question class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): """Return the last five published questions.""" return Question.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) #def search(request): # if 'q' in request.GET: # message = 'You searched for : %r' % request.GET['q'] # else: # message = 'You submitted an empty form.' # return HttpResponse(message)
[ "zyy.bobo@gmail.com" ]
zyy.bobo@gmail.com
2920e203fc11befa607533797fa0a869e256256c
0bd465e3365ee99e9272562baf8fd1a61edd158b
/P-Uppgift/main.py
1ca5adb5431708747177e47f2519e279686b10e9
[]
no_license
FlyHighXX/Darwin
e6ea43c684aaeb386208f005c0511c149d3795e4
974392fcdbc70429f77a706bcc58b9fed7a2024d
refs/heads/master
2020-05-02T13:55:11.430396
2019-03-27T13:05:25
2019-03-27T13:05:25
177,995,537
0
0
null
null
null
null
UTF-8
Python
false
false
1,563
py
import Player def read_data(): player_list = [] file = open("data.txt","r") lines = file.read().splitlines() file.close() line_count = 0 for l in lines: line_count = line_count + 1 count=0 while count<line_count: name = lines[count] chance = float(lines[count + 1]) wins = int(lines[count + 2]) played = int(lines[count + 3]) player1 = Player.Player(name,chance,wins,played) player_list.append(player1) count = count + 4 return player_list def write_data(player_list): file = open("data.txt","w") for player in player_list: name = player.name chance = player.chance wins = player.wins played = player.played file.write(name + '\n') file.write(str(chance) + '\n') file.write(str(wins)+ '\n') file.write(str(played)+ '\n') file.close() def new_game(): x = 1 def show_table(): x = 2 def main(): player_list = read_data() while True: print("*** Welcome to tennis game ***") print("1. New Game\n2. Show Table\n3. Exit") try: x = input() x = int(x) if x == 1: new_game() elif x == 2: show_table() elif x == 3: write_data(player_list) exit() else: print("Number must be between 1 and 3!") except NameError: print("Input was not a number! Please try again") main()
[ "diacouthman@gmail.com" ]
diacouthman@gmail.com
3d00516d849973dd2fd3f65ddf205e06d57a0f36
2d27b88d6e9655708b091e5999637a1b4e685697
/petugas/urls.py
fc02dc693e21373091ba4b04b369a394620463a0
[]
no_license
wahyu-ramadhan69/sistem_inven_tes
276c89aed5a8d8cb0b1717aec4fa1861db19bfb2
49351353a5429981c6a546d9659ac17ca2b23df5
refs/heads/main
2023-06-11T08:20:50.124486
2021-06-27T15:34:09
2021-06-27T15:34:09
380,743,148
0
0
null
null
null
null
UTF-8
Python
false
false
2,786
py
from django.conf.urls import url, include from django.urls import path from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('', views.dashboard_op, name='dashboard_op'), path('pegawai_op/', views.pegawai_op, name='pegawai_op'), path('tambahpegawai/', views.tambahpegawai, name='tambahpegawai'), path('detail_pegawai/<int:id>', views.detail_pegawai, name='detail_pegawai'), path('edit_pegawai/<int:id>', views.edit_pegawai, name='edit_pegawai'), path('hapus_pegawai/<int:id>', views.hapus_pegawai, name='hapus_pegawai'), path('barang_op/', views.barang_op, name='barang_op'), path('tambah_barang/', views.tambah_barang, name='tambah_barang'), path('edit_barang/<int:id>', views.edit_barang, name='edit_barang'), path('hapus_barang/<int:id>', views.hapus_barang, name='hapus_barang'), path('detail_barang/<int:id>', views.detail_barang, name='detail_barang'), path('jenis_op/', views.jenis_op, name='jenis_op'), path('tambah_jenis/', views.tambah_jenis, name='tambah_jenis'), path('edit_jenis/<int:id>', views.edit_jenis, name='edit_jenis'), path('hapus_jenis/<int:id>', views.hapus_jenis, name='hapus_jenis'), path('peminjaman/', views.peminjaman, name='peminjaman'), path('hapus_pinjam/<int:id>', views.hapus_pinjam, name='hapus_pinjam'), path('pinjam_barang/<int:id>', views.pinjam_barang, name='pinjam_barang'), path('list_peminjaman/', views.list_peminjaman, name='list_peminjaman'), path('pengembalian/', views.pengembalian, name='pengembalian'), path('kembali_barang/<int:id>', views.kembali_barang, name='kembali_barang'), path('list_pengembalian/', views.list_pengembalian, name='list_pengembalian'), path('filter_pinjam/', views.filter_pinjam, name='filter_pinjam'), path('filter_kembali/', views.filter_kembali, name='filter_kembali'), path('c_pegawai', views.c_pegawai, name='c_pegawai'), path('c_barang', views.c_barang, name='c_barang'), path('c_peminjaman', views.c_peminjaman, name='c_peminjaman'), path('c_pengembalian', views.c_pengembalian, name='c_pengembalian'), path('c_f_peminjaman', views.c_f_peminjaman, name='c_f_peminjaman'), path('c_f_pengembalian', views.c_f_pengembalian, name='c_f_pengembalian'), path('coba', views.coba, name='coba'), path('hapus_keranjang/<int:id>', views.hapus_keranjang, name='hapus_keranjang'), path('hapus_keranjang2/<int:id>', views.hapus_keranjang2, name='hapus_keranjang2'), path('buat_pinjam', views.buat_pinjam, name='buat_pinjam'), path('pengembalian2/', views.pengembalian2, name='pengembalian2'), path('simple_upload/', views.simple_upload, name='simple_upload'), ]
[ "wahyu.ramadhani6969@gmail.com" ]
wahyu.ramadhani6969@gmail.com
616f3614b5aa6ab1b0ecc700b5cc7011614107ee
f07e2dd5d8dc613846958acfbbed3c8aa31a55a6
/0x11-python-network_1/3-error_code.py
58cd62ec833c7bb9f5240c93b47b2cb131dbea0d
[]
no_license
Andrecast/holbertonschool-higher_level_programming
5067e446a5e4bc9241135382f982d6a2f27f6250
c5a4c79ad01fd120dd08037f29bdf7a5c2e1f035
refs/heads/master
2023-08-14T02:40:15.805407
2021-09-23T00:52:17
2021-09-23T00:52:17
361,873,483
0
0
null
null
null
null
UTF-8
Python
false
false
314
py
#!/usr/bin/python3 """Error code""" import urllib.request import sys if __name__ == "__main__": try: with urllib.request.urlopen(sys.argv[1]) as url: s = url.read() print(s.decode('utf-8')) except urllib.error.HTTPError as e: print("Error code: {}".format(e.code))
[ "acastrillonpuerta@gmail.com" ]
acastrillonpuerta@gmail.com
0d19d3a14832ac71fed5dc4b702fe30b7ee26c06
0d63f253b6a1c8d5fa69d7cf794c9a370e85fb73
/preprocess/script/rename.py
e2526fad3e25ada611efaf62770d09bb0769fe7c
[]
no_license
MitsukiUsui/genome
b457b5c1ec631baca51d0cfa220ec7af9c79ce53
fa2458a86c6258105b7630287222e62fa6d9e42d
refs/heads/master
2021-01-19T22:23:36.402965
2017-11-05T09:16:14
2017-11-05T09:16:14
88,808,081
2
1
null
2017-11-05T09:16:14
2017-04-20T01:41:17
Jupyter Notebook
UTF-8
Python
false
false
1,371
py
import sys import subprocess sys.path.append("/home/mitsuki/altorf/genome/helper") from dbcontroller import DbController from myutil import myrun """ !!! UNTESTED with myrun !!! """ def main(): directory_lst = ["/data/mitsuki/data/refseq/genomic_fna", "/data/mitsuki/data/refseq/genomic_gff", "/data/mitsuki/data/refseq/cds_from_genomic"] suffix_lst = ["_genomic.fna", "_genomic.gff", "_cds_from_genomic.fna"] dbFilepath = "../db/altorf.db" dc = DbController(dbFilepath) taxid_lst = dc.get_target("preprocess") for _, taxid in enumerate(taxid_lst): row = dc.get_row(taxid) for directory, suffix in zip(directory_lst, suffix_lst): realFilepath = directory + "/" + row["ftp_basename"] + suffix gzFilepath = realFilepath + ".gz" linkFilepath = directory + "/" + str(taxid) + suffix # gunzip cmd = "gunzip {}".format(gzFilepath) success = myrun(cmd) if not(success): print("ERROR: {}".format(cmd)) # create symbolic link cmd = "ln -s {} {}".format(realFilepath, linkFilepath) success = myrun(cmd) if not(success): print("ERROR: {}".format(cmd)) if __name__ == "__main__": main()
[ "mitsuo.com.mu@gmail.com" ]
mitsuo.com.mu@gmail.com
2875602ac590e999b46721b79edf9aa554bcda98
3db6aac7c295de17fbe879349ac066b2f37328e2
/apps/course/migrations/0001_initial.py
72afe2a98baaf8a637b8638a3af78d470ca98690
[]
no_license
sabyrbekov/catalog_of_courses
629fed26eb1e18cdcc7e1a7d62b958d5b2ae3d3a
b96e264f7c757828bb4de54b7beea43742c8b36e
refs/heads/master
2023-01-20T14:34:48.309356
2020-12-04T21:49:48
2020-12-04T21:49:48
318,638,262
0
0
null
null
null
null
UTF-8
Python
false
false
840
py
# Generated by Django 3.1.3 on 2020-12-04 19:26 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CourseModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(db_index=True, max_length=255)), ('description', models.TextField()), ('start_date', models.DateField()), ('end_date', models.DateField()), ], options={ 'verbose_name': 'Курс', 'verbose_name_plural': 'Курсы', 'ordering': ('start_date',), }, ), ]
[ "aza10k@mail.ru" ]
aza10k@mail.ru
11d3461e2e4a73fcf8b10009c351751829506064
4ae3b27a1d782ae43bc786c841cafb3ace212d55
/Test_Slen/PythonSelFramework/tests/ex_5.py
ddc1761ab33da8a4af2aa9fca9c69f4566747e79
[]
no_license
bopopescu/Py_projects
c9084efa5aa02fd9ff6ed8ac5c7872fedcf53e32
a2fe4f198e3ca4026cf2e3e429ac09707d5a19de
refs/heads/master
2022-09-29T20:50:57.354678
2020-04-28T05:23:14
2020-04-28T05:23:14
null
0
0
null
null
null
null
UTF-8
Python
false
false
538
py
from selenium import webdriver import io # io.StringIO or io.BytesIO from PIL import Image driver = webdriver.Chrome() driver.get("https://www.lambdatest.com/") # 1. use relative path driver.save_screenshot('..\screenshot_1.png') # 2. driver.get_screenshot_as_file('screenshot_2.png') # 3. # screenshot = driver.get_screenshot_as_png() # # # screenshot_size = (20, 10, 480, 600) # image = Image.open(io.StringIO(screen)) # region = image.crop(screenshot_size) # region.save('screenshot_3.jpg', 'JPEG', optimize=True) driver.close()
[ "sunusd@yahoo.com" ]
sunusd@yahoo.com
af36b5d687b4d21a51051f3af63cb8e58446f9ce
2a3743ced45bd79826dcdc55f304da049f627f1b
/venv/lib/python3.7/site-packages/matplotlib/backends/backend_qt5.py
b4562db7f207f89ef4e24d801dd4acd4bfb6a9fe
[ "MIT" ]
permissive
Dimasik007/Deribit_funding_rate_indicator
12cc8cd7c0be564d6e34d9eae91940c62492ae2a
3251602ae5249069489834f9afb57b11ff37750e
refs/heads/master
2023-05-26T10:14:20.395939
2019-08-03T11:35:51
2019-08-03T11:35:51
198,705,946
5
3
MIT
2023-05-22T22:29:24
2019-07-24T20:32:19
Python
UTF-8
Python
false
false
40,230
py
import functools import os import re import signal import sys import traceback import matplotlib from matplotlib import backend_tools, cbook from matplotlib._pylab_helpers import Gcf from matplotlib.backend_bases import ( _Backend, FigureCanvasBase, FigureManagerBase, NavigationToolbar2, TimerBase, cursors, ToolContainerBase, StatusbarBase, MouseButton) import matplotlib.backends.qt_editor.figureoptions as figureoptions from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool from matplotlib.backend_managers import ToolManager from .qt_compat import ( QtCore, QtGui, QtWidgets, _getSaveFileName, is_pyqt5, __version__, QT_API) backend_version = __version__ # SPECIAL_KEYS are keys that do *not* return their unicode name # instead they have manually specified names SPECIAL_KEYS = {QtCore.Qt.Key_Control: 'control', QtCore.Qt.Key_Shift: 'shift', QtCore.Qt.Key_Alt: 'alt', QtCore.Qt.Key_Meta: 'super', QtCore.Qt.Key_Return: 'enter', QtCore.Qt.Key_Left: 'left', QtCore.Qt.Key_Up: 'up', QtCore.Qt.Key_Right: 'right', QtCore.Qt.Key_Down: 'down', QtCore.Qt.Key_Escape: 'escape', QtCore.Qt.Key_F1: 'f1', QtCore.Qt.Key_F2: 'f2', QtCore.Qt.Key_F3: 'f3', QtCore.Qt.Key_F4: 'f4', QtCore.Qt.Key_F5: 'f5', QtCore.Qt.Key_F6: 'f6', QtCore.Qt.Key_F7: 'f7', QtCore.Qt.Key_F8: 'f8', QtCore.Qt.Key_F9: 'f9', QtCore.Qt.Key_F10: 'f10', QtCore.Qt.Key_F11: 'f11', QtCore.Qt.Key_F12: 'f12', QtCore.Qt.Key_Home: 'home', QtCore.Qt.Key_End: 'end', QtCore.Qt.Key_PageUp: 'pageup', QtCore.Qt.Key_PageDown: 'pagedown', QtCore.Qt.Key_Tab: 'tab', QtCore.Qt.Key_Backspace: 'backspace', QtCore.Qt.Key_Enter: 'enter', QtCore.Qt.Key_Insert: 'insert', QtCore.Qt.Key_Delete: 'delete', QtCore.Qt.Key_Pause: 'pause', QtCore.Qt.Key_SysReq: 'sysreq', QtCore.Qt.Key_Clear: 'clear', } # define which modifier keys are collected on keyboard events. # elements are (mpl names, Modifier Flag, Qt Key) tuples SUPER = 0 ALT = 1 CTRL = 2 SHIFT = 3 MODIFIER_KEYS = [('super', QtCore.Qt.MetaModifier, QtCore.Qt.Key_Meta), ('alt', QtCore.Qt.AltModifier, QtCore.Qt.Key_Alt), ('ctrl', QtCore.Qt.ControlModifier, QtCore.Qt.Key_Control), ('shift', QtCore.Qt.ShiftModifier, QtCore.Qt.Key_Shift), ] if sys.platform == 'darwin': # in OSX, the control and super (aka cmd/apple) keys are switched, so # switch them back. SPECIAL_KEYS.update({QtCore.Qt.Key_Control: 'cmd', # cmd/apple key QtCore.Qt.Key_Meta: 'control', }) MODIFIER_KEYS[0] = ('cmd', QtCore.Qt.ControlModifier, QtCore.Qt.Key_Control) MODIFIER_KEYS[2] = ('ctrl', QtCore.Qt.MetaModifier, QtCore.Qt.Key_Meta) cursord = { cursors.MOVE: QtCore.Qt.SizeAllCursor, cursors.HAND: QtCore.Qt.PointingHandCursor, cursors.POINTER: QtCore.Qt.ArrowCursor, cursors.SELECT_REGION: QtCore.Qt.CrossCursor, cursors.WAIT: QtCore.Qt.WaitCursor, } # make place holder qApp = None def _create_qApp(): """ Only one qApp can exist at a time, so check before creating one. """ global qApp if qApp is None: app = QtWidgets.QApplication.instance() if app is None: # check for DISPLAY env variable on X11 build of Qt if is_pyqt5(): try: from PyQt5 import QtX11Extras is_x11_build = True except ImportError: is_x11_build = False else: is_x11_build = hasattr(QtGui, "QX11Info") if is_x11_build: display = os.environ.get('DISPLAY') if display is None or not re.search(r':\d', display): raise RuntimeError('Invalid DISPLAY variable') try: QtWidgets.QApplication.setAttribute( QtCore.Qt.AA_EnableHighDpiScaling) except AttributeError: # Attribute only exists for Qt>=5.6. pass qApp = QtWidgets.QApplication([b"matplotlib"]) qApp.lastWindowClosed.connect(qApp.quit) else: qApp = app if is_pyqt5(): try: qApp.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps) except AttributeError: pass def _allow_super_init(__init__): """ Decorator for ``__init__`` to allow ``super().__init__`` on PyQt4/PySide2. """ if QT_API == "PyQt5": return __init__ else: # To work around lack of cooperative inheritance in PyQt4, PySide, # and PySide2, when calling FigureCanvasQT.__init__, we temporarily # patch QWidget.__init__ by a cooperative version, that first calls # QWidget.__init__ with no additional arguments, and then finds the # next class in the MRO with an __init__ that does support cooperative # inheritance (i.e., not defined by the PyQt4, PySide, PySide2, sip # or Shiboken packages), and manually call its `__init__`, once again # passing the additional arguments. qwidget_init = QtWidgets.QWidget.__init__ def cooperative_qwidget_init(self, *args, **kwargs): qwidget_init(self) mro = type(self).__mro__ next_coop_init = next( cls for cls in mro[mro.index(QtWidgets.QWidget) + 1:] if cls.__module__.split(".")[0] not in [ "PyQt4", "sip", "PySide", "PySide2", "Shiboken"]) next_coop_init.__init__(self, *args, **kwargs) @functools.wraps(__init__) def wrapper(self, *args, **kwargs): with cbook._setattr_cm(QtWidgets.QWidget, __init__=cooperative_qwidget_init): __init__(self, *args, **kwargs) return wrapper class TimerQT(TimerBase): ''' Subclass of :class:`backend_bases.TimerBase` that uses Qt timer events. Attributes ---------- interval : int The time between timer events in milliseconds. Default is 1000 ms. single_shot : bool Boolean flag indicating whether this timer should operate as single shot (run once and then stop). Defaults to False. callbacks : list Stores list of (func, args) tuples that will be called upon timer events. This list can be manipulated directly, or the functions `add_callback` and `remove_callback` can be used. ''' def __init__(self, *args, **kwargs): TimerBase.__init__(self, *args, **kwargs) # Create a new timer and connect the timeout() signal to the # _on_timer method. self._timer = QtCore.QTimer() self._timer.timeout.connect(self._on_timer) self._timer_set_interval() def _timer_set_single_shot(self): self._timer.setSingleShot(self._single) def _timer_set_interval(self): self._timer.setInterval(self._interval) def _timer_start(self): self._timer.start() def _timer_stop(self): self._timer.stop() class FigureCanvasQT(QtWidgets.QWidget, FigureCanvasBase): # map Qt button codes to MouseEvent's ones: buttond = {QtCore.Qt.LeftButton: MouseButton.LEFT, QtCore.Qt.MidButton: MouseButton.MIDDLE, QtCore.Qt.RightButton: MouseButton.RIGHT, QtCore.Qt.XButton1: MouseButton.BACK, QtCore.Qt.XButton2: MouseButton.FORWARD, } @_allow_super_init def __init__(self, figure): _create_qApp() super().__init__(figure=figure) self.figure = figure # We don't want to scale up the figure DPI more than once. # Note, we don't handle a signal for changing DPI yet. figure._original_dpi = figure.dpi self._update_figure_dpi() # In cases with mixed resolution displays, we need to be careful if the # dpi_ratio changes - in this case we need to resize the canvas # accordingly. We could watch for screenChanged events from Qt, but # the issue is that we can't guarantee this will be emitted *before* # the first paintEvent for the canvas, so instead we keep track of the # dpi_ratio value here and in paintEvent we resize the canvas if # needed. self._dpi_ratio_prev = None self._draw_pending = False self._is_drawing = False self._draw_rect_callback = lambda painter: None self.setAttribute(QtCore.Qt.WA_OpaquePaintEvent) self.setMouseTracking(True) self.resize(*self.get_width_height()) # Key auto-repeat enabled by default self._keyautorepeat = True palette = QtGui.QPalette(QtCore.Qt.white) self.setPalette(palette) def _update_figure_dpi(self): dpi = self._dpi_ratio * self.figure._original_dpi self.figure._set_dpi(dpi, forward=False) @property def _dpi_ratio(self): # Not available on Qt4 or some older Qt5. try: # self.devicePixelRatio() returns 0 in rare cases return self.devicePixelRatio() or 1 except AttributeError: return 1 def _update_dpi(self): # As described in __init__ above, we need to be careful in cases with # mixed resolution displays if dpi_ratio is changing between painting # events. # Return whether we triggered a resizeEvent (and thus a paintEvent) # from within this function. if self._dpi_ratio != self._dpi_ratio_prev: # We need to update the figure DPI. self._update_figure_dpi() self._dpi_ratio_prev = self._dpi_ratio # The easiest way to resize the canvas is to emit a resizeEvent # since we implement all the logic for resizing the canvas for # that event. event = QtGui.QResizeEvent(self.size(), self.size()) self.resizeEvent(event) # resizeEvent triggers a paintEvent itself, so we exit this one # (after making sure that the event is immediately handled). return True return False def get_width_height(self): w, h = FigureCanvasBase.get_width_height(self) return int(w / self._dpi_ratio), int(h / self._dpi_ratio) def enterEvent(self, event): try: x, y = self.mouseEventCoords(event.pos()) except AttributeError: # the event from PyQt4 does not include the position x = y = None FigureCanvasBase.enter_notify_event(self, guiEvent=event, xy=(x, y)) def leaveEvent(self, event): QtWidgets.QApplication.restoreOverrideCursor() FigureCanvasBase.leave_notify_event(self, guiEvent=event) def mouseEventCoords(self, pos): """Calculate mouse coordinates in physical pixels Qt5 use logical pixels, but the figure is scaled to physical pixels for rendering. Transform to physical pixels so that all of the down-stream transforms work as expected. Also, the origin is different and needs to be corrected. """ dpi_ratio = self._dpi_ratio x = pos.x() # flip y so y=0 is bottom of canvas y = self.figure.bbox.height / dpi_ratio - pos.y() return x * dpi_ratio, y * dpi_ratio def mousePressEvent(self, event): x, y = self.mouseEventCoords(event.pos()) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_press_event(self, x, y, button, guiEvent=event) def mouseDoubleClickEvent(self, event): x, y = self.mouseEventCoords(event.pos()) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_press_event(self, x, y, button, dblclick=True, guiEvent=event) def mouseMoveEvent(self, event): x, y = self.mouseEventCoords(event) FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=event) def mouseReleaseEvent(self, event): x, y = self.mouseEventCoords(event) button = self.buttond.get(event.button()) if button is not None: FigureCanvasBase.button_release_event(self, x, y, button, guiEvent=event) if is_pyqt5(): def wheelEvent(self, event): x, y = self.mouseEventCoords(event) # from QWheelEvent::delta doc if event.pixelDelta().x() == 0 and event.pixelDelta().y() == 0: steps = event.angleDelta().y() / 120 else: steps = event.pixelDelta().y() if steps: FigureCanvasBase.scroll_event( self, x, y, steps, guiEvent=event) else: def wheelEvent(self, event): x = event.x() # flipy so y=0 is bottom of canvas y = self.figure.bbox.height - event.y() # from QWheelEvent::delta doc steps = event.delta() / 120 if event.orientation() == QtCore.Qt.Vertical: FigureCanvasBase.scroll_event( self, x, y, steps, guiEvent=event) def keyPressEvent(self, event): key = self._get_key(event) if key is not None: FigureCanvasBase.key_press_event(self, key, guiEvent=event) def keyReleaseEvent(self, event): key = self._get_key(event) if key is not None: FigureCanvasBase.key_release_event(self, key, guiEvent=event) @cbook.deprecated("3.0", alternative="event.guiEvent.isAutoRepeat") @property def keyAutoRepeat(self): """ If True, enable auto-repeat for key events. """ return self._keyautorepeat @keyAutoRepeat.setter def keyAutoRepeat(self, val): self._keyautorepeat = bool(val) def resizeEvent(self, event): # _dpi_ratio_prev will be set the first time the canvas is painted, and # the rendered buffer is useless before anyways. if self._dpi_ratio_prev is None: return w = event.size().width() * self._dpi_ratio h = event.size().height() * self._dpi_ratio dpival = self.figure.dpi winch = w / dpival hinch = h / dpival self.figure.set_size_inches(winch, hinch, forward=False) # pass back into Qt to let it finish QtWidgets.QWidget.resizeEvent(self, event) # emit our resize events FigureCanvasBase.resize_event(self) def sizeHint(self): w, h = self.get_width_height() return QtCore.QSize(w, h) def minumumSizeHint(self): return QtCore.QSize(10, 10) def _get_key(self, event): if not self._keyautorepeat and event.isAutoRepeat(): return None event_key = event.key() event_mods = int(event.modifiers()) # actually a bitmask # get names of the pressed modifier keys # bit twiddling to pick out modifier keys from event_mods bitmask, # if event_key is a MODIFIER, it should not be duplicated in mods mods = [name for name, mod_key, qt_key in MODIFIER_KEYS if event_key != qt_key and (event_mods & mod_key) == mod_key] try: # for certain keys (enter, left, backspace, etc) use a word for the # key, rather than unicode key = SPECIAL_KEYS[event_key] except KeyError: # unicode defines code points up to 0x0010ffff # QT will use Key_Codes larger than that for keyboard keys that are # are not unicode characters (like multimedia keys) # skip these # if you really want them, you should add them to SPECIAL_KEYS MAX_UNICODE = 0x10ffff if event_key > MAX_UNICODE: return None key = chr(event_key) # qt delivers capitalized letters. fix capitalization # note that capslock is ignored if 'shift' in mods: mods.remove('shift') else: key = key.lower() mods.reverse() return '+'.join(mods + [key]) def new_timer(self, *args, **kwargs): # docstring inherited return TimerQT(*args, **kwargs) def flush_events(self): # docstring inherited qApp.processEvents() def start_event_loop(self, timeout=0): # docstring inherited if hasattr(self, "_event_loop") and self._event_loop.isRunning(): raise RuntimeError("Event loop already running") self._event_loop = event_loop = QtCore.QEventLoop() if timeout: timer = QtCore.QTimer.singleShot(timeout * 1000, event_loop.quit) event_loop.exec_() def stop_event_loop(self, event=None): # docstring inherited if hasattr(self, "_event_loop"): self._event_loop.quit() def draw(self): """Render the figure, and queue a request for a Qt draw. """ # The renderer draw is done here; delaying causes problems with code # that uses the result of the draw() to update plot elements. if self._is_drawing: return with cbook._setattr_cm(self, _is_drawing=True): super().draw() self.update() def draw_idle(self): """Queue redraw of the Agg buffer and request Qt paintEvent. """ # The Agg draw needs to be handled by the same thread matplotlib # modifies the scene graph from. Post Agg draw request to the # current event loop in order to ensure thread affinity and to # accumulate multiple draw requests from event handling. # TODO: queued signal connection might be safer than singleShot if not (self._draw_pending or self._is_drawing): self._draw_pending = True QtCore.QTimer.singleShot(0, self._draw_idle) def _draw_idle(self): if self.height() < 0 or self.width() < 0: self._draw_pending = False if not self._draw_pending: return try: self.draw() except Exception: # Uncaught exceptions are fatal for PyQt5, so catch them instead. traceback.print_exc() finally: self._draw_pending = False def drawRectangle(self, rect): # Draw the zoom rectangle to the QPainter. _draw_rect_callback needs # to be called at the end of paintEvent. if rect is not None: def _draw_rect_callback(painter): pen = QtGui.QPen(QtCore.Qt.black, 1 / self._dpi_ratio, QtCore.Qt.DotLine) painter.setPen(pen) painter.drawRect(*(pt / self._dpi_ratio for pt in rect)) else: def _draw_rect_callback(painter): return self._draw_rect_callback = _draw_rect_callback self.update() class MainWindow(QtWidgets.QMainWindow): closing = QtCore.Signal() def closeEvent(self, event): self.closing.emit() QtWidgets.QMainWindow.closeEvent(self, event) class FigureManagerQT(FigureManagerBase): """ Attributes ---------- canvas : `FigureCanvas` The FigureCanvas instance num : int or str The Figure number toolbar : qt.QToolBar The qt.QToolBar window : qt.QMainWindow The qt.QMainWindow """ def __init__(self, canvas, num): FigureManagerBase.__init__(self, canvas, num) self.canvas = canvas self.window = MainWindow() self.window.closing.connect(canvas.close_event) self.window.closing.connect(self._widgetclosed) self.window.setWindowTitle("Figure %d" % num) image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.svg') self.window.setWindowIcon(QtGui.QIcon(image)) # Give the keyboard focus to the figure instead of the # manager; StrongFocus accepts both tab and click to focus and # will enable the canvas to process event w/o clicking. # ClickFocus only takes the focus is the window has been # clicked # on. http://qt-project.org/doc/qt-4.8/qt.html#FocusPolicy-enum or # http://doc.qt.digia.com/qt/qt.html#FocusPolicy-enum self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus) self.canvas.setFocus() self.window._destroying = False self.toolmanager = self._get_toolmanager() self.toolbar = self._get_toolbar(self.canvas, self.window) self.statusbar = None if self.toolmanager: backend_tools.add_tools_to_manager(self.toolmanager) if self.toolbar: backend_tools.add_tools_to_container(self.toolbar) self.statusbar = StatusbarQt(self.window, self.toolmanager) if self.toolbar is not None: self.window.addToolBar(self.toolbar) if not self.toolmanager: # add text label to status bar statusbar_label = QtWidgets.QLabel() self.window.statusBar().addWidget(statusbar_label) self.toolbar.message.connect(statusbar_label.setText) tbs_height = self.toolbar.sizeHint().height() else: tbs_height = 0 # resize the main window so it will display the canvas with the # requested size: cs = canvas.sizeHint() sbs = self.window.statusBar().sizeHint() height = cs.height() + tbs_height + sbs.height() self.window.resize(cs.width(), height) self.window.setCentralWidget(self.canvas) if matplotlib.is_interactive(): self.window.show() self.canvas.draw_idle() self.window.raise_() def full_screen_toggle(self): if self.window.isFullScreen(): self.window.showNormal() else: self.window.showFullScreen() def _widgetclosed(self): if self.window._destroying: return self.window._destroying = True try: Gcf.destroy(self.num) except AttributeError: pass # It seems that when the python session is killed, # Gcf can get destroyed before the Gcf.destroy # line is run, leading to a useless AttributeError. def _get_toolbar(self, canvas, parent): # must be inited after the window, drawingArea and figure # attrs are set if matplotlib.rcParams['toolbar'] == 'toolbar2': toolbar = NavigationToolbar2QT(canvas, parent, False) elif matplotlib.rcParams['toolbar'] == 'toolmanager': toolbar = ToolbarQt(self.toolmanager, self.window) else: toolbar = None return toolbar def _get_toolmanager(self): if matplotlib.rcParams['toolbar'] == 'toolmanager': toolmanager = ToolManager(self.canvas.figure) else: toolmanager = None return toolmanager def resize(self, width, height): # these are Qt methods so they return sizes in 'virtual' pixels # so we do not need to worry about dpi scaling here. extra_width = self.window.width() - self.canvas.width() extra_height = self.window.height() - self.canvas.height() self.window.resize(width+extra_width, height+extra_height) def show(self): self.window.show() self.window.activateWindow() self.window.raise_() def destroy(self, *args): # check for qApp first, as PySide deletes it in its atexit handler if QtWidgets.QApplication.instance() is None: return if self.window._destroying: return self.window._destroying = True if self.toolbar: self.toolbar.destroy() self.window.close() def get_window_title(self): return self.window.windowTitle() def set_window_title(self, title): self.window.setWindowTitle(title) class NavigationToolbar2QT(NavigationToolbar2, QtWidgets.QToolBar): message = QtCore.Signal(str) def __init__(self, canvas, parent, coordinates=True): """ coordinates: should we show the coordinates on the right? """ self.canvas = canvas self.parent = parent self.coordinates = coordinates self._actions = {} """A mapping of toolitem method names to their QActions""" QtWidgets.QToolBar.__init__(self, parent) NavigationToolbar2.__init__(self, canvas) def _icon(self, name): if is_pyqt5(): name = name.replace('.png', '_large.png') pm = QtGui.QPixmap(os.path.join(self.basedir, name)) if hasattr(pm, 'setDevicePixelRatio'): pm.setDevicePixelRatio(self.canvas._dpi_ratio) return QtGui.QIcon(pm) def _init_toolbar(self): self.basedir = os.path.join(matplotlib.rcParams['datapath'], 'images') for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.addSeparator() else: a = self.addAction(self._icon(image_file + '.png'), text, getattr(self, callback)) self._actions[callback] = a if callback in ['zoom', 'pan']: a.setCheckable(True) if tooltip_text is not None: a.setToolTip(tooltip_text) if text == 'Subplots': a = self.addAction(self._icon("qt4_editor_options.png"), 'Customize', self.edit_parameters) a.setToolTip('Edit axis, curve and image parameters') # Add the x,y location widget at the right side of the toolbar # The stretch factor is 1 which means any resizing of the toolbar # will resize this label instead of the buttons. if self.coordinates: self.locLabel = QtWidgets.QLabel("", self) self.locLabel.setAlignment( QtCore.Qt.AlignRight | QtCore.Qt.AlignTop) self.locLabel.setSizePolicy( QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Ignored)) labelAction = self.addWidget(self.locLabel) labelAction.setVisible(True) # Esthetic adjustments - we need to set these explicitly in PyQt5 # otherwise the layout looks different - but we don't want to set it if # not using HiDPI icons otherwise they look worse than before. if is_pyqt5() and self.canvas._dpi_ratio > 1: self.setIconSize(QtCore.QSize(24, 24)) self.layout().setSpacing(12) @cbook.deprecated("3.1") @property def buttons(self): return {} @cbook.deprecated("3.1") @property def adj_window(self): return None if is_pyqt5(): # For some reason, self.setMinimumHeight doesn't seem to carry over to # the actual sizeHint, so override it instead in order to make the # aesthetic adjustments noted above. def sizeHint(self): size = super().sizeHint() size.setHeight(max(48, size.height())) return size def edit_parameters(self): axes = self.canvas.figure.get_axes() if not axes: QtWidgets.QMessageBox.warning( self.parent, "Error", "There are no axes to edit.") return elif len(axes) == 1: ax, = axes else: titles = [ ax.get_label() or ax.get_title() or " - ".join(filter(None, [ax.get_xlabel(), ax.get_ylabel()])) or f"<anonymous {type(ax).__name__}>" for ax in axes] duplicate_titles = [ title for title in titles if titles.count(title) > 1] for i, ax in enumerate(axes): if titles[i] in duplicate_titles: titles[i] += f" (id: {id(ax):#x})" # Deduplicate titles. item, ok = QtWidgets.QInputDialog.getItem( self.parent, 'Customize', 'Select axes:', titles, 0, False) if not ok: return ax = axes[titles.index(item)] figureoptions.figure_edit(ax, self) def _update_buttons_checked(self): # sync button checkstates to match active mode self._actions['pan'].setChecked(self._active == 'PAN') self._actions['zoom'].setChecked(self._active == 'ZOOM') def pan(self, *args): super().pan(*args) self._update_buttons_checked() def zoom(self, *args): super().zoom(*args) self._update_buttons_checked() def set_message(self, s): self.message.emit(s) if self.coordinates: self.locLabel.setText(s) def set_cursor(self, cursor): self.canvas.setCursor(cursord[cursor]) def draw_rubberband(self, event, x0, y0, x1, y1): height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 rect = [int(val) for val in (x0, y0, x1 - x0, y1 - y0)] self.canvas.drawRectangle(rect) def remove_rubberband(self): self.canvas.drawRectangle(None) def configure_subplots(self): image = os.path.join(matplotlib.rcParams['datapath'], 'images', 'matplotlib.png') dia = SubplotToolQt(self.canvas.figure, self.canvas.parent()) dia.setWindowIcon(QtGui.QIcon(image)) dia.exec_() def save_figure(self, *args): filetypes = self.canvas.get_supported_filetypes_grouped() sorted_filetypes = sorted(filetypes.items()) default_filetype = self.canvas.get_default_filetype() startpath = os.path.expanduser( matplotlib.rcParams['savefig.directory']) start = os.path.join(startpath, self.canvas.get_default_filename()) filters = [] selectedFilter = None for name, exts in sorted_filetypes: exts_list = " ".join(['*.%s' % ext for ext in exts]) filter = '%s (%s)' % (name, exts_list) if default_filetype in exts: selectedFilter = filter filters.append(filter) filters = ';;'.join(filters) fname, filter = _getSaveFileName(self.canvas.parent(), "Choose a filename to save to", start, filters, selectedFilter) if fname: # Save dir for next time, unless empty str (i.e., use cwd). if startpath != "": matplotlib.rcParams['savefig.directory'] = ( os.path.dirname(fname)) try: self.canvas.figure.savefig(fname) except Exception as e: QtWidgets.QMessageBox.critical( self, "Error saving file", str(e), QtWidgets.QMessageBox.Ok, QtWidgets.QMessageBox.NoButton) def set_history_buttons(self): can_backward = self._nav_stack._pos > 0 can_forward = self._nav_stack._pos < len(self._nav_stack._elements) - 1 if 'back' in self._actions: self._actions['back'].setEnabled(can_backward) if 'forward' in self._actions: self._actions['forward'].setEnabled(can_forward) class SubplotToolQt(UiSubplotTool): def __init__(self, targetfig, parent): UiSubplotTool.__init__(self, None) self._figure = targetfig for lower, higher in [("bottom", "top"), ("left", "right")]: self._widgets[lower].valueChanged.connect( lambda val: self._widgets[higher].setMinimum(val + .001)) self._widgets[higher].valueChanged.connect( lambda val: self._widgets[lower].setMaximum(val - .001)) self._attrs = ["top", "bottom", "left", "right", "hspace", "wspace"] self._defaults = {attr: vars(self._figure.subplotpars)[attr] for attr in self._attrs} # Set values after setting the range callbacks, but before setting up # the redraw callbacks. self._reset() for attr in self._attrs: self._widgets[attr].valueChanged.connect(self._on_value_changed) for action, method in [("Export values", self._export_values), ("Tight layout", self._tight_layout), ("Reset", self._reset), ("Close", self.close)]: self._widgets[action].clicked.connect(method) def _export_values(self): # Explicitly round to 3 decimals (which is also the spinbox precision) # to avoid numbers of the form 0.100...001. dialog = QtWidgets.QDialog() layout = QtWidgets.QVBoxLayout() dialog.setLayout(layout) text = QtWidgets.QPlainTextEdit() text.setReadOnly(True) layout.addWidget(text) text.setPlainText( ",\n".join("{}={:.3}".format(attr, self._widgets[attr].value()) for attr in self._attrs)) # Adjust the height of the text widget to fit the whole text, plus # some padding. size = text.maximumSize() size.setHeight( QtGui.QFontMetrics(text.document().defaultFont()) .size(0, text.toPlainText()).height() + 20) text.setMaximumSize(size) dialog.exec_() def _on_value_changed(self): self._figure.subplots_adjust(**{attr: self._widgets[attr].value() for attr in self._attrs}) self._figure.canvas.draw_idle() def _tight_layout(self): self._figure.tight_layout() for attr in self._attrs: widget = self._widgets[attr] widget.blockSignals(True) widget.setValue(vars(self._figure.subplotpars)[attr]) widget.blockSignals(False) self._figure.canvas.draw_idle() def _reset(self): for attr, value in self._defaults.items(): self._widgets[attr].setValue(value) class ToolbarQt(ToolContainerBase, QtWidgets.QToolBar): def __init__(self, toolmanager, parent): ToolContainerBase.__init__(self, toolmanager) QtWidgets.QToolBar.__init__(self, parent) self._toolitems = {} self._groups = {} @property def _icon_extension(self): if is_pyqt5(): return '_large.png' return '.png' def add_toolitem( self, name, group, position, image_file, description, toggle): button = QtWidgets.QToolButton(self) button.setIcon(self._icon(image_file)) button.setText(name) if description: button.setToolTip(description) def handler(): self.trigger_tool(name) if toggle: button.setCheckable(True) button.toggled.connect(handler) else: button.clicked.connect(handler) self._toolitems.setdefault(name, []) self._add_to_group(group, name, button, position) self._toolitems[name].append((button, handler)) def _add_to_group(self, group, name, button, position): gr = self._groups.get(group, []) if not gr: sep = self.addSeparator() gr.append(sep) before = gr[position] widget = self.insertWidget(before, button) gr.insert(position, widget) self._groups[group] = gr def _icon(self, name): pm = QtGui.QPixmap(name) if hasattr(pm, 'setDevicePixelRatio'): pm.setDevicePixelRatio(self.toolmanager.canvas._dpi_ratio) return QtGui.QIcon(pm) def toggle_toolitem(self, name, toggled): if name not in self._toolitems: return for button, handler in self._toolitems[name]: button.toggled.disconnect(handler) button.setChecked(toggled) button.toggled.connect(handler) def remove_toolitem(self, name): for button, handler in self._toolitems[name]: button.setParent(None) del self._toolitems[name] class StatusbarQt(StatusbarBase, QtWidgets.QLabel): def __init__(self, window, *args, **kwargs): StatusbarBase.__init__(self, *args, **kwargs) QtWidgets.QLabel.__init__(self) window.statusBar().addWidget(self) def set_message(self, s): self.setText(s) class ConfigureSubplotsQt(backend_tools.ConfigureSubplotsBase): def trigger(self, *args): NavigationToolbar2QT.configure_subplots( self._make_classic_style_pseudo_toolbar()) class SaveFigureQt(backend_tools.SaveFigureBase): def trigger(self, *args): NavigationToolbar2QT.save_figure( self._make_classic_style_pseudo_toolbar()) class SetCursorQt(backend_tools.SetCursorBase): def set_cursor(self, cursor): NavigationToolbar2QT.set_cursor( self._make_classic_style_pseudo_toolbar(), cursor) class RubberbandQt(backend_tools.RubberbandBase): def draw_rubberband(self, x0, y0, x1, y1): NavigationToolbar2QT.draw_rubberband( self._make_classic_style_pseudo_toolbar(), None, x0, y0, x1, y1) def remove_rubberband(self): NavigationToolbar2QT.remove_rubberband( self._make_classic_style_pseudo_toolbar()) class HelpQt(backend_tools.ToolHelpBase): def trigger(self, *args): QtWidgets.QMessageBox.information(None, "Help", self._get_help_html()) class ToolCopyToClipboardQT(backend_tools.ToolCopyToClipboardBase): def trigger(self, *args, **kwargs): pixmap = self.canvas.grab() qApp.clipboard().setPixmap(pixmap) backend_tools.ToolSaveFigure = SaveFigureQt backend_tools.ToolConfigureSubplots = ConfigureSubplotsQt backend_tools.ToolSetCursor = SetCursorQt backend_tools.ToolRubberband = RubberbandQt backend_tools.ToolHelp = HelpQt backend_tools.ToolCopyToClipboard = ToolCopyToClipboardQT @cbook.deprecated("3.0") def error_msg_qt(msg, parent=None): if not isinstance(msg, str): msg = ','.join(map(str, msg)) QtWidgets.QMessageBox.warning(None, "Matplotlib", msg, QtGui.QMessageBox.Ok) @cbook.deprecated("3.0") def exception_handler(type, value, tb): """Handle uncaught exceptions It does not catch SystemExit """ msg = '' # get the filename attribute if available (for IOError) if hasattr(value, 'filename') and value.filename is not None: msg = value.filename + ': ' if hasattr(value, 'strerror') and value.strerror is not None: msg += value.strerror else: msg += str(value) if len(msg): error_msg_qt(msg) @_Backend.export class _BackendQT5(_Backend): required_interactive_framework = "qt5" FigureCanvas = FigureCanvasQT FigureManager = FigureManagerQT @staticmethod def trigger_manager_draw(manager): manager.canvas.draw_idle() @staticmethod def mainloop(): old_signal = signal.getsignal(signal.SIGINT) # allow SIGINT exceptions to close the plot window. signal.signal(signal.SIGINT, signal.SIG_DFL) try: qApp.exec_() finally: # reset the SIGINT exception handler signal.signal(signal.SIGINT, old_signal)
[ "dmitriy00vn@gmail.com" ]
dmitriy00vn@gmail.com
50af001fda531249a70452aea587a1eb3c199ced
bc56efb9dc901501b8675b0a6e549b10a206934d
/tst.py
82d76815638e81739cd3b6863fbedffe38403fab
[]
no_license
fogcitymarathoner/python_cherrypy_proxy
a35d13a1f8ba4c6bbc2ceed65f7711d621179f48
d822c544a9724b62429cba096a8863ad88ab8dc1
refs/heads/master
2021-01-19T13:01:40.589377
2015-02-12T18:49:08
2015-02-12T18:49:08
30,224,643
0
0
null
null
null
null
UTF-8
Python
false
false
130
py
import requests payload = {'url': 'http://ebay.com'} r = requests.get('http://69.181.224.185:8081', params=payload) print r.text
[ "marc.f.condon@hp.com" ]
marc.f.condon@hp.com
5c2e698e5e46d53efc1f6abca6bd3909ba0f59c8
439b5668cedf50840f35eca34710cb767ddcb278
/list1.py
aad20403cf3212f4551c78b2aa260f4c880903da
[]
no_license
mjhiremath/Practice
4840f5e588522d38c98b99d17c337107b2e03359
332294ac0ff60917efc92e676697811884408c0c
refs/heads/master
2022-05-26T08:05:07.486311
2020-05-02T08:10:06
2020-05-02T08:10:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
968
py
list1 = [10,9,3,7,2,1,21,1,561,1,1,96,1] list1.sort() print(list1) list1.reverse() print(list1) list1 = [1,2,3,4,5,6] list2 = [] for each in list1: if each%2==0: list2.append(each*each) print(list2) port = [[80,'http'],[20,'ftp'],[23,'telnet'],[443,'https'],[53,'DNS']] port1 = dict(port) for key in port1.keys(): print(key) print(port1.keys()) print(port1.values()) #print(port1.keys()) port2={22:"SSH"} port1.update(port2) print(port1) print(port1.items()) for k,v in port1.items(): print(k, " :" ,v) list4 = [1,2,3,4,5] list5 = ["a","b","c","d","e"] #print(len(list4)) dict2={} for index in range(len(list4)): dict2[list4[index]]=list5[index] print(dict2) list6 = ["Londo","New yyork","Paris","Hyderbad"] for each in list6: str1 = each print(each) for s in str1: if s == 'o': break print(s,end="") print("\n") for each in list6: if each== "Paris": continue print(each)
[ "MJ.Hiremath@MoviusCorp.com" ]
MJ.Hiremath@MoviusCorp.com
2962546557c72373f1a398c3a9edf065e418bbc2
8bf260274799b0b162694100346a12a09e33d3f6
/asp_scanzip/aspscan_zip_package/tasks/scan_data.py
5ab8a7ca34d6f4d46ac18ab830980dcb7b9c6885
[]
no_license
galaxyLiu/File_processing_tools
df6cf4f0d80123338045ff614df3222c67797314
278692261e3c6a00b4120e74a21224479cfaf13a
refs/heads/main
2023-03-27T19:40:28.470395
2021-03-29T07:20:42
2021-03-29T07:20:42
352,238,219
1
0
null
null
null
null
UTF-8
Python
false
false
1,920
py
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils.es import ElasticObj from utils.scan import ScanObj from utils.xls import XlwtObj from common.handler_data import get_xls_data, get_scan_data from config import * from urllib.parse import unquote def taskjob(task, xls_outfile): esobj = ElasticObj(es_address) xlwtobj = XlwtObj(xls_outfile) scan = ScanObj(base_url) # subtask_url = base_url + task + "/" + subtask + "/" subtask_url = base_url + task + "/" poolnames = scan.get_dirname(subtask_url) pool_pro_names = {} for poolname in poolnames: scan_jobs = scan.get_dirname(subtask_url + poolname) pool_pro_names[poolname] = scan_jobs for poolname in poolnames: ncols = 1 if pool_pro_names[poolname]: sheet = xlwtobj.get_sheet(poolname.strip("/")) xlwtobj.sheet_write_header(sheet, scan_title) for scan_job in pool_pro_names[poolname]: final_name = scan.get_dirname(subtask_url + poolname + scan_job) final_name = unquote(final_name[0], encoding="utf8") if final_name == "无存活主机/": continue else: task_url = subtask_url + poolname + scan_job + 'index.html' scan_job = unquote(scan_job, encoding="utf8") scan_id = scan_job.split('_')[0] result = scan.get_result(task_url, scan_id, task, poolname) xlwtobj.sheet_write(sheet, ncols, len(scan_title), get_xls_data(result)) # 将cmdb数据写入excel表中 ncols = ncols + len(result) index = scan_index_prefix + poolname.strip("/") esobj.bulk_Index_Data(index, get_scan_data(index, result)) # 以index的形式存入es中,会覆盖以前的数据 def scan_data_job(): task = lm_task_name xls_outfile = scan_report_xsl taskjob(task, xls_outfile)
[ "1183682032@qq.com" ]
1183682032@qq.com
bcfbacb0b1e224b592e8ab8306f8fabddbb89fd5
abc3c06ca144334fd85daee4750a6381e807e331
/src/specktre/utils.py
15307738db2ce3261bbb8edfc251f30750472c97
[ "MIT" ]
permissive
alexwlchan/specktre
fd5e1f58fbb812e89a7c983a89c1488b8128f097
dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc
refs/heads/development
2023-02-07T11:04:27.778883
2019-04-07T05:44:04
2019-04-07T05:44:04
71,328,631
13
7
MIT
2019-04-07T11:57:26
2016-10-19T07:04:36
Python
UTF-8
Python
false
false
1,040
py
# -*- encoding: utf-8 -*- """Utility functions.""" import os import random import string def _candidate_filenames(): """Generates filenames of the form 'specktre_123AB.png'. The random noise is five characters long, which allows for 62^5 = 916 million possible filenames. """ while True: random_stub = ''.join([ random.choice(string.ascii_letters + string.digits) for _ in range(5) ]) yield 'specktre_%s.png' % random_stub def new_filename(): """Returns a filename for a new specktre image. This filename is of the form 'specktre_123AB.png' and does not already exist when this function is called. """ for filename in _candidate_filenames(): if not os.path.exists(filename): return filename # Since _candidate_filenames() is an infinite generator and produces # millions of options, this branch should never be hit in practice. # Keeps coverage happy. else: assert False, 'Should not be reachable'
[ "alex@alexwlchan.net" ]
alex@alexwlchan.net
f4cbe8768b6b892341f1b65d50ed02c9b5bce84c
e78f7584f5326b855cbd635001fd21977280ffcd
/ECI/primitive_datatype/key_methods.py
4eec9f0f7c0cbb6da475853f32718c548c1ec7c5
[]
no_license
alle-zhinzher/Books
ca039a5ecc3df443f7f73c9bd1a11cd428ecda5f
4c3dcbac60b7a5777431b2f4f5a7827b5cd4bd2d
refs/heads/master
2020-04-19T03:57:02.776733
2019-04-22T03:22:50
2019-04-22T03:22:50
167,948,837
0
0
null
null
null
null
UTF-8
Python
false
false
375
py
import random "The key methods for numeric types are" import math abs(-34.5) math.ceil(2.17) math.floor(3.14) min(8, -4) max(3.4, 6) pow(2.7, 3.14) "Unlike integers, floats are not infinite precision" float('inf') float('-inf') "The key methods in random are" A = ['5', '6', '9'] random.randrange(28) random.randint(1, 8) random.random() random.shuffle(A) random.choice(A)
[ "sanches2000009@gmail.com" ]
sanches2000009@gmail.com
1966da1430249c115859159fdb6358ee67e4c05c
8ac9ead261b79e107fd8889e7df0beb2e59abfdd
/bitwise-XOR/examples/single-number/python/MainApp/app/mainApp.py
f22167b6792551278b3699e5cd64cc43365e710a
[]
no_license
nikhilbagde/Grokking-The-Coding-Interview
866cf7a6a12ded74900d2235c59af9bccedfafdd
35bf0b4ee31b958f6c1ab0159d4465c5ee27ddc6
refs/heads/main
2023-04-16T03:11:38.087172
2021-04-30T07:10:13
2021-04-30T07:10:13
370,174,345
1
0
null
2021-05-23T23:02:59
2021-05-23T23:02:59
null
UTF-8
Python
false
false
496
py
class MainApp: def __init__(self): pass ''' Given a non-empty array of integers `nums`, every element appears twice except for one. Find that single one. Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory? Example 1: Input: nums = [2,2,1] ^ Output: 1 ''' @staticmethod def run(arr): xor = 0 for n in arr: xor ^= n return xor
[ "adikid1996@gmail.com" ]
adikid1996@gmail.com
a47e4fa2e79a89fce7694cbce9923eee00dbfad9
e802499fa5c6cdde7ee239b198a2d59a2d93b22c
/7_whileloop/mountain_poll.py
e4d50ff060ed02781bbc30491c7b97607c24ba70
[]
no_license
michaelzh17/python_crash
a4a76efd042aa664757ba659f218a053a4eb8350
193957ad621ccf17b9ca77a9db9a2bbdea8b96ed
refs/heads/master
2020-04-04T20:29:49.604165
2018-11-13T02:07:24
2018-11-13T02:07:24
156,248,846
0
0
null
null
null
null
UTF-8
Python
false
false
718
py
# -*- coding: utf-8 -*- responses = {} # Set a flag to indicate that polling is active polling_active = True while polling_active: # Prompt for the person's name and response. name = input("\nWhat is your name? ") response = input("\nWhich mountain would you like to climb someday? ") # Store the response in the dictionary responses[name] = response # Find out if anyone else is going to take the poll repeat = input("Would you like to let another person respond? (yes/no) ") if repeat.lower() == 'no': polling_active = False # Polling is complete. Show the results. print("\n--- Polling Results ---") for name, response in responses.items(): print(name + " would like to climb " + response + ".")
[ "macalzhang@gmail.com" ]
macalzhang@gmail.com
406d3124a354ad1297c9973de5f7b22c8d7fa4e4
a425e5921254936869ae43efc55ad317e9b7c91e
/RIdwan Ilyas/part 5.py
3cf402491eaefaad25178567bb01d29765a08081
[]
no_license
Pythonjowo/Fundamental_banget2020
72071718f9b3fa47b2584a45239aeadbbe3acb28
5c19892361ff87b4743e4825101847ffc44840c5
refs/heads/master
2023-02-09T14:38:33.020898
2021-01-05T23:54:23
2021-01-05T23:54:23
296,386,642
0
0
null
null
null
null
UTF-8
Python
false
false
92
py
a = 1 if a > 5: print('Benar') elif a > 1: print('Sedang') else: print('Kecil')
[ "psfauzi@gmail.com" ]
psfauzi@gmail.com
e1201756d49e5ae6e7e0e9a55b9aaccd104f6658
85186196b2ad25919667fea7733be4e92dd973a1
/migrations/versions/cda3560efe7b_migration.py
276cf5749552d8a149f758c53530a02ad5d337ce
[ "MIT" ]
permissive
WILLGENIUS15/-pitch-
73b14e5a6b33f105b978d4be9ceb53f17d9a8cd4
2d91834a03ed0fe9ceb4491c93e5f8d2eb7c5437
refs/heads/master
2022-12-15T12:25:46.943182
2019-09-20T05:13:30
2019-09-20T05:13:30
208,209,684
0
1
null
2022-12-08T02:34:45
2019-09-13T06:39:24
Python
UTF-8
Python
false
false
2,029
py
"""migration Revision ID: cda3560efe7b Revises: Create Date: 2019-08-06 15:41:39.852407 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'cda3560efe7b' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=255), nullable=True), sa.Column('email', sa.String(length=255), nullable=True), sa.Column('bio', sa.String(length=255), nullable=True), sa.Column('profile_pic_path', sa.String(), nullable=True), sa.Column('pass_secure', sa.String(length=255), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) op.create_table('pitches', sa.Column('id', sa.Integer(), nullable=False), sa.Column('upvotes', sa.Integer(), nullable=True), sa.Column('downvotes', sa.Integer(), nullable=True), sa.Column('title', sa.String(), nullable=True), sa.Column('content', sa.String(), nullable=True), sa.Column('posted', sa.DateTime(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('comments', sa.Column('id', sa.Integer(), nullable=False), sa.Column('content', sa.String(), nullable=True), sa.Column('posted', sa.DateTime(), nullable=True), sa.Column('pitch_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['pitch_id'], ['pitches.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('comments') op.drop_table('pitches') op.drop_index(op.f('ix_users_email'), table_name='users') op.drop_table('users') # ### end Alembic commands ###
[ "willgenius@gmail.com" ]
willgenius@gmail.com
e8c62c117de3ea36c017a311ec5bd784ade3bae7
907f255b6b51b97f6cc7cda1bd38fa689e933dab
/project_2020/project_2020/asgi.py
be5963ad23e1e35c928287652bfd1a35c75267f5
[]
no_license
nandaanumolu/Project-2020
4175e95c26af814f0e852228b4faa78b7e072fe9
b650a095821d9498591f60f15830bb55737a57c8
refs/heads/main
2023-02-18T12:46:26.350858
2021-01-03T15:02:18
2021-01-03T15:02:18
326,430,818
1
0
null
null
null
null
UTF-8
Python
false
false
401
py
""" ASGI config for project_2020 project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_2020.settings') application = get_asgi_application()
[ "nandakishore087@gmail.com" ]
nandakishore087@gmail.com
f7a407549d3796908aeec72dd3c1c10271ab2051
e23a4f57ce5474d468258e5e63b9e23fb6011188
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/Tree/208_ImplementTrie.py
8d9387fe2eeb4a660c9e6c9a2872e6531d306164
[]
no_license
syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
2023-02-16T03:08:10
2019-11-09T02:58:47
Python
UTF-8
Python
false
false
1,453
py
#! /usr/bin/env python # -*- coding: utf-8 -*- # @Author: xuezaigds@gmail.com # Refer to: # https://leetcode.com/discuss/49529/my-python-solution c.. TrieNode o.. ___ __init__(self self.children _ # dict self.is_word = F.. c.. Trie o.. ___ __init__(self self.root = TrieNode() ___ insert word # Inserts a word into the trie. cur_node = self.root ___ ch __ word: __ ch n.. __ cur_node.children: cur_node.children[ch] = TrieNode() cur_node = cur_node.children[ch] cur_node.is_word = True ___ search word # Returns if the word is in the trie. cur_node = self.root ___ ch __ word: __ ch n.. __ cur_node.children: r_ F.. cur_node = cur_node.children[ch] r_ cur_node.is_word ___ startsWith prefix # Returns if there is any word in the trie # that starts with the given prefix. cur_node = self.root ___ ch __ prefix: __ ch n.. __ cur_node.children: r_ F.. cur_node = cur_node.children[ch] r_ True """ if __name__ == '__main__': trie = Trie() trie.insert("app") trie.insert("apple") trie.insert("beer") trie.insert("add") trie.insert("jam") trie.insert("rental") print trie.search("apps") print trie.search("app") print trie.search("ad") """
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
4b0027aba10550f8e210dfd5e46a51f834e1b9d5
363b8f40cfa26a8269b57998f8397f430767fc2d
/src/lib/mine/task/config.py
473f218524f00fbfb3d874ebbd0d728d58679349
[ "MIT" ]
permissive
rdw20170120/build
f1cadf1b0f4f932305d22d030b2deb327b07a573
f1bbaed94dbac55437cad09aca62a7fea8051f59
refs/heads/master
2023-07-25T08:39:58.935112
2023-07-12T17:31:20
2023-07-12T17:31:20
263,498,700
0
0
null
null
null
null
UTF-8
Python
false
false
4,153
py
#!/usr/bin/env false """Manage configuration.""" # Internal packages (absolute references, distributed with Python) from sys import maxsize # External packages (absolute references, NOT distributed with Python) # Library modules (absolute references, NOT packaged, in project) from utility import environment from utility.config import Config as BaseConfig # Project modules (relative references, NOT packaged, in project) class Config(BaseConfig): @property def fake_suffix(self): return ".fake" @property def filesystem_to_watch(self): return self.temporary_directory @property def is_dry_run(self): """Return whether we are performing a dry-run execution. This setting is configured in each deployment by the absence or the value of the environment variable. By default, the variable is undefined. As a consequence, execution is NOT a dry-run. If the variable is defined in the deployment with an appropriate value, then we execute as a dry-run in which no actual changes are made. This provides an advantage during development and testing. """ try: v = environment.get("Run") return v.lower() == "dry" except KeyError: return False @property def is_forced_run(self): """Return whether we are performing a forced-run execution. This setting is configured in each deployment by the absence or the value of the environment variable. By default, the variable is undefined. As a consequence, execution is NOT a forced-run. If the variable is defined in the deployment with an appropriate value, then we execute as a forced-run in which we overwrite computed data files instead of skipping them when they already exist. This provides an advantage during development and testing. """ try: v = environment.get("Run") return v.lower() == "force" except KeyError: return False @property def quick_run_limit(self): """Return quick run file size limit, if any. This setting is configured in each deployment by the absence or the value of the environment variable. By default, the variable is undefined. As a consequence, execution is NOT limited to a quick run. If the variable is defined in the deployment with an appropriate value, then we execute as a quick run in which we process only existing data files whose size is under the limit specified by the environment variable value (integer bytes). This provides an advantage during development and testing. """ try: return int(environment.get("Quick")) except KeyError: return maxsize @property def reserved_disk_space_in_bytes(self): """Return disk space to reserve in bytes. In the absence of a defined value for the environment variable, we use the maximum integer value as a default. """ try: return int(environment.get("ReservedDiskSpaceInBytes")) except KeyError: return maxsize @property def should_abort_upon_task_failure(self): return False @property def should_fake_it(self): """Return whether we should fake the data processing during execution. This setting is configured in each deployment by the absence or presence of the environment variable. By default, the variable is undefined. As a consequence, execution performs real data processing. If the variable is defined in the deployment, then data processing is faked. This provides an advantage during development and testing since the real data processing takes significant time. """ try: environment.get("FakeIt") return True except KeyError: return False @property def should_leave_output_upon_task_failure(self): return False """DisabledContent """
[ "x299424@mac-jf4j397k.lan" ]
x299424@mac-jf4j397k.lan
dbb911125b94c50c5cb9bb85dec1b7a99417c658
80cd5c8c19c96f7eac2dbe6f8a1fb4186de9f0ac
/multWords.py
c633e3a9a5fbef18b8a5630a6ab5f007dd387085
[]
no_license
kjm5723/basicblackout
a90b1bbe8e233c77416df09b4862351a8b99ba33
3f33eb661ea6d7f3fdf14dcf727449a94f1dc2e4
refs/heads/master
2022-07-31T20:16:35.665802
2020-05-24T17:45:17
2020-05-24T17:45:17
266,592,566
0
0
null
null
null
null
UTF-8
Python
false
false
521
py
import re def multWords(): l = [] newW = '\u2588' i = 0 while i < 5: newW += '\u2588' i += 1 s = str(input("Enter plaintext:")) w = str(input("Enter word you wish to censor (type STOP to end entry mode): ")) while w != "STOP": l.append(w) w = str(input("Enter word you wish to censor (type STOP to end entry mode): ")) for c in l: c = re.compile(c, re.IGNORECASE) newS = c.sub(newW, s) s = newS print(newS)
[ "noreply@github.com" ]
kjm5723.noreply@github.com
28f86e134af496e71a7090fdcb99788cc2569b30
8a1269ad6127d79124720feadd4fce7283333ff4
/python_scripts/intersectionSpreadsheet_UIDs.py
3d4532bf910aac6f2c5a71dec56f93c89022ba36
[]
no_license
DavisLaboratory/Db_Compare
9bdab9f974b6a0d6b966e1b98b4bf96ac592d6a5
fd21885c4bc0a14817195b179ac758e016115738
refs/heads/master
2023-03-11T23:38:36.114000
2021-02-25T06:28:22
2021-02-25T06:28:22
290,677,904
0
0
null
null
null
null
UTF-8
Python
false
false
1,935
py
import os import glob import sys # input the file containing the UIDs for the databases HPRD, BioGRID, Reactome, KEGG, WikiPathways PhosphositePlus, and SIGNOR, in that order # outputs a tsv file containing the UID intersections of each database with all qphos 'samples' def intersectionFunction(fHPRD, fBG, fRXM, fKEGG, fWP, fPSP, fSIG): UID_spreadsheet = open("database_qPhos_Comparison_UID.tsv", "w+") UID_spreadsheet.write("Intersection\tHPRD\tBioGRID\tReactome\tKEGG\tWikiPathways\tPhosphoSitePlus\tSIGNOR\n") HPRD = set(line.strip() for line in open(fHPRD)) RXM = set(line.strip() for line in open(fRXM)) KEGG= set(line.strip() for line in open(fKEGG)) WP = set(line.strip() for line in open(fWP)) PSP = set(line.strip() for line in open(fPSP)) BG = set(line.strip() for line in open(fBG)) SIG = set(line.strip() for line in open(fSIG)) # get all UID files and MOD files for each qphos 'sample' for file in glob.glob('UID*_NoIso.txt'): if not(file.startswith("UID_MOD")): with open(file) as f: fileName = set(line.strip() for line in open(file)) iHPRD = len(HPRD.intersection(fileName)) iRXM = len(RXM.intersection(fileName)) iKEGG = len(KEGG.intersection(fileName)) iWP = len(WP.intersection(fileName)) iPSP = len(PSP.intersection(fileName)) iBG = len(BG.intersection(fileName)) iSIG = len(SIG.intersection(fileName)) UID_spreadsheet.write('%s\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n'%(file, iHPRD, iBG, iRXM, iKEGG, iWP, iPSP, iSIG)) UID_spreadsheet.close() def main(): intersectionFunction(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7]) if __name__ == "__main__": main()
[ "huckstephannah@gmail.com" ]
huckstephannah@gmail.com
74a7ac8c9244c9882044fd031b38b2096874d4a8
186b6e386d9ddaa9232aaf1f73ee8be7275a1e56
/fio-resultados/k8s-rbd/bk4-rtx/plot.py
908677c07bf04b1294001af955e8b6400a1983a5
[]
no_license
gemoya/memoria_exp
316844ae2373a7cf047639098c1508e841ab7d8c
74886010c6c21de036de4df3c9aa0a6ceb8f3d17
refs/heads/master
2021-05-16T01:19:12.252667
2018-03-04T21:09:27
2018-03-04T21:09:27
107,055,338
0
0
null
null
null
null
UTF-8
Python
false
false
63
py
import matplotlib.pyplot as plt import json plt.xlabel("")
[ "gemoya@AirdeGonzalo2.home" ]
gemoya@AirdeGonzalo2.home
8aedd48cba8c490675b376065a3f58df2297b510
a8e7db522b98b4e4c497079b752b70d4a4c1d215
/Cracking the coding Interview/Arrays&StringsPg90/URLify.py
325183834e52098cd6cc77346e594c66492c08ee
[]
no_license
zkoebler/Zephrom-DSA-solutions
3d5f75cf91805be4a862a1ef3d3204d791be435c
41531f10aa3dc5f2f25b116c3b4b04019e1114ad
refs/heads/main
2023-07-04T18:54:08.804519
2021-08-24T03:27:33
2021-08-24T03:27:33
null
0
0
null
null
null
null
UTF-8
Python
false
false
289
py
#O(n) algo for inserting def URLify(string): elements = string.split(' ') newList = [x for x in elements if x != ''] idx = 1 while(idx < len(newList)): newList.insert(idx,'%20') idx += 2 return newList print(URLify(" Mr John Smith is happy! "))
[ "zkoebler@gmail.com" ]
zkoebler@gmail.com
b34080942f8a3571ef47e9b4d282fdaa292e6e3e
fcf4bccb11838cc7b526a3a1fdde4a8b1fac03df
/cloud_computing/src/aviation/rank_airline_per_route.py
f8e3f34a74c62d808251df972b8175ee5105e053
[]
no_license
beaglebagel/mooc
ee09120be29dd2728dd0a9dc93d98e56a00332c2
02603a10060a21fa4f48798838ae2d98fa515329
refs/heads/master
2016-08-11T21:53:22.696539
2016-04-28T01:26:33
2016-04-28T01:26:33
44,508,371
3
0
null
null
null
null
UTF-8
Python
false
false
2,210
py
from mrjob.job import MRJob, MRStep class RankAirlinePerRoute(MRJob): """ Group 2.3 For each route(origin -> destination), rank the airline by on-time arrival performance. Capstone: Top 10 airlines per routes based on on-time arrival performance. Each file line is composed of the following 19 fields in order as is: 0-4: year, month, dayofmonth, dayofweek, flight_date, 5-9: unique_carrier, flightNum, origin, dest, crs_dep_time, 10-14: dep_delay_min, dep_del_15, crs_arr_time, arr_delay_min, arr_del_15, 15-20: cancelled, diverted """ def mapper(self, _, line): # @NOTE: for departure delay, try using dep_delay_min first.. fields = line.strip().split('|') origin, destination, airline = fields[7], fields[8], fields[5] delay = fields[-4] # [origin, destination, airline] -> ( Delay, 1 ) ] yield (origin, destination, airline), (float(delay), 1) def combiner(self, route, delays_counts): # [origin, destination, airline] -> ( delay_min, 1 ) yield route, map(sum, zip(*delays_counts)) def reducer(self, route, delays_counts): # [origin, destination, airline] -> tuple ( delay_min, 1 ) total_delay, count = map(sum, zip(*delays_counts)) # [origin, destination, airline] -> average delay_min yield route, total_delay / count def mapper2(self, route, avg_delay): origin, destination, airline = route[0], route[1], route[2] yield (origin,destination), (avg_delay, airline) def reducer2(self, route, pair): sorted_pairs = sorted(pair, reverse=False) yield route, sorted_pairs def mapper3(self, route, sorted_pairs): reverse_pairs = [(airline, avg_delay) for avg_delay, airline in sorted_pairs] yield route, reverse_pairs def steps(self): return [ MRStep(mapper=self.mapper, combiner=self.combiner, reducer=self.reducer), MRStep(mapper=self.mapper2, reducer=self.reducer2), MRStep(mapper=self.mapper3) ] if __name__ == '__main__': RankAirlinePerRoute.run()
[ "jblee@riseup.net" ]
jblee@riseup.net
de974b7c9e890ef6b0c1f3a7373d12bb1340ed99
6483506612126ffbde6ca9b788f6f6569e834811
/patterns/precip.py
deb59d0227683021f15cf329a5125232b924dde2
[ "MIT" ]
permissive
imedgar/bot-assistant
94b2505cd3f45879631dfa3a4021c8a11f8eb0e6
13ba3320cd4ff1f89bfd051fd80fc44a3ead6c38
refs/heads/master
2020-06-03T10:28:00.873336
2019-06-12T09:07:43
2019-06-12T09:07:43
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,340
py
#!/usr/bin/env python import argparse import random import time import scrollphathd def generate_lightning(intensity): """Generate a lightning bolt""" if random.random() < intensity: x = random.randint(0, width - 1) # generate a random crooked path from top to bottom, # making sure to not go off the sides for y in range(0, height): if y > 1 and y < height - 1: branch = random.random() if branch < .3: x -= 1 if x <= 0: x = 0 elif branch > .6: x += 1 if x >= width - 1: x = width - 1 # generate a wider flash around the bolt itself wide = [int(x - (width / 2)), int(x + (width / 2))] med = [int(x - (width / 4)), int(x + (width / 4))] small = [x - 1, x + 1] for val in [wide, med, small]: if val[0] < 0: val[0] = 0 if val[1] > width - 1: val[1] = width - 1 for flash in [[wide, .1], [med, .2], [small, .4]]: scrollphathd.fill( flash[1], x=flash[0][0], y=y, width=flash[0][1] - flash[0][0] + 1, height=1 ) scrollphathd.set_pixel(x, y, brightness=1) scrollphathd.show() scrollphathd.clear() def new_drop(pixels, values): """Generate a new particle at the top of the board""" # First, get a list of columns that haven't generated # a particle recently cols = [] for x in range(0, width): good_col = True for y in range(0, int(height * values['safe'])): if pixels[x][y] == values['brightness']: good_col = False if good_col is True: cols.append(x) # Then pick a random value from this list, # test a random number against the amount variable, # and generate a new particle in that column. # Then remove it from the list. # Do this as many times as required by the intensity variable if len(cols) > 0: random.shuffle(cols) cols_left = values['intensity'] while len(cols) > 0 and cols_left > 0: if random.random() <= values['amount']: pixels[cols.pop()][0] = values['brightness'] + values['fade'] cols_left -= 1 def fade_pixels(pixel_array, fade): """Fade all the lit particles on the board by the fade variable""" for x in range(0, width): for y in range(0, height): if pixel_array[x][y] > 0: pixel_array[x][y] -= fade pixel_array[x][y] = round(pixel_array[x][y], 2) if pixel_array[x][y] < 0: pixel_array[x][y] = 0 return pixel_array def update_pixels(pixels, values): """Update the board by lighting new pixels as they fall""" for x in range(0, width): for y in range(0, height - 1): if pixels[x][y] == values['brightness']: pixels[x][y + 1] = values['brightness'] + values['fade'] fade_pixels(pixels, values['fade']) x = range(width) y = range(height) [[[scrollphathd.set_pixel(a, b, pixels[a][b])] for a in x] for b in y] for a in range(0, len(pixels)): for b in range(0, len(pixels[a])): scrollphathd.set_pixel(a, b, pixels[a][b]) scrollphathd.show() # Command line argument parsing functions def msg(name=None): return '''precip.py [options...] ''' def setup_parser(): parser = argparse.ArgumentParser( description='Generate precipitation; CTRL+C to exit', usage=msg(), argument_default=argparse.SUPPRESS ) parser.add_argument( "-a", "--amount", help="Chance of generating a new particle in each possible column " "(0 to 1)", type=float ) parser.add_argument( "-b", "--brightness", help="Initial brightness of a particle (0 to 1)", type=float ) parser.add_argument( "-d", "--delay", help="Delay between steps (0 and up, in seconds)", type=float ) parser.add_argument( "-f", "--fade", help="How quickly a particle fades; determines how long the tail is" " (0 to 1)", type=float ) parser.add_argument( "-i", "--intensity", help="How many columns have the chance " "to generate a new particle each tick (0 to width, integer)", type=int ) parser.add_argument( "-l", "--lightning", help="Chance of lightning on each tick (0 to 1)", type=float ) parser.add_argument( "-q", "--quiet", help="Suppress output", action="store_false" ) parser.add_argument( "-r", "--rotate", help="Rotate the board", default=0, choices=[ 0, 90, 180, 270 ], type=int ) parser.add_argument( "-s", "--safe", help="How far down a column a particle must get " "before a new particle can be generated in that column " "(0 to 1, fraction of the column)", type=float ) parser.add_argument( "-t", "--type", help="Type of precipitation. Sets a preset for all conditions; " "will be overridden by any specified conditions.", default="thunderstorm", choices=[ "rain", "heavy rain", "snow", "heavy snow", "thunderstorm" ] ) return parser if __name__ == '__main__': # Set up command line argument parsing parser = setup_parser() args = parser.parse_args() arguments = vars(args) scrollphathd.set_clear_on_exit() scrollphathd.set_brightness(1) # Board rotation scrollphathd.rotate(degrees=180) width = scrollphathd.get_shape()[0] height = scrollphathd.get_shape()[1] presets = { "thunderstorm": { "amount": .7, "brightness": .15, "delay": 0, "fade": .05, "intensity": 1, "lightning": .01, "safe": .3 }, "rain": { "amount": .7, "brightness": .15, "delay": 0, "fade": .05, "intensity": 1, "lightning": 0, "safe": .3 }, "heavy rain": { "amount": .7, "brightness": .15, "delay": 0, "fade": .05, "intensity": 4, "lightning": 0, "safe": .3 }, "snow": { "amount": .2, "brightness": .4, "delay": .25, "fade": .4, "intensity": 2, "lightning": 0, "safe": .3 }, "heavy snow": { "amount": .3, "brightness": .4, "delay": .25, "fade": .4, "intensity": 4, "lightning": 0, "safe": .3 } } values = {} conditions = [ 'amount', 'brightness', 'delay', 'fade', 'intensity', 'lightning', 'safe' ] # Set initial values from arguments or preset for condition in conditions: values[condition] = arguments.get( condition, presets[arguments['type']][condition] ) # Set up initial pixel matrix pixels = [] for x in range(width): pixels.append([]) for y in range(height): pixels[x].append(0) # Print conditions if arguments.get('quiet') is not False: print("Current conditions:") for condition in conditions: print("{}: {}".format(condition, values[condition])) # Run display loop while True: if values['lightning'] > 0: generate_lightning(values['lightning']) new_drop(pixels, values) update_pixels(pixels, values) time.sleep(values['delay'])
[ "ed.ga.ru90@gmail.com" ]
ed.ga.ru90@gmail.com
9c2eb8f2f1811beb52ba4d6f7c54cb4dd7553edb
a9b02b162949fe75170afaee1068dd2342402ff7
/C123/0992_subarrays_with_k_different_integers/solution_1.py
78642c25091c3885433e74f3eaabe31555e7e51d
[]
no_license
asymmetry/leetcode
d0c0f7f61f72699bdfffc8a17f5746991bb4103c
3232620c73175dcf4cfef31a07319e7cc032d224
refs/heads/master
2020-03-22T15:58:16.945882
2019-02-10T21:04:18
2019-02-10T21:04:18
140,293,077
0
0
null
null
null
null
UTF-8
Python
false
false
955
py
from collections import Counter class Solution: def subarraysWithKDistinct(self, A: 'List[int]', K: 'int') -> 'int': c_l1 = Counter() d_l1 = 0 c_l2 = Counter() d_l2 = 0 result = 0 l1, l2 = 0, 0 for aa in A: c_l1[aa] += 1 if c_l1[aa] == 1: d_l1 += 1 c_l2[aa] += 1 if c_l2[aa] == 1: d_l2 += 1 while d_l1 > K: c_l1[A[l1]] -= 1 if c_l1[A[l1]] == 0: d_l1 -= 1 l1 += 1 while d_l2 >= K: c_l2[A[l2]] -= 1 if c_l2[A[l2]] == 0: d_l2 -= 1 l2 += 1 result += l2 - l1 return result if __name__ == '__main__': print(Solution().subarraysWithKDistinct([1, 2, 1, 2, 3], 2)) print(Solution().subarraysWithKDistinct([1, 2, 1, 3, 4], 3))
[ "guchao.pku@gmail.com" ]
guchao.pku@gmail.com
9a91982f4aa04eb7363bce546a761edd1724927c
2b14cb46428ff4867798cae6e2b5a4d711373dd2
/vanya_and_lanterns.py
77df91e8ec13003544d1506ab461f7dd933ed909
[]
no_license
fali007/competetive-coding
2847db3e8205bd0483950211b05a59b658ae836a
22fa9056f942be3ae1e9104a132e26c670820dc3
refs/heads/master
2022-08-20T04:09:29.027017
2020-05-10T22:10:40
2020-05-10T22:10:40
262,882,620
0
0
null
null
null
null
UTF-8
Python
false
false
222
py
a,b=map(int,input().split(' ')) array=map(int,input().split(' ')) array=sorted(array) max_gap=max(array[0],a-array[-1]) for i in range(1,len(array)): max_gap=max((array[i]-array[i-1])/2,max_gap) print("%.9f"%(max_gap))
[ "noreply@github.com" ]
fali007.noreply@github.com
40024c309610ede8fb4fa74e21f50acdc682c14d
ea9d07e01407af824e1cc8b59a48375002cd4e79
/scripts/deploy_mainnet.py
340e4ff9249506bb07ce9e00ff0e52eb1f54c9ad
[ "Unlicense" ]
permissive
xiaojay/alpha-vaults-contracts
787dcc5d86930b9d1c837260cf22292eb09f0c35
bcbcbcb45d2479f6294b8af80065481be6579887
refs/heads/main
2023-05-29T11:20:29.257997
2021-06-12T05:24:11
2021-06-12T05:24:11
372,115,542
0
0
Unlicense
2021-05-30T03:34:21
2021-05-30T03:34:20
null
UTF-8
Python
false
false
1,207
py
from brownie import accounts, AlphaVault, AlphaStrategy from brownie.network.gas.strategies import GasNowScalingStrategy # POOL = "0x8ad599c3a0ff1de082011efddc58f1908eb6e6d8" # USDC / ETH POOL = "0x4e68ccd3e89f51c3074ca5072bbac773960dfa36" # ETH / USDT PROTOCOL_FEE = 5000 MAX_TOTAL_SUPPLY = 2e17 BASE_THRESHOLD = 3600 LIMIT_THRESHOLD = 1200 MAX_TWAP_DEVIATION = 100 TWAP_DURATION = 60 KEEPER = "0x04c82c5791bbbdfbdda3e836ccbef567fdb2ea07" def main(): deployer = accounts.load("deployer") balance = deployer.balance() gas_strategy = GasNowScalingStrategy() vault = deployer.deploy( AlphaVault, POOL, PROTOCOL_FEE, MAX_TOTAL_SUPPLY, publish_source=True, gas_price=gas_strategy, ) strategy = deployer.deploy( AlphaStrategy, vault, BASE_THRESHOLD, LIMIT_THRESHOLD, MAX_TWAP_DEVIATION, TWAP_DURATION, KEEPER, publish_source=True, gas_price=gas_strategy, ) vault.setStrategy(strategy, {"from": deployer, "gas_price": gas_strategy}) print(f"Gas used: {(balance - deployer.balance()) / 1e18:.4f} ETH") print(f"Vault address: {vault.address}")
[ "72396409+mxwtnb@users.noreply.github.com" ]
72396409+mxwtnb@users.noreply.github.com
d3f2bab7bd79b27aedc275c1c5c01e4c9de5aebb
56522f4280d3c5c69e0af95f32e354c5c820a066
/json_generator.py
d4eaca0b1085c3a927671ef7a885236cae9b263d
[ "Apache-2.0" ]
permissive
ligi/android-drawable-importer-intellij-plugin
ba61a05f4cb8243964261e376ac7d7f71ffecf34
5bb2363eea9d4c5bd19a1ba0e8457c0fee0672eb
refs/heads/develop
2020-11-30T16:21:40.287785
2015-12-29T19:14:22
2015-12-29T19:14:22
52,488,365
0
0
null
2016-02-25T01:48:33
2016-02-25T01:48:32
null
UTF-8
Python
false
false
5,186
py
import json import os import io from itertools import izip, islice from os.path import join from PIL import Image root = 'src/main/resources/assets/' android_icons_url = 'http://www.androidicons.com/' material_icons_url = 'https://www.google.com/design/icons/' def convert_image(file): pil_img = Image.open(file) if pil_img.mode == '1': img = Image.open(file) img = img.convert('RGBA') datas = img.getdata() newData = [] for item in datas: if item[0] == 0 and item[1] == 0 and item[2] == 0: newData.append((0, 0, 0, 0)) else: newData.append(item) img.putdata(newData) img.save(file) def convert_images(): iconpack_root = join(root, 'android_icons') for color in list_dirs_only(iconpack_root): color_root = join(iconpack_root, color) for resolution in list_dirs_only(color_root): resolution_root = join(color_root, resolution) for image in list_images(resolution_root): convert_image(join(resolution_root, image)) iconpack_root = join(root, 'material_icons') for category in list_dirs_only(iconpack_root): category_root = join(iconpack_root, category) for resolution in list_dirs_only(category_root): resolution_root = join(category_root, resolution) for image in list_images(resolution_root): convert_image(join(resolution_root, image)) def get_android_icons_file(color, resolution, name): iconpack_root = join(root, 'android_icons') color_root = join(iconpack_root, color) resolution_root = join(color_root, resolution) full_name = name + '.png' return join(resolution_root, full_name) def handle_android_icons(): iconpack_root = join(root, 'android_icons') id = 'android_icons' colors = list_dirs_only(iconpack_root) firstcolordir = join(iconpack_root, colors[0]) resolutions = list_dirs_only(firstcolordir) assets = list_images(join(firstcolordir, resolutions[0])) packdata = {'name': 'Android Icons', 'id': id, 'url': android_icons_url, 'path': 'android_icons/', 'categories': ['all'] } assetdata = [] for asset in assets: name = os.path.splitext(asset)[0] data = {'name': name, 'pack': id, 'category': 'all', 'resolutions': resolutions, 'colors': colors, 'sizes': ['18dp']} assetdata.append(data) packdata['assets'] = assetdata return packdata def list_dirs_only(dir): return [f for f in os.listdir(dir) if os.path.isdir(join(dir, f))] def list_images(dir): return [f for f in os.listdir(dir) if f.endswith('.png')] def extract_data(icon_file_name): file_name = os.path.splitext(icon_file_name)[0] splits = file_name.split('_') size = splits[-1] splits.pop() color = splits[-1] splits.pop() name = '_'.join(splits) return name, color, size def get_material_icons_file(category, color, size, resolution, name): iconpack_root = join(root, 'material_icons') category_root = join(iconpack_root, category) resolution_root = join(category_root, 'drawable-' + resolution) full_name = "_".join([name, color, size]) + '.png' return join(resolution_root, full_name) def handle_material_icons(): iconpack_root = join(root, 'material_icons') categories = list_dirs_only(iconpack_root) id = 'material_icons' packdata = {'name': 'Material Icons', 'id': id, 'url': material_icons_url, 'path': 'material_icons/', 'categories': categories } assetdata = [] for category in categories: category_root = join(iconpack_root, category) resolutions = [s.split('-')[1] for s in list_dirs_only(category_root)] raw_assets = [extract_data(f) for f in list_images(join(category_root, 'drawable-' + resolutions[0]))] colors = [] sizes = [] for current_item, next_item in izip(raw_assets, islice(raw_assets, 1, None)): colors.append(current_item[1]) sizes.append(current_item[2]) if current_item[0] != next_item[0]: data = {'name': current_item[0], 'pack': id, 'category': category, 'resolutions': resolutions, 'colors': sorted(set(colors)), 'sizes': sorted(set(sizes))} assetdata.append(data) colors = [] sizes = [] continue packdata['assets'] = assetdata return packdata convert_images() android_icons_data = handle_android_icons() material_icons_data = handle_material_icons() packs = [android_icons_data, material_icons_data] with io.open(join(root, 'content.json'), 'w', encoding='utf-8') as f: f.write(unicode(json.dumps(packs, ensure_ascii=False))) print('Created json at ' + join(join(os.getcwd(), root), 'content.json'))
[ "marcprengemann@web.de" ]
marcprengemann@web.de
6259072bc09c65a130a23d473503f56f9ae8f7b0
a2211f0ef8297a77200a0b2eec8ba3476989b7e6
/itcast/02_python核心编程/02_linux系统编程/day01_进程/demo04_创建子进程.py
c236a108071be71b8f33da98ba163ba4dd2f4094
[]
no_license
qq1197977022/learnPython
f720ecffd2a70044f1644f3527f4c29692eb2233
ba294b8fa930f784304771be451d7b5981b794f3
refs/heads/master
2020-03-25T09:23:12.407510
2018-09-16T00:41:56
2018-09-16T00:42:00
143,663,862
0
0
null
null
null
null
UTF-8
Python
false
false
808
py
import os, time ret = os.fork() # fork a child process, 仅适用于类Unix平台 print('fork函数返回值 = {}'.format(ret)) if ret == 0: print('当前进程(即子进程)pid---{0}父进程pid---{1}'.format(os.getpid(), os.getppid())) else: print('当前进程(即父进程)pid============{0}父进程pid==={1}'.format(os.getpid(), os.getppid())) '''https://baike.baidu.com/item/fork/7143171?fr=aladdin 1.分叉函数 1.返回值 1.成功调用 1.向子进程返回0 2.向父进程返回子进程PID 2.失败返回-1 2.作用: 将运行着的程序分成两个几乎完全一样的进程 1.每个进程都启动一个从代码同一位置同时开始执行的线程,就像是同时启动了该应用程序的两个副本 '''
[ "1197977022@qq.com" ]
1197977022@qq.com
fba2d76f95aefa09b611da75e7484df3a4299f6f
a2e19fd174bedd860297bcc72032dce0f1ea2339
/graphs/experiments/train.py
3cbff03d38f1c1b20cfff14fe5eaddc11e2a1f0e
[ "MIT" ]
permissive
Cyanogenoid/fspool
29772ea76fa96c35b59e1c0cdb7581b3714028ee
a9f93cc774610c6d96c2c3095a1ab16f53abbefb
refs/heads/master
2023-08-03T10:58:16.139258
2022-11-22T23:16:32
2022-11-22T23:16:32
190,535,015
47
8
MIT
2023-07-22T07:41:22
2019-06-06T07:25:24
Python
UTF-8
Python
false
false
6,308
py
import os.path as osp import argparse import torch from torch.nn import Sequential, Linear, ReLU import torch.nn.functional as F from torch_geometric.datasets import TUDataset from torch_geometric.data import DataLoader from torch_geometric.nn import GraphConv, FSPooling, GINConv from torch_geometric.nn import global_mean_pool, global_add_pool from torch_geometric.utils import degree import torch_geometric.transforms as T from sklearn.model_selection import KFold parser = argparse.ArgumentParser() parser.add_argument('--dataset') parser.add_argument('--model', choices=['fsort', 'sum', 'mean']) parser.add_argument('--fold', type=int, default=0) parser.add_argument('--validation', action='store_true') parser.add_argument('--epochs', type=int, default=500) parser.add_argument('--batch-size', type=int, default=128) parser.add_argument('--dim', type=int, default=32) parser.add_argument('--drop', type=float, default=0.5) parser.add_argument('--seed', type=int, default=0) parser.add_argument('--gpu', type=int) args = parser.parse_args() if args.gpu is not None: torch.cuda.set_device(args.gpu) max_degrees = { 'IMDB-BINARY': 135, 'IMDB-MULTI': 88, 'COLLAB': 491, } transforms = [] if 'REDDIT' in args.dataset or args.dataset in max_degrees: transforms.append(T.Constant(1)) if args.dataset in max_degrees: transforms.append(T.OneHotDegree(max_degrees[args.dataset])) print('transforms:', transforms) path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', args.dataset) dataset = TUDataset(path, name=args.dataset, transform=T.Compose(transforms)) # different seeds for different folds so that one particularly good or bad init doesn't affect the results for the whole seed # multiply folds by 10 so that nets in different seeds are initialised with different seeds seed = args.seed + 10 * args.fold torch.manual_seed(seed) torch.cuda.manual_seed(seed) dataset = dataset.shuffle() kfold = KFold(n_splits=10) train_indices, test_indices = list(kfold.split(range(len(dataset))))[args.fold] if args.dataset in max_degrees: # make sure that correct num is used max_degree = max(degree(d.edge_index[0]).max() for d in dataset).item() specified = max_degrees[args.dataset] assert specified == max_degree, f'max node degree is {max_degree} but was specified as {specified}' train_dataset = dataset[torch.LongTensor(train_indices)] test_dataset = dataset[torch.LongTensor(test_indices)] n = (len(dataset) + 9) // 10 if args.validation: train_dataset, val_dataset = train_dataset[n:], train_dataset[:n] val_loader = DataLoader(val_dataset, batch_size=args.batch_size) train_loader = DataLoader(train_dataset, batch_size=args.batch_size) test_loader = DataLoader(test_dataset, batch_size=args.batch_size) class GINBlock(torch.nn.Module): def __init__(self, in_channels, out_channels): super().__init__() nn = Sequential( Linear(in_channels, out_channels), ReLU(), torch.nn.BatchNorm1d(out_channels), Linear(out_channels, out_channels), ReLU(), torch.nn.BatchNorm1d(out_channels), ) self.conv = GINConv(nn, in_channels) def forward(self, x, edge_index): return self.conv(x, edge_index) class Net(torch.nn.Module): def __init__(self): super(Net, self).__init__() num_features = dataset.num_features dim = args.dim blocks = 5 convs = [] in_channels = num_features for _ in range(blocks): convs.append(GINBlock(in_channels, dim)) in_channels = dim self.convs = torch.nn.ModuleList(convs) self.pools = torch.nn.ModuleList(FSPooling(dim, 5, global_pool=True) for _ in range(blocks)) self.classifier = Sequential( torch.nn.BatchNorm1d(blocks * dim), Linear(blocks * dim, dim), ReLU(inplace=True), torch.nn.Dropout(args.drop), Linear(dim, dataset.num_classes), ) for m in self.modules(): if isinstance(m, torch.nn.Linear): torch.nn.init.xavier_uniform_(m.weight) m.bias.data.fill_(0) def forward(self, data): x, edge_index, batch = data.x, data.edge_index, data.batch features = [] for conv, pool in zip(self.convs, self.pools): x = conv(x, edge_index) if args.model == 'fsort': features.append(pool(x, batch=batch)) elif args.model == 'sum': features.append(global_add_pool(x, batch)) elif args.model == 'mean': features.append(global_mean_pool(x, batch)) else: raise ValueError('invalid model variant') x = torch.cat(features, dim=1) x = self.classifier(x) return F.log_softmax(x, dim=-1) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = Net().to(device) optimizer = torch.optim.Adam(model.parameters(), lr=0.01) def train(epoch): model.train() if epoch % 50 == 0: for param_group in optimizer.param_groups: param_group['lr'] = 0.5 * param_group['lr'] loss_all = 0 for data in train_loader: data = data.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, data.y) loss.backward() loss_all += data.num_graphs * loss.item() optimizer.step() return loss_all / len(train_dataset) def test(loader): model.eval() correct = 0 for data in loader: data = data.to(device) pred = model(data).max(dim=1)[1] correct += pred.eq(data.y).sum().item() return correct / len(loader.dataset) for epoch in range(1, 1 + args.epochs): loss = train(epoch) if args.validation: val_acc = test(val_loader) test_acc = test(test_loader) print('Epoch: {:03d}, Train Loss: {:.5f}, Val Acc: {:.5f}, Test Acc: {:.5f}'. format(epoch, loss, val_acc, test_acc)) else: train_acc = test(train_loader) test_acc = test(test_loader) print('Epoch: {:03d}, Train Loss: {:.5f}, Train Acc: {:.5f}, Test Acc: {:.5f}'. format(epoch, loss, train_acc, test_acc))
[ "cyanogenoid@cyanogenoid.com" ]
cyanogenoid@cyanogenoid.com
b8623d7d3896192cae8214c6fafbcef332a1c310
23117aabee7f76648ec88b083191f336ece61de8
/Customers/migrations/0008_order_status.py
5c7cd5b1fbd9f3b90a6f26dc3b67ccf47fc943a1
[]
no_license
smanjot27/Order-Tracking-System-
49236656de87893309d6fdb0a576348681e0fc28
65d0c432c0233b4cd7ee843a51fb9e22f2f33de5
refs/heads/master
2023-06-28T00:02:22.649004
2021-08-03T12:02:21
2021-08-03T12:02:21
371,034,842
0
0
null
null
null
null
UTF-8
Python
false
false
391
py
# Generated by Django 3.1.7 on 2021-04-28 14:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Customers', '0007_order'), ] operations = [ migrations.AddField( model_name='order', name='status', field=models.CharField(default='ongoing', max_length=30), ), ]
[ "chughsaloni27@gmail.com" ]
chughsaloni27@gmail.com
ed0ca9df220b85c5cd4fccfd803e005bc515f4b4
33633b89288e8b46ce2ce13e1b29a3f2ca79d188
/Athens/online/views.py
b691677665f6344ca71150f191e8b7656ab0248e
[]
no_license
moon-seong/athens
b5e3557d69c13f63afec92e69e65de013240e0df
9dc33c7c1aa84f3e840abb65f2f7327d3fb29bbe
refs/heads/master
2023-01-29T21:31:24.545716
2020-12-14T02:27:47
2020-12-14T02:27:47
311,843,991
0
0
null
null
null
null
UTF-8
Python
false
false
3,936
py
import os from os.path import basename from django.core.paginator import Paginator from django.http import HttpResponse from django.shortcuts import render, redirect from django.utils.http import urlquote from admin.models import * from django.utils import timezone def select_lecture_teacher(request): teacher = teacher_tbl.objects.get(user=request.user.id) lecture =lecture_tbl.objects.filter(t_no_id=teacher.t_no) context = {'lecture':lecture} return render(request, 'online/select_lecture.html', context) def select_online_index_teacher(request,pk): lecture = lecture_tbl.objects.get(l_no=pk) online= online_tbl.objects.filter(l_no_id=lecture.l_no).order_by('-on_date') # 페이징 page = request.GET.get('page', '1') # 페이지 paginator = Paginator(online, 10) # 페이지당 10개 page_obj = paginator.get_page(page) context = {'online': page_obj} return render(request, 'online/select_online_teacher.html', context) def post_online(request): teacher = teacher_tbl.objects.get(user=request.user.id) lecture = lecture_tbl.objects.filter(t_no_id=teacher.t_no) context={'lecture':lecture} if request.method == "POST": select_lec = lecture_tbl.objects.get(l_no=request.POST['l_no']) post=online_tbl.objects.create(on_title=request.POST['on_title'],on_content=request.POST['on_content'],on_div=request.POST['on_div'],l_no_id=select_lec.l_no,on_date=timezone.now()) try: if request.FILES['on_file']: post.on_file = request.FILES['on_file'] except: pass post.save() return redirect('/teacher/online/%s'%(select_lec.l_no)) else: return render(request, 'online/online_post.html', context) def online_contents(request,pk): content = online_tbl.objects.get(pk=pk) fname='' fsize=0 if content.on_file: file = content.on_file fname= basename(file.name) try: with open('%s'%(fname),'wb') as fp: for chunk in file.chunks(): fp.write(chunk) fsize=round(os.path.getsize(fname)/1024) except: pass context={'content':content,'fname':fname,'fsize':fsize} return render(request, 'online/online_contents_t.html', context) def online_download(request): id=request.GET['on_no'] file = online_tbl.objects.get(on_no=id) path = 'media/' + file.on_file.name filename = basename(path) filename=urlquote(filename) with open(path,'rb') as download: response=HttpResponse(download.read(),content_type='application/octet-stream') response['Content-Disposition']=\ "attchment;filename*=UTF-8''{0}".format(filename) return response def online_update(request): teacher = teacher_tbl.objects.get(user=request.user.id) lecture = lecture_tbl.objects.filter(t_no_id=teacher.t_no) id=request.GET['on_no'] update = online_tbl.objects.get(on_no=id) if request.method == 'POST': print('save') select_lec = lecture_tbl.objects.get(l_no=request.POST['l_no']) update.on_title = request.POST['on_title'] try: if request.FILES['on_file']: file = request.FILES['on_file'] update.on_file = file except: pass update.on_div = request.POST['on_div'] update.on_content = request.POST['on_content'] update.l_no_id = select_lec.l_no update.save() return redirect('/teacher/online/content/%s'%(update.on_no)) else: context = {'update': update, 'lecture': lecture} return render(request,'online/online_contents_update.html',context) def online_delete(request): id=request.POST['on_no'] lecture = online_tbl.objects.get(on_no=id) online_tbl.objects.get(on_no=id).delete() return redirect('/teacher/online/%s'%(lecture.l_no.l_no))
[ "anstmdgks123@gmail.com" ]
anstmdgks123@gmail.com
ce59728b7dddf9a1fd6620e26ae3115249116443
44d8cbe0bf7a0eecb09838fee29c0c06d08d9aef
/realtors/models.py
edf467afa4590c3f71873a1f1788ce2ddac18bf5
[]
no_license
MohamedJamaal/BT-Real-State
63c16af969fd3c6000a61b9442ddb1822f353e17
449496e00f95605f4a41d64703df9e0e5d7b1311
refs/heads/master
2020-09-29T00:41:13.625623
2019-12-18T12:55:16
2019-12-18T12:55:16
226,904,125
0
0
null
null
null
null
UTF-8
Python
false
false
500
py
from django.db import models from datetime import datetime class Realtor(models.Model): name = models.CharField(max_length=200) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') description = models.TextField(blank=True) phone = models.CharField(max_length=20) email = models.CharField(max_length=50) is_mvp = models.BooleanField(default=False) hire_date = models.DateTimeField(default = datetime.now , blank = True) def __str__(self): return self.name
[ "mohamed_gamal19@hotmail.com" ]
mohamed_gamal19@hotmail.com
a153664582c7e9c5d5301d14a5f8f29d49160003
03625cc0ffeddb5246e7686c76988889cda30854
/app.py
d2aaace6dbf5ea16a41244cd3abdfd489a08e415
[]
no_license
John-byte62/AI-School
29c3c73943cb2a81f5c46bb7902a1b9aeded2a5c
a383afb0be02a085ff446a0b291c965b9234fb8a
refs/heads/main
2023-05-23T16:47:21.868293
2021-06-13T14:18:59
2021-06-13T14:18:59
375,472,289
0
0
null
null
null
null
UTF-8
Python
false
false
45,802
py
import numpy as np import os import pickle import streamlit as st import sys import tensorflow as tf import urllib from PIL import Image sys.path.append('tl_gan') sys.path.append('pg_gan') import feature_axis import tfutil import tfutil_cpu # This should not be hashed by Streamlit when using st.cache. TL_GAN_HASH_FUNCS = { tf.Session : id } def main(): st.title("Welcome to the world of Programming & AI") """ We are living in an era where we definitely must have heard about the term AI . And many a time we might have wondered what exactly is this AI . And why it is getting discussed now a days. Lets find out As per the definition from Wikipedia , `Artificial intelligence (AI) is intelligence demonstrated by machines, unlike the natural intelligence displayed by humans and animals, which involves consciousness and emotionality.` In the recent years capability of AI has progressed enormously and its effect can be seen in every field . Chatbots , Amazon Alexa, Siri , Google Map , Robotics , Social Media , Airline industry are a small example where we can see the usage of AI. But but but... What's the starting point of AI ? You might have guessed it right . It's programming . So what is programming ? Let us start. """ st.header('What is programming ?') st.write('Programming is the process of creating a set of instructions that tell a computer how to perform a task. Programming can be done using a variety of computer programming languages, such as JavaScript, Python, and C++. And what is a programming language, it is just like a normal language , which we used to chat with computers. ') st.header('Which programming language is the best ?') st.write('Just as we in day to day life cannot choose , which spoken language is the best. Similarly in the world of computers, all the programming languages are beautiful.') st.write('But as we are focused on understanding the working of AI , ``Python`` is the most preferred language for it. Why python ? , because it is relatively easy to understand and it has a huge array of applications.Python is more intuitive than other programming dialects. And with a great community support. (I promise ,you can find solution for any of your python related issues :blush: ) ') st.subheader('Let deep dive into the world of Python. But before that lets play with an AI program , which can generate an imaginary image based on random values ') st.write('On the LHS, you can play with the sliders . But beware, selecting some of the features may produce some **biases**. This AI program used , a neural network which is known as ``` Transparent Latent-space GAN method ``` for tuning the output face characteristics ') st.write(' ') # Download all data files if they aren't already in the working directory. for filename in EXTERNAL_DEPENDENCIES.keys(): download_file(filename) # Read in models from the data files. tl_gan_model, feature_names = load_tl_gan_model() session, pg_gan_model = load_pg_gan_model() st.sidebar.title('Features') seed = 27834096 # If the user doesn't want to select which features to control, these will be used. default_control_features = ['Young','Smiling','Male'] if st.sidebar.checkbox('Show advanced options'): # Randomly initialize feature values. features = get_random_features(feature_names, seed) # Some features are badly calibrated and biased. Removing them block_list = ['Attractive', 'Big_Lips', 'Big_Nose', 'Pale_Skin'] sanitized_features = [feature for feature in features if feature not in block_list] # Let the user pick which features to control with sliders. control_features = st.sidebar.multiselect( 'Control which features?', sorted(sanitized_features), default_control_features) else: features = get_random_features(feature_names, seed) # Don't let the user pick feature values to control. control_features = default_control_features # Insert user-controlled values from sliders into the feature vector. for feature in control_features: features[feature] = st.sidebar.slider(feature, 0, 100, 50, 5) st.sidebar.title('Note') st.sidebar.write( """Playing with the sliders, you _will_ find **biases** that exist in this model. """ ) st.sidebar.write( """For example, moving the `Smiling` slider can turn a face from masculine to feminine or from lighter skin to darker. """ ) st.sidebar.write( """Apps like these that allow you to visually inspect model inputs help you find these biases so you can address them in your model _before_ it's put into production. """ ) # Generate a new image from this feature vector (or retrieve it from the cache). with session.as_default(): image_out = generate_image(session, pg_gan_model, tl_gan_model, features, feature_names) st.image(image_out, width=500, use_column_width=False) st.header('Let us start with Python !! ') with st.beta_expander(label=' What is Python ?'): st.write('Python is a cross-platform programming language, which means that it can run on multiple platforms like Windows, macOS, Linux, and has even been ported to the Java and .NET virtual machines. It is free and open-source.') st.write('Even though most of today\'s Linux and Mac have Python pre-installed in it, the version might be out-of-date. So, it is always a good idea to install the most current version.') with st.beta_expander(label ='Python installation instructions. '): st.subheader('A. The Easiest Way to Run Python') st.write('The easiest way to run Python is by using Thonny IDE.') st.write('The **Thonny IDE** comes with the latest version of Python bundled in it. So you don\'t have to install Python separately.Follow the following steps to run Python on your computer.') st.write(' 1.Download Thonny IDE.') st.write(' 2.Run the installer to install Thonny on your computer.') st.write(' 3.Go to: File > New. Then save the file with **.py** extension. For example, **hello.py**, **example.py** , etc.You can give any name to the file. However, the file name should end with .py') st.write(' 4.Write Python code in the file and save it.') st.subheader('B. Run Python in the Integrated Development Environment (IDE)') st.write('We can use any text editing software to write a Python script file.') st.write('We just need to save it with the .py extension. But using an IDE can make our life a lot easier. IDE is a piece of software that provides useful features like code hinting, syntax highlighting and checking, file explorers, etc. to the programmer for application development.') st.write('By the way, when you install Python, an IDE named **IDLE** is also installed. You can use it to run Python on your computer. It\'s a decent IDE for beginners.Apart from that you can install other popular IDE like **Visual Studio , Pycharm , Spyder etc**') st.subheader('Your first Python Program') st.write('Now that we have Python up and running, we can write our first Python program.') st.write('Let\'s create a very simple program called Hello World. A "Hello, World!" is a simple program that outputs Hello, World! on the screen. Since it\'s a very simple program, it\'s often used to introduce a new programming language to beginners.') st.write('Type the following code') st.write('**print(','\'Hello World\')**') st.write('in any text editor or an IDE and save it as **hello_world.py**','.Then, run the file. You will get the following output. **Hello World** ') st.write('*Congratulations!! You ran your first python program :thumbsup:*') with st.beta_expander(label ='Python Keywords and Identifier.'): st.subheader('Python Keywords') st.write('Keywords are the reserved words in Python.') st.write('We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language.') st.write('In Python, keywords are case sensitive.') st.write('There are 33 keywords in Python 3.7. This number can vary slightly over the course of time.') st.write('All the keywords except **True, False and None** are in lowercase and they must be written as they are. The list of all the keywords is given below.') st.image(Image.open('keywords.JPG'),width=650,use_column_width=False) st.write('Looking at all the keywords at once and trying to figure out what they mean might be overwhelming. So let us ignore it for some moment and let us focus on that we cannot use these names as any other identifier') st.subheader('Python Identifiers') st.write('An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.') st.write('Rules for writing identifiers') st.write('1.Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _ . Names like **myClass, var_1 and print_this_to_screen**, all are valid example.') st.write('2.An identifier cannot start with a digit. **1variable** is invalid, but **variable1** is a valid name.') st.write('3.Keywords cannot be used as identifiers. ') st.write('4.We cannot use special symbols like !, @, #, $, etc. in our identifier. ') st.write('5.An identifier can be of any length.') st.subheader('Things to Remember') st.write('A. Python is a case-sensitive language. This means, **Variable** and **variable** are not the same.Multiple words can be separated using an underscore, like **this_is_a_long_variable.**') st.write('B. Most of the programming languages like C, C++, and Java use braces { } to define a block of code. Python, however, uses indentation.') st.write('C. Code block like a body of a function, loop, etc.**(All this will be discussed later)** starts with indentation and ends with the first unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.') st.write('D. Comments are very important while writing a program. They describe what is going on inside a program, so that a person looking at the source code does not have a hard time figuring it out.Comments are for programmers to better understand a program. Python Interpreter ignores comments.In Python, we use the **hash (#)** symbol to start writing a comment.') st.write('E. For multi line comment , we can use Another way of doing this is to use triple quotes, either \'\'\' or """. ') with st.beta_expander(label ='Python Variables and Datatypes.'): st.subheader('Python Variables') st.write('A variable is a named location used to store data in the memory. It is helpful to think of variables as a container that holds data that can be changed later in the program') st.write('For example , number = 10') st.write('Here, we have created a variable named **number**. We have assigned the value 10 to the variable. You can use the **assignment operator =** to assign a value to a variable.') st.write('You can think of variables as a bag to store books in it and that book can be replaced at any time. :smile:') st.write('number = 10') st.write('number = 1.1') st.write('Initially, the value of **number** was **10**. Later, it was changed to **1.1**. This reassignment can be done several times') st.write('Use **print(number)** command to print the value stored in the variable. Here **number** is the variable name. In this case **1.1** will be printed') st.write('***Note: In Python, we don\'t actually assign values to the variables. Instead, Python gives the reference of the object(value) to the variable.***') st.write('** You can assign multiple values to multiple variables** like ***a, b, c = 5, 3.2, "Hello"*** OR **x = y = z = "same"**') st.write("In first case , a will be 5 , b will be 3.2 and c='Hello' ") st.subheader('Literal') st.write('Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as follows:') st.write('**Numeric Literals** - Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical types: *Integer, Float, and Complex.*') st.write('**String literals** - A string literal is a sequence of characters surrounded by quotes. We can use both single, double, or triple quotes for a string. And, a character literal is a single character surrounded by single or double quotes.Example , *strings = "This is Python"*') st.write('**Boolean literals** - A Boolean literal can have any of the two values: True or False.In Python, True represents the value as 1 and False as 0') st.write('**Special literals** - Python contains one special literal i.e. *None*. We use it to specify that the field has not been created.') st.write("**Literal Collections**-There are four different literal collections *List literals, Tuple literals, Dict literals, and Set literals.* We will deep dive into it , don't worry") st.subheader(' Decoding Literal Collections ') st.write("") st.write('**Python List**') st.write("List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type. Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ]. Example **a = [1, 2.2, 'python']**.We can use the slicing operator [ ] to extract an item or a range of items from a list. The index starts from 0 in Python.") st.image(Image.open('list.JPG'),width=500,use_column_width=False) st.write('Lists are mutable, meaning, the value of elements of a list can be altered.') st.write("") st.write('**Python Tuple**') st.write("Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.It is defined within parentheses () where items are separated by commas.We can use the slicing operator [] to extract items but we cannot change its value." ) st.image(Image.open('tuples.JPG'),width=500,use_column_width=False) st.write("") st.write("**Python Set**") st.write("Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.We can perform set operations like union, intersection on two sets. Sets have unique values. They eliminate duplicates.Since, set are unordered collection, indexing has no meaning. Hence, the slicing operator [] does not work.") st.image(Image.open('set.JPG'),width=500,use_column_width=False) st.write("") st.write("**Python Dictionary**") st.write("Dictionary is an unordered collection of key-value pairs.It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.In Python, dictionaries are defined within braces \{\} with each item being a pair in the form key:value. Key and value can be of any type.") st.image(Image.open('dict.JPG'),width=500,use_column_width=False) with st.beta_expander(label ='Python Operators '): st.header("What are operators in python?") st.write("Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.") st.write("For example : 2+3 will result in 5 .Here, **+** is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the operation.") st.write('**Arithmetic operators**') st.write("Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc.") st.image(Image.open('arith.JPG'),width=600,use_column_width=False) st.write("") st.write("**Comparison operators**") st.write('Comparison operators are used to compare values. It returns either True or False according to the condition') st.image(Image.open('comp.JPG'),width=600,use_column_width=False) st.write("") st.write("**Logical operators**") st.write('Logical operators are the and, or, not operators.') st.image(Image.open('log.JPG'),width=600,use_column_width=False) st.write("") st.write("**Bitwise operators**") st.write('Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.For example, 2 is 10 in binary and 7 is 111.In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)') st.image(Image.open('bit.JPG'),width=600,use_column_width=False) st.write("") st.write("**Assignment operators**") st.write("Assignment operators are used in Python to assign values to variables.a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left.There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. It is equivalent to a = a + 5.") st.image(Image.open('assign.JPG'),width=600,use_column_width=False) st.write("") st.write("Python language offers some special types of operators like the identity operator or the membership operator. They are described below with examples.") st.write("**Identity operatorss :** *is* and *is not* are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical. Kindly look at the below example ") st.image(Image.open('iden.JPG'),width=600,use_column_width=False) st.write('Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. Same is the case with x2 and y2 (strings).But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory although they are equal.') st.write("") st.write("**Membership operators : ** *in and not in* are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).In a dictionary we can only test for presence of key, not the value.") st.image(Image.open('mem.JPG'),width=600,use_column_width=False) with st.beta_expander(label ='Python Flow Controls'): st.header("Python if...else Statement") st.write("Decision making is required when we want to execute a code only if a certain condition is satisfied.The **if…elif…else** statement is used in Python for decision making.") st.image(Image.open('flowchartif.JPG'),width=600,use_column_width=False) st.write("**Example of if...elif...else**") st.image(Image.open('ifelse.JPG'),width=600,use_column_width=False) st.write("When variable num is positive, **Positive number** is printed.") st.write("If num is equal to 0, **Zero** is printed.") st.write("If num is negative, **Negative number** is printed.") st.write("") st.write("**Python Nested if statements**") st.write("We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.") st.write("**Example of nested if...elif...else**") st.image(Image.open('nestedif.JPG'),width=600,use_column_width=False) st.header("Python for Loop") st.write("In this article, you'll learn to iterate over a sequence of elements using the different variations of for loop.") st.write("**What is for loop in Python?**") st.write("The *for* loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.") st.write("There is something known as **range() function** ,through which we can generate a sequence of numbers.range(10) will generate numbers from 0 to 9 (10 numbers).We can also define the start, stop and step size as range(start, stop,step_size). step_size defaults to 1 if not provided. This range() is extensively used with for loop ") st.write("**Example of for loop**") st.image(Image.open('forloop.JPG'),width=600,use_column_width=False) st.write("**for loop with else**") st.write("A for *loop* can have an optional *else* block as well. The else part is executed if the items in the sequence used in for loop exhausts.The *break* keyword can be used to stop a for loop. In such cases, the else part is ignored.Hence, *a for loop's else part runs if no break occurs.*") st.image(Image.open('forelse.JPG'),width=300,use_column_width=False) st.write("Here, the *for* loop prints items of the list until the loop exhausts. When the *for* loop exhausts, it executes the block of code in the *else* and prints *No items left.* Moreover a proper *if .. elif...else* block can also be nested inside for loop") st.header("Python while Loop") st.write("Loops are used in programming to repeat a specific block of code. In this article, you will learn to create a while loop in Python.") st.write("The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.We generally use this loop when we don't know the number of times to iterate beforehand.") st.write("In the while loop, test expression is checked first. The body of the loop is entered only if the *test_expression* evaluates to *True*. After one iteration, the *test expression* is checked again. This process continues until the *test_expression* evaluates to *False*.In Python, the body of the while loop is determined through indentation.The body starts with indentation and the first unindented line marks the end.Python interprets any non-zero value as *True. None and 0* are interpreted as *False*.") st.write("Example: Python while Loop") st.image(Image.open('while.JPG'),width=600,use_column_width=False) st.write("In the above program, the test expression will be True as long as our counter variable i is less than or equal to n (10 in our program).We need to increase the value of the counter variable in the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in an infinite loop (never-ending loop).Finally, the result is displayed.") st.write("**While loop with else**") st.write("Same as with for loops, while loops can also have an optional else block.The else part is executed if the condition in the while loop evaluates to False.The while loop can be terminated with a break statement. In such cases, the else part is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.") st.write("Example to illustrate this") st.image(Image.open('whileelse.JPG'),width=600,use_column_width=False) st.header("Python break , continue and pass") st.write("**What is the use of break and continue in Python?**") st.write("In Python, *break* and *continue* statements can alter the flow of a normal loop.Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.The *break* and *continue* statements are used in these cases.") st.write("**break : **The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.") st.write("**continue :** The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. ") st.write("**pass :** In Python programming, the pass statement is a null statement. The difference between a comment and a *pass* statement in Python is that while the interpreter ignores a *comment* entirely, *pass* is not ignored.Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing. ") with st.beta_expander(label ='Python Functions'): st.write("In Python, a function is a group of related statements that performs a specific task.Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.Furthermore, it avoids repetition and makes the code reusable.") st.write("**Syntax of Function**") st.image(Image.open('func.JPG'),width=300,use_column_width=False) st.write('Above shown is a function definition that consists of the following components.') st.write("1.Keyword *def* that marks the start of the function header.") st.write("2.A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.") st.write("3.Parameters (arguments) through which we pass values to a function. They are optional.") st.write("4.A colon (:) to mark the end of the function header.") st.write("5.Optional documentation string (docstring) to describe what the function does.") st.write("6.One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).") st.write("7.An optional *return* statement to return a value from the function.") st.write("**How to call a function in python?**") st.write('Once we have defined a function, we can call it from another function, program or even the Python prompt. To call a function we simply type the function name with appropriate parameters.') st.write("Below example illustrate how to create a function , define its functionality , returning of value and calling of the function") st.image(Image.open('func_return.JPG'),width=500,use_column_width=False) st.write("**Lambda Function **") st.write("Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.") st.write("Example of lambda function") st.image(Image.open('lamba.JPG'),width=500,use_column_width=False) with st.beta_expander(label ='Food for thought. '): st.write("Apart from all the different topics that we have discussed above , there are many more areas in Python which we can explore. But as we are focusing on how AI program works, using the above knowledge we can now explore the basic nature of neural networks and AI. ") st.header('Let us explore the basic working of Neural Networks and AI !! ') st.write("**Artificial neural networks are a fascinating area of study, although they can be intimidating when just getting started.But do not worry I will try to make everything as simple as possible. So let start our journey ! **") with st.beta_expander("Multi-Layer Perceptrons"): st.write("The field of artificial neural networks is often just called neural networks or multi-layer perceptrons after perhaps the most useful type of neural network. A perceptron is a single neuron model that was a precursor to larger neural networks.") st.write("It is a field that investigates how simple models of biological brains can be used to solve difficult computational tasks like the predictive modeling tasks we see in machine learning. The goal is not to create realistic models of the brain, but instead to develop robust algorithms and data structures that we can use to model difficult problems.") st.write("The power of neural networks comes from their ability to learn the representation in your training data and how to best relate it to the output variable that you want to predict. In this sense neural networks learn a mapping. Mathematically, they are capable of learning any mapping function and have been proven to be a universal approximation algorithm.") st.write("The predictive capability of neural networks comes from the hierarchical or multi-layered structure of the networks. The data structure can pick out (learn to represent) features at different scales or resolutions and combine them into higher-order features. For example from lines, to collections of lines to shapes.") with st.beta_expander("Neurons"): st.write("The building block for neural networks are artificial neurons.") st.write("These are simple computational units that have weighted input signals and produce an output signal using an activation function.") st.image(Image.open('neuron.JPG'),width=300,use_column_width=False) st.write("**Neuron Weights**") st.write("Neuron Weights are nothing but a numerical value which gets attached to an input. These weights have the ability of the getting readjusted . And this behaviour of the weights help us to create awesome neural networks") st.write("For example ,suppose we are passing an input of 10 , then weight can be 0.1 or anything random. That means value of 10*0.1 i.e 1 is passed to next neurons") st.write("**Activation Functions**") st.write("The weighted inputs are summed and passed through an activation function, sometimes called a transfer function.") st.write("An activation function is a simple mapping of summed weighted input to the output of the neuron. It is called an activation function because it governs the threshold at which the neuron is activated and strength of the output signal.") st.write("Historically simple step activation functions were used where if the summed input was above a threshold, for example 0.5, then the neuron would output a value of 1.0, otherwise it would output a 0.0.") st.write("Traditionally non-linear activation functions are used. This allows the network to combine the inputs in more complex ways and in turn provide a richer capability in the functions they can model. Non-linear functions like the logistic also called the sigmoid function were used that output a value between 0 and 1 with an s-shaped distribution, and the hyperbolic tangent function also called tanh that outputs the same distribution over the range -1 to +1.More recently the rectifier activation function has been shown to provide better results.") with st.beta_expander("Networks of Neurons"): st.write("Neurons are arranged into networks of neurons.A row of neurons is called a layer and one network can have multiple layers. The architecture of the neurons in the network is often called the network topology.") st.image(Image.open('nn.JPG'),width=300,use_column_width=False) st.write("**Input or Visible Layers**") st.write("The bottom layer that takes input from your dataset is called the visible layer, because it is the exposed part of the network. Often a neural network is drawn with a visible layer with one neuron per input value or column in your dataset. These are not neurons as described above, but simply pass the input value though to the next layer.") st.write("**Hidden Layers**") st.write("Layers after the input layer are called hidden layers because that are not directly exposed to the input. The simplest network structure is to have a single neuron in the hidden layer that directly outputs the value.") st.write("Given increases in computing power and efficient libraries, very deep neural networks can be constructed. Deep learning can refer to having many hidden layers in your neural network. They are deep because they would have been unimaginably slow to train historically, but may take seconds or minutes to train using modern techniques and hardware.") st.write("**Output Layer**") st.write("The final hidden layer is called the output layer and it is responsible for outputting a value or vector of values that correspond to the format required for the problem.The choice of activation function in he output layer is strongly constrained by the type of problem that you are modeling") with st.beta_expander("Training of Networks"): st.write("Once configured, the neural network needs to be trained on your dataset") st.write("**Data Preparation**") st.write("You must first prepare your data for training on a neural network. Data must be numerical, for example real values. If you have categorical data, such as a sex attribute with the values “male” and “female”, you can convert it to a real-valued representation called a *one hot encoding*. This is where one new column is added for each class value (two columns in the case of sex of male and female) and a 0 or 1 is added for each row depending on the class value for that row.") st.write("This same one hot encoding can be used on the output variable in classification problems with more than one class. This would create a binary vector from a single column that would be easy to directly compare to the output of the neuron in the network’s output layer, that as described above, would output one value for each class.") st.write("Neural networks require the input to be scaled in a consistent way. You can rescale it to the range between 0 and 1 called normalization. Another popular technique is to standardize it so that the distribution of each column has the mean of zero and the standard deviation of 1.") st.write("Scaling also applies to image pixel data. Data such as words can be converted to integers, such as the popularity rank of the word in the dataset and other encoding techniques.") st.write("** Stochastic Gradient Descent **") st.write("The classical and still preferred training algorithm for neural networks is called stochastic gradient descent.") st.write("This is where one row of data is exposed to the network at a time as input. The network processes the input upward activating neurons as it goes to finally produce an output value. This is called a forward pass on the network. It is the type of pass that is also used after the network is trained in order to make predictions on new data.") st.write("The output of the network is compared to the expected output and an error is calculated. This error is then propagated back through the network, one layer at a time, and the weights are updated according to the amount that they contributed to the error. This clever bit of math is called the backpropagation algorithm.") st.write("The process is repeated for all of the examples in your training data. One round of updating the network for the entire training dataset is called an epoch. A network may be trained for tens, hundreds or many thousands of epochs.") st.write("** Weight Updates **") st.write("The weights in the network can be updated from the errors calculated for each training example and this is called online learning. It can result in fast but also chaotic changes to the network.") st.write("Alternatively, the errors can be saved up across all of the training examples and the network can be updated at the end. This is called batch learning and is often more stable.") st.write("Typically, because datasets are so large and because of computational efficiencies, the size of the batch, the number of examples the network is shown before an update is often reduced to a small number, such as tens or hundreds of examples.") st.write("The amount that weights are updated is controlled by a configuration parameters called the learning rate. It is also called the step size and controls the step or change made to network weight for a given error. Often small weight sizes are used such as 0.1 or 0.01 or smaller.") st.write("The update equation can be complemented with additional configuration terms that you can set. ") st.write("1.Momentum is a term that incorporates the properties from the previous weight update to allow the weights to continue to change in the same direction even when there is less error being calculated.") st.write("2.Learning Rate Decay is used to decrease the learning rate over epochs to allow the network to make large changes to the weights at the beginning and smaller fine tuning changes later in the training schedule.") st.write("** Prediction **") st.write("Once a neural network has been trained it can be used to make predictions.") st.write("You can make predictions on test or validation data in order to estimate the skill of the model on unseen data. You can also deploy it operationally and use it to make predictions continuously.") st.write("The network topology and the final set of weights is all that you need to save from the model. Predictions are made by providing the input to the network and performing a forward-pass allowing it to generate an output that you can use as a prediction.") st.write('## Summary') st.write(" So we just completed the basics of Python & Neural Networks.Below are the points that we covered in the blog") st.write("1.Basics of Python language & different concepts related to coding like loops,if..else statement,functions etc.") st.write("2.How neural networks are not models of the brain but are instead computational models for solving complex machine learning problems.") st.write("3.The neural networks are comprised of neurons that have weights and activation functions.") st.write("4.The networks are organized into layers of neurons and are trained using stochastic gradient descent.Moreover it is a good idea to prepare your data before training a neural network model.") st.write("***The field of AI , Machine Learning , Data Science is very vast, but they are one of the most interesting field in today's era. I hope you all will try to deep dive into this field and will make the best out of it. Stay Safe , Stay Healthy , Stay Strong !! ***") st.write("") st.write("") st.write("") st.image(Image.open('end.jpg'),width=800,use_column_width=False) def download_file(file_path): # Don't download the file twice. (If possible, verify the download using the file length.) if os.path.exists(file_path): if "size" not in EXTERNAL_DEPENDENCIES[file_path]: return elif os.path.getsize(file_path) == EXTERNAL_DEPENDENCIES[file_path]["size"]: return # These are handles to two visual elements to animate. weights_warning, progress_bar = None, None try: weights_warning = st.warning("Downloading %s..." % file_path) progress_bar = st.progress(0) with open(file_path, "wb") as output_file: with urllib.request.urlopen(EXTERNAL_DEPENDENCIES[file_path]["url"]) as response: length = int(response.info()["Content-Length"]) counter = 0.0 MEGABYTES = 2.0 ** 20.0 while True: data = response.read(8192) if not data: break counter += len(data) output_file.write(data) # We perform animation by overwriting the elements. weights_warning.warning("Downloading %s... (%6.2f/%6.2f MB)" % (file_path, counter / MEGABYTES, length / MEGABYTES)) progress_bar.progress(min(counter / length, 1.0)) # Finally, we remove these visual elements by calling .empty(). finally: if weights_warning is not None: weights_warning.empty() if progress_bar is not None: progress_bar.empty() # Ensure that load_pg_gan_model is called only once, when the app first loads. @st.cache(allow_output_mutation=True, hash_funcs=TL_GAN_HASH_FUNCS) def load_pg_gan_model(): """ Create the tensorflow session. """ # Open a new TensorFlow session. config = tf.ConfigProto(allow_soft_placement=True) session = tf.Session(config=config) # Must have a default TensorFlow session established in order to initialize the GAN. with session.as_default(): # Read in either the GPU or the CPU version of the GAN with open(MODEL_FILE_GPU if USE_GPU else MODEL_FILE_CPU, 'rb') as f: G = pickle.load(f) return session, G # Ensure that load_tl_gan_model is called only once, when the app first loads. @st.cache(hash_funcs=TL_GAN_HASH_FUNCS) def load_tl_gan_model(): """ Load the linear model (matrix) which maps the feature space to the GAN's latent space. """ with open(FEATURE_DIRECTION_FILE, 'rb') as f: feature_direction_name = pickle.load(f) # Pick apart the feature_direction_name data structure. feature_direction = feature_direction_name['direction'] feature_names = feature_direction_name['name'] num_feature = feature_direction.shape[1] feature_lock_status = np.zeros(num_feature).astype('bool') # Rearrange feature directions using Shaobo's library function. feature_direction_disentangled = \ feature_axis.disentangle_feature_axis_by_idx( feature_direction, idx_base=np.flatnonzero(feature_lock_status)) return feature_direction_disentangled, feature_names def get_random_features(feature_names, seed): """ Return a random dictionary from feature names to feature values within the range [40,60] (out of [0,100]). """ np.random.seed(seed) features = dict((name, 40+np.random.randint(0,21)) for name in feature_names) return features # Hash the TensorFlow session, the pg-GAN model, and the TL-GAN model by id # to avoid expensive or illegal computations. @st.cache(show_spinner=False, hash_funcs=TL_GAN_HASH_FUNCS) def generate_image(session, pg_gan_model, tl_gan_model, features, feature_names): """ Converts a feature vector into an image. """ # Create rescaled feature vector. feature_values = np.array([features[name] for name in feature_names]) feature_values = (feature_values - 50) / 250 # Multiply by Shaobo's matrix to get the latent variables. latents = np.dot(tl_gan_model, feature_values) latents = latents.reshape(1, -1) dummies = np.zeros([1] + pg_gan_model.input_shapes[1][1:]) # Feed the latent vector to the GAN in TensorFlow. with session.as_default(): images = pg_gan_model.run(latents, dummies) # Rescale and reorient the GAN's output to make an image. images = np.clip(np.rint((images + 1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8) # [-1,1] => [0,255] if USE_GPU: images = images.transpose(0, 2, 3, 1) # NCHW => NHWC return images[0] USE_GPU = False FEATURE_DIRECTION_FILE = "feature_direction_2018102_044444.pkl" MODEL_FILE_GPU = "karras2018iclr-celebahq-1024x1024-condensed.pkl" MODEL_FILE_CPU = "karras2018iclr-celebahq-1024x1024-condensed-cpu.pkl" EXTERNAL_DEPENDENCIES = { "feature_direction_2018102_044444.pkl" : { "url": "https://streamlit-demo-data.s3-us-west-2.amazonaws.com/facegan/feature_direction_20181002_044444.pkl", "size": 164742 }, "karras2018iclr-celebahq-1024x1024-condensed.pkl": { "url": "https://streamlit-demo-data.s3-us-west-2.amazonaws.com/facegan/karras2018iclr-celebahq-1024x1024-condensed.pkl", "size": 92338293 }, "karras2018iclr-celebahq-1024x1024-condensed-cpu.pkl": { "url": "https://streamlit-demo-data.s3-us-west-2.amazonaws.com/facegan/karras2018iclr-celebahq-1024x1024-condensed-cpu.pkl", "size": 92340233 } } if __name__ == "__main__": main()
[ "noreply@github.com" ]
John-byte62.noreply@github.com
a8c460d4f7a3a8a53695a5600917c8c78c8340a6
638693af6683c491a1bd9e7402dc6dfdb1fb71ae
/Lesson 2.1.py
0b108b8a75b34e994acf306ef8df793dcac988c7
[]
no_license
BandS-Y/GB-inter-in-Python
efec8616e7a20527389dd9446de75b340220d754
049b466a1c4aa2a634e87c75c3c040a30b2d72bb
refs/heads/master
2023-06-15T04:09:51.641912
2021-07-12T16:18:09
2021-07-12T16:18:09
323,373,280
0
0
null
null
null
null
UTF-8
Python
false
false
161
py
my_list_1 = [2, 5, 8, 2, 12, 12, 4] my_list_2 = [2, 7, 12, 3] new_list = set(my_list_1) - set(my_list_2) print(new_list) print(set(my_list_1) - set(my_list_2))
[ "yuverch@gmail.com" ]
yuverch@gmail.com
204c0c46eb52f0d484a7ee8fc26fbd3cd6aeb9b0
1bbb518e911a84d02042b5b1b4824df2b5d9e46c
/tests/unused_test_shell281.py
72741f653c3071a834137d041e97e20eafa5c99d
[ "MIT" ]
permissive
AdrlVmadriel/pyansys
d6f47273d0e242088ba0d21ed07473a5b59ef7e7
3f97f970546f7cdf1f301f683c9a6bdcd92357c2
refs/heads/master
2020-05-09T10:49:13.887290
2019-04-10T09:41:36
2019-04-10T09:41:36
181,059,354
1
0
NOASSERTION
2019-04-12T18:01:32
2019-04-12T18:01:31
null
UTF-8
Python
false
false
5,433
py
""" In PyAnsys I type ``` test_result = pyansys.open_result('sample.rst') estress,elem,enode = test_result.element_stress(0) print(estress[23]) print(enode[23]) ``` And get ``` [[nan nan nan nan nan nan] [nan nan nan nan nan nan] [nan nan nan nan nan nan] [nan nan nan nan nan nan]] [ 1 82 92 8] ``` And in Ansys I get ``` ELEMENT= 24 SHELL281 NODE SX SY SZ SXY SYZ SXZ 1 -50.863 -0.63898E-030 -215.25 -0.18465E-015 0.10251E-013 -47.847 82 13.635 -0.74815E-030 -178.71 -0.21958E-015 0.11999E-013 17.232 92 -7.1801 -0.84355E-030 -213.77 -0.56253E-015 0.13214E-013 2.0152 8 -47.523 -0.96156E-030 -204.12 -0.30574E-014 0.12646E-013 2.4081 1 107.75 0.13549E-029 454.30 0.45391E-015-0.21674E-013 100.34 82 -28.816 0.15515E-029 372.47 0.38337E-015-0.24955E-013 -35.077 92 14.454 0.16547E-029 429.43 0.80716E-015-0.26217E-013 1.2719 8 94.254 0.19148E-029 409.31 0.59899E-014-0.25281E-013 -3.5690 ``` It would also be really useful to be able to read the Nodal Forces and Moment from the Elemental Solution using the: element_solution_data(0,'ENF',sort=True) From PyAnsys for element 24: ``` array([ 7.1140683e-01, 2.5775826e-06, 1.8592998e+00, 1.7531972e-03, -5.4216904e-12, -6.6381943e-04, 7.8414015e-02, 4.7199319e-06, -1.2074181e+00, -9.0049638e-04, -5.2645028e-12, -3.2152122e-05, 7.3660083e-02, 2.5742002e-05, -1.1951995e+00, -2.7250897e-04, 1.0039868e-12, 1.5112829e-04, -1.9362889e-01, 4.7199323e-06, 1.3849777e+00, 6.4305059e-05, 2.9884493e-12, -2.2116321e-04, 3.0604819e-02, -4.8676171e-05, -1.0389121e-01, 5.7917450e-16, -2.7263033e-25, 4.0045388e-17, -8.5023224e-02, 2.9796447e-05, -5.3827515e+00, -2.2202423e-03, 3.8493188e-11, 7.6806801e-04, -8.5418850e-01, 2.4989351e-06, -3.3126956e-01, -9.2828198e-04, 6.3002242e-11, 8.8052053e-05, 2.3875487e-01, -2.1378659e-05, 4.9762526e+00, 2.5969518e-03, 5.0141464e-11, -1.8303801e-04], dtype=float32)]) ``` And From Ansys: ``` ELEM= 24 FX FY FZ 1 0.71141 0.25776E-005 1.8593 82 0.78414E-001 0.47199E-005 -1.2074 92 0.73660E-001 0.25742E-004 -1.1952 8 -0.19363 0.47199E-005 1.3850 83 0.30605E-001-0.48676E-004-0.10389 86 -0.85023E-001 0.29796E-004 -5.3828 93 -0.85419 0.24989E-005-0.33127 9 0.23875 -0.21379E-004 4.9763 ELEM= 24 MX MY MZ 1 0.17532E-002-0.54217E-011-0.66382E-003 82 -0.90050E-003-0.52645E-011-0.32152E-004 92 -0.27251E-003 0.10040E-011 0.15113E-003 8 0.64305E-004 0.29884E-011-0.22116E-003 83 0.57917E-015-0.27263E-024 0.40045E-016 86 -0.22202E-002 0.38493E-010 0.76807E-003 93 -0.92828E-003 0.63002E-010 0.88052E-004 9 0.25970E-002 0.50141E-010-0.18304E-003 """ import os import numpy as np import pyansys # from pyansys.examples import hexarchivefile # from pyansys.examples import rstfile # from pyansys.examples import fullfile try: __file__ test_path = os.path.dirname(os.path.abspath(__file__)) testfiles_path = os.path.join(test_path, 'testfiles') except: testfiles_path = '/home/alex/afrl/python/source/pyansys/tests/testfiles' ANSYS_ELEM = [[0.17662E-07, 79.410, -11.979, -0.11843E-02, 4.8423, -0.72216E-04], [0.20287E-07, 91.212, 27.364, -0.13603E-02, 4.8423, -0.72216E-04], [0.20287E-07, 91.212, 27.364, -0.13603E-02, -4.8423, 0.72216E-04], [0.17662E-07, 79.410, -11.979, -0.11843E-02, -4.8423, 0.72216E-04]] ANSYS_NODE = [[0.20287E-07, 91.212, 27.364, -0.13603E-02, 4.8423, -0.72216E-04], [0.17662E-07, 79.410, -11.979, -0.11843E-02, 4.8423, -0.72216E-04], [0.17662E-07, 79.410, -11.979, -0.11843E-02, -4.8423, 0.72216E-04], [0.20287E-07, 91.212, 27.364, -0.13603E-02, -4.8423, 0.72216E-04]] result_file = os.path.join(testfiles_path, 'shell281.rst') test_result = pyansys.open_result(result_file, valid_element_types=['281']) # estress, elem, enode = test_result.element_stress(0, in_element_coord_sys=False) estress, elem, enode = test_result.element_stress(0, in_element_coord_sys=True) print(estress[23][:4]) # debug np.any(np.isclose(-50.863, estress[23])) np.isclose(-50.863, estress[23]).any(1).nonzero() # np.isclose(-50.863, table).any(1).nonzero() f.seek(400284 - 8) table = read_table(f, 'f') # f.seek(400284) ncomp = 6 nodstr = 4 nl = 7 # nread = nl*3*nodstr*ncomp # table = read_table(f, 'f', get_nread=False, nread=nread) print((np.isclose(-50.863, table).nonzero()[0] - 1)/table.size) # print(read_table(f, 'i', get_nread=False, nread=1)) # print(table[:10]) # # elem, res = test_result.element_solution_data(0, 'ENF', sort=True) # # print(res[23].reshape(8, -1)) # # fseek(cfile, (ele_table + PTR_ENS_IDX)*4, SEEK_SET) # # fread(&ptrENS, sizeof(int32_t), 1, cfile) # # fseek(cfile, (ele_table + ptrENS)*4, SEEK_SET) # # fread(&ele_data_arr[c, 0], sizeof(float), nread, cfile) # # number of items in this record is NL*3*nodstr*ncomp # ncomp = 6 # nodstr = 4
[ "akascap@gmail.com" ]
akascap@gmail.com
8e3b17e0ec77e9c8fc55297372223b9924b29451
814fc89eed73852b33da2f5a1a1a508a42fe0b66
/github.py
12c1d9153934dd89ce213c18943841eb12631809
[]
no_license
sunil9768/Automatic-social-media-login-by-face_recog-using-selenium
10a779bcdb560bdf47e053dab3408e9157266d74
995ba8608149b7f93eec0bb8342c3ac4a1aef053
refs/heads/master
2020-04-23T06:19:49.189825
2019-03-02T09:41:54
2019-03-02T09:41:54
170,969,700
1
0
null
null
null
null
UTF-8
Python
false
false
583
py
import selenium from selenium import webdriver from getpass import getpass from time import sleep use = "9928686341" pwd = "********" #message=input('Enter your message for status:') browser = webdriver.Chrome('/home/sunil/Downloads/chromedriver_linux64(1)/chromedriver') browser.get('https://github.com/login') username_box = browser.find_element_by_id('login_field') username_box.send_keys(use) sleep(3) pwd_box=browser.find_element_by_id('password') pwd_box.send_keys(pwd) sleep(3) github_login=browser.find_element_by_name('commit') github_login.submit() sleep(3)
[ "noreply@github.com" ]
sunil9768.noreply@github.com
115fd421627ac2c6795ee1bf300c863c52e55f1e
29e57d7de7e2ac762553df61d6fca0b5744620d7
/tests/test_chebtech.py
425f34f9df607737e7fe32579242d61cb705eb6c
[ "BSD-3-Clause" ]
permissive
nbren12/chebpy
a5a26f59c092cf9dd46fab428efc037a1f1266ea
b7df7a0367750836644208c55455e07c351142c1
refs/heads/master
2020-07-13T07:24:23.873572
2016-11-16T06:09:02
2016-11-16T06:09:02
73,889,570
0
0
null
2016-11-16T06:08:29
2016-11-16T06:08:29
null
UTF-8
Python
false
false
24,893
py
# -*- coding: utf-8 -*- """ Unit-tests for pyfun/core/chebtech.py """ from __future__ import division from operator import __add__ from operator import truediv from operator import __mul__ from operator import __neg__ from operator import __pos__ from operator import __sub__ from unittest import TestCase from itertools import combinations from numpy import all from numpy import arange from numpy import array from numpy import cos from numpy import diff from numpy import exp from numpy import linspace from numpy import pi from numpy import sin from numpy.random import rand from numpy.random import seed from matplotlib.pyplot import subplots from chebpy.core.settings import DefaultPrefs from chebpy.core.chebtech import Chebtech2 from chebpy.core.algorithms import standard_chop from tests.utilities import testfunctions from tests.utilities import infnorm from tests.utilities import scaled_tol from tests.utilities import infNormLessThanTol eps = DefaultPrefs.eps seed(0) # staticmethod aliases _vals2coeffs = Chebtech2._vals2coeffs _coeffs2vals = Chebtech2._coeffs2vals # ------------------------ class ChebyshevPoints(TestCase): """Unit-tests for Chebtech2""" def test_chebpts_0(self): self.assertEquals(Chebtech2._chebpts(0).size, 0) def test_vals2coeffs_empty(self): self.assertEquals(_vals2coeffs(array([])).size, 0) def test_coeffs2vals_empty(self): self.assertEquals(_coeffs2vals(array([])).size, 0) # check we are returned the array for an array of size 1 def test_vals2coeffs_size1(self): for k in arange(10): fk = array([k]) self.assertLessEqual(infnorm(_vals2coeffs(fk)-fk), eps) # check we are returned the array for an array of size 1 def test_coeffs2vals_size1(self): for k in arange(10): ak = array([k]) self.assertLessEqual(infnorm(_coeffs2vals(ak)-ak), eps) # TODO: further checks for chepbts # ------------------------------------------------------------------------ # Tests to verify the mutually inverse nature of vals2coeffs and coeffs2vals # ------------------------------------------------------------------------ def vals2coeffs2valsTester(n): def asserter(self): values = rand(n) coeffs = _vals2coeffs(values) _values_ = _coeffs2vals(coeffs) self.assertLessEqual( infnorm(values-_values_), scaled_tol(n) ) return asserter def coeffs2vals2coeffsTester(n): def asserter(self): coeffs = rand(n) values = _coeffs2vals(coeffs) _coeffs_ = _vals2coeffs(values) self.assertLessEqual( infnorm(coeffs-_coeffs_), scaled_tol(n) ) return asserter for k, n in enumerate(2**arange(2,18,2)+1): # vals2coeffs2vals _testfun_ = vals2coeffs2valsTester(n) _testfun_.__name__ = "test_vals2coeffs2vals_{:02}".format(k) setattr(ChebyshevPoints, _testfun_.__name__, _testfun_) # coeffs2vals2coeffs _testfun_ = coeffs2vals2coeffsTester(n) _testfun_.__name__ = "test_coeffs2vals2coeffs_{:02}".format(k) setattr(ChebyshevPoints, _testfun_.__name__, _testfun_) # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ # Add second-kind Chebyshev points test cases to ChebyshevPoints # ------------------------------------------------------------------------ chebpts2_testlist = ( (Chebtech2._chebpts(1), array([0.]), eps), (Chebtech2._chebpts(2), array([-1., 1.]), eps), (Chebtech2._chebpts(3), array([-1., 0., 1.]), eps), (Chebtech2._chebpts(4), array([-1., -.5, .5, 1.]), 2*eps), (Chebtech2._chebpts(5), array([-1., -2.**(-.5), 0., 2.**(-.5), 1.]), eps), ) for k, (a,b,tol) in enumerate(chebpts2_testlist): _testfun_ = infNormLessThanTol(a,b,tol) _testfun_.__name__ = "test_chebpts_{:02}".format(k+1) setattr(ChebyshevPoints, _testfun_.__name__, _testfun_) # check the output is of the correct length, the endpoint values are -1 # and 1, respectively, and that the sequence is monotonically increasing def chebptsLenTester(k): def asserter(self): pts = Chebtech2._chebpts(k) self.assertEquals(pts.size, k) self.assertEquals(pts[0], -1.) self.assertEquals(pts[-1], 1.) self.assertTrue( all(diff(pts)) > 0 ) return asserter for k, n in enumerate(2**arange(2,18,2)): _testfun_ = chebptsLenTester(n+3) _testfun_.__name__ = "test_chebpts_len_{:02}".format(k) setattr(ChebyshevPoints, _testfun_.__name__, _testfun_) # ------------------------------------------------------------------------ class ClassUsage(TestCase): """Unit-tests for miscelaneous Chebtech2 class usage""" def setUp(self): self.ff = Chebtech2.initfun_fixedlen(lambda x: sin(30*x), 100) self.xx = -1 + 2*rand(100) # tests for emptiness of Chebtech2 objects def test_isempty_True(self): f = Chebtech2(array([])) self.assertTrue(f.isempty) self.assertFalse(not f.isempty) def test_isempty_False(self): f = Chebtech2(array([1.])) self.assertFalse(f.isempty) self.assertTrue(not f.isempty) # tests for constantness of Chebtech2 objects def test_isconst_True(self): f = Chebtech2(array([1.])) self.assertTrue(f.isconst) self.assertFalse(not f.isconst) def test_isconst_False(self): f = Chebtech2(array([])) self.assertFalse(f.isconst) self.assertTrue(not f.isconst) # check the size() method is working properly def test_size(self): cfs = rand(10) self.assertEquals(Chebtech2(array([])).size, 0) self.assertEquals(Chebtech2(array([1.])).size, 1) self.assertEquals(Chebtech2(cfs).size, cfs.size) # test the different permutations of self(xx, ..) def test_call(self): self.ff(self.xx) def test_call_bary(self): self.ff(self.xx, "bary") self.ff(self.xx, how="bary") def test_call_clenshaw(self): self.ff(self.xx, "clenshaw") self.ff(self.xx, how="clenshaw") def test_call_bary_vs_clenshaw(self): b = self.ff(self.xx, "clenshaw") c = self.ff(self.xx, "bary") self.assertLessEqual(infnorm(b-c), 5e1*eps) def test_call_raises(self): self.assertRaises(ValueError, self.ff, self.xx, "notamethod") self.assertRaises(ValueError, self.ff, self.xx, how="notamethod") def test_prolong(self): for k in [0, 1, 20, self.ff.size, 200]: self.assertEquals(self.ff.prolong(k).size, k) def test_vscale_empty(self): gg = Chebtech2(array([])) self.assertEquals(gg.vscale, 0.) def test_copy(self): ff = self.ff gg = self.ff.copy() self.assertEquals(ff, ff) self.assertEquals(gg, gg) self.assertNotEquals(ff, gg) self.assertEquals( infnorm(ff.coeffs - gg.coeffs), 0) def test_simplify(self): gg = self.ff.simplify() # check that simplify is calling standard_chop underneath self.assertEqual(gg.size, standard_chop(self.ff.coeffs)) self.assertEqual(infnorm(self.ff.coeffs[:gg.size]-gg.coeffs), 0) # check we are returned a copy of self's coeffcients by changing # one entry of gg fcfs = self.ff.coeffs gcfs = gg.coeffs self.assertEqual((fcfs[:gg.size]-gcfs).sum(),0) gg.coeffs[0] = 1 self.assertNotEqual((fcfs[:gg.size]-gcfs).sum(),0) # -------------------------------------- # vscale estimates # -------------------------------------- vscales = [ # (function, number of points, vscale) (lambda x: sin(4*pi*x), 40, 1), (lambda x: cos(x), 15, 1), (lambda x: cos(4*pi*x), 39, 1), (lambda x: exp(cos(4*pi*x)), 181, exp(1)), (lambda x: cos(3244*x), 3389, 1), (lambda x: exp(x), 15, exp(1)), (lambda x: 1e10*exp(x), 15, 1e10*exp(1)), (lambda x: 0*x+1., 1, 1), ] def definiteIntegralTester(fun, n, vscale): ff = Chebtech2.initfun_fixedlen(fun, n) def tester(self): absdiff = abs(ff.vscale-vscale) self.assertLessEqual(absdiff, .1*vscale) return tester for k, args in enumerate(vscales): _testfun_ = definiteIntegralTester(*args) _testfun_.__name__ = "test_vscale_{:02}".format(k) setattr(ClassUsage, _testfun_.__name__, _testfun_) class Plotting(TestCase): """Unit-tests for Chebtech2 plotting methods""" def setUp(self): f = lambda x: sin(3*x) + 5e-1*cos(30*x) self.f0 = Chebtech2.initfun_fixedlen(f, 100) self.f1 = Chebtech2.initfun_adaptive(f) def test_plot(self): fig, ax = subplots() self.f0.plot(ax=ax) def test_plotcoeffs(self): fig, ax = subplots() self.f0.plotcoeffs(ax=ax) self.f1.plotcoeffs(ax=ax, color="r") class Calculus(TestCase): """Unit-tests for Chebtech2 calculus operations""" def setUp(self): self.emptyfun = Chebtech2(array([])) # tests for the correct results in the empty cases def test_sum_empty(self): self.assertEqual(self.emptyfun.sum(), 0) def test_cumsum_empty(self): self.assertTrue(self.emptyfun.cumsum().isempty) def test_diff_empty(self): self.assertTrue(self.emptyfun.diff().isempty) # -------------------------------------- # definite integrals # -------------------------------------- def_integrals = [ # (function, number of points, integral, tolerance) (lambda x: sin(x), 14, .0, eps), (lambda x: sin(4*pi*x), 40, .0, 1e1*eps), (lambda x: cos(x), 15, 1.682941969615793, 2*eps), (lambda x: cos(4*pi*x), 39, .0, 2*eps), (lambda x: exp(cos(4*pi*x)), 182, 2.532131755504016, 4*eps), (lambda x: cos(3244*x), 3389, 5.879599674161602e-04, 5e2*eps), (lambda x: exp(x), 15, exp(1)-exp(-1), 2*eps), (lambda x: 1e10*exp(x), 15, 1e10*(exp(1)-exp(-1)), 4e10*eps), (lambda x: 0*x+1., 1, 2, eps), ] def definiteIntegralTester(fun, n, integral, tol): ff = Chebtech2.initfun_fixedlen(fun, n) def tester(self): absdiff = abs(ff.sum()-integral) self.assertLessEqual(absdiff, tol) return tester for k, (fun, n, integral, tol) in enumerate(def_integrals): _testfun_ = definiteIntegralTester(fun, n, integral, tol) _testfun_.__name__ = "test_sum_{:02}".format(k) setattr(Calculus, _testfun_.__name__, _testfun_) # -------------------------------------- # indefinite integrals # -------------------------------------- indef_integrals = [ # (function, indefinite integral, number of points, tolerance) (lambda x: 0*x+1., lambda x: x, 1, eps), (lambda x: x, lambda x: 1/2*x**2, 2, 2*eps), (lambda x: x**2, lambda x: 1/3*x**3, 3, 2*eps), (lambda x: x**3, lambda x: 1/4*x**4, 4, 2*eps), (lambda x: x**4, lambda x: 1/5*x**5, 5, 2*eps), (lambda x: x**5, lambda x: 1/6*x**6, 6, 4*eps), (lambda x: sin(x), lambda x: -cos(x), 16, 2*eps), (lambda x: cos(3*x), lambda x: 1./3*sin(3*x), 23, 2*eps), (lambda x: exp(x), lambda x: exp(x), 16, 3*eps), (lambda x: 1e10*exp(x), lambda x: 1e10*exp(x), 16, 1e10*(3*eps)), ] def indefiniteIntegralTester(fun, dfn, n, tol): ff = Chebtech2.initfun_fixedlen(fun, n) gg = Chebtech2.initfun_fixedlen(dfn, n+1) coeffs = gg.coeffs coeffs[0] = coeffs[0] - dfn(array([-1])) def tester(self): absdiff = infnorm(ff.cumsum().coeffs - coeffs) self.assertLessEqual(absdiff, tol) return tester for k, (fun, dfn, n, tol) in enumerate(indef_integrals): _testfun_ = indefiniteIntegralTester(fun, dfn, n, tol) _testfun_.__name__ = "test_cumsum_{:02}".format(k) setattr(Calculus, _testfun_.__name__, _testfun_) # -------------------------------------- # derivatives # -------------------------------------- derivatives = [ # (function, derivative, number of points, tolerance) (lambda x: 0*x+1., lambda x: 0*x+0, 1, eps), (lambda x: x, lambda x: 0*x+1, 2, 2*eps), (lambda x: x**2, lambda x: 2*x, 3, 2*eps), (lambda x: x**3, lambda x: 3*x**2, 4, 2*eps), (lambda x: x**4, lambda x: 4*x**3, 5, 3*eps), (lambda x: x**5, lambda x: 5*x**4, 6, 4*eps), (lambda x: sin(x), lambda x: cos(x), 16, 5e1*eps), (lambda x: cos(3*x), lambda x: -3*sin(3*x), 23, 5e2*eps), (lambda x: exp(x), lambda x: exp(x), 16, 2e2*eps), (lambda x: 1e10*exp(x), lambda x: 1e10*exp(x), 16, 1e10*2e2*eps), ] def derivativeTester(fun, der, n, tol): ff = Chebtech2.initfun_fixedlen(fun, n) gg = Chebtech2.initfun_fixedlen(der, max(n-1,1)) def tester(self): absdiff = infnorm(ff.diff().coeffs - gg.coeffs) self.assertLessEqual(absdiff, tol) return tester for k, (fun, der, n, tol) in enumerate(derivatives): _testfun_ = derivativeTester(fun, der, n, tol) _testfun_.__name__ = "test_diff_{:02}".format(k) setattr(Calculus, _testfun_.__name__, _testfun_) class Construction(TestCase): """Unit-tests for construction of Chebtech2 objects""" #TODO: expand to all the constructor variants def test_initvalues(self): # test n = 0 case separately vals = rand(0) fun = Chebtech2.initvalues(vals) cfs = Chebtech2._vals2coeffs(vals) self.assertTrue(fun.coeffs.size==cfs.size==0) # now test the other cases for n in range(1,10): vals = rand(n) fun = Chebtech2.initvalues(vals) cfs = Chebtech2._vals2coeffs(vals) self.assertEqual(infnorm(fun.coeffs-cfs), 0.) def test_initidentity(self): x = Chebtech2.initidentity() s = -1 + 2*rand(10000) self.assertEqual(infnorm(s-x(s)), 0.) def test_coeff_construction(self): coeffs = rand(10) f = Chebtech2(coeffs) self.assertIsInstance(f, Chebtech2) self.assertLess(infnorm(f.coeffs-coeffs), eps) def test_const_construction(self): ff = Chebtech2.initconst(1.) self.assertEquals(ff.size, 1) self.assertTrue(ff.isconst) self.assertFalse(ff.isempty) self.assertRaises(ValueError, Chebtech2.initconst, [1.]) def test_empty_construction(self): ff = Chebtech2.initempty() self.assertEquals(ff.size, 0) self.assertFalse(ff.isconst) self.assertTrue(ff.isempty) self.assertRaises(TypeError, Chebtech2.initempty, [1.]) def adaptiveTester(fun, funlen): ff = Chebtech2.initfun_adaptive(fun) def tester(self): self.assertEquals(ff.size, funlen) return tester def fixedlenTester(fun, n): ff = Chebtech2.initfun_fixedlen(fun, n) def tester(self): self.assertEquals(ff.size, n) return tester for (fun, funlen, _) in testfunctions: # add the adaptive tests _testfun_ = adaptiveTester(fun, funlen) _testfun_.__name__ = "test_adaptive_{}".format(fun.__name__) setattr(Construction, _testfun_.__name__, _testfun_) # add the fixedlen tests for n in array([50, 500]): _testfun_ = fixedlenTester(fun, n) _testfun_.__name__ = \ "test_fixedlen_{}_{:003}pts".format(fun.__name__, n) setattr(Construction, _testfun_.__name__, _testfun_) class Algebra(TestCase): """Unit-tests for Chebtech2 algebraic operations""" def setUp(self): self.xx = -1 + 2 * rand(1000) self.emptyfun = Chebtech2.initempty() # check (empty Chebtech) + (Chebtech) = (empty Chebtech) # and (Chebtech) + (empty Chebtech) = (empty Chebtech) def test__add__radd__empty(self): for (fun, funlen, _) in testfunctions: chebtech = Chebtech2.initfun_fixedlen(fun, funlen) self.assertTrue((self.emptyfun+chebtech).isempty) self.assertTrue((chebtech+self.emptyfun).isempty) # check the output of (constant + Chebtech) # and (Chebtech + constant) def test__add__radd__constant(self): xx = self.xx for (fun, funlen, _) in testfunctions: for const in (-1, 1, 10, -1e5): f = lambda x: const + fun(x) techfun = Chebtech2.initfun_fixedlen(fun, funlen) f1 = const + techfun f2 = techfun + const tol = 5e1 * eps * abs(const) self.assertLessEqual(infnorm(f(xx)-f1(xx)), tol) self.assertLessEqual(infnorm(f(xx)-f2(xx)), tol) # check (empty Chebtech) - (Chebtech) = (empty Chebtech) # and (Chebtech) - (empty Chebtech) = (empty Chebtech) def test__sub__rsub__empty(self): for (fun, funlen, _) in testfunctions: chebtech = Chebtech2.initfun_fixedlen(fun, funlen) self.assertTrue((self.emptyfun-chebtech).isempty) self.assertTrue((chebtech-self.emptyfun).isempty) # check the output of constant - Chebtech # and Chebtech - constant def test__sub__rsub__constant(self): xx = self.xx for (fun, funlen, _) in testfunctions: for const in (-1, 1, 10, -1e5): techfun = Chebtech2.initfun_fixedlen(fun, funlen) f = lambda x: const - fun(x) g = lambda x: fun(x) - const ff = const - techfun gg = techfun - const tol = 5e1 * eps * abs(const) self.assertLessEqual(infnorm(f(xx)-ff(xx)), tol) self.assertLessEqual(infnorm(g(xx)-gg(xx)), tol) # check (empty Chebtech) * (Chebtech) = (empty Chebtech) # and (Chebtech) * (empty Chebtech) = (empty Chebtech) def test__mul__rmul__empty(self): for (fun, funlen, _) in testfunctions: chebtech = Chebtech2.initfun_fixedlen(fun, funlen) self.assertTrue((self.emptyfun*chebtech).isempty) self.assertTrue((chebtech*self.emptyfun).isempty) # check the output of constant * Chebtech # and Chebtech * constant def test__mul__rmul__constant(self): xx = self.xx for (fun, funlen, _) in testfunctions: for const in (-1, 1, 10, -1e5): techfun = Chebtech2.initfun_fixedlen(fun, funlen) f = lambda x: const * fun(x) g = lambda x: fun(x) * const ff = const * techfun gg = techfun * const tol = 5e1 * eps * abs(const) self.assertLessEqual(infnorm(f(xx)-ff(xx)), tol) self.assertLessEqual(infnorm(g(xx)-gg(xx)), tol) # check (empty Chebtech) / (Chebtech) = (empty Chebtech) # and (Chebtech) / (empty Chebtech) = (empty Chebtech) def test_truediv_empty(self): for (fun, funlen, _) in testfunctions: chebtech = Chebtech2.initfun_fixedlen(fun, funlen) self.assertTrue(truediv(self.emptyfun,chebtech).isempty) self.assertTrue(truediv(chebtech,self.emptyfun).isempty) # __truediv__ self.assertTrue((self.emptyfun/chebtech).isempty) self.assertTrue((chebtech/self.emptyfun).isempty) # check the output of constant / Chebtech # and Chebtech / constant # this tests truediv, __rdiv__, __truediv__, __rtruediv__, since # from __future__ import division is executed at the top of the file # TODO: find a way to test truediv and __truediv__ genuinely separately def test_truediv_constant(self): xx = self.xx for (fun, funlen, hasRoots) in testfunctions: for const in (-1, 1, 10, -1e5): tol = eps*abs(const) techfun = Chebtech2.initfun_fixedlen(fun, funlen) g = lambda x: fun(x) / const gg = techfun / const self.assertLessEqual(infnorm(g(xx)-gg(xx)), 2*gg.size*tol) # don't do the following test for functions with roots if not hasRoots: f = lambda x: const / fun(x) ff = const / techfun self.assertLessEqual(infnorm(f(xx)-ff(xx)), 3*ff.size*tol) # check +(empty Chebtech) = (empty Chebtech) def test__pos__empty(self): self.assertTrue((+self.emptyfun).isempty) # check -(empty Chebtech) = (empty Chebtech) def test__neg__empty(self): self.assertTrue((-self.emptyfun).isempty) # add tests for the binary operators def binaryOpTester(f, g, binop, nf, ng): ff = Chebtech2.initfun_fixedlen(f, nf) gg = Chebtech2.initfun_fixedlen(g, ng) FG = lambda x: binop(f(x),g(x)) fg = binop(ff, gg) def tester(self): vscl = max([ff.vscale, gg.vscale]) lscl = max([ff.size, gg.size]) self.assertLessEqual(infnorm(fg(self.xx)-FG(self.xx)), 3*vscl*lscl*eps) if binop is __mul__: # check simplify is not being called in __mul__ self.assertEqual(fg.size, ff.size+gg.size-1) return tester # note: defining __radd__(a,b) = __add__(b,a) and feeding this into the # test will not in fact test the __radd__ functionality of the class. These # test need to be added manually to the class. binops = ( __add__, truediv, __mul__, __sub__, ) for binop in binops: # add generic binary operator tests for (f, nf, _), (g, ng, denomRoots) in combinations(testfunctions, 2): if binop is truediv and denomRoots: # skip truediv test if the denominator has roots pass else: _testfun_ = binaryOpTester(f, g, binop, nf, ng) _testfun_.__name__ = \ "test{}{}_{}".format(binop.__name__, f.__name__, g.__name__) setattr(Algebra, _testfun_.__name__, _testfun_) # add tests for the unary operators def unaryOpTester(unaryop, f, nf): ff = Chebtech2.initfun_fixedlen(f, nf) gg = lambda x: unaryop(f(x)) GG = unaryop(ff) def tester(self): self.assertLessEqual(infnorm(gg(self.xx)-GG(self.xx)), 4e1*eps) return tester unaryops = ( __pos__, __neg__, ) for unaryop in unaryops: for (f, nf, _) in testfunctions: _testfun_ = unaryOpTester(unaryop, f, nf) _testfun_.__name__ = \ "test{}{}".format(unaryop.__name__, f.__name__) setattr(Algebra, _testfun_.__name__, _testfun_) class Roots(TestCase): def test_empty(self): ff = Chebtech2.initempty() self.assertEquals(ff.roots().size, 0) def test_const(self): ff = Chebtech2.initconst(0.) gg = Chebtech2.initconst(2.) self.assertEquals(ff.roots().size, 0) self.assertEquals(gg.roots().size, 0) # add tests for roots def rootsTester(f, roots, tol): ff = Chebtech2.initfun_adaptive(f) rts = ff.roots() def tester(self): self.assertLessEqual(infnorm(rts-roots), tol) return tester rootstestfuns = ( (lambda x: 3*x+2., array([-2/3]), 1*eps), (lambda x: x**2, array([0.,0.]), 1*eps), (lambda x: x**2+.2*x-.08, array([-.4, .2]), 1*eps), (lambda x: sin(x), array([0]), 1*eps), (lambda x: cos(2*pi*x), array([-0.75, -0.25, 0.25, 0.75]), 1*eps), (lambda x: sin(100*pi*x), linspace(-1,1,201), 1*eps), (lambda x: sin(5*pi/2*x), array([-.8, -.4, 0, .4, .8]), 1*eps) ) for k, args in enumerate(rootstestfuns): _testfun_ = rootsTester(*args) _testfun_.__name__ = "test_roots_{}".format(k) setattr(Roots, _testfun_.__name__, _testfun_) # reset the testsfun variable so it doesn't get picked up by nose _testfun_ = None
[ "mrichardson82@gmail.com" ]
mrichardson82@gmail.com
6a6424b36571b772e02240b83645ca0e666bc507
1d42fda48e152fc4bc06ebff73ef5560da192880
/DT-Tours-Backend/dt_tours/wsgi.py
66ebe450274d2c0b6459db2e91d8f206187a1e4e
[]
no_license
digtaltech/Hack123
ce6b7d86f7df5cf1acfd764d51f2bd3b39e07139
6e73706c941646b2a6fb26e12da387d1cdae3d65
refs/heads/master
2023-06-10T00:30:19.162096
2021-06-20T09:42:29
2021-06-20T09:42:29
378,513,845
0
0
null
null
null
null
UTF-8
Python
false
false
393
py
""" WSGI config for dt_tours project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dt_tours.settings') application = get_wsgi_application()
[ "kirill.bodunoff@gmail.com" ]
kirill.bodunoff@gmail.com
deff27ffbeed2cb9da0b98ccb70b61f889a99bf2
2b390e9d541b75784cf743cb14355157f00f81ef
/docs/conf.py
4388b0e9bcbbcea7e651ccfa8a9ef0c57910c878
[]
no_license
pickmylight/docker-selenium-python
f64dbd976908041aa92cf0a43f11acd37b1140bc
39cfbeb09dcf5a11ef0457ac60f960f8128f990b
refs/heads/main
2023-07-18T04:21:21.039193
2021-07-09T12:01:11
2021-07-09T12:01:11
317,457,192
0
0
null
null
null
null
UTF-8
Python
false
false
2,179
py
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../examples/')) # -- Project information ----------------------------------------------------- project = 'Docker Selenium Python' copyright = '2021, pickmylight' author = 'pickmylight' # The full version, including alpha/beta/rc tags release = '1.3' # -- General configuration --------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] napoleon_include_init_with_doc = False napoleon_use_ivar = True napoleon_google_docstring = False napoleon_use_rtype = False napoleon_use_param = False
[ "paul_schmidt@mail.de" ]
paul_schmidt@mail.de
798ac583a3c35cf33ed0c7eb34306cb302348e0e
7922dd41be02e9b0246774f6af5c55f8ab599a96
/demo/knndemo1.py
51a07a9488cd0aea3531a6d236af6a9678bde0dd
[]
no_license
song-hm/machineLearning
a5d057fd067039ddb16d9f3b211d8bbed6602cf6
b9312778594967a632eb0b15299c1aa848099daf
refs/heads/master
2020-05-23T13:08:10.564429
2019-06-18T14:28:00
2019-06-18T14:28:00
186,770,506
0
0
null
null
null
null
UTF-8
Python
false
false
691
py
import numpy as np import collections as c data = np.array([ [154,1], [126,2], [70,2], [196,2], [161,2], [371,4] ]) # 输入值 feature = (data[:,0]) # 结果label ,-1表示取最后一列 label = data[:,-1] # 预测点 predictPoint = 200 # 计算每个投掷点与predictPoint的距离 distance = list(map(lambda x:abs(predictPoint-x),feature)) #对distance的集合元素从小到大排列(返回元素排序的下标位置) sortindex = (np.argsort(distance)) #用排序的sortindex操作label集合 sortedlabel = (label[sortindex]) #knn算法的k取最近的三个邻居 k = 3 print(c.Counter(sortedlabel[0:k]).most_common(1)[0][0])
[ "2516107012@qq.com" ]
2516107012@qq.com
68c1abdeff6e2d3abeb950bffdabb091288a58d4
06f118ffe64655cf608865435e0ea01de195a964
/my_memory_card.py
f44a4025956ebd4daafae8012518daab277b67f3
[]
no_license
strvlad96/MC
2c2d9689a892717d7c652241cd19c8e8c05cd209
54412fb0e984120b8aae324025ca8cc6a3e8c202
refs/heads/main
2023-08-27T20:13:39.830043
2021-11-14T10:22:42
2021-11-14T10:22:42
427,896,501
0
0
null
null
null
null
UTF-8
Python
false
false
9,826
py
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import ( QApplication, QWidget, QHBoxLayout, QVBoxLayout, QGroupBox, QButtonGroup, QRadioButton, QPushButton, QLabel) from random import shuffle, randint class Question(): def __init__(self, question, right_answer, wrong1, wrong2, wrong3): # все строки надо задать при создании объекта, они запоминаются в свойства self.question = question self.right_answer = right_answer self.wrong1 = wrong1 self.wrong2 = wrong2 self.wrong3 = wrong3 questions_list = [] questions_list.append(Question('Государственный язык Бразилии', 'Португальский', 'Английский', 'Испанский', 'Бразильский')) questions_list.append(Question('Какого цвета нет на флаге России?', 'Зелёный', 'Красный', 'Белый', 'Синий')) questions_list.append(Question('Национальная хижина якутов', 'Ураса', 'Юрта', 'Иглу', 'Хата')) points = 0 questions_count = 0 app = QApplication([]) btn_OK = QPushButton('Ответить') # кнопка ответа lb_Question = QLabel('Самый сложный вопрос в мире!') # текст вопроса RadioGroupBox = QGroupBox("Варианты ответов") # группа на экране для переключателей с ответами rbtn_1 = QRadioButton('Вариант 1') rbtn_2 = QRadioButton('Вариант 2') rbtn_3 = QRadioButton('Вариант 3') rbtn_4 = QRadioButton('Вариант 4') RadioGroup = QButtonGroup() # это для группировки переключателей, чтобы управлять их поведением RadioGroup.addButton(rbtn_1) RadioGroup.addButton(rbtn_2) RadioGroup.addButton(rbtn_3) RadioGroup.addButton(rbtn_4) layout_ans1 = QHBoxLayout() layout_ans2 = QVBoxLayout() # вертикальные будут внутри горизонтального layout_ans3 = QVBoxLayout() layout_ans2.addWidget(rbtn_1) # два ответа в первый столбец layout_ans2.addWidget(rbtn_2) layout_ans3.addWidget(rbtn_3) # два ответа во второй столбец layout_ans3.addWidget(rbtn_4) layout_ans1.addLayout(layout_ans2) layout_ans1.addLayout(layout_ans3) # разместили столбцы в одной строке RadioGroupBox.setLayout(layout_ans1) # готова "панель" с вариантами ответов AnsGroupBox = QGroupBox("Результат теста") lb_Result = QLabel('прав ты или нет?') # здесь размещается надпись "правильно" или "неправильно" lb_Correct = QLabel('ответ будет тут!') # здесь будет написан текст правильного ответа layout_res = QVBoxLayout() layout_res.addWidget(lb_Result, alignment=(Qt.AlignLeft | Qt.AlignTop)) layout_res.addWidget(lb_Correct, alignment=Qt.AlignHCenter, stretch=2) AnsGroupBox.setLayout(layout_res) # ResultGroupBox = QGroupBox('Результат тестирования') # lb_Result_Test = QLabel('') layout_test_res = QVBoxLayout() layout_test_res.addWidget(lb_Result_Test, alignment=(Qt.AlignLeft | Qt.AlignTop)) # ResultGroupBox.setLayout(layout_test_res) layout_line1 = QHBoxLayout() # вопрос layout_line2 = QHBoxLayout() # варианты ответов или результат теста layout_line3 = QHBoxLayout() # кнопка "Ответить" layout_line1.addWidget(lb_Question, alignment=(Qt.AlignHCenter | Qt.AlignVCenter)) layout_line2.addWidget(RadioGroupBox) layout_line2.addWidget(AnsGroupBox) layout_line2.addWidget(ResultGroupBox) AnsGroupBox.hide() # скроем панель с ответом, сначала должна быть видна панель вопросов # ResultGroupBox.hide() layout_line3.addStretch(1) layout_line3.addWidget(btn_OK, stretch=2) # кнопка должна быть большой layout_line3.addStretch(1) layout_card = QVBoxLayout() layout_card.addLayout(layout_line1, stretch=2) layout_card.addLayout(layout_line2, stretch=8) layout_card.addStretch(1) layout_card.addLayout(layout_line3, stretch=1) layout_card.addStretch(1) layout_card.setSpacing(5) # пробелы между содержимым def show_result(): ''' показать панель ответов ''' RadioGroupBox.hide() AnsGroupBox.show() btn_OK.setText('Следующий вопрос') def show_question(): ''' показать панель вопросов ''' RadioGroupBox.show() AnsGroupBox.hide() btn_OK.setText('Ответить') # сбросить выбранную радио-кнопку RadioGroup.setExclusive(False) # сняли ограничения, чтобы можно было сбросить выбор радиокнопки rbtn_1.setChecked(False) rbtn_2.setChecked(False) rbtn_3.setChecked(False) rbtn_4.setChecked(False) RadioGroup.setExclusive(True) # вернули ограничения, теперь только одна радиокнопка может быть выбрана answers = [rbtn_1, rbtn_2, rbtn_3, rbtn_4] def ask(q: Question): ''' функция записывает значения вопроса и ответов в соответствующие виджеты, при этом варианты ответов распределяются случайным образом''' shuffle(answers) # перемешали список из кнопок, теперь на первом месте списка какая-то непредсказуемая кнопка answers[0].setText(q.right_answer) # первый элемент списка заполним правильным ответом, остальные - неверными answers[1].setText(q.wrong1) answers[2].setText(q.wrong2) answers[3].setText(q.wrong3) lb_Question.setText(q.question) # вопрос lb_Correct.setText(q.right_answer) # ответ questions_list.remove(q) show_question() # показываем панель вопросов def show_correct(res): ''' показать результат - установим переданный текст в надпись "результат" и покажем нужную панель ''' lb_Result.setText(res) show_result() def check_answer(): ''' если выбран какой-то вариант ответа, то надо проверить и показать панель ответов''' global points, questions_count if answers[0].isChecked(): # правильный ответ! points += 1 questions_count += 1 show_correct('Правильно! У вас ' + str(points) + ' очков') else: questions_count += 1 if answers[1].isChecked() or answers[2].isChecked() or answers[3].isChecked(): # неправильный ответ! show_correct('Неверно! У вас ' + str(points) + ' очков') def next_question(): ''' задает следующий вопрос из списка ''' # этой функции нужна переменная, в которой будет указываться номер текущего вопроса # эту переменную можно сделать глобальной, либо же сделать свойством "глобального объекта" (app или window) # мы заведем (ниже) свойство window.cur_question. if len(questions_list) == 0: show_test_result() else: window.cur_question = randint(0, len(questions_list)-1) q = questions_list[window.cur_question] # взяли вопрос ask(q) # спросили def show_test_result(): global points, questions_count RadioGroupBox.hide() AnsGroupBox.hide() lb_Result_Test.setText('Ваш результат: ' + str(points) + ' из ' + str(questions_count)) ResultGroupBox.show() def click_OK(): ''' определяет, надо ли показывать другой вопрос либо проверить ответ на этот ''' if btn_OK.text() == 'Ответить': check_answer() # проверка ответа else: next_question() # следующий вопрос window = QWidget() window.setLayout(layout_card) window.setWindowTitle('Memo Card') # текущий вопрос из списка сделаем свойством объекта "окно", так мы сможем спокойно менять его из функции: window.cur_question = -1 # по-хорошему такие переменные должны быть свойствами, # только надо писать класс, экземпляры которого получат такие свойства, # но python позволяет создать свойство у отдельно взятого экземпляра btn_OK.clicked.connect(click_OK) # по нажатии на кнопку выбираем, что конкретно происходит # все настроено, осталось задать вопрос и показать окно: next_question() window.resize(400, 300) window.show() app.exec()
[ "noreply@github.com" ]
strvlad96.noreply@github.com
c8b1a7655087184602bc4d1404cd9d2c9991c5c9
711b6812486d98eb4d21dacaa4381810ae82506d
/main.py
cce1c189268a12b9fd6474c59ee738a79f7ddd06
[]
no_license
nico9695/Demo
b50308b69e5f01477624080d91e09ccaf816cf50
cca9f751852101d14517d8b6154d57a012b0dfcf
refs/heads/main
2023-03-23T08:37:02.317425
2021-03-05T13:38:40
2021-03-05T13:38:40
344,810,484
0
0
null
null
null
null
UTF-8
Python
false
false
630
py
print('Processing the order for {target} shares') if delta > 0: buy_quantity = min(abs(self.position), buy_quantity) print('Buying {buy_quantity} shares') self.current_order = self.api.submit_order(self.symbol, buy, _quantity, 'buy', 'limit', 'day', self.last_price) elif delta < 0: sell_quantity = min(labs(self.position), sell_quantity) print(f'Selling {sell_quantity} shares') self.current_order = self.api.submit_order(self.symbol, sell_quantity, 'sell', 'limit', 'day', self.last_price) if _name_ == '_main_': t = Martingale() t.submit_order(3)
[ "noreply@github.com" ]
nico9695.noreply@github.com
05d2925545dae1edc329935ae160993cd856cb5c
d6c117812a618ff34055488337aaffea8cf81ca1
/git/github/GitignoreTemplate.py
06df576cfdd5fd0dd58ae1d7e25a837559c462c0
[]
no_license
c0ns0le/Pythonista
44829969f28783b040dd90b46d08c36cc7a1f590
4caba2d48508eafa2477370923e96132947d7b24
refs/heads/master
2023-01-21T19:44:28.968799
2016-04-01T22:34:04
2016-04-01T22:34:04
55,368,932
3
0
null
2023-01-22T01:26:07
2016-04-03T21:04:40
Python
UTF-8
Python
false
false
1,946
py
# -*- coding: utf-8 -*- # Copyright 2012 Vincent Jacques vincent@vincent-jacques.net # Copyright 2013 Vincent Jacques vincent@vincent-jacques.net # This file is part of PyGithub. http://jacquev6.github.com/PyGithub/ # PyGithub is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License # as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. # PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License along with PyGithub. If not, see <http://www.gnu.org/licenses/>. import github.GithubObject class GitignoreTemplate(github.GithubObject.NonCompletableGithubObject): """ This class represents GitignoreTemplates as returned for example by http://developer.github.com/v3/todo """ @property def source(self): """ :type: string """ return self._NoneIfNotSet(self._source) @property def name(self): """ :type: string """ return self._NoneIfNotSet(self._name) def _initAttributes(self): self._source = github.GithubObject.NotSet self._name = github.GithubObject.NotSet def _useAttributes(self, attributes): if "source" in attributes: # pragma no branch assert attributes["source"] is None or isinstance(attributes["source"], (str, unicode)), attributes["source"] self._source = attributes["source"] if "name" in attributes: # pragma no branch assert attributes["name"] is None or isinstance(attributes["name"], (str, unicode)), attributes["name"] self._name = attributes["name"]
[ "itdamdouni@gmail.com" ]
itdamdouni@gmail.com
70b059dbafbdc6db2f797168a4997c28029b7c38
0efd4df5872e49dcd98345593760d08505a84b1a
/flasksql/main.py
6313004adf07ea54beb2001614af0f91010d59a5
[ "MIT" ]
permissive
Kwargers/AiLearning
6077cbb9e8a03f4a008c88698ebeae3330975fc3
dbbbcdbbc528109458300288cb5839054f9dec34
refs/heads/main
2022-12-20T08:06:24.356934
2020-10-16T00:57:35
2020-10-16T00:57:35
304,327,870
0
3
MIT
2020-10-16T00:57:36
2020-10-15T13:02:27
Jupyter Notebook
UTF-8
Python
false
false
3,321
py
from flask import Flask, render_template, request import sqlite3 database = 'music.db' app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/createArtist", methods=["POST"]) def createArtist(): #artistID = request.form.get("artistID") artistName = request.form.get("artistName") conn = sqlite3.connect(database) cursor = conn.cursor() cursor.execute('CREATE TABLE IF NOT EXISTS artist(artistID INTEGER PRIMARY KEY AUTOINCREMENT, artistName TEXT);') #cursor.execute('CREATE TABLE artist(ArtistID INTEGER, ArtistName TEXT, PRIMARY KEY(ArtistID) );') cursor.execute('INSERT INTO artist ( artistName) VALUES ( "{artistName}");'.format(artistName=artistName)) conn.commit() conn.close() return render_template('index.html') @app.route("/track") def track(): return render_template('track.html') @app.route("/createTrack", methods=["POST"]) def createTrack(): #trackID = request.form.get("trackID") trackName = request.form.get("trackName") artistName = request.form.get("artistName") conn = sqlite3.connect(database) cursor = conn.cursor() artistIDList = [] cursor.execute('CREATE TABLE IF NOT EXISTS track(trackID INTEGER PRIMARY KEY AUTOINCREMENT, trackName TEXT, trackArtistID INTEGER, FOREIGN KEY(trackArtistID) REFERENCES artist(artistID));') artistID = cursor.execute('SELECT artistID FROM artist WHERE artistName="{artistName}"'.format(artistName=artistName)) print(artistID) for artist in artistID: print(artist) for ID in artist: artistID = [ID] cursor.execute('INSERT INTO track (trackName, trackArtistID) VALUES ("{trackName}", {trackArtistID});'.format(trackName=trackName, trackArtistID=artistID[0])) conn.commit() conn.close() return render_template('track.html')ts @app.route("/trackdb", methods=["GET", "POST"]) def trackdb(): trackArray = [] conn = sqlite3.connect(database) cursor = conn.cursor() tracks = cursor.execute('SELECT * FROM track;') for track in tracks: trackArray.append(track) conn.close() return render_template('trackdb.html', trackArray=trackArray) @app.route("/dbartist") def dbartist(): artistArray = [] conn = sqlite3.connect(database) cursor = conn.cursor() artists = cursor.execute('SELECT * FROM artist') for artist in artists: artistArray.append(artist) conn.close() return render_template('artistdb.html', artistArray=artistArray) @app.route("/db") def db(): return render_template('db.html') @app.route("/queryartist", methods=["POST", "GET"]) def queryartist(): artistName = request.form.get("artistName") artistSongList = [] conn = sqlite3.connect(database) cursor = conn.cursor() artistID = cursor.execute('SELECT artistID FROM artist WHERE artistName="{artistName}"'.format(artistName=artistName)) for artist in artistID: for ID in artist: artistID = [ID] artistSong = cursor.execute('SELECT * FROM track WHERE trackArtistID={artistID};'.format(artistID=artistID[0])) for info in artistSong: artistSongList.append(info) return render_template('db.html', infoList=artistSongList) conn.close() app.run(host='0.0.0.0', port=5000)
[ "noreply@github.com" ]
Kwargers.noreply@github.com