code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def shareEntityWithUsers(self, domainId, entityId, userList, permissionTypeId, cascadePermission): <NEW_LINE> <INDENT> pass
<p>API method to share an entity with users</p> Parameters: - domainId - entityId - userList - permissionTypeId - cascadePermission
625941de97e22403b379d2d0
def linear2mu(x, mu=255): <NEW_LINE> <INDENT> x_mu = np.sign(x) * np.log(1 + mu*np.abs(x))/np.log(1 + mu) <NEW_LINE> return ((x_mu + 1)/2 * mu).astype('int16')
From Joao x should be normalized between -1 and 1 Converts an array according to mu-law and discretizes it Note: mu2linear(linear2mu(x)) != x Because we are compressing to 8 bits here. They will sound pretty much the same, though. :usage: >>> bitrate, samples = scipy.io.wavfile.read('orig.wav') >>...
625941de50485f2cf553d0d0
def hasCycle(self, head): <NEW_LINE> <INDENT> s = set() <NEW_LINE> node = head <NEW_LINE> while node != None: <NEW_LINE> <INDENT> if node in s: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s.add(node) <NEW_LINE> <DEDENT> node = node.next <NEW_LINE> <DEDENT> return False
:type head: ListNode :rtype: bool
625941ded58c6744b4257f93
def test_whitelist_specificity(parse_style, target_package, whitelist, tmpdir): <NEW_LINE> <INDENT> contents = exec_test( tmpdir.strpath, target_package, parse_style, whitelist=whitelist) <NEW_LINE> bads = set(CLASS_NAMES) - set(whitelist) <NEW_LINE> present = [n for n in bads if n in contents] <NEW_LINE> assert [] == ...
Non whitelisted entities should be excluded.
625941de3539df3088e2e680
def resetBall(self): <NEW_LINE> <INDENT> self._ball.center_x=GAME_WIDTH/2 <NEW_LINE> self._ball.center_y=GAME_HEIGHT/2
This method updates the position of the ball to the middle of the game screen
625941de0383005118ecf917
def numberToWords(self, num): <NEW_LINE> <INDENT> digits = len(str(int(num))) <NEW_LINE> words = '' <NEW_LINE> if num == 0: return 'Zero' <NEW_LINE> for i in range((digits-1)//3,-1,-1): <NEW_LINE> <INDENT> curnum = num // math.pow(1000,i) <NEW_LINE> num = num % math.pow(1000,i) <NEW_LINE> if curnum > 0: <NEW_LINE> <IND...
:type num: int :rtype: str
625941de60cbc95b062c6878
def clickselect(extend=False, column=False, channel=False): <NEW_LINE> <INDENT> pass
Select keyframes by clicking on them :param extend: Extend Select, Toggle keyframe selection instead of leaving newly selected keyframes only :type extend: boolean, (optional) :param column: Column Select, Select all keyframes that occur on the same frame as the one under the mouse :type column: boolean, (optional)...
625941deb545ff76a891414b
def removeCnEndEnglishHalfBracket(content): <NEW_LINE> <INDENT> if content.endswith(u"「") and content.find(u"」") > 0: <NEW_LINE> <INDENT> return content[:content.find(u"「")] <NEW_LINE> <DEDENT> return content
去除字符串『符号开始的内容 例: u'『你好啊』嘎嘎' <=> u'嘎嘎'
625941de097d151d1a22318d
def send(self): <NEW_LINE> <INDENT> if self.status is OUTWARD_STATUS.get('sent'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> recipients = self.get_recipients() <NEW_LINE> emails = [] <NEW_LINE> if OUTWARD_HTML: <NEW_LINE> <INDENT> html_content = self.message <NEW_LINE> EmailClass = EmailMultiAlternatives <NEW...
Sends the email to the recipients
625941deadb09d7d5db6cac3
def hashtag(plot): <NEW_LINE> <INDENT> idx_longest_word = plot.find(max(plot.split(),key=len)) <NEW_LINE> return plot[:idx_longest_word] + '#' + plot[idx_longest_word:]
Adds a hashtag to the longest word in the given sentence (here: plot). And returns the hashtagged sentence.
625941deeab8aa0e5d26de8e
def find_account_id(self, account_idx): <NEW_LINE> <INDENT> account_folder = ( self.setup_path / f"wow{account_idx}" / "_retail_" / "WTF" / "Account" ) <NEW_LINE> if not account_folder.exists(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> account_ids = [ f.name for f in account_folder.iterdir() if f.is_dir() an...
Find account_id folder (account SavedVariables parent directory)
625941deb830903b967e9c3d
def install(*names): <NEW_LINE> <INDENT> urls = set() <NEW_LINE> def add(n): <NEW_LINE> <INDENT> s = get_script(n) <NEW_LINE> if "download" not in s: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> url, arch = s["download"] <NEW_LINE> arch = joinpath(getpath("download", n), expandvars(n, arch)) <NEW_LINE> urls.update([(...
Installs vim script with given name.
625941de31939e2706e4d19b
def write_out_csv(flags, warn_patterns, warning_messages, warning_links, warning_records, header_str, project_names): <NEW_LINE> <INDENT> if flags.csvpath: <NEW_LINE> <INDENT> with open(flags.csvpath, 'w') as outf: <NEW_LINE> <INDENT> dump_csv(csv.writer(outf, lineterminator='\n'), warn_patterns) <NEW_LINE> <DEDENT> <D...
Write warnings csv file.
625941de851cf427c661a842
def editDistance(s1: str, s2: str) -> {int}: <NEW_LINE> <INDENT> rows = len(s1) + 1 <NEW_LINE> cols = len(s2) + 1 <NEW_LINE> matrix = np.zeros([rows, cols], dtype=int) <NEW_LINE> penalty = 1 <NEW_LINE> for i in range(rows): <NEW_LINE> <INDENT> matrix[i][0] = i * penalty <NEW_LINE> <DEDENT> for j in range(cols): <NEW_LI...
The edit distance is the minimum number of edit operations needed to transform s1 into s2, where operation is defined as substitution, insertion, or deletion of a single symbol. Input: Two amino acid strings s1, s2. Return: The maximum alignment score of these strings followed by an alignment achieving this maximum sco...
625941dee64d504609d74b75
def apply_updates(self, model, grads): <NEW_LINE> <INDENT> update_ops = [] <NEW_LINE> mom_ops = [] <NEW_LINE> if isinstance(self._learning_rate, list): <NEW_LINE> <INDENT> lrs = self._learning_rate <NEW_LINE> print('d') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lrs = [self._learning_rate for p in model.model_params...
Updates the model parameters based on the given gradients, using momentum
625941de2eb69b55b151cbe8
def ex0_save(instance,source,f_name): <NEW_LINE> <INDENT> truths = truth_parser(instance) <NEW_LINE> nan_array= nan_array_parser(instance, truths, instance.base_model) <NEW_LINE> obs, obs_key = obs_parser(instance, True) <NEW_LINE> preds = preds_parser(instance, True) <NEW_LINE> forecasts = forecasts_parser(instance, ...
save grand median L2s between truths and obs,preds, and ukf - extract truths, obs, ukf predictions (preds), and forecasts - remove inactive agent measurements to prevent bias - calculate L2 distances between truth vs obs,preds and ukfs. - take grand median of L2s for each estimator - store scalar grand medians in 3x1...
625941de1b99ca400220ade8
def infer_shape(self, max_data_shape=None, max_label_shape=None): <NEW_LINE> <INDENT> if max_data_shape is None: <NEW_LINE> <INDENT> max_data_shape = [] <NEW_LINE> <DEDENT> if max_label_shape is None: <NEW_LINE> <INDENT> max_label_shape = [] <NEW_LINE> <DEDENT> max_shapes = dict(max_data_shape + max_label_shape) <NEW_L...
Return maximum data and label shape for single gpu
625941ded10714528d60001c
def clone(self): <NEW_LINE> <INDENT> clone = self._color.clone() <NEW_LINE> return self.new(clone.space(), clone.coords(), clone.alpha)
Clone.
625941de26238365f5f0f1a8
def get_class_id(element, type): <NEW_LINE> <INDENT> attr = 'class' if type == '\.' else 'id' <NEW_LINE> matches = re.search(f"({type}+\w+\S+)", element) <NEW_LINE> if matches is not None: <NEW_LINE> <INDENT> split_del = '.' if type =='\.' else type <NEW_LINE> attrs = matches.group(0).split(split_del) <NEW_LINE> new_el...
Returns class or id attribute in proper HTML form
625941deaad79263cf390d7b
def get_time_source(self): <NEW_LINE> <INDENT> return self._time_source
Return the currently selected time source
625941deec188e330fd5aacf
def loop(self): <NEW_LINE> <INDENT> user_socket, addr = self.sock.accept() <NEW_LINE> while True: <NEW_LINE> <INDENT> msg, req_type = util.packet_recv(user_socket) <NEW_LINE> if req_type is 'S': <NEW_LINE> <INDENT> print("Received sbf request") <NEW_LINE> self.create_sbf() <NEW_LINE> self.encrypt_sbf() <NEW_LINE> data...
Create socket send sbf datas then waith until recives user datas. receive S as send sbf data receive C as check user position Args: sbf_vector_enc (list) public_key (PaillierPublicKey) bit_mapping (int) hash_family (str) hash_runs (int) salt (str) mask (list): encrypted and shuffles user...
625941de5166f23b2e1a548f
def __init__( self, x_arr: np.ndarray, y_arr: np.ndarray, a_arr: np.ndarray, b_arr: np.ndarray ): <NEW_LINE> <INDENT> assert 1 == x_arr.ndim <NEW_LINE> assert 1 == y_arr.ndim <NEW_LINE> assert 1 == a_arr.ndim <NEW_LINE> assert 1 == b_arr.ndim <NEW_LINE> self.n_grid_points = x_arr.shape[0] <NEW_LINE> assert self.n_grid_...
Creates a RITA object, which stores the tables of RITA parameters Args: x_arr (np.ndarray): the x_i's (grid points) for RITA y_arr (np.ndarray): the y_i's (Greek 'xi' values) for RITA a_arr (np.ndarray): the a_i's for RITA b_arr (np.ndarray): the b_i's for RITA
625941de046cf37aa974d07b
@retry(stop_max_attempt_number=constants.RETRY_TIMES, stop_max_delay=constants.STOP_MAX_DELAY, wait_fixed=constants.WAIT_FIXED) <NEW_LINE> def requests_job_detail_data(job_id): <NEW_LINE> <INDENT> headers = generate_http_header() <NEW_LINE> crawler_sleep() <NEW_LINE> try: <NEW_LINE> <INDENT> response = requests.get( ur...
请求职位详情页数据
625941de63d6d428bbe44826
def getXml(self, nodepath=None, withChildren=False): <NEW_LINE> <INDENT> if nodepath is None: <NEW_LINE> <INDENT> nodepath = self.snpath <NEW_LINE> <DEDENT> content = self.createContent(nodepath) <NEW_LINE> if content is not None: <NEW_LINE> <INDENT> return content.GetXml(withChildren) <NEW_LINE> <DEDENT> return None
getXml(nodepath, withChildren=False) Loads the Content at the node path and returns XML STREAM. If nodepath is None, the class snpath is used. To get a string, call getXmlStr()
625941de377c676e912724dd
def search_commits( self, query, sort=github.GithubObject.NotSet, order=github.GithubObject.NotSet, **qualifiers, ): <NEW_LINE> <INDENT> assert isinstance(query, str), query <NEW_LINE> url_parameters = dict() <NEW_LINE> if ( sort is not github.GithubObject.NotSet ): <NEW_LINE> <INDENT> assert sort in ("author-date", "c...
:calls: `GET /search/commits <http://docs.github.com/en/rest/reference/search>`_ :param query: string :param sort: string ('author-date', 'committer-date') :param order: string ('asc', 'desc') :param qualifiers: keyword dict query qualifiers :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Commit.C...
625941de9f2886367277abc1
def _clean_cluster_databag_item(self, target_system, clusterid): <NEW_LINE> <INDENT> self._clean_databag_item( target_system, self._cluster_databag_name(clusterid))
clean cluster databag item.
625941de3317a56b86939f87
def add_group_value_count(df, cols, value): <NEW_LINE> <INDENT> df_value_count = df.groupby(cols)[value].size().unstack().fillna(0.0).reset_index() <NEW_LINE> df_value_count.columns = [cols[0]] + ["_".join(c.split()).upper() + "_count" for c in df_value_count.columns.tolist()[1:]] <NEW_LINE> df = df.merge(df_value_coun...
Extract value_counts() in each group
625941dea05bb46b383ecb56
def _tof_default_q_binning(self, q_min, q_max): <NEW_LINE> <INDENT> return [q_min, -0.05, q_max]
Returns default q binning for tof mode
625941de3d592f4c4ed1d39c
def test_ambiguous_dst_time_spring(self): <NEW_LINE> <INDENT> eastern = pytz.timezone('US/Eastern') <NEW_LINE> dt = eastern.localize(datetime(2002, 3, 31, 2, 30, 00)).astimezone(pytz.utc).replace(tzinfo=None) <NEW_LINE> self.event.start = dt <NEW_LINE> self.event.stop = dt + relativedelta(hours=1) <NEW_LINE> self.event...
Test hours stays the same, regardless of DST changes
625941de76d4e153a657ee68
def test_cleanup_error(self): <NEW_LINE> <INDENT> result = {"retcode": 1, "stdout": "some error", "stderr": ""} <NEW_LINE> salt_mock = { "cmd.run_all": MagicMock(return_value=result), } <NEW_LINE> with patch.dict(suseconnect.__salt__, salt_mock): <NEW_LINE> <INDENT> with self.assertRaises(CommandExecutionError): <NEW_L...
Test suseconnect.cleanup error
625941dec432627299f04f7e
def create(self, name, description=None, limit=None): <NEW_LINE> <INDENT> self.click(locators['system-groups.new']) <NEW_LINE> self.assign_value(locators['system-groups.name'], name) <NEW_LINE> if description: <NEW_LINE> <INDENT> self.assign_value( locators['system-groups.description'], description) <NEW_LINE> <DEDENT>...
Creates new System Group from UI
625941dec4546d3d9de72d6c
def odootil_bin_field_download( self, field=None, filename=None, target='self'): <NEW_LINE> <INDENT> self.ensure_one() <NEW_LINE> return { 'type': 'ir.actions.act_url', 'url': "web/content?model=%s&id=%s&field=%s&filename_field=%s&" "download=true" % ( self._name, self.id, field or self._odootil_bin_field_datas, filena...
Download file from binary field.
625941de4428ac0f6e5bab2a
def gen_sweep_async(n_frames, n_frames_fade, n_frames_rand, colors): <NEW_LINE> <INDENT> h0, s0, v0 = colors[0] <NEW_LINE> for f in range(n_frames_rand): <NEW_LINE> <INDENT> yield hsv_to_rgb(h0, s0, v0 * (float(f) / n_frames_rand)) <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> for f in range(n_frames): <NEW_LINE>...
Browse the full color wheel (hue component) :param n_frames: Duration between two consecutive colors :param n_frames_fade: Unused :param n_frames_rand: Duration of fade + random seed :param colors: 1-element list containing the first color of the wheel
625941ded486a94d0b98e47d
def press_1(): <NEW_LINE> <INDENT> if pygame.key.get_pressed()[pygame.K_1]: <NEW_LINE> <INDENT> return True
Returns True WHILE the 1 key is being pressed.
625941dec4546d3d9de72d6d
def get_state_dict(self) -> OrderedDict: <NEW_LINE> <INDENT> dqn = deepcopy(self.dqn) <NEW_LINE> return dqn.cpu().state_dict()
Return state dicts, mainly for distributed worker.
625941de66673b3332b923c7
def test_eos_bounds_plot_vol(self): <NEW_LINE> <INDENT> eos = EOSModel(self.p_fun) <NEW_LINE> test_vol = np.linspace(0.01, 1.0, 200) <NEW_LINE> fig = plt.figure() <NEW_LINE> ax1 = fig.gca() <NEW_LINE> ax1.plot(test_vol, eos(test_vol)) <NEW_LINE> for i in range(5): <NEW_LINE> <INDENT> old_dof = eos.get_dof() <NEW_LINE> ...
Plots the extrapolated behaviour
625941de956e5f7376d711a2
def read_one(fname): <NEW_LINE> <INDENT> if fname in PEOPLE: <NEW_LINE> <INDENT> person = PEOPLE.get(fname) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> abort( 404, f"Person with first name {fname} not found" ) <NEW_LINE> <DEDENT> return person
This function responds to a requests for /api/people/{fname} with one matching person from people :param fname: first name of person to find :return: person matching first name
625941defbf16365ca6f64ff
def click_select_payment_method(self, num): <NEW_LINE> <INDENT> self.click_func(self.order_payment_page.find_select_payment_method(num))
点击选择支付方式方法
625941de8e71fb1e9831dade
def create_port(self, context, port): <NEW_LINE> <INDENT> tenant_id = port['port']['tenant_id'] <NEW_LINE> network_id = port['port']['network_id'] <NEW_LINE> admin_state_up = port['port']['admin_state_up'] <NEW_LINE> physical_interface = self.physical_interface <NEW_LINE> with context.session.begin(subtransactions=True...
Create logical port on the switch.
625941de56ac1b37e6264500
def nw(seq_a, seq_b, scores={}, gop=-2.5, gep=-1.75): <NEW_LINE> <INDENT> matrix = {} <NEW_LINE> for y in range(len(seq_b) + 1): <NEW_LINE> <INDENT> for x in range(len(seq_a) + 1): <NEW_LINE> <INDENT> cands = [] <NEW_LINE> if x > 0: <NEW_LINE> <INDENT> score = matrix[(x-1, y)][0] + (gep if matrix[(x-...
Align two sequences using a flavour of the Needleman-Wunsch algorithm with fixed gap opening and gap extension penalties, attributed to Gotoh (1994). The scores arg should be a (char_a, char_b): score dict; if a char pair is missing, 1/-1 are used as match/mismatch scores. Return the best alignment score and one opti...
625941de23849d37ff7b33c3
def UnzipFiles(zip_path, file_names, out_dir): <NEW_LINE> <INDENT> logging.info('Extracting %s from %s', file_names, zip_path) <NEW_LINE> result = [] <NEW_LINE> zip_file = zipfile.ZipFile(zip_path) <NEW_LINE> try: <NEW_LINE> <INDENT> for zip_info in zip_file.infolist(): <NEW_LINE> <INDENT> if zip_info.filename in file_...
Extracts files from zip file. Args: zip_path: Path to zip file. file_names: File names to be extracted. out_dir: Destination directory. Returns: Paths of extracted files.
625941debaa26c4b54cb1453
def _get_set_(self): <NEW_LINE> <INDENT> return self.__set_
Getter method for set_, mapped from YANG variable /network_instances/network_instance/protocols/protocol/ospfv2/global/timers/max_metric/state/set (boolean) YANG Description: When this leaf is set to true, all non-stub interfaces of the local system are advertised with the maximum metric, such that the router ...
625941def7d966606f6aa33e
def fft2(img): <NEW_LINE> <INDENT> r <NEW_LINE> out = np.zeros(img.shape, dtype=complex) <NEW_LINE> for i in range(out.shape[1]): <NEW_LINE> <INDENT> out[:, i] = fft(img[:, i]) <NEW_LINE> <DEDENT> for j in range(out.shape[0]): <NEW_LINE> <INDENT> out[j, :] = fft(out[j, :]) <NEW_LINE> <DEDENT> return out
Improved 2D fft
625941de4e696a04525c9783
def load_config(self): <NEW_LINE> <INDENT> self.config = configparser.ConfigParser() <NEW_LINE> self.config.read('config/eve.cfg')
Loads the general configuration file for EVE
625941deb5575c28eb68e339
def download_workflow(url): <NEW_LINE> <INDENT> filename = url.split("/")[-1] <NEW_LINE> if (not url.endswith('.alfredworkflow') or not filename.endswith('.alfredworkflow')): <NEW_LINE> <INDENT> raise ValueError('Attachment `{0}` not a workflow'.format(filename)) <NEW_LINE> <DEDENT> local_path = os.path.join(tempfile.g...
Download workflow at ``url`` to a local temporary file :param url: URL to .alfredworkflow file in GitHub repo :returns: path to downloaded file
625941de099cdd3c635f0f90
def scan_iteration(cases, paths_extends, filePath, fileInputBase, std_flag=False): <NEW_LINE> <INDENT> fileInputName = fileInputBase <NEW_LINE> def get_model_inputs_labels(filePart): <NEW_LINE> <INDENT> inputs, extra_input, labels = get_inputs_labels(filePath, fileInputName, filePart) <NEW_LINE> inputs_simple, extra_in...
Fills a dictionary with all important model statistics :param cases: model name type :param paths_extends: tuple with path to model and model saveName extension :param filePath: labels filepath :param fileInputBase: base name of labels and models :param std_flag: when active, adds stds from ...
625941de0a366e3fb873eb53
def __init__(self, courses, senior = False, master = False): <NEW_LINE> <INDENT> self.isSenior = senior <NEW_LINE> self.credit = 0 <NEW_LINE> self.finishedCourses = [] <NEW_LINE> self.currentCourses = [] <NEW_LINE> self.isMaster = master <NEW_LINE> self.quartersSpent = 0 <NEW_LINE> self.GPA = N.random.normal(MEAN_GPA,S...
Description: constructor Pre : None Post : A student object is appropriately set Warning: Do not pass in senior = True and master = True Parameters: courses: a list of elective courses that department could offer, in int representation senior: a boolean master: a boolean Returns: None
625941de3cc13d1c6d3c76af
def get_video_comments_features(self): <NEW_LINE> <INDENT> all_video_comments_features = list() <NEW_LINE> if not os.path.isfile(self.VIDEO_COMMENTS_FEATURES_FILENAME): <NEW_LINE> <INDENT> progress = tqdm(total=len(self.GROUNDTRUTH_VIDEOS)) <NEW_LINE> for video_id in self.GROUNDTRUTH_VIDEOS: <NEW_LINE> <INDENT> video_c...
Method that gets the Video Comments 'features' for all all_videos in our Ground Truth :return:
625941de796e427e537b08fe
def show_boxes(im_path, dets, cls, colors=None): <NEW_LINE> <INDENT> if colors is None: <NEW_LINE> <INDENT> colors = ['red' for _ in range(len(dets))] <NEW_LINE> <DEDENT> im = plt.imread(im_path) <NEW_LINE> fig, ax = plt.subplots(figsize=(12, 12)) <NEW_LINE> ax.imshow(im, aspect='equal') <NEW_LINE> for i in range(0, le...
Draw detected bounding boxes.
625941de711fe17d8254269b
def put(self, url, data=None, raw=False): <NEW_LINE> <INDENT> return self.post(url, data, raw, 'PUT')
Send PUT request. Thin wrapper around :func:`~unifi_video.api.post`; the same parameter/return semantics apply here.
625941dee5267d203edcdfd0
def json2paramater(x, is_rand, random_state, oldy=None, Rand=False, name=NodeType.Root.value): <NEW_LINE> <INDENT> if isinstance(x, dict): <NEW_LINE> <INDENT> if NodeType.Type.value in x.keys(): <NEW_LINE> <INDENT> _type = x[NodeType.Type.value] <NEW_LINE> _value = x[NodeType.Value.value] <NEW_LINE> name = name + '-' +...
Json to pramaters.
625941de287bf620b61d3d98
def test_user_exists(self): <NEW_LINE> <INDENT> payload = { 'email': 'test@abc.com', 'password': 'test123', 'name': 'test name' } <NEW_LINE> create_user(**payload) <NEW_LINE> res = self.client.post(CREATE_USER_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
Test creating user that already exists fails
625941dea4f1c619b28b0369
def do_up(self): <NEW_LINE> <INDENT> self.move('up')
sali le scale
625941de097d151d1a22318e
def free_accessibles(self): <NEW_LINE> <INDENT> accessibles = [] <NEW_LINE> for name, accessible in self.astng_element.items(): <NEW_LINE> <INDENT> accessibles.append(LanguageElement.create(accessible, name=name, context_string=self.context_string)) <NEW_LINE> <DEDENT> return accessibles + self.parent().free_accessible...
Return all free accessible of this module
625941de76e4537e8c3519ab
def turn_off(self, **kwargs): <NEW_LINE> <INDENT> self._state = False <NEW_LINE> self.set_state(0, 0, 0, 0) <NEW_LINE> self.schedule_update_ha_state()
Turn the specified light off.
625941de3cc13d1c6d3c76b0
def _binary_clf_curves(self, stabalize_thresh=7, stabalize_pad=7): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from sklearn.metrics._ranking import _binary_clf_curve <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> from sklearn.metrics.ranking import _binary_clf_curve <NEW_LINE> <DEDENT> data = self.data <N...
Code common to ROC, PR, and threshold measures TODO: refactor ROC and PR curves to use this code, perhaps even memoizing it.
625941debe383301e01b57b7
def make_attention_mask_3d(source_block, target_block): <NEW_LINE> <INDENT> mask = (target_block[:, None, :] >= 1) * (source_block[:, :, None] >= 1) <NEW_LINE> return mask
Returns a 3-dimensional (3-D) attention mask :param source_block: 1-D array :param target_block: 1-D array
625941de379a373c97cfae7d
def CalculateDiam(self,Cluster): <NEW_LINE> <INDENT> Max = float('-inf') <NEW_LINE> for ID1 in Cluster: <NEW_LINE> <INDENT> for ID2 in Cluster: <NEW_LINE> <INDENT> if self.LenTwitter <= 1500: <NEW_LINE> <INDENT> dist = self.JaccardMatrix[ID1][ID2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dist = self.JaccardDistanc...
计算聚类之中元素的最大距离 :param Cluster: 输入聚类 :return: 返回最大值
625941dea17c0f6771cbe386
def add_literal_level(self, level): <NEW_LINE> <INDENT> actions = self.a_levels[level-1] <NEW_LINE> curr_level = set() <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> effects = action.effnodes <NEW_LINE> for effect in effects: <NEW_LINE> <INDENT> effect.parents.add(action) <NEW_LINE> action.children.add(effect) <...
add an S (literal) level to the Planning Graph :param level: int the level number alternates S0, A0, S1, A1, S2, .... etc the level number is also used as the index for the node set lists self.a_levels[] and self.s_levels[] :return: adds S nodes to the current level in self.s_levels[level]
625941de3539df3088e2e681
def size(self): <NEW_LINE> <INDENT> return abs(self.begin - self.end)
Get the size of the region.
625941de099cdd3c635f0f91
def _search(self, x, k=3): <NEW_LINE> <INDENT> cur_node = self.root <NEW_LINE> while cur_node.left: <NEW_LINE> <INDENT> if x[cur_node.splitting_feature] <= cur_node.splitting_value: <NEW_LINE> <INDENT> cur_node = cur_node.left <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur_node = cur_node.right <NEW_LINE> <DEDENT> <...
:param x: the target sample point. shape is (n_features,) :param k: the number of nearest neighbours to find. :return: a list of k nearest neighbours.
625941de091ae35668667290
@keras_symbol_child <NEW_LINE> def arange(start, stop=None, step=1, dtype='int32'): <NEW_LINE> <INDENT> dtype = np.dtype(dtype) <NEW_LINE> return KerasSymbol(mx.sym.arange(start=start, stop=stop, step=step, dtype=dtype))
Creates a 1-D tensor containing a sequence of integers. The function arguments use the same convention as Theano's arange: if only one argument is provided, it is in fact the "stop" argument. The default type of the returned tensor is `'int32'` to match TensorFlow's default.
625941de56b00c62f0f14992
def getAction(self, gameState): <NEW_LINE> <INDENT> def isTerminal(state,depth): <NEW_LINE> <INDENT> return state.isWin() or state.isLose() or depth==0 <NEW_LINE> <DEDENT> def Value(state,agentIndex,depth): <NEW_LINE> <INDENT> if isTerminal(state,depth): <NEW_LINE> <INDENT> return self.evaluationFunction(state) <NEW_LI...
Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves.
625941de99cbb53fe6792f1d
def parseCode(input_filename, output_filename): <NEW_LINE> <INDENT> input_file = open(input_filename, 'r') <NEW_LINE> output_file = open(output_filename, 'w') <NEW_LINE> for line in input_file: <NEW_LINE> <INDENT> line = re.sub("_H_NL_", "\n", line) <NEW_LINE> output_file.write(line) <NEW_LINE> <DEDENT> output_file.clo...
Parse the code file
625941de7b25080760e3978f
def __init__(self, **kwargs): <NEW_LINE> <INDENT> self.vimExec = kwargs.get('vimExec', '') <NEW_LINE> self.netbeanPwd = kwargs.get('netbeanPwd', '') <NEW_LINE> self.netbeanPort = kwargs.get('netbeanPort', 5678) <NEW_LINE> self.netbeanHost = kwargs.get('netbeanHost', 'localhost' ) <NEW_LINE> self.useNetbean = kwargs.get...
Init the vim launcher. Keyword arguments: - vimExec: path the vim executable file - netbeanPwd: netbean password. If not provided, generated on the fly. - netbeanPort: port number of the netbean server. Default to 5678 - netbeanHost: host on which the netbean server is running. Default to localhost. - useNetbean: co...
625941ded6c5a10208144384
def print_parameters(self, group_id): <NEW_LINE> <INDENT> group = self.get_group(group_id) <NEW_LINE> if group is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for pid in group.keys(): <NEW_LINE> <INDENT> print('\'' + pid + '\': ', self.try_parse_param(group_id, pid))
Try parse all parameters in a group and print the result.
625941de5fcc89381b1e19f8
def API_KEY(): <NEW_LINE> <INDENT> return pickle.load(open(os.path.join("interface", "src", "bins", "api-key.bin"), "rb"))
Load the API KEY from file so Django cache doens't pick the wrong one
625941de507cdc57c6307019
def test_affordable_list_endpoint_returns_all_objects(self): <NEW_LINE> <INDENT> url = reverse('affordable_list') <NEW_LINE> these_objects = list() <NEW_LINE> for _ in range(5): <NEW_LINE> <INDENT> obj = mixer.blend(Affordable) <NEW_LINE> obj.save() <NEW_LINE> these_objects.append(obj) <NEW_LINE> <DEDENT> response = se...
Ensure that the affordable endpoint returns a list of all values
625941de7c178a314d6ef79c
def compare_analyses(analysis, other_analysis) -> Dict[str, int]: <NEW_LINE> <INDENT> genotype_pairs = zip(analysis.genotypes, other_analysis.genotypes) <NEW_LINE> results = ( compare_genotypes(genotype, other_genotype) for genotype, other_genotype in genotype_pairs ) <NEW_LINE> counter = Counter(results) <NEW_LINE> re...
Compare and score analyses.
625941de96565a6dacc8fa01
def edit_task(self, task_id, attrs): <NEW_LINE> <INDENT> task = self.__connector.get_task(task_id) <NEW_LINE> if 'title' in attrs: <NEW_LINE> <INDENT> task.title = attrs['title'] <NEW_LINE> <DEDENT> self.__connector.save_task(task)
Replace attributes of task with given id by new attributes. :param task_id: id of task to edit. :param attrs: dict of new attributes in format "attribute name: value". Example: {'title': 'task1'}. :return: None :raises 'KeyError': if task with given id does not exist.
625941ded7e4931a7ee9e256
@task <NEW_LINE> def build(ctx, publish=False, carefully=False, travis=False): <NEW_LINE> <INDENT> config = "pelicanconf.py" <NEW_LINE> if publish: <NEW_LINE> <INDENT> config = "publishconf.py" <NEW_LINE> <DEDENT> if travis: <NEW_LINE> <INDENT> config = "travisconf.py" <NEW_LINE> <DEDENT> if carefully: <NEW_LINE> <INDE...
Build a local version of the blog.
625941de60cbc95b062c687a
def test_eval_expr_8(self): <NEW_LINE> <INDENT> sexpr1 = "(define fib (lambda (n) (if (< n 2) 1 (+ (fib (- n 1)) (fib (- n 2))))))" <NEW_LINE> sexpr2 = "(define range (lambda (a b) (if (= a b) (quote ()) (cons a (range (+ a 1) b)))))" <NEW_LINE> sexpr3 = "(range 0 10)" <NEW_LINE> sexpr4 = "(map fib (range 0 10))" <NEW_...
Test 'eval_sexpr' range
625941de0383005118ecf919
def restoring_user(self): <NEW_LINE> <INDENT> self = cPickle.load(open( "users/" + self.user + ".p"))
Once user is known, restore his data from the user list. Based on this data the new dialogue will begin You cannot call this until the user is known. The first thing to be done here will be to check if this user exists.
625941de7d43ff24873a2fd9
@PUT <NEW_LINE> def edit_hook(**kwargs): <NEW_LINE> <INDENT> return HOOK_PATH.format(**kwargs), kwargs
Edit project hook
625941de67a9b606de4a81ee
def test_filter_input_filter_vocab(self): <NEW_LINE> <INDENT> input_tensor = constant_op.constant( [b"the", b"answer", b"to", b"life", b"and", b"universe"]) <NEW_LINE> keys = constant_op.constant([b"and", b"life", b"the", b"to", b"universe"]) <NEW_LINE> values = constant_op.constant([0, 1, 2, 3, 4], dtypes.int64) <NEW_...
Tests input filtering based on vocab frequency table and thresholds.
625941deadb09d7d5db6cac5
def get_modules_repo(self, moduel_name): <NEW_LINE> <INDENT> bare = True <NEW_LINE> if moduel_name == 'test': <NEW_LINE> <INDENT> bare = False <NEW_LINE> <DEDENT> with open('./repositories.yaml') as file: <NEW_LINE> <INDENT> repositories = yaml.load(file) <NEW_LINE> <DEDENT> repo_address = repositories[moduel_name]['re...
finds a modules repository address from repositories.json file and returns a Repo object for the repository @:param module's name @:return repository object for the module
625941de8da39b475bd652ae
def _get_fund_num(url): <NEW_LINE> <INDENT> ct._write_console() <NEW_LINE> try: <NEW_LINE> <INDENT> request = Request(url,headers=ua.get_ua()) <NEW_LINE> text = urlopen(request, timeout=10).read() <NEW_LINE> text = text.decode('gbk') <NEW_LINE> if text == 'null': <NEW_LINE> <INDENT> raise ValueError('get fund num error...
获取基金数量
625941deeab8aa0e5d26de90
def getFoundCompletePath(self): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for string, parentMLT, valueMLT, triesNode in self.existingPath: <NEW_LINE> <INDENT> if triesNode == None: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> ret.append(triesNode.getCompleteName()) <NEW_LINE> <DEDENT> return ret
This method convert any prefix into the original stringList into the complete string stored in the tree @rtype: string list @return: the list of the complete path of each token in the original string list
625941de8a43f66fc4b54399
def test_exempt_login(self): <NEW_LINE> <INDENT> request = self.factory.get('/api/v1/login') <NEW_LINE> response = self.middleware.process_request(request) <NEW_LINE> self.assertIsNone(response)
This test case exempts login view from token authentication
625941de94891a1f4081bde2
def _get_frequencies(self, wav_file, data_size, frames_num): <NEW_LINE> <INDENT> frequencies_num = int(frames_num / data_size) <NEW_LINE> for freq_data in range(frequencies_num): <NEW_LINE> <INDENT> data = wav_file.readframes(data_size) <NEW_LINE> yield self._get_frequency(data, data_size)
Generator. Calculates the remaining frequencies number in wav_file. Reads data_size frames. Returns a frequency in Hz of the frames red. :param wav_file: :param data_size: size of each freq :param frames_num: Where to begin to read
625941ded10714528d60001e
def dump_stats(self, obj): <NEW_LINE> <INDENT> if '_stats' in obj.get('metadata', {}): <NEW_LINE> <INDENT> return obj['metadata'].get('_stats', {}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pid = self.context.get('pid') <NEW_LINE> if isinstance(pid, PersistentIdentifier): <NEW_LINE> <INDENT> return get_record_stats...
Dump the stats to a dictionary.
625941de63f4b57ef0001448
def calc_total_time_in_queue_in_interval(self, start_time, end_time): <NEW_LINE> <INDENT> len_intersection = lambda task: min(task.time_end, end_time) - max(task.time_submit, start_time) <NEW_LINE> return sum(filter(lambda x: x > 0, map(len_intersection, self._tasks)))
Returns total time spent in queue between start_time and end_time by any task. Task is queued on interval [task.time_submit, task.time_end]. If this interval insersects with [start_time, end_time], we add length of this intersection to result.
625941de5fdd1c0f98dc056c
def __init__(self, min_paddle_height=None, max_paddle_height=None, *args, **kwargs): <NEW_LINE> <INDENT> super(OffsetPaddleBreakout, self).__init__(*args, **kwargs) <NEW_LINE> self.min_paddle_height = min_paddle_height <NEW_LINE> self.max_paddle_height = max_paddle_height <NEW_LINE> if self.min_paddle_height is None: <...
Parameters ---------- min_paddle_height : int or None Minimum paddle height. If None, zero. max_paddle_height : int or None Maximum paddle height. If None, a fourth of the game height.
625941de82261d6c526ab7db
def makeCylinder (self, posOne, posTwo, rad_One, rad_Two, unitCell): <NEW_LINE> <INDENT> x = posTwo[0] - posOne[0] <NEW_LINE> y = posTwo[1] - posOne[1] <NEW_LINE> z = posTwo[2] - posOne[2] <NEW_LINE> distance = ((x**2 + y**2 + z**2)**.5 -rad_One - rad_Two) <NEW_LINE> cylinder = vtkCylinderSource() <NEW_LINE> cylinder.S...
returns a cylindrical Actor to represent a bond PosOne and PosTwo are the positions of the two spherical actors rad_One and rad_Two are the radii of the spheres The cylinder will connect the surfaces of the two spheres. The default color for a bond is currently blue.
625941decdde0d52a9e5336c
def read_parameters(self, fp): <NEW_LINE> <INDENT> pass
Read and return the parameters from the stream.
625941de046cf37aa974d07d
@init.command("db") <NEW_LINE> @click.option('--email', type=click.STRING, default=None, help="Email address to use for the initial superuser account.") <NEW_LINE> @click.password_option(prompt=config.SUPERUSER_PASSWORD is None) <NEW_LINE> @click.option('--use-alembic', type=click.BOOL, default=False, help="Use Alembic...
Initializes the database.
625941deff9c53063f47c52a
def encoding_pass(self, dst_file, epass=1): <NEW_LINE> <INDENT> dst_file = dst_file+".mp4" <NEW_LINE> logger.info("encoding_pass: %s" % (dst_file)) <NEW_LINE> encode_cmd = self.build_cmd(dst_file, True, epass) <NEW_LINE> return self.run(encode_cmd, dst_file)
Normal multi-stage encoding pass
625941de63d6d428bbe44828
def listen(self,queue=5): <NEW_LINE> <INDENT> self.socket.listen(queue) <NEW_LINE> socket,addr=self.socket.accept() <NEW_LINE> c=Client() <NEW_LINE> c.socket=socket <NEW_LINE> c.connected=True <NEW_LINE> c.host,c.port=addr <NEW_LINE> return c
Waits for new client.
625941de379a373c97cfae7e
def get_entries(self, topics, start_stamp, end_stamp): <NEW_LINE> <INDENT> with self._bag_lock: <NEW_LINE> <INDENT> bag_entries = [] <NEW_LINE> for b in self._bags: <NEW_LINE> <INDENT> bag_start_time = bag_helper.get_start_stamp(b) <NEW_LINE> if bag_start_time is not None and bag_start_time > end_stamp: <NEW_LINE> <IND...
generator function for bag entries :param topics: list of topics to query, ''list(str)'' :param start_stamp: stamp to start at, ''rospy.Time'' :param end_stamp: stamp to end at, ''rospy,Time'' :returns: entries the bag file, ''msg''
625941de7b180e01f3dc4b2f
def __generate_module_link_dir(self, module): <NEW_LINE> <INDENT> info = "" <NEW_LINE> if module.lib_dirs: <NEW_LINE> <INDENT> info += "LINK_DIRECTORIES({}){}" .format(tmake_utils.flat_path_list(tmake_utils.fix_path_to_abs(module.lib_dirs)), core.LINESEP) <NEW_LINE> <DEDENT> return info
生成 LINK_DIRECTORIES :param module: :return:
625941ded164cc6175783086
def transmit(self, data, receive_length=None): <NEW_LINE> <INDENT> if receive_length is None: <NEW_LINE> <INDENT> receive_length = len(data) <NEW_LINE> <DEDENT> if receive_length > len(data): <NEW_LINE> <INDENT> padding = receive_length - len(data) <NEW_LINE> data.extend([0] * padding) <NEW_LINE> <DEDENT> if len(data) ...
Sends (and typically receives) data over the SPI bus. Args: data -- The data to be sent to the given device. receive_length -- Returns the total amount of data to be read. If longer than the data length, the transmit will automatically be extended with zeroes. TODO: Support more than one chip-...
625941ded164cc6175783087
def outcome(self): <NEW_LINE> <INDENT> have = [] <NEW_LINE> for x in self.supplies.inventory: <NEW_LINE> <INDENT> if x.type == self.pack: <NEW_LINE> <INDENT> have.append(x) <NEW_LINE> <DEDENT> <DEDENT> if len(have) > 0: <NEW_LINE> <INDENT> self.supplies.get_item(self.gain) <NEW_LINE> print(self.story_gain) <NEW_LINE> <...
The outcome function checks a character's inventory for the key associated with a Landmark Whehther the key is present in the inventory then calls a loss or a gain to the inventory. Do I need three functions to affect inventories, characters, etc like with luck?
625941de8e7ae83300e4b305
def make_bst(nums): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> pivot = len(nums) // 2 <NEW_LINE> node = BinaryNode(nums[pivot]) <NEW_LINE> node.right = make_bst(nums[pivot+1:]) <NEW_LINE> node.left = make_bst(nums[:pivot]) <NEW_LINE> return node
Given a list of sorted numbers, make a binary search tree. Returns the root node of a new BST that is valid and balanced.
625941de55399d3f055889ed
def add_set(self, image_folder, label_file, n_train, n_val, n_test, copy_images=True, shuffle=True): <NEW_LINE> <INDENT> with open(label_file, "r") as fp: <NEW_LINE> <INDENT> labels = json.load(fp) <NEW_LINE> <DEDENT> assert (len(labels) == n_train + n_val + n_test) <NEW_LINE> if shuffle: <NEW_LINE> <INDENT> random.see...
Add subset into this dataset Args: image_folder (str): Path to image folder of subset label_file (str): Path to annotation file of subset n_train (int): Number of samples for training n_val (int): Number of samples for validation n_test (int): Number of samples for testing
625941de8da39b475bd652af
def assert_data(self, data, format="yaml", text=None): <NEW_LINE> <INDENT> self.assert_no_error(text) <NEW_LINE> assert self.decoded is not None, "No value was decoded from calicoctl response." <NEW_LINE> if isinstance(data, str): <NEW_LINE> <INDENT> data, _ = decode_json_yaml(data) <NEW_LINE> assert data is not None, ...
Assert the decoded output from the calicoctl command matches the supplied data and the expected decoder format. Args: data: The data to compare format: The expected output format of the data. text: (optional) Expected text in the command output.
625941de32920d7e50b2850b
def __init__(self, container, name): <NEW_LINE> <INDENT> self._container = container <NEW_LINE> self._stat_start_time = None <NEW_LINE> self._name = name <NEW_LINE> self._count = 0 <NEW_LINE> self._exception_count = 0 <NEW_LINE> self._time_sum = float(0) <NEW_LINE> self._time_min = float('inf') <NEW_LINE> self._time_ma...
Parameters: container (:class:`~pywbem.Statistics`): The statistics container that holds this operation statistic object. name (string): Name of the operation.
625941de566aa707497f489d
def splitListToParts(self, root, k): <NEW_LINE> <INDENT> result = [None] * k <NEW_LINE> count = get_count(root) <NEW_LINE> small_chunk_size, num_large_chunks = divmod(count, k) <NEW_LINE> for i in range(num_large_chunks): <NEW_LINE> <INDENT> result[i] = root <NEW_LINE> for j in range(small_chunk_size): <NEW_LINE> <INDE...
:type root: ListNode :type k: int :rtype: List[ListNode]
625941de97e22403b379d2d3
def getColorTable(imgFile, bandNumber=1): <NEW_LINE> <INDENT> if isinstance(imgFile, basestring): <NEW_LINE> <INDENT> ds = gdal.Open(str(imgFile)) <NEW_LINE> <DEDENT> elif isinstance(imgFile, gdal.Dataset): <NEW_LINE> <INDENT> ds = imgFile <NEW_LINE> <DEDENT> gdalBand = ds.GetRasterBand(bandNumber) <NEW_LINE> colorTabl...
Given either an open gdal dataset, or a filename, reads the color table as an array that can be passed to ImageWriter.setColorTable() or rat.setColorTable() The returned colour table is a numpy array, described in detail in the docstring for rat.setColorTable().
625941dedc8b845886cb586e
def timefeatures(time): <NEW_LINE> <INDENT> from_zone = tz.gettz('UTC') <NEW_LINE> to_zone = tz.gettz('America/New_York') <NEW_LINE> [y,m,d,H,M,S]=re.search(r'(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)',time).group(1,2,3,4,5,6) <NEW_LINE> utc = datetime(int(y), int(m), int(d), int(H), int(M), int(S)) <NEW_LINE> utc = utc.repl...
Calculates the day(Sun to Sat), daynumber(0 to 6), hour (0 to 23), month and year from the time input input: text: a date string with UTC time (example 2015-08-25T20:04:14+0000) returns: day (Tuesday), daynumber (2), hour (20), monthyear (082015) ... [NewYorkTime]
625941dea05bb46b383ecb58
def register_services(): <NEW_LINE> <INDENT> global look_up, cat_control, cloudlog_on <NEW_LINE> look_up = None <NEW_LINE> cat_control = None <NEW_LINE> if preference.preference["useqrz"]: <NEW_LINE> <INDENT> look_up = QRZlookup( preference.preference["lookupusername"], preference.preference["lookuppassword"], ) <NEW_L...
setup services
625941de0c0af96317bb8520