blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
288
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
684 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
147 values
src_encoding
stringclasses
25 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
128
12.7k
extension
stringclasses
142 values
content
stringlengths
128
8.19k
authors
listlengths
1
1
author_id
stringlengths
1
132
141f79b6886fd8aaea730704ff814f1295b70634
f3b233e5053e28fa95c549017bd75a30456eb50c
/p38a_input/L3FN/3FN-2EE_wat_20Abox/set_1.py
804c27b410c13656dad3d34b5d311abf77b6b6be
[]
no_license
AnguseZhang/Input_TI
ddf2ed40ff1c0aa24eea3275b83d4d405b50b820
50ada0833890be9e261c967d00948f998313cb60
refs/heads/master
2021-05-25T15:02:38.858785
2020-02-18T16:57:04
2020-02-18T16:57:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
741
py
import os dir = '/mnt/scratch/songlin3/run/p38a/L3FN/wat_20Abox/ti_one-step/3FN_2EE/' filesdir = dir + 'files/' temp_prodin = filesdir + 'temp_prod_1.in' temp_pbs = filesdir + 'temp_1.pbs' lambd = [ 0.00922, 0.04794, 0.11505, 0.20634, 0.31608, 0.43738, 0.56262, 0.68392, 0.79366, 0.88495, 0.95206, 0.99078] for j in lambd: os.chdir("%6.5f" %(j)) workdir = dir + "%6.5f" %(j) + '/' #prodin prodin = workdir + "%6.5f_prod_1.in" %(j) os.system("cp %s %s" %(temp_prodin, prodin)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, prodin)) #PBS pbs = workdir + "%6.5f_1.pbs" %(j) os.system("cp %s %s" %(temp_pbs, pbs)) os.system("sed -i 's/XXX/%6.5f/g' %s" %(j, pbs)) #submit pbs #os.system("qsub %s" %(pbs)) os.chdir(dir)
[ "songlin3@msu.edu" ]
songlin3@msu.edu
8e6c677a16dc1d427a1edd44756097980b1e30b8
6c628b7b72eef4dbcc982803eb18c20a01d50a25
/brownie/network/middlewares/geth_poa.py
15f367f095955a0b58e9d250619483ab01db7da8
[ "MIT" ]
permissive
eth-brownie/brownie
174c5cb549427f4814fa5a1dc9ede225acc983f8
bc7b511583060fdaff1d4b5269aedcc1cb710bc6
refs/heads/master
2023-09-04T15:53:39.804726
2023-06-12T07:27:29
2023-06-12T07:27:29
155,913,585
2,408
518
MIT
2023-09-06T14:20:17
2018-11-02T19:39:26
Python
UTF-8
Python
false
false
706
py
from typing import Callable, Dict, List, Optional from web3 import Web3 from web3.exceptions import ExtraDataLengthError from web3.middleware import geth_poa_middleware from brownie.network.middlewares import BrownieMiddlewareABC class GethPOAMiddleware(BrownieMiddlewareABC): @classmethod def get_layer(cls, w3: Web3, network_type: str) -> Optional[int]: try: w3.eth.get_block("latest") return None except ExtraDataLengthError: return -1 def process_request(self, make_request: Callable, method: str, params: List) -> Dict: middleware_fn = geth_poa_middleware(make_request, self.w3) return middleware_fn(method, params)
[ "ben@hauser.id" ]
ben@hauser.id
f8f918c669b2af2f1c30e88d810d20640137ec04
081ff1c741a5db5d9e95bba09cb14acf8fa7d454
/DeleteDoublyLinkedList.py
af359bc72796adbfc3c05f70f3dbebca6e219e2c
[]
no_license
aljaserm/LinkedList
e95f72be52728ffd0451d8c308c3c659efeffa6d
6e3f2efe1dc9afe5e9f3a19c2639b29f7cbf94ca
refs/heads/master
2020-05-05T00:44:04.948919
2019-04-09T00:00:53
2019-04-09T00:00:53
179,583,916
0
0
null
null
null
null
UTF-8
Python
false
false
929
py
# next means next address class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class LinkedList: def __init__(self): self.head = None def AddNode(self, vals): a = Node(vals) a.next = self.head if self.head is not None: self.head.prev = a self.head = a def removeNode(self, node): if node.prev is None: self.x = node.next else: node.prev.next = node.next if node.next is None: self.y = node.prev else: node.next.prev = node.prev def PrintIt(self, node): while node is not None: print(node.data) last = node node = node.next x = LinkedList() x.AddNode("MJ") x.AddNode("OO") x.AddNode("OJ") x.AddNode("SJ") x.AddNode("SM") x.removeNode(x.head.next) x.PrintIt(x.head)
[ "aljaserm7@gmail.com" ]
aljaserm7@gmail.com
10dd2968efb88ce5f6e840638d5808e5e16da86e
419873dd3b7412f704b1a7907b64a60b44cedf39
/python/1006. 笨阶乘.py
ed9a117bd779587e9f848f772232411ff520a0df
[]
no_license
Weless/leetcode
0585c5bfa260713f44dabc51fa58ebf8a10e7814
0566622daa5849f7deb0cfdc6de2282fb3127f4c
refs/heads/master
2021-11-13T07:59:20.299920
2021-10-25T02:09:53
2021-10-25T02:09:53
203,720,668
0
0
null
null
null
null
UTF-8
Python
false
false
456
py
import math class Solution: def clumsy(self, N: int) -> int: stack = [N] N-=1 i = 0 while N > 0: if i % 4 == 0: stack[-1]*=N elif i % 4 == 1: stack[-1] //= N elif i % 4 == 2: stack.append(N) else: stack.append(-N) N-=1 i+=1 return sum(stack) s = Solution() print(s.clumsy(56))
[ "409766394@qq.com" ]
409766394@qq.com
3734c7f76d851b2ac29fa0b13f249f92ebfd9e91
551b75f52d28c0b5c8944d808a361470e2602654
/huaweicloud-sdk-iotda/huaweicloudsdkiotda/v5/model/show_applications_response.py
22469cad3949e1835092b27290ea40acef8c0afd
[ "Apache-2.0" ]
permissive
wuchen-huawei/huaweicloud-sdk-python-v3
9d6597ce8ab666a9a297b3d936aeb85c55cf5877
3683d703f4320edb2b8516f36f16d485cff08fc2
refs/heads/master
2023-05-08T21:32:31.920300
2021-05-26T08:54:18
2021-05-26T08:54:18
370,898,764
0
0
NOASSERTION
2021-05-26T03:50:07
2021-05-26T03:50:07
null
UTF-8
Python
false
false
3,080
py
# coding: utf-8 import pprint import re import six from huaweicloudsdkcore.sdk_response import SdkResponse class ShowApplicationsResponse(SdkResponse): """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { 'applications': 'list[ApplicationDTO]' } attribute_map = { 'applications': 'applications' } def __init__(self, applications=None): """ShowApplicationsResponse - a model defined in huaweicloud sdk""" super(ShowApplicationsResponse, self).__init__() self._applications = None self.discriminator = None if applications is not None: self.applications = applications @property def applications(self): """Gets the applications of this ShowApplicationsResponse. 资源空间信息列表。 :return: The applications of this ShowApplicationsResponse. :rtype: list[ApplicationDTO] """ return self._applications @applications.setter def applications(self, applications): """Sets the applications of this ShowApplicationsResponse. 资源空间信息列表。 :param applications: The applications of this ShowApplicationsResponse. :type: list[ApplicationDTO] """ self._applications = applications def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: if attr in self.sensitive_list: result[attr] = "****" 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, ShowApplicationsResponse): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
[ "hwcloudsdk@huawei.com" ]
hwcloudsdk@huawei.com
f4d16d24449c59d2bf9bcdad4731f0406b0a67f0
e0c6f652a4fb4633845a9d0c565999b18dfe120f
/smartmeter/asgi.py
350ac118090a953173234d3fb79a3cea2e82843b
[]
no_license
TanmayAmbadkar/smart-meter
1a985bb90707adbe5acb02f41e6ea6b24d72c77b
510676fc7f94927f9693c2178b0df55e4d81e66f
refs/heads/master
2023-02-10T07:44:08.750685
2020-12-31T09:16:32
2020-12-31T09:16:32
325,762,286
3
1
null
null
null
null
UTF-8
Python
false
false
397
py
""" ASGI config for smartmeter 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', 'smartmeter.settings') application = get_asgi_application()
[ "tanmay.ambadkar@gmail.com" ]
tanmay.ambadkar@gmail.com
f62a88f6f2b169bbf59ec58269be8455d930e004
209a7a4023a9a79693ec1f6e8045646496d1ea71
/COMP0016_2020_21_Team12-datasetsExperimentsAna/pwa/FADapp/pythonScripts/venv/Lib/site-packages/pandas/tests/indexes/test_index_new.py
ca3ba52c2ff20aab0a1debc676d3de3e7a079371
[ "MIT" ]
permissive
anzhao920/MicrosoftProject15_Invictus
5e2347015411bbffbdf0ceb059df854661fb240c
15f44eebb09561acbbe7b6730dfadf141e4c166d
refs/heads/main
2023-04-16T13:24:39.332492
2021-04-27T00:47:13
2021-04-27T00:47:13
361,913,170
0
0
MIT
2021-04-26T22:41:56
2021-04-26T22:41:55
null
UTF-8
Python
false
false
4,628
py
""" Tests for the Index constructor conducting inference. """ import numpy as np import pytest from pandas.core.dtypes.common import is_unsigned_integer_dtype from pandas import ( NA, CategoricalIndex, DatetimeIndex, Index, Int64Index, MultiIndex, NaT, PeriodIndex, Series, TimedeltaIndex, Timestamp, UInt64Index, period_range, ) import pandas._testing as tm class TestIndexConstructorInference: @pytest.mark.parametrize("na_value", [None, np.nan]) @pytest.mark.parametrize("vtype", [list, tuple, iter]) def test_construction_list_tuples_nan(self, na_value, vtype): # GH#18505 : valid tuples containing NaN values = [(1, "two"), (3.0, na_value)] result = Index(vtype(values)) expected = MultiIndex.from_tuples(values) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "dtype", [int, "int64", "int32", "int16", "int8", "uint64", "uint32", "uint16", "uint8"], ) def test_constructor_int_dtype_float(self, dtype): # GH#18400 if is_unsigned_integer_dtype(dtype): index_type = UInt64Index else: index_type = Int64Index expected = index_type([0, 1, 2, 3]) result = Index([0.0, 1.0, 2.0, 3.0], dtype=dtype) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cast_index", [True, False]) @pytest.mark.parametrize( "vals", [[True, False, True], np.array([True, False, True], dtype=bool)] ) def test_constructor_dtypes_to_object(self, cast_index, vals): if cast_index: index = Index(vals, dtype=bool) else: index = Index(vals) assert type(index) is Index assert index.dtype == object def test_constructor_categorical_to_object(self): # GH#32167 Categorical data and dtype=object should return object-dtype ci = CategoricalIndex(range(5)) result = Index(ci, dtype=object) assert not isinstance(result, CategoricalIndex) def test_constructor_infer_periodindex(self): xp = period_range("2012-1-1", freq="M", periods=3) rs = Index(xp) tm.assert_index_equal(rs, xp) assert isinstance(rs, PeriodIndex) @pytest.mark.parametrize("pos", [0, 1]) @pytest.mark.parametrize( "klass,dtype,ctor", [ (DatetimeIndex, "datetime64[ns]", np.datetime64("nat")), (TimedeltaIndex, "timedelta64[ns]", np.timedelta64("nat")), ], ) def test_constructor_infer_nat_dt_like( self, pos, klass, dtype, ctor, nulls_fixture, request ): expected = klass([NaT, NaT]) assert expected.dtype == dtype data = [ctor] data.insert(pos, nulls_fixture) warn = None if nulls_fixture is NA: expected = Index([NA, NaT]) mark = pytest.mark.xfail(reason="Broken with np.NaT ctor; see GH 31884") request.node.add_marker(mark) # GH#35942 numpy will emit a DeprecationWarning within the # assert_index_equal calls. Since we can't do anything # about it until GH#31884 is fixed, we suppress that warning. warn = DeprecationWarning result = Index(data) with tm.assert_produces_warning(warn): tm.assert_index_equal(result, expected) result = Index(np.array(data, dtype=object)) with tm.assert_produces_warning(warn): tm.assert_index_equal(result, expected) @pytest.mark.parametrize("swap_objs", [True, False]) def test_constructor_mixed_nat_objs_infers_object(self, swap_objs): # mixed np.datetime64/timedelta64 nat results in object data = [np.datetime64("nat"), np.timedelta64("nat")] if swap_objs: data = data[::-1] expected = Index(data, dtype=object) tm.assert_index_equal(Index(data), expected) tm.assert_index_equal(Index(np.array(data, dtype=object)), expected) class TestIndexConstructorUnwrapping: # Test passing different arraylike values to pd.Index @pytest.mark.parametrize("klass", [Index, DatetimeIndex]) def test_constructor_from_series_dt64(self, klass): stamps = [Timestamp("20110101"), Timestamp("20120101"), Timestamp("20130101")] expected = DatetimeIndex(stamps) ser = Series(stamps) result = klass(ser) tm.assert_index_equal(result, expected)
[ "ana.kapros@yahoo.ro" ]
ana.kapros@yahoo.ro
114bae97f9225e13e887d737906cde8d2618b154
45c170fb0673deece06f3055979ece25c3210380
/toontown/minigame/VineSpider.py
c7130c813f252a1921d75071928067cf07ea8c75
[]
no_license
MTTPAM/PublicRelease
5a479f5f696cfe9f2d9dcd96f378b5ce160ec93f
825f562d5021c65d40115d64523bb850feff6a98
refs/heads/master
2021-07-24T09:48:32.607518
2018-11-13T03:17:53
2018-11-13T03:17:53
119,129,731
2
6
null
2018-11-07T22:10:10
2018-01-27T03:43:39
Python
UTF-8
Python
false
false
2,673
py
#Embedded file name: toontown.minigame.VineSpider from direct.showbase.DirectObject import DirectObject from toontown.toonbase.ToontownGlobals import * from direct.directnotify import DirectNotifyGlobal from pandac.PandaModules import * from toontown.minigame import VineGameGlobals class VineSpider(NodePath, DirectObject): RADIUS = 1.7 def __init__(self): NodePath.__init__(self, 'VineSpider') DirectObject.__init__(self) pos = Point3(0, 0, 0) serialNum = 0 gameId = 0 self.serialNum = serialNum gameAssets = loader.loadModel('phase_4/models/minigames/vine_game') spider2 = gameAssets.find('**/spider_3') spider1 = gameAssets.find('**/spider_2') seqNode = SequenceNode('spider') seqNode.addChild(spider1.node()) seqNode.addChild(spider2.node()) seqNode.setFrameRate(2) seqNode.loop(False) self.spiderModel = self.attachNewNode(seqNode) self.spiderModel.reparentTo(self) gameAssets.removeNode() self.spiderModelIcon = self.attachNewNode('spiderIcon') self.spiderModel.copyTo(self.spiderModelIcon) regularCamMask = BitMask32.bit(0) self.spiderModelIcon.hide(regularCamMask) self.spiderModelIcon.show(VineGameGlobals.RadarCameraBitmask) self.spiderModel.setScale(0.2) self.spiderModelIcon.setScale(0.75) self.setPos(-100, 0, 0) center = Point3(0, 0, 0) self.sphereName = 'spiderSphere-%s-%s' % (gameId, self.serialNum) self.collSphere = CollisionSphere(center[0], center[1], center[2], self.RADIUS) self.collSphere.setTangible(0) self.collNode = CollisionNode(self.sphereName) self.collNode.setIntoCollideMask(VineGameGlobals.SpiderBitmask) self.collNode.addSolid(self.collSphere) self.collNodePath = self.attachNewNode(self.collNode) self.collNodePath.hide() self.accept('enter' + self.sphereName, self.__handleEnterSphere) self.reparentTo(render) def destroy(self): self.ignoreAll() self.spiderModel.removeNode() del self.spiderModel del self.collSphere self.collNodePath.removeNode() del self.collNodePath del self.collNode self.removeNode() def __handleEnterSphere(self, collEntry): print 'VineSpider.__handleEnterSphere' print collEntry self.ignoreAll() self.notify.debug('treasuerGrabbed') messenger.send('VineSpiderGrabbed', [self.serialNum]) def showGrab(self): self.reparentTo(hidden) self.collNode.setIntoCollideMask(BitMask32(0))
[ "linktlh@gmail.com" ]
linktlh@gmail.com
547b62d0a902073341c311d8d736935a5b53c4c8
09e57dd1374713f06b70d7b37a580130d9bbab0d
/data/p3BR/R1/benchmark/startPyquil15.py
d2fa0f153cc58d9453ef0250a8d7f1ad386b3117
[ "BSD-3-Clause" ]
permissive
UCLA-SEAL/QDiff
ad53650034897abb5941e74539e3aee8edb600ab
d968cbc47fe926b7f88b4adf10490f1edd6f8819
refs/heads/main
2023-08-05T04:52:24.961998
2021-09-19T02:56:16
2021-09-19T02:56:16
405,159,939
2
0
null
null
null
null
UTF-8
Python
false
false
1,024
py
# qubit number=2 # total number=5 import pyquil from pyquil.api import local_forest_runtime, QVMConnection from pyquil import Program, get_qc from pyquil.gates import * import numpy as np conn = QVMConnection() def make_circuit()-> Program: prog = Program() # circuit begin prog += H(0) # number=1 prog += RX(-0.09738937226128368,2) # number=2 prog += Y(2) # number=3 prog += Y(2) # number=4 # circuit end return prog def summrise_results(bitstrings) -> dict: d = {} for l in bitstrings: if d.get(l) is None: d[l] = 1 else: d[l] = d[l] + 1 return d if __name__ == '__main__': prog = make_circuit() qvm = get_qc('1q-qvm') results = qvm.run_and_measure(prog,1024) bitstrings = np.vstack([results[i] for i in qvm.qubits()]).T bitstrings = [''.join(map(str, l)) for l in bitstrings] writefile = open("../data/startPyquil15.csv","w") print(summrise_results(bitstrings),file=writefile) writefile.close()
[ "wangjiyuan123@yeah.net" ]
wangjiyuan123@yeah.net
df83ced68032f588982e49ffedc41c6cf3ae582f
e085147a267a44e49bade582178de80208be5a61
/templates.py
0e83f41fc5f0b9730848b949ede332c10b5721c1
[]
no_license
math2001/BetterSnippetManager
5302c0c04bd4d294835a2664c5410426f0702c92
bc50d47961ff9806be3c9ca76174d50d56e7f46f
refs/heads/master
2021-05-02T00:48:17.462763
2020-12-14T23:31:14
2020-12-14T23:31:31
78,321,810
15
3
null
2020-01-16T02:39:43
2017-01-08T04:43:54
Python
UTF-8
Python
false
false
363
py
# -*- encoding: utf-8 -*- class templates: pass templates.xml = """\ <snippet> \t<content><![CDATA[ {content} ]]></content> \t<tabTrigger>{trigger}</tabTrigger> \t<scope>{scopes}</scope> \t<description>{description}</description> </snippet> """ templates.sane = """\ --- tabTrigger: {trigger} scope: {scopes} description: {description} --- {content} """
[ "australie.p@gmail.com" ]
australie.p@gmail.com
7533dcb11fc243fd6d862bf0ea136ed5a667820f
2545624bbbf982aa6243acf8b0cb9f7eaef155d6
/2016/round_1a/soldiers.py
a774b3d07780d9e3f9667c4f4863ec4564ce946c
[]
no_license
dprgarner/codejam
9f420003fb48c2155bd54942803781a095e984d1
d7e1134fe3fe850b419aa675260c4ced630731d0
refs/heads/master
2021-07-12T05:36:08.465603
2021-07-03T12:37:46
2021-07-03T12:37:46
87,791,734
1
0
null
null
null
null
UTF-8
Python
false
false
877
py
from codejam import CodeJamParser class Soldiers(CodeJamParser): """ Q2, Round 1A, 2016 (Practice) https://code.google.com/codejam/contest/4304486/dashboard#s=p1 """ def get_cases(self): cases = int(next(self.source)) for i in range(1, cases + 1): rows = [] n = int(next(self.source)) for j in range(2 * n - 1): heights_str = next(self.source) rows.append([int(x) for x in heights_str.split(' ')]) yield rows, def handle_case(self, rows): counts = {} for row in rows: for height in row: counts[height] = counts.get(height, 0) + 1 missing_heights = sorted([k for k, v in counts.items() if v % 2 == 1]) return ' '.join([str(h) for h in missing_heights]) if __name__ == '__main__': Soldiers()
[ "dprgarner@gmail.com" ]
dprgarner@gmail.com
2d882c80148d94bde9b688793fa3bd0abb9f6b9e
f4326f80c69ec975985a4b70f9fae06937733643
/eigencharacter/__init__.py
ed6ec39aff1ff9ec75eb451a61c31529bb5bbb82
[]
no_license
seantyh/eigencharacter
d488918d7e782f52292ad5eb5822c4ed03df7712
db5f79871b4235b9e0e49cd36bfa31f37f2dad4b
refs/heads/master
2020-08-30T01:08:51.189031
2019-11-26T17:04:59
2019-11-26T17:04:59
218,222,286
0
0
null
null
null
null
UTF-8
Python
false
false
189
py
from .text2bitmap import * from .utils import * from .char_dataset import * from .vae_dataset import * from .svd_dataset import * from .svd_ops import * from .ec_space import CharacterSpace
[ "seantyh@gmail.com" ]
seantyh@gmail.com
f6f669ff3ba51a61d52e8f6e2bdf307cd6757b2a
1c568fed8094a35c114613d118179937179761c7
/abi/pool4.py
a9b54ed3b79ac47f86161683297add6163579a8d
[]
no_license
yfii/yfii_stats
953b699cb5dc4d5886a2a083f57066d33f99d28a
6e11c6ccacb7e9bb8a1b3f73678a8086725c406d
refs/heads/master
2022-12-15T17:24:33.684421
2020-09-25T05:38:27
2020-09-25T05:38:27
298,928,410
0
2
null
2020-09-27T01:20:53
2020-09-27T01:20:52
null
UTF-8
Python
false
false
1,985
py
from web3 import Web3, HTTPProvider import json # from abi_json.ERC20 import erc20Abi w3url = "https://mainnet.infura.io/v3/998f64f3627548bbaf2630599c1eefca" w3 = Web3(HTTPProvider(w3url)) WETH = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" YFII = "0xa1d0E215a23d7030842FC67cE582a6aFa3CCaB83" DAI = "0x6B175474E89094C44Da98b954EedeAC495271d0F" iUSDT = "0x72Cf258c852Dc485a853370171d46B9D29fD3184" POOL4 = "0x3d367C9529f260B0661e1C1E91167C9319ee96cA" yfii2dai = [YFII, WETH, DAI] with open("./abi_json/erc20.json") as f: erc20ABI = json.loads(f.read()) with open("./abi_json/uniswapRouterv2.json") as f: uniswapABI = json.loads(f.read()) with open("./abi_json/pool4.json") as f: pool4ABI = json.loads(f.read()) uniswap_instance = w3.eth.contract( abi=uniswapABI, address=w3.toChecksumAddress("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"), ) pool4_instance = w3.eth.contract(abi=pool4ABI, address=POOL4) def getyfiiprice(): price = uniswap_instance.functions.getAmountsOut( w3.toWei(1, "ether"), yfii2dai ).call()[-1] return float(w3.fromWei(price, "ether")) def _weekly_reward(): return pool4_instance.functions.rewardRate().call() / 1e18 * 60480 def _totalStakedAmount(): token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) return token_instance.functions.balanceOf(POOL4).call() / 1e18 def getDATA(): weekly_reward = ( pool4_instance.functions.rewardRate().call() / 1e6 * 7 * 24 * 60 * 60 ) token_instance = w3.eth.contract(abi=erc20ABI, address=w3.toChecksumAddress(YFII)) totalStakedAmount = token_instance.functions.balanceOf(POOL4).call() / 1e18 YFIIPrice = getyfiiprice() TVL = totalStakedAmount * YFIIPrice YFIWeeklyROI = (weekly_reward / TVL) * 100 / 1.01 apy = YFIWeeklyROI * 52 return {"apy": apy, "totalStakedAmount": totalStakedAmount, "TVL": TVL, 'YFIWeeklyROI': YFIWeeklyROI} if __name__ == "__main__": print(getDATA())
[ "524290558@qq.com" ]
524290558@qq.com
f41e112d80a319f33b145521a0d5836320f51f99
0e78b2df0fb93afc62684dece8ac05b700570248
/BOJ/2447.py
866fc5b8e905935b1c23e71f4daff60a64e625fa
[]
no_license
ajy720/Algorithm
f1e2301327db09667ba011bc317c8f380707c25c
b141538802e9056f154ab91c816ad29500505f34
refs/heads/master
2022-05-06T21:37:05.780170
2022-04-23T09:25:52
2022-04-23T09:25:52
200,335,390
0
1
null
null
null
null
UTF-8
Python
false
false
515
py
def solve(n : int, x : int , y : int): unit = n//3 for i in range(x+unit, x+unit*2): matrix[i][y+unit:y+unit*2]=" " * len(matrix[i][y+unit:y+unit*2]) if unit == 1: return for i in range(x, x+(unit*3), unit): for j in range(y, y+(unit*3), unit): if i == x + unit and j == y + unit: continue solve(unit, i, j) n = int(input()) matrix = [['*'] * n for i in range(n)] solve(n, 0, 0) for i in range(n): print(''.join(matrix[i]))
[ "ajy720@gmail.com" ]
ajy720@gmail.com
22bee87892c25ad3c214b586e4be43ad9e09e758
6f224b734744e38062a100c42d737b433292fb47
/lldb/test/API/sanity/TestModuleCacheSanity.py
1d3a6b3158898c7f165160f8604a51008a4043a0
[ "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
smeenai/llvm-project
1af036024dcc175c29c9bd2901358ad9b0e6610e
764287f1ad69469cc264bb094e8fcdcfdd0fcdfb
refs/heads/main
2023-09-01T04:26:38.516584
2023-08-29T21:11:41
2023-08-31T22:16:12
216,062,316
0
0
Apache-2.0
2019-10-18T16:12:03
2019-10-18T16:12:03
null
UTF-8
Python
false
false
499
py
""" This is a sanity check that verifies that the module cache path is set correctly and points inside the default test build directory. """ import lldb import lldbsuite.test.lldbutil as lldbutil from lldbsuite.test.lldbtest import * class ModuleCacheSanityTestCase(TestBase): NO_DEBUG_INFO_TESTCASE = True def test(self): self.expect( "settings show symbols.clang-modules-cache-path", substrs=["lldb-test-build.noindex", "module-cache-lldb"], )
[ "jonas@devlieghere.com" ]
jonas@devlieghere.com
9fea3da5ed6f751ba82e561e3fe8754d12b0b6f6
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/otherforms/_entertains.py
25274e502bb6a369a62bb3431f4a069083692312
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
234
py
#calss header class _ENTERTAINS(): def __init__(self,): self.name = "ENTERTAINS" self.definitions = entertain self.parents = [] self.childen = [] self.properties = [] self.jsondata = {} self.basic = ['entertain']
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
9a4d57257defb51885222276dd996d666f5ba530
a94e8b83bb2a4ccc1fffbd28dd18f8783872daab
/COCI/COCI08 Perket.py
d066335f7eca1c5f9286c68c67bae86bae1ce439
[]
no_license
MowMowchow/Competitive-Programming
d679c1fe2d7d52940dc83a07dc8048922078704e
0ec81190f6322e103c2ae0ad8c3935bd4cdfff46
refs/heads/master
2022-03-03T03:01:03.383337
2022-02-17T07:27:45
2022-02-17T07:27:45
184,678,148
0
0
null
null
null
null
UTF-8
Python
false
false
765
py
import sys n = int(sys.stdin.readline()) ingredients = [[int(x) for x in sys.stdin.readline().split()] for x in range(n)] final = float("inf") def choose(curr, sourprod, bittersum, taken): result = abs(sourprod-bittersum) if curr == -1: return choose(curr+1, 1, 0, taken) elif curr < n: use = choose(curr+1, sourprod*ingredients[curr][0], bittersum+ingredients[curr][1], True) skip = choose(curr+1, sourprod, bittersum, taken) return min(use, skip) elif curr == n and not taken: return float("inf") return result # for i in range(n): # final = min(final, choose(i, ingredients[i][0], ingredients[i][1], abs(ingredients[i][0]-ingredients[i][1]))) final = choose(-1, 1, 0, False) print(final)
[ "darkstar.hou2@gmail.com" ]
darkstar.hou2@gmail.com
ac8367e73fedbf6e6451183fa44632b0eb62e8f9
077d6a98c19951ccec87ca03ddd0bb468aa98c14
/linkedlist/remove_nth_node_from_end_of_list.py
241e44fdede82176533ccb70d2a05966821f834b
[]
no_license
rayt579/leetcode
c099a5147f161d44179a5a2bf9bd33ab3a661f79
9d0ff0f8705451947a6605ab5ef92bb3e27a7147
refs/heads/master
2020-03-19T04:45:07.829074
2019-04-07T22:26:02
2019-04-07T22:26:02
135,862,033
0
0
null
null
null
null
UTF-8
Python
false
false
1,162
py
''' https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/ ''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if head is None: return None sentinel = ListNode('sentinel') sentinel.next = head curr, fwd = sentinel, sentinel for i in range(n): fwd = fwd.next if fwd is None: return head while fwd.next is not None: fwd = fwd.next curr = curr.next next_node = curr.next curr.next = next_node.next next_node.next = None return sentinel.next sol = Solution() linkedlist = ListNode(1) linkedlist.next = ListNode(2) linkedlist.next.next = ListNode(3) linkedlist.next.next.next = ListNode(4) linkedlist.next.next.next.next = ListNode(5) newlist = sol.removeNthFromEnd(linkedlist, 2) curr = newlist while curr: print(curr.val) curr = curr.next
[ "rayt579@yahoo.com" ]
rayt579@yahoo.com
5b17bbf9f8e503ace725e9a65ea3788e8b5c6270
70280955a5382d73e58395eba78c119a400f4ce7
/asakatsu/0701/3.py
1127fd535f870c1dd74510bb4347caeff0a319a1
[]
no_license
cohock13/atcoder
a7d0e26a10a4e58690347a2e36839c2f503a79ba
d268aa68fc96203eab94d021bd158cf84bdb00bc
refs/heads/master
2021-01-03T00:41:31.055553
2020-10-27T12:28:06
2020-10-27T12:28:06
239,839,477
0
0
null
null
null
null
UTF-8
Python
false
false
148
py
N = int(input()) a = list(map(int,input().split())) b = [(j,i+1) for i,j in enumerate(a)] b.sort(reverse=True) for _,n in b: print(n)
[ "callout2690@gmail.com" ]
callout2690@gmail.com
f5278cfe7ba91b87557ea7fc14b88d5577d0db7f
55c8557a675d9228a3fb96bf8736ec613351ebb3
/apps/crm/migrations/0006_pylead_user_id.py
e4afff43d66cbbec428e90886b3b89e81c594199
[ "MIT" ]
permissive
gvizquel/pyerp
e56024b481977e07339e8a0a17a26e1a0e4f1147
c859f7293cabd1003f79112463cee93ac89fccba
refs/heads/master
2022-12-07T13:12:16.333420
2019-08-29T21:38:22
2019-08-29T21:38:22
204,968,470
0
0
MIT
2022-12-04T09:21:19
2019-08-28T15:48:24
JavaScript
UTF-8
Python
false
false
594
py
# Generated by Django 2.2.4 on 2019-08-17 19:13 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('crm', '0005_pylead_stage_id'), ] operations = [ migrations.AddField( model_name='pylead', name='user_id', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL), ), ]
[ "falconsoft.3d@gmail.com" ]
falconsoft.3d@gmail.com
6c268e3b6fdbcf63221d42441b529f834f8fc3b7
667f896c43a92d58a00d8a0899a68afdf7bdf2d6
/shop/migrations/0004_auto_20190722_1024.py
1bb2f675db16bfcf1c819231c670c801d7cdd970
[]
no_license
blazer-05/myshop3
bfa9ac1072122bbecea3bbfac6ee59c44d1d3ac6
8a91f04fc3dfa6a0d07934c5f8a6e87c39b3da61
refs/heads/master
2022-11-25T01:31:16.613811
2020-05-06T07:37:30
2020-05-06T07:37:30
141,247,818
2
2
null
2022-11-22T03:22:57
2018-07-17T07:18:38
HTML
UTF-8
Python
false
false
479
py
# Generated by Django 2.0.6 on 2019-07-22 07:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0003_categoryindexpage_brands'), ] operations = [ migrations.AlterField( model_name='categoryindexpage', name='brands', field=models.ManyToManyField(blank=True, to='shop.Brand', verbose_name='Сортировать по брендам'), ), ]
[ "blazer-05@mail.ru" ]
blazer-05@mail.ru
29540371d2a4f6365c7141d0e1382600b9d97863
31580e8e50f1e55e1fa3a1ed927c9595fa4c22cb
/audiomate/utils/units.py
1f2d0cf6731022cfbe614b59feea5d83a9d4bcec
[ "MIT" ]
permissive
toddrme2178/audiomate
9651a7075efeee84a4d2d229ef173d1e7204b336
14e932ce9c0b0bebb895d496cb6054521fc80ab1
refs/heads/master
2020-04-04T09:02:54.197973
2018-10-05T09:23:45
2018-10-05T09:23:45
155,804,640
0
0
MIT
2018-11-02T02:40:29
2018-11-02T02:40:28
null
UTF-8
Python
false
false
3,785
py
""" This module contains functions for handling different units. Especially it provides function to convert from one to another unit (e.g. seconds -> sample-indexn). """ import math import numpy as np def seconds_to_sample(seconds, sampling_rate=16000): """ Convert a value in seconds to a sample index based on the given sampling rate. Args: seconds (float): The value in seconds. sampling_rate (int): The sampling rate to use for conversion. Returns: int: The sample index (0-based). Example:: >>> seconds_to_sample(1.3, sampling_rate=16000) 20800 """ return int(np.round(sampling_rate * seconds)) def sample_to_seconds(sample, sampling_rate=16000): """ Convert a sample index to seconds based on the given sampling rate. Args: sample (int): The index of the sample (0 based). sampling_rate (int): The sampling rate to use for conversion. Returns: float: The time in seconds. Example:: >>> sample_to_seconds(20800, sampling_rate=16000) 1.3 """ return sample / sampling_rate class FrameSettings(object): """ This class provides functions for handling conversions/calculations between time, samples and frames. By default the framing is done as follows: * The first frame starts at sample 0 * The end of the last frame is higher than the last sample. * The end of the last frame is smaller than the last sample + hop_size Args: frame_size (int): Number of samples used per frame. hop_size (int): Number of samples between two frames. """ def __init__(self, frame_size, hop_size): self.frame_size = frame_size self.hop_size = hop_size def num_frames(self, num_samples): """ Return the number of frames that will be used for a signal with the length of ``num_samples``. """ return math.ceil(float(max(num_samples - self.frame_size, 0)) / float(self.hop_size)) + 1 def sample_to_frame_range(self, sample_index): """ Return a tuple containing the indices of the first frame containing the sample with the given index and the last frame (exclusive, doesn't contain the sample anymore). """ start = max(0, int((sample_index - self.frame_size) / self.hop_size) + 1) end = int(sample_index / self.hop_size) + 1 return start, end def frame_to_sample(self, frame_index): """ Return a tuple containing the indices of the sample which are the first sample and the end (exclusive) of the frame with the given index. """ start = frame_index * self.hop_size end = start + self.frame_size return start, end def frame_to_seconds(self, frame_index, sr): """ Return a tuple containing the start and end of the frame in seconds. """ start_sample, end_sample = self.frame_to_sample(frame_index) return sample_to_seconds(start_sample, sampling_rate=sr), sample_to_seconds(end_sample, sampling_rate=sr) def time_range_to_frame_range(self, start, end, sr): """ Calculate the frames containing samples from the given time range in seconds. Args: start (float): Start time in seconds. end (float): End time in seconds. sr (int): The sampling rate to use for time-to-sample conversion. Returns: tuple: A tuple containing the start and end (exclusive) frame indices. """ start_sample = seconds_to_sample(start, sr) end_sample = seconds_to_sample(end, sr) return self.sample_to_frame_range(start_sample)[0], self.sample_to_frame_range(end_sample - 1)[1]
[ "m.buechi@outlook.com" ]
m.buechi@outlook.com
0cbc87ac7309af97c8143cc09db4ee2ecab25463
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03612/s546294004.py
2630a3e0d1757945406b04e54b3cce785b681c6f
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
241
py
def main(): n, *p = map(int, open(0).read().split()) ans = 0 i = False for p, q in enumerate(p, 1): j = p == q i = (i or j) and (not i) ans += i print(ans) if __name__ == '__main__': main()
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
012a4f8d8d70aabb9da5e65f51ea257e404789ed
42fa1862effc3e494859904b76c43ce2bcd623a0
/compare_box_results_annual.py
783480ceb71e52330ce72ea852abb25df0ee901d
[]
no_license
PaulHalloran/desktop_python_scripts
3e83aedf3e232da610b5f7477e4d7e8fb0253f99
325e923527278a5c3e9ab8c978f29b2816dab087
refs/heads/master
2021-01-01T19:52:06.828997
2015-06-27T21:14:10
2015-06-27T21:14:10
38,155,075
0
0
null
null
null
null
UTF-8
Python
false
false
2,003
py
import numpy as np import glob import matplotlib.pyplot as plt import matplotlib array_size=239 source=r"/net/project/obgc/boxmodel_testing_less_boxes_4_monthly_inclusing_vol_params/results/order_runs_processed_in_box_model.txt" inp = open(source,"r") count=0 for line in inp: count +=1 ''' Read in subpolar gyre co2 flux data from QUMP ''' run_names_order=str.split(line,' ') run_names_order=run_names_order[0:-1] input_year=np.zeros(array_size) qump_co2_flux=np.zeros(array_size) dir0='/net/project/obgc/qump_out_python/annual_means/' no_filenames=glob.glob(dir0+'*30249.txt') filenames0=glob.glob(dir0+'*'+run_names_order[1]+'*30249.txt') qump_year=np.zeros(array_size) qump_co2_flux=np.zeros(array_size) input2=np.genfromtxt(filenames0[0], delimiter=",") qump_year=input2[:,0] filenames0=glob.glob(dir0+'*'+run_names_order[1]+'*30249.txt') input2=np.genfromtxt(filenames0[0], delimiter=",") if input2[:,1].size == array_size: qump_co2_flux[:]=input2[:,1] ''' Read in data from box model ''' dir1='/net/project/obgc/boxmodel_testing_less_boxes_4_annual_b/results/' filenames=glob.glob(dir1+'box_model_qump_results_20.csv') input1=np.genfromtxt(filenames[0], delimiter=",") box_co2_flux=np.zeros(array_size) box_years=input1[:,0] box_co2_flux[:]=input1[:,2] ''' ''' dir2='/net/project/obgc/boxmodel_testing_less_boxes_4_annual_b/results2/' filenames2=glob.glob(dir2+'box_model_qump_results_20.csv') input2=np.genfromtxt(filenames2[0], delimiter=",") box_co2_flux2=np.zeros(array_size) box_years2=input2[:,0] box_co2_flux2[:]=input2[:,2] ''' plotting ''' smoothing_len=12.0 plt.plot(box_years[smoothing_len/2.0:-smoothing_len/2.0+1],matplotlib.mlab.movavg(qump_co2_flux,smoothing_len),'k') plt.plot(box_years[smoothing_len/2.0:-smoothing_len/2.0+1],matplotlib.mlab.movavg((box_co2_flux/1.12e13)*1.0e15/12.0,smoothing_len),'b') plt.plot(box_years[smoothing_len/2.0:-smoothing_len/2.0+1],matplotlib.mlab.movavg((box_co2_flux2/1.12e13)*1.0e15/12.0,smoothing_len),'r') plt.show()
[ "paul.halloran@gmail.com" ]
paul.halloran@gmail.com
7e05b056b98a880923fa9f2dd1b5cc563d72c4e6
627e78614aaf50abbb0c73a63a8a3f24b66d6f51
/srcOptics/migrations/0006_auto_20190518_0308.py
330a50a29c43d5ff2a7d8004a98405e47954b27f
[ "Apache-2.0" ]
permissive
rndmh3ro/src_optics
66ac0c9e1a92fc9ebeee8510f6d159eb8b333442
50b3f486bcd6a1ecf6f77ea71c3e1ab0d13c8c4c
refs/heads/master
2020-05-24T17:23:25.764085
2019-05-18T03:08:57
2019-05-18T03:08:57
187,383,824
0
0
null
2019-05-18T17:00:43
2019-05-18T17:00:42
null
UTF-8
Python
false
false
693
py
# Generated by Django 2.2 on 2019-05-18 03:08 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('srcOptics', '0005_auto_20190518_0245'), ] operations = [ migrations.RemoveIndex( model_name='commit', name='srcOptics_c_commit__d99f63_idx', ), migrations.RemoveIndex( model_name='commit', name='srcOptics_c_commit__abe930_idx', ), migrations.RemoveIndex( model_name='statistic', name='rollup2', ), migrations.RemoveIndex( model_name='statistic', name='rollup3', ), ]
[ "michael@michaeldehaan.net" ]
michael@michaeldehaan.net
6226796b04f665cb95bfbf1198ebc8f2adeb65e0
9e988c0dfbea15cd23a3de860cb0c88c3dcdbd97
/sdBs/AllRun/sdssj9-10_j150850.13+005408.0/sdB_SDSSJ910_J150850.13+005408.0_coadd.py
e31ebe0ed205234c48ee10c9ad9ac4c0ca2b859c
[]
no_license
tboudreaux/SummerSTScICode
73b2e5839b10c0bf733808f4316d34be91c5a3bd
4dd1ffbb09e0a599257d21872f9d62b5420028b0
refs/heads/master
2021-01-20T18:07:44.723496
2016-08-08T16:49:53
2016-08-08T16:49:53
65,221,159
0
0
null
null
null
null
UTF-8
Python
false
false
497
py
from gPhoton.gMap import gMap def main(): gMap(band="NUV", skypos=[227.208875,0.902222], skyrange=[0.0333333333333,0.0333333333333], stepsz = 30., cntfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdBs/sdB_SDSSJ910_J150850.13+005408.0/sdB_SDSSJ910_J150850.13+005408.0_movie_count.fits", cntcoaddfile="/data2/fleming/GPHOTON_OUTPUT/LIGHTCURVES/sdB/sdB_SDSSJ910_J150850.13+005408.0/sdB_SDSSJ910_J150850.13+005408.0_count_coadd.fits", overwrite=True, verbose=3) if __name__ == "__main__": main()
[ "thomas@boudreauxmail.com" ]
thomas@boudreauxmail.com
28a84491ace1d938a383c8c28f3502534a18d7c1
e0980f704a573894350e285f66f4cf390837238e
/.history/streams/blocks_20201029154353.py
83848421758b343e9e1be692b66855eb360ce765
[]
no_license
rucpata/WagtailWebsite
28008474ec779d12ef43bceb61827168274a8b61
5aa44f51592f49c9a708fc5515ad877c6a29dfd9
refs/heads/main
2023-02-09T15:30:02.133415
2021-01-05T14:55:45
2021-01-05T14:55:45
303,961,094
0
0
null
null
null
null
UTF-8
Python
false
false
3,872
py
from django import forms from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock from wagtail.contrib.table_block.blocks import TableBlock #Walidacja problemu from django.core.exceptions import ValidationError from django.form.utils import ErrorList class TitleBlock(blocks.StructBlock): text = blocks.CharBlock( required = True, elp_text='Tekst do wyświetlenia', ) class Meta: template = 'streams/title_block.html' icon = 'edycja' label = 'Tytuł' help_text = 'Wyśrodkowany tekst do wyświetlenia na stronie.' class LinkValue(blocks.StructValue): """Dodatkowao logika dla lików""" def url(self) -> str: internal_page = self.get('internal_page') external_link = self.get('external_link') if internal_page: return internal_page.url elif external_link: return external_link return '' class Link(blocks.StructBlock): link_text = blocks.CharBlock( max_length=50, default='Więcej szczegółów' ) internal_page = blocks.PageChooserBlock( required=False ) external_link = blocks.URLBlock( required=False ) class Meta: value_class = LinkValue def clean(self, value): error = {} if w: class Card(blocks.StructBlock): title = blocks.CharBlock( max_length=100, help_text = 'Pogrubiony tytuł tej karty. Maksymalnie 100 znaków.' ) text = blocks.TextBlock( max_length=255, help_text='Opcjonalny tekst tej karty. Maksymalnie 255 znaków.' ) image = ImageChooserBlock( help_text = 'Obraz zostanie automatycznie przycięty o 570 na 370 pikseli' ) link = Link(help_text = 'Wwybierz link') class CardsBlock(blocks.StructBlock): cards = blocks.ListBlock( Card() ) class Meta: template = 'streams/card_block.html' icon = 'image' label = 'Karty standardowe' class RadioSelectBlock(blocks.ChoiceBlock): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.field.widget = forms.RadioSelect( choices=self.field.widget.choices ) class ImageAndTextBlock(blocks.StructBlock): image = ImageChooserBlock(help_text='Obraz automatycznie przycięty do rozmiaru 786 na 552 px.') image_alignment = RadioSelectBlock( choices = ( ('left','Opraz po lewej stronie'), ('right', 'Obraz po prawej stronie'), ), default = 'left', help_text = 'Obraz po lewej stronie, tekst po prawej lub obraz po prawej stronie tekst po lewej.' ) title = blocks.CharBlock( max_length=60, help_text='Maksymalna długość 60 znaków.' ) text = blocks.CharBlock( max_length = 140, required = False, ) link = Link() class Meta: template = 'streams/image_and_text_block.html' icon = 'image' label = 'Obraz & Tekst' class CallToActionBlock(blocks.StructBlock): title =blocks.CharBlock( max_length = 200, help_text = 'Maksymalnie 200 znaków.' ) link = Link() class Meta: template = 'streams/call_to_action_block.html' icon = 'plus' label = 'Wezwanie do działania' class PricingTableBlock(TableBlock): """Blok tabeli cen.""" class Meta: template = 'streams/pricing_table_block.html' label = 'Tabela cen' icon = 'table' help_text = 'Twoje tabele z cenami powinny zawierać zawsze 4 kolumny.' ''' class RichTextWithTitleBlock(blocks.StructBlock): title = blocks.CharBlock(max_length=50) context = blocks.RichTextBlock(features=[]) class Meta: template = 'streams/simple_richtext_block.html' '''
[ "rucinska.patrycja@gmail.com" ]
rucinska.patrycja@gmail.com
bdb51ebcfbc9fdb629487fa4a3612921c0f24684
c23dca8100394d66f0a6aadfefdf15fa8ab7ce54
/examples/animations/vulfbach.py
1b930e16dec2fbdf35fdc172e2921c2abf9d30fa
[ "Apache-2.0" ]
permissive
beesandbombs/coldtype
c2ad2141bf12d35a1845d407465b6a0777ce5020
d02c7dd36bf1576fa37dc8c50d5c1a6e47b1c5ea
refs/heads/main
2023-02-01T18:19:56.556888
2020-12-17T02:48:02
2020-12-17T02:48:02
322,321,369
1
0
Apache-2.0
2020-12-17T14:35:07
2020-12-17T14:35:06
null
UTF-8
Python
false
false
1,867
py
from coldtype import * from coldtype.animation.midi import MidiReader """ Run as `coldtype examples/animation/vulfbach.py` To multiplex, add ` -m` to the end of that call (then when you hit `a` in the viewer app, the frames will render in parallel in random-order) Rendered with organ.wav as the backing track: https://vimeo.com/489013931/cd77ab7e4d """ midi = MidiReader("examples/animations/media/organ.mid", bpm=183, fps=30) organ = midi[0] note_width = 3 r = Rect(1440, 1080) def pos(x, y): return (x*note_width, (y-midi.min)*(r.h-200)/midi.spread+100) def build_line(): dp = DATPen().f(None).s(1, 0, 0.5).sw(3) last_note = None for note in organ.notes: if last_note and (note.on - last_note.off > 3 or last_note.note == note.note): dp.lineTo((pos(last_note.off, last_note.note))) dp.endPath() last_note = None if last_note: if last_note.off < note.on: dp.lineTo((pos(last_note.off, last_note.note))) else: dp.lineTo((pos(note.on, last_note.note))) dp.lineTo((pos(note.on, note.note))) else: dp.moveTo((pos(note.on, note.note))) last_note = note if last_note: dp.lineTo((pos(last_note.off, last_note.note))) dp.endPath() return dp line = build_line() @animation(duration=organ.duration, rect=r, storyboard=[50]) def render(f): looped_line = DATPenSet([ line.copy().translate(-f.i*note_width+r.w-note_width*3-organ.duration*note_width, 0), line.copy().translate(-f.i*note_width+r.w-note_width*3, 0) ]) return DATPenSet([ DATPen().rect(f.a.r).f(0), (looped_line.pen() .color_phototype(f.a.r, blur=20, cut=215, cutw=40)), (looped_line.pen() .color_phototype(f.a.r, blur=3, cut=200, cutw=25))])
[ "rob.stenson@gmail.com" ]
rob.stenson@gmail.com
be1832b8027e0d6184936ec244f1e8dfcac9a79d
bec60c149e879666de11bd1bcf47ab0dc2225d49
/Testing/cobbity/sft_main.py
ac86f5013747763de6985b0a5a9576f1f0b9e8b5
[]
no_license
KipCrossing/OpenEM
7fee5f3d98bb931209999a8dca41295c1412308e
0572d3697b1c8299c29e31840e6ec1f9e08c172c
refs/heads/master
2021-07-17T02:58:15.385369
2020-07-02T12:16:39
2020-07-02T12:16:39
186,344,444
0
0
null
2019-09-06T02:25:56
2019-05-13T04:19:59
Python
UTF-8
Python
false
false
4,040
py
import pandas as pd import matplotlib.pyplot as plt import math import numpy as np from scipy import stats import random file_number = 1 df = pd.read_csv('temp_data_cobbity'+str(file_number)+'.csv', sep=',') notes_df = pd.read_csv('temp_notes_cobbity'+str(file_number)+'.csv', sep=',') spw = 10 ishift = 8.6 # - 0.375 # temprature vector at 7.1 and # the Change vector at 6.85 +- 2.5 print(list(df)) delay = 0 roll = 20 df['Temp_rolling'] = df['Temp'].rolling(roll*100, center=True, min_periods=1).mean().shift(-delay) # Hs = amp*math.sin(math.pi*2*sft_out/spw) # Hp = amp*math.cos(math.pi*2*sft_out/spw) df['Hs'] = df['Amp']*np.sin(math.pi*2*(df['Shift']-ishift)/spw) df['Hp'] = df['Amp']*np.cos(math.pi*2*(df['Shift']-ishift)/spw) df['Amp_rolling'] = df['Amp'].rolling(roll, center=True, min_periods=1).mean().shift(-delay) df['Hs_rolling'] = df['Hs'].rolling(roll, center=True, min_periods=1).mean().shift(-delay) df['Hp_rolling'] = df['Hp'].rolling(roll, center=True, min_periods=1).mean().shift(-delay) df['Sft_rolling'] = df['Shift'].rolling(roll, center=True, min_periods=1).mean().shift(-delay) df['Volt_rolling'] = df['Voltage'].rolling(roll, center=True, min_periods=1).mean().shift(-delay) print(df.head()) print('-----') print(df.tail()) cut_df = df # .query('ID > 7900').query('ID < 13400') x = cut_df['Temp_rolling'] y = cut_df['Sft_rolling'] # plt.plot() # plt.plot(cut_df['ID'], x*0.8) # plt.plot(cut_df['ID'], y) # plt.plot(cut_df['ID'], cut_df['Shift']/10) # # for rown in range(notes_df.shape[0]-1): # plt.axvline(x=notes_df.iloc[rown][0], color='black', ls='--', label=notes_df.iloc[rown][1]) # plt.annotate(notes_df.iloc[rown][1], xy=(notes_df.iloc[rown][0], random.random())) # # # plt.show(block=True) # slope, intercept, r_value, p_value, std_err = stats.linregress( x, y) print('Slope: ', slope) print('Intercept: ', intercept) print('R value: ', r_value) cut_df['Tem_Adj'] = (cut_df['Temp_rolling']*slope + intercept) cut_df['Adj'] = cut_df['Sft_rolling'] - (cut_df['Temp_rolling']*slope + intercept) df['Hs'] = df['Amp']*np.sin(math.pi*2*(cut_df['Adj']-ishift)/spw) df['Hp'] = df['Amp']*np.cos(math.pi*2*(cut_df['Adj']-ishift)/spw) df['Hs_rolling'] = df['Hs'].rolling(roll, center=True, min_periods=1).mean().shift(-delay) df['Hp_rolling'] = df['Hp'].rolling(roll, center=True, min_periods=1).mean().shift(-delay) # Real/Imagionary # plt.scatter(cut_df['Temp_rolling'], cut_df['Adj'], s=0.5) # plt.scatter(cut_df['Temp_rolling'], cut_df['Sft_rolling'], s=0.5) # plt.scatter(cut_df['Temp_rolling'], cut_df['Tem_Adj'], s=0.5) # plt.legend() # plt.show(block=True) # cut_df['Ht_adj'] = (cut_df['Adj']**2 + cut_df['Hp_rolling']**2)**0.5 # cut_df['Sft_adj'] = np.arctan(cut_df['Adj']/cut_df['Hp_rolling'])purple # plt.plot(cut_df['ID'], cut_df['Sft_rolling']) # plt.plot(cut_df['ID'], cut_df['Tem_Adj']) # plt.legend() # plt.show() # # plt.plot(cut_df['ID'], cut_df['Adj']) # plt.show() to_plot = [['Amp_rolling', 'Amp_rolling', 'orange'], ['Hp_rolling', 'Hp', 'r'], [ 'Hs_rolling', 'Hs', 'b'], ['Temp_rolling', 'Temp', 'g'], ['Sft_rolling', 'Shift', 'purple'], ['Volt_rolling', 'Volt_rolling', 'yellow']] # plt.subplot(len(to_plot), 1, 1) for info_i in range(len(to_plot)): plt.subplot(len(to_plot), 1, info_i+1) plt.plot(cut_df['ID'], cut_df[to_plot[info_i][0]], c=to_plot[info_i][2]) plt.ylabel(to_plot[info_i][1]) for rown in range(notes_df.shape[0]): plt.axvline(x=notes_df.iloc[rown][0], color='black', ls='--', label=notes_df.iloc[rown][1]) lev = (rown+1)/(notes_df.shape[0]+1) text_place = min(cut_df[to_plot[info_i][0]]) + lev * \ (max(cut_df[to_plot[info_i][0]]) - min(cut_df[to_plot[info_i][0]])) plt.annotate(notes_df.iloc[rown][1], xy=(notes_df.iloc[rown][0], text_place)) plt.suptitle('r2: ' + str(round(r_value, 3))+'\nShift = ' + str(round(ishift/10, 3))) plt.xlabel("Time") # plt.legend() plt.show(block=True) print(file_number) cut_df.to_csv('Cobbity9_run'+str(file_number)+'.csv', index=False)
[ "kip.crossing@gmail.com" ]
kip.crossing@gmail.com
98980a00b8e976c7c027a4d14ae42f905f50841b
4705111dfabedfc883ad51dca15294f32a4de2de
/codes/evaluate_csv.py
bd6ee1b65d8fcca0b657b7f7b85dad76fb46bdbe
[]
no_license
Bala93/Glaucoma
d57ec31fce2c3eff2805aa42dfcbf4eda1b02da2
f1b600135db855de81e963cff00890eb81be9a0c
refs/heads/master
2021-09-19T05:20:24.012747
2018-07-23T20:10:17
2018-07-23T20:10:17
139,633,353
3
0
null
null
null
null
UTF-8
Python
false
false
1,743
py
import pandas as pd import numpy as np import os from scipy import stats from sklearn.metrics import roc_auc_score,classification_report import itertools out_csv = '/media/htic/Balamurali/Glaucoma_models/classification_results.csv' src_path = '/media/htic/Balamurali/Glaucoma_models/' test_data_len = 400 color_space = ['LAB','Normalized','PseudoDepth'] models = ['resnet152']#,'densenet201','resnet101','densenet169'] score_np = np.empty([test_data_len,0]) pred_np = np.empty([test_data_len,0]) # Change for test is_test = False csv_name = 'output.csv' for model in models: for color in color_space: csv_path = os.path.join(src_path,'{}_{}'.format(model,color),csv_name) pd_data = pd.read_csv(csv_path) file_names = pd_data['FileName'].values.reshape(400,1) pred_data = pd_data['Predicted'].values.reshape(400,1) score_data = pd_data['Glaucoma Risk'].values.reshape(400,1) pred_np = np.hstack([pred_np,pred_data]) score_np = np.hstack([score_np,score_data]) # break # break #print (file_names) best_predict,_ = stats.mode(pred_np,axis=1) best_predict = best_predict.astype(np.uint8) score_np_min = np.min(score_np,axis=1).reshape(400,1) score_np_max = np.max(score_np,axis=1).reshape(400,1) zero_mask = np.where(best_predict == 0) one_mask = np.where(best_predict == 1) print(zero_mask[0].shape) result_score = np.zeros([400,1]) result_score[zero_mask] = score_np_max[zero_mask] result_score[one_mask] = score_np_min[one_mask] # print (result_score) if is_test: gt = np.zeros((400,1)) gt[:40] = 1 # print(gt) print(roc_auc_score(gt,result_score)) result = np.hstack([file_names,result_score]) df = pd.DataFrame(result) df.to_csv(out_csv,header=['FileName','Glaucoma Risk'],index=False)
[ "balamuralim.1993@gmail.com" ]
balamuralim.1993@gmail.com
dca029d4e16c600ea29a4b2816b3f76e290cca76
77090c3eaf15342505edc228ea19769ab219e0f7
/CNVbenchmarkeR/output/manta2-datasetall/results17340/runWorkflow.py
c8ec302120f7fb9810ece6c2480fc03e00f90fe7
[ "MIT" ]
permissive
robinwijngaard/TFM_code
046c983a8eee7630de50753cff1b15ca3f7b1bd5
d18b3e0b100cfb5bdd9c47c91b01718cc9e96232
refs/heads/main
2023-06-20T02:55:52.071899
2021-07-13T13:18:09
2021-07-13T13:18:09
345,280,544
0
0
null
null
null
null
UTF-8
Python
false
false
7,090
py
#!/usr/bin/env python2 # Workflow run script auto-generated by command: '/home/robin/Documents/Project/manta/Install/bin/configManta.py --bam=/home/robin/Documents/Project/Samples/bam/all/17340.bam --referenceFasta=/home/robin/Documents/Project/Samples/hg38/hg38.fa --config=/home/robin/Documents/Project/TFM_code/CNVbenchmarkeR/output/manta2-datasetall/configManta.py.ini --exome --runDir=/home/robin/Documents/Project/TFM_code/CNVbenchmarkeR/output/manta2-datasetall/results17340' # import os, sys if sys.version_info >= (3,0): import platform raise Exception("Manta does not currently support python3 (version %s detected)" % (platform.python_version())) if sys.version_info < (2,6): import platform raise Exception("Manta requires python2 version 2.6+ (version %s detected)" % (platform.python_version())) scriptDir=os.path.abspath(os.path.dirname(__file__)) sys.path.append(r'/home/robin/Documents/Project/manta/Install/lib/python') from mantaWorkflow import MantaWorkflow def get_run_options(workflowClassName) : from optparse import OptionGroup, SUPPRESS_HELP from configBuildTimeInfo import workflowVersion from configureUtil import EpilogOptionParser from estimateHardware import EstException, getNodeHyperthreadCoreCount, getNodeMemMb epilog="""Note this script can be re-run to continue the workflow run in case of interruption. Also note that dryRun option has limited utility when task definition depends on upstream task results -- in this case the dry run will not cover the full 'live' run task set.""" parser = EpilogOptionParser(description="Version: %s" % (workflowVersion), epilog=epilog, version=workflowVersion) parser.add_option("-m", "--mode", type="string",dest="mode", help=SUPPRESS_HELP) parser.add_option("-j", "--jobs", type="string",dest="jobs", help="number of jobs, must be an integer or 'unlimited' (default: Estimate total cores on this node)") parser.add_option("-g","--memGb", type="string",dest="memGb", help="gigabytes of memory available to run workflow, must be an integer (default: Estimate the total memory for this node)") parser.add_option("-d","--dryRun", dest="isDryRun",action="store_true",default=False, help="dryRun workflow code without actually running command-tasks") parser.add_option("--quiet", dest="isQuiet",action="store_true",default=False, help="Don't write any log output to stderr (but still write to workspace/pyflow.data/logs/pyflow_log.txt)") def isLocalSmtp() : import smtplib try : smtplib.SMTP('localhost') except : return False return True isEmail = isLocalSmtp() emailHelp = SUPPRESS_HELP if isEmail : emailHelp="send email notification of job completion status to this address (may be provided multiple times for more than one email address)" parser.add_option("-e","--mailTo", type="string",dest="mailTo",action="append",help=emailHelp) debug_group = OptionGroup(parser,"development debug options") debug_group.add_option("--rescore", dest="isRescore",action="store_true",default=False, help="Reset task list to re-run hypothesis generation and scoring without resetting graph generation.") parser.add_option_group(debug_group) ext_group = OptionGroup(parser,"extended portability options (should not be needed by most users)") ext_group.add_option("--maxTaskRuntime", type="string", metavar="hh:mm:ss", help="Specify max runtime per task (no default)") parser.add_option_group(ext_group) (options,args) = parser.parse_args() if not isEmail : options.mailTo = None if len(args) : parser.print_help() sys.exit(2) if options.mode is None : options.mode = "local" elif options.mode not in ["local"] : parser.error("Invalid mode. Available modes are: local") if options.jobs is None : try : options.jobs = getNodeHyperthreadCoreCount() except EstException: parser.error("Failed to estimate cores on this node. Please provide job count argument (-j).") if options.jobs != "unlimited" : options.jobs=int(options.jobs) if options.jobs <= 0 : parser.error("Jobs must be 'unlimited' or an integer greater than 1") # note that the user sees gigs, but we set megs if options.memGb is None : try : options.memMb = getNodeMemMb() except EstException: parser.error("Failed to estimate available memory on this node. Please provide available gigabyte argument (-g).") elif options.memGb != "unlimited" : options.memGb=int(options.memGb) if options.memGb <= 0 : parser.error("memGb must be 'unlimited' or an integer greater than 1") options.memMb = 1024*options.memGb else : options.memMb = options.memGb options.resetTasks=[] if options.isRescore : options.resetTasks.append("makeHyGenDir") return options def main(pickleConfigFile, primaryConfigSection, workflowClassName) : from configureUtil import getConfigWithPrimaryOptions runOptions=get_run_options(workflowClassName) flowOptions,configSections=getConfigWithPrimaryOptions(pickleConfigFile,primaryConfigSection) # new logs and marker files to assist automated workflow monitoring: warningpath=os.path.join(flowOptions.runDir,"workflow.warning.log.txt") errorpath=os.path.join(flowOptions.runDir,"workflow.error.log.txt") exitpath=os.path.join(flowOptions.runDir,"workflow.exitcode.txt") # the exit path should only exist once the workflow completes: if os.path.exists(exitpath) : if not os.path.isfile(exitpath) : raise Exception("Unexpected filesystem item: '%s'" % (exitpath)) os.unlink(exitpath) wflow = workflowClassName(flowOptions) retval=1 try: retval=wflow.run(mode=runOptions.mode, nCores=runOptions.jobs, memMb=runOptions.memMb, dataDirRoot=flowOptions.workDir, mailTo=runOptions.mailTo, isContinue="Auto", isForceContinue=True, isDryRun=runOptions.isDryRun, isQuiet=runOptions.isQuiet, resetTasks=runOptions.resetTasks, successMsg=wflow.getSuccessMessage(), retryWindow=0, retryMode='all', warningLogFile=warningpath, errorLogFile=errorpath) finally: exitfp=open(exitpath,"w") exitfp.write("%i\n" % (retval)) exitfp.close() sys.exit(retval) main(r"/home/robin/Documents/Project/TFM_code/CNVbenchmarkeR/output/manta2-datasetall/results17340/runWorkflow.py.config.pickle","manta",MantaWorkflow)
[ "robinwijngaard@gmail.com" ]
robinwijngaard@gmail.com
619b95ba555b66b32096a474e7a7ba1383b06fda
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2726/60712/321256.py
368edb38bd94bf3eeac6e5e68f29e508e443272e
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
267
py
l=[] for i in range(1): l.append(input()) if l==['[3,9,20,null,null,15,7]']: print(0) elif l==['4', '[[0,1],[0,2],[1,2]]']: print(1) elif l==['6', '[[0,1],[0,2],[0,3],[1,2]]']: print(-1) elif l==['AABAAABBABAAB', '4']: print(12) else: print(l)
[ "1069583789@qq.com" ]
1069583789@qq.com
803c66c2822fc5788ba624e77b172860ff06af94
89b45e528f3d495f1dd6f5bcdd1a38ff96870e25
/HeadFirstPython/chapter7/yate.py
0075146abacf9eac9aa72f3fbc0456c831991deb
[]
no_license
imatyukin/python
2ec6e712d4d988335fc815c7f8da049968cc1161
58e72e43c835fa96fb2e8e800fe1a370c7328a39
refs/heads/master
2023-07-21T13:00:31.433336
2022-08-24T13:34:32
2022-08-24T13:34:32
98,356,174
2
0
null
2023-07-16T02:31:48
2017-07-25T22:45:29
Python
UTF-8
Python
false
false
3,147
py
#!/usr/bin/env python3 '''Import the “Template” class from the standard library’s “string” module. This allows for simple string-substitution templates.''' from string import Template '''This function takes a single (optional) string as its argument and uses it to create a CGI “Content-type:” line, with “text/html” as the default.''' def start_response(resp="text/html"): return('Content-type: ' + resp + '\n\n') '''This function takes a single string as its argument and uses at the title for the start of a HTML page. The page itself is stored within a separate file in “templates/header.html”, and the title is substituted in as needed.''' def include_header(the_title): with open('templates/header.html') as headf: head_text = headf.read() header = Template(head_text) return(header.substitute(title=the_title)) '''Similar to the “include_header” function, this one uses its single string as its argument to create the end of a HTML page. The page itself is stored within a separate file in “templates/footer.html”, and the argument is used to dynamically create a set of HTML link tags. Based on how they are used, it looks like the argument needs to be a dictionary.''' def include_footer(the_links): with open('templates/footer.html') as footf: foot_text = footf.read() link_string = '' for key in the_links: link_string += '<a href="' + the_links[key] + '">' + key + '</a>&nbsp;&nbsp;&nbsp;&nbsp;' footer = Template(foot_text) return(footer.substitute(links=link_string)) '''This function returns the HTML for the start of a form and lets the caller specify the URL to send the form’s data to, as well as the method to use.''' def start_form(the_url, form_type="POST"): return('<form action="' + the_url + '" method="' + form_type + '">') '''This function returns the HTML markup, which terminates the form while allowing the caller to customize the text of the form’s “submit” button.''' def end_form(submit_msg="Submit"): return('<p></p><input type=submit value="' + submit_msg + '">') '''Given a radio-button name and value, create a HTML radio button (which is typically included within a HTML form). Note: both arguments are required.''' def radio_button(rb_name, rb_value): return('<input type="radio" name="' + rb_name + '" value="' + rb_value + '"> ' + rb_value + '<br />') '''Given a list of items, this function turns the list into a HTML unnumbered list. A simple “for” loop does all the work, adding a LI to the UL element with each iteration.''' def u_list(items): u_string = '<ul>' for item in items: u_string += '<li>' + item + '</li>' u_string += '</ul>' return(u_string) '''Create and return a HTML header tag (H1, H2, H2, and so on) with level 2 as the default.. The “header_text” argument is required.''' def header(header_text, header_level=2): return('<h' + str(header_level) + '>' + header_text + '</h' + str(header_level) + '>') '''Enclose a paragraph of text (a string) in HTML paragraph tags.''' def para(para_text): return('<p>' + para_text + '</p>')
[ "i.matukin@gmail.com" ]
i.matukin@gmail.com
e11a9bf8ca7823fc0080cc5df2dd9920564063e0
5c335469a9198d61e2095293d06ce78e781726d0
/python/Semester 1/Assignments/1B/numMultiples.py
365aa036299834bcb8a0fe4cf38979e4456ea3f7
[]
no_license
LaurenceGA/programmingProjects
5e203b450d11bff9cdb652661934ec3f797a6860
1fe3ea9a89be4c32cd68dd46da7a842b933c438b
refs/heads/master
2021-01-15T10:59:09.890932
2017-06-18T11:20:28
2017-06-18T11:20:28
36,592,569
1
1
null
null
null
null
UTF-8
Python
false
false
856
py
#!/usr/bin/env python # 159.171 Assignment 1B # Laurence Armstrong, 15062061 __author__ = 'Laurence Armstrong' authorship_string = "%s created by %s (%d)\n%s\n" % \ ("numMultiples.py", __author__, 15062061, "-----" * 15) \ if __name__ == '__main__' else "" print(authorship_string, end="") def getMultiples(num, limit): multiples = [] for i in range(int(limit/num)): multiples.append(num*(i+1)) return multiples def getListProduct(numList): product = 1 for num in numList: product *= num return product try: number = int(input("Enter a number: ")) limit = int(input("Enter a limit: ")) mul = getMultiples(number, limit) print(mul) print("The product of the list is {}".format(getListProduct(mul))) except ValueError: print("That is not an acceptable input.")
[ "lorryarmstrong@gmail.com" ]
lorryarmstrong@gmail.com
9b5a3614e14a5dd10bca9a13250a10e6c978cf84
99f43f4591f63d0c57cd07f07af28c0b554b8e90
/python/beckjun/2020하반기삼성/마법사상어와 파이어볼.py
0891e4adc5d3232a28b049e8a5bcfd58b848c88e
[]
no_license
SINHOLEE/Algorithm
049fa139f89234dd626348c753d97484fab811a7
5f39d45e215c079862871636d8e0306d6c304f7e
refs/heads/master
2023-04-13T18:55:11.499413
2023-04-10T06:21:29
2023-04-10T06:21:29
199,813,684
0
0
null
null
null
null
UTF-8
Python
false
false
3,078
py
def solution(n, m, k, dic): def move(y, x, d, s): dy = [-1, -1, 0, 1, 1, 1, 0, -1] dx = [0, 1, 1, 1, 0, -1, -1, -1] ny = (y + s*dy[d])%n nx = (x + s*dx[d])%n return ny, nx def is_all_even_or_odd(directions): pivot = directions[0] for diction in directions: if pivot % 2 != diction % 2: return False return True # 같은 칸에 있는 파이어볼은 모두 하나로 합쳐진다. # 파이어볼은 4개의 파이어볼로 나누어진다. # 나누어진 파이어볼의 질량, 속력, 방향은 다음과 같다. # 질량은 ⌊(합쳐진 파이어볼 질량의 합)/5⌋이다. # 속력은 ⌊(합쳐진 파이어볼 속력의 합)/(합쳐진 파이어볼의 개수)⌋이다. # 합쳐지는 파이어볼의 방향이 모두 홀수이거나 모두 짝수이면, 방향은 0, 2, 4, 6이 되고, 그렇지 않으면 1, 3, 5, 7이 된다. # 질량이 0 인 파이어볼은 소멸한다 def merge(values): total_m, total_s = 0, 0 directions = [] cnt_s = 0 for value in values: m, s, d = value directions.append(d) total_m += m total_s += s cnt_s += 1 if total_m >=5: if is_all_even_or_odd(directions): return [(total_m // 5, total_s // cnt_s, 0), (total_m // 5, total_s // cnt_s, 2), (total_m // 5, total_s // cnt_s,4), (total_m // 5, total_s // cnt_s,6)] else: return [(total_m // 5, total_s // cnt_s,1), (total_m // 5, total_s // cnt_s,3), (total_m // 5, total_s // cnt_s,5), (total_m // 5, total_s // cnt_s,7)] else: return [] # k 번 반복한다 while k: k -= 1 new_dic = {} # 새로운 공간에 이동한 파이어볼을 적재한다. for key, values in dic.items(): y, x = key for value in values: m, s, d = value ny, nx = move(y, x, d, s) if new_dic.get((ny, nx)) is None: new_dic[(ny, nx)] = [(m, s, d)] else: new_dic[(ny, nx)].append((m, s, d)) # 적재한 파이어볼 중 두개 이상인 애들을 다음과 같은 일을 한다 dic = {} for key, values in new_dic.items(): if len(values) > 1: new_values = merge(values) if len(new_values): dic[(key[0], key[1])] = new_values else: dic[(key[0], key[1])] = values # 남은 파이어볼의 총 질량을 구한다. res = 0 for key, values in dic.items(): for value in values: m,s,d = value res += m return res if __name__ == "__main__": n, m, k = map(int, input().split()) dic = {} for _ in range(m): y, x, m, d, s = map(int, input().split()) y, x = y-1, x-1 dic[(y, x)] = [(m, d, s)] print(solution(n, m, k, dic))
[ "dltlsgh5@naver.com" ]
dltlsgh5@naver.com
77e9b515c379d267c79bc469465617ce712b7d21
ebd5d8445e2bf928a1e9f2ac1c6dfa0a56575c04
/setup.py
7309dbfdba923a6d8ce1c042fb37bed253e4a00b
[]
no_license
mozilla-services/jenkins-publisher
e30a869303816e430f08efd326b339e9a62525e9
75064327ecddb4974c66764d993ce93f22bdc6e7
refs/heads/master
2021-01-19T17:44:34.389854
2012-05-10T13:17:30
2012-05-10T13:17:30
4,283,548
1
3
null
2019-03-28T02:23:17
2012-05-10T11:19:33
Python
UTF-8
Python
false
false
734
py
from setuptools import setup, find_packages install_requires = ['feedparser', 'mako'] with open("README.rst") as f: README = f.read() with open("CHANGES.rst") as f: CHANGES = f.read() setup(name='jenkins-publisher', version='0.1', packages=find_packages(), description="Publish a static website using the Jenkins RSS feed", long_description=README + '\n' + CHANGES, author="Mozilla Foundation", author_email="services-dev@lists.mozila.org", include_package_data=True, zip_safe=False, install_requires=install_requires, test_requires=['nose'], test_suite = 'nose.collector', entry_points=""" [console_scripts] jpub = jpub:main """)
[ "tarek@ziade.org" ]
tarek@ziade.org
4fbde5941a6cfa9eadb4112815e95ad71960b1db
3eb877ab6d9aba74c63acfc7d9dfe83fe77195ba
/google-cloud-sdk/lib/surface/ml_engine/jobs/submit/prediction.py
d52be0ef85b211bb64b18800ceedb849e00afd71
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Gilolume/HeuApplication
cd65267e6171277fc50f31a582b6ff6634758209
e48c68ba9bc4f952b7bd5a0ba47f4c810ed56812
refs/heads/master
2022-11-25T06:18:47.892562
2017-11-24T09:21:16
2017-11-24T09:21:16
104,208,662
0
1
null
2020-07-25T12:32:09
2017-09-20T11:47:10
Python
UTF-8
Python
false
false
4,458
py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ml-engine jobs submit batch prediction command.""" from googlecloudsdk.api_lib.ml_engine import jobs from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.ml_engine import flags from googlecloudsdk.command_lib.ml_engine import jobs_util _TF_RECORD_URL = ('https://www.tensorflow.org/versions/r0.12/how_tos/' 'reading_data/index.html#file-formats') def _AddSubmitPredictionArgs(parser): """Add arguments for `jobs submit prediction` command.""" parser.add_argument('job', help='Name of the batch prediction job.') model_group = parser.add_mutually_exclusive_group(required=True) model_group.add_argument( '--model-dir', help=('Google Cloud Storage location where ' 'the model files are located.')) model_group.add_argument( '--model', help='Name of the model to use for prediction.') parser.add_argument( '--version', help="""\ Model version to be used. This flag may only be given if --model is specified. If unspecified, the default version of the model will be used. To list versions for a model, run $ gcloud ml-engine versions list """) # input location is a repeated field. parser.add_argument( '--input-paths', type=arg_parsers.ArgList(min_length=1), required=True, metavar='INPUT_PATH', help="""\ Google Cloud Storage paths to the instances to run prediction on. Wildcards (```*```) accepted at the *end* of a path. More than one path can be specified if multiple file patterns are needed. For example, gs://my-bucket/instances*,gs://my-bucket/other-instances1 will match any objects whose names start with `instances` in `my-bucket` as well as the `other-instances1` bucket, while gs://my-bucket/instance-dir/* will match any objects in the `instance-dir` "directory" (since directories aren't a first-class Cloud Storage concept) of `my-bucket`. """) parser.add_argument( '--data-format', required=True, choices={ 'TEXT': ('Text files with instances separated by the new-line ' 'character.'), 'TF_RECORD': 'TFRecord files; see {}'.format(_TF_RECORD_URL), 'TF_RECORD_GZIP': 'GZIP-compressed TFRecord files.' }, help='Data format of the input files.') parser.add_argument( '--output-path', required=True, help='Google Cloud Storage path to which to save the output. ' 'Example: gs://my-bucket/output.') parser.add_argument( '--region', required=True, help='The Google Compute Engine region to run the job in.') parser.add_argument( '--max-worker-count', required=False, type=int, help=('The maximum number of workers to be used for parallel processing. ' 'Defaults to 10 if not specified.')) parser.add_argument( '--batch-size', required=False, type=int, help=('The number of records per batch. The service will buffer ' 'batch_size number of records in memory before invoking TensorFlow.' ' Defaults to 64 if not specified.')) flags.RUNTIME_VERSION.AddToParser(parser) class Prediction(base.Command): """Start a Cloud ML Engine batch prediction job.""" @staticmethod def Args(parser): _AddSubmitPredictionArgs(parser) parser.display_info.AddFormat(jobs_util.JOB_FORMAT) def Run(self, args): return jobs_util.SubmitPrediction( jobs.JobsClient(), args.job, model_dir=args.model_dir, model=args.model, version=args.version, input_paths=args.input_paths, data_format=args.data_format, output_path=args.output_path, region=args.region, runtime_version=args.runtime_version, max_worker_count=args.max_worker_count, batch_size=args.batch_size)
[ "jeremy.debelleix@gmail.com" ]
jeremy.debelleix@gmail.com
ab753027171ce8d0b51aa099be22fa8d5959a81c
282d0a84b45b12359b96bbf0b1d7ca9ee0cb5d19
/Malware1/venv/Lib/site-packages/scipy/stats/__init__.py
322018470481aef44a285731378b7f70f0fe8bf2
[]
no_license
sameerakhtar/CyberSecurity
9cfe58df98495eac6e4e2708e34e70b7e4c055d3
594973df27b4e1a43f8faba0140ce7d6c6618f93
refs/heads/master
2022-12-11T11:53:40.875462
2020-09-07T23:13:22
2020-09-07T23:13:22
293,598,094
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:9ad28cc455004e21eba19c1b3b1666198544f7d90cb91815a5e8defe7796e6f1 size 9929
[ "46763165+sameerakhtar@users.noreply.github.com" ]
46763165+sameerakhtar@users.noreply.github.com
8795bb7db926a366167eecf4133dd3008994e40e
a60a3f718cbf8828ed510918f667332f14f49433
/phys_math/numerical_differentiation/finite_diff.py
3f0f3999726342721954fd74c8304dd8c8fce123
[]
no_license
Christopher-Bradshaw/learning
c2c8c453c02bba4584787cc50320d111b16cdb77
34c58a6313090c934eab3ff07d6973ddccae89ee
refs/heads/master
2022-08-24T08:23:21.616268
2022-08-04T05:55:46
2022-08-04T05:55:46
156,060,869
0
0
null
2019-09-10T21:17:12
2018-11-04T07:56:15
Jupyter Notebook
UTF-8
Python
false
false
942
py
# The func below might be better def finite_diff(f, *args): eps = 1 while eps > 1e-30: diff = ( f(*[args[i] + eps * (i == 0) for i in range(len(args))]) - f(*[args[i] - eps * (i == 0) for i in range(len(args))]) ) if diff < 1e-5: return diff/(2*eps) eps /= 2 raise Exception("No converge! Function varies too rapidly.") # import math # # See Numerical Optimization Nocedal and Wright chapter 8 or # # https://math.stackexchange.com/questions/815113/is-there-a-general-formula-for-estimating-the-step-size-h-in-numerical-different # def finite_diff(f, *args): # ulp = 1e-53 # eps = args[0] * math.sqrt(ulp) # diff = ( # f(*[args[i] + eps * (i == 0) for i in range(len(args))]) - # f(*[args[i] - eps * (i == 0) for i in range(len(args))]) # ) # return diff/(2*eps) print(finite_diff(lambda x1: x1**3, 2))
[ "christopher.peter.bradshaw+github@gmail.com" ]
christopher.peter.bradshaw+github@gmail.com
ff67de3642d9ca62920ad2baf257ab1c2bea578d
96dcea595e7c16cec07b3f649afd65f3660a0bad
/tests/components/flux_led/test_switch.py
cb0034f8d36b191a4bee3150bece882e5bd71b85
[ "Apache-2.0" ]
permissive
home-assistant/core
3455eac2e9d925c92d30178643b1aaccf3a6484f
80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743
refs/heads/dev
2023-08-31T15:41:06.299469
2023-08-31T14:50:53
2023-08-31T14:50:53
12,888,993
35,501
20,617
Apache-2.0
2023-09-14T21:50:15
2013-09-17T07:29:48
Python
UTF-8
Python
false
false
6,901
py
"""Tests for switch platform.""" from flux_led.const import MODE_MUSIC from homeassistant.components import flux_led from homeassistant.components.flux_led.const import ( CONF_REMOTE_ACCESS_ENABLED, CONF_REMOTE_ACCESS_HOST, CONF_REMOTE_ACCESS_PORT, DOMAIN, ) from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, CONF_HOST, CONF_NAME, STATE_OFF, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from homeassistant.setup import async_setup_component from . import ( DEFAULT_ENTRY_TITLE, IP_ADDRESS, MAC_ADDRESS, _mocked_bulb, _mocked_switch, _patch_discovery, _patch_wifibulb, async_mock_device_turn_off, async_mock_device_turn_on, ) from tests.common import MockConfigEntry async def test_switch_on_off(hass: HomeAssistant) -> None: """Test a smart plug.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE}, unique_id=MAC_ADDRESS, ) config_entry.add_to_hass(hass) switch = _mocked_switch() with _patch_discovery(), _patch_wifibulb(device=switch): await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}}) await hass.async_block_till_done() entity_id = "switch.bulb_rgbcw_ddeeff" state = hass.states.get(entity_id) assert state.state == STATE_ON await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True ) switch.async_turn_off.assert_called_once() await async_mock_device_turn_off(hass, switch) assert hass.states.get(entity_id).state == STATE_OFF await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True ) switch.async_turn_on.assert_called_once() switch.async_turn_on.reset_mock() await async_mock_device_turn_on(hass, switch) assert hass.states.get(entity_id).state == STATE_ON async def test_remote_access_unique_id(hass: HomeAssistant) -> None: """Test a remote access switch unique id.""" config_entry = MockConfigEntry( domain=DOMAIN, data={ CONF_REMOTE_ACCESS_HOST: "any", CONF_REMOTE_ACCESS_ENABLED: True, CONF_REMOTE_ACCESS_PORT: 1234, CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE, }, unique_id=MAC_ADDRESS, ) config_entry.add_to_hass(hass) bulb = _mocked_bulb() with _patch_discovery(), _patch_wifibulb(device=bulb): await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}}) await hass.async_block_till_done() entity_id = "switch.bulb_rgbcw_ddeeff_remote_access" entity_registry = er.async_get(hass) assert ( entity_registry.async_get(entity_id).unique_id == f"{MAC_ADDRESS}_remote_access" ) async def test_effects_speed_unique_id_no_discovery(hass: HomeAssistant) -> None: """Test a remote access switch unique id when discovery fails.""" config_entry = MockConfigEntry( domain=DOMAIN, data={ CONF_REMOTE_ACCESS_HOST: "any", CONF_REMOTE_ACCESS_ENABLED: True, CONF_REMOTE_ACCESS_PORT: 1234, CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE, }, ) config_entry.add_to_hass(hass) bulb = _mocked_bulb() with _patch_discovery(no_device=True), _patch_wifibulb(device=bulb): await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}}) await hass.async_block_till_done() entity_id = "switch.bulb_rgbcw_ddeeff_remote_access" entity_registry = er.async_get(hass) assert ( entity_registry.async_get(entity_id).unique_id == f"{config_entry.entry_id}_remote_access" ) async def test_remote_access_on_off(hass: HomeAssistant) -> None: """Test enable/disable remote access.""" config_entry = MockConfigEntry( domain=DOMAIN, data={ CONF_REMOTE_ACCESS_HOST: "any", CONF_REMOTE_ACCESS_ENABLED: True, CONF_REMOTE_ACCESS_PORT: 1234, CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE, }, unique_id=MAC_ADDRESS, ) config_entry.add_to_hass(hass) bulb = _mocked_bulb() with _patch_discovery(), _patch_wifibulb(bulb): await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}}) await hass.async_block_till_done() entity_id = "switch.bulb_rgbcw_ddeeff_remote_access" state = hass.states.get(entity_id) assert state.state == STATE_ON await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True ) bulb.async_disable_remote_access.assert_called_once() assert hass.states.get(entity_id).state == STATE_OFF assert config_entry.data[CONF_REMOTE_ACCESS_ENABLED] is False await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True ) bulb.async_enable_remote_access.assert_called_once() assert hass.states.get(entity_id).state == STATE_ON assert config_entry.data[CONF_REMOTE_ACCESS_ENABLED] is True async def test_music_mode_switch(hass: HomeAssistant) -> None: """Test music mode switch.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: IP_ADDRESS, CONF_NAME: DEFAULT_ENTRY_TITLE}, unique_id=MAC_ADDRESS, ) config_entry.add_to_hass(hass) bulb = _mocked_bulb() bulb.raw_state = bulb.raw_state._replace(model_num=0xA3) # has music mode bulb.microphone = True with _patch_discovery(), _patch_wifibulb(device=bulb): await async_setup_component(hass, flux_led.DOMAIN, {flux_led.DOMAIN: {}}) await hass.async_block_till_done() entity_id = "switch.bulb_rgbcw_ddeeff_music" assert hass.states.get(entity_id).state == STATE_OFF bulb.effect = MODE_MUSIC bulb.is_on = False await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True ) bulb.async_set_music_mode.assert_called_once() assert hass.states.get(entity_id).state == STATE_OFF bulb.async_set_music_mode.reset_mock() bulb.is_on = True await hass.services.async_call( SWITCH_DOMAIN, "turn_on", {ATTR_ENTITY_ID: entity_id}, blocking=True ) bulb.async_set_music_mode.assert_called_once() assert hass.states.get(entity_id).state == STATE_ON bulb.effect = None await hass.services.async_call( SWITCH_DOMAIN, "turn_off", {ATTR_ENTITY_ID: entity_id}, blocking=True ) bulb.async_set_levels.assert_called_once() assert hass.states.get(entity_id).state == STATE_OFF
[ "noreply@github.com" ]
home-assistant.noreply@github.com
00a86c01113de79d1c176f7ebc800cd5aebf42f2
922d5487bc18dd4d044d41d6b81cd14eb952c591
/build/Part_5/irb120/irb120_planner/catkin_generated/pkg.installspace.context.pc.py
fa5af0c018f3ed132ee5aaba7d45dc290247085a
[]
no_license
hanbincho/ros_ws
21b747f115cee85a3b8a578028ac44e069721c31
d92feebd845a69bb8535e8c48592caf2b94d6497
refs/heads/master
2020-04-02T15:45:16.395227
2018-11-07T04:09:07
2018-11-07T04:09:07
149,820,985
0
0
null
null
null
null
UTF-8
Python
false
false
467
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "roscpp;generic_cartesian_planner;fk_ik_virtual;irb120_fk_ik;xform_utils;arm_motion_interface".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "irb120_planner" PROJECT_SPACE_DIR = "/home/hanbin/ros_ws/install" PROJECT_VERSION = "0.0.0"
[ "hxc431@case.edu" ]
hxc431@case.edu
9f240f0de70cda605f740a222529faad3ae13b4b
5c60941cfe9b163ec283c1615cf2e1ca53e885c2
/demo/irc/dccbot.py
f44f0c4537266c77d5f53f07b39851dfc2a87f16
[ "MIT" ]
permissive
ghostlyman/untwisted
25bac2ed1c53e74eed38995b0c30efc7e3e0fa7e
92cd47512c52ebfa02f57898df72e29627034efc
refs/heads/master
2021-01-11T14:45:14.839599
2016-05-04T22:45:23
2016-05-04T22:45:23
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,149
py
""" """ # We import the basic modules. from untwisted.network import * from untwisted.iostd import * from untwisted.splits import Terminator, logcon from untwisted.tools import coroutine from untwisted.plugins.irc import * from socket import * from os.path import getsize, isfile ADDRESS = 'irc.freenode.org' PORT = 6667 NICK = 'uxirc' USER = 'uxirc uxirc uxirc :uxirc' # The folder where we will be serving files. FOLDER = '/home/tau/Downloads' @coroutine def get_myaddr(con, prefix, nick, msg): send_cmd(con, 'userhost %s' % nick) args = yield con, '302' _, _, ident = args user, myaddr = ident.split('@') con.myaddr = myaddr def setup(con): Stdin(con) Stdout(con) Terminator(con) Irc(con) CTCP(con) xmap(con, 'PING', lambda con, prefix, servaddr: send_cmd(con, 'PONG :%s' % servaddr)) xmap(con, '376', lambda con, *args: send_cmd(con, 'JOIN #ameliabot')) xmap(con, 'PRIVMSG', send_file) xmap(con, 'DCC SEND', check_file_existence) xmap(con, '376', get_myaddr) xmap(con, CLOSE, lambda con, err: lose(con)) logcon(con) send_cmd(con, 'NICK %s' % NICK) send_cmd(con, 'USER %s' % USER) def main(): sock = socket(AF_INET, SOCK_STREAM) con = Spin(sock) Client(con) con.connect_ex((ADDRESS, PORT)) xmap(con, CONNECT, setup) def send_file(con, nick, user, host, target, msg): if not msg.startswith('.send'): return cmd, filename, port = msg.split(' ') resource = '%s/%s' % (FOLDER, filename) size = getsize(resource) fd = open(resource, 'rb') def is_done(msg): send_msg(con, nick, msg) fd.close() try: dcc = DccServer(fd, int(port), timeout=50) except Exception: is_done('Couldnt list on the port!') raise xmap(dcc, DONE, lambda *args: is_done('Done.')) xmap(dcc, CLOSE, lambda *args: is_done('Failed!')) xmap(dcc, ACCEPT_ERR, lambda *args: is_done("Accept error!")) xmap(dcc, TIMEOUT, lambda *args: is_done('TIMEOUT!')) HEADER = '\001DCC SEND %s %s %s %s\001' request = HEADER % (filename, ip_to_long(con.myaddr), port, size) send_msg(con, nick, request) def check_file_existence(con, (nick, user, host, target, msg), filename, address, port, size): resource = '%s/%s' % (FOLDER, filename) if isfile(resource): send_msg(con, nick, 'File already exists.') else: recv_file(con, nick, resource, address, port, size) def recv_file(con, nick, resource, address, port, size): fd = open(resource, 'wb') dcc = DccClient(long_to_ip(int(address)), int(port), fd, int(size)) def is_done(msg): send_msg(con, nick, msg) fd.close() xmap(dcc, DONE, lambda *args: is_done('Done!')) xmap(dcc, CLOSE, lambda *args: is_done('Failed!')) xmap(dcc, CONNECT_ERR, lambda *args: is_done("It couldn't connect!")) if __name__ == '__main__': # import argparser # parser = argparser.ArgumentParser() main() core.gear.mainloop()
[ "ioliveira.id.uff.br" ]
ioliveira.id.uff.br
57aebb71ab95073cbca32e46faf2cb866680e256
54b666acabd9e8dbca56fe842b7d0eccb243bff7
/modules/main.py
ac3dac08defef04d1a58f9efac059d8932df4b36
[]
no_license
sambapython/batch56
618c198acb7d75a804ac09477d6c0ee3e661d1c9
fda93d2c600b489a65c808cf88baf3a15cb31785
refs/heads/master
2020-04-27T15:41:30.933519
2019-04-14T04:53:27
2019-04-14T04:53:27
174,455,903
1
0
null
null
null
null
UTF-8
Python
false
false
402
py
''' import sys sys.path.append("/home/khyaathipython/") print(sys.path) import sales import pur ''' ''' sales.create_customer() print(sales.a) print(sales.b) print(sales.c) res=sales.add(10,20) print(res) ''' ''' import mod1 ''' ''' from mod1 import file1,file2 file1.fun() file2.fun() ''' ''' import mod1 mod1.file1.fun() ''' ''' from mod1.mod1_1 import in_1 in_1.fun() ''' # if __name__ == "__main__"
[ "sambapython@gmail.com" ]
sambapython@gmail.com
d06f862750984cf6327fddb6a9b5ff6eb1981d07
5f1c3a2930b20c3847496a249692dc8d98f87eee
/Pandas/DataSeries/Question7.py
b7cb329d9299cf3764f164a04da73f85a860072a
[]
no_license
AmbyMbayi/CODE_py
c572e10673ba437d06ec0f2ae16022d7cbe21d1c
5369abf21a8db1b54a5be6cbd49432c7d7775687
refs/heads/master
2020-04-24T05:01:46.277759
2019-02-22T08:26:04
2019-02-22T08:26:04
171,723,155
0
0
null
null
null
null
UTF-8
Python
false
false
290
py
"""write a python pandss to change the dta type of given column or series""" import pandas as pd s1 = pd.Series(['100', '200', 'python', '300.2','400']) print("original data series") print(s1) print("Change the said data type to numeric") s2 = pd.to_numeric(s1, errors='coerce') print(s2)
[ "root@localhost.localdomain" ]
root@localhost.localdomain
1913fde03738b7c32446ab5969a788192995a5d6
503437b96f7b6179ea848ae6748c468c89fd38f5
/accounts/migrations/0002_auto_20160929_1759.py
bb123bf4960dfb24d40766e6a2cabf8c29abc9c2
[]
no_license
HugOoOguH/blog
049cfd73fcb5e6b906baf65b743b2b5d35f98387
ace8ff1541023f02666f8ef8f5c72a9be444d51f
refs/heads/master
2021-01-24T09:56:45.107125
2016-09-30T16:16:10
2016-09-30T16:16:10
69,678,541
0
0
null
null
null
null
UTF-8
Python
false
false
450
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-29 17:59 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0001_initial'), ] operations = [ migrations.AlterField( model_name='profile', name='age', field=models.IntegerField(blank=True, null=True), ), ]
[ "hugo-ensc@outlook.com" ]
hugo-ensc@outlook.com
ae23a301db17c66822f1a23006e53e537ddece28
0f1e9b16f60a062c4ee18f39de6e5d7c163afaa8
/src/modules/token_embedders/pretrained_transformer_mismatched_embedder.py
26332d8ab69efc607c686f65dc59d9b6ac0bf869
[]
no_license
Chung-I/maml-parsing
01604553ab1f376d5780b5bea6acf7463db65d8b
368a0300bc8def0595a24ae93b1af53ebd8d7dc5
refs/heads/master
2023-06-27T11:20:22.273868
2020-10-28T11:50:53
2020-10-28T11:50:53
241,025,505
2
0
null
2023-06-12T21:27:57
2020-02-17T05:17:12
Python
UTF-8
Python
false
false
4,711
py
from typing import Optional from overrides import overrides import torch from allennlp.modules.token_embedders import TokenEmbedder from allennlp.nn import util from src.modules.token_embedders import PretrainedTransformerEmbedder @TokenEmbedder.register("transformer_pretrained_mismatched") class PretrainedTransformerMismatchedEmbedder(TokenEmbedder): """ Use this embedder to embed wordpieces given by `PretrainedTransformerMismatchedIndexer` and to pool the resulting vectors to get word-level representations. # Parameters model_name : `str` The name of the `transformers` model to use. Should be the same as the corresponding `PretrainedTransformerMismatchedIndexer`. max_length : `int`, optional (default = None) If positive, folds input token IDs into multiple segments of this length, pass them through the transformer model independently, and concatenate the final representations. Should be set to the same value as the `max_length` option on the `PretrainedTransformerMismatchedIndexer`. """ def __init__( self, model_name: str, max_length: int = None, requires_grad: bool = True, layer_dropout: float = 0.0, bert_dropout: float = 0.0, dropout: float = 0.0, combine_layers: str = "mix", adapter_size: int = 8, ft_layernorm: bool = False, pretrained: bool = True, lang_file: str = None, mean_affix: str = None, lang_norm: bool = False, batch_norm: bool = False, inherit_bn: bool = False, lang_norm_affine: bool = True, ) -> None: super().__init__() # The matched version v.s. mismatched self._matched_embedder = PretrainedTransformerEmbedder( model_name, max_length=max_length, requires_grad=requires_grad, layer_dropout=layer_dropout, bert_dropout=bert_dropout, dropout=dropout, combine_layers=combine_layers, adapter_size=adapter_size, ft_layernorm=ft_layernorm, pretrained=pretrained, lang_file=lang_file, mean_affix=mean_affix, lang_norm=lang_norm, batch_norm=batch_norm, inherit_bn=inherit_bn, lang_norm_affine=lang_norm_affine, ) @overrides def get_output_dim(self): return self._matched_embedder.get_output_dim() @overrides def forward( self, token_ids: torch.LongTensor, mask: torch.LongTensor, offsets: torch.LongTensor, wordpiece_mask: torch.LongTensor, type_ids: Optional[torch.LongTensor] = None, segment_concat_mask: Optional[torch.LongTensor] = None, lang: Optional[str] = None, ) -> torch.Tensor: # type: ignore """ # Parameters token_ids: torch.LongTensor Shape: [batch_size, num_wordpieces] (for exception see `PretrainedTransformerEmbedder`). mask: torch.LongTensor Shape: [batch_size, num_orig_tokens]. offsets: torch.LongTensor Shape: [batch_size, num_orig_tokens, 2]. Maps indices for the original tokens, i.e. those given as input to the indexer, to a span in token_ids. `token_ids[i][offsets[i][j][0]:offsets[i][j][1] + 1]` corresponds to the original j-th token from the i-th batch. wordpiece_mask: torch.LongTensor Shape: [batch_size, num_wordpieces]. type_ids: Optional[torch.LongTensor] Shape: [batch_size, num_wordpieces]. segment_concat_mask: Optional[torch.LongTensor] See `PretrainedTransformerEmbedder`. # Returns: Shape: [batch_size, num_orig_tokens, embedding_size]. """ # Shape: [batch_size, num_wordpieces, embedding_size]. embeddings = self._matched_embedder( token_ids, wordpiece_mask, type_ids=type_ids, segment_concat_mask=segment_concat_mask, lang=lang, ) # span_embeddings: (batch_size, num_orig_tokens, max_span_length, embedding_size) # span_mask: (batch_size, num_orig_tokens, max_span_length) span_embeddings, span_mask = util.batched_span_select(embeddings.contiguous(), offsets) span_mask = span_mask.unsqueeze(-1) span_embeddings *= span_mask # zero out paddings span_embeddings_sum = span_embeddings.sum(2) span_embeddings_len = span_mask.sum(2) # Shape: (batch_size, num_orig_tokens, embedding_size) orig_embeddings = span_embeddings_sum / span_embeddings_len return orig_embeddings
[ "leon129506@gmail.com" ]
leon129506@gmail.com
0a32ee0edb9239f8ed14e608e551d8f818304744
8bd6b0784de9a1e6a39d0f5f23f2d8fb50c73d49
/MethodRefine-Rand/logistics/MethodRefine/logistics_benchmark-mid/training/training_16.py
ed8e340c60a63d93af46d76f5e74548b8bda9ee3
[]
no_license
sysulic/MethodRefine
a483d74e65337dff4bc2539ce3caa3bf83748b48
adbb22d4663041d853d3132f75032b7561bf605c
refs/heads/master
2020-09-14T10:45:55.948174
2020-05-01T09:13:59
2020-05-01T09:13:59
223,104,986
3
2
null
2020-04-27T11:01:36
2019-11-21T06:33:16
Python
UTF-8
Python
false
false
1,395
py
#!/usr/bin/env python # coding=utf-8 import sys sys.path.insert(0, './') from logistic import * import new_tihtn_planner state0 = new_tihtn_planner.State('state0') allow = True state0.loc = {'truck1':('city1','loc2'),'truck2':('city2','loc2'),'truck3':('city3','loc1'),'truck4':('city4','loc2'),'truck5':('city5','loc2'),'plane1':('city5','loc1'),'pkg1':('city1','loc1'),'pkg2':('city1','loc2'),'pkg3':('city4','loc1'),} state0.load = {'truck1':False,'truck2':False,'truck3':False,'truck4':False,'truck5':False,'plane1':False,} state0.plane_nums = 1 new_tihtn_planner.declare_types({'location':[('city1','loc1'),('city1','loc2'),('city2','loc1'),('city2','loc2'),('city3','loc1'),('city3','loc2'),('city4','loc1'),('city4','loc2'),('city5','loc1'),('city5','loc2'),],'truck':['truck1','truck2','truck3','truck4','truck5',],'plane':['plane1',],'pkg':['pkg1','pkg2','pkg3',]}) new_tihtn_planner.declare_funs({load_plane:['pkg', 'location', 'plane'],load_truck:['pkg', 'location', 'truck'],by_plane:['plane', 'location'],drive_truck:['truck', 'location'], unload_truck:['pkg', 'location', 'truck'],unload_plane:['pkg', 'location', 'plane']}) new_tihtn_planner.instance() def execute(completable): return new_tihtn_planner.pyhop(completable, allow, state0,[('delievery','pkg1',('city5','loc2')),('delievery','pkg2',('city5','loc1')),('delievery','pkg3',('city1','loc2')),],[[0, 1],[1, 2],], 9)
[ "526552330@qq.com" ]
526552330@qq.com
0b69665b7733a16cbc3122ec3750240d0fc83638
913110006f5f6ff03ccd2cb4bbe205ffa51a2910
/py_scripts/tools/bin.py
b6b6f3755d2d05a40412619008759f749f50c7f5
[]
no_license
jonathaw/fleishman_pymol
ce8f464295ba77ac1118dfbe715194e827b2af9d
d54ce690aa94e13c15c02394dbb8423d124068fa
refs/heads/master
2020-05-17T08:43:08.029264
2017-10-24T10:17:57
2017-10-24T10:17:57
29,957,610
0
2
null
2015-02-19T16:37:43
2015-01-28T08:24:14
Python
UTF-8
Python
false
false
1,422
py
#!/usr/bin/python __author__ = ['Andrew Wollacott (amw215@u.washington.edu)'] __version__ = "Revision 0.1" import string, sys, os from optparse import OptionParser def main(): """ creates sets of directories and fills them with files from a list """ parser = OptionParser() parser.add_option("-l", dest="list", help="list of files") parser.add_option("-b", dest="nper", help="number per bin") parser.add_option("-n", dest="name", help="base name") parser.add_option("-p", dest="nbin", help="number of bins") parser.set_description(main.__doc__) (options, args) = parser.parse_args() if options.list == None: parser.print_help() name = "set" if options.name != None: name = options.name try: PDBLIST = open(options.list) except: print "unable to open list" sys.exit() files = [] for file in PDBLIST.readlines(): file = string.strip(file) files.append(file) if len(files) == 0: sys.exit() nper = 0 if options.nper: nper = int(options.nper) elif options.nbin != None: nper = int(len(files)/int(options.nbin))+1 else: parser.print_help() sys.exit() nsets = 0 mydir = name + str(nsets) count = 0 os.system("mkdir " + mydir) for file in files: if count == nper: nsets += 1 mydir = name + str(nsets) os.system("mkdir " + mydir) count = 0 move = "mv " + file + " " + mydir os.system(move) count += 1 if __name__ == "__main__": main()
[ "jonathan.weinstein@weizmann.ac.il" ]
jonathan.weinstein@weizmann.ac.il
47d2b4e414e23014afe9e3503bc3d4395142d38d
0c7ff0ec35ba2bb38f99ef6ecb261ec33466dd52
/Day3/treasure-island.py
023fd21f334872bb24f6c463299676f136fb471b
[]
no_license
TheKinshu/100-Days-Python
15cbacc608ee349cc9733a7032e10a359bebb731
293ad6b3e5f5208da84efbc5b2d2d395a5a53421
refs/heads/master
2023-04-18T08:21:30.361800
2021-05-02T18:48:39
2021-05-02T18:48:39
351,582,416
0
0
null
null
null
null
UTF-8
Python
false
false
3,233
py
def decision(word): dec = input(word) return dec.lower() print(''' ******************************************************************************* | | | | _________|________________.=""_;=.______________|_____________________|_______ | | ,-"_,="" `"=.| | |___________________|__"=._o`"-._ `"=.______________|___________________ | `"=._o`"=._ _`"=._ | _________|_____________________:=._o "=._."_.-="'"=.__________________|_______ | | __.--" , ; `"=._o." ,-"""-._ ". | |___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________ | |o`"=._` , "` `; .". , "-._"-._; ; | _________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______ | | |o; `"-.o`"=._`` '` " ,__.--o; | |___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________ ____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____ /______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_ ____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____ /______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_ ____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____ /______/______/______/______/______/______/______/______/______/______/_____ / ******************************************************************************* ''') print("Welcome to Treasure Island.") print("Your mission is to find the treasure.") while(True): choice = decision('You\'re at a cross road. Where do you want to go? Type "left" or right ') if choice == 'right': print("There it was a dead end, you inspect further but end up falling into a hole.\nGame Over.") break elif choice == 'left': choice = decision('You arrive at a river, the water current is very quick it will be hard to cross the river. What will you do? Type "swim" or "wait" ') if choice == 'swim': print("You try to swim across the river but the current was too fast, and you got swept away.\nGame Over.") break elif choice == 'wait': choice = decision('You decided to wait as the current is very fast and would have swept you away.\nYou spotted a in a distant coming towards you, the boat stopped right infront of you. What will you do? Type "aboard" "wait" "run" ') if not (choice == 'aboard'): print("Out of no-where tiger jumps out from the side and attacked you.\nGame Over.") break elif choice == 'aboard': print("You aboarded the ship, but there was no one. You look around to see if you can find anything worth taking. You approached a door and open it and found yourself treasure.\nYou win!") break #https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26export%3Ddownload
[ "kc007919@gmail.com" ]
kc007919@gmail.com
ea8aa7869c523afcdbcb222b2ea4ba45c034a82a
e74e89592d8a3b1a0b465a7b1595708b224362d2
/pset_challenging_ext/exercises/p59.py
7e935b02730f8610aec024c02e5ec363318f2fac
[ "MIT" ]
permissive
mottaquikarim/pydev-psets
016f60f1e9d9a534bd9a66ecde8eb412beee37d1
9749e0d216ee0a5c586d0d3013ef481cc21dee27
refs/heads/master
2023-01-10T11:15:57.041287
2021-06-07T23:38:34
2021-06-07T23:38:34
178,547,933
5
2
MIT
2023-01-03T22:28:27
2019-03-30T11:09:08
Jupyter Notebook
UTF-8
Python
false
false
740
py
""" Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. """ """Question: Assuming that we have some email addresses in the "username@companyname.com" format, please write program to print the company name of a given email address. Both user names and company names are composed of letters only. Example: If the following email address is given as input to the program: john@google.com Then, the output of the program should be: google In case of input data being supplied to the question, it should be assumed to be a console input. Hints: Use \w to match letters. """
[ "taqqui.karim@gmail.com" ]
taqqui.karim@gmail.com
0b1438b5c62ed9d4a3e106deef874b757206b26e
1a2ca64839723ede3134a0781128b0dc0b5f6ab8
/ExtractFeatures/Data/mrafayaleem/test_bufferedhttp.py
02de8eff183fe95de81737109da48ce8bd4c05b6
[]
no_license
vivekaxl/LexisNexis
bc8ee0b92ae95a200c41bd077082212243ee248c
5fa3a818c3d41bd9c3eb25122e1d376c8910269c
refs/heads/master
2021-01-13T01:44:41.814348
2015-07-08T15:42:35
2015-07-08T15:42:35
29,705,371
9
3
null
null
null
null
UTF-8
Python
false
false
3,870
py
# Copyright (c) 2010-2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from eventlet import spawn, Timeout, listen from swift.common import bufferedhttp class TestBufferedHTTP(unittest.TestCase): def test_http_connect(self): bindsock = listen(('127.0.0.1', 0)) def accept(expected_par): try: with Timeout(3): sock, addr = bindsock.accept() fp = sock.makefile() fp.write('HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\n' 'RESPONSE') fp.flush() self.assertEquals(fp.readline(), 'PUT /dev/%s/path/..%%25/?omg&no=%%7f HTTP/1.1\r\n' % expected_par) headers = {} line = fp.readline() while line and line != '\r\n': headers[line.split(':')[0].lower()] = \ line.split(':')[1].strip() line = fp.readline() self.assertEquals(headers['content-length'], '7') self.assertEquals(headers['x-header'], 'value') self.assertEquals(fp.readline(), 'REQUEST\r\n') except BaseException, err: return err return None for par in ('par', 1357): event = spawn(accept, par) try: with Timeout(3): conn = bufferedhttp.http_connect('127.0.0.1', bindsock.getsockname()[1], 'dev', par, 'PUT', '/path/..%/', {'content-length': 7, 'x-header': 'value'}, query_string='omg&no=%7f') conn.send('REQUEST\r\n') resp = conn.getresponse() body = resp.read() conn.close() self.assertEquals(resp.status, 200) self.assertEquals(resp.reason, 'OK') self.assertEquals(body, 'RESPONSE') finally: err = event.wait() if err: raise Exception(err) def test_nonstr_header_values(self): class MockHTTPSConnection(object): def __init__(self, hostport): pass def putrequest(self, method, path, skip_host=0): pass def putheader(self, header, *values): # Essentially what Python 2.7 does that caused us problems. '\r\n\t'.join(values) def endheaders(self): pass origHTTPSConnection = bufferedhttp.HTTPSConnection bufferedhttp.HTTPSConnection = MockHTTPSConnection try: bufferedhttp.http_connect('127.0.0.1', 8080, 'sda', 1, 'GET', '/', headers={'x-one': '1', 'x-two': 2, 'x-three': 3.0, 'x-four': {'crazy': 'value'}}, ssl=True) bufferedhttp.http_connect_raw('127.0.0.1', 8080, 'GET', '/', headers={'x-one': '1', 'x-two': 2, 'x-three': 3.0, 'x-four': {'crazy': 'value'}}, ssl=True) finally: bufferedhttp.HTTPSConnection = origHTTPSConnection if __name__ == '__main__': unittest.main()
[ "vivekaxl@gmail.com" ]
vivekaxl@gmail.com
3ef110c9114daee068bc72b504cea4b5f7057017
ca47672d0cbcf7d82d89ca93ef193a5415d782d8
/office365/sharepoint/list_data_service.py
a211d361a61c023ff756021e7d519fcbff600f9b
[ "MIT" ]
permissive
eperegudov/Office365-REST-Python-Client
2980c6d6a4003bf43f547d8c97786e09afb0dcaf
2a2efac58d9882ad30bc20b2410c57aa4aac6739
refs/heads/master
2023-04-28T17:49:38.915377
2019-11-14T10:04:32
2019-11-14T10:04:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,522
py
from office365.runtime.action_type import ActionType from office365.runtime.client_query import ClientQuery from office365.runtime.client_runtime_context import ClientRuntimeContext from office365.runtime.odata.json_light_format import JsonLightFormat from office365.runtime.odata.odata_metadata_level import ODataMetadataLevel from office365.runtime.resource_path_service_operation import ResourcePathServiceOperation from office365.sharepoint.listitem import ListItem class ListDataService(ClientRuntimeContext): """SharePoint 2010 list data service""" def __init__(self, base_url, auth_context): if base_url.endswith("/"): base_url = base_url[:len(base_url) - 1] super(ListDataService, self).__init__(base_url + "/_vti_bin/listdata.svc/", auth_context) self.json_format = JsonLightFormat(ODataMetadataLevel.Verbose) def get_list_item(self, list_name, item_id): return ListItem(self, ResourcePathServiceOperation(self, None, list_name, [item_id])) def delete_list_item(self, list_name, item_id): resource_url = self.service_root_url + list_name + "(" + str(item_id) + ")" qry = ClientQuery(resource_url, ActionType.DeleteEntity) self.add_query(qry) def update_list_item(self, list_name, item_id, field_values): resource_url = self.service_root_url + list_name + "(" + str(item_id) + ")" qry = ClientQuery(resource_url, ActionType.UpdateEntity, field_values) self.add_query(qry)
[ "vvgrem@gmail.com" ]
vvgrem@gmail.com
7d0cdbfe58969765ac139b97341aa051db94e112
f4fdb0c1213bbb403b87c2dbbde390918ac08861
/generate_pos.py
7b1d1a80327e86d0d38228b29050c379a2bb8e56
[]
no_license
benwing2/RuNounChanges
0d5076e576237f10b50049ed52b91f96c95cca95
048dfed5abe09b8d5629c5772292027ce0a170f2
refs/heads/master
2023-09-03T22:48:06.972127
2023-09-03T06:27:56
2023-09-03T06:27:56
41,480,942
3
0
null
null
null
null
UTF-8
Python
false
false
7,205
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re class Peeker: __slots__ = ['lineiter', 'next_lines'] def __init__(self, lineiter): self.lineiter = lineiter self.next_lines = [] self.lineno = 0 def peek_next_line(self, n): while len(self.next_lines) < n + 1: try: self.next_lines.append(next(self.lineiter)) except StopIteration: # print("peek_next_line(%s): return None" % n) return None # print("peek_next_line(%s): return %s" % (n, self.next_lines[n])) return self.next_lines[n] def get_next_line(self): if len(self.next_lines) > 0: retval = self.next_lines[0] del self.next_lines[0] # print("get_next_line(): return cached %s" % retval) self.lineno += 1 return retval try: retval = next(self.lineiter) # print("get_next_line(): return new %s" % retval) self.lineno += 1 return retval except StopIteration: # print("get_next_line(): return None") return None def generate_multiline_defn(peeker): defnlines = [] lineind = 0 nextline = peeker.peek_next_line(0) if nextline != None and not nextline.strip(): lineind = 1 nextline = peeker.peek_next_line(1) nextline = peeker.peek_next_line(lineind) if nextline != None and re.search(r"^\[(def|defn|definition)\]$", nextline.strip()): for i in range(lineind + 1): peeker.get_next_line() if not (peeker.peek_next_line(0) or "").strip(): peeker.get_next_line() while True: line = peeker.get_next_line() if not (line or "").strip(): break defnlines.append(line.strip() + "\n") return "".join(defnlines) return None def generate_dimaugpej(defn, template, pos, lang): parts = re.split(":", defn) assert len(parts) in [2, 3] defnline = "{{%s|%s|%s%s}}" % (template, lang, re.sub(r", *", ", ", parts[1]), "" if pos == "noun" else "|pos=%ss" % pos) if len(parts) == 3: defnline = "%s: %s" % (defnline, re.sub(r", *", ", ", parts[2])) return defnline known_labels = { "or": "or", "also": ["also", "_"], "f": "figurative", "fig": "figurative", "a": "archaic", "arch": "archaic", "d": "dated", "dat": "dated", "p": "poetic", "poet": "poetic", "h": "historical", "hist": "historical", "n": "nonstandard", "lc": ["low", "_", "colloquial"], "v": "vernacular", "inf": "informal", "c": "colloquial", "col": "colloquial", "l": "literary", "lit": "literary", "tr": "transitive", "in": "intransitive", "intr": "intransitive", "io": "imperfective only", "po": "perfective only", "im": "impersonal", "imp": "impersonal", "pej": "pejorative", "vul": "vulgar", "reg": "regional", "dia": "dialectal", "joc": "jocular", "an": "animate", "inan": "inanimate", "refl": "reflexive", "rel": "relational", } def parse_off_labels(defn): labels = [] while True: if defn.startswith("+"): labels.append("relational") defn = re.sub(r"^\+", "", defn) elif defn.startswith("#"): labels.append("figurative") defn = re.sub(r"^#", "", defn) elif defn.startswith("!"): labels.append("colloquial") defn = re.sub(r"^!", "", defn) else: m = re.search(r"^\((.*?)\)((?! ).*)$", defn) if m: shortlab = m.group(1) if shortlab in known_labels: longlab = known_labels[shortlab] if type(longlab) is list: labels.extend(longlab) else: labels.append(longlab) else: labels.append(shortlab) defn = m.group(2) else: defn = defn.replace(r"\(", "(").replace(r"\)", ")") break return defn, labels def generate_defn(defns, pos, lang): defnlines = [] addlprops = {} ever_saw_refl = False # the following regex uses a negative lookbehind so we split on a semicolon # but not on a backslashed semicolon, which we then replace with a regular # semicolon in the next line for defn in re.split(r"(?<![\\]);", defns): saw_refl = False saw_actual_defn = False defn = defn.replace(r"\;", ";") if defn == "-": defnlines.append("# {{rfdef|%s}}\n" % lang) elif defn.startswith("ux:"): defnlines.append("#: {{uxi|%s|%s}}\n" % (lang, re.sub("^ux:", "", re.sub(r", *", ", ", defn)))) elif defn.startswith("uxx:"): defnlines.append("#: {{ux|%s|%s}}\n" % (lang, re.sub("^uxx:", "", re.sub(r", *", ", ", defn)))) elif defn.startswith("quote:"): defnlines.append("#: {{quote|%s|%s}}\n" % (lang, re.sub("^quote:", "", re.sub(r", *", ", ", defn)))) elif re.search("^(syn|ant|pf|impf):", defn): m = re.search("^(.*?):(.*)$", defn) tempname, defn = m.groups() defn, labels = parse_off_labels(defn) defntext = "#: {{%s|%s|%s}}" % (tempname, lang, re.sub(r", *", "|", defn)) if labels: defntext += " {{i|%s}}" % ", ".join(labels) defnlines.append(defntext + "\n") else: saw_actual_defn = True prefix = "" defn, labels = parse_off_labels(defn) if labels: if lang == "bg" and labels[0] == "reflexive": prefix = "{{bg-reflexive%s}} " % "|".join([""] + labels[1:]) saw_refl = True elif lang == "bg" and labels[0] == "reflsi": prefix = "{{bg-reflexive-си%s}} " % "|".join([""] + labels[1:]) saw_refl = True else: prefix = "{{lb|%s|%s}} " % (lang, "|".join(labels)) if defn.startswith("altof:"): defnline = "{{alt form|%s|%s}}" % (lang, re.sub("^altof:", "", defn)) elif defn.startswith("oui:"): oui = re.sub("^oui:", "", defn) if "oui" in addlprops: addlprops["oui"].append(oui) else: addlprops["oui"] = [oui] defnline = "{{only used in|%s|%s}}" % (lang, oui) elif defn.startswith("dim:"): defnline = generate_dimaugpej(defn, "diminutive of", pos, lang) elif defn.startswith("end:"): defnline = generate_dimaugpej(defn, "endearing form of", pos, lang) elif defn.startswith("enddim:"): defnline = generate_dimaugpej(defn, "endearing diminutive of", pos, lang) elif defn.startswith("aug:"): defnline = generate_dimaugpej(defn, "augmentative of|nocap=1", pos, lang) elif defn.startswith("pej:"): defnline = generate_dimaugpej(defn, "pejorative of", pos, lang) elif defn.startswith("gn:"): gnparts = re.split(":", defn) assert len(gnparts) in [2] defnline = "{{given name|%s|%s}}" % (lang, gnparts[1]) else: defnline = re.sub(r", *", ", ", defn) defnline = re.sub(r"\(\((.*?)\)\)", r"{{m|%s|\1}}" % lang, defnline) defnline = re.sub(r"g<<(.*?)>>", r"{{gloss|\1}}", defnline) defnline = re.sub(r"<<(.*?)>>", r"{{i|\1}}", defnline) defnline = re.sub(r"g\((.*?)\)", r"{{glossary|\1}}", defnline) defnlines.append("# %s%s\n" % (prefix, defnline)) if saw_refl: ever_saw_refl = True elif ever_saw_refl and saw_actual_defn: return None, "Saw non-reflexive definition '%s' after reflexive definition" % defn return "".join(defnlines), addlprops
[ "ben@benwing.com" ]
ben@benwing.com
6d308c8fdbcad1d9cc4c82c322d064954d19a3f4
69e7dca194ab7b190e1a72928e28aa3821b47cfb
/Companies/Microsoft/subsets_with_balanced_sum.py
1428bc9a3fa76a75669c8400c331129c5205eec9
[]
no_license
Dinesh94Singh/PythonArchivedSolutions
a392891b431d47de0d5f606f7342a11b3127df4d
80cca595dc688ca67c1ebb45b339e724ec09c374
refs/heads/master
2023-06-14T14:56:44.470466
2021-07-11T06:07:38
2021-07-11T06:07:38
384,871,541
0
0
null
null
null
null
UTF-8
Python
false
false
392
py
import heapq def subset(arr, n): heap = [(0, i) for i in range(n)] res = [[] for _ in range(n)] for each in sorted(arr, reverse=True): val, idx = heapq.heappop(heap) total = val + each res[idx].append(each) heapq.heappush(heap, (total, idx)) return res ip = [1, 2, 3, 4, 5, 2, 2, 3, 9] total_subsets = 3 print(subset(ip, total_subsets))
[ "dinesh94singh@gmail.com" ]
dinesh94singh@gmail.com
1c62a910e86390ce30fb5d486b36b9d4701fe83c
72aa6c612eb583e3b29df62171ab720bebcb008f
/process_large.py
be40bdba0f60c4eeb66828a757573706761d012c
[]
no_license
phamthuonghai/aivivn-vn-tones
b9dbd36a96385f33e6da6bef1404139222700e3a
1747ec6d2999a84d33b86b857b9a3c1011d100b8
refs/heads/master
2020-05-18T16:37:19.807653
2019-08-16T06:36:36
2019-08-16T06:36:36
184,531,450
3
0
null
null
null
null
UTF-8
Python
false
false
1,493
py
import random import fire from tqdm import tqdm from utils import remove_tone_line def run(corpus='/home/vietai/wd8/vn-news/corpus-full.txt', train_d='./input/train_large.d', train_t='./input/train_large.t', dev_d='./input/dev_large.d', dev_t='./input/dev_large.t', exclude='./input/test.d', dev_prob=10000.0/111000000): input_file = open(corpus, 'r') train_d_file = open(train_d, 'w') train_t_file = open(train_t, 'w') dev_d_file = open(dev_d, 'w') dev_t_file = open(dev_t, 'w') to_exclude = set() with open(exclude, 'r') as f: for line in f: to_exclude.add(line.strip().lower()) print('%d sentences from %s' % (len(to_exclude), exclude)) ex_cnt = 0 cnt = 0 for line in tqdm(input_file): cnt += 1 t_line = line.strip() d_line = remove_tone_line(t_line) if d_line.lower() in to_exclude: ex_cnt += 1 continue if random.random() < dev_prob: # Write to dev dev_d_file.write(d_line + '\n') dev_t_file.write(t_line + '\n') else: # Write to train train_d_file.write(d_line + '\n') train_t_file.write(t_line + '\n') print('%d/%d sentences excluded' % (ex_cnt, cnt)) input_file.close() train_d_file.close() train_t_file.close() dev_d_file.close() dev_t_file.close() if __name__ == '__main__': fire.Fire(run)
[ "phamthuonghai@gmail.com" ]
phamthuonghai@gmail.com
48cca7809910d64fae390cc12e4d864ab4cc1ad9
f889bc01147869459c0a516382e7b95221295a7b
/test/test_cms_data_page_interface.py
1a1a421e864e585bfce415e94b6c343a2b2dcd74
[]
no_license
wildatheart/magento2-api-client
249a86f5c0289743f8df5b0324ccabd76f326512
e6a707f85b37c6c3e4ef3ff78507a7deb8f71427
refs/heads/master
2021-07-14T16:01:17.644472
2017-10-18T13:33:08
2017-10-18T13:33:08
107,412,121
1
1
null
null
null
null
UTF-8
Python
false
false
987
py
# coding: utf-8 """ Magento Community No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import swagger_client from swagger_client.rest import ApiException from swagger_client.models.cms_data_page_interface import CmsDataPageInterface class TestCmsDataPageInterface(unittest.TestCase): """ CmsDataPageInterface unit test stubs """ def setUp(self): pass def tearDown(self): pass def testCmsDataPageInterface(self): """ Test CmsDataPageInterface """ # FIXME: construct object with mandatory attributes with example values #model = swagger_client.models.cms_data_page_interface.CmsDataPageInterface() pass if __name__ == '__main__': unittest.main()
[ "sander@wildatheart.eu" ]
sander@wildatheart.eu
abefda220a2b161d360c89410353dfb823d3bdd5
2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae
/python/python_9713.py
e1e86620ac4a9c4f5591c0ddf0a9f7e62d4f8ce8
[]
no_license
AK-1121/code_extraction
cc812b6832b112e3ffcc2bb7eb4237fd85c88c01
5297a4a3aab3bb37efa24a89636935da04a1f8b6
refs/heads/master
2020-05-23T08:04:11.789141
2015-10-22T19:19:40
2015-10-22T19:19:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
153
py
# extracting specific content from html page from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(your_text) description = soup.find('a').string
[ "ubuntu@ip-172-31-7-228.us-west-2.compute.internal" ]
ubuntu@ip-172-31-7-228.us-west-2.compute.internal
0a2ff779889d398092de74b7f4c06519fdd8eb7a
08de348b667e45225a09c76e32fc61581a657ee1
/prescriptions/backend/migrations/0006_alter_patient_allergies.py
2844194cc1da2cfd98c1ccf951025daf1f1d2a2b
[]
no_license
JoeTanto2/SimpleOrder1
d676d34028642ccd38036d01194095029e19ff53
9a813c11292af755b560235cda0779d385a2c768
refs/heads/main
2023-07-24T02:24:38.309233
2021-09-04T16:51:50
2021-09-04T16:51:50
403,098,899
0
0
null
null
null
null
UTF-8
Python
false
false
399
py
# Generated by Django 3.2.6 on 2021-08-29 19:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0005_patient_allergies'), ] operations = [ migrations.AlterField( model_name='patient', name='allergies', field=models.JSONField(default=None, null=True), ), ]
[ "77851879+JoeTanto2@users.noreply.github.com" ]
77851879+JoeTanto2@users.noreply.github.com
de106655ce1ec7a32ca516d82784bf46461b429f
7c615414af2591146f2898444fb68f60e00a8482
/download/psutil-2.0.0/test/_bsd.py
4347a7fb404bc1019408b96856b186ca14e9e35a
[ "BSD-3-Clause" ]
permissive
guulyfox/Demonkeyse-Manell
15da1db0f0abf734cd638184d46015357de02612
745e552ac956c5bf087943dd3f075dede9c212ac
refs/heads/master
2021-01-01T04:37:29.080726
2019-03-11T00:43:40
2019-03-11T00:43:40
97,210,987
1
0
null
null
null
null
UTF-8
Python
false
false
7,730
py
#!/usr/bin/env python # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # TODO: add test for comparing connections with 'sockstat' cmd """BSD specific tests. These are implicitly run by test_psutil.py.""" import subprocess import time import sys import os import psutil from psutil._compat import PY3 from test_psutil import (TOLERANCE, sh, get_test_subprocess, which, retry_before_failing, reap_children, unittest) PAGESIZE = os.sysconf("SC_PAGE_SIZE") if os.getuid() == 0: # muse requires root privileges MUSE_AVAILABLE = which('muse') else: MUSE_AVAILABLE = False def sysctl(cmdline): """Expects a sysctl command with an argument and parse the result returning only the value of interest. """ result = sh("sysctl " + cmdline) result = result[result.find(": ") + 2:] try: return int(result) except ValueError: return result def muse(field): """Thin wrapper around 'muse' cmdline utility.""" out = sh('muse') for line in out.split('\n'): if line.startswith(field): break else: raise ValueError("line not found") return int(line.split()[1]) class BSDSpecificTestCase(unittest.TestCase): def setUp(self): self.pid = get_test_subprocess().pid def tearDown(self): reap_children() def test_boot_time(self): s = sysctl('sysctl kern.boottime') s = s[s.find(" sec = ") + 7:] s = s[:s.find(',')] btime = int(s) self.assertEqual(btime, psutil.boot_time()) def test_process_create_time(self): cmdline = "ps -o lstart -p %s" % self.pid p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE) output = p.communicate()[0] if PY3: output = str(output, sys.stdout.encoding) start_ps = output.replace('STARTED', '').strip() start_psutil = psutil.Process(self.pid).create_time() start_psutil = time.strftime("%a %b %e %H:%M:%S %Y", time.localtime(start_psutil)) self.assertEqual(start_ps, start_psutil) def test_disks(self): # test psutil.disk_usage() and psutil.disk_partitions() # against "df -a" def df(path): out = sh('df -k "%s"' % path).strip() lines = out.split('\n') lines.pop(0) line = lines.pop(0) dev, total, used, free = line.split()[:4] if dev == 'none': dev = '' total = int(total) * 1024 used = int(used) * 1024 free = int(free) * 1024 return dev, total, used, free for part in psutil.disk_partitions(all=False): usage = psutil.disk_usage(part.mountpoint) dev, total, used, free = df(part.mountpoint) self.assertEqual(part.device, dev) self.assertEqual(usage.total, total) # 10 MB tollerance if abs(usage.free - free) > 10 * 1024 * 1024: self.fail("psutil=%s, df=%s" % (usage.free, free)) if abs(usage.used - used) > 10 * 1024 * 1024: self.fail("psutil=%s, df=%s" % (usage.used, used)) def test_memory_maps(self): out = sh('procstat -v %s' % self.pid) maps = psutil.Process(self.pid).memory_maps(grouped=False) lines = out.split('\n')[1:] while lines: line = lines.pop() fields = line.split() _, start, stop, perms, res = fields[:5] map = maps.pop() self.assertEqual("%s-%s" % (start, stop), map.addr) self.assertEqual(int(res), map.rss) if not map.path.startswith('['): self.assertEqual(fields[10], map.path) # --- virtual_memory(); tests against sysctl def test_vmem_total(self): syst = sysctl("sysctl vm.stats.vm.v_page_count") * PAGESIZE self.assertEqual(psutil.virtual_memory().total, syst) @retry_before_failing() def test_vmem_active(self): syst = sysctl("vm.stats.vm.v_active_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().active, syst, delta=TOLERANCE) @retry_before_failing() def test_vmem_inactive(self): syst = sysctl("vm.stats.vm.v_inactive_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().inactive, syst, delta=TOLERANCE) @retry_before_failing() def test_vmem_wired(self): syst = sysctl("vm.stats.vm.v_wire_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().wired, syst, delta=TOLERANCE) @retry_before_failing() def test_vmem_cached(self): syst = sysctl("vm.stats.vm.v_cache_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().cached, syst, delta=TOLERANCE) @retry_before_failing() def test_vmem_free(self): syst = sysctl("vm.stats.vm.v_free_count") * PAGESIZE self.assertAlmostEqual(psutil.virtual_memory().free, syst, delta=TOLERANCE) @retry_before_failing() def test_vmem_buffers(self): syst = sysctl("vfs.bufspace") self.assertAlmostEqual(psutil.virtual_memory().buffers, syst, delta=TOLERANCE) # --- virtual_memory(); tests against muse @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available") def test_total(self): num = muse('Total') self.assertEqual(psutil.virtual_memory().total, num) @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available") @retry_before_failing() def test_active(self): num = muse('Active') self.assertAlmostEqual(psutil.virtual_memory().active, num, delta=TOLERANCE) @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available") @retry_before_failing() def test_inactive(self): num = muse('Inactive') self.assertAlmostEqual(psutil.virtual_memory().inactive, num, delta=TOLERANCE) @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available") @retry_before_failing() def test_wired(self): num = muse('Wired') self.assertAlmostEqual(psutil.virtual_memory().wired, num, delta=TOLERANCE) @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available") @retry_before_failing() def test_cached(self): num = muse('Cache') self.assertAlmostEqual(psutil.virtual_memory().cached, num, delta=TOLERANCE) @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available") @retry_before_failing() def test_free(self): num = muse('Free') self.assertAlmostEqual(psutil.virtual_memory().free, num, delta=TOLERANCE) @unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available") @retry_before_failing() def test_buffers(self): num = muse('Buffer') self.assertAlmostEqual(psutil.virtual_memory().buffers, num, delta=TOLERANCE) def test_main(): test_suite = unittest.TestSuite() test_suite.addTest(unittest.makeSuite(BSDSpecificTestCase)) result = unittest.TextTestRunner(verbosity=2).run(test_suite) return result.wasSuccessful() if __name__ == '__main__': if not test_main(): sys.exit(1)
[ "www.hubiwu.com@qq.com" ]
www.hubiwu.com@qq.com
ad4ccfc0df9176a1e8689df166cbcc7779955649
e780a5bd72f98ca2513c993d64a85b08578166a6
/buildout-cache/eggs/plone.i18n-3.0.7-py2.7.egg/plone/i18n/locales/cctld.py
003176d7dc641dd0bed2174775eca7231c719ea3
[]
no_license
vedantc98/Plone-test
023246597ffe848e2a49b9f65742ff49127b190b
9fd520fc78481e2c0b9b7ec427821e7f961c777e
refs/heads/master
2021-03-30T22:14:33.368739
2018-03-11T19:22:58
2018-03-11T19:22:58
124,671,713
0
0
null
null
null
null
UTF-8
Python
false
false
7,763
py
# -*- coding: utf-8 -*- # This file contains a map from internet top level domains to the spoken # language(s) in the country associated with the domain. # Top level domain list taken from # http://data.iana.org/TLD/tlds-alpha-by-domain.txt # Descriptions for most TLDs a can be found at # http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains from plone.i18n.locales.interfaces import ICcTLDInformation from zope.interface import implementer @implementer(ICcTLDInformation) class CcTLDInformation(object): """A list of country code top level domains their relevant languages. """ def getAvailableTLDs(self): """Return a sequence of country code top level domains. """ return _tld_to_language.keys() def getTLDs(self): """Return a sequence of ccTLDs and their languages. """ return _tld_to_language.copy() def getLanguagesForTLD(self, tld): """Return the relevant languages for a top level domain. """ return _tld_to_language[tld] ccTLDInformation = CcTLDInformation() _tld_to_language = { u"ac" : [], u"ad" : [], u"ae" : [], u"aero" : [], u"af" : [], u"ag" : [], u"ai" : [], u"al" : [], u"am" : [], u"an" : [], u"ao" : [], u"aq" : [u"en"], u"ar" : [u"pt"], u"arpa" : [u"en"], u"as" : [u"en"], u"asia" : [], u"at" : [u"de"], u"au" : [u"en"], u"aw" : [], u"ax" : [], u"az" : [], u"ba" : [u"bs"], u"bb" : [], u"bd" : [], u"be" : [u"nl", u"fr"], u"bf" : [], u"bg" : [], u"bh" : [], u"bi" : [], u"biz" : [], u"bj" : [], u"bm" : [], u"bn" : [], u"bo" : [], u"br" : [u"pt"], u"bs" : [], u"bt" : [], u"bv" : [], u"bw" : [], u"by" : [], u"bz" : [], u"ca" : [u"en"], u"cat" : [u"ca"], u"cc" : [], u"cd" : [], u"cf" : [], u"cg" : [], u"ch" : [u"de"], u"ci" : [], u"ck" : [], u"cl" : [], u"cm" : [], u"cn" : [u"zh"], u"co" : [], u"com" : [], u"coop" : [], u"cr" : [u"es"], u"cu" : [], u"cv" : [], u"cx" : [], u"cy" : [], u"cz" : [], u"de" : [u"de"], u"dj" : [], u"dk" : [u"da"], u"dm" : [], u"do" : [], u"dz" : [], u"ec" : [], u"edu" : [u"en"], u"ee" : [u"et"], u"eg" : [], u"er" : [], u"es" : [u"es"], u"et" : [], u"eu" : [], u"fi" : [u"fi"], u"fj" : [], u"fk" : [], u"fm" : [], u"fo" : [u"fo"], u"fr" : [u"fr"], u"ga" : [], u"gb" : [u"en"], u"gd" : [], u"ge" : [u"ka"], u"gf" : [], u"gg" : [], u"gh" : [], u"gi" : [], u"gl" : [], u"gm" : [], u"gn" : [], u"gov" : [u"en"], u"gp" : [], u"gq" : [], u"gr" : [u"gr"], u"gs" : [], u"gt" : [], u"gu" : [], u"gw" : [], u"gy" : [], u"hk" : [], u"hm" : [], u"hn" : [], u"hr" : [u"hr"], u"ht" : [], u"hu" : [u"hu"], u"id" : [], u"ie" : [], u"il" : [u"he"], u"im" : [u"en"], u"in" : [u"hi"], u"info" : [], u"int" : [], u"io" : [u"en"], u"iq" : [u"ar"], u"ir" : [u"ar"], u"is" : [u"is"], u"it" : [u"it"], u"je" : [u"en"], u"jm" : [], u"jo" : [], u"jobs" : [], u"jp" : [u"ja"], u"ke" : [], u"kg" : [], u"kh" : [], u"ki" : [], u"km" : [], u"kn" : [], u"kp" : [u"ko"], u"kr" : [u"ko"], u"kw" : [], u"ky" : [], u"kz" : [u"kk"], u"la" : [], u"lb" : [], u"lc" : [], u"li" : [], u"lk" : [], u"lr" : [], u"ls" : [], u"lt" : [], u"lu" : [u"lb"], u"lv" : [u"lv"], u"ly" : [], u"ma" : [], u"mc" : [], u"md" : [u"mo"], u"me" : [], u"mg" : [u"mg"], u"mh" : [], u"mil" : [u"en"], u"mk" : [], u"ml" : [], u"mm" : [], u"mn" : [u"mn"], u"mo" : [], u"mobi" : [], u"mp" : [], u"mq" : [], u"mr" : [], u"ms" : [], u"mt" : [u"mt"], u"mu" : [], u"museum" : [], u"mv" : [], u"mw" : [], u"mx" : [], u"my" : [], u"mz" : [], u"na" : [], u"name" : [], u"nc" : [], u"ne" : [], u"net" : [], u"nf" : [], u"ng" : [], u"ni" : [], u"nl" : [u"nl"], u"no" : [u"no"], u"np" : [], u"nr" : [], u"nu" : [], u"nz" : [], u"om" : [u"en"], u"org" : [], u"pa" : [], u"pe" : [], u"pf" : [], u"pg" : [], u"ph" : [], u"pk" : [], u"pl" : [u"pl"], u"pm" : [], u"pn" : [], u"pr" : [u"es"], u"pro" : [], u"ps" : [u"ar"], u"pt" : [u"pt"], u"pw" : [], u"py" : [], u"qa" : [], u"re" : [], u"ro" : [u"ro"], u"rs" : [], u"ru" : [u"ru"], u"rw" : [], u"sa" : [u"ar"], u"sb" : [], u"sc" : [], u"sd" : [u"su"], u"se" : [u"sv"], u"sg" : [u"si"], u"sh" : [], u"si" : [u"sl"], u"sj" : [], u"sk" : [u"sk"], u"sl" : [], u"sm" : [], u"sn" : [u"fr"], u"so" : [u"so"], u"sr" : [u"nl"], u"ss" : [], u"st" : [], u"su" : [u"ru"], u"sv" : [], u"sy" : [], u"sz" : [], u"tc" : [u"tr"], u"td" : [], u"tel" : [], u"tf" : [], u"tg" : [u"to"], u"th" : [u"th"], u"tj" : [u"fa"], u"tk" : [u"tk"], u"tl" : [u"pt"], u"tm" : [u"tk"], u"tn" : [], u"to" : [], u"tp" : [u"pt"], u"tr" : [], u"travel" : [], u"tt" : [], u"tv" : [], u"tw" : [u"zh"], u"tz" : [], u"ua" : [], u"ug" : [], u"uk" : [u"en"], u"us" : [u"en"], u"uy" : [], u"uz" : [], u"va" : [u"it"], u"vc" : [], u"ve" : [], u"vg" : [], u"vi" : [u"en"], u"vn" : [u"vi"], u"vu" : [], u"wf" : [], u"ws" : [u"sm"], u"xxx" : [], u"ye" : [], u"yt" : [], u"yu" : [u"sh"], u"za" : [u"af"], u"zm" : [], u"zw" : [], }
[ "vedantc98@gmail.com" ]
vedantc98@gmail.com
c017510ed7159d47b9fed3efac38c5b571af3693
aace314f751737115ba181ce0bd3a87c12a360f7
/qiime/core/archive/__init__.py
0d194198fc017578e356a3e8e22dbe85b15441bb
[ "BSD-3-Clause" ]
permissive
PingPi357/qiime2
7acbf7b09f10fe9525d8b2d27208a6c220602cc5
9b4805b7722039f777e064736229495f28115006
refs/heads/master
2021-05-04T02:37:27.644028
2016-10-10T22:17:32
2016-10-10T22:17:32
null
0
0
null
null
null
null
UTF-8
Python
false
false
407
py
# ---------------------------------------------------------------------------- # Copyright (c) 2016--, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from .archiver import Archiver __all__ = ['Archiver']
[ "jai.rideout@gmail.com" ]
jai.rideout@gmail.com
261e84a94928d51b94cc2881a9d8d858fa338fc6
dd01a23a65ccd57058de6ae62edfe1e85e225869
/core/models.py
11bdb8adb5c5c66ef2c9a26747a4bed3bff6bad6
[]
no_license
safwanvk/bus_tracker
2b25e72e9e8ea33068f503f1253cc5a16662b609
036269a9a85b11bfe61dabb5e0d0d86d6e573f9b
refs/heads/main
2023-06-02T07:07:27.071500
2021-05-08T08:09:10
2021-05-08T08:09:10
353,282,070
0
0
null
null
null
null
UTF-8
Python
false
false
1,427
py
from django.db import models # Create your models here. class UserType(models.Model): id = models.IntegerField(null=False, primary_key=True) role_name = models.CharField(max_length=50) def __str__(self): return self.role_name class Meta: db_table = "User_Type" class User(models.Model): id = models.AutoField(null=False, primary_key=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) phone = models.CharField(max_length=15) address = models.CharField(max_length=500) city = models.CharField(max_length=50) state = models.CharField(max_length=50) address = models.CharField(max_length=500) is_active = models.BooleanField() role_id = models.ForeignKey(UserType,to_field='id',on_delete=models.CASCADE, null=False) def __str__(self): return self.first_name + self.last_name class Meta: db_table = "User" class Feedback(models.Model): id = models.AutoField(null=False, primary_key=True) name = models.CharField(max_length=50) email = models.CharField(max_length=50) title = models.CharField(max_length=200) message = models.CharField(max_length=500) date = models.DateTimeField() user_id = models.ForeignKey(User,to_field='id',on_delete=models.CASCADE,null=False) def __str__(self): return self.title class Meta: db_table = "Feedback"
[ "safwanvalakundil@gmail.com" ]
safwanvalakundil@gmail.com
cc8c70a152accaa5e2b48a635558cb9f99660941
01017443bb892f4f3a2d1f1fd1e9aa693312865c
/test/test_command_definition.py
f50e33f7e7f3b113121ed3b2cdf2a1ec4a2aec6b
[ "MIT" ]
permissive
biberhund/home-connect-api
d088b995e0d7d1b588894059330c91c9a29a87d3
62cca9c0faee9a18210ef7f7a94d2e6dafb97524
refs/heads/master
2023-03-23T03:25:39.040078
2020-04-16T05:14:50
2020-04-16T05:14:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,741
py
# coding: utf-8 """ Home Connect API This API provides access to home appliances enabled by Home Connect (https://home-connect.com). Through the API programs can be started and stopped, or home appliances configured and monitored. For instance, you can start a cotton program on a washer and get a notification when the cycle is complete. To get started with this web client, visit https://developer.home-connect.com and register an account. An application with a client ID for this API client will be automatically generated for you. In order to use this API in your own client, you need an OAuth 2 client implementing the authorization code grant flow (https://developer.home-connect.com/docs/authorization/flow). More details can be found here: https://www.rfc-editor.org/rfc/rfc6749.txt Authorization URL: https://api.home-connect.com/security/oauth/authorize Token URL: https://api.home-connect.com/security/oauth/token # noqa: E501 OpenAPI spec version: 1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import home_connect_api from models.command_definition import CommandDefinition # noqa: E501 from home_connect_api.rest import ApiException class TestCommandDefinition(unittest.TestCase): """CommandDefinition unit test stubs""" def setUp(self): pass def tearDown(self): pass def testCommandDefinition(self): """Test CommandDefinition""" # FIXME: construct object with mandatory attributes with example values # model = home_connect_api.models.command_definition.CommandDefinition() # noqa: E501 pass if __name__ == '__main__': unittest.main()
[ "jeroenvdwaal@gmail.com" ]
jeroenvdwaal@gmail.com
a0916b38680c1281089cc29534cd7a877e618195
5266fd579b4b62f1f1d560c85d60c2a05385e090
/lesson119.py
b0934f2905456a89cccdef2569fcd316e2b3f887
[]
no_license
ipcoo43/pythonthree
2daf6e7f552a5865980414b53d796585a21e3f32
a10fa643a9a6aa5b5a09c14d8abb8ac028220b17
refs/heads/master
2020-05-16T21:56:51.751583
2019-04-28T09:11:06
2019-04-28T09:11:06
183,321,923
0
0
null
null
null
null
UTF-8
Python
false
false
539
py
import os lstA = ['abs(x)','int(x)','long(x)','float(x)','complex(re,im)','divmod(x,y) ','pow(x,y)'] lstB = ['x의 절대값','x를 int(정수)형으로 변환','x를 long형으로 변환','x를 float형으로 변환','실수부re와 허수부im를 갖는 복소수','(x/y, x%y) 쌍','x의 y승'] i=0 while i<len(lstA): os.system('clear') print('>>>',lstB[i]) data = input('{} >> '.format(lstA[i])) print('>>>',lstB[i]) if data == '': break i += 1 os.system('clear') print('내장 수치 연산 함수를 학습 하였습니다.')
[ "ipcoo43@gmail.com" ]
ipcoo43@gmail.com
5c41841127e240cbf431eab48b536cea5d153aea
0857ee93b0a041bb38c635b71e456247982e18f0
/app/serializers.py
1d1c885af6982f70b920521fec61d84cdd948ac2
[]
no_license
ConnorFieldUser/single_page_secrets
932ae5f253c3c4742d3584ecb6a34e0776f5672e
e4acdc26e64999e9d351beda98fd4f6af91566b5
refs/heads/master
2020-07-26T21:48:56.960107
2016-11-10T17:15:48
2016-11-10T17:15:48
null
0
0
null
null
null
null
UTF-8
Python
false
false
195
py
from rest_framework import serializers from app.models import Secret class SecretSerializer(serializers.ModelSerializer): class Meta: model = Secret fields = ("body", )
[ "jtaddei@gmail.com" ]
jtaddei@gmail.com
6be19436b3247c0ba7952325e97cf3d57b5a654c
8da76aabcf9cfea3478f56037edbb5fa1513140b
/eutp/bin/easy_install-2.7
afaf27c0188981876c719ca6ec61edf771e495c5
[]
no_license
mikanyman/.virtualenvs-legacy
039479f31f2ca9f9a3d3544d8837429ddd0a7492
5486128b5b3b7ddb9ec81d43e3bb601a23b4025a
refs/heads/master
2020-12-31T07:10:07.018881
2017-02-01T02:16:55
2017-02-01T02:16:55
80,566,220
0
0
null
null
null
null
UTF-8
Python
false
false
317
7
#!/home/mnyman/.virtualenvs/eutp/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==0.6c11','console_scripts','easy_install-2.7' __requires__ = 'setuptools==0.6c11' import sys from pkg_resources import load_entry_point sys.exit( load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install-2.7')() )
[ "mika.nyman@synapse-computing.com" ]
mika.nyman@synapse-computing.com
82eb2747f9f89c46ea53d85dcf8ab130c0eea5e6
fe75ab418adfd723f48b8eafc80515c9fd913395
/PAT/PAT_B1006.py
3a0b650fe0c3cda25d36ea164d44db27ffbcebf3
[]
no_license
AshkenSC/Programming-Practice
d029e9d901f51ef750ed4089f10c1f16783d2695
98e20c63ce1590deda6761ff2f9c8c37f3fb3c4a
refs/heads/master
2021-07-20T06:41:12.673248
2021-06-25T15:44:06
2021-06-25T15:44:06
127,313,792
0
0
null
null
null
null
UTF-8
Python
false
false
511
py
# PAT B1006 num_str = input() if len(num_str) == 1: for i in range(1, int(num_str)+1): print(str(i), end='') elif len(num_str) == 2: for i in range(int(num_str[0])): print('S', end='') for i in range(1, int(num_str[1]) + 1): print(str(i), end='') elif len(num_str) == 3: for i in range(int(num_str[0])): print('B', end='') for i in range(int(num_str[1])): print('S', end='') for i in range(1, int(num_str[2]) + 1): print(str(i), end='')
[ "393940378@qq.com" ]
393940378@qq.com
ad99f02f854d3e984b1788c7d12295f9b75d0498
3949414cb8e26d025fd46bb8094aee3908b5658d
/2_字符串和文本/2_6.py
6dccaed4d09e64c0df467bbcd77bf4078eaee0a9
[]
no_license
haoxiaoning1125/python_cookbook
6b932aae4a6bdc849e257d21de702a2ae0c241ee
a1e5f9feeb949b39d93fda8bcf97050699cf6bff
refs/heads/master
2020-07-02T01:50:21.314472
2019-09-09T02:29:35
2019-09-09T02:29:35
201,377,132
0
0
null
null
null
null
UTF-8
Python
false
false
759
py
# coding:utf-8 """ 字符串忽略大小写的搜索替换 """ import re if __name__ == '__main__': text = 'UPPER PYTHON, lower python, Mixed Python' print re.findall('python', text, flags=re.IGNORECASE) print re.sub('python', 'snake', text, flags=re.IGNORECASE) print '-' * 20 # 辅助函数 def matchcase(word): def replace(m): t = m.group() if t.isupper(): return word.upper() elif t.islower(): return word.lower() elif t[0].isupper(): return word.capitalize() else: return word return replace print re.sub('python', matchcase('snake'), text, flags=re.IGNORECASE) print '-' * 20
[ "1977835153@qq.com" ]
1977835153@qq.com
1b7e495d10b8bbeacc0894360a2ec9341f5abb32
0e9bb6c8dbecf2300821d5dd554f1238a00e2b7b
/Classes/Base/Vector.py
a5992d337cc3bd77187101ce3bbe61866ec4bee7
[ "MIT" ]
permissive
crablab/cs1830_project
91c985e8bf09e42537f7e0c1c89d90fde8c95079
af0767a5860e18f5c7d58464704f186552a90ee6
refs/heads/master
2021-03-27T13:13:34.144901
2018-03-19T17:22:56
2018-03-19T17:22:56
122,527,145
0
0
null
null
null
null
UTF-8
Python
false
false
2,735
py
from SimpleGUICS2Pygame import simpleguics2pygame, simplegui_lib_keys, simplegui_lib_fps import random import copy import pygame import math import json class Vector: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(" + str(self.x) + "," + str(self.y) + ")" def negate(self): self.multiply(-1) def getP(self): return (self.x, self.y) def getX(self): return self.x def getY(self): return self.y def copy(self): v = Vector(self.x, self.y) return v def add(self, other): self.x += other.x self.y += other.y return self def subtract(self, other): self.x -= other.x self.y -= other.y return self def multiply(self, k): self.x *= k self.y *= k return self def multiplyVector(self, other): self.x *= other.x self.y *= other.y return self def divide(self, k): self.x /= k self.y /= k return self def divideVector(self, other): self.x /= other.x self.y /= other.y return self def normalize(self): return self.divide(self.length()) def isEqual(self,other): return self.x==other.x and self.y == other.y def dot(self, other): return self.x * other.x + self.y * other.y # Returns the length of the vector def length(self): return math.sqrt(self.x ** 2 + self.y ** 2) def size(self): return self.x+self.y # Returns the squared length of the vector def lengthSq(self): return self.x ** 2 + self.y ** 2 def distanceTo(self,pos): return math.sqrt((self.x-pos.x)**2 +(self.y-pos.y)**2) def distanceToVector(self,pos): return self.x-pos.x,self.y-pos.y # Reflect this vector on a normal def reflect(self, normal): n = normal.copy() n.mult(2 * self.dot(normal)) self.subtract(n) return self def rotate(self, angle): self.x = self.x * math.cos(angle) - self.y * math.sin(angle) self.y = self.x * math.sin(angle) + self.y * math.cos(angle) return self def getAngle(self, other): return math.acos(self.dot(other)) def transformFromCam(self,cam): self.subtract(cam.dimCanv.copy().divide(2)) ratio = cam.dim.copy().divideVector(cam.dimCanv) self.multiplyVector(ratio) self.add(cam.origin) return self def transformToCam(self,cam): self.subtract(cam.origin) ratio=cam.dimCanv.copy().divideVector(cam.dim) self.multiplyVector(ratio) self.add(cam.dimCanv.copy().divide(2)) return self
[ "octavio.delser@gmail.com" ]
octavio.delser@gmail.com
1a7df0f420695f019e3f8569733052927d23ba46
ef90992dc00640f42ec615075a9b030b771f81e4
/python-machine-learning/ch07/ch07-3/gyudon_downloader.py
12614af02e9278a5edf15bafc7185dd327728d7b
[]
no_license
korea7030/pythonwork
88f5e67b33e9143eb40f6c10311a29e08317b77e
70741acb0477c9348ad3f1ea07a183dda82a5402
refs/heads/master
2023-01-08T01:47:15.141471
2020-09-09T13:28:20
2020-09-09T13:28:20
54,378,053
0
0
null
2022-12-26T20:25:43
2016-03-21T10:00:07
Jupyter Notebook
UTF-8
Python
false
false
2,712
py
# -*- coding: utf-8 -*- import sys import os import re import time import urllib.request as req import urllib.parse as parse import json # API의 URL 지정하기 PHOTOZOU_API = "https://api.photozou.jp/rest/search_public.json" CACHE_DIR = "./image/cache" # 포토주 API로 이미지 검색하기 --- (※1) def search_photo(keyword, offset=0, limit=100): # API 쿼리 조합하기 keyword_enc = parse.quote_plus(keyword) q = "keyword={0}&offset={1}&limit={2}".format(keyword_enc, offset, limit) url = PHOTOZOU_API + "?" + q # 캐시 전용 폴더 만들기 if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) cache = CACHE_DIR + "/" + re.sub(r'[^a-zA-Z0-9\%\#]+', '_', url) if os.path.exists(cache): return json.load(open(cache, "r", encoding="utf-8")) print("[API] " + url) req.urlretrieve(url, cache) time.sleep(1) # --- 1초 쉬기 return json.load(open(cache, "r", encoding="utf-8")) # 이미지 다운로드하기 --- (※2) def download_thumb(info, save_dir): if not os.path.exists(save_dir): os.makedirs(save_dir) if info is None: return if not "photo" in info["info"]: print("[ERROR] broken info") return photolist = info["info"]["photo"] for photo in photolist: title = photo["photo_title"] photo_id = photo["photo_id"] url = photo["thumbnail_image_url"] path = save_dir + "/" + str(photo_id) + "_thumb.jpg" if os.path.exists(path): continue try: print("[download]", title, photo_id) req.urlretrieve(url, path) time.sleep(1) # --- 1초 쉬기 except Exception as e: print("[ERROR] failed to downlaod url=", url) # 모두 검색하고 다운로드하기 --- (※3) def download_all(keyword, save_dir, maxphoto=1000): offset = 0 limit = 100 while True: # API 호출 info = search_photo(keyword, offset=offset, limit=limit) if info is None: print("[ERROR] no result") return if (not "info" in info) or (not "photo_num" in info["info"]): print("[ERROR] broken data") return photo_num = info["info"]["photo_num"] if photo_num == 0: print("photo_num = 0, offset=", offset) return # 사진 정보가 포함돼 있으면 다운받기 print("*** download offset=", offset) download_thumb(info, save_dir) offset += limit if offset >= maxphoto: break if __name__ == '__main__': # 모듈로 사용할 수 있게 설정 download_all("牛丼", "./image/gyudon") # --- (※4)
[ "korea7030@naver.com" ]
korea7030@naver.com
7b7187a1c2541f891f978a9f95e6d677124c9caa
34ff3024ae08718573ee1282ed91a0714caaaf44
/chapter_4/4-10.py
7b97241feb55da6d0ee0a69010a30b3acb8580e3
[]
no_license
lhui2010/python_crash
62bdac5c495b84e09570fa5e1be38ec68fd5b2a2
7c06f134b5863e6c10fe4f91bcda30299f671085
refs/heads/master
2020-03-16T00:43:23.435287
2018-07-26T05:53:32
2018-07-26T05:53:32
132,423,846
0
0
null
null
null
null
UTF-8
Python
false
false
160
py
# coding: utf-8 odd_nums=list(range(3,31,3)) print ("The first three: ", odd_nums[:3]) print ("The middle: ", odd_nums[3:6]) print ("The last: ", odd_nums[6:])
[ "lhui2010@gmail.com" ]
lhui2010@gmail.com
f4fea9c4ea2afe59cd6b8921f7808aa217c3ccd3
19cec240505e27546cb9b10104ecb16cc2454702
/moin/lib/python2.4/site-packages/MoinMoin/i18n/mail_i18n-maintainers.py
d3ce7420c6d772d300e0934d8f07880164786ca2
[]
no_license
imosts/flume
1a9b746c5f080c826c1f316a8008d8ea1b145a89
a17b987c5adaa13befb0fd74ac400c8edbe62ef5
refs/heads/master
2021-01-10T09:43:03.931167
2016-03-09T12:09:53
2016-03-09T12:09:53
53,101,798
0
0
null
null
null
null
UTF-8
Python
false
false
2,713
py
#!/usr/bin/env python """ read mail text from standard input and send an email to all i18n maintainers %(lang)s will be replaced by language @copyright: 2004 Thomas Waldmann @license: GNU GPL, see COPYING for details """ mail_from = 'tw-public@gmx.de' mail_subject = 'MoinMoin i18n notification' mail_smarthost = 'localhost' mail_login = None charset = 'iso-8859-1' from meta import languages def sendmail(mfrom, mto, subject, text): """ Send a mail to the address(es) in 'to', with the given subject and mail body 'text'. Return a tuple of success or error indicator and message. TODO: code duplicated from MoinMoin/util/mail.py @param mfrom: source email address @param to: target email address @param subject: subject of email @param text: email body text @rtype: tuple @return: (is_ok, msg) """ import smtplib, socket, os from email.MIMEText import MIMEText from email.Header import Header from email.Utils import formatdate global charset, mail_smarthost, mail_login # Create a text/plain message msg = MIMEText(text, 'plain', charset) msg['From'] = mfrom msg['To'] = ', '.join(mto) msg['Subject'] = Header(subject, charset) msg['Date'] = formatdate() try: server = smtplib.SMTP(mail_smarthost) try: #server.set_debuglevel(1) if mail_login: user, pwd = mail_login.split() server.login(user, pwd) server.sendmail(mail_from, mto, msg.as_string()) finally: try: server.quit() except AttributeError: # in case the connection failed, SMTP has no "sock" attribute pass except smtplib.SMTPException, e: return (0, str(e)) except (os.error, socket.error), e: return (0, "Connection to mailserver '%(server)s' failed: %(reason)s" % { 'server': mail_smarthost, 'reason': str(e) }) return (1, "Mail sent OK") def notify_maintainer(lang, mail_text): mailaddr = languages[lang][4] rc = None if mailaddr and mailaddr.find('***vacant***') < 0: print lang, mailaddr text = mail_text % locals() rc = sendmail(mail_from, [mailaddr], mail_subject, text) return rc if __name__ == '__main__': langs = languages.keys() langs.remove('en') # nothing to do for english, so remove it #langs = ['de', ] # for testing import sys mail_text = sys.stdin.read() if len(mail_text) > 10: # do not send mails w/o real content for lang in langs: notify_maintainer(lang, mail_text)
[ "imosts" ]
imosts
10a5fc2e0899903db9f87c86d3ce2c38615d7220
0ad598414852adb1d8fbdf37a34d00522325ba92
/test.py
afa7553498dbc90e596d747ee3accd7ed424e863
[]
no_license
HsinTingHo/Practical-Aspects-of-Modern-Cryptography
ee0a3d7f523d7916f8112e305b494b74159da4ed
47f53f7110a0796155c7e48a49d583a082c9a831
refs/heads/master
2023-01-14T08:23:02.528855
2020-11-20T19:35:11
2020-11-20T19:35:11
297,689,037
0
0
null
2020-09-22T20:20:46
2020-09-22T15:17:58
Python
UTF-8
Python
false
false
730
py
from traditional_cryptography import ciphers as c char_table = { 'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7, 'I':8 ,'J':9, 'K':10, 'L':11, 'M':12, 'N':13, 'O':14, 'P':15, 'Q':16, 'R':17, 'S':18, 'T':19, 'U':20, 'V':21, 'W':22, 'X':23, 'Y':24, 'Z':25 } #test affine_encoding test = 'STOPPOLLUTION' length = len(test) for i in range(length): num = char_table[test[i]] print(c.affine_encoding(17,22,num,26)) #test caesar_decoding test = 'EOXHMHDQV' length = len(test) for i in range(length): num = char_table[test[i]] print(c.caesar_decoding(num,26)) #test block transposition cipher test = 'GRIZZLYBEARS' permutation_list = [3,5,1,2,4] print(c.block_transposition_encoding(permutation_list, test, 5))
[ "replituser@example.com" ]
replituser@example.com
12432af76e6cbac19b97fbe017f7fc474c3f9e0f
ad14bfaa88467d8d1278e87651b2c393ba5c8780
/skytrip/ticket_search/search_config.py
69913772bdbcb51a448fca64f1b5687d423593b1
[]
no_license
NumanIbnMazid/reservation
e2ecb9ff3eb7dc9241ed8b71e4d00c2a39cc38ad
bbe7c7e74313ed63d7765a16cf11fdf7f3ad706a
refs/heads/master
2023-03-30T17:30:50.889955
2021-04-06T14:52:07
2021-04-06T14:52:07
355,220,371
1
0
null
null
null
null
UTF-8
Python
false
false
2,771
py
# skytrip ticket search config class class SearchConfig: # class variables for ticket search passenger_types_to_skip_count = ["INF"] requestor_id_company_code = "TN" def get_skytrip_ticket_search_response_standard_structure(self): """ Getter method for getting standard structure for skytrip search response return => object """ structure = { "statusCode": None, "body": { "token": None, "responseData": { "Messages": [], "Statistics": { "ItineraryCount": "" }, "LegDescription": [], "Itineraries": [] }, "UTILS": { "Sabre": None, "Galileo": None, "Amadeous": None } } } return structure def get_search_request_structure(self): """ get_search_request_structure() => returns BFM Search Request Structure. """ structure = { "OTA_AirLowFareSearchRQ": { "OriginDestinationInformation": [], "POS": { "Source": [ { "PseudoCityCode": "", "RequestorID": { "CompanyName": { "Code": "" }, "ID": "1", "Type": "1" } } ] }, "TPA_Extensions": { "IntelliSellTransaction": { "RequestType": { "Name": "200ITINS" } } }, "TravelPreferences": { "TPA_Extensions": { "DataSources": { "ATPCO": "Enable", "LCC": "Disable", "NDC": "Disable" }, "NumTrips": {} } }, "TravelerInfoSummary": { "AirTravelerAvail": [ { "PassengerTypeQuantity": [] } ], "SeatsRequested": [] }, # "AvailableFlightsOnly": True, # "DirectFlightsOnly": True, "Version": "1" } } return structure
[ "numanibnmazid@gmail.com" ]
numanibnmazid@gmail.com
7e2fd2dc5c20ae33908e6aa0002089704d991952
d0d5c2b4b1c5f21247b756ed8cd2912b1c4b66b6
/utils.py
2b9bf1236311c3fff4db246b94cf2ae2b4837460
[]
no_license
GT-AcerZhang/pacman-with-paddlepaddle-gesture-control
37e8fb13dad4875add1090f7482b445b55ccecb8
a9da953ca429140b3126bebd3fc981da9bb7c719
refs/heads/main
2023-03-17T20:12:07.270108
2021-03-09T03:16:13
2021-03-09T03:16:13
345,868,705
0
0
null
2021-03-09T03:15:50
2021-03-09T03:15:49
null
UTF-8
Python
false
false
2,747
py
import pygame from config import * class Player(pygame.sprite.Sprite): change_x = 0 change_y = 0 def __init__(self, x, y, filename): pygame.sprite.Sprite.__init__(self) self.count = 0 self.image = pygame.image.load(filename).convert_alpha() self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x self.prev_x = x self.prev_y = y def prevdirection(self): self.prev_x = self.change_x self.prev_y = self.change_y def changespeed(self, x, y): self.change_x = x self.change_y = y def update(self, walls, gate): old_x = self.rect.left new_x = old_x+self.change_x prev_x = old_x+self.prev_x self.rect.left = new_x old_y = self.rect.top new_y = old_y+self.change_y prev_y = old_y+self.prev_y x_collide = pygame.sprite.spritecollide(self, walls, False) if x_collide: self.rect.left = old_x else: self.rect.top = new_y y_collide = pygame.sprite.spritecollide(self, walls, False) if y_collide: self.rect.top = old_y if gate != False: gate_hit = pygame.sprite.spritecollide(self, gate, False) if gate_hit: self.rect.left = old_x self.rect.top = old_y class Wall(pygame.sprite.Sprite): def __init__(self, x, y, width, height, color): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.top = y self.rect.left = x class Block(pygame.sprite.Sprite): def __init__(self, color, width, height): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(white) self.image.set_colorkey(white) pygame.draw.ellipse(self.image, color, [0, 0, width, height]) self.rect = self.image.get_rect() class Ghost(Player): def changespeed(self, list, ghost, turn, steps, l): try: z = list[turn][2] if steps < z: self.change_x = list[turn][0] self.change_y = list[turn][1] steps += 1 else: if turn < l: turn += 1 elif ghost == 'clyde': turn = 2 else: turn = 0 self.change_x = list[turn][0] self.change_y = list[turn][1] steps = 0 return [turn, steps] except IndexError: return [0, 0]
[ "1691608003@qq.com" ]
1691608003@qq.com
a0cfdf83332e866605a71d3d51bce1225c9a2a43
32b386dc92933cd4cd0ffbf56ec61d9e723ea3c7
/PhysicsTools/PatAlgos/python/slimming/prunedGenParticles_cfi.py
a72fb3e99930714e24d028fcdd196849794e4d47
[]
no_license
sbein/StealthSusy
828ae8622c645eb9388f55dc355e2a02780b56c0
247f25d9dc936fc6edd472ecd50087477ce386ca
refs/heads/master
2021-05-23T05:47:49.408523
2018-01-22T15:09:01
2018-01-22T15:09:01
94,929,454
0
0
null
null
null
null
UTF-8
Python
false
false
3,351
py
import FWCore.ParameterSet.Config as cms prunedGenParticles = cms.EDProducer("GenParticlePruner", src = cms.InputTag("genParticles"), select = cms.vstring( "drop *", # this is the default "++keep abs(pdgId) == 11 || abs(pdgId) == 13 || abs(pdgId) == 15", # keep leptons, with history "keep abs(pdgId) == 12 || abs(pdgId) == 14 || abs(pdgId) == 16", # keep neutrinos "drop status == 2", # drop the shower part of the history "+keep pdgId == 22 && status == 1 && (pt > 10 || isPromptFinalState())", # keep gamma above 10 GeV (or all prompt) and its first parent "+keep abs(pdgId) == 11 && status == 1 && (pt > 3 || isPromptFinalState())", # keep first parent of electrons above 3 GeV (or prompt) "keep++ abs(pdgId) == 15", # but keep keep taus with decays "drop status > 30 && status < 70 ", #remove pythia8 garbage "drop pdgId == 21 && pt < 5", #remove pythia8 garbage "drop status == 2 && abs(pdgId) == 21", # but remove again gluons in the inheritance chain "keep abs(pdgId) == 23 || abs(pdgId) == 24 || abs(pdgId) == 25 || abs(pdgId) == 6 || abs(pdgId) == 37 ", # keep VIP(articles)s "keep abs(pdgId) == 310 && abs(eta) < 2.5 && pt > 1 ", # keep K0 # keep heavy flavour quarks for parton-based jet flavour "keep (4 <= abs(pdgId) <= 5)", # keep light-flavour quarks and gluons for parton-based jet flavour "keep (1 <= abs(pdgId) <= 3 || pdgId = 21) & (status = 2 || status = 11 || status = 71 || status = 72) && pt>5", # keep b and c hadrons for hadron-based jet flavour "keep (400 < abs(pdgId) < 600) || (4000 < abs(pdgId) < 6000)", # keep onia states "keep abs(pdgId) == 443 || abs(pdgId) == 100443 || abs(pdgId) == 10441 || abs(pdgId) == 20443 || abs(pdgId) == 445 || abs(pdgId) == 30443", "keep abs(pdgId) == 553 || abs(pdgId) == 100553 || abs(pdgId) == 200553 || abs(pdgId) == 10551 || abs(pdgId) == 20553 || abs(pdgId) == 555", # additional c hadrons for jet fragmentation studies "keep abs(pdgId) = 10411 || abs(pdgId) = 10421 || abs(pdgId) = 10413 || abs(pdgId) = 10423 || abs(pdgId) = 20413 || abs(pdgId) = 20423 || abs(pdgId) = 10431 || abs(pdgId) = 10433 || abs(pdgId) = 20433", # additional b hadrons for jet fragmentation studies "keep abs(pdgId) = 10511 || abs(pdgId) = 10521 || abs(pdgId) = 10513 || abs(pdgId) = 10523 || abs(pdgId) = 20513 || abs(pdgId) = 20523 || abs(pdgId) = 10531 || abs(pdgId) = 10533 || abs(pdgId) = 20533 || abs(pdgId) = 10541 || abs(pdgId) = 10543 || abs(pdgId) = 20543", #keep SUSY particles "keep (1000001 <= abs(pdgId) <= 1000039 ) || ( 2000001 <= abs(pdgId) <= 2000015)", # keep protons "keep pdgId = 2212", "keep status == 3 || ( 21 <= status <= 29) || ( 11 <= status <= 19)", #keep event summary (status=3 for pythia6, 21 <= status <= 29 for pythia8) "keep isHardProcess() || fromHardProcessFinalState() || fromHardProcessDecayed() || fromHardProcessBeforeFSR() || (statusFlags().fromHardProcess() && statusFlags().isLastCopy())", #keep event summary based on status flags "keep (abs(pdgId) == 3000001 || abs(pdgId) == 3000002)", ) )
[ "samuel.bein@gmail.com" ]
samuel.bein@gmail.com
0cbbddcb2ae9ff2fe142a1a201f3507745ddb7bc
845d4102771a547dbc447f1d837b89a538f977b7
/listaExercicios/LISTA_FABIO_ITERACAO/21.py
330564bdf462b6bcfb498da0057d9508a10b66d7
[]
no_license
TemistoclesZwang/Algoritmo_IFPI_2020
16e92d6f3e5e3f15ad573819cbd0171c5a5e3f5d
cc24657864985c3894ab738692807a01eab8d377
refs/heads/main
2023-08-23T02:57:58.838585
2021-10-05T16:18:14
2021-10-05T16:18:14
310,669,249
0
0
null
null
null
null
UTF-8
Python
false
false
459
py
n = int(input('Digite o valor de N: ')) contador = 2 constante = 1 cima = 1 baixo = 1 cima_impar = 3 while contador <= n: #operacao 1 calc_cima = (baixo * cima_impar) + (contador * cima) calc_baixo = contador * baixo contador += 1 cima_impar += 2 cima = calc_cima baixo = calc_baixo #operacao 2 divisao_cima = cima / 2 divisao_baixo = baixo / 2 #Resultado final = (divisao_cima / 2) / (divisao_baixo / 2) print(f'Resultado: {final}')
[ "temis2st@gmail.com" ]
temis2st@gmail.com
36d8f9f73cadb080f774863da3d6235f3ddabd0a
e0b48bcc55dafe59f0032a6fea2c8da770d849af
/Text Processing - exercise/winning ticket.py
be4390c34f87ed0cb4d6ff894a8b5f3eb41cff7c
[ "MIT" ]
permissive
DiyanKalaydzhiev23/fundamentals---python
a80bc9308aad87902e3fcd4e61cdd4e2c47853df
7fa032d9a3270648ffa383bb00dad8e51613189d
refs/heads/main
2023-03-30T21:49:56.244273
2021-04-02T11:17:17
2021-04-02T11:17:17
353,996,815
1
0
null
null
null
null
UTF-8
Python
false
false
1,438
py
tickets = input().split(",") for ticket in tickets: result = "" ticket = ticket.strip() symbol = None current_count = 0 if len(ticket) == 20: first_half = ticket[:int(len(ticket)/2)] second_half = ticket[int(len(ticket)/2):] monkey_a = first_half.count("@") hashtag = first_half.count("#") dollar = first_half.count("$") house = first_half.count("^") if monkey_a >= 6: symbol = "@" current_count = monkey_a elif hashtag >= 6: symbol = "#" current_count = hashtag elif dollar >= 6: symbol = "$" current_count = dollar elif house >= 6: symbol = "^" current_count = house if symbol: count_symbol = second_half.count(symbol) if current_count + count_symbol == 20: result = f'ticket "{ticket}" - 10{symbol} Jackpot!' elif count_symbol >= current_count: result = f'ticket "{ticket}" - {current_count}{symbol}' elif current_count > count_symbol: result = f'ticket "{ticket}" - {count_symbol}{symbol}' elif count_symbol < 6 or current_count < 6: result = f'ticket "{ticket}" - no match' else: result = f'ticket "{ticket}" - no match' else: result = "invalid ticket" print(result)
[ "diankostadenov@gmail.com" ]
diankostadenov@gmail.com
81f17da771fdcef8276e652e023b8ddbd74492d3
2bcc6c45a28251dcde72bb8b003b5592350dc208
/universities/models.py
3c4e775e2528b5a5bc1a43893c40f159d6d754a7
[]
no_license
amanjhurani/university_dost
153d1a245df4338be60df3e9980e0238408e40ad
41f6119c88d36f0153fbf1a5be1913e2c45d9751
refs/heads/master
2021-10-08T22:23:42.252577
2018-12-18T11:22:10
2018-12-18T11:22:10
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,426
py
from django.urls import reverse from django.db import models from django.db.models.signals import pre_save from config.utils import (upload_university_logo_path, upload_university_cover_path, upload_course_cover_path, upload_subject_cover_path, unique_slug_generator,) class University(models.Model): # Fields name = models.CharField(max_length=128) university_code = models.CharField(max_length=8) description = models.TextField() founded = models.DateField() address = models.TextField() phone = models.CharField(max_length=20) logo = models.ImageField(upload_to=upload_university_logo_path, null=True, blank=True) cover = models.ImageField( upload_to=upload_university_cover_path, null=True, blank=True) class Meta: ordering = ('-pk',) verbose_name_plural = "universities" def __str__(self): return self.name def get_absolute_url(self): return reverse('universities_university_detail', args=(self.pk,)) def get_update_url(self): return reverse('universities_university_update', args=(self.pk,)) class Course(models.Model): # Choices COURSE_TYPE_CHOICES = ( ('full-time', 'Full-Time'), ('part-time', 'Part-Time'), ) DEGREE_TYPE_CHOICES = ( ('be', 'Bachelor of Engineering'), ('btech', 'Bachelor of Technology'), ) # Fields name = models.CharField(max_length=128) course_type = models.CharField(max_length=12, choices=COURSE_TYPE_CHOICES) degree_type = models.CharField(max_length=32, choices=DEGREE_TYPE_CHOICES) years = models.IntegerField() description = models.TextField() course_code = models.CharField(max_length=128) slug = models.SlugField(blank=True, unique=True) cover = models.ImageField(upload_to=upload_course_cover_path, null=True, blank=True) # Relationship Fields university = models.ForeignKey( University, on_delete=models.CASCADE ) class Meta: ordering = ('-pk',) def save(self, *args, **kwargs): if len(self.course_code.split('-')) > 1: self.course_code = self.course_code.split('-')[1] self.course_code = '{}-{}'.format( self.university.university_code, self.course_code ) super(Course, self).save(*args, **kwargs) def __str__(self): return self.name+"-"+self.university.university_code def get_absolute_url(self): return reverse('universities_course_detail', args=(self.slug,)) def get_update_url(self): return reverse('universities_course_update', args=(self.slug,)) def course_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(course_pre_save_receiver, sender=Course) class Subject(models.Model): # Fields name = models.CharField(max_length=128) semester = models.IntegerField(default=2) # remove default in production year = models.IntegerField() subject_code = models.CharField(max_length=128, blank=True, null=True) slug = models.SlugField(blank=True, unique=True) cover = models.ImageField(upload_to=upload_subject_cover_path, null=True, blank=True) # Relationship Fields course = models.ForeignKey( Course, on_delete=models.CASCADE ) class Meta: ordering = ('-pk',) def save(self, *args, **kwargs): if len(self.subject_code.split('-')) > 2: self.subject_code = self.subject_code.split('-')[2] self.subject_code = '{}-{}'.format( self.course.course_code, self.subject_code ) super(Subject, self).save(*args, **kwargs) def __str__(self): return self.name def get_absolute_url(self): return reverse('universities_subject_detail', args=(self.slug,)) def get_update_url(self): return reverse('universities_subject_update', args=(self.slug,)) def subject_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(subject_pre_save_receiver, sender=Subject)
[ "dhaval.savalia6@gmail.com" ]
dhaval.savalia6@gmail.com
7b2d1c35a886b772ed27df72b7a0557071802538
add203bbb92cfce011f61334f7dfc3092a85618d
/tutorials/tutorial_8.py
57ca6a4a3d268f88a90ca1f4a29ecf0e98ec74b5
[]
no_license
katrinafyi/math3202
63e3e27ca21781bad5fc6c349283ff97b18c2e16
8bab9fc644e334db0dcc8365c03eb0ec382b6184
refs/heads/master
2022-05-21T22:17:47.119756
2019-06-14T03:52:15
2019-06-14T03:52:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,955
py
from functools import lru_cache import sys from typing import * @lru_cache(maxsize=2**15) def fib(n): if n == 0 or n == 1 or n == 2: return 1 return fib(n-1) + fib(n-2) passing = { 0: [0.2, 0.25, 0.1], 1: [0.3, 0.3, 0.3], 2: [0.35, 0.33, 0.4], 3: [0.38, 0.35, 0.45], 4: [0.4, 0.38, 0.5] } @lru_cache(maxsize=2**10) def _solve_study(hours: int, subject: int): if hours == 0 or subject > 2: return (1, ()) min_prob = float('inf') min_x = None for x in range(0, hours+1): # x = hours at this subject _p, _x = _solve_study(hours-x, subject+1) p = (1-passing[x][subject])*_p if p < min_prob: min_prob = p min_x = (x, ) + _x return (min_prob, min_x) def studying(): return _solve_study(4, 0) def _vladimir(games: int, delta: int): if games >= 2: if delta > 0: return (1, 'win') elif delta < 0: return (0, 'lose') return (0.45, 'bold') bold = (0.45*_vladimir(games+1, delta+1)[0] + 0.55*_vladimir(games+1, delta-1)[0], 'bold') cons = (0.9*_vladimir(games+1, delta)[0] + 0.1*_vladimir(games+1, delta-1)[0], 'cons') return max(bold, cons) values = [25, 12, 8] sizes = [7, 4, 3] @lru_cache() def knapsack(item: int, space: int): if space == 0 or item > 2: return (0, ()) max_value = 0 max_items = () for n in range(space): # number of item 'i' to put in knapsack if n*sizes[item] > space: break v, i = knapsack(item+1, space-n*sizes[item]) val = n*values[item] + v if val > max_value: max_value = val max_items = (n, ) + i return (max_value, max_items) if __name__ == '__main__': # print(knapsack(0, 20)) print(knapsack.cache_info()) print(_vladimir(0, 0)) # print(studying()) # print(_solve_study.cache_info()) # print(fib(int(sys.argv[1])))
[ "kenton_lam@outlook.com" ]
kenton_lam@outlook.com
8e0702e1d4d0414446854a9adc75ee8f4be26b0b
d9767e1809bba642dba63c4f2c6a81d256840e96
/walmart_log/walmart_log/tasks.py
56a49c70dc54b4f66c934f5dff505e96eeb0ee33
[]
no_license
fernandochimi/walmart-log
7a342681b11b153d2a025e41d0d9e2a484a46eac
ab177fb7c6847dd6a26378289043af77ef6514a7
refs/heads/master
2021-01-10T11:26:39.253375
2016-01-10T20:58:43
2016-01-10T20:58:43
49,100,353
0
0
null
null
null
null
UTF-8
Python
false
false
1,431
py
# coding: utf-8 import logging from decimal import Decimal from settings import celery_app from models import City, Map, Transport logger = logging.getLogger('walmart_log.walmart_log.tasks') @celery_app.task def create_map(map_info): logger.info(u"Start creation of city {0}".format(map_info['city_origin'])) city_origin, created = City.objects.get_or_create( name=map_info['city_origin'], ) logger.info( u"City {0} created with success".format(map_info['city_origin'])) logger.info( u"Start creation of city {0}".format(map_info['city_destiny'])) city_destiny, created = City.objects.get_or_create( name=map_info['city_destiny'], ) logger.info( u"City {0} created with success".format(map_info['city_destiny'])) logger.info( u"Start creation of Map {0}".format(map_info['name'])) route_map, created = Map.objects.get_or_create( name=map_info['name'], transport=Transport.objects.get(sign=map_info['transport_sign']), city_origin=City.objects.get(slug=city_origin.slug), city_destiny=City.objects.get(slug=city_destiny.slug), logistic_order=", ".join([i for i in map_info['logistic_order']]), total_distance=map_info['total_distance'], gas_value=Decimal(map_info['gas_value'].replace(",", "."))) logger.info( u"Map {0} created with success".format(map_info['name']))
[ "fernando.chimicoviaki@gmail.com" ]
fernando.chimicoviaki@gmail.com
d3996bd212f520fabe230f80e82e4c01187d25cd
8bda8911512f1c454f5e75ef36f3d828661b1479
/dynamic_programming_01/test08_01.py
b39c1aa6f1bf423f93f65d010174b333142a1605
[]
no_license
choijaehoon1/backjoon
0f5909a1e1d416f8f431d6b986754af7eb6a3396
a0411dba08c057a312733e38683246162256e61d
refs/heads/master
2023-02-26T12:28:33.733297
2021-02-05T13:28:33
2021-02-05T13:28:33
280,430,716
0
0
null
null
null
null
UTF-8
Python
false
false
292
py
n = int(input()) dp = [n] cnt = 0 while True: if 1 in dp: print(cnt) break s = [] for i in dp: if i % 3 == 0: s.append(i/3) if i % 2 == 0: s.append(i/2) s.append(i-1) dp = s cnt+=1
[ "wogns_20@naver.com" ]
wogns_20@naver.com
1d110f890d16ed696a16a280f312e39a71700f9e
2dc75dd56b09df32501be9b9fd9005a842461a2d
/10_image.py
e337a4da6daf2f6c681e4ee8c997cdbd7556103f
[]
no_license
virus-warnning/pyopencl_samples
99ed0942f3cb84edb829a20a5cb1a53bdb5ee88a
898e1c07a138ef12a098821e0ea3b25b0ac5956d
refs/heads/master
2020-03-21T12:34:31.204406
2018-07-16T02:09:25
2018-07-16T02:09:25
138,560,081
6
1
null
2018-07-16T02:09:26
2018-06-25T07:40:55
Python
UTF-8
Python
false
false
1,673
py
import numpy as np import pyopencl as cl from PIL import Image def main(): CL_CODE = ''' constant float R_weight = 0.6; constant float G_weight = 0.4; constant float B_weight = 0.8; constant float ALL_weight = 1.8; constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP | CLK_FILTER_NEAREST; kernel void gray(__read_only image2d_t src_img, __write_only image2d_t dst_img) { int x = get_global_id(0); int y = get_global_id(1); int2 coord = (int2)(x, y); uint4 pixel = read_imageui(src_img, sampler, coord); uint g = (uint)((pixel[0] * R_weight + pixel[1] * G_weight + pixel[2] * B_weight) / ALL_weight); pixel = g; pixel[3] = 255; write_imageui(dst_img, coord, pixel); } ''' plf = [(cl.context_properties.PLATFORM, cl.get_platforms()[0])] ctx = cl.Context(dev_type=cl.device_type.GPU, properties=plf) prg = cl.Program(ctx, CL_CODE).build() queue = cl.CommandQueue(ctx) mf = cl.mem_flags src_raw = np.asarray(Image.open('res/tile-z16.png').convert("RGBA")) src_img = cl.image_from_array(ctx, src_raw, 4) (w, h, _) = src_raw.shape image_size = (w, h) fmt = cl.ImageFormat(cl.channel_order.RGBA, cl.channel_type.UNSIGNED_INT8) dst_img = cl.Image(ctx, mf.WRITE_ONLY, fmt, shape=image_size) dst_raw = np.empty_like(src_raw) prg.gray(queue, image_size, (1, 1), src_img, dst_img) cl.enqueue_copy(queue, dst_raw, dst_img, origin=(0, 0), region=image_size) Image.fromarray(dst_raw).show() if __name__ == '__main__': main()
[ "virus.warnning@gmail.com" ]
virus.warnning@gmail.com
377d188db6f366e82e58951d0e49caf5167dea20
77900cdd9a815caf1cd04705321ca93f5072179f
/Project2/Project2/.history/blog/views_20211114214141.py
f7c23d22e6dfcc088bf99445e8a5660e43de8a58
[]
no_license
Bom19990111/helloword_python
717799d994223d65de5adaeabecf396ff2bc1fb7
2ee2e67a60043f03c1ce4b070470c7d2dcdc72a7
refs/heads/master
2023-09-06T04:17:02.057628
2021-11-21T20:00:46
2021-11-21T20:00:46
407,063,273
0
1
null
2021-11-21T20:00:47
2021-09-16T07:18:35
Python
UTF-8
Python
false
false
469
py
from django.shortcuts import get_object_or_404, render from .models import Blog # Create your views here. def base(request): return render(request, 'blog/base.html') def all_blogs(request): blogs = Blog.objects.filter(status=1).order_by('-created_on') return render(request, 'blog/base.html', {'blogs': blogs}) def detail(request, slug): blog = get_object_or_404(Blog, slug=slug) return render(request, 'blog/detail.html', {'blog': blog})
[ "phanthituyngoc1995@gmail.com" ]
phanthituyngoc1995@gmail.com
f1b7ac1fe581dee52dee908d0d6647e440ded070
de56b7409521bec01709042fb6ba8d7b49c066bc
/programmers/level2/후보키.py
334ca7d96c4ef6517779229492bcd09cf42b2d86
[]
no_license
hodurie/Algorithm
40595c836febef815eff80585765a21a8cc299f1
f0a72afd65d078661f3e8921de61d8c61ac06d89
refs/heads/master
2023-07-26T04:29:59.181987
2021-09-06T11:44:39
2021-09-06T11:44:39
264,898,915
0
0
null
null
null
null
UTF-8
Python
false
false
638
py
from itertools import combinations def solution(relation): n_row = len(relation) n_col = len(relation[0]) candidates = [] for i in range(1, n_col + 1): candidates.extend(combinations(range(n_col), i)) unique = [] for cand in candidates: temp = [tuple([row[c] for c in cand]) for row in relation] if len(set(temp)) == n_row: unique.append(cand) res = set(unique) for i in range(len(unique)): for j in range(i + 1, len(unique)): if len(unique[i]) == len(set(unique[i]) & set(unique[j])): res.discard(unique[j]) return len(res)
[ "hodurie@gmail.com" ]
hodurie@gmail.com
af7196f7cedb5320794c7eb948e77943bfabd18e
03e3138f99f275d15d41a5c5bfb212f85d64d02e
/source/res/scripts/common/soft_exception.py
d7c28f2b1525c2103a23b84ce6b40f84d575eb4a
[]
no_license
TrenSeP/WorldOfTanks-Decompiled
e428728e7901146d0b599d02c930d70532232a97
1faa748acec1b7e435b657fd054ecba23dd72778
refs/heads/1.4.1
2020-04-27T08:07:49.813023
2019-03-05T17:37:06
2019-03-05T17:37:06
174,159,837
1
0
null
2019-03-06T14:33:33
2019-03-06T14:24:36
Python
UTF-8
Python
false
false
149
py
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/common/soft_exception.py class SoftException(Exception): pass
[ "StranikS_Scan@mail.ru" ]
StranikS_Scan@mail.ru
f5fb11850e71df84c187a363c0a4cc238b3e148a
1bfa884daea72f461341640b3d6a98f89bba3790
/core/DataController.py
97e1de4661dbc08acef34d907e0c21c75d26eb2c
[]
no_license
berendkleinhaneveld/data-inspector
6b9fa3d1bbcea0e8917d25a7e36f52a4be5d5cde
1f246f00c8f177725594d6d188c43d0664a1be6a
refs/heads/master
2021-01-25T00:57:23.282366
2017-06-18T20:00:56
2017-06-18T20:00:56
94,709,452
0
0
null
null
null
null
UTF-8
Python
false
false
1,009
py
""" DataController :Authors: Berend Klein Haneveld """ class DataController(object): """ DataController is the base interface for the reader and writer. """ def __init__(self): super(DataController, self).__init__() self.supportedExtensions = [] def is_extension_supported(self, extension): """ :type extension: basestring :rtype: bool """ result = False for ext in self.supportedExtensions: if ext == extension: result = True break return result def get_supported_extensions_as_string(self): """ Create string representation of all the supported file extensions. It will be formatted as follows: '*.mbr *.dcm' :rtype: basestr """ stringRepresentation = "" for extension in self.supportedExtensions: stringRepresentation += ("*." + extension + " ") return stringRepresentation
[ "berendkleinhaneveld@gmail.com" ]
berendkleinhaneveld@gmail.com
66a6a8b3655e657f9bb763cd704c462ab3dc0519
abf006d9b28fb50071e9fb921f29d6a4fc2bff1a
/remove_consec_duplicates.py
b93016e401f955a601c36ff955a65b83ef9b4708
[]
no_license
bhrigu123/interview_prep_python
fc4a07beab5c682c5ee26437c86ec82ff771b27b
1ae6419ba28504b79fb50d14917a87346167fce4
refs/heads/master
2021-01-12T12:10:59.225300
2016-10-30T06:21:58
2016-10-30T06:21:58
72,336,570
0
1
null
2016-10-30T07:56:38
2016-10-30T07:56:37
null
UTF-8
Python
false
false
409
py
''' Remove consecutive duplicates from a string recursively. For example, convert "aabccba" to "abcba". ''' def remove_dups(arr, prev , current, result): if current == len(arr): return result if prev == -1 or arr[prev] != arr[current]: return remove_dups(arr,current, current+1, result+arr[current]) else: return remove_dups(arr, current, current+1, result) print remove_dups('aabccba', -1, 0, '')
[ "yask123@gmail.com" ]
yask123@gmail.com
ccb373fbc58c8fbb3cbf829d5d533a2487028a41
877992e90b8f5ff7a5541a97cb7af28e31da1ecb
/dwapp/permissions.py
592724f470785039ae6ced4a8b439dfed994d2a0
[]
no_license
devdw98/likelion-server5_hw
13ffd33a329773cf8f9266e2c475121485eadb8a
d0fb9bf9bd022ca40a90a71964f4ad7c5302a47a
refs/heads/master
2020-05-27T06:26:19.064979
2019-05-25T04:50:26
2019-05-25T04:50:26
188,521,335
0
0
null
null
null
null
UTF-8
Python
false
false
660
py
from rest_framework import permissions class IsAuthOrReadOnly(permissions.BasePermission): def has_permission(self, request, view): return request.user.is_authenticated #권한이 있는 사람만 게시글 보이도록 설정 def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True # 관리자만 삭제 가능 if request.method == 'DELETE': return request.user.is_superuser # 해당 글의 작성자일 경우에만 'PUT'요청 허용 if request.method == 'PUT': return obj.author == request.user
[ "devdw98@gmail.com" ]
devdw98@gmail.com
46b9f009b529f360ec45c1ed4a9c85514053858e
e00d41c9f4045b6c6f36c0494f92cad2bec771e2
/multimedia/misc/t1lib/actions.py
e1b9a1f36bdeb847eb86f804bc54c185880c4fdc
[]
no_license
pisilinux/main
c40093a5ec9275c771eb5fb47a323e308440efef
bfe45a2e84ea43608e77fb9ffad1bf9850048f02
refs/heads/master
2023-08-19T00:17:14.685830
2023-08-18T20:06:02
2023-08-18T20:06:02
37,426,721
94
295
null
2023-09-14T08:22:22
2015-06-14T19:38:36
Python
UTF-8
Python
false
false
707
py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Licensed under the GNU General Public License, version 3. # See the file http://www.gnu.org/licenses/gpl.txt from pisi.actionsapi import autotools from pisi.actionsapi import pisitools from pisi.actionsapi import get def setup(): pisitools.dosed("doc/Makefile.in", "dvips", "#dvips") pisitools.dosed("xglyph/xglyph.c", "\./\(t1lib\.config\)", "/etc/t1lib/\1") autotools.configure("--datadir=/etc \ --with-x \ --enable-static=no") def build(): autotools.make("without_doc") def install(): autotools.rawInstall("DESTDIR=%s" % get.installDIR()) pisitools.dodoc("Changes", "README*")
[ "muscnsl@hotmail.com" ]
muscnsl@hotmail.com
1f88e0bb68c835e5b159c878670f9039f6c42090
4cd62443b3cd918ed608ce0bcdefe8928f283af1
/book_codes/Odoo11DevelopmentCookbookSecondEdition_Codes/Chapter06/ch06_r09/some_model_ch06r09/models.py
5c67dc07a5ee78862a25dbe337301c6a7d70395a
[]
no_license
thienkimlove/odoo-league
e3f4eeec191e44037b515d60268c657bc0df161d
1812cf7623bdce8856dbf4bbd79d493294d04331
refs/heads/master
2020-03-15T23:59:33.352371
2018-05-15T11:15:07
2018-05-15T11:15:07
132,405,334
0
0
null
null
null
null
UTF-8
Python
false
false
324
py
from odoo import models, api class SomeModel(models.Model): _name = 'some.model' @api.model def get_email_addresses(self, partner): partner.ensure_one() return partner.mapped('child_ids.email') @api.model def get_companies(self, partners): return partners.mapped('parent_id')
[ "quan.dm@teko.vn" ]
quan.dm@teko.vn
7736c1f4ea4be3ed1c527edac2a321987b7ab8af
deecbbec8c61aa1d23c3cd612e081790b25b4d92
/shapesdf/datasets/cubes.py
60e87008eb8109c5969fb8a94e9ccc955d154255
[]
no_license
schardong/shape_sdf
f3c435498fdbff944645e95556bc1fb65076a9b9
0c241bd1fb565cc3ed6f62c4e878ecc6308f2471
refs/heads/master
2021-02-25T22:36:24.319909
2019-04-01T20:30:55
2019-04-01T20:30:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,468
py
import json import os import pickle import random import warnings import cv2 import numpy as np from matplotlib import pyplot as plt from PIL import Image, ImageFile from scipy.stats import special_ortho_group import scipy import trimesh from tqdm import tqdm from shapesdf.datasets.queries import (BaseQueries, TransQueries, get_trans_queries) from shapesdf.datasets import vertexsample from shapesdf.datasets.objutils import fast_load_obj ImageFile.LOAD_TRUNCATED_IMAGES = True class Cubes(): def __init__( self, size=1000, split='train', mini_factor=1): """ Dataset of cubes randomly rotated around their center """ self.split = split self.size = int(size * mini_factor) self.all_queries = [BaseQueries.objverts3d, BaseQueries.objfaces, BaseQueries.objpoints3d] trans_queries = get_trans_queries(self.all_queries) self.all_queries.extend(trans_queries) self.name = 'cubes' self.mini_factor = mini_factor self.cam_intr = np.array([[480., 0., 128.], [0., 480., 128.], [0., 0., 1.]]).astype(np.float32) self.cam_extr = np.array([[1., 0., 0., 0.], [0., -1., 0., 0.], [0., 0., -1., 0.]]).astype(np.float32) self.load_dataset() def load_dataset(self): all_vertices = [] _, faces = _create_cube() self.faces = faces for sample_idx in range(self.size): vertices, _ = _create_cube() all_vertices.append(vertices) self.objverts3d = all_vertices def get_obj_verts_faces(self, idx): faces = self.faces vertices = self.objverts3d[idx] return vertices, faces def get_objpoints3d(self, idx, point_nb=600): points = vertexsample.points_from_mesh(self.faces, self.objverts3d[idx], vertex_nb=point_nb) return points def __len__(self): return self.size def _create_cube(center=True, random_rot=True): vertices = np.array([[0,0,0], [1,0,0], [1,1,0], [0,1,0], [0,1,1], [1,1,1], [1,0,1], [0,0,1]]) faces = np.array([[0, 2, 1], [0, 3, 2], [2, 3, 4], [2, 4, 5], [1,2,5], [1,5,6], [0, 7,4], [0, 4, 3], [5, 4, 7], [5, 7, 6], [0, 6, 7], [0, 1, 6]]) if center: vertices = vertices - 0.5 if random_rot: rot_mat = special_ortho_group.rvs(3) vertices = rot_mat.dot(vertices.transpose()).transpose() return vertices, faces
[ "yanahasson@gmail.com" ]
yanahasson@gmail.com
7c9099a51045358090f90446539a7818e51d7e84
2cc3aed1b5dfb91e3df165144d95c01a495bd54b
/297-Serialize-and-Deserialize-Binary-Tree.py
19411dc8312cf42760e44c9c7221a0098d24cdad
[]
no_license
listenviolet/leetcode
f38e996148cb5d4be8f08286daac16243b3c30e4
0c1efcbfd35e5ef036ec1ccd0c014cd7baf2ed2b
refs/heads/master
2020-05-01T07:35:23.462429
2019-12-11T12:44:32
2019-12-11T12:44:32
177,354,773
0
0
null
null
null
null
UTF-8
Python
false
false
2,616
py
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def child(root): if root is None: str.append("#") return else: str.append(root.val) child(root.left) child(root.right) str = [] child(root) return str def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ def child(): val = next(vals) if val == "#": return None root = TreeNode(int(val)) root.left = child() root.right = child() return root if not data: return None vals = iter(data) return child() # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root)) # Description: # Serialization is the process of converting a data structure or object # into a sequence of bits so that it can be stored in a file or memory buffer, # or transmitted across a network connection link # to be reconstructed later in the same or another computer environment. # Design an algorithm to serialize and deserialize a binary tree. # There is no restriction on how your serialization/deserialization algorithm should work. # You just need to ensure that a binary tree can be serialized to a string # and this string can be deserialized to the original tree structure. # Example: # You may serialize the following tree: # 1 # / \ # 2 3 # / \ # 4 5 # as "[1,2,3,null,null,4,5]" # Clarification: Just the same as how LeetCode OJ serializes a binary tree. # You do not necessarily need to follow this format, # so please be creative and come up with different approaches yourself. # Note: Do not use class member/global/static variables to store states. # Your serialize and deserialize algorithms should be stateless. # Solution: # Note: # 不可以直接定义类成员str,否则,第一次试验后的结果会影响之后的结果 # 可以在类成员函数中定义,如上Str,这样每次调用都会清零更新 # 这里deseialize中使用了iter,可以依次获取data中下一个元素 # Beats: 97.42% # Runtime: 175ms # hard
[ "listenviolet@gmail.com" ]
listenviolet@gmail.com
b157670bf7aa6e5c3050a4be89d3c04d5a1c4851
bc7199ee3cb7139ac90788cd0469c91d48315797
/demo/assignments/string_pattern.py
bd98d2efd7e35fd9bad8f3cfa8051a913964e83a
[]
no_license
srikanthpragada/python_14_dec_2020
617039e15285d84c8503ba49994aec08096d46f9
78c046b4aaf9590211dea447c08507969e053e60
refs/heads/master
2023-02-24T17:41:41.807841
2021-02-01T02:17:40
2021-02-01T02:17:40
322,155,634
1
0
null
null
null
null
UTF-8
Python
false
false
210
py
s = "AB123433434Y" middle = s[2:-2] # Take everything except first two and last two chars if s[:2].isalnum() and s[-2:].isalpha() and middle.isdigit(): print("Valid Code") else: print("Invalid Code")
[ "srikanthpragada@gmail.com" ]
srikanthpragada@gmail.com
9a1b7f50b6d3b195c887d7396266d96a4eb3ed69
d5b8b495f3f2f664bb39ff6ed1347363a967fdc3
/democracy_club/apps/report_2016/management/commands/report_2016_make_graphs.py
43c6e3473a23f37450843adedb5c823589f6a2fc
[]
permissive
pmk01/Website
7ffbdd75eec5c5466d9b0961bdb3d8133a3214f9
1ae0fb4e1a0be0bf9597a0ab5dc49d9365cbe755
refs/heads/master
2021-01-26T04:15:58.310045
2020-02-17T08:22:31
2020-02-17T08:22:31
243,304,779
0
0
BSD-3-Clause
2021-01-12T14:06:58
2020-02-26T16:03:58
null
UTF-8
Python
false
false
634
py
import os from django.core.management.base import BaseCommand from report_2016 import graphs class Command(BaseCommand): def handle(self, **options): includes_path = os.path.join( os.path.dirname(graphs.__file__), 'templates', 'report_2016', 'includes', ) for graph in graphs.GRAPHS: include_name = os.path.join( includes_path, "_{}_graph.html".format(graph.name) ) html = graph().html with open(include_name, 'w') as include_file: include_file.write(html)
[ "sym.roe@talusdesign.co.uk" ]
sym.roe@talusdesign.co.uk
4770ddf69f56864cc61d5d1cddf2af2b2f414133
80ad6face806f8c187cb24cb705c6297d8578b78
/manage.py
6a3bdd9092b2112b53cd196aa49e3a62c8b271ac
[ "Apache-2.0" ]
permissive
timothyclemans/checklistsforglass
6d7a9e7fa0a7614b5cbec95bb760f70041029b8d
c21d9efacc4c2ff4642385543a069b2bc4963af1
refs/heads/master
2020-07-20T15:46:55.798073
2014-04-22T19:30:19
2014-04-22T19:30:19
null
0
0
null
null
null
null
UTF-8
Python
false
false
261
py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "checklistsforglass.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
[ "timothy.clemans@gmail.com" ]
timothy.clemans@gmail.com
55532829484e972d14cbc1f469f9c206703e7165
673e829dda9583c8dd2ac8d958ba1dc304bffeaf
/data/multilingual/Latn.WOL/Mono_12/pdf_to_json_test_Latn.WOL_Mono_12.py
2889f53a56c597117beb375fe0bfcd2930248af7
[ "BSD-3-Clause" ]
permissive
antoinecarme/pdf_to_json_tests
58bab9f6ba263531e69f793233ddc4d33b783b7e
d57a024fde862e698d916a1178f285883d7a3b2f
refs/heads/master
2021-01-26T08:41:47.327804
2020-02-27T15:54:48
2020-02-27T15:54:48
243,359,934
2
1
null
null
null
null
UTF-8
Python
false
false
303
py
import pdf_to_json as p2j import json url = "file:data/multilingual/Latn.WOL/Mono_12/udhr_Latn.WOL_Mono_12.pdf" lConverter = p2j.pdf_to_json.pdf_to_json_converter() lConverter.mImageHashOnly = True lDict = lConverter.convert(url) print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
[ "antoine.carme@laposte.net" ]
antoine.carme@laposte.net
f9bae2ba9cd2b934688b6c83464f55b61bfc1cd4
0377a4135f9e8940809a62186b229295bed9e9bc
/螺旋矩阵/螺旋矩阵.py
966888a17dfe7a89a40561f3fe0cdf84faa89183
[]
no_license
neko-niko/leetcode
80f54a8ffa799cb026a7f60296de26d59a0826b0
311f19641d890772cc78d5aad9d4162dedfc20a0
refs/heads/master
2021-07-10T10:24:57.284226
2020-09-13T11:28:45
2020-09-13T11:28:45
198,792,951
0
0
null
null
null
null
UTF-8
Python
false
false
1,547
py
# 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。 class Solution: def spiralOrder(self, matrix: list) -> list: row = len(matrix) if row == 0: return [] col = len(matrix[0]) if col == 0: return [] if col == 1 or row == 1: return matrix[0] if row == 1 else list(map(lambda x: x[0], matrix)) i = 0 res = [] while i * 2 < col and i * 2 < row: endX = col - i - 1 endY = row - i - 1 for j in range(i, endX + 1): res.append(matrix[i][j]) if endY > i: for j in range(i+1, endY + 1): res.append(matrix[j][endX]) if i < endX and i < endY: for j in reversed(range(i, endX)): res.append(matrix[endY][j]) if i + 1 < endY and i < endX: for j in reversed(range(i + 1, endY)): res.append(matrix[j][i]) i += 1 return res def solution2(self, matrix: list): res = [] while matrix: res += matrix.pop(0) if matrix and matrix[0]: for row in matrix: res.append(row.pop()) if matrix: res += matrix.pop()[: : -1] if matrix and matrix[0]: for row in matrix[: : -1]: res.append(row.pop(0)) return res
[ "2361253285@qq.com" ]
2361253285@qq.com
34dcfaa41df212b1ce5e031d33a33a26b397194b
e23a4f57ce5474d468258e5e63b9e23fb6011188
/140_gui/pyqt_pyside/examples/PyQt_PySide_book/003_Placing several components in the box/009_Components accordion/135_setCurrentWidget - toClass.py
42e277f6b86d022edcba2b9e87f9ad37c5e3b013
[]
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
862
py
def on_clicked(): toolBox.setCurrentWidget(label2) from PySide import QtCore, QtGui import sys class SampleWindow(QtGui.QWidget): def __init__(self): super(SampleWindow, self).__init__() self.setWindowTitle("Класс QToolBox") self.resize(300, 250) toolBox = QtGui.QToolBox() button = QtGui.QPushButton("Сделать вкладку 2 видимой") button.clicked.connect(on_clicked) label1 = QtGui.QLabel("Содержимое вкладки 1") label2 = QtGui.QLabel("Содержимое вкладки 2") toolBox.addItem(label1, "Вкладка &1") toolBox.addItem(label2, "Вкладка &2") toolBox.setCurrentIndex(0) vbox = QtGui.QVBoxLayout() vbox.addWidget(toolBox) vbox.addWidget(button) self.setLayout(vbox)
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
b3d0268258baf08fbc583b0c311b3b8a75435783
b4d25688cd86062d3877d1aaad85d4abde98aa96
/MultiSC/MultiServer/security/encryption.py
68681fc9599f185f75277034955a71c8a8b4a10c
[ "MIT" ]
permissive
hvuhsg/MultiSC
7ffced49f10c43d82f970c17a2911adbd3556ce6
079f7be1b8fed4938e6003a81e2d03a8ea03ffd4
refs/heads/master
2020-05-26T22:45:10.731554
2019-06-19T09:37:28
2019-06-19T09:37:28
188,402,849
8
0
MIT
2019-06-02T21:16:03
2019-05-24T10:29:16
Python
UTF-8
Python
false
false
1,004
py
from cryptography.fernet import Fernet as Fernet_class class Encryption: def __init__(self, key): self.key = key @staticmethod def new_key(): pass def encrypt(self, data) -> bytes: pass def decrypt(self, data) -> bytes: pass class Fernet(Fernet_class, Encryption): def __init__(self, key=None): self.have_key = False if key: self.have_key = True self.key = key super().__init__(self.key) def encrypt(self, data): if not self.have_key: raise ValueError("can't encrypt without key -> set key first") return super().encrypt(data) def decrypt(self, data): if not self.have_key: raise ValueError("can't decrypt without key -> set key first") return super().decrypt(data) def set_key(self, key): self.key = key self.have_key = True @staticmethod def new_key(): return super().generate_key()
[ "hvuhsg6@gmail.com" ]
hvuhsg6@gmail.com