query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Function that return the url where to read the status.
def get_server_read_status_url(self): read_url: str = self.bot_data_file["bot_status"]["server_state_saving"]["readStateUrl"] if self.get_bot_save_state_to_server() and read_url.startswith(self.empty_url): print( "save_state_to_server IS TRUE BUT STATUS READ URL STARTS WITH '...
[ "def get_absolute_url(self):\n return \"/status/%i/\" % self.id", "def url(self):\n self._validate_status()\n return self.details.get('url')", "def get_status_callback_url(self):\n return [obj for obj in self._request_uri(\"status_callback_url\")]", "def get_status_url(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that return the username for the meme generator
def get_meme_generator_username(self): key = self.bot_data_file["meme_generator"]["username"] if self.check_empty_key(key): return key else: print("ERROR GETTING THE MEME USERNAME (register on https://api.imgflip.com/) - BOT ABORTING") quit(1)
[ "def generateUsername(self):\n retval= \"{0}.{1}\".format( self.first_name.split()[0].lower(),\n self.last_name.split()[-1].lower() )\n \n return toAscii(retval)", "def _random_username():\n symbols_gen = string.ascii_uppercase...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that return the password for the meme generator
def get_meme_generator_password(self): key = self.bot_data_file["meme_generator"]["password"] if self.check_empty_key(key): return key else: print("ERROR GETTING THE MEME PASSWORD (register on https://api.imgflip.com/) - BOT ABORTING") quit(1)
[ "def passwordGen() :\n\treturn __randomString(12)", "def generate_password():\n gen_pass = Credential.generate_password()\n return gen_pass", "def password_generate(self):\n password = ''\n password_base = self._password_base()\n for _ in range(self.size):\n password += cho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that return the owner ID to send private messages
def get_owner_private_messages(self): owner_id = self.bot_data_file["owners_data"]["ownerPrivateMessagesID"] if owner_id == "": print("ERROR GETTING THE OWNER ID - EMPTY") return "" else: return owner_id
[ "def owner_id(self) -> int:\n return pulumi.get(self, \"owner_id\")", "def bot_owner_id(self):\n return self._bot_owner_id", "def _GenerateOwnerId(self):\r\n self._SetOwnerId(str(random.getrandbits(48)))", "def owner_id(self):\n return self._owner_id", "def owner_uuid(self) -> str:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that return all the owners of the bot that have master permissions
def get_owners_list(self): final_list = [] for entry in self.bot_data_file["owners_data"]["owners_list"]: final_list.append(str(entry["name"])) if len(final_list) == 0: print("ERROR GETTING THE OWNERS LIST (i need at least 1 owner) - BOT ABORTING") quit(1) ...
[ "def owners(self):\n return self.find_users_by_rel('owner')", "def is_owner(ctx):\n return ctx.author.id in owners", "def owners_only(command):\n @wraps(command)\n def wrapped_up(bot):\n if bot.message.nick not in conf.get('owners', []):\n return irc.Response('Sorry, you are no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the network with the first layer of nodes in state x
def run_network(self, x): # We have the input vector x, this is the first layer in our nn a = x # So we need to run the neural network now. We are going to make # things extra explicit by having the z term. Clearly super # inefficient for w, b in zip(self.weights, self...
[ "def trainNet():", "def run_through_model(self, x):\n\n for idx, (W, b) in enumerate(zip(self._conv_weights, self._conv_biases)):\n curr_n = self.n_values[idx]\n curr_k = self.k_values[idx]\n\n x = self.conv_layer_as_matrix_op(W, b, x, curr_n, curr_k)\n x = x.fla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modify /etc/hosts and test if a log exists by running \'sudo journalctl f\'
def test_host_file_audit(host): with host.sudo(): host.run("touch /etc/hosts") audit_log = host.run("journalctl -u auditd --since \"10 seconds ago\" | grep \"/etc/hosts\"") assert audit_log.stdout
[ "def add_to_hosts(ip, fqdn):\n with open('/etc/hosts', 'r+') as hdl:\n if fqdn in hdl.read():\n return -1\n hdl.write('{ip} {fqdn} {name}\\n'.format(ip=ip, fqdn=fqdn, name=fqdn.split('.')[0]))\n return 0", "def setup_hosts():\n if not getattr(env, 'hostname', None):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modify /etc/sudoers and test if a log exists by running \'sudo journalctl f\'
def test_sudoers_audit(host): with host.sudo(): sudoers_access = host.run("touch /etc/sudoers") audit_log = host.run("journalctl -u auditd --since \"10 seconds ago\" | grep \"/etc/sudoers\"") assert audit_log.stdout
[ "def in_sudo_mode():\n if not 'SUDO_UID' in os.environ.keys():\n print(\"Try running this program with sudo.\")\n exit()", "def check_upstart():\n conf = env.upstart_script+'.conf'\n sudo('test -f /etc/init/'+conf+' || cp etc/'+conf+' /etc/init')\n sudo('diff etc/'+conf+' /etc/init/'+con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
s > hash code
def get_hash_code(s): h = 0 n = len(s) for i, c in enumerate(s): h = h + ord(c) * 31 ** (n - 1 - i) return StrUtil.convert_4_bytes(h)
[ "def hashFunc(s):\n return abs(hash(s))", "def state_hash(self, s):\n pass", "def elf_hash(s):\n h = 0\n for c in s:\n h = (h << 4) + ord(c)\n t = (h & 0xF0000000)\n if t != 0:\n h = h ^ (t >> 24)\n h = h & ~t\n return h", "def hash(x) -> int:\n pass"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get default channel list
def get_api_default_channel_list(self): url = "http://api.applezhuan.com/api/c/get_default_channellist?&" params = { "android_id": self.mobile.android_id, "platform": "2", "av": "2", "type": "1", "time": self.get_current_time, "ov":...
[ "def listAvailableCommunicationChannels():", "def get_channels():\n all_channels = channels\n emit(\"channels_all\", all_channels)", "def channels(self):\n if not self.is_loaded():\n return []\n else:\n return ipmi_channels()", "def getDefaultCommunicationChannel():",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get content info by id
def get_content_by_id(self, content_id): url = "http://api.applezhuan.com/api/m/get_content?content_id=%s" % content_id headers = { "Host": "api.applezhuan.com", "Connection": "keep-alive", "Accept": "application/json", "Origin": "http://m.applezhuan.com",...
[ "def get_content_by_id_get(self, head, id, locale):\n # TODO: Assuming first server is good - need to make fallback logic\n return self.session.get_any(\"{base}{request_url}\".format(base=self.servers[0],\n request_url=F\"/Content/GetCont...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Padding s to 16bits.
def pad(s): return s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
[ "def _pad16(s):\r\n l = 16 - len(s) % 16\r\n if l < 16:\r\n s = s + ''.join([' '] * l)\r\n return s", "def _pad(self, s):\n if len(s) > 65535:\n raise ValueError(\"Maximum plaintext size is 65535 bytes.\")\n # Minimum ciphertext size is 64 bytes to conceal the length of sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate lat and lon
def gen_lat_lon(self): delta = round(random.random() * random.randint(1, 4), 4) sign = random.randint(1, 100) if sign % 2 == 0: self.lat += delta else: self.lat -= delta delta = round(random.random() * random.randint(1, 4), 4) sign = random.randin...
[ "def random_gps_gen_from_range(s_lat,n_lat, e_lon, w_lon):\n #print(s_lat, n_lat, e_lon, w_lon)\n latitude = random.uniform(s_lat, n_lat)\n longitude = random.uniform(e_lon, w_lon)\n return latitude, longitude", "def generate_longitude_and_latitude():\n min_x = random.randint(-180, 180) # 西经\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a mobile info
def get_mobile_info(self): # 1. select brand self.select_brand() # 2. select os self.select_os() # 3. device_id self.gen_device_id() # 4. lat lon self.gen_lat_lon() # 5. mac self.gen_mac()
[ "def get_phone_info(self):\n self.title()\n # 获取所有手机型号等信息 #\n self.kill_other_python()\n\n android_phone = GetPhoneInfoAndroid().get_phone_info()\n ios_phone = GetPhoneInfoIos().get_phone_info()\n device = dict(android_phone, **ios_phone)\n\n # Appium可使用的端口 #\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
login the mobile and save into database
def save_login(mobile): mobile = Mobile(mobile) ktt = KTT(mobile) ktt.gen_device_code() ktt.get_api_start() time.sleep(4) ktt.post_login() time.sleep(4) ktt.get_user_info() user_info = ( ktt.user_info["uid"], ktt.user_info["name"], ktt.user_info["mobile"], ktt.user_in...
[ "def login(self):", "def login():", "def login(self):\n self.open(self.urls['login'])\n self.select_form(nr=0)\n\n self.form['custno'] = self.username\n self.form['password'] = self.password\n res = self.submit()\n \n return res", "def login_in():", "def logi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a car using a couple positional parameters and and arbitrary number of arguments as car.
def make_car(manufacturer, model, **car): car['manufacturer'] = manufacturer car['model'] = model return car
[ "def make_car(manufacturer, name, **car_info):\n car_profile = {}\n car_profile['Manufacturer'] = manufacturer\n car_profile['Model name'] = name\n for key, value in car_info.items():\n car_profile[key] = value\n return(car_profile)", "def make_car(manufacturer, model, **options):\r\n car...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do the bandwidth limitations
def limit(): bwc = BandwidthConfigurator() bwc.limit()
[ "def limit_bandwidth(self):\n return self._limit_bandwidth", "def bandwidth_limit(self) -> 'outputs.BandwidthLimitResponse':\n return pulumi.get(self, \"bandwidth_limit\")", "def get_hard_limit():", "def change_bandwidth(self,edge_notice):\n #print(\"==============带宽控制=============\",edge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the path to the link info file in the config.json file
def update_link_info_path(path_to_link_info): if not systeminfo.file_exists(path_to_link_info): print("File "+str(path_to_link_info)+" does not exist") exit(1) else: try: with open(Constants.path_to_config_file, "r") as jsonFile: data = json.load(jsonFile) ...
[ "def update_link(self):\n output_link_path = self.conf_reader.data_args.get('output_link_path')\n try:\n os.remove(output_link_path)\n logging.info(\"Remove link file succeed\")\n except Exception as e:\n logging.error(\"Remove link file failed\" + str(e))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the default bandwidth in the config.json file
def update_default_bw(default_bandwidth): try: bw = int(default_bandwidth) except ValueError: error_exit() if bw < 0: error_exit() try: with open(Constants.path_to_config_file, "r") as jsonFile: data = json.load(jsonFile) data["DefaultBandwidth"] = b...
[ "def auto_bandwidth(self, bandwidth):\n l2tester.Sender.auto_bandwidth(self, int(bandwidth*1000))", "def bandwidth(self, bandwidth):\n self._bandwidth = bandwidth", "def test_change_default_throttling_settings_http_with_overwrite_throttled_burst_above_account_quota():", "def test_change_default_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit because there were invalid arguments.
def error_exit(): print("Invalid arguments!") print("Type -h to get help.") exit(0)
[ "def bad_args(args):\n PARSER.print_help()\n exit(0)", "def exit_error_invalid_args_count(valid_count: int, supplied_count: Optional[int] = None):\n\n\tmessage = f\"Invalid count of arguments. Program takes: {valid_count}.\"\n\tif (supplied_count != None):\n\t\tmessage = f\"{message} Supplied: {supplied_cou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the material ID from URL parameter 'mat_id', or return one for testing.
def get_mat_id(): try: name = curdoc().session_context.request.arguments.get('mat_id')[0] if isinstance(name, bytes): mat_id = name.decode() except (TypeError, KeyError, AttributeError): mat_id = '05001N2' # equivalent of http://localhost:5006/details?mat_id=05001N2 ret...
[ "def get_mat_id():\n try:\n name = curdoc().session_context.request.arguments.get('mat_id')[0]\n if isinstance(name, bytes):\n mat_id = name.decode()\n except (TypeError, KeyError, AttributeError):\n mat_id = '05001N2' # equivalent of http://localhost:5006/detail?mat_id=05001N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a table of geometric properties, given the Zeopp output.
def get_geom_table(zeopp): # Usefull: ⁻¹²³⁴⁵⁶⁷⁸⁹⁰Å decimals = 2 md_str = """ |||| |---|---|---| | Density | {} g/cm³ | | | Access. Surface Area | {} m²/g | {} m²/cm³ | | Non-Access. Surface Area | {} m²/g | {} m²/cm³ | | Acces...
[ "def _engprop(l): # {{{1\n print(\" \\\\begin{tabular}[t]{rcrrl}\")\n print(\" \\\\multicolumn{4}{c}{\\\\small\"\n \"\\\\textbf{Laminate stacking}}\\\\\\\\[0.1em]\")\n print(\" \\\\toprule %% \\\\usepackage{booktabs}\")\n print(\" Layer & Weight & Angle & vf & Fiber type\\\\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return URL to EXPLORE section for given uuid.
def get_provenance_url(uuid): return '{explore_url}/details/{uuid}'.format(explore_url=EXPLORE_URL, uuid=uuid)
[ "def uuidToURL(uuid):\n site = getSite()\n catalog = getToolByName(site, 'portal_catalog')\n res = catalog.unrestrictedSearchResults(UID=uuid)\n if res:\n plt = getToolByName(site, 'portal_languages')\n # Check if a translation in the requested language exists\n # XXX Could be made ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return pn.HTML representation of provenance link.
def get_provenance_link(uuid, label=None): if label is None: label = "Browse provenance\n" + uuid html_str = "<a href='{link}' target='_blank'><img src='{logo_url}' title='{label}' class='provenance-logo'></a>"\ .format(link=get_provenance_url(uuid), label=label, logo_url=AIIDA_LOGO_PATH) ...
[ "def provenance_link(uuid, label=None):\n\n if label is None:\n label = \"Browse provenance\\n\" + uuid\n\n logo_url = \"detail/static/images/aiida-128.png\"\n explore_url = os.getenv('EXPLORE_URL', \"https://dev-www.materialscloud.org/explore/curated-cofs\")\n return pn.pane.HTML(\n \"<a ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return pn.Row representation of title. Includes provenance link, if uuid is specified.
def get_title(text, uuid=None): if uuid is not None: text += get_provenance_link(uuid) title = pn.Row(pn.pane.HTML('<h2>{}</h2>'.format(text)), align='start') return title
[ "def get_title(text, uuid=None):\n title = pn.Row(pn.pane.Markdown('#### ' + text), align='start')\n\n if uuid is not None:\n title.append(provenance_link(uuid))\n\n return title", "def link_title(self):\n\n if self.publication_type == u'link' and 'v12' in self.data:\n return sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receives an instance of a BasicDesignParameter object and returns its value in field units (if possible)
def GetValueInFieldUnits(self, designParam): val = None try: val = designParam.GetValue() if val != None and designParam.GetInfoType() & USESUNIT_INFO: unitType = designParam.GetType().unitType if unitType: unit = S42Glob.unitSy...
[ "def parameter_units(self) -> Tuple[str]:", "def get_units(name):\r\n from ..prms import Helper\r\n\r\n help = Helper()\r\n\r\n if name in help.prms_parameter_names:\r\n return help.prms_parameter_names[name][\"Units\"]\r\n\r\n elif name in help.prms_output_variables:\r\n return help.prm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receives an instance of a BasicDesignParameter object (designParam) and a value (valueInField). Converts valueInField into sim42 units and sets it into designParam
def SetValueFromFieldUnits(self, designParam, valueInField): val = valueInField try: if val != None and designParam.GetInfoType() & USESUNIT_INFO: unitType = designParam.GetType().unitType if unitType: unit = S42Glob.unitSystem.GetSim42Unit...
[ "def GetValueInFieldUnits(self, designParam):\n val = None\n try:\n val = designParam.GetValue()\n if val != None and designParam.GetInfoType() & USESUNIT_INFO:\n unitType = designParam.GetType().unitType\n if unitType:\n unit = S4...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get ids and OrgIds by lpu data list lpu_list contains info from `findOrgStructureByAddress` remote method
def _get_lpu_ids(self, lpu_list): for key, item in lpu_list: query = (self.session.query(UnitsParentForId.OrgId, LPU.id) .filter(UnitsParentForId.LpuId == LPU.id) .filter(LPU.key == item['serverId']) .filter(UnitsParentForId.ChildId == i...
[ "def get_lists_in(uid):", "def get_list_ids():", "def get_list_information(listids=None):", "def test_retrieve_l_organization_locations(self):\n pass", "def test_retrieve_l_organizations(self):\n pass", "def getOrgStructures(self, organisationInfis):\n pass", "def getOrgStructures(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get LPU by id and check if proxy url is available
def get_by_id(self, id): try: result = self.session.query(LPU).filter(LPU.id == int(id)).one() except NoResultFound, e: print e logger.error(e, extra=logger_tags) else: result.proxy = result.proxy.split(';')[0] if result.protocol in ('i...
[ "def get_proxy_by_id(self, name, id):\n cls, pending, connected = self._proxies[name]\n for proxy in pending:\n if proxy.id == id:\n return proxy\n for proxy in connected:\n if proxy.id == id:\n return proxy", "def get_proxy(self, proxy_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get LPU.uid by code
def get_uid_by_code(self, code): try: result = self.session.query(LPU.id).filter(LPU.key == code).one() except NoResultFound, e: logger.error(e, extra=logger_tags) print e except MultipleResultsFound, e: logger.error(e, extra=logger_tags) ...
[ "def uid():\n\tpass", "def make_uid(cls):\n big_time = TIMERS.time * _uid_timecode_multiplier\n if big_time > Entity.__uid_timecode:\n Entity.__uid_timecode = big_time\n else:\n Entity.__uid_timecode += 1\n timecode_string = int_to_base_n(Entity.__uid_timecode,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get LPU_Unit by id
def get_by_id(self, id): try: result = self.session.query(LPU_Units).filter(LPU_Units.id == int(id)).one() except NoResultFound, e: logger.error(e, extra=logger_tags) print e else: return result return None
[ "def get_unit_by_id(unit_id):\n # unit ID should always be a string\n unit_id = str(unit_id)\n data = get_data()\n if data and unit_id in data:\n unit_data = data[unit_id]\n should_ring_bell = unit_data.get('chime', 1)\n recipients = unit_data.get('recipients') or {}\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return generated pdf for ticket print !NOT USED
def __get_ticket_print(self, **kwargs): # TODO: выяснить используется ли pdf в принципе. В эл.регестратуре он никак не используется # TODO: pdf creator based on Flask templates and xhtml2pdf return ""
[ "def make_pdf():\n d = datetime.utcnow()\n report_date = d.strftime(\"%Y%m%d%H%M%S\")\n report_name = \"report-\" + report_date + \".pdf\"\n pdf = canvas.Canvas(report_name, pagesize=letter)\n pdf.setFont(\"Courier\", 50)\n pdf.setStrokeColorRGB(1, 0, 0)\n pdf.setFillColorRGB(1, 0, 0)\n pdf....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
yield successive palindromes starting at n
def palindromes(n: int) -> int: # 1 -> 2 -> 3 ... 9 -> 11 -> 22 -> 33 -> 44 .. 99 -> 101 # 101 -> 111 -> 121 -> 131 -> ... -> 191 -> 202 -> 212 # 989 -> 999 -> 1001 -> 1111 -> 1221 # 9889 -> 9999 -> 10001 -> 10101 -> 10201 prev = n s = str(n) even = len(s) % 2 == 0 s = s[:ceil(len(s) / 2...
[ "def palindromes():\n for n in count(1):\n if str(n) == str(n)[::-1]:\n yield n", "def find_prev_palindromic_prime(n):\n\n # if n < 11, no palindromes, pick a prime in the list\n if (n <= 101):\n for i in [101, 11, 7, 5, 3, 2]:\n if i < n:\n return i\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return lowest prime palindrome >= N
def primePalindrome(self, N: int) -> int: for p in palindromes(N): if isPrime(p): return p
[ "def find_prev_palindromic_prime(n):\n\n # if n < 11, no palindromes, pick a prime in the list\n if (n <= 101):\n for i in [101, 11, 7, 5, 3, 2]:\n if i < n:\n return i\n\n n_str = str(n)\n n_len = (len(n_str) // 2 ) + 1\n\n start = int(n_str[0:n_len])\n end = 0\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All JSON files should comply with the respective schemas
def test_json(): schemas = { 'schema-languages': 'bible/languages.json', 'schema-book-metadata': 'bible/book-metadata.json', 'schema-bible': 'bible/bible-*.json' } for schema_name, data_path_glob in schemas.items(): schema_path = 'schemas/{}.json'.format(schema_name) ...
[ "def load_schemas():\n schemas = {}\n for filename in os.listdir(get_abs_path('schemas')):\n path = get_abs_path('schemas') + '/' + filename\n file_raw = filename.replace('.json', '')\n with open(path) as file:\n schemas[file_raw] = Schema.from_dict(json.load(file))\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All source file imports should be properly ordered/formatted.
def test_import_order(): file_paths = glob.iglob('*/*.py') for file_path in file_paths: with open(file_path, 'r') as file_obj: file_contents = file_obj.read() new_file_contents = isort.code(file_contents) fail_msg = '{} imports are not compliant'.format( file_path...
[ "def format_imports():\n astrodynamics_dir = Path('astrodynamics')\n constants_dir = astrodynamics_dir / 'constants'\n for initfile in astrodynamics_dir.glob('**/__init__.py'):\n if constants_dir in initfile.parents:\n continue\n SortImports(str(initfile),\n mult...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Language IDs in languages.json should have a corresponding data file
def test_language_id_correspondence(): with open('bible/languages.json', 'r') as languages_file: languages = json.load(languages_file) for language in languages: case.assertTrue( os.path.exists(os.path.join( 'bible', 'bible-{}.json'.format(language['id']))), ...
[ "def load_all_languages():\n current_directory = os.path.dirname(os.path.realpath(__file__))\n language_directory = 'language'\n language_directory_path = os.path.join(current_directory, language_directory)\n\n for filename in os.listdir(language_directory_path):\n if filename.endswith(\".json\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split a string on separator, ignoring ones escaped by backslashes.
def split_escaped(string, separator): result = [] current = '' escaped = False for char in string: if not escaped: if char == '\\': escaped = True continue elif char == separator: result.append(current) curr...
[ "def split_by_separator(self, string, separator):\n return string.split(separator)", "def safe_split(string, sep=','):\n regex = re.escape(sep) + r'\\s*(?![^\\[\\]]*\\])(?![^()]*\\))'\n return re.split(regex, string)", "def split_escaped_delim (delimiter, string, count=0):\n assert len(delimiter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether NetworkManager is available on the system.
def is_available(cls): try: proc = subprocess.Popen( ['systemctl', 'status', 'NetworkManager'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) proc.communicate() return proc.returncode == 0 except OSError...
[ "def nm_available() -> bool:\n if bool('gi.repository.NM' in modules):\n try:\n get_client()\n return True\n except Exception:\n ...\n return False", "def is_network_device(self):\n return self._is_network_device", "def is_available (self):\r\n\r\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The number of the current page (1 indexed)
def current_page(self): if self.limit > 0 and self.offset > 0: return int(ceil(self.offset / float(self.limit))) + 1 return 1
[ "def get_current_page_num(self):\n return self.current_page", "def get_num_of_pages(self):", "def current_page(self):\n if self.no_items:\n return 0\n else:\n _, last_num = self.displayed_items\n return math.ceil(last_num / self.current_per_page)", "def cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if a next page exists.
def has_next(self): return self.current_page < self.pages
[ "def has_next(self):\n return self.page < self.total_pages", "def has_next(self):\n return self.page < self.pages", "def has_next(self):\n return self.current_page < self.total_pages", "def list_has_next_page(self, soup):\n\n # Check for the 'next page' element at the bottom of the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if a previous page exists.
def has_previous(self): return self.current_page > 1
[ "def has_previous(self) -> bool:\n return self.page > 1", "def has_previous(self):\n return self.page > 1", "def has_prev(self):\n return self.page > 1", "def previous_page(self):\n\n\t\tif not self.is_paginated:\n\t\t\traise PaginationError(\"The response is not paginated.\")\n\n\t\tif s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the next url for the current endpoint.
def next_url(self): if self.has_next: kwargs = g.request_args.copy() kwargs.update(request.view_args.copy()) kwargs['offset'] = self.offset + self.limit kwargs['limit'] = self.limit return url_for(request.endpoint, **kwargs)
[ "def next_url(self):\n step = self.remaining_steps(skip_current=True).next()\n return self.url_for(step.name)", "def next_url(self):\n\n return self.make_link(self.page + 1, 'next')", "def get_next_url(self, request):\n if \"next\" in request.GET:\n return request.GET.get(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the marker is a wall marker.
def is_wall_marker(self): return self.id in WALL
[ "def is_wall(self, x, y):\r\n\r\n return self.get_bool(x, y, 'wall')", "def __isTileWall(self, point):\n return self.__getElementFromPairs(point) == \"-\"", "def isWall(self, position):\n util.raiseNotDefined()", "def isWall(mapObj, x, y):\r\n if x < 0 or x >= len(mapObj) or y < 0 or y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the marker is a token marker.
def is_token_marker(self): return self.id in TOKEN
[ "def is_token(self): # tag matches token tag\n return self.tag == tagset.token.tag", "def _has_token( self ):\n t = self.tokens.get_token()\n return False if t==self.tokens.eof else self.tokens.push_token( t ) or True", "def ismarker(typename, tree):\n if type(tree) is not With or len(t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the coordinates of the vertices of a regular polygon with radius r and n sides centered at coordinate c.
def RegularPolygonPoints(n,c): coord = [] for i in range(n): x = m.cos(2*m.pi*i/n)+c[0] y = m.sin(2*m.pi*i/n)+c[1] coord.append([x,y]) return(coord)
[ "def regular_polygon(cls, center, radius, n_vertices, start_angle=0, **kwargs):\n angles = (np.arange(n_vertices) * 2 * np.pi / n_vertices) + start_angle\n return cls(center + radius * np.array([np.cos(angles), np.sin(angles)]).T, **kwargs)", "def get_vertices(self, rad, col):\n ivc = self.in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves the point a distance of s from the current position to a random vertex of the regular polygon and then does it again. k amounts of steps pos initial position, all the points the marker has been.
def MovePoint(pos,points,s=0.5, k = 1000): x = [pos[0]] y = [pos[1]] rdm.seed(1) # comment out if you want randomness for i in range(k): n = len(points) r = int(rdm.random()*n) x.append(x[i] + (points[r][0] - x[i]) * s) y.append(y[i] + (points[r][1] -...
[ "def move_to_random_pos(self):\n newpos = [(np.random.rand() - 0.5) * 0.1,\n (np.random.rand() - 0.5) * 0.1,\n np.random.rand() * 0.9 + 0.2]\n self.move_to(newpos)", "def move_nsew(self): # Make the particle move in cardinal directions \n if random.random() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get most recent memento for url.
def _get_closest_memento_url(url, when=None, timegate_uri=None): if isinstance(memento_client, ImportError): raise memento_client if not when: when = datetime.datetime.now() mc = memento_client.MementoClient() if timegate_uri: mc.timegate_uri = timegate_uri retry_count = 0...
[ "def get_recent(self):\t\t\n\t\tif self.is_caching():\n\t\t\tTweetScraper._is_updated.wait()\n\t\t\treturn TweetScraper._tweet_data[-1]", "def popUrl(self):\n url = None\n#self.lock.acquire()\n try:\n url = self.__unvistedUrls.get(timeout=2) #2s\n except:\n url = None\n#...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor. redirectChain is a list of redirects which were resolved by resolveRedirect(). This is needed to detect redirect loops.
def __init__(self, url, redirectChain=[], serverEncoding=None, HTTPignore=[]): self.url = url self.serverEncoding = serverEncoding fake_ua_config = config.fake_user_agent_default.get( 'weblinkchecker', False) if fake_ua_config and isinstance(fake_ua_config, ...
[ "def redirects(self):\n return self.data.setdefault('redirects', {})", "def _follow_redirect(self, uri, method, body, headers, response,\n content, max_redirects):\n (scheme, authority, absolute_uri,\n defrag_uri) = httplib2.urlnorm(httplib2.iri2uri(uri))\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get encodung used by server.
def getEncodingUsedByServer(self): if not self.serverEncoding: try: pywikibot.output( u'Contacting server %s to find out its default encoding...' % self.host) conn = self.getConnection() conn.request('HEAD', '/',...
[ "def get_encoded(self):\n return self.key", "def server_side_encryption(self) -> str:\n return pulumi.get(self, \"server_side_encryption\")", "def get_as_string(self, use_cache_if_available=True):\n obj_bytes = self.get_bytes(use_cache_if_available=use_cache_if_available)\n return ob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read encoding from response.
def readEncodingFromResponse(self, response): if not self.serverEncoding: try: ct = response.getheader('Content-Type') charsetR = re.compile('charset=(.+)') charset = charsetR.search(ct).group(1) self.serverEncoding = charset ...
[ "def get_charset(response): # 根据请求返回的响应获取数据()\n _charset = requests.utils.get_encoding_from_headers(response.headers)\n if _charset == 'ISO-8859-1':\n __charset = requests.utils.get_encodings_from_content(response.text)\n if __charset:\n _charset = __charset[0]\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the redirect target URL as a string, if it is a HTTP redirect. If useHEAD is true, uses the HTTP HEAD method, which saves bandwidth by not downloading the body. Otherwise, the HTTP GET method is used.
def resolveRedirect(self, useHEAD=False): conn = self.getConnection() try: if useHEAD: conn.request('HEAD', '%s%s' % (self.path, self.query), None, self.header) else: conn.request('GET', '%s%s' % (self.path, self.query)...
[ "def redirect_url(self) -> Optional[str]:\n for k, v in self.headers:\n if k.lower() == 'location':\n return v\n return self.url", "def target_url(self):\n if urlparse(self.target).scheme:\n return self.target\n elif \"http\" in self.components_prop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the fact that the link was found dead to the .dat file.
def setLinkDead(self, url, error, page, weblink_dead_days): #test output #pywikibot.output('setLinkDead: SEM acquire [%s][%s][%s]' % (url,page.title(),error)) self.semaphore.acquire() #test output #pywikibot.output('[%s] setLinkDead: SEM acc DONE [%s][%s][%s]' % (datetime.datetim...
[ "def __del__(self):\n if self.linkinfo:\n try:\n linkinfo_file = open(self._linkinfo_file(), \"w\")\n self.linkinfo.write(linkinfo_file)\n finally:\n linkinfo_file.close()", "def test_open_unlinked(self):\n fname = join(self.dfuse.di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Record that the link is now alive. If link was previously found dead, remove it from the .dat file.
def setLinkAlive(self, url): if url in self.historyDict: #test output #pywikibot.output('[%s] setLinkAlive: SEM acquire [%s]' % (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),url)) self.semaphore.acquire() try: del self.historyDict[url] ...
[ "def __del__(self):\n if self.linkinfo:\n try:\n linkinfo_file = open(self._linkinfo_file(), \"w\")\n self.linkinfo.write(linkinfo_file)\n finally:\n linkinfo_file.close()", "def setLinkDead(self, url, error, page, weblink_dead_days):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generator for pages in History.
def RepeatPageGenerator(): history = History(None) pageTitles = set() for value in history.historyDict.values(): for entry in value: pageTitles.add(entry[0]) for pageTitle in sorted(pageTitles): page = pywikibot.Page(pywikibot.Site(), pageTitle) yield page
[ "def list_pages(self):\n raise NotImplementedError()", "def _render_history(self, req, page):\n if not page.exists:\n raise TracError(_(\"Page %(name)s does not exist\", name=page.name))\n\n data = self._page_data(req, page, 'history')\n\n history = []\n for version, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that User has attr email, and it's an empty string
def test_email_attr(self): user = User() self.assertTrue(hasattr(user, "email")) self.assertEqual(user.email, "")
[ "def test_email_is_not_blank(self):\n email_field = User._meta.get_field(\"email\")\n self.assertFalse(email_field.blank)", "def test_email_is_not_null(self):\n email_field = User._meta.get_field(\"email\")\n self.assertFalse(email_field.null)", "def test_blank_username(self):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that User has attr password, and it's an empty string
def test_password_attr(self): user = User() self.assertTrue(hasattr(user, "password")) self.assertEqual(user.password, "")
[ "def test_password_none(self):\n self.assertEqual(self.user.password, None)", "def test_password(self):\n u = User()\n self.assertTrue(hasattr(u, \"password\"))\n self.assertEqual(u.password, \"\")", "def test_login_emptypassword(self):\n emptypassword = self.new_user.user_log...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that User has attr first_name, and it's an empty string
def test_first_name_attr(self): user = User() self.assertTrue(hasattr(user, "first_name")) self.assertEqual(user.first_name, "")
[ "def test_first_name(self):\n user = User()\n self.assertTrue(hasattr(user, \"first_name\"))\n self.assertEqual(user.first_name, \"\")", "def test_first_name(self):\n u = User()\n self.assertTrue(hasattr(u, \"first_name\"))\n self.assertEqual(u.first_name, \"\")", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that User has attr last_name, and it's an empty string
def test_last_name_attr(self): user = User() self.assertTrue(hasattr(user, "last_name")) self.assertEqual(user.last_name, "")
[ "def test_last_name(self):\n u = User()\n self.assertTrue(hasattr(u, \"last_name\"))\n self.assertEqual(u.last_name, \"\")", "def test_last_name_is_optional(self):\n self.updated_data['last_name'] = ''\n self.update_user()\n self.assertEqual(self.user.last_name, self.upda...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function goes through each item in a list of items sorted by decreasing weight, and places it in the box with the most remaining space left.
def RoomyStrategy(I_list,box_list): SortedItems = quick_sort(I_list) lemon = [] iso = 0 for element in range(0, len(SortedItems)): w = SortedItems[element].weight x = FindMaxCap(box_list) if w <= x.max_cap - x.curr_cap: x.curr_cap += w x.items_list.append(...
[ "def tightest(file):\n boxes, items = read_files(file)\n items = sort_Items(items)\n for ele in items:\n index = find_least(boxes, ele.weight)\n if index < 0:\n pass\n else:\n boxes[index].items.append(ele)\n boxes[index].capacity_left = boxes[index].ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function goes through each item in a list of items sorted by decreasing weight, and places it in the box with the least remaining space left that will fit the item.
def TightStrategy(I_list,box_list): iso = 0 lemon = [] SortedItems = quick_sort(I_list) for element in range(0, len(SortedItems)): w = SortedItems[element].weight x = FindTightFit(box_list, w) if x == None: iso+=1 pass else: if w <= x.m...
[ "def tightest(file):\n boxes, items = read_files(file)\n items = sort_Items(items)\n for ele in items:\n index = find_least(boxes, ele.weight)\n if index < 0:\n pass\n else:\n boxes[index].items.append(ele)\n boxes[index].capacity_left = boxes[index].ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a helper function for RoomyStrategy(), it finds the box in box_list that has the most space left.
def FindMaxCap(box_list): rem = 0 for i in range(0,len(box_list)): curr = box_list[i].max_cap - box_list[i].curr_cap if curr >= rem: rem = curr box = box_list[i] elif curr < rem: pass return box
[ "def findLowestAvailableBox(gameBoard):\n\tlowest_in_col = defaultdict(int)\n\tfor box in gameBoard.box:\n\t\tif box.points == 0: #only care about boxes that are still available to split\n\t\t\trow = math.floor(box.y/2)\n\t\t\tcol = math.floor(box.x/2)\n\t\t\tif row > lowest_in_col[col]:\n\t\t\t\tlowest_in_col[col]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a helper function for TightStrategy(), it finds the box in box_list that has the least space left, while still having enough space for the chosen item.
def FindTightFit(box_list,w): mini = w x = None for i in range(0,len(box_list)): curr = box_list[i].max_cap - box_list[i].curr_cap if curr >= w: x = box_list[i] rem = curr - w if curr > mini: mini = rem x = box_list[i] r...
[ "def TightStrategy(I_list,box_list):\n iso = 0\n lemon = []\n SortedItems = quick_sort(I_list)\n for element in range(0, len(SortedItems)):\n w = SortedItems[element].weight\n x = FindTightFit(box_list, w)\n if x == None:\n iso+=1\n pass\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the open of this DayResult.
def open(self) -> float: return self._open
[ "def open_date(self):\n return self._open_date", "def get_closed(self):\n return self.filter(status=\"CLOSED\")", "def getOpen(date, symbol):\n return getInfo(date, symbol)[\"1. open\"]", "def is_open(self):\n return self.door.is_open()", "def IsOpen(self):\n return self._is_ope...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the open of this DayResult.
def open(self, open: float): if open is None: raise ValueError("Invalid value for `open`, must not be `None`") # noqa: E501 self._open = open
[ "def open_date(self, open_date):\n\n self._open_date = open_date", "def opened(self, opened):\n\n self._opened = opened", "def open_value(self, open_value):\n\n self._open_value = open_value", "def active_date_open(self, active_date_open):\n\n self._active_date_open = active_date_o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the high of this DayResult.
def high(self) -> float: return self._high
[ "def highvalue(self):\r\n return resource.HighValue(self)", "def last_high(self):\n return self.data.last('1D').high.iat[0]", "def high(self, json, units):\n high = str(json['forecast']['simpleforecast']['forecastday'][0]['high'][units])\n return high", "def Get_ZHighEventOccured_V...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the high of this DayResult.
def high(self, high: float): if high is None: raise ValueError("Invalid value for `high`, must not be `None`") # noqa: E501 self._high = high
[ "def high(self, high):\n\n self._high = high", "def high_value(self, high_value):\n\n self._high_value = high_value", "def price_high(self, price_high):\n\n self._price_high = price_high", "def changeHigh(self):\n self.changeLowHigh(self.ui.t_high, t_type=\"high\")", "def set_hig...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the low of this DayResult.
def low(self) -> float: return self._low
[ "def low(self, json, units):\n low = str(json['forecast']['simpleforecast']['forecastday'][0]['low'][units])\n return low", "def get_lowht(self):\n return self._lowht", "def last_low(self):\n return self.data.last('1D').low.iat[0]", "def min(self):\n return self._min", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the low of this DayResult.
def low(self, low: float): if low is None: raise ValueError("Invalid value for `low`, must not be `None`") # noqa: E501 self._low = low
[ "def low(self, low):\n\n self._low = low", "def set_low(self, line):\n self.output(line, LOW)", "def changeLow(self):\n self.changeLowHigh(self.ui.t_low, t_type=\"low\")", "def low(self) -> float:\n return self._low", "def set_low(self):\n if self._mode == self.INPUT:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the close of this DayResult.
def close(self, close: float): if close is None: raise ValueError("Invalid value for `close`, must not be `None`") # noqa: E501 self._close = close
[ "def closed(self, closed):\n\n self._closed = closed", "def actual_close_date(self, actual_close_date):\n\n self._actual_close_date = actual_close_date", "def active_date_close(self, active_date_close):\n\n self._active_date_close = active_date_close", "def is_close(self, is_close):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the adj_close of this DayResult.
def adj_close(self) -> float: return self._adj_close
[ "def DIFF(self):\r\n adj_close = self.df_OHLC['close']\r\n DIFF = self._EMA(12, 12, adj_close) - self._EMA(26, 26, adj_close)\r\n return DIFF", "def adj_close(self, adj_close: float):\n if adj_close is None:\n raise ValueError(\"Invalid value for `adj_close`, must not be `No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the adj_close of this DayResult.
def adj_close(self, adj_close: float): if adj_close is None: raise ValueError("Invalid value for `adj_close`, must not be `None`") # noqa: E501 self._adj_close = adj_close
[ "def adj_close(self) -> float:\n return self._adj_close", "def actual_close_date(self, actual_close_date):\n\n self._actual_close_date = actual_close_date", "def active_date_close(self, active_date_close):\n\n self._active_date_close = active_date_close", "def setAdjInner(self, inner):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the volume of this DayResult.
def volume(self) -> float: return self._volume
[ "def volume(self):\n return self.filled_count * self.element_volume", "def get_volume(self):\n return self.truck_volume", "def volume(self):\n return self._radius ** 3 * math.pi * 4 / 3", "def volume(self):\n return sum(i.volume for i in self.items)", "def volume(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the sma of this DayResult.
def sma(self) -> float: return self._sma
[ "def get_salario(self):\n return self.__salario", "def mae(self):\n return self._metric_json['mae']", "def mse(self):\n return self._metric_json['MSE']", "def getMasses(self):\n try:\n return self._massList\n except AttributeError:\n self._massList = [f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the sma of this DayResult.
def sma(self, sma: float): self._sma = sma
[ "def sma(self) -> float:\n return self._sma", "def reset_stamina(self):\n self.stamina = 10", "def set_salario(self, salario):\n self.__salario = salario", "def setMasses(self, masses):\n self.clearNumberDensities()\n for nucName, mass in masses.items():\n self.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the ema of this DayResult.
def ema(self) -> float: return self._ema
[ "def ema(args):\n assert len(args[0])\n\n # from utils.symbols import get_symbol\n # from indicators.price import get_current_price_humanized\n\n try:\n # symbol = get_symbol(args[0])\n pass\n\n except ChatBotException as e:\n # logger.debug(e.developer_message)\n return e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the ema of this DayResult.
def ema(self, ema: float): self._ema = ema
[ "def ema(self) -> float:\n return self._ema", "def ema(args):\n assert len(args[0])\n\n # from utils.symbols import get_symbol\n # from indicators.price import get_current_price_humanized\n\n try:\n # symbol = get_symbol(args[0])\n pass\n\n except ChatBotException as e:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the bb_top of this DayResult.
def bb_top(self) -> float: return self._bb_top
[ "def top_bid(self):\n return self._top_bid", "def bb_top(self, bb_top: float):\n\n self._bb_top = bb_top", "def get_top_cell(self):\n return self._top_cell", "def top(self):", "def getPageTop(self):\n return self.pageTop", "def top(self) -> int:\n return self.topEle", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the bb_top of this DayResult.
def bb_top(self, bb_top: float): self._bb_top = bb_top
[ "def top(self, top):\n\n self._top = top", "def bevel_top(self, bevel_top):\n self._bevel_top = bevel_top", "def set_top(self, top: float) -> None:\n self._selected_top = top", "def bb_top(self) -> float:\n return self._bb_top", "def top_bid(self, top_bid):\n\n self._top_b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the bb_bottom of this DayResult.
def bb_bottom(self) -> float: return self._bb_bottom
[ "def bottom(self):\n return self.height - 1", "def bottom( self , i , j ):\n return self._get_bottom( i , j )", "def bb_bottom(self, bb_bottom: float):\n\n self._bb_bottom = bb_bottom", "def bottom(self):\n return int(round(self._box[3]))", "def getExceedingBoxBottom(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the bb_bottom of this DayResult.
def bb_bottom(self, bb_bottom: float): self._bb_bottom = bb_bottom
[ "def bottom(self, bottom):\n\n self._bottom = bottom", "def bb_bottom(self) -> float:\n return self._bb_bottom", "def bevel_bottom(self, bevel_bottom):\n self._bevel_bottom = bevel_bottom", "def right_bottom(self, right_bottom):\n\n self._right_bottom = right_bottom", "def set_bo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the percent_b of this DayResult.
def percent_b(self) -> float: return self._percent_b
[ "def get_percent_b(data):\n if data is None:\n raise EmptyDataError('[!] Invalid data value')\n\n result = TA.PERCENT_B(data)\n if result is None:\n raise IndicatorException\n return result", "def percent_b(self, percent_b: float):\n\n self._percent_b = per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the percent_b of this DayResult.
def percent_b(self, percent_b: float): self._percent_b = percent_b
[ "def percent_b(self) -> float:\n return self._percent_b", "def bid_percentage(self, bid_percentage):\n\n self._bid_percentage = bid_percentage", "def get_percent_b(data):\n if data is None:\n raise EmptyDataError('[!] Invalid data value')\n\n result = TA.PERCENT_B(data)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the rsi of this DayResult.
def rsi(self) -> float: return self._rsi
[ "def rsi(date):\n\n # print(float(r_json['Technical Analysis: RSI'][date]['RSI']))\n return float(r_json['Technical Analysis: RSI'][date]['RSI'])", "def _get_rsi(self):\r\n print(\"On veut acceder à l'attribut '_rsi'\")\r\n return self._rsi #C'est qu'on retourne l'att\r", "def rsi(self, n, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the rsi of this DayResult.
def rsi(self, rsi: float): self._rsi = rsi
[ "def rsi(self) -> float:\n return self._rsi", "def rsi(date):\n\n # print(float(r_json['Technical Analysis: RSI'][date]['RSI']))\n return float(r_json['Technical Analysis: RSI'][date]['RSI'])", "def set_rdate(self, rdate):\n self.__rdate = rdate", "def _set_rsi(self,n_rsi):\r\n prin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the cci of this DayResult.
def cci(self) -> float: return self._cci
[ "def cidade(self):\n return self._cidade", "def get_cid(self):\n results = self.database.findall(text(\"select cid from cid_minter\"))\n if results:\n return results[0]\n else:\n err_msg = \"Database error: No CID was found in the cid_minter table.\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the cci of this DayResult.
def cci(self, cci: float): self._cci = cci
[ "def iccid(self, iccid):\n\n self._iccid = iccid", "def cmyk_coordinate_cyanic(self, cmyk_coordinate_cyanic):\n\n self._cmyk_coordinate_cyanic = cmyk_coordinate_cyanic", "def cci(self) -> float:\n return self._cci", "def set_Ci(self, new_Ci, update=False):\n self.Ci = (update==Fals...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the trade of this DayResult.
def trade(self) -> float: return self._trade
[ "def getTrade(self, trade_id):\n getTradeResponse = self._api.trade.get(self._account_id, trade_id)\n return getTradeResponse", "def get_trade(self, id: int) -> TradeOffer | None:\n return self._connection.get_trade(id)", "def get():\n\n query_dict = {}\n coin = Model.get(quer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the trade of this DayResult.
def trade(self, trade: float): if trade is None: raise ValueError("Invalid value for `trade`, must not be `None`") # noqa: E501 self._trade = trade
[ "def trade_id(self, trade_id):\n\n self._trade_id = trade_id", "def trade_type(self, trade_type):\n\n self._trade_type = trade_type", "def trade_time(self, trade_time):\n self._trade_time = trade_time", "def trade_state(self, trade_state):\n\n self._trade_state = trade_state", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the holding of this DayResult.
def holding(self) -> float: return self._holding
[ "def get_current_stock_holding(self):\n return self.current_stock_holding", "def celery_result(self):\n return self._celery_result", "def keepday(self):\n return self._keepday", "def get(self):\n \n if self._state == self.State.transfering_no_waiters:\n d = defer....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the cash of this DayResult.
def cash(self, cash: float): if cash is None: raise ValueError("Invalid value for `cash`, must not be `None`") # noqa: E501 self._cash = cash
[ "def cash(self, cash):\n\n self._cash = cash", "def cash_amount(self, cash_amount):\n self._cash_amount = cash_amount", "def cash_discount(self, cash_discount):\n\n self._cash_discount = cash_discount", "def set_cash_balance(self):\n self.set_values(\n start_phrase='Cash...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compose functions where g returns multiple arguments, which are then expanded to fit arguments of f
def compose_expanded_args(f,g): def composed(*args): return f(*(g(*args))) return composed
[ "def compose(f, g):\n def h(x):\n return f(g(x))\n return h", "def compose1(f, g):\n return lambda x: f(g(x))", "def composition(f, g):\n return lambda x: g(f(x))", "def chain(f, g):\n return lambda *a: g(f(*a))", "def compose1(h, g):\n def f(x):\n return h(g(x))\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
decorator for factory f's __call__ that after __call__, saves object at specified path
def save_at_specified_path_dec(f, full_path): def decorated_f(*args, **kwargs): x = f(*args, **kwargs) f.print_handler_f(x, full_path) return x return decorated_f
[ "def store(obj, path: str) -> None:\n dirname = os.path.dirname(os.path.abspath(path))\n if dirname != \"\":\n os.makedirs(dirname, exist_ok=True)\n Backend({}, {}).dump(obj, path)", "def savecache(func):\n def inner(self, obj, idx = None, *args, **kwargs):\n # call the n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
decorator that returns val if an exception is raised by function call
def None_if_exception(f, val): def decorated_f(*args, **kwargs): try: x = f(*args, **kwargs) except Exception: return None else: return x return decorated_f
[ "def _raise_ex(fn):\n def _decorated(*args, **kwargs):\n v = fn(*args, **kwargs)\n if isinstance(v, Exception): raise v\n return v\n return _decorated", "def lazy_value_or_error(value):\n try:\n return value() if callable(value) else value\n except Exception:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds other tutors who teach similar subjects to "example" as measured by their jaccard similarity.
def subject_similarity(example, df, possible_subjects): ex_subj = example[possible_subjects][example[possible_subjects]==1].index.values sim_tuts = df[possible_subjects].apply(\ lambda x: jaccard_similarity( \ x[x[possible_subjects]==1].index...
[ "def subject_similarity(example, df, possible_subjects):\n # Get subjects that example tutor tutors.\n ex_subj = example[possible_subjects][example[possible_subjects]==1].index.values\n\n sim_tuts = df[possible_subjects].apply(\\\n lambda x: jaccard_similarity( \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find tutors that overlap with the example tutor. Overlap is True if the tutoring radius (in miles) encompasses the center of the zip code of the example tutor.
def location_overlap(example, df): def haversin(lat1, lon1, lat2, lon2): """ Finds haversin distance (distance along great circle) in miles between two points. Points are defined by latitude and longitude. Radius of the Earth is assumed to be the midpoint between radius at the equator and radius at...
[ "def location_overlap(example, df):\n\n def haversin(lat1, lon1, lat2, lon2):\n \"\"\"\n Finds haversin distance (distance along great circle) in miles between two points. Points are defined by latitude and longitude. Radius of the Earth is assumed to be halfway between radius at the equator and ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the maximal timeUUID for the timestamp immediately preceding the timestamp of the timeUUID ``u``
def uuid_for_prev_dt(u): t60 = time60_from_uuid(u) return max_uuid_from_time60(t60 - 1)
[ "def uuid_for_next_dt(u):\n t60 = time60_from_uuid(u)\n return min_uuid_from_time60(t60 + 1)", "def time(self, u):\n return self._ll_tree.get_time(u)", "def min_utc_time():\n return datetime.min.replace(tzinfo=timezone.utc)", "def max_utc_time():\n return datetime.max.replace(tzinfo=timezon...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the minimal timeUUID for the timestamp immediately following the timestamp of the timeUUID ``u``
def uuid_for_next_dt(u): t60 = time60_from_uuid(u) return min_uuid_from_time60(t60 + 1)
[ "def uuid_for_prev_dt(u):\n t60 = time60_from_uuid(u)\n return max_uuid_from_time60(t60 - 1)", "def min_utc_time():\n return datetime.min.replace(tzinfo=timezone.utc)", "def timeasc(self, u=NULL):\n nodes = self.preorder(u)\n is_virtual_root = u == self.virtual_root\n time = self.t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produces a list of ipvanish servers based on a list of tuples mapping base link urls with the maximum number of servers at that base link
def build_ipvanish_server_list(base_links): server_list = [] pattern = '\d{2}' for base_link in base_links: for i in range(1, base_link[1]): repl = str(i) if i > 9 else '0' + str(i) server_list.append(re.sub(pattern=pattern, repl=repl, string=base_link[0])) return server_...
[ "def _get_servers(self):\n for _ in range(3):\n try:\n with velarium.network.download('https://www.ipvanish.com/api/servers.geojson') as servers_mem_file:\n data = servers_mem_file.getvalue()\n\n servers = [IPVanishServer(**server) for server in jso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
plant the plant to run the simulation and evaluation on orderList the list of orders in the given schedule simulator Simulator instance to run a schedule evaluator Evaluator instance to evaluate a schedule
def __init__(self, plant, orderList, simulator, evaluator): assert plant != None assert orderList != None self.plant = plant self.orderList = orderList self.simulator = simulator self.evaluator = evaluator # used for benchmarking self.simulatorTime = 0 # enable/disable console output self.p...
[ "def simulation_run_v4(num_demand_nodes,num_nurses,time_horizon, locations, fixed_service_time=True, shifts=False, restrictions=False):\n\n # generate demand nodes, customers, and nurses\n node = True\n node_type = input('Input \"actual\" for nodes to be actual locations, \"random\" for nodes to be randoml...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }