query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Gets the current team's score from the API | def _get_current_teams_score(self):
for game in self._get_live_games():
teams_playing = [x['abbreviation'] for index, x in game['teams'].items()]
if self.team in teams_playing:
# Our team is playing in this game, get the score
return int(ga... | [
"def league_scores(self):\n date = datetime.datetime.strftime(self.date, \"%Y%m%d\")\n url = f\"{self.base_url}{self.season}-regular/scoreboard.json?fordate={date}\"\n scores = self.api_request(url)\n return scores['scoreboard']['gameScore']",
"def score():\n\n if request.data:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A callback for when the score has changed | def _score_has_changed(self):
print('The score for {} has changed'.format(self.team))
self.relay_controller.activate_solenoid() | [
"def update_score():\n pass",
"def on_score_change(self):\n return self._on_score_change",
"def _change_score(self, score):\n self.score = score\n\n level = (self.score // 10) + 1\n if level != self.level:\n self.level = level\n print('Level: {}'.format(l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a dict(a2p=arr0, p2a=arr1). Key "a2p" means converting amber order to phenix order Key "p2a" means converting phenix order to amber order | def get_indices_convert_dict(fn):
pdb_inp = pdb.input(file_name=fn)
pdb_hierarchy = pdb_inp.construct_hierarchy()
newids = OrderedDict((atom.id_str(), idx) for (idx, atom) in enumerate(pdb_hierarchy.atoms()))
oldids= OrderedDict((atom.id_str(), idx) for (idx, atom) in enumerate(pdb_inp.atoms()))
return ... | [
"def paramz_to_dict(p):\n return dict([(k.name, np.array(k)) for k in p])",
"def proba_trans_arr(self, i, j):\r\n arr = {}\r\n if self.case_possible(i - 1, j - 1):\r\n if self.case_possible(i - 1, j):\r\n arr[i - 1, j - 1, 1] = (1 - self.p)/2\r\n if self.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Emit a deprecation warning about a gnomerelated reactor. | def deprecatedGnomeReactor(name: str, version: Version) -> None:
stem = DEPRECATION_WARNING_FORMAT % {
"fqpn": "twisted.internet." + name,
"version": getVersionString(version),
}
msg = stem + ". Please use twisted.internet.gireactor instead."
warnings.warn(msg, category=DeprecationWarni... | [
"def warn_deprecated(msg):\n warnings.warn(msg, category=NeuroMDeprecationWarning, stacklevel=3)",
"def deprecated_module(msg):\n warn_deprecated(msg)",
"def deprecation(self, message, *args, **kws):\n self._log(DEPRECATION, message, args, **kws)",
"def dwarning(msg):\n warnings.warn(msg, OTreeDep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clears noise from given image using bilateral Filter. | def filter_image(img):
return cv2.bilateralFilter(img, 9, 50, 50) | [
"def bilateral_filter(im):\n raise NotImplementedError(\"This algorithm will be implemented later!\")",
"def _noise_reduction(binary_image):\n struct_size = 2 # max(round(binary_image.size / 8000000), 2)\n structure = np.ones((struct_size, struct_size))\n #binary_image = ndimage.gaussian_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receives two images to compare, img1 being the original. and a string indictating which error function to use. doesnt assume images are the same size. | def compare_img(img1, img2, err_function="ALL"):
# make sure images are the same shape #
height1, width1, height2, width2 = img1.shape[0], img1.shape[1], img2.shape[0], img2.shape[1]
if img1.shape != img2.shape:
if width1 * height1 > width2 * height2:
img1 = resize_image(img1, width2, h... | [
"def test_SAIBrain_is_diff_old_image_new_image_case_same_images_ok(self):\n # Result : MSE = 0.0\n self.generic_test_SAIBrain_is_diff_old_image_new_image(\"old_image_2.png\", \"new_image_2.png\", True)",
"def compare_images(self, img1, img2):\n if self.debug:\n cv2.imshow('img1', i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to log an event with the given key. If the ``key`` has not exceeded their allotted events, then the function returns ``False`` to indicate that no limit is being imposed. If the ``key`` has exceeded the number of events, then the function returns ``True`` indicating ratelimiting should occur. | def limit(self, key):
if self._debug:
return False
counter = self.database.List(self.name + ':' + key)
n = len(counter)
is_limited = False
if n < self._limit:
counter.prepend(str(time.time()))
else:
oldest = counter[-1]
if ... | [
"def is_throttled(self, key: str) -> bool:\n if self._is_fresh_call(key):\n self.cache[key] = \\\n {\n \"num_of_calls\": 1,\n \"last_call_ts\": datetime.utcnow()\n }\n else:\n self.cache[key][\"num_of_calls\"] +=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function or method decorator that will prevent calls to the decorated function when the number of events has been exceeded for the given time period. It is probably important that you take care to choose an appropriate key function. For instance, if ratelimiting a webpage you might use the requesting user's IP as the k... | def rate_limited(self, key_function=None):
if key_function is None:
def key_function(*args, **kwargs):
data = pickle.dumps((args, sorted(kwargs.items())))
return hashlib.md5(data).hexdigest()
def decorator(fn):
@wraps(fn)
def inner(*ar... | [
"def rate_limit(limit=5, duration=60, by_ip=False, allow_bypass=False):\n\n def decorator(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n settings = api.config.get_settings()\n if not settings.get(\"enable_rate_limiting\", True):\n return f(*args, **kwargs)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get reported total capacity of file system Returns | def get_capacity():
fs.get_capacity() | [
"def get_space_used():\n fs.get_space_used()",
"def capacity(self):\n\t\treturn self.monitor.get_value(self.service, '/InstalledCapacity')",
"def fs_percent_used_capacity(self):\n return self._fs_percent_used_capacity",
"def usedspace(self):\n self.log.info(\"freespace\")\n nbytes = 0\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get space used on file system Returns | def get_space_used():
fs.get_space_used() | [
"def fs_size(fs_path):\n import shutil\n\n total, used, free = shutil.disk_usage(fs_path)\n return total",
"def get_disk_space():\n try:\n return shutil.disk_usage('/')\n except FileNotFoundError:\n logging.error(\n 'Failed to locate OS partition. Could not determine disk size.')",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return detailed HDFS information for path | def info(path):
fs.info(path) | [
"def stat(self, path):\n return libhdfs.hdfsGetPathInfo(self.fs, path).contents",
"def ls_hdfs(path='/'):\n if not path or path[0] != '/':\n path = '/' + path\n return _list_hdfs(path)",
"def _read_hdfs(self):\n\t\traise NotImplementedError()",
"def lsinfo(path):",
"async def _in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine the box grid, the row 'x' and column 'y' are in and return the box grid boundaries (top left, bottom right). | def get_box_grid(x, y):
for grid in GRIDS:
if x >= grid[0][0] and y >= grid[0][1] and \
x <= grid[1][0] and y <= grid[1][1]:
return grid
return None | [
"def bounding_box(self, grid=1):\n supp = self.support\n grid = [np.linspace(s[0], s[1], grid+1) for s in supp]\n X = self.grid_eval(grid)\n X.shape = (-1, self.dim)\n return tuple((X[:, d].min(), X[:, d].max()) for d in range(self.dim))",
"def find_boxes_under_coord(self,x,y):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check through the puzzle array in the range delimited by top left (tl) and bottom right (br) for values in 'potential'. Any value found that is in 'potential' is removed so only missing values remain when it is returned. | def rm_pot(potential, puzzle, tl, br):
for y in range(tl[1], br[1]+1):
for x in range(tl[0], br[0]+1):
if puzzle[y][x] in potential:
potential.remove(puzzle[y][x])
return potential | [
"def update_potential_values(self):\n if self.value is None:\n self.potential_values = [c for c in \"123456789\"]\n for cell in self.neighbors:\n if cell.value in self.potential_values:\n self.potential_values.remove(cell.value)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
assert that calling func(args, kwargs) triggers a DeprecationWarning. | def deprecated_call(func, *args, **kwargs):
warningmodule = py.std.warnings
l = []
oldwarn_explicit = getattr(warningmodule, 'warn_explicit')
def warn_explicit(*args, **kwargs):
l.append(args)
oldwarn_explicit(*args, **kwargs)
oldwarn = getattr(warningmodule, 'warn')
def warn(... | [
"def test_deprecate_args(self):\n @deprecate(arguments={\"bar\": \"use foo instead\"})\n def foo(a, foo=None, bar=None):\n return 2*a\n\n with warnings.catch_warnings(record=True) as w:\n self.assertEqual(foo(1, bar=True), 2,\n \"Decorated funct... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all files required by some base files. | def required_files(self, args):
args_set = set(args)
edge_list = self.__transform_pre(self.__include_deps_supply.get_file_include_deps())
targets = chain((target for (source, target) in edge_list if source in args_set), args_set)
return self.__transform_post(targets) | [
"def file_requirements():\n return library._file_requirements()",
"def files(self):\n\t\t\n\t\tpaths = fileList(self.paths['build'], relative=True)\n\t\tpaths = filterPaths(paths, self.ignorePatterns())\n\t\t\n\t\treturn [File(self, p) for p in paths]",
"def get_files(directory: str):\n include_files = []... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Guess the bean name from a WSDL type. Assume the bean name is equal to the type having the first letter capitalized. | def guessbeanname(self):
t = self.name
return t[0].upper() + t[1:] | [
"def type_from_name(type_name):\n if type_name == 'reference':\n # move import to run time to avoid circular imports\n from pywbemReq import cim_obj\n return cim_obj.CIMInstanceName\n try:\n type_obj = _TYPE_FROM_NAME[type_name]\n except KeyError:\n raise ValueError(\"Unk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the many to one relations (relType == ONE). | def getrelations(self):
return self.getfieldnames('ONE') | [
"def _filter_related_one2one(self, rel):\n field = rel.field\n if isinstance(field, models.OneToOneField):\n if self._join_allowed(rel.parent_model, rel.model, field):\n return rel",
"def many_to_one(table, backref):\n return relationship(table, back_populates=backref, v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the one to many relations (relType == MANY). | def getmanyrelations(self):
return self.getfieldnames('MANY') | [
"def getrelations(self):\n return self.getfieldnames('ONE')",
"def get_relations(self):\n return self.client.call('GET', 'contact_relation', {})",
"def relations(self):\n return set(self.triples()[\"relation\"])",
"def relations(self):\n return self._relations",
"def get_relation... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether the entity is consistent with this entity info. The entity is supposed to be a subclass of Entity. Report any abnormalities as warnings to the logger. Return the number of warnings emitted. | def check(self, entity):
nwarn = 0
if entity is None:
return nwarn
if not issubclass(entity, Entity):
raise TypeError("invalid argument %s, expect subclass of Entity" %
entity)
cname = entity.__name__
beanname = self.beanna... | [
"def check(self):\n\n nwarn = 0\n\n # Check that the set of entity types is the same as in the\n # schema.\n schemanames = set(self.schema.keys())\n clientnames = set(self.client.typemap.keys())\n missing = schemanames - clientnames\n if missing:\n log.war... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for entities defined at the server. Return a dict with type names as keys and EntityInfo objects as values. | def getentities(self):
entities = {}
# The following will create lots of errors in suds.client, one
# for every type that is not an entity. Disable their logger
# temporarily to avoid cluttering the log.
sudslog = logging.getLogger('suds.client')
sudssav = sudslog.disab... | [
"def entity_types(self):\n r = fapi.get_entity_types(self.namespace, self.name, self.api_url)\n fapi._check_response_code(r, 200)\n return r.json().keys()",
"def get_entities(self, scope='all', metadata=None):\n # TODO: memoize results\n layouts = self._get_layouts_in_scope(scop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check consistency of the ICAT client with the server schema. Report any abnormalities as warnings to the logger. Returns the number of warnings emitted. | def check(self):
nwarn = 0
# Check that the set of entity types is the same as in the
# schema.
schemanames = set(self.schema.keys())
clientnames = set(self.client.typemap.keys())
missing = schemanames - clientnames
if missing:
log.warning("missing e... | [
"def checkExceptions(self):\n\n nwarn = 0\n\n icatExceptionType = self.client.factory.create('icatExceptionType')\n schemaexceptions = set(icatExceptionType.__keylist__)\n clientexceptions = set(icat.exception.IcatExceptionTypeMap.keys())\n missing = schemaexceptions - clientexcep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check consistency of exceptions. Check that all icatExceptionTypes defined in the WSDL have a corresponding exception class defined in icat.exception. Report missing exceptions as a warning to the logger. Return the number of warnings emitted. | def checkExceptions(self):
nwarn = 0
icatExceptionType = self.client.factory.create('icatExceptionType')
schemaexceptions = set(icatExceptionType.__keylist__)
clientexceptions = set(icat.exception.IcatExceptionTypeMap.keys())
missing = schemaexceptions - clientexceptions
... | [
"def count_error_types(graph: BELGraph) -> typing.Counter[str]:\n return Counter(exc.__class__.__name__ for _, exc, _ in graph.warnings)",
"def check(self):\n\n nwarn = 0\n\n # Check that the set of entity types is the same as in the\n # schema.\n schemanames = set(self.schema.keys(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate Python source code matching the ICAT schema. Generate source code for a set of classes that match the entity info found at the server. The source code is returned as a string. The Python classes are created as a hierarchy. It is assumed that there is one abstract base type which is the root of the genealogy tr... | def pythonsrc(self, genealogyrules=None, baseclassname='Entity'):
if genealogyrules is None:
genealogyrules = [(r'','entityBaseBean')]
tree = self._genealogy(genealogyrules)
base = [t for t in tree if tree[t]['base'] is None][0]
self.schema[base].classname = baseclassname
... | [
"def genCode(self, fileName, allowedTypes, genGraph = 1, isRootNode = 0, \r\n metaModelName = None, export = 0, newTypes = None, \r\n nodesToGenList = [], openModelStringList=[], attrGenFix=False):\r\n file = open(fileName, \"w+t\" )\r\n\r\n dir, fil = os.path.split(fileName)\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
updates .coveralls.yml file to allow upload of coverage report | def update_coveralls_config(
path_to_coverage,
coveralls_token,
token_key='repo_token',
):
try:
with open(path_to_coverage, 'r') as cover_fh:
raw_file = cover_fh.read()
except FileNotFoundError:
raw_file = ''
# check if repo_token is already in .coveralls... | [
"def _update_coverage(cov_value):\n coverage_path = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n 'coverage'\n )\n\n with open(coverage_path, \"w\") as f:\n f.write(str(cov_value))",
"def set_coverage(self, coverage): \n self.coverage = coverage\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
turn multiline config entry into a list of commands | def parse_command_list(config_str):
return [command for command in config_str.splitlines() if command] | [
"def config_changes(cli):\n result = []\n in_config = False\n for line in cli.splitlines():\n if not in_config and line == 'Building configuration...':\n in_config = True\n elif in_config:\n result.append(line)\n\n return '\\n'.join(result)",
"def commands_from_in_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
atexit handler for deactivating and removing local venv even if tools crash | def atexit_deactivate_venv(
venv_name,
cwd,
logger=p_logging.DEFAULT_LOGGER
): # pragma: no cover
logger.info('Cleaning up venv post-test')
logger.info('--removing venv')
try:
rm_log = local['rm']('-rf', path.join(cwd, venv_name))
logger.debug(rm_log)
except Exc... | [
"def env_cleanup(self):\n pass",
"def teardown(self):\n self.logger.info('Tearing down file server vm')\n self.local_env.execute('uninstall', task_retries=40,\n task_retry_interval=30)",
"def cleanup():\r\n assert env.host_string\r\n\r\n # Search for active e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the extension validation is working properly | def test_extensions(self):
field = TypedFileField(required=False, ext_whitelist=self.good_extensions)
for ext in self.good_extensions:
name = 'somefooname.%s' % ext
file = UploadedFile(name=name, size=1)
assert field.clean(file) is file
for ext in self.bad_e... | [
"def test_upload_manager_validates_file_ext(self):\n self.assertTrue(UploadManager(self.app).driver('disk').accept('jpg', 'png').validate_extension('test.png'))",
"def test_update_extension(self):\n pass",
"def test_get_built_in_extension(self):\n\n spec = {\n '$ext': {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the mimetypes are validate correctly | def test_mimetypes(self):
field = TypedFileField(required=False, type_whitelist=self.good_types, use_magic=False)
for t in self.good_types:
name = 'somefooname'
file = UploadedFile(name=name, size=1, content_type=t)
assert field.clean(file) is file
for t in ... | [
"def test_mimetypes_magic(self, mock_get_content_type):\n\n def get_content_type(value):\n return value.content_type\n\n mock_get_content_type.side_effect = get_content_type\n\n field = TypedFileField(required=False, type_whitelist=self.good_types, use_magic=True)\n\n for t in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the mimetypes are validate correctly | def test_mimetypes_magic(self, mock_get_content_type):
def get_content_type(value):
return value.content_type
mock_get_content_type.side_effect = get_content_type
field = TypedFileField(required=False, type_whitelist=self.good_types, use_magic=True)
for t in self.good_typ... | [
"def test_mimetypes(self):\n field = TypedFileField(required=False, type_whitelist=self.good_types, use_magic=False)\n\n for t in self.good_types:\n name = 'somefooname'\n file = UploadedFile(name=name, size=1, content_type=t)\n assert field.clean(file) is file\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure ``ValidationError`` is raised if uploaded file has no mimetype | def test_no_mimetype(self):
field = TypedFileField(required=False, type_whitelist=self.good_types, use_magic=False)
for t in self.good_types:
name = 'somefooname'
file = UploadedFile(name=name, size=1, content_type=t)
del file.content_type
with pytest.rai... | [
"def test_no_mimetype_magic(self, mock_get_content_type):\n mock_get_content_type.side_effect = ValueError\n\n field = TypedFileField(required=False, type_whitelist=self.good_types)\n\n for t in self.good_types:\n name = 'somefooname'\n file = UploadedFile(name=name, size=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure ``ValidationError`` is raised if uploaded file has no mimetype | def test_no_mimetype_magic(self, mock_get_content_type):
mock_get_content_type.side_effect = ValueError
field = TypedFileField(required=False, type_whitelist=self.good_types)
for t in self.good_types:
name = 'somefooname'
file = UploadedFile(name=name, size=1, content_t... | [
"def test_no_mimetype(self):\n field = TypedFileField(required=False, type_whitelist=self.good_types, use_magic=False)\n\n for t in self.good_types:\n name = 'somefooname'\n file = UploadedFile(name=name, size=1, content_type=t)\n del file.content_type\n wit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize class with lfp data | def __init__(self, lfp_data):
self.lfp_data = lfp_data | [
"def __init__(self):\n self.data = []\n self.headers = []\n self.lamps_data = []\n self.lamps_headers = []",
"def __init__(self, data=None):\n if data:\n # We have to preserve the original fw_info_leaf bytes in order to preserve\n # hash equivalence with what is stored in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove temporal mean from each trial | def remove_temporal_mean(self):
if not hasattr(self, 'detrended_data'):
self.detrend_data()
self.mean_removed_data = self.detrended_data - \
np.mean(self.detrended_data, axis=-1, keepdims=True) | [
"def remove_temporal_mean(self):\n if not hasattr(self,'detrended_data'):\n self.detrend_data()\n self.mean_removed_data = self.detrended_data - \\\n np.mean(self.detrended_data,axis=-1,keepdims=True)",
"def subtract_mean_across_trials(self):\n if not hasattr(self,'s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Divide by temporal standard deviation | def divide_by_temporal_std(self):
if not hasattr(self, 'mean_removed_data'):
self.remove_temporal_mean()
self.std_divided_data = self.mean_removed_data / \
np.std(self.mean_removed_data, axis=-1, keepdims=True) | [
"def divide_by_temporal_std(self):\n if not hasattr(self,'mean_removed_data'):\n self.remove_temporal_mean()\n self.std_divided_data = self.mean_removed_data / \\\n np.std(self.mean_removed_data,axis=-1,keepdims=True)",
"def STDDEV(df, time_period=5, nb_dev=1):\n close =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subtract mean across trials from each trial (for each timepoint) | def subtract_mean_across_trials(self):
if not hasattr(self, 'std_divided_data'):
self.divide_by_temporal_std()
self.mean_across_trials_subtracted_data = \
self.std_divided_data - \
np.mean(self.std_divided_data, axis=1, keepdims=True) | [
"def subtract_mean_across_trials(self):\n if not hasattr(self,'std_divided_data'):\n self.divide_by_temporal_std()\n self.mean_across_trials_subtracted_data = \\\n self.std_divided_data - \\\n np.mean(self.std_divided_data,axis=1,keepdims=True)",
"def avgtr(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Divide by standard deviation across trials (for each timepoint) | def divide_by_std_across_trials(self):
if not hasattr(self, 'mean_across_trials_subtracted_data'):
self.subtract_mean_across_trials()
self.std_across_trials_divided_data = \
self.mean_across_trials_subtracted_data / \
np.std(self.mean_across_trials_subtracted_data,
... | [
"def divide_by_std_across_trials(self):\n if not hasattr(self,'mean_across_trials_subtracted_data'):\n self.subtract_mean_across_trials()\n self.std_across_trials_divided_data = \\\n self.mean_across_trials_subtracted_data / \\\n np.std(self.mean_across_trials_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
alpha = threshold for single test (will be Bonferroni corrected internally) wanted_fraction = minimum fraction of tests that should be significant (stationary) | def run_adfuller_test(preprocessed_data, alpha=0.05, wanted_fraction=0.95):
inds = list(np.ndindex(preprocessed_data.shape[:-1]))
def return_adfuller_pval(this_ind): return adfuller(
preprocessed_data[this_ind])[1]
pval_list = np.array(parallelize(return_adfuller_pval, inds, n_jobs=30))
alpha =... | [
"def run_adfuller_test(preprocessed_data, alpha = 0.05, wanted_fraction = 0.95):\n inds = list(np.ndindex(preprocessed_data.shape[:-1]))\n return_adfuller_pval = lambda this_ind: adfuller(preprocessed_data[this_ind])[1]\n pval_list = np.array(parallelize(return_adfuller_pval, inds, n_jobs=30))\n alpha =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate granger causality time_series = time x trials x channels | def calc_granger(time_series,
time_halfbandwidth_product=1,
sampling_frequency=1000,
time_window_duration=0.3,
time_window_step=0.05,
):
m = Multitaper(
time_series,
sampling_frequency=sampling_frequency, # in Hz
... | [
"def granger_causality(self, sample_dict: Dict):\n A_all = 0\n all_types = sample_dict['Cs'][:, 0]\n all_features = sample_dict['FCs']\n if all_features is None:\n all_features = self.emb_event(all_types)\n for m in range(self.num_base):\n u_all = self.basis[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
preprocessed_data = (n_channels, n_trials, n_timepoints) sampling_frequency = in Hz n_shuffles = number of shuffles to perform wanted_window = window to calculate granger causality in alpha = significance level multitaper_time_window_duration = duration of time window for multitaper multitaper_time_window_step = step o... | def __init__(self,
good_lfp_data,
# preprocessed_data,
sampling_frequency=1000,
n_shuffles=500,
wanted_window=[1500, 4000],
alpha=0.05,
multitaper_time_halfbandwidth_product=1,
multita... | [
"def __init__(self, \n good_lfp_data,\n #preprocessed_data,\n sampling_frequency=1000,\n n_shuffles=500,\n wanted_window = [1500,4000],\n alpha = 0.05,\n multitaper_time_window_duration=0.3,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate bootstrapped actual granger causality to allow for estimation of error | def calc_granger_actual(self):
if not hasattr(self, 'input_data'):
self.preprocess_and_check_stationarity()
# input_data shape = (n_timepoints, n_trials, n_channels)
# Calculate as many bootstrapped samples as n_shuffles
trial_inds = np.random.randint(
0, self... | [
"def granger_causality(self, sample_dict: Dict):\n A_all = 0\n all_types = sample_dict['Cs'][:, 0]\n all_features = sample_dict['FCs']\n if all_features is None:\n all_features = self.emb_event(all_types)\n for m in range(self.num_base):\n u_all = self.basis[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate shuffled granger causality | def calc_granger_shuffle(self):
if not hasattr(self, 'input_data'):
self.preprocess_and_check_stationarity()
temp_series = [np.stack([np.random.permutation(x)
for x in self.input_data.T]).T
for i in trange(self.n_shuffles)]
outs... | [
"def calc_granger_shuffle(self):\n if not hasattr(self,'input_data'):\n self.preprocess_and_check_stationarity()\n temp_series = [np.stack([np.random.permutation(x) \\\n for x in self.input_data.T]).T \\\n for i in trange... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mask is True when granger causality is NOT SIGNIFICANT | def get_granger_sig_mask(self):
if not hasattr(self, 'percentile_granger'):
self.calc_shuffle_threshold()
if not hasattr(self, 'granger_actual'):
self.calc_granger_actual()
mean_granger_actual = np.mean(self.granger_actual, axis=0)
self.masked_granger = np.ma.mask... | [
"def mask(self):",
"def get_mask(A):\n return A != -1",
"def mask_act(self):\n # mask_act = np.zeros([self.ypix,self.xpix]).astype('bool')\n # rb, rt, rl, rr = self.ref_info\n # mask_act[rb:-rt,rl:-rr] = True # This doesn't work if rr or rt are 0!!\n return ~self.mask_ref",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A list of return codes of all processes launched by the pipe | def returncodes(self):
for p in self.processes:
p.wait()
codes = [p.poll() for p in self.processes]
if set(codes) == set([0]):
return []
return codes | [
"def status(self):\n r = []\n for host in self.hosts:\n history = self.get_history(host)\n if history:\n history = history[-1]\n r.append((host, history.get('exitcode')))\n return r",
"def list_active_processes():\n return psutil.process_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
combined stderr of all processes | def stderr(self):
if self._stderr is None:
stderr = [p.stderr.read() for p in self.processes if p.stderr]
output = b'\n'.join(stderr).strip()
if not isinstance(output, str):
output = output.decode(self.encoding, 'ignore')
self._stderr = output
... | [
"def stderr(self):\r\n self.wait()\r\n return self._stderr",
"def read_stderr():\n for line in remote.stderr:\n print(name + \": \" + line.rstrip())",
"def print_error(process_name, stdout, stderr):\n\n print(\">! ERROR\")\n print(\"- STDOUT START -\")\n for line in iter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run processes in background. Return the last piped Popen object | def bg(self):
p = None
self.processes = []
self._stderr = None
stdin = sys.stdin
cmds = self.commands
if [c for c in cmds if c._cmd_args[:1] == ['sudo']]:
check_sudo()
for cmd in cmds:
if isinstance(cmd, Stdin):
stdin = cm... | [
"def popen(self, args, **kwargs):\n self.log.debug(\"popen %s\", ' '.join(args))\n return vaping.io.subprocess.Popen(args, **kwargs)",
"def subproc(*args, **kwargs):\n return subprocess.Popen(*args, \n shell=False, close_fds=True,\n stdout=PIPE, stdin=None, stderr=PIPE,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate chut scripts contained in location | def chutifab(self, *args):
ll = logging.getLogger(posixpath.basename(sys.argv[0]))
level = ll.level
ll.setLevel(logging.WARN)
if not args:
args = ['.']
for location in args:
Generator(destination='.chutifab')(location)
ll.setLevel(level)
se... | [
"def main():\n ScriptDirectory(op.split(__file__)[0])()",
"def emit_scripts(templates):\n\n for platform, ver, apps, deps in load_deps_transformed():\n shell = \"batch\" if platform[\"os\"] in [\"windows\"] else \"shell\"\n suffix = \".bat\" if shell == \"batch\" else \".sh\"\n ident = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload a script and run it. ``args`` are used as command line arguments. ``kwargs`` are passed to `fabric`'s `run` | def run(self, script, *args, **kwargs):
return self._run('run', script, *args, **kwargs) | [
"def run_local(self, args):\n snapshot = str(args.snapshot) if args.snapshot else None\n release = args.release or DEFAULT_RELEASE\n\n self.run_build_script(\n snapshot=snapshot,\n release=release,\n validate=args.validate,\n s3_bucket=args.s3_bucket,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload a script and run it using sudo. ``args`` are used as command line arguments. ``kwargs`` are passed to `fabric`'s `sudo` | def sudo(self, script, *args, **kwargs):
return self._run('sudo', script, *args, **kwargs) | [
"def run(*args, **kwargs):\n if MODE == MODE_SUDO:\n return fabric.api.sudo(*args, **kwargs)\n else:\n return fabric.api.run(*args, **kwargs)",
"def sudo(*args, **kwargs):\n if os.geteuid() == 0:\n run(*args, **kwargs)\n else:\n run(*args, sudo='root', **kwargs)",
"def sudo_(*args, *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a random ktuple of unique elements selected from population. | def rand_tuple(population, k, required_inds=None):
if isinstance(population, int):
population = xrange(population)
if required_inds is None:
required_inds = []
if not isinstance(required_inds, collections.Iterable):
required_inds = [required_inds]
t = set(random.sample(populati... | [
"def random_sample(population, k):\n return random.sample(population, k)",
"def random_generic_vertex_set(self, k, E=None):\n if E is None:\n E = set()\n S = [None for _ in xrange(k)]\n E = list(E)\n for i in xrange(k):\n S[i] = (ifilter(lambda x: x not in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a CNAME RR is present at a node, no other data should be present; this ensures that the data for a canonical name and its aliases cannot be different." | def check_for_cname(record):
CNAME = cydns.cname.models.CNAME
if hasattr(record, 'label'):
if CNAME.objects.filter(domain=record.domain,
label=record.label).exists():
raise ValidationError("A CNAME with this name already exists.")
else:
if CNAME.ob... | [
"def test_cname_response(self):\n fqdn = \"cname.github.com\"\n answer = self.resolver.query(fqdn, \"CNAME\")\n for rr in answer:\n if rr.target.to_text() != \"github.map.fastly.net.\":\n raise TestException(\"Unexpected target for {0}: {1}\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If an object's domain is delegated it should not be able to be changed. Delegated domains cannot have objects created in them. | def check_for_delegation(record):
try:
if not record.domain.delegated:
return
except ObjectDoesNotExist:
return
if not record.pk: # We don't exist yet.
raise ValidationError("No objects can be created in the {0}"
"domain. It is delegated."
... | [
"def test_hideDisabledProxies(self):\n\n # Check proxies empty right now\n principal01 = yield self.principalRootResource.principalForUID((yield self.userUIDFromShortName(\"user01\")))\n self.assertTrue(len((yield principal01.proxyFor(False))) == 0)\n self.assertTrue(len((yield principal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the taxicab distance between two intersections. >>> times_square = intersection(46, 7) >>> ess_a_bagel = intersection(51, 3) >>> taxicab(times_square, ess_a_bagel) 9 >>> taxicab(ess_a_bagel, times_square) 9 | def taxicab(a, b):
"*** YOUR CODE HERE ***"
return abs(street(a)-street(b)) + abs(avenue(a)-avenue(b)) | [
"def taxicab(a, b):\n street_1, street_2 = street(a), street(b)\n avenue_1, avenue_2 = avenue(a), avenue(b)\n return abs(street_1 - street_2) + abs(avenue_1 - avenue_2)",
"def taxicab(a, b):\n return abs(street(a) - street(b)) + abs(avenue(a) - avenue(b))",
"def taxicab(a, b):\n \"*** YOUR CODE H... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the value of G(n), computed recursively. >>> g(1) 1 >>> g(2) 2 >>> g(3) 3 >>> g(4) 10 >>> g(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g', ['While', 'For']) True | def g(n):
"*** YOUR CODE HERE ***"
if n <= 3:
return n
else:
return g(n-1) + 2*g(n-2) + 3*g(n-3) | [
"def g(n):\n if n in (1,2,3):\n return n\n else:\n return g(n-1) + 2*g(n-2) + 3*g(n-3)",
"def g(n):\r\n if n <= 3:\r\n return n\r\n else:\r\n return (g(n - 1)) + (2 * g(n - 2)) + (3 * g(n - 3))",
"def g(n):\n \"*** YOUR CODE HERE ***\"\n if n < 4:\n return n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the value of G(n), computed iteratively. >>> g_iter(1) 1 >>> g_iter(2) 2 >>> g_iter(3) 3 >>> g_iter(4) 10 >>> g_iter(5) 22 >>> from construct_check import check >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion']) True | def g_iter(n):
if n <= 3:
return n
else:
g_n_1, g_n_2, g_n_3 = 3, 2, 1
# always update the g_i until reach the final n
for i in range(4,n+1):
g_i = g_n_1 + 2*g_n_2 + 3*g_n_3
# update the g(n-1), g(n-2), g(n-3)
g_n_1, g_n_2, g_n_3 = g_i, g_n_1, g_n_2
return g_i
"*** YOUR CODE HERE ***" | [
"def g_iter(n):\n\tpass",
"def g_iter(n):\n g = 0\n g1, g2, g3 = 1, 2, 3\n g_3, g_2, g_1 = g1, g2, g3\n if n == 1: g = g1\n elif n == 2: g = g2\n elif n == 3: g = g3\n for term in range(4, n + 1):\n g = g_1 + 2 * g_2 + 3 * g_3 # g = g(n-1) + 2 * g(n-2) + 3 * g(n-3)\n g_3, g_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if at least one of the digits of k is a 7, False otherwise. >>> has_seven(3) False >>> has_seven(7) True >>> has_seven(2734) True >>> has_seven(2634) False >>> has_seven(734) True >>> has_seven(7777) True | def has_seven(k):
if k % 10 == 7:
return True
elif k < 10:
return False
else:
return has_seven(k // 10) | [
"def has_seven(k):\n # return \"7\" in str(k)\n if not k:\n return False\n if k % 10 == 7:\n return True\n else:\n return has_seven(k//10)",
"def has_seven(k):\n if k % 10 == 7:\n return True\n elif k < 10:\n return False\n else:\n return has_seven(k ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of ways to make change for amount. >>> count_change(7) 6 >>> count_change(10) 14 >>> count_change(20) 60 >>> count_change(100) 9828 | def count_change(amount):
options = [2**i for i in range(amount+1) if 2**i <= amount]
options = sorted(options, reverse = True)
length = len(options)
# print(length)
def helper(remains, i, options, length):
# loop until reaching the smallest coin
if i >= length :
return 0
# check the remains
if remains... | [
"def count_change(amount):\n coins = [pow(2, x) for x in range(0, amount//2 + 1) if pow(2, x) <= amount]\n\n def count_rec(amount, index):\n if index < 0:\n return 0\n if amount < 0:\n return 0\n if amount == 0:\n return 1\n else:\n with_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementation of Focal Loss from the paper in multiclass classification | def categorical_focal_loss(gamma=2.0, alpha=0.25):
def focal_loss(y_true, y_pred):
# Define epsilon so that the backpropagation will not result in NaN for 0 divisor case
epsilon = backend.epsilon()
# Add the epsilon to prediction value
#y_pred = y_pred + epsilon
# Clip the pr... | [
"def cls_loss(self, preds: list) -> float:\n _, pred_cls, _, _, _, _ = preds\n\n target = torch.zeros_like(pred_cls, device=\"cuda:0\")\n focal_loss = WeightedFocalLoss()\n\n return focal_loss(pred_cls, target)",
"def focal_loss1_multi_category(y_true, y_pred, alpha, gamma=2.0):\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform actions on all infected members of the population in a random order | def turn(grid):
# Select infected people
rows, cols = np.where(grid == 1)
#print(f"Infected at {rows}, {cols}")
# In random order, go through each infected
idx = np.arange(len(rows))
np.random.shuffle(idx)
for i in idx:
# Chance to heal
if np.random.binomial(1, heal_rate):
... | [
"def process(self, world_object: World) -> None:\n for eater in world_object.worms_by_initiative:\n targets = world_object.food_at(eater.coordinates)\n if len(targets) != 0:\n target = random.choice(targets)\n eater.eat(target)",
"def mutate_all(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removes the old repo in server and clones a new one. the configures the host. | def flush_repo():
server = get_server()
run("rm -rf %(project_name)s" % env)
git.clone()
server.setup() | [
"def git_clone_target_repo(self):\r\n self.repo = git.Repo.clone_from(self.target_repo_url, self.local_gitlab_runner_repo)\r\n print(\"Cloning Repo - completed ....\")",
"def init_remote_site():\n run(\"git clone %s\" % _get_remote_repo_dir())",
"def clone_repo():\r\n run('git clone %(reposi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a list with items with the same student | def get_all_by_student(self, stud_id):
l = []
for item in self._items:
if item.get_student() == stud_id:
l.append(item)
return l[:] | [
"def students(self):\n\t\treturn self.grade_set.all().distinct()",
"def find_duplicate(student_list):\r\n place_holder = student_info('null', 'null', '0', '0')\r\n current = place_holder\r\n dupe = []\r\n final = []\r\n for student in student_list:\r\n previous = current\r\n current =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a list with items with the same discipline | def get_all_by_discipline(self, disc_id):
l = []
for i in self._items:
if i.get_id_disciplina() == disc_id:
l.append(i)
return l[:] | [
"def deduped(items):\n \n return list(set(items))",
"def filter_dups(lista):\n list_uniq = []\n for list_item in lista:\n if list_item not in list_uniq:\n list_uniq.append(list_item)\n return list_uniq",
"def find_discipline(self, did):\n aux = my_filter(self._discipline_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sliding window algorithm realization Output 'segments' contains start and end indexes for each step Assumption data is contiguous data | def segment_sliding_window(data, winSizeMillisecond=1000, stepSizeMillisecond=100):
logger.info("Sliding window with win size %.2f second and step size %.2f second",
winSizeMillisecond, stepSizeMillisecond)
if stepSizeMillisecond <= 0:
raise ValueError("Step size must be larger t... | [
"def getMovingWindowSegments(data, windowSize):\n segmentCount = len(data) - windowSize\n segments = [None] * segmentCount\n for i in range(segmentCount):\n segments[i] = data[i:i+windowSize]\n return segments",
"def _sliding_windows(data, seq_length, future=1):\n x = []\n y = []\n\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert django model to geojson | def to_geojson(model, contrib_id):
feature_collection = []
for record in model.objects.filter(contributer_id=contrib_id):
try:
properies = {
"name": record.name,
"address": record.address,
"email": record.email,
"website": recor... | [
"def return_geo_json(self):\n self.pull_update()\n dengue = Dengue.objects.all()\n dengue_json = json.loads(serialize('geojson', dengue))\n for x in dengue_json['features']:\n x['properties']['type'] = 'dengue'\n return dengue_json",
"def as_geojson(self):\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the candidates as a simple string | def cand_str(self):
return "".join([str(x) for x in self.cands]) | [
"def candidates(self,state):\n cmd = 'select names.dem,names.gop,names.ind,names.incum from names LEFT JOIN abbr on names.state = abbr.code where abbr.full = \"'+state+'\";'\n self.cur.execute(cmd)\n cand = np.array((self.cur.fetchall())[0])\n for i in range(len(cand)):\n cand... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disables provided function from one or multiple channels which are specified. A function can be any of the commands, plugins or galaxies which are allowed to be disabled. | async def disable(self, ctx, function: typing.Union[CommandConverter, PluginConverter, GalaxyConverter],
*channels: discord.TextChannel):
channels = channels or (ctx.channel, )
await ctx.guild_profile.permissions.disable_function(function, channels)
# noinspection PyUnresol... | [
"def disable(func):\n return func",
"def disable(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n return func(*args, **kwargs)\n\n return wrapper",
"async def disable_channel(self, ctx, *channels: discord.TextChannel):\n channels = channels or (ctx.channel, )\n await ctx.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables provided function in all of the specified channels. A function can be any of the commands, plugins or galaxies. | async def enable(self, ctx, function: typing.Union[CommandConverter, PluginConverter, GalaxyConverter],
*channels: discord.TextChannel):
channels = channels or (ctx.channel, )
await ctx.guild_profile.permissions.enable_function(function, channels)
# noinspection PyUnresolved... | [
"def _enable_channels(self) -> None:\n for ch in self.active_channels:\n path = f\"qachannels_{ch}_\"\n self.set(path + \"input_on\", 1)\n self.set(path + \"output_on\", 1)",
"async def enable_channel(self, ctx, *channels: discord.TextChannel):\n channels = channels ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disables bot commands and most of its automatic messages in current or provided channels. | async def disable_channel(self, ctx, *channels: discord.TextChannel):
channels = channels or (ctx.channel, )
await ctx.guild_profile.permissions.disable_channels(channels)
await ctx.send_line(f"{ctx.emotes.web_emotion.galka} Bot commands and messages has been disabled in specified channels.") | [
"async def disable(self, ctx, function: typing.Union[CommandConverter, PluginConverter, GalaxyConverter],\n *channels: discord.TextChannel):\n channels = channels or (ctx.channel, )\n await ctx.guild_profile.permissions.disable_function(function, channels)\n # noinspection ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables back bot commands and its automatic messages in current or provided channels if it was disabled previously. | async def enable_channel(self, ctx, *channels: discord.TextChannel):
channels = channels or (ctx.channel, )
await ctx.guild_profile.permissions.enable_channels(channels)
await ctx.send_line(f"{ctx.emotes.web_emotion.galka} Bot commands and messages has been enabled in specified channels.") | [
"def func(self):\n from evennia.comms.models import ChannelDB\n\n caller = self.caller\n if self.args not in (\"on\", \"off\"):\n return super(CmdArxAllCom, self).func()\n if self.args == \"on\":\n # get names of all channels available to listen to\n # an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Name scope. Must be defined by implementations. | def name_scope(self):
pass | [
"def scope(self, name):\r\n raise NotImplementedError",
"def _set_name_scope(self):\n if self.name is None:\n self._name_scope = self.__class__.__name__\n elif self.name == '<lambda>':\n self._name_scope = 'lambda'\n else:\n # E.g. '_my_loss' => 'my_loss'\n self._name_scope = self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether to dynamically check the number of anchors generated. Can be overridden by implementations that would like to disable this behavior. | def check_num_anchors(self):
return True | [
"def num_anchors_per_location(self):\n pass",
"def adjust_anchors(self):\n pass",
"def is_anchor_valid(self):\n return self.properties.get('IsAnchorValid', None)",
"def setAnchorsManual(self):\n status = self.pozyx.clearDevices(self.remote_id)\n for anchor in self.anchors:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of anchors per spatial location. | def num_anchors_per_location(self):
pass | [
"def num_anchors_per_localization(self):\n num_rot = len(self._rotations)\n num_size = np.array(self._sizes).reshape([-1, 3]).shape[0]\n return num_rot * num_size",
"def number_of_locations(self):\n return self._number_of_locations",
"def locations_count(self):\n return len(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that correct number of anchors was generated. | def _assert_correct_number_of_anchors(self, anchors_list,
feature_map_shape_list):
expected_num_anchors = 0
actual_num_anchors = 0
for num_anchors_per_location, feature_map_shape, anchors in zip(
self.num_anchors_per_location(), feature_map_shape_list, anchors... | [
"def check_num_anchors(self):\n return True",
"def test_backlinks_redirects_length(self):\n self.assertLength(self.backlinks, 1)\n self.assertLength(self.references, 1)\n self.assertLength(self.nofollow, 1)",
"def test_generation_length(self):\n for i in range(1, 20, 3):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run cfg2json() on a predefined list of .cfg files | def batch_run_cfg2json():
cfg_path = os.environ.get("CFG_FILE_PATH")
cfg_list = ['any_n1.cfg',
'ir_grism_n2.cfg',
'ir_grism_n4.cfg',
'ir_any_n2.cfg',
'ir_any_n4.cfg',
'uvis_any_n2.cfg',
'uvis_any_n4.cfg',
... | [
"def export_all_configs_to_json(output_dir=\"./\"):\n for config_name in [\"lbd_theory\", \"lbd_onefifth\", \"lbd_p_c\", \"lbd1_lbd2_p_c\"]:\n config_to_json(config_name, json_file=output_dir + \"/\" + config_name + \".json\")",
"def build_configs():",
"def converter_to_JSON(config_txt_file, config_JS... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reformat userspecifed input json file to use standard (indent = 4) format | def reformat_json_file(infilename, outfilename, clobber=False):
# open input json file
with open(infilename) as json_file:
json_string = json_file.read()
json_data = json.loads(json_string)
# see if output file already exists and determine course of action
if os.path.exists(outfilename)... | [
"def reformat_json(file_path: str):\n orig_data = get_data(file_path)\n with open(file_path, \"w\") as f:\n f.write(json.dumps(orig_data, indent=4))",
"def collapse_json(text, indent=4):\n initial = \" \" * indent\n out = [] # final json output\n sublevel = [] # accumulation list for suble... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse attributes buffer into a list of (type, data) tuples. | def parse_attrs(buf):
attrs = []
while buf:
t = ord(buf[0])
l = ord(buf[1])
if l < 2:
break
d, buf = buf[2:l], buf[l:]
attrs.append((t, d))
return attrs | [
"def _get_attributes(self):\n\n attributes = []\n regex = re.compile(\"\"\"\\s*attribute\\s+(?P<type>\\w+)\\s+\"\"\"\n \"\"\"(?P<name>\\w+)\\s*(\\[(?P<size>\\d+)\\])?\\s*;\"\"\")\n for m in re.finditer(regex,self._code):\n size = -1\n gtype = Shad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current userdefined configuration from the database | def get_user_config():
config = models.Config.query.get(0)
if config is None:
config = models.Config()
config.id = 0
config.save()
return config | [
"def get_config(self):\n return self.db_config",
"def user_config(self):\n return self._new_user_config",
"def get_config():\n CONFIG.clear() #clear config\n sql=\"SELECT * FROM config\"\n conn=sqlite3.connect(CONNECTION_STRING)\n c=conn.cursor()\n c.execute(sql)\n results=c.fetc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get an i18ned message from the appropriate json file for the given key. | def get_json_message(message_key):
file_path = (os.getcwd() + '/ufo/static/locales/' +
flask.session['language_prefix'] + '/messages.json')
try:
with open(file_path) as json_file:
messages = json.load(json_file)
return messages[message_key]
except:
return message_key | [
"def get(self, key, domain=None, language=None, context=None):\n\n if domain is None:\n if self.default_domain is None:\n raise ValueError('No domain given!')\n domain = self.default_domain\n messages = self.get_domain(domain, language)\n\n if not key in mes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make the resources for the oauth configuration component. | def make_oauth_configration_resources_dict():
config = get_user_config()
return {
'config': config.to_dict(),
'oauth_url': oauth.getOauthFlow().step1_get_authorize_url(),
} | [
"def _get_oauth_configration_resources_dict(config, oauth_url):\n return {\n 'config': config.to_dict(),\n 'oauth_url': oauth_url,\n }",
"def defineResources():\n # Read the resources.cfg file and add all resource locations in it\n cf = ogre.ConfigFile()\n cf.load(\"resources.cfg\")\n seci = c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine the language prefix using the language header. | def determine_language_prefix():
# TODO(eholder): Figure out a more appropriate way to map the header into
# our set of prefixes. Since I don't know what those prefixes are yet, this
# is intentionally very generic. I also need to decide if this should just be
# done once as part of the login flow rather than c... | [
"def test_prefix_matching(self):\n best = get_best_language('en-gb, es;q=0.2')\n eq_('en-US', best)",
"def get_language_header():\n return {\"Http-Accept-Language\": get_service_locale()}",
"def get_full_language(self, language):\n if language:\n language = pycountry.languages... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API Wrapper object which returns stats for a specific hero | def get_heroes_stats(tag, hero, platform="pc", region="eu", mode="quickplay"):
try:
context = ssl._create_unverified_context()
hero_stats = json.load(
const.codec(
urlopen(const.URL + platform + "/" + region + "/" + tag + "/" + mode + "/hero/" + hero + "/", context=contex... | [
"def get_hero(self, uuid, hero):\n\n # I can't wait for case statements in python (3.10)\n if hero == Heroes.BULK:\n return Bulk(self.api_key, uuid)\n\n elif hero == Heroes.GENERAL_CLUCK:\n return GeneralCluck(self.api_key, uuid)\n\n elif hero == Heroes.CAKE_MONSTER... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A view to return the delivery and returns page | def delivery(request):
return render(request, 'contact/delivery.html') | [
"def delivery(request):\n\n return render(request, 'home/delivery.html')",
"def view_delivery() -> str:\r\n #List with amount of bottles ready for delivery for each lsit\r\n delivery_amounts = []\r\n delivery_amounts.append(delivery_information[\"Organic Red Helles\"])\r\n delivery_amounts.append(d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
InvalidSegmentError should be thrown when the segment begin is greater than the segment end. | def test_validate_begin_greater_than_end():
with pytest.raises(InvalidSegmentError):
_validate([[1, 2], [5, 3]]) | [
"def test_wrong_segment(self):\n msg = self._create_message(self.adt_a01)\n spm = parse_segment('SPM|1|100187400201^||SPECIMEN^Blood|||||||PSN^Human Patient||||||20110708162817||'\n '20110708162817|||||||1|CONTAINER^CONTAINER DESC\\r', version='2.6')\n msg.add(spm)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
InvalidSegmentError should be thrown when the segment begin equals teh segment end. | def test_validate_begin_equals_end():
with pytest.raises(InvalidSegmentError):
_validate([[1, 2], [5, 5]]) | [
"def test_wrong_segment(self):\n msg = self._create_message(self.adt_a01)\n spm = parse_segment('SPM|1|100187400201^||SPECIMEN^Blood|||||||PSN^Human Patient||||||20110708162817||'\n '20110708162817|||||||1|CONTAINER^CONTAINER DESC\\r', version='2.6')\n msg.add(spm)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a Boolean value indicating whether this skill can be used to handle the given command. | def matches_command(self, skill_input: SkillInput) -> bool:
verb = (skill_input.verb or None) and skill_input.verb.lower()
return verb in self._cmd_list | [
"def can_execute(command: Command) -> bool:\n command_wrapper = commands.get_wrapper(command.name)\n perm_filter = get_permission_filter(command.guild_id(), command_wrapper)\n has_permission = filter_context.test(perm_filter, command.context) if perm_filter else False\n\n caller = command.context.author... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to verify view profile button Uses TestStatus class to mark/assert test case results | def test_TC_Users_200819_3(self):
self.log.info("*#" * 20)
self.log.info("test_TC_Users_200819_3 started")
self.log.info("*#" * 20)
self.us.gotoUsers()
self.us.clickViewProfile()
result = self.us.verifyViewProfile()
self.ts.markFinal("test_TC_Users_200819_3", resu... | [
"def test_view_profile(self):\n LOGGER.debug(\"Test GET /rango/view/leothelion/ for anon user\")\n anon_view_response = self.client.get('/rango/view/leothelion/')\n self.assertContains(anon_view_response, \"leothelion@hotmail.com\")\n \n LOGGER.debug(\"Test GET /rango/view/leothelion/ fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for Teams working table open/close Uses TestStatus class to mark/assert test case results | def test_TC_Users_UserProfile_200819_2(self):
self.log.info("*#" * 20)
self.log.info("test_TC_Users_UserProfile_200819_2 started")
self.log.info("*#" * 20)
self.us.gotoUsers()
self.us.clickViewProfile()
self.us.clickTeam()
result = self.us.verifyTeamOpenClose()
... | [
"def test_meeting_status(self):\n pass",
"def test_get_team_history(self):\n pass",
"def test_TC_Users_UserProfile_200819_4(self):\n self.log.info(\"*#\" * 20)\n self.log.info(\"test_TC_Users_UserProfile_200819_4 started\")\n self.log.info(\"*#\" * 20)\n self.us.gotoUse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for team user details page Uses TestStatus class to mark/assert test case results | def test_TC_Users_UserProfile_200819_4(self):
self.log.info("*#" * 20)
self.log.info("test_TC_Users_UserProfile_200819_4 started")
self.log.info("*#" * 20)
self.us.gotoUsers()
self.us.clickViewProfile()
self.us.clickTeam()
self.us.clickDetails()
result = s... | [
"def test_TC_Users_UserProfile_200819_2(self):\n self.log.info(\"*#\" * 20)\n self.log.info(\"test_TC_Users_UserProfile_200819_2 started\")\n self.log.info(\"*#\" * 20)\n self.us.gotoUsers()\n self.us.clickViewProfile()\n self.us.clickTeam()\n result = self.us.verify... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a list a list of files (and directories) by iterating recursively over the given path | def build_file_list(path):
dirs = []
files = []
for x in path.iterdir():
try:
if x.is_symlink():
continue
elif x.is_dir():
dirs.append(x)
new_dirs, new_files = build_file_list(x)
dirs.extend(new_dirs)
... | [
"def generate_files_list(path):\n if path[-1] == '/':\n path = path[:-1]\n\n lfiles = []\n\n for lf in os.walk(path):\n if lf[2]:\n for f in lf[2]:\n lfiles.append(lf[0] + '/' + f)\n return lfiles",
"def get_files(self, path):\n lst1 = get_content(path)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing switch to buy functionality | def switch_to_buy(self):
self.switch_to_window()
self.accept_ssl_certificate() | [
"def buy(user_id, ticker, amount, price):\r\n pass",
"def action(self):\n if self.type == self.BUY:\n return \"sell\"\n else:\n return \"buy\"",
"def buy(self, price, volume):\r\n self.order(\"bid\", price, volume)",
"def buy(self, RA, price):\n raise NotIm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing get buy page title functionality | def get_buy_page_title(self):
self.wait().until(EC.visibility_of_element_located(self.default_tab_header_locator), 'default tab header not found before specified time')
return self.page_title() | [
"def doTitle(bunch, text, env):\n return env[\"pagename\"]",
"def get_page_title(self):\n return self.driver.get_title()",
"def get_title(self):\n\t\treturn self.title",
"def get_page(\n self, title: str,\n ) -> str:\n raise NotImplementedError()",
"def get_item_title(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing is buy dashboard tab present functionality | def is_buy_dashboard_tab_present(self):
return self.is_element_present(self.buy_dashboard_tab_locator) | [
"def select_buy_dashboard_tab(self):\n self.select_static_tab(self.buy_dashboard_tab_locator, True)",
"def click_buy_and_sell_deal_management_link(self):\n self.select_static_tab(self.buy_and_sell_deal_management_locator, message=\"buy and sell deal management locator not found before specified time... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing is vendors tab present functionality | def is_vendors_tab_present(self):
return self.is_element_present(self.vendors_tab_locator) | [
"def select_vendors_tab(self):\n self.select_static_tab(self.vendors_tab_locator, 'vendors tab not found before specified time')",
"def is_specific_tab_on_vendor_profile_page_present(self, tab_name):\n tab_locator = (By.XPATH, \"//div[contains(@id, 'SourceProfileTabStrip')]/descendant::a[text()='%s'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing is country groups link present functionality | def is_country_groups_link_present(self):
return self.is_element_present(self.country_groups_locator) | [
"def click_country_group(self):\n self.click_element(self.country_groups_locator, script_executor=True)",
"def ip_country_link(self, obj):\n if obj.ip_country:\n return '<a href=\"{0}?ip_country__exact={1}\">{2}</a>'.format(\n reverse('admin:tracking_analyzer_tracker_change... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing is reanalysis link present functionality | def is_re_analysis_link_present(self):
return self.is_element_present(self.re_analysis_locator) | [
"def review_links():",
"def click_re_analysis_link(self):\n self.click_element(self.re_analysis_locator, True)",
"def relink(self, link_id):",
"def getLink(self):",
"def link_residues(self) -> None:\n ...",
"def update_link(self, link):",
"def fixLinks():",
"def visit(self, link, source=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing select vendors tab functionality | def select_vendors_tab(self):
self.select_static_tab(self.vendors_tab_locator, 'vendors tab not found before specified time') | [
"def set_vendor(self, vendor_list):\n self.multiple_items_selection_from_kendo_dropdown(self.vendor_dropdown_locator, vendor_list)\n self.wait_for_ajax_spinner_load()",
"def tabSelected(self):",
"def select_objects_ui(self):\r\n item = self.list_widget.selectedItems()[0]\r\n objects ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing is create vendor present functionality | def is_create_vendor_present(self):
return self.is_element_present(self.create_vendor_locator) | [
"def test_create_vendor(self):\n name = 'Test Vendor'\n vendor = Vendor.objects.create(\n name=name,\n user=self.user\n )\n\n self.assertEqual(vendor.name, name)\n self.assertEqual(vendor.user.id, self.user.id)",
"def onVendorCreated(self):\n\n try:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing is vendor price lists present functionality | def is_vendor_price_lists_present(self):
return self.is_element_present(self.vendor_price_lists_locator) | [
"def get_vendor_price_lists_details(self):\n try:\n self.vendor_price_lists_dict = self.get_grid_row_details(self.customer_price_list_grid_div_id, self.vendor_price_lists_dict)\n return True\n except:\n return False",
"def verify_vendor_price_lists_details(self, row_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing click buy page inline action button functionality | def click_buy_page_inline_action_button(self, vendor):
self.click_inline_action_button(self.vendors_div_id, vendor, self.grid_column_number) | [
"def click_buy_and_sell_deal_management_grid_first_row_inline_action_button(self):\n self.click_inline_action_button(self.buy_and_sell_management_grid_div_id, None, self.buy_and_sell_management_grid_inline_action_column_number, True)",
"def click(self):\r\n self.action(self)",
"def click_buy_and_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing is vendor profile present functionality | def is_vendor_profile_present(self):
return self.is_element_present(self.vendor_profile_locator) | [
"def is_vendor_profile_page_loaded_properly(self):\n return self.is_element_present(self.save_vendor_profile_locator)",
"def is_vendor(self) -> bool:\n return self._is_vendor",
"def test_is_this_vendor(self):\n #Credential's keyword is incorrect\n self.assertFalse(\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implementing is vendor digits present functionality | def is_vendor_digits_present(self):
return self.is_element_present(self.vendor_digits_locator) | [
"def findVendor(self):\n if self.model in ['nokia39','nokia56','chkp40','chkp20','chkp120','chkp13']:\n return 'nokia'\n elif self.model in ['asa10','asa25','asa50','asa85']:\n return 'cisco'",
"def is_manufacturer_specific(self):\n try:\n dif = self.parts[0]\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |