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
373cc79e198cb302d06dbf14
train
class
class UnprocessedParamType(ParamType): name = "text" def convert(self, value, param, ctx): return value def __repr__(self): return "UNPROCESSED"
class UnprocessedParamType(ParamType):
name = "text" def convert(self, value, param, ctx): return value def __repr__(self): return "UNPROCESSED"
, param, ctx): try: return self.func(value) except ValueError: try: value = str(value) except UnicodeError: value = value.decode("utf-8", "replace") self.fail(value, param, ctx) class UnprocessedParamType(ParamType):
64
64
45
9
55
click-contrib/asyncclick
src/click/types.py
Python
UnprocessedParamType
UnprocessedParamType
156
163
156
156
b57281ee7aa6833ba5a719c867290c5b458562c3
bigcode/the-stack
train
4646b1fd20752b8c993d6b40
train
class
class Path(ParamType): """The path type is similar to the :class:`File` type but it performs different checks. First of all, instead of returning an open file handle it returns just the filename. Secondly, it can perform various basic checks about what the file or directory should be. .. versionc...
class Path(ParamType):
"""The path type is similar to the :class:`File` type but it performs different checks. First of all, instead of returning an open file handle it returns just the filename. Secondly, it can perform various basic checks about what the file or directory should be. .. versionchanged:: 6.0 `al...
automatically close the file # at the end of the context execution (or flush out). If a # context does not exist, it's the caller's responsibility to # properly close the file. This for instance happens when the # type is used with prompts. if ctx is not No...
255
256
1,134
6
249
click-contrib/asyncclick
src/click/types.py
Python
Path
Path
645
789
645
645
9efe0762d672fd8c316e0aa62b9b2703e3d9bc58
bigcode/the-stack
train
490994060fead851670d5633
train
class
class ParamType: """Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of t...
class ParamType:
"""Represents the type of a parameter. Validates and converts values from the command line or Python into the correct type. To implement a custom type, subclass and implement at least the following: - The :attr:`name` class attribute must be set. - Calling an instance of the type with ``No...
import os import stat from datetime import datetime from ._compat import _get_argv_encoding from ._compat import filename_to_ui from ._compat import get_filesystem_encoding from ._compat import get_strerror from ._compat import open_stream from .exceptions import BadParameter from .utils import LazyFile from .utils im...
84
256
936
4
79
click-contrib/asyncclick
src/click/types.py
Python
ParamType
ParamType
15
123
15
15
9d7aa194bc716b155ca0f1fbca5ba9034782ed69
bigcode/the-stack
train
1b999a827da493521d2c7c74
train
class
class _NumberRangeBase(_NumberParamTypeBase): def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False): self.min = min self.max = max self.min_open = min_open self.max_open = max_open self.clamp = clamp async def to_info_dict(self): inf...
class _NumberRangeBase(_NumberParamTypeBase):
def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False): self.min = min self.max = max self.min_open = min_open self.max_open = max_open self.clamp = clamp async def to_info_dict(self): info_dict = await super().to_info_dict() ...
None: return converted plural = "s" if len(self.formats) > 1 else "" formats_str = ", ".join(repr(f) for f in self.formats) self.fail( f"{value!r} does not match the format{plural} {formats_str}.", param, ctx ) def __repr__(self): return "DateTi...
161
161
538
11
150
click-contrib/asyncclick
src/click/types.py
Python
_NumberRangeBase
_NumberRangeBase
357
425
357
357
abc60ca77853d3e7e75b93761df963684b05a55d
bigcode/the-stack
train
4934f5b2c83c4bfb74bacd32
train
function
def convert_type(ty, default=None): """Find the most appropriate :class:`ParamType` for the given Python type. If the type isn't provided, it can be inferred from a default value. """ guessed_type = False if ty is None and default is not None: if isinstance(default, (tuple, list)): ...
def convert_type(ty, default=None):
"""Find the most appropriate :class:`ParamType` for the given Python type. If the type isn't provided, it can be inferred from a default value. """ guessed_type = False if ty is None and default is not None: if isinstance(default, (tuple, list)): # If the default is empty, t...
return f"<{' '.join(ty.name for ty in self.types)}>" @property def arity(self): return len(self.types) def convert(self, value, param, ctx): if len(value) != len(self.types): raise TypeError( "It would appear that nargs is set to conflict with the" ...
113
113
378
9
104
click-contrib/asyncclick
src/click/types.py
Python
convert_type
convert_type
831
891
831
831
f729f2a1d217f968c455ef37fd03761284a1373a
bigcode/the-stack
train
aa6d43ca9ad6bc6dc66c04aa
train
class
class File(ParamType): """Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working). Files can be opened for reading or writing. The special value ``-`` indicates stdin or stdout depending on the mod...
class File(ParamType):
"""Declares a parameter to be a file for reading or writing. The file is automatically closed once the context tears down (after the command finished working). Files can be opened for reading or writing. The special value ``-`` indicates stdin or stdout depending on the mode. By default, the...
if needed. raise RuntimeError("Clamping is not supported for open bounds.") class BoolParamType(ParamType): name = "boolean" def convert(self, value, param, ctx): if value in {False, True}: return bool(value) norm = value.strip().lower() if norm in {"1", "true",...
249
249
832
6
243
click-contrib/asyncclick
src/click/types.py
Python
File
File
545
642
545
545
e7b21c60a6600a5107977344b075702b0aaeea93
bigcode/the-stack
train
5404d53a87cb9073e234eb72
train
class
class OASELogID: Ary = {} # LOSE Ary['LOSE00000'] = "Failed to get OASE_T_MAIL_ACTION_HISTORY table. (action_his_id: {}, Traceback: {})" Ary['LOSE00001'] = "Failed to get OASE_T_ITA_ACTION_HISTORY table. (action_his_id: {}, Traceback: {})" Ary['LOSE00002'] = "Error has occurred. {}" Ary['LOSE01000']...
class OASELogID:
Ary = {} # LOSE Ary['LOSE00000'] = "Failed to get OASE_T_MAIL_ACTION_HISTORY table. (action_his_id: {}, Traceback: {})" Ary['LOSE00001'] = "Failed to get OASE_T_ITA_ACTION_HISTORY table. (action_his_id: {}, Traceback: {})" Ary['LOSE00002'] = "Error has occurred. {}" Ary['LOSE01000'] = "RestAPI acces...
# Copyright 2019 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
147
256
18,078
6
141
wreathvine/oase
oase-root/libs/messages/oase_logid.py
Python
OASELogID
OASELogID
21
838
21
21
a898a17c5a0ae4f1fa88258691c5873e6645865c
bigcode/the-stack
train
343880e998c40675cd3015ee
train
class
class DayOfWeekField(BaseField): REAL = False COMPILERS = BaseField.COMPILERS + [WeekdayRangeExpression] def get_value(self, dateval): return dateval.weekday()
class DayOfWeekField(BaseField):
REAL = False COMPILERS = BaseField.COMPILERS + [WeekdayRangeExpression] def get_value(self, dateval): return dateval.weekday()
] class DayOfMonthField(BaseField): COMPILERS = BaseField.COMPILERS + [WeekdayPositionExpression, LastDayOfMonthExpression] def get_max(self, dateval): return monthrange(dateval.year, dateval.month)[1] class DayOfWeekField(BaseField):
64
64
46
8
56
hephaestus9/Ironworks
lib/apscheduler/triggers/cron/fields.py
Python
DayOfWeekField
DayOfWeekField
95
100
95
95
d6034b2888c766e3c3f04ebc087d91b1cf6f51fc
bigcode/the-stack
train
2ee2d92fc7c873c09c13cf8b
train
class
class WeekField(BaseField): REAL = False def get_value(self, dateval): return dateval.isocalendar()[1]
class WeekField(BaseField):
REAL = False def get_value(self, dateval): return dateval.isocalendar()[1]
__(self): expr_strings = (str(e) for e in self.expressions) return ','.join(expr_strings) def __repr__(self): return "%s('%s', '%s')" % (self.__class__.__name__, self.name, str(self)) class WeekField(BaseField):
64
64
30
6
58
hephaestus9/Ironworks
lib/apscheduler/triggers/cron/fields.py
Python
WeekField
WeekField
80
84
80
80
48e6888faf2b0bc9eea5db0d3ef680b040cd3f0d
bigcode/the-stack
train
e4fdb62f05d87f84c290c92e
train
class
class DayOfMonthField(BaseField): COMPILERS = BaseField.COMPILERS + [WeekdayPositionExpression, LastDayOfMonthExpression] def get_max(self, dateval): return monthrange(dateval.year, dateval.month)[1]
class DayOfMonthField(BaseField):
COMPILERS = BaseField.COMPILERS + [WeekdayPositionExpression, LastDayOfMonthExpression] def get_max(self, dateval): return monthrange(dateval.year, dateval.month)[1]
): return "%s('%s', '%s')" % (self.__class__.__name__, self.name, str(self)) class WeekField(BaseField): REAL = False def get_value(self, dateval): return dateval.isocalendar()[1] class DayOfMonthField(BaseField):
64
64
55
8
56
hephaestus9/Ironworks
lib/apscheduler/triggers/cron/fields.py
Python
DayOfMonthField
DayOfMonthField
87
92
87
87
419cdb72187c00ad598e4136c9a132a196035f0f
bigcode/the-stack
train
d5d9a84ab717fc4ccfc0c681
train
class
class BaseField(object): REAL = True COMPILERS = [AllExpression, RangeExpression] def __init__(self, name, exprs, is_default=False): self.name = name self.is_default = is_default self.compile_expressions(exprs) def get_min(self, dateval): return MIN_VALUES[self.name] ...
class BaseField(object):
REAL = True COMPILERS = [AllExpression, RangeExpression] def __init__(self, name, exprs, is_default=False): self.name = name self.is_default = is_default self.compile_expressions(exprs) def get_min(self, dateval): return MIN_VALUES[self.name] def get_max(self, date...
_VALUES = {'year': 2 ** 63, 'month': 12, 'day:': 31, 'week': 53, 'day_of_week': 6, 'hour': 23, 'minute': 59, 'second': 59} DEFAULT_VALUES = {'year': '*', 'month': 1, 'day': 1, 'week': '*', 'day_of_week': '*', 'hour': 0, 'minute': 0, 'second': 0} class BaseField(object):
113
113
378
5
108
hephaestus9/Ironworks
lib/apscheduler/triggers/cron/fields.py
Python
BaseField
BaseField
22
77
22
22
f983124c8e0e941d6f40906bba1b8a0ddcc8f470
bigcode/the-stack
train
0db82194372dbcc443aa74af
train
class
class AccountRoutes: class AccountView(StrictSchemaView): tags = ["Account"] class AccountInfo(AccountView): summary = "Get an account info" parameters = [] responses = { HTTPStatus.OK: response_definition( "Account information", schema=AccountInfoSch...
class AccountRoutes:
class AccountView(StrictSchemaView): tags = ["Account"] class AccountInfo(AccountView): summary = "Get an account info" parameters = [] responses = { HTTPStatus.OK: response_definition( "Account information", schema=AccountInfoSchema ), ...
# pyre-ignore-all-errors # Copyright (c) The Diem Core Contributors # SPDX-License-Identifier: Apache-2.0 from http import HTTPStatus from typing import Dict from flask import request, Blueprint import context from diem import identifier, utils from diem_utils.types.currencies import DiemCurrency from wallet.servic...
241
256
1,856
4
237
tanshuai/reference-wallet
backend/webapp/routes/account.py
Python
AccountRoutes
AccountRoutes
41
339
41
41
064cd2f3ab0bd0d05ecc16a1d2565dd52f72542a
bigcode/the-stack
train
8cbe7c32232d462805be12a0
train
function
def getsize(hi,ker,srd): pad = np.asarray((0,0)) dil = np.asarray((1,1)) new_size = np.asarray(hi) ker = np.asarray(ker) srd = np.asarray(srd) return(tuple((np.squeeze(\ (new_size+2*pad-dil*[ker-1]-1)/srd+1\ )).astype(int)))
def getsize(hi,ker,srd):
pad = np.asarray((0,0)) dil = np.asarray((1,1)) new_size = np.asarray(hi) ker = np.asarray(ker) srd = np.asarray(srd) return(tuple((np.squeeze(\ (new_size+2*pad-dil*[ker-1]-1)/srd+1\ )).astype(int)))
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def getsize(hi,ker,srd):
31
64
92
10
20
cherepas/circles_public
plot_output/e075/e075l007/cnet.py
Python
getsize
getsize
5
13
5
5
1e51fd827958899ac4d55b1e8083a87f49622608
bigcode/the-stack
train
ad9dd2163f404ce7cf961bbb
train
class
class CNet(torch.nn.Module): #network from Henderson, Ferrari article def __init__(self, hidden_dim, chidden_dim, kernel_sizes, cnum, h, w, usehaf): # , lb, ro, C, angles_list, super(CNet, self).__init__() # (h, w) = (h, w) # print('h, w=, ',h, w) self.use...
class CNet(torch.nn.Module): #network from Henderson, Ferrari article
def __init__(self, hidden_dim, chidden_dim, kernel_sizes, cnum, h, w, usehaf): # , lb, ro, C, angles_list, super(CNet, self).__init__() # (h, w) = (h, w) # print('h, w=, ',h, w) self.usehaf = usehaf if usehaf: self.conv0 = nn.Conv2d(cnum, 3...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def getsize(hi,ker,srd): pad = np.asarray((0,0)) dil = np.asarray((1,1)) new_size = np.asarray(hi) ker = np.asarray(ker) srd = np.asarray(srd) return(tuple((np.squeeze(\ (new_size+2*pad-dil*[ker-1]-1)/s...
129
256
1,099
16
113
cherepas/circles_public
plot_output/e075/e075l007/cnet.py
Python
CNet
CNet
14
107
14
15
2a9eba5f2b4b862e994df99887b145627d8b106a
bigcode/the-stack
train
8e3e91e7b85cf910fe23113b
train
function
def dbugp(s): if _debug: print(col.WHT+"["+col.BLK+"debug"+col.WHT+"] "+col.BLN+str(s))
def dbugp(s):
if _debug: print(col.WHT+"["+col.BLK+"debug"+col.WHT+"] "+col.BLN+str(s))
.BLN+str(s)) def logfp(s,logf=None): print(col.WHT+"["+col.MGN+" log"+col.WHT+"] "+col.BLN+str(s)) if logf is not None: logf.write(str(s)+"\n") def dbugp(s):
64
64
36
6
58
pcrain/review-reappropriator
common.py
Python
dbugp
dbugp
67
69
67
67
bbfe06c68b863d587ca89056c0c0b08e896a0831
bigcode/the-stack
train
6559374dc6b8567db41ad3ea
train
function
def timeit(method): def timed(*args, **kw): start = timer() result = method(*args, **kw) end = timer() dbugp(" Took {} seconds".format(end-start)) return result return timed
def timeit(method):
def timed(*args, **kw): start = timer() result = method(*args, **kw) end = timer() dbugp(" Took {} seconds".format(end-start)) return result return timed
["+col.CYN+" recv"+col.WHT+"] "+s+col.BLN) def passp(s): return getpass(col.WHT+"["+col.BLU+"paswd"+col.WHT+"] "+str(s)+col.BLN) #Timer decorator for method execution time def timeit(method):
64
64
56
5
58
pcrain/review-reappropriator
common.py
Python
timeit
timeit
85
92
85
85
f3e3d28241ccb6bd3c11a774086103ecd253e594
bigcode/the-stack
train
72e44fa98fd0d08385793de5
train
function
def findNgramInSortedList(item,sortedlist): ipoint = sortedlist.bisect_left([item,[DEFAULTTUPLE]]) return None if (ipoint == len(sortedlist) or (sortedlist[ipoint][0] != item)) else ipoint
def findNgramInSortedList(item,sortedlist):
ipoint = sortedlist.bisect_left([item,[DEFAULTTUPLE]]) return None if (ipoint == len(sortedlist) or (sortedlist[ipoint][0] != item)) else ipoint
tokenlist: if not RE_WORD.search(token[0]): continue if token[1] in STOPWORDS: #Check if lemmatized version is in stopwords continue validtokens.append(token) return validtokens def findNgramInSortedList(item,sortedlist):
64
64
58
12
51
pcrain/review-reappropriator
common.py
Python
findNgramInSortedList
findNgramInSortedList
239
241
239
239
fea28e4d32cc1c4f277f2b597f81f0ab5b17671f
bigcode/the-stack
train
d16dfb214405934e1154bed5
train
class
class MySocket: def __init__(self, sock=None): if sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def setsockopt(self,a,b,c): self.sock.setsockopt(a,b,c) def bind(self,hostport): self.sock.bind(hostport) def connect(self, host, por...
class MySocket:
def __init__(self, sock=None): if sock is None: self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: self.sock = sock def setsockopt(self,a,b,c): self.sock.setsockopt(a,b,c) def bind(self,hostport): self.sock.bind(hostport) def connect(self, host, port): self.soc...
# self.nlp = spacy.load('en_core_web_sm') def processText(self,text): structure = {} structure["text"] = text structure["_md5"] = md5(text) structure.update(nlpPreprocess(self.nlp,text)) structure["ideaunits"] = getIdeaUnits(structure) structure["unigrams"] = [] structure["bi...
199
199
664
4
194
pcrain/review-reappropriator
common.py
Python
MySocket
MySocket
284
376
284
284
3604c94003084b75bdce72d6d6e265225b712e4c
bigcode/the-stack
train
12297b4d7c0ba58e81b45485
train
function
def warnp(s): print(col.WHT+"["+col.YLW+" warn"+col.WHT+"] "+col.BLN+str(s))
def warnp(s):
print(col.WHT+"["+col.YLW+" warn"+col.WHT+"] "+col.BLN+str(s))
(col.WHT+"["+col.BLK+"debug"+col.WHT+"] "+col.BLN+str(s)) def simup(s): if _simulate: print(col.WHT+"["+col.CYN+"simul"+col.WHT+"] "+col.BLN+str(s)) def warnp(s):
64
64
30
5
59
pcrain/review-reappropriator
common.py
Python
warnp
warnp
73
74
73
73
01ebc8223b6528baf6f011ec6bc66642961d482a
bigcode/the-stack
train
3dd4c6eb6d085ff8d63b39f8
train
function
def sendp(s): print(col.WHT+"["+col.CYN+" send"+col.WHT+"] "+s+col.BLN)
def sendp(s):
print(col.WHT+"["+col.CYN+" send"+col.WHT+"] "+s+col.BLN)
print(col.WHT+"["+col.YLW+" warn"+col.WHT+"] "+col.BLN+str(s)) def erorp(s): sys.stderr.write(col.WHT+"["+col.RED+"error"+col.WHT+"] "+col.BLN+str(s)+"\n") def sendp(s):
64
64
29
5
59
pcrain/review-reappropriator
common.py
Python
sendp
sendp
77
78
77
77
ee21591fd982874de2280ee24f580280da07d16e
bigcode/the-stack
train
eacbdd5a70e8ce7520e915d4
train
function
def nlpPreprocess(nlpmodel,sentence): structure = {} structure["_tokens"] = [] structure["_units"] = [] sentence = sentence.lower() doc = nlpmodel(sentence) for token in doc: structure["_tokens"].append([ #Make sure this matches TOKEN_STRUCTURE above token.text, ...
def nlpPreprocess(nlpmodel,sentence):
structure = {} structure["_tokens"] = [] structure["_units"] = [] sentence = sentence.lower() doc = nlpmodel(sentence) for token in doc: structure["_tokens"].append([ #Make sure this matches TOKEN_STRUCTURE above token.text, #Plaintext of the token token...
given as substring spans def getRootSpan(token): spanmin = token.idx for child in token.children: spanmin = min(spanmin,getRootSpan(child)) return spanmin #Preprocess a string using our default nlp def nlpPreprocess(nlpmodel,sentence):
64
64
173
11
52
pcrain/review-reappropriator
common.py
Python
nlpPreprocess
nlpPreprocess
194
211
194
194
cb7d00c906f2a64be7ab6b3285dba9bec86964a2
bigcode/the-stack
train
c2e6d39038684e155f2adf7a
train
function
def compressedWrite(data,filename): with gzip.GzipFile(filename, 'w') as fout: fout.write(data.encode('utf-8'))
def compressedWrite(data,filename):
with gzip.GzipFile(filename, 'w') as fout: fout.write(data.encode('utf-8'))
file def jsonWrite(data,filename,indent=2): with open(filename, 'w') as fout: fout.write(json.dumps(data,indent=indent)) # pprint.PrettyPrinter(width=118,indent=indent,stream=fout).pprint(data) def compressedWrite(data,filename):
64
64
31
7
57
pcrain/review-reappropriator
common.py
Python
compressedWrite
compressedWrite
122
124
122
122
64e6ab7003a1f511ab11aedfde7080266ffb360c
bigcode/the-stack
train
1b4aad439e32b20d5c7595a2
train
function
def passp(s): return getpass(col.WHT+"["+col.BLU+"paswd"+col.WHT+"] "+str(s)+col.BLN)
def passp(s):
return getpass(col.WHT+"["+col.BLU+"paswd"+col.WHT+"] "+str(s)+col.BLN)
") def sendp(s): print(col.WHT+"["+col.CYN+" send"+col.WHT+"] "+s+col.BLN) def recvp(s): print(col.WHT+"["+col.CYN+" recv"+col.WHT+"] "+s+col.BLN) def passp(s):
64
64
33
5
59
pcrain/review-reappropriator
common.py
Python
passp
passp
81
82
81
81
ff1bc40fcceb4b27fb110e83590dd0d376811c95
bigcode/the-stack
train
bc5a5dfc562003452075827b
train
function
def infop(s): print(col.WHT+"["+col.GRN+" info"+col.WHT+"] "+col.BLN+str(s))
def infop(s):
print(col.WHT+"["+col.GRN+" info"+col.WHT+"] "+col.BLN+str(s))
m' # Cyan WHT = '\033[1;37m' # White # Useful printing codes (long) def inptp(s): return input(col.WHT+"["+col.BLU+"input"+col.WHT+"] "+str(s)+col.BLN) def infop(s):
64
64
30
5
59
pcrain/review-reappropriator
common.py
Python
infop
infop
62
63
62
62
bd57a5ffce8fa46cc5ee16b33f7c6ab65e206038
bigcode/the-stack
train
8fa0fbb9f34fa27c670ae57f
train
class
class NLP_Pipeline(): def __init__(self,model=None): self.nlp = spacy.load('en_core_web_sm' if model is None else model) # self.nlp = spacy.load('en_core_web_sm') def processText(self,text): structure = {} structure["text"] = text structure["_md5"] = md5(text) structure.update(nlpPr...
class NLP_Pipeline():
def __init__(self,model=None): self.nlp = spacy.load('en_core_web_sm' if model is None else model) # self.nlp = spacy.load('en_core_web_sm') def processText(self,text): structure = {} structure["text"] = text structure["_md5"] = md5(text) structure.update(nlpPreprocess(self.nlp,text...
similarphrases.append([ #Join the ngram and multiply the weights together ngram, reduce(lambda x, y: x*y, [p[0] for p in permutation]), ]) return similarphrases #Pipeline to transform a string of text into usable NLP metadata class NLP_Pipeline():
66
66
221
5
60
pcrain/review-reappropriator
common.py
Python
NLP_Pipeline
NLP_Pipeline
262
281
262
262
3b35778ee9f15d442819111345beb31a0b334d97
bigcode/the-stack
train
5a21b2189bb26d34b4cbffcb
train
function
def logfp(s,logf=None): print(col.WHT+"["+col.MGN+" log"+col.WHT+"] "+col.BLN+str(s)) if logf is not None: logf.write(str(s)+"\n")
def logfp(s,logf=None):
print(col.WHT+"["+col.MGN+" log"+col.WHT+"] "+col.BLN+str(s)) if logf is not None: logf.write(str(s)+"\n")
return input(col.WHT+"["+col.BLU+"input"+col.WHT+"] "+str(s)+col.BLN) def infop(s): print(col.WHT+"["+col.GRN+" info"+col.WHT+"] "+col.BLN+str(s)) def logfp(s,logf=None):
64
64
52
9
55
pcrain/review-reappropriator
common.py
Python
logfp
logfp
64
66
64
64
be2f89b756f534be9d75ce473b63c9f84039fdb6
bigcode/the-stack
train
cae7c8a6de2c54f2e612e22b
train
class
class JsonStreamLoader: # from jsonstreamer import JSONStreamer def __init__(self): self._json_streamer = JSONStreamer() #same for JSONStreamer self.partial_json = None self.substructures = [] self.keys = [] # self._dicttype = SortedDict # self._dicttype ...
class JsonStreamLoader: # from jsonstreamer import JSONStreamer
def __init__(self): self._json_streamer = JSONStreamer() #same for JSONStreamer self.partial_json = None self.substructures = [] self.keys = [] # self._dicttype = SortedDict # self._dicttype = blist.sorteddict # self._dicttype = blist.sorteddict ...
len(chunk) bb = b''.join(chunks) # print(bb) return bb def receiveInt(self): nbytes = struct.unpack(">b",self.receiveBytes(1))[0] if nbytes == 1: return struct.unpack(">b",self.receiveBytes(nbytes)) elif nbytes == 2: return struct.unpack(">h",self.receiveBytes(nbytes)) elif n...
217
217
726
15
201
pcrain/review-reappropriator
common.py
Python
JsonStreamLoader
JsonStreamLoader
379
458
379
380
63cee593a2ed27846c56c7ce463c4302ade8b820
bigcode/the-stack
train
b1aa610663d702df9b849403
train
function
def erorp(s): sys.stderr.write(col.WHT+"["+col.RED+"error"+col.WHT+"] "+col.BLN+str(s)+"\n")
def erorp(s):
sys.stderr.write(col.WHT+"["+col.RED+"error"+col.WHT+"] "+col.BLN+str(s)+"\n")
_simulate: print(col.WHT+"["+col.CYN+"simul"+col.WHT+"] "+col.BLN+str(s)) def warnp(s): print(col.WHT+"["+col.YLW+" warn"+col.WHT+"] "+col.BLN+str(s)) def erorp(s):
64
64
34
5
59
pcrain/review-reappropriator
common.py
Python
erorp
erorp
75
76
75
75
190450ead77cb53c8250b914927c4622a02e68c4
bigcode/the-stack
train
61fddb5d9964c74b6cca26cf
train
function
def inptp(s): return input(col.WHT+"["+col.BLU+"input"+col.WHT+"] "+str(s)+col.BLN)
def inptp(s):
return input(col.WHT+"["+col.BLU+"input"+col.WHT+"] "+str(s)+col.BLN)
m' # Blue MGN = '\033[1;35m' # Magenta CYN = '\033[1;36m' # Cyan WHT = '\033[1;37m' # White # Useful printing codes (long) def inptp(s):
64
64
32
6
58
pcrain/review-reappropriator
common.py
Python
inptp
inptp
60
61
60
60
b3a0e5c8390d05a0a105339d80819735097f8439
bigcode/the-stack
train
09467a3a06606890894af9d1
train
class
class col: BLN = '\033[0m' # Blank UND = '\033[1;4m' # Underlined INV = '\033[1;7m' # Inverted CRT = '\033[1;41m' # Critical BLK = '\033[1;30m' # Black RED = '\033[1;31m' # Red GRN = '\033[1;32m' # Green YLW = '\033[1;33m' # Yellow BLU = '\033[1;34m' # Blue MGN = '\033[1;35m' # Magenta CYN = ...
class col:
BLN = '\033[0m' # Blank UND = '\033[1;4m' # Underlined INV = '\033[1;7m' # Inverted CRT = '\033[1;41m' # Critical BLK = '\033[1;30m' # Black RED = '\033[1;31m' # Red GRN = '\033[1;32m' # Green YLW = '\033[1;33m' # Yellow BLU = '\033[1;34m' # Blue MGN = '\033[1;35m' # Magenta CYN = '\033[1;36m...
'was', 'here', 'than' } ALPHA = 'abcdefghijklmnopqrstuvwxyz' RE_WORD = re.compile(r"""[\-\'a-zA-Z]{2,}""") DEFAULTTUPLE = [0,9999,9999] _debug = True #Colors class col:
64
64
183
3
60
pcrain/review-reappropriator
common.py
Python
col
col
45
57
45
45
c24cb4d84b742a262ba960e0eaa8a0d5d300e722
bigcode/the-stack
train
0cf15406d97bdbadc72e89e0
train
function
def writeDictToCsv(file,headerfields,datadict): with open(file,'w') as fout: writer = csv.writer(fout,delimiter='\t') writer.writerow(headerfields) for entry in datadict: writer.writerow([entry[f] if f in entry else "" for f in headerfields])
def writeDictToCsv(file,headerfields,datadict):
with open(file,'w') as fout: writer = csv.writer(fout,delimiter='\t') writer.writerow(headerfields) for entry in datadict: writer.writerow([entry[f] if f in entry else "" for f in headerfields])
= timer() result = method(*args, **kw) end = timer() dbugp(" Took {} seconds".format(end-start)) return result return timed #Write a list of dictionaries to a CSV def writeDictToCsv(file,headerfields,datadict):
64
64
69
14
49
pcrain/review-reappropriator
common.py
Python
writeDictToCsv
writeDictToCsv
95
100
95
95
7ae76a53a39efffa55ca28e3490ed7e42188d0ef
bigcode/the-stack
train
81f2e0e67f5c8b8a86378f28
train
function
def getValidTokens(tokenlist): validtokens = [] for token in tokenlist: if not RE_WORD.search(token[0]): continue if token[1] in STOPWORDS: #Check if lemmatized version is in stopwords continue validtokens.append(token) return validtokens
def getValidTokens(tokenlist):
validtokens = [] for token in tokenlist: if not RE_WORD.search(token[0]): continue if token[1] in STOPWORDS: #Check if lemmatized version is in stopwords continue validtokens.append(token) return validtokens
its-1): curunit += 1 units.append([]) nextunitpos = len(review["text"]) if (curunit == nunits-1) else review["_units"][curunit+1] units[-1].append(t) return units def getValidTokens(tokenlist):
64
64
68
7
56
pcrain/review-reappropriator
common.py
Python
getValidTokens
getValidTokens
229
237
229
229
da8bc8945fa12084a6aa020a15d020ce869962d6
bigcode/the-stack
train
ed81f5ebac0cffed812cbd0f
train
function
def recvp(s): print(col.WHT+"["+col.CYN+" recv"+col.WHT+"] "+s+col.BLN)
def recvp(s):
print(col.WHT+"["+col.CYN+" recv"+col.WHT+"] "+s+col.BLN)
): sys.stderr.write(col.WHT+"["+col.RED+"error"+col.WHT+"] "+col.BLN+str(s)+"\n") def sendp(s): print(col.WHT+"["+col.CYN+" send"+col.WHT+"] "+s+col.BLN) def recvp(s):
64
64
29
5
59
pcrain/review-reappropriator
common.py
Python
recvp
recvp
79
80
79
79
d7403302c7e2877a30e8c0243c0d55216a07cd70
bigcode/the-stack
train
7b55d81cbb7ef5bb65c45c87
train
function
def skipgrams(sequence, n, k, **kwargs): """ Returns all possible skipgrams generated from a sequence of items, as an iterator. Skipgrams are ngrams that allows tokens to be skipped. Refer to http://homepages.inf.ed.ac.uk/ballison/pdf/lrec_skipgrams.pdf :param sequence: the source data to be conver...
def skipgrams(sequence, n, k, **kwargs):
""" Returns all possible skipgrams generated from a sequence of items, as an iterator. Skipgrams are ngrams that allows tokens to be skipped. Refer to http://homepages.inf.ed.ac.uk/ballison/pdf/lrec_skipgrams.pdf :param sequence: the source data to be converted into trigrams :type sequence: seq...
Pad an ngram sequence def pad_sequence(sequence, n, pad_left=False, pad_right=False, pad_symbol=None): if pad_left: sequence = chain((pad_symbol,) * (n-1), sequence) if pad_right: sequence = chain(sequence, (pad_symbol,) * (n-1)) return sequence #Generate skipgrams from a sequence def skip...
91
91
305
12
78
pcrain/review-reappropriator
common.py
Python
skipgrams
skipgrams
155
184
155
155
6a5f9fa8d3ecf6ef53e51a76459cd2b0b6282352
bigcode/the-stack
train
3eef45876cc6e8558b557465
train
function
def jsonWrite(data,filename,indent=2): with open(filename, 'w') as fout: fout.write(json.dumps(data,indent=indent))
def jsonWrite(data,filename,indent=2):
with open(filename, 'w') as fout: fout.write(json.dumps(data,indent=indent))
ikey] : { f : row[i] for i,f in enumerate(fields) } for row in reader} #Create a directory and all children necessary def makedir(directory): os.makedirs(directory,exist_ok=True) #Write a JSON to a file def jsonWrite(data,filename,indent=2):
64
64
33
11
52
pcrain/review-reappropriator
common.py
Python
jsonWrite
jsonWrite
117
119
117
117
bc35e454d4103a2ab95d60906b8d25377f55f358
bigcode/the-stack
train
0bd6bc6b3424b3dda204267a
train
function
def pad_sequence(sequence, n, pad_left=False, pad_right=False, pad_symbol=None): if pad_left: sequence = chain((pad_symbol,) * (n-1), sequence) if pad_right: sequence = chain(sequence, (pad_symbol,) * (n-1)) return sequence
def pad_sequence(sequence, n, pad_left=False, pad_right=False, pad_symbol=None):
if pad_left: sequence = chain((pad_symbol,) * (n-1), sequence) if pad_right: sequence = chain(sequence, (pad_symbol,) * (n-1)) return sequence
print("obj.%s = %r" % (attr, getattr(obj, attr))) except: print("obj.%s = %s" % (attr, "error")) # Pad an ngram sequence def pad_sequence(sequence, n, pad_left=False, pad_right=False, pad_symbol=None):
64
64
65
19
44
pcrain/review-reappropriator
common.py
Python
pad_sequence
pad_sequence
147
152
147
147
06a3a808e9f51bc3f71547287b406a5600094b65
bigcode/the-stack
train
a939a720bb806c01696ec316
train
function
def makedir(directory): os.makedirs(directory,exist_ok=True)
def makedir(directory):
os.makedirs(directory,exist_ok=True)
: return [ { f : row[i] for i,f in enumerate(fields) } for row in reader ] return { row[ikey] : { f : row[i] for i,f in enumerate(fields) } for row in reader} #Create a directory and all children necessary def makedir(directory):
64
64
14
5
58
pcrain/review-reappropriator
common.py
Python
makedir
makedir
113
114
113
113
ddff5be3b548ea9c00df0273baad4942e25cef88
bigcode/the-stack
train
096a2a074fd124ac40a453f8
train
function
def loadCsvAsDict(file,ikey=None): with open(file,"r") as csvfile: reader = csv.reader((x.replace('\0', ' ') for x in csvfile),delimiter='\t',quoting=csv.QUOTE_NONE) fields = next(reader) ikey = None if not ikey in fields else fields.index(ikey) if ikey is None: return [ { f : row[i] for i,f in ...
def loadCsvAsDict(file,ikey=None):
with open(file,"r") as csvfile: reader = csv.reader((x.replace('\0', ' ') for x in csvfile),delimiter='\t',quoting=csv.QUOTE_NONE) fields = next(reader) ikey = None if not ikey in fields else fields.index(ikey) if ikey is None: return [ { f : row[i] for i,f in enumerate(fields) } for row in read...
(fout,delimiter='\t') writer.writerow(headerfields) for entry in datadict: writer.writerow([entry[f] if f in entry else "" for f in headerfields]) #Load a CSV into a list of dictionaries or dictionary of dictionaries def loadCsvAsDict(file,ikey=None):
64
64
131
10
53
pcrain/review-reappropriator
common.py
Python
loadCsvAsDict
loadCsvAsDict
103
110
103
103
b774571ef46c9ca79f59eb8c235b69f12fb12d11
bigcode/the-stack
train
5be65790456715ab9d3da6ef
train
function
def md5(string): return hashlib.md5(string.encode('utf-8')).hexdigest()
def md5(string):
return hashlib.md5(string.encode('utf-8')).hexdigest()
).encode('utf-8')) #Decompress and read a JSON from a file def compressedJsonRead(filename): with gzip.GzipFile(filename, 'r') as fin: return json.loads(fin.read().decode('utf-8')) #Compute md5sum for string def md5(string):
64
64
20
5
58
pcrain/review-reappropriator
common.py
Python
md5
md5
137
138
137
137
004d58309ea8bec4f00b5bb7c678da1721290359
bigcode/the-stack
train
358237eaffa7cebb27efeb94
train
function
def compressedJsonRead(filename): with gzip.GzipFile(filename, 'r') as fin: return json.loads(fin.read().decode('utf-8'))
def compressedJsonRead(filename):
with gzip.GzipFile(filename, 'r') as fin: return json.loads(fin.read().decode('utf-8'))
8')) #Compress and write a JSON to a file def compressedJsonWrite(data,filename): with gzip.GzipFile(filename, 'w') as fout: fout.write(json.dumps(data).encode('utf-8')) #Decompress and read a JSON from a file def compressedJsonRead(filename):
64
64
33
6
57
pcrain/review-reappropriator
common.py
Python
compressedJsonRead
compressedJsonRead
132
134
132
132
140df910a877e2d5611fa8b4105d540ffbbf1b88
bigcode/the-stack
train
edc291108c4a83f3685b2a9d
train
function
def findSimilarPhrases(item,similaritydict,max_synonyms=10): mutations = [[] for _ in item] #Generate an empty list of mutations for ind,word in enumerate([w[1] for w in item]): #Use lemmatized form of each word if word not in similaritydict: continue for synonym in similaritydict[word][:max_synonyms]...
def findSimilarPhrases(item,similaritydict,max_synonyms=10):
mutations = [[] for _ in item] #Generate an empty list of mutations for ind,word in enumerate([w[1] for w in item]): #Use lemmatized form of each word if word not in similaritydict: continue for synonym in similaritydict[word][:max_synonyms]: #Get the top max_synonyms for each word and it's sim-weight...
findNgramInSortedList(item,sortedlist): ipoint = sortedlist.bisect_left([item,[DEFAULTTUPLE]]) return None if (ipoint == len(sortedlist) or (sortedlist[ipoint][0] != item)) else ipoint def findSimilarPhrases(item,similaritydict,max_synonyms=10):
73
73
245
16
56
pcrain/review-reappropriator
common.py
Python
findSimilarPhrases
findSimilarPhrases
243
259
243
243
fff2a811abe38aa1b0469a3d036e3daa7e76a083
bigcode/the-stack
train
7089657f7fbf83265f9a7c31
train
function
def simup(s): if _simulate: print(col.WHT+"["+col.CYN+"simul"+col.WHT+"] "+col.BLN+str(s))
def simup(s):
if _simulate: print(col.WHT+"["+col.CYN+"simul"+col.WHT+"] "+col.BLN+str(s))
.BLN+str(s)) if logf is not None: logf.write(str(s)+"\n") def dbugp(s): if _debug: print(col.WHT+"["+col.BLK+"debug"+col.WHT+"] "+col.BLN+str(s)) def simup(s):
64
64
36
5
59
pcrain/review-reappropriator
common.py
Python
simup
simup
70
72
70
70
b9bb1e4b9b95d8b6c20a809f5afce4a9cbcfa415
bigcode/the-stack
train
3c4961871b228366afbff59f
train
function
def compressedJsonWrite(data,filename): with gzip.GzipFile(filename, 'w') as fout: fout.write(json.dumps(data).encode('utf-8'))
def compressedJsonWrite(data,filename):
with gzip.GzipFile(filename, 'w') as fout: fout.write(json.dumps(data).encode('utf-8'))
=118,indent=indent,stream=fout).pprint(data) def compressedWrite(data,filename): with gzip.GzipFile(filename, 'w') as fout: fout.write(data.encode('utf-8')) #Compress and write a JSON to a file def compressedJsonWrite(data,filename):
64
64
35
8
55
pcrain/review-reappropriator
common.py
Python
compressedJsonWrite
compressedJsonWrite
127
129
127
127
e66735306836da6c137c80dfe0b7870c11cb1ea9
bigcode/the-stack
train
33ec4f4db265d9aefba09c9b
train
function
def getRootSpan(token): spanmin = token.idx for child in token.children: spanmin = min(spanmin,getRootSpan(child)) return spanmin
def getRootSpan(token):
spanmin = token.idx for child in token.children: spanmin = min(spanmin,getRootSpan(child)) return spanmin
tail = ngram[1:] for skip_tail in combinations(tail, n - 1): if skip_tail[-1] is SENTINEL: continue yield head + skip_tail #Given a token, break it into idea units given as substring spans def getRootSpan(token):
64
64
37
6
57
pcrain/review-reappropriator
common.py
Python
getRootSpan
getRootSpan
187
191
187
187
87829d2840bba521807c5cb8f4e6f771249b660f
bigcode/the-stack
train
562b8826b770ce42a9125bc0
train
function
def dump(obj): for attr in dir(obj): try: print("obj.%s = %r" % (attr, getattr(obj, attr))) except: print("obj.%s = %s" % (attr, "error"))
def dump(obj):
for attr in dir(obj): try: print("obj.%s = %r" % (attr, getattr(obj, attr))) except: print("obj.%s = %s" % (attr, "error"))
with gzip.GzipFile(filename, 'r') as fin: return json.loads(fin.read().decode('utf-8')) #Compute md5sum for string def md5(string): return hashlib.md5(string.encode('utf-8')).hexdigest() # Dump an object's attributes def dump(obj):
64
64
52
4
59
pcrain/review-reappropriator
common.py
Python
dump
dump
141
144
141
141
99e305a4fa3b5d642a8464793e7587bfff5097b8
bigcode/the-stack
train
494c7673d667320018ecb61d
train
function
def getIdeaUnits(review): nunits = len(review["_units"]) if nunits == 1: return [review["_tokens"]] units = [ [] ] curunit = 0 nextunitpos = review["_units"][curunit+1] for t in review["_tokens"]: if t[2] >= nextunitpos: #t[2] = offset of token into string if (curunit < nunits-1): ...
def getIdeaUnits(review):
nunits = len(review["_units"]) if nunits == 1: return [review["_tokens"]] units = [ [] ] curunit = 0 nextunitpos = review["_units"][curunit+1] for t in review["_tokens"]: if t[2] >= nextunitpos: #t[2] = offset of token into string if (curunit < nunits-1): curunit += 1 ...
tag for token token.pos_, #Part of Speech tag for token token.head.idx, #Offset of parent token into the original string ]) if token.dep_ == "ROOT": structure["_units"].append(getRootSpan(token)) return structure def getIdeaUnits(review):
64
64
155
6
57
pcrain/review-reappropriator
common.py
Python
getIdeaUnits
getIdeaUnits
213
227
213
213
cdd27a7baa61fb8f7a41034d1081bb322ea87a1c
bigcode/the-stack
train
36e70566d4661a70cc1b1f81
train
class
class SubProcArgs: base = {'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT} win = {'creationflags': subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP} darwin = {'preexec_fn': os.setpgrp} linux = {} @classmethod def get_host_args(cls): if sys.platform.startswit...
class SubProcArgs:
base = {'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT} win = {'creationflags': subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP} darwin = {'preexec_fn': os.setpgrp} linux = {} @classmethod def get_host_args(cls): if sys.platform.startswith('win'): return cl...
cache(): global runzCache, runz_dir if runzCache is None: runz_dir = get_lazydir(True).joinpath('runz') runzCache = Cache(directory = runz_dir.as_posix()) return runzCache class SubProcArgs:
64
64
140
5
58
trisongz/lazycls
lazy/runz/core.py
Python
SubProcArgs
SubProcArgs
27
43
27
27
e74d5c8b0adfb67a49f03964ce9103bb08011b14
bigcode/the-stack
train
8c1b0f62ab9d9d8358d05966
train
class
class RunzType(type): @classmethod def run_system(cls, cmd: str): """ alias for os.system(cmd) """ return os.system(cmd) @classmethod def run_cmd(cls, cmd: Union[List[str], str], shell: bool = True, raise_error: bool = True, **kwargs): """ Uses subproces...
class RunzType(type): @classmethod
def run_system(cls, cmd: str): """ alias for os.system(cmd) """ return os.system(cmd) @classmethod def run_cmd(cls, cmd: Union[List[str], str], shell: bool = True, raise_error: bool = True, **kwargs): """ Uses subprocess.check_output(cmd, shell=shell, **kwarg...
def get_runzcache(): global runzCache, runz_dir if runzCache is None: runz_dir = get_lazydir(True).joinpath('runz') runzCache = Cache(directory = runz_dir.as_posix()) return runzCache class SubProcArgs: base = {'stdout': subprocess.PIPE, 'stderr': subprocess.STDOUT} win = {'creatio...
213
213
712
10
203
trisongz/lazycls
lazy/runz/core.py
Python
RunzType
RunzType
46
114
46
48
41ef2abe6f3d58beea7f66ad0e76713ea473f2da
bigcode/the-stack
train
c50c528ebb424a103e14f6d8
train
function
def get_runzcache(): global runzCache, runz_dir if runzCache is None: runz_dir = get_lazydir(True).joinpath('runz') runzCache = Cache(directory = runz_dir.as_posix()) return runzCache
def get_runzcache():
global runzCache, runz_dir if runzCache is None: runz_dir = get_lazydir(True).joinpath('runz') runzCache = Cache(directory = runz_dir.as_posix()) return runzCache
PathLike, get_lazydir from lazy.io.cachez import Cache from .utils import * runz_dir: PathLike = None #get_lazydir(True).joinpath('runz') runzCache: Cache = None # = Cache(directory = ) def get_runzcache():
64
64
63
6
58
trisongz/lazycls
lazy/runz/core.py
Python
get_runzcache
get_runzcache
19
24
19
19
db955bb479bd4213808f1575b80934163c763a59
bigcode/the-stack
train
ede9d9c023b359ebe1116560
train
function
def almostEqual(a, b, thresh=0.01): return a <= b + thresh * abs(b) and a >= b - thresh * abs(b)
def almostEqual(a, b, thresh=0.01):
return a <= b + thresh * abs(b) and a >= b - thresh * abs(b)
def almostEqual(a, b, thresh=0.01):
13
64
34
13
0
Sagar133/alpha-homora-v2-public-contract
tests/utils.py
Python
almostEqual
almostEqual
1
2
1
1
0da36ddf019c3d5649ea38c70c1a49564924dec2
bigcode/the-stack
train
f0afdd3db350b43e93a166d0
train
class
class ConfluenceReportBuilder(Builder): name = 'internal-confluence-report' def __init__(self, app): super(ConfluenceReportBuilder, self).__init__(app) def init(self): validate_configuration(self) self.config.sphinx_verbosity = self.app.verbosity
class ConfluenceReportBuilder(Builder):
name = 'internal-confluence-report' def __init__(self, app): super(ConfluenceReportBuilder, self).__init__(app) def init(self): validate_configuration(self) self.config.sphinx_verbosity = self.app.verbosity
: utf-8 -*- """ :copyright: Copyright 2020 Sphinx Confluence Builder Contributors (AUTHORS) :license: BSD-2-Clause (LICENSE) """ from sphinx.builders import Builder from sphinxcontrib.confluencebuilder.config.checks import validate_configuration class ConfluenceReportBuilder(Builder):
64
64
63
8
55
bob-schumaker/confluencebuilder
sphinxcontrib/confluencebuilder/reportbuilder.py
Python
ConfluenceReportBuilder
ConfluenceReportBuilder
10
18
10
10
4bccc9a6551c7f9b5cd37ea9568cd47cd3c8bb37
bigcode/the-stack
train
18e38cb461a44d77cb588b39
train
function
def run_load_test(): mock_test_file = load_json_file_test('load_tests_file_mock.json') bert_wrapper = BertModelWrapper() best_post_processor = BertNaturalAnswerPostprocessor() for num_word in num_words: start_time = time.time() print('----------------------------') print('load t...
def run_load_test():
mock_test_file = load_json_file_test('load_tests_file_mock.json') bert_wrapper = BertModelWrapper() best_post_processor = BertNaturalAnswerPostprocessor() for num_word in num_words: start_time = time.time() print('----------------------------') print('load test with ', num_word,...
100', '150', '200', '250', '300', '350', '400', '450', '500', '550', '600', '650', '700', '750', '800', '850', '900', '950', '1000' ] def run_load_test():
64
64
183
5
59
guillaume-chevalier/ReuBERT
test/acceptance/charges_test/bert_user_input_load_test.py
Python
run_load_test
run_load_test
20
45
20
20
ff4e4e08edcbc14691b68d1379cc9ebcc61afb86
bigcode/the-stack
train
985cf12995c6bdb68ac9828a
train
function
def load_json_file_test(json_name): with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), json_name), encoding="utf8") as json_data: return json.load(json_data)
def load_json_file_test(json_name):
with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), json_name), encoding="utf8") as json_data: return json.load(json_data)
import os import json import time from src.infrastructure.pipeline_steps.bert_model_wrapper import BertModelWrapper from src.infrastructure.pipeline_steps.bert_natural_answer_postprocessor import BertNaturalAnswerPostprocessor def load_json_file_test(json_name):
50
64
44
8
41
guillaume-chevalier/ReuBERT
test/acceptance/charges_test/bert_user_input_load_test.py
Python
load_json_file_test
load_json_file_test
9
11
9
9
f8ea7656f0328a9d4ec6522625dbde189e7a4e4d
bigcode/the-stack
train
0db099494afa6da97966f5f8
train
class
class MockRenderer(ScopeRenderer): def function(self, content: str, escape: bool = True) -> str: return self._wrap_with_scope_style(content, "entity.name.function") def punctuation(self, content: str) -> str: return self._wrap_with_scope_style(content, "punctuation") def parameter(self, c...
class MockRenderer(ScopeRenderer):
def function(self, content: str, escape: bool = True) -> str: return self._wrap_with_scope_style(content, "entity.name.function") def punctuation(self, content: str) -> str: return self._wrap_with_scope_style(content, "punctuation") def parameter(self, content: str, emphasize: bool = False...
""" JSON_STRINGIFY = """""" def create_signature(label: str, *param_labels, **kwargs) -> dict: raw = dict(label=label, parameters=list(dict(label=param_label) for param_label in param_labels)) raw.update(kwargs) return raw class MockRenderer(ScopeRenderer):
64
64
168
7
56
AmjadHD/LSP
tests/test_signature_help.py
Python
MockRenderer
MockRenderer
118
133
118
119
021dd78f19dcd9ec1c2186c5e45c14f1f749b88d
bigcode/the-stack
train
4be6447a0659e679f98ac108
train
class
class GetDocumentationTests(unittest.TestCase): def test_absent(self): self.assertIsNone(get_documentation({})) def test_is_str(self): self.assertEqual(get_documentation({'documentation': 'str'}), 'str') def test_is_dict(self): self.assertEqual(get_documentation({'documentation': ...
class GetDocumentationTests(unittest.TestCase):
def test_absent(self): self.assertIsNone(get_documentation({})) def test_is_str(self): self.assertEqual(get_documentation({'documentation': 'str'}), 'str') def test_is_dict(self): self.assertEqual(get_documentation({'documentation': {'value': 'value'}}), 'value')
, emphasize: bool = False) -> str: return '\n<{}{}>{}</{}>'.format(scope, " emphasize" if emphasize else "", content, scope) def markdown(self, content: str) -> str: return content renderer = MockRenderer() class GetDocumentationTests(unittest.TestCase):
64
64
77
8
56
AmjadHD/LSP
tests/test_signature_help.py
Python
GetDocumentationTests
GetDocumentationTests
139
148
139
140
53f8a8789cc95a63a1e4e1a498a77efd9130355d
bigcode/the-stack
train
ef10a90f77f66159dfd3b119
train
function
def create_signature(label: str, *param_labels, **kwargs) -> dict: raw = dict(label=label, parameters=list(dict(label=param_label) for param_label in param_labels)) raw.update(kwargs) return raw
def create_signature(label: str, *param_labels, **kwargs) -> dict:
raw = dict(label=label, parameters=list(dict(label=param_label) for param_label in param_labels)) raw.update(kwargs) return raw
.name.function> </pre></div> <p>Foobaring with a multiplier</p> <p><b>multiplier</b>: Change foobar to work on larger increments</p>""" JSON_STRINGIFY = """""" def create_signature(label: str, *param_labels, **kwargs) -> dict:
64
64
49
17
46
AmjadHD/LSP
tests/test_signature_help.py
Python
create_signature
create_signature
112
115
112
112
598ab04e0403c813d1d55c1cfd0cbde0d2f2c9e0
bigcode/the-stack
train
d7c822fe37c4fa64a0220d22
train
class
class RenderSignatureLabelTests(unittest.TestCase): def test_no_parameters(self): sig = create_signature("foobar()") help = create_signature_help(dict(signatures=[sig])) if help: label = render_signature_label(renderer, help.active_signature(), 0) self.assertEqual(la...
class RenderSignatureLabelTests(unittest.TestCase):
def test_no_parameters(self): sig = create_signature("foobar()") help = create_signature_help(dict(signatures=[sig])) if help: label = render_signature_label(renderer, help.active_signature(), 0) self.assertEqual(label, "\n<entity.name.function>foobar()</entity.name.f...
.assertIsNotNone(help) if help: self.assertEqual(help._active_signature_index, 0) self.assertEqual(help._active_parameter_index, -1) def test_dockerfile_signature_help(self): info = parse_signature_information({ 'label': 'RUN [ "command" "parameters", ... ]', ...
256
256
981
9
247
AmjadHD/LSP
tests/test_signature_help.py
Python
RenderSignatureLabelTests
RenderSignatureLabelTests
190
276
190
191
6d453bafe518aa77d3b1c381ad304f109495755d
bigcode/the-stack
train
6c12818bb327e0a1e9f54ffe
train
class
class SignatureHelpTests(unittest.TestCase): def test_single_signature(self): help = SignatureHelp([signature_information]) self.assertIsNotNone(help) if help: content = help.build_popup_content(renderer) self.assertFalse(help.has_multiple_signatures()) s...
class SignatureHelpTests(unittest.TestCase):
def test_single_signature(self): help = SignatureHelp([signature_information]) self.assertIsNotNone(help) if help: content = help.build_popup_content(renderer) self.assertFalse(help.has_multiple_signatures()) self.assertEqual(content, SINGLE_SIGNATURE) ...
</variable.parameter>: int,\ <br>&nbsp;&nbsp;&nbsp;&nbsp;\n<variable.parameter emphasize>bar_if_needed</variable.parameter>: Optional[str],\ <br>&nbsp;&nbsp;&nbsp;&nbsp;\n<variable.parameter>in_uppercase</variable.parameter>: Optional[bool] <punctuation>)</punctuation> -&gt; Optional[str]</entity.name.function>""") c...
92
92
308
8
84
AmjadHD/LSP
tests/test_signature_help.py
Python
SignatureHelpTests
SignatureHelpTests
279
317
279
280
964d6201de816118fd7c1bc562391b53b5961685
bigcode/the-stack
train
810c3e2a61cfe1e3f7fbdcd2
train
class
class CreateSignatureHelpTests(unittest.TestCase): def test_none(self): self.assertIsNone(create_signature_help(None)) def test_empty(self): self.assertIsNone(create_signature_help({})) def test_default_indices(self): help = create_signature_help({"signatures": [signature]}) ...
class CreateSignatureHelpTests(unittest.TestCase):
def test_none(self): self.assertIsNone(create_signature_help(None)) def test_empty(self): self.assertIsNone(create_signature_help({})) def test_default_indices(self): help = create_signature_help({"signatures": [signature]}) self.assertIsNotNone(help) if help: ...
content renderer = MockRenderer() class GetDocumentationTests(unittest.TestCase): def test_absent(self): self.assertIsNone(get_documentation({})) def test_is_str(self): self.assertEqual(get_documentation({'documentation': 'str'}), 'str') def test_is_dict(self): self.assertEqu...
93
93
312
9
84
AmjadHD/LSP
tests/test_signature_help.py
Python
CreateSignatureHelpTests
CreateSignatureHelpTests
151
187
151
152
2f884dbfe834fd1ab7d42a342a0ce2d910ffc2ed
bigcode/the-stack
train
eb9215945ea88afb3969b417
train
class
class Animal(Model): __table__="animals"
class Animal(Model):
__table__="animals"
"""Animal Model.""" from masoniteorm.models import Model class Animal(Model):
16
64
11
4
11
ehuber0601/online_zoo_backend
app/Animal.py
Python
Animal
Animal
6
7
6
6
4836ec4b2258e48c0af229c154c9bd0f117a6996
bigcode/the-stack
train
6b54f6e8b8dc87c7e77df969
train
class
class Broker: """ This class provides a template interface for all those broker related actions/tasks wrapping the actual implementation class internally """ factory: BrokerFactory stocks_ifc: StocksInterface account_ifc: AccountInterface def __init__(self, factory: BrokerFactory) -> N...
class Broker:
""" This class provides a template interface for all those broker related actions/tasks wrapping the actual implementation class internally """ factory: BrokerFactory stocks_ifc: StocksInterface account_ifc: AccountInterface def __init__(self, factory: BrokerFactory) -> None: s...
from typing import Any, Dict, List, Optional from ...interfaces import Market, MarketHistory, MarketMACD, Position from .. import Interval, TradeDirection from . import AccountInterface, BrokerFactory, StocksInterface class Broker:
49
198
662
3
45
stungkit/TradingBot
tradingbot/components/broker/broker.py
Python
Broker
Broker
8
99
8
8
6ac3e9471ff889debc28a280cea93c0410d96412
bigcode/the-stack
train
15d5be7485dccab8096595c3
train
function
def generate_user_knowledge_database(answers_dict): # texts = pd.read_csv("3000.csv") user_id = answers_dict['username'] user_tests_stack = redis_db.get("username_" + user_id + "_last_test") print("generate_user_knowledge_database >> user_tests_stack", user_tests_stack) if user_tests_stack is not N...
def generate_user_knowledge_database(answers_dict): # texts = pd.read_csv("3000.csv")
user_id = answers_dict['username'] user_tests_stack = redis_db.get("username_" + user_id + "_last_test") print("generate_user_knowledge_database >> user_tests_stack", user_tests_stack) if user_tests_stack is not None: # user_tests_stack["username_" + user_id + "_last_test"] = None redis_...
json.load(f) """ json_text_map = get_text_map("./text_8.txt") #print(json_text_map['sentences_map'][0]) user.update_vector_with_answer_sentence(json_text_map['sentences_map'][0],1) user.update_vector_with_answer_sentence(json_text_map['sentences_map'][4],1) user.update_vector_with_answer_sentence(json_text_map['sen...
113
113
377
22
91
NatalieIsupova/hseling-repo-autotutor
hseling_api_autotutor/app/recommendation_logic/get_marked_datasets.py
Python
generate_user_knowledge_database
generate_user_knowledge_database
35
63
35
37
9edda33726df71565dfe77ccec91a981017d71b4
bigcode/the-stack
train
d7b7ecc59ae0523319d16998
train
function
def hex_bits(features): # We always to full bytes flen = (max(features + [0]) + 7) // 8 * 8 res = bitstring.BitArray(length=flen) # Big endian sucketh. for f in features: res[flen - 1 - f] = 1 return res.hex
def hex_bits(features): # We always to full bytes
flen = (max(features + [0]) + 7) // 8 * 8 res = bitstring.BitArray(length=flen) # Big endian sucketh. for f in features: res[flen - 1 - f] = 1 return res.hex
ln.testing.utils import EXPERIMENTAL_DUAL_FUND EXPERIMENTAL_FEATURES = env("EXPERIMENTAL_FEATURES", "0") == "1" COMPAT = env("COMPAT", "1") == "1" def hex_bits(features): # We always to full bytes
64
64
78
13
51
openoms/lightning
tests/utils.py
Python
hex_bits
hex_bits
11
18
11
12
e81a6052e06d917b7049527416ed546689f763a2
bigcode/the-stack
train
8ceb93706ceb6a659edc6472
train
function
def check_coin_moves(n, account_id, expected_moves, chainparams): moves = n.rpc.call('listcoinmoves_plugin')['coin_moves'] node_id = n.info['id'] acct_moves = [m for m in moves if m['account_id'] == account_id] for mv in acct_moves: print("{{'type': '{}', 'credit': {}, 'debit': {}, 'tag': '{}'}}...
def check_coin_moves(n, account_id, expected_moves, chainparams):
moves = n.rpc.call('listcoinmoves_plugin')['coin_moves'] node_id = n.info['id'] acct_moves = [m for m in moves if m['account_id'] == account_id] for mv in acct_moves: print("{{'type': '{}', 'credit': {}, 'debit': {}, 'tag': '{}'}}," .format(mv['type'], Millisa...
for this configuration""" features = [] return hex_bits(features + extra) def move_matches(exp, mv): if mv['type'] != exp['type']: return False if mv['credit'] != "{}msat".format(exp['credit']): return False if mv['debit'] != "{}msat".format(exp['debit']): return False ...
114
114
380
15
98
openoms/lightning
tests/utils.py
Python
check_coin_moves
check_coin_moves
77
114
77
77
cf4ed34662693c0c498d8a395a580f1fd41e3833
bigcode/the-stack
train
1bdb9614f1dc5d158386b496
train
function
def expected_peer_features(wumbo_channels=False, extra=[]): """Return the expected peer features hexstring for this configuration""" features = [1, 5, 7, 9, 11, 13, 15, 17, 27] if EXPERIMENTAL_FEATURES: # OPT_ONION_MESSAGES features += [103] # option_anchor_outputs features +...
def expected_peer_features(wumbo_channels=False, extra=[]):
"""Return the expected peer features hexstring for this configuration""" features = [1, 5, 7, 9, 11, 13, 15, 17, 27] if EXPERIMENTAL_FEATURES: # OPT_ONION_MESSAGES features += [103] # option_anchor_outputs features += [21] if wumbo_channels: features += [19] i...
7) // 8 * 8 res = bitstring.BitArray(length=flen) # Big endian sucketh. for f in features: res[flen - 1 - f] = 1 return res.hex def expected_peer_features(wumbo_channels=False, extra=[]):
64
64
146
12
51
openoms/lightning
tests/utils.py
Python
expected_peer_features
expected_peer_features
21
36
21
21
e6bf4baeda51df58d02732c5cd456cd6eee3e8f9
bigcode/the-stack
train
a10cf81726fc54c066586591
train
function
def move_matches(exp, mv): if mv['type'] != exp['type']: return False if mv['credit'] != "{}msat".format(exp['credit']): return False if mv['debit'] != "{}msat".format(exp['debit']): return False if mv['tag'] != exp['tag']: return False return True
def move_matches(exp, mv):
if mv['type'] != exp['type']: return False if mv['credit'] != "{}msat".format(exp['credit']): return False if mv['debit'] != "{}msat".format(exp['debit']): return False if mv['tag'] != exp['tag']: return False return True
option_dual_fund features += [29] return hex_bits(features + extra) def expected_channel_features(wumbo_channels=False, extra=[]): """Return the expected channel features hexstring for this configuration""" features = [] return hex_bits(features + extra) def move_matches(exp, mv):
64
64
83
7
57
openoms/lightning
tests/utils.py
Python
move_matches
move_matches
65
74
65
65
7ea2a0f6d5d11a684fb4c837ac15e43c97a93b1d
bigcode/the-stack
train
0167aa0255151f534d0a906a
train
function
def check_coin_moves_idx(n): """ Just check that the counter increments smoothly""" moves = n.rpc.call('listcoinmoves_plugin')['coin_moves'] idx = 0 for m in moves: c_idx = m['movement_idx'] # verify that the index count increments smoothly here, also if c_idx == 0 and idx == 0: ...
def check_coin_moves_idx(n):
""" Just check that the counter increments smoothly""" moves = n.rpc.call('listcoinmoves_plugin')['coin_moves'] idx = 0 for m in moves: c_idx = m['movement_idx'] # verify that the index count increments smoothly here, also if c_idx == 0 and idx == 0: continue ...
_moves[number_moves:] else: if not move_matches(m, acct_moves[0]): raise ValueError("Unexpected move {}: {} != {}".format(num, acct_moves[0], m)) acct_moves = acct_moves[1:] assert acct_moves == [] def check_coin_moves_idx(n):
63
64
98
7
56
openoms/lightning
tests/utils.py
Python
check_coin_moves_idx
check_coin_moves_idx
117
127
117
117
fcd566a8e99779a03da294d54b24d0026eceab20
bigcode/the-stack
train
73634ba75be07b45ddd51608
train
function
def account_balance(n, account_id): moves = n.rpc.call('listcoinmoves_plugin')['coin_moves'] chan_moves = [m for m in moves if m['account_id'] == account_id] assert len(chan_moves) > 0 m_sum = 0 for m in chan_moves: m_sum += int(m['credit'][:-4]) m_sum -= int(m['debit'][:-4]) ret...
def account_balance(n, account_id):
moves = n.rpc.call('listcoinmoves_plugin')['coin_moves'] chan_moves = [m for m in moves if m['account_id'] == account_id] assert len(chan_moves) > 0 m_sum = 0 for m in chan_moves: m_sum += int(m['credit'][:-4]) m_sum -= int(m['debit'][:-4]) return m_sum
moves: c_idx = m['movement_idx'] # verify that the index count increments smoothly here, also if c_idx == 0 and idx == 0: continue assert c_idx == idx + 1 idx = c_idx def account_balance(n, account_id):
64
64
97
8
55
openoms/lightning
tests/utils.py
Python
account_balance
account_balance
130
138
130
130
f869ab1b82d5296101baac2c0e8727aaddb5bc0d
bigcode/the-stack
train
899407facb982a06cabd01c0
train
function
def expected_channel_features(wumbo_channels=False, extra=[]): """Return the expected channel features hexstring for this configuration""" features = [] return hex_bits(features + extra)
def expected_channel_features(wumbo_channels=False, extra=[]):
"""Return the expected channel features hexstring for this configuration""" features = [] return hex_bits(features + extra)
: features += [19] if EXPERIMENTAL_DUAL_FUND: # option_anchor_outputs features += [21] # option_dual_fund features += [29] return hex_bits(features + extra) def expected_channel_features(wumbo_channels=False, extra=[]):
64
64
37
12
52
openoms/lightning
tests/utils.py
Python
expected_channel_features
expected_channel_features
59
62
59
59
52e3ab4e03c874a132eda40487af1c1965b4865b
bigcode/the-stack
train
6ae4380ed46953af55136770
train
function
def expected_node_features(wumbo_channels=False, extra=[]): """Return the expected node features hexstring for this configuration""" features = [1, 5, 7, 9, 11, 13, 15, 17, 27, 55] if EXPERIMENTAL_FEATURES: # OPT_ONION_MESSAGES features += [103] # option_anchor_outputs featur...
def expected_node_features(wumbo_channels=False, extra=[]):
"""Return the expected node features hexstring for this configuration""" features = [1, 5, 7, 9, 11, 13, 15, 17, 27, 55] if EXPERIMENTAL_FEATURES: # OPT_ONION_MESSAGES features += [103] # option_anchor_outputs features += [21] if wumbo_channels: features += [19] ...
_dual_fund features += [29] return hex_bits(features + extra) # With the addition of the keysend plugin, we now send a different set of # features for the 'node' and the 'peer' feature sets def expected_node_features(wumbo_channels=False, extra=[]):
64
64
149
12
51
openoms/lightning
tests/utils.py
Python
expected_node_features
expected_node_features
41
56
41
41
f2596816b596ddc3e35137ff6e1b573d3bfff226
bigcode/the-stack
train
91b4a6317214c2d625789b74
train
function
def scriptpubkey_addr(scriptpubkey): if 'addresses' in scriptpubkey: return scriptpubkey['addresses'][0] elif 'address' in scriptpubkey: # Modern bitcoin (at least, git master) return scriptpubkey['address'] return None
def scriptpubkey_addr(scriptpubkey):
if 'addresses' in scriptpubkey: return scriptpubkey['addresses'][0] elif 'address' in scriptpubkey: # Modern bitcoin (at least, git master) return scriptpubkey['address'] return None
): if EXPERIMENTAL_FEATURES or EXPERIMENTAL_DUAL_FUND: # option_anchor_outputs weight = 1124 else: weight = 724 return (weight * feerate) // 1000 def scriptpubkey_addr(scriptpubkey):
64
64
62
9
54
openoms/lightning
tests/utils.py
Python
scriptpubkey_addr
scriptpubkey_addr
154
160
154
154
9fb8c42df5551fffc7541d43690fde8cafa65230
bigcode/the-stack
train
8e7e16d69ef6a888f0f4bf38
train
function
def basic_fee(feerate): if EXPERIMENTAL_FEATURES or EXPERIMENTAL_DUAL_FUND: # option_anchor_outputs weight = 1124 else: weight = 724 return (weight * feerate) // 1000
def basic_fee(feerate):
if EXPERIMENTAL_FEATURES or EXPERIMENTAL_DUAL_FUND: # option_anchor_outputs weight = 1124 else: weight = 724 return (weight * feerate) // 1000
m_sum -= int(m['debit'][:-4]) return m_sum def first_channel_id(n1, n2): return only_one(only_one(n1.rpc.listpeers(n2.info['id'])['peers'])['channels'])['channel_id'] def basic_fee(feerate):
64
64
61
7
57
openoms/lightning
tests/utils.py
Python
basic_fee
basic_fee
145
151
145
145
1eeaee8861beb540e55b00c82de243cc2395a3b1
bigcode/the-stack
train
f751ded18bc60df3f59f7ccd
train
function
def first_channel_id(n1, n2): return only_one(only_one(n1.rpc.listpeers(n2.info['id'])['peers'])['channels'])['channel_id']
def first_channel_id(n1, n2):
return only_one(only_one(n1.rpc.listpeers(n2.info['id'])['peers'])['channels'])['channel_id']
assert len(chan_moves) > 0 m_sum = 0 for m in chan_moves: m_sum += int(m['credit'][:-4]) m_sum -= int(m['debit'][:-4]) return m_sum def first_channel_id(n1, n2):
64
64
40
10
53
openoms/lightning
tests/utils.py
Python
first_channel_id
first_channel_id
141
142
141
141
0e534a7ca6cab2ec5a2d12bdfb16140badbaa961
bigcode/the-stack
train
0e7210a2fba39db5a05ce9f0
train
class
class UnconfiguredProviderException(Exception): pass
class UnconfiguredProviderException(Exception):
pass
: blob}) out_fileno.write(header) out_fileno.flush() _aepipe.seal(key, in_fileno, out_fileno) @contextmanager def closing_fd(fd): try: yield fd finally: os.close(fd) class UnconfiguredProviderException(Exception):
64
64
10
7
57
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
UnconfiguredProviderException
UnconfiguredProviderException
88
89
88
88
f8a4faa14fb7b04486eaa8c64360bd493e1afc1c
bigcode/the-stack
train
45bbab5e0b946ae6fa8356c6
train
function
def seal(provider_name, provider_args, context, in_fileno, out_fileno): module = get_provider_by_name(provider_name) (plaintext, blob) = module.get_keypair(**provider_args) salt = os.urandom(64) checksum, key = derive_key(plaintext, salt, context) # The checksum serves only to identify whether the...
def seal(provider_name, provider_args, context, in_fileno, out_fileno):
module = get_provider_by_name(provider_name) (plaintext, blob) = module.get_keypair(**provider_args) salt = os.urandom(64) checksum, key = derive_key(plaintext, salt, context) # The checksum serves only to identify whether the correct key has been # derived. Most of the header could be garbage...
; indeed, it is an essential requirement # that the leakage of one key produced by the KDF should not compromise # other such keys" checksum = next(generator) return checksum, key def seal(provider_name, provider_args, context, in_fileno, out_fileno):
64
64
157
18
45
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
seal
seal
64
77
64
64
7ae72a5b391ff1ed2432dc5ce222920d64ff932a
bigcode/the-stack
train
a09fc65b4312883fbf9bc36f
train
function
def get_provider_by_name(name): module_name = providers[name] return get_provider_module(module_name)
def get_provider_by_name(name):
module_name = providers[name] return get_provider_module(module_name)
= b"" for i in range(0, 255): t = hmac(prk, t + info + bytes([1 + i]), hashlib.sha256) yield t def get_provider_module(module_name): return importlib.import_module(module_name) def get_provider_by_name(name):
64
64
22
7
57
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
get_provider_by_name
get_provider_by_name
42
44
42
42
6cff4aa84fda7cde6207445d3b75a054992116c2
bigcode/the-stack
train
1c91494a8de5b35dd2bdcc04
train
function
def _hkdf_generator(ikm, salt, info): # Using SHA-512 and truncating its output is explicitly endorsed by # https://eprint.iacr.org/2010/264.pdf , pg. 27 # Appendix D, #4 prk = hmac(salt, ikm, func=hashlib.sha512)[:32] t = b"" for i in range(0, 255): t = hmac(prk, t + info + bytes([1 + i...
def _hkdf_generator(ikm, salt, info): # Using SHA-512 and truncating its output is explicitly endorsed by # https://eprint.iacr.org/2010/264.pdf , pg. 27 # Appendix D, #4
prk = hmac(salt, ikm, func=hashlib.sha512)[:32] t = b"" for i in range(0, 255): t = hmac(prk, t + info + bytes([1 + i]), hashlib.sha256) yield t
data, func).digest() def _hkdf_generator(ikm, salt, info): # Using SHA-512 and truncating its output is explicitly endorsed by # https://eprint.iacr.org/2010/264.pdf , pg. 27 # Appendix D, #4
64
64
123
58
6
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
_hkdf_generator
_hkdf_generator
27
35
27
30
9e1afac253b665b9862f251097356418a2ebfc22
bigcode/the-stack
train
4f821c9a4171c967ede276fc
train
class
class InvalidKeyError(RuntimeError): pass
class InvalidKeyError(RuntimeError):
pass
._aepipe import AEError from .serialization import deserialize from .serialization import serialize providers = dict( kms="keypipe.managers.kms", vault="keypipe.managers.vault", keyfile="keypipe.managers.keyfile", ) class InvalidKeyError(RuntimeError):
64
64
10
7
57
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
InvalidKeyError
InvalidKeyError
19
20
19
19
cb16f700adbcce8c152776e8ccdfba1695732d37
bigcode/the-stack
train
fd9c3819f06fbdb5ecbc2d76
train
function
def derive_key(ikm, salt, context): generator = _hkdf_generator(ikm, salt, context) key = next(generator) # Hugo Krawczyk. "Cryptographic Extraction and Key Derivation: The HKDF # Scheme" https://eprint.iacr.org/2010/264.pdf p.21 # explicitly endorses disclosing other output from the KDF: # "...
def derive_key(ikm, salt, context):
generator = _hkdf_generator(ikm, salt, context) key = next(generator) # Hugo Krawczyk. "Cryptographic Extraction and Key Derivation: The HKDF # Scheme" https://eprint.iacr.org/2010/264.pdf p.21 # explicitly endorses disclosing other output from the KDF: # "Second, if the leakage of an output ...
+ bytes([1 + i]), hashlib.sha256) yield t def get_provider_module(module_name): return importlib.import_module(module_name) def get_provider_by_name(name): module_name = providers[name] return get_provider_module(module_name) def derive_key(ikm, salt, context):
64
64
184
11
53
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
derive_key
derive_key
47
61
47
47
cbd598b93b3c134a5a3ae2373584879ae4eb3ba0
bigcode/the-stack
train
90bb9bc6fe00de457576faa9
train
function
def unseal(provider_args, context, infile, outfile): salt, checksum, providers = deserialize(infile) for name, blob in providers: if name not in provider_args: continue args = provider_args[name] manager = get_provider_by_name(name) plaintext = manager.read_blob(blob...
def unseal(provider_args, context, infile, outfile):
salt, checksum, providers = deserialize(infile) for name, blob in providers: if name not in provider_args: continue args = provider_args[name] manager = get_provider_by_name(name) plaintext = manager.read_blob(blob, **args) derived_checksum, key = derive_key(pla...
() _aepipe.seal(key, in_fileno, out_fileno) @contextmanager def closing_fd(fd): try: yield fd finally: os.close(fd) class UnconfiguredProviderException(Exception): pass def unseal(provider_args, context, infile, outfile):
64
64
110
12
51
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
unseal
unseal
92
106
92
92
fcfe468a413d198e494e7882a29eb632e79609f4
bigcode/the-stack
train
ddf30fe27d2420814cc87ce5
train
function
def get_provider_module(module_name): return importlib.import_module(module_name)
def get_provider_module(module_name):
return importlib.import_module(module_name)
, ikm, func=hashlib.sha512)[:32] t = b"" for i in range(0, 255): t = hmac(prk, t + info + bytes([1 + i]), hashlib.sha256) yield t def get_provider_module(module_name):
64
64
16
7
56
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
get_provider_module
get_provider_module
38
39
38
38
2b9386312880427508da4a8d18e1822ba1f949ea
bigcode/the-stack
train
98b1ec0943051b9deb74d6fa
train
function
@contextmanager def closing_fd(fd): try: yield fd finally: os.close(fd)
@contextmanager def closing_fd(fd):
try: yield fd finally: os.close(fd)
# a correct key, the checksum will match. header = serialize(salt, checksum, {provider_name: blob}) out_fileno.write(header) out_fileno.flush() _aepipe.seal(key, in_fileno, out_fileno) @contextmanager def closing_fd(fd):
64
64
24
9
55
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
closing_fd
closing_fd
80
85
80
81
72473b63e6ff98642ea04c630c9f94608160c407
bigcode/the-stack
train
87ee8ef73ca5080c73e0c5c2
train
function
def hmac(key, data, func): return _hmac(key, data, func).digest()
def hmac(key, data, func):
return _hmac(key, data, func).digest()
import deserialize from .serialization import serialize providers = dict( kms="keypipe.managers.kms", vault="keypipe.managers.vault", keyfile="keypipe.managers.keyfile", ) class InvalidKeyError(RuntimeError): pass def hmac(key, data, func):
64
64
22
9
54
hashbrowncipher/gcmpipe
keypipe/__init__.py
Python
hmac
hmac
23
24
23
23
f7f3ac66f08a5d8f1e110842b19c76130e8a572e
bigcode/the-stack
train
441e8492918236c26b4391be
train
class
class DictAverageMeter(object): def __init__(self): self.data = {} self.count = 0 def update(self, new_input): self.count += 1 if len(self.data) == 0: for k, v in new_input.items(): if not isinstance(v, float): raise NotImplemented...
class DictAverageMeter(object):
def __init__(self): self.data = {} self.count = 0 def update(self, new_input): self.count += 1 if len(self.data) == 0: for k, v in new_input.items(): if not isinstance(v, float): raise NotImplementedError("invalid data {}: {}".form...
(mode, key) logger.add_image(name, preprocess(name, value), global_step) else: for idx in range(len(value)): name = '{}/{}_{}'.format(mode, key, idx) logger.add_image(name, preprocess(name, value[idx]), global_step) class DictAverageMeter(object):
64
64
162
6
58
Tangshengku/DDR-Net
utils.py
Python
DictAverageMeter
DictAverageMeter
104
123
104
104
3974f2a237f83f60285cab2ebc2fbc2e0c27386a
bigcode/the-stack
train
7ece2aad5911ecf6be6279e2
train
function
def reduce_scalar_outputs(scalar_outputs): world_size = get_world_size() if world_size < 2: return scalar_outputs with torch.no_grad(): names = [] scalars = [] for k in sorted(scalar_outputs.keys()): names.append(k) scalars.append(scalar_outputs[k]) ...
def reduce_scalar_outputs(scalar_outputs):
world_size = get_world_size() if world_size < 2: return scalar_outputs with torch.no_grad(): names = [] scalars = [] for k in sorted(scalar_outputs.keys()): names.append(k) scalars.append(scalar_outputs[k]) scalars = torch.stack(scalars, dim=0)...
.get_world_size() if world_size == 1: return dist.barrier() def get_world_size(): if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size() def reduce_scalar_outputs(scalar_outputs):
64
64
157
8
56
Tangshengku/DDR-Net
utils.py
Python
reduce_scalar_outputs
reduce_scalar_outputs
184
202
184
184
37db2d427e604d96ffea4abfa65be0b8ea46fe5b
bigcode/the-stack
train
581660f41ad01fae37be18ac
train
function
def set_random_seed(seed): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
def set_random_seed(seed):
random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed)
up_factor, self.gamma, self.milestones, self.last_epoch)) return [ base_lr * warmup_factor * self.gamma ** bisect_right(self.milestones, self.last_epoch) for base_lr in self.base_lrs ] def set_random_seed(seed):
63
64
31
6
57
Tangshengku/DDR-Net
utils.py
Python
set_random_seed
set_random_seed
256
260
256
256
1108ed474cda2e554ec005fbdd949fa3edf36b99
bigcode/the-stack
train
59ae3a02e4510fd647f7e9d1
train
function
def compute_metrics_for_each_image(metric_func): def wrapper(depth_est, depth_gt, mask, *args): batch_size = depth_gt.shape[0] results = [] # compute result one by one for idx in range(batch_size): ret = metric_func(depth_est[idx], depth_gt[idx], mask[idx], *args) ...
def compute_metrics_for_each_image(metric_func):
def wrapper(depth_est, depth_gt, mask, *args): batch_size = depth_gt.shape[0] results = [] # compute result one by one for idx in range(batch_size): ret = metric_func(depth_est[idx], depth_gt[idx], mask[idx], *args) results.append(ret) return torch.sta...
("invalid data {}: {}".format(k, type(v))) self.data[k] += v def mean(self): return {k: v / self.count for k, v in self.data.items()} # a wrapper to compute metrics for each image individually def compute_metrics_for_each_image(metric_func):
64
64
89
9
54
Tangshengku/DDR-Net
utils.py
Python
compute_metrics_for_each_image
compute_metrics_for_each_image
127
137
127
127
a9713fff25daa5d25445b8baa5ec4a75965f1f6b
bigcode/the-stack
train
381624aebdd27a6b117d0afe
train
function
def show_prob(depth_range,pro_volume,x,y): depth=depth_range[0].detach().cpu().numpy() prob=pro_volume[0].detach().cpu().numpy() prob=prob[:,1,1] depth=depth[:,1,1] plt.plot(depth,prob) plt.show() plt.savefig('1.jpg')
def show_prob(depth_range,pro_volume,x,y):
depth=depth_range[0].detach().cpu().numpy() prob=pro_volume[0].detach().cpu().numpy() prob=prob[:,1,1] depth=depth[:,1,1] plt.plot(depth,prob) plt.show() plt.savefig('1.jpg')
end_header %s ''' % (len(points), "".join(points))) file.close() print("save ply, fx:{}, fy:{}, cx:{}, cy:{}".format(fx, fy, cx, cy)) def show_prob(depth_range,pro_volume,x,y):
63
64
77
11
52
Tangshengku/DDR-Net
utils.py
Python
show_prob
show_prob
317
326
317
317
8ce28646ed6b5a79508f6408087a063759a25e16
bigcode/the-stack
train
e253e769b1e642fbb34d0776
train
function
@make_recursive_func def tensor2float(vars): if isinstance(vars, float): return vars elif isinstance(vars, torch.Tensor): return vars.data.item() else: raise NotImplementedError("invalid input type {} for tensor2float".format(type(vars)))
@make_recursive_func def tensor2float(vars):
if isinstance(vars, float): return vars elif isinstance(vars, torch.Tensor): return vars.data.item() else: raise NotImplementedError("invalid input type {} for tensor2float".format(type(vars)))
elif isinstance(vars, tuple): return tuple([wrapper(x) for x in vars]) elif isinstance(vars, dict): return {k: wrapper(v) for k, v in vars.items()} else: return func(vars) return wrapper @make_recursive_func def tensor2float(vars):
64
64
58
11
52
Tangshengku/DDR-Net
utils.py
Python
tensor2float
tensor2float
41
48
41
42
66d3c39bd34c1d6d207ae2fc581d7ce9474246b3
bigcode/the-stack
train
e48a9d88b5b588a2c74b8f80
train
function
@make_recursive_func def tocuda(vars): if isinstance(vars, torch.Tensor): return vars.to(torch.device("cuda")) elif isinstance(vars, str): return vars else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars)))
@make_recursive_func def tocuda(vars):
if isinstance(vars, torch.Tensor): return vars.to(torch.device("cuda")) elif isinstance(vars, str): return vars else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars)))
if isinstance(vars, np.ndarray): return vars elif isinstance(vars, torch.Tensor): return vars.detach().cpu().numpy().copy() else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars))) @make_recursive_func def tocuda(vars):
63
64
60
10
53
Tangshengku/DDR-Net
utils.py
Python
tocuda
tocuda
61
68
61
62
49723a0276ab7e1a6057751b9c93b7d33ebddfa6
bigcode/the-stack
train
8451584b2086ff1792e0dcd9
train
function
def get_world_size(): if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size()
def get_world_size():
if not dist.is_available(): return 1 if not dist.is_initialized(): return 1 return dist.get_world_size()
rier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.barrier() def get_world_size():
64
64
36
5
59
Tangshengku/DDR-Net
utils.py
Python
get_world_size
get_world_size
177
182
177
177
e3a522da0c20c013eb6f3dca8fb2e0c47c620212
bigcode/the-stack
train
0f51f3699ee1157c12d76633
train
function
def make_recursive_func(func): def wrapper(vars): if isinstance(vars, list): return [wrapper(x) for x in vars] elif isinstance(vars, tuple): return tuple([wrapper(x) for x in vars]) elif isinstance(vars, dict): return {k: wrapper(v) for k, v in vars.items(...
def make_recursive_func(func):
def wrapper(vars): if isinstance(vars, list): return [wrapper(x) for x in vars] elif isinstance(vars, tuple): return tuple([wrapper(x) for x in vars]) elif isinstance(vars, dict): return {k: wrapper(v) for k, v in vars.items()} else: re...
_nograd_func(func): def wrapper(*f_args, **f_kwargs): with torch.no_grad(): ret = func(*f_args, **f_kwargs) return ret return wrapper # convert a function into recursive style to handle nested dict/list/tuple variables def make_recursive_func(func):
64
64
83
6
57
Tangshengku/DDR-Net
utils.py
Python
make_recursive_func
make_recursive_func
27
38
27
27
42f8efb57a2963b60c53878e8cbb647b3f39725f
bigcode/the-stack
train
eb97941fec1df753e8820289
train
function
@make_recursive_func def tensor2numpy(vars): if isinstance(vars, np.ndarray): return vars elif isinstance(vars, torch.Tensor): return vars.detach().cpu().numpy().copy() else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars)))
@make_recursive_func def tensor2numpy(vars):
if isinstance(vars, np.ndarray): return vars elif isinstance(vars, torch.Tensor): return vars.detach().cpu().numpy().copy() else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars)))
tensor2float(vars): if isinstance(vars, float): return vars elif isinstance(vars, torch.Tensor): return vars.data.item() else: raise NotImplementedError("invalid input type {} for tensor2float".format(type(vars))) @make_recursive_func def tensor2numpy(vars):
63
64
64
11
52
Tangshengku/DDR-Net
utils.py
Python
tensor2numpy
tensor2numpy
51
58
51
52
8b7c70fe36d5b8c67280ad712ae773820845002d
bigcode/the-stack
train
75b9f0cf7555502804193f00
train
function
def synchronize(): """ Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.b...
def synchronize():
""" Helper function to synchronize (barrier) among all processes when using distributed training """ if not dist.is_available(): return if not dist.is_initialized(): return world_size = dist.get_world_size() if world_size == 1: return dist.barrier()
[(error >= float(thres[0])) & (error <= float(thres[1]))] if error.shape[0] == 0: return torch.tensor(0, device=error.device, dtype=error.dtype) return torch.mean(error) import torch.distributed as dist def synchronize():
64
64
71
3
60
Tangshengku/DDR-Net
utils.py
Python
synchronize
synchronize
163
175
163
163
e6e3db153b5a0bad471cf9a93add277fa84402bc
bigcode/the-stack
train
f9792416ee8f7297d7bb2346
train
function
def save_images(logger, mode, images_dict, global_step): images_dict = tensor2numpy(images_dict) def preprocess(name, img): if not (len(img.shape) == 3 or len(img.shape) == 4): raise NotImplementedError("invalid img shape {}:{} in save_images".format(name, img.shape)) if len(img.sha...
def save_images(logger, mode, images_dict, global_step):
images_dict = tensor2numpy(images_dict) def preprocess(name, img): if not (len(img.shape) == 3 or len(img.shape) == 4): raise NotImplementedError("invalid img shape {}:{} in save_images".format(name, img.shape)) if len(img.shape) == 3: img = img[:, np.newaxis, :, :] ...
, key) logger.add_scalar(name, value, global_step) else: for idx in range(len(value)): name = '{}/{}_{}'.format(mode, key, idx) logger.add_scalar(name, value[idx], global_step) def save_images(logger, mode, images_dict, global_step):
64
64
212
13
51
Tangshengku/DDR-Net
utils.py
Python
save_images
save_images
83
101
83
83
2ea0f0337ca563cc73adaeedc0e0436fb531cfe9
bigcode/the-stack
train
a67600459d70fa50c6c5249e
train
function
def generate_pointcloud(rgb, depth, ply_file, intr, scale=1.0): """ Generate a colored point cloud in PLY format from a color and a depth image. Input: rgb_file -- filename of color image depth_file -- filename of depth image ply_file -- filename of ply file """ fx, fy, cx, cy = intr[...
def generate_pointcloud(rgb, depth, ply_file, intr, scale=1.0):
""" Generate a colored point cloud in PLY format from a color and a depth image. Input: rgb_file -- filename of color image depth_file -- filename of depth image ply_file -- filename of ply file """ fx, fy, cx, cy = intr[0, 0], intr[1, 1], intr[0, 2], intr[1, 2] points = [] for...
np.ones_like(y)]) p3d = np.matmul(np.linalg.inv(intr), p2d) depth = depth.reshape(1, nx * ny) p3d *= depth p3d = np.transpose(p3d, (1, 0)) p3d = p3d.reshape(ny, nx, 3).astype(np.float32) return p3d def generate_pointcloud(rgb, depth, ply_file, intr, scale=1.0):
105
105
352
19
85
Tangshengku/DDR-Net
utils.py
Python
generate_pointcloud
generate_pointcloud
277
313
277
278
9f90670b0b9c06e689d464906628ae5c2efc14ee
bigcode/the-stack
train
cb8a7f23f70b7fe8c7f78aba
train
function
@make_nograd_func @compute_metrics_for_each_image def Thres_metrics(depth_est, depth_gt, mask, thres): assert isinstance(thres, (int, float)) depth_est, depth_gt = depth_est[mask], depth_gt[mask] errors = torch.abs(depth_est - depth_gt) err_mask = errors > thres return torch.mean(err_mask.float())
@make_nograd_func @compute_metrics_for_each_image def Thres_metrics(depth_est, depth_gt, mask, thres):
assert isinstance(thres, (int, float)) depth_est, depth_gt = depth_est[mask], depth_gt[mask] errors = torch.abs(depth_est - depth_gt) err_mask = errors > thres return torch.mean(err_mask.float())
ret = metric_func(depth_est[idx], depth_gt[idx], mask[idx], *args) results.append(ret) return torch.stack(results).mean() return wrapper @make_nograd_func @compute_metrics_for_each_image def Thres_metrics(depth_est, depth_gt, mask, thres):
64
64
84
28
35
Tangshengku/DDR-Net
utils.py
Python
Thres_metrics
Thres_metrics
140
147
140
142
3db46ad28aa8a886c6aae6ea924055081be8336c
bigcode/the-stack
train
c810b5fe9f42b9db73f48317
train
function
def save_scalars(logger, mode, scalar_dict, global_step): scalar_dict = tensor2float(scalar_dict) for key, value in scalar_dict.items(): if not isinstance(value, (list, tuple)): name = '{}/{}'.format(mode, key) logger.add_scalar(name, value, global_step) else: ...
def save_scalars(logger, mode, scalar_dict, global_step):
scalar_dict = tensor2float(scalar_dict) for key, value in scalar_dict.items(): if not isinstance(value, (list, tuple)): name = '{}/{}'.format(mode, key) logger.add_scalar(name, value, global_step) else: for idx in range(len(value)): name = '{}/...
if isinstance(vars, torch.Tensor): return vars.to(torch.device("cuda")) elif isinstance(vars, str): return vars else: raise NotImplementedError("invalid input type {} for tensor2numpy".format(type(vars))) def save_scalars(logger, mode, scalar_dict, global_step):
63
64
105
14
49
Tangshengku/DDR-Net
utils.py
Python
save_scalars
save_scalars
71
80
71
71
dc9cc1b63db955a2d0f177a3e0e89f3d539a972b
bigcode/the-stack
train
cab7ea385f1d19af1c203022
train
class
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler): def __init__( self, optimizer, milestones, gamma=0.1, warmup_factor=1.0 / 3, warmup_iters=500, warmup_method="linear", last_epoch=-1, ): if not list(milestones) == sorted(miles...
class WarmupMultiStepLR(torch.optim.lr_scheduler._LRScheduler):
def __init__( self, optimizer, milestones, gamma=0.1, warmup_factor=1.0 / 3, warmup_iters=500, warmup_method="linear", last_epoch=-1, ): if not list(milestones) == sorted(milestones): raise ValueError( "Milestone...
_rank() == 0: # only main process gets accumulated, so only divide by # world_size in this case scalars /= world_size reduced_scalars = {k: v for k, v in zip(names, scalars)} return reduced_scalars import torch from bisect import bisect_right # FIXME ideally this would ...
122
122
408
15
106
Tangshengku/DDR-Net
utils.py
Python
WarmupMultiStepLR
WarmupMultiStepLR
209
253
209
209
ff04de2ced1a538a2ccb20d51f81449f9c5f65f7
bigcode/the-stack
train
eb1e494e7c030b0c7dc3f240
train
function
def print_args(args): print("################################ args ################################") for k, v in args.__dict__.items(): print("{0: <10}\t{1: <30}\t{2: <20}".format(k, str(v), str(type(v)))) print("########################################################################")
def print_args(args):
print("################################ args ################################") for k, v in args.__dict__.items(): print("{0: <10}\t{1: <30}\t{2: <20}".format(k, str(v), str(type(v)))) print("########################################################################")
import numpy as np import torchvision.utils as vutils import torch, random import torch.nn.functional as F import matplotlib.pyplot as plt # print arguments def print_args(args):
39
64
63
5
33
Tangshengku/DDR-Net
utils.py
Python
print_args
print_args
9
13
9
9
30b33a86336777c907d9b486abe11e0f417d8576
bigcode/the-stack
train