query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Transfer model weights to target model with a factor of Tau | def transfer_weights(self):
W, target_W = self.model.get_weights(), self.target_model.get_weights()
for i in range(len(W)):
target_W[i] = self.tau * W[i] + (1 - self.tau)* target_W[i]
self.target_model.set_weights(target_W) | [
"def update_target_model(self):\n self.target_model.set_weights(self.model.get_weights())",
"def update_target(self):\n # raise NotImplementedError\n self.target.set_weights([(1 - self.tau) * self.target_params[i] + self.tau * self.model_params[i] for i in range(len(self.target_params))])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Output the company CIK listed (applicable only for stocks issues in the SEC, so no exchange name is required) | def get_company_cik(stock_ticker: str):
company_cik = sec_finance_functions.get_company_data_by_ticker(stock_ticker).company_cik
return company_cik | [
"def getCIKs(TICKERS):\n URL = 'http://www.sec.gov/cgi-bin/browse-edgar?CIK={}&Find=Search&owner=exclude&action=getcompany'\n CIK_RE = re.compile(r'.*CIK=(\\d{10}).*')\n cik_dict = {}\n for ticker in TICKERS:\n f = requests.get(URL.format(ticker[0]), stream = True)\n results = CIK_RE.finda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the number of fillings of a stock for the given year (or all fillings since the company listing) | def get_last_filling(stock_ticker: str,
filling_year: Optional[int] = None):
company_cik = sec_finance_functions.get_company_data_by_ticker(stock_ticker).company_cik
all_company_fillings = sec_finance_functions.get_all_company_filings_by_cik(company_cik)
all_company_fillings_by_year = s... | [
"def get_year_count(self):\r\n ward_group = self.current_table.groupby(['Year'])\r\n self.year_count = ward_group['Year'].unique().count()\r\n return self.year_count",
"def yearCount(self, year):\n count = 0\n for k, v in self.popData.items():\n if (v[\"birth\"] <= ye... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call to inform that the any concurrent ripping process is finished. | def rip_finished(self):
if self.is_ripping:
self.is_ripping.clear() | [
"def syncDone (self) :\r\n self.ongoing_sync_count -= 1",
"def _notify_end(self):\n to_scan = len(self._files_to_scan)\n event.notify(ScanProgressEvent(to_scan, to_scan, True))",
"def __mark_finished_procs(self):\n for i in range(self.__incoming):\n if not self.__processes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over DISC, splitting it into packets starting at TRACK_NUMBER index 1. This call will ensure that no packets cross a track or pregap boundary, and will also obey any edits to the disc. It will not, however, read any samples from disc, just tell the calling code what to read. | def iterate(cls, disc, track_number):
assert track_number >= 0 and track_number < len(disc.tracks)
track = disc.tracks[track_number]
packet_frame_size = (
disc.audio_format.rate / cls.PACKETS_PER_SECOND)
# Mock up a packet that ends at the start of index 1, so the
... | [
"def _read_packets(self, reader: Par2FileReader):\n start_count = len(self)\n pointers = reader.get_pointers()\n # Create RecoverySets if needed\n for set_id, pointer_set in packets.by_set_id(pointers).items():\n print(set_id.hex(), pointer_set)\n if set_id not in s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes base paths to specs and resources. | def set_paths(self, specs, resources):
self.install = 'install.xml'
self.specs_path = path_format(specs)
self.root = path_format(dirname(dirname(self.specs_path)) + '/')
self.res_path = path_format(resources)
self.resources['BASE'] = self.res_path
self.specs['BASE'] = sel... | [
"def setup_paths(self):\n # TODO: separate out paths based on android, json patch, server_gen.\n app_base_path = os.path.join(self.base_dir, self.app_name)\n build_dir = os.path.join(app_base_path, \"build\")\n api_spec_dir = os.path.join(app_base_path, \"api_specs\")\n api_spec_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts paths to available izpack resources and spec files from the installer's install.xml spec. | def parse_paths(self):
self.soup = BeautifulSoup(open(self.get_path('install')))
for spec in list(self.specs.keys()):
spec_file = self.find_specs_path(spec)
if spec_file:
# If spec file exists
self.specs[spec] = path_format(spec_file)
e... | [
"def _discover(self):\n self.update({entry.name: entry.load() for entry in pkg_resources.iter_entry_points(self.entry_point)})",
"def set_paths(self, specs, resources):\n self.install = 'install.xml'\n self.specs_path = path_format(specs)\n self.root = path_format(dirname(dirname(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the path for the spec in the install.xml file. | def find_specs_path(self, spec):
element = self.soup.find(spec)
if element:
child = element.find('xi:include')
if child: # if xi:include exists, specs are external.
path = self.properties.substitute(child['href'])
else:
# Internal spec... | [
"def parse_paths(self):\n self.soup = BeautifulSoup(open(self.get_path('install')))\n for spec in list(self.specs.keys()):\n spec_file = self.find_specs_path(spec)\n if spec_file:\n # If spec file exists\n self.specs[spec] = path_format(spec_file)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the install.xml (or resources.xml) soup to find all available resources. | def parse_resources(self, soup):
for res in soup.find_all('res'):
if 'customlangpack' in res['id'].lower():
self.find_langpack_path(res)
else:
rid = remove_xml(res['id'])
self.resources[rid] = path_format(self.properties.substitute(res['src... | [
"def crawl_pypi():\n updates = feedparser.parse(\"https://pypi.org/rss/updates.xml\")\n packages = feedparser.parse(\"https://pypi.org/rss/packages.xml\")\n return set(package[\"link\"] for package in updates[\"items\"] + packages[\"items\"])",
"def parse_paths(self):\n self.soup = BeautifulSoup(o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds a langpack path from the given xml langpack element | def find_langpack_path(self, langpack):
lid = langpack['id']
src = path_format(self.properties.substitute(langpack['src']))
if '.xml_' in lid:
self.langpacks[lid[-3:]] = src
if not 'default' in self.langpacks:
self.langpacks['default'] = src
self.reso... | [
"def get_language_element(cls, element_path: str, lang: str\n ) -> etree.Element:\n return cls._get_lang_or_eng(element_path, lang)",
"def findPath(root, path):\n assert('|' not in path), 'Update XML search to use XPATH syntax!'\n # edit tags for allowable characters\n path =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the path to the langpack with the given localization id. | def get_langpack_path(self, lid='default'):
path = self.langpacks[lid]
return force_absolute(self.res_path, path) | [
"def find_langpack_path(self, langpack):\n lid = langpack['id']\n src = path_format(self.properties.substitute(langpack['src']))\n if '.xml_' in lid:\n self.langpacks[lid[-3:]] = src\n\n if not 'default' in self.langpacks:\n self.langpacks['default'] = src\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the .xml from a resource or spec id. | def remove_xml(rid):
if '.xml' in rid[-4:]:
return rid[:-4]
else:
return rid | [
"def delete_manifest(self):\n os.remove('../raw_data/' + self.uuid + '/' + self.uuid + '.xml')",
"def remove_task_xml_file_on_delete(sender, instance, **kwargs):\n # We have to use save=False as otherwise validation would fail ;)\n if len(instance.task_xml.name):\n instance.task_xml.delete(sav... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensures that the base path is not appended to an absolute path. | def force_absolute(base, path):
if os.path.abspath(path) and os.path.exists(path):
return path
else:
return path_format(base + path) | [
"def check_abolute_path(self, path):\n if(path.startswith('/')):\n raise StandardError('Absolute path names are not supported by now! Check: %s' %path)",
"def _is_bad_path(path, base):\r\n return not resolved(joinpath(base, path)).startswith(base)",
"def _NewPathCheck(path):\n _PathCheck... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append a child SHETNode object to this parent. | def append_child(self, child):
self._children.append(child) | [
"def appendChild(self, child):\n self.__initChild()\n self.__child.append(child)",
"def appendChild(self, child):\r\n self.children.append(child)\r\n child.parent = self",
"def add_child(self, child):\r\n self.children.append(child)",
"def add_child(self, child):\n as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the child object for this row. | def child(self, row):
return self._children[row] | [
"def child(self, row):\r\n return self._childItems[row]",
"def child(self, row):\n return self._children[row]",
"def fm_get_child(self, idx):\n return self._relation_lst[self.CHILD][idx]",
"def parent_row(self):\n dict_cur.execute('SELECT * FROM \"{}\" WHERE {} = {}'.format(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of children for this object. | def child_count(self):
return len(self._children) | [
"def child_count(self):\n return len(self.children)",
"def get_num_children(self):\n return len(self.children)",
"def get_childcount(self):\n return len(self._childrenlist)",
"def getNumChildren(self):\n return _libsbml.XMLNode_getNumChildren(self)",
"def children_count(self):\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the row number of this object in its parents child object list. | def row(self):
if self._parent != None:
return self._parent._children.index(self)
else:
return 0 | [
"def GetIndexInParent(self) -> int:\n return self.parent.value.index(self)",
"def get_parent_index(self):\n return self.pindex",
"def get_parent_index(self):\n return (self.index - 1) // 2",
"def rowCount(self, parent):\n if parent.column() > 0:\n return 0\n paren... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a count of games for each team between a range of dates. The range of dates is inclusive. The result is a dictionary, where the key is a team ID and the values is the number of games played within the date range. | def games_count(self, start_date, end_date): # noqa
if start_date > end_date:
raise RuntimeError("End date must be beyond start")
cur_date = start_date
tot_gc = defaultdict(int)
while cur_date <= end_date:
teams_playing = self._teams_playing_one_day(cur_date)
... | [
"def counts_per_teams(cls, date_scope):\n return cls._counts_per(\"player_team\", date_scope)",
"def collect_after_game_dicts(league, start_date, end_date):\n after_game_no_dicts = collections.defaultdict(dict)\n\n def add_team_stats(team, after_game_no, stat):\n stat_dict = after_game_no_dict... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the full list of all players in the NHL. Each player is returned with their teamID and playerID. | def players(self):
if self.players_cache is None:
team_df = self.teams()
self.players_cache = self.ea.players_endpoint(
team_df["id"].tolist())
columns = ["teamId", "playerId", "name", "position"]
all_players = []
for team in self.players_cache["t... | [
"async def players(self) -> list:\n\n return await self._client.GetLeaderboardPlayers(\n self.title,\n self.platform,\n gameType=self.gameType,\n gameMode=self.gameMode,\n timeFrame=self.timeFrame,\n page=self.page,\n )",
"def players... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dict of all exporters available in this module. | def exporters():
return dict(_exporters) | [
"def registered_exporters():\n return _GLOBAL_REGISTERED_EXPORTERS.keys",
"def get_exporters():\n return Exporter.__subclasses__()",
"def importers():\n return dict(_importers)",
"def exports(self):\n out = {} # type: dict\n out.update(self.__exports__)\n return out",
"def Regi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dict of all expression writers available in this module. | def ewriters():
return dict(_ewriters) | [
"def build_writers(self):\n # Here the default print/log frequency of each writer is used.\n return [\n # It may not always print what you want to see, since it prints \"common\" metrics only.\n CommonMetricPrinter(self.max_iter),\n JSONWriter(os.path.join(self.cfg.OUT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generates all prime numbers smaller than _n_ using the Sieve of Eratosthenes | def primes(n):
sieve = [True]*n
for p in range(2, n):
if sieve[p]:
yield p
for i in range(p*p, n, p):
sieve[i] = False | [
"def primes(n):\n\tsieve = [True] * n\n\tyield 2\n\tfor i in xrange(3,int(n**0.5)+1,2):\n\t\tif sieve[i]:\n\t\t\tyield i\n\t\t\tsieve[i*i::2*i] = [False]*((n-i*i-1)/(2*i)+1)\n\tfor i in xrange(i+2,n,2):\n\t\tif sieve[i]: yield i",
"def SieveOfEratosthenes(n):\n #Initialise array of Prime True values.\n prim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the given sequence is a Fibonacci sequence. Fibonacci sequence is assumed to have length > 2. | def check_fibonacci(data: Sequence[int]) -> bool:
if len(data) < 3:
return False
if data[0] != 0 or data[1] != 1:
return False
for n in range(2, len(data)):
if data[n] != data[n - 1] + data[n - 2]:
return False
return True | [
"def check_fibonacci(data: Sequence) -> bool:\n\n # get number of sequence elements\n numb_of_elements = len(data)\n\n # if the number of elements in data Sequence less then\n # two the condition F[n] = F[n-1] + F[n-2] can not be\n # satisfied, so that means that the considered sequence\n # is not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the first n bits of fractional part of float f | def frac_bin(f, n=32):
f -= math.floor(f) # get only the fractional part
f *= 2**n # shift left
f = int(f) # truncate the rest of the fractional content
return f | [
"def cntfrac2float(fractions):\r\n f = 0\r\n n = len(fractions)-1\r\n while n > 0:\r\n f = 1.0 / (fractions[n] + f)\r\n print f\r\n n -= 1\r\n return f + fractions[0]",
"def fpart(x):\n return x - np.floor(x)",
"def bits_estimation(n, f=0.01, N_b=7.3E21):\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preprocesses the given bitext by removing empty lines, sentence pairs in incorrect languages, sentences above a the specified length threshold, and sentence pair exceeding the specified length ratio. | def preprocess_bitext(src_path, tgt_path, src_lang, tgt_lang, max_len, max_len_ratio):
# Generate output paths
src_out_path = '.'.join(src_path.split('.')[:-1]) + '.clean.{:s}'.format(src_lang)
tgt_out_path = '.'.join(tgt_path.split('.')[:-1]) + '.clean.{:s}'.format(tgt_lang)
# Open aligned corpora
... | [
"def preprocess(text):\n text = remove_space(text)\n text = clean_special_punctuations(text)\n text = handle_emojis(text)\n text = clean_number(text)\n text = spacing_punctuation(text)\n text = clean_repeat_words(text)\n text = remove_space(text)\n #text = stop(text)# if changing this, then ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a small set of random templates for testing | def tst_random_set():
final_wave, final_spec, final_z = desi_qso_templates(
outfil='test_random_set.fits', N_perz=100, seed=12345) | [
"def generate_random_tomogram_set(templates, criteria, number_of_tomograms, dim, seed=None, noise=False):\n if (seed == None):\n seed = random.randint(0, 2 ** 31 - 1)\n print('Using random seed: ', seed)\n random.seed(int(seed))\n np.random.seed(int(seed))\n\n for i in range(number_of_tomogram... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints a message that the restaurant is open. | def open_restaurant(self):
print(f"The restaurant is open.") | [
"def open_restaurant(self):\n print(\"\\tThe restaurant is open now.\")",
"def open_restaurant(self):\n msg = f\"{self.name} is open. Come on in!\"\n print(f\"\\n{msg}\")",
"def open_restaurant(self):\n\t\topen = f\"{self.restaurant_name} is now open.\"\n\t\tprint(f\"\\n{open}\")",
"def o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove duplicates in a 2D list. | def remove_dupl_2d(arr):
arr_len = len(arr)
idx = 0
unique = set()
while idx < arr_len:
if tuple(arr[idx]) in unique:
del arr[idx]
arr_len -= 1
continue
unique.add(tuple(arr[idx]))
idx += 1
return arr | [
"def unique_elements_from_2D_list(list_2d):\n return list(set(flatten_2D_list(list_2d)))",
"def deduplicate_list(lst):\n return list(set(lst))",
"def remove_duplicates(lista):\n return list(set(lista))",
"def removeDuplicates(list):\n\treturn set((item for item in list))",
"def deduplicate_list(inp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialise verboseprint() if verbose to a specific nvfunc or print, else to no printing. | def init_verbose_print(verbose=True, vfunc=print, nvfunc=None):
global verboseprint
if verbose:
verboseprint = vfunc
else:
if not nvfunc:
verboseprint = lambda *a, **k: None
else:
verboseprint = nvfunc
return verboseprint | [
"def verbose_print(verbose, print_function=None):\n\n if verbose:\n return print_function or print\n else:\n def vprint(*args, **kwars):\n pass\n return vprint",
"def set_verboseprint(func=misc.init_verbose_print(verbose=True, vfunc=print, nvfunc=misc.log)):\n global verbo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of all abundant numbers less than an upper limit | def getAbundantNumbers(upperLimit):
result = []
for i in range(1, upperLimit):
if d(i) > i:
result.append(i)
return result | [
"def getListOfAbundantNumbers():\n\tabundantNumbersList = []\n\tfor num in range(1, LIMIT + 1):\n\t\tif isNumberAbundant(num):\n\t\t\tabundantNumbersList.append(num)\n\n\treturn abundantNumbersList",
"def compute(upper_bound: int = 10000) -> int:\n\n def d(n: int) -> int:\n return sum(eulerlib.factors(n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true iff the number n can be written as the sum of two abundant numbers. | def canBeWritten(n):
for a in abundantNumbersList:
if a >= n: break
if (n - a) in abundantNumbersSet:
return True
return False | [
"def is_abundant(n):\r\n if sum_proper_divisors(n) > n:\r\n return True\r\n else:\r\n return False",
"def isAbundant(n):\n\treturn sumProperDivisors(n, PRIMES) > n",
"def is_abundant(number):\n return find_divisor_sum(number) > number",
"def is_abundant(num: int) -> bool:\n return su... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For making a new request for ride. | def ride():
from services import taxi_service
customer_id = request.form['customer_id']
res = taxi_service.ride(customer_id)
return json_response(res) | [
"def createrideRequest():\n name = request.args.get('name', 0, type=str)\n cellphone = request.args.get('cellphone', 0, type=str)\n studentID = request.args.get('studentID', 0, type=str)\n pickupTime = request.args.get('pickupTime', 0, type=str)\n pickupLoc = request.args.get('pickupLoc', 0, type=str)\n dropo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the function 'save_screenshot' | def test_save_screenshot():
surface_flow_file = Path(TEST_RESULTS_FILES_PATH, "surface_flow.vtu")
screenshot_file = save_screenshot(surface_flow_file, "Mach")
assert screenshot_file.exists()
if screenshot_file.exists():
screenshot_file.unlink() | [
"def test_screenshot_create(self):\n pass",
"def test_screenshot_show(self):\n pass",
"def test_screenshot_update(self):\n pass",
"def isave_screenshot():\n save_screenshot(conv_s())",
"def capture_screenshot(self):\n filename = os.environ.get('LOG_DIR', '../../logs') + \"/scr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the date as a string only shows month/day [bias] as days want to add on today(could be minus) defaut is zero stands for today | def get_date_str(bias=0):
today = datetime.datetime.today() # ็ฒๅพไปๅคฉ็ๆฅๆ
date = (today + datetime.timedelta(days=bias)).strftime("%m/%d") # ๆ ผๅผๅๆฅๆ
return ' ' + date[1:] if date[0] == '0' else date # ๆ0ๆๆ็ฉบ็ฝ | [
"def today_date():\n today = datetime.date.today()\n date_str = '%d-%d-%d'%(today.year, today.month, today.day)\n return date_str",
"def todaystr():\n today = datetime.datetime.today()\n return f\"{today.year}{today.month:02}{today.day:02}\"",
"def get_date(date):\n return date.strftime(\"%B %... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the demand along each edge for a particular routing and flow | def calc_demand(self, routing: np.ndarray, demand: float,
commodity_idx: int) -> np.ndarray:
commodity = self.commodities[commodity_idx]
node_flow = np.zeros(self.num_nodes)
node_flow[commodity[0]] = demand
split_matrix = np.zeros((self.num_nodes, self.num_nodes), dt... | [
"def calc_per_flow_link_utilisation(self, flow: Tuple[int, int],\n demand: float,\n routing: np.ndarray) -> np.ndarray:\n edge_mapping = {edge: i for i, edge in\n enumerate(sorted(self.graph.edges))}\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the link utilisation over a graph for a particular flow and its demand. (NB utilisation in bandwidth, not relative to capacity) | def calc_per_flow_link_utilisation(self, flow: Tuple[int, int],
demand: float,
routing: np.ndarray) -> np.ndarray:
edge_mapping = {edge: i for i, edge in
enumerate(sorted(self.graph.edges))}
link_utili... | [
"def calc_overall_link_utilisation(self, demands: Demand,\n routing: Routing) -> np.ndarray:\n flows = [(i, j) for i in range(self.num_nodes)\n for j in range(self.num_nodes)\n if i != j]\n\n link_utilisation = np.zeros(self.num_edge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the overall utilisation of each link in a network given a routing choice and a set of demands. (NB utilisation in bandwidth, not relative to capacity) | def calc_overall_link_utilisation(self, demands: Demand,
routing: Routing) -> np.ndarray:
flows = [(i, j) for i in range(self.num_nodes)
for j in range(self.num_nodes)
if i != j]
link_utilisation = np.zeros(self.num_edges)
... | [
"def calc_per_flow_link_utilisation(self, flow: Tuple[int, int],\n demand: float,\n routing: np.ndarray) -> np.ndarray:\n edge_mapping = {edge: i for i, edge in\n enumerate(sorted(self.graph.edges))}\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a time interval, number of steps, adjacency matrix, payment matrix (or matrices), relationship matrix and initial state of all vertices to return the result of the hyperrational evolutionary game played on the given graph in that time interval | def hr_game(t0, tf, n, A, B, R, x0):
# t0 - Initial time
# tf - Final time
# n - Number of steps
# A - Adjacency matrix, np.ndarray (N,N)
# B - A 2D or 3D matrix with all payoff matrices, np.ndarray (S,S,N)
# R - Relationship or preference matrix, np.ndarray (N,N)
# x0 - Initial state of o... | [
"def timestep(self, dt):\r\n N=self.size\r\n\t\r\n\tinteraction = np.zeros(N, dtype = 'float')\r\n\t\r\n\ts=self.synaptic_position()\r\n\tv=self.v_position()\r\n\t\r\n\t#print np.eye(N)*v\r\n\tV=np.eye(N)*self.V_rev-np.eye(N)*v\r\n\tinteraction=self.I+np.dot(V,np.dot(self.G,s))\r\n \r\n '''\r\n\tint... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor for the RestoreObjectState class | def __init__(self,
error=None,
object_status=None,
resource_pool_id=None,
restored_object_id=None,
source_object_id=None,
):
# Initialize members of the class
self.error = error
self.object_status =... | [
"def __init__(self):\n self.__dict__ = self.__state",
"def restore(self, state: T):",
"def prepare_restore(self, *args, **kwargs):\n pass",
"def mos_object(self):\n return self._restore_fn(*self._restore_args)",
"def __init__(self, init_state):\n self._curr_state = init_state",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test login with 2SA. | def test_login_2sa(self):
dsm_7 = SynologyDSMMock(
VALID_HOST,
VALID_PORT,
VALID_USER_2SA,
VALID_PASSWORD,
VALID_HTTPS,
VALID_VERIFY_SSL,
)
dsm_7.dsm_version = 7
with pytest.raises(SynologyDSMLogin2SARequiredExceptio... | [
"def test_v1login(self):\n pass",
"def test_login_2sa_new_session(self):\n dsm_7 = SynologyDSMMock(\n VALID_HOST,\n VALID_PORT,\n VALID_USER_2SA,\n VALID_PASSWORD,\n VALID_HTTPS,\n VALID_VERIFY_SSL,\n device_token=DEVICE_TO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test login with 2SA and a new session with granted device. | def test_login_2sa_new_session(self):
dsm_7 = SynologyDSMMock(
VALID_HOST,
VALID_PORT,
VALID_USER_2SA,
VALID_PASSWORD,
VALID_HTTPS,
VALID_VERIFY_SSL,
device_token=DEVICE_TOKEN,
)
dsm_7.dsm_version = 7
ass... | [
"def test_login_2sa(self):\n dsm_7 = SynologyDSMMock(\n VALID_HOST,\n VALID_PORT,\n VALID_USER_2SA,\n VALID_PASSWORD,\n VALID_HTTPS,\n VALID_VERIFY_SSL,\n )\n dsm_7.dsm_version = 7\n with pytest.raises(SynologyDSMLogin2SAR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the serial message have a valid CRC. | def crcCheck(serialMessage):
checkResult = False
#CRC from serial message
crc = int.from_bytes(serialMessage[14:16], byteorder='little', signed=False)
#calculated CRC
crcCalc = libscrc.modbus(serialMessage[0:14])
if crc == crcCalc:
checkResult = True
return checkResult | [
"def _crc_valid(self):\n calc_crc = CRCfromString(' '.join(self.raw.split(' ')[1:-3])).upper()\n if calc_crc[2:4].upper() == self.crc[0].upper() and \\\n calc_crc[4:6].upper() == self.crc[1].upper():\n return True\n else:\n return False",
"def checkCRC(self, ms... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests that square inherits from Base | def test_SquareinheritancefromBase(self):
Square.reset_objects()
self.assertEqual(issubclass(Square, Base), True) | [
"def test_10_01_subclass(self):\n\n self.assertTrue(issubclass(Square, Rectangle))\n self.assertTrue(issubclass(Square, Base))",
"def test_SquareinheritancefromRectangle(self):\n Square.reset_objects()\n self.assertEqual(issubclass(Square, Rectangle), True)",
"def testSquareIsChild(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests that square inherits from Base | def test_SquareinheritancefromRectangle(self):
Square.reset_objects()
self.assertEqual(issubclass(Square, Rectangle), True) | [
"def test_SquareinheritancefromBase(self):\n Square.reset_objects()\n self.assertEqual(issubclass(Square, Base), True)",
"def test_10_01_subclass(self):\n\n self.assertTrue(issubclass(Square, Rectangle))\n self.assertTrue(issubclass(Square, Base))",
"def testSquareIsChild(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests that ValueError is thrown for 0 size value | def test_0size(self):
Square.reset_objects()
with self.assertRaises(ValueError) as e:
s1 = Square(0)
self.assertEqual(str(e.exception), "width must be > 0") | [
"def test_raises_on_empty(self):\n self.assertRaises(ValueError, rootIO.reweight, np.array([]))",
"def test_fails_on_nonempty_list(self):\r\n with assertions.assert_raises(AssertionError):\r\n assertions.assert_empty([0])",
"def test_length_check_zero(self):\n digraph = nx.DiGrap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad x value with string | def test_badxvaluewithstring(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, "foo", 2, 3)
self.assertEqual(str(e.exception), 'x must be an integer') | [
"def test_check_x_ValueError(self):\n self.assertRaisesRegex(\n ValueError,\n 'x must be >= 0',\n Rectangle,\n 4, 2, -1, 0, 12\n )",
"def test_square_ValueError_x(self):\n with self.assertRaisesRegex(ValueError, \"x must be >= 0\"):\n Squ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad x value with tuple | def test_badxvaluewithtuple(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, (1, 2), 2, 3)
self.assertEqual(str(e.exception), 'x must be an integer') | [
"def test_tuples_to_avoid(self):\n self.assertFalse(\n any(key in self.resultDict and self.resultDict[key] == tuplesToAvoid[key] for key in tuplesToAvoid))",
"def test_tuple_response_fail() -> None:\n fail_conditions = (_view_function_invalid_status,\n _view_function_tup... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad x value with list | def test_badxvaluewithlist(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, [1, 2], 2, 3)
self.assertEqual(str(e.exception), 'x must be an integer') | [
"def is_error(cls, x):\n\n try:\n x = cls.get_list_val(x)\n\n except AssertionError:\n return False\n\n return (cls.has(x) and x != cls.OK)",
"def test_validate_positive_integer_list():\n with pytest.raises(ValueError):\n validate_positive_integer_list(0.5, 1)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad size value with bools | def test_badsizevaluebool(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(True, 1, 2, 3)
self.assertEqual(str(e.exception), 'width must be an integer') | [
"def _check_size(size):\r\n\r\n if not isinstance(size, (list, tuple)):\r\n raise ValueError(\"Size must be a tuple\")\r\n if len(size) != 2:\r\n raise ValueError(\"Size must be a tuple of length 2\")\r\n if size[0] < 0 or size[1] < 0:\r\n raise ValueError(\"Width and height must be >=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad y value with bools | def test_badyvaluewithbools(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, 2, True, 3)
self.assertEqual(str(e.exception), 'y must be an integer') | [
"def has_y(self):\n return any(map(lambda s: s.is_y, self))",
"def test_false_positives(self):\n pred_y, val_y = y_data()\n\n test_fp = 1\n\n fp = crossval.false_positives(pred_y, val_y)\n\n self.assertEqual(fp, test_fp)",
"def false_neg(yt, yp) -> Any:\n from keras import ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad size value with floats | def test_badsizevaluefloats(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(float(1), 1, 2, 3)
self.assertEqual(str(e.exception), 'width must be an integer') | [
"def check_for_float(check):",
"def is_float(self, size=None):\n return False",
"def is_float_broken():\n # we do this instead of float('nan') because windows throws a wobbler.\n nan = 1e300000/1e300000\n\n return str(nan) != str(struct.unpack(\"!d\", '\\xff\\xf8\\x00\\x00\\x00\\x00\\x00\\x00')[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad x value with sets | def test_badxvaluewithsets(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, {1, 2, 3}, 2, 3)
self.assertEqual(str(e.exception), 'x must be an integer') | [
"def test_mismatching_indset(self, iterset, x):\n with pytest.raises(MapValueError):\n op2.par_loop(op2.Kernel(\"\", \"dummy\"), iterset,\n x(op2.WRITE, op2.Map(iterset, op2.Set(nelems), 1)))",
"def test_mismatching_iterset(self, iterset, indset, x):\n with pytest.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad x value with dicts | def test_badxvaluewithdicts(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, {"foo": 1}, 2, 3)
self.assertEqual(str(e.exception), 'x must be an integer') | [
"def test_badyvaluewithdicts(self):\n Rectangle.reset_objects()\n with self.assertRaises(TypeError) as e:\n r1 = Square(1, 2, {\"foo\": 1}, 3)\n self.assertEqual(str(e.exception), 'y must be an integer')",
"def check_for_dict(check):",
"def test_dict_error(self):\r\n \r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad y value with dicts | def test_badyvaluewithdicts(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, 2, {"foo": 1}, 3)
self.assertEqual(str(e.exception), 'y must be an integer') | [
"def _validate_y(self, y, sample_weight=None):",
"def test_check_y_not_int_not_float(wage_X_y, wage_gam):\n X, y = wage_X_y\n y_str = ['hi'] * len(y)\n\n with pytest.raises(ValueError):\n check_y(y_str, wage_gam.link, wage_gam.distribution)",
"def _validate_dict_data(self, expected, actual):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests for bad x value with funcs | def test_badxvaluewithfuncs(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, print(), 2, 3)
self.assertEqual(str(e.exception), 'x must be an integer') | [
"def is_error(f, x):\n try:\n f(x)\n return False\n except:\n return True",
"def test_square_ValueError_x(self):\n with self.assertRaisesRegex(ValueError, \"x must be >= 0\"):\n Square(3, -2)\n Square(5, 0)",
"def test_check_x_ValueError(self):\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests the size getter | def test_sizegetter(self):
Rectangle.reset_objects()
r1 = Square(1, 2, 2, 3)
self.assertEqual(r1.size, 1) | [
"def check_get_size(self, data, expected_return_value):\r\n return_value = get_size(data)\r\n self.assertEqual(return_value, expected_return_value)",
"def testGetSize(self):\n asserts.assertEqual(self.MEM_SIZE, self._mem_obj.getSize())",
"def size(self):",
"def Size(self) -> int:",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests the size setter | def test_sizesetter(self):
Rectangle.reset_objects()
r1 = Square(1, 2, 2, 3)
self.assertEqual(r1.size, 1)
r1.size = 100
self.assertEqual(r1.size, 100) | [
"def test_size_setter(self):\n s1 = Square(3, 1, 2, 45)\n s1.size = 27\n self.assertEqual(s1.size, 27)",
"def test_sizegetter(self):\n Rectangle.reset_objects()\n r1 = Square(1, 2, 2, 3)\n self.assertEqual(r1.size, 1)",
"def test_sizesetterwithfunc(self):\n Recta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests the size setter with string | def test_sizesetterwithstring(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, 2, 2, 3)
self.assertEqual(r1.size, 1)
r1.size = "foo"
self.assertEqual(str(e.exception), "width must be an integer") | [
"def test_size_setter(self):\n s1 = Square(3, 1, 2, 45)\n s1.size = 27\n self.assertEqual(s1.size, 27)",
"def test_sizesetter(self):\n Rectangle.reset_objects()\n r1 = Square(1, 2, 2, 3)\n self.assertEqual(r1.size, 1)\n r1.size = 100\n self.assertEqual(r1.si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests the size setter with func | def test_sizesetterwithfunc(self):
Rectangle.reset_objects()
with self.assertRaises(TypeError) as e:
r1 = Square(1, 2, 2, 3)
self.assertEqual(r1.size, 1)
r1.size = print()
self.assertEqual(str(e.exception), "width must be an integer") | [
"def test_size_setter(self):\n s1 = Square(3, 1, 2, 45)\n s1.size = 27\n self.assertEqual(s1.size, 27)",
"def test_sizesetter(self):\n Rectangle.reset_objects()\n r1 = Square(1, 2, 2, 3)\n self.assertEqual(r1.size, 1)\n r1.size = 100\n self.assertEqual(r1.si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests the to_dictionary function | def test_to_dict(self):
Square.reset_objects()
s1 = Square(10, 2, 1)
s1_dictionary = s1.to_dictionary()
self.assertEqual(s1_dictionary, {'id': 1, 'x': 2, 'size': 10, 'y': 1}) | [
"def test_toDictIsDict(self):\n r1 = Rectangle(10, 7, 2, 8)\n dictionary = r1.to_dictionary()\n self.assertTrue((type(dictionary) is dict))",
"def test_dict_to_dict(self):\n @converters.wrap\n def inner_test(param: dict):\n \"\"\"Make sure the parameter was converted ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests the update function with to_dict | def test_updatewithdict(self):
s1 = Square(10, 2, 1)
s1_dictionary = s1.to_dictionary()
s2 = Square(1, 1)
s2.update(**s1_dictionary)
self.assertEqual(s2.size, 10)
self.assertEqual(s2.x, 2)
self.assertEqual(s2.y, 1) | [
"def test_update(self):\n x = adict(y=1, z=2)\n x.update({ 'a': 0, 'b': -1 })\n self.assertEqual([k for k in x.keys()], ['a', 'b', 'y', 'z'])\n self.assertEqual([v for v in x.values()], [0, -1, 1, 2])",
"def test_update(inp):\n atty = AttyDict(a={'aa': 1, 'ab': 2})\n regular = di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function tests the display function | def test_display__method(self):
Rectangle.reset_objects()
s1 = Square(5)
f = io.StringIO()
with contextlib.redirect_stdout(f):
s1.display()
self.assertEqual(f.getvalue(), "#####\n#####\n#####\n#####\n#####\n") | [
"def test_ad_display1(self):\n r1 = Rectangle(2, 3, 2, 1)\n f = StringIO()\n with contextlib.redirect_stdout(f):\n r1.display()\n self.assertEqual(f.getvalue(), \"\\n ##\\n ##\\n ##\\n\")",
"def test_ad_display2(self):\n r1 = Rectangle(5, 3, 2, 2)\n f = Stri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Repeat a dataframe n times. | def repeat(df, n):
return pd.concat([df] * n, ignore_index=True) | [
"def Repeat(dataset, count=None):\n return dataset.repeat(count=count)",
"def repeat(arg, n, axis=1):\n if not checks.is_array(arg):\n arg = np.asarray(arg)\n if axis == 0:\n if checks.is_pandas(arg):\n return array_wrapper.ArrayWrapper.from_obj(arg).wrap(\n np.rep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test type inference works properly for a parquet file with unconventional types types. | def test_infer_parquet_types(tmpdir):
# Create a temporary directory to store the parquet file
tmpdir = str(tmpdir)
# Create a dataframe with all the types
df = pd.DataFrame(
{
"int": [1, 2, 3],
"float": [1.1, 2.2, 3.3],
"string": ["a", "b", "c"],
... | [
"def test_converted_type_null():\n p = fastparquet.ParquetFile(os.path.join(TEST_DATA,\n \"test-converted-type-null.parquet\"))\n data = p.to_pandas()\n expected = pd.DataFrame([{\"foo\": \"bar\"}, {\"foo\": None}])\n for col in data:\n if isinstance(data[c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows all the installations from the database | def show_installations(self):
database = Database('data/database.db')
installations = database.read_installations()
view = Template(filename="view/template.html", lookup=lookup)
return view.render(
rows = [[item.number, item.name, item.address, item.zip_code, item.... | [
"def all_installation(self):\n\t\tself.db = DB()\n\t\tinstallation_all = self.db.select_all_from(\"installations\")\n\t\ttmpl = lookup.get_template(\"installation.html\")\n\t\treturn (tmpl.render(installation=installation_all))",
"def installation(request):\n return render(request, 'ecosystem/installation.html... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows all the equipments from the database | def show_equipments(self):
database = Database('data/database.db')
equipments = database.read_equipments()
view = Template(filename="view/template.html", lookup=lookup)
return view.render(
rows = [[item.number, item.name, item.installation_number] for item ... | [
"def all_equipment(self):\n\t\tself.db = DB()\n\t\tactivity_all = self.db.select_all_from(\"equipment\")\n\t\ttmpl = lookup.get_template(\"equipment.html\")\n\t\treturn (tmpl.render(equipment=activity_all))",
"def show_equipment(self, number):\n database = Database('data/database.db')\n equip = data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows all the activities from the database | def show_activities(self):
database = Database('data/database.db')
activities = database.read_activities()
view = Template(filename="view/template.html", lookup=lookup)
return view.render(
rows = [[item.number, item.name] for item in activities],
... | [
"def all_activity(self):\n\t\tself.db = DB()\n\t\tactivity_all = self.db.select_all_from(\"activity\")\n\t\ttmpl = lookup.get_template(\"activity.html\")\n\t\treturn (tmpl.render(activity=activity_all))",
"def __ui_list_all_activities(self):\n activities_list = self.__activity_service.service_get_list_of_a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows the installation which has the given number from the database | def show_installation(self, number):
database = Database('data/database.db')
inst = database.read_installation(number)
view = Template(filename="view/template.html", lookup=lookup)
try:
render = view.render(
rows = [[inst.number, inst.name, inst.address, ... | [
"def show_installations(self):\n database = Database('data/database.db')\n installations = database.read_installations()\n view = Template(filename=\"view/template.html\", lookup=lookup)\n \n \n return view.render(\n rows = [[item.number, item.name, item.address, item.z... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows the equipment which has the given number from the database | def show_equipment(self, number):
database = Database('data/database.db')
equip = database.read_equipment(number)
view = Template(filename="view/template.html", lookup=lookup)
try:
render = view.render(
rows = [[equip.number, equip.name, equip.installation_nu... | [
"def show_equipments(self): \n database = Database('data/database.db')\n equipments = database.read_equipments()\n view = Template(filename=\"view/template.html\", lookup=lookup)\n \n \n return view.render(\n rows = [[item.number, item.name, item.installation_num... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows the activity which has the given number from the database | def show_activity(self, number):
database = Database('data/database.db')
activ = database.read_activity(number)
view = Template(filename="view/template.html", lookup=lookup)
try:
render = view.render(
rows = [[activ.number, activ.name]],
pageT... | [
"def show_activities(self): \n database = Database('data/database.db')\n activities = database.read_activities()\n view = Template(filename=\"view/template.html\", lookup=lookup)\n \n \n return view.render(\n rows = [[item.number, item.name] for item in activities]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows all the installations, equipments and activities which match the given activity and city | def find_infos(self, activity_name, city):
database = Database('data/database.db')
infos = database.get_infos(activity_name, city)
view = Template(filename="view/template.html", lookup=lookup)
try:
render = view.render(
rows = [[item[0].number, i... | [
"def select_place_of_activity_in_city(self, DB, activity, city):\n c = DB.con.cursor()\n tab=[]\n lcity = \"'\"+city+\"'\"\n query = \"SELECT * FROM equipment, place WHERE equipment.num_place=place.id and equipment.num_place in (SELECT id FROM place WHERE city={1}) and equipment.id in(SE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
fill line edit with curve name | def fillCurveLE(self):
sel = mn.ls( sl = True, dag = True, ni = True, typ = 'nurbsCurve' )
self.curve_le.setText( sel[0].name ) | [
"def add_to_plot(self, line_name, points):\n points = [x * 100 for x in points]\n plt.plot(points, label=line_name)",
"def updateCurve(self):\n \n pass",
"def setCurve(self, index, curve) -> None:\n ...",
"def add_curve(self):\n pv_name = self._get_full_pv_name(self.pv_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove selected object from list | def removeObject(self):
for SelectedItem in self.objects_lw.selectedItems():
self.objects_lw.takeItem(self.objects_lw.row(SelectedItem) ) | [
"def remove_selected(self):\n if self._selected_index is not None:\n self._list = self._model.stringList()\n self._list.pop(self._selected_index)\n self._model.setStringList(self._list)\n self._selected_index = None",
"def _remove_from_object_list(self, objlist, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create scatter based on UI | def createScatter(self):
curv = str( self.curve_le.text() )
objCount = self.controlCount_sbx.value()
random = self.random_chb.isChecked()
useTip = self.useTips_chb.isChecked()
keepConn = self.keepConnected_chb.isChecked()
tangent = self.tangent_chb.isChecked()
groupIt = self.groupIt_chb.isChecked()
anim... | [
"def get_scatterplot(self) -> None:",
"def scatter2d(self):\n pass",
"def scatterplot(self, **kwargs) -> None:\n self.initialization_figure\n self.builder.get_scatterplot(**kwargs)",
"def scattergrid(self, scatter_data, initial_feature):\n # features\n features = self.featur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
่ทๅ็ฌฌ Num ไธช ้ฎ้ข็ญๆกๅฏน ๅนถๅจๅญๅจๆไปถไธญ ่ฟๅๆไปถ inputPath ่พๅ
ฅๆไปถ่ทฏๅพ aswPath ่พๅบๆไปถ่ทฏๅพ Num ็ฌฌๅ ไธช pk ้ข็ฎid StoreDirectory ๅญๅจ่ทฏๅพๅ | def decodeFile(inputPath:str, aswPath:str,pk:int, Num:int, StoreDirectory:str):
inputFile = StoreDirectory+str(pk)+"_"+str(Num)+"input.txt" # ๆไปถ่ทฏๅพๅ
if os._exists(inputFile): # ่ฅๅทฒๅญๅจ
pass
else:
inputLines = open(inputPath,'r').readlines() # ่ทๅๅ
ๅฎน
l = len(inputLines)
count = 1
... | [
"def read_info():\n # TODO use 123.pdf file name\n file_name = str(input('Write file name: ').strip())\n number_of_questions = int(\"\".join(\n sorted(filter(lambda x: x.isdigit(), input(\"How many question you want?: \")))))\n return number_of_questions, file_name",
"def main():\n\n # Open ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ไบง็ๆง่ก็ๅฝไปค lang ่ฏญ่จ fileN ้ๆบๆไปถๅ filePath ็จๅบๆไปถ่ทฏๅพ inputPath ่พๅ
ฅๆไปถ่ทฏๅพ outputDirectory ่พๅบๆไปถ็ฎๅฝ่ทฏๅพ ่พๅบๆไปถ outputDirectory/fileN.txt | def getCommand(lang:str, fileN:str, filePath:str, inputPath:str, outputDirectory:str):
commands = ""
Fix = suffix[lang]
if lang=="C":
commands = "gcc -o "+outputDirectory+fileN+" "+filePath+"; "+outputDirectory+fileN+" <"+inputPath+" >"+outputDirectory+fileN+".txt"
elif lang=="C++":
comm... | [
"def generateCommand(self,inputFiles,executable,clargs=None,fargs=None, preExec=None):\n found = False\n for index, inputFile in enumerate(inputFiles):\n if inputFile.getExt() in self.getInputExtension():\n found = True\n break\n if not found:\n raise IOError('None of the input file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ๅฐ็จๅบ่พๅบไธ็ญๆก่ฟ่กๆฏๅฏน outputPath ็จๅบ่พๅบๆไปถ่ทฏๅพ aswPath ็ญๆกๆไปถ่ทฏๅพ | def compare(outputPath:str, aswPath:str):
x = open(outputPath).readlines()
y = open(aswPath).readlines()
rx =[]
ry =[]
# ๅค็ๆไปถ ๅป้ค็ฉบ่ก
for line in x:
if len(line.strip())>0:
rx.append(line.strip())
# print(line.strip())
for line in y:
if len(line.strip())... | [
"def test_call_output_to_file(self):\r\n\r\n fd, tmp_result_filepath = mkstemp(\r\n prefix='CdHitOtuPickerTest.test_call_output_to_file_',\r\n suffix='.txt')\r\n close(fd)\r\n\r\n app = CdHitOtuPicker(params={'Similarity': 0.90})\r\n obs = app(self.tmp_seq_filepath1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the cluster_node_id of this StateSyncNode. | def cluster_node_id(self, cluster_node_id):
self._cluster_node_id = cluster_node_id | [
"def cluster_id(self, cluster_id):\n self._cluster_id = cluster_id",
"def hsm_cluster_id(self, hsm_cluster_id):\n self._hsm_cluster_id = hsm_cluster_id",
"def cluster_uuid(self, cluster_uuid):\n\n self._cluster_uuid = cluster_uuid",
"def cluster_num(self, cluster_num):\n\n self._cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the api_listen_ip of this StateSyncNode. | def api_listen_ip(self, api_listen_ip):
self._api_listen_ip = api_listen_ip | [
"async def async_set_slave_ip(self, slave_ip):\n self._slave_ip = slave_ip",
"def allowed_ip(self, allowed_ip):\n\n self._allowed_ip = allowed_ip",
"def api_port(self, api_port):\n\n self._api_port = api_port",
"def ip(self, ip):\n self._ip = ip",
"def setServerip(self):\n\t\tsel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Suggest a tweak based on an encoding result. For fixed QP, suggest increasing minq when bitrate is too high, otherwise suggest decreasing it. If a parameter is already at the limit, go to the next one. | def SuggestTweak(self, encoding):
if not encoding.result:
return None
parameters = self._SuggestTweakToName(encoding, 'fixed-q')
if not parameters:
parameters = self._SuggestTweakToName(encoding, 'gold-q')
if not parameters:
parameters = self._SuggestTweakToName(encoding, 'key-q')
... | [
"def get_multiplier(quality):\n\n if quality == \"low\":\n return 5\n elif quality == \"medium\":\n return 6\n elif quality == \"good\":\n return 7\n elif quality == \"high\":\n return 8\n return 6",
"def increment_quality(self, increment_unit):\n if self.quality ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the points for a given fish body | def _fish_body_points(cls, fish_num):
# y coordinate is from top of FISH_HEIGHT for a given fish, to bottom of FISH_HEIGHT for a given FISH
left_oval_side = FishTileView.SIZE_MULTIPLIER, \
(fish_num * cls.FISH_HEIGHT) + (cls.FISH_HEIGHT / FishTile.MAX_AMOUNT_FISH)
right... | [
"def find_body_part(self, body_points, segmentation_image):\n print(\"start the measuring....\")\n body_parts = {}\n shoulders = self.find_shoulders_point(body_points, segmentation_image)\n abdomen = self.find_abdomen_point(body_points)\n chest = self.find_chest_point(body_points)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts triples using Stanford CoreNLP OpenIE library via CoreNLPConnector in Java REST API | def openie(text: str) -> List[Tuple[str, str, str]]:
client = env.resolve('servers.java')
verbose.info('Extracting triples using OpenIE at: ' + client['address'], caller=openie)
return requests.get('%s/openie/triples' % client['address'], params={'text': text}).json() | [
"def call_corenlp(text, corenlp_depparse_path=None, corenlp_pos_path=None):\n properties = {'tokenize.whitespace': 'true',\n 'annotators': 'tokenize,pos,depparse',\n 'outputFormat': 'conllu',\n 'ssplit.eolonly': True}\n if corenlp_depparse_path:\n prop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
readPDF opens pdf as array to be hundled by opevCV. {{{ When the pdf file has multiple pages, automatically pick first page. | def readPDF(infile, width, grayscale=True):
#To open a pdf file.
imgAllPages = convert_from_path(infile, dpi=100)
img = imgAllPages[0] #pick first page up
img = np.asarray(img)
img = img.take([1,2,0], axis=2) #change color ch. (GBR -> RGB)
#To scale image to designated width.
if img... | [
"def read_forida_dept_health_pdf(input_pdfName, output_filename):\n\n read_pdf = PyPDF2.PdfFileReader(input_pdfName)\n \n with open(output_filename, 'a') as f:\n for i in range(read_pdf.getNumPages()):\n page = read_pdf.getPage(i)\n f.write(f'Page No - {str(1+read_pdf.getPageNumber(page))}')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
correctMisalign corrects misalignment/misscale of a image {{{ by using two markers on the image. | def correctMisalign(img, marker, center, compus, scope=100):
markerCenter = np.asarray(marker.shape)//2
guide = np.asarray([center, compus])
landmark = np.zeros(guide.shape)
#To run template matching to finder markers
result = cv2.matchTemplate(img, marker, 0)
result = (1-result/np.max(res... | [
"def misalign(out, stats):\n if len(out['precise_alignment']['onsets']) > 0:\n alignment = 'precise_alignment'\n else:\n alignment = 'broad_alignment'\n onsets = stats.get_random_onsets(out[alignment]['onsets'])\n offsets = stats.get_random_offsets(out[alignment]['onsets'],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tv_loss. Deprecated. Please use tensorflow total_variation loss implementation. | def tv_loss(x, name='tv_loss'):
raise NotImplementedError("Please use tensorflow total_variation loss.") | [
"def get_loss_fn_v2(loss_factor=1.0):\n\n def sts_loss_fn(labels, logits):\n \"\"\"STS loss\"\"\"\n logits = tf.squeeze(logits, [-1])\n per_example_loss = tf.square(logits - labels)\n loss = tf.reduce_mean(per_example_loss)\n loss *= loss_factor\n return loss\n\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs loadData from LoadDataModel. Runs also previewData from this class. Shows error warning in GUI if data load does not work. | def loadPreviewData(self):
# parameters for data load from GUI
self.loadDataModel.pathToDataSet = self.entryPath.get()
self.loadDataModel.firstRowIsTitle = bool(self.checkVarRow.get())
self.loadDataModel.firstColIsRowNbr = bool(self.checkVarCol.get())
# if entry field is empty, s... | [
"def loadPreviewDataforClassification(self):\n # parameters for data load from GUI\n self.loadDataModel.pathToDataSet = self.entryPath.get()\n self.loadDataModel.firstRowIsTitle = bool(self.checkVarRow.get())\n self.loadDataModel.firstColIsRowNbr = bool(self.checkVarCol.get())\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs loadData from LoadDataModel. Runs also previewData from this class. Shows error warning in GUI if data load does not work. | def loadPreviewDataforClassification(self):
# parameters for data load from GUI
self.loadDataModel.pathToDataSet = self.entryPath.get()
self.loadDataModel.firstRowIsTitle = bool(self.checkVarRow.get())
self.loadDataModel.firstColIsRowNbr = bool(self.checkVarCol.get())
# if entry ... | [
"def loadPreviewData(self):\n # parameters for data load from GUI\n self.loadDataModel.pathToDataSet = self.entryPath.get()\n self.loadDataModel.firstRowIsTitle = bool(self.checkVarRow.get())\n self.loadDataModel.firstColIsRowNbr = bool(self.checkVarCol.get())\n # if entry field i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set initials and try to set django user before saving | def save(self, *args, **kwargs):
self._set_first_initial()
self._set_user()
super(AbstractHuman, self).save(*args, **kwargs) | [
"def save(self, **kwargs):\n kwargs[\"user\"] = self.fields[\"user\"].get_default()\n return super().save(**kwargs)",
"def __init__(self, *args, **kwargs):\r\n super(SetUsernameForm, self).__init__(*args, **kwargs)\r\n\r\n self.initial[\"username\"] = \"\"",
"def save(self, *args, **... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get this entry first author | def _get_first_author(self):
if not len(self.get_authors()):
return ''
return self.get_authors()[0] | [
"def get_author(self):\n return self.author",
"def get_author(self):\r\n return self._author",
"def author(self):\n return self._changeset.get('author', None)",
"def author(self):\n return User(None, self.get_data(\"author\"))",
"def author_name(self):\n return self._autho... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get this entry last author | def _get_last_author(self):
if not len(self.get_authors()):
return ''
return self.get_authors()[-1] | [
"def get_author(self):\n return self.author",
"def get_author(self):\r\n return self._author",
"def _get_first_author(self):\n if not len(self.get_authors()):\n return ''\n return self.get_authors()[0]",
"def author(self):\n return self._changeset.get('author', No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get ordered authors list Note that authorentryrank_set is ordered as expected while the authors queryset is not (M2M with a through case). | def get_authors(self):
return [aer.author for aer in self.authorentryrank_set.all()] | [
"def author_list(self):\n return [a.full_name for a in self.authors.all()]",
"def get_authors(self):\n\t\treturn self.authors",
"def authors(self):\n authors = [\n n.authors for n in self.story_author_relationship.all()\n ]\n\n return authors",
"def get_authors(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method determines the highest http a server can support. This is done over http or https, depending on the parameter. HTTP2 is checked but never used to exchange messages. | def get_highest_http(uri, https, upgrade=True):
highest_http = '1.0'
response_status = ""
redirect = False
location = ""
port = 443 if https else 80
use_https = https
use_upgrade = upgrade
host, path = get_host(uri)
i_p = check_host_name(host)
request_line = "GET "+ path +" HTTP/... | [
"def get_http_protocol(self):\n if self.cfg.ssl:\n return \"https\"\n else:\n return \"http\"",
"def get_protocol():\n if https():\n protocol = 'https'\n else:\n protocol = 'http'\n return protocol",
"def supports_http_1_1():",
"def is_http2(listener)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Passes CL args to smart_client() | def main():
parser = argparse.ArgumentParser()
parser.add_argument("URI")
args = parser.parse_args()
smart_client(args.URI) | [
"def get_args(cls, client, args) :\n\t\ttry :\n\t\t\tobj = nstrace()\n\t\t\toption_ = options()\n\t\t\toption_.args = nitro_util.object_to_string_withoutquotes(args)\n\t\t\tresponse = obj.get_resources(client, option_)\n\t\t\treturn response\n\t\texcept Exception as e :\n\t\t\traise e",
"def create_client(self):"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set names using a semicolon (;) seperated string or a list of strings | def SetNames(self, names):
# parse the names (a semicolon seperated list of names)
if isinstance(names, str):
names = names.split(';')
if self.__names != names:
self.__names = names
self.Modified() | [
"def take_names(self, names):\n for name, (i, j) in names:\n self.set_name(name, i, end=j)",
"def newNames(artwork, names):\n artwork[\"NombresArtistas\"] = names",
"def names(self, names):\n\n self._names = names",
"def set_names(self, *args):\n def setnames(a, b):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the number of columns for the output ``vtkTable`` | def SetNumberOfColumns(self, ncols):
if isinstance(ncols, float):
ncols = int(ncols)
if self.__ncols != ncols:
self.__ncols = ncols
self.Modified() | [
"def setNumCols(serDisplay, cols):\n cmd = array.array('B', (124,0))\n if (cols == 20):\n cmd[1] = 3\n else:\n if (cols != 16):\n print(\"WARNING: num columns of %d not valid - must be 16 or 20. Defaulting to 16\", cols)\n cmd[1] = 6 \n writeToDisplay(serDisplay, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for networking_project_network_create | def test_networking_project_network_create(self):
pass | [
"def test_networking_project_netadp_create(self):\n pass",
"def test_networking_project_network_tag_create(self):\n pass",
"def test_create_network():\n _network = Network()",
"def test_networking_project_network_get(self):\n pass",
"def test_networking_project_network_list(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for networking_project_network_delete | def test_networking_project_network_delete(self):
pass | [
"def test_delete_network(self):\n pass",
"def test_networking_project_netadp_delete(self):\n pass",
"def test_networking_project_network_tag_delete(self):\n pass",
"def test_delete__network(self):\n arglist = [\n '--network',\n self.projects[0].id,\n ]\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for networking_project_network_event_get | def test_networking_project_network_event_get(self):
pass | [
"def test_networking_project_netadp_event_get(self):\n pass",
"def test_networking_project_network_event_list(self):\n pass",
"def test_networking_project_network_get(self):\n pass",
"def test_networking_project_network_service_get(self):\n pass",
"def test_networking_project_net... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for networking_project_network_event_list | def test_networking_project_network_event_list(self):
pass | [
"def test_networking_project_netadp_event_list(self):\n pass",
"def test_networking_project_network_event_get(self):\n pass",
"def test_networking_project_network_list(self):\n pass",
"def test_networking_project_network_service_list(self):\n pass",
"def test_networking_project_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for networking_project_network_get | def test_networking_project_network_get(self):
pass | [
"def test_networking_project_network_service_get(self):\n pass",
"def test_get_network(self):\n pass",
"def test_networking_project_network_list(self):\n pass",
"def test_networking_project_netadp_get(self):\n pass",
"def test_networking_project_network_create(self):\n pas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |