uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
62f7ce29f8a9e9fbfe833896
train
function
@app.route("/", methods=['GET', 'POST']) def main(): form = SymbolSearch(csrf_enabled=False) if request.method == 'POST' and form.validate(): return redirect(url_for('results', symbol=request.form['symbol'], trend1=request.form['trend1'], trend2=re...
@app.route("/", methods=['GET', 'POST']) def main():
form = SymbolSearch(csrf_enabled=False) if request.method == 'POST' and form.validate(): return redirect(url_for('results', symbol=request.form['symbol'], trend1=request.form['trend1'], trend2=request.form['trend2'])) return render_template('se...
[key]['y'] = df[key].values lines[key]['name'] = key lines_plotly = [lines[key] for key in df] return lines_plotly # # Main app # app = Flask(__name__) @app.route("/", methods=['GET', 'POST']) def main():
64
64
78
13
51
yhilpisch/rpi
doc/build/html/_downloads/stock_interactive.py
Python
main
main
48
55
48
49
99a58bc4a96117223ee5ef887349adff442f30c3
bigcode/the-stack
train
8b240fbddc2c6be953c433f7
train
function
def cadastrar(*args): try: telaProduto = args[0] telaErro = args[1] cursor = args[2] banco10 = args[3] QtWidgets = args[4] sabor = telaProduto.produto_adc.text() valor = telaProduto.valor_adc.text() sabor = sabor.upper() tamanho = 'Seis' ...
def cadastrar(*args):
try: telaProduto = args[0] telaErro = args[1] cursor = args[2] banco10 = args[3] QtWidgets = args[4] sabor = telaProduto.produto_adc.text() valor = telaProduto.valor_adc.text() sabor = sabor.upper() tamanho = 'Seis' sql = "insert into ...
def cadastrar(*args):
5
97
324
5
0
kallif003/Sistema-Delivery
modulo_cadastro/cadastrar_adicionais_seis_pedacos.py
Python
cadastrar
cadastrar
1
37
1
1
48a943f24d71ddeab2d9b68b1641cfbcc1f8536f
bigcode/the-stack
train
f0a81e42c28614a2dd74cc05
train
function
def word_count(input_file, output_file, min_length=1): """ Load a file, calculate the frequencies of each word in the file and save in a new file the words, counts and percentages of the total in descending order. Only words whose length is >= min_length are included. """ lines = load_text(...
def word_count(input_file, output_file, min_length=1):
""" Load a file, calculate the frequencies of each word in the file and save in a new file the words, counts and percentages of the total in descending order. Only words whose length is >= min_length are included. """ lines = load_text(input_file) counts = calculate_word_counts(lines) ...
0 for count in counts: total += count[1] tuples = [(word, count, (float(count) / total) * 100.0) for (word, count) in counts] return tuples def word_count(input_file, output_file, min_length=1):
64
64
131
14
49
coderefinery/git-archeology-exercise
source/wordcount.py
Python
word_count
word_count
87
99
87
87
ecc3cf0f815ea6cf9dd3dba196a7496592237e9b
bigcode/the-stack
train
ee8ec87baab9c55a0fcc7359
train
function
def update_word_counts(line, counts): """ Given a string, parse the string and update a dictionary of word counts (mapping words to counts of their frequencies). DELIMITERS are removed before the string is parsed. The function is case-insensitive and words in the dictionary are in lower-case. ""...
def update_word_counts(line, counts):
""" Given a string, parse the string and update a dictionary of word counts (mapping words to counts of their frequencies). DELIMITERS are removed before the string is parsed. The function is case-insensitive and words in the dictionary are in lower-case. """ for purge in DELIMITERS: ...
a file, in the form "word count percentage", one tuple per line. """ with open(filename, 'w') as output: for count in counts: output.write("%s\n" % " ".join(str(c) for c in count)) def update_word_counts(line, counts):
64
64
132
8
56
coderefinery/git-archeology-exercise
source/wordcount.py
Python
update_word_counts
update_word_counts
24
39
24
24
b0e525752929958556138c116c7a6904bb6d886b
bigcode/the-stack
train
db8b5d4059c637904dba6a1b
train
function
def filter_word_counts(counts, min_length=1): """ Given a list of (word, count) tuples, create a new list with only those tuples whose word is >= min_length. """ stripped = [] for (word, count) in counts: if len(word) >= min_length: stripped.append((word, count)) return s...
def filter_word_counts(counts, min_length=1):
""" Given a list of (word, count) tuples, create a new list with only those tuples whose word is >= min_length. """ stripped = [] for (word, count) in counts: if len(word) >= min_length: stripped.append((word, count)) return stripped
an ordered list of tuples (word, count). The list is ordered by decreasing count, unless increase is True. """ return sorted(list(counts.items()), key=lambda key_value: key_value[1], reverse=decrease) def filter_word_counts(counts, min_length=1):
64
64
80
12
52
coderefinery/git-archeology-exercise
source/wordcount.py
Python
filter_word_counts
filter_word_counts
63
72
63
63
eb7eee5fc01055500022de012bd020c1c8f5016a
bigcode/the-stack
train
56499dff9a082d738cc79f64
train
function
def calculate_word_counts(lines): """ Given a list of strings, parse each string and create a dictionary of word counts (mapping words to counts of their frequencies). DELIMITERS are removed before the string is parsed. The function is case-insensitive and words in the dictionary are in lower-case. ...
def calculate_word_counts(lines):
""" Given a list of strings, parse each string and create a dictionary of word counts (mapping words to counts of their frequencies). DELIMITERS are removed before the string is parsed. The function is case-insensitive and words in the dictionary are in lower-case. """ counts = {} for li...
IMITERS: line = line.replace(purge, " ") words = line.split() for word in words: word = word.lower().strip() if word in counts: counts[word] += 1 else: counts[word] = 1 def calculate_word_counts(lines):
64
64
91
6
57
coderefinery/git-archeology-exercise
source/wordcount.py
Python
calculate_word_counts
calculate_word_counts
41
51
41
41
1bff9d57996dfb0983fcb3be2af88485b7c4d039
bigcode/the-stack
train
1a515f347911378e865584e1
train
function
def save_word_counts(filename, counts): """ Save a list of [word, count, percentage] lists to a file, in the form "word count percentage", one tuple per line. """ with open(filename, 'w') as output: for count in counts: output.write("%s\n" % " ".join(str(c) for c in count))
def save_word_counts(filename, counts):
""" Save a list of [word, count, percentage] lists to a file, in the form "word count percentage", one tuple per line. """ with open(filename, 'w') as output: for count in counts: output.write("%s\n" % " ".join(str(c) for c in count))
_text(filename): """ Load lines from a plain-text file and return these as a list, with trailing newlines stripped. """ with open(filename, "r") as input_fd: lines = input_fd.read().splitlines() return lines def save_word_counts(filename, counts):
64
64
80
8
55
coderefinery/git-archeology-exercise
source/wordcount.py
Python
save_word_counts
save_word_counts
15
22
15
15
597124d28e6f2a5fcd8883f7f0c9479c73757a47
bigcode/the-stack
train
4b828fe718ffcef1983d0a7e
train
function
def word_count_dict_to_tuples(counts, decrease=True): """ Given a dictionary of word counts (mapping words to counts of their frequencies), convert this into an ordered list of tuples (word, count). The list is ordered by decreasing count, unless increase is True. """ return sorted(list(coun...
def word_count_dict_to_tuples(counts, decrease=True):
""" Given a dictionary of word counts (mapping words to counts of their frequencies), convert this into an ordered list of tuples (word, count). The list is ordered by decreasing count, unless increase is True. """ return sorted(list(counts.items()), key=lambda key_value: key_value[1], ...
are removed before the string is parsed. The function is case-insensitive and words in the dictionary are in lower-case. """ counts = {} for line in lines: update_word_counts(line, counts) return counts def word_count_dict_to_tuples(counts, decrease=True):
64
64
88
13
50
coderefinery/git-archeology-exercise
source/wordcount.py
Python
word_count_dict_to_tuples
word_count_dict_to_tuples
53
61
53
53
002d4048721adb128d9227acf0e14b3908468ce6
bigcode/the-stack
train
0105749d67648b9e4a6ae427
train
function
def load_text(filename): """ Load lines from a plain-text file and return these as a list, with trailing newlines stripped. """ with open(filename, "r") as input_fd: lines = input_fd.read().splitlines() return lines
def load_text(filename):
""" Load lines from a plain-text file and return these as a list, with trailing newlines stripped. """ with open(filename, "r") as input_fd: lines = input_fd.read().splitlines() return lines
import sys DELIMITERS = ". , ; : ? $ @ ^ < > # % ` ! * - = ( ) [ ] { } / \" '".split() def load_text(filename):
40
64
58
5
35
coderefinery/git-archeology-exercise
source/wordcount.py
Python
load_text
load_text
6
13
6
6
405769c7ea8cc92b6ef49abe744e7e5f97c3d602
bigcode/the-stack
train
72c0e5a66d0baf0669efcc9c
train
function
def calculate_percentages(counts): """ Given a list of (word, count) tuples, create a new list (word, count, percentage) where percentage is the percentage number of occurrences of this word compared to the total number of words. """ total = 0 for count in counts: total += count[1] ...
def calculate_percentages(counts):
""" Given a list of (word, count) tuples, create a new list (word, count, percentage) where percentage is the percentage number of occurrences of this word compared to the total number of words. """ total = 0 for count in counts: total += count[1] tuples = [(word, count, (float(c...
) tuples, create a new list with only those tuples whose word is >= min_length. """ stripped = [] for (word, count) in counts: if len(word) >= min_length: stripped.append((word, count)) return stripped def calculate_percentages(counts):
64
64
110
7
56
coderefinery/git-archeology-exercise
source/wordcount.py
Python
calculate_percentages
calculate_percentages
74
85
74
74
9a2a82ab6659f155c13fe9ec4f8785b1302ef9d9
bigcode/the-stack
train
3841fc8c94db6443acbae4d5
train
class
class handleBpCondition(pykd.eventHandler): targetEprocess="" def __init__(self,addr,targetProcessName): self.bp_init = pykdPackage.setBp(addr, self.enter_call_back) self.bp_end = None self.targetEprocess = pykdPackage.getEprocessByName(targetProcessName) print("handleBpCondition...
class handleBpCondition(pykd.eventHandler):
targetEprocess="" def __init__(self,addr,targetProcessName): self.bp_init = pykdPackage.setBp(addr, self.enter_call_back) self.bp_end = None self.targetEprocess = pykdPackage.getEprocessByName(targetProcessName) print("handleBpCondition ok") print(addr) def enter_call...
pykdPackage #enter_call_back返回false表示处理了,true表示没有处理 #构造函数传递的是要hook地址,16进制数或者10进制数 #targetProcessName需要对哪个进程进行关照 class handleBpCondition(pykd.eventHandler):
64
64
184
10
53
iam0xcc/PycharmPykd
windbgPy/BpCondition.py
Python
handleBpCondition
handleBpCondition
9
29
9
9
2a5175e645b44b306f05e69a43a934a105005893
bigcode/the-stack
train
c892ebcf691ab8c56d25653b
train
class
class trace(pykd.eventHandler): startAddr=0 endAddr=0 def __init__(self,startAddr,endAddr,constraitStartAddr,constraitEndaddr): pass
class trace(pykd.eventHandler):
startAddr=0 endAddr=0 def __init__(self,startAddr,endAddr,constraitStartAddr,constraitEndaddr): pass
the hood ret_val = hex(pykd.reg("al")) log.write(self.out + ret_val + "\n") return False # 从startAddr跟踪到endAddr,限定函数跳转在constraitStartAddr到constraitEndaddr class trace(pykd.eventHandler):
64
64
41
8
55
iam0xcc/PycharmPykd
windbgPy/BpCondition.py
Python
trace
trace
31
35
31
31
f9ac58ebe9c5a33adf468b8f8cb2609e7c4e87f5
bigcode/the-stack
train
62dcc0897c3b03fafc06e9e4
train
class
class YamahaDevice(MediaPlayerDevice): """Representation of a Yamaha device.""" def __init__(self, name, receiver, source_ignore, source_names): """Initialize the Yamaha Receiver.""" self._receiver = receiver self._muted = False self._volume = 0 self._pwstate = STATE_OFF...
class YamahaDevice(MediaPlayerDevice):
"""Representation of a Yamaha device.""" def __init__(self, name, receiver, source_ignore, source_names): """Initialize the Yamaha Receiver.""" self._receiver = receiver self._muted = False self._volume = 0 self._pwstate = STATE_OFF self._current_source = None ...
) if discovery_info is not None: name = discovery_info.get('name') model = discovery_info.get('model_name') ctrl_url = discovery_info.get('control_url') desc_url = discovery_info.get('description_url') if ctrl_url in hass.data[KNOWN]: _LOGGER.info("%s already man...
255
256
1,451
7
248
adolfoeliazat/voidhomecontrol
homeassistant/components/media_player/yamaha.py
Python
YamahaDevice
YamahaDevice
92
293
92
92
6c47f2072a173af5579cebff22e5ff1387a051b6
bigcode/the-stack
train
b697e53d9747a5b61927fb09
train
function
def setup_platform(hass, config, add_devices, discovery_info=None): """Set up the Yamaha platform.""" import rxv # keep track of configured receivers so that we don't end up # discovering a receiver dynamically that we have static config # for. if hass.data.get(KNOWN, None) is None: hass...
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Yamaha platform.""" import rxv # keep track of configured receivers so that we don't end up # discovering a receiver dynamically that we have static config # for. if hass.data.get(KNOWN, None) is None: hass.data[KNOWN] = set() name = config.get(CONF_NAME) host = co...
ivers' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_HOST): cv.string, vol.Optional(CONF_SOURCE_IGNORE, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_ZONE_IGNORE, default=[]): vol.All(cv.ensu...
113
113
379
15
98
adolfoeliazat/voidhomecontrol
homeassistant/components/media_player/yamaha.py
Python
setup_platform
setup_platform
46
89
46
46
30d88dfa17084a3b412de298898077eb1117525d
bigcode/the-stack
train
6fa87fdbcd3c7f457eeedc48
train
function
def main(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "locfilm.config") os.environ.setdefault("DJANGO_CONFIGURATION", "Local") try: from configurations.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that th...
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "locfilm.config") os.environ.setdefault("DJANGO_CONFIGURATION", "Local") try: from configurations.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # ...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main():
26
64
155
3
22
locfilm/locfilm-api
manage.py
Python
main
main
7
26
7
7
866fa2e096e321d0e224a47540e267f17fefcb07
bigcode/the-stack
train
797356901d6869493b5af49d
train
class
class GetAttachment(EWSAccountService): """ MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/getattachment-operation """ SERVICE_NAME = 'GetAttachment' element_container_name = '{%s}Attachments' % MNS streaming = True def call(self, items, include_mime_...
class GetAttachment(EWSAccountService):
""" MSDN: https://docs.microsoft.com/en-us/exchange/client-developer/web-service-reference/getattachment-operation """ SERVICE_NAME = 'GetAttachment' element_container_name = '{%s}Attachments' % MNS streaming = True def call(self, items, include_mime_content): return self._get_eleme...
from ..util import create_element, add_xml_child, DummyResponse, StreamingBase64Parser, StreamingContentHandler, \ ElementNotFound, MNS from .common import EWSAccountService, create_attachment_ids_element class GetAttachment(EWSAccountService):
54
172
576
8
45
kraglik/exchangelib
exchangelib/services/get_attachment.py
Python
GetAttachment
GetAttachment
6
60
6
6
3543d3a6a54d2fc27a77b11c14c3dffec0368571
bigcode/the-stack
train
3b9567dc0db579a7640446a2
train
function
def driver(): driver = webdriver.Chrome(chromedriver,chrome_options=options) for url in urls: driver.get('https://www.youtube.com/{}/videos?view=0&sort=p&flow=grid'.format(url)) content = driver.page_source.encode('utf-8').strip() soup = BeautifulSoup(content,'html.parser') time....
def driver():
driver = webdriver.Chrome(chromedriver,chrome_options=options) for url in urls: driver.get('https://www.youtube.com/{}/videos?view=0&sort=p&flow=grid'.format(url)) content = driver.page_source.encode('utf-8').strip() soup = BeautifulSoup(content,'html.parser') time.sleep(2) ...
from selenium import webdriver import time chromedriver = '/home/facundoic/Desktop/GitHub/Repositories/MLprojects/chromedriver' options = webdriver.ChromeOptions() options.add_argument('--start-maximized') options.add_argument('-ignore-certificate-errors') options.add_argument('--incognito') urls = [ 'DotCSV', ...
86
86
287
3
83
facundoic/MLprojects
src/scraper.py
Python
driver
driver
16
40
16
16
a76a4b641d9d06752cfe51fc9180b7674d772e7f
bigcode/the-stack
train
dab04bb00a0b59c63d313624
train
function
def _authentication_policy(credential): authentication_policy = None if credential is None: raise ValueError("Parameter 'credential' must not be None.") if isinstance(credential, AzureKeyCredential): authentication_policy = AzureKeyCredentialPolicy( name="Ocp-Apim-Subscription-Ke...
def _authentication_policy(credential):
authentication_policy = None if credential is None: raise ValueError("Parameter 'credential' must not be None.") if isinstance(credential, AzureKeyCredential): authentication_policy = AzureKeyCredentialPolicy( name="Ocp-Apim-Subscription-Key", credential=credential ) ...
io import TextAnalyticsClient as _TextAnalyticsClient from .._policies import TextAnalyticsResponseHookPolicy from .._user_agent import USER_AGENT from .._version import DEFAULT_API_VERSION if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential def _authentication_policy(credential):
64
64
128
7
56
vincenttran-msft/azure-sdk-for-python
sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_base_client_async.py
Python
_authentication_policy
_authentication_policy
16
29
16
16
ccd54089a1b46fffb5b5ece6f7625080fb055b71
bigcode/the-stack
train
ad18e61070af45503b5ffe0a
train
class
class AsyncTextAnalyticsClientBase: def __init__( self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: http_logging_policy = HttpLoggingPolicy(**kwargs) http_logging_policy.allowed_header_names.update( ...
class AsyncTextAnalyticsClientBase:
def __init__( self, endpoint: str, credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: http_logging_policy = HttpLoggingPolicy(**kwargs) http_logging_policy.allowed_header_names.update( { "Operation-L...
if credential is None: raise ValueError("Parameter 'credential' must not be None.") if isinstance(credential, AzureKeyCredential): authentication_policy = AzureKeyCredentialPolicy( name="Ocp-Apim-Subscription-Key", credential=credential ) elif credential is not None and ...
123
123
412
7
115
vincenttran-msft/azure-sdk-for-python
sdk/textanalytics/azure-ai-textanalytics/azure/ai/textanalytics/aio/_base_client_async.py
Python
AsyncTextAnalyticsClientBase
AsyncTextAnalyticsClientBase
32
89
32
32
1b6b0f5992e3244776ff08fa9d008741fe746b24
bigcode/the-stack
train
4125e107f141c0084a063fdb
train
class
class PointCloudDot(Mobject1D): CONFIG = { "radius": 0.075, "stroke_width": 2, "density": DEFAULT_POINT_DENSITY_1D, "color": YELLOW, } def __init__(self, center=ORIGIN, **kwargs): Mobject1D.__init__(self, **kwargs) self.shift(center) def generate_points(...
class PointCloudDot(Mobject1D):
CONFIG = { "radius": 0.075, "stroke_width": 2, "density": DEFAULT_POINT_DENSITY_1D, "color": YELLOW, } def __init__(self, center=ORIGIN, **kwargs): Mobject1D.__init__(self, **kwargs) self.shift(center) def generate_points(self): self.add_points([...
*pmobs, **kwargs): if not all([isinstance(m, PMobject) for m in pmobs]): raise Exception("All submobjects must be of type PMobject") super().__init__(**kwargs) self.add(*pmobs) class PointCloudDot(Mobject1D):
64
64
153
9
55
unAlpha/AgManim
manimlib/mobject/types/point_cloud_mobject.py
Python
PointCloudDot
PointCloudDot
232
249
232
232
030196cc9d918f02895a62c7e28904bbe75c3532
bigcode/the-stack
train
287426c52f159b9f2c9316da
train
class
class Point(PMobject): CONFIG = { "color": BLACK, } def __init__(self, location=ORIGIN, **kwargs): PMobject.__init__(self, **kwargs) self.add_points([location])
class Point(PMobject):
CONFIG = { "color": BLACK, } def __init__(self, location=ORIGIN, **kwargs): PMobject.__init__(self, **kwargs) self.add_points([location])
r * (np.cos(theta) * RIGHT + np.sin(theta) * UP) for r in np.arange(0, self.radius, self.epsilon) for theta in np.arange(0, 2 * np.pi, self.epsilon / r) ]) class Point(PMobject):
63
64
51
6
57
unAlpha/AgManim
manimlib/mobject/types/point_cloud_mobject.py
Python
Point
Point
252
259
252
252
13fd8fbae46cd519552f146b020e65da02db2d1b
bigcode/the-stack
train
e754cd97883d19671a31c814
train
class
class PGroup(PMobject): def __init__(self, *pmobs, **kwargs): if not all([isinstance(m, PMobject) for m in pmobs]): raise Exception("All submobjects must be of type PMobject") super().__init__(**kwargs) self.add(*pmobs)
class PGroup(PMobject):
def __init__(self, *pmobs, **kwargs): if not all([isinstance(m, PMobject) for m in pmobs]): raise Exception("All submobjects must be of type PMobject") super().__init__(**kwargs) self.add(*pmobs)
"density": DEFAULT_POINT_DENSITY_2D, } def __init__(self, **kwargs): digest_config(self, kwargs) self.epsilon = 1.0 / self.density Mobject.__init__(self, **kwargs) class PGroup(PMobject):
64
64
69
7
57
unAlpha/AgManim
manimlib/mobject/types/point_cloud_mobject.py
Python
PGroup
PGroup
224
229
224
224
c039ba4b08dbcffc9cf0ee115bb1e80f3674d8c0
bigcode/the-stack
train
d34ebc2ea95dafe8794ba681
train
class
class Mobject2D(PMobject): CONFIG = { "density": DEFAULT_POINT_DENSITY_2D, } def __init__(self, **kwargs): digest_config(self, kwargs) self.epsilon = 1.0 / self.density Mobject.__init__(self, **kwargs)
class Mobject2D(PMobject):
CONFIG = { "density": DEFAULT_POINT_DENSITY_2D, } def __init__(self, **kwargs): digest_config(self, kwargs) self.epsilon = 1.0 / self.density Mobject.__init__(self, **kwargs)
points = [start] else: epsilon = self.epsilon / length points = [ interpolate(start, end, t) for t in np.arange(0, 1, epsilon) ] self.add_points(points, color=color) class Mobject2D(PMobject):
64
64
70
9
55
unAlpha/AgManim
manimlib/mobject/types/point_cloud_mobject.py
Python
Mobject2D
Mobject2D
213
221
213
213
2e07d5edd0cfb30e81d4ea083d4cebac16bb05e0
bigcode/the-stack
train
0e6bf31ee0d03796ad444ca8
train
class
class PMobject(Mobject): CONFIG = { "stroke_width": DEFAULT_STROKE_WIDTH, } def reset_points(self): self.rgbas = np.zeros((0, 4)) self.points = np.zeros((0, 3)) return self def get_array_attrs(self): return Mobject.get_array_attrs(self) + ["rgbas"] def add_...
class PMobject(Mobject):
CONFIG = { "stroke_width": DEFAULT_STROKE_WIDTH, } def reset_points(self): self.rgbas = np.zeros((0, 4)) self.points = np.zeros((0, 3)) return self def get_array_attrs(self): return Mobject.get_array_attrs(self) + ["rgbas"] def add_points(self, points, rgba...
from manimlib.constants import * from manimlib.mobject.mobject import Mobject from manimlib.utils.bezier import interpolate from manimlib.utils.color import color_gradient from manimlib.utils.color import color_to_rgba from manimlib.utils.color import rgba_to_color from manimlib.utils.config_ops import digest_config fr...
104
256
1,333
6
97
unAlpha/AgManim
manimlib/mobject/types/point_cloud_mobject.py
Python
PMobject
PMobject
12
185
12
12
f92d77455ba8a2ca417ec86a0739dfd5b86c1015
bigcode/the-stack
train
6db5f8972d338cfdbf6102d6
train
class
class Mobject1D(PMobject): CONFIG = { "density": DEFAULT_POINT_DENSITY_1D, } def __init__(self, **kwargs): digest_config(self, kwargs) self.epsilon = 1.0 / self.density Mobject.__init__(self, **kwargs) def add_line(self, start, end, color=None): start, end = lis...
class Mobject1D(PMobject):
CONFIG = { "density": DEFAULT_POINT_DENSITY_1D, } def __init__(self, **kwargs): digest_config(self, kwargs) self.epsilon = 1.0 / self.density Mobject.__init__(self, **kwargs) def add_line(self, start, end, color=None): start, end = list(map(np.array, [start, end...
for attr in self.get_array_attrs(): full_array = getattr(mobject, attr) partial_array = full_array[lower_index:upper_index] setattr(self, attr, partial_array) # TODO, Make the two implementations bellow non-redundant class Mobject1D(PMobject):
64
64
169
9
54
unAlpha/AgManim
manimlib/mobject/types/point_cloud_mobject.py
Python
Mobject1D
Mobject1D
189
210
189
189
9f9e41e6938059272f16600fc8e2e86330487a6f
bigcode/the-stack
train
23adb62df67f2a963bfe57f6
train
class
class ESEDBParserTest(test_lib.ParserTestCase): """Tests for the Extensible Storage Engine database (ESEDB) file parser.""" @shared_test_lib.skipUnlessHasTestFile(['Windows.edb']) def testParse(self): """Tests the Parse function.""" parser = esedb.ESEDBParser() storage_writer = self._ParseFile(['Wind...
class ESEDBParserTest(test_lib.ParserTestCase):
"""Tests for the Extensible Storage Engine database (ESEDB) file parser.""" @shared_test_lib.skipUnlessHasTestFile(['Windows.edb']) def testParse(self): """Tests the Parse function.""" parser = esedb.ESEDBParser() storage_writer = self._ParseFile(['Windows.edb'], parser) # Extensible Storage Eng...
"""Tests for the Extensible Storage Engine (ESE) database files (EDB) parser.""" from __future__ import unicode_literals import unittest from plaso.parsers import esedb from plaso.parsers import esedb_plugins # pylint: disable=unused-import from tests import test_lib as shared_test_lib from tests.parsers import te...
87
87
291
12
74
ir4n6/plaso
tests/parsers/esedb.py
Python
ESEDBParserTest
ESEDBParserTest
16
48
16
16
9337ac6b78387f54920b7cadfed33043083d24da
bigcode/the-stack
train
6f28218e82df7fc1eaa20610
train
function
def queue_is_empty(config): resp = requests.get( url='http://localhost:15672/api/queues/%2F/{}'.format(QDESC['name']), auth=(config['user'], config['password']), timeout=1, ) return resp.json()['messages'] == 0
def queue_is_empty(config):
resp = requests.get( url='http://localhost:15672/api/queues/%2F/{}'.format(QDESC['name']), auth=(config['user'], config['password']), timeout=1, ) return resp.json()['messages'] == 0
QDESC, callback, lambda *args: output_q.put('on_success'), lambda *args: output_q.put('on_failure'), poll_interval=0.1, ) queue_consumer.start() queue_consumer.stop() queue_consumer.join() def queue_is_empty(config):
64
64
64
6
58
richardgoater/metaspace
metaspace/engine/tests/test_queue.py
Python
queue_is_empty
queue_is_empty
42
48
42
42
15fd9d28997673e400c71d7c9479301ae1365dfa
bigcode/the-stack
train
ba7c6f5cad6148b5c30f281c
train
function
@fixture(scope='module') def delete_queue(sm_config): # delete before tests queue_pub = QueuePublisher(sm_config['rabbitmq'], QDESC) queue_pub.delete_queue() yield # delete after tests queue_pub = QueuePublisher(sm_config['rabbitmq'], QDESC) queue_pub.delete_queue()
@fixture(scope='module') def delete_queue(sm_config): # delete before tests
queue_pub = QueuePublisher(sm_config['rabbitmq'], QDESC) queue_pub.delete_queue() yield # delete after tests queue_pub = QueuePublisher(sm_config['rabbitmq'], QDESC) queue_pub.delete_queue()
Queue import logging from sm.engine.queue import QueuePublisher, QueueConsumer, SM_ANNOTATE logging.basicConfig(level=logging.DEBUG) QDESC = SM_ANNOTATE QDESC['name'] = 'sm_test' @fixture(scope='module') def delete_queue(sm_config): # delete before tests
64
64
69
18
46
richardgoater/metaspace
metaspace/engine/tests/test_queue.py
Python
delete_queue
delete_queue
16
25
16
18
78b3c9539df57947420be1f6f030beb9efc558c7
bigcode/the-stack
train
c00ff51f4e37b5ed60bf241d
train
function
def test_queue_msg_published_consumed_on_failure_called(sm_config): config = sm_config['rabbitmq'] queue_pub = QueuePublisher(config, QDESC) msg = {'test': 'message'} queue_pub.publish(msg) output_q = Queue() def raise_exception(*args): output_q.put('callback') raise Exception(...
def test_queue_msg_published_consumed_on_failure_called(sm_config):
config = sm_config['rabbitmq'] queue_pub = QueuePublisher(config, QDESC) msg = {'test': 'message'} queue_pub.publish(msg) output_q = Queue() def raise_exception(*args): output_q.put('callback') raise Exception('Callback exception') run_queue_consumer_thread(config, callbac...
=output_q, wait=1 ) assert output_q.get() == 'callback' assert output_q.get() == 'on_success' assert output_q.empty() time.sleep(5) assert queue_is_empty(config) def test_queue_msg_published_consumed_on_failure_called(sm_config):
64
64
133
14
50
richardgoater/metaspace
metaspace/engine/tests/test_queue.py
Python
test_queue_msg_published_consumed_on_failure_called
test_queue_msg_published_consumed_on_failure_called
70
88
70
70
b3c7a2915d9e7631062df773b2d91a41c88367d9
bigcode/the-stack
train
f9ae6ffcb7464699d69d4c73
train
function
def run_queue_consumer_thread(config, callback, output_q, wait=1): queue_consumer = QueueConsumer( config, QDESC, callback, lambda *args: output_q.put('on_success'), lambda *args: output_q.put('on_failure'), poll_interval=0.1, ) queue_consumer.start() queu...
def run_queue_consumer_thread(config, callback, output_q, wait=1):
queue_consumer = QueueConsumer( config, QDESC, callback, lambda *args: output_q.put('on_success'), lambda *args: output_q.put('on_failure'), poll_interval=0.1, ) queue_consumer.start() queue_consumer.stop() queue_consumer.join()
QueuePublisher(sm_config['rabbitmq'], QDESC) queue_pub.delete_queue() yield # delete after tests queue_pub = QueuePublisher(sm_config['rabbitmq'], QDESC) queue_pub.delete_queue() def run_queue_consumer_thread(config, callback, output_q, wait=1):
64
64
87
17
47
richardgoater/metaspace
metaspace/engine/tests/test_queue.py
Python
run_queue_consumer_thread
run_queue_consumer_thread
28
39
28
28
8c23a6efc18ac76ad0c07c6d64b3c872710cffe8
bigcode/the-stack
train
417fcb645c2d468c5ad25924
train
function
def test_queue_msg_published_consumed_on_success_called(sm_config, delete_queue): config = sm_config['rabbitmq'] queue_pub = QueuePublisher(config, QDESC) msg = {'test': 'message'} queue_pub.publish(msg) output_q = Queue() run_queue_consumer_thread( config, callback=lambda *args: output...
def test_queue_msg_published_consumed_on_success_called(sm_config, delete_queue):
config = sm_config['rabbitmq'] queue_pub = QueuePublisher(config, QDESC) msg = {'test': 'message'} queue_pub.publish(msg) output_q = Queue() run_queue_consumer_thread( config, callback=lambda *args: output_q.put('callback'), output_q=output_q, wait=1 ) assert output_q.get() == ...
localhost:15672/api/queues/%2F/{}'.format(QDESC['name']), auth=(config['user'], config['password']), timeout=1, ) return resp.json()['messages'] == 0 def test_queue_msg_published_consumed_on_success_called(sm_config, delete_queue):
64
64
131
17
46
richardgoater/metaspace
metaspace/engine/tests/test_queue.py
Python
test_queue_msg_published_consumed_on_success_called
test_queue_msg_published_consumed_on_success_called
51
67
51
51
2bc4041e0d06a809d7dcecb4d6ed15270af0696a
bigcode/the-stack
train
33a7dd04cb7399bf88a882d7
train
function
@app.route('/analyze', methods=['POST']) def analyze(): #DEBUG app.logger.warning(request.get_json()) app.logger.warning(type(request.get_json())) app.logger.warning(request.get_json()['artist']) # retrieve artist from request artist = request.get_json()['artist'].lower() # get artist...
@app.route('/analyze', methods=['POST']) def analyze(): #DEBUG
app.logger.warning(request.get_json()) app.logger.warning(type(request.get_json())) app.logger.warning(request.get_json()['artist']) # retrieve artist from request artist = request.get_json()['artist'].lower() # get artist id artist_id = (song_retrieval.get_artist_id(artist)) app.logg...
from logging.handlers import RotatingFileHandler import json import song_retrieval import database app = Flask(__name__) @app.route('/') def hello_world(): return render_template("%s.html" % "index") @app.route('/analyze', methods=['POST']) def analyze(): #DEBUG
64
64
182
18
46
maxcohn/sicc-song-analytics
server.py
Python
analyze
analyze
14
39
14
17
47ecc84b096bcfb24e2c5eb8114e08877d8614b2
bigcode/the-stack
train
6d2c503bfdfa1440a8248d13
train
function
@app.route('/') def hello_world(): return render_template("%s.html" % "index")
@app.route('/') def hello_world():
return render_template("%s.html" % "index")
from flask import Flask, render_template, request import logging from logging.handlers import RotatingFileHandler import json import song_retrieval import database app = Flask(__name__) @app.route('/') def hello_world():
47
64
19
7
40
maxcohn/sicc-song-analytics
server.py
Python
hello_world
hello_world
10
12
10
11
71c5efa7626b60cbe7e6f1a537792142357d349a
bigcode/the-stack
train
5f030ad9243ccd709952a162
train
function
def greedy_schedule(timestamps, n_workers): ''' Implements the Longest Processing Time Scheduling Strategy. At each iteration, the largest process is scheduled to the worker with the least load. Parameters ---------- timestamps: dict of lists The timestaps of each process n_work...
def greedy_schedule(timestamps, n_workers):
''' Implements the Longest Processing Time Scheduling Strategy. At each iteration, the largest process is scheduled to the worker with the least load. Parameters ---------- timestamps: dict of lists The timestaps of each process n_workers: int The number of workers ...
import numpy as np def define_worker_for_each_process(static_schedule): '''Given a static schedule generates the reverse mapping''' proc2worker = {} for worker_id in static_schedule: for proc in static_schedule[worker_id]: proc2worker[proc] = worker_id return proc2worker def greed...
76
76
254
9
66
myozka/granger-busca
gb/scheduler.py
Python
greedy_schedule
greedy_schedule
17
52
17
17
f04aff246a8754ece29623b8b00d077a24d8c719
bigcode/the-stack
train
e7ef6489d230f13c3fd52e37
train
function
def define_worker_for_each_process(static_schedule): '''Given a static schedule generates the reverse mapping''' proc2worker = {} for worker_id in static_schedule: for proc in static_schedule[worker_id]: proc2worker[proc] = worker_id return proc2worker
def define_worker_for_each_process(static_schedule):
'''Given a static schedule generates the reverse mapping''' proc2worker = {} for worker_id in static_schedule: for proc in static_schedule[worker_id]: proc2worker[proc] = worker_id return proc2worker
# -*- coding: utf8 import heapq import numpy as np def define_worker_for_each_process(static_schedule):
25
64
61
9
15
myozka/granger-busca
gb/scheduler.py
Python
define_worker_for_each_process
define_worker_for_each_process
8
14
8
8
ed87b70ad5e8feaa4cba3c8cf9864f84998727bb
bigcode/the-stack
train
8bccc7a20d5b0bb68001c11d
train
class
class Imposto(object): __metaclass__ = ABCMeta def __init__(self, outro_imposto = None): self.__outro_imposto = outro_imposto def calculo_outro_imposto(self, orcamento): if self.__outro_imposto is not None: return self.__outro_imposto.calcula(orcamento) else: ...
class Imposto(object):
__metaclass__ = ABCMeta def __init__(self, outro_imposto = None): self.__outro_imposto = outro_imposto def calculo_outro_imposto(self, orcamento): if self.__outro_imposto is not None: return self.__outro_imposto.calcula(orcamento) else: return 0 ...
#!/usr/bin/env python # -*- coding=utf-8 -*- from abc import ABCMeta, abstractmethod # Decorator utilizando o pattern OO class Imposto(object):
36
64
103
5
30
ramonlimaramos/python_design_patterns
Decorator/imposto.py
Python
Imposto
Imposto
7
20
7
7
f631b973ad53720ae34ad8897cceee4121057d9f
bigcode/the-stack
train
3bad1a2c0554d307a0346d7c
train
class
class ICMS(Imposto): def calcula(self, orcamento): return orcamento.valor * 0.20 + self.calculo_outro_imposto(orcamento)
class ICMS(Imposto):
def calcula(self, orcamento): return orcamento.valor * 0.20 + self.calculo_outro_imposto(orcamento)
def minima_taxacao(self, orcamento): pass class ISS(Imposto): @IPVX def calcula(self, orcamento): return orcamento.valor * 0.10 + self.calculo_outro_imposto(orcamento) class ICMS(Imposto):
64
64
39
7
57
ramonlimaramos/python_design_patterns
Decorator/imposto.py
Python
ICMS
ICMS
54
57
54
55
1c404fb0061892214eaa074621d4748d8404bf56
bigcode/the-stack
train
53c8259ca7fada606e9b58c8
train
class
class ISS(Imposto): @IPVX def calcula(self, orcamento): return orcamento.valor * 0.10 + self.calculo_outro_imposto(orcamento)
class ISS(Imposto): @IPVX
def calcula(self, orcamento): return orcamento.valor * 0.10 + self.calculo_outro_imposto(orcamento)
method def deve_utilizar_maxima(self, orcamento): pass @abstractmethod def maxima_taxacao(self, orcamento): pass @abstractmethod def minima_taxacao(self, orcamento): pass class ISS(Imposto): @IPVX
64
64
43
11
52
ramonlimaramos/python_design_patterns
Decorator/imposto.py
Python
ISS
ISS
47
51
47
49
83e35b61851cc5fe7bc0a9c841842c5b995e5a17
bigcode/the-stack
train
dd4116379efd31e2fa31a283
train
class
class IKCV(Template_Imposto_Condicional): def deve_utilizar_maxima(self, orcamento): return orcamento.valor > 500 and self.__item_maior_100(orcamento) def maxima_taxacao(self, orcamento): return orcamento.valor * 0.10 + self.calculo_outro_imposto(orcamento) def minima_taxacao(self...
class IKCV(Template_Imposto_Condicional):
def deve_utilizar_maxima(self, orcamento): return orcamento.valor > 500 and self.__item_maior_100(orcamento) def maxima_taxacao(self, orcamento): return orcamento.valor * 0.10 + self.calculo_outro_imposto(orcamento) def minima_taxacao(self, orcamento): return orcamento.valor...
.valor * 0.07 + self.calculo_outro_imposto(orcamento) def minima_taxacao(self, orcamento): return orcamento.valor * 0.05 + self.calculo_outro_imposto(orcamento) class IKCV(Template_Imposto_Condicional):
64
64
154
12
52
ramonlimaramos/python_design_patterns
Decorator/imposto.py
Python
IKCV
IKCV
72
87
72
73
c47263eb292591e6ba8cf98a88bf8562d9c56b17
bigcode/the-stack
train
23af2ba57f90c28f7fd671d4
train
function
def IPVX(metodo_ou_funcao): def wrapper(self, orcamento): return metodo_ou_funcao(self, orcamento) + 50.0 return wrapper
def IPVX(metodo_ou_funcao):
def wrapper(self, orcamento): return metodo_ou_funcao(self, orcamento) + 50.0 return wrapper
outro_imposto is not None: return self.__outro_imposto.calcula(orcamento) else: return 0 @abstractmethod def calcula(self, orcamento): pass # Bult-in Decorator def IPVX(metodo_ou_funcao):
64
64
43
11
52
ramonlimaramos/python_design_patterns
Decorator/imposto.py
Python
IPVX
IPVX
23
26
23
23
7062546d22c5d9269a23d8ee50c0081251f03bcc
bigcode/the-stack
train
b88bbb7744f716228a1ec725
train
class
class ICPP(Template_Imposto_Condicional): def deve_utilizar_maxima(self, orcamento): return orcamento.valor > 500 def maxima_taxacao(self, orcamento): return orcamento.valor * 0.07 + self.calculo_outro_imposto(orcamento) def minima_taxacao(self, orcamento): return orc...
class ICPP(Template_Imposto_Condicional):
def deve_utilizar_maxima(self, orcamento): return orcamento.valor > 500 def maxima_taxacao(self, orcamento): return orcamento.valor * 0.07 + self.calculo_outro_imposto(orcamento) def minima_taxacao(self, orcamento): return orcamento.valor * 0.05 + self.calculo_outro_imposto(...
+ self.calculo_outro_imposto(orcamento) class ICMS(Imposto): def calcula(self, orcamento): return orcamento.valor * 0.20 + self.calculo_outro_imposto(orcamento) class ICPP(Template_Imposto_Condicional):
64
64
104
13
51
ramonlimaramos/python_design_patterns
Decorator/imposto.py
Python
ICPP
ICPP
60
69
60
61
9d395283fe62e56dd25445eff9b09435ea785fc9
bigcode/the-stack
train
9c6af2acc3c692801304d114
train
class
class Template_Imposto_Condicional(Imposto): __metaclass__ = ABCMeta def calcula(self, orcamento): if self.deve_utilizar_maxima(orcamento): return self.maxima_taxacao(orcamento) else: return self.minima_taxacao(orcamento) @abstractmethod def deve_u...
class Template_Imposto_Condicional(Imposto):
__metaclass__ = ABCMeta def calcula(self, orcamento): if self.deve_utilizar_maxima(orcamento): return self.maxima_taxacao(orcamento) else: return self.minima_taxacao(orcamento) @abstractmethod def deve_utilizar_maxima(self, orcamento): pass @...
): pass # Bult-in Decorator def IPVX(metodo_ou_funcao): def wrapper(self, orcamento): return metodo_ou_funcao(self, orcamento) + 50.0 return wrapper class Template_Imposto_Condicional(Imposto):
64
64
123
11
52
ramonlimaramos/python_design_patterns
Decorator/imposto.py
Python
Template_Imposto_Condicional
Template_Imposto_Condicional
28
44
28
28
a559885f08cd90fa65dcc6e10073e09db7dd576c
bigcode/the-stack
train
005490f6e4edfd7fa0ce20e9
train
function
def model_fn(model_dir): """Load model from the model_dir. This is the same model that is saved in the main if statement. """ print("Loading model.") # load using joblib model = joblib.load(os.path.join(model_dir, "model.joblib")) print("Done loading model.") return model
def model_fn(model_dir):
"""Load model from the model_dir. This is the same model that is saved in the main if statement. """ print("Loading model.") # load using joblib model = joblib.load(os.path.join(model_dir, "model.joblib")) print("Done loading model.") return model
from __future__ import print_function import argparse import os import pandas as pd from sklearn.externals import joblib ## TODO: Import any additional libraries you need to define a model from sklearn.naive_bayes import GaussianNB # Provided model load function def model_fn(model_dir):
63
64
76
6
56
bmaingret/plagiarism-detector
source_sklearn/train_NB.py
Python
model_fn
model_fn
13
23
13
13
971b1eb5494763e02bacd3f12c2f6db3fe2db2d6
bigcode/the-stack
train
02ad1e415a65e088772426c6
train
class
class site_scraper: def __init__(self, JD): self.sitename = "torrentmap" self.name = "web_scraper_02" self.mainUrl = "https://torrentmap.com" self.JD = JD self.kortv_ent_id = JD.get('history').get("%s_kortv_ent" % (self.sitename)) self.kortv_soc_id = JD.get('history'...
class site_scraper:
def __init__(self, JD): self.sitename = "torrentmap" self.name = "web_scraper_02" self.mainUrl = "https://torrentmap.com" self.JD = JD self.kortv_ent_id = JD.get('history').get("%s_kortv_ent" % (self.sitename)) self.kortv_soc_id = JD.get('history').get("%s_kortv_soc"...
#!/usr/bin/env python3 from urllib.request import Request, urlopen from bs4 import BeautifulSoup import subprocess import re import json import web_scraper_lib webpage_addr = [ "https://www.torrentmap.com/bbs/board.php?bo_table=kr_ent&page=", "https://www.torrentmap.com/bbs/board.php?bo_table=kr_daq&pa...
96
212
709
5
91
pcjnao/web_scraper
web_scraper_02.py
Python
site_scraper
site_scraper
14
103
14
14
4dd89bf7923286a7ab7c0efe2ffca265d088d54d
bigcode/the-stack
train
da27045580f75ccf64359dd1
train
class
class Report(models.Model): reporter = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="reports", on_delete=models.CASCADE ) declaration = models.ForeignKey( Declaration, related_name="reports", blank=True, null=True, on_delete=models.CASCADE, ) ...
class Report(models.Model):
reporter = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="reports", on_delete=models.CASCADE ) declaration = models.ForeignKey( Declaration, related_name="reports", blank=True, null=True, on_delete=models.CASCADE, ) resolution = models.Fore...
_type, declaration_type=SITUATION) neutral = curry(children_by_declaration_type, declaration_type=NEUTRAL) def update_weight(self): weight = 1 + self.supporters.count() - self.reports.count() for child in self.published_children(): child_weight = child.update_weight() ...
115
115
384
5
109
un-project/un-project.org
web/declarations/models.py
Python
Report
Report
740
802
740
740
c383bed6c2dd4949c66a321bd0da53a53992247c
bigcode/the-stack
train
d2cacfab979bfb1da2451b5e
train
class
class Declaration(DeletePreventionMixin, models.Model): from profiles.models import Speaker # avoid circular import resolution = models.ForeignKey( Resolution, related_name="declarations", on_delete=models.CASCADE ) speaker = models.ForeignKey( Speaker, related_name="speake...
class Declaration(DeletePreventionMixin, models.Model):
from profiles.models import Speaker # avoid circular import resolution = models.ForeignKey( Resolution, related_name="declarations", on_delete=models.CASCADE ) speaker = models.ForeignKey( Speaker, related_name="speaker_declarations", null=True, on_delete=mo...
= ( Noun.objects.filter( language=normalize_language_code(get_language()), id__in=noun_ids ) .annotate(resolution_count=Count("resolutions")) .filter(resolutions__is_published=True) .prefetch_related("resolutions") ) serialize...
256
256
1,936
10
245
un-project/un-project.org
web/declarations/models.py
Python
Declaration
Declaration
461
737
461
461
92a8399bd1c2aa81718450ad5a575789ab1fb93a
bigcode/the-stack
train
4b7e01bfe6fd44a0c426ba23
train
class
class Resolution(DeletePreventionMixin, models.Model): from profiles.models import State title = models.CharField( max_length=512, verbose_name=_("Resolution"), help_text=render_to_string("declarations/examples/resolution.html"), ) slug = models.SlugField(max_length=512, blank=T...
class Resolution(DeletePreventionMixin, models.Model):
from profiles.models import State title = models.CharField( max_length=512, verbose_name=_("Resolution"), help_text=render_to_string("declarations/examples/resolution.html"), ) slug = models.SlugField(max_length=512, blank=True) description = models.TextField(null=True, blan...
Against TheMan")), ("PoisoningTheWell", _("Poisoning The Well")), ("FallacyOfTheBeard", _("Fallacy Of The Beard")), ("FallacyOfSlipperySlope", _("Fallacy Of Slippery Slope")), ("FallacyOfFalseCause", _("Fallacy Of False Cause")), ("FallacyOfPreviousThis", _("Fallacy Of Previous This")), ("Joint...
256
256
2,627
10
246
un-project/un-project.org
web/declarations/models.py
Python
Resolution
Resolution
77
458
77
77
12aa101ca85e1ff31ccff714f5cb91446e3af1d3
bigcode/the-stack
train
d03c55034675cde977e0ec84
train
function
def main(): logging.basicConfig( level='WARNING', format='%(asctime)s %(levelname)s %(name)s %(message)s') argparser = argparse.ArgumentParser( description='Retrieve MRMS precipitation data, regrid it, and save', formatter_class=argparse.ArgumentDefaultsHelpFormatter) argpars...
def main():
logging.basicConfig( level='WARNING', format='%(asctime)s %(levelname)s %(name)s %(message)s') argparser = argparse.ArgumentParser( description='Retrieve MRMS precipitation data, regrid it, and save', formatter_class=argparse.ArgumentDefaultsHelpFormatter) argparser.add_argum...
and grid to a numpy file""" logging.info('Saving numpy data to a file...') thedir = os.path.join(os.path.expanduser(base_dir), valid_date.strftime('%Y/%m/%d')) if not os.path.isdir(thedir): os.makedirs(thedir) path = os.path.join(thedir, valid_date.strftime('%HZ.npz')...
130
130
434
3
127
UARENForecasting/ARTSy
download_and_regrid.py
Python
main
main
95
134
95
95
1e242cb364e4459523aad43d526d3fbf0d946a34
bigcode/the-stack
train
7bd30fbb464026236940d079
train
function
def download_data(date, tmpfile): """Download the MRMS correlated precip data from NCEP""" base_url = 'http://mrms.ncep.noaa.gov/data/2D/GaugeCorr_QPE_24H/' if date == 'latest': timestr = '.latest' else: timestr = date.strftime('_00.00_%Y%m%d-%H%M%S') filename = 'MRMS_GaugeCorr_QPE_2...
def download_data(date, tmpfile):
"""Download the MRMS correlated precip data from NCEP""" base_url = 'http://mrms.ncep.noaa.gov/data/2D/GaugeCorr_QPE_24H/' if date == 'latest': timestr = '.latest' else: timestr = date.strftime('_00.00_%Y%m%d-%H%M%S') filename = 'MRMS_GaugeCorr_QPE_24H{timestr}.grib2.gz'.format( ...
web mercator""" R = 6378137 x = np.radians(lon) * R y = np.log(np.tan(np.pi / 4 + np.radians(lat) / 2)) * R return x, y def download_data(date, tmpfile):
64
64
212
8
55
UARENForecasting/ARTSy
download_and_regrid.py
Python
download_data
download_data
31
48
31
31
1f67c414fcec8d3075f76f5606f63ecf0948bee1
bigcode/the-stack
train
79cdae2a92a0ca639c3d8fff
train
function
def save_data(base_dir, valid_date, regridded_data, X, Y, overwrite): """Save the data and grid to a numpy file""" logging.info('Saving numpy data to a file...') thedir = os.path.join(os.path.expanduser(base_dir), valid_date.strftime('%Y/%m/%d')) if not os.path.isdir(thedir): ...
def save_data(base_dir, valid_date, regridded_data, X, Y, overwrite):
"""Save the data and grid to a numpy file""" logging.info('Saving numpy data to a file...') thedir = os.path.join(os.path.expanduser(base_dir), valid_date.strftime('%Y/%m/%d')) if not os.path.isdir(thedir): os.makedirs(thedir) path = os.path.join(thedir, valid_date...
= scipy.interpolate.griddata((x.ravel(), y.ravel()), grb_data.ravel(), (X, Y), method='linear') return regridded_data, X, Y def save_data(base_dir, valid_date, regridded_data, X, Y, overwrite):
64
64
153
21
42
UARENForecasting/ARTSy
download_and_regrid.py
Python
save_data
save_data
80
92
80
80
85aacdd2598fd0e427484c1c2c1012099de92393
bigcode/the-stack
train
bb27c076f57fd274ad2cd939
train
function
def read_subset(tmpfilename, bbox): """Read a subset of the data from the grib file""" logging.info('Reading subset of data from grib file') grbs = pygrib.open(tmpfilename) grb = grbs.message(1) min_lat, max_lat, min_lon, max_lon = bbox grb_data, lats, lons = grb.data(lat1=min_lat, lat2=max_lat,...
def read_subset(tmpfilename, bbox):
"""Read a subset of the data from the grib file""" logging.info('Reading subset of data from grib file') grbs = pygrib.open(tmpfilename) grb = grbs.message(1) min_lat, max_lat, min_lon, max_lon = bbox grb_data, lats, lons = grb.data(lat1=min_lat, lat2=max_lat, lon1=min_lon, ...
file: %s', r.text) sys.exit(1) gzipped_data = BytesIO(r.content) with gzip.open(gzipped_data, 'rb') as f_in: shutil.copyfileobj(f_in, tmpfile) tmpfile.flush() def read_subset(tmpfilename, bbox):
64
64
135
8
56
UARENForecasting/ARTSy
download_and_regrid.py
Python
read_subset
read_subset
51
61
51
51
951f02d4acfca68f1743c2ef2acd96c5d0f99e8b
bigcode/the-stack
train
1a473bad9c917d25438cca2c
train
function
def webmerc_proj(lat, lon): """Convert latititude and longitude to web mercator""" R = 6378137 x = np.radians(lon) * R y = np.log(np.tan(np.pi / 4 + np.radians(lat) / 2)) * R return x, y
def webmerc_proj(lat, lon):
"""Convert latititude and longitude to web mercator""" R = 6378137 x = np.radians(lon) * R y = np.log(np.tan(np.pi / 4 + np.radians(lat) / 2)) * R return x, y
regular grid for later plotting. """ import argparse import datetime as dt import gzip from io import BytesIO import logging import os import shutil import sys import tempfile import numpy as np import pygrib import requests import scipy.interpolate def webmerc_proj(lat, lon):
64
64
73
8
55
UARENForecasting/ARTSy
download_and_regrid.py
Python
webmerc_proj
webmerc_proj
23
28
23
23
f7df7702c9045e1104932a9eed30238e9e8c6420
bigcode/the-stack
train
ec932eda1257f81dc24ee3a1
train
function
def regrid(grb_data, lats, lons): """Regrid the data onto an even web mercator grid""" logging.info('Regridding data...') x, y = webmerc_proj(lats, lons) # make new grid xn = np.linspace(x.min(), x.max(), grb_data.shape[1]) yn = np.linspace(y.min(), y.max(), grb_data.shape[0]) X, Y = np.mes...
def regrid(grb_data, lats, lons):
"""Regrid the data onto an even web mercator grid""" logging.info('Regridding data...') x, y = webmerc_proj(lats, lons) # make new grid xn = np.linspace(x.min(), x.max(), grb_data.shape[1]) yn = np.linspace(y.min(), y.max(), grb_data.shape[0]) X, Y = np.meshgrid(xn, yn) regridded_data ...
.data(lat1=min_lat, lat2=max_lat, lon1=min_lon, lon2=max_lon) valid_date = grb.validDate grbs.close() return grb_data, lats, lons, valid_date def regrid(grb_data, lats, lons):
64
64
154
13
50
UARENForecasting/ARTSy
download_and_regrid.py
Python
regrid
regrid
64
77
64
64
2c1716660f10d62cc1d4344fe53f46f0be9813d2
bigcode/the-stack
train
d015cacb908233a72b59aacc
train
function
def get_pr(owner, repo, sha): data = request("https://api.github.com/search/issues?q=type:pr+is:merged+repo:%s/%s+sha:%s" % (owner, repo, sha), "Getting PR") if data is None: return None items = data["items"] if len(items) == 0: logger.error("No PR found for %s" % sha...
def get_pr(owner, repo, sha):
data = request("https://api.github.com/search/issues?q=type:pr+is:merged+repo:%s/%s+sha:%s" % (owner, repo, sha), "Getting PR") if data is None: return None items = data["items"] if len(items) == 0: logger.error("No PR found for %s" % sha) return None if l...
.status_code)) logger.error(resp.text) return None try: return resp.json() except ValueError: logger.error("%s failed: Returned data was not JSON Response:" % (desc, resp.status_code)) logger.error(resp.text) def get_pr(owner, repo, sha):
64
64
135
9
55
Thezone1975/wpt
tools/ci/manifest_build.py
Python
get_pr
get_pr
91
106
91
91
85f9638681c71916ec31a1b7145376cfd78f366e
bigcode/the-stack
train
6aaf4e07ee44103ffcb94d09
train
function
def compress_manifest(path): for args in [["gzip", "-k", "-f", "--best"], ["bzip2", "-k", "-f", "--best"], ["zstd", "-k", "-f", "--ultra", "-22"]]: run(args + [path])
def compress_manifest(path):
for args in [["gzip", "-k", "-f", "--best"], ["bzip2", "-k", "-f", "--best"], ["zstd", "-k", "-f", "--ultra", "-22"]]: run(args + [path])
): logger.info(" ".join(cmd)) if return_stdout: f = subprocess.check_output else: f = subprocess.check_call return f(cmd, **kwargs) def create_manifest(path): run(["./wpt", "manifest", "-p", path]) def compress_manifest(path):
64
64
62
5
59
Thezone1975/wpt
tools/ci/manifest_build.py
Python
compress_manifest
compress_manifest
40
44
40
40
09e30796c1c3658672aff78a369252db06619939
bigcode/the-stack
train
bf7ff55a2ad3c542e505e285
train
class
class Status(object): SUCCESS = 0 FAIL = 1 NEUTRAL = 0
class Status(object):
SUCCESS = 0 FAIL = 1 NEUTRAL = 0
.abspath(os.path.join(here, os.pardir, os.pardir)) if not(wpt_root in sys.path): sys.path.append(wpt_root) from tools.wpt.testfiles import get_git_cmd logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class Status(object):
64
64
24
4
60
Thezone1975/wpt
tools/ci/manifest_build.py
Python
Status
Status
21
24
21
21
00107e700bb4e4ee756543acc0344b6662f7e9e4
bigcode/the-stack
train
a0088d41df09aa3eeb3e0151
train
function
def tag(owner, repo, sha, tag): data = {"ref": "refs/tags/%s" % tag, "sha": sha} url = "https://api.github.com/repos/%s/%s/git/refs" % (owner, repo) resp_data = request(url, "Tag creation", json_data=data) if not resp_data: return False logger.info("Tagged %s as %s" % (sha, tag...
def tag(owner, repo, sha, tag):
data = {"ref": "refs/tags/%s" % tag, "sha": sha} url = "https://api.github.com/repos/%s/%s/git/refs" % (owner, repo) resp_data = request(url, "Tag creation", json_data=data) if not resp_data: return False logger.info("Tagged %s as %s" % (sha, tag)) return True
.error("No PR found for %s" % sha) return None if len(items) > 1: logger.warning("Found multiple PRs for %s" % sha) pr = items[0] return pr["number"] def tag(owner, repo, sha, tag):
63
64
102
10
53
Thezone1975/wpt
tools/ci/manifest_build.py
Python
tag
tag
109
119
109
109
ad68a4fa9b8da1fd507b6210926e96f2a404c881
bigcode/the-stack
train
bd4970b7f3085c0e7b7f6832
train
function
def main(): repo_key = "GITHUB_REPOSITORY" if not should_run_action(): return Status.NEUTRAL owner, repo = os.environ[repo_key].split("/", 1) git = get_git_cmd(wpt_root) head_rev = git("rev-parse", "HEAD") pr = get_pr(owner, repo, head_rev) if pr is None: # This should on...
def main():
repo_key = "GITHUB_REPOSITORY" if not should_run_action(): return Status.NEUTRAL owner, repo = os.environ[repo_key].split("/", 1) git = get_git_cmd(wpt_root) head_rev = git("rev-parse", "HEAD") pr = get_pr(owner, repo, head_rev) if pr is None: # This should only really ha...
= json.load(f) logger.info(json.dumps(event, indent=2)) if "pull_request" in event: logger.info("Not tagging for PR") return False if event.get("ref") != "refs/heads/master": logger.info("Not tagging for ref %s" % event.get("ref")) return False return True def main(...
80
80
269
3
76
Thezone1975/wpt
tools/ci/manifest_build.py
Python
main
main
174
210
174
174
f9da5098b0a732986e1a991e1a240059d4f17c7e
bigcode/the-stack
train
659b1454ca07ab8be2aeabdf
train
function
def should_run_action(): with open(os.environ["GITHUB_EVENT_PATH"]) as f: event = json.load(f) logger.info(json.dumps(event, indent=2)) if "pull_request" in event: logger.info("Not tagging for PR") return False if event.get("ref") != "refs/heads/master": logger.info(...
def should_run_action():
with open(os.environ["GITHUB_EVENT_PATH"]) as f: event = json.load(f) logger.info(json.dumps(event, indent=2)) if "pull_request" in event: logger.info("Not tagging for PR") return False if event.get("ref") != "refs/heads/master": logger.info("Not tagging for ref %s" ...
logger.info("Uploading %s bytes" % len(upload_data)) upload_resp = request(upload_url, "Manifest upload", data=upload_data, params=params, headers={'Content-Type': 'application/octet-stream'}) if not upload_resp: success = False return success def should_...
64
64
98
5
58
Thezone1975/wpt
tools/ci/manifest_build.py
Python
should_run_action
should_run_action
160
171
160
160
07d9feb369e743b05bad92add0454885bbdcbf14
bigcode/the-stack
train
0a41f6418b2353183f0144b7
train
function
def run(cmd, return_stdout=False, **kwargs): logger.info(" ".join(cmd)) if return_stdout: f = subprocess.check_output else: f = subprocess.check_call return f(cmd, **kwargs)
def run(cmd, return_stdout=False, **kwargs):
logger.info(" ".join(cmd)) if return_stdout: f = subprocess.check_output else: f = subprocess.check_call return f(cmd, **kwargs)
pt_root) from tools.wpt.testfiles import get_git_cmd logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class Status(object): SUCCESS = 0 FAIL = 1 NEUTRAL = 0 def run(cmd, return_stdout=False, **kwargs):
64
64
49
11
52
Thezone1975/wpt
tools/ci/manifest_build.py
Python
run
run
27
33
27
27
6b44998502fcb2a25e68f933949d57e0fdac27f1
bigcode/the-stack
train
0aab6218d37904b08309f93c
train
function
def create_manifest(path): run(["./wpt", "manifest", "-p", path])
def create_manifest(path):
run(["./wpt", "manifest", "-p", path])
1 NEUTRAL = 0 def run(cmd, return_stdout=False, **kwargs): logger.info(" ".join(cmd)) if return_stdout: f = subprocess.check_output else: f = subprocess.check_call return f(cmd, **kwargs) def create_manifest(path):
64
64
20
5
59
Thezone1975/wpt
tools/ci/manifest_build.py
Python
create_manifest
create_manifest
36
37
36
36
cccf281cafbb710a722666200529e8188a1c2f15
bigcode/the-stack
train
52c0bdc7d382cc2f66210520
train
function
def create_release(manifest_path, owner, repo, sha, tag, summary, body): if body: body = "%s\n%s" % (summary, body) else: body = summary create_url = "https://api.github.com/repos/%s/%s/releases" % (owner, repo) create_data = {"tag_name": tag, "name": tag, ...
def create_release(manifest_path, owner, repo, sha, tag, summary, body):
if body: body = "%s\n%s" % (summary, body) else: body = summary create_url = "https://api.github.com/repos/%s/%s/releases" % (owner, repo) create_data = {"tag_name": tag, "name": tag, "body": body} create_data = request(create_url, "Release crea...
"sha": sha} url = "https://api.github.com/repos/%s/%s/git/refs" % (owner, repo) resp_data = request(url, "Tag creation", json_data=data) if not resp_data: return False logger.info("Tagged %s as %s" % (sha, tag)) return True def create_release(manifest_path, owner, repo, sha, tag, summary,...
94
94
315
19
74
Thezone1975/wpt
tools/ci/manifest_build.py
Python
create_release
create_release
122
157
122
122
d5e66d6b1cab2578af890fe0408f2e3e2a29d6e7
bigcode/the-stack
train
d062e32fec8d18130a1cac29
train
function
def request(url, desc, data=None, json_data=None, params=None, headers=None): github_token = os.environ.get("GITHUB_TOKEN") default_headers = { "Authorization": "token %s" % github_token, "Accept": "application/vnd.github.machine-man-preview+json" } _headers = default_headers if hea...
def request(url, desc, data=None, json_data=None, params=None, headers=None):
github_token = os.environ.get("GITHUB_TOKEN") default_headers = { "Authorization": "token %s" % github_token, "Accept": "application/vnd.github.machine-man-preview+json" } _headers = default_headers if headers is not None: _headers.update(headers) kwargs = {"params": pa...
p", path]) def compress_manifest(path): for args in [["gzip", "-k", "-f", "--best"], ["bzip2", "-k", "-f", "--best"], ["zstd", "-k", "-f", "--ultra", "-22"]]: run(args + [path]) def request(url, desc, data=None, json_data=None, params=None, headers=None):
85
85
286
19
66
Thezone1975/wpt
tools/ci/manifest_build.py
Python
request
request
47
88
47
47
e863aba786fb483a2faa383eb7c1d48cf1399f4a
bigcode/the-stack
train
fbf3a32780bba95f8e9c2f41
train
class
class ProgramStartupAttributeFactory(DjangoModelFactory): class Meta: model = ProgramStartupAttribute program = SubFactory(ProgramFactory) attribute_type = "django.forms.CharField" attribute_label = Sequence(lambda n: "Attribute Label {0}".format(n)) attribute_description = Sequence(lambda ...
class ProgramStartupAttributeFactory(DjangoModelFactory):
class Meta: model = ProgramStartupAttribute program = SubFactory(ProgramFactory) attribute_type = "django.forms.CharField" attribute_label = Sequence(lambda n: "Attribute Label {0}".format(n)) attribute_description = Sequence(lambda n: "Description {0}".format(n)) admin_viewable = False...
import swapper from factory import ( Sequence, SubFactory, ) from factory.django import DjangoModelFactory from accelerator.tests.factories.program_factory import ProgramFactory ProgramStartupAttribute = swapper.load_model('accelerator', 'ProgramStartupAttribute') ...
64
64
109
10
54
masschallenge/django-accelerator
accelerator/tests/factories/program_startup_attribute_factory.py
Python
ProgramStartupAttributeFactory
ProgramStartupAttributeFactory
19
31
19
19
ee38034bccf799473fd224e3ea3cfe7131b75e21
bigcode/the-stack
train
2e23e1c94e49d522e0591dc6
train
function
def main(): print("Hello World")
def main():
print("Hello World")
import sys from importlib import resources import theabbie def main():
17
64
9
3
13
theabbie/package
python/package/__main__.py
Python
main
main
7
8
7
7
b97f09cce6cdcd47b493d33cacf2bc7ed3173c95
bigcode/the-stack
train
036a403e2cef38b7e4a648db
train
class
class AlmostFull(HirolaException, Warning): """To be raised or warned if the near-fullness of a hash table can lead to poor performance."""
class AlmostFull(HirolaException, Warning):
"""To be raised or warned if the near-fullness of a hash table can lead to poor performance."""
:class:`hirola.HashTable` which has called :meth:`hirola.HashTable.destroy`.""" def __str__(self): return "This table has been destroyed by HashTable.destroy() and can " \ "no longer be used." class AlmostFull(HirolaException, Warning):
64
64
34
10
54
bwoodsend/hoatzin
hirola/exceptions.py
Python
AlmostFull
AlmostFull
32
34
32
32
43dfa17f7207db68241ed1bf0278fe1c6cdc3a35
bigcode/the-stack
train
e7a6b74299f5b4ccbb934e74
train
class
class HashTableDestroyed(HirolaException): """Raised on adding or getting from a :class:`hirola.HashTable` which has called :meth:`hirola.HashTable.destroy`.""" def __str__(self): return "This table has been destroyed by HashTable.destroy() and can " \ "no longer be used."
class HashTableDestroyed(HirolaException):
"""Raised on adding or getting from a :class:`hirola.HashTable` which has called :meth:`hirola.HashTable.destroy`.""" def __str__(self): return "This table has been destroyed by HashTable.destroy() and can " \ "no longer be used."
(Exception): """Base exception for all errors :mod:`hirola`-related.""" pass class HashTableFullError(HirolaException): """Raised on attempting to add a new item to a table when the table is full. """ pass class HashTableDestroyed(HirolaException):
64
64
72
9
54
bwoodsend/hoatzin
hirola/exceptions.py
Python
HashTableDestroyed
HashTableDestroyed
23
29
23
23
e24ab5273f401bc65bec180d803e581990a8b801
bigcode/the-stack
train
aa3f44069bb6fe695e2a9cf2
train
class
class HashTableFullError(HirolaException): """Raised on attempting to add a new item to a table when the table is full. """ pass
class HashTableFullError(HirolaException):
"""Raised on attempting to add a new item to a table when the table is full. """ pass
========================= :mod:`hirola.exceptions` ========================= Custom :class:`Exception` subclasses used by :mod:`hirola`. """ class HirolaException(Exception): """Base exception for all errors :mod:`hirola`-related.""" pass class HashTableFullError(HirolaException):
64
64
34
10
53
bwoodsend/hoatzin
hirola/exceptions.py
Python
HashTableFullError
HashTableFullError
17
20
17
17
5d64e4d6bbf59fb26ba62c30adbc1446242504eb
bigcode/the-stack
train
310ba3f1fc29516eece8f505
train
class
class HirolaException(Exception): """Base exception for all errors :mod:`hirola`-related.""" pass
class HirolaException(Exception):
"""Base exception for all errors :mod:`hirola`-related.""" pass
# -*- coding: utf-8 -*- """ ========================= :mod:`hirola.exceptions` ========================= Custom :class:`Exception` subclasses used by :mod:`hirola`. """ class HirolaException(Exception):
44
64
25
6
38
bwoodsend/hoatzin
hirola/exceptions.py
Python
HirolaException
HirolaException
12
14
12
12
efe90c4737dbfdac5588722d23225db75b20f374
bigcode/the-stack
train
d7ec8b5d5793d16500c7d259
train
class
class TextVisitor: def visit_webpage(self, webpage): html = webpage.get_html() return self._get_text(html) def _get_text(self, raw_html): soup = BeautifulSoup(raw_html, 'html.parser') return soup.get_text().replace("\n", "").replace(",", " ")
class TextVisitor:
def visit_webpage(self, webpage): html = webpage.get_html() return self._get_text(html) def _get_text(self, raw_html): soup = BeautifulSoup(raw_html, 'html.parser') return soup.get_text().replace("\n", "").replace(",", " ")
from bs4 import BeautifulSoup class TextVisitor:
11
64
65
4
6
sofiabesenski4/scrapr
app/models/text_visitor.py
Python
TextVisitor
TextVisitor
3
10
3
3
1404d59e6e870b4d6a38b6a4c23b8c2f584b92e0
bigcode/the-stack
train
99f04aeb1b7a421320255f32
train
class
class XFilterManager(XInterface_8f010a43): """ Specifies a filter manager interface for a FilePicker. See Also: `API XFilterManager <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1ui_1_1dialogs_1_1XFilterManager.html>`_ """ __ooo_ns__: str = 'com.sun.star.ui.dialogs...
class XFilterManager(XInterface_8f010a43):
""" Specifies a filter manager interface for a FilePicker. See Also: `API XFilterManager <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1ui_1_1dialogs_1_1XFilterManager.html>`_ """ __ooo_ns__: str = 'com.sun.star.ui.dialogs' __ooo_full_ns__: str = 'com.sun.star....
# limitations under the License. # # Interface Class # this is a auto generated file generated by Cheetah # Libre Office Version: 7.3 # Namespace: com.sun.star.ui.dialogs from abc import abstractmethod from ...uno.x_interface import XInterface as XInterface_8f010a43 class XFilterManager(XInterface_8f010a43):
82
82
276
13
68
Amourspirit/ooo_uno_tmpl
ooobuild/lo/ui/dialogs/x_filter_manager.py
Python
XFilterManager
XFilterManager
24
56
24
24
5eb005c722e6f232df293610b12137d1a2c19303
bigcode/the-stack
train
2b0320884ecf3749e252c3e9
train
function
def generate_simulation_and_driver(settings): ofolder = settings['output']['dir'] input_pdbx_file = settings['input']['dir'] + '/' + settings['name'] + '.cif' custom_xml = settings['input']['dir'] + '/' + settings['name'] + '.ffxml' forcefield = app.ForceField('amber10-constph.xml', 'gaff.xml', custom...
def generate_simulation_and_driver(settings):
ofolder = settings['output']['dir'] input_pdbx_file = settings['input']['dir'] + '/' + settings['name'] + '.cif' custom_xml = settings['input']['dir'] + '/' + settings['name'] + '.ffxml' forcefield = app.ForceField('amber10-constph.xml', 'gaff.xml', custom_xml, 'tip3p.xml', 'ions_tip3p.xml') # Loa...
'.hxml' offxml = settings['input']['dir'] + '/' + settings['name'] + '.ffxml' ocalib = settings['input']['dir'] + '/' + settings['name'] + '.cif' # Debugging/intermediate files dhydrogen_fix = settings['input']['dir'] + '/' + settings['name'] + '_hydrogen_fixed1.mol2' ofolder = settings['ou...
256
256
2,059
8
248
choderalab/Protons
examples/tautomers/tautomer_utils.py
Python
generate_simulation_and_driver
generate_simulation_and_driver
88
348
88
89
387363a14591ecadba336da859a7ee59ee6b56d2
bigcode/the-stack
train
ee0c2730e072568249f76530
train
function
def run_main(simulation, driver, pdb_object, settings): """Main simulation loop.""" # Add reporters ncfile = netCDF4.Dataset(settings['simulation']['netCDF4'], "w") dcd_output_name = settings['simulation']['dcd_filename'] simulation.update_reporters.append(app.MetadataReporter(ncfile)) simulat...
def run_main(simulation, driver, pdb_object, settings):
"""Main simulation loop.""" # Add reporters ncfile = netCDF4.Dataset(settings['simulation']['netCDF4'], "w") dcd_output_name = settings['simulation']['dcd_filename'] simulation.update_reporters.append(app.MetadataReporter(ncfile)) simulation.reporters.append(app.DCDReporter(dcd_output_name, 10...
2_for_parametrization from protons.scripts.utilities import * from protons.app import TautomerForceFieldProtonDrive, TautomerNCMCProtonDrive from protons.app import MetadataReporter, TitrationReporter, NCMCReporter, SAMSReporter from simtk import unit, openmm as mm from saltswap.wrappers import Salinator from protons.a...
125
125
419
13
111
choderalab/Protons
examples/tautomers/tautomer_utils.py
Python
run_main
run_main
14
50
14
14
0f5eda9cad3da42860f9df5d4bbb52b9b8c1af88
bigcode/the-stack
train
0ca0accfe9543f987b0c90d2
train
function
def setting_up_tautomer(settings, isomer_dictionary): pH = settings['pH'] resname = settings['resname'] #retrieve input files icalib = settings['input']['dir'] + '/' + settings['name'] + '.pdb' input_mol2 = settings['input']['dir'] + '/' + settings['name'] + '_tautomer_set.mol2' #define l...
def setting_up_tautomer(settings, isomer_dictionary):
pH = settings['pH'] resname = settings['resname'] #retrieve input files icalib = settings['input']['dir'] + '/' + settings['name'] + '.pdb' input_mol2 = settings['input']['dir'] + '/' + settings['name'] + '_tautomer_set.mol2' #define location of set up files hydrogen_def = settings['in...
.writeFile(pdb_object.topology, pos, open(settings['output']['dir'] + '/tmp/mcmc_'+str(i)+'.pdb', 'w')) if driver.calibration_state is not None: if driver.calibration_state.approach is SAMSApproach.ONESITE: simulation.update(1, pool="calibration") else: ...
109
109
364
12
97
choderalab/Protons
examples/tautomers/tautomer_utils.py
Python
setting_up_tautomer
setting_up_tautomer
53
86
53
54
5d02c36fe14a6a64960786f53ef4f8ea6668d119
bigcode/the-stack
train
115958de5e03e3e7c483d999
train
function
def index(request): template = loader.get_template('construction/welcome.html') context = { 'latest_question_list': "welcome", } return HttpResponse(template.render(context, request))
def index(request):
template = loader.get_template('construction/welcome.html') context = { 'latest_question_list': "welcome", } return HttpResponse(template.render(context, request))
. from django.shortcuts import render # Create your views here. from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.shortcuts import render from django.template import loader from django import forms from django.http import HttpResponseRedirect import dateti...
64
64
41
4
59
Raj-kishore/awslinkdjango
construction/views.py
Python
index
index
18
23
18
18
6fa042b7b33c15c1f1ac6f3355628df93f1827b3
bigcode/the-stack
train
197a5b192993cf26107d0971
train
function
def tiny_mahjong_dqn_model(): return _two_layer_cnn_model(input_shape=TM_DEFAULT_INPUT_SHAPE, output_number=TM_DEFAULT_OUTPUT_NUMBER, layer_configurations=TM_DEFAULT_LAYER_CONFIGURATIONS, optimizer=TM_DEFAULT_OPTIMIZER, ...
def tiny_mahjong_dqn_model():
return _two_layer_cnn_model(input_shape=TM_DEFAULT_INPUT_SHAPE, output_number=TM_DEFAULT_OUTPUT_NUMBER, layer_configurations=TM_DEFAULT_LAYER_CONFIGURATIONS, optimizer=TM_DEFAULT_OPTIMIZER, ...
APE = (14, 16, 1) SM_DEFAULT_OUTPUT_NUMBER = 14 SM_DEFAULT_LAYER_CONFIGURATIONS = (64, 64, 512) SM_DEFAULT_OPTIMIZER = Adam SM_DEFAULT_LEARNING_RATE = 0.00025 def tiny_mahjong_dqn_model():
64
64
75
9
54
0xsuu/Project-Mahjong
python_app/keras_models/model_generator.py
Python
tiny_mahjong_dqn_model
tiny_mahjong_dqn_model
38
44
38
38
37af2fe994daeded4473a6fa97fd3ef5ac12cf4e
bigcode/the-stack
train
5a1ab19d05347a5084bdb81f
train
function
def simple_mahjong_dqn_model(): return _two_layer_cnn_model(input_shape=SM_DEFAULT_INPUT_SHAPE, output_number=SM_DEFAULT_OUTPUT_NUMBER, layer_configurations=SM_DEFAULT_LAYER_CONFIGURATIONS, optimizer=SM_DEFAULT_OPTIMIZER...
def simple_mahjong_dqn_model():
return _two_layer_cnn_model(input_shape=SM_DEFAULT_INPUT_SHAPE, output_number=SM_DEFAULT_OUTPUT_NUMBER, layer_configurations=SM_DEFAULT_LAYER_CONFIGURATIONS, optimizer=SM_DEFAULT_OPTIMIZER, ...
TM_DEFAULT_INPUT_SHAPE, output_number=TM_DEFAULT_OUTPUT_NUMBER, layer_configurations=TM_DEFAULT_LAYER_CONFIGURATIONS, optimizer=TM_DEFAULT_OPTIMIZER, lr=TM_DEFAULT_LEARNING_RATE, ...
64
64
75
9
55
0xsuu/Project-Mahjong
python_app/keras_models/model_generator.py
Python
simple_mahjong_dqn_model
simple_mahjong_dqn_model
47
53
47
47
6959628bf89b2007daa6d91a1eebd44d23f16917
bigcode/the-stack
train
e791d49e51bae851d77619c8
train
function
def _two_layer_cnn_model(input_shape, output_number, layer_configurations, optimizer, lr, network_type, dim_ordering="tf"): backend.set_image_dim_ordering(dim_ordering) model = Sequential() model.add(Conv2D(layer_configurations[0], kernel_size=(3, 3), padding='...
def _two_layer_cnn_model(input_shape, output_number, layer_configurations, optimizer, lr, network_type, dim_ordering="tf"):
backend.set_image_dim_ordering(dim_ordering) model = Sequential() model.add(Conv2D(layer_configurations[0], kernel_size=(3, 3), padding='same', input_shape=input_shape)) model.add(Activation('relu')) model.add(Conv2D(layer_configurations[1], kernel_size=(3, 3))) model.add(A...
_DEFAULT_INPUT_SHAPE, output_number=SM_DEFAULT_OUTPUT_NUMBER, layer_configurations=SM_DEFAULT_LAYER_CONFIGURATIONS, optimizer=SM_DEFAULT_OPTIMIZER, lr=SM_DEFAULT_LEARNING_RATE, ...
85
85
286
31
54
0xsuu/Project-Mahjong
python_app/keras_models/model_generator.py
Python
_two_layer_cnn_model
_two_layer_cnn_model
56
89
56
57
5c746e73d2dd9a1e7506ee0cdb818c9daf981e1a
bigcode/the-stack
train
d8286914831f689bde9aa0d7
train
function
def obtain_analogActivations(analogModel, inputs): # Obtain the analog activations activations_analog = {} for l in range(1, len(analogModel.layers)): model_shortened = Model(inputs=analogModel.input, outputs=analogModel.layers[l].output) activations_analog[l] = model_shortened.predict(input...
def obtain_analogActivations(analogModel, inputs): # Obtain the analog activations
activations_analog = {} for l in range(1, len(analogModel.layers)): model_shortened = Model(inputs=analogModel.input, outputs=analogModel.layers[l].output) activations_analog[l] = model_shortened.predict(inputs) return activations_analog
[i+offset + 1 ] * h,activations_analog[j], n=n, limit=limit) all_diffs.append(diff) return activations, activations_analog, all_diffs def obtain_analogActivations(analogModel, inputs): # Obtain the analog activations
64
64
83
20
43
lynnsoerensen/SpatialAttention_sDCNN_2020
asn/conversion/check.py
Python
obtain_analogActivations
obtain_analogActivations
52
58
52
53
870b621e5db4d2a006607a71be22d7ce157b0209
bigcode/the-stack
train
b2d51841b603e500a69c916b
train
function
def check_spikingModel(spikingModel, analogModel, model_match, inputs, outputs, n=1000, limit= 0.05, batch_size=2, activations_analog=None, activations=None): if isinstance(inputs, list): analogInput = inputs[0] else: analogInput = inputs if activations_analog is Non...
def check_spikingModel(spikingModel, analogModel, model_match, inputs, outputs, n=1000, limit= 0.05, batch_size=2, activations_analog=None, activations=None):
if isinstance(inputs, list): analogInput = inputs[0] else: analogInput = inputs if activations_analog is None: activations_analog = obtain_analogActivations(analogModel, analogInput) if activations is None: activations = obtain_spikingActivations(spikingModel, inputs, o...
import numpy as np from asn.conversion.utils import normalize_transfer from asn.evaluation.wrappers import predict_generator from asn.evaluation.generators import TimeReplication from keras.models import Model from asn.neuronModel import ASN def check_spikingModel(spikingModel, analogModel, model_match, inputs, outputs...
101
139
465
48
52
lynnsoerensen/SpatialAttention_sDCNN_2020
asn/conversion/check.py
Python
check_spikingModel
check_spikingModel
9
49
9
10
6962b0745bf6dfe4eee5ca47cf91cd192851f4ca
bigcode/the-stack
train
db8ed04ae38acb41f1571bb5
train
function
def check_spikingLayer(activationSpiking, activationAnalog, bias=[], n=10, limit=0.05): diff = [] for i in range(n): # pick a random index shape = np.shape(activationAnalog) idx = [] for s in shape: idx.append(np.random.randint(s)) neuron = ASN() if l...
def check_spikingLayer(activationSpiking, activationAnalog, bias=[], n=10, limit=0.05):
diff = [] for i in range(n): # pick a random index shape = np.shape(activationAnalog) idx = [] for s in shape: idx.append(np.random.randint(s)) neuron = ASN() if len(shape) == 4: if len(bias) > 0: S_next_neuron, spikes_neur...
activations = {} for l in range(len(spikingModel.layers)): if spikingModel.layers[l].__class__.__name__ is not 'InputLayer': print(l) model_shortened = Model(inputs=spikingModel.inputs, outputs=spikingModel.layers[l].output) activations[l] = predict_generator(model_shor...
126
126
423
25
100
lynnsoerensen/SpatialAttention_sDCNN_2020
asn/conversion/check.py
Python
check_spikingLayer
check_spikingLayer
83
121
83
83
dd7e03fc051ceecf78582b956814d9f0c2750ae1
bigcode/the-stack
train
5d0230b93c57645936be0ce4
train
function
def obtain_spikingActivations(spikingModel, inputs, outputs, batch_size): # Obtain the spiking activations if isinstance(inputs,list): time_steps = spikingModel.input_shape[0][1] steps = int(np.ceil(inputs[0].shape[0] / batch_size)) else: time_steps = spikingModel.input_shape[1] ...
def obtain_spikingActivations(spikingModel, inputs, outputs, batch_size): # Obtain the spiking activations
if isinstance(inputs,list): time_steps = spikingModel.input_shape[0][1] steps = int(np.ceil(inputs[0].shape[0] / batch_size)) else: time_steps = spikingModel.input_shape[1] steps = int(np.ceil(inputs.shape[0] / batch_size)) activations = {} for l in range(len(spikingModel...
= Model(inputs=analogModel.input, outputs=analogModel.layers[l].output) activations_analog[l] = model_shortened.predict(inputs) return activations_analog def obtain_spikingActivations(spikingModel, inputs, outputs, batch_size): # Obtain the spiking activations
64
64
196
26
37
lynnsoerensen/SpatialAttention_sDCNN_2020
asn/conversion/check.py
Python
obtain_spikingActivations
obtain_spikingActivations
61
80
61
62
20bb1d6c91a8781eeb8333d07a6b10ab0b6abd30
bigcode/the-stack
train
2cf16244f696039778d11c40
train
class
class MNistApexAMPTrial(MNISTTrial): def __init__(self, context: PyTorchTrialContext) -> None: super().__init__(context, precision=16, amp_backend="apex")
class MNistApexAMPTrial(MNISTTrial):
def __init__(self, context: PyTorchTrialContext) -> None: super().__init__(context, precision=16, amp_backend="apex")
""" This example demonstrates how to modify a LightningAdapter model to use PyTorchTrial support for NVIDIA APEX in Determined. """ from model_def import MNISTTrial from determined.pytorch import PyTorchTrialContext class MNistApexAMPTrial(MNISTTrial):
57
64
46
12
44
gh-determined-ai/determined
e2e_tests/tests/fixtures/pytorch_lightning_amp/apex_amp_model_def.py
Python
MNistApexAMPTrial
MNistApexAMPTrial
11
13
11
11
9cb65f51cd129dd5ce23d4326eb89f6da291deaf
bigcode/the-stack
train
4349114cd9579f664b5dbf87
train
function
def synchronize(filename1, filename2, hopSize, TempoBiases, bSub, FeatureParams, CSMTypes,\ Kappa, fileprefix = "", doPlot = False, outputSnippets = True, doNegative = False): """ :param filename1: First song path :param filename2: Second song path :param hopSize: Hop size (in samples) ...
def synchronize(filename1, filename2, hopSize, TempoBiases, bSub, FeatureParams, CSMTypes,\ Kappa, fileprefix = "", doPlot = False, outputSnippets = True, doNegative = False):
""" :param filename1: First song path :param filename2: Second song path :param hopSize: Hop size (in samples) to be used between feature windows :param TempoBiases: The different tempo levels to be tried for beat tracking :param bSub: The factor by which to subdivide the beats :param Featur...
x2 if len(fileprefix) > 0: filename = "%s_%i.mp3"%(fileprefix, i) sio.wavfile.write("temp.wav", Fs, X) subprocess.call(["avconv", "-i", "temp.wav", filename]) beat1 = beats1[j+1]*hopSize-t1 beatsFinal.append(XFinal.shape[0]) XFinal = np.concatenate((X...
256
256
1,527
49
207
ctralie/CoverSongSynthesis
Synchronize.py
Python
synchronize
synchronize
101
211
101
102
8e1e4c8b2fb2f4dd03e0096110676427e2b4f03a
bigcode/the-stack
train
81ba357ef23128c19c38e32b
train
function
def syncBlocks(path, CSM, beats1, beats2, Fs, hopSize, XAudio1, XAudio2, BeatsPerBlock, fileprefix = ""): """ :param path: Px2 array representing a partial warping path to align two songs :param CSM: The cross similarity matrix between two songs :param beats1: An array of beat onsets for song 1 in incre...
def syncBlocks(path, CSM, beats1, beats2, Fs, hopSize, XAudio1, XAudio2, BeatsPerBlock, fileprefix = ""):
""" :param path: Px2 array representing a partial warping path to align two songs :param CSM: The cross similarity matrix between two songs :param beats1: An array of beat onsets for song 1 in increments of hopSize :param beats2: An array of beat onsets for song 2 in increments of hopSize :param...
Purpose: Naive O(N^2) algorithm to do the greedy permutation param: D (NxN distance matrix for points) return: (permutation (N-length array of indices), lambdas (N-length array of insertion radii)) """ N = D.shape[0] #By default, takes the first point in the list to be the #first...
210
210
700
36
174
ctralie/CoverSongSynthesis
Synchronize.py
Python
syncBlocks
syncBlocks
40
89
40
40
4e39eef6ef76c50e1f4e22af717fb893cec64c82
bigcode/the-stack
train
71c4eb8d40e110069b32f35d
train
function
def expandBeats(beats, bSub): if bSub == 1: return beats import scipy.interpolate as interp idx = np.arange(beats.size) idxx = (np.arange(bSub*beats.size)/float(bSub))[0:-bSub+1] y = interp.spline(idx, beats, idxx) y = np.round(y) return np.array(y, dtype = np.int64)
def expandBeats(beats, bSub):
if bSub == 1: return beats import scipy.interpolate as interp idx = np.arange(beats.size) idxx = (np.arange(bSub*beats.size)/float(bSub))[0:-bSub+1] y = interp.spline(idx, beats, idxx) y = np.round(y) return np.array(y, dtype = np.int64)
1 = beats1[j+1]*hopSize-t1 beatsFinal.append(XFinal.shape[0]) XFinal = np.concatenate((XFinal, X[0:beat1, :])) return (XFinal, beatsFinal, scoresFinal) def expandBeats(beats, bSub):
64
64
94
10
54
ctralie/CoverSongSynthesis
Synchronize.py
Python
expandBeats
expandBeats
91
99
91
91
e446e994d66bb5418a84cb459694e61cbea6cc96
bigcode/the-stack
train
5c4c15a0840a51f5bc9f4fc0
train
function
def getGreedyPerm(D): """ Purpose: Naive O(N^2) algorithm to do the greedy permutation param: D (NxN distance matrix for points) return: (permutation (N-length array of indices), lambdas (N-length array of insertion radii)) """ N = D.shape[0] #By default, takes the first point in...
def getGreedyPerm(D):
""" Purpose: Naive O(N^2) algorithm to do the greedy permutation param: D (NxN distance matrix for points) return: (permutation (N-length array of indices), lambdas (N-length array of insertion radii)) """ N = D.shape[0] #By default, takes the first point in the list to be the ...
.CSMSSMTools import * from GeometricCoverSongs.BlockWindowFeatures import * from GeometricCoverSongs.pyMIRBasic.AudioIO import * from GeometricCoverSongs.pyMIRBasic.Onsets import * import json import pyrubberband as pyrb import subprocess def getGreedyPerm(D):
64
64
183
7
56
ctralie/CoverSongSynthesis
Synchronize.py
Python
getGreedyPerm
getGreedyPerm
20
38
20
20
ce8e2b191e7e04c49809bb8ef305d11d86a06380
bigcode/the-stack
train
ab7348796c466753831dffbc
train
function
def DynamicListedMenu(MenuListItems, FunctionsList): """ MenuListItems: List , FunctionsList: List Add a list of menu items followed by a list of functions to display a menu with numbered selections """ # add exit menu option to the menu list at the end of the list MenuListItems.insert(len(M...
def DynamicListedMenu(MenuListItems, FunctionsList):
""" MenuListItems: List , FunctionsList: List Add a list of menu items followed by a list of functions to display a menu with numbered selections """ # add exit menu option to the menu list at the end of the list MenuListItems.insert(len(MenuListItems), 'Exit Menu') # add a dummy functi...
def DynamicListedMenu(MenuListItems, FunctionsList):
11
84
282
11
0
Repo-cmd/LegoCV-Public
Modules/Menus/DynamicListedMenu.py
Python
DynamicListedMenu
DynamicListedMenu
1
30
1
1
04f0d9184953a7c7bfb00b8d9a22ea6743604152
bigcode/the-stack
train
722aca50e365f3d0290b5831
train
class
class Embargo: def __init__(self): self.api_url = "https://api.openaccessbutton.org/permissions/{}" self.table = "jump_embargo" self.load_openalex() self.harvest_embargos() def load_openalex(self): self.openalex_data = OpenalexDBRaw.query.all() for x in self.open...
class Embargo:
def __init__(self): self.api_url = "https://api.openaccessbutton.org/permissions/{}" self.table = "jump_embargo" self.load_openalex() self.harvest_embargos() def load_openalex(self): self.openalex_data = OpenalexDBRaw.query.all() for x in self.openalex_data: ...
import time import argparse import re from datetime import datetime from dateutil.parser import parse import requests from psycopg2 import sql from psycopg2.extras import execute_values from openalex import OpenalexDBRaw # class Empty(object): # pass # self = Empty() # self.__class__ = Embargo class Embargo:
79
179
598
4
74
Impactstory/jump-api
embargo_harvest.py
Python
Embargo
Embargo
17
78
17
17
fcc5786f92e35f689084dc62580e52c07c639522
bigcode/the-stack
train
87eec2d49657ed1962014da7
train
class
class Material: #--------------------------------------------------------------------------- # Add the types to the given module. #--------------------------------------------------------------------------- def __init__(self, mod, srcdir, topsrcdir, dims): self.dims = dims # Includes....
class Material: #--------------------------------------------------------------------------- # Add the types to the given module. #---------------------------------------------------------------------------
def __init__(self, mod, srcdir, topsrcdir, dims): self.dims = dims # Includes. mod.add_include('"%s/MaterialTypes.hh"' % srcdir) # Namespace. space = mod.add_cpp_namespace("Spheral") # Expose types. self.MaterialPressureMinType = space.add_enum("Materi...
from pybindgen import * from PBGutils import * #------------------------------------------------------------------------------- # The class to handle wrapping this module. #------------------------------------------------------------------------------- class Material: #-------------------------------------------...
48
256
2,912
21
27
as1m0n/spheral
src/PBGWraps/Material/MaterialModule.py
Python
Material
Material
8
269
8
12
e5be94b6d8a5403d78a609c1d9c3042eab9bd739
bigcode/the-stack
train
79648c88d016cb0fa7ce2a59
train
function
def generateEquationOfStateVirtualBindings(x, ndim, pureVirtual): scalarfield = "Spheral::ScalarField%id" % ndim # Methods. x.add_method("setPressure", None, [refparam(scalarfield, "pressure"), constrefparam(scalarfield, "massDensity"), ...
def generateEquationOfStateVirtualBindings(x, ndim, pureVirtual):
scalarfield = "Spheral::ScalarField%id" % ndim # Methods. x.add_method("setPressure", None, [refparam(scalarfield, "pressure"), constrefparam(scalarfield, "massDensity"), constrefparam(scalarfield, "specificThermalEnergy")], ...
double", "specificThermalEnergy")], is_const=True) x.add_method("gamma", "double", [param("double", "massDensity"), param("double", "specificThermalEnergy")], is_const=True) x.add_method("bulkModulus", "double", [param("d...
176
176
587
14
162
as1m0n/spheral
src/PBGWraps/Material/MaterialModule.py
Python
generateEquationOfStateVirtualBindings
generateEquationOfStateVirtualBindings
274
314
274
275
37c22d46721aee06c1c38816a53c28f796e5823c
bigcode/the-stack
train
c683289605d3f2ed8e3b6a69
train
function
def instantiateComponent(supcComponent): supcInstanceName = supcComponent.createStringSymbol("SUPC_INSTANCE_NAME", None) supcInstanceName.setVisible(False) supcInstanceName.setDefaultValue(supcComponent.getID().upper()) print("Running " + supcInstanceName.getValue()) # SM configuration supcSMM...
def instantiateComponent(supcComponent):
supcInstanceName = supcComponent.createStringSymbol("SUPC_INSTANCE_NAME", None) supcInstanceName.setVisible(False) supcInstanceName.setDefaultValue(supcComponent.getID().upper()) print("Running " + supcInstanceName.getValue()) # SM configuration supcSMMenu= supcComponent.createBooleanSymbol("SM...
AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAG...
198
198
663
8
189
Unitek-KL/csp
peripheral/supc_44082/config/supc.py
Python
instantiateComponent
instantiateComponent
29
79
29
30
e7ac71d138bf1dbf31fd2593722dd5751b89c88c
bigcode/the-stack
train
78bfed3daffe49cc423c0f5c
train
function
@contextlib.contextmanager def using_config(name, value): old_value = getattr(Config, name) setattr(Config, name, value) try: yield finally: setattr(Config, name, old_value)
@contextlib.contextmanager def using_config(name, value):
old_value = getattr(Config, name) setattr(Config, name, value) try: yield finally: setattr(Config, name, old_value)
): x = Variable(np.random.rand(1)) y = square(x) y.backward() num_grad = numerical_diff(square, x) flg = np.allclose(x.grad, num_grad) self.assertTrue(flg) @contextlib.contextmanager def using_config(name, value):
64
64
48
13
51
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
using_config
using_config
142
149
142
143
ce59b53be3cf5094438aedd0207dab03e41e86f1
bigcode/the-stack
train
a044a048e511cb4208a62c86
train
function
def numerical_diff(f, x, eps=1e-4): x0 = Variable(x.data - eps) x1 = Variable(x.data + eps) y0 = f(x0) y1 = f(x1) return (y1.data - y0.data) / (2 * eps)
def numerical_diff(f, x, eps=1e-4):
x0 = Variable(x.data - eps) x1 = Variable(x.data + eps) y0 = f(x0) y1 = f(x1) return (y1.data - y0.data) / (2 * eps)
x ** 2 return y def backward(self, gy): x = self.inputs[0].data gx = 2 * x * gy return gx def square(x): return Square()(x) def numerical_diff(f, x, eps=1e-4):
64
64
67
14
50
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
numerical_diff
numerical_diff
113
118
113
113
93bc618fc6031bb4f4b8ff584c44c2c7c1b8769b
bigcode/the-stack
train
9e14da80b22a871935cb698c
train
class
class Variable: def __init__(self, data): if data is not None: if not isinstance(data, np.ndarray): raise TypeError('{} is not supported'.format(type(data))) self.data = data self.grad = None self.creator = None self.generation = 0 def set_cr...
class Variable:
def __init__(self, data): if data is not None: if not isinstance(data, np.ndarray): raise TypeError('{} is not supported'.format(type(data))) self.data = data self.grad = None self.creator = None self.generation = 0 def set_creator(self, func...
#%% import unittest from xml.sax.xmlreader import InputSource import numpy as np import weakref import contextlib class Variable:
31
96
322
3
27
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
Variable
Variable
8
58
8
8
58bec2f8e19bc174bd15c7938253e71aae5910ec
bigcode/the-stack
train
f5b74df970e2e915f6d99e16
train
function
def add(x0, x1): return Add()(x0, x1)
def add(x0, x1):
return Add()(x0, x1)
return using_config('enable_backprop', False) #%% class Add(Function): def forward(self, x0, x1): y = x0 + x1 return y def backward(self, gy): return gy, gy # %% def add(x0, x1):
64
64
18
8
56
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
add
add
164
165
164
164
205eca868beabd7457b486c064e7388b5ed98d7b
bigcode/the-stack
train
0e799aba6bdbe4a4a3fb2cf4
train
function
def square(x): return Square()(x)
def square(x):
return Square()(x)
enable_backprop = True class Square(Function): def forward(self, x): y = x ** 2 return y def backward(self, gy): x = self.inputs[0].data gx = 2 * x * gy return gx def square(x):
64
64
10
4
59
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
square
square
109
110
109
109
0cf62d4a323c676c90be02d6bdfced1f55d1150d
bigcode/the-stack
train
facde1b241d0291f9ff3e003
train
function
def as_array(x): if np.isscalar(x): return np.array(x) return x
def as_array(x):
if np.isscalar(x): return np.array(x) return x
else: x.grad = x.grad + gx if x.creator is not None: add_func(x.creator) if not retain_grad: for y in f.outputs: y().grad = None def cleargrad(self): self.grad = None def as_array(x):
64
64
23
5
58
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
as_array
as_array
61
64
61
61
5b0486963e88b66b442238707d3c8c9d030718ad
bigcode/the-stack
train
610c906d904d0845f2d58253
train
class
class Function: def __call__(self, *inputs): xs = [x.data for x in inputs] ys = self.forward(*xs) if not isinstance(ys, tuple): ys = (ys,) outputs = [Variable(as_array(y)) for y in ys] if Config.enable_backprop: self.generation = max( ...
class Function:
def __call__(self, *inputs): xs = [x.data for x in inputs] ys = self.forward(*xs) if not isinstance(ys, tuple): ys = (ys,) outputs = [Variable(as_array(y)) for y in ys] if Config.enable_backprop: self.generation = max( x.generation for...
add_func(x.creator) if not retain_grad: for y in f.outputs: y().grad = None def cleargrad(self): self.grad = None def as_array(x): if np.isscalar(x): return np.array(x) return x class Function:
64
64
162
3
60
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
Function
Function
67
92
67
67
0303d054fa18b13c9adadc250674f93b058cf0bf
bigcode/the-stack
train
c4286630ff35a949da02ad22
train
class
class Add(Function): def forward(self, x0, x1): y = x0 + x1 return y def backward(self, gy): return gy, gy
class Add(Function):
def forward(self, x0, x1): y = x0 + x1 return y def backward(self, gy): return gy, gy
def using_config(name, value): old_value = getattr(Config, name) setattr(Config, name, value) try: yield finally: setattr(Config, name, old_value) def no_grad(): return using_config('enable_backprop', False) #%% class Add(Function):
64
64
41
4
60
ck-ksst/deep-learning-from-scratch-3
steps/step18.py
Python
Add
Add
155
161
155
155
bb57eee1b70aec395afd3721993f9f8c3a7fff9d
bigcode/the-stack
train