code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _get_arns(self): <NEW_LINE> <INDENT> client = self._get_client() <NEW_LINE> account_arns = set() <NEW_LINE> for role in list_roles(**self.conn_details): <NEW_LINE> <INDENT> account_arns.add(role['Arn']) <NEW_LINE> <DEDENT> for user in list_users(**self.conn_details): <NEW_LINE> <INDENT> account_arns.add(user['Arn']... | Gets a list of all Role ARNs in a given account, optionally limited by
class property ARN filter
:return: list of role ARNs | 625941dacc40096d61595c04 |
def load_and_process(self): <NEW_LINE> <INDENT> msg = 'There is an error with your input! \n' <NEW_LINE> try: <NEW_LINE> <INDENT> self.files_raw <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> msg = msg + '\n Please select raw input files' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.output_path <NE... | Once all parameters have been chosen, checks all the input values and
begins the processing. | 625941dadd821e528d63b45c |
def _update_domain(api_key, zone_name, domain_list, ttl): <NEW_LINE> <INDENT> api = _create_api_client(api_key) <NEW_LINE> zone_id = _get_zone_for_name(api, api_key, zone_name) <NEW_LINE> ip_address = _get_current_address() <NEW_LINE> needs_update = [] <NEW_LINE> for record in api.domain.zone.record.list(api_key, zone_... | gandi api to update an ip address | 625941da50812a4eaa59c5d3 |
def closest_station(lat, lon, cache_dir): <NEW_LINE> <INDENT> if lat is None or lon is None or not os.path.isdir(cache_dir): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> stations = bom_stations(cache_dir) <NEW_LINE> def comparable_dist(wmo_id): <NEW_LINE> <INDENT> station_lat, station_lon = stations[wmo_id] <NEW_LINE... | Return the ZONE_ID.WMO_ID of the closest station to our lat/lon. | 625941da287bf620b61d3d16 |
def cmpxchg(self, loc, expected, desired, weak=False, ord_succ=MuMemOrd.SEQ_CST, ord_fail=MuMemOrd.SEQ_CST): <NEW_LINE> <INDENT> _assert_instance(loc, MuIRefValue) <NEW_LINE> weak = int(weak) <NEW_LINE> succ_buf = ctypes.c_int(0) <NEW_LINE> rv = self.cmpxchg_(ord_succ, ord_fail, weak, loc, expected, desired, ctypes.byr... | Wrapper of the underlying ``cmpxchg``.
It is strong by default.
The memory orders are optional and defaults to MuMemOrd.SEQ_CST.
The return value is a pair (value, succ), where value is a MuValue of
the old value, and succ is a bool which indicates whether this operation
is successful. | 625941da23e79379d52ee815 |
def state_path(self, obs_seq): <NEW_LINE> <INDENT> V, prev = self.viterbi(obs_seq) <NEW_LINE> last_state = np.argmax(V[:, -1]) <NEW_LINE> path = list(self.build_viterbi_path(prev, last_state)) <NEW_LINE> return V[last_state, -1], reversed(path) | :return:
V[last_state, -1]:float
probability of the optimal state path
path:list(int)
Optimal state path for the observation sequence | 625941da4f6381625f114cf0 |
def strStr(self, haystack, needle): <NEW_LINE> <INDENT> if len(needle) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> next = self.GetNext(needle) <NEW_LINE> i = 0 <NEW_LINE> j = 0 <NEW_LINE> sLen = len(haystack) <NEW_LINE> pLen = len(needle) <NEW_LINE> while i < sLen and j < pLen: <NEW_LINE> <INDENT> if j == -1... | :type haystack: str
:type needle: str
:rtype: int | 625941da8a43f66fc4b54317 |
def chu(*args): <NEW_LINE> <INDENT> res = args[0:1] <NEW_LINE> res = float(res[0]) <NEW_LINE> for i in args[1:]: <NEW_LINE> <INDENT> i = float(i) <NEW_LINE> res /= i <NEW_LINE> <DEDENT> return res | 除法解析
:param args:
:return: | 625941da460517430c394434 |
def castToInt(self,data): <NEW_LINE> <INDENT> if re.search(rm_prnth,data): <NEW_LINE> <INDENT> return int(data[1:len(data)-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return int(data) | This method takes the 'data' and returns an integer that removes the
parathesis surrounding it and casts it to an int. | 625941daa17c0f6771cbe304 |
def hyper_param_search_function(X_train, y_train, hyper_param_space, classifier_type = RandomForestClassifier, n_iter = 30, search_method = 'random_search', resampling=False, **kwargs): <NEW_LINE> <INDENT> hyperparam_results = Counter() <NEW_LINE> cv_fold_X_train, cv_fold_X_val, cv_fold_y_train, cv_fold_y_val = train_t... | Args: training data + hyperparam search space according to the sklearn classifier being passed;
**kwargs is for the resampling params like upsampling ratios for my custom data augmentation function
The search_method specifies whether its a RandomSearchCV or a GridSearchCV being passed inside | 625941dabde94217f36830a3 |
def __del_publisher(self, prefix): <NEW_LINE> <INDENT> pval = self.get_property("property", "publisher-search-order") <NEW_LINE> if prefix in pval: <NEW_LINE> <INDENT> self.remove_property_value("property", "publisher-search-order", prefix) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.remove_section("authority_{0}... | Accessor method for publishers | 625941daf7d966606f6aa2bc |
def deserialize_numpy(self, str, numpy): <NEW_LINE> <INDENT> codecs.lookup_error("rosmsg").msg_type = self._type <NEW_LINE> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.obsts is None: <NEW_LINE> <INDENT> self.obsts = None <NEW_LINE>... | unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module | 625941da442bda511e8be6c9 |
def create_namespace_with_name_from_yaml(v1: CoreV1Api, name, yaml_manifest) -> str: <NEW_LINE> <INDENT> print(f"Create a namespace with specific name: {name}") <NEW_LINE> with open(yaml_manifest) as f: <NEW_LINE> <INDENT> dep = yaml.safe_load(f) <NEW_LINE> dep["metadata"]["name"] = name <NEW_LINE> v1.create_namespace(... | Create a namespace with a specific name based on a yaml manifest.
:param v1: CoreV1Api
:param name: name
:param yaml_manifest: an absolute path to file
:return: str | 625941dad53ae8145f87a520 |
def jenkins_api_query_build_statuses(jenkins_url): <NEW_LINE> <INDENT> return "{url}/api/json?tree=builds[result,number]".format(url=jenkins_url) | Construct API query to Jenkins (CI). | 625941da9f2886367277ab40 |
def _exclude_unwanted_cc_tests(tests): <NEW_LINE> <INDENT> tests = [test for test in tests if not test.startswith('test/cpp/qps:')] <NEW_LINE> tests = [ test for test in tests if not test.startswith('test/cpp/ext/filters/census:') ] <NEW_LINE> tests = [ test for test in tests if not test.startswith('test/cpp/microbench... | Filters out bazel tests that we don't want to run with other build systems or we cannot build them reasonably | 625941da507cdc57c6306f94 |
def pdf_report_generate(self, cnx, mysql=False, postgres=False): <NEW_LINE> <INDENT> aux = ControllerHelper() <NEW_LINE> ret = aux._EXIT_SUCCESS <NEW_LINE> model = ReporterModel() <NEW_LINE> (hdr_set, row_set) = model.get_data_items_by_date(self.FROM, self.TO, cnx, mysql, postgres) <NEW_LINE> if (not(row_set)): <NEW_LI... | Generates the PDF report.
Args:
cnx: The database connection object.
Kwargs:
mysql: The indicator that shows whether the database connection
object is MySQL connection.
(Default is False)
postgres: The indicator that shows whether the database connection
object... | 625941da1f037a2d8b9464b2 |
def IsMultiPolygon(self) -> "bool": <NEW_LINE> <INDENT> return _gskernel.GsPolygon_IsMultiPolygon(self) | 是否是复合多边形(具有多个外圈的多边形) | 625941dab545ff76a89140ca |
def addItems(self, items, select=False): <NEW_LINE> <INDENT> self.itemsWidget().addItems(items) <NEW_LINE> self._items.extend(items) <NEW_LINE> if select: <NEW_LINE> <INDENT> self.selectItems(items) <NEW_LINE> self.scrollToSelectedItem() | Add the given items to the itemsWidget.
:type items: list[studiolibrary.LibraryItem]
:type select: bool
:rtype: None | 625941da26238365f5f0f126 |
def make_public(self): <NEW_LINE> <INDENT> self._is_public = True | Makes the document public. Sets the :py:attr:is_public attribute to True.
:return: | 625941dae1aae11d1e749f6e |
def test_distance(self, strategy): <NEW_LINE> <INDENT> input_1 = np.matrix( [[0, 1 / 3.], [0, 1.], [2 / 3., 1.]], dtype=np.float32) <NEW_LINE> input_3 = np.matrix([[2 / 3., 0], [2 / 3., 2 / 3.], [0, 2 / 3.]], dtype=np.float32) <NEW_LINE> output = strategy.compute_distance(input_1, input_3) <NEW_LINE> assert_allclose(ou... | Tests the computation of the distance of two trajectories | 625941da090684286d50ef9c |
def isAromatic(self): <NEW_LINE> <INDENT> cython.declare(rc=list, cycle=list, atom=Atom) <NEW_LINE> rc = self.getRelevantCycles() <NEW_LINE> if rc: <NEW_LINE> <INDENT> for cycle in rc: <NEW_LINE> <INDENT> if len(cycle) == 6: <NEW_LINE> <INDENT> for atom in cycle: <NEW_LINE> <INDENT> if atom.atomType.label == 'Cb' or at... | Returns ``True`` if the molecule is aromatic, or ``False`` if not.
Iterates over the SSSR's and searches for rings that consist solely of Cb
atoms. Assumes that aromatic rings always consist of 6 atoms.
In cases of naphthalene, where a 6 + 4 aromatic system exists,
there will be at least one 6 membered aromatic ri... | 625941da30bbd722463cc07d |
def draw_solution(self): <NEW_LINE> <INDENT> self.canvas.delete('solved') <NEW_LINE> path = self.cmap.get_smooth_path() <NEW_LINE> for p in range(len(path)-1): <NEW_LINE> <INDENT> self.draw_edge(path[p], path[p+1], color='#DDDD00', width=5, tags='solved') | "Redraw one solution from start to goal
| 625941da0fa83653e465726e |
def _atualizar_irmaos(self): <NEW_LINE> <INDENT> for node in self: <NEW_LINE> <INDENT> if node.left: <NEW_LINE> <INDENT> node.left.brother_right = node.right <NEW_LINE> <DEDENT> <DEDENT> if self.apontada_por: <NEW_LINE> <INDENT> if self.lista_elementos[-1].right: <NEW_LINE> <INDENT> if self.brother_right: <NEW_LINE> <I... | :return: Atualiza todos os irmãos de todos os filhos dessa página | 625941daf9cc0f698b1408ae |
def count_sub_in_file(filename, s): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = open(filename, 'r') <NEW_LINE> text = f.read().split(s) <NEW_LINE> f.close <NEW_LINE> return len(text) - 1 <NEW_LINE> <DEDENT> except FileNotFoundError: <NEW_LINE> <INDENT> return -1 | Takes two arguments, 'filename', the name of the file in
which this function searches and 's', the string this function
searches for. Returns how many times 's' apears in the file. | 625941da4c3428357757c5db |
def _validate_newly_encountered_seqs_indicator(self, newly_encountered_seqs_indicator): <NEW_LINE> <INDENT> pass | Validates the newly encountered seqs indicator.
The vanilla TP doesnt need any extra step in falsifying newly encountered sequences. | 625941da507cdc57c6306f95 |
def __init__(self, embed_size): <NEW_LINE> <INDENT> super(EncoderCNN, self).__init__() <NEW_LINE> resnet = models.resnet152(pretrained=True) <NEW_LINE> modules = list(resnet.children())[:-1] <NEW_LINE> self.resnet = nn.Sequential(*modules) <NEW_LINE> self.linear = nn.Linear(resnet.fc.in_features, embed_size) <NEW_LINE>... | Load the pretrained ResNet-152 and replace top fc layer. | 625941dacb5e8a47e48b7d5b |
def intersection(r1, r2): <NEW_LINE> <INDENT> area = interval_intersection(r1[:2], r2[:2]) * interval_intersection(r1[2:], r2[2:]) <NEW_LINE> return area | intersection of two rectangles
:param r1 tuple (left, right, top, bottom), rectangle 1
:param r2: tuple (left, right, top, bottom), rectangle 2
:return: the intersection area | 625941dad10714528d5fff9a |
def run(self): <NEW_LINE> <INDENT> self._stop_called.clear() <NEW_LINE> self._process_done.clear() <NEW_LINE> try: <NEW_LINE> <INDENT> with lock(self): <NEW_LINE> <INDENT> self._scanner.clear() <NEW_LINE> self._exc = None <NEW_LINE> self._scanner.start(passive=False) <NEW_LINE> while True: <NEW_LINE> <INDENT> self._sca... | Run the thread. | 625941da377c676e9127245d |
def __str__(self): <NEW_LINE> <INDENT> return self.name | Return the name of the teamtype. | 625941da60cbc95b062c67f8 |
def test_parser_discontinuities_snx(): <NEW_LINE> <INDENT> parser = get_parser("discontinuities_snx").as_dict() <NEW_LINE> assert len(parser) == 9 <NEW_LINE> assert "0194" in parser <NEW_LINE> assert "solution_discontinuity" in parser["ab06"] <NEW_LINE> assert "point_code" in parser["ab06"]["solution_discontinuity"][0] | Test that parsing discontinuities_snx gives expected output | 625941da21a7993f00bc7fa8 |
def vendor_in_use(self, vendor_id): <NEW_LINE> <INDENT> collections = ['cabinets', 'shelving_units', 'toolchests', 'tools', 'workbenches'] <NEW_LINE> for collection_name in collections: <NEW_LINE> <INDENT> collection = self.schema.get_collection(collection_name) <NEW_LINE> res = collection.find('vendorid = :param1'). ... | Search collections for vendor id | 625941da15baa723493c422c |
def create_node(self, name, size, image, server_key=None, console_key=None, zone=None, **kwargs): <NEW_LINE> <INDENT> hostname = kwargs.get('hostname', name) <NEW_LINE> service_type = size.id <NEW_LINE> image = image.id <NEW_LINE> connect_attempts = int(kwargs.get('connect_attempts', CONNECT_ATTEMPTS)) <NEW_LINE> data ... | Creates the node, and sets the ssh key, console key
NephoScale will respond with a 200-200 response after sending a valid
request. If nowait=True is specified in the args, we then ask a few
times until the server is created and assigned a public IP address,
so that deploy_node can be run
>>> from libcloud.compute.prov... | 625941daac7a0e7691ed437d |
def drawTop(self): <NEW_LINE> <INDENT> self.top = Top(master=self, bg='#99CCFF', height=self.topH) <NEW_LINE> self.top.place(in_=self, relwidth=1, y=0) | 画出顶部栏 | 625941da5f7d997b87174d4f |
def contour(X,Y,Z, extent=None, vrange=None, levels=None, extend='both', inaxis=None, cmap=None, addcolorbar=True, clabel=None, smooth=True, smoothlen=None): <NEW_LINE> <INDENT> XX, YY = _getmesh(X,Y,Z) <NEW_LINE> extent = _getextent(extent, XX, YY) <NEW_LINE> vrange = _getvrange(vrange, XX,YY,Z, inaxis=inaxis) <NEW_LI... | Build a super fancy contour image | 625941da4e696a04525c9701 |
def _logout(self): <NEW_LINE> <INDENT> logout(self.request) <NEW_LINE> self._ctx.isLogin = False | Do logout | 625941da57b8e32f52483751 |
def near2d(x, y, x0, y0): <NEW_LINE> <INDENT> dx = np.abs(x - x0); dx = dx / dx.max() <NEW_LINE> dy = np.abs(y - y0); dy = dy / dy.max() <NEW_LINE> dn = dx + dy <NEW_LINE> fn = np.where(dn == dn.min()) <NEW_LINE> line = int(fn[0]) <NEW_LINE> col = int(fn[1]) <NEW_LINE> return line, col | Find the indexes of the grid point that is
nearest a chosen (x0, y0).
Usage: line, col = near2d(x, y, x0, y0) | 625941da925a0f43d254a12e |
def __init__(self, thermistor, mosfet, name, onoff_control): <NEW_LINE> <INDENT> self.thermistor = thermistor <NEW_LINE> self.mosfet = mosfet <NEW_LINE> self.name = name <NEW_LINE> self.current_temp = 0.0 <NEW_LINE> self.target_temp = 0.0 <NEW_LINE> self.last_error = 0.0 <NEW_LINE> self.error_integral = 0.0 <NEW_LINE> ... | Init | 625941da23849d37ff7b3342 |
def constraint_add_with_targets(type=''): <NEW_LINE> <INDENT> pass | Add a constraint to the active object, with target (where applicable) set to the selected Objects/Bones
Arguments:
@type (str): in ['CAMERA_SOLVER', 'FOLLOW_TRACK', 'OBJECT_SOLVER', 'COPY_LOCATION', 'COPY_ROTATION', 'COPY_SCALE', 'COPY_TRANSFORMS', 'LIMIT_DISTANCE', 'LIMIT_LOCATION', 'LIMIT_ROTATION', 'LIMIT_SCALE', 'M... | 625941da5fcc89381b1e1976 |
def remove_all_containers(self, stop_timeout=10, raise_on_error=False, list_only=False): <NEW_LINE> <INDENT> containers = [(container['Id'], container['Status']) for container in self.containers(all=True)] <NEW_LINE> running_containers = [c_id for c_id, status in containers if not (status.startswith('Exited') or status... | First stops (if necessary) and them removes all containers present on the Docker instance.
:param stop_timeout: Timeout to stopping each container.
:type stop_timeout: int
:param raise_on_error: Forward errors raised by the client and cancel the process. By default only logs errors.
:type raise_on_error: bool
:param l... | 625941dade87d2750b86004a |
def _fix_paths(self, data): <NEW_LINE> <INDENT> data['include_paths'] = [join('$PROJ_DIR$', path) for path in data['include_paths']] <NEW_LINE> if data['linker_file']: <NEW_LINE> <INDENT> data['linker_file'] = join('$PROJ_DIR$', data['linker_file']) <NEW_LINE> <DEDENT> data['groups'] = {} <NEW_LINE> for attribute in SO... | All paths needs to be fixed - add PROJ_DIR prefix + normalize | 625941da85dfad0860c3b110 |
@app.route('/') <NEW_LINE> def home(): <NEW_LINE> <INDENT> if not g.user: <NEW_LINE> <INDENT> return redirect(url_for('login')) <NEW_LINE> <DEDENT> msg = CDLC.query.all() <NEW_LINE> for m in msg: <NEW_LINE> <INDENT> m.tags = [y.strip() for y in m.tags.split(';')] <NEW_LINE> <DEDENT> return render_template('home.html', ... | Shows a users timeline or if no user is logged in it will
redirect to the public timeline. This timeline shows the user's
messages as well as all the messages of followed users. | 625941da6e29344779a628c5 |
@login_required <NEW_LINE> def stu_entries(request, activity_pk): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> activity = Activity.objects.get(pk=activity_pk) <NEW_LINE> if activity.student.user.email != request.user.email: <NEW_LINE> <INDENT> return HttpResponseRedirect('/activities') <NEW_LINE> <DEDENT> name = activi... | Function to satify the gathering of entries for a particular activity | 625941da090684286d50ef9d |
def sanitize_collection_extension(self, extension): <NEW_LINE> <INDENT> if extension: <NEW_LINE> <INDENT> return extension.lstrip(".") <NEW_LINE> <DEDENT> return self.ext | Returns the `extension` without the leading dot, if given, or the default one
`Output.ext` otherwise. | 625941da44b2445a33932349 |
def santa_elevator(instructions: str) -> int: <NEW_LINE> <INDENT> current_floor = 0 <NEW_LINE> for step in instructions: <NEW_LINE> <INDENT> if step == "(": <NEW_LINE> <INDENT> current_floor += 1 <NEW_LINE> <DEDENT> elif step == ")": <NEW_LINE> <INDENT> current_floor -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r... | Help Santa navigate the large apartment building!
`instructions` is a string of parentheses, where ( goes up one floor and ) goes down one floor
Returns the destination floor | 625941da1f5feb6acb0c4e01 |
def btreeGameWinningMove(self, root, n, x): <NEW_LINE> <INDENT> point_num = [0, 0, 0] <NEW_LINE> target_node = [None] <NEW_LINE> def recursive(node): <NEW_LINE> <INDENT> if not node or target_node[0]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if node.val == x: <NEW_LINE> <INDENT> target_node[0] = node <NEW_LINE> r... | :type root: TreeNode
:type n: int
:type x: int
:rtype: bool | 625941da44b2445a3393234a |
def value_leaf(self, data, schema, tree): <NEW_LINE> <INDENT> key, value = data <NEW_LINE> schema_key, schema_value = schema <NEW_LINE> if hasattr(schema_value, '__validator_leaf__'): <NEW_LINE> <INDENT> return schema_value(value, tree) <NEW_LINE> <DEDENT> enforce(value, schema_value, tree, 'value') | The deepest validation we can make in any given circumstance for
a value. Does not recurse, it will just receive both values and the
tree, passing them on to the :fun:`enforce` function. | 625941daec188e330fd5aa50 |
def compare_directories(xvals, dir1, dir2): <NEW_LINE> <INDENT> processes = re.compile("eBrem|msc|eIoni|compt|phot|Rayl|conv") <NEW_LINE> particles = re.compile("e-|proton|gamma") <NEW_LINE> materials = re.compile("cellular|water|davis") <NEW_LINE> files1 = os.listdir(dir1) <NEW_LINE> files2 = os.listdir(dir2) <NEW_LIN... | fig = compare(xvals, particle, processes, medium1, medium2, label1, label2,
emin, emax)
emin and emax are strings | 625941da07f4c71912b11739 |
def getOption(self, p, name): <NEW_LINE> <INDENT> d = self.scriptSettingsDict <NEW_LINE> name = self.munge(name) <NEW_LINE> trace = False and not g.unitTesting <NEW_LINE> verbose = False <NEW_LINE> assert p, g.callers() <NEW_LINE> def dump(kind, p, val): <NEW_LINE> <INDENT> if trace: <NEW_LINE> <INDENT> g.pr('getOption... | Return the value of the named option at node p. | 625941da091ae3566866720f |
def fit(self, tol=1e-6, reg_factor=10.0, max_reg=1.0, max_iter=1000): <NEW_LINE> <INDENT> raise NotImplementedError | Fits the model.
Args:
tol (float): Tolerance.
reg_factor (float): Regularization multiplicative factor.
max_reg (float): Maximum regularization term.
max_iter (int): Maximum number of iterations.
Returns:
Number of iterations. | 625941da5e10d32532c5f1dc |
def _fixup_scope(self, scope): <NEW_LINE> <INDENT> if scope is None: <NEW_LINE> <INDENT> scope = ldap.SCOPE_SUBTREE <NEW_LINE> <DEDENT> elif scope == 'base': <NEW_LINE> <INDENT> scope = ldap.SCOPE_BASE <NEW_LINE> <DEDENT> elif scope == 'onelevel': <NEW_LINE> <INDENT> scope = ldap.SCOPE_ONELEVEL <NEW_LINE> <DEDENT> elif... | Check the ldap scope `scope'. | 625941daa934411ee3751949 |
def run_websocket_server(): <NEW_LINE> <INDENT> import asyncio <NEW_LINE> factory = BroadcastServerFactory(settings.WEBSOCKET_URL, debug=settings.WEBSOCKET_DEBUG) <NEW_LINE> factory.protocol = BroadcastServerProtocol <NEW_LINE> factory.setProtocolOptions() <NEW_LINE> loop = asyncio.get_event_loop() <NEW_LINE> server = ... | Démarre le service de broadcasting par websocket
:return: Rien | 625941da3346ee7daa2b3022 |
def _on_dec(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError("Value of the field '{}' cannot be decremented".format(self._name)) | Hook, called by self.dec_val(), must return external value representation
| 625941da7b25080760e3970d |
def upwind_x(self,func,u): <NEW_LINE> <INDENT> funret = np.zeros((self.nx,self.ny)) <NEW_LINE> forward = np.roll(func, 1, axis=0) <NEW_LINE> backward = np.roll(func, -1, axis=0) <NEW_LINE> pos = np.where(u >= 0) <NEW_LINE> neg = np.where(u < 0) <NEW_LINE> funret[pos[0],pos[1]] = (func[pos[0],pos[1]]-backward[pos[0],pos... | upwind difference scheme in x-direction | 625941da4e4d5625662d468a |
def decryption_materials(self, encryption_context): <NEW_LINE> <INDENT> decryption_material_description = encryption_context.material_description.copy() <NEW_LINE> initial_material = self._decrypt_initial_material(encryption_context) <NEW_LINE> signing_key_info = KeyInfo.from_material_description( material_description=... | Provide decryption materials.
:param EncryptionContext encryption_context: Encryption context for request
:returns: Encryption materials
:rtype: RawDecryptionMaterials | 625941da56ac1b37e6264481 |
def main(): <NEW_LINE> <INDENT> description = ('Create 2 EPGs within the same Context and have' '1 EPG provide a contract to the other EPG.') <NEW_LINE> creds = Credentials('apic', description) <NEW_LINE> args = creds.get() <NEW_LINE> tenant = Tenant('aci-toolkit-demo') <NEW_LINE> app = AppProfile('my-demo-app', tenant... | Create 2 EPGs within the same Context and have
1 EPG provide a contract to the other EPG. | 625941dac432627299f04efd |
def create_schema(self, type_schm, schema, name=None, check=True): <NEW_LINE> <INDENT> if "keys" not in schema["datasets"][0]: <NEW_LINE> <INDENT> assert(len(schema["datasets"]) == 1), "keys are optional if and only if there is one dataset" <NEW_LINE> schema["datasets"][0]["keys"] = [] <NEW_LINE> <DEDENT... | Create a new schema into the current collection
:param type_schm: ``train``, ``test`` or ``export``
:param schema: a python dictionary recording datasets like this
::
{
"tags": ["dataset", "tag"],
"datasets": [
{
"name": "Dataset Name",
"filepath": "/pa... | 625941dabf627c535bc13484 |
def hit_cnt(self, x): <NEW_LINE> <INDENT> clf_cluster_dict = AbuUmpBase.dump_clf_manager.get_ump(self) <NEW_LINE> hit_cnt = 0 <NEW_LINE> for clf, cluster in clf_cluster_dict.values(): <NEW_LINE> <INDENT> predict_cluster = clf.predict(x) <NEW_LINE> if predict_cluster == cluster: <NEW_LINE> <INDENT> hit_cnt += 1 <NEW_LIN... | 辅助统计工具函数,从CachedUmpManager中获取缓存clf_cluster_dict,迭代ump字典对象,
对交易特征形成的x使用字典中元素(clf, cluster)中的clf进行predict
结果和 (clf, cluster)中存储的cluster一致的情况下代表hit
:param x: 交易特征形成的x eg: array([[ 8.341, -9.45 , 0.73 , 12.397]])
:return: kwargs关键字参数所描述的交易特征进行分类簇命中统计,返回int值 | 625941da26068e7796caef97 |
def set_write_firmware_pointer(self, pointer): <NEW_LINE> <INDENT> self.check_validity() <NEW_LINE> pointer = int(pointer) <NEW_LINE> self.ipcon.send_request(self, BrickletDMX.FUNCTION_SET_WRITE_FIRMWARE_POINTER, (pointer,), 'I', 0, '') | Sets the firmware pointer for :func:`Write Firmware`. The pointer has
to be increased by chunks of size 64. The data is written to flash
every 4 chunks (which equals to one page of size 256).
This function is used by Brick Viewer during flashing. It should not be
necessary to call it in a normal user program. | 625941dad486a94d0b98e3fc |
def test_index_contains_locations(self): <NEW_LINE> <INDENT> resp = self.app.get('/') <NEW_LINE> self.assertTrue('{"cities":' in resp.data) <NEW_LINE> self.assertTrue('Portland, Oregon' in resp.data) <NEW_LINE> self.assertTrue('Corpus Christi, Texas' in resp.data) <NEW_LINE> self.assertTrue('"all": "http://chicago.crai... | The index should load and render JSON data for Craigslist
locations. | 625941da67a9b606de4a816e |
def test_future_question_and_past_question(self): <NEW_LINE> <INDENT> create_question(question_text="Past question.", days=-30) <NEW_LINE> create_question(question_text="Future question.", days=30) <NEW_LINE> response = self.client.get(reverse('polls:index')) <NEW_LINE> self.assertQuerysetEqual( response.context['lates... | Even if both past and future questions exist, only past question
are displayed. | 625941da63f4b57ef00013c8 |
def _query(self, sql, params=None, many=False): <NEW_LINE> <INDENT> if many: <NEW_LINE> <INDENT> call = getattr(self._cursor, 'executemany') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> call = getattr(self._cursor, 'execute') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> call(sql, params) <NEW_LINE> self._connection.co... | Internal method for running SQL commands
The code difference between execute, and executemany is just the method
we call on the cursor object.
:Returns: Generator
:param sql: **Required** The SQL syntax to execute
:type sql: String
:param params: The values to use in a parameterized SQL query
:type params: Iterable... | 625941da462c4b4f79d1d986 |
def test_with_six_old_questions(self): <NEW_LINE> <INDENT> create_question(question_text='old_question_1', days=1) <NEW_LINE> create_question(question_text='old_question_2', days=6) <NEW_LINE> create_question(question_text='old_question_3', days=5) <NEW_LINE> create_question(question_text='old_question_4', days=4) <NEW... | view MUST show five questions and sort them by -pub_date | 625941da3617ad0b5ed681ac |
def get_orders(self, asset, currency): <NEW_LINE> <INDENT> orders = self.market.Order.Order_getOrders(symbol=asset + currency, reverse=True).result() <NEW_LINE> orderList = orders[0] <NEW_LINE> return orderList | :param asset:
:param currency: | 625941dad99f1b3c44c67841 |
def stop(self): <NEW_LINE> <INDENT> return _gnuradio_core_gengen.gr_sub_ss_sptr_stop(self) | stop(self) -> bool | 625941da01c39578d7e750f1 |
def on_outgoing(self, topic, headers, message, match): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.outgoing.send_message( topic, headers, *message, flags=NOBLOCK) <NEW_LINE> <DEDENT> except ZMQError as e: <NEW_LINE> <INDENT> if e.errno == EINTR: <NEW_LINE> <INDENT> continue <NEW_LI... | Forward messages to external subscribers. | 625941dacc40096d61595c05 |
def index_of(index: int, of: int): <NEW_LINE> <INDENT> return '{!r} of {!r}'.format(index, of) | Return '$index of $of'
Arguments:
index {int} -- index
of {int} -- count
Returns:
str -- string | 625941da31939e2706e4d11c |
@templatedoc() <NEW_LINE> def sequence_reverse(x, name=None): <NEW_LINE> <INDENT> assert not in_dygraph_mode(), ( "sequence layer is not supported in dygraph mode yet.") <NEW_LINE> helper = LayerHelper("sequence_reverse", **locals()) <NEW_LINE> check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int8', 'int32', 'i... | **Notes: The Op only receives LoDTensor as input. If your input is Tensor, please use reverse Op.(fluid.layers.** :ref:`api_fluid_layers_reverse` ).
This operator only supports LoDTensor as input. It will reverse each sequence for input LoDTensor.
Currently it only supports 1-level LoDTensor. This operator is very use... | 625941da460517430c394435 |
def make_reject(self, request, queryset): <NEW_LINE> <INDENT> rows = queryset.update(status='Rejected') <NEW_LINE> self.status_message(request, rows, 'Rejected') | Function to update the status as Rejected | 625941dab7558d58953c51c6 |
def __init__(self, mu, beta, infected, population, n=1000, max_t=100): <NEW_LINE> <INDENT> self.mu = mu <NEW_LINE> self.beta = beta <NEW_LINE> self.population = float(population) <NEW_LINE> self.n = n <NEW_LINE> self.max_t = max_t <NEW_LINE> I0 = float(infected)/population <NEW_LINE> S0 = 1-I0 <NEW_LINE> R0 = 0 <NEW_LI... | Args:
mu: Mu as defined in the basic SIR equations
beta: Beta as defined in the basic SIR equations
infected: number of people infected initially
population: the total number of people represented in the curve
n: number of time steps
max_t: upper bound of number of days | 625941dae64d504609d74af6 |
def ExportCreateReferenceModelObjectAttributeEnumerator(self, pEnumerator): <NEW_LINE> <INDENT> pass | ExportCreateReferenceModelObjectAttributeEnumerator(self: ICDelegate, pEnumerator: dotReferenceModelObjectAttributeEnumerator_t) -> (int, dotReferenceModelObjectAttributeEnumerator_t) | 625941da7d43ff24873a2f57 |
def send(event=None, msg=""): <NEW_LINE> <INDENT> client_socket.send(bytes(msg, "utf8")) <NEW_LINE> if msg == "{quit}": <NEW_LINE> <INDENT> client_socket.close() | Handles sending of messages. | 625941da4e4d5625662d468b |
def generate_tilted_profile_line(mat, index, angle): <NEW_LINE> <INDENT> if mat.ndim != 2: <NEW_LINE> <INDENT> raise ValueError("Input must be a 2D array !!!") <NEW_LINE> <DEDENT> (height, width) = mat.shape <NEW_LINE> x_cen = (width - 1.0) / 2 <NEW_LINE> y_cen = (height - 1.0) / 2 <NEW_LINE> x_list = np.arange(0, widt... | Generate a tilted horizontal intensity-profile of an image.
Parameters
----------
mat : array_like
2D array.
index : int
Index of the line.
angle : float
Tilted angle in degree.
Returns
-------
array_like
1D array. | 625941da8e7ae83300e4b283 |
def vtkVariantLessThan(s1, s2): <NEW_LINE> <INDENT> return (s1 < s2) | Return true if s1 < s2. This isn't very useful in Python. | 625941da82261d6c526ab758 |
def signed_url(self, key): <NEW_LINE> <INDENT> params = {'Bucket': self.bucket, 'Key': key} <NEW_LINE> url = self.s3.generate_presigned_url( 'get_object', Params=params) <NEW_LINE> return url | Generate a signed URL to GET an object | 625941dabd1bec0571d908e5 |
def get_multi(self, hrefs): <NEW_LINE> <INDENT> for href in hrefs: <NEW_LINE> <INDENT> item, etag = self.get(href) <NEW_LINE> yield href, item, etag | :param hrefs: list of hrefs to fetch
:raises: :exc:`vdirsyncer.exceptions.PreconditionFailed` if one of the
items couldn't be found.
:returns: iterable of (href, item, etag) | 625941da9c8ee82313fbba2b |
def get_fav(user): <NEW_LINE> <INDENT> db = sqlite3.connect(DB_FILE) <NEW_LINE> c = db.cursor() <NEW_LINE> fav_data = [] <NEW_LINE> temp = c.execute("SELECT recipe, id FROM favRec WHERE username = '{}'".format(user)).fetchall() <NEW_LINE> for entry in temp: <NEW_LINE> <INDENT> fav_data.append(entry) <NEW_LINE> <DEDENT>... | Retrieve a list of the user's favorites for given type. | 625941da5fdd1c0f98dc04ea |
def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile): <NEW_LINE> <INDENT> pixels = array('B') <NEW_LINE> pixels.fromfile(ppmfile, self.bytes_per_sample * self.color_depth * self.width * self.height) <NEW_LINE> apixels = array('B') <NEW_LINE> apixels.fromfile(pgmfile, self.bytes_per_sample * self.width * self.height... | Convert a PPM and PGM file containing raw pixel data into a
PNG outfile with the parameters set in the writer object. | 625941da91af0d3eaac9bcd1 |
def substring_at_node(self, node): <NEW_LINE> <INDENT> substring = "" <NEW_LINE> while node != 0: <NEW_LINE> <INDENT> substring = self.word[self.nodes[node].edge_start:self.nodes[node].edge_end - 0] + substring <NEW_LINE> node = self.nodes[node].upstream <NEW_LINE> <DEDENT> return substring | Reads the substring that leads from the root to the specified node.
Arguments: int
Returns: str | 625941da45492302aab5e57c |
def new_mpiserviceaccount(job, name, jobname): <NEW_LINE> <INDENT> if not name: <NEW_LINE> <INDENT> name = build_name(job) <NEW_LINE> <DEDENT> if not jobname: <NEW_LINE> <INDENT> jobname = jobname_name(job) <NEW_LINE> <DEDENT> serviceaccount = { 'apiVersion': 'v1', 'kind': 'ServiceAccount', 'metadata': { 'labels': { 'g... | MPI launcher serviceaccount for kubectl access to worker Pods | 625941da5510c4643540f694 |
def __init__(self): <NEW_LINE> <INDENT> self.ImageIds = None <NEW_LINE> self.Filters = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> self.InstanceType = None | :param ImageIds: 镜像ID列表 。镜像ID如:`img-gvbnzy6f`。array型参数的格式可以参考[API简介](https://cloud.tencent.com/document/api/213/15688)。镜像ID可以通过如下方式获取:<br><li>通过[DescribeImages](https://cloud.tencent.com/document/api/213/15715)接口返回的`ImageId`获取。<br><li>通过[镜像控制台](https://console.cloud.tencent.com/cvm/image)获取。
:type Image... | 625941dabe383301e01b5737 |
def get_account(self,type): <NEW_LINE> <INDENT> self.host = self.env_entry.get() <NEW_LINE> register = Register(self.host) <NEW_LINE> phone = register.random_mobile() <NEW_LINE> password = '111111' <NEW_LINE> yewu = { 1: '一级批发商', 2:'二级批发商', 3:'零售商' } <NEW_LINE> sucess = True <NEW_LINE> try: <NEW_LINE> <INDENT> work_thr... | 创建账号,返回账号信息 | 625941daa05bb46b383ecad6 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, TeamNextGameScheduleTeamsAwayTeam): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941dacc40096d61595c06 |
@event.listens_for(Session, "before_flush") <NEW_LINE> def update_backtrace_quality(session, flush_context, instances) -> None: <NEW_LINE> <INDENT> objects = session.new.union(session.dirty) <NEW_LINE> for obj in [c for c in objects if isinstance(c, ReportBacktrace)]: <NEW_LINE> <INDENT> if isinstance(obj, ReportBacktr... | Compute and store backtrace quality information | 625941da96565a6dacc8f981 |
def get_top_frequents(self, top=42): <NEW_LINE> <INDENT> return self.tf_dist.most_common(top) | The method identifies and returns top frequent terms.
Args:
top (int): Size of the short list (default 42).
Returns:
(:obj:`list` of :obj:`tuple` of :obj:`str` and :obj:`int`): Returns the frequency dist
for top terms as list of tuples of term and frequency pairs. | 625941dad58c6744b4257f14 |
def add_user(self, user_id, user_ip): <NEW_LINE> <INDENT> self.users.set_registed_user(user_id, user_ip) <NEW_LINE> print("LOG: %s from %s has been added" % (user_id, user_ip)) | add the user into the database | 625941da4527f215b584c70a |
def pause(vm_): <NEW_LINE> <INDENT> with _get_xapi_session() as xapi: <NEW_LINE> <INDENT> vm_uuid = _get_label_uuid(xapi, 'VM', vm_) <NEW_LINE> if vm_uuid is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> xapi.VM.pause(vm_uuid) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exce... | Pause the named vm
CLI Example::
salt '*' virt.pause <vm name> | 625941daa219f33f34628c1c |
def select(self): <NEW_LINE> <INDENT> warnings.filterwarnings("ignore", category=DeprecationWarning) <NEW_LINE> try: <NEW_LINE> <INDENT> best_score, best_model = max([ScoredModel(self.cv_score(num_states)) for num_states in range(self.min_n_components, self.max_n_components + 1)]) <NEW_LINE> return best_model <NEW_LINE... | select the best model for self.this_word based on
CV score for n between self.min_n_components and self.max_n_components
It is based on log likehood
:return: GaussianHMM object | 625941da8a43f66fc4b54319 |
def setEditorData(self, editor, index): <NEW_LINE> <INDENT> if isinstance(editor,QtGui.QComboBox): <NEW_LINE> <INDENT> editor.addItems(index.model().getData(index)) <NEW_LINE> self.editor.view().setMinimumWidth(self.calculateListWidth()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> editor.setText(index.model().getData... | @summary Overrides QItemDelegate's setEditorData method. Sets the widget's data after createEditor has created it
@param editor , index : see QItemDelegate's doc for more information | 625941da0a50d4780f66714b |
def get_P_2(self, xi_0=None, time=None): <NEW_LINE> <INDENT> if xi_0 is None: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> xi_0 = self.xi_0 <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> print("self.xi_0 must already be set, or passed as an option") <NEW_LINE> raise <NEW_LINE> <DEDENT> <DEDENT> if time ... | Get post-shock fluid pressure | 625941da046cf37aa974cffc |
def __setitem__(self, key, value): <NEW_LINE> <INDENT> self.weights[key] = value | This sets the weight of a feature couple (x,y) given as key.
Enables the 'w[] = ' syntax.
@param key: a couple (x,y) of observed value and class value
@param value: a real | 625941dab545ff76a89140cc |
def _list(self, node, indent=0): <NEW_LINE> <INDENT> assert node, "Invalid node given." <NEW_LINE> if node: <NEW_LINE> <INDENT> print(" " * indent, node.key, "=", node.value) <NEW_LINE> if node.left: <NEW_LINE> <INDENT> print(" " * indent, "<", end="") <NEW_LINE> self._list(node.left, indent+1) <NEW_LINE> <DEDENT> if n... | Print out the contents of the list. | 625941da1f037a2d8b9464b4 |
def xyztoradec(xyz): <NEW_LINE> <INDENT> if len(xyz.shape) == 1: <NEW_LINE> <INDENT> rs,ds = xyztoradec(xyz[newaxis,:]) <NEW_LINE> return (rs[0], ds[0]) <NEW_LINE> <DEDENT> (nil,three) = xyz.shape <NEW_LINE> assert(three == 3) <NEW_LINE> ra = arctan2(xyz[:,1], xyz[:,0]) <NEW_LINE> ra += 2*pi * (ra < 0) <NEW_LINE> dec =... | Converts positions on the unit sphere to RA,Dec in degrees.
'xyz' must be a numpy array, either of shape (3,) or (N,3)
Returns a tuple (RA,Dec).
If 'xyz' is a scalar, RA,Dec are scalars.
If 'xyz' is shape (N,3), RA,Dec are shape (N,).
>>> xyztoradec(array([1,0,0]))
(0.0, 0.0)
>>> xyztoradec(array([ [1,0,0], [0,1,... | 625941da8e05c05ec3eea62d |
def makeIsoCurveFeature(): <NEW_LINE> <INDENT> selfobj = App.ActiveDocument.addObject("Part::FeaturePython","IsoCurve") <NEW_LINE> IsoCurve(selfobj) <NEW_LINE> ViewProviderIsoCurve(selfobj.ViewObject) <NEW_LINE> return selfobj | makeIsoCurveFeature(): makes a IsoCurve parametric feature object. Returns the new object. | 625941dabe8e80087fb20ef6 |
def insertRows(self, p_int, *__args): <NEW_LINE> <INDENT> pass | insertRows(self, int, int)
insertRows(self, int, Iterable[QStandardItem]) | 625941dae1aae11d1e749f70 |
def get_playnow ( self ): <NEW_LINE> <INDENT> if not self.user: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> track = self.user.get_now_playing() <NEW_LINE> if not track: <NEW_LINE> <INDENT> recent_track = self.user.get_recent_tracks(limit=1) <NEW_LINE> if len(recent_track) > 0: <NEW_LINE> <INDENT> recent_track = ... | Return dict "{'artist': 'track_artist', 'title': 'track_title'}" | 625941da30bbd722463cc07f |
def conv2d_nhwc(Input, Filter, stride, padding, dilation, out_dtype='float32'): <NEW_LINE> <INDENT> assert isinstance(stride, int) or len(stride) == 2 <NEW_LINE> assert isinstance(dilation, int) or len(dilation) == 2 <NEW_LINE> if isinstance(stride, int): <NEW_LINE> <INDENT> stride_h = stride_w = stride <NEW_LINE> <DED... | Convolution operator in NHWC layout.
Parameters
----------
Input : tvm.Tensor
4-D with shape [batch, in_height, in_width, in_channel]
Filter : tvm.Tensor
4-D with shape [filter_height, filter_width, in_channel, num_filter]
stride : int or a list/tuple of two ints
Stride size, or [stride_height, stride_wi... | 625941da004d5f362079a5e9 |
@cli.command() <NEW_LINE> @click.pass_context <NEW_LINE> @click.argument("input", nargs=-1, required=False, callback=alias.alias_checker) <NEW_LINE> def diary(ctx, input): <NEW_LINE> <INDENT> input = util.get_arguments(ctx, -1) <NEW_LINE> if input: <NEW_LINE> <INDENT> test_string = "" <NEW_LINE> for i in input: <NEW_LI... | Maintain a personal diary
roughly based on the concept of Bullet Journal (http://bulletjournal.com/)
Commands:
nn: New note
nt: new Task
dt: delete task
notes: view all notes
ut: update task
un: update note
dct: delete all completed tasks
dn:delete particular note
tasks: view all completed and incomplete ... | 625941dad4950a0f3b08c602 |
def _get_url(self): <NEW_LINE> <INDENT> raise NotImplementedError('override this method') | Return movie, person url | 625941da07d97122c4178b47 |
def connect(self, parent): <NEW_LINE> <INDENT> raise ValueError('%s should always be root.' %self.__class__.__name__) | RootPipelineNode denies connect().
| 625941dadc8b845886cb57ed |
@botcmd <NEW_LINE> @ignore_msg_from_self <NEW_LINE> def hq_vater(self, mess, args): <NEW_LINE> <INDENT> hq_vater = '' <NEW_LINE> try: <NEW_LINE> <INDENT> hq_vater += os.popen('/home/freebot/pentabot/shell/hq-check-vater.sh').read() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> hq_vater += 'Sorry Dude' <NEW_LINE> <DED... | User availability | 625941da377c676e9127245e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.