code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_releasefield_emergence(self,location): <NEW_LINE> <INDENT> if location == 'kalbar': <NEW_LINE> <INDENT> data_loc = 'data/sampling_details.xlsx' <NEW_LINE> self.releasefield_id = 'A' <NEW_LINE> self.release_DataFrames = [] <NEW_LINE> release_field_data = pd.read_excel( data_loc,sheetname='Kal-releasefield-raw') ...
Get data relating to release field emergence observations. This implementation will need to change completely according to the structure of your dataset. Parsing routines for multiple locations' data can be stored here - just extend the if-then clause based on the value of the location argument. WHAT IS REQ...
625941c64e4d5625662d43f7
def get(self, request, news_id): <NEW_LINE> <INDENT> news = models.News.objects.select_related('tag', 'author').only('title', 'content', 'update_time', 'tag__name', 'author__username').filter(is_delete=False, id=news_id).first() <NEW_LINE> if news: <NEW_LINE> <INDENT> comments = models.Comment.objects.select_related('a...
get请求,返回详情页
625941c6379a373c97cfab62
def _create_ui(self): <NEW_LINE> <INDENT> self.setTitle("Default Macro Action Delay") <NEW_LINE> self.delay_value = gremlin.ui.common.DynamicDoubleSpinBox() <NEW_LINE> self.delay_value.setRange(0.0, 10.0) <NEW_LINE> self.delay_value.setSingleStep(0.05) <NEW_LINE> self.delay_value.setValue(self.profile_data.default_dela...
Creates the UI of this widget.
625941c6d58c6744b4257c7e
def test_instantiate_cirros(session, so_host, data_center_id, rest_endpoint): <NEW_LINE> <INDENT> uri = "{endpoint}/api/operational/nsd-catalog".format(endpoint=rest_endpoint) <NEW_LINE> response = session.request("GET", uri) <NEW_LINE> catalog = json.loads(response.text) <NEW_LINE> cirros_nsd = None <NEW_LINE> for nsd...
Instantiate an instance of cirros from descriptors
625941c6a219f33f3462898a
def __init__(self, problem, iface, datadir = None): <NEW_LINE> <INDENT> self.problem = problem <NEW_LINE> self.iface = int(iface) <NEW_LINE> if datadir is None: <NEW_LINE> <INDENT> self.datadir = getcwd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.datadir = datadir <NEW_LINE> <DEDENT> path.append(datadir) <NEW_...
initializes output object with simulation information
625941c61b99ca400220aacf
def create_tables(self): <NEW_LINE> <INDENT> Building.create_tab(self) <NEW_LINE> Dean.create_tab(self) <NEW_LINE> Room.create_tab(self) <NEW_LINE> Department.create_tab(self) <NEW_LINE> DeansEmp.create_tab(self) <NEW_LINE> FieldOfStudy.create_tab(self) <NEW_LINE> Student.create_tab(self) <NEW_LINE> ExeGroup.create_tab...
func create all tables
625941c631939e2706e4ce8a
def get_optimal_models(train_state, split, reverse=False ): <NEW_LINE> <INDENT> trgts= sort_preds(train_state[f'{split}_indexes'][-1],train_state[f'{split}_targets'][-1].reshape(-1,1)) <NEW_LINE> total_preds = len(train_state[f'{split}_indexes']) <NEW_LINE> init = np.zeros(train_state[f'{split}_preds'][-1].shape) <NEW_...
Naive Ensembling
625941c6b545ff76a8913e35
def __init__(self, complex, rank, name="form", scalar=1): <NEW_LINE> <INDENT> if rank>complex.dimension: <NEW_LINE> <INDENT> print ("impossible to create a form of rank higher than the dimension of the complex generating the form") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.complex = complex <NEW_LINE> self.ran...
A terminal Form is defined by a complex, a rank (need to be an int) and a name The rank has to be lower than the dimension of the complex
625941c64f88993c3716c086
def test_winner(self): <NEW_LINE> <INDENT> self.assertEqual(-987, self.winner_tree.winner[1], 'The result is NOT the winner!')
赢者测试 :return:
625941c632920d7e50b281ed
def most_recent_index(): <NEW_LINE> <INDENT> indices = find_indices() <NEW_LINE> if not indices: <NEW_LINE> <INDENT> status_err('There are no elasticsearch indices to search', m_name='maas_elasticsearch') <NEW_LINE> <DEDENT> return indices[-1]
Get the most recent index if one indeed exists.
625941c657b8e32f524834b8
def _cool_down(self): <NEW_LINE> <INDENT> self._set_power_hook(0) <NEW_LINE> threshold = 300 <NEW_LINE> func = None <NEW_LINE> tm = self.manager.get_device("temperature_monitor") <NEW_LINE> if tm is not None: <NEW_LINE> <INDENT> func = tm.get_process_value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tc = self.manager...
wait until temp is below threshold
625941c60fa83653e4656fda
def init_conf(argv): <NEW_LINE> <INDENT> conf = ConfigParser() <NEW_LINE> conf.read(argv[1]) <NEW_LINE> CONF['logfile'] = conf.get('ping', 'logfile') <NEW_LINE> CONF['magic_number'] = unhexlify(conf.get('ping', 'magic_number')) <NEW_LINE> CONF['db'] = conf.getint('ping', 'db') <NEW_LINE> CONF['workers'] = conf.getint('...
Populates CONF with key-value pairs from configuration file.
625941c607d97122c41788a7
def palette(self, alpha='natural'): <NEW_LINE> <INDENT> if not self.plte: <NEW_LINE> <INDENT> raise FormatError( "Required PLTE chunk is missing in colour type 3 image.") <NEW_LINE> <DEDENT> plte = group(array('B', self.plte), 3) <NEW_LINE> if self.trns or alpha == 'force': <NEW_LINE> <INDENT> trns = array('B', self.tr...
Returns a palette that is a sequence of 3-tuples or 4-tuples, synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These chunks should have already been processed (for example, by calling the :meth:`preamble` method). All the tuples are the same size: 3-tuples if there is no ``tRNS`` chunk, 4-tuples when there is a...
625941c6f8510a7c17cf971a
def sample_par(): <NEW_LINE> <INDENT> sched = Scheduler() <NEW_LINE> sched.schedule_tasks() <NEW_LINE> return sched.load_profile.get_par()
Compute the PAR for a sample run.
625941c6627d3e7fe0d68e6d
def device_update(self): <NEW_LINE> <INDENT> import requests <NEW_LINE> import json <NEW_LINE> result = requests.get(self._url).text <NEW_LINE> data = json.loads(result, strict=False)['result']['list'][0]['content'] <NEW_LINE> self._state = data
更新传感器状态
625941c624f1403a92600b86
def __init__(self, estimator, **kwargs): <NEW_LINE> <INDENT> super(LogisticRegression, self).__init__( estimator, **kwargs) <NEW_LINE> self.estimator = estimator
Port a trained estimator to a dict. Parameters ---------- :param estimator : LogisticRegression An instance of a trained LogisticRegression estimator.
625941c65fdd1c0f98dc0251
def is_unique(str): <NEW_LINE> <INDENT> s = set(str) <NEW_LINE> return True if len(str) == len(s) else False
Implement an algorithm to determine if a string has all unique characters. Args: str - String to test whether its characters are all unique. Returns: bool - True if str contains all unique characters, False otherwise.
625941c6cad5886f8bd26ff8
def walk_up (self, tips, curnode, pathlen, cutoff): <NEW_LINE> <INDENT> pathlen += curnode.branch_length <NEW_LINE> if pathlen < cutoff: <NEW_LINE> <INDENT> if curnode.is_terminal(): <NEW_LINE> <INDENT> tips.append((curnode, pathlen)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for c in curnode.clades: <NEW_LINE> <IN...
Recursive function for traversing up a tree.
625941c6377c676e912721c7
def _addNewObject(self): <NEW_LINE> <INDENT> self.objectCount += 1 <NEW_LINE> self.offsets[self.objectCount] = len(self.buffer) <NEW_LINE> self._bufferAppend(str(self.objectCount)+" 0 obj")
Helper (private) function to add a new object on the PDF buffer and update the reference numbers.
625941c6a8ecb033257d30ec
def cost(self, index): <NEW_LINE> <INDENT> if to_cell(index).has_structure: <NEW_LINE> <INDENT> return 0.0 <NEW_LINE> <DEDENT> modifier = self._disputed_factor(index) * self._expansion_factor(index) <NEW_LINE> return -1.0 * modifier * self.map_data.halite_density[index]
Cost representing the quality of the index as a dropoff location.
625941c64f88993c3716c087
def build_country_code_dictionary(self): <NEW_LINE> <INDENT> country_code_path = os.path.join( self.cache_dir, 'country_names_and_code_elements_txt-temp.htm') <NEW_LINE> if not os.path.exists(country_code_path): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.map_co = {} <NEW_LINE> country_code_file = open(country_...
Return a dictionary mapping country name to the country code.
625941c6d99f1b3c44c675af
def __pred_for_csr(self, csr, num_iteration, predict_type): <NEW_LINE> <INDENT> def inner_predict(csr, num_iteration, predict_type, preds=None): <NEW_LINE> <INDENT> nrow = len(csr.indptr) - 1 <NEW_LINE> n_preds = self.__get_num_preds(num_iteration, nrow, predict_type) <NEW_LINE> if preds is None: <NEW_LINE> <INDENT> pr...
Predict for a csr data
625941c61d351010ab855b3b
def post_load(): <NEW_LINE> <INDENT> ProductProduct.name_get = product_name_get <NEW_LINE> ProductTemplate.name_get = template_name_get
Monkeypatch the replacement methods onto the models from the product_brand module when this module is loaded
625941c6236d856c2ad447f7
def OnDragDiffCurve(event): <NEW_LINE> <INDENT> if event.ydata is None: return <NEW_LINE> if G2frame.itemPicked is None: return <NEW_LINE> Page.canvas.restore_region(savedplot) <NEW_LINE> coords = G2frame.itemPicked.get_data() <NEW_LINE> coords[1][:] += Page.diffOffset + event.ydata <NEW_LINE> Page.diffOffset = -event....
Respond to dragging of the difference curve
625941c6046cf37aa974cd67
def test_not_assign_to_wave(self): <NEW_LINE> <INDENT> location = self.env['stock.location'].create({ 'name': 'Container', 'location_id': self.stock_location.id }) <NEW_LINE> self.env['stock.quant']._update_available_quantity(self.productA, location, 5.0, lot_id=self.lots_p_a[0]) <NEW_LINE> self.env['stock.quant']._upd...
Picking - Move line A 5 from Container to Cust -> Going to a wave picking - Move line A 5 from Container to Cust -> Validate --------------------------------------------- Create - Move A 5 from Container to Cust Check it creates a new picking and it's not assign to the wave
625941c6be7bc26dc91cd621
def urlItems(self, url): <NEW_LINE> <INDENT> raise NotImplementedError("To be implemented by subclass")
:return: list of string-like items which can be found at the given url. If this url is combined with one of the returned items separated by a slash, a valid url is formed, i.e. url/item :param url: A given slash-separated url like base/subitem or '', which requests items at the root of all urls
625941c671ff763f4b5496a8
def __init__(self): <NEW_LINE> <INDENT> self.Total = None <NEW_LINE> self.Used = None <NEW_LINE> self.Stock = None <NEW_LINE> self.Quota = None
:param Total: 总共额度 :type Total: int :param Used: 已使用额度 :type Used: int :param Stock: 库存 :type Stock: int :param Quota: 用户限额 :type Quota: int
625941c691af0d3eaac9ba36
@remote_compatible <NEW_LINE> def test_rrm_beacon_req_table_rsne(dev, apdev): <NEW_LINE> <INDENT> params = hostapd.wpa2_params(ssid="rrm-rsn", passphrase="12345678") <NEW_LINE> params["rrm_beacon_report"] = "1" <NEW_LINE> hapd = hostapd.add_ap(apdev[0], params) <NEW_LINE> dev[0].connect("rrm-rsn", psk="12345678", scan_...
Beacon request - beacon table mode - RSNE reporting
625941c656b00c62f0f14677
def factory_external(arg): <NEW_LINE> <INDENT> return ExternalRedirectTo(arg)
Create a new external-redirect-to action
625941c667a9b606de4a7ed9
def test_spec_manager(): <NEW_LINE> <INDENT> crawler_settings = CrawlerSettings(settings_module=test_settings) <NEW_LINE> return SpecManager(crawler_settings)
Create a CrawlerSpecManager configured to use test settings
625941c656ac1b37e62641f0
def __calculateCentroidsDistanceThreads(self,centroids,j,distanceList): <NEW_LINE> <INDENT> for i in range(self.__m): <NEW_LINE> <INDENT> distance = 0 <NEW_LINE> for n in range(self.__n): <NEW_LINE> <INDENT> distance += pow(self.__inputDataFrame.iloc[i][n] - centroids.iloc[j][n], 2) <NEW_LINE> <DEDENT> distanceList.app...
Threads To make Calculations Faster
625941c656ac1b37e62641f1
def scrapeIndex(self, url): <NEW_LINE> <INDENT> month_urls = ['https://lists.w3.org/Archives/Public/public-restrictedmedia/2013Jul/'] <NEW_LINE> return list(reversed(month_urls))
Returns a list of URLs for month archives, in chronological order.
625941c6091ae35668666f7f
def _get_item_data_name_format(self): <NEW_LINE> <INDENT> return self.format_data['item_data_format_left']
Gets the format used to display the item data name. @return: xlsxwriter.Format that is used to display the item name to the data area.
625941c6d7e4931a7ee9df3c
def test_update_branch(): <NEW_LINE> <INDENT> repo_name = 'audit-python-package' <NEW_LINE> branch_name = 'master' <NEW_LINE> paths = ['requirements/base.txt', 'requirements/documentation.txt', 'requirements/tests.txt'] <NEW_LINE> args = ['requires.io', 'update-branch', '--repository', repo_name, '--name', branch_name]...
update_branch() should call requires.io with the expected parameters
625941c6f7d966606f6aa022
def get_git_dir(path: str) -> Optional[str]: <NEW_LINE> <INDENT> path = os.path.realpath(path) <NEW_LINE> if path.endswith('.git') and is_git_dir(path): <NEW_LINE> <INDENT> return path <NEW_LINE> <DEDENT> git_subdir = os.path.join(path, '.git') <NEW_LINE> if is_git_dir(git_subdir): <NEW_LINE> <INDENT> return git_subdir...
If path points to a git repository, return the path to the repository .git directory. Otherwise, if the path is not a git repository, return None.
625941c6925a0f43d2549e95
def add_random_crop(self, crop_shape, padding=None): <NEW_LINE> <INDENT> self.methods.append(self._random_crop) <NEW_LINE> self.args.append([crop_shape, padding])
add_random_crop. Randomly crop a picture according to 'crop_shape'. An optional padding can be specified, for padding picture with 0s (To conserve original image shape). Examples: ```python # Example: pictures of 32x32 imgaug = tflearn.ImageAugmentation() # Random crop of 24x24 into a 32x32 picture =>...
625941c63317a56b86939c7a
def read_element_from_skf(fileobj, symbol): <NEW_LINE> <INDENT> if isinstance(fileobj, str): <NEW_LINE> <INDENT> fileobj = open(fileobj) <NEW_LINE> <DEDENT> fileobj.readline() <NEW_LINE> eself = [ 0.0 ]*3 <NEW_LINE> U = [ 0.0 ]*3 <NEW_LINE> q = [ 0.0 ]*3 <NEW_LINE> eself[0], eself[1], eself[2], espin, U[0], U[1]...
Read element data from DFTB-style .skf file. Parameters: ----------- fileobj: filename of file-object to read from symbol: chemical symbol of the element
625941c645492302aab5e2e1
def prime_divisors(n=None, factorization=None): <NEW_LINE> <INDENT> if n is None and factorization is None: <NEW_LINE> <INDENT> raise TypeError("prime_divisors: Expected at least one argument.") <NEW_LINE> <DEDENT> elif factorization is None: <NEW_LINE> <INDENT> factorization = factor(abs(n)) <NEW_LINE> <DEDENT> else: ...
Returns a sorted list of the primes dividing `n`. Parameters ---------- n : int, optional factorization : list, optional Factorization of `n` given as a list of (prime, exponent) pairs. Returns ------- p_list : list Sorted list of the prime divisors of `n`. See Also -------- divisors, unitary_divisors, xdiv...
625941c6099cdd3c635f0c7a
def _cancel_transfers(storage=None, vo_name=None): <NEW_LINE> <INDENT> affected_job_ids = set() <NEW_LINE> files = Session.query(File.file_id).filter( and_( (File.source_se == storage) | (File.dest_se == storage), File.file_state.in_(FileActiveStates + ['NOT_USED']) ) ) <NEW_LINE> if vo_name and vo_name != '*': <NEW_LI...
Cancels the transfers that have the given storage either in source or destination, and belong to the given VO. Returns the list of affected jobs ids.
625941c6507cdc57c6306cf7
def __init__(self, to_tensor=True): <NEW_LINE> <INDENT> self.to_tensor = to_tensor
Collates a list of example dicts to a dict of lists, where lists of numpy arrays are stacked. Optionally casts numpy arrays to torch Tensors. Args: to_tensor:
625941c6c432627299f04c64
def __init__(self, config_alg, n_agents, l_state, l_obs, l_action, nn): <NEW_LINE> <INDENT> self.l_state = l_state <NEW_LINE> self.l_obs = l_obs <NEW_LINE> self.l_action = l_action <NEW_LINE> self.nn = nn <NEW_LINE> self.n_agents = n_agents <NEW_LINE> self.tau = config_alg['tau'] <NEW_LINE> self.lr_Q = config_alg['lr_Q...
Args: config_alg: dictionary of general RL params n_agents: number of agents on the team controlled by this alg l_state, l_obs, l_action: int nn: dictionary with neural net sizes
625941c6d4950a0f3b08c36f
def _listen_(_firstNoteInRange_, _lastNoteInRange_, _noteInterval_, _midiCounter_): <NEW_LINE> <INDENT> notes = ['A0', 'A#0', 'B0', 'C1', 'C#1', 'D1', 'D#1', 'E1', 'F1', 'F#1', 'G1', 'G#1', 'A1', 'A#1', 'B1', 'C2', 'C#2', 'D2', 'D#2', 'E2', 'F2', 'F#2', 'G2', 'G#2', 'A2', 'A#2', 'B2', 'C3', 'C#3', 'D3', 'D#3', 'E3', 'F...
Fills dictionaries with note symbols and corresponding frequency values
625941c666656f66f7cbc1c9
def operator_average(psi, op): <NEW_LINE> <INDENT> assert psi.nsites == op.nsites <NEW_LINE> if psi.nsites == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> T = np.identity(psi.A[-1].shape[2], dtype=psi.A[-1].dtype) <NEW_LINE> T = T.reshape((psi.A[-1].shape[2], 1, psi.A[-1].shape[2])) <NEW_LINE> for i in reversed(...
Compute the expectation value `<psi | op | psi>`. Args: psi: wavefunction represented as MPS op: operator represented as MPO Returns: complex: `<psi | op | psi>`
625941c6711fe17d8254238d
def __init__(self, problem: Problem, state: str, serial_planning=True): <NEW_LINE> <INDENT> self.problem = problem <NEW_LINE> self.fs = decode_state(state, problem.state_map) <NEW_LINE> self.serial = serial_planning <NEW_LINE> self.all_actions = self.problem.actions_list + self.noop_actions(self.problem.state_map) <NEW...
:param problem: PlanningProblem (or subclass such as AirCargoProblem or HaveCakeProblem) :param state: str (will be in form TFTTFF... representing fluent states) :param serial_planning: bool (whether or not to assume that only one action can occur at a time) Instance variable calculated: fs: FluentState the...
625941c63eb6a72ae02ec4f9
def threshold(self, img): <NEW_LINE> <INDENT> img = cv2.medianBlur(img, 5) <NEW_LINE> img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) <NEW_LINE> mask = cv2.inRange(img_hsv, self.thresh_low, self.thresh_high) <NEW_LINE> masked_img = cv2.bitwise_and(img, img, mask=mask) <NEW_LINE> return masked_img
Apply the threshold to the image to get only blue parts :param img: RGB camera image :return: Masked image
625941c660cbc95b062c6562
def test_create_users_with_list_input(client: TestClient): <NEW_LINE> <INDENT> user = [{"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phone":"phone","id":0,"email":"email","username":"username"}] <NEW_LINE> headers = { "api_key": "special-key", } <NEW_LINE> response = client.req...
Test case for create_users_with_list_input Creates list of users with given input array
625941c631939e2706e4ce8b
def topKFrequent(self, words, k): <NEW_LINE> <INDENT> count = Counter(words) <NEW_LINE> q = [(-freq, word) for word, freq in count.items()] <NEW_LINE> heapify(q) <NEW_LINE> return [heappop(q)[1] for _ in range(k)]
:type words: List[str] :type k: int :rtype: List[str]
625941c656b00c62f0f14678
def reset_image_attribute(self, image_id, attribute='launchPermission'): <NEW_LINE> <INDENT> params = {'ImageId' : image_id, 'Attribute' : attribute} <NEW_LINE> return self.get_status('ResetImageAttribute', params)
Resets an attribute of an AMI to its default value. See http://docs.amazonwebservices.com/AWSEC2/2008-02-01/DeveloperGuide/ApiReference-Query-ResetImageAttribute.html @type image_id: string @param image_id: ID of the AMI for which an attribute will be described @type attribute: string @param attribute: The attribute ...
625941c65510c4643540f407
@jit <NEW_LINE> def importance_sampling_log_likelihood(log_joint: Tensor, latent_log_joint: Tensor, axis: Optional[List[int]] = None, keepdims: bool = False, reduction: str = 'none', ) -> Tensor: <NEW_LINE> <INDENT> if axis is None or len(axis) == 0: <NEW_LINE> <INDENT> raise ValueError( '`importance_sampling_log_likel...
Compute :math:`\log p(\mathbf{x})` by importance sampling. .. math:: \log p(\mathbf{x}) = \log \mathbb{E}_{q(\mathbf{z}|\mathbf{x})} \Big[\exp\big(\log p(\mathbf{x},\mathbf{z}) - \log q(\mathbf{z}|\mathbf{x})\big) \Big] Args: log_joint: Values of :math:`\log p(\mathbf{z},\mathbf{x})`, compute...
625941c6be8e80087fb20c64
def _change_activity_status( committer_id, activity_id, activity_type, new_status, commit_message): <NEW_LINE> <INDENT> activity_rights = _get_activity_rights(activity_type, activity_id) <NEW_LINE> old_status = activity_rights.status <NEW_LINE> activity_rights.status = new_status <NEW_LINE> if activity_type == constant...
Changes the status of the given activity. Args: committer_id: str. ID of the user who is performing the update action. activity_id: str. ID of the activity. activity_type: str. The type of activity. Possible values: constants.ACTIVITY_TYPE_EXPLORATION, constants.ACTIVITY_TYPE_COLLECTION. ...
625941c65e10d32532c5ef46
def addReport(self, report): <NEW_LINE> <INDENT> with self.reportsLock: <NEW_LINE> <INDENT> probeId = report.getProbeId() <NEW_LINE> self.reports[probeId] = report <NEW_LINE> testLogger.ddebug("Received new report from target probe") <NEW_LINE> if len(self.reports) == self.test.getProbeNumber(): <NEW_LINE> <INDENT> tes...
Adds a report from the remote probe :param report : Report of this probe about the test
625941c6e8904600ed9f1f4a
def get_prices( self, market: Market, interval: Interval, data_range: int ) -> MarketHistory: <NEW_LINE> <INDENT> return self.stocks_ifc.get_prices(market, interval, data_range)
Returns past prices for the given market - market: market to query prices for - interval: resolution of the time series: minute, hours, etc. - data_range: amount of past datapoint to fetch - Returns the MarketHistory instance
625941c62eb69b55b151c8cd
def is_allowed_to_emulate_users(user): <NEW_LINE> <INDENT> allowed = False <NEW_LINE> if user is not None and user.is_authenticated: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> user_profile = user.profile <NEW_LINE> if user_profile.is_company_officer: <NEW_LINE> <INDENT> allowed = True <NEW_LINE> <DEDENT> <DEDENT> exc...
Determines whether `user` is allowed to emulate other users
625941c6187af65679ca513d
def _lint_output(linter, count, violations_list, is_html=False, limit=0): <NEW_LINE> <INDENT> if is_html: <NEW_LINE> <INDENT> lines = ['<body>\n'] <NEW_LINE> sep = '-------------<br/>\n' <NEW_LINE> title = HTML("<h1>Quality Report: {}</h1>\n").format(linter) <NEW_LINE> violations_bullets = ''.join( [HTML('<li>{violatio...
Given a count & list of pylint violations, pretty-print the output. If `is_html`, will print out with HTML markup.
625941c623849d37ff7b30af
def find_resource_by_pattern(endpoint_id, search_pattern): <NEW_LINE> <INDENT> return 'do some magic!'
Find resource by pattern Find resource by pattern within the given context :param endpoint_id: Id of the OXAP endpoint for this OXAP account :type endpoint_id: str :param search_pattern: Pattern for the search request :type search_pattern: str :rtype: Resource
625941c64d74a7450ccd41e3
def edit(db: Session, req_body: schemas.EditMsg) -> models.Message: <NEW_LINE> <INDENT> msg = get_check_user(db, req_body) <NEW_LINE> msg.message = req_body.message <NEW_LINE> if req_body.content_type: <NEW_LINE> <INDENT> msg.content_type = req_body.content_type <NEW_LINE> <DEDENT> if req_body.referal_block: <NEW_LINE>...
Edit text message by id.
625941c6cc0a2c11143dceb0
def do_deleteType(self, args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> argList = args.split() <NEW_LINE> if argList: <NEW_LINE> <INDENT> typeName = argList[0].strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gLogger.error("No type name specified") <NEW_LINE> return <NEW_LINE> <DEDENT> while True: <NEW_LINE> <...
Delete a registered accounting type. Usage : deleteType <typeName> WARN! It will delete all data associated to that type! VERY DANGEROUS! If you screw it, you'll discover a new dimension of pain and doom! :)
625941c6f8510a7c17cf971b
def test_clean_part_all_np_array_types2(self): <NEW_LINE> <INDENT> for dtype in [int, int8, int16, int32, int64, float, float16, float32, float64, float128]: <NEW_LINE> <INDENT> num = np.array([1, 2], dtype=dtype) <NEW_LINE> num_ = _clean_part(num) <NEW_LINE> assert isinstance(num_, list) <NEW_LINE> assert np.all([isin...
Test numpy array for all types.
625941c694891a1f4081bac8
def get_labeled_windowed_data(observations, window_size=7): <NEW_LINE> <INDENT> num_time_points, num_markets = observations.shape <NEW_LINE> windows = [] <NEW_LINE> window_labels = [] <NEW_LINE> for start_idx in range(num_time_points - window_size): <NEW_LINE> <INDENT> windows.append(observations[start_idx:start_idx + ...
Split up the observations into windowed chunks. Each windowed chunk of observations is associated with a label vector of what the price change is per market *immediately after* the windowed chunk (+1 for price goes up, 0 for no change, and -1 for price goes down). Thus, a classifier's task for the data is given a windo...
625941c644b2445a339320b6
def setup(self): <NEW_LINE> <INDENT> self.start_time = None <NEW_LINE> self.splash = pong.AnnoyingSplashScreen() <NEW_LINE> self.display_time = 4
Set up the scene with the basic objects we need to render. * create the splash screen sprite * initialize a timer set to a None value. Later on in our update we'll check the timer to see if it needs to be initialized. Following that we'll check it to see if enough time has elapsed for us to stop displaying.
625941c6dc8b845886cb5554
def remove(self, e): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.vals.remove(e) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> raise ValueError(str(e) + ' not found')
Assuems e is an integer and removes e form self Raises ValueError if e is not in self
625941c62c8b7c6e89b357e1
def belongs_to_folder(path, fileName): <NEW_LINE> <INDENT> return fileName.startswith(path)
Determine if fileName is located under path structure.
625941c676d4e153a657eb50
def create_xmodule(self, location, definition_data=None, metadata=None, system=None): <NEW_LINE> <INDENT> if not isinstance(location, Location): <NEW_LINE> <INDENT> location = Location(location) <NEW_LINE> <DEDENT> if metadata is None: <NEW_LINE> <INDENT> metadata = {} <NEW_LINE> <DEDENT> if system is None: <NEW_LINE> ...
Create the new xmodule but don't save it. Returns the new module. :param location: a Location--must have a category :param definition_data: can be empty. The initial definition_data for the kvs :param metadata: can be empty, the initial metadata for the kvs :param system: if you already have an xblock from the course,...
625941c676e4537e8c351691
def __init__(self, name, slice=None): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> section = getattr(config, 'runner.' + name) <NEW_LINE> substitutions = config.paths <NEW_LINE> substitutions['name'] = name <NEW_LINE> numslices = int(section.instances) <NEW_LINE> if self.is_queue_runner: <NEW_LINE> <INDENT> self.que...
Create a runner. :param slice: The slice number for this runner. This is passed directly to the underlying `ISwitchboard` object. This is ignored for runners that don't manage a queue. :type slice: int or None
625941c696565a6dacc8f6eb
def correct_timezone(dt_value, latitude, longitude): <NEW_LINE> <INDENT> latitude, longitude = float(latitude), float(longitude) <NEW_LINE> tf = timezonefinder.TimezoneFinder() <NEW_LINE> timezone_str = tf.certain_timezone_at(lat=latitude, lng=longitude) <NEW_LINE> if timezone_str is None: <NEW_LINE> <INDENT> tz_correc...
Applies timezone correction to a date-time object using latitude and longitude information
625941c6d6c5a10208144069
def setUp(self): <NEW_LINE> <INDENT> pass
override TestAdminMixin.setUp
625941c6187af65679ca513e
def start_lift(self, lsm): <NEW_LINE> <INDENT> self.lsm = lsm <NEW_LINE> self.lsm.trigger(st.INIT_LIFT_POSITION_TRIGGER) <NEW_LINE> self.lift_move_time = self.calculate_floor_print_time() <NEW_LINE> self.input_passenger_floor_position() <NEW_LINE> while True: <NEW_LINE> <INDENT> self.lsm.trigger(st.GET_LIFT_TRIGGER, li...
This method trigger lift to the first state. :return: None
625941c6460517430c3941a8
def getMeanAirmass(self): <NEW_LINE> <INDENT> midHA = utils.calculateMean(self.getHA()) <NEW_LINE> return utils.computeAirmass(self.dec, midHA)
Returns airmass at mid exposure.
625941c61f5feb6acb0c4b72
def ToShortDateString(self): <NEW_LINE> <INDENT> pass
ToShortDateString(self: DateTime) -> str Converts the value of the current System.DateTime object to its equivalent short date string representation. Returns: A string that contains the short date string representation of the current System.DateTime object.
625941c6d164cc6175782d6d
def insert_worklog(jira_info, issue_id, time_seconds, date_string, comment): <NEW_LINE> <INDENT> this_data = json.dumps({ "timeSpentSeconds": int(time_seconds), "dateStarted": date_string + "T00:00:00.000", "author": { "name": jira_info.username }, "issue": { "key": issue_id }, "comment": comment }) <NEW_LINE> r = requ...
issue_id is e.g. SRCHRD-392 date_string is e.g. 2018-09-25, in other words, the format is yyyy-mm-dd
625941c685dfad0860c3ae7a
def _inrange(self, segment): <NEW_LINE> <INDENT> start = segment.get('start', 0) <NEW_LINE> end = start + segment.get('duration') <NEW_LINE> return start > self.start and end < self.end
Check if a segment is in the song's analysis range
625941c64527f215b584c478
def on_vote_count_updated(game, notification): <NEW_LINE> <INDENT> assert Game.is_observer_game(game)
Manage notification VoteCountUpdated (for observer game). :param game: game associated to received notification. :param notification: received notification. :type game: diplomacy.client.network_game.NetworkGame
625941c6ec188e330fd5a7c1
def kEmptySlots(self, flowers, k): <NEW_LINE> <INDENT> vec = [0 for i in xrange(len(flowers)+1)] <NEW_LINE> box = set() <NEW_LINE> for i in xrange(len(flowers)): <NEW_LINE> <INDENT> idx = flowers[i] <NEW_LINE> self.add(vec, idx, 1) <NEW_LINE> if idx-k-1 in box: <NEW_LINE> <INDENT> if self.get(vec, idx) - self.get(vec, ...
:type flowers: List[int] :type k: int :rtype: int
625941c66fb2d068a760f0bb
def pop(self): <NEW_LINE> <INDENT> self.stack.pop() <NEW_LINE> if len(self.stack) != 0: <NEW_LINE> <INDENT> self.min_val = min(self.stack) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.min_val = sys.maxint
:rtype: void
625941c638b623060ff0ae0d
def test_size_conv(): <NEW_LINE> <INDENT> test_strings = [ '50 PiB', '45 TiB', '4.3 EiB', '1.0 GiB', '100 MiB', '50 KiB', '5 B' ] <NEW_LINE> passed, failed = 0, 0 <NEW_LINE> print('SIZE CONVERSION') <NEW_LINE> for test_str in test_strings: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print('{} -> {}'.format(test_str, a...
Tests string to float conversions for sizes.
625941c65e10d32532c5ef47
def _right_scaffold(G): <NEW_LINE> <INDENT> clss = [cooled_left_stop(G_R) for G_R in G.right] <NEW_LINE> @np.vectorize <NEW_LINE> def inner(t): <NEW_LINE> <INDENT> return np.min([cls(t) + t for cls in clss]) <NEW_LINE> <DEDENT> return inner
Compute the right scaffold of the thermograph of G. Parameters ---------- G : Game The Game of interest. Returns ------- rs : func The right scaffold as a function of temperature.
625941c6b830903b967e992c
def setRegion(self, rgn): <NEW_LINE> <INDENT> if self.lines[0].value() == rgn[0] and self.lines[1].value() == rgn[1]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.blockLineSignal = True <NEW_LINE> self.lines[0].setValue(rgn[0]) <NEW_LINE> self.blockLineSignal = False <NEW_LINE> self.lines[1].setValue(rgn[1]) <NE...
Set the values for the edges of the region. ============= ============================================== **Arguments** rgn A list or tuple of the lower and upper values. ============= ==============================================
625941c6090684286d50ed04
def get_sites(self, entry): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> index_url = reverse('zinnia:entry_archive_index') <NEW_LINE> <DEDENT> except NoReverseMatch: <NEW_LINE> <INDENT> index_url = '' <NEW_LINE> <DEDENT> return ', '.join( ['<a href="%s://%s%s" target="blank">%s</a>' % (settings.PROTOCOL, site.domain, i...
Return the sites linked in HTML.
625941c6adb09d7d5db6c7b0
def _score_battles(self, first_order, second_order): <NEW_LINE> <INDENT> assert len(first_order) == len(second_order) == self.n_strongholds, 'Orders must be specified for all of the strongholds.' <NEW_LINE> final_score = 0 <NEW_LINE> for first_regiment, second_regiment in zip(first_order, second_order): <NEW...
Returns outcome of the specified orders for two armies.
625941c673bcbd0ca4b2c096
def FloatToIntegerDivison(num : float) -> Tuple[int]: <NEW_LINE> <INDENT> decimal_places = len(str(num).split(".")[1]) <NEW_LINE> expon = 10 ** decimal_places <NEW_LINE> nom_denom = (expon * num,expon) <NEW_LINE> g_c_d = GCD(nom_denom[0],nom_denom[1]) <NEW_LINE> while g_c_d > 1: <NEW_LINE> <INDENT> nom_denom = (nom_den...
Returns an a tuple of 2 integers, whose division produces the passed in floating point number
625941c682261d6c526ab4bd
def get_receiver_language(user_id, system): <NEW_LINE> <INDENT> get_language_call = ("SELECT language_code FROM languages WHERE user_id = %s " "AND languages.system = %s") <NEW_LINE> language_values = [user_id, system] <NEW_LINE> language_return = modules.db.get_db_data_new(get_language_call, language_values) <NEW_LINE...
Set the language for the receiver of the tip
625941c626068e7796caecfd
def write_raise(self, stream, error_level=40, log_level=30): <NEW_LINE> <INDENT> if self.problem_level >= log_level: <NEW_LINE> <INDENT> stream.write('Level %s: %s\n' % (self.problem_level, self.message)) <NEW_LINE> <DEDENT> if self.problem_level and self.problem_level >= error_level: <NEW_LINE> <INDENT> if self.error:...
Write report to `stream` Parameters ---------- stream : file-like implementing ``write`` method error_level : int, optional level at which to raise error for problem detected in ``self`` log_level : int, optional Such that if `log_level` is >= ``self.problem_level`` we write the report to `stream`, othe...
625941c616aa5153ce362498
@numba_util.jit() <NEW_LINE> def array_2d_via_indexes_from( array_2d_slim: np.ndarray, sub_shape: Tuple[int, int], native_index_for_slim_index_2d: np.ndarray, ) -> np.ndarray: <NEW_LINE> <INDENT> sub_array_native_2d = np.zeros(sub_shape) <NEW_LINE> for slim_index in range(len(native_index_for_slim_index_2d)): <NEW_LINE...
For a slimmed sub array with sub-indexes mapping the slimmed sub-array values to their native sub-array, return the native 2D sub-array. A sub-array is an array whose dimensions correspond to the normal array multiplied by the sub_size. For example if an array is shape [total_y_pixels, total_x_pixels] and the ``sub_si...
625941c63d592f4c4ed1d091
def blend_face_images(self, img1, img2, weight1=0.5): <NEW_LINE> <INDENT> coeffs1 = coefficient_estimation.estimate_coefficients(img1, self.pix2face_net, self.pix2face_data, self.cuda_device) <NEW_LINE> coeffs2 = coefficient_estimation.estimate_coefficients(img2, self.pix2face_net, self.pix2face_data, self.cuda_device)...
Blend the face images of img1 and img2 using an estimated 3D model and texture map
625941c6a05bb46b383ec843
def setUp(self): <NEW_LINE> <INDENT> super(MagUnauthorisedAuthTestCase, self).setUp() <NEW_LINE> instance_loader = InstanceLoader( database='test', validation=False) <NEW_LINE> instance_loader.add_instances(MOCK_AUTH_MODELS) <NEW_LINE> self.collection = open_test_collection('auth_test') <NEW_LINE> self.collection.remov...
Open a database connection.
625941c6507cdc57c6306cf8
def predict_throughput_pack_sum(raw_preds, pack_ids): <NEW_LINE> <INDENT> sum_pred = np.bincount(pack_ids, weights=raw_preds) <NEW_LINE> return sum_pred
Predict the throughputs for predictions in pack-sum format Parameters ---------- raw_preds: np.ndarray The raw predictions pack_ids: List[int] The pack id for predictions Returns ------- throughputs: np.ndarray The throughput
625941c638b623060ff0ae0e
def get_cur_conditions(): <NEW_LINE> <INDENT> cur_temp = int(math.ceil(WTHR["currently"]["temperature"])) <NEW_LINE> cur_cond = WTHR["currently"]["summary"] <NEW_LINE> precip_prob = WTHR["currently"]["precipProbability"] <NEW_LINE> humidity = WTHR["currently"]["humidity"] * 100 <NEW_LINE> icon = get_weather_emoji(WTHR[...
print current weather
625941c6656771135c3eb88d
def extract_dictionary(infile): <NEW_LINE> <INDENT> word_list = {} <NEW_LINE> with open(infile, 'rU') as fid : <NEW_LINE> <INDENT> counter = 0 <NEW_LINE> for line in fid: <NEW_LINE> <INDENT> words_in_line = extract_words(line) <NEW_LINE> for word_t in words_in_line: <NEW_LINE> <INDENT> if not word_t in word_list.keys()...
Given a filename, reads the text file and builds a dictionary of unique words/punctuations. Parameters -------------------- infile -- string, filename Returns -------------------- word_list -- dictionary, (key, value) pairs are (word, index)
625941c6cb5e8a47e48b7acc
def write_rdf_out4fp(fname,specorder,nspcs,agr,nr,rmax,pairs=None,rmin=0.0,nperline=6): <NEW_LINE> <INDENT> if pairs != None: <NEW_LINE> <INDENT> if type(pairs) not in (list,tuple): <NEW_LINE> <INDENT> raise TypeError('pairs must be list or tuple.') <NEW_LINE> <DEDENT> ndat = nr *len(pairs) <NEW_LINE> data = np.zeros(n...
Write out RDF data in general fp.py format. Parameters ---------- nperline : int Number of data in a line. [default: 6]
625941c64a966d76dd55102f
def solve(x: int) -> int: <NEW_LINE> <INDENT> return next(i for i in count(2) if all(len(distinct_prime_factors(j)) == x for j in range(i, i + x)))
Find x consecutive integers that have x distinct prime factors each.
625941c6a17c0f6771cbe071
def guided_relu(x): <NEW_LINE> <INDENT> return GuidedReLU()(x)
Rectified Linear Unit function with guided backpropagation. .. math:: f(x)=\max(0, x). Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. Returns: ~chainer.Variable: Output variable. A ...
625941c68a349b6b435e8193
def test_get_categories(self): <NEW_LINE> <INDENT> response = self.category.get_categories() <NEW_LINE> self.assertIsInstance(response, list, msg = "Can't get categories") <NEW_LINE> self.assertIsInstance(response[0], dict, msg = "Can't get categories")
test get categories
625941c64e4d5625662d43f9
def gravatar(self, size=128, default='identicon', rating='g'): <NEW_LINE> <INDENT> return 'http://www.gravatar.com/avatar/{}?s={}&d={}&r={}'.format( hashlib.md5(self.email.encode('utf-8')).hexdigest(), size, default, rating )
user avatar, using gravatar
625941c6379a373c97cfab64
def _VerifyImageHas(self, tar, expected): <NEW_LINE> <INDENT> tmp_dir = tempfile.mkdtemp(dir='/tmp') <NEW_LINE> tar_cmd = ['tar', '-xzf', tar, '-C', tmp_dir] <NEW_LINE> self.assertEqual(subprocess.call(tar_cmd), 0) <NEW_LINE> disk_path = os.path.join(tmp_dir, 'disk.raw') <NEW_LINE> with utils.LoadDiskImage(disk_path) a...
Tests if raw disk contains an expected list of files/directories.
625941c64f6381625f114a5b
def plot_compare(self, other_plotter): <NEW_LINE> <INDENT> plt = self.get_plot() <NEW_LINE> data_orig = self.bs_plot_data() <NEW_LINE> data = other_plotter.bs_plot_data() <NEW_LINE> band_linewidth = 3 <NEW_LINE> for i in range(other_plotter._nb_bands): <NEW_LINE> <INDENT> plt.plot(data_orig['distances'], [e for e in da...
plot two band structure for comparison. One is in red the other in blue (no difference in spins). The two band structures need to be defined on the same symmetry lines! and the distance between symmetry lines is the one of the band structure used to build the BSPlotter Args: another band structure object defined a...
625941c6283ffb24f3c55923
def _add_to_jobs_page(self): <NEW_LINE> <INDENT> areas = len(self.areas_list) <NEW_LINE> new_line = u'#[[%s]] ([[%s]] boss)\n' % (self.area_name, self.boss_name) <NEW_LINE> text = self.jobs_page_text.replace(u'There are currently %d [[' % areas, u'There are currently %d [[' % (areas + 1)) <NEW_LINE> if self.new_number ...
Add the new area to the Jobs page.
625941c6baa26c4b54cb1141
def resequence_route_all(self, **kwargs): <NEW_LINE> <INDENT> kwargs.update({'api_key': self.params['api_key'], }) <NEW_LINE> if self.check_required_params(kwargs, ['disable_optimization', 'route_id', 'optimize', ]): <NEW_LINE> <INDENT> response = self.api._request_get(RESEQUENCE_ROUTE, kwargs) <NEW_LINE> return respon...
Resequence Route using GET :return: API response :raises: ParamValueException if required params are not present. AttributeError if there is an error deleting a route
625941c6fb3f5b602dac36b2
def __call__(self, his, buf, stk, label): <NEW_LINE> <INDENT> stk = self.U(stk) <NEW_LINE> stk = F.relu(stk) <NEW_LINE> buf = self.V(buf) <NEW_LINE> buf = F.relu(buf) <NEW_LINE> at = self.LA(his) <NEW_LINE> at = F.relu(at) <NEW_LINE> st = self.LS(stk) <NEW_LINE> st = F.relu(st) <NEW_LINE> bt = self.LB(buf) <NEW_LINE> b...
params: his: {his}, {his}, {...} buf: {w,wlm,t}, {...}, {...} stk: {h,d,r}, {...}, {...} label: y0,y1,y2 ...
625941c6c432627299f04c65
def get_learned_routes( self, resource_group_name, virtual_network_gateway_name, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworkGateways/{virtualNetworkGatewayName}/getLearnedRou...
This operation retrieves a list of routes the virtual network gateway has learned, including routes learned from BGP peers. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param virtual_network_gateway_name: The name of the virtual network gateway. :type virtual_network_gat...
625941c6a934411ee37516b4
def incremental_server_update(self, server_id, current_files): <NEW_LINE> <INDENT> def delete_doc(writer, serverid, path): <NEW_LINE> <INDENT> writer.delete_by_query(Term('server_id', str(serverid)) & Term('path', path)) <NEW_LINE> <DEDENT> to_index = {} <NEW_LINE> for path, size, mtime in current_files: <NEW_LINE> <IN...
Prepares to incrementaly update the documents for the given server. server_id -- Id of the server to update. current_files -- a list of (path, size, mtime) tuples for each files currently on the server. Delete all the outdated files from the index and returns a list of files needing to be rein...
625941c632920d7e50b281ef