query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Return the document as a string, using the given newline sequence
def string_with_newline(self, newline: str) -> str: if self._string is None or detect_newline(self._string) != newline: return joinlines(self.lines or (), newline) return self._string
[ "def get_newline():\n\treturn newline", "def make_string(self):\n text = \"\"\n for line in self.lines:\n # using \"\\n\" line end as that's what existing files have\n #(Note from windows need to write using \"wb\" mode from to keep this)\n text = text + line + \"\\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the newline character sequence used in the document
def newline(self) -> str: return self._newline
[ "def get_newline():\n\treturn newline", "def newline(self):\r\n #TODO: we need newline detection\r\n return \"\\n\"", "def getterminator(self):\n if self.multiline:\n return \"%s.%s\" % (CRLF,CRLF)\n return CRLF", "def line(self):\n return \"\".join(self.text[self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a document object from a binary string
def from_bytes(cls, data: bytes, mtime: str = "") -> "TextDocument": srcbuf = io.BytesIO(data) encoding, lines = tokenize.detect_encoding(srcbuf.readline) if not lines: return cls(lines=[], encoding=encoding, mtime=mtime) return cls.from_str(data.decode(encoding), encoding=en...
[ "def deserialize_instance(self, string: str) -> Document:\n\n return jsonpickle.loads(string) # type: ignore", "def from_binary(cls, binary_string):\n integer_part, decimal_part = binary_string.split('.')\n return cls(len(integer_part), len(decimal_part), int(integer_part + decimal_part, 2))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a document object by reading a text file Also store the last modification time of the file.
def from_file(cls, path: Path) -> "TextDocument": mtime = datetime.utcfromtimestamp(path.stat().st_mtime).strftime(GIT_DATEFORMAT) with path.open("rb") as srcbuf: return cls.from_bytes(srcbuf.read(), mtime)
[ "def upload_file(filename: str) -> Document:\n with open(filename) as file:\n return create_document(file.read())", "def make_document(full_path, unix_timestamp, contents):\n doc = Document()\n # two separate date fields per recommendation\n # at https://lucene.apache.org/core/7_6_0/core/org/ap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a document object from a list of lines The lines should be strings without trailing newlines. They should be encoded in UTF8 unless a different encoding is specified with the ``encoding`` argument.
def from_lines( cls, lines: Iterable[str], encoding: str = DEFAULT_ENCODING, newline: str = DEFAULT_NEWLINE, mtime: str = "", ) -> "TextDocument": return cls(None, lines, encoding=encoding, newline=newline, mtime=mtime)
[ "def create_document_list(lines_of_file):\n\n document = []\n documents = []\n\n for line in lines_of_file:\n document.append(line.rstrip())\n\n # Either a newline of the last line\n if line == '\\n' or line == lines_of_file[-1]:\n documents.append(create_document(document))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Join a list of lines back, adding a linefeed after each line This is the reverse of ``str.splitlines()``.
def joinlines(lines: Iterable[str], newline: str = "\n") -> str: return "".join(f"{line}{newline}" for line in lines)
[ "def joinlines(lines: List[str]) -> str:\n return \"\".join(f\"{line}\\n\" for line in lines)", "def normalize_line_endings(lines):\r\n newline = find_newline(lines)\r\n return [line.rstrip('\\n\\r') + newline for line in lines]", "def list_str_breaks(lis):\r\n as_str = \"\"\r\n for item in lis:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the deepest common parent directory of given paths
def get_common_root(paths: Iterable[Path]) -> Path: resolved_paths = [path.resolve() for path in paths] parents = reversed(list(zip(*(get_path_ancestry(path) for path in resolved_paths)))) for first_path, *other_paths in parents: if all(path == first_path for path in other_paths): return...
[ "def get_common_parent(paths: 'List[str]') -> str:\n return os.path.commonprefix([path + '/' for path in paths]).rstrip('/')", "def find_ancestor(self, path, top_dirs):\n for top in top_dirs:\n if string.find(path, top) == 0:\n return top,path[len(top) + 1:]\n return Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return `True` if path matches any of the patterns Return `False` if there are no patterns to match.
def glob_any(path: Path, patterns: Collection[str]) -> bool: return any(path.glob(pattern) for pattern in patterns)
[ "def _matches_patterns(path, patterns):\n for glob in patterns:\n try:\n if PurePath(path).match(glob):\n return True\n except TypeError:\n pass\n return False", "def matchPatterns(path, patterns):\n name = os.path.basename(pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a row object for D2TXT. If `row` is a mapping, each keyvalue pair is copied to the new row. Keys that do not match any column name in `d2txt` are ignored. Otherwise, `row` is treated as an iterable of values to insert into each cell of the new row.
def __init__(self, d2txt: "D2TXT", row: _RowPrototype) -> None: self._d2txt = d2txt num_columns = len(d2txt.column_names()) if isinstance(row, collections.abc.Mapping): self._row = [None] * num_columns for column_name, value in row.items(): try: ...
[ "def insert_original(self, translated_row, row):\n for key in row:\n if key is None or key.strip() == \"\":\n continue\n translated_row[key] = row.get(key)\n return translated_row", "def FromRow(cls, row):\n return Entry(*row)", "def _add_row(self, w2):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a row at the given index, or a `list` of rows if slice syntax is used.
def __getitem__(self, index: Union[int, slice]) -> Union[D2TXTRow, List[D2TXTRow]]: return self._rows[index]
[ "def row(self, index):\n return self.data[index - 1]", "def get(self, index):\n return self._rows[index]", "def GetRow(a: numpy.ndarray, index: int) -> numpy.ndarray:\n return a[index, numpy.newaxis]", "def _get_row (self, index):\n rowcount = self._table.nrows\n if rowcount == 0:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a row at the given index to `value`. If slice syntax is used, replaces the rows with each item in `value`.
def __setitem__( self, index: Union[int, slice], value: Union[_RowPrototype, Iterable[_RowPrototype]], ) -> None: if isinstance(index, slice): self._rows[index] = [D2TXTRow(self, row) for row in value] else: self._rows[index] = D2TXTRow(self, value)
[ "def __setitem__(self, index, value):\n if not isinstance(index, tuple) or len(index) > 2:\n msg = \"data subscripting must be [rows,cols] or [rows,]\"\n raise ValueError(msg)\n sel_rows = self._check_index(self._nobs, index[0])\n sel_cols = (self._convert_col_index(index[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a readonly view of the list of column names.
def column_names(self) -> D2TXTColumnNameView: return D2TXTColumnNameView(self._column_names)
[ "def list_columns():\n return list(_COLUMNS.keys())", "def get_column_names(self) -> List[str]:\n return [c.name for c in self.columns]", "def get_colnames(self, model):\n return [\n field.column \n for field in model._meta.get_fields() \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the index of a column.
def column_index(self, column_name: str) -> int: return self._column_indices[column_name]
[ "def _col_index(column):\n if column:\n return column.index\n else:\n return '-'", "def getColIdx(self, col):\n try:\n return int(col)\n except:\n return ord(col)-ord('a')", "def getColIdx(self, col):\n try: \n return int(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a D2TXT object from a tabbed TXT file.
def load_txt(cls, txtfile: Union[str, PathLike, TextIO]) -> "D2TXT": try: txtfile_fd = open(txtfile, encoding="cp949") except TypeError: pass else: with txtfile_fd: return cls.load_txt(txtfile_fd) txt_reader = csv.reader( t...
[ "def d2txt_to_toml(d2txt: D2TXT) -> str:\n columns = d2txt.column_names()\n colgroups = get_matched_colgroups(columns)\n columns_with_colgroups = get_sorted_columns_and_groups(columns, colgroups)\n\n toml_rows = [make_toml_row(row, colgroups, columns_with_colgroups) for row in d2txt]\n\n # Use qtoml....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decodes an AuraFilter value into a list of flag names.
def decode_aurafilter(aurafilter: int) -> Tuple[List[str], _Hex]: af_names = [] for name, flag in AURAFILTER_FLAGS.items(): if aurafilter & flag: aurafilter &= ~flag af_names.append(name) return af_names, _Hex(aurafilter)
[ "def parse(value: str):\n return [member for member in FilterMode if member.name == value][0]", "def encode_aurafilter(flags: List[str]) -> int:\n aurafilter = 0\n for name in flags:\n try:\n aurafilter |= AURAFILTER_FLAGS[name]\n except KeyError:\n raise ValueErro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an integer made from combining the list of AuraFilter flag names.
def encode_aurafilter(flags: List[str]) -> int: aurafilter = 0 for name in flags: try: aurafilter |= AURAFILTER_FLAGS[name] except KeyError: raise ValueError(f"Unknown AuraFilter flag name: {name!r}") from None return aurafilter
[ "def decode_aurafilter(aurafilter: int) -> Tuple[List[str], _Hex]:\n af_names = []\n for name, flag in AURAFILTER_FLAGS.items():\n if aurafilter & flag:\n aurafilter &= ~flag\n af_names.append(name)\n return af_names, _Hex(aurafilter)", "def encode_flags(names):\n return r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a range that starts at 1 and ends at `stop`, inclusive.
def range_1(stop: int) -> range: return range(1, stop + 1)
[ "def get_range(start, stop):\n \n nums = []\n\n for num in range(start, stop):\n nums.append(num)\n\n return nums", "def get_range(start, stop):\n\n nums = []\n\n for num in range(start, stop):\n nums.append(num)\n\n return nums", "def downrange(start, stop=0, step=1):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively traverses `schema` and yields member column names.
def yield_column_names(schema: ColumnGroupSchema) -> Iterator[str]: if isinstance(schema, str): yield schema else: seq = schema.values() if isinstance(schema, collections.abc.Mapping) else schema for value in seq: yield from yield_column_names(value)
[ "def member_names(self) -> Iterator[str]:\n return yield_column_names(self.schema)", "def _columns(cls, schema: dsl.Source.Schema) -> typing.Sequence[str]:\n return tuple(f.name for f in schema)", "def _columns(is_refresh: bool, current_path: str, session: ObjectExplorerSession, match_params: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an iterator of member column names.
def member_names(self) -> Iterator[str]: return yield_column_names(self.schema)
[ "def GetColumnIterator(self):\n return self.columns.__iter__()", "def __iter__(self):\n return iter(list(self.get_column_names()))", "def __iter__(self):\r\n for column_id in self._columns.keys():\r\n yield column_id", "def __iter__(self) -> Generator[str, None, None]:\n\n y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new column group schema parameterized with str.format().
def format_schema(schema: ColumnGroupSchema, param: str) -> ColumnGroupSchema: if isinstance(schema, str): return schema.format(param) if isinstance(schema, collections.abc.Mapping): return {k.format(param): format_schema(v, param) for k, v in schema.items()} return [format_schema(v, param) ...
[ "def get_formatter(template_format: str) -> Callable[[Match], str]:\n format_templates = {\n \"JSON\": f\"'$new_name': $db_name\",\n \"Array\": f\"$db_name\"\n }\n\n try:\n template = Template(format_templates[template_format])\n except KeyError:\n raise InvalidStructure()\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the list of column group rules.
def initialize_column_groups( *colgroups: Iterable[Tuple[str, ColumnGroupSchema]] ) -> List[ColumnGroupRule]: return sorted( (ColumnGroupRule(*colgroup_def) for colgroup_def in colgroups), key=lambda colgroup: sum(1 for _ in colgroup.member_names()), reverse=True, )
[ "def _init_rules(self):\n if self.rules is None:\n self.rules = {}\n\n if self.flags.real:\n self.set_rule('C', '.')\n if self.flags.symmetric:\n self.set_rule('T', '.')\n if self.flags.hermitian:\n self.set_rule('H', '.')\n if self.flag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new column group schema with properly recased member names.
def recase_schema( obj: ColumnGroupSchema, uncasefold: Mapping[str, str] ) -> ColumnGroupSchema: if isinstance(obj, str): return uncasefold[obj.casefold()] if isinstance(obj, collections.abc.Mapping): return {key: recase_schema(value, uncasefold) for key, value in obj.items()} return [re...
[ "def standardize_column_names(self, df):\n df.columns = [c.replace(\" \",\"_\").lower() for c in df.columns]\n return df", "def get_cleaned_column_names(self):\n fixed = []\n for k in self.stats.keys():\n pieces = []\n splitter = k.split(\".\")\n for s ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of column groups that match the given column names.
def get_matched_colgroups(column_names: Iterable[str]) -> List[ColumnGroupRule]: casefold_to_normal = {name.casefold(): name for name in column_names} matched_colgroups = [] for group in COLUMN_GROUPS: try: new_schema = recase_schema(group.schema, casefold_to_normal) except KeyE...
[ "def get_matching_columns(self, columns):\n result = []\n for column in columns:\n if self.match(column):\n result.append(column)\n return result", "def get_sorted_columns_and_groups(\n columns: Collection[str], colgroups: Iterable[ColumnGroupRule]\n) -> List[Unio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds a sorted list of column names and column groups.
def get_sorted_columns_and_groups( columns: Collection[str], colgroups: Iterable[ColumnGroupRule] ) -> List[Union[ColumnGroupRule, str]]: column_to_index = {name: index for index, name in enumerate(columns)} # Build an iterable of tuples of (index, column name or colgroup). # Each colgroup is given the ...
[ "def get_country_groups_grid_column_names_by_order(self):\n self.column_name_list = self.get_grid_column_names_by_order(self.country_groups_grid_div_id)\n return self.column_name_list", "def define_columnorder():\n columns = [\"itemid\",\n \"version1\",\n \"version2\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a D2TXT object to TOML markup.
def d2txt_to_toml(d2txt: D2TXT) -> str: columns = d2txt.column_names() colgroups = get_matched_colgroups(columns) columns_with_colgroups = get_sorted_columns_and_groups(columns, colgroups) toml_rows = [make_toml_row(row, colgroups, columns_with_colgroups) for row in d2txt] # Use qtoml.dumps(), bec...
[ "def convert_md2tex(md):\n temp = md\n temp = conversions.convert_headers(temp)\n temp = conversions.convert_lists(temp)\n temp = conversions.convert_table(temp)\n temp = conversions.convert_images(temp)\n temp = conversions.convert_links(temp)\n temp = conversions.convert_bold(temp)\n temp ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively unpacks a column group, yielding column names and values.
def unpack_colgroup( schema: ColumnGroupSchema, value: Union[Mapping, Collection, str] ) -> Iterator[Tuple[str, Union[int, str]]]: if isinstance(value, (int, str)): yield schema, value elif isinstance(value, collections.abc.Mapping): for key, sub_value in value.items(): yield fro...
[ "def unpack(buf: bytes) -> dict[str, Any]:\n flags: int\n column_count: int\n len_names: int\n flags, column_count, len_names = struct_unpack_from(\"<BHH\", buf)\n data_offset_code, coldata_size, data_offset_mask = decode_data_size(flags)\n if (flags & 0xFC) != 4:\n raise DynColValueError(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Repaint display. Optional rect or rect list to specify regions to repaint.
def update(self, rect_list=None): if isinstance(rect_list, list): self._rect_list = rect_list elif rect_list: self._rect_list = [rect_list] else: self._rect_list = self._surface_rect try: SwingUtilities.invokeAndWait(self) except In...
[ "def update_rect(self):\n self._update_tiles()", "def crDisplayRect(*args, **kwargs):\n pass", "def redraw(self):\n for i, j in self.rectangles:\n self.canvas.itemconfig(self.rectangles[(i, j)], fill=self.check_colour((i, j)))\n if self.check_visible(self.coord):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creating a dictionary of all rmsd values calculated after docking. Writes to 'no_rmsd' receptors that failed the docking.
def _get_rmsd_list(self): fout_no = open('no_rmsd','w')#no poses file fout_empty = open('rmsd_empty','w')#poses file was empty fout_minus = open('minus_1','w') for subdir in os.listdir(self.path): if subdir.startswith('.'): continue try: ...
[ "def checkMeasurementsAndResonances(self):\n \n setCurrentStore(self.project,'NmrProject')\n \n #\n # Make dict of resonance names (based on application format)\n #\n \n self.resonanceNames = getApplResNames(self.format,self.project.currentNmrProject.resonances)\n\n #\n # Check if exact sa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets self.running_time by summing all run times of successful runs
def _get_running_time(self): time_sum = 0.0 for subdir in os.listdir(self.path): if subdir.startswith('.'): continue try: line = open('{0}/{1}/{2}/out/OUTDOCK'.format(self.path, subdir, DOCKING_RUN_FILES),'r').readlines()[-1] if lin...
[ "def task_time_running(self, task_id, task_name, args, kwargs, nsecs):\n nsecs = float(nsecs)\n self.total_tasks_processed += 1\n self.total_task_time_running += nsecs\n if task_name not in self.total_task_time_running_by_type:\n self.total_task_time_running_by_type[task_name]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reads a baseline file (contains list of names and rmsd values) and returns it as a dictionary
def _read_baseline(self, path): base_rmsd = dict() fin = open(path,'r') for line in fin: if line == '\s' or line == '' or line == '\n': continue k, v = line.split() base_rmsd[k.strip()] = float(v.strip()) return base_rmsd
[ "def readRunDict(fileName):\n result = {}\n with FileWrapper(fileName) as f:\n for ln, line in enumerate(tqdm(f, desc='loading run (by line)', leave=False)):\n line = line.strip()\n if not line:\n continue\n fld = line.split()\n if len(fld) != ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reads a scores file (contains list of names and scores) and returns it as a dictionary
def _read_scores(self,path): scores = dict() fin = open(path,'r') for line in fin: k, v = line.split() scores[k.strip()] = float(v.strip()) return scores
[ "def get_scores():\n with open('scores.json') as f:\n scores = loads(f.read())\n return scores", "def parse_scores_file(filename):\n scores = []\n with open(filename, \"r\") as scores_file:\n for line in scores_file:\n line = line.rstrip()\n info = line.split(\":\")...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function split the attribute manifest file of CelebA dataset into three files, train, test and valid file which are used
def split_manifest(root_path, manifest_file_path): train_manifest = open(os.path.join(root_path,"dataset", "train_manifest.txt"), "w+") test_manifest = open(os.path.join(root_path, "dataset","test_manifest.txt"), "w+") val_manifest = open(os.path.join(root_path,"dataset" ,"valid_manifest.txt"), "w+") w...
[ "def preprocess(self):\n lines = [line.rstrip() for line in open(self.attr_path, 'r')]\n all_attr_names = lines[1].split()\n for i, attr_name in enumerate(all_attr_names):\n self.attr2idx[attr_name] = i\n self.idx2attr[i] = attr_name\n\n lines = lines[2:]\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts samples with the same amount of pressed and not pressed keys. Returns a list of these samples. Each sample is a tuple, containing (time, data, key_code), where key_code is 0 for a sample where no key was pressed.
def extract_samples(config, preprosessed_events): MIN_DISTANCE = config.negative_sample_min_distance BEFORE_PRESSED = int(round(config.sequence_length * config.sequence_ratio)) AFTER_PRESSED = config.sequence_length - BEFORE_PRESSED preprosessed_events = list(preprosessed_events) samples = [] ...
[ "def get_sample():\n sample_output = check_output([NODE_TOOL, 'rangekeysample'])\n keys = [{'key': key.strip().decode('hex'), 'size': 0}\n for key in sample_output.splitlines()[1:]]\n sorted(keys, key=lambda key: key['key'])\n return keys", "def read_keys(self) -> list[KeyPress]:", "def getKeyEvent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test drop API call
def test_drop(self): client_cik, client_rid = self.makeClient(self.cik) isok, response = self.onep.drop(self.cik, client_rid) self.assertTrue(isok, 'client drop succeeded') isok, response = self.onep.info(self.cik, client_rid) self.assertFalse(isok, 'dropped client was really dro...
[ "def test_drop(self):\n self._run_tests(\"drop\")", "def test_delete_nonexistent_dog(temp_app, temp_db):\n res = temp_app.delete('/api/dogs/blorma')\n res_data = json.loads(res.data)\n assert res.status_code == 404, 'The response should be 404 -- NOT FOUND.'\n assert isinstance(res_data, dict),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create HLD yaml file.
def generate_HLD(component, output): component.delete_none_attrs() yaml.indent(mapping=2, sequence=4, offset=2) d = component.asdict() yaml.dump(d, output)
[ "def user_create_yaml(self):\n pass", "def create_yaml(self):\n if self._language == PYTHON:\n language_str = 'python'\n package_route = '$(System.DefaultWorkingDirectory)'\n dependencies = self._python_dependencies()\n elif self._language == NODE:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests sorting by revenue.
def testGameRevenue(self): response = self.client.get( reverse('api:game-list', args=['v1']), {'order_by': 'revenue'}, format='json' ) self.assertEquals(response.status_code, 200) content = self.parser.parse(BytesIO(response.content)) ...
[ "def test_sorting_ascending_by_price_and_area():", "def test_sorting_descending_by_price():", "def test_sorting_descending_by_price_and_area():", "def test_sorting_ascending_by_district():", "def test_sorting_ascending_by_area():", "def test_overall_report_banner_revenue():\n assert (overall_data['bann...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test function to check equality of two SciPy Compressed Sparse Row (CSR) matrices.
def test__csr_matrix_equal(self): matrix_a = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2)) matrix_b = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2)) matrix_c = sparse.csr_matrix(([1.0], ([1], [0])), shape=(2, 2)) self.assertEqual(decaydata._csr_matrix_equal(matrix_a, matrix...
[ "def test_check_sparse(self):\n x, x_rand, s = self.create_testdata()\n task = mmRDTR()\n #check that a dense array x is passed thru unchanged\n check = task.check_sparse(x)\n self.assertEqual(np.all(check==x),True)\n #check that a sparse matrix s is converted to a numpy ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test instantiation of DecayMatrices objects.
def test_decaymatrices_instantiation(self): # check with artificial SciPy data decay_consts = np.array([0.0] * 2) matrix_c = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2)) matrix_c_inv = sparse.csr_matrix(([1.0], ([1], [1])), shape=(2, 2)) year_conv = 365.0 decay_m...
[ "def test_init_no_optionals(tmpdir):\n exp_mat = pyEM2.ExpressionMatrix(\n os.path.join(str(tmpdir), \"EM2\"))\n\n assert isinstance(exp_mat, pyEM2.ExpressionMatrix)", "def test_rate_matrix_creation(self): \n \n # testing that rate matrix was correctly created from dimension\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test DecayMatrices instances equal.
def test_decaymatrices___eq__(self): # check with artificial SciPy data decay_consts = np.array([0.0] * 2) matrix_c = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2)) matrix_c_inv = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2)) year_conv = 365.0 decay_mats_a =...
[ "def test__csr_matrix_equal(self):\n\n matrix_a = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2))\n matrix_b = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2))\n matrix_c = sparse.csr_matrix(([1.0], ([1], [0])), shape=(2, 2))\n self.assertEqual(decaydata._csr_matrix_equal(matrix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test DecayMatrices instances not equal.
def test_decaymatrices___ne__(self): # check with artificial SciPy data decay_consts = np.array([0.0] * 2) matrix_c = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2)) matrix_c_inv = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2)) year_conv = 365.0 decay_mats_a =...
[ "def test_decaymatrices___eq__(self):\n\n # check with artificial SciPy data\n decay_consts = np.array([0.0] * 2)\n matrix_c = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2))\n matrix_c_inv = sparse.csr_matrix(([1.0], ([0], [0])), shape=(2, 2))\n year_conv = 365.0\n de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test instantiation of DecayData objects.
def test_decaydata_instantiation(self): # pylint: disable=too-many-statements # check instantiation from sub-package data = decaydata.DecayData("icrp107", load_sympy=False) self.assertEqual(data.dataset, "icrp107") self.assertEqual(data.hldata[0][0], 100.5) self.assertE...
[ "def test_factory_methods(self):\n\n DatumTest.create_data()", "def test_default_constructor(self):\n\n datum = Datum()", "def test_constructor(self):\n pass", "def test_data_object_vaporise(self):\n pass", "def test_instantiation(self):\n self.report('Testing instantiation of...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test DecayData half_life() method.
def test_decaydata_half_life(self): data = decaydata.DecayData("icrp107") self.assertEqual(data.half_life("H-3"), 388781329.30560005) self.assertEqual(data.half_life("H-3", "y"), 12.32) self.assertEqual(data.half_life("Fm-257", "h"), 2412.0) self.assertEqual(data.half_life("Rn-2...
[ "def test_half_life_u_220():\n\n isotope_without_half_life_data = \"No-248\"\n\n with pytest.raises(MissingAtomicDataError, message=(\n f\"This test assumes that {isotope_without_half_life_data} does \"\n f\"not have half-life data. If half-life data is added for this \"\n f\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test DecayData branching_fraction() method.
def test_decaydata_branching_fraction(self): data = decaydata.DecayData("icrp107") self.assertEqual(data.branching_fraction("K-40", "Ca-40"), 0.8914) self.assertEqual(data.branching_fraction("K-40", "H-3"), 0.0)
[ "def testConsistency(self):\n #self.assertAlmostEqual(self.fxlinkedcashflow.amount(),0)", "def test_calculate_retention_fee():\n assert calculate_retention_fee(2578) == Decimal('128.91')", "def test_gt(self) -> None:\r\n f12: Fraction = Fraction(1, 2)\r\n f34: Fraction = Fraction(3, 4)\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test DecayData decay_mode() method.
def test_decaydata_decay_mode(self): data = decaydata.DecayData("icrp107") self.assertEqual(data.decay_mode("K-40", "Ca-40"), "\u03b2-") self.assertEqual(data.decay_mode("K-40", "H-3"), "")
[ "def test_decaydata_instantiation(self):\n\n # pylint: disable=too-many-statements\n\n # check instantiation from sub-package\n data = decaydata.DecayData(\"icrp107\", load_sympy=False)\n self.assertEqual(data.dataset, \"icrp107\")\n self.assertEqual(data.hldata[0][0], 100.5)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test DecayData not equality.
def test_decaydata___ne__(self): data1 = decaydata.DecayData("icrp107") data2 = decaydata.DecayData("icrp107") data2.dataset = "icrp07" self.assertNotEqual(data1, data2)
[ "def test_ne(self):\n dummy = DummyCryptographicObject()\n self.assertFalse(dummy != dummy)", "def test_not_equal_on_not_equal_object_type(self):\n a = payloads.GetResponsePayload(\n object_type=enums.ObjectType.SYMMETRIC_KEY\n )\n b = payloads.GetResponsePayload(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filters the Pipeline IR proto, thus enabling partial runs. The set of nodes included in the filtered pipeline is the set of nodes between from_nodes and to_nodes, minus the set of skip_nodes. Note that the input_pipeline will not have any subpipeline nodes, since the compiler is supposed to flatten them. Also, if the i...
def filter_pipeline( input_pipeline: p_pb2.Pipeline, pipeline_run_id_fn: Callable[[p_pb2.InputSpec.Channel], str], from_nodes: Optional[Callable[[str], bool]] = None, to_nodes: Optional[Callable[[str], bool]] = None, skip_nodes: Optional[Callable[[str], bool]] = None, ) -> p_pb2.Pipeline: if any( ...
[ "def test_node_state_for_skipped_nodes_in_partial_pipeline_run(\n self, mock_time\n ):\n mock_time.time.return_value = time.time()\n with self._mlmd_connection as m:\n pipeline = _test_pipeline(\n 'pipeline1',\n execution_mode=pipeline_pb2.Pipeline.SYNC,\n pipeline_nodes=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes a pipeline_run_id_fn that automatically resolves pipeline_run_ids.
def make_latest_resolver_pipeline_run_id_fn( metadata_connection_config: mlmd_pb2.ConnectionConfig ) -> Callable[[p_pb2.InputSpec.Channel], str]: mlmd_client = mlmd_analytics.Analytics(metadata_connection_config) def _pipeline_run_id_fn(channel): pipeline_run = mlmd_client.get_latest_pipeline_run( ...
[ "def pipeline_id(self):\n pass", "def ids(pytestconfig, subscriber) -> Callable[[ResourceType], str]:\n sub = subscriber\n if sub is None:\n sub = 'unknown'\n factory = IDFactory(sub)\n return lambda id_code: factory.make_id(id_code)", "def _MakeARunId(*args):\n return run_id.RunId.GenerateGlobal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Traverse a DAG from start_nodes, either upstream or downstream.
def _traverse(node_map: Mapping[str, p_pb2.PipelineNode], direction: _Direction, start_nodes: Collection[str]) -> Set[str]: visited_node_ids = set() stack = [] for start_node in start_nodes: # Depth-first traversal stack.append(start_node) while stack: current_node_id = stack.pop()...
[ "def __visit_task_nodes(self, curr_node, start_nodes):\n if curr_node in start_nodes:\n return [curr_node]\n\n visited_nodes = [curr_node]\n for dependency in self.task_dependencies[curr_node]:\n visited_nodes += self.__visit_task_nodes(dependency, start_nodes)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove node.downstream_nodes that have been filtered out.
def _remove_dangling_downstream_nodes( node: p_pb2.PipelineNode, node_ids_to_keep: Collection[str]) -> p_pb2.PipelineNode: # Using a loop instead of set intersection to ensure the same order. downstream_nodes_to_keep = [ downstream_node for downstream_node in node.downstream_nodes if downstream_...
[ "def prune_network(self):\n\n done = False\n while not done:\n done = True\n\n for node in list(self.graph.nodes()):\n in_edge_cnt = len(self.graph.in_edges(nbunch=[node]))\n node_type = self.graph.nodes[node][\"type\"]\n\n if in_edge_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter pernode deployment configs. Cast deployment configs from Any proto to IntermediateDeploymentConfig. Take all three pernode fields and filter out the nodes using node_ids_to_keep. This works because those fields don't contain references to other nodes.
def _fix_deployment_config( input_pipeline: p_pb2.Pipeline, node_ids_to_keep: Collection[str]) -> Union[any_pb2.Any, None]: if not input_pipeline.HasField('deployment_config'): return None deployment_config = p_pb2.IntermediateDeploymentConfig() input_pipeline.deployment_config.Unpack(deployment_conf...
[ "def filtered_config_from_config(config):\n if 'filter' in config.keys() and config['filter'] is not None:\n f = config['filter']\n for key in ['environments', 'n_episodes', 'n_steps', 'n_instances', 'timeout']:\n if type(config[key]) is list:\n config[key] = [config[key][...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a FBAModel to a SBML file
def to_sbml(self, params): files = {} _id, cobra_model = self._ws_obj_to_cobra(params['input_ref']) files['file_path'] = os.path.join(params['destination_dir'], _id + ".xml") cobra.io.write_sbml_model(cobra_model, files['file_path']) return _id, files
[ "def create_fba(sbml_file):\n sbmlns = SBMLNamespaces(3, 1)\n sbmlns.addPackageNamespace(\"fbc\", 2)\n sbmlns.addPackageNamespace(\"comp\", 1)\n\n doc_fba = SBMLDocument(sbmlns)\n doc_fba.setPackageRequired(\"comp\", True)\n mdoc = doc_fba.getPlugin(\"comp\")\n doc_fba.setPackageRequired(\"fbc\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute the specified file, optionaly setup its context by using globals and locals.
def exec_file(filename, globals=None, locals=None): if globals is None: globals = {} if locals is None: locals = globals locals['__file__'] = filename from py import path from _pytest import config from _pytest.assertion import rewrite f = path.local(filename) config = co...
[ "def run_file(file_path, globals_, script_dir=SCRIPT_DIR):\n fix_sys_path()\n script_name = os.path.basename(file_path)\n script_name = SCRIPT_EXCEPTIONS.get(script_name, script_name)\n script_path = os.path.join(script_dir, script_name)\n execfile(script_path, globals_)", "def exec_file(path: str, global_va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the specified command in container. equiv of `docker exec`, command is str
def _exec_command_in_container(client, container, command): exec_id = client.exec_create(container, command) output = client.exec_start(exec_id).decode('utf-8') logger.info(output) return output
[ "def exec_cmd(self, container: _t.Any, cmd: str) -> _t.Any:", "def _run(self, command):\n print('Running: ' + command)\n return api.sudo('docker exec {user} bash -c \"{command}\"'.format(\n user=self.username, command=command.replace('\"', '\\\\\"')))", "def run_command(self, command, stdin=sys.std...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send the JSON file to the selected API endpoint. The optional custom header is used (given it is provided).
def _send_json_file(endpoint, filename, custom_headers=None): headers = {'Content-Type': 'application/json', 'Accept': 'application/json'} if custom_headers is not None: headers.update(custom_headers) with open(filename) as json_data: response = requests.post(endpoint, data=js...
[ "def send_json_file(self, endpoint, filename):\n headers = {'Content-Type': 'application/json',\n 'Accept': 'application/json'}\n\n headers.update(self.authorization())\n with open(filename) as json_data:\n response = requests.post(endpoint, data=json_data, headers=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if given environment variable exist. Check the existence of environment variable needed to connect to the AWS S3 database.
def _check_env_var_presence_s3_db(env_var_name): if os.environ.get(env_var_name) is None: logger.info("Warning: the {name} environment variable is not set.\n" "All tests that access AWS S3 database will fail\n".format( name=env_var_name))
[ "def check_envvar(envvar):\n if not os.environ.get(envvar):\n raise EnvironmentError(\"Variable '%s' not set\" % envvar)", "def is_environment_variables_present():\n return (os.getenv('WORK_SERVER_HOSTNAME') is not None\n and os.getenv('WORK_SERVER_PORT') is not None\n and os.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the test environent whether tests are run locally or in Docker.
def check_test_environment(context, coreapi_url): if context.running_locally: logger.info("Note: integration tests are running localy via docker-compose") if coreapi_url: _check_env_for_remote_tests("F8A_API_URL") _check_env_for_remote_tests("F8A_JOB_API_URL") _ch...
[ "def is_testing() -> bool:\n return bool(int(os.environ.get(\"TEST\", 0)))", "def is_docker_env() -> bool:\n return Path(\"/.dockerenv\").exists()", "def _in_travis(): # pragma: no cover\n return 'TRAVIS' in os.environ", "def running_on_ci() -> bool:\n env_vars = [\"CI\", \"BUILD_NUMBER\"]\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the basic structure of response with access token.
def check_token_structure(data): assert "token" in data token_structure = data["token"] assert "access_token" in token_structure assert "token_type" in token_structure assert "expires_in" in token_structure
[ "def has_access_token(request: Request) -> bool:", "def test_user_obtain_token(self):\n self.assertEqual(self.response.status_code, status.HTTP_200_OK)\n token_dict = json.loads(self.response.content)\n self.assertTrue('access' in token_dict)\n self.assertTrue('refresh' in token_dict)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the current stock level for a product.
def get_stock_level(cls, product): available_stock_level = cls.available_stock_level(product.sku) StockLevelHistory.objects.new_import_stock_level_update( product=product, stock_level=available_stock_level ) return available_stock_level
[ "def get_initial_stock_level(cls, product):\n try:\n instance = InitialStockLevel.objects.get(sku=product.sku)\n except InitialStockLevel.DoesNotExist:\n return None\n else:\n return instance.stock_level", "def getProduct_Stock(self):\r\n return self.__...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the current stock level for multiple products.
def get_stock_levels(cls, products): skus = products.values_list("sku", flat=True) stock_level_records = cls._get_multiple_stock_level_info_from_linnworks(*skus) with transaction.atomic(): for product in products: StockLevelHistory.objects.new_import_stock_level_updat...
[ "def get_stock_level(cls, product):\n available_stock_level = cls.available_stock_level(product.sku)\n StockLevelHistory.objects.new_import_stock_level_update(\n product=product, stock_level=available_stock_level\n )\n return available_stock_level", "def get_initial_stock_le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the temporary intial stock level for a new product.
def get_initial_stock_level(cls, product): try: instance = InitialStockLevel.objects.get(sku=product.sku) except InitialStockLevel.DoesNotExist: return None else: return instance.stock_level
[ "def get_stock_level(cls, product):\n available_stock_level = cls.available_stock_level(product.sku)\n StockLevelHistory.objects.new_import_stock_level_update(\n product=product, stock_level=available_stock_level\n )\n return available_stock_level", "def calculate_init_stock...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the stock level for a product.
def set_stock_level(cls, product, user, new_stock_level, change_source=""): available_stock_level = cls.available_stock_level(sku=product.sku) relative_stock_level_change = new_stock_level - available_stock_level change_source = change_source or f"Updated through STCAdmin by {user}" upda...
[ "def update_stock_level(self):\n try:\n current_stock_level = StockManager.get_stock_level(self.instance.product)\n new_stock_level = current_stock_level - self.instance.quantity\n if new_stock_level < 0:\n raise Exception(\"Cannot set stock level below zero.\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a history of stock level changes for a SKU.
def get_stock_level_history(cls, sku): records = cls._get_stock_level_history(sku) return [ { "timestamp": record.timestamp, "stock_level": record.stock_level, "text": record.text, "relative_change": record.relative_change, ...
[ "def stock_level_info(cls, sku):\n return cls._get_stock_level__info_from_linnworks(sku)", "def _get_stock_level__info_from_linnworks(cls, sku):\n return linnapi.inventory.get_stock_level_by_sku(sku=sku)", "def get_stock_levels(cls, products):\n skus = products.values_list(\"sku\", flat=Tru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return stock level information for a product SKU.
def stock_level_info(cls, sku): return cls._get_stock_level__info_from_linnworks(sku)
[ "def _get_stock_level__info_from_linnworks(cls, sku):\n return linnapi.inventory.get_stock_level_by_sku(sku=sku)", "def get_stock_level(cls, product):\n available_stock_level = cls.available_stock_level(product.sku)\n StockLevelHistory.objects.new_import_stock_level_update(\n produ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if all SKUs exist in Linnworks, otherwise False.
def products_exist(cls, *skus): try: stock_level_ids = cls._get_stock_item_ids(*skus) except linnapi.exceptions.InvalidResponseError: return False if not set(skus).issubset(set(stock_level_ids.keys())): return False return True
[ "def is_valid_sku(sku: str, batches: Sequence[Batch]) -> bool:\n return sku in {it.sku for it in batches}", "def __contains__(self, name_or_package):\n for package, wool in self.wools.items():\n if name_or_package == package or (\n name_or_package.lower() == wool.id()):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return channel linked items for SKUs.
def channel_links(cls, *skus): links = cls._get_channel_linked_items(*skus) output = defaultdict(lambda: defaultdict(list)) for sku, sku_links in links.items(): for channel in LinnworksChannel.objects.all(): for link in sku_links: if ( ...
[ "def channels():\n yield from _channels.values()", "def mediapackage_channels(region):\n service = boto3.client(\"mediapackage\", region_name=region)\n jsonpath_expr = parse('$..Password')\n response = service.list_channels()\n items = response['Channels']\n while \"NextToken\" in response:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return stock item IDs for one or more SKUs.
def _get_stock_item_ids(cls, *skus): return linnapi.inventory.get_stock_item_ids_by_sku(*skus)
[ "def get_all_skus():\n sku_ids = set()\n for sku_id in sku_database.find({}, {\"_id\": 0, \"SKU_id\": 1}):\n if sku_id.get(\"SKU_id\"):\n sku_ids.add(sku_id[\"SKU_id\"])\n else:\n continue\n\n return list(sku_ids)", "def get_items(self):\n\n items = []\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return stock level information for a product SKU.
def _get_stock_level__info_from_linnworks(cls, sku): return linnapi.inventory.get_stock_level_by_sku(sku=sku)
[ "def stock_level_info(cls, sku):\n return cls._get_stock_level__info_from_linnworks(sku)", "def get_stock_level(cls, product):\n available_stock_level = cls.available_stock_level(product.sku)\n StockLevelHistory.objects.new_import_stock_level_update(\n product=product, stock_level=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return stock level information for multiple product SKUs.
def _get_multiple_stock_level_info_from_linnworks(cls, *skus): if not skus: return {} return linnapi.inventory.get_stock_levels_by_skus(*skus)
[ "def stock_level_info(cls, sku):\n return cls._get_stock_level__info_from_linnworks(sku)", "def _get_stock_level__info_from_linnworks(cls, sku):\n return linnapi.inventory.get_stock_level_by_sku(sku=sku)", "def get_stock_levels(cls, products):\n skus = products.values_list(\"sku\", flat=Tru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the total number of items in stock.
def stock_count(self): return self.stock_level_records.aggregate(models.Sum("stock_level"))[ "stock_level__sum" ]
[ "def get_amount_of_items(self):\n amount = 0\n for item in self.get_items():\n amount += item.amount\n return amount", "def get_numStocks(self):\n return len(self.DoS)", "def countInventoryTotal(conn):\n curs = conn.cursor()\n curs.execute(\n '''select count(*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return if perform importing, based on checking zexp files in /import directory.
def checkIfImport(): instance_ipath, product_ipath = getImportedPathes() product_ilist = [i for i in os.listdir(product_ipath) \ if osp.isfile(osp.join(product_ipath,i)) and i.endswith('.zexp')] if product_ilist: return 1 return 0
[ "def is_import():\n return sync_mode in (SyncMode.IMPORT_LOCAL, SyncMode.IMPORT_REMOTE)", "def imports(self):\n line = self.line.strip()\n if line.startswith('im'):\n if line.startswith('import') is False:\n return True\n elif line == '':\n return True"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return Plone instance and Skin product import pathes.
def getImportedPathes(): # Based on instance path, construct import pathes cfg = getConfiguration() instance_ipath = osp.join(cfg.instancehome, "import") product_ipath = osp.join(package_home(GLOBALS), "import") # Check presence of Product import directory if not osp.isdir(product_ipath): ...
[ "def copyToInstanceImport():\n print >> import_out, INTRO_TO_INSTANCE\n instance_ipath, product_ipath = getImportedPathes()\n\n # Compose temp dir back_[date] dir path in Instance import directory\n temp_dir_id = \"back_%s\" % strftime(\"%Y%m%d%H%M%S\", gmtime())\n temp_dir_path = osp.join(instance_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move samenamed files from Instanse's dir to temp dir.
def moveToTemp(same_instance_files, instance_ipath, temp_dir_path): os.mkdir(temp_dir_path) # Create temp back_[date] dir try: [copyFile(instance_ipath, temp_dir_path, f_name) for f_name in same_instance_files] [os.remove(osp.join(instance_ipath, f_name)) for f_name in same_instance_files] ...
[ "def _move_files(self):\n self._move_directory(self._origin, self._destination)\n for directory in self._filesystem.listdir(self._filesystem.join(self._layout_tests_root, PLATFORM_DIRECTORY)):\n self._move_directory(self._filesystem.join(PLATFORM_DIRECTORY, directory, self._origin),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform copying imported files from /import dir to Plone's instance import dir.
def copyToInstanceImport(): print >> import_out, INTRO_TO_INSTANCE instance_ipath, product_ipath = getImportedPathes() # Compose temp dir back_[date] dir path in Instance import directory temp_dir_id = "back_%s" % strftime("%Y%m%d%H%M%S", gmtime()) temp_dir_path = osp.join(instance_ipath, temp_dir_...
[ "def importfiles(self, irc, msg, args, e):\n self.db.importFiles()", "def copy_files(self):\n copy_all(self.test_path, self.game_path)\n shutil.copyfile(self.spt_path, self.spt_out)", "def import_dir(self, dir, move=False):\n copytree(dir,self.dir, move)", "def import_wp_content(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perfom backup same named portal objects in temp folder.
def makeBackUp(portal, portal_objects, temp_dir_path, obj_id): # Get id of temp folder-object durty_path,temp_id = osp.split(temp_dir_path) if not temp_id: durty_path,temp_id = osp.split(durty_path) # Get temp folder-object if temp_id not in portal_objects: portal.invokeFactory('L...
[ "def __makeBackup(self):\n pass #FIXME!!!", "def _make_backup(self):\n\t\ttimestr = time.strftime(\"%Y-%m-%d %H%M%S\")\n\t\tif not os.path.isdir(self.BACKUP_DIR):\n\t\t\tos.makedirs(self.BACKUP_DIR)\n\t\tbackup_path = os.path.join(self.BACKUP_DIR, '{}{} {}'.format(\n\t\t\ttimestr, randint(0, 9), 'Processes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import all objects from zexp files to portal root (based on IMPORT_POLICY).
def importToPortalRoot(portal, product_file_names, temp_dir_path): if not IMPORT_POLICY in ALLOWED_IMPORT_POLICY: raise Exception("%s - wrong import policy, must be one of the %s" \ % (IMPORT_POLICY, ALLOWED_IMPORT_POLICY) ) print >> import_out, INTRO_TO_ROOT % (product_file_na...
[ "def import_workspace( ws , objects):\n\n if not isinstance( objects, list ):\n objects = [objects,]\n\n ## NOTE getattr is needed to escape python keyword import\n for o in objects:\n getattr( ws, \"import\") ( o )", "def import_all():\n\n # count the number of files loaded\n count =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crea un Collage en el contexto dado..
def createCollage(context, title): id = idnormalizer.normalize(title, 'es') if not hasattr(context, id): context.invokeFactory('Collage', id=id, title=title)
[ "def make(self) -> None:\n\n # arbitrarily selecting the first image from the list, index 0\n with Image.open(self.image_list[0]) as first_frame_image_in_list:\n\n # Find the width and height of the first image of the list.\n # Assuming all the images have same size.\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for user groups.
def search_user_groups(self, fields=None, q=None): params = {} if fields: params.update({"f": fields}) page_num = 1 page_size = 1 total = 2 if q: params['q'] = q while page_num * page_size < total: resp = self.sonarqube.make...
[ "def searchDB():\n \n db = connect_db()\n cursor = db.cursor()\n cursor.execute(\"SELECT * FROM userGroups\")\n rows = cursor.fetchall()\n for row in rows:\n print(\"Group: \", row[0])\n print(\"Members: \", row[1])\n db.close()", "def group_search_results(self):\r\n def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for users with membership information with respect to a group.
def search_users_belong_to_group(self, group_name, q=None, selected="selected"): params = { 'name': group_name, 'selected': selected } page_num = 1 page_size = 1 total = 2 if q: params.update({'q': q}) while page_num * page_si...
[ "def getMembersByGroup(group):\n \n db = connect_db()#Connect to the user groups database\n cursor = db.cursor()#Create cursor object for searching the database table\n cursor.execute(\"SELECT usersInGroup FROM userGroups WHERE groupName=?\", (group,))#Search the database for the user group id and retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
recursively load data from HDF5 archive as dict
def recursively_load_dict_contents_from_group(h5file: "h5py.File", path: str, ) -> dict: ans = {} for key, item in h5file[path].items(): if isinstance(item, h5py._hl.dataset.Dataset): ans[key] = item.value elif isinstance(item, h...
[ "def load_hdf5(file_path, file_dictionary_path=\"/\"):\n\n def data_grabber(file, path):\n \"\"\"\n Helper function which recursively loads data from the hdf5 group structure to a dictionary.\n\n :param file: hdf5 file instance to load the data from.\n :param path: Current group path ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
count() ... GROUP is generally an aggregation query which we can ignore.
def test_ok_count_with_group(self): with self.patch_schema({}): sql = ( "SELECT count(*), userid " "FROM a GROUP BY userid ORDER BY id DESC") stmt = sqlparse.parse(sql)[0] assert False == self.has_order_by_count(stmt)
[ "def create_sql_groupby_count(self):\n pass", "def _group_and_count( cls ,model , field):\n count = func.count(field)\n query = db.session.query(count , field).group_by(field).all() \n\n\n results = {\n 'query': query ,\n 'total': model.query.count()\n }\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates set of indices corresponding to image timestamps for a traverse, where each timestamp corresponds to a camera pose that has regular spatial separation (threshold) from the previous entry.
def build_reference_keyframes(gt, threshold, attitude_weight): indices = [0] # first image in set of keyframes gt_curr = gt[0] for i in range(1, len(gt)): curr_diff = geometry.metric(gt_curr, gt[i], attitude_weight) if curr_diff > threshold: indices.append(i) gt_curr ...
[ "def getInterPathTimes(self):\n\n interPathTimes = defaultdict( lambda: list() )\n for e in self.tedges:\n # Get target v of current edge e=(u,v,t)\n v = e[1]\n t = e[2]\n\n # Get time stamp of link (v,*,t_next) with smallest t_next such that t_next > t\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the storage directory name from comments in the deck.
def getstoragename(deck): try: ff = open(deck,'r') except IOError: print "I don't know what you want. The file ",deck," doesn't exist and no" print "storage directory was specified." sys.exit(1) lines = ff.readlines() for l in lines: if l[:2] == storageflag: return string.strip(l[2:]) ...
[ "def get_storage_dir(self, kind):\n return self.STORAGE_DIRS[kind] / str(self.id)", "def _get_ds_name_folder_path(self, backing):\n vmdk_ds_file_path = self.volumeops.get_path_name(backing)\n (datastore_name,\n folder_path, _) = volumeops.split_datastore_path(vmdk_ds_file_path)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts tcp forwarding from localhost to this android device.
def tcp_forward(self, host_port, device_port): if self._ssh_connection: # We have to hop through a remote host first. # 1) Find some free port on the remote host's localhost # 2) Setup forwarding between that remote port and the requested # device port ...
[ "def open(self):\n self._server = socketserver.ThreadingTCPServer(\n server_address=('localhost', self._requested_local_port),\n RequestHandlerClass=self._create_handler(self._ssh_client, self._remote_host, self._remote_port),\n )\n\n threading.Thread(target=self.serve_for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop tcp forwarding a port from localhost to this android device.
def remove_tcp_forward(self, host_port): if self._ssh_connection: remote_port = self._ssh_connection.close_ssh_tunnel(host_port) if remote_port is None: logging.warning("Cannot close unknown forwarded tcp port: %d", host_port) ...
[ "def adb_down(self, port):\n self.adb_transport = None\n self.check_adb([\"disconnect\", \"localhost:%d\" % port])\n\n # Wait until QEMU's forward has expired\n CONNECT_MAX_TRIES = 15\n connect_tries = 0\n while True:\n try:\n sock = socket.socket(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main for the program for getting image stats.
def main(): base_dir = '/home/sjimenez/imagenes_prueba' out_dir = '/home/sjimenez/easy_analysis' for _, _, files in os.walk(base_dir, topdown=False): for f in files: print('--------- {} ---------'.format(f)) act_dir = osp.join(base_dir, f) act_im = cv2.imread(act_...
[ "def main():\n\n usage = 'usage: %prog [options] imagefile'\n\n parser = OptionParser(usage=usage)\n options, args = parser.parse_args()\n\n if len(args) != 1:\n print \"Incorrect command line arguments. Missing (or too many) image files\"\n return 1\n\n image = args[0]\n\n scan_file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get listing of all possible platform combinations matching current platform.
def get_platform_combinations(): mapped_osname = platform_map(g_osname) mapped_osarch = g_osarch ret = [mapped_osname] while True: ret += [mapped_osarch, mapped_osname + "-" + mapped_osarch] mapped_osarch = platform_map_iterate(mapped_osarch) if not mapped_osarch: break return sorted(ret, re...
[ "def get_platforms(self):\n if self.platform == 'All':\n return PLATFORMS\n else:\n return self.platform.split(':')", "def get_platform_combinations():\n mapped_osname = platform_map(g_osname.lower())\n mapped_osarch = g_osarch.lower()\n ret = [mapped_osname]\n whil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tell if this platform value can be deconstructed.
def deconstructable(self): return isinstance(self.get(), int)
[ "def is_deconstructable(op):\n return isinstance(op, int) or (isinstance(op, PlatformVar) and op.deconstructable())", "def deconstructable(self):\n return isinstance(self.get(), int)", "def _pfp__can_unpack(self):\n return self._pfp__pack_type is not None", "def can_decode(self) -> bool:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Follow platform mapping chain as long as possible.
def platform_map(op): while True: found = platform_map_iterate(op) if not found: break op = found return op
[ "def platform_map(op):\n while True:\n found = platform_map_iterate(op)\n if not found:\n break\n op = found\n return op", "def remap(self, paths, output_platform):\n if output_platform not in self._map.keys():\n print 'Error: platform name {} not found in m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Destroy platform variable, replace with default.
def replace_platform_variable(name, op): if not name in g_platform_variables: raise RuntimeError("trying to destroy nonexistent platform variable '%s'" % (name)) g_platform_variables[name] = { "default" : op }
[ "def replace_platform_variable(name, op):\n if not name in g_platform_variables:\n raise RuntimeError(\"trying to destroy nonexistent platform variable '%s'\" % (name))\n g_platform_variables[name] = {\"default\": op}", "def sdk_deconfigure(self, platform_name):\n\n if platform_name == 'androi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a blockformatted comment.
def format_block_comment(self, desc, length = 40): block_text = "" for ii in range(length): block_text += self.__comment block_text += "\n" ret = self.__comment if desc: ret += " " + desc + " " for ii in range(len(ret), length): ret += self.__comment return block_text + ret...
[ "def request_comment(block_id: int) -> str:\n if block_id not in [0, 1, 2]:\n raise ValueError(\"Invalid block_id.\")\n return f\"NMK{block_id + 1}\"", "def comment_block(block_string, comment=False):\n block = block_string.split('\\n')\n\n if comment:\n commented_block = ['#...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove local labels that would seem to generate .bss, make a fake .bss section.
def generate_fake_bss(self, assembler, und_symbols = None, elfling = None): bss = AssemblerSectionBss() for ii in self.__sections: while True: entry = ii.extract_bss(und_symbols) if not entry: break if not entry.is_und_symbol(): bss.add_element(entry) if elf...
[ "def fix_static_global_kernels(in_txt):\n in_txt = in_txt.replace(\" __global__ static\", \"__global__\")\n return in_txt", "def test_func_bss(self):\n cmd = \"deref $_bss()\"\n target = _target(\"bss\")\n self.assertFailIfInactiveSession(gdb_run_cmd(cmd, target=target))\n res = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove .rodata sections by merging them into the previous .text section.
def remove_rodata(self): text_section = None rodata_sections = [] ii = 0 while len(self.__sections) > ii: section = self.__sections[ii] if "text" == section.get_name(): text_section = section ii += 1 elif "rodata" == section.get_name(): if text_section: ...
[ "def cleanupHead(linedata):\n for i in range(5,-1,-1):\n del linedata[i]\n return linedata", "def cleanupTail(linedata):\n for i in range(0,3):\n del linedata[len(linedata)-1]\n return linedata", "def unmerge(self, section):\n if self == section:\n raise RuntimeExcept...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace constant with a replacement constant.
def replace_constant(self, src, dst): replace_count = 0 for ii in self.__sections: for jj in range(len(ii.content)): line = ii.content[jj] replaced = re.sub(r'(\$%s|\$%s)' % (src, hex(src)), r'$%s' % hex(dst), line) if line != replaced: ii.content[jj] = replaced ...
[ "def replace_constant(proof: Proof, constant: str, variable: str = 'zz') -> \\\n Proof:\n assert proof.is_valid()\n assert is_constant(constant)\n assert is_variable(variable)\n for assumption in proof.assumptions:\n assert constant not in assumption.templates\n assert variable not ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write an output assembler file or append to an existing file.
def write(self, op, assembler): if isinstance(op, str): fd = open(op, "w") for ii in self.__sections: ii.write(fd) fd.close() if is_verbose(): print("Wrote assembler source file '%s'." % (op)) else: prefix = assembler.format_block_comment("Program") op.write(p...
[ "def save_output_to_file(file_name, file_content, append_to_file=False):\n\n if append_to_file in (True, 'True'):\n mode = 'a'\n elif append_to_file in (False, 'False'):\n mode = 'w'\n else:\n raise Exception(\n 'Given append value unsupported! Supported values: True, False'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tell if this is an und symbol.
def is_und_symbol(self): return self.__und
[ "def isSymbolChar(c):\n return c.isalnum() or \\\n c in [\"+\",\"-\",\"*\",\"/\",\"@\",\"$\",\"%\",\"^\",\"&\",\n \"_\",\"\\\\\",\"<\",\">\",\"~\",\".\",\"=\",\":\"]", "def is_symbol(p):\n return len(p) == 1 and p.isalpha()", "def is_symbol(s):\n return isinstance(s, str) and ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Crunch popping before a jump.
def crunch_jump_pop(self, op): lst = self.want_line(r'\s*(jmp\s+%s)\s+.*' % (op)) if not lst: return ii = lst[0] jj = ii - 1 while True: if (0 > jj) or not re.match(r'\s*(pop\S).*', self.__content[jj], re.IGNORECASE): if is_verbose(): print("Erasing function footer befo...
[ "def pop_jump(cls):\n\t\treturn cls.jump_stack.pop()", "def fix_jump(self):\n pass", "def remove_trailing_jumps(bblock):\n last_jump = None\n for i in range(len(bblock.items) -1, -1, -1):\n if bblock.items[i].op in (\"goto\", \"if\"):\n last_jump = i\n else:\n br...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract a variable that should go to .bss section.
def extract_bss(self, und_symbols): # Test for relevant .globl element. found = self.extract_globl_object() if found: return AssemblerBssElement(found[0], found[1], und_symbols) found = self.extract_comm_object() if found: return AssemblerBssElement(found[0], found[1], und_symbols) s...
[ "def bss_param(self):\n return self._bss_param", "def bss_param(self, bss_param):\n self._bss_param = bss_param", "def global_val(self, var_num: int) -> ZWord:\n var_address = self._header.global_var_table_address + (var_num * 2)\n return ZWord(self._memory, var_address)", "def Var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge content with another section.
def merge_content(self, other): self.__content += other.__content
[ "def merge(self, section=None):\n if section is None:\n # for the high level interface\n if self._link is not None:\n self.link = self._link\n elif self._include is not None:\n self.include = self._include\n return\n\n for obj i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all .align declarations, replace with desired alignment.
def minimal_align(self): desired = int(PlatformVar("align")) for ii in range(len(self.__content)): line = self.__content[ii] match = re.match(r'.*\.align\s+(\d+).*', line) if match: align = int(match.group(1)) # Due to GNU AS compatibility modes, .align may mean different thing...
[ "def unaligned(self):\n new_alignment = Alignment()\n new_alignment.datatype = self.datatype\n for name, seq in self.items():\n new_seq = re.sub(_INDEL, '', str(seq))\n if new_seq != '':\n new_alignment[name] = new_seq\n return new_alignment", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces an entry point with given entry point name from this section, should it exist.
def replace_entry_point(self, op): lst = self.want_entry_point() if lst: self.__content[lst[0]] = "%s:\n" % op
[ "def set_entrypoint(e):\n config.set(\"app\", \"entrypoint\", e)", "def entrypoint(self, entrypoint):\n\n self._entrypoint = entrypoint", "def add_entrypoints(setupcfg: ConfigUpdater, opts: ScaffoldOpts):\n new_section_name = \"options.entry_points\"\n if new_section_name in setupcfg:\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }