query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Return a config template compatible with `self.get_dag`. | def get_config_template(self) -> cconfig.Config: | [
"def get_config_template(self):\n if self.config_template:\n return self.config_template\n if self.device_role.config_template:\n return self.device_role.config_template\n if self.platform and self.platform.config_template:\n return self.platform.config_template... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Methods supported by the DAG. | def methods(self) -> List[str]:
# TODO(*): Consider make this an abstractmethod.
return ["fit", "predict"] | [
"def _operation(self):\n raise NotImplementedError()",
"def get_operations(self):\n raise NotImplementedError(\n 'operation get_operations(...) not yet implemented')",
"def actions(self):\n raise NotImplementedError(\"actions not implemented\")",
"def getOperations(self):\n\t\trais... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of sequences generated after each sequence in the given list is extended by one move. | def extend_sequences(grid: Grid, sequences: List[Tuple[GridItem]]) -> List[Tuple[GridItem, GridItem]]:
new_sequences = []
for seq in sequences:
last_move = seq[-1]
next_moves = get_available_locations_after_knight_move(grid=grid, start_location=last_move)
valid_moves = [m for m in next_... | [
"def runs(L):\n last = None\n result = []\n # process the list one-at-a-time\n for x in L:\n # if there's a sequence in progress check if x goes at end\n if last is not None:\n # does x belong at end of current sequence?\n if last[-1]+1 == x:\n # yup, a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the tensor_map in convparam | def get_tensor_map(self):
return self.TENSOR_MAP | [
"def _get_tensor_strategy(dev_mat, tensor_map):\n tensor_strategy = []\n for dim in tensor_map:\n if dim == -1:\n tensor_strategy.append(1)\n else:\n tensor_strategy.append(dev_mat[-dim-1])\n return tensor_strategy",
"def get_conv_params(onnx_node): # type: (NodeWrapp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate use load2d or not | def get_load2d_flag(stride, pads, shape_filter_ncdhw):
l0a_load2d_flag = False
_, _, filter_d, filter_h, filter_w = shape_filter_ncdhw
if list(pads) == [0, 0, 0, 0, 0, 0] and list(stride) == [1, 1, 1] and \
[filter_d, filter_h, filter_w] == [1, 1, 1]:
l0a_load2d_flag = True
... | [
"def has_2D(self):\n\t\tif self.have_fastas is False:\n\t\t\tself._extract_fastas_from_fast5()\n\t\t\tself.have_fastas = True\n\n\t\tif self.fastas.get('twodirections') is not None:\n\t\t\treturn True\n\t\treturn False",
"def is_2d(self) -> bool:\n return self.layers == 1 and self.times == 1",
"def _calc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate whether to do cyclebuffer | def get_cyclebuffer_flag(tiling, shape_w, w_dtype, channel_c1, stride_d,
l0a_load2d_flag):
cyclebuffer_flag = False
filter_d = shape_w[1]
cyc_size = 0
if tiling["AL1_shape"]:
cyc_size = int(tiling["AL1_shape"][0] * tiling["AL1_shape"][-1] // \
(sha... | [
"def cycle(self):\n return self.start==self.end",
"def has_cycle_constant(link):\n # slow_pointer = link\n # fast_pointer = link\n # step = 0\n # while not fast_pointer.rest is Link.empty:\n # fast_pointer = fast_pointer.rest\n # if slow_pointer is fast_pointer:\n # ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to turn this intermediate slice into a simple slice. | def try_simple(self) -> TemplatedFileSlice:
# Yield anything simple
if len(self.slice_buffer) == 1:
return TemplatedFileSlice(
self.slice_buffer[0].slice_type,
self.source_slice,
self.templated_slice,
)
else:
rai... | [
"def _new_empty_slice(self) -> None:",
"def _explicit_slicing(cls, slicing, shape):\n explicit_slicing = ()\n for slc, maxstop in zip(slicing, shape):\n if not isinstance(slc, slice):\n explicit_slicing += (slc,)\n else:\n start, stop, step = slc.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Coalesce this whole slice into a single one. Brutally. | def coalesce(self) -> TemplatedFileSlice:
return TemplatedFileSlice(
PythonTemplater._coalesce_types(self.slice_buffer),
self.source_slice,
self.templated_slice,
) | [
"def _coalesce(*args):\n return next((a for a in args if a is not None), None)",
"def trim(self):\n for i in range(len(self)):\n if self[i] != TRIT_ZERO:\n return self.__class__(self[i:])\n return self.__class__([])",
"def _single_out(array):\r\n if len(array) < 1:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the templating context from the config. | def get_context(self, fname=None, config=None, **kw) -> Dict:
# TODO: The config loading should be done outside the templater code. Here
# is a silly place.
if config:
# This is now a nested section
loaded_context = (
config.get_section((self.templater_sel... | [
"def get_template(self, context, **kwargs):\r\n return self.template",
"def get_template_engine():\n return _current_template_engine",
"def get_config_template(self) -> cconfig.Config:",
"def template_path(self):\n return self.get_config(\"templates\")",
"def get_config_template(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process a string and return a TemplatedFile. Note that the arguments are enforced as keywords because Templaters can have differences in their `process` method signature. A Templater that only supports reading from a file | def process(
self, *, in_str: str, fname: str, config=None, formatter=None
) -> Tuple[Optional[TemplatedFile], list]:
live_context = self.get_context(fname=fname, config=config)
def render_func(raw_str: str) -> str:
"""Render the string using the captured live_context."""
... | [
"def process_tempita(fromfile, outfile=None):\n if outfile is None:\n # We're dealing with a distutils build here, write in-place\n outfile = os.path.splitext(fromfile)[0]\n\n from_filename = tempita.Template.from_filename\n template = from_filename(fromfile, encoding=sys.getdefaultencoding()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Identify a wrapped query (e.g. dbt test) and handle it. If unwrap_wrapped is true, we trim the wrapping from the templated file. If unwrap_wrapped is false, we add a slice at start and end. | def _check_for_wrapped(
cls,
slices: List[TemplatedFileSlice],
templated_str: str,
unwrap_wrapped: bool = True,
) -> Tuple[List[TemplatedFileSlice], str]:
if not slices:
# If there are no slices, return
return slices, templated_str
first_slice ... | [
"def view_unwrapping():\r\n pass",
"def seek_wrapped_response(response):\n if needs_seek_wrapper(response):\n wrapper_class = get_seek_wrapper_class(response)\n response = wrapper_class(response)\n assert hasattr(response, \"get_data\")\n return response",
"def __getitem__(self, wrappe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sort a dict of occurrences into a sorted list of tuples. | def _sorted_occurrence_tuples(
occurrences: Dict[str, List[int]]
) -> List[Tuple[str, int]]:
return sorted(
((raw, idx) for raw in occurrences.keys() for idx in occurrences[raw]),
# Sort first by position, then by lexical (for stability)
key=lambda x: (x[1], x[0])... | [
"def value_sorted(dic):\n l = [(num, key) for (key, num) in dic.items()]\n l.sort(reverse=True)\n l = [(key, num) for (num, key) in l]\n return l",
"def sorted_items(c: Counter) -> List[Tuple[AnyStr, int]]:\n return sorted(c.items(), key=itemgetter(1), reverse=True)",
"def convert_dict_to_tuple(d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Slice a templated python string into token tuples. | def _slice_template(cls, in_str: str) -> Iterator[RawFileSlice]:
fmt = Formatter()
in_idx = 0
for literal_text, field_name, format_spec, conversion in fmt.parse(in_str):
if literal_text:
escape_chars = cls._sorted_occurrence_tuples(
cls._substring_... | [
"def _splitTemplate(self, template):\r\n tmpl = template.replace(\"#\", \"@@@@\")\r\n # Regular expression that detects a substitution pattern.\r\n # There are two variants:\r\n # 1. A number of @ characters, followed by an optional index (@@@2)\r\n # 2. A full expression enclosed... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split a sliced file on its invariant literals. We prioritise the _longest_ invariants first as they are more likely to the the anchors. | def _split_invariants(
cls,
raw_sliced: List[RawFileSlice],
literals: List[str],
raw_occurrences: Dict[str, List[int]],
templated_occurrences: Dict[str, List[int]],
templated_str: str,
) -> Iterator[IntermediateFileSlice]:
# Calculate invariants
invari... | [
"def split_fasta(fname, parts):\n seqparser = SeqIO.parse(fname, 'fasta')\n # load length array\n lenf = fname + '_lens.npy'\n if os.path.exists(lenf):\n print(\"Loading entries lengths...\")\n lens = np.load(lenf)\n n = len(lens)\n else:\n print(\"Entries lengths array do... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter a dict of occurrences to just those within a slice. | def _filter_occurrences(
file_slice: slice, occurrences: Dict[str, List[int]]
) -> Dict[str, List[int]]:
filtered = {
key: [
pos
for pos in occurrences[key]
if pos >= file_slice.start and pos < file_slice.stop
]
for ... | [
"def _filter_dict(\n param_dict: TParameterization, subset_keys: List[str]\n) -> TParameterization:\n return {k: v for k, v in param_dict.items() if k in subset_keys}",
"def filter_dict(dict, filter=[]):\n return {key: dict[key] for key in filter}",
"def _filter_dict(src_dict, key_set):\n for k in s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Coalesce to the priority type. | def _coalesce_types(elems: List[RawFileSlice]) -> str:
# Make a set of types
types = {elem.slice_type for elem in elems}
# Replace block types with templated
for typ in list(types):
if typ.startswith("block_"): # pragma: no cover
types.remove(typ)
... | [
"def _set_priority(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=[RestrictedClassType(base_type=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), restriction_dict={'range': [u'0..7']}),RestrictedClassType(b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
seq_s should be the SPLIT_WORD numericalized LongTensor of the table header as prepared by torchtext. returns an encoding for each column. | def forward(self, seq_s):
# s = flat sequence length with split index specifying columns
# c = num columns
# e = generic embedding index
seq_se = self.embedding(seq_s)
ends = torch.nonzero(seq_s == self.split_idx).detach().cpu().numpy()
ends = ends.ravel()
begins ... | [
"def _seqs_to_train(self, seqs):\n X = []\n Y = []\n for seq in seqs:\n for token in seq:\n features = token.strip().split()\n X.append({i:xi for (i, xi) in enumerate(features[:-1]) } )#features \n Y.append(features[-1])#label\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
configures the tags for Browser. | def configureTags (self):
self.window.tag_config("a", foreground = "blue", underline=1)
## self.window.tag_bind('a', '<Button-1>')
self.window.tag_config('u', underline=1)
self.window.tag_config('center', justify = CENTER)
self.window.tag_config('right', justify = RIGHT) | [
"def config_tags(self):\n \n # Discover what 'basefont' currently in use\n curFontName = self.cget('font')\n curFont = tkFont.nametofont(curFontName)\n curFontSpecs = curFont.actual()\n basefont = ' '.join([ str(curFontSpecs[k]) for k in 'family size'.split() ])\n \n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if a given database field uses the specified requirement (IS_IN_SET, IS_INT_IN_RANGE, etc) | def uses_requirement(requirement, field):
if hasattr(field.requires, "other") or requirement in str(field.requires):
if hasattr(field.requires, "other"):
if requirement in str(field.requires.other):
return True
elif requirement in str(field.requires):
return ... | [
"def check_validity(self, field_name, value):",
"def is_one_of(field: str, value: list[Any]) -> Expression:\n return Expression(_criterion(field, \"inSet\", value))",
"def _check_valid_field(self, field):\n exists = False\n if field in self.resource.fields_dict:\n exists = True\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates the XML for bindings for the specified database field. | def generate_bindings(table, fieldname, ref):
field = table[fieldname]
if "IS_NOT_EMPTY" in str(field.requires):
required = "true()"
else:
required = "false()"
if field.type == "string":
_type = "string"
elif field.type == "double":
_type = "decimal"
# Collect d... | [
"def bind(self, field_name, parent):\n if field_name:\n self.source = field_name[:-len(self.field_name_suffix)]\n super(IdPrimaryKeyRelatedField, self).bind(field_name, parent)",
"def xml_field_close(cls, field):\n return \"</%s>\" % field",
"def _bind_to_schema(self, field_name,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates the controllers XML for the database table field. | def generate_controllers(table, fieldname, ref):
itext_list = [] # Internationalization
controllers_list = []
field = table[fieldname]
itext_list.append(TAG["text"](TAG["value"](field.label),
_id=ref + ":label"))
itext_list.append(TAG["text"](TAG["value"](field.co... | [
"def show_database_structure(self):\n self.analyze()\n items = []\n for model in get_models():\n names = []\n # for f, m in model._meta.get_fields_with_model():\n for f in model._meta.concrete_fields:\n names.append(f.name)\n items.appe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the data in the given node as a comma separated string | def csvdata(nodelist):
data = ""
for subnode in nodelist:
if (subnode.nodeType == subnode.ELEMENT_NODE):
try:
data = data + "," + subnode.childNodes[0].data
except:
data = data+ ","
return data[1:] + "\n" | [
"def node_to_string(*, node: InpFileNode) -> str:\n items = (node.node_id, node.x, node.y, node.z)\n return \", \".join(map(str, items)) + \"\\n\"",
"def data(self, node):\n self.writer.write_str(node.data)",
"def __str__(self):\n current_node = self.head\n list_string = \"[\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the XML to a CSV compatible with the import_from_csv_file of web2py | def importxml(db, xmlinput):
from io import StringIO
import xml.dom.minidom
try:
doc = xml.dom.minidom.parseString(xmlinput)
except:
raise Exception("XML parse error")
parent = doc.childNodes[0].tagName
csvout = csvheader(parent, doc.childNodes[0].childNodes)
for subnode i... | [
"def _xml_to_csv(self, xml_dir):\n\n # Parse XML data\n xml_list = []\n for xml_file in glob.glob(xml_dir + '/*.xml'):\n value = self._read_pascal_xml(xml_file)\n xml_list.extend(value)\n\n # Write data to CSV\n if len(xml_list) > 0:\n df = pd.Data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a list of Xforms based on database tables for ODK Collect | def formList():
# Test statements
#xml = TAG.forms(*[TAG.form(getName("Name"), _url = "http://" + request.env.http_host + URL(c="static", "current.xml"))])
#xml = TAG.forms(*[TAG.form(getName(t), _url = "http://" + request.env.http_host + URL(f="create", args=t)) for t in db.tables()])
# List of a cou... | [
"def show_database_structure(self):\n self.analyze()\n items = []\n for model in get_models():\n names = []\n # for f, m in model._meta.get_fields_with_model():\n for f in model._meta.concrete_fields:\n names.append(f.name)\n items.appe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows for submission of Xforms by ODK Collect | def submission():
# @ToDo: Something better than this crude check
if not auth.s3_logged_in():
auth.permission.fail()
from io import StringIO
import cgi
from lxml import etree
source = request.post_vars.get("xml_submission_file", None)
if isinstance(source, cgi.FieldStorage):
... | [
"def parse_extdirect_form_submit(request):\n params = request.params\n action = params.get('extAction')\n method = params.get('extMethod')\n tid = params.get('extTID')\n metadata = params.get('extMetadata')\n if metadata:\n metadata = json.loads(metadata)\n data = dict()\n for key in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change the state of the application and get the new interface (if given). Set up graphics for the new state if required. change_state(int, Menu/Game) > void | def change_state(self, state, interface=None):
self._state = state
if interface != None:
self._interface = interface
if self._state == config.GS_LOADING:
# Background with loading text
self._background = self._pygame.Surface(self... | [
"def set_game_state(new_state):\n global game_state\n game_state = new_state",
"def _switch_state(self):\n if self._app.is_active():\n self._app.deactivate_game()\n self._text.set('Start')\n else:\n try:\n self._app.activate_game()\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tokenizes the expression expr [str] The expression to tokenize | def tokenize_expr(self, expr: str) -> str:
# Output Variable
# For now, this is equivilent to expr
out = expr
for token in self.tokens.keys():
# Lets add a backslash between every character
# Of the token
token = [f"\{tok}" for tok in token]
... | [
"def tokenize(expr):\n lst = []\n for line in expr.splitlines():\n line = line.strip()\n if len(line) == 0:\n continue\n if line[0] == '*':\n continue # Skip comments\n line = line.replace(\"+\", \" + \")\n line = line.replace(\"-\", \" - \")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts infix algebra to prefix algebra. expr [str] The input expression | def infix_to_prefix(self, expr: str) -> str:
# Reverse expr
expr = reversed(expr)
# Convert expr to list
expr = list(expr)
# Reverse all parantheses
for i, e in enumerate(expr):
if e == "(":
expr[i] = ")"
elif e == ")":
... | [
"def prefix_to_infix(self, expr):\n p, r = self._prefix_to_infix(expr)\n if len(r) > 0:\n raise InvalidPrefixExpression(f\"Incorrect prefix expression \\\"{expr}\\\". \\\"{r}\\\" was not parsed.\")\n return f'({p})'",
"def trans_infix_prefix(expression):\n expression = expressio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts prefix math to a treelib tree. expr [str] The input expression This MUST be delimeted by some form of delimeter delimeter [str] = None This is the character that the infix algebra is delimeted by. None means whitespace name [str] = "base" The name of the root node of the tree | def prefix_to_tree(self, expr: str, delimeter: str = None, node_name: str = "base") -> Tree:
# Create a tree
tree = Tree()
# Convert the expression to a deque
expr_deque = deque(expr.split(delimeter))
# Create a base node
base_node = tree.create_node(node_name,0)
... | [
"def infix_to_tree(self, expr: str, delimeter: str = None, node_name: str = \"base\") -> Tree:\n\n # Convert expr to prefix\n prefix = self.infix_to_prefix(expr)\n\n # Return prefix_to_tree of this expr\n return self.prefix_to_tree(prefix, delimeter, node_name)",
"def expression_tree(p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts post math to a treelib tree. expr [str] The input expression This MUST be delimeted by some form of delimeter delimeter [str] = None This is the character that the infix algebra is delimeted by. None means whitespace name [str] = "base" The name of the root node of the tree | def infix_to_tree(self, expr: str, delimeter: str = None, node_name: str = "base") -> Tree:
# Convert expr to prefix
prefix = self.infix_to_prefix(expr)
# Return prefix_to_tree of this expr
return self.prefix_to_tree(prefix, delimeter, node_name) | [
"def expression_tree(postfix:str) -> Node:\n stack = deque()\n for ch in postfix:\n if ch not in {'+', '-', '*', '/', '^'}:\n stack.append(Node(ch))\n else:\n middle_node = Node(ch)\n right_node = stack.pop()\n left_node = stack.pop()\n midd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Optimizes a tree_list. tree_list [list[list[list]]] The input list | def optimize_tree_list(self, tree_list: list[list[list]], namespace: str = "base") -> list[list[list]]:
# First lets take all constant values and insert them into a dictionary
# For later reference
const_values: dict = {}
# For every expression
for expr in tree_list[0]:
... | [
"def improve_tree(tree, freq_dict):\n # todo",
"def make_tree(list, category):\n\t#takes in a list separated by + and - and puts it into a very left-heavy tree\n\ttree = list[0]\n\tlist.pop(0)\n\tfor i in range(0, len(list)):\n\t\tif list[i] in category:\n\t\t\tsubtree = list[i+1]\n\t\t\tif subtree.count('*') ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the expr to a result expr [str] Input expression namespace [str] The namespace to use for creating variables | def parse(self, expr: str, namespace: str = "base") -> ParseResult:
# Convert infix to tree
tree = self.infix_to_tree(expr)
# Convert tree to list
tree_list = self._tree_to_list(tree, tree[0], [[],[]], namespace)
if self.optimize:
# If we should optimize, do that n... | [
"def ev(expr):\n return eval(expr,user_ns())",
"def eval_expr(expr):\n return eval_(ast.parse(expr, mode=\"eval\").body)",
"def eval_expr(expr):\n return eval_(ast.parse(expr, mode='eval').body)",
"def xpath_eval(node,expr,namespaces=None):\r\n ctxt = common_doc.xpathNewContext() #@UndefinedVariab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for create_ban | def test_create_ban(self):
pass | [
"def test_get_ban(self):\n pass",
"def test_create_boat(self):\n pass",
"def test_update_ban(self):\n pass",
"def test_client_bank_account_create(self):\n pass",
"def test_create_bill(self):\n pass",
"def test_api_can_create_a_brigade(self):\n response = self.clie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for exclude_ip_ban | def test_exclude_ip_ban(self):
pass | [
"def validate_ip_not_banned(strategy, details, backend, user=None, *args, **kwargs):\n if not user or user.is_staff:\n return None\n \n ban = get_request_ip_ban(strategy.request)\n if ban:\n hydrated_ban = Ban(\n check_type=Ban.IP,\n user_message=ban['message'],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for expire_ban | def test_expire_ban(self):
pass | [
"def test_expired_ban(self):\n Ban.objects.create(banned_value='bo*',\n expires_on=timezone.now() - timedelta(days=7))\n\n self.assertIsNone(get_user_ban(self.user))\n self.assertFalse(self.user.ban_cache.is_banned)",
"def test_expired_ban(self):\n Ban.objects... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for get_ban | def test_get_ban(self):
pass | [
"def test_create_ban(self):\n pass",
"def test_get_bans(self):\n pass",
"def test_update_ban(self):\n pass",
"def test_get_boat(self):\n pass",
"def test_ban_ip(self):\n ban = ban_ip('127.0.0.1', 'User reason', 'Staff reason')\n self.assertEqual(ban.user_message, 'U... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for get_bans | def test_get_bans(self):
pass | [
"def test_get_ban(self):\n pass",
"async def bans(self, ctx):\n try:\n bans = await self.bot.get_bans(ctx.message.server)\n except discord.Forbidden:\n await self.bot.say('I do not have the proper permissions')\n except discord.HTTPException:\n await se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for update_ban | def test_update_ban(self):
pass | [
"def test_update_bill(self):\n pass",
"def test_get_ban(self):\n pass",
"def test_client_bank_account_update(self):\n pass",
"def test_create_ban(self):\n pass",
"def test_partial_update_bill(self):\n pass",
"def test_client_bank_account_partial_update(self):\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if image is rgb only accept rgb image when building train set | def is_RGB(self,img_path):
image=Image.open(img_path)
image=np.asarray(image)
if(len(image.shape)<3):
return False
return True | [
"def is_rgb(im):\n if(im.ndim == 3):\n return True\n else:\n return False",
"def is_rgb(im):\n return len(im.shape) == 3",
"def is_rgb(img: np.ndarray) -> bool:\n\n return len(img.shape) >= 1 and img.shape[-1] == 3",
"def check_isrgb(im):\n \n im_sze = im.shape\n \n if le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save resized image to destination path | def resize_image(self, filename, size=(299,299,3)):
path = join(self.source_dir, filename)
img = Image.open(path)
img = img.resize(size)
img.save(join(self.dest_dir, filename), 'JPEG', optimize=True) | [
"def resize_and_save(filename, output_dir, size=SIZE):\n image = Image.open(filename)\n # Use bilinear interpolation instead of the default \"nearest neighbor\" method\n image = image.resize((size, size), Image.BILINEAR)\n image.save(os.path.join(output_dir, filename.split('/')[-1]))",
"def resize_and... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the text regexp representation If `strict` is True, than in case of construction error is detected, an exception should be raised. Otherwise, the object is expected to return a string (but it is not expected to be a correct regex). | def get_regex(self, strict=True):
_ctx = construction.Context(strict=strict)
return self._get_regex(_ctx) | [
"def assertRegexp(self, text, regex, msg=None):\n for name in ['assertRegex', 'assertRegexpMatches']:\n if hasattr(self, name):\n return getattr(self, name)(text, regex, msg)\n self.assertTrue(False, \"No method to check assertRegexp\")",
"def translate(self, txt, strict=Fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return compiled regex object. | def get_compiled(self, flags=0):
return re.compile(self.get_regex(), flags) | [
"def lazy_re_compile(\n regex: AnyStr,\n flags: int = 0,\n) -> re.Pattern:\n\n return cast(re.Pattern, SimpleLazyObject(lambda: re.compile(regex, flags)))",
"def build_compiled_pattern(self) -> Pattern:\n return re.compile(self.build_pattern(), re.VERBOSE)",
"def regex(self):\n\t\tregexpr = get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Escape given text string. | def escape(self, text, escape_chars):
_bs = "\\"
# backslash is always escaped
text = text.replace(_bs, _bs * 2)
for _el in escape_chars:
assert _el != _bs, "Backslash has been already escaped"
text = text.replace(_el, _bs + _el)
return text | [
"def _escape_text(text):\n if isinstance(text, str):\n text = cgi.escape(text.translate(__trans, __todel))\n elif isinstance(text, unicode):\n text = cgi.escape(text.translate(__uni_trans))\n return text",
"def HtmlEscape(text):\n return escape(text, _HTML_ESCAPE_TABLE)",
"def _escape(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Usual epsilon greedy strategy except that we no longer explore when at the critical states | def epsilon_greedy(Q, epsilon, state):
random_number = random.random()
if (random_number < epsilon) and (state not in critical_states):
return env.action_space.sample()
else:
return np.argmax(Q[state]) | [
"def _epsilon_greedy(self, info_state, legal_actions, epsilon):\n probs = np.zeros(self._num_actions)\n if np.random.rand() < epsilon:\n action = np.random.choice(legal_actions)\n probs[legal_actions] = 1.0 / len(legal_actions)\n else:\n info_state = np.reshape(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the checksum of a list of bytes and appends it | def addChecksum(bytes_list):
checksum = 0
for elem in bytes_list:
checksum += elem
checksum = int(checksum % 256)
return bytes_list.append(checksum) | [
"def checksum(self, bytes) -> int :\n return ((sum(bytes) & 0xff) ^ 0xff) + 1",
"def checksums(values):\n return [checksum(x) for x in values]",
"def checksum_byte_calculator(hex_values):\n hex_values = bytearray.fromhex(hex_values)\n addition = 0\n checksum = ''\n for i in range(2,17):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts an unsigned integer into an array of 4 bytes, in a bigendian fashion. Used to send the number of µsteps to the servos. | def convToBytes(integer):
_bytes = [0, 0, 0, 0]
_bytes[0] = integer / (256**3)
integer = integer % (256**3)
_bytes[1] = integer / (256**2)
integer = integer % (256**2)
_bytes[2] = integer / 256
integer = integer % 256
_bytes[3] = integer
return _bytes | [
"def bytearray_from_integer(integer):\n bytemax = 256\n return [\n format(integer // bytemax**i % bytemax, '02X')\n for i in range(3,-1,-1)\n ]",
"def uint32_to_bytes(value):\n return struct.pack(\"I\", value)",
"def encodeFourByteInt(self, numberToEncode):\n fourByteInt = b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns string equivalent metric tensor for arbitrary signature (n+1,1). | def arbitrary_metric_conformal(n):
str1 = ','.join(n*[n*'# '+'0 0'])
return ','.join([str1, n*'0 '+'1 0', n*'0 '+'0 -1']) | [
"def metric_tensor():\n return tnp.asarray([-1.0, -1.0, -1.0, 1.0], dtype=tnp.float64)",
"def gguf_get_tensor_name(ctx: ffi.CData, i: int) -> ffi.CData:\n ...",
"def T(metric_name):\n return \"%s_total\" % M(metric_name)",
"def get_tensor_name(t):\n return t.name.split(':')[0]",
"def node_to_ten... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialization of multivector X. Inputs are as follows mvtype base result default default Zero multivector 'basisvector' int i ith basis vector 'basisbivector' int i ith basis bivector 'scalar' x scalar of value x 's' 'grade' [A] X.grade(i) = A 's,i' 'vector' [A] X.grade(1) = [A] 's' 'grade2' or 'bivector' [A] X.grade(... | def __init__(self, base=None, mvtype=None, fct=False, blade_rep=False):
def make_scalar(self, base): # make a scalar (grade 0)
if isinstance(base, str):
if self.fct:
self.obj = Function(base)(*MV.coords) * MV.ONE
else:
self.ob... | [
"def parse_multivector(self, mv_string: str) -> 'MultiVector':\n # Get the names of the canonical blades\n blade_name_index_map = {name: index for index, name in enumerate(self.names)}\n\n # Clean up the input string a bit\n cleaned_string = re.sub('[()]', '', mv_string)\n\n # Cre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
blst is a list of integers [i_{1},...,i_{r}] representing the geometric product of r basis vectors a_{{i_1}}...a_{{i_r}}. reduce_basis_loop searches along the list [i_{1},...,i_{r}] untill it finds i_{j} == i_{j+1} and in this case contracts the list, or if i_{j} > i_{j+1} it revises the list (~i_{j} means remove i_{j}... | def reduce_basis_loop(blst):
nblst = len(blst) # number of basis vectors
if nblst <= 1:
return True # a scalar or vector is already reduced
jstep = 1
while jstep < nblst:
istep = jstep - 1
if blst[istep] == blst[jstep]: # basis vectorindex is repeat... | [
"def reduce_basis(blst):\n if blst == []: # blst represents scalar\n blst_coef = [S.One]\n blst_expand = [[]]\n return blst_coef, blst_expand\n blst_expand = [blst]\n blst_coef = [S.One]\n blst_flg = [False]\n # reduce untill all blst revise flgs ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Repetitively applies reduce_basis_loop to blst product representation until normal form is realized. | def reduce_basis(blst):
if blst == []: # blst represents scalar
blst_coef = [S.One]
blst_expand = [[]]
return blst_coef, blst_expand
blst_expand = [blst]
blst_coef = [S.One]
blst_flg = [False]
# reduce untill all blst revise flgs are True
... | [
"def reduce_basis_loop(blst):\n nblst = len(blst) # number of basis vectors\n if nblst <= 1:\n return True # a scalar or vector is already reduced\n jstep = 1\n while jstep < nblst:\n istep = jstep - 1\n if blst[istep] == blst[jstep]: # basis vectorind... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
basic_geometric_product assumes that mv1 and mv2 are both mulitvectors, not scalars and both are in the base and not the blade representation. No multivector flags are checked. This function is used to construct the blades from the bases. | def basic_geometric_product(obj1, obj2):
def mul_table(b1, b2):
return MV.base_mul_table[(b1, b2)]
obj12 = bilinear_product(obj1 * obj2, mul_table)
return obj12 | [
"def geometric_product(b1, b2):\n if MV.is_orthogonal:\n return MV.product_orthogonal_blades(b1, b2)\n else:\n result = MV.base_mul_table[(b1, b2)]\n return result",
"def product(m1, m2, *, algebra):\r\n if algebra.generic:\r\n return product_generic(m1, m2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
geometric_product(b1, b2) calculates the geometric product of the multivectors b1 and b2 (b1b2). | def geometric_product(b1, b2):
if MV.is_orthogonal:
return MV.product_orthogonal_blades(b1, b2)
else:
result = MV.base_mul_table[(b1, b2)]
return result | [
"def basic_geometric_product(obj1, obj2):\n def mul_table(b1, b2):\n return MV.base_mul_table[(b1, b2)]\n\n obj12 = bilinear_product(obj1 * obj2, mul_table)\n\n return obj12",
"def product(m1, m2, *, algebra):\r\n if algebra.generic:\r\n return product_generic(m1, m2, alg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
basic_add assummes that mv1 and mv2 are multivectors both in the base or blade representation. It sets no flags for the output and forms mv1.obj+mv2.obj. It is used to form the base expansion of the blades. | def basic_add(mv1, mv2):
obj = expand(mv1.obj + mv2.obj)
return MV(obj) | [
"def __add__(self, other):\n return add_mps(self, other)",
"def __add__(self, other):\n if type(other) == type(self):\n clone = Vector2(*self)\n clone[0] += other[0]\n clone[1] += other[1]\n \n return clone\n \n elif type(other) == Rect:\n clone = Re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
basic_sub assummes that mv1 and mv2 are multivectors both in the base or blade representation. It sets no flags for the output and forms mv1.objmv2.obj. It is used to form the base expansion of the blades. | def basic_sub(mv1, mv2):
obj = expand(mv1.obj - mv2.obj)
return MV(obj) | [
"def __sub__(self, other):\n if type(other) == type(self):\n clone = Vector2(*self)\n clone[0] -= other[0]\n clone[1] -= other[1]\n \n return clone\n \n elif type(other) == Rect:\n clone = Rect(other)\n clone.left -= self[0]\n clone.top -= sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MV.setup() creates all the arrays and dictionaries required to construct, multiply, add, and differentiate multivectors in linear and curvilinear coordinate systems. The inputs to MV.setup() are as follows | def setup(basis, metric=None, coords=None, rframe=False, debug=False, curv=(None, None)):
MV.print_blades = False
MV.connection = False
MV.ONE = ONE_NC
MV.basis_vectors = Vector.setup(basis, metric=metric, coords=coords, curv=curv, debug=debug)
MV.curv_norm = curv[1]
MV... | [
"def _setup_world(self):\n if \"varying_mass\" in self._hyperparams:\n self.create_xml()\n\n pdb.set_trace()\n\n self._model= mujoco_py.MjModel(self._hyperparams['filename'])\n self.model_nomarkers = mujoco_py.MjModel(self._hyperparams['filename_nomarkers'])\n\n gofast ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn on the galgebraaware string printer. This function is intended for interactive use only. Use | def ga_print_on():
GA_Printer._on()
return | [
"def _init_python_printing(stringify_func):\n import __builtin__, sys\n\n def _displayhook(arg):\n \"\"\"Python's pretty-printer display hook.\n\n This function was adapted from:\n\n http://www.python.org/dev/peps/pep-0217/\n\n \"\"\"\n if arg is not None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn off the galgebraaware string printer. This function is intended for interactive use only. See ga_print_on for the noninteractive technique. | def ga_print_off():
GA_Printer._off()
return | [
"def disable():\n builtins.print = print_orig",
"def SetDumpStringOff(self):\n errors = self._SetDumpStringOff(self.id,0)\n if errors != 0:\n self._RaiseStringError(errors)",
"def off() -> None:\n __display.off()",
"def off(self):\n self.log.debug(\"Turning Off GI String\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Walk through subscribers and call each | def notify(self) -> None:
for s in self.subscribers:
s() | [
"def call_subscribers(self, *args, **kwargs) -> None:\n for subscriber in self.get_subscribers():\n subscriber(*args, **kwargs)",
"def subscribers(self) -> Iterator[Any]:\n yield from self.get_subscribers()",
"def _notify_all(self, event_data):\n for subs in self._subscribers:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for user registration if the username field is left blank. | def test_registeration_no_username(self):
response = self.signup_a_user(self.user_lacks_username)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn("token", response.data) | [
"def test_null_username_field(self):\n nullusernameresult = self.new_user.register_user(\"\", \"kaguna@gmail.com\", \"password\", \"password\")\n self.assertEqual(\"check_username_pattern\", nullusernameresult, \"Please fill the Username field.\")",
"def test_register_empty_user_name(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for user registration if the email field is left blank. | def test_registeration_no_email(self):
response = self.signup_a_user(self.user_lacks_email)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["errors"]["email"],
["This field may not be blank."]
)
... | [
"def test_null_email_field(self):\n nullemailresult = self.new_user.register_user(\"kaguna\", \"\", \"password\", \"password\")\n self.assertEqual(\"check_null_fields\", nullemailresult, \"Please fill the Email field.\")",
"def available(form, field):\n # Ensure no other registered users have tha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for user registration if the password field is left blank. | def test_registeration_no_password(self):
response = self.signup_a_user(self.user_lacks_password)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["errors"]["password"],
["This field may not be blank."]
... | [
"def test_blank_password(self):\n rv = self.signup('Bo', 'Theo', 'Bo_theo5@example.com', '', 'Bo1995')\n self.assertIn(b'This field is required.', rv.data)",
"def test_password_none(self):\n self.assertEqual(self.user.password, None)",
"def test_login_emptypassword(self):\n emptypass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for user registration if the username given email is invalid. | def test_registeration_invalid_email(self):
response = self.signup_a_user(self.user_invalid_email)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data["errors"]["email"],
["Enter a valid email address."]
... | [
"def test_registeration_no_email(self):\n response = self.signup_a_user(self.user_lacks_email)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(response.data[\"errors\"][\"email\"],\n [\"This field may not be blank.\"]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for user registration if a short password is given. | def test_registeration_short_password(self):
response = self.signup_a_user(self.user_short_password)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertNotIn("token", response.data) | [
"def test_prohibit_with_short_password(self):\n data = {\n 'email': 'testusersignup1@cultidate.com',\n 'username': 'testusersignup',\n 'password': '1',\n 'first_name': 'name',\n 'last_name': 'surname',\n 'bio': 'MyBio',\n 'city': 'I... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for user registration if the username entered already exists. | def test_registeration_duplicate_username(self):
self.signup_a_user(self.user_data)
response_duplicate = self.signup_a_user(
self.user_data_duplicate_username)
self.assertEqual(response_duplicate.status_code,
status.HTTP_400_BAD_REQUEST)
self.assertEq... | [
"def username_available(self):\n if User.objects.filter(username=self.cleaned_data['profile_username_both']).exists():\n raise forms.ValidationError(self.error_messages['unavailable_username'], code='unavailable_username')",
"def username_taken(self, username: str) -> bool:\n\n if usernam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if user email can be successfull verified | def test_successful_email_verification(self):
self.signup_a_user(self.user_data)
time = datetime.now() + timedelta(hours=24)
token = jwt.encode({
"email": self.user_data['user']['email'],
"username": self.user_data['user']['username'],
"exp": int(time.strftime... | [
"def test_email_resent_verification_email(self):\n user = UserFactory(is_active=False)\n self.assertEmailCount('Ativa a tua conta', 1)\n\n url = reverse('resend-verification')\n data = {'email': user.email}\n \n response = self.client.post(url, data)\n self.assertEma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if superuser lacks password during registration | def test_registeration_for_a_super_user_no_password(self):
with self.assertRaisesMessage(TypeError,
'Superusers must have a password.'):
User.objects.create_superuser(
'jey',
'jey@gmail.com',
None
) | [
"def test_registeration_no_password(self):\n response = self.signup_a_user(self.user_lacks_password)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(response.data[\"errors\"][\"password\"],\n [\"This field may not be blank.\"]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the NFL.com XML schedule URL. `year` should be an integer, `stype` should be one of the strings `PRE`, `REG` or `POST`, and `gsis_week` should be a value in the range `[0, 17]`. | def schedule_url(year, stype, week):
xmlurl = 'http://www.nfl.com/ajax/scorestrip?'
if stype == 'POST':
week += 17
if week == 21: # NFL.com you so silly
week += 1
return '%sseason=%s&seasonType=%s&week=%s' % (xmlurl, year, stype, week) | [
"def build_url(self, week, year, rules):\n return self.url_base + '&yr=' + str(year) + '&wk=' + str(week) + '&rules=' + str(rules)",
"def _create_url(self, year):\n return ROSTER_URL % (self._team.upper(), year)",
"def nflweek(self, irc, msg, args, optlist, optweek):\n \n url = self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of dictionaries with information about each game in the week specified. The games are ordered by gsis_id. `year` should be an integer, `stype` should be one of the strings `PRE`, `REG` or `POST`, and `gsis_week` should be a value in the range `[1, 17]`. | def week_schedule(year, stype, week):
url = schedule_url(year, stype, week)
try:
dom = xml.parse(urllib.request.urlopen(url))
except urllib.error.HTTPError:
print >> sys.stderr, 'Could not load %s' % url
return []
games = []
for g in dom.getElementsByTagName("g"):
gs... | [
"def get_games_by_week(self, week=None):\n games = []\n if not week:\n week = self.upcoming_week\n for game in self.schedule:\n if game['week'] == week:\n games.append(game)\n\n return games",
"def get_games_by_week(self, week=None):\n games ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the schedule for the given week in place. `year` should be an integer year, `stype` should be one of the strings `PRE`, `REG` or `POST`, and `week` should be an integer in the range `[1, 17]`. | def update_week(sched, year, stype, week):
games = week_schedule(year, stype, week)
if not games:
return False
for game in games:
sched[game['eid']] = game
return True | [
"def schedule_url(year, stype, week):\n xmlurl = 'http://www.nfl.com/ajax/scorestrip?'\n if stype == 'POST':\n week += 17\n if week == 21: # NFL.com you so silly\n week += 1\n return '%sseason=%s&seasonType=%s&week=%s' % (xmlurl, year, stype, week)",
"def do_upw(self, arg):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
IFieldWidget factory for MonthYearWidget. | def MonthYearFieldWidget(field, request):
return z3c.form.widget.FieldWidget(field, MonthYearWidget(request)) | [
"def MonthYearFieldWidget(field, request):\n return FieldWidget(field, MonthYearWidget(request))",
"def YearFieldWidget(field, request):\n return FieldWidget(field, YearWidget(request))",
"def get_month_year_form(answer, answer_store, metadata, error_messages, group_instance=0):\n class MonthYearDateFo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the concept recursively by building the dependencies in a DFS. | def ParseConcept(self, parsed_args):
def _ParseConcept(node):
"""Recursive parsing."""
if not node.is_group:
fallthroughs = []
if node.arg_name:
fallthroughs.append(deps_lib.ArgFallthrough(node.arg_name))
fallthroughs += node.fallthroughs
return node.concept.Pa... | [
"def find_dependencies(root):\n \n symbol_table = create_symbol_table(root)\n\n names = []\n #Set the depth of the root node\n set_depth(root, 0)\n #Stack of nodes to visit\n stack = Stack(root)\n \n #List of (src, dest) of dependencies\n dependency_table = DTable(symbol_table=symbol_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the marshalled dependencies or None if not marshalled. | def marshalled_dependencies(self):
return self._marshalled_dependencies | [
"def get_dependencies(self):\n return self.dependencies",
"def _get_serialized_dependencies() -> list[dict]:\n ge_execution_environment = GXExecutionEnvironment()\n dependencies: list[PackageInfo] = ge_execution_environment.dependencies\n\n schema = PackageInfoSchema()\n\n seria... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds the dependency tree from the attribute. | def FromAttribute(cls, attribute):
kwargs = {
'concept': attribute.concept,
}
marshal = attribute.concept.Marshal()
if marshal:
attributes = [concept.Attribute() for concept in marshal]
elif not isinstance(attribute, base.Attribute):
attributes = attribute.attributes
else:
... | [
"def __generate_dependency_tree(self):\n dependency_dict = {}\n for s in self.manifest.sections():\n if s != \"config\":\n if self.manifest.has_option(s, 'depends'):\n dependency_list = [d.strip() for d in re.split('\\n|,', self.manifest.get(s, 'depends'))]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce a graph from a graph specification string | def make_graph_from_spec(graphtype, args):
parsed = parse_graph_argument(graphtype, args)
assert parsed['graphtype'] == graphtype
return obtain_graph(parsed) | [
"def from_string(data, format):\n # Using ConjunctiveGraph instead of Graph for nquads support.\n graph = rdflib.ConjunctiveGraph()\n graph.parse(data=data, format=format)\n return graph",
"def from_string(factory, str_graph):\n\n builder = Builder(factory)\n node_sequences = [s.split('->') for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an Argparse action for the appropriate graph type | def _make_graph_action(graphtype):
class X(ObtainGraphAction):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super(ObtainSimpleGraph, self).__init__(option_strings, dest,
... | [
"def build_parser(self, parser: ArgumentParser) -> None:",
"def parseacttype(self, buf, size):\n typeparse = self.proto.epp_single_type\n typeparse.restype = ActionType\n typeparse.argtypes = [ct.c_char_p, ct.c_uint]\n\n return typeparse(buf, size)",
"def to_action(self, node):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
. sdssArchie populates a directory with links to raw images from the SDSS mission. These images are all in FITS format and suitable for reprojection, moaicking, etc. | def sdssDownload(band, location, size, path):
debug = 0
# Build the URL to get image metadata
url = "http://montage.ipac.caltech.edu/cgi-bin/ArchiveList/nph-archivelist?survey=SDSSDR7+" \
+ urllib.parse.quote_plus(band) \
+ "&location=" \
+ urllib.parse.quote_plus(locatio... | [
"def make_star_thumbnails():\n os.chdir(unicorn.GRISM_HOME+'ANALYSIS/SURVEY_PAPER')\n \n ######### Make full COSMOS catalog \n file=unicorn.GRISM_HOME+'COSMOS/PREP_FLT/COSMOS-F140W_drz.fits'\n ROOT_GRISM = os.path.basename(file).split('_drz.fits')[0]\n se = threedhst.sex.SExtractor()\n se.aX... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find living area(businesscluster)/user_group(user_cluster) from user[review]business pattern use pyspark.mlib.fpm.FPGrowth ? | def livingAreaFromPattern(business_list):
print("livingAreaFromUser")
dataset_path = "../dataset/yelp_dataset_challenge_academic_dataset/"
review_path = dataset_path + "yelp_academic_dataset_review.json"
# make empty user list for each business
business_user_list = {} # mine user set from business... | [
"def filteringForNetworkBusiness():\n spark = SparkSession.builder.getOrCreate();\n\n # ------------------------------------- FILTERING ELITE USER OF 2017 ------------------------------------------\n file_elite_users = os.listdir(\"../yelp_dataset/elite_users_with_friends.json\")\n\n pyspark_df_elite_us... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dpy test open.core.betterself.tests.views.test_supplement_log_views.TestSupplementLogViews.test_display_name_on_log_serializer_some_hours_ago keepdb | def test_display_name_on_log_serializer_some_hours_ago(self):
supplement = SupplementFactory(user=self.user_1)
utc_now = get_utc_now()
# if you adjust it this way, it should result in about 4.5 hours ago
time = get_time_relative_units_ago(utc_now, hours=5.0)
time = get_time_rela... | [
"def test_log_entry(self):\n yesterday = datetime.now() - timedelta(days=1)\n details = {'msg':'my test log entry'}\n log_db_entry('test_task1', 'ACTION', details,\n yesterday)\n try:\n log1 = LogHistory.objects.get(\n logger='test_task1', st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dpy test open.core.betterself.tests.views.test_supplement_log_views.TestSupplementLogViews.test_create_supplement_log_with_supplement_stack keepdb | def test_create_supplement_log_with_supplement_stack(self):
# a hidden feature, not really restful, but allow a user to send a supplement_stack_uuid
# to create a set of supplements taken at the same time
supplements = SupplementFactory.create_batch(3, user=self.user_1)
stack = Suppleme... | [
"def test_provider_project_development_log_list(self):\n pass",
"def test_log_entry(self):\n yesterday = datetime.now() - timedelta(days=1)\n details = {'msg':'my test log entry'}\n log_db_entry('test_task1', 'ACTION', details,\n yesterday)\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method is for starting all worker threads. We are using three workers right now . 1. One for fetching latest instances info and adds to Queue 2. One for fetching from Queue and updating Redis 3. For updating the aggregator app , about this applications info. All are deamon threads. | def init_workers():
party_queue = Queue()
p = Producer(party_queue)
p.daemon = True
c = Consumer(party_queue)
c.deamon= True
m = MasterUpdater(db,application_name)
m.deamon = True
p.start()
c.start()
m.start() | [
"def setup_worker_threads(self):\n \n for thread_number in range(0, self.max_workers):\n worker = DeviceWorker(self, thread_number)\n self.worker_threads.append(worker)\n worker.start()",
"def work(self):\n max_procs = self.max_procs - self.num_connected_workers()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This endpoint is for adding threads to the application. Loadbalancer decids to go for which instances and based on that thread is added to it. | def addthread():
instance_id = os.getenv("CF_INSTANCE_INDEX")
print 'Instance Id ****************%s'%instance_id
thread_count = int(db.hget(application_name,instance_id))
thread_count+=1
print 'Threadcount ****************%s'%thread_count
result = db.hset(application_name,str(instance_id),str(th... | [
"def _addThread(self, *args, **kwargs):\n t = threading.Thread(*args, **kwargs)\n self.threads.append(t)\n t.start()\n return t",
"def create_thread(self):\n thread = super(ForumsTasks, self).create_thread(self.random_topic_id(), name='forums:create_thread')\n ForumsTasks._thread_ids.app... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This endpoint is for deleting threads to the application. Loadbalancer decids to go for which instances and based on that thread is deleted from it. | def deletethread():
instance_id = os.getenv("CF_INSTANCE_INDEX")
print 'Instance Id **************%s'%instance_id
thread_count = int(db.hget(application_name,instance_id))
thread_count-=1
db.hset(application_name,instance_id,thread_count)
return json.dumps({'message':'success'}) | [
"def delete(self, request, *args, **kwargs):\n thread = self.get_thread()\n if not thread:\n raise NotFound(code=status.HTTP_404_NOT_FOUND)\n\n thread.userthread_set.filter(user=request.user).update(deleted=True)\n return Response(status=status.HTTP_200_OK)",
"def delete_thr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a proper filename for the given location If the given location points to directories, the returned location will contain only the filename | def create_file_location(loc: str) -> str:
slash = "/"
reverse_data = loc[-4:] # "/" will not be in the type of the file already in reverse_data
reverse_data_ind = -4
while slash not in reverse_data:
reverse_data_ind -= 1
reverse_data = loc[reverse_data_ind:]
... | [
"def create_path(parent, file_name):\n result = ''\n file_name = file_name.lstrip('/')\n\n if os.path.exists(parent):\n if os.path.isfile(parent):\n parent = os.path.dirname(parent)\n\n result = os.path.normpath(os.path.join(parent, file_name))\n\n return result",
"def get_wls... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split the remote URI and filename | def get_remote_uri_and_filename(uri_to_filename: str) -> tuple:
wrld_wide_web = "www"
slashstr = "/"
begin_uri_ind = uri_to_filename.find(wrld_wide_web)
end_uri_ind = uri_to_filename[begin_uri_ind:].find(slashstr) + begin_uri_ind
if begin_uri_ind == -1:
end_uri_ind ... | [
"def parse_url(self, url):\n url = url.replace(self._url, '')\n url = url.strip('/').lower()\n url = url.split('/')\n id = '-'.join(url[:-1])\n filename = url[-1]\n return id, filename",
"def split_server_request_url(url):\n url_parts = list(urllib.parse.urlparse(url))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receive header from the server Since bytes get received in chunks from the server, a part of the body can be fetched while retrieving the header if the HTTP command is a GET. Returns tuple Returns the data gotten from the server in bytes in a tuple with the header and the beginning part of the body, respectively | def recv_header(self) -> tuple:
print("[RECV] receiving header data...")
raw_data = b''
double_new_line = "\r\n\r\n"
raw_double_new_line = double_new_line.encode(HttpClient.FORMAT)
end_header_ind = raw_data.find(raw_double_new_line)
while end_header_ind == -1:
... | [
"def read_http_header(sock):\n buf = []\n hdr_end = '\\r\\n\\r\\n'\n\n while True:\n buf.append(sock.recv(bufsize).decode('utf-8'))\n data = ''.join(buf)\n i = data.find(hdr_end)\n if i == -1:\n continue\n return data[:i], data[i + len(hdr_end):]",
"def _read... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search the given data for image references to get from the server and update file locations in the data This function searches image references, creates image HTTP commands and sends and receives them as well as write the gotten images to .png files and update their locations in the given data string. | def update_images(self, data: str) -> str:
soup = BeautifulSoup(data, 'html.parser')
images = soup.find_all('img')
imgs_fetched = 0
added_slash = False
for img in images:
img_src = [img['src']]
try:
img_lowsrc = img['lowsrc']
... | [
"def imageUpload(in_data):\n servCode, errMsg = validate_image(in_data)\n if errMsg:\n logging.error(errMsg)\n statusCode = servCode\n return {\"error\": errMsg}, statusCode\n log_data = {\n \"user\": in_data[\"user\"],\n \"client\": in_data[\"client\"],\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the given data in bytes to the file specified by the given location | def write_to_binary_file(self, loc: str, data: bytes):
try:
os.mkdir("../" + self.uri)
except FileExistsError:
pass
f = open("../" + self.uri + loc, "wb")
f.write(data)
print("[WRITE] written to binary file loc")
f.close() | [
"def write_to_file(data, filename, location=None):\n if location:\n filename = normpath(\"%s/%s\" % (location, filename))\n\n f = open(filename, \"w\")\n if type(data) == str():\n f.write(data)\n else:\n f.writelines(data)\n f.close()",
"def write_file(data, file_path):\n wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
just return the data field without validation or cleaning | def clean_data(self):
return self.instance.data | [
"def clean(self):\n cleaned_data = super().clean()\n cleaned_data = {key: field for key, field in cleaned_data.items()\n if field is not None}\n return cleaned_data",
"def _cleaned_data(self):\n try:\n return self.cleaned_data\n except AttributeEr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload a batch of bulk SMS messages for the given batch. Delete the temp file after we're done. Assumes the file is valid (run is_file_valid on it first!) | def upload_bulk_sms_file(batch_id, file_path):
batch = Batch.objects.get(id=batch_id)
batch.add_messages(read_messages_from_file(file_path))
batch.status = Batch.PENDING
batch.save() | [
"def upload_chunks_to_aws(small_file_list):\n counter = 0\n for small_filename in small_file_list:\n with open(small_filename) as handle:\n # build the request\n response = requests.put(aws_bulk_load_url, headers=headers, data=handle.read())\n print(\"AWS Bulk Upload Re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator that yields (phone_number, message_text, from_shortcode) tuples for the phone numbers that we need to send this reminder to. | def get_phone_numbers_to_send_to(self):
# Get the phone numbers we want to send to, excluding those that have
# already done the thing we want to remind them of
phone_numbers = self.PhoneModel.objects.exclude(phone_number__in=self.to_exclude())\
.va... | [
"def phone_number():\n\n while True:\n yield \"\".join(str(random.randint(0, 9)) for _ in range(11))",
"def phones(utt):\n for word in utt['words']:\n pos = word['start']\n for phone in word['phones']:\n start = pos\n end = pos + phone['duration']\n pos ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return list of phone numbers to exclude | def to_exclude(self):
midnight = now().replace(hour=0, minute=0, microsecond=0)
return CenterOpen.objects.filter(
creation_date__gte=midnight,
).values_list('phone_number', flat=True) | [
"def to_exclude(self):\n reporting_period = self.message_number - 3\n one_day_ago = now() - datetime.timedelta(hours=24)\n\n return PollingReport.objects.filter(\n period_number=reporting_period,\n creation_date__gte=one_day_ago,\n ).values_list('phone_number', flat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return list of phone numbers to exclude | def to_exclude(self):
reporting_period = self.message_number - 3
one_day_ago = now() - datetime.timedelta(hours=24)
return PollingReport.objects.filter(
period_number=reporting_period,
creation_date__gte=one_day_ago,
).values_list('phone_number', flat=True) | [
"def to_exclude(self):\n midnight = now().replace(hour=0, minute=0, microsecond=0)\n return CenterOpen.objects.filter(\n creation_date__gte=midnight,\n ).values_list('phone_number', flat=True)",
"def get_phone_numbers(r):\n phone_match = re.findall(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks for the existence of index.json in our container this should contain a list of the known environments | def load_footprints(self):
# container = self.cf.get_container(self.container_name)
try:
index = self.container.get_object("index.json")
except pyrax.exceptions.NoSuchObject, e:
logging.warning(e.message)
index = None
return False
... | [
"def test_environment_json():\n for l in list(environments.data):\n e = environments[l]\n assert len(json.dumps(e.json())) > 0",
"def _test_env_data(self):\n\n client = get_api_client()\n\n LOG.info(\"Checking presence of accounts and subnets in created environments\")\n\n pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stops a footprint. Doesn't save beforehand... | def stop_footprint(self, fpname):
logging.debug("%s entered" % __name__)
fp = self.get_footprint(fpname, start=False)
if fp.footprint_status == 'locked':
notify("Footprint is locked. use 'vcauto unlock %s' to unlock" % fpname)
return False
fp.stop() | [
"def _stop(self):\n self.display_end_message()",
"def stop():\n stop_tracking()",
"def stop(self):\n self.halt()\n self.serial.close()",
"def stop(self):\n self.tie(None)\n self._mmio.write(0x30, 0x00011080)\n while self.running:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cleans up old images for a footprint | def cleanup_footprint(self, fpname):
logging.debug("Environment: %s entered" % __name__)
fp = self.get_footprint(fpname, start=False)
fp.cleanup_old_images()
fp.save() | [
"def cleanup_old_images(self):\n \n logging.debug(\"%s cleanup_old_images entered\" % self.footprint_name)\n active_imgs = self.images.values()\n old_images = self.old_images[:]\n for img_id in old_images:\n logging.info(\"Deleting image %s from footprint %s\" % (img_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the machine is up and running, returns true. Otherwise, false | def isup(self):
if self.cloudserver:
# print self.cloudserver.status
if self.cloudserver.status in ("ACTIVE",):
return True
return False | [
"def is_running(self):\n cmd = [\"machinectl\", \"--no-pager\", \"status\", self.name]\n try:\n subprocess.check_call(cmd)\n return True\n except subprocess.CalledProcessError as ex:\n logger.info(\"nspawn container %s is not running probably: %s\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads a machine configuration from UUID | def load(self, uuid):
try:
self.cloudserver = cs.servers.find(id=uuid)
except novaclient.exceptions.NotFound, e:
logging.warn("MACHINE LOAD: %s" % (e.message))
self.cloudserver = None | [
"def load(self, uuid):\n uuid = dlite.get_uuid(uuid)\n return instance_from_dict(self.d[uuid])",
"def get_machine_from_uuid(uuid):\n machine = Machine()\n machine.get_from_uuid(uuid)\n return machine",
"def getActualConfigFrom(self, uuid):\n if uuid in self.listOfSwitchManagers.key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the image id for this server's image if no images are available, returns false | def get_image(self):
logging.debug("%s get_image entered" % str(self.machine_name))
snapshots = cs.list_snapshots()
# find the one for this server
if self.cloudserver:
server_id = self.cloudserver.id
else:
return self.image_id
for snapshot in snap... | [
"def __get_image_id(self):\n return self.__get_multi_images_ids(1)",
"def image_id(self):\n return self._image_id",
"def get_image_id(self, image_name):\n _url = \"http://\" + self.host_ip + \":8774/v2/\" +\\\n self.cloud_admin_info[\"project_id\"] + \"/images/detail\"\n _... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a network object based on a UUID | def load(self, uuid, start=False):
try:
self.cloudnet = cn.find(id=uuid)
except pyrax.exceptions.NotFound:
logging.debug("Net '%s' not found" % uuid)
notify("Net %s not found" % uuid)
if start:
logging.info("Creating saved network %s" % str... | [
"def _create_network(self, *args):\n return self._network_class()",
"def create_network(self, host, username, password, net_id):\n pass",
"def with_uuid(self, uuid: Optional[str]) -> 'Node':\n return dataclasses.replace(self, uuid=uuid)",
"def create_network(self, network):\n public_ur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads machines in this footprint from a saved configuration | def load_machines(self, start=False):
logging.debug("%s load_machines entered" % self)
all_containers = cf.list_containers()
if self.container_name in all_containers:
logging.info("Found existing container, checking for machine configuration")
mycontainer = cf.get_contain... | [
"def load_machines(self, paths):\n self.machines = []\n for file_path in paths:\n hdf5file = bob.io.HDF5File(file_path)\n self.machines.append(bob.machine.GMMMachine(hdf5file))\n del hdf5file",
"def load_config(cls, filename):\n json_data = None\n with ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |