code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def _calculate_w( biophysical_table, lulc_path, w_factor_path, out_thresholded_w_factor_path): <NEW_LINE> <INDENT> lulc_to_c = dict( [(lulc_code, float(table['usle_c'])) for (lulc_code, table) in biophysical_table.items()]) <NEW_LINE> if geoprocessing.get_raster_info(lulc_path)['nodata'][0] is None: <NEW_LINE> <INDENT>... | W factor: map C values from LULC and lower threshold to 0.001.
W is a factor in calculating d_up accumulation for SDR.
Parameters:
biophysical_table (dict): map of LULC codes to dictionaries that
contain at least a 'usle_c' field
lulc_path (string): path to LULC raster
w_factor_path (string): path... | 625941c73346ee7daa2b2dbf |
def _mouse_click ( self, event, trait ): <NEW_LINE> <INDENT> x = event.GetX() <NEW_LINE> row, flags = self.control.HitTest( wx.Point( x, event.GetY() ) ) <NEW_LINE> if row == wx.NOT_FOUND: <NEW_LINE> <INDENT> if self.factory.multi_select: <NEW_LINE> <INDENT> self.multi_selected = [] <NEW_LINE> self.multi_selec... | Generate a TabularEditorEvent event for a specified mouse event and
editor trait name. | 625941c724f1403a92600bbb |
def exe( self, parent_job: str, job_script: str, facetpath: str, cores: int = 1) -> Any: <NEW_LINE> <INDENT> from balsam.launcher.dag import BalsamJob <NEW_LINE> job_files_path = os.path.join( creation_dir, job_file_dir_name, facetpath) <NEW_LINE> slab_opt = '00_{}_set_up_slab_opt.py'.format(facetpath) <NEW_LINE> big_s... | Add python job file to balsam DB
Parameters
----------
parent_job : str
a parent job on which subbmited jobs depends on. Formatted as:
``00`` or ``01`` or ``02`` or ``03`` or ``04`` or ``05``,
depending on the job
job_script : str
a script that is about to be submitted
cores : int
number of cores ... | 625941c7566aa707497f45bf |
def generate_script(self, profile, system, name): <NEW_LINE> <INDENT> self.log("generate_script") <NEW_LINE> if system: <NEW_LINE> <INDENT> return self.tftpgen.generate_script("system", system, name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.tftpgen.generate_script("profile", profile, name) | Generate an autoinstall script for the specified profile or system. The system wins over the profile.
:param profile: The profile to generate the script for.
:param system: The system to generate the script for.
:param name: The name of the script which should be generated.
:return: The generated script or an error me... | 625941c791f36d47f21ac546 |
def subjoinsemilattice(self, elms): <NEW_LINE> <INDENT> gens_remaining = set(elms) <NEW_LINE> current_set = set() <NEW_LINE> while gens_remaining: <NEW_LINE> <INDENT> g = gens_remaining.pop() <NEW_LINE> if g in current_set: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for x in current_set: <NEW_LINE> <INDENT> gens_... | Return the smallest join-subsemilattice containing elements on the given list.
INPUT:
- ``elms`` -- a list of elements of the lattice.
EXAMPLES::
sage: L = posets.DivisorLattice(1000)
sage: L_ = L.subjoinsemilattice([2, 25, 125]); L_
Finite join-semilattice containing 5 elements
sage: sorted(L_.list... | 625941c7cdde0d52a9e53086 |
def test_bounds(xes: fd.ERSource): <NEW_LINE> <INDENT> data = xes.data <NEW_LINE> for qn in quanta_types: <NEW_LINE> <INDENT> for p in ('produced', 'detected'): <NEW_LINE> <INDENT> print(qn + '_' + p) <NEW_LINE> np.testing.assert_array_less( data['%ss_%s_min' % (qn, p)].values, data['%ss_%s_mle' % (qn, p)].values + 1e-... | Test bounds on nq_produced and _detected | 625941c70fa83653e4657010 |
def append(self, valor): <NEW_LINE> <INDENT> new = No(valor) <NEW_LINE> if self.tail is None: <NEW_LINE> <INDENT> self.head = self.tail = new <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tail.proximo = new <NEW_LINE> self.tail = self.tail.proximo | Insere X no final da lista. | 625941c77047854f462a145f |
def logwarn_dataframe(dataframe, msg, columns=None, max_row_count=30): <NEW_LINE> <INDENT> if len(dataframe) > max_row_count: <NEW_LINE> <INDENT> chunks = ['showing first', 'row' if max_row_count == 1 else '%d rows' % max_row_count, 'only'] <NEW_LINE> footer = "\n... (%s)" % " ".join(chunks) <NEW_LINE> dataframe = data... | Log as warning the current dataframe. Does not check if
Dataframe is empty
:param columns: the columns to print, if None writes all columns | 625941c7f7d966606f6aa057 |
def get_format_dict(self): <NEW_LINE> <INDENT> return { 'name': self.get_name_str(), 'type': self.get_type_str(), 'comment': self.get_comment_str(), 'method': self.get_method_name_str() } | 用于格式化 | 625941c729b78933be1e5702 |
def remove_last(self, actions): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> for action in actions: <NEW_LINE> <INDENT> if index == len(actions) - 1: <NEW_LINE> <INDENT> actions.remove(action) <NEW_LINE> <DEDENT> index += 1 | removes the last element of actions | 625941c730bbd722463cbe19 |
def connect(self, synchronous: bool = False): <NEW_LINE> <INDENT> self._connect_crazyflie() <NEW_LINE> if synchronous: <NEW_LINE> <INDENT> self._connect_event.wait() | Connects to the Crazyflie. | 625941c7d268445f265b4ec2 |
def decompose_rules(self, flows, groups): <NEW_LINE> <INDENT> device_rules = deepcopy(self.get_all_default_rules()) <NEW_LINE> group_map = dict((g.desc.group_id, g) for g in groups) <NEW_LINE> for flow in flows: <NEW_LINE> <INDENT> for device_id, (_flows, _groups) in self.decompose_flow(flow, group_m... | Generate per-device flows and flow-groups from the flows and groups
defined on a logical device
:param flows: logical device flows
:param groups: logical device flow groups
:return: dict(device_id ->
(OrderedDict-of-device-flows, OrderedDict-of-device-flow-groups)) | 625941c7adb09d7d5db6c7e4 |
def spewer(frame, s, ignored): <NEW_LINE> <INDENT> from twisted.python import reflect <NEW_LINE> if "self" in frame.f_locals: <NEW_LINE> <INDENT> se = frame.f_locals["self"] <NEW_LINE> if hasattr(se, "__class__"): <NEW_LINE> <INDENT> k = reflect.qual(se.__class__) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> k = refle... | A trace function for sys.settrace that prints every function or method call. | 625941c756b00c62f0f146ad |
def set_url(self, url: str): <NEW_LINE> <INDENT> del self.story <NEW_LINE> self.story = None <NEW_LINE> for site_class, site_identifier in cst.SITES.values(): <NEW_LINE> <INDENT> if re.search(site_identifier, url) is not None: <NEW_LINE> <INDENT> self.__logger = tls.setup_logging( f'StoryWriter | {site_class.__name__}'... | Set the new url to use for the writer
:param url: the new url to use
:raise: AttributeError if the url does not belong to a handled site
Internet related errors if the connection fails | 625941c7b5575c28eb68e054 |
def _indexedProps(spec): <NEW_LINE> <INDENT> return [prop for prop, propclass in spec.getprops().items() if isinstance(propclass, hyperdb.String) and propclass.indexme] | Get a list of properties to be indexed on 'spec'. | 625941c72eb69b55b151c902 |
def write_hex_key(key): <NEW_LINE> <INDENT> with open("Key.txt", 'wb') as f: <NEW_LINE> <INDENT> f.write(key) | Запись ключа в файл в вибе байтов, что бы можна было скопировать его и использовать
в программах, таких как CrypTool | 625941c75fcc89381b1e1713 |
def knightProbability(self, N: int, K: int, r: int, c: int) -> float: <NEW_LINE> <INDENT> currDp = [[0] * N for _ in range(N)] <NEW_LINE> currDp[r][c] = 1 <NEW_LINE> DIRECTIONS = [ (2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2) ] <NEW_LINE> for _ in range(K): <NEW_LINE> <INDENT> nextDp = [[0] * ... | 1. Suppose f[r][c][s] is the possibility to reach cell (r, c)
after s steps. Then we have:
f[r][c][s] = sum(f[r + dr][c + dc][s - 1] / 8.0).
2. Then our problem is to find
sum(f[r][c][K] for r in range(N) for c in range(N)).
3. Since the equation of f is only related to the f[s] and f[s - 1], we
co... | 625941c7ab23a570cc2501d6 |
def fire_and_forget(self, frame_set): <NEW_LINE> <INDENT> assert isinstance(frame_set, UbxFrame) <NEW_LINE> logger.debug(f"firing {frame_set.NAME}") <NEW_LINE> frame_set.pack() <NEW_LINE> self._send(frame_set) | Send a set message to modem without waiting for a response
(fire and forget)
This method is typically used for commands that are not ACKed, i.e.
- cold start
- change baudrate | 625941c7ac7a0e7691ed4123 |
def got_line(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request = json.loads(data.decode()) <NEW_LINE> _LOGGER.info('Got client request: %s - %r', self.peer(), request) <NEW_LINE> reply = self.on_request(request) <NEW_LINE> self.write(json.dumps(reply).encode()) <NEW_LINE> <DEDENT> except Exception as er... | Line callback.
| 625941c74e4d5625662d442e |
@robot_api.route('/robot/webhooks', methods=['GET']) <NEW_LINE> def ListWebHooks(): <NEW_LINE> <INDENT> return handlers.ListWebHooksHandler() | List all configured web hooks
It is handler for GET /robot/webhooks | 625941c7a4f1c619b28b0090 |
def mutexify(node1: PgNode, node2: PgNode): <NEW_LINE> <INDENT> if type(node1) != type(node2): <NEW_LINE> <INDENT> raise TypeError('Attempted to mutex two nodes of different types') <NEW_LINE> <DEDENT> node1.mutex.add(node2) <NEW_LINE> node2.mutex.add(node1) | adds sibling nodes to each other's mutual exclusion (mutex) set. These should be sibling nodes!
:param node1: PgNode (or inherited PgNode_a, PgNode_s types)
:param node2: PgNode (or inherited PgNode_a, PgNode_s types)
:return:
node mutex sets modified | 625941c77d43ff24873a2cf5 |
def contains_issue(self, jira_issue: JiraIssue) -> bool: <NEW_LINE> <INDENT> return jira_issue.issue_key in self.known_issues | Used after report population to determine if an issue should be displayed by a MemberIssuesByStatus | 625941c7925a0f43d2549ecb |
def _parse_wadl_file(self, filename): <NEW_LINE> <INDENT> filename = os.path.join(self.data_path, filename) <NEW_LINE> with open(filename, "rb") as fh: <NEW_LINE> <INDENT> wadl_string = fh.read() <NEW_LINE> <DEDENT> with warnings.catch_warnings(record=True) as w: <NEW_LINE> <INDENT> warnings.simplefilter("always") <NEW... | Parses wadl, returns WADLParser and any catched warnings. | 625941c7fbf16365ca6f6217 |
def test_transform_empty(self, klass): <NEW_LINE> <INDENT> assert klass().transform('') is None | Test transform with none_ok = False and an empty value. | 625941c75166f23b2e1a51ae |
def test__api_cart_remove_no_reqno(self): <NEW_LINE> <INDENT> url = '/__cart/remove.json?opusid=co-iss-n1460961026' <NEW_LINE> self._run_status_equal(url, 404, HTTP404_BAD_OR_MISSING_REQNO('/__cart/remove.json')) | [test_cart_api.py] /__cart/remove: no reqno | 625941c7e8904600ed9f1f81 |
def Synthesise( self ): <NEW_LINE> <INDENT> output_sig = np.zeros( ( 1, self._num_frames*self._frame_inc + self._win_len ) ) <NEW_LINE> time_windows = np.fft.ifft( self._spec, axis=0 ) <NEW_LINE> time_windows = time_windows[:self._win_len,:] <NEW_LINE> time_windows = np.real( time_windows ) <NEW_LINE> for win_num in ra... | Synthesise the spectrogram as a 1D real signal using the overlap-add method with no synthesis windowing.
Return:
np.ndarray 1D - The synthesised signal using overlap-add. | 625941c7ec188e330fd5a7f6 |
def _check_args(self, **kwargs): <NEW_LINE> <INDENT> for arg in kwargs.keys(): <NEW_LINE> <INDENT> if type(kwargs[arg]) not in self.ALLOWED_TYPES: <NEW_LINE> <INDENT> raise TypeError('Argument {} has invalid type {}'.format(arg, type(kwargs[arg]))) | Checks whether the arguments are in the required structure
:param kwargs: arguments
:return: None | 625941c7796e427e537b061a |
def add_category(self, obj, user_id): <NEW_LINE> <INDENT> new_category = Category() <NEW_LINE> new_category.name = obj['name'] <NEW_LINE> new_category.slug = obj['slug'] <NEW_LINE> new_category.icon= obj['icon'] <NEW_LINE> new_category.user_id = user_id <NEW_LINE> session.add(new_category) <NEW_LINE> session.commit() <... | Controller for passing items within a category to DB
:param obj: JSON passed from AJAX
:param user_id: User ID Integer
:return: | 625941c766656f66f7cbc1ff |
def __init__(self): <NEW_LINE> <INDENT> self.client = pymongo.MongoClient('localhost',27017) <NEW_LINE> self.database = self.client.lagou | 连接数据库
client:mongodb对象
database:数据库对象 | 625941c7f548e778e58cd5d2 |
def fourSum(self, nums, target): <NEW_LINE> <INDENT> result = [] <NEW_LINE> sums={} <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> for j in range(i+1,len(nums)): <NEW_LINE> <INDENT> s = nums[i]+nums[j] <NEW_LINE> if s not in sums: <NEW_LINE> <INDENT> sums[s] = [[i,j]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN... | :type nums: List[int]
:type target: int
:rtype: List[List[int]] | 625941c77cff6e4e811179db |
def run(self): <NEW_LINE> <INDENT> self.__set_spider_schedule() <NEW_LINE> while True: <NEW_LINE> <INDENT> self.schedule.run_pending() | 开始按计划运行
:return: | 625941c750812a4eaa59c378 |
def amount(self): <NEW_LINE> <INDENT> if self.amount_ is not None: <NEW_LINE> <INDENT> return self.amount_ <NEW_LINE> <DEDENT> cur = self.sqldb.cursor() <NEW_LINE> cur.execute('select amount from block_info where block=?', (self.id,)) <NEW_LINE> amount = next(cur)[0] <NEW_LINE> if amount is not None: <NEW_LINE> <INDENT... | For a send/receive/open block compute the amount being transfered.
For other block types return None. | 625941c707f4c71912b114d7 |
def __init__(self, w=40, h=30, c=3, out=3, init_zeros=False, dueling=False): <NEW_LINE> <INDENT> super(DQNetwork, self).__init__() <NEW_LINE> self.dueling = dueling <NEW_LINE> self.conv_1 = nn.Conv2d( in_channels=c, out_channels=32, kernel_size=8, stride=4) <NEW_LINE> self.conv_2 = nn.Conv2d( in_channels=32, out_channe... | Description
---------------
Constructor of Deep Q-network class.
Parameters
---------------
w : Int, input width
h : Int, input height
c : Int, input channels
init_zeros : Boolean, whether to initialize the weights to zero or not.
out : Int, the number of output units, it corresponds ... | 625941c7435de62698dfdca1 |
def do_reload(self, line): <NEW_LINE> <INDENT> pass | Reload configuration files and scripts.
Usage: reload
not implimented | 625941c7656771135c3eb8c3 |
def test_Detail(self): <NEW_LINE> <INDENT> obj, created = self.model.objects.get_or_create(**self.get_add_form_data()) <NEW_LINE> client = Client() <NEW_LINE> client.login(username=self.username, password=self.password) <NEW_LINE> response = client.get(reverse_lazy(self.get_url_name('detail', postfix=True), args=[obj.u... | Tests the Detail view | 625941c7498bea3a759b9b04 |
def to_sparse(rt_input, name=None): <NEW_LINE> <INDENT> if not ragged_tensor.is_ragged(rt_input): <NEW_LINE> <INDENT> raise TypeError('Expected RaggedTensor, got %s' % type(rt_input).__name__) <NEW_LINE> <DEDENT> with ops.name_scope(name, 'RaggedToSparse', [rt_input]): <NEW_LINE> <INDENT> rt_input = ragged_factory_ops.... | Converts a `RaggedTensor` into a sparse tensor.
Example:
```python
>>> rt = ragged.constant([[1, 2, 3], [4], [], [5, 6]])
>>> ragged.to_sparse(rt).eval()
SparseTensorValue(indices=[[0, 0], [0, 1], [0, 2], [1, 0], [3, 0], [3, 1]],
values=[1, 2, 3, 4, 5, 6],
dense_shape=[4, 3])
```
... | 625941c73cc13d1c6d3c73d0 |
def _prepare_cloned_data(self, original_asset, source_version, partial_update): <NEW_LINE> <INDENT> if self._validate_destination_type(original_asset): <NEW_LINE> <INDENT> cloned_data = original_asset.to_clone_dict(version=source_version) <NEW_LINE> cloned_data.update(self.request.data.items()) <NEW_LINE> if partial_up... | Some business rules must be applied when cloning an asset to another with a different type.
It prepares the data to be cloned accordingly.
It raises an exception if source and destination are not compatible for cloning.
:param original_asset: Asset
:param source_version: AssetVersion
:param partial_update: Boolean
:r... | 625941c78c3a87329515840f |
def _read_layer_tagged_blocks(fp, remaining_length): <NEW_LINE> <INDENT> blocks = [] <NEW_LINE> start_pos = fp.tell() <NEW_LINE> read_bytes = 0 <NEW_LINE> while read_bytes < remaining_length: <NEW_LINE> <INDENT> block = _read_additional_layer_info_block(fp) <NEW_LINE> read_bytes = fp.tell() - start_pos <NEW_LINE> if bl... | Reads a section of tagged blocks with additional layer information. | 625941c7d164cc6175782da3 |
def on_change(self, event): <NEW_LINE> <INDENT> self.ctrl.update_layout() | Notify control to resize accordingly | 625941c7cb5e8a47e48b7b01 |
def create_hud(self, hud_name): <NEW_LINE> <INDENT> self.remove_hud(hud_name) <NEW_LINE> try: <NEW_LINE> <INDENT> pm.headsUpDisplay( hud_name, section=7, block=1, ao=1, blockSize="medium", labelFontSize="large", dfs="large", command=self.get_hud_data, atr=1 ) <NEW_LINE> <DEDENT> except RuntimeError: <NEW_LINE> <INDENT>... | creates HUD
| 625941c7293b9510aa2c32ec |
def processor_affinity(self): <NEW_LINE> <INDENT> return _iio_swig.fmcomms2_source_f32c_sptr_processor_affinity(self) | processor_affinity(fmcomms2_source_f32c_sptr self) -> std::vector< int,std::allocator< int > > | 625941c7004d5f362079a389 |
def checkStatus(self): <NEW_LINE> <INDENT> runningJobs = self.bossAir.track() <NEW_LINE> if len(runningJobs) < 1: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self.timeouts == {}: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> jobsToKill = [] <NEW_LINE> for job in runningJobs: <NEW_LINE> <INDENT> globalState = job... | _checkStatus_
Run the BossAir track() function (self-contained)
and then check for jobs that have timed out. | 625941c7be7bc26dc91cd657 |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ApiUserSource): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941c7eab8aa0e5d26dbad |
def filename_from_url(url): <NEW_LINE> <INDENT> filename = "".join(i for i in url if i not in "\/:*?<>|") <NEW_LINE> return filename | Similar to Django slugify
http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python
:param url: url to convert
:return: a valid filename | 625941c7bde94217f3682e47 |
def sortedArrayToBST(nums): <NEW_LINE> <INDENT> pass | :type nums: List[int]
:rtype: TreeNode
构造平衡二叉树 | 625941c750485f2cf553cdef |
def exchange_delete(self, callback=None, exchange=None, if_unused=False, nowait=False): <NEW_LINE> <INDENT> self._validate_channel_and_callback(callback) <NEW_LINE> return self._rpc(spec.Exchange.Delete(0, exchange, if_unused, nowait), callback, [spec.Exchange.DeleteOk] if nowait is False else []) | Delete the exchange.
:param method callback: The method to call on Exchange.DeleteOk
:param exchange: The exchange name
:type exchange: str or unicode
:param bool if_unused: only delete if the exchange is unused
:param bool nowait: Do not wait for an Exchange.DeleteOk | 625941c715fb5d323cde0b64 |
def rhs(y,param): <NEW_LINE> <INDENT> dydx = numpy.array([y[1], param[0]*(y[0]**3)-(param[1]**2)*y[0]]) <NEW_LINE> return dydx | RHS function. ici y[0,:] = psi, y[1,:] = psi'
y[2,:]= phi, y[3,:] = phi' | 625941c7a8ecb033257d3123 |
def norm_resid(self, Y): <NEW_LINE> <INDENT> return self.resid(Y) * positive_reciprocal(np.sqrt(self.dispersion)) | Residuals, normalized to have unit length.
Notes
-----
Is this supposed to return "stanardized residuals,"
residuals standardized
to have mean zero and approximately unit variance?
d_i = e_i / sqrt(MS_E)
Where MS_E = SSE / (n - k)
See: Montgomery and Peck 3.2.1 p. 68
Davidson and MacKinnon 15.2 p 662 | 625941c74e696a04525c94a1 |
def p_if_quadruple(t): <NEW_LINE> <INDENT> if_quadruple() | if_quadruple : | 625941c7e5267d203edcdcf4 |
def get_calendar(): <NEW_LINE> <INDENT> for widget in frame_calendar_events.winfo_children(): <NEW_LINE> <INDENT> widget.destroy() <NEW_LINE> <DEDENT> for i in frame_calendar_image.winfo_children(): <NEW_LINE> <INDENT> i.destroy() <NEW_LINE> <DEDENT> credentials = get_credentials() <NEW_LINE> http = credentials.authori... | Shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object and outputs a list of the next
5 events on the user's calendar. | 625941c75f7d997b87174aec |
def get_propertygroup(target_platform, attributes=''): <NEW_LINE> <INDENT> prop = '//ns:PropertyGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'{}\'"{}]'.format( '|'.join(target_platform), attributes) <NEW_LINE> return prop | Return "property_groups" value for wanted platform and target
:param target_platform: wanted target: debug | release
:type target_platform: tuple[str,str]
:param attributes: attributes to add to namespace
:type attributes: str
:return: "property_groups" value
:rtype: str | 625941c792d797404e3041df |
def generate_initial_conditions(parameters): <NEW_LINE> <INDENT> graph_type = parameters.get('graph_type', 'small_world') <NEW_LINE> n_consumers = parameters['number_of_consumers'] <NEW_LINE> n_neighbors = parameters['number_of_neighbors'] <NEW_LINE> randomness = parameters['randomness'] <NEW_LINE> if graph_type == 'sm... | Initial conditions for the simulation
Create the graph on which the diffusion occurs and set additional
attributes for its node
`parameters` is a dictionary that contains the parameters that control
the evolution. | 625941c7dd821e528d63b1ff |
def size(self): <NEW_LINE> <INDENT> return sum([len(block) for block in self._data]) | Возвращает размер данных в контейнере | 625941c78a349b6b435e81c9 |
def gantt(chart, colors, title, bar_width, showgrid_x, showgrid_y, height, width, tasks=None, task_names=None, data=None, group_tasks=False): <NEW_LINE> <INDENT> if tasks is None: <NEW_LINE> <INDENT> tasks = [] <NEW_LINE> <DEDENT> if task_names is None: <NEW_LINE> <INDENT> task_names = [] <NEW_LINE> <DEDENT> if data is... | Refer to create_gantt() for docstring | 625941c78e05c05ec3eea3c9 |
def get_schedule_dict(input_string): <NEW_LINE> <INDENT> schedule_dict = {} <NEW_LINE> regex = r" ([0-9]+)\D([0-9]+)\ +([a-zA-Z]+)" <NEW_LINE> for match in re.finditer(regex, input_string): <NEW_LINE> <INDENT> h = match.group(1) <NEW_LINE> m = match.group(2) <NEW_LINE> w = match.group(3).lower() <NEW_LINE> if len(h) <=... | Creating dict.
:param input_string: | 625941c70a366e3fb873e86f |
def var_count(self, kind): <NEW_LINE> <INDENT> return sum(symbol['kind'] == kind for symbol in self.symbols) | returns the number of variables of the given kind already defined in the current scope | 625941c71f5feb6acb0c4ba7 |
def video_dir_to_frame_dir(video_dir, output_dir, suppress=False): <NEW_LINE> <INDENT> if os.path.exists(video_dir): <NEW_LINE> <INDENT> if os.path.isdir(video_dir): <NEW_LINE> <INDENT> contents = os.listdir(video_dir) <NEW_LINE> movies = [os.path.join(video_dir, cont) for cont in contents if cont.lower().endswith(".mo... | create a directory that contains subdirectories
that contain all of the frames of the movies contained
within the video_dir
args:
video_dir : directory with videos
output_dir : location to place the output frames
suppress (optional) : display output
returns:
imgs_captured : a list of image framenames ... | 625941c7566aa707497f45c0 |
def get_due_jobs(self, now): <NEW_LINE> <INDENT> curr_timestamp = datetime_to_utc_timestamp(now) <NEW_LINE> due_jobs = [] <NEW_LINE> for job_id, timestamp in self.job_run_time: <NEW_LINE> <INDENT> if timestamp is None or timestamp > curr_timestamp: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> job_info = self.job_info[... | Get due jobs.
:type now: datetime.datetime | 625941c76aa9bd52df036dfa |
def bisectpdf(a, up, below): <NEW_LINE> <INDENT> z = None <NEW_LINE> dl = 1.0e-6 <NEW_LINE> p = a[0] <NEW_LINE> if (p < 0 or p > 1): <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> up = up <NEW_LINE> low = below <NEW_LINE> mid = below + (up - below) * p <NEW_LINE> count = 1 <NEW_LINE> while (abs(up - low) > dl * mid)... | The function computes the cutoff value a such that the probabilty
of an observation from the given distribution, less than x, is a(0).
u and l are the upper and lower limits for x, respectively.
Parameters
----------
a : list or tuple
u : int
The upper limit for x.
l : int
The lower limit for x.
Returns
-----... | 625941c75e10d32532c5ef7d |
def update(self): <NEW_LINE> <INDENT> if self.check_same(): <NEW_LINE> <INDENT> os.chdir(self.options['location']) <NEW_LINE> self.git('fetch', ['origin', ]) <NEW_LINE> if 'rev' in self.options: <NEW_LINE> <INDENT> self.git('checkout', [self.ref, ]) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.install() ... | Update repository rather than download it again | 625941c7f7d966606f6aa059 |
def get_num_epoch(buffer_length=BUFFER_LENGTH, epoch_length=EPOCH_LENGTH, shift_length=SHIFT_LENGTH): <NEW_LINE> <INDENT> n_win_test = int(np.floor((buffer_length - epoch_length)*(epoch_length/shift_length))) <NEW_LINE> return n_win_test | Compute the number of epochs in "buffer_length"
:param buffer_length:
:param epoch_length:
:param shift_length:
:return: | 625941c7a17c0f6771cbe0a7 |
def __call__(self, corpus: str): <NEW_LINE> <INDENT> if self._use_fasttext: <NEW_LINE> <INDENT> corpus = corpus.replace('\n', '') <NEW_LINE> labels, scores = self._model.predict(corpus) <NEW_LINE> label = labels[0].replace("__label__", "") <NEW_LINE> return label, scores[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Parameters
----------
corpus
Input corpus
Returns
-------
lang_label
The ISO-639 1 code of the predicted language
score
The score of the prediction | 625941c7be7bc26dc91cd658 |
def WriteRawImage(self, mount_point, fn): <NEW_LINE> <INDENT> fstab = self.info["fstab"] <NEW_LINE> if fstab: <NEW_LINE> <INDENT> p = fstab[mount_point] <NEW_LINE> partition_type = common.PARTITION_TYPES[p.fs_type] <NEW_LINE> args = {'device': p.device, 'fn': fn} <NEW_LINE> if partition_type == "MTD": <NEW_LINE> <INDEN... | Write the given package file into the partition for the given
mount point. | 625941c716aa5153ce3624cf |
def get_cancel_url(self): <NEW_LINE> <INDENT> return self.cancel_url | Returns url to link to if they cancel. | 625941c73eb6a72ae02ec531 |
def parse_identifiers(self): <NEW_LINE> <INDENT> obj_index = 5 <NEW_LINE> tmp = self.data[obj_index].replace('Object ','').split('---') <NEW_LINE> simbad_ident = tmp[0].strip() <NEW_LINE> self.identifiers['MAIN_ID'] = simbad_ident <NEW_LINE> [l_start, l_end] = self.find_identifier_section() <NEW_LINE> for identifier in... | Parse the primary (Simbad) object identifier as well as
secondary identifiers of interest to us such as WDS, SAO, HD,
and the common name. | 625941c730bbd722463cbe1b |
def visu_loss_along_time(cpts, losses, loss_file_name) -> None: <NEW_LINE> <INDENT> fig, ax = plt.subplots(figsize=(16, 10)) <NEW_LINE> plt.cla() <NEW_LINE> ax.set_title('Loss Analysis', fontsize=35) <NEW_LINE> ax.set_xlabel('cpt', fontsize=24) <NEW_LINE> ax.set_ylabel('loss', fontsize=24) <NEW_LINE> ax.scatter(cpts, l... | Plots the evolution of the loss along time
:param cpts: step counter
:param losses: the successive values of the loss
:param loss_file_name: the file where to store the results
:return: nothing | 625941c757b8e32f524834f1 |
def __extractOriginFrom(self, path): <NEW_LINE> <INDENT> origin = path <NEW_LINE> if path.startswith( self.flashPlayerDataPath() + self.__sharedObjectDirName()): <NEW_LINE> <INDENT> origin = origin.replace( self.flashPlayerDataPath() + self.__sharedObjectDirName(), "") <NEW_LINE> if "/" in origin: <NEW_LINE> <INDENT> o... | Private method to extract the cookie origin given its file name.
@param path file name of the cookie file
@type str
@return cookie origin
@rtype str | 625941c7d268445f265b4ec4 |
def get_member_id_as_string(member): <NEW_LINE> <INDENT> pass | Get string representation of ``member`` ID. | 625941c7a8ecb033257d3124 |
def is_authenticated(self): <NEW_LINE> <INDENT> return True | Always return True. This is a way to tell if the user has been authenticated in templates. | 625941c7fb3f5b602dac36e8 |
def delete_credentials(self): <NEW_LINE> <INDENT> Credentials.credentials_list.remove(self) | delete_credentials method deletes a saved credential from the credentials_list | 625941c72eb69b55b151c904 |
def is_vlan_used_elsewhere(self, vlan, ifc): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> vlan = int(vlan) <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> vlan_ifcs = self.get_vlan_interfaces(exclude=ifc) <NEW_LINE> conflict_ifc = '' <NEW_LINE> for _ifc in vlan_ifcs: <... | Checks to see if a given vlan number is already in use.
Inputs:
vlan (int or str): vlan number.
ifc (str): Name of the interface to exclude from the check.
Returns: True or False | 625941c71b99ca400220ab08 |
def remove_all(link , value): <NEW_LINE> <INDENT> cur, next = link, link.rest <NEW_LINE> while next is not Link.empty: <NEW_LINE> <INDENT> if next.first == value: <NEW_LINE> <INDENT> cur.rest, next.rest = next.rest, Link.empty <NEW_LINE> next = cur.rest <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cur, next = next, ne... | Remove all the nodes containing value. Assume there exists some
nodes to be removed and the first element is never removed.
>>> l1 = Link(0, Link(2, Link(2, Link(3, Link(1, Link(2, Link(3)))))))
>>> print(l1)
<0 2 2 3 1 2 3>
>>> remove_all(l1, 2)
>>> print(l1)
<0 3 1 3>
>>> remove_all(l1, 3)
>>> print(l1)
<0 1> | 625941c7236d856c2ad4482f |
def setUp(self): <NEW_LINE> <INDENT> self.url = api_url() <NEW_LINE> requests.delete(self.url) <NEW_LINE> self.uuid = unicode(uuid.uuid1()) <NEW_LINE> self.simple_params = { 'from': self.uuid + 'example.com', 'to': 'www.example.com', } <NEW_LINE> self.http_params = { 'from': 'http://' + self.uuid + 'example.com', 'to':... | This method is run once before _each_ test method is executed | 625941c7d58c6744b4257cb7 |
def _download_photos(self, park_info): <NEW_LINE> <INDENT> keys = park_info.keys() <NEW_LINE> num_parks = len(keys) <NEW_LINE> park_index = 1 <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> photos = park_info[key]["photos"] <NEW_LINE> index = 0 <NEW_LINE> for url in photos: <NEW_LINE> <INDENT> if index > 3: <NEW_LINE> ... | # Download photos of the national park sites locally.
:param park_info: A dictionary containing park name, and other information (photos) as values in a dict.
:return: None | 625941c77b25080760e394b0 |
def _encode(self, doc: FeatureDocument) -> FeatureContext: <NEW_LINE> <INDENT> arr = self.torch_config.zeros(self._get_shape_for_document(doc)) <NEW_LINE> if logger.isEnabledFor(logging.DEBUG): <NEW_LINE> <INDENT> logger.debug(f'type array shape: {arr.shape}') <NEW_LINE> <DEDENT> sent: FeatureSentence <NEW_LINE> for si... | Encode tokens found in the container by aggregating the SpaCy vectorizers
output. | 625941c74e4d5625662d4430 |
@blueprint.route('/search') <NEW_LINE> def host_search_form(): <NEW_LINE> <INDENT> return redirect(url_for('.host_search', query=request.args.get('q'))) | Redirect to search results page | 625941c77d43ff24873a2cf7 |
def trace_info(self, msg, *args, **kwargs): <NEW_LINE> <INDENT> self.log(TRACE_INFO, msg, *args, **kwargs) | Log message with TRACE_INFO severity. | 625941c715baa723493c3fcb |
def test_deltree(self): <NEW_LINE> <INDENT> assert not os.system("rm -rf testfiles/output") <NEW_LINE> assert not os.system("cp -pR testfiles/deltree testfiles/output") <NEW_LINE> p = Path("testfiles/output") <NEW_LINE> assert p.isdir() <NEW_LINE> p.deltree() <NEW_LINE> assert not p.type, p.type | Test deleting a tree | 625941c7187af65679ca5175 |
def app_labels(apps_list): <NEW_LINE> <INDENT> if AppConfig is None: <NEW_LINE> <INDENT> return [app.split('.')[-1] for app in apps_list] <NEW_LINE> <DEDENT> return [AppConfig.create(app).label for app in apps_list] | Returns a list of app labels of the given apps_list, now properly handles
new Django 1.7+ application registry.
https://docs.djangoproject.com/en/1.8/ref/applications/#django.apps.AppConfig.label | 625941c776e4537e8c3516c8 |
def get_measures(self) -> List[Dict[str, Union[str, List[Dict[str, str]]]]]: <NEW_LINE> <INDENT> return deepcopy(GrowthAccountingView.default_measures) | Generate measures for the Growth Accounting Framework. | 625941c7d486a94d0b98e19c |
def cdf_curve(data): <NEW_LINE> <INDENT> sdata = sorted(data) <NEW_LINE> xdata, ydata = [], [] <NEW_LINE> len_xset = len(sdata) <NEW_LINE> for i,x in enumerate(sdata): <NEW_LINE> <INDENT> xdata.append(x) <NEW_LINE> ydata.append(i/len_xset) <NEW_LINE> <DEDENT> return [xdata, ydata] | Returns the cdf of a dataset credit to McMullen
input:
data - list of datapoints
output:
graphdata - [xdata, ydata] | 625941c767a9b606de4a7f11 |
def get_amp_stack(fits_files, amp, sigma=10, nx=10, ny=10, grow=2): <NEW_LINE> <INDENT> amp_stack = [] <NEW_LINE> for item in fits_files: <NEW_LINE> <INDENT> with fits.open(item) as hdus: <NEW_LINE> <INDENT> if sigma is None: <NEW_LINE> <INDENT> imarr = hdus[amp].data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> imarr... | Get a list of numpy arrays of pixel data for the specified amp.
Parameters
----------
fits_files: list
List of FITS filenames.
amp: int
Desired amp.
sigma: float [10]
Numer of standard deviations to use in sigma-clipping mask
applied to each frame. If None, then no masking will be
performed.
nx: i... | 625941c75e10d32532c5ef7e |
def test_redirect_POST(self): <NEW_LINE> <INDENT> response = RedirectView.as_view(url='/bar/')(self.rf.post('/foo/')) <NEW_LINE> self.assertEqual(response.status_code, 302) <NEW_LINE> self.assertEqual(response.url, '/bar/') | Default is a temporary redirect | 625941c77047854f462a1462 |
def classify(self): <NEW_LINE> <INDENT> ratings = {} <NEW_LINE> for header, column in self.data.items(): <NEW_LINE> <INDENT> scores = {} <NEW_LINE> for name, pipe in self.pipes.items(): <NEW_LINE> <INDENT> if pipe.classifier is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> scores[name] = pipe.rate(column) <NEW... | Classifies this pipeline's data.
Returns:
Dict[str => Dict[str => float]]: A dictionary of classification scores. | 625941c7656771135c3eb8c4 |
def get_all_script_lists(folder_path): <NEW_LINE> <INDENT> all_text = [] <NEW_LINE> for dirname in os.listdir(folder_path): <NEW_LINE> <INDENT> cur_path = os.path.join(folder_path,dirname) <NEW_LINE> for script in os.listdir(cur_path): <NEW_LINE> <INDENT> script_path = os.path.join(cur_path,script) <NEW_LINE> all_text... | :param folder_name:
:return: | 625941c745492302aab5e319 |
def __init__( self, *, public_ip_prefixes: Optional[List["ResourceReference"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ManagedClusterLoadBalancerProfileOutboundIPPrefixes, self).__init__(**kwargs) <NEW_LINE> self.public_ip_prefixes = public_ip_prefixes | :keyword public_ip_prefixes: A list of public IP prefix resources.
:paramtype public_ip_prefixes:
list[~azure.mgmt.containerservice.v2020_01_01.models.ResourceReference] | 625941c78a349b6b435e81ca |
@opcode <NEW_LINE> def UADDL2(cpu_context, instruction): <NEW_LINE> <INDENT> logger.debug("%s instruction not currently implemented.", instruction.mnem) | Unsigned add long (vector form) | 625941c744b2445a339320ed |
def get_diff_ratio(text1, text2): <NEW_LINE> <INDENT> if not text1: <NEW_LINE> <INDENT> text1 = "" <NEW_LINE> <DEDENT> if not text2: <NEW_LINE> <INDENT> text2 = "" <NEW_LINE> <DEDENT> if not isinstance(text1, basestring): <NEW_LINE> <INDENT> raise TypeError("Expected string, got %r instead" % type(text1)) <NEW_LINE> <D... | Compare two texts and return a floating point value between 0 and 1 with
the difference ratio, with 0 being absolutely different and 1 being
absolutely equal - the more similar the two texts are, the closer the ratio
will be to 1.
..note:
This function was taken from Golismero project: http://github.com/golismero/... | 625941c7f548e778e58cd5d4 |
def set_chi_prompt_mgxs(self, chi_prompt, temperature=ROOM_TEMPERATURE_KELVIN, nuclide='total', xs_type='macro', subdomain=None): <NEW_LINE> <INDENT> check_type('chi_prompt', chi_prompt, openmc.mgxs.Chi) <NEW_LINE> check_value('prompt', chi_prompt.prompt, [True]) <NEW_LINE> check_value('energy_groups', chi_prompt.energ... | This method allows for an openmc.mgxs.Chi to be used to set
chi-prompt for this XSdata object.
Parameters
----------
chi_prompt: openmc.mgxs.Chi
MGXS Object containing chi-prompt for the domain of interest.
temperature : float
Temperature (in units of Kelvin) of the provided dataset. Defaults
to 294K
nucli... | 625941c7d8ef3951e3243594 |
def empty(self) -> bool: <NEW_LINE> <INDENT> return self.stack.empty() | Returns whether the stack is empty. | 625941c701c39578d7e74e92 |
def q1(z): <NEW_LINE> <INDENT> return q1max*math.cos(math.pi/L*z) | Linear heat generation rate in the hot channel
Parameter:
----------
z: float, m; axial distance. z=0 is midplane
Returns:
--------
q': float, kW/m; linear generation rate | 625941c7507cdc57c6306d30 |
@utils.arg('id', metavar='<NAME or ID>', help=_('Name or ID of the stack containing the snapshots.')) <NEW_LINE> def do_snapshot_list(hc, args): <NEW_LINE> <INDENT> fields = {'stack_id': args.id} <NEW_LINE> try: <NEW_LINE> <INDENT> snapshots = hc.stacks.snapshot_list(**fields) <NEW_LINE> <DEDENT> except exc.HTTPNotFoun... | List the snapshots of a stack. | 625941c7cc40096d615959a8 |
def add_node(self, xml_this, txt, pos, feat_list): <NEW_LINE> <INDENT> oFirst = {'AdjP': 'adj', 'AdvP': 'adv', 'PP': 'adv'} <NEW_LINE> oSecond = {'Subj': 's', 'Objc': 'o', 'Cmpl': 'o'} <NEW_LINE> try: <NEW_LINE> <INDENT> ndx_node = self.pdx.add_xml_child(xml_this, self.tag_node, [atom("attribute", "class", pos)]) <NEW_... | Add a constituent node to [xml_this] in LOWFAT | 625941c7dc8b845886cb558b |
def init(self, session, ro_def): <NEW_LINE> <INDENT> loc_def = dict(ro_def) <NEW_LINE> doi = loc_def.pop('doi', "") <NEW_LINE> ResearchObject.init(self, session, loc_def) <NEW_LINE> self.doi = doi | Initialize this RO with a set of attributes
Args:
session (DBSession):
ro_def (dict): set of properties to initialize this RO
Returns:
None | 625941c77b180e01f3dc4856 |
def JourneyInput(): <NEW_LINE> <INDENT> journey = [] <NEW_LINE> NumberofJourney = int(input()) <NEW_LINE> for destination in range(NumberofJourney): <NEW_LINE> <INDENT> destination = input() <NEW_LINE> journey.append(destination) <NEW_LINE> <DEDENT> return journey | takes in the users input for their desired journey | 625941c78a43f66fc4b540bd |
def _render_loop(loop: Loop, render_measurements: bool,) -> Tuple[Waveform, List[MeasurementWindow]]: <NEW_LINE> <INDENT> waveform = to_waveform(loop) <NEW_LINE> if render_measurements: <NEW_LINE> <INDENT> measurement_dict = loop.get_measurement_windows() <NEW_LINE> measurement_list = [] <NEW_LINE> for name, (begins, l... | Transform program into single waveform and measurement windows.
The specific implementation of render for Loop arguments. | 625941c72c8b7c6e89b35818 |
def write_list_or_dict_into_csv(data, have_chinese=False, csv_path=None): <NEW_LINE> <INDENT> if type(data) not in {list, dict}: <NEW_LINE> <INDENT> raise ValueError('The type of the input data must ' 'be \'dict\' or \'list\'') <NEW_LINE> <DEDENT> if csv_path is None: <NEW_LINE> <INDENT> raise ValueError('csv_path shou... | Write the answer into a csv file
Inputs:
- data: A list or dict.
- have_chinese: True or False, whether the data contains chinese.
- csv_path: A string which contains the path to the csv file. | 625941c77d847024c06be311 |
@pytest.mark.rhel_testing <NEW_LINE> @pytest.mark.tier(2) <NEW_LINE> @pytest.mark.ignore_stream('upstream') <NEW_LINE> def test_appliance_console_backup_restore_db_local(request, two_appliances_one_with_providers): <NEW_LINE> <INDENT> appl1, appl2 = two_appliances_one_with_providers <NEW_LINE> appl1_provider_names = se... | Test single appliance backup and restore, configures appliance with providers,
backs up database, restores it to fresh appliance and checks for matching providers.
Polarion:
assignee: jhenner
casecomponent: Configuration
caseimportance: critical
initialEstimate: 1/2h | 625941c7bd1bec0571d90686 |
def get(self, storage_provider, storage_bucket_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self.s3_client.get_bucket_lifecycle_configuration(Bucket=storage_bucket_name) <NEW_LINE> Console.ok(json.dumps(result, indent=4, sort_keys=True)) <NEW_LINE> <DEDENT> except ClientError as error: <NEW_LINE> <INDEN... | Loads the lifecycle configuration defined for a bucket.
:param storage_provider: Name of the cloud service provider
:param storage_bucket_name: Name of the storage bucket
:exception: Exception
:returns: Result of operation as string | 625941c77d847024c06be312 |
def FirstNotRepeatingChar_2(self, s): <NEW_LINE> <INDENT> return s.index(list(filter(lambda c:s.count(c)==1,s))[0]) if s else -1 | 同上
:param s:
:return: | 625941c76fb2d068a760f0f3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.