query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Mostly internal routine to update the limits. Shouldn't need to be called explicitly in most cases.
def update_limits(self): if len(self) == 0: self.limits = np.array([[0.0, 0.0], [0.0, 0.0]]) else: x_min, x_max = self.buf[self.rear][0], self.buf[self.front][0] y_min, y_max = self.slmm.get_minmax() self.limits = np.array([[x_min, y_min], [x_max, y_max]])
[ "def _update_limits(self):\n if self.pos_x > self.max_x:\n self.max_x = self.pos_x\n if self.pos_y > self.max_y:\n self.max_y = self.pos_y\n if self.pos_x < self.min_x:\n self.min_x = self.pos_x\n if self.pos_y < self.min_y:\n self.min_y = self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a series of points. `points` should be a list/array/sequence of (x, y)
def add_points(self, points): for pt in points: self._add(pt) self.update_limits()
[ "def add_points(self, points):\n self.points += points", "def add_set_of_points(self, points):\r\n self.set_of_points = np.concatenate((self.set_of_points, points))", "def add_points(self, points):\n\n c = 0\n point_count = 0\n seg_count = self.segments[c].pointcount\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the associated plot with the current set of points. If `update_limits` is `True` then the plot limits will be updated with the current limits of the data.
def update_plot_from_source(dsrc, xyplot, update_limits=False): arr = dsrc.get_points() if update_limits: limits = dsrc.get_limits() xyplot.plot(arr, limits=limits) else: xyplot.plot(arr)
[ "def refresh_plot(self):\n self.ax.relim() # recompute the data limits\n self.ax.autoscale_view() # automatic axis scaling\n self.fig.canvas.flush_events()", "def updatexPlot(self):\n # Block indicator update when panning to greatly enhance\n # performan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the principal components analysis of matrix X, only the first k eigenvalues and eigenvectors will be returned.
def pca(X, k): n, dim = X.shape # Center the data X_mean = np.mean(X, axis = 0) X = X - X_mean # Get the covariance matrix covariance_matrix = np.dot(X.T, X) / (n - 1) eigval, eigvec = eigs(covariance_matrix, k) return np.array(eigvec), np.array(eigval)
[ "def pca(X,k):\n m = X.shape[0]\n covariance = np.dot(X.T, X) / (m-1)\n # Eigen decomposition\n eigenvals, eigenvecs = np.linalg.eig(covariance)\n #project in K dimensions\n print(\"First two Principal Components from PCA:\")\n print(eigenvecs[:,:k])\n pca_result = np.dot(X, eigenvecs[:,:k])...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare two dataframes by element with precision margin.
def eq(df1, df2, precision=0.5) -> bool: return ((df1 - df2).abs() < precision).all()
[ "def compare_almost_equal(self, df1, df2, name):\n\n\t\tcomp_df = pd.DataFrame()\n\t\tcomp_df['left'] = df1[name].round(SIG_DIG)\n\t\tcomp_df['right'] = df2[name].round(SIG_DIG)\n\t\tcomp_df['diff'] = comp_df['left'] - comp_df['right']\n\t\tcomp_df['diff'] = comp_df['diff'].abs().round(SIG_DIG)\n\t\t# print(comp_df...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new Annotation to mPulse dashboard.
def addAnnotation(self, token, title, text, start, end = None): if end is None: payload = "{\"title\":\"" + title + "\", \"start\": \"" + str(start) + "\", \"text\":\"" + text + "\"}" else: payload = "{\"title\":\"" + title + "\", \"start\": \"" + str(start) + "\", \"end\":\"" + str(end) + "\", \"text\":\"" +...
[ "def appendAnnotation(self, *args):\n return _libsbml.SBase_appendAnnotation(self, *args)", "def _add_annotation(annotation_dict, annotation_name):\n self.annotation[annotation_name] = annotation_dict[self.uuid]", "def _add_annotation(raw_fig):\n data_ax = raw_fig.mne.ax_main\n\n key_event =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This Example evolves a CoDeepNEAT population on the MNIST handwritten digit dataset for 72 generations. Subsequently the best genome is trained for a final 200 epochs and its genotype and Tensorflow model are backed up.
def codeepneat_mnist_example(_): # Set standard configuration specific to TFNE but not the neuroevolution process logging_level = logging.INFO config_file_path = './codeepneat_mnist_example_config.cfg' backup_dir_path = './tfne_state_backups/' max_generations = 20 max_fitness = None # Read ...
[ "def main():\n # \"\"\"Prepare neuromorphic MNIST image datasets for use in caffe\n # Each dataset will be generated with different number of unique spikes\n # \"\"\"\n # initial_size = 1e6 #best to make this big enough avoid expensive\n # re-allocation\n # test_dir = os.path.abspath('testFull')\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receive a packed xrootd request (iterable generator method)
def receive(self): while True: if self.pending_request: request = self.unpack(self.pending_request) self.pending_request = None else: request = self.unpack(self.mh.receive_message()) if request: yield request else: break
[ "def to_requested_things(self):\n\n if self.__request_prop_names == None:\n self.__request_prop_names = []\n\n if self.__request_actions == None:\n self.__request_actions = {}\n\n if self.raw_bytes == None: # no payload to process, keep vars as empty\n return No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform handshake/protocol/login/auth/authmore sequence with default values. If verify_auth is true, the credentials supplied by the client in the kXR_auth request will be properly authenticated, otherwise they will not be checked.
def do_full_handshake(self, verify_auth=False): for request in self.receive(): if request.type == 'handshake': print request # Send handshake + protocol at the same time self.send(self.handshake() + self.kXR_protocol(streamid=request.streamid)) elif reque...
[ "def _initialize_authentication(self):\n self._broker_connection.request(SaslHandshakeRequest.get_versions()[self.handshake_version](self.mechanism))\n response = SaslHandshakeResponse.get_versions()[self.handshake_version](self._broker_connection.response())\n if response.error_code != 0:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_bind response.
def kXR_bind(self, streamid=None, status=None, dlen=None, pathid=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Bind') params = \ {'streamid': streamid if streamid else 0, 'status' : status if status else get_responseid('kXR_...
[ "def pack(self) -> bytes:\n\n return self.ENCODER.pack(\n self.ENCODER.size,\n self.info1,\n self.info2,\n self.info3,\n self.status_code,\n self.generation,\n self.record_ttl,\n self.transaction_ttl,\n self.fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_dirlist response.
def kXR_dirlist(self, streamid=None, status=None, dlen=None, data=None): return self.kXR_ok(streamid, status, dlen, data)
[ "def listdir(dir_name: str, addr: tuple) -> List[str]:\n if dir_name == \"\":\n dir_name = \".\"\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect(addr)\n s.sendall(pickle.dumps([\"listdir\", dir_name]))\n d = bdtp.new_receive_data_port((\"\", 0))\n d.recv(s)\n s.close(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_login response. Pass verify_auth=True to enable authentication.
def kXR_login(self, streamid=None, status=None, dlen=None, sessid=None, sec=None, verify_auth=False): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Login') # Check if client needs to authenticate if verify_auth and not...
[ "def _login_challenge(self):\n headers, items = self._get('/login', {\n 'dbus': 'AUTH DBUS_COOKIE_SHA1 %s' % self.username\n })\n\n if headers.get('request_result') != 'success':\n raise ApiException(\"Failed receiving challenge\")\n\n return items[0].get('dbus').sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_open response.
def kXR_open(self, streamid=None, status=None, dlen=None, fhandle=None, cpsize=None, cptype=None, data=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Open') params = \ {'streamid': streamid if streamid else 0, 'status...
[ "def kXR_protocol(self, streamid=None, status=None, dlen=None, pval=None, \n flags=None): \n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBody_Protocol')\n params = \\\n {'streamid': streamid if streamid else 0,\n 'status' : ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_prepare response.
def kXR_prepare(self, streamid=None, status=None, dlen=None, data=None): return self.kXR_ok(streamid, status, dlen, data)
[ "def pack(self) -> bytes:\n\n return self.ENCODER.pack(\n self.ENCODER.size,\n self.info1,\n self.info2,\n self.info3,\n self.status_code,\n self.generation,\n self.record_ttl,\n self.transaction_ttl,\n self.fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_protocol response.
def kXR_protocol(self, streamid=None, status=None, dlen=None, pval=None, flags=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Protocol') params = \ {'streamid': streamid if streamid else 0, 'status' : status if ...
[ "def pack(self) -> bytes:\n\n return self.ENCODER.pack(\n self.ENCODER.size,\n self.info1,\n self.info2,\n self.info3,\n self.status_code,\n self.generation,\n self.record_ttl,\n self.transaction_ttl,\n self.fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_read response.
def kXR_read(self, streamid=None, status=None, dlen=None, data=None): return self.kXR_ok(streamid, status, dlen, data)
[ "def read_rdatac_response(self):\n if self.mode == self.MessagePackMode:\n response_obj = self._serial_read_messagepack_message()\n else:\n message = self._serial_readline()\n try:\n response_obj = json.loads(message)\n except JSONDecodeError:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_readv response.
def kXR_readv(self, streamid=None, status=None, dlen=None, data=None): return self.kXR_ok(streamid, status, dlen, data)
[ "def read_rdatac_response(self):\n if self.mode == self.MessagePackMode:\n response_obj = self._serial_read_messagepack_message()\n else:\n message = self._serial_readline()\n try:\n response_obj = json.loads(message)\n except JSONDecodeError:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_stat response.
def kXR_stat(self, streamid=None, status=None, dlen=None, data=None, id=None, size=None, flags=None, modtime=None): if not data: data = (x for x in (id, size, flags, modtime) if x is not None) data = ' '.join([str(param) for param in data]) return self.kXR_ok(stream...
[ "def xrd_statinfo2dict(response_statinfo) -> dict:\n if not response_statinfo: return {}\n if not HAS_XROOTD:\n print_err('XRootD not present')\n return {}\n if not isinstance(response_statinfo, xrd_client.responses.StatInfo):\n print_err('Invalid argument type passed to xrd_statinfo2d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_statx response.
def kXR_statx(self, streamid=None, status=None, dlen=None, data=None): return self.kXR_ok(streamid, status, dlen, data)
[ "def xrd_statinfo2dict(response_statinfo) -> dict:\n if not response_statinfo: return {}\n if not HAS_XROOTD:\n print_err('XRootD not present')\n return {}\n if not isinstance(response_statinfo, xrd_client.responses.StatInfo):\n print_err('Invalid argument type passed to xrd_statinfo2d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_attn_asyncab response.
def kXR_attn_asyncab(self, streamid=None, status=None, dlen=None, actnum=None, msg=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Attn') if not msg: msg = '' params = \ {'streamid': streamid if streamid else 0...
[ "def get_cap_value(response, ipb, psn):\n\n if Tag.RMTF1 in response.data:\n # Response type 1, deserialise it with our static DOL.\n data = GAC_RESPONSE_DOL.unserialise(response.data[Tag.RMTF1])\n elif Tag.RMTF2 in response.data:\n # Response type 2, TLV format.\n data = response....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_attn_asyncdi response.
def kXR_attn_asyncdi(self, streamid=None, status=None, dlen=None, actnum=None, wsec=None, msec=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Attn_asyncdi') params = \ {'streamid': streamid if streamid else 0, ...
[ "def kXR_attn_asyncab(self, streamid=None, status=None, dlen=None, actnum=None, \n msg=None):\n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBody_Attn')\n if not msg: msg = ''\n params = \\\n {'streamid': streamid if st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_attn_asyncms response.
def kXR_attn_asyncms(self, streamid=None, status=None, dlen=None, actnum=None, msg=None): if not actnum: actnum = get_attncode('kXR_asyncms') return self.kXR_attn_asyncab(streamid, status, dlen, actnum, msg)
[ "def kXR_attn_asyncab(self, streamid=None, status=None, dlen=None, actnum=None, \n msg=None):\n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBody_Attn')\n if not msg: msg = ''\n params = \\\n {'streamid': streamid if st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_attn_asyncrd response.
def kXR_attn_asyncrd(self, streamid=None, status=None, dlen=None, actnum=None, port=None, host=None, token=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Attn_asyncrd') if not host: host = '' else: host += (token if...
[ "def kXR_attn_asynresp(self, streamid=None, status=None, dlen=None, \n actnum=None, reserved=None, rstreamid=None,\n rstatus=None, rlen=None, rdata=None):\n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_attn_asynresp response.
def kXR_attn_asynresp(self, streamid=None, status=None, dlen=None, actnum=None, reserved=None, rstreamid=None, rstatus=None, rlen=None, rdata=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Attn_asy...
[ "def kXR_attn_asyncab(self, streamid=None, status=None, dlen=None, actnum=None, \n msg=None):\n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBody_Attn')\n if not msg: msg = ''\n params = \\\n {'streamid': streamid if st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_attn_asyncwt response.
def kXR_attn_asyncwt(self, streamid=None, status=None, dlen=None, actnum=None, wsec=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Attn_asyncwt') params = \ {'streamid': streamid if streamid else 0, 'status' ...
[ "def kXR_attn_asyncab(self, streamid=None, status=None, dlen=None, actnum=None, \n msg=None):\n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBody_Attn')\n if not msg: msg = ''\n params = \\\n {'streamid': streamid if st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_authmore response.
def kXR_authmore(self, streamid=None, status=None, dlen=None, data=None): if not status: status = get_responseid('kXR_authmore') return self.kXR_ok(streamid, status, dlen, data)
[ "def get_rsp_ud2(self):\n resp_bytes = []\n resp_bytes.append(0x68) # start\n resp_bytes.append(0xFF) # length\n resp_bytes.append(0xFF) # length\n resp_bytes.append(0x68) # start\n resp_bytes.append(0x08) # C\n resp_bytes.append(self._primary_address) # A\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_error response.
def kXR_error(self, streamid=None, status=None, dlen=None, errnum=None, errmsg=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Error') if not errmsg: errmsg = '' if not errnum: errnum = XProtocol.XErrorCode.kXR_ArgInvalid ...
[ "def errorResponse(self):\n return self._errorResponse", "def xen_api_error(error):\n if type(error) == tuple:\n error = list(error)\n if type(error) != list:\n error = [error]\n if len(error) == 0:\n error = ['INTERNAL_ERROR', 'Empty list given to xen_api_error']\n\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_ok response.
def kXR_ok(self, streamid=None, status=None, dlen=None, data=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Buffer') if not data: data = '' params = \ {'streamid': streamid if streamid else 0, 'status' : status if status e...
[ "def kXR_oksofar(self, streamid=None, status=None, dlen=None, data=None):\n status = get_responseid('kXR_oksofar')\n return self.kXR_ok(streamid, status, dlen, data)", "def test_ok_response(self):\n res = OkResponse({\"message\": self.message})", "def checkResponseOK(response):\n assert response...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_oksofar response.
def kXR_oksofar(self, streamid=None, status=None, dlen=None, data=None): status = get_responseid('kXR_oksofar') return self.kXR_ok(streamid, status, dlen, data)
[ "def kXR_ok(self, streamid=None, status=None, dlen=None, data=None):\n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBody_Buffer')\n if not data: data = ''\n params = \\\n {'streamid': streamid if streamid else 0,\n 'status' : status ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_redirect response.
def kXR_redirect(self, streamid=None, status=None, dlen=None, port=None, host=None, opaque=None, token=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Redirect') if not host: host = '' else: host += (opaque if opaque els...
[ "def encode(self, response):\r\n encode_as = response.whichEncoding()\r\n if encode_as == ENCODE_KVFORM:\r\n wr = self.responseFactory(body=response.encodeToKVForm())\r\n if isinstance(response, Exception):\r\n wr.code = HTTP_ERROR\r\n elif encode_as == ENCO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_wait response.
def kXR_wait(self, streamid=None, status=None, dlen=None, seconds=None, infomsg=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Wait') if not infomsg: infomsg = '' params = \ {'streamid': streamid if streamid else 0, ...
[ "def kXR_waitresp(self, streamid=None, status=None, dlen=None, seconds=None):\n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBody_Waitresp')\n params = \\\n {'streamid': streamid if streamid else 0,\n 'status' : status if status else ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a packed representation of a kXR_waitresp response.
def kXR_waitresp(self, streamid=None, status=None, dlen=None, seconds=None): response_struct = get_struct('ServerResponseHeader') + \ get_struct('ServerResponseBody_Waitresp') params = \ {'streamid': streamid if streamid else 0, 'status' : status if status else get_response...
[ "def kXR_wait(self, streamid=None, status=None, dlen=None, seconds=None,\n infomsg=None):\n response_struct = get_struct('ServerResponseHeader') + \\\n get_struct('ServerResponseBody_Wait')\n if not infomsg: infomsg = ''\n params = \\\n {'streamid': streamid if stream...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate Python blocks in the page. We add "request" > Request to the locals dictionary so that "request" can be referred to.
def eval_python_blocks(req, body): localsdict = {"request": req} globalsdict = {} old_stdout = sys.stdout old_stderr = sys.stderr try: start = 0 while body.find("<%", start) != -1: start = body.find("<%") end = body.find("%>", start) if star...
[ "def _run(self, request):\n\n # 1: call check method\n check_flag, check_dict = self._check(request)\n if not check_flag: \n return self._render(request, check_dict) # pragma: no cover\n else: \n # 2: call process\n node_dict = self._process(request)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Looks for wiki links in [[topic]] and [[topic | desc]] format and expands them.
def connect_links(base_url, extensions, wikidir, body): if base_url.endswith("/"): base_url = base_url[:-1] i = 0 body2 = [] for match in WIKILINK.finditer(body): body2.append(body[i:match.span(0)[0]]) text = match.group(1) if "|" in text: topic, d...
[ "def test_internal_link_text():\n content = \"[[Foobar|fuzzbar]]\"\n wikicode = mwparserfromhell.parse(content)\n assert (\n compose(wikicode) == '<p><a href=\"/wiki/Foobar\" title=\"Foobar\">fuzzbar</a></p>'\n )", "def breakup_desc(exp):\n from tardis.apps.hpctardis.publish.rif_cs_profile.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert to iterable. If input is iterable, returns it. Otherwise returns it in a list. Useful when you want to iterate over something (like in a for loop), and you don't want to have to do type checking or handle exceptions when it isn't a sequence
def toiter(x): if iterable(x): return x else: return [x]
[ "def make_iterable(value):\n try:\n iter(value)\n except TypeError:\n return [value]\n else:\n return value", "def arg_to_iter(arg):\n if arg is None:\n return []\n elif not isinstance(arg, _ITERABLE_SINGLE_VALUES) and hasattr(arg, '__iter__'):\n return arg\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return C contiguous copy of array x if it isn't C contiguous already
def tocontig(x): if not x.flags.c_contiguous: x = x.copy() return x
[ "def as_c_contiguous(array):\n if not array.flags.c_contiguous:\n return array.copy(order=\"C\")\n return array", "def contiguous( cls, source, typeCode=None ):\n typeCode = GL_TYPE_TO_ARRAY_MAPPING[ typeCode ]\n try:\n contiguous = source.flags.contiguous\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up rgbsids array for later use in self.pick()
def set_sids(self, sids): self._sids = sids # encode sids in RGB r = sids // 256**2 rem = sids % 256**2 # remainder g = rem // 256 b = rem % 256 self.rgbsids = np.zeros((self.npoints, 3), dtype=np.uint8) self.rgbsids[:, 0] = r self.rgbsids[:, 1] = ...
[ "def assign_rings(self):\n rings = self.make_rings()\n ring_angles = [rings[r][0] for r in rings]\n self.rp = np.zeros((self.npks), dtype=int)\n for i in range(self.npks):\n self.rp[i] = (np.abs(self.polar_angle[i] - ring_angles)).argmin()", "def set_gids(self, N = []):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set colors of points corresponding to sids according to their nids, with saturation level sat. Caller is responsible for calling self.updateGL()
def color(self, sids=None, sat=1): if sids == None: # init/overwrite self.colors nids = self.nids # uint8, single unit nids are 1-based: self.colors = CLUSTERCLRSRGB[nids % len(CLUSTERCLRSRGB) - 1] * sat # overwrite unclustered/multiunit points with GREYRGB ...
[ "def color(self, sids=None, sat=1):\n if sids is None: # init/overwrite self.colors\n nids = self.nids\n # uint8, single unit nids are 1-based:\n self.colors = CLUSTERCLRSRGB[nids % len(CLUSTERCLRSRGB) - 1] * sat\n # overwrite unclustered/multiunit points with GREY...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Paint mini xyz axes in bottom left of widget
def paint_mini_axes(self): w, h = self.width(), self.height() vt = self.getTranslation() # this is in eye coordinates GL.glViewport(0, 0, w//8, h//8) # mini viewport at bottom left of widget self.setTranslation((0, 0, -3)) # draw in center of this mini viewport self.paint_axes() ...
[ "def _set_axes(self):\n self += helper.line(stroke=\"black\", x1=self.__dict__['x'], x2=self.__dict__['x'], y1=0, y2=self.__dict__['y']*2)\n self += helper.line(stroke=\"black\", x1=0, x2=self.__dict__['x']*2, y1=self.__dict__['y'], y2=self.__dict__['y'])", "def centerAxis():\n dislin.cen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Paint axes at origin, with lines of length l
def paint_axes(self, l=1): GL.glBegin(GL.GL_LINES) GL.glColor3f(1, 0, 0) # red x axis GL.glVertex3f(0, 0, 0) GL.glVertex3f(l, 0, 0) GL.glColor3f(0, 1, 0) # green y axis GL.glVertex3f(0, 0, 0) GL.glVertex3f(0, l, 0) GL.glColor3f(0, 0, 1) # blue z axis ...
[ "def hline(self, x, y, l, color=0xffffff):\n for i in range(l):\n self.pixel(x+i, y, color)", "def _set_axes(self):\n self += helper.line(stroke=\"black\", x1=self.__dict__['x'], x2=self.__dict__['x'], y1=0, y2=self.__dict__['y']*2)\n self += helper.line(stroke=\"black\", x...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make x axis point out. Work on top left 3x3 subset of MV matrix. This was deduced by watching behaviour of MV matrix while manually
def rotateXOut(self): MV = self.MV MV[:3, 2] = 1, 0, 0 # 3rd col is normal vector, make it point along x axis # set top left and top middle values to zero: MV[0, 0] = 0 MV[0, 1] = 0 b = MV[2, 0] # grab bottom left value a = np.sqrt(1 - b**2) # calc new complementa...
[ "def moveXaxis(self):\r\n new_x = 0\r\n old_x = self.x\r\n # select direction\r\n if (random.random()<0.5):\r\n new_x = old_x + 1\r\n else:\r\n new_x = old_x - 1\r\n # check for boundaries\r\n if new_x < 0:\r\n new_x = 0\r\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make y axis point right. Work on top left 3x3 subset of MV matrix. This was deduced by watching behaviour of MV matrix while manually
def rotateYRight(self): MV = self.MV MV[:3, 0] = 0, 1, 0 # 1st col is right vector, make it point along y axis # set middle middle and middle right values to zero: MV[1, 1] = 0 MV[1, 2] = 0 a = MV[0, 1] # grab top middle value b = np.sqrt(1 - a**2) # calc new comp...
[ "def moveYaxis(self):\r\n new_y = 0\r\n old_y = self.y\r\n # select direction\r\n if (random.random()<0.5):\r\n new_y = old_y + 1\r\n else:\r\n new_y = old_y - 1\r\n # check for boundaries\r\n if new_y < 0:\r\n new_y = 0\r\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make z axis point up. Work on top left 3x3 subset of MV matrix. This was deduced by watching behaviour of MV matrix while manually
def rotateZUp(self): MV = self.MV MV[:3, 1] = 0, 0, 1 # 2nd col is up vector, make it point along z axis # set bottom left and bottom right z values to zero: MV[2, 0] = 0 MV[2, 2] = 0 a = MV[0, 0] # grab top left value b = np.sqrt(1 - a**2) # calc new complementar...
[ "def rotateXOut(self):\n MV = self.MV\n MV[:3, 2] = 1, 0, 0 # 3rd col is normal vector, make it point along x axis\n # set top left and top middle values to zero:\n MV[0, 0] = 0\n MV[0, 1] = 0\n b = MV[2, 0] # grab bottom left value\n a = np.sqrt(1 - b**2) # calc new...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate along view right and view up vectors such that data point p is centered in the viewport. Not entirely sure why or how this works, figured it out using guess and test
def panTo(self, p=None): if p == None: p = self.focus MV = self.MV vr = self.getViewRight() vu = self.getViewUp() p = -p x = np.dot(p, vr) # dot product y = np.dot(p, vu) MV[3, :2] = x, y # set first two entries of 4th row to x, y self....
[ "def uvmap(self, p):\n # bottom left corner of the plane\n p00 = self.position - (self.sx * self.n0) / 2 - (self.sy * self.n1) / 2\n dif_vector = p - p00\n u = np.dot(dif_vector, self.n0) / self.sx\n v = np.dot(dif_vector, self.n1) / self.sy\n return u, v", "def projectPo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return sid of point at window coords x, y (bottom left origin), or first or multiple sids that fall within a square 2pb+1 pix on a side, centered on x, y. pb is the pixel border to include around x, y
def pick(self, x, y, pb=2, multiple=False): width = self.size().width() height = self.size().height() #print('coords: %d, %d' % (x, y)) # constrain to within border 1 pix smaller than widget, for glReadPixels call if not (pb <= x < width-pb and pb <= y < height-pb): # cursor out ...
[ "def get_square_at(x, y):\n if settings.IS_RECT:\n i = x // SQ_SIZE\n j = y // SQ_SIZE\n else:\n i = (y * math.sqrt(3) /\n SQ_SIZE + x / SQ_SIZE - GRID_SIZE / 2 + ROWS) / 2\n j = i - x / SQ_SIZE + GRID_SIZE / 2\n return int(i), int(j)", "def get_pixel_in_window(img...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert encoded rgb value to sid
def decodeRGB(self, rgb): r, g, b = rgb sid = r*65536 + g*256 + b if sid < 16777215: # 2**24 - 1 return sid # it's a valid sid
[ "def Pixel_Convert (self, val):\n #separate string into component colors, then convert to int\n red = int(\"0x\" + val[2:4], 16)\n green = int(\"0x\" + val[4:6], 16)\n blue = int(\"0x\" + val[6:8], 16)\n return red, green, blue", "def _to_code(rgb):\n code = 0\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get current mouse cursor position in Qt coords (top left origin)
def cursorPosQt(self): globalPos = QtGui.QCursor.pos() pos = self.mapFromGlobal(globalPos) return pos.x(), pos.y()
[ "def mousePos():\n data = display.Display().screen().root.query_pointer()._data\n return data[\"root_x\"], data[\"root_y\"]", "def cursorPosGL(self):\n globalPos = QtGui.QCursor.pos()\n pos = self.mapFromGlobal(globalPos)\n y = self.size().height() - pos.y()\n return pos.x(), y",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get current mouse cursor position in OpenGL coords (bottom left origin)
def cursorPosGL(self): globalPos = QtGui.QCursor.pos() pos = self.mapFromGlobal(globalPos) y = self.size().height() - pos.y() return pos.x(), y
[ "def mousePos():\n data = display.Display().screen().root.query_pointer()._data\n return data[\"root_x\"], data[\"root_y\"]", "def getPosition():\r\n return mouse.position", "def getCursorRelative(self):\n\t\twx,wy = glfw.GetCursorPos(self.window)\n\t\tcx,cy = glfw.GetWindowPos(self.window)\n\t\treturn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert GL screen coords to Qt, return as QPoint
def GLtoQt(self, x, y): y = self.size().height() - y return QtCore.QPoint(x, y)
[ "def cursorPosQt(self):\n globalPos = QtGui.QCursor.pos()\n pos = self.mapFromGlobal(globalPos)\n return pos.x(), pos.y()", "def cursorPosGL(self):\n globalPos = QtGui.QCursor.pos()\n pos = self.mapFromGlobal(globalPos)\n y = self.size().height() - pos.y()\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Record mouse position on button press, for use in mouseMoveEvent. On middle click, select spikes
def mousePressEvent(self, event): #sw = self.spw.windows['Sort'] buttons = event.buttons() if buttons == QtCore.Qt.MiddleButton: #sw.on_actionSelectRandomSpikes_triggered() #sw.spykewindow.ui.plotButton.click() # same as hitting ENTER in nslist self.selecting ...
[ "def on_click_mouse_move(self):\n self.button_selected = ButtonKey.MOUSE", "def mousePressEvent(self, event):\n #sw = self.spw.windows['Sort']\n buttons = event.buttons()\n if buttons == QtCore.Qt.MiddleButton:\n #sw.on_actionSelectRandomSpikes_triggered()\n #sw.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save cluster plot to file
def save(self): fname = getSaveFileName(self, "Save cluster plot to", 'cluster_plot.png') if fname: fname = str(fname) # convert from QString image = self.grabFrameBuffer() # defaults to withAlpha=False, makes no difference try: image.save(fname) ...
[ "def save(self):\n fname, _ = getSaveFileName(self, \"Save cluster plot to\", 'cluster_plot.png')\n if fname:\n fname = str(fname) # convert from QString\n image = self.grabFrameBuffer() # defaults to withAlpha=False, makes no difference\n try:\n image.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pop up a nid or sid tooltip at current mouse cursor position
def showToolTip(self): # hide first if you want tooltip to move even when text is unchanged: #QtGui.QToolTip.hideText() #spw = self.spw #sort = spw.sort x, y = self.cursorPosGL() sid = self.pick(x, y) if sid != None: #spos = [] #dims = spw....
[ "def showTooltip(self, label): \n self.tooltipWindow = ocempgui.widgets.TooltipWindow (label)\n x, y = pygame.mouse.get_pos ()\n self.tooltipWindow.topleft = x + 8, y - 5\n self.tooltipWindow.depth = 99 # Make it the topmost widget.\n self.tooltipWindow.zOrder = 30000\n self.window.add_child(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update point selection with those currently under cursor, within pixel border pb. Call this method on S and D down, and on mouse motion when either S or D are down
def selectPointsUnderCursor(self): #spw = self.spw #sw = spw.windows['Sort'] #if clear: # sw.uslist.clearSelection() # sw.nlist.clearSelection() x, y = self.cursorPosGL() sids = self.pick(x, y, pb=10, multiple=True) if sids == None: retur...
[ "def selectPointsUnderCursor(self):\n spw = self.spw\n sw = spw.windows['Sort']\n #if clear:\n # sw.uslist.clearSelection()\n # sw.nlist.clearSelection()\n x, y = self.cursorPosGL()\n sids = self.pick(x, y, pb=10, multiple=True)\n if sids is None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get and set OpenGL ModelView matrix and focus. Useful for setting two different instances to the exact same projection
def showProjectionDialog(self): dlg = uic.loadUi('multilineinputdialog.ui') dlg.setWindowTitle('Get and set OpenGL ModelView matrix and focus') precision = 8 # use default precision MV_repr = np.array_repr(self.MV, precision=precision) focus_repr = np.array_repr(self.focus, preci...
[ "def _set_camera(self):\n gl.glMatrixMode(gl.GL_PROJECTION)\n gl.glLoadIdentity()\n glu.gluPerspective(45.0, float(self.width)/float(self.height),\n self.z_near, self.z_far)\n projection = gl.glGetFloatv(gl.GL_PROJECTION_MATRIX)\n\n gl.glMatrixMode(gl.GL_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the line_deque into options and subsections for this section.
def parse(self, line_deque): self._check_is_line_deque(line_deque) while len(line_deque) > 0: line = line_deque.popleft() name = self._parse_option_name(line) if self._is_option(line): if name in self._OPTIONS.keys(): option_value =...
[ "def _check_is_line_deque(line_deque):\n if not isinstance(line_deque, LineDeque):\n raise ValueError(\"Curly braces must be provided, even if no options are specified.\")", "def parse_line(self):\n def add_element(value, index):\n self.out_lines.append(Line(value, int(index)))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks to see if any crucial information is missing after user input is parsed.
def _check_for_incomplete_input(self): pass
[ "def validate_fields(self):\n if self.file == '':\n sg.popup_error('The data path is empty. Select a supported dataset file.', title='Input Error')\n return False\n if self.results == '':\n sg.popup_error('The result path is empty. Select a location for the results.', ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Throws an error if argument is not a LineDeque instance.
def _check_is_line_deque(line_deque): if not isinstance(line_deque, LineDeque): raise ValueError("Curly braces must be provided, even if no options are specified.")
[ "def parse(self, line_deque):\n self._check_is_line_deque(line_deque)\n while len(line_deque) > 0:\n line = line_deque.popleft()\n name = self._parse_option_name(line)\n if self._is_option(line):\n if name in self._OPTIONS.keys():\n op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if line contains a option, False if it is section name.
def _is_option(line): return '=' in line
[ "def section_has_option(self, section, option):\n return self.has_option(section, option)", "def has_option(self, opt):\r\n return self.cf.has_option(self.main_section, opt)", "def has_option(self, section, option):\n try:\n if option in self._dict[section]:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Throws ValueError if the option is not valid for this section.
def _invalid_option_error(self, option_name): msg = "'{}' is not a valid option for the '{}' section.".format(option_name, self._SECTION_NAME) raise ValueError(msg)
[ "def is_value_valid(self, section_name, option_name, option_value):", "def assert_valid_option(cls, option):\n\n if option not in cls.AvaliableOptions:\n raise ValueError(\n f\"Invalid option '{option}'. The avaliable options are {cls.AvaliableOptions}\"\n )", "def va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Throws ValueError if the section is not a valid subsection for this section.
def _invalid_section_error(self, section_name): msg = "'{}' is not a subsection for the '{}' section.".format(section_name, self._SECTION_NAME) raise ValueError(msg)
[ "def validate_section(section):\n for subsect in section:\n is_mod = 'exercises' in section[subsect]\n\n if section[subsect] == {}:\n print 'WARNING: Section ' + subsect + ' is empty'\n continue\n elif not is_mod:\n for field in section[subsect]:\n if type(section[subsect][field]) !=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a matrix NxM, returns a new matrix with size NxN containing all the cosine similarities between each row to every other row of the provided matrix.
def cosine_sim(matrix): if type(matrix) is not csr_matrix: matrix = csr_matrix(matrix) return cosine_similarity(matrix, dense_output=False)
[ "def fast_cosine_similarity_matrix(mat):\n # calculate the inner products between all row vectors\n products = mat * mat.T\n # for each row vector, the magnitude can be read off of the\n # resulting diagonal\n norms = np.sqrt(np.diag(products))\n # for each cell, calculate the product of the norms...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a matrix NxM, returns a new matrix with size NxN containing all the cosine similarities between each row to every other row of the provided matrix. The applied cosine formula is a variant that is sometimes considered on collaborative filtering (CF) environments (Adomavicius, G., & Tuzhilin, A. (2005). Toward the ...
def cosine_sim_cf(matrix): if type(matrix) is not lil_matrix: matrix = lil_matrix(matrix) n = matrix.shape[0] rows, cols, data = [], [], [] user_items = [sorted([(item, idx) for idx, item in enumerate(matrix.rows[i])]) for i in range(n)] for i in range(n): i_ratings, i_items = matr...
[ "def fast_cosine_similarity_matrix(mat):\n # calculate the inner products between all row vectors\n products = mat * mat.T\n # for each row vector, the magnitude can be read off of the\n # resulting diagonal\n norms = np.sqrt(np.diag(products))\n # for each cell, calculate the product of the norms...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a matrix NxM, returns a new matrix with size NxN containing all the adjusted cosine similarities between each row to every other row of the provided matrix. Adjusted cosine sim. is the cosine sim. applied after subtracting the matrix column averages of each column values.
def adjusted_cosine_sim(matrix): if type(matrix) is not csr_matrix: matrix = csr_matrix(matrix) matrix = _subtract_row_mean(matrix) return cosine_similarity(matrix, dense_output=False)
[ "def fast_cosine_similarity_matrix(mat):\n # calculate the inner products between all row vectors\n products = mat * mat.T\n # for each row vector, the magnitude can be read off of the\n # resulting diagonal\n norms = np.sqrt(np.diag(products))\n # for each cell, calculate the product of the norms...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a matrix NxM, returns a new matrix with size NxN containing all the jaccard similarities between each row to every other row of the provided matrix.
def jaccard_sim(matrix): if type(matrix) is not csr_matrix: matrix = csr_matrix(matrix) def matrix_jacc(matrix): matrix = matrix.astype(bool).astype(int) intersection = matrix.dot(matrix.T) row_sums = intersection.diagonal() row_sums = row_sums[:, None] + row_sums ...
[ "def jaccard_similarity_matrix(references: np.ndarray, queries: np.ndarray) -> np.ndarray:\n size1 = references.shape[0]\n size2 = queries.shape[0]\n scores = np.zeros((size1, size2))\n for i in range(size1):\n for j in range(size2):\n scores[i, j] = jaccard_index(references[i, :], que...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For each row in the given matrix, subtracts the row mean from every value in the row.
def _subtract_row_mean(A): assert type(A) is csr_matrix, "The given argument should be of type scipy.sparse.csr_matrix" sum_rows = np.array(A.sum(axis=1).squeeze())[0] size_rows = np.diff(A.indptr) avg_rows = np.divide(sum_rows, size_rows, where=size_rows != 0) avg_diag_matrix = diags(avg_rows, 0) ...
[ "def de_mean_matrix(a_matrix):\n nr, nc = shape(a_matrix)\n column_means, _ = scale(a_matrix)\n return make_matrix(nr, nc, lambda i, j: a_matrix[i][j] - column_means[j])", "def matrix_mean(matrix):\n return sum(map(mean,matrix))", "def de_mean_matrix(A):\n nr, nc = shape(A)\n column_means, _ =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if a `dpp_scope` is active.
def dpp_scope_active(): return _dpp_scope_active
[ "def has_scope(self, scope):\n return scope in self.scopes", "def isScopeActive(self, name):", "def _in_scope(self, scope):\n scope = listify(scope)\n\n if 'all' in scope:\n return True\n\n # We assume something is a BIDS-derivatives dataset if it either has a\n # d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solve the instance of HR using either the resident or hospitaloriented algorithm. Return the matching.
def solve(self, optimal="resident"): self.matching = Matching( hospital_resident(self.residents, self.hospitals, optimal) ) return self.matching
[ "def test_solve(resident_names, hospital_names, capacities, seed):\n\n for optimal in [\"resident\", \"hospital\"]:\n residents, hospitals, game = make_game(\n resident_names, hospital_names, capacities, seed\n )\n\n matching = game.solve(optimal)\n assert isinstance(matchi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for the existence of any blocking pairs in the current matching, thus determining the stability of the matching.
def check_stability(self): blocking_pairs = [] for resident in self.residents: for hospital in self.hospitals: if ( _check_mutual_preference(resident, hospital) and _check_resident_unhappy(resident, hospital) and _c...
[ "def check_stability(self):\n\n blocking_pairs = []\n for suitor in self.suitors:\n for reviewer in self.reviewers:\n if suitor.prefers(\n reviewer, suitor.matching\n ) and reviewer.prefers(suitor, reviewer.matching):\n blo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure that the residents' preferences are all subsets of the available hospital names. Otherwise, raise an error.
def _check_resident_prefs(self): errors = [] for resident in self.residents: if not set(resident.prefs).issubset(set(self.hospitals)): errors.append( ValueError( f"{resident} has ranked a non-hospital: " f"{...
[ "def _check_hospital_prefs(self):\n\n errors = []\n for hospital in self.hospitals:\n residents_that_ranked = [\n res for res in self.residents if hospital in res.prefs\n ]\n if set(hospital.prefs) != set(residents_that_ranked):\n errors.a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure that every hospital ranks all and only those residents that have ranked it. Otherwise, raise an error.
def _check_hospital_prefs(self): errors = [] for hospital in self.hospitals: residents_that_ranked = [ res for res in self.residents if hospital in res.prefs ] if set(hospital.prefs) != set(residents_that_ranked): errors.append( ...
[ "def test_validate_rank_input_vals(self):\n with self.assertRaises(ValueError):\n self.r[10] = 0\n self.cl._validate_rank(self.r)", "def _validate_rank(self, rank):\n if rank <= 0 or rank > self.num_users:\n raise RankError(\"Rank must be in the range 0 < rank <= num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether a resident is unhappy because they are unmatched, or they prefer the hospital to their current match.
def _check_resident_unhappy(resident, hospital): return resident.matching is None or resident.prefers( hospital, resident.matching )
[ "def _check_hospital_unhappy(resident, hospital):\n\n return len(hospital.matching) < hospital.capacity or any(\n [hospital.prefers(resident, match) for match in hospital.matching]\n )", "def is_unhappy(self):\n #checked!#\n ###your code here###\n same=0\n for i in self.ho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine whether a hospital is unhappy because they are undersubscribed, or they prefer the resident to at least one of their current matches.
def _check_hospital_unhappy(resident, hospital): return len(hospital.matching) < hospital.capacity or any( [hospital.prefers(resident, match) for match in hospital.matching] )
[ "def _check_resident_unhappy(resident, hospital):\n\n return resident.matching is None or resident.prefers(\n hospital, resident.matching\n )", "def is_unhappy(self):\n #checked!#\n ###your code here###\n same=0\n for i in self.home.neighbors:\n if i.occupant!=N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unmatch a (resident, hospital)pair.
def unmatch_pair(resident, hospital): resident.unmatch() hospital.unmatch(resident)
[ "def _unmatch_pair(resident, hospital):\n\n resident._unmatch()\n hospital._unmatch(resident)", "def unmatch_pair(student, project):\n\n student._unmatch()\n project._unmatch(student)", "def unpair(self, request, pk=None):\n # TODO: Call with PUT /api/v2/taxlots/1/unpair/?property_id=1&organi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a set of residents and hospitals from the dictionaries given, and add their preferences.
def _make_players(resident_prefs, hospital_prefs, capacities): resident_dict, hospital_dict = _make_instances( resident_prefs, hospital_prefs, capacities ) for resident_name, resident in resident_dict.items(): prefs = [hospital_dict[name] for name in resident_prefs[resident_name]] ...
[ "def create_hospital_to_preferences_map(resident_to_preferences):\n\n hospital_to_residents = defaultdict(set)\n for resident, hospitals in resident_to_preferences.items():\n for hospital in hospitals:\n hospital_to_residents[hospital].add(resident)\n\n hospital_to_preferences = {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize the DICESearch class. Precompile data structures and mappings from types.gd with self.compileTypes(). Initialize spreadsheetSearch with super(DICESearch, self).__init__(). Construct columns for spread sheet. scope > character range within which to search for combos
def __init__(self, scope = 100): self.toDICE, self.toTYPE, self.toWORD = self.compileTypes() # Compile mappings for TYPE/DICE, WORD/TYPE, and TERM/WORD for DICESearch Class super(DICESearch, self).__init__() # Initiate SpreadsheetSearch for DICESearch Class self.addColumn("Document", length = 1) # Column ...
[ "def initiate_criteria(self):\n if self.criteria != None:\n return\n\n self.criteria = dict()\n charset = [Board.EMPTY_SLOT, Board.BLACK_SLOT, Board.WHITE_SLOT]\n\n for a in charset:\n for b in charset:\n for c in charset:\n for d i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates a new data structure containing strings combined from the left kernel, center kernel, and right kernel of the spreadsheet. This method requires there be data in the self.spreadsheet vari able in order to return anything. This method returns a list of strings.
def buildKernel(self): kernel = list() if not self.spreadsheet_transposed: # If the spreadsheet is NOT transposed, i.e., the spreadsheet contains rows, transpose it so it contains columns self.transpose(1) # CALL THESE JUST ONCE BEFORE LOOP(S) append = kernel.append lower = str.lower format = str.fo...
[ "def getKernels(indices):\n\n\t\t\ti = indices[0]\n\t\t\tj = indices[1]\n\n\t\t\th = i - self.scope\n\t\t\tk = j + self.scope\n\n\t\t\tif h < 0: h = 0\n\t\t\tif k > len(text): k = len(text)-1\n\n\t\t\treturn text[h:i].replace(\"\\n\", \"__\").replace(\"\\t\", \" \"), text[i:j].replace(\"\\n\", \"__\").replace(\"\\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
buildSpreadsheet() creates a string from the data structure in self. spreadsheet in preparation for writing to a text file. This method returns a temporary or final build. If a temporary build is indic
def buildSpreadsheet(self, getTempBuild = False): if self.spreadsheet_transposed: self.transpose(1) # CALL THESE JUST ONCE BEFORE LOOP(S) tempBuild = list() append = tempBuild.append # - - - - - - - - - - - - - - - - - - for row in self.spreadsheet: row = [str(item) for item in row] if row not i...
[ "def export_builds_results_to_googlesheet(\n self, sheet_name=\"E2E Workloads\", sheet_index=3\n ):\n # Collect data and export to Google doc spreadsheet\n log.info(\"Exporting Jenkins data to google spreadsheet\")\n g_sheet = GoogleSpreadSheetAPI(sheet_name=sheet_name, sheet_index=sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
findInstance() searchs for a term in a text and records the init ial and ending indices of that term if found in the text. This method returns a list of indices in a list where every two numb ers corresponds to the initial and ending indices of the search term respectively, e.g., if term="the" were found 3 times in a t...
def findInstance(self, text, term): indexList = set() index = 0 text = text.upper() term = " {0} ".format(term.upper()) # CALL THESE JUST ONCE BEFORE LOOP(S) add = indexList.add find = text.find # - - - - - - - - - - - - - - - - - - while True: index = find(term, index) if index == -1: ...
[ "def findAllInstances(text, term):\n index = 0 - len(term)\n text = text.lower()\n term = term.lower()\n try:\n while True:\n index = text.index(term, index + len(term))\n yield index\n except ValueError:\n pass", "def find(self, text, term):\n\t\tlistOfResults =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes the indices provided by findAll(), getTypesAndIndices(), and getDICECode() to get the appropriate strings from the text document. This method contains three submethods that create the excerpts, list the combo terms, and calculate the proximity of the combo terms within the combined kernels. This method returns a ...
def getExcerpts(self, text, DICECodeResults): """ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - """ def getKernels(indices): """ getKernels() is a sub-method that extracts strings from a doc- ument using indices provided by the DICECodeResults data struc- ture passed into thi...
[ "def getDICECode(self, typesAndIndicesResults):\n\n\t\tDICECodeResults = list()\n\t\ttypesList = [tuples[0] for tuples in typesAndIndicesResults]\n\n\t\ti = 0\n\n\t\t# CALL THESE JUST ONCE BEFORE LOOP(S)\n\t\tappend = DICECodeResults.append\n\t\t# - - - - - - - - - - - - - - - - - -\n\n\t\twhile i < len(typesAndInd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getKernels() is a submethod that extracts strings from a doc ument using indices provided by the DICECodeResults data struc ture passed into this submethod's parent method, getExcerpts(). This submethod returns three strings. indices > tuple containing indices in the document with text to extract.
def getKernels(indices): i = indices[0] j = indices[1] h = i - self.scope k = j + self.scope if h < 0: h = 0 if k > len(text): k = len(text)-1 return text[h:i].replace("\n", "__").replace("\t", " "), text[i:j].replace("\n", "__").replace("\t", " "), text[j:k].replace("\n", "__").replace("\t", "...
[ "def getExcerpts(self, text, DICECodeResults):\n\t\t\"\"\" - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \"\"\"\n\t\t\n\t\tdef getKernels(indices):\n\t\t\t\"\"\"\n\t\t\t\tgetKernels() is a sub-method that extracts strings from a doc-\n\t\t\t\tument using indices provided by the DICECodeResults...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getComboTerms() is a submethod that combines search terms and their indices provided in the tuple parameter into a string with
def getComboTerms(tuples): #return "[{0}]".format('; '.join(["({0})".format(','.join([text[indices[0]:indices[1]], str(indices[0])])) for indices in tuples])) return "{0}".format('; '.join(("{0}".format(text[indices[0]:indices[1]]) for indices in tuples)))
[ "def terms(self) -> Tuple[Term, ...]:\n ...", "def show_terms(concept, terms):\n st.subheader(concept)\n terms.sort()\n \n # Allow user to add/remove spelling variations\n selected = st.multiselect(\"Terms found in corpus\", terms, default=terms, key=concept + \"_ms\")\n selected.sort()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getProximity() is a submethod that calculates the distance of the search terms provided in the tuple parameter. This submethod returns an absolute value integer.
def getProximity(tuples): sortedIndices = [indices for indices in tuples] #return abs(sortedIndices[0][1] - sortedIndices[-1][0]) return sortedIndices[-1][0] - sortedIndices[0][1]
[ "def proximity(self) -> 'outputs.PreventionInspectTemplateInspectConfigRuleSetRuleHotwordRuleProximity':\n return pulumi.get(self, \"proximity\")", "def GPSProximity(coords1, coords2, units='miles'):\n from geopy.distance import vincenty as vc\n return vc(coords1, coords2).miles", "def proximity(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getDICECode() appends the DICE Code associated with the type in the typesAndIndicesResults variable, which comes from the getTypesAndIndices() method. This method returns a list of tuples
def getDICECode(self, typesAndIndicesResults): DICECodeResults = list() typesList = [tuples[0] for tuples in typesAndIndicesResults] i = 0 # CALL THESE JUST ONCE BEFORE LOOP(S) append = DICECodeResults.append # - - - - - - - - - - - - - - - - - - while i < len(typesAndIndicesResults): for DICECode...
[ "def getTypesAndIndices(self, findAllResults = None):\n\t\tresultsIndices = [i for i,j in findAllResults]\n\t\ttypesAndIndicesResults = list()\n\n\n\t\t#=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=#\n\t\t# (1) Iterate through the (INDEX, LOCATION) formatted tuple t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getType() iterates through the self.toTYPE variable to find a TYPE that matches the TERM in the terms variable. This method returns a list of types that could potentially match the terms variable.
def getType(self, terms): return [i for i in xrange(len(self.toTYPE)) if terms in self.toTYPE[i]]
[ "def types(self):\n return [term for term in self._terms\n if isinstance(term, (TypeIdentifier, String, Regex))]", "def get_type_term_set(self):\n term_set = self._term_set\n if term_set is None:\n term_set = set()\n type_tuples = self.get_type_tuples()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getTypesAndIndices() iterates through the results of findAll() and checks to see if they are within range of each other for TYPES that contain TERMS with more than one WORD (e.g., [W01, W02, etc.]). This method returns a list of tuples taking on the following struct
def getTypesAndIndices(self, findAllResults = None): resultsIndices = [i for i,j in findAllResults] typesAndIndicesResults = list() #=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=# # (1) Iterate through the (INDEX, LOCATION) formatted tuple to see what DICE Cod...
[ "def keywordTypes(self):\n\ti = 0\n\tkeyword_types = []\n\t\n\twhile True:\n\t keyword_type = libextractor.EXTRACTOR_getKeywordTypeAsString(i)\n\t if not keyword_type:\n\t\tbreak\n\t keyword_types.append(keyword_type)\n\t i += 1\n\t \n\treturn tuple(keyword_types)", "def get_accessibility_type_term...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isSufficient() compares terms in the searchkeywordsall.txt file, which contains relevant variants from the database, to the terms found in self.spreadsheet. A new kernel is built from the left kernel, center kernel, and right kernel from the self.spreadsheet data structure. dbPath > Location of the database file to che...
def isSufficient(self, dbPath = "L:\DICE Documents\JoshsAwesomeScript\search-keywords-all.txt"): keywords = self.openFile(dbPath) startClock = clock() print "[2A: KERNEL ]\tKernel building ...", kernel = self.buildKernel() print "Complete ({0} seconds)".format(round(clock() - startClock, 2)) # CALL THE...
[ "def dmg_freq_is_low(folder):\n total = 0.0\n for filename in (\"5pCtoT_freq.txt\", \"3pGtoA_freq.txt\"):\n if not os.path.exists(folder+\"/\"+filename):\n print(\"Error: Required table has not been created ('%s'), bayesian computation cannot be performed\" \\\n % filename)\n return True\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
isTermInRange() checks to see if the terms within the findAllResults variable are close enough to each other if there are multiple terms. If they are single terms, then the term is automatically indicated as being in range (i.e., return True). This method returns a tuple containing a boolean value indicating the term's...
def isTermInRange(self, findAllResults = None, terms = None): resultsIndices = [indices for indices,locations in findAllResults] resultsLocuses = [(i, findAllResults[i][1], "W{0}".format(str(resultsIndices[i]).zfill(2))) for i in xrange(len(findAllResults)) if resultsIndices[i] in terms] #resultsRanges = xrang...
[ "def _find_term(word_list, term_name):\n\n start = 0\n stop = len(word_list)\n term_name = term_name.lower()\n\n for i in range(len(word_list)):\n if word_list[i].lower() == term_name:\n start = i + 1\n elif start > 0 and i > start and word_list[i][0:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
reviseSpreadsheet() adds rows from getExcerptsResults as well as the document name in sourcDocumentName to the current spreadsheet. getExcerptsResults > results from the getExcerpts() method sourceDocumentName > name of the document analyzed with getExcerpts(). Typically following the format .txt.
def reviseSpreadsheet(self, getExcerptsResults, sourceDocumentName, sheet = 1): if self.spreadsheet_transposed: self.transpose(sheet) #=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*# # Iterate through the results to update/append the rows onto the spreadsheet varia...
[ "def write_reverted(self):\n reverted = revert(format_file(self.input_file))\n write(reverted, self.output_file)", "def edit_report(self):\n\n\t\t#Instantiates the rules engine class as a checker object with a\n\t\t#LAR schema, a TS schema, and geographic geographic data. \n\t\tchecker = rules_engin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the provided stack of images provided to the generator (screen) in a cv2 window with the provided window title. Args
def show_image(window_title = ''): while True: screen = (yield) window_title = window_title cv2.namedWindow(window_title, cv2.WINDOW_NORMAL) # stack each of the provided greyscale images horizontally. img = None for s in range(scre...
[ "def display_gui_window(self, window_title):\r\n cv2.imshow(window_title, self.image)", "def show(self, I, title=''):\n cv2.imshow(title, I)\n cv2.waitKey(0)\n cv2.destroyAllWindows() \n return()", "def show(im, title = 'none'):\n\tif title == 'none':\n\t\tframe = inspect.curr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a value and a set of cutoffs returns the percentile within which the value lies
def compute_percentile(value, cutoffs): if value < cutoffs[0]: return 0.0 for i, cutoff in enumerate(cutoffs): if value < cutoff: return math.floor(100 * (float(i)/(len(cutoffs)))) break return 100.0
[ "def percentile(values, percent):\n if not values:\n return\n\n k = (len(values)-1) * percent\n f = math.floor(k)\n c = math.ceil(k)\n if f == c:\n return values[int(k)]\n d0 = values[int(f)] * (c-k)\n d1 = values[int(c)] * (k-f)\n return d0+d1", "def percentile(self, values, p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a schema with a dataset this function reads in the numeric fields and computes the percentile cutoffs for the numerric fields. It appends this information to the schema and returns it.
def compute_schema_percentiles(schema): values = {} schemaFields = schema["fields"] for field in schemaFields: if schemaFields[field]["type"] == FIELD_TYPE_NUMERIC: values[field] = [] if(len(values) == 0): return schema def processRow(row, schemaFields, values): # cache the values for numerics for field...
[ "def df_percentile_calculator(data_frame, start_percent, celltype=None, define_percentile=False):\n if define_percentile:\n column_label = \"Percentile {}\".format(start_percent)\n else:\n column_label = \"Percentile_col\"\n if celltype is not None:\n data_frame[column_label] = np.perc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads the sentences for the given schema and passes them back to the callback function in the object given to the callback each field (key) maps to a set of sentences
def read_sentences(schema, callback, update_message=None): path = sentence_file_path(schema) with open(path, "r") as f: i = 0 while True: l = f.readline() i = i+1 if not l: break callback(json.loads(l.rstrip())) if(update_message and i%1000 == 0): print update_message + " " + str(i)
[ "def build_sentences(schema):\n\twith open(sentence_file_path(schema), \"w\") as output:\n\t\tdef processKeyValue(keyValue, output, schema):\n\t\t\tsentencesByKey = {}\n\t\t\tfor key in keyValue:\n\t\t\t\twords = generate_field_features(schema, key, keyValue[key])\n\t\t\t\tif(len(words)):\n\t\t\t\t\tsentencesByKey[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a sentence file for the schema.
def build_sentences(schema): with open(sentence_file_path(schema), "w") as output: def processKeyValue(keyValue, output, schema): sentencesByKey = {} for key in keyValue: words = generate_field_features(schema, key, keyValue[key]) if(len(words)): sentencesByKey[key] = words output.write(json.du...
[ "def generate_sentence(self, sentences):\n normalcase_tokens = [x.text for x in self.nlp.tokenizer(sentences)]\n truecase_sentence = self._get_true_case(normalcase_tokens)\n truecase_sentence = ' '.join(truecase_sentence)\n return truecase_sentence", "def generate_sentence(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a set of raw key values read from base data returns a sentence which can be fed to a Word2Vec model
def convert_key_value_to_sentence(schema, keyValues, fieldsToRead): features = [] for field in fieldsToRead: value = keyValues[field] features += generate_field_features(schema,field, value) return features
[ "def generate_sentence(word1, word2, length, vocab, model):\n reverse_vocab = {idx: word for word, idx in vocab.items()}\n output_string = np.zeros((1, length), dtype=np.int)\n output_string[:, 0: 2] = vocab[word1], vocab[word2]\n\n for end in range(2, length):\n start = end - 2\n output_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a keyValue where values are already sentences (keyed by field) it converts the input into a single sentence by pulling fields from fieldsToRead
def merge_sentences_to_single_sentence(keyValue, fieldsToRead): ret = [] for field in fieldsToRead: if(field in keyValue): ret += keyValue[field] return ret
[ "def convert_key_value_to_sentence(schema, keyValues, fieldsToRead):\n\tfeatures = []\n\tfor field in fieldsToRead:\n\t\tvalue = keyValues[field]\n\t\tfeatures += generate_field_features(schema,field, value)\n\treturn features", "def build_sentences(schema):\n\twith open(sentence_file_path(schema), \"w\") as outp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a schema and vectorSize trains the model.
def train_model(schema,fieldsToRead = None): if not fieldsToRead: fieldsToRead = schema["fields"].keys() if("vector_size" in schema): vectorSize = schema["vector_size"] else: vectorSize = DEFAULT_VECTOR_SIZE sentences = [] # build sentences: print "Building Feature vectors..." read_sentences(schema, lam...
[ "def setUp(self):\n super(VectorWeightedAdditionTest, self).setUp()\n self._comp_model = VectorWeightedAddition(embedding_size=2)", "def fit(self, vectors):\n self.vectors = vectors", "def train(self, input_vects):\n \n #Training iterations\n for iter_no in range(self._n_itera...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots the first 100 word vectors for the given model
def plot_schema_vectors(schema, model): vectorList = map(lambda x : x.rstrip().split(' ')[0], open(weight_matrix_path(schema), "r").readlines())[1:] words = vectorList[:500] if(len(model[words[0]]) != 2): print "Vectors must be of dimension 2 to plot! ... Aborting (vector dim is : " + str(len(model[words[0]])) +...
[ "def plot_embeddings(M_reduced, word2Ind, words):\n\n # YOUR CODE HERE\n \n for i,type in enumerate(words):\n x_coor,y_coor = M_reduced[word2Ind[type]][0],M_reduced[word2Ind[type]][1]\n \n plt.scatter(x_coor, y_coor, marker='*', color='red')\n plt.text(x_coor+0.05, y_coor+0.05, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the list of snippets in this document, as a TagQuery.
def snippets(self): queries = [] from tagged_document import TagQuery # start with a version of ourself that has no expanded snippets source_lines = self.cleaned_contents.split("\n") # the list of lines we're working with output_lines = [] # default to workin...
[ "def snippets_by_tag(request, slug):\n tag = get_object_or_404(Tag, slug__exact=slug)\n return list_detail.object_list(request,\n queryset=Snippet.objects.get_by_tag(slug),\n extra_context={ 'object': tag },\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the set of all tags referred to in this document.
def tags_used(self): return set([query.all_referenced_tags for query in self.snippets])
[ "def tags(self):\n tag_docs = self.tag_data\n tags = set([x[\"tag\"] for x in tag_docs])\n # remove the \"thawed\" tag\n tags.discard(\"thawed\")\n return tags", "def collect_tags(self):\n tags = []\n for document in self.documents:\n for tag_token in do...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shift the matrix M in upleft and upright directions and count the ones in the overlapping zone.
def shift_and_count(x_shift, y_shift, M, R): left_shift_count, right_shift_count = 0, 0 for r_row, m_row in enumerate(range(y_shift, dim)): for r_col, m_col in enumerate(range(x_shift, dim)): if M[m_row][m_col] == 1 and M[m_row][m_col] == R[r_row][r_col]: ...
[ "def shift_and_count(x_shift, y_shift, M, R):\n A, B = 0, 0\n for r_row, m_row in enumerate(range(y_shift, n)): # r_row, r_col is the reference, always starting from 0\n for r_col, m_col in enumerate(range(x_shift, n)):\n A += (M[m_row][m_col] == R[r_row][r_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }