query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
The collection of associated Private Endpoint Connections.
def private_endpoint_connections(self) -> Sequence['outputs.PrivateEndpointConnectionDataModelResponse']: return pulumi.get(self, "private_endpoint_connections")
[ "def get_connections(self):\n return self.connections", "def list_connections(self):\n path = self.build_url(\"/connections\")\n return self.request('get', path)", "def endpoints(self) -> object:\n return self._endpoints", "def list_connections(self):\n\t\treturn dict((conn.con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Guid id of the private link scope.
def private_link_scope_id(self) -> str: return pulumi.get(self, "private_link_scope_id")
[ "def GUID(self) -> _n_2_t_0:", "def block_id(self):\n return str(self.scope_ids.usage_id)", "def access_group_id(self) -> str:\n return pulumi.get(self, \"access_group_id\")", "def url_id(self):\n return self.id", "def scope_map_id(self) -> Optional[str]:\n return pulumi.get(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The country or region where the resource is located
def country_or_region(self) -> Optional[str]: return pulumi.get(self, "country_or_region")
[ "def this_region(self):\n _logger.debug('%s', where_am_i())\n if self._metadata is None:\n _logger.warning('metadata is None !')\n # TODO: should it severe error case instead ??\n return None\n try:\n return self._metadata['instance']['region']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The district, state, or province where the resource is located.
def district(self) -> Optional[str]: return pulumi.get(self, "district")
[ "def state_or_province(self):\n return self._state_or_province", "def location(self):\n return self.patient.get('location', None)", "def district_or_county(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"district_or_county\")", "def get_district(self):\n for p in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The machine extension instance view.
def instance_view(self) -> Optional['outputs.MachineExtensionInstanceViewResponse']: return pulumi.get(self, "instance_view")
[ "def instance_view(self) -> Optional['outputs.VirtualMachineExtensionInstanceViewResponse']:\n return pulumi.get(self, \"instance_view\")", "def inspect_view(self, request, instance_pk):\n kwargs = {\"model_admin\": self, \"instance_pk\": instance_pk}\n view_class = self.inspect_view_class\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Specifies the assessment mode.
def assessment_mode(self) -> Optional[str]: return pulumi.get(self, "assessment_mode")
[ "def set_mode(self, mode):\n self._mode = mode", "def set_ai(self):\n difficulty = self.difficulty()\n if difficulty == \"easy\":\n self._ai = EasyMode()\n elif difficulty == \"medium\":\n self._ai = MediumMode()\n elif difficulty == \"hard\":\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Specifies the patch mode.
def patch_mode(self) -> Optional[str]: return pulumi.get(self, "patch_mode")
[ "def set_mode(self, mode):\n self._mode = mode", "def set_reference_mode(self, mode='ext'):\n if mode == 'ext':\n self.write(\"FMOD 0\")\n else:\n self.write(\"FMOD 1\")", "def _change_mode(self, attr, old, new):\n self.exg_mode = new", "def patch(self, patch)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Specifies the assessment mode.
def assessment_mode(self) -> Optional[str]: return pulumi.get(self, "assessment_mode")
[ "def set_mode(self, mode):\n self._mode = mode", "def set_ai(self):\n difficulty = self.difficulty()\n if difficulty == \"easy\":\n self._ai = EasyMode()\n elif difficulty == \"medium\":\n self._ai = MediumMode()\n elif difficulty == \"hard\":\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Specifies the patch mode.
def patch_mode(self) -> Optional[str]: return pulumi.get(self, "patch_mode")
[ "def set_mode(self, mode):\n self._mode = mode", "def set_reference_mode(self, mode='ext'):\n if mode == 'ext':\n self.write(\"FMOD 0\")\n else:\n self.write(\"FMOD 1\")", "def _change_mode(self, attr, old, new):\n self.exg_mode = new", "def patch(self, patch)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Private Endpoint Connection properties.
def properties(self) -> Optional['outputs.PrivateEndpointConnectionPropertiesResponse']: return pulumi.get(self, "properties")
[ "def private_endpoint_connections(self) -> Sequence['outputs.PrivateEndpointConnectionDataModelResponse']:\n return pulumi.get(self, \"private_endpoint_connections\")", "def private_interconnect_infos(self) -> pulumi.Output[Sequence['outputs.InterconnectAttachmentPrivateInterconnectInfo']]:\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List of group IDs.
def group_ids(self) -> Sequence[str]: return pulumi.get(self, "group_ids")
[ "def group_ids(self):\n if hasattr(self, '_group_ids'):\n return self._group_ids\n d = self.allele_and_contig_pairs_to_unique_ids()\n return [\n d[(allele, contig)]\n for (allele, contig)\n in zip(self.alleles, self.contigs)\n ]", "def all_se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The state of the guest configuration service on the Arcenabled machine.
def guest_configuration_service(self) -> Optional['outputs.ServiceStatusResponse']: return pulumi.get(self, "guest_configuration_service")
[ "def state(self):\n ret = self._get_attr(\"state\")\n return GuestUserState(ret)", "def status(self):\n ret = self._get_attr(\"status\")\n return GuestSessionStatus(ret)", "def device_state_attributes(self):", "def state(self):\n if self.device.vacuum_status is not None and ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the self.y value of the Raindrop down the screen (y increase) at the self.speed.
def move(self): # TODO 11: Change the y position of this Raindrop by its speed. pass
[ "def update(self):\n self.y += (self.settings.alien_speed * self.settings.alien_direction)\n self.rect.y = self.y", "def update_y(self) -> None:\n self.y_vel += self.gravity\n self.position.y += self.y_vel", "def move(self):\n self.tick_count += 1\n\n # equation for dis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the Raindrop y value is not shown on the screen, otherwise false.
def off_screen(self): # Note: this will be used for testing, but not used in the final version of the code for the sake of simplicity. # TODO 13: Return True if the y position of this Raindrop is greater than 800. pass
[ "def y_axis_visibility(self) -> bool:\n return bool(self.GetYAxisVisibility())", "def loses(self):\n return not (-2.5 < self.x < 2.5 and -0.262 < self.phi < 0.262)", "def y_label_visibility(self) -> bool:\n return self._y_label_visibility", "def at_top(self) -> bool:\n return self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given raindrop is hitting this Hero, otherwise false.
def hit_by(self, raindrop): # TODO 19: Return True if this Hero is currently colliding with the given Raindrop. pass
[ "def inside_target(self, shot_coordinates):\n\n #checking distance\n dist = cv2.pointPolygonTest(self.t_points,(shot_coordinates[0], shot_coordinates[1]),True)\n\n #if distance is 0 or more, shot is inside the target\n if dist >= 0:\n self.update_target(shot_coordinates)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Cloud sprite that will produce Raindrop objects. The cloud will be moving around.
def __init__(self, screen, x, y, image_filename): # TODO 24: Initialize this Cloud, as follows: # TODO - Store the screen. # TODO - Set the initial position of this Cloud to x and y. # TODO - Set the image of this Cloud to the given image filename. # TODO - Create a l...
[ "def rain(self):\n # TODO 28: Append a new Raindrop to this Cloud's list of Raindrops,\n # TODO where the new Raindrop starts at:\n # TODO - x is a random integer between this Cloud's x and this Cloud's x + 300.\n # TODO - y is this Cloud's y + 100.\n pass", "def cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a Raindrop to the array of raindrops so that it looks like the Cloud is raining.
def rain(self): # TODO 28: Append a new Raindrop to this Cloud's list of Raindrops, # TODO where the new Raindrop starts at: # TODO - x is a random integer between this Cloud's x and this Cloud's x + 300. # TODO - y is this Cloud's y + 100. pass
[ "def create_rain(settings, screen, raindrops, x):\n raindrop = Raindrop(settings, screen)\n raindrop.rect.x = x\n raindrops.add(raindrop)\n print(len(raindrops))", "def drop_rain(settings, screen, raindrops):\n if len(raindrops) >= 20:\n print(\"were in here\")\n raindrops.update()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs a semantic fusion unit on the input vector and the fusion vectors to produce an output.
def semantic_fusion(input_vector, input_dim, fusion_vectors, scope): with tf.variable_scope(scope): assert len(fusion_vectors) > 0 stacked_vectors = tf.concat(fusion_vectors + [input_vector], axis=-1) # size = [batch_size, ..., input_dim * (len(fusion_vectors) + 1)] num_total_vectors = len(f...
[ "def infer_vector(self, text):\n raise NotImplementedError", "def _conv2d_compute_fusion_para(inputs):\r\n input_memory_type = inputs.op.attrs[\"addr_type\"].value \\\r\n if \"addr_type\" in inputs.op.attrs else 0\r\n valid_shape = inputs.op.attrs[\"valid_shape\"] \\\r\n if \"valid_shap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds a shortest path from start to end using the provided edges
def shortest_path(edges, start, end): # generate the graph graph = {} for edge in edges: s = edge['start'] e = edge['end'] if s in graph: graph[s].append(e) else: graph[s] = [e] # build up a queue for BFS path_total = [] # append initial no...
[ "def shortest_path_no_lefts(edges, start, end):\n # build up the graph; the key is an edge, the value is a list of edges connecting to it\n graph = {}\n current_start_nodes = {}\n current_end_nodes = {}\n for edge in edges:\n s = edge['start']\n e = edge['end']\n # v1 = (e[0] - s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds a shortest path without any left turns that goes from start to end using the provided edges. (reversing turns are also not allowed)
def shortest_path_no_lefts(edges, start, end): # build up the graph; the key is an edge, the value is a list of edges connecting to it graph = {} current_start_nodes = {} current_end_nodes = {} for edge in edges: s = edge['start'] e = edge['end'] # v1 = (e[0] - s[0], e[1] - s...
[ "def shortest_path(edges, start, end):\n # generate the graph\n graph = {}\n for edge in edges:\n s = edge['start']\n e = edge['end']\n if s in graph:\n graph[s].append(e)\n else:\n graph[s] = [e]\n # build up a queue for BFS\n path_total = []\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds a shortest path with no more than k left turns that goes from start to end using the provided edges. (reversing turns are also not allowed)
def shortest_path_k_lefts(edges, start, end, k): # build up the graph; the key is an edge, the value is a list of edges connecting to it graph = {} current_start_nodes = {} current_end_nodes = {} for edge in edges: s = edge['start'] e = edge['end'] # v1 = (e[0] - s[0], e[1] -...
[ "def shortest_path_no_lefts(edges, start, end):\n # build up the graph; the key is an edge, the value is a list of edges connecting to it\n graph = {}\n current_start_nodes = {}\n current_end_nodes = {}\n for edge in edges:\n s = edge['start']\n e = edge['end']\n # v1 = (e[0] - s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In entries, find one that matches the name. Name can be prefixed with scope, in the format of "scope.name". There must be only one matching entry.
def _find_entry(self, entries, name): scope, _, name = name.rpartition('.') matching_entries = [ entry for entry in entries if entry.name == name and (not scope or entry.scope == scope)] if not matching_entries: raise NotFoundError(name) if...
[ "def ls_entry_by_name(entries, name):\n return next(e for e in entries if os.path.basename(os.path.normpath(e['path'])) == name)", "def find_by_name(self, name_prefix):\n for project in self:\n if project['name'].startswith(name_prefix):\n return project\n return None", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test matrix square root
def test_sqrtm(): C = 2*np.eye(3) Ctrue = np.sqrt(2)*np.eye(3) assert_array_almost_equal(sqrtm(C), Ctrue)
[ "def test_sqrtm(self):\n\n matrices = jax.random.normal(self.rng, (self.batch, self.dim, 2 * self.dim))\n\n for x in (matrices, matrices[0, :, :]): # try with many and only one.\n x = jnp.matmul(x, jnp.swapaxes(x, -1, -2))\n threshold = 1e-4\n\n sqrt_x, inv_sqrt_x, errors = matrix_square_root....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates Lambda deployment package
def build_lambda(): try: os.system("mkdir -p ./build") os.system("cp -r ./lambda ./build") os.system("pip3 install -r ./build/lambda/requirements.txt -t ./build/lambda") shutil.make_archive("./build/lambda", 'zip', "./build/lambda") os.system("rm -rf ./build/lambda") ...
[ "def _generate_lambda(appName, _lambda, roleARN, config, projPath):\n\n if( not os.path.exists(projPath+'/.tmp') ):\n os.mkdir(projPath+'/.tmp')\n\n if( not os.path.isfile(projPath+'/.tmp/dist.zip') ):\n AWSSetup._compress_app_package(\n projPath+'/.tmp/dist',\n projPath+'/.tmp/dist.zi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uploads Lambda deployment package to S3
def upload_lambda(): s3 = session.resource('s3') try: s3.Bucket(f"lambda-source-{os.environ['AWS_ACCOUNT']}").upload_file('./build/lambda.zip', 'lambda.zip') print("Lambda deployment package uploaded to S3!") except Exception as e: print(f"Error uploading deployment package. Excep...
[ "def _deploy_to_s3():\n s3cmd = 's3cmd -P --add-header=Cache-Control:max-age=5 --guess-mime-type --recursive --exclude-from gzip_types.txt put gzip/ %s'\n s3cmd_gzip = 's3cmd -P --add-header=Cache-Control:max-age=5 --add-header=Content-encoding:gzip --guess-mime-type --recursive --exclude \"*\" --include-from...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publishes a new Lambda version
def update_lambda(): client = session.client('lambda') try: client.update_function_code( FunctionName='process_csv', S3Key='lambda.csv', S3Bucket=f"lambda-source-{os.environ['AWS_ACCOUNT']}", Publish=True ) print("Lambda function publishe...
[ "def upload_lambda():\n\n s3 = session.resource('s3')\n\n try:\n s3.Bucket(f\"lambda-source-{os.environ['AWS_ACCOUNT']}\").upload_file('./build/lambda.zip', 'lambda.zip')\n print(\"Lambda deployment package uploaded to S3!\")\n\n except Exception as e:\n print(f\"Error uploading deploy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates S3 Bucket for Lambda source code
def create_bucket(): s3 = session.resource('s3') try: s3.create_bucket(Bucket=f"lambda-source-{os.environ['AWS_ACCOUNT']}", ACL='private') print('Created S3 bucket!') except Exception as e: print(f"Error creating S3 bucket. Exception: {e}.")
[ "def create_bucket(self):\n AWSApi.instance().s3.create_bucket(bucket_name=self.name, region=self.region)", "def bucket_create():\r\n conn = connect_s3()\r\n bucket = conn.create_bucket(BUCKET_NAME, policy='public-read')\r\n bucket.configure_website('index.html', 'error.html')\r\n print 'Bucket...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes S3 Bucket for Lambda source code
def delete_bucket(): s3 = session.resource('s3') try: bucket = s3.Bucket(f"lambda-source-{os.environ['AWS_ACCOUNT']}") bucket.objects.all().delete() bucket.delete() print('Deleted S3 bucket!') except Exception as e: print(f"Error deleting S3 bucket. Exception: {e}....
[ "def bucket_delete():\r\n if not confirm(\"Are you sure you want to delete the bucket %r?\" % BUCKET_NAME):\r\n abort('Aborting at user request.')\r\n conn = connect_s3()\r\n conn.delete_bucket(BUCKET_NAME)\r\n print 'Bucket %r deleted.' % BUCKET_NAME", "def delete_bucket(self):\n self.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
y = getitem(x, sl)
def pb___getitem__(cls, ybar, x, sl, y, out = None): if out == None: raise NotImplementedError('I\'m not sure that this makes sense') # workaround for qr and eigh if isinstance( out[0], tuple): tmp = list(out[0]) tmp[sl] += ybar # usual workflow ...
[ "def get(self, x, y):\n return self.data[(y * self.sx) + x]", "def __getitem__(self,j):\r\n return self._coords[j]", "def get_item(self, identifier):", "def __getitem__(self, item):\n if isinstance(item, tuple):\n if len(item) != 3:\n raise KeyError(f\"Tuple item...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tries to convert a container (e.g. list or numpy.array) with UTPM elements as instances to a UTPM instance
def as_utpm(cls, x): x_shp = numpy.shape(x) xr = numpy.ravel(x) D,P = xr[0].data.shape[:2] shp = xr[0].data.shape[2:] if not isinstance(shp, tuple): shp = (shp,) if not isinstance(x_shp, tuple): x_shp = (x_shp,) y = UTPM(numpy.zeros((D,P) + x_shp + shp)) ...
[ "def _convert_seq(sequence, new_class):\n return [new_class(obj) for obj in sequence]", "def _element_to_serializable(obj: Any) -> Any:\n if isinstance(obj, bytes):\n obj = obj.decode('utf-8')\n\n elif isinstance(obj, np.generic):\n obj = obj.item()\n\n return obj", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
operation to extract UTP coefficients of x defined by the slice sl creates a new UTPM instance where the coefficients have the shape as defined by shp
def coeff_op(self, sl, shp): tmp = self.data.__getitem__(sl) tmp = tmp.reshape(shp) return self.__class__(tmp)
[ "def as_utpm(cls, x):\n\n x_shp = numpy.shape(x)\n xr = numpy.ravel(x)\n D,P = xr[0].data.shape[:2]\n shp = xr[0].data.shape[2:]\n\n if not isinstance(shp, tuple): shp = (shp,)\n if not isinstance(x_shp, tuple): x_shp = (x_shp,)\n\n y = UTPM(numpy.zeros((D,P) + x_shp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes y = hyp1f1(a, b, x) in UTP arithmetic
def hyp1f1(cls, a, b, x): retval = x.clone() cls._hyp1f1(a, b, x.data, out = retval.data) return retval
[ "def hyp1f1(a, b, z):\n #global mp\n uselib = lib is not None and not use_mpmath\n #if not uselib and mp is None:\n # mp = __import__(\"mpmath\")\n\n p = PrmsAndInfo(c_int(max_iter), c_double(tol), c_int(0), c_double(0), c_int(0))\n if (np.ndim(a) + np.ndim(b) + np.ndim(z) > 1):\n l = [l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes y = hyperu(a, b, x) in UTP arithmetic
def hyperu(cls, a, b, x): retval = x.clone() cls._hyperu(a, b, x.data, out = retval.data) return retval
[ "def h( self , x , u , t ):\n \n #y = np.zeros(self.p) # Output vector\n \n y = self.sys.h( x , self.sys.ubar , t )\n \n return y", "def solve_U(U, b):\n m, k = b.shape\n x = np.zeros((m,k))\n x[-1,:] = b[-1,:] / U[-1,-1]\n for i in range(m-2,-1,-1):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes y = botched_clip(a_min, a_max, x) in UTP arithmetic
def botched_clip(cls, a_min, a_max, x): retval = x.clone() cls._botched_clip(a_min, a_max, x.data, out = retval.data) return retval
[ "def clip(x:T, minvalue:T, maxvalue:T) -> T:\n if x < minvalue:\n return minvalue\n elif x < maxvalue:\n return x\n return maxvalue", "def clip(x, min=0, max=1):\n return np.clip(x.obs, min, max)", "def clip_image(image, clip_min, clip_max):\n return np.minimum(np.maximum(clip_min, im...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes y = hyp2f0(a1, a2, x) in UTP arithmetic
def dpm_hyp2f0(cls, a1, a2, x): retval = x.clone() cls._dpm_hyp2f0(a1, a2, x.data, out = retval.data) return retval
[ "def h( self , x , u , t ):\n \n #y = np.zeros(self.p) # Output vector\n \n y = self.sys.h( x , self.sys.ubar , t )\n \n return y", "def hypothenuse(a, b):\n return sqrt(a*a + b*b)", "def _hyp2f1_dlmf1583_first(a_i, b_i, a_j, b_j, y, mu):\n\n a = a_j\n c = a_j ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes y = hyp2f0(a1, a2, x) in UTP arithmetic
def hyp2f0(cls, a1, a2, x): retval = x.clone() cls._hyp2f0(a1, a2, x.data, out = retval.data) return retval
[ "def h( self , x , u , t ):\n \n #y = np.zeros(self.p) # Output vector\n \n y = self.sys.h( x , self.sys.ubar , t )\n \n return y", "def hypothenuse(a, b):\n return sqrt(a*a + b*b)", "def _hyp2f1_dlmf1583_first(a_i, b_i, a_j, b_j, y, mu):\n\n a = a_j\n c = a_j ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes y = hyp0f1(b, x) in UTP arithmetic
def hyp0f1(cls, b, x): retval = x.clone() cls._hyp0f1(b, x.data, out = retval.data) return retval
[ "def h( self , x , u , t ):\n \n #y = np.zeros(self.p) # Output vector\n \n y = self.sys.h( x , self.sys.ubar , t )\n \n return y", "def _h_function(self,h):\n return self.contribution * np.exp(-1.0 * h / self.a)", "def hyperbolic_tangent(a, b, prime_offset=0.0, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes y = polygamma(n, x) in UTP arithmetic
def polygamma(cls, n, x): retval = x.clone() cls._polygamma(n, x.data, out = retval.data) return retval
[ "def polyfunc(x, *p):\n y = 0\n for n, P in enumerate(p):\n y += P * x ** n\n return y", "def polynomial():\n np.random.seed(42)\n input_data = 10 * np.random.rand(30)\n y = (\n 5 * input_data +\n 2.0 * input_data ** 2 +\n 7 +\n 10 * np.random.randn(len(input_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes y = reciprocal(x) in UTP arithmetic
def reciprocal(cls, x): retval = x.clone() cls._reciprocal(x.data, out = retval.data) return retval
[ "def reciprocal(self):\n\n value = -1 / (self.val * self.val)\n der = {k: value * v for k, v in self.der.items()}\n return AutoDiff(self.var, 1 / self.val, der)", "def GetReciprocal(self) -> \"itkVersorD\":\n return _itkVersorPython.itkVersorD_GetReciprocal(self)", "def reciprocal(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
inverse operation of FtoJT x.data.shape = (D,1, P,shp) y = x.JTtoF() y.data.shape = (D+1, P, shp)
def JTtoF(self): D = self.data.shape[0] P = self.data.shape[2] shp = self.data.shape[3:] tmp = numpy.zeros((D+1,P) + shp) tmp[0:D,...] = self.data.reshape((D,P) + shp) return UTPM(tmp)
[ "def jonswap(f,Hm0,Tp,\n g = 9.81,\n gamma = 3.3, \n method = 'Yamaguchi', \n normalize = True,\n sa = 0.07,\n sb = 0.09):\n \n # method = 'Yamaguchi'; # 'Goda' \n\n def sigma(f,fpeak,sa,sb):\n s = np.ones(f.size)*sa\n s[f > fpeak] = sb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new UTPM instance with the same data. `clone` is opposed to `copy` or `deepcopy` by calling the __init__ function.
def clone(self): return UTPM(self.data.copy())
[ "def create_copy(self):\n print('WARNING: Implementation and testing still in progress!!!!')\n\n new_obj = self.__class__()\n new_obj.data = copy.deepcopy(self.data)\n new_obj.topography = copy.deepcopy(self.topography)\n new_obj.electrode_positions = copy.deepcopy(\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initializes this UTPM instance to compute the Jacobian, it is possible to force the dtype to a certain dtype, if no dtype is provided, the dtype is inferred from x
def init_jacobian(cls, x, dtype=None): x = numpy.asarray(x) if dtype==None: # try to infer the dtype from x dtype= x.dtype if dtype==int: dtype=float shp = numpy.shape(x) data = numpy.zeros(numpy.hstack( [2, numpy.size(x), shp]), d...
[ "def jacobian(\n self, t: float, state: np.ndarray, u: np.ndarray) -> np.ndarray:\n pass", "def init_jac_vec(cls, x, v, dtype=None):\n\n x = numpy.asarray(x)\n\n if dtype==None:\n # try to infer the dtype from x\n dtype= x.dtype\n\n if dtype==int:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initializes this UTPM instance to compute the Jacobian vector product J v, it is possible to force the dtype to a certain dtype, if no dtype is provided, the dtype is inferred from x
def init_jac_vec(cls, x, v, dtype=None): x = numpy.asarray(x) if dtype==None: # try to infer the dtype from x dtype= x.dtype if dtype==int: dtype=float shp = numpy.shape(x) data = numpy.zeros(numpy.hstack( [2, 1, shp]), dtype=dtype...
[ "def init_jacobian(cls, x, dtype=None):\n\n x = numpy.asarray(x)\n\n if dtype==None:\n # try to infer the dtype from x\n dtype= x.dtype\n\n if dtype==int:\n dtype=float\n\n\n shp = numpy.shape(x)\n data = numpy.zeros(numpy.hstack( [2, numpy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initializes this UTPM instance to compute the Hessian
def init_hessian(cls, x): x = numpy.ravel(x) # generate directions N = x.size M = (N*(N+1))/2 L = (N*(N-1))/2 S = numpy.zeros((N,M), dtype=x.dtype) s = 0 i = 0 for n in range(1,N+1): S[-n:,s:s+n] = numpy.eye(n) S[-n,s:s+n...
[ "def build_hessian(self,x,y):\n #Precalculate entries of hessian\n x_sum = np.sum(x)\n x_squared_sum = np.sum(x*x)\n y_sum = np.sum(y)\n y_squared_sum = np.sum(y*y)\n xy_sum = np.sum(x*y)\n n = len(x)\n\n hessian = np.array([\n [n,0,x_sum,y_sum,0,0]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extracts the Hessian of shape (N,N) from the UTPM instance y
def extract_hessian(cls, N, y, as_full_matrix = True, use_mpmath=False): if use_mpmath: import mpmath mpmath.dps = 50 H = numpy.zeros((N,N),dtype=y.data.dtype) for n in range(N): for m in range(n): a = sum(range(n+1)) b = s...
[ "def build_hessian(self,x,y):\n #Precalculate entries of hessian\n x_sum = np.sum(x)\n x_squared_sum = np.sum(x*x)\n y_sum = np.sum(y)\n y_squared_sum = np.sum(y*y)\n xy_sum = np.sum(x*y)\n n = len(x)\n\n hessian = np.array([\n [n,0,x_sum,y_sum,0,0]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a full symmetric matrix filled the distinct elements of v, filled rowwise
def vecsym(cls, v): D,P = v.data.shape[:2] Nv = v.data[0,0].size tmp = numpy.sqrt(1 + 8*Nv) if abs(int(tmp) - tmp) > 1e-16: # hackish way to check that the input length of v makes sense raise ValueError('size of v does not match any possible symmetric matrix') ...
[ "def fill_diagonal(self, v: 'int const &') -> \"vnl_diag_matrixSI &\":\n return _vnl_diag_matrixPython.vnl_diag_matrixSI_fill_diagonal(self, v)", "def vector_to_matrix(v):\r\n if not (np.sqrt(8 * v.shape[0] + 1) == int(np.sqrt(8 * v.shape[0] + 1))):\r\n print(\"ERROR: Can not make a square matrix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import public keys of a friend (receiver) into the PKFernet object's. The receiver_public_keyring dictionary object can contain public keys for multiple receivers, but this method will only import the keys associated with the receiver_name parameter.
def import_pub_keys(self, receiver_name, receiver_public_keyring): self.public_keys[receiver_name] = receiver_public_keyring[receiver_name]
[ "def import_key_pair(DryRun=None, KeyName=None, PublicKeyMaterial=None):\n pass", "def sync(self, ask_anyway=False):\n info = {}\n added = []\n crypto = self.crypto\n\n first = True\n while first or (ask_anyway or not crypto.can_encrypt):\n first = False\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform the coordinate to agentcentric. Input state tensor is of size (batch_size, state_length) 'px', 'py', 'vx', 'vy', 'gx', 'gy', 'px1', 'py1', 'vx1', 'vy1', 'radius1' 0 1 2 3 4 5 6 7 8 9 10
def rotate(state): size = state.shape # (100, 20, 11) last_dim = len(size) - 1 # 3 dx = state[..., 4] - state[..., 0] # (100, 20) dy = state[..., 5] - state[..., 1] rot = torch.atan2(dy, dx) # (100, 20) dg = torch.norm(torch.cat([dx.unsqueeze(dim = last_dim), dy.unsqueeze(dim = last_dim)], d...
[ "def discretize_state(self, state):\n x, x_dot, phi, phi_dot = state\n if x > 1.:\n x = 1\n elif x < -1.:\n x = -1\n else: \n x = 0\n\n if x_dot < -0.1:\n x_dot = -2\n elif x_dot > 0.1:\n x_dot = 2\n elif x_dot <...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dataframe containing the path to each different picture. Two pictures are considered the same if they have the same file name (image id).
def get_list_image_file(path_to_root_dir): dictionary = {} for filename in glob.iglob(path_to_root_dir + '/**/*.jpg', recursive=True): file_without_jpg = os.path.basename(filename).replace(".jpg", '') dictionary[int(file_without_jpg)] = os.path.abspath(filename) df_filepath = pd.DataFrame(...
[ "def get_image_df(image_path, df):\n image = process_image(image_path)\n return image, df", "def build_hash_to_image_dataframe(self):\n\n # df_hashes's columns: file, hash, hash_list\n # file -> image's file path\n # hash -> hash code associated to image\n # hash_list -> list of all ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reshapes the Keras model weight as a vector.
def model_weights_as_vector(model): weights_vector = [] for layer in model.layers: # model.get_weights(): if layer.trainable: layer_weights = layer.get_weights() for l_weights in layer_weights: vector = numpy.reshape(l_weights, newshape=(l_weights.size)) ...
[ "def flatten_weights(model, numpy_output: bool = True):\n all_params = []\n for param in model.parameters():\n all_params.append(param.view(-1))\n all_params = torch.cat(all_params)\n if numpy_output:\n return all_params.cpu().detach().numpy()\n return all_params", "def _reshape_weigh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the initial population of the genetic algorithm as a list of networks' weights (i.e. solutions). Each element in the list holds a different weights of the Keras model. The method returns a list holding the weights of all solutions.
def create_population(self): model_weights_vector = model_weights_as_vector(model=self.model) net_population_weights = [] net_population_weights.append(model_weights_vector) for idx in range(self.num_solutions-1): net_weights = copy.deepcopy(model_weights_vector)...
[ "def compute_weights(self) -> list:\n weights = []\n for num in self.population:\n # Our purpose: find x with fitness value near 0 as much as possible\n # So if abs(x) is large, negative of it (weight) will be small\n weights.append(0 - abs(self.equation(num+self.offse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Class which sets up the google client and the environment. If "audio_length" is received (so it is different than 0) that means that we the user is listening to an audio and we only care about "stop" and "end" commands. If by the time the audio finishes none of those commands have been said by the user, the the mic sto...
def listen_command(self, keyword_bool, audio_length = 0): # we calculate current time (approximate time at which the audio starts) audio_init_time = time.time() with MicrophoneStream.MicrophoneStream(RATE, CHUNK) as stream: audio_generator = stream.generator(au...
[ "def start_audio(self):\n raylibpy.init_audio_device()", "def initiate_Pepper(self):\n\n # starts the recognizer\n r = sr.Recognizer()\n\n with sr.Microphone() as source:\n\n while True:\n logger.debug(\"Awaiting user input.\")\n audio = r.liste...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a usergiven position to an usable one. Position can be either a tuple of x and y or an int.
def _position(self, input_pos: (int, int) or int) -> (int, int): if type(input_pos) == tuple: return input_pos if type(input_pos) == int: return input_pos % self.width, input_pos // self.width raise IndexError
[ "def convert_coordinates(coord):\n if len(coord) != 2:\n raise ValueError(\"Invalid coordinate %s\" % coord)\n column = ord(coord.lower()[0]) - 97\n if not 0 <= column <= 7:\n raise ValueError(\"Invalid coordinate %s\" % coord)\n try:\n row = int(coord[1]) - 1\n except ValueError:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps evaluation of `self[position]` to the matrix.
def __getitem__(self, position: (int, int) or int): x, y = self._position(position) return self.__matrix[y][x]
[ "def _matrix_(self):\n return self.to_matrix()", "def get_mapping_matrix(self):\r\n return self.matrix", "def __setitem__(self, position: (int, int) or int, value):\n x, y = self._position(position)\n\n self.__matrix[y][x] = value", "def __getitem__(self, index):\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps assignment of `self[position]` to the matrix.
def __setitem__(self, position: (int, int) or int, value): x, y = self._position(position) self.__matrix[y][x] = value
[ "def get_mapping_matrix(self):\r\n return self.matrix", "def __setitem__(self, *args):\n return _coin.SoMFMatrix___setitem__(self, *args)", "def __getitem__(self, position: (int, int) or int):\n x, y = self._position(position)\n\n return self.__matrix[y][x]", "def __setitem__(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps deletion of `self[position]` to the matrix.
def __delitem__(self, position: (int, int) or int): x, y = self._position(position) self.__matrix[y][x] = None
[ "def remove(self, pos: vec2d):\n pos //= self.fulltile\n x, y = pos.ftup()\n self.array.delete(x, y)", "def remove_tensor(self, position):\n target_indices = self.tensors[position].non_der_indices\n new_tensors = []\n for tensor in rest(self.tensors, position):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
'Greater than' comparison between each values of the instance and an external value or the values of another Matrix.
def __gt__(self, other): if isinstance(other, self.__class__): result = self.__class__(self.width, self.height) for index, value in enumerate(self): result[index] = value > other[index] return result else: for value in self: ...
[ "def __gt__(self, other: 'MetricList') -> bool:\n self._compare_metrics(other)\n for name, metric in self.metrics.items():\n cmp = metric.better(self.values[name], other.values[name])\n if cmp is not None:\n return cmp\n return False", "def __gt__(i1, i2):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates registration information of the peer with new values.
def register_update(self, port): self.reg_times.append(time.time()) self.reg_date = datetime.datetime.now() self.port = port self.update()
[ "def update_registration():\n try:\n requests.post(\n f'http://{CATALOG_IP_PORT[\"ip\"]}:{CATALOG_IP_PORT[\"port\"]}/catalog/devices',\n data=UPDATE_BODY,\n headers={\"Content-Type\": \"application/json\"}\n )\n except requests.ConnectionError:\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates information of the peer per leave request.
def leave_update(self): self.port = None self.flag = False self.ttl = 0
[ "def on_peer_leave(self, node_info):\n msg = json.dumps({'type': 'user_leave', 'id': node_info['node_id'], 'name': node_info['name']})\n self.send_to_all_clients(msg)", "def leave(self):\n for n in self.m_nbrs:\n pkt = Packet(self, n.m_peer, PACKET_LEAVE)\n self.send_pkt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs the test whether the peer is still active and updates its TTL field.
def is_active(self): if self.flag: diff_time = time.time() - self.reg_times[-1] self.ttl = TTL - diff_time self.flag = True if self.ttl > 0 else False if not self.flag: self.ttl = 0
[ "def _ping_keep_alive(self):\n self.client.active_ping(self.channel_name)\n return True", "def is_expired(self):\n return self.ttl <= 0", "def check_live_peers(self):\n\n to_delete = set()\n\n with self.peer_lock:\n for peer_id, peer in self.peers.items():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs the new thread to execute request and send response back. Continuously waits for connections from the peers on the wellknown port 654231. Once the request is obtained from the peer it calls helper functions to extract the request information and construct the response message. Sends response message back to peer.
def run(self): # Loop forever waiting for new connections from different peers while True: # Wait on accept and create new socket try: connection_socket, address = server_socket.accept() except error: print 'Shuts down the TCP Register ...
[ "def execute_request(method, host, port, cookie):\n try:\n if method == 'REGISTER':\n if cookie is None:\n # The peer has never register before.\n assert len(dict_peers) not in dict_peers, \\\n 'Error: Cookie for the new peer is in use.'\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts request from the protocol that is received from the peer. Extracts request message from P2PDI/1.0 protocol and calls helper function to prepare response message back to the peer.
def extract_data_protocol(request_data): data_list = request_data.split() method = data_list[1] version = data_list[2] try: assert version == PROTOCOL, 'Exception: Undefined App Layer Protocol...' except AssertionError, _e: print _e response_message = encapsulate_data_protoco...
[ "def unpack(breq_original):\n\t\tbreq = bytearray(breq_original)\n\n\t\t# Extract request ID and length.\n\t\tr_id, r_len = struct.unpack(\"<BI\", breq[:5])\n\t\tbreq = breq[5:(5+r_len)]\n\t\t# Create a dict of parameters.\n\t\td = {\"id\":r_id}\n\n\t\t# Join\n\t\tif r_id == Protocol.REQ_JOIN:\n\t\t\t# Extract nick...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes peer request and prepares response message back to the peer. Supports request methods Register, Leave, PQuery, and KeepAlive. Takes actions according to the request method. After request is completed it calls another helper function that generates the response message by encapsulating response data into P2PDI/...
def execute_request(method, host, port, cookie): try: if method == 'REGISTER': if cookie is None: # The peer has never register before. assert len(dict_peers) not in dict_peers, \ 'Error: Cookie for the new peer is in use.' # Ad...
[ "def xmlrpc_dispatch(self, request):\r\n try:\r\n params, method = xmlrpclib.loads(request.raw_post_data)\r\n if method != 'pingback.ping':\r\n raise Exception('Method \"%s\" not supported' % method)\r\n source_uri, target_uri = params\r\n response =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays/prints all peers that have registered with this Register Server. Request comes from the user while it continuously prompts for request. The output displays all possible information about each registered peer.
def do_show(): if dict_peers: print 'Show: Each Registered Peer Information...' for key, peer in dict_peers.iteritems(): peer.is_active() print key, ' ==> ', 'Hostname: {} '.format(peer.hostname), \ 'Port: {} (RFC Server) '.format(peer.port), \ ...
[ "def onRequestPeers(self):\n selection = self.peerList.curselection()\n if len(selection) == 1:\n peerid = self.peerList.get(selection[0])\n self.btpeer.sendtopeer( peerid, GETPEERS, \"%s\" % ( self.btpeer.myid) )", "def fetch_peers():\n get_chain_address = \"{}/chain\".form...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts the gluster volume
def volume_start(mnode, volname, force=False): data = { "force-start-bricks": force } return RestClient(mnode).handle_request( "POST", "/v1/volumes/%s/start" % volname, httplib.OK, data)
[ "def start():\n\n brick_device = os.environ.get(\"BRICK_DEVICE\", None)\n brick_path = os.environ[\"BRICK_PATH\"]\n if brick_device is not None and brick_device != \"\":\n brickfs = os.environ.get(\"BRICK_FS\", \"xfs\")\n create_and_mount_brick(brick_device, brick_path, brickfs)\n\n volume...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stops the gluster volume
def volume_stop(mnode, volname, force=False): return RestClient(mnode).handle_request( "POST", "/v1/volumes/%s/stop" % volname, httplib.OK, None)
[ "def test_volume_stop(self):\n pass", "def stop_vm():\n send_vm_command(VM_STOP)", "def volume_scrub_stop(self, name=None):\n return self.request( \"volume-scrub-stop\", {\n 'name': [ name, 'name', [ basestring, 'None' ], False ],\n }, {\n } )", "def stop():\n # re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes the gluster volume if given volume exists in gluster and deletes the directories in the bricks associated with the given volume
def volume_delete(mnode, volname, xfail=False): hosts = [] paths = [] volinfo = get_volume_info(mnode, volname, xfail) if not volinfo: if xfail: g.log.info( "Volume {} does not exist in {}" .format(volname, mnode) ) return True ...
[ "def delete_volume(client, volume_id):\n if supports_volumes_api(client):\n client.remove_volume(volume_id)\n return\n\n def clear_path(path):\n if exists(path):\n logging.info(\"Removing path: %s\", path)\n rmtree(path)\n clear_path(os.path.join(DOCKER_VFS_DIR, v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Resets the gluster volume
def volume_reset(mnode, volname, force=False, options=None, all_volumes=False): if not 'options': options = {} data = { "options": options, "force": force, "all": all_volumes, } return RestClient(mnode).handle_request( "DEL...
[ "def reset(to_unblock):\n log_everywhere(resource.nodes, 'Resetting cluster state')\n always_blocked = connections(from_nodes=[A, B, C], to_node=B)\n all_blocked = always_blocked.extend(to_unblock)\n all_blocked.unblock()\n all_blocked.event(r'connection .* connection:Connected')\n\n resource.down...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get gluster volume info
def volume_info(mnode, volname): return RestClient(mnode).handle_request("GET", "/v1/volumes/%s" % volname, httplib.OK, None)
[ "def get_gluster_on_compute_volume():\n # type: (None) -> str\n return _GLUSTER_ON_COMPUTE_VOLUME", "def get_volumes(self):\n\tapi = NaElement(\"volume-get-iter\")\n\txi = NaElement(\"desired-attributes\")\n\tapi.child_add(xi)\n\t## This specifies max number of volume records to pull from sdk api\n\t## Defa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get gluster volume status
def volume_status(mnode, volname): return RestClient(mnode).handle_request( "GET", "/v1/volumes/%s/status" % volname, httplib.OK, None)
[ "def volume_status(self, volume):\r\n volume = self._get_volume(volume)\r\n raid = self._get_raid(volume[\"devicefile\"])\r\n if volume is not None and raid is not None:\r\n return raid[\"state\"]", "def get_status(self):\n result = None\n try:\n r = reques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get gluster volume brick status
def volume_brick_status(mnode, volname): return RestClient(mnode).handle_request( "GET", "/v1/volumes/%s/bricks" % volname, httplib.OK, None)
[ "def volume_status(mnode, volname):\n return RestClient(mnode).handle_request(\n \"GET\", \"/v1/volumes/%s/status\" % volname,\n httplib.OK, None)", "def get_bricks(volname):\n value = []\n cmd = [\"gluster\", \"volume\", \"info\", volname, \"--xml\"]\n info = execute(cmd)\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List the gluster volume
def volume_list(mnode): return RestClient(mnode).handle_request( "GET", "/v1/volumes", httplib.OK, None)
[ "def volume_list(search_opts=None):\r\n c_client = cinderclient()\r\n if c_client is None:\r\n return []\r\n # print c_client.volumes.list(search_opts=search_opts)\r\n return c_client.volumes.list(search_opts=search_opts)", "def show_asm_volumes(self):\n sql = \"select NAME from v$asm_di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the option values for the given volume.
def get_volume_options(mnode, volname, option=None): if not option: _, get_vol_options, err = RestClient(mnode).handle_request( "GET", "/v1/volumes/%s/options" % volname, httplib.OK, None) else: _, get_vol_options, err = RestClient(mnode).handle_request( "GET", "/v1/volum...
[ "def volume_options_list_info(self, volume):\n return self.request( \"volume-options-list-info\", {\n 'volume': [ volume, 'volume', [ basestring, 'None' ], False ],\n }, {\n 'options': [ VolumeOptionInfo, True ],\n } )", "def volumes(self):\r\n volumes = self.prop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if object is accessed by attributes or not.
def is_attribute_access(obj, fields): ag = operator.attrgetter(*fields) try: ag(obj) return True except AttributeError: return False
[ "def _has_private_attribute(self):\n return isinstance(self.attributes, dict) and any([k.startswith('__') for k in self.attributes.keys()])", "def _check_object_attrs(self, obj: Any) -> bool:\n for a, v in self._named_attrs.items():\n if not hasattr(obj, a):\n return False\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends wav attachment to Microsoft Bing Speech Recognition Service.
def speechrec(wavobj): # Decode base64 attachment outobj = base64.b64decode(wavobj) # Set connection parameters authhost = 'api.cognitive.microsoft.com' authpath = '/sts/v1.0/issueToken' speechhost = 'speech.platform.bing.com' speechpath = '/recognize?scenarios=smd&appid=D4D52672-91D7-4C74-8...
[ "def stt_google_wav(audio_fname):\n\n print (\"Sending \", audio_fname)\n #Convert to flac first\n with io.open(audio_fname, 'rb') as audio_file:\n content = audio_file.read()\n audio = types.RecognitionAudio(content=content)\n config = types.RecognitionConfig(encoding=enums.Recognitio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks to see if HTML tags exist in the message and changes content type
def examinehtml(textobject, contenttype): if not globalconfig('check_html'): return contenttype if (('<html>' in textobject) and ('</html>' in textobject)): return 'text/html' else: return 'text/plain'
[ "def is_html_message(self):\n return self._is_html_message", "def is_html(text):\n if text is not None and '<html' in text[:300].lower():\n return True\n return False", "def is_html_like(text):\n if isinstance(text, str):\n text = text.strip()\n if text.startswith(\"<\"):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts wav attachments to MP3. Requires FFMPEG
def vmtomp3(filename, wavobj): outobj = base64.b64decode(wavobj) if not globalconfig('vm_to_mp3'): return [filename, 'audio/x-wav', outobj] randfilename = str(random.randint(1,10000000000)) + filename newrandfilename = randfilename[:-3] + "mp3" try: tempwav = open(globalconfig('temp_...
[ "def wav2mp3(wavfile, mp3file, bitrate=128):\n cmd = \"sox -c 1 %s -C %d %s\" % (wavfile, bitrate, mp3file)\n subprocess.call(cmd.split(\" \"))", "def convert_mp3(self, filename, to_mp3=True):\r\n fs = FluidSynth()\r\n title = filename.split('.')[0]\r\n audio_filename = f'{title}.mp3' i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get number from string of format {currency}{value}{multiplicator}
def parse_param_string(parameter_string: str) -> Number: parameter_string = parameter_string.replace('\xa0', ' ') match = re.search( r'(?:US\$)' # currency r'(?P<value>[+−-]?\d+(?:\.\d+)?)' # value, minus sign can be written as − or - r'(?P<multiplicator>\s[a-zA-Z]*)?', #...
[ "def string_to_number(self,s):\n str_number = self.regex_decimal.search(s).group(0)\n str_number = str_number.replace(',', '.')\n nb = float(str_number)\n regex_mapper = re.compile('|'.join(['(' + k + ')' for k in self.mapping_number.keys()]))\n match = regex_m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get company name from summary table.
def scrape_company_name(html: str) -> str: page = bs.BeautifulSoup(html, 'html.parser') summary_table = page.find('table', # find one summary table class_='infobox vcard') if not summary_table: raise ValueError('No summary table found') try: caption = sum...
[ "def get_company_name(self):\r\n return self.company_name", "def get_company_name(url_str):\n scraper = get_scraper(url_str)\n\n h1 = scraper.find_all(\"h1\", {\"id\": \"cn-cont\"})[0]\n return h1.contents[0].strip()", "def get_CompanyName(TargetID):\n pass", "def get_company_summary(parsed...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert parameters to other currency.
def convert_currency(params: Dict[str, Number], exchange_rate: Dict[str, Number]) -> Dict[str, Number]: converted_params = {name: round(value * exchange_rate['exchange_rate'], 2) for name, value in params.items()} return converted_params
[ "def convert(self, params):\r\n if self.rates is None:\r\n self.load_rates()\r\n\r\n try:\r\n if params['in_currency'] == 'USD':\r\n result = params['amount'] * self.rates[params['out_currency']]\r\n elif params['out_currency'] == 'USD':\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
See if the client wants json by inspecting the mimetypes
def wants_json(mimetypes): best = mimetypes.best_match(['application/json', 'text/html']) return best == 'application/json'
[ "def _json_request(self):\n return 'json' in self._get_content_type()", "def test_media_types(sut: SystemUnderTest, uri, response):\n if (uri != '/redfish/v1/$metadata' and response.request.method != 'HEAD'\n and response.status_code in [requests.codes.OK,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Discover BIGIP in Device / ADC
def ltm_discover(self, config, devid): iq = self.config['bigiq'] ip = config['bigip'] username = config['ip_username'] password = config['ip_password'] iq_username = config['iq_username'] iq_password = config['iq_password'] self.logger.info("Discover BIGIP {0} in Device"...
[ "def discover_atag():\r\n # return format: [b'ONE xxxx-xxxx-xxxx_xx-xx-xxx-xxx (ST)',\r\n # ('xxx.xxx.x.x', xxxx)]\r\n # sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP\r\n sock.setsockopt(socket.SOL_SOCKET...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call addition on MC
def addition(arg1, arg2): return materials_commons.add(arg1, arg2)
[ "def add(arg1, arg2):\n\treturn arg1 + arg2", "def addThem(n, m):\n\treturn n + m", "def multiplyAndAdd(n, m):\n\treturn (n + 5) * (m + 7)", "def __add__(self, *args):\n return _snap.TCnComV___add__(self, *args)", "def add(num1, num2, num3):\n\treturn num1 + num2 + num3", "def __add__(self, matrix)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call subtraction on MC
def subtraction(arg1, arg2): return materials_commons.sub(arg1, arg2)
[ "def substract():\n print(\"SUBTRACT\")\n a,b = getInput()\n print(a - b)", "def subtract(minuend: int, subtrahend: int) -> int:\n click.echo(f\"{minuend} - {subtrahend} = {minuend - subtrahend}\")", "def subtract(*arg):\n #first element will be the initial value of substraction, since we substru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PubNub Status Callback Implementation
def status(self, pubnub, status): if utils.is_subscribed_event(status) and not self.connected_event.is_set(): self.connected_event.set() self.disconnected_event.clear() elif utils.is_unsubscribed_event(status) and not self.disconnected_event.is_set(): self.disconnecte...
[ "def presence(self, pubnub, presence):", "def status_callback(self, response):\n print response", "def on_publish(self, client, userdata, retcode):\n self.log.debug(\n \"on_publish: Successfully published message %s, %s, %s\",\n client,\n userdata,\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PubNub Message Callback Implementation
def message(self, pubnub, message): self._callback(ActivityState.from_dict(message.message))
[ "def message_callback(callback):\r\n @wraps(callback) #update attribute data for decorator\r\n def message_handler(client,userdata,message):\r\n #decode and log the message and return the payload values\r\n message.payload = message.payload.decode(\"utf-8\")\r\n logger.debug('Received ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PubNub Presence Callback Implementation
def presence(self, pubnub, presence):
[ "def _update_presence():\n # get presence info from Centrifugo\n cent_url = CENTRIFUGO_HOST+\":\"+str(CENTRIFUGO_PORT)\n client = Client(cent_url, SECRET_KEY, timeout=1)\n clients = client.presence(CHANNEL)\n if DEBUG:\n print \"Updating presence\"\n # post presence info\n total_users = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Async utility function that waits for subscription disconnect.
async def wait_for_disconnect(self): if not self.disconnected_event.is_set(): await self.disconnected_event.wait()
[ "async def unsubscribe_and_await_disconnect(self):\n self.unsubscribe()\n await self._listener.wait_for_disconnect()", "async def wait_until_endpoint_subscriptions_change(self) -> None:\n ...", "async def test_signal_listener_disconnect(\n proxy: DBusInterfaceProxy, test_service: TestInt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unsubscribe to Snoo Activity Channel and await disconnect
async def unsubscribe_and_await_disconnect(self): self.unsubscribe() await self._listener.wait_for_disconnect()
[ "def unsubscribe(channel: str) -> None:\n _get().unsubscribe(channel)", "def unsubscribe(self) -> None:\n if self.cdata is None:\n return\n if self.asyncio_register and self.fd != -1:\n self.loop.remove_reader(self.fd)\n try:\n check_call(lib.sr_unsubscribe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publish a message to the Snoo control command channel
async def publish(self, message): task = await self._pubnub.publish().channel( self._controlcommand_channel).message(message).future() return task
[ "def send_control(self, control):\n if not self.is_closed:\n with self._lock:\n self.client.channel_control_write(self.number, control)", "def publish(self, channel, message):\r\n return self.execute_command(\"PUBLISH\", channel, message)", "def publish(self, rosmsg):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publish a message a start_snoo command to the Snoo control command channel
async def publish_start(self): return await self.publish({ 'command': 'start_snoo' })
[ "async def start_control(self) -> None:\n print('[Balancing] Starting sonos control loop')\n await self.sonos.control_loop()", "def serviceStarted(self):\n self.openChannel(ShellSlaveChannel(conn=self))", "def session_start(self, event):\n\n self.send_presence()\n # Most get_*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop and Cleanup the Async Pubnub Utility
async def stop(self): # pylint: disable=protected-access # Workaround until PR is accepted: # https://github.com/pubnub/python/pull/99 # self._pubnub.stop() await self._pubnub._session.close() if self._pubnub._subscription_manager is not None: self._pubnub._su...
[ "def cleanup() -> None:\n\n global _broadcaster\n _broadcaster = None", "async def cleanup(self) -> None:\n for pf in self._scheduled_functions.values():\n pf.stop()\n for t in self._in_stream.values():\n t.cancel()\n if self._cb_app_heartbeat:\n self._c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a tuple containing True if the key could be deleted and the message to send back to the client.
def handle_delete(key): try: del DATABASE_DICT[key] except KeyError: operation_status = False result_msg = 'ERROR: Key [{}] not found and could not be deleted'.format(key) else: operation_status = True result_msg = "Key [{}] deleted".format(key) return operation_...
[ "def deleted_message(self):\n return isinstance(self.original.action,\n types.ChannelAdminLogEventActionDeleteMessage)", "def isDeleted():", "async def messagedelete(self, ctx):\n status = await self.bot.pool.fetch(\"SELECT * FROM loggingsettings WHERE guildid = $1\", ctx....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function that pushes the text through the django templating engine. Keep in mind that it does not escape text, which is good!
def templatize(self, text, context): return Template("{% autoescape off %}" + text + "{% endautoescape %}").render(context)
[ "def render_template(text, context=None):\n template = engines[\"django\"].from_string(text)\n if not context:\n context = {}\n return template.render(context)", "def do_normal(self, string):\n _append = Appender()\n def append(string):\n _append(string)\n code_obj ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to execute a func inside the QThreadPool
def AsQThread(func): @wraps(func) def AsyncFunc(*args, **kwargs): runnable = Runnable(func = func, args = args, kwargs = kwargs) global pool pool.start(runnable) return AsyncFunc
[ "def job(self, func):\n @functools.wraps(func)\n def delay(*args, **kwargs): # pragma: no cover\n return self.enqueue(func, *args, **kwargs)\n func.delay = delay\n return func", "def call_threaded(func: t.Callable[..., None]) -> t.Callable[..., \"Future\"]:\n\n @wraps(fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new action for a rule associated with a specific resource name.
def create_action_for_rule(self, ruleresourcename: str, action_post: ActionPOST, query_params: Dict[str, object] = None) -> Action: if query_params is None: query_params = {} path_params = { "ruleresourcename": ruleresourcename, } path = Template("/catalog/v2alp...
[ "def create_action_for_rule_by_id(self, ruleid: str, action_post: ActionPOST, query_params: Dict[str, object] = None) -> Action:\n if query_params is None:\n query_params = {}\n\n path_params = {\n \"ruleid\": ruleid,\n }\n\n path = Template(\"/catalog/v2alpha2/rule...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new action for a specific rule.
def create_action_for_rule_by_id(self, ruleid: str, action_post: ActionPOST, query_params: Dict[str, object] = None) -> Action: if query_params is None: query_params = {} path_params = { "ruleid": ruleid, } path = Template("/catalog/v2alpha2/rules/${ruleid}/acti...
[ "def create_action_for_rule(self, ruleresourcename: str, action_post: ActionPOST, query_params: Dict[str, object] = None) -> Action:\n if query_params is None:\n query_params = {}\n\n path_params = {\n \"ruleresourcename\": ruleresourcename,\n }\n\n path = Template(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new annotation for a specific dashboard.
def create_annotation_for_dashboardby_id(self, dashboardid: str, annotation_post: AnnotationPOST, query_params: Dict[str, object] = None) -> Annotation: if query_params is None: query_params = {} path_params = { "dashboardid": dashboardid, } path = Template("/ca...
[ "def create_annotations(self) -> None:\n pass", "def create_annotation_for_dataset_by_id(self, datasetid: str, annotation_post: AnnotationPOST, query_params: Dict[str, object] = None) -> Annotation:\n if query_params is None:\n query_params = {}\n\n path_params = {\n \"d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new annotation for a specific dataset.
def create_annotation_for_dataset_by_id(self, datasetid: str, annotation_post: AnnotationPOST, query_params: Dict[str, object] = None) -> Annotation: if query_params is None: query_params = {} path_params = { "datasetid": datasetid, } path = Template("/catalog/v...
[ "def create_annotation_for_dataset_by_resource_name(self, datasetresourcename: str, annotation_post: AnnotationPOST, query_params: Dict[str, object] = None) -> Annotation:\n if query_params is None:\n query_params = {}\n\n path_params = {\n \"datasetresourcename\": datasetresourc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new annotation for a specific dataset.
def create_annotation_for_dataset_by_resource_name(self, datasetresourcename: str, annotation_post: AnnotationPOST, query_params: Dict[str, object] = None) -> Annotation: if query_params is None: query_params = {} path_params = { "datasetresourcename": datasetresourcename, ...
[ "def create_annotation_for_dataset_by_id(self, datasetid: str, annotation_post: AnnotationPOST, query_params: Dict[str, object] = None) -> Annotation:\n if query_params is None:\n query_params = {}\n\n path_params = {\n \"datasetid\": datasetid,\n }\n\n path = Templ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }