query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Navigates to the Home view of a Salesforce Object | def go_to_object_home(self, obj_name):
url = self.cumulusci.org.lightning_base_url
url = "{}/lightning/o/{}/home".format(url, obj_name)
self.selenium.go_to(url)
self.wait_until_loading_is_complete(lex_locators["actions"]) | [
"def _go_to_page(self):\n self.salesforce.go_to_setup_home()\n self.eda.wait_for_new_window(\"Home | Salesforce\")\n self.selenium.switch_window(\"Home | Salesforce\")\n self.salesforce.wait_until_loading_is_complete()",
"def go_home(self):\n self.screen.home_screen()",
"def g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigates to the Home tab of Salesforce Setup | def go_to_setup_home(self):
url = self.cumulusci.org.lightning_base_url
self.selenium.go_to(url + "/lightning/setup/SetupOneHome/home")
self.wait_until_loading_is_complete() | [
"def _go_to_page(self):\n self.salesforce.go_to_setup_home()\n self.eda.wait_for_new_window(\"Home | Salesforce\")\n self.selenium.switch_window(\"Home | Salesforce\")\n self.salesforce.wait_until_loading_is_complete()",
"def go_home(self):\n self.screen.home_screen()",
"def g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigates to the Object Manager tab of Salesforce Setup | def go_to_setup_object_manager(self):
url = self.cumulusci.org.lightning_base_url
self.selenium.go_to(url + "/lightning/setup/ObjectManager/home")
self.wait_until_loading_is_complete() | [
"def _go_to_page(self):\n self.salesforce.go_to_setup_home()\n self.eda.wait_for_new_window(\"Home | Salesforce\")\n self.selenium.switch_window(\"Home | Salesforce\")\n self.salesforce.wait_until_loading_is_complete()",
"def go_to_object_home(self, obj_name):\n url = self.cumul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that a field in the record header does not have a value. | def header_field_should_not_have_value(self, label):
locator = lex_locators["record"]["header"]["field_value"].format(label)
self.selenium.page_should_not_contain_element(locator) | [
"def _entry_field_values_are_not_empty(entry: _LexiconEntry) -> None:\n empty_fields = [f for f in _REQUIRED_FIELDS if not entry[f]]\n\n if empty_fields:\n field_str = \", \".join(sorted(empty_fields))\n raise InvalidLexiconEntryError(\n f\"Entry fields have empty values: '{field_str}'\")",
"def ch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that a field in the record header has a link as its value | def header_field_should_have_link(self, label):
locator = lex_locators["record"]["header"]["field_value_link"].format(label)
self.selenium.page_should_contain_element(locator) | [
"def link_check(form, field):\n if form.registrable.data and len(field.data)==0:\n raise validators.ValidationError('link should is required when the forum is registrable')",
"def _validate_item_link(self, item):\n if len(item.link) > 255:\n raise ValueError(\"item.link length too long... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that a field in the record header does not have a link as its value | def header_field_should_not_have_link(self, label):
locator = lex_locators["record"]["header"]["field_value_link"].format(label)
self.selenium.page_should_not_contain_element(locator) | [
"def _validate_type(self):\n if self._type != \"link\":\n raise securesystemslib.exceptions.FormatError(\n \"Invalid Link: field `_type` must be set to 'link', got: {}\"\n .format(self._type))",
"def link_check(form, field):\n if form.registrable.data and len(field.data)==0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clicks a link in record header. | def click_header_field_link(self, label):
locator = lex_locators["record"]["header"]["field_value_link"].format(label)
self._jsclick(locator) | [
"def click(cls, user, link):\r\n pass",
"def click(cls, user, link):\n pass",
"def header_field_should_have_link(self, label):\n locator = lex_locators[\"record\"][\"header\"][\"field_value_link\"].format(label)\n self.selenium.page_should_contain_element(locator)",
"def on_click_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that a checkbox field in the record header is checked | def header_field_should_be_checked(self, label):
locator = lex_locators["record"]["header"]["field_value_checked"].format(label)
self.selenium.page_should_contain_element(locator) | [
"def form_CheckboxRequired(request):\n schema = schemaish.Structure()\n schema.add('checkbox', schemaish.Boolean(validator=validatish.Required()))\n\n form = formish.Form(schema, 'form')\n return form",
"def header_field_should_be_unchecked(self, label):\n locator = lex_locators[\"record\"][\"h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that a checkbox field in the record header is unchecked | def header_field_should_be_unchecked(self, label):
locator = lex_locators["record"]["header"]["field_value_unchecked"].format(
label
)
self.selenium.page_should_contain_element(locator) | [
"def test_detect_non_checkbox(self):\r\n f = self.form()\r\n\r\n self.assertFalse(self.mtforms.is_checkbox(f[\"level\"]))",
"def test_widget_is_not_checkbox():\n form = ExampleForm()\n field = form[\"text\"]\n assert is_checkbox(field) is False",
"def uncheckBoxes(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Logs all of the browser capabilities as reported by selenium | def log_browser_capabilities(self, loglevel="INFO"):
output = "selenium browser capabilities:\n"
output += pformat(self.selenium.driver.capabilities, indent=4)
self.builtin.log(output, level=loglevel) | [
"def base_chrome_capabilities():\n from selenium.webdriver.chrome.options import Options\n\n options = Options()\n # enable collection of network logging\n options.set_capability('goog:loggingPrefs', {'performance': 'ALL'})\n return options",
"def capture_log(self):\n entries = []\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the Saleforce App Launcher Modal | def open_app_launcher(self, retry=True):
self._jsclick("sf:app_launcher.button")
self._jsclick("sf:app_launcher.view_all")
self.wait_until_modal_is_open()
try:
# the modal may be open, but not yet fully rendered
# wait until at least one link appears. We've seen ... | [
"def launch_an_app(appname,ui):\r\n ui = ui\r\n time.sleep(WAIT)\r\n \"\"\"Clicking on Launcher button\"\"\"\r\n ui.doDefault_on_obj('Launcher', False, role='button') \r\n time.sleep(WAIT)\r\n ui.doDefault_on_obj(name='Expand to all apps', role='button')\r\n time.sleep(WAIT)\r\n \"\"\"Launch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enters a value into a lookup field. | def populate_lookup_field(self, name, value):
input_locator = self._get_input_field_locator(name)
menu_locator = lex_locators["object"]["field_lookup_link"].format(value)
self._populate_field(input_locator, value)
for x in range(3):
self.wait_for_aura()
try:
... | [
"def _lookup(self, table, value):\n\n\t\treturn table[value] if value in table else '%d (Unknown)' % value",
"def set_field_val(self, field_display_name, field_value):\n selector = f'{self.editor_selector} li.field label:contains(\"{field_display_name}\") + input'\n script = \"$(arguments[0]).val(ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set focus to an element In addition to merely setting the focus, we click the mouse to the field in case there are functions tied to that event. | def _focus(self, element):
actions = ActionChains(self.selenium.driver)
actions.move_to_element(element).click().perform()
self.selenium.set_focus_to_element(element) | [
"def focus(self, locator):\n \n self.element = self._element_finder(locator)\n self._current_browser().execute_script(\"arguments[0].focus();\", self.element)\n log.mjLog.LogReporter(\"WebUIOperation\",\"debug\",\"focus operation successful: %s\" %(locator))",
"def setFocus(self):\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use bruteforce to clear an element This moves the cursor to the end of the input field and then issues a series of backspace keys to delete the data in the field. | def _force_clear(self, element):
value = element.get_attribute("value")
actions = ActionChains(self.selenium.driver)
actions.move_to_element(element).click().send_keys(Keys.END)
for character in value:
actions.send_keys(Keys.BACKSPACE)
actions.perform() | [
"def clearInput(self):\n\n self.value = \"\"\n self.UpdateText()",
"def clear_input_field(self, locator, method=0):\n\n\t\telement = self._element_find(locator, True, True)\n\t\t\n\t\tif (int(method) == 0):\n\n\t\t\tself._info(\"Clearing input on element '%s'\" % (locator))\n\t\t\telement.clear()\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enters multiple values from a mapping into form fields. | def populate_form(self, **kwargs):
for name, value in kwargs.items():
self.populate_field(name, value) | [
"def fill_form_inputs(driver, form_element, input_name_map):\n # Iterate through input_name_map\n for name, value in input_name_map.items():\n fill_form_input(driver, form_element, name, value)",
"def fill_multiple_textbox(self, key_val):\n for xpath, value in key_val.items():\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Selects a record type while adding an object. | def select_record_type(self, label):
self.wait_until_modal_is_open()
locator = lex_locators["object"]["record_type_option"].format(label)
self._jsclick(locator)
self.selenium.click_button("Next") | [
"def _set_record_type(self):\n\n if self.invoice_obj.pools:\n self.raw_records = self.invoice_obj.pools\n self.record_type = \"Pool\"\n elif self.invoice_obj.samples:\n self.record_type = \"Sample\"\n self.raw_records = self.invoice_obj.samples\n elif... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Navigates to a tab via the App Launcher | def select_app_launcher_tab(self, tab_name):
locator = lex_locators["app_launcher"]["tab_link"].format(tab_name)
self.open_app_launcher()
self.selenium.wait_until_page_contains_element(locator)
self.selenium.set_focus_to_element(locator)
self._jsclick(locator)
self.wait_u... | [
"def go_to_tab(self, tab_name):\r\n\r\n if tab_name not in ['Courseware', 'Course Info', 'Discussion', 'Wiki', 'Progress']:\r\n self.warning(\"'{0}' is not a valid tab name\".format(tab_name))\r\n\r\n # The only identifier for individual tabs is the link href\r\n # so we find the tab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a Salesforce object by object name and Id. | def salesforce_delete(self, obj_name, obj_id):
self.builtin.log("Deleting {} with Id {}".format(obj_name, obj_id))
obj_class = getattr(self.cumulusci.sf, obj_name)
obj_class.delete(obj_id)
self.remove_session_record(obj_name, obj_id) | [
"def delete_object(self, id):\n self.request(id, post_args={\"method\": \"delete\"})",
"def delete_object(self, id):\r\n self.request(id, post_args={\"method\": \"delete\"})",
"def delete_object(self, id):\n return self.request(\n \"{0}/{1}\".format(self.version, id), method=\"DE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a Salesforce object by Id and returns the result as a dict. | def salesforce_get(self, obj_name, obj_id):
self.builtin.log(f"Getting {obj_name} with Id {obj_id}")
obj_class = getattr(self.cumulusci.sf, obj_name)
return obj_class.get(obj_id) | [
"def get_by_id(self, id: int) -> dict:\n result = self.es.get(index=self.es_index, id=id, doc_type='_doc')\n return result",
"def get_object(id):",
"def get_object(self, id_):\n return self._objects.get(id_, None)",
"def get_by_id(cls, id):\n e = api.get([key.Key(cls.__name__, id)]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new Salesforce object and returns the Id. The fields of the object may be defined with keyword arguments where the keyword name is the same as the field name. The object name and Id is passed to the Store Session Record keyword, and will be deleted when the keyword Delete Session Records is called. As a best ... | def salesforce_insert(self, obj_name, **kwargs):
self.builtin.log("Inserting {} with values {}".format(obj_name, kwargs))
obj_class = getattr(self.cumulusci.sf, obj_name)
res = obj_class.create(kwargs)
self.store_session_record(obj_name, res["id"])
return res["id"] | [
"def ID(cls,objectid, **kkw):\n rec = cls(**kkw)\n rec.setObjectID(objectid) \n return rec",
"def create_id(self, id_form):\n return # osid.id.Id",
"def salesforce_delete(self, obj_name, obj_id):\n self.builtin.log(\"Deleting {} with Id {}\".format(obj_name, obj_id))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate bulk test data This returns an array of dictionaries with templateformatted arguments which can be passed to the Salesforce Collection Insert keyword. You can use ``{{number}}`` to represent the unique index of the row in the list of rows. If the entire string consists of a number, Salesforce API will treat th... | def generate_test_data(self, obj_name, number_to_create, **fields):
objs = []
for i in range(int(number_to_create)):
formatted_fields = {
name: format_str(value, {"number": i}) for name, value in fields.items()
}
newobj = self._salesforce_generate_obj... | [
"def setup_sample_data(no_of_records):\n rows_in_database = [{'id': counter, 'name': get_random_string(string.ascii_lowercase, 20), 'dt': '2017-05-03'}\n for counter in range(0, no_of_records)]\n return rows_in_database",
"def create_test_data(n):\r\n ret = []\r\n for i in xrange(n)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inserts records that were created with Generate Test Data. _objects_ is a list of data, typically generated by the Generate Test Data keyword. A 200 record limit is enforced by the Salesforce APIs. The object name and Id is passed to the Store Session Record keyword, and will be deleted when the keyword Delete Session ... | def salesforce_collection_insert(self, objects):
assert (
not obj.get("id", None) for obj in objects
), "Insertable objects should not have IDs"
assert len(objects) <= SF_COLLECTION_INSERTION_LIMIT, (
"Cannot insert more than %s objects with this keyword"
% SF... | [
"def add_objects(self, objects):\n requests = []\n for obj in objects:\n requests.append({\"action\": \"addObject\", \"body\": obj})\n request = {\"requests\": requests}\n return self.batch(request)",
"def insert(self, bulkdata):\n new_session = self.open_session()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates records described as Robot/Python dictionaries. _objects_ is a dictionary of data in the format returned by the Salesforce Collection Insert keyword. A 200 record limit is enforced by the Salesforce APIs. | def salesforce_collection_update(self, objects):
for obj in objects:
assert obj[
"id"
], "Should be a list of objects with Ids returned by Salesforce Collection Insert"
if STATUS_KEY in obj:
del obj[STATUS_KEY]
assert len(objects) <= S... | [
"def partial_update_objects(self, objects):\n requests = []\n for obj in objects:\n requests.append({\"action\": \"partialUpdateObject\", \"objectID\": obj[\"objectID\"], \"body\": obj})\n request = {\"requests\": requests}\n return self.batch(request)",
"def salesforce_coll... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs and runs a simple SOQL query and returns a list of dictionaries. By default the results will only contain object Ids. You can specify a SOQL SELECT clase via keyword arguments by passing a commaseparated list of fields with the ``select`` keyword argument. | def salesforce_query(self, obj_name, **kwargs):
query = "SELECT "
if "select" in kwargs:
query += kwargs["select"]
else:
query += "Id"
query += " FROM {}".format(obj_name)
where = []
for key, value in kwargs.items():
if key == "select":... | [
"def create_select():\n return _query(\"select\")",
"def query(self, statement, **kwargs):\n return Records(self.con.execute(text(statement), **kwargs))",
"def run_select_examples():\n table = \"actors\"\n select_fields = ['name', 'last_name', 'country']\n select_conds1 = {}\n select_conds... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait for modal to open | def wait_until_modal_is_open(self):
self.selenium.wait_until_page_contains_element(
lex_locators["modal"]["is_open"],
timeout=15,
error="Expected to see a modal window, but didn't",
) | [
"def wait_until_modal_is_closed(self):\n self.selenium.wait_until_page_does_not_contain_element(\n lex_locators[\"modal\"][\"is_open\"], timeout=15\n )",
"def check_modal(client):\n modal_close_btn_xpath = \"/html/body/div[9]/div[3]/div/button[1]\"\n\n try:\n modal_close_btn ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait for modal to close | def wait_until_modal_is_closed(self):
self.selenium.wait_until_page_does_not_contain_element(
lex_locators["modal"]["is_open"], timeout=15
) | [
"def wait_until_modal_is_closed(self, timeout=None):\n locator = \"//div[contains(@class, 'uiModal')]\"\n\n self.selenium.wait_until_page_does_not_contain_element(locator)",
"def wait_until_modal_is_open(self):\n self.selenium.wait_until_page_contains_element(\n lex_locators[\"moda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Waits until we are able to render the initial salesforce landing page It will continue to refresh the page until we land on a lightning page or until a timeout has been reached. The timeout can be specified in any time string supported by robot | def wait_until_salesforce_is_ready(self, locator=None, timeout=None, interval=5):
# Note: we can't just ask selenium to wait for an element,
# because the org might not be availble due to infrastructure
# issues (eg: the domain not being propagated). In such a case
# the element will ne... | [
"def wait_front_page_load(self, timeout=DEFAULT_LOGIN_TIMEOUT):\n conditions = [\n invisibility_of_element_located(self.page.button_accept.locator),\n invisibility_of_element_located(self.page.div_loading_documents.locator),\n invisibility_of_element_located(self.page.div_loa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serves as a breakpoint for the robot debugger | def breakpoint(self):
return None | [
"def debugger_add_hw_breakpoint():",
"def debugger_enable_breakpoint():",
"def gdb_breakpoint():\n _gdb_python_call_gen('gdb_breakpoint')()",
"def debugger_add_sw_breakpoint():",
"def debugger_step_over():",
"def debugger_break_now():",
"def debugger_show_breakpoints():",
"def debugger_step_into():... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switch to lightning if we land on a classic page This seems to happen randomly, causing tests to fail catastrophically. The idea is to detect such a case and autoclick the "switch to lightning" link | def _check_for_classic(self):
try:
# we don't actually want to wait here, but if we don't
# explicitly wait, we'll implicitly wait longer than
# necessary. This needs to be a quick-ish check.
self.selenium.wait_until_element_is_visible(
"class:swi... | [
"def lightning():",
"async def light(self) -> None:\n self.lit = True\n await self.run_command(\"miner fault_light on\")\n print(\"light \" + self.ip)",
"def TurnLightOn(self):\n self.isOn = True\n self.mainWin.settings_general_tip_of_the_day = 1\n self.setPixmap(self.l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Return all rows from sql table that match condition. | def read_all_rows(condition, database, table):
connection = sqlite3.connect(database)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute('SELECT * FROM ' + table + ' WHERE ' + condition)
rows = cursor.fetchall()
cursor.close()
connection.close()
return rows | [
"def select(self, table, columns=['*'], condition='', orderby='', limit=0, isFetchAll=True):",
"def get_rows(self, table_name, condition=None, limit='limit 10 offset 0'):\n if self.is_conn_open() is False:\n logger.error('连接已断开')\n return None\n # 参数判断\n if table_name is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Return cursor object which can iterate through rows matching condition. | def cursor_with_rows(condition, database, table):
connection = sqlite3.connect(database)
connection.row_factory = sqlite3.Row
cursor = connection.cursor()
cursor.execute('SELECT * FROM ' + table + ' WHERE ' + condition)
return cursor, connection | [
"def rowgen(searchcursor_rows):\n rows = searchcursor_rows\n row = rows.next() \n while row:\n yield row\n row = rows.next()",
"def find_if(self, condition):\n\t\tfor pos in self.keys():\n\t\t\tif conditi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Close connection and cursor. | def close(connection, cursor):
cursor.close()
connection.close() | [
"def disconnect(self):\n\n try:\n self.cursor.close()\n self.db.close()\n except cx_Oracle.DatabaseError:\n pass",
"def _closeConnection(cursor, db):\n cursor.commit()\n cursor.close()\n db.close()",
"def _close_cursor(self):\n self.cursor.close()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find where values of a first tensor are equal to values of a second one. | def where_in(a, b):
return torch.nonzero((a[..., None] == b).any(-1)).squeeze() | [
"def intersect1d(tensor1, tensor2):\n aux = torch.cat((tensor1, tensor2), dim=0)\n aux = aux.sort()[0]\n return aux[:-1][(aux[1:] == aux[:-1]).data]",
"def _equal_indices(a, b):\n if torch.is_tensor(a) and torch.is_tensor(b):\n return torch.equal(a, b)\n elif not torch.is_tensor(a) and not t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomly choose n elements from a 1dtensor. | def choose(n, a):
return torch.as_tensor([a[idx] for idx in torch.randperm(len(a))[:n]]) | [
"def get(self, n):\n return random.sample(self.samples, n)",
"def choose_at_random(dataset, n_instances):\n return dataset.sample(n = n_instances)",
"def sample_n(arr: np.ndarray, n: int) -> np.ndarray: # pylint: disable=C0103\n if len(arr) <= n:\n return arr\n\n subsel = np.linspace(0, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unpack the data from a JSON object and create encodings. This function assumes that for each synset, its lemma on highway is always at index 0. | def process_data(self, json_dict: dict):
all_token_ids = []
all_level_ids = []
all_synset_ids = []
all_lemma_ids = []
all_is_highway = []
all_targets = []
def tokenize(lemma_):
return self.tokenizer(
lemma_,
add_special... | [
"def band_json_to_py(band_json):",
"def json_to_packstream(cls, data):\n # TODO: other partial hydration\n if \"self\" in data:\n if \"type\" in data:\n return Structure(ord(b\"R\"),\n cls._uri_to_id(data[\"self\"]),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds spam information a graph for detection using Karger's algorithm. | def _add_spam_info_to_graph_k(graph, items, actions):
# Adds flag information (graph.add_answer(...)) to the graph object.
for act in actions:
if act.type == ACTION_FLAG_SPAM:
# Spam flag!
graph.add_answer(act.user_id, act.item_id, -1,
base_reliability = act.user.... | [
"def spam():",
"def spam(bot, msg):\n\n sendername = msg.sendername\n\n if msg.command != \"PRIVMSG\" or sendername in bot.services:\n return\n\n message = msg.args[1]\n\n if sendername not in spammers or message != spammers[sendername][0]:\n spammers[sendername] = [message, 0]\n else... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function udoes flagging spam/ham without checking for original action in the DB (it is assumed that it should be done outside the function) | def _undo_spam_ham_flag(item, user, session, spam_flag=True):
answr = -1 if spam_flag else 1
if item.sk_frozen:
# The item is known as spam/ham.
val = np.sign(item.sk_weight) * answr * BASE_SPAM_INCREMENT
user.sk_base_reliab -= val
return
# Okay, item participate in offline s... | [
"def _raise_spam_ham_flag_fresh(item, user, timestamp,\n session, spam_flag=True):\n # Creates a record in Action table\n if spam_flag:\n answr = -1\n act = ActionMixin.cls(item.id, user.id, ACTION_FLAG_SPAM, timestamp)\n item.spam_flag_counter += 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function flags spam/ham on the item. It is assumed that the item was not flagged as spam/ham by the user. | def _raise_spam_ham_flag_fresh(item, user, timestamp,
session, spam_flag=True):
# Creates a record in Action table
if spam_flag:
answr = -1
act = ActionMixin.cls(item.id, user.id, ACTION_FLAG_SPAM, timestamp)
item.spam_flag_counter += 1
else:
... | [
"def _undo_spam_ham_flag(item, user, session, spam_flag=True):\n answr = -1 if spam_flag else 1\n if item.sk_frozen:\n # The item is known as spam/ham.\n val = np.sign(item.sk_weight) * answr * BASE_SPAM_INCREMENT\n user.sk_base_reliab -= val\n return\n # Okay, item participate ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes spam action from the db, it takes care of spam flag counter. | def _delete_spam_action(act, session):
if act is None:
return
act.item.spam_flag_counter -= 1
session.delete(act) | [
"def delete(action):\n with DB.connection_context():\n action.delete_instance()",
"def delete_activity():\n pass",
"def delete_spam_item_by_author(item, session):\n actions = ActionMixin.cls.get_actions_on_item(item.id, session)\n if item.sk_frozen:\n # If the item is frozen th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If item is deleted by author then there is no reputation damage to the author, plus users who flagged it receive boost to base reliability. | def delete_spam_item_by_author(item, session):
actions = ActionMixin.cls.get_actions_on_item(item.id, session)
if item.sk_frozen:
# If the item is frozen then users who flagged it already got changes
# to their spam reliability.
# In this case the user's karma user also has changes to it... | [
"async def penalty(msg):\n incorrect_users.append(msg.author.id)\n penaltymsg = await msg.channel.send(msg.author.mention + \" +5s penalty.\")\n await penaltymsg.delete(delay=5)\n await asyncio.sleep(5)\n del incorrect_users[0]",
"def test_delete_muveto_gain_model_item(self):\n pass",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preprocess data after extracted for ml. As the the scale between features are very difference, running scaling normalization before put data into machine learning algorithm is essential. | def _preprocess(self, data, normalize=False) -> np.ndarray:
preprocessor = StandardScaler() if not normalize else Normalizer()
data = preprocessor.fit_transform(data)
return data | [
"def pre_processing (self, data, norm=False, std=False) :\n result = data\n if norm : \n result = Normalizer().fit_transform(data)\n if std : \n result = StandardScaler().fit_transform(data)\n return result",
"def scale_data(self):\n logging.info(\"[DataLoa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert and return a new vertex with value val | def add_vertex(self, u, val):
raise NotImplementedError() | [
"def create_vertex(value=None, datatype=None):",
"def add_vert(self, val):\n # Check if the supplied value is a valid dict key\n try:\n {val: 0}\n except TypeError:\n raise TypeError('Vertex values must be hashable types.')\n if not self.has_vert(val):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert and return a new edge from vertex u to v with value val (identifies the edge) | def add_edge(self, u, v, val):
raise NotImplementedError() | [
"def add_edge(self, u, v):",
"def add_edge(self, u, v):\r\n keys = self.d.keys()\r\n #if nodes are not in graph, add them\r\n if u not in keys:\r\n self.add_node(u)\r\n if v not in keys:\r\n self.add_node(v)\r\n #add each node to the value set of each other... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Connect to a pshell server in another process, note that this does not do any handshaking to the remote pshell or maintain a connection state, it meerly sets the internal destination remote pshell server information to use when sending commands via the sendCommandN functions and sets up any resources necessary for the ... | def connectServer(controlName, remoteServer, port, defaultTimeout):
return (_connectServer(controlName, remoteServer, port, defaultTimeout)) | [
"def connect_thread(service=VoidService, config={}, remote_service=VoidService, remote_config={}):\n listener = socket.socket()\n listener.bind((\"localhost\", 0))\n listener.listen(1)\n remote_server = partial(_server, listener, remote_service, remote_config)\n spawn(remote_server)\n host, port =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This command will add a controlList of multicast receivers to a multicast group, multicast groups are based either on a specified command, or if the special argument PSHELL_MULTICAST_ALL is used, the given controlList will receive all multicast commands, the format of the controlList is a CSV formatted list of all the ... | def addMulticast(command, controlList):
_addMulticast(command, controlList) | [
"def subscribe_to_mc_groups(addrs=None):\n\n listen_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP)\n listen_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n listen_sock.bind(('', DEFAULT_TDM_PORT))\n\n for mc in addrs:\n print(\"subscribing to {}\".format(m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This command will send a given command to all the registered multicast receivers for this multicast group, multicast groups are based on the command's keyword, this function will issue the command as a best effort fireandforget command to each receiver in the multicast group, no results will be requested or expected, a... | def sendMulticast(command):
_sendMulticast(command) | [
"def addMulticast(command, controlList):\n _addMulticast(command, controlList)",
"def multicast(self, groups, message):\n data_len = len(message)\n send_head = protocol_Create('SEND_MESS',self.private_name,groups,data_len)\n self.socket_send(send_head)\n \tmsg = struct.pack('!%ss'%data_le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a command overriding the default timeout, if the override timeout is 0, the server will not reply with a response and this function will not wait for one | def sendCommand2(controlName, timeoutOverride, command):
return (_sendCommand2(controlName, timeoutOverride, command)) | [
"def send_cmd(self,cmd,timeout=5):\n if not self.checkConnected():\n self.connect()\n \n while True:\n try:\n self.sock.recv(10000)\n except:\n break\n \n tic = time.time()\n try:\n self._send(cmd)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the largest prime factor of n | def largest_prime_fac(n):
divisor = 2
# Start with lowest prime and work through prime factors until highest is left
while divisor ** 2 < n:
while n % divisor == 0:
n = n / divisor
divisor += 1
return n | [
"def largest_prime_factor(n: int) -> int:\n i = 2\n while i * i <= n:\n if n % i:\n i += 1\n else:\n n //= i\n return n",
"def largest_prime_factor(n):\n return max(gen_prime_factors(n))",
"def largest_factor(n):\n stop = ceil(n ** 0.5)\n for i in range(2, s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Looks in config for legal server key, subkeys servername, username, and password then calls _ls_submit_online_intake with those values | def ls_submit_online_intake(params, task=None):
servername = daconfig.get('legal server',{}).get('servername')
username = daconfig.get('legal server',{}).get('username')
password = daconfig.get('legal server',{}).get('password')
return _ls_submit_online_intake(servername, username, password, params,task... | [
"def serverSetup(self):\n\t\tif self.serverDir is None:\n\t\t\tself.serverDir = os.getcwd()\n\t\tif self.user is None:\n\t\t\tself.user = pwd.getpwuid(os.geteuid()).pw_name \n\t\t# Set up the host key\n\t\tself.hostkey,self.hostkeypub = self.genkey(\"rsa\")",
"def process_ask_configs(config):\n\n if config.co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes IoU overlaps between two sets of masks. | def compute_overlaps_masks(masks1, masks2):
# If either set of masks is empty return empty result
if masks1.shape[-1] == 0 or masks2.shape[-1] == 0:
return np.zeros((masks1.shape[-1], masks2.shape[-1]))
# flatten masks and compute their areas
masks1 = np.reshape(masks1 > .5, (-1, masks1.sha... | [
"def compute_overlaps_masks(masks1, masks2):\r\n \r\n # If either set of masks is empty return empty result\r\n if masks1.shape[0] == 0 or masks2.shape[0] == 0:\r\n return np.zeros((masks1.shape[0], masks2.shape[-1]))\r\n # flatten masks and compute their areas\r\n masks1 = np.reshape(masks1 >... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs nonmaximum suppression and returns indices of kept boxes. | def non_max_suppression(boxes, scores, threshold):
assert boxes.shape[0] > 0
if boxes.dtype.kind != "f":
boxes = boxes.astype(np.float32)
# Compute box areas
y1 = boxes[:, 0]
x1 = boxes[:, 1]
y2 = boxes[:, 2]
x2 = boxes[:, 3]
area = (y2 - y1) * (x2 - x1)
# Get indicies of b... | [
"def non_max_suppression(self, filtered_boxes, box_classes, box_scores):\n sort_order = np.lexsort((-box_scores, box_classes))\n box_scores = box_scores[sort_order]\n box_classes = box_classes[sort_order]\n filtered_boxes = filtered_boxes[sort_order]\n del_idxs = []\n for i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies the given deltas to the given boxes. | def apply_box_deltas(boxes, deltas):
boxes = boxes.astype(np.float32)
# Convert to y, x, h, w
height = boxes[:, 2] - boxes[:, 0]
width = boxes[:, 3] - boxes[:, 1]
center_y = boxes[:, 0] + 0.5 * height
center_x = boxes[:, 1] + 0.5 * width
# Apply deltas
center_y += deltas[:, 0] * height
... | [
"def apply_box_deltas(boxes, deltas):\n height = boxes[:, 2] - boxes[:, 0]\n width = boxes[:, 3] - boxes[:, 1]\n center_y = boxes[:, 0] + 0.5 * height\n center_x = boxes[:, 1] + 0.5 * width\n center_y += deltas[:, 0] * height\n center_x += deltas[:, 1] * width\n height *= torch.exp(deltas[:, 2]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)] | def box_refinement_graph(box, gt_box):
box = tf.cast(box, tf.float32)
gt_box = tf.cast(gt_box, tf.float32)
height = box[:, 2] - box[:, 0]
width = box[:, 3] - box[:, 1]
center_y = box[:, 0] + 0.5 * height
center_x = box[:, 1] + 0.5 * width
gt_height = gt_box[:, 2] - gt_box[:, 0]
gt_widt... | [
"def box_refinement(box, gt_box):\n box = box.astype(np.float32)\n gt_box = gt_box.astype(np.float32)\n\n height = box[:, 2] - box[:, 0]\n width = box[:, 3] - box[:, 1]\n center_y = box[:, 0] + 0.5 * height\n center_x = box[:, 1] + 0.5 * width\n\n gt_height = gt_box[:, 2] - gt_box[:, 0]\n gt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)]. (y2, x2) is assumed to be outside the box. | def box_refinement(box, gt_box):
box = box.astype(np.float32)
gt_box = gt_box.astype(np.float32)
height = box[:, 2] - box[:, 0]
width = box[:, 3] - box[:, 1]
center_y = box[:, 0] + 0.5 * height
center_x = box[:, 1] + 0.5 * width
gt_height = gt_box[:, 2] - gt_box[:, 0]
gt_width = gt_box... | [
"def box_refinement(box, gt_box):\n box = box.astype(np.float32)\n gt_box = gt_box.astype(np.float32)\n\n height = box[:, 2] - box[:, 0]\n width = box[:, 3] - box[:, 1]\n center_y = box[:, 0] + 0.5 * height\n center_x = box[:, 1] + 0.5 * width\n\n gt_height = gt_box[:, 2] - gt_box[:, 0]\n gt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resizes a mask using the given scale and padding. Typically, you get the scale and padding from resize_image() to ensure both, the image and the mask, are resized consistently. | def resize_mask(mask, scale, padding, crop=None):
# Suppress warning from scipy 0.13.0, the output shape of zoom() is
# calculated with round() instead of int()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1], order=0)
... | [
"def resize_mask(mask, scale, padding):\n h, w = mask.shape[:2]\n mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1], order=0)\n mask = np.pad(mask, padding, mode='constant', constant_values=0)\n return mask",
"def resize_mask(mask, scale):\n # Suppress warning from scipy 0.13.0, the output sha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate anchors at different levels of a feature pyramid. Each scale is associated with a level of the pyramid, but each ratio is used in all levels of the pyramid. | def generate_pyramid_anchors(scales, ratios, feature_shapes, feature_strides,
anchor_stride):
# Anchors
# [anchor_count, (y1, x1, y2, x2)]
anchors = []
for i in range(len(scales)):
anchors.append(generate_anchors(scales[i], ratios, feature_shapes[i],
... | [
"def create_pyramid_anchors(scales, ratios, feature_shapes, feature_strides, anchor_stride):\n # Anchors\n # [anchor_count, (y1, x1, y2, x2)]\n anchors = []\n for i in range(len(scales)):\n anchors.append(\n create_anchors(scales[i], ratios, feature_shapes[i], feature_strides[i],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds matches between prediction and ground truth instances. | def compute_matches(gt_boxes, gt_class_ids, gt_masks,
pred_boxes, pred_class_ids, pred_scores, pred_masks,
iou_threshold=0.5, score_threshold=0.0):
# Trim zero padding
# TODO: cleaner to do zero unpadding upstream
gt_boxes = trim_zeros(gt_boxes)
gt_masks = gt_mask... | [
"def test_calculate_matches(self, gt_boxes, gt_class_ids, gt_masks, pred_boxes, pred_class_ids, pred_scores, pred_masks, iou_threshold=0.5, score_threshold=0.0):\n\n # Trim zero padding of the masks\n gt_boxes, pred_boxes = self.trim_zeros(gt_boxes), self.trim_zeros(pred_boxes)\n gt_masks, pred... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute AP over a range or IoU thresholds. Default range is 0.50.95. | def compute_ap_range(gt_box, gt_class_id, gt_mask,
pred_box, pred_class_id, pred_score, pred_mask,
iou_thresholds=None, verbose=1):
# Default is 0.5 to 0.95 with increments of 0.05
iou_thresholds = iou_thresholds or np.arange(0.5, 1.0, 0.05)
# Compute AP over r... | [
"def area_under_curve(\n predictions, labels, weights=None, num_thresholds=200,\n macro_average=False, curve='pr', values_collections=None,\n updates_collections=None, resets_collections=None, name='auc',\n requested_ops=None):\n curve = curve.lower()\n if curve != 'roc' and curve ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the recall at the given IoU threshold. It's an indication of how many GT boxes were found by the given prediction boxes. | def compute_recall(pred_boxes, gt_boxes, iou):
# Measure overlaps
overlaps = compute_overlaps(pred_boxes, gt_boxes)
iou_max = np.max(overlaps, axis=1)
iou_argmax = np.argmax(overlaps, axis=1)
positive_ids = np.where(iou_max >= iou)[0]
matched_gt_boxes = iou_argmax[positive_ids]
recall = len... | [
"def recall_thresholded(recommendations: List[Tuple[int, float]],\n ground_truth: List[int], threshold: float) -> float:\n valid_recommendations = [x[0] for x in recommendations\n if x[1] >= threshold]\n return recall(valid_recommendations, ground_truth)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits inputs into slices and feeds each slice to a copy of the given computation graph and then combines the results. It allows you to run a graph on a batch of inputs even if the graph is written to support one instance only. | def batch_slice(inputs, graph_fn, batch_size, names=None):
if not isinstance(inputs, list):
inputs = [inputs]
outputs = []
for i in range(batch_size):
inputs_slice = [x[i] for x in inputs]
output_slice = graph_fn(*inputs_slice)
if not isinstance(output_slice, (tuple, list)):... | [
"def _batch_graphs(graphs):\n result = graphs[0].clone()\n for idx in range(1, len(graphs)):\n result.append(graphs[idx])\n return result",
"def execute(self, g, inputs):\n \n if self._started:\n raise ValueError(\"Traverser can only be started once.\")\n self._started = True... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Download COCO trained weights from Releases. | def download_trained_weights(coco_model_path, verbose=1):
if verbose > 0:
print("Downloading pretrained model to " + coco_model_path + " ...")
with urllib.request.urlopen(COCO_MODEL_URL) as resp, open(coco_model_path, 'wb') as out:
shutil.copyfileobj(resp, out)
if verbose > 0:
print(... | [
"def download_yolo_weights(weights_path):\n from arcgis.gis import GIS\n gis = GIS(set_active=False)\n item = gis.content.get('8b4600eb9a29407bbfe51491ad5bf62c')\n print(f\"[INFO] Downloading COCO pretrained weights for YOLOv3 in {weights_path}...\")\n filepath = item.download(weights_path)\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes the comparison between the areas found by the fronts and the hand drawn fronts | def fast_comparison(path = "Data/data_fronts/",path1 = "Results/modified_images/fronts/"):
#computes the areas for the first frame in order to normalize the other areas
pol0dx = grid(path1+"m_0.png_dx.txt")
pol0dx.columns = ["y","x"]
pol0sx = grid(path1+"m_0.png_sx.txt")
pol0sx.columns = ["y","x"]
... | [
"def home():\n\n rect(screen, home_color, (width/16, height/2.5, width/6, height/4.5))\n polygon(screen, roof_color, [[width/17, height/2.5], [width/4.3, height/2.5], [width/7, height/5]])\n rect(screen, contours_color, (width/16, height/2.5, width/6, height/4.5), contours_thickness)\n polygon(screen, c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the error between two arrays of areas in L^2 | def error(area, area_hand):
#computes the error in L^2 between the two areas
error = np.sqrt((area - area_hand)**2)
return np.array(error) | [
"def epipolar_error(x1, x2, l1, l2): \n # calculate the distance between the line l1 and x1.\n\n dist = lambda point, line: np.abs(point[0]*line[0] + point[1]*line[1] + point[2]*line[2]) / np.sqrt(line[0]**2 + line[1]**2)\n\n d1 = dist(x1, l1)\n d2 = dist(x2, l2)\n\n # compute the total error.\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the velocity of the fronts. Since the Delta t is defined by the single frame, the velocity of the front results to be only the difference between the final and the initial position between two frames | def velocity(df0, df1):
velocity = df1 - df0
return velocity | [
"def computeVelocity(self, prevFrame, dt):\n for i, agent in enumerate(self.agents):\n agent.vel = (agent.pos - prevFrame.agents[i].pos) / dt",
"def get_velocity(self):\n self.velocity = 0.5*(self.f2[:-1]/self.f1[:-1]+self.f2[1:]/self.f1[1:])",
"def _compute_temporal_velocity(self):\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the Velocity Autocorrelation Fuction (VACF) which is the correlation between the velocities of the fronts | def VACF(df,conversion = "x"):
#conversion from pixels to micrometers
if conversion == "y":
df = df/1200*633
else:
df = df/1600*844
#computes the velocity in one direction between the frames
dif = pd.DataFrame()
for i in range(1,len(df.T)):
dif[i-1] = velocity(df[i-... | [
"def _var_acf(coefs, sig_u):\n p, k, k2 = coefs.shape\n assert k == k2\n\n A = util.comp_matrix(coefs)\n # construct VAR(1) noise covariance\n SigU = np.zeros((k * p, k * p))\n SigU[:k, :k] = sig_u\n\n # vec(ACF) = (I_(kp)^2 - kron(A, A))^-1 vec(Sigma_U)\n vecACF = np.linalg.solve(np.eye((k ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in a string and determines if the string has all unique characters. | def is_unique(a_string):
if len(a_string) is 0:
print "String is empty."
return False
chars = []
for char in a_string:
if char not in chars:
chars.append(char)
else:
return False
return True | [
"def has_all_unique_characters1(string):\n if type(string) != str:\n return(\"Hey that's not a string!\")\n all_unique = True\n char_count = []\n for i in range(len(string)):\n if string[i] in char_count:\n all_unique = False\n char_count.append(string[i])\n return(all... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the size of the QTable | def get_Q_size(self):
return len(self.qTable) | [
"def get_size(self):\n return len(self.table)",
"def __len__(self) -> int:\n return len(self.table)",
"def get_table_size_from_IS(self, table_name):\n result = self.query(sql.show_table_stats(self._current_db), (self.table_name,))\n if result:\n return result[0][\"Data_len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
[API router to undeploy a AutoML model] | async def undeploy_model(
undeploy_model_request: ManageModel,
token: str = Depends(oauth2_scheme),
):
try:
logging.info("Calling /gcp/automl/undeploy_model endpoint")
logging.debug(f"Request: {undeploy_model_request}")
if decodeJWT(token=token):
response = ManageModelCon... | [
"def UndeployModel(self, request, global_params=None):\n config = self.GetMethodConfig('UndeployModel')\n return self._RunMethod(\n config, request, global_params=global_params)",
"def _undeploy(\n self,\n deployed_model_id: str,\n traffic_split: Optional[Dict[str, int]] = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiates the publisher service client. | def __init__(
self,
*,
credentials: ga_credentials.Credentials = None,
transport: Union[str, PublisherServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
self.... | [
"def __init__(self, project, cred_json):\n super(PublisherClient, self).__init__(project, cred_json)\n # Instantiates a client\n self.client = pubsub_v1.PublisherClient(credentials=self.cred)",
"def __init__(self, broker_handler: SubscriberBrokerHandler, sm_service: SubscriptionManagerService... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts given value to long if possible, otherwise None is returned. | def field_to_long(value):
if isinstance(value, (int, long)):
return long(value)
elif isinstance(value, basestring):
return bytes_to_long(from_hex(value))
else:
return None | [
"def to_long(self, value):\n if value is not None:\n return long(value)",
"def to_nullable_long(value: Any) -> Optional[int]:\n if value is None:\n return None\n if type(value) == int or isinstance(value, float):\n return int(value)\n if isinstance(valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts textual status from the response statusdetail, if present. Otherwise extracts status field. | def get_text_status(json):
if json is None:
return None
elif 'statusdetail' in json:
return json['statusdetail']
elif 'status' in json:
return json['status']
else:
return None | [
"def extract_status(self, status) -> None:\r\n if \"VehicleInfo\" in status:\r\n if \"RemoteHvacInfo\" in status[\"VehicleInfo\"]:\r\n self.hvac = status[\"VehicleInfo\"][\"RemoteHvacInfo\"]\r\n\r\n if \"ChargeInfo\" in status[\"VehicleInfo\"]:\r\n self.bat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return next larger sparse number | def next_sparse(sparse_number):
# print("sparse_number 0b{0:b}".format(sparse_number))
# Edge case. Handle explicitly for clarity
if sparse_number == 0:
return 1
power_max = twos_power_max(sparse_number)
for power in range(0, power_max):
# print("power", power)
if is_zero... | [
"def next_sparse_incremental(sparse_number):\n\n\n # limit is arbitrary in Python\n # http://stackoverflow.com/questions/5470693/python-number-limit\n limit = 2 ** 32\n for possible_sparse in range(sparse_number + 1, limit):\n if is_sparse(possible_sparse):\n return possible_sparse\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return next larger sparse number | def next_sparse_incremental(sparse_number):
# limit is arbitrary in Python
# http://stackoverflow.com/questions/5470693/python-number-limit
limit = 2 ** 32
for possible_sparse in range(sparse_number + 1, limit):
if is_sparse(possible_sparse):
return possible_sparse
return None | [
"def next_sparse(sparse_number):\n\n # print(\"sparse_number 0b{0:b}\".format(sparse_number))\n\n # Edge case. Handle explicitly for clarity\n if sparse_number == 0:\n return 1\n\n power_max = twos_power_max(sparse_number)\n\n for power in range(0, power_max):\n # print(\"power\", power... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return True if number binary digit 1s have no adjacent 1s. | def is_sparse(number):
if number == 0:
return True
if number == 1:
# edge case. List explicitly for clarity. Define to be True
return True
else:
bits = bits_list(number)
# start power_of_2 at 1 so previous_bit index won't be out of list range
for power_of_2 i... | [
"def is_binary(number):\n for digit in number:\n if digit != '1' and digit != '0':\n return False\n return True",
"def hasAlternatingBits(self, n):\n\n # Convert input integer to binary representation\n binary = \"{0:b}\".format(n)\n print(binary)\n\n # Get the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return list of bits in number | def bits_list(number):
# https://wiki.python.org/moin/BitManipulation
if number == 0:
return [0]
else:
# binary_literal string e.g. '0b101'
binary_literal = bin(number)
bits_string = binary_literal.lstrip('0b')
# list comprehension
bits = [int(bit_character) ... | [
"def _bits_of_n(n):\n bits = []\n while n:\n bits.append(n % 2)\n n /= 2\n return bits",
"def get_bit_list(self) -> list:\r\n\t\tresult = []\r\n\t\tfor index in range(self.number_of_element):\r\n\t\t\tresult.append(self.is_bit(index))\r\n\r\n\t\tif self.bit_order == BitOrder.little:\r\n\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return bit in number at location 2 exponent | def bit_at_twos_power(number, exponent):
bits = bits_list(number)
# NOTE: reverse() modifies object, returns None
bits.reverse()
if exponent > (len(bits) - 1):
return 0
else:
return bits[exponent] | [
"def get_bit(num, position):\n\treturn (num >> position) & 0b1",
"def get_bit(number, position):\n if position < 0 or position > 31:\n return 0\n return (number >> (31 - position)) & 1",
"def get_bit(n, b):\n return ((1 << b) & n) >> b",
"def get_bit(number, index):\n return (number >> inde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return highest power of two in number | def twos_power_max(number):
bits = bits_list(number)
return len(bits) - 1 | [
"def get_highest_power_of_2(n):\n\t\tres = 0\n\t\tfor i in range(int(n), 0, -1):\n\t\t\t# if i is a power of 2\n\t\t\tif (i & (i - 1)) == 0:\n\t\t\t\tres = i\n\t\t\t\tbreak\n\t\treturn res",
"def next_power2(num):\n return 2 ** int(np.ceil(np.log2(num)))",
"def _find_nearest_power_of_two(x):\n\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format an AWS instance's metadata for reporting. | def format_aws_instance(cls, aws_instance):
instance_id = "Instance ID: {instance}".format(instance=aws_instance[0]) # NOQA
aws_account = "AWS Account: {account}".format(account=aws_instance[1]["aws_account"]) # NOQA
aws_region = "AWS Region: {region}".format(region=aws_instance[1]["aws_region... | [
"def format_aws_instance_csv(cls, aws_instance):\n result = {\"instance_id\": aws_instance[0],\n \"aws_account\": aws_instance[1][\"aws_account\"],\n \"aws_region\": aws_instance[1][\"aws_region\"],\n \"key_name\": aws_instance[1][\"key_name\"],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format an AWS instance's metadata for reporting in CSV format. | def format_aws_instance_csv(cls, aws_instance):
result = {"instance_id": aws_instance[0],
"aws_account": aws_instance[1]["aws_account"],
"aws_region": aws_instance[1]["aws_region"],
"key_name": aws_instance[1]["key_name"],
"launch_time": aw... | [
"def format_aws_instance(cls, aws_instance):\n instance_id = \"Instance ID: {instance}\".format(instance=aws_instance[0]) # NOQA\n aws_account = \"AWS Account: {account}\".format(account=aws_instance[1][\"aws_account\"]) # NOQA\n aws_region = \"AWS Region: {region}\".format(region=aws_instanc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) | def registerPlayer(name):
# gets connection to tournament database in conn object
conn = connect()
# gets the cursor to execute queries
c = conn.cursor()
# executes insert query which takes the name variable passed in arguments
# of this method and adds a new player record to PLAYER table where ... | [
"def registerPlayer(player_name, tournament_id=\"\"):\n db = connect()\n cursor = db.cursor()\n # Different decisiions based on the tournament id.\n # Using 0 as a standard blank tournament that's included in my sql\n if tournament_id != \"\":\n cursor.execute(\"INSERT INTO Players (player_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearlyequal win record, that is, a player adjacent to him or her in the standings. | def swissPairings():
# retreives player standings i.e. id, player, wins, matches
standings = playerStandings()
# pairs for next round are stored in this array.
next_round = []
# iterates on the standings results. As the results are already in
# descending order, the pairs can be made using adja... | [
"def swissPairings(self):\r\n\r\n # Returns a list of temp_pairs of players for the next round of a match.\r\n self.round += 1\r\n next_match_pairings = []\r\n standings = self.playerStandings()\r\n previous_pairings = self.get_previous_pairings()\r\n\r\n\r\n #loop until no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds two Reco objects, returns a Reco object. | def addReco(obj1,obj2):
px = obj1.px + obj2.px
py = obj1.py + obj2.py
pz = obj1.pz + obj2.pz
E = obj1.E + obj2.E
return Reco(px,py,pz,E) | [
"def __add__(self, other):\n return self.__class__(self._docs + other)",
"def __add__(self, other):\n self._check_arithmetic(other)\n\n roi = ROI()\n roi.set(self.rois, self.data + other.data)\n\n return roi",
"def __add__(self, other):\n t = deepcopy(self)\n t.m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a Reco object to a string. | def stringReco(obj):
name = obj.get_name()
name = obj._pid if (name is None) else name
return ("pdg: " + name + " E: " + str(obj._E)
+ " px: " + str(obj._px) + " py: " + str(obj._py)
+ " pz: "+ str(obj._pz) + " mass: " + str(obj._m)) | [
"def get_str(self, obj):\n return str(obj)",
"def str_(object_):\n return str(object_)",
"def obj_to_string(rental):\n string = rental.id + ';' + rental.movie_id + ';' + rental.client_id + ';' \\\n + str(rental.rented_date) + ';' + str(rental.due_date) + ';' + str(rental.returned_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends an email to the user who requested a new password or a confirmation email to a user who has reset his or her password. If email and password is set, a mail is sent to a newly registrated user. If email and token is set, a request to reset password is sent to the user with a link and a temporary token. If only the... | def email_user(to_email, password=None, token=None):
try:
if password and token:
raise Exception('No email has been sent. Both token and password is set.')
mail = Mail(APP)
if to_email and password:
message = Message(
'Resel... | [
"def send_user_reset_email(request, email, password):\n\n c = {\n 'email': email,\n 'password': password,\n }\n send_html_email(_(u'Password has been reset on %s') % get_site_name(),\n 'sysadmin/user_reset_email.html', c, None, [email])",
"def post(self):\n data = requ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads outfile to the storage element at dst_url under output directory outdir, returns 0 on success, raises an exception on error. | def upload(outfile, outdir):
outpath = outdir + "/" + outfile
my_env = os.environ.copy()
my_env["X509_USER_PROXY"] = dst_cred
for retry in range(0,99):
try:
subprocess.check_output(["globus-url-copy", "-create-dest",
"-rst", "-stall-timeout", "300",
... | [
"def upload(self, src, dst):\r\n raise NotImplementedError()",
"def testSaveLocalFile(self):\n # Set path to None so we don't try to initialize GCS outout writer.\n config.GCS_OUTPUT_PATH = None\n self.task.output_manager.setup(self.task.name, self.task.id)\n tmp_dir, local_dir = self.task.outp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge the output hddm files from the individual jobs into a single hddm file for each input raw data file. Returns 0 on success, nonzero on error. | def merge_hddm_output(run, seqno, slices):
inset = {"REST": "dana_rest.hddm",
"converted_random": "converted_random.hddm",
}
outset = {"REST": "dana_rest_{0:06d}_{1:03d}.hddm",
"converted_random": "converted_random_{0:06d}_{1:03d}.hddm",
}
badslices = []
slice... | [
"def upload_output_files_metadata(self):\n if os.environ.get('TEST_POSTJOB_NO_STATUS_UPDATE', False):\n return\n edm_file_count = 0\n for file_info in self.output_files_info:\n if file_info['filetype'] == 'EDM':\n edm_file_count += 1\n multiple_edm = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if it's a JavaScript source. | def test_js_source(self):
actual = is_js_source(self.view)
self.assertTrue(actual) | [
"def is_javascript(view):\n # Check the file extension\n name = view.file_name()\n extensions = set(settings.get('extensions'))\n if name and os.path.splitext(name)[1][1:] in extensions:\n return True\n # If it has no name (?) or it's not a JS, check the syntax\n syntax = view.settings().ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return false if it's not a JS source. | def test_non_js_source(self):
self.view.set_syntax_file("Packages/Python/Python.tmLanguage")
actual = is_js_source(self.view)
self.assertFalse(actual) | [
"def test_js_source(self):\n actual = is_js_source(self.view)\n\n self.assertTrue(actual)",
"def is_javascript(view):\n # Check the file extension\n name = view.file_name()\n extensions = set(settings.get('extensions'))\n if name and os.path.splitext(name)[1][1:] in extensions:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple test of applyFunction() function. The function we'll apply is exp(x) so this is equivalent to the test_exp tests above | def test_applyFunction(self):
ptwise_linear = XYs1d(axes=XYs1d.defaultAxes(labelsUnits={
XYs1dModule.yAxisIndex: ('crossSection', 'b'),
XYs1dModule.xAxisIndex: ('energy_in', 'eV')}), data=[[1e-5, 1.0], [20.0e6, 21.0]])
self.assertAlmostEqual(ptwise_linear.evaluate(15.0e6), 16.0... | [
"def test_exp_basic(self):\n\n def test_f(a):\n b = torch.exp(a)\n return torch.exp(b)\n\n x = torch.randn(4)\n\n jitVsGlow(test_f, x, expected_fused_ops={\"aten::exp\"})",
"def test_exp(self):\n funcs = ['exp', 'exp_']\n for func in funcs:\n ten... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates authentication signature and return it in a dictionary | def generate_auth_dict(self) -> Dict[str, str]:
# api.exchange.bitcoin.com uses Basic Authentication https://api.exchange.bitcoin.com/#authentication
message = self.api_key + ":" + self.secret_key
signature = base64.b64encode(bytes(message, "utf8")).decode("utf8")
return {
... | [
"def generate_signature(self, auth_payload) -> (Dict[str, Any]):\n return hmac.new(\n self.secret_key.encode('utf-8'),\n msg=auth_payload.encode('utf-8'),\n digestmod=hashlib.sha256).hexdigest()",
"def generate_auth_dict(\n self,\n path_url: str,\n ):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
串联方式生成列表 时间复杂度为O(n) n为数据数量 这个可以理解为单链表的添加(通过指针) (python内部list的实现是PyObject ob_item) 假设空间足够,每次在首部添加了内容之后,添加内容之前的所有 元素都有后移, 故效率不高 | def test1():
l = []
for i in range(1000):
l = l + [i] | [
"def gen_list(size: int) -> list:\n return list(range(size))",
"def nlist(length):\n # noinspection PyUnusedLocal\n return [[] for l in range(length)]",
"def create_list(vals):\n my_list = LinkedList()\n for i in vals:\n my_list.insert(i)\n return my_list",
"def BufferList(self) -> _n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
bspline basis function c = number of control points. n = number of points on the curve. degree = curve degree | def bspline_basis(c, n, degree):
# Create knot vector and a range of samples on the curve
kv = np.array([0] * degree + [i for i in range(c - degree + 1)] +
[c - degree] * degree, dtype='int') # knot vector
u = np.linspace(0, c - degree, n) # samples range
# Cox - DeBoor recursive fu... | [
"def bspline(cv, n=100, degree=3, periodic=False):\n\n\t# If periodic, extend the point array by count+degree+1\n\tcv = np.asarray(cv)\n\tcount = len(cv)\n\tif periodic:\n\t\tfactor, fraction = divmod(count+degree+1, count)\n\t\tcv = np.concatenate((cv,) * factor + (cv[:fraction],))\n\t\tcount = len(cv)\n\t\tdegree... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a string in scientific notation format to a float in regular format | def sci_notation_to_float(n):
if 'e' in n:
exponent = float(n[n.find('e') + 1:])
number = float(n[:n.find('-') - 1])
number *= 10**exponent
return number
return n | [
"def parse_non_hex_float(s):\n f = float(s)\n # successfully parsed as float if here - check for format in original string\n if 'e' in s and not ('+' in s or '-' in s):\n raise ValueError('could not convert string to float: ' + s)\n return f",
"def make_float(self,\n s,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses needed information from HAAR training data in an XML | def haar_parser():
tree = ET.parse('haarcascade_frontalface_alt.xml')
root = tree.getroot()
stage_number = 0
for haar_data in root.findall('haarcascade_frontalface_alt'):
for stage in haar_data.findall('stages'):
for underscore in stage.findall('_'):
for tree in und... | [
"def _populate_from_xml_file(self, xml):\n '''\n example from API: http://www.ga.gov.au/www/argus.argus_api.survey?pSurveyNo=921\n\n <?xml version=\"1.0\" ?>\n <ROWSET>\n <ROW>\n <SURVEYID>921</SURVEYID>\n <SURVEYNAME>Goomalling, WA, 1996</SURVEYN... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Should print the given configuration to stdout. | def test_print_config(self) -> None:
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.config.print()
self.assertEqual(
out.getvalue().rstrip(),
"{}: {}\n{}".format("q2", "abcdefghij", "^".rjust(7)),
) | [
"def config_(config: Configuration) -> None:\n print_configuration(config)",
"def print(self):\n self._config.write(sys.stdout)",
"def print_config(_run):\n final_config = _run.config\n config_mods = _run.config_modifications\n print(_format_config(final_config, config_mods))",
"def print_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Should be able to iterate over a Turing machine tape. | def test_tape_iteration(self) -> None:
tape = TMTape(
tape="abcdef",
blank_symbol=".",
current_position=2,
)
self.assertEqual(tuple(tape), ("a", "b", "c", "d", "e", "f")) | [
"def run(self, tape):\r\n while True:\r\n for item in self.recipe:\r\n if item[0] == tape.currentCondition():\r\n tape.update(item[1])\r\n break\r\n else:\r\n break\r\n print(tape)",
"def main():\n infile = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens a cloud manifest file at `path` Converts headers of file to lowercase since partners choose to capitalize arbitrarily returns dictionary | def read_data_from_cloud_manifest(path: str) -> dict:
with open_cloud_file(path, 'r') as csv_file:
def clean_file_header(header: str) -> str:
return header.strip().lower()
data_to_ingest = {'rows': []}
csv_reader = csv.DictReader(csv_file, delimiter=",")
... | [
"def load_manifest(path: Path):\n with open(path, \"rt\") as fin:\n data = json_load(fin)\n return Manifest.schema().load(data, many=True)",
"def parse_manifest(manifest_path):\n with open(manifest_path, 'r') as f:\n data = f.read()\n if data:\n return json... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Entrypoint for SMS Workflow execution. Creates a SmsJobController and determines which process to run | def execute_workflow(self):
logging.info(f"called {self.job} with {self.file_type}")
job_params = {
"job": self.job,
"job_run_dao": self.job_run_dao,
"incident_dao": self.incident_dao,
"subprocess": self.file_type
}
with SmsJobController(... | [
"def makeWorkflow(self):\n self.timestamp = int(time.time())\n self.workflow = WorkflowSpec()\n self.workflowName = \"AlcaSkim-Run%s-%s\" % \\\n (self.run, self.primaryDataset)\n\n self.workflow.setWorkflowName(self.workflowName)\n self.workflow.setReque... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the adding of an emoji to a server. | async def process_add_emoji(
emoji,
emoji_name,
user_id,
ctx: commands.Context = None,
inter: AppCmdInter = None,
allowed_mentions=None,
):
response_deferred = await defer_inter(inter)
url = emoji if not isinstance(emoji, disnake.PartialEmoji) else emoji.url
user = await User.get(use... | [
"def emoji_callback(**payload):\n web_client = payload['web_client']\n\n event_type = payload['data']['subtype']\n emoji_name = payload['data']['name'] if event_type == 'add' else payload['data']['names'][0]\n\n send_emoji_message(web_client, 'admin', emoji_name, event_type)",
"async def add_emoji(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send the command prefixes of a guild. | async def process_prefix_list(
guild: disnake.Guild,
ctx: commands.Context = None,
inter: AppCmdInter = None,
allowed_mentions=None,
):
await create_guild_model(guild)
guild = await Guild.get(guild.id)
msg = f"The following are the custom prefixes for {guild.name}:\n" + ", ".join(
gu... | [
"async def prefix(self,ctx):\r\n\t\ttry:\r\n\t\t\tprefixes = self.bot.config[f\"{ctx.guild.id}\"][\"prefix\"]\r\n\t\texcept KeyError:\r\n\t\t\tself.bot.config[f\"{ctx.guild.id}\"][\"prefix\"] = ['$','!','`','.','-','?']\r\n\t\t\tawait self._save()\r\n\t\t\tprefixes = self.bot.config[f\"{ctx.guild.id}\"][\"prefix\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |