code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
@jit([float64[:,:](float64[:,:],float64[:],int64,int64,int64,int64,float64)],target='cpu') <NEW_LINE> def rmhmc(X,y,niter = 6000,burnin = 1000,nleapfrog = 6,nnewton = 1,alpha = 100): <NEW_LINE> <INDENT> step_size = 3 / nleapfrog <NEW_LINE> n,D = X.shape <NEW_LINE> theta = np.ones((D,1))*1e-3 <NEW_LINE> thetasamples = n... | 625941d716aa5153ce3626c1 | |
def rmspace(s): <NEW_LINE> <INDENT> s = " ".join(s.split()) <NEW_LINE> if len(s) > 0: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return np.nan | Removes extra whitespace and returns nan, if empty string. | 625941d7379a373c97cfad90 |
def requires_role(role): <NEW_LINE> <INDENT> def decorator(f): <NEW_LINE> <INDENT> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> if not current_user.is_anonymous(): <NEW_LINE> <INDENT> if current_user.role >= constants.USER_PERMS.get(role): <NEW_LINE> <INDENT> return f(*args, **kwargs) <NEW_LINE> <DEDENT> flash("Yo... | Decorator for defining access to certain actions.
Levels (as defined in constants.py):
1 - General User (Implicit with login_required)
2 - Help Desk
3 - Admin | 625941d755399d3f055888fe |
def until( condition: callable, f: callable, *args: Any, **kwargs: Any) -> None: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> result = f(*args, **kwargs) <NEW_LINE> if condition(result): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> yield result | Call {f(*args, **kwargs)} until {condition} is true.
:arg condition: Function that inspects the result of {f}.
:arg f: Any function.
:arg *args: Porisional arguments of {f}.
:arg **kwargs: Keyword arguments of {f}. | 625941d75fc7496912cc3bc8 |
def isPalindromev2(head): <NEW_LINE> <INDENT> left = head <NEW_LINE> slow = get_mid(head) <NEW_LINE> right = reverse(slow) <NEW_LINE> p = left <NEW_LINE> q = right <NEW_LINE> res = True <NEW_LINE> while (right is not None): <NEW_LINE> <INDENT> if left.value != right.value: <NEW_LINE> <INDENT> res = False <NEW_LINE> <DE... | @brief 判断回文链表:快慢指针优化
@details https://leetcode-cn.com/problems/palindrome-linked-list/
@param head(ListNode): 头结点
@return res(bool): 是否为回文链表 | 625941d7435de62698dfde97 |
def verify_decode_jwt(token): <NEW_LINE> <INDENT> jsonurl = urlopen(f'https://{AUTH0_DOMAIN}/.well-known/jwks.json') <NEW_LINE> jwks = json.loads(jsonurl.read()) <NEW_LINE> unverified_header = jwt.get_unverified_header(token) <NEW_LINE> rsa_key = {} <NEW_LINE> if 'kid' not in unverified_header: <NEW_LINE> <INDENT> rais... | Verify Auth0 JWTs | 625941d745492302aab5e50f |
def inorder_traverse(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> curr_node = root <NEW_LINE> result = [] <NEW_LINE> if curr_node: <NEW_LINE> <INDENT> if curr_node.left != NIL: <NEW_LINE> <INDENT> left_nodes = self.inorder_traverse(curr_node.left) <NEW_LINE> for lnode ... | Left tree nodes , root , right tree nodes | 625941d701c39578d7e75085 |
def attack_from_below(self, attack): <NEW_LINE> <INDENT> i, j = attack[0] <NEW_LINE> return self.attacker.enemy_config[i][j] == constants.OCCUPIED | called from the attack class, should return the result | 625941d7d10714528d5fff2f |
def merge2(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: <NEW_LINE> <INDENT> nums1[m:] = nums2[:n] <NEW_LINE> nums1.sort() | Do not return anything, modify nums1 in-place instead. | 625941d760cbc95b062c678d |
@pytest.mark.skipif(no_username_password(), reason=SKIP_REASON) <NEW_LINE> @pytest.mark.skipif(no_idservice(), reason=NO_IDSERVICE_ERR) <NEW_LINE> def test_next_collection(): <NEW_LINE> <INDENT> ic = idservice.IDServiceClient() <NEW_LINE> code,status = ic.login(config.IDSERVICE_USERNAME, config.IDSERVICE_PASSWORD) <NEW... | Test if app can get or post next collection
| 625941d701c39578d7e75086 |
def test_sitewide_artist_stat_negative_offset(self): <NEW_LINE> <INDENT> response = self.client.get(url_for('stats_api_v1.get_sitewide_artist'), query_string={'offset': -5}) <NEW_LINE> self.assert400(response) <NEW_LINE> self.assertEqual("'offset' should be a non-negative integer", response.json['error']) | Test to make sure 400 response is received if offset is negative | 625941d73617ad0b5ed68140 |
def get_relvaldata_id(file): <NEW_LINE> <INDENT> run_id = re.search('R\d{9}', file) <NEW_LINE> run = re.search('_RelVal_([\w\d]*)-v\d__', file) <NEW_LINE> if not run: <NEW_LINE> <INDENT> run = re.search('GR_R_\d*_V\d*C?_([\w\d]*)-v\d__', file) <NEW_LINE> <DEDENT> if run_id and run: <NEW_LINE> <INDENT> return (run_id.gr... | Returns unique relvaldata ID for a given file. | 625941d77047854f462a1651 |
def get_input(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Get input received from user | 625941d7004d5f362079a57c |
def test_no_std_name(): <NEW_LINE> <INDENT> grid = two_triangles_with_depths() <NEW_LINE> junk = UVar('junk', location='node', data=[1.0, 2.0, 3.0, 4.0]) <NEW_LINE> junk.attributes['units'] = 'unknown' <NEW_LINE> grid.add_data(junk) <NEW_LINE> depths = find_depths(grid) <NEW_LINE> assert depths.name == 'depth' | Tests to make sure it doesn't crash if a `UVar` does not have a
`standard_name`. | 625941d7de87d2750b85ffde |
def isValidSudoku(self, board): <NEW_LINE> <INDENT> for i in board: <NEW_LINE> <INDENT> tmp = [] <NEW_LINE> for j in i: <NEW_LINE> <INDENT> if j == '.': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if j in tmp: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ... | :type board: List[List[str]]
:rtype: bool | 625941d70c0af96317bb8432 |
def on_x264_deblock_alpha_spinbutton_value_changed(self, x264_deblock_alpha_spinbutton): <NEW_LINE> <INDENT> if self.x264_handlers.is_widgets_setting_up: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> deblock_settings = self.x264_handlers.get_deblock_settings() <NEW_LINE> for row in self.inputs_page_handlers.get_select... | Applies the Deblock option and updates the preview page.
:param x264_deblock_alpha_spinbutton: Spinbutton that emitted the signal. | 625941d7287bf620b61d3cad |
def get_volumes(self): <NEW_LINE> <INDENT> src_pool_list = self.get_src_pool_list() <NEW_LINE> return [i for i in self.cinder.get_volume_list() if getattr(i, 'os-vol-host-attr:host') in src_pool_list and self.storage_model.get_volume_by_uuid(i.id)] | Get migrate target volumes
:returns: volume list on src pools and storage scope | 625941d76aa9bd52df036fef |
def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> reg = self.reg <NEW_LINE> N = X.shape[0] <NEW_LINE> out1, cache1 = affine_relu_forward(X, W1, b1) <NEW_LINE> scores, cache2 = affine_f... | Compute loss and gradient for a minibatch of data.
Inputs:
- X: Array of input data of shape (N, d_1, ..., d_k)
- y: Array of labels, of shape (N,). y[i] gives the label for X[i].
Returns:
If y is None, then run a test-time forward pass of the model and return:
- scores: Array of shape (N, C) giving classification sc... | 625941d7498bea3a759b9cf9 |
def __init__(self, v, d, m, model_name, save_dir, list_classes, optimizer=tf.train.GradientDescentOptimizer, lr=0.001, max_to_keep=2, clip_norm=5.0, input_dim=[None, None], add_summary_emb=True, size_dense_layer=256, activation=tf.nn.tanh ): <NEW_LINE> <INDENT> super(QuestionPairVectorDistAngRNNModelTF, self).__init__(... | this model, compares two sentences by concatenating the final hidden states of their representation by running
them separately through a LSTM. the concatenated representation is them passed through a dense layer with
sigmoid non-linearity and then though an output layer with softmax to predict the probabilities.
:para... | 625941d79c8ee82313fbb9c0 |
def close(self): <NEW_LINE> <INDENT> if self.serial.isOpen(): <NEW_LINE> <INDENT> self.serial.close() | Closes the Connection.
| 625941d7e1aae11d1e749f03 |
def indices_in_iterable(target, queries): <NEW_LINE> <INDENT> if len(np.unique(np.array(target, dtype=object))) != len(target): <NEW_LINE> <INDENT> raise ValueError('Target has to be comprised by unique elements.') <NEW_LINE> <DEDENT> d = {name: i for i, name in enumerate(target)} <NEW_LINE> mapping = [] <NEW_LINE> for... | Find index of each item of the 'queries' in the 'target'.
If a query does not exist in the target, the corresponding index is set to -1. | 625941d77b25080760e396a3 |
def create_row_processor(self, selectcontext, path, reduced_path, mapper, row, adapter): <NEW_LINE> <INDENT> return None, None, None | Return row processing functions which fulfill the contract
specified by MapperProperty.create_row_processor.
StrategizedProperty delegates its create_row_processor method
directly to this method. | 625941d79f2886367277aad6 |
def __init__(self, session): <NEW_LINE> <INDENT> self.prelogin_url = "http://login.sina.com.cn/sso/prelogin.php?entry=weibo" "&callback=sinaSSOController.preloginCallBack&su=&rsakt" "=mod&client=ssologin.js(v1.4.18)&_=1407721000736" <NEW_LINE> self.login_url = "http://login.sina.com.cn/sso/login.p... | Input:
- session: A requests.Session object. | 625941d7f548e778e58cd7c9 |
def get_frame_num(row): <NEW_LINE> <INDENT> return int(row[0]) - 1 | Return the 0 based frame number of the given row of the csv | 625941d78a43f66fc4b542ad |
def __init__(self, url): <NEW_LINE> <INDENT> self.url = url | Return the url endpoint. | 625941d799cbb53fe6792e31 |
def display_answer(self, names, links): <NEW_LINE> <INDENT> results = "" <NEW_LINE> if len(names) == len(links): <NEW_LINE> <INDENT> for i in range(len(names)): <NEW_LINE> <INDENT> results += "\n" <NEW_LINE> nameres = "Job: " + names[i] <NEW_LINE> results + "\n" <NEW_LINE> results += nameres <NEW_LINE> lnk = "URL: " + ... | Displays the links and the names of the jobs, found by parsing Craigslist
:param names: List
:param links: List
:return: None | 625941d72ae34c7f2600d37b |
def _checkDBReduce(self): <NEW_LINE> <INDENT> return | Check and reduce the learnt clause database if needed | 625941d71f5feb6acb0c4d97 |
def _document_form_initial(document): <NEW_LINE> <INDENT> return {'title': document.title, 'slug': document.slug, 'category': document.category, 'is_localizable': document.is_localizable, 'is_archived': document.is_archived, 'tags': [t.name for t in document.tags.all() if t.name not in PRODUCT_TAGS], 'products': [t.nam... | Return a dict with the document data pertinent for the form. | 625941d7bde94217f3683039 |
def last_char_in_str(string, char): <NEW_LINE> <INDENT> string = string[::-1] <NEW_LINE> invidx = string.find('-') <NEW_LINE> idx = len(string) - invidx - 1 <NEW_LINE> return idx | get index of last character char in a string (inverse order to
str.find) | 625941d78e71fb1e9831d9f3 |
def bind(self, host, port): <NEW_LINE> <INDENT> if self.running is False: <NEW_LINE> <INDENT> self.__socket.bind((host, port)) <NEW_LINE> self.server_name = socket.getfqdn(host) <NEW_LINE> self.setup_environ() | Bind host and port to server socket | 625941d7fb3f5b602dac38e0 |
def step(self, action): <NEW_LINE> <INDENT> events = pygame.event.get(pygame.QUIT) <NEW_LINE> for e in events: <NEW_LINE> <INDENT> if e.type == pygame.QUIT: <NEW_LINE> <INDENT> raise (SystemExit, "QUIT") <NEW_LINE> <DEDENT> <DEDENT> self.keyboard_inputs.tick() <NEW_LINE> self.callback(self) <NEW_LINE> self.frame += 1 | (!)for reinforcement learning only(!) WIP:
Executes one action on the game.
The action gets translated into a keyboard sequence first, then is played.
:param str action: the action to execute on the MDP | 625941d73eb6a72ae02ec72c |
def colour_text(text): <NEW_LINE> <INDENT> if type(text) != str: <NEW_LINE> <INDENT> return text <NEW_LINE> <DEDENT> for regex, replacement in shell_patterns: <NEW_LINE> <INDENT> text = regex.sub(replacement, text) <NEW_LINE> <DEDENT> return text | Converts text to display in the shell with pretty colours
Bold: ''{TEXT}''
Underline: __{TEXT}__
Blink: **{TEXT}**
Colour: [colour]{TEXT}[/colour]
Colours supported: Red, Green, Yellow, Blue, Magenta, Cyan | 625941d763b5f9789fde7330 |
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.trajectory is None: <NEW_LINE> <INDENT> self.trajectory = trajectory_msgs.msg.JointTrajectory() <NEW_LINE> <DEDENT> if self.error_code is None: <NEW_LINE> <INDENT> self.error_code = arm_navigation_msgs.msg.ArmNavigationErrorCodes() <NEW_LI... | unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str`` | 625941d78c0ade5d55d3ec07 |
def float_lat_lon_a( row_iter ): <NEW_LINE> <INDENT> return ( pick_lat_lon(*row) for row in row_iter ) | >>> data= [['-76.33029518659048', '37.54901619777347', '0']]
>>> list(float_lat_lon_a( data ))
[('37.54901619777347', '-76.33029518659048')] | 625941d766673b3332b922dc |
def iter_entries(self, predicate=None): <NEW_LINE> <INDENT> predicate = predicate or (lambda x: True) <NEW_LINE> for k, entry in self.publications.entries.items(): <NEW_LINE> <INDENT> if predicate(entry): <NEW_LINE> <INDENT> yield (k, entry) | Create and iterator for filtering entries.
:param predicate: Filter function to use. If ``None``, all entries will be included.
:param predicate: function | 625941d7bf627c535bc1341a |
def compose_aug_inchi_key(inchi_key, ulayer=None, player=None): <NEW_LINE> <INDENT> aug_inchi_key = inchi_key <NEW_LINE> for layer in [_f for _f in [ulayer, player] if _f]: <NEW_LINE> <INDENT> aug_inchi_key += '-' + layer[1:] <NEW_LINE> <DEDENT> return aug_inchi_key | Composes an augmented InChI Key by concatenating the different pieces
as follows:
XXXXXXXXXXXXXX-XXXXXXXXXX-ux,x,xxx
Uses hyphens rather than forward slashes to avoid messing up file paths. | 625941d78a43f66fc4b542ae |
def unset_processor_affinity(self): <NEW_LINE> <INDENT> return _pmt_cpp_swig.preprocessor_master_sptr_unset_processor_affinity(self) | unset_processor_affinity(preprocessor_master_sptr self) | 625941d73346ee7daa2b2fb7 |
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'query_key': 'QueryKeyContainer', 'sum': 'float', 'count': 'int', 'last_value': 'float', 'mean': 'float', 'max': 'float', 'min': 'float', 'median': 'float' } <NEW_LINE> self.attribute_map = { 'query_key': 'queryKey', 'sum': 'sum', 'count': 'count', 'last_va... | TimeseriesStatsContainer - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941d763f4b57ef000135f |
def tornado_graph(sensitivities: dict): <NEW_LINE> <INDENT> data = [ ( key, max(sensitivities[key].df_["Expected Value"]) - min(sensitivities[key].df_["Expected Value"]), min(sensitivities[key].df_["Expected Value"]), ) for key in sensitivities.keys() ] <NEW_LINE> data = sorted(data, key=itemgetter(1), reverse=False) <... | Creates a tornado graph of value sensitivities for the analyzed tree.
:param sensitivities:
dictionary contains ValueSensitivity results for individual values in the tree. | 625941d726068e7796caef2d |
def _rescaleSample(smpl, loc, bs_axis=None): <NEW_LINE> <INDENT> if isinstance(loc, np.ndarray): <NEW_LINE> <INDENT> if np.any(loc != 1): <NEW_LINE> <INDENT> if bs_axis is not None: loc = loc.take([0], axis=bs_axis).squeeze() <NEW_LINE> if loc.ndim == smpl.ndim: <NEW_LINE> <INDENT> smpl = smpl*loc <NEW_LINE> <DEDENT> e... | helper method to rescale samples | 625941d715fb5d323cde0d5d |
def make_offset(wire_or_face, offsetDistance, altitude=0, joinType=GeomAbs_Arc): <NEW_LINE> <INDENT> from OCC.Core.Core.BRepOffsetAPI import BRepOffsetAPI_MakeOffset <NEW_LINE> _joints = [GeomAbs_Arc, GeomAbs_Tangent, GeomAbs_Intersection] <NEW_LINE> assert joinType in _joints, '%s is not one of %s' % (joinType, _joint... | builds a offsetted wire or face from a wire or face
construct an offsetted version of the shape
@param wire_or_face: the wire or face to offset
@param offsetDistance: the distance to offset
@param altitude: move the offsetted shape to altitude
from the normal of the wire or face
@param joinType:... | 625941d73346ee7daa2b2fb8 |
def __init__(self): <NEW_LINE> <INDENT> Commande.__init__(self, "contrôler", "control") <NEW_LINE> self.groupe = "administrateur" <NEW_LINE> self.nom_categorie = "batisseur" <NEW_LINE> self.schema = "<cle>" <NEW_LINE> self.aide_courte = "contrôle un PNJ" <NEW_LINE> self.aide_longue = "Cette commande permet d... | Constructeur de la commande | 625941d7b57a9660fec33ad2 |
def leaky_relu(x: ndarray) -> ndarray: <NEW_LINE> <INDENT> return np.maximum(0.2 * x, x) | Apply "Leaky ReLU" function to each element in ndarray | 625941d70a50d4780f6670df |
def get_effective_dataset(self, return_subMxs=False): <NEW_LINE> <INDENT> p = self.parent <NEW_LINE> gss = p.gatestring_structs['final'] <NEW_LINE> weights = self.parameters.get("weights",None) <NEW_LINE> if weights is not None: <NEW_LINE> <INDENT> scaled_dataset = p.dataset.copy_nonstatic() <NEW_LINE> nRows, nCols = g... | Generate a `DataSet` containing the effective counts as dictated by
the "weights" parameter, which specifies a dict of gate string weights.
This function rescales the actual data contained in this Estimate's
parent `Results` object according to the estimate's "weights" parameter.
The scaled data set is returned, along... | 625941d771ff763f4b5498da |
def get_possible_moves(self): <NEW_LINE> <INDENT> p = self.get_position('A') <NEW_LINE> moves = deepcopy(MOVES) <NEW_LINE> if p[1] == 0 or self.maze[p[0]][p[1] - 1] == 'X': <NEW_LINE> <INDENT> moves.remove('L') <NEW_LINE> <DEDENT> if p[0] == 0 or self.maze[p[0] - 1][p[1]] == 'X': <NEW_LINE> <INDENT> moves.remove('U') <... | :return: list containing all the possible moves from the current state | 625941d7e1aae11d1e749f04 |
def xreload(mod): <NEW_LINE> <INDENT> r = Reload(mod) <NEW_LINE> r.apply() <NEW_LINE> found_change = r.found_change <NEW_LINE> r = None <NEW_LINE> clear_trace_filter_cache() <NEW_LINE> return found_change | Reload a module in place, updating classes, methods and functions.
mod: a module object
Returns a boolean indicating whether a change was done. | 625941d7f8510a7c17cf9948 |
def open(self): <NEW_LINE> <INDENT> if self.interface_configured: return <NEW_LINE> self.interface_configured = True <NEW_LINE> complete = False <NEW_LINE> try: <NEW_LINE> <INDENT> self.reset() <NEW_LINE> self.at_cmd("ATE0") <NEW_LINE> self.at_cmd("ATL0") <NEW_LINE> self.at_cmd("ATH1") <NEW_LINE> complete = True <NEW_L... | Configure the interface (scan tool) for use.
This does not initiate a connection with the vehicle; it simply
opens the connection between the computer and the interface.
See connect_to_vehicle() for comparison. | 625941d7d58c6744b4257eaa |
def feature_class_data(): <NEW_LINE> <INDENT> leukemia_data = pd.read_csv(LEUKEMIA_MASTER_PATH) <NEW_LINE> leukemia_data.rename(columns=symptoms_name_dict, inplace=True) <NEW_LINE> y = leukemia_data['class'].values <NEW_LINE> x = leukemia_data.drop('class', axis=1) <NEW_LINE> return x, y | Get leukemia data split into leukemia features and
leukemia type
:return: tuple (X,Y)
X - leukemia data (features only)
Y - leukemia data (leukemia type only) | 625941d75510c4643540f62b |
@patch('helcim.conversions.TO_API_FIELDS', MOCK_TO_FIELDS_STRING) <NEW_LINE> def test__validate_request_fields__string_min_invalid(): <NEW_LINE> <INDENT> details = { 'cc_cvv': '12' } <NEW_LINE> try: <NEW_LINE> <INDENT> conversions.validate_request_fields(details) <NEW_LINE> <DEDENT> except ValueError as error: <NEW_LIN... | Confirms handling of string minimum length validation. | 625941d7dc8b845886cb5781 |
def ShouldRetry(self, _exception): <NEW_LINE> <INDENT> self.session_token_retry_count += 1 <NEW_LINE> self.request.clear_route_to_location() <NEW_LINE> if not self.endpoint_discovery_enable: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.can_use_multiple_write_locations: <NEW_LINE> <INDENT> if _OperationT... | Returns true if should retry based on the passed-in exception.
:param (exceptions.CosmosHttpResponseError instance) exception:
:rtype: boolean | 625941d73cc13d1c6d3c75c5 |
def roll_die(self): <NEW_LINE> <INDENT> return randint(1, self.num_sides) | 返回所掷骰子数 | 625941d7b830903b967e9b54 |
def test_csrf(self): <NEW_LINE> <INDENT> self.assertContains(self.response, 'csrfmiddlewaretoken') | HTML must contain CSRF token | 625941d78e7ae83300e4b218 |
def test_window(self): <NEW_LINE> <INDENT> x = y = np.linspace(0, 1, 10) <NEW_LINE> kernel_interpolator = KernelInterpolator(x, y, window=3) <NEW_LINE> self.assertEqual(kernel_interpolator.window, 3) | Test :attr:`colour.algebra.interpolation.KernelInterpolator.window`
property. | 625941d723e79379d52ee7ad |
def DeleteGrid(self, e): <NEW_LINE> <INDENT> debug("DeleteGrid") <NEW_LINE> text = self.GetItemText(self.GetSelection()) <NEW_LINE> if text == "Grids": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if text.find("|") == -1: <NEW_LINE> <INDENT> text = self.GetItemText(self.GetItemParent(self.GetSelection())) <NEW_LINE> ... | Delete a grid
| 625941d74e696a04525c9697 |
def getIntervalSchedule(self): <NEW_LINE> <INDENT> return self._IntervalSchedule | A RegularTimePoint belongs to a RegularIntervalSchedule.
| 625941d766656f66f7cbc3f7 |
def __init__(self, N, c = 0.5): <NEW_LINE> <INDENT> if not isinstance(N, int): <NEW_LINE> <INDENT> print("N must be an integer.") <NEW_LINE> return None <NEW_LINE> <DEDENT> if not isinstance(c, float): <NEW_LINE> <INDENT> print("c must be a number between 0 and 1.") <NEW_LINE> return None <NEW_LINE> <DEDENT> else: <NEW... | Creates a model for N two-level systems.
Parameters:
N (int): The number of spins
c (double): The bias for up spins, must be between 0 and 1
(default = 0.5) | 625941d70a366e3fb873ea67 |
def inherit(self, name, parent, fields): <NEW_LINE> <INDENT> if isinstance(parent, ApiSchemaModel): <NEW_LINE> <INDENT> model = ApiSchemaModel(name, fields) <NEW_LINE> model.__apidoc__['name'] = name <NEW_LINE> model.__parent__ = parent <NEW_LINE> self.models[name] = model <NEW_LINE> return model <NEW_LINE> <DEDENT> re... | Extends :meth:`flask_restplus.Api.inherit` to allow `fields` to be a json schema, if `parent` is a
:class:`ApiSchemaModel`. | 625941d729b78933be1e58f4 |
def test_undefined_singleton(): <NEW_LINE> <INDENT> from openff.evaluator.attributes.attributes import UndefinedAttribute <NEW_LINE> value_a = UndefinedAttribute() <NEW_LINE> value_b = UndefinedAttribute() <NEW_LINE> assert value_a == value_b | A test of the UNDEFINED singleton pattern | 625941d7507cdc57c6306f2a |
def test_get_weight(self): <NEW_LINE> <INDENT> self.assertTrue(haproxyconn.get_weight('db1.salt.com', 'mysql')) | Test if it get a value from etcd, by direct path | 625941d78c3a873295158607 |
def from_axes(axes, **kwargs): <NEW_LINE> <INDENT> is_tight = kwargs.pop("is_tight", True) <NEW_LINE> return image_misc.ax_to_image(axes, is_tight, **kwargs) | Convert `matplotlib.figure.Figure` to `PIL.Image.Image`. | 625941d70383005118ecf82d |
@task <NEW_LINE> def quickinstallation(c): <NEW_LINE> <INDENT> inv_logging.task(quickinstallation.__name__) <NEW_LINE> folders(c) <NEW_LINE> setenvironment(c, "development") <NEW_LINE> inv_docker.rebuild(c) <NEW_LINE> inv_node.npm(c, "install") <NEW_LINE> inv_django.migrate(c) <NEW_LINE> inv_django.createsuperuser(c) <... | A task for quick installation of cigsanalysistool and start of a development server | 625941d7442bda511e8be661 |
def seek_write(path, data, offset): <NEW_LINE> <INDENT> path = os.path.expanduser(path) <NEW_LINE> seek_fh = os.open(path, os.O_WRONLY) <NEW_LINE> try: <NEW_LINE> <INDENT> os.lseek(seek_fh, int(offset), 0) <NEW_LINE> ret = os.write(seek_fh, data) <NEW_LINE> os.fsync(seek_fh) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <IND... | .. versionadded:: 2014.1.0
Seek to a position on a file and write to it
path
path to file
data
data to write to file
offset
position in file to start writing
CLI Example:
.. code-block:: bash
salt '*' file.seek_write /path/to/file 'some data' 4096 | 625941d730bbd722463cc013 |
def crear_preguntas(nombre, correctas, incorrectas, encabezado, descuento, tipo, version): <NEW_LINE> <INDENT> if len(correctas) != len(incorrectas): <NEW_LINE> <INDENT> print("Es necesario que el número de opciones verdaderas sea igual al número de opciones falsas") <NEW_LINE> sys.exit() <NEW_LINE> <DEDENT> if descuen... | Crear las preguntas a partir de un número de opciones verdaderas y falsas | 625941d7eab8aa0e5d26dda4 |
def _find(self): <NEW_LINE> <INDENT> if self._explored: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> encountered = set() <NEW_LINE> for ep in pkg_resources.iter_entry_points(self._group): <NEW_LINE> <INDENT> encountered.add(ep.name) <NEW_LINE> if (ep.name in self._entries and id(ep) in self._entries[ep.name]._entries... | Explore the entrypoint space. This fills ``self._entries`` with
the entrypoints that can be loaded. Note that this will
explore the whole space, and update the entrypoint lists to
reflect this. | 625941d7097d151d1a2230a4 |
@serialize_action_result <NEW_LINE> def get_and_extract_results(hits, **kwargs): <NEW_LINE> <INDENT> assignments = get_assignments(hits) <NEW_LINE> answers = _get_answers(assignments) <NEW_LINE> return _extract_responses(answers) | Retrieves AMT assignments and extracts turker responses
:param hits: list of AMT hits
:return: dict of task results keyed on their globalID | 625941d797e22403b379d1e6 |
def warn_out(msgs): <NEW_LINE> <INDENT> term = Terminal() <NEW_LINE> _out(msgs, "WARNING", term.yellow) | Print the given error message (or list of messages) and exit. | 625941d7cc0a2c11143dd0dc |
def host_uptime(): <NEW_LINE> <INDENT> f = open('/proc/uptime') <NEW_LINE> uptime = int(f.readlines()[0].split('.')[0]) <NEW_LINE> minutes = uptime / 60 % 60 <NEW_LINE> hours = uptime / 60 / 60 % 24 <NEW_LINE> days = uptime / 60 / 60 / 24 <NEW_LINE> f.close() <NEW_LINE> return {'day': days, 'time': '%d:%02d' % (hours, ... | returns a dict of the system uptime
{'day': days,
'time': '%d:%02d' % (hours,minutes)} | 625941d7851cf427c661a759 |
def progress_message(self, message): <NEW_LINE> <INDENT> timestamp = f'{now():%Y-%m-%d %H:%M:%S}' <NEW_LINE> process_name = self.project.type <NEW_LINE> dataset_name = self.namespace.dataset <NEW_LINE> if process_name == dataset_name: <NEW_LINE> <INDENT> dataset_name = '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d... | Output progress message for current process. | 625941d7dd821e528d63b3f4 |
def set_adjustable(self, adjustable): <NEW_LINE> <INDENT> if adjustable in ('box', 'datalim', 'box-forced'): <NEW_LINE> <INDENT> if self in self._shared_x_axes or self in self._shared_y_axes: <NEW_LINE> <INDENT> if adjustable == 'box': <NEW_LINE> <INDENT> raise ValueError( 'adjustable must be "datalim" for shared axes'... | ACCEPTS: [ 'box' | 'datalim' | 'box-forced'] | 625941d71f037a2d8b946449 |
def Login(self,*,uUsername:str, uPassword:str) ->bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.oFTP.login(uUsername,uPassword) <NEW_LINE> Logger.debug('Logged in as (%s)' % uUsername) <NEW_LINE> return True <NEW_LINE> <DEDENT> except ftplib.error_perm as e: <NEW_LINE> <INDENT> uMsg=LogError(uMsg='FTP: can\'t ... | logs to an ftp server | 625941d7462c4b4f79d1d91c |
def build_tables_for_sql(self): <NEW_LINE> <INDENT> self.prep_for_sql.update(self._build_subject_table()) <NEW_LINE> self.prep_for_sql.update(self._build_sample_table()) <NEW_LINE> self.prep_for_sql.update(self._build_visit_table()) | Extract and store data as tables in preparation for SQL conversion. | 625941d71b99ca400220acfd |
def cmd(self, payload): <NEW_LINE> <INDENT> return self._compose_msg('CMD', payload) | Send a command message to the log server. | 625941d745492302aab5e511 |
def select_regions(binary, f, min=0, nbest=100000): <NEW_LINE> <INDENT> labels, n = label(binary) <NEW_LINE> objects = find_objects(labels) <NEW_LINE> scores = [f(o) for o in objects] <NEW_LINE> best = np.argsort(scores) <NEW_LINE> keep = np.zeros(len(objects) + 1, 'i') <NEW_LINE> if nbest > 0: <NEW_LINE> <INDENT> for ... | Given a scoring function f over slice tuples (as returned by
find_objects), keeps at most nbest regions whose scores is higher
than min. | 625941d7090684286d50ef33 |
def get_square_error(true,pred): <NEW_LINE> <INDENT> return np.square(get_error(true,pred)) | Returns the square of predicted - true for each entry | 625941d71b99ca400220acfe |
def test_empty(): <NEW_LINE> <INDENT> with pytest.raises(SystemExit) as excinfo: <NEW_LINE> <INDENT> ogre.cli.main() <NEW_LINE> <DEDENT> assert excinfo.value != 0 | Test invocation with no arguments. | 625941d760cbc95b062c678f |
def __init__(self, model_path, data_path): <NEW_LINE> <INDENT> self.data = np.load(data_path) <NEW_LINE> self.model = load_model(model_path) <NEW_LINE> self.x_train, self.y_train = self.data['x_train'] / 255, self.data['y_train'] <NEW_LINE> self.X = tf.Variable(self.get_sample_img(), dtype=tf.float32) | initialization of some variables
:param model_path: pre-trained model path (.h5)
:param data_path: file path of data set (mnist.npz) | 625941d7a05bb46b383eca6d |
def _parse_pf(self, line): <NEW_LINE> <INDENT> parts = line.split() <NEW_LINE> new_serial = parts[3] <NEW_LINE> if ( new_serial in self.serials and self.serials[new_serial]["dlname"] == parts[0] ): <NEW_LINE> <INDENT> self.logger.debug( "New entry for %s: %s => %s" % (new_serial, self.serials[new_serial]["dlname"], par... | Read the parameter file. | 625941d730c21e258bdfa6ea |
def __call__(self, idx, src_shape=None, flat_src=False): <NEW_LINE> <INDENT> if idx is ...: <NEW_LINE> <INDENT> idxer = EllipsisIndexer((idx,), flat_src=flat_src) <NEW_LINE> <DEDENT> elif isinstance(idx, int): <NEW_LINE> <INDENT> idxer = IntIndexer(idx, flat_src=flat_src) <NEW_LINE> <DEDENT> elif isinstance(idx, slice)... | Return an Indexer instance based on the passed indices/slices.
Parameters
----------
idx : int, ndarray, slice, or tuple
Some sort of index/indices/slice.
src_shape : tuple or None
Source shape if known.
flat_src : bool
If True, indices are into a flat source.
Returns
-------
Indexer
The Indexer insta... | 625941d71f037a2d8b94644a |
def rvs(self, m: int) -> int: <NEW_LINE> <INDENT> if not 0 <= m <= self.nr_of_models - 1: <NEW_LINE> <INDENT> raise Exception('m has to be between 0 and nr_of_models - 1') <NEW_LINE> <DEDENT> if self.nr_of_models == 1: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return int(self._get_discr... | Sample a Kernel jump from model ``m`` to another model.
Parameters
----------
m: int
Model source nr.
Returns
-------
target: int
Target model nr. | 625941d7a79ad161976cc392 |
def save_features(self, name='features', path='data/'): <NEW_LINE> <INDENT> import pickle <NEW_LINE> import os <NEW_LINE> num_features = len(self.descriptors) <NEW_LINE> name += '_' + str(num_features) <NEW_LINE> ext = '.dat' <NEW_LINE> file_name = path + name + ext <NEW_LINE> if not os.path.exists(path): <NEW_LINE> <I... | Output feature set to a file using Pickle. | 625941d7de87d2750b85ffe0 |
def _doScan(self, scanPath): <NEW_LINE> <INDENT> staticFileInfo = collections.OrderedDict() <NEW_LINE> for dir, subdirs, fileList in os.walk(scanPath): <NEW_LINE> <INDENT> for fname in fileList: <NEW_LINE> <INDENT> matcher = self._reXMLPatter.match(fname) <NEW_LINE> if matcher != None: <NEW_LINE> <INDENT> fileFullPath ... | 运行主函数,收集目录下符合条件的文件,准备比较 | 625941d7b7558d58953c515d |
def __init__(self, matrix, verify_pd=True, name='OperatorPDFull'): <NEW_LINE> <INDENT> with ops.name_scope(name): <NEW_LINE> <INDENT> with ops.op_scope([matrix], 'init'): <NEW_LINE> <INDENT> matrix = ops.convert_to_tensor(matrix) <NEW_LINE> if verify_pd: <NEW_LINE> <INDENT> matrix = _check_symmetric(matrix) <NEW_LINE> ... | Initialize an OperatorPDFull.
Args:
matrix: Shape `[N1,...,Nb, k, k]` tensor with `b >= 0`, `k >= 1`. The
last two dimensions should be `k x k` symmetric positive definite
matrices.
verify_pd: Whether to check that `matrix` is symmetric positive definite.
If `verify_pd` is `False`, correct behavior i... | 625941d7004d5f362079a57f |
def get_response(self, course): <NEW_LINE> <INDENT> return self.client.get(reverse('progress', args=[unicode(course.id)])) | Returns the HTML for the progress page | 625941d74428ac0f6e5baa3f |
def pK_CaHPO4(T=298.15): <NEW_LINE> <INDENT> return 2.74 | CaHPO4 formation [MP98 following MR97]. | 625941d7ac7a0e7691ed4315 |
def _onOk(self): <NEW_LINE> <INDENT> if not self._refTableWidget.val() and not self._simEntry[1].isEnabled(): <NEW_LINE> <INDENT> self._refTableWidget.warn() <NEW_LINE> return <NEW_LINE> <DEDENT> method, ref = self._collect() <NEW_LINE> self._internalModel.addMethod(method) <NEW_LINE> self._internalModel.addRefTable(re... | Called when user presses ok. Update method settings. | 625941d72eb69b55b151cafd |
def associate(left, attr, right): <NEW_LINE> <INDENT> rt.assert_doc("left", left) <NEW_LINE> rt.assert_doc("right", right) <NEW_LINE> if not hasattr(left, attr): <NEW_LINE> <INDENT> rt.throw("Cannot set association upon invalid attribute.") <NEW_LINE> <DEDENT> ref = cim.v1.DocReference() <NEW_LINE> ref.id = right.meta.... | Creates and returns an association between two documents.
:param left: A document.
:type left: A pyesdoc object.
:param attr: Name of attribute upon left document to which the association will be assigned.
:type attr: str
:param right: A document.
:type right: A pyesdoc object.
:returns: A document reference.
:r... | 625941d70c0af96317bb8434 |
def matchPath(res): <NEW_LINE> <INDENT> pass | 功能说明:
使用相对路径的资源获得资源的绝对路径。
注意:资源必须在KBE_RES_PATH之下才可以访问到。
例子:
>>>KBEngine.matchPath("scripts/entities.xml")
'/home/kbe/kbengine/demo/res/scripts/entities.xml'
@param res:string,资源的相对路径(包括资源名称)。
@return:string, 资源的绝对路径。
| 625941d7287bf620b61d3caf |
def __init__(self, enable=None): <NEW_LINE> <INDENT> if enable is None: <NEW_LINE> <INDENT> enable = self.get_global_color_enabled() <NEW_LINE> <DEDENT> self.enable = enable | :param bool|None enable: | 625941d716aa5153ce3626c4 |
def unique3(S, length=0): <NEW_LINE> <INDENT> if length == len(S)-1: <NEW_LINE> <INDENT> return unique(S, length) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if unique(S, length): <NEW_LINE> <INDENT> return unique3(S, length+1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Running time is O(n^2) since each element in S is compared n times. | 625941d7c4546d3d9de72c81 |
def TStr_MkClone(*args): <NEW_LINE> <INDENT> return _snap.TStr_MkClone(*args) | TStr_MkClone(TStr Str) -> TStr
Parameters:
Str: TStr const & | 625941d782261d6c526ab6ee |
def is_file_or_link(exe): <NEW_LINE> <INDENT> return os.access(exe, os.X_OK) and (os.path.isfile(exe) or os.path.islink(exe)) | Check for os.X_OK doesn't suffice because directory may executable
:param exe: path
:return: bool | 625941d77047854f462a1654 |
def index(request): <NEW_LINE> <INDENT> return render(request, 'homepage/index.html') | Renders the home page | 625941d7cc40096d61595b9c |
def test_errors_group_navigation(): <NEW_LINE> <INDENT> with inntest.connection() as conn: <NEW_LINE> <INDENT> conn._require_reader() <NEW_LINE> count, low, high = conn.group(inntest.group) <NEW_LINE> for cmd in _article_commands: <NEW_LINE> <INDENT> for delta in _number_deltas: <NEW_LINE> <INDENT> artno = high+delta <... | inntest.Tests.test_errors_group_navigation()
Test errors for group navigation commands. | 625941d7e64d504609d74a8c |
def deep_learning(model, trainloader, validationloader,criterion, optimizer, epochs, print_every, device): <NEW_LINE> <INDENT> epochs = epochs <NEW_LINE> print_every = print_every <NEW_LINE> steps = 0 <NEW_LINE> model.to(device) <NEW_LINE> for e in range(epochs): <NEW_LINE> <INDENT> running_loss = 0 <NEW_LINE> model.tr... | Trains the neural network. | 625941d721bff66bcd684b9d |
def getMentions(outputf): <NEW_LINE> <INDENT> fsarrays, cur_fsarray, in_fsarray = [], None, False <NEW_LINE> pln, tag_tokens = None, 0 <NEW_LINE> concepts, array_bounds = {}, {} <NEW_LINE> hook = codecs.open(outputf, 'r') <NEW_LINE> for line in hook: <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if common.matchesR... | Get the (ambiguous) entity mentions from the XMI file,
as a list of Mention objects. | 625941d72eb69b55b151cafe |
def _setup_dynamic(self): <NEW_LINE> <INDENT> display.info('Provisioning %s cloud environment.' % self.platform, verbosity=1) <NEW_LINE> config = self._read_config_template() <NEW_LINE> response = {} <NEW_LINE> if os.path.isfile(self.SHERLOCK_CONFIG_PATH): <NEW_LINE> <INDENT> with open(self.SHERLOCK_CONFIG_PATH, 'r') a... | Request Azure credentials through Sherlock. | 625941d79f2886367277aad8 |
def max_drawdown_rate(X): <NEW_LINE> <INDENT> mdd = 0 <NEW_LINE> peak = X[0] <NEW_LINE> for x in X: <NEW_LINE> <INDENT> if x > peak: <NEW_LINE> <INDENT> peak = x <NEW_LINE> <DEDENT> dd = (peak - x) / peak <NEW_LINE> if dd > mdd: <NEW_LINE> <INDENT> mdd = dd <NEW_LINE> <DEDENT> <DEDENT> return mdd | Return the absolute value of the maximum drawdown of sequence X.
Note
----
If the sequence is strictly increasing, 0 is returned. | 625941d75fdd1c0f98dc0480 |
def ip_acl_ip_access_list_extended_hide_ip_acl_ext_seq_sync(self, **kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list") <NEW_LINE> ip = ET.SubElement(ip_acl, "ip") <NEW_LINE> access_list = ET.SubElement(ip, "... | Auto Generated Code
| 625941d74527f215b584c6a1 |
def get_dataset(self, shuffle=True): <NEW_LINE> <INDENT> audio_np = np.load(self.base_path+"_AUDIO.npy") <NEW_LINE> ld_np = np.load(self.base_path+"_LD.npy") <NEW_LINE> f0_np = np.load(self.base_path+"_F0.npy") <NEW_LINE> print(np.mean(audio_np)) <NEW_LINE> print(np.max(ld_np)) <NEW_LINE> print(np.mean(f0_np)) <NEW_LIN... | Read dataset.
Args:
shuffle: Whether to shuffle the input files.
Returns:
dataset: A tf.data.Dataset that reads from TFDS. | 625941d7956e5f7376d710b8 |
def check_keyup_events(event, ship): <NEW_LINE> <INDENT> if event.key == pygame.K_RIGHT: <NEW_LINE> <INDENT> ship.moving_right = False <NEW_LINE> <DEDENT> elif event.key == pygame.K_LEFT: <NEW_LINE> <INDENT> ship.moving_left = False | 当键盘被松开
:param event: 游戏事件对象
:param ship: 飞船对象
:return: | 625941d799cbb53fe6792e33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.