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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e08fcd2d1e413bc7a3a92ee6303bb7e8cfd5379e
|
581b960e3782e6968c23a664567cf1e857161048
|
/20190505_pycon_plugins/code_pyplugs/plotters/line.py
|
cb0f32bc87907ba66f3c6c9b086fd2c2e61e74ee
|
[] |
no_license
|
gahjelle/talks
|
d6f04e0edf8ce15949120f715479c7e82de9d46c
|
d0423f46568b6495ee913f8a850c619c65c1214c
|
refs/heads/master
| 2023-04-30T16:21:18.801997
| 2023-04-23T18:39:29
| 2023-04-23T18:39:29
| 147,107,339
| 21
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 149
|
py
|
"""Plot a line plot"""
# Third party imports
import pyplugs
@pyplugs.register
def line(ax, data):
"""Plot a line plot"""
data.plot(ax=ax)
|
[
"geirarne@gmail.com"
] |
geirarne@gmail.com
|
bdc7c56228322a08b6c0e6e1e2705a7bb79dad5d
|
db863bdd3507bf53800368d88a887247ef4a7636
|
/Transaction/migrations/0009_auto_20210408_1019.py
|
55bea4125b4834ec2947a82808078a205c74bdd9
|
[] |
no_license
|
vikasjoshis001/yes_backend
|
ed116f774237517da23dc5b420d791cba33a3efa
|
97e071a4037f7020cc4bce667eee10e7294903f7
|
refs/heads/master
| 2023-08-01T03:27:40.521169
| 2021-09-15T09:16:29
| 2021-09-15T09:16:29
| 353,229,366
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 603
|
py
|
# Generated by Django 3.0.7 on 2021-04-08 10:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Transaction', '0008_auto_20210408_1015'),
]
operations = [
migrations.AlterField(
model_name='transactionhistorymodel',
name='transactionDate',
field=models.DateField(auto_now_add=True),
),
migrations.AlterField(
model_name='transactionhistorymodel',
name='transactionTime',
field=models.TimeField(auto_now_add=True),
),
]
|
[
"vikasjoshis001@gmail.com"
] |
vikasjoshis001@gmail.com
|
42b84294b85ec7fda3c05db22cbb46d5d6bec28e
|
462682b3b29304b561eaea3833c29e84d1e95c0e
|
/PythonTypes/ConsoleCode.py
|
46da9d7f5a7259f3b5872f29883a929d85b87cc7
|
[] |
no_license
|
ravi4all/PythonDecMorning
|
4452b8340ce0b4ab067bd769725c5a6f831b7f45
|
1e20da3c90d407dbef714770ad54e72f16be0eec
|
refs/heads/master
| 2021-09-02T11:01:28.686860
| 2018-01-02T05:05:06
| 2018-01-02T05:05:06
| 113,133,365
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,304
|
py
|
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> a = []
>>> a.append(1)
>>> a
[1]
>>> a.append(2)
>>> a
[1, 2]
>>> a.append("Hello")
>>> a
[1, 2, 'Hello']
>>> a = [1,2,3,10.5,"Hello",True]
>>> a[0]
1
>>> a[1]
2
>>> a[-1]
True
>>> a[-2]
'Hello'
>>> a[1:5]
[2, 3, 10.5, 'Hello']
>>> a[3][1:2]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
a[3][1:2]
TypeError: 'float' object is not subscriptable
>>> a[4][1:2]
'e'
>>> a.append(12)
>>> a
[1, 2, 3, 10.5, 'Hello', True, 12]
>>> a.append(13,14)
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
a.append(13,14)
TypeError: append() takes exactly one argument (2 given)
>>> a.append([13,14])
>>> a
[1, 2, 3, 10.5, 'Hello', True, 12, [13, 14]]
>>> a.extend([15,16,17])
>>> a
[1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16, 17]
>>> user = []
>>> user.extend(["Name"])
>>> user
['Name']
>>> user = {"Name" : ["Ram", "Shyam"]}
>>> user
{'Name': ['Ram', 'Shyam']}
>>> a
[1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16, 17]
>>> a.insert(0, "Bye")
>>> a
['Bye', 1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16, 17]
>>> a[0] = "Hi"
>>> a
['Hi', 1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16, 17]
>>> a.pop()
17
>>> a
['Hi', 1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15, 16]
>>> a.pop()
16
>>> a
['Hi', 1, 2, 3, 10.5, 'Hello', True, 12, [13, 14], 15]
>>> a.pop(4)
10.5
>>> a
['Hi', 1, 2, 3, 'Hello', True, 12, [13, 14], 15]
>>> a.remove(11)
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
a.remove(11)
ValueError: list.remove(x): x not in list
>>> a.remove(12)
>>> a
['Hi', 1, 2, 3, 'Hello', True, [13, 14], 15]
>>> len(a)
8
>>> a =[12,11,45,3,56,4,7,0,2,23]
>>> sorted(a)
[0, 2, 3, 4, 7, 11, 12, 23, 45, 56]
>>> sorted(a, reverse = True)
[56, 45, 23, 12, 11, 7, 4, 3, 2, 0]
>>> a
[12, 11, 45, 3, 56, 4, 7, 0, 2, 23]
>>> a.sort()
>>> a
[0, 2, 3, 4, 7, 11, 12, 23, 45, 56]
>>> 11 in a
True
>>> 'Hello' not in a
True
>>> 2 and 3 in a
True
>>> 2 or 3 in a
2
>>> b =(12,11,45,3,56,4,7,0,2,23)
>>> a
[0, 2, 3, 4, 7, 11, 12, 23, 45, 56]
>>> b
(12, 11, 45, 3, 56, 4, 7, 0, 2, 23)
>>> a[0] = 'Hi'
>>> a
['Hi', 2, 3, 4, 7, 11, 12, 23, 45, 56]
>>> b[0] = 'Hi'
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
b[0] = 'Hi'
TypeError: 'tuple' object does not support item assignment
>>> b
(12, 11, 45, 3, 56, 4, 7, 0, 2, 23)
>>> b[0]
12
>>> b[0:5]
(12, 11, 45, 3, 56)
>>> user = {"Name" : "Ram", "Age" : 20, "Num" : 89898979}
>>> user
{'Name': 'Ram', 'Age': 20, 'Num': 89898979}
>>> user[0]
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
user[0]
KeyError: 0
>>> user['Name']
'Ram'
>>> for data in user:
print(data)
Name
Age
Num
>>> user.keys()
dict_keys(['Name', 'Age', 'Num'])
>>> user.values()
dict_values(['Ram', 20, 89898979])
>>> for data in user.values:
print(data)
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
for data in user.values:
TypeError: 'builtin_function_or_method' object is not iterable
>>> for data in user.values():
print(data)
Ram
20
89898979
>>> user.items()
dict_items([('Name', 'Ram'), ('Age', 20), ('Num', 89898979)])
>>> for data in user.items():
print(data)
('Name', 'Ram')
('Age', 20)
('Num', 89898979)
>>> user
{'Name': 'Ram', 'Age': 20, 'Num': 89898979}
>>> user['Name'] = ['Ram']
>>> user
{'Name': ['Ram'], 'Age': 20, 'Num': 89898979}
>>> user['Name']
['Ram']
>>> name = user['Name']
>>> name
['Ram']
>>> name.append('Shyam')
>>> user
{'Name': ['Ram', 'Shyam'], 'Age': 20, 'Num': 89898979}
>>> set_1 = {1,2,3,4,5,6}
>>> type(set_1)
<class 'set'>
>>> set_2 = {4,5,6,7,8,9}
>>> set_1.intersection(set_2)
{4, 5, 6}
>>> a
['Hi', 2, 3, 4, 7, 11, 12, 23, 45, 56]
>>> set(a)
{'Hi', 2, 3, 4, 7, 11, 12, 45, 23, 56}
>>> a
['Hi', 2, 3, 4, 7, 11, 12, 23, 45, 56]
>>> set(b)
{0, 2, 3, 4, 7, 11, 12, 45, 23, 56}
>>> set_a = set(a)
>>> set_b = set(b)
>>> set_a.intersection(set_b)
{2, 3, 4, 7, 11, 12, 45, 23, 56}
>>>
|
[
"noreply@github.com"
] |
ravi4all.noreply@github.com
|
ec95f318cee2e9f5dd28e4996ed3789e99994eb5
|
bc41457e2550489ebb3795f58b243da74a1c27ae
|
/python/ghtc2012.py
|
1eacd49e770cdbff348b5fe621063937f34b7f50
|
[] |
no_license
|
SEL-Columbia/ss_sql_views
|
28a901d95fe779b278d2a51aec84d6bf51245c02
|
d146fd96849a4d165f3dc3f197aadda804a2f60a
|
refs/heads/master
| 2021-01-01T19:35:18.999147
| 2012-05-10T18:43:36
| 2012-05-10T18:43:36
| 3,020,367
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,797
|
py
|
import offline_gateway as og
import datetime as dt
import matplotlib.pyplot as plt
import pandas as p
'''
25 "ml00"
164 "ml01"
143 "ml02"
213 "ml03"
192 "ml04"
57 "ml05"
70 "ml06"
102 "ml07"
123 "ml08"
'''
# todo: fit solar generation over same time period
'''
print
print 'ml03'
og.analyze_load_profile_curve(213, date_start, date_end)
og.plot_load_profile_curve_to_file(213, date_start, date_end, 'ml03-ldc.pdf')
print
print 'ml05'
og.analyze_load_profile_curve(57, date_start, date_end)
og.plot_load_profile_curve_to_file(57, date_start, date_end, 'ml05-ldc.pdf')
print
print 'ml06'
og.analyze_load_profile_curve(70, date_start, date_end)
og.plot_load_profile_curve_to_file(70, date_start, date_end, 'ml06-ldc.pdf')
print
print 'ml07'
og.analyze_load_profile_curve(102, date_start, date_end)
og.plot_load_profile_curve_to_file(102, date_start, date_end, 'ml07-ldc.pdf')
print
print 'ml08'
og.analyze_load_profile_curve(123, date_start, date_end)
og.plot_load_profile_curve_to_file(123, date_start, date_end, 'ml08-ldc.pdf')
'''
def plot_two_ldc(date_start, date_end):
f, ax = plt.subplots(1, 1)
og.plot_load_profile_curve_to_axis(57, date_start, date_end, ax, label='Lighting')
og.plot_load_profile_curve_to_axis(123, date_start, date_end, ax, label='Lighting and Freezer')
ax.legend()
ax.set_xlabel('Fraction of Availability')
ax.grid(True, linestyle='-', color='#cccccc')
plt.savefig('two_ldc.pdf')
def plot_two_bulb_profile(date_start, date_end):
og.plot_hourly_power_profile(230, date_start, date_end, 'two_bulb_profile.pdf', title=False)
def plot_freezer_profile(date_start, date_end):
og.plot_hourly_power_profile(96, date_start, date_end, 'freezer_profile.pdf', title=False)
def tbl_efficiency(date_start, date_end):
print '% tbl_efficiency'
print '%', date_start
print '%', date_end
dl = []
for meter, cid in [('ml05', 57), ('ml06', 70), ('ml07', 102), ('ml08', 123)]:
d = og.analyze_load_profile_curve(cid, date_start, date_end)
og.plot_load_profile_curve_to_file(cid, date_start, date_end, meter+'-ldc.pdf')
dl.append(d)
df = p.DataFrame(dl)
for row in df.index:
print '%.2f' % df.ix[row]['capacity_factor'],
print '&',
print df.ix[row]['circuit_id'],
print '\\\\'
if __name__ == '__main__':
date_start = dt.datetime(2012, 2, 15)
date_end = dt.datetime(2012, 4, 15)
#plot_two_ldc(date_start, date_end)
date_start = dt.datetime(2012, 1, 1)
date_end = dt.datetime(2012, 3, 1)
#plot_two_bulb_profile(date_start, date_end)
#plot_freezer_profile(dt.datetime(2012, 2, 1), dt.datetime(2012, 4, 15))
date_start = dt.datetime(2012, 2, 15)
date_end = dt.datetime(2012, 4, 15)
tbl_efficiency(date_start, date_end)
|
[
"danielrsoto@gmail.com"
] |
danielrsoto@gmail.com
|
cbbc41a4f95e61fcc71ca12aa4a08db0df652e6f
|
1e4b37d3bfa9ecba22517548c0577dee76704d8f
|
/temp_ws/src/sawyer_velctrlsim-master/src/ref_rand_joint_state_pub.py
|
4cb127b09acdbc0ce1e8873cbdce164979627504
|
[] |
no_license
|
mch5048/catkin_ws_4rl
|
0aa19dc46effd2ae7941cc1e0b6d824f595d8574
|
2201d3b353da3b380dc7330ae5651e9640cd3408
|
refs/heads/master
| 2020-04-19T01:42:56.013573
| 2019-02-21T01:09:13
| 2019-02-21T01:09:13
| 167,879,885
| 0
| 0
| null | 2019-02-21T01:09:14
| 2019-01-28T01:27:31
|
Makefile
|
UTF-8
|
Python
| false
| false
| 1,350
|
py
|
#!/usr/bin/env python
import rospy
import numpy as np
from sensor_msgs.msg import JointState
class RandomJointState:
def __init__(self):
rospy.init_node('ref_js_randomizer')
self.pub = rospy.Publisher('/ref_sawyer/joint_states',JointState, queue_size=10)
self.ref_js = JointState()
self.ref_js.name = ['right_j0', 'head_pan', 'right_j1', 'right_j2', \
'right_j3', 'right_j4', 'right_j5', 'right_j6']
j_ranges = [[-3.05, 3.05],\
[0,0],\
[-3.81,2.27],\
[-3.04,3.04],\
[-3.04,3.04],\
[-2.98,2.98],\
[-2.98,2.98],\
[-4.71,4.71]]
joints = np.ndarray.tolist(np.random.rand(8))
for i in range(len(joints)):
joints[i] = joints[i]*np.ptp(j_ranges[i])+j_ranges[i][0]
self.ref_js.position = joints
def pub_random_js(self):
self.ref_js.header.stamp = rospy.Time.now() #add timestamp to joint state msg
self.pub.publish(self.ref_js)
if __name__=='__main__':
try:
out = RandomJointState()
rate = rospy.Rate(10) #10Hz
while not rospy.is_shutdown():
out.pub_random_js()
rate.sleep()
except rospy.ROSInterruptException:
raise e
|
[
"mch5048@korea.ac.kr"
] |
mch5048@korea.ac.kr
|
9c9fb00c316199447af33e79a78359efcc6b08d9
|
1d2bbeda56f8fede69cd9ebde6f5f2b8a50d4a41
|
/medium/python/c0075_142_linked-list-cycle-ii/00_leetcode_0075.py
|
439484c8b6b418348aa22f97d0b9fbe24737d76b
|
[] |
no_license
|
drunkwater/leetcode
|
38b8e477eade68250d0bc8b2317542aa62431e03
|
8cc4a07763e71efbaedb523015f0c1eff2927f60
|
refs/heads/master
| 2020-04-06T07:09:43.798498
| 2018-06-20T02:06:40
| 2018-06-20T02:06:40
| 127,843,545
| 0
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 691
|
py
|
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#142. Linked List Cycle II
#Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
#Note: Do not modify the linked list.
#Follow up:
#Can you solve it without using extra space?
## Definition for singly-linked list.
## class ListNode(object):
## def __init__(self, x):
## self.val = x
## self.next = None
#class Solution(object):
# def detectCycle(self, head):
# """
# :type head: ListNode
# :rtype: ListNode
# """
# Time Is Money
|
[
"Church.Zhong@audiocodes.com"
] |
Church.Zhong@audiocodes.com
|
65a545ee33b66672c39fab64dbefac761dbab3cf
|
6fbd633d0c7c831ca8217788dcd3e82cd26dd72d
|
/src/pkgcheck/const.py
|
87135e5e7de36a83947d0af03c71d28bba8104a3
|
[
"BSD-3-Clause"
] |
permissive
|
chutz/pkgcheck
|
b93724cc0c0dd3d17e49c734faf019b2ad67b0c7
|
714c016381b53246b449dd9c3116811e50db744f
|
refs/heads/master
| 2020-09-22T13:46:59.498632
| 2019-12-01T04:05:35
| 2019-12-01T04:06:11
| 225,225,319
| 0
| 0
|
BSD-3-Clause
| 2019-12-01T20:22:06
| 2019-12-01T20:22:05
| null |
UTF-8
|
Python
| false
| false
| 3,343
|
py
|
"""Registration for keywords, checks, and reporters."""
import inspect
import os
import pkgutil
import sys
from functools import partial
from importlib import import_module
from snakeoil import mappings
from . import __title__, checks, reporters, results
_reporoot = os.path.realpath(__file__).rsplit(os.path.sep, 3)[0]
_module = sys.modules[__name__]
try:
# This is a file written during installation;
# if it exists, we defer to it. If it doesn't, then we're
# running from a git checkout or a tarball.
from . import _const as _defaults
except ImportError:
_defaults = object()
def _GET_CONST(attr, default_value, allow_environment_override=False):
consts = mappings.ProxiedAttrs(_module)
is_tuple = not isinstance(default_value, str)
if is_tuple:
default_value = tuple(x % consts for x in default_value)
else:
default_value %= consts
result = getattr(_defaults, attr, default_value)
if allow_environment_override:
result = os.environ.get(f'PKGCHECK_OVERRIDE_{attr}', result)
if is_tuple:
result = tuple(result)
return result
def _find_modules(module):
if getattr(module, '__path__', False):
for _imp, name, _ in pkgutil.walk_packages(module.__path__, module.__name__ + '.'):
# skip "private" modules
if name.rsplit('.', 1)[1][0] == '_':
continue
try:
yield import_module(name)
except ImportError as e:
raise Exception(f'failed importing {name!r}: {e}')
else:
yield module
def _find_classes(module, matching_cls):
for _name, cls in inspect.getmembers(module):
if (inspect.isclass(cls) and issubclass(cls, matching_cls)
and cls.__name__[0] != '_'):
yield cls
def _find_obj_classes(module_name, matching_cls):
module = import_module(f'.{module_name}', __title__)
# skip top-level, base classes
base_classes = {matching_cls.__name__: matching_cls}
if os.path.basename(module.__file__) == '__init__.py':
for cls in _find_classes(module, matching_cls):
base_classes[cls.__name__] = cls
classes = {}
for m in _find_modules(module):
for cls in _find_classes(m, matching_cls):
if cls.__name__ in base_classes:
continue
if cls.__name__ in classes and classes[cls.__name__] != cls:
raise Exception(f'object name overlap: {cls} and {classes[cls.__name__]}')
classes[cls.__name__] = cls
return classes
def _GET_VALS(attr, func):
try:
result = getattr(_defaults, attr)
except AttributeError:
result = func()
return result
REPO_PATH = _GET_CONST('REPO_PATH', _reporoot, allow_environment_override=True)
DATA_PATH = _GET_CONST('DATA_PATH', '%(REPO_PATH)s/data')
try:
KEYWORDS = mappings.ImmutableDict(_GET_VALS(
'KEYWORDS', partial(_find_obj_classes, 'checks', results.Result)))
CHECKS = mappings.ImmutableDict(_GET_VALS(
'CHECKS', partial(_find_obj_classes, 'checks', checks.Check)))
REPORTERS = mappings.ImmutableDict(_GET_VALS(
'REPORTERS', partial(_find_obj_classes, 'reporters', reporters.Reporter)))
except SyntaxError as e:
raise SyntaxError(f'invalid syntax: {e.filename}, line {e.lineno}')
|
[
"radhermit@gmail.com"
] |
radhermit@gmail.com
|
c6ef643551dfb8508cda8c878e72f447e75cb54d
|
bec8f33002130d8395f4ac4f0c74b785aa22cac5
|
/appium/options/ios/xcuitest/other/command_timeouts_option.py
|
420b350397bc4e77af147af84a13acbd818a8ad0
|
[
"Apache-2.0"
] |
permissive
|
appium/python-client
|
1c974fdf1ac64ce4ac37f3fc8c0a3e30c186d3ca
|
2e49569ed45751df4c6953466f9769336698c033
|
refs/heads/master
| 2023-09-01T22:14:03.166402
| 2023-09-01T11:52:27
| 2023-09-01T11:52:27
| 18,525,395
| 1,588
| 606
|
Apache-2.0
| 2023-09-10T02:00:09
| 2014-04-07T17:01:35
|
Python
|
UTF-8
|
Python
| false
| false
| 2,627
|
py
|
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from datetime import timedelta
from typing import Dict, Optional, Union
from appium.options.common.supports_capabilities import SupportsCapabilities
COMMAND_TIMEOUTS = 'commandTimeouts'
class CommandTimeoutsOption(SupportsCapabilities):
@property
def command_timeouts(self) -> Optional[Union[Dict[str, timedelta], timedelta]]:
"""
Custom timeout(s) for WDA backend commands execution.
"""
value = self.get_capability(COMMAND_TIMEOUTS)
if value is None:
return None
if isinstance(value, dict):
return {k: timedelta(milliseconds=v) for k, v in value.items()}
return timedelta(milliseconds=int(value))
@command_timeouts.setter
def command_timeouts(self, value: Union[Dict[str, timedelta], timedelta, int]) -> None:
"""
Custom timeout for all WDA backend commands execution.
This might be useful if WDA backend freezes unexpectedly or requires too
much time to fail and blocks automated test execution.
Dictionary keys are command names which you can find in server logs. Look for
"Executing command 'command_name'" records.
Timeout value is expected to contain max duration to wait for
the given WDA command to be executed before terminating the session forcefully.
The magic 'default' key allows to provide the timeout for all other commands that
were not explicitly mentioned as dictionary keys
"""
if isinstance(value, dict):
self.set_capability(COMMAND_TIMEOUTS, {k: int(v.total_seconds() * 1000) for k, v in value.items()})
elif isinstance(value, timedelta):
self.set_capability(COMMAND_TIMEOUTS, f'{int(value.total_seconds() * 1000)}')
else:
self.set_capability(COMMAND_TIMEOUTS, value)
|
[
"noreply@github.com"
] |
appium.noreply@github.com
|
9f3e016075ca44f0a6162e23e5b74692c5851c57
|
6b1febf141315330fcb67495e094ff7aeb6520c8
|
/ajaxsite/mixins.py
|
f42c1cf1f8587b620de9f6014651869faba40358
|
[] |
no_license
|
anidem/ajax-setup
|
40a6ae856b0b3415ba3a2842f812c96d2b0978ef
|
bf5c9187eb878c627c5cb20a6e58a4e0e602be65
|
refs/heads/master
| 2021-01-10T20:38:22.928879
| 2014-11-17T18:13:46
| 2014-11-17T18:13:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 971
|
py
|
from django.http import JsonResponse
class AjaxableResponseMixin(object):
"""
Mixin to add AJAX support to a form.
Must be used with an object-based FormView (e.g. CreateView)
"""
def form_invalid(self, form):
response = super(AjaxableResponseMixin, self).form_invalid(form)
if self.request.is_ajax():
return JsonResponse(form.errors, status=400)
else:
return response
def form_valid(self, form):
# We make sure to call the parent's form_valid() method because
# it might do some processing (in the case of CreateView, it will
# call form.save() for example).
response = super(AjaxableResponseMixin, self).form_valid(form)
print 'AJAX Mixin: ', self.request.is_ajax()
if self.request.is_ajax():
data = {
'pk': self.object.pk,
}
return JsonResponse(data)
else:
return response
|
[
"richmedina@gmail.com"
] |
richmedina@gmail.com
|
3ac03889ebac07e88d1b65696d71d07c0ca04cb5
|
3bbe69481d294eba60f83639f3a9430fb8cda4d9
|
/feedback/views.py
|
69481acb6cf19ded68b141738fab0ae2af40b3df
|
[] |
no_license
|
ulugbek1999/ncd-cms
|
5e288f44b01387cd66a54d2dcaf1e0d288205bc4
|
dcb43bf65f0d6efcbf6481f5c9284c8c1a7c6b9d
|
refs/heads/master
| 2022-09-06T13:22:34.637080
| 2019-12-14T09:10:26
| 2019-12-14T09:10:26
| 204,455,916
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 615
|
py
|
from django.urls import reverse
from django.views.generic import TemplateView, ListView, View, DetailView
from .models import Feedback
from django.contrib.auth.mixins import LoginRequiredMixin
class FeedbackListView(LoginRequiredMixin, ListView):
template_name = 'feedback/list.html'
model = Feedback
context_object_name = 'feedbacks'
class FeedbackCreateView(LoginRequiredMixin, TemplateView):
template_name = 'feedback/create.html'
class FeedbackUpdateView(LoginRequiredMixin, DetailView):
template_name = 'feedback/update.html'
model = Feedback
context_object_name = 'feedback'
|
[
"kayrat.nazov@gmail.com"
] |
kayrat.nazov@gmail.com
|
11bb78f5bf946d78ca3589dc9dcad9baeaa919c9
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2462/60708/289131.py
|
444c31167f10af1ad63b76154f6c924656b18429
|
[] |
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
| 652
|
py
|
def find(list,l,r,index):
if(l>r):
return index
mid=(l+r)//2
if(list[mid]>list[mid-1] and list[mid]>list[mid+1]):
index=mid
find(list,l,mid-1,index)
return index
else:
index1=find(list,l,mid-1,index)
index2=find(list,mid+1,r,index)
if index1!=-1:
return index1
if index2!=-1:
return index2
else:
return -1
if __name__ == '__main__':
temp = input().split(",")
list = []
for item in temp:
list.append(int(item))
try:
print(find(list, 0, len(list) - 1,-1))
except BaseException:
print(1)
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
02cc23d4157b6b0f584b4183e57cb643b4c693e1
|
57870ba30e4c530482db3a2f182e6c037a010a01
|
/cauldron/test/test_reload.py
|
c9f2890cf6018d34bfe35ba78af77afa1113469a
|
[
"MIT"
] |
permissive
|
khemanta/cauldron
|
32e17b978a5856a4ac12bc79cdd23583207c0750
|
79ae3aa2cf919feb5c3365f85ae006075bec47e3
|
refs/heads/master
| 2021-01-11T14:25:16.416313
| 2017-02-08T23:12:24
| 2017-02-08T23:12:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 398
|
py
|
from cauldron.test import support
from cauldron.test.support import scaffolds
class TestReload(scaffolds.ResultsTest):
"""
"""
def test_reload(self):
"""
"""
r = support.run_command('open @examples:hello_cauldron')
r = support.run_command('reload')
self.assertFalse(r.failed, 'should not have failed')
support.run_command('close')
|
[
"swernst@gmail.com"
] |
swernst@gmail.com
|
f023f3dae9e638f1830edf280727cf851dbd9faa
|
fdb9b553a23647f7ea06f690613707c40b54902f
|
/src/main/resources/resource/Tracking/Tracking.py
|
870b67eea8d276da57bc8641d9971ca3702a1d76
|
[
"CC-BY-2.5",
"Apache-2.0"
] |
permissive
|
ShaunHolt/myrobotlab
|
d8d9f94e90457474cf363d36f4a45d396cfae900
|
92046d77abd560f0203050b3cccb21aa9df467f2
|
refs/heads/develop
| 2021-07-08T04:55:01.462116
| 2020-04-18T19:58:17
| 2020-04-18T19:58:17
| 122,795,957
| 0
| 0
|
Apache-2.0
| 2020-04-18T19:58:18
| 2018-02-25T01:37:54
|
Java
|
UTF-8
|
Python
| false
| false
| 2,158
|
py
|
# a minimal tracking script - this will start all peer
# services and attach everything appropriately
# change parameters depending on your pan tilt, pins and
# Arduino details
# all commented code is not necessary but allows custom
# options
port = "COM19" #change COM port to your own port
xServoPin = 13 #change this to the right servo pin if needed, for inmoov this is right
yServoPin = 12 #change this to the right servo pin if needed, for inmoov this is right
# create a servo controller and a servo
arduino = Runtime.start("arduino","Arduino")
xServo = Runtime.start("xServo","Servo")
yServo = Runtime.start("yServo","Servo")
# start optional virtual arduino service, used for test
#virtual=1
if ('virtual' in globals() and virtual):
virtualArduino = Runtime.start("virtualArduino", "VirtualArduino")
virtualArduino.connect(port)
arduino.connect(port)
xServo.attach(arduino.getName(), xServoPin)
yServo.attach(arduino.getName(), yServoPin)
tracker = Runtime.start("tracker", "Tracking")
opencv=tracker.getOpenCV()
# set specifics on each Servo
xServo.setMinMax(30, 150) #minimum and maximum settings for the X servo
# servoX.setInverted(True) # invert if necessary
xServo.setMinMax(30, 150) #minimum and maximum settings for the Y servo
# servoY.setInverted(True) # invert if necessary
# changing Pid values change the
# speed and "jumpyness" of the Servos
pid = tracker.getPID()
# these are default setting
# adjust to make more smooth
# or faster
pid.setPID("x",5.0, 5.0, 0.1)
pid.setPID("y",5.0, 5.0, 0.1)
# connect to the Arduino ( 0 = camera index )
tracker.connect(opencv, xServo, yServo)
opencv.broadcastState();
sleep(1)
# Gray & PyramidDown make face tracking
# faster - if you dont like these filters - you
# may remove them before you select a tracking type with
# the following command
# tracker.clearPreFilters()
# diffrent types of tracking
# lkpoint - click in video stream with
# mouse and it should track
# simple point detection and tracking
# tracker.startLKTracking()
# scans for faces - tracks if found
# tracker.findFace()
# tracker + facedetect : tracker.faceDetect(True)
tracker.faceDetect()
|
[
"grog@myrobotlab.org"
] |
grog@myrobotlab.org
|
11563a609e255317803e2b21817ec9e87f6efe33
|
7bededcada9271d92f34da6dae7088f3faf61c02
|
/pypureclient/flasharray/FA_2_19/models/directory.py
|
0a684f6248f887806fa3011cccd444893b0e0135
|
[
"BSD-2-Clause"
] |
permissive
|
PureStorage-OpenConnect/py-pure-client
|
a5348c6a153f8c809d6e3cf734d95d6946c5f659
|
7e3c3ec1d639fb004627e94d3d63a6fdc141ae1e
|
refs/heads/master
| 2023-09-04T10:59:03.009972
| 2023-08-25T07:40:41
| 2023-08-25T07:40:41
| 160,391,444
| 18
| 29
|
BSD-2-Clause
| 2023-09-08T09:08:30
| 2018-12-04T17:02:51
|
Python
|
UTF-8
|
Python
| false
| false
| 6,952
|
py
|
# coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.19
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flasharray.FA_2_19 import models
class Directory(object):
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'str',
'name': 'str',
'created': 'int',
'destroyed': 'bool',
'directory_name': 'str',
'file_system': 'FixedReference',
'path': 'str',
'space': 'Space',
'time_remaining': 'int',
'limited_by': 'LimitedBy'
}
attribute_map = {
'id': 'id',
'name': 'name',
'created': 'created',
'destroyed': 'destroyed',
'directory_name': 'directory_name',
'file_system': 'file_system',
'path': 'path',
'space': 'space',
'time_remaining': 'time_remaining',
'limited_by': 'limited_by'
}
required_args = {
}
def __init__(
self,
id=None, # type: str
name=None, # type: str
created=None, # type: int
destroyed=None, # type: bool
directory_name=None, # type: str
file_system=None, # type: models.FixedReference
path=None, # type: str
space=None, # type: models.Space
time_remaining=None, # type: int
limited_by=None, # type: models.LimitedBy
):
"""
Keyword args:
id (str): A globally unique, system-generated ID. The ID cannot be modified and cannot refer to another resource.
name (str): A user-specified name. The name must be locally unique and can be changed.
created (int): The managed directory creation time, measured in milliseconds since the UNIX epoch.
destroyed (bool): Returns a value of `true` if the managed directory has been destroyed and is pending eradication. The `time_remaining` value displays the amount of time left until the destroyed managed directory is permanently eradicated. Once the `time_remaining` period has elapsed, the managed directory is permanently eradicated and can no longer be recovered.
directory_name (str): The managed directory name without the file system name prefix. A full managed directory name is constructed in the form of `FILE_SYSTEM:DIR` where `FILE_SYSTEM` is the file system name and `DIR` is the value of this field.
file_system (FixedReference): The file system that this managed directory is in.
path (str): Absolute path of the managed directory in the file system.
space (Space): Displays size and space consumption information.
time_remaining (int): The amount of time left, measured in milliseconds until the destroyed managed directory is permanently eradicated.
limited_by (LimitedBy): The quota policy that is limiting usage on this managed directory. This policy defines the total amount of space provisioned to this managed directory and its descendants. The returned value contains two parts: the name of the policy and the managed directory to which the policy is attached.
"""
if id is not None:
self.id = id
if name is not None:
self.name = name
if created is not None:
self.created = created
if destroyed is not None:
self.destroyed = destroyed
if directory_name is not None:
self.directory_name = directory_name
if file_system is not None:
self.file_system = file_system
if path is not None:
self.path = path
if space is not None:
self.space = space
if time_remaining is not None:
self.time_remaining = time_remaining
if limited_by is not None:
self.limited_by = limited_by
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `Directory`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
raise AttributeError
else:
return value
def __getitem__(self, key):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `Directory`".format(key))
return object.__getattribute__(self, key)
def __setitem__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `Directory`".format(key))
object.__setattr__(self, key, value)
def __delitem__(self, key):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `Directory`".format(key))
object.__delattr__(self, key)
def keys(self):
return self.attribute_map.keys()
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(Directory, dict):
for key, value in self.items():
result[key] = 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, Directory):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"noreply@github.com"
] |
PureStorage-OpenConnect.noreply@github.com
|
f3b1cf51d5b02fff27e636e3da4cc964efe47835
|
77be22f90869e8ad91e8ae15009274e97753e832
|
/andrewl_mortal_kombat/rsa1.py
|
8cb9ea18f8adfb8bd5883d58c0d3962a58e2e93a
|
[] |
no_license
|
lwerdna/crackme
|
a18b0544c51d04b947bf2d6254c71dc4744dd728
|
9f9e082805a75120c6084cedb4a9306c6ec3818d
|
refs/heads/master
| 2023-02-14T04:55:39.275773
| 2023-01-22T05:50:25
| 2023-01-22T05:50:25
| 192,410,237
| 4
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 807
|
py
|
#!/usr/bin/python
# rsa challenge, straight forward
#
# example name/serial pairs:
#
# knowledge/26582066182495701597915248727138888909
# is/141271412203160330710342183730048971956
# power/135066534443646675683259471815808056369
# Mortal/125332528239055605555179231197739673804
# Kombat/97493559731364222970517291247384579880
import sys
# globals
d = 65537
n = 152415787532388368909312594615759791673
# args?
if len(sys.argv) != 3:
print "usage: ", sys.argv[0], " <name> <serial>";
quit()
# convert name to number eg: "AAAA" -> 0x41414141
m = 0;
for char in sys.argv[1]:
m = m*256 + ord(char);
if m > n:
m = m % n;
# convert serial to number eg: "1234" -> 1234
c = int(sys.argv[2], 10);
# process, check
if pow(c, d, n) == m:
print "good"
else:
print "bad"
|
[
"andrew@vector35.com"
] |
andrew@vector35.com
|
72cd412bb1d32b99ae9b5fb9e575dec5bfecfaf3
|
56d58964a7a498e8f99bf804927b5d15f69fbccb
|
/fluent_pages/pagetypes/fluentpage/admin.py
|
992accd311303ed0bd915a6ae3924c8c0af9afd4
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
floppya/django-fluent-pages
|
3c8e56a12261c6901ef63008e3203f7518f5864e
|
5041d3b2d1d02bfc90cca1fe017618d99555a37b
|
refs/heads/master
| 2021-01-18T11:26:13.853182
| 2013-04-06T22:16:20
| 2013-04-06T22:16:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,839
|
py
|
from django.conf.urls.defaults import patterns, url
from fluent_pages.admin import HtmlPageAdmin
from fluent_pages.models import PageLayout
from fluent_pages.utils.ajax import JsonResponse
from fluent_contents.admin.placeholdereditor import PlaceholderEditorAdmin
from fluent_contents.analyzer import get_template_placeholder_data
from .widgets import LayoutSelector
class FluentPageAdmin(PlaceholderEditorAdmin, HtmlPageAdmin):
"""
This admin is a small binding between the pagetypes of *django-fluent-pages*
and page contents of *django-fluent-contents*. In fact, most code only concerns with the layout
mechanism that is custom for each implementation. To build a variation of this page,
see the API documentation of `Creating a CMS system <http://django-fluent-contents.readthedocs.org/en/latest/cms.html>`_
in the *django-fluent-contents* documentation to implement the required API's.
"""
# By using base_fieldsets, the parent PageAdmin will
# add an extra fieldset for all derived fields automatically.
FIELDSET_GENERAL = (None, {
'fields': HtmlPageAdmin.FIELDSET_GENERAL[1]['fields'][:-1] + ('layout',) + HtmlPageAdmin.FIELDSET_GENERAL[1]['fields'][-1:],
})
base_fieldsets = (
FIELDSET_GENERAL,
HtmlPageAdmin.FIELDSET_SEO,
HtmlPageAdmin.FIELDSET_MENU,
HtmlPageAdmin.FIELDSET_PUBLICATION,
)
change_form_template = ["admin/fluent_pages/page/page_editor.html",
"admin/fluent_pages/page.html",
]
class Media:
js = ('fluent_pages/fluentpage/fluent_layouts.js',)
# ---- fluent-contents integration ----
def get_placeholder_data(self, request, obj):
"""
Provides a list of :class:`fluent_contents.models.PlaceholderData` classes,
that describe the contents of the template.
"""
template = self.get_page_template(obj)
if not template:
return []
else:
return get_template_placeholder_data(template)
def get_page_template(self, page):
"""
Return the template that is associated with the page.
"""
if page is None:
# Add page. start with default template.
try:
return PageLayout.objects.all()[0].get_template()
except IndexError:
return None
else:
# Change page, honor template of object.
return page.layout.get_template()
# ---- Layout selector code ----
def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
if db_field.name == 'layout':
kwargs['widget'] = LayoutSelector
return super(FluentPageAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
def get_urls(self):
"""
Introduce more urls
"""
urls = super(FluentPageAdmin, self).get_urls()
my_urls = patterns('',
url(r'^get_layout/(?P<id>\d+)/$', self.admin_site.admin_view(self.get_layout_view))
)
return my_urls + urls
def get_layout_view(self, request, id):
"""
Return the metadata about a layout
"""
try:
layout = PageLayout.objects.get(pk=id)
except PageLayout.DoesNotExist:
json = {'success': False, 'error': 'Layout not found'}
status = 404
else:
template = layout.get_template()
placeholders = get_template_placeholder_data(template)
status = 200
json = {
'id': layout.id,
'key': layout.key,
'title': layout.title,
'placeholders': [p.as_dict() for p in placeholders],
}
return JsonResponse(json, status=status)
|
[
"vdboor@edoburu.nl"
] |
vdboor@edoburu.nl
|
dbbc4a131d4c1c6286c0c8fad167b1b843753cd3
|
795efc7484b5e1ccfd18ead6afed9dc3ccb7de99
|
/apps/books/urls.py
|
344716a952eff813a2da3a1fe534e881ef2988ca
|
[] |
no_license
|
wd5/book_base
|
ccf874357a42679043cb9063be443761a6d91ed4
|
922820180b24c45fd56afff72e55de79728d32b4
|
refs/heads/master
| 2021-01-10T01:37:41.318168
| 2012-08-01T09:54:34
| 2012-08-01T09:54:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,181
|
py
|
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url
from .views import BookList, BookDetail
from .views import BookBlank, BookBlankFromBookmark
from .views import BookmarkList, BookmarkAdd, BookmarkDel, BookmarkDelAll
from .views import RenderOrderBookForm, MakeOrderBook, CancelOrderBook
urlpatterns = patterns('',
url(r'^$', BookList.as_view(), name='book_list'),
url(r'^(?P<pk>\d+)/$', BookDetail.as_view(), name='book_detail'),
url(r'^(?P<pk>\d+)/blank/$', BookBlank.as_view(), name='book_blank'),
url(r'^bookmark/$', BookmarkList.as_view(), name='bookmark_list'),
url(r'^bookmark/add/$', BookmarkAdd.as_view(), name='bookmark_add'),
url(r'^bookmark/del/$', BookmarkDel.as_view(), name='bookmark_del'),
url(r'^bookmark/del/all/$', BookmarkDelAll.as_view(), name='bookmark_del_all'),
url(r'^bookmark/print-all/$', BookBlankFromBookmark.as_view(), name='bookmarks_print_all'),
#
url(r'^order/form/$', RenderOrderBookForm.as_view(), name='order_form'),
url(r'^order/make/$', MakeOrderBook.as_view(), name='order_make'),
url(r'^order/calcel/$', CancelOrderBook.as_view(), name='order_cancel'),
)
|
[
"DrMartiner@GMail.Com"
] |
DrMartiner@GMail.Com
|
cbbfba50005ee9b1a3b09f614c684c894ae7e6b6
|
b0ec01db9a15fcb171f9a73f44f67a736804f113
|
/app/__init__.py
|
323adc2762af574ee13612b08b7c39bece7521d6
|
[] |
no_license
|
uwase-diane/BookApp
|
60b7aded64f6892e51a13f3c6c487c25534f46f0
|
4549a1705b38a4a2f86c1b0cb34a2468c5964a56
|
refs/heads/master
| 2023-01-29T00:28:24.781440
| 2020-12-10T09:28:49
| 2020-12-10T09:28:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,242
|
py
|
from flask import Flask
from config import config_options
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_uploads import UploadSet,configure_uploads,IMAGES
from flask_simplemde import SimpleMDE
login_manager = LoginManager()
login_manager.session_protection = 'strong'
login_manager.login_view = 'auth.login'
bootstrap = Bootstrap()
db = SQLAlchemy()
photos = UploadSet('photos',IMAGES)
simple = SimpleMDE()
def create_app(configuration):
app = Flask(__name__)
app.url_map.strict_slashes = False
simple.init_app(app)
# Creating the app configurations
app.config.from_object(config_options[configuration])
# Initializing Flask Extensions
bootstrap = Bootstrap(app)
db.init_app(app)
login_manager.init_app(app)
# Registering the blueprint
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
from .auth import auth as auth_blueprint
app.register_blueprint(auth_blueprint,url_prefix = '/authenticate')
# configure UploadSet
configure_uploads(app,photos)
# setting config
from .request import configure_request
configure_request(app)
return app
|
[
"tharcissieidufashe@gmail.com"
] |
tharcissieidufashe@gmail.com
|
01521707f60526029a7269c3681ee91590141a97
|
6219e6536774e8eeb4cadc4a84f6f2bea376c1b0
|
/scraper/storage_spiders/demxinhvn.py
|
c23106e40abebd9467378da623d03ed7d214615c
|
[
"MIT"
] |
permissive
|
nguyenminhthai/choinho
|
109d354b410b92784a9737f020894d073bea1534
|
d2a216fe7a5064d73cdee3e928a7beef7f511fd1
|
refs/heads/master
| 2023-05-07T16:51:46.667755
| 2019-10-22T07:53:41
| 2019-10-22T07:53:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 975
|
py
|
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@id='product-main']/h1",
'price' : "//span[@class='price-new']/span[@id='formated_special']",
'category' : "",
'description' : "//div[@id='tab-description']",
'images' : "//ul[@id='boss-image-additional']/li/a/@href | //div[@class='image a_bossthemes']/a/@href",
'canonical' : "//link[@rel='canonical']/@href",
'base_url' : "//base/@href",
'brand' : ""
}
name = 'demxinh.vn'
allowed_domains = ['demxinh.vn']
start_urls = ['http://demxinh.vn/']
tracking_url = ''
sitemap_urls = ['']
sitemap_rules = [('', 'parse_item')]
sitemap_follow = ['']
rules = [
Rule(LinkExtractor(allow=['\.html$']), 'parse_item'),
Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+($|\?page=\d+$)'], deny=['index\.php']), 'parse'),
#Rule(LinkExtractor(), 'parse_item_and_links'),
]
|
[
"nguyenchungthuy.hust@gmail.com"
] |
nguyenchungthuy.hust@gmail.com
|
74ebf1832b3b13468d1c73b53dcd6062ad53a6bb
|
50be0ae5bc8a28b25c2ed81ea119140b8fa160bd
|
/libs/markdowncode.py
|
44fef0ef313ec8be9bb438da32e337aa86416770
|
[] |
no_license
|
Deattor/docmaster
|
e899c98cc3f93fd2cb4383205ae76111a53febe5
|
d3647c2734415c566554e07363fc85ec652fa626
|
refs/heads/master
| 2020-12-26T20:40:38.404797
| 2014-03-09T04:45:28
| 2014-03-09T04:45:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,091
|
py
|
#encoding=utf-8
##预处理器
from markdown.preprocessors import Preprocessor
class CodePreprocessor(Preprocessor):
def run(self, lines):
new_lines = []
flag_in = False
block = []
for line in lines:
if line[:3]=='!!!':
flag_in = True
block.append('<pre class="brush: %s;">' % line[3:].strip())
elif flag_in:
if line.strip() and line[0]=='!':
block.append(line[1:])
else:
flag_in = False
block.append('</pre>')
block.append(line)
new_lines.extend(block)
block = []
else:
new_lines.append(line)
if not new_lines and block:
new_lines = block
return new_lines
##后置处理器
from markdown.postprocessors import Postprocessor
class CodePostprocessor(Postprocessor):
def run(self, text):
t_list = []
for line in text.split('\n'):
if line[:5]=='<p>!<':
line = line.lstrip('<p>').replace('</p>', '')[1:]
t_list.append(line)
return '\n'.join(t_list)
##扩展主体类
from markdown.extensions import Extension
from markdown.util import etree
class CodeExtension(Extension):
def __init__(self, configs={}):
self.config = configs
def extendMarkdown(self, md, md_globals):
##注册扩展,用于markdown.reset时扩展同时reset
md.registerExtension(self)
##设置Preprocessor
codepreprocessor = CodePreprocessor()
#print md.preprocessors.keys()
md.preprocessors.add('codepreprocessor', codepreprocessor, '<normalize_whitespace')
##设置Postprocessor
codepostprocessor = CodePostprocessor()
#print md.postprocessors.keys()
md.postprocessors.add('codepostprocessor', codepostprocessor, '>unescape')
##print md_globals ##markdown全局变量
|
[
"five3@163.com"
] |
five3@163.com
|
a372d6acf27900226db66972f167ca17971335c0
|
5f57cfb662e7a490235255273114d2eb712a9ce4
|
/djd-prog2/noite-aula10/inimigos.py
|
84a03745c90c009a40dee665aa4cb6f38314c03d
|
[] |
no_license
|
antoniorcn/fatec-2020-2s
|
762e14acfbf0cb42a2e478662e6cf0001794f72c
|
4d90cc35d354382ad38c20ce2e32924216d7d747
|
refs/heads/master
| 2023-01-27T22:52:29.529360
| 2020-12-05T13:51:30
| 2020-12-05T13:51:30
| 289,972,977
| 9
| 7
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 253
|
py
|
AMARELO = (255, 255, 0)
class Alien:
def __init__(self, c, x, y):
self.cor = c
self.pos_x = x
self.pos_y = y
a1 = Alien("AMARELO", 100, 500)
a2 = Alien("AZUL", 150, 350)
print("A1 Cor:", a1.cor)
print("A2 Cor:", a2.cor)
|
[
"antoniorcn@hotmail.com"
] |
antoniorcn@hotmail.com
|
17544fa8a3e7e531224872ab76b461074fd8402f
|
3db0033d5266d73a84ab8cb0385b1b5f718f1d47
|
/menpobench/predefined/trainable_method/sdm.py
|
9f087bed219adb651b23bc29f03d6016f17151ca
|
[
"BSD-3-Clause"
] |
permissive
|
luckynote/menpobench
|
64ba98480712289e777d75b1d40402a8fe121857
|
cf0ea24c0bb6143bcfc6b0dc18951bcded69317e
|
refs/heads/master
| 2020-03-26T22:58:14.692536
| 2016-06-16T21:32:40
| 2016-06-16T21:32:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 756
|
py
|
from menpobench.method import MenpoFitWrapper
from menpobench.imgprocess import menpo_img_process
from menpofit.sdm import SDMTrainer
metadata = {
'display_name': 'Menpo Supervised Decent Method',
'display_name_short': 'Menpo SDM'
}
def train(img_generator):
# clean up the images with the standard menpo pre-processing
images = [menpo_img_process(img) for img in img_generator]
fitter = SDMTrainer(normalization_diagonal=150,
downscale=1.1,
n_perturbations=15).train(images, group='gt',
verbose=True)
# return a callable that wraps the menpo fitter in order to integrate with
# menpobench
return MenpoFitWrapper(fitter)
|
[
"jabooth@gmail.com"
] |
jabooth@gmail.com
|
f925dec040d95821cef191779da6306070d8ebd1
|
74951991a9e1dbe92d4999da9060409a9492bdc3
|
/minimum-number-of-operations-to-move-all-balls-to-each-box/minimum-number-of-operations-to-move-all-balls-to-each-box.py
|
8b91d314c3fcf1107e5a03f5f58cacc5ca30453a
|
[] |
no_license
|
drpuig/Leetcode-1
|
fd800ee2f13c7ce03fa57c8a1d10b3aa6976d7c0
|
4ee104f3069c380e1756dd65f6ff6004554e6c0e
|
refs/heads/main
| 2023-07-15T08:57:32.971194
| 2021-08-21T08:29:24
| 2021-08-21T08:29:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 756
|
py
|
class Solution:
def minOperations(self, boxes: str) -> List[int]:
# similar to 238. Product of Array Except Self and 42. Trapping Rain Water
# example for leftCost:
# input 11010
# leftCount 01223
# leftCost 01358
ans = [0]*len(boxes)
leftCount, leftCost, rightCount, rightCost, n = 0, 0, 0, 0, len(boxes)
for i in range(1, n):
if boxes[i-1] == '1': leftCount += 1
leftCost += leftCount # each step move to right, the cost increases by # of 1s on the left
ans[i] = leftCost
for i in range(n-2, -1, -1):
if boxes[i+1] == '1': rightCount += 1
rightCost += rightCount
ans[i] += rightCost
return ans
|
[
"32110646+trungnguyencs@users.noreply.github.com"
] |
32110646+trungnguyencs@users.noreply.github.com
|
f9adf60909c5eb13e5acb5e65c6af8986fc22867
|
28bf7793cde66074ac6cbe2c76df92bd4803dab9
|
/answers/Anuraj Pariya/Day 3/question 2.py
|
e1eb01c954fac70baaec7abeb51bcb72b21b949c
|
[
"MIT"
] |
permissive
|
Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021
|
2dee33e057ba22092795a6ecc6686a9d31607c9d
|
66c7d85025481074c93cfda7853b145c88a30da4
|
refs/heads/main
| 2023-05-29T10:33:31.795738
| 2021-06-10T14:57:30
| 2021-06-10T14:57:30
| 348,153,476
| 22
| 135
|
MIT
| 2021-06-10T14:57:31
| 2021-03-15T23:37:26
|
Java
|
UTF-8
|
Python
| false
| false
| 356
|
py
|
def uniqueCharacters(num):
for i in range(len(num)):
for j in range(i + 1,len(num)):
if(num[i] == num[j]):
return False
return True
num = input('enter no.')
if(uniqueCharacters(num)):
print("The String ", num," has all unique characters")
else:
print("The String ", num, " has duplicate characters")
|
[
"noreply@github.com"
] |
Codechef-SRM-NCR-Chapter.noreply@github.com
|
1e73fcf13b62a58f6664ed0b3991ee7998376d37
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02842/s205208232.py
|
ff1472f4186e61c2bc8dcd3915d423c7c49f881b
|
[] |
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
| 211
|
py
|
import math
n = int(input())
x = int(n/1.08)
if math.floor(x*1.08) == n:
print (x)
elif math.floor((x-1)*1.08) == n:
print (x-1)
elif math.floor((x+1)*1.08) == n:
print (x+1)
else:
print (":(")
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
50e7908500919233f20330f73cca0b3ef23c2b71
|
6b045457b0ea97f950eaef8373f417617be0bdd6
|
/edexOsgi/com.raytheon.uf.edex.plugin.goesr/utility/common_static/base/derivedParameters/functions/satRgbRecipeDiff.py
|
45781926363996d2c0eb651e84109c0ed370a9dd
|
[] |
no_license
|
Unidata/awips2-goesr
|
76228dda89e2d867318f2d6bffb10a897afe4083
|
61cc76f83643fea62dbfe59ba26d04e1ec9bc0ac
|
refs/heads/unidata_18.2.1
| 2023-09-04T06:36:35.949636
| 2023-05-02T18:59:52
| 2023-05-02T18:59:52
| 72,454,342
| 2
| 5
| null | 2023-05-02T18:59:53
| 2016-10-31T16:15:04
|
Java
|
UTF-8
|
Python
| false
| false
| 5,460
|
py
|
'''
<!--
This is an absolute override file, indicating that a higher priority
version of the file will completely replace a lower priority version
of the file.
-->
<!-- TOWRdocs Header
Derived Parameter Python file for implementing channel difference RGB recipes.
-->
<!-- TOWRdocs Description
This method implements channel difference RGB recipes outlined in EUMETSAT's "Best
Practices for RGB Displays of Multispectral Imagery" document
(http://oiswww.eumetsat.int/~idds/html/doc/best_practices.pdf). Two arrays
of satellite data are passed to this method along with various recipe options
outlined below. The channel difference is calculated as physicalElement1 -
physicalElement2. An array of display values is returned that corresponds to a
single color component of an RGB product.
-->
<!-- TOWRdocs Status
This is a new derived parameters file.
It is used to implement channel difference RGB recipes.
-->
<!-- TOWRdocs POC
Kevin M. McGrath
-->
CONTACTS:
This code was co-developed via the AWIPS II Experimental Products Development
Team (EPDT) by personnel from NASA SPoRT, CIRA, and the NWS:
Jason Burks/CIRA/MDL (jason.burks@noaa.gov)
Nancy Eustice/NWS (nancy.eustice@noaa.gov)
Kevin McGrath/NASA SPoRT/Jacobs (kevin.m.mcgrath@nasa.gov)
Deb Molenar/NOAA/NESDIS/RAMMB (Debra.Molenar@noaa.gov)
Matt Smith/NASA SPoRT/UAH (matthew.r.smith@nasa.gov)
Nate Smith/NWS (nate.smith@noaa.gov)
INPUT PARAMETERS:
@param physicalElement1:
Array of satellite data.
@param physicalElement2:
Array of satellite data.
@param calNumber:
This integer corresponds to methods in satRgbRecipeCalibration.py,
which converts satellite data values to physical values(e.g.,
IR counts to brightness temperatures). For most data, calNumber is 0
(no calibration required) because these values are already calibrated
when passed to this method. The units of the data passed to this method
is controlled by the the "unit=" option in the derived parameter definition
.xml files. As an example with GOES-R IR data, we need the data to be calibrated
to brightness temperature in units of Kelvin. The following line in a derived
parameter definition .xml file would accomplish this:
<Field abbreviation="CH-08-6.19um" unit="K"/>
Here's an example requesting GOES-13 IR data (unit="IRPixel") in units of Kelvin:
<Field abbreviation="Imager 11 micron IR" unit="IRPixel"/>
In the case of visible imagery, we want the data to be in albedo from 0 to 100.
The following line in a derived parameter definition .xml file would accomplish this
for GOES-R visible data (unit="%"):
<Field abbreviation="CH-06-2.25um" unit="%"/>
If no "unit=" option is included in the "Field abbreviation" derived parameter
definition, raw values will be passed to this method.
@param minCalibratedValue:
The calibrated satellite data values are clipped to this minimum
value.
@param maxCalibratedValue:
The calibrated satellite data values are clipped to this maximum
value.
@param gamma:
Gamma value used for stretching.
@param invert:
Invert the final display values (255 - value)? (0 = no, 1 = yes)
RETURNS:
@return: Display values
@rtype: numpy array (int8)
DEPENDENCIES:
* Numpy
* The satRgbRecipeCalibration module found in satRgbRecipeCalibration.py:
This is only required and imported if we need to calibrate the satellite
data (calNumber != 0).
MODIFICATIONS:
'''
import numpy as np
def execute(physicalElement1, physicalElement2, calNum, minCalibratedValue, maxCalibratedValue, gamma, invert):
#########################
# Create calibrated arrays.
if (int(calNum) == 0):
# No need to calibrate the data.
a1_calibrated = physicalElement1
a2_calibrated = physicalElement2
else:
# Import the calibration module.
import satRgbRecipeCalibration as calibration
# Define calibration method to call.
calTypeString = 'calType_' + str(int(calNum))
try:
calMethodToCall = getattr(calibration, calTypeString)
except AttributeError:
return(0)
# Calibrate the data by calling calType_<calNum> method.
a1_calibrated = calMethodToCall(physicalElement1)
a2_calibrated = calMethodToCall(physicalElement2)
#########################
# Calculate the difference between a1_calibrated and a2_calibrated.
diff_calibrated = a1_calibrated - a2_calibrated
#########################
# Clip the calibrated values.
diff_calibrated_clipped = np.clip(diff_calibrated, minCalibratedValue, maxCalibratedValue)
#########################
# Generate display values by implement EUMETSAT recipe.
dispValue_float = 255.*(np.power( (diff_calibrated_clipped - minCalibratedValue)/(maxCalibratedValue - minCalibratedValue), (1./gamma)))
#########################
# Invert, if selected.
if (invert):
dispValue_float = 255. - dispValue_float
#########################
# Convert from float to int8.
dispValue_byte = np.array(dispValue_float, dtype=np.int8)
#########################
# CAVE interprets byte values of 0 as "No Data". Force values of 0 to 1.
dispValue_byte[dispValue_byte == 0] = 1
#########################
# For any pixels where physicalElement1 or physicalElement2 is zero (no data), set
# the displayValue_byte to 0 (no data) so that the pixel is transparent.
dispValue_byte[(physicalElement1 == 0) | (physicalElement2 == 0)] = 0
return dispValue_byte
|
[
"mjames@unidata.ucar.edu"
] |
mjames@unidata.ucar.edu
|
e3c648df17473aa2c6ec699a3c3a228f309b458b
|
cc096d321ab5c6abf54fdcea67f10e77cd02dfde
|
/flex-backend/pypy/rpython/rctypes/achar_p.py
|
679fb44c613f75c7b294d3527c0d94da6c01241f
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
limweb/flex-pypy
|
310bd8fcd6a9ddc01c0b14a92f0298d0ae3aabd2
|
05aeeda183babdac80f9c10fca41e3fb1a272ccb
|
refs/heads/master
| 2021-01-19T22:10:56.654997
| 2008-03-19T23:51:59
| 2008-03-19T23:51:59
| 32,463,309
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,100
|
py
|
from pypy.rpython.rctypes.implementation import CTypesCallEntry, CTypesObjEntry
from pypy.annotation.model import SomeString
from ctypes import c_char_p
class CallEntry(CTypesCallEntry):
"Annotation and rtyping of calls to c_char_p."
_about_ = c_char_p
def specialize_call(self, hop):
string_repr = hop.rtyper.type_system.rstr.string_repr
r_char_p = hop.r_result
hop.exception_cannot_occur()
v_result = r_char_p.allocate_instance(hop.llops)
if len(hop.args_s):
v_value, = hop.inputargs(string_repr)
r_char_p.setstring(hop.llops, v_result, v_value)
return v_result
class ObjEntry(CTypesObjEntry):
"Annotation and rtyping of c_char_p instances."
_type_ = c_char_p
s_return_trick = SomeString(can_be_None=True)
def get_field_annotation(self, s_char_p, fieldname):
assert fieldname == 'value'
return self.s_return_trick
def get_repr(self, rtyper, s_char_p):
from pypy.rpython.rctypes import rchar_p
return rchar_p.CCharPRepr(rtyper, s_char_p, rchar_p.CCHARP)
|
[
"lucio.torre@dbd81ab4-9648-0410-a770-9b81666e587d"
] |
lucio.torre@dbd81ab4-9648-0410-a770-9b81666e587d
|
6fbe95249a65618956af92f25e82a132dbcd9f39
|
2940f5416082dadd9c646cd9a46d2d0a99883efb
|
/venv/Lib/site-packages/scipy/_lib/tests/test_linear_assignment.py
|
5ba729dcac445604773fab01e74e2df735b11eb7
|
[
"BSD-3-Clause",
"Python-2.0",
"Qhull",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-2-Clause",
"GPL-3.0-or-later",
"BSD-3-Clause-Open-MPI",
"GCC-exception-3.1",
"GPL-3.0-only"
] |
permissive
|
tpike3/SugarScape
|
4813e4fefbfb0a701f5913d74f045fd0eaed1942
|
39efe4007fba2b12b75c72f7795827a1f74d640b
|
refs/heads/main
| 2021-06-20T03:55:46.288721
| 2021-01-20T17:06:35
| 2021-01-20T17:06:35
| 168,583,530
| 11
| 3
|
MIT
| 2021-01-20T17:19:53
| 2019-01-31T19:29:40
|
Jupyter Notebook
|
UTF-8
|
Python
| false
| false
| 3,420
|
py
|
from itertools import product
from numpy.testing import assert_array_equal
import numpy as np
import pytest
from scipy.optimize import linear_sum_assignment
from scipy.sparse import csr_matrix, random
from scipy.sparse.csgraph import min_weight_full_bipartite_matching
# Tests that combine scipy.optimize.linear_sum_assignment and
# scipy.sparse.csgraph.min_weight_full_bipartite_matching
@pytest.mark.parametrize('solver_type,sign,test_case', product(
[(linear_sum_assignment, np.array),
(min_weight_full_bipartite_matching, csr_matrix)],
[-1, 1],
[
# Square
([[400, 150, 400],
[400, 450, 600],
[300, 225, 300]],
[150, 400, 300]),
# Rectangular variant
([[400, 150, 400, 1],
[400, 450, 600, 2],
[300, 225, 300, 3]],
[150, 2, 300]),
([[10, 10, 8],
[9, 8, 1],
[9, 7, 4]],
[10, 1, 7]),
# Square
([[10, 10, 8, 11],
[9, 8, 1, 1],
[9, 7, 4, 10]],
[10, 1, 4]),
# Rectangular variant
([[10, float("inf"), float("inf")],
[float("inf"), float("inf"), 1],
[float("inf"), 7, float("inf")]],
[10, 1, 7]),
])
)
def test_two_methods_give_expected_result_on_small_inputs(
solver_type, sign, test_case
):
solver, array_type = solver_type
cost_matrix, expected_cost = test_case
maximize = sign == -1
cost_matrix = sign * array_type(cost_matrix)
expected_cost = sign * np.array(expected_cost)
row_ind, col_ind = solver(cost_matrix, maximize=maximize)
assert_array_equal(row_ind, np.sort(row_ind))
assert_array_equal(expected_cost,
np.array(cost_matrix[row_ind, col_ind]).flatten())
cost_matrix = cost_matrix.T
row_ind, col_ind = solver(cost_matrix, maximize=maximize)
assert_array_equal(row_ind, np.sort(row_ind))
assert_array_equal(np.sort(expected_cost),
np.sort(np.array(
cost_matrix[row_ind, col_ind])).flatten())
def test_two_methods_give_same_result_on_many_sparse_inputs():
# As opposed to the test above, here we do not spell out the expected
# output; only assert that the two methods give the same result.
# Concretely, the below tests 100 cases of size 100x100, out of which
# 36 are infeasible.
np.random.seed(1234)
for _ in range(100):
lsa_raises = False
mwfbm_raises = False
sparse = random(100, 100, density=0.06,
data_rvs=lambda size: np.random.randint(1, 100, size))
# In csgraph, zeros correspond to missing edges, so we explicitly
# replace those with infinities
dense = np.full(sparse.shape, np.inf)
dense[sparse.row, sparse.col] = sparse.data
sparse = sparse.tocsr()
try:
row_ind, col_ind = linear_sum_assignment(dense)
lsa_cost = dense[row_ind, col_ind].sum()
except ValueError:
lsa_raises = True
try:
row_ind, col_ind = min_weight_full_bipartite_matching(sparse)
mwfbm_cost = sparse[row_ind, col_ind].sum()
except ValueError:
mwfbm_raises = True
# Ensure that if one method raises, so does the other one.
assert lsa_raises == mwfbm_raises
if not lsa_raises:
assert lsa_cost == mwfbm_cost
|
[
"tpike3@gmu.edu"
] |
tpike3@gmu.edu
|
d8aacd22dc55729c0394ca6fdd998d7aef004f28
|
3bedfe030662300844861d8f4d0ba52c1e43f950
|
/fit_farquhar_model/plot_priors.py
|
af76c6018455b51fd775409540fd1529586fb42a
|
[] |
no_license
|
shaoxiuma/FitFarquharModel
|
d200ae38d3fd6ab73b1db4910ef7c15fe16bb0f3
|
fd3766feaea65e80025df9bf5a9257e68805f696
|
refs/heads/master
| 2021-01-06T06:45:36.683836
| 2016-07-14T09:41:05
| 2016-07-14T09:41:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,978
|
py
|
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import truncnorm as tn
import pymc
#mu = 25.0
#sigma = 11.25
#a = 1.0
#b = 650.0
#vals = tn(a=a, b=b, loc=mu, scale=sigma)
#plt.hist(vals.rvs(100000), bins=50)
#plt.xlim(0, 100)
#plt.show()
N = 10000
Vcmax = [pymc.TruncatedNormal('Vcmax25', \
mu=100.0, tau=1.0/61.25**2, a=0.0, b=650.0).value \
for i in xrange(N)]
Jfac = [pymc.TruncatedNormal('Jfac', mu=1.8, tau=1.0/0.5**2, \
a=0.0, b=5.0).value for i in xrange(N)]
Rdfac = [pymc.Uniform('Rdfac', lower=0.005, upper=0.05).value \
for i in xrange(N)]
Eaj = [pymc.TruncatedNormal('Eaj', mu=40000.0, tau=1.0/10000.0**2, a=0.0,
b=199999.9).value for i in xrange(N)]
Eav = [pymc.TruncatedNormal('Eav', mu=60000.0, tau=1.0/10000.0**2, a=0.0,
b=199999.9).value for i in xrange(N)]
Ear = [pymc.TruncatedNormal('Ear', mu=34000.0, tau=1.0/10000.0**2, a=0.0,
b=199999.9).value for i in xrange(N)]
delSj = [pymc.TruncatedNormal('delSj', mu=640.0, tau=1.0/10.0**2, a=300.0,
b=800.0).value for i in xrange(N)]
delSv = [pymc.TruncatedNormal('delSv', mu=640.0, tau=1.0/10.0**2,
a=300.0, b=800.0).value for i in xrange(N)]
plt.rcParams['figure.subplot.hspace'] = 0.3
plt.rcParams['figure.subplot.wspace'] = 0.3
plt.rcParams['font.size'] = 10
plt.rcParams['legend.fontsize'] = 10
plt.rcParams['xtick.labelsize'] = 10.0
plt.rcParams['ytick.labelsize'] = 10.0
plt.rcParams['axes.labelsize'] = 10.0
var_names = ["Vcmax", "Jfac", "Rdfac", "Eaj", "Eav", "Ear", "delSj", "delSv"]
vars = [Vcmax, Jfac, Rdfac, Eaj, Eav, Ear, delSj, delSv]
fig = plt.figure(figsize=(10,10))
bins = 50
for index, var in enumerate(var_names):
ax = fig.add_subplot(4,2,(index+1))
ax.set_title(var_names[index])
ax.hist(vars[index], bins=bins)
fig.savefig("/Users/mdekauwe/Desktop/priors.png", dpi=150)
plt.show()
|
[
"mdekauwe@gmail.com"
] |
mdekauwe@gmail.com
|
30bb5a8de099650a678bb641cbd91df19f7b70e5
|
edc1f1369794a4a1c499c6e9d5fe49a712657611
|
/algorithms/BAT-algorithms/Linklist/把链表分隔成 k 部分.py
|
b8bdcc1f196b6ec7dc476ed648423dfbb07a90aa
|
[] |
no_license
|
williamsyb/mycookbook
|
93d4aca1a539b506c8ed2797863de6da8a0ed70f
|
dd917b6eba48eef42f1086a54880bab6cd1fbf07
|
refs/heads/master
| 2023-03-07T04:16:18.384481
| 2020-11-11T14:36:54
| 2020-11-11T14:36:54
| 280,005,004
| 2
| 0
| null | 2023-03-07T02:07:46
| 2020-07-15T23:34:24
|
Python
|
UTF-8
|
Python
| false
| false
| 1,148
|
py
|
"""
题目:
把链表分隔成 k 部分,每部分的长度都应该尽可能相同,排在前面的长度应该大于等于后面的。
示例:
Input:
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
"""
from Linklist.utils import *
def split_list_to_parts(root, k):
cur = root
count = 0 # 统计节点个数
while cur is not None:
count += 1
cur = cur.next
mod = count % k
size = int(count / k)
cut_way = [size] * k # 划分成k个部分,cut_way中记录每部分的节点个数
for i in range(mod):
cut_way[i] += 1
result = [None] * k
cur = root
i = 0
# 按cut_way中每部分的节点个数将链表分成k断,存于result中
while cur is not None and i < k:
result[i] = cur
for j in range(cut_way[i] - 1):
cur = cur.next
next1 = cur.next
cur.next = None
cur = next1
i += 1
return result
if __name__ == '__main__':
head = build_l([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
for l in split_list_to_parts(head, 3):
print_l(l)
|
[
"william_sun1990@hotmail.com"
] |
william_sun1990@hotmail.com
|
3cba030978802e2c08627276829ad7783d3fa0b9
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/AaSXX4SKNdZ7mgqK7_17.py
|
be63a7e642493a1b3670a3c483d9fb9f2cc07103
|
[] |
no_license
|
daniel-reich/turbo-robot
|
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
|
a7a25c63097674c0a81675eed7e6b763785f1c41
|
refs/heads/main
| 2023-03-26T01:55:14.210264
| 2021-03-23T16:08:01
| 2021-03-23T16:08:01
| 350,773,815
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,821
|
py
|
"""
Check the principles of minimalist code in the [intro to the first
challenge](https://edabit.com/challenge/2XLjgZhmACph76Pkr).
In the **Code** tab you will find a code that is missing a single character in
order to pass the tests. However, your goal is to submit a function as
**minimalist** as possible. Use the tips in the tips section below.
Write a function that returns the **first truthy argument** passed to the
function. If all arguments are falsy, return the string `"not found"`. The
function will be called with a **minimum of one** and a **maximum of four**
arguments: `a`, `b`, `c`, `d`.
### Tips
The operator `or` can be used to assign or return the first truthy value among
two or more elements. If no truthy value is found, the last element will be
returned.
For example, the code:
def one_of_these(a, b, c):
return a if a else b if b else c
Can be simplified to:
def one_of_these(a, b, c):
return a or b or c
### Bonus
Once a truthy value is found, the rest of the elements will not be checked.
This can be used to define a sort of default value that will be returned if
all of the previous elements happen to be false or empty:
txt1 = ""
txt2 = "Edabit"
txt1 or "Empty string" ➞ "Empty string"
txt2 or "Empty string" ➞ "Edabit"
### Notes
* This is an open series: there isn't a definite list of features for the challenges. Please, do not hesitate to leave your **suggestions** in the **Comments**.
* _ **Readability**_ is indeed a subjective concept. **Let's discuss it!** Feel free to leave your opinion in the **Comments**.
* You can find all the exercises in this series [over here](https://edabit.com/collection/8F3LA2Mwrf5bp7kse).
"""
def first_one(a,b=None,c=None,d=None):
return a or b or c or d or 'not found'
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
f6fe6717319bec24fa325da576bb51eb891e8504
|
34652a47355a8dbe9200db229a1bbc62619de364
|
/Courses, Trainings, Books & Exams/PYTHON 3 - Scientific Training/5-1 Defining and Calling Functions -03.py
|
17586f32ac4d6ca197e6bf670f6a09aad7f612a0
|
[] |
no_license
|
btrif/Python_dev_repo
|
df34ab7066eab662a5c11467d390e067ab5bf0f8
|
b4c81010a1476721cabc2621b17d92fead9314b4
|
refs/heads/master
| 2020-04-02T13:34:11.655162
| 2019-11-10T11:08:23
| 2019-11-10T11:08:23
| 154,487,015
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 363
|
py
|
#!/usr/bin/python
def parrot(voltage, state='a stiff', action='voom'):
print("-- This parrot wouldn't", action,)
print("if you put", voltage, "volts through it.",)
print("E's", state, "!")
# Define a dictionary
d = {"voltage": "4.000.000", "state": "bleedin' demised", "action": "VOOM"}
# call the function parrot with the dictionary
parrot(**d)
|
[
"bogdan.evanzo@gmail.com"
] |
bogdan.evanzo@gmail.com
|
3197e0ded1fcd0b9cbfc65013a98c0b902ec901a
|
becf6e96bd866e4a8ee964bc1901225e4fa3fb46
|
/thornoise/noise.py
|
264f7672212363d1214a68567be5297050cf0eaa
|
[
"MIT"
] |
permissive
|
YannThorimbert/RpgMap
|
80be6a4aea9e8af41a8ff61657a8fcfddd12dd62
|
c8c4746e1c99930142d8742e0aa6975dde7efa90
|
refs/heads/main
| 2023-04-20T17:50:03.875740
| 2021-05-05T12:47:52
| 2021-05-05T12:47:52
| 354,846,610
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,210
|
py
|
from __future__ import print_function, division
import random, math
import matplotlib.pyplot as plt
def generate_constraints(n_octaves, S, chunk):
"""Generates random height constraints used by terrain generation.
THIS IS NOT THE ACTUAL TERRAIN GENERATION FUNCTION."""
min_res = int(S / 2**(n_octaves-1))
hmap_size = S//min_res + 1
random.seed(chunk)
h = [[random.random() for x in range(hmap_size)] for y in range(hmap_size)]
#
XCOORD, YCOORD = chunk
#left
random.seed((XCOORD,YCOORD))
for y in range(hmap_size):
h[0][y] = random.random()
#right
random.seed((XCOORD+1,YCOORD))
for y in range(hmap_size):
h[-1][y] = random.random()
#top
random.seed((XCOORD,YCOORD))
for x in range(hmap_size):
h[x][0] = random.random()
#bottom
random.seed((XCOORD,YCOORD+1))
for x in range(hmap_size):
h[x][-1] = random.random()
random.seed((XCOORD,YCOORD))
h[0][0] = random.random()
random.seed((XCOORD+1,YCOORD+1))
h[-1][-1] = random.random()
random.seed((XCOORD,YCOORD+1))
h[0][-1] = random.random()
random.seed((XCOORD+1,YCOORD))
h[-1][0] = random.random()
return h, min_res
def generate_terrain(size, n_octaves=None, chunk=(0,0), persistance=2.):
"""Returns a <S> times <S> array of heigth values for <n_octaves>, using
<chunk> as seed."""
S = size
if n_octaves is None: #automatic max number of octaves
n_octaves = int(math.log(S,2))
h, min_res = generate_constraints(n_octaves, S, chunk) #h is the hmap constraint
terrain = [[0. for x in range(S)] for y in range(S)] #actual heightmap
res = int(S) #resolution for the current octave
step = res//min_res #space step in pixels for the current octave
change_cell = True #indicates when polynomial coeffs have to be recomputed
amplitude = persistance
for i in range(n_octaves):
delta = 1./res #size of current cell
x_rel = 0. #x-pos in the current cell
for x in range(S): #here x is coord of pixel
y_rel = 0. #y-pos in the current cell
x2 = x_rel*x_rel;
smoothx = 3.*x2 - 2.*x_rel*x2;
for y in range(S):
y2 = y_rel*y_rel
smoothy = 3.*y2 - 2.*y_rel*y2
diag_term = x_rel*y_rel - smoothx*y_rel - smoothy*x_rel
if change_cell:
idx0, idy0 = int(x/res)*step, int(y/res)*step
idx1, idy1 = idx0+step, idy0+step
h00 = h[idx0][idy0]
h01 = h[idx0][idy1]
h10 = h[idx1][idy0]
h11 = h[idx1][idy1]
#
dx = h10 - h00
dy = h01 - h00
A = dx - h11 + h01
change_cell = False
dh = h00 + smoothx*dx + smoothy*dy + A*diag_term
terrain[x][y] += amplitude*dh
#
y_rel += delta
if y_rel >= 1.: #periodicity
change_cell = True
y_rel = 0.
x_rel += delta
if x_rel >= 1.: #periodicity
change_cell = True
x_rel = 0.
res //= 2
step = res//min_res
amplitude /= persistance
return terrain
def normalize(terrain):
"""Normalize in place the values of <terrain>."""
M = max([max(line) for line in terrain])
m = min([min(line) for line in terrain])
S = len(terrain)
for x in range(S):
for y in range(S):
terrain[x][y] = (terrain[x][y] - m)/(M-m)
return terrain
resolution = 128
terrain = generate_terrain(size=resolution, n_octaves=8, persistance=1.5)
normalize(terrain)
#here we add an offset (don't add offset if you just want natural noise)
offset_amplitude = -2.5/resolution
for x in range(resolution):
for y in range(resolution):
terrain[x][y] += x*offset_amplitude
plt.imshow(terrain, cmap="Blues")
plt.show()
#note: matplotlib swap the axes compared to the matrix format used here
#cool cmaps for terrain : "terrain", "gist_earth", ... (see https://matplotlib.org/users/colormaps.html)
|
[
"yann.thorimbert@gmail.com"
] |
yann.thorimbert@gmail.com
|
f948d2c486bf549cd835bfca0a5694c3e2e0688a
|
0f5c047bdb5cd8aee5b6aac3447e7cf75c6eedcc
|
/weighted/weighted_lev_gen.py
|
752dfb8ad94d66988658319bec58e4935880d9ff
|
[] |
no_license
|
dengl11/CS166-Project
|
fcde43fe5a044757432faa53ef79dcaa4ed46132
|
f05c5de12a0cfe6939e55149cc69d82ceca41a1c
|
refs/heads/master
| 2020-03-18T23:13:56.963216
| 2018-06-13T22:21:19
| 2018-06-13T22:21:19
| 135,390,090
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,569
|
py
|
import sys, os
sys.path.append(os.path.join(os.path.abspath(__file__), "../"))
from util import *
from trie import *
from levenshtein import *
from match import *
from generator import *
from config import *
from lev_dfa_gen import *
from weighted_gen import *
class WeighedLevTrieGenerator(LevTrieDFAGenerator):
def __init__(self, costs, corpus_dfa = None):
self.corpus_dfa = corpus_dfa or load_data(corpus_dfa_path)
WeightedGenerator.__init__(self, costs)
def construct_levenshten(self, word, k):
nfa = self.construct_levenshten_nfa(word, k)
return DFA.from_nfa(nfa)
def construct_levenshten_nfa(self, word, k):
"""
Args:
word:
k : max edit distance
Return:
"""
n = len(word)
m = dict() # {(n_char, n_err): state_name}
for nc in range(n + 1):
for ne in range(k + 1):
m[(nc, ne)] = str((nc, ne))
transitions = defaultdict(lambda: defaultdict(lambda: set()))
for i in range(n + 1):
ch = word[i] if (i < n) else None
for e in range(k + 1):
credit = k - e # remaining credits
curr = m[(i, e)]
right = m[(i + 1, e)] if ch else None
if credit >= self.c_insert: # can insert
up = m[(i, e + self.c_insert)]
for c in ALPHABETS: transitions[curr][c].add(up)
if not right: continue
transitions[curr][ch].add(right) # correct char: right arrow
if credit >= self.c_delete: # can delete
next_del = m[(i + 1, e + self.c_delete)]
transitions[curr][""].add(next_del) # deletions - epsilon: diagonal arrow
if credit < self.c_subs: continue
next_subs = m[(i + 1, e + self.c_subs)]
for c in ALPHABETS:
transitions[curr][c].add(next_subs
)
nfa = NFA(states = set(m.values()),\
transitions = transitions,\
initial_state = m[(0, 0)],\
final_states = {m[(n, j)] for j in range(k + 1)},\
input_symbols = set(ALPHABETS))
return nfa
def gen_candidates(self, w, k):
"""get candidates of w within edit distance of k
Args:
w:
Return:
"""
lev_dfa = self.construct_levenshten(w, k)
return list(match(self.corpus_dfa, lev_dfa))
|
[
"dengl11@stanford.edu"
] |
dengl11@stanford.edu
|
a38ad724f73002d0f6a61cdd841bd780cfb1b1fc
|
6d7336a48936a15484798d59cb863d8419e9578c
|
/setup.py
|
84631162f58c4005edc139c3796016fad04db54b
|
[
"MIT"
] |
permissive
|
bbengfort/cellular-automata
|
48f8f07925e1fb3b4466f090127f44f8f761c799
|
c58ab58773796037979da70806b9d19797a64926
|
refs/heads/master
| 2021-01-01T15:35:44.698790
| 2014-02-07T20:48:49
| 2014-02-07T20:48:49
| 16,409,041
| 5
| 7
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,347
|
py
|
#!/usr/bin/env python
# setup
# Setup script for cellular-automata
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Fri Jan 31 09:15:08 2014 -0500
#
# Copyright (C) 2014 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: setup.py [] benjamin@bengfort.com $
"""
Setup script for cellular-automata
"""
##########################################################################
## Imports
##########################################################################
try:
from setuptools import setup
from setuptools import find_packages
except ImportError:
raise ImportError("Could not import \"setuptools\"."
"Please install the setuptools package.")
##########################################################################
## Package Information
##########################################################################
packages = find_packages(where=".", exclude=("tests", "bin", "docs", "fixtures",))
requires = []
with open('requirements.txt', 'r') as reqfile:
for line in reqfile:
requires.append(line.strip())
classifiers = (
'Development Status :: 3 - Alpha',
'Environment :: MacOS X',
'Environment :: Console',
'Environment :: Other Environment',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: MacOS :: MacOS X',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 2.7',
'Topic :: Multimedia :: Graphics',
'Topic :: Artistic Software',
'Topic :: Scientific/Engineering :: Visualization',
'Topic :: Scientific/Engineering :: Artificial Life',
)
config = {
"name": "PyCellularAutomata",
"version": "0.2",
"description": "a Python Cellular Automata visualization library",
"author": "Benjamin Bengfort",
"author_email": "benjamin@bengfort.com",
"url": "https://github.com/bbengfort/cellular-automata",
"packages": packages,
"install_requires": requires,
"classifiers": classifiers,
"zip_safe": False,
"scripts": ["bin/pyca",],
}
##########################################################################
## Run setup script
##########################################################################
if __name__ == '__main__':
setup(**config)
|
[
"benjamin@bengfort.com"
] |
benjamin@bengfort.com
|
55f1881da1b8b571d4ead59e470624bd417dde15
|
eb2df6020f5759feee3d6d78c5f8c78999454a09
|
/scheduled_jobs/trulight_energy/capacity_curves/read_capacity.py
|
7a06b2ec665d19e94399d9f1b55cf383d3f12c1f
|
[] |
no_license
|
mywork-dragon/dave-energy
|
7a08f855d245c2d90a9c13aa85fc3b9f28ae9294
|
4b3430be6ef6957389ab05be3a17a0245f5d6662
|
refs/heads/master
| 2023-07-28T02:55:26.791724
| 2021-09-06T11:44:30
| 2021-09-06T11:44:30
| 365,872,455
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 240
|
py
|
from scheduled_jobs.trulight_energy.run import run
from scheduled_jobs.trulight_energy.run import TrulightAPIType
CAPACITY_CURVE_URL = "/api/CapacityCurve"
if __name__ == "__main__":
run(CAPACITY_CURVE_URL, TrulightAPIType.Capacity)
|
[
"dragonblueyounger@gmail.com"
] |
dragonblueyounger@gmail.com
|
9b080ae18cafe06d4113940f5175b3baafc4f009
|
311c4dc3034b108049c0d21adad71144433c539d
|
/cars/tests.py
|
7215f9f9f078bb99be857970d1c462350d43c22c
|
[] |
no_license
|
Osama-Yousef/cars-api-permissions-postgres
|
34acfd9fdc0545e147d07e821f767e1e414149f9
|
2292f10e6ae53b6da3f0848ed1832d1fe1346c4d
|
refs/heads/master
| 2022-12-22T07:21:24.926870
| 2020-09-28T15:00:47
| 2020-09-28T15:00:47
| 299,285,921
| 1
| 0
| null | 2020-09-28T15:00:48
| 2020-09-28T11:25:05
|
Python
|
UTF-8
|
Python
| false
| false
| 907
|
py
|
from django.test import TestCase
from django.contrib.auth import get_user_model
from .models import Car
# Create your tests here.
class BlogTest(TestCase):
@classmethod
def setUpTestData(cls):
test_user = get_user_model().objects.create_user(username='testuser', password='password')
test_user.save()
car = Car.objects.create(
author = test_user,
title = 'ferrari enzo',
body = 'amazing car through the years'
)
car.save() # Save the object to mock Database
def test_blog_content(self):
car = Car.objects.get(id=1)
actual_author = str(car.author)
actual_title = str(car.title)
actual_body = str(car.body)
self.assertEqual(actual_author, 'testuser')
self.assertEqual(actual_title, 'ferrari enzo')
self.assertEqual(actual_body, 'amazing car through the years')
|
[
"osamawalidyousef@gmail.com"
] |
osamawalidyousef@gmail.com
|
4dd7ac5371dafbffb4120681c5a84bd01d820d3f
|
7860f554d0a51f8af87f71c0a927d12f618b2197
|
/all_topic/esay_topic/38. 外观数列.py
|
2ee250f25b470d91b81d208e631bc16b3aa019bd
|
[] |
no_license
|
starrye/LeetCode
|
79586b5984a4c28b9a641a0108a41dccacd9375a
|
83c589464e0caad960679aea259681c965218d13
|
refs/heads/master
| 2022-07-26T21:05:42.616460
| 2022-06-23T10:10:38
| 2022-06-23T10:10:38
| 158,910,651
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,603
|
py
|
#!/usr/local/bin/python3
# -*- coding:utf-8 -*-
"""
@author:
@file: 38. 外观数列.py
@time: 2020/8/10 16:15
@desc:
"""
from typing import List
"""
给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第 n 项。
注意:整数序列中的每一项将表示为一个字符串。
「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
第一项是数字 1
描述前一项,这个数是 1 即 “一个 1 ”,记作 11
描述前一项,这个数是 11 即 “两个 1 ” ,记作 21
描述前一项,这个数是 21 即 “一个 2 一个 1 ” ,记作 1211
描述前一项,这个数是 1211 即 “一个 1 一个 2 两个 1 ” ,记作 111221
示例 1:
输入: 1
输出: "1"
解释:这是一个基本样例。
示例 2:
输入: 4
输出: "1211"
解释:当 n = 3 时,序列是 "21",其中我们有 "2" 和 "1" 两组,"2" 可以读作 "12",也就是出现频次 = 1 而 值 = 2;类似 "1" 可以读作 "11"。所以答案是 "12" 和 "11" 组合在一起,也就是 "1211"。
"""
"""
每次外循环含义为给定上一个人报的数,求下一个人报的数
每次内循环为遍历上一个人报的数
先设置上一人为'1'
开始外循环
每次外循环先置下一人为空字符串,置待处理的字符num为上一人的第一位,置记录出现的次数为1
开始内循环,遍历上一人的数,如果数是和num一致,则count增加。
若不一致,则将count和num一同添加到next_person报的数中,同时更新num和count
别忘了更新next_person的最后两个数为上一个人最后一个字符以及其出现次数!
作者:qsctech-sange
链接:https://leetcode-cn.com/problems/count-and-say/solution/ji-su-jie-bu-di-gui-zhi-ji-lu-qian-hou-liang-ren-p/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
"""
class Solution:
def countAndSay(self, n: int) -> str:
# 设置初始值
pre_str = "1"
for i in range(1, n):
cur_str, count, tmp_str = "", 1, pre_str[0]
for j in pre_str[1:]:
if j == tmp_str:
count += 1
else:
cur_str += str(count) + tmp_str
count = 1
tmp_str = j
cur_str += str(count) + tmp_str
pre_str = cur_str
return pre_str
a = Solution().countAndSay(3)
print(a)
|
[
"hello-lwz@163.com"
] |
hello-lwz@163.com
|
03a9735ba626fe96b762c8a33362a10ef2117c76
|
21e177a4d828f4e0a003e9424c4952dbc0b47d29
|
/testlints/test_lint_sub_ca_certificate_policies_marked_critical.py
|
fdded72a9b8ed872ca9ac65bd20ff499b974937f
|
[] |
no_license
|
846468230/Plint
|
1071277a55144bb3185347a58dd9787562fc0538
|
c7e7ca27e5d04bbaa4e7ad71d8e86ec5c9388987
|
refs/heads/master
| 2020-05-15T12:11:22.358000
| 2019-04-19T11:46:05
| 2019-04-19T11:46:05
| 182,255,941
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,279
|
py
|
import sys
sys.path.append("..")
from lints import base
from lints import lint_sub_ca_certificate_policies_marked_critical
import unittest
import os
from cryptography import x509
from cryptography.hazmat.backends import default_backend
class TestSubCaPolicyCrit(unittest.TestCase):
'''test lint_sub_ca_certificate_policies_marked_critical.py'''
def test_SubCaPolicyCrit(self):
certPath ='..\\testCerts\\subCAWCertPolicyCrit.pem'
lint_sub_ca_certificate_policies_marked_critical.init()
with open(certPath, "rb") as f:
cert = x509.load_pem_x509_certificate(f.read(), default_backend())
out = base.Lints["w_sub_ca_certificate_policies_marked_critical"].Execute(cert)
self.assertEqual(base.LintStatus.Warn,out.Status)
def test_SubCaPolicyNotCrit(self):
certPath ='..\\testCerts\\subCAWCertPolicyNoCrit.pem'
lint_sub_ca_certificate_policies_marked_critical.init()
with open(certPath, "rb") as f:
cert = x509.load_pem_x509_certificate(f.read(), default_backend())
out = base.Lints["w_sub_ca_certificate_policies_marked_critical"].Execute(cert)
self.assertEqual(base.LintStatus.Pass,out.Status)
if __name__=="__main__":
unittest.main(verbosity=2)
|
[
"846468230@qq.com"
] |
846468230@qq.com
|
7db12f0089bc848a4c09ea3a04ec1d7797dfce8a
|
675cdd4d9d2d5b6f8e1383d1e60c9f758322981f
|
/supervised_learning/0x11-attention/8-transformer_decoder_block.py
|
6297de99d6e9a896c8f3eaa4dd43d2e1acc22042
|
[] |
no_license
|
AndresSern/holbertonschool-machine_learning-1
|
5c4a8db28438d818b6b37725ff95681c4757fd9f
|
7dafc37d306fcf2ea0f5af5bd97dfd78d388100c
|
refs/heads/main
| 2023-07-11T04:47:01.565852
| 2021-08-03T04:22:38
| 2021-08-03T04:22:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,821
|
py
|
#!/usr/bin/env python3
""" Tranformer decoder block"""
import tensorflow as tf
MultiHeadAttention = __import__('6-multihead_attention').MultiHeadAttention
class DecoderBlock(tf.keras.layers.Layer):
""" create an encoder block for a transformer: """
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""
ARGS:
-dm - the dimensionality of the model
-h - the number of heads
-hidden - the number of hidden units
in the fully connected layer
-drop_rate - the dropout rate
"""
super().__init__()
self.mha1 = MultiHeadAttention(dm, h)
self.mha2 = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(units=hidden,
activation='relu')
self.dense_output = tf.keras.layers.Dense(units=dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
self.layernorm3 = tf.keras.layers.LayerNormalization(epsilon=1e-6)
self.dropout1 = tf.keras.layers.Dropout(drop_rate)
self.dropout2 = tf.keras.layers.Dropout(drop_rate)
self.dropout3 = tf.keras.layers.Dropout(drop_rate)
def call(self, x, encoder_output, training, look_ahead_mask, padding_mask):
""" Function that returns a tensor containing the block’s output
ARGS:
-x :{tensor} shape (batch, target_seq_len, dm)
containing the input to the decoder block
-encoder_output :{tensor} shape (batch, input_seq_len, dm)
containing the output of the encoder
-training: {boolean} : to determine if the model is training
-look_ahead_mask: the mask to be applied to the
first multi head attention layer
-padding_mask: the mask to be applied to the
second multi head attention layer
Returns:
-a tensor of shape (batch, target_seq_len, dm)
containing the block’s output
"""
attn1, attn_weights_block1 = self.mha1(x, x, x, look_ahead_mask)
attn1 = self.dropout1(attn1, training=training)
out1 = self.layernorm1(attn1 + x)
attn2, attn_weights_block2 = self.mha2(out1, encoder_output,
encoder_output,
padding_mask)
attn2 = self.dropout2(attn2, training=training)
out2 = self.layernorm2(attn2 + out1)
ffn_output = self.dense_hidden(out2)
ffn_output = self.dense_output(ffn_output)
ffn_output = self.dropout3(ffn_output, training=training)
out3 = self.layernorm3(ffn_output + out2)
return out3
|
[
"bouzouitina.hamdi@gmail.com"
] |
bouzouitina.hamdi@gmail.com
|
57a43a810299204f78640312238dbe2c58d1d9a6
|
551b75f52d28c0b5c8944d808a361470e2602654
|
/huaweicloud-sdk-kms/huaweicloudsdkkms/v1/model/list_secrets_request.py
|
ec09eb7b62cb6671442582b7035c6ecf09abdefa
|
[
"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,501
|
py
|
# coding: utf-8
import pprint
import re
import six
class ListSecretsRequest:
"""
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 = {
'limit': 'str',
'marker': 'str'
}
attribute_map = {
'limit': 'limit',
'marker': 'marker'
}
def __init__(self, limit=None, marker=None):
"""ListSecretsRequest - a model defined in huaweicloud sdk"""
self._limit = None
self._marker = None
self.discriminator = None
if limit is not None:
self.limit = limit
if marker is not None:
self.marker = marker
@property
def limit(self):
"""Gets the limit of this ListSecretsRequest.
每页返回的个数。 默认值:50。
:return: The limit of this ListSecretsRequest.
:rtype: str
"""
return self._limit
@limit.setter
def limit(self, limit):
"""Sets the limit of this ListSecretsRequest.
每页返回的个数。 默认值:50。
:param limit: The limit of this ListSecretsRequest.
:type: str
"""
self._limit = limit
@property
def marker(self):
"""Gets the marker of this ListSecretsRequest.
分页查询起始的资源id,为空时为查询第一页
:return: The marker of this ListSecretsRequest.
:rtype: str
"""
return self._marker
@marker.setter
def marker(self, marker):
"""Sets the marker of this ListSecretsRequest.
分页查询起始的资源id,为空时为查询第一页
:param marker: The marker of this ListSecretsRequest.
:type: str
"""
self._marker = marker
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, ListSecretsRequest):
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
|
415113fb75120a82dfd4e56463217dc72faec19b
|
10abe784a87ce1f9b37383471af15c69db7087ed
|
/snippets/input_3.py
|
cc99892ca9e2792c2974c9f1a1221bbd023922d8
|
[] |
no_license
|
The-Cooper-Union-CS102/Lesson-7-Introduction-To-Python
|
e5f27dadbea27dda83bde7893771d39c0d4cb064
|
e663bb2e5373b19fd79553757c0ab52e9600518a
|
refs/heads/main
| 2023-01-24T13:03:21.161831
| 2020-11-24T22:51:54
| 2020-11-24T22:51:54
| 303,213,874
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 315
|
py
|
opened_file = open('README.md')
content = opened_file.read()
print(f'Number of characters: {len(content)}')
words = content.split()
print(f'Number of words: {len(words)}')
lines = content.split('\n')
print(f'Number of lines: {len(lines)}')
print(f'Number of unique words: {len(set(words))}')
opened_file.close()
|
[
"cory.nezin@gmail.com"
] |
cory.nezin@gmail.com
|
5c6af0f82f0c47d71d0ca32753a263aaa76c23a5
|
3784268a19831d75753392c726ed59118dde632d
|
/cifar/eval_all.py
|
cef8a0014979778f66cbd7f671d7f481776959c7
|
[
"MIT"
] |
permissive
|
joaomonteirof/e2e_verification
|
d789399e026a9e6505395a7decae79da0057f3f4
|
867f7a2fbdb2ac9154c31e1e63762b9a58b32d7e
|
refs/heads/master
| 2022-12-08T13:24:03.653512
| 2020-09-02T03:28:42
| 2020-09-02T03:28:42
| 186,659,374
| 8
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,461
|
py
|
from __future__ import print_function
import argparse
import torch
from torchvision import datasets, transforms
from models import vgg, resnet, densenet
import numpy as np
import os
import sys
import glob
from utils import *
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Cifar10 - Evaluation of set of cps')
parser.add_argument('--cp-path', type=str, default=None, metavar='Path', help='Path for checkpoints')
parser.add_argument('--data-path', type=str, default='./data/', metavar='Path', help='Path to data')
parser.add_argument('--model', choices=['vgg', 'resnet', 'densenet'], default='resnet')
parser.add_argument('--dropout-prob', type=float, default=0.25, metavar='p', help='Dropout probability (default: 0.25)')
parser.add_argument('--no-cuda', action='store_true', default=False, help='Disables GPU use')
args = parser.parse_args()
args.cuda = True if not args.no_cuda and torch.cuda.is_available() else False
transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize([x / 255 for x in [125.3, 123.0, 113.9]], [x / 255 for x in [63.0, 62.1, 66.7]])])
validset = datasets.CIFAR10(root='./data', train=False, download=True, transform=transform_test)
labels_list = [x[1] for x in validset]
idxs_enroll, idxs_test, labels = create_trials_labels(labels_list)
print('\n{} trials created out of which {} are target trials'.format(len(idxs_enroll), np.sum(labels)))
cp_list = glob.glob(args.cp_path+'*.pt')
best_model, best_e2e_eer = None, float('inf')
for cp in cp_list:
ckpt = torch.load(cp, map_location = lambda storage, loc: storage)
try :
dropout_prob, n_hidden, hidden_size, softmax = ckpt['dropout_prob'], ckpt['n_hidden'], ckpt['hidden_size'], ckpt['sm_type']
except KeyError as err:
print("Key Error: {0}".format(err))
print('\nProbably old cp has no info regarding classifiers arch!\n')
try:
n_hidden, hidden_size, softmax = get_classifier_config_from_cp(ckpt)
dropout_prob = args.dropout_prob
except:
print('\nSkipping cp {}. Could not load it.'.format(cp))
continue
if args.model == 'vgg':
model = vgg.VGG('VGG16', nh=n_hidden, n_h=hidden_size, dropout_prob=dropout_prob, sm_type=softmax)
elif args.model == 'resnet':
model = resnet.ResNet18(nh=n_hidden, n_h=hidden_size, dropout_prob=dropout_prob, sm_type=softmax)
elif args.model == 'densenet':
model = densenet.densenet_cifar(nh=n_hidden, n_h=hidden_size, dropout_prob=dropout_prob, sm_type=softmax)
try:
model.load_state_dict(ckpt['model_state'], strict=True)
except:
print('\nSkipping model {}'.format(cp.split('/')[-1]))
continue
if args.cuda:
device = get_freer_gpu()
model = model.cuda(device)
cos_scores = []
e2e_scores = []
out_e2e = []
out_cos = []
mem_embeddings = {}
model.eval()
with torch.no_grad():
for i in range(len(labels)):
enroll_ex = str(idxs_enroll[i])
try:
emb_enroll = mem_embeddings[enroll_ex]
except KeyError:
enroll_ex_data = validset[idxs_enroll[i]][0].unsqueeze(0)
if args.cuda:
enroll_ex_data = enroll_ex_data.cuda(device)
emb_enroll = model.forward(enroll_ex_data).detach()
mem_embeddings[str(idxs_enroll[i])] = emb_enroll
test_ex = str(idxs_test[i])
try:
emb_test = mem_embeddings[test_ex]
except KeyError:
test_ex_data = validset[idxs_test[i]][0].unsqueeze(0)
if args.cuda:
test_ex_data = test_ex_data.cuda(device)
emb_test = model.forward(test_ex_data).detach()
mem_embeddings[str(idxs_test[i])] = emb_test
e2e_scores.append( model.forward_bin(torch.cat([emb_enroll, emb_test],1)).squeeze().item() )
cos_scores.append( torch.nn.functional.cosine_similarity(emb_enroll, emb_test).mean().item() )
out_e2e.append([str(idxs_enroll[i]), str(idxs_test[i]), e2e_scores[-1]])
out_cos.append([str(idxs_enroll[i]), str(idxs_test[i]), cos_scores[-1]])
e2e_scores = np.asarray(e2e_scores)
cos_scores = np.asarray(cos_scores)
all_scores = (e2e_scores + 0.5*(cos_scores+1.))*0.5
labels = np.asarray(labels)
model_id = cp.split('/')[-1]
print('\nEval of model {}:'.format(model_id))
e2e_eer, e2e_auc, avg_precision, acc, threshold = compute_metrics(labels, e2e_scores)
print('\nE2E:')
print('ERR, AUC, Average Precision, Accuracy and corresponding threshold: {}, {}, {}, {}, {}'.format(e2e_eer, e2e_auc, avg_precision, acc, threshold))
cos_eer, cos_auc, avg_precision, acc, threshold = compute_metrics(labels, cos_scores)
print('\nCOS:')
print('ERR, AUC, Average Precision, Accuracy and corresponding threshold: {}, {}, {}, {}, {}'.format(e2e_eer, e2e_auc, avg_precision, acc, threshold))
fus_eer, fus_auc, avg_precision, acc, threshold = compute_metrics(labels, all_scores)
print('\nFUS:')
print('ERR, AUC, Average Precision, Accuracy and corresponding threshold: {}, {}, {}, {}, {}'.format(e2e_eer, e2e_auc, avg_precision, acc, threshold))
if e2e_eer<best_e2e_eer:
best_model, best_e2e_eer, best_e2e_auc, best_cos_eer, best_cos_auc, best_fus_eer, best_fus_auc = model_id, e2e_eer, e2e_auc, cos_eer, cos_auc, fus_eer, fus_auc
print('Best model and corresponding E2E eer and auc: {} - {} - {}'.format(best_model, best_e2e_eer, best_e2e_auc))
print('Corresponding COS eer and auc: {} - {} - {}'.format(best_model, best_cos_eer, best_cos_auc))
print('Corresponding FUS eer and auc: {} - {} - {}'.format(best_model, best_fus_eer, best_fus_auc))
|
[
"joaomonteirof@gmail.com"
] |
joaomonteirof@gmail.com
|
34cd44260e0cfe1b01d0c68d5483e76202bc1907
|
92e3a6424326bf0b83e4823c3abc2c9d1190cf5e
|
/scripts/icehouse/opt/stack/heat/heat/openstack/common/db/exception.py
|
27987c57b6aeadb45b9547d26ff7820317516fa3
|
[
"Apache-2.0"
] |
permissive
|
AnthonyEzeigbo/OpenStackInAction
|
d6c21cf972ce2b1f58a93a29973534ded965d1ea
|
ff28cc4ee3c1a8d3bbe477d9d6104d2c6e71bf2e
|
refs/heads/master
| 2023-07-28T05:38:06.120723
| 2020-07-25T15:19:21
| 2020-07-25T15:19:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,853
|
py
|
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""DB related custom exceptions."""
from heat.openstack.common.gettextutils import _
class DBError(Exception):
"""Wraps an implementation specific exception."""
def __init__(self, inner_exception=None):
self.inner_exception = inner_exception
super(DBError, self).__init__(str(inner_exception))
class DBDuplicateEntry(DBError):
"""Wraps an implementation specific exception."""
def __init__(self, columns=[], inner_exception=None):
self.columns = columns
super(DBDuplicateEntry, self).__init__(inner_exception)
class DBDeadlock(DBError):
def __init__(self, inner_exception=None):
super(DBDeadlock, self).__init__(inner_exception)
class DBInvalidUnicodeParameter(Exception):
message = _("Invalid Parameter: "
"Unicode is not supported by the current database.")
class DbMigrationError(DBError):
"""Wraps migration specific exception."""
def __init__(self, message=None):
super(DbMigrationError, self).__init__(str(message))
class DBConnectionError(DBError):
"""Wraps connection specific exception."""
pass
|
[
"cody@uky.edu"
] |
cody@uky.edu
|
ae802470108ec86a3a76c105e3ae18dd8acbfab3
|
904fd519e3f10c8a21653d3fdea34915d2e708e2
|
/dat/migrations/0001_initial.py
|
586992533e52fb421a095ca0084fdeddfc2485fe
|
[
"Apache-2.0"
] |
permissive
|
Kgermando/es-script
|
5d4c74996dd83a2e91fb462f3ceb4943c887811c
|
f1b10ecf2c805e8875a025e7033c724e236f6cd1
|
refs/heads/main
| 2023-06-26T00:54:31.351588
| 2021-07-26T15:40:14
| 2021-07-26T15:40:14
| 366,509,163
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,548
|
py
|
# Generated by Django 3.1.7 on 2021-06-11 05:52
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contacts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Dat',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_date', models.DateTimeField(auto_now_add=True)),
('questions1', models.CharField(default='-', max_length=200, null=True)),
('questions2', models.CharField(default='-', max_length=200, null=True)),
('Statut', models.CharField(choices=[('---------', '--------------'), ('Accord', 'Accord'), ('Déjà payé son crédit', 'Déjà payé son crédit'), ('Refus', 'Refus'), ('Rappel', 'Rappel (interlocuteur demande de rappeler)'), ('Injoignable', 'Injoignable'), ('Absent', 'Absent'), ('Faux numéro', 'Faux numéro'), ('Réfléchir', 'Réfléchir')], max_length=30, null=True)),
('Bound', models.CharField(max_length=20, null=True)),
('Contact', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contacts.contact')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
|
[
"katakugermain@gmail.com"
] |
katakugermain@gmail.com
|
fc31d030779e0d6f5442220445962d8dc9cd3eaf
|
c0ca5fe06bce08f9ab739cd4bdcddd782b915898
|
/Python_tests/decoraror_kwargs/spookiplugins.py
|
6fcf735fc81f09b74b864cfc0566b0d1b31bdb8a
|
[] |
no_license
|
PhilippeCarphin/tests
|
bac30ceb9d2d8135b34af3e520fe2a9030028044
|
9716f53a41ed025c2d346be90c19866c59a03daa
|
refs/heads/master
| 2023-07-06T15:09:53.048447
| 2023-07-04T23:52:43
| 2023-07-04T23:52:43
| 53,367,022
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,215
|
py
|
from pyunix import make_unix_function
# noinspection PyUnusedLocal
@make_unix_function
def decorated_arg_function(humeur=None,
couleur=8,
bonjour=False) -> IMO:
"""EXAMPLE SPECIFICATION : A function that doesn't do anything.
# TODO The behavior will be that declaring a function to be
or simpler than that.
a factory function that does this:
make_unix_function(initial_words, arg_spec):
git_clone('https://github.com/philippecarphin/configurations')
git_clone('https://github.com/philippecarphin/configurations', target='~/Documents/GitHub/config')
mv(src='somefile', 'dst=somefile')
mv(src='somefile', 'dst=somefile')
{target: NO_DEFAULT, link_name= NO_DEFAULT})
It is decorated to make a function that checks the argumensts, builds a
string and makes a call to the spooki plugin by the same name.
humeur is a mandatory argument, an exception will be raised if a call is
made without it.
couleur has a default value, it doesn't need to be specified.
bonjour is a flag if it is set to true then the flag will be appended
to the command
"""
pass
class PyUnixArg:
def __init__(self, argname):
self.argname = argnamejk
class PyUnixOption:
# option
# optarg
pass
class PyUnixPosarg:
# argname
# default
pass
class PyUnixFlag:
pass
class PyArgList:
# just a list of words
# like for mv or rm
# except mv is more complicated. Then you have
# to add something like a last_arg property along with the option_before
# property. If last_arg is true, then the function will have
# unix_move(target=os.path.join(...), files_to_move=my_file_list)
# unix_move(files_to_move=my_file_list, target=os.path.join(...))
# So I would specify one kwarg that is a PyArgList, and one that is a PyUnixOption.
# and I would get the function above.
class PyUnixKwarg(name=this, other_prop=that, option_prefix='--', with_equal=False)
# def make_unix_function(initial_words, args = ((name, default), (name, default), ...), kwargs, options_before=True)
def make_unix_function(initial_words,list_arg_spec):
# list_arg_spec is a list of PyUnixXYarg
def make_unix_function(initial_words, argspec=[()], kwargspec={}, options_before=True, varargs=false):
# Validate that argspec is a list of 2-element tuples
# validate that kwargspec is a dictionary of
# {
# PyUnixKwarg(name=this, other_prop=that, option_prefix='--', with_equal=False, flag=False)
# }
# Both argspec and kwargspec will be lists of these. Optio
# Argspec same 'struct' but an ordered list of them instead of a dictionary of them.
if options_before:
def new_func(*args, **kwargs):
option_words = make_option_words(kwargspec, kwargs) # A list
arg_words = list(args)
command_words = initial_words + option_words + arg_words
subprocess.run(command_words)
else:
def new_func(*args, **kwargs):
option_words = make_option_words(kwargspec, kwargs) # A list
arg_words = list(args)
command_words = initial_words + arg_words + option_words
subprocess.run(command_words)
# noinspection PyUnusedLocal
@make_unix_function
def git(temperature="cold",
pressure=130,
some_flag=False) -> IMO:
""" This docstring will be given over to the new function """
pass
# noinspection PyUnusedLocal
@make_unix_function
def annotated_func(humidity: int=8,
stickyness: str="hello",
sweatiness: str=None,
sunny: bool=False) -> IMO:
pass
if __name__ == "__main__":
# print("CALLING DECORATED FUNCTION")
decorated_arg_function(humeur='piss-bucket', couleur=8, bonjour=True)
# print("CALLING DECORATED FUNCTION")
# decorated_arg_function(humeur='Joyeux', bonjour=True)
# print("CALLING DECORATED FUNCTION")
# decorated_arg_function(couleur='rouge', humeur='piss-bucket', bonjour=True)
windchill()
windchill(some_flag=True)
annotated_func(humidity=8, stickyness="9", sweatiness="asdf", sunny=True)
|
[
"philippe.carphin@polymtl.ca"
] |
philippe.carphin@polymtl.ca
|
bdc0db1a009ab22c4fed0cab30158cc6d04d80fb
|
dde0d75db42c19390f2625a7888586e4d2a14fd7
|
/devel/.private/cob_object_detection_msgs/lib/python2.7/dist-packages/cob_object_detection_msgs/msg/_TrainObjectResult.py
|
4334f1679464dd809bb35e2ddf81fa5c4c2cac43
|
[] |
no_license
|
dhemp09/uml-robotics
|
16460efe8195a3f9a6a8296047f4fd4d9df0de80
|
862132e00e221b0a86bc283e7568efa984be673f
|
refs/heads/master
| 2020-03-26T09:44:04.033762
| 2018-08-15T18:11:18
| 2018-08-15T18:11:18
| 144,762,178
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,963
|
py
|
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from cob_object_detection_msgs/TrainObjectResult.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class TrainObjectResult(genpy.Message):
_md5sum = "d41d8cd98f00b204e9800998ecf8427e"
_type = "cob_object_detection_msgs/TrainObjectResult"
_has_header = False #flag to mark the presence of a Header object
_full_text = """# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======
# The results
"""
__slots__ = []
_slot_types = []
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(TrainObjectResult, self).__init__(*args, **kwds)
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
pass
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
pass
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', self)))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(locals().get('_x', self)))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
|
[
"dhemp09@gmail.com"
] |
dhemp09@gmail.com
|
276311ba192111ad3852fba51761d00a98d969e2
|
e0a51ac08f13f4d3d89ccd770225a9ca0cecb80a
|
/seucorretor/cidades/admin.py
|
6d8a0d0175ea14209d65b26b1205eee421665a9c
|
[] |
no_license
|
MarcosDihl/corretaza-buscador
|
8bbc94a81f7414a3cbc4a1b7ce7b841431209b1c
|
a3579059839f32c585dda05775fa525fdd34121e
|
refs/heads/master
| 2022-04-04T03:36:47.360708
| 2018-01-31T03:05:13
| 2018-01-31T03:05:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 267
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import absolute_import
from django.contrib import admin
from .models import Cidade, Regiao, Bairro
admin.site.register(Cidade)
admin.site.register(Regiao)
admin.site.register(Bairro)
|
[
"huogerac@gmail.com"
] |
huogerac@gmail.com
|
d12d58a30488fa6fba934eb791e0ccbbffd9631b
|
ed63c99ccb0beebcfe9bff2ef68e9c86877fa7d8
|
/vocoder/train.py
|
b2449f66ffe8fcb05e7c7aeccb502f70c6c114b5
|
[
"MIT"
] |
permissive
|
X-CCS/Real-Time-Voice-Cloning-1
|
d25588a852b87849f9a517d587a3a36d086bbae0
|
ae4aa2aa1605168d2f04275e1a45f6de2d88f3f0
|
refs/heads/master
| 2022-02-28T03:29:26.135339
| 2019-10-23T12:01:10
| 2019-10-23T12:01:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,376
|
py
|
from vocoder.models.fatchord_version import WaveRNN
from vocoder.vocoder_dataset import VocoderDataset, collate_vocoder
from vocoder.distribution import discretized_mix_logistic_loss
from vocoder.display import stream, simple_table
from vocoder.gen_wavernn import gen_testset
from torch.utils.data import DataLoader
from pathlib import Path
from torch import optim
import torch.nn.functional as F
import vocoder.hparams as hp
import numpy as np
import time
def train(run_id: str, syn_dir: Path, voc_dir: Path, models_dir: Path, ground_truth: bool,
save_every: int, backup_every: int, force_restart: bool):
# Check to make sure the hop length is correctly factorised
assert np.cumprod(hp.voc_upsample_factors)[-1] == hp.hop_length
# Instantiate the model
print("Initializing the model...")
model = WaveRNN(
rnn_dims=hp.voc_rnn_dims,
fc_dims=hp.voc_fc_dims,
bits=hp.bits,
pad=hp.voc_pad,
upsample_factors=hp.voc_upsample_factors,
feat_dims=hp.num_mels,
compute_dims=hp.voc_compute_dims,
res_out_dims=hp.voc_res_out_dims,
res_blocks=hp.voc_res_blocks,
hop_length=hp.hop_length,
sample_rate=hp.sample_rate,
mode=hp.voc_mode
).cuda()
# Initialize the optimizer
optimizer = optim.Adam(model.parameters())
for p in optimizer.param_groups:
p["lr"] = hp.voc_lr
loss_func = F.cross_entropy if model.mode == "RAW" else discretized_mix_logistic_loss
# Load the weights
model_dir = models_dir.joinpath(run_id)
model_dir.mkdir(exist_ok=True)
weights_fpath = model_dir.joinpath(run_id + ".pt")
if force_restart or not weights_fpath.exists():
print("\nStarting the training of WaveRNN from scratch\n")
model.save(weights_fpath, optimizer)
else:
print("\nLoading weights at %s" % weights_fpath)
model.load(weights_fpath, optimizer)
print("WaveRNN weights loaded from step %d" % model.step)
# Initialize the dataset
metadata_fpath = syn_dir.joinpath("train.txt") if ground_truth else \
voc_dir.joinpath("synthesized.txt")
mel_dir = syn_dir.joinpath("mels") if ground_truth else voc_dir.joinpath("mels_gta")
wav_dir = syn_dir.joinpath("audio")
dataset = VocoderDataset(metadata_fpath, mel_dir, wav_dir)
test_loader = DataLoader(dataset,
batch_size=1,
shuffle=True,
pin_memory=True)
# Begin the training
simple_table([('Batch size', hp.voc_batch_size),
('LR', hp.voc_lr),
('Sequence Len', hp.voc_seq_len)])
for epoch in range(1, 350):
data_loader = DataLoader(dataset,
collate_fn=collate_vocoder,
batch_size=hp.voc_batch_size,
num_workers=2,
shuffle=True,
pin_memory=True)
start = time.time()
running_loss = 0.
for i, (x, y, m) in enumerate(data_loader, 1):
x, m, y = x.cuda(), m.cuda(), y.cuda()
# Forward pass
y_hat = model(x, m)
if model.mode == 'RAW':
y_hat = y_hat.transpose(1, 2).unsqueeze(-1)
elif model.mode == 'MOL':
y = y.float()
y = y.unsqueeze(-1)
# Backward pass
loss = loss_func(y_hat, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
running_loss += loss.item()
speed = i / (time.time() - start)
avg_loss = running_loss / i
step = model.get_step()
k = step // 1000
if backup_every != 0 and step % backup_every == 0:
model.checkpoint(model_dir, optimizer)
if save_every != 0 and step % save_every == 0:
model.save(weights_fpath, optimizer)
msg = "| Epoch: %04d (%d/%d) | Loss: %.4f | %.1f steps/s | Step: %d | " % (
epoch, i, len(data_loader), avg_loss, speed, k
)
stream(msg)
gen_testset(model, test_loader, hp.voc_gen_at_checkpoint, hp.voc_gen_batched,
hp.voc_target, hp.voc_overlap, model_dir)
print("")
|
[
"red_wind@foxmail.com"
] |
red_wind@foxmail.com
|
baf29f1497792eadf8baea08bff17463c2572a94
|
5f6c16e89cf58304c2e70f1e34f14110fcec636c
|
/python-swagger-sdk/test/test_secret_network_rest_api.py
|
67db62646ec81cd1341b284912b0e92b3292fe27
|
[] |
no_license
|
mohammedpatla/secretapi
|
481c97901a5e92ca02e29470ab683df80ea0f26a
|
df420498bd0ae37fd1a152c3877a1342275a8f43
|
refs/heads/master
| 2022-12-25T01:55:18.038954
| 2020-10-04T23:13:54
| 2020-10-04T23:13:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 958
|
py
|
# coding: utf-8
"""
API for Secret Network by ChainofSecrets.org
A REST interface for state queries, transaction generation and broadcasting. # noqa: E501
OpenAPI spec version: 3.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.api.secret_network_rest_api import SecretNetworkRESTApi # noqa: E501
from swagger_client.rest import ApiException
class TestSecretNetworkRESTApi(unittest.TestCase):
"""SecretNetworkRESTApi unit test stubs"""
def setUp(self):
self.api = swagger_client.api.secret_network_rest_api.SecretNetworkRESTApi() # noqa: E501
def tearDown(self):
pass
def test_node_info_get(self):
"""Test case for node_info_get
The properties of the connected node # noqa: E501
"""
pass
if __name__ == '__main__':
unittest.main()
|
[
"lauraweindorf@gmail.com"
] |
lauraweindorf@gmail.com
|
8566f9e75de89e699548243255089d570f8f980a
|
a59ec95fddc064ea9a554ad41e4ac8e82376701a
|
/myshop/orders/forms.py
|
85b29fe6f1e2dd581d3dc42576bb2d6f250431df
|
[] |
no_license
|
Nicholas86/PythonDemos
|
449c08713c7c03633719a4ae7287b127783d7574
|
4f06639cc65a5e10cc993335d3d34e2d60aac983
|
refs/heads/master
| 2021-01-22T21:07:11.457179
| 2017-08-18T06:40:44
| 2017-08-18T06:40:44
| 100,681,216
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 442
|
py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
from django import forms
from .models import *
# 创建模型表单,根据模型Order
class OrderCreateForm(forms.ModelForm):
class Meta:
model = Order
# 表单展示的字段,用户需要填写的内容
fields = ['first_name', 'last_name', 'email', 'address','postal_code', 'city']
|
[
"970649831@qq.com"
] |
970649831@qq.com
|
58cb0959aa62afa5c2cbef4ea5407a68d55606ce
|
cceeb787cf02dfee98f6b913e0815a5250505a29
|
/special/special_m_CochranQ检验.py
|
9ec770271c99a0204bdee065914558bcfc190c82
|
[] |
no_license
|
shandakangping/BioStat
|
4782bdf599ddc4b44dcb9c4ad100459edbd2d221
|
c2ecc1282bc12228b88eeba66551aec87d30fd8e
|
refs/heads/master
| 2022-03-28T05:37:50.322348
| 2019-12-05T04:20:17
| 2019-12-05T04:20:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,392
|
py
|
#CochranQ检验 https://spssau.com/front/spssau/helps/medicalmethod/cochranQ.html
import pandas as pd
from statsmodels.sandbox.stats.runs import cochrans_q
def core(x):
'''
x: pd.DataFrame()
'''
n = len(x)
freq = x.apply(lambda a:a.value_counts()).T
perc = freq.apply(lambda a:a/n)
f1 = freq.T
f1 = f1.reset_index()
f1.index = ['频数', '频数']
f1 = f1.reset_index().set_index(['level_0','index'])
f2 = perc.T
f2 = f2.reset_index()
f2.index = ['百分比', '百分比']
f2 = f2.reset_index().set_index(['level_0','index'])
f = f1.append(f2).T
f.columns.names = [None, None]
z, p = cochrans_q(x)
df = pd.Series({'样本量':n, 'CochransQ 统计量':z, 'p':p, 'df':x.shape[1]-1})
df = df.to_frame().T.set_index('样本量')
res = {'频数分析结果':f, 'CochranQ检验结果': df}
return res
if __name__ == '__main__':
d = '''村长 村民1 村民2 村民3 村民4 村民5 村民6 村民7 村民8 村民9 村民10
村长1 0 1 1 0 0 1 1 1 1 1
村长2 1 1 0 0 0 1 1 1 1 1
村长3 0 1 1 1 1 0 0 0 0 1
村长4 0 0 0 0 1 1 0 0 1 0'''
df = pd.DataFrame([i.split('\t') for i in d.split('\n')]).T.set_index(0).T
df = df.set_index('村长')
df.columns.name = None
df = df.astype(int)
res = core(x)
|
[
"shenwanxiang@tsinghua.org.cn"
] |
shenwanxiang@tsinghua.org.cn
|
12a26396e8dab5f0018ea9c4f98927ab88a5a63b
|
f0d713996eb095bcdc701f3fab0a8110b8541cbb
|
/pzQXHMqizBmaLDCHc_9.py
|
15c6a97cb23a0e43aaf7b064fe8045b18ba3fc93
|
[] |
no_license
|
daniel-reich/turbo-robot
|
feda6c0523bb83ab8954b6d06302bfec5b16ebdf
|
a7a25c63097674c0a81675eed7e6b763785f1c41
|
refs/heads/main
| 2023-03-26T01:55:14.210264
| 2021-03-23T16:08:01
| 2021-03-23T16:08:01
| 350,773,815
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,858
|
py
|
"""
It's a Pokemon battle! Your task is to calculate the damage that a particular
move would do using the following formula (not the actual one from the game):
damage = 50 * (attack / defense) * effectiveness
* attack = your attack power
* defense = the opponent's defense
* effectiveness = the effectiveness of the attack based on the matchup (see explanation below)
Effectiveness:
Attacks can be super effective, neutral, or not very effective depending on
the matchup. For example, water would be super effective against fire, but not
very effective against grass.
* Super effective: 2x damage
* Neutral: 1x damage
* Not very effective: 0.5x damage
To prevent this challenge from being tedious, you'll only be dealing with four
types: fire, water, grass, and electric. Here is the effectiveness of each
matchup:
* fire > grass
* fire < water
* fire = electric
* water < grass
* water < electric
* grass = electric
The function you must implement takes in:
* your type
* the opponent's type
* your attack power
* the opponent's defense
### Examples
calculate_damage("fire", "water", 100, 100) ➞ 25
calculate_damage("grass", "fire", 35, 5) ➞ 175
calculate_damage("electric", "fire", 100, 100) ➞ 50
### Notes
Any type against itself is not very effective. Also, assume that the
relationships between different types are symmetric (if A is super effective
against B, then B is not very effective against A).
"""
def calculate_damage(your_type, opponent_type, attack, defense):
eff = (("fire", "grass"), ("water", "fire"), ("grass", "water"), ("electric", "water"))
if (your_type, opponent_type) in eff:
effectiveness = 2
elif (opponent_type, your_type) in eff:
effectiveness = 0.5
else:
effectiveness = 1
return 50 * (attack / defense) * effectiveness
|
[
"daniel.reich@danielreichs-MacBook-Pro.local"
] |
daniel.reich@danielreichs-MacBook-Pro.local
|
294569d8a26a8235760f1210848bfc69ed7e87ec
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_242/ch150_2020_04_13_20_26_06_768478.py
|
39ac017bfbff2072d7991d338db44e25d37255e3
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 178
|
py
|
import math
def calcula_pi(n):
contador=1
soma=0
while contador<=n:
soma+=6/(contador**2)
contador+=1
pi = math.sqrt(soma)
return pi
|
[
"you@example.com"
] |
you@example.com
|
b8e9300a6881004ad7de71e3459c045a7a356399
|
6cb25fcb5ce0e4f3b8cfb1165abe15d3de7fce82
|
/link/tasks.py
|
17747a2aee50b47ae5cd6eecc5882eb6e64a79f8
|
[] |
no_license
|
RoodrigoRoot/bills_celery
|
4d3f904821f49629f2c024772899943e06042451
|
3ec5c5806c9b1ec75ff6ec3b287bf4d0a2537164
|
refs/heads/master
| 2022-12-24T09:04:46.917201
| 2020-02-10T22:41:55
| 2020-02-10T22:41:55
| 239,628,828
| 0
| 0
| null | 2022-12-08T03:35:29
| 2020-02-10T22:42:03
|
Python
|
UTF-8
|
Python
| false
| false
| 330
|
py
|
from celery import shared_task
from ftplib import FTP
@shared_task
def get_bills_moth():
#month = "manual_en.pdf"
#ftp = FTP("demo.wftpserver.com")
#ftp.login("demo-user", "demo-user")
#ftp.cwd("download")
#ftp.retrbinary("RETR " + month ,open(month, 'wb').write)
print("Factura descargada")
return 0
|
[
"roodrigoroot@gmail.com"
] |
roodrigoroot@gmail.com
|
e0d214ad9218a623239cde1c8e194ac4ca8332fb
|
7d44d7e8b12263ed3f692fba4f19eaff0420c5c0
|
/earth/adventurers.py
|
d812355915f9774a05acd68bdb8c1dd2cbebff3e
|
[
"MIT"
] |
permissive
|
ryltsev/earth
|
64a59b5af20477d0e9c1e2585d8772223d6b7421
|
2787eeb37692f1c82bc12cb24a4c1574826204a7
|
refs/heads/master
| 2023-08-18T15:37:25.506828
| 2019-05-26T09:11:40
| 2019-05-26T09:11:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,272
|
py
|
import time
import typing
import attr
from .year import Months
from .travel import fly, AirportProblem
class Busy(RuntimeError):
"""Raised when Adventurer is busy."""
def pack(adventurer):
print(f"{adventurer.profile} {adventurer.name} is packing 👜")
@attr.s(auto_attribs=True, kw_only=True)
class Adventurer:
name: str
location: str
profile: str
_availability: typing.List = attr.ib(repr=False)
_calendar: typing.Dict = attr.ib(repr=False, init=False)
_getting_ready: typing.List[typing.Callable] = attr.ib(repr=False)
_ready: bool = attr.ib(repr=False, default=False, init=False)
def __str__(self):
return f"{self.profile} {self.name}"
@_getting_ready.default
def default_activities(self):
return [pack]
@_availability.default
def default_availability(self):
return list(Months)
def __attrs_post_init__(self):
self._calendar = {
month: month in self._availability for month in Months
}
def hello(self):
print(f"{self.profile} Hello, my name is {self.name}!")
def rsvp(self, event):
available = self._calendar[event.month]
if not available:
raise Busy(f"{self} sorry, I'm busy!")
self._calendar[event.month] = False
def get_ready(self):
if self._ready is not True:
for activity in self._getting_ready:
activity(self)
self._ready = True
return self._ready
def travel_to(self, event):
if self.location != event.location:
try:
location = fly(self.location, event.location)
except AirportProblem as exc:
print(f"{self}'s flight was cancelled 😞 {exc}")
else:
print(
f"{self} is travelling: "
f"{self.location} ✈️ {event.location}"
)
self.location = location
def new_panda(name, **kwargs):
def eat(panda):
for i in range(4):
print(f"{panda.profile} {panda.name} is eating... 🌱")
time.sleep(5)
kwargs.setdefault("location", "Asia")
return Adventurer(
name=name, profile="🐼", getting_ready=[eat, pack], **kwargs
)
def new_bear(name, **kwargs):
kwargs.setdefault("location", "North America")
kwargs.setdefault("availability", [Months.JUN, Months.JUL, Months.AUG])
return Adventurer(name=name, profile="🐻", **kwargs)
def new_tiger(name, **kwargs):
# Tigers travel light; do not pack
kwargs.setdefault("location", "Asia")
return Adventurer(name=name, profile="🐯", getting_ready=[], **kwargs)
def new_koala(name, **kwargs):
kwargs.setdefault("location", "Australia")
return Adventurer(name=name, profile="🐨", **kwargs)
def new_lion(name, **kwargs):
kwargs.setdefault("location", "Africa")
return Adventurer(name=name, profile="🦁", **kwargs)
def new_frog(name, **kwargs):
kwargs.setdefault("location", "South America")
return Adventurer(name=name, profile="🐸", **kwargs)
def new_fox(name, **kwargs):
kwargs.setdefault("location", "Europe")
return Adventurer(name=name, profile="🦊", getting_ready=[pack], **kwargs)
|
[
"raphael@hackebrot.de"
] |
raphael@hackebrot.de
|
dc2c6fac31db0f166a99c5899a1563edaf631d31
|
f682bf62d7de4afeeadf7c4f93dd51cfe51a78ec
|
/vikuraa/NumberDisplay.py
|
e781b41148dfc47b4834f3122482c00767f9e032
|
[] |
no_license
|
aliaafee/vikuraa
|
1159d19573f043baa8401510888c22920d9edf04
|
df02493249b563c2f14ecd517ef8cbd09f1641a0
|
refs/heads/master
| 2020-05-29T13:13:35.554124
| 2017-02-20T18:21:48
| 2017-02-20T18:21:48
| 82,592,264
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,457
|
py
|
import wx
class NumberDisplay(wx.Panel):
def __init__(self, parent, rows, first_row_big=True, size=wx.Size(-1,-1)):
wx.Panel.__init__(self, parent, style=wx.SUNKEN_BORDER, size=size)
self.SetBackgroundColour('WHITE')
self.label = {}
self.value = {}
gs = wx.FlexGridSizer(len(self.label), 2, 0, 0)
self.fontBig = wx.Font(
24,
family=wx.MODERN,
style=wx.NORMAL,
weight=wx.FONTWEIGHT_BOLD)
self.fontMed = wx.Font(
16,
family=wx.MODERN,
style=wx.NORMAL,
weight=wx.FONTWEIGHT_BOLD)
for i in range(len(rows)):
self.label[i] = wx.StaticText(
self,
label = rows[i],
size = wx.Size(-1,-1),
style=0)
self.value[i] = wx.StaticText(
self,
label = '',
size = wx.Size(-1,-1),
style=0)
if i == 0:
if first_row_big == True:
self.value[i].SetFont(self.fontBig)
else:
self.value[i].SetFont(self.fontMed)
else:
self.value[i].SetFont(self.fontMed)
gs.Add(self.label[i],
proportion=0,
flag=wx.ALL| wx.ALIGN_CENTER_VERTICAL,
border=5)
gs.Add(self.value[i],
proportion=0,
flag=wx.ALL| wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
border=5)
for i in range(len(self.label)):
gs.AddGrowableRow(i)
gs.AddGrowableCol(0)
self.SetSizer(gs)
def SetValue(self, row, value):
self.value[row].SetLabel(value)
self.Layout()
def GetStaticText(self, row):
return self.value[row]
if __name__ == "__main__":
app = wx.App()
frame = wx.Frame(None)
pnl = NumberDisplay(frame,
['Total Due',
'Incl. 6% GST',
'Tender',
'Balance'])
pnl.SetValue(0, 'Rf 9412.00')
sz = wx.BoxSizer()
sz.Add(pnl,1,wx.ALL|wx.EXPAND,10)
frame.SetSizer(sz)
frame.Show()
app.MainLoop()
|
[
"ali.aafee@gmail.com"
] |
ali.aafee@gmail.com
|
2bd17aa550e72879b0baf592355a60b8120b372f
|
1f9611710ffaf5e0493799f716d3006c2f27b412
|
/tests/test_madlib.py
|
dea7c141a360f9b41dc1300064bd9d61a683a647
|
[] |
no_license
|
majdalkilany/madlib-cli.1
|
2ea8d37cfe39e60151480c15ccad2841f58f53d8
|
48fb9e0b5aa1a9d29081e50304ff1e208ede3921
|
refs/heads/master
| 2022-12-02T19:14:57.538714
| 2020-08-22T14:39:52
| 2020-08-22T14:39:52
| 289,232,834
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 752
|
py
|
from madlib_cli_1.madlib import read_file ,parse ,merge_and_write_file
def test_read() :
expected = open('assets/mad_file.txt').read().strip()
received = read_file()
assert expected == received
def user_input_test () :
accepted = 'please enter name >> '
actual = user_input(['name'])
assert accepted == actual
def test_Parse():
expected = ["majd","27"]
received = parse( "hello i ma {majd}, I am {27} years old")
assert expected == received
def testMerge():
words = ['smart', 'boxes', 'hungry', 'eat']
text = 'A {} {} had a {} dog so they {} them'
received = merge_and_write_file(words, text)
expected = 'A smart boxes had a hungry dog so they eat them'
assert expected == received
|
[
"majdkilany92@gmail.com"
] |
majdkilany92@gmail.com
|
51df05dbb475d3d601e27c671a0abd7bfd968318
|
a02789088ef6f7134d70b7235fa92ddcab9a667b
|
/eventsourcing/popo.py
|
62bf9a207f000983720a274e3360dcd1d0d436a9
|
[
"BSD-3-Clause"
] |
permissive
|
bernardotorres/eventsourcing
|
89f4f6aaf62f321ce28f5ec9ddbb60712495aa8b
|
002077d185c261920f8ea8a397e292ab73a25319
|
refs/heads/main
| 2023-08-07T17:38:59.665618
| 2021-09-18T07:04:19
| 2021-09-18T07:04:19
| 407,116,568
| 0
| 0
|
BSD-3-Clause
| 2021-09-16T10:13:36
| 2021-09-16T10:13:35
| null |
UTF-8
|
Python
| false
| false
| 4,826
|
py
|
from collections import defaultdict
from threading import Lock
from typing import Any, Dict, Iterable, List, Optional
from uuid import UUID
from eventsourcing.persistence import (
AggregateRecorder,
ApplicationRecorder,
InfrastructureFactory,
IntegrityError,
Notification,
ProcessRecorder,
StoredEvent,
Tracking,
)
class POPOAggregateRecorder(AggregateRecorder):
def __init__(self) -> None:
self.stored_events: List[StoredEvent] = []
self.stored_events_index: Dict[UUID, Dict[int, int]] = defaultdict(dict)
self.database_lock = Lock()
def insert_events(self, stored_events: List[StoredEvent], **kwargs: Any) -> None:
with self.database_lock:
self.assert_uniqueness(stored_events, **kwargs)
self.update_table(stored_events, **kwargs)
def assert_uniqueness(
self, stored_events: List[StoredEvent], **kwargs: Any
) -> None:
new = set()
for s in stored_events:
# Check events don't already exist.
if s.originator_version in self.stored_events_index[s.originator_id]:
raise IntegrityError()
new.add((s.originator_id, s.originator_version))
# Check new events are unique.
if len(new) < len(stored_events):
raise IntegrityError()
def update_table(self, stored_events: List[StoredEvent], **kwargs: Any) -> None:
for s in stored_events:
self.stored_events.append(s)
self.stored_events_index[s.originator_id][s.originator_version] = (
len(self.stored_events) - 1
)
def select_events(
self,
originator_id: UUID,
gt: Optional[int] = None,
lte: Optional[int] = None,
desc: bool = False,
limit: Optional[int] = None,
) -> List[StoredEvent]:
with self.database_lock:
results = []
index = self.stored_events_index[originator_id]
positions: Iterable = index.keys()
if desc:
positions = reversed(list(positions))
for p in positions:
if gt is not None:
if not p > gt:
continue
if lte is not None:
if not p <= lte:
continue
s = self.stored_events[index[p]]
results.append(s)
if len(results) == limit:
break
return results
class POPOApplicationRecorder(ApplicationRecorder, POPOAggregateRecorder):
def select_notifications(self, start: int, limit: int) -> List[Notification]:
with self.database_lock:
results = []
i = start - 1
j = i + limit
for notification_id, s in enumerate(self.stored_events[i:j], start):
n = Notification(
id=notification_id,
originator_id=s.originator_id,
originator_version=s.originator_version,
topic=s.topic,
state=s.state,
)
results.append(n)
return results
def max_notification_id(self) -> int:
with self.database_lock:
return len(self.stored_events)
class POPOProcessRecorder(ProcessRecorder, POPOApplicationRecorder):
def __init__(self) -> None:
super().__init__()
self.tracking_table: Dict[str, int] = defaultdict(None)
def assert_uniqueness(
self, stored_events: List[StoredEvent], **kwargs: Any
) -> None:
super().assert_uniqueness(stored_events, **kwargs)
tracking: Optional[Tracking] = kwargs.get("tracking", None)
if tracking:
last = self.tracking_table.get(tracking.application_name, 0)
if tracking.notification_id <= last:
raise IntegrityError()
def update_table(self, stored_events: List[StoredEvent], **kwargs: Any) -> None:
super().update_table(stored_events, **kwargs)
tracking: Optional[Tracking] = kwargs.get("tracking", None)
if tracking:
self.tracking_table[tracking.application_name] = tracking.notification_id
def max_tracking_id(self, application_name: str) -> int:
with self.database_lock:
try:
return self.tracking_table[application_name]
except KeyError:
return 0
class Factory(InfrastructureFactory):
def aggregate_recorder(self, purpose: str = "events") -> AggregateRecorder:
return POPOAggregateRecorder()
def application_recorder(self) -> ApplicationRecorder:
return POPOApplicationRecorder()
def process_recorder(self) -> ProcessRecorder:
return POPOProcessRecorder()
|
[
"john.bywater@appropriatesoftware.net"
] |
john.bywater@appropriatesoftware.net
|
456af233a7576621e75971e4b2de66322b1689c9
|
5a914243183e26f26e445c6f9d0bdf38eacde83a
|
/em/here_em1.py
|
b2054ec7f7c21d3da446dab1657a78cc4e948c56
|
[] |
no_license
|
linafeng/KDD-demo
|
b95834a0c9ae3e0e08d1d2fb710bf421b9eda8d5
|
8648a69f49dd8b27060e8349d84d6cde8b070716
|
refs/heads/master
| 2022-06-16T02:08:10.140190
| 2020-05-07T10:04:23
| 2020-05-07T10:04:23
| 255,523,915
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,922
|
py
|
# -*- coding: utf-8 -*-
"""
用全部的特征值矩阵进行聚类训练
"""
import pandas as pd
import csv
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.mixture import GaussianMixture
from sklearn.preprocessing import StandardScaler
# 数据加载,避免中文乱码问题
data_ori = pd.read_csv('./heros.csv', encoding='gb18030')
features = [u'最大生命', u'生命成长', u'初始生命', u'最大法力', u'法力成长', u'初始法力', u'最高物攻', u'物攻成长', u'初始物攻', u'最大物防', u'物防成长', u'初始物防',
u'最大每5秒回血', u'每5秒回血成长', u'初始每5秒回血', u'最大每5秒回蓝', u'每5秒回蓝成长', u'初始每5秒回蓝', u'最大攻速', u'攻击范围']
data = data_ori[features]
data.loc[:, u'最大攻速'] = data.loc[:, (u'最大攻速')].apply(lambda x: float(x.strip('%')) / 100)
# data.loc[:,(u'最大攻速')].apply(lambda x: float(x.strip('%')) / 100)
data[u'攻击范围'] = data[u'攻击范围'].map({'远程': 1, '近战': 0})
print(data[u'攻击范围'])
# 采用 Z-Score 规范化数据,保证每个特征维度的数据均值为 0,方差为 1
ss = StandardScaler()
data = ss.fit_transform(data)
# 构造 GMM 聚类
# n_components为分组数
gmm = GaussianMixture(n_components=3, covariance_type='full')
gmm.fit(data)
# 训练数据
prediction = gmm.predict(data)
print(prediction)
from sklearn.metrics import calinski_harabaz_score
print('3组的分数')
print(calinski_harabaz_score(data, prediction))
gmm = GaussianMixture(n_components=30, covariance_type='full')
gmm.fit(data)
# 训练数据
prediction = gmm.predict(data)
print(prediction)
#指标分数越高,代表聚类效果越好,也就是相同类中的差异性小,不同类之间的差异性大
from sklearn.metrics import calinski_harabaz_score
print('30组的分数')
print(calinski_harabaz_score(data, prediction))
|
[
"lina.feng@gentinghk.com"
] |
lina.feng@gentinghk.com
|
b488e8f76122fb33075b71ea5447d66f8dab36ea
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2986/60705/264139.py
|
b726ef653c77a48cfa8e0baed697e3d4e6069ce1
|
[] |
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
| 485
|
py
|
word1 = input()
word2 = input()
m = len(word1)
n = len(word2)
line = [0 for i in range(0, n+1)]
matrix = [line.copy() for i in range(0, m+1)]
for i in range(0, m+1):
matrix[i][0] = i
for i in range(0, n+1):
matrix[0][i] = i
for i in range(1, m+1):
for j in range(1, n+1):
if word1[i-1] == word2[j-1]:
matrix[i][j] = matrix[i-1][j-1]
else:
matrix[i][j] = 1 + min(matrix[i-1][j-1], matrix[i][j-1], matrix[i-1][j])
print(matrix[m][n])
|
[
"1069583789@qq.com"
] |
1069583789@qq.com
|
03d890f8f2dfbdcee709b7d5c2e90d16d30b8606
|
277f976227c7590f6de5e7991d8fbed23b6646fe
|
/euler/solution/p7.py
|
24b6e6d889b48270005e27956ac6af780eaa9deb
|
[] |
no_license
|
domspad/euler
|
ca19aae72165eb4d08104ef7a2757115cfdb9a18
|
a4901403e442b376c2edd987a1571ab962dadab2
|
refs/heads/master
| 2021-01-17T14:04:39.198658
| 2016-07-25T23:40:10
| 2016-07-25T23:40:10
| 54,561,463
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 959
|
py
|
# BRUTE Force - alg from p3... 10 mins
# In [35]: %time p7()
# 10 0
# 20 8
# 40 12
# 80 22
# 160 37
# 320 66
# 640 115
# 1280 207
# 2560 375
# 5120 685
# 10240 1254
# 20480 2312
# 40960 4288
# 81920 8009
# CPU times: user 1.05 s, sys: 24.2 ms, total: 1.07 s
# Wall time: 1.1 s
# Out[35]: 104743
from math import sqrt
def extend_primes(N, primes=None):
"""
Return all primes less than N > 0 int
"""
if primes is None or len(primes) == 0:
# test every number less than N/2
primes = [ i for i in xrange(2,N)
if not any( ( i % p == 0 for p in xrange(2,int(sqrt(i))+1) ) )]
return primes
else:
start = primes[-1] + 1
more_primes = [ i for i in xrange(start,N)
if not any( ( i % p == 0 for p in xrange(2,int(sqrt(i))+1) ) )]
primes.extend(more_primes)
return primes
def p7():
primes = []
N = 10
while len(primes) < 10001:
print N, len(primes)
N *= 2
primes = extend_primes(N, primes=primes)
return primes[10000]
|
[
"domspad@umich.edu"
] |
domspad@umich.edu
|
abb757860c83b8d6040106470b0abcc1405c33f1
|
f3b233e5053e28fa95c549017bd75a30456eb50c
|
/bace_input/L4N/4N-4M_MD_NVT_rerun/set_3.py
|
e43d9b8429c088bc81e4ec4d4db05a1ba78a0721
|
[] |
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
| 740
|
py
|
import os
dir = '/mnt/scratch/songlin3/run/bace/L4N/MD_NVT_rerun/ti_one-step/4N_4M/'
filesdir = dir + 'files/'
temp_prodin = filesdir + 'temp_prod_3.in'
temp_pbs = filesdir + 'temp_3.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_3.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_3.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
|
b132f75964416e8fb6db865f13619d5a5d4feebc
|
ca41bc15576624f4be22c777833b6dbf80a3d5f9
|
/dolly/tarjetas/views.py
|
6f751f0cebaf9d47fe33c218daa4b79650d76b56
|
[] |
no_license
|
aris-osorio/dolly
|
74840477e01a020dfaaaf3a4e94c4f95f48f690e
|
256042bae4d4253fbc93f50aa125047e5090b68c
|
refs/heads/main
| 2023-02-01T14:48:19.840785
| 2020-12-17T07:30:34
| 2020-12-17T07:30:34
| 321,873,299
| 0
| 0
| null | 2020-12-17T06:51:59
| 2020-12-16T04:58:55
|
Python
|
UTF-8
|
Python
| false
| false
| 309
|
py
|
from rest_framework import viewsets
from django.shortcuts import render
from tarjetas.models import Tarjeta
from tarjetas.serializers import TarjetaSerializer
# Create your views here.
class TarjetasViewSet(viewsets.ModelViewSet):
serializer_class = TarjetaSerializer
queryset = Tarjeta.objects.all()
|
[
"aris.osorio@alumnos.udg.mx"
] |
aris.osorio@alumnos.udg.mx
|
1783bd109902241c813c9e0a689496e14d5cedcc
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_089/ch48_2020_04_10_20_07_55_415960.py
|
44a694247dd0499ee9a39cc77edfd3fd0ea899fd
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 295
|
py
|
def eh_crescente(x):
numero = True
i = 0
while numero:
while (i + 1) < len(x):
if x[i] < x[i+1]:
i = i + 1
else:
numero = False
return(False)
return(True)
|
[
"you@example.com"
] |
you@example.com
|
a48aae75de72aac5915ef51f45e6d1a46a853b69
|
82b946da326148a3c1c1f687f96c0da165bb2c15
|
/sdk/python/pulumi_azure_native/recoveryservices/v20201201/get_protection_container.py
|
f52c0b9299418c861bc4540e9f8abd775c160bd0
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
morrell/pulumi-azure-native
|
3916e978382366607f3df0a669f24cb16293ff5e
|
cd3ba4b9cb08c5e1df7674c1c71695b80e443f08
|
refs/heads/master
| 2023-06-20T19:37:05.414924
| 2021-07-19T20:57:53
| 2021-07-19T20:57:53
| 387,815,163
| 0
| 0
|
Apache-2.0
| 2021-07-20T14:18:29
| 2021-07-20T14:18:28
| null |
UTF-8
|
Python
| false
| false
| 5,276
|
py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetProtectionContainerResult',
'AwaitableGetProtectionContainerResult',
'get_protection_container',
]
@pulumi.output_type
class GetProtectionContainerResult:
"""
Base class for container with backup items. Containers with specific workloads are derived from this class.
"""
def __init__(__self__, e_tag=None, id=None, location=None, name=None, properties=None, tags=None, type=None):
if e_tag and not isinstance(e_tag, str):
raise TypeError("Expected argument 'e_tag' to be a str")
pulumi.set(__self__, "e_tag", e_tag)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if properties and not isinstance(properties, dict):
raise TypeError("Expected argument 'properties' to be a dict")
pulumi.set(__self__, "properties", properties)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter(name="eTag")
def e_tag(self) -> Optional[str]:
"""
Optional ETag.
"""
return pulumi.get(self, "e_tag")
@property
@pulumi.getter
def id(self) -> str:
"""
Resource Id represents the complete path to the resource.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def location(self) -> Optional[str]:
"""
Resource location.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> str:
"""
Resource name associated with the resource.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def properties(self) -> Any:
"""
ProtectionContainerResource properties
"""
return pulumi.get(self, "properties")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
"""
Resource tags.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type represents the complete path of the form Namespace/ResourceType/ResourceType/...
"""
return pulumi.get(self, "type")
class AwaitableGetProtectionContainerResult(GetProtectionContainerResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetProtectionContainerResult(
e_tag=self.e_tag,
id=self.id,
location=self.location,
name=self.name,
properties=self.properties,
tags=self.tags,
type=self.type)
def get_protection_container(container_name: Optional[str] = None,
fabric_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
vault_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetProtectionContainerResult:
"""
Base class for container with backup items. Containers with specific workloads are derived from this class.
:param str container_name: Name of the container whose details need to be fetched.
:param str fabric_name: Name of the fabric where the container belongs.
:param str resource_group_name: The name of the resource group where the recovery services vault is present.
:param str vault_name: The name of the recovery services vault.
"""
__args__ = dict()
__args__['containerName'] = container_name
__args__['fabricName'] = fabric_name
__args__['resourceGroupName'] = resource_group_name
__args__['vaultName'] = vault_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-native:recoveryservices/v20201201:getProtectionContainer', __args__, opts=opts, typ=GetProtectionContainerResult).value
return AwaitableGetProtectionContainerResult(
e_tag=__ret__.e_tag,
id=__ret__.id,
location=__ret__.location,
name=__ret__.name,
properties=__ret__.properties,
tags=__ret__.tags,
type=__ret__.type)
|
[
"noreply@github.com"
] |
morrell.noreply@github.com
|
dc8f58995b56a74a71ab55bfcf0f407a1856b1e8
|
e21f7d14e564d7fb921277a329ff078e86ad86a2
|
/2020/day-02/day_02.py
|
77772c41380808b0f53d3cf39eedf829893ccbe2
|
[] |
no_license
|
MrGallo/advent-of-code-solutions
|
31456a0718303cca6790cf1227831bcb14649e27
|
28e0331e663443ffa2638188437cc7e46d09f465
|
refs/heads/master
| 2022-07-07T08:49:30.460166
| 2020-12-17T17:22:24
| 2020-12-17T17:22:24
| 160,988,019
| 0
| 1
| null | 2022-06-21T22:26:19
| 2018-12-08T23:34:51
|
Python
|
UTF-8
|
Python
| false
| false
| 1,269
|
py
|
from typing import List, Tuple, Callable
Password = Tuple[str, str, int, int]
def main():
with open('input.txt', 'r') as f:
lines = f.read().split("\n")
passwords = []
for line in lines:
password = line.split()[-1] # last 'word'
colon_pos = line.index(':')
minmax, letter = line[:colon_pos].split()
a, b = map(int, minmax.split("-"))
passwords.append((password, letter, a, b))
print(len(valid_passwords(passwords, is_valid_sled_rental_password))) # Part 1: 628
print(len(valid_passwords(passwords, is_valid_toboggan_rental_password))) # Part 2: 705
def valid_passwords(passwords: List[Password], validation_func: Callable) -> List[Password]:
return [password for password in passwords if validation_func(password)]
def is_valid_sled_rental_password(password: Password) -> bool:
text, letter, low, high = password
count = text.count(letter)
return count >= low and count <= high
def is_valid_toboggan_rental_password(password: Password) -> bool:
text, letter, a, b = password
in_pos_one = text[a-1] == letter
in_pos_two = text[b-1] == letter
return in_pos_one and not in_pos_two or in_pos_two and not in_pos_one
if __name__ == "__main__":
main()
|
[
"daniel.gallo@ycdsbk12.ca"
] |
daniel.gallo@ycdsbk12.ca
|
76a65c84f9cf87f1a638d3ca4ab887975e058090
|
9bd1c702f6a764f1227bb92b3c25045e1270e6d7
|
/utility/queueUtility/queueFactory.py
|
2111478742d447159b4ed8236151ef2c58c2ba4a
|
[] |
no_license
|
sdz7121211/Crawler
|
94b429d343165c959713ff1fffa40c54e41bcb57
|
6b3f1d0f78fed3027f2f075963e433d2c1c13bb8
|
refs/heads/master
| 2021-01-22T11:46:20.299124
| 2014-01-21T07:04:59
| 2014-01-21T07:04:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,512
|
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import Queue
instanceList = {}
def GetInstance(queue_id):
return instanceList[queue_id]
def CreatInstance(queue_id, maxNum = 0):
obj = Queue.Queue(maxsize = maxNum)
instanceList[queue_id] = obj
##!/usr/bin/python
## -*- coding: utf-8 -*-
##from queuesControler import queuesControler
#import dataQueue
#
#
##QueuesControlerInstance = None
#QueuesInstance = []
##
##
##def getQueuesControler():
## global QueuesControlerInstance
## if not QueuesControlerInstance:
## QueuesControlerInstance = queuesControler()
## print "鏂板缓 getQueuesControler"
## return QueuesControlerInstance
## else:
## print "杩斿洖宸插瓨鍦ㄧ殑 getQueuesControler"
## return QueuesControlerInstance
#
#def getDataQueueInstance(maxNum = 0,description = None):
# dataQueueInstance = dataQueue.dataQueue(maxNum,description)
# return dataQueueInstance
#
#
#if QueuesInstance == []:
# print '鍒濆鍖�涓槦鍒�
# QueuesInstance.append(getDataQueueInstance(1000,"鑾峰彇 '缃戠珯鍚� '鍒嗙被URL' '鍒嗙被鍚�"))
# QueuesInstance.append(getDataQueueInstance(1000,"锛�缃戠珯鍚� '鍒嗙被URL' '鍒嗙被鍚�锛夎幏鍙� '鍒嗙被URL'鎵�寚鍚戠殑婧愪唬鐮�))
# QueuesInstance.append(getDataQueueInstance(20000,"锛�缃戠珯鍚� '鍒嗙被URL' '鍒嗙被鍚�锛�'鍒嗙被URL'鎵�寚鍚戠殑婧愪唬鐮� 鑾峰彇鍏朵粬鐨�))
|
[
"sudazhuang1@163.com"
] |
sudazhuang1@163.com
|
4e7a333cf591059236324b62a574244c81efc0c5
|
7bdf57cdb8d7a8dd0916e9263e63ef2d20723bec
|
/src/app/config.py
|
29b15c27ea5973e7184897e54f7bfe46ab9bfd75
|
[] |
no_license
|
cyr1z/api-generate-table-image
|
085b855c6ec48f6b46f602f92cd21ec0f03391e3
|
d06e13eb6538ac4d2986903fba086140b11c3832
|
refs/heads/main
| 2023-07-13T20:50:01.146353
| 2021-08-30T06:03:10
| 2021-08-30T06:03:10
| 401,231,871
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 293
|
py
|
from os import getenv
from dotenv import load_dotenv
load_dotenv()
class Config:
port = getenv('PORT')
production = getenv('PROD')
project = getenv('PROJECT_NAME', 'default')
base_url = getenv('BASE_URL')
storage_dir = getenv('STORAGE_DIR')
token = getenv('TOKEN')
|
[
"cyr@zolotarev.pp.ua"
] |
cyr@zolotarev.pp.ua
|
47debde28beda902a0c661b99da718fe0df26f64
|
e2f7350e08784a793044e911670f50fdc560bcbc
|
/examples/population-annealing-qpu.py
|
5229bee006233aecdf36ffa1c65d186d6815a2fa
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
hsadeghidw/dwave-hybrid
|
7a5dc4dd9ce7d8544f9276309eb1a4e8b450a5f8
|
e667035b5623f122813795d433a40db6e520ff66
|
refs/heads/master
| 2020-08-21T21:31:19.708429
| 2019-09-19T16:59:50
| 2019-09-19T16:59:50
| 216,250,242
| 0
| 0
|
Apache-2.0
| 2019-10-19T18:12:07
| 2019-10-19T18:12:07
| null |
UTF-8
|
Python
| false
| false
| 2,194
|
py
|
#!/usr/bin/env python
# Copyright 2019 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
import sys
import neal
import dimod
import hybrid
from hybrid.reference.pt import FixedTemperatureSampler
from hybrid.reference.pa import (
CalculateAnnealingBetaSchedule, ProgressBetaAlongSchedule, EnergyWeightedResampler)
# load a problem
problem = sys.argv[1]
with open(problem) as fp:
bqm = dimod.BinaryQuadraticModel.from_coo(fp)
print("BQM: {} nodes, {} edges, {:.2f} density".format(
len(bqm), len(bqm.quadratic), hybrid.bqm_density(bqm)))
# sweeps per fixed-temperature sampling step
num_sweeps = 1000
# number of generations, or temperatures to progress through
num_iter = 20
# population size
num_samples = 20
# QPU initial sampling: limits the PA workflow to QPU-sized problems
qpu_init = (
hybrid.IdentityDecomposer()
| hybrid.QPUSubproblemAutoEmbeddingSampler(num_reads=num_samples)
| hybrid.IdentityComposer()
) | hybrid.AggregatedSamples(False)
# PA workflow: after initial beta schedule estimation, we do `num_iter` steps
# (one per beta/temperature) of fixed-temperature sampling / weighted resampling
workflow = qpu_init | CalculateAnnealingBetaSchedule(length=num_iter) | hybrid.Loop(
ProgressBetaAlongSchedule() | FixedTemperatureSampler(num_sweeps=num_sweeps) | EnergyWeightedResampler(),
max_iter=num_iter
)
# run the workflow
state = hybrid.State.from_problem(bqm)
solution = workflow.run(state).result()
# show execution profile
hybrid.profiling.print_counters(workflow)
# show results
print("Solution: sample={0.samples.first}, energy={0.samples.first.energy}".format(solution))
|
[
"radomir@dwavesys.com"
] |
radomir@dwavesys.com
|
8dccce2cb401bc399d13979fc9d02d0db03644cd
|
cea3a0be3209626c11f3ec7c235b0a7f7fdbe256
|
/appengine_config.py
|
cad07b958597b5ca5a2a64641a75d268d1cd0720
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
snarfed/plusstreamfeed
|
56a2d1441097dd1660b9c5a46b546505ac8c2fa8
|
01362468594b820d9f57f4830a13df5f1aceaed1
|
refs/heads/master
| 2020-04-10T15:53:21.389755
| 2019-04-18T14:18:33
| 2019-04-18T23:18:43
| 41,272,334
| 3
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 209
|
py
|
# Load packages from virtualenv
# https://cloud.google.com/appengine/docs/python/tools/libraries27#vendoring
from google.appengine.ext import vendor
vendor.add('local')
from granary.appengine_config import *
|
[
"git@ryanb.org"
] |
git@ryanb.org
|
e26cbf3aa76e7ccbaad9ffdccf7b920147bf8c64
|
cd555725b300579d44c0bd3f6fc8f6a968912dfb
|
/UF1/Nieto_Alejandro_Gomez_Alejandro_PT15/Exercici2-2.py
|
847dc7532d4ef40f9f8a3a48b08218e721990879
|
[] |
no_license
|
aleexnl/aws-python
|
2da5d8a416927f381618f1d6076d98d5e35b3b5e
|
03fce7744b443b2b59a02c261067ecae46ecc3d9
|
refs/heads/master
| 2022-11-24T08:58:24.686651
| 2020-04-18T15:58:32
| 2020-04-18T15:58:32
| 221,772,677
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 833
|
py
|
# Fem una tupla amb els dias que tenen cada mes
dias_mes = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# Fem una altra on passarem una data.
avui = (2018, 4, 11)
# Guardamos los valores de la tupla en las variables a(any), m(mes) y d(dia)
a, m, d = avui
# Creem una tupla a la cual possarem el dia que es nadal (25 de desdembre)
nadal = (2018, 12, 25)
# Guardamos los valores de la tupla en las variables a1, m1 y d1 (com en la tupla de abans)
a2, m2, d2 = nadal
# Creem una variable on guardarem el dia de nadal mes la suma de las resta dels dias del mes menys la data actual
suma = d2 + (dias_mes[m-1] -d)
# Finalment farem un bucle on guardarem en una variable la quantiat de dias que queden fins nadal i els printarem .
for i in range(m, m2-1):
suma = suma + dias_mes[i]
print("El dies entre avui i nadal són:", suma)
|
[
"alex.nieto0027@gmail.com"
] |
alex.nieto0027@gmail.com
|
e1edaf60e374412bee0cbbd1ef24f83c1c72e19a
|
0bdd797b3e95429e03108152cacfbb26069f1d76
|
/stack/ternaryexpression.py
|
da9bb4cd80a9007718dd489b83661c65f5fdbb77
|
[
"MIT"
] |
permissive
|
mengyangbai/leetcode
|
3eda89470c933fdec5ffdfbf9cceb57e85c7e44d
|
e7a6906ecc5bce665dec5d0f057b302a64d50f40
|
refs/heads/master
| 2021-06-28T15:39:16.258564
| 2019-06-27T07:30:22
| 2019-06-27T07:30:22
| 142,398,571
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 533
|
py
|
class Solution(object):
def parseTernary(self, expression):
"""
:type expression: str
:rtype: str
"""
stack = []
expr = list(expression)
while len(stack) > 1 or expr:
tail = stack[-5:]
if len(tail) == 5 and tail[3] == '?' and tail[1] == ':':
tail = tail[2] if tail[4] == 'T' else tail[0]
stack = stack[:-5] + [tail]
else:
stack.append(expr.pop())
return stack[0] if stack else None
|
[
"mengyang.b@exciteholidays.com"
] |
mengyang.b@exciteholidays.com
|
2dc546f6dbc042377bebe95d64321e6f51650677
|
af57db915a3e0376a400511417c5750e180de3d5
|
/auto/forms.py
|
2a3709428dbab0f1cf9f461305895e35748bcd2a
|
[] |
no_license
|
Aitodev/ais
|
a8377e572a7cbf902c0d2229e27465af01a202f3
|
a463dac02dde4be2586e4d3e77b58b7c0cb89f7e
|
refs/heads/main
| 2023-02-25T06:55:09.594195
| 2021-02-01T16:06:45
| 2021-02-01T16:06:45
| 335,005,826
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,618
|
py
|
from django import forms
from django.contrib.auth.models import User
from .models import *
from .models import Feedback
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
class UserRegistrationForm(forms.ModelForm):
password = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Repeat password',widget=forms.PasswordInput)
class Meta:
model = User
fields = ('username', 'first_name')
def clean_password2(self):
cd = self.cleaned_data
if cd['password'] != cd['password2']:
raise forms.ValidationError('Passwords don\'t match.')
return cd['password2']
class UserEditForm(forms.ModelForm):
class Meta:
model = User
fields = ('first_name', 'last_name')
class ProfileEditForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('userClient', 'name', 'sirName', 'patronymic', 'sex', 'birthDate', 'country', 'docs',
'docNumber', 'gave', 'date', 'inn', 'postalCode', 'region', 'district', 'settlement',
'settlementName', 'street', 'buildingNumber', 'housing', 'apartment', 'phoneNumber',
'location', 'city', 'carCost', 'postalCode_f', 'region_f', 'district_f', 'settlement_f', 'settlementName_f',
'street_f', 'buildingNumber_f', 'housing_f', 'apartment_f', 'employmentType', 'income', 'familyIncome',
'password', 'passwordRepeat', 'phoneNumber2', 'phoneNumberSub', 'secretWord')
class PartnerEditForm(forms.ModelForm):
class Meta:
model = Partner
fields = ('userPartner' ,'namePartner', 'sirNamePartner', 'patronymicPartner', 'phonePartner', 'emailPartner',
'adressPartner', 'secretWordPartner', 'passwordPartner', 'passwordRepeatPartner', 'docNumberPartner',
'gavePartner', 'datePartner', 'upload')
class FeedbackForm(forms.ModelForm):
class Meta:
model = Feedback
fields = ['phoneNumber', 'name', 'text']
class VerificationOfDocumentsForm(forms.ModelForm):
class Meta:
model = VerificationOfDocuments
fields = ['applicationForMembership', 'passportSides', 'addressReference']
class MakeAPaymentForm(forms.ModelForm):
class Meta:
model = MakeAPayment
fields = ['entranceFee', 'dateOfPayment', 'paymentMethod', 'document']
class UserList(forms.ModelForm):
class Meta:
model = UserList
fields = ['first_name', 'last_name']
|
[
"guruitcompany@gmail.com"
] |
guruitcompany@gmail.com
|
6fd84c7eaaf2f3f098c6eafed22ac366f1da98cb
|
5c59dd613315aefbdc26d2494efd9184c177f8a9
|
/langevin_thermostat.py
|
b23b17896f0ae28f3e6aabaf25bd74692e63de0b
|
[] |
no_license
|
DuaneNielsen/odes
|
d7f4480e18a5044726e8faacf85eb2be67b08fb3
|
26735aad34d0658755f639464670cae0add3cd02
|
refs/heads/master
| 2022-12-28T15:34:19.014633
| 2020-10-10T17:43:05
| 2020-10-10T17:43:05
| 302,956,412
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,126
|
py
|
from vpython import *
import random
ground = box(color=color.red, size=vector(22, 1, 1), pos=vector(0, -1.5, 0))
top = box(color=color.red, size=vector(22, 1, 1), pos=vector(0, 19.5, 0))
left = box(color=color.red, size=vector(1, 22, 1), pos=vector(-11, 9, 0))
right = box(color=color.red, size=vector(1, 22, 1), pos=vector(11, 9, 0))
s = sphere()
s.pos = vector(-10, 0, 0)
s.velocity = vector(5, 19.2, 0)
s.mass = 1.0
k_boltzmann = 1.0
alpha = 0.2
def random_vector():
return vector(random.gauss(0, 1), random.gauss(0, 1), random.gauss(0, 1))
def f_langevin(alpha, m, temp, dt):
return sqrt(2 * alpha * m * temp / dt) * random_vector()
t = 0
dt = 0.001
while t < 20:
s.accel = f_langevin(alpha, s.mass, 400.0, dt) - alpha * s.velocity * s.mass
s.velocity += s.accel * dt
s.pos += s.velocity * dt
t = t + dt
rate(abs(1.0 / dt))
""" bounce off the sides of the box"""
if not -10.0 < s.pos.x < 10.0:
s.velocity.x = - s.velocity.x
if not 0.0 < s.pos.y < 19.0:
s.velocity.y = - s.velocity.y
if not 0.0 < s.pos.z < 1.0:
s.velocity.z = - s.velocity.z
|
[
"duane.nielsen.rocks@gmail.com"
] |
duane.nielsen.rocks@gmail.com
|
f983b13f56d37aa51fd6fad03f39562f4d2a7fd3
|
9e2935a5186914e44a739989c9b5c1a89fef9f65
|
/dht11_no_sucess/2.py
|
7049346ef0a6743c5245a6eb104bb2cfb894eb16
|
[] |
no_license
|
raspberrypitools/sensor
|
a36001f0eea6e423ea1659c7bb514e244a12bcf6
|
96e731416843c6cba04e3e549a59714123e665e6
|
refs/heads/master
| 2021-02-17T09:58:22.822618
| 2020-06-12T14:40:33
| 2020-06-12T14:40:33
| 245,087,406
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,769
|
py
|
#!/usr/bin/python
#-*- coding:utf-8 -*-
import RPi.GPIO as GPIO
import time
channel =7
data = []
j = 0
GPIO.setmode(GPIO.BCM)
time.sleep(1)
GPIO.setup(channel, GPIO.OUT)
GPIO.output(channel, GPIO.LOW)
time.sleep(0.02)
GPIO.output(channel, GPIO.HIGH)
GPIO.setup(channel, GPIO.IN)
print GPIO.input(channel),GPIO.LOW,GPIO.HIGH
#while GPIO.input(channel) == GPIO.LOW:
# continue
#while GPIO.input(channel) == GPIO.HIGH:
# continue
while j < 40:
k = 0
while GPIO.input(channel) == GPIO.LOW:
continue
while GPIO.input(channel) == GPIO.HIGH:
k += 1
if k > 100:
break
if k < 8:
data.append(0)
else:
data.append(1)
j += 1
print "sensor is working."
print data
humidity_bit = data[0:8]
humidity_point_bit = data[8:16]
temperature_bit = data[16:24]
temperature_point_bit = data[24:32]
check_bit = data[32:40]
humidity = 0
humidity_point = 0
temperature = 0
temperature_point = 0
check = 0
for i in range(8):
humidity += humidity_bit[i] * 2 ** (7-i)
humidity_point += humidity_point_bit[i] * 2 ** (7-i)
temperature += temperature_bit[i] * 2 ** (7-i)
temperature_point += temperature_point_bit[i] * 2 ** (7-i)
check += check_bit[i] * 2 ** (7-i)
tmp = humidity + humidity_point + temperature + temperature_point
print 'tmp:',tmp
print 'check:',check
if check == tmp:
print "temperature :", temperature, "*C, humidity :", humidity, "%"
else:
print "wrong"
print "temperature :", temperature, "*C, humidity :", humidity, "% check :", check, ", tmp :", tmp
mytemp = '%f' %temperature
myhumi = '%f' %humidity
tmp_output = open('./tmp_data.txt', 'w')
hud_output = open('./hum_data.txt', 'w')
tmp_output.write(mytemp)
hud_output.write(myhumi)
tmp_output.close
hud_output.close
GPIO.cleanup()
|
[
"you@example.com"
] |
you@example.com
|
a891d1335f0277aed08bff930a81a3111785cbcd
|
5dd5d4f80a883459ece27066bb88a8a951b1f88a
|
/examples/volumetric/read_vti.py
|
bc37309bb1de11d7eca624cf3460946772df96b7
|
[
"MIT"
] |
permissive
|
Gjacquenot/vtkplotter
|
428cd7c302ca50980a829aa274cf0c4165990267
|
dc865f28dec0c6f10de159dc1f8f20dd69ee74cf
|
refs/heads/master
| 2020-05-25T17:19:55.569739
| 2019-05-22T14:56:50
| 2019-05-22T14:56:50
| 170,382,207
| 0
| 0
|
MIT
| 2019-02-12T19:58:25
| 2019-02-12T19:58:24
| null |
UTF-8
|
Python
| false
| false
| 873
|
py
|
"""
Using normal vtk commands to load a xml vti file
then use vtkplotter to show the resulting 3d image.
"""
import vtk
from vtkplotter import datadir
# Create the reader for the data.
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName(datadir+"vase.vti")
reader.Update()
img = reader.GetOutput()
# specify the data array in the file to process
# img.GetPointData().SetActiveAttribute('SLCImage', 0)
#################################
from vtkplotter import Volume, load, show, Text
# can set colors and transparencies along the scalar range
vol = Volume(img, c=["gray", "fuchsia", "dg", (0, 0, 1)], alpha=[0.1, 0.2, 0.3, 0.8])
# load command returns an isosurface (vtkActor) of the 3d image
iso = load(datadir+"vase.vti", threshold=140).wire(True).alpha(0.1)
# show command creates and returns an instance of class Plotter
show(vol, iso, Text(__doc__), bg="w")
|
[
"marco.musy@gmail.com"
] |
marco.musy@gmail.com
|
7f4c31ff4d35f469ac39c66f2f9f5a3237164696
|
6929f9696a8f90b3778d449a199cee8891f3f739
|
/python_core/packages_test/package_described.py
|
9212ff4dd84afff229f7e04dd0d8c09253353576
|
[] |
no_license
|
chemplife/Python
|
881d492a4271fb2b423f2dd611eaac53a0efdc34
|
7fdfbf442a915e4f41506503baad4345a52d1e86
|
refs/heads/master
| 2022-12-31T20:00:22.475985
| 2020-10-19T20:14:43
| 2020-10-19T20:14:43
| 305,503,403
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,935
|
py
|
"""
The directory this file is in, is now a python package.
Package: It is a MODULE that has additional functionalities.
- It can have more packages inside it
- It can have module inside it.
To make any directory a package recoganisable by python compiler,
- There needs to be a __init__.py file in it.
Eg:
app/
pack1/
__init__.py
module1.py
module2.py
Now,
import pack1
-> pack1 code is in __init__.py file
-> code is loaded and execute in sys.modules['pack1']: JUST LIKE A MODULE
-> 'pack1' will be added to the global namespace of the file: JUST LIKE A MODULE
Package and Module, difference:
- __path__:
- module_name.__path__: either EMPTY or MISSING
- package_name.__path__: contains ABSOLUTE PATH to the Package.
- __file__:
- module_name.__file__: ABSOLUTE path to file that contains source_code of the Module.
- package_name.__file__: ABSOLUTE path to __init__.py file
- __package__:
- module_name.__package__: package the module_code is located in. If Module is in application root, this is empty.
- package_name.__package__: contains 'package_name' (it's own name.)
(In case of nested packaged, the inner package_name is: pack1.pack_inner)
app/
module_root.py
pack1/
__init__.py
module1.py
module2.py
pack_inner/
__init__.py
module1_inner.py
module2_inner.py
module_root.py
import pack1.pack_inner.module1_inner.py
- Sequence of loading
- Load pack1 and cache it in sys.modules['pack1']
- Load pack_inner and cache it in sys.modules['pack_inner']
- Load module1_inner.py and cache it in sys.modules['module1_inner']
- global namespace will have 'pack1' in it. -> global()['pack1'] / module_root.__dict__['pack1']
**** While loading pack1 and pack_inner, they execute __init__.py files and load any dependent modules as well.
############################################################################################################################
############################################################################################################################
So, it can be EXTREMELY USEFUL
If we do
- import pack1 or import pack1.pack_inner
(By default- The modules in these packages are NOT going to load in sys.modules[].
So, we cannot access them.)
- pack1.module1a.value -> will NOT work (Until we 'import pack1.module1a') -> or any other module in these package.
- So, to access all the modules in a package just by import package_name
- import module_name -> inside __init__.py file of the package
(Because __init__.py file gets executed when the package is imported
and it will import all the imports of __init__.py file.)
############################################################################################################################
############################################################################################################################
"""
|
[
"ratul.aggarwal@outlook.com"
] |
ratul.aggarwal@outlook.com
|
03a69a90e7668a902e87e4659702760b40bab9f8
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_200/2553.py
|
33b08c886bcd825a1acedf643a39ec999814fd9f
|
[] |
no_license
|
dr-dos-ok/Code_Jam_Webscraper
|
c06fd59870842664cd79c41eb460a09553e1c80a
|
26a35bf114a3aa30fc4c677ef069d95f41665cc0
|
refs/heads/master
| 2020-04-06T08:17:40.938460
| 2018-10-14T10:12:47
| 2018-10-14T10:12:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,332
|
py
|
# function to flip
def flip(s):
if s == '+' :
return '-'
else:
return '+'
# function takes N as input and prints output
def compare(f, s):
return int(f) < int(s)
def solution(N):
result = None
n = list(str(N))
i = len(n) - 1
while i > 0 :
# print(i, len(n))
if compare(n[i], n[i-1]):
# do something
# change i, i -1
f = int(n[i -1])
# s = int(n[i])
# change i+1 till end with 999
n[i-1] = str(f - 1)
n[i] = "9"
n = n[:i + 1] + list("9" * (len(n) - (i + 1)) )
else:
i-=1
k = ''.join(n)
if k[0] == '0':
result = k[1:]
else:
result = k
return result
# brute force check :P
# def check(N):
# n = list(str(N))
# result = True
# i = len(n) - 1
# while i > 0:
# if compare(n[i], n[i - 1]):
# result = False
# break
# i-=1
# return result
# def solution_b(N):
# while not check(N):
# N-=1
# return N
n = int(raw_input())
for i in range(n):
# pass
# read the inout number
N = int(raw_input())
result = solution(N)
print("Case #" + str(i + 1) + ": " + str(result))
# print Case #i: str(result)
|
[
"miliar1732@gmail.com"
] |
miliar1732@gmail.com
|
46062115961e2560753e312d28159cdebeda7ca2
|
849cd35166a93259c8bf84f001a3c40d9fe18b98
|
/bomj.py
|
3ab89c246b9b4a91d31b4921845d35dac34a030e
|
[] |
no_license
|
Larionov0/Group2-lessons
|
98c3d20d7532583ee66e766371235cfe888264c5
|
6426962e9b6766a9470ab1408b95486e63e4c2fa
|
refs/heads/master
| 2023-05-07T01:42:57.290428
| 2021-05-27T17:52:02
| 2021-05-27T17:52:02
| 334,012,422
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,404
|
py
|
import random
from time import sleep
money = 1000
satiety = max_satiety = 10
satiety = 1
things = [
['аксесуар', 'шорти', 0],
['аксесуар', "кепка", 0],
]
store = [
['аксесуар', 'тапки', 50],
['аксесуар', "телефон", 200],
['аксесуар', "спортивний костюм", 300],
['аксесуар', "смартфон", 1000],
['аксесуар', 'ноутбук', 6000],
['аксесуар', 'квартира', 100000],
['їжа', 'хліб', 10, 2],
['їжа', 'окорок', 70, 6],
['їжа', 'піца з равликами', 700, 10]
]
print("Welcome to Симулятор Бомжа")
while True:
if satiety <= 0:
print("Бомж відкинув копита :(")
break
print("\n\n\n--= Головне меню =--")
print("Гроші: ", money, 'грн')
print("Ситість: ", satiety, '/', max_satiety)
print("Речі:")
for thing in things:
print('-', thing[1])
print('----= Ваші дії:')
print("0 - вихід з гри")
print("1 - магазин")
print("2 - на заробітки")
print("3 - вуличні битви")
print("4 - поритися на звалці")
print("5 - поїсти")
choice = input("Ваш вибір: ")
if choice == '1':
while True:
print("\n\n--= Магазин =--")
print("Гроші: ", money, 'грн')
print("Ситість: ", satiety, '/', max_satiety)
print("Речі:")
for thing in things:
print('-', thing[1])
print('----= Товари:')
print("0 - назад")
# Виводимо вс товари на екран
i = 1
for thing in store:
print(i, '-', thing[1], '(', thing[2], 'грн )')
i += 1
# Користувач вибирає номер товару
choice = int(input("Ваш вибір: "))
if choice == 0:
break
# Дістаємо річ зі списку за заданим номером
thing = store[choice - 1] # наприклад thing = ["смартфон", 1000]
# Стандартна логіка зі зняттям коштів (покупка)
if money >= thing[2]:
money -= thing[2]
things.append(thing)
print("Успішна закупка: ", thing[1])
else:
print("Недостатньо грошей:(")
elif choice == '2':
while True:
print("\n\n--= Заробітки =--")
print("Гроші: ", money, 'грн')
print("Ситість: ", satiety, '/', max_satiety)
print("Речі:")
for thing in things:
print('-', thing[1])
print('----= Ваші дії:')
print("0 - назад")
print("1 - жебракувати (0 - 30 грн)")
print("2 - збирати пляшки (10 - 20 грн)")
print("3 - гружчик (потрібне взуття) (50 грн)")
print("4 - менеджер (потрібен телефон, костюм) (200 грн)")
choice = input("Ваш вибір: ")
if choice == '0':
break
elif choice == '1':
print("Бомж став на коліна і збирає данину...")
sleep(3)
zarobitok = random.randint(0, 30)
money += zarobitok
print("Бомж заробив", zarobitok, "грн. Тепер у нього", money, 'грн')
satiety -= 1
elif choice == '2':
print("Бомж збирає пляшки...")
sleep(3)
zarobitok = random.randint(10, 20)
money += zarobitok
print("Бомж заробив", zarobitok, "грн. Тепер у нього", money, 'грн')
satiety -= 1
elif choice == '3':
if ['аксесуар', 'тапки', 50] in things:
print("Бомж іде грузити товари")
print("Перетаскуємо мішки...")
input("<Enter>")
print("Тягаємо ящики...")
input("<Enter>")
print("Грузимо мішки...")
input("<Enter>")
print("Чистимо взуття начальнику...")
input("<Enter>")
zarobitok = 50
money += zarobitok
print("Бомж заробив", zarobitok, "грн. Тепер у нього", money, 'грн')
satiety -= 2
else:
print("Недостатньо речей!")
elif choice == '3':
pass
elif choice == '4':
pass
elif choice == '5':
while True:
print("--= Поїдання =--")
print("Гроші: ", money, 'грн')
print("Ситість: ", satiety, '/', max_satiety)
print("Речі:")
for thing in things:
print('-', thing[1])
food = []
for thing in things:
if thing[0] == 'їжа':
food.append(thing)
# виводимо всю їжу, яка є у гравця
print("0 - назад")
i = 1
for dish in food:
print(f"{i} - {dish[1]} (+{dish[3]} ситості)")
i += 1
choice = int(input("Ваш вибір: "))
if choice == 0:
break
dish = food[choice - 1] # dish=['їжа', 'хліб', 10, 2]
print("Бомж зїв", dish[1])
things.remove(dish)
satiety += dish[3]
if satiety > max_satiety:
satiety = max_satiety
elif choice == '0':
break
else:
pass
|
[
"larionov1001@gmail.com"
] |
larionov1001@gmail.com
|
8cafb8dc6888632bb689dd46e15eb44721ac98d4
|
210b05500599fe0fbe165c1cd3056e9a11487b0d
|
/ico/cmd/refund.py
|
06da4a97c1ca722f174293455fb0c5996989f604
|
[
"Apache-2.0"
] |
permissive
|
streamr-dev/token-launch-smart-contracts
|
b7fa04c9b33b5c2e371fc88dee1555b74334000e
|
209d574ded70b4c382894d09ea886a2704291ce0
|
refs/heads/master
| 2021-01-01T04:48:56.809663
| 2017-07-10T01:23:33
| 2017-07-10T01:23:33
| 97,254,821
| 11
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,520
|
py
|
"""Distribute ETH refunds."""
import csv
import datetime
import json
import os
import time
from decimal import Decimal
import shutil
import click
from eth_utils import from_wei
from eth_utils import is_checksum_address
from eth_utils import to_wei
from populus.utils.accounts import is_account_locked
from populus import Project
from populus.utils.cli import request_account_unlock
from ico.utils import check_succesful_tx
@click.command()
@click.option('--chain', nargs=1, default="mainnet", help='On which chain to deploy - see populus.json')
@click.option('--hot-wallet-address', nargs=1, help='The account that deploys the issuer contract, controls the contract and pays for the gas fees', required=True)
@click.option('--csv-file', nargs=1, help='CSV file containing distribution data', required=True)
@click.option('--address-column', nargs=1, help='Name of CSV column containing Ethereum addresses', default="address")
@click.option('--amount-column', nargs=1, help='Name of CSV column containing decimal token amounts', default="amount")
@click.option('--id-column', nargs=1, help='Name of CSV column containing unique identifier for all refund participants (usually email)', default="email")
@click.option('--limit', nargs=1, help='How many items to import in this batch', required=False, default=1000)
@click.option('--start-from', nargs=1, help='First row to import (zero based)', required=False, default=0)
@click.option('--state-file', nargs=1, help='JSON file where we keep the state', required=True)
def main(chain, hot_wallet_address, csv_file, limit, start_from, address_column, amount_column, id_column, state_file):
"""Distribute ETh refunds.
Reads in funds distribution data as CSV. Then sends funds from a local address.
The refund status is stored as a JSON file.
Example:
refund --chain=kovan --hot-wallet-address=0x001fc7d7e506866aeab82c11da515e9dd6d02c25 --csv-file=refunds.csv --address-column="Refund address" --amount-column="ETH" --id-column="Email" --start-from=0 --limit=2 --state-file=refund-state.json
Example CSV data:
.. code-block:: csv
Email,ETH,Refund address
yyy@xxx.com,61.52,0x0078EF811B6564c996fD10012579633B1a518b9D
yyy@xxx.com,111.21,0xf0b91641CCe2ADB4c0D7B90c54E7eE96CCCBc3d1
yyy@xxx.com,61.52,0x0dAbC71Faa8982bF23eE2c4979d22536F5101065
yyy@xxx.com,61.52,0x0B8EceBc18153166Beec1b568D510B55B560789D
"""
# Make a backup of the state file
if os.path.exists(state_file):
assert state_file.endswith(".json")
backup_name = state_file.replace(".json", "." + datetime.datetime.utcnow().isoformat() + ".bak.json")
print("Backing up state file to", backup_name)
shutil.copy(state_file, backup_name)
project = Project()
with project.get_chain(chain) as c:
web3 = c.web3
print("Web3 provider is", web3.currentProvider)
print("Hot wallet address is", hot_wallet_address)
print("Hot wallet balance is", from_wei(web3.eth.getBalance(hot_wallet_address), "ether"), "ETH")
# Goes through geth account unlock process if needed
if is_account_locked(web3, hot_wallet_address):
request_account_unlock(c, hot_wallet_address, timeout=3600*6)
assert not is_account_locked(web3, hot_wallet_address)
print("Reading data", csv_file)
with open(csv_file, "rt", encoding='utf-8-sig') as inp:
reader = csv.DictReader(inp)
rows = [row for row in reader]
# Check that we have unique addresses
uniq_ids = set()
for row in rows:
print(row)
id = row[id_column].strip()
if id in uniq_ids:
raise RuntimeError("Id appears twice in input data", id)
uniq_ids.add(id)
addr = row[address_column]
if not is_checksum_address(addr):
print("Not a checksummed address", addr)
# Start distribution
start_time = time.time()
start_balance = from_wei(web3.eth.getBalance(hot_wallet_address), "ether")
print("Total rows", len(rows))
if os.path.exists(state_file):
with open(state_file, "rt") as inp:
state = json.load(inp)
else:
state = {}
for i in range(start_from, min(start_from+limit, len(rows))):
data = rows[i]
addr = data[address_column].strip()
id = data[id_column].strip()
amount = Decimal(data[amount_column].strip())
amount_wei = to_wei(amount, "ether")
if id in state:
print("Already refunded", id, addr, amount)
continue
# Use non-default gas price for speedier processing
gas_price = int(web3.eth.gasPrice * 10)
txid = web3.eth.sendTransaction({"from": hot_wallet_address, "to": addr, "value": amount_wei, "gasPrice": gas_price})
duration = time.time() - start_time
print("Transferring", id, amount_wei, "to", addr, "txid", txid, "duration", duration)
state[id] = txid
with open(state_file, "wt") as out:
json.dump(state, out)
check_succesful_tx(web3, txid)
end_balance = from_wei(web3.eth.getBalance(hot_wallet_address), "ether")
print("Refund cost is", start_balance - end_balance, "ETH")
print("All done! Enjoy your decentralized future.")
if __name__ == "__main__":
main()
|
[
"mikko@opensourcehacker.com"
] |
mikko@opensourcehacker.com
|
32b5aa500d83bd14aee751d92265569351a866f2
|
e4066b34668bbf7fccd2ff20deb0d53392350982
|
/project_scrapy/spiders/fishpond.py
|
a505966943e5272cc2c64493bb9cf1f8f5c9e360
|
[] |
no_license
|
sushma535/WebSites
|
24a688b86e1c6571110f20421533f0e7fdf6e1a8
|
16a3bfa44e6c7e22ae230f5b336a059817871a97
|
refs/heads/master
| 2023-08-18T09:09:16.052555
| 2021-10-11T00:41:50
| 2021-10-11T00:41:50
| 415,621,279
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,545
|
py
|
import scrapy
from scrapy.crawler import CrawlerProcess
import os
import csv
from csv import reader
import re
total_data = {}
class SimilarWeb(scrapy.Spider):
name = 'SW'
user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
start_urls = ['https://www.fishpond.com.au/', 'https://www.similarsites.com/site/fishpond.com.au/']
csv_columns = ['Category', 'Description', 'Name', 'Url']
csv_file = 'websites1_data.csv'
count = 0
def parse(self, response):
data, desc, cat = '', '', ''
print('response url:', response.url)
if response.url == self.start_urls[0]:
data = response.css('title::text').get()
if data:
data = re.sub("\n\t\t", '', data)
total_data['Name'] = data
self.count += 1
elif response.url == self.start_urls[1]:
cat = response.css(
'div[class="StatisticsCategoriesDistribution__CategoryTitle-fnuckk-6 jsMDeK"]::text').getall()
desc = response.css('div[class="SiteHeader__Description-sc-1ybnx66-8 hhZNQm"]::text').get()
if cat:
cat = ": ".join(cat[:])
total_data['Category'] = cat
total_data['Description'] = desc
total_data['Url'] = self.start_urls[0]
self.count += 1
if self.count == 2:
print("total data", total_data)
new_data = [total_data['Category'], total_data['Description'], total_data['Name'],
total_data['Url']]
print("new data", new_data)
self.row_appending_to_csv_file(new_data)
def row_appending_to_csv_file(self, data):
if os.path.exists(self.csv_file):
need_to_add_headers = False
with open(self.csv_file, 'a+', newline='') as file:
file.seek(0)
csv_reader = reader(file)
if len(list(csv_reader)) == 0:
need_to_add_headers = True
csv_writer = csv.writer(file)
if need_to_add_headers:
csv_writer.writerow(self.csv_columns)
csv_writer.writerow(data)
else:
with open(self.csv_file, 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerow(self.csv_columns) # header
csv_writer.writerow(data)
process = CrawlerProcess()
process.crawl(SimilarWeb)
process.start()
|
[
"sushmakusumareddy@gmail.com"
] |
sushmakusumareddy@gmail.com
|
96c83faea4fa8fcd498552cfd69510ae95d4500b
|
368c66467b78adf62da04cb0b8cedd2ef37bb127
|
/BOJ/Python/15684_사다리조작.py
|
ad8c21b700f5ed8bafd0f746b37d65e039941596
|
[] |
no_license
|
DJHyun/Algorithm
|
c8786ddcd8b5693fc9b3b4721fdf1eeda21611c5
|
fd6ae800886dac4ec5ff6cf2618bc2c839a76e7a
|
refs/heads/master
| 2020-07-30T16:32:49.344329
| 2020-02-25T07:59:34
| 2020-02-25T07:59:34
| 210,289,983
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,413
|
py
|
# baekjoon source = "https://www.acmicpc.net/problem/15684"
def check(x, y):
if x < 0 or x > h : return False
if y < 0 or y > n - 1: return False
return True
def make_ladder(a,b):
pass
def ladder(a, b):
q = [[a, b]]
visited = [[0] * n for _ in range(h +1)]
while q:
t = q.pop(0)
# visited[t[0]+1][t[1]] = 1
tx = t[0] + 1
ty = t[1]
if check(tx,ty):
visited[tx][ty] = 1
if arr[tx][ty] == 1:
for i in range(2):
x = tx + dx[i]
y = ty + dy[i]
if check(x, y) and arr[x][y] == 1:
q.append([x, y])
visited[x][y]= 1
break
else:
q.append([tx, ty])
visited[tx][ty] = 1
for i in visited:
print(i)
print()
if b == t[1]:
return False
else:
return True
n, m, h = map(int, input().split())
arr = [[0] * n for _ in range(h + 1)]
dx, dy = [0, 0], [1, -1]
print(n, m, h)
for i in arr:
print(i)
print()
for i in range(m):
a, b = map(int, input().split())
# if b%2:
# arr[a-1][b] = 1
# else:
arr[a][b - 1] = 1
arr[a][b] = 1
for i in arr:
print(i)
print()
idx = 0
while True:
if ladder(0,idx):
make_ladder(0,idx)
else:
idx += 1
|
[
"djestiny4444@naver.com"
] |
djestiny4444@naver.com
|
a179f9c4dfc6c25e8e7b9b0ebef9df266971e387
|
4911cc3eaadd536a234dc9e7e563ad0df8e7ba3c
|
/src/bd2k/util/test/test_d32.py
|
aaf9711801ab83db106c1de7ff75ea68a9b4ab52
|
[] |
no_license
|
hschmidt/bd2k-python-lib
|
56ca4747e2b2cc3baf98c5f0efa343229018ea77
|
a662f3c5564299a6c2d86233e6bee741e9e44c3d
|
refs/heads/master
| 2020-06-28T06:04:27.265541
| 2016-11-18T07:22:44
| 2016-11-18T07:22:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,516
|
py
|
# Copyright (c) 2014 Dominic Tarr
# Copyright (c) 2015 Hannes Schmidt
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
# BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Inspired by JavaScript code found at https://github.com/dominictarr/d64
from __future__ import absolute_import
from unittest import TestCase
from bd2k.util.d32 import standard as d32
import os
class TestD32( TestCase ):
def test( self ):
l = [ os.urandom( i ) for i in xrange( 1000 ) ]
self.assertEqual( map( d32.decode, sorted( map( d32.encode, l ) ) ), sorted( l ) )
|
[
"hannes@ucsc.edu"
] |
hannes@ucsc.edu
|
c0f861945d032cb15056a8e6d63ad54fa9f7c2b0
|
c10f20abec372f81dbd6468ead208543f60940f1
|
/learning/5.Package/5.2.stat.py
|
de809c5d862f6396d89748097203c556a8f6ae77
|
[] |
no_license
|
alenzhd/meachineLearning
|
64876e7a6c0b8b39a63a9eb586d306a3489b4447
|
1b66ce2f73b226548f07e45c8537b8286635a048
|
refs/heads/master
| 2021-08-24T10:55:52.056439
| 2017-12-09T10:26:37
| 2017-12-09T10:26:37
| 112,688,163
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,425
|
py
|
#!/usr/bin/python
# -*- coding:utf-8 -*-
import numpy as np
from scipy import stats
import math
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
def calc_statistics(x):
n = x.shape[0] # 样本个数
# 手动计算
m = 0
m2 = 0
m3 = 0
m4 = 0
for t in x:
m += t
m2 += t*t
m3 += t**3
m4 += t**4
m /= n
m2 /= n
m3 /= n
m4 /= n
mu = m
sigma = np.sqrt(m2 - mu*mu)
skew = (m3 - 3*mu*m2 + 2*mu**3) / sigma**3
kurtosis = (m4 - 4*mu*m3 + 6*mu*mu*m2 - 4*mu**3*mu + mu**4) / sigma**4 - 3
print ('手动计算均值、标准差、偏度、峰度:', mu, sigma, skew, kurtosis)
# 使用系统函数验证
mu = np.mean(x, axis=0)
sigma = np.std(x, axis=0)
skew = stats.skew(x)
kurtosis = stats.kurtosis(x)
return mu, sigma, skew, kurtosis
if __name__ == '__main__':
d = np.random.randn(100000)
print (d)
mu, sigma, skew, kurtosis = calc_statistics(d)
print ('函数库计算均值、标准差、偏度、峰度:', mu, sigma, skew, kurtosis)
# 一维直方图
mpl.rcParams[u'font.sans-serif'] = 'SimHei'
mpl.rcParams[u'axes.unicode_minus'] = False
y1, x1, dummy = plt.hist(d, bins=50, normed=True, color='g', alpha=0.75)
t = np.arange(x1.min(), x1.max(), 0.05)
y = np.exp(-t**2 / 2) / math.sqrt(2*math.pi)
plt.plot(t, y, 'r-', lw=2)
plt.title(u'高斯分布,样本个数:%d' % d.shape[0])
plt.grid(True)
# plt.show()
d = np.random.randn(100000, 2)
mu, sigma, skew, kurtosis = calc_statistics(d)
print ('函数库计算均值、标准差、偏度、峰度:', mu, sigma, skew, kurtosis)
# 二维图像
N = 30
density, edges = np.histogramdd(d, bins=[N, N])
print ('样本总数:', np.sum(density))
density /= density.max()
x = y = np.arange(N)
t = np.meshgrid(x, y)
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, projection='3d')
ax.scatter(t[0], t[1], density, c='r', s=15*density, marker='o', depthshade=True)
ax.plot_surface(t[0], t[1], density, cmap=cm.Accent, rstride=2, cstride=2, alpha=0.9, lw=0.75)
ax.set_xlabel(u'X')
ax.set_ylabel(u'Y')
ax.set_zlabel(u'Z')
plt.title(u'二元高斯分布,样本个数:%d' % d.shape[0], fontsize=20)
plt.tight_layout(0.1)
plt.show()
|
[
"zhanghd@asiainfo-mixdata.com"
] |
zhanghd@asiainfo-mixdata.com
|
3f7fb0c976574d21edfe92fca912a67f210f5bfa
|
9a9788a67925ba563f835fac204e76dc6cabb5bd
|
/Products/CMFDefault/browser/discussion/tests/test_discussion.py
|
ca429f37cfe1f2a3600665d5f7040b2a8ec0931b
|
[
"ZPL-2.1"
] |
permissive
|
zopefoundation/Products.CMFDefault
|
d8f5fe6754d90abfaa37460ee2a3b0314167e34a
|
a176d9aac5a7e04725dbd0f7b76c6ac357062139
|
refs/heads/master
| 2023-06-21T20:54:29.719764
| 2021-02-05T17:36:40
| 2021-02-05T17:36:40
| 36,096,105
| 0
| 4
|
NOASSERTION
| 2021-02-04T15:08:40
| 2015-05-22T21:29:53
|
Python
|
UTF-8
|
Python
| false
| false
| 950
|
py
|
##############################################################################
#
# Copyright (c) 2008 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Test Products.CMFDefault.browser.rss
"""
import unittest
from Testing import ZopeTestCase
from Products.CMFDefault.testing import FunctionalLayer
ftest_suite = ZopeTestCase.FunctionalDocFileSuite('discussion.txt')
ftest_suite.layer = FunctionalLayer
def test_suite():
return unittest.TestSuite((
ftest_suite,
))
|
[
"charlie.clark@clark-consulting.eu"
] |
charlie.clark@clark-consulting.eu
|
96343d7dbf5cef604566654a976175dd9694d385
|
aaed251a860f6606fa826ccc057d5bbb13800fe1
|
/swagger_client/models/jvm_info.py
|
ca9db7012cb553c3b0715ee388d53a85989b7044
|
[] |
no_license
|
japaniel/insightvm-python
|
707f0bd16f20302e99c117f3e562cd5dbf25359e
|
9bf8ae98b6d61c1d5c4ab2d8c6c810a68e16bf3d
|
refs/heads/main
| 2023-02-02T04:01:36.204154
| 2020-12-16T01:21:20
| 2020-12-16T01:21:20
| 320,130,684
| 1
| 0
| null | 2020-12-16T01:21:21
| 2020-12-10T01:57:52
|
Python
|
UTF-8
|
Python
| false
| false
| 6,254
|
py
|
# coding: utf-8
"""
InsightVM API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 3
Contact: support@rapid7.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class JVMInfo(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'str',
'start_time': 'str',
'uptime': 'str',
'vendor': 'str',
'version': 'str'
}
attribute_map = {
'name': 'name',
'start_time': 'startTime',
'uptime': 'uptime',
'vendor': 'vendor',
'version': 'version'
}
def __init__(self, name=None, start_time=None, uptime=None, vendor=None, version=None): # noqa: E501
"""JVMInfo - a model defined in Swagger""" # noqa: E501
self._name = None
self._start_time = None
self._uptime = None
self._vendor = None
self._version = None
self.discriminator = None
if name is not None:
self.name = name
if start_time is not None:
self.start_time = start_time
if uptime is not None:
self.uptime = uptime
if vendor is not None:
self.vendor = vendor
if version is not None:
self.version = version
@property
def name(self):
"""Gets the name of this JVMInfo. # noqa: E501
The name of the Java Virtual Machine. # noqa: E501
:return: The name of this JVMInfo. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this JVMInfo.
The name of the Java Virtual Machine. # noqa: E501
:param name: The name of this JVMInfo. # noqa: E501
:type: str
"""
self._name = name
@property
def start_time(self):
"""Gets the start_time of this JVMInfo. # noqa: E501
The date and time the Java Virtual Machine last started. # noqa: E501
:return: The start_time of this JVMInfo. # noqa: E501
:rtype: str
"""
return self._start_time
@start_time.setter
def start_time(self, start_time):
"""Sets the start_time of this JVMInfo.
The date and time the Java Virtual Machine last started. # noqa: E501
:param start_time: The start_time of this JVMInfo. # noqa: E501
:type: str
"""
self._start_time = start_time
@property
def uptime(self):
"""Gets the uptime of this JVMInfo. # noqa: E501
Total up-time of the Java Virtual Machine, in ISO 8601 format. For example: `\"PT1H4M24.214S\"`. # noqa: E501
:return: The uptime of this JVMInfo. # noqa: E501
:rtype: str
"""
return self._uptime
@uptime.setter
def uptime(self, uptime):
"""Sets the uptime of this JVMInfo.
Total up-time of the Java Virtual Machine, in ISO 8601 format. For example: `\"PT1H4M24.214S\"`. # noqa: E501
:param uptime: The uptime of this JVMInfo. # noqa: E501
:type: str
"""
self._uptime = uptime
@property
def vendor(self):
"""Gets the vendor of this JVMInfo. # noqa: E501
The vendor of the Java Virtual Machine. # noqa: E501
:return: The vendor of this JVMInfo. # noqa: E501
:rtype: str
"""
return self._vendor
@vendor.setter
def vendor(self, vendor):
"""Sets the vendor of this JVMInfo.
The vendor of the Java Virtual Machine. # noqa: E501
:param vendor: The vendor of this JVMInfo. # noqa: E501
:type: str
"""
self._vendor = vendor
@property
def version(self):
"""Gets the version of this JVMInfo. # noqa: E501
The version of the Java Virtual Machine. # noqa: E501
:return: The version of this JVMInfo. # noqa: E501
:rtype: str
"""
return self._version
@version.setter
def version(self, version):
"""Sets the version of this JVMInfo.
The version of the Java Virtual Machine. # noqa: E501
:param version: The version of this JVMInfo. # noqa: E501
:type: str
"""
self._version = version
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(JVMInfo, dict):
for key, value in self.items():
result[key] = 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, JVMInfo):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"dredington@artemishealth.com"
] |
dredington@artemishealth.com
|
5e0de4bfd6bde7090acbcccc3bf5523f1cca16b6
|
75ec986d34d5391d46d6469c513626f69f5d978d
|
/Incepator/listcomprehensions/listcomprehensions1.py
|
68f786bc3bef3a729cc3f9c8b4b0748696eef5ee
|
[] |
no_license
|
CatrunaMarius/python
|
d9f8dc221458e4b65c3f801daf3b59aa2b946358
|
d063bffb4eafa56ac1e205c2d39fc893ab50e992
|
refs/heads/master
| 2020-04-24T05:23:22.756002
| 2020-01-06T11:56:12
| 2020-01-06T11:56:12
| 171,703,482
| 0
| 0
| null | 2019-02-20T16:12:39
| 2019-02-20T15:59:08
| null |
UTF-8
|
Python
| false
| false
| 181
|
py
|
#fillind with random numbers
from random import randint
low = int(input("Entre min: "))
high = int(input("Entre max: "))
a= [randint(low, high) for i in range(10)]
print(a)
|
[
"noreply@github.com"
] |
CatrunaMarius.noreply@github.com
|
f039e27d9ed5f302d3c0eadb99c82005051d3598
|
66c9ce87b3462ec49caa8cd5286ffccc0e6f26ee
|
/dag.py
|
b415d17786098c013d11d9ce2e1e0304774e8779
|
[
"MIT"
] |
permissive
|
kendricktan/dpim
|
e0b839f8ce9e65c48b020819b5cd96630ec66789
|
0b8c95f625c3b136f3b938ea7663c90bcb73c5e4
|
refs/heads/master
| 2020-03-12T03:25:16.904858
| 2018-04-21T08:43:45
| 2018-04-21T08:43:45
| 130,424,055
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,979
|
py
|
import hashlib
import crypto
from collections import namedtuple
MIN_WORK = '000'
# directed acyclic graph primitives
# OpenTx
# params:
# account => which blockchain account you trying to open
# hash => hash of the opentx
# work => work done to get the 'valid' txid (starts with X amount of zeros)
OpenTx = namedtuple("OpenTx", "account hash work")
# SendTx
# params:
# prev => previous hash
# hash => hash of the sendtx
# rpk => random pk (for stealth address)
# signature => signature to verify that the sender authorized it
# msg => msg type
# work => work done to get the 'valid' hash (starts with X amount of zeros)
SendTx = namedtuple("SendTx", "prev hash rpk destination signature msg work")
# ReceiveTx
# params:
# prev => previous hash
# hash => hash of the receive tx
# source => source of the receiveTx (hash of the sendtx)
# work => work done to get the 'valid' hash (starts with X amount of zeros)
ReceiveTx = namedtuple("ReceiveTx", "prev hash source work")
# DAG
class DAG:
def __init__(self, usedtxids={}, cachehash={}, cachedmessages={}, accounts={}):
"""
params:
usedtxids => {}
cachehash => {}
cachedmessages => {}
accounts => {}
usedtxids is a dictionary containing used send txids
cachehash is a dictionary where key: hash value: tx
cachedmessages is a dictionary where key: hash, value: message
accounts is a dictionary where each key is an address e.g.
accounts = {
'abcdefgh': {
'latest': 5,
1: tx(),
2: tx(),
3: tx()
}
}
"""
self.usedtxids = usedtxids
self.accounts = accounts
self.cachehash = cachehash
self.cachedmessages = cachedmessages
def insert_tx(self, pk, tx):
t = type(tx)
if t == OpenTx:
self._insert_open(pk, tx)
elif t == SendTx:
self._insert_send(pk, tx)
elif t == ReceiveTx:
self._insert_receive(pk, tx)
self.cachehash[tx.hash] = tx
def _insert_open(self, pk, tx):
if not valid_work(tx):
return
# Don't overwrite existing account
if self.accounts.get(pk, None) is not None:
return
self.accounts[pk] = {
'latest': 0,
0: tx
}
def _insert_send(self, pk, tx):
if not (valid_signature(pk, tx) and valid_work(tx)):
return
if not (self.get_latest(pk).hash == tx.prev):
return
new_latest = self.accounts[pk]['latest'] + 1
self.accounts[pk]['latest'] = new_latest
self.accounts[pk][new_latest] = tx
def _insert_receive(self, pk, tx):
if not valid_work(tx):
return
if not (self.get_latest(pk).hash == tx.prev):
return
new_latest = self.accounts[pk]['latest'] + 1
self.accounts[pk]['latest'] = new_latest
self.accounts[pk][new_latest] = tx
def get_message(self, h):
return self.cachedmessages.get(h, None)
def get_messages(self):
return self.cachedmessages
def add_message(self, h, decrypted_msg):
self.cachedmessages[h] = decrypted_msg
def get_latest(self, pk):
pk_dict = self.accounts.get(pk, {})
if pk_dict == {}:
return None
latest_no = pk_dict['latest']
return pk_dict[latest_no]
def get_account(self, pk):
return self.accounts.get(pk, {})
def get_hash(self, h):
if self.hash_received(h):
return self.cachehash[h]
return None
def hash_received(self, h):
return h in self.cachehash
# Hashes an opentx
def hash_opentx(opentx):
bytestr = str.encode("account:{},work:{}".format(
opentx.account, opentx.work))
h = hashlib.sha256(bytestr).hexdigest()
return h
# Hashes a send tx
def hash_sendtx(sendtx):
bytestr = str.encode(
"prev:{},destination:{},rpk:{},signature:{},msg:{},work:{}".format(
sendtx.prev, sendtx.destination, sendtx.rpk, sendtx.signature, sendtx.msg, sendtx.work
)
)
h = hashlib.sha256(bytestr).hexdigest()
return h
# Hashes a receive tx
def hash_receivetx(receivetx):
bytestr = str.encode(
"prev:{},source:{},work:{}".format(
receivetx.prev, receivetx.source, receivetx.work
)
)
h = hashlib.sha256(bytestr).hexdigest()
return h
# Hashes tx
def hash_tx(tx):
t = type(tx)
if t != OpenTx and t != SendTx and t != ReceiveTx:
return -1
if t == OpenTx:
h = hash_opentx(tx)
elif t == SendTx:
h = hash_sendtx(tx)
elif t == ReceiveTx:
h = hash_receivetx(tx)
return h
def prep_signature(sendtx):
s = "prev:{},destination:{},rpk:{},msg:{}".format(
sendtx.prev, sendtx.destination, sendtx.rpk, sendtx.msg)
return s
def sign_sendtx(sk, sendtx):
sk = crypto.decodeint(sk[:64].decode('hex'))
msg = prep_signature(sendtx)
pk = crypto.publickey(sk)
sig = crypto.signature(msg, sk, pk)
# Reconstruct named tuple
tx_dict = sendtx._asdict()
tx_dict['signature'] = sig.encode('hex')
return SendTx(**tx_dict)
def valid_work(tx):
# Tx hash
h = hash_tx(tx)
return h[:len(MIN_WORK)] == MIN_WORK
def valid_signature(pk, sendtx):
sig = sendtx.signature.decode('hex')
msg = prep_signature(sendtx)
return crypto.checkvalid(sig, msg, pk[:64].decode('hex'))
def mine_tx(tx):
# Tx hash
h = hash_tx(tx)
# Tx type
t = type(tx)
if h == -1:
return -1
# Valid work done
# Python and recursion doesn't work well
# So i'll have to use a while loop
while not valid_work(tx):
d = tx._asdict()
d['work'] = tx.work + 1
tx = t(**d)
h = hash_tx(tx)
d = tx._asdict()
d['hash'] = h
return t(**d)
|
[
"kendricktan0814@gmail.com"
] |
kendricktan0814@gmail.com
|
7d339ebc3f20cf56e6b20c247266259ba6e349f3
|
861db97defcdadae5f10263b9a6d41e7d0b85131
|
/ex111/utilidadescev/moeda/__init__.py
|
bd0def54dfeb7a94e37473fc89d39d79370bb5b3
|
[] |
no_license
|
gguilherme42/CursoEmVideo_Python
|
0483f092fe6563bc97a260ca07c2d4f1f882ac61
|
54eec56e98ae71dbb2ba02eb6904cd236a42be70
|
refs/heads/master
| 2021-01-06T15:15:25.194038
| 2020-04-27T22:19:42
| 2020-04-27T22:19:42
| 241,374,850
| 4
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,056
|
py
|
'''
Exercício 110:
Crie um pacote chamado utilidadezCeV que tenha dois
módulos internos chamados moeda e dado.
Transfira todas as funções utilizadas nos desafios 107,
108 e 109 para o primeiro pacote e mantenha tudo funcionando.
'''
def moeda(n=0, moeda='R$'):
return f'{moeda}{n:.2f}'.replace('.', ',')
def aumentar(n=0, a=0, f=True):
c = (n * a) / 100
l = c + n
return l if not f else moeda(l)
def diminuir(n=0, a=0, f=True):
c = (n * a) / 100
l = n - c
return l if not f else moeda(l)
def dobro(n=0, f=True):
d = n * 2
return d if not f else moeda(d)
def metade(n=0, f=True):
m = n / 2
return m if not f else moeda(m)
def resumo(n, a=0, b=0, f=True):
print('=' * 30)
print(f' {"RESUMO":^25} ')
print('-' * 30)
print(f'{"- Aumento: ":<5} {aumentar(n, a, f):>10}')
print(f'{"- Diminuição: ":<5} {diminuir(n, b, f):>10}')
print(f'{"- Dobro: ":<5} {dobro(n, f):>10}')
print(f'{"- Metade: ":<5} {metade(n, f):>10}')
print('=' * 30)
|
[
"anoobs@tutamail.com"
] |
anoobs@tutamail.com
|
1ab177bf9094897a7f5e1adc529942f3e0d1ed73
|
ccfe4e0bb18b46b4dd5ce4503ae54b1eaae3bba5
|
/scripts/queue_splitter.py
|
3e43004ca4b1cfebde60515da52ec0887e608299
|
[
"ISC"
] |
permissive
|
dimitri/skytools
|
5cb67f5f581ab16acd8b84d78ba5cc9e05b9cb56
|
37ec8fc09ba897b02a1ca871055eb69a00deceae
|
refs/heads/master
| 2021-01-15T18:05:21.396894
| 2011-10-17T15:06:18
| 2011-10-17T15:06:18
| 1,082,431
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,438
|
py
|
#! /usr/bin/env python
"""Puts events into queue specified by field from 'queue_field' config parameter.
Config parameters::
## Parameters for queue_splitter
# database locations
src_db = dbname=sourcedb_test
dst_db = dbname=destdb_test
# event fields from where target queue name is read
#queue_field = extra1
"""
import sys
import pkgloader
pkgloader.require('skytools', '3.0')
import pgq
class QueueSplitter(pgq.SerialConsumer):
__doc__ = __doc__
def __init__(self, args):
pgq.SerialConsumer.__init__(self, "queue_splitter", "src_db", "dst_db", args)
def process_remote_batch(self, db, batch_id, ev_list, dst_db):
cache = {}
queue_field = self.cf.get('queue_field', 'extra1')
for ev in ev_list:
row = [ev.type, ev.data, ev.extra1, ev.extra2, ev.extra3, ev.extra4, ev.time]
queue = ev.__getattr__(queue_field)
if queue not in cache:
cache[queue] = []
cache[queue].append(row)
# should match the composed row
fields = ['type', 'data', 'extra1', 'extra2', 'extra3', 'extra4', 'time']
# now send them to right queues
curs = dst_db.cursor()
for queue, rows in cache.items():
pgq.bulk_insert_events(curs, rows, fields, queue)
if __name__ == '__main__':
script = QueueSplitter(sys.argv[1:])
script.start()
|
[
"markokr@gmail.com"
] |
markokr@gmail.com
|
3d8f5d713d82e1349cb2ac1a43f58dec0dd32a96
|
786027545626c24486753351d6e19093b261cd7d
|
/ghidra9.2.1_pyi/ghidra/app/plugin/core/analysis/AnalysisTask.pyi
|
2450f5f4a1e96ac652add615aed51765563f62a3
|
[
"MIT"
] |
permissive
|
kohnakagawa/ghidra_scripts
|
51cede1874ef2b1fed901b802316449b4bf25661
|
5afed1234a7266c0624ec445133280993077c376
|
refs/heads/main
| 2023-03-25T08:25:16.842142
| 2021-03-18T13:31:40
| 2021-03-18T13:31:40
| 338,577,905
| 14
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,214
|
pyi
|
import ghidra.framework.cmd
import ghidra.framework.model
import ghidra.util.task
import java.lang
class AnalysisTask(ghidra.framework.cmd.BackgroundCommand):
def __init__(self, __a0: ghidra.app.plugin.core.analysis.AnalysisScheduler, __a1: ghidra.app.util.importer.MessageLog): ...
@overload
def applyTo(self, __a0: ghidra.framework.model.DomainObject) -> bool: ...
@overload
def applyTo(self, __a0: ghidra.framework.model.DomainObject, __a1: ghidra.util.task.TaskMonitor) -> bool: ...
def canCancel(self) -> bool: ...
def dispose(self) -> None: ...
def equals(self, __a0: object) -> bool: ...
def getClass(self) -> java.lang.Class: ...
def getName(self) -> unicode: ...
def getStatusMsg(self) -> unicode: ...
def hasProgress(self) -> bool: ...
def hashCode(self) -> int: ...
def isModal(self) -> bool: ...
def notify(self) -> None: ...
def notifyAll(self) -> None: ...
def taskCompleted(self) -> None: ...
def toString(self) -> unicode: ...
@overload
def wait(self) -> None: ...
@overload
def wait(self, __a0: long) -> None: ...
@overload
def wait(self, __a0: long, __a1: int) -> None: ...
|
[
"tsunekou1019@gmail.com"
] |
tsunekou1019@gmail.com
|
84e01bd5afe8578563e994e94102bc3484de4101
|
61f921e1ee1d2461ba420ef33b854a53f2169c6f
|
/tests/test_designer.py
|
db1e8f9269f74adb0a3615adadb84e9a73b768fe
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
jsheppard95/typhon
|
420ef80b8568dec76bb0551301354144d9bf18ea
|
072e3cd821068f7f148d9ed7bffe58abc5a4d7d4
|
refs/heads/master
| 2020-04-18T09:48:18.368334
| 2019-01-23T21:44:21
| 2019-01-23T21:44:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 128
|
py
|
from typhon.designer import TyphonSignalPanelPlugin
def test_typhon_panel_plugin_smoke():
tpp = TyphonSignalPanelPlugin()
|
[
"trendahl@slac.stanford.edu"
] |
trendahl@slac.stanford.edu
|
2327f182abd9ddab4db6d24bdc1284e162f57a56
|
8dae5a0fa4efcb3cdef596b58f0ebfcd7b73e315
|
/skidl/__init__.py
|
7ef3364ad1afd33243b357d244c0b49270544f98
|
[
"MIT"
] |
permissive
|
andrewjaykeller/skidl
|
94c790b9ffaf3c6948b38569e890d29cfff73b12
|
89cb53dc142c51c620223a14164b158407685505
|
refs/heads/master
| 2020-05-17T21:50:03.570986
| 2019-04-19T19:55:39
| 2019-04-19T19:55:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 701
|
py
|
# -*- coding: utf-8 -*-
"""SKiDL: A Python-Based Schematic Design Language
This module extends Python with the ability to design electronic
circuits. It provides classes for working with:
* Electronic parts (``Part``),
* Collections of part terminals (``Pin``) connected via wires (``Net``), and
* Groups of related nets (``Bus``).
Using these classes, you can concisely describe the interconnection of
parts using a flat or hierarchical structure.
A resulting Python script outputs a netlist that can be
imported into a PCB layout tool or Spice simulator.
The script can also
check the resulting circuitry for electrical rule violations.
"""
from .skidl import *
from .netlist_to_skidl import *
|
[
"devb@xess.com"
] |
devb@xess.com
|
cf80ca5edffa2b7ae75c87fed73d72279668bf58
|
8b926cf341d6294deac60949e19716a1bccf80e3
|
/day3/functions/10.py
|
0fd509940291d6ab4dc6bc2c350e549de0843374
|
[] |
no_license
|
shobhit-nigam/qberry
|
dc041ecb7468ef04545c761636cb605660105f8e
|
54d8988ddf9c1301174b23c9c02c3b3b9b3473c0
|
refs/heads/main
| 2023-08-07T02:39:19.426236
| 2021-10-07T12:53:00
| 2021-10-07T12:53:00
| 413,307,799
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 210
|
py
|
def funca (la=55, lb=77, lc=66):
return la+lb, la+lc, "hey", [la, lb, lc]
u, v, w, x = funca(100, 22, 10)
print("u =", u)
print("v =", v)
print("w =", w)
print("x =", x)
# error
u, v = funca(100, 22, 10)
|
[
"noreply@github.com"
] |
shobhit-nigam.noreply@github.com
|
36fd3ec3e343ef9210b2a247491bed58499851a0
|
9463d85666453fd8e57a0ce9e515e4765ae2b60a
|
/cwpoliticl/cwpoliticl/scraped_websites.py
|
1b5c36189affb30506c8ee8cbbc97f9b239d97d0
|
[
"MIT"
] |
permissive
|
trujunzhang/djzhang-targets
|
dc6c3086553a5450fb239cc1cef5330a51a02e1f
|
c2e327acde9d51f0455e7243f17d93d74b579501
|
refs/heads/master
| 2021-01-09T20:52:31.258826
| 2016-07-16T13:18:53
| 2016-07-16T13:18:53
| 60,747,429
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,909
|
py
|
from enum import Enum
from cwpoliticl.extensions.dailyo_parser import DailyoParser
from cwpoliticl.extensions.deccanchronicle_parser import DeccanchronicleParser
from cwpoliticl.extensions.dnaindia_parser import DnaIndiaParser
from cwpoliticl.extensions.firstpost_parser import FirstPostParser
from cwpoliticl.extensions.hindustantimes_parser import HindustantimesParser
from cwpoliticl.extensions.indianexpress_parser import IndianExpressParser
from cwpoliticl.extensions.news18_parser import News18Parser
from cwpoliticl.extensions.theindianeconomist_parser import TheIndianEconomistParser
from cwpoliticl.extensions.theviewspaper_parser import TheViewsPaperParser
class WebsiteTypes(Enum):
def __str__(self):
return str(self.value)
dnaindia = "dnaindia"
indianexpress = "indianexpress"
theviewspaper = "theviewspaper"
dailyo = "dailyo"
deccanchronicle = "deccanchronicle"
firstpost = "firstpost"
# forbesindia = "forbesindia" # ???
hindustantimes = "hindustantimes"
news18 = "news18"
theindianeconomist = "theindianeconomist"
@classmethod
def get_pagination_url(cls, type):
return scraped_websites_pagination.keys()[scraped_websites_pagination.values().index(type)]
content_seperator = '\n' + '\n'
websites_allowed_domains = {
WebsiteTypes.dnaindia: "www.dnaindia.com",
WebsiteTypes.indianexpress: "www.indianexpress.com",
WebsiteTypes.theviewspaper: "theviewspaper.net",
WebsiteTypes.dailyo: 'www.dailyo.in',
WebsiteTypes.deccanchronicle: 'www.deccanchronicle.com',
WebsiteTypes.firstpost: 'www.firstpost.com',
# WebsiteTypes.forbesindia: 'forbesindia.com', # ???
WebsiteTypes.hindustantimes: 'www.hindustantimes.com',
WebsiteTypes.news18: 'www.news18.com',
WebsiteTypes.theindianeconomist: 'theindianeconomist.com',
}
scraped_websites_pagination = {
'http://www.dnaindia.com/analysis': WebsiteTypes.dnaindia,
'http://indianexpress.com/opinion/': WebsiteTypes.indianexpress,
'http://theviewspaper.net': WebsiteTypes.theviewspaper,
'http://www.dailyo.in/politics': WebsiteTypes.dailyo,
'http://www.deccanchronicle.com/opinion': WebsiteTypes.deccanchronicle,
'http://www.firstpost.com/category/politics': WebsiteTypes.firstpost,
# 'http://forbesindia.com/': WebsiteTypes.forbesindia, # ???
'http://www.hindustantimes.com/opinion/': WebsiteTypes.hindustantimes,
'http://www.news18.com/blogs/': WebsiteTypes.news18,
'http://theindianeconomist.com/': WebsiteTypes.theindianeconomist,
}
websites_parses = {
WebsiteTypes.dnaindia: DnaIndiaParser(),
WebsiteTypes.indianexpress: IndianExpressParser(),
WebsiteTypes.theviewspaper: TheViewsPaperParser(),
WebsiteTypes.dailyo: DailyoParser(),
WebsiteTypes.deccanchronicle: DeccanchronicleParser(),
WebsiteTypes.firstpost: FirstPostParser(),
# WebsiteTypes.forbesindia: FirstPostParser(), # ???
WebsiteTypes.hindustantimes: HindustantimesParser(),
WebsiteTypes.news18: News18Parser(),
WebsiteTypes.theindianeconomist: TheIndianEconomistParser()
}
# ===
# for debug
# ===
def get_crawler_name():
# Extensions
# is_pagination = True
is_pagination = False
# url_from = WebsiteTypes.dnaindia
# url_from = WebsiteTypes.indianexpress
# url_from = WebsiteTypes.theviewspaper
url_from = WebsiteTypes.dailyo
# url_from = WebsiteTypes.deccanchronicle
# url_from = WebsiteTypes.firstpost
# url_from = WebsiteTypes.forbesindia # ???
# url_from = WebsiteTypes.hindustantimes
# url_from = WebsiteTypes.news18
# url_from = WebsiteTypes.theindianeconomist
crawler_names = [
# "politicl",
# "politicl_watch",
"{}_debug".format(url_from.value)
]
return {
'name': crawler_names[0],
'is_pagination': is_pagination
}
is_pagination = get_crawler_name()['is_pagination']
|
[
"trujunzhang@gmail.com"
] |
trujunzhang@gmail.com
|
65356e5dbd131f3cc166ec4c8ccf3afb28c990af
|
daa3498147304fe617b8b77a38bc96bb9a8f6d6c
|
/archs/core/wideresnet.py
|
75186cfbaa58b8ade7c484fc2bf077c0e9b12c14
|
[
"MIT"
] |
permissive
|
gatheluck/archs
|
9a13050f0b217d8f24528d0e0743c63190fa3f0c
|
23adfd71ae3b1f73416c59e82af80698cb2e593e
|
refs/heads/master
| 2023-03-10T08:34:26.917271
| 2021-02-19T03:13:14
| 2021-02-19T03:13:14
| 333,693,669
| 0
| 0
|
MIT
| 2021-02-28T13:34:10
| 2021-01-28T08:27:24
|
Python
|
UTF-8
|
Python
| false
| false
| 5,584
|
py
|
import math
from typing import Type, Union
import torch
from torch import nn
from torch.nn import functional
__all__ = ["wideresnet16", "wideresnet28", "wideresnet40"]
class BasicBlock(nn.Module):
def __init__(
self, in_planes: int, out_planes: int, stride: int, droprate: float = 0.0
) -> None:
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(True)
self.conv1 = nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False
)
self.bn2 = nn.BatchNorm2d(out_planes)
self.relu2 = nn.ReLU(True)
self.conv2 = nn.Conv2d(
out_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=False
)
self.droprate = droprate
self.equal_io = in_planes == out_planes
self.shortcut = (
nn.Conv2d(
in_planes,
out_planes,
kernel_size=1,
stride=stride,
padding=0,
bias=False,
)
if not self.equal_io
else None
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
o = self.relu1(self.bn1(x))
if not self.equal_io: # for shortcut
x = self.shortcut(o) # type: ignore
o = self.relu2(self.bn2(self.conv1(o)))
if self.droprate > 0:
o = functional.dropout(o, p=self.droprate, training=self.training)
o = self.conv2(o)
return x + o
class NetworkBlock(nn.Module):
def __init__(
self,
block: Type[nn.Module],
in_planes: int,
out_planes: int,
n: Union[int, float],
stride: int,
droprate: float = 0.0,
) -> None:
super(NetworkBlock, self).__init__()
self.layer = self._make_layer(block, in_planes, out_planes, n, stride, droprate)
def _make_layer(
self,
block: Type[nn.Module],
in_planes: int,
out_planes: int,
n: Union[int, float],
stride: int,
droprate: float,
) -> nn.Module:
layers = []
for i in range(int(n)):
layers.append(
block( # type: ignore
in_planes if i == 0 else out_planes,
out_planes,
stride if i == 0 else 1,
droprate,
)
)
return nn.Sequential(*layers)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.layer(x)
class WideResNet(nn.Module):
def __init__(
self, num_classes: int, depth: int, width: int = 1, droprate: float = 0.0
) -> None:
super(WideResNet, self).__init__()
nc = [16, 16 * width, 32 * width, 64 * width]
assert (depth - 4) % 6 == 0
n = (depth - 4) / 6
block = BasicBlock
self.depth = depth
self.width = width
self.conv1 = nn.Conv2d(3, nc[0], kernel_size=3, stride=1, padding=1, bias=False)
self.block1 = NetworkBlock(block, nc[0], nc[1], n, 1, droprate)
self.block2 = NetworkBlock(block, nc[1], nc[2], n, 2, droprate)
self.block3 = NetworkBlock(block, nc[2], nc[3], n, 2, droprate)
self.bn = nn.BatchNorm2d(nc[3])
self.relu = nn.ReLU(True)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(nc[3], num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2.0 / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.bias.data.zero_()
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.conv1(x)
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.relu(self.bn(x))
x = self.avgpool(x)
x = x.view(-1, 64 * self.width)
return self.fc(x)
def wideresnet16(
num_classes: int = 1000, widening_factor: int = 8, droprate: float = 0.3
) -> nn.Module:
"""factory class of Wide ResNet-16.
Parameters
----------
num_classes : int
Number of output class.
widening_factor : int
This number decide width of model which is represented by k in original paper.
droprate : float
Probability of dropout.
"""
return WideResNet(num_classes, 16, widening_factor, droprate)
def wideresnet28(
num_classes: int = 1000, widening_factor: int = 10, droprate: float = 0.3
) -> nn.Module:
"""factory class of Wide ResNet-28.
Parameters
----------
num_classes : int
Number of output class.
widening_factor : int
This number decide width of model which is represented by k in original paper.
droprate : float
Probability of dropout.
"""
return WideResNet(num_classes, 28, widening_factor, droprate)
def wideresnet40(
num_classes: int = 1000, widening_factor: int = 2, droprate: float = 0.3
) -> nn.Module:
"""factory class of Wide ResNet-40.
Parameters
----------
num_classes : int
Number of output class.
widening_factor : int
This number decide width of model which is represented by k in original paper.
droprate : float
Probability of dropout.
"""
return WideResNet(num_classes, 40, widening_factor, droprate)
|
[
"gatheluck+tech@gmail.com"
] |
gatheluck+tech@gmail.com
|
75948801b21c5fbd376936925ab4134c3dfaedec
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p02397/s703752111.py
|
c76263628dfd6c936ed83609679a4b2b18dfa38d
|
[] |
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
| 190
|
py
|
for i in range(3000):
a = input().split()
x = int(a[0])
y = int(a[1])
if x + y == 0:
break
elif x < y:
print(x,y)
elif y < x:
print(y,x)
else:
print(x,y)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
7458d7f380e6667abd2fe6bb0b1909024baa0a30
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/40/usersdata/84/23549/submittedfiles/main.py
|
c42463e6d42fbe22f24ac4b3c428bb369aaa1b15
|
[] |
no_license
|
rafaelperazzo/programacao-web
|
95643423a35c44613b0f64bed05bd34780fe2436
|
170dd5440afb9ee68a973f3de13a99aa4c735d79
|
refs/heads/master
| 2021-01-12T14:06:25.773146
| 2017-12-22T16:05:45
| 2017-12-22T16:05:45
| 69,566,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 291
|
py
|
# -*- coding: utf-8 -*-
from __future__ import division
import funcoes
#COMECE AQUI
m=input('digite o numero m de termos da formula de pi:')
e=input('digite o epsilon para o calculo da razao aurea:')
print('%.15f'%(funcoes.calcula_pi(m)))
print('%.15f'%(funcoes.calcula_razao_aurea(m,e)))
|
[
"rafael.mota@ufca.edu.br"
] |
rafael.mota@ufca.edu.br
|
cedd6424f3d86009eb50c26c71ae2df8dd7d90cd
|
c1fdff5522b65fbff697d5445ef018f5a4c4d39f
|
/src/profiles_project/profiles_api/urls.py
|
1570d40b697fc89f4ce5e8252b65c87fedc2fb79
|
[] |
no_license
|
jimpalowski/2nd-REST
|
858f2ac4b38e59ec275cbcbb682a929bc8052a50
|
e7e51da345332b5a5f854076b46776677f2f7571
|
refs/heads/master
| 2021-04-26T23:53:44.496698
| 2018-03-05T06:44:51
| 2018-03-05T06:44:51
| 123,876,527
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 529
|
py
|
from django.conf.urls import url
from django.conf.urls import include
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, base_name='hello-viewset')
router.register('profile', views.UserProfileViewSet)
router.register('login', views.LoginViewSet, base_name='login')
router.register('feed', views.UserProfileFeedViewSet)
urlpatterns = [
url(r'^hello-view/', views.HelloApiView.as_view()),
url(r'', include(router.urls))
]
|
[
"palowskijim@gmail.com"
] |
palowskijim@gmail.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.