nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
Nuitka/Nuitka
39262276993757fa4e299f497654065600453fc9
nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Variables/PackageVariable.py
python
PackageVariable
(key, help, default, searchfunc=None)
return (key, help, default, lambda k, v, e: _validator(k,v,e,searchfunc), _converter)
The input parameters describe a 'package list' option, thus they are returned with the correct converter and validator appended. The result is usable for input to opts.Add() . A 'package list' option may either be 'all', 'none' or a list of package names (separated by space).
The input parameters describe a 'package list' option, thus they are returned with the correct converter and validator appended. The result is usable for input to opts.Add() .
[ "The", "input", "parameters", "describe", "a", "package", "list", "option", "thus", "they", "are", "returned", "with", "the", "correct", "converter", "and", "validator", "appended", ".", "The", "result", "is", "usable", "for", "input", "to", "opts", ".", "Ad...
def PackageVariable(key, help, default, searchfunc=None): # NB: searchfunc is currently undocumented and unsupported """ The input parameters describe a 'package list' option, thus they are returned with the correct converter and validator appended. The result is usable for input to opts.Add() . A 'package list' option may either be 'all', 'none' or a list of package names (separated by space). """ help = '\n '.join( (help, '( yes | no | /path/to/%s )' % key)) return (key, help, default, lambda k, v, e: _validator(k,v,e,searchfunc), _converter)
[ "def", "PackageVariable", "(", "key", ",", "help", ",", "default", ",", "searchfunc", "=", "None", ")", ":", "# NB: searchfunc is currently undocumented and unsupported", "help", "=", "'\\n '", ".", "join", "(", "(", "help", ",", "'( yes | no | /path/to/%s )'", "...
https://github.com/Nuitka/Nuitka/blob/39262276993757fa4e299f497654065600453fc9/nuitka/build/inline_copy/lib/scons-3.1.2/SCons/Variables/PackageVariable.py#L86-L100
n1nj4sec/pupy
a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39
pupy/packages/windows/all/fsutils_ext.py
python
WINTRUST_DATA.__init__
(self, filename)
[]
def __init__(self, filename): self._pFile = WINTRUST_FILE_INFO(filename) self.cbStruct = DWORD(sizeof(self)) self.pPolicyCallbackData = None self.pSIPClientData = None self.dwUIChoice = WTD_UI_NONE self.fdwRevocationChecks = WTD_REVOKE_NONE self.dwUnionChoice = WTD_CHOICE_FILE self.dwStateAction = WTD_STATEACTION_VERIFY self.hWVTStateData = None self.pwszURLReference = None self.dwUIContext = 0 self.pvInfo = addressof(self._pFile)
[ "def", "__init__", "(", "self", ",", "filename", ")", ":", "self", ".", "_pFile", "=", "WINTRUST_FILE_INFO", "(", "filename", ")", "self", ".", "cbStruct", "=", "DWORD", "(", "sizeof", "(", "self", ")", ")", "self", ".", "pPolicyCallbackData", "=", "None...
https://github.com/n1nj4sec/pupy/blob/a5d766ea81fdfe3bc2c38c9bdaf10e9b75af3b39/pupy/packages/windows/all/fsutils_ext.py#L340-L353
allegroai/clearml
5953dc6eefadcdfcc2bdbb6a0da32be58823a5af
examples/frameworks/click/click_single_cmd.py
python
hello
(count, name)
Simple program that greets NAME for a total of COUNT times.
Simple program that greets NAME for a total of COUNT times.
[ "Simple", "program", "that", "greets", "NAME", "for", "a", "total", "of", "COUNT", "times", "." ]
def hello(count, name): task = Task.init(project_name='examples', task_name='click single command') """Simple program that greets NAME for a total of COUNT times.""" for x in range(count): click.echo("Hello {}!".format(name))
[ "def", "hello", "(", "count", ",", "name", ")", ":", "task", "=", "Task", ".", "init", "(", "project_name", "=", "'examples'", ",", "task_name", "=", "'click single command'", ")", "for", "x", "in", "range", "(", "count", ")", ":", "click", ".", "echo"...
https://github.com/allegroai/clearml/blob/5953dc6eefadcdfcc2bdbb6a0da32be58823a5af/examples/frameworks/click/click_single_cmd.py#L9-L14
RJT1990/mantra
7db4d272a1625c33eaa681b8c2e75c0aa57c6952
mantraml/ui/core/views.py
python
view_trial_group
(request, trial_group_folder)
return render(request, 'view_trial_group.html', context)
This view shows a group of trials for a given trial id
This view shows a group of trials for a given trial id
[ "This", "view", "shows", "a", "group", "of", "trials", "for", "a", "given", "trial", "id" ]
def view_trial_group(request, trial_group_folder): """ This view shows a group of trials for a given trial id """ # delete trial option - catch and process if request.method == 'POST': form = DeleteTrialForm(request.POST) if form.is_valid(): trials = Trial.get_trial_contents_as_dicts(settings=settings) trial_contents = Trial.get_trial_contents(settings=settings) group_trials = [group_trial for group_trial in trials if group_trial['trial_group_hash'].startswith(trial_group_folder)] trial_hash = form.cleaned_data['trial_hash'] new_contents = [trial for trial in trial_contents if not trial[2] == trial_hash] try: trial_folder_name = [trial for trial in trial_contents if trial[2] == trial_hash][0][1] trial_exists = True except IndexError: trial_exists = False if trial_exists: new_information = '\n'.join([" ".join(content) for content in new_contents]) + '\n' if os.path.exists('%s/%s/%s' % (settings.MANTRA_PROJECT_ROOT, 'trials', trial_folder_name)): shutil.rmtree('%s/%s/%s' % (settings.MANTRA_PROJECT_ROOT, 'trials', trial_folder_name)) # delete the trial folder with open("%s/.mantra/TRIALS" % settings.MANTRA_PROJECT_ROOT, "w") as trial_file: trial_file.write(new_information) trials = Trial.get_trial_contents_as_dicts(settings=settings) group_trials = [group_trial for group_trial in trials if group_trial['trial_group_hash'].startswith(trial_group_folder)] form = DeleteTrialForm() if not group_trials: raise Http404("Trial Group does not exist") else: sys.path.append(settings.MANTRA_PROJECT_ROOT) model_trials = [trial for trial in trials if trial['trial_group_hash'] == group_trials[0]['trial_group_hash']] task_name = model_trials[0]['task_name'] task_full_name = Mantra.find_task_metadata(task_name)['name'] evaluation_name = Mantra.find_task_metadata(task_name)['evaluation_name'] context = {} yaml_content = Trial.get_trial_group_name_dict(settings=settings) try: context['trial_group_name'] = yaml_content[model_trials[0]['trial_group_hash']] except: context['trial_group_name'] = 'Trial Group ' + model_trials[0]['trial_group_hash'][:6] context['task_name'] = task_name context['task_full_name'] = task_full_name context['evaluation_name'] = evaluation_name context['trial_group_hash'] = model_trials[0]['trial_group_hash'] context['trials'] = model_trials context['latest_trial'] = datetime.datetime.utcfromtimestamp(int(str(max([trial['start_timestamp'] for trial in model_trials])))) hyperparameter_list = [] metric_name_list = [] for trial in context['trials']: trial.update({'time': datetime.datetime.utcfromtimestamp(int(str(trial['start_timestamp'])))}) try: trial['metadata'] = yaml.load(open('%s/trials/%s/trial_metadata.yml' % (settings.MANTRA_PROJECT_ROOT, trial['folder_name']), 'r').read()) except: # can't load yaml trial['metadata'] = {} if 'hyperparameters' in trial['metadata']: hyperparameter_list = hyperparameter_list + list(trial['metadata']['hyperparameters'].keys()) if 'secondary_metrics' in trial['metadata']: metric_name_list = metric_name_list + list(trial['metadata']['secondary_metrics'].keys()) occur = Counter([hyperparm for hyperparm in hyperparameter_list if hyperparm not in ['epochs', 'image_dim']]) context['hyperparms'] = [i[0] for i in occur.most_common(5)] context['metric_names'] = list(set(metric_name_list)) for trial in context['trials']: if 'hyperparameters' in trial['metadata']: hyperparm_list = [] for hyperparm_no, hyperparm in enumerate(context['hyperparms']): if hyperparm in trial['metadata']['hyperparameters']: hyperparameter_value = trial['metadata']['hyperparameters'][hyperparm] if isinstance(hyperparameter_value, list): hyperparameter_value_type = 'list' elif isinstance(hyperparameter_value, float): hyperparameter_value_type = 'float' else: hyperparameter_value_type = 'str' hyperparm_list.append({'value': hyperparameter_value, 'type': hyperparameter_value_type}) else: hyperparm_list.append({}) trial.update({'hyperparm_values': hyperparm_list}) else: trial.update({'hyperparm_values': [None]*len(context['hyperparms'])}) if 'secondary_metrics' in trial['metadata']: metric_list = [] for metric_no, metric in enumerate(context['metric_names']): if metric in trial['metadata']['secondary_metrics']: metric_list.append(trial['metadata']['secondary_metrics'][metric]) else: metric_list.append(None) trial.update({'metric_values': metric_list}) else: trial.update({'metric_values': [None]*len(context['metric_names'])}) context['hyperparms'] = [hyperparm.replace('_', ' ').title() for hyperparm in context['hyperparms']] context['trials'].sort(key=lambda item: item['time'], reverse=True) context['model'] = {} context['data'] = {} context['model'].update(Mantra.find_model_metadata(model_trials[0]['model_name'])) context['data'].update(Mantra.find_dataset_metadata(model_trials[0]['data_name'])) context['form'] = form return render(request, 'view_trial_group.html', context)
[ "def", "view_trial_group", "(", "request", ",", "trial_group_folder", ")", ":", "# delete trial option - catch and process", "if", "request", ".", "method", "==", "'POST'", ":", "form", "=", "DeleteTrialForm", "(", "request", ".", "POST", ")", "if", "form", ".", ...
https://github.com/RJT1990/mantra/blob/7db4d272a1625c33eaa681b8c2e75c0aa57c6952/mantraml/ui/core/views.py#L343-L471
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/sqli/tamper/versionedkeywords.py
python
dependencies
()
[]
def dependencies(): singleTimeWarnMessage("tamper script '%s' is only meant to be run against %s" % (os.path.basename(__file__).split(".")[0], DBMS.MYSQL))
[ "def", "dependencies", "(", ")", ":", "singleTimeWarnMessage", "(", "\"tamper script '%s' is only meant to be run against %s\"", "%", "(", "os", ".", "path", ".", "basename", "(", "__file__", ")", ".", "split", "(", "\".\"", ")", "[", "0", "]", ",", "DBMS", "....
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/tamper/versionedkeywords.py#L18-L19
lyft/cartography
921a790d686c679ab5d8936b07e167fd424ee8d6
cartography/intel/digitalocean/__init__.py
python
start_digitalocean_ingestion
(neo4j_session: neo4j.Session, config: Config)
return
If this module is configured, perform ingestion of DigitalOcean data. Otherwise warn and exit :param neo4j_session: Neo4J session for database interface :param config: A cartography.config object :return: None
If this module is configured, perform ingestion of DigitalOcean data. Otherwise warn and exit :param neo4j_session: Neo4J session for database interface :param config: A cartography.config object :return: None
[ "If", "this", "module", "is", "configured", "perform", "ingestion", "of", "DigitalOcean", "data", ".", "Otherwise", "warn", "and", "exit", ":", "param", "neo4j_session", ":", "Neo4J", "session", "for", "database", "interface", ":", "param", "config", ":", "A",...
def start_digitalocean_ingestion(neo4j_session: neo4j.Session, config: Config) -> None: """ If this module is configured, perform ingestion of DigitalOcean data. Otherwise warn and exit :param neo4j_session: Neo4J session for database interface :param config: A cartography.config object :return: None """ if not config.digitalocean_token: logger.info('DigitalOcean import is not configured - skipping this module. See docs to configure.') return common_job_parameters = { "UPDATE_TAG": config.update_tag, } manager = Manager(token=config.digitalocean_token) """ Get Account ID related to this credentials and pass it along in `common_job_parameters` to avoid cleaning up other accounts resources """ account = manager.get_account() common_job_parameters["DO_ACCOUNT_ID"] = account.uuid platform.sync(neo4j_session, account, config.update_tag, common_job_parameters) project_resources = management.sync(neo4j_session, manager, config.update_tag, common_job_parameters) compute.sync(neo4j_session, manager, project_resources, config.update_tag, common_job_parameters) return
[ "def", "start_digitalocean_ingestion", "(", "neo4j_session", ":", "neo4j", ".", "Session", ",", "config", ":", "Config", ")", "->", "None", ":", "if", "not", "config", ".", "digitalocean_token", ":", "logger", ".", "info", "(", "'DigitalOcean import is not configu...
https://github.com/lyft/cartography/blob/921a790d686c679ab5d8936b07e167fd424ee8d6/cartography/intel/digitalocean/__init__.py#L17-L44
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/collections.py
python
OrderedDict.__iter__
(self)
od.__iter__() <==> iter(od)
od.__iter__() <==> iter(od)
[ "od", ".", "__iter__", "()", "<", "==", ">", "iter", "(", "od", ")" ]
def __iter__(self): 'od.__iter__() <==> iter(od)' # Traverse the linked list in order. NEXT, KEY = 1, 2 root = self.__root curr = root[NEXT] while curr is not root: yield curr[KEY] curr = curr[NEXT]
[ "def", "__iter__", "(", "self", ")", ":", "# Traverse the linked list in order.", "NEXT", ",", "KEY", "=", "1", ",", "2", "root", "=", "self", ".", "__root", "curr", "=", "root", "[", "NEXT", "]", "while", "curr", "is", "not", "root", ":", "yield", "cu...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/collections.py#L72-L80
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/plugins/import_export/mealmaster_plugin/mealmaster_importer.py
python
mmf_importer.handle_group
(self, groupm)
Start a new ingredient group.
Start a new ingredient group.
[ "Start", "a", "new", "ingredient", "group", "." ]
def handle_group (self, groupm): """Start a new ingredient group.""" testtimer = TimeAction('mealmaster_importer.handle_group',10) debug("start handle_group",10) # the only group of the match will contain # the name of the group. We'll put it into # a more sane title case (MealMaster defaults # to all caps name = groupm.groups()[1] if not name: name = groupm.groups()[2] if not name: return name = name.strip().title() self.group=name #if re.match('^[^A-Za-z]*$',self.group): self.group=None #WTF was this for? testtimer.end()
[ "def", "handle_group", "(", "self", ",", "groupm", ")", ":", "testtimer", "=", "TimeAction", "(", "'mealmaster_importer.handle_group'", ",", "10", ")", "debug", "(", "\"start handle_group\"", ",", "10", ")", "# the only group of the match will contain", "# the name of t...
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/plugins/import_export/mealmaster_plugin/mealmaster_importer.py#L281-L297
rferrazz/pyqt4topyqt5
c0630e1a3e1e2884d8c56127812c35854dbdf301
pyqt4topyqt5/__init__.py
python
PyQt4ToPyQt5.is_class
(self, line)
return line.lstrip().startswith('class ')
Returns True if a line is a class definition line. Args: line -- the line code
Returns True if a line is a class definition line.
[ "Returns", "True", "if", "a", "line", "is", "a", "class", "definition", "line", "." ]
def is_class(self, line): """Returns True if a line is a class definition line. Args: line -- the line code """ return line.lstrip().startswith('class ')
[ "def", "is_class", "(", "self", ",", "line", ")", ":", "return", "line", ".", "lstrip", "(", ")", ".", "startswith", "(", "'class '", ")" ]
https://github.com/rferrazz/pyqt4topyqt5/blob/c0630e1a3e1e2884d8c56127812c35854dbdf301/pyqt4topyqt5/__init__.py#L1564-L1570
openstack/kuryr-kubernetes
513ada72685ef02cd9f3aca418ac1b2e0dc1b8ba
kuryr_kubernetes/controller/handlers/kuryrnetworkpolicy.py
python
KuryrNetworkPolicyHandler._get_networkpolicy
(self, link)
return self.k8s.get(link)
[]
def _get_networkpolicy(self, link): return self.k8s.get(link)
[ "def", "_get_networkpolicy", "(", "self", ",", "link", ")", ":", "return", "self", ".", "k8s", ".", "get", "(", "link", ")" ]
https://github.com/openstack/kuryr-kubernetes/blob/513ada72685ef02cd9f3aca418ac1b2e0dc1b8ba/kuryr_kubernetes/controller/handlers/kuryrnetworkpolicy.py#L75-L76
Lasagne/Lasagne
5d3c63cb315c50b1cbd27a6bc8664b406f34dd99
lasagne/layers/helper.py
python
count_params
(layer, **tags)
return sum(counts)
This function counts all parameters (i.e., the number of scalar values) of all layers below one or more given :class:`Layer` instances, including the layer(s) itself. This is useful to compare the capacity of various network architectures. All parameters returned by the :class:`Layer`s' `get_params` methods are counted. Parameters ---------- layer : Layer or list The :class:`Layer` instance for which to count the parameters, or a list of :class:`Layer` instances. **tags (optional) tags can be specified to filter the list of parameter variables that will be included in the count. Specifying ``tag1=True`` will limit the list to parameters that are tagged with ``tag1``. Specifying ``tag1=False`` will limit the list to parameters that are not tagged with ``tag1``. Commonly used tags are ``regularizable`` and ``trainable``. Returns ------- int The total number of learnable parameters. Examples -------- >>> from lasagne.layers import InputLayer, DenseLayer >>> l_in = InputLayer((100, 20)) >>> l1 = DenseLayer(l_in, num_units=50) >>> param_count = count_params(l1) >>> param_count 1050 >>> param_count == 20 * 50 + 50 # 20 input * 50 units + 50 biases True
This function counts all parameters (i.e., the number of scalar values) of all layers below one or more given :class:`Layer` instances, including the layer(s) itself.
[ "This", "function", "counts", "all", "parameters", "(", "i", ".", "e", ".", "the", "number", "of", "scalar", "values", ")", "of", "all", "layers", "below", "one", "or", "more", "given", ":", "class", ":", "Layer", "instances", "including", "the", "layer"...
def count_params(layer, **tags): """ This function counts all parameters (i.e., the number of scalar values) of all layers below one or more given :class:`Layer` instances, including the layer(s) itself. This is useful to compare the capacity of various network architectures. All parameters returned by the :class:`Layer`s' `get_params` methods are counted. Parameters ---------- layer : Layer or list The :class:`Layer` instance for which to count the parameters, or a list of :class:`Layer` instances. **tags (optional) tags can be specified to filter the list of parameter variables that will be included in the count. Specifying ``tag1=True`` will limit the list to parameters that are tagged with ``tag1``. Specifying ``tag1=False`` will limit the list to parameters that are not tagged with ``tag1``. Commonly used tags are ``regularizable`` and ``trainable``. Returns ------- int The total number of learnable parameters. Examples -------- >>> from lasagne.layers import InputLayer, DenseLayer >>> l_in = InputLayer((100, 20)) >>> l1 = DenseLayer(l_in, num_units=50) >>> param_count = count_params(l1) >>> param_count 1050 >>> param_count == 20 * 50 + 50 # 20 input * 50 units + 50 biases True """ params = get_all_params(layer, **tags) shapes = [p.get_value().shape for p in params] counts = [np.prod(shape) for shape in shapes] return sum(counts)
[ "def", "count_params", "(", "layer", ",", "*", "*", "tags", ")", ":", "params", "=", "get_all_params", "(", "layer", ",", "*", "*", "tags", ")", "shapes", "=", "[", "p", ".", "get_value", "(", ")", ".", "shape", "for", "p", "in", "params", "]", "...
https://github.com/Lasagne/Lasagne/blob/5d3c63cb315c50b1cbd27a6bc8664b406f34dd99/lasagne/layers/helper.py#L381-L424
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/integrals/transforms.py
python
_laplace_rule_heaviside
(f, t, s, doit=True, **hints)
return None
This internal helper function tries to transform a product containing the `Heaviside` function and returns `None` if it cannot do it.
This internal helper function tries to transform a product containing the `Heaviside` function and returns `None` if it cannot do it.
[ "This", "internal", "helper", "function", "tries", "to", "transform", "a", "product", "containing", "the", "Heaviside", "function", "and", "returns", "None", "if", "it", "cannot", "do", "it", "." ]
def _laplace_rule_heaviside(f, t, s, doit=True, **hints): """ This internal helper function tries to transform a product containing the `Heaviside` function and returns `None` if it cannot do it. """ hints.pop('simplify', True) a = Wild('a', exclude=[t]) b = Wild('b', exclude=[t]) y = Wild('y') g = WildFunction('g', nargs=1) k, func = f.as_independent(t, as_Add=False) ma1 = func.match(Heaviside(y)*g) if ma1: ma2 = ma1[y].match(t-a) ma3 = ma1[g].args[0].collect(t).match(t-b) if ma2 and ma2[a]>0 and ma3 and ma2[a]==ma3[b]: debug('_laplace_apply_rules match:') debug(' f: %s ( %s, %s, %s )'%(f, ma1, ma2, ma3)) debug(' rule: time shift (1.3)') L = _laplace_apply_rules(ma1[g].func(t), t, s, doit=doit, **hints) try: r, p, c = L return (k*exp(-ma2[a]*s)*r, p, c) except TypeError: return k*exp(-ma2[a]*s)*L return None
[ "def", "_laplace_rule_heaviside", "(", "f", ",", "t", ",", "s", ",", "doit", "=", "True", ",", "*", "*", "hints", ")", ":", "hints", ".", "pop", "(", "'simplify'", ",", "True", ")", "a", "=", "Wild", "(", "'a'", ",", "exclude", "=", "[", "t", "...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/integrals/transforms.py#L1607-L1632
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/apps/accounting/models.py
python
CustomerInvoice.applied_tax
(self)
return Decimal('%.4f' % round(self.tax_rate * self.subtotal, 4))
[]
def applied_tax(self): return Decimal('%.4f' % round(self.tax_rate * self.subtotal, 4))
[ "def", "applied_tax", "(", "self", ")", ":", "return", "Decimal", "(", "'%.4f'", "%", "round", "(", "self", ".", "tax_rate", "*", "self", ".", "subtotal", ",", "4", ")", ")" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/apps/accounting/models.py#L2270-L2271
CLUEbenchmark/CLUEPretrainedModels
b384fd41665a8261f9c689c940cf750b3bc21fce
baselines/models_pytorch/classifier_pytorch/transformers/modeling_xlnet.py
python
gelu
(x)
return x * cdf
Implementation of the gelu activation function. XLNet is using OpenAI GPT's gelu (not exactly the same as BERT) Also see https://arxiv.org/abs/1606.08415
Implementation of the gelu activation function. XLNet is using OpenAI GPT's gelu (not exactly the same as BERT) Also see https://arxiv.org/abs/1606.08415
[ "Implementation", "of", "the", "gelu", "activation", "function", ".", "XLNet", "is", "using", "OpenAI", "GPT", "s", "gelu", "(", "not", "exactly", "the", "same", "as", "BERT", ")", "Also", "see", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/"...
def gelu(x): """ Implementation of the gelu activation function. XLNet is using OpenAI GPT's gelu (not exactly the same as BERT) Also see https://arxiv.org/abs/1606.08415 """ cdf = 0.5 * (1.0 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) return x * cdf
[ "def", "gelu", "(", "x", ")", ":", "cdf", "=", "0.5", "*", "(", "1.0", "+", "torch", ".", "tanh", "(", "math", ".", "sqrt", "(", "2", "/", "math", ".", "pi", ")", "*", "(", "x", "+", "0.044715", "*", "torch", ".", "pow", "(", "x", ",", "3...
https://github.com/CLUEbenchmark/CLUEPretrainedModels/blob/b384fd41665a8261f9c689c940cf750b3bc21fce/baselines/models_pytorch/classifier_pytorch/transformers/modeling_xlnet.py#L175-L181
alibaba/iOSSecAudit
f94ed3254263f3382f374e3f05afae8a1fe79f20
lib/cycriptUtil.py
python
CycriptUtil.__init__
(self)
Constructor
Constructor
[ "Constructor" ]
def __init__(self): """Constructor"""
[ "def", "__init__", "(", "self", ")", ":" ]
https://github.com/alibaba/iOSSecAudit/blob/f94ed3254263f3382f374e3f05afae8a1fe79f20/lib/cycriptUtil.py#L16-L17
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
xl/hal.py
python
UDisksDBusWrapper.iface
(self)
return self._iface
Returns a dbus.Interface for the object's primary interface type
Returns a dbus.Interface for the object's primary interface type
[ "Returns", "a", "dbus", ".", "Interface", "for", "the", "object", "s", "primary", "interface", "type" ]
def iface(self): '''Returns a dbus.Interface for the object's primary interface type''' if self._iface is None: self._iface = dbus.Interface(self.obj, self.iface_type) return self._iface
[ "def", "iface", "(", "self", ")", ":", "if", "self", ".", "_iface", "is", "None", ":", "self", ".", "_iface", "=", "dbus", ".", "Interface", "(", "self", ".", "obj", ",", "self", ".", "iface_type", ")", "return", "self", ".", "_iface" ]
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/xl/hal.py#L94-L98
digidotcom/xbee-python
0757f4be0017530c205175fbee8f9f61be9614d1
digi/xbee/models/options.py
python
RegisterKeyOptions.code
(self)
return self.__code
Returns the code of the `RegisterKeyOptions` element. Returns: Integer: the code of the `RegisterKeyOptions` element.
Returns the code of the `RegisterKeyOptions` element.
[ "Returns", "the", "code", "of", "the", "RegisterKeyOptions", "element", "." ]
def code(self): """ Returns the code of the `RegisterKeyOptions` element. Returns: Integer: the code of the `RegisterKeyOptions` element. """ return self.__code
[ "def", "code", "(", "self", ")", ":", "return", "self", ".", "__code" ]
https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/models/options.py#L555-L562
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/sim_variable.py
python
SimVariableSet.add_memory_variables
(self, addrs, size)
[]
def add_memory_variables(self, addrs, size): for a in addrs: var = SimMemoryVariable(a, size) self.add_memory_variable(var)
[ "def", "add_memory_variables", "(", "self", ",", "addrs", ",", "size", ")", ":", "for", "a", "in", "addrs", ":", "var", "=", "SimMemoryVariable", "(", "a", ",", "size", ")", "self", ".", "add_memory_variable", "(", "var", ")" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/sim_variable.py#L475-L478
kronenthaler/mod-pbxproj
e848ce35d677346d84c83f7979a49fd6d298d843
pbxproj/pbxextensions/ProjectFlags.py
python
ProjectFlags.add_code_sign
(self, code_sign_identity, development_team, provisioning_profile_uuid, provisioning_profile_specifier, target_name=None, configuration_name=None)
Adds the code sign information to the project and creates the appropriate flags in the configuration. In xcode 8+ the provisioning_profile_uuid becomes optional, and the provisioning_profile_specifier becomes mandatory. Contrariwise, in xcode 8< provisioning_profile_uuid becomes mandatory and provisioning_profile_specifier becomes optional. :param code_sign_identity: Code sign identity name. Usually formatted as: 'iPhone Distribution[: <Company name> (MAAYFEXXXX)]' :param development_team: Development team identifier string. Usually formatted as: 'MAAYFEXXXX' :param provisioning_profile_uuid: Provisioning profile UUID string. Usually formatted as: '6f1ffc4d-xxxx-xxxx-xxxx-6dc186280e1e' :param provisioning_profile_specifier: Provisioning profile specifier (a.k.a. name) string. :param target_name: Target name or list of target names to add the flag to or None for every target :param configuration_name: Configuration name to add the flag to or None for every configuration :return:
Adds the code sign information to the project and creates the appropriate flags in the configuration. In xcode 8+ the provisioning_profile_uuid becomes optional, and the provisioning_profile_specifier becomes mandatory. Contrariwise, in xcode 8< provisioning_profile_uuid becomes mandatory and provisioning_profile_specifier becomes optional.
[ "Adds", "the", "code", "sign", "information", "to", "the", "project", "and", "creates", "the", "appropriate", "flags", "in", "the", "configuration", ".", "In", "xcode", "8", "+", "the", "provisioning_profile_uuid", "becomes", "optional", "and", "the", "provision...
def add_code_sign(self, code_sign_identity, development_team, provisioning_profile_uuid, provisioning_profile_specifier, target_name=None, configuration_name=None): """ Adds the code sign information to the project and creates the appropriate flags in the configuration. In xcode 8+ the provisioning_profile_uuid becomes optional, and the provisioning_profile_specifier becomes mandatory. Contrariwise, in xcode 8< provisioning_profile_uuid becomes mandatory and provisioning_profile_specifier becomes optional. :param code_sign_identity: Code sign identity name. Usually formatted as: 'iPhone Distribution[: <Company name> (MAAYFEXXXX)]' :param development_team: Development team identifier string. Usually formatted as: 'MAAYFEXXXX' :param provisioning_profile_uuid: Provisioning profile UUID string. Usually formatted as: '6f1ffc4d-xxxx-xxxx-xxxx-6dc186280e1e' :param provisioning_profile_specifier: Provisioning profile specifier (a.k.a. name) string. :param target_name: Target name or list of target names to add the flag to or None for every target :param configuration_name: Configuration name to add the flag to or None for every configuration :return: """ self.set_flags('CODE_SIGN_IDENTITY[sdk=iphoneos*]', code_sign_identity, target_name, configuration_name) self.set_flags('DEVELOPMENT_TEAM', development_team, target_name, configuration_name) self.set_flags('PROVISIONING_PROFILE', provisioning_profile_uuid, target_name, configuration_name) self.set_flags('PROVISIONING_PROFILE_SPECIFIER', provisioning_profile_specifier, target_name, configuration_name) for target in self.objects.get_targets(target_name): self.objects[self.rootObject].set_provisioning_style(PBXProvisioningTypes.MANUAL, target)
[ "def", "add_code_sign", "(", "self", ",", "code_sign_identity", ",", "development_team", ",", "provisioning_profile_uuid", ",", "provisioning_profile_specifier", ",", "target_name", "=", "None", ",", "configuration_name", "=", "None", ")", ":", "self", ".", "set_flags...
https://github.com/kronenthaler/mod-pbxproj/blob/e848ce35d677346d84c83f7979a49fd6d298d843/pbxproj/pbxextensions/ProjectFlags.py#L244-L266
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/database.py
python
EggInfoDistribution.check_installed_files
(self)
return mismatches
Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value.
Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value.
[ "Checks", "that", "the", "hashes", "and", "sizes", "of", "the", "files", "in", "RECORD", "are", "matched", "by", "the", "files", "themselves", ".", "Returns", "a", "(", "possibly", "empty", ")", "list", "of", "mismatches", ".", "Each", "entry", "in", "th...
def check_installed_files(self): """ Checks that the hashes and sizes of the files in ``RECORD`` are matched by the files themselves. Returns a (possibly empty) list of mismatches. Each entry in the mismatch list will be a tuple consisting of the path, 'exists', 'size' or 'hash' according to what didn't match (existence is checked first, then size, then hash), the expected value and the actual value. """ mismatches = [] record_path = os.path.join(self.path, 'installed-files.txt') if os.path.exists(record_path): for path, _, _ in self.list_installed_files(): if path == record_path: continue if not os.path.exists(path): mismatches.append((path, 'exists', True, False)) return mismatches
[ "def", "check_installed_files", "(", "self", ")", ":", "mismatches", "=", "[", "]", "record_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'installed-files.txt'", ")", "if", "os", ".", "path", ".", "exists", "(", "record_path...
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/distlib/database.py#L958-L975
obspy/obspy
0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f
obspy/core/event/event.py
python
Event.preferred_focal_mechanism
(self)
return self.preferred_focal_mechanism_id.get_referred_object()
Returns the preferred focal mechanism
Returns the preferred focal mechanism
[ "Returns", "the", "preferred", "focal", "mechanism" ]
def preferred_focal_mechanism(self): """ Returns the preferred focal mechanism """ if self.preferred_focal_mechanism_id is None: return None return self.preferred_focal_mechanism_id.get_referred_object()
[ "def", "preferred_focal_mechanism", "(", "self", ")", ":", "if", "self", ".", "preferred_focal_mechanism_id", "is", "None", ":", "return", "None", "return", "self", ".", "preferred_focal_mechanism_id", ".", "get_referred_object", "(", ")" ]
https://github.com/obspy/obspy/blob/0ee5a0d2db293c8d5d4c3b1f148a6c5a85fea55f/obspy/core/event/event.py#L168-L174
dcowden/cadquery
90b609dcc14676334211dfec9389660af8d116d0
cadquery/freecad_impl/geom.py
python
Plane.rotateShapes
(self, listOfShapes, rotationMatrix)
return resultWires
Rotate the listOfShapes by the supplied rotationMatrix @param listOfShapes is a list of shape objects @param rotationMatrix is a geom.Matrix object. returns a list of shape objects rotated according to the rotationMatrix.
Rotate the listOfShapes by the supplied rotationMatrix
[ "Rotate", "the", "listOfShapes", "by", "the", "supplied", "rotationMatrix" ]
def rotateShapes(self, listOfShapes, rotationMatrix): """Rotate the listOfShapes by the supplied rotationMatrix @param listOfShapes is a list of shape objects @param rotationMatrix is a geom.Matrix object. returns a list of shape objects rotated according to the rotationMatrix. """ # Compute rotation matrix (global --> local --> rotate --> global). # rm = self.plane.fG.multiply(matrix).multiply(self.plane.rG) # rm = self.computeTransform(rotationMatrix) # There might be a better way, but to do this rotation takes 3 steps: # - transform geometry to local coordinates # - then rotate about x # - then transform back to global coordinates. resultWires = [] for w in listOfShapes: mirrored = w.transformGeometry(rotationMatrix.wrapped) # If the first vertex of the second wire is not coincident with the # first or last vertices of the first wire we have to fix the wire # so that it will mirror correctly. if ((mirrored.wrapped.Vertexes[0].X == w.wrapped.Vertexes[0].X and mirrored.wrapped.Vertexes[0].Y == w.wrapped.Vertexes[0].Y and mirrored.wrapped.Vertexes[0].Z == w.wrapped.Vertexes[0].Z) or (mirrored.wrapped.Vertexes[0].X == w.wrapped.Vertexes[-1].X and mirrored.wrapped.Vertexes[0].Y == w.wrapped.Vertexes[-1].Y and mirrored.wrapped.Vertexes[0].Z == w.wrapped.Vertexes[-1].Z)): resultWires.append(mirrored) else: # Make sure that our mirrored edges meet up and are ordered # properly. aEdges = w.wrapped.Edges aEdges.extend(mirrored.wrapped.Edges) comp = FreeCADPart.Compound(aEdges) mirroredWire = comp.connectEdgesToWires(False).Wires[0] resultWires.append(cadquery.Shape.cast(mirroredWire)) return resultWires
[ "def", "rotateShapes", "(", "self", ",", "listOfShapes", ",", "rotationMatrix", ")", ":", "# Compute rotation matrix (global --> local --> rotate --> global).", "# rm = self.plane.fG.multiply(matrix).multiply(self.plane.rG)", "# rm = self.computeTransform(rotationMatrix)", "# There might b...
https://github.com/dcowden/cadquery/blob/90b609dcc14676334211dfec9389660af8d116d0/cadquery/freecad_impl/geom.py#L600-L641
francisck/DanderSpritz_docs
86bb7caca5a957147f120b18bb5c31f299914904
Python/Core/Lib/email/iterators.py
python
walk
(self)
Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator.
Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator.
[ "Walk", "over", "the", "message", "tree", "yielding", "each", "subpart", ".", "The", "walk", "is", "performed", "in", "depth", "-", "first", "order", ".", "This", "method", "is", "a", "generator", "." ]
def walk(self): """Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. """ yield self if self.is_multipart(): for subpart in self.get_payload(): for subsubpart in subpart.walk(): yield subsubpart
[ "def", "walk", "(", "self", ")", ":", "yield", "self", "if", "self", ".", "is_multipart", "(", ")", ":", "for", "subpart", "in", "self", ".", "get_payload", "(", ")", ":", "for", "subsubpart", "in", "subpart", ".", "walk", "(", ")", ":", "yield", "...
https://github.com/francisck/DanderSpritz_docs/blob/86bb7caca5a957147f120b18bb5c31f299914904/Python/Core/Lib/email/iterators.py#L14-L24
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/ipykernel/serialize.py
python
unpack_apply_message
(bufs, g=None, copy=True)
return f,args,kwargs
unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs
unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs
[ "unpack", "f", "args", "kwargs", "from", "buffers", "packed", "by", "pack_apply_message", "()", "Returns", ":", "original", "f", "args", "kwargs" ]
def unpack_apply_message(bufs, g=None, copy=True): """unpack f,args,kwargs from buffers packed by pack_apply_message() Returns: original f,args,kwargs""" bufs = list(bufs) # allow us to pop assert len(bufs) >= 2, "not enough buffers!" pf = buffer_to_bytes_py2(bufs.pop(0)) f = uncan(pickle.loads(pf), g) pinfo = buffer_to_bytes_py2(bufs.pop(0)) info = pickle.loads(pinfo) arg_bufs, kwarg_bufs = bufs[:info['narg_bufs']], bufs[info['narg_bufs']:] args = [] for i in range(info['nargs']): arg, arg_bufs = deserialize_object(arg_bufs, g) args.append(arg) args = tuple(args) assert not arg_bufs, "Shouldn't be any arg bufs left over" kwargs = {} for key in info['kw_keys']: kwarg, kwarg_bufs = deserialize_object(kwarg_bufs, g) kwargs[key] = kwarg assert not kwarg_bufs, "Shouldn't be any kwarg bufs left over" return f,args,kwargs
[ "def", "unpack_apply_message", "(", "bufs", ",", "g", "=", "None", ",", "copy", "=", "True", ")", ":", "bufs", "=", "list", "(", "bufs", ")", "# allow us to pop", "assert", "len", "(", "bufs", ")", ">=", "2", ",", "\"not enough buffers!\"", "pf", "=", ...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/ipykernel/serialize.py#L162-L186
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/ims/v20200713/models.py
python
ObjectDetail.__init__
(self)
r""" :param Id: 序号 :type Id: int :param Name: 标签名称 :type Name: str :param Value: 标签值, 当标签为二维码时,表示URL地址,如Name为QrCode时,Value为"http//abc.com/aaa" :type Value: str :param Score: 分数 :type Score: int :param Location: 检测框坐标 :type Location: :class:`tencentcloud.ims.v20200713.models.Location`
r""" :param Id: 序号 :type Id: int :param Name: 标签名称 :type Name: str :param Value: 标签值, 当标签为二维码时,表示URL地址,如Name为QrCode时,Value为"http//abc.com/aaa" :type Value: str :param Score: 分数 :type Score: int :param Location: 检测框坐标 :type Location: :class:`tencentcloud.ims.v20200713.models.Location`
[ "r", ":", "param", "Id", ":", "序号", ":", "type", "Id", ":", "int", ":", "param", "Name", ":", "标签名称", ":", "type", "Name", ":", "str", ":", "param", "Value", ":", "标签值,", "当标签为二维码时,表示URL地址,如Name为QrCode时,Value为", "http", "//", "abc", ".", "com", "/", ...
def __init__(self): r""" :param Id: 序号 :type Id: int :param Name: 标签名称 :type Name: str :param Value: 标签值, 当标签为二维码时,表示URL地址,如Name为QrCode时,Value为"http//abc.com/aaa" :type Value: str :param Score: 分数 :type Score: int :param Location: 检测框坐标 :type Location: :class:`tencentcloud.ims.v20200713.models.Location` """ self.Id = None self.Name = None self.Value = None self.Score = None self.Location = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "Id", "=", "None", "self", ".", "Name", "=", "None", "self", ".", "Value", "=", "None", "self", ".", "Score", "=", "None", "self", ".", "Location", "=", "None" ]
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/ims/v20200713/models.py#L744-L762
knownsec/Pocsuite
877d1b1604629b8dcd6e53b167c3c98249e5e94f
pocsuite/thirdparty/requests/packages/urllib3/_collections.py
python
HTTPHeaderDict.iteritems
(self)
Iterate over all header lines, including duplicate ones.
Iterate over all header lines, including duplicate ones.
[ "Iterate", "over", "all", "header", "lines", "including", "duplicate", "ones", "." ]
def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = _dict_getitem(self, key) for val in vals[1:]: yield vals[0], val
[ "def", "iteritems", "(", "self", ")", ":", "for", "key", "in", "self", ":", "vals", "=", "_dict_getitem", "(", "self", ",", "key", ")", "for", "val", "in", "vals", "[", "1", ":", "]", ":", "yield", "vals", "[", "0", "]", ",", "val" ]
https://github.com/knownsec/Pocsuite/blob/877d1b1604629b8dcd6e53b167c3c98249e5e94f/pocsuite/thirdparty/requests/packages/urllib3/_collections.py#L290-L295
dcowden/cadquery
90b609dcc14676334211dfec9389660af8d116d0
cadquery/cq.py
python
CQ.vertices
(self, selector=None)
return self._selectObjects('Vertices', selector)
Select the vertices of objects on the stack, optionally filtering the selection. If there are multiple objects on the stack, the vertices of all objects are collected and a list of all the distinct vertices is returned. :param selector: :type selector: None, a Selector object, or a string selector expression. :return: a CQ object who's stack contains the *distinct* vertices of *all* objects on the current stack, after being filtered by the selector, if provided If there are no vertices for any objects on the current stack, an empty CQ object is returned The typical use is to select the vertices of a single object on the stack. For example:: Workplane().box(1,1,1).faces("+Z").vertices().size() returns 4, because the topmost face of cube will contain four vertices. While this:: Workplane().box(1,1,1).faces().vertices().size() returns 8, because a cube has a total of 8 vertices **Note** Circles are peculiar, they have a single vertex at the center! :py:class:`StringSyntaxSelector`
Select the vertices of objects on the stack, optionally filtering the selection. If there are multiple objects on the stack, the vertices of all objects are collected and a list of all the distinct vertices is returned.
[ "Select", "the", "vertices", "of", "objects", "on", "the", "stack", "optionally", "filtering", "the", "selection", ".", "If", "there", "are", "multiple", "objects", "on", "the", "stack", "the", "vertices", "of", "all", "objects", "are", "collected", "and", "...
def vertices(self, selector=None): """ Select the vertices of objects on the stack, optionally filtering the selection. If there are multiple objects on the stack, the vertices of all objects are collected and a list of all the distinct vertices is returned. :param selector: :type selector: None, a Selector object, or a string selector expression. :return: a CQ object who's stack contains the *distinct* vertices of *all* objects on the current stack, after being filtered by the selector, if provided If there are no vertices for any objects on the current stack, an empty CQ object is returned The typical use is to select the vertices of a single object on the stack. For example:: Workplane().box(1,1,1).faces("+Z").vertices().size() returns 4, because the topmost face of cube will contain four vertices. While this:: Workplane().box(1,1,1).faces().vertices().size() returns 8, because a cube has a total of 8 vertices **Note** Circles are peculiar, they have a single vertex at the center! :py:class:`StringSyntaxSelector` """ return self._selectObjects('Vertices', selector)
[ "def", "vertices", "(", "self", ",", "selector", "=", "None", ")", ":", "return", "self", ".", "_selectObjects", "(", "'Vertices'", ",", "selector", ")" ]
https://github.com/dcowden/cadquery/blob/90b609dcc14676334211dfec9389660af8d116d0/cadquery/cq.py#L493-L522
alessandrodd/apk_api_key_extractor
cbc2a8b02a5758886ac6aa08ed4b1b193e2b02aa
apk_analyzer.py
python
analyze_decoded_apk
(decoded_apk_folder)
return apikey_postfiltered, extracted, package, version_code, version_name
Given a decoded apk (e.g. decoded using apktool), analyzes its content to extract API keys :param decoded_apk_folder: folder that contains the decoded apk :return: a list of api keys found, the name of the package, the version code and the version name
Given a decoded apk (e.g. decoded using apktool), analyzes its content to extract API keys
[ "Given", "a", "decoded", "apk", "(", "e", ".", "g", ".", "decoded", "using", "apktool", ")", "analyzes", "its", "content", "to", "extract", "API", "keys" ]
def analyze_decoded_apk(decoded_apk_folder): """ Given a decoded apk (e.g. decoded using apktool), analyzes its content to extract API keys :param decoded_apk_folder: folder that contains the decoded apk :return: a list of api keys found, the name of the package, the version code and the version name """ manifest = os.path.join(decoded_apk_folder, "AndroidManifest.xml") if not os.path.exists(manifest): logging.error("Unable to find manifest file for {0}".format(decoded_apk_folder)) return manifest_parser = AndroidManifestXmlParser(manifest) package = manifest_parser.get_package() if not package: logging.error("Unable to determine package name for {0}".format(decoded_apk_folder)) return version_code = 0 version_name = "0" yml_file = os.path.join(decoded_apk_folder, "apktool.yml") if not os.path.exists(yml_file): logging.warning("Unable to find apktool.yml file for {0}".format(decoded_apk_folder)) else: try: yml_parser = ApktoolYmlParser(yml_file) version_code = int(yml_parser.get_version_code()) version_name = yml_parser.get_version_name() except (IOError, ValueError) as e: logging.error("Unable to parse apktool.yml; {0}".format(e)) extracted = extract_metadata_resource(manifest_parser) extracted += extract_strings_resource(decoded_apk_folder) extracted += extract_smali_strings(decoded_apk_folder, package, manifest_parser) extracted += extract_native_strings(decoded_apk_folder) apikey_strings = analyze_strings(extracted) apikey_postfiltered = [] for mystring in apikey_strings: if s_filter.post_filter_mystring(mystring): apikey_postfiltered.append(mystring) return apikey_postfiltered, extracted, package, version_code, version_name
[ "def", "analyze_decoded_apk", "(", "decoded_apk_folder", ")", ":", "manifest", "=", "os", ".", "path", ".", "join", "(", "decoded_apk_folder", ",", "\"AndroidManifest.xml\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "manifest", ")", ":", "log...
https://github.com/alessandrodd/apk_api_key_extractor/blob/cbc2a8b02a5758886ac6aa08ed4b1b193e2b02aa/apk_analyzer.py#L223-L260
allegro/ralph
1e4a9e1800d5f664abaef2624b8bf7512df279ce
src/ralph/virtual/management/commands/openstack_sync.py
python
Command._process_servers
(self, servers, project)
Add/modify/remove servers within project
Add/modify/remove servers within project
[ "Add", "/", "modify", "/", "remove", "servers", "within", "project" ]
def _process_servers(self, servers, project): """Add/modify/remove servers within project""" for server_id, server in servers.items(): try: ralph_server = ( self.ralph_projects[project.project_id]['servers'][server_id] # noqa ) except KeyError: self._add_server(server, server_id, project) self.summary['new_instances'] += 1 else: modified = self._update_server( server, server_id, ralph_server, ) if modified: self.summary['mod_instances'] += 1 self.summary['total_instances'] += 1 self._cleanup_servers(servers, project.project_id)
[ "def", "_process_servers", "(", "self", ",", "servers", ",", "project", ")", ":", "for", "server_id", ",", "server", "in", "servers", ".", "items", "(", ")", ":", "try", ":", "ralph_server", "=", "(", "self", ".", "ralph_projects", "[", "project", ".", ...
https://github.com/allegro/ralph/blob/1e4a9e1800d5f664abaef2624b8bf7512df279ce/src/ralph/virtual/management/commands/openstack_sync.py#L417-L436
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/xml/sax/xmlreader.py
python
InputSource.getSystemId
(self)
return self.__system_id
Returns the system identifier of this InputSource.
Returns the system identifier of this InputSource.
[ "Returns", "the", "system", "identifier", "of", "this", "InputSource", "." ]
def getSystemId(self): "Returns the system identifier of this InputSource." return self.__system_id
[ "def", "getSystemId", "(", "self", ")", ":", "return", "self", ".", "__system_id" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/xml/sax/xmlreader.py#L222-L224
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_12/paramiko/transport.py
python
Transport.start_client
(self, event=None)
Negotiate a new SSH2 session as a client. This is the first step after creating a new L{Transport}. A separate thread is created for protocol negotiation. If an event is passed in, this method returns immediately. When negotiation is done (successful or not), the given C{Event} will be triggered. On failure, L{is_active} will return C{False}. (Since 1.4) If C{event} is C{None}, this method will not return until negotation is done. On success, the method returns normally. Otherwise an SSHException is raised. After a successful negotiation, you will usually want to authenticate, calling L{auth_password <Transport.auth_password>} or L{auth_publickey <Transport.auth_publickey>}. @note: L{connect} is a simpler method for connecting as a client. @note: After calling this method (or L{start_server} or L{connect}), you should no longer directly read from or write to the original socket object. @param event: an event to trigger when negotiation is complete (optional) @type event: threading.Event @raise SSHException: if negotiation fails (and no C{event} was passed in)
Negotiate a new SSH2 session as a client. This is the first step after creating a new L{Transport}. A separate thread is created for protocol negotiation.
[ "Negotiate", "a", "new", "SSH2", "session", "as", "a", "client", ".", "This", "is", "the", "first", "step", "after", "creating", "a", "new", "L", "{", "Transport", "}", ".", "A", "separate", "thread", "is", "created", "for", "protocol", "negotiation", "....
def start_client(self, event=None): """ Negotiate a new SSH2 session as a client. This is the first step after creating a new L{Transport}. A separate thread is created for protocol negotiation. If an event is passed in, this method returns immediately. When negotiation is done (successful or not), the given C{Event} will be triggered. On failure, L{is_active} will return C{False}. (Since 1.4) If C{event} is C{None}, this method will not return until negotation is done. On success, the method returns normally. Otherwise an SSHException is raised. After a successful negotiation, you will usually want to authenticate, calling L{auth_password <Transport.auth_password>} or L{auth_publickey <Transport.auth_publickey>}. @note: L{connect} is a simpler method for connecting as a client. @note: After calling this method (or L{start_server} or L{connect}), you should no longer directly read from or write to the original socket object. @param event: an event to trigger when negotiation is complete (optional) @type event: threading.Event @raise SSHException: if negotiation fails (and no C{event} was passed in) """ self.active = True if event is not None: # async, return immediately and let the app poll for completion self.completion_event = event self.start() return # synchronous, wait for a result self.completion_event = event = threading.Event() self.start() Random.atfork() while True: event.wait(0.1) if not self.active: e = self.get_exception() if e is not None: raise e raise SSHException('Negotiation failed.') if event.isSet(): break
[ "def", "start_client", "(", "self", ",", "event", "=", "None", ")", ":", "self", ".", "active", "=", "True", "if", "event", "is", "not", "None", ":", "# async, return immediately and let the app poll for completion", "self", ".", "completion_event", "=", "event", ...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_12/paramiko/transport.py#L419-L469
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
tools/sqlmap/tamper/equaltolike.py
python
tamper
(payload, **kwargs)
return retVal
Replaces all occurances of operator equal ('=') with operator 'LIKE' Tested against: * Microsoft SQL Server 2005 * MySQL 4, 5.0 and 5.5 Notes: * Useful to bypass weak and bespoke web application firewalls that filter the equal character ('=') * The LIKE operator is SQL standard. Hence, this tamper script should work against all (?) databases >>> tamper('SELECT * FROM users WHERE id=1') 'SELECT * FROM users WHERE id LIKE 1'
Replaces all occurances of operator equal ('=') with operator 'LIKE'
[ "Replaces", "all", "occurances", "of", "operator", "equal", "(", "=", ")", "with", "operator", "LIKE" ]
def tamper(payload, **kwargs): """ Replaces all occurances of operator equal ('=') with operator 'LIKE' Tested against: * Microsoft SQL Server 2005 * MySQL 4, 5.0 and 5.5 Notes: * Useful to bypass weak and bespoke web application firewalls that filter the equal character ('=') * The LIKE operator is SQL standard. Hence, this tamper script should work against all (?) databases >>> tamper('SELECT * FROM users WHERE id=1') 'SELECT * FROM users WHERE id LIKE 1' """ def process(match): word = match.group() word = "%sLIKE%s" % (" " if word[0] != " " else "", " " if word[-1] != " " else "") return word retVal = payload if payload: retVal = re.sub(r"\s*=\s*", lambda match: process(match), retVal) return retVal
[ "def", "tamper", "(", "payload", ",", "*", "*", "kwargs", ")", ":", "def", "process", "(", "match", ")", ":", "word", "=", "match", ".", "group", "(", ")", "word", "=", "\"%sLIKE%s\"", "%", "(", "\" \"", "if", "word", "[", "0", "]", "!=", "\" \""...
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/tools/sqlmap/tamper/equaltolike.py#L20-L49
kensho-technologies/graphql-compiler
4318443b7b2512a059f3616112bfc40bbf8eec06
graphql_compiler/compiler/common.py
python
_compile_graphql_generic
( target_backend: Backend, schema_info: Union[CommonSchemaInfo, SQLAlchemySchemaInfo], graphql_string: str, )
return CompilationResult( query=query, language=target_backend.language, output_metadata=ir_and_metadata.output_metadata, input_metadata=ir_and_metadata.input_metadata, )
Compile the GraphQL input, lowering and emitting the query using the given functions. Args: target_backend: Backend used to compile the query schema_info: target_backend.schemaInfoClass containing all necessary schema information. graphql_string: str, GraphQL query to compile to the target language Returns: CompilationResult object
Compile the GraphQL input, lowering and emitting the query using the given functions.
[ "Compile", "the", "GraphQL", "input", "lowering", "and", "emitting", "the", "query", "using", "the", "given", "functions", "." ]
def _compile_graphql_generic( target_backend: Backend, schema_info: Union[CommonSchemaInfo, SQLAlchemySchemaInfo], graphql_string: str, ) -> CompilationResult: """Compile the GraphQL input, lowering and emitting the query using the given functions. Args: target_backend: Backend used to compile the query schema_info: target_backend.schemaInfoClass containing all necessary schema information. graphql_string: str, GraphQL query to compile to the target language Returns: CompilationResult object """ ir_and_metadata = graphql_to_ir( schema_info.schema, graphql_string, type_equivalence_hints=schema_info.type_equivalence_hints, ) lowered_ir_blocks = target_backend.lower_func(schema_info, ir_and_metadata) query = target_backend.emit_func(schema_info, lowered_ir_blocks) return CompilationResult( query=query, language=target_backend.language, output_metadata=ir_and_metadata.output_metadata, input_metadata=ir_and_metadata.input_metadata, )
[ "def", "_compile_graphql_generic", "(", "target_backend", ":", "Backend", ",", "schema_info", ":", "Union", "[", "CommonSchemaInfo", ",", "SQLAlchemySchemaInfo", "]", ",", "graphql_string", ":", "str", ",", ")", "->", "CompilationResult", ":", "ir_and_metadata", "="...
https://github.com/kensho-technologies/graphql-compiler/blob/4318443b7b2512a059f3616112bfc40bbf8eec06/graphql_compiler/compiler/common.py#L87-L115
google-research/football
c5c6a5c1d587a94673597ff6d61da43044a0c9ac
gfootball/examples/run_ppo2.py
python
create_single_football_env
(iprocess)
return env
Creates gfootball environment.
Creates gfootball environment.
[ "Creates", "gfootball", "environment", "." ]
def create_single_football_env(iprocess): """Creates gfootball environment.""" env = football_env.create_environment( env_name=FLAGS.level, stacked=('stacked' in FLAGS.state), rewards=FLAGS.reward_experiment, logdir=logger.get_dir(), write_goal_dumps=FLAGS.dump_scores and (iprocess == 0), write_full_episode_dumps=FLAGS.dump_full_episodes and (iprocess == 0), render=FLAGS.render and (iprocess == 0), dump_frequency=50 if FLAGS.render and iprocess == 0 else 0) env = monitor.Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(), str(iprocess))) return env
[ "def", "create_single_football_env", "(", "iprocess", ")", ":", "env", "=", "football_env", ".", "create_environment", "(", "env_name", "=", "FLAGS", ".", "level", ",", "stacked", "=", "(", "'stacked'", "in", "FLAGS", ".", "state", ")", ",", "rewards", "=", ...
https://github.com/google-research/football/blob/c5c6a5c1d587a94673597ff6d61da43044a0c9ac/gfootball/examples/run_ppo2.py#L70-L82
City-Bureau/city-scrapers
b295d0aa612e3979a9fccab7c5f55ecea9ed074c
city_scrapers/spiders/chi_ssa_26.py
python
ChiSsa26Spider.parse
(self, response)
`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
`parse` should always `yield` Meeting items.
[ "parse", "should", "always", "yield", "Meeting", "items", "." ]
def parse(self, response): """ `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs. """ self.link_map = {} self._parse_links(response) self._parse_upcoming(response) for start, links in self.link_map.items(): meeting = Meeting( title="Commission", description="", classification=COMMISSION, start=start, end=None, all_day=False, time_notes="", location=self.location, links=links, source=response.url, ) meeting["status"] = self._get_status(meeting) meeting["id"] = self._get_id(meeting) yield meeting
[ "def", "parse", "(", "self", ",", "response", ")", ":", "self", ".", "link_map", "=", "{", "}", "self", ".", "_parse_links", "(", "response", ")", "self", ".", "_parse_upcoming", "(", "response", ")", "for", "start", ",", "links", "in", "self", ".", ...
https://github.com/City-Bureau/city-scrapers/blob/b295d0aa612e3979a9fccab7c5f55ecea9ed074c/city_scrapers/spiders/chi_ssa_26.py#L19-L47
Telefonica/HomePWN
080398174159f856f4155dcb155c6754d1f85ad8
utils/opendrop/util.py
python
AirDropUtil.generate_file_icon
(file_path)
return file_icon
Generates a small and a big thumbnail of an image This will make it possible to preview the sent file :param file_path: The path to the image
Generates a small and a big thumbnail of an image This will make it possible to preview the sent file
[ "Generates", "a", "small", "and", "a", "big", "thumbnail", "of", "an", "image", "This", "will", "make", "it", "possible", "to", "preview", "the", "sent", "file" ]
def generate_file_icon(file_path): """ Generates a small and a big thumbnail of an image This will make it possible to preview the sent file :param file_path: The path to the image """ im = Image.open(file_path) # rotate according to EXIF tags try: exif = dict((ExifTags.TAGS[k], v) for k, v in im._getexif().items() if k in ExifTags.TAGS) angles = {3: 180, 6: 270, 8: 90} orientation = exif['Orientation'] if orientation in angles.keys(): im = im.rotate(angles[orientation], expand=True) except AttributeError: pass # no EXIF data available # Big image im.thumbnail((540, 540), Image.ANTIALIAS) imgByteArr = io.BytesIO() im.save(imgByteArr, format='JPEG2000') file_icon = imgByteArr.getvalue() # Small image #im.thumbnail((64, 64), Image.ANTIALIAS) #imgByteArr = io.BytesIO() #im.save(imgByteArr, format='JPEG2000') #small_file_icon = imgByteArr.getvalue() return file_icon
[ "def", "generate_file_icon", "(", "file_path", ")", ":", "im", "=", "Image", ".", "open", "(", "file_path", ")", "# rotate according to EXIF tags", "try", ":", "exif", "=", "dict", "(", "(", "ExifTags", ".", "TAGS", "[", "k", "]", ",", "v", ")", "for", ...
https://github.com/Telefonica/HomePWN/blob/080398174159f856f4155dcb155c6754d1f85ad8/utils/opendrop/util.py#L168-L199
nccgroup/ScoutSuite
b9b8e201a45bd63835f611eec67fe3bb7c892a0a
ScoutSuite/providers/gcp/provider.py
python
GCPProvider._match_networks_and_instances
(self)
For each network, math instances in that network :return:
For each network, math instances in that network
[ "For", "each", "network", "math", "instances", "in", "that", "network" ]
def _match_networks_and_instances(self): """ For each network, math instances in that network :return: """ try: if 'computeengine' in self.service_list: for project in self.services['computeengine']['projects'].values(): for network in project['networks'].values(): network['instances'] = [] for zone in project['zones'].values(): # Skip the counts contained in the zones dictionary if zone is int: continue for instance in zone['instances'].values(): instance['network_id'] = None for network_interface in instance['network_interfaces']: if network_interface['network'] == network['network_url']: network['instances'].append({'instance_id': instance['id'], 'instance_zone': instance['zone']}) network_interface['network_id'] = network['id'] except Exception as e: print_exception('Unable to match instances and networks: {}'.format(e))
[ "def", "_match_networks_and_instances", "(", "self", ")", ":", "try", ":", "if", "'computeengine'", "in", "self", ".", "service_list", ":", "for", "project", "in", "self", ".", "services", "[", "'computeengine'", "]", "[", "'projects'", "]", ".", "values", "...
https://github.com/nccgroup/ScoutSuite/blob/b9b8e201a45bd63835f611eec67fe3bb7c892a0a/ScoutSuite/providers/gcp/provider.py#L116-L140
bslatkin/effectivepython
4ae6f3141291ea137eb29a245bf889dbc8091713
example_code/item_61.py
python
AsyncSession.send_number
(self)
[]
async def send_number(self): # Changed guess = self.next_guess() self.guesses.append(guess) await self.send(format(guess))
[ "async", "def", "send_number", "(", "self", ")", ":", "# Changed", "guess", "=", "self", ".", "next_guess", "(", ")", "self", ".", "guesses", ".", "append", "(", "guess", ")", "await", "self", ".", "send", "(", "format", "(", "guess", ")", ")" ]
https://github.com/bslatkin/effectivepython/blob/4ae6f3141291ea137eb29a245bf889dbc8091713/example_code/item_61.py#L322-L325
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
futures2/ctp/__init__.py
python
TraderApi.OnRspQryEWarrantOffset
(self, pEWarrantOffset, pRspInfo, nRequestID, bIsLast)
请求查询仓单折抵信息响应
请求查询仓单折抵信息响应
[ "请求查询仓单折抵信息响应" ]
def OnRspQryEWarrantOffset(self, pEWarrantOffset, pRspInfo, nRequestID, bIsLast): """请求查询仓单折抵信息响应"""
[ "def", "OnRspQryEWarrantOffset", "(", "self", ",", "pEWarrantOffset", ",", "pRspInfo", ",", "nRequestID", ",", "bIsLast", ")", ":" ]
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/futures2/ctp/__init__.py#L632-L633
CouchPotato/CouchPotatoV1
135b3331d1b88ef645e29b76f2d4cc4a732c9232
library/sqlalchemy/sql/expression.py
python
ClauseElement.params
(self, *optionaldict, **kwargs)
return self._params(False, optionaldict, kwargs)
Return a copy with :func:`bindparam()` elments replaced. Returns a copy of this ClauseElement with :func:`bindparam()` elements replaced with values taken from the given dictionary:: >>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7}
Return a copy with :func:`bindparam()` elments replaced.
[ "Return", "a", "copy", "with", ":", "func", ":", "bindparam", "()", "elments", "replaced", "." ]
def params(self, *optionaldict, **kwargs): """Return a copy with :func:`bindparam()` elments replaced. Returns a copy of this ClauseElement with :func:`bindparam()` elements replaced with values taken from the given dictionary:: >>> clause = column('x') + bindparam('foo') >>> print clause.compile().params {'foo':None} >>> print clause.params({'foo':7}).compile().params {'foo':7} """ return self._params(False, optionaldict, kwargs)
[ "def", "params", "(", "self", ",", "*", "optionaldict", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_params", "(", "False", ",", "optionaldict", ",", "kwargs", ")" ]
https://github.com/CouchPotato/CouchPotatoV1/blob/135b3331d1b88ef645e29b76f2d4cc4a732c9232/library/sqlalchemy/sql/expression.py#L1230-L1243
smiley-debugger/smiley
0fd0c5df7196b8f18b2f938f43dc67f6114c2f3c
smiley/local.py
python
LocalPublisher.end_run
(self, run_id, end_time, message, traceback, stats)
Called when an 'end_run' event is seen.
Called when an 'end_run' event is seen.
[ "Called", "when", "an", "end_run", "event", "is", "seen", "." ]
def end_run(self, run_id, end_time, message, traceback, stats): """Called when an 'end_run' event is seen. """ self._q.put(('end', (run_id, end_time, message, traceback, stats))) self._stop()
[ "def", "end_run", "(", "self", ",", "run_id", ",", "end_time", ",", "message", ",", "traceback", ",", "stats", ")", ":", "self", ".", "_q", ".", "put", "(", "(", "'end'", ",", "(", "run_id", ",", "end_time", ",", "message", ",", "traceback", ",", "...
https://github.com/smiley-debugger/smiley/blob/0fd0c5df7196b8f18b2f938f43dc67f6114c2f3c/smiley/local.py#L83-L87
phantomcyber/playbooks
9e850ecc44cb98c5dde53784744213a1ed5799bd
alert_escalation_for_attacked_executives.py
python
escalate_alert
(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs)
return
[]
def escalate_alert(action=None, success=None, container=None, results=None, handle=None, filtered_artifacts=None, filtered_results=None, custom_function=None, **kwargs): phantom.debug('escalate_alert() called') phantom.set_sensitivity(container=container, sensitivity="red") phantom.set_severity(container=container, severity="high") return
[ "def", "escalate_alert", "(", "action", "=", "None", ",", "success", "=", "None", ",", "container", "=", "None", ",", "results", "=", "None", ",", "handle", "=", "None", ",", "filtered_artifacts", "=", "None", ",", "filtered_results", "=", "None", ",", "...
https://github.com/phantomcyber/playbooks/blob/9e850ecc44cb98c5dde53784744213a1ed5799bd/alert_escalation_for_attacked_executives.py#L16-L23
suurjaak/Skyperious
6a4f264dbac8d326c2fa8aeb5483dbca987860bf
skyperious/gui.py
python
ChatContentSTC.RetrieveMoreMessages
(self, count=None)
Retrieves another N messages starting from current first. @param count maximum number of more messages to retrieve, defaults to conf.MaxHistoryInitialMessages / 2
Retrieves another N messages starting from current first.
[ "Retrieves", "another", "N", "messages", "starting", "from", "current", "first", "." ]
def RetrieveMoreMessages(self, count=None): """ Retrieves another N messages starting from current first. @param count maximum number of more messages to retrieve, defaults to conf.MaxHistoryInitialMessages / 2 """ if count is None: count = max(1, conf.MaxHistoryInitialMessages / 2) if not count: return center_id, stamp_from = None, None if self._messages: if self._messages_current: center_id = self._messages_current[0]["id"] stamp_from = self._messages[0]["timestamp"] elif any(self._filter.get("daterange") or []): stamp_from = util.datetime_to_epoch(self._filter["daterange"][0]) if stamp_from is None: return mm, kws = [], dict(timestamp_from=stamp_from, ascending=False, use_cache=False) busy = controls.BusyPanel(self._page or self.Parent, "Retrieving more messages.") try: for i, m in enumerate(self._db.get_messages(self._chat, **kws)): mm.append(m) if i + 1 >= count: break # for i, m self._messages[:0] = mm[::-1] # Insert ascending at front self._center_message_id = self._center_message_index = None if self._messages: rng = [self._messages[x]["datetime"].date() for x in (0, -1)] self._filter["daterange"] = rng if self._page: self._page.range_date.SetValues(*rng) self._page.chat_filter["daterange"] = rng self.RefreshMessages() if self._page: self._page.populate_chat_statistics() self._page.list_timeline.Populate(*self.GetTimelineData()) finally: busy.Close() if center_id is not None: self.FocusMessage(center_id, select=False)
[ "def", "RetrieveMoreMessages", "(", "self", ",", "count", "=", "None", ")", ":", "if", "count", "is", "None", ":", "count", "=", "max", "(", "1", ",", "conf", ".", "MaxHistoryInitialMessages", "/", "2", ")", "if", "not", "count", ":", "return", "center...
https://github.com/suurjaak/Skyperious/blob/6a4f264dbac8d326c2fa8aeb5483dbca987860bf/skyperious/gui.py#L7588-L7627
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/modulargcd.py
python
func_field_modgcd
(f, g)
return h, f.quo(h), g.quo(h)
r""" Compute the GCD of two polynomials `f` and `g` in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` using a modular algorithm. The algorithm first computes the primitive associate `\check m_{\alpha}(z)` of the minimal polynomial `m_{\alpha}` in `\mathbb{Z}[z]` and the primitive associates of `f` and `g` in `\mathbb{Z}[x_1, \ldots, x_{n-1}][z]/(\check m_{\alpha})[x_0]`. Then it computes the GCD in `\mathbb Q(x_1, \ldots, x_{n-1})[z]/(m_{\alpha}(z))[x_0]`. This is done by calculating the GCD in `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]` for suitable primes `p` and then reconstructing the coefficients with the Chinese Remainder Theorem and Rational Reconstuction. The GCD over `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]` is computed with a recursive subroutine, which evaluates the polynomials at `x_{n-1} = a` for suitable evaluation points `a \in \mathbb Z_p` and then calls itself recursively until the ground domain does no longer contain any parameters. For `\mathbb{Z}_p[z]/(\check m_{\alpha}(z))[x_0]` the Euclidean Algorithm is used. The results of those recursive calls are then interpolated and Rational Function Reconstruction is used to obtain the correct coefficients. The results, both in `\mathbb Q(x_1, \ldots, x_{n-1})[z]/(m_{\alpha}(z))[x_0]` and `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]`, are verified by a fraction free trial division. Apart from the above GCD computation some GCDs in `\mathbb Q(\alpha)[x_1, \ldots, x_{n-1}]` have to be calculated, because treating the polynomials as univariate ones can result in a spurious content of the GCD. For this ``func_field_modgcd`` is called recursively. Parameters ========== f, g : PolyElement polynomials in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` Returns ======= h : PolyElement monic GCD of the polynomials `f` and `g` cff : PolyElement cofactor of `f`, i.e. `\frac f h` cfg : PolyElement cofactor of `g`, i.e. `\frac g h` Examples ======== >>> from sympy.polys.modulargcd import func_field_modgcd >>> from sympy.polys import AlgebraicField, QQ, ring >>> from sympy import sqrt >>> A = AlgebraicField(QQ, sqrt(2)) >>> R, x = ring('x', A) >>> f = x**2 - 2 >>> g = x + sqrt(2) >>> h, cff, cfg = func_field_modgcd(f, g) >>> h == x + sqrt(2) True >>> cff * h == f True >>> cfg * h == g True >>> R, x, y = ring('x, y', A) >>> f = x**2 + 2*sqrt(2)*x*y + 2*y**2 >>> g = x + sqrt(2)*y >>> h, cff, cfg = func_field_modgcd(f, g) >>> h == x + sqrt(2)*y True >>> cff * h == f True >>> cfg * h == g True >>> f = x + sqrt(2)*y >>> g = x + y >>> h, cff, cfg = func_field_modgcd(f, g) >>> h == R.one True >>> cff * h == f True >>> cfg * h == g True References ========== 1. [Hoeij04]_
r""" Compute the GCD of two polynomials `f` and `g` in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` using a modular algorithm.
[ "r", "Compute", "the", "GCD", "of", "two", "polynomials", "f", "and", "g", "in", "\\", "mathbb", "Q", "(", "\\", "alpha", ")", "[", "x_0", "\\", "ldots", "x_", "{", "n", "-", "1", "}", "]", "using", "a", "modular", "algorithm", "." ]
def func_field_modgcd(f, g): r""" Compute the GCD of two polynomials `f` and `g` in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` using a modular algorithm. The algorithm first computes the primitive associate `\check m_{\alpha}(z)` of the minimal polynomial `m_{\alpha}` in `\mathbb{Z}[z]` and the primitive associates of `f` and `g` in `\mathbb{Z}[x_1, \ldots, x_{n-1}][z]/(\check m_{\alpha})[x_0]`. Then it computes the GCD in `\mathbb Q(x_1, \ldots, x_{n-1})[z]/(m_{\alpha}(z))[x_0]`. This is done by calculating the GCD in `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]` for suitable primes `p` and then reconstructing the coefficients with the Chinese Remainder Theorem and Rational Reconstuction. The GCD over `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]` is computed with a recursive subroutine, which evaluates the polynomials at `x_{n-1} = a` for suitable evaluation points `a \in \mathbb Z_p` and then calls itself recursively until the ground domain does no longer contain any parameters. For `\mathbb{Z}_p[z]/(\check m_{\alpha}(z))[x_0]` the Euclidean Algorithm is used. The results of those recursive calls are then interpolated and Rational Function Reconstruction is used to obtain the correct coefficients. The results, both in `\mathbb Q(x_1, \ldots, x_{n-1})[z]/(m_{\alpha}(z))[x_0]` and `\mathbb{Z}_p(x_1, \ldots, x_{n-1})[z]/(\check m_{\alpha}(z))[x_0]`, are verified by a fraction free trial division. Apart from the above GCD computation some GCDs in `\mathbb Q(\alpha)[x_1, \ldots, x_{n-1}]` have to be calculated, because treating the polynomials as univariate ones can result in a spurious content of the GCD. For this ``func_field_modgcd`` is called recursively. Parameters ========== f, g : PolyElement polynomials in `\mathbb Q(\alpha)[x_0, \ldots, x_{n-1}]` Returns ======= h : PolyElement monic GCD of the polynomials `f` and `g` cff : PolyElement cofactor of `f`, i.e. `\frac f h` cfg : PolyElement cofactor of `g`, i.e. `\frac g h` Examples ======== >>> from sympy.polys.modulargcd import func_field_modgcd >>> from sympy.polys import AlgebraicField, QQ, ring >>> from sympy import sqrt >>> A = AlgebraicField(QQ, sqrt(2)) >>> R, x = ring('x', A) >>> f = x**2 - 2 >>> g = x + sqrt(2) >>> h, cff, cfg = func_field_modgcd(f, g) >>> h == x + sqrt(2) True >>> cff * h == f True >>> cfg * h == g True >>> R, x, y = ring('x, y', A) >>> f = x**2 + 2*sqrt(2)*x*y + 2*y**2 >>> g = x + sqrt(2)*y >>> h, cff, cfg = func_field_modgcd(f, g) >>> h == x + sqrt(2)*y True >>> cff * h == f True >>> cfg * h == g True >>> f = x + sqrt(2)*y >>> g = x + y >>> h, cff, cfg = func_field_modgcd(f, g) >>> h == R.one True >>> cff * h == f True >>> cfg * h == g True References ========== 1. [Hoeij04]_ """ ring = f.ring domain = ring.domain n = ring.ngens assert ring == g.ring and domain.is_Algebraic result = _trivial_gcd(f, g) if result is not None: return result z = Dummy('z') ZZring = ring.clone(symbols=ring.symbols + (z,), domain=domain.domain.get_ring()) if n == 1: f_ = _to_ZZ_poly(f, ZZring) g_ = _to_ZZ_poly(g, ZZring) minpoly = ZZring.drop(0).from_dense(domain.mod.rep) h = _func_field_modgcd_m(f_, g_, minpoly) h = _to_ANP_poly(h, ring) else: # contx0f in Q(a)[x_1, ..., x_{n-1}], f in Q(a)[x_0, ..., x_{n-1}] contx0f, f = _primitive_in_x0(f) contx0g, g = _primitive_in_x0(g) contx0h = func_field_modgcd(contx0f, contx0g)[0] ZZring_ = ZZring.drop_to_ground(*xrange(1, n)) f_ = _to_ZZ_poly(f, ZZring_) g_ = _to_ZZ_poly(g, ZZring_) minpoly = _minpoly_from_dense(domain.mod, ZZring_.drop(0)) h = _func_field_modgcd_m(f_, g_, minpoly) h = _to_ANP_poly(h, ring) contx0h_, h = _primitive_in_x0(h) h *= contx0h.set_ring(ring) f *= contx0f.set_ring(ring) g *= contx0g.set_ring(ring) h = h.quo_ground(h.LC) return h, f.quo(h), g.quo(h)
[ "def", "func_field_modgcd", "(", "f", ",", "g", ")", ":", "ring", "=", "f", ".", "ring", "domain", "=", "ring", ".", "domain", "n", "=", "ring", ".", "ngens", "assert", "ring", "==", "g", ".", "ring", "and", "domain", ".", "is_Algebraic", "result", ...
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/polys/modulargcd.py#L2133-L2281
ray-project/ray
703c1610348615dcb8c2d141a0c46675084660f5
rllib/examples/env/ant_rand_goal.py
python
AntRandGoalEnv.set_task
(self, task)
Args: task: task of the meta-learning environment
Args: task: task of the meta-learning environment
[ "Args", ":", "task", ":", "task", "of", "the", "meta", "-", "learning", "environment" ]
def set_task(self, task): """ Args: task: task of the meta-learning environment """ self.goal_pos = task
[ "def", "set_task", "(", "self", ",", "task", ")", ":", "self", ".", "goal_pos", "=", "task" ]
https://github.com/ray-project/ray/blob/703c1610348615dcb8c2d141a0c46675084660f5/rllib/examples/env/ant_rand_goal.py#L25-L30
getdock/whitelist
704bb41552f71d1a91ecf35e373d8f0b7434f144
app/upload/models.py
python
Upload.stored_size
(self)
return s3.file_size(self.filename)
Return size in bytes of the file stored on s3. This is more reliable than data provided by user.
Return size in bytes of the file stored on s3. This is more reliable than data provided by user.
[ "Return", "size", "in", "bytes", "of", "the", "file", "stored", "on", "s3", ".", "This", "is", "more", "reliable", "than", "data", "provided", "by", "user", "." ]
def stored_size(self): """ Return size in bytes of the file stored on s3. This is more reliable than data provided by user. """ return s3.file_size(self.filename)
[ "def", "stored_size", "(", "self", ")", ":", "return", "s3", ".", "file_size", "(", "self", ".", "filename", ")" ]
https://github.com/getdock/whitelist/blob/704bb41552f71d1a91ecf35e373d8f0b7434f144/app/upload/models.py#L97-L99
pysmt/pysmt
ade4dc2a825727615033a96d31c71e9f53ce4764
pysmt/solvers/cvc4.py
python
CVC4Converter.walk_not
(self, formula, args, **kwargs)
return self.mkExpr(CVC4.NOT, args[0])
[]
def walk_not(self, formula, args, **kwargs): return self.mkExpr(CVC4.NOT, args[0])
[ "def", "walk_not", "(", "self", ",", "formula", ",", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "mkExpr", "(", "CVC4", ".", "NOT", ",", "args", "[", "0", "]", ")" ]
https://github.com/pysmt/pysmt/blob/ade4dc2a825727615033a96d31c71e9f53ce4764/pysmt/solvers/cvc4.py#L276-L277
kuri65536/python-for-android
26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891
python-modules/twisted/twisted/internet/posixbase.py
python
PosixReactorBase._handleSignals
(self)
Extend the basic signal handling logic to also support handling SIGCHLD to know when to try to reap child processes.
Extend the basic signal handling logic to also support handling SIGCHLD to know when to try to reap child processes.
[ "Extend", "the", "basic", "signal", "handling", "logic", "to", "also", "support", "handling", "SIGCHLD", "to", "know", "when", "to", "try", "to", "reap", "child", "processes", "." ]
def _handleSignals(self): """ Extend the basic signal handling logic to also support handling SIGCHLD to know when to try to reap child processes. """ _SignalReactorMixin._handleSignals(self) if platformType == 'posix': if not self._childWaker: self._childWaker = _SIGCHLDWaker(self) self._internalReaders.add(self._childWaker) self.addReader(self._childWaker) self._childWaker.install() # Also reap all processes right now, in case we missed any # signals before we installed the SIGCHLD waker/handler. # This should only happen if someone used spawnProcess # before calling reactor.run (and the process also exited # already). process.reapAllProcesses()
[ "def", "_handleSignals", "(", "self", ")", ":", "_SignalReactorMixin", ".", "_handleSignals", "(", "self", ")", "if", "platformType", "==", "'posix'", ":", "if", "not", "self", ".", "_childWaker", ":", "self", ".", "_childWaker", "=", "_SIGCHLDWaker", "(", "...
https://github.com/kuri65536/python-for-android/blob/26402a08fc46b09ef94e8d7a6bbc3a54ff9d0891/python-modules/twisted/twisted/internet/posixbase.py#L272-L289
Abjad/abjad
d0646dfbe83db3dc5ab268f76a0950712b87b7fd
abjad/typedcollections.py
python
TypedCounter.viewitems
(self)
return self._collection.items()
Please document.
Please document.
[ "Please", "document", "." ]
def viewitems(self): """ Please document. """ return self._collection.items()
[ "def", "viewitems", "(", "self", ")", ":", "return", "self", ".", "_collection", ".", "items", "(", ")" ]
https://github.com/Abjad/abjad/blob/d0646dfbe83db3dc5ab268f76a0950712b87b7fd/abjad/typedcollections.py#L398-L402
magic-wormhole/magic-wormhole
e522a3992217b433ac2c36543bf85c27a7226ed9
src/wormhole/transit.py
python
InboundConnectionFactory.buildProtocol
(self, addr)
return p
[]
def buildProtocol(self, addr): p = self.protocol(self.owner, None, self.start, self._describePeer(addr)) p.factory = self return p
[ "def", "buildProtocol", "(", "self", ",", "addr", ")", ":", "p", "=", "self", ".", "protocol", "(", "self", ".", "owner", ",", "None", ",", "self", ".", "start", ",", "self", ".", "_describePeer", "(", "addr", ")", ")", "p", ".", "factory", "=", ...
https://github.com/magic-wormhole/magic-wormhole/blob/e522a3992217b433ac2c36543bf85c27a7226ed9/src/wormhole/transit.py#L452-L456
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/widgets/text.py
python
TextEdit.get
(self)
return self.ext.get()
Return the raw unicode value from Qt
Return the raw unicode value from Qt
[ "Return", "the", "raw", "unicode", "value", "from", "Qt" ]
def get(self): """Return the raw unicode value from Qt""" return self.ext.get()
[ "def", "get", "(", "self", ")", ":", "return", "self", ".", "ext", ".", "get", "(", ")" ]
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/text.py#L313-L315
ansible-collections/community.general
3faffe8f47968a2400ba3c896c8901c03001a194
plugins/module_utils/xenserver.py
python
module_to_xapi_vm_power_state
(power_state)
return vm_power_state_map.get(power_state)
Maps module VM power states to XAPI VM power states.
Maps module VM power states to XAPI VM power states.
[ "Maps", "module", "VM", "power", "states", "to", "XAPI", "VM", "power", "states", "." ]
def module_to_xapi_vm_power_state(power_state): """Maps module VM power states to XAPI VM power states.""" vm_power_state_map = { "poweredon": "running", "poweredoff": "halted", "restarted": "running", "suspended": "suspended", "shutdownguest": "halted", "rebootguest": "running", } return vm_power_state_map.get(power_state)
[ "def", "module_to_xapi_vm_power_state", "(", "power_state", ")", ":", "vm_power_state_map", "=", "{", "\"poweredon\"", ":", "\"running\"", ",", "\"poweredoff\"", ":", "\"halted\"", ",", "\"restarted\"", ":", "\"running\"", ",", "\"suspended\"", ":", "\"suspended\"", "...
https://github.com/ansible-collections/community.general/blob/3faffe8f47968a2400ba3c896c8901c03001a194/plugins/module_utils/xenserver.py#L63-L74
aplpy/aplpy
241f744a33e7dee677718bd690ea52fbba3628d7
aplpy/core.py
python
FITSFigure.remove_colorbar
(self)
Removes the colorbar from the current figure.
Removes the colorbar from the current figure.
[ "Removes", "the", "colorbar", "from", "the", "current", "figure", "." ]
def remove_colorbar(self): """ Removes the colorbar from the current figure. """ self.colorbar._remove() del self.colorbar
[ "def", "remove_colorbar", "(", "self", ")", ":", "self", ".", "colorbar", ".", "_remove", "(", ")", "del", "self", ".", "colorbar" ]
https://github.com/aplpy/aplpy/blob/241f744a33e7dee677718bd690ea52fbba3628d7/aplpy/core.py#L2092-L2097
lmb-freiburg/netdef_models
7d3311579cf712b31d05ec29f3dc63df067aa07b
SceneFlow/occ-fill/net.py
python
Network.make_graph
(self, data, include_losses=True)
return out
[]
def make_graph(self, data, include_losses=True): pred_config = nd.PredConfig() pred_config.add(nd.PredConfigId(type='disp', perspective='L', channels=1, scale=self._scale, )) pred_dispL_t_1 = data.disp.L pred_flow_fwd = data.flow[0].fwd pred_occ_fwd = data.occ[0].fwd pred_dispL_t1_warped = nd.ops.warp(pred_dispL_t_1, pred_flow_fwd) pred_config[0].mod_func = lambda x: self.interpolator(pred=x, prev_disp=pred_dispL_t1_warped) inp = nd.ops.concat(data.img.L, nd.ops.scale(pred_dispL_t1_warped, 0.05), pred_occ_fwd) with nd.Scope('refine_disp', learn=True, **self.scope_args()): arch = Architecture_S( num_outputs=pred_config.total_channels(), disassembling_function=pred_config.disassemble, loss_function=None, conv_upsample=self._conv_upsample, exit_after=0 ) out = arch.make_graph(inp, edge_features=data.img.L) return out
[ "def", "make_graph", "(", "self", ",", "data", ",", "include_losses", "=", "True", ")", ":", "pred_config", "=", "nd", ".", "PredConfig", "(", ")", "pred_config", ".", "add", "(", "nd", ".", "PredConfigId", "(", "type", "=", "'disp'", ",", "perspective",...
https://github.com/lmb-freiburg/netdef_models/blob/7d3311579cf712b31d05ec29f3dc63df067aa07b/SceneFlow/occ-fill/net.py#L19-L46
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
site-packages/pyparsing.py
python
ParserElement.__add__
(self, other )
return And( [ self, other ] )
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!']
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default.
[ "Implementation", "of", "+", "operator", "-", "returns", "C", "{", "L", "{", "And", "}}", ".", "Adding", "strings", "to", "a", "ParserElement", "converts", "them", "to", "L", "{", "Literal", "}", "s", "by", "default", "." ]
def __add__(self, other ): """ Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement converts them to L{Literal}s by default. Example:: greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Hello, World!" print (hello, "->", greet.parseString(hello)) Prints:: Hello, World! -> ['Hello', ',', 'World', '!'] """ if isinstance( other, basestring ): other = ParserElement._literalStringClass( other ) if not isinstance( other, ParserElement ): warnings.warn("Cannot combine element of type %s with ParserElement" % type(other), SyntaxWarning, stacklevel=2) return None return And( [ self, other ] )
[ "def", "__add__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "basestring", ")", ":", "other", "=", "ParserElement", ".", "_literalStringClass", "(", "other", ")", "if", "not", "isinstance", "(", "other", ",", "ParserElement...
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/site-packages/pyparsing.py#L1803-L1821
OUCMachineLearning/OUCML
5b54337d7c0316084cb1a74befda2bba96137d4a
代码技巧汇总/TF_GAN_util.py
python
bn
(inputs)
return (inputs - mean) * scale / (tf.sqrt(var + epsilon)) + shift
[]
def bn(inputs): mean, var = tf.nn.moments(inputs, axes=[1, 2], keep_dims=True) scale = tf.get_variable("scale", shape=mean.shape, initializer=tf.constant_initializer([1.0])) shift = tf.get_variable("shift", shape=mean.shape, initializer=tf.constant_initializer([0.0])) return (inputs - mean) * scale / (tf.sqrt(var + epsilon)) + shift
[ "def", "bn", "(", "inputs", ")", ":", "mean", ",", "var", "=", "tf", ".", "nn", ".", "moments", "(", "inputs", ",", "axes", "=", "[", "1", ",", "2", "]", ",", "keep_dims", "=", "True", ")", "scale", "=", "tf", ".", "get_variable", "(", "\"scale...
https://github.com/OUCMachineLearning/OUCML/blob/5b54337d7c0316084cb1a74befda2bba96137d4a/代码技巧汇总/TF_GAN_util.py#L76-L80
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/_pydecimal.py
python
Decimal.__reduce__
(self)
return (self.__class__, (str(self),))
[]
def __reduce__(self): return (self.__class__, (str(self),))
[ "def", "__reduce__", "(", "self", ")", ":", "return", "(", "self", ".", "__class__", ",", "(", "str", "(", "self", ")", ",", ")", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/_pydecimal.py#L3733-L3734
kakao/khaiii
328d5a8af456a5941130383354c07d1cd0e47cf5
src/main/python/khaiii/train/models.py
python
Model.forward
(self, *inputs)
return logits_pos, logits_spc
[]
def forward(self, *inputs): contexts, left_spc_masks, right_spc_masks = inputs features_pos = self.conv_layer(contexts, left_spc_masks, right_spc_masks) features_spc = self.conv_layer(contexts, None, None) logits_pos = self.hidden_layer_pos(features_pos) logits_spc = self.hidden_layer_spc(features_spc) return logits_pos, logits_spc
[ "def", "forward", "(", "self", ",", "*", "inputs", ")", ":", "contexts", ",", "left_spc_masks", ",", "right_spc_masks", "=", "inputs", "features_pos", "=", "self", ".", "conv_layer", "(", "contexts", ",", "left_spc_masks", ",", "right_spc_masks", ")", "feature...
https://github.com/kakao/khaiii/blob/328d5a8af456a5941130383354c07d1cd0e47cf5/src/main/python/khaiii/train/models.py#L101-L107
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.iterkeys
(self)
return iter(self)
od.iterkeys() -> an iterator over the keys in od
od.iterkeys() -> an iterator over the keys in od
[ "od", ".", "iterkeys", "()", "-", ">", "an", "iterator", "over", "the", "keys", "in", "od" ]
def iterkeys(self): 'od.iterkeys() -> an iterator over the keys in od' return iter(self)
[ "def", "iterkeys", "(", "self", ")", ":", "return", "iter", "(", "self", ")" ]
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/python_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/ordered_dict.py#L128-L130
City-Bureau/city-scrapers
b295d0aa612e3979a9fccab7c5f55ecea9ed074c
city_scrapers/spiders/chi_fire_benefit_fund.py
python
ChiFireBenefitFundSpider.parse
(self, response)
`parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs.
`parse` should always `yield` Meeting items.
[ "parse", "should", "always", "yield", "Meeting", "items", "." ]
def parse(self, response): """ `parse` should always `yield` Meeting items. Change the `_parse_title`, `_parse_start`, etc methods to fit your scraping needs. """ link_list = self._parse_link_list(response) active_tab = response.css(".tab-pane.active .row") for idx, col in enumerate( active_tab.css(".col-sm-2:nth-child(2), .col-sm-2:nth-child(3)") ): # Board meetings are in the first column, committee meetings in the second is_board = idx == 0 for date_str in col.css("*::text").extract(): # Ignore strings that don't have a year in them if not re.search(r"\d{4}", date_str): continue start = self._parse_start(date_str) links = self._parse_links(start, link_list) meeting = Meeting( title=self._parse_title(is_board, links), description="", classification=self._parse_classification(is_board), start=start, end=None, all_day=False, time_notes="See agenda for meeting time", location=self.location, links=links, source=response.url, ) meeting["status"] = self._get_status(meeting) meeting["id"] = self._get_id(meeting) yield meeting for item in response.css(".meetings"): start = self._parse_start(item)
[ "def", "parse", "(", "self", ",", "response", ")", ":", "link_list", "=", "self", ".", "_parse_link_list", "(", "response", ")", "active_tab", "=", "response", ".", "css", "(", "\".tab-pane.active .row\"", ")", "for", "idx", ",", "col", "in", "enumerate", ...
https://github.com/City-Bureau/city-scrapers/blob/b295d0aa612e3979a9fccab7c5f55ecea9ed074c/city_scrapers/spiders/chi_fire_benefit_fund.py#L19-L58
nltk/nltk
3f74ac55681667d7ef78b664557487145f51eb02
nltk/draw/dispersion.py
python
dispersion_plot
(text, words, ignore_case=False, title="Lexical Dispersion Plot")
Generate a lexical dispersion plot. :param text: The source text :type text: list(str) or enum(str) :param words: The target words :type words: list of str :param ignore_case: flag to set if case should be ignored when searching text :type ignore_case: bool
Generate a lexical dispersion plot.
[ "Generate", "a", "lexical", "dispersion", "plot", "." ]
def dispersion_plot(text, words, ignore_case=False, title="Lexical Dispersion Plot"): """ Generate a lexical dispersion plot. :param text: The source text :type text: list(str) or enum(str) :param words: The target words :type words: list of str :param ignore_case: flag to set if case should be ignored when searching text :type ignore_case: bool """ try: from matplotlib import pylab except ImportError as e: raise ValueError( "The plot function requires matplotlib to be installed." "See https://matplotlib.org/" ) from e text = list(text) words.reverse() if ignore_case: words_to_comp = list(map(str.lower, words)) text_to_comp = list(map(str.lower, text)) else: words_to_comp = words text_to_comp = text points = [ (x, y) for x in range(len(text_to_comp)) for y in range(len(words_to_comp)) if text_to_comp[x] == words_to_comp[y] ] if points: x, y = list(zip(*points)) else: x = y = () pylab.plot(x, y, "b|", scalex=0.1) pylab.yticks(list(range(len(words))), words, color="b") pylab.ylim(-1, len(words)) pylab.title(title) pylab.xlabel("Word Offset") pylab.show()
[ "def", "dispersion_plot", "(", "text", ",", "words", ",", "ignore_case", "=", "False", ",", "title", "=", "\"Lexical Dispersion Plot\"", ")", ":", "try", ":", "from", "matplotlib", "import", "pylab", "except", "ImportError", "as", "e", ":", "raise", "ValueErro...
https://github.com/nltk/nltk/blob/3f74ac55681667d7ef78b664557487145f51eb02/nltk/draw/dispersion.py#L13-L58
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Zimperium/Integrations/Zimperium/Zimperium.py
python
devices_get_last_updated
(client: Client, args: Dict)
return command_results
Retrieve last updated devices Args: client: Client object with request. args: Usually demisto.args() Returns: Outputs.
Retrieve last updated devices
[ "Retrieve", "last", "updated", "devices" ]
def devices_get_last_updated(client: Client, args: Dict) -> CommandResults: """Retrieve last updated devices Args: client: Client object with request. args: Usually demisto.args() Returns: Outputs. """ timestamp_format = '%Y-%m-%d' from_last_update = str(args.get('from_last_update', '1 day')) last_updated = parse_date_range(from_last_update, date_format=timestamp_format)[0] exclude_deleted = args.get('exclude_deleted') == 'false' size = str(args.get('size', '10')) page = str(args.get('page', '0')) devices = client.devices_get_last_updated_request(last_updated, exclude_deleted, size, page) devices_data = devices.get('content') total_elements = devices.get('totalElements', '0') table_name = '' if not devices.get('last'): table_name = ' More Devices are available in the next page.' headers = ['deviceId', 'zdid', 'model', 'osType', 'osVersion', 'updatedDate', 'deviceHash'] readable_output = tableToMarkdown(name=f"Number of devices found: {total_elements}. {table_name}", t=devices_data, headers=headers, removeNull=True) command_results = CommandResults( outputs_prefix='Zimperium.Devices', outputs_key_field='deviceId', outputs=devices_data, readable_output=readable_output, raw_response=devices ) return command_results
[ "def", "devices_get_last_updated", "(", "client", ":", "Client", ",", "args", ":", "Dict", ")", "->", "CommandResults", ":", "timestamp_format", "=", "'%Y-%m-%d'", "from_last_update", "=", "str", "(", "args", ".", "get", "(", "'from_last_update'", ",", "'1 day'"...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Zimperium/Integrations/Zimperium/Zimperium.py#L360-L396
NordicSemiconductor/pc-nrfutil
d08e742128f2a3dac522601bc6b9f9b2b63952df
nordicsemi/dfu/dfu_transport_ant.py
python
DfuTransportAnt.__execute
(self)
[]
def __execute(self): self.dfu_adapter.send_message([DfuTransportAnt.OP_CODE['Execute']]) self.__get_response(DfuTransportAnt.OP_CODE['Execute'])
[ "def", "__execute", "(", "self", ")", ":", "self", ".", "dfu_adapter", ".", "send_message", "(", "[", "DfuTransportAnt", ".", "OP_CODE", "[", "'Execute'", "]", "]", ")", "self", ".", "__get_response", "(", "DfuTransportAnt", ".", "OP_CODE", "[", "'Execute'",...
https://github.com/NordicSemiconductor/pc-nrfutil/blob/d08e742128f2a3dac522601bc6b9f9b2b63952df/nordicsemi/dfu/dfu_transport_ant.py#L519-L521
CR-Gjx/LeakGAN
dc3360e30f2572cc4d7281cf2c8f490558e4a794
No Temperature/Synthetic Data/Main.py
python
main
()
[]
def main(): random.seed(SEED) np.random.seed(SEED) assert START_TOKEN == 0 gen_data_loader = Gen_Data_loader(BATCH_SIZE,FLAGS.length) likelihood_data_loader = Gen_Data_loader(BATCH_SIZE,FLAGS.length) # For testing vocab_size = 5000 file = open('save/target_params.pkl', 'rb') target_params = cPickle.load(file) dis_data_loader = Dis_dataloader(BATCH_SIZE,SEQ_LENGTH) discriminator = Discriminator(SEQ_LENGTH,num_classes=2,vocab_size=vocab_size,dis_emb_dim=dis_embedding_dim,filter_sizes=dis_filter_sizes,num_filters=dis_num_filters, batch_size=BATCH_SIZE,hidden_dim=HIDDEN_DIM,start_token=START_TOKEN,goal_out_size=GOAL_OUT_SIZE,step_size=4) leakgan = LeakGAN(SEQ_LENGTH,num_classes=2,vocab_size=vocab_size,emb_dim=EMB_DIM,dis_emb_dim=dis_embedding_dim,filter_sizes=dis_filter_sizes,num_filters=dis_num_filters, batch_size=BATCH_SIZE,hidden_dim=HIDDEN_DIM,start_token=START_TOKEN,goal_out_size=GOAL_OUT_SIZE,goal_size=GOAL_SIZE,step_size=4,D_model=discriminator, learning_rate=LEARNING_RATE) if SEQ_LENGTH == 40: target_lstm = TARGET_LSTM(vocab_size, BATCH_SIZE, EMB_DIM, HIDDEN_DIM, SEQ_LENGTH, START_TOKEN) # The oracle model else: target_lstm = TARGET_LSTM20(vocab_size, BATCH_SIZE, EMB_DIM, HIDDEN_DIM, SEQ_LENGTH, START_TOKEN,target_params) config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.5 sess = tf.Session(config=config) sess.run(tf.global_variables_initializer()) generate_samples(sess, target_lstm, BATCH_SIZE, generated_num, positive_file, 0) for a in range(1): g = sess.run(leakgan.gen_x,feed_dict={leakgan.drop_out:0.8,leakgan.train:1}) print(g) print("epoch:",a," ") log = open('save/experiment-log.txt', 'w') gen_data_loader.create_batches(positive_file) saver_variables = tf.global_variables() saver = tf.train.Saver(saver_variables) model = tf.train.latest_checkpoint(model_path) print(model) if FLAGS.restore and model: # model = tf.train.latest_checkpoint(model_path) # if model and FLAGS.restore: if model_path+'/' + FLAGS.model: print(model_path+'/' + FLAGS.model) saver.restore(sess, model_path+'/' + FLAGS.model) else: saver.restore(sess, model) else: if FLAGS.resD and model_path + '/' + FLAGS.model: print(model_path + '/' + FLAGS.model) saver.restore(sess, model_path + '/' + FLAGS.model) print('Start pre-training...') log.write('pre-training...\n') for epoch in range(PRE_EPOCH_NUM): loss = pre_train_epoch(sess, leakgan, gen_data_loader) if epoch % 5 == 0: generate_samples(sess, leakgan, BATCH_SIZE, generated_num, eval_file, 0) likelihood_data_loader.create_batches(eval_file) test_loss = target_loss(sess, target_lstm, likelihood_data_loader) print('pre-train epoch ', epoch, 'test_loss ', test_loss) buffer = 'epoch:\t' + str(epoch) + '\tnll:\t' + str(test_loss) + '\n' log.write(buffer) generate_samples(sess, target_lstm, BATCH_SIZE, generated_num, eval_file, 0) likelihood_data_loader.create_batches(eval_file) test_loss = target_loss(sess, target_lstm, likelihood_data_loader) print("Groud-Truth:", test_loss) saver.save(sess, model_path + '/leakgan_pre') else: print('Start pre-training discriminator...') # Train 3 epoch on the generated data and do this for 50 times for i in range(10): for _ in range(5): generate_samples(sess, leakgan, BATCH_SIZE, generated_num, negative_file,0) generate_samples(sess, target_lstm, BATCH_SIZE, generated_num, positive_file,0) # gen_data_loader.create_batches(positive_file) dis_data_loader.load_train_data(positive_file, negative_file) for _ in range(3): dis_data_loader.reset_pointer() for it in range(dis_data_loader.num_batch): x_batch, y_batch = dis_data_loader.next_batch() feed = { discriminator.D_input_x: x_batch, discriminator.D_input_y: y_batch, discriminator.dropout_keep_prob: dis_dropout_keep_prob } D_loss,_ = sess.run([discriminator.D_loss,discriminator.D_train_op], feed) # # print 'D_loss ', D_loss # buffer = str(D_loss) + '\n' # log.write(buffer) leakgan.update_feature_function(discriminator) saver.save(sess, model_path + '/leakgan_preD') # saver.save(sess, model_path + '/leakgan') # pre-train generator print('Start pre-training...') log.write('pre-training...\n') for epoch in range(PRE_EPOCH_NUM/10): loss = pre_train_epoch(sess, leakgan, gen_data_loader) if epoch % 5 == 0: generate_samples(sess, leakgan, BATCH_SIZE, generated_num, eval_file,0) likelihood_data_loader.create_batches(eval_file) test_loss = target_loss(sess, target_lstm, likelihood_data_loader) print('pre-train epoch ', epoch, 'test_loss ', test_loss) buffer = 'epoch:\t'+ str(epoch) + '\tnll:\t' + str(test_loss) + '\n' log.write(buffer) generate_samples(sess, target_lstm, BATCH_SIZE, generated_num, eval_file, 0) likelihood_data_loader.create_batches(eval_file) test_loss = target_loss(sess, target_lstm, likelihood_data_loader) print("Groud-Truth:", test_loss) saver.save(sess, model_path + '/leakgan_pre') gencircle = 1 # print('#########################################################################') print('Start Adversarial Training...') log.write('adversarial training...\n') for total_batch in range(TOTAL_BATCH): # Train the generator for one step for it in range(1): for gi in range(gencircle): samples = leakgan.generate(sess,1.0,1) rewards = get_reward(leakgan, discriminator,sess, samples, 4, dis_dropout_keep_prob) feed = {leakgan.x: samples, leakgan.reward: rewards,leakgan.drop_out:1.0} _,_,g_loss,w_loss = sess.run([leakgan.manager_updates,leakgan.worker_updates,leakgan.goal_loss,leakgan.worker_loss], feed_dict=feed) print('total_batch: ', total_batch, " ",g_loss," ", w_loss) # Test if total_batch % 5 == 0 or total_batch == TOTAL_BATCH - 1: generate_samples(sess, leakgan, BATCH_SIZE, generated_num, eval_file,0) likelihood_data_loader.create_batches(eval_file) test_loss = target_loss(sess, target_lstm, likelihood_data_loader) buffer = 'epoch:\t' + str(total_batch) + '\tnll:\t' + str(test_loss) + '\n' print('total_batch: ', total_batch, 'test_loss: ', test_loss) log.write(buffer) generate_samples(sess, target_lstm, BATCH_SIZE, generated_num, eval_file, 0) likelihood_data_loader.create_batches(eval_file) test_loss = target_loss(sess, target_lstm, likelihood_data_loader) print("Groud-Truth:" ,test_loss) # Train the discriminator for _ in range(5): generate_samples(sess, leakgan, BATCH_SIZE, generated_num, negative_file,0) generate_samples(sess, target_lstm, BATCH_SIZE, generated_num, positive_file,0) dis_data_loader.load_train_data(positive_file, negative_file) for _ in range(3): dis_data_loader.reset_pointer() for it in range(dis_data_loader.num_batch): x_batch, y_batch = dis_data_loader.next_batch() feed = { discriminator.D_input_x: x_batch, discriminator.D_input_y: y_batch, discriminator.dropout_keep_prob: dis_dropout_keep_prob } D_loss, _ = sess.run([discriminator.D_loss, discriminator.D_train_op], feed) # print 'D_loss ', D_loss leakgan.update_feature_function(discriminator) log.close()
[ "def", "main", "(", ")", ":", "random", ".", "seed", "(", "SEED", ")", "np", ".", "random", ".", "seed", "(", "SEED", ")", "assert", "START_TOKEN", "==", "0", "gen_data_loader", "=", "Gen_Data_loader", "(", "BATCH_SIZE", ",", "FLAGS", ".", "length", ")...
https://github.com/CR-Gjx/LeakGAN/blob/dc3360e30f2572cc4d7281cf2c8f490558e4a794/No Temperature/Synthetic Data/Main.py#L161-L320
sripathikrishnan/redis-rdb-tools
548b11ec3c81a603f5b321228d07a61a0b940159
rdbtools/memprofiler.py
python
MemoryCallback.skiplist_entry_overhead
(self)
return self.hashtable_entry_overhead() + 2*self.sizeof_pointer() + 8 + (self.sizeof_pointer() + 8) * self.zset_random_level()
[]
def skiplist_entry_overhead(self): return self.hashtable_entry_overhead() + 2*self.sizeof_pointer() + 8 + (self.sizeof_pointer() + 8) * self.zset_random_level()
[ "def", "skiplist_entry_overhead", "(", "self", ")", ":", "return", "self", ".", "hashtable_entry_overhead", "(", ")", "+", "2", "*", "self", ".", "sizeof_pointer", "(", ")", "+", "8", "+", "(", "self", ".", "sizeof_pointer", "(", ")", "+", "8", ")", "*...
https://github.com/sripathikrishnan/redis-rdb-tools/blob/548b11ec3c81a603f5b321228d07a61a0b940159/rdbtools/memprofiler.py#L518-L519
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/metagoofil/hachoir_parser/program/java.py
python
JavaCompiledClassFile.createFields
(self)
[]
def createFields(self): yield textHandler(UInt32(self, "magic", "Java compiled class signature"), hexadecimal) yield UInt16(self, "minor_version", "Class format minor version") yield UInt16(self, "major_version", "Class format major version") yield UInt16(self, "constant_pool_count", "Size of the constant pool") if self["constant_pool_count"].value > 1: #yield FieldArray(self, "constant_pool", CPInfo, # (self["constant_pool_count"].value - 1), first_index=1) # Mmmh... can't use FieldArray actually, because ConstantPool # requires some specific hacks (skipping some indexes after Long # and Double entries). yield ConstantPool(self, "constant_pool", (self["constant_pool_count"].value)) # Inner class access flags (16 bits) yield NullBits(self, "reserved[]", 5) yield Bit(self, "abstract") yield Bit(self, "interface") yield NullBits(self, "reserved[]", 3) yield Bit(self, "super") yield Bit(self, "final") yield Bit(self, "static") yield Bit(self, "protected") yield Bit(self, "private") yield Bit(self, "public") yield CPIndex(self, "this_class", "Class name", target_types="Class") yield CPIndex(self, "super_class", "Super class name", target_types="Class") yield UInt16(self, "interfaces_count", "Number of implemented interfaces") if self["interfaces_count"].value > 0: yield FieldArray(self, "interfaces", CPIndex, self["interfaces_count"].value, target_types="Class") yield UInt16(self, "fields_count", "Number of fields") if self["fields_count"].value > 0: yield FieldArray(self, "fields", FieldInfo, self["fields_count"].value) yield UInt16(self, "methods_count", "Number of methods") if self["methods_count"].value > 0: yield FieldArray(self, "methods", MethodInfo, self["methods_count"].value) yield UInt16(self, "attributes_count", "Number of attributes") if self["attributes_count"].value > 0: yield FieldArray(self, "attributes", AttributeInfo, self["attributes_count"].value)
[ "def", "createFields", "(", "self", ")", ":", "yield", "textHandler", "(", "UInt32", "(", "self", ",", "\"magic\"", ",", "\"Java compiled class signature\"", ")", ",", "hexadecimal", ")", "yield", "UInt16", "(", "self", ",", "\"minor_version\"", ",", "\"Class fo...
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/metagoofil/hachoir_parser/program/java.py#L671-L715
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py
python
ScriptMaker.make
(self, specification, options=None)
return filenames
Make a script. :param specification: The specification, which is either a valid export entry specification (to make a script from a callable) or a filename (to make a script by copying from a source location). :param options: A dictionary of options controlling script generation. :return: A list of all absolute pathnames written to.
Make a script.
[ "Make", "a", "script", "." ]
def make(self, specification, options=None): """ Make a script. :param specification: The specification, which is either a valid export entry specification (to make a script from a callable) or a filename (to make a script by copying from a source location). :param options: A dictionary of options controlling script generation. :return: A list of all absolute pathnames written to. """ filenames = [] entry = get_export_entry(specification) if entry is None: self._copy_script(specification, filenames) else: self._make_script(entry, filenames, options=options) return filenames
[ "def", "make", "(", "self", ",", "specification", ",", "options", "=", "None", ")", ":", "filenames", "=", "[", "]", "entry", "=", "get_export_entry", "(", "specification", ")", "if", "entry", "is", "None", ":", "self", ".", "_copy_script", "(", "specifi...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv_mac_py3/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py#L387-L404
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/jinja2/loaders.py
python
ModuleLoader.load
(self, environment, name, globals=None)
return environment.template_class.from_module_dict( environment, mod.__dict__, globals)
[]
def load(self, environment, name, globals=None): key = self.get_template_key(name) module = '%s.%s' % (self.package_name, key) mod = getattr(self.module, module, None) if mod is None: try: mod = __import__(module, None, None, ['root']) except ImportError: raise TemplateNotFound(name) # remove the entry from sys.modules, we only want the attribute # on the module object we have stored on the loader. sys.modules.pop(module, None) return environment.template_class.from_module_dict( environment, mod.__dict__, globals)
[ "def", "load", "(", "self", ",", "environment", ",", "name", ",", "globals", "=", "None", ")", ":", "key", "=", "self", ".", "get_template_key", "(", "name", ")", "module", "=", "'%s.%s'", "%", "(", "self", ".", "package_name", ",", "key", ")", "mod"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/jinja2/loaders.py#L466-L481
bdcht/amoco
dac8e00b862eb6d87cc88dddd1e5316c67c1d798
amoco/logger.py
python
set_log_all
(level)
set all loggers to specified level Args: level (int): level value as an integer.
set all loggers to specified level
[ "set", "all", "loggers", "to", "specified", "level" ]
def set_log_all(level): """set all loggers to specified level Args: level (int): level value as an integer. """ for l in Log.loggers.values(): l.setLevel(level)
[ "def", "set_log_all", "(", "level", ")", ":", "for", "l", "in", "Log", ".", "loggers", ".", "values", "(", ")", ":", "l", ".", "setLevel", "(", "level", ")" ]
https://github.com/bdcht/amoco/blob/dac8e00b862eb6d87cc88dddd1e5316c67c1d798/amoco/logger.py#L141-L148
laughtervv/DISN
f8206adb45f8a0714eaefcae8433337cd562b82a
demo/demo.py
python
test_one_epoch
(sess, ops, batch_data)
ops: dict mapping from string to tf ops
ops: dict mapping from string to tf ops
[ "ops", ":", "dict", "mapping", "from", "string", "to", "tf", "ops" ]
def test_one_epoch(sess, ops, batch_data): """ ops: dict mapping from string to tf ops """ is_training = False # Shuffle train samples log_string(str(datetime.now())) losses = {} for lossname in ops['end_points']['losses'].keys(): losses[lossname] = 0 with ThreadPoolExecutor(max_workers=4) as executor: extra_pts = np.zeros((1, SPLIT_SIZE * NUM_SAMPLE_POINTS - TOTAL_POINTS, 3), dtype=np.float32) batch_points = np.zeros((SPLIT_SIZE, 0, NUM_SAMPLE_POINTS, 3), dtype=np.float32) if not FLAGS.threedcnn: for b in range(BATCH_SIZE): sdf_params = batch_data['sdf_params'][b] x_ = np.linspace(sdf_params[0], sdf_params[3], num=RESOLUTION) y_ = np.linspace(sdf_params[1], sdf_params[4], num=RESOLUTION) z_ = np.linspace(sdf_params[2], sdf_params[5], num=RESOLUTION) z, y, x = np.meshgrid(z_, y_, x_, indexing='ij') x = np.expand_dims(x, 3) y = np.expand_dims(y, 3) z = np.expand_dims(z, 3) all_pts = np.concatenate((x, y, z), axis=3).astype(np.float32) all_pts = all_pts.reshape(1, -1, 3) all_pts = np.concatenate((all_pts, extra_pts), axis=1).reshape(SPLIT_SIZE, 1, -1, 3) print('all_pts', all_pts.shape) batch_points = np.concatenate((batch_points, all_pts), axis=1) pred_sdf_val_all = np.zeros((SPLIT_SIZE, BATCH_SIZE, NUM_SAMPLE_POINTS, 2 if FLAGS.binary else 1)) for sp in range(SPLIT_SIZE): if FLAGS.threedcnn: feed_dict = {ops['is_training_pl']: is_training, ops['input_pls']['imgs']: batch_data['img']} else: feed_dict = {ops['is_training_pl']: is_training, ops['input_pls']['sample_pc']: batch_points[sp,...].reshape(BATCH_SIZE, -1, 3), ops['input_pls']['sample_pc_rot']: batch_points[sp,...].reshape(BATCH_SIZE, -1, 3), ops['input_pls']['imgs']: batch_data['img'], ops['input_pls']['trans_mat']: batch_data['trans_mat']} output_list = [ops['end_points']['pred_sdf'], ops['end_points']['ref_img'], ops['end_points']['sample_img_points']] pred_sdf_val, ref_img_val, sample_img_points_val = sess.run(output_list, feed_dict=feed_dict) pred_sdf_val_all[sp,:,:,:] = pred_sdf_val pred_sdf_val_all = np.swapaxes(pred_sdf_val_all,0,1) # B, S, NUM SAMPLE, 1 or 2 pred_sdf_val_all = pred_sdf_val_all.reshape((BATCH_SIZE,-1,2 if FLAGS.binary else 1))[:, :TOTAL_POINTS, :] if FLAGS.binary: expo = np.exp(pred_sdf_val_all) prob = expo[:,:,1] / np.sum(expo, axis = 2) result = (prob - 0.5) / 10. print("result.shape", result.shape) else: result = pred_sdf_val_all / SDF_WEIGHT for b in range(BATCH_SIZE): print("submit create_obj") executor.submit(create_obj, result[b], batch_data['sdf_params'][b], RESULT_OBJ_PATH, FLAGS.iso)
[ "def", "test_one_epoch", "(", "sess", ",", "ops", ",", "batch_data", ")", ":", "is_training", "=", "False", "# Shuffle train samples", "log_string", "(", "str", "(", "datetime", ".", "now", "(", ")", ")", ")", "losses", "=", "{", "}", "for", "lossname", ...
https://github.com/laughtervv/DISN/blob/f8206adb45f8a0714eaefcae8433337cd562b82a/demo/demo.py#L281-L339
ambujraj/hacktoberfest2018
53df2cac8b3404261131a873352ec4f2ffa3544d
MAC_changer/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/ipaddress.py
python
_BaseV6._reverse_pointer
(self)
return '.'.join(reverse_chars) + '.ip6.arpa'
Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5.
Return the reverse DNS pointer name for the IPv6 address.
[ "Return", "the", "reverse", "DNS", "pointer", "name", "for", "the", "IPv6", "address", "." ]
def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5. """ reverse_chars = self.exploded[::-1].replace(':', '') return '.'.join(reverse_chars) + '.ip6.arpa'
[ "def", "_reverse_pointer", "(", "self", ")", ":", "reverse_chars", "=", "self", ".", "exploded", "[", ":", ":", "-", "1", "]", ".", "replace", "(", "':'", ",", "''", ")", "return", "'.'", ".", "join", "(", "reverse_chars", ")", "+", "'.ip6.arpa'" ]
https://github.com/ambujraj/hacktoberfest2018/blob/53df2cac8b3404261131a873352ec4f2ffa3544d/MAC_changer/venv/lib/python3.7/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/ipaddress.py#L1978-L1985
atlassian-api/atlassian-python-api
6d8545a790c3aae10b75bdc225fb5c3a0aee44db
atlassian/bitbucket/server/common/permissions.py
python
Permissions.get
(self, name)
Returns the requested group/user :param name: string: The requested element name. :return: The requested group/user object
Returns the requested group/user
[ "Returns", "the", "requested", "group", "/", "user" ]
def get(self, name): """ Returns the requested group/user :param name: string: The requested element name. :return: The requested group/user object """ for entry in self.each(filter=name): if entry.name == name: return entry raise Exception("Unknown group/user '{}'".format(name))
[ "def", "get", "(", "self", ",", "name", ")", ":", "for", "entry", "in", "self", ".", "each", "(", "filter", "=", "name", ")", ":", "if", "entry", ".", "name", "==", "name", ":", "return", "entry", "raise", "Exception", "(", "\"Unknown group/user '{}'\"...
https://github.com/atlassian-api/atlassian-python-api/blob/6d8545a790c3aae10b75bdc225fb5c3a0aee44db/atlassian/bitbucket/server/common/permissions.py#L95-L107
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/edit.py
python
three_point_overwrite_action
(data)
return action
[]
def three_point_overwrite_action(data): action = EditAction(_three_over_undo, _three_over_redo, data) return action
[ "def", "three_point_overwrite_action", "(", "data", ")", ":", "action", "=", "EditAction", "(", "_three_over_undo", ",", "_three_over_redo", ",", "data", ")", "return", "action" ]
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/edit.py#L833-L835
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/preview/sync/service/sync_list/sync_list_item.py
python
SyncListItemList.create
(self, data)
return SyncListItemInstance( self._version, payload, service_sid=self._solution['service_sid'], list_sid=self._solution['list_sid'], )
Create the SyncListItemInstance :param dict data: The data :returns: The created SyncListItemInstance :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance
Create the SyncListItemInstance
[ "Create", "the", "SyncListItemInstance" ]
def create(self, data): """ Create the SyncListItemInstance :param dict data: The data :returns: The created SyncListItemInstance :rtype: twilio.rest.preview.sync.service.sync_list.sync_list_item.SyncListItemInstance """ data = values.of({'Data': serialize.object(data), }) payload = self._version.create(method='POST', uri=self._uri, data=data, ) return SyncListItemInstance( self._version, payload, service_sid=self._solution['service_sid'], list_sid=self._solution['list_sid'], )
[ "def", "create", "(", "self", ",", "data", ")", ":", "data", "=", "values", ".", "of", "(", "{", "'Data'", ":", "serialize", ".", "object", "(", "data", ")", ",", "}", ")", "payload", "=", "self", ".", "_version", ".", "create", "(", "method", "=...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/preview/sync/service/sync_list/sync_list_item.py#L40-L58
deluge-torrent/deluge
2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc
deluge/core/torrentmanager.py
python
TorrentManager.on_alert_file_completed
(self, alert)
Alert handler for libtorrent file_completed_alert Emits: TorrentFileCompletedEvent: When an individual file completes downloading.
Alert handler for libtorrent file_completed_alert
[ "Alert", "handler", "for", "libtorrent", "file_completed_alert" ]
def on_alert_file_completed(self, alert): """Alert handler for libtorrent file_completed_alert Emits: TorrentFileCompletedEvent: When an individual file completes downloading. """ try: torrent_id = str(alert.handle.info_hash()) except RuntimeError: return if torrent_id in self.torrents: component.get('EventManager').emit( TorrentFileCompletedEvent(torrent_id, alert.index) )
[ "def", "on_alert_file_completed", "(", "self", ",", "alert", ")", ":", "try", ":", "torrent_id", "=", "str", "(", "alert", ".", "handle", ".", "info_hash", "(", ")", ")", "except", "RuntimeError", ":", "return", "if", "torrent_id", "in", "self", ".", "to...
https://github.com/deluge-torrent/deluge/blob/2316088f5c0dd6cb044d9d4832fa7d56dcc79cdc/deluge/core/torrentmanager.py#L1587-L1601
scikit-hep/scikit-hep
506149b352eeb2291f24aef3f40691b5f6be2da7
skhep/math/kinematics.py
python
Armenteros_Podolanski_variables
(pplus_3Dvec, pminus_3Dvec)
return (qT, alpha)
Calculate the Armenteros Podolanski [APPaper]_ variables :math:`(\\alpha,q_T)` for a 2-body decay. Definition ---------- .. math:: \\alpha = \\frac{p_L^+ - p_L^-}{p_L^+ + p_L^-} q_T = \\frac{| p^- \\times p^{\\mathrm mother}|}{|p^{\\mathrm mother}|} where the longitudinal momentum along the direction of flight of the mother particle is .. math:: p_L^\\pm = \\frac{p^\\pm \\cdot p^{\\mathrm mother}}{|p^{\\mathrm mother}|} and :math:`q_T` is the transverse momentum of the daughter particles with respect to the direction of flight of the mother particle. These expressions can be simplified to .. math:: \\alpha = \\frac{|p^+|^2 - |p^-|^2}{|p^+ + p^-|^2} q_T = \\frac{| p^+ \\times p^- |}{|p^+ + p^-|} Parameters ----------- pplus_3Dvec : Vector3D 3D-momentum vector of the positively-charged daughter particle. pminus_3Dvec : Vector3D 3D-momentum vector of the negatively-charged daughter particle. Returns ------- Tuple :math:`(\\alpha,q_T)`. References ---------- .. [APPaper] J. Podolanski and R. Armenteros, III. Analysis of V-events, The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science 45 (1954) 13, http://dx.doi.org/10.1080/14786440108520416
Calculate the Armenteros Podolanski [APPaper]_ variables :math:`(\\alpha,q_T)` for a 2-body decay.
[ "Calculate", "the", "Armenteros", "Podolanski", "[", "APPaper", "]", "_", "variables", ":", "math", ":", "(", "\\\\", "alpha", "q_T", ")", "for", "a", "2", "-", "body", "decay", "." ]
def Armenteros_Podolanski_variables(pplus_3Dvec, pminus_3Dvec): """ Calculate the Armenteros Podolanski [APPaper]_ variables :math:`(\\alpha,q_T)` for a 2-body decay. Definition ---------- .. math:: \\alpha = \\frac{p_L^+ - p_L^-}{p_L^+ + p_L^-} q_T = \\frac{| p^- \\times p^{\\mathrm mother}|}{|p^{\\mathrm mother}|} where the longitudinal momentum along the direction of flight of the mother particle is .. math:: p_L^\\pm = \\frac{p^\\pm \\cdot p^{\\mathrm mother}}{|p^{\\mathrm mother}|} and :math:`q_T` is the transverse momentum of the daughter particles with respect to the direction of flight of the mother particle. These expressions can be simplified to .. math:: \\alpha = \\frac{|p^+|^2 - |p^-|^2}{|p^+ + p^-|^2} q_T = \\frac{| p^+ \\times p^- |}{|p^+ + p^-|} Parameters ----------- pplus_3Dvec : Vector3D 3D-momentum vector of the positively-charged daughter particle. pminus_3Dvec : Vector3D 3D-momentum vector of the negatively-charged daughter particle. Returns ------- Tuple :math:`(\\alpha,q_T)`. References ---------- .. [APPaper] J. Podolanski and R. Armenteros, III. Analysis of V-events, The London, Edinburgh, and Dublin Philosophical Magazine and Journal of Science 45 (1954) 13, http://dx.doi.org/10.1080/14786440108520416 """ mother_mag = (pplus_3Dvec + pminus_3Dvec).mag if isequal(mother_mag, 0.0): raise ValueError("Total momentum has zero magnitude!") # Longitudinal momentum asymmetry, i.e. imbalance alpha = (pplus_3Dvec.mag2 - pminus_3Dvec.mag2) / mother_mag ** 2 # Transverse momentum of positively-charged particle along the mother particle momentum direction qT = (pplus_3Dvec.cross(pminus_3Dvec)).mag / mother_mag return (qT, alpha)
[ "def", "Armenteros_Podolanski_variables", "(", "pplus_3Dvec", ",", "pminus_3Dvec", ")", ":", "mother_mag", "=", "(", "pplus_3Dvec", "+", "pminus_3Dvec", ")", ".", "mag", "if", "isequal", "(", "mother_mag", ",", "0.0", ")", ":", "raise", "ValueError", "(", "\"T...
https://github.com/scikit-hep/scikit-hep/blob/506149b352eeb2291f24aef3f40691b5f6be2da7/skhep/math/kinematics.py#L52-L108
tensorflow/privacy
867f3d4c5566b21433a6a1bed998094d1479b4d5
tensorflow_privacy/privacy/dp_query/no_privacy_query.py
python
NoPrivacySumQuery.get_noised_result
(self, sample_state, global_state)
return sample_state, global_state, dp_event.NonPrivateDpEvent()
Implements `tensorflow_privacy.DPQuery.get_noised_result`.
Implements `tensorflow_privacy.DPQuery.get_noised_result`.
[ "Implements", "tensorflow_privacy", ".", "DPQuery", ".", "get_noised_result", "." ]
def get_noised_result(self, sample_state, global_state): """Implements `tensorflow_privacy.DPQuery.get_noised_result`.""" return sample_state, global_state, dp_event.NonPrivateDpEvent()
[ "def", "get_noised_result", "(", "self", ",", "sample_state", ",", "global_state", ")", ":", "return", "sample_state", ",", "global_state", ",", "dp_event", ".", "NonPrivateDpEvent", "(", ")" ]
https://github.com/tensorflow/privacy/blob/867f3d4c5566b21433a6a1bed998094d1479b4d5/tensorflow_privacy/privacy/dp_query/no_privacy_query.py#L32-L34
bhoov/exbert
d27b6236aa51b185f7d3fed904f25cabe3baeb1a
server/transformers/examples/distillation/lm_seqs_dataset.py
python
LmSeqsDataset.print_statistics
(self)
Print some statistics on the corpus. Only the master process.
Print some statistics on the corpus. Only the master process.
[ "Print", "some", "statistics", "on", "the", "corpus", ".", "Only", "the", "master", "process", "." ]
def print_statistics(self): """ Print some statistics on the corpus. Only the master process. """ if not self.params.is_master: return logger.info(f"{len(self)} sequences")
[ "def", "print_statistics", "(", "self", ")", ":", "if", "not", "self", ".", "params", ".", "is_master", ":", "return", "logger", ".", "info", "(", "f\"{len(self)} sequences\"", ")" ]
https://github.com/bhoov/exbert/blob/d27b6236aa51b185f7d3fed904f25cabe3baeb1a/server/transformers/examples/distillation/lm_seqs_dataset.py#L129-L135
openvax/pyensembl
3fd9948ec6157db3061f74aa448fce1f1f914e98
pyensembl/database.py
python
Database.connect_or_create
(self, overwrite=False)
Return a connection to the database if it exists, otherwise create it. Overwrite the existing database if `overwrite` is True.
Return a connection to the database if it exists, otherwise create it. Overwrite the existing database if `overwrite` is True.
[ "Return", "a", "connection", "to", "the", "database", "if", "it", "exists", "otherwise", "create", "it", ".", "Overwrite", "the", "existing", "database", "if", "overwrite", "is", "True", "." ]
def connect_or_create(self, overwrite=False): """ Return a connection to the database if it exists, otherwise create it. Overwrite the existing database if `overwrite` is True. """ connection = self._get_connection() if connection: return connection else: return self.create(overwrite=overwrite)
[ "def", "connect_or_create", "(", "self", ",", "overwrite", "=", "False", ")", ":", "connection", "=", "self", ".", "_get_connection", "(", ")", "if", "connection", ":", "return", "connection", "else", ":", "return", "self", ".", "create", "(", "overwrite", ...
https://github.com/openvax/pyensembl/blob/3fd9948ec6157db3061f74aa448fce1f1f914e98/pyensembl/database.py#L284-L293
Map-A-Droid/MAD
81375b5c9ccc5ca3161eb487aa81469d40ded221
mapadroid/mad_apk/wizard.py
python
APKWizard.lookup_version_code
(self, version_code: str, arch: APKArch)
return 0
[]
def lookup_version_code(self, version_code: str, arch: APKArch) -> Optional[int]: named_arch = '32' if arch == APKArch.armeabi_v7a else '64' latest_version = f"{version_code}_{named_arch}" data = get_version_codes() if data: try: return data[latest_version] except KeyError: pass return 0
[ "def", "lookup_version_code", "(", "self", ",", "version_code", ":", "str", ",", "arch", ":", "APKArch", ")", "->", "Optional", "[", "int", "]", ":", "named_arch", "=", "'32'", "if", "arch", "==", "APKArch", ".", "armeabi_v7a", "else", "'64'", "latest_vers...
https://github.com/Map-A-Droid/MAD/blob/81375b5c9ccc5ca3161eb487aa81469d40ded221/mapadroid/mad_apk/wizard.py#L373-L382
kevoreilly/CAPEv2
6cf79c33264624b3604d4cd432cde2a6b4536de6
lib/cuckoo/common/abstracts.py
python
Signature.on_call
(self, call, process)
Notify signature about API call. Return value determines if this signature is done or could still match. @param call: logged API call. @param process: process doing API call. @raise NotImplementedError: this method is abstract.
Notify signature about API call. Return value determines if this signature is done or could still match.
[ "Notify", "signature", "about", "API", "call", ".", "Return", "value", "determines", "if", "this", "signature", "is", "done", "or", "could", "still", "match", "." ]
def on_call(self, call, process): """Notify signature about API call. Return value determines if this signature is done or could still match. @param call: logged API call. @param process: process doing API call. @raise NotImplementedError: this method is abstract. """ raise NotImplementedError
[ "def", "on_call", "(", "self", ",", "call", ",", "process", ")", ":", "raise", "NotImplementedError" ]
https://github.com/kevoreilly/CAPEv2/blob/6cf79c33264624b3604d4cd432cde2a6b4536de6/lib/cuckoo/common/abstracts.py#L1516-L1523
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/cls/v20201016/cls_client.py
python
ClsClient.CreateIndex
(self, request)
本接口用于创建索引 :param request: Request instance for CreateIndex. :type request: :class:`tencentcloud.cls.v20201016.models.CreateIndexRequest` :rtype: :class:`tencentcloud.cls.v20201016.models.CreateIndexResponse`
本接口用于创建索引
[ "本接口用于创建索引" ]
def CreateIndex(self, request): """本接口用于创建索引 :param request: Request instance for CreateIndex. :type request: :class:`tencentcloud.cls.v20201016.models.CreateIndexRequest` :rtype: :class:`tencentcloud.cls.v20201016.models.CreateIndexResponse` """ try: params = request._serialize() body = self.call("CreateIndex", params) response = json.loads(body) if "Error" not in response["Response"]: model = models.CreateIndexResponse() model._deserialize(response["Response"]) return model else: code = response["Response"]["Error"]["Code"] message = response["Response"]["Error"]["Message"] reqid = response["Response"]["RequestId"] raise TencentCloudSDKException(code, message, reqid) except Exception as e: if isinstance(e, TencentCloudSDKException): raise else: raise TencentCloudSDKException(e.message, e.message)
[ "def", "CreateIndex", "(", "self", ",", "request", ")", ":", "try", ":", "params", "=", "request", ".", "_serialize", "(", ")", "body", "=", "self", ".", "call", "(", "\"CreateIndex\"", ",", "params", ")", "response", "=", "json", ".", "loads", "(", ...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/cls/v20201016/cls_client.py#L197-L222
crossbario/autobahn-python
fa9f2da0c5005574e63456a3a04f00e405744014
autobahn/xbr/_seller.py
python
SimpleSeller.public_key
(self)
return self._pkey.public_key
This seller delegate public Ethereum key. :return: Ethereum public key of this seller delegate. :rtype: bytes
This seller delegate public Ethereum key.
[ "This", "seller", "delegate", "public", "Ethereum", "key", "." ]
def public_key(self): """ This seller delegate public Ethereum key. :return: Ethereum public key of this seller delegate. :rtype: bytes """ return self._pkey.public_key
[ "def", "public_key", "(", "self", ")", ":", "return", "self", ".", "_pkey", ".", "public_key" ]
https://github.com/crossbario/autobahn-python/blob/fa9f2da0c5005574e63456a3a04f00e405744014/autobahn/xbr/_seller.py#L269-L276
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
dist/lib/python2.7/numbers.py
python
Rational.__float__
(self)
return self.numerator / self.denominator
float(self) = self.numerator / self.denominator It's important that this conversion use the integer's "true" division rather than casting one side to float before dividing so that ratios of huge integers convert without overflowing.
float(self) = self.numerator / self.denominator
[ "float", "(", "self", ")", "=", "self", ".", "numerator", "/", "self", ".", "denominator" ]
def __float__(self): """float(self) = self.numerator / self.denominator It's important that this conversion use the integer's "true" division rather than casting one side to float before dividing so that ratios of huge integers convert without overflowing. """ return self.numerator / self.denominator
[ "def", "__float__", "(", "self", ")", ":", "return", "self", ".", "numerator", "/", "self", ".", "denominator" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/numbers.py#L284-L292
taigaio/taiga-ncurses
65312098f2d167762e0dbd1c16019754ab64d068
taiga_ncurses/data.py
python
issue_assigned_to_with_color
(issue, project, default_color="#ffffff")
return (default_color, "Unassigned")
[]
def issue_assigned_to_with_color(issue, project, default_color="#ffffff"): # FIXME: Improvement, get memberships and users from a project constant # TODO: Check that the color is in hex format user_id = issue.get("assigned_to", None) if user_id: memberships = {str(p["user"]): p for p in project["memberships"]} try: return (memberships[str(user_id)]["color"] or default_color, memberships[str(user_id)]["full_name"]) except KeyError: pass return (default_color, "Unassigned")
[ "def", "issue_assigned_to_with_color", "(", "issue", ",", "project", ",", "default_color", "=", "\"#ffffff\"", ")", ":", "# FIXME: Improvement, get memberships and users from a project constant", "# TODO: Check that the color is in hex format", "user_id", "=", "issue", ".", "get"...
https://github.com/taigaio/taiga-ncurses/blob/65312098f2d167762e0dbd1c16019754ab64d068/taiga_ncurses/data.py#L186-L197
TheAlgorithms/Python
9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c
project_euler/problem_045/sol1.py
python
solution
(start: int = 144)
return num
Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805
Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805
[ "Returns", "the", "next", "number", "which", "is", "triangular", "pentagonal", "and", "hexagonal", ".", ">>>", "solution", "(", "144", ")", "1533776805" ]
def solution(start: int = 144) -> int: """ Returns the next number which is triangular, pentagonal and hexagonal. >>> solution(144) 1533776805 """ n = start num = hexagonal_num(n) while not is_pentagonal(num): n += 1 num = hexagonal_num(n) return num
[ "def", "solution", "(", "start", ":", "int", "=", "144", ")", "->", "int", ":", "n", "=", "start", "num", "=", "hexagonal_num", "(", "n", ")", "while", "not", "is_pentagonal", "(", "num", ")", ":", "n", "+=", "1", "num", "=", "hexagonal_num", "(", ...
https://github.com/TheAlgorithms/Python/blob/9af2eef9b3761bf51580dedfb6fa7136ca0c5c2c/project_euler/problem_045/sol1.py#L44-L55
dexy/dexy
323c1806e51f75435e11d2265703e68f46c8aef3
dexy/node.py
python
Node.sorted_args
(self, skip=['contents'])
return sorted_args
Returns a list of args in sorted order.
Returns a list of args in sorted order.
[ "Returns", "a", "list", "of", "args", "in", "sorted", "order", "." ]
def sorted_args(self, skip=['contents']): """ Returns a list of args in sorted order. """ if not skip: skip = [] sorted_args = [] for k in sorted(self.args): if not k in skip: sorted_args.append((k, self.args[k])) return sorted_args
[ "def", "sorted_args", "(", "self", ",", "skip", "=", "[", "'contents'", "]", ")", ":", "if", "not", "skip", ":", "skip", "=", "[", "]", "sorted_args", "=", "[", "]", "for", "k", "in", "sorted", "(", "self", ".", "args", ")", ":", "if", "not", "...
https://github.com/dexy/dexy/blob/323c1806e51f75435e11d2265703e68f46c8aef3/dexy/node.py#L124-L135
mrlesmithjr/Ansible
d44f0dc0d942bdf3bf7334b307e6048f0ee16e36
roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
_version_from_file
(lines)
return safe_version(value.strip()) or None
Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise.
Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise.
[ "Given", "an", "iterable", "of", "lines", "from", "a", "Metadata", "file", "return", "the", "value", "of", "the", "Version", "field", "if", "present", "or", "None", "otherwise", "." ]
def _version_from_file(lines): """ Given an iterable of lines from a Metadata file, return the value of the Version field, if present, or None otherwise. """ is_version_line = lambda line: line.lower().startswith('version:') version_lines = filter(is_version_line, lines) line = next(iter(version_lines), '') _, _, value = line.partition(':') return safe_version(value.strip()) or None
[ "def", "_version_from_file", "(", "lines", ")", ":", "is_version_line", "=", "lambda", "line", ":", "line", ".", "lower", "(", ")", ".", "startswith", "(", "'version:'", ")", "version_lines", "=", "filter", "(", "is_version_line", ",", "lines", ")", "line", ...
https://github.com/mrlesmithjr/Ansible/blob/d44f0dc0d942bdf3bf7334b307e6048f0ee16e36/roles/ansible-vsphere-management/scripts/pdns/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L2391-L2400
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/py_compile.py
python
main
(args=None)
return rv
Compile several source files. The files named in 'args' (or on the command line, if 'args' is not specified) are compiled and the resulting bytecode is cached in the normal manner. This function does not search a directory structure to locate source files; it only compiles files named explicitly. If '-' is the only parameter in args, the list of files is taken from standard input.
Compile several source files.
[ "Compile", "several", "source", "files", "." ]
def main(args=None): """Compile several source files. The files named in 'args' (or on the command line, if 'args' is not specified) are compiled and the resulting bytecode is cached in the normal manner. This function does not search a directory structure to locate source files; it only compiles files named explicitly. If '-' is the only parameter in args, the list of files is taken from standard input. """ if args is None: args = sys.argv[1:] rv = 0 if args == ['-']: while True: filename = sys.stdin.readline() if not filename: break filename = filename.rstrip('\n') try: compile(filename, doraise=True) except PyCompileError as error: rv = 1 sys.stderr.write("%s\n" % error.msg) except IOError as error: rv = 1 sys.stderr.write("%s\n" % error) else: for filename in args: try: compile(filename, doraise=True) except PyCompileError as error: # return value to indicate at least one failure rv = 1 sys.stderr.write(error.msg) return rv
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "rv", "=", "0", "if", "args", "==", "[", "'-'", "]", ":", "while", "True", ":", "filename", "=", "sys", ...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/py_compile.py#L131-L167
spotify/luigi
c3b66f4a5fa7eaa52f9a72eb6704b1049035c789
luigi/contrib/mysqldb.py
python
CopyToTable.run
(self)
Inserts data generated by rows() into target table. If the target table doesn't exist, self.create_table will be called to attempt to create the table. Normally you don't want to override this.
Inserts data generated by rows() into target table.
[ "Inserts", "data", "generated", "by", "rows", "()", "into", "target", "table", "." ]
def run(self): """ Inserts data generated by rows() into target table. If the target table doesn't exist, self.create_table will be called to attempt to create the table. Normally you don't want to override this. """ if not (self.table and self.columns): raise Exception("table and columns need to be specified") connection = self.output().connect() # attempt to copy the data into mysql # if it fails because the target table doesn't exist # try to create it by running self.create_table for attempt in range(2): try: cursor = connection.cursor() print("caling init copy...") self.init_copy(connection) self.copy(cursor) self.post_copy(connection) if self.enable_metadata_columns: self.post_copy_metacolumns(cursor) except Error as err: if err.errno == errorcode.ER_NO_SUCH_TABLE and attempt == 0: # if first attempt fails with "relation not found", try creating table # logger.info("Creating table %s", self.table) connection.reconnect() self.create_table(connection) else: raise else: break # mark as complete in same transaction self.output().touch(connection) connection.commit() connection.close()
[ "def", "run", "(", "self", ")", ":", "if", "not", "(", "self", ".", "table", "and", "self", ".", "columns", ")", ":", "raise", "Exception", "(", "\"table and columns need to be specified\"", ")", "connection", "=", "self", ".", "output", "(", ")", ".", "...
https://github.com/spotify/luigi/blob/c3b66f4a5fa7eaa52f9a72eb6704b1049035c789/luigi/contrib/mysqldb.py#L207-L246
collinsctk/PyQYT
7af3673955f94ff1b2df2f94220cd2dab2e252af
ExtentionPackages/cffi/api.py
python
FFI.new
(self, cdecl, init=None)
return self._backend.newp(cdecl, init)
Allocate an instance according to the specified C type and return a pointer to it. The specified C type must be either a pointer or an array: ``new('X *')`` allocates an X and returns a pointer to it, whereas ``new('X[n]')`` allocates an array of n X'es and returns an array referencing it (which works mostly like a pointer, like in C). You can also use ``new('X[]', n)`` to allocate an array of a non-constant length n. The memory is initialized following the rules of declaring a global variable in C: by default it is zero-initialized, but an explicit initializer can be given which can be used to fill all or part of the memory. When the returned <cdata> object goes out of scope, the memory is freed. In other words the returned <cdata> object has ownership of the value of type 'cdecl' that it points to. This means that the raw data can be used as long as this object is kept alive, but must not be used for a longer time. Be careful about that when copying the pointer to the memory somewhere else, e.g. into another structure.
Allocate an instance according to the specified C type and return a pointer to it. The specified C type must be either a pointer or an array: ``new('X *')`` allocates an X and returns a pointer to it, whereas ``new('X[n]')`` allocates an array of n X'es and returns an array referencing it (which works mostly like a pointer, like in C). You can also use ``new('X[]', n)`` to allocate an array of a non-constant length n.
[ "Allocate", "an", "instance", "according", "to", "the", "specified", "C", "type", "and", "return", "a", "pointer", "to", "it", ".", "The", "specified", "C", "type", "must", "be", "either", "a", "pointer", "or", "an", "array", ":", "new", "(", "X", "*",...
def new(self, cdecl, init=None): """Allocate an instance according to the specified C type and return a pointer to it. The specified C type must be either a pointer or an array: ``new('X *')`` allocates an X and returns a pointer to it, whereas ``new('X[n]')`` allocates an array of n X'es and returns an array referencing it (which works mostly like a pointer, like in C). You can also use ``new('X[]', n)`` to allocate an array of a non-constant length n. The memory is initialized following the rules of declaring a global variable in C: by default it is zero-initialized, but an explicit initializer can be given which can be used to fill all or part of the memory. When the returned <cdata> object goes out of scope, the memory is freed. In other words the returned <cdata> object has ownership of the value of type 'cdecl' that it points to. This means that the raw data can be used as long as this object is kept alive, but must not be used for a longer time. Be careful about that when copying the pointer to the memory somewhere else, e.g. into another structure. """ if isinstance(cdecl, basestring): cdecl = self._typeof(cdecl) return self._backend.newp(cdecl, init)
[ "def", "new", "(", "self", ",", "cdecl", ",", "init", "=", "None", ")", ":", "if", "isinstance", "(", "cdecl", ",", "basestring", ")", ":", "cdecl", "=", "self", ".", "_typeof", "(", "cdecl", ")", "return", "self", ".", "_backend", ".", "newp", "("...
https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/cffi/api.py#L224-L249
brosner/everyblock_code
25397148223dad81e7fbb9c7cf2f169162df4681
ebdata/ebdata/templatemaker/sst.py
python
tree_diff
(tree1, tree2, algorithm=1)
return result
Returns a "diff" of the two etree objects, using these placeholders in case of differences: TEXT_HOLE -- used when the 'text' differs TAIL_HOLE -- used when the 'tail' differs ATTRIB_HOLE -- used when an attribute value (or existence) differs MULTITAG_HOLE -- used when an element's children differ This assumes tree1 and tree2 share the same root tag, e.g. "<html>".
Returns a "diff" of the two etree objects, using these placeholders in case of differences: TEXT_HOLE -- used when the 'text' differs TAIL_HOLE -- used when the 'tail' differs ATTRIB_HOLE -- used when an attribute value (or existence) differs MULTITAG_HOLE -- used when an element's children differ
[ "Returns", "a", "diff", "of", "the", "two", "etree", "objects", "using", "these", "placeholders", "in", "case", "of", "differences", ":", "TEXT_HOLE", "--", "used", "when", "the", "text", "differs", "TAIL_HOLE", "--", "used", "when", "the", "tail", "differs"...
def tree_diff(tree1, tree2, algorithm=1): """ Returns a "diff" of the two etree objects, using these placeholders in case of differences: TEXT_HOLE -- used when the 'text' differs TAIL_HOLE -- used when the 'tail' differs ATTRIB_HOLE -- used when an attribute value (or existence) differs MULTITAG_HOLE -- used when an element's children differ This assumes tree1 and tree2 share the same root tag, e.g. "<html>". """ # Copy the element (but not its children). result = etree.Element(tree1.tag) result.text = (tree1.text != tree2.text) and 'TEXT_HOLE' or tree1.text result.tail = (tree1.tail != tree2.tail) and 'TAIL_HOLE' or tree1.tail attrs1, attrs2 = dict(tree1.attrib), dict(tree2.attrib) for k1, v1 in attrs1.items(): if attrs2.pop(k1, None) == v1: result.attrib[k1] = v1 else: result.attrib[k1] = 'ATTRIB_HOLE' for k2 in attrs2.keys(): result.attrib[k2] = 'ATTRIB_HOLE' if algorithm == 1: for child in tree_diff_children(list(tree1), list(tree2), element_hash_strict, algorithm): result.append(child) elif algorithm == 2: if [child.tag for child in tree1] == [child.tag for child in tree2]: for i, child in enumerate(tree1): diff_child = tree_diff(child, tree2[i], algorithm) result.append(diff_child) else: result.append(etree.Element('MULTITAG_HOLE')) else: raise ValueError('Got invalid algorithm: %r' % algorithm) return result
[ "def", "tree_diff", "(", "tree1", ",", "tree2", ",", "algorithm", "=", "1", ")", ":", "# Copy the element (but not its children).", "result", "=", "etree", ".", "Element", "(", "tree1", ".", "tag", ")", "result", ".", "text", "=", "(", "tree1", ".", "text"...
https://github.com/brosner/everyblock_code/blob/25397148223dad81e7fbb9c7cf2f169162df4681/ebdata/ebdata/templatemaker/sst.py#L72-L107
gnome-terminator/terminator
ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1
terminatorlib/titlebar.py
python
Titlebar.__init__
(self, terminal)
Class initialiser
Class initialiser
[ "Class", "initialiser" ]
def __init__(self, terminal): """Class initialiser""" GObject.GObject.__init__(self) self.terminator = Terminator() self.terminal = terminal self.config = self.terminal.config self.label = EditableLabel() self.label.connect('edit-done', self.on_edit_done) self.ebox = Gtk.EventBox() grouphbox = Gtk.HBox() self.grouplabel = Gtk.Label(ellipsize='end') self.groupicon = Gtk.Image() self.bellicon = Gtk.Image() self.bellicon.set_no_show_all(True) self.groupentry = Gtk.Entry() self.groupentry.set_no_show_all(True) self.groupentry.connect('focus-out-event', self.groupentry_cancel) self.groupentry.connect('activate', self.groupentry_activate) self.groupentry.connect('key-press-event', self.groupentry_keypress) groupsend_type = self.terminator.groupsend_type if self.terminator.groupsend == groupsend_type['all']: icon_name = 'all' elif self.terminator.groupsend == groupsend_type['group']: icon_name = 'group' elif self.terminator.groupsend == groupsend_type['off']: icon_name = 'off' self.set_from_icon_name('_active_broadcast_%s' % icon_name, Gtk.IconSize.MENU) grouphbox.pack_start(self.groupicon, False, True, 2) grouphbox.pack_start(self.grouplabel, False, True, 2) grouphbox.pack_start(self.groupentry, False, True, 2) self.ebox.add(grouphbox) self.ebox.show_all() self.bellicon.set_from_icon_name('terminal-bell', Gtk.IconSize.MENU) viewport = Gtk.Viewport(hscroll_policy='natural') viewport.add(self.label) hbox = Gtk.HBox() hbox.pack_start(self.ebox, False, True, 0) hbox.pack_start(Gtk.VSeparator(), False, True, 0) hbox.pack_start(viewport, True, True, 0) hbox.pack_end(self.bellicon, False, False, 2) self.add(hbox) hbox.show_all() self.set_no_show_all(True) self.show() self.connect('button-press-event', self.on_clicked)
[ "def", "__init__", "(", "self", ",", "terminal", ")", ":", "GObject", ".", "GObject", ".", "__init__", "(", "self", ")", "self", ".", "terminator", "=", "Terminator", "(", ")", "self", ".", "terminal", "=", "terminal", "self", ".", "config", "=", "self...
https://github.com/gnome-terminator/terminator/blob/ca335e45eb1a4ea7c22fe0d515bb270e9a0e12a1/terminatorlib/titlebar.py#L42-L98
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/deps/oscrypto/_openssl/_libcrypto.py
python
peek_openssl_error
()
return (lib, func, reason)
Peeks into the error stack and pulls out the lib, func and reason :return: A three-element tuple of integers (lib, func, reason)
Peeks into the error stack and pulls out the lib, func and reason
[ "Peeks", "into", "the", "error", "stack", "and", "pulls", "out", "the", "lib", "func", "and", "reason" ]
def peek_openssl_error(): """ Peeks into the error stack and pulls out the lib, func and reason :return: A three-element tuple of integers (lib, func, reason) """ error = libcrypto.ERR_peek_error() lib = int((error >> 24) & 0xff) func = int((error >> 12) & 0xfff) reason = int(error & 0xfff) return (lib, func, reason)
[ "def", "peek_openssl_error", "(", ")", ":", "error", "=", "libcrypto", ".", "ERR_peek_error", "(", ")", "lib", "=", "int", "(", "(", "error", ">>", "24", ")", "&", "0xff", ")", "func", "=", "int", "(", "(", "error", ">>", "12", ")", "&", "0xfff", ...
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/deps/oscrypto/_openssl/_libcrypto.py#L89-L102
CiscoDevNet/webexteamssdk
673312779b8e05cf0535bea8b96599015cccbff1
webexteamssdk/models/mixins/access_token.py
python
AccessTokenBasicPropertiesMixin.refresh_token
(self)
return self._json_data.get('refresh_token')
Refresh token used to request a new/refreshed access token.
Refresh token used to request a new/refreshed access token.
[ "Refresh", "token", "used", "to", "request", "a", "new", "/", "refreshed", "access", "token", "." ]
def refresh_token(self): """Refresh token used to request a new/refreshed access token.""" return self._json_data.get('refresh_token')
[ "def", "refresh_token", "(", "self", ")", ":", "return", "self", ".", "_json_data", ".", "get", "(", "'refresh_token'", ")" ]
https://github.com/CiscoDevNet/webexteamssdk/blob/673312779b8e05cf0535bea8b96599015cccbff1/webexteamssdk/models/mixins/access_token.py#L50-L52
tebesu/CollaborativeMemoryNetwork
0cbdc359b3858d40ea2d1090d72bfaca678066fb
util/layers.py
python
LossLayer._build
(self, X, y)
return self._loss
:param X: predicted value :param y: ground truth :returns: Loss with l1/l2 regularization added if in keys
[]
def _build(self, X, y): """ :param X: predicted value :param y: ground truth :returns: Loss with l1/l2 regularization added if in keys """ graph_regularizers = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES) self._loss = tf.squeeze(_bpr_loss(X, y)) self._regularization = None self._loss_no_regularization = self._loss # Add regularization if graph_regularizers: self._regularization = tf.reduce_sum(graph_regularizers) tf.add_to_collection(GraphKeys.LOSS_REG, self._regularization) tf.add_to_collection(GraphKeys.LOSS_NO_REG, self._loss) self._loss = self._loss + self._regularization tf.add_to_collection(GraphKeys.LOSSES, self._loss) return self._loss
[ "def", "_build", "(", "self", ",", "X", ",", "y", ")", ":", "graph_regularizers", "=", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "REGULARIZATION_LOSSES", ")", "self", ".", "_loss", "=", "tf", ".", "squeeze", "(", "_bpr_loss", "(", ...
https://github.com/tebesu/CollaborativeMemoryNetwork/blob/0cbdc359b3858d40ea2d1090d72bfaca678066fb/util/layers.py#L55-L76
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/db/sqlalchemy/api.py
python
_quota_reservations_query
(session, context, reservations)
return model_query(context, models.Reservation, read_deleted="no", session=session).\ filter(models.Reservation.uuid.in_(reservations)).\ with_lockmode('update')
Return the relevant reservations.
Return the relevant reservations.
[ "Return", "the", "relevant", "reservations", "." ]
def _quota_reservations_query(session, context, reservations): """Return the relevant reservations.""" # Get the listed reservations return model_query(context, models.Reservation, read_deleted="no", session=session).\ filter(models.Reservation.uuid.in_(reservations)).\ with_lockmode('update')
[ "def", "_quota_reservations_query", "(", "session", ",", "context", ",", "reservations", ")", ":", "# Get the listed reservations", "return", "model_query", "(", "context", ",", "models", ".", "Reservation", ",", "read_deleted", "=", "\"no\"", ",", "session", "=", ...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/db/sqlalchemy/api.py#L2764-L2772
rajatomar788/pywebcopy
a7b030fe588bf24737d2f6ff7443598cbe429ca3
pywebcopy/elements.py
python
GenericResource.filepath
(self)
return self.context.resolve()
Returns if available a valid filepath where this file should be written.
Returns if available a valid filepath where this file should be written.
[ "Returns", "if", "available", "a", "valid", "filepath", "where", "this", "file", "should", "be", "written", "." ]
def filepath(self): """Returns if available a valid filepath where this file should be written.""" if self.context is None: raise AttributeError("Context attribute is not set.") if self.response is not None: ctypes = get_content_type_from_headers(self.response.headers) self.context = self.context.with_values(content_type=ctypes) return self.context.resolve()
[ "def", "filepath", "(", "self", ")", ":", "if", "self", ".", "context", "is", "None", ":", "raise", "AttributeError", "(", "\"Context attribute is not set.\"", ")", "if", "self", ".", "response", "is", "not", "None", ":", "ctypes", "=", "get_content_type_from_...
https://github.com/rajatomar788/pywebcopy/blob/a7b030fe588bf24737d2f6ff7443598cbe429ca3/pywebcopy/elements.py#L189-L197
dhondta/python-sploitkit
501ee5c034189d39e2ed76e9ccf6a538ab638409
sploitkit/core/entity.py
python
Entity.unregister_subclasses
(cls, *subclss)
Remove entries from the registry of subclasses.
Remove entries from the registry of subclasses.
[ "Remove", "entries", "from", "the", "registry", "of", "subclasses", "." ]
def unregister_subclasses(cls, *subclss): """ Remove entries from the registry of subclasses. """ for subcls in subclss: cls.unregister_subclass(subcls)
[ "def", "unregister_subclasses", "(", "cls", ",", "*", "subclss", ")", ":", "for", "subcls", "in", "subclss", ":", "cls", ".", "unregister_subclass", "(", "subcls", ")" ]
https://github.com/dhondta/python-sploitkit/blob/501ee5c034189d39e2ed76e9ccf6a538ab638409/sploitkit/core/entity.py#L554-L557
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/icicle/_marker.py
python
Marker.cmax
(self)
return self["cmax"]
Sets the upper bound of the color domain. Has an effect only if colorsis set to a numerical array. Value should have the same units as colors and if set, `marker.cmin` must be set as well. The 'cmax' property is a number and may be specified as: - An int or float Returns ------- int|float
Sets the upper bound of the color domain. Has an effect only if colorsis set to a numerical array. Value should have the same units as colors and if set, `marker.cmin` must be set as well. The 'cmax' property is a number and may be specified as: - An int or float
[ "Sets", "the", "upper", "bound", "of", "the", "color", "domain", ".", "Has", "an", "effect", "only", "if", "colorsis", "set", "to", "a", "numerical", "array", ".", "Value", "should", "have", "the", "same", "units", "as", "colors", "and", "if", "set", "...
def cmax(self): """ Sets the upper bound of the color domain. Has an effect only if colorsis set to a numerical array. Value should have the same units as colors and if set, `marker.cmin` must be set as well. The 'cmax' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["cmax"]
[ "def", "cmax", "(", "self", ")", ":", "return", "self", "[", "\"cmax\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/icicle/_marker.py#L80-L93