content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def action_create(name, args):
"""create a llvmlab installation"""
import llvmlab
from optparse import OptionParser, OptionGroup
parser = OptionParser("%%prog %s [options] <path>" % name)
group = OptionGroup(parser, "CONFIG OPTIONS")
group.add_option("", "--admin-login", dest="admin_login",
help="administrator login [%default]", default='admin')
group.add_option("", "--admin-name", dest="admin_name",
help="administrator name [%default]",
default='Administrator')
group.add_option("", "--admin-password", dest="admin_password",
help="administrator password [%default]", default='admin')
group.add_option("", "--admin-email", dest="admin_email",
help="administrator email [%default]",
default='[email protected]')
group.add_option("", "--master-url", dest="master_url",
help="URL for the buildbot master [%default]",
default='http://lab.llvm.org:8013')
group.add_option("", "--plugin-module", dest="plugin_module",
help="name of the dashboard plugin to load [%default]",
default=None)
group.add_option("", "--debug-server", dest="debug_server",
help="run server in debug mode [%default]",
action="store_true", default=False)
parser.add_option_group(group)
(opts, args) = parser.parse_args(args)
if len(args) != 1:
parser.error("invalid number of arguments")
install_path, = args
install_path = os.path.abspath(install_path)
cfg_path = os.path.join(install_path, 'lab.cfg')
app_path = os.path.join(install_path, 'app.wsgi')
# Create the install directory.
if os.path.exists(install_path):
parser.error("refusing to install: %r exists" % install_path)
try:
os.mkdir(install_path)
except:
parser.error("unable to create directory: %r" % install_path)
# Construct the config file.
sample_cfg_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"lab.cfg.sample")
sample_cfg_file = open(sample_cfg_path, "rb")
sample_cfg_data = sample_cfg_file.read()
sample_cfg_file.close()
# Fill in the sample config.
secret_key = hashlib.sha1(str(random.getrandbits(256))).hexdigest()
cfg_options = dict(opts.__dict__)
cfg_options['admin_passhash'] = hashlib.sha256(
opts.admin_password + secret_key).hexdigest()
cfg_options['secret_key'] = secret_key
cfg_options['install_path'] = install_path
cfg_options['plugin_module'] = opts.plugin_module
cfg_data = sample_cfg_data % cfg_options
# Write the initial config file.
cfg_file = open(cfg_path, 'w')
cfg_file.write(cfg_data)
cfg_file.close()
# Construct the WSGI app file.
app_wsgi_path = os.path.join(os.path.abspath(os.path.dirname(__file__)),
"app.wsgi.sample")
app_wsgi_file = open(app_wsgi_path, "rb")
app_wsgi_data = app_wsgi_file.read()
app_wsgi_file.close()
# Fill in the sample WSGI app.
virtual_env = os.environ.get('VIRTUAL_ENV')
if virtual_env:
site_import_string = """
import site
site.addsitedir(%r)\n""" % virtual_env
else:
site_import_string = ""
app_data = app_wsgi_data % { 'site_import_string' : site_import_string,
'lab_config_path' : cfg_path }
app_file = open(app_path, 'w')
app_file.write(app_data)
app_file.close()
# Construct the initial database and status files.
data = llvmlab.data.Data(users = [], machines = [])
status = llvmlab.ci.status.Status(opts.master_url, {})
# Construct an app instance, and save the data.
instance = llvmlab.ui.app.App.create_standalone(data = data,
status = status,
config_path = cfg_path)
instance.save_data()
instance.save_status()
| 5,345,900 |
def convert_to_github_url_with_token(url, token):
"""
Convert a Github URL to a git+https url that identifies via an Oauth token. This allows for installation of
private packages.
:param url: The url to convert into a Github access token oauth url.
:param token: The Github access token to use for the oauth url.
:return: A git+https url with Oauth identification.
"""
for prefix in [GIT_SSH_PREFIX, GIT_GIT_PREFIX, GIT_HTTPS_PREFIX]:
if url.startswith(prefix):
return 'git+https://{}:[email protected]/{}'.format(token, url[len(prefix):])
return url
| 5,345,901 |
def test_owner_approval_apply_failed(test1_token, empty_device_apply_record, execute_sql):
"""
owner审批失败,不能审批其他owner的
:param test1_token:
:param empty_device_apply_record:
:param execute_sql:
:return:
"""
empty_device_apply_record(1, 1)
sql = """INSERT INTO device_apply_record VALUES (1, 1, 2, '2019-10-15 09:28:55', '2019-10-30 00:55:55', '测试需要', 1, NULL, NULL, NULL, NULL, 0, 0, '2019-10-15 16:16:48.399755', '2019-10-15 16:16:48.399755');
"""
execute_sql(sql)
data = {"approval": 1, "reason": "owner审批apply记录,失败"}
result = http_post(audit_url.format(apply_id=1), data=data, token=test1_token)
assert result.json()['code'] == 3007
assert result.json()['msg'] == "审批失败"
| 5,345,902 |
def get_numbers_of_papers(metrics):
"""
Convert the metrics into a format that is easier to work with. Year-ordered
numpy arrays.
"""
publications = metrics['histograms']['publications']
year, total, year_refereed, refereed = [], [], [], []
y = list(publications['all publications'].keys())
y.sort()
for i in range(len(y)):
k = y[i]
year.append(datetime.strptime(k, '%Y'))
total.append(publications['all publications'][k])
refereed.append(publications['refereed publications'][k])
year, total, refereed = \
numpy.array(year), numpy.array(total), numpy.array(refereed)
return year, total, refereed
| 5,345,903 |
def show_warning(parent, title, message):
""" Helper method for opening a simple yes/no dialog and getting the answer
"""
dialog = Gtk.MessageDialog(parent=parent, flags=0,
message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.OK, text=title)
dialog.format_secondary_text(message)
dialog.run()
dialog.destroy()
| 5,345,904 |
def test_base_provider_get_transform_json_exception(mock_name, mock_value):
"""
Test BaseProvider.get() with a json transform that raises an exception
"""
mock_data = json.dumps({mock_name: mock_value}) + "{"
class TestProvider(BaseProvider):
def _get(self, name: str, **kwargs) -> str:
assert name == mock_name
return mock_data
def _get_multiple(self, path: str, **kwargs) -> Dict[str, str]:
raise NotImplementedError()
provider = TestProvider()
with pytest.raises(parameters.TransformParameterError) as excinfo:
provider.get(mock_name, transform="json")
assert "Extra data" in str(excinfo)
| 5,345,905 |
def load_check_definitions(lang):
"""
Retrieve Trust Advisor check definitions
"""
retval = {}
resp = TA_C.describe_trusted_advisor_checks(language=lang)
if resp:
try:
checks = resp['checks']
retval = {a['id']:a for a in checks}
except ValueError:
LOGGER.error('Received invalid check definitions: %s', str(resp))
else:
LOGGER.error('No response from check definitions')
return retval
| 5,345,906 |
def test_register_again_deserializer(deserializer_type):
"""
Test registering a deserializer again.
"""
with pytest.raises(ValueError):
register_deserializer(*deserializer_type)
| 5,345,907 |
def filter_phrase(comments, phrase):
"""Returns list of comments and replies filtered by substring."""
results = []
for comment in comments:
if phrase.lower() in comment.message.lower():
results.append(comment)
for reply in comment.replies:
if phrase.lower() in reply.message.lower():
results.append(reply)
if not results:
return None
return results
| 5,345,908 |
def get_available_plugins():
"""
Print a list of available plugins
:return:
"""
print("Available plugins:\n")
for instrument, class_name in _working_plugins.items():
print("%s for %s" % (class_name, instrument))
| 5,345,909 |
def asses_completeness(language_code: str, sw: ServiceWorker = Depends(get_sw)):
"""
make a completion test for language: check fe,be, domains and entries
@param language_code:
@param sw:
@return:
"""
if language_code not in sw.messages.get_added_languages():
raise ApplicationException(HTTP_404_NOT_FOUND, "Language not yet added")
return sw.translation.asses_completion(language_code)
| 5,345,910 |
def create_intrinsic_node_class(cls):
"""
Create dynamic sub class
"""
class intrinsic_class(cls):
"""Node class created based on the input class"""
def is_valid(self):
raise TemplateAttributeError('intrisnic class shouldn\'t be directly used')
intrinsic_class.__name__ = '%s_intrinsic' % cls.__name__
return intrinsic_class
| 5,345,911 |
def delete_assessment_run(assessmentRunArn=None):
"""
Deletes the assessment run that is specified by the ARN of the assessment run.
See also: AWS API Documentation
Exceptions
Examples
Deletes the assessment run that is specified by the ARN of the assessment run.
Expected Output:
:example: response = client.delete_assessment_run(
assessmentRunArn='string'
)
:type assessmentRunArn: string
:param assessmentRunArn: [REQUIRED]\nThe ARN that specifies the assessment run that you want to delete.\n
:return: response = client.delete_assessment_run(
assessmentRunArn='arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-11LMTAVe',
)
print(response)
"""
pass
| 5,345,912 |
def load(provider, config_location=DEFAULT_CONFIG_DIR):
"""Load provider specific auth info from file """
auth = None
auth_file = None
try:
config_dir = os.path.join(config_location, NOIPY_CONFIG)
print("Loading stored auth info [%s]... " % config_dir, end="")
auth_file = os.path.join(config_dir, provider)
with open(auth_file) as f:
auth_key = f.read()
auth = ApiAuth.get_instance(auth_key.encode('utf-8'))
print("OK.")
except IOError as e:
print('{0}: "{1}"'.format(e.strerror, auth_file))
raise e
return auth
| 5,345,913 |
def segment_fish(image):
"""Attempts to segment the clown fish out of the provided image."""
hsv_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
light_orange = (1, 190, 200)
dark_orange = (18, 255, 255)
mask = cv2.inRange(hsv_image, light_orange, dark_orange)
light_white = (0, 0, 200)
dark_white = (145, 60, 255)
mask_white = cv2.inRange(hsv_image, light_white, dark_white)
final_mask = mask + mask_white
result = cv2.bitwise_and(image, image, mask=final_mask)
result = cv2.GaussianBlur(result, (7, 7), 0)
return result
| 5,345,914 |
def get_bugzilla_url(bug_id):
"""Return bugzilla url for bug_id."""
return u'https://bugzilla.mozilla.org/show_bug.cgi?id=%d' % bug_id
| 5,345,915 |
def enable_faster_encoder(self, need_build=True, use_fp16=False):
"""
Compiles fusion encoder operator intergrated FasterTransformer using the
method of JIT(Just-In-Time) and replaces the `forward` function of
`paddle.nn.TransformerEncoder` and `paddle.nn.TransformerEncoderLayer`
objects inherited from `self` to support inference using FasterTransformer.
Examples:
.. code-block:: python
from paddlenlp.ops import enable_faster_encoder, disable_faster_encoder
model.eval()
model = enable_faster_encoder(model)
enc_out = model(src, src_mask)
model = disable_faster_encoder(model)
"""
def init_func(layer):
if isinstance(layer, TransformerEncoderLayer):
is_usable = True
if layer._config['bias_attr'] == False:
logger.warning("`False` for paddle.nn.TransformerEncoder's" \
" parameter `bias_attr` is not supported in " \
"FasterTransformer by now. The original forward" \
" will be involved.")
is_usable = False
if layer._config['activation'] not in ('relu', 'gelu'):
logger.warning("Only 'relu' or 'gelu' is supported by now. " \
"The original forward will be involved.")
is_usable = False
if is_usable:
layer.forward = layer._ft_forward
elif isinstance(layer, TransformerEncoder):
layer.forward = layer._ft_forward
if use_fp16:
convert_to_fp16(layer)
if not self.training:
if need_build:
try:
load("FasterTransformer", verbose=True)
except Exception:
logger.warning(
"Exception occurs when using FasterTransformer. " \
"The original forward will be involved. ")
return self
for layer in self.children():
layer.apply(init_func)
return self
| 5,345,916 |
def func(*x):
""" Compute the function to minimise.
Vector reshaped for more readability.
"""
res = 0
x = np.array(x)
x = x.reshape((n, 2))
for i in range(n):
for j in range(i+1, n):
(x1, y1), (x2, y2) = x[i, :], x[j, :]
delta = (x2 - x1)**2 + (y2 - y1)**2 - distances[i, j]**2
res += delta**2
return res
| 5,345,917 |
def transform_target(target, classes=None):
"""
Accepts target value either single dimensional torch.Tensor or (int, float)
:param target:
:param classes:
:return:
"""
if isinstance(target, torch.Tensor):
if target.ndim == 1:
target = target.item() if target.shape[0] == 1 else target
if target.ndim == 0 and classes is None:
return round(target.item(), 2)
if target.shape[0] == 1 and type(classes) in (list, tuple) and classes:
return classes[target]
# Multi-label
if target.shape[0] > 1 and type(classes) in (list, tuple) and classes:
return ",".join([classes[index] for index, value in enumerate(target) if value])
elif isinstance(target, int) and classes:
target = classes[target]
return target
| 5,345,918 |
def test_delete_without_resource_typeerror():
"""If entity= is not a Resource, create() should raise TypeError"""
auth = mock_auth()
base = Rest(auth)
# Resource without change
resource = Mock(Collection)
assert_raises(TypeError, base.delete, resource)
| 5,345,919 |
def called_on_joined():
""" Loop sending the state of this machine using WAMP every x seconds.
This function is executed when the client joins the router, which
means it's connected and authenticated, ready to send WAMP messages.
"""
print("Connected")
# Then we make a POST request to the server to notify it we are active
# and to retrieve the configuration values for our client.
response = requests.post('https://' + SERVER + ':8888/clients/', data={'ip': app._params['ip']})
if response.status_code == 200:
app._params.update(response.json())
else:
print("Could not retrieve configuration for client: {} ({})".format(response.reason, response.status_code))
# The we loop for ever.
print("Entering stats loop ..")
while True:
print("Tick")
try:
# Every time we loop, we get the stats for our machine
stats = {'ip': app._params['ip'], 'name': app._params['name']}
stats.update(get_stats(app._params))
# If we are requested to send the stats, we publish them using WAMP.
if not app._params['disabled']:
app.session.publish('clientstats', stats)
print("Stats published: {}".format(stats))
# Then we wait. Thanks to @inlineCallbacks, using yield means we
# won't block here, so our client can still listen to WAMP events
# and react to them.
yield sleep(app._params['frequency'])
except Exception as e:
print("Error in stats loop: {}".format(e))
break
| 5,345,920 |
def toggle_display_backlight_brightness(low_brightness=12):
"""Reads Raspberry pi touch display's current brightness values from system
file and toggles it between low and max (255) values depending on the
current value.
"""
old = _get_current_display_backlight_brightness()
# set to furthest away from current brightness
if abs(old-low_brightness) < abs(old-HIGH_BRIGHTNESS):
new = HIGH_BRIGHTNESS
else:
new = low_brightness
set_display_backlight_brightness(new)
| 5,345,921 |
def merge_all_regions(out_path: str, id_regions: List[Tuple[int, File]]) -> Tuple[int, int, File]:
"""
Recursively merge a list of region files.
"""
if len(id_regions) == 1:
# Base case 1.
[(sample_id, region_file)] = id_regions
return (sample_id, sample_id, region_file)
elif len(id_regions) == 2:
# Base case 2.
[(sample1_id, region1_file), (sample2_id, region2_file)] = id_regions
else:
# Recursive case.
k = find_midpoint(len(id_regions))
sample1_id, _, region1_file = merge_all_regions(out_path, id_regions[:k])
_, sample2_id, region2_file = merge_all_regions(out_path, id_regions[k:])
return (
sample1_id,
sample2_id,
merge_regions(out_path, sample1_id, region1_file, sample2_id, region2_file),
)
| 5,345,922 |
def write_champ_file_geometry(filename, nucleus_num, nucleus_label, nucleus_coord):
"""Writes the geometry data from the quantum
chemistry calculation to a champ v2.0 format file.
Returns:
None as a function value
"""
if filename is not None:
if isinstance(filename, str):
## Write down a geometry file in the new champ v2.0 format
filename_geometry = os.path.splitext("champ_v2_" + filename)[0]+'_geom.xyz'
with open(filename_geometry, 'w') as file:
file.write("{} \n".format(nucleus_num))
# header line printed below
file.write("# Converted from the trexio file using trex2champ converter https://github.com/TREX-CoE/trexio_tools \n")
for element in range(nucleus_num):
file.write("{:5s} {: 0.6f} {: 0.6f} {: 0.6f} \n".format(nucleus_label[element], nucleus_coord[element][0], nucleus_coord[element][1], nucleus_coord[element][2]))
file.write("\n")
file.close()
else:
raise ValueError
# If filename is None, return a string representation of the output.
else:
return None
| 5,345,923 |
def check_for_collision(sprite1: arcade.Sprite,
sprite2: arcade.Sprite) -> bool:
"""Check for collision between two sprites.
Used instead of Arcade's default implementation as we need a hack to
return False if there is just a one pixel overlap, if it's not
multiplayer...
"""
allowed_overlap = 0
if isinstance(sprite1, player.Player):
if isinstance(sprite1.game, game.Game):
allowed_overlap = 1
x_collision = (
sprite1.right - allowed_overlap > sprite2.left + allowed_overlap
and sprite1.left + allowed_overlap < sprite2.right - allowed_overlap
)
if not x_collision:
return False
return (
sprite1.top - allowed_overlap > sprite2.bottom + allowed_overlap
and sprite1.bottom + allowed_overlap < sprite2.top - allowed_overlap
)
| 5,345,924 |
def maybe_insert_input_equalization_observers_for_node(
node: Node,
equalization_qconfig: Any,
model: torch.nn.Module,
modules: Dict[str, torch.nn.Module],
graph: Graph,
node_name_to_target_dtype: Dict[str, Any],
is_branch: bool,
) -> None:
"""
If `node` needs to be equalized, find the input/weight observers it needs in
`equalization_qconfig`, creates them, and inserts it into `graph`.
If `node` does not need an equalization observer, returns None.
"""
if equalization_qconfig is None or not node_supports_equalization(node, modules):
return
if is_branch:
warnings.warn(
f"Cannot equalize {node} because it is part of a branch."
)
return
new_args = []
for arg in node.args:
if not isinstance(arg, Node) or node_arg_is_bias(node, arg):
new_args.append(arg)
continue
is_weight = node_arg_is_weight(node, arg)
act_eq_process_ctr = equalization_qconfig.weight if is_weight else \
equalization_qconfig.input_activation
new_eq_obs_mod = act_eq_process_ctr()
new_eq_obs_node = insert_observer(
arg, new_eq_obs_mod, model, modules, graph)
# set the type, so the next node can read it
node_name_to_target_dtype[new_eq_obs_node.name] = node_name_to_target_dtype[arg.name]
new_args.append(new_eq_obs_node)
# assign the new args and kwargs to the node, inplace
node.args = tuple(new_args)
| 5,345,925 |
def _bootstrap0(registry_client, executor_manager, store_client,
store_command, release_store, formation):
"""Bootstrap the scheduler.
The steps (and hops) we need to go through to get this up and
running:
1. read the release manifest (release.yml)
2. create instances based on the release manifest.
3. deploy the _store instance.
4. when up and running, create formation in the _store.
5. deploy the rest of the instances.
6. hope for the best.
"""
data = os.getenv('RELEASE')
if data:
release = yaml.load(data)
else:
with open(os.path.join(os.path.dirname(__file__),
'../release.yml')) as fp:
release = yaml.load(fp)
release['name'] = _INITIAL_RELEASE_NAME
services = release['services']
insts = {name: _create(store_command, formation, name,
_INITIAL_RELEASE_NAME, services[name])
for name in services if name != '_bootstrap'}
executor = _select_executor(registry_client)
_deploy_instance(executor_manager, insts['_store'], executor)
# the instance is now up and running, so now we can do a proper
# "assign".
logging.info("waiting for _store to start ...")
time.sleep(4)
store_client.start()
insts['_store'].update(state=store.Instance.STATE_RUNNING,
assigned_to=executor)
# write our release to the store.
release_store.create(formation, _INITIAL_RELEASE_NAME, release)
leader_lock = util.Lock(store_client, 'leader', 'bootstrapper')
with leader_lock:
_create_formation(store_command, insts.values())
for name, inst in insts.items():
if name != '_store':
executor = _select_executor(registry_client)
_deploy_instance(executor_manager, inst, executor)
inst.update(state=store.Instance.STATE_RUNNING,
assigned_to=executor)
logging.info("done! scheduler should be up and running!")
| 5,345,926 |
def test_equality_numpy_scalar():
"""
A regression test to ensure that numpy scalars are correctly compared
(which originally failed due to the lack of ``__array_priority__``).
"""
assert 10 != 10. * u.m
assert np.int64(10) != 10 * u.m
assert 10 * u.m != np.int64(10)
| 5,345,927 |
def modify_color(hsbk, **kwargs):
"""
Helper function to make new colors from an existing color by modifying it.
:param hsbk: The base color
:param hue: The new Hue value (optional)
:param saturation: The new Saturation value (optional)
:param brightness: The new Brightness value (optional)
:param kelvin: The new Kelvin value (optional)
"""
return hsbk._replace(**kwargs)
| 5,345,928 |
def train_val_test_split(df, train_p=0.8, val_p=0.1, state=1, shuffle=True):
"""Wrapper to split data into train, validation, and test sets.
Parameters
-----------
df: pd.DataFrame, np.ndarray
Dataframe containing features (X) and labels (y).
train_p: float
Percent of data to assign to train set.
val_p: float
Percent of data to assign to validation set.
state: int or None
Int will make the split repeatable. None will give a different random
split each time.
shuffle: bool
If True, randomly shuffle the data before splitting.
"""
test_p = 1 - val_p / (1 - train_p)
train, val = train_test_split(df, train_size=train_p, shuffle=shuffle,
random_state=state)
test = None
if not np.isclose(test_p, 0):
val, test = train_test_split(val, test_size=test_p, random_state=state)
return train, val, test
| 5,345,929 |
def add_logs_to_table_heads(max_logs):
"""Adds log headers to table data depending on the maximum number of logs from trees within the stand"""
master = []
for i in range(2, max_logs + 1):
for name in ['Length', 'Grade', 'Defect']:
master.append(f'Log {i} {name}')
if i < max_logs:
master.append('Between Logs Feet')
return master
| 5,345,930 |
def stations_at_risk(stations, level):
"""Returns a list of tuples, (station, risk_level) for all stations with risk above level"""
level = risk_level(level)
stations = [(i, station_flood_risk(i)) for i in stations]
return [i for i in stations if risk_level(i[1]) >= level]
| 5,345,931 |
def try_to_acquire_archive_contents(pull_from: str, extract_to: Path) -> bool:
"""Try to acquire the contents of the archive.
Priority:
1. (already extracted) local contents
2. adress-specified (local|remote) archive through fsspec
Returns:
True if success_acquisition else False
"""
# validation
if extract_to.is_file():
msg = f"contents ({str(extract_to)}) should be directory or empty, but it is file."
raise RuntimeError(msg)
# contents directory already exists.
if extract_to.exists():
return True
else:
file_system: fsspec.AbstractFileSystem = fsspec.filesystem(get_protocol(pull_from))
# todo: get_protocol with cache
archive_exists = file_system.exists(pull_from)
archive_is_file = file_system.isfile(pull_from)
# No corresponding archive. Failed to acquire.
if not archive_exists:
return False
else:
# validation
if not archive_is_file:
msg = f"Archive ({pull_from}) should be file or empty, but is directory."
raise RuntimeError(msg)
# A dataset file exists, so pull and extract.
pull_from_with_cache = f"simplecache::{pull_from}"
extract_to.mkdir(parents=True, exist_ok=True)
print("Accessing the archive in the adress...")
with fsspec.open(pull_from_with_cache, "rb") as archive:
with NamedTemporaryFile("ab") as tmp:
print("Reading the archive in the adress...")
while True:
# Read every 100 MB for large corpus.
d = archive.read(100*1000*1000)
if d:
tmp.write(d)
else:
break
tmp.seek(0)
print("Read.")
print("Extracting...")
extract_archive(tmp.name, str(extract_to))
print("Extracted.")
return True
| 5,345,932 |
def unproxy(proxy):
"""Return a new copy of the original function of method behind a proxy.
The result behaves like the original function in that calling it
does not trigger compilation nor execution of any compiled code."""
if isinstance(proxy, types.FunctionType):
return _psyco.unproxycode(proxy.func_code)
if isinstance(proxy, types.MethodType):
f = unproxy(proxy.im_func)
return new.instancemethod(f, proxy.im_self, proxy.im_class)
raise TypeError, "%s objects cannot be proxies" % type(proxy).__name__
| 5,345,933 |
def get_measured_attribute(data_model, metric_type: str, source_type: str) -> Optional[str]:
"""Return the attribute of the entities of a source that are measured in the context of a metric.
For example, when using Jira as source for user story points, the points of user stories (the source entities) are
summed to arrive at the total number of user story points.
"""
attribute = (
data_model["sources"].get(source_type, {}).get("entities", {}).get(metric_type, {}).get("measured_attribute")
)
return str(attribute) if attribute else attribute
| 5,345,934 |
def collect_app_manager_information(ID_person, subtitle):
"""
Method that is able to collect data and call personal information page constructor
:param ID_person: id inserted by the app manager
"""
# no integer or empty
try:
ID = int(ID_person)
except ValueError:
canvas.itemconfig(subtitle, text="The following field must be fulfilled with a number", fill="red")
canvas.coords(subtitle, 160, 363)
return
global session
global personal_information
find_person_by_ID(session, ID)
# id is not link to any person (also negative )
if len(personal_information) < 3:
canvas.itemconfig(subtitle, text="The following field must be fulfilled with an existing ID", fill="red")
canvas.coords(subtitle, 140, 363)
return
canvas.delete("all")
global button_list
for x in button_list:
x.destroy()
global entry_list
for x in entry_list:
x.destroy()
entry_list = []
button_list = []
create_add_ct()
| 5,345,935 |
def get_one_frame_stack_dynamic(sp, idx):
"""
for a given sp and index number in a dynamic caller operand_stack data, return its
data type and value.
Note, at runtime, caller.operand_stack is dynamic, sp, idx, types and values are all
changing during the run time.
"""
if idx > sp:
return None, None
# get the caller.operand_stack length
length = None
try:
buffer = m_util.gdb_exec_to_str('p func.operand_stack.size()')
except:
return None, None
if buffer[0] != '$':
return None, None
if ' = ' in buffer:
try:
length = int(buffer.split(' = ')[1])
except:
return None, None
else:
return None, None
if m_debug.Debug: m_debug.dbg_print("length=", length)
if length <= sp or length < idx:
return None, None
try:
maple_type = m_util.gdb_exec_to_str('p func.operand_stack[' + str(idx) + '].ptyp')
except:
return None, None
maple_type = maple_type.split(' = ')[1].split('maple::PTY_')[1].rstrip()
try:
buffer = m_util.gdb_exec_to_str('p func.operand_stack[' + str(idx) + ']')
except:
return None, None
value = buffer.split('x = ')[1][1:].split('}')[0]
if maple_type in value:
v = value.split(maple_type + ' = ')[1].split(',')[0]
else:
return None, None
if m_debug.Debug: m_debug.dbg_print("return maple_type=", maple_type, "v=", v)
return maple_type, v
| 5,345,936 |
def getIntArg(arg, optional=False):
"""
Similar to "getArg" but return the integer value of the arg.
Args:
arg (str): arg to get
optional (bool): argument to get
Returns:
int: arg value
"""
return(int(getArg(arg, optional)))
| 5,345,937 |
def erase_all_simulators(path=None):
"""Erases all simulator devices.
Args:
path: (str) A path with simulators
"""
command = ['xcrun', 'simctl']
if path:
command += ['--set', path]
LOGGER.info('Erasing all simulators from folder %s.' % path)
else:
LOGGER.info('Erasing all simulators.')
try:
subprocess.check_call(command + ['erase', 'all'])
except subprocess.CalledProcessError as e:
# Logging error instead of throwing so we don't cause failures in case
# this was indeed failing to clean up.
message = 'Failed to erase all simulators. Error: %s' % e.output
LOGGER.error(message)
| 5,345,938 |
def test_sync_bulk(mocker):
"""Test the hubspot bulk sync function"""
mock_request = mocker.patch("hubspot.tasks.send_hubspot_request")
profile = ProfileFactory.create()
sync_bulk_with_hubspot([profile.user], make_contact_sync_message, "CONTACT")
mock_request.assert_called_once()
| 5,345,939 |
def get_in_with_default(keys: Iterable, default):
"""`get_in` function, returning `default` if a key is not there.
>>> get_in_with_default(["a", "b", 1], 0)({"a": {"b": [0, 1, 2]}})
1
>>> get_in_with_default(["a", "c", 1], 0)({"a": {"b": [0, 1, 2]}})
0
"""
getter = get_in(keys)
def get_in_with_default(x):
try:
return getter(x)
except (KeyError, IndexError, TypeError):
return default
return get_in_with_default
| 5,345,940 |
def conv_HSV2BGR(hsv_img):
"""HSV画像をBGR画像に変換します。
Arguments:
hsv_img {numpy.ndarray} -- HSV画像(3ch)
Returns:
numpy.ndarray -- BGR画像(3ch)
"""
V = hsv_img[:, :, 2]
C = hsv_img[:, :, 1]
H_p = hsv_img[:, :, 0] / 60
X = C * (1 - np.abs(H_p % 2 - 1))
Z = np.zeros_like(C)
vals = [[Z, X, C], [Z, C, X], [X, C, Z], [C, X, Z], [C, Z, X], [X, Z, C]]
bgr_img = np.zeros_like(hsv_img)
for i in range(6):
idx = (i <= H_p) * (H_p < (i + 1))
bgr_img[:, :, 0][idx] = (V - C)[idx] + vals[i][0][idx]
bgr_img[:, :, 1][idx] = (V - C)[idx] + vals[i][1][idx]
bgr_img[:, :, 2][idx] = (V - C)[idx] + vals[i][2][idx]
return (bgr_img * 255).astype(np.uint8)
| 5,345,941 |
def remap(tensor, map_x, map_y, align_corners=False):
"""
Applies a generic geometrical transformation to a tensor.
"""
if not tensor.shape[-2:] == map_x.shape[-2:] == map_y.shape[-2:]:
raise ValueError("Inputs last two dimensions must match.")
batch_size, _, height, width = tensor.shape
# grid_sample need the grid between -1/1
map_xy = torch.stack([map_x, map_y], dim=-1)
map_xy_norm = normalize_pixel_coordinates(map_xy, height, width)
# simulate broadcasting since grid_sample does not support it
map_xy_norm = map_xy_norm.expand(batch_size, -1, -1, -1)
# warp ans return
tensor_warped = F.grid_sample(tensor, map_xy_norm, align_corners=align_corners)
return tensor_warped
| 5,345,942 |
def run_zero_filled_sense(args, data_loader):
""" Run Adjoint (zero-filled SENSE) reconstruction """
logging.info('Run zero-filled SENSE reconstruction')
logging.info(f'Arguments: {args}')
reconstructions = defaultdict(list)
with torch.no_grad():
for sample in tqdm(iter(data_loader)):
sample = data_batch._read_data(sample)
rec_x = sample['attrs']['metadata']['rec_x']
rec_y = sample['attrs']['metadata']['rec_y']
x = sample['input']
recons = postprocess(x, (rec_x, rec_y))
# mask background using background mean value
if args.mask_bg:
fg_mask = center_crop(
sample['fg_mask'],
(rec_x, rec_y),
).squeeze(1)
if args.use_bg_noise_mean:
bg_mean = sample['input_rss_mean'].reshape(-1, 1, 1)
recons = recons * fg_mask + (1 - fg_mask) * bg_mean
else:
recons = recons * fg_mask
# renormalize
norm = sample['attrs']['norm'].numpy()[:, np.newaxis, np.newaxis]
recons = recons.numpy() * norm
for bidx in range(recons.shape[0]):
reconstructions[sample['fname']].append(
(sample['slidx'][bidx], recons[bidx])
)
reconstructions = {
fname: np.stack([pred for _, pred in sorted(slice_preds)])
for fname, slice_preds in reconstructions.items()}
save_reconstructions(reconstructions, args.out_dir)
| 5,345,943 |
def main():
"""Parameter handling main method."""
parser = argparse.ArgumentParser(description="Mel spectrograph using librosa.")
parser.add_argument("-f", "--filename", type=str, help="mp3 or wav file to analyze")
parser.add_argument("--full_mel", action="store_true", help="full mel spectrograph")
parser.add_argument("--split_mel", action="store_true", help="per source mel spectrograph")
args = vars(parser.parse_args())
filename = args["filename"]
if filename is not None:
print(f"Filename: {filename}")
# y = loaded audio as waveform
# sr = sampling rate
y, sr = librosa.load(filename, sr=44100)
if args["full_mel"]:
mel_spectrograph(y, sr)
if args["split_mel"]:
_, _ = mel_spectrograph_by_source(y, sr)
| 5,345,944 |
def AutoRegression(df_input,
target_column,
time_column,
epochs_to_forecast=1,
epochs_to_test=1,
hyper_params_ar={}):
"""
This function performs regression using feature augmentation and then training XGB with Crossvalidation.
Parameters:
- df_input (pandas.DataFrame): Input Time Series.
- target_column (str): name of the column containing the target feature
- time_column (str): name of the column containing the pandas Timestamps
- frequency_data (str): string representing the time frequency of record, e.g. "h" (hours), "D" (days), "M" (months)
- epochs_to_forecast (int): number of steps for predicting future data
- epochs_to_test (int): number of steps corresponding to most recent records to test on
- hyper_params_ar: Parameters of AR model
Returns:
- df_output (pandas.DataFrame): Output DataFrame with forecast
"""
# create and evaluate an updated autoregressive model
# load dataset
input_series = df_input[:-(epochs_to_forecast+epochs_to_test)].set_index(time_column, 1)[target_column]
# split dataset
model = ar_select_order(input_series, **hyper_params_ar)
for hyp_param in ["maxlag","glob","ic"]:
if hyp_param in hyper_params_ar.keys():
del hyper_params_ar[hyp_param]
model = AutoReg(input_series, lags=model.ar_lags, **hyper_params_ar)
res = model.fit()
print(res.summary())
#start_idx = df_input[:-(epochs_to_forecast+epochs_to_test)][time_column].max()
start_idx = df_input[-(epochs_to_forecast+epochs_to_test):][time_column].min()
end_idx = df_input[-(epochs_to_forecast+epochs_to_test):][time_column].max()
# =============================================================================
# ### for statsmodels< 0.12.0
# #forecast_steps = model.predict(res.params, start=start_idx, end=end_idx, dynamic=True)
# forecast = df_input[target_column] * np.nan
# forecast[-(epochs_to_forecast+epochs_to_test):] = forecast_steps
# df_output = df_input.copy()
# df_output["forecast"] = forecast
# df_output["forecast_up"] = forecast * 1.1
# df_output["forecast_low"] = forecast * 0.9
# =============================================================================
### for statsmodels>= 0.12.0
forecast_steps = res.get_prediction(start=start_idx, end=end_idx)
forecast_steps_mean = forecast_steps.predicted_mean
forecast_steps_low = forecast_steps.conf_int()["lower"]
forecast_steps_up = forecast_steps.conf_int()["upper"]
forecast = df_input[target_column] * np.nan
forecast_low = df_input[target_column] * np.nan
forecast_up = df_input[target_column] * np.nan
forecast[-(epochs_to_forecast+epochs_to_test):] = forecast_steps_mean
forecast_low[-(epochs_to_forecast+epochs_to_test):] = forecast_steps_low
forecast_up[-(epochs_to_forecast+epochs_to_test):] = forecast_steps_up
df_output = df_input.copy()
df_output["forecast"] = forecast
df_output["forecast_low"] = forecast_low
df_output["forecast_up"] = forecast_up
return df_output
| 5,345,945 |
def VMACD(prices, timeperiod1=12, timeperiod2=26, timeperiod3=9):
"""
39. VMACD量指数平滑异同移动平均线
(Vol Moving Average Convergence and Divergence,VMACD)
说明:
量平滑异同移动平均线(VMACD)用于衡量量能的发展趋势,属于量能引趋向指标。
MACD称为指数平滑异同平均线。分析的数学公式都是一样的,只是分析的物理量不同。
VMACD对成交量VOL进行分析计算,而MACD对收盘价CLOSE进行分析计算。
计算方法:
SHORT=EMA(VOL,N1)
LONG=EMA(VOL,N2)
DIFF=SHORT-LONG
DEA=EMA(DIFF,M)
VMACD=DIFF-DEA
通常N1=12,N2=26,M=9
:param prices:
:param timeperiod1: N1
:param timeperiod2: N2
:param timeperiod3: N3
:return:
"""
assert prices is not None
timeperiod = max(timeperiod1, timeperiod2, timeperiod3)
_assert_greater_or_equal(len(prices), timeperiod)
assert isinstance(timeperiod1, int)
assert isinstance(timeperiod2, int)
assert isinstance(timeperiod3, int)
df_price = prices.copy()
df_price = df_price.sort_index(ascending=True)
EMA = ta.EMA
short = EMA(df_price['volume'].values.astype(float), timeperiod1)
long = EMA(df_price['volume'].values.astype(float), timeperiod2)
diff = short - long
dea = EMA(diff, timeperiod3)
vmacd = diff - dea
df_price['VMACD'] = vmacd
return df_price['VMACD']
| 5,345,946 |
def try_compress_numbers_to_range(elements):
"""
Map the "number" attribute of any element in `elements` to the most compact
range possible (starting from 1). If the resulting numbers are within
[MIN_RANGE, MAX_RANGE], return True, otherwise, return False. If it is not
possible to obtain a mapping within [MIN_RANGE, MAX_RANGE], the number
attributes not modified.
"""
numbers = set(int(e.get('number')) for e in elements)
if len(numbers) <= ((MAX_RANGE - MIN_RANGE) + 1):
actual_nrs = sorted(numbers)
ideal_nrs = range(MIN_RANGE, MIN_RANGE + len(numbers))
if np.any(np.array(actual_nrs) != np.array(ideal_nrs)):
nr_map = dict(zip(actual_nrs, ideal_nrs))
LOGGER.debug(u'compressing number range {}'
.format(', '.join(u'{} → {}'.format(k, v) for k, v in nr_map.items())))
for e in elements:
old_nr = int(e.get('number'))
new_nr = nr_map[old_nr]
e.set('number', str(new_nr))
all_within_range = True
else:
all_within_range = False
return all_within_range
| 5,345,947 |
def merge_all_mods(list_of_mods, gfx=None):
"""Merges the specified list of mods, starting with graphics if set to
pre-merge (or if a pack is specified explicitly).
Params:
list_of_mods
a list of the names of mods to merge
gfx
a graphics pack to be merged in
Returns:
A list of status ints for each mod given:
-1: Unmerged
0: Merge was successful, all well
1: Potential compatibility issues, no merge problems
2: Non-fatal error, overlapping lines or non-existent mod etc
3: Fatal error, not returned (rebuilds to previous, rest unmerged)
"""
from . import graphics
clear_temp()
if gfx:
add_graphics(gfx)
elif will_premerge_gfx():
add_graphics(graphics.current_pack())
ret_list = []
for i, mod in enumerate(list_of_mods):
status = merge_a_mod(mod)
ret_list.append(status)
if status == 3:
log.i('Mod {}, in {}, could not be merged.'.format(
mod, str(list_of_mods)))
merged = merge_all_mods(list_of_mods[:i-1], gfx)
return merged + [-1]*len(list_of_mods[i:])
return ret_list
| 5,345,948 |
def pearson_r_p_value(a, b, dim):
"""
2-tailed p-value associated with pearson's correlation coefficient.
Parameters
----------
a : Dataset, DataArray, GroupBy, Variable, numpy/dask arrays or scalars
Mix of labeled and/or unlabeled arrays to which to apply the function.
b : Dataset, DataArray, GroupBy, Variable, numpy/dask arrays or scalars
Mix of labeled and/or unlabeled arrays to which to apply the function.
dim : str
The dimension to apply the correlation along.
Returns
-------
Single value or tuple of Dataset, DataArray, Variable, dask.array.Array or
numpy.ndarray, the first type on that list to appear on an input.
2-tailed p-value.
See Also
--------
scipy.stats.pearsonr
xarray.apply_unfunc
"""
return xr.apply_ufunc(_pearson_r_p_value, a, b,
input_core_dims=[[dim], [dim]],
kwargs={'axis': -1})
| 5,345,949 |
def get_ceilometer_usages(date, connection_string):
"""
Function which talks with openstack
"""
today = datetime.datetime.combine(date, datetime.datetime.min.time())
yesterday = today - datetime.timedelta(days=1)
engine = create_engine(connection_string)
connection = engine.connect()
query = CEILOMETER_QUERY.format(
from_ts=time.mktime(yesterday.timetuple()),
to_ts=time.mktime(today.timetuple())
)
return connection.execute(query)
| 5,345,950 |
def _do_artifact_mapping(query_definition, event_message, metadata,
response, res_client, context_token,
additional_map_data=None):
""" Map query results to new artifact and add to Resilient """
incident = event_message.get("incident", {})
incident_id = incident.get("id")
if not response:
return
existing_artifacts = [_artifact_key(artifact) for artifact in _get_artifacts(incident_id, res_client)]
LOG.debug(u"Existing Artifacts:\n%s", u"\n".join(existing_artifacts))
if query_definition.result_container:
# Create an artifact for each query result row
for row in response:
for artifact_template in query_definition.artifact_mapping:
mapdata = {"result": row}
# Add in any query result metadata
mapdata.update(metadata)
if additional_map_data:
mapdata.update(additional_map_data)
artifact = template_functions.render_json(artifact_template,
mapdata)
if artifact.get("value") and _unique_artifact(artifact, existing_artifacts):
_add_artifact(res_client, incident_id, artifact, context_token)
existing_artifacts.append(_artifact_key(artifact))
else:
# Create a single artifact from the query result
for artifact_template in query_definition.artifact_mapping:
artifact = template_functions.render_json(artifact_template, response)
if artifact.get("value") and _unique_artifact(artifact, existing_artifacts):
_add_artifact(res_client, incident_id, artifact, context_token)
existing_artifacts.append(_artifact_key(artifact))
| 5,345,951 |
def fit_kij(kij_bounds, eos, mix, datavle=None, datalle=None, datavlle=None,
weights_vle=[1., 1.], weights_lle=[1., 1.],
weights_vlle=[1., 1., 1., 1.], minimize_options={}):
"""
fit_kij: attemps to fit kij to VLE, LLE, VLLE
Parameters
----------
kij_bounds : tuple
bounds for kij correction
eos : function
cubic eos to fit kij for qmr mixrule
mix: object
binary mixture
datavle: tuple, optional
(Xexp, Yexp, Texp, Pexp)
datalle: tuple, optional
(Xexp, Wexp, Texp, Pexp)
datavlle: tuple, optional
(Xexp, Wexp, Yexp, Texp, Pexp)
weights_vle: list or array_like, optional
weights_vle[0] = weight for Y composition error, default to 1.
weights_vle[1] = weight for bubble pressure error, default to 1.
weights_lle: list or array_like, optional
weights_lle[0] = weight for X (liquid 1) composition error, default to 1.
weights_lle[1] = weight for W (liquid 2) composition error, default to 1.
weights_vlle: list or array_like, optional
weights_vlle[0] = weight for X (liquid 1) composition error, default to 1.
weights_vlle[1] = weight for W (liquid 2) composition error, default to 1.
weights_vlle[2] = weight for Y (vapor) composition error, default to 1.
weights_vlle[3] = weight for equilibrium pressure error, default to 1.
minimize_options: dict
Dictionary of any additional spefication for scipy minimize_scalar
Returns
-------
fit : OptimizeResult
Result of SciPy minimize
"""
fit = minimize_scalar(fobj_kij, kij_bounds, args=(eos, mix, datavle,
datalle, datavlle, weights_vle, weights_lle,
weights_vlle), **minimize_options)
return fit
| 5,345,952 |
def pickle_photospheres(photosphere_filenames, kind, meta=None):
"""
Load all model photospheres, parse the points and photospheric structures.
"""
if meta is None:
meta = {
"kind": kind,
"source_directory": os.path.dirname(photosphere_filenames[0])
}
elif not isinstance(meta, dict):
raise TypeError("meta must be a dictionary or None")
# Get the names from the first filename
parsers = {
"marcs": marcs,
"castelli/kurucz": castelli_kurucz
}
try:
parser = parsers[kind.lower()]
except KeyError:
raise ValueError("don't recognise photosphere kind '{0}'; available kinds"
" are {1}".format(kind, ", ".join(parsers.keys())))
_, parameter_names = parser.parse_filename(photosphere_filenames[0], True)
# Get the parameters of all the points
parameters = np.core.records.fromrecords(
map(parser.parse_filename, photosphere_filenames), names=parameter_names)
# Verify there are no duplicates.
array_view = parameters.view(float).reshape(parameters.size, -1)
_ = np.ascontiguousarray(array_view).view(np.dtype((np.void,
array_view.dtype.itemsize * array_view.shape[1])))
_, idx = np.unique(_, return_index=True)
if idx.size != parameters.size:
raise ValueError("{} duplicate stellar parameters found".format(
parameters.size - idx.size))
# Now sort the array by the left most columns. Keep track of the indices
# because we will load the photospheres in this order.
i = np.argsort(parameters, order=parameter_names)
parameters = parameters[i]
_, photosphere_columns = parser.parse_photospheric_structure(
photosphere_filenames[0], full_output=True)
d = np.array([parser.parse_photospheric_structure(photosphere_filenames[_]) \
for _ in i])
return (parameters, d, photosphere_columns, meta)
| 5,345,953 |
def get_pid_and_server():
"""Find process id and name of server the analysis is running on
Use the platform.uname to find servername instead of os.uname because the latter is not supported on Windows.
"""
pid = os.getpid()
server = platform.uname().node
return f"{pid}@{server}"
| 5,345,954 |
def cal_embedding(sents, model_path, word_idx, mode='mean'):
"""Calculate the embedding for each sentence
Args:
sents (list): a list of sentences
model_path (str): keras model path
word_idx (dict): a dictionary of mapping between words and indices
mode (str): current support mean and concatenate word vectors
"""
# check the mode
if mode not in ['mean', 'concatenate']:
print('Only mean and concatenate are allowed currently!')
sys.exit(0)
# get weights of embedding layer from the model
from keras.models import load_model
k_model = load_model(model_path)
embd_weights = k_model.layers[0].get_weights()[0]
# loop through the sentences to calculate embedding for each sentence
for sent in sents:
sent = sent.strip()
if len(sent) < 1: # control the length of sentences
continue
# simple tokenization by whitespace
idx_list = [word_idx.get(word.strip().lower(), -1)
for word in sent.split(' ') if len(word.strip()) > 0]
# calculate embeddings
sent_embedding = []
if mode == 'mean':
for tmp_idx in idx_list:
if tmp_idx == -1 or tmp_idx > len(embd_weights) - 1:
sent_embedding.append(list(np.zeros(len(embd_weights[0]))))
else:
sent_embedding.append(embd_weights[tmp_idx])
sent_embedding = np.mean(sent_embedding, axis=0)
elif mode == 'concatenate':
for tmp_idx in idx_list:
if tmp_idx == -1 or tmp_idx > len(embd_weights) - 1:
sent_embedding.extend(list(np.zeros(len(embd_weights[0]))))
else:
sent_embedding.extend(embd_weights[tmp_idx])
yield sent_embedding
| 5,345,955 |
def MemGetSize(BlockID):
"""
Returns the size of a memory block (Also useful for determining if a memory block already exists
Output: Returns the size of the memory block. Returns 0 if data block could not be found.
"""
pass
| 5,345,956 |
def calc_ac_score(labels_true, labels_pred):
"""calculate unsupervised accuracy score
Parameters
----------
labels_true: labels from ground truth
labels_pred: labels form clustering
Return
-------
ac: accuracy score
"""
nclass = len(np.unique(labels_true))
labels_size = len(labels_true)
mat = labels_size * np.ones((nclass, nclass))
idx = 0
for i in range(labels_size):
mat[labels_pred[i], labels_true[i]] -= 1.0
munkres = Munkres()
mapping = munkres.compute(mat)
ac = 0.0
for i in range(labels_size):
val = mapping[labels_pred[i]][1]
if val == labels_true[i]:
ac += 1.0
ac = ac / labels_size
return ac
| 5,345,957 |
def main(**kwargs):
"""Update info in AWS_EC2 and AWS_IP redis-helper collections"""
if kwargs['all'] is True:
for profile in get_profiles():
ec2 = EC2(profile)
ec2.update_collection()
else:
ec2 = EC2(kwargs['profile'])
ec2.update_collection()
if kwargs['non_interactive'] is not True:
ih.start_ipython(ec2=AWS_EC2, ip=AWS_IP)
| 5,345,958 |
def wave_ode_gamma_neq0(t, X, *f_args):
"""
Right hand side of the wave equation ODE when gamma > 0
"""
C = f_args[0]
D = f_args[1]
CD = C*D
x, y, z = X
return np.array([-(1./(1.+y) + CD)*x + C*(1+D*CD)*(z-y), x, CD*(z-y)])
| 5,345,959 |
def populate_daily_metrics_for_site(site_id, date_for, force_update=False):
"""Collect metrics for the given site and date
"""
try:
site = Site.objects.get(id=site_id)
except Site.DoesNotExist as e:
msg = ('{prefix}:SITE:FAIL:populate_daily_metrics_for_site:site_id: '
'{site_id} does not exist')
logger.exception(msg.format(prefix=FPD_LOG_PREFIX, site_id=site_id))
raise e
for course_id in site_course_ids(site):
try:
populate_single_cdm(course_id=course_id,
date_for=date_for,
force_update=force_update)
except Exception as e: # pylint: disable=broad-except
msg = ('{prefix}:SITE:COURSE:FAIL:populate_daily_metrics_for_site.'
' site_id:{site_id}, date_for:{date_for}. course_id:{course_id}'
' exception:{exception}')
logger.exception(msg.format(prefix=FPD_LOG_PREFIX,
site_id=site_id,
date_for=date_for,
course_id=str(course_id),
exception=e))
populate_single_sdm(site_id=site.id,
date_for=date_for,
force_update=force_update)
| 5,345,960 |
def run_workflow(
config: Dict,
form_data: ImmutableMultiDict,
*args,
**kwargs
) -> Dict:
"""Executes workflow and save info to database; returns unique run id."""
# Validate data and prepare run environment
form_data_dict = __immutable_multi_dict_to_nested_dict(
multi_dict=form_data
)
__validate_run_workflow_request(data=form_data_dict)
__check_service_info_compatibility(data=form_data_dict)
document = __init_run_document(data=form_data_dict)
document = __create_run_environment(
config=config,
document=document,
**kwargs
)
# Start workflow run in background
__run_workflow(
config=config,
document=document,
**kwargs
)
response = {'run_id': document['run_id']}
return response
| 5,345,961 |
def insertion_stack(nums: List[int]) -> List[int]:
""" A helper function that sort the data in an ascending order
Args:
nums: The original data
Returns:
a sorted list in ascending order
"""
left = []
right = []
for num in nums:
while left and left[-1] > num:
right.append(left.pop())
left.append(num)
while right:
left.append(right.pop())
return left
| 5,345,962 |
def svn_wc_get_pristine_contents(*args):
"""svn_wc_get_pristine_contents(char const * path, apr_pool_t result_pool, apr_pool_t scratch_pool) -> svn_error_t"""
return _wc.svn_wc_get_pristine_contents(*args)
| 5,345,963 |
def _FindAllPossibleBrowsers(finder_options, android_platform):
"""Testable version of FindAllAvailableBrowsers."""
if not android_platform:
return []
possible_browsers = []
if finder_options.webview_embedder_apk and not os.path.exists(
finder_options.webview_embedder_apk):
raise exceptions.PathMissingError(
'Unable to find apk specified by --webview-embedder-apk=%s' %
finder_options.browser_executable)
# Add the exact APK if given.
if _CanPossiblyHandlePath(finder_options.browser_executable):
if not os.path.exists(finder_options.browser_executable):
raise exceptions.PathMissingError(
'Unable to find exact apk specified by --browser-executable=%s' %
finder_options.browser_executable)
package_name = apk_helper.GetPackageName(finder_options.browser_executable)
try:
backend_settings = next(
b for b in ANDROID_BACKEND_SETTINGS if b.package == package_name)
except StopIteration:
raise exceptions.UnknownPackageError(
'%s specified by --browser-executable has an unknown package: %s' %
(finder_options.browser_executable, package_name))
possible_browsers.append(PossibleAndroidBrowser(
'exact',
finder_options,
android_platform,
backend_settings,
finder_options.browser_executable))
# Add the reference build if found.
os_version = dependency_util.GetChromeApkOsVersion(
android_platform.GetOSVersionName())
arch = android_platform.GetArchName()
try:
reference_build = binary_manager.FetchPath(
'chrome_stable', arch, 'android', os_version)
except (binary_manager.NoPathFoundError,
binary_manager.CloudStorageError):
reference_build = None
if reference_build and os.path.exists(reference_build):
# TODO(aiolos): how do we stably map the android chrome_stable apk to the
# correct backend settings?
possible_browsers.append(PossibleAndroidBrowser(
'reference',
finder_options,
android_platform,
android_browser_backend_settings.ANDROID_CHROME,
reference_build))
# Add any other known available browsers.
for settings in ANDROID_BACKEND_SETTINGS:
p_browser = PossibleAndroidBrowser(
settings.browser_type, finder_options, android_platform, settings)
if p_browser.IsAvailable():
possible_browsers.append(p_browser)
return possible_browsers
| 5,345,964 |
def test_populate_intended_for(tmpdir, folder, expected_prefix, simulation_function):
"""
Test populate_intended_for.
Parameters:
----------
tmpdir
folder : str or os.path
path to BIDS study to be simulated, relative to tmpdir
expected_prefix : str
expected start of the "IntendedFor" elements
simulation_function : function
function to create the directory tree and expected results
"""
session_folder = op.join(str(tmpdir), folder)
session_struct, expected_result, _, _ = simulation_function(session_folder)
populate_intended_for(session_folder, matching_parameters='Shims', criterion='First')
# Now, loop through the jsons in the fmap folder and make sure it matches
# the expected result:
fmap_folder = op.join(session_folder, 'fmap')
for j in session_struct['fmap'].keys():
if j.endswith('.json'):
assert j in expected_result.keys()
data = load_json(op.join(fmap_folder, j))
if expected_result[j]:
assert data['IntendedFor'] == expected_result[j]
# Also, make sure the run with random shims is not here:
# (It is assured by the assert above, but let's make it
# explicit)
run_prefix = j.split('_acq')[0]
assert '{p}_acq-unmatched_bold.nii.gz'.format(p=run_prefix) not in data['IntendedFor']
else:
assert 'IntendedFor' not in data.keys()
| 5,345,965 |
def getLanguageSpecification(lang):
"""
Return a dictionary which contains the specification of a language.
Specifically, return the key-value pairs defined in the 'lang.yaml' file as
a dictionary, i.e. for the language cpp return the contents of
'plugins/cpp/lang.yaml'.
Raise an IOError if the 'lang.yaml' file does not exist.
Arguments:
lang -- the name of the language
"""
dirPath = '/'.join([os.path.dirname(__file__), PLUGIN_PATH, lang])
if not exists(dirPath):
print('ERROR:', dirPath, 'dir not found.')
raise IOError()
filePath = '/'.join([dirPath, 'lang.yaml'])
if not exists(filePath):
print('ERROR: lang.yaml file not found for language', lang)
raise IOError()
return yaml.load(open(filePath).read().strip())
| 5,345,966 |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a connection
with the context.
"""
with engine().connect() as connection:
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
| 5,345,967 |
def _is_valid_file(file):
"""Returns whether a file is valid.
This means that it is a file and not a directory, but also that
it isn't an unnecessary dummy file like `.DS_Store` on MacOS.
"""
if os.path.isfile(file):
if not file.startswith('.git') and file not in ['.DS_Store']:
return True
return False
| 5,345,968 |
def create_cache_key(func, key_dict=None, self=None):
"""Get a cache namespace and key used by the beaker_cache decorator.
Example::
from tg import cache
from tg.caching import create_cache_key
namespace, key = create_cache_key(MyController.some_method)
cache.get_cache(namespace).remove(key)
"""
kls = None
imfunc = im_func(func)
if imfunc:
kls = im_class(func)
func = imfunc
cache_key = func.__name__
else:
cache_key = func.__name__
if key_dict:
cache_key += " " + " ".join("%s=%s" % (k, v)
for k, v in key_dict.items())
if not kls and self:
kls = getattr(self, '__class__', None)
if kls:
return '%s.%s' % (kls.__module__, kls.__name__), cache_key
else:
return func.__module__, cache_key
| 5,345,969 |
def longest_common_substring(s, t):
"""
Find the longest common substring between the given two strings
:param s: source string
:type s: str
:param t: target string
:type t: str
:return: the length of the longest common substring
:rtype: int
"""
if s == '' or t == '':
return 0
f = [[0 for _ in range(len(t) + 1)]
for _ in range(len(s) + 1)]
for i in range(len(s)):
for j in range(len(t)):
if s[i] == t[j]:
f[i + 1][j + 1] = f[i][j] + 1
return max(map(max, f))
| 5,345,970 |
def add_cutoff_freqs(ax, mode, arrow_dir, y_max, c_L, c_S,
plt_kwargs={'color': 'k', 'ls': '--', 'lw': 0.5}):
"""Add vertical lines indicating cutoff frequencies to a matplotlib
axes object.
Parameters
----------
ax : axes
Matplotlib axes in which the plot will be added.
mode : str
Mode to plot. Can be "A0", "A1", "A2", ..., "An" or "S0", "S1",
"S2", ..., "Sn", with 'n' being the order of the corresponding
mode.
arrow_dir : str
Set arrows' direction in the plot. Can be 'up' (for group
velocity plots) or 'down' (for phase velocity plots).
y_max : float
Maximum y value in the plot. Used to position arrows in phase
velocity plots.
c_L : float
Longitudinal wave velocity of the material, in m/s.
c_S: float
Shear wave velocity of the material, in m/s.
plt_kwargs : dict, optional
Matplotlib kwargs (to change color, linewidth, linestyle, etc.).
"""
if arrow_dir == 'down':
arrow_y_pos = y_max
arrow_str = r'$\downarrow$'
arrow_va = 'top'
elif arrow_dir == 'up':
arrow_y_pos = 0
arrow_str = r'$\uparrow$'
arrow_va = 'bottom'
n = int(mode[1:]) + 1
ax.axvline(x = n*c_S if mode[0] == 'S' else n*c_L,
**plt_kwargs)
ax.text(x = n*c_S if mode[0] == 'S' else n*c_L,
y=arrow_y_pos, s=arrow_str, va=arrow_va, ha='center',
clip_on=True)
if n % 2 != 0:
ax.axvline(x = n*c_L/2 if mode[0] == 'S' else n*c_S/2,
**plt_kwargs)
ax.text(x = n*c_L/2 if mode[0] == 'S' else n*c_S/2,
y=arrow_y_pos, s=arrow_str, va=arrow_va, ha='center',
clip_on=True)
| 5,345,971 |
def pytest_addoption(parser):
""" Load in config path. """
group = parser.getgroup("Agent Test Suite Configuration", "agent", after="general")
group.addoption(
"--sc",
"--suite-config",
dest='suite_config',
action="store",
metavar="SUITE_CONFIG",
help="Load suite configuration from SUITE_CONFIG",
)
group.addoption(
"-F",
"--feature-select",
dest='select',
action='store',
metavar='SELECT_REGEX',
help='Run tests matching SELECT_REGEX. Overrides tests selected in configuration.'
)
| 5,345,972 |
def correct_predictions(output_probabilities, targets):
"""
Compute the number of predictions that match some target classes in the
output of a model.
Args:
output_probabilities: A tensor of probabilities for different output
classes.
targets: The indices of the actual target classes.
Returns:
The number of correct predictions in 'output_probabilities'.
"""
_, out_classes = output_probabilities.max(dim=1)
correct = (out_classes == targets).sum()
return out_classes, correct.item()
| 5,345,973 |
def resolve_all(anno, task):
"""Resolve all pending annotations."""
return (x for x in (_first_match(anno, task), _first_match_any(anno)) if x)
| 5,345,974 |
def get_free_port():
""" Find and returns free port number. """
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
soc.bind(("", 0))
free_port = soc.getsockname()[1]
soc.close()
return free_port
| 5,345,975 |
def test_upload_subtitles_authentication(
mock_user_moira_lists, logged_in_apiclient, mocker
):
"""
Tests that only authenticated users with collection admin permissions can call UploadVideoSubtitle
"""
client, user = logged_in_apiclient
client.logout()
url = reverse("upload-subtitles")
moira_list = factories.MoiraListFactory()
video = VideoFactory(collection=CollectionFactory(admin_lists=[moira_list]))
filename = "file.vtt"
input_data = {
"collection": video.collection.hexkey,
"video": video.hexkey,
"language": "en",
"filename": filename,
"file": SimpleUploadedFile(filename, bytes(1024)),
}
mocker.patch(
"ui.views.cloudapi.upload_subtitle_to_s3",
return_value=VideoSubtitle(video=video, filename=filename),
)
mocker.patch("ui.utils.cache")
# call with anonymous user
assert (
client.post(url, input_data, format="multipart").status_code
== status.HTTP_403_FORBIDDEN
)
# call with another user not on admin list
client.force_login(user)
assert (
client.post(url, input_data, format="multipart").status_code
== status.HTTP_403_FORBIDDEN
)
# call with user on admin list
mock_user_moira_lists.return_value = {moira_list.name}
assert (
client.post(url, input_data, format="multipart").status_code
== status.HTTP_202_ACCEPTED
)
| 5,345,976 |
def get_diff_list(small_list, big_list):
"""
Get the difference set of the two list.
:param small_list: The small data list.
:param big_list: The bigger data list.
:return: diff_list: The difference set list of the two list.
"""
# big_list有而small_list没有的元素
diff_list = list(set(big_list).difference(set(small_list)))
return diff_list
| 5,345,977 |
def blend_weight_arrays(n_weightsA, n_weightsB, value=1.0, weights_pp=None):
"""
Blend two 2d weight arrays with a global mult factor, and per point weight values.
The incoming weights_pp should be a 1d array, as it's reshaped for the number of influences.
Args:
n_weightsA (np.array): Weight array to blend towards n_weightsB.
n_weightsB (np.array): Target weight array to move n_weightsA towards.
value (float): Global mult factor.
weights_pp (list/float): Per point weight values. This should be a 1d array.
Returns (numpy.ndarray): Blended weights array.
"""
if n_weightsA.shape != n_weightsB.shape:
raise ValueError('Shape of both arrays must match: {}, {}'.format(n_weightsA.shape, n_weightsB.shape))
weights_pp = weights_pp or np.ones(n_weightsA.shape[0])
weights_pp = np.repeat(weights_pp, n_weightsA.shape[1]).reshape(-1, n_weightsA.shape[1]) * value
n_weights = np_interp_by_weight(n_weightsA, n_weightsB, weights_pp)
return n_weights
| 5,345,978 |
def weight_kabsch_dist(x1, x2, weights):
"""
Compute the Mahalabonis distance between positions x1 and x2 given Kabsch weights (inverse variance)
x1 (required) : float64 array with dimensions (n_atoms,3) of one molecular configuration
x2 (required) : float64 array with dimensions (n_atoms,3) of another molecular configuration
weights (required) : float64 matrix with dimensions (n_atoms, n_atoms) of inverse (n_atoms, n_atoms) covariance
"""
# zero distance
dist = 0.0
# compute distance as sum over indepdent (because covar is n_atoms x n_atoms) dimensions
for i in range(3):
disp = x1[:,i] - x2[:,i]
dist += np.dot(disp,np.dot(weights,disp))
# return value
return dist
| 5,345,979 |
def calc_color_rarity(color_frequencies: dict) -> float:
"""
Return rarity value normalized to 64.
Value ascending from 0 (most rare) to 64 (most common).
"""
percentages = calc_pixel_percentages(color_frequencies)
weighted_rarity = [PERCENTAGES_NORMALIZED.get(k) * v * 64 for k,v in percentages.items()]
return sum(weighted_rarity)
| 5,345,980 |
def exp_map(x, r, tangent_point=None):
"""
Let \(\mathcal{M}\) be a CCM of radius `r`, and \(T_{p}\mathcal{M}\) the
tangent plane of the CCM at point \(p\) (`tangent_point`).
This function maps a point `x` on the tangent plane to the CCM, using the
Riemannian exponential map.
:param x: np.array, point on the tangent plane (intrinsic coordinates);
:param r: float, radius of the CCM;
:param tangent_point: np.array, origin of the tangent plane on the CCM
(extrinsic coordinates); if `None`, defaults to `[0., ..., 0., r]`.
:return: the exp-map of x to the CCM (extrinsic coordinates).
"""
extrinsic_dim = x.shape[-1] + 1
if tangent_point is None:
tangent_point = np.zeros((extrinsic_dim,))
tangent_point[-1] = np.abs(r)
if isinstance(tangent_point, np.ndarray):
if tangent_point.shape != (extrinsic_dim,) and tangent_point.shape != (1, extrinsic_dim):
raise ValueError('Expected tangent_point of shape ({0},) or (1, {0}), got {1}'.format(extrinsic_dim, tangent_point.shape))
if tangent_point.ndim == 1:
tangent_point = tangent_point[np.newaxis, ...]
if not belongs(tangent_point, r)[0]:
raise ValueError('Tangent point must belong to manifold {}'.format(tangent_point))
else:
raise TypeError('tangent_point must be np.array or None')
if r > 0.:
return SphericalManifold.exp_map(tangent_point, x)
elif r < 0.:
return HyperbolicManifold.exp_map(tangent_point, x)
else:
return x
| 5,345,981 |
def test_parser_read(fresh_aiida_env):
"""Test to read a INCAR file."""
path = data_path('phonondb', 'INCAR')
parser = IncarParser(file_path=path)
incar = parser.incar
assert incar['prec'] == 'Accurate'
assert incar['ibrion'] == -1
assert incar['encut'] == 359.7399
assert incar['lreal'] is False
| 5,345,982 |
def get_python_msvcrt_version():
"""Return the Visual C runtime version Python is linked to, as an int"""
python_version = sys.version_info[0:2]
if python_version < (2.4):
return 60
if python_version < (2.6):
return 71
return 90
| 5,345,983 |
def _get_data_column_label_in_name(item_name):
"""
:param item_name: Name of a group or dataset
:return: Data column label or ``None``
:rtype: str on None
"""
# /1.1/measurement/mca_0 should not be interpreted as the label of a
# data column (let's hope no-one ever uses mca_0 as a label)
if measurement_mca_group_pattern.match(item_name):
return None
data_column_match = measurement_data_pattern.match(item_name)
if not data_column_match:
return None
return data_column_match.group(1)
| 5,345,984 |
def _auto_backward(loss,
startup_program=None,
parameter_list=None,
no_grad_set=None,
callbacks=None,
distop_context=None):
"""
modification is inplaced
"""
act_no_grad_set = _get_no_grad_set(loss, no_grad_set)
assert isinstance(loss, Variable), "The target loss should be an Variable."
if callbacks is None:
callbacks = [error_clip_callback]
else:
assert (isinstance(callbacks, list))
assert len(loss.shape) == 1 and loss.shape[0] == 1, \
"The loss.shape should be (1L,), but the current loss.shape is {}. " \
"Maybe that you should call fluid.layers.mean to process the current loss.".format(
loss.shape)
program = loss.block.program
with program_guard(program, startup_program):
params_grads = append_backward(
loss,
parameter_list,
act_no_grad_set,
callbacks,
distop_context=distop_context)
return params_grads
| 5,345,985 |
def strip_from_ansi_esc_sequences(text):
"""
find ANSI escape sequences in text and remove them
:param text: str
:return: list, should be passed to ListBox
"""
# esc[ + values + control character
# h, l, p commands are complicated, let's ignore them
seq_regex = r"\x1b\[[0-9;]*[mKJusDCBAfH]"
regex = re.compile(seq_regex)
start = 0
response = ""
for match in regex.finditer(text):
end = match.start()
response += text[start:end]
start = match.end()
response += text[start:len(text)]
return response
| 5,345,986 |
def test_steamgameentity_extra_state_attributes_property(manager_mock):
"""Test the device_state_attributes property."""
game_id = "975150"
game = util.get_steam_game(game_id, manager_mock.coordinator.data[game_id])
entity = SteamGameEntity(manager_mock, game)
expected = {
"box_art_url": "https://steamcdn-a.akamaihd.net/steam/apps/975150/header_292x136.jpg?t=1590678003",
"normal_price": 19.99,
"percent_off": 15,
"review_desc": "3 user reviews",
"reviews_percent": 100,
"reviews_total": "3",
"sale_price": 16.99,
"steam_id": "975150",
"title": "Resolutiion",
}
assert expected == entity.extra_state_attributes
| 5,345,987 |
def periodic_task1():
"""
@summary: 周期性任务执行函数
"""
now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
try:
import requests
req = requests.get('http://www.baidu.com')
print req.status_code
logger.info(u"Celery 周期任务调用成功,当前时间:{}".format(now))
except Exception:
logger.error(u"Celery 周期任务调用失败,当前时间:{}".format(now))
| 5,345,988 |
def _concat_columns(args: list):
"""Dispatch function to concatenate DataFrames with axis=1"""
if len(args) == 1:
return args[0]
else:
_lib = cudf if HAS_GPU and isinstance(args[0], cudf.DataFrame) else pd
return _lib.concat(
[a.reset_index(drop=True) for a in args],
axis=1,
)
return None
| 5,345,989 |
def test_grdinfo():
"""
Make sure grdinfo works as expected.
"""
grid = load_earth_relief(registration="gridline")
result = grdinfo(grid=grid, force_scan=0, per_column="n")
assert result.strip() == "-180 180 -90 90 -8592.5 5559 1 1 361 181 0 1"
| 5,345,990 |
def applyRegexToList(list, regex, separator=' '):
"""Apply a list of regex to list and return result"""
if type(regex) != type(list):
regex = [regex]
regexList = [re.compile(r) for r in regex]
for r in regexList:
list = [l for l in list if r.match(l)]
list = [l.split(separator) for l in list]
return [i[0] for i in list]
| 5,345,991 |
def tomorrow(event):
""" show todo items for tomorrow. """
if not event._parsed.rest:
event.reply("tomorrow <txt>")
return
event.tomorrow = event.txt.replace("tomorrow", "").strip()
event.prefix = "tomorrow"
event.save()
event.ok()
| 5,345,992 |
def pathsplit(path):
""" This version, in contrast to the original version, permits trailing
slashes in the pathname (in the event that it is a directory).
It also uses no recursion """
return path.split(os.path.sep)
| 5,345,993 |
def GetFileName(path: str) -> str:
"""Get the name of the file from the path
:type path: str
:rtype: str
"""
return splitext(basename(path))[0]
| 5,345,994 |
async def test_new_ignored_users_available(
hass, caplog, entry, mock_websocket, setup_plex_server
):
"""Test setting up when new users available on Plex server but are ignored."""
MONITORED_USERS = {"Owner": {"enabled": True}}
OPTIONS_WITH_USERS = copy.deepcopy(DEFAULT_OPTIONS)
OPTIONS_WITH_USERS[MP_DOMAIN][CONF_MONITORED_USERS] = MONITORED_USERS
OPTIONS_WITH_USERS[MP_DOMAIN][CONF_IGNORE_NEW_SHARED_USERS] = True
entry.options = OPTIONS_WITH_USERS
mock_plex_server = await setup_plex_server(config_entry=entry)
server_id = mock_plex_server.machineIdentifier
trigger_plex_update(mock_websocket)
await hass.async_block_till_done()
monitored_users = hass.data[DOMAIN][SERVERS][server_id].option_monitored_users
ignored_users = [x for x in mock_plex_server.accounts if x not in monitored_users]
assert len(monitored_users) == 1
assert len(ignored_users) == 2
for ignored_user in ignored_users:
ignored_client = [
x.players[0]
for x in mock_plex_server.sessions()
if x.usernames[0] == ignored_user
][0]
assert (
f"Ignoring {ignored_client.product} client owned by '{ignored_user}'"
in caplog.text
)
sensor = hass.states.get("sensor.plex_plex_server_1")
assert sensor.state == str(len(mock_plex_server.accounts))
| 5,345,995 |
def get_dnssec_output(hosted_zone_id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetDNSSECResult]:
"""
Resource used to control (enable/disable) DNSSEC in a specific hosted zone.
:param str hosted_zone_id: The unique string (ID) used to identify a hosted zone.
"""
...
| 5,345,996 |
def test_reset_password(client, user_info):
"""A user can reset their password using a link sent to their email."""
new_password = 'New_Password123'
assert new_password != user_info['password']
register_user(client, user_info)
log_out_current_user(client)
with mail.record_messages() as outbox:
rv = client.get(url_for('user.password_recovery'))
rv = client.post(url_for('user.password_recovery'),
data=dict(csrf_token=csrf_token(rv.data),
email=user_info['email'],
captcha='xyzzy'))
message = outbox.pop()
assert message.send_to == {user_info['email']}
soup = BeautifulSoup(message.html, 'html.parser')
token = soup.a['href'].split('/')[-1]
rv = client.get(url_for('user.password_reset', token=token),
follow_redirects=True)
rv = client.post(url_for('do.reset'),
data=dict(csrf_token=csrf_token(rv.data),
user=get_value(rv.data, 'user'),
key=get_value(rv.data, 'key'),
password=new_password, confirm=new_password))
log_out_current_user(client)
user_info['password'] = new_password
log_in_user(client, user_info, expect_success=True)
| 5,345,997 |
def main(out_path, ud_dir, check_parse=False, langs=ALL_LANGUAGES, exclude_trained_models=False, exclude_multi=False,
hide_freq=False, corpus='train', best_per_language=False):
""""
Assemble all treebanks and models to run evaluations with.
When setting check_parse to True, the default models will not be evaluated as they don't have parsing functionality
"""
languages = [lang.strip() for lang in langs.split(",")]
print_freq_tasks = []
if not hide_freq:
print_freq_tasks = ['Tokens']
# fetching all relevant treebank from the directory
treebanks = fetch_all_treebanks(ud_dir, languages, corpus, best_per_language)
print()
print("Loading all relevant models for", languages)
models = dict()
# multi-lang model
multi = None
if not exclude_multi and not check_parse:
multi = load_model('xx_ent_wiki_sm', add_sentencizer=True)
# initialize all models with the multi-lang model
for lang in languages:
models[lang] = [multi] if multi else []
# add default models if we don't want to evaluate parsing info
if not check_parse:
# Norwegian is 'nb' in spaCy but 'no' in the UD corpora
if lang == 'no':
models['no'].append(load_default_model_sentencizer('nb'))
else:
models[lang].append(load_default_model_sentencizer(lang))
# language-specific trained models
if not exclude_trained_models:
if 'de' in models:
models['de'].append(load_model('de_core_news_sm'))
models['de'].append(load_model('de_core_news_md'))
if 'el' in models:
models['el'].append(load_model('el_core_news_sm'))
models['el'].append(load_model('el_core_news_md'))
if 'en' in models:
models['en'].append(load_model('en_core_web_sm'))
models['en'].append(load_model('en_core_web_md'))
models['en'].append(load_model('en_core_web_lg'))
if 'es' in models:
models['es'].append(load_model('es_core_news_sm'))
models['es'].append(load_model('es_core_news_md'))
if 'fr' in models:
models['fr'].append(load_model('fr_core_news_sm'))
models['fr'].append(load_model('fr_core_news_md'))
if 'it' in models:
models['it'].append(load_model('it_core_news_sm'))
if 'nl' in models:
models['nl'].append(load_model('nl_core_news_sm'))
if 'pt' in models:
models['pt'].append(load_model('pt_core_news_sm'))
with out_path.open(mode='w', encoding='utf-8') as out_file:
run_all_evals(models, treebanks, out_file, check_parse, print_freq_tasks)
| 5,345,998 |
def collapse(individual_refs):
"""Collapse references like [C1,C2,C3,C7,C10,C11,C12,C13] into 'C1-C3, C7, C10-C13'.
Args:
individual_refs (string): Uncollapsed references.
Returns:
string: Collapsed references.
"""
parts = []
for ref in individual_refs:
mtch = re.match(r"(?P<part_prefix>\D+)(?P<number>.+)", ref)
if mtch is not None:
part_prefix = mtch.group("part_prefix")
number = mtch.group("number")
try:
number = int(mtch.group("number"))
except ValueError:
pass
parts.append((part_prefix, number))
parts.sort()
def toRef(part):
return "{}{}".format(part[0], part[1])
def make_groups(accumulator, part):
prev = None
if len(accumulator) > 0:
group = accumulator[-1]
if len(group) > 0:
prev = group[-1]
if (prev != None) and (prev[0] == part[0]) and isinstance(prev[1], int) and ((prev[1] + 1) == part[1]):
group.append(part)
accumulator[-1] = group
else:
accumulator.append([part])
return accumulator
groups = reduce(make_groups, parts, [])
groups = map(lambda g: tuple(map(toRef, g)), groups)
collapsed = ""
for group in groups:
if (len(collapsed) > 1) and (collapsed[-2] != ","):
collapsed += ", "
if len(group) > 2:
collapsed += group[0] + "-" + group[-1]
else:
collapsed += ", ".join(group)
return collapsed
| 5,345,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.