code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def restart(self): <NEW_LINE> <INDENT> self.stop() <NEW_LINE> self.start() | Restart the daemon process | 625941ce76e4537e8c3517a1 |
def test2(): <NEW_LINE> <INDENT> pass | >>> x = Yolo(1)
>>> x.g(3)
4
>>> x.g(5)
6
>>> x.motto = 5
>>> x.g(5)
10 | 625941cea4f1c619b28b0167 |
def testMolpro_Molpro2012_dvb_gopt_unconverged_out(logfile): <NEW_LINE> <INDENT> assert hasattr(logfile.data, 'optdone') and not logfile.data.optdone | An unconverged geometry optimization to test for empty optdone (see #103 for details). | 625941ce8c0ade5d55d3eae9 |
def check_errors(self, check=None): <NEW_LINE> <INDENT> if (check if check is not None else self.check) and self.error_type is not None: <NEW_LINE> <INDENT> raise self.error_type(self) | Raise an exception if the external command failed.
This raises :attr:`error_type` when :attr:`check` is set and the
external command failed.
:param check: Override the value of :attr:`check` for the duration of
this call. Defaults to :data:`None` which means
:attr:`check` is not overridden... | 625941cee64d504609d7496e |
def add_to_ruby_dictionary(d, file_info, ruby_dict): <NEW_LINE> <INDENT> led = file_info[0] <NEW_LINE> thickness = file_info[1] <NEW_LINE> wavelength = file_info[2] <NEW_LINE> direction = file_info[3] <NEW_LINE> if led not in ruby_dict: <NEW_LINE> <INDENT> ruby_dict[led] = {} <NEW_LINE> <DEDENT> if thickness not in rub... | :param d: List
[time, counts] for a given monochromator wavelength. Where time and counts are both lists of floats.
:param file_info: List
Expects a list in the form [LED Wavelength, Ruby Thickness, Monochromator Wavelength, up/down, date(mm/dd)]
where each entry is a string.
:return: None. Modifies the dictionary in p... | 625941ce0383005118ecf711 |
def SplitNumbers(text): <NEW_LINE> <INDENT> lst = MATCH_SPLIT.split(text) <NEW_LINE> if lst[0] == '': <NEW_LINE> <INDENT> del lst[0] <NEW_LINE> <DEDENT> if len(lst) > 0 and lst[len(lst) - 1] == '': <NEW_LINE> <INDENT> del lst[len(lst) - 1] <NEW_LINE> <DEDENT> return lst | Splits text to list of phone numbers. | 625941ce507cdc57c6306e0a |
def _get_bus_column(self, bus): <NEW_LINE> <INDENT> if bus == self.topology.lines_df.at[self.branch, "bus0"]: <NEW_LINE> <INDENT> col = "bus0" <NEW_LINE> <DEDENT> elif bus == self.topology.lines_df.at[self.branch, "bus1"]: <NEW_LINE> <INDENT> col = "bus1" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_L... | Returns column name of lines_df given bus is in. | 625941ced18da76e23532605 |
@coroutine <NEW_LINE> def inputAssocHandler(): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> fileSection, node = (yield) <NEW_LINE> for inputnode in node.children: <NEW_LINE> <INDENT> data = {} <NEW_LINE> for subnode in inputnode.children: <NEW_LINE> <INDENT> data.__setitem__(subnode.name, subnode.text) <NEW_LINE... | _inputAssocHandler_
Sink to handle output:input association information. Given the following
XML:
<Input>
<LFN>/path/to/some/lfn.root</LFN>
<PFN>/some/pfn/info/path/to/some/lfn.root</PFN>
</Input>
Extract the LFN and call the addInputToFile() function to associate input to
output in the FWJR. | 625941ceaad79263cf390b70 |
def createSquare(size): <NEW_LINE> <INDENT> if size % 2 == 0: <NEW_LINE> <INDENT> print('Size must be odd') <NEW_LINE> return False <NEW_LINE> <DEDENT> magic_square = np.zeros((size,size), dtype=int) <NEW_LINE> n = 1 <NEW_LINE> i, j = 0, size//2 <NEW_LINE> while n <= size**2: <NEW_LINE> <INDENT> magic_square[i, j] = n ... | Creates an N x N magic square
In a magic square, every row, column, and diagonal add up to the same number.
@param size The size of the magic square
@return A boolean representing if the square was created or not | 625941cecc40096d61595a7f |
@pytest.mark.parametrize('cls', [TotalOrdered, OrderedLt]) <NEW_LINE> def test_given_cmp_function_bytes_fails(cls): <NEW_LINE> <INDENT> with pytest.raises(ValueError) as err: <NEW_LINE> <INDENT> orderedstructs.SkipList(bytes, lambda x, y: x < y) <NEW_LINE> <DEDENT> assert err.value.args[0] == 'Can not specify... | Test of passing in a non-callable.
This can be detected at instantiation time. | 625941ce99fddb7c1c9de4bf |
def __deepcopy__(self, memo=None): <NEW_LINE> <INDENT> if self.on_device.get("mask"): <NEW_LINE> <INDENT> mask = self.cl_mem["mask"].get() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mask = None <NEW_LINE> <DEDENT> if memo is None: <NEW_LINE> <INDENT> memo = {} <NEW_LINE> <DEDENT> radial = self.radial.copy() <NEW_LIN... | deep copy of the object
:return: deepcopy of the object | 625941ce460517430c3942b3 |
def get_dices(min_edge_value=1, max_edge_value=6, dices_count=5): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for _ in range(dices_count): <NEW_LINE> <INDENT> result.append(random.randint(min_edge_value, max_edge_value)) <NEW_LINE> <DEDENT> return result | Получение сл. значений пяти кубиков
:rtype: list of int | 625941cebde94217f3682f1f |
def __init__(self, session_key): <NEW_LINE> <INDENT> super(Talk, self).__init__() <NEW_LINE> self.session_key = session_key <NEW_LINE> self.tcp_clients = [] <NEW_LINE> self.participants = [] <NEW_LINE> if self.session_key in Talk.talk_sessions: <NEW_LINE> <INDENT> raise NameError("There already exists a session with th... | Set up the instance variables. | 625941ce63b5f9789fde7214 |
def validate_file(fpath, file_hash, algorithm='auto', chunk_size=65535): <NEW_LINE> <INDENT> if ((algorithm == 'sha256') or (algorithm == 'auto' and len( file_hash) == 64)): <NEW_LINE> <INDENT> hasher = 'sha256' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hasher = 'md5' <NEW_LINE> <DEDENT> if str(_hash_file(fpath, ha... | Validates a file against a sha256 or md5 hash.
:param fpath: path to the file being validated
:param file_hash: The expected hash string of the file.
The sha256 and md5 hash algorithms are both supported.
:param algorithm: Hash algorithm, one of 'auto', 'sha256', or 'md5'.
The default 'auto' detects the hash ... | 625941ce66656f66f7cbc2d9 |
def find_orthogonal_complement(U_basis, W_basis): <NEW_LINE> <INDENT> return [v for v in orthogonalize(U_basis + W_basis)[len(U_basis):] if not v.is_almost_zero()] | Find the list of vectors that form the orthogonal complement of U with respect to W
Vectors u*1..k have same span and are nonzero
as u1..k is linearly independent. n-k of the remaining vectors of
w*1..n are nonzero and every one is orthogonal to u1..n, so they
are orthogonal to every vector in U.
:param U_basis: list ... | 625941cebde94217f3682f20 |
def get_allocation_stats(self): <NEW_LINE> <INDENT> return _nrt_mstats(alloc=_nrt.memsys_get_stats_alloc(), free=_nrt.memsys_get_stats_free(), mi_alloc=_nrt.memsys_get_stats_mi_alloc(), mi_free=_nrt.memsys_get_stats_mi_free()) | Returns a namedtuple of (alloc, free, mi_alloc, mi_free) for count of
each memory operations. | 625941cecad5886f8bd27108 |
def onRestart(self): <NEW_LINE> <INDENT> SimonTurtle.reset(self) <NEW_LINE> print("neue Lösung bereit auf Turtle (Länge: {})".format(self.size)) | Reset screen on restart
(overwritten method from SimonSays) | 625941cea05bb46b383ec950 |
def _initial_population(self): <NEW_LINE> <INDENT> population = [Route(self.points) for _ in range(self.ARGS["size"])] <NEW_LINE> return np.array(population) | Creates an initial population made of Routes
:return: list of Route objects | 625941ce9c8ee82313fbb8a4 |
def normalize(lines): <NEW_LINE> <INDENT> count = 1 <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> count, l = _simplify_closure(line, count) <NEW_LINE> for newline in l: <NEW_LINE> <INDENT> yield newline | Normalizes a set of (parsed) lines. | 625941ce97e22403b379d0c8 |
def model(data, train=False): <NEW_LINE> <INDENT> conv = tf.nn.conv2d(data, conv1_weights, strides=[1, 1, 1, 1], padding='SAME') <NEW_LINE> conv = tf.nn.bias_add(conv, conv1_biases) <NEW_LINE> pool = tf.nn.max_pool(conv, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') <NEW_LINE> pool_shape = pool.get_shape().... | The Model definition. | 625941ce097d151d1a222f88 |
def match(self, regex, reCompileFlag=0): <NEW_LINE> <INDENT> match = None <NEW_LINE> if isinstance(regex, Content.compiled_re_type): <NEW_LINE> <INDENT> match = regex.search(self.string[self.pos:]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> match = re.search(self.string[self.pos:], flags = reCompileFlag) <NEW_LINE> ... | If re matches at current position in the subject, advance the position
in string content and return the match; otherwise return None | 625941ced99f1b3c44c676bd |
def hashBand(cur_band,buckets_list): <NEW_LINE> <INDENT> for c in cur_band.columns: <NEW_LINE> <INDENT> hs = hash(tuple(cur_band[c].values)) <NEW_LINE> if hs in buckets_list: <NEW_LINE> <INDENT> buckets_list[hs].append(c) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> buckets_list[hs] = [c] | Function to hash one band of the document given as input to one of the buckets
in bucket list given as input. | 625941ce92d797404e3042b9 |
def convert_DT_string(byte_string, is_little_endian, struct_format=None): <NEW_LINE> <INDENT> if config.datetime_conversion: <NEW_LINE> <INDENT> byte_string = byte_string.decode(default_encoding) <NEW_LINE> splitup = byte_string.split("\\") <NEW_LINE> if len(splitup) == 1: <NEW_LINE> <INDENT> return _DT_from_byte_strin... | Return a decoded 'DT' value.
Parameters
----------
byte_string : bytes or str
The encoded 'DT' element value.
is_little_endian : bool
``True`` if the value is encoded as little endian, ``False`` otherwise.
struct_format : str, optional
Not used.
Returns
-------
str or list of str or valuerep.DT or list of... | 625941cefb3f5b602dac37c2 |
def __init__(self, butler=None, refObjLoader=None, **kwargs): <NEW_LINE> <INDENT> Task.__init__(self, **kwargs) <NEW_LINE> if not refObjLoader: <NEW_LINE> <INDENT> self.makeSubtask("refObjLoader", butler=butler) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.refObjLoader = refObjLoader | !Ctor
Either a 'butler' or 'refObjLoader' is required.
@param butler Data butler, or None
@param refObjLoader For loading reference objects (lsst.meas.algorithms.LoadReferenceObjectsTask), or
None
@param kwargs Other keyword arguments required for instantiating a Task (e.g., 'config') | 625941ce3cc13d1c6d3c74a9 |
def SetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkMinimumImageFilterPython.itkMinimumImageFilterIF3IF3IF3_Superclass_SetFunctor(self, *args) | SetFunctor(self, itk::Function::Minimum<(float,float,float)> functor) | 625941ced58c6744b4257d8f |
def __init__(self, grid_height, grid_width, frames_used): <NEW_LINE> <INDENT> self.frames_used = frames_used <NEW_LINE> self.grid_height = grid_height <NEW_LINE> self.grid_width = grid_width <NEW_LINE> self.grid_shape = self.grid_height, self.grid_width <NEW_LINE> self.grid_size = grid_height*grid_width <NEW_LINE> self... | To make printing easier the coordinates refer to
distance from the top border
distance from the left border | 625941ce4f6381625f114b69 |
def mle_estimate(self): <NEW_LINE> <INDENT> c = ptu.zeros(self.weights.shape[:2]) <NEW_LINE> ind = torch.argmax(self.weights, dim=1) <NEW_LINE> c.scatter_(1, ind, 1) <NEW_LINE> s = torch.matmul(self.normal_means, c[:, :, None]) <NEW_LINE> return torch.squeeze(s, 2) | Return the mean of the most likely component.
This often computes the mode of the distribution, but not always. | 625941ce63f4b57ef0001248 |
def _addLdapConfiguration(self, ldapConfiguration): <NEW_LINE> <INDENT> updateConfigurationCmd = updateConfiguration.updateConfigurationCmd() <NEW_LINE> updateConfigurationCmd.name = "ldap.basedn" <NEW_LINE> updateConfigurationCmd.value = ldapConfiguration['basedn'] <NEW_LINE> updateConfigurationResponse = self.apiClie... | :param ldapConfiguration | 625941cee1aae11d1e749de6 |
def test_loop_through_genbank(self): <NEW_LINE> <INDENT> newf = os.path.join(self.test_dir, "new.gbk") <NEW_LINE> af.make_new_genbank( genbank=self.ref_gb, new_genbank=newf, approved_accessions=["IPDMBIDP_00043"], logger=logger) <NEW_LINE> nlines = 0 <NEW_LINE> with open(newf, "r") as inf: <NEW_LINE> <INDENT> for line ... | test creation of new gb after filtering.
Not the greatest test | 625941cebe8e80087fb20d71 |
def get_time_segments(self, sampling): <NEW_LINE> <INDENT> if isinstance(sampling, Analysis): <NEW_LINE> <INDENT> sampling = sampling.data <NEW_LINE> <DEDENT> return sampling.tessellation.time_lattice | Returns the time segment bounds as an Nx2 array. | 625941ce3eb6a72ae02ec60d |
def gen_braid_maze(w, h, braid_degree=1.0): <NEW_LINE> <INDENT> amap = gen_perfect_maze(w, h) <NEW_LINE> for x in xrange(0, w, 2): <NEW_LINE> <INDENT> for y in xrange(0, h, 2): <NEW_LINE> <INDENT> connections = 0 <NEW_LINE> if amap.grid[x][y].kind != 'wall': <NEW_LINE> <INDENT> if x > 0 and amap.grid[x - 1][y].kind != ... | Generate a braid maze.
The braid_degree is a float between 0 and 1, indicating the chance
of extending a dead-end through the wall. | 625941ce45492302aab5e3f2 |
def preprocess_validation_batch(batch_size): <NEW_LINE> <INDENT> filename = 'preprocess_validation_model_20.p' <NEW_LINE> features, labels = pickle.load(open(filename, mode='rb')) <NEW_LINE> return batch_features_labels(features, labels, batch_size) | Load the Preprocessed validation data and return them in batches of <batch_size> or less | 625941ce1f5feb6acb0c4c7f |
def send_message(module, client_id, client_secret, topic, msg): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> access_token = get_access_token(module, client_id, client_secret) <NEW_LINE> url = 'https://typetalk.com/api/v1/topics/%d' % topic <NEW_LINE> headers = { 'Authorization': 'Bearer %s' % access_token, } <NEW_LINE>... | send message to typetalk | 625941ce5f7d997b87174bc7 |
def sgd(w, dw, config): <NEW_LINE> <INDENT> w -= config['learning_rate'] * dw <NEW_LINE> return w, config | Performs vanilla stochastic gradient descent.
config format:
- learning_rate: Scalar learning rate. | 625941ce8c3a8732951584ea |
def quoteIdent(self, ident): <NEW_LINE> <INDENT> return '%s%s%s' % (self.ident_quote, ident, self.ident_quote) | Wrap an identifier into appropriate quotes.
``ident`` is wrapped by the character specified by the database's
``ident_quote`` field.
INPUT:
- ``ident`` - the identifier to be quoted. | 625941ceb7558d58953c5043 |
def get_values(self): <NEW_LINE> <INDENT> values = OrderedDict() <NEW_LINE> for name in dir(self): <NEW_LINE> <INDENT> if name[0] != '_' or name[1] == '_': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> values[name[1:]] = str(getattr(self, name)) <NEW_LINE> <DEDENT> return values | Get the option values as a dict.
| 625941cea79ad161976cc275 |
def get(self, name, **kwargs): <NEW_LINE> <INDENT> self.request = requests.get(self.build_url(kwargs), headers=self.headers) | This is for get requests. | 625941ce21bff66bcd684a82 |
@hug.delete('/', output=hug.output_format.json) <NEW_LINE> def deletePokemon(body): <NEW_LINE> <INDENT> cursor = cnx.cursor() <NEW_LINE> print(body.get("id")) <NEW_LINE> try: <NEW_LINE> <INDENT> cursor.execute("""DELETE FROM pokemon WHERE pokemon.id = %s""", [str(body.get("id"))]) <NEW_LINE> cnx.commit() <NEW_LINE> <DE... | Delete a pokemon | 625941ce0fa83653e46570ea |
def get_the_countrys_table(country): <NEW_LINE> <INDENT> table = get_the_full_table() <NEW_LINE> country_table = table[table['Country'] == country] <NEW_LINE> return country_table | Return the table with only one country in the 'Country' column left. | 625941ce293b9510aa2c33c5 |
def serve(): <NEW_LINE> <INDENT> options = command_line_options() <NEW_LINE> log = configure_logging(options) <NEW_LINE> log.info("Starting application") <NEW_LINE> routes = route.get_routes() <NEW_LINE> routes.append((r"/public/(.*)", StaticFileHandler, {"path": "public"})) <NEW_LINE> routes = routes + TornadioRouter(... | application entry point | 625941cec432627299f04d75 |
def dump(self, obj): <NEW_LINE> <INDENT> if self.schema_class: <NEW_LINE> <INDENT> obj = self.schema_class().dump(obj).data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> obj = obj['metadata'] <NEW_LINE> <DEDENT> return super(MARCXMLSerializer, self).dump(obj) | Serialize object with schema.
:param obj: The object to serialize.
:returns: The object serialized. | 625941ce9c8ee82313fbb8a5 |
def test_create_user_object(): <NEW_LINE> <INDENT> from .scripts.initializedb import create_user_object <NEW_LINE> user_object = create_user_object("test", "test", "test") <NEW_LINE> assert isinstance(user_object, User) | Test create_user_object returns a User model. | 625941ce91f36d47f21ac622 |
def __init__(self, ai_settings, screen, ship): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.rect = pygame.Rect( 0, 0, ai_settings.bullet_width, ai_settings.bullet_height ) <NEW_LINE> self.rect.centerx = ship.rect.centerx <NEW_LINE> self.rect.top = ship.rect.top <NEW_LINE> self.... | 在飞船所处的地方创建一个子弹对象 | 625941ce01c39578d7e74f6a |
def get_recProfile(self): <NEW_LINE> <INDENT> return self.get_History_attr('profile') | The value of recProfile depends on the presence of History attribute on profile option. | 625941ce30bbd722463cbef5 |
def blob(frame, x_ways=8, y_ways=7, bins_per_color=D, with_prost=False): <NEW_LINE> <INDENT> all_features = [] <NEW_LINE> h, w = frame.shape[1: 3] <NEW_LINE> bin_size = int(np.floor(255. / bins_per_color)) <NEW_LINE> nh, nw = int(np.ceil(h / y_ways)), int(np.ceil(w / x_ways)) <NEW_LINE> all_blobs = [] <NEW_LINE> for ch... | Blob features for a single sample.
:param frame: a single frame, hxwx3
:param x_ways: Divide x dimension of sample by `x_ways`
:param y_ways: Divide y dimension of sample by `y_ways`
:param bins_per_color: Split each color into this many bins.
:param with_prost: Add prost features
:return: h2xw2x3 where h2=h/y_ways, w... | 625941cee76e3b2f99f3a93a |
@pytest.mark.tier(2) <NEW_LINE> @pytest.mark.manual('manualonly') <NEW_LINE> @pytest.mark.meta(coverage=[1531914, 1534589]) <NEW_LINE> def test_quota_with_invalid_service_request(): <NEW_LINE> <INDENT> pass | This test case is to test quotas with various regions and invalid service requests
To reproduce this issue: (You"ll need to have the RedHat Automate
domain)
Polarion:
assignee: ghubale
initialEstimate: 1/4h
caseimportance: medium
caseposneg: positive
testtype: functional
startsin: 5.9
casec... | 625941ce4527f215b584c586 |
def test_internal(self): <NEW_LINE> <INDENT> pfa = process_from_address('(Tor_internal)', 80, self.fakestate) <NEW_LINE> self.assertEqual(pfa, self.fakestate.tor_pid) | look up the (Tor_internal) PID | 625941ce293b9510aa2c33c6 |
def create_tuple(self, node, offset): <NEW_LINE> <INDENT> average = 0.0 <NEW_LINE> for os in offset: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> average += offset[os] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> average += os <NEW_LINE> <DEDENT> <DEDENT> average /= len(offset) <NEW_LINE> node.offsets[0] ... | Computes the offset for a node, given the offset of its children | 625941ce30bbd722463cbef6 |
def __init__(self, value=b''): <NEW_LINE> <INDENT> super(CertificateValue, self).__init__(value, Tags.CERTIFICATE_VALUE) | Construct a CertificateValue byte string.
Args:
value (bytes): A byte string (e.g., b' ...') containing the
certificate bytes to store. Optional, defaults to the empty
byte string. | 625941ce460517430c3942b4 |
def C3(x): <NEW_LINE> <INDENT> from test_mogi2 import cost_function <NEW_LINE> return cost_function(x) | Cost function constructed by hand | 625941ce1b99ca400220abe1 |
def truncate(self, p_int): <NEW_LINE> <INDENT> pass | QByteArray.truncate(int) | 625941ce30dc7b7665901a96 |
def credit_card_charge( amount, chargeFee, token, expirationYear, expirationMonth, name, zipcode, address, city, state, phone, number, validationValue, clientReferenceData1, isRecurring, accountGroupCode, callbackId, save, convenienceFeeType, customerId, splitPayGroupId ): <NEW_LINE> <INDENT> URL = 'https://stgapiproce... | Charge credit card to Oneinc endpoint
Request
Amount(Charge amount, required)(decimal number)
ChargeFee(Should we charge with fee (default = true))(boolean)
Token(Saved CreditCard token, Required if CreditCard is not provided)(string)
CreditCard(Credit card information, Optional. Eit... | 625941ce3539df3088e2e47a |
def test_handle_cancels(self): <NEW_LINE> <INDENT> commands = [('validate', 'info1'), ('load', 0, 'info2'), ('validate', 'info3'), ('cancel', 'info1'), ('cancel', 'info2'), ('validate', 'info2'), ('load', 1, 'info1'), ('load', 2, 'info3')] <NEW_LINE> result = self.__builder._handle_cancels(commands) <NEW_LINE> self.ass... | Check the effect of cancel commands. | 625941ce3617ad0b5ed68027 |
def projectsForOrgs(entity, *args): <NEW_LINE> <INDENT> if not soc_profile_logic.hasProject(entity): <NEW_LINE> <INDENT> return 'N/A' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ', '.join( org_key.get().name for org_key in entity.student_data.project_for_orgs) | Helper function to get value of projects_for_orgs column. | 625941ce29b78933be1e57db |
def _on_chat(self, data: JSON) -> None: <NEW_LINE> <INDENT> user_name = data["user"] <NEW_LINE> message = data["msg"] <NEW_LINE> for c in self._invoke_on_chat: <NEW_LINE> <INDENT> c(user_name, message) | Callback called when a chat message is received. | 625941ce60cbc95b062c6673 |
def reformate_path(path): <NEW_LINE> <INDENT> _path = path.split('file:///', 2) <NEW_LINE> if len(_path) == 2: <NEW_LINE> <INDENT> new_path = path.split('file:///', 2)[1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_path = path <NEW_LINE> <DEDENT> return new_path | On certain editors (e.g. Spyder on Windows) a copy-paste of the path from the explorer includes a 'file:///'
attribute before the real path. This function removes this extra piece
Args:
path: original path
Returns:
Reformatted path | 625941ce091ae3566866708d |
def test_product_installed(self): <NEW_LINE> <INDENT> self.assertTrue(self.installer.isProductInstalled("collective.tiles.carousel")) | Test if collective.tiles.carousel is installed. | 625941ce8e71fb1e9831d8d8 |
def find_headers(filename): <NEW_LINE> <INDENT> headerID = 'Data Type:' <NEW_LINE> f = open(filename, 'r') <NEW_LINE> header_loc = [] <NEW_LINE> header_count = 0 <NEW_LINE> for linenum, line in enumerate(f): <NEW_LINE> <INDENT> if (headerID) in line: <NEW_LINE> <INDENT> header_count += 1 <NEW_LINE> header_loc.append(li... | Finds the location of the headers of each data instance inside the CLS
file. Returns the number of headers and header locations.
Parameters
----------
filename: str
Filename for cls file. | 625941cea934411ee37517c3 |
def choose_action(self, state): <NEW_LINE> <INDENT> self.state = state <NEW_LINE> self.next_waypoint = self.planner.next_waypoint() <NEW_LINE> action = None <NEW_LINE> if not self.learning: <NEW_LINE> <INDENT> action = random.choice(self.valid_actions) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if random.random() < ... | The choose_action function is called when the agent is asked to choose
which action to take, based on the 'state' the smartcab is in. | 625941ce85dfad0860c3af8b |
def splitArray(self, nums: List[int], m: int) -> int: <NEW_LINE> <INDENT> minSum = maxSum = 0 <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> minSum = max(minSum, num) <NEW_LINE> maxSum += num <NEW_LINE> <DEDENT> if m == 1: <NEW_LINE> <INDENT> return maxSum <NEW_LINE> <DEDENT> if m == len(nums): <NEW_LINE> <INDENT> ret... | The total cut is in [1, len(nums)], which means the range of the
largest summary of sub arrays is from [max(nums), sum(nums)], given
that all the numbers in nums are non-negative.
Then we could perform binary search in this sum range to find the
smallest one. | 625941cebd1bec0571d9075f |
def __truediv__(self, other): <NEW_LINE> <INDENT> if isinstance(other, (int, float, complex, np.number)): <NEW_LINE> <INDENT> return FRD(self.fresp * (1/other), self.omega, smooth=(self.ifunc is not None)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> other = _convertToFRD(other, omega=self.omega) <NEW_LINE> <DEDENT> i... | Divide two LTI objects. | 625941ced164cc6175782e7d |
def resolve_replica(self, fspec, primary_schemas=None, allowed_schemas=None, domain=None): <NEW_LINE> <INDENT> if not fspec.replicas: <NEW_LINE> <INDENT> self.logger.warning('resolve_replica() received no fspec.replicas') <NEW_LINE> return <NEW_LINE> <DEDENT> allowed_schemas = allowed_schemas or [None] <NEW_LINE> prima... | Resolve input replica (matched by `domain` if need) first according to `primary_schemas`,
if not found then look up within `allowed_schemas`
Primary schemas ignore replica priority (used to resolve direct access replica, which could be not with top priority set)
:param fspec: input `FileSpec` objects
:param allowed_sch... | 625941ce3c8af77a43ae38d0 |
def get_image_hdu(): <NEW_LINE> <INDENT> raise NotImplementedError | Get the first image HDU | 625941ce99cbb53fe6792d16 |
def _make_detail(self, app, pmid, summary_html=None, keys=None, values=None, ignore=False, article=None, content_html=None): <NEW_LINE> <INDENT> if content_html is not None: <NEW_LINE> <INDENT> route = '/HTML/content/' + ''.join(pmid) + '.html' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> route = '/HTML/' + ''.join(pm... | 注册创建文章详情页
| 625941ce6aa9bd52df036ed4 |
@remote_compatible <NEW_LINE> def test_ap_invalid_config2(dev, apdev): <NEW_LINE> <INDENT> hapd = invalid_ap(apdev[0]) <NEW_LINE> logger.info("Remove interface with failed configuration") <NEW_LINE> hostapd.remove_bss(apdev[0]) | Try to start AP with invalid configuration and remove interface | 625941ceeab8aa0e5d26dc88 |
def __delslice__(self, *args, **kwargs): <NEW_LINE> <INDENT> return _pmt_swig.pmt_vector_double___delslice__(self, *args, **kwargs) | __delslice__(pmt_vector_double self, std::vector< double >::difference_type i, std::vector< double >::difference_type j) | 625941ce50485f2cf553ceca |
def custom_score_2_moves_minus_opponents(game, player): <NEW_LINE> <INDENT> if game.is_loser(player): <NEW_LINE> <INDENT> return float("-inf") <NEW_LINE> <DEDENT> if game.is_winner(player): <NEW_LINE> <INDENT> return float("inf") <NEW_LINE> <DEDENT> return float(2 * len(game.get_legal_moves(player)) - len(game.get_lega... | Calculate the heuristic value of a game state from the point of view
of the given player.
Note: this function should be called from within a Player instance as
`self.score()` -- you should not need to call this function directly.
# OPTION 4: 2 x Number of My Moves - Number of Opponent's Moves | 625941ce004d5f362079a462 |
def __call__(self, wave, left=0, right=1., **kwargs): <NEW_LINE> <INDENT> if not hasattr(wave, 'unit'): <NEW_LINE> <INDENT> xu = wave*u.Angstrom <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if wave.unit is None: <NEW_LINE> <INDENT> xu.unit = u.Angstrom <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xu = wave <NEW_LINE>... | Return reddening factor.
Parameters
----------
wave : array (NW)
Wavelength array. If has no units, assume
`~astropy.units.Angstrom`.
left, right : float
Extrapolation at short/long wavelengths
Returns
-------
ext : array (NW)
Extinction / attenuation as a function of wavelength
| 625941ce8e7ae83300e4b0fc |
def test_plain(self): <NEW_LINE> <INDENT> server = self.socket(zmq.DEALER) <NEW_LINE> server.identity = b'IDENT' <NEW_LINE> client = self.socket(zmq.DEALER) <NEW_LINE> self.assertEqual(client.plain_username, b'') <NEW_LINE> self.assertEqual(client.plain_password, b'') <NEW_LINE> client.plain_username = USER <NEW_LINE> ... | test PLAIN authentication | 625941ceac7a0e7691ed41fc |
def _query_m2m_field(self, field_name): <NEW_LINE> <INDENT> qs = self.queryset.values('pk', field_name).order_by('pk') <NEW_LINE> return dict((pk, tuple(values)) for pk, values in groupby(qs.iterator(), lambda item: item['pk'])) | Query ManyToManyField order by model's pk
Return value's format:
{
object_pk1: ({'pk': object_pk1, 'field_name': related_object_pk1},
{'pk': object_pk1, 'field_name': related_object_pk2},
),
object_pk2: ({'pk': object_pk2, 'field_name': related_object_pk3},
{'p... | 625941ce4f88993c3716c196 |
def ultra_summit_set(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from sage.libs.braiding import ultrasummitset <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> raise PackageNotFoundError("libbraiding") <NEW_LINE> <DEDENT> uss = ultrasummitset(self) <NEW_LINE> B = self.parent() <NEW_LINE> return [[B._... | Return a list with the orbits of the ultra summit set of ``self``
EXAMPLES::
sage: B = BraidGroup(3)
sage: a = B([2, 2, -1, -1, 2, 2])
sage: b = B([2, 1, 2, 1])
sage: b.ultra_summit_set()
[[s0*s1*s0^2, (s0*s1)^2]]
sage: a.ultra_summit_set()
[[(s0^-1*s1^-1*s0^-1)^2*s1^3*s0^2*s1^3,
(s0^-... | 625941cedc8b845886cb5665 |
def __setRunId__(self): <NEW_LINE> <INDENT> if self.run_prefix: <NEW_LINE> <INDENT> idx = 0 <NEW_LINE> search_dir = os.path.join(self.case_dir, 'RESU', self.run_prefix) + '*' <NEW_LINE> dirlist = glob(search_dir) <NEW_LINE> dirlist.sort() <NEW_LINE> if len(dirlist) > 0: <NEW_LINE> <INDENT> idx = int(dirlist[-1].split("... | Set the current run id. Needed for the distant launching scripts | 625941ce925a0f43d2549fa7 |
def __init__( self, *, image_reference: Optional["ImageReference"] = None, os_disk: Optional["VirtualMachineScaleSetOSDisk"] = None, data_disks: Optional[List["VirtualMachineScaleSetDataDisk"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(VirtualMachineScaleSetStorageProfile, self).__init__(**kwargs) <NEW_LINE> self.i... | :keyword image_reference: Specifies information about the image to use. You can specify
information about platform images, marketplace images, or virtual machine images. This element
is required when you want to use a platform image, marketplace image, or virtual machine image,
but is not used in other creation oper... | 625941ce94891a1f4081bbd9 |
def Activate(self): <NEW_LINE> <INDENT> return self.SetActivation(True) | Activate a membership and returns the previous value of activation | 625941ce0c0af96317bb8318 |
def store_in_yearfolder(self): <NEW_LINE> <INDENT> inbox = aq_parent(aq_inner(self.context)) <NEW_LINE> yearfolder = _get_yearfolder(inbox) <NEW_LINE> try: <NEW_LINE> <INDENT> _sm = AccessControl.getSecurityManager() <NEW_LINE> AccessControl.SecurityManagement.newSecurityManager( self.context.REQUEST, AccessControl.Sec... | Move the forwarding (adapted context) in the actual yearfolder. | 625941ce6e29344779a62741 |
def to_formatted_xml(self): <NEW_LINE> <INDENT> n = self.to_Node() <NEW_LINE> return n.toprettyxml() | Return a readable XML serialisation of the query
================================================
This method serialises the current state of the query to an
xml string, suitable for storing, or sending over the
internet to the webservice, only more readably.
@return: the serialised xml string
@rtype: string | 625941ce45492302aab5e3f3 |
def list_pets(self, **kwargs): <NEW_LINE> <INDENT> url = urljoin(self.index_url, "/pets") <NEW_LINE> return self.session.request(method='GET', url=url, headers=self.headers, params=kwargs) | Returns a list of pets, taking optional keyword argument page_size and offset for pagination
:return: | 625941ce377c676e912722d8 |
def getdeep(dct, key): <NEW_LINE> <INDENT> if not isinstance(key, tuple): <NEW_LINE> <INDENT> key = key.split('.') <NEW_LINE> <DEDENT> for k in key[:-1]: <NEW_LINE> <INDENT> dct = dct[k] <NEW_LINE> <DEDENT> return dct[key[-1]] | Get deeply nested value of a dict-like object `dct`.
>>> dct = {'a': {'b': {'c': 1}}}
>>> getdeep(dct, 'a.b.c')
1
>>> getdeep(dct, 'a.b.d')
Traceback (most recent call last):
...
KeyError: 'd' | 625941ce099cdd3c635f0d8a |
def build(self, rgb): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> print("build model started") <NEW_LINE> rgb_scaled = rgb <NEW_LINE> blue, green, red = tf.split(axis=3, num_or_size_splits=3, value=rgb_scaled) <NEW_LINE> bgr = tf.concat(axis=3, values=[ blue - VGG_MEAN[0], green - VGG_MEAN[1], red - VGG_MEA... | load variable from npy to build the VGG
:param rgb: rgb image [batch, height, width, 3] values scaled [0, 1] | 625941ce7b180e01f3dc492c |
def tokenize(document): <NEW_LINE> <INDENT> answer = re.findall('\w+', document.lower()) <NEW_LINE> return answer | Convert a string representing one document into a list of
words. Remove all punctuation and split on whitespace.
Params:
document...a string to be tokenized
Returns:
A list of strings, one per token.
Here is a doctest:
>>> tokenize("Hi there. What's going on?")
['hi', 'there', 'what', 's', 'going', 'on'] | 625941ce167d2b6e31218cc6 |
@dcc.reroute <NEW_LINE> def name_is_right(side, patterns=None): <NEW_LINE> <INDENT> raise NotImplementedError() | Returns whether given side is a valid right side or not
:param side: str
:param patterns: list<str>
:return: bool | 625941ce1f5feb6acb0c4c80 |
def _add(self, trys, limit=None): <NEW_LINE> <INDENT> alignment = self.store[-1] <NEW_LINE> self.minlen = min([self.seqstore[e][1] for e in self.seqstore.keys()]) <NEW_LINE> if len(self.seqstore.sppool) == 0: <NEW_LINE> <INDENT> return True, trys <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sequence = self.seqstore.ne... | Add sequence to alignment, return True if successful | 625941ce8a349b6b435e82a3 |
def UpdateUI(self,) -> 'None': <NEW_LINE> <INDENT> pass | Description of UpdateUI.
Args:
Returns:
None
| 625941cecad5886f8bd27109 |
def get_user_by_index(self, index: int) -> User: <NEW_LINE> <INDENT> id = self._user_ids[index] <NEW_LINE> return self.get_user_by_id(id) | Returns user by its index.
:param index: Index in file of needed user
:return: User | 625941cee8904600ed9f205d |
def request(self, routing_key, params={}, **kwargs): <NEW_LINE> <INDENT> id = self.create_id() <NEW_LINE> response_queue_name = 'response-{}'.format(id) <NEW_LINE> self.logger.debug('Creating response queue "%s"', response_queue_name) <NEW_LINE> queue_opts = { 'auto_delete': True, 'durable': False, } <NEW_LINE> if kwar... | Sends a request to a simple queue. Requests create the initial response
queue and wait for a response.
:param routing_key: The routing key to publish on.
:type routing_key: str
:param params: Keyword parameters to pass to the remote method.
:type params: dict
:param kwargs: Keyword arguments to pass to SimpleQueue
:ty... | 625941ce5fdd1c0f98dc0363 |
def stop_pilight_client(_): <NEW_LINE> <INDENT> pilight_client.stop() | Called once when Home Assistant stops. | 625941ceb7558d58953c5044 |
def shutdown(self) -> None: <NEW_LINE> <INDENT> _seabreeze_device_instance_registry.clear() <NEW_LINE> USBTransport.shutdown(**self._kwargs) | shutdown the api backend
normally this function does not have to be called directly by the user | 625941ced486a94d0b98e276 |
def data_loader(train_inputs, val_inputs, train_labels, val_labels, batch_size=50): <NEW_LINE> <INDENT> train_inputs, val_inputs, train_labels, val_labels = tuple(torch.tensor(data) for data in [train_inputs, val_inputs, train_labels, val_labels]) <NEW_LINE> batch_size = 50 <NEW_LINE> train_data = TensorDataset(trai... | Convert train and validation sets to torch.Tensors and load them to
DataLoader. | 625941ce711fe17d8254249b |
def test_cpp_multiline_tokens(self): <NEW_LINE> <INDENT> ltoken = '/*' <NEW_LINE> rtoken = '*/' <NEW_LINE> data = TestLineClass.create_multiline_test_data(ltoken, rtoken) <NEW_LINE> previous_line = False <NEW_LINE> for i in range(len(data['input_strings'])): <NEW_LINE> <INDENT> with self.subTest(input_string=data['inpu... | tests the properties of a Line object with cpp l and r tokens | 625941ce7cff6e4e81117ab6 |
def get_today(self) -> str: <NEW_LINE> <INDENT> self.__reset_time() <NEW_LINE> return self.today | Gets today's day as an uppercased string.
Returns
----------
A string of today's day uppercased.
Ex: FRIDAY | 625941ce7b25080760e39589 |
def unpackSingleParams(self): <NEW_LINE> <INDENT> self.reportFileName = self.rawData[0][0] <NEW_LINE> self.massWindow = float(self.rawData[0][1]) <NEW_LINE> self.edc = float(self.rawData[0][2]) <NEW_LINE> self.TOFPusherInt = float(self.rawData[0][3]) <NEW_LINE> self.savgolWindow = int(self.rawData[0][4]) <NEW_LINE> sel... | ParseInputFile.unpackSingleParams
Unpack the paramters from the params array into fields with names that make sense for easy
access from the main execution. Cast the values into the proper types that they should be
for how they are going to be used.
unpacked parameters:
self.reportFileName <- rfn
self.mas... | 625941ce8e7ae83300e4b0fd |
def teardown(self, whitelist=None): <NEW_LINE> <INDENT> pass | Called to teardown a server.
This will be executed right before the server is torn down. | 625941ce2c8b7c6e89b358f1 |
def cmd_output_list(self): <NEW_LINE> <INDENT> print("%u outputs" % len(self.mpstate.mav_outputs)) <NEW_LINE> for i in range(len(self.mpstate.mav_outputs)): <NEW_LINE> <INDENT> conn = self.mpstate.mav_outputs[i] <NEW_LINE> print("%u: %s" % (i, conn.address)) <NEW_LINE> <DEDENT> if len(self.mpstate.sysid_outputs) > 0: <... | list outputs | 625941ce91af0d3eaac9bb49 |
def __init__(self, hass, device_id, friendly_name, state_template, on_action, off_action, entity_ids): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.entity_id = async_generate_entity_id(ENTITY_ID_FORMAT, device_id, hass=hass) <NEW_LINE> self._name = friendly_name <NEW_LINE> self._template = state_template <NEW_L... | Initialize the Template switch. | 625941cef548e778e58cd6ae |
def affine_backward(dout, cache): <NEW_LINE> <INDENT> x, w, b = cache <NEW_LINE> dx, dw, db = None, None, None <NEW_LINE> pass <NEW_LINE> n=x.shape[0] <NEW_LINE> d=np.prod(x.shape[1:]) <NEW_LINE> xnew=np.reshape(x,[n,d]) <NEW_LINE> dw=np.dot(xnew.T,dout) <NEW_LINE> dx=np.dot(dout,w.T) <NEW_LINE> dx=np.reshape(dx,x.shap... | Computes the backward pass for an affine layer.
Inputs:
- dout: Upstream derivative, of shape (N, M)
- cache: Tuple of:
- x: Input data, of shape (N, d_1, ... d_k)
- w: Weights, of shape (D, M)
- b: Biases, of shape (M,)
Returns a tuple of:
- dx: Gradient with respect to x, of shape (N, d1, ..., d_k)
- dw: Grad... | 625941ce38b623060ff0af1e |
def findPositionInChapter (self,p1,strict=False): <NEW_LINE> <INDENT> trace = False and not g.unitTesting ; verbose = False <NEW_LINE> c,cc = self.c,self.cc <NEW_LINE> if trace: <NEW_LINE> <INDENT> g.trace('%s exists: %s p: %s' % ( self.name,c.positionExists(p1),p1)) <NEW_LINE> <DEDENT> if self.name == 'main' and c.pos... | Return a valid position p such that p.v == v. | 625941ce0383005118ecf713 |
def p_expr_while(symbols): <NEW_LINE> <INDENT> symbols[0] = WhileStatementNode(symbols[2], symbols[4]) <NEW_LINE> symbols[0].line_number = symbols.lineno(1) <NEW_LINE> symbols[2].parent_node = symbols[0] <NEW_LINE> symbols[4].parent_node = symbols[0] | expr : WHILE expr DO expr | 625941ced18da76e23532607 |
def position(self, account, contract, position, avgCost): <NEW_LINE> <INDENT> super().position(account, contract, position, avgCost) <NEW_LINE> dictionary = { "Account": account, "Symbol": contract.symbol, "SecType": contract.secType, "Currency": contract.currency, "Position": position, "Avg cost": avgCost, } <NEW_LINE... | retrieve all current positions to a dataframe | 625941cebe383301e01b55b5 |
@app.route('/submit-edit/unit', methods=['POST']) <NEW_LINE> def submit_edit(): <NEW_LINE> <INDENT> request_json = request.get_json() <NEW_LINE> if not request_json: <NEW_LINE> <INDENT> return jsonify(errno=RET.PARAMERR, errmsg="参数错误") <NEW_LINE> <DEDENT> email = request_json.get('email') <NEW_LINE> text = request_json... | 提交新标注的数据 | 625941ce15fb5d323cde0c41 |
def remove(self): <NEW_LINE> <INDENT> os.remove(self) <NEW_LINE> return self | See: :func:`os.remove` | 625941ceab23a570cc2502b3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.