code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def form(self): <NEW_LINE> <INDENT> for row in self.vehicles_rows: <NEW_LINE> <INDENT> self.vehicles_dict[row['vin']] = row['id'] | Put custmoers into dict indexed by pureName.
further indexed by dealer_id
and then list of customer_info | 625941d07047854f462a1579 |
def add_all(self): <NEW_LINE> <INDENT> for image in range(self.num_images): <NEW_LINE> <INDENT> fname = os.path.join(em2d_dir, self.image_name_format % image) <NEW_LINE> l = ihm.location.InputFileLocation(fname) <NEW_LINE> dataset = ihm.dataset.EM2DClassDataset(location=l) <NEW_LINE> r = ihm.restraint.EM2DRestraint(dat... | Point to the raw image files used for the EM2D restraint | 625941d091f36d47f21ac663 |
def save_success_id(tenant_id): <NEW_LINE> <INDENT> with open('goods_success.txt', 'a', encoding='utf-8') as f: <NEW_LINE> <INDENT> f.write(str(tenant_id) + '\n') <NEW_LINE> f.close() | 把已经抓取的url保存到txt文件中
:param url:
:return: | 625941d0fb3f5b602dac3804 |
def __correct_encoding(self, encode, filename): <NEW_LINE> <INDENT> if encode == 'None' or encode == self.__tencoding: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> buffname = '~old' + filename <NEW_LINE> self.__os.rename(filename, buffname) <NEW_LINE> with open(buffname, 'r', encoding=self.__tencoding) as fr: <NEW_LI... | change the encoding to target encoding
| 625941d015fb5d323cde0c81 |
def _init_arch(arch): <NEW_LINE> <INDENT> if arch == 'default': <NEW_LINE> <INDENT> return { 'cache_size': 256 * 10**3, 'double': 8 } <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return { 'cache_size': 0, 'double': sys.maxint } | Set architecture-specific parameters. | 625941d007d97122c41789fd |
def get_mobject(node): <NEW_LINE> <INDENT> selection_list = OpenMaya.MSelectionList() <NEW_LINE> selection_list.add(node) <NEW_LINE> mobject = OpenMaya.MObject() <NEW_LINE> selection_list.getDependNode(0, mobject) <NEW_LINE> return mobject | Get the MObject of the given node.
:param node: Node name
:return: Node MObject | 625941d0b830903b967e9a7b |
def twitter_update_blocks(secateur_user: "models.User") -> None: <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> api = secateur_user.api <NEW_LINE> account = secateur_user.account <NEW_LINE> assert account is not None <NEW_LINE> api_function = partial(api.GetBlocksIDsPaged) <NEW_LINE> accounts_handlers = [partial(a... | Trigger django-q tasks to update the block list of a secateur user. | 625941d0596a897236089c31 |
@freeze_time(DST_DATETIME) <NEW_LINE> def test_count_todays_date_dst( client, user_base, enclosure_base, animal_A, animal_count_A_BAR, group_B ): <NEW_LINE> <INDENT> client.force_login(user_base) <NEW_LINE> resp = client.get(f"/count/{enclosure_base.slug}/") <NEW_LINE> assert "Today's Count" in resp.content.decode() <N... | mock the current date to be on daylight savings (@12pm)
we should still be seeing "todays date" -- this requires us being at 12pm currently
because today_time utility uses localtime to generate a date | 625941d085dfad0860c3afcc |
def sample_teacher(**options): <NEW_LINE> <INDENT> fields = sample_teacher_payload() <NEW_LINE> fields.update(options) <NEW_LINE> return Teacher.objects.create(**fields) | Create and return a sample Teacher object | 625941d0851cf427c661a67f |
def regexGenerator(self, regexp, textrun): <NEW_LINE> <INDENT> regex = re.compile(r'%s' % regexp, re.UNICODE|re.DOTALL) <NEW_LINE> results = regex.findall(textrun) <NEW_LINE> for image in results: <NEW_LINE> <INDENT> yield wikipedia.ImagePage(self.site, image) | Generator used when an user use a regex parsing a page to yield the results | 625941d0adb09d7d5db6c900 |
def canUnpublish(id, userId): <NEW_LINE> <INDENT> db = core.connect() <NEW_LINE> theShift = db[id] <NEW_LINE> return user.isAdmin(userId) or (userId == theShift['createdBy']) | Check where a user can unpublish a shift.
Parameters:
id - a shift id.
userId - a user id.
Returns:
bool. | 625941d0bf627c535bc13340 |
def train(self, X, y, X_val, y_val, learning_rate=1e-3, learning_rate_decay=0.95, reg=5e-6, num_iters=100, batch_size=200, dropout = False, p = 0.5, verbose=False): <NEW_LINE> <INDENT> num_train = X.shape[0] <NEW_LINE> iterations_per_epoch = max(num_train / batch_size, 1) <NEW_LINE> loss_history = [] <NEW_LINE> train_a... | Train this neural network using stochastic gradient descent.
Inputs:
- X: A numpy array of shape (N, D) giving training data.
- y: A numpy array f shape (N,) giving training labels; y[i] = c means that
X[i] has label c, where 0 <= c < C.
- X_val: A numpy array of shape (N_val, D) giving validation data.
- y_val: A n... | 625941d04f6381625f114bab |
def get_default_path_to_osm_file(self, subregion_name, osm_file_format, mkdir=False, update=False, verbose=False): <NEW_LINE> <INDENT> subregion_name_ = self.validate_input_subregion_name(subregion_name) <NEW_LINE> osm_file_format_ = self.validate_input_file_format(osm_file_format) <NEW_LINE> subregion_name_, download_... | Get a default path to a local directory for storing a downloaded data file.
The default file path is derived from the relevant download URL for the requested data file.
:param subregion_name: name of a geographic region available on Geofabrik free download server
:type subregion_name: str
:param osm_file_format: file... | 625941d0a934411ee3751804 |
def get_embedding(self, img_name): <NEW_LINE> <INDENT> image_path = os.path.join(app_config['DATA_IMAGE_ROOT'], img_name) <NEW_LINE> if os.path.exists(image_path): <NEW_LINE> <INDENT> img = load_img(image_path, target_size=(self.input_shape[0], self.input_shape[1])) <NEW_LINE> x = img_to_array(img) <NEW_LINE> x = np.ex... | Extract feature from the image.
:param img_name: name of the image
:return: feature map of the image | 625941d04f6381625f114bac |
def execute(self, clause, params=None, mapper=None, instance=None): <NEW_LINE> <INDENT> engine = self.get_bind(mapper, clause=clause, instance=instance) <NEW_LINE> return self.__connection(engine, close_with_result=True).execute(clause, params or {}) | Execute the given clause, using the current transaction (if any).
Returns a ``ResultProxy`` corresponding to the execution's results.
clause
a ClauseElement (i.e. select(), text(), etc.) or
string SQL statement to be executed
params
a dictionary of bind parameters.
mapper
a mapped class or Map... | 625941d066673b3332b92202 |
def __init__(self, text, coordinates): <NEW_LINE> <INDENT> self.text = text <NEW_LINE> self.coordinates = coordinates | Simple class used for annotating text.
@text : str (working mode which starts in this time)
@coordinates : tuple of floats (time, energy) - where the text is placed | 625941d00a50d4780f667004 |
def set_custom_vcard_information(self, vCard): <NEW_LINE> <INDENT> vCard.append(xmpp.Node("TITLE", payload=self.vcard_infos["TITLE"])) <NEW_LINE> vCard.append(xmpp.Node("ORGNAME", payload=self.vcard_infos["ORGNAME"])) <NEW_LINE> vCard.append(xmpp.Node("ORGUNIT", payload=self.vcard_infos["ORGUNIT"])) <NEW_LINE> vCard.ap... | Put custom information in vCard | 625941d076e4537e8c3517e4 |
def get_ref_data(): <NEW_LINE> <INDENT> import itertools <NEW_LINE> x = range(-10, 10) <NEW_LINE> y = list(range(-10, 10)) <NEW_LINE> y.remove(0) <NEW_LINE> return list(itertools.product(x, y)) | Get reference data for every pairs | 625941d03c8af77a43ae3911 |
def boundary_subcomplex(self): <NEW_LINE> <INDENT> if self.is_full_dimensional(): <NEW_LINE> <INDENT> return PolyhedralComplex(self.relative_boundary_cells(), is_immutable=self._is_immutable, backend=self._backend) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ans = copy(self) <NEW_LINE> if self._is_immutable: <NEW_LIN... | Return the sub-polyhedral complex that is the boundary of ``self``.
A point `P` is on the boundary of a set `S` if `P` is in the
closure of `S` but not in the interior of `S`.
EXAMPLES::
sage: p1 = Polyhedron(vertices=[(1, 1), (0, 0), (1, 2)])
sage: p2 = Polyhedron(vertices=[(1, 2), (0, 0), (0, 2)])
sage... | 625941d0656771135c3eb9e0 |
def __init__(self, config = None, filters = 4, base_kernel = (3,1), trans_kernel = (2,1), batch_norm = False, base_activation = 'relu', trans_activation = 'relu', dropout = 0.5, compression = 2, bottleneck = True, bottleneck_factor = 4, name = 'ResBlock'): <NEW_LINE> <INDENT> super().__init__( config = config, filters ... | A Block object which represents a basic residual block with:
base_block: building_blocks.residual_layer (or bn_residual_layer)
up_sample: building_blocks.transition_layer("up")
down_sample: building_blocks.transition_layer("down)
The down and up sample blocks reduce the resolution. To maintain
a similar n... | 625941d03c8af77a43ae3912 |
def __getScopChainMapping(self, siftsSummaryDirPath, csvFileName): <NEW_LINE> <INDENT> fp = os.path.join(siftsSummaryDirPath, csvFileName) <NEW_LINE> rowDL = self.__readSiftsSummaryFile(fp) <NEW_LINE> logger.info("Length of SIFTS summary file %s %d", csvFileName, len(rowDL)) <NEW_LINE> logger.debug("%r", list(rowDL[0].... | Integrated SIFTS summary instance-level SCOP mapping data. | 625941d02ae34c7f2600d2a2 |
def gcloud_config_get(key): <NEW_LINE> <INDENT> res = cmd(["gcloud", "config", "get-value", key], structured=True) <NEW_LINE> return res | Retrieves a configuration value using gcloud config get-value | 625941d055399d3f05588826 |
def set_real_theorem (theorem_name): <NEW_LINE> <INDENT> return runOcarinaFunction (libocarina_python.set_real_theorem, theorem_name) | Set main REAL theorem
:param theorem_name: name of the theorem
:type theorem_name: string | 625941d030bbd722463cbf37 |
def scrape_qb_data_pro_football(self, name): <NEW_LINE> <INDENT> pattern = re.compile(r'\w+ \w+') <NEW_LINE> url = self.pro_fb_url <NEW_LINE> qb_request = requests.get(url).text <NEW_LINE> qb_soup = bs(qb_request, "lxml") <NEW_LINE> if pattern.search(qb_soup.find('h1', {'itemprop':'name'}).text.strip()) == name: <NEW_L... | Returns a Beautiful Soup soup object | 625941d0dc8b845886cb56a6 |
def DescribeDBSecurityGroups(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> params = request._serialize() <NEW_LINE> body = self.call("DescribeDBSecurityGroups", params) <NEW_LINE> response = json.loads(body) <NEW_LINE> if "Error" not in response["Response"]: <NEW_LINE> <INDENT> model = models.DescribeDBS... | 本接口(DescribeDBSecurityGroups)用于查询实例的安全组详情。
:param request: Request instance for DescribeDBSecurityGroups.
:type request: :class:`tencentcloud.redis.v20180412.models.DescribeDBSecurityGroupsRequest`
:rtype: :class:`tencentcloud.redis.v20180412.models.DescribeDBSecurityGroupsResponse` | 625941d02c8b7c6e89b35931 |
def __init__(self, stickerset, archived): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.result = None <NEW_LINE> self.content_related = True <NEW_LINE> self.stickerset = stickerset <NEW_LINE> self.archived = archived | :param TypeInputStickerSet stickerset:
:param TypeBool archived:
:returns messages.StickerSetInstallResult: Instance of either StickerSetInstallResultSuccess, StickerSetInstallResultArchive. | 625941d097e22403b379d10b |
def decode_all(data, as_class=dict, tz_aware=True): <NEW_LINE> <INDENT> docs = [] <NEW_LINE> while len(data): <NEW_LINE> <INDENT> (doc, data) = _bson_to_dict(data, as_class, tz_aware) <NEW_LINE> docs.append(doc) <NEW_LINE> <DEDENT> return docs | Decode BSON data to multiple documents.
`data` must be a string of concatenated, valid, BSON-encoded
documents.
:Parameters:
- `data`: BSON data
- `as_class` (optional): the class to use for the resulting
documents
- `tz_aware` (optional): if ``True``, return timezone-aware
:class:`~datetime.datetime` i... | 625941d021a7993f00bc7e62 |
def _get_fastest_dim(lst): <NEW_LINE> <INDENT> return np.argmax(list(map(lambda x: max(x)-min(x), map(list, zip(*[value for value in lst]))))) | lst is [ [x1,y1,z1], [x2,y2,z2], ... ]
Will return the index of the dimension with the largest difference
between max and min | 625941d08e71fb1e9831d91a |
@register.assignment_tag <NEW_LINE> def orders_by_customer_filter(orders, user): <NEW_LINE> <INDENT> new_orders = [] <NEW_LINE> for order in orders: <NEW_LINE> <INDENT> if order.user_info == user: <NEW_LINE> <INDENT> new_orders.append(order) <NEW_LINE> <DEDENT> <DEDENT> return new_orders | returns all orders (Preorders) of user | 625941d06aa9bd52df036f16 |
def bounds(self, wide, high, radius=R_M): <NEW_LINE> <INDENT> a, _ = self.to2ab() <NEW_LINE> ca = cos(a) <NEW_LINE> if ca > EPS: <NEW_LINE> <INDENT> w = abs(degrees(asin(wide * 0.5 / radius) / ca)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> w = 0 <NEW_LINE> <DEDENT> h = abs(degrees(high * 0.5 / radius)) <NEW_LINE> r... | Return the SE and NW lat-/longitude of a great circle
bounding box centered at this location.
@param wide: Longitudinal box width (meter, like radius).
@param high: Latitudinal box height (meter, like radius).
@keyword radius: Optional, mean earth radius (meter).
@return: 2-Tuple (LatLonSW, LatLonNE) of (I{LatLon}s).... | 625941d044b2445a33932206 |
def open_url(url_path, prox): <NEW_LINE> <INDENT> filehandle = urllib.urlopen(url_path,proxies=prox) <NEW_LINE> return filehandle.readline() | open URL, return content | 625941d09b70327d1c4e0f47 |
def __init__(self, albedo:Vector3, texture:Texture=None): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._albedo = albedo <NEW_LINE> self._texture = ConstantTexture(Vector3(1.0, 1.0, 1.0)) if texture is None else texture | Lamberian Material
:param albedo: albedo color of the material
:type albedo: Vector3 | 625941d032920d7e50b28342 |
def __get_releaseCount(self, *args): <NEW_LINE> <INDENT> return _moose.BinSynchan___get_releaseCount(self, *args) | __get_releaseCount(self, unsigned int index) -> double | 625941d04e4d5625662d4548 |
def add(a, b): <NEW_LINE> <INDENT> return a + b | >>> add(2,3)
5
>>> add(100,200)
300
>>> add(51,49)
100
>>> add(29, 2)
31 | 625941d001c39578d7e74fac |
def test_delayed_network(self): <NEW_LINE> <INDENT> run_command(netem_change.format("delay "+str(timeout)+"ms 20ms")) <NEW_LINE> setUp() <NEW_LINE> createClient() <NEW_LINE> data = sendMessage() <NEW_LINE> recv_data = getMessage() <NEW_LINE> self.assertEqual(data, recv_data) | reliability over network with delay relative to the timeout value | 625941d0167d2b6e31218d07 |
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> name = config.get(CONF_NAME) <NEW_LINE> host = config.get(CONF_HOST) <NEW_LINE> mac_address = config.get(CONF_MAC_ADDRESS) <NEW_LINE> broadcast_address = config.get(CONF_BROADCAST_ADDRESS) <NEW_LINE> off_action = config.get(CONF_OFF... | Set up a wake on lan switch. | 625941d0b830903b967e9a7c |
def add_demand(self, source_node_name, dest_node_name, traffic=0, name="none"): <NEW_LINE> <INDENT> source_node_object = self.get_node_object(source_node_name) <NEW_LINE> dest_node_object = self.get_node_object(dest_node_name) <NEW_LINE> added_demand = Demand(source_node_object, dest_node_object, traffic, name) <NEW_LI... | Adds a traffic load (Demand) from point A to point B in the
model and validates model.
:param source_node_name: name of Demand's source Node
:param dest_node_name: name of Demand's destination Node
:param traffic: amount of traffic (magnitude) of the Demand
:param name: Demand name
:return: A validated Model object wi... | 625941d023e79379d52ee6d5 |
def install_ssl_options_conf(self, options_ssl, options_ssl_digest, warn_on_no_mod_ssl=True): <NEW_LINE> <INDENT> apache_config_path = self.pick_apache_config(warn_on_no_mod_ssl) <NEW_LINE> return common.install_version_controlled_file( options_ssl, options_ssl_digest, apache_config_path, constants.ALL_SSL_OPTIONS_HASH... | Copy Certbot's SSL options file into the system's config dir if required.
:param bool warn_on_no_mod_ssl: True if we should warn if mod_ssl is not found. | 625941d08e7ae83300e4b13e |
def __getattr__(self: 'pyobj', attr: str) -> Callable: <NEW_LINE> <INDENT> def ret(node1: 'node', node2: 'node', v: 'flatdict') -> 'node': <NEW_LINE> <INDENT> if __debug__: <NEW_LINE> <INDENT> assert hasattr(node1, 'obj'), 'every object should!' <NEW_LINE> assert hasattr(node1.obj, '_pyobj_valof'), "... | Get an attribute - like __add__ and __mod__ - that doesn't exist.
Provides a default implementation that otherwise wouldn't exist | 625941d01f037a2d8b94636f |
def matchesSyntax(line): <NEW_LINE> <INDENT> line = line[1:] <NEW_LINE> s = line.split() <NEW_LINE> (ok0, msg0) = matchesPatternSyntax(s[0]) <NEW_LINE> if len(s) < 1 or ok0: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: return (False, msg0) <NEW_LINE> (ok1, msg1) = matchesPatternSyntax(s[1]) <NEW_LINE> if len(s) <... | parses a configuration line and returns whether it conforms to the syntax | 625941d0bd1bec0571d907a1 |
def end_of(self, event_id, import_options=True): <NEW_LINE> <INDENT> event_id = str(event_id) <NEW_LINE> if event_id in WidgetConfig.events: <NEW_LINE> <INDENT> linked_picker = WidgetConfig.events[event_id] <NEW_LINE> self.config.linked_to = linked_picker.config.id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Ke... | Set Date-Picker as the end-date of a date-range.
Args:
- event_id (string): User-defined unique id for linking two fields | 625941d015baa723493c40e7 |
def __updateHeader(self): <NEW_LINE> <INDENT> count = self.calltraceList.count <NEW_LINE> if count: <NEW_LINE> <INDENT> self.__calltraceLabel.setText('Call Trace (' + str(count) + ')') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__calltraceLabel.setText('Call Trace') | Updates the header | 625941d0b5575c28eb68e172 |
def _ansi(self, code, *args): <NEW_LINE> <INDENT> result = "" <NEW_LINE> if self.ansi_support: <NEW_LINE> <INDENT> result = "\x1b[{0}{1}".format(";".join([str(arg) for arg in args]) if type(args) == list else "", code) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._error("Primary output does not support ansi") <NE... | Returns the ansi escape sequence if the console supports it, or raises an error and returns an empty string
if it doesn't. | 625941d0d99f1b3c44c676ff |
def send_emergency_stop(self): <NEW_LINE> <INDENT> pk = CRTPPacket() <NEW_LINE> pk.port = CRTPPort.LOCALIZATION <NEW_LINE> pk.channel = self.GENERIC_CH <NEW_LINE> pk.data = struct.pack('<B', self.EMERGENCY_STOP) <NEW_LINE> self._cf.send_packet(pk) | Send emergency stop | 625941d010dbd63aa1bd2d15 |
def check_scale(self,i,old_value=None): <NEW_LINE> <INDENT> t = self.tri() <NEW_LINE> edges = where( t.edge_db == i )[0] <NEW_LINE> for e in edges: <NEW_LINE> <INDENT> a,b = t.edge_db[e] <NEW_LINE> if self.F[a] > self.F[b]: <NEW_LINE> <INDENT> a,b = b,a <NEW_LINE> <DEDENT> if a==i: <NEW_LINE> <INDENT> continue <NEW_LIN... | old_value: if specified, on each edge, if the neighbor is far enough away, insert
a new node along the edge at the scale that it would have been if we hadn't
adjusted this node | 625941d045492302aab5e435 |
def register_instances(self, instances): <NEW_LINE> <INDENT> if isinstance(instances, basestring): <NEW_LINE> <INDENT> instances = [instances] <NEW_LINE> <DEDENT> new_instances = self.connection.register_instances(self.name, instances) <NEW_LINE> self.instances = new_instances | Adds instances to this load balancer. All instances must be in the same
region as the load balancer. Adding endpoints that are already
registered with the load balancer has no effect.
:param list instances: List of instance IDs (strings) that you'd like
to add to this load balancer. | 625941d0097d151d1a222fcb |
def _clear_timers(self): <NEW_LINE> <INDENT> if self._query_timer is not None: <NEW_LINE> <INDENT> self._query_timer.cancel() <NEW_LINE> <DEDENT> if self._polling_timer is not None: <NEW_LINE> <INDENT> self._polling_timer.cancel() | Clears all the timers and disconnects from the service | 625941d08c0ade5d55d3eb2d |
def make_boss(head, torso, path=""): <NEW_LINE> <INDENT> if path: <NEW_LINE> <INDENT> path = pfile.fromOsSpecific("%s/" % path).getFullpath() <NEW_LINE> <DEDENT> boss_dict = { "sell": "phase_9/models/char/sellbotBoss", "cash": "phase_10/models/char/cashbotBoss", "law": "phase_11/models/char/lawbotBoss", "boss": "phase_... | Return any cog boss as an Actor.
Args:
head (str): The name of the boss' suit to be used for its head.
torse (str): The name of the boss' suit to be used for its torso.
path (str, optional): The file path to the Toontown phase files.
Defaults to Panda3D's search path.
Examples:
from toontown i... | 625941d0627d3e7fe0d68fc2 |
def delete(self, req, filesystem_id, id): <NEW_LINE> <INDENT> fs_name = filesystem_id <NEW_LINE> instance_uuid = id <NEW_LINE> context = req.environ['nova.context'] <NEW_LINE> instance = db.instance_get_by_uuid(context, instance_uuid) <NEW_LINE> if not instance: <NEW_LINE> <INDENT> msg = (_("Unable to find instance %s.... | Detach an instance from a filesystem. | 625941d0236d856c2ad4494d |
def computeActionFromQValues(self, state): <NEW_LINE> <INDENT> actions = self.action_space <NEW_LINE> max_value = None <NEW_LINE> max_value_action = None <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> q_value = self.getQValue(state, action) <NEW_LINE> if max_value is None: <NEW_LINE> <INDENT> max_value = q_value... | Compute the best action to take in a state. Note that if there
are no legal actions, which is the case at the terminal state,
you should return None. | 625941d0cdde0d52a9e531a6 |
def _init_ssh(opts): <NEW_LINE> <INDENT> if opts is None: <NEW_LINE> <INDENT> opts = __opts__ <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> this_prompt = None <NEW_LINE> if 'prompt_regex' in opts['proxy']: <NEW_LINE> <INDENT> this_prompt = opts['proxy']['prompt_regex'] <NEW_LINE> <DEDENT> elif 'prompt_name' in opts['pro... | Open a connection to the NX-OS switch over SSH. | 625941d0d18da76e23532648 |
def dbconnect(): <NEW_LINE> <INDENT> return sqlite3.connect(app.database) | Connect to sqlite database
:return: (Object) sqlite3 database connection object | 625941d0435de62698dfddbf |
def _highway_layer(input_, size, num_layers=1, bias=-2.0): <NEW_LINE> <INDENT> for idx in range(num_layers): <NEW_LINE> <INDENT> h = tf.nn.relu(_linear(input_, size, scope=("highway_h_{0}".format(idx)))) <NEW_LINE> t = tf.sigmoid(_linear(input_, size, initializer=tf.constant_initializer(bias), scope=("highway_t_{0}".fo... | Highway Network (cf. http://arxiv.org/abs/1505.00387).
t = sigmoid(Wx + b); h = relu(W'x + b')
z = t * h + (1 - t) * x
where t is transform gate, and (1 - t) is carry gate. | 625941d00a366e3fb873e98d |
def get_transform(self): <NEW_LINE> <INDENT> return (self._xy_mat, self.z_mat) | Return additional transform applied through the 'transform' method.
:return: | 625941d08da39b475bd650e6 |
def connect_db(query=None, DB_URL=None): <NEW_LINE> <INDENT> conn = None <NEW_LINE> cursor = None <NEW_LINE> if DB_URL is None: <NEW_LINE> <INDENT> DB_URL = os.getenv('DATABASE_URL') <NEW_LINE> print(DB_URL) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> conn = psycopg2.connect(DB_URL) <NEW_LINE> print("\n\nConnected {}\... | Connection to the database | 625941d04c3428357757c499 |
def tester_func(device_id, apk_path_list, interval, duration, event_policy, output_dir): <NEW_LINE> <INDENT> for apk_path in apk_path_list: <NEW_LINE> <INDENT> test_cmd = ("droidbot -d {device_id} -a {apk_path} -interval {interval} " "-duration {duration} -event {event_policy} -o {output_dir}").format( device_id=device... | test apks on the assigned vm/device | 625941d057b8e32f5248360d |
def testOrganization(self): <NEW_LINE> <INDENT> program = program_utils.seedProgram() <NEW_LINE> organization = org_utils.seedOrganization(program.key()) <NEW_LINE> url = self.linker.organization( organization.key, soc_urls.UrlNames.ORG_PROFILE_EDIT) <NEW_LINE> self.assertEqual( '/gsoc/org/profile/edit/%s' % organizati... | Tests organization function. | 625941d0099cdd3c635f0dcd |
def get_base64_by_id(self, file_id): <NEW_LINE> <INDENT> img_base64 = None <NEW_LINE> try: <NEW_LINE> <INDENT> gf = self.fs.get(file_id=ObjectId(file_id)) <NEW_LINE> img_binary = gf.read() <NEW_LINE> img_base64 = str(base64.b64encode(img_binary))[2:-1] <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> mong... | 按文件'file_id'获取图片'base64码'
:param file_id:
:return:
1.获取成功 -> 返回 图片二进制文件
2.找不到该文件 -> 返回 no such file
3.mongo连接不上 -> 返回 None | 625941d0adb09d7d5db6c901 |
def set_block_length(self, n): <NEW_LINE> <INDENT> self.block_l = n | :param n: new block length
:return: none | 625941d026238365f5f0efe1 |
def clearCookies(self): <NEW_LINE> <INDENT> self.driver.delete_all_cookies() | 启动后删除cookies | 625941d0090684286d50ee58 |
def setAnimationControl( self, state ): <NEW_LINE> <INDENT> cast( control.kiibohd.Pixel_animationControl, POINTER( c_uint8 ) )[0] = state | Set the PixelMap AnimationState
NOTE: You must do one processing cycle in order for this setting to take hold.
0 - AnimationControl_Forward (Default state)
1 - AnimationControl_ForwardOne
2 - AnimationControl_Pause
3 - AnimationControl_Stop (Very useful in cleaning up the current PixelMap state)
4 - AnimationControl_R... | 625941d08a349b6b435e82e5 |
def __call__(key): <NEW_LINE> <INDENT> pass | Return the value belonging to the key given. The key may be a
dotted name - it will be splitted on dots and attributes
will be looked up in turn on the resulting objects.
Return None if no corresponding setting can be found.
The method may also provide some fallback mechanism when
the element is not defined in the cu... | 625941d0ac7a0e7691ed423d |
def find_listings(self, transport, key, listingFilter=None, callback=None): <NEW_LINE> <INDENT> peer = self._routingTable.getContact(key) <NEW_LINE> if peer: <NEW_LINE> <INDENT> peer.send({'type': 'query_listings', 'key': key}) <NEW_LINE> return <NEW_LINE> <DEDENT> listing_index_key = hashlib.sha1('contracts-%s' % key)... | Send a get product listings call to the node in question and then cache those listings locally
TODO: Ideally we would want to send an array of listing IDs that we have locally and then the node would
send back the missing or updated listings. This would save on queries for listings we already have. | 625941d00c0af96317bb835a |
@view_config( context=APIResource, name="user", request_method="PUT", subpath=("username/*"), renderer="json", permission=NO_PERMISSION_REQUIRED, ) <NEW_LINE> @argify <NEW_LINE> def register(request, password): <NEW_LINE> <INDENT> username = request.named_subpaths["username"] <NEW_LINE> return handle_register_request(r... | Register a user | 625941d09f2886367277a9ff |
def get_pod_info(self): <NEW_LINE> <INDENT> pod_name = self.stateless_job.job_id + "-" + str(self.instance_id) <NEW_LINE> request = pod_svc.GetPodRequest( pod_name=v1alpha_peloton.PodName(value=pod_name), status_only=False ) <NEW_LINE> resp = self.stateless_job.client.pod_svc.GetPod( request, metadata=self.stateless_jo... | Get info of a pod | 625941d0fbf16365ca6f6338 |
def get_json_client_credentials_facebook(facebook_auth_token): <NEW_LINE> <INDENT> data = {} <NEW_LINE> data['facebookAuthToken'] = facebook_auth_token <NEW_LINE> return data | Devuelve el json que tenemos que enviarle al SharedServer para validar credenciales
a partir del token de facebook
@param facebook_auth_token es el token de facebook del cliente | 625941d0b5575c28eb68e173 |
def test_quoted(self): <NEW_LINE> <INDENT> ops = NmapOptions() <NEW_LINE> ops.parse_string('--script ""') <NEW_LINE> self.assertEqual(ops["--script"], "") <NEW_LINE> ops.parse_string("--script ''") <NEW_LINE> self.assertEqual(ops["--script"], "") <NEW_LINE> ops.parse_string('--script test one two three') <NEW_LINE> sel... | Test that strings can be quoted. | 625941d076d4e153a657eca3 |
def put(self, request, key): <NEW_LINE> <INDENT> filename = get_filename(key) <NEW_LINE> pickle.dump(self.CONTENT, open(filename, 'wb')) <NEW_LINE> return self.CONTENT | Update/create a stored object, by pickling the request content to a
locally stored file. | 625941d06e29344779a62784 |
def score(self, string): <NEW_LINE> <INDENT> prev, current, score = None, None, defaultdict(float) <NEW_LINE> for ngram in ngrams(string, self.n): <NEW_LINE> <INDENT> current = self[ngram] <NEW_LINE> if len(current) > 0: <NEW_LINE> <INDENT> for language in self.languages: <NEW_LINE> <INDENT> score[language] += current[... | score the string via it's n-grams | 625941d01d351010ab855c8e |
def delete_deployment(self, service_name, deployment_name, complete=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> req = self.service.delete_deployment(service_name, deployment_name, delete_vhd=complete) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.log.error("delete deployment %s failed: %r... | delete a deployment from azure
this is the sync wrapper of ServiceManagementService.delete_deployment | 625941d099cbb53fe6792d58 |
def test_get_success_url(self): <NEW_LINE> <INDENT> self.assertEqual( TaskCreateView(object=TaskFactory()).get_success_url(), reverse('tasks:home') ) | " upon success, redirect to tasks:home | 625941d063f4b57ef000128a |
def insertion_sort(alist): <NEW_LINE> <INDENT> size = len(alist) <NEW_LINE> print(alist) <NEW_LINE> for i in range(1, size): <NEW_LINE> <INDENT> j = i <NEW_LINE> while j > 0 and alist[j - 1][1] > alist[j][1]: <NEW_LINE> <INDENT> print('alist[j - 1][1]\t', alist[j - 1][1]) <NEW_LINE> print('alist[j][1]\t', alist[j][1]) ... | Takes a tuple of string, int pairs and performs insertion sort
based on int in descending order.
Args:
alist (list): a list of integers
Returns:
int: the number of comparisons performed in the sort | 625941d010dbd63aa1bd2d16 |
def isAbsoluteCall(instruction): <NEW_LINE> <INDENT> return getOpcode(instruction) == b'\x9a' | call Ap | 625941d0d164cc6175782ec0 |
def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> self.env_settings = super().get_env_settings() <NEW_LINE> self.original_path = self.env_settings.value(super().SYNC_ENV_VARIABLE) <NEW_LINE> self.path = os.path.join(self.original_path, "tree") <NEW_LINE> self.path = r'%s' % self.path <NEW_LINE> pathlib.Pa... | Metodo che viene chiamato prima di ogni metodo | 625941d0b7558d58953c5085 |
def merge(self, other): <NEW_LINE> <INDENT> raise RuntimeError("Cannot merge resources of kind {}".format(self.kind)) | Construct a 'merged' resource, given another resource with the same kind and id.
Generally, resources can be merged if all fields either match or can be combined
in some way, such as taking the union of scopesets | 625941d03cc13d1c6d3c74ec |
def validate(self, rendered_action_data, action_data, search, action): <NEW_LINE> <INDENT> silent_errors = action_data.get('silent_errors', False) <NEW_LINE> if action not in ['create', 'assertion'] or action_data.get( 'skip_validation' ): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> model = getattr(entities, action_... | Based on action fields or using action_data['search_query']
searches the system and validates the existence of all entities | 625941d0a05bb46b383ec993 |
@asyncio.coroutine <NEW_LINE> def from_url(url, login_method='AMQPLAIN', insist=False, protocol_factory=AmqpProtocol): <NEW_LINE> <INDENT> url = urlparse(url) <NEW_LINE> if url.scheme not in ('amqp', 'amqps'): <NEW_LINE> <INDENT> raise ValueError('Invalid protocol %s, valid protocols are amqp or amqps' % url.scheme) <N... | Connect to the AMQP using a single url parameter and return the client.
| 625941d063b5f9789fde7258 |
def getStringOrDefault(self): <NEW_LINE> <INDENT> strVal = self.getString() <NEW_LINE> return strVal or self.defValueStr | Return the current value of the field, or the default if blank
Raise ValueError or TypeError is current value is invalid. | 625941d066656f66f7cbc31d |
def get_transparent_colour(self): <NEW_LINE> <INDENT> if self == Colour.RED: <NEW_LINE> <INDENT> return Colour.PINK <NEW_LINE> <DEDENT> if self == Colour.BLACK: <NEW_LINE> <INDENT> return Colour.GREY <NEW_LINE> <DEDENT> raise ValueError(f'This only works for red or black, not {self}') | Converts a dark colour to a light colour.
Args:
colour (Colour): The input colour.
Returns:
Colour: The lighter version of the input colour.
Raises:
ValueError: If self is not red or black. | 625941d0ac7a0e7691ed423e |
def get_all(self): <NEW_LINE> <INDENT> return self.driver.get_all() | Returns all services | 625941d0d10714528d5ffe56 |
def qualname(self, name): <NEW_LINE> <INDENT> aliases = [] <NEW_LINE> nocases = [] <NEW_LINE> classes = [] <NEW_LINE> name_lowered = name.lower() <NEW_LINE> for qualname, entry in self.items(): <NEW_LINE> <INDENT> if name == entry.name: <NEW_LINE> <INDENT> return qualname <NEW_LINE> <DEDENT> if name in entry.aliases: <... | Find a fully qualified lexicon name for the specified name.
First, tries to find the exact match on the ``name`` attribute, then
the aliases, then a case insensitive match, and then the same for the
Language class name. | 625941d01f037a2d8b946370 |
def plot1(nE,m,n,interval=[0,1.0e-2]): <NEW_LINE> <INDENT> Vup, Vdown = SC1GNRTop(nE,m,n) <NEW_LINE> fXi = np.vectorize(lambda w: X1RPAGNRTop(nE,m,n,Vup,Vdown,w).imag) <NEW_LINE> wilist, Xitemp = sample_function(fXi,interval, tol=1e-3) <NEW_LINE> Xilist = Xitemp[0] <NEW_LINE> pl.plot(wilist,Xilist) <NEW_LINE> pl.savefi... | Calculates the susceptibility against w for a single impurity.
Optionally allows the user to specify an interval on which the susceptibility will be plotted.
nE: Ribbon Width
m1,n1: Location of first impurity
s: Sublattice (0:bb,1:bw,-1:wb)
interval: plotting range | 625941d0b7558d58953c5086 |
def setUp(self): <NEW_LINE> <INDENT> self.url = self.url + reverse('deleteReaction') <NEW_LINE> self.reaction = PerformedReaction.objects.get( reference='turkish_delight', labGroup__title='narnia') <NEW_LINE> self.payload['id'] = self.reaction.id <NEW_LINE> super(DeletePerformedReaction, self).setUp() | Allow for dynamic url. | 625941d05510c4643540f556 |
def get_val_data(self, batch_size): <NEW_LINE> <INDENT> transform_val = transforms.Compose([ transforms.Resize(256), transforms.RandomResizedCrop(224), transforms.ToTensor(), transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ]) <NEW_LINE> td = MultilabelDataset(data_folder=self.val_folder, data_file=se... | 获取验证数据,数据扩充 | 625941d060cbc95b062c66b6 |
def should_parse(item): <NEW_LINE> <INDENT> return (isinstance(item, str) and not item.startswith('!') or isinstance(item, int)) | 判断是否需要解析:不以!开头的字符串或数字 | 625941d0ec188e330fd5a910 |
def fanio(*code): <NEW_LINE> <INDENT> ext = FanInOut() <NEW_LINE> def process(ext, code): <NEW_LINE> <INDENT> result = FileAnalyzer(get_extensions([ext])).analyze_source_code("a.cpp", code) <NEW_LINE> ext.reduce(result) <NEW_LINE> return result <NEW_LINE> <DEDENT> results = [process(ext, code) for code in code] <NEW_LI... | this helper function can simulate the situation that multiple files are
processed with the io extension. | 625941d0a934411ee3751806 |
def update_sfc_port_chain(self, port_chain, body=None): <NEW_LINE> <INDENT> return self.put(self.sfc_port_chain_path % port_chain, body=body) | Update a Port Chain. | 625941d04f6381625f114bad |
def post_list(request): <NEW_LINE> <INDENT> posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') <NEW_LINE> return render(request, 'blog/post_list.html', {'posts': posts}) | this function is for landing page of blog site | 625941d0cad5886f8bd2714c |
def find(self): <NEW_LINE> <INDENT> yield from self._read_includes(self.cc_file) | Yield the transitive includes. | 625941d0656771135c3eb9e2 |
def __getitem__(self, i): <NEW_LINE> <INDENT> start = self.__start + i*self.__step <NEW_LINE> if start >= self.__end: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return Segment(start=start, end=start+self.__duration) | Parameters
----------
i : int
Index of sliding window position
Returns
-------
segment : :class:`Segment`
Sliding window at ith position | 625941d02eb69b55b151ca23 |
def _write_chrm(f, chromaticity): <NEW_LINE> <INDENT> data = (100000 * _np.array(chromaticity) + 0.5).astype(_np.uint32) <NEW_LINE> chunk_data = _struct.pack('!IIIIIIII', *data.ravel()) <NEW_LINE> _write_chunk(f, b'cHRM', chunk_data) | Write a cHRM chunk to `f`. | 625941d0d164cc6175782ec1 |
@localserviceHandle <NEW_LINE> def CreateZuDui_4301(key,dynamicId,request_proto): <NEW_LINE> <INDENT> argument = CreateZuDui4301_pb2.CreateZuDuiRequest() <NEW_LINE> argument.ParseFromString(request_proto) <NEW_LINE> dynamicId = dynamicId <NEW_LINE> pid = argument.id <NEW_LINE> pos = argument.pos <NEW_LINE> gkType = arg... | 创建队伍
| 625941d03c8af77a43ae3914 |
def parse(parser): <NEW_LINE> <INDENT> def outer_wrapper(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> kwargs['data'] = parser.parse_args() <NEW_LINE> return func(*args, **kwargs) <NEW_LINE> <DEDENT> return wrapper <NEW_LINE> <DEDENT> return outer_wrapper | Uses a RequestParser to require a specific body schema | 625941d030c21e258bdfa611 |
def test_bad_responses(self): <NEW_LINE> <INDENT> json_return = 'foobar' <NEW_LINE> status_code = 422 <NEW_LINE> history = WebHistory('http://blah', 'asdf') <NEW_LINE> response_mock = mock.MagicMock() <NEW_LINE> response_mock.status_code = status_code <NEW_LINE> response_mock.json.return_value = json_return <NEW_LINE> ... | Test we raise when a connection is bad. | 625941d0f548e778e58cd6f1 |
def __str__(self): <NEW_LINE> <INDENT> if self.corner1 is not None: <NEW_LINE> <INDENT> if self.corner2 is not None: <NEW_LINE> <INDENT> return self.corner1.__str__() + ':' + self.corner2.__str__() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.corner1.__str__() + ':None' <NEW_LINE> <DEDENT> <DEDENT> else: <... | Override __str__ to print meaningful string representation | 625941d007d97122c4178a00 |
def filter_blue( rgb, red_upper_thresh, green_upper_thresh, blue_lower_thresh, output_type="bool", ): <NEW_LINE> <INDENT> r = rgb[:, :, 0] < red_upper_thresh <NEW_LINE> g = rgb[:, :, 1] < green_upper_thresh <NEW_LINE> b = rgb[:, :, 2] > blue_lower_thresh <NEW_LINE> result = ~(r & g & b) <NEW_LINE> if output_type == "bo... | Create a mask to filter out blueish colors, where the mask is based on a pixel being below a
red channel threshold value, below a green channel threshold value, and above a blue channel threshold value.
Args:
rgb: RGB image as a NumPy array.
red_upper_thresh: Red channel upper threshold value.
green_upper_t... | 625941d02c8b7c6e89b35933 |
def __eq__(self, f): <NEW_LINE> <INDENT> return bool() | bool KFileMetaInfo.WhatFlags.__eq__(KFileMetaInfo.WhatFlags f) | 625941d063d6d428bbe44662 |
def from_json(self, filename: str) -> None: <NEW_LINE> <INDENT> with open(filename, "r") as f: <NEW_LINE> <INDENT> json_data = json.load(f) <NEW_LINE> <DEDENT> load_from_json(self, json_data) | Set's the class's data with attributes taken from the save file | 625941d0b57a9660fec339f7 |
def SetWizardButtons(self,flags:'Any') -> 'None': <NEW_LINE> <INDENT> pass | Enables the wizard buttons
Args:
flags(Any):The wizard flags
Returns:
None
| 625941d0099cdd3c635f0dce |
def dump_to_file(out_file, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(out_file, 'w') as out_f: <NEW_LINE> <INDENT> out_f.write(data) <NEW_LINE> <DEDENT> out_f.close() <NEW_LINE> <DEDENT> except IOError as err: <NEW_LINE> <INDENT> log_error("{0} - I/O error({1}): {2}".format(out_file, err.errno, err.s... | Dump data to a file | 625941d03539df3088e2e4be |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.