code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def children(self, module: torch.nn.Module): <NEW_LINE> <INDENT> yield from self._analyse(module, "children")
**Look for Depthwise convolution using module's** `children()` **method (shallow scanning).** Parameters ---------- module : torch.nn.Module Module to be scanned Yields ------ int Indices where module is considered depthwise convolution.
625941f73c8af77a43ae3e17
def draw_labyrinth(matrix, start, finish, width_line=20, width_walls=5, color_way=(255, 255, 255), color_wall=(0, 0, 0), border=5, color_start=(0, 255, 0), color_finish=(255, 0, 0)): <NEW_LINE> <INDENT> width = (len(matrix) // 2 + 1) * width_line + (len(matrix) // 2) * width_walls + border * 2 <NEW_LINE> height = (len(...
Рисование лабиринта
625941f7283ffb24f3c55f68
def get_account_invitation(self, account_id, invitation_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('asynchronous'): <NEW_LINE> <INDENT> return self.get_account_invitation_with_http_info(account_id, invitation_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN...
Details of a user invitation. # noqa: E501 An endpoint for retrieving the details of an active user invitation sent for a new or an existing user to join the account. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{account-id}/user-invitations/{invitation-id} -H 'Authorization: Bearer API_...
625941f7d58c6744b42582cb
def get_model_hitboxes(self, model): <NEW_LINE> <INDENT> if model == None: <NEW_LINE> <INDENT> raise Exception("model is null") <NEW_LINE> <DEDENT> if not model in self.model_to_hitboxes.keys(): <NEW_LINE> <INDENT> raise KeyError("the given model is not in this collision") <NEW_LINE> <DEDENT> return self.model_to_hitbo...
returns hitboxes for a given model
625941f7596a89723608a125
@pytest.mark.parametrize( "transformer_class", [STLBootstrapTransformer, MovingBlockBootstrapTransformer] ) <NEW_LINE> def test_block_length_exception(transformer_class): <NEW_LINE> <INDENT> msg = ( f"{transformer_class.__name__} requires that block_length" " is greater than the length of X" ) <NEW_LINE> with pytest.ra...
Tests that a Value error is raised when block_length is smaller than len(X).
625941f7adb09d7d5db6cdfa
def get_access_token(self): <NEW_LINE> <INDENT> token_work = time.time() < self.expires <NEW_LINE> if token_work: <NEW_LINE> <INDENT> return self.access_token <NEW_LINE> <DEDENT> data = { 'client_id': self.client_id, 'grant_type': 'implicit' } <NEW_LINE> response = requests.post('https://api.moltin.com/oauth/access_tok...
Get token if it active, else update before get. :return: access_token: str, elasticpath token
625941f70c0af96317bb8855
def remove(self, prop): <NEW_LINE> <INDENT> return bl_scene.remove(self, prop)
Remove a prop from the scene, then return it. :param Prop prop: Prop to remove. :rtype: Prop
625941f7f548e778e58cdbef
def append(self, *args): <NEW_LINE> <INDENT> return _pyBasePython.vectorvectorD_append(self, *args)
append(self, value_type x)
625941f75166f23b2e1a57c8
def testBadInputs(self): <NEW_LINE> <INDENT> mem_slots = 4 <NEW_LINE> head_size = 32 <NEW_LINE> with self.assertRaisesRegexp(ValueError, "num_blocks must be >= 1"): <NEW_LINE> <INDENT> relational_memory.RelationalMemory(mem_slots, head_size, num_blocks=0) <NEW_LINE> <DEDENT> with self.assertRaisesRegexp(ValueError, "at...
Test that verifies errors are thrown for bad input arguments.
625941f715fb5d323cde1189
def do_de_approve(self, account): <NEW_LINE> <INDENT> if len(account) == 0: <NEW_LINE> <INDENT> self._responder('Missing account name.') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if account not in self._conf.APPROVED: <NEW_LINE> <INDENT> self._responder('%s is not an approved account.' % account) <NEW_LINE> <DEDENT...
Remove an account from the approved file. :param account: The account name to remove from the file. :type account: str
625941f7ff9c53063f47c85e
def _parse_legacy_uuid(doc, json_options): <NEW_LINE> <INDENT> if len(doc) != 1: <NEW_LINE> <INDENT> raise TypeError('Bad $uuid, extra field(s): %s' % (doc,)) <NEW_LINE> <DEDENT> if not isinstance(doc["$uuid"], str): <NEW_LINE> <INDENT> raise TypeError('$uuid must be a string: %s' % (doc,)) <NEW_LINE> <DEDENT> if json_...
Decode a JSON legacy $uuid to Python UUID.
625941f74e4d5625662d4a3c
def normalize_samples_window(window, k): <NEW_LINE> <INDENT> window_mean = np.mean(window) <NEW_LINE> divisor = np.linalg.norm(window - window_mean) <NEW_LINE> if (divisor != 0): <NEW_LINE> <INDENT> return ((window - window_mean) / divisor) <NEW_LINE> <DEDENT> return np.zeros((k, k))
given window of samples - normalize it
625941f716aa5153ce362ae8
def find_netid_to_register_with(self, imsi): <NEW_LINE> <INDENT> def process_netnames(networks): <NEW_LINE> <INDENT> networks.sort(reverse=True) <NEW_LINE> for n in networks: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> is_imsi_prefix = imsi.startswith(n.netid) if len(n.netid) els...
Registers with the first netid that appears in both +COPS=? and +CPOL?
625941f7cb5e8a47e48b810d
def __init__(self, name, **fig_args): <NEW_LINE> <INDENT> self.name=name <NEW_LINE> self.live_data = dict( ant_cur = { 'x': [-1e9], 'y': [0]}, ant_cmd = { 'x': [-1e9], 'y': [0]}, sat = { 'x': [-1e9], 'y': [0]}, dpass = { 'x': [-1e9,-1e9,-1e9,-1e9], 'y': [-10, -5, 5, 10]} ) <NEW_LINE> self._fig_args = fig_args
Args: name: Unique name for this plot **fig_args: Arguments to pass to :class:`bokeh.plotting.figure.Figure`
625941f7656771135c3ebee6
def generate_sample_ep(multi=None, abd=False, sports=False, anime=False, anime_type=None): <NEW_LINE> <INDENT> sample_ep_obj = TVEpisodeSample(2, 3, 3, 'Ep Name') <NEW_LINE> sample_ep_obj._status = Quality.compositeStatus(DOWNLOADED, Quality.HDTV) <NEW_LINE> sample_ep_obj._airdate = datetime.date(2011, 3, 9) <NEW_LINE>...
:param multi: :type multi: None or bool :param abd: :type abd: bool :param sports: :type sports: bool :param anime: :type anime: bool :param anime_type: :type anime_type: int or None :return: :rtype: TVEpisodeSample
625941f70a366e3fb873ee8f
def __init__(self, ctx = None): <NEW_LINE> <INDENT> super(VehicleSellDialog, self).__init__() <NEW_LINE> self.vehInvID = ctx.get('vehInvID', {}) <NEW_LINE> self.controlNumber = None <NEW_LINE> return
Ctor
625941f799cbb53fe6793253
def detectCycle(self, head): <NEW_LINE> <INDENT> if head is None or head.next is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> slow = head.next <NEW_LINE> fast = head.next.next <NEW_LINE> while fast is not None and fast.next is not None: <NEW_LINE> <INDENT> if slow == fast: <NEW_LINE> <INDENT> fast = head <...
:type head: ListNode :rtype: ListNode
625941f7ec188e330fd5adff
def test_random_list(): <NEW_LINE> <INDENT> from quick_sort import quick_sort <NEW_LINE> nums = random.sample(range(1, 1000), 20) <NEW_LINE> assert quick_sort(nums) == sorted(nums)
Make some random numbers.
625941f7ad47b63b2c50a5ef
def fit(self, X, y): <NEW_LINE> <INDENT> pass
Function to train and construct the RandomForestClassifier Inputs: X: pd.DataFrame with rows as samples and columns as features (shape of X is N X P) where N is the number of samples and P is the number of columns. y: pd.Series with rows corresponding to output variable (shape of Y is N)
625941f707f4c71912b11af4
def _get_variables_to_train(): <NEW_LINE> <INDENT> return [v for v in tf.trainable_variables() if v.name.startswith('resnet_v1_50/left_branch') or v.name.startswith('resnet_v1_50/right_branch') or v.name.startswith('resnet_v1_50/branch_fn')]
Returns a list of variables to train. Returns: A list of variables to train by the optimizer.
625941f7442bda511e8bea7d
@tf.function <NEW_LINE> def create_unitary_rotation_y(angle: float) -> tf.Tensor: <NEW_LINE> <INDENT> return tf.convert_to_tensor([[math.cos(angle/2), -math.sin(angle/2)], [+math.sin(angle/2), math.cos(angle/2)]], dtype=COMPLEX)
Creates a unitary operator describing rotations of quantum state via Y axis.
625941f773bcbd0ca4b2c6e4
def display_results(disp_input_images, disp_predicted): <NEW_LINE> <INDENT> plt.figure(figsize=(15, 5)) <NEW_LINE> display_one_row(disp_input_images, 0, shape=(IMAGE_SIZE,IMAGE_SIZE,3)) <NEW_LINE> display_one_row(disp_predicted, 20, shape=(IMAGE_SIZE,IMAGE_SIZE,3))
Displays input and predicted images.
625941f776e4537e8c351ce8
def height(self): <NEW_LINE> <INDENT> left_height = 0 <NEW_LINE> right_height = 0 <NEW_LINE> if self.is_leaf(): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if self.left is not None: <NEW_LINE> <INDENT> left_height = self.left.height() <NEW_LINE> <DEDENT> if self.right is not None: <NEW_LINE> <INDENT> right_height ...
Return the height of this node (the number of edges on the longest downward path from this node to a descendant leaf node). TODO: Best and worst case running time: ??? under what conditions?
625941f78e71fb1e9831de15
def update_coordinates(self, SURFACE): <NEW_LINE> <INDENT> self.current_x = (((self.path - 1) * 50) + 100) * math.cos(self.parameter / self.restrict) + 400 <NEW_LINE> self.current_y = (((self.path - 1) * 50) + 100) * math.sin(self.parameter / self.restrict) + 400 <NEW_LINE> return self.update_area(SURFACE)
(Moon, pygame.display) -> Rect Updates the coordinates of the Moon and redraws the Moon, returning the Rect bounding it.
625941f755399d3f05588d28
def create_mesh(mesh, area, clusters, cnorm, flipnorm=True): <NEW_LINE> <INDENT> faces = mesh.faces.reshape(-1, 4) <NEW_LINE> points = mesh.points <NEW_LINE> if points.dtype != np.double: <NEW_LINE> <INDENT> points = points.astype(np.double) <NEW_LINE> <DEDENT> ccent = np.ascontiguousarray(cluster_centroid(points, area...
Generates a new mesh given cluster data moveclus is a boolean flag to move cluster centers to the surface of their corresponding cluster
625941f796565a6dacc8fd38
def sendCancel(self, newtext, rev): <NEW_LINE> <INDENT> request = self.request <NEW_LINE> _ = self._ <NEW_LINE> self._save_draft(newtext, rev) <NEW_LINE> self.lock.release() <NEW_LINE> backto = request.values.get('backto') <NEW_LINE> if backto: <NEW_LINE> <INDENT> pg = Page(request, backto) <NEW_LINE> request.http_redi...
User clicked on Cancel button. If edit locking is active, delete the current lock file. @param newtext: the edited text (which has been cancelled) @param rev: not used!?
625941f7fff4ab517eb2fab0
def abbr_month_date_time_str(adatetime): <NEW_LINE> <INDENT> return "%s %d, %d at %s" % (adatetime.strftime("%b"), adatetime.day, adatetime.year, time_str(adatetime))
Return a date value in the format of "Month(abbreviated name) day, 4-digit-year at hour:minute [AP]M"
625941f73eb6a72ae02ecb5f
def decode_sig(sig): <NEW_LINE> <INDENT> bytez = base64.b64decode(sig) <NEW_LINE> return from_byte_to_int(bytez[0]), decode(bytez[1:33], 256), decode(bytez[33:], 256)
takes Base64 sig string and returns (vbyte, r, s) in binary
625941f74f88993c3716c6cf
def containsDuplicate(self, nums): <NEW_LINE> <INDENT> nums.sort() <NEW_LINE> for idx, num in enumerate(nums): <NEW_LINE> <INDENT> if idx != 0: <NEW_LINE> <INDENT> if num == nums[idx-1]: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False
:type nums: List[int] :rtype: bool
625941f7f8510a7c17cf9d71
def getOccurrenceDays(self, until=None): <NEW_LINE> <INDENT> rule = self.getRecurrenceRule() <NEW_LINE> if rule is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if until is None: <NEW_LINE> <INDENT> until = datetime.datetime.now() + datetime.timedelta(365*5) <NEW_LINE> <DEDENT> if until.tzi...
Days on which the event occurs. Used for indexing
625941f77b180e01f3dc4e5e
def add_string(self, *strings): <NEW_LINE> <INDENT> if self._flush_on_add: <NEW_LINE> <INDENT> self.flush() <NEW_LINE> <DEDENT> for string in strings: <NEW_LINE> <INDENT> bytestring = string.encode('utf-8') <NEW_LINE> self._waiting_objects.append(bytestring) <NEW_LINE> <DEDENT> return self
Queue strings to be printed.
625941f70a50d4780f667507
def image_mouseDoubleClickEvent(self, event): <NEW_LINE> <INDENT> if self.currentMaster: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not os.path.isdir(nm.settings().robots_path): <NEW_LINE> <INDENT> os.makedirs(nm.settings().robots_path) <NEW_LINE> <DEDENT> (fileName, _) = QFileDialog.getOpenFileName(self, "Set rob...
Set the robot image
625941f721a7993f00bc836c
def testZObject(self): <NEW_LINE> <INDENT> pass
Test ZObject
625941f7a934411ee3751d05
def test_run_card_genes_sample_group(self): <NEW_LINE> <INDENT> def create_sample(i): <NEW_LINE> <INDENT> args = { 'name': f'Sample{i}', 'metadata': {'foobar': f'baz{i}'}, TOOL_MODULE_NAME: create_card_amr(), } <NEW_LINE> return Sample(**args).save() <NEW_LINE> <DEDENT> self.generic_run_group_test(create_sample, CARDGe...
Ensure CARD Genes run_sample_group produces correct results.
625941f7ff9c53063f47c85f
def _FetchHelper(self, opt, project, lock, fetched, pm, sem, err_event): <NEW_LINE> <INDENT> did_lock = False <NEW_LINE> if not opt.quiet: <NEW_LINE> <INDENT> print('Fetching project %s' % project.name) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start = time.time() <NEW_LINE> success = projec...
Fetch git objects for a single project. Args: opt: Program options returned from optparse. See _Options(). project: Project object for the project to fetch. lock: Lock for accessing objects that are shared amongst multiple _FetchHelper() threads. fetched: set object that we will add project.gitdir to wh...
625941f7090684286d50f361
def get_pan_hex(self, pan): <NEW_LINE> <INDENT> pan = self._check_pan(float(pan)) <NEW_LINE> val = float(MIN_PAN_HEX) + float(pan - MIN_PAN_DEGREE) * float(MAX_PAN_HEX - MIN_PAN_HEX) / float(MAX_PAN_DEGREE - MIN_PAN_DEGREE) <NEW_LINE> return -1 * int(val)
Get the hex value for a pan value in degrees :param pan: pan value in degrees :returns: pan value in hex
625941f7236d856c2ad44e54
@pipe <NEW_LINE> def traverse(stdin): <NEW_LINE> <INDENT> for item in stdin: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if isinstance(item, str): <NEW_LINE> <INDENT> yield item <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for i in traverse(item): <NEW_LINE> <INDENT> yield i <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> exce...
Recursively browse all items, as if nested levels where flatten. Yield all items in the corresponding flatten list. >>> list([[1],[[2,3]],[[[4],[5]]]] | traverse()) [1, 2, 3, 4, 5]
625941f7925a0f43d254a4ed
def test_check_health_fail(self): <NEW_LINE> <INDENT> def throw(*_, **__): <NEW_LINE> <INDENT> raise Exception("secrets exception") <NEW_LINE> <DEDENT> self.client.get_secret_value.side_effect = throw <NEW_LINE> ok, msg = self.access.check_health() <NEW_LINE> self.assertFalse(ok)
check_health returns False for bad connection
625941f78da39b475bd655ec
def init_dirs(self): <NEW_LINE> <INDENT> msgt(init_dirs.__doc__) <NEW_LINE> if not isdir(TWORAVENS_ORIG_ROOK_DIR): <NEW_LINE> <INDENT> msgx('Directory not found: %s' % TWORAVENS_ORIG_ROOK_DIR) <NEW_LINE> <DEDENT> self.make_dir(TWORAVENS_WORKING_ROOK_DIRECTORY) <NEW_LINE> self.make_dir(TWORAVENS_STATIC_DIRECTORY)
(1) Check/Create directories
625941f74c3428357757c993
def place_nomin_fiat_ask(havven_model, player, order_quant, order_price, success): <NEW_LINE> <INDENT> ask = player.place_nomin_fiat_ask(order_quant, order_price) <NEW_LINE> if success: <NEW_LINE> <INDENT> assert ask is not None <NEW_LINE> assert ask.quantity == order_quant <NEW_LINE> assert ask.fee == havven_model.fee...
Place an nomin fiat limit sell (Ask) and check it's correctness matching on order should be disabled.
625941f7460517430c3947e2
def invalidate_remembered_browsers(self, user_id): <NEW_LINE> <INDENT> url = self._url('{}/multifactor/actions/invalidate-remember-browser'.format(user_id)) <NEW_LINE> return self.client.post(url)
Invalidate all remembered browsers across all authentication factors for a user. Args: user_id (str): The user_id to invalidate remembered browsers for. See: https://auth0.com/docs/api/management/v2#!/Users/post_invalidate_remember_browser
625941f710dbd63aa1bd3211
def search(self,multifilters=None,**kwargs) : <NEW_LINE> <INDENT> if multifilters is None : <NEW_LINE> <INDENT> multifilters = MultiFilters(**kwargs) <NEW_LINE> <DEDENT> return self._search(multifilters)
Search the database with several parameters (see Package.constraints for a full list)
625941f7283ffb24f3c55f69
def cmd_quote(expr, chatid, replyid, msg): <NEW_LINE> <INDENT> typing(chatid) <NEW_LINE> sec = daystart() <NEW_LINE> msg = conn.execute('SELECT id FROM messages WHERE date >= ? AND date < ? ORDER BY RANDOM() LIMIT 1', (sec, sec + 86400)).fetchone() <NEW_LINE> if msg is None: <NEW_LINE> <INDENT> msg = conn.execute('SELE...
/quote Send a today's random message.
625941f730bbd722463cc43a
def is_fullscreen(self): <NEW_LINE> <INDENT> return self.__fs is not None
Return True if application is fullscreen
625941f73346ee7daa2b33e2
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_2iB.pack(_x.handle, _x.parentHandle, _x.keepInPlace)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(locals().get('_x', se...
serialize message into buffer :param buff: buffer, ``StringIO``
625941f7adb09d7d5db6cdfb
def encrypt(self, password, assoc=None): <NEW_LINE> <INDENT> return _win_crypto.encrypt(password)
Encrypt the password using the CryptAPI.
625941f766673b3332b92701
def revise_service_insertion_section_with_rules_revise_with_rules(self, body, section_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.revise_service_insertion_section_with_rules_revise_with_rules_with_http_info(body, secti...
Update an Existing Section with Rules # noqa: E501 Modifies an existing serviceinsertion section along with its relative position among other serviceinsertion sections with rules. When invoked on a large number of rules, this API is supported only at low rates of invocation (not more than 2 times per minute). The typ...
625941f7f7d966606f6aa67b
def get_urn(self, schemes=None): <NEW_LINE> <INDENT> if isinstance(schemes, basestring): <NEW_LINE> <INDENT> schemes = (schemes,) <NEW_LINE> <DEDENT> urns = self.get_urns() <NEW_LINE> if schemes is not None: <NEW_LINE> <INDENT> for urn in urns: <NEW_LINE> <INDENT> if urn.scheme in schemes: <NEW_LINE> <INDENT> return ur...
Gets the highest priority matching URN for this contact. Schemes may be a single scheme or a set/list/tuple
625941f7b57a9660fec33efd
def _support_error(self): <NEW_LINE> <INDENT> raise ValueError("morphism defined by\n" "%s\n" "does not map\n" "%s\n" "into the support of\n" "%s!" % (self.matrix(), self.domain_fan(), self.codomain_fan()))
Raise a ``ValueError`` exception due to support incompatibility. OUTPUT: - none, a ``ValueError`` exception is raised. TESTS: We deliberately construct an invalid morphism for this demonstration:: sage: quadrant = Cone([(1,0), (0,1)]) sage: quadrant = Fan([quadrant]) sage: quadrant_bl = quadrant.subdiv...
625941f74e696a04525c9abe
def sign_file(self, repository_identifier, file_path): <NEW_LINE> <INDENT> metadata = self.get_key_metadata(repository_identifier) <NEW_LINE> return self.__sign_file(file_path, metadata['fingerprint'])
Sign given file path using key of given repository identifier. A custom passphrase can be provided as string. @param repository_identifier: repository identifier @type repository_identifier: string @param file_path: path to file to sign @type file_path: string @return: path to signature file @rtype: string @raise KeyE...
625941f7ac7a0e7691ed472e
def publish_polaris_coords(): <NEW_LINE> <INDENT> pub = rospy.Publisher('/polaris_coords',PointStamped, queue_size=20) <NEW_LINE> rate = rospy.Rate(100) <NEW_LINE> earth_radius = rospy.get_param("earth_radius") <NEW_LINE> polaris_ra = rospy.get_param('polaris_ra') <NEW_LINE> polaris_dec = ...
This node publishes the coordinates of the projection of polaris on Earth now. More specifically, the 3D Cartesian coordinates x,y,z in the Earth Frame of the point defined by the intersection between the surface of the Earth and the line between polaris and the center of the Earth.
625941f7379a373c97cfb1b7
def test_invalid_move(self): <NEW_LINE> <INDENT> GameStateTest.G.add_edge(0, 1) <NEW_LINE> state = GameState(GameStateTest.G) <NEW_LINE> state.make_move(0) <NEW_LINE> state.make_move(1) <NEW_LINE> self.assertRaises(InvalidMoveException)
Tests that invalid moves raise an exception
625941f78e05c05ec3eea9ea
def test_inside_lot(self): <NEW_LINE> <INDENT> computers_id = self.get_fixtures_computers() <NEW_LINE> pcs_in_lot = computers_id[0:2] <NEW_LINE> pcs_outside_lot = computers_id[2:4] <NEW_LINE> lot = self.get_fixture(self.GROUPS, 'lot') <NEW_LINE> lot['children']['devices'] = pcs_in_lot <NEW_LINE> lot = self.post_201(sel...
Tests the operator dh$insideLot
625941f76aa9bd52df037418
def at_least_one_bigger(prediction, threshold): <NEW_LINE> <INDENT> for element in prediction[0]: <NEW_LINE> <INDENT> if element > threshold: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return False
prediction is a matrix ith one line and 2 or 3 columns That function returns True if one of the coefficient is bigger than threshold :param prediction: :param threshold: :return:
625941f78e7ae83300e4b63f
def blacklist_jobs(): <NEW_LINE> <INDENT> blacklist_templates = [ 'system-required' ] <NEW_LINE> errors = False <NEW_LINE> print("\nChecking for obsolete jobs and templates") <NEW_LINE> print("=========================================") <NEW_LINE> for entry in projects: <NEW_LINE> <INDENT> project = entry['project'] <N...
Check that certain jobs and templates are *not* used.
625941f7f7d966606f6aa67c
def abstractmethod(funcobj): <NEW_LINE> <INDENT> funcobj.__isabstractmethod__ = True <NEW_LINE> return funcobj
A decorator indicating abstract methods. Requires that the metaclass is AbstractBase or derived from it. A class that has a metaclass derived from AbstractBase cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. ...
625941f7a4f1c619b28b0698
def baseline_perp(Set): <NEW_LINE> <INDENT> fig = plt.figure() <NEW_LINE> self = Set <NEW_LINE> x = np.arange(self.Nig) <NEW_LINE> y = [ig.Bperp for ig in self] <NEW_LINE> y.sort() <NEW_LINE> black_grey = np.tile(('0','0.5'), self.Nig) <NEW_LINE> ax = plt.bar(x,y,color=black_grey, edgecolor='k') <NEW_LINE> plt.title('{...
bargraph of baselines for each interferogram in set
625941f7627d3e7fe0d694c2
def generate_expression(self, num_operations: int, allowed_operators: List[Dict] = None): <NEW_LINE> <INDENT> if num_operations == 0: <NEW_LINE> <INDENT> return random.sample(self.numbers, 1)[0] <NEW_LINE> <DEDENT> if allowed_operators is None: <NEW_LINE> <INDENT> allowed_operators = self.operators <NEW_LINE> <DEDENT> ...
Generates a single expression that contains the given number of operations.
625941f776d4e153a657f1a2
def remove_memoize(unique_name): <NEW_LINE> <INDENT> if unique_name in memo: <NEW_LINE> <INDENT> del memo[unique_name]
清除缓存
625941f7167d2b6e31219204
def run(self): <NEW_LINE> <INDENT> self._sock = WebSocket( enable_multithread=True, skip_utf8_validation=True ) <NEW_LINE> self.run_heartbeat() <NEW_LINE> while True: <NEW_LINE> <INDENT> logger.info("Connecting to Gateway...") <NEW_LINE> try: <NEW_LINE> <INDENT> self._sock.connect(self.url) <NEW_LINE> <DEDENT> except E...
Start the heartbeat and run _event_loop in a loop until .stop calls. heartbeat_thread, init_thread gets created in this method, as well as .cleanup method which gets called after the socket disconnects. Since the connection restarts after the socket has been disconnected, if a problem occurs from eg. heartbeat thread...
625941f74d74a7450ccd4836
def _PlotTimestampMinuteRangeForDay(self, arg_result_dt, arg_result_qty, arg_output_dir=None, arg_output_fname=None, arg_markNow=False): <NEW_LINE> <INDENT> from matplotlib.ticker import (AutoMinorLocator, MultipleLocator) <NEW_LINE> arg_result_dt_nonetzinfo = [] <NEW_LINE> for loop_dt in arg_result_dt: <NEW_LINE> <IND...
plot datetimes and corresponding quantities, and save to given dir with given filename. If current datetime is in datetime range, mark it on plot
625941f715baa723493c45eb
def dt_utc(dt): <NEW_LINE> <INDENT> local_tz = get_localzone() <NEW_LINE> dt = dateutil.parser.parse(dt) <NEW_LINE> if dt.tzinfo is None: <NEW_LINE> <INDENT> dt = dt.replace(tzinfo=local_tz) <NEW_LINE> <DEDENT> utc_now = dt.astimezone(pytz.utc) <NEW_LINE> return utc_now
Function helper to convert time to UTC before store to database.
625941f771ff763f4b549d08
def poly_divmod(poly1, poly2): <NEW_LINE> <INDENT> l1 = len(poly1) <NEW_LINE> l2 = len(poly2) <NEW_LINE> if l1 < l2: <NEW_LINE> <INDENT> return np.zeros(1, dtype=poly1.dtype), poly1 <NEW_LINE> <DEDENT> quotient = np.zeros(l1 - l2 + 1, dtype=poly1.dtype) <NEW_LINE> remaining = poly1.copy() <NEW_LINE> for i in range(l1-1...
return poly1 / poly2, poly1 % poly2 @poly1, poly2 (np.array): polynomial coefficients, representing sum_i poly[i] * x^i
625941f77c178a314d6efadb
def parse(lines): <NEW_LINE> <INDENT> nodes = [] <NEW_LINE> if lines.__sizeof__() > 0: <NEW_LINE> <INDENT> for line in lines: <NEW_LINE> <INDENT> if line.startswith("Name"): <NEW_LINE> <INDENT> node = {} <NEW_LINE> node['name'] = get_name(line) <NEW_LINE> <DEDENT> elif line.startswith('Allocated resources'): <NEW_LINE>...
parse lines(list) and extract data about node
625941f78a349b6b435e87e2
def monitorTcpPkt(self, iface = None, senderIp = None, receiverIp = None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> sniffPkt = sniff(stop_filter=lambda x:(x.haslayer('TCP') and x['IP'].src == senderIp and x['IP'].dst == receiverIp), timeout = self.timeout)[-1] <NEW_LINE> if sniffPkt.haslayer('TCP') and sniffPkt['I...
监控TCP 请求 :param iface: :param senderIp: :param receiverIp: :return: 符合要求的TCP包 / None
625941f721a7993f00bc836d
@given(deep_speech_1s(return_kwargs=True)) <NEW_LINE> def test_correct_ds1_returned(ds1_kwargs: Tuple[DeepSpeech1, Dict]) -> None: <NEW_LINE> <INDENT> ds1, kwargs = ds1_kwargs <NEW_LINE> fc1 = ds1.fc1 <NEW_LINE> fc2 = ds1.fc2 <NEW_LINE> fc3 = ds1.fc3 <NEW_LINE> fc4 = ds1.fc4 <NEW_LINE> fcout = ds1.out <NEW_LINE> if not...
Ensures correct ``rnn`` type and initialisation.
625941f7dd821e528d63b813
def _get_bins(self, obs_min, obs_max): <NEW_LINE> <INDENT> if obs_min < 0 and obs_max > 0: <NEW_LINE> <INDENT> b1 = np.linspace(obs_min, 0, self.n_disc) <NEW_LINE> b2 = np.linspace(0, obs_max, self.n_disc) <NEW_LINE> return np.hstack([b1, b2[1:]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bins = np.linspace(obs_min...
get bins to discretize length of bins == 2 * self.n_disc - 1 total number of discrete state per dimension: 2 * self.n_disc Args: obs_min (float): obs_max (float): Returns: np.array: bins
625941f7b830903b967e9f73
def compute_labels(X, centroids): <NEW_LINE> <INDENT> pass
Compute labels. Parameters ---------- X: array-like, shape (n_samples, n_features) List of n_features-dimensional data points. Each row corresponds to a single data point. centroids: array-like, shape (n_clusters, n_features) The estimated centroids. Returns ------- labels : array, shape (n_samples,) ...
625941f7fff4ab517eb2fab1
def message_ports_in(self): <NEW_LINE> <INDENT> return _cdma_swig.vector_insert2_sptr_message_ports_in(self)
message_ports_in(vector_insert2_sptr self) -> swig_int_ptr
625941f755399d3f05588d29
def get_system(self, jarvis): <NEW_LINE> <INDENT> syst = {1: 'metric', 2: 'imperial'} <NEW_LINE> jarvis.say("Metric system: Type your height in centimeter, weight in kg") <NEW_LINE> jarvis.say("Imperial system: Type your height in ft and inches, weight in lbs") <NEW_LINE> jarvis.say("All measurements should be Integers...
Asks user to choose which system they want to use
625941f78e71fb1e9831de16
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(MenuResponse, self).__init__(*args, **kwds) <NEW_LINE> if self.selection is None: <NEW_LINE> <INDENT> self.selection = 0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.selection = 0
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: selection :param args: complete s...
625941f785dfad0860c3b4ce
def test_only_debug_mode(self): <NEW_LINE> <INDENT> self.user.is_staff = True <NEW_LINE> self.user.is_superuser = True <NEW_LINE> self.user.save() <NEW_LINE> response = self.client_auth.get(self.url) <NEW_LINE> assert response.status_code == 403 <NEW_LINE> with self.settings(DEBUG=True): <NEW_LINE> <INDENT> response = ...
Test ADMIN_SHELL_ONLY_DEBUG_MODE is True / False Default user must be authenticated and is_stuff and superuser
625941f78a349b6b435e87e3
def get_solr_dynamic_fields(self): <NEW_LINE> <INDENT> return [ SolrDynamicField(name, field) for name, field in self.get_fields() if SolrDynamicField.supports(field) ]
Return all solr dynamic fields for this definition's schema.
625941f732920d7e50b28846
def arbitrary_string(size=4, base_text=None): <NEW_LINE> <INDENT> if (base_text is None) or (base_text == ''): <NEW_LINE> <INDENT> base_text = 'test' <NEW_LINE> <DEDENT> if size <= 0: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> extra = size % len(base_text) <NEW_LINE> body = '' <NEW_LINE> if extra == 0: <NEW_LINE...
Return exactly size bytes worth of base_text as a string
625941f7c4546d3d9de730ab
def cleanup(self): <NEW_LINE> <INDENT> super(run_user, self).cleanup() <NEW_LINE> name = self.stuff['container'] <NEW_LINE> conts = self.stuff['dc'].list_containers_with_name(name) <NEW_LINE> if conts == []: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif len(conts) > 1: <NEW_LINE> <INDENT> msg = ("Multiple contain...
Cleanup the container
625941f73c8af77a43ae3e19
def calc_predator_forces(self, predatorList): <NEW_LINE> <INDENT> F_x, F_y = 0, 0 <NEW_LINE> if not predatorList: <NEW_LINE> <INDENT> return F_x, F_y <NEW_LINE> <DEDENT> for fish in predatorList: <NEW_LINE> <INDENT> if self.behind_me(fish): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> dx = self.rect[0] - fish.rect[...
Predator-Predator repulsion.
625941f7fbf16365ca6f6843
def AsJsonString(self): <NEW_LINE> <INDENT> return json.dumps(self.AsDict(), sort_keys=True)
Returns the TwitterModel as a JSON string based on key/value pairs returned from the AsDict() method.
625941f7cad5886f8bd27648
def get_updates_without_momentum(self, loss_tensor, param_vars): <NEW_LINE> <INDENT> grad_tensors = tf.gradients(loss_tensor, param_vars) <NEW_LINE> updates = [] <NEW_LINE> for i in range(len(param_vars)): <NEW_LINE> <INDENT> new_tensor_param_var = param_vars[i] - self.learning_rate * grad_tensors[i] <NEW_LINE> updates...
Question 4: Returns the gradient descent updates when no momentum is used. Args: loss_tensor: loss tensor used to compute the gradients. param_vars: list of parameter variables. Returns: A list of tuples, where each tuple is an update of the form (param_var, new_param_tensor) indicating that, at runti...
625941f7d10714528d60035c
def bounding_hues_from_renotation(hue_and_code: ArrayLike) -> NDArray: <NEW_LINE> <INDENT> hue, code = as_float_array(hue_and_code) <NEW_LINE> hue_cw: Floating <NEW_LINE> code_cw: Floating <NEW_LINE> hue_ccw: Floating <NEW_LINE> code_ccw: Floating <NEW_LINE> if hue % 2.5 == 0: <NEW_LINE> <INDENT> if hue == 0: <NEW_LINE...
Return for a given *Munsell* *Colorlab* specification hue and *Munsell* *Colorlab* specification code the two bounding hues from *Munsell Renotation System* data. Parameters ---------- hue_and_code *Munsell* *Colorlab* specification hue and *Munsell* *Colorlab* specification code. Returns ------- :class:`nump...
625941f791af0d3eaac9c08e
def yubico_api_signature(data, api_key): <NEW_LINE> <INDENT> r = dict(data) <NEW_LINE> if 'h' in r: <NEW_LINE> <INDENT> del r['h'] <NEW_LINE> <DEDENT> keys = sorted(r.keys()) <NEW_LINE> data_string = "" <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> data_string += "{0!s}={1!s}&".format(key, r.get(key)) <NEW_LINE> <DED...
Get a dictionary "data", sort the dictionary by the keys and sign it HMAC-SHA1 with the api_key :param data: The data to be signed :type data: dict :param api_key: base64 encoded API key :type api_key: basestring :return: base64 encoded signature
625941f7cdde0d52a9e536aa
def load_adnidod_av45_pet(): <NEW_LINE> <INDENT> subjects, subject_paths, description = _get_subjects_and_description( base_dir='ADNIDOD_av45_pet', prefix='0*') <NEW_LINE> subjects = np.array(subjects) <NEW_LINE> func_files = list(map(lambda x: _glob_subject_img( x, suffix='pet/' + 'wr*.nii', first_img=True), subject_p...
loader for adnidod rs fmri
625941f7e8904600ed9f25a9
def add(table): <NEW_LINE> <INDENT> list_labels = ["Name: ", "Manufacturer: ", "purchase_date: ", "Durability: "] <NEW_LINE> data_input = ui.get_inputs(list_labels, "Add new record") <NEW_LINE> id_ = common.generate_random(table) <NEW_LINE> is_date_number = data_input[2].isdigit() and len(data_input) == 4 <NEW_LINE> is...
Asks user for input and adds it into the table. Args: table: table to add new record to Returns: Table with a new record
625941f73539df3088e2e9bc
def tearDown(self): <NEW_LINE> <INDENT> sonos.SonosDevice.available = self.real_available <NEW_LINE> sonos.DEVICES = [] <NEW_LINE> self.hass.stop()
Stop everything that was started.
625941f7f548e778e58cdbf1
def sortColors(self, nums): <NEW_LINE> <INDENT> p0 = 0; p2 = len(nums) - 1 <NEW_LINE> i = 0 <NEW_LINE> while i <= p2: <NEW_LINE> <INDENT> if nums[i] == 0: <NEW_LINE> <INDENT> nums[p0], nums[i] = nums[i], nums[p0] <NEW_LINE> p0 += 1 <NEW_LINE> i += 1 <NEW_LINE> <DEDENT> elif nums[i] == 2: <NEW_LINE> <INDENT> nums[p2], n...
:type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.
625941f7bf627c535bc13840
def iter_vertex(self): <NEW_LINE> <INDENT> for v in self.vertices: <NEW_LINE> <INDENT> yield v
Iterate through all of the vertices
625941f7460517430c3947e3
def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10, dropout=0, use_batchnorm=False, reg=0.0, weight_scale=1e-2, dtype=np.float32, seed=None): <NEW_LINE> <INDENT> self.use_batchnorm = use_batchnorm <NEW_LINE> self.use_dropout = dropout > 0 <NEW_LINE> self.reg = reg <NEW_LINE> self.num_layers = 1 + len(hid...
Initialize a new FullyConnectedNet. Inputs: - hidden_dims: A list of integers giving the size of each hidden layer. - input_dim: An integer giving the size of the input. - num_classes: An integer giving the number of classes to classify. - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then th...
625941f7a219f33f34628fd1
def delete_sqs_message(sqs_queue_url, msg_receipt_handle, region_name='cn-north-1'): <NEW_LINE> <INDENT> sqs_client = boto3.client('sqs', region_name=region_name) <NEW_LINE> sqs_client.delete_message(QueueUrl=sqs_queue_url, ReceiptHandle=msg_receipt_handle)
Delete a message from an SQS queue :param sqs_queue_url: String URL of existing SQS queue :param msg_receipt_handle: Receipt handle value of retrieved message
625941f75fcc89381b1e1d35
def read_irregular_file(fn): <NEW_LINE> <INDENT> df = pd.read_csv(fn, delim_whitespace=True, skiprows=1, low_memory=False) <NEW_LINE> first_line = df.columns.tolist() <NEW_LINE> df.loc[-1] = df.columns.tolist() <NEW_LINE> df.index = df.index + 1 <NEW_LINE> df = df.sort_index() <NEW_LINE> df.columns = [0, 1, 2, 3, 4] <N...
A tricky workaround here to read irregular file
625941f74428ac0f6e5bae69
def _generate_examples(self, filename): <NEW_LINE> <INDENT> fieldnames = ['comment_text', 'emotion_ids', 'comment_id'] <NEW_LINE> with tf.io.gfile.GFile(filename) as f: <NEW_LINE> <INDENT> reader = csv.DictReader(f, fieldnames=fieldnames, delimiter='\t') <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> example = self....
Yields examples. Each example contains a text input with the relevant emotion labels. Args: filename: the path of the file to be read for this split. Yields: A dictionary of features, containing the comment text and, for each emotions label, 0/1 depending on whether is it a label for the input.
625941f7dc8b845886cb5ba8
def transformProperties(properties, termIDMap={}, markerIDMap={}, providerLinkMap={}): <NEW_LINE> <INDENT> transformed = [] <NEW_LINE> CL_regex = re.compile(r'^CL:', re.I) <NEW_LINE> EMAPA_regex = re.compile(r'^EMAPA:', re.I) <NEW_LINE> ENSEMBL_regex = re.compile(r'^ENSEMBL:', re.I) <NEW_LINE> GO_regex = re.compile(r'^...
Transform the properties into their display values using provided termIDMap {id:term}, and markerIDMap {id:symbol}, and providerLinkMap {actualdb.name : urlpattern} -- for external urls returns [ {'displayNote', '_evidenceproperty_key'}, ]
625941f7d268445f265b54e0
def init(self, name: str) -> int: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.makedirs(f'.ergo/{name}') <NEW_LINE> <DEDENT> except FileExistsError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.use(name) <NEW_LINE> return 0
Summary. Args: name (str): Description Returns: int: Description
625941f73346ee7daa2b33e3
def test_queue_and_bucket(): <NEW_LINE> <INDENT> from dataProcessing.tfRecoderData import TFReader <NEW_LINE> dataReader = TFReader(args.dir_dev_data, args=args) <NEW_LINE> tfqueue_filename = tf.train.string_input_producer(dataReader.list_tfdata_filenames, num_epochs=2, shuffle=False) <NEW_LINE> reader_tfRecord = tf.TF...
https://zhuanlan.zhihu.com/p/27238630
625941f75fcc89381b1e1d36
def post(self): <NEW_LINE> <INDENT> instance_ids = simplejson.loads(self.GetRequiredParameter('instance_ids')) <NEW_LINE> if not instance_ids: <NEW_LINE> <INDENT> logging.error('Missing Instance ID.') <NEW_LINE> self.response.out.write('Missing Instance ID.') <NEW_LINE> <DEDENT> ec2 = ec2_manager.EC2Manager() <NEW_LINE...
Stops instances given list of instance ids.
625941f7656771135c3ebee7
def discover_auth_systems(): <NEW_LINE> <INDENT> global _discovered_plugins <NEW_LINE> _discovered_plugins = {} <NEW_LINE> def add_plugin(ext): <NEW_LINE> <INDENT> _discovered_plugins[ext.name] = ext.plugin <NEW_LINE> <DEDENT> ep_namespace = "kingbirdclient.openstack.common.apiclient.auth" <NEW_LINE> mgr = extension.Ex...
Discover the available auth-systems. This won't take into account the old style auth-systems.
625941f7656771135c3ebee8
def anomaly_likelihood(self, X): <NEW_LINE> <INDENT> threshold = np.percentile(self.decision_function(X),100. * self.contamination) <NEW_LINE> outlier_score = self.decision_function(X) <NEW_LINE> mask = outlier_score < threshold <NEW_LINE> sc_pos = outlier_score.clip(max=0) <NEW_LINE> sc_neg = outlier_score.clip(min=0)...
A normalization function to clip and scale the outlier_scores returned by self.decision_function(). Normalization is done separately for data points falling above and below the threshold Parameters ---------- X : dataframe of shape (n_samples, n_features) The training input samples. Sparse matrices are accepted onl...
625941f73617ad0b5ed68567
def unpack_amp_phase(amp_ph, tides=None): <NEW_LINE> <INDENT> tides = _set_tides(tides) <NEW_LINE> am = np.zeros((len(tides),)) <NEW_LINE> ph = am.copy() <NEW_LINE> for n, t in enumerate(tides): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> am[n] = amp_ph[t].amp <NEW_LINE> ph[n] = amp_ph[t].phase <NEW_LINE> <DEDENT> exc...
Given a dictionary of amplitude and phase parameters, unpack the dictionary and return an amp_phase namedtuple with arrays for each element that are in the order of the tides array. Parameters ---------- amp_ph : dict, amp_phase dictionary returned by fit or pack_amp_phase tides: list of strings, List of strings t...
625941f771ff763f4b549d09
def _make_parameter_name(self, parameter): <NEW_LINE> <INDENT> return "__{node_name}_{parameter}__".format( node_name=self.name, parameter=parameter )
Creates an unique name for the given parameter. This method uses the scheme __{node_name}_{parameter}__ to make each parameter a unique variable. :param parameter: The name of the parameter to make unique :type parameter: str :return: A unique name for the given parameter. :rtype: str
625941f71b99ca400220b125
@sb.request_handler( can_handle_func=lambda input: is_intent_name("AMAZON.CancelIntent")(input) or is_intent_name("AMAZON.StopIntent")(input)) <NEW_LINE> def cancel_and_stop_intent_handler(handler_input): <NEW_LINE> <INDENT> speech_text = "Thanks for playing!" <NEW_LINE> handler_input.response_builder.speak( speech_tex...
Single handler for Cancel and Stop Intent.
625941f77d847024c06be933
def run(self): <NEW_LINE> <INDENT> self.__main_frame = self.__create_screen() <NEW_LINE> self.__register_default_hotkeys() <NEW_LINE> self.__loop = urwid.MainLoop(self.__main_frame, self._convert_palette(), input_filter=self.__filter_hotkeys) <NEW_LINE> self.navigate.to_first_plugin() <NEW_LINE> self.__loop.run()
Run the UI
625941f724f1403a926011d1
@app.route('/') <NEW_LINE> def show_entries(): <NEW_LINE> <INDENT> db = get_db() <NEW_LINE> coll = db.entries <NEW_LINE> entries = coll.find() <NEW_LINE> arr_entries = [] <NEW_LINE> for entry in entries: <NEW_LINE> <INDENT> arr_entries.append(entry) <NEW_LINE> <DEDENT> return render_template('show_entries.html', entrie...
Busca las entradas en la BBDD y luego renderiza una vista mostrando las entradas halladas
625941f77b180e01f3dc4e5f