query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Test Foreach.handle_message() with last complete msg. | def test_handle_message_last_completed(self):
msg = Message(name='completed', target='fake-id_0',
origin='fake-id_0_1')
self.root.state = 'active'
self.foreach.state = 'active'
self.foreach.children[0].state = 'completed'
self.foreach.children[1].state = 'c... | [
"def test_handle_message_completed_from_non_last_child(self):\n\n msg = Message(name='completed', target='fake-id_0',\n origin='fake-id_0_0')\n self.root.state = 'active'\n self.foreach.state = 'active'\n self.foreach.context._props[\"inst:iteration\"] = 1\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the state_dict and load_state_dict methods of Progress | def test_progress_state_dict(self) -> None:
progress = Progress(
num_epochs_completed=2,
num_steps_completed=8,
num_steps_completed_in_epoch=4,
)
state_dict = progress.state_dict()
new_progress = Progress()
self.assertEqual(new_progress.num_... | [
"def test_state_dict(self):\n # Module.\n fx = TaylorNet(dim=4)\n\n # Get state dict.\n state_dict1 = get_state_dict(fx)\n\n # Set state dict.\n set_state_dict(fx, state_dict1)\n\n # Compare state dicts.\n state_dict2 = get_state_dict(fx)\n for key in s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the names of the segments. | def names(self) -> Tuple[str, ...]:
return tuple(key for key, _ in self.segments) | [
"def get_segments(self):\n return self.segments",
"def segments(self):\n return list(self._segments)",
"def getSegmentsList(self):\n return [self.getSegment(x) for x in xrange(self.getSegmentCount())]",
"def get_names(self):\n return self.clusters.keys()",
"def list_segments(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find instances in image | def find_instances(img):
pass | [
"def search(imagename):\n # loading astronaut image\n img = Image.open(imagename)\n img_arr = np.array(img)\n W,H = img.size\n\n # perform selective search\n img_lbl, regions = selectivesearch.selective_search(\n img_arr, scale=500, sigma=0.8, min_size=200)\n\n candidates = set()\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new image with marked classified instances | def create_output_image(img, instances):
pass | [
"def classify_forced(self, mod = imagenet_model):\n classes = super(EasyImageFile, self).classify(mod)\n output = [mod, classes]\n exif_json.save(self.path, output, classify_field)\n return classes",
"def create_new_image(self):\n logging.info('Starting image \\'' + self.name + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate specified value is bool or Boolean type. | def validate_bool(value: Union[bool, Boolean]) -> None:
from apysc.type import type_util
is_bool: bool = type_util.is_bool(value=value)
if is_bool:
return
raise ValueError(
f'Specified value is not bool or Boolean type: {type(value)}') | [
"def validate_boolean(self, value):\n if value is not None:\n assert isinstance(value, bool)\n return value",
"def ensure_boolean(val):\n if isinstance(val, bool):\n return val\n elif isinstance(val, str):\n return val.lower() == 'true'\n else:\n return False... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute likelihood profiles for multiple parameters. | def likelihood_profiles(self, model, parameters="all"):
profiles = {}
if parameters == "all":
parameters = [par.name for par in model.paramaters]
for parname in parameters:
profiles[parname] = self.likelihood_profile(model, parname)
return profiles | [
"def likelihood_profile(self, parameter_values, data, weights=None, expected_number_of_events=None):\n if self.r is None:\n raise RuntimeError(\"Please call fit first\")\n if len(parameter_values) != len(self.r.x):\n raise RuntimeError(\"The number of provided values does not mat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the sqrt(TS) of a model against the null hypthesis, that the amplitude of the model is zero. | def sqrt_ts(self, parameters):
stat_best_fit = self.total_stat(parameters)
# store best fit amplitude, set amplitude of fit model to zero
amplitude = parameters["amplitude"].value
parameters["amplitude"].value = 0
stat_null = self.total_stat(parameters)
# set amplitude ... | [
"def sqrt (x):\n if x > 0:\n return np.sqrt(x)\n else :\n return 0;",
"def computeSD(self,t):\n r0 = self.trajectoire[0]\n rt = self.trajectoire[t]\n return np.linalg.norm( rt - r0 , axis = 1)**2",
"def sqrt(x):\n\ttry:\n\t\tval = np.sqrt(x.val)\n\t\tders = defaultdict(f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot likelihood profile for a given parameter. | def plot_likelihood_profile(self, parameter, ax=None, **kwargs):
import matplotlib.pyplot as plt
if ax is None:
ax = plt.gca()
ts_diff = self.likelihood_profiles[parameter]["likelihood"] - self.total_stat
values = self.likelihood_profiles[parameter]["values"]
ax.pl... | [
"def plot_loglikelihood_vs_parameter(plotter: Plotter, mcmc_tables: List[pd.DataFrame], param_name: str, burn_in=0):\n ll_vals = mcmc_tables[0]['loglikelihood']\n p_vals = mcmc_tables[0][param_name]\n log_ll_vals = [-log(-x) for x in ll_vals]\n fig, axis, _, _, _ = plotter.get_figure()\n axis.plot(p_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines whether this backend is allowed to send a notification to the given user and notice_type. | def can_send(self, user, nf_type_label):
try:
user.notifications_settings.get(notification_type__label=nf_type_label, disabled=False,
channels__contains=self.channel_id)
return True
except ObjectDoesNotExist:
return False | [
"def send_notice(cls, **kwargs):\n\n notice_type = kwargs.get('notice_type') or 'joined'\n corp_membership_type = kwargs.get('corporate_membership_type')\n corporate_membership = kwargs.get('corporate_membership')\n recipients = kwargs.get('recipients') or []\n anonymous_join_logi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deliver a notification to the given recipients. | def deliver(self, recipient, notification):
# raise NotImplementedError()
pass | [
"def set_recipients(self, recipients):\n self.recipients = recipients",
"def send_email_notification(instance, args, message):\n subject = \"you have new notification from from authors haven \"\n recipient = []\n for i in args:\n recipient.append(i.user.email)\n send... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render a notification with the template for this backend. | def render(self, notification):
raise NotImplementedError() | [
"def send_templated(self, backend, recipient, template_name, **kwargs):\n message_content = self.render_template(template_name, **kwargs)\n data = {\"backend\": backend.value,\n \"recipient\": recipient,\n \"message\": message_content}\n self.send_notification_requ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" >>> _pdfmark_unicode('ascii text with ) paren') '(ascii text with \\) paren)' >>> _pdfmark_unicode('\u03b1\u03b2\u03b3') '' | def _pdfmark_unicode(string):
try:
string.encode('ascii')
except UnicodeEncodeError:
b = codecs.BOM_UTF16_BE + string.encode('utf-16-be')
return '<{}>'.format(''.join('{:02X}'.format(byte) for byte in b))
else:
# escape special characters
for a, b in [('\\', '\\\\'), ... | [
"def replace_unicodes(text):\n\ttext = text.replace(u'\\ufffd', \"'\")\n\treturn text",
"def _pdfmark_unicode_decode(string):\n if not (string.startswith('<FEFF') and string.endswith('>')):\n raise PdfMarkError\n\n b = bytes(int(float.fromhex(x1+x2))\n for x1, x2 in zip(string[5:-2:2], s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" >>> _pdfmark_unicode_decode(_pdfmark_unicode('\u03b1\u03b2\u03b3')) '\u03b1\u03b2\u03b3' | def _pdfmark_unicode_decode(string):
if not (string.startswith('<FEFF') and string.endswith('>')):
raise PdfMarkError
b = bytes(int(float.fromhex(x1+x2))
for x1, x2 in zip(string[5:-2:2], string[6:-1:2]))
return b.decode('utf-16-be') | [
"def _pdfmark_unicode(string):\n try:\n string.encode('ascii')\n except UnicodeEncodeError:\n b = codecs.BOM_UTF16_BE + string.encode('utf-16-be')\n return '<{}>'.format(''.join('{:02X}'.format(byte) for byte in b))\n else:\n # escape special characters\n for a, b in [('\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a Question string for an External URL HIT pointing to the given URL. | def get_external_question(url: str):
return EXTERNAL_URL_QUESTION.format(url) | [
"def create_external_question_XML(self, url):\n\n self.external_question = EXTERNAL_Q_TEMPLATE.substitute(\n url=url, frame_height=self.config['AWS-MTURK']['HIT_FRAMEHEIGHT'])\n \n if self.debug_level:\n print(self.external_question)\n\n return self.external_questio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a Question string for an HTMLQuestion with the given content. | def get_html_question(html: str):
return HTML_QUESTION.format(html) | [
"def __str__(self):\n q_type = self.question_type\n text = self.text\n valid = str(self.is_valid)\n encoded = self.encode()\n return \"Question{type: \" + q_type + \", text: \" + text + \", valid: \" + valid + \", encoded: \" + encoded + \"}\"",
"def display_question(content):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create HIT using provided HITTypeId. You still need to pass 'LifetimeInSeconds', 'MaxAssignments', 'Question'. | def create_hit_with_hit_type(**kwargs):
if 'HITTypeId' not in kwargs:
raise ValueError('missing required argument HITTypeId')
elif 'Question' not in kwargs:
raise ValueError('missing required argument Question')
elif 'MaxAssignments' not in kwargs:
raise ValueError('missing required ... | [
"def create_hit_with_hit_type(HITTypeId=None, MaxAssignments=None, LifetimeInSeconds=None, Question=None, RequesterAnnotation=None, UniqueRequestToken=None, AssignmentReviewPolicy=None, HITReviewPolicy=None, HITLayoutId=None, HITLayoutParameters=None):\n pass",
"def create_hit_with_hit_type(\n client: MTurk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a HIT with the given arguments. | def create_hit(**kwargs):
response = objective_turk.client().create_hit(**kwargs)
logger.debug(response)
#pylint: disable=protected-access
return objective_turk.Hit._new_from_response(response['HIT']) | [
"def create_hit_with_hit_type(**kwargs):\n if 'HITTypeId' not in kwargs:\n raise ValueError('missing required argument HITTypeId')\n elif 'Question' not in kwargs:\n raise ValueError('missing required argument Question')\n elif 'MaxAssignments' not in kwargs:\n raise ValueError('missin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the likelihood of the data under the hypothesis. | def likelihood(self, data, hypo):
x = hypo / 100.0
heads, tails = data
like = x ** heads * (1 - x) ** tails
return like | [
"def likelihood(self, x: np.ndarray) -> np.ndarray:",
"def likelihood(self, data, hypo):\n std = 30\n meanx, meany = hypo\n x, y = data\n\n like = stats.norm.pdf(x, meanx, std)\n like *= stats.norm.pdf(y, meany, std)\n return like",
"def dataLikelihood(self, step):",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes a Suite with a triangular prior. | def TrianglePrior():
suite = Euro()
for x in range(0, 51):
suite.set(x, x)
for x in range(51, 101):
suite.set(x, 100 - x)
suite.normalize()
return suite | [
"def testCreateSet_trapezoidal(self):\n membership.CreateSet('trapezoidal', 'triangle', [0.5, 1.5, 2.5, 3.5])",
"def make_trajectory(lower, upper):\n xvals = np.array(range(lower, upper + 1)) + np.random.random()\n return make_1d_traj(xvals)",
"def pre_create_trial(self):",
"def __init__(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads an ntuple with uproot, fills and returns a histogram with the observable. The paths may contain wildcards. | def with_uproot(
ntuple_paths: List[pathlib.Path],
pos_in_file: str,
variable: str,
bins: np.ndarray,
*,
weight: Optional[str] = None,
selection_filter: Optional[str] = None,
) -> bh.Histogram:
# concatenate the path to file and location within file with ":"
paths_with_trees = [str(p... | [
"def fill_histogram_from_tree(self, tree):\n try:\n counts = tree.Project(self.GetName(), self.select, self.cut)\n except:\n print 'Error filling histogram', self.GetName(),\\\n 'from tree, histogram will not be filled'",
"def fill_dpToverpT_hist(tree, hist_dpToverpT, \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute a single INSERT request | def single_insert(conn, insert_req):
cursor = conn.cursor()
try:
cursor.execute(insert_req)
conn.commit()
except Exception as e:
print(f"Error: {e}")
conn.rollback()
cursor.close()
return 1
cursor.close() | [
"def insert(self, sql):",
"def insert_row(self, statement: str, values=None):\n # Format: \"INSERT INTO table(attr) VALUES (attr) RETURNING id.\n cursor = self.execute_statement(statement, values)\n add_id = cursor.fetchone()[0]\n self.connection.commit()\n cursor.close()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the object to be signed for the ith input of this transaction | def signature_form_legacy(self, i, script=b'', hashcode=SIGHASH.ALL):
# Recreates the object that needs to be signed which is not the actual transaction
# More info at:
# https://bitcoin.stackexchange.com/questions/32628/redeeming-a-raw-transaction-step-by-step-example-required/32695#32695
... | [
"def sign(self, obj):\n assert valid_type(obj, 'Transaction', 'Block')\n assert obj.signature is None, 'This Message is already signed'\n key = RSA.import_key(self.private_key)\n assert RSA.RsaKey.has_private(key), 'Invalid private key'\n signer = pkcs1_15.new(key)\n obj.si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Segwit version of signature_form | def signature_form_segwit(self, i, hashcode=SIGHASH.ALL):
# https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki#specification
tx = deepcopy(self)
ref = tx.inputs[i].ref()
nversion = tx._version[::-1]
hashprevouts = sha256(sha256(concat((inp.outpoint() for inp in tx.i... | [
"def key_signature(self, sf, mi):\n pass",
"def computeSignature(self, image, signature=...) -> signature:\n ...",
"def process_signature(\n app, what: str, name: str, obj, options, signature, return_annotation\n):\n\n def process(sig_obj):\n \"\"\"process the signature object\"\"\"\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unzip gtfs to gtfspath | def unzip_gtfs(gtfs_zip_file_name, gtfspath, _log):
pardir = Path(os.getcwd()).parent
gtfs_contets_folder = Path(os.getcwd()).parent / gtfspath / gtfs_zip_file_name
if not os.path.isfile(gtfs_contets_folder):
_log.error("%s does not exist - please check correct GTFS date is configured", gtfs_zip_fil... | [
"def gtfs_unzip():\n try:\n processdate = process_date.get_date_now()\n gtfs_zip_file_name = cfg.gtfsdirbase + processdate + \".zip\"\n unzip_gtfs(gtfs_zip_file_name, cfg.gtfspath, _log)\n remove_bom_characters_from_unzipped_files(os.path.join(cfg.gtfspath, cfg.gtfsdirbase+processdate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sometimes the GTFS files are preceded with a BOM set of characters (\ufeff) This method remvoed them | def remove_bom_characters_from_unzipped_files(gtfspath):
BUFSIZE = 4096
BOMLEN = len(codecs.BOM_UTF8)
gtfs_contets_folder = Path(os.getcwd()).parent / gtfspath
for file in os.listdir(gtfs_contets_folder):
if ".txt" in file:
with open( gtfs_contets_folder / file, "r+b") as fp:
... | [
"def AutoDetectEncoding(self, srcFile):\n srcFile.seek(0)\n magic = srcFile.read(4)\n while len(magic) < 4:\n magic = magic + 'Q'\n if magic[:2] == '\\xff\\xfe' or magic[:2] == '\\xfe\\xff':\n if magic[2:] != '\\x00\\x00':\n magic = magic[:2]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unzip GTFS and remove BOM charcters that interrupt with reasing the file | def gtfs_unzip():
try:
processdate = process_date.get_date_now()
gtfs_zip_file_name = cfg.gtfsdirbase + processdate + ".zip"
unzip_gtfs(gtfs_zip_file_name, cfg.gtfspath, _log)
remove_bom_characters_from_unzipped_files(os.path.join(cfg.gtfspath, cfg.gtfsdirbase+processdate))
excep... | [
"def remove_bom_characters_from_unzipped_files(gtfspath):\n BUFSIZE = 4096\n BOMLEN = len(codecs.BOM_UTF8)\n\n gtfs_contets_folder = Path(os.getcwd()).parent / gtfspath\n for file in os.listdir(gtfs_contets_folder):\n if \".txt\" in file:\n with open( gtfs_contets_folder / file, \"r+b\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asks a user for informatino about a dog. Prints out the information in a bulleted list. Uses a try/except block in case of a casting ValueError | def dog():
dog_name = input("Enter the dog's name: ")
coat_colour = input("Enter the dogs coat colour: ")
eye_colour = input("Enter the dogs eye colour: ")
length_cm = input("Enter the dog's length in cm: ")
weight_kg = input("Enter the dog's weight in Kg: ")
price = input("Enter the dog's pric... | [
"def dog2():\n dog_name = input(\"Enter the dog's name: \")\n coat_colour = input(\"Enter the dogs coat colour: \")\n eye_colour = input(\"Enter the dogs eye colour: \")\n length_cm = input(\"Enter the dog's length in cm: \")\n weight_kg = input(\"Enter the dog's weight in Kg: \")\n price_pence = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asks the user for information about a dog. prints out that information out in a bulleted list. Uses a try except block to run the code in case of a casting ValueError | def dog2():
dog_name = input("Enter the dog's name: ")
coat_colour = input("Enter the dogs coat colour: ")
eye_colour = input("Enter the dogs eye colour: ")
length_cm = input("Enter the dog's length in cm: ")
weight_kg = input("Enter the dog's weight in Kg: ")
price_pence = input("Enter the dog'... | [
"def dog():\n\n dog_name = input(\"Enter the dog's name: \")\n coat_colour = input(\"Enter the dogs coat colour: \")\n eye_colour = input(\"Enter the dogs eye colour: \")\n length_cm = input(\"Enter the dog's length in cm: \")\n weight_kg = input(\"Enter the dog's weight in Kg: \")\n price = input... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the numerator of this DisplayAspectRatio. | def numerator(self):
# type: () -> int
return self._numerator | [
"def numerator(self):\n try:\n return self._num_ideal\n except AttributeError:\n pass\n self._num_ideal = self * self.denominator()\n return self._num_ideal",
"def getAspectRatio(self) -> \"float\":\n return _coin.SbBox2i32_getAspectRatio(self)",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the denominator of this DisplayAspectRatio. | def denominator(self):
# type: () -> int
return self._denominator | [
"def getAspectRatio(self) -> \"double\":\n return _coin.SbBox2d_getAspectRatio(self)",
"def getAspectRatio(self) -> \"float\":\n return _coin.SbBox2f_getAspectRatio(self)",
"def getAspectRatio(self) -> \"float\":\n return _coin.SbBox2s_getAspectRatio(self)",
"def getAspectRatio(self) -> \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the denominator of this DisplayAspectRatio. | def denominator(self, denominator):
# type: (int) -> None
if denominator is not None:
if denominator is not None and denominator < 1:
raise ValueError("Invalid value for `denominator`, must be a value greater than or equal to `1`")
if not isinstance(denominator, ... | [
"def setAspectRatio(*args, **kwargs):\n \n pass",
"def setMaxAspectRatio(self, value) -> None:\n ...",
"def setReductionRatio(self, rRatio) -> None:\n ...",
"def divide_mass(self, ratio):\r\n\t\tself.values /= ratio\r\n\t\tself.mass_ratio = ratio",
"def denominator(self):\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a listing of all commands that require a player to be run. | def get_player_commands(self, player_id):
if isinstance(player_id, int):
return self._getjson(self.url + '/queue/online-commands/' + str(player_id))
else:
raise BuycraftException("player_id parameter is not valid") | [
"def list_commands(self, ctx):\n return self.commands.keys()",
"def show_commands(player):\n commands = (\n f\"Combine verbs with nouns from the list below.\\n\"\n f\"You can also use item or monster names in place of nouns.\\n\"\n f\"\\n\"\n )\n for idx, val in player.action_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Marks the specified commands as complete. | def mark_commands_completed(self, command_ids):
resp = requests.delete(self.url + '/queue', params={'ids[]': command_ids},
headers={'X-Buycraft-Secret': self.secret})
return resp.status_code == 204 | [
"def handle_completed_command(self, command: CompletedCommandType) -> None:\n pass",
"def test_complete(self):\n pdb = PdbTest()\n pdb.noninteractive = True\n if hasattr(pdb, 'do_complete'):\n print \"Have complete\"\n pdb.do_complete(\"c\")\n correct =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the rest of recent payments made for this webstore. | def recent_payments(self, limit):
if isinstance(limit, int):
return self._getjson(self.url + '/payments')
else:
raise BuycraftException("limit parameter is not valid") | [
"async def get_payments(self):\n from .payment import Payment # work around circular import\n\n url = self._get_link(\"payments\")\n if url:\n resp = await self._resource.perform_api_call(self._resource.REST_READ, url)\n return List(resp, Payment)",
"def get_all_payment... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a checkout link for a package. | def create_checkout_link(self, username, package_id):
if not isinstance(username, str) or len(username) > 16 or not re.match('\w', username):
raise BuycraftException("Username is not valid")
if not isinstance(package_id, int):
raise BuycraftException("Package ID is not valid")
... | [
"def link(connection, args):\n\n resp = sap.adt.abapgit.Repository.link(connection, {\n 'package': args.package.upper(),\n 'url': args.url,\n 'branchName': args.branch,\n 'remoteUser': args.remote_user,\n 'remotePassword': args.remote_password,\n 'transportRequest': args... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
draws filled octagons w/ turtle tu, length edgeLen, and center at coordinates (cx, cy) | def drawOctagon(tu, edgeLen, cx, cy):
tu.showturtle()
tu.up()
tu.goto(cx - edgeLen/2, cy - round(edgeLen * (1 + math.sqrt(2))/2))
tu.down()
tu.begin_fill()
for i in range(8):
tu.forward(edgeLen)
tu.left(45)
tu.end_fill()
tu.hideturtle() | [
"def drawHexagonSide(size):\n turtle.down()\n turtle.forward( size )\n turtle.right( 60 )\n turtle.up()",
"def drawHex (x,y):\n turtle.up()\n turtle.setposition(x,y)\n for _ in range(6):\n drawHexagonSide(50)",
"def draw_a(turtle, size):\r\n turtle.lt(90)\r\n# arc(turtle, size/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate WHO's turn score after rolling DICE for NUM_ROLLS times. | def roll_dice(num_rolls, dice=six_sided_dice, who='Boss Hogg'):
roll_total = 0
got_a_one = False
assert type(num_rolls) == int, 'num_rolls must be an integer.'
assert num_rolls > 0, 'Must roll at least once.'
for x in range (0,num_rolls):
a = dice()
if commentary:
announ... | [
"def each_roll():\n current_roll=roll()\n print(current_roll)\n current_roll_score = 0\n if current_roll == 6:\n current_roll_score = 0\n else:\n current_roll_score = current_roll\n\n return current_roll_score",
"def two_dice_roll(num_trials, wanted_result):\n dice = range(1, 7)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the roll_dice and take_turn functions using test dice. | def take_turn_test():
print('-- Testing roll_dice --')
dice = make_test_dice(4, 6, 1)
assert roll_dice(2, dice) == 10, 'First two rolls total 10'
dice = make_test_dice(4, 6, 1)
assert roll_dice(3, dice) == 1, 'Third roll is a 1'
dice = make_test_dice(1, 2, 3)
assert roll_dice(3, dice) == 1... | [
"def test_roll_dice(self):\n dice = Dice()\n exp = random.randint(dice.lowest, dice.highest)\n res = dice.lowest <= exp <= dice.highest\n self.assertIn(exp, self.faces)\n self.assertTrue(res)\n\n # another assertion\n dice.roll_dice()\n self.assertIn(dice.roll... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a text representation of rolling the number N. If a number has multiple possible representations (such as 2 and 3), any valid representation is acceptable. >>> print(draw_number(3)) | | | | | | >>> print(draw_number(5)) | | | | | | >>> print(draw_number(6, '$')) | $ $ | | $ $ | | $ $ | | def draw_number(n, dot='*'):
if n == 1:
return draw_dice(1,0,0,0,dot)
elif n == 2:
return draw_dice(0,1,0,0,dot)
elif n == 3:
return draw_dice(1,1,0,0,dot)
elif n == 4:
return draw_dice(0,1,1,0,dot)
elif n == 5:
return draw_dice(1,1,1,0,dot)
elif n == 6:
... | [
"def show_number(n):\n\n return \"{} is a number\".format(n)",
"def print_number_only(n):\n return \"{} is a number\".format(n)",
"def translate(n, wd, nd):\n\n\tglobal LIMIT\n\n\tif n > LIMIT:\n\t\tprint(\"translate: Error. This function only accepts number below %d.\\n\" % (LIMIT))\n\t\treturn \"\", 0\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an ASCII art representation of a die roll. c, f, b, & s are boolean arguments. This function returns a multiline string of the following form, where the letters in the diagram are either filled if the corresponding argument is true, or empty if it is false. | b f | | s c s | | f b | The sides with 2 and 3 dots h... | def draw_dice(c, f, b, s, dot):
assert len(dot) == 1, 'Dot must be a single symbol'
border = ' -------'
def draw(b):
return dot if b else ' '
c, f, b, s = map(draw, [c, f, b, s])
top = ' '.join(['|', b, ' ', f, '|'])
middle = ' '.join(['|', s, c, s, '|'])
bottom = ' '.join(['|', f, '... | [
"def roll_two_dice(self, graphical=True):\n\n die_1 = self.get_random_die() # Set random value between 1 - 6\n die_2 = self.get_random_die() # Set random value between 1 - 6\n\n # -------------------\n # DIE MAP DESCRIPTION\n # -------------------\n # The die map holds th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the maximum number of dice allowed this turn. The maximum number of dice allowed is 10 unless the sum of SCORE and OPPONENT_SCORE has a 7 as its ones digit. >>> num_allowed_dice(1, 0) 10 >>> num_allowed_dice(5, 7) 10 >>> num_allowed_dice(7, 10) 1 >>> num_allowed_dice(13, 24) 1 | def num_allowed_dice(score, opponent_score):
return 1 if ( (opponent_score+score == 7) or (opponent_score+score) % 10 == 7 ) else 10 | [
"def countGamesPerRound():\n # Fun fact: Dividing 2 integers yields an integer, even if the\n # result has a remainder. Must use at least 1 float in the division\n # to properly yield the remainder.\n return int(math.ceil(countPlayers() / 2.0))",
"def select_dice(score, opponent_score):\n return fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select 6sided dice unless the sum of scores is a multiple of 7. >>> select_dice(4, 24) == four_sided_dice True >>> select_dice(16, 64) == six_sided_dice True | def select_dice(score, opponent_score):
return four_sided_dice if (opponent_score + score) % 7 == 0 else six_sided_dice | [
"def num_allowed_dice(score, opponent_score):\n return 1 if ( (opponent_score+score == 7) or (opponent_score+score) % 10 == 7 ) else 10",
"def sixes(dice):\n return dice_counts(dice)[6] * 6",
"def hope(dices):\n # with only 1 dice left, it should at least be 4\n if dices == 1:\n return 4\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the name of player WHO, for player numbered 0 or 1. | def name(who):
if who == 0:
return 'Player 0'
elif who == 1:
return 'Player 1'
else:
return 'An unknown player' | [
"def get_player_name(self, player_number):\n p, q = self.players\n return p if self.__piece_type__(p) == player_number else q",
"def get_other_player_name(self) :\n return self.players[1]",
"def get_player_name():\n\n return player.get(\"player_name\")",
"def name(player):\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simulate a game and return 0 if the first player wins and 1 otherwise. A strategy function takes two scores for the current and opposing players. It returns the number of dice that the current player will roll this turn. If a strategy returns more than the maximum allowed dice for a turn, then the maximum allowed is ro... | def play(strategy0, strategy1):
who = 0 # Which player is about to take a turn, 0 (first) or 1 (second)
score0 = 0
score1 = 0
while ((score0 < 100) and (score1 < 100)):
if who == 0:
x = strategy0(score0,score1)
a = num_allowed_dice(score0,score1)
if x > 10... | [
"def final_strategy(score, opponent_score):\n def E(n):\n \"\"\" Returns the expected score (without special rules applied) for rolling N six sided die\n \"\"\"\n return pow((5/6),n)*4*n\n\n def E_4(n):\n \"\"\" Returns the expected score (without special rules applied) for rolling... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a strategy that always rolls N dice. A strategy is a function that takes two game scores as arguments (the current player's score, and the opponent's score), and returns a number of dice to roll. If a strategy returns more than the maximum allowed dice for a turn, then the maximum allowed is rolled instead. >>> ... | def always_roll(n):
def strategy(score, opponent_score):
return n
return strategy | [
"def rollSeveral(self, amount, mode, glitchRule):\r\n if amount <= 0:\r\n raise ValueError(\"Invalid amount of dice.\")\r\n if mode == \"chance\":\r\n raise TypeError(\"Function rollSeveral() doesn't handle chance die rolls.\")\r\n _glitchCount = 0\r\n _hits = 0\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a function that returns the average_value of FN when called. To implement this function, you will have to use args syntax, a new Python feature introduced in this project. See the project description. >>> dice = make_test_dice(3, 1, 5, 6) >>> avg_dice = make_average(dice, 100) >>> avg_dice() 3.75 >>> avg_score =... | def make_average(fn, num_samples=100):
def avg_fn(*args):
i = 0
for x in range (0,num_samples):
i += fn(*args)
return i/num_samples
return avg_fn | [
"def average_value(func):\n\n def avg_value(args, **kwargs):\n return pd.Series(func(args, **kwargs)).mean()\n\n return avg_value",
"def test_calculate_average():\r\n\r\n score1 = 9\r\n score2 = 7\r\n score3 = 8\r\n average_score = calculate_average(score1, score2, score3)\r\n assert a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the best integer argument value for MAKE_STRATEGY to use against the alwaysroll5 baseline, between LOWER_BOUND and UPPER_BOUND (inclusive). make_strategy A oneargument function that returns a strategy. lower_bound lower bound of the evaluation range. upper_bound upper bound of the evaluation range. | def eval_strategy_range(make_strategy, lower_bound, upper_bound):
best_value, best_win_rate = 0, 0
value = lower_bound
while value <= upper_bound:
strategy = make_strategy(value)
win_rate = compare_strategies(strategy)
print('Win rate against the baseline using', value, 'value:', win... | [
"def get_max_bounded(*args, low, high):\n result = args[0]\n for num in args:\n if (result <= low or result >= high):\n result = num\n if (low < num < high and num > result):\n result = num\n if (result > low and result < high):\n return result\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a series of strategy experiments and report results. | def run_experiments():
if False: # Change to False when done testing always_roll
result = eval_strategy_range(always_roll, 1, 10)
print('Best always_roll strategy:', result)
if False: # Change to True when ready to test make_comeback_strategy
result = eval_strategy_range(make_comeback_s... | [
"def run_experiments():\n\n results = synthetic_experiment()\n results2 = unbalanced_synthetic_experiment()\n # results3, n_bank = bank_experiment('data/bank_raw.csv')\n # results4, n_pokec = pokec_experiment('data/soc-pokec-profiles.txt', 'data/soc-pokec-relationships.txt')\n\n with open('results/re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a strategy that rolls one extra time when losing by MARGIN. | def make_comeback_strategy(margin, num_rolls=5):
def s1(score,opponent_score):
if ((opponent_score - score) >= margin):
return num_rolls+1
else:
return num_rolls
return s1 | [
"def _rolling_window(self, x: chex.Array, axis: int = 0) -> chex.Array:\n def rw(y):\n return mpo_utils.rolling_window(\n y, window=self._model_rollout_length, axis=axis, time_major=True)\n\n return mpo_utils.tree_map_distribution(rw, x)",
"def get_Adjust(self):\n if \"AdjustPrb\" in se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a brief description of your final strategy. First we compute the expected values of rolling up to 10 four sided or six sided dice and enter them into an array whose index refers to the number of dice rolled. The maximum of the expected scores is the default number of dice to roll. For certain circumstances, we ap... | def final_strategy(score, opponent_score):
def E(n):
""" Returns the expected score (without special rules applied) for rolling N six sided die
"""
return pow((5/6),n)*4*n
def E_4(n):
""" Returns the expected score (without special rules applied) for rolling N four sided die
... | [
"def dice_roll(player_count: int, sides=6):\n\n if player_count < 1:\n return print('wrong players number')\n if sides < 2:\n return print('should be more sides on dice')\n\n list_of_num = [0] * player_count\n index_of_max = [i for i, j in enumerate(list_of_num)]\n not_max = []\n rou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares final strategy to the baseline strategy. | def final_strategy_test():
print('-- Testing final_strategy --')
print('Win rate:', compare_strategies(final_strategy)) | [
"def test_different_to_base_metric(self):\n if not isinstance(self.instance, DerivedRankBasedMetric):\n self.skipTest(\"no base metric\")\n base_instance = rank_based_metric_resolver.make(self.instance.base_cls)\n base_factor = 1 if base_instance.increasing else -1\n self.asse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a metadata node, to connect to different states | def add_metadata(self, metadata):
self.add_node(metadata, type='metadata') | [
"def add_metadata(self, metadata: Dict[str, str]) -> None:\n self.metadata.update(metadata)",
"def addMetadata(streamName=\"string\", scene=bool, channelName=\"string\", indexType=\"string\", channelType=\"string\", structure=\"string\"):\n pass",
"def stream_metadata_node(self, node: Node, path: str)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(r,a,v,s) and (r,a,w,t) are 2 edges of tou that violate subseq condition, with s<t | def find_subseq_violation(self):
# Iterate through all edge pairs
# If determinism condition present for any pair, (v==w and s==t)
# return edges
# Else return None
graph = self.graph
states = graph.states()
for state in states:
neighbors = graph[state]
# print(len(neighb... | [
"def inr(r,s,t):\n return (r < t) and (r >= s)",
"def weak_covers(s):\n return [v for v in s.bruhat_succ() if\n s.length() + (s.inverse().right_action_product(v)).length() == v.length()]",
"def weak_covers(s):\n return [v for v in s.bruhat_succ() if\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If v = uw (u=prefix, w=suffix), u = v w1 Returns suffix after eliminating prefix | def eliminate_suffix(v, w):
u = v.rstrip(w)
return(u) | [
"def eliminate_suffix(v, w):\n\n u = v.rstrip(w)\n return(u)",
"def eliminate_prefix(v, u):\n\n w = v.lstrip(u)\n return(w)",
"def dmp_strip(f, u):\n if not u:\n for i, c in enumerate(f):\n if c:\n return f[i:]\n return dmp_zero(u)\n\n v = u - 1\n\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the supplied entity_reference and searches the contents of the supplied bin. If any Bin Item holds a clip with the entity reference as an existing Version, that clip will be returned instead. If no existing clips match the reference, then a new clip will be created and configured to reference that Entity. hiero.c... | def findOrCreateClipInBin(entityRef, bin, context=None, session=None):
# First look for an existing clip in the bin
for binItem in bin.clips():
matches = findVersionsMatchingRefs([entityRef,], binItem)
if matches:
return matches[0]
# If we can't find one, make one
if not session:
session = ... | [
"def addClipToBinOrVersion(clip, parentBin, entity=None, context=None):\n\n if not context:\n context = FnAssetAPI.SessionManager.currentSession().createContext()\n\n if not entity:\n entity = entityUtils.entityFromObj(clip)\n\n existingClip = None\n\n if entity:\n with context.scopedOverride():\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the supplied clip is another version of an existing ProjectItem within the parentBin, then it will be added as a new Version accordingly. If it is a 'new' clip, then it will be added to the supplied parentBin. entity FnAssetAPI.Entity, The Entity that the clip has been created from. If this is not supplied, attempts... | def addClipToBinOrVersion(clip, parentBin, entity=None, context=None):
if not context:
context = FnAssetAPI.SessionManager.currentSession().createContext()
if not entity:
entity = entityUtils.entityFromObj(clip)
existingClip = None
if entity:
with context.scopedOverride():
context.retenti... | [
"def addClipAsVersion(clip, binItem, entityVersionsList):\n\n ref = clip.entityReference()\n\n # see which our index is\n versionIndex = entityVersionsList.index(ref)\n targetBinIndex = -1\n\n # Try to find the closed version that already exists in the bin\n binIndex = 0\n for v in binItem.items():\n\n c ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the supplied clip to the supplied bin item as a new Version. It takes care that the clip is placed at the right index in the bin so that versions are correctly sorted. This is done by comparing all other Versions already present to the supplied entityVersionList to determine the correct index. entityVersionsList l... | def addClipAsVersion(clip, binItem, entityVersionsList):
ref = clip.entityReference()
# see which our index is
versionIndex = entityVersionsList.index(ref)
targetBinIndex = -1
# Try to find the closed version that already exists in the bin
binIndex = 0
for v in binItem.items():
c = v.item()
if... | [
"def addClipToBinOrVersion(clip, parentBin, entity=None, context=None):\n\n if not context:\n context = FnAssetAPI.SessionManager.currentSession().createContext()\n\n if not entity:\n entity = entityUtils.entityFromObj(clip)\n\n existingClip = None\n\n if entity:\n with context.scopedOverride():\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds Clips under a BinItem that represent the supplied list of entity refs. binItem hiero.core.BinItem, The BinItem that holds a number of Versions. The function only looks at the immediate items of the binItem, and does not recurse in the case of a binItem holding a bin. list of hiero.core.Clips that match, in order ... | def findVersionsMatchingRefs(entityRefs, binItem):
matches = []
for version in binItem.items():
clip = version.item()
if clip and hasattr(clip, 'entityReference'):
## @todo Stop once we've found all of them?
if clip.entityReference() in entityRefs:
matches.append(clip)
return matche... | [
"def addClipAsVersion(clip, binItem, entityVersionsList):\n\n ref = clip.entityReference()\n\n # see which our index is\n versionIndex = entityVersionsList.index(ref)\n targetBinIndex = -1\n\n # Try to find the closed version that already exists in the bin\n binIndex = 0\n for v in binItem.items():\n\n c ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert keypoint point, size, and octave to input image size. | def convert_keypoints_to_input_image_size(keypoints):
converted_keypoints = []
for keypoint in keypoints:
keypoint.pt = tuple(0.5 * array(keypoint.pt))
keypoint.size *= 0.5
keypoint.octave = (
keypoint.octave & ~255) | (
(keypoint.octave - 1) & 255)
... | [
"def extract_n_preprocess_dicom(path, size):\n ds = cv2.imread(path)\n ds = cv2.cvtColor(ds, cv2.COLOR_BGR2GRAY)\n ds = crop_to_square(ds, upsampling=True)\n ds = imresize(ds, (size,size), \"lanczos\")\n return ds",
"def get_input_size(self, model_name: str):\n\n return self.models_[model_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the specified image and overlay the photo_calib.dat sources on top. Coordinates are converted from pixels to arcsec using the coo star and assuming that the angle of the image is 0. | def plotPhotoCalib(image, cooStar,
photoCalib='/u/ghezgroup/data/gc/source_list/photo_calib.dat'):
# Load up the photometric calibraters table.
_tab = asciidata.open(photoCalib)
name = _tab[0].tonumpy()
x = _tab[1].tonumpy()
y = _tab[2].tonumpy()
# Load up the image
imag... | [
"def __plot_aperture(self, annulus_pix, ra, dec, ap_pix, r1, r2, \n ap_name=None): \n # wcs object\n w = wcs.WCS(self.image_header)\n\n # update wcs object and image to span a box around the aperture\n xpix, ypix = ap_pix.positions[0] # pix coords of aper. c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The upgrade converts the pickled training set into a SQLite3 training set. All of the training data is retained. | def test_upgradedTrainingDataset(self):
bayes = self.store.findUnique(SpambayesFilter)
db = sqlite3.connect(bayes._classifierPath().path)
cursor = db.cursor()
self.addCleanup(db.close)
self.addCleanup(cursor.close)
cursor.execute('SELECT word, nham, nspam FROM bayes')
... | [
"def upgrade_legacy(self):\n # Transform to version 1\n if not hasattr(self, 'version'):\n self._models = [\n self.conv1,\n self.conv2,\n self.conv3,\n self.conv4\n ]\n\n self.version = '1'",
"def add_traini... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if spectra with (slightly) different metadata are correctly compared. | def test_comparing_spectra_with_metadata():
spectrum0 = Spectrum(mz=numpy.array([100.0, 101.0], dtype="float"),
intensities=numpy.array([0.4, 0.5], dtype="float"),
metadata={"float_example": 400.768,
"str_example": "whatever",
... | [
"def test_comparing_spectra_with_arrays():\n spectrum0 = Spectrum(mz=numpy.array([], dtype=\"float\"),\n intensities=numpy.array([], dtype=\"float\"),\n metadata={})\n\n fingerprint1 = numpy.array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0])\n spectrum1 ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if spectra can be compared that contain numpy.arrays in the metadata. (Failed in an earlier version) | def test_comparing_spectra_with_arrays():
spectrum0 = Spectrum(mz=numpy.array([], dtype="float"),
intensities=numpy.array([], dtype="float"),
metadata={})
fingerprint1 = numpy.array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0])
spectrum1 = Spectrum(mz=n... | [
"def test_comparing_spectra_with_metadata():\n spectrum0 = Spectrum(mz=numpy.array([100.0, 101.0], dtype=\"float\"),\n intensities=numpy.array([0.4, 0.5], dtype=\"float\"),\n metadata={\"float_example\": 400.768,\n \"str_example\":... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a data model cache matching the given configuration. | def get_model_cache(config):
cache_config = config.get("DATA_MODEL_CACHE_CONFIG", {})
engine = cache_config.get("engine", "noop")
if engine == "noop":
return NoopDataModelCache(cache_config)
if engine == "inmemory":
return InMemoryDataModelCache(cache_config)
if engine == "memcach... | [
"def get_cache(cls, key):\n return cls._instance(key)._cache",
"def get_cache(backend, **kwargs):\n try:\n backend, location, params = parse_backend_conf(backend, **kwargs)\n mod_path, cls_name = backend.rsplit('.', 1)\n mod = import_object(mod_path)\n backend_cls = getattr(m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read numpy matrix using the loadtxt function. | def _read_matrix(matrix_file):
matrix = numpy.loadtxt(matrix_file, dtype='float')
return matrix | [
"def read_matrix(transfo_file):\n from numpy import loadtxt\n lines = loadtxt(transfo_file)\n return np.asarray(lines)",
"def load_txt_matrix(fileName):\n # Loads a txt-matrix that looks like this\n #\n # 0 0 1 0\n # 0 1 1 1\n # 1 1 0 0\n #\n file = open(fileName,'r')\n matrix ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes a matrix to a file, used by remove surrogates to generate a new matrix for use with finemap. | def _write_matrix(matrix, output_matrix):
numpy.savetxt(output_matrix, matrix, delimiter=' ', newline='\n') | [
"def _write_niftyreg_matrix(matrix, txt_path):\n matrix = np.linalg.inv(matrix)\n np.savetxt(txt_path, matrix, fmt='%.8f')",
"def writeMatrix(header_rows,header_cols,matrix,matrixFile,precision=4):\n \n nrows=len(header_rows)\n ncols=len(header_cols)\n \n # interaction matrix output\n out_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the LD matrix to remove surrogates. | def remove_surrogates(matrix_file, z_score_file, surrogates_file=None):
matrix = _read_matrix(matrix_file)
(nrow, ncol) = matrix.shape
remove_snps =[]
logging.info(matrix.shape)
# Create a data structure that will store input and output
with_surrogates = {}
for i in range(nrow):
for... | [
"def clean_dial(row):\n for i, term in enumerate(L1):\n row = row.replace(term, L2[i])\n for term in L3:\n row = row.replace(term, \" \")\n\n return row.translate(str.maketrans(\"\", \"\", string.punctuation)).lower()",
"def _clean_mesh(self):\n # remove the junk after garment was st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes the Casual SNP K file. Let's just write the file that I used in the example. 0.6 0.3 0.1 | def _write_k_file(output_k, causal_snp_number):
# Write the number of K files.
causal_snp_number = 3
threshold = 1.0/(causal_snp_number)
thresh_list = [threshold] * causal_snp_number
thresh_list = [str(o) for o in thresh_list]
with open(output_k, 'w') as out:
out.write(" ".join(thresh_l... | [
"def write_cp2k_wfn(self,filename):\n words = (self.natom_read,\\\n self.nspin_read,\\\n self.nao_read,\\\n self.nset_max,\\\n self.nshell_max)\n self.writeline(words)\n self.writeline(self.nset_info)\n self.writeline(self.n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wraps the run finemap function so that it can be used from the command line | def run_finemap_wrap(args):
input_directory = args.input_directory
causal_snp_number = args.causal_snp_number
number_of_ind = args.number_of_individuals
output_directory = args.output_directory
run_finemap(input_directory, causal_snp_number, output_directory, number_of_ind) | [
"def run():\n sys.exit(main(sys.argv[1:]) or 0)",
"def main():\n if(len(sys.argv) != 2):\n print(\n \"Please provide --argv[1]:raw OdometryLanemarker bin file to display\")\n sys.exit()\n read_lane_markers_data(sys.argv[1])",
"def run(self, dryrun=False):\n\n if self.run... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Push DLLNode(data) into the list. | def push(self, data):
node = DLLNode(data)
node.next = self.head
self.head.prev = node
self.head = node | [
"def add_node(self, data):\n\n self.nodes.add(data)",
"def push(self, data):\n self.__stacknode.items.append(data)",
"def add_to_back(self, data):\r\n\t\tif self._head is None:\r\n\t\t\tself._head = Node(data, self._head)\r\n\t\telse:\r\n\t\t\tprobe = self._head\r\n\t\t\twhile probe.next is not No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert DLLNode(data) after prev_node(list[idx]). | def insert_after(self, prev_node, data):
node = DLLNode(data)
node.prev = prev_node
node.next = prev_node.next
prev_node.next = node
if node.next is None:
return
node.next.prev = node | [
"def insert_after_node(self, key, data):\n node = ListNode(data)\n p = self.head\n while p is not None:\n if p.data == key:\n node.next = p.next\n p.next = node\n p = p.next",
"def insert(self, prev, data):\n node = self.__search(prev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert DLLNode(data) at list[idx]. | def insert(self, idx, data):
if idx == 0:
self.push(data)
else:
i = 0
node = self.head
while(i+1 < idx and node.next):
i += 1
node = node.next
self.insert_after(node, data) | [
"def insert(self, data, index):\n if index == 0:\n self.add(data)\n\n if index > 0:\n new = Node(data)\n\n position = index\n current = self.head\n\n while position > 1:\n current = current.next_node\n position -= 1\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove first occurence of DLLNode(data). | def remove(self, data):
node = self.head
if node.data == data:
self.head = node.next
if self.head:
self.head.prev = None
else:
while node.next:
node = node.next
if node.data == data:
node.prev... | [
"def removeFirst(self):\n\t\tself.head = self.head.after",
"def removeNode(self, py_node): \r\n \r\n hash_code = py_node.getHashCode()\r\n \r\n if self._py_nodes.has_key(hash_code):\r\n del(self._py_nodes[hash_code])",
"def removeData(self, data: 'ScXMLDataElt') -> ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute given value's factorial and store. | def factorial(self, value):
# Compute given value's factorial and store
self._result = factorial(value)
# Return the computed factorial
return self._result | [
"def factorial(n):\n \"*** YOUR CODE HERE ***\"\n return product(n, lambda x: x)",
"def factorial(num):\n if num == 0:\n return 1\n return num * factorial(num - 1)",
"def factorial(n):\n\tif n==1:\n\t\treturn 1\n\telse:\n\t\treturn n*factorial(n-1)",
"def _falling_factorial(x, n):\n val ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply watershed algorithm on the cytoplasm to segment cell instances. | def cyt_watershed(relief, nuc_labelled, mask, smooth=None):
# TODO how to be sure nucleus label corresponds to cell label?
# check parameters
stack.check_array(relief,
ndim=2,
dtype=[np.uint8, np.uint16])
stack.check_array(nuc_labelled,
n... | [
"def onApplyWS(self):\r\n volumeNode = self.inputSelector.currentNode()\r\n\r\n # the WaspLogic should be able to be run from the slicer python command line\r\n self.logic = WaspLogic()\r\n\r\n # perform the watershed\r\n self.logic.runWS(volumeNode,\r\n fl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes a bounding box on the WGS84 ellipsoid associated to a Pleiades image region of interest, through its rpc function. | def geodesic_bounding_box(rpc, x, y, w, h):
# compute altitude coarse extrema from rpc data
m = rpc.altOff - rpc.altScale
M = rpc.altOff + rpc.altScale
# build an array with vertices of the 3D ROI, obtained as {2D ROI} x [m, M]
x = np.array([x, x, x, x, x+w, x+w, x+w, x+w])
y = np.array([y,... | [
"def boundingBox(self):\r\n\t\tfrom blur3d.lib.cartesian import BoundingBox, Point\r\n\t\tp1, p2 = mxs.nodeGetBoundingBox(self.nativePointer(), mxs.matrix3(1))\r\n\t\treturn BoundingBox(Point.newFromMaxPoint(p1), Point.newFromMaxPoint(p2))",
"def bounding_box(self):\n# first_point and last_point contain UTM coord... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Samples a geodetic "rectangular" region with regularly spaced points. The sampling distance is the srtm resolution, ie 3 arcseconds. | def sample_bounding_box(lon_m, lon_M, lat_m, lat_M):
# check parameters
assert lon_m > -180
assert lon_M < 180
assert lon_m < lon_M
assert lat_m > -60
assert lat_M < 60
assert lat_m < lat_M
# width of srtm bin: 6000x6000 samples in a tile of 5x5 degrees, ie 3
# arcseconds (in degree... | [
"def regenerate_time_sample(d):\n try:\n # Trying to get Time coordinate. If not present regenerating it\n d.get_coordinate_object('Time')\n except ValueError:\n ct = d.get_coordinate_object('Start Time in int(Time)')\n c_shift = d.get_coordinate_object('Rel. Time in int(Time)')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rounds down (resp. up) a (resp. b) to the closest multiple of q. | def round_updown(a, b, q):
a = q*np.floor(a/q)
b = q*np.ceil(b/q)
return a, b | [
"def round_up(x: float, a: float) -> float:\n return (round_down(x, a)+a)",
"def round_up(n, alignment):\n return round_down(n + alignment-1, alignment)",
"def mod_switch(x, q, rq): \n return int(round(1.* rq * x / q) % rq)",
"def _round_up(value, n):\n return n * ((value + (n - 1)) // n)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes a coarse altitude range using the RPC informations only. | def altitude_range_coarse(rpc):
m = rpc.altOff - rpc.altScale
M = rpc.altOff + rpc.altScale
return m, M | [
"def altitude_range(rpc, x, y, w, h, margin_top, margin_bottom):\n # TODO: iterate the procedure used here to get a finer estimation of the\n # TODO: bounding box on the ellipsoid and thus of the altitude range. For flat\n # TODO: regions it will not improve much, but for mountainous regions there is a\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes an altitude range using SRTM data. | def altitude_range(rpc, x, y, w, h, margin_top, margin_bottom):
# TODO: iterate the procedure used here to get a finer estimation of the
# TODO: bounding box on the ellipsoid and thus of the altitude range. For flat
# TODO: regions it will not improve much, but for mountainous regions there is a
# TODO:... | [
"def altitude_range_coarse(rpc):\n m = rpc.altOff - rpc.altScale\n M = rpc.altOff + rpc.altScale\n return m, M",
"def elevation_range(self):\n if self._elevation_range is None:\n startel = self._obj.attrs[\"startelA\"]\n stopel = self._obj.attrs[\"stopelA\"]\n elev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses RPC functions to determine the region of im2 associated to the specified ROI of im1. | def corresponding_roi(rpc1, rpc2, x, y, w, h):
m, M = altitude_range(rpc1, x, y, w, h, 0, 0)
# build an array with vertices of the 3D ROI, obtained as {2D ROI} x [m, M]
a = np.array([x, x, x, x, x+w, x+w, x+w, x+w])
b = np.array([y, y, y+h, y+h, y, y, y+h, y+h])
c = np.array([m, M, m, M... | [
"def roi_overlap(ROIs1, ROIs2, param1, param2, im1_shape, im2_shape, thr_ovlp=0.5, pplot=False, im1=None):\n\n ROIs1_trans = rottrans_rois(ROIs1, param1[0], param1[1], param1[2], im1_shape[0], im1_shape[1])\n ROIs2_trans = rottrans_rois(ROIs2, param2[0], param2[1], param2[2], im2_shape[0], im2_shape[1])\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the HTML details of a form, including action, method and list of form controls (inputs, etc) | def get_form_details(form):
details = {}
# get the form action (requested URL)
action = form.attrs.get("action").lower()
# get the form method (POST, GET, DELETE, etc)
# if not specified, GET is the default in HTML
method = form.attrs.get("method", "get").lower()
# get all form inputs
in... | [
"def get_form_details(form):\r\n details = {}\r\n try:\r\n action = form.attrs.get(\"action\").lower()\r\n except:\r\n action = None\r\n method = form.attrs.get(\"method\", \"get\").lower()\r\n inputs = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that checks whether all parentheses `{}, [], ()` are balanced in the given `expression`. >>> parentheses_checker("(((]})") False >>> parentheses_checker("(") False >>> parentheses_checker("(){}[]]") False >>> parentheses_checker("( x )") True >>> parentheses_checker("a()b{}c[]d") True >>> parentheses_checker... | def parentheses_checker(expression):
# YOUR CODE GOES HERE #
left_paran = Stack()
for char in expression:
if char in set(['{', '(', '[']):
left_paran.push(char)
elif char in set(['}', ')', ']']):
if (left_paran.is_empty()):
return False
to... | [
"def is_balanced(expression):\n if len(expression) <= 1:\n return False\n\n elements = {')': '(', ']': '[', '}': '{'}\n stack = []\n\n for char in expression:\n if char in elements.values():\n stack.append(char)\n # stack is empty or closing does not match opening element... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A generator that takes in an `iterable` object and infinitely yields its items. This generator skips items by an increasing amount after each yield. If this generator reached the end of the `iterable`, proceed from the front. >>> gen = inf_skip_increasing(range(10)) >>> next(gen) 0 >>> next(gen) 1 >>> [next(gen) for _ ... | def inf_skip_increasing(iterable):
# YOUR CODE GOES HERE #
def generator():
queue = Queue()
for item in iterable:
queue.enqueue(item)
n_skips = 0
while True:
yield queue.peek()
# move the yielded item to the back
item = queue.dequeu... | [
"def infinite_integer(i=0, step=1):\n while True:\n yield i\n i += step",
"def endless_generator(func, *args, **kwds):\n buffer = deque()\n while True:\n while buffer:\n yield buffer.popleft()\n buffer.extend(func(*args, **kwds))",
"def skip(sequence, number):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
message du serveur vers tous les clients | def MessagePourTous(message):
for client in dict_clients:
dict_clients[client].send(bytes(message,"utf8")) | [
"def client_verbindung(client):\n name = client.recv(BUFFERSIZE).decode(\"utf8\")\n willkommen = 'Willkomen %s! Um sich auszuloggen schreiben Sie bitte {quit}!' %name\n client.send(bytes(willkommen, \"utf8\"))\n msg = \"%s hat sich Verbunden!\" %name\n broadcast(bytes(msg, \"utf8\"))\n clients[cli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test getting Plex clients from plex.tv. | async def test_plex_tv_clients(hass, entry, mock_plex_account, setup_plex_server):
mock_plex_server = await setup_plex_server()
server_id = mock_plex_server.machineIdentifier
plex_server = hass.data[DOMAIN][SERVERS][server_id]
resource = next(
x
for x in mock_plex_account.resources()
... | [
"def test_get_all_clients(self):\n\n response = client.get(\"/api/client\")\n self.assertEqual(len(response.data), 3)\n self.assertEqual(response.status_code, status.HTTP_200_OK)",
"def test_get_player_list(self):\n response = self.client.open(\n '/api/v1/getPlayerList/{prov... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the width of the animation. This is the horizontal space that the animation will take up throughout the animation. This value can be used to create a box that keeps the animation from overlapping with other elements at any time during the animation. | def get_width(animation):
return animation.max_x - animation.min_x | [
"def width(self) -> float:\n return self._width",
"def get_width(self):\n return self.textsurf.get_width()",
"def _get_width(self) -> \"double\" :\n return _core.OrientedBoundingBox3D__get_width(self)",
"def frame_width(self):\n # type: () -> int\n return self._frame_width",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the height of the animation. This is the vertical space that the animation will take up throughout the animation. This value can be used to create a box that keeps the animation from overlapping with other elements at any time during the animation. | def get_height(animation):
return animation.max_y - animation.min_y | [
"def get_height(self):\n\t\treturn self.y[1] - self.y[0]",
"def get_height(self):\n return self.textsurf.get_height()",
"def getHeight( self ):\n return self.height",
"def _get_height(self) -> \"double\" :\n return _core.OrientedBoundingBox3D__get_height(self)",
"def getFrameHeight(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Custom login_required to handle ajax request Check user is login and is_active | def login_required(view):
@wraps(view)
def inner(request, *args, **kwargs):
if not request.user.is_authenticated() or not request.user.is_active:
if request.is_ajax():
# if is ajax return 403
return JsonResponse({'login_url': settings.LOGIN_URL}, status=403)
... | [
"def ajax_login_required(view_func):\n\n @wraps(view_func, assigned=available_attrs(view_func))\n def _wrapped_view(request, *args, **kwargs):\n if request.is_ajax():\n if request.user.is_authenticated():\n return view_func(request, *args, **kwargs)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
write strata gaps to csv | def write_strata_gaps():
days_ago = parameters['days_ago']
sensor = parameters['sensor']
maxgapsec = parameters['maxgapsec']
pad_path = parameters['pad_path']
csv_file = parameters['csv_file']
gaps = get_strata_gaps(days_ago=days_ago, sensor=sensor, maxgapsec=maxgapsec, basedir=pad_path)
... | [
"def write_train_csv(self):\n smiles_only = pd.DataFrame({\"SMILES\": list(self.assays[self.smiles_type])})\n smiles_only.to_csv(self.ligands_csv)",
"def generate_csv():\n\tdata_frame = get_all_occupancy_data(False)\n\tdata_frame = resample_timestamp(data_frame)\n\tprint('Resample time stamp DONE')\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the mse for vector e. | def calculate_mse(e):
return 1 / 2 * np.mean(e**2) | [
"def calculate_mse(e):\n return (1/2) * np.mean(e**2)",
"def mse(f_x, y):\n return (f_x - y).pow(2).sum(dim=1).mean(dim=0)",
"def compute_mse(actual, forecast):\n return np.mean(np.square(np.subtract(forecast, actual)))",
"def Get_MSE(self, test_y, pre_result):\n diff = []\n for i in ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the mae for vector e. | def calculate_mae(e):
return np.mean(np.abs(e)) | [
"def compute_mae(y, tx, w):\n \n # number of samples\n N = len(y)\n \n # compute the error\n e = y-tx.dot(w)\n \n # when loss is the MAE\n mae = abs(e).mean()\n \n return mae",
"def calculate_mse(e):\n return 1 / 2 * np.mean(e**2)",
"def sig_ae(E,m):\n beta = (1 - m**2./E**... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sends the menu options to the client after the handshake between client and server is done. | def _send_menu(self):
data = {'menu': self.menu_list, 'option_selected': 7}
self.send(data) | [
"def _connection_menu_bgfun(self):\n # when in INITIAL state and client connection got a status\n if self.__connectionMenuState == sstatecons.ConnectionMenuState.INITIAL and\\\n Client.get_instance().connection_alive is not None:\n\n self.__connectionMenu.add_line('')\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the option selected by the user and the data sent by the client related to that option. Note that validation of the option selected must be done in client and server. In this method, I already implemented the server validation of the option selected. | def process_options(self):
data = self.receive()
if 'option_selected' in data.keys() and 1 <= data['option_selected'] <= 6: # validates a valid option selected
option = data['option_selected']
if option == 1:
self._send_user_list()
elif option == 2:
... | [
"def process_user_data(self):\n self.show_menu()\n option = self.option_selected()\n if 1 <= option <= 6: # validates a valid option\n # (i,e algo: if option == 1, then data = self.menu.option1, then. send request to server with the data)\n if option == 1:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method takes an list and an element id it will return the element from the list if found else it will return 1 | def get_element_from_list_on_server(self, list, element_id):
element = list.get(str(element_id), "1")
if element != "1":
return element
else:
return -1 # returns -1 if element not found in the elements list | [
"def find_element_in_list(element, list_element):\n try:\n index_element = list_element.index(element)\n return index_element\n except ValueError:\n return None",
"def get_from_id(id, lst):\n for k in lst:\n if k['id'] == id:\n return k\n return None",
"def che... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this method takes a room id then it would signin the client to that room if chatroom does not exist the return value for get_element_from_list_on_server() is 1 would be returned from this method as well | def sign_in_to_chatroom(self, room_id):
chat_room = self.get_element_from_list_on_server(self.server.chatrooms, room_id)
if chat_room != -1:
chat_room.add_user(self.client_id, self)
return chat_room | [
"def not_in_room_by_id(room_id):\n return Response(\"you are not in the room %s\" % room_id, 406)",
"def chat_page():\n try:\n if request.method == \"POST\":\n data = request.form.to_dict(flat=False)\n # print(data)\n if db_function.create_connection() is not None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method would take user list sender id and data/message it would send the data to all users in the list but the sender won't get it | def send_message_to_all_users(self, users, sender_id, data):
for user in users:
if user != sender_id:
users[user].send(data) | [
"def broadcast(self, data):\n for usr in users:\n users[usr].sendall(data)",
"def send_audio_to_users(self, speaking_user, data):\n\n # copy current connected users to make sure no one joins while sending data\n self.users_copy = self.users.copy()\n\n # check every user in s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get min max ranges as numpy array. | def ranges_array(self):
return np.array([
[m.meta.min, m.meta.max] for m in self.channels
]).T | [
"def get_range(dataset):\n min_max = []\n for col in dataset.columns:\n min_max.append([min(dataset[col]), max(dataset[col])])\n return min_max",
"def range_minmax(ranges):\n rmin = min(ranges)[0]\n rmax = max(ranges, key=lambda x: x[1])[1]\n return rmin, rmax",
"def get_min_max_values(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reorder columns based on list of channels given. | def reorder_channels(self, channels: List[str]) -> "FCSData":
if any(map(lambda c: c not in self.channels, channels)):
raise ValueError("Some given channels not contained in data.")
return self[channels] | [
"def swap_channels(axes):\n # type: (List[str/[int]) -> Function\n\n def _swap_channels(img):\n # Img is in HWC\n channels = [img[:, :, i] for i in [0, 1, 2]]\n\n return np.stack(tuple([channels[a] for a in axes]), axis=2)\n\n return _transpose",
"def orderMagnitudeColumns(filter_ord... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |