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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a11414020e389e004fa7ba41d64bb7afc662c6ec
|
33cc37817d93dd784be2398c904c9b4cacf84c52
|
/Week5_Object_Oriented_Programming/Practice_Problems/currencies.py
|
1e40cb96d3c767ece8d29f152b283a21e682a68a
|
[] |
no_license
|
M1c17/ICS_and_Programming_Using_Python
|
305e53561af27067998cb767ee5d566dfc02d33d
|
ee5127a272fbf19289a6a97cbe9b2ada2f7785ca
|
refs/heads/master
| 2020-07-02T00:04:28.574491 | 2019-08-09T00:16:11 | 2019-08-09T00:16:11 | 201,354,816 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,217 |
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 5 12:09:10 2019
@author: MASTER
"""
'''
The class "Ccy" can be used to define money values in various currencies.
A Ccy instance has the string attributes 'unit' (e.g. 'CHF', 'CAD' od 'EUR'
and the 'value' as a float.
A currency object consists of a value and the corresponding unit.
'''
class Ccy:
currencies = {'CHF': 1.0821202355817312,
'CAD': 1.488609845538393,
'GBP': 0.8916546282920325,
'JPY': 114.38826536281809,
'EUR': 1.0,
'USD': 1.11123458162018}
def __init__(self, value, unit = 'EUR'):
self.value = value
self.unit = unit
def __str__(self):
return "{0:5.2f}".format(self.value) + " " + self.unit
def changeTo(self, new_unit):
"""
An Ccy object is transformed from the unit "self.unit" to "new_unit"
"""
self.value = (self.value / Ccy.currencies[self.unit] * Ccy.currencies[new_unit])
self.unit = new_unit
def __add__(self, other):
"""
Defines the '+' operator.
If other is a CCy object the currency values
are added and the result will be the unit of
self. If other is an int or a float, other will
be treated as a Euro value.
"""
if type(other) == int or type(other) == float:
x = (other * Ccy.currencies[self.unit])
else:
x = (other.value / Ccy.currencies[other.unit] * Ccy.currencies[self.unit])
return Ccy(x + self.value, self.unit)
def __iadd__(self, other):
"""
Similar to __add__
"""
if type(other) == int or type(other) == float:
x = (other * Ccy.currencies[self.unit])
else:
x = (other.value / Ccy.currencies[other.unit] * Ccy.currencies[self.unit])
self.value += x
return self
# we need change to EUR
def __radd__(self, other):
res = self + other
if self.unit != "EUR":
res.changeTo("EUR")
return res
# def __radd__(self, other):
# return Ccy.__add__(self,other)
def __mul__(self, other):
"""
Multiplication is only defined as a scalar multiplication,
i.e. a money value can be multiplied by an int or a float.
It is not possible to multiply to money values
"""
if type(other)==int or type(other)==float:
return Ccy(self.value * other, self.unit)
else:
raise TypeError("unsupported operand type(s) for *: 'Ccy' and " + type(other).__name__)
def __rmul__(self, other):
return self.__mul__(other)
def __imul__(self, other):
if type(other)==int or type(other)==float:
self.value *= other
return self
else:
raise TypeError("unsupported operand type(s) for *: 'Ccy' and " + type(other).__name__)
x = Ccy(10,"USD")
y = Ccy(11)
z = Ccy(12.34, "JPY")
z = 7.8 + x + y + 255 + z
print(z)
lst = [Ccy(10,"USD"), Ccy(11), Ccy(12.34, "JPY"), Ccy(12.34, "CAD")]
z = sum(lst)
print(z)
|
[
"[email protected]"
] | |
f9c126902d927e7a260fb705bce0e1c27552cc30
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/309/usersdata/284/72935/submittedfiles/atm.py
|
bdf46aa78ba6d32e46748200a85c384c0a0db6f1
|
[] |
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 | 292 |
py
|
# -*- coding: utf-8 -*-
from __future__ import division
import math
#COMECE SEU CODIGO AQUI
v=int(input('digite o valor a ser sacado: '))
a=20
b=10
c=5
d=2
e=1
f=(v%a)
g=(f%10)
h=(g%5)
i=(h%2)
if v//a!=0:
print(v//a)
print(f//10)
print(g//5)
print(h//2)
print(i//1)
|
[
"[email protected]"
] | |
1f96f72f233d70286289b429157d02f586e49a0c
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/134/usersdata/228/53506/submittedfiles/escadarolante.py
|
b21aed3136bcf8b81ed533496221440ebca0f3d7
|
[] |
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 | 748 |
py
|
# -*- coding: utf-8 -*-
def rolagem(lista):
for i in range (0,len(lista)-2,1):
tempo=10
if lista[i+1]<(lista[i]+10):
tempo=tempo+(lista[i]-lista[i+1])
elif lista[i+1]>=(lista[i]+10):
tempo=tempo+10
for i in range (len(lista)-1,len(lista)-2,1):
if lista[len(lista-1)]<lista[len(lista)-2]+10:
tempo=tempo+(lista[len(lista)-1]-lista[len(lista)-2])
elif lista[len(lista)-1]>=lista[len(lista)-2]+10:
tempo=tempo+10
return(tempo+10)
n=int(input('digite um valor:'))
lista=[]
for i in range(0,n,1):
tn=int(input('digite um tempo de passagem:'))
lista.append(tn)
print (rolagem(lista))
|
[
"[email protected]"
] | |
97f9717024df32c598a14e0f724cbdbe3bf03874
|
08d316151302f7ba4ae841c15b7adfe4e348ddf1
|
/reviewboard/hostingsvcs/tests/test_sourceforge.py
|
f51901fb883aee02393c4d7033117c7503f6470d
|
[
"MIT"
] |
permissive
|
LloydFinch/reviewboard
|
aa8cd21fac359d49b3dfc5a68c42b857c0c04bd8
|
563c1e8d4dfd860f372281dc0f380a0809f6ae15
|
refs/heads/master
| 2020-08-10T20:02:32.204351 | 2019-10-02T20:46:08 | 2019-10-02T20:46:08 | 214,411,166 | 2 | 0 |
MIT
| 2019-10-11T10:44:55 | 2019-10-11T10:44:54 | null |
UTF-8
|
Python
| false | false | 2,727 |
py
|
"""Unit tests for the SourceForge hosting service."""
from __future__ import unicode_literals
from reviewboard.hostingsvcs.testing import HostingServiceTestCase
class SourceForgeTests(HostingServiceTestCase):
"""Unit tests for the SourceForge hosting service."""
service_name = 'sourceforge'
def test_service_support(self):
"""Testing SourceForge service support capabilities"""
self.assertTrue(self.service_class.supports_bug_trackers)
self.assertTrue(self.service_class.supports_repositories)
def test_get_repository_fields_with_bazaar(self):
"""Testing SourceForge.get_repository_fields for Bazaar"""
self.assertEqual(
self.get_repository_fields(
'Bazaar',
fields={
'sourceforge_project_name': 'myproj',
}
),
{
'path': 'bzr://myproj.bzr.sourceforge.net/bzrroot/myproj',
'mirror_path': ('bzr+ssh://myproj.bzr.sourceforge.net/bzrroot/'
'myproj'),
})
def test_get_repository_fields_with_cvs(self):
"""Testing SourceForge.get_repository_fields for CVS"""
self.assertEqual(
self.get_repository_fields(
'CVS',
fields={
'sourceforge_project_name': 'myproj',
}
),
{
'path': (':pserver:[email protected]:'
'/cvsroot/myproj'),
'mirror_path': 'myproj.cvs.sourceforge.net/cvsroot/myproj',
})
def test_get_repository_fields_with_mercurial(self):
"""Testing SourceForge.get_repository_fields for Mercurial"""
self.assertEqual(
self.get_repository_fields(
'Mercurial',
fields={
'sourceforge_project_name': 'myproj',
}
),
{
'path': 'http://myproj.hg.sourceforge.net:8000/hgroot/myproj',
'mirror_path': 'ssh://myproj.hg.sourceforge.net/hgroot/myproj',
})
def test_get_repository_fields_with_svn(self):
"""Testing SourceForge.get_repository_fields for Subversion"""
self.assertEqual(
self.get_repository_fields(
'Subversion',
fields={
'sourceforge_project_name': 'myproj',
}
),
{
'path': 'http://myproj.svn.sourceforge.net/svnroot/myproj',
'mirror_path': ('https://myproj.svn.sourceforge.net/svnroot/'
'myproj'),
})
|
[
"[email protected]"
] | |
b2d53ffd5c0d66ff8ad6d790ce50cfb7e2ec15cd
|
04a97dbb2ab510ec64a944dd5aaf834271788a32
|
/django2/mysite/city_summary_stats.py
|
465ddd22ae68c7689bedb5da94be9e8d77ced5a7
|
[] |
no_license
|
emilyding/ACE-cs122project
|
98d2b67aa8151b2649c4a980d6daf80fb9817898
|
5941d8de85770f3e1b05e0bdc5a4b1cd6f1d35f5
|
refs/heads/master
| 2021-01-11T17:19:25.243093 | 2017-03-14T21:25:18 | 2017-03-14T21:25:18 | 79,745,285 | 0 | 0 | null | 2017-03-10T20:16:16 | 2017-01-22T20:59:03 |
HTML
|
UTF-8
|
Python
| false | false | 6,330 |
py
|
# Summary City Data
'''
Takes as an input a dictionary with the name of a city, and returns interesting
summary statistics. Note that using the adjusted database will lead to errors
identifying universally hated/acclaimed restaurants (as ratings of 1 or 5 will
be adjusted slightly upwards or downwards)
Usage: Call get_summary_info with the city of interest.
Example Call: get_summary_info({'city': 'Los Angeles'})
'''
import sqlite3
import csv
# Maps cities to median min meters between starbucks
# Dictionary readout produced by build_starbucks_dictionary.py
starbucks_mapper = {'albuquerque': '154.15', 'arlington': '83.33', 'atlanta': '352.59',
'austin': '123.41', 'baltimore': '86.41', 'boston': '98.32', 'buffalo': '162.93',
'charlotte': '251.00', 'chicago': '138.73', 'cleveland': '149.90', 'colorado springs': '221.52',
'columbus': '385.16', 'dallas': '517.69', 'denver': '282.46', 'detroit': '486.73',
'el paso': '241.77', 'fort worth': '239.43', 'fresno': '96.81', 'honolulu': '33.39',
'houston': '393.32', 'indianapolis': '406.86', 'jacksonville': '184.75', 'kansas city': '978.47',
'las vegas': '395.43', 'long beach': '112.44', 'los angeles': '187.45', 'louisville': '213.46',
'memphis': '219.27', 'mesa': '411.07', 'miami': '142.43', 'milwaukee': '146.95',
'minneapolis': '317.86', 'nashville': '173.47', 'new orleans': '103.72', 'new york': '105.39',
'oakland': '97.87', 'oklahoma city': '213.86', 'omaha': '228.06', 'philadelphia': '106.38',
'phoenix': '531.17', 'pittsburgh': '272.22', 'portland': '193.92', 'raleigh': '564.58',
'sacramento': '84.44', 'san antonio': '363.24', 'san diego': '110.48', 'san francisco': '67.07',
'san jose': '89.94', 'seattle': '134.22', 'st louis': '635.64', 'st paul': '125.64',
'tampa': '324.66', 'tucson': '135.19', 'tulsa': '327.75', 'virginia beach': '140.52',
'washington dc': '106.63'}
def build_starbucks_dictionary(filepath = 'starbucks_index.csv'):
'''
Given a filepath, constructs a dictionary mapping each city to the
median minimum distance to another Starbucks. Used in get_summary_info.
Inputs:
- filepath: The location of the Starbucks distance csv
Returns:
- Dictionary mapping cities to the median min starbucks distance
'''
starbucks_mapper = {}
with open(filepath) as holding:
reader = csv.reader(holding)
for row in reader:
# Skip headers
if row[2] != "Median Distance":
# Build dictionary, applying rounding
starbucks_mapper.update({row[1]: "{0:.2f}".format(float(row[2]))})
return starbucks_mapper
def get_summary_info(city = {'city': 'Los Angeles'}, database = "yelp_raw.db"):
'''
Takes in a city dictionary and database and returns summary statistics.
Inputs:
- city: City of interest. Format is {'city': 'Chicago'}
- database = Location of unadjusted database
Returns:
- A list of tuples displaying summary information
'''
# Change city input to lowercase, if necessary
city["city"] = city["city"].lower()
# Find necessary information
total_restaurants = find_total_restaurants(city, database)
starbucks_index = starbucks_mapper[city["city"]]
most_reviewed = find_most_reviewed_restaurant(city, database)
most_acclaimed = find_consensus_restaurant(city, database, rating = 5)
most_hated = find_consensus_restaurant(city, database, rating = 1)
# Construct Result List
result_list = []
result_list.append(("Total Restaurants in City:", total_restaurants))
result_list.append(("Starbucks Distance Index:",
"{} Meters".format(starbucks_index)))
result_list.append(("Most Reviewed Restaurant:",
"{}, {} Reviews".format(most_reviewed[0], most_reviewed[1])))
result_list.append(("Most Reviewed 5-Star Restaurant:",
"{}, {} Reviews".format(most_acclaimed[0], most_acclaimed[1])))
result_list.append(("Most Reviewed 1-Star Restaurant:",
"{}, {} Reviews".format(most_hated[0], most_hated[1])))
return result_list
def find_total_restaurants(city, database):
'''
Finds total number of restauarants in a city.
Inputs:
- city: City of interest. Format is {'city': 'Chicago'}
- database = Location of unadjusted database
Returns:
- Integer of number of cities
'''
connection = sqlite3.connect(database)
c = connection.cursor()
search_string = '''SELECT COUNT(*)
FROM restaurant
WHERE city = ?
COLLATE NOCASE
'''
params = [city["city"]]
result = c.execute(search_string, params)
result = result.fetchone()
connection.commit()
c.connection.close()
return result[0]
def find_most_reviewed_restaurant(city, database):
'''
Finds the most reviewed restaurant and its review count
Inputs:
- city: City of interest. Format is {'city': 'Chicago'}
- database = Location of unadjusted database
Returns:
- Most reviewed restauarant and review count as a list
'''
connection = sqlite3.connect(database)
c = connection.cursor()
search_string = '''SELECT name, reviews
FROM restaurant
WHERE city = ?
COLLATE NOCASE
'''
params = [city["city"]]
result = c.execute(search_string, params)
results = result.fetchall()
# Sort by review count
results = sorted(results, key=lambda x: x[1], reverse = True)
connection.commit()
c.connection.close()
return results[0]
def find_consensus_restaurant(city, database, rating):
'''
Finds most reviewed restaurant at a given rating level.
Inputs:
- city: City of interest. Format is {'city': 'Chicago'}
- database = Location of unadjusted database
Returns:
- Most reviewed restauarant and review count as a list
'''
connection = sqlite3.connect(database)
c = connection.cursor()
search_string = '''SELECT name, reviews, rating
FROM restaurant
WHERE city = ?
COLLATE NOCASE
AND rating = ?;
'''
params = [city["city"], rating]
result = c.execute(search_string, params)
results = result.fetchall()
# Sort by review count
results = sorted(results, key=lambda x: x[1], reverse = True)
connection.commit()
c.connection.close()
return results[0]
|
[
"[email protected]"
] | |
1068b7713ec020de5734f28062543b8079b9df6d
|
d62fbff86f8d4f332e843843bba7d07e2361554f
|
/Examples/tests/example_2_unittest.py
|
a4ecd8c88c26e34fb9560b454a023f409b1c0266
|
[] |
no_license
|
haisfo/python-environments
|
e031850fa4e8778eea7c618d1eec74e723e615f1
|
73fb4dbe56f1ebbfba71d440ba3c953556688bf9
|
refs/heads/master
| 2022-12-27T19:51:13.046530 | 2020-10-16T00:11:28 | 2020-10-16T00:11:28 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,149 |
py
|
import unittest
from rock_paper_scissors_buggy import determine_winner, game_over, YOU, COMP
class TestWordGame(unittest.TestCase):
def test_determine_winner(self):
self.assertEqual(determine_winner('r', 'r'), None)
self.assertEqual(determine_winner('r', 'p'), COMP)
self.assertEqual(determine_winner('r', 's'), YOU)
self.assertEqual(determine_winner('p', 'r'), YOU)
self.assertEqual(determine_winner('p', 'p'), None)
self.assertEqual(determine_winner('p', 's'), COMP)
self.assertEqual(determine_winner('s', 'r'), COMP)
self.assertEqual(determine_winner('s', 'p'), YOU)
self.assertEqual(determine_winner('s', 's'), None)
def test_game_over(self):
self.assertEqual(game_over(3, [0, 0]), None)
self.assertEqual(game_over(3, [1, 1]), None)
self.assertEqual(game_over(3, [2, 1]), YOU)
self.assertEqual(game_over(3, [1, 2]), COMP)
self.assertEqual(game_over(5, [2, 2]), None)
self.assertEqual(game_over(5, [3, 0]), YOU)
self.assertEqual(game_over(5, [1, 3]), COMP)
if __name__ == '__main__':
unittest.main()
|
[
"[email protected]"
] | |
87000c88ad989e720e8303d6f29d9912748b2d30
|
254d38ad3d455b94170e4ef17045d6c10daee986
|
/doc_src/code_sample/case1_admin.py
|
f34ae1be6a6e05c2cdd7ae730c848ce4f701da26
|
[
"Apache-2.0"
] |
permissive
|
giorgil/django-articleappkit
|
4d2108b6bb32e3089c61c5b81c55d7d6febf5acb
|
d301f2d511a65461eedbcc301955dafecba189ca
|
refs/heads/master
| 2019-07-06T06:43:47.256809 | 2017-10-19T18:10:40 | 2017-10-19T18:10:40 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 487 |
py
|
from django.contrib import admin
from articleappkit.admin import (ArticleBaseAdmin, ARTICLE_BASE_FIELDSET,
SINGLE_AUTHOR_FIELDSET, KEY_IMAGE_FIELDSET,
PUBLISHING_FIELDSET)
from .models import Story
class StoryAdmin(ArticleBaseAdmin):
fieldsets = (
ARTICLE_BASE_FIELDSET,
SINGLE_AUTHOR_FIELDSET,
KEY_IMAGE_FIELDSET,
PUBLISHING_FIELDSET,
)
admin.site.register(Story, StoryAdmin)
|
[
"[email protected]"
] | |
856dc99df1b2a415589cdc169f574672bd782c91
|
2616952e9dcf7a996c691e5410551d89ec735943
|
/Python Basic for ML and DL Book3/Ensemble methods Ensemble Error diagram.py
|
2ec889de7b8cb72089d30d213d0d2065c1cbc6fa
|
[] |
no_license
|
BaoBao0406/Machine-Learning
|
5c9f00c19422e7fead74d4f441fcc43556b62b78
|
c3e1c03301b41220c58a1bbda8f872638dc24104
|
refs/heads/master
| 2021-07-12T10:25:28.791579 | 2020-08-24T00:17:43 | 2020-08-24T00:17:43 | 197,107,543 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 794 |
py
|
from scipy.misc import comb
import math
def ensemble_error(n_classifier, error):
k_start = int(math.ceil(n_classifier / 2.))
probs = [comb(n_classifier, k) * error**k * (1-error)**(n_classifier - k)
for k in range(k_start, n_classifier + 1)]
return sum(probs)
ensemble_error(n_classifier=11, error=0.25)
import numpy as np
import matplotlib.pyplot as plt
error_range = np.range(0.0, 1.01, 0.01)
ens_errors = [ensemble_error(n_classifier=11, error=error)
for error in error_range]
plt.plot(error_range, ens_errors, label='Ensemble error', linewidth=2)
plt.plot(error_range, error_range, linestyle='--', label='Base error', linewidth=2)
plt.xlabel('Base error')
plt.ylabel('Base/Ensemble error')
plt.legend(loc='upper left')
plt.grid(alpha=0.5)
plt.show()
|
[
"[email protected]"
] | |
639a60840ad7e8b452e12cb388e417b5a2b16264
|
be0f3dfbaa2fa3d8bbe59229aef3212d032e7dd1
|
/Gauss_v45r9/Gen/DecFiles/options/12143431.py
|
e56ad1dfbd9078ce9947efcd957b4a0ee3f23907
|
[] |
no_license
|
Sally27/backup_cmtuser_full
|
34782102ed23c6335c48650a6eaa901137355d00
|
8924bebb935b96d438ce85b384cfc132d9af90f6
|
refs/heads/master
| 2020-05-21T09:27:04.370765 | 2018-12-12T14:41:07 | 2018-12-12T14:41:07 | 185,989,173 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,809 |
py
|
# file /home/hep/ss4314/cmtuser/Gauss_v45r9/Gen/DecFiles/options/12143431.py generated: Fri, 27 Mar 2015 16:10:07
#
# Event Type: 12143431
#
# ASCII decay Descriptor: [B+ -> K+ (J/psi(1S) -> mu+ mu- {,gamma} {,gamma}) (eta -> gamma gamma)]cc
#
from Configurables import Generation
Generation().EventType = 12143431
Generation().SampleGenerationTool = "SignalRepeatedHadronization"
from Configurables import SignalRepeatedHadronization
Generation().addTool( SignalRepeatedHadronization )
Generation().SignalRepeatedHadronization.ProductionTool = "PythiaProduction"
from Configurables import ToolSvc
from Configurables import EvtGenDecay
ToolSvc().addTool( EvtGenDecay )
ToolSvc().EvtGenDecay.UserDecayFile = "$DECFILESROOT/dkfiles/Bu_JpsietaK,mm,gg=DecProdCut.dec"
Generation().SignalRepeatedHadronization.CutTool = "DaughtersInLHCb"
Generation().SignalRepeatedHadronization.SignalPIDList = [ 521,-521 ]
# Ad-hoc particle gun code
from Configurables import ParticleGun
pgun = ParticleGun("ParticleGun")
pgun.SignalPdgCode = 521
pgun.DecayTool = "EvtGenDecay"
pgun.GenCutTool = "DaughtersInLHCb"
from Configurables import FlatNParticles
pgun.NumberOfParticlesTool = "FlatNParticles"
pgun.addTool( FlatNParticles , name = "FlatNParticles" )
from Configurables import MomentumSpectrum
pgun.ParticleGunTool = "MomentumSpectrum"
pgun.addTool( MomentumSpectrum , name = "MomentumSpectrum" )
pgun.MomentumSpectrum.PdgCodes = [ 521,-521 ]
pgun.MomentumSpectrum.InputFile = "$PGUNSDATAROOT/data/Ebeam4000GeV/MomentumSpectrum_521.root"
pgun.MomentumSpectrum.BinningVariables = "pteta"
pgun.MomentumSpectrum.HistogramPath = "h_pteta"
from Configurables import BeamSpotSmearVertex
pgun.addTool(BeamSpotSmearVertex, name="BeamSpotSmearVertex")
pgun.VertexSmearingTool = "BeamSpotSmearVertex"
pgun.EventType = 12143431
|
[
"[email protected]"
] | |
4c507eda6df4eec5409d9ba0f7c5c58dbe4adc2c
|
a8637de7c6e38c95cd19b46b45b3e00c42ae8140
|
/recruitments/forms.py
|
b4d18a84d6fec828e87868c360f345c9f5ccb4dd
|
[] |
no_license
|
nishant57/edc
|
9c0d3d363882c44bc08dc4da47024e5e83731077
|
5ab9f6dc5d474b5071c7f027cd287c32a9d43501
|
refs/heads/master
| 2021-01-12T19:31:49.655509 | 2013-02-17T10:00:36 | 2013-02-17T10:00:36 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,431 |
py
|
from django.db import models
from django.forms import ModelForm, Textarea
from django import forms
from constants import *
from recruitments.models import Candidate, Setup
from ckeditor.widgets import CKEditorWidget
from django.core.exceptions import ObjectDoesNotExist
class CandidateForm(forms.ModelForm):
class Meta:
model = Candidate
exclude = ('hash_value', 'blocked', 'setup', 'slot')
def clean(self):
cleaned_data = self.cleaned_data
email = cleaned_data.get('email')
try:
s = Setup.objects.get(date_recruitment_ends__gt=datetime.now(), date_recruitment_starts__lt=datetime.now())
Candidate.objects.get(email=email, setup=s)
raise forms.ValidationError('This Email ID has already applied for this recruitment process')
except ObjectDoesNotExist:
pass
return cleaned_data
'''
salutation = forms.CharField(max_length=10,required=True,choices=SALUTATION_CHOICES)
name = forms.CharField(max_length=50,required = True,label='Your name')
email = forms.EmailField(max_length=50,required=True,label='Email Address')
branch = forms.CharField(max_length=50,required=True,choices=BRANCH_CHOICES)
phone = forms.CharField(max_length=15, required=True)
why_edc = forms.TextField(max_length=500,required=True)
other_groups = forms.TextField(max_length=100)
interests = forms.
'''
|
[
"[email protected]"
] | |
ea026000b6292aaf81ca75b7bc134d1a849290bd
|
ee561aa019a80f621007f82bdb21fe6ed8b6278f
|
/build/turtlebot3-melodic-devel/turtlebot3_navigation/catkin_generated/pkg.installspace.context.pc.py
|
2314ec5e0e068618e2ccde34da5357db5a46d171
|
[] |
no_license
|
allanwhledu/agv_edu_prj
|
4fb5fbf14cf0a14edd57ee9bd87903dc25d4d4f2
|
643a8a96ca7027529332f25208350de78c07e33d
|
refs/heads/master
| 2020-09-23T23:32:54.430035 | 2019-12-04T07:47:55 | 2019-12-04T07:47:55 | 225,613,426 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 388 |
py
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "turtlebot3_navigation"
PROJECT_SPACE_DIR = "/home/sjtuwhl/ROBOTLAB_WS/install"
PROJECT_VERSION = "1.2.2"
|
[
"[email protected]"
] | |
3892f819ab9827f25746acaf5e7ddb23394850ca
|
f259ca399ab33b5c2e66ae07921711ea5917ac9e
|
/pytorch/sphereface.py
|
d6413d43827cf63587f8d89889c96b608aa81521
|
[] |
no_license
|
jizhuoran/HyperTea_Maker
|
9a7930e1d6af995c8fdb9a15354eea5fc29f0806
|
2c3f8dfcb699495093165cd986eebedfb17a2433
|
refs/heads/master
| 2020-04-22T19:32:39.385611 | 2019-04-14T15:12:06 | 2019-04-14T15:12:48 | 170,610,900 | 4 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,268 |
py
|
# -*- coding: utf-8 -*-
import torch
from sphere20a import sphere20a as Model
from hypertea_generator.hypertea_generator import HyperteaGenerator
model = Model().train()
precision = 'float'
genetator = HyperteaGenerator(model, torch.ones((1, 3, 112, 96), dtype = torch.float), precision)
output = genetator.get_net_output()
inference_code = f'''
void inference( std::vector<{precision}> &data_from_user, std::vector<{precision}> &data_to_user) {{
auto x = DeviceTensor(data_from_user);
x = relu1_1(conv1_1(x))
x = x + relu1_3(conv1_3(relu1_2(conv1_2(x))))
x = relu2_1(conv2_1(x))
x = x + relu2_3(conv2_3(relu2_2(conv2_2(x))))
x = x + relu2_5(conv2_5(relu2_4(conv2_4(x))))
x = relu3_1(conv3_1(x))
x = x + relu3_3(conv3_3(relu3_2(conv3_2(x))))
x = x + relu3_5(conv3_5(relu3_4(conv3_4(x))))
x = x + relu3_7(conv3_7(relu3_6(conv3_6(x))))
x = x + relu3_9(conv3_9(relu3_8(conv3_8(x))))
x = relu4_1(conv4_1(x))
x = x + relu4_3(conv4_3(relu4_2(conv4_2(x))))
x = fc5(x)
x = fc6(x)
x.copy_to_ptr((void*)data_to_user.data());
}}
'''
print(genetator.network_defination(inference_code, 'work_space/new_net'))
|
[
"[email protected]"
] | |
e9dfb0e3bcc9bd274fa48b51fe6060bd14ae10b0
|
a6281073aaddf903d13d903e01ef8f6597e0c366
|
/RPWR/lookup/urls.py
|
5e482fdb24bd35e8a3820306e06da0aa9fab213c
|
[] |
no_license
|
pronob1010/D152-Recipe-provider-with-Redis
|
9c92be028bef4260a26b876084fde6aa51662ea6
|
970b5f98da7e5e35de9fe8b9642d64e89daff809
|
refs/heads/main
| 2023-06-23T18:21:42.697646 | 2021-07-25T11:57:01 | 2021-07-25T11:57:01 | 389,307,045 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 161 |
py
|
from django.urls import path
from . views import *
urlpatterns = [
path('', index, name="index"),
path('details/<int:pk>', details, name="details" )
]
|
[
"[email protected]"
] | |
28ac291d1ae4422fbc31b029ac29566e60bb06d6
|
aa01560e68a07033d4b24c4770966771349e2b4f
|
/src/jobs/migrations/0006_auto_20201209_1527.py
|
6892aa2f3a57b13172292e19d88ab9cece02673e
|
[] |
no_license
|
fluffcoding/solitaireHR
|
a0a357e1b19b955caae8df11ca92188cad79e217
|
b97a29f9accc5b45cd62986b62673a6ba802771b
|
refs/heads/main
| 2023-04-05T11:46:41.855323 | 2021-04-26T04:57:27 | 2021-04-26T04:57:27 | 322,067,817 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 933 |
py
|
# Generated by Django 3.1.2 on 2020-12-09 15:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0005_jobapplication'),
]
operations = [
migrations.AddField(
model_name='jobapplication',
name='applied',
field=models.BooleanField(blank=True, default=True, null=True),
),
migrations.AddField(
model_name='jobapplication',
name='interviewed',
field=models.BooleanField(blank=True, null=True),
),
migrations.AddField(
model_name='jobapplication',
name='selected',
field=models.BooleanField(blank=True, null=True),
),
migrations.AddField(
model_name='jobapplication',
name='shortlisted',
field=models.BooleanField(blank=True, null=True),
),
]
|
[
"[email protected]"
] | |
0d04bd3854dda5ce09a0ee3aa7f1f60626f35220
|
0d5e4ad0a693492204aa6210c2de470b26732509
|
/commands/eztv_mininova.py
|
f03143d557ebdcff904fff885f927ad0d6d242bd
|
[] |
no_license
|
enlavin/tvscrap
|
7d4ffe16a5af9f1747c021a0cc6bd187a5b0c91e
|
28d9baf1a2b2db4321b59747e85f1302f92f3a98
|
refs/heads/master
| 2020-04-29T10:20:45.150974 | 2015-04-26T18:11:26 | 2015-04-26T18:11:26 | 18,444,784 | 1 | 1 | null | 2015-04-28T20:24:58 | 2014-04-04T16:18:24 |
Python
|
UTF-8
|
Python
| false | false | 2,225 |
py
|
# -*- coding: utf-8 -*-
# GNU General Public Licence (GPL)
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA
try:
import feedparser
except ImportError:
print "feedparser support not installed. Try easy_install feedparser."
import sys
sys.exit(1)
import re
from optparse import OptionParser
from db import Show, Episode
from lib.feed_command import FeedCommand
EZTV_MININOVA_RSS="http://www.mininova.org/rss.xml?user=eztv"
class Command(FeedCommand):
def __init__(self, store):
super(Command, self).__init__(store)
self.rx_episode_size = re.compile(u'Size:\s+([0-9.]+)')
def _config_feed(self):
import feedparser
if getattr(self.options, "file"):
self.feed = feedparser.parse(self.options.file)
elif getattr(self.options, "url"):
self.feed = feedparser.parse(self.options.url)
else:
self.feed = feedparser.parse(EZTV_MININOVA_RSS)
if not self.feed["entries"]:
raise Exception()
def _iter_feed(self):
for entry in self.feed["entries"]:
try:
size = float(self.rx_episode_size.findall(entry["summary"])[0])
except IndexError:
print "File size not available. Skipping"
continue
except TypeError:
print "File size field corrupt. Skipping"
continue
yield {
"name": entry["title"],
"size": size,
"url_torrent": [entry['enclosures'][0]["href"]],
}
|
[
"devnull@localhost"
] |
devnull@localhost
|
1a254cdc13044408437afdc922e0f764e45c5795
|
0e9fad9c000430a735e10568644dc3e0c6a1de54
|
/curriculum_ctvt/input_mistakes.py
|
f578c6927d70e2f14f213a7c2b373d114132797e
|
[] |
no_license
|
pedal-edu/curriculum-ctvt
|
54d489926f366b486a3e5663de444221a5924f92
|
2f8472627b9adceb90466f206f1131fdecc3a2e5
|
refs/heads/master
| 2023-04-01T20:17:58.542300 | 2021-03-25T13:54:51 | 2021-03-25T13:54:51 | 276,709,305 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 671 |
py
|
from pedal.core.commands import gently, explain
from pedal.cait.cait_api import *
def unnecessary_cast(needed_casts):
"""
Args:
needed_casts: List of casts that are necessary to this problem
Returns:
"""
message = "Converting to {} is unnecessary in this problem"
code = "ex_cast"
tldr = "Unnecessary Conversion"
known_casts = ["float", "int", "str"]
matches = find_matches("_cast_(___)")
for match in matches:
user_cast = match["_cast_"].id
if user_cast not in needed_casts and user_cast in known_casts:
return explain(message.format(user_cast), label=code, title=tldr)
return False
|
[
"[email protected]"
] | |
1c459705148d5b935a6f2166345b8b6e897b9b97
|
763774bbcd6aa6adf64bde5fbe9521a937785362
|
/tests/test_concise_keras.py
|
6203e9afeee825596836ae6f6bce515552396ef0
|
[
"MIT"
] |
permissive
|
morphinggen/concise
|
969075dfbed99071fae53b0cba637bb5c25e3359
|
12078d75f37fe176bb7d221134b8b14aeb48e11f
|
refs/heads/master
| 2022-04-28T03:11:08.606943 | 2020-04-15T19:19:34 | 2020-04-15T19:19:34 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,079 |
py
|
"""
test_concise_keras
----------------------------------
Tests for `concise_keras` module
"""
import keras
from keras.models import model_from_json
from concise.legacy.models import single_layer_pos_effect as concise_model
from concise.eval_metrics import mse
from sklearn.linear_model import LinearRegression
import pytest
from tests.setup_concise_load_data import load_example_data
import numpy as np
def test_serialization():
c = concise_model(init_motifs=["TAATA", "TGCGAT"],
pooling_layer="sum",
n_splines=10,
)
js = c.to_json()
assert isinstance(model_from_json(js), keras.models.Model)
def test_serialization_disk(tmpdir):
param, X_feat, X_seq, y, id_vec = load_example_data()
dc = concise_model(pooling_layer="sum",
init_motifs=["TGCGAT", "TATTTAT"],
n_splines=10,
n_covariates=X_feat.shape[1],
seq_length=X_seq.shape[1],
**param)
dc.fit([X_seq, X_feat], y, epochs=1,
validation_data=([X_seq, X_feat], y))
fn = tmpdir.mkdir('data').join('test_keras.h5')
dc.save(str(fn))
dc = keras.models.load_model(str(fn))
assert isinstance(dc, keras.models.Model)
class TestKerasConciseBasic(object):
@classmethod
def setup_class(cls):
cls.data = load_example_data()
# pass
def test_no_error(self):
# test the nice print:
param, X_feat, X_seq, y, id_vec = self.data
dc = concise_model(pooling_layer="max",
n_covariates=X_feat.shape[1],
seq_length=X_seq.shape[1],
**param)
dc.fit([X_seq, X_feat], y, epochs=1,
validation_data=([X_seq, X_feat], y))
y_pred = dc.predict([X_seq, X_feat])
y_pred
def test_train_predict_no_X_feat(self):
# test the nice print:
param, X_feat, X_seq, y, id_vec = self.data
dc = concise_model(pooling_layer="max",
n_covariates=0,
seq_length=X_seq.shape[1],
**param)
dc.fit(X_seq, y, epochs=1,
validation_data=(X_seq, y))
y_pred = dc.predict(X_seq)
y_pred
@classmethod
def teardown_class(cls):
pass
class TestMultiTaskLearning(TestKerasConciseBasic):
"""
Test multi-task learning
"""
@classmethod
def setup_class(cls):
cls.data = load_example_data(num_tasks=3)
class TestConcisePrediction(object):
@classmethod
def setup_class(cls):
cls.data = load_example_data(trim_seq_len=1, standardize_features=False)
cls.data[0]["n_motifs"] = 1
cls.data[0]["motif_length"] = 1
cls.data[0]["step_size"] = 0.001
cls.data[0]["early_stop_patience"] = 3
def test_non_std(self):
# test the nice print:
param, X_feat, X_seq, y, id_vec = self.data
dc = concise_model(pooling_layer="max",
n_covariates=X_feat.shape[1],
lambd=0,
seq_length=X_seq.shape[1],
**param)
callback = keras.callbacks.EarlyStopping(patience=param["early_stop_patience"])
dc.fit([X_seq, X_feat], y, epochs=50,
callbacks=[callback],
validation_data=([X_seq, X_feat], y))
dc_coef = dc.layers[-1].get_weights()[0][-X_feat.shape[1]:, 0]
lm = LinearRegression()
lm.fit(X_feat, y)
# np.allclose(lm.coef_, dc_coef, atol=0.02)
# # weights has to be the same as for linear regression
# (dc_coef - lm.coef_) / lm.coef_
# they both have to predict the same
y_pred = dc.predict([X_seq, X_feat])
mse_lm = mse(y, lm.predict(X_feat))
mse_dc = mse(y, y_pred)
print("mse_lm")
print(mse_lm)
print("mse_dc")
print(mse_dc)
assert mse_dc < mse_lm + 0.01
|
[
"[email protected]"
] | |
9a5ec1a187e75627e6dcb81ca8146aa919e1183d
|
69b4f343861f6fb366c8fbbe590376a1bdd0c658
|
/Tests.py
|
055c802f1a0a921b5024e5e83d059629edfe7772
|
[] |
no_license
|
freQuensy23-coder/CaptchServiceAPI
|
81f8a705193b07892f65cdc05b84a8ac6961b286
|
85a8b3585a4c6e6b98ae5c11375567b9d4b4dbfa
|
refs/heads/main
| 2023-03-13T14:43:45.044766 | 2021-03-02T19:03:22 | 2021-03-02T19:03:22 | 341,452,481 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 537 |
py
|
import unittest
from generator import generate_font_image, generate_random_word, do_image_dim
from PIL import Image
class Tester(unittest.TestCase):
def setUp(self) -> None:
pass
def test_get_font(self):
# TODO
for i in range(5555):
generate_font_image()
def test_generate_random_word(self):
for i in range(50):
print(str(generate_random_word()))
def test_do_image_dim(self):
im = Image.open("background.jpg")
do_image_dim(im, force=4096).show()
|
[
"[email protected]"
] | |
6c2e15fe001ee7f4ada3747278a504be5e557b84
|
f4b79529109fbb4055f334d0d9c7c96cb0710447
|
/colour/examples/colorimetry/examples_photometry.py
|
1a933c8490479fed65be2c0deaf6b89803b4c56e
|
[
"BSD-3-Clause"
] |
permissive
|
trevorandersen/colour
|
167381b3d03e506a270a8d2a519a164808995437
|
02b595b26313c4b4f55adc41d599f90c4c9edbcd
|
refs/heads/develop
| 2021-07-15T04:48:19.585586 | 2021-01-23T23:51:44 | 2021-01-23T23:51:44 | 230,421,054 | 0 | 0 |
BSD-3-Clause
| 2019-12-28T12:54:20 | 2019-12-27T10:10:30 | null |
UTF-8
|
Python
| false | false | 858 |
py
|
# -*- coding: utf-8 -*-
"""
Showcases *Photometry* computations.
"""
import colour
from colour.utilities import message_box
message_box('"Photometry" Computations')
sd_light_source = colour.SDS_LIGHT_SOURCES['Neodimium Incandescent']
message_box(('Computing "Luminous Flux" for given spectral '
'distribution:\n'
'\n\t{0}'.format(sd_light_source.name)))
print(colour.luminous_flux(sd_light_source))
print('\n')
message_box(('Computing "Luminous Efficiency" for given spectral '
'distribution:\n'
'\n\t{0}'.format(sd_light_source.name)))
print(colour.luminous_efficiency(sd_light_source))
print('\n')
message_box(('Computing "Luminous Efficacy" for given spectral '
'distribution:\n'
'\n\t{0}'.format(sd_light_source.name)))
print(colour.luminous_efficacy(sd_light_source))
|
[
"[email protected]"
] | |
395fa81b18711e219bc6cd2cb0dbbacfb2042d17
|
6230dd7501bb504643cb3b8d8d18889f4bc9e292
|
/web_frameworks/web_frameworks/settings.py
|
bbbc17a5d7ddd4c0c58cd449416a3ff2c7e94384
|
[
"MIT"
] |
permissive
|
Minkov/python-web-frameworks-2020-11
|
f83a8560cbbcd06549bcacaca83de3af4824adc6
|
5857bb626792a9efe1f2d06677fa3779f5e2cc1d
|
refs/heads/main
| 2023-01-21T07:02:46.141981 | 2020-12-01T18:30:20 | 2020-12-01T18:30:20 | 310,352,954 | 4 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,445 |
py
|
"""
Django settings for web_frameworks project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from os.path import join
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '73l^kfu(th-t&nk219%xvlg&29*5khenic!ji$(s-3r5-tc!ww'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'templates_advanced',
'resources',
'cbv',
'books',
'books_api',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'web_frameworks.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates']
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'web_frameworks.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
}
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATICFILES_DIRS = (
join(BASE_DIR, 'static'),
)
STATIC_ROOT = '/tmp/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = join(BASE_DIR, 'media')
|
[
"[email protected]"
] | |
12dff4722892f3042a30723dc845bff0321cbf83
|
c6f47e7e96c5a9f7f0f24026dffe60fbf5bb034d
|
/notebooks/pendigits/pendigits_dmkde_adp.py
|
5a1d32c2b06c4dcb647eb5bb198c15006267ab63
|
[] |
no_license
|
Joaggi/anomaly-detection-density-matrix-kernel-density-estimation
|
762b2a944cef2ea06172834e6f445f02a52a7f89
|
34c3eb16fde9f2aad4daaaf233947c362b0f5416
|
refs/heads/master
| 2023-04-08T06:53:16.742624 | 2022-11-09T21:39:50 | 2022-11-09T21:39:50 | 425,664,863 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,359 |
py
|
current_path = ""
try:
import google.colab
IN_COLAB = True
except:
IN_COLAB = False
if IN_COLAB:
import os
import sys
sys.path.append('submodules/qmc/')
#sys.path.append('../../../../submodules/qmc/')
print(sys.path)
else:
import sys
sys.path.append('submodules/qmc/')
sys.path.append('data/')
#sys.path.append('../../../../submodules/qmc/')
print(sys.path)
# %cd ../../
print(os.getcwd())
sys.path.append('scripts/')
import qmc.tf.layers as layers
import qmc.tf.models as models
import tensorflow as tf
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from experiments import experiments
from mlflow_create_experiment import mlflow_create_experiment
setting = {
"z_name_of_experiment": 'dmkde_adp-pendigits',
"z_run_name": "dmkde_adp",
"z_dataset": "pendigits",
"z_rff_components": 1000,
"z_num_samples": 10000,
"z_batch_size": 16,
"z_select_best_experiment": True,
"z_threshold": 0.0
}
prod_settings = {"z_gamma": [2**i for i in range(-9,6)]}
params_int = ["z_rff_components", "z_batch_size", "z_num_samples"]
params_float = ["z_gamma", "z_threshold"]
mlflow = mlflow_create_experiment(setting["z_name_of_experiment"])
experiments(setting, prod_settings, params_int, params_float, mlflow)
|
[
"[email protected]"
] | |
9867fe19d328e3fb7a896205afc9498f7e784422
|
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
|
/Z8REdTE5P57f4q7dK_20.py
|
02025f57265a048945b02e93032e46722f6d5199
|
[] |
no_license
|
daniel-reich/ubiquitous-fiesta
|
26e80f0082f8589e51d359ce7953117a3da7d38c
|
9af2700dbe59284f5697e612491499841a6c126f
|
refs/heads/master
| 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 148 |
py
|
def collatz(n, r=[]):
if not r: r = [n]
if n == 1: return (len(r), max(*r))
n = n * 3 + 1 if n & 1 else n // 2
return collatz(n, r + [n])
|
[
"[email protected]"
] | |
d8d7c2533a436b336dde94b74fadb5d8c040b775
|
d05c946e345baa67e7894ee33ca21e24b8d26028
|
/general/data-cleaning-pandas/data_cleaning.py
|
7e03b3efd348f785821adfca186f950771cfa799
|
[
"MIT"
] |
permissive
|
x4nth055/pythoncode-tutorials
|
327255550812f84149841d56f2d13eaa84efd42e
|
d6ba5d672f7060ba88384db5910efab1768c7230
|
refs/heads/master
| 2023-09-01T02:36:58.442748 | 2023-08-19T14:04:34 | 2023-08-19T14:04:34 | 199,449,624 | 1,858 | 2,055 |
MIT
| 2023-08-25T20:41:56 | 2019-07-29T12:35:40 |
Jupyter Notebook
|
UTF-8
|
Python
| false | false | 202 |
py
|
import pandas as pd
# Config settings
pd.set_option('max_columns', None)
pd.set_option('max_rows', 12)
# Import CSV data
data_frames = pd.read_csv (r'simulated_data.csv')
print(data_frames.head(10))
|
[
"[email protected]"
] | |
19336d3be69f6065ae890b7c90e28de999166652
|
564fe9c8409d9ff4ba5f88dd36c0743d417767fa
|
/opsgenie_swagger/models/contact.py
|
8a11eaff8b7fc6180a2fc9809ec2522e53d44ade
|
[
"Apache-2.0"
] |
permissive
|
criteo-forks/opsgenie-python-sdk
|
28cf4b2e5eb5f10df582cfd6393a0e952dee5102
|
2a3924a0bd779eab47937925eb5d42ffbbd751d4
|
refs/heads/master
| 2020-04-05T23:09:41.002143 | 2019-04-12T13:37:22 | 2019-04-12T13:37:22 | 65,009,459 | 0 | 2 | null | 2016-08-05T10:08:55 | 2016-08-05T10:08:55 | null |
UTF-8
|
Python
| false | false | 4,584 |
py
|
# coding: utf-8
"""
OpsGenie REST API
OpsGenie OpenAPI Specification # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from opsgenie_swagger.models.contact_status import ContactStatus # noqa: F401,E501
class Contact(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 = {
'id': 'str',
'method': 'str',
'to': 'str',
'status': 'ContactStatus'
}
attribute_map = {
'id': 'id',
'method': 'method',
'to': 'to',
'status': 'status'
}
def __init__(self, id=None, method=None, to=None, status=None): # noqa: E501
"""Contact - a model defined in Swagger""" # noqa: E501
self._id = None
self._method = None
self._to = None
self._status = None
self.discriminator = None
if id is not None:
self.id = id
if method is not None:
self.method = method
if to is not None:
self.to = to
if status is not None:
self.status = status
@property
def id(self):
"""Gets the id of this Contact. # noqa: E501
:return: The id of this Contact. # noqa: E501
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this Contact.
:param id: The id of this Contact. # noqa: E501
:type: str
"""
self._id = id
@property
def method(self):
"""Gets the method of this Contact. # noqa: E501
:return: The method of this Contact. # noqa: E501
:rtype: str
"""
return self._method
@method.setter
def method(self, method):
"""Sets the method of this Contact.
:param method: The method of this Contact. # noqa: E501
:type: str
"""
self._method = method
@property
def to(self):
"""Gets the to of this Contact. # noqa: E501
:return: The to of this Contact. # noqa: E501
:rtype: str
"""
return self._to
@to.setter
def to(self, to):
"""Sets the to of this Contact.
:param to: The to of this Contact. # noqa: E501
:type: str
"""
self._to = to
@property
def status(self):
"""Gets the status of this Contact. # noqa: E501
:return: The status of this Contact. # noqa: E501
:rtype: ContactStatus
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this Contact.
:param status: The status of this Contact. # noqa: E501
:type: ContactStatus
"""
self._status = status
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, Contact):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"[email protected]"
] | |
f81fa202ac030ed1854e85d1d468bada85820ad5
|
4d9e7425ea6902a45eeda81c5cd5ede7d44fd087
|
/examples/starwars/tests/test_connections.py
|
d266df33d782e73fb8019b1abe3fbbc0aa505e77
|
[
"MIT"
] |
permissive
|
Salalem/graphene-neo4j
|
2258b29093337fd8981b880065b144dc4e6c145b
|
f2b99fa18b7367cf3a581d1f4a71fda16a1320fc
|
refs/heads/master
| 2023-08-08T06:57:41.749557 | 2019-06-14T16:22:14 | 2019-06-14T16:22:14 | 222,071,239 | 1 | 1 |
MIT
| 2023-07-22T21:45:41 | 2019-11-16T08:45:32 | null |
UTF-8
|
Python
| false | false | 1,441 |
py
|
import pytest
from ..data import initialize
from ..schema import schema
pytestmark = pytest.mark.django_db
def test_correct_fetch_first_ship_rebels():
initialize()
query = '''
query RebelsShipsQuery {
rebels {
name,
hero {
name
}
ships(first: 1) {
edges {
node {
name
}
}
}
}
}
'''
expected = {
'rebels': {
'name': 'Alliance to Restore the Republic',
'hero': {
'name': 'Human'
},
'ships': {
'edges': [
{
'node': {
'name': 'X-Wing'
}
}
]
}
}
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
def test_correct_list_characters():
initialize()
query = '''
query RebelsShipsQuery {
node(id: "U2hpcDox") {
... on Ship {
name
characters {
name
}
}
}
}
'''
expected = {
'node': {
'name': 'X-Wing',
'characters': [{
'name': 'Human'
}],
}
}
result = schema.execute(query)
assert not result.errors
assert result.data == expected
|
[
"[email protected]"
] | |
50aa838108041994970b4a245b95fa893a34737f
|
66dd570bf5945dcbd183ed3c0cf897c0359cbccd
|
/python/python语法/pyexercise/Exercise05_09.py
|
e942db9fe0e15a945d4dac56ce26d7e5c0745b7a
|
[] |
no_license
|
SamJ2018/LeetCode
|
302cc97626220521c8847d30b99858e63fa509f3
|
784bd0b1491050bbd80f5a0e2420467b63152d8f
|
refs/heads/master
| 2021-06-19T10:30:37.381542 | 2021-02-06T16:15:01 | 2021-02-06T16:15:01 | 178,962,481 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 279 |
py
|
tuition = 10000
count = 1
while count <= 10:
tuition = tuition * 1.05;
count += 1
print("Tuition in ten years is", tuition)
sum = tuition
for i in range(2, 5):
tuition = tuition * 1.05
sum += tuition
print("The four-year tuition in ten years is", sum)
|
[
"[email protected]"
] | |
017d0a8ffb2b9b577b8ef976168c48995c63e689
|
6df76f8a6fcdf444c3863e3788a2f4b2c539c22c
|
/django code/p105/p105/settings.py
|
a76b29db32f2d0ab4cdf3fc1733f20e72b6b2894
|
[] |
no_license
|
basantbhandari/DjangoProjectsAsDocs
|
068e4a704fade4a97e6c40353edb0a4299bd9678
|
594dbb560391eaf94bb6db6dc07702d127010b88
|
refs/heads/master
| 2022-12-18T22:33:23.902228 | 2020-09-22T13:11:01 | 2020-09-22T13:11:01 | 297,651,728 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,134 |
py
|
"""
Django settings for p105 project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*o3o*nsr8m66()euw(-%s1%0(y@(a$-bypjgao_uqbn1q=elc!'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#userapp
'myapp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'p105.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'p105.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME':
'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
|
[
"[email protected]"
] | |
ccd9a13878867c64b046d0c2430669e314344e6b
|
259cc507d97bfeff84d21de3a0ab56640676a9eb
|
/venv1/Lib/site-packages/tensorflow/contrib/sparsemax/python/ops/sparsemax.py
|
ab6bdcb499055455ea400a70cb2c8dbe89ad712d
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
Soum-Soum/Tensorflow_Face_Finder
|
c3ef71b6f718f6720b80f8760d28b6ca6e11e6d2
|
fec6c15d2df7012608511ad87f4b55731bf99478
|
refs/heads/master
| 2020-03-22T20:31:39.606644 | 2018-07-12T13:47:56 | 2018-07-12T13:47:56 | 140,607,068 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,667 |
py
|
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Sparsemax op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
__all__ = ["sparsemax"]
def sparsemax(logits, name=None):
"""Computes sparsemax activations [1].
For each batch `i` and class `j` we have
sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)
[1]: https://arxiv.org/abs/1602.02068
Args:
logits: A `Tensor`. Must be one of the following types: `half`, `float32`,
`float64`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `logits`.
"""
with ops.name_scope(name, "sparsemax", [logits]) as name:
logits = ops.convert_to_tensor(logits, name="logits")
obs = array_ops.shape(logits)[0]
dims = array_ops.shape(logits)[1]
z = logits - math_ops.reduce_mean(logits, axis=1)[:, array_ops.newaxis]
# sort z
z_sorted, _ = nn.top_k(z, k=dims)
# calculate k(z)
z_cumsum = math_ops.cumsum(z_sorted, axis=1)
k = math_ops.range(
1, math_ops.cast(dims, logits.dtype) + 1, dtype=logits.dtype)
z_check = 1 + k * z_sorted > z_cumsum
# because the z_check vector is always [1,1,...1,0,0,...0] finding the
# (index + 1) of the last `1` is the same as just summing the number of 1.
k_z = math_ops.reduce_sum(math_ops.cast(z_check, dtypes.int32), axis=1)
# calculate tau(z)
indices = array_ops.stack([math_ops.range(0, obs), k_z - 1], axis=1)
tau_sum = array_ops.gather_nd(z_cumsum, indices)
tau_z = (tau_sum - 1) / math_ops.cast(k_z, logits.dtype)
# calculate p
return math_ops.maximum(
math_ops.cast(0, logits.dtype), z - tau_z[:, array_ops.newaxis])
|
[
"[email protected]"
] | |
c883e1a0a408db687bff3e281fefff765a1d8a66
|
c6ec292a52ea54499a35a7ec7bc042a9fd56b1aa
|
/Python/1102.py
|
2cae0a34d41306787e668057e921d884cf86347d
|
[] |
no_license
|
arnabs542/Leetcode-38
|
ad585353d569d863613e90edb82ea80097e9ca6c
|
b75b06fa1551f5e4d8a559ef64e1ac29db79c083
|
refs/heads/master
| 2023-02-01T01:18:45.851097 | 2020-12-19T03:46:26 | 2020-12-19T03:46:26 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 804 |
py
|
class Solution:
def maximumMinimumPath(self, A: List[List[int]]) -> int:
if not A or not A[0]:
return 0
m, n = len(A), len(A[0])
visited = [[False] * n for _ in range(m)]
mi = A[0][0]
heap = [(-mi, 0, 0)]
dx = [1, -1, 0, 0]
dy = [0, 0, -1, 1]
while heap:
curMin, x, y = heapq.heappop(heap)
if x == m - 1 and y == n - 1:
return -curMin
for i in range(4):
nx, ny = dx[i] + x, dy[i] + y
if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny]:
visited[nx][ny] = True
newMin = min(-curMin, A[nx][ny])
heapq.heappush(heap, (-newMin, nx, ny))
return -1
|
[
"[email protected]"
] | |
77acc0d3cf53b10d4d349208c468bc9079016a6e
|
045cb1a5638c3575296f83471758dc09a8065725
|
/addons/sale_coupon/wizard/__init__.py
|
635af11d6b33d4b83895e11bf4abe859856175f1
|
[] |
no_license
|
marionumza/saas
|
7236842b0db98d1a0d0c3c88df32d268509629cb
|
148dd95d991a348ebbaff9396759a7dd1fe6e101
|
refs/heads/main
| 2023-03-27T14:08:57.121601 | 2021-03-20T07:59:08 | 2021-03-20T07:59:08 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 175 |
py
|
# -*- coding: utf-8 -*-
# Part of Harpiya. See LICENSE file for full copyright and licensing details.
from . import sale_coupon_apply_code
from . import sale_coupon_generate
|
[
"[email protected]"
] | |
efefb440146c23d804a17792e39d091c1a94ae26
|
06476bc4cb7fc3ce378beb357fac7d5aacb87b3b
|
/Prototype/env/lib/python3.8/site-packages/Xlib/xobject/icccm.py
|
a328925ed9e58bccae33040d004ca1fabba4d98d
|
[
"MIT"
] |
permissive
|
marc-ortuno/VOPEC
|
44d3a74d3e0686474dd57fcb21e845fd5fd48897
|
e7ed1f13cc1868a824f4036dd08ec6bed4266c08
|
refs/heads/main
| 2023-06-12T19:15:18.060897 | 2021-07-01T17:15:03 | 2021-07-01T17:15:03 | 344,433,646 | 0 | 0 |
MIT
| 2021-06-14T19:15:47 | 2021-03-04T10:22:05 |
Python
|
UTF-8
|
Python
| false | false | 3,441 |
py
|
# Xlib.xobject.icccm -- ICCCM structures
#
# Copyright (C) 2000 Peter Liljenberg <[email protected]>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc.,
# 59 Temple Place,
# Suite 330,
# Boston, MA 02111-1307 USA
from Xlib import X, Xutil
from Xlib.protocol import rq
Aspect = rq.Struct( rq.Int32('num'), rq.Int32('denum') )
WMNormalHints = rq.Struct( rq.Card32('flags'),
rq.Pad(16),
rq.Int32('min_width', default = 0),
rq.Int32('min_height', default = 0),
rq.Int32('max_width', default = 0),
rq.Int32('max_height', default = 0),
rq.Int32('width_inc', default = 0),
rq.Int32('height_inc', default = 0),
rq.Object('min_aspect', Aspect, default = (0, 0)),
rq.Object('max_aspect', Aspect, default = (0, 0)),
rq.Int32('base_width', default = 0),
rq.Int32('base_height', default = 0),
rq.Int32('win_gravity', default = 0),
)
WMHints = rq.Struct( rq.Card32('flags'),
rq.Card32('input', default = 0),
rq.Set('initial_state', 4,
# withdrawn is totally bogus according to
# ICCCM, but some window managers seem to
# use this value to identify dockapps.
# Oh well.
( Xutil.WithdrawnState,
Xutil.NormalState,
Xutil.IconicState ),
default = Xutil.NormalState),
rq.Pixmap('icon_pixmap', default = 0),
rq.Window('icon_window', default = 0),
rq.Int32('icon_x', default = 0),
rq.Int32('icon_y', default = 0),
rq.Pixmap('icon_mask', default = 0),
rq.Window('window_group', default = 0),
)
WMState = rq.Struct( rq.Set('state', 4,
( Xutil.WithdrawnState,
Xutil.NormalState,
Xutil.IconicState )),
rq.Window('icon', ( X.NONE, )),
)
WMIconSize = rq.Struct( rq.Card32('min_width'),
rq.Card32('min_height'),
rq.Card32('max_width'),
rq.Card32('max_height'),
rq.Card32('width_inc'),
rq.Card32('height_inc'),
)
|
[
"[email protected]"
] | |
a1ad11fe81cbafd2634f7e88da34d940617525ed
|
0728a2e165808cfe5651693a6e7f47804bfb085f
|
/get/2013/site/getmyad/tests/functional/test_private.py
|
bb8b9931e924edaa1d8c9b4539e9f53d599872dc
|
[] |
no_license
|
testTemtProj/OLD_PROJECT
|
5b026e072017f5135159b0940370fda860241d39
|
9e5b165f4e8acf9003536e05dcefd33a5ae46890
|
refs/heads/master
| 2020-05-18T15:30:24.543319 | 2013-07-23T15:17:32 | 2013-07-23T15:17:32 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 203 |
py
|
from getmyad.tests import *
class TestPrivateController(TestController):
def test_index(self):
response = self.app.get(url(controller='private', action='index'))
# Test response...
|
[
"[email protected]"
] | |
bb0ce9645fde1dd12f1cdcbc2c425aca062c074a
|
981fcfe446a0289752790fd0c5be24020cbaee07
|
/python2_Grammer/src/basic/zhengze/rool/字符集和数量/字符集/5_单个字符.py
|
a5c6ad067a51536c1c61d9cec1f9965226efcb1d
|
[] |
no_license
|
lijianbo0130/My_Python
|
7ba45a631049f6defec3977e680cd9bd75d138d1
|
8bd7548c97d2e6d2982070e949f1433232db9e07
|
refs/heads/master
| 2020-12-24T18:42:19.103529 | 2016-05-30T03:03:34 | 2016-05-30T03:03:34 | 58,097,799 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 331 |
py
|
#coding=utf-8
'''
Created on 2015年8月4日
@author: Administrator
'''
from __future__ import division
import sys
reload(sys)
sys.setdefaultencoding('utf-8') # @UndefinedVariable
import re
# 单个字母 \w [A-Za-z0-9_] 包含 '_'
# 非单词字符 \W
lis=re.findall("\w", "_ppa")#\w 包含_
print lis # ['_', 'p', 'p', 'a']
|
[
"[email protected]"
] | |
f42bc817dcd318885005c9843c46c7c2fbb6a3a8
|
83934c40b2bd835464732345fa516b2c657a6259
|
/Pyrado/scripts/training/qq-su_bayrn_power_sim2sim.py
|
bb7f330fbe57985f6ca1ae10001237a0591dbaea
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
1abner1/SimuRLacra
|
e0427bf4f2459dcb992206d3b2f347beab68a5b4
|
d7e9cd191ccb318d5f1e580babc2fc38b5b3675a
|
refs/heads/master
| 2023-05-25T04:52:17.917649 | 2021-06-07T07:26:44 | 2021-06-07T07:26:44 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,840 |
py
|
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH,
# or Technical University of Darmstadt, nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH,
# OR TECHNICAL UNIVERSITY OF DARMSTADT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""
Train an agent to solve the Qube swing-up task using Bayesian Domain Randomization.
"""
import numpy as np
import pyrado
from pyrado.algorithms.episodic.power import PoWER
from pyrado.algorithms.meta.bayrn import BayRn
from pyrado.domain_randomization.default_randomizers import (
create_default_domain_param_map_qq,
create_zero_var_randomizer,
)
from pyrado.domain_randomization.utils import wrap_like_other_env
from pyrado.environment_wrappers.domain_randomization import DomainRandWrapperLive, MetaDomainRandWrapper
from pyrado.environments.pysim.quanser_qube import QQubeSwingUpSim
from pyrado.logger.experiment import save_dicts_to_yaml, setup_experiment
from pyrado.policies.special.environment_specific import QQubeSwingUpAndBalanceCtrl
from pyrado.spaces import BoxSpace
from pyrado.utils.argparser import get_argparser
if __name__ == "__main__":
# Parse command line arguments
args = get_argparser().parse_args()
# Experiment (set seed before creating the modules)
ex_dir = setup_experiment(
QQubeSwingUpSim.name,
f"{BayRn.name}-{PoWER.name}_{QQubeSwingUpAndBalanceCtrl.name}",
f"sim2sim_rand-Mp-Mr_seed-{args.seed}",
)
# Set seed if desired
pyrado.set_seed(args.seed, verbose=True)
# Environments
env_sim_hparams = dict(dt=1 / 100.0, max_steps=600)
env_sim = QQubeSwingUpSim(**env_sim_hparams)
env_sim = DomainRandWrapperLive(env_sim, create_zero_var_randomizer(env_sim))
dp_map = create_default_domain_param_map_qq()
env_sim = MetaDomainRandWrapper(env_sim, dp_map)
env_real = QQubeSwingUpSim(**env_sim_hparams)
env_real.domain_param = dict(
Mp=0.024 * 1.1,
Mr=0.095 * 1.1,
)
env_real_hparams = env_sim_hparams
env_real = wrap_like_other_env(env_real, env_sim)
# PoWER and energy-based controller setup
policy_hparam = dict(energy_gain=0.587, ref_energy=0.827, acc_max=10.0)
policy = QQubeSwingUpAndBalanceCtrl(env_sim.spec, **policy_hparam)
subrtn_hparam = dict(
max_iter=5,
pop_size=50,
num_init_states_per_domain=4,
num_domains=10,
num_is_samples=5,
expl_std_init=2.0,
expl_std_min=0.02,
symm_sampling=False,
num_workers=12,
)
subrtn = PoWER(ex_dir, env_sim, policy, **subrtn_hparam)
# PoWER and linear policy setup
# policy_hparam = dict(
# feats=FeatureStack(identity_feat, sign_feat, abs_feat, squared_feat,
# MultFeat((2, 5)), MultFeat((3, 5)), MultFeat((4, 5)))
# )
# policy = LinearPolicy(spec=env_sim.spec, **policy_hparam)
# subrtn_hparam = dict(
# max_iter=20,
# pop_size=200,
# num_init_states_per_domain=6,
# num_is_samples=10,
# expl_std_init=2.0,
# expl_std_min=0.02,
# symm_sampling=False,
# num_workers=32,
# )
# subrtn = PoWER(ex_dir, env_sim, policy, **subrtn_hparam)
# Set the boundaries for the GP
dp_nom = QQubeSwingUpSim.get_nominal_domain_param()
ddp_space = BoxSpace(
bound_lo=np.array([0.8 * dp_nom["Mp"], 1e-8, 0.8 * dp_nom["Mr"], 1e-8]),
bound_up=np.array([1.2 * dp_nom["Mp"], 1e-7, 1.2 * dp_nom["Mr"], 1e-7]),
)
# Algorithm
bayrn_hparam = dict(
max_iter=15,
acq_fc="UCB",
acq_param=dict(beta=0.25),
acq_restarts=500,
acq_samples=1000,
num_init_cand=4,
warmstart=False,
num_eval_rollouts_real=100,
thold_succ_subrtn=300,
)
# Save the environments and the hyper-parameters (do it before the init routine of BayRn)
save_dicts_to_yaml(
dict(env_sim=env_sim_hparams, env_real=env_real_hparams, seed=args.seed),
dict(policy=policy_hparam),
dict(subrtn=subrtn_hparam, subrtn_name=PoWER.name),
dict(algo=bayrn_hparam, algo_name=BayRn.name, dp_map=dp_map),
save_dir=ex_dir,
)
algo = BayRn(ex_dir, env_sim, env_real, subrtn, ddp_space, **bayrn_hparam)
# Jeeeha
algo.train(snapshot_mode="latest", seed=args.seed)
|
[
"[email protected]"
] | |
04f3348dcba79ceb132538619203da84de297413
|
ad13583673551857615498b9605d9dcab63bb2c3
|
/output/instances/nistData/atomic/byte/Schema+Instance/NISTXML-SV-IV-atomic-byte-maxExclusive-3-1.py
|
2e778fde1dbab8cd334f90bfc4b9a342ede77976
|
[
"MIT"
] |
permissive
|
tefra/xsdata-w3c-tests
|
397180205a735b06170aa188f1f39451d2089815
|
081d0908382a0e0b29c8ee9caca6f1c0e36dd6db
|
refs/heads/main
| 2023-08-03T04:25:37.841917 | 2023-07-29T17:10:13 | 2023-07-30T12:11:13 | 239,622,251 | 2 | 0 |
MIT
| 2023-07-25T14:19:04 | 2020-02-10T21:59:47 |
Python
|
UTF-8
|
Python
| false | false | 260 |
py
|
from output.models.nist_data.atomic.byte.schema_instance.nistschema_sv_iv_atomic_byte_max_exclusive_3_xsd.nistschema_sv_iv_atomic_byte_max_exclusive_3 import NistschemaSvIvAtomicByteMaxExclusive3
obj = NistschemaSvIvAtomicByteMaxExclusive3(
value=-128
)
|
[
"[email protected]"
] | |
849dc7bec027beb9388173ab0f4d7875af17de51
|
09c87fe780df6d1f9eb33799ed516a0bbd7ab1e3
|
/src/tests/python-in/testmodule_pynsource.py
|
735e0b98628d7ea19d2e62d5bcea3176a8213c7a
|
[] |
no_license
|
abulka/pynsource
|
8ad412b85dc1acaeb83d7d34af8cc033c6baba91
|
979436525c57fdaeaa832e960985e0406e123587
|
refs/heads/master
| 2023-04-13T12:58:02.911318 | 2023-04-11T09:56:32 | 2023-04-11T09:56:32 | 32,249,425 | 271 | 46 | null | 2022-10-10T04:36:57 | 2015-03-15T07:21:43 |
Python
|
UTF-8
|
Python
| false | false | 3,827 |
py
|
# pynsource command line tool
import os
# from core_parser import *
from generate_code.gen_asciiart import CmdLinePythonToAsciiArt
from generate_code.gen_yuml import CmdLinePythonToYuml
from generate_code.gen_delphi import CmdLinePythonToDelphi
from generate_code.gen_java import CmdLinePythonToJava
import messages
def test():
# FILE = "..\\tests\\python-in\\testmodule01.py"
FILE = "..\\tests\\python-in\\testmodule66.py"
# p = PySourceAsText()
p = PySourceAsYuml()
# p.optionModuleAsClass = True
p.Parse(FILE)
# print '*'*20, 'parsing', FILE, '*'*20
print(p)
# print 'Done.'
def ParseArgsAndRun():
import sys, glob
import getopt # good doco http://www.doughellmann.com/PyMOTW/getopt/
# should possibly upgrade to using http://docs.python.org/library/argparse.html#module-argparse
SIMPLE = 0
globbed = []
optionVerbose = 0
optionModuleAsClass = 0
optionExportToJava = 0
optionExportToDelphi = 0
optionExportToYuml = False
optionExportTo_outdir = ""
if SIMPLE:
params = sys.argv[1]
globbed = glob.glob(params)
else:
listofoptionvaluepairs, params = getopt.getopt(sys.argv[1:], "amvy:j:d:")
# print listofoptionvaluepairs, params
# print dict(listofoptionvaluepairs) # turn e.g. [('-v', ''), ('-y', 'fred.png')] into nicer? dict e.g. {'-v': '', '-y': 'fred.png'}
def EnsurePathExists(outdir, outlanguagemsg):
assert outdir, "Need to specify output folder for %s output - got %s." % (
outlanguagemsg,
outdir,
)
if not os.path.exists(outdir):
raise RuntimeError(
"Output directory %s for %s file output does not exist."
% (outdir, outlanguagemsg)
)
for optionvaluepair in listofoptionvaluepairs:
if "-a" == optionvaluepair[0]:
pass # default is asciart, so don't need to specify
if "-m" == optionvaluepair[0]:
optionModuleAsClass = 1
if "-v" == optionvaluepair[0]:
optionVerbose = 1
if optionvaluepair[0] in ("-j", "-d"):
if optionvaluepair[0] == "-j":
optionExportToJava = 1
language = "Java"
else:
optionExportToDelphi = 1
language = "Delphi"
optionExportTo_outdir = optionvaluepair[1]
EnsurePathExists(optionExportTo_outdir, language)
if optionvaluepair[0] in ("-y"):
optionExportToYuml = True
optionExportTo_outpng = optionvaluepair[1]
for param in params:
files = glob.glob(param)
globbed += files
if globbed:
if optionExportToJava or optionExportToDelphi:
if optionExportToJava:
u = CmdLinePythonToJava(
globbed, treatmoduleasclass=optionModuleAsClass, verbose=optionVerbose
)
else:
u = CmdLinePythonToDelphi(
globbed, treatmoduleasclass=optionModuleAsClass, verbose=optionVerbose
)
u.ExportTo(optionExportTo_outdir)
elif optionExportToYuml:
u = CmdLinePythonToYuml(
globbed, treatmoduleasclass=optionModuleAsClass, verbose=optionVerbose
)
u.ExportTo(optionExportTo_outpng)
else:
u = CmdLinePythonToAsciiArt(
globbed, treatmoduleasclass=optionModuleAsClass, verbose=optionVerbose
)
u.ExportTo(None)
else:
print(messages.HELP_COMMAND_LINE_USAGE)
if __name__ == "__main__":
# test()
# exit(0)
ParseArgsAndRun()
|
[
"[email protected]"
] | |
736177be6e62fa382ac47be5d33fbdc6148042ad
|
98c6ea9c884152e8340605a706efefbea6170be5
|
/examples/data/Assignment_1/brkluk001/question2.py
|
3b83362c9673632335a5e01fda0b228f12c0c017
|
[] |
no_license
|
MrHamdulay/csc3-capstone
|
479d659e1dcd28040e83ebd9e3374d0ccc0c6817
|
6f0fa0fa1555ceb1b0fb33f25e9694e68b6a53d2
|
refs/heads/master
| 2021-03-12T21:55:57.781339 | 2014-09-22T02:22:22 | 2014-09-22T02:22:22 | 22,372,174 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 336 |
py
|
validity = 'invalid.'
hours = eval(input('Enter the hours:\n'))
minutes = eval(input('Enter the minutes:\n'))
seconds = eval(input('Enter the seconds:\n'))
if 0 <= hours <= 23:
if 0 <= minutes <= 60:
if 0 <= seconds <= 60:
validity = 'valid.'
print('Your time is',validity)
|
[
"[email protected]"
] | |
d4d08f73436f51abbf9249999f8bd5b6dce1cb2a
|
ccf94dcb6b1500fcbbd56964ae8c4832a496b8b3
|
/python/baiduads-sdk-auto/test/test_add_campaign_feed_response_wrapper_body.py
|
2f27de5df0deda8130743c0c31f94739b41f8938
|
[
"Apache-2.0"
] |
permissive
|
baidu/baiduads-sdk
|
24c36b5cf3da9362ec5c8ecd417ff280421198ff
|
176363de5e8a4e98aaca039e4300703c3964c1c7
|
refs/heads/main
| 2023-06-08T15:40:24.787863 | 2023-05-20T03:40:51 | 2023-05-20T03:40:51 | 446,718,177 | 16 | 11 |
Apache-2.0
| 2023-06-02T05:19:40 | 2022-01-11T07:23:17 |
Python
|
UTF-8
|
Python
| false | false | 928 |
py
|
"""
dev2 api schema
'dev2.baidu.com' api schema # noqa: E501
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import baiduads
from baiduads.campaignfeed.model.campaign_feed_type import CampaignFeedType
globals()['CampaignFeedType'] = CampaignFeedType
from baiduads.campaignfeed.model.add_campaign_feed_response_wrapper_body import AddCampaignFeedResponseWrapperBody
class TestAddCampaignFeedResponseWrapperBody(unittest.TestCase):
"""AddCampaignFeedResponseWrapperBody unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testAddCampaignFeedResponseWrapperBody(self):
"""Test AddCampaignFeedResponseWrapperBody"""
# FIXME: construct object with mandatory attributes with example values
# model = AddCampaignFeedResponseWrapperBody() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
[
"[email protected]"
] | |
5e9f5edc1885013a836356ef125492c6de7d6b52
|
8ddda8fb6e5853126dcdafa3281c75071ada45c1
|
/vyperlogix/trees/BinarySearchTree/__init__.py
|
9e650390474f68b25b15dfda4a0d59db47884e97
|
[
"CC0-1.0"
] |
permissive
|
raychorn/chrome_gui
|
a48f3f9d931922a018e894f891ccd952476cd1ee
|
f1fade70b61af12ee43c55c075aa9cfd32caa962
|
refs/heads/master
| 2022-12-19T19:46:04.656032 | 2020-10-08T14:45:14 | 2020-10-08T14:45:14 | 299,167,534 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,463 |
py
|
__copyright__ = """\
(c). Copyright 2008-2020, Vyper Logix Corp., All Rights Reserved.
Published under Creative Commons License
(http://creativecommons.org/licenses/by-nc/3.0/)
restricted to non-commercial educational use only.,
http://www.VyperLogix.com for details
THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL,
INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
WITH THE USE OR PERFORMANCE OF THIS SOFTWARE !
USE AT YOUR OWN RISK.
"""
from vyperlogix.classes.CooperativeClass import Cooperative
class Node(Cooperative):
def __init__(self, lchild=None, rchild=None, value=-1, data=None):
self.lchild = lchild
self.rchild = rchild
self.value = value
self.data = data
class BinaryTree(Cooperative):
"""Implement Binary Search Tree."""
def __init__(self):
self.l = [] # Nodes
self.root = None
def add(self, key, dt):
"""Add a node in tree."""
if self.root == None:
self.root = Node(value=key, data=dt)
self.l.append(self.root)
return 0
else:
self.p = self.root
while True:
if self.p.value > key:
if self.p.lchild == None:
self.p.lchild = Node(value=key, data=dt)
return 0 # Success
else:
self.p = self.p.lchild
elif self.p.value == key:
return -1 # Value already in tree
else:
if self.p.rchild == None:
self.p.rchild = Node(value=key, data=dt)
return 0 # Success
else:
self.p = self.p.rchild
return -2 # Should never happen
def search(self, key):
"""Search Tree for a key and return data; if not found return None."""
self.p = self.root
if self.p == None:
return None
while True:
# print self.p.value, self.p.data
if self.p.value > key:
if self.p.lchild == None:
return None # Not found
else:
self.p = self.p.lchild
elif self.p.value == key:
return self.p.data
else:
if self.p.rchild == None:
return None # Not found
else:
self.p = self.p.rchild
return None # Should never happen
def deleteNode(self, key):
"""Delete node with value == key."""
if self.root.value == key:
if self.root.rchild == None:
if self.root.lchild == None:
self.root = None
else: self.root = self.root.lchild
else:
self.root.rchild.lchild = self.root.lchild
self.root = self.root.rchild
return 1
self.p = self.root
while True:
if self.p.value > key:
if self.p.lchild == None:
return 0 # Not found anything to delete
elif self.p.lchild.value == key:
self.p.lchild = self.proceed(self.p, self.p.lchild)
return 1
else:
self.p = self.p.lchild
# There's no way for self.p.value to be equal to key:
if self.p.value < key:
if self.p.rchild == None:
return 0 # Not found anything to delete
elif self.p.rchild.value == key:
self.p.rchild = self.proceed(self.p, self.p.rchild)
return 1
else:
self.p = self.p.rchild
return 0
def proceed(self, parent, delValue):
if delValue.lchild == None and delValue.rchild == None:
return None
elif delValue.rchild == None:
return delValue.lchild
else:
return delValue.rchild
def sort(self):
self.__traverse__(self.root, mode=1)
def __traverse__(self, v, mode=0):
"""Traverse in: preorder = 0, inorder = 1, postorder = 2."""
if v == None:
return
if mode == 0:
print (v.value, v.data)
self.__traverse__(v.lchild)
self.__traverse__(v.rchild)
elif mode == 1:
self.__traverse__(v.lchild, 1)
print (v.value, v.data)
self.__traverse__(v.rchild, 1)
else:
self.__traverse__(v.lchild, 2)
self.__traverse__(v.rchild, 2)
print (v.value, v.data)
if (__name__ == "__main__"):
import sys
print >>sys.stdout, __copyright__
print >>sys.stderr, __copyright__
tree = BinaryTree()
tree.add(4, "test1")
tree.add(10, "test2")
tree.add(23, "test3")
tree.add(1, "test4")
tree.add(3, "test5")
tree.add(2, "test6")
tree.sort()
print tree.search(3)
print tree.deleteNode(10)
print tree.deleteNode(23)
print tree.deleteNode(4)
print tree.search(3)
tree.sort()
|
[
"[email protected]"
] | |
47193ec756fca771cdefe437d9cfd48ad786e116
|
a9ac3c537fc778b34cb32d4528e2d1190e65e19e
|
/scripts/quantum_hall/plot_soi_vs_density.py
|
1d23715075d28101edc610eb3beca90b6a499c9b
|
[
"MIT"
] |
permissive
|
wms269/shabanipy
|
9f770cfdf113ca8e8af69cd793be2f8bf9b0141a
|
1e751631e031c528e18d5e0d8ff4fa1457f4107e
|
refs/heads/master
| 2022-09-23T15:43:43.875608 | 2020-04-09T17:49:24 | 2020-04-09T17:49:24 | 265,638,022 | 1 | 0 |
MIT
| 2020-05-20T17:25:40 | 2020-05-20T17:25:39 | null |
UTF-8
|
Python
| false | false | 2,360 |
py
|
# -*- coding: utf-8 -*-
"""Plot Rashba and mobility vs density from extracted parameters.
The csv file to read is expected to have been generated by
extract_soi_from_wal.py
"""
# =============================================================================
# --- Parameters --------------------------------------------------------------
# =============================================================================
#: Path to the csv fild holding the data
PATH = ('/Users/mdartiailh/Documents/PostDocNYU/DataAnalysis/WAL/JS124/'
'average_rashba_only/JS138_124HB_BM003_004_wal_analysis_avg.csv')
#: Density column
DENSITY_COLUMN = 'Density (m^-2)'
#: Mobility column
MOBILITY_COLUMN = 'Mobility (m^2V^-1s^-1)'
#: SOI column
SOI_COLUMN = 'Rashba SOI (meV.A)'
#: Densities to mark on the SOI plot (in 1e12 cm^-2)
DENSITIES = [1.3, 1.9, 3.8]
#: Number of points on which to average the SOI strength to compute stderr
STDERR_COMPUTATION = 3
# =============================================================================
# --- Execution ---------------------------------------------------------------
# =============================================================================
import os
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 14})
plt.rcParams.update({'pdf.fonttype': 42})
data = pd.read_csv(PATH, comment='#')
density = np.array(data[DENSITY_COLUMN][1:])
mobility = np.array(data[MOBILITY_COLUMN][1:])
rashba = np.array(data[SOI_COLUMN][1:])
density = np.mean(density.reshape((-1, STDERR_COMPUTATION)), axis=1)
mean_mob = np.mean(mobility.reshape((-1, STDERR_COMPUTATION)), axis=1)
std_mob = np.std(mobility.reshape((-1, STDERR_COMPUTATION)), axis=1)
mean_soi = np.mean(rashba.reshape((-1, STDERR_COMPUTATION)), axis=1)
std_soi = np.std(rashba.reshape((-1, STDERR_COMPUTATION)), axis=1)
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, constrained_layout=True, figsize=(15,4))
ax1.errorbar(density/1e4, mean_mob*1e4, std_mob*1e4, fmt='+', color='C2')
ax1.set_ylabel('Mobility (cm$^{-2}$V${^-1}$s$^{-1}$)')
ax1.set_xlabel('Density (cm$^{-2}$)')
ax2.errorbar(density/1e4, mean_soi, std_soi, fmt='+',)
ax2.set_ylabel('Rashba SOI (meV.A)')
ax2.set_xlabel('Density (cm$^{-2}$)')
for n in DENSITIES:
ax2.axvline(n*1e12, ymin=0.95, color='k')
plt.show()
|
[
"[email protected]"
] | |
9c32089e5865258988d73e8474c68a70f34955e7
|
068d271e241d8cdb46dbf4243166e4b8ee7025b2
|
/Django/进阶部分/day67课上代码两个项目哦/day67/mysite67/app01/urls.py
|
59ca711f596bdc197689aaf3513219e0abe2620d
|
[] |
no_license
|
caiqinxiong/python
|
f6e226e76cb62aac970bcfbcb6c8adfc64858b60
|
9029f6c528d2cb742b600af224e803baa74cbe6a
|
refs/heads/master
| 2023-05-26T19:41:34.911885 | 2020-05-15T09:02:08 | 2020-05-15T09:02:08 | 195,261,757 | 1 | 0 | null | 2021-06-10T23:33:33 | 2019-07-04T15:01:42 |
JavaScript
|
UTF-8
|
Python
| false | false | 338 |
py
|
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r'^home/', views.home, {"age": 18}, name="home"),
# 位置参数
url(r'^book/([0-9]{2,4})/([a-zA-Z]{2})/$', views.book, name="book"),
# 关键字参数
# url(r'^book/(?P<year>[0-9]{2,4})/(?P<title>[a-zA-Z]{2})/$', views.book, name="book")
]
|
[
"[email protected]"
] | |
28630e10caac44c62f98b0f86af906f33d97d559
|
b1f801f4f805467491c0b7c2db01c7806c10f4ea
|
/hockey/oilers.py
|
e86e659297f1c98fe3f825a975a73fb97d18d29d
|
[
"MIT"
] |
permissive
|
Obliviatum/Trusty-cogs
|
2fd00effade8cb45c139a85aac53b791d1a278f9
|
f2297675f92b8cfc25993271b8ad6abccbec7230
|
refs/heads/master
| 2022-12-16T15:51:05.072770 | 2020-09-10T23:40:16 | 2020-09-10T23:40:16 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,178 |
py
|
import asyncio
from phue import Bridge
import functools
class Oilers:
def __init__(self, bot):
self.bot = bot
self.bridge = Bridge("192.168.50.123")
self.lights = self.bridge.lights
self.bridge2 = Bridge("192.168.50.163")
self.lights2 = self.bridge2.lights
self.cur_lights = {}
self.cur_lights2 = {}
def goal_lights(self):
async def task():
task = functools.partial(self.get_current_lights_setting)
task = self.bot.loop.run_in_executor(None, task)
try:
await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
for i in range(5):
task = functools.partial(self.oilers_hex_set, x=1.0, y=1.0)
task = self.bot.loop.run_in_executor(None, task)
try:
await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
pass
# await self.oilers_hex_set(1.0, 1.0)
await asyncio.sleep(0.5)
task = functools.partial(self.oilers_hex_set, x=0, y=0)
task = self.bot.loop.run_in_executor(None, task)
try:
await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
pass
# await self.oilers_hex_set(0, 0)
await asyncio.sleep(0.5)
task = functools.partial(self.reset_light_setting)
task = self.bot.loop.run_in_executor(None, task)
try:
await asyncio.wait_for(task, timeout=60)
except asyncio.TimeoutError:
return
return self.bot.loop.create_task(task())
def reset_light_setting(self):
for light in self.lights:
old_temp = self.cur_lights[light.name][1]
if old_temp < 154:
old_temp = 154
if old_temp > 500:
old_temp = 499
light.colortemp = old_temp
light.on = self.cur_lights[light.name][0]
for light in self.lights2:
old_temp = self.cur_lights2[light.name][1]
if old_temp < 154:
old_temp = 154
if old_temp > 500:
old_temp = 499
light.colortemp = old_temp
light.on = self.cur_lights2[light.name][0]
return
def get_current_lights_setting(self):
for light in self.lights:
self.cur_lights[light.name] = [light.on, light.colortemp]
for light in self.lights2:
self.cur_lights2[light.name] = [light.on, light.colortemp]
return
def oilers_hex_set(self, x: float, y: float):
"""Sets the colour for Oilers Goals"""
if x > 1.0 or x < 0.0:
x = 1.0
if y > 1.0 or y < 0.0:
y = 1.0
for light in self.lights:
if not light.on:
light.on = True
light.xy = [x, y]
for light in self.lights2:
if not light.on:
light.on = True
light.xy = [x, y]
|
[
"[email protected]"
] | |
2b4d92d3292e81047c5230dabf58430a113fa1b0
|
453d2e699d218fdb3bc1e535a707988194ac6717
|
/dash/render/renderer.py
|
87d2dcebc49cfb1dfa4d0322c90249b714943d80
|
[
"MIT"
] |
permissive
|
defgsus/thegame
|
d54ffcd343c7e1805d2c11e24cd38b02243e73d4
|
38a627d9108f1418b94b08831fd640dd87fbba83
|
refs/heads/master
| 2023-07-23T06:32:40.297591 | 2022-04-11T12:02:32 | 2022-04-11T12:02:32 | 127,875,178 | 1 | 0 |
MIT
| 2023-07-06T22:07:07 | 2018-04-03T08:21:31 |
Python
|
UTF-8
|
Python
| false | false | 3,349 |
py
|
import time
import math
from typing import Optional
from pyglet import gl
import glm
from lib.opengl import *
from lib.math import FollowFilter
from .._path import ASSET_PATH
from ..game import Game
from .rs import GameRenderSettings
from .tilemap_node import TileMapNode
from .objects_node import ObjectsNode
from .object_debug_node import ObjectDebugNode
from .constraint_debug_node import ConstraintDebugNode
class GameRenderer:
def __init__(self, game: Game):
self.game = game
self.graph: Optional[RenderGraph] = None
self.pipeline: Optional[RenderPipeline] = None
self.render_settings = GameRenderSettings(32, 32)
self.debug_node = None
self.frame_number = 0
self.camera_pos = glm.vec2(-1, -5)
self.camera_rotation = 0.
self._target_speed_filter = FollowFilter(follow_up=.03, follow_down=.01)
def update(self, time: float, dt: float):
target = self.game.player
#target_speed = self._target_speed_filter(target.average_speed)
target_pos = glm.vec2(target.position) #+ target.direction_of_movement * target_speed * .5
self.camera_pos += min(1., dt * 3.) * (target_pos - self.camera_pos)
# self.camera_rotation += min(1., dt*.3) * (self.game.player.rotation - self.camera_rotation)
self.pipeline.update(self.render_settings, dt)
def render(self):
self.render_settings.projection.location = self.camera_pos
self.render_settings.projection.rotation_deg = self.camera_rotation
if self.graph is None:
self.graph = self.create_render_graph()
if self.pipeline is None:
self.pipeline = self.graph.create_pipeline()
self.pipeline.dump()
# self.pipeline.verbose = 5
#if self.frame_number % 100 == 0:
# self.tile_render_node.upload_map(self.game.tile_map.get_map(0, 0, 32, 32))
self.pipeline.render(self.render_settings)
self.pipeline.render_to_screen(self.render_settings)
self.frame_number += 1
def create_render_graph(self) -> RenderGraph:
graph = RenderGraph()
tile_tex = Texture2DNode(
ASSET_PATH /
"tileset03.png"
)
graph.add_node(tile_tex)
self.tile_render_node = TileMapNode(
"tilerender", self.game.world.tile_map,
tile_size=(16, 16),
tile_set_size=(10, 6),
)
graph.add_node(self.tile_render_node)
graph.connect(tile_tex, 0, self.tile_render_node, mag_filter=gl.GL_NEAREST)
self.object_node = ObjectsNode(
"objects", self.game.world.objects,
tile_size=(16, 16),
tile_set_size=(10, 6),
)
graph.add_node(self.object_node)
graph.connect(tile_tex, 0, self.object_node, mag_filter=gl.GL_NEAREST)
if 1:
self.debug_node = ConstraintDebugNode(
"debug", self.game.world.objects,
)
graph.add_node(self.debug_node)
mix_node = graph.add_node(postproc.Add("mix", count=3 if self.debug_node else 2))
graph.connect(self.tile_render_node, 0, mix_node, 0)
graph.connect(self.object_node, 0, mix_node, 1)
if self.debug_node:
graph.connect(self.debug_node, 0, mix_node, 2)
return graph
|
[
"[email protected]"
] | |
c8db3a8e226cb70ad8c96b08f2330917343112c1
|
58141d7fc37854efad4ad64c74891a12908192ed
|
/config/coconut/node_272.py
|
6b2d09a25a2e728fba4ec6858f853d862492788a
|
[] |
no_license
|
stanleylio/fishie
|
b028a93b2093f59a8ceee4f78b55a91bb1f69506
|
0685045c07e4105934d713a0fd58c4bc28821ed6
|
refs/heads/master
| 2022-08-14T13:08:55.548830 | 2022-07-29T01:32:28 | 2022-07-29T01:32:28 | 30,433,819 | 8 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,993 |
py
|
name = 'controller02'
location = 'Coconut Island'
note = "v0 code: {'neutral':0, 'heating':1, 'cooling':2, 'flush':3}"
latitude = 21.4347
longitude = -157.7990
deployment_status = 'deployed'
conf = [
{
'dbtag':'ts',
'description':'Device clock',
'interval':60,
},
{
'dbtag':'t0',
'unit':'\u00b0C',
'description':'Water Temperature',
'lb':22,
'ub':35,
'interval':60,
'plot_range':14*24,
},
{
'dbtag':'c0',
'unit':'\u00b0C',
'description':'Probe offset',
'lb':-1,
'ub':1,
'interval':60,
'plot_range':14*24,
},
{
'dbtag':'s0',
'unit':'\u00b0C',
'description':'Setpoint',
'lb':0,
'ub':50,
'interval':60,
'plot_range':14*24,
},
{
'dbtag':'v0',
'unit':'-',
'description':'Valve state',
'interval':60,
'plot_range':14*24,
},
{
'dbtag':'k',
'unit':'-',
'description':'Tank number',
'interval':60,
'plot_range':14*24,
},
{
'dbtag':'uptime_second',
'description':'Uptime in seconds',
'lb':24*60*60,
'interval':60,
'plot_range':2*24,
},
{
'dbtag':'freeMB',
'unit':'MB',
'description':'Remaining free disk space',
'lb':800,
'interval':60,
'plot_range':2*24,
},
{
'dbtag':'cpu_temp',
'unit':'\u00b0C',
'description':'CPU Temperature',
'lb':5,
'ub':68,
'interval':60,
'plot_range':2*24,
},
]
if '__main__' == __name__:
for c in conf:
print('- - -')
for k,v in c.items():
print(k,':',v)
import sys
sys.path.append('../..')
from os.path import basename
from storage.storage2 import create_table
create_table(conf, basename(__file__).split('.')[0].replace('_','-'))
|
[
"[email protected]"
] | |
c6e59b6836ac31b3775c83db628c1e1a2d0c6413
|
ece0d321e48f182832252b23db1df0c21b78f20c
|
/engine/2.80/scripts/freestyle/styles/split_at_highest_2d_curvatures.py
|
68a80d89ea7c7b23302858dd2ddfe88b93707121
|
[
"GPL-3.0-only",
"Font-exception-2.0",
"GPL-3.0-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain-disclaimer",
"Bitstream-Vera",
"LicenseRef-scancode-blender-2010",
"LGPL-2.1-or-later",
"GPL-2.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"PSF-2.0",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"BSD-2-Clause",
"Unlicense"
] |
permissive
|
byteinc/Phasor
|
47d4e48a52fa562dfa1a2dbe493f8ec9e94625b9
|
f7d23a489c2b4bcc3c1961ac955926484ff8b8d9
|
refs/heads/master
| 2022-10-25T17:05:01.585032 | 2019-03-16T19:24:22 | 2019-03-16T19:24:22 | 175,723,233 | 3 | 1 |
Unlicense
| 2022-10-21T07:02:37 | 2019-03-15T00:58:08 |
Python
|
UTF-8
|
Python
| false | false | 1,852 |
py
|
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# Filename : split_at_highest_2d_curvature.py
# Author : Stephane Grabli
# Date : 04/08/2005
# Purpose : Draws the visible lines (chaining follows same nature lines)
# (most basic style module)
from freestyle.chainingiterators import ChainSilhouetteIterator
from freestyle.functions import pyInverseCurvature2DAngleF0D
from freestyle.predicates import (
NotUP1D,
QuantitativeInvisibilityUP1D,
TrueUP1D,
pyHigherLengthUP1D,
pyParameterUP0D,
)
from freestyle.shaders import (
ConstantThicknessShader,
IncreasingColorShader,
)
from freestyle.types import Operators
Operators.select(QuantitativeInvisibilityUP1D(0))
Operators.bidirectional_chain(ChainSilhouetteIterator(), NotUP1D(QuantitativeInvisibilityUP1D(0)))
func = pyInverseCurvature2DAngleF0D()
Operators.recursive_split(func, pyParameterUP0D(0.4, 0.6), NotUP1D(pyHigherLengthUP1D(100)), 2)
shaders_list = [
ConstantThicknessShader(10),
IncreasingColorShader(1, 0, 0, 1, 0, 1, 0, 1),
]
Operators.create(TrueUP1D(), shaders_list)
|
[
"[email protected]"
] | |
5d5f19e950b769abbcaddf745393f2ddc66ce44e
|
e3c8f786d09e311d6ea1cab50edde040bf1ea988
|
/Incident-Response/Tools/cyphon/cyphon/responder/couriers/migrations/0001_initial.py
|
63f51235b83605b3ed2479a1caecf6f191b6d741
|
[
"LicenseRef-scancode-proprietary-license",
"GPL-3.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-copyleft",
"MIT"
] |
permissive
|
foss2cyber/Incident-Playbook
|
d1add8aec6e28a19e515754c6ce2e524d67f368e
|
a379a134c0c5af14df4ed2afa066c1626506b754
|
refs/heads/main
| 2023-06-07T09:16:27.876561 | 2021-07-07T03:48:54 | 2021-07-07T03:48:54 | 384,988,036 | 1 | 0 |
MIT
| 2021-07-11T15:45:31 | 2021-07-11T15:45:31 | null |
UTF-8
|
Python
| false | false | 2,005 |
py
|
# -*- coding: utf-8 -*-
# Copyright 2017-2019 ControlScan, Inc.
#
# This file is part of Cyphon Engine.
#
# Cyphon Engine is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Cyphon Engine is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cyphon Engine. If not, see <http://www.gnu.org/licenses/>.
#
# Generated by Django 1.10.1 on 2017-03-20 16:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('visas', '0001_initial'),
('passports', '0001_initial'),
('actions', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Courier',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=40, unique=True)),
('endpoints', models.ManyToManyField(related_name='emissaries', related_query_name='emissary', to='actions.Action', verbose_name='actions')),
('passport', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='passports.Passport')),
('visa', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='visas.Visa')),
],
options={
'abstract': False,
},
),
migrations.AlterUniqueTogether(
name='courier',
unique_together=set([('passport', 'visa')]),
),
]
|
[
"[email protected]"
] | |
fe477ca8839d24ef5c701f59cf5ec4ec9470a23a
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03547/s710097147.py
|
ae361a95c0c868de2d887122c718078902ffa546
|
[] |
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 | 128 |
py
|
X,Y = input().split()
S=[X,Y]
S.sort()
if X==Y:
print("=")
else:
if S[0]==X:
print("<")
elif S[0]==Y:
print(">")
|
[
"[email protected]"
] | |
1194dfd86a3d043f09ac701fb4b1c43643524106
|
4da72085e8b3adc68a6ec967025caf9576a75363
|
/tapiriik/services/api.py
|
0d61cea0af5e343af7a8d1f00d2a42d8eb991179
|
[
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
blakearnold/tapiriik
|
ec9063b3bc234dccc5dc63fcbe2f31bbcabc6e96
|
bf2e803cc8825a6c21bf7eae115044683dc98837
|
refs/heads/master
| 2021-01-20T01:10:52.259265 | 2014-07-21T00:58:58 | 2014-07-21T00:58:58 | 18,734,981 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,895 |
py
|
class ServiceExceptionScope:
Account = "account"
Service = "service"
class ServiceException(Exception):
def __init__(self, message, scope=ServiceExceptionScope.Service, block=False, user_exception=None):
Exception.__init__(self, message)
self.Message = message
self.UserException = user_exception
self.Block = block
self.Scope = scope
def __str__(self):
return self.Message + " (user " + str(self.UserException) + " )"
class ServiceWarning(ServiceException):
pass
class APIException(ServiceException):
pass
class APIWarning(ServiceWarning):
pass
# Theoretically, APIExcludeActivity should actually be a ServiceException with block=True, scope=Activity
# It's on the to-do list.
class APIExcludeActivity(Exception):
def __init__(self, message, activity=None, activityId=None, permanent=True, userException=None):
Exception.__init__(self, message)
self.Message = message
self.Activity = activity
self.ExternalActivityID = activityId
self.Permanent = permanent
self.UserException = userException
def __str__(self):
return self.Message + " (activity " + str(self.ExternalActivityID) + ")"
class UserExceptionType:
# Account-level exceptions (not a hardcoded thing, just to keep these seperate)
Authorization = "auth"
AccountFull = "full"
AccountExpired = "expired"
AccountUnpaid = "unpaid" # vs. expired, which implies it was at some point function, via payment or trial or otherwise.
# Activity-level exceptions
FlowException = "flow"
Private = "private"
NotTriggered = "notrigger"
RateLimited = "ratelimited"
MissingCredentials = "credentials_missing" # They forgot to check the "Remember these details" box
NotConfigured = "config_missing" # Don't think this error is even possible any more.
StationaryUnsupported = "stationary"
NonGPSUnsupported = "nongps"
TypeUnsupported = "type_unsupported"
DownloadError = "download"
ListingError = "list" # Cases when a service fails listing, so nothing can be uploaded to it.
UploadError = "upload"
SanityError = "sanity"
Corrupt = "corrupt" # Kind of a scary term for what's generally "some data is missing"
Untagged = "untagged"
LiveTracking = "live"
UnknownTZ = "tz_unknown"
System = "system"
Other = "other"
class UserException:
def __init__(self, type, extra=None, intervention_required=False, clear_group=None):
self.Type = type
self.Extra = extra # Unimplemented - displayed as part of the error message.
self.InterventionRequired = intervention_required # Does the user need to dismiss this error?
self.ClearGroup = clear_group if clear_group else type # Used to group error messages displayed to the user, and let them clear a group that share a common cause.
|
[
"[email protected]"
] | |
24fa541ba8035e7771c837154211bd159e7bd92e
|
2d2c10ffa7aa5ee35393371e7f8c13b4fab94446
|
/projects/ai/reader/read-records.py
|
ad82b741cf38c8653e3c5b8df2f1402d4a8f7ed8
|
[] |
no_license
|
faker2081/pikachu2
|
bec83750a5ff3c7b5a26662000517df0f608c1c1
|
4f06d47c7bf79eb4e5a22648e088b3296dad3b2d
|
refs/heads/main
| 2023-09-02T00:28:41.723277 | 2021-11-17T11:15:44 | 2021-11-17T11:15:44 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,377 |
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
# \file inference.py
# \author chenghuige
# \date 2018-02-05 20:05:25.123740
# \Description
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('input', './mount/temp/ai2018/sentiment/tfrecord/valid/*record,', '')
flags.DEFINE_integer('batch_size_', 512, '')
flags.DEFINE_string('type', 'debug', '')
flags.DEFINE_string('base', './mount/temp/ai2018/sentiment/tfrecord/', '')
#flags.DEFINE_integer('fold', None, '')
import tensorflow as tf
tf.compat.v1.enable_eager_execution()
import sys, os
from sklearn import metrics
import pandas as pd
import numpy as np
import gezi
import pickle
from wenzheng.utils import ids2text
import melt
logging = melt.logging
from dataset import Dataset
from tqdm import tqdm
# TODO by default save all ? so do not need to change the code ?
# _asdict() https://stackoverflow.com/questions/26180528/python-named-tuple-to-dictionary
# err... valid and test data share same id...
def deal(dataset, infos):
for x, _ in tqdm(dataset, ascii=True):
for key in x:
x[key] = x[key].numpy()
if type(x[key][0]) == bytes:
x[key] = gezi.decode(x[key])
ids = x['id']
for j in range(len(ids)):
infos[ids[j]] = {}
for key in x:
infos[ids[j]][key] = x[key][j]
def main(_):
base = FLAGS.base
logging.set_logging_path('./mount/tmp/')
vocab_path = f'{base}/vocab.txt'
ids2text.init(vocab_path)
FLAGS.vocab = f'{base}/vocab.txt'
# FLAGS.length_index = 2
# FLAGS.buckets = '100,400'
# FLAGS.batch_sizes = '64,64,32'
input_ = FLAGS.input
if FLAGS.type == 'test':
input_ = input_.replace('valid', 'test')
inputs = gezi.list_files(input_)
inputs.sort()
if FLAGS.fold is not None:
inputs = [x for x in inputs if not x.endswith('%d.record' % FLAGS.fold)]
if FLAGS.type == 'debug':
print('type', FLAGS.type, 'inputs', inputs, file=sys.stderr)
dataset = Dataset('valid')
dataset = dataset.make_batch(FLAGS.batch_size_, inputs)
print('dataset', dataset)
timer = gezi.Timer('read record')
for i, (x, y) in enumerate(dataset):
# if i % 10 == 1:
# print(x['id'])
# print(x['content'][0])
# print(ids2text.ids2text(x['content'][0], sep='|'))
# print(x['content'])
# print(type(x['id'].numpy()[0]) == bytes)
# break
x['id'] = gezi.decode(x['id'].numpy())
x['content_str'] = gezi.decode(x['content_str'].numpy())
for j, id in enumerate(x['id']):
if id == '573':
print(id, x['content_str'][j])
elif FLAGS.type == 'dump':
valid_infos = {}
test_infos = {}
inputs = gezi.list_files(f'{base}/train/*record')
dataset = Dataset('valid')
dataset = dataset.make_batch(1, inputs)
deal(dataset, valid_infos)
print('after valid', len(valid_infos))
inputs = gezi.list_files(f'{base}/test/*record')
dataset = Dataset('test')
dataset = dataset.make_batch(1, inputs)
deal(dataset, test_infos)
print('after test', len(test_infos))
for key in valid_infos:
print(valid_infos[key])
print(ids2text.ids2text(valid_infos[key]['content']))
break
ofile = f'{base}/info.pkl'
with open(ofile, 'wb') as out:
pickle.dump(valid_infos, out)
ofile = ofile.replace('.pkl', '.test.pkl')
with open(ofile, 'wb') as out:
pickle.dump(test_infos, out)
elif FLAGS.type == 'show_info':
valid_infos = pickle.load(open(f'{base}/info.pkl', 'rb'))
lens = [len(valid_infos[key]['content']) for key in valid_infos]
unks = [list(valid_infos[key]['content']).count(1) for key in valid_infos]
print('num unks per doc:', sum(unks) / len(unks))
print('num doc with unk ratio:', len([x for x in unks if x != 0]) / len(unks))
print('un unk tokens ratio:', sum(unks) / sum(lens))
print('len max:', np.max(lens))
print('len min:', np.min(lens))
print('len mean:', np.mean(lens))
else:
raise ValueError(FLAGS.type)
if __name__ == '__main__':
tf.compat.v1.app.run()
|
[
"[email protected]"
] | |
ab23e48873e7ca764d6bfc1216f93ed33e7f1c28
|
69c185d0dfed894234506a1aa6c6bf863849c589
|
/web服务器最初引进/wsgi/ctime.py
|
ac9c1f737f07361c21f766c78184b8254b451ce7
|
[] |
no_license
|
haha479/Socket_CS_project
|
19599edc47dda61a60afc55dae16a6b59c78fdd5
|
5b54ef8db0b10d63bf9e6f980a32a45c4055238a
|
refs/heads/master
| 2020-04-08T11:23:16.514181 | 2018-11-30T04:26:08 | 2018-11-30T04:26:08 | 159,304,060 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 362 |
py
|
import time
#将返回给浏览器的数据解耦到次脚本文件中
def get_time(env,start_response):
statu = "200 OK"
headers = [('Content-Type', 'text/html')]
start_response(statu,headers)
return time.ctime()
def get_love(env,start_response):
statu = "200 OK"
headers = [('Content-Type', 'text/html')]
start_response(statu,headers)
return "Love"
|
[
"[email protected]"
] | |
91c211a6e01d7c3e851c89671af6973faa5c1296
|
8bc025f27f451f245bd371b66f3d58253e4587d3
|
/src/Foundation/Standard/practice12.py
|
9c2c3dd3ebc73f06f3f63c509ae4d052354cdf83
|
[
"MIT"
] |
permissive
|
mryyomutga/PracticePython
|
8f2c5cdef074091eb8fcf76bd78800b959024e02
|
e191d73064248d0983344b137fbe6b69e5eb1d12
|
refs/heads/master
| 2021-05-15T14:31:16.365211 | 2017-10-29T04:46:51 | 2017-10-29T04:46:51 | 107,212,505 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,680 |
py
|
# -*- coding:utf-8 -*-
# ジェネレータ
# 処理の途中で値を返し、必要に応じて処理を再開できる
def sample_generator():
print("call 1")
yield "1st step"
print("call 2")
yield "2nd step"
print("call 3")
yield "3rd step"
# ジェネレータオブジェクトを作成
gen_func = sample_generator()
text = gen_func.__next__() # yieldまで実行
print(text) # 1st step
text = gen_func.__next__()
print(text) # 2nd step
text = gen_func.__next__()
print(text) # 3rd step
print()
# ループ処理でジェネレータ関数を実行
def sample_generator():
print("call 1")
yield "1st step"
print("call 2")
yield "2nd step"
print("call 3")
yield "3rd step"
gen_func = sample_generator()
for text in gen_func:
print(text)
# フィボナッチ数列を返すジェネレータ
def fibonacci_generator():
f0, f1 = 0, 1
while True: # この中が10回繰り返される
yield f0
f0, f1 = f1, f0 + f1
gen_func = fibonacci_generator()
for i in range(0, 10):
# 10個取得する
num = next(gen_func)
print(num)
print()
# send()メソッド
# 待機中のジェネレータに値を設定する
def sample_generator():
text = yield "Good Morning"
yield text
yield text
gen_func = sample_generator()
text = next(gen_func)
print(text)
text = gen_func.send("Hello")
print(text)
text = next(gen_func)
print(text)
# thorw()メソッド
# 待機中のジェネレータに例外を送信
# close()メソッド
# 待機中のジェネレータを正常終了させる
|
[
"[email protected]"
] | |
7c69ed213923a672ef47819e263bc2c7a18b0dae
|
4f0385a90230c0fe808e8672bb5b8abcceb43783
|
/LNH/day4/Common module/06 sys module-FLS-MPB.py
|
8b07eaf64b395655b35a8a69cb85bf7d9ab01420
|
[] |
no_license
|
lincappu/pycharmlearningproject
|
4084dab7adde01db9fa82a12769a67e8b26b3382
|
b501523e417b61373688ba12f11b384166baf489
|
refs/heads/master
| 2023-07-10T05:21:15.163393 | 2023-06-29T14:02:35 | 2023-06-29T14:02:35 | 113,925,289 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 384 |
py
|
# !/usr/bin/env python3
# _*_coding:utf-8_*_
# __author__:FLS
from pprint import pprint
import sys
print(sys.argv[0])
# 重定向标准输出:
saveout=sys.stdout
flog=open('t2.log.sh','w',encoding='utf-8')
sys.stdout=flog
print('12345323')
flog.close()
sys.stdout=saveout
print('zhengcheng')
print(sys.builtin_module_names)
pprint(sys.path)
pprint(sys.platform)
|
[
"[email protected]"
] | |
661ecdd01b1742556a9e7a99a743c13e13548b0f
|
06d3156837abec83be6e038e21ee4bfd0f6c0a23
|
/mysite/settings.py
|
be5097c4338860646302a2ba8e43adb57d314010
|
[] |
no_license
|
Igorskie/my-first-blog
|
2f4c94380ab61024c009f24f6f7cf3d0ac0df0b3
|
431a35144803cb9768e597d945116c94ced6ea13
|
refs/heads/master
| 2020-07-06T01:14:07.806438 | 2019-08-17T08:03:57 | 2019-08-17T08:03:57 | 202,833,238 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,181 |
py
|
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.0.13.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'b&pf-&z59!43(r882u2*k36s4fbtpw##$z1=570m!cjb13+$-a'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1', '.pythonanywhere.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
|
[
"[email protected]"
] | |
e72f0caffcab32a6b1d54c4d895be2149304c7d8
|
6b265b404d74b09e1b1e3710e8ea872cd50f4263
|
/Python/PyParsing/macro_expander.py
|
0c15b33b30ac328bf08b6d947d174a4f430e5943
|
[
"CC-BY-4.0"
] |
permissive
|
gjbex/training-material
|
cdc189469ae2c7d43784ecdcb4bcca10ecbc21ae
|
e748466a2af9f3388a8b0ed091aa061dbfc752d6
|
refs/heads/master
| 2023-08-17T11:02:27.322865 | 2023-04-27T14:42:55 | 2023-04-27T14:42:55 | 18,587,808 | 130 | 60 |
CC-BY-4.0
| 2023-08-03T07:07:25 | 2014-04-09T06:35:58 |
Jupyter Notebook
|
UTF-8
|
Python
| false | false | 3,443 |
py
|
#!/usr/bin/env python
from argparse import ArgumentParser, FileType
import imp
import sys
import types
from pyparsing import Regex, Literal, ZeroOrMore, Group
class UndefinedMacroError(Exception):
'''Class encoding an exception for an undefined macro encountered
while parsing a text'''
def __init__(self, function_name):
'''Constructor, takes the unknown macro name as an argument'''
super(UndefinedMacroError, self).__init__()
self._msg = "unknown macro '{0}'".format(function_name.strip('\\'))
def __str__(self):
'''method to stringify the exception'''
return repr(self._msg)
class MacroExpander(object):
'''Macro expansion class, macros are encoded as
\\macro_name{param_1}...{param_n}'''
def __init__(self):
'''Constructor'''
self._macros = {}
text = Regex(r'[^\\]+').leaveWhitespace()
lb = Literal('{').suppress()
rb = Literal('}').suppress()
param_value = Regex(r'[^}\\]+')
param = lb + ZeroOrMore(param_value) + rb
params = Group(ZeroOrMore(param)).setResultsName('params')
macro_name = Regex(r'\\\w+').setResultsName('macro')
macro_call = macro_name + params
text_file = ZeroOrMore(text | macro_call)
def macro_action(toks):
macro_name = toks['macro']
params = toks['params']
if self._has_macro(macro_name):
return self._macros[macro_name](*params)
else:
raise UndefinedMacroError(macro_name)
macro_call.addParseAction(macro_action)
self._grammar = text_file
def add_macro(self, macro_name, macro_impl):
'''method to add a new macro to the macro expander, given
the function name, and its implementation as arguments'''
self._macros['\\' + macro_name] = macro_impl
def _has_macro(self, macro_name):
'''internal method to check whether the parser has a
definition for the given macro name'''
return macro_name in self._macros
def expand(self, text):
'''method to perform the macro expansion on the given text'''
results = self._grammar.parseString(text)
return ''.join(results)
def main():
arg_parser = ArgumentParser(description='macro expansion utility')
arg_parser.add_argument('--file', type=FileType('r'),
action='store', dest='file',
required=True, help='file to expand')
arg_parser.add_argument('--def', type=str, action='store',
default='macro_defs', dest='defs',
help='macro definitions module name')
try:
options = arg_parser.parse_args()
text = ''.join(options.file)
module_info = imp.find_module(options.defs)
macro_module = imp.load_module(options.defs, *module_info)
expander = MacroExpander()
for macro_def in macro_module.__dict__.values():
if isinstance(macro_def, types.FunctionType):
expander.add_macro(macro_def.__name__, macro_def)
print(expander.expand(text))
except UndefinedMacroError as error:
sys.stderr.write('### error: ' + str(error) + '\n')
sys.exit(2)
except Exception as error:
sys.stderr.write('### error: ' + str(error) + '\n')
sys.exit(1)
if __name__ == '__main__':
main()
|
[
"[email protected]"
] | |
099cc4fda3d3ac97352d0deffc1bdb6a06428dc2
|
6c28060d11ec001b48a091760d0f883b23a72eaa
|
/notification/context_processor.py
|
cd66be1f866e7ca6946f8fafb29de4b9f29741eb
|
[] |
no_license
|
s-soroosh/rose
|
8b37904781d382fbac58fbaf9668391dddee2fc7
|
1f7ab356656696de06c56f8a86808ae59474c649
|
refs/heads/master
| 2021-05-26T18:22:37.349231 | 2014-07-02T07:25:54 | 2014-07-02T07:25:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 216 |
py
|
from assign.models import Assign
__author__ = 'soroosh'
def notification(request):
count = Assign.objects.filter(target__id=request.user.id, status='pending').count()
return {'notifications_count': count}
|
[
"[email protected]"
] | |
0621261bead3ecfcb35630fd2ffb1926684431d1
|
0e647273cffc1fb6cbd589fa3c7c277b221ba247
|
/configs/hpt-pretrain/chexpert-r18/no_basetrain/5000-iters.py
|
eea6cd8ca1b09c010a379fe19bbf022ffb5a8f90
|
[
"Apache-2.0"
] |
permissive
|
Berkeley-Data/OpenSelfSup
|
e9976bf011b69ebf918506ba184f464b1073ec13
|
221191b88d891de57725b149caf237ffef72e529
|
refs/heads/master
| 2023-05-12T07:34:52.268476 | 2021-04-08T00:58:37 | 2021-04-08T00:58:37 | 343,654,823 | 0 | 1 |
Apache-2.0
| 2021-04-08T00:58:37 | 2021-03-02T05:20:27 |
Python
|
UTF-8
|
Python
| false | false | 206 |
py
|
_base_="../base-chexpert-r18-config.py"
# this will merge with the parent
# epoch related
total_iters=5000
checkpoint_config = dict(interval=total_iters)
checkpoint_config = dict(interval=total_iters//2)
|
[
"[email protected]"
] | |
157d369702bec630b730984870fff4996b38d54e
|
b28df8f2cd9a4b4fe274eb1688e7410ae19f9da1
|
/kwippy/models/login.py
|
f89b8a0d9b01ef11b043d89d16a026f3e3f39269
|
[] |
no_license
|
kwippy-com/kwippycore
|
ba2d8b584e2171fd5322446df409e6983e23409b
|
d0647405cf77c4490cb40194b35e385955d56707
|
refs/heads/master
| 2020-06-14T14:56:35.169865 | 2014-12-08T16:44:20 | 2014-12-08T16:44:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 307 |
py
|
from django.db import models
from django.contrib.auth.models import *
class Login(models.Model):
user = models.ForeignKey(User)
login_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self) :
return '%s' % (self.user)
class Meta:
app_label="kwippy"
|
[
"[email protected]"
] | |
5566d9fe68f4a8e90970c0c0c27916071980e61a
|
2ec14fd1724fc8959e1d3a1b4d3f61d5c0cf6f48
|
/test/functional/feature_uacomment.py
|
e8b6937d62c8a3a6b6640d2715077b8465f8deaf
|
[
"MIT"
] |
permissive
|
vitae-labs/Vitae
|
7ddf8142d1e663f406399ec17de1c7bbba5e32fd
|
fa301e714cb26e742cfe29164a25961f1ff6d52c
|
refs/heads/main
| 2022-07-28T15:48:24.765770 | 2022-01-29T06:13:19 | 2022-01-29T06:13:19 | 451,559,855 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,769 |
py
|
#!/usr/bin/env python3
# Copyright (c) 2017-2019 The Bitcoin Core developers
# Copyright (c) 2020-2021 The Vitae Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the -uacomment option."""
import re
from test_framework.test_framework import VitaeTestFramework
from test_framework.test_node import ErrorMatch
from test_framework.util import assert_equal
class UacommentTest(VitaeTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def run_test(self):
self.log.info("test multiple -uacomment")
test_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-12:-1]
assert_equal(test_uacomment, "(testnode0)")
self.restart_node(0, ["-uacomment=foo"])
foo_uacomment = self.nodes[0].getnetworkinfo()["subversion"][-17:-1]
assert_equal(foo_uacomment, "(testnode0; foo)")
self.log.info("test -uacomment max length")
self.stop_node(0)
expected = r"Error: Total length of network version string \([0-9]+\) exceeds maximum length \(256\). Reduce the number or size of uacomments."
self.nodes[0].assert_start_raises_init_error(["-uacomment=" + 'a' * 256], expected, match=ErrorMatch.FULL_REGEX)
self.log.info("test -uacomment unsafe characters")
for unsafe_char in ['/', ':', '(', ')', '₿', '🏃']:
expected = r"Error: User Agent comment \(" + re.escape(unsafe_char) + r"\) contains unsafe characters."
self.nodes[0].assert_start_raises_init_error(["-uacomment=" + unsafe_char], expected, match=ErrorMatch.FULL_REGEX)
if __name__ == '__main__':
UacommentTest().main()
|
[
"[email protected]"
] | |
d09d651c8b884b3ed825d329a4531ec94b0b54d5
|
ad71c89863122dfb4093db0d9f9c40d962d567ff
|
/Week 10/3-HorizontalHistogram.py
|
487bedcb770ac0989049098209474854bb385e10
|
[] |
no_license
|
jacktnp/PSIT60
|
8958e7cca278c81d2c5d3af6956728c35425628d
|
b63c63d8d9c1e97ce66bbb0b884b1f19fecf7b6b
|
refs/heads/master
| 2021-08-16T07:53:33.900161 | 2017-11-19T10:07:02 | 2017-11-19T10:07:02 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 944 |
py
|
""" PSIT Week 10
Wiput Pootong (60070090)
HorizontalHistogram
"""
def main():
""" Display histogram of alphabets """
text = input()
upper = {}
lower = {}
for char in text:
if char.isupper():
if char not in upper:
upper[char] = 0
upper[char] += 1
else:
if char not in lower:
lower[char] = 0
lower[char] += 1
for char in sorted(lower):
print("%s : " %char, end='')
for count in range(lower[char]):
print("-", end='')
if count % 5 == 4 and count != (lower[char] - 1):
print("|", end='')
print()
for char in sorted(upper):
print("%s : " %char, end='')
for count in range(upper[char]):
print("-", end='')
if count % 5 == 4 and count != (upper[char] - 1):
print("|", end='')
print()
main()
|
[
"[email protected]"
] | |
c17ad1ba1dfe17e3fa802c32622852702517642a
|
3424161b573d2fe8873905d434d459a28336e87c
|
/head_soccer_06_3/source/database/mysql.py
|
fbb8e3d541273717b2f80f718259dc62c29cae0d
|
[] |
no_license
|
newtonis/Head-Soccer-Network
|
412f7717b97bcb2216bc8086ef131e9e9a4f3908
|
fd76920c486fb4af903b0e92b0d014a7d254f124
|
refs/heads/master
| 2023-05-23T23:08:46.952852 | 2021-06-27T00:20:12 | 2021-06-27T00:20:12 | 30,889,769 | 2 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,566 |
py
|
__author__ = 'Dylan'
import _mysql
import time
try:
con = _mysql.connect('db4free.net','grandt','1221dylan','headsoccerdb')
except:
print "[Info] Not able to reach internet"
con = None
class SQLEngine:
def CheckDeadServers(self):
actual = self.GetServers()
for x in actual:
if float(x["Created"]) < time.time() - 120:
self.RemoveServer(x["IP"],x["Name"])
def AddServer(self,name,ip):
### Add server to Servers database ###
con.query("SELECT * FROM Servers WHERE Name = '"+name+"'")
if con.store_result().num_rows() == 0:
con.query("INSERT INTO Servers (Name,IP,Created) VALUES ('"+name+"','"+ip+"',"+str(time.time())+")")
return True
else:
return False
def RemoveServer(self,ip,name):
### Remove server from Servers database by IP
con.query("DELETE FROM Servers WHERE IP = '"+ip+"' AND Name = '"+name+"'")
def GetServers(self):
### Return list of servers ###
if not con:
return []
con.query("SELECT * FROM Servers")
res = con.store_result()
servers = []
for x in range(res.num_rows()):
data = list(res.fetch_row())[0]
servers.append({"Name":data[0],"IP":data[1],"Created":data[2]})
return servers
def UpdateServer(self,ip,name):
try:
con.query("UPDATE Servers SET Created="+str(time.time())+" WHERE IP = '"+ip+"' AND Name = '"+name+"'")
except:
pass
MySQL = SQLEngine()
|
[
"[email protected]"
] | |
a1c8c70909a8fc1c7ae9cd1d3c59271506fb61df
|
cb73fe89463892c8c147c6995e220f5b1635fabb
|
/AtCoder Beginner Contest 174/q3.py
|
ac39b97c6a5853fd19f555ce923192f306771a27
|
[] |
no_license
|
Haraboo0814/AtCoder
|
244f6fd17e8f6beee2d46fbfaea6a8e798878920
|
7ad794fd85e8d22d4e35087ed38f453da3c573ca
|
refs/heads/master
| 2023-06-15T20:08:37.348078 | 2021-07-17T09:31:30 | 2021-07-17T09:31:30 | 254,162,544 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,004 |
py
|
import sys
from io import StringIO
import unittest
def resolve():
k = int(input())
x = 7 % k
for i in range(1, k + 1):
if x == 0:
print(i)
return
x = (x * 10 + 7) % k
print(-1)
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_入力例_1(self):
input = """101"""
output = """4"""
self.assertIO(input, output)
def test_入力例_2(self):
input = """2"""
output = """-1"""
self.assertIO(input, output)
def test_入力例_3(self):
input = """999983"""
output = """999982"""
self.assertIO(input, output)
if __name__ == "__main__":
unittest.main()
|
[
"[email protected]"
] | |
f480fc8f2b9e68eea63991f2c1e899917ba3f613
|
c5148bc364dac753c0872bd5676027a30b260486
|
/build/lib/biosteam/units/decorators/_design.py
|
bd20530d6c47562af76bc4bada9d063ee6920593
|
[
"MIT",
"NCSA",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Ecoent/biosteam
|
86f47c713a2cae5d6261b6c2c7734ccf7a90fb4e
|
f1371386d089df3aa8ce041175f210c0318c1fe0
|
refs/heads/master
| 2021-02-24T14:10:23.158984 | 2020-03-05T03:43:17 | 2020-03-05T03:43:17 | 245,433,768 | 1 | 0 |
NOASSERTION
| 2020-03-06T13:59:27 | 2020-03-06T13:59:26 | null |
UTF-8
|
Python
| false | false | 4,647 |
py
|
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 17:19:41 2019
@author: yoelr
"""
__all__ = ('design', 'add_design')
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 17 21:18:50 2019
@author: yoelr
"""
from thermosteam.base import stream_units_of_measure
__all__ = ('design',)
# %% Design Center class
def _design(self):
D = self.design_results
U = self._units
for i, j in self._design_basis_: D[i] = j(self, U[i])
class DesignCenter:
"""Create a DesignCenter object that manages all design basis functions. When called, it returns a Unit class decorator that adds a design item to the given Unit class."""
__slots__ = ('design_basis_functions',)
def __init__(self):
self.design_basis_functions = {}
def define(self, design_basis):
"""Define a new design basis.
Parameters
----------
design_basis : function
Should accept the unit_object and the units_of_measure and return design basis value.
.. Note::
Design basis is registered with the name of the design basis function.
"""
name = design_basis.__name__.replace('_', ' ').capitalize()
functions = self.design_basis_functions
if name in functions: raise ValueError(f"design basis '{name}' already implemented")
functions[name] = design_basis
return design_basis
def __call__(self, name, units, fsize=None):
"""Return a Unit class decorator that adds a size/design requirement to the class.
Parameters
----------
name : str
Name of design item.
units : str
Units of measure of design item.
fsize : function
Should return design item given the Unit object. If None, defaults to function predefined for given name and units.
"""
return lambda cls: self._add_design2cls(cls, name, units, fsize)
def _add_design2cls(self, cls, name, units, fsize):
"""Add size/design requirement to class.
Parameters
----------
cls : Unit class.
name : str
Name of design item.
units : str
Units of measure of design item.
fsize : function
Should return design item given the Unit object. If None, defaults to function predefined for given name and units.
Examples
--------
:doc:`Unit decorators`
"""
f = fsize or self.design_basis_functions[name.capitalize()]
# Make sure new _units dictionary is defined
if not cls._units:
cls._units = {}
elif '_units' not in cls.__dict__:
cls._units = cls._units.copy()
# Make sure design basis is not defined
if name in cls._units:
raise RuntimeError(f"design basis '{name}' already defined in class")
else:
cls._units[name] = units
# Add design basis
if cls._design is _design:
cls._design_basis_.append((name, f))
elif '_design' in cls.__dict__:
raise RuntimeError("'_design' method already implemented")
else:
cls._design_basis_ = [(name, f)]
cls._design = _design
return cls
def __contains__(self, basis):
return basis in self.__dict__
def __iter__(self):
yield from self.__dict__
def __repr__(self):
return f"<{type(self).__name__}: {', '.join(self)}>"
# %% Design factories
design = DesignCenter() #: Used to decorate classes with new design item
@design.define
def flow_rate(self, units):
if self._N_ins == 1:
return self._ins[0].get_total_flow(units)
elif self._N_outs == 1:
return self._outs[0].get_total_flow(units)
elif self._N_ins < self._N_outs:
return sum([i.get_total_flow(units) for i in self._ins])
else:
return sum([i.get_total_flow(units) for i in self._outs])
H_units = stream_units_of_measure['H']
@design.define
def duty(self, units):
self._duty = duty = self.H_out - self.H_in
self.heat_utilities[0](duty, self.ins[0].T, self.outs[0].T)
return H_units.conversion_factor(units) * duty
@design.define
def dry_flow_rate(self, units):
ins = self._ins
flow_in = sum([i.get_total_flow(units) for i in ins])
moisture = sum([i.get_flow(units, IDs='7732-18-5') for i in ins])
return flow_in - moisture
del flow_rate, duty, dry_flow_rate
|
[
"[email protected]"
] | |
a54031a091dc8ef18fbd886a0d9a5de58b59c0fa
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03326/s432961114.py
|
004e333b7354de53b77847c25af19fb0cad2aa12
|
[] |
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 | 595 |
py
|
n,m = map(int, input().split())
ab = [list(map(int, input().split())) for _ in range(n)]
import itertools
nums = [0,1]
ll = list(itertools.product(nums,repeat=3))
res = 0
for i in ll:
temp =[]
for j in range(n):
if i[0]==0:
x = ab[j][0]
else:
x = -ab[j][0]
if i[1]==0:
y = ab[j][1]
else:
y = -ab[j][1]
if i[2] ==0:
z = ab[j][2]
else:
z = -ab[j][2]
temp.append(x+y+z)
tempp =list(sorted(temp,reverse=True))
res = max(res,sum(tempp[:m]))
print(res)
|
[
"[email protected]"
] | |
6f0fb9c49884e780a516de1d650e4a68ef9638bb
|
8937c4d452c98699610923f76a395a2247f576df
|
/demo/download_demo_data.py
|
849791f18789882a992f77b515e00bad9d872f31
|
[] |
no_license
|
mistycheney/MouseBrainAtlas
|
812b204af06ed303f3c12d5c81edef50c8d9d1ed
|
bffbaa1ede9297084e64fc197716e63d5cb54275
|
refs/heads/master
| 2020-04-11T13:44:09.632311 | 2018-11-20T22:32:15 | 2018-11-20T22:32:15 | 20,377,173 | 3 | 9 | null | 2017-03-15T19:39:27 | 2014-06-01T12:42:08 |
Jupyter Notebook
|
UTF-8
|
Python
| false | false | 3,974 |
py
|
#! /usr/bin/env python
import sys, os
sys.path.append(os.path.join(os.environ['REPO_DIR'], 'utilities'))
from utilities2015 import *
from metadata import *
from data_manager import *
import argparse
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='This script downloads input data for demo.')
parser.add_argument("-d", "--demo_data_dir", type=str, help="Directory to store demo input data", default='demo_data')
args = parser.parse_args()
# demo_data_dir = '/home/yuncong/Brain/demo_data/'
def download_to_demo(fp):
demo_data_dir = args.demo_data_dir
s3_http_prefix = 'https://s3-us-west-1.amazonaws.com/mousebrainatlas-data/'
url = s3_http_prefix + fp
demo_fp = os.path.join(demo_data_dir, fp)
execute_command('wget -N -P \"%s\" \"%s\"' % (os.path.dirname(demo_fp), url))
return demo_fp
##### For registration demo. #####
fp = DataManager.get_sorted_filenames_filename(stack='DEMO999')
rel_fp = relative_to_local(fp, local_root=DATA_ROOTDIR)
download_to_demo(rel_fp)
fp = DataManager.get_anchor_filename_filename(stack='DEMO999')
rel_fp = relative_to_local(fp, local_root=DATA_ROOTDIR)
anchor_fp_demo = download_to_demo(rel_fp)
anchor_fn = DataManager.load_data(anchor_fp_demo, filetype='anchor')
fp = DataManager.get_section_limits_filename_v2(stack='DEMO999', anchor_fn=anchor_fn)
rel_fp = relative_to_local(fp, local_root=DATA_ROOTDIR)
download_to_demo(rel_fp)
fp = DataManager.get_cropbox_filename_v2(stack='DEMO999', prep_id=2, anchor_fn=anchor_fn)
rel_fp = relative_to_local(fp, local_root=DATA_ROOTDIR)
download_to_demo(rel_fp)
download_to_demo(os.path.join('CSHL_simple_global_registration', 'DEMO999_T_atlas_wrt_canonicalAtlasSpace_subject_wrt_wholebrain_atlasResol.bp'))
# Download subject detection maps
for name_s in ['3N_R', '4N_R', '12N']:
fp = DataManager.get_score_volume_filepath_v3(stack_spec={'name':'DEMO999', 'detector_id':799, 'resolution':'10.0um', 'vol_type':'score'}, structure=name_s)
rel_fp = relative_to_local(fp, local_root=ROOT_DIR)
download_to_demo(rel_fp)
fp = DataManager.get_score_volume_origin_filepath_v3(stack_spec={'name':'DEMO999', 'detector_id':799, 'resolution':'10.0um', 'vol_type':'score'}, structure=name_s, wrt='wholebrain')
rel_fp = relative_to_local(fp, local_root=ROOT_DIR)
download_to_demo(rel_fp)
# Download atlas
for name_s in ['3N_R', '4N_R', '3N_R_surround_200um', '4N_R_surround_200um','12N', '12N_surround_200um']:
fp = DataManager.get_score_volume_filepath_v3(stack_spec={'name':'atlasV7', 'resolution':'10.0um', 'vol_type':'score'}, structure=name_s)
rel_fp = relative_to_local(fp, local_root=ROOT_DIR)
download_to_demo(rel_fp)
fp = DataManager.get_score_volume_origin_filepath_v3(stack_spec={'name':'atlasV7', 'resolution':'10.0um', 'vol_type':'score'}, structure=name_s, wrt='canonicalAtlasSpace')
rel_fp = relative_to_local(fp, local_root=ROOT_DIR)
download_to_demo(rel_fp)
##### For visualization demo. #####
# Download images
for sec in range(221, 238):
fp = DataManager.get_image_filepath_v2(stack='DEMO999', prep_id=2, resol='raw', version='NtbNormalizedAdaptiveInvertedGammaJpeg', section=sec)
rel_fp = relative_to_local(fp, local_root=DATA_ROOTDIR)
download_to_demo(rel_fp)
fp = DataManager.get_original_volume_filepath_v2(stack_spec={'name':'DEMO999', 'resolution':'10.0um', 'vol_type':'intensity', 'prep_id':'wholebrainWithMargin'}, structure=None)
rel_fp = relative_to_local(fp, local_root=ROOT_DIR)
download_to_demo(rel_fp)
fp = DataManager.get_original_volume_origin_filepath_v3(stack_spec={'name':'DEMO999', 'resolution':'10.0um', 'vol_type':'intensity', 'prep_id':'wholebrainWithMargin'}, structure=None)
rel_fp = relative_to_local(fp, local_root=ROOT_DIR)
download_to_demo(rel_fp)
download_to_demo(os.path.join('CSHL_simple_global_registration', 'DEMO999_registered_atlas_structures_wrt_wholebrainXYcropped_xysecTwoCorners.json'))
|
[
"[email protected]"
] | |
e5d11a77ce1c989514ae0215922f88d8f5fb9851
|
137b2969323f7fb20cf4b72bf24ff98339a410c8
|
/tutorial/2/cal_pi_python.py
|
c9c4f802a962d65871cd0ef97a9fb7dd63ca74cd
|
[] |
no_license
|
kangheeyong/STUDY-make-lda-lib
|
c91b6d9a5bff7b25a0c00b63e61f93fbd60d2a8e
|
0f658032cf63922a0a5fc2fb5f34b8f22e97c94f
|
refs/heads/master
| 2021-02-12T06:27:27.900312 | 2020-04-03T10:56:21 | 2020-04-03T10:56:21 | 244,568,658 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 234 |
py
|
# calc_pi.py
def recip_square(i):
return 1. / i ** 2
def approx_pi(n=10000000):
val = 0.
for k in range(1, n + 1):
val += recip_square(k)
return (6 * val) ** .5
if __name__ == '__main__':
approx_pi()
|
[
"[email protected]"
] | |
879b16bbb01c016b6e984839fa4a918be7adb5cf
|
f8e8e365c9cf58b61d72655bc2340baeaed5baff
|
/Leetcode/Python Solutions/Stack/largestRectangleinHistogram.py
|
39ee39bff0455b2a950049c9ecd1446682f4e05b
|
[
"MIT"
] |
permissive
|
Mostofa-Najmus-Sakib/Applied-Algorithm
|
39a69f6b9ed113efe4a420d19cad79e0aa317637
|
bc656fd655617407856e0ce45b68585fa81c5035
|
refs/heads/master
| 2023-08-31T19:54:34.242559 | 2021-11-05T03:43:35 | 2021-11-05T03:43:35 | 412,263,430 | 0 | 0 |
MIT
| 2021-09-30T23:45:29 | 2021-09-30T23:45:25 | null |
UTF-8
|
Python
| false | false | 641 |
py
|
"""
LeetCode Problem: 84. Largest Rectangle in Histogram
Link: https://leetcode.com/problems/largest-rectangle-in-histogram/
Language: Python
Written by: Mostofa Adib Shakib
Time Complexity: O(N)
Space Complexity: O(N)
"""
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0)
stack = [-1]
ans = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
ans = max(ans, h * w)
stack.append(i)
return ans
|
[
"[email protected]"
] | |
d21803cc3e6025eb6eac8884a3604a3dfc0f2cfe
|
b0d7d91ccb7e388829abddb31b4aa04a2f9365cd
|
/archive-20200922/binary-search/first_bad_version2.py
|
62556ed0f8ac0ef51c7ea5298bc5dd50a4ec3b3f
|
[] |
no_license
|
clarkngo/python-projects
|
fe0e0aa02896debe82d1e9de84b1ae7d00932607
|
139a20063476f9847652b334a8495b7df1e80e27
|
refs/heads/master
| 2021-07-02T10:45:31.242041 | 2020-10-25T08:59:23 | 2020-10-25T08:59:23 | 188,570,684 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,351 |
py
|
# https://leetcode.com/problems/first-bad-version/submissions/
# You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
# Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
# You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
# Example:
# Given n = 5, and version = 4 is the first bad version.
# call isBadVersion(3) -> false
# call isBadVersion(5) -> true
# call isBadVersion(4) -> true
# Then 4 is the first bad version.
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
import bisect
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
self.__getitem__ = isBadVersion
return bisect.bisect_left(self, True, 1, n)
import unittest
a = Solution()
class Test(unittest.TestCase):
def test(self):
self.assertEqual(a.firstBadVersion())
|
[
"[email protected]"
] | |
21418667a8fe05896963725a6a68685b6845f11a
|
468a20df682ba43484f1953797f343011f77d7c1
|
/app.py
|
31669bddb87e95ebaf2f6c422b3575cae13d671e
|
[
"MIT"
] |
permissive
|
hchen13/capshelper
|
447006d363420e87a1ca4389ab1388b496495cdd
|
aea799c07064369642c3db557e939634c6c5da70
|
refs/heads/master
| 2020-03-21T21:09:30.904144 | 2018-06-29T03:20:30 | 2018-06-29T03:20:30 | 139,049,101 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,922 |
py
|
import json
import os
from butler import Butler
from butler.visualize import *
from downloader import *
from settings import ROOT_DIR
butler = Butler()
downloader = Downloader()
main_coins = 'USDT BTC ETH'.split(" ")
def update_watchlist():
watchlist = []
for counter in main_coins:
coins = downloader.get_top_coins(counter, limit=20)
watchlist += coins
return list(set(watchlist))
def get_watchlist(from_cache=True):
cache_file = "watchlist.json"
cache_path = os.path.join(ROOT_DIR, cache_file)
if from_cache and os.path.exists(cache_path):
return json.load(open(cache_path, 'r'))
watchlist = update_watchlist()
json.dump(watchlist, open(cache_path, 'w'))
return watchlist
def collect(base, counter):
base = base.upper()
counter = counter.upper()
ts = butler.latest_timestamp(base, counter)
if ts is None:
ts = datetime(2017, 2, 1, 0, 0).timestamp()
data = downloader.get_candlesticks(base, counter, start=ts)
if len(data):
butler.save_candlesticks(data)
butler.update_indicators(base, counter)
def single_run():
watchlist = get_watchlist(from_cache=True)
for counter in main_coins:
for base in watchlist:
counter = counter.upper()
base = base.upper()
if base == counter:
continue
collect(base, counter)
def prepare_train_data(path):
train_end = datetime(2018, 6, 1, 23, 59).timestamp()
valid_end = datetime(2018, 6, 10, 23, 59).timestamp()
test_end = datetime.now().timestamp()
butler.generate_train_files(path, 'train', end=train_end)
butler.generate_train_files(path, 'valid', start=train_end + 1, end=valid_end)
butler.generate_train_files(path, 'test', start=valid_end + 1, end=test_end)
if __name__ == '__main__':
# get_watchlist(False)
# single_run()
prepare_train_data('data/')
|
[
"[email protected]"
] | |
edfd582480b72d10d09c194a3b7b3e81e62b6e35
|
14b5679d88afa782dc5d6b35878ab043089a060a
|
/students/Siyang Liu/voicecontrol_changechoth/voice.py
|
7236b542f70ca123741e24926ba00368fad76e9a
|
[] |
no_license
|
mutiangua/EIS2020
|
c541ef32623f67f9277945cd39cff3c02f06e4dd
|
92aa2711b763a2c93be238825c445bf2db8da391
|
refs/heads/master
| 2022-11-18T05:21:47.567342 | 2020-07-11T10:11:21 | 2020-07-11T10:11:21 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,374 |
py
|
import wave
from aip import AipSpeech
from xpinyin import Pinyin
import pyaudio
import os
import cv2
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 8000
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "audio.wav"
APP_ID = '19165946'
API_KEY = 'D7BqfDPOj9ORbG85FL5jOQjh'
SECRET_KEY = 'skL4Mag0dGquseo08RaVsDgM1ABMxGN7'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
STATE = 0
TIME_START = 0
TIME_END = 0
num = 0
x = 0
y = 0
w = 0
h = 0
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
pd = cv2.imread('white.jpg')
pd1 = cv2.imread('yellow.jpg')
pd2 = cv2.imread('black.jpg')
img = cv2.imread('freedom.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
pass
head = img[y:(y + h), x:(x + w)]
head = cv2.resize(head, (130, 130), interpolation=cv2.INTER_CUBIC)
cv2.namedWindow('result')
def readFile(fileName):
with open(fileName, 'rb') as fp:
return fp.read()
def writeFile(fileName, result):
with open(fileName, 'wb') as fp:
fp.write(result)
def getBaiduText():
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
stream.start_stream()
print("* 开始录音......")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
stream.stop_stream()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
print("* 正在识别......")
result = client.asr(readFile('audio.wav'), 'wav', 16000, {
'dev_pid': 1537,
})
if result["err_no"] == 0:
for t in result["result"]:
return t
else:
print("没有识别到语音\n")
return ""
def getBaiduVoice(text):
result = client.synthesis(text, 'zh', 6, {'vol': 5, 'per': 4, 'spd': 5})
if not isinstance(result, dict):
writeFile("back.mp3", result)
os.system("back.mp3")
def getPinYin(result):
pin = Pinyin()
return pin.get_pinyin(result)
def pic(pd4):
cv2.destroyWindow('result')
pd4[185:315, 315:445] = head[0:130, 0:130]
cv2.imshow('result', pd4)
def wakeUp(pinyin):
if getPinYin("白色衣服") in pinyin:
print("好的,白色衣服")
pic(pd)
elif getPinYin("黄色衣服") in pinyin:
print("好的,黄色衣服")
pic(pd1)
elif getPinYin("黑色衣服") in pinyin:
print("好的,黑色衣服")
pic(pd2)
def main():
pic(pd)
if cv2.waitKey(10) & 0xFF == 'q':
return
while True:
result = getBaiduText()
pinyin = getPinYin(result)
print("等待唤醒")
print(result)
wakeUp(pinyin)
if cv2.waitKey(10) & 0xFF == 'q':
break
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
os.system("back.mp3")
os.system("audio.wav")
os.system("rmdir /s/q __pycache__")
|
[
"[email protected]"
] | |
dc2dd5439cb5bc87b057d15c4313f5adde3c50df
|
cebf2e5276e6d064d0ec86beaf1129fe0d0fd582
|
/days051-060/day059/capstone/blog.py
|
5a570cc0b88eb25417e462a8cc83d88159821495
|
[] |
no_license
|
SheikhFahimFayasalSowrav/100days
|
532a71c5c790bc28b9fd93c936126a082bc415f5
|
0af9f2f16044facc0ee6bce96ae5e1b5f88977bc
|
refs/heads/master
| 2023-06-14T06:18:44.109685 | 2021-07-08T16:58:13 | 2021-07-08T16:58:13 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 562 |
py
|
import requests
from flask import Flask, render_template
app = Flask(__name__)
posts = requests.get('https://api.npoint.io/a6ff5a040e0baf25233b').json()
@app.route('/')
def home():
return render_template('index.html', posts=posts)
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/contact')
def contact():
return render_template('contact.html')
@app.route('/post/<int:index>')
def post(index):
return render_template('post.html', post=posts[index])
if __name__ == '__main__':
app.run(debug=True)
|
[
"[email protected]"
] | |
4eaa041d0256e39539ed200f4a816597c3d3edad
|
ccbb5c8f53448af1a4721dbbfd06fc1ee72f58a9
|
/setup.py
|
4d756203887506c35187f9a7a08ac108a4b197af
|
[
"BSD-2-Clause"
] |
permissive
|
jorisvandenbossche/spatialpandas
|
ed7c05e2d3e2c2223fdcbeaa78279edf200c5a80
|
b63ebe619b8b8692fe282662725d23a50007acd9
|
refs/heads/master
| 2020-09-07T22:55:03.581677 | 2019-11-04T22:50:48 | 2019-11-04T22:50:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 230 |
py
|
from setuptools import setup, find_packages
setup(name='spatialpandas',
packages=find_packages(exclude=('tests',)),
install_requires=['pandas', 'dask', 'numba', 'numpy'],
tests_require=['pytest', 'hypothesis'])
|
[
"[email protected]"
] | |
7fb0fdcff4227dc74d10c6bffc07eb836805e31f
|
f2889a13368b59d8b82f7def1a31a6277b6518b7
|
/661.py
|
020da6437c8f01ec4483274e593f6429a27683c4
|
[] |
no_license
|
htl1126/leetcode
|
dacde03de5c9c967e527c4c3b29a4547154e11b3
|
c33559dc5e0bf6879bb3462ab65a9446a66d19f6
|
refs/heads/master
| 2023-09-01T14:57:57.302544 | 2023-08-25T15:50:56 | 2023-08-25T15:50:56 | 29,514,867 | 7 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 548 |
py
|
class Solution:
def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
r, c = len(img), len(img[0])
ans = [[0] * c for _ in range(r)]
for i in range(r):
for j in range(c):
t = size = 0
for x in range(-1, 2, 1):
for y in range(-1, 2, 1):
if 0 <= i + x < r and 0 <= j + y < c:
t += img[i + x][j + y]
size += 1
ans[i][j] = t // size
return ans
|
[
"[email protected]"
] | |
13009baf812cd8747ff405145799588fa9fb1406
|
9ae6ce54bf9a2a86201961fdbd5e7b0ec913ff56
|
/google/ads/googleads/v9/errors/types/query_error.py
|
8758e1728e679b9b1207402920a2e48a6a25d5ba
|
[
"Apache-2.0"
] |
permissive
|
GerhardusM/google-ads-python
|
73b275a06e5401e6b951a6cd99af98c247e34aa3
|
676ac5fcb5bec0d9b5897f4c950049dac5647555
|
refs/heads/master
| 2022-07-06T19:05:50.932553 | 2022-06-17T20:41:17 | 2022-06-17T20:41:17 | 207,535,443 | 0 | 0 |
Apache-2.0
| 2019-09-10T10:58:55 | 2019-09-10T10:58:55 | null |
UTF-8
|
Python
| false | false | 3,253 |
py
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v9.errors",
marshal="google.ads.googleads.v9",
manifest={"QueryErrorEnum",},
)
class QueryErrorEnum(proto.Message):
r"""Container for enum describing possible query errors.
"""
class QueryError(proto.Enum):
r"""Enum describing possible query errors."""
UNSPECIFIED = 0
UNKNOWN = 1
QUERY_ERROR = 50
BAD_ENUM_CONSTANT = 18
BAD_ESCAPE_SEQUENCE = 7
BAD_FIELD_NAME = 12
BAD_LIMIT_VALUE = 15
BAD_NUMBER = 5
BAD_OPERATOR = 3
BAD_PARAMETER_NAME = 61
BAD_PARAMETER_VALUE = 62
BAD_RESOURCE_TYPE_IN_FROM_CLAUSE = 45
BAD_SYMBOL = 2
BAD_VALUE = 4
DATE_RANGE_TOO_WIDE = 36
DATE_RANGE_TOO_NARROW = 60
EXPECTED_AND = 30
EXPECTED_BY = 14
EXPECTED_DIMENSION_FIELD_IN_SELECT_CLAUSE = 37
EXPECTED_FILTERS_ON_DATE_RANGE = 55
EXPECTED_FROM = 44
EXPECTED_LIST = 41
EXPECTED_REFERENCED_FIELD_IN_SELECT_CLAUSE = 16
EXPECTED_SELECT = 13
EXPECTED_SINGLE_VALUE = 42
EXPECTED_VALUE_WITH_BETWEEN_OPERATOR = 29
INVALID_DATE_FORMAT = 38
MISALIGNED_DATE_FOR_FILTER = 64
INVALID_STRING_VALUE = 57
INVALID_VALUE_WITH_BETWEEN_OPERATOR = 26
INVALID_VALUE_WITH_DURING_OPERATOR = 22
INVALID_VALUE_WITH_LIKE_OPERATOR = 56
OPERATOR_FIELD_MISMATCH = 35
PROHIBITED_EMPTY_LIST_IN_CONDITION = 28
PROHIBITED_ENUM_CONSTANT = 54
PROHIBITED_FIELD_COMBINATION_IN_SELECT_CLAUSE = 31
PROHIBITED_FIELD_IN_ORDER_BY_CLAUSE = 40
PROHIBITED_FIELD_IN_SELECT_CLAUSE = 23
PROHIBITED_FIELD_IN_WHERE_CLAUSE = 24
PROHIBITED_RESOURCE_TYPE_IN_FROM_CLAUSE = 43
PROHIBITED_RESOURCE_TYPE_IN_SELECT_CLAUSE = 48
PROHIBITED_RESOURCE_TYPE_IN_WHERE_CLAUSE = 58
PROHIBITED_METRIC_IN_SELECT_OR_WHERE_CLAUSE = 49
PROHIBITED_SEGMENT_IN_SELECT_OR_WHERE_CLAUSE = 51
PROHIBITED_SEGMENT_WITH_METRIC_IN_SELECT_OR_WHERE_CLAUSE = 53
LIMIT_VALUE_TOO_LOW = 25
PROHIBITED_NEWLINE_IN_STRING = 8
PROHIBITED_VALUE_COMBINATION_IN_LIST = 10
PROHIBITED_VALUE_COMBINATION_WITH_BETWEEN_OPERATOR = 21
STRING_NOT_TERMINATED = 6
TOO_MANY_SEGMENTS = 34
UNEXPECTED_END_OF_QUERY = 9
UNEXPECTED_FROM_CLAUSE = 47
UNRECOGNIZED_FIELD = 32
UNEXPECTED_INPUT = 11
REQUESTED_METRICS_FOR_MANAGER = 59
FILTER_HAS_TOO_MANY_VALUES = 63
__all__ = tuple(sorted(__protobuf__.manifest))
|
[
"[email protected]"
] | |
b67319a271d923790927e483e58fe947902af3ae
|
a50fc03c5de39fb321f07016ef64e13d98fa7c50
|
/MyDB/data/make_labels/work_flow.py
|
287d933be1953d53aad6cc87108bf26781f58287
|
[
"Apache-2.0"
] |
permissive
|
PKQ1688/text_detection
|
a94c435b3e2ee962b7489a094438ad052d7e7655
|
e306b003f2e8eb9f8d07fc95d2d9def14fa8b38c
|
refs/heads/master
| 2022-11-21T18:09:49.430313 | 2020-07-29T08:44:50 | 2020-07-29T08:44:50 | 246,490,664 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,440 |
py
|
# -*- coding:utf-8 -*-
# @author :adolf
from data.make_labels.make_border_map import MakeBorderMap
from data.make_labels.make_shrink_map import MakeShrinkMap
import numpy as np
from data.data_utils.clockwise_points import order_points_clockwise
import cv2
import os
# img_path = '/home/shizai/data2/ocr_data/rctw/imgs/rctw_image_3890.jpg'
# gt_path = '/home/shizai/data2/ocr_data/rctw/gts/rctw_image_3890.txt'
def get_annotation(gt_path, ignore_tags=['*', '###']):
boxes = list()
texts = list()
ignores = list()
with open(gt_path, encoding='utf-8', mode='r') as f:
for line in f.readlines():
params = line.strip().strip('\ufeff').strip('\xef\xbb\xbf').split(',')
# print(params)
try:
box = order_points_clockwise(np.array(list(map(float, params[:8]))).reshape(-1, 2))
# print(box)
if cv2.contourArea(box) > 0:
boxes.append(box)
texts.append(params[8])
ignores.append(params[8] in ignore_tags)
except Exception as e:
print(e)
print('get annotation is failed {}'.format(gt_path))
data = {'text_polys': np.array(boxes),
'texts': texts,
'ignore_tags': ignores}
return data
# data = get_annotation(gt_path)
# img = cv2.imread(img_path)
# img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# data['img'] = img
# print(data['ignore_tags'])
# data = MakeShrinkMap()(data)
# cv2.imwrite('images_result/ori_img.png', img)
# print(data['shrink_map'])
# data = MakeBorderMap()(data)
# print(data.keys())
# cv2.imwrite('images_result/shrink_map.png', (data['shrink_map'] * 255).astype(np.uint8))
# cv2.imwrite('images_result/shrink_mask.png', (data['shrink_mask'] * 255).astype(np.uint8))
# cv2.imwrite('images_result/threshold_map.png', (data['threshold_map'] * 255).astype(np.uint8))
# cv2.imwrite('images_result/threshold_mask.png', (data['threshold_mask'] * 255).astype(np.uint8))
def make_use_label(file_path, img_name):
img_path = os.path.join(file_path, 'imgs', img_name)
gt_name = 'gt_' + img_name.replace('png', 'txt').replace('jpg', 'txt').replace('jpeg', 'txt')
gt_path = os.path.join(file_path, 'gts', gt_name)
data = get_annotation(gt_path)
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
data['img'] = img
data = MakeShrinkMap()(data)
data = MakeBorderMap()(data)
cv2.imwrite(os.path.join(file_path, 'shrink_map', img_name), data['shrink_map'])
cv2.imwrite(os.path.join(file_path, 'shrink_mask', img_name), data['shrink_mask'])
#
cv2.imwrite(os.path.join(file_path, 'threshold_map', img_name), data['threshold_map'])
cv2.imwrite(os.path.join(file_path, 'threshold_mask', img_name), data['threshold_mask'])
rctw_path = "/home/shizai/data2/ocr_data/rctw"
rctw_list = os.listdir(os.path.join(rctw_path, 'imgs'))
# print('begin...')
# for rctw_img in rctw_list:
# make_use_label(rctw_path, rctw_img)
#
# third_path = "/home/shizai/data2/ocr_data/third_data"
# third_list = os.listdir(os.path.join(third_path, 'imgs'))
#
# for third_img in third_list:
# make_use_label(third_path, third_img)
# print('end...')
icdar_path = "/home/shizai/data2/ocr_data/icdar2015/train/"
icdar_list = os.listdir(os.path.join(icdar_path, 'imgs'))
for icdar_img in icdar_list:
make_use_label(icdar_path, icdar_img)
|
[
"[email protected]"
] | |
c970668ee9d13930e662701f9264a1f3549c7dbb
|
de24f83a5e3768a2638ebcf13cbe717e75740168
|
/moodledata/vpl_data/77/usersdata/232/41242/submittedfiles/exercicio24.py
|
3eac611f36a389948a2e0b1b66783af935b9b375
|
[] |
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 | 296 |
py
|
# -*- coding: utf-8 -*-
import math
a=int(input('Digite o valor de a: '))
b=int(input('Digite o valor de b: '))
if a>b:
for i in range (1,b,1):
if (a%i)==0 and (b%i)==0:
print(i)
else:
for i in range (1,a,1):
if (b%i)==0 and (a%i)==0:
print(i)
|
[
"[email protected]"
] | |
bbdba525d199606ba340c0a5217998203f805593
|
df6c141f5fb53c093b75da13275576728d40cb6c
|
/tests/core/parse/test_parse_delimited.py
|
0259f7b44c53a32886d111e2a8987d9e7d35ef1b
|
[
"MIT"
] |
permissive
|
conormancone-cimpress/mygrations
|
3adee758dc5b9f8c0abb3e097a7d7146042696bf
|
30d1d568ca7d6c38dbc5211834dd2d04c0bcf078
|
refs/heads/master
| 2022-04-03T20:55:54.892085 | 2020-02-18T11:31:24 | 2020-02-18T11:31:24 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,632 |
py
|
import unittest
from mygrations.core.parse.rule_delimited import rule_delimited
class test_parse_delimited(unittest.TestCase):
def get_rule(self, name, separator, quote, literal):
return rule_delimited(
False, {
'name': name,
'separator': separator,
'quote': quote
}, {
'type': 'literal',
'value': literal
}
)
def test_name_required(self):
with self.assertRaises(ValueError):
self.get_rule('', ',', '`', 'asdf')
def test_separator_required(self):
with self.assertRaises(ValueError):
self.get_rule('bob', '', '', 'asdf')
def test_no_multi_character_separator(self):
with self.assertRaises(ValueError):
self.get_rule('bob', 'as', '', 'asdf')
def test_no_multi_character_quote(self):
with self.assertRaises(ValueError):
self.get_rule('bob', ',', 'as', 'asdf')
def test_literal_required(self):
with self.assertRaises(ValueError):
rule_delimited(False, {'name': 'bob', 'separator': ',', 'quote': '`'}, {})
def test_can_init_with_name_and_separator(self):
rule = self.get_rule('bob', ',', '', 'asdf')
self.assertEquals(rule.name, 'bob')
self.assertEquals(rule.separator, ',')
def test_parse_without_quote(self):
rule = self.get_rule('bob', ',', '', ')')
self.assertTrue(rule.parse('1,2,3,4)'))
self.assertEquals(['1', '2', '3', '4'], rule.result)
self.assertEquals(')', rule.leftovers)
def test_parse_optional_quotes(self):
rule = self.get_rule('bob', ',', '`', ')')
self.assertTrue(rule.parse('asdf,`bob`,huh,`okay`) sup'))
self.assertEquals(['asdf', 'bob', 'huh', 'okay'], rule.result)
self.assertEquals(') sup', rule.leftovers)
def test_syntax_error_missing_quote(self):
with self.assertRaises(SyntaxError):
rule = self.get_rule('bob', ',', '`', ')')
rule.parse('asdf,`bob)')
def test_separator_in_quotes(self):
rule = self.get_rule('bob', ',', '`', ')')
self.assertTrue(rule.parse('asdf,`bob,`,huh,`okay`) sup'))
self.assertEquals(['asdf', 'bob,', 'huh', 'okay'], rule.result)
self.assertEquals(') sup', rule.leftovers)
def test_alternate_characters(self):
rule = self.get_rule('bob', 'X', '<', 'asdf')
self.assertTrue(rule.parse('<hey<X<sup<asdf'))
self.assertEquals(['hey', 'sup'], rule.result)
self.assertEquals('asdf', rule.leftovers)
|
[
"[email protected]"
] | |
96e148bc4a0214e66c46be3fb70e8b07f9f28a1b
|
52b2e3470cd4b91975b2e1caed8d1c93c20e5d05
|
/tools/misc/dedup.py
|
b45b5fdcaa724397e39049fcdfd692a60aaaf159
|
[] |
no_license
|
xprime480/projects
|
c2f9a82bbe91e00859568dc27ae17c3b5dd873e3
|
3c5eb2d53bd7fa198edbe27d842ee5b5ff56e226
|
refs/heads/master
| 2020-04-27T03:51:29.456979 | 2019-04-12T14:34:39 | 2019-04-12T14:34:39 | 174,037,060 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,003 |
py
|
#!/usr/bin/python
class Deduper(object) :
def __init__(self) :
self.lines = {}
self.count = 0
def addLine(self, line) :
self.count += 1
self.lines[line] = self.count
def getLines(self) :
lineListWithIndex = [(index,line) for line,index in self.lines.items()]
lineListWithIndex.sort()
linesSortedByIndex = [line for index,line in lineListWithIndex]
return linesSortedByIndex
class FileDeduper(object) :
def __init__(self, fileName) :
deduper = Deduper()
with open(fileName) as fileHandle :
for line in fileHandle.readlines() :
deduper.addLine(line[:-1])
self.lines = deduper.getLines()
def getLines(self) :
return self.lines
def dedupFile(fileName) :
deduper = FileDeduper(fileName)
for line in deduper.getLines() :
print line
if __name__ == '__main__' :
import sys
for fileName in sys.argv[1:] :
dedupFile(fileName)
|
[
"[email protected]"
] | |
481366b4ed79ce490dd3f6c4e8e0913f760fd9bb
|
b96d4479c86b971a23d20854000aecd6e1f8ce0a
|
/audit/mixins.py
|
1c261b7a7072d808856ef448bae880fab709c7f9
|
[] |
no_license
|
dbsiavichay/invenco
|
0eb3d74e8403dbed9d4d9459bd25c8ae107368fe
|
11e06d1ae694f9ffc158400fc63f4b81f1807875
|
refs/heads/master
| 2022-11-29T21:08:05.075194 | 2019-07-23T14:06:51 | 2019-07-23T14:06:51 | 92,068,624 | 1 | 0 | null | 2022-11-22T01:15:08 | 2017-05-22T15:22:30 |
JavaScript
|
UTF-8
|
Python
| false | false | 864 |
py
|
# -*- coding: utf-8 -*-
from django.contrib.contenttypes.models import ContentType
from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION
from django.utils.encoding import force_unicode
class AuditMixin(object):
def save_log(self, user, message, ACTION):
log = LogEntry.objects.create(
user_id = user.id,
content_type_id = ContentType.objects.get_for_model(self).id,
object_id = self.id,
object_repr = force_unicode(self),
action_flag = ACTION,
change_message = message
)
def save_addition(self, user):
message = '[{"añadidos": {}}]'
self.save_log(user, message, ADDITION)
def save_edition(self, user):
self.save_log(user, '[{"cambiados": {"fields": []}}]', CHANGE)
def save_deletion(self, user):
self.save_log(user, '[{"eliminados": {}}]', DELETION)
|
[
"[email protected]"
] | |
808d060c64c007cbf5ccbed2a10e6f19c169a93e
|
ff6248be9573caec94bea0fa2b1e4b6bf0aa682b
|
/StudentProblem/10.21.9.56/3/1569573341.py
|
7861b0d7864d83874341994b8d4a4c9183986b35
|
[] |
no_license
|
LennartElbe/codeEvo
|
0e41b1a7705204e934ef71a5a28c047366c10f71
|
e89b329bc9edd37d5d9986f07ca8a63d50686882
|
refs/heads/master
| 2020-12-21T17:28:25.150352 | 2020-03-26T10:22:35 | 2020-03-26T10:22:35 | 236,498,032 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 645 |
py
|
import functools
import typing
import string
import random
import pytest
def leap(jahrzahl: int) -> bool:
'return True if the given year is schaltjahr and false if not'
if jahrzahl > 1582:
if jahrzahl % 100 == 0 and jahrzahl% 400 != 0:
return True
else:
return False
else:
print('jahrzahl ist kleiner als 1582')
######################################################################
## Lösung Teil 2 (Tests)
def test_leap():
assert leap(155) == jahrzahl ist kleiner als 1582
assert leap(2000) == False
######################################################################
|
[
"[email protected]"
] | |
cc3f3bdd7b7d3c7b6073fc600dab76adaa827007
|
0dd881b86146eff46a99e3100a12addcb5b1bde9
|
/No701 Insert into a Binary Search Tree.py
|
bf808a212bff8626fffb83d0862a468224faf119
|
[] |
no_license
|
BaijingML/leetcode
|
8b04599ba6f1f9cf12fbb2726f6a1463a42f0a70
|
0ba37ea32ad71d9467f73da6f9e71971911f1d4c
|
refs/heads/master
| 2020-03-22T05:07:17.884441 | 2020-01-10T12:13:54 | 2020-01-10T12:13:54 | 138,399,745 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 628 |
py
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return root
if val < root.val:
if root.left:
self.insertIntoBST(root.left, val)
else:
root.left = TreeNode(val)
else:
if root.right:
self.insertIntoBST(root.right, val)
else:
root.right = TreeNode(val)
return root
|
[
"[email protected]"
] | |
ab2368e353ecfb086908d5635656a7bd22fb9cbb
|
5f67c696967456c063e5f8a0d14cf18cf845ad38
|
/archiv/_python/py4inf/xml1.py
|
e71260c5a8b2930fed02fa39bbc048217dc8cb67
|
[] |
no_license
|
wuxi20/Pythonista
|
3f2abf8c40fd6554a4d7596982c510e6ba3d6d38
|
acf12d264615749f605a0a6b6ea7ab72442e049c
|
refs/heads/master
| 2020-04-02T01:17:39.264328 | 2019-04-16T18:26:59 | 2019-04-16T18:26:59 | 153,848,116 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 281 |
py
|
import xml.etree.ElementTree as ET
data = '''
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes"/>
</person>'''
tree = ET.fromstring(data)
print('Name:',tree.find('name').text)
print('Attr:',tree.find('email').get('hide'))
|
[
"[email protected]"
] | |
7923e0d4e6524bc8d6329971c1e892fc33f5efa7
|
ea99544eef7572b194c2d3607fa7121cb1e45872
|
/apps/support/migrations/0003_auto_20190407_1007.py
|
abf7098fd524718ce25631fdde2aa89a1d5d749a
|
[] |
no_license
|
ash018/FFTracker
|
4ab55d504a9d8ba9e541a8b682bc821f112a0866
|
11be165f85cda0ffe7a237d011de562d3dc64135
|
refs/heads/master
| 2022-12-02T15:04:58.543382 | 2019-10-05T12:54:27 | 2019-10-05T12:54:27 | 212,999,035 | 0 | 0 | null | 2022-11-22T03:58:29 | 2019-10-05T12:53:26 |
Python
|
UTF-8
|
Python
| false | false | 470 |
py
|
# Generated by Django 2.2 on 2019-04-07 10:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('support', '0002_customersupport_user'),
]
operations = [
migrations.AlterField(
model_name='customersupport',
name='status',
field=models.PositiveSmallIntegerField(choices=[(2, 'Resolved'), (1, 'In progress'), (0, 'Pending')], default=0),
),
]
|
[
"[email protected]"
] | |
301498f89b89d64d5a6b050f084e33d3e27e9569
|
53784d3746eccb6d8fca540be9087a12f3713d1c
|
/res/packages/scripts/scripts/client/gui/Scaleform/daapi/view/lobby/cyberSport/CyberSportUnitsListView.py
|
37f7802efad2cd66a095df4f913fd0d67f3ec9e6
|
[] |
no_license
|
webiumsk/WOT-0.9.17.1-CT
|
736666d53cbd0da6745b970e90a8bac6ea80813d
|
d7c3cf340ae40318933e7205bf9a17c7e53bac52
|
refs/heads/master
| 2021-01-09T06:00:33.898009 | 2017-02-03T21:40:17 | 2017-02-03T21:40:17 | 80,870,824 | 0 | 0 | null | null | null | null |
WINDOWS-1250
|
Python
| false | false | 5,519 |
py
|
# 2017.02.03 21:49:44 Střední Evropa (běžný čas)
# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/cyberSport/CyberSportUnitsListView.py
from UnitBase import UNIT_BROWSER_TYPE
from gui.Scaleform.daapi.view.lobby.rally.rally_dps import ManualSearchDataProvider
from gui.Scaleform.daapi.view.meta.CyberSportUnitsListMeta import CyberSportUnitsListMeta
from gui.Scaleform.genConsts.CYBER_SPORT_ALIASES import CYBER_SPORT_ALIASES
from gui.Scaleform.locale.CYBERSPORT import CYBERSPORT
from gui.Scaleform.locale.RES_ICONS import RES_ICONS
from gui.prb_control.settings import REQUEST_TYPE
from gui.shared import events
from gui.shared.view_helpers import CooldownHelper
from helpers import int2roman
from helpers.i18n import makeString as _ms
from gui.shared.formatters import text_styles
class CyberSportUnitsListView(CyberSportUnitsListMeta):
def __init__(self):
super(CyberSportUnitsListView, self).__init__()
self._unitTypeFlags = UNIT_BROWSER_TYPE.ALL
self._cooldown = CooldownHelper(self.getCoolDownRequests(), self._onCooldownHandle, events.CoolDownEvent.PREBATTLE)
self.__currentEmblem = None
return
def getPyDataProvider(self):
return ManualSearchDataProvider()
def getCoolDownRequests(self):
return [REQUEST_TYPE.UNITS_LIST]
def loadPrevious(self):
listReq = self.prbEntity.getBrowser()
if listReq:
listReq.request(req=REQUEST_TYPE.UNITS_NAV_LEFT)
def loadNext(self):
listReq = self.prbEntity.getBrowser()
if listReq:
listReq.request(req=REQUEST_TYPE.UNITS_NAV_RIGHT)
def refreshTeams(self):
listReq = self.prbEntity.getBrowser()
if listReq:
listReq.request(req=REQUEST_TYPE.UNITS_REFRESH)
def getRallyDetails(self, index):
if index != self._searchDP.selectedRallyIndex:
self.__currentEmblem = None
cfdUnitID, vo = self._searchDP.getRally(index)
listReq = self.prbEntity.getBrowser()
if listReq:
listReq.setSelectedID(cfdUnitID)
self.__setDetails(vo)
return
def onPrbEntitySwitching(self):
browser = self.prbEntity.getBrowser()
if browser:
browser.stop()
def _populate(self):
super(CyberSportUnitsListView, self)._populate()
self._cooldown.start()
self.prbEntity.getBrowser().start(self.__onUnitsListUpdated)
self.as_setHeaderS({'title': text_styles.promoTitle(CYBERSPORT.WINDOW_UNITLISTVIEW_TITLE),
'createBtnLabel': CYBERSPORT.WINDOW_UNITLISTVIEW_CREATE_BTN,
'createBtnTooltip': None,
'createBtnEnabled': True,
'columnHeaders': self.__getColumnHeaders()})
return
def _dispose(self):
self._cooldown.stop()
self._cooldown = None
super(CyberSportUnitsListView, self)._dispose()
return
def _onUserActionReceived(self, _, user):
self.__updateView(user)
def _doEnableNavButtons(self, isEnabled):
self.as_updateNavigationBlockS({'previousVisible': True,
'previousEnabled': isEnabled,
'nextVisible': True,
'nextEnabled': isEnabled})
def _onCooldownHandle(self, isInCooldown):
self._doEnableNavButtons(not isInCooldown)
def __getColumnHeaders(self):
return [self.__createHedader('', 82, 'center', RES_ICONS.MAPS_ICONS_STATISTIC_RATING24),
self.__createHedader(CYBERSPORT.WINDOW_UNIT_UNITLISTVIEW_COMMANDER, 152),
self.__createHedader(CYBERSPORT.WINDOW_UNIT_UNITLISTVIEW_DESCRIPTION, 220),
self.__createHedader(CYBERSPORT.WINDOW_UNIT_UNITLISTVIEW_PLAYERS, 76)]
def __createHedader(self, label, buttonWidth, position = 'left', iconSource = None):
return {'label': label,
'buttonWidth': buttonWidth,
'iconSource': iconSource,
'enabled': False,
'textAlign': position}
def __updateVehicleLabel(self):
settings = self.prbEntity.getRosterSettings()
self._updateVehiclesLabel(int2roman(settings.getMinLevel()), int2roman(settings.getMaxLevel()))
def __onUnitsListUpdated(self, selectedID, isFullUpdate, isReqInCoolDown, units):
if isFullUpdate:
selectedIdx = self._searchDP.rebuildList(selectedID, units)
self._doEnableNavButtons(not isReqInCoolDown)
else:
selectedIdx = self._searchDP.updateList(selectedID, units)
if selectedIdx is not None:
self.as_selectByIndexS(selectedIdx)
return
def __setDetails(self, vo):
linkage = CYBER_SPORT_ALIASES.COMMNAD_DETAILS_LINKAGE_JOIN_TO_NONSTATIC
self.as_setDetailsS({'viewLinkage': linkage,
'data': vo})
self.__updateVehicleLabel()
def __refreshDetails(self, idx):
_, vo = self._searchDP.getRally(idx)
self.__setDetails(vo)
def __updateView(self, user):
self._searchDP.updateListItem(user.getID())
self.__refreshDetails(self._searchDP.selectedRallyIndex)
def __recenterList(self):
listReq = self.prbEntity.getBrowser()
if listReq:
listReq.request(req=REQUEST_TYPE.UNITS_RECENTER, unitTypeFlags=self._unitTypeFlags)
# okay decompyling c:\Users\PC\wotsources\files\originals\res\packages\scripts\scripts\client\gui\Scaleform\daapi\view\lobby\cyberSport\CyberSportUnitsListView.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2017.02.03 21:49:44 Střední Evropa (běžný čas)
|
[
"[email protected]"
] | |
f00fe9f24b7f590fb1a7de3a9fae4f9da18bf2ff
|
21e1d00c48c1732cc44af077572299831b93ffc2
|
/1000_PROBLEMS/SimplePythonPrograms/Problem-13.py
|
414ab5620f03a8d4311ccd9c1a6e407e2cce8267
|
[] |
no_license
|
GolamRabbani20/PYTHON-A2Z
|
7be72041407e4417359b3a610ced0919f3939993
|
7c89223f253aa559fa15caacb89c68e0b78ff915
|
refs/heads/master
| 2023-05-09T00:43:03.012963 | 2021-05-26T07:56:56 | 2021-05-26T07:56:56 | 317,953,879 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 173 |
py
|
#Python Program to Count the Number of Digits in a Numbe
x=int(input("Enter a number:"))
s=0
while x>=1:
rem=x%10
s+=1
x=x//10
print("Total number of digits:",s)
|
[
"[email protected]"
] | |
a2dce625a2f9f2cd0e30411bdbfc7ec2277792d5
|
601b8aa76cc86c159c2736107d0779e31a2a7c56
|
/datacube/utils/__init__.py
|
c3cf7fd4d9f2b1a4b74d75f432eb6ed7d1a339a6
|
[
"Apache-2.0"
] |
permissive
|
PhilipeRLeal/datacube-core
|
531b7156b777fa4b631b6af163f65473055a58d9
|
81bed714f2e5cb30a2492f1b0cf3397b79141c3a
|
refs/heads/develop
| 2022-12-13T20:36:52.188166 | 2019-10-16T01:08:03 | 2019-10-23T02:45:40 | 217,332,524 | 2 | 0 |
Apache-2.0
| 2022-12-08T01:08:59 | 2019-10-24T15:29:47 | null |
UTF-8
|
Python
| false | false | 1,712 |
py
|
"""
Utility functions
"""
from .dates import datetime_to_seconds_since_1970, parse_time
from .py import cached_property, ignore_exceptions_if, import_function
from .serialise import jsonify_document
from .uris import is_url, uri_to_local_path, get_part_from_uri, mk_part_uri
from .io import slurp, check_write_path, write_user_secret_file
from .documents import (
InvalidDocException,
SimpleDocNav,
DocReader,
is_supported_document_type,
read_strings_from_netcdf,
read_documents,
validate_document,
NoDatesSafeLoader,
get_doc_offset,
get_doc_offset_safe,
netcdf_extract_string,
without_lineage_sources,
schema_validated,
_readable_offset,
)
from .math import (
unsqueeze_data_array,
iter_slices,
unsqueeze_dataset,
data_resolution_and_offset,
)
from ._misc import (
DatacubeException,
gen_password,
)
__all__ = (
"datetime_to_seconds_since_1970",
"parse_time",
"cached_property",
"ignore_exceptions_if",
"import_function",
"jsonify_document",
"is_url",
"uri_to_local_path",
"get_part_from_uri",
"mk_part_uri",
"InvalidDocException",
"SimpleDocNav",
"DocReader",
"is_supported_document_type",
"read_strings_from_netcdf",
"read_documents",
"validate_document",
"NoDatesSafeLoader",
"get_doc_offset",
"get_doc_offset_safe",
"netcdf_extract_string",
"without_lineage_sources",
"unsqueeze_data_array",
"iter_slices",
"unsqueeze_dataset",
"data_resolution_and_offset",
"DatacubeException",
"schema_validated",
"write_user_secret_file",
"slurp",
"check_write_path",
"gen_password",
"_readable_offset",
)
|
[
"37929162+mergify[bot]@users.noreply.github.com"
] |
37929162+mergify[bot]@users.noreply.github.com
|
4d00a92665d503a391ba2c6d9695fc807d185ad4
|
a97fb0584709e292a475defc8506eeb85bb24339
|
/source code/code/ch1712.py
|
6fe76d7f548707cc2b35f37252628da0f72d23fc
|
[] |
no_license
|
AAQ6291/PYCATCH
|
bd297858051042613739819ed70c535901569079
|
27ec4094be785810074be8b16ef84c85048065b5
|
refs/heads/master
| 2020-03-26T13:54:57.051016 | 2018-08-17T09:05:19 | 2018-08-17T09:05:19 | 144,963,014 | 0 | 0 | null | null | null | null |
BIG5
|
Python
| false | false | 1,116 |
py
|
#!/usr/bin/env python
# -*- coding: cp950 -*-
# 載入wx模組
import wx
class myApp(wx.App):
def OnInit(self):
frame = myFrame()
frame.Show()
return True
# 定義myFrame並繼承wx.Frame類別
class myFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(
self,
None,
-1,
'Up/Down按鈕',
size=(300, 150))
# 建立panel
panel = wx.Panel(self, -1)
# 建立up/down按鈕
spinctrl = wx.SpinCtrl(
panel,
-1,
pos=(10, 20),
size=(60, -1))
# 設定最小值與最大值
spinctrl.SetRange(0, 100)
# 設定一開始的值
spinctrl.SetValue(10)
# 建立up/down按鈕
spinctrl1 = wx.SpinCtrl(
panel,
id = -1,
value = wx.EmptyString,
pos = (10, 50),
size = wx.DefaultSize,
style = wx.SP_ARROW_KEYS|wx.SP_WRAP,
min = 0,
max = 100,
initial = 0,
name = "mySpinCtrl")
def main():
app = myApp()
app.MainLoop()
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
a4b4cf7d907ae028a1c2e6372fe13bc2ba30a25d
|
6a58240cdfcacec18fbfc2a08d75288092cc6da1
|
/data/HASOC/utils.py
|
2c38470bf232fc56e074adaf1ac1d1e25942c2f5
|
[] |
no_license
|
airKlizz/germeval2021toxic
|
132ae9de11bb85c79acbff3a756f8608e32a385a
|
1be57a15509a76b1551c871e73619241499257fe
|
refs/heads/main
| 2023-08-18T04:25:42.387320 | 2021-09-14T12:10:18 | 2021-09-14T12:10:18 | 369,182,623 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 567 |
py
|
import pandas as pd
DATA_FILES = [
"data/HASOC/english_dataset.tsv",
"data/HASOC/german_dataset.tsv",
"data/HASOC/hindi_dataset.tsv",
]
df = pd.concat([pd.read_csv(DATA_FILE, sep="\t") for DATA_FILE in DATA_FILES])
print(df)
TEXT_COLUMN = "text"
LABEL_COLUMN = "task_1"
texts = df[TEXT_COLUMN].values.tolist()
labels = [0 if l.replace(" ", "").lower() == "not" else 1 for l in df[LABEL_COLUMN].values.tolist()]
data = list(zip(texts, labels))
df = pd.DataFrame(data=data, columns=["comment_text", "hf"])
print(df)
df.to_csv("data/HASOC/train.csv")
|
[
"[email protected]"
] | |
fbee8c798cd7d44f148b6dfc4cb1800c034eff07
|
9743d5fd24822f79c156ad112229e25adb9ed6f6
|
/xai/brain/wordbase/nouns/_sobriety.py
|
5a609ca90c82239903ee659ab33783e0970f8b7f
|
[
"MIT"
] |
permissive
|
cash2one/xai
|
de7adad1758f50dd6786bf0111e71a903f039b64
|
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
|
refs/heads/master
| 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 328 |
py
|
#calss header
class _SOBRIETY():
def __init__(self,):
self.name = "SOBRIETY"
self.definitions = [u'the state of being sober: ', u'seriousness: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
|
[
"[email protected]"
] | |
29577dd61fc0b2ab4e46b2f21f32670e2dc1af00
|
1bc7053e7582e43bdd4b943c5700677e07449d3c
|
/pytsite/tpl/_error.py
|
4bb04363d32ffdb9ef93b8c458e31aa365c0ac61
|
[
"MIT"
] |
permissive
|
pytsite/pytsite
|
f92eaa041d85b245fbfcdff44224b24da5d9b73a
|
e4896722709607bda88b4a69400dcde4bf7e5f0a
|
refs/heads/master
| 2021-01-18T01:06:12.357397 | 2019-08-03T02:56:48 | 2019-08-03T02:56:48 | 34,899,242 | 12 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 208 |
py
|
"""PytSite Templates Support Errors
"""
__author__ = 'Oleksandr Shepetko'
__email__ = '[email protected]'
__license__ = 'MIT'
import jinja2 as _jinja
class TemplateNotFound(_jinja.TemplateNotFound):
pass
|
[
"[email protected]"
] | |
cf5162cac66fc297d23a734d6bb7a8848f53e50b
|
9e780f17eb49171d1f234944563225ca22b3c286
|
/postgresqleu/confsponsor/management/commands/sponsor_generate_discount_invoices.py
|
ab716d6862d691c73452bd021d108291aeca7354
|
[
"MIT"
] |
permissive
|
pgeu/pgeu-system
|
e5216d5e90eec6c72770b88a5af4b3fd565cda59
|
885cfdcdadd4a721f72b699a39f26c94d1f636e0
|
refs/heads/master
| 2023-08-06T13:03:55.606562 | 2023-08-03T12:47:37 | 2023-08-03T12:47:37 | 161,434,221 | 15 | 27 |
MIT
| 2023-05-30T11:21:24 | 2018-12-12T04:48:14 |
Python
|
UTF-8
|
Python
| false | false | 6,001 |
py
|
# Generate invoices for discount codes. That is, sponsors that have ordered discount codes,
# that have now either expired or been used fully.
#
from django.core.management.base import BaseCommand
from django.utils import timezone
from django.db import transaction
from django.conf import settings
from datetime import timedelta, time
from django.db.models import Q, F, Count
from postgresqleu.confreg.models import DiscountCode
from postgresqleu.confreg.util import send_conference_mail
from postgresqleu.confsponsor.util import send_conference_sponsor_notification, send_sponsor_manager_email
from postgresqleu.invoices.util import InvoiceManager, InvoiceWrapper
from postgresqleu.util.time import today_global
class Command(BaseCommand):
help = 'Generate invoices for discount codes'
class ScheduledJob:
scheduled_times = [time(5, 19), ]
internal = True
@classmethod
def should_run(self):
return DiscountCode.objects.filter(sponsor__isnull=False, is_invoiced=False).exists()
@transaction.atomic
def handle(self, *args, **options):
# We're always going to process all conferences, since most will not have any
# open discount codes.
filt = Q(sponsor__isnull=False, is_invoiced=False) & (Q(validuntil__lte=today_global()) | Q(num_uses__gte=F('maxuses')))
codes = DiscountCode.objects.annotate(num_uses=Count('registrations')).filter(filt)
for code in codes:
# Either the code has expired, or it is fully used by now. Time to generate the invoice. We'll also
# send an email to the sponsor (and the admins) to inform them of what's happening.
# The invoice will be a one-off one, we don't need a registered manager for it since the
# discounts have already been given out.
if code.count == 0:
# In case there is not a single user, we just notify the user of this and set it to
# invoiced in the system so we don't try again.
code.is_invoiced = True
code.save()
send_conference_sponsor_notification(
code.conference,
"[{0}] Discount code expired".format(code.conference),
"Discount code {0} has expired without any uses.".format(code.code),
)
send_sponsor_manager_email(
code.sponsor,
"Discount code {0} expired".format(code.code),
'confsponsor/mail/discount_expired.txt',
{
'code': code,
'sponsor': code.sponsor,
'conference': code.conference,
},
)
else:
# At least one use, so we generate the invoice
invoicerows = []
for r in code.registrations.all():
if code.discountamount:
# Fixed amount discount. Always apply
discountvalue = code.discountamount
else:
# Percentage discount, so we need to calculate it. Ordered discount codes will
# only support a registration-only style discount code, so only count it
# against that.
discountvalue = r.regtype.cost * code.discountpercentage / 100
invoicerows.append(['Attendee "{0}"'.format(r.fullname), 1, discountvalue, r.conference.vat_registrations])
# All invoices are always due immediately
manager = InvoiceManager()
code.invoice = manager.create_invoice(
code.sponsor_rep,
code.sponsor_rep.email,
"{0} {1}".format(code.sponsor_rep.first_name, code.sponsor_rep.last_name),
'%s\n%s' % (code.sponsor.name, code.sponsor.invoiceaddr),
'{0} discount code {1}'.format(code.conference, code.code),
timezone.now(),
timezone.now() + timedelta(days=1),
invoicerows,
accounting_account=settings.ACCOUNTING_CONFREG_ACCOUNT,
accounting_object=code.conference.accounting_object,
paymentmethods=code.conference.paymentmethods.all(),
)
code.invoice.save()
code.is_invoiced = True
code.save()
wrapper = InvoiceWrapper(code.invoice)
wrapper.email_invoice()
# Now also fire off emails, both to the admins and to all the managers of the sponsor
# (so they know where the invoice was sent).
send_conference_sponsor_notification(
code.conference,
"[{0}] Discount code {1} has been invoiced".format(code.conference, code.code),
"The discount code {0} has been closed,\nand an invoice has been sent to {1}.\n\nA total of {2} registrations used this code, and the total amount was {3}.\n".format(
code.code,
code.sponsor,
len(invoicerows),
code.invoice.total_amount,
),
)
send_sponsor_manager_email(
code.sponsor,
"Discount code {0} has been invoiced".format(code.code),
'confsponsor/mail/discount_invoiced.txt',
{
'code': code,
'conference': code.conference,
'sponsor': code.sponsor,
'invoice': code.invoice,
'curr': settings.CURRENCY_ABBREV,
'expired_time': code.validuntil < today_global(),
},
)
|
[
"[email protected]"
] | |
b7868249902bfe1fb69ee6e3267b9e1aab3b8417
|
6b247e365d97951ae7137bb8140447fe72100ff6
|
/app/urls.py
|
c942d1ca3e5b888307b6d9ccafa4f13c869944b5
|
[] |
no_license
|
tharcissie/Discussion_Board
|
27f251875218174b3285a48b5d1de58653930e5a
|
42b3c14b9993a906dc6bfa142dab0d3ddfac66b8
|
refs/heads/master
| 2023-02-27T18:03:36.251799 | 2021-02-10T15:57:33 | 2021-02-10T15:57:33 | 336,992,064 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 714 |
py
|
from django.urls import path
from .views import home, topics, new_topic, signup, topic_detail,reply_topic, profile, delete_topic,update_topic
urlpatterns = [
path('', home, name='home'),
path('topics/<id>', topics, name='topics'),
path('topics/<id>/create_topic', new_topic, name='create_topic'),
path('signup/', signup, name='signup'),
path('topic_detail/<id>', topic_detail, name='topic_detail'),
path('topic_detail/<id>/reply_topic', reply_topic , name='reply_topic'),
path('profile/<username>', profile, name='profile'),
path('topic_detail/<id>/delete', delete_topic , name='delete_topic'),
path('topic_detail/<id>/update_topic', update_topic , name='update_topic'),
]
|
[
"[email protected]"
] | |
d23690b10700d834432702a5b133c61e359439af
|
50948d4cb10dcb1cc9bc0355918478fb2841322a
|
/azure-mgmt-sql/azure/mgmt/sql/models/restorable_dropped_managed_database_paged.py
|
d6e432c2c35188bdfa6c829f58d7c60fe70a9ab3
|
[
"MIT"
] |
permissive
|
xiafu-msft/azure-sdk-for-python
|
de9cd680b39962702b629a8e94726bb4ab261594
|
4d9560cfd519ee60667f3cc2f5295a58c18625db
|
refs/heads/master
| 2023-08-12T20:36:24.284497 | 2019-05-22T00:55:16 | 2019-05-22T00:55:16 | 187,986,993 | 1 | 0 |
MIT
| 2020-10-02T01:17:02 | 2019-05-22T07:33:46 |
Python
|
UTF-8
|
Python
| false | false | 1,036 |
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.paging import Paged
class RestorableDroppedManagedDatabasePaged(Paged):
"""
A paging container for iterating over a list of :class:`RestorableDroppedManagedDatabase <azure.mgmt.sql.models.RestorableDroppedManagedDatabase>` object
"""
_attribute_map = {
'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[RestorableDroppedManagedDatabase]'}
}
def __init__(self, *args, **kwargs):
super(RestorableDroppedManagedDatabasePaged, self).__init__(*args, **kwargs)
|
[
"[email protected]"
] | |
a42b874d58734949d3b054019a599a8224df6ec5
|
216e6e4957e02780129ab4e917e94cfb975dbfcb
|
/chapter_6/es148.py
|
22764021b34b3dcfda7b4d40ffc5d138be098555
|
[] |
no_license
|
DamManc/workbook
|
d7e72fd1ed098bd7bccb23fa5fd9a102cfff10db
|
2103dbdc8a6635ffd6a1b16b581c98800c9f21a2
|
refs/heads/master
| 2023-04-19T21:26:23.940011 | 2021-05-23T22:37:27 | 2021-05-23T22:37:27 | 335,064,547 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,080 |
py
|
# Exercise 148: Play Bingo
from es147 import *
import copy
def main():
print('Welcome to the Bingo Game!!')
print('------ Your card ------')
card = bingo_card()
print_bingo_card(card)
n_calls = []
for i in range(0, 1000):
copy_card = copy.deepcopy(card)
gamble = False
count = 0
while not gamble:
numbers = []
while len(numbers) < 5:
r = random.randint(1, 75)
if r not in numbers:
numbers.append(r)
gamble = check_card(copy_card, numbers)
if gamble:
print('Your call:', end='\t')
print(f'{numbers} *****************---> WIN {gamble}')
print(f'tot calls: {count}')
n_calls.append(count)
else:
count += 1
print(f'The minimum number of calls is {min(n_calls)}')
print(f'The maximum number of calls is {max(n_calls)}')
print(f'The average number of calls is {sum(n_calls) / 1000}')
if __name__ == '__main__':
main()
|
[
"[email protected]"
] | |
fb5fd8b8750934092164597d06bd43e67d19e4c4
|
15f321878face2af9317363c5f6de1e5ddd9b749
|
/solutions_python/Problem_97/768.py
|
789102ddeb40b07f44f85d54dd152798feab35b8
|
[] |
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,576 |
py
|
import sys
def nbValidPermutation(i, maxi):
strF = str(i)
nb = 0
finded = []
for j in range(len(strF))[:-1]:
other = int(strF[j+1:]+strF[:j+1])
if other > i and other <= maxi and not other in finded:
finded.append(other)
nb += 1
return nb
def buildKelem(i, maxi):
strF = str(i)
nb = 0
finded = []
for j in range(len(strF))[:-1]:
other = int(strF[j+1:]+strF[:j+1])
if other > i and other <= maxi and not other in finded:
finded.append(other)
nb += 1
return sorted(finded,reverse=True)
def buildK():
vals = []
for i in range(2000000):
vals.append(buildKelem(i,2000000))
return vals
def computeSolKno(mini,maxi,kno):
sol = 0
for i in range(mini,maxi-1):
sol += len(kno[i])
counter = 0
while counter < len(kno[i]):
if kno[i][counter] <= maxi:
counter = len(kno[i])
else:
counter += 1
sol -= 1
return sol
def computeSol(mini,maxi):
sol = 0
for i in range(mini,maxi-1):
sol += nbValidPermutation(i,maxi)
return sol
def solve(pathI,pathOut):
kno = buildK()
print 'ok, kno'
counter = 1
fI = file(pathI,'rU')
fO = file(pathOut,'w')
lines = fI.readlines()
for line in lines[1:]:
print line
elem = line.split()
mini = int(elem[0])
maxi = int(elem[1])
sol = computeSolKno(mini,maxi,kno)
fO.write('Case #')
fO.write(str(counter))
fO.write(': ')
fO.write(str(sol))
fO.write('\n')
counter+=1
fI.close()
fO.close()
def main():
args = sys.argv[1:]
solve(args[0],args[1])
main()
|
[
"[email protected]"
] | |
7937ed53104fe047714bf6e587ccd85bf22f019c
|
0437ec3526cc39af1d8d87c2e3c0928b9740e7b9
|
/Node.py
|
19436774365bebf7a66124db81ab1caa08a93e7e
|
[] |
no_license
|
wkcn/Flow
|
b5b2c15a72e2407fcce3e8d2535705acf9f11bb1
|
461b8c181b8bca68c41bb69d20e2a0083596cef9
|
refs/heads/master
| 2021-06-07T07:37:49.633042 | 2016-09-11T14:55:19 | 2016-09-11T14:55:19 | 67,905,517 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 216 |
py
|
#coding=utf-8
class Node:
def __init__(self, x, y):
self.x = x
self.y = y
self.ox = 0
self.oy = 0
self.edges = []
self.neighbors = []
self.redgreen = False
|
[
"[email protected]"
] | |
deec09e0baf2531114f192fdb1aba714d03af881
|
2a266dda00578ea177b231e8f0dfd14a1824d2e6
|
/pw_ls/pw_ls_AB/test_decompress.py
|
1ad25097f68c7ea5778186d55d9da1735b9235dd
|
[] |
no_license
|
sanskrit-lexicon/PWK
|
fbb51c19d9169e4c28d5c9056484c4a53def78eb
|
57d07725b828a95b22b859422287474bfd858ffe
|
refs/heads/master
| 2023-08-17T04:32:37.387691 | 2023-08-15T18:34:46 | 2023-08-15T18:34:46 | 15,903,957 | 3 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 324 |
py
|
#-*- coding:utf-8 -*-
"""make_numberchange2b.py
"""
from __future__ import print_function
import sys, re,codecs
from make_numberchange2b import lsnumstr_to_intseq, decompress
if __name__=="__main__":
x = sys.argv[1]
seq,flag = lsnumstr_to_intseq(x)
print(flag,seq)
if flag:
d,flag1 = decompress(seq)
print(flag1,d)
|
[
"[email protected]"
] | |
3c6efaa9740b328d1508fc75df89820d4fa4ed29
|
7c01cd1df700a68965a22a041fcf0425fb5b8d2e
|
/api/tacticalrmm/apiv3/urls.py
|
934da836b1079809c5346d405b12aac2207b14af
|
[
"MIT"
] |
permissive
|
socmap/tacticalrmm
|
61de15244c61edfb343314bd9e7d832b473df38e
|
72d55a010b8a55583a955daf5546b21273e5a5f0
|
refs/heads/master
| 2023-03-17T23:50:37.565735 | 2021-03-05T23:05:17 | 2021-03-05T23:05:17 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 983 |
py
|
from django.urls import path
from . import views
urlpatterns = [
path("checkrunner/", views.CheckRunner.as_view()),
path("<str:agentid>/checkrunner/", views.CheckRunner.as_view()),
path("<str:agentid>/checkinterval/", views.CheckRunnerInterval.as_view()),
path("<int:pk>/<str:agentid>/taskrunner/", views.TaskRunner.as_view()),
path("meshexe/", views.MeshExe.as_view()),
path("sysinfo/", views.SysInfo.as_view()),
path("newagent/", views.NewAgent.as_view()),
path("software/", views.Software.as_view()),
path("installer/", views.Installer.as_view()),
path("checkin/", views.CheckIn.as_view()),
path("syncmesh/", views.SyncMeshNodeID.as_view()),
path("choco/", views.Choco.as_view()),
path("winupdates/", views.WinUpdates.as_view()),
path("superseded/", views.SupersededWinUpdate.as_view()),
path("<int:pk>/chocoresult/", views.ChocoResult.as_view()),
path("<str:agentid>/recovery/", views.AgentRecovery.as_view()),
]
|
[
"[email protected]"
] | |
32370305956bdaa9a3226650e42697ee227b1f90
|
9ac405635f3ac9332e02d0c7803df757417b7fee
|
/cotizaciones/migrations/0042_auto_20191019_0954.py
|
236d57369a78000a98643a41cf309646161b8d74
|
[] |
no_license
|
odecsarrollo/07_intranet_proyectos
|
80af5de8da5faeb40807dd7df3a4f55f432ff4c0
|
524aeebb140bda9b1bf7a09b60e54a02f56fec9f
|
refs/heads/master
| 2023-01-08T04:59:57.617626 | 2020-09-25T18:01:09 | 2020-09-25T18:01:09 | 187,250,667 | 0 | 0 | null | 2022-12-30T09:36:37 | 2019-05-17T16:41:35 |
JavaScript
|
UTF-8
|
Python
| false | false | 838 |
py
|
# Generated by Django 2.2.6 on 2019-10-19 14:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cotizaciones', '0041_cotizacion_revisada'),
]
operations = [
migrations.AlterField(
model_name='cotizacion',
name='estado',
field=models.CharField(choices=[('Cita/Generación Interés', 'Cita/Generación Interés'), ('Configurando Propuesta', 'Configurando Propuesta'), ('Cotización Enviada', 'Cotización Enviada'), ('Evaluación Técnica y Económica', 'Evaluación Técnica y Económica'), ('Aceptación de Terminos y Condiciones', 'Aceptación de Terminos y Condiciones'), ('Cierre (Aprobado)', 'Cierre (Aprobado)'), ('Aplazado', 'Aplazado'), ('Cancelado', 'Cancelado')], max_length=200, null=True),
),
]
|
[
"[email protected]"
] | |
017d19b97fd8f6aab8a08babe66bec2918da227a
|
233928d206e13e068cf8cb5ff7888c9a2d84ad61
|
/swea/D5/swea_1242_암호코드스캔.py
|
36d01ac84b27da5410b011fd26f7544b5e741c33
|
[] |
no_license
|
Jinwoongma/Algorithm
|
7f6daa2d3c2c361059c09fb4fe287b1cce4863e2
|
78803f4572f1416451a9f4f31f53b7d653f74d4a
|
refs/heads/master
| 2022-10-07T22:53:20.333329 | 2020-06-07T13:27:47 | 2020-06-07T13:27:47 | 237,114,107 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,455 |
py
|
hcode = {'0':'0000', '1':'0001', '2':'0010', '3':'0011',
'4':'0100', '5':'0101', '6':'0110', '7':'0111',
'8':'1000', '9':'1001', 'A':'1010', 'B':'1011',
'C':'1100', 'D':'1101', 'E':'1110', 'F':'1111'}
scode = {211:0, 221:1, 122:2, 411:3, 132:4, 231:5, 114:6, 312:7, 213:8, 112:9}
TC = int(input())
for tc in range(TC):
R, C = map(int, input().split())
data = [input() for _ in range(R)]
answer = 0
mat = [''] * R
for i in range(R):
for j in range(C):
mat[i] += hcode[data[i][j]]
for i in range(1, len(mat) - 6):
j = C * 4 - 1
while j > 56:
if mat[i][j] == '1' and mat[i - 1][j] == '0':
c = [0] * 8
for k in range(7, -1, -1):
c1, c2, c3 = 0, 0, 0
while mat[i][j] == '1': c3 += 1; j -= 1
while mat[i][j] == '0': c2 += 1; j -= 1
while mat[i][j] == '1': c1 += 1; j -= 1
while mat[i][j] == '0' and k: j -= 1
MIN = min(c1, c2, c3)
c1, c2, c3 = c1 // MIN, c2 // MIN, c3 // MIN
c[k] = scode[100 * c1 + 10 * c2 + c3]
t = 3 * (c[0] + c[2] + c[4] + c[6]) + c[1] + c[3] + c[5] + c[7]
if t % 10 == 0:
answer += sum(c)
j -= 1
print('#{} {}'.format(tc + 1, answer))
|
[
"[email protected]"
] | |
7f18b56489ef36f4e2391878671a569f4252027d
|
1ac9f756c5bab3ae8ae2df8daa596b6fc55b63d1
|
/backend/accounts/views.py
|
c3104129fe20c9ad274477dc8f541600ce56fc03
|
[] |
no_license
|
woorud/facebook_clone
|
6520adbf5e5aaeb3f517abe7920a0b90096e4f89
|
a5b96f215c74e2960465cd2a96568e57db92043c
|
refs/heads/master
| 2022-12-11T18:26:07.648768 | 2020-08-29T14:45:43 | 2020-08-29T14:45:43 | 277,793,569 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,907 |
py
|
from django.shortcuts import render, redirect
from .models import *
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout as django_logout
from .forms import SignupForm, LoginForm
from django.shortcuts import get_object_or_404
from django.contrib.auth import get_user_model
from django.http import HttpResponse
import json
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST, request.FILES)
if form.is_valid():
user = form.save()
return redirect('accounts:login')
else:
form = SignupForm()
return render(request, 'accounts/signup.html', {
'form':form,
})
def login_check(request):
if request.method == 'POST':
form = LoginForm(request.POST)
name = request.POST.get('username')
pwd = request.POST.get('password')
user = authenticate(username = name, password = pwd)
if user is not None:
login(request, user)
return redirect('/')
else:
form = LoginForm()
return render(request, 'accounts/login.html', {
'form':form
})
def logout(request):
django_logout(request)
return redirect('/')
def create_friend_request(request):
user_id = request.POST.get('pk', None)
user = request.user
target_user = get_object_or_404(get_user_model(), pk=user_id)
try:
user.friend_requests.create(from_user=user, to_user=target_user)
context = {'result': 'succes'}
except Exception as ex:
print('에러가 발생했습니다', ex) # ex는 발생한 에러의 이름을 받아오는 변수
context = {
'result': 'error',
}
return HttpResponse(json.dumps(context), content_type="application/json")
def accept_friend_request(request):
friend_request_id = request.POST.get('pk', None)
# 요청
friend_request = FriendRequest.objects.get(pk=friend_request_id)
# 커런트유저 가져오기
from_user = friend_request.from_user
# 타겟유저 가져오기
to_user = friend_request.to_user
try:
# 친구관계 생성
# room_name= "{},{}".format(from_user.username, to_user.username)
# 채팅방을 만들고
# room = Room.objects.create(room_name=room_name)
Friend.objects.create(user=from_user, current_user=to_user, room=room)
Friend.objects.create(user=to_user, current_user=from_user, room=room)
# 현재 만들어진 친구요청을 삭제
friend_request.delete()
context = {
'result': 'success',
}
except Exception as ex:
print('에러가 발생했습니다', ex)
context = {
'result': 'error',
}
return HttpResponse(json.dumps(context), content_type="application/json")
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.