repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
hobson/pug-ann | pug/ann/example.py | train_weather_predictor | def train_weather_predictor(
location='Portland, OR',
years=range(2013, 2016,),
delays=(1, 2, 3),
inputs=('Min Temperature', 'Max Temperature', 'Min Sea Level Pressure', u'Max Sea Level Pressure', 'WindDirDegrees',),
outputs=(u'Max TemperatureF',),
N_hidden=6,
epochs=30,
use_cache=False,
verbosity=2,
):
"""Train a neural nerual net to predict the weather for tomorrow based on past weather.
Builds a linear single hidden layer neural net (multi-dimensional nonlinear regression).
The dataset is a basic SupervisedDataSet rather than a SequentialDataSet, so the training set
and the test set are sampled randomly. This means that historical data for one sample (the delayed
input vector) will likely be used as the target for other samples.
Uses CSVs scraped from wunderground (without an api key) to get daily weather for the years indicated.
Arguments:
location (str): City and state in standard US postal service format: "City, ST"
alternatively an airport code like "PDX or LAX"
delays (list of int): sample delays to use for the input tapped delay line.
Positive and negative values are treated the same as sample counts into the past.
default: [1, 2, 3], in z-transform notation: z^-1 + z^-2 + z^-3
years (int or list of int): list of 4-digit years to download weather from wunderground
inputs (list of int or list of str): column indices or labels for the inputs
outputs (list of int or list of str): column indices or labels for the outputs
Returns:
3-tuple: tuple(dataset, list of means, list of stds)
means and stds allow normalization of new inputs and denormalization of the outputs
"""
df = weather.daily(location, years=years, use_cache=use_cache, verbosity=verbosity).sort()
ds = util.dataset_from_dataframe(df, normalize=False, delays=delays, inputs=inputs, outputs=outputs, verbosity=verbosity)
nn = util.ann_from_ds(ds, N_hidden=N_hidden, verbosity=verbosity)
trainer = util.build_trainer(nn, ds=ds, verbosity=verbosity)
trainer.trainEpochs(epochs)
columns = []
for delay in delays:
columns += [inp + "[-{}]".format(delay) for inp in inputs]
columns += list(outputs)
columns += ['Predicted {}'.format(outp) for outp in outputs]
table = [list(i) + list(t) + list(trainer.module.activate(i)) for i, t in zip(trainer.ds['input'], trainer.ds['target'])]
df = pd.DataFrame(table, columns=columns, index=df.index[max(delays):])
#comparison = df[[] + list(outputs)]
return trainer, df | python | def train_weather_predictor(
location='Portland, OR',
years=range(2013, 2016,),
delays=(1, 2, 3),
inputs=('Min Temperature', 'Max Temperature', 'Min Sea Level Pressure', u'Max Sea Level Pressure', 'WindDirDegrees',),
outputs=(u'Max TemperatureF',),
N_hidden=6,
epochs=30,
use_cache=False,
verbosity=2,
):
"""Train a neural nerual net to predict the weather for tomorrow based on past weather.
Builds a linear single hidden layer neural net (multi-dimensional nonlinear regression).
The dataset is a basic SupervisedDataSet rather than a SequentialDataSet, so the training set
and the test set are sampled randomly. This means that historical data for one sample (the delayed
input vector) will likely be used as the target for other samples.
Uses CSVs scraped from wunderground (without an api key) to get daily weather for the years indicated.
Arguments:
location (str): City and state in standard US postal service format: "City, ST"
alternatively an airport code like "PDX or LAX"
delays (list of int): sample delays to use for the input tapped delay line.
Positive and negative values are treated the same as sample counts into the past.
default: [1, 2, 3], in z-transform notation: z^-1 + z^-2 + z^-3
years (int or list of int): list of 4-digit years to download weather from wunderground
inputs (list of int or list of str): column indices or labels for the inputs
outputs (list of int or list of str): column indices or labels for the outputs
Returns:
3-tuple: tuple(dataset, list of means, list of stds)
means and stds allow normalization of new inputs and denormalization of the outputs
"""
df = weather.daily(location, years=years, use_cache=use_cache, verbosity=verbosity).sort()
ds = util.dataset_from_dataframe(df, normalize=False, delays=delays, inputs=inputs, outputs=outputs, verbosity=verbosity)
nn = util.ann_from_ds(ds, N_hidden=N_hidden, verbosity=verbosity)
trainer = util.build_trainer(nn, ds=ds, verbosity=verbosity)
trainer.trainEpochs(epochs)
columns = []
for delay in delays:
columns += [inp + "[-{}]".format(delay) for inp in inputs]
columns += list(outputs)
columns += ['Predicted {}'.format(outp) for outp in outputs]
table = [list(i) + list(t) + list(trainer.module.activate(i)) for i, t in zip(trainer.ds['input'], trainer.ds['target'])]
df = pd.DataFrame(table, columns=columns, index=df.index[max(delays):])
#comparison = df[[] + list(outputs)]
return trainer, df | [
"def",
"train_weather_predictor",
"(",
"location",
"=",
"'Portland, OR'",
",",
"years",
"=",
"range",
"(",
"2013",
",",
"2016",
",",
")",
",",
"delays",
"=",
"(",
"1",
",",
"2",
",",
"3",
")",
",",
"inputs",
"=",
"(",
"'Min Temperature'",
",",
"'Max Te... | Train a neural nerual net to predict the weather for tomorrow based on past weather.
Builds a linear single hidden layer neural net (multi-dimensional nonlinear regression).
The dataset is a basic SupervisedDataSet rather than a SequentialDataSet, so the training set
and the test set are sampled randomly. This means that historical data for one sample (the delayed
input vector) will likely be used as the target for other samples.
Uses CSVs scraped from wunderground (without an api key) to get daily weather for the years indicated.
Arguments:
location (str): City and state in standard US postal service format: "City, ST"
alternatively an airport code like "PDX or LAX"
delays (list of int): sample delays to use for the input tapped delay line.
Positive and negative values are treated the same as sample counts into the past.
default: [1, 2, 3], in z-transform notation: z^-1 + z^-2 + z^-3
years (int or list of int): list of 4-digit years to download weather from wunderground
inputs (list of int or list of str): column indices or labels for the inputs
outputs (list of int or list of str): column indices or labels for the outputs
Returns:
3-tuple: tuple(dataset, list of means, list of stds)
means and stds allow normalization of new inputs and denormalization of the outputs | [
"Train",
"a",
"neural",
"nerual",
"net",
"to",
"predict",
"the",
"weather",
"for",
"tomorrow",
"based",
"on",
"past",
"weather",
"."
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/example.py#L28-L79 |
hobson/pug-ann | pug/ann/example.py | oneday_weather_forecast | def oneday_weather_forecast(
location='Portland, OR',
inputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity', 'Mean Humidity', 'Min Humidity', 'Max Sea Level Pressure', 'Mean Sea Level Pressure', 'Min Sea Level Pressure', 'Wind Direction'),
outputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity'),
date=None,
epochs=200,
delays=(1, 2, 3, 4),
num_years=4,
use_cache=False,
verbosity=1,
):
""" Provide a weather forecast for tomorrow based on historical weather at that location """
date = make_date(date or datetime.datetime.now().date())
num_years = int(num_years or 10)
years = range(date.year - num_years, date.year + 1)
df = weather.daily(location, years=years, use_cache=use_cache, verbosity=verbosity).sort()
# because up-to-date weather history was cached above, can use that cache, regardless of use_cache kwarg
trainer, df = train_weather_predictor(
location,
years=years,
delays=delays,
inputs=inputs,
outputs=outputs,
epochs=epochs,
verbosity=verbosity,
use_cache=True,
)
nn = trainer.module
forecast = {'trainer': trainer}
yesterday = dict(zip(outputs, nn.activate(trainer.ds['input'][-2])))
forecast['yesterday'] = update_dict(yesterday, {'date': df.index[-2].date()})
today = dict(zip(outputs, nn.activate(trainer.ds['input'][-1])))
forecast['today'] = update_dict(today, {'date': df.index[-1].date()})
ds = util.input_dataset_from_dataframe(df[-max(delays):], delays=delays, inputs=inputs, normalize=False, verbosity=0)
tomorrow = dict(zip(outputs, nn.activate(ds['input'][-1])))
forecast['tomorrow'] = update_dict(tomorrow, {'date': (df.index[-1] + datetime.timedelta(1)).date()})
return forecast | python | def oneday_weather_forecast(
location='Portland, OR',
inputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity', 'Mean Humidity', 'Min Humidity', 'Max Sea Level Pressure', 'Mean Sea Level Pressure', 'Min Sea Level Pressure', 'Wind Direction'),
outputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity'),
date=None,
epochs=200,
delays=(1, 2, 3, 4),
num_years=4,
use_cache=False,
verbosity=1,
):
""" Provide a weather forecast for tomorrow based on historical weather at that location """
date = make_date(date or datetime.datetime.now().date())
num_years = int(num_years or 10)
years = range(date.year - num_years, date.year + 1)
df = weather.daily(location, years=years, use_cache=use_cache, verbosity=verbosity).sort()
# because up-to-date weather history was cached above, can use that cache, regardless of use_cache kwarg
trainer, df = train_weather_predictor(
location,
years=years,
delays=delays,
inputs=inputs,
outputs=outputs,
epochs=epochs,
verbosity=verbosity,
use_cache=True,
)
nn = trainer.module
forecast = {'trainer': trainer}
yesterday = dict(zip(outputs, nn.activate(trainer.ds['input'][-2])))
forecast['yesterday'] = update_dict(yesterday, {'date': df.index[-2].date()})
today = dict(zip(outputs, nn.activate(trainer.ds['input'][-1])))
forecast['today'] = update_dict(today, {'date': df.index[-1].date()})
ds = util.input_dataset_from_dataframe(df[-max(delays):], delays=delays, inputs=inputs, normalize=False, verbosity=0)
tomorrow = dict(zip(outputs, nn.activate(ds['input'][-1])))
forecast['tomorrow'] = update_dict(tomorrow, {'date': (df.index[-1] + datetime.timedelta(1)).date()})
return forecast | [
"def",
"oneday_weather_forecast",
"(",
"location",
"=",
"'Portland, OR'",
",",
"inputs",
"=",
"(",
"'Min Temperature'",
",",
"'Mean Temperature'",
",",
"'Max Temperature'",
",",
"'Max Humidity'",
",",
"'Mean Humidity'",
",",
"'Min Humidity'",
",",
"'Max Sea Level Pressure... | Provide a weather forecast for tomorrow based on historical weather at that location | [
"Provide",
"a",
"weather",
"forecast",
"for",
"tomorrow",
"based",
"on",
"historical",
"weather",
"at",
"that",
"location"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/example.py#L82-L122 |
hobson/pug-ann | pug/ann/example.py | run_competition | def run_competition(builders=[], task=BalanceTask(), Optimizer=HillClimber, rounds=3, max_eval=20, N_hidden=3, verbosity=0):
""" pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them!
Arguments:
task (Task): task to compete at
Optimizer (class): pybrain.Optimizer class to instantiate for each competitor
rounds (int): number of times to run the competition
max_eval (int): number of objective function evaluations that the optimizer is allowed
in each round
N_hidden (int): number of hidden nodes in each network being competed
The functional difference that I can see is that:
buildNetwork connects the bias to the output
build_ann does not
The api differences are:
build_ann allows heterogeneous layer types but the output layer is always linear
buildNetwork allows specification of the output layer type
"""
results = []
builders = list(builders) + [buildNetwork, util.build_ann]
for r in range(rounds):
heat = []
# FIXME: shuffle the order of the builders to keep things fair
# (like switching sides of the tennis court)
for builder in builders:
try:
competitor = builder(task.outdim, N_hidden, task.indim, verbosity=verbosity)
except NetworkError:
competitor = builder(task.outdim, N_hidden, task.indim)
# TODO: verify that a full reset is actually happening
task.reset()
optimizer = Optimizer(task, competitor, maxEvaluations=max_eval)
t0 = time.time()
nn, nn_best = optimizer.learn()
t1 = time.time()
heat += [(nn_best, t1-t0, nn)]
results += [tuple(heat)]
if verbosity >= 0:
print([competitor_scores[:2] for competitor_scores in heat])
# # alternatively:
# agent = ( pybrain.rl.agents.OptimizationAgent(net, HillClimber())
# or
# pybrain.rl.agents.LearningAgent(net, pybrain.rl.learners.ENAC()) )
# exp = pybrain.rl.experiments.EpisodicExperiment(task, agent).doEpisodes(100)
means = [[np.array([r[i][j] for r in results]).mean() for i in range(len(results[0]))] for j in range(2)]
if verbosity > -1:
print('Mean Performance:')
print(means)
perfi, speedi = np.argmax(means[0]), np.argmin(means[1])
print('And the winner for performance is ... Algorithm #{} (0-offset array index [{}])'.format(perfi+1, perfi))
print('And the winner for speed is ... Algorithm #{} (0-offset array index [{}])'.format(speedi+1, speedi))
return results, means | python | def run_competition(builders=[], task=BalanceTask(), Optimizer=HillClimber, rounds=3, max_eval=20, N_hidden=3, verbosity=0):
""" pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them!
Arguments:
task (Task): task to compete at
Optimizer (class): pybrain.Optimizer class to instantiate for each competitor
rounds (int): number of times to run the competition
max_eval (int): number of objective function evaluations that the optimizer is allowed
in each round
N_hidden (int): number of hidden nodes in each network being competed
The functional difference that I can see is that:
buildNetwork connects the bias to the output
build_ann does not
The api differences are:
build_ann allows heterogeneous layer types but the output layer is always linear
buildNetwork allows specification of the output layer type
"""
results = []
builders = list(builders) + [buildNetwork, util.build_ann]
for r in range(rounds):
heat = []
# FIXME: shuffle the order of the builders to keep things fair
# (like switching sides of the tennis court)
for builder in builders:
try:
competitor = builder(task.outdim, N_hidden, task.indim, verbosity=verbosity)
except NetworkError:
competitor = builder(task.outdim, N_hidden, task.indim)
# TODO: verify that a full reset is actually happening
task.reset()
optimizer = Optimizer(task, competitor, maxEvaluations=max_eval)
t0 = time.time()
nn, nn_best = optimizer.learn()
t1 = time.time()
heat += [(nn_best, t1-t0, nn)]
results += [tuple(heat)]
if verbosity >= 0:
print([competitor_scores[:2] for competitor_scores in heat])
# # alternatively:
# agent = ( pybrain.rl.agents.OptimizationAgent(net, HillClimber())
# or
# pybrain.rl.agents.LearningAgent(net, pybrain.rl.learners.ENAC()) )
# exp = pybrain.rl.experiments.EpisodicExperiment(task, agent).doEpisodes(100)
means = [[np.array([r[i][j] for r in results]).mean() for i in range(len(results[0]))] for j in range(2)]
if verbosity > -1:
print('Mean Performance:')
print(means)
perfi, speedi = np.argmax(means[0]), np.argmin(means[1])
print('And the winner for performance is ... Algorithm #{} (0-offset array index [{}])'.format(perfi+1, perfi))
print('And the winner for speed is ... Algorithm #{} (0-offset array index [{}])'.format(speedi+1, speedi))
return results, means | [
"def",
"run_competition",
"(",
"builders",
"=",
"[",
"]",
",",
"task",
"=",
"BalanceTask",
"(",
")",
",",
"Optimizer",
"=",
"HillClimber",
",",
"rounds",
"=",
"3",
",",
"max_eval",
"=",
"20",
",",
"N_hidden",
"=",
"3",
",",
"verbosity",
"=",
"0",
")"... | pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them!
Arguments:
task (Task): task to compete at
Optimizer (class): pybrain.Optimizer class to instantiate for each competitor
rounds (int): number of times to run the competition
max_eval (int): number of objective function evaluations that the optimizer is allowed
in each round
N_hidden (int): number of hidden nodes in each network being competed
The functional difference that I can see is that:
buildNetwork connects the bias to the output
build_ann does not
The api differences are:
build_ann allows heterogeneous layer types but the output layer is always linear
buildNetwork allows specification of the output layer type | [
"pybrain",
"buildNetwork",
"builds",
"a",
"subtly",
"different",
"network",
"structhan",
"build_ann",
"...",
"so",
"compete",
"them!"
] | train | https://github.com/hobson/pug-ann/blob/8a4d7103a744d15b4a737fc0f9a84c823973e0ec/pug/ann/example.py#L286-L347 |
bioidiap/gridtk | gridtk/setshell.py | environ | def environ(context):
"""Retrieves the environment for a particular SETSHELL context"""
if 'BASEDIRSETSHELL' not in os.environ:
# It seems that we are in a hostile environment
# try to source the Idiap-wide shell
idiap_source = "/idiap/resource/software/initfiles/shrc"
if os.path.exists(idiap_source):
logger.debug("Sourcing: '%s'"%idiap_source)
try:
command = ['bash', '-c', 'source %s && env' % idiap_source]
pi = subprocess.Popen(command, stdout = subprocess.PIPE)
# overwrite the default environment
for line in pi.stdout:
line = str_(line)
(key, _, value) = line.partition("=")
os.environ[key.strip()] = value.strip()
except OSError as e:
# occurs when the file is not executable or not found
pass
# in case the BASEDIRSETSHELL environment variable is not set,
# we are not at Idiap,
# and so we don't have to set any additional variables.
if 'BASEDIRSETSHELL' not in os.environ:
return dict(os.environ)
BASEDIRSETSHELL = os.environ['BASEDIRSETSHELL']
dosetshell = '%s/setshell/bin/dosetshell' % BASEDIRSETSHELL
command = [dosetshell, '-s', 'sh', context]
# First things first, we get the path to the temp file created by dosetshell
try:
logger.debug("Executing: '%s'", ' '.join(command))
p = subprocess.Popen(command, stdout = subprocess.PIPE)
except OSError as e:
# occurs when the file is not executable or not found
raise OSError("Error executing '%s': %s (%d)" % (' '.join(command), e.strerror, e.errno))
try:
source = str_(p.communicate()[0]).strip()
except KeyboardInterrupt: # the user CTRL-C'ed
os.kill(p.pid, signal.SIGTERM)
sys.exit(signal.SIGTERM)
# We have now the name of the source file, source it and erase it
command2 = ['bash', '-c', 'source %s && env' % source]
try:
logger.debug("Executing: '%s'", ' '.join(command2))
p2 = subprocess.Popen(command2, stdout = subprocess.PIPE)
except OSError as e:
# occurs when the file is not executable or not found
raise OSError("Error executing '%s': %s (%d)" % (' '.join(command2), e.strerror, e.errno))
new_environ = dict(os.environ)
for line in p2.stdout:
line = str_(line)
(key, _, value) = line.partition("=")
new_environ[key.strip()] = value.strip()
try:
p2.communicate()
except KeyboardInterrupt: # the user CTRL-C'ed
os.kill(p2.pid, signal.SIGTERM)
sys.exit(signal.SIGTERM)
if os.path.exists(source): os.unlink(source)
logger.debug("Discovered environment for context '%s':", context)
for k in sorted(new_environ.keys()):
logger.debug(" %s = %s", k, new_environ[k])
return new_environ | python | def environ(context):
"""Retrieves the environment for a particular SETSHELL context"""
if 'BASEDIRSETSHELL' not in os.environ:
# It seems that we are in a hostile environment
# try to source the Idiap-wide shell
idiap_source = "/idiap/resource/software/initfiles/shrc"
if os.path.exists(idiap_source):
logger.debug("Sourcing: '%s'"%idiap_source)
try:
command = ['bash', '-c', 'source %s && env' % idiap_source]
pi = subprocess.Popen(command, stdout = subprocess.PIPE)
# overwrite the default environment
for line in pi.stdout:
line = str_(line)
(key, _, value) = line.partition("=")
os.environ[key.strip()] = value.strip()
except OSError as e:
# occurs when the file is not executable or not found
pass
# in case the BASEDIRSETSHELL environment variable is not set,
# we are not at Idiap,
# and so we don't have to set any additional variables.
if 'BASEDIRSETSHELL' not in os.environ:
return dict(os.environ)
BASEDIRSETSHELL = os.environ['BASEDIRSETSHELL']
dosetshell = '%s/setshell/bin/dosetshell' % BASEDIRSETSHELL
command = [dosetshell, '-s', 'sh', context]
# First things first, we get the path to the temp file created by dosetshell
try:
logger.debug("Executing: '%s'", ' '.join(command))
p = subprocess.Popen(command, stdout = subprocess.PIPE)
except OSError as e:
# occurs when the file is not executable or not found
raise OSError("Error executing '%s': %s (%d)" % (' '.join(command), e.strerror, e.errno))
try:
source = str_(p.communicate()[0]).strip()
except KeyboardInterrupt: # the user CTRL-C'ed
os.kill(p.pid, signal.SIGTERM)
sys.exit(signal.SIGTERM)
# We have now the name of the source file, source it and erase it
command2 = ['bash', '-c', 'source %s && env' % source]
try:
logger.debug("Executing: '%s'", ' '.join(command2))
p2 = subprocess.Popen(command2, stdout = subprocess.PIPE)
except OSError as e:
# occurs when the file is not executable or not found
raise OSError("Error executing '%s': %s (%d)" % (' '.join(command2), e.strerror, e.errno))
new_environ = dict(os.environ)
for line in p2.stdout:
line = str_(line)
(key, _, value) = line.partition("=")
new_environ[key.strip()] = value.strip()
try:
p2.communicate()
except KeyboardInterrupt: # the user CTRL-C'ed
os.kill(p2.pid, signal.SIGTERM)
sys.exit(signal.SIGTERM)
if os.path.exists(source): os.unlink(source)
logger.debug("Discovered environment for context '%s':", context)
for k in sorted(new_environ.keys()):
logger.debug(" %s = %s", k, new_environ[k])
return new_environ | [
"def",
"environ",
"(",
"context",
")",
":",
"if",
"'BASEDIRSETSHELL'",
"not",
"in",
"os",
".",
"environ",
":",
"# It seems that we are in a hostile environment",
"# try to source the Idiap-wide shell",
"idiap_source",
"=",
"\"/idiap/resource/software/initfiles/shrc\"",
"if",
... | Retrieves the environment for a particular SETSHELL context | [
"Retrieves",
"the",
"environment",
"for",
"a",
"particular",
"SETSHELL",
"context"
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/setshell.py#L15-L88 |
bioidiap/gridtk | gridtk/setshell.py | sexec | def sexec(context, command, error_on_nonzero=True):
"""Executes a command within a particular Idiap SETSHELL context"""
import six
if isinstance(context, six.string_types): E = environ(context)
else: E = context
try:
logger.debug("Executing: '%s'", ' '.join(command))
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, env=E)
(stdout, stderr) = p.communicate() #note: stderr will be 'None'
if p.returncode != 0:
if error_on_nonzero:
raise RuntimeError("Execution of '%s' exited with status != 0 (%d): %s" % (' '.join(command), p.returncode, str_(stdout)))
else:
logger.debug("Execution of '%s' exited with status != 0 (%d): %s" % \
(' '.join(command), p.returncode, str_(stdout)))
return stdout.strip()
except KeyboardInterrupt: # the user CTRC-C'ed
os.kill(p.pid, signal.SIGTERM)
sys.exit(signal.SIGTERM) | python | def sexec(context, command, error_on_nonzero=True):
"""Executes a command within a particular Idiap SETSHELL context"""
import six
if isinstance(context, six.string_types): E = environ(context)
else: E = context
try:
logger.debug("Executing: '%s'", ' '.join(command))
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, env=E)
(stdout, stderr) = p.communicate() #note: stderr will be 'None'
if p.returncode != 0:
if error_on_nonzero:
raise RuntimeError("Execution of '%s' exited with status != 0 (%d): %s" % (' '.join(command), p.returncode, str_(stdout)))
else:
logger.debug("Execution of '%s' exited with status != 0 (%d): %s" % \
(' '.join(command), p.returncode, str_(stdout)))
return stdout.strip()
except KeyboardInterrupt: # the user CTRC-C'ed
os.kill(p.pid, signal.SIGTERM)
sys.exit(signal.SIGTERM) | [
"def",
"sexec",
"(",
"context",
",",
"command",
",",
"error_on_nonzero",
"=",
"True",
")",
":",
"import",
"six",
"if",
"isinstance",
"(",
"context",
",",
"six",
".",
"string_types",
")",
":",
"E",
"=",
"environ",
"(",
"context",
")",
"else",
":",
"E",
... | Executes a command within a particular Idiap SETSHELL context | [
"Executes",
"a",
"command",
"within",
"a",
"particular",
"Idiap",
"SETSHELL",
"context"
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/setshell.py#L90-L113 |
Datary/scrapbag | scrapbag/dates.py | get_dates_in_period | def get_dates_in_period(start=None, top=None, step=1, step_dict={}):
"""Return a list of dates from the `start` to `top`."""
delta = relativedelta(**step_dict) if step_dict else timedelta(days=step)
start = start or datetime.today()
top = top or start + delta
dates = []
current = start
while current <= top:
dates.append(current)
current += delta
return dates | python | def get_dates_in_period(start=None, top=None, step=1, step_dict={}):
"""Return a list of dates from the `start` to `top`."""
delta = relativedelta(**step_dict) if step_dict else timedelta(days=step)
start = start or datetime.today()
top = top or start + delta
dates = []
current = start
while current <= top:
dates.append(current)
current += delta
return dates | [
"def",
"get_dates_in_period",
"(",
"start",
"=",
"None",
",",
"top",
"=",
"None",
",",
"step",
"=",
"1",
",",
"step_dict",
"=",
"{",
"}",
")",
":",
"delta",
"=",
"relativedelta",
"(",
"*",
"*",
"step_dict",
")",
"if",
"step_dict",
"else",
"timedelta",
... | Return a list of dates from the `start` to `top`. | [
"Return",
"a",
"list",
"of",
"dates",
"from",
"the",
"start",
"to",
"top",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/dates.py#L30-L42 |
Datary/scrapbag | scrapbag/dates.py | localize_date | def localize_date(date, city):
""" Localize date into city
Date: datetime
City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'..
"""
local = pytz.timezone(city)
local_dt = local.localize(date, is_dst=None)
return local_dt | python | def localize_date(date, city):
""" Localize date into city
Date: datetime
City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'..
"""
local = pytz.timezone(city)
local_dt = local.localize(date, is_dst=None)
return local_dt | [
"def",
"localize_date",
"(",
"date",
",",
"city",
")",
":",
"local",
"=",
"pytz",
".",
"timezone",
"(",
"city",
")",
"local_dt",
"=",
"local",
".",
"localize",
"(",
"date",
",",
"is_dst",
"=",
"None",
")",
"return",
"local_dt"
] | Localize date into city
Date: datetime
City: timezone city definitio. Example: 'Asia/Qatar', 'America/New York'.. | [
"Localize",
"date",
"into",
"city"
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/dates.py#L51-L59 |
Datary/scrapbag | scrapbag/dates.py | get_month_from_date_str | def get_month_from_date_str(date_str, lang=DEFAULT_DATE_LANG):
"""Find the month name for the given locale, in the given string.
Returns a tuple ``(number_of_month, abbr_name)``.
"""
date_str = date_str.lower()
with calendar.different_locale(LOCALES[lang]):
month_abbrs = list(calendar.month_abbr)
for seq, abbr in enumerate(month_abbrs):
if abbr and abbr.lower() in date_str:
return seq, abbr
return () | python | def get_month_from_date_str(date_str, lang=DEFAULT_DATE_LANG):
"""Find the month name for the given locale, in the given string.
Returns a tuple ``(number_of_month, abbr_name)``.
"""
date_str = date_str.lower()
with calendar.different_locale(LOCALES[lang]):
month_abbrs = list(calendar.month_abbr)
for seq, abbr in enumerate(month_abbrs):
if abbr and abbr.lower() in date_str:
return seq, abbr
return () | [
"def",
"get_month_from_date_str",
"(",
"date_str",
",",
"lang",
"=",
"DEFAULT_DATE_LANG",
")",
":",
"date_str",
"=",
"date_str",
".",
"lower",
"(",
")",
"with",
"calendar",
".",
"different_locale",
"(",
"LOCALES",
"[",
"lang",
"]",
")",
":",
"month_abbrs",
"... | Find the month name for the given locale, in the given string.
Returns a tuple ``(number_of_month, abbr_name)``. | [
"Find",
"the",
"month",
"name",
"for",
"the",
"given",
"locale",
"in",
"the",
"given",
"string",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/dates.py#L69-L80 |
Datary/scrapbag | scrapbag/dates.py | replace_month_abbr_with_num | def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):
"""Replace month strings occurrences with month number."""
num, abbr = get_month_from_date_str(date_str, lang)
return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE) | python | def replace_month_abbr_with_num(date_str, lang=DEFAULT_DATE_LANG):
"""Replace month strings occurrences with month number."""
num, abbr = get_month_from_date_str(date_str, lang)
return re.sub(abbr, str(num), date_str, flags=re.IGNORECASE) | [
"def",
"replace_month_abbr_with_num",
"(",
"date_str",
",",
"lang",
"=",
"DEFAULT_DATE_LANG",
")",
":",
"num",
",",
"abbr",
"=",
"get_month_from_date_str",
"(",
"date_str",
",",
"lang",
")",
"return",
"re",
".",
"sub",
"(",
"abbr",
",",
"str",
"(",
"num",
... | Replace month strings occurrences with month number. | [
"Replace",
"month",
"strings",
"occurrences",
"with",
"month",
"number",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/dates.py#L83-L86 |
Datary/scrapbag | scrapbag/dates.py | translate_month_abbr | def translate_month_abbr(
date_str,
source_lang=DEFAULT_DATE_LANG,
target_lang=DEFAULT_DATE_LANG):
"""Translate the month abbreviation from one locale to another."""
month_num, month_abbr = get_month_from_date_str(date_str, source_lang)
with calendar.different_locale(LOCALES[target_lang]):
translated_abbr = calendar.month_abbr[month_num]
return re.sub(
month_abbr, translated_abbr, date_str, flags=re.IGNORECASE) | python | def translate_month_abbr(
date_str,
source_lang=DEFAULT_DATE_LANG,
target_lang=DEFAULT_DATE_LANG):
"""Translate the month abbreviation from one locale to another."""
month_num, month_abbr = get_month_from_date_str(date_str, source_lang)
with calendar.different_locale(LOCALES[target_lang]):
translated_abbr = calendar.month_abbr[month_num]
return re.sub(
month_abbr, translated_abbr, date_str, flags=re.IGNORECASE) | [
"def",
"translate_month_abbr",
"(",
"date_str",
",",
"source_lang",
"=",
"DEFAULT_DATE_LANG",
",",
"target_lang",
"=",
"DEFAULT_DATE_LANG",
")",
":",
"month_num",
",",
"month_abbr",
"=",
"get_month_from_date_str",
"(",
"date_str",
",",
"source_lang",
")",
"with",
"c... | Translate the month abbreviation from one locale to another. | [
"Translate",
"the",
"month",
"abbreviation",
"from",
"one",
"locale",
"to",
"another",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/dates.py#L89-L98 |
Datary/scrapbag | scrapbag/dates.py | merge_datetime | def merge_datetime(date, time='', date_format='%d/%m/%Y', time_format='%H:%M'):
"""Create ``datetime`` object from date and time strings."""
day = datetime.strptime(date, date_format)
if time:
time = datetime.strptime(time, time_format)
time = datetime.time(time)
day = datetime.date(day)
day = datetime.combine(day, time)
return day | python | def merge_datetime(date, time='', date_format='%d/%m/%Y', time_format='%H:%M'):
"""Create ``datetime`` object from date and time strings."""
day = datetime.strptime(date, date_format)
if time:
time = datetime.strptime(time, time_format)
time = datetime.time(time)
day = datetime.date(day)
day = datetime.combine(day, time)
return day | [
"def",
"merge_datetime",
"(",
"date",
",",
"time",
"=",
"''",
",",
"date_format",
"=",
"'%d/%m/%Y'",
",",
"time_format",
"=",
"'%H:%M'",
")",
":",
"day",
"=",
"datetime",
".",
"strptime",
"(",
"date",
",",
"date_format",
")",
"if",
"time",
":",
"time",
... | Create ``datetime`` object from date and time strings. | [
"Create",
"datetime",
"object",
"from",
"date",
"and",
"time",
"strings",
"."
] | train | https://github.com/Datary/scrapbag/blob/3a4f9824ab6fe21121214ba9963690618da2c9de/scrapbag/dates.py#L101-L109 |
robehickman/simple-http-file-sync | shttpfs/common.py | display_list | def display_list(prefix, l, color):
""" Prints a file list to terminal, allows colouring output. """
for itm in l: print colored(prefix + itm['path'], color) | python | def display_list(prefix, l, color):
""" Prints a file list to terminal, allows colouring output. """
for itm in l: print colored(prefix + itm['path'], color) | [
"def",
"display_list",
"(",
"prefix",
",",
"l",
",",
"color",
")",
":",
"for",
"itm",
"in",
"l",
":",
"print",
"colored",
"(",
"prefix",
"+",
"itm",
"[",
"'path'",
"]",
",",
"color",
")"
] | Prints a file list to terminal, allows colouring output. | [
"Prints",
"a",
"file",
"list",
"to",
"terminal",
"allows",
"colouring",
"output",
"."
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L17-L19 |
robehickman/simple-http-file-sync | shttpfs/common.py | pfx_path | def pfx_path(path):
""" Prefix a path with the OS path separator if it is not already """
if path[0] != os.path.sep: return os.path.sep + path
else: return path | python | def pfx_path(path):
""" Prefix a path with the OS path separator if it is not already """
if path[0] != os.path.sep: return os.path.sep + path
else: return path | [
"def",
"pfx_path",
"(",
"path",
")",
":",
"if",
"path",
"[",
"0",
"]",
"!=",
"os",
".",
"path",
".",
"sep",
":",
"return",
"os",
".",
"path",
".",
"sep",
"+",
"path",
"else",
":",
"return",
"path"
] | Prefix a path with the OS path separator if it is not already | [
"Prefix",
"a",
"path",
"with",
"the",
"OS",
"path",
"separator",
"if",
"it",
"is",
"not",
"already"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L26-L29 |
robehickman/simple-http-file-sync | shttpfs/common.py | file_put_contents | def file_put_contents(path, data):
""" Put passed contents into file located at 'path' """
with open(path, 'w') as f:
f.write(data); f.flush() | python | def file_put_contents(path, data):
""" Put passed contents into file located at 'path' """
with open(path, 'w') as f:
f.write(data); f.flush() | [
"def",
"file_put_contents",
"(",
"path",
",",
"data",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"data",
")",
"f",
".",
"flush",
"(",
")"
] | Put passed contents into file located at 'path' | [
"Put",
"passed",
"contents",
"into",
"file",
"located",
"at",
"path"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L39-L42 |
robehickman/simple-http-file-sync | shttpfs/common.py | file_or_default | def file_or_default(path, default, function = None):
""" Return a default value if a file does not exist """
try:
result = file_get_contents(path)
if function != None: return function(result)
return result
except IOError as e:
if e.errno == errno.ENOENT: return default
raise | python | def file_or_default(path, default, function = None):
""" Return a default value if a file does not exist """
try:
result = file_get_contents(path)
if function != None: return function(result)
return result
except IOError as e:
if e.errno == errno.ENOENT: return default
raise | [
"def",
"file_or_default",
"(",
"path",
",",
"default",
",",
"function",
"=",
"None",
")",
":",
"try",
":",
"result",
"=",
"file_get_contents",
"(",
"path",
")",
"if",
"function",
"!=",
"None",
":",
"return",
"function",
"(",
"result",
")",
"return",
"res... | Return a default value if a file does not exist | [
"Return",
"a",
"default",
"value",
"if",
"a",
"file",
"does",
"not",
"exist"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L45-L53 |
robehickman/simple-http-file-sync | shttpfs/common.py | make_dirs_if_dont_exist | def make_dirs_if_dont_exist(path):
""" Create directories in path if they do not exist """
if path[-1] not in ['/']: path += '/'
path = os.path.dirname(path)
if path != '':
try: os.makedirs(path)
except OSError: pass | python | def make_dirs_if_dont_exist(path):
""" Create directories in path if they do not exist """
if path[-1] not in ['/']: path += '/'
path = os.path.dirname(path)
if path != '':
try: os.makedirs(path)
except OSError: pass | [
"def",
"make_dirs_if_dont_exist",
"(",
"path",
")",
":",
"if",
"path",
"[",
"-",
"1",
"]",
"not",
"in",
"[",
"'/'",
"]",
":",
"path",
"+=",
"'/'",
"path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"path",
"!=",
"''",
":",
... | Create directories in path if they do not exist | [
"Create",
"directories",
"in",
"path",
"if",
"they",
"do",
"not",
"exist"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L56-L62 |
robehickman/simple-http-file-sync | shttpfs/common.py | cpjoin | def cpjoin(*args):
""" custom path join """
rooted = True if args[0].startswith('/') else False
def deslash(a): return a[1:] if a.startswith('/') else a
newargs = [deslash(arg) for arg in args]
path = os.path.join(*newargs)
if rooted: path = os.path.sep + path
return path | python | def cpjoin(*args):
""" custom path join """
rooted = True if args[0].startswith('/') else False
def deslash(a): return a[1:] if a.startswith('/') else a
newargs = [deslash(arg) for arg in args]
path = os.path.join(*newargs)
if rooted: path = os.path.sep + path
return path | [
"def",
"cpjoin",
"(",
"*",
"args",
")",
":",
"rooted",
"=",
"True",
"if",
"args",
"[",
"0",
"]",
".",
"startswith",
"(",
"'/'",
")",
"else",
"False",
"def",
"deslash",
"(",
"a",
")",
":",
"return",
"a",
"[",
"1",
":",
"]",
"if",
"a",
".",
"st... | custom path join | [
"custom",
"path",
"join"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L65-L72 |
robehickman/simple-http-file-sync | shttpfs/common.py | get_single_file_info | def get_single_file_info(f_path, int_path):
""" Gets the creates and last change times for a single file,
f_path is the path to the file on disk, int_path is an internal
path relative to a root directory. """
return { 'path' : force_unicode(int_path),
'created' : os.path.getctime(f_path),
'last_mod' : os.path.getmtime(f_path)} | python | def get_single_file_info(f_path, int_path):
""" Gets the creates and last change times for a single file,
f_path is the path to the file on disk, int_path is an internal
path relative to a root directory. """
return { 'path' : force_unicode(int_path),
'created' : os.path.getctime(f_path),
'last_mod' : os.path.getmtime(f_path)} | [
"def",
"get_single_file_info",
"(",
"f_path",
",",
"int_path",
")",
":",
"return",
"{",
"'path'",
":",
"force_unicode",
"(",
"int_path",
")",
",",
"'created'",
":",
"os",
".",
"path",
".",
"getctime",
"(",
"f_path",
")",
",",
"'last_mod'",
":",
"os",
"."... | Gets the creates and last change times for a single file,
f_path is the path to the file on disk, int_path is an internal
path relative to a root directory. | [
"Gets",
"the",
"creates",
"and",
"last",
"change",
"times",
"for",
"a",
"single",
"file",
"f_path",
"is",
"the",
"path",
"to",
"the",
"file",
"on",
"disk",
"int_path",
"is",
"an",
"internal",
"path",
"relative",
"to",
"a",
"root",
"directory",
"."
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L75-L81 |
robehickman/simple-http-file-sync | shttpfs/common.py | hash_file | def hash_file(file_path, block_size = 65536):
""" Hashes a file with sha256 """
sha = hashlib.sha256()
with open(file_path, 'rb') as h_file:
file_buffer = h_file.read(block_size)
while len(file_buffer) > 0:
sha.update(file_buffer)
file_buffer = h_file.read(block_size)
return sha.hexdigest() | python | def hash_file(file_path, block_size = 65536):
""" Hashes a file with sha256 """
sha = hashlib.sha256()
with open(file_path, 'rb') as h_file:
file_buffer = h_file.read(block_size)
while len(file_buffer) > 0:
sha.update(file_buffer)
file_buffer = h_file.read(block_size)
return sha.hexdigest() | [
"def",
"hash_file",
"(",
"file_path",
",",
"block_size",
"=",
"65536",
")",
":",
"sha",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"h_file",
":",
"file_buffer",
"=",
"h_file",
".",
"read",
"(",
... | Hashes a file with sha256 | [
"Hashes",
"a",
"file",
"with",
"sha256"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L84-L92 |
robehickman/simple-http-file-sync | shttpfs/common.py | get_file_list | def get_file_list(path):
""" Recursively lists all files in a file system below 'path'. """
f_list = []
def recur_dir(path, newpath = os.path.sep):
files = os.listdir(path)
for fle in files:
f_path = cpjoin(path, fle)
if os.path.isdir(f_path): recur_dir(f_path, cpjoin(newpath, fle))
elif os.path.isfile(f_path): f_list.append(get_single_file_info(f_path, cpjoin(newpath, fle)))
recur_dir(path)
return f_list | python | def get_file_list(path):
""" Recursively lists all files in a file system below 'path'. """
f_list = []
def recur_dir(path, newpath = os.path.sep):
files = os.listdir(path)
for fle in files:
f_path = cpjoin(path, fle)
if os.path.isdir(f_path): recur_dir(f_path, cpjoin(newpath, fle))
elif os.path.isfile(f_path): f_list.append(get_single_file_info(f_path, cpjoin(newpath, fle)))
recur_dir(path)
return f_list | [
"def",
"get_file_list",
"(",
"path",
")",
":",
"f_list",
"=",
"[",
"]",
"def",
"recur_dir",
"(",
"path",
",",
"newpath",
"=",
"os",
".",
"path",
".",
"sep",
")",
":",
"files",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"for",
"fle",
"in",
"file... | Recursively lists all files in a file system below 'path'. | [
"Recursively",
"lists",
"all",
"files",
"in",
"a",
"file",
"system",
"below",
"path",
"."
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L95-L106 |
robehickman/simple-http-file-sync | shttpfs/common.py | find_manifest_changes | def find_manifest_changes(new_file_state, old_file_state):
""" Find what has changed between two sets of files """
prev_state_dict = copy.deepcopy(old_file_state)
changed_files = {}
# Find files which are new on the server
for itm in new_file_state:
if itm['path'] in prev_state_dict:
d_itm = prev_state_dict.pop(itm['path'])
# If the file has been modified
if itm['last_mod'] != d_itm['last_mod']:
n_itm = itm.copy()
n_itm['status'] = 'changed'
changed_files[itm['path']] = n_itm
else:
pass # The file has not changed
else:
n_itm = itm.copy()
n_itm['status'] = 'new'
changed_files[itm['path']] = n_itm
# any files remaining in the old file state have been deleted locally
for itm in prev_state_dict.itervalues():
n_itm = itm.copy()
n_itm['status'] = 'deleted'
changed_files[itm['path']] = n_itm
return changed_files | python | def find_manifest_changes(new_file_state, old_file_state):
""" Find what has changed between two sets of files """
prev_state_dict = copy.deepcopy(old_file_state)
changed_files = {}
# Find files which are new on the server
for itm in new_file_state:
if itm['path'] in prev_state_dict:
d_itm = prev_state_dict.pop(itm['path'])
# If the file has been modified
if itm['last_mod'] != d_itm['last_mod']:
n_itm = itm.copy()
n_itm['status'] = 'changed'
changed_files[itm['path']] = n_itm
else:
pass # The file has not changed
else:
n_itm = itm.copy()
n_itm['status'] = 'new'
changed_files[itm['path']] = n_itm
# any files remaining in the old file state have been deleted locally
for itm in prev_state_dict.itervalues():
n_itm = itm.copy()
n_itm['status'] = 'deleted'
changed_files[itm['path']] = n_itm
return changed_files | [
"def",
"find_manifest_changes",
"(",
"new_file_state",
",",
"old_file_state",
")",
":",
"prev_state_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"old_file_state",
")",
"changed_files",
"=",
"{",
"}",
"# Find files which are new on the server",
"for",
"itm",
"in",
"new_fi... | Find what has changed between two sets of files | [
"Find",
"what",
"has",
"changed",
"between",
"two",
"sets",
"of",
"files"
] | train | https://github.com/robehickman/simple-http-file-sync/blob/fa29b3ee58e9504e1d3ddfc0c14047284bf9921d/shttpfs/common.py#L109-L138 |
TAPPGuild/bitjws | bitjws/crypto.py | shasha | def shasha(msg):
"""SHA256(SHA256(msg)) -> HASH object"""
res = hashlib.sha256(hashlib.sha256(msg).digest())
return res | python | def shasha(msg):
"""SHA256(SHA256(msg)) -> HASH object"""
res = hashlib.sha256(hashlib.sha256(msg).digest())
return res | [
"def",
"shasha",
"(",
"msg",
")",
":",
"res",
"=",
"hashlib",
".",
"sha256",
"(",
"hashlib",
".",
"sha256",
"(",
"msg",
")",
".",
"digest",
"(",
")",
")",
"return",
"res"
] | SHA256(SHA256(msg)) -> HASH object | [
"SHA256",
"(",
"SHA256",
"(",
"msg",
"))",
"-",
">",
"HASH",
"object"
] | train | https://github.com/TAPPGuild/bitjws/blob/bcf943e0c60985da11fb7895a416525e63728c35/bitjws/crypto.py#L36-L39 |
TAPPGuild/bitjws | bitjws/crypto.py | ripesha | def ripesha(msg):
"""RIPEMD160(SHA256(msg)) -> HASH object"""
ripe = hashlib.new('ripemd160')
ripe.update(hashlib.sha256(msg).digest())
return ripe | python | def ripesha(msg):
"""RIPEMD160(SHA256(msg)) -> HASH object"""
ripe = hashlib.new('ripemd160')
ripe.update(hashlib.sha256(msg).digest())
return ripe | [
"def",
"ripesha",
"(",
"msg",
")",
":",
"ripe",
"=",
"hashlib",
".",
"new",
"(",
"'ripemd160'",
")",
"ripe",
".",
"update",
"(",
"hashlib",
".",
"sha256",
"(",
"msg",
")",
".",
"digest",
"(",
")",
")",
"return",
"ripe"
] | RIPEMD160(SHA256(msg)) -> HASH object | [
"RIPEMD160",
"(",
"SHA256",
"(",
"msg",
"))",
"-",
">",
"HASH",
"object"
] | train | https://github.com/TAPPGuild/bitjws/blob/bcf943e0c60985da11fb7895a416525e63728c35/bitjws/crypto.py#L42-L46 |
TAPPGuild/bitjws | bitjws/crypto.py | privkey_to_wif | def privkey_to_wif(rawkey, compressed=True, net=BC):
"""Convert privkey bytes to Wallet Import Format (WIF)."""
# See https://en.bitcoin.it/wiki/Wallet_import_format.
k = net.wifprefix + rawkey
if compressed:
k += b'\x01'
chksum = shasha(k).digest()[:4]
key = k + chksum
b58key = b58encode(key)
return b58key | python | def privkey_to_wif(rawkey, compressed=True, net=BC):
"""Convert privkey bytes to Wallet Import Format (WIF)."""
# See https://en.bitcoin.it/wiki/Wallet_import_format.
k = net.wifprefix + rawkey
if compressed:
k += b'\x01'
chksum = shasha(k).digest()[:4]
key = k + chksum
b58key = b58encode(key)
return b58key | [
"def",
"privkey_to_wif",
"(",
"rawkey",
",",
"compressed",
"=",
"True",
",",
"net",
"=",
"BC",
")",
":",
"# See https://en.bitcoin.it/wiki/Wallet_import_format.",
"k",
"=",
"net",
".",
"wifprefix",
"+",
"rawkey",
"if",
"compressed",
":",
"k",
"+=",
"b'\\x01'",
... | Convert privkey bytes to Wallet Import Format (WIF). | [
"Convert",
"privkey",
"bytes",
"to",
"Wallet",
"Import",
"Format",
"(",
"WIF",
")",
"."
] | train | https://github.com/TAPPGuild/bitjws/blob/bcf943e0c60985da11fb7895a416525e63728c35/bitjws/crypto.py#L53-L64 |
TAPPGuild/bitjws | bitjws/crypto.py | wif_to_privkey | def wif_to_privkey(wif, compressed=True, net=BC):
"""Convert Wallet Import Format (WIF) to privkey bytes."""
key = b58decode(wif)
version, raw, check = key[0:1], key[1:-4], key[-4:]
assert version == net.wifprefix, "unexpected version byte"
check_compare = shasha(version + raw).digest()[:4]
assert check_compare == check
if compressed:
raw = raw[:-1]
return raw | python | def wif_to_privkey(wif, compressed=True, net=BC):
"""Convert Wallet Import Format (WIF) to privkey bytes."""
key = b58decode(wif)
version, raw, check = key[0:1], key[1:-4], key[-4:]
assert version == net.wifprefix, "unexpected version byte"
check_compare = shasha(version + raw).digest()[:4]
assert check_compare == check
if compressed:
raw = raw[:-1]
return raw | [
"def",
"wif_to_privkey",
"(",
"wif",
",",
"compressed",
"=",
"True",
",",
"net",
"=",
"BC",
")",
":",
"key",
"=",
"b58decode",
"(",
"wif",
")",
"version",
",",
"raw",
",",
"check",
"=",
"key",
"[",
"0",
":",
"1",
"]",
",",
"key",
"[",
"1",
":",... | Convert Wallet Import Format (WIF) to privkey bytes. | [
"Convert",
"Wallet",
"Import",
"Format",
"(",
"WIF",
")",
"to",
"privkey",
"bytes",
"."
] | train | https://github.com/TAPPGuild/bitjws/blob/bcf943e0c60985da11fb7895a416525e63728c35/bitjws/crypto.py#L67-L80 |
azraq27/neural | neural/utils.py | is_archive | def is_archive(filename):
'''returns boolean of whether this filename looks like an archive'''
for archive in archive_formats:
if filename.endswith(archive_formats[archive]['suffix']):
return True
return False | python | def is_archive(filename):
'''returns boolean of whether this filename looks like an archive'''
for archive in archive_formats:
if filename.endswith(archive_formats[archive]['suffix']):
return True
return False | [
"def",
"is_archive",
"(",
"filename",
")",
":",
"for",
"archive",
"in",
"archive_formats",
":",
"if",
"filename",
".",
"endswith",
"(",
"archive_formats",
"[",
"archive",
"]",
"[",
"'suffix'",
"]",
")",
":",
"return",
"True",
"return",
"False"
] | returns boolean of whether this filename looks like an archive | [
"returns",
"boolean",
"of",
"whether",
"this",
"filename",
"looks",
"like",
"an",
"archive"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L22-L27 |
azraq27/neural | neural/utils.py | archive_basename | def archive_basename(filename):
'''returns the basename (name without extension) of a recognized archive file'''
for archive in archive_formats:
if filename.endswith(archive_formats[archive]['suffix']):
return filename.rstrip('.' + archive_formats[archive]['suffix'])
return False | python | def archive_basename(filename):
'''returns the basename (name without extension) of a recognized archive file'''
for archive in archive_formats:
if filename.endswith(archive_formats[archive]['suffix']):
return filename.rstrip('.' + archive_formats[archive]['suffix'])
return False | [
"def",
"archive_basename",
"(",
"filename",
")",
":",
"for",
"archive",
"in",
"archive_formats",
":",
"if",
"filename",
".",
"endswith",
"(",
"archive_formats",
"[",
"archive",
"]",
"[",
"'suffix'",
"]",
")",
":",
"return",
"filename",
".",
"rstrip",
"(",
... | returns the basename (name without extension) of a recognized archive file | [
"returns",
"the",
"basename",
"(",
"name",
"without",
"extension",
")",
"of",
"a",
"recognized",
"archive",
"file"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L29-L34 |
azraq27/neural | neural/utils.py | unarchive | def unarchive(filename,output_dir='.'):
'''unpacks the given archive into ``output_dir``'''
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for archive in archive_formats:
if filename.endswith(archive_formats[archive]['suffix']):
return subprocess.call(archive_formats[archive]['command'](output_dir,filename))==0
return False | python | def unarchive(filename,output_dir='.'):
'''unpacks the given archive into ``output_dir``'''
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for archive in archive_formats:
if filename.endswith(archive_formats[archive]['suffix']):
return subprocess.call(archive_formats[archive]['command'](output_dir,filename))==0
return False | [
"def",
"unarchive",
"(",
"filename",
",",
"output_dir",
"=",
"'.'",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"output_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"output_dir",
")",
"for",
"archive",
"in",
"archive_formats",
":",
"if... | unpacks the given archive into ``output_dir`` | [
"unpacks",
"the",
"given",
"archive",
"into",
"output_dir"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L36-L43 |
azraq27/neural | neural/utils.py | flatten | def flatten(nested_list):
'''converts a list-of-lists to a single flat list'''
return_list = []
for i in nested_list:
if isinstance(i,list):
return_list += flatten(i)
else:
return_list.append(i)
return return_list | python | def flatten(nested_list):
'''converts a list-of-lists to a single flat list'''
return_list = []
for i in nested_list:
if isinstance(i,list):
return_list += flatten(i)
else:
return_list.append(i)
return return_list | [
"def",
"flatten",
"(",
"nested_list",
")",
":",
"return_list",
"=",
"[",
"]",
"for",
"i",
"in",
"nested_list",
":",
"if",
"isinstance",
"(",
"i",
",",
"list",
")",
":",
"return_list",
"+=",
"flatten",
"(",
"i",
")",
"else",
":",
"return_list",
".",
"... | converts a list-of-lists to a single flat list | [
"converts",
"a",
"list",
"-",
"of",
"-",
"lists",
"to",
"a",
"single",
"flat",
"list"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L45-L53 |
azraq27/neural | neural/utils.py | run | def run(command,products=None,working_directory='.',force_local=False,stderr=True,quiet=False):
'''wrapper to run external programs
:command: list containing command and parameters
(formatted the same as subprocess; must contain only strings)
:products: string or list of files that are the products of this command
if all products exist, the command will not be run, and False returned
:working_directory: will chdir to this directory
:force_local: when used with `neural.scheduler`, setting to ``True`` will disable
all job distribution functions
:stderr: forward ``stderr`` into the output
``True`` will combine ``stderr`` and ``stdout``
``False`` will return ``stdout`` and let ``stderr`` print to the console
``None`` will return ``stdout`` and suppress ``stderr``
:quiet: ``False`` (default) will print friendly messages
``True`` will suppress everything but errors
``None`` will suppress all output
Returns result in form of :class:`RunResult`
'''
with run_in(working_directory):
if products:
if isinstance(products,basestring):
products = [products]
if all([os.path.exists(x) for x in products]):
return False
command = flatten(command)
command = [str(x) for x in command]
quiet_option = False if quiet==False else True
with nl.notify('Running %s...' % command[0],level=nl.level.debug,quiet=quiet_option):
out = None
returncode = 0
try:
if stderr:
# include STDERR in STDOUT output
out = subprocess.check_output(command,stderr=subprocess.STDOUT)
elif stderr==None:
# dump STDERR into nothing
out = subprocess.check_output(command,stderr=subprocess.PIPE)
else:
# let STDERR show through to the console
out = subprocess.check_output(command)
except subprocess.CalledProcessError, e:
if quiet!=None:
nl.notify('''ERROR: %s returned a non-zero status
----COMMAND------------
%s
-----------------------
----OUTPUT-------------
%s
-----------------------
Return code: %d
''' % (command[0],' '.join(command),e.output,e.returncode),level=nl.level.error)
out = e.output
returncode = e.returncode
result = RunResult(out,returncode)
if products and returncode==0:
result.output_filename = products[0]
return result | python | def run(command,products=None,working_directory='.',force_local=False,stderr=True,quiet=False):
'''wrapper to run external programs
:command: list containing command and parameters
(formatted the same as subprocess; must contain only strings)
:products: string or list of files that are the products of this command
if all products exist, the command will not be run, and False returned
:working_directory: will chdir to this directory
:force_local: when used with `neural.scheduler`, setting to ``True`` will disable
all job distribution functions
:stderr: forward ``stderr`` into the output
``True`` will combine ``stderr`` and ``stdout``
``False`` will return ``stdout`` and let ``stderr`` print to the console
``None`` will return ``stdout`` and suppress ``stderr``
:quiet: ``False`` (default) will print friendly messages
``True`` will suppress everything but errors
``None`` will suppress all output
Returns result in form of :class:`RunResult`
'''
with run_in(working_directory):
if products:
if isinstance(products,basestring):
products = [products]
if all([os.path.exists(x) for x in products]):
return False
command = flatten(command)
command = [str(x) for x in command]
quiet_option = False if quiet==False else True
with nl.notify('Running %s...' % command[0],level=nl.level.debug,quiet=quiet_option):
out = None
returncode = 0
try:
if stderr:
# include STDERR in STDOUT output
out = subprocess.check_output(command,stderr=subprocess.STDOUT)
elif stderr==None:
# dump STDERR into nothing
out = subprocess.check_output(command,stderr=subprocess.PIPE)
else:
# let STDERR show through to the console
out = subprocess.check_output(command)
except subprocess.CalledProcessError, e:
if quiet!=None:
nl.notify('''ERROR: %s returned a non-zero status
----COMMAND------------
%s
-----------------------
----OUTPUT-------------
%s
-----------------------
Return code: %d
''' % (command[0],' '.join(command),e.output,e.returncode),level=nl.level.error)
out = e.output
returncode = e.returncode
result = RunResult(out,returncode)
if products and returncode==0:
result.output_filename = products[0]
return result | [
"def",
"run",
"(",
"command",
",",
"products",
"=",
"None",
",",
"working_directory",
"=",
"'.'",
",",
"force_local",
"=",
"False",
",",
"stderr",
"=",
"True",
",",
"quiet",
"=",
"False",
")",
":",
"with",
"run_in",
"(",
"working_directory",
")",
":",
... | wrapper to run external programs
:command: list containing command and parameters
(formatted the same as subprocess; must contain only strings)
:products: string or list of files that are the products of this command
if all products exist, the command will not be run, and False returned
:working_directory: will chdir to this directory
:force_local: when used with `neural.scheduler`, setting to ``True`` will disable
all job distribution functions
:stderr: forward ``stderr`` into the output
``True`` will combine ``stderr`` and ``stdout``
``False`` will return ``stdout`` and let ``stderr`` print to the console
``None`` will return ``stdout`` and suppress ``stderr``
:quiet: ``False`` (default) will print friendly messages
``True`` will suppress everything but errors
``None`` will suppress all output
Returns result in form of :class:`RunResult` | [
"wrapper",
"to",
"run",
"external",
"programs"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L102-L164 |
azraq27/neural | neural/utils.py | log | def log(fname,msg):
''' generic logging function '''
with open(fname,'a') as f:
f.write(datetime.datetime.now().strftime('%m-%d-%Y %H:%M:\n') + msg + '\n') | python | def log(fname,msg):
''' generic logging function '''
with open(fname,'a') as f:
f.write(datetime.datetime.now().strftime('%m-%d-%Y %H:%M:\n') + msg + '\n') | [
"def",
"log",
"(",
"fname",
",",
"msg",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'a'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%m-%d-%Y %H:%M:\\n'",
")",
"+",
"m... | generic logging function | [
"generic",
"logging",
"function"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L166-L169 |
azraq27/neural | neural/utils.py | hash | def hash(filename):
'''returns string of MD5 hash of given filename'''
buffer_size = 10*1024*1024
m = hashlib.md5()
with open(filename) as f:
buff = f.read(buffer_size)
while len(buff)>0:
m.update(buff)
buff = f.read(buffer_size)
dig = m.digest()
return ''.join(['%x' % ord(x) for x in dig]) | python | def hash(filename):
'''returns string of MD5 hash of given filename'''
buffer_size = 10*1024*1024
m = hashlib.md5()
with open(filename) as f:
buff = f.read(buffer_size)
while len(buff)>0:
m.update(buff)
buff = f.read(buffer_size)
dig = m.digest()
return ''.join(['%x' % ord(x) for x in dig]) | [
"def",
"hash",
"(",
"filename",
")",
":",
"buffer_size",
"=",
"10",
"*",
"1024",
"*",
"1024",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"buff",
"=",
"f",
".",
"read",
"(",
"buffer_size",
")",... | returns string of MD5 hash of given filename | [
"returns",
"string",
"of",
"MD5",
"hash",
"of",
"given",
"filename"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L171-L181 |
azraq27/neural | neural/utils.py | hash_str | def hash_str(string):
'''returns string of MD5 hash of given string'''
m = hashlib.md5()
m.update(string)
dig = m.digest()
return ''.join(['%x' % ord(x) for x in dig]) | python | def hash_str(string):
'''returns string of MD5 hash of given string'''
m = hashlib.md5()
m.update(string)
dig = m.digest()
return ''.join(['%x' % ord(x) for x in dig]) | [
"def",
"hash_str",
"(",
"string",
")",
":",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"m",
".",
"update",
"(",
"string",
")",
"dig",
"=",
"m",
".",
"digest",
"(",
")",
"return",
"''",
".",
"join",
"(",
"[",
"'%x'",
"%",
"ord",
"(",
"x",
")",... | returns string of MD5 hash of given string | [
"returns",
"string",
"of",
"MD5",
"hash",
"of",
"given",
"string"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L183-L188 |
azraq27/neural | neural/utils.py | find | def find(file):
'''tries to find ``file`` using OS-specific searches and some guessing'''
# Try MacOS Spotlight:
mdfind = which('mdfind')
if mdfind:
out = run([mdfind,'-name',file],stderr=None,quiet=None)
if out.return_code==0 and out.output:
for fname in out.output.split('\n'):
if os.path.basename(fname)==file:
return fname
# Try UNIX locate:
locate = which('locate')
if locate:
out = run([locate,file],stderr=None,quiet=None)
if out.return_code==0 and out.output:
for fname in out.output.split('\n'):
if os.path.basename(fname)==file:
return fname
# Try to look through the PATH, and some guesses:
path_search = os.environ["PATH"].split(os.pathsep)
path_search += ['/usr/local/afni','/usr/local/afni/atlases','/usr/local/share','/usr/local/share/afni','/usr/local/share/afni/atlases']
afni_path = which('afni')
if afni_path:
path_search.append(os.path.dirname(afni_path))
if nl.wrappers.fsl.bet2:
path_search.append(os.path.dirname(nl.wrappers.fsl.bet2))
for path in path_search:
path = path.strip('"')
try:
if file in os.listdir(path):
return os.path.join(path,file)
except:
pass | python | def find(file):
'''tries to find ``file`` using OS-specific searches and some guessing'''
# Try MacOS Spotlight:
mdfind = which('mdfind')
if mdfind:
out = run([mdfind,'-name',file],stderr=None,quiet=None)
if out.return_code==0 and out.output:
for fname in out.output.split('\n'):
if os.path.basename(fname)==file:
return fname
# Try UNIX locate:
locate = which('locate')
if locate:
out = run([locate,file],stderr=None,quiet=None)
if out.return_code==0 and out.output:
for fname in out.output.split('\n'):
if os.path.basename(fname)==file:
return fname
# Try to look through the PATH, and some guesses:
path_search = os.environ["PATH"].split(os.pathsep)
path_search += ['/usr/local/afni','/usr/local/afni/atlases','/usr/local/share','/usr/local/share/afni','/usr/local/share/afni/atlases']
afni_path = which('afni')
if afni_path:
path_search.append(os.path.dirname(afni_path))
if nl.wrappers.fsl.bet2:
path_search.append(os.path.dirname(nl.wrappers.fsl.bet2))
for path in path_search:
path = path.strip('"')
try:
if file in os.listdir(path):
return os.path.join(path,file)
except:
pass | [
"def",
"find",
"(",
"file",
")",
":",
"# Try MacOS Spotlight:",
"mdfind",
"=",
"which",
"(",
"'mdfind'",
")",
"if",
"mdfind",
":",
"out",
"=",
"run",
"(",
"[",
"mdfind",
",",
"'-name'",
",",
"file",
"]",
",",
"stderr",
"=",
"None",
",",
"quiet",
"=",... | tries to find ``file`` using OS-specific searches and some guessing | [
"tries",
"to",
"find",
"file",
"using",
"OS",
"-",
"specific",
"searches",
"and",
"some",
"guessing"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L240-L274 |
azraq27/neural | neural/utils.py | universal_read | def universal_read(fname):
'''Will open and read a file with universal line endings, trying to decode whatever format it's in (e.g., utf8 or utf16)'''
with open(fname,'rU') as f:
data = f.read()
enc_guess = chardet.detect(data)
return data.decode(enc_guess['encoding']) | python | def universal_read(fname):
'''Will open and read a file with universal line endings, trying to decode whatever format it's in (e.g., utf8 or utf16)'''
with open(fname,'rU') as f:
data = f.read()
enc_guess = chardet.detect(data)
return data.decode(enc_guess['encoding']) | [
"def",
"universal_read",
"(",
"fname",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'rU'",
")",
"as",
"f",
":",
"data",
"=",
"f",
".",
"read",
"(",
")",
"enc_guess",
"=",
"chardet",
".",
"detect",
"(",
"data",
")",
"return",
"data",
".",
"decode",... | Will open and read a file with universal line endings, trying to decode whatever format it's in (e.g., utf8 or utf16) | [
"Will",
"open",
"and",
"read",
"a",
"file",
"with",
"universal",
"line",
"endings",
"trying",
"to",
"decode",
"whatever",
"format",
"it",
"s",
"in",
"(",
"e",
".",
"g",
".",
"utf8",
"or",
"utf16",
")"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L311-L316 |
azraq27/neural | neural/utils.py | strip_rows | def strip_rows(array,invalid=None):
'''takes a ``list`` of ``list``s and removes corresponding indices containing the
invalid value (default ``None``). '''
array = np.array(array)
none_indices = np.where(np.any(np.equal(array,invalid),axis=0))
return tuple(np.delete(array,none_indices,axis=1)) | python | def strip_rows(array,invalid=None):
'''takes a ``list`` of ``list``s and removes corresponding indices containing the
invalid value (default ``None``). '''
array = np.array(array)
none_indices = np.where(np.any(np.equal(array,invalid),axis=0))
return tuple(np.delete(array,none_indices,axis=1)) | [
"def",
"strip_rows",
"(",
"array",
",",
"invalid",
"=",
"None",
")",
":",
"array",
"=",
"np",
".",
"array",
"(",
"array",
")",
"none_indices",
"=",
"np",
".",
"where",
"(",
"np",
".",
"any",
"(",
"np",
".",
"equal",
"(",
"array",
",",
"invalid",
... | takes a ``list`` of ``list``s and removes corresponding indices containing the
invalid value (default ``None``). | [
"takes",
"a",
"list",
"of",
"list",
"s",
"and",
"removes",
"corresponding",
"indices",
"containing",
"the",
"invalid",
"value",
"(",
"default",
"None",
")",
"."
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L425-L430 |
azraq27/neural | neural/utils.py | numberize | def numberize(string):
'''Turns a string into a number (``int`` or ``float``) if it's only a number (ignoring spaces), otherwise returns the string.
For example, ``"5 "`` becomes ``5`` and ``"2 ton"`` remains ``"2 ton"``'''
if not isinstance(string,basestring):
return string
just_int = r'^\s*[-+]?\d+\s*$'
just_float = r'^\s*[-+]?\d+\.(\d+)?\s*$'
if re.match(just_int,string):
return int(string)
if re.match(just_float,string):
return float(string)
return string | python | def numberize(string):
'''Turns a string into a number (``int`` or ``float``) if it's only a number (ignoring spaces), otherwise returns the string.
For example, ``"5 "`` becomes ``5`` and ``"2 ton"`` remains ``"2 ton"``'''
if not isinstance(string,basestring):
return string
just_int = r'^\s*[-+]?\d+\s*$'
just_float = r'^\s*[-+]?\d+\.(\d+)?\s*$'
if re.match(just_int,string):
return int(string)
if re.match(just_float,string):
return float(string)
return string | [
"def",
"numberize",
"(",
"string",
")",
":",
"if",
"not",
"isinstance",
"(",
"string",
",",
"basestring",
")",
":",
"return",
"string",
"just_int",
"=",
"r'^\\s*[-+]?\\d+\\s*$'",
"just_float",
"=",
"r'^\\s*[-+]?\\d+\\.(\\d+)?\\s*$'",
"if",
"re",
".",
"match",
"(... | Turns a string into a number (``int`` or ``float``) if it's only a number (ignoring spaces), otherwise returns the string.
For example, ``"5 "`` becomes ``5`` and ``"2 ton"`` remains ``"2 ton"`` | [
"Turns",
"a",
"string",
"into",
"a",
"number",
"(",
"int",
"or",
"float",
")",
"if",
"it",
"s",
"only",
"a",
"number",
"(",
"ignoring",
"spaces",
")",
"otherwise",
"returns",
"the",
"string",
".",
"For",
"example",
"5",
"becomes",
"5",
"and",
"2",
"t... | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L432-L443 |
azraq27/neural | neural/utils.py | Beacon.check_packet | def check_packet(self):
'''is there a valid packet (from another thread) for this app/instance?'''
if not os.path.exists(self.packet_file()):
# No packet file, we're good
return True
else:
# There's already a file, but is it still running?
try:
with open(self.packet_file()) as f:
packet = json.loads(f.read())
if time.time() - packet['last_time'] > 3.0*packet['poll_time']:
# We haven't heard a ping in too long. It's probably dead
return True
else:
# Still getting pings.. probably still a live process
return False
except:
# Failed to read file... try again in a second
time.sleep(random.random()*2)
return self.check_packet() | python | def check_packet(self):
'''is there a valid packet (from another thread) for this app/instance?'''
if not os.path.exists(self.packet_file()):
# No packet file, we're good
return True
else:
# There's already a file, but is it still running?
try:
with open(self.packet_file()) as f:
packet = json.loads(f.read())
if time.time() - packet['last_time'] > 3.0*packet['poll_time']:
# We haven't heard a ping in too long. It's probably dead
return True
else:
# Still getting pings.. probably still a live process
return False
except:
# Failed to read file... try again in a second
time.sleep(random.random()*2)
return self.check_packet() | [
"def",
"check_packet",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"packet_file",
"(",
")",
")",
":",
"# No packet file, we're good",
"return",
"True",
"else",
":",
"# There's already a file, but is it still running?",
... | is there a valid packet (from another thread) for this app/instance? | [
"is",
"there",
"a",
"valid",
"packet",
"(",
"from",
"another",
"thread",
")",
"for",
"this",
"app",
"/",
"instance?"
] | train | https://github.com/azraq27/neural/blob/fe91bfeecbf73ad99708cf5dca66cb61fcd529f5/neural/utils.py#L392-L411 |
ajyoon/blur | blur/iching.py | get_hexagram | def get_hexagram(method='THREE COIN'):
"""
Return one or two hexagrams using any of a variety of divination methods.
The ``NAIVE`` method simply returns a uniformally random ``int`` between
``1`` and ``64``.
All other methods return a 2-tuple where the first value
represents the starting hexagram and the second represents the 'moving to'
hexagram.
To find the name and unicode glyph for a found hexagram, look it up in
the module-level `hexagrams` dict.
Args:
method (str): ``'THREE COIN'``, ``'YARROW'``, or ``'NAIVE'``,
the divination method model to use. Note that the three coin and
yarrow methods are not actually literally simulated,
but rather statistical models reflecting the methods are passed
to `blur.rand` functions to accurately approximate them.
Returns:
int: If ``method == 'NAIVE'``, the ``int`` key of the found hexagram.
Otherwise a `tuple` will be returned.
tuple: A 2-tuple of form ``(int, int)`` where the first value
is key of the starting hexagram and the second is that of the
'moving-to' hexagram.
Raises: ValueError if ``method`` is invalid
Examples:
The function being used alone: ::
>>> get_hexagram(method='THREE COIN') # doctest: +SKIP
# Might be...
(55, 2)
>>> get_hexagram(method='YARROW') # doctest: +SKIP
# Might be...
(41, 27)
>>> get_hexagram(method='NAIVE') # doctest: +SKIP
# Might be...
26
Usage in combination with hexagram lookup: ::
>>> grams = get_hexagram()
>>> grams # doctest: +SKIP
(47, 42)
# unpack hexagrams for convenient reference
>>> initial, moving_to = grams
>>> hexagrams[initial] # doctest: +SKIP
('䷮', '困', 'Confining')
>>> hexagrams[moving_to] # doctest: +SKIP
('䷩', '益', 'Augmenting')
>>> print('{} moving to {}'.format(
... hexagrams[initial][2],
... hexagrams[moving_to][2])
... ) # doctest: +SKIP
Confining moving to Augmenting
"""
if method == 'THREE COIN':
weights = [('MOVING YANG', 2),
('MOVING YIN', 2),
('STATIC YANG', 6),
('STATIC YIN', 6)]
elif method == 'YARROW':
weights = [('MOVING YANG', 8),
('MOVING YIN', 2),
('STATIC YANG', 11),
('STATIC YIN', 17)]
elif method == 'NAIVE':
return random.randint(1, 64)
else:
raise ValueError('`method` value of "{}" is invalid')
hexagram_1 = []
hexagram_2 = []
for i in range(6):
roll = weighted_choice(weights)
if roll == 'MOVING YANG':
hexagram_1.append(1)
hexagram_2.append(0)
elif roll == 'MOVING YIN':
hexagram_1.append(0)
hexagram_2.append(1)
elif roll == 'STATIC YANG':
hexagram_1.append(1)
hexagram_2.append(1)
else: # if roll == 'STATIC YIN'
hexagram_1.append(0)
hexagram_2.append(0)
# Convert hexagrams lists into tuples
hexagram_1 = tuple(hexagram_1)
hexagram_2 = tuple(hexagram_2)
return (_hexagram_dict[hexagram_1], _hexagram_dict[hexagram_2]) | python | def get_hexagram(method='THREE COIN'):
"""
Return one or two hexagrams using any of a variety of divination methods.
The ``NAIVE`` method simply returns a uniformally random ``int`` between
``1`` and ``64``.
All other methods return a 2-tuple where the first value
represents the starting hexagram and the second represents the 'moving to'
hexagram.
To find the name and unicode glyph for a found hexagram, look it up in
the module-level `hexagrams` dict.
Args:
method (str): ``'THREE COIN'``, ``'YARROW'``, or ``'NAIVE'``,
the divination method model to use. Note that the three coin and
yarrow methods are not actually literally simulated,
but rather statistical models reflecting the methods are passed
to `blur.rand` functions to accurately approximate them.
Returns:
int: If ``method == 'NAIVE'``, the ``int`` key of the found hexagram.
Otherwise a `tuple` will be returned.
tuple: A 2-tuple of form ``(int, int)`` where the first value
is key of the starting hexagram and the second is that of the
'moving-to' hexagram.
Raises: ValueError if ``method`` is invalid
Examples:
The function being used alone: ::
>>> get_hexagram(method='THREE COIN') # doctest: +SKIP
# Might be...
(55, 2)
>>> get_hexagram(method='YARROW') # doctest: +SKIP
# Might be...
(41, 27)
>>> get_hexagram(method='NAIVE') # doctest: +SKIP
# Might be...
26
Usage in combination with hexagram lookup: ::
>>> grams = get_hexagram()
>>> grams # doctest: +SKIP
(47, 42)
# unpack hexagrams for convenient reference
>>> initial, moving_to = grams
>>> hexagrams[initial] # doctest: +SKIP
('䷮', '困', 'Confining')
>>> hexagrams[moving_to] # doctest: +SKIP
('䷩', '益', 'Augmenting')
>>> print('{} moving to {}'.format(
... hexagrams[initial][2],
... hexagrams[moving_to][2])
... ) # doctest: +SKIP
Confining moving to Augmenting
"""
if method == 'THREE COIN':
weights = [('MOVING YANG', 2),
('MOVING YIN', 2),
('STATIC YANG', 6),
('STATIC YIN', 6)]
elif method == 'YARROW':
weights = [('MOVING YANG', 8),
('MOVING YIN', 2),
('STATIC YANG', 11),
('STATIC YIN', 17)]
elif method == 'NAIVE':
return random.randint(1, 64)
else:
raise ValueError('`method` value of "{}" is invalid')
hexagram_1 = []
hexagram_2 = []
for i in range(6):
roll = weighted_choice(weights)
if roll == 'MOVING YANG':
hexagram_1.append(1)
hexagram_2.append(0)
elif roll == 'MOVING YIN':
hexagram_1.append(0)
hexagram_2.append(1)
elif roll == 'STATIC YANG':
hexagram_1.append(1)
hexagram_2.append(1)
else: # if roll == 'STATIC YIN'
hexagram_1.append(0)
hexagram_2.append(0)
# Convert hexagrams lists into tuples
hexagram_1 = tuple(hexagram_1)
hexagram_2 = tuple(hexagram_2)
return (_hexagram_dict[hexagram_1], _hexagram_dict[hexagram_2]) | [
"def",
"get_hexagram",
"(",
"method",
"=",
"'THREE COIN'",
")",
":",
"if",
"method",
"==",
"'THREE COIN'",
":",
"weights",
"=",
"[",
"(",
"'MOVING YANG'",
",",
"2",
")",
",",
"(",
"'MOVING YIN'",
",",
"2",
")",
",",
"(",
"'STATIC YANG'",
",",
"6",
")",... | Return one or two hexagrams using any of a variety of divination methods.
The ``NAIVE`` method simply returns a uniformally random ``int`` between
``1`` and ``64``.
All other methods return a 2-tuple where the first value
represents the starting hexagram and the second represents the 'moving to'
hexagram.
To find the name and unicode glyph for a found hexagram, look it up in
the module-level `hexagrams` dict.
Args:
method (str): ``'THREE COIN'``, ``'YARROW'``, or ``'NAIVE'``,
the divination method model to use. Note that the three coin and
yarrow methods are not actually literally simulated,
but rather statistical models reflecting the methods are passed
to `blur.rand` functions to accurately approximate them.
Returns:
int: If ``method == 'NAIVE'``, the ``int`` key of the found hexagram.
Otherwise a `tuple` will be returned.
tuple: A 2-tuple of form ``(int, int)`` where the first value
is key of the starting hexagram and the second is that of the
'moving-to' hexagram.
Raises: ValueError if ``method`` is invalid
Examples:
The function being used alone: ::
>>> get_hexagram(method='THREE COIN') # doctest: +SKIP
# Might be...
(55, 2)
>>> get_hexagram(method='YARROW') # doctest: +SKIP
# Might be...
(41, 27)
>>> get_hexagram(method='NAIVE') # doctest: +SKIP
# Might be...
26
Usage in combination with hexagram lookup: ::
>>> grams = get_hexagram()
>>> grams # doctest: +SKIP
(47, 42)
# unpack hexagrams for convenient reference
>>> initial, moving_to = grams
>>> hexagrams[initial] # doctest: +SKIP
('䷮', '困', 'Confining')
>>> hexagrams[moving_to] # doctest: +SKIP
('䷩', '益', 'Augmenting')
>>> print('{} moving to {}'.format(
... hexagrams[initial][2],
... hexagrams[moving_to][2])
... ) # doctest: +SKIP
Confining moving to Augmenting | [
"Return",
"one",
"or",
"two",
"hexagrams",
"using",
"any",
"of",
"a",
"variety",
"of",
"divination",
"methods",
"."
] | train | https://github.com/ajyoon/blur/blob/25fcf083af112bb003956a7a7e1c6ff7d8fef279/blur/iching.py#L162-L259 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/supported.py | get_supported_resources | def get_supported_resources(netid):
"""
Returns list of Supported resources
"""
url = _netid_supported_url(netid)
response = get_resource(url)
return _json_to_supported(response) | python | def get_supported_resources(netid):
"""
Returns list of Supported resources
"""
url = _netid_supported_url(netid)
response = get_resource(url)
return _json_to_supported(response) | [
"def",
"get_supported_resources",
"(",
"netid",
")",
":",
"url",
"=",
"_netid_supported_url",
"(",
"netid",
")",
"response",
"=",
"get_resource",
"(",
"url",
")",
"return",
"_json_to_supported",
"(",
"response",
")"
] | Returns list of Supported resources | [
"Returns",
"list",
"of",
"Supported",
"resources"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/supported.py#L14-L20 |
uw-it-aca/uw-restclients-uwnetid | uw_uwnetid/supported.py | _json_to_supported | def _json_to_supported(response_body):
"""
Returns a list of Supported objects
"""
data = json.loads(response_body)
supported = []
for supported_data in data.get("supportedList", []):
supported.append(Supported().from_json(
supported_data))
return supported | python | def _json_to_supported(response_body):
"""
Returns a list of Supported objects
"""
data = json.loads(response_body)
supported = []
for supported_data in data.get("supportedList", []):
supported.append(Supported().from_json(
supported_data))
return supported | [
"def",
"_json_to_supported",
"(",
"response_body",
")",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"response_body",
")",
"supported",
"=",
"[",
"]",
"for",
"supported_data",
"in",
"data",
".",
"get",
"(",
"\"supportedList\"",
",",
"[",
"]",
")",
":",
"... | Returns a list of Supported objects | [
"Returns",
"a",
"list",
"of",
"Supported",
"objects"
] | train | https://github.com/uw-it-aca/uw-restclients-uwnetid/blob/58c78b564f9c920a8f8fd408eec959ddd5605b0b/uw_uwnetid/supported.py#L31-L41 |
bioidiap/gridtk | gridtk/easy.py | add_arguments | def add_arguments(parser):
"""Adds stock arguments to argparse parsers from scripts that submit grid
jobs."""
default_log_path = os.path.realpath('logs')
parser.add_argument('--log-dir', metavar='LOG', type=str,
dest='logdir', default=default_log_path,
help='Base directory used for logging (defaults to "%(default)s")')
q_choices = (
'default', 'all.q',
'q_1day', 'q1d',
'q_1week', 'q1w',
'q_1month', 'q1m',
'q_1day_mth', 'q1dm',
'q_1week_mth', 'q1wm',
'q_gpu', 'gpu',
'q_long_gpu', 'lgpu',
'q_short_gpu', 'sgpu',
)
parser.add_argument('--queue-name', metavar='QUEUE', type=str,
dest='queue', default=q_choices[0], choices=q_choices,
help='Queue for submission - one of ' + \
'|'.join(q_choices) + ' (defaults to "%(default)s")')
parser.add_argument('--hostname', metavar='HOSTNAME', type=str,
dest='hostname', default=None,
help='If set, it asks the queue to use only a subset of the available nodes')
parser.add_argument('--memfree', metavar='MEMFREE', type=str,
dest='memfree', default=None,
help='Adds the \'-l mem_free\' argument to qsub')
parser.add_argument('--hvmem', metavar='HVMEM', type=str,
dest='hvmem', default=None,
help='Adds the \'-l h_vmem\' argument to qsub')
parser.add_argument('--pe-opt', metavar='PE_OPT', type=str,
dest='pe_opt', default=None,
help='Adds the \'--pe \' argument to qsub')
parser.add_argument('--no-cwd', default=True, action='store_false',
dest='cwd', help='Do not change to the current directory when starting the grid job')
parser.add_argument('--dry-run', default=False, action='store_true',
dest='dryrun', help='Does not really submit anything, just print what would do instead')
parser.add_argument('--job-database', default=None,
dest='statefile', help='The path to the state file that will be created with the submissions (defaults to the parent directory of your logs directory)')
return parser | python | def add_arguments(parser):
"""Adds stock arguments to argparse parsers from scripts that submit grid
jobs."""
default_log_path = os.path.realpath('logs')
parser.add_argument('--log-dir', metavar='LOG', type=str,
dest='logdir', default=default_log_path,
help='Base directory used for logging (defaults to "%(default)s")')
q_choices = (
'default', 'all.q',
'q_1day', 'q1d',
'q_1week', 'q1w',
'q_1month', 'q1m',
'q_1day_mth', 'q1dm',
'q_1week_mth', 'q1wm',
'q_gpu', 'gpu',
'q_long_gpu', 'lgpu',
'q_short_gpu', 'sgpu',
)
parser.add_argument('--queue-name', metavar='QUEUE', type=str,
dest='queue', default=q_choices[0], choices=q_choices,
help='Queue for submission - one of ' + \
'|'.join(q_choices) + ' (defaults to "%(default)s")')
parser.add_argument('--hostname', metavar='HOSTNAME', type=str,
dest='hostname', default=None,
help='If set, it asks the queue to use only a subset of the available nodes')
parser.add_argument('--memfree', metavar='MEMFREE', type=str,
dest='memfree', default=None,
help='Adds the \'-l mem_free\' argument to qsub')
parser.add_argument('--hvmem', metavar='HVMEM', type=str,
dest='hvmem', default=None,
help='Adds the \'-l h_vmem\' argument to qsub')
parser.add_argument('--pe-opt', metavar='PE_OPT', type=str,
dest='pe_opt', default=None,
help='Adds the \'--pe \' argument to qsub')
parser.add_argument('--no-cwd', default=True, action='store_false',
dest='cwd', help='Do not change to the current directory when starting the grid job')
parser.add_argument('--dry-run', default=False, action='store_true',
dest='dryrun', help='Does not really submit anything, just print what would do instead')
parser.add_argument('--job-database', default=None,
dest='statefile', help='The path to the state file that will be created with the submissions (defaults to the parent directory of your logs directory)')
return parser | [
"def",
"add_arguments",
"(",
"parser",
")",
":",
"default_log_path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"'logs'",
")",
"parser",
".",
"add_argument",
"(",
"'--log-dir'",
",",
"metavar",
"=",
"'LOG'",
",",
"type",
"=",
"str",
",",
"dest",
"=",
... | Adds stock arguments to argparse parsers from scripts that submit grid
jobs. | [
"Adds",
"stock",
"arguments",
"to",
"argparse",
"parsers",
"from",
"scripts",
"that",
"submit",
"grid",
"jobs",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/easy.py#L14-L63 |
bioidiap/gridtk | gridtk/easy.py | create_manager | def create_manager(arguments):
"""A simple wrapper to JobManager() that places the statefile on the correct path by default"""
if arguments.statefile is None:
arguments.statefile = os.path.join(os.path.dirname(arguments.logdir), 'submitted.db')
arguments.statefile = os.path.realpath(arguments.statefile)
return manager.JobManager(statefile=arguments.statefile) | python | def create_manager(arguments):
"""A simple wrapper to JobManager() that places the statefile on the correct path by default"""
if arguments.statefile is None:
arguments.statefile = os.path.join(os.path.dirname(arguments.logdir), 'submitted.db')
arguments.statefile = os.path.realpath(arguments.statefile)
return manager.JobManager(statefile=arguments.statefile) | [
"def",
"create_manager",
"(",
"arguments",
")",
":",
"if",
"arguments",
".",
"statefile",
"is",
"None",
":",
"arguments",
".",
"statefile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"arguments",
".",
"logdir",
")... | A simple wrapper to JobManager() that places the statefile on the correct path by default | [
"A",
"simple",
"wrapper",
"to",
"JobManager",
"()",
"that",
"places",
"the",
"statefile",
"on",
"the",
"correct",
"path",
"by",
"default"
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/easy.py#L65-L73 |
bioidiap/gridtk | gridtk/easy.py | submit | def submit(jman, command, arguments, deps=[], array=None):
"""An easy submission option for grid-enabled scripts. Create the log
directories using random hash codes. Use the arguments as parsed by the main
script."""
logdir = os.path.join(os.path.realpath(arguments.logdir),
tools.random_logdir())
jobname = os.path.splitext(os.path.basename(command[0]))[0]
cmd = tools.make_shell(sys.executable, command)
if arguments.dryrun:
return DryRunJob(cmd, cwd=arguments.cwd, queue=arguments.queue,
hostname=arguments.hostname, memfree=arguments.memfree,
hvmem=arguments.hvmem, gpumem=arguments.gpumem, pe_opt=arguments.pe_opt,
stdout=logdir, stderr=logdir, name=jobname, deps=deps,
array=array)
# really submit
return jman.submit(cmd, cwd=arguments.cwd, queue=arguments.queue,
hostname=arguments.hostname, memfree=arguments.memfree,
hvmem=arguments.hvmem, gpumem=arguments.gpumem, pe_opt=arguments.pe_opt,
stdout=logdir, stderr=logdir, name=jobname, deps=deps,
array=array) | python | def submit(jman, command, arguments, deps=[], array=None):
"""An easy submission option for grid-enabled scripts. Create the log
directories using random hash codes. Use the arguments as parsed by the main
script."""
logdir = os.path.join(os.path.realpath(arguments.logdir),
tools.random_logdir())
jobname = os.path.splitext(os.path.basename(command[0]))[0]
cmd = tools.make_shell(sys.executable, command)
if arguments.dryrun:
return DryRunJob(cmd, cwd=arguments.cwd, queue=arguments.queue,
hostname=arguments.hostname, memfree=arguments.memfree,
hvmem=arguments.hvmem, gpumem=arguments.gpumem, pe_opt=arguments.pe_opt,
stdout=logdir, stderr=logdir, name=jobname, deps=deps,
array=array)
# really submit
return jman.submit(cmd, cwd=arguments.cwd, queue=arguments.queue,
hostname=arguments.hostname, memfree=arguments.memfree,
hvmem=arguments.hvmem, gpumem=arguments.gpumem, pe_opt=arguments.pe_opt,
stdout=logdir, stderr=logdir, name=jobname, deps=deps,
array=array) | [
"def",
"submit",
"(",
"jman",
",",
"command",
",",
"arguments",
",",
"deps",
"=",
"[",
"]",
",",
"array",
"=",
"None",
")",
":",
"logdir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"arguments",
".",
"logdi... | An easy submission option for grid-enabled scripts. Create the log
directories using random hash codes. Use the arguments as parsed by the main
script. | [
"An",
"easy",
"submission",
"option",
"for",
"grid",
"-",
"enabled",
"scripts",
".",
"Create",
"the",
"log",
"directories",
"using",
"random",
"hash",
"codes",
".",
"Use",
"the",
"arguments",
"as",
"parsed",
"by",
"the",
"main",
"script",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/easy.py#L135-L158 |
kwkelly/MarkovText | MarkovText/MarkovText.py | Markov.add_to_dict | def add_to_dict(self, text):
""" Generate word n-tuple and next word probability dict """
n = self.n
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|!)\s', text)
# '' is a special symbol for the start of a sentence like pymarkovchain uses
for sentence in sentences:
sentence = sentence.replace('"','') # remove quotes
words = sentence.strip().split() # split each sentence into its constituent words
if len(words) == 0:
continue
# first word follows a sentence end
self.word_dict[("",)][words[0]].count += 1
for j in range(1, n+1):
for i in range(len(words) - 1):
if i + j >= len(words):
continue
word = tuple(words[i:i + j])
self.word_dict[word][words[i + j]].count += 1
# last word precedes a sentence end
self.word_dict[tuple(words[len(words) - j:len(words)])][""].count += 1
# We've now got the db filled with parametrized word counts
# We still need to normalize this to represent probabilities
for word in self.word_dict:
wordsum = 0
for nextword in self.word_dict[word]:
wordsum += self.word_dict[word][nextword].count
if wordsum != 0:
for nextword in self.word_dict[word]:
self.word_dict[word][nextword].prob = self.word_dict[word][nextword].count / wordsum | python | def add_to_dict(self, text):
""" Generate word n-tuple and next word probability dict """
n = self.n
sentences = re.split(r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|!)\s', text)
# '' is a special symbol for the start of a sentence like pymarkovchain uses
for sentence in sentences:
sentence = sentence.replace('"','') # remove quotes
words = sentence.strip().split() # split each sentence into its constituent words
if len(words) == 0:
continue
# first word follows a sentence end
self.word_dict[("",)][words[0]].count += 1
for j in range(1, n+1):
for i in range(len(words) - 1):
if i + j >= len(words):
continue
word = tuple(words[i:i + j])
self.word_dict[word][words[i + j]].count += 1
# last word precedes a sentence end
self.word_dict[tuple(words[len(words) - j:len(words)])][""].count += 1
# We've now got the db filled with parametrized word counts
# We still need to normalize this to represent probabilities
for word in self.word_dict:
wordsum = 0
for nextword in self.word_dict[word]:
wordsum += self.word_dict[word][nextword].count
if wordsum != 0:
for nextword in self.word_dict[word]:
self.word_dict[word][nextword].prob = self.word_dict[word][nextword].count / wordsum | [
"def",
"add_to_dict",
"(",
"self",
",",
"text",
")",
":",
"n",
"=",
"self",
".",
"n",
"sentences",
"=",
"re",
".",
"split",
"(",
"r'(?<!\\w\\.\\w.)(?<![A-Z][a-z]\\.)(?<=\\.|\\?|!)\\s'",
",",
"text",
")",
"# '' is a special symbol for the start of a sentence like pymarko... | Generate word n-tuple and next word probability dict | [
"Generate",
"word",
"n",
"-",
"tuple",
"and",
"next",
"word",
"probability",
"dict"
] | train | https://github.com/kwkelly/MarkovText/blob/39b2c129b8ee04041cd1945322c0e501aca9691b/MarkovText/MarkovText.py#L21-L54 |
kwkelly/MarkovText | MarkovText/MarkovText.py | Markov.next_word | def next_word(self, previous_words):
"""The next word that is generated by the Markov Chain
depends on a tuple of the previous words from the Chain"""
# The previous words may never have appeared in order in the corpus used to
# generate the word_dict. Consequently, we want to try to find the previous
# words in orde, but if they are not there, then we remove the earliest word
# one by one and recheck. This means that next word depends on the current state
# but possible not on the entire state
previous_words = tuple(previous_words)
if previous_words != ("",): # the empty string 1-tuple (singleton tuple) is always there
while previous_words not in self.word_dict:
previous_words = tuple(previous_words[1:])
if not previous_words:
return ""
frequencies = self.word_dict[previous_words]
inv = [(v.prob,k) for k, v in frequencies.items()]
p, w = zip(*inv)
return np.random.choice(w,1,p)[0] | python | def next_word(self, previous_words):
"""The next word that is generated by the Markov Chain
depends on a tuple of the previous words from the Chain"""
# The previous words may never have appeared in order in the corpus used to
# generate the word_dict. Consequently, we want to try to find the previous
# words in orde, but if they are not there, then we remove the earliest word
# one by one and recheck. This means that next word depends on the current state
# but possible not on the entire state
previous_words = tuple(previous_words)
if previous_words != ("",): # the empty string 1-tuple (singleton tuple) is always there
while previous_words not in self.word_dict:
previous_words = tuple(previous_words[1:])
if not previous_words:
return ""
frequencies = self.word_dict[previous_words]
inv = [(v.prob,k) for k, v in frequencies.items()]
p, w = zip(*inv)
return np.random.choice(w,1,p)[0] | [
"def",
"next_word",
"(",
"self",
",",
"previous_words",
")",
":",
"# The previous words may never have appeared in order in the corpus used to",
"# generate the word_dict. Consequently, we want to try to find the previous ",
"# words in orde, but if they are not there, then we remove the earlies... | The next word that is generated by the Markov Chain
depends on a tuple of the previous words from the Chain | [
"The",
"next",
"word",
"that",
"is",
"generated",
"by",
"the",
"Markov",
"Chain",
"depends",
"on",
"a",
"tuple",
"of",
"the",
"previous",
"words",
"from",
"the",
"Chain"
] | train | https://github.com/kwkelly/MarkovText/blob/39b2c129b8ee04041cd1945322c0e501aca9691b/MarkovText/MarkovText.py#L65-L82 |
duniter/duniter-python-api | examples/send_transaction.py | get_transaction_document | def get_transaction_document(current_block: dict, source: dict, from_pubkey: str, to_pubkey: str) -> Transaction:
"""
Return a Transaction document
:param current_block: Current block infos
:param source: Source to send
:param from_pubkey: Public key of the issuer
:param to_pubkey: Public key of the receiver
:return: Transaction
"""
# list of inputs (sources)
inputs = [
InputSource(
amount=source['amount'],
base=source['base'],
source=source['type'],
origin_id=source['identifier'],
index=source['noffset']
)
]
# list of issuers of the inputs
issuers = [
from_pubkey
]
# list of unlocks of the inputs
unlocks = [
Unlock(
# inputs[index]
index=0,
# unlock inputs[index] if signatures[0] is from public key of issuers[0]
parameters=[SIGParameter(0)]
)
]
# lists of outputs
outputs = [
OutputSource(amount=source['amount'], base=source['base'], condition="SIG({0})".format(to_pubkey))
]
transaction = Transaction(
version=TRANSACTION_VERSION,
currency=current_block['currency'],
blockstamp=BlockUID(current_block['number'], current_block['hash']),
locktime=0,
issuers=issuers,
inputs=inputs,
unlocks=unlocks,
outputs=outputs,
comment='',
signatures=[]
)
return transaction | python | def get_transaction_document(current_block: dict, source: dict, from_pubkey: str, to_pubkey: str) -> Transaction:
"""
Return a Transaction document
:param current_block: Current block infos
:param source: Source to send
:param from_pubkey: Public key of the issuer
:param to_pubkey: Public key of the receiver
:return: Transaction
"""
# list of inputs (sources)
inputs = [
InputSource(
amount=source['amount'],
base=source['base'],
source=source['type'],
origin_id=source['identifier'],
index=source['noffset']
)
]
# list of issuers of the inputs
issuers = [
from_pubkey
]
# list of unlocks of the inputs
unlocks = [
Unlock(
# inputs[index]
index=0,
# unlock inputs[index] if signatures[0] is from public key of issuers[0]
parameters=[SIGParameter(0)]
)
]
# lists of outputs
outputs = [
OutputSource(amount=source['amount'], base=source['base'], condition="SIG({0})".format(to_pubkey))
]
transaction = Transaction(
version=TRANSACTION_VERSION,
currency=current_block['currency'],
blockstamp=BlockUID(current_block['number'], current_block['hash']),
locktime=0,
issuers=issuers,
inputs=inputs,
unlocks=unlocks,
outputs=outputs,
comment='',
signatures=[]
)
return transaction | [
"def",
"get_transaction_document",
"(",
"current_block",
":",
"dict",
",",
"source",
":",
"dict",
",",
"from_pubkey",
":",
"str",
",",
"to_pubkey",
":",
"str",
")",
"->",
"Transaction",
":",
"# list of inputs (sources)",
"inputs",
"=",
"[",
"InputSource",
"(",
... | Return a Transaction document
:param current_block: Current block infos
:param source: Source to send
:param from_pubkey: Public key of the issuer
:param to_pubkey: Public key of the receiver
:return: Transaction | [
"Return",
"a",
"Transaction",
"document"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/send_transaction.py#L24-L79 |
duniter/duniter-python-api | examples/send_transaction.py | main | async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection
response = await client(bma.node.summary)
print(response)
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
# prompt hidden user entry
password = getpass.getpass("Enter your password: ")
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
pubkey_from = key.pubkey
# prompt entry
pubkey_to = input("Enter recipient pubkey: ")
# capture current block to get version and currency and blockstamp
current_block = await client(bma.blockchain.current)
# capture sources of account
response = await client(bma.tx.sources, pubkey_from)
if len(response['sources']) == 0:
print("no sources found for account %s" % pubkey_to)
exit(1)
# get the first source
source = response['sources'][0]
# create the transaction document
transaction = get_transaction_document(current_block, source, pubkey_from, pubkey_to)
# sign document
transaction.sign([key])
# send the Transaction document to the node
response = await client(bma.tx.process, transaction.signed_raw())
if response.status == 200:
print(await response.text())
else:
print("Error while publishing transaction: {0}".format(await response.text()))
# Close client aiohttp session
await client.close() | python | async def main():
"""
Main code
"""
# Create Client from endpoint string in Duniter format
client = Client(BMAS_ENDPOINT)
# Get the node summary infos to test the connection
response = await client(bma.node.summary)
print(response)
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
# prompt hidden user entry
password = getpass.getpass("Enter your password: ")
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
pubkey_from = key.pubkey
# prompt entry
pubkey_to = input("Enter recipient pubkey: ")
# capture current block to get version and currency and blockstamp
current_block = await client(bma.blockchain.current)
# capture sources of account
response = await client(bma.tx.sources, pubkey_from)
if len(response['sources']) == 0:
print("no sources found for account %s" % pubkey_to)
exit(1)
# get the first source
source = response['sources'][0]
# create the transaction document
transaction = get_transaction_document(current_block, source, pubkey_from, pubkey_to)
# sign document
transaction.sign([key])
# send the Transaction document to the node
response = await client(bma.tx.process, transaction.signed_raw())
if response.status == 200:
print(await response.text())
else:
print("Error while publishing transaction: {0}".format(await response.text()))
# Close client aiohttp session
await client.close() | [
"async",
"def",
"main",
"(",
")",
":",
"# Create Client from endpoint string in Duniter format",
"client",
"=",
"Client",
"(",
"BMAS_ENDPOINT",
")",
"# Get the node summary infos to test the connection",
"response",
"=",
"await",
"client",
"(",
"bma",
".",
"node",
".",
... | Main code | [
"Main",
"code"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/examples/send_transaction.py#L82-L134 |
jacopofar/runtime_typecheck | runtime_typecheck/runtime_typecheck.py | check_type | def check_type(obj: Any,
candidate_type: Any,
reltype: str = 'invariant') -> bool:
"""Tell wether a value correspond to a type,
optionally specifying the type as contravariant or covariant.
Args:
obj (Any): The value to check.
candidate_type (Any): The type to check the object against.
reltype (:obj:`str`, optional): Variance of the type, can be contravariant,
covariant or invariant. By default is invariant.
Returns:
bool: True if the type is fine, False otherwise
Raises:
ValueError: When the variance or the type are not among the ones the function can manage.
"""
if reltype not in ['invariant', 'covariant', 'contravariant']:
raise ValueError(f' Variadic type {reltype} is unknown')
# builtin type like str, or a class
if type(candidate_type) == type and reltype in ['invariant']:
return isinstance(obj, candidate_type)
if type(candidate_type) == type and reltype in ['covariant']:
return issubclass(obj.__class__, candidate_type)
if type(candidate_type) == type and reltype in ['contravariant']:
return issubclass(candidate_type, obj.__class__)
# Any accepts everything
if type(candidate_type) == type(Any):
return True
# Union, at least one match in __args__
if type(candidate_type) == type(Union):
return any(check_type(obj, t, reltype) for t in candidate_type.__args__)
# Tuple, each element matches the corresponding type in __args__
if type(candidate_type) == type(Tuple) and tuple in candidate_type.__bases__:
if not hasattr(obj, '__len__'):
return False
if len(candidate_type.__args__) != len(obj):
return False
return all(check_type(o, t, reltype) for (o, t) in zip(obj, candidate_type.__args__))
# Dict, each (key, value) matches the type in __args__
if type(candidate_type) == type(Dict) and dict in candidate_type.__bases__:
if type(obj) != dict:
return False
return all(check_type(k, candidate_type.__args__[0], reltype)
and check_type(v, candidate_type.__args__[1], reltype)
for (k, v) in obj.items())
# List or Set, each element matches the type in __args__
if type(candidate_type) == type(List) and \
(list in candidate_type.__bases__ or set in candidate_type.__bases__):
if not hasattr(obj, '__len__'):
return False
return all(check_type(o, candidate_type.__args__[0], reltype) for o in obj)
# TypeVar, this is tricky
if type(candidate_type) == TypeVar:
# TODO consider contravariant, variant and bound
# invariant with a list of constraints, acts like a Tuple
if not candidate_type.__constraints__:
return True
if not (candidate_type.__covariant__ or candidate_type.__contravariant__):
return any(check_type(obj, t) for t in candidate_type.__constraints__)
if type(candidate_type) == type(Type):
return check_type(obj, candidate_type.__args__[0], reltype='covariant')
if inspect.isclass(candidate_type) and reltype in ['invariant']:
return isinstance(obj, candidate_type)
raise ValueError(f'Cannot check against {reltype} type {candidate_type}') | python | def check_type(obj: Any,
candidate_type: Any,
reltype: str = 'invariant') -> bool:
"""Tell wether a value correspond to a type,
optionally specifying the type as contravariant or covariant.
Args:
obj (Any): The value to check.
candidate_type (Any): The type to check the object against.
reltype (:obj:`str`, optional): Variance of the type, can be contravariant,
covariant or invariant. By default is invariant.
Returns:
bool: True if the type is fine, False otherwise
Raises:
ValueError: When the variance or the type are not among the ones the function can manage.
"""
if reltype not in ['invariant', 'covariant', 'contravariant']:
raise ValueError(f' Variadic type {reltype} is unknown')
# builtin type like str, or a class
if type(candidate_type) == type and reltype in ['invariant']:
return isinstance(obj, candidate_type)
if type(candidate_type) == type and reltype in ['covariant']:
return issubclass(obj.__class__, candidate_type)
if type(candidate_type) == type and reltype in ['contravariant']:
return issubclass(candidate_type, obj.__class__)
# Any accepts everything
if type(candidate_type) == type(Any):
return True
# Union, at least one match in __args__
if type(candidate_type) == type(Union):
return any(check_type(obj, t, reltype) for t in candidate_type.__args__)
# Tuple, each element matches the corresponding type in __args__
if type(candidate_type) == type(Tuple) and tuple in candidate_type.__bases__:
if not hasattr(obj, '__len__'):
return False
if len(candidate_type.__args__) != len(obj):
return False
return all(check_type(o, t, reltype) for (o, t) in zip(obj, candidate_type.__args__))
# Dict, each (key, value) matches the type in __args__
if type(candidate_type) == type(Dict) and dict in candidate_type.__bases__:
if type(obj) != dict:
return False
return all(check_type(k, candidate_type.__args__[0], reltype)
and check_type(v, candidate_type.__args__[1], reltype)
for (k, v) in obj.items())
# List or Set, each element matches the type in __args__
if type(candidate_type) == type(List) and \
(list in candidate_type.__bases__ or set in candidate_type.__bases__):
if not hasattr(obj, '__len__'):
return False
return all(check_type(o, candidate_type.__args__[0], reltype) for o in obj)
# TypeVar, this is tricky
if type(candidate_type) == TypeVar:
# TODO consider contravariant, variant and bound
# invariant with a list of constraints, acts like a Tuple
if not candidate_type.__constraints__:
return True
if not (candidate_type.__covariant__ or candidate_type.__contravariant__):
return any(check_type(obj, t) for t in candidate_type.__constraints__)
if type(candidate_type) == type(Type):
return check_type(obj, candidate_type.__args__[0], reltype='covariant')
if inspect.isclass(candidate_type) and reltype in ['invariant']:
return isinstance(obj, candidate_type)
raise ValueError(f'Cannot check against {reltype} type {candidate_type}') | [
"def",
"check_type",
"(",
"obj",
":",
"Any",
",",
"candidate_type",
":",
"Any",
",",
"reltype",
":",
"str",
"=",
"'invariant'",
")",
"->",
"bool",
":",
"if",
"reltype",
"not",
"in",
"[",
"'invariant'",
",",
"'covariant'",
",",
"'contravariant'",
"]",
":"... | Tell wether a value correspond to a type,
optionally specifying the type as contravariant or covariant.
Args:
obj (Any): The value to check.
candidate_type (Any): The type to check the object against.
reltype (:obj:`str`, optional): Variance of the type, can be contravariant,
covariant or invariant. By default is invariant.
Returns:
bool: True if the type is fine, False otherwise
Raises:
ValueError: When the variance or the type are not among the ones the function can manage. | [
"Tell",
"wether",
"a",
"value",
"correspond",
"to",
"a",
"type",
"optionally",
"specifying",
"the",
"type",
"as",
"contravariant",
"or",
"covariant",
"."
] | train | https://github.com/jacopofar/runtime_typecheck/blob/9a5e5caff65751bfd711cfe8b4b7dd31d5ece215/runtime_typecheck/runtime_typecheck.py#L15-L91 |
jacopofar/runtime_typecheck | runtime_typecheck/runtime_typecheck.py | check_args | def check_args(func):
"""A decorator that performs type checking using type hints at runtime::
@check_args
def fun(a: int):
print(f'fun is being called with parameter {a}')
# this will raise a TypeError describing the issue without the function being called
fun('not an int')
"""
@wraps(func)
def check(*args, **kwargs): # pylint: disable=C0111
sig = inspect.signature(func)
found_errors = []
binding = None
try:
binding = sig.bind(*args, **kwargs)
except TypeError as te:
for name, metadata in sig.parameters.items():
# Comparison with the message error as a string :(
# Know a nicer way? Please drop me a message
if metadata.default == inspect.Parameter.empty:
# copy from inspect module, it is the very same error message
error_in_case = 'missing a required argument: {arg!r}'.format(arg=name)
if str(te) == error_in_case:
found_errors.append(IssueDescription(
name, sig.parameters[name].annotation, None, True))
# NOTE currently only find one, at most, detecting what else
# is missing is tricky if not impossible
if not found_errors:
raise DetailedTypeError([IssueDescription(None, None, None, None, str(te))])
raise DetailedTypeError(found_errors)
for name, value in binding.arguments.items():
if not check_type(value, sig.parameters[name].annotation):
found_errors.append(IssueDescription(
name, sig.parameters[name].annotation, value, False))
if found_errors:
raise DetailedTypeError(found_errors)
return func(*args, **kwargs)
return check | python | def check_args(func):
"""A decorator that performs type checking using type hints at runtime::
@check_args
def fun(a: int):
print(f'fun is being called with parameter {a}')
# this will raise a TypeError describing the issue without the function being called
fun('not an int')
"""
@wraps(func)
def check(*args, **kwargs): # pylint: disable=C0111
sig = inspect.signature(func)
found_errors = []
binding = None
try:
binding = sig.bind(*args, **kwargs)
except TypeError as te:
for name, metadata in sig.parameters.items():
# Comparison with the message error as a string :(
# Know a nicer way? Please drop me a message
if metadata.default == inspect.Parameter.empty:
# copy from inspect module, it is the very same error message
error_in_case = 'missing a required argument: {arg!r}'.format(arg=name)
if str(te) == error_in_case:
found_errors.append(IssueDescription(
name, sig.parameters[name].annotation, None, True))
# NOTE currently only find one, at most, detecting what else
# is missing is tricky if not impossible
if not found_errors:
raise DetailedTypeError([IssueDescription(None, None, None, None, str(te))])
raise DetailedTypeError(found_errors)
for name, value in binding.arguments.items():
if not check_type(value, sig.parameters[name].annotation):
found_errors.append(IssueDescription(
name, sig.parameters[name].annotation, value, False))
if found_errors:
raise DetailedTypeError(found_errors)
return func(*args, **kwargs)
return check | [
"def",
"check_args",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"check",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=C0111",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"found_errors",
"=",
... | A decorator that performs type checking using type hints at runtime::
@check_args
def fun(a: int):
print(f'fun is being called with parameter {a}')
# this will raise a TypeError describing the issue without the function being called
fun('not an int') | [
"A",
"decorator",
"that",
"performs",
"type",
"checking",
"using",
"type",
"hints",
"at",
"runtime",
"::"
] | train | https://github.com/jacopofar/runtime_typecheck/blob/9a5e5caff65751bfd711cfe8b4b7dd31d5ece215/runtime_typecheck/runtime_typecheck.py#L94-L135 |
onyxfish/clan | clan/auth.py | AuthCommand.add_argparser | def add_argparser(self, root, parents):
"""
Add arguments for this command.
"""
parents.append(tools.argparser)
parser = root.add_parser('auth', parents=parents)
parser.set_defaults(func=self)
parser.add_argument(
'--secrets',
dest='secrets', action='store',
help='Path to the authorization secrets file (client_secrets.json).'
)
return parser | python | def add_argparser(self, root, parents):
"""
Add arguments for this command.
"""
parents.append(tools.argparser)
parser = root.add_parser('auth', parents=parents)
parser.set_defaults(func=self)
parser.add_argument(
'--secrets',
dest='secrets', action='store',
help='Path to the authorization secrets file (client_secrets.json).'
)
return parser | [
"def",
"add_argparser",
"(",
"self",
",",
"root",
",",
"parents",
")",
":",
"parents",
".",
"append",
"(",
"tools",
".",
"argparser",
")",
"parser",
"=",
"root",
".",
"add_parser",
"(",
"'auth'",
",",
"parents",
"=",
"parents",
")",
"parser",
".",
"set... | Add arguments for this command. | [
"Add",
"arguments",
"for",
"this",
"command",
"."
] | train | https://github.com/onyxfish/clan/blob/415ddd027ea81013f2d62d75aec6da70703df49c/clan/auth.py#L35-L50 |
COLORFULBOARD/revision | revision/client.py | Client.add_config | def add_config(self, config):
"""
:param config:
:type config: dict
"""
self.pre_configure()
self.config = config
if not self.has_revision_file():
#: Create new revision file.
touch_file(self.revfile_path)
self.history.load(self.revfile_path)
self.archiver.target_path = self.dest_path
self.archiver.zip_path = self.tmp_file_path
self.state.state_path = os.path.join(
REVISION_HOME,
"clients",
self.key
)
self.state.prepare()
self.post_configure()
self.prepared = True | python | def add_config(self, config):
"""
:param config:
:type config: dict
"""
self.pre_configure()
self.config = config
if not self.has_revision_file():
#: Create new revision file.
touch_file(self.revfile_path)
self.history.load(self.revfile_path)
self.archiver.target_path = self.dest_path
self.archiver.zip_path = self.tmp_file_path
self.state.state_path = os.path.join(
REVISION_HOME,
"clients",
self.key
)
self.state.prepare()
self.post_configure()
self.prepared = True | [
"def",
"add_config",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"pre_configure",
"(",
")",
"self",
".",
"config",
"=",
"config",
"if",
"not",
"self",
".",
"has_revision_file",
"(",
")",
":",
"#: Create new revision file.",
"touch_file",
"(",
"self",
... | :param config:
:type config: dict | [
":",
"param",
"config",
":",
":",
"type",
"config",
":",
"dict"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L79-L106 |
COLORFULBOARD/revision | revision/client.py | Client.filename | def filename(self):
"""
:return:
:rtype: str
"""
filename = self.key
if self.has_revision_file() and self.history.current_revision:
filename += "-"
filename += self.history.current_revision.revision_id
filename += ".zip"
return filename | python | def filename(self):
"""
:return:
:rtype: str
"""
filename = self.key
if self.has_revision_file() and self.history.current_revision:
filename += "-"
filename += self.history.current_revision.revision_id
filename += ".zip"
return filename | [
"def",
"filename",
"(",
"self",
")",
":",
"filename",
"=",
"self",
".",
"key",
"if",
"self",
".",
"has_revision_file",
"(",
")",
"and",
"self",
".",
"history",
".",
"current_revision",
":",
"filename",
"+=",
"\"-\"",
"filename",
"+=",
"self",
".",
"histo... | :return:
:rtype: str | [
":",
"return",
":",
":",
"rtype",
":",
"str"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L149-L162 |
COLORFULBOARD/revision | revision/client.py | Client.has_commit | def has_commit(self):
"""
:return:
:rtype: boolean
"""
current_revision = self.history.current_revision
revision_id = self.state.revision_id
return current_revision.revision_id != revision_id | python | def has_commit(self):
"""
:return:
:rtype: boolean
"""
current_revision = self.history.current_revision
revision_id = self.state.revision_id
return current_revision.revision_id != revision_id | [
"def",
"has_commit",
"(",
"self",
")",
":",
"current_revision",
"=",
"self",
".",
"history",
".",
"current_revision",
"revision_id",
"=",
"self",
".",
"state",
".",
"revision_id",
"return",
"current_revision",
".",
"revision_id",
"!=",
"revision_id"
] | :return:
:rtype: boolean | [
":",
"return",
":",
":",
"rtype",
":",
"boolean"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L178-L186 |
COLORFULBOARD/revision | revision/client.py | Client.revfile_path | def revfile_path(self):
"""
:return: The full path of revision file.
:rtype: str
"""
return os.path.normpath(os.path.join(
os.getcwd(),
self.config.revision_file
)) | python | def revfile_path(self):
"""
:return: The full path of revision file.
:rtype: str
"""
return os.path.normpath(os.path.join(
os.getcwd(),
self.config.revision_file
)) | [
"def",
"revfile_path",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"self",
".",
"config",
".",
"revision_file",
")",
")"
] | :return: The full path of revision file.
:rtype: str | [
":",
"return",
":",
"The",
"full",
"path",
"of",
"revision",
"file",
".",
":",
"rtype",
":",
"str"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L189-L197 |
COLORFULBOARD/revision | revision/client.py | Client.infofile_path | def infofile_path(self):
"""
:return:
:rtype: str
"""
return os.path.normpath(os.path.join(
self.dest_path,
self.config.info_file
)) | python | def infofile_path(self):
"""
:return:
:rtype: str
"""
return os.path.normpath(os.path.join(
self.dest_path,
self.config.info_file
)) | [
"def",
"infofile_path",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dest_path",
",",
"self",
".",
"config",
".",
"info_file",
")",
")"
] | :return:
:rtype: str | [
":",
"return",
":",
":",
"rtype",
":",
"str"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L200-L208 |
COLORFULBOARD/revision | revision/client.py | Client.dest_path | def dest_path(self):
"""
:return: The destination path.
:rtype: str
"""
if os.path.isabs(self.config.local_path):
return self.config.local_path
else:
return os.path.normpath(os.path.join(
os.getcwd(),
self.config.local_path
)) | python | def dest_path(self):
"""
:return: The destination path.
:rtype: str
"""
if os.path.isabs(self.config.local_path):
return self.config.local_path
else:
return os.path.normpath(os.path.join(
os.getcwd(),
self.config.local_path
)) | [
"def",
"dest_path",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"self",
".",
"config",
".",
"local_path",
")",
":",
"return",
"self",
".",
"config",
".",
"local_path",
"else",
":",
"return",
"os",
".",
"path",
".",
"normpath",
... | :return: The destination path.
:rtype: str | [
":",
"return",
":",
"The",
"destination",
"path",
".",
":",
"rtype",
":",
"str"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L211-L222 |
COLORFULBOARD/revision | revision/client.py | Client.tmp_file_path | def tmp_file_path(self):
"""
:return:
:rtype: str
"""
return os.path.normpath(os.path.join(
TMP_DIR,
self.filename
)) | python | def tmp_file_path(self):
"""
:return:
:rtype: str
"""
return os.path.normpath(os.path.join(
TMP_DIR,
self.filename
)) | [
"def",
"tmp_file_path",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"TMP_DIR",
",",
"self",
".",
"filename",
")",
")"
] | :return:
:rtype: str | [
":",
"return",
":",
":",
"rtype",
":",
"str"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L225-L233 |
COLORFULBOARD/revision | revision/client.py | Client.save | def save(self, revision):
"""
:param revision:
:type revision: :class:`revision.data.Revision`
"""
if not isinstance(revision, Revision):
raise InvalidArgType()
self.state.update(revision) | python | def save(self, revision):
"""
:param revision:
:type revision: :class:`revision.data.Revision`
"""
if not isinstance(revision, Revision):
raise InvalidArgType()
self.state.update(revision) | [
"def",
"save",
"(",
"self",
",",
"revision",
")",
":",
"if",
"not",
"isinstance",
"(",
"revision",
",",
"Revision",
")",
":",
"raise",
"InvalidArgType",
"(",
")",
"self",
".",
"state",
".",
"update",
"(",
"revision",
")"
] | :param revision:
:type revision: :class:`revision.data.Revision` | [
":",
"param",
"revision",
":",
":",
"type",
"revision",
":",
":",
"class",
":",
"revision",
".",
"data",
".",
"Revision"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L235-L243 |
COLORFULBOARD/revision | revision/client.py | Client.has_new_revision | def has_new_revision(self):
"""
:return: True if new revision exists, False if not.
:rtype: boolean
"""
if self.history.current_revision is None:
return self.state.revision_id is not None
current_revision_id = self.history.current_revision.revision_id
return self.state.revision_id != current_revision_id | python | def has_new_revision(self):
"""
:return: True if new revision exists, False if not.
:rtype: boolean
"""
if self.history.current_revision is None:
return self.state.revision_id is not None
current_revision_id = self.history.current_revision.revision_id
return self.state.revision_id != current_revision_id | [
"def",
"has_new_revision",
"(",
"self",
")",
":",
"if",
"self",
".",
"history",
".",
"current_revision",
"is",
"None",
":",
"return",
"self",
".",
"state",
".",
"revision_id",
"is",
"not",
"None",
"current_revision_id",
"=",
"self",
".",
"history",
".",
"c... | :return: True if new revision exists, False if not.
:rtype: boolean | [
":",
"return",
":",
"True",
"if",
"new",
"revision",
"exists",
"False",
"if",
"not",
".",
":",
"rtype",
":",
"boolean"
] | train | https://github.com/COLORFULBOARD/revision/blob/2f22e72cce5b60032a80c002ac45c2ecef0ed987/revision/client.py#L265-L274 |
berndca/xmodels | xmodels/fields.py | BaseField.get_source | def get_source(self, key, name_spaces=None, default_prefix=''):
"""Generates the dictionary key for the serialized representation
based on the instance variable source and a provided key.
:param str key: name of the field in model
:returns: self.source or key
"""
source = self.source or key
prefix = default_prefix
if name_spaces and self.name_space and self.name_space in name_spaces:
prefix = ''.join([name_spaces[self.name_space], ':'])
return ''.join([prefix, source]) | python | def get_source(self, key, name_spaces=None, default_prefix=''):
"""Generates the dictionary key for the serialized representation
based on the instance variable source and a provided key.
:param str key: name of the field in model
:returns: self.source or key
"""
source = self.source or key
prefix = default_prefix
if name_spaces and self.name_space and self.name_space in name_spaces:
prefix = ''.join([name_spaces[self.name_space], ':'])
return ''.join([prefix, source]) | [
"def",
"get_source",
"(",
"self",
",",
"key",
",",
"name_spaces",
"=",
"None",
",",
"default_prefix",
"=",
"''",
")",
":",
"source",
"=",
"self",
".",
"source",
"or",
"key",
"prefix",
"=",
"default_prefix",
"if",
"name_spaces",
"and",
"self",
".",
"name_... | Generates the dictionary key for the serialized representation
based on the instance variable source and a provided key.
:param str key: name of the field in model
:returns: self.source or key | [
"Generates",
"the",
"dictionary",
"key",
"for",
"the",
"serialized",
"representation",
"based",
"on",
"the",
"instance",
"variable",
"source",
"and",
"a",
"provided",
"key",
"."
] | train | https://github.com/berndca/xmodels/blob/8265522229a1ce482a2866cdbd1938293a74bb67/xmodels/fields.py#L86-L97 |
berndca/xmodels | xmodels/fields.py | IntegerField.validate | def validate(self, raw_data, **kwargs):
"""Convert the raw_data to an integer.
"""
try:
converted_data = int(raw_data)
return super(IntegerField, self).validate(converted_data)
except ValueError:
raise ValidationException(self.messages['invalid'], repr(raw_data)) | python | def validate(self, raw_data, **kwargs):
"""Convert the raw_data to an integer.
"""
try:
converted_data = int(raw_data)
return super(IntegerField, self).validate(converted_data)
except ValueError:
raise ValidationException(self.messages['invalid'], repr(raw_data)) | [
"def",
"validate",
"(",
"self",
",",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"converted_data",
"=",
"int",
"(",
"raw_data",
")",
"return",
"super",
"(",
"IntegerField",
",",
"self",
")",
".",
"validate",
"(",
"converted_data",
")",
"... | Convert the raw_data to an integer. | [
"Convert",
"the",
"raw_data",
"to",
"an",
"integer",
"."
] | train | https://github.com/berndca/xmodels/blob/8265522229a1ce482a2866cdbd1938293a74bb67/xmodels/fields.py#L409-L417 |
berndca/xmodels | xmodels/fields.py | FloatField.validate | def validate(self, raw_data, **kwargs):
"""Convert the raw_data to a float.
"""
try:
converted_data = float(raw_data)
super(FloatField, self).validate(converted_data, **kwargs)
return raw_data
except ValueError:
raise ValidationException(self.messages['invalid'], repr(raw_data)) | python | def validate(self, raw_data, **kwargs):
"""Convert the raw_data to a float.
"""
try:
converted_data = float(raw_data)
super(FloatField, self).validate(converted_data, **kwargs)
return raw_data
except ValueError:
raise ValidationException(self.messages['invalid'], repr(raw_data)) | [
"def",
"validate",
"(",
"self",
",",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"converted_data",
"=",
"float",
"(",
"raw_data",
")",
"super",
"(",
"FloatField",
",",
"self",
")",
".",
"validate",
"(",
"converted_data",
",",
"*",
"*",
... | Convert the raw_data to a float. | [
"Convert",
"the",
"raw_data",
"to",
"a",
"float",
"."
] | train | https://github.com/berndca/xmodels/blob/8265522229a1ce482a2866cdbd1938293a74bb67/xmodels/fields.py#L454-L463 |
berndca/xmodels | xmodels/fields.py | BooleanField.validate | def validate(self, raw_data, **kwargs):
"""The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
"""
super(BooleanField, self).validate(raw_data, **kwargs)
if isinstance(raw_data, string_types):
valid_data = raw_data.strip().lower() == 'true'
elif isinstance(raw_data, bool):
valid_data = raw_data
else:
valid_data = raw_data > 0
return valid_data | python | def validate(self, raw_data, **kwargs):
"""The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers.
"""
super(BooleanField, self).validate(raw_data, **kwargs)
if isinstance(raw_data, string_types):
valid_data = raw_data.strip().lower() == 'true'
elif isinstance(raw_data, bool):
valid_data = raw_data
else:
valid_data = raw_data > 0
return valid_data | [
"def",
"validate",
"(",
"self",
",",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"BooleanField",
",",
"self",
")",
".",
"validate",
"(",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"raw_data",
",",
"string_types"... | The string ``'True'`` (case insensitive) will be converted
to ``True``, as will any positive integers. | [
"The",
"string",
"True",
"(",
"case",
"insensitive",
")",
"will",
"be",
"converted",
"to",
"True",
"as",
"will",
"any",
"positive",
"integers",
"."
] | train | https://github.com/berndca/xmodels/blob/8265522229a1ce482a2866cdbd1938293a74bb67/xmodels/fields.py#L508-L520 |
berndca/xmodels | xmodels/fields.py | DateTimeField.validate | def validate(self, raw_data, **kwargs):
"""The raw_data is returned unchanged."""
super(DateTimeField, self).validate(raw_data, **kwargs)
try:
if isinstance(raw_data, datetime.datetime):
self.converted = raw_data
elif self.serial_format is None:
# parse as iso8601
self.converted = parse(raw_data)
else:
self.converted = datetime.datetime.strptime(raw_data,
self.serial_format)
return raw_data
except (ParseError, ValueError) as e:
msg = self.messages['parse'] % dict(cls=self.__class__.__name__,
data=raw_data,
format=self.serial_format)
raise ValidationException(msg, raw_data) | python | def validate(self, raw_data, **kwargs):
"""The raw_data is returned unchanged."""
super(DateTimeField, self).validate(raw_data, **kwargs)
try:
if isinstance(raw_data, datetime.datetime):
self.converted = raw_data
elif self.serial_format is None:
# parse as iso8601
self.converted = parse(raw_data)
else:
self.converted = datetime.datetime.strptime(raw_data,
self.serial_format)
return raw_data
except (ParseError, ValueError) as e:
msg = self.messages['parse'] % dict(cls=self.__class__.__name__,
data=raw_data,
format=self.serial_format)
raise ValidationException(msg, raw_data) | [
"def",
"validate",
"(",
"self",
",",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"DateTimeField",
",",
"self",
")",
".",
"validate",
"(",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"if",
"isinstance",
"(",
"raw_data",
",",... | The raw_data is returned unchanged. | [
"The",
"raw_data",
"is",
"returned",
"unchanged",
"."
] | train | https://github.com/berndca/xmodels/blob/8265522229a1ce482a2866cdbd1938293a74bb67/xmodels/fields.py#L600-L618 |
berndca/xmodels | xmodels/fields.py | DateTimeField.deserialize | def deserialize(self, raw_data, **kwargs):
"""A :class:`datetime.datetime` object is returned."""
super(DateTimeField, self).deserialize(raw_data, **kwargs)
return self.converted | python | def deserialize(self, raw_data, **kwargs):
"""A :class:`datetime.datetime` object is returned."""
super(DateTimeField, self).deserialize(raw_data, **kwargs)
return self.converted | [
"def",
"deserialize",
"(",
"self",
",",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
"DateTimeField",
",",
"self",
")",
".",
"deserialize",
"(",
"raw_data",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"converted"
] | A :class:`datetime.datetime` object is returned. | [
"A",
":",
"class",
":",
"datetime",
".",
"datetime",
"object",
"is",
"returned",
"."
] | train | https://github.com/berndca/xmodels/blob/8265522229a1ce482a2866cdbd1938293a74bb67/xmodels/fields.py#L620-L623 |
marteinn/AtomicPress | atomicpress/ext/importer/__init__.py | _clean_post_content | def _clean_post_content(blog_url, content):
"""
Replace import path with something relative to blog.
"""
content = re.sub(
"<img.src=\"%s(.*)\"" % blog_url,
lambda s: "<img src=\"%s\"" % _get_relative_upload(s.groups(1)[0]),
content)
return content | python | def _clean_post_content(blog_url, content):
"""
Replace import path with something relative to blog.
"""
content = re.sub(
"<img.src=\"%s(.*)\"" % blog_url,
lambda s: "<img src=\"%s\"" % _get_relative_upload(s.groups(1)[0]),
content)
return content | [
"def",
"_clean_post_content",
"(",
"blog_url",
",",
"content",
")",
":",
"content",
"=",
"re",
".",
"sub",
"(",
"\"<img.src=\\\"%s(.*)\\\"\"",
"%",
"blog_url",
",",
"lambda",
"s",
":",
"\"<img src=\\\"%s\\\"\"",
"%",
"_get_relative_upload",
"(",
"s",
".",
"group... | Replace import path with something relative to blog. | [
"Replace",
"import",
"path",
"with",
"something",
"relative",
"to",
"blog",
"."
] | train | https://github.com/marteinn/AtomicPress/blob/b8a0ca9c9c327f062833fc4a401a8ac0baccf6d1/atomicpress/ext/importer/__init__.py#L179-L189 |
damirazo/py-config-parser | config_parser/parser.py | ConfigParser.register_conversion_handler | def register_conversion_handler(self, name, handler):
u"""
Регистрация обработчика конвертирования
:param name: Имя обработчика в таблице соответствия
:param handler: Обработчик
"""
if name in self.conversion_table:
warnings.warn((
u'Конвертирующий тип с именем {} уже '
u'существует и будет перезаписан!'
).format(name))
self.conversion_table[name] = handler | python | def register_conversion_handler(self, name, handler):
u"""
Регистрация обработчика конвертирования
:param name: Имя обработчика в таблице соответствия
:param handler: Обработчик
"""
if name in self.conversion_table:
warnings.warn((
u'Конвертирующий тип с именем {} уже '
u'существует и будет перезаписан!'
).format(name))
self.conversion_table[name] = handler | [
"def",
"register_conversion_handler",
"(",
"self",
",",
"name",
",",
"handler",
")",
":",
"if",
"name",
"in",
"self",
".",
"conversion_table",
":",
"warnings",
".",
"warn",
"(",
"(",
"u'Конвертирующий тип с именем {} уже '",
"u'существует и будет перезаписан!'",
")",
... | u"""
Регистрация обработчика конвертирования
:param name: Имя обработчика в таблице соответствия
:param handler: Обработчик | [
"u",
"Регистрация",
"обработчика",
"конвертирования"
] | train | https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L27-L40 |
damirazo/py-config-parser | config_parser/parser.py | ConfigParser.conversion_handler | def conversion_handler(self, name):
u"""
Возвращает обработчик конвертации с указанным именем
:param name: Имя обработчика
:return: callable
"""
try:
handler = self.conversion_table[name]
except KeyError:
raise KeyError((
u'Конвертирующий тип с именем {} отсутствует '
u'в таблице соответствия!'
).format(name))
return handler | python | def conversion_handler(self, name):
u"""
Возвращает обработчик конвертации с указанным именем
:param name: Имя обработчика
:return: callable
"""
try:
handler = self.conversion_table[name]
except KeyError:
raise KeyError((
u'Конвертирующий тип с именем {} отсутствует '
u'в таблице соответствия!'
).format(name))
return handler | [
"def",
"conversion_handler",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"handler",
"=",
"self",
".",
"conversion_table",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"(",
"u'Конвертирующий тип с именем {} отсутствует '",
"u'в таблице... | u"""
Возвращает обработчик конвертации с указанным именем
:param name: Имя обработчика
:return: callable | [
"u",
"Возвращает",
"обработчик",
"конвертации",
"с",
"указанным",
"именем"
] | train | https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L42-L57 |
damirazo/py-config-parser | config_parser/parser.py | ConfigParser.get | def get(self, key, default=None):
u"""
Возвращает значение с указанным ключем
Пример вызова:
value = self.get('system.database.name')
:param key: Имя параметра
:param default: Значение, возвращаемое по умолчанию
:return: mixed
"""
segments = key.split('.')
result = reduce(
lambda dct, k: dct and dct.get(k) or None,
segments, self.data)
return result or default | python | def get(self, key, default=None):
u"""
Возвращает значение с указанным ключем
Пример вызова:
value = self.get('system.database.name')
:param key: Имя параметра
:param default: Значение, возвращаемое по умолчанию
:return: mixed
"""
segments = key.split('.')
result = reduce(
lambda dct, k: dct and dct.get(k) or None,
segments, self.data)
return result or default | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"segments",
"=",
"key",
".",
"split",
"(",
"'.'",
")",
"result",
"=",
"reduce",
"(",
"lambda",
"dct",
",",
"k",
":",
"dct",
"and",
"dct",
".",
"get",
"(",
"k",
")",
... | u"""
Возвращает значение с указанным ключем
Пример вызова:
value = self.get('system.database.name')
:param key: Имя параметра
:param default: Значение, возвращаемое по умолчанию
:return: mixed | [
"u",
"Возвращает",
"значение",
"с",
"указанным",
"ключем"
] | train | https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L67-L83 |
damirazo/py-config-parser | config_parser/parser.py | ConfigParser.get_converted | def get_converted(self, key, conversion_type, default=None):
u"""
Возвращает значение, приведенное к типу,
соответствующему указанному типу из таблицы соответствия
:param key: Имя параметра
:param conversion_type: Имя обработчика конвертации
из таблицы соответствия
:param default: Значение по умолчанию
:return: mixed
"""
# В случае отсутствия параметра сразу возвращаем значение по умолчанию
if not self.has_param(key):
return default
value = self.get(key, default=default)
handler = self.conversion_handler(conversion_type)
try:
value = handler(value)
except Exception as exc:
raise ConversionTypeError((
u'Произошла ошибка при попытке преобразования типа: {}'
).format(exc))
return value | python | def get_converted(self, key, conversion_type, default=None):
u"""
Возвращает значение, приведенное к типу,
соответствующему указанному типу из таблицы соответствия
:param key: Имя параметра
:param conversion_type: Имя обработчика конвертации
из таблицы соответствия
:param default: Значение по умолчанию
:return: mixed
"""
# В случае отсутствия параметра сразу возвращаем значение по умолчанию
if not self.has_param(key):
return default
value = self.get(key, default=default)
handler = self.conversion_handler(conversion_type)
try:
value = handler(value)
except Exception as exc:
raise ConversionTypeError((
u'Произошла ошибка при попытке преобразования типа: {}'
).format(exc))
return value | [
"def",
"get_converted",
"(",
"self",
",",
"key",
",",
"conversion_type",
",",
"default",
"=",
"None",
")",
":",
"# В случае отсутствия параметра сразу возвращаем значение по умолчанию",
"if",
"not",
"self",
".",
"has_param",
"(",
"key",
")",
":",
"return",
"default"... | u"""
Возвращает значение, приведенное к типу,
соответствующему указанному типу из таблицы соответствия
:param key: Имя параметра
:param conversion_type: Имя обработчика конвертации
из таблицы соответствия
:param default: Значение по умолчанию
:return: mixed | [
"u",
"Возвращает",
"значение",
"приведенное",
"к",
"типу",
"соответствующему",
"указанному",
"типу",
"из",
"таблицы",
"соответствия"
] | train | https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L85-L110 |
damirazo/py-config-parser | config_parser/parser.py | ConfigParser.get_by_type | def get_by_type(self, key, conversion_func, default=None):
u"""
Возвращает значение, приведенное к типу
с использованием переданной функции
:param key: Имя параметра
:param conversion_func: callable объект,
принимающий и возвращающий значение
:param default: Значение по умолчанию
:return: mixed
"""
if not self.has_param(key):
return default
value = self.get(key, default=default)
try:
value = conversion_func(value)
except Exception as exc:
raise ConversionTypeError((
u'Произошла ошибка при попытке преобразования типа: {}'
).format(exc))
return value | python | def get_by_type(self, key, conversion_func, default=None):
u"""
Возвращает значение, приведенное к типу
с использованием переданной функции
:param key: Имя параметра
:param conversion_func: callable объект,
принимающий и возвращающий значение
:param default: Значение по умолчанию
:return: mixed
"""
if not self.has_param(key):
return default
value = self.get(key, default=default)
try:
value = conversion_func(value)
except Exception as exc:
raise ConversionTypeError((
u'Произошла ошибка при попытке преобразования типа: {}'
).format(exc))
return value | [
"def",
"get_by_type",
"(",
"self",
",",
"key",
",",
"conversion_func",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"has_param",
"(",
"key",
")",
":",
"return",
"default",
"value",
"=",
"self",
".",
"get",
"(",
"key",
",",
"defaul... | u"""
Возвращает значение, приведенное к типу
с использованием переданной функции
:param key: Имя параметра
:param conversion_func: callable объект,
принимающий и возвращающий значение
:param default: Значение по умолчанию
:return: mixed | [
"u",
"Возвращает",
"значение",
"приведенное",
"к",
"типу",
"с",
"использованием",
"переданной",
"функции"
] | train | https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L112-L135 |
damirazo/py-config-parser | config_parser/parser.py | ConfigParser.get_int | def get_int(self, key, default=None):
u"""
Возвращает значение, приведенное к числовому
"""
return self.get_converted(
key, ConversionTypeEnum.INTEGER, default=default) | python | def get_int(self, key, default=None):
u"""
Возвращает значение, приведенное к числовому
"""
return self.get_converted(
key, ConversionTypeEnum.INTEGER, default=default) | [
"def",
"get_int",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_converted",
"(",
"key",
",",
"ConversionTypeEnum",
".",
"INTEGER",
",",
"default",
"=",
"default",
")"
] | u"""
Возвращает значение, приведенное к числовому | [
"u",
"Возвращает",
"значение",
"приведенное",
"к",
"числовому"
] | train | https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L141-L146 |
damirazo/py-config-parser | config_parser/parser.py | ConfigParser.get_bool | def get_bool(self, key, default=None):
u"""
Возвращает значение, приведенное к булеву
"""
return self.get_converted(
key, ConversionTypeEnum.BOOL, default=default) | python | def get_bool(self, key, default=None):
u"""
Возвращает значение, приведенное к булеву
"""
return self.get_converted(
key, ConversionTypeEnum.BOOL, default=default) | [
"def",
"get_bool",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"get_converted",
"(",
"key",
",",
"ConversionTypeEnum",
".",
"BOOL",
",",
"default",
"=",
"default",
")"
] | u"""
Возвращает значение, приведенное к булеву | [
"u",
"Возвращает",
"значение",
"приведенное",
"к",
"булеву"
] | train | https://github.com/damirazo/py-config-parser/blob/8dd6efb659b6541713875b15910ca0474723382a/config_parser/parser.py#L148-L153 |
bioidiap/gridtk | gridtk/sge.py | JobManagerSGE._queue | def _queue(self, kwargs):
"""The hard resource_list comes like this: '<qname>=TRUE,mem=128M'. To
process it we have to split it twice (',' and then on '='), create a
dictionary and extract just the qname"""
if not 'hard resource_list' in kwargs: return 'all.q'
d = dict([k.split('=') for k in kwargs['hard resource_list'].split(',')])
for k in d:
if k[0] == 'q' and d[k] == 'TRUE': return k
return 'all.q' | python | def _queue(self, kwargs):
"""The hard resource_list comes like this: '<qname>=TRUE,mem=128M'. To
process it we have to split it twice (',' and then on '='), create a
dictionary and extract just the qname"""
if not 'hard resource_list' in kwargs: return 'all.q'
d = dict([k.split('=') for k in kwargs['hard resource_list'].split(',')])
for k in d:
if k[0] == 'q' and d[k] == 'TRUE': return k
return 'all.q' | [
"def",
"_queue",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"not",
"'hard resource_list'",
"in",
"kwargs",
":",
"return",
"'all.q'",
"d",
"=",
"dict",
"(",
"[",
"k",
".",
"split",
"(",
"'='",
")",
"for",
"k",
"in",
"kwargs",
"[",
"'hard resource_list'... | The hard resource_list comes like this: '<qname>=TRUE,mem=128M'. To
process it we have to split it twice (',' and then on '='), create a
dictionary and extract just the qname | [
"The",
"hard",
"resource_list",
"comes",
"like",
"this",
":",
"<qname",
">",
"=",
"TRUE",
"mem",
"=",
"128M",
".",
"To",
"process",
"it",
"we",
"have",
"to",
"split",
"it",
"twice",
"(",
"and",
"then",
"on",
"=",
")",
"create",
"a",
"dictionary",
"an... | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/sge.py#L43-L51 |
bioidiap/gridtk | gridtk/sge.py | JobManagerSGE.submit | def submit(self, command_line, name = None, array = None, dependencies = [], exec_dir = None, log_dir = "logs", dry_run = False, verbosity = 0, stop_on_failure = False, **kwargs):
"""Submits a job that will be executed in the grid."""
# add job to database
self.lock()
job = add_job(self.session, command_line, name, dependencies, array, exec_dir=exec_dir, log_dir=log_dir, stop_on_failure=stop_on_failure, context=self.context, **kwargs)
logger.info("Added job '%s' to the database." % job)
if dry_run:
print("Would have added the Job")
print(job)
print("to the database to be executed in the grid with options:", str(kwargs))
self.session.delete(job)
logger.info("Deleted job '%s' from the database due to dry-run option" % job)
job_id = None
else:
job_id = self._submit_to_grid(job, name, array, dependencies, log_dir, verbosity, **kwargs)
self.session.commit()
self.unlock()
return job_id | python | def submit(self, command_line, name = None, array = None, dependencies = [], exec_dir = None, log_dir = "logs", dry_run = False, verbosity = 0, stop_on_failure = False, **kwargs):
"""Submits a job that will be executed in the grid."""
# add job to database
self.lock()
job = add_job(self.session, command_line, name, dependencies, array, exec_dir=exec_dir, log_dir=log_dir, stop_on_failure=stop_on_failure, context=self.context, **kwargs)
logger.info("Added job '%s' to the database." % job)
if dry_run:
print("Would have added the Job")
print(job)
print("to the database to be executed in the grid with options:", str(kwargs))
self.session.delete(job)
logger.info("Deleted job '%s' from the database due to dry-run option" % job)
job_id = None
else:
job_id = self._submit_to_grid(job, name, array, dependencies, log_dir, verbosity, **kwargs)
self.session.commit()
self.unlock()
return job_id | [
"def",
"submit",
"(",
"self",
",",
"command_line",
",",
"name",
"=",
"None",
",",
"array",
"=",
"None",
",",
"dependencies",
"=",
"[",
"]",
",",
"exec_dir",
"=",
"None",
",",
"log_dir",
"=",
"\"logs\"",
",",
"dry_run",
"=",
"False",
",",
"verbosity",
... | Submits a job that will be executed in the grid. | [
"Submits",
"a",
"job",
"that",
"will",
"be",
"executed",
"in",
"the",
"grid",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/sge.py#L92-L112 |
bioidiap/gridtk | gridtk/sge.py | JobManagerSGE.communicate | def communicate(self, job_ids = None):
"""Communicates with the SGE grid (using qstat) to see if jobs are still running."""
self.lock()
# iterate over all jobs
jobs = self.get_jobs(job_ids)
for job in jobs:
job.refresh()
if job.status in ('queued', 'executing', 'waiting') and job.queue_name != 'local':
status = qstat(job.id, context=self.context)
if len(status) == 0:
job.status = 'failure'
job.result = 70 # ASCII: 'F'
logger.warn("The job '%s' was not executed successfully (maybe a time-out happened). Please check the log files." % job)
for array_job in job.array:
if array_job.status in ('queued', 'executing'):
array_job.status = 'failure'
array_job.result = 70 # ASCII: 'F'
self.session.commit()
self.unlock() | python | def communicate(self, job_ids = None):
"""Communicates with the SGE grid (using qstat) to see if jobs are still running."""
self.lock()
# iterate over all jobs
jobs = self.get_jobs(job_ids)
for job in jobs:
job.refresh()
if job.status in ('queued', 'executing', 'waiting') and job.queue_name != 'local':
status = qstat(job.id, context=self.context)
if len(status) == 0:
job.status = 'failure'
job.result = 70 # ASCII: 'F'
logger.warn("The job '%s' was not executed successfully (maybe a time-out happened). Please check the log files." % job)
for array_job in job.array:
if array_job.status in ('queued', 'executing'):
array_job.status = 'failure'
array_job.result = 70 # ASCII: 'F'
self.session.commit()
self.unlock() | [
"def",
"communicate",
"(",
"self",
",",
"job_ids",
"=",
"None",
")",
":",
"self",
".",
"lock",
"(",
")",
"# iterate over all jobs",
"jobs",
"=",
"self",
".",
"get_jobs",
"(",
"job_ids",
")",
"for",
"job",
"in",
"jobs",
":",
"job",
".",
"refresh",
"(",
... | Communicates with the SGE grid (using qstat) to see if jobs are still running. | [
"Communicates",
"with",
"the",
"SGE",
"grid",
"(",
"using",
"qstat",
")",
"to",
"see",
"if",
"jobs",
"are",
"still",
"running",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/sge.py#L115-L135 |
bioidiap/gridtk | gridtk/sge.py | JobManagerSGE.resubmit | def resubmit(self, job_ids = None, also_success = False, running_jobs = False, new_command=None, verbosity=0, keep_logs=False, **kwargs):
"""Re-submit jobs automatically"""
self.lock()
# iterate over all jobs
jobs = self.get_jobs(job_ids)
if new_command is not None:
if len(jobs) == 1:
jobs[0].set_command_line(new_command)
else:
logger.warn("Ignoring new command since no single job id was specified")
accepted_old_status = ('submitted', 'success', 'failure') if also_success else ('submitted', 'failure',)
for job in jobs:
# check if this job needs re-submission
if running_jobs or job.status in accepted_old_status:
grid_status = qstat(job.id, context=self.context)
if len(grid_status) != 0:
logger.warn("Deleting job '%d' since it was still running in the grid." % job.unique)
qdel(job.id, context=self.context)
# re-submit job to the grid
arguments = job.get_arguments()
arguments.update(**kwargs)
if ('queue' not in arguments or arguments['queue'] == 'all.q'):
for arg in ('hvmem', 'pe_opt', 'io_big'):
if arg in arguments:
del arguments[arg]
job.set_arguments(kwargs=arguments)
# delete old status and result of the job
if not keep_logs:
self.delete_logs(job)
job.submit()
if job.queue_name == 'local' and 'queue' not in arguments:
logger.warn("Re-submitting job '%s' locally (since no queue name is specified)." % job)
else:
deps = [dep.unique for dep in job.get_jobs_we_wait_for()]
logger.debug("Re-submitting job '%s' with dependencies '%s' to the grid." % (job, deps))
self._submit_to_grid(job, job.name, job.get_array(), deps, job.log_dir, verbosity, **arguments)
# commit after each job to avoid failures of not finding the job during execution in the grid
self.session.commit()
self.unlock() | python | def resubmit(self, job_ids = None, also_success = False, running_jobs = False, new_command=None, verbosity=0, keep_logs=False, **kwargs):
"""Re-submit jobs automatically"""
self.lock()
# iterate over all jobs
jobs = self.get_jobs(job_ids)
if new_command is not None:
if len(jobs) == 1:
jobs[0].set_command_line(new_command)
else:
logger.warn("Ignoring new command since no single job id was specified")
accepted_old_status = ('submitted', 'success', 'failure') if also_success else ('submitted', 'failure',)
for job in jobs:
# check if this job needs re-submission
if running_jobs or job.status in accepted_old_status:
grid_status = qstat(job.id, context=self.context)
if len(grid_status) != 0:
logger.warn("Deleting job '%d' since it was still running in the grid." % job.unique)
qdel(job.id, context=self.context)
# re-submit job to the grid
arguments = job.get_arguments()
arguments.update(**kwargs)
if ('queue' not in arguments or arguments['queue'] == 'all.q'):
for arg in ('hvmem', 'pe_opt', 'io_big'):
if arg in arguments:
del arguments[arg]
job.set_arguments(kwargs=arguments)
# delete old status and result of the job
if not keep_logs:
self.delete_logs(job)
job.submit()
if job.queue_name == 'local' and 'queue' not in arguments:
logger.warn("Re-submitting job '%s' locally (since no queue name is specified)." % job)
else:
deps = [dep.unique for dep in job.get_jobs_we_wait_for()]
logger.debug("Re-submitting job '%s' with dependencies '%s' to the grid." % (job, deps))
self._submit_to_grid(job, job.name, job.get_array(), deps, job.log_dir, verbosity, **arguments)
# commit after each job to avoid failures of not finding the job during execution in the grid
self.session.commit()
self.unlock() | [
"def",
"resubmit",
"(",
"self",
",",
"job_ids",
"=",
"None",
",",
"also_success",
"=",
"False",
",",
"running_jobs",
"=",
"False",
",",
"new_command",
"=",
"None",
",",
"verbosity",
"=",
"0",
",",
"keep_logs",
"=",
"False",
",",
"*",
"*",
"kwargs",
")"... | Re-submit jobs automatically | [
"Re",
"-",
"submit",
"jobs",
"automatically"
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/sge.py#L138-L177 |
bioidiap/gridtk | gridtk/sge.py | JobManagerSGE.run_job | def run_job(self, job_id, array_id = None):
"""Overwrites the run-job command from the manager to extract the correct job id before calling base class implementation."""
# get the unique job id from the given grid id
self.lock()
jobs = list(self.session.query(Job).filter(Job.id == job_id))
if len(jobs) != 1:
self.unlock()
raise ValueError("Could not find job id '%d' in the database'" % job_id)
job_id = jobs[0].unique
self.unlock()
# call base class implementation with the corrected job id
return JobManager.run_job(self, job_id, array_id) | python | def run_job(self, job_id, array_id = None):
"""Overwrites the run-job command from the manager to extract the correct job id before calling base class implementation."""
# get the unique job id from the given grid id
self.lock()
jobs = list(self.session.query(Job).filter(Job.id == job_id))
if len(jobs) != 1:
self.unlock()
raise ValueError("Could not find job id '%d' in the database'" % job_id)
job_id = jobs[0].unique
self.unlock()
# call base class implementation with the corrected job id
return JobManager.run_job(self, job_id, array_id) | [
"def",
"run_job",
"(",
"self",
",",
"job_id",
",",
"array_id",
"=",
"None",
")",
":",
"# get the unique job id from the given grid id",
"self",
".",
"lock",
"(",
")",
"jobs",
"=",
"list",
"(",
"self",
".",
"session",
".",
"query",
"(",
"Job",
")",
".",
"... | Overwrites the run-job command from the manager to extract the correct job id before calling base class implementation. | [
"Overwrites",
"the",
"run",
"-",
"job",
"command",
"from",
"the",
"manager",
"to",
"extract",
"the",
"correct",
"job",
"id",
"before",
"calling",
"base",
"class",
"implementation",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/sge.py#L180-L191 |
bioidiap/gridtk | gridtk/sge.py | JobManagerSGE.stop_jobs | def stop_jobs(self, job_ids):
"""Stops the jobs in the grid."""
self.lock()
jobs = self.get_jobs(job_ids)
for job in jobs:
if job.status in ('executing', 'queued', 'waiting'):
qdel(job.id, context=self.context)
logger.info("Stopped job '%s' in the SGE grid." % job)
job.submit()
self.session.commit()
self.unlock() | python | def stop_jobs(self, job_ids):
"""Stops the jobs in the grid."""
self.lock()
jobs = self.get_jobs(job_ids)
for job in jobs:
if job.status in ('executing', 'queued', 'waiting'):
qdel(job.id, context=self.context)
logger.info("Stopped job '%s' in the SGE grid." % job)
job.submit()
self.session.commit()
self.unlock() | [
"def",
"stop_jobs",
"(",
"self",
",",
"job_ids",
")",
":",
"self",
".",
"lock",
"(",
")",
"jobs",
"=",
"self",
".",
"get_jobs",
"(",
"job_ids",
")",
"for",
"job",
"in",
"jobs",
":",
"if",
"job",
".",
"status",
"in",
"(",
"'executing'",
",",
"'queue... | Stops the jobs in the grid. | [
"Stops",
"the",
"jobs",
"in",
"the",
"grid",
"."
] | train | https://github.com/bioidiap/gridtk/blob/9e3291b8b50388682908927231b2730db1da147d/gridtk/sge.py#L194-L206 |
duniter/duniter-python-api | duniterpy/key/encryption_key.py | SecretKey.encrypt | def encrypt(self, pubkey: str, nonce: Union[str, bytes], text: Union[str, bytes]) -> str:
"""
Encrypt message text with the public key of the recipient and a nonce
The nonce must be a 24 character string (you can use libnacl.utils.rand_nonce() to get one)
and unique for each encrypted message.
Return base58 encoded encrypted message
:param pubkey: Base58 encoded public key of the recipient
:param nonce: Unique nonce
:param text: Message to encrypt
:return:
"""
text_bytes = ensure_bytes(text)
nonce_bytes = ensure_bytes(nonce)
recipient_pubkey = PublicKey(pubkey)
crypt_bytes = libnacl.public.Box(self, recipient_pubkey).encrypt(text_bytes, nonce_bytes)
return Base58Encoder.encode(crypt_bytes[24:]) | python | def encrypt(self, pubkey: str, nonce: Union[str, bytes], text: Union[str, bytes]) -> str:
"""
Encrypt message text with the public key of the recipient and a nonce
The nonce must be a 24 character string (you can use libnacl.utils.rand_nonce() to get one)
and unique for each encrypted message.
Return base58 encoded encrypted message
:param pubkey: Base58 encoded public key of the recipient
:param nonce: Unique nonce
:param text: Message to encrypt
:return:
"""
text_bytes = ensure_bytes(text)
nonce_bytes = ensure_bytes(nonce)
recipient_pubkey = PublicKey(pubkey)
crypt_bytes = libnacl.public.Box(self, recipient_pubkey).encrypt(text_bytes, nonce_bytes)
return Base58Encoder.encode(crypt_bytes[24:]) | [
"def",
"encrypt",
"(",
"self",
",",
"pubkey",
":",
"str",
",",
"nonce",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"text",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"str",
":",
"text_bytes",
"=",
"ensure_bytes",
"(",
"text",
... | Encrypt message text with the public key of the recipient and a nonce
The nonce must be a 24 character string (you can use libnacl.utils.rand_nonce() to get one)
and unique for each encrypted message.
Return base58 encoded encrypted message
:param pubkey: Base58 encoded public key of the recipient
:param nonce: Unique nonce
:param text: Message to encrypt
:return: | [
"Encrypt",
"message",
"text",
"with",
"the",
"public",
"key",
"of",
"the",
"recipient",
"and",
"a",
"nonce"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/encryption_key.py#L40-L58 |
duniter/duniter-python-api | duniterpy/key/encryption_key.py | SecretKey.decrypt | def decrypt(self, pubkey: str, nonce: Union[str, bytes], text: str) -> str:
"""
Decrypt encrypted message text with recipient public key and the unique nonce used by the sender.
:param pubkey: Public key of the recipient
:param nonce: Unique nonce used by the sender
:param text: Encrypted message
:return:
"""
sender_pubkey = PublicKey(pubkey)
nonce_bytes = ensure_bytes(nonce)
encrypt_bytes = Base58Encoder.decode(text)
decrypt_bytes = libnacl.public.Box(self, sender_pubkey).decrypt(encrypt_bytes, nonce_bytes)
return decrypt_bytes.decode('utf-8') | python | def decrypt(self, pubkey: str, nonce: Union[str, bytes], text: str) -> str:
"""
Decrypt encrypted message text with recipient public key and the unique nonce used by the sender.
:param pubkey: Public key of the recipient
:param nonce: Unique nonce used by the sender
:param text: Encrypted message
:return:
"""
sender_pubkey = PublicKey(pubkey)
nonce_bytes = ensure_bytes(nonce)
encrypt_bytes = Base58Encoder.decode(text)
decrypt_bytes = libnacl.public.Box(self, sender_pubkey).decrypt(encrypt_bytes, nonce_bytes)
return decrypt_bytes.decode('utf-8') | [
"def",
"decrypt",
"(",
"self",
",",
"pubkey",
":",
"str",
",",
"nonce",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
",",
"text",
":",
"str",
")",
"->",
"str",
":",
"sender_pubkey",
"=",
"PublicKey",
"(",
"pubkey",
")",
"nonce_bytes",
"=",
"ensure_by... | Decrypt encrypted message text with recipient public key and the unique nonce used by the sender.
:param pubkey: Public key of the recipient
:param nonce: Unique nonce used by the sender
:param text: Encrypted message
:return: | [
"Decrypt",
"encrypted",
"message",
"text",
"with",
"recipient",
"public",
"key",
"and",
"the",
"unique",
"nonce",
"used",
"by",
"the",
"sender",
"."
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/encryption_key.py#L60-L73 |
duniter/duniter-python-api | duniterpy/key/encryption_key.py | PublicKey.encrypt_seal | def encrypt_seal(self, data: Union[str, bytes]) -> bytes:
"""
Encrypt data with a curve25519 version of the ed25519 public key
:param data: Bytes data to encrypt
"""
curve25519_public_key = libnacl.crypto_sign_ed25519_pk_to_curve25519(self.pk)
return libnacl.crypto_box_seal(ensure_bytes(data), curve25519_public_key) | python | def encrypt_seal(self, data: Union[str, bytes]) -> bytes:
"""
Encrypt data with a curve25519 version of the ed25519 public key
:param data: Bytes data to encrypt
"""
curve25519_public_key = libnacl.crypto_sign_ed25519_pk_to_curve25519(self.pk)
return libnacl.crypto_box_seal(ensure_bytes(data), curve25519_public_key) | [
"def",
"encrypt_seal",
"(",
"self",
",",
"data",
":",
"Union",
"[",
"str",
",",
"bytes",
"]",
")",
"->",
"bytes",
":",
"curve25519_public_key",
"=",
"libnacl",
".",
"crypto_sign_ed25519_pk_to_curve25519",
"(",
"self",
".",
"pk",
")",
"return",
"libnacl",
"."... | Encrypt data with a curve25519 version of the ed25519 public key
:param data: Bytes data to encrypt | [
"Encrypt",
"data",
"with",
"a",
"curve25519",
"version",
"of",
"the",
"ed25519",
"public",
"key"
] | train | https://github.com/duniter/duniter-python-api/blob/3a1e5d61a2f72f5afaf29d010c6cf4dff3648165/duniterpy/key/encryption_key.py#L92-L99 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.override_default_templates | def override_default_templates(self):
"""
Override the default emails already defined by other apps
"""
if plugs_mail_settings['OVERRIDE_TEMPLATE_DIR']:
dir_ = plugs_mail_settings['OVERRIDE_TEMPLATE_DIR']
for file_ in os.listdir(dir_):
if file_.endswith(('.html', 'txt')):
self.overrides[file_] = dir_ | python | def override_default_templates(self):
"""
Override the default emails already defined by other apps
"""
if plugs_mail_settings['OVERRIDE_TEMPLATE_DIR']:
dir_ = plugs_mail_settings['OVERRIDE_TEMPLATE_DIR']
for file_ in os.listdir(dir_):
if file_.endswith(('.html', 'txt')):
self.overrides[file_] = dir_ | [
"def",
"override_default_templates",
"(",
"self",
")",
":",
"if",
"plugs_mail_settings",
"[",
"'OVERRIDE_TEMPLATE_DIR'",
"]",
":",
"dir_",
"=",
"plugs_mail_settings",
"[",
"'OVERRIDE_TEMPLATE_DIR'",
"]",
"for",
"file_",
"in",
"os",
".",
"listdir",
"(",
"dir_",
")"... | Override the default emails already defined by other apps | [
"Override",
"the",
"default",
"emails",
"already",
"defined",
"by",
"other",
"apps"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L29-L37 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.get_apps | def get_apps(self):
"""
Get the list of installed apps
and return the apps that have
an emails module
"""
templates = []
for app in settings.INSTALLED_APPS:
try:
app = import_module(app + '.emails')
templates += self.get_plugs_mail_classes(app)
except ImportError:
pass
return templates | python | def get_apps(self):
"""
Get the list of installed apps
and return the apps that have
an emails module
"""
templates = []
for app in settings.INSTALLED_APPS:
try:
app = import_module(app + '.emails')
templates += self.get_plugs_mail_classes(app)
except ImportError:
pass
return templates | [
"def",
"get_apps",
"(",
"self",
")",
":",
"templates",
"=",
"[",
"]",
"for",
"app",
"in",
"settings",
".",
"INSTALLED_APPS",
":",
"try",
":",
"app",
"=",
"import_module",
"(",
"app",
"+",
"'.emails'",
")",
"templates",
"+=",
"self",
".",
"get_plugs_mail_... | Get the list of installed apps
and return the apps that have
an emails module | [
"Get",
"the",
"list",
"of",
"installed",
"apps",
"and",
"return",
"the",
"apps",
"that",
"have",
"an",
"emails",
"module"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L39-L52 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.get_template_files | def get_template_files(self, location, class_name):
"""
Multilanguage support means that for each template
we can have multiple templtate files, this methods
returns all the template (html and txt) files
that match the (class) template name
"""
template_name = utils.camel_to_snake(class_name)
dir_ = location[:-9] + 'templates/emails/'
files_ = []
for file_ in self.get_templates_files_in_dir(dir_):
if file_.startswith(template_name) and file_.endswith(('.html', '.txt')):
if file_ in self.overrides:
files_.append(self.overrides[file_] + file_)
else:
files_.append(dir_ + file_)
return files_ | python | def get_template_files(self, location, class_name):
"""
Multilanguage support means that for each template
we can have multiple templtate files, this methods
returns all the template (html and txt) files
that match the (class) template name
"""
template_name = utils.camel_to_snake(class_name)
dir_ = location[:-9] + 'templates/emails/'
files_ = []
for file_ in self.get_templates_files_in_dir(dir_):
if file_.startswith(template_name) and file_.endswith(('.html', '.txt')):
if file_ in self.overrides:
files_.append(self.overrides[file_] + file_)
else:
files_.append(dir_ + file_)
return files_ | [
"def",
"get_template_files",
"(",
"self",
",",
"location",
",",
"class_name",
")",
":",
"template_name",
"=",
"utils",
".",
"camel_to_snake",
"(",
"class_name",
")",
"dir_",
"=",
"location",
"[",
":",
"-",
"9",
"]",
"+",
"'templates/emails/'",
"files_",
"=",... | Multilanguage support means that for each template
we can have multiple templtate files, this methods
returns all the template (html and txt) files
that match the (class) template name | [
"Multilanguage",
"support",
"means",
"that",
"for",
"each",
"template",
"we",
"can",
"have",
"multiple",
"templtate",
"files",
"this",
"methods",
"returns",
"all",
"the",
"template",
"(",
"html",
"and",
"txt",
")",
"files",
"that",
"match",
"the",
"(",
"clas... | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L60-L76 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.get_plugs_mail_classes | def get_plugs_mail_classes(self, app):
"""
Returns a list of tuples, but it should
return a list of dicts
"""
classes = []
members = self.get_members(app)
for member in members:
name, cls = member
if inspect.isclass(cls) and issubclass(cls, PlugsMail) and name != 'PlugsMail':
files_ = self.get_template_files(app.__file__, name)
for file_ in files_:
try:
description = cls.description
location = file_
language = self.get_template_language(location)
classes.append((name, location, description, language))
except AttributeError:
raise AttributeError('Email class must specify email description.')
return classes | python | def get_plugs_mail_classes(self, app):
"""
Returns a list of tuples, but it should
return a list of dicts
"""
classes = []
members = self.get_members(app)
for member in members:
name, cls = member
if inspect.isclass(cls) and issubclass(cls, PlugsMail) and name != 'PlugsMail':
files_ = self.get_template_files(app.__file__, name)
for file_ in files_:
try:
description = cls.description
location = file_
language = self.get_template_language(location)
classes.append((name, location, description, language))
except AttributeError:
raise AttributeError('Email class must specify email description.')
return classes | [
"def",
"get_plugs_mail_classes",
"(",
"self",
",",
"app",
")",
":",
"classes",
"=",
"[",
"]",
"members",
"=",
"self",
".",
"get_members",
"(",
"app",
")",
"for",
"member",
"in",
"members",
":",
"name",
",",
"cls",
"=",
"member",
"if",
"inspect",
".",
... | Returns a list of tuples, but it should
return a list of dicts | [
"Returns",
"a",
"list",
"of",
"tuples",
"but",
"it",
"should",
"return",
"a",
"list",
"of",
"dicts"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L78-L97 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.get_template_language | def get_template_language(self, file_):
"""
Return the template language
Every template file must end in
with the language code, and the
code must match the ISO_6301 lang code
https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
valid examples:
account_created_pt.html
payment_created_en.txt
"""
stem = Path(file_).stem
language_code = stem.split('_')[-1:][0]
if len(language_code) != 2:
# TODO naive and temp implementation
# check if the two chars correspond to one of the
# available languages
raise Exception('Template file `%s` must end in ISO_639-1 language code.' % file_)
return language_code.lower() | python | def get_template_language(self, file_):
"""
Return the template language
Every template file must end in
with the language code, and the
code must match the ISO_6301 lang code
https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
valid examples:
account_created_pt.html
payment_created_en.txt
"""
stem = Path(file_).stem
language_code = stem.split('_')[-1:][0]
if len(language_code) != 2:
# TODO naive and temp implementation
# check if the two chars correspond to one of the
# available languages
raise Exception('Template file `%s` must end in ISO_639-1 language code.' % file_)
return language_code.lower() | [
"def",
"get_template_language",
"(",
"self",
",",
"file_",
")",
":",
"stem",
"=",
"Path",
"(",
"file_",
")",
".",
"stem",
"language_code",
"=",
"stem",
".",
"split",
"(",
"'_'",
")",
"[",
"-",
"1",
":",
"]",
"[",
"0",
"]",
"if",
"len",
"(",
"lang... | Return the template language
Every template file must end in
with the language code, and the
code must match the ISO_6301 lang code
https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
valid examples:
account_created_pt.html
payment_created_en.txt | [
"Return",
"the",
"template",
"language",
"Every",
"template",
"file",
"must",
"end",
"in",
"with",
"the",
"language",
"code",
"and",
"the",
"code",
"must",
"match",
"the",
"ISO_6301",
"lang",
"code",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
... | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L99-L118 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.get_subject | def get_subject(self, text):
"""
Email template subject is the first
line of the email template, we can optionally
add SUBJECT: to make it clearer
"""
first_line = text.splitlines(True)[0]
# TODO second line should be empty
if first_line.startswith('SUBJECT:'):
subject = first_line[len('SUBJECT:'):]
else:
subject = first_line
return subject.strip() | python | def get_subject(self, text):
"""
Email template subject is the first
line of the email template, we can optionally
add SUBJECT: to make it clearer
"""
first_line = text.splitlines(True)[0]
# TODO second line should be empty
if first_line.startswith('SUBJECT:'):
subject = first_line[len('SUBJECT:'):]
else:
subject = first_line
return subject.strip() | [
"def",
"get_subject",
"(",
"self",
",",
"text",
")",
":",
"first_line",
"=",
"text",
".",
"splitlines",
"(",
"True",
")",
"[",
"0",
"]",
"# TODO second line should be empty",
"if",
"first_line",
".",
"startswith",
"(",
"'SUBJECT:'",
")",
":",
"subject",
"=",... | Email template subject is the first
line of the email template, we can optionally
add SUBJECT: to make it clearer | [
"Email",
"template",
"subject",
"is",
"the",
"first",
"line",
"of",
"the",
"email",
"template",
"we",
"can",
"optionally",
"add",
"SUBJECT",
":",
"to",
"make",
"it",
"clearer"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L120-L132 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.create_templates | def create_templates(self, templates):
"""
Gets a list of templates to insert into the database
"""
count = 0
for template in templates:
if not self.template_exists_db(template):
name, location, description, language = template
text = self.open_file(location)
html_content = self.get_html_content(text)
data = {
'name': utils.camel_to_snake(name).upper(),
'html_content': html_content,
'content': self.text_version(html_content),
'subject': self.get_subject(text),
'description': description,
'language': language
}
if models.EmailTemplate.objects.create(**data):
count += 1
return count | python | def create_templates(self, templates):
"""
Gets a list of templates to insert into the database
"""
count = 0
for template in templates:
if not self.template_exists_db(template):
name, location, description, language = template
text = self.open_file(location)
html_content = self.get_html_content(text)
data = {
'name': utils.camel_to_snake(name).upper(),
'html_content': html_content,
'content': self.text_version(html_content),
'subject': self.get_subject(text),
'description': description,
'language': language
}
if models.EmailTemplate.objects.create(**data):
count += 1
return count | [
"def",
"create_templates",
"(",
"self",
",",
"templates",
")",
":",
"count",
"=",
"0",
"for",
"template",
"in",
"templates",
":",
"if",
"not",
"self",
".",
"template_exists_db",
"(",
"template",
")",
":",
"name",
",",
"location",
",",
"description",
",",
... | Gets a list of templates to insert into the database | [
"Gets",
"a",
"list",
"of",
"templates",
"to",
"insert",
"into",
"the",
"database"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L141-L161 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.open_file | def open_file(self, file_):
"""
Receives a file path has input and returns a
string with the contents of the file
"""
with open(file_, 'r', encoding='utf-8') as file:
text = ''
for line in file:
text += line
return text | python | def open_file(self, file_):
"""
Receives a file path has input and returns a
string with the contents of the file
"""
with open(file_, 'r', encoding='utf-8') as file:
text = ''
for line in file:
text += line
return text | [
"def",
"open_file",
"(",
"self",
",",
"file_",
")",
":",
"with",
"open",
"(",
"file_",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"file",
":",
"text",
"=",
"''",
"for",
"line",
"in",
"file",
":",
"text",
"+=",
"line",
"return",
"text"
... | Receives a file path has input and returns a
string with the contents of the file | [
"Receives",
"a",
"file",
"path",
"has",
"input",
"and",
"returns",
"a",
"string",
"with",
"the",
"contents",
"of",
"the",
"file"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L171-L180 |
solocompt/plugs-mail | plugs_mail/management/commands/load_email_templates.py | Command.template_exists_db | def template_exists_db(self, template):
"""
Receives a template and checks if it exists in the database
using the template name and language
"""
name = utils.camel_to_snake(template[0]).upper()
language = utils.camel_to_snake(template[3])
try:
models.EmailTemplate.objects.get(name=name, language=language)
except models.EmailTemplate.DoesNotExist:
return False
return True | python | def template_exists_db(self, template):
"""
Receives a template and checks if it exists in the database
using the template name and language
"""
name = utils.camel_to_snake(template[0]).upper()
language = utils.camel_to_snake(template[3])
try:
models.EmailTemplate.objects.get(name=name, language=language)
except models.EmailTemplate.DoesNotExist:
return False
return True | [
"def",
"template_exists_db",
"(",
"self",
",",
"template",
")",
":",
"name",
"=",
"utils",
".",
"camel_to_snake",
"(",
"template",
"[",
"0",
"]",
")",
".",
"upper",
"(",
")",
"language",
"=",
"utils",
".",
"camel_to_snake",
"(",
"template",
"[",
"3",
"... | Receives a template and checks if it exists in the database
using the template name and language | [
"Receives",
"a",
"template",
"and",
"checks",
"if",
"it",
"exists",
"in",
"the",
"database",
"using",
"the",
"template",
"name",
"and",
"language"
] | train | https://github.com/solocompt/plugs-mail/blob/6139fa79ddb437562db1769d03bd3098c25a06fa/plugs_mail/management/commands/load_email_templates.py#L183-L194 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | PathFinder2.invalidate_caches | def invalidate_caches(cls):
"""Call the invalidate_caches() method on all path entry finders
stored in sys.path_importer_caches (where implemented)."""
for finder in sys.path_importer_cache.values():
if hasattr(finder, 'invalidate_caches'):
finder.invalidate_caches() | python | def invalidate_caches(cls):
"""Call the invalidate_caches() method on all path entry finders
stored in sys.path_importer_caches (where implemented)."""
for finder in sys.path_importer_cache.values():
if hasattr(finder, 'invalidate_caches'):
finder.invalidate_caches() | [
"def",
"invalidate_caches",
"(",
"cls",
")",
":",
"for",
"finder",
"in",
"sys",
".",
"path_importer_cache",
".",
"values",
"(",
")",
":",
"if",
"hasattr",
"(",
"finder",
",",
"'invalidate_caches'",
")",
":",
"finder",
".",
"invalidate_caches",
"(",
")"
] | Call the invalidate_caches() method on all path entry finders
stored in sys.path_importer_caches (where implemented). | [
"Call",
"the",
"invalidate_caches",
"()",
"method",
"on",
"all",
"path",
"entry",
"finders",
"stored",
"in",
"sys",
".",
"path_importer_caches",
"(",
"where",
"implemented",
")",
"."
] | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L38-L43 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | PathFinder2._path_hooks | def _path_hooks(cls, path): # from importlib.PathFinder
"""Search sys.path_hooks for a finder for 'path'."""
if sys.path_hooks is not None and not sys.path_hooks:
warnings.warn('sys.path_hooks is empty', ImportWarning)
for hook in sys.path_hooks:
try:
return hook(path)
except ImportError:
continue
else:
return None | python | def _path_hooks(cls, path): # from importlib.PathFinder
"""Search sys.path_hooks for a finder for 'path'."""
if sys.path_hooks is not None and not sys.path_hooks:
warnings.warn('sys.path_hooks is empty', ImportWarning)
for hook in sys.path_hooks:
try:
return hook(path)
except ImportError:
continue
else:
return None | [
"def",
"_path_hooks",
"(",
"cls",
",",
"path",
")",
":",
"# from importlib.PathFinder",
"if",
"sys",
".",
"path_hooks",
"is",
"not",
"None",
"and",
"not",
"sys",
".",
"path_hooks",
":",
"warnings",
".",
"warn",
"(",
"'sys.path_hooks is empty'",
",",
"ImportWar... | Search sys.path_hooks for a finder for 'path'. | [
"Search",
"sys",
".",
"path_hooks",
"for",
"a",
"finder",
"for",
"path",
"."
] | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L46-L56 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | PathFinder2._path_importer_cache | def _path_importer_cache(cls, path): # from importlib.PathFinder
"""Get the finder for the path entry from sys.path_importer_cache.
If the path entry is not in the cache, find the appropriate finder
and cache it. If no finder is available, store None.
"""
if path == '':
try:
path = os.getcwd()
except FileNotFoundError:
# Don't cache the failure as the cwd can easily change to
# a valid directory later on.
return None
try:
finder = sys.path_importer_cache[path]
except KeyError:
finder = cls._path_hooks(path)
sys.path_importer_cache[path] = finder
return finder | python | def _path_importer_cache(cls, path): # from importlib.PathFinder
"""Get the finder for the path entry from sys.path_importer_cache.
If the path entry is not in the cache, find the appropriate finder
and cache it. If no finder is available, store None.
"""
if path == '':
try:
path = os.getcwd()
except FileNotFoundError:
# Don't cache the failure as the cwd can easily change to
# a valid directory later on.
return None
try:
finder = sys.path_importer_cache[path]
except KeyError:
finder = cls._path_hooks(path)
sys.path_importer_cache[path] = finder
return finder | [
"def",
"_path_importer_cache",
"(",
"cls",
",",
"path",
")",
":",
"# from importlib.PathFinder",
"if",
"path",
"==",
"''",
":",
"try",
":",
"path",
"=",
"os",
".",
"getcwd",
"(",
")",
"except",
"FileNotFoundError",
":",
"# Don't cache the failure as the cwd can ea... | Get the finder for the path entry from sys.path_importer_cache.
If the path entry is not in the cache, find the appropriate finder
and cache it. If no finder is available, store None. | [
"Get",
"the",
"finder",
"for",
"the",
"path",
"entry",
"from",
"sys",
".",
"path_importer_cache",
".",
"If",
"the",
"path",
"entry",
"is",
"not",
"in",
"the",
"cache",
"find",
"the",
"appropriate",
"finder",
"and",
"cache",
"it",
".",
"If",
"no",
"finder... | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L59-L77 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | PathFinder2._get_spec | def _get_spec(cls, fullname, path, target=None):
"""Find the loader or namespace_path for this module/package name."""
# If this ends up being a namespace package, namespace_path is
# the list of paths that will become its __path__
namespace_path = []
for entry in path:
if not isinstance(entry, (str, bytes)):
continue
finder = cls._path_importer_cache(entry)
if finder is not None:
if hasattr(finder, 'find_spec'):
spec = finder.find_spec(fullname, target)
else:
spec = cls._legacy_get_spec(fullname, finder)
if spec is None:
continue
if spec.loader is not None:
return spec
portions = spec.submodule_search_locations
if portions is None:
raise ImportError('spec missing loader')
# This is possibly part of a namespace package.
# Remember these path entries (if any) for when we
# create a namespace package, and continue iterating
# on path.
namespace_path.extend(portions)
else:
spec = ModuleSpec(fullname, None)
spec.submodule_search_locations = namespace_path
return spec | python | def _get_spec(cls, fullname, path, target=None):
"""Find the loader or namespace_path for this module/package name."""
# If this ends up being a namespace package, namespace_path is
# the list of paths that will become its __path__
namespace_path = []
for entry in path:
if not isinstance(entry, (str, bytes)):
continue
finder = cls._path_importer_cache(entry)
if finder is not None:
if hasattr(finder, 'find_spec'):
spec = finder.find_spec(fullname, target)
else:
spec = cls._legacy_get_spec(fullname, finder)
if spec is None:
continue
if spec.loader is not None:
return spec
portions = spec.submodule_search_locations
if portions is None:
raise ImportError('spec missing loader')
# This is possibly part of a namespace package.
# Remember these path entries (if any) for when we
# create a namespace package, and continue iterating
# on path.
namespace_path.extend(portions)
else:
spec = ModuleSpec(fullname, None)
spec.submodule_search_locations = namespace_path
return spec | [
"def",
"_get_spec",
"(",
"cls",
",",
"fullname",
",",
"path",
",",
"target",
"=",
"None",
")",
":",
"# If this ends up being a namespace package, namespace_path is",
"# the list of paths that will become its __path__",
"namespace_path",
"=",
"[",
"]",
"for",
"entry",
"in... | Find the loader or namespace_path for this module/package name. | [
"Find",
"the",
"loader",
"or",
"namespace_path",
"for",
"this",
"module",
"/",
"package",
"name",
"."
] | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L95-L124 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | PathFinder2.find_module | def find_module(cls, fullname, path=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.
This method is for python2 only
"""
spec = cls.find_spec(fullname, path)
if spec is None:
return None
elif spec.loader is None and spec.submodule_search_locations:
# Here we need to create a namespace loader to handle namespaces since python2 doesn't...
return NamespaceLoader2(spec.name, spec.submodule_search_locations)
else:
return spec.loader | python | def find_module(cls, fullname, path=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.
This method is for python2 only
"""
spec = cls.find_spec(fullname, path)
if spec is None:
return None
elif spec.loader is None and spec.submodule_search_locations:
# Here we need to create a namespace loader to handle namespaces since python2 doesn't...
return NamespaceLoader2(spec.name, spec.submodule_search_locations)
else:
return spec.loader | [
"def",
"find_module",
"(",
"cls",
",",
"fullname",
",",
"path",
"=",
"None",
")",
":",
"spec",
"=",
"cls",
".",
"find_spec",
"(",
"fullname",
",",
"path",
")",
"if",
"spec",
"is",
"None",
":",
"return",
"None",
"elif",
"spec",
".",
"loader",
"is",
... | find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.
This method is for python2 only | [
"find",
"the",
"module",
"on",
"sys",
".",
"path",
"or",
"path",
"based",
"on",
"sys",
".",
"path_hooks",
"and",
"sys",
".",
"path_importer_cache",
".",
"This",
"method",
"is",
"for",
"python2",
"only"
] | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L127-L139 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | PathFinder2.find_spec | def find_spec(cls, fullname, path=None, target=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache."""
if path is None:
path = sys.path
spec = cls._get_spec(fullname, path, target)
if spec is None:
return None
elif spec.loader is None:
namespace_path = spec.submodule_search_locations
if namespace_path:
# We found at least one namespace path. Return a
# spec which can create the namespace package.
spec.origin = 'namespace'
spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)
return spec
else:
return None
else:
return spec | python | def find_spec(cls, fullname, path=None, target=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache."""
if path is None:
path = sys.path
spec = cls._get_spec(fullname, path, target)
if spec is None:
return None
elif spec.loader is None:
namespace_path = spec.submodule_search_locations
if namespace_path:
# We found at least one namespace path. Return a
# spec which can create the namespace package.
spec.origin = 'namespace'
spec.submodule_search_locations = _NamespacePath(fullname, namespace_path, cls._get_spec)
return spec
else:
return None
else:
return spec | [
"def",
"find_spec",
"(",
"cls",
",",
"fullname",
",",
"path",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"sys",
".",
"path",
"spec",
"=",
"cls",
".",
"_get_spec",
"(",
"fullname",
",",
"path",
... | find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache. | [
"find",
"the",
"module",
"on",
"sys",
".",
"path",
"or",
"path",
"based",
"on",
"sys",
".",
"path_hooks",
"and",
"sys",
".",
"path_importer_cache",
"."
] | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L142-L161 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | FileFinder2.find_spec | def find_spec(self, fullname, target=None):
"""Try to find a spec for the specified module. Returns the
matching spec, or None if not found."""
is_namespace = False
tail_module = fullname.rpartition('.')[2]
base_path = os.path.join(self.path, tail_module)
for suffix, loader_class in self._loaders:
init_filename = '__init__' + suffix
init_full_path = os.path.join(base_path, init_filename)
full_path = base_path + suffix
if os.path.isfile(init_full_path):
return self._get_spec(loader_class, fullname, init_full_path, [base_path], target)
if os.path.isfile(full_path): # maybe we need more checks here (importlib filefinder checks its cache...)
return self._get_spec(loader_class, fullname, full_path, None, target)
else:
# If a namespace package, return the path if we don't
# find a module in the next section.
is_namespace = os.path.isdir(base_path)
if is_namespace:
_verbose_message('possible namespace for {}'.format(base_path))
spec = ModuleSpec(fullname, None)
spec.submodule_search_locations = [base_path]
return spec
return None | python | def find_spec(self, fullname, target=None):
"""Try to find a spec for the specified module. Returns the
matching spec, or None if not found."""
is_namespace = False
tail_module = fullname.rpartition('.')[2]
base_path = os.path.join(self.path, tail_module)
for suffix, loader_class in self._loaders:
init_filename = '__init__' + suffix
init_full_path = os.path.join(base_path, init_filename)
full_path = base_path + suffix
if os.path.isfile(init_full_path):
return self._get_spec(loader_class, fullname, init_full_path, [base_path], target)
if os.path.isfile(full_path): # maybe we need more checks here (importlib filefinder checks its cache...)
return self._get_spec(loader_class, fullname, full_path, None, target)
else:
# If a namespace package, return the path if we don't
# find a module in the next section.
is_namespace = os.path.isdir(base_path)
if is_namespace:
_verbose_message('possible namespace for {}'.format(base_path))
spec = ModuleSpec(fullname, None)
spec.submodule_search_locations = [base_path]
return spec
return None | [
"def",
"find_spec",
"(",
"self",
",",
"fullname",
",",
"target",
"=",
"None",
")",
":",
"is_namespace",
"=",
"False",
"tail_module",
"=",
"fullname",
".",
"rpartition",
"(",
"'.'",
")",
"[",
"2",
"]",
"base_path",
"=",
"os",
".",
"path",
".",
"join",
... | Try to find a spec for the specified module. Returns the
matching spec, or None if not found. | [
"Try",
"to",
"find",
"a",
"spec",
"for",
"the",
"specified",
"module",
".",
"Returns",
"the",
"matching",
"spec",
"or",
"None",
"if",
"not",
"found",
"."
] | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L210-L235 |
asmodehn/filefinder2 | filefinder2/_filefinder2.py | FileFinder2.find_loader | def find_loader(self, fullname):
"""Try to find a loader for the specified module, or the namespace
package portions. Returns (loader, list-of-portions).
This method is deprecated. Use find_spec() instead.
"""
spec = self.find_spec(fullname)
if spec is None:
return None, []
return spec.loader, spec.submodule_search_locations or [] | python | def find_loader(self, fullname):
"""Try to find a loader for the specified module, or the namespace
package portions. Returns (loader, list-of-portions).
This method is deprecated. Use find_spec() instead.
"""
spec = self.find_spec(fullname)
if spec is None:
return None, []
return spec.loader, spec.submodule_search_locations or [] | [
"def",
"find_loader",
"(",
"self",
",",
"fullname",
")",
":",
"spec",
"=",
"self",
".",
"find_spec",
"(",
"fullname",
")",
"if",
"spec",
"is",
"None",
":",
"return",
"None",
",",
"[",
"]",
"return",
"spec",
".",
"loader",
",",
"spec",
".",
"submodule... | Try to find a loader for the specified module, or the namespace
package portions. Returns (loader, list-of-portions).
This method is deprecated. Use find_spec() instead. | [
"Try",
"to",
"find",
"a",
"loader",
"for",
"the",
"specified",
"module",
"or",
"the",
"namespace",
"package",
"portions",
".",
"Returns",
"(",
"loader",
"list",
"-",
"of",
"-",
"portions",
")",
".",
"This",
"method",
"is",
"deprecated",
".",
"Use",
"find... | train | https://github.com/asmodehn/filefinder2/blob/3f0b211ce11a34562e2a2160e039ae5290b68d6b/filefinder2/_filefinder2.py#L254-L262 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.