hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
ccc1f64370ace7ca49451275029b6738329d4522
duncanbarth/UT330B
UT330BUI/model/UT330.py
[ "MIT" ]
Python
delete_data
null
def delete_data(self): """Deletes the temperature, humidity, and pressure data from the device""" # The delete command self._buffer = [0xab, 0xcd, 0x03, 0x18, 0xb1, 0x05] self._buffer[5], self._buffer[4] = modbusCRC(self._buffer[0:4]) # Write the command self....
Deletes the temperature, humidity, and pressure data from the device
Deletes the temperature, humidity, and pressure data from the device
[ "Deletes", "the", "temperature", "humidity", "and", "pressure", "data", "from", "the", "device" ]
def delete_data(self): self._buffer = [0xab, 0xcd, 0x03, 0x18, 0xb1, 0x05] self._buffer[5], self._buffer[4] = modbusCRC(self._buffer[0:4]) self._write_buffer() self._read_buffer(7) if [171, 205, 4, 24, 0, 116, 181] != self._buffer: raise IOError("Error! Delete data re...
[ "def", "delete_data", "(", "self", ")", ":", "self", ".", "_buffer", "=", "[", "0xab", ",", "0xcd", ",", "0x03", ",", "0x18", ",", "0xb1", ",", "0x05", "]", "self", ".", "_buffer", "[", "5", "]", ",", "self", ".", "_buffer", "[", "4", "]", "=",...
Deletes the temperature, humidity, and pressure data from the device
[ "Deletes", "the", "temperature", "humidity", "and", "pressure", "data", "from", "the", "device" ]
[ "\"\"\"Deletes the temperature, humidity, and pressure data from the\n device\"\"\"", "# The delete command", "# Write the command", "# Now get the response data from the buffer", "# Check the return code shows the data was correctly deleted" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ccc1f64370ace7ca49451275029b6738329d4522
duncanbarth/UT330B
UT330BUI/model/UT330.py
[ "MIT" ]
Python
read_config
<not_specific>
def read_config(self): """Read the configuration data from the device, saves it to disk""" # Send the read info command to the device self._buffer = [0xab, 0xcd, 0x03, 0x11, 0x71, 0x03] # Write the command self._write_buffer() # Now get the data from the buffer. We kn...
Read the configuration data from the device, saves it to disk
Read the configuration data from the device, saves it to disk
[ "Read", "the", "configuration", "data", "from", "the", "device", "saves", "it", "to", "disk" ]
def read_config(self): self._buffer = [0xab, 0xcd, 0x03, 0x11, 0x71, 0x03] self._write_buffer() self._read_buffer(46) config = {} self._index = 4 config['device name'] = self._get_name() config['sampling interval'] = (256*256*self._buffer[22] + ...
[ "def", "read_config", "(", "self", ")", ":", "self", ".", "_buffer", "=", "[", "0xab", ",", "0xcd", ",", "0x03", ",", "0x11", ",", "0x71", ",", "0x03", "]", "self", ".", "_write_buffer", "(", ")", "self", ".", "_read_buffer", "(", "46", ")", "confi...
Read the configuration data from the device, saves it to disk
[ "Read", "the", "configuration", "data", "from", "the", "device", "saves", "it", "to", "disk" ]
[ "\"\"\"Read the configuration data from the device, saves it to disk\"\"\"", "# Send the read info command to the device", "# Write the command", "# Now get the data from the buffer. We know the returned length will", "# be 46.", "# Now, interpret the data in the buffer", "# Get the device name", "# I...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ccc1f64370ace7ca49451275029b6738329d4522
duncanbarth/UT330B
UT330BUI/model/UT330.py
[ "MIT" ]
Python
write_config
null
def write_config(self, config): """Sets the configuration information on the device""" # The command to send, note we'll be overriding some bytes self._buffer = [0xab, 0xcd, 0x1a, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ...
Sets the configuration information on the device
Sets the configuration information on the device
[ "Sets", "the", "configuration", "information", "on", "the", "device" ]
def write_config(self, config): self._buffer = [0xab, 0xcd, 0x1a, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] if len(config['device name']) > 10: raise ValueError('Error! device name {0} is {1} characters when ' ...
[ "def", "write_config", "(", "self", ",", "config", ")", ":", "self", ".", "_buffer", "=", "[", "0xab", ",", "0xcd", ",", "0x1a", ",", "0x10", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "...
Sets the configuration information on the device
[ "Sets", "the", "configuration", "information", "on", "the", "device" ]
[ "\"\"\"Sets the configuration information on the device\"\"\"", "# The command to send, note we'll be overriding some bytes", "# Check config parameters", "# -----------------------", "# Prepare the data for writing", "# ----------------------------", "# Add the device name - pad to 10 characters with s...
[ { "param": "self", "type": null }, { "param": "config", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "config", "type": null, "docstring": null, "docstring_tokens":...
ccc1f64370ace7ca49451275029b6738329d4522
duncanbarth/UT330B
UT330BUI/model/UT330.py
[ "MIT" ]
Python
write_datetime
null
def write_datetime(self, timestamp): """Syncs the time to the timestamp""" # The command to send, note we'll be overriding some bytes self._buffer = [0xab, 0xcd, 0x09, 0x12, 0, 0, 0, 0, 0, 0, 0, 0] self._buffer[4] = timestamp.year - 2000 self._buffer[5] = timestamp.month ...
Syncs the time to the timestamp
Syncs the time to the timestamp
[ "Syncs", "the", "time", "to", "the", "timestamp" ]
def write_datetime(self, timestamp): self._buffer = [0xab, 0xcd, 0x09, 0x12, 0, 0, 0, 0, 0, 0, 0, 0] self._buffer[4] = timestamp.year - 2000 self._buffer[5] = timestamp.month self._buffer[6] = timestamp.day self._buffer[7] = timestamp.hour self._buffer[8] = timestamp.minu...
[ "def", "write_datetime", "(", "self", ",", "timestamp", ")", ":", "self", ".", "_buffer", "=", "[", "0xab", ",", "0xcd", ",", "0x09", ",", "0x12", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", "]", "self", ...
Syncs the time to the timestamp
[ "Syncs", "the", "time", "to", "the", "timestamp" ]
[ "\"\"\"Syncs the time to the timestamp\"\"\"", "# The command to send, note we'll be overriding some bytes", "# Add the CRC bytes", "# Now get the response data from the buffer", "# Check the return code shows the data was correctly written" ]
[ { "param": "self", "type": null }, { "param": "timestamp", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "timestamp", "type": null, "docstring": null, "docstring_token...
ccc1f64370ace7ca49451275029b6738329d4522
duncanbarth/UT330B
UT330BUI/model/UT330.py
[ "MIT" ]
Python
read_offsets
<not_specific>
def read_offsets(self): """Reads the temperature, humidity, pressure offset""" self._buffer = [0xab, 0xcd, 0x03, 0x17, 0xF1, 0x01] self._write_buffer() # Now get the response data from the buffer. The returned buffer length # is known to be 18. self._read_buffer(18) ...
Reads the temperature, humidity, pressure offset
Reads the temperature, humidity, pressure offset
[ "Reads", "the", "temperature", "humidity", "pressure", "offset" ]
def read_offsets(self): self._buffer = [0xab, 0xcd, 0x03, 0x17, 0xF1, 0x01] self._write_buffer() self._read_buffer(18) offsets = {} self._index = 4 offsets['temperature'] = self._get_temperature() if self._buffer[6] < 128: offsets['temperature offset']...
[ "def", "read_offsets", "(", "self", ")", ":", "self", ".", "_buffer", "=", "[", "0xab", ",", "0xcd", ",", "0x03", ",", "0x17", ",", "0xF1", ",", "0x01", "]", "self", ".", "_write_buffer", "(", ")", "self", ".", "_read_buffer", "(", "18", ")", "offs...
Reads the temperature, humidity, pressure offset
[ "Reads", "the", "temperature", "humidity", "pressure", "offset" ]
[ "\"\"\"Reads the temperature, humidity, pressure offset\"\"\"", "# Now get the response data from the buffer. The returned buffer length", "# is known to be 18.", "# Decode the data", "# I don't know what bytes 13, 14, and 15 are" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ccc1f64370ace7ca49451275029b6738329d4522
duncanbarth/UT330B
UT330BUI/model/UT330.py
[ "MIT" ]
Python
write_offsets
null
def write_offsets(self, offsets): """Set the device offsets for temperature, humidity, pressure""" # Check for errors in parameters if offsets['temperature offset'] > 6.1 or \ offsets['temperature offset'] < -6: raise ValueError('Error! The temperature offset is {0} when...
Set the device offsets for temperature, humidity, pressure
Set the device offsets for temperature, humidity, pressure
[ "Set", "the", "device", "offsets", "for", "temperature", "humidity", "pressure" ]
def write_offsets(self, offsets): if offsets['temperature offset'] > 6.1 or \ offsets['temperature offset'] < -6: raise ValueError('Error! The temperature offset is {0} when it ' 'must be between -6 and 6.1 C'. format(offsets['temp...
[ "def", "write_offsets", "(", "self", ",", "offsets", ")", ":", "if", "offsets", "[", "'temperature offset'", "]", ">", "6.1", "or", "offsets", "[", "'temperature offset'", "]", "<", "-", "6", ":", "raise", "ValueError", "(", "'Error! The temperature offset is {0...
Set the device offsets for temperature, humidity, pressure
[ "Set", "the", "device", "offsets", "for", "temperature", "humidity", "pressure" ]
[ "\"\"\"Set the device offsets for temperature, humidity, pressure\"\"\"", "# Check for errors in parameters", "# The command to send, note we'll be overriding some bytes", "# Add the CRC bytes", "# Now get the response data from the buffer", "# Check the return code shows the data was correctly written" ]
[ { "param": "self", "type": null }, { "param": "offsets", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "offsets", "type": null, "docstring": null, "docstring_tokens"...
ccc1f64370ace7ca49451275029b6738329d4522
duncanbarth/UT330B
UT330BUI/model/UT330.py
[ "MIT" ]
Python
restore_factory
null
def restore_factory(self): """This command is given as a factory reset in the Windows software""" self._buffer = [0xab, 0xcd, 0x03, 0x20, 0xb0, 0xd7] self._write_buffer() # Now get the data from the buffer self._read_buffer(7) # Check the return code shows the data w...
This command is given as a factory reset in the Windows software
This command is given as a factory reset in the Windows software
[ "This", "command", "is", "given", "as", "a", "factory", "reset", "in", "the", "Windows", "software" ]
def restore_factory(self): self._buffer = [0xab, 0xcd, 0x03, 0x20, 0xb0, 0xd7] self._write_buffer() self._read_buffer(7) if [171, 205, 4, 32, 0, 103, 117] != self._buffer: raise IOError("Error! Restore factory returned an error code.")
[ "def", "restore_factory", "(", "self", ")", ":", "self", ".", "_buffer", "=", "[", "0xab", ",", "0xcd", ",", "0x03", ",", "0x20", ",", "0xb0", ",", "0xd7", "]", "self", ".", "_write_buffer", "(", ")", "self", ".", "_read_buffer", "(", "7", ")", "if...
This command is given as a factory reset in the Windows software
[ "This", "command", "is", "given", "as", "a", "factory", "reset", "in", "the", "Windows", "software" ]
[ "\"\"\"This command is given as a factory reset in the Windows software\"\"\"", "# Now get the data from the buffer", "# Check the return code shows the data was correctly written" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
511d9c6371ab4661901f93033472cbc5d8de1ab6
VasLem/SNPLIB
SNPLIB/snplib.py
[ "BSD-3-Clause" ]
Python
importPLINKDATA
null
def importPLINKDATA(self, bfile): """Import plink binary fileset Parameters ---------- bfile : str The name of plink binary fileset """ filename = bfile + '.bim' self.SNPs = pd.read_table( bfile+'.bim', sep=None, names=['CHR', 'RSID', 'Cm...
Import plink binary fileset Parameters ---------- bfile : str The name of plink binary fileset
Import plink binary fileset Parameters bfile : str The name of plink binary fileset
[ "Import", "plink", "binary", "fileset", "Parameters", "bfile", ":", "str", "The", "name", "of", "plink", "binary", "fileset" ]
def importPLINKDATA(self, bfile): filename = bfile + '.bim' self.SNPs = pd.read_table( bfile+'.bim', sep=None, names=['CHR', 'RSID', 'Cm', 'POS', 'ALT', 'REF'], engine='python') self.Samples = pd.read_table(bfile+'.fam', sep=None, names=['FID', 'I...
[ "def", "importPLINKDATA", "(", "self", ",", "bfile", ")", ":", "filename", "=", "bfile", "+", "'.bim'", "self", ".", "SNPs", "=", "pd", ".", "read_table", "(", "bfile", "+", "'.bim'", ",", "sep", "=", "None", ",", "names", "=", "[", "'CHR'", ",", "...
Import plink binary fileset Parameters
[ "Import", "plink", "binary", "fileset", "Parameters" ]
[ "\"\"\"Import plink binary fileset\n\n Parameters\n ----------\n bfile : str\n The name of plink binary fileset\n\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "bfile", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "bfile", "type": null, "docstring": null, "docstring_tokens": ...
511d9c6371ab4661901f93033472cbc5d8de1ab6
VasLem/SNPLIB
SNPLIB/snplib.py
[ "BSD-3-Clause" ]
Python
GenerateIndividuals
null
def GenerateIndividuals(self, af): """Simulate the genotypes according to the individual allele frequencies Parameters ---------- af : ndarray A `ndarray` matrix contains the individual allele frequencies, with shape of ``(num_samples, num_snps)`` """ self.n...
Simulate the genotypes according to the individual allele frequencies Parameters ---------- af : ndarray A `ndarray` matrix contains the individual allele frequencies, with shape of ``(num_samples, num_snps)``
Simulate the genotypes according to the individual allele frequencies Parameters
[ "Simulate", "the", "genotypes", "according", "to", "the", "individual", "allele", "frequencies", "Parameters" ]
def GenerateIndividuals(self, af): self.nSamples = af.shape[0] self.nSNPs = af.shape[1] self.GENO = lib.GenerateIndividuals(af)
[ "def", "GenerateIndividuals", "(", "self", ",", "af", ")", ":", "self", ".", "nSamples", "=", "af", ".", "shape", "[", "0", "]", "self", ".", "nSNPs", "=", "af", ".", "shape", "[", "1", "]", "self", ".", "GENO", "=", "lib", ".", "GenerateIndividual...
Simulate the genotypes according to the individual allele frequencies Parameters
[ "Simulate", "the", "genotypes", "according", "to", "the", "individual", "allele", "frequencies", "Parameters" ]
[ "\"\"\"Simulate the genotypes according to the individual allele frequencies\n\n Parameters\n ----------\n af : ndarray\n A `ndarray` matrix contains the individual allele frequencies, with shape of ``(num_samples, num_snps)``\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "af", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "af", "type": null, "docstring": null, "docstring_tokens": [],...
511d9c6371ab4661901f93033472cbc5d8de1ab6
VasLem/SNPLIB
SNPLIB/snplib.py
[ "BSD-3-Clause" ]
Python
UnpackGeno
<not_specific>
def UnpackGeno(self): """Unpack the plink binary format into a double matrix Returns ------- `ndarray` A `ndarray` matrix contains the individual genotypes """ return lib.UnpackGeno(self.GENO, self.nSamples)
Unpack the plink binary format into a double matrix Returns ------- `ndarray` A `ndarray` matrix contains the individual genotypes
Unpack the plink binary format into a double matrix Returns `ndarray` A `ndarray` matrix contains the individual genotypes
[ "Unpack", "the", "plink", "binary", "format", "into", "a", "double", "matrix", "Returns", "`", "ndarray", "`", "A", "`", "ndarray", "`", "matrix", "contains", "the", "individual", "genotypes" ]
def UnpackGeno(self): return lib.UnpackGeno(self.GENO, self.nSamples)
[ "def", "UnpackGeno", "(", "self", ")", ":", "return", "lib", ".", "UnpackGeno", "(", "self", ".", "GENO", ",", "self", ".", "nSamples", ")" ]
Unpack the plink binary format into a double matrix Returns
[ "Unpack", "the", "plink", "binary", "format", "into", "a", "double", "matrix", "Returns" ]
[ "\"\"\"Unpack the plink binary format into a double matrix\n\n Returns\n -------\n `ndarray`\n A `ndarray` matrix contains the individual genotypes\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
bcd37997b9de89e637e5b2c80a606b19b16078be
bhaskarkumar1/StarGAN-Voice-Conversion
preprocess.py
[ "MIT" ]
Python
load_wavs
<not_specific>
def load_wavs(dataset: str, sr): ''' data dict contains all audios file path resdict contains all wav files ''' data = {} with os.scandir(dataset) as it: for entry in it: if entry.is_dir(): data[entry.name] = [] # print(entry.name, entry.pat...
data dict contains all audios file path resdict contains all wav files
data dict contains all audios file path resdict contains all wav files
[ "data", "dict", "contains", "all", "audios", "file", "path", "resdict", "contains", "all", "wav", "files" ]
def load_wavs(dataset: str, sr): data = {} with os.scandir(dataset) as it: for entry in it: if entry.is_dir(): data[entry.name] = [] with os.scandir(entry.path) as it_f: for onefile in it_f: if onefile.is_file(): ...
[ "def", "load_wavs", "(", "dataset", ":", "str", ",", "sr", ")", ":", "data", "=", "{", "}", "with", "os", ".", "scandir", "(", "dataset", ")", "as", "it", ":", "for", "entry", "in", "it", ":", "if", "entry", ".", "is_dir", "(", ")", ":", "data"...
data dict contains all audios file path resdict contains all wav files
[ "data", "dict", "contains", "all", "audios", "file", "path", "resdict", "contains", "all", "wav", "files" ]
[ "'''\n data dict contains all audios file path\n resdict contains all wav files \n '''", "# print(entry.name, entry.path)", "# print(onefile.path)", "# data like {TM1:[xx,xx,xxx,xxx]}", "# like 100061", "# resdict[key].append(temp_dict) #like TM1:{100062:[xxxxx], .... }" ]
[ { "param": "dataset", "type": "str" }, { "param": "sr", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dataset", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sr", "type": null, "docstring": null, "docstring_tokens":...
bcd37997b9de89e637e5b2c80a606b19b16078be
bhaskarkumar1/StarGAN-Voice-Conversion
preprocess.py
[ "MIT" ]
Python
wav_to_mcep_file
null
def wav_to_mcep_file(dataset: str, sr=16000, ispad: bool = False, processed_filepath: str = './data/processed'): '''convert wavs to mcep feature using image repr''' # if no processed_filepath, create it ,or delete all npz files if not os.path.exists(processed_filepath): os.makedirs(processed_filepat...
convert wavs to mcep feature using image repr
convert wavs to mcep feature using image repr
[ "convert", "wavs", "to", "mcep", "feature", "using", "image", "repr" ]
def wav_to_mcep_file(dataset: str, sr=16000, ispad: bool = False, processed_filepath: str = './data/processed'): if not os.path.exists(processed_filepath): os.makedirs(processed_filepath) else: filelist = glob.glob(os.path.join(processed_filepath, "*.npy")) for f in filelist: ...
[ "def", "wav_to_mcep_file", "(", "dataset", ":", "str", ",", "sr", "=", "16000", ",", "ispad", ":", "bool", "=", "False", ",", "processed_filepath", ":", "str", "=", "'./data/processed'", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "pr...
convert wavs to mcep feature using image repr
[ "convert", "wavs", "to", "mcep", "feature", "using", "image", "repr" ]
[ "'''convert wavs to mcep feature using image repr'''", "# if no processed_filepath, create it ,or delete all npz files", "# allwavs_cnt = allwavs_cnt//4*3 * 12+200 #about this number not precise", "#", "# cal source audio feature", "# save the dict as npz", "# save every 36*FRAMES blocks", "# TODO st...
[ { "param": "dataset", "type": "str" }, { "param": "sr", "type": null }, { "param": "ispad", "type": "bool" }, { "param": "processed_filepath", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dataset", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sr", "type": null, "docstring": null, "docstring_tokens":...
bcd37997b9de89e637e5b2c80a606b19b16078be
bhaskarkumar1/StarGAN-Voice-Conversion
preprocess.py
[ "MIT" ]
Python
cal_mcep
<not_specific>
def cal_mcep(wav_ori, fs=SAMPLE_RATE, ispad=False, frame_period=0.005, dim=FEATURE_DIM, fft_size=FFTSIZE): '''cal mcep given wav singnal the frame_period used only for pad_wav_to_get_fixed_frames ''' if ispad: wav, pad_length = pad_wav_to_get_fixed_frames( wav_ori, frames=FRAMES,...
cal mcep given wav singnal the frame_period used only for pad_wav_to_get_fixed_frames
cal mcep given wav singnal the frame_period used only for pad_wav_to_get_fixed_frames
[ "cal", "mcep", "given", "wav", "singnal", "the", "frame_period", "used", "only", "for", "pad_wav_to_get_fixed_frames" ]
def cal_mcep(wav_ori, fs=SAMPLE_RATE, ispad=False, frame_period=0.005, dim=FEATURE_DIM, fft_size=FFTSIZE): if ispad: wav, pad_length = pad_wav_to_get_fixed_frames( wav_ori, frames=FRAMES, frame_period=frame_period, sr=fs) else: wav = wav_ori f0, timeaxis = pyworld.harvest(wav, fs...
[ "def", "cal_mcep", "(", "wav_ori", ",", "fs", "=", "SAMPLE_RATE", ",", "ispad", "=", "False", ",", "frame_period", "=", "0.005", ",", "dim", "=", "FEATURE_DIM", ",", "fft_size", "=", "FFTSIZE", ")", ":", "if", "ispad", ":", "wav", ",", "pad_length", "=...
cal mcep given wav singnal the frame_period used only for pad_wav_to_get_fixed_frames
[ "cal", "mcep", "given", "wav", "singnal", "the", "frame_period", "used", "only", "for", "pad_wav_to_get_fixed_frames" ]
[ "'''cal mcep given wav singnal\n the frame_period used only for pad_wav_to_get_fixed_frames\n '''", "# Harvest F0 extraction algorithm.", "# CheapTrick harmonic spectral envelope estimation algorithm.", "# D4C aperiodicity estimation algorithm.", "# feature reduction nxdim", "# log", "# dim x ...
[ { "param": "wav_ori", "type": null }, { "param": "fs", "type": null }, { "param": "ispad", "type": null }, { "param": "frame_period", "type": null }, { "param": "dim", "type": null }, { "param": "fft_size", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "wav_ori", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fs", "type": null, "docstring": null, "docstring_tokens": ...
7cb5307e4dec6a8176780ba1c01f0b4dc0babcc5
bhaskarkumar1/StarGAN-Voice-Conversion
utility.py
[ "MIT" ]
Python
pitch_conversion
<not_specific>
def pitch_conversion(self, f0, source_speaker, target_speaker): '''Logarithm Gaussian normalization for Pitch Conversions''' mean_log_src = self.norm_dict[source_speaker]['log_f0s_mean'] std_log_src = self.norm_dict[source_speaker]['log_f0s_std'] mean_log_target = self.norm_dict[target...
Logarithm Gaussian normalization for Pitch Conversions
Logarithm Gaussian normalization for Pitch Conversions
[ "Logarithm", "Gaussian", "normalization", "for", "Pitch", "Conversions" ]
def pitch_conversion(self, f0, source_speaker, target_speaker): mean_log_src = self.norm_dict[source_speaker]['log_f0s_mean'] std_log_src = self.norm_dict[source_speaker]['log_f0s_std'] mean_log_target = self.norm_dict[target_speaker]['log_f0s_mean'] std_log_target = self.norm_dict[targe...
[ "def", "pitch_conversion", "(", "self", ",", "f0", ",", "source_speaker", ",", "target_speaker", ")", ":", "mean_log_src", "=", "self", ".", "norm_dict", "[", "source_speaker", "]", "[", "'log_f0s_mean'", "]", "std_log_src", "=", "self", ".", "norm_dict", "[",...
Logarithm Gaussian normalization for Pitch Conversions
[ "Logarithm", "Gaussian", "normalization", "for", "Pitch", "Conversions" ]
[ "'''Logarithm Gaussian normalization for Pitch Conversions'''" ]
[ { "param": "self", "type": null }, { "param": "f0", "type": null }, { "param": "source_speaker", "type": null }, { "param": "target_speaker", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "f0", "type": null, "docstring": null, "docstring_tokens": [],...
7cb5307e4dec6a8176780ba1c01f0b4dc0babcc5
bhaskarkumar1/StarGAN-Voice-Conversion
utility.py
[ "MIT" ]
Python
generate_stats
null
def generate_stats(self, statfolder: str = './etc'): '''generate all user's statitics used for calutate normalized input like sp, f0 step 1: generate coded_sp mean std step 2: generate f0 mean std ''' etc_path = os.path.join(os.path.realpath('.'), statfolder) ...
generate all user's statitics used for calutate normalized input like sp, f0 step 1: generate coded_sp mean std step 2: generate f0 mean std
generate all user's statitics used for calutate normalized input like sp, f0 step 1: generate coded_sp mean std step 2: generate f0 mean std
[ "generate", "all", "user", "'", "s", "statitics", "used", "for", "calutate", "normalized", "input", "like", "sp", "f0", "step", "1", ":", "generate", "coded_sp", "mean", "std", "step", "2", ":", "generate", "f0", "mean", "std" ]
def generate_stats(self, statfolder: str = './etc'): etc_path = os.path.join(os.path.realpath('.'), statfolder) if not os.path.exists(etc_path): os.makedirs(etc_path, exist_ok=True) for one_speaker in self.include_dict.keys(): coded_sps = [] arr = self.include...
[ "def", "generate_stats", "(", "self", ",", "statfolder", ":", "str", "=", "'./etc'", ")", ":", "etc_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "realpath", "(", "'.'", ")", ",", "statfolder", ")", "if", "not", "os", "."...
generate all user's statitics used for calutate normalized input like sp, f0 step 1: generate coded_sp mean std step 2: generate f0 mean std
[ "generate", "all", "user", "'", "s", "statitics", "used", "for", "calutate", "normalized", "input", "like", "sp", "f0", "step", "1", ":", "generate", "coded_sp", "mean", "std", "step", "2", ":", "generate", "f0", "mean", "std" ]
[ "'''generate all user's statitics used for calutate normalized\n input like sp, f0\n step 1: generate coded_sp mean std\n step 2: generate f0 mean std\n '''", "# print(t.shape)", "# print(f'sp_mean: {coded_sps_mean.shape} \\", "# sp_std: {coded_sps_std.shape}')", "# pri...
[ { "param": "self", "type": null }, { "param": "statfolder", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "statfolder", "type": "str", "docstring": null, "docstring_tok...
bca4607bd9d402d190c08708c4f743f3175bd1a4
niveditalodha/ReadME
codeletter/codeletter/utils.py
[ "MIT" ]
Python
insert_article
<not_specific>
def insert_article(data_json): """ Given json, it gets the concept ids and insert the article into article database. :param data_json: json containing article information is given as input :type data_json: dict """ concept_ids = get_or_insert_concept(data_json["concepts"]) article_rec = Art...
Given json, it gets the concept ids and insert the article into article database. :param data_json: json containing article information is given as input :type data_json: dict
Given json, it gets the concept ids and insert the article into article database.
[ "Given", "json", "it", "gets", "the", "concept", "ids", "and", "insert", "the", "article", "into", "article", "database", "." ]
def insert_article(data_json): concept_ids = get_or_insert_concept(data_json["concepts"]) article_rec = Article( url=data_json["url"], title=data_json["title"], abstract=data_json["abstract"], domain=data_json["domain"], concept_ids=concept_ids, ) article_rec.save...
[ "def", "insert_article", "(", "data_json", ")", ":", "concept_ids", "=", "get_or_insert_concept", "(", "data_json", "[", "\"concepts\"", "]", ")", "article_rec", "=", "Article", "(", "url", "=", "data_json", "[", "\"url\"", "]", ",", "title", "=", "data_json",...
Given json, it gets the concept ids and insert the article into article database.
[ "Given", "json", "it", "gets", "the", "concept", "ids", "and", "insert", "the", "article", "into", "article", "database", "." ]
[ "\"\"\"\n Given json, it gets the concept ids and insert the article into article database.\n\n :param data_json: json containing article information is given as input\n :type data_json: dict\n \"\"\"" ]
[ { "param": "data_json", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "data_json", "type": null, "docstring": "json containing article information is given as input", "docstring_tokens": [ "json", "containing", "article", "information", "is", "given...
bca4607bd9d402d190c08708c4f743f3175bd1a4
niveditalodha/ReadME
codeletter/codeletter/utils.py
[ "MIT" ]
Python
is_leap
<not_specific>
def is_leap(year): """ Takes year as input, and returns if its leap year or not. :param year: a calendar year :type year: int :return: true or false :rtype: boolean """ if year % 4 != 0: return False elif year % 100 != 0: return True elif year % 400 != 0: ...
Takes year as input, and returns if its leap year or not. :param year: a calendar year :type year: int :return: true or false :rtype: boolean
Takes year as input, and returns if its leap year or not.
[ "Takes", "year", "as", "input", "and", "returns", "if", "its", "leap", "year", "or", "not", "." ]
def is_leap(year): if year % 4 != 0: return False elif year % 100 != 0: return True elif year % 400 != 0: return False else: return True
[ "def", "is_leap", "(", "year", ")", ":", "if", "year", "%", "4", "!=", "0", ":", "return", "False", "elif", "year", "%", "100", "!=", "0", ":", "return", "True", "elif", "year", "%", "400", "!=", "0", ":", "return", "False", "else", ":", "return"...
Takes year as input, and returns if its leap year or not.
[ "Takes", "year", "as", "input", "and", "returns", "if", "its", "leap", "year", "or", "not", "." ]
[ "\"\"\"\n Takes year as input, and returns if its leap year or not.\n\n :param year: a calendar year\n :type year: int\n :return: true or false\n :rtype: boolean\n \"\"\"" ]
[ { "param": "year", "type": null } ]
{ "returns": [ { "docstring": "true or false", "docstring_tokens": [ "true", "or", "false" ], "type": "boolean" } ], "raises": [], "params": [ { "identifier": "year", "type": null, "docstring": "a calendar year", "docstring_toke...
bca4607bd9d402d190c08708c4f743f3175bd1a4
niveditalodha/ReadME
codeletter/codeletter/utils.py
[ "MIT" ]
Python
convert_day
<not_specific>
def convert_day(day, year): """ Takes day and year as input, and returns date and month in that year. :param day: day of the month :type day: int :param year: a calendar year :type year: int :return: pair of month and date :rtype: pair(int,int) """ month_days = [ 31, ...
Takes day and year as input, and returns date and month in that year. :param day: day of the month :type day: int :param year: a calendar year :type year: int :return: pair of month and date :rtype: pair(int,int)
Takes day and year as input, and returns date and month in that year.
[ "Takes", "day", "and", "year", "as", "input", "and", "returns", "date", "and", "month", "in", "that", "year", "." ]
def convert_day(day, year): month_days = [ 31, 29 if is_leap(year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ] m = 0 d = 0 while day > 0: d = day day -= month_days[m] m += 1...
[ "def", "convert_day", "(", "day", ",", "year", ")", ":", "month_days", "=", "[", "31", ",", "29", "if", "is_leap", "(", "year", ")", "else", "28", ",", "31", ",", "30", ",", "31", ",", "30", ",", "31", ",", "31", ",", "30", ",", "31", ",", ...
Takes day and year as input, and returns date and month in that year.
[ "Takes", "day", "and", "year", "as", "input", "and", "returns", "date", "and", "month", "in", "that", "year", "." ]
[ "\"\"\"\n Takes day and year as input, and returns date and month in that year.\n\n :param day: day of the month\n :type day: int\n :param year: a calendar year\n :type year: int\n :return: pair of month and date\n :rtype: pair(int,int)\n \"\"\"" ]
[ { "param": "day", "type": null }, { "param": "year", "type": null } ]
{ "returns": [ { "docstring": "pair of month and date", "docstring_tokens": [ "pair", "of", "month", "and", "date" ], "type": "pair(int,int)" } ], "raises": [], "params": [ { "identifier": "day", "type": null, "docstri...
5aa4bfa8c218a7f00947ce886947e3c4ae78dfea
MoraesCaio/ktrain
ktrain/lroptimize/lrfinder.py
[ "MIT" ]
Python
find
<not_specific>
def find(self, train_data, steps_per_epoch, use_gen=False, start_lr=1e-7, lr_mult=1.01, max_epochs=None, batch_size=U.DEFAULT_BS, workers=1, use_multiprocessing=False, verbose=1): """ Track loss as learning rate is increased. NOTE: batch_size is ignored when train_data...
Track loss as learning rate is increased. NOTE: batch_size is ignored when train_data is instance of Iterator.
Track loss as learning rate is increased. NOTE: batch_size is ignored when train_data is instance of Iterator.
[ "Track", "loss", "as", "learning", "rate", "is", "increased", ".", "NOTE", ":", "batch_size", "is", "ignored", "when", "train_data", "is", "instance", "of", "Iterator", "." ]
def find(self, train_data, steps_per_epoch, use_gen=False, start_lr=1e-7, lr_mult=1.01, max_epochs=None, batch_size=U.DEFAULT_BS, workers=1, use_multiprocessing=False, verbose=1): if train_data is None: raise ValueError('train_data is required') self.lrs = [] ...
[ "def", "find", "(", "self", ",", "train_data", ",", "steps_per_epoch", ",", "use_gen", "=", "False", ",", "start_lr", "=", "1e-7", ",", "lr_mult", "=", "1.01", ",", "max_epochs", "=", "None", ",", "batch_size", "=", "U", ".", "DEFAULT_BS", ",", "workers"...
Track loss as learning rate is increased.
[ "Track", "loss", "as", "learning", "rate", "is", "increased", "." ]
[ "\"\"\"\n Track loss as learning rate is increased.\n NOTE: batch_size is ignored when train_data is instance of Iterator.\n \"\"\"", "# check arguments and initialize", "#U.data_arg_check(train_data=train_data, train_required=True)", "# compute steps_per_epoch", "#num_samples = U.nsamp...
[ { "param": "self", "type": null }, { "param": "train_data", "type": null }, { "param": "steps_per_epoch", "type": null }, { "param": "use_gen", "type": null }, { "param": "start_lr", "type": null }, { "param": "lr_mult", "type": null }, { "...
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "train_data", "type": null, "docstring": null, "docstring_toke...
5aa4bfa8c218a7f00947ce886947e3c4ae78dfea
MoraesCaio/ktrain
ktrain/lroptimize/lrfinder.py
[ "MIT" ]
Python
plot_loss
<not_specific>
def plot_loss(self, n_skip_beginning=10, n_skip_end=1): """ Plots the loss. Parameters: n_skip_beginning - number of batches to skip on the left. n_skip_end - number of batches to skip on the right. highlight - will highlight numerical estimate ...
Plots the loss. Parameters: n_skip_beginning - number of batches to skip on the left. n_skip_end - number of batches to skip on the right. highlight - will highlight numerical estimate of best lr if True
Plots the loss. Parameters: n_skip_beginning - number of batches to skip on the left. n_skip_end - number of batches to skip on the right. highlight - will highlight numerical estimate of best lr if True
[ "Plots", "the", "loss", ".", "Parameters", ":", "n_skip_beginning", "-", "number", "of", "batches", "to", "skip", "on", "the", "left", ".", "n_skip_end", "-", "number", "of", "batches", "to", "skip", "on", "the", "right", ".", "highlight", "-", "will", "...
def plot_loss(self, n_skip_beginning=10, n_skip_end=1): fig, ax = plt.subplots() plt.ylabel("loss") plt.xlabel("learning rate (log scale)") ax.plot(self.lrs[n_skip_beginning:-n_skip_end], self.losses[n_skip_beginning:-n_skip_end]) plt.xscale('log') plt.show() retu...
[ "def", "plot_loss", "(", "self", ",", "n_skip_beginning", "=", "10", ",", "n_skip_end", "=", "1", ")", ":", "fig", ",", "ax", "=", "plt", ".", "subplots", "(", ")", "plt", ".", "ylabel", "(", "\"loss\"", ")", "plt", ".", "xlabel", "(", "\"learning ra...
Plots the loss.
[ "Plots", "the", "loss", "." ]
[ "\"\"\"\n Plots the loss.\n Parameters:\n n_skip_beginning - number of batches to skip on the left.\n n_skip_end - number of batches to skip on the right.\n highlight - will highlight numerical estimate\n of best lr if True\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "n_skip_beginning", "type": null }, { "param": "n_skip_end", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "n_skip_beginning", "type": null, "docstring": null, "docstrin...
5aa4bfa8c218a7f00947ce886947e3c4ae78dfea
MoraesCaio/ktrain
ktrain/lroptimize/lrfinder.py
[ "MIT" ]
Python
plot_loss_change
null
def plot_loss_change(self, sma=1, n_skip_beginning=10, n_skip_end=5, y_lim=(-0.01, 0.01)): """ Plots rate of change of the loss function. Parameters: sma - number of batches for simple moving average to smooth out the curve. n_skip_beginning - number of batches to skip on...
Plots rate of change of the loss function. Parameters: sma - number of batches for simple moving average to smooth out the curve. n_skip_beginning - number of batches to skip on the left. n_skip_end - number of batches to skip on the right. y_lim - limits...
Plots rate of change of the loss function. Parameters: sma - number of batches for simple moving average to smooth out the curve. n_skip_beginning - number of batches to skip on the left. n_skip_end - number of batches to skip on the right. y_lim - limits for the y axis.
[ "Plots", "rate", "of", "change", "of", "the", "loss", "function", ".", "Parameters", ":", "sma", "-", "number", "of", "batches", "for", "simple", "moving", "average", "to", "smooth", "out", "the", "curve", ".", "n_skip_beginning", "-", "number", "of", "bat...
def plot_loss_change(self, sma=1, n_skip_beginning=10, n_skip_end=5, y_lim=(-0.01, 0.01)): assert sma >= 1 derivatives = [0] * sma for i in range(sma, len(self.lrs)): derivative = (self.losses[i] - self.losses[i - sma]) / sma derivatives.append(derivative) plt.yla...
[ "def", "plot_loss_change", "(", "self", ",", "sma", "=", "1", ",", "n_skip_beginning", "=", "10", ",", "n_skip_end", "=", "5", ",", "y_lim", "=", "(", "-", "0.01", ",", "0.01", ")", ")", ":", "assert", "sma", ">=", "1", "derivatives", "=", "[", "0"...
Plots rate of change of the loss function.
[ "Plots", "rate", "of", "change", "of", "the", "loss", "function", "." ]
[ "\"\"\"\n Plots rate of change of the loss function.\n Parameters:\n sma - number of batches for simple moving average to smooth out the curve.\n n_skip_beginning - number of batches to skip on the left.\n n_skip_end - number of batches to skip on the right.\n ...
[ { "param": "self", "type": null }, { "param": "sma", "type": null }, { "param": "n_skip_beginning", "type": null }, { "param": "n_skip_end", "type": null }, { "param": "y_lim", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "sma", "type": null, "docstring": null, "docstring_tokens": []...
2c0800986be2b5d4d088441e00ca0b163ead5dc4
MoraesCaio/ktrain
ktrain/text/data.py
[ "MIT" ]
Python
texts_from_array
<not_specific>
def texts_from_array(x_train, y_train, x_test=None, y_test=None, class_names = [], max_features=MAX_FEATURES, maxlen=MAXLEN, val_pct=0.1, ngram_range=1, preprocess_mode='standard', lang=None, # auto-detected random_state=N...
Loads and preprocesses text data from arrays. texts_from_array can handle data for both text classification and text regression. If class_names is empty, a regression task is assumed. Args: x_train(list): list of training texts y_train(list): labels in one of the following forms: ...
Loads and preprocesses text data from arrays. texts_from_array can handle data for both text classification and text regression. If class_names is empty, a regression task is assumed.
[ "Loads", "and", "preprocesses", "text", "data", "from", "arrays", ".", "texts_from_array", "can", "handle", "data", "for", "both", "text", "classification", "and", "text", "regression", ".", "If", "class_names", "is", "empty", "a", "regression", "task", "is", ...
def texts_from_array(x_train, y_train, x_test=None, y_test=None, class_names = [], max_features=MAX_FEATURES, maxlen=MAXLEN, val_pct=0.1, ngram_range=1, preprocess_mode='standard', lang=None, random_state=None, ...
[ "def", "texts_from_array", "(", "x_train", ",", "y_train", ",", "x_test", "=", "None", ",", "y_test", "=", "None", ",", "class_names", "=", "[", "]", ",", "max_features", "=", "MAX_FEATURES", ",", "maxlen", "=", "MAXLEN", ",", "val_pct", "=", "0.1", ",",...
Loads and preprocesses text data from arrays.
[ "Loads", "and", "preprocesses", "text", "data", "from", "arrays", "." ]
[ "# auto-detected", "\"\"\"\n Loads and preprocesses text data from arrays.\n texts_from_array can handle data for both text classification\n and text regression. If class_names is empty, a regression task is assumed.\n Args:\n x_train(list): list of training texts \n y_train(list): labe...
[ { "param": "x_train", "type": null }, { "param": "y_train", "type": null }, { "param": "x_test", "type": null }, { "param": "y_test", "type": null }, { "param": "class_names", "type": null }, { "param": "max_features", "type": null }, { "pa...
{ "returns": [], "raises": [], "params": [ { "identifier": "x_train", "type": null, "docstring": "list of training texts", "docstring_tokens": [ "list", "of", "training", "texts" ], "default": null, "is_optional": false }, { ...
2c0800986be2b5d4d088441e00ca0b163ead5dc4
MoraesCaio/ktrain
ktrain/text/data.py
[ "MIT" ]
Python
standardize_to_utf8
<not_specific>
def standardize_to_utf8(encoding): """ standardize to utf-8 if necessary. NOTE: mainly used to use utf-8 if ASCII is detected, as BERT performance suffers otherwise. """ encoding = 'utf-8' if encoding.lower() in ['ascii', 'utf8', 'utf-8'] else encoding return encoding
standardize to utf-8 if necessary. NOTE: mainly used to use utf-8 if ASCII is detected, as BERT performance suffers otherwise.
standardize to utf-8 if necessary. NOTE: mainly used to use utf-8 if ASCII is detected, as BERT performance suffers otherwise.
[ "standardize", "to", "utf", "-", "8", "if", "necessary", ".", "NOTE", ":", "mainly", "used", "to", "use", "utf", "-", "8", "if", "ASCII", "is", "detected", "as", "BERT", "performance", "suffers", "otherwise", "." ]
def standardize_to_utf8(encoding): encoding = 'utf-8' if encoding.lower() in ['ascii', 'utf8', 'utf-8'] else encoding return encoding
[ "def", "standardize_to_utf8", "(", "encoding", ")", ":", "encoding", "=", "'utf-8'", "if", "encoding", ".", "lower", "(", ")", "in", "[", "'ascii'", ",", "'utf8'", ",", "'utf-8'", "]", "else", "encoding", "return", "encoding" ]
standardize to utf-8 if necessary.
[ "standardize", "to", "utf", "-", "8", "if", "necessary", "." ]
[ "\"\"\"\n standardize to utf-8 if necessary.\n NOTE: mainly used to use utf-8 if ASCII is detected, as\n BERT performance suffers otherwise.\n \"\"\"" ]
[ { "param": "encoding", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "encoding", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
38e3722af837b9581d48f71a4c5391ced97af351
MoraesCaio/ktrain
ktrain/graph/models.py
[ "MIT" ]
Python
graph_node_classifier
<not_specific>
def graph_node_classifier(name, train_data, layer_sizes=[32,32], verbose=1): """ Build and return a neural node classification model. Notes: Only mutually-exclusive class labels are supported. Args: name (string): one of: - 'graphsage' for GraphSAGE model ...
Build and return a neural node classification model. Notes: Only mutually-exclusive class labels are supported. Args: name (string): one of: - 'graphsage' for GraphSAGE model (only GraphSAGE currently supported) train_data (NodeSequenceWrapper)...
Build and return a neural node classification model. Notes: Only mutually-exclusive class labels are supported.
[ "Build", "and", "return", "a", "neural", "node", "classification", "model", ".", "Notes", ":", "Only", "mutually", "-", "exclusive", "class", "labels", "are", "supported", "." ]
def graph_node_classifier(name, train_data, layer_sizes=[32,32], verbose=1): from .node_generator import NodeSequenceWrapper if not isinstance(train_data, NodeSequenceWrapper): err =""" train_data must be a ktrain.graph.node_generator.NodeSequenceWrapper object """ raise ...
[ "def", "graph_node_classifier", "(", "name", ",", "train_data", ",", "layer_sizes", "=", "[", "32", ",", "32", "]", ",", "verbose", "=", "1", ")", ":", "from", ".", "node_generator", "import", "NodeSequenceWrapper", "if", "not", "isinstance", "(", "train_dat...
Build and return a neural node classification model.
[ "Build", "and", "return", "a", "neural", "node", "classification", "model", "." ]
[ "\"\"\"\n Build and return a neural node classification model.\n Notes: Only mutually-exclusive class labels are supported.\n\n Args:\n name (string): one of:\n - 'graphsage' for GraphSAGE model \n (only GraphSAGE currently supported)\n\n train_data (...
[ { "param": "name", "type": null }, { "param": "train_data", "type": null }, { "param": "layer_sizes", "type": null }, { "param": "verbose", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "name", "type": null, "docstring": "one of:\n'graphsage' for GraphSAGE model\n(only GraphSAGE currently supported)", "docstring_tokens": [ "one", "of", ":", "'", "graphsage", "'",...
d0d830d72b4d849321f474a266e2d8011cd24131
MoraesCaio/ktrain
ktrain/text/ner/models.py
[ "MIT" ]
Python
sequence_tagger
<not_specific>
def sequence_tagger(name, preproc, word_embedding_dim=100, char_embedding_dim=25, word_lstm_size=100, char_lstm_size=25, fc_dim=100, dropout=0.5, verbose=1): """ Build and...
Build and return a sequence tagger (i.e., named entity recognizer). Args: name (string): one of: - 'bilstm-crf' for Bidirectional LSTM-CRF model preproc(NERPreprocessor): an instance of NERPreprocessor embeddings(str): Currently, either None or 'cbow' is supporte...
Build and return a sequence tagger .
[ "Build", "and", "return", "a", "sequence", "tagger", "." ]
def sequence_tagger(name, preproc, word_embedding_dim=100, char_embedding_dim=25, word_lstm_size=100, char_lstm_size=25, fc_dim=100, dropout=0.5, verbose=1): if not DISABLE_V2...
[ "def", "sequence_tagger", "(", "name", ",", "preproc", ",", "word_embedding_dim", "=", "100", ",", "char_embedding_dim", "=", "25", ",", "word_lstm_size", "=", "100", ",", "char_lstm_size", "=", "25", ",", "fc_dim", "=", "100", ",", "dropout", "=", "0.5", ...
Build and return a sequence tagger (i.e., named entity recognizer).
[ "Build", "and", "return", "a", "sequence", "tagger", "(", "i", ".", "e", ".", "named", "entity", "recognizer", ")", "." ]
[ "\"\"\"\n Build and return a sequence tagger (i.e., named entity recognizer).\n\n Args:\n name (string): one of:\n - 'bilstm-crf' for Bidirectional LSTM-CRF model\n preproc(NERPreprocessor): an instance of NERPreprocessor\n embeddings(str): Currently, either None or ...
[ { "param": "name", "type": null }, { "param": "preproc", "type": null }, { "param": "word_embedding_dim", "type": null }, { "param": "char_embedding_dim", "type": null }, { "param": "word_lstm_size", "type": null }, { "param": "char_lstm_size", "ty...
{ "returns": [], "raises": [], "params": [ { "identifier": "name", "type": null, "docstring": "one of:\n'bilstm-crf' for Bidirectional LSTM-CRF model", "docstring_tokens": [ "one", "of", ":", "'", "bilstm", "-", "crf", "'"...
7c1375935b74d0843faad1eb145d5f34fa2eda2d
MoraesCaio/ktrain
ktrain/vision/predictor.py
[ "MIT" ]
Python
predict
<not_specific>
def predict(self, data, return_proba=False): """ Predicts class from image in array format. If return_proba is True, returns probabilities of each class. """ if not isinstance(data, np.ndarray): raise ValueError('data must be numpy.ndarray') (generator, steps)...
Predicts class from image in array format. If return_proba is True, returns probabilities of each class.
Predicts class from image in array format. If return_proba is True, returns probabilities of each class.
[ "Predicts", "class", "from", "image", "in", "array", "format", ".", "If", "return_proba", "is", "True", "returns", "probabilities", "of", "each", "class", "." ]
def predict(self, data, return_proba=False): if not isinstance(data, np.ndarray): raise ValueError('data must be numpy.ndarray') (generator, steps) = self.preproc.preprocess(data) return self.predict_generator(generator, steps=steps, return_proba=return_proba)
[ "def", "predict", "(", "self", ",", "data", ",", "return_proba", "=", "False", ")", ":", "if", "not", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", ":", "raise", "ValueError", "(", "'data must be numpy.ndarray'", ")", "(", "generator", ",", ...
Predicts class from image in array format.
[ "Predicts", "class", "from", "image", "in", "array", "format", "." ]
[ "\"\"\"\n Predicts class from image in array format.\n If return_proba is True, returns probabilities of each class.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "data", "type": null }, { "param": "return_proba", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": null, "docstring": null, "docstring_tokens": [...
7c1375935b74d0843faad1eb145d5f34fa2eda2d
MoraesCaio/ktrain
ktrain/vision/predictor.py
[ "MIT" ]
Python
predict_filename
<not_specific>
def predict_filename(self, img_path, return_proba=False): """ Predicts class from filepath to single image file. If return_proba is True, returns probabilities of each class. """ if not os.path.isfile(img_path): raise ValueError('img_path must be valid file') (generator, ...
Predicts class from filepath to single image file. If return_proba is True, returns probabilities of each class.
Predicts class from filepath to single image file. If return_proba is True, returns probabilities of each class.
[ "Predicts", "class", "from", "filepath", "to", "single", "image", "file", ".", "If", "return_proba", "is", "True", "returns", "probabilities", "of", "each", "class", "." ]
def predict_filename(self, img_path, return_proba=False): if not os.path.isfile(img_path): raise ValueError('img_path must be valid file') (generator, steps) = self.preproc.preprocess(img_path) return self.predict_generator(generator, steps=steps, return_proba=return_proba)
[ "def", "predict_filename", "(", "self", ",", "img_path", ",", "return_proba", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "img_path", ")", ":", "raise", "ValueError", "(", "'img_path must be valid file'", ")", "(", "generator"...
Predicts class from filepath to single image file.
[ "Predicts", "class", "from", "filepath", "to", "single", "image", "file", "." ]
[ "\"\"\"\n Predicts class from filepath to single image file.\n If return_proba is True, returns probabilities of each class.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "img_path", "type": null }, { "param": "return_proba", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "img_path", "type": null, "docstring": null, "docstring_tokens...
7c1375935b74d0843faad1eb145d5f34fa2eda2d
MoraesCaio/ktrain
ktrain/vision/predictor.py
[ "MIT" ]
Python
predict_folder
<not_specific>
def predict_folder(self, folder, return_proba=False): """ Predicts the classes of all images in a folder. If return_proba is True, returns probabilities of each class. """ if not os.path.isdir(folder): raise ValueError('folder must be valid directory') (generator...
Predicts the classes of all images in a folder. If return_proba is True, returns probabilities of each class.
Predicts the classes of all images in a folder. If return_proba is True, returns probabilities of each class.
[ "Predicts", "the", "classes", "of", "all", "images", "in", "a", "folder", ".", "If", "return_proba", "is", "True", "returns", "probabilities", "of", "each", "class", "." ]
def predict_folder(self, folder, return_proba=False): if not os.path.isdir(folder): raise ValueError('folder must be valid directory') (generator, steps) = self.preproc.preprocess(folder) result = self.predict_generator(generator, steps=steps, return_proba=return_proba) if len(result) !=...
[ "def", "predict_folder", "(", "self", ",", "folder", ",", "return_proba", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "raise", "ValueError", "(", "'folder must be valid directory'", ")", "(", "generator", ...
Predicts the classes of all images in a folder.
[ "Predicts", "the", "classes", "of", "all", "images", "in", "a", "folder", "." ]
[ "\"\"\"\n Predicts the classes of all images in a folder.\n If return_proba is True, returns probabilities of each class.\n \n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "folder", "type": null }, { "param": "return_proba", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "folder", "type": null, "docstring": null, "docstring_tokens":...
7c1375935b74d0843faad1eb145d5f34fa2eda2d
MoraesCaio/ktrain
ktrain/vision/predictor.py
[ "MIT" ]
Python
analyze_valid
<not_specific>
def analyze_valid(self, generator, print_report=True, multilabel=None): """ Makes predictions on validation set and returns the confusion matrix. Accepts as input a genrator (e.g., DirectoryIterator, DataframeIterator) representing the validation set. Optionally prints a classi...
Makes predictions on validation set and returns the confusion matrix. Accepts as input a genrator (e.g., DirectoryIterator, DataframeIterator) representing the validation set. Optionally prints a classification report. Currently, this method is only supported for binary and mu...
Makes predictions on validation set and returns the confusion matrix. Accepts as input a genrator representing the validation set. Optionally prints a classification report. Currently, this method is only supported for binary and multiclass problems, not multilabel classification problems.
[ "Makes", "predictions", "on", "validation", "set", "and", "returns", "the", "confusion", "matrix", ".", "Accepts", "as", "input", "a", "genrator", "representing", "the", "validation", "set", ".", "Optionally", "prints", "a", "classification", "report", ".", "Cur...
def analyze_valid(self, generator, print_report=True, multilabel=None): if multilabel is None: multilabel = U.is_multilabel(generator) if multilabel: warnings.warn('multilabel_confusion_matrix not yet supported - skipping') return y_true = generator.classes ...
[ "def", "analyze_valid", "(", "self", ",", "generator", ",", "print_report", "=", "True", ",", "multilabel", "=", "None", ")", ":", "if", "multilabel", "is", "None", ":", "multilabel", "=", "U", ".", "is_multilabel", "(", "generator", ")", "if", "multilabel...
Makes predictions on validation set and returns the confusion matrix.
[ "Makes", "predictions", "on", "validation", "set", "and", "returns", "the", "confusion", "matrix", "." ]
[ "\"\"\"\n Makes predictions on validation set and returns the confusion matrix.\n Accepts as input a genrator (e.g., DirectoryIterator, DataframeIterator)\n representing the validation set.\n\n\n Optionally prints a classification report.\n Currently, this method is only supported...
[ { "param": "self", "type": null }, { "param": "generator", "type": null }, { "param": "print_report", "type": null }, { "param": "multilabel", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "generator", "type": null, "docstring": null, "docstring_token...
415e14f2fe4d9d74f74219d8714994ca73ea4266
JMarkin/afbmq
afbmq/fb.py
[ "MIT" ]
Python
request_timeout
null
def request_timeout(self, timeout: typing.Union[int, float, aiohttp.ClientTimeout]): """ Context manager implements opportunity to change request timeout in current context :param timeout: Request timeout :type timeout: :obj:`typing.Optional[typing.Union[base.Integer, base.Float, aiohtt...
Context manager implements opportunity to change request timeout in current context :param timeout: Request timeout :type timeout: :obj:`typing.Optional[typing.Union[base.Integer, base.Float, aiohttp.ClientTimeout]]` :return:
Context manager implements opportunity to change request timeout in current context
[ "Context", "manager", "implements", "opportunity", "to", "change", "request", "timeout", "in", "current", "context" ]
def request_timeout(self, timeout: typing.Union[int, float, aiohttp.ClientTimeout]): timeout = self._prepare_timeout(timeout) token = self._ctx_timeout.set(timeout) try: yield finally: self._ctx_timeout.reset(token)
[ "def", "request_timeout", "(", "self", ",", "timeout", ":", "typing", ".", "Union", "[", "int", ",", "float", ",", "aiohttp", ".", "ClientTimeout", "]", ")", ":", "timeout", "=", "self", ".", "_prepare_timeout", "(", "timeout", ")", "token", "=", "self",...
Context manager implements opportunity to change request timeout in current context
[ "Context", "manager", "implements", "opportunity", "to", "change", "request", "timeout", "in", "current", "context" ]
[ "\"\"\"\n Context manager implements opportunity to change request timeout in current context\n\n :param timeout: Request timeout\n :type timeout: :obj:`typing.Optional[typing.Union[base.Integer, base.Float, aiohttp.ClientTimeout]]`\n :return:\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "timeout", "type": "typing.Union[int, float, aiohttp.ClientTimeout]" } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
cad5396b2c7613fa5cf787a44fcec10cd87e1a97
JMarkin/afbmq
afbmq/dispatcher/webhook.py
[ "MIT" ]
Python
check_ip
<not_specific>
def check_ip(self): """ Check client IP. Accept requests only from FB servers. :return: """ # For reverse proxy (nginx) forwarded_for = self.request.headers.get('X-Forwarded-For', None) if forwarded_for: return forwarded_for, _check_ip(forwarded_for) ...
Check client IP. Accept requests only from FB servers. :return:
Check client IP. Accept requests only from FB servers.
[ "Check", "client", "IP", ".", "Accept", "requests", "only", "from", "FB", "servers", "." ]
def check_ip(self): forwarded_for = self.request.headers.get('X-Forwarded-For', None) if forwarded_for: return forwarded_for, _check_ip(forwarded_for) peer_name = self.request.transport.get_extra_info('peername') if peer_name is not None: host, _ = peer_name ...
[ "def", "check_ip", "(", "self", ")", ":", "forwarded_for", "=", "self", ".", "request", ".", "headers", ".", "get", "(", "'X-Forwarded-For'", ",", "None", ")", "if", "forwarded_for", ":", "return", "forwarded_for", ",", "_check_ip", "(", "forwarded_for", ")"...
Check client IP.
[ "Check", "client", "IP", "." ]
[ "\"\"\"\n Check client IP. Accept requests only from FB servers.\n\n :return:\n \"\"\"", "# For reverse proxy (nginx)", "# For default method", "# Not allowed and can't get client IP" ]
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
cad5396b2c7613fa5cf787a44fcec10cd87e1a97
JMarkin/afbmq
afbmq/dispatcher/webhook.py
[ "MIT" ]
Python
validate_ip
null
def validate_ip(self): """ Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts. """ if self.request.app.get('_check_ip', False): ip_address, accept = self.check_ip() if not accept: raise web.HTTPUnauthorized()
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.
[ "Check", "ip", "if", "that", "is", "needed", ".", "Raise", "web", ".", "HTTPUnauthorized", "for", "not", "allowed", "hosts", "." ]
def validate_ip(self): if self.request.app.get('_check_ip', False): ip_address, accept = self.check_ip() if not accept: raise web.HTTPUnauthorized()
[ "def", "validate_ip", "(", "self", ")", ":", "if", "self", ".", "request", ".", "app", ".", "get", "(", "'_check_ip'", ",", "False", ")", ":", "ip_address", ",", "accept", "=", "self", ".", "check_ip", "(", ")", "if", "not", "accept", ":", "raise", ...
Check ip if that is needed.
[ "Check", "ip", "if", "that", "is", "needed", "." ]
[ "\"\"\"\n Check ip if that is needed. Raise web.HTTPUnauthorized for not allowed hosts.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
cad5396b2c7613fa5cf787a44fcec10cd87e1a97
JMarkin/afbmq
afbmq/dispatcher/webhook.py
[ "MIT" ]
Python
configure_app
null
def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH): """ You can prepare web.Application for working with webhook handler. :param dispatcher: Dispatcher instance :param app: :class:`aiohttp.web.Application` :param path: Path to your webhook. :return: """ app.route...
You can prepare web.Application for working with webhook handler. :param dispatcher: Dispatcher instance :param app: :class:`aiohttp.web.Application` :param path: Path to your webhook. :return:
You can prepare web.Application for working with webhook handler.
[ "You", "can", "prepare", "web", ".", "Application", "for", "working", "with", "webhook", "handler", "." ]
def configure_app(dispatcher, app: web.Application, path=DEFAULT_WEB_PATH): app.router.add_route('*', path, WebhookRequestHandler, name='webhook_handler') app[FB_DISPATCHER_KEY] = dispatcher
[ "def", "configure_app", "(", "dispatcher", ",", "app", ":", "web", ".", "Application", ",", "path", "=", "DEFAULT_WEB_PATH", ")", ":", "app", ".", "router", ".", "add_route", "(", "'*'", ",", "path", ",", "WebhookRequestHandler", ",", "name", "=", "'webhoo...
You can prepare web.Application for working with webhook handler.
[ "You", "can", "prepare", "web", ".", "Application", "for", "working", "with", "webhook", "handler", "." ]
[ "\"\"\"\n You can prepare web.Application for working with webhook handler.\n\n :param dispatcher: Dispatcher instance\n :param app: :class:`aiohttp.web.Application`\n :param path: Path to your webhook.\n :return:\n \"\"\"" ]
[ { "param": "dispatcher", "type": null }, { "param": "app", "type": "web.Application" }, { "param": "path", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "dispatcher", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, ...
7841a4d0128262ee9b425d0edb226217344aaca3
JMarkin/afbmq
afbmq/dispatcher/filters/builtin.py
[ "MIT" ]
Python
check
<not_specific>
async def check(self, event: types.MessageEvent, message: types.Message): """ If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler :param event: :param message: :return: """ check = await super().check(even...
If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler :param event: :param message: :return:
If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler
[ "If", "deep", "-", "linking", "is", "passed", "to", "the", "filter", "result", "of", "the", "matching", "will", "be", "passed", "as", "`", "`", "deep_link", "`", "`", "to", "the", "handler" ]
async def check(self, event: types.MessageEvent, message: types.Message): check = await super().check(event, message) if check and self.deep_link is not None: if not isinstance(self.deep_link, re.Pattern): return message.get_args() == self.deep_link match = self.d...
[ "async", "def", "check", "(", "self", ",", "event", ":", "types", ".", "MessageEvent", ",", "message", ":", "types", ".", "Message", ")", ":", "check", "=", "await", "super", "(", ")", ".", "check", "(", "event", ",", "message", ")", "if", "check", ...
If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler
[ "If", "deep", "-", "linking", "is", "passed", "to", "the", "filter", "result", "of", "the", "matching", "will", "be", "passed", "as", "`", "`", "deep_link", "`", "`", "to", "the", "handler" ]
[ "\"\"\"\n If deep-linking is passed to the filter result of the matching will be passed as ``deep_link`` to the handler\n\n :param event:\n :param message:\n :return:\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "event", "type": "types.MessageEvent" }, { "param": "message", "type": "types.Message" } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
d6ebf3778c01c7805497246201eaa662210a4577
tumeteor/neurips2019challenge
src/data_utils/loader.py
[ "Apache-2.0" ]
Python
_salt_and_pepper_noise
object
def _salt_and_pepper_noise(image: object, noise_typ: object = "gauss") -> object: """ add Gaussian noise to distort the high-frequency features (zero pixels) Args: image (numpy.ndarray): the target image Returns: numpy.ndarray: the image with random noise """ if noise_typ == "ga...
add Gaussian noise to distort the high-frequency features (zero pixels) Args: image (numpy.ndarray): the target image Returns: numpy.ndarray: the image with random noise
add Gaussian noise to distort the high-frequency features (zero pixels)
[ "add", "Gaussian", "noise", "to", "distort", "the", "high", "-", "frequency", "features", "(", "zero", "pixels", ")" ]
def _salt_and_pepper_noise(image: object, noise_typ: object = "gauss") -> object: if noise_typ == "gauss": row, col, ch = image.shape mean = 0 var = 0.05 sigma = var ** 0.5 gauss = np.random.normal(mean, sigma, (row, col, ch)) gauss = gauss.reshape(row, col, ch) ...
[ "def", "_salt_and_pepper_noise", "(", "image", ":", "object", ",", "noise_typ", ":", "object", "=", "\"gauss\"", ")", "->", "object", ":", "if", "noise_typ", "==", "\"gauss\"", ":", "row", ",", "col", ",", "ch", "=", "image", ".", "shape", "mean", "=", ...
add Gaussian noise to distort the high-frequency features (zero pixels)
[ "add", "Gaussian", "noise", "to", "distort", "the", "high", "-", "frequency", "features", "(", "zero", "pixels", ")" ]
[ "\"\"\"\n add Gaussian noise to distort the high-frequency features (zero pixels)\n Args:\n image (numpy.ndarray): the target image\n\n Returns:\n numpy.ndarray: the image with random noise\n \"\"\"", "# one channel", "# Salt mode", "# Pepper mode" ]
[ { "param": "image", "type": "object" }, { "param": "noise_typ", "type": "object" } ]
{ "returns": [ { "docstring": "the image with random noise", "docstring_tokens": [ "the", "image", "with", "random", "noise" ], "type": "numpy.ndarray" } ], "raises": [], "params": [ { "identifier": "image", "type": "object"...
d6ebf3778c01c7805497246201eaa662210a4577
tumeteor/neurips2019challenge
src/data_utils/loader.py
[ "Apache-2.0" ]
Python
load_data
<not_specific>
def load_data(file_path, indices=None, K=10, T=10, training=True, batch_size=1): """Load data for one test day, return as numpy array with normalized samples of each 6 time steps in random order. Args.: file_path (str): file path of h5 file for one day indices (list): list w...
Load data for one test day, return as numpy array with normalized samples of each 6 time steps in random order. Args.: file_path (str): file path of h5 file for one day indices (list): list with prediction times (as list indices in the interval [0, 288]) K (int): the...
Load data for one test day, return as numpy array with normalized samples of each 6 time steps in random order.
[ "Load", "data", "for", "one", "test", "day", "return", "as", "numpy", "array", "with", "normalized", "samples", "of", "each", "6", "time", "steps", "in", "random", "order", "." ]
def load_data(file_path, indices=None, K=10, T=10, training=True, batch_size=1): logging.info("load data: {}".format(file_path)) fr = h5py.File(file_path, 'r') a_group_key = list(fr.keys())[0] data = fr[a_group_key] data = np.array(data) data = [to_tiles(_salt_and_pepper_noise(crop_image(im)) / ...
[ "def", "load_data", "(", "file_path", ",", "indices", "=", "None", ",", "K", "=", "10", ",", "T", "=", "10", ",", "training", "=", "True", ",", "batch_size", "=", "1", ")", ":", "logging", ".", "info", "(", "\"load data: {}\"", ".", "format", "(", ...
Load data for one test day, return as numpy array with normalized samples of each 6 time steps in random order.
[ "Load", "data", "for", "one", "test", "day", "return", "as", "numpy", "array", "with", "normalized", "samples", "of", "each", "6", "time", "steps", "in", "random", "order", "." ]
[ "\"\"\"Load data for one test day, return as numpy array with normalized samples of each\n 6 time steps in random order.\n\n Args.:\n file_path (str): file path of h5 file for one day\n indices (list): list with prediction times (as list indices in the interval [0, 288])\n ...
[ { "param": "file_path", "type": null }, { "param": "indices", "type": null }, { "param": "K", "type": null }, { "param": "T", "type": null }, { "param": "training", "type": null }, { "param": "batch_size", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "file_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "indices", "type": null, "docstring": null, "docstring_to...
d6ebf3778c01c7805497246201eaa662210a4577
tumeteor/neurips2019challenge
src/data_utils/loader.py
[ "Apache-2.0" ]
Python
return_date
<not_specific>
def return_date(file_name): """Auxilliary function which returns datetime object from Traffic4Cast filename. Args.: file_name (str): file name, e.g., '20180516_100m_bins.h5' Returns: date string, e.g., '2018-05-16' """ match = re.search(r'\d{4}\d{2}\d{2}', file_name) date ...
Auxilliary function which returns datetime object from Traffic4Cast filename. Args.: file_name (str): file name, e.g., '20180516_100m_bins.h5' Returns: date string, e.g., '2018-05-16'
Auxilliary function which returns datetime object from Traffic4Cast filename.
[ "Auxilliary", "function", "which", "returns", "datetime", "object", "from", "Traffic4Cast", "filename", "." ]
def return_date(file_name): match = re.search(r'\d{4}\d{2}\d{2}', file_name) date = datetime.datetime.strptime(match.group(), '%Y%m%d').date() return date
[ "def", "return_date", "(", "file_name", ")", ":", "match", "=", "re", ".", "search", "(", "r'\\d{4}\\d{2}\\d{2}'", ",", "file_name", ")", "date", "=", "datetime", ".", "datetime", ".", "strptime", "(", "match", ".", "group", "(", ")", ",", "'%Y%m%d'", ")...
Auxilliary function which returns datetime object from Traffic4Cast filename.
[ "Auxilliary", "function", "which", "returns", "datetime", "object", "from", "Traffic4Cast", "filename", "." ]
[ "\"\"\"Auxilliary function which returns datetime object from Traffic4Cast filename.\n\n Args.:\n file_name (str): file name, e.g., '20180516_100m_bins.h5'\n\n Returns: date string, e.g., '2018-05-16'\n \"\"\"" ]
[ { "param": "file_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "file_name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
a4a993e4419b789e6605e74f61add0046d5ebaaf
tumeteor/neurips2019challenge
src/utils.py
[ "Apache-2.0" ]
Python
merge
<not_specific>
def merge(images, size): """ merge image sequence (backward + forward) Args: images (numpy.ndarray): the array of images (backward + forward sequences), shape (2*T, 80, 80, 3) size (list): (2,1), example value: [2,T] Returns: """ h, w = images.shape[1], images.shape[2] img...
merge image sequence (backward + forward) Args: images (numpy.ndarray): the array of images (backward + forward sequences), shape (2*T, 80, 80, 3) size (list): (2,1), example value: [2,T] Returns:
merge image sequence (backward + forward)
[ "merge", "image", "sequence", "(", "backward", "+", "forward", ")" ]
def merge(images, size): h, w = images.shape[1], images.shape[2] img = np.zeros((h * size[0], w * size[1], 3)) for idx, image in enumerate(images): print(idx, np.shape(image)) i = idx % size[1] j = idx // size[1] img[j * h:j * h + h, i * w:i * w + w, :] = image return img
[ "def", "merge", "(", "images", ",", "size", ")", ":", "h", ",", "w", "=", "images", ".", "shape", "[", "1", "]", ",", "images", ".", "shape", "[", "2", "]", "img", "=", "np", ".", "zeros", "(", "(", "h", "*", "size", "[", "0", "]", ",", "...
merge image sequence (backward + forward)
[ "merge", "image", "sequence", "(", "backward", "+", "forward", ")" ]
[ "\"\"\"\n merge image sequence (backward + forward)\n Args:\n images (numpy.ndarray): the array of images (backward + forward sequences), shape (2*T, 80, 80, 3)\n size (list): (2,1), example value: [2,T]\n\n Returns:\n\n \"\"\"" ]
[ { "param": "images", "type": null }, { "param": "size", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "images", "type": null, "docstring": "the array of images (backward + forward sequences), shape (2*T, 80, 80, 3)", ...
a4a993e4419b789e6605e74f61add0046d5ebaaf
tumeteor/neurips2019challenge
src/utils.py
[ "Apache-2.0" ]
Python
reshape_patch
<not_specific>
def reshape_patch(img_tensor, patch_size): """Reshape a 5D image tensor to a 5D patch tensor.""" # print(f"adasd {np.shape(img_tensor)}") # assert 5 == img_tensor.ndim batch_size = np.shape(img_tensor)[0] seq_length = np.shape(img_tensor)[1] img_height = np.shape(img_tensor)[2] img_width = n...
Reshape a 5D image tensor to a 5D patch tensor.
Reshape a 5D image tensor to a 5D patch tensor.
[ "Reshape", "a", "5D", "image", "tensor", "to", "a", "5D", "patch", "tensor", "." ]
def reshape_patch(img_tensor, patch_size): batch_size = np.shape(img_tensor)[0] seq_length = np.shape(img_tensor)[1] img_height = np.shape(img_tensor)[2] img_width = np.shape(img_tensor)[3] num_channels = np.shape(img_tensor)[4] a = np.reshape(img_tensor, [ batch_size, seq_length, img_he...
[ "def", "reshape_patch", "(", "img_tensor", ",", "patch_size", ")", ":", "batch_size", "=", "np", ".", "shape", "(", "img_tensor", ")", "[", "0", "]", "seq_length", "=", "np", ".", "shape", "(", "img_tensor", ")", "[", "1", "]", "img_height", "=", "np",...
Reshape a 5D image tensor to a 5D patch tensor.
[ "Reshape", "a", "5D", "image", "tensor", "to", "a", "5D", "patch", "tensor", "." ]
[ "\"\"\"Reshape a 5D image tensor to a 5D patch tensor.\"\"\"", "# print(f\"adasd {np.shape(img_tensor)}\")", "# assert 5 == img_tensor.ndim" ]
[ { "param": "img_tensor", "type": null }, { "param": "patch_size", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "img_tensor", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "patch_size", "type": null, "docstring": null, "docstrin...
0a1cb1ef4efedf39848386200e0dd0d24b25d73e
brn73/ftp2http
ftp2http/ftp2http.py
[ "MIT" ]
Python
validpath
<not_specific>
def validpath(self, path): """ Check whether the path belongs to the user's home directory. Expected argument is a "real" filesystem pathname. Pathnames escaping from user's root directory are considered not valid. Overridden to not access the filesystem at all. ...
Check whether the path belongs to the user's home directory. Expected argument is a "real" filesystem pathname. Pathnames escaping from user's root directory are considered not valid. Overridden to not access the filesystem at all.
Check whether the path belongs to the user's home directory. Expected argument is a "real" filesystem pathname. Pathnames escaping from user's root directory are considered not valid. Overridden to not access the filesystem at all.
[ "Check", "whether", "the", "path", "belongs", "to", "the", "user", "'", "s", "home", "directory", ".", "Expected", "argument", "is", "a", "\"", "real", "\"", "filesystem", "pathname", ".", "Pathnames", "escaping", "from", "user", "'", "s", "root", "directo...
def validpath(self, path): assert isinstance(path, unicode), path root = os.path.normpath(self.root) path = os.path.normpath(path) if not root.endswith(os.sep): root = root + os.sep if not path.endswith(os.sep): path = path + os.sep if path[0:len(r...
[ "def", "validpath", "(", "self", ",", "path", ")", ":", "assert", "isinstance", "(", "path", ",", "unicode", ")", ",", "path", "root", "=", "os", ".", "path", ".", "normpath", "(", "self", ".", "root", ")", "path", "=", "os", ".", "path", ".", "n...
Check whether the path belongs to the user's home directory.
[ "Check", "whether", "the", "path", "belongs", "to", "the", "user", "'", "s", "home", "directory", "." ]
[ "\"\"\"\n Check whether the path belongs to the user's home directory.\n Expected argument is a \"real\" filesystem pathname.\n\n Pathnames escaping from user's root directory are considered\n not valid.\n\n Overridden to not access the filesystem at all.\n\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [...
0a1cb1ef4efedf39848386200e0dd0d24b25d73e
brn73/ftp2http
ftp2http/ftp2http.py
[ "MIT" ]
Python
close
<not_specific>
def close(self): """ Extend the class to close the file earlier than usual, making the HTTP upload occur before a response is sent to the FTP client. In the event of an unsuccessful HTTP upload, relay the HTTP error message to the FTP client by overriding the response. "...
Extend the class to close the file earlier than usual, making the HTTP upload occur before a response is sent to the FTP client. In the event of an unsuccessful HTTP upload, relay the HTTP error message to the FTP client by overriding the response.
Extend the class to close the file earlier than usual, making the HTTP upload occur before a response is sent to the FTP client. In the event of an unsuccessful HTTP upload, relay the HTTP error message to the FTP client by overriding the response.
[ "Extend", "the", "class", "to", "close", "the", "file", "earlier", "than", "usual", "making", "the", "HTTP", "upload", "occur", "before", "a", "response", "is", "sent", "to", "the", "FTP", "client", ".", "In", "the", "event", "of", "an", "unsuccessful", ...
def close(self): if self.receive and self.transfer_finished and not self._closed: if self.file_obj is not None and not self.file_obj.closed: try: self.file_obj.close() except UnexpectedHTTPResponse as error: self._resp = ('550 E...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "receive", "and", "self", ".", "transfer_finished", "and", "not", "self", ".", "_closed", ":", "if", "self", ".", "file_obj", "is", "not", "None", "and", "not", "self", ".", "file_obj", ".", "...
Extend the class to close the file earlier than usual, making the HTTP upload occur before a response is sent to the FTP client.
[ "Extend", "the", "class", "to", "close", "the", "file", "earlier", "than", "usual", "making", "the", "HTTP", "upload", "occur", "before", "a", "response", "is", "sent", "to", "the", "FTP", "client", "." ]
[ "\"\"\"\n Extend the class to close the file earlier than usual, making the HTTP\n upload occur before a response is sent to the FTP client. In the event\n of an unsuccessful HTTP upload, relay the HTTP error message to the\n FTP client by overriding the response.\n\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
0a1cb1ef4efedf39848386200e0dd0d24b25d73e
brn73/ftp2http
ftp2http/ftp2http.py
[ "MIT" ]
Python
validate_authentication
null
def validate_authentication(self, username, password, handler): """ Raises AuthenticationFailed if the supplied username and password are not valid credentials, else return None. """ valid = self._validate_with_user_table(username, password) if not valid: fo...
Raises AuthenticationFailed if the supplied username and password are not valid credentials, else return None.
Raises AuthenticationFailed if the supplied username and password are not valid credentials, else return None.
[ "Raises", "AuthenticationFailed", "if", "the", "supplied", "username", "and", "password", "are", "not", "valid", "credentials", "else", "return", "None", "." ]
def validate_authentication(self, username, password, handler): valid = self._validate_with_user_table(username, password) if not valid: for url in self._backends: valid = self._validate_with_url(username, password, url) if valid: break ...
[ "def", "validate_authentication", "(", "self", ",", "username", ",", "password", ",", "handler", ")", ":", "valid", "=", "self", ".", "_validate_with_user_table", "(", "username", ",", "password", ")", "if", "not", "valid", ":", "for", "url", "in", "self", ...
Raises AuthenticationFailed if the supplied username and password are not valid credentials, else return None.
[ "Raises", "AuthenticationFailed", "if", "the", "supplied", "username", "and", "password", "are", "not", "valid", "credentials", "else", "return", "None", "." ]
[ "\"\"\"\n Raises AuthenticationFailed if the supplied username and password\n are not valid credentials, else return None.\n\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "username", "type": null }, { "param": "password", "type": null }, { "param": "handler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "username", "type": null, "docstring": null, "docstring_tokens...
527b0e5f9ad80ae473d1c150c3d065a923131666
jaideep2/yanrin
yanrin/topic_modeling_old.py
[ "Apache-2.0" ]
Python
ret_top_model
<not_specific>
def ret_top_model(corpus): """ Since LDAmodel is a probabilistic model, it comes up different topics each time we run it. To control the quality of the topic model we produce, we can see what the interpretability of the best topic is and keep evaluating the topic model until this threshold is crossed. ...
Since LDAmodel is a probabilistic model, it comes up different topics each time we run it. To control the quality of the topic model we produce, we can see what the interpretability of the best topic is and keep evaluating the topic model until this threshold is crossed. Returns: ------- lm: F...
Since LDAmodel is a probabilistic model, it comes up different topics each time we run it. To control the quality of the topic model we produce, we can see what the interpretability of the best topic is and keep evaluating the topic model until this threshold is crossed.
[ "Since", "LDAmodel", "is", "a", "probabilistic", "model", "it", "comes", "up", "different", "topics", "each", "time", "we", "run", "it", ".", "To", "control", "the", "quality", "of", "the", "topic", "model", "we", "produce", "we", "can", "see", "what", "...
def ret_top_model(corpus): top_topics = [(0, 0)] rounds = 1 high = 0.0 out_lm = None while True: lm = LdaModel(corpus=corpus, num_topics=20, id2word=dictionary, minimum_probability=0) coherence_values = {} for n, topic in lm.show_topics(num_topics=-1, formatted=False): ...
[ "def", "ret_top_model", "(", "corpus", ")", ":", "top_topics", "=", "[", "(", "0", ",", "0", ")", "]", "rounds", "=", "1", "high", "=", "0.0", "out_lm", "=", "None", "while", "True", ":", "lm", "=", "LdaModel", "(", "corpus", "=", "corpus", ",", ...
Since LDAmodel is a probabilistic model, it comes up different topics each time we run it.
[ "Since", "LDAmodel", "is", "a", "probabilistic", "model", "it", "comes", "up", "different", "topics", "each", "time", "we", "run", "it", "." ]
[ "\"\"\"\n Since LDAmodel is a probabilistic model, it comes up different topics each time we run it. To control the\n quality of the topic model we produce, we can see what the interpretability of the best topic is and keep\n evaluating the topic model until this threshold is crossed.\n\n Returns:\n ...
[ { "param": "corpus", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "corpus", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
4a07c63add5abc7ad9451d054d9385cd5e5d4161
jaideep2/yanrin
yanrin/topic_modeling.py
[ "Apache-2.0" ]
Python
ret_top_model
<not_specific>
def ret_top_model(corpus, dictionary, train_texts, num_times): """ Since LDAmodel is a probabilistic model, it comes up different topics each time we run it. To control the quality of the topic model we produce, we can see what the interpretability of the best topic is and keep evaluating the topic mode...
Since LDAmodel is a probabilistic model, it comes up different topics each time we run it. To control the quality of the topic model we produce, we can see what the interpretability of the best topic is and keep evaluating the topic model until a certian threshold is crossed. Returns: ------- ...
Since LDAmodel is a probabilistic model, it comes up different topics each time we run it. To control the quality of the topic model we produce, we can see what the interpretability of the best topic is and keep evaluating the topic model until a certian threshold is crossed.
[ "Since", "LDAmodel", "is", "a", "probabilistic", "model", "it", "comes", "up", "different", "topics", "each", "time", "we", "run", "it", ".", "To", "control", "the", "quality", "of", "the", "topic", "model", "we", "produce", "we", "can", "see", "what", "...
def ret_top_model(corpus, dictionary, train_texts, num_times): top_topics = [(0, 0)] rounds = 1 high = 0.0 out_lm = None print('dict size:',len(dictionary)) num_topics = int(len(dictionary)*0.1) print('num_topics:',num_topics) while True: lm = LdaModel(corpus=corpus, num_topics=...
[ "def", "ret_top_model", "(", "corpus", ",", "dictionary", ",", "train_texts", ",", "num_times", ")", ":", "top_topics", "=", "[", "(", "0", ",", "0", ")", "]", "rounds", "=", "1", "high", "=", "0.0", "out_lm", "=", "None", "print", "(", "'dict size:'",...
Since LDAmodel is a probabilistic model, it comes up different topics each time we run it.
[ "Since", "LDAmodel", "is", "a", "probabilistic", "model", "it", "comes", "up", "different", "topics", "each", "time", "we", "run", "it", "." ]
[ "\"\"\"\n Since LDAmodel is a probabilistic model, it comes up different topics each time we run it. To control the\n quality of the topic model we produce, we can see what the interpretability of the best topic is and keep\n evaluating the topic model until a certian threshold is crossed.\n\n Returns:\...
[ { "param": "corpus", "type": null }, { "param": "dictionary", "type": null }, { "param": "train_texts", "type": null }, { "param": "num_times", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "corpus", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
4a07c63add5abc7ad9451d054d9385cd5e5d4161
jaideep2/yanrin
yanrin/topic_modeling.py
[ "Apache-2.0" ]
Python
main
null
def main(): ''' 0. decide what date or range of dates to run this on 1. create dictionary and corpus 2. create model 3. for each doc get top topic 4. insert topic into topic table with date :return: ''' datez = create_dates(2016) doc = [] for date in datez: doc.extend...
0. decide what date or range of dates to run this on 1. create dictionary and corpus 2. create model 3. for each doc get top topic 4. insert topic into topic table with date :return:
0. decide what date or range of dates to run this on 1. create dictionary and corpus 2. create model 3. for each doc get top topic 4. insert topic into topic table with date
[ "0", ".", "decide", "what", "date", "or", "range", "of", "dates", "to", "run", "this", "on", "1", ".", "create", "dictionary", "and", "corpus", "2", ".", "create", "model", "3", ".", "for", "each", "doc", "get", "top", "topic", "4", ".", "insert", ...
def main(): datez = create_dates(2016) doc = [] for date in datez: doc.extend(get_doc(date)) doc_len = len(doc) train_texts = process_doc(doc) dictionary = process_dict(train_texts,doc_len) corpus = [dictionary.doc2bow(text) for text in train_texts] print('doc_len:',doc_len) ...
[ "def", "main", "(", ")", ":", "datez", "=", "create_dates", "(", "2016", ")", "doc", "=", "[", "]", "for", "date", "in", "datez", ":", "doc", ".", "extend", "(", "get_doc", "(", "date", ")", ")", "doc_len", "=", "len", "(", "doc", ")", "train_tex...
0. decide what date or range of dates to run this on 1. create dictionary and corpus 2. create model 3. for each doc get top topic 4. insert topic into topic table with date
[ "0", ".", "decide", "what", "date", "or", "range", "of", "dates", "to", "run", "this", "on", "1", ".", "create", "dictionary", "and", "corpus", "2", ".", "create", "model", "3", ".", "for", "each", "doc", "get", "top", "topic", "4", ".", "insert", ...
[ "'''\n 0. decide what date or range of dates to run this on\n 1. create dictionary and corpus\n 2. create model\n 3. for each doc get top topic\n 4. insert topic into topic table with date\n :return:\n '''" ]
[]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [], "outlier_params": [], "others": [] }
01fecd5cf19183c437a11be29e7d1b465f6b8dd9
TSO-team/StationDePesage
python/utils/interfaces/VL6180X.py
[ "Apache-2.0" ]
Python
read_lux
<not_specific>
def read_lux(self, gain): """Read the lux (light value) from the sensor and return it. Must specify the gain value to use for the lux reading: - ALS_GAIN_1 = 1x - ALS_GAIN_1_25 = 1.25x - ALS_GAIN_1_67 = 1.67x - ALS_GAIN_2_5 = 2.5x - ALS_GAIN_5 = 5x - ALS_...
Read the lux (light value) from the sensor and return it. Must specify the gain value to use for the lux reading: - ALS_GAIN_1 = 1x - ALS_GAIN_1_25 = 1.25x - ALS_GAIN_1_67 = 1.67x - ALS_GAIN_2_5 = 2.5x - ALS_GAIN_5 = 5x - ALS_GAIN_10 = 10x - ALS_GAIN_20 =...
Read the lux (light value) from the sensor and return it.
[ "Read", "the", "lux", "(", "light", "value", ")", "from", "the", "sensor", "and", "return", "it", "." ]
def read_lux(self, gain): reg = self._read_8(_VL6180X_REG_SYSTEM_INTERRUPT_CONFIG) reg &= ~0x38 reg |= 0x4 << 3 self._write_8(_VL6180X_REG_SYSTEM_INTERRUPT_CONFIG, reg) self._write_8(_VL6180X_REG_SYSALS_INTEGRATION_PERIOD_HI, 0) self._write_8(_VL6180X_REG_SYSALS_INTEGRAT...
[ "def", "read_lux", "(", "self", ",", "gain", ")", ":", "reg", "=", "self", ".", "_read_8", "(", "_VL6180X_REG_SYSTEM_INTERRUPT_CONFIG", ")", "reg", "&=", "~", "0x38", "reg", "|=", "0x4", "<<", "3", "self", ".", "_write_8", "(", "_VL6180X_REG_SYSTEM_INTERRUPT...
Read the lux (light value) from the sensor and return it.
[ "Read", "the", "lux", "(", "light", "value", ")", "from", "the", "sensor", "and", "return", "it", "." ]
[ "\"\"\"Read the lux (light value) from the sensor and return it. Must\n specify the gain value to use for the lux reading:\n - ALS_GAIN_1 = 1x\n - ALS_GAIN_1_25 = 1.25x\n - ALS_GAIN_1_67 = 1.67x\n - ALS_GAIN_2_5 = 2.5x\n - ALS_GAIN_5 = 5x\n - ALS_GAIN_10 = 10x\n ...
[ { "param": "self", "type": null }, { "param": "gain", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "gain", "type": null, "docstring": null, "docstring_tokens": [...
95cd67814903401abd9e3ab1b92f1d45c4b1e3a2
tophatmonocle/dd-trace-py
ddtrace/contrib/gevent/patch.py
[ "BSD-3-Clause" ]
Python
unpatch
null
def unpatch(): """ Restore the original ``Greenlet``. This function must be invoked before executing application code, otherwise the ``DatadogGreenlet`` class may be used during initialization. """ _replace(__Greenlet, __IMap, __IMapUnordered) ddtrace.tracer.configure(context_provider=Defaul...
Restore the original ``Greenlet``. This function must be invoked before executing application code, otherwise the ``DatadogGreenlet`` class may be used during initialization.
Restore the original ``Greenlet``. This function must be invoked before executing application code, otherwise the ``DatadogGreenlet`` class may be used during initialization.
[ "Restore", "the", "original", "`", "`", "Greenlet", "`", "`", ".", "This", "function", "must", "be", "invoked", "before", "executing", "application", "code", "otherwise", "the", "`", "`", "DatadogGreenlet", "`", "`", "class", "may", "be", "used", "during", ...
def unpatch(): _replace(__Greenlet, __IMap, __IMapUnordered) ddtrace.tracer.configure(context_provider=DefaultContextProvider())
[ "def", "unpatch", "(", ")", ":", "_replace", "(", "__Greenlet", ",", "__IMap", ",", "__IMapUnordered", ")", "ddtrace", ".", "tracer", ".", "configure", "(", "context_provider", "=", "DefaultContextProvider", "(", ")", ")" ]
Restore the original ``Greenlet``.
[ "Restore", "the", "original", "`", "`", "Greenlet", "`", "`", "." ]
[ "\"\"\"\n Restore the original ``Greenlet``. This function must be invoked\n before executing application code, otherwise the ``DatadogGreenlet``\n class may be used during initialization.\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
95cd67814903401abd9e3ab1b92f1d45c4b1e3a2
tophatmonocle/dd-trace-py
ddtrace/contrib/gevent/patch.py
[ "BSD-3-Clause" ]
Python
_replace
null
def _replace(g_class, imap_class, imap_unordered_class): """ Utility function that replace the gevent Greenlet class with the given one. """ # replace the original Greenlet classes with the new one gevent.greenlet.Greenlet = g_class gevent.pool.IMap = imap_class gevent.pool.IMapUnordered = i...
Utility function that replace the gevent Greenlet class with the given one.
Utility function that replace the gevent Greenlet class with the given one.
[ "Utility", "function", "that", "replace", "the", "gevent", "Greenlet", "class", "with", "the", "given", "one", "." ]
def _replace(g_class, imap_class, imap_unordered_class): gevent.greenlet.Greenlet = g_class gevent.pool.IMap = imap_class gevent.pool.IMapUnordered = imap_unordered_class gevent.pool.Group.greenlet_class = g_class gevent.Greenlet = gevent.greenlet.Greenlet gevent.spawn = gevent.greenlet.Greenlet...
[ "def", "_replace", "(", "g_class", ",", "imap_class", ",", "imap_unordered_class", ")", ":", "gevent", ".", "greenlet", ".", "Greenlet", "=", "g_class", "gevent", ".", "pool", ".", "IMap", "=", "imap_class", "gevent", ".", "pool", ".", "IMapUnordered", "=", ...
Utility function that replace the gevent Greenlet class with the given one.
[ "Utility", "function", "that", "replace", "the", "gevent", "Greenlet", "class", "with", "the", "given", "one", "." ]
[ "\"\"\"\n Utility function that replace the gevent Greenlet class with the given one.\n \"\"\"", "# replace the original Greenlet classes with the new one", "# replace gevent shortcuts" ]
[ { "param": "g_class", "type": null }, { "param": "imap_class", "type": null }, { "param": "imap_unordered_class", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "g_class", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "imap_class", "type": null, "docstring": null, "docstring_t...
639869df8095adfb1b26f2f90fa169194abc2226
tophatmonocle/dd-trace-py
tests/commands/test_runner.py
[ "BSD-3-Clause" ]
Python
tearDown
null
def tearDown(self): """ Clear DATADOG_* env vars between tests """ for k in ('DATADOG_ENV', 'DATADOG_TRACE_ENABLED', 'DATADOG_SERVICE_NAME', 'DATADOG_TRACE_DEBUG'): if k in os.environ: del os.environ[k]
Clear DATADOG_* env vars between tests
Clear DATADOG_* env vars between tests
[ "Clear", "DATADOG_", "*", "env", "vars", "between", "tests" ]
def tearDown(self): for k in ('DATADOG_ENV', 'DATADOG_TRACE_ENABLED', 'DATADOG_SERVICE_NAME', 'DATADOG_TRACE_DEBUG'): if k in os.environ: del os.environ[k]
[ "def", "tearDown", "(", "self", ")", ":", "for", "k", "in", "(", "'DATADOG_ENV'", ",", "'DATADOG_TRACE_ENABLED'", ",", "'DATADOG_SERVICE_NAME'", ",", "'DATADOG_TRACE_DEBUG'", ")", ":", "if", "k", "in", "os", ".", "environ", ":", "del", "os", ".", "environ", ...
Clear DATADOG_* env vars between tests
[ "Clear", "DATADOG_", "*", "env", "vars", "between", "tests" ]
[ "\"\"\"\n Clear DATADOG_* env vars between tests\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
d614e9125b8ab9890c915ea1a350a42589533ff2
tophatmonocle/dd-trace-py
ddtrace/contrib/falcon/middleware.py
[ "BSD-3-Clause" ]
Python
_detect_and_set_status_error
<not_specific>
def _detect_and_set_status_error(err_type, span): """Detect the HTTP status code from the current stacktrace and set the traceback to the given Span """ if not _is_404(err_type): span.set_traceback() return '500' elif _is_404(err_type): return '404'
Detect the HTTP status code from the current stacktrace and set the traceback to the given Span
Detect the HTTP status code from the current stacktrace and set the traceback to the given Span
[ "Detect", "the", "HTTP", "status", "code", "from", "the", "current", "stacktrace", "and", "set", "the", "traceback", "to", "the", "given", "Span" ]
def _detect_and_set_status_error(err_type, span): if not _is_404(err_type): span.set_traceback() return '500' elif _is_404(err_type): return '404'
[ "def", "_detect_and_set_status_error", "(", "err_type", ",", "span", ")", ":", "if", "not", "_is_404", "(", "err_type", ")", ":", "span", ".", "set_traceback", "(", ")", "return", "'500'", "elif", "_is_404", "(", "err_type", ")", ":", "return", "'404'" ]
Detect the HTTP status code from the current stacktrace and set the traceback to the given Span
[ "Detect", "the", "HTTP", "status", "code", "from", "the", "current", "stacktrace", "and", "set", "the", "traceback", "to", "the", "given", "Span" ]
[ "\"\"\"Detect the HTTP status code from the current stacktrace and\n set the traceback to the given Span\n \"\"\"" ]
[ { "param": "err_type", "type": null }, { "param": "span", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "err_type", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "span", "type": null, "docstring": null, "docstring_tokens...
762f2f658604dc48e5dff605278efd4b86f2f0e7
tophatmonocle/dd-trace-py
ddtrace/pin.py
[ "BSD-3-Clause" ]
Python
service
<not_specific>
def service(self): """Backward compatibility: accessing to `pin.service` returns the underlying configuration value. """ return self._config['service_name']
Backward compatibility: accessing to `pin.service` returns the underlying configuration value.
Backward compatibility: accessing to `pin.service` returns the underlying configuration value.
[ "Backward", "compatibility", ":", "accessing", "to", "`", "pin", ".", "service", "`", "returns", "the", "underlying", "configuration", "value", "." ]
def service(self): return self._config['service_name']
[ "def", "service", "(", "self", ")", ":", "return", "self", ".", "_config", "[", "'service_name'", "]" ]
Backward compatibility: accessing to `pin.service` returns the underlying configuration value.
[ "Backward", "compatibility", ":", "accessing", "to", "`", "pin", ".", "service", "`", "returns", "the", "underlying", "configuration", "value", "." ]
[ "\"\"\"Backward compatibility: accessing to `pin.service` returns the underlying\n configuration value.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
762f2f658604dc48e5dff605278efd4b86f2f0e7
tophatmonocle/dd-trace-py
ddtrace/pin.py
[ "BSD-3-Clause" ]
Python
override
<not_specific>
def override(cls, obj, service=None, app=None, app_type=None, tags=None, tracer=None): """Override an object with the given attributes. That's the recommended way to customize an already instrumented client, without losing existing attributes. >>> conn = sqlite.connect("/tmp/user.d...
Override an object with the given attributes. That's the recommended way to customize an already instrumented client, without losing existing attributes. >>> conn = sqlite.connect("/tmp/user.db") >>> # Override a pin for a specific connection >>> Pin.override(conn, ...
Override an object with the given attributes. That's the recommended way to customize an already instrumented client, without losing existing attributes.
[ "Override", "an", "object", "with", "the", "given", "attributes", ".", "That", "'", "s", "the", "recommended", "way", "to", "customize", "an", "already", "instrumented", "client", "without", "losing", "existing", "attributes", "." ]
def override(cls, obj, service=None, app=None, app_type=None, tags=None, tracer=None): if not obj: return pin = cls.get_from(obj) if not pin: pin = Pin(service) pin.clone( service=service, app=app, app_type=app_type, ...
[ "def", "override", "(", "cls", ",", "obj", ",", "service", "=", "None", ",", "app", "=", "None", ",", "app_type", "=", "None", ",", "tags", "=", "None", ",", "tracer", "=", "None", ")", ":", "if", "not", "obj", ":", "return", "pin", "=", "cls", ...
Override an object with the given attributes.
[ "Override", "an", "object", "with", "the", "given", "attributes", "." ]
[ "\"\"\"Override an object with the given attributes.\n\n That's the recommended way to customize an already instrumented client, without\n losing existing attributes.\n\n >>> conn = sqlite.connect(\"/tmp/user.db\")\n >>> # Override a pin for a specific connection\n >>>...
[ { "param": "cls", "type": null }, { "param": "obj", "type": null }, { "param": "service", "type": null }, { "param": "app", "type": null }, { "param": "app_type", "type": null }, { "param": "tags", "type": null }, { "param": "tracer", "...
{ "returns": [], "raises": [], "params": [ { "identifier": "cls", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obj", "type": null, "docstring": null, "docstring_tokens": [],...
762f2f658604dc48e5dff605278efd4b86f2f0e7
tophatmonocle/dd-trace-py
ddtrace/pin.py
[ "BSD-3-Clause" ]
Python
onto
<not_specific>
def onto(self, obj, send=True): """Patch this pin onto the given object. If send is true, it will also queue the metadata to be sent to the server. """ # pinning will also queue the metadata for service submission. this # feels a bit side-effecty, but bc it's async and pretty cle...
Patch this pin onto the given object. If send is true, it will also queue the metadata to be sent to the server.
Patch this pin onto the given object. If send is true, it will also queue the metadata to be sent to the server.
[ "Patch", "this", "pin", "onto", "the", "given", "object", ".", "If", "send", "is", "true", "it", "will", "also", "queue", "the", "metadata", "to", "be", "sent", "to", "the", "server", "." ]
def onto(self, obj, send=True): if send: try: self._send() except Exception: log.debug("can't send pin info", exc_info=True) try: if hasattr(obj, '__setddpin__'): return obj.__setddpin__(self) pin_name = _DD_...
[ "def", "onto", "(", "self", ",", "obj", ",", "send", "=", "True", ")", ":", "if", "send", ":", "try", ":", "self", ".", "_send", "(", ")", "except", "Exception", ":", "log", ".", "debug", "(", "\"can't send pin info\"", ",", "exc_info", "=", "True", ...
Patch this pin onto the given object.
[ "Patch", "this", "pin", "onto", "the", "given", "object", "." ]
[ "\"\"\"Patch this pin onto the given object. If send is true, it will also\n queue the metadata to be sent to the server.\n \"\"\"", "# pinning will also queue the metadata for service submission. this", "# feels a bit side-effecty, but bc it's async and pretty clearly", "# communicates what we ...
[ { "param": "self", "type": null }, { "param": "obj", "type": null }, { "param": "send", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "obj", "type": null, "docstring": null, "docstring_tokens": []...
762f2f658604dc48e5dff605278efd4b86f2f0e7
tophatmonocle/dd-trace-py
ddtrace/pin.py
[ "BSD-3-Clause" ]
Python
clone
<not_specific>
def clone(self, service=None, app=None, app_type=None, tags=None, tracer=None): """Return a clone of the pin with the given attributes replaced.""" # do a shallow copy of Pin dicts if not tags and self.tags: tags = self.tags.copy() # we use a copy instead of a deepcopy becau...
Return a clone of the pin with the given attributes replaced.
Return a clone of the pin with the given attributes replaced.
[ "Return", "a", "clone", "of", "the", "pin", "with", "the", "given", "attributes", "replaced", "." ]
def clone(self, service=None, app=None, app_type=None, tags=None, tracer=None): if not tags and self.tags: tags = self.tags.copy() copy: 0.00654911994934082 deepcopy: 0.2787208557128906 config = self._config.copy() return Pin( service=service or self.ser...
[ "def", "clone", "(", "self", ",", "service", "=", "None", ",", "app", "=", "None", ",", "app_type", "=", "None", ",", "tags", "=", "None", ",", "tracer", "=", "None", ")", ":", "if", "not", "tags", "and", "self", ".", "tags", ":", "tags", "=", ...
Return a clone of the pin with the given attributes replaced.
[ "Return", "a", "clone", "of", "the", "pin", "with", "the", "given", "attributes", "replaced", "." ]
[ "\"\"\"Return a clone of the pin with the given attributes replaced.\"\"\"", "# do a shallow copy of Pin dicts", "# we use a copy instead of a deepcopy because we expect configurations", "# to have only a root level dictionary without nested objects. Using", "# deepcopy introduces a big overhead:", "#", ...
[ { "param": "self", "type": null }, { "param": "service", "type": null }, { "param": "app", "type": null }, { "param": "app_type", "type": null }, { "param": "tags", "type": null }, { "param": "tracer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "service", "type": null, "docstring": null, "docstring_tokens"...
9fe3de6efb9108f190ea74e52f51471b50a2c63d
tophatmonocle/dd-trace-py
ddtrace/utils/reraise.py
[ "BSD-3-Clause" ]
Python
_reraise
null
def _reraise(tp, value, tb=None): """Python 2 re-raise function. This function is internal and will be replaced entirely with the `six` library. """ raise tp, value, tb
Python 2 re-raise function. This function is internal and will be replaced entirely with the `six` library.
Python 2 re-raise function. This function is internal and will be replaced entirely with the `six` library.
[ "Python", "2", "re", "-", "raise", "function", ".", "This", "function", "is", "internal", "and", "will", "be", "replaced", "entirely", "with", "the", "`", "six", "`", "library", "." ]
def _reraise(tp, value, tb=None): raise tp, value, tb
[ "def", "_reraise", "(", "tp", ",", "value", ",", "tb", "=", "None", ")", ":", "raise", "tp", ",", "value", ",", "tb" ]
Python 2 re-raise function.
[ "Python", "2", "re", "-", "raise", "function", "." ]
[ "\"\"\"Python 2 re-raise function. This function is internal and\n will be replaced entirely with the `six` library.\n \"\"\"" ]
[ { "param": "tp", "type": null }, { "param": "value", "type": null }, { "param": "tb", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tp", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "value", "type": null, "docstring": null, "docstring_tokens": []...
5330632cf5efc7429207eff3b8de9b6d14704721
tophatmonocle/dd-trace-py
ddtrace/api.py
[ "BSD-3-Clause" ]
Python
_parse_response_json
<not_specific>
def _parse_response_json(response): """ Parse the content of a response object, and return the right type, can be a string if the output was plain text, or a dictionnary if the output was a JSON. """ if hasattr(response, 'read'): body = response.read() try: if not isi...
Parse the content of a response object, and return the right type, can be a string if the output was plain text, or a dictionnary if the output was a JSON.
Parse the content of a response object, and return the right type, can be a string if the output was plain text, or a dictionnary if the output was a JSON.
[ "Parse", "the", "content", "of", "a", "response", "object", "and", "return", "the", "right", "type", "can", "be", "a", "string", "if", "the", "output", "was", "plain", "text", "or", "a", "dictionnary", "if", "the", "output", "was", "a", "JSON", "." ]
def _parse_response_json(response): if hasattr(response, 'read'): body = response.read() try: if not isinstance(body, str) and hasattr(body, 'decode'): body = body.decode('utf-8') if hasattr(body, 'startswith') and body.startswith('OK'): log.de...
[ "def", "_parse_response_json", "(", "response", ")", ":", "if", "hasattr", "(", "response", ",", "'read'", ")", ":", "body", "=", "response", ".", "read", "(", ")", "try", ":", "if", "not", "isinstance", "(", "body", ",", "str", ")", "and", "hasattr", ...
Parse the content of a response object, and return the right type, can be a string if the output was plain text, or a dictionnary if the output was a JSON.
[ "Parse", "the", "content", "of", "a", "response", "object", "and", "return", "the", "right", "type", "can", "be", "a", "string", "if", "the", "output", "was", "plain", "text", "or", "a", "dictionnary", "if", "the", "output", "was", "a", "JSON", "." ]
[ "\"\"\"\n Parse the content of a response object, and return the right type,\n can be a string if the output was plain text, or a dictionnary if\n the output was a JSON.\n \"\"\"", "# This typically happens when using a priority-sampling enabled", "# library with an outdated agent. It still works, b...
[ { "param": "response", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "response", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b62044d17ce3ba420b23a634eb5fa917e4c1ef6c
tophatmonocle/dd-trace-py
tests/wait-for-services.py
[ "BSD-3-Clause" ]
Python
try_until_timeout
<not_specific>
def try_until_timeout(exception): """Utility decorator that tries to call a check until there is a timeout. The default timeout is about 20 seconds. """ def wrap(fn): err = None def wrapper(*args, **kwargs): for i in range(100): try: fn()...
Utility decorator that tries to call a check until there is a timeout. The default timeout is about 20 seconds.
Utility decorator that tries to call a check until there is a timeout. The default timeout is about 20 seconds.
[ "Utility", "decorator", "that", "tries", "to", "call", "a", "check", "until", "there", "is", "a", "timeout", ".", "The", "default", "timeout", "is", "about", "20", "seconds", "." ]
def try_until_timeout(exception): def wrap(fn): err = None def wrapper(*args, **kwargs): for i in range(100): try: fn() except exception as e: err = e time.sleep(0.2) else: ...
[ "def", "try_until_timeout", "(", "exception", ")", ":", "def", "wrap", "(", "fn", ")", ":", "err", "=", "None", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "for", "i", "in", "range", "(", "100", ")", ":", "try", ":", "fn", ...
Utility decorator that tries to call a check until there is a timeout.
[ "Utility", "decorator", "that", "tries", "to", "call", "a", "check", "until", "there", "is", "a", "timeout", "." ]
[ "\"\"\"Utility decorator that tries to call a check until there is a\n timeout. The default timeout is about 20 seconds.\n\n \"\"\"" ]
[ { "param": "exception", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "exception", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
6653d3d0bd888311b1fd752d73d79f90e4b940f1
tophatmonocle/dd-trace-py
tests/contrib/vertica/utils.py
[ "BSD-3-Clause" ]
Python
override_config
<not_specific>
def override_config(custom_conf): """Overrides the vertica configuration and reinstalls the previous afterwards.""" from ddtrace import config def provide_config(func): def wrapper(*args, **kwargs): orig = deepcopy(config.vertica) merge(config.vertica, custom_conf) ...
Overrides the vertica configuration and reinstalls the previous afterwards.
Overrides the vertica configuration and reinstalls the previous afterwards.
[ "Overrides", "the", "vertica", "configuration", "and", "reinstalls", "the", "previous", "afterwards", "." ]
def override_config(custom_conf): from ddtrace import config def provide_config(func): def wrapper(*args, **kwargs): orig = deepcopy(config.vertica) merge(config.vertica, custom_conf) r = func(*args, **kwargs) config._add("vertica", orig) retur...
[ "def", "override_config", "(", "custom_conf", ")", ":", "from", "ddtrace", "import", "config", "def", "provide_config", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "orig", "=", "deepcopy", "(", "config", ".",...
Overrides the vertica configuration and reinstalls the previous afterwards.
[ "Overrides", "the", "vertica", "configuration", "and", "reinstalls", "the", "previous", "afterwards", "." ]
[ "\"\"\"Overrides the vertica configuration and reinstalls the previous\n afterwards.\"\"\"" ]
[ { "param": "custom_conf", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "custom_conf", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
34619ddf4a77ce8367c67371ece6f447e2754784
tophatmonocle/dd-trace-py
ddtrace/settings.py
[ "BSD-3-Clause" ]
Python
_add
null
def _add(self, integration, settings, merge=True): """Internal API that registers an integration with given default settings. :param str integration: The integration name (i.e. `requests`) :param dict settings: A dictionary that contains integration settings; to preserve imm...
Internal API that registers an integration with given default settings. :param str integration: The integration name (i.e. `requests`) :param dict settings: A dictionary that contains integration settings; to preserve immutability of these values, the dictionary is copied ...
Internal API that registers an integration with given default settings.
[ "Internal", "API", "that", "registers", "an", "integration", "with", "given", "default", "settings", "." ]
def _add(self, integration, settings, merge=True): existing = getattr(self, integration) settings = deepcopy(settings) if merge: >>> config.requests['split_by_domain'] = True >>> config._add('requests', dict(split_by_domain=False)) >>> config.requests['spli...
[ "def", "_add", "(", "self", ",", "integration", ",", "settings", ",", "merge", "=", "True", ")", ":", "existing", "=", "getattr", "(", "self", ",", "integration", ")", "settings", "=", "deepcopy", "(", "settings", ")", "if", "merge", ":", "self", ".", ...
Internal API that registers an integration with given default settings.
[ "Internal", "API", "that", "registers", "an", "integration", "with", "given", "default", "settings", "." ]
[ "\"\"\"Internal API that registers an integration with given default\n settings.\n\n :param str integration: The integration name (i.e. `requests`)\n :param dict settings: A dictionary that contains integration settings;\n to preserve immutability of these values, the dictionary is c...
[ { "param": "self", "type": null }, { "param": "integration", "type": null }, { "param": "settings", "type": null }, { "param": "merge", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "integration", "type": null, "docstring": "The integration name", ...
3a317a788e2e1a09b5cd3db74561e2a33cd66c72
tophatmonocle/dd-trace-py
ddtrace/contrib/tornado/decorators.py
[ "BSD-3-Clause" ]
Python
_finish_span
null
def _finish_span(future): """ Finish the span if it's attached to the given ``Future`` object. This method is a Tornado callback used to close a decorated function executed as a coroutine or as a synchronous function in another thread. """ span = getattr(future, FUTURE_SPAN_KEY, None) if sp...
Finish the span if it's attached to the given ``Future`` object. This method is a Tornado callback used to close a decorated function executed as a coroutine or as a synchronous function in another thread.
Finish the span if it's attached to the given ``Future`` object. This method is a Tornado callback used to close a decorated function executed as a coroutine or as a synchronous function in another thread.
[ "Finish", "the", "span", "if", "it", "'", "s", "attached", "to", "the", "given", "`", "`", "Future", "`", "`", "object", ".", "This", "method", "is", "a", "Tornado", "callback", "used", "to", "close", "a", "decorated", "function", "executed", "as", "a"...
def _finish_span(future): span = getattr(future, FUTURE_SPAN_KEY, None) if span: if callable(getattr(future, 'exc_info', None)): exc_info = future.exc_info() if exc_info: span.set_exc_info(*exc_info) elif callable(getattr(future, 'exception', None)): ...
[ "def", "_finish_span", "(", "future", ")", ":", "span", "=", "getattr", "(", "future", ",", "FUTURE_SPAN_KEY", ",", "None", ")", "if", "span", ":", "if", "callable", "(", "getattr", "(", "future", ",", "'exc_info'", ",", "None", ")", ")", ":", "exc_inf...
Finish the span if it's attached to the given ``Future`` object.
[ "Finish", "the", "span", "if", "it", "'", "s", "attached", "to", "the", "given", "`", "`", "Future", "`", "`", "object", "." ]
[ "\"\"\"\n Finish the span if it's attached to the given ``Future`` object.\n This method is a Tornado callback used to close a decorated function\n executed as a coroutine or as a synchronous function in another thread.\n \"\"\"", "# retrieve the exception from the coroutine object", "# retrieve the...
[ { "param": "future", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "future", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
cfd6230283406fca245dddf87f09d3ca7e419ba9
tophatmonocle/dd-trace-py
ddtrace/contrib/pymongo/parse.py
[ "BSD-3-Clause" ]
Python
parse_msg
<not_specific>
def parse_msg(msg_bytes): """ Return a command from a binary mongo db message or None if we shoudln't trace it. The protocol is documented here: http://docs.mongodb.com/manual/reference/mongodb-wire-protocol """ # NOTE[matt] this is used for queries in pymongo <= 3.0.0 and for inserts # ...
Return a command from a binary mongo db message or None if we shoudln't trace it. The protocol is documented here: http://docs.mongodb.com/manual/reference/mongodb-wire-protocol
Return a command from a binary mongo db message or None if we shoudln't trace it.
[ "Return", "a", "command", "from", "a", "binary", "mongo", "db", "message", "or", "None", "if", "we", "shoudln", "'", "t", "trace", "it", "." ]
def parse_msg(msg_bytes): msg_len = len(msg_bytes) if msg_len <= 0: return None header = header_struct.unpack_from(msg_bytes, 0) (length, req_id, response_to, op_code) = header op = OP_CODES.get(op_code) if not op: log.debug("unknown op code: %s", op_code) return None ...
[ "def", "parse_msg", "(", "msg_bytes", ")", ":", "msg_len", "=", "len", "(", "msg_bytes", ")", "if", "msg_len", "<=", "0", ":", "return", "None", "header", "=", "header_struct", ".", "unpack_from", "(", "msg_bytes", ",", "0", ")", "(", "length", ",", "r...
Return a command from a binary mongo db message or None if we shoudln't trace it.
[ "Return", "a", "command", "from", "a", "binary", "mongo", "db", "message", "or", "None", "if", "we", "shoudln", "'", "t", "trace", "it", "." ]
[ "\"\"\" Return a command from a binary mongo db message or None if we shoudln't\n trace it. The protocol is documented here:\n http://docs.mongodb.com/manual/reference/mongodb-wire-protocol\n \"\"\"", "# NOTE[matt] this is used for queries in pymongo <= 3.0.0 and for inserts", "# in up to date ...
[ { "param": "msg_bytes", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "msg_bytes", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
cfd6230283406fca245dddf87f09d3ca7e419ba9
tophatmonocle/dd-trace-py
ddtrace/contrib/pymongo/parse.py
[ "BSD-3-Clause" ]
Python
parse_query
<not_specific>
def parse_query(query): """ Return a command parsed from the given mongo db query. """ db, coll = None, None ns = getattr(query, "ns", None) if ns: # version < 3.1 stores the full namespace db, coll = _split_namespace(ns) else: # version >= 3.1 stores the db and coll seperate...
Return a command parsed from the given mongo db query.
Return a command parsed from the given mongo db query.
[ "Return", "a", "command", "parsed", "from", "the", "given", "mongo", "db", "query", "." ]
def parse_query(query): db, coll = None, None ns = getattr(query, "ns", None) if ns: db, coll = _split_namespace(ns) else: coll = getattr(query, "coll", None) db = getattr(query, "db", None) cmd = Command("query", db, coll) cmd.query = query.spec return cmd
[ "def", "parse_query", "(", "query", ")", ":", "db", ",", "coll", "=", "None", ",", "None", "ns", "=", "getattr", "(", "query", ",", "\"ns\"", ",", "None", ")", "if", "ns", ":", "db", ",", "coll", "=", "_split_namespace", "(", "ns", ")", "else", "...
Return a command parsed from the given mongo db query.
[ "Return", "a", "command", "parsed", "from", "the", "given", "mongo", "db", "query", "." ]
[ "\"\"\" Return a command parsed from the given mongo db query. \"\"\"", "# version < 3.1 stores the full namespace", "# version >= 3.1 stores the db and coll seperately", "# FIXME[matt] mongo < 3.1 _Query doesn't not have a name field,", "# so hardcode to query." ]
[ { "param": "query", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "query", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
cfd6230283406fca245dddf87f09d3ca7e419ba9
tophatmonocle/dd-trace-py
ddtrace/contrib/pymongo/parse.py
[ "BSD-3-Clause" ]
Python
parse_spec
<not_specific>
def parse_spec(spec, db=None): """ Return a Command that has parsed the relevant detail for the given pymongo SON spec. """ # the first element is the command and collection items = list(spec.items()) if not items: return None name, coll = items[0] cmd = Command(name, db, co...
Return a Command that has parsed the relevant detail for the given pymongo SON spec.
Return a Command that has parsed the relevant detail for the given pymongo SON spec.
[ "Return", "a", "Command", "that", "has", "parsed", "the", "relevant", "detail", "for", "the", "given", "pymongo", "SON", "spec", "." ]
def parse_spec(spec, db=None): items = list(spec.items()) if not items: return None name, coll = items[0] cmd = Command(name, db, coll) if 'ordered' in spec: cmd.tags['mongodb.ordered'] = spec['ordered'] if cmd.name == 'insert': if 'documents' in spec: cmd.me...
[ "def", "parse_spec", "(", "spec", ",", "db", "=", "None", ")", ":", "items", "=", "list", "(", "spec", ".", "items", "(", ")", ")", "if", "not", "items", ":", "return", "None", "name", ",", "coll", "=", "items", "[", "0", "]", "cmd", "=", "Comm...
Return a Command that has parsed the relevant detail for the given pymongo SON spec.
[ "Return", "a", "Command", "that", "has", "parsed", "the", "relevant", "detail", "for", "the", "given", "pymongo", "SON", "spec", "." ]
[ "\"\"\" Return a Command that has parsed the relevant detail for the given\n pymongo SON spec.\n \"\"\"", "# the first element is the command and collection", "# in insert and update", "# FIXME[matt] is there ever more than one here?", "# FIXME[matt] is there ever more than one here?" ]
[ { "param": "spec", "type": null }, { "param": "db", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "spec", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "db", "type": null, "docstring": null, "docstring_tokens": [],...
1966f05c59c68404d2c3becc77aa7aa9bca12e09
tophatmonocle/dd-trace-py
ddtrace/contrib/django/utils.py
[ "BSD-3-Clause" ]
Python
_resource_from_cache_prefix
<not_specific>
def _resource_from_cache_prefix(resource, cache): """ Combine the resource name with the cache prefix (if any) """ if getattr(cache, "key_prefix", None): name = "{} {}".format(resource, cache.key_prefix) else: name = resource # enforce lowercase to make the output nicer to read ...
Combine the resource name with the cache prefix (if any)
Combine the resource name with the cache prefix (if any)
[ "Combine", "the", "resource", "name", "with", "the", "cache", "prefix", "(", "if", "any", ")" ]
def _resource_from_cache_prefix(resource, cache): if getattr(cache, "key_prefix", None): name = "{} {}".format(resource, cache.key_prefix) else: name = resource return name.lower()
[ "def", "_resource_from_cache_prefix", "(", "resource", ",", "cache", ")", ":", "if", "getattr", "(", "cache", ",", "\"key_prefix\"", ",", "None", ")", ":", "name", "=", "\"{} {}\"", ".", "format", "(", "resource", ",", "cache", ".", "key_prefix", ")", "els...
Combine the resource name with the cache prefix (if any)
[ "Combine", "the", "resource", "name", "with", "the", "cache", "prefix", "(", "if", "any", ")" ]
[ "\"\"\"\n Combine the resource name with the cache prefix (if any)\n \"\"\"", "# enforce lowercase to make the output nicer to read" ]
[ { "param": "resource", "type": null }, { "param": "cache", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "resource", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "cache", "type": null, "docstring": null, "docstring_token...
7d8be42c9213ca7f8051cc8fa395d0cf37557e8f
tophatmonocle/dd-trace-py
ddtrace/compat_async.py
[ "BSD-3-Clause" ]
Python
_make_async_decorator
<not_specific>
def _make_async_decorator(tracer, coro, *params, **kw_params): """ Decorator factory that creates an asynchronous wrapper that yields a coroutine result. This factory is required to handle Python 2 compatibilities. :param object tracer: the tracer instance that is used :param function f: the co...
Decorator factory that creates an asynchronous wrapper that yields a coroutine result. This factory is required to handle Python 2 compatibilities. :param object tracer: the tracer instance that is used :param function f: the coroutine that must be executed :param tuple params: arguments given...
Decorator factory that creates an asynchronous wrapper that yields a coroutine result. This factory is required to handle Python 2 compatibilities.
[ "Decorator", "factory", "that", "creates", "an", "asynchronous", "wrapper", "that", "yields", "a", "coroutine", "result", ".", "This", "factory", "is", "required", "to", "handle", "Python", "2", "compatibilities", "." ]
def _make_async_decorator(tracer, coro, *params, **kw_params): @functools.wraps(coro) @asyncio.coroutine def func_wrapper(*args, **kwargs): with tracer.trace(*params, **kw_params): result = yield from coro(*args, **kwargs) return result return func_wrapper
[ "def", "_make_async_decorator", "(", "tracer", ",", "coro", ",", "*", "params", ",", "**", "kw_params", ")", ":", "@", "functools", ".", "wraps", "(", "coro", ")", "@", "asyncio", ".", "coroutine", "def", "func_wrapper", "(", "*", "args", ",", "**", "k...
Decorator factory that creates an asynchronous wrapper that yields a coroutine result.
[ "Decorator", "factory", "that", "creates", "an", "asynchronous", "wrapper", "that", "yields", "a", "coroutine", "result", "." ]
[ "\"\"\"\n Decorator factory that creates an asynchronous wrapper that yields\n a coroutine result. This factory is required to handle Python 2\n compatibilities.\n\n :param object tracer: the tracer instance that is used\n :param function f: the coroutine that must be executed\n :param tuple param...
[ { "param": "tracer", "type": null }, { "param": "coro", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "tracer", "type": null, "docstring": "the tracer instance that is used", "docstring_tokens": [ "the", "tracer", "instance", "that", "is", "used" ], "default": null, ...
4e6a2d7f757bb19ffef1cda73b656394f685d424
tophatmonocle/dd-trace-py
ddtrace/contrib/celery/utils.py
[ "BSD-3-Clause" ]
Python
attach_span
null
def attach_span(task, task_id, span): """Helper to propagate a `Span` for the given `Task` instance. This function uses a `WeakValueDictionary` that stores a Datadog Span using the `task_id` as a key. This is useful when information must be propagated from one Celery signal to another. """ weak_...
Helper to propagate a `Span` for the given `Task` instance. This function uses a `WeakValueDictionary` that stores a Datadog Span using the `task_id` as a key. This is useful when information must be propagated from one Celery signal to another.
Helper to propagate a `Span` for the given `Task` instance. This function uses a `WeakValueDictionary` that stores a Datadog Span using the `task_id` as a key. This is useful when information must be propagated from one Celery signal to another.
[ "Helper", "to", "propagate", "a", "`", "Span", "`", "for", "the", "given", "`", "Task", "`", "instance", ".", "This", "function", "uses", "a", "`", "WeakValueDictionary", "`", "that", "stores", "a", "Datadog", "Span", "using", "the", "`", "task_id", "`",...
def attach_span(task, task_id, span): weak_dict = getattr(task, CTX_KEY, None) if weak_dict is None: weak_dict = WeakValueDictionary() setattr(task, CTX_KEY, weak_dict) weak_dict[task_id] = span
[ "def", "attach_span", "(", "task", ",", "task_id", ",", "span", ")", ":", "weak_dict", "=", "getattr", "(", "task", ",", "CTX_KEY", ",", "None", ")", "if", "weak_dict", "is", "None", ":", "weak_dict", "=", "WeakValueDictionary", "(", ")", "setattr", "(",...
Helper to propagate a `Span` for the given `Task` instance.
[ "Helper", "to", "propagate", "a", "`", "Span", "`", "for", "the", "given", "`", "Task", "`", "instance", "." ]
[ "\"\"\"Helper to propagate a `Span` for the given `Task` instance. This\n function uses a `WeakValueDictionary` that stores a Datadog Span using\n the `task_id` as a key. This is useful when information must be\n propagated from one Celery signal to another.\n \"\"\"" ]
[ { "param": "task", "type": null }, { "param": "task_id", "type": null }, { "param": "span", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "task", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "task_id", "type": null, "docstring": null, "docstring_tokens"...
4e6a2d7f757bb19ffef1cda73b656394f685d424
tophatmonocle/dd-trace-py
ddtrace/contrib/celery/utils.py
[ "BSD-3-Clause" ]
Python
detach_span
<not_specific>
def detach_span(task, task_id): """Helper to remove a `Span` in a Celery task when it's propagated. This function handles tasks where the `Span` is not attached. """ weak_dict = getattr(task, CTX_KEY, None) if weak_dict is None: return weak_dict.pop(task_id, None)
Helper to remove a `Span` in a Celery task when it's propagated. This function handles tasks where the `Span` is not attached.
Helper to remove a `Span` in a Celery task when it's propagated. This function handles tasks where the `Span` is not attached.
[ "Helper", "to", "remove", "a", "`", "Span", "`", "in", "a", "Celery", "task", "when", "it", "'", "s", "propagated", ".", "This", "function", "handles", "tasks", "where", "the", "`", "Span", "`", "is", "not", "attached", "." ]
def detach_span(task, task_id): weak_dict = getattr(task, CTX_KEY, None) if weak_dict is None: return weak_dict.pop(task_id, None)
[ "def", "detach_span", "(", "task", ",", "task_id", ")", ":", "weak_dict", "=", "getattr", "(", "task", ",", "CTX_KEY", ",", "None", ")", "if", "weak_dict", "is", "None", ":", "return", "weak_dict", ".", "pop", "(", "task_id", ",", "None", ")" ]
Helper to remove a `Span` in a Celery task when it's propagated.
[ "Helper", "to", "remove", "a", "`", "Span", "`", "in", "a", "Celery", "task", "when", "it", "'", "s", "propagated", "." ]
[ "\"\"\"Helper to remove a `Span` in a Celery task when it's propagated.\n This function handles tasks where the `Span` is not attached.\n \"\"\"" ]
[ { "param": "task", "type": null }, { "param": "task_id", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "task", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "task_id", "type": null, "docstring": null, "docstring_tokens"...
4e6a2d7f757bb19ffef1cda73b656394f685d424
tophatmonocle/dd-trace-py
ddtrace/contrib/celery/utils.py
[ "BSD-3-Clause" ]
Python
retrieve_span
<not_specific>
def retrieve_span(task, task_id): """Helper to retrieve an active `Span` stored in a `Task` instance """ weak_dict = getattr(task, CTX_KEY, None) if weak_dict is None: return else: return weak_dict.get(task_id)
Helper to retrieve an active `Span` stored in a `Task` instance
Helper to retrieve an active `Span` stored in a `Task` instance
[ "Helper", "to", "retrieve", "an", "active", "`", "Span", "`", "stored", "in", "a", "`", "Task", "`", "instance" ]
def retrieve_span(task, task_id): weak_dict = getattr(task, CTX_KEY, None) if weak_dict is None: return else: return weak_dict.get(task_id)
[ "def", "retrieve_span", "(", "task", ",", "task_id", ")", ":", "weak_dict", "=", "getattr", "(", "task", ",", "CTX_KEY", ",", "None", ")", "if", "weak_dict", "is", "None", ":", "return", "else", ":", "return", "weak_dict", ".", "get", "(", "task_id", "...
Helper to retrieve an active `Span` stored in a `Task` instance
[ "Helper", "to", "retrieve", "an", "active", "`", "Span", "`", "stored", "in", "a", "`", "Task", "`", "instance" ]
[ "\"\"\"Helper to retrieve an active `Span` stored in a `Task`\n instance\n \"\"\"" ]
[ { "param": "task", "type": null }, { "param": "task_id", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "task", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "task_id", "type": null, "docstring": null, "docstring_tokens"...
94e3d9a7693cce43689e41b79068c3a23b042eae
tophatmonocle/dd-trace-py
ddtrace/contrib/tornado/handlers.py
[ "BSD-3-Clause" ]
Python
execute
<not_specific>
def execute(func, handler, args, kwargs): """ Wrap the handler execute method so that the entire request is within the same ``TracerStackContext``. This simplifies users code when the automatic ``Context`` retrieval is used via ``Tracer.trace()`` method. """ # retrieve tracing settings setti...
Wrap the handler execute method so that the entire request is within the same ``TracerStackContext``. This simplifies users code when the automatic ``Context`` retrieval is used via ``Tracer.trace()`` method.
Wrap the handler execute method so that the entire request is within the same ``TracerStackContext``.
[ "Wrap", "the", "handler", "execute", "method", "so", "that", "the", "entire", "request", "is", "within", "the", "same", "`", "`", "TracerStackContext", "`", "`", "." ]
def execute(func, handler, args, kwargs): settings = handler.settings[CONFIG_KEY] tracer = settings['tracer'] service = settings['default_service'] distributed_tracing = settings['distributed_tracing'] with TracerStackContext(): setattr(handler.request, REQUEST_CONTEXT_KEY, tracer.get_call_c...
[ "def", "execute", "(", "func", ",", "handler", ",", "args", ",", "kwargs", ")", ":", "settings", "=", "handler", ".", "settings", "[", "CONFIG_KEY", "]", "tracer", "=", "settings", "[", "'tracer'", "]", "service", "=", "settings", "[", "'default_service'",...
Wrap the handler execute method so that the entire request is within the same ``TracerStackContext``.
[ "Wrap", "the", "handler", "execute", "method", "so", "that", "the", "entire", "request", "is", "within", "the", "same", "`", "`", "TracerStackContext", "`", "`", "." ]
[ "\"\"\"\n Wrap the handler execute method so that the entire request is within the same\n ``TracerStackContext``. This simplifies users code when the automatic ``Context``\n retrieval is used via ``Tracer.trace()`` method.\n \"\"\"", "# retrieve tracing settings", "# attach the context to the reques...
[ { "param": "func", "type": null }, { "param": "handler", "type": null }, { "param": "args", "type": null }, { "param": "kwargs", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "func", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "handler", "type": null, "docstring": null, "docstring_tokens"...
34855164b29bf75463e4289caf59208af1f35739
tophatmonocle/dd-trace-py
ddtrace/contrib/flask_cache/tracers.py
[ "BSD-3-Clause" ]
Python
__trace
<not_specific>
def __trace(self, cmd): """ Start a tracing with default attributes and tags """ # create a new span s = self._datadog_tracer.trace( cmd, span_type=TYPE, service=self._datadog_service ) # ...
Start a tracing with default attributes and tags
Start a tracing with default attributes and tags
[ "Start", "a", "tracing", "with", "default", "attributes", "and", "tags" ]
def __trace(self, cmd): s = self._datadog_tracer.trace( cmd, span_type=TYPE, service=self._datadog_service ) s.set_tag(CACHE_BACKEND, self.config.get("CACHE_TYPE")) s.set_tags(self._datadog_meta) if getattr(self....
[ "def", "__trace", "(", "self", ",", "cmd", ")", ":", "s", "=", "self", ".", "_datadog_tracer", ".", "trace", "(", "cmd", ",", "span_type", "=", "TYPE", ",", "service", "=", "self", ".", "_datadog_service", ")", "s", ".", "set_tag", "(", "CACHE_BACKEND"...
Start a tracing with default attributes and tags
[ "Start", "a", "tracing", "with", "default", "attributes", "and", "tags" ]
[ "\"\"\"\n Start a tracing with default attributes and tags\n \"\"\"", "# create a new span", "# set span tags", "# add connection meta if there is one" ]
[ { "param": "self", "type": null }, { "param": "cmd", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "cmd", "type": null, "docstring": null, "docstring_tokens": []...
e8df0dcaae05c89a2533f9ec75180cf7df2dabd7
RazanGhzouli/Behavior-Trees-in-Action
scripts/rawdata/pytreeros/smarc-project_smarc_missions_reactive_seq.py
[ "MIT" ]
Python
tick
<not_specific>
def tick(self): """ Run the tick behaviour for this selector. Note that the status of the tick is always determined by its children, not by the user customised update function. Yields: :class:`~py_trees.behaviour.Behaviour`: a reference to itself or one of its childr...
Run the tick behaviour for this selector. Note that the status of the tick is always determined by its children, not by the user customised update function. Yields: :class:`~py_trees.behaviour.Behaviour`: a reference to itself or one of its children
Run the tick behaviour for this selector. Note that the status of the tick is always determined by its children, not by the user customised update function.
[ "Run", "the", "tick", "behaviour", "for", "this", "selector", ".", "Note", "that", "the", "status", "of", "the", "tick", "is", "always", "determined", "by", "its", "children", "not", "by", "the", "user", "customised", "update", "function", "." ]
def tick(self): self.logger.debug("%s.tick()" % self.__class__.__name__) if self.status != pt.Status.RUNNING: self.initialise() self.update() previous = self.current_child for child in self.children: for node in child.tick(): yield node ...
[ "def", "tick", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"%s.tick()\"", "%", "self", ".", "__class__", ".", "__name__", ")", "if", "self", ".", "status", "!=", "pt", ".", "Status", ".", "RUNNING", ":", "self", ".", "initialis...
Run the tick behaviour for this selector.
[ "Run", "the", "tick", "behaviour", "for", "this", "selector", "." ]
[ "\"\"\"\n Run the tick behaviour for this selector. Note that the status\n of the tick is always determined by its children, not\n by the user customised update function.\n\n Yields:\n :class:`~py_trees.behaviour.Behaviour`: a reference to itself or one of its children\n ...
[ { "param": "self", "type": null } ]
{ "returns": [ { "docstring": ":class:`~py_trees.behaviour.Behaviour`: a reference to itself or one of its children", "docstring_tokens": [ ":", "class", ":", "`", "~py_trees", ".", "behaviour", ".", "Behaviour", "`", ...
e8df0dcaae05c89a2533f9ec75180cf7df2dabd7
RazanGhzouli/Behavior-Trees-in-Action
scripts/rawdata/pytreeros/smarc-project_smarc_missions_reactive_seq.py
[ "MIT" ]
Python
stop
null
def stop(self, new_status=pt.Status.INVALID): """ Stopping a selector requires setting the current child to none. Note that it is important to implement this here instead of terminate, so users are free to subclass this easily with their own terminate and not have to remember tha...
Stopping a selector requires setting the current child to none. Note that it is important to implement this here instead of terminate, so users are free to subclass this easily with their own terminate and not have to remember that they need to call this function manually. Args...
Stopping a selector requires setting the current child to none. Note that it is important to implement this here instead of terminate, so users are free to subclass this easily with their own terminate and not have to remember that they need to call this function manually.
[ "Stopping", "a", "selector", "requires", "setting", "the", "current", "child", "to", "none", ".", "Note", "that", "it", "is", "important", "to", "implement", "this", "here", "instead", "of", "terminate", "so", "users", "are", "free", "to", "subclass", "this"...
def stop(self, new_status=pt.Status.INVALID): if new_status == pt.Status.INVALID: self.current_child = None pt.Composite.stop(self, new_status)
[ "def", "stop", "(", "self", ",", "new_status", "=", "pt", ".", "Status", ".", "INVALID", ")", ":", "if", "new_status", "==", "pt", ".", "Status", ".", "INVALID", ":", "self", ".", "current_child", "=", "None", "pt", ".", "Composite", ".", "stop", "("...
Stopping a selector requires setting the current child to none.
[ "Stopping", "a", "selector", "requires", "setting", "the", "current", "child", "to", "none", "." ]
[ "\"\"\"\n Stopping a selector requires setting the current child to none. Note that it\n is important to implement this here instead of terminate, so users are free\n to subclass this easily with their own terminate and not have to remember\n that they need to call this function manually...
[ { "param": "self", "type": null }, { "param": "new_status", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "new_status", "type": null, "docstring": null, "docstring_toke...
8e438b1d58fe2ff8a8e775dfed5e78674e509e92
RazanGhzouli/Behavior-Trees-in-Action
scripts/notebooks/test.py
[ "MIT" ]
Python
testAccessTokenErrorCatch
null
def testAccessTokenErrorCatch(self, mock_stdout): """ Test access token function catch error with token value """ access_token = BT_mining_script_for_testing.access_token ## fake access token data = ['12345678932165498774185296332145987555'] expected_outp...
Test access token function catch error with token value
Test access token function catch error with token value
[ "Test", "access", "token", "function", "catch", "error", "with", "token", "value" ]
def testAccessTokenErrorCatch(self, mock_stdout): access_token = BT_mining_script_for_testing.access_token data = ['12345678932165498774185296332145987555'] expected_output = "Please provide a working access token\n" access_token(data[0]) self.assertEqual(mock_stdout...
[ "def", "testAccessTokenErrorCatch", "(", "self", ",", "mock_stdout", ")", ":", "access_token", "=", "BT_mining_script_for_testing", ".", "access_token", "data", "=", "[", "'12345678932165498774185296332145987555'", "]", "expected_output", "=", "\"Please provide a working acce...
Test access token function catch error with token value
[ "Test", "access", "token", "function", "catch", "error", "with", "token", "value" ]
[ "\"\"\"\n Test access token function catch error with token value\n \"\"\"", "## fake access token" ]
[ { "param": "self", "type": null }, { "param": "mock_stdout", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mock_stdout", "type": null, "docstring": null, "docstring_tok...
8e438b1d58fe2ff8a8e775dfed5e78674e509e92
RazanGhzouli/Behavior-Trees-in-Action
scripts/notebooks/test.py
[ "MIT" ]
Python
testQueryGithubInput
null
def testQueryGithubInput(self, input): """ Test query function catch entered input """ query_github = BT_mining_script_for_testing.query_github g = Github(self.data) self.assertIsNotNone( query_github(g), "input wasn't catched...
Test query function catch entered input
Test query function catch entered input
[ "Test", "query", "function", "catch", "entered", "input" ]
def testQueryGithubInput(self, input): query_github = BT_mining_script_for_testing.query_github g = Github(self.data) self.assertIsNotNone( query_github(g), "input wasn't catched by function")
[ "def", "testQueryGithubInput", "(", "self", ",", "input", ")", ":", "query_github", "=", "BT_mining_script_for_testing", ".", "query_github", "g", "=", "Github", "(", "self", ".", "data", ")", "self", ".", "assertIsNotNone", "(", "query_github", "(", "g", ")",...
Test query function catch entered input
[ "Test", "query", "function", "catch", "entered", "input" ]
[ "\"\"\"\n Test query function catch entered input\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "input", "type": null, "docstring": null, "docstring_tokens": ...
8e438b1d58fe2ff8a8e775dfed5e78674e509e92
RazanGhzouli/Behavior-Trees-in-Action
scripts/notebooks/test.py
[ "MIT" ]
Python
testNumberReturnedFiles
null
def testNumberReturnedFiles (self, mock_stdout): """ Test query function return specific number of files """ query_github = BT_mining_script_for_testing.query_github g = Github(self.data) expected_output = "Found 254 file(s)\n" qu...
Test query function return specific number of files
Test query function return specific number of files
[ "Test", "query", "function", "return", "specific", "number", "of", "files" ]
def testNumberReturnedFiles (self, mock_stdout): query_github = BT_mining_script_for_testing.query_github g = Github(self.data) expected_output = "Found 254 file(s)\n" query_github(g ,keywords = "py_trees_ros") self.assertEqual(mock_stdout.getvalue(), expected_output, "Number of ...
[ "def", "testNumberReturnedFiles", "(", "self", ",", "mock_stdout", ")", ":", "query_github", "=", "BT_mining_script_for_testing", ".", "query_github", "g", "=", "Github", "(", "self", ".", "data", ")", "expected_output", "=", "\"Found 254 file(s)\\n\"", "query_github"...
Test query function return specific number of files
[ "Test", "query", "function", "return", "specific", "number", "of", "files" ]
[ "\"\"\"\n Test query function return specific number of files\n \n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "mock_stdout", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mock_stdout", "type": null, "docstring": null, "docstring_tok...
8e438b1d58fe2ff8a8e775dfed5e78674e509e92
RazanGhzouli/Behavior-Trees-in-Action
scripts/notebooks/test.py
[ "MIT" ]
Python
testFileWriting
null
def testFileWriting(self): """ Test extract_url_repo_name function return non-empty dictionary of URL and repo names """ query_github = BT_mining_script_for_testing.query_github extract_url_repo_name = BT_mining_script_for_testing.extract_url_repo_name g ...
Test extract_url_repo_name function return non-empty dictionary of URL and repo names
Test extract_url_repo_name function return non-empty dictionary of URL and repo names
[ "Test", "extract_url_repo_name", "function", "return", "non", "-", "empty", "dictionary", "of", "URL", "and", "repo", "names" ]
def testFileWriting(self): query_github = BT_mining_script_for_testing.query_github extract_url_repo_name = BT_mining_script_for_testing.extract_url_repo_name g = Github(self.data) result = query_github(g ,keywords = "py_trees_ros") self.assertTrue(extract_url_repo_name(result),"...
[ "def", "testFileWriting", "(", "self", ")", ":", "query_github", "=", "BT_mining_script_for_testing", ".", "query_github", "extract_url_repo_name", "=", "BT_mining_script_for_testing", ".", "extract_url_repo_name", "g", "=", "Github", "(", "self", ".", "data", ")", "r...
Test extract_url_repo_name function return non-empty dictionary of URL and repo names
[ "Test", "extract_url_repo_name", "function", "return", "non", "-", "empty", "dictionary", "of", "URL", "and", "repo", "names" ]
[ "\"\"\"\n Test extract_url_repo_name function return non-empty dictionary of URL and repo names\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8e438b1d58fe2ff8a8e775dfed5e78674e509e92
RazanGhzouli/Behavior-Trees-in-Action
scripts/notebooks/test.py
[ "MIT" ]
Python
testSlicedResultSize
null
def testSlicedResultSize(self): """ Test limit_result_size function return the desired result size """ query_github = BT_mining_script_for_testing.query_github limit_result_size = BT_mining_script_for_testing.limit_result_size desired_size = 10 g =...
Test limit_result_size function return the desired result size
Test limit_result_size function return the desired result size
[ "Test", "limit_result_size", "function", "return", "the", "desired", "result", "size" ]
def testSlicedResultSize(self): query_github = BT_mining_script_for_testing.query_github limit_result_size = BT_mining_script_for_testing.limit_result_size desired_size = 10 g = Github(self.data) result = query_github(g ,keywords = "py_trees_ros") self.assertEqual(len(lis...
[ "def", "testSlicedResultSize", "(", "self", ")", ":", "query_github", "=", "BT_mining_script_for_testing", ".", "query_github", "limit_result_size", "=", "BT_mining_script_for_testing", ".", "limit_result_size", "desired_size", "=", "10", "g", "=", "Github", "(", "self"...
Test limit_result_size function return the desired result size
[ "Test", "limit_result_size", "function", "return", "the", "desired", "result", "size" ]
[ "\"\"\"\n Test limit_result_size function return the desired result size\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8e438b1d58fe2ff8a8e775dfed5e78674e509e92
RazanGhzouli/Behavior-Trees-in-Action
scripts/notebooks/test.py
[ "MIT" ]
Python
testLimitSizeReturnedValue
null
def testLimitSizeReturnedValue(self): """ Test limit_result_size function does return results """ query_github = BT_mining_script_for_testing.query_github limit_result_size = BT_mining_script_for_testing.limit_result_size desired_size = 10 g = Gith...
Test limit_result_size function does return results
Test limit_result_size function does return results
[ "Test", "limit_result_size", "function", "does", "return", "results" ]
def testLimitSizeReturnedValue(self): query_github = BT_mining_script_for_testing.query_github limit_result_size = BT_mining_script_for_testing.limit_result_size desired_size = 10 g = Github(self.data) result = query_github(g ,keywords = "py_trees_ros") self.assertTrue(li...
[ "def", "testLimitSizeReturnedValue", "(", "self", ")", ":", "query_github", "=", "BT_mining_script_for_testing", ".", "query_github", "limit_result_size", "=", "BT_mining_script_for_testing", ".", "limit_result_size", "desired_size", "=", "10", "g", "=", "Github", "(", ...
Test limit_result_size function does return results
[ "Test", "limit_result_size", "function", "does", "return", "results" ]
[ "\"\"\"\n Test limit_result_size function does return results\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8e438b1d58fe2ff8a8e775dfed5e78674e509e92
RazanGhzouli/Behavior-Trees-in-Action
scripts/notebooks/test.py
[ "MIT" ]
Python
testSaveDictionary
null
def testSaveDictionary (self, mock_stdout): """ Test extract_url_repo_name save dictionary with repo and url names """ query_github = BT_mining_script_for_testing.query_github limit_result_size = BT_mining_script_for_testing.limit_result_size extract_url_repo_nam...
Test extract_url_repo_name save dictionary with repo and url names
Test extract_url_repo_name save dictionary with repo and url names
[ "Test", "extract_url_repo_name", "save", "dictionary", "with", "repo", "and", "url", "names" ]
def testSaveDictionary (self, mock_stdout): query_github = BT_mining_script_for_testing.query_github limit_result_size = BT_mining_script_for_testing.limit_result_size extract_url_repo_name = BT_mining_script_for_testing.extract_url_repo_name desired_size = 2 g = Github(self.data...
[ "def", "testSaveDictionary", "(", "self", ",", "mock_stdout", ")", ":", "query_github", "=", "BT_mining_script_for_testing", ".", "query_github", "limit_result_size", "=", "BT_mining_script_for_testing", ".", "limit_result_size", "extract_url_repo_name", "=", "BT_mining_scrip...
Test extract_url_repo_name save dictionary with repo and url names
[ "Test", "extract_url_repo_name", "save", "dictionary", "with", "repo", "and", "url", "names" ]
[ "\"\"\"\n Test extract_url_repo_name save dictionary with repo and url names\n \n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "mock_stdout", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mock_stdout", "type": null, "docstring": null, "docstring_tok...
8e438b1d58fe2ff8a8e775dfed5e78674e509e92
RazanGhzouli/Behavior-Trees-in-Action
scripts/notebooks/test.py
[ "MIT" ]
Python
testNumberRepo
null
def testNumberRepo (self, mock_stdout): """ Test extract_url_repo_name find specific number of repo """ query_github = BT_mining_script_for_testing.query_github limit_result_size = BT_mining_script_for_testing.limit_result_size extract_url_repo_name = BT_mining_s...
Test extract_url_repo_name find specific number of repo
Test extract_url_repo_name find specific number of repo
[ "Test", "extract_url_repo_name", "find", "specific", "number", "of", "repo" ]
def testNumberRepo (self, mock_stdout): query_github = BT_mining_script_for_testing.query_github limit_result_size = BT_mining_script_for_testing.limit_result_size extract_url_repo_name = BT_mining_script_for_testing.extract_url_repo_name desired_size = 2 g = Github(self.data) ...
[ "def", "testNumberRepo", "(", "self", ",", "mock_stdout", ")", ":", "query_github", "=", "BT_mining_script_for_testing", ".", "query_github", "limit_result_size", "=", "BT_mining_script_for_testing", ".", "limit_result_size", "extract_url_repo_name", "=", "BT_mining_script_fo...
Test extract_url_repo_name find specific number of repo
[ "Test", "extract_url_repo_name", "find", "specific", "number", "of", "repo" ]
[ "\"\"\"\n Test extract_url_repo_name find specific number of repo\n \n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "mock_stdout", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "mock_stdout", "type": null, "docstring": null, "docstring_tok...
f08499649550c0ba0004a3f3d8fca65eba0a8992
RazanGhzouli/Behavior-Trees-in-Action
scripts/rawdata/pytreeros/smarc-project_smarc_missions_sam_execute_mission.py
[ "MIT" ]
Python
execute
<not_specific>
def execute(self, goal): # We override """ Check for pre-emption, but otherwise just spin around gradually incrementing a hypothetical 'percent' done. Args: goal (:obj:`any`): goal of type specified by the action_type in the constructor. """ #if self....
Check for pre-emption, but otherwise just spin around gradually incrementing a hypothetical 'percent' done. Args: goal (:obj:`any`): goal of type specified by the action_type in the constructor.
Check for pre-emption, but otherwise just spin around gradually incrementing a hypothetical 'percent' done.
[ "Check", "for", "pre", "-", "emption", "but", "otherwise", "just", "spin", "around", "gradually", "incrementing", "a", "hypothetical", "'", "percent", "'", "done", "." ]
def execute(self, goal): frequency = 3.0 increment = 100 / (frequency * self.parameters.duration) self.percent_completed = 0 rate = rospy.Rate(frequency) goal = eval(goal.bt_action_goal) rospy.loginfo("{title}: received a goal:{goal}".format(title=self.title, goal=str...
[ "def", "execute", "(", "self", ",", "goal", ")", ":", "frequency", "=", "3.0", "increment", "=", "100", "/", "(", "frequency", "*", "self", ".", "parameters", ".", "duration", ")", "self", ".", "percent_completed", "=", "0", "rate", "=", "rospy", ".", ...
Check for pre-emption, but otherwise just spin around gradually incrementing a hypothetical 'percent' done.
[ "Check", "for", "pre", "-", "emption", "but", "otherwise", "just", "spin", "around", "gradually", "incrementing", "a", "hypothetical", "'", "percent", "'", "done", "." ]
[ "# We override", "\"\"\"\n Check for pre-emption, but otherwise just spin around gradually incrementing\n a hypothetical 'percent' done.\n\n Args:\n goal (:obj:`any`): goal of type specified by the action_type in the constructor.\n \"\"\"", "#if self.goal_received_callback...
[ { "param": "self", "type": null }, { "param": "goal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "goal", "type": null, "docstring": null, "docstring_tokens": [...
ef3da0367e0ebe304faf84753893a929d2c89cfb
RazanGhzouli/Behavior-Trees-in-Action
scripts/rawdata/pytreeros/smarc-project_smarc_missions_sam_emergency.py
[ "MIT" ]
Python
execute
null
def execute(self, goal): # We override """ Check for pre-emption, but otherwise just spin around gradually incrementing a hypothetical 'percent' done. Args: goal (:obj:`any`): goal of type specified by the action_type in the constructor. """ #if self....
Check for pre-emption, but otherwise just spin around gradually incrementing a hypothetical 'percent' done. Args: goal (:obj:`any`): goal of type specified by the action_type in the constructor.
Check for pre-emption, but otherwise just spin around gradually incrementing a hypothetical 'percent' done.
[ "Check", "for", "pre", "-", "emption", "but", "otherwise", "just", "spin", "around", "gradually", "incrementing", "a", "hypothetical", "'", "percent", "'", "done", "." ]
def execute(self, goal): frequency = 3.0 increment = 100 / (frequency * self.parameters.duration) self.percent_completed = 0 rate = rospy.Rate(frequency) rospy.loginfo("{title}: received a goal".format(title=self.title)) self.action_server.preempt_request = False ...
[ "def", "execute", "(", "self", ",", "goal", ")", ":", "frequency", "=", "3.0", "increment", "=", "100", "/", "(", "frequency", "*", "self", ".", "parameters", ".", "duration", ")", "self", ".", "percent_completed", "=", "0", "rate", "=", "rospy", ".", ...
Check for pre-emption, but otherwise just spin around gradually incrementing a hypothetical 'percent' done.
[ "Check", "for", "pre", "-", "emption", "but", "otherwise", "just", "spin", "around", "gradually", "incrementing", "a", "hypothetical", "'", "percent", "'", "done", "." ]
[ "# We override", "\"\"\"\n Check for pre-emption, but otherwise just spin around gradually incrementing\n a hypothetical 'percent' done.\n\n Args:\n goal (:obj:`any`): goal of type specified by the action_type in the constructor.\n \"\"\"", "#if self.goal_received_callback...
[ { "param": "self", "type": null }, { "param": "goal", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "goal", "type": null, "docstring": null, "docstring_tokens": [...
e32db2eba913e4333ba3d0b426c16deaaa16fc44
mateusap1/athenas
model/network.py
[ "MIT" ]
Python
load
None
def load(self) -> None: """Loads essential components of the node""" if self.__info is None: try: with open(NODE_PATH, "r") as f: self.__info = json.load(f) except IOError: self.__info = {"connected_nodes": [], "transactions": ...
Loads essential components of the node
Loads essential components of the node
[ "Loads", "essential", "components", "of", "the", "node" ]
def load(self) -> None: if self.__info is None: try: with open(NODE_PATH, "r") as f: self.__info = json.load(f) except IOError: self.__info = {"connected_nodes": [], "transactions": {}} self.save()
[ "def", "load", "(", "self", ")", "->", "None", ":", "if", "self", ".", "__info", "is", "None", ":", "try", ":", "with", "open", "(", "NODE_PATH", ",", "\"r\"", ")", "as", "f", ":", "self", ".", "__info", "=", "json", ".", "load", "(", "f", ")",...
Loads essential components of the node
[ "Loads", "essential", "components", "of", "the", "node" ]
[ "\"\"\"Loads essential components of the node\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e32db2eba913e4333ba3d0b426c16deaaa16fc44
mateusap1/athenas
model/network.py
[ "MIT" ]
Python
save
None
def save(self) -> None: """Saves the changes into a JSON file""" with open(NODE_PATH, "w") as f: json.dump(self.__info, f)
Saves the changes into a JSON file
Saves the changes into a JSON file
[ "Saves", "the", "changes", "into", "a", "JSON", "file" ]
def save(self) -> None: with open(NODE_PATH, "w") as f: json.dump(self.__info, f)
[ "def", "save", "(", "self", ")", "->", "None", ":", "with", "open", "(", "NODE_PATH", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "self", ".", "__info", ",", "f", ")" ]
Saves the changes into a JSON file
[ "Saves", "the", "changes", "into", "a", "JSON", "file" ]
[ "\"\"\"Saves the changes into a JSON file\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e32db2eba913e4333ba3d0b426c16deaaa16fc44
mateusap1/athenas
model/network.py
[ "MIT" ]
Python
is_transaction_valid
bool
def is_transaction_valid(self, transaction: dict, _type: object) -> bool: """Verfies if a transaction is valid or not""" required_keys = ["content", "receivers"] if Counter(transaction.keys()) != Counter(required_keys): # If, doesn't matter the order, the keys are not all ...
Verfies if a transaction is valid or not
Verfies if a transaction is valid or not
[ "Verfies", "if", "a", "transaction", "is", "valid", "or", "not" ]
def is_transaction_valid(self, transaction: dict, _type: object) -> bool: required_keys = ["content", "receivers"] if Counter(transaction.keys()) != Counter(required_keys): print("Invalid transaction: Keys don't match") return False tr_content = transaction["content"] ...
[ "def", "is_transaction_valid", "(", "self", ",", "transaction", ":", "dict", ",", "_type", ":", "object", ")", "->", "bool", ":", "required_keys", "=", "[", "\"content\"", ",", "\"receivers\"", "]", "if", "Counter", "(", "transaction", ".", "keys", "(", ")...
Verfies if a transaction is valid or not
[ "Verfies", "if", "a", "transaction", "is", "valid", "or", "not" ]
[ "\"\"\"Verfies if a transaction is valid or not\"\"\"", "# If, doesn't matter the order, the keys are not all", "# the same as the expected ones, return False", "# Returns false if any of the transaction values", "# have a different type other than the expected" ]
[ { "param": "self", "type": null }, { "param": "transaction", "type": "dict" }, { "param": "_type", "type": "object" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "transaction", "type": "dict", "docstring": null, "docstring_t...
e32db2eba913e4333ba3d0b426c16deaaa16fc44
mateusap1/athenas
model/network.py
[ "MIT" ]
Python
send_transaction
bool
def send_transaction(self, transaction: dict, _type: object) -> bool: """Stores the transaction sent if it's valid and has valid IDs""" if len(self.__info["transactions"]) == MAX_TRANSACTIONS: print("Error while adding transaction: Limit of transactions exceeded") return False ...
Stores the transaction sent if it's valid and has valid IDs
Stores the transaction sent if it's valid and has valid IDs
[ "Stores", "the", "transaction", "sent", "if", "it", "'", "s", "valid", "and", "has", "valid", "IDs" ]
def send_transaction(self, transaction: dict, _type: object) -> bool: if len(self.__info["transactions"]) == MAX_TRANSACTIONS: print("Error while adding transaction: Limit of transactions exceeded") return False if self.is_transaction_valid(transaction, _type) is False: ...
[ "def", "send_transaction", "(", "self", ",", "transaction", ":", "dict", ",", "_type", ":", "object", ")", "->", "bool", ":", "if", "len", "(", "self", ".", "__info", "[", "\"transactions\"", "]", ")", "==", "MAX_TRANSACTIONS", ":", "print", "(", "\"Erro...
Stores the transaction sent if it's valid and has valid IDs
[ "Stores", "the", "transaction", "sent", "if", "it", "'", "s", "valid", "and", "has", "valid", "IDs" ]
[ "\"\"\"Stores the transaction sent if it's valid and has valid IDs\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "transaction", "type": "dict" }, { "param": "_type", "type": "object" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "transaction", "type": "dict", "docstring": null, "docstring_t...
e32db2eba913e4333ba3d0b426c16deaaa16fc44
mateusap1/athenas
model/network.py
[ "MIT" ]
Python
connect_nodes
None
def connect_nodes(self, nodes: list) -> None: """Connect nodes that weren't connected before""" for node in nodes: if not Counter(node.keys()) == Counter(["ip", "port"]): raise ValueError( "Node must contain two arguments: \"ip\" and \"port\"") ...
Connect nodes that weren't connected before
Connect nodes that weren't connected before
[ "Connect", "nodes", "that", "weren", "'", "t", "connected", "before" ]
def connect_nodes(self, nodes: list) -> None: for node in nodes: if not Counter(node.keys()) == Counter(["ip", "port"]): raise ValueError( "Node must contain two arguments: \"ip\" and \"port\"") elif not node in self.__info["connected_nodes"]: ...
[ "def", "connect_nodes", "(", "self", ",", "nodes", ":", "list", ")", "->", "None", ":", "for", "node", "in", "nodes", ":", "if", "not", "Counter", "(", "node", ".", "keys", "(", ")", ")", "==", "Counter", "(", "[", "\"ip\"", ",", "\"port\"", "]", ...
Connect nodes that weren't connected before
[ "Connect", "nodes", "that", "weren", "'", "t", "connected", "before" ]
[ "\"\"\"Connect nodes that weren't connected before\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "nodes", "type": "list" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nodes", "type": "list", "docstring": null, "docstring_tokens"...
e32db2eba913e4333ba3d0b426c16deaaa16fc44
mateusap1/athenas
model/network.py
[ "MIT" ]
Python
remove_outdated_transactions
null
def remove_outdated_transactions(self): """Removes any transactions that were added more than N days ago, where N is the transactions day limit""" date_limit = datetime.datetime.now(datetime.timezone.utc) - \ datetime.timedelta(days=TRANSACTION_EXPIRE_DAYS) for key, value i...
Removes any transactions that were added more than N days ago, where N is the transactions day limit
Removes any transactions that were added more than N days ago, where N is the transactions day limit
[ "Removes", "any", "transactions", "that", "were", "added", "more", "than", "N", "days", "ago", "where", "N", "is", "the", "transactions", "day", "limit" ]
def remove_outdated_transactions(self): date_limit = datetime.datetime.now(datetime.timezone.utc) - \ datetime.timedelta(days=TRANSACTION_EXPIRE_DAYS) for key, value in self.__info["transactions"].items(): self.__info["transactions"][key] = list(filter( lambda x: ...
[ "def", "remove_outdated_transactions", "(", "self", ")", ":", "date_limit", "=", "datetime", ".", "datetime", ".", "now", "(", "datetime", ".", "timezone", ".", "utc", ")", "-", "datetime", ".", "timedelta", "(", "days", "=", "TRANSACTION_EXPIRE_DAYS", ")", ...
Removes any transactions that were added more than N days ago, where N is the transactions day limit
[ "Removes", "any", "transactions", "that", "were", "added", "more", "than", "N", "days", "ago", "where", "N", "is", "the", "transactions", "day", "limit" ]
[ "\"\"\"Removes any transactions that were added more than N days ago,\n where N is the transactions day limit\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2c96d14816d721ec0dda9e93f1ffc5caeca8c16e
mateusap1/athenas
model/utils.py
[ "MIT" ]
Python
parse_key
str
def parse_key(key: RSA.RsaKey) -> str: """Returns the string version of a RSA key""" return binascii.hexlify(key.exportKey( format='DER')).decode('ascii')
Returns the string version of a RSA key
Returns the string version of a RSA key
[ "Returns", "the", "string", "version", "of", "a", "RSA", "key" ]
def parse_key(key: RSA.RsaKey) -> str: return binascii.hexlify(key.exportKey( format='DER')).decode('ascii')
[ "def", "parse_key", "(", "key", ":", "RSA", ".", "RsaKey", ")", "->", "str", ":", "return", "binascii", ".", "hexlify", "(", "key", ".", "exportKey", "(", "format", "=", "'DER'", ")", ")", ".", "decode", "(", "'ascii'", ")" ]
Returns the string version of a RSA key
[ "Returns", "the", "string", "version", "of", "a", "RSA", "key" ]
[ "\"\"\"Returns the string version of a RSA key\"\"\"" ]
[ { "param": "key", "type": "RSA.RsaKey" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "key", "type": "RSA.RsaKey", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2c96d14816d721ec0dda9e93f1ffc5caeca8c16e
mateusap1/athenas
model/utils.py
[ "MIT" ]
Python
import_key
RSA.RsaKey
def import_key(key: str) -> RSA.RsaKey: """Returns the RSA key correspondent to a string version. It's the inverse function of parse_key""" return RSA.importKey(binascii.unhexlify(key))
Returns the RSA key correspondent to a string version. It's the inverse function of parse_key
Returns the RSA key correspondent to a string version. It's the inverse function of parse_key
[ "Returns", "the", "RSA", "key", "correspondent", "to", "a", "string", "version", ".", "It", "'", "s", "the", "inverse", "function", "of", "parse_key" ]
def import_key(key: str) -> RSA.RsaKey: return RSA.importKey(binascii.unhexlify(key))
[ "def", "import_key", "(", "key", ":", "str", ")", "->", "RSA", ".", "RsaKey", ":", "return", "RSA", ".", "importKey", "(", "binascii", ".", "unhexlify", "(", "key", ")", ")" ]
Returns the RSA key correspondent to a string version.
[ "Returns", "the", "RSA", "key", "correspondent", "to", "a", "string", "version", "." ]
[ "\"\"\"Returns the RSA key correspondent to a string version.\n It's the inverse function of parse_key\"\"\"" ]
[ { "param": "key", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "key", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2c96d14816d721ec0dda9e93f1ffc5caeca8c16e
mateusap1/athenas
model/utils.py
[ "MIT" ]
Python
sign
None
def sign(private_key: RsaKey, content: dict) -> None: """Returns a signature according to a private key and a content""" signer = PKCS1_v1_5.new(private_key) encoded_content = json.dumps(content, sort_keys=True).encode() h = SHA256.new(encoded_content) signature = signer.sign(h) return binasci...
Returns a signature according to a private key and a content
Returns a signature according to a private key and a content
[ "Returns", "a", "signature", "according", "to", "a", "private", "key", "and", "a", "content" ]
def sign(private_key: RsaKey, content: dict) -> None: signer = PKCS1_v1_5.new(private_key) encoded_content = json.dumps(content, sort_keys=True).encode() h = SHA256.new(encoded_content) signature = signer.sign(h) return binascii.hexlify(signature).decode('ascii')
[ "def", "sign", "(", "private_key", ":", "RsaKey", ",", "content", ":", "dict", ")", "->", "None", ":", "signer", "=", "PKCS1_v1_5", ".", "new", "(", "private_key", ")", "encoded_content", "=", "json", ".", "dumps", "(", "content", ",", "sort_keys", "=", ...
Returns a signature according to a private key and a content
[ "Returns", "a", "signature", "according", "to", "a", "private", "key", "and", "a", "content" ]
[ "\"\"\"Returns a signature according to a private key and a content\"\"\"" ]
[ { "param": "private_key", "type": "RsaKey" }, { "param": "content", "type": "dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "private_key", "type": "RsaKey", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "content", "type": "dict", "docstring": null, "docs...
2c96d14816d721ec0dda9e93f1ffc5caeca8c16e
mateusap1/athenas
model/utils.py
[ "MIT" ]
Python
compare_signature
bool
def compare_signature(public_key: str, signature: str, content: dict) -> bool: """Verifies if the signature is valid""" public_key = import_key(public_key) verifier = PKCS1_v1_5.new(public_key) encoded_content = json.dumps(content, sort_keys=True).encode() h = SHA256.new(encoded_content) retur...
Verifies if the signature is valid
Verifies if the signature is valid
[ "Verifies", "if", "the", "signature", "is", "valid" ]
def compare_signature(public_key: str, signature: str, content: dict) -> bool: public_key = import_key(public_key) verifier = PKCS1_v1_5.new(public_key) encoded_content = json.dumps(content, sort_keys=True).encode() h = SHA256.new(encoded_content) return verifier.verify(h, binascii.unhexlify(signatu...
[ "def", "compare_signature", "(", "public_key", ":", "str", ",", "signature", ":", "str", ",", "content", ":", "dict", ")", "->", "bool", ":", "public_key", "=", "import_key", "(", "public_key", ")", "verifier", "=", "PKCS1_v1_5", ".", "new", "(", "public_k...
Verifies if the signature is valid
[ "Verifies", "if", "the", "signature", "is", "valid" ]
[ "\"\"\"Verifies if the signature is valid\"\"\"" ]
[ { "param": "public_key", "type": "str" }, { "param": "signature", "type": "str" }, { "param": "content", "type": "dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "public_key", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "signature", "type": "str", "docstring": null, "docstri...
2c96d14816d721ec0dda9e93f1ffc5caeca8c16e
mateusap1/athenas
model/utils.py
[ "MIT" ]
Python
verify_hash
bool
def verify_hash(content: dict, hashing: str) -> bool: """Verifies if the hash is valid""" encoded_content = json.dumps(content, sort_keys=True).encode() hash_value = hashlib.sha256(encoded_content).hexdigest() return hash_value == hashing
Verifies if the hash is valid
Verifies if the hash is valid
[ "Verifies", "if", "the", "hash", "is", "valid" ]
def verify_hash(content: dict, hashing: str) -> bool: encoded_content = json.dumps(content, sort_keys=True).encode() hash_value = hashlib.sha256(encoded_content).hexdigest() return hash_value == hashing
[ "def", "verify_hash", "(", "content", ":", "dict", ",", "hashing", ":", "str", ")", "->", "bool", ":", "encoded_content", "=", "json", ".", "dumps", "(", "content", ",", "sort_keys", "=", "True", ")", ".", "encode", "(", ")", "hash_value", "=", "hashli...
Verifies if the hash is valid
[ "Verifies", "if", "the", "hash", "is", "valid" ]
[ "\"\"\"Verifies if the hash is valid\"\"\"" ]
[ { "param": "content", "type": "dict" }, { "param": "hashing", "type": "str" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "content", "type": "dict", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "hashing", "type": "str", "docstring": null, "docstring_t...
2c96d14816d721ec0dda9e93f1ffc5caeca8c16e
mateusap1/athenas
model/utils.py
[ "MIT" ]
Python
hash_content
dict
def hash_content(content: dict, difficulty: int, nonce_limit: int) -> dict: """Returns the new dictionary with it's hash containing N leading zeros, where N is the given difficulty""" content["nonce"] = 0 timestamp = datetime.datetime.now(datetime.timezone.utc) content["timestamp"] = str(timestamp...
Returns the new dictionary with it's hash containing N leading zeros, where N is the given difficulty
Returns the new dictionary with it's hash containing N leading zeros, where N is the given difficulty
[ "Returns", "the", "new", "dictionary", "with", "it", "'", "s", "hash", "containing", "N", "leading", "zeros", "where", "N", "is", "the", "given", "difficulty" ]
def hash_content(content: dict, difficulty: int, nonce_limit: int) -> dict: content["nonce"] = 0 timestamp = datetime.datetime.now(datetime.timezone.utc) content["timestamp"] = str(timestamp) hash_value = "" while not hash_value[:difficulty] == "0" * difficulty: content["nonce"] += 1 ...
[ "def", "hash_content", "(", "content", ":", "dict", ",", "difficulty", ":", "int", ",", "nonce_limit", ":", "int", ")", "->", "dict", ":", "content", "[", "\"nonce\"", "]", "=", "0", "timestamp", "=", "datetime", ".", "datetime", ".", "now", "(", "date...
Returns the new dictionary with it's hash containing N leading zeros, where N is the given difficulty
[ "Returns", "the", "new", "dictionary", "with", "it", "'", "s", "hash", "containing", "N", "leading", "zeros", "where", "N", "is", "the", "given", "difficulty" ]
[ "\"\"\"Returns the new dictionary with it's hash containing \n N leading zeros, where N is the given difficulty\"\"\"" ]
[ { "param": "content", "type": "dict" }, { "param": "difficulty", "type": "int" }, { "param": "nonce_limit", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "content", "type": "dict", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "difficulty", "type": "int", "docstring": null, "docstrin...
1d65ddea64f186127ef6360408ad4e4adadba090
mateusap1/athenas
model/Account.py
[ "MIT" ]
Python
create_keys
null
def create_keys(self): """Create a new pair of private and public keys""" try: # If we've already created a private key before, import it # Otherwise, create it with open(self.key_path, "r") as f: private_key = RSA.import_key( f.re...
Create a new pair of private and public keys
Create a new pair of private and public keys
[ "Create", "a", "new", "pair", "of", "private", "and", "public", "keys" ]
def create_keys(self): try: with open(self.key_path, "r") as f: private_key = RSA.import_key( f.read(), passphrase=self.__password) public_key = private_key.publickey() except IOError: private_key = create_key() publ...
[ "def", "create_keys", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "key_path", ",", "\"r\"", ")", "as", "f", ":", "private_key", "=", "RSA", ".", "import_key", "(", "f", ".", "read", "(", ")", ",", "passphrase", "=", "self",...
Create a new pair of private and public keys
[ "Create", "a", "new", "pair", "of", "private", "and", "public", "keys" ]
[ "\"\"\"Create a new pair of private and public keys\"\"\"", "# If we've already created a private key before, import it", "# Otherwise, create it" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
1d65ddea64f186127ef6360408ad4e4adadba090
mateusap1/athenas
model/Account.py
[ "MIT" ]
Python
create_id
null
def create_id(self): """Creates an ID if there isn't one already""" try: with open(self.info_path) as f: self.__info = json.load(f) except IOError: if self.__username is None: raise UnspecifiedInformation("Username not provided") ...
Creates an ID if there isn't one already
Creates an ID if there isn't one already
[ "Creates", "an", "ID", "if", "there", "isn", "'", "t", "one", "already" ]
def create_id(self): try: with open(self.info_path) as f: self.__info = json.load(f) except IOError: if self.__username is None: raise UnspecifiedInformation("Username not provided") content = { "username": self.__userna...
[ "def", "create_id", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "info_path", ")", "as", "f", ":", "self", ".", "__info", "=", "json", ".", "load", "(", "f", ")", "except", "IOError", ":", "if", "self", ".", "__username", ...
Creates an ID if there isn't one already
[ "Creates", "an", "ID", "if", "there", "isn", "'", "t", "one", "already" ]
[ "\"\"\"Creates an ID if there isn't one already\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b32d6567051a3f4cafca764cf70bbaa3e1e1bb91
mateusap1/athenas
model/transaction/Contract.py
[ "MIT" ]
Python
to_dict
dict
def to_dict(self) -> dict: """Returns all class paramaters in a dictionary form""" return { "sender": self.__sender.to_dict(), "rules": self.__rules, "judges": [i.to_dict() for i in self.__judges], "expire": str(self.__expire), "signature": se...
Returns all class paramaters in a dictionary form
Returns all class paramaters in a dictionary form
[ "Returns", "all", "class", "paramaters", "in", "a", "dictionary", "form" ]
def to_dict(self) -> dict: return { "sender": self.__sender.to_dict(), "rules": self.__rules, "judges": [i.to_dict() for i in self.__judges], "expire": str(self.__expire), "signature": self.__signature }
[ "def", "to_dict", "(", "self", ")", "->", "dict", ":", "return", "{", "\"sender\"", ":", "self", ".", "__sender", ".", "to_dict", "(", ")", ",", "\"rules\"", ":", "self", ".", "__rules", ",", "\"judges\"", ":", "[", "i", ".", "to_dict", "(", ")", "...
Returns all class paramaters in a dictionary form
[ "Returns", "all", "class", "paramaters", "in", "a", "dictionary", "form" ]
[ "\"\"\"Returns all class paramaters in a dictionary form\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b4898b915a02caf2b8465a9a41a4eb701c69d0ab
mateusap1/athenas
model/transaction/Appeal.py
[ "MIT" ]
Python
to_dict
dict
def to_dict(self) -> dict: """Returns 'Transaction' content on a dictionary format""" return { "sender": self.__sender.to_dict(), "verdict": self.__verdict.to_dict(), "signature": self.__signature }
Returns 'Transaction' content on a dictionary format
Returns 'Transaction' content on a dictionary format
[ "Returns", "'", "Transaction", "'", "content", "on", "a", "dictionary", "format" ]
def to_dict(self) -> dict: return { "sender": self.__sender.to_dict(), "verdict": self.__verdict.to_dict(), "signature": self.__signature }
[ "def", "to_dict", "(", "self", ")", "->", "dict", ":", "return", "{", "\"sender\"", ":", "self", ".", "__sender", ".", "to_dict", "(", ")", ",", "\"verdict\"", ":", "self", ".", "__verdict", ".", "to_dict", "(", ")", ",", "\"signature\"", ":", "self", ...
Returns 'Transaction' content on a dictionary format
[ "Returns", "'", "Transaction", "'", "content", "on", "a", "dictionary", "format" ]
[ "\"\"\"Returns 'Transaction' content on a dictionary format\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
b4898b915a02caf2b8465a9a41a4eb701c69d0ab
mateusap1/athenas
model/transaction/Appeal.py
[ "MIT" ]
Python
import_dict
Optional[Appeal]
def import_dict(transaction: dict) -> Optional[Appeal]: """Returns an instance of Appeal object based on it's dictionary version""" keys = ["sender", "verdict", "signature"] if any([not key in keys for key in transaction.keys()]): print("Invalid transaction: Keys mis...
Returns an instance of Appeal object based on it's dictionary version
Returns an instance of Appeal object based on it's dictionary version
[ "Returns", "an", "instance", "of", "Appeal", "object", "based", "on", "it", "'", "s", "dictionary", "version" ]
def import_dict(transaction: dict) -> Optional[Appeal]: keys = ["sender", "verdict", "signature"] if any([not key in keys for key in transaction.keys()]): print("Invalid transaction: Keys missing") return None try: sender = ID(**transaction["sender"]) ...
[ "def", "import_dict", "(", "transaction", ":", "dict", ")", "->", "Optional", "[", "Appeal", "]", ":", "keys", "=", "[", "\"sender\"", ",", "\"verdict\"", ",", "\"signature\"", "]", "if", "any", "(", "[", "not", "key", "in", "keys", "for", "key", "in",...
Returns an instance of Appeal object based on it's dictionary version
[ "Returns", "an", "instance", "of", "Appeal", "object", "based", "on", "it", "'", "s", "dictionary", "version" ]
[ "\"\"\"Returns an instance of Appeal object\n based on it's dictionary version\"\"\"" ]
[ { "param": "transaction", "type": "dict" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "transaction", "type": "dict", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
8e4ded8d3d43d0e5fdddb7ac5940d962e174875c
mateusap1/athenas
model/identity.py
[ "MIT" ]
Python
to_dict
dict
def to_dict(self) -> dict: """Returns all class paramaters in a dictionary form""" return { "username": self.__username, "public_key": self.__public_key, "nonce": self.__nonce, "timestamp": self.__timestamp, "hash_value": self.__hash_value ...
Returns all class paramaters in a dictionary form
Returns all class paramaters in a dictionary form
[ "Returns", "all", "class", "paramaters", "in", "a", "dictionary", "form" ]
def to_dict(self) -> dict: return { "username": self.__username, "public_key": self.__public_key, "nonce": self.__nonce, "timestamp": self.__timestamp, "hash_value": self.__hash_value }
[ "def", "to_dict", "(", "self", ")", "->", "dict", ":", "return", "{", "\"username\"", ":", "self", ".", "__username", ",", "\"public_key\"", ":", "self", ".", "__public_key", ",", "\"nonce\"", ":", "self", ".", "__nonce", ",", "\"timestamp\"", ":", "self",...
Returns all class paramaters in a dictionary form
[ "Returns", "all", "class", "paramaters", "in", "a", "dictionary", "form" ]
[ "\"\"\"Returns all class paramaters in a dictionary form\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }