code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def dutch_flag(colors): <NEW_LINE> <INDENT> green = 0 <NEW_LINE> first_color = 0 <NEW_LINE> last_color = len(colors) - 1 <NEW_LINE> while first_color <= last_color: <NEW_LINE> <INDENT> if colors[first_color] == 'red': <NEW_LINE> <INDENT> colors[green], colors[first_color] = colors[first_color]...
(list of str) -> list of str Returns colors rearranged so that the srings are in the color of the Dutch national flag.('Red','Green','Blue') >>> dutch_flag(['green','red','blue','green','red','green','blue','green','blue','green', 'blue','red','blue','red','green','green','green','green']) ['red', 'red', 'red', 'red...
625941e6e5267d203edce0d2
def remove_external_links(text): <NEW_LINE> <INDENT> return re.sub(r"\[([^]]+)\]", lambda m: m.group(1).split(" ")[-1], text)
外部リンクのマークアップを除去
625941e6be383301e01b58b8
def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return self.create(request, *args, **kwargs)
Records new activity with a user **Tags: profile, broker, usermodel **Examples .. code-block:: http POST /api/contacts/xia/activities/ HTTP/1.1 .. code-block:: json { "text": "Phone call", "account": null } responds .. code-block:: json { "text": "Phone call", "account":...
625941e6099cdd3c635f1093
def changecase(a): <NEW_LINE> <INDENT> if chr(a).isupper(): <NEW_LINE> <INDENT> return ord(chr(a).lower()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return ord(chr(a).upper())
Changes char case.
625941e6097d151d1a223292
def set_metadata(self,control,omi_popy): <NEW_LINE> <INDENT> import sys <NEW_LINE> import numpy as np <NEW_LINE> import time <NEW_LINE> self.logger.info('setting metadata values') <NEW_LINE> granule_id='{0}_{1}m{2}{3}_v{4}-{5}.nc'.format( control['Metadata']['L3prodID'][0], control['Metadata']['StartDate'][0][0:4], con...
Create metadata dictionary ARGS: config_params (dictionary containing control.txt info) omi_popoy (omi_popy object)
625941e6ab23a570cc2505c0
def __repr__(self): <NEW_LINE> <INDENT> return '<Actor "%s">' % (self.get('name'))
Representation of actor name.
625941e65fdd1c0f98dc0670
def OnClear(self,evt): <NEW_LINE> <INDENT> self.Clear()
Clear event handler
625941e68e05c05ec3eea7b3
def from_payload(self, payload): <NEW_LINE> <INDENT> self.session_id = payload[0] * 256 + payload[1] <NEW_LINE> len_node_ids = payload[2] <NEW_LINE> if len_node_ids > 20: <NEW_LINE> <INDENT> raise PyVLXException("command_send_request_wrong_node_length") <NEW_LINE> <DEDENT> self.node_ids = [] <NEW_LINE> for i in range(l...
Init frame from binary data.
625941e64a966d76dd55144e
def __normalizeSelected(self): <NEW_LINE> <INDENT> if self.__lhsSelected is not None and self.__rhsSelected is not None: <NEW_LINE> <INDENT> if self.__rhsSelected.date < self.__lhsSelected.date: <NEW_LINE> <INDENT> temp = self.__rhsSelected <NEW_LINE> self.__rhsSelected = self.__lhsSelected <NEW_LINE> self.__lhsSelecte...
Puts the earliest revision first
625941e63346ee7daa2b31aa
def _createLineItems(self): <NEW_LINE> <INDENT> titles = ["Data zajec", "Od", "Do", "Przedmiot", "Prowadzacy", "Sala", "Forma zajec"] <NEW_LINE> d = [] <NEW_LINE> font_size = 8 <NEW_LINE> centered = ParagraphStyle(name="centered", alignment=TA_CENTER) <NEW_LINE> for text in titles: <NEW_LINE> <INDENT> ptext = "<font si...
Create table with schedule
625941e6d164cc617578318a
def main(): <NEW_LINE> <INDENT> merge_temp_prec_dise_prod_data()
:return:
625941e6f9cc0f698b140a32
def call(self, event): <NEW_LINE> <INDENT> raise NotImplementedError()
In case that your :func:`match` function returned `True` this function will be called. It will again receive: :param event: an instance of the :class:`Event` class Now you are free to send data or do whatever you have to do.
625941e65510c4643540f814
def check_complete(self): <NEW_LINE> <INDENT> if self.process.poll() is None: <NEW_LINE> <INDENT> self._start_check_timer() <NEW_LINE> return <NEW_LINE> <DEDENT> self.stdout, self.stderr = (self._read_temp_file(self.stdout_file), self._read_temp_file(self.stderr_file)) <NEW_LINE> for temp_file in [self.stdout_file, sel...
Runs completion flow for this task if it's finished.
625941e64f6381625f114e76
def tsplot(df, uuid, trend=True, detrended=True, save_image=False): <NEW_LINE> <INDENT> fig = { 'data': [ { 'x': df['timepoint'], 'y': df["temperature"], 'name': "Temperature", 'opacity': 0.7, 'mode': 'lines+markers' } ], 'layout': { "title": uuid, 'xaxis': {'title': 'Date'}, 'yaxis': {'title': "Temperature"} } } <NEW_...
Parameters ---------- df: pandas DataFrame Output of function `hodrick_prescott`. uuid: str Experiment and case identifier. save_image: bool, optional Whether to download the figure as a static file. Returns ------- A long DataFrame containing the temperature, trend, and var...
625941e6283ffb24f3c55d38
def clone( self, name, clone_name, template_content=None, template_type=None): <NEW_LINE> <INDENT> self.search(name) <NEW_LINE> self.click(locators['job.template_dropdown'] % name) <NEW_LINE> self.click(locators['job.template_clone']) <NEW_LINE> self.assign_value(locators['job.template_name'], clone_name) <NEW_LINE> if...
Clones a given job template.
625941e6ff9c53063f47c62c
def resnext20_16x8d_cifar100(classes=100, **kwargs): <NEW_LINE> <INDENT> return get_resnext_cifar(classes=classes, blocks=20, cardinality=16, bottleneck_width=8, model_name="resnext20_16x8d_cifar100", **kwargs)
ResNeXt-20 (16x8d) model for CIFAR-100 from 'Aggregated Residual Transformations for Deep Neural Networks,' http://arxiv.org/abs/1611.05431. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default False Whether to load the pretrained weights for model. roo...
625941e61d351010ab855f56
def test_env_set_folded_none(self): <NEW_LINE> <INDENT> self.dbgfunc() <NEW_LINE> sname = 'env' <NEW_LINE> evname = 'UTIL_TEST' <NEW_LINE> newval = "one:\n two:\n three" <NEW_LINE> exp = re.sub("\n\s*", "", newval) <NEW_LINE> with U.tmpenv(evname, None): <NEW_LINE> <INDENT> cfg = hx.cfg.config() <NEW_LINE> cfg.add_...
TEST: set undefined environment variable from a folded [env] entry unconditionally EXP: the value gets set
625941e650812a4eaa59c758
def from_annotation(self, annotation, from_node, to_node): <NEW_LINE> <INDENT> if isinstance(annotation, SkeletonAnnotation): <NEW_LINE> <INDENT> annotation = EnhancedAnnotation(annotation) <NEW_LINE> <DEDENT> self.annotation = annotation <NEW_LINE> self.from_node = from_node <NEW_LINE> self.to_node = to_node <NEW_LINE...
Parameters ---------- annotation : EnhancedAnnotation object Annotation in which the path is defined from_node, to_node : SkeletonNode object First and last node in shortest path, respectively.
625941e6eab8aa0e5d26df94
def bit_reverse(list,clk): <NEW_LINE> <INDENT> N = len(list) <NEW_LINE> list = list[:] <NEW_LINE> br_indices = range(len(list)) <NEW_LINE> for i in downrange(len(list)): <NEW_LINE> <INDENT> k =0 <NEW_LINE> b = N>>1 <NEW_LINE> a = 1 <NEW_LINE> while b >= a: <NEW_LINE> <INDENT> if b & i: k = k | a <NEW_LINE> if a & i: k ...
reverses the order of bits in the list credit
625941e6dc8b845886cb5971
def __init__( self, class_spec, name, type_='string', label=None, short_label=None, index_type=None, label_width=80, content_width=None, display=True, details_display=True, grid_display=True, renderer=None, order=None, ): <NEW_LINE> <INDENT> self.class_spec = class_spec <NEW_LINE> self.name = name <NEW_LINE> self.type_...
TODO.
625941e6b5575c28eb68e43f
def post(events_dir, event): <NEW_LINE> <INDENT> _LOGGER.debug('post: %s: %r', events_dir, event) <NEW_LINE> ( _ts, _src, what, event_type, event_data, payload ) = event.to_data() <NEW_LINE> filename = '%s,%s,%s,%s' % ( time.time(), what, event_type, event_data ) <NEW_LINE> def _write_temp(temp): <NEW_LINE> <INDENT> if...
Post event to event directory.
625941e6090684286d50f126
def download_track(song_position): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> track = track_list.song_metadata[song_position] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> gui.show_error_message('No song selected') <NEW_LINE> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> client.get_recording(track....
download_track : given an index, download the track at that position in the track list
625941e6f7d966606f6aa444
def on_connection_open(self, _unused_connection): <NEW_LINE> <INDENT> LOGGER.info(f'Connection opened for {self.QUEUE}') <NEW_LINE> self.open_channel()
This method is called by pika once the connection to RabbitMQ has been established. It passes the handle to the connection object in case we need it. Parameters ---------- unused_connection : `pika.Connection` unused - required by the API
625941e69b70327d1c4e1212
def p_id_list(p): <NEW_LINE> <INDENT> if len(p) == 2: <NEW_LINE> <INDENT> p[0] = [p[1]] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = p[1] <NEW_LINE> p[0].append(p[3])
id_list : ID | id_list COMMA ID
625941e6009cb60464c637e9
def __init__(self): <NEW_LINE> <INDENT> self.covariance = None <NEW_LINE> self.parameters = [ 1.0, 1.0, 1.0, 1.0, 1.0 ]
Construct a GammaModel model object. The model object has a parameters vector that is specific to the functional form defined in the evaluate() method. We guess this vector at the time of initialization and let the upstream code use the getters and setters to override with better values.
625941e6f8510a7c17cf9b3a
def cluster_categories(distribution, exposure): <NEW_LINE> <INDENT> linkage = [cl for cl in sorted(exposure, key=lambda x: int(x))] <NEW_LINE> N = len(linkage) <NEW_LINE> categories = return_categories(distribution) <NEW_LINE> N_unit, N_class, N_tot = compute_totals(distribution, categories) <NEW_LINE> for cl in catego...
Perform hierarhical clustering on the intra-tract exposure values At each step of the aggregation, we look for the pair `(eta, \delta)` of categories that has the highest exposure (renormalised by the maximum possible value). We aggregate them in a new category `\gamma` whose exposure with the other categories `lph...
625941e626068e7796caf120
def call(self, x): <NEW_LINE> <INDENT> x_shape = x.get_shape() <NEW_LINE> offsets = super(ConvOffset2D, self).call(x) <NEW_LINE> offsets = self._to_bc_h_w_2(offsets, x_shape) <NEW_LINE> x = self._to_bc_h_w(x, x_shape) <NEW_LINE> x_offset = tf_batch_map_offsets(x, offsets) <NEW_LINE> x_offset = self._to_b_h_w_c(x_offset...
return the deformed featureed map
625941e623849d37ff7b34c7
def put_timeseries(self, timeseries, starttime=None, endtime=None, channels=None, type=None, interval=None): <NEW_LINE> <INDENT> IAGA2002Factory.write_file(self, self._stream, timeseries, channels)
Implements put_timeseries Notes: Calls IAGA2002Factory.write_file in place of IAGA2002Factory.get_timeseries. This can result in a non-standard IAGA2002 file, specifically one of longer then expected length.
625941e6498bea3a759b9ee9
def delete_version(self, project_id_or_key, _id): <NEW_LINE> <INDENT> return self._request( '/projects/{}/versions/{}'.format(project_id_or_key, _id), method='DELETE')
Deletes Version. :param str project_id_or_key: Project ID or Project Key :param int _id: Version のID :return: requests Response object :rtype: requests.Response
625941e6d6c5a10208144489
@_reap_children_on_err <NEW_LINE> def get_test_subprocess(cmd=None, **kwds): <NEW_LINE> <INDENT> kwds.setdefault("stdin", DEVNULL) <NEW_LINE> kwds.setdefault("stdout", DEVNULL) <NEW_LINE> kwds.setdefault("cwd", os.getcwd()) <NEW_LINE> kwds.setdefault("env", os.environ) <NEW_LINE> if WINDOWS: <NEW_LINE> <INDENT> kwds.se...
Creates a python subprocess which does nothing for 60 secs and return it as subprocess.Popen instance. If "cmd" is specified that is used instead of python. By default stdin and stdout are redirected to /dev/null. It also attemps to make sure the process is in a reasonably initialized state. The process is registered f...
625941e6f548e778e58cd9bb
def _set_routing_policy(self, v, load=False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass(v,base=routing_policy.routing_policy, is_container='container', yang_name="routing-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconf...
Setter method for routing_policy, mapped from YANG variable /routing_policy (container) If this variable is read-only (config: false) in the source YANG file, then _set_routing_policy is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_routing_policy() dir...
625941e6a05bb46b383ecc59
def __call__(self, response, handler): <NEW_LINE> <INDENT> if response.status_code == httplib.NOT_FOUND: <NEW_LINE> <INDENT> if response.scerror and response.scerror.code == "404-001": <NEW_LINE> <INDENT> logger.info("intercepted '404-001 Sensor Not Found' error and adding the sensor %s", self._sensor.name) <NEW_LINE>...
called for a request to doRequest
625941e615baa723493c43b4
def print_fizzbuzz(): <NEW_LINE> <INDENT> for i in range(1, 101): <NEW_LINE> <INDENT> if i % 15 == 0: <NEW_LINE> <INDENT> print('FizzBuzz') <NEW_LINE> <DEDENT> elif i % 3 == 0: <NEW_LINE> <INDENT> print('Fizz') <NEW_LINE> <DEDENT> elif i % 5 == 0: <NEW_LINE> <INDENT> print('Buzz') <NEW_LINE> <DEDENT> else: <NEW_LINE> <...
Return classic Fizz Buzz exercise.
625941e685dfad0860c3b297
def migrate(self, dconn, flags=0, dname=None, uri=None, bandwidth=0): <NEW_LINE> <INDENT> if dconn is None: dconn__o = None <NEW_LINE> else: dconn__o = dconn._o <NEW_LINE> ret = libvirtmod.virDomainMigrate(self._o, dconn__o, flags, dname, uri, bandwidth) <NEW_LINE> if ret is None:raise libvirtError('virDomainMigrate() ...
Migrate the domain object from its current host to the destination host given by dconn (a connection to the destination host). Flags may be one of more of the following: VIR_MIGRATE_LIVE Do not pause the VM during migration VIR_MIGRATE_PEER2PEER Direct connection between source & destination hosts VIR_MIGRA...
625941e68e71fb1e9831dbe3
def __init__(self, msg, exception=None): <NEW_LINE> <INDENT> self._msg = msg <NEW_LINE> self._exception = exception
Creates an exception. The message is required, but the exception is optional.
625941e6adb09d7d5db6cbc8
def SetFunctor(self, *args): <NEW_LINE> <INDENT> return _itkConstrainedValueAdditionImageFilterPython.itkConstrainedValueAdditionImageFilterIUC2IUC2IUC2_Superclass_SetFunctor(self, *args)
SetFunctor(self, itk::Functor::ConstrainedValueAddition<(unsigned char,unsigned char,unsigned char)> functor)
625941e6462c4b4f79d1db0b
def parse_date(datestring): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> tokens = list(map(str.strip, datestring.split())) <NEW_LINE> if len(tokens) >= 2: <NEW_LINE> <INDENT> date_parts = list(map(int, tokens[0].split('-'))) + [1, 1] <NEW_LINE> time_parts = list(map(int, tokens[1].split(':'))) + [0, 0, 0] <NEW_LINE> re...
Parse a date/time string in one of the formats listed below. Raises :py:class:`InvalidDate` when the date cannot be parsed. Supported date/time formats: - ``YYYY-MM-DD`` - ``YYYY-MM-DD HH:MM:SS`` :param datestring: The date/time string to parse. :returns: A tuple with the numbers ``(year, month, day, hour, minute, ...
625941e6460517430c3945b5
def axis_labels_from_ctype(ctype, unit): <NEW_LINE> <INDENT> ctype_short = ctype[:4] <NEW_LINE> labels = {'HGLN': f'Heliographic Longitude', 'CRLN': f'Carrington Longitude', 'HPLN': f'Helioprojective Longitude (Solar-X)', 'SOLX': f'Heliocentric X', 'HGLT': f'Latitude', 'CRLT': f'Latitude', 'HPLT': f'Helioprojective Lat...
Returns axis labels for the given coordinate type and unit. Parameters ---------- ctype : `str` Coordinate type. unit : `str`, `None` Required unit. If `None` no unit is added to the label. Returns ------- `str` "Axis Label [Unit]"
625941e645492302aab5e703
def __read_excel_data(self, selected_area, group_by): <NEW_LINE> <INDENT> logger.info('从源 Excel 文件中读取数据-开始') <NEW_LINE> try: <NEW_LINE> <INDENT> data = self.worksheet.range(selected_area).value <NEW_LINE> self.sheet_header = data[0] <NEW_LINE> for col_cell_list in data[1:]: <NEW_LINE> <INDENT> group_name = str(col_cell...
根据传入的 Excel 区域,从 Excel 文件中读取数据,并分组存放到一个字典中
625941e66fece00bbac2db7f
def __init__(self, nestedList): <NEW_LINE> <INDENT> self.data = self.flatten(nestedList) <NEW_LINE> l = len(nestedList) <NEW_LINE> for i in range(0, l): <NEW_LINE> <INDENT> nestedList[i] = self.data[i] <NEW_LINE> <DEDENT> nestedList.extend(self.data[i-1:]) <NEW_LINE> self.nestedList = nestedList
Initialize your data structure here. :type nestedList: List[NestedInteger]
625941e6b57a9660fec33cc5
def test_to_universal_rejects_non_date_arguments(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> times.to_universal('lol')
to_universal rejects non-date arguments
625941e6f9cc0f698b140a33
def save_image(widget, path, *, quality=-1): <NEW_LINE> <INDENT> pixmap = QtGui.QPixmap(widget.size()) <NEW_LINE> widget.render(pixmap) <NEW_LINE> success = pixmap.toImage().save(path, quality=quality) <NEW_LINE> if not success: <NEW_LINE> <INDENT> raise OSError(f'Cannot save image to {path!r}') <NEW_LINE> <DEDENT> ret...
Save a widget to an image file. Parameters ---------- widget : :class:`QtWidgets.QWidget` The widget to save as an image. path : :class:`str` The file path to save the image to. The image format is chosen based on the file extension. quality : :class:`int`, optional The quality factor. Must be in the r...
625941e6442bda511e8be84d
def increase_number(data, amount): <NEW_LINE> <INDENT> data.number = data.number + amount <NEW_LINE> new_text = 'The number is {}'.format(data.number) <NEW_LINE> data.number_label['text'] = new_text
Increases the number in the given Data object by the given amount and updates the Label in the given Data object that displays the number.
625941e6e8904600ed9f236f
def _test_scheme(self, scheme): <NEW_LINE> <INDENT> self.delete_user() <NEW_LINE> password = self.random_password() <NEW_LINE> db_path = "%s/%s/%s/private/sam.ldb" % (scheme, self.prefix, self.env) <NEW_LINE> try: <NEW_LINE> <INDENT> command = "samba-tool user create %s %s -H %s" % ( self.user, password,...
Ensure a user can be created by samba-tool with the supplied scheme and that that user can logon.
625941e6ff9c53063f47c62d
def __delitem__(self, attrib): <NEW_LINE> <INDENT> full_attrib = attrib <NEW_LINE> attrib_lang = ('%s|' % attrib).split('|') <NEW_LINE> attrib = attrib_lang[0] <NEW_LINE> lang = attrib_lang[1] or None <NEW_LINE> kwargs = {} <NEW_LINE> if lang and attrib in self.lang_interfaces: <NEW_LINE> <INDENT> kwargs['lang'] = lang...
Delete the value of a stanza interface using dict-like syntax. Example:: >>> msg['body'] = "Hi!" >>> msg['body'] 'Hi!' >>> del msg['body'] >>> msg['body'] '' Stanza interfaces are typically mapped directly to the underlyig XML object, but can be overridden by the presence of a ``del_attrib`` ...
625941e67c178a314d6ef8a2
def run_one(V, rank): <NEW_LINE> <INDENT> print("================= Rank = %d =================" % rank) <NEW_LINE> consensus = np.zeros((V.shape[1], V.shape[1])) <NEW_LINE> for i in range(50): <NEW_LINE> <INDENT> nmf = nimfa.Nmf(V, rank=rank, seed="random_vcol", max_iter=200, update='euclidean', objective='conn', conn_...
Run standard NMF on leukemia data set. 50 runs of Standard NMF are performed and obtained consensus matrix averages all 50 connectivity matrices. :param V: Target matrix with gene expression data. :type V: `numpy.ndarray` :param rank: Factorization rank. :type rank: `int`
625941e6baa26c4b54cb1557
def __call__(self, path) -> dict: <NEW_LINE> <INDENT> sample_dict = {} <NEW_LINE> for key, item in self._sample_ext.items(): <NEW_LINE> <INDENT> data_list = [] <NEW_LINE> for f in item: <NEW_LINE> <INDENT> data = self._sample_fn(os.path.join(path, f), **self._kwargs) <NEW_LINE> if (key in self._normalize) or (f in self...
Load sample from multiple files Parameters ---------- path : str defines patch to folder which contain the _sample_ext Returns ------- dict dict with data defines by _sample_ext
625941e629b78933be1e5ae2
def worker(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> self.flags['invalidate'].clear() <NEW_LINE> expiry = self.max_age <NEW_LINE> workspace, camera = self.backend <NEW_LINE> timeout = self.timeout <NEW_LINE> with self.lock: <NEW_LINE> <INDENT> for (i, j), rect, image in self.images: <NEW_LINE> <INDENT>...
main loop -- continually enqueue expired images and handle request timeouts
625941e656ac1b37e6264603
def GetEchoResponseData(echo_request_data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not echo_request_data: <NEW_LINE> <INDENT> raise ValueError('Invalid payload:%s' % echo_request_data) <NEW_LINE> <DEDENT> echo_request = EchoRequest() <NEW_LINE> echo_request.ParseAndInitialize(echo_request_data) <NEW_LINE> if C...
Verifies the echo_request_data and returns "echo response" message. It builds the EchoRequest object from the echo_request_data and then verifies the checksum of the EchoRequest is same as the calculated checksum of the payload. If the checksums don't match then it returns None. It checksums match, it builds the echo_...
625941e655399d3f05588af2
def lengthOfLIS(self, nums): <NEW_LINE> <INDENT> dp=[1]*len(nums) <NEW_LINE> res=0 <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> for j in range(i): <NEW_LINE> <INDENT> if nums[i]>nums[j]: <NEW_LINE> <INDENT> dp[i]=max(dp[i],dp[j]+1) <NEW_LINE> <DEDENT> <DEDENT> res=max(res,dp[i]) <NEW_LINE> <DEDENT> return ...
:type nums: List[int] :rtype: int
625941e64c3428357757c761
def getmilestone(self, id_, milestone_id): <NEW_LINE> <INDENT> request = requests.get(self.projects_url + "/" + str(id_) + "/milestones/" + str(milestone_id), headers=self.headers, verify=self.verify_ssl) <NEW_LINE> if request.status_code == 200: <NEW_LINE> <INDENT> return json.loads(request.content.decode("utf-8")) <N...
get an specific milestone :param id_: project id :param milestone_id: milestone id :return: the milestone
625941e671ff763f4b549ace
def description(self): <NEW_LINE> <INDENT> return "Plugin to provide pytest services for ox_herd."
Implement as required by OxPlugin.
625941e6a4f1c619b28b046b
@pytest.yield_fixture <NEW_LINE> def example_app(): <NEW_LINE> <INDENT> current_dir = os.getcwd() <NEW_LINE> project_dir = dirname(dirname(abspath(__file__))) <NEW_LINE> exampleapp_dir = join(project_dir, 'examples') <NEW_LINE> os.chdir(exampleapp_dir) <NEW_LINE> assert subprocess.call('./app-setup.sh', shell=True) == ...
Example app fixture.
625941e68a43f66fc4b5449c
def test_negative_integer(self): <NEW_LINE> <INDENT> self.assertEqual(max_integer([-1, -2, -5]), -1)
Test only negative integers
625941e67d847024c06be6fb
def Open(self,worksetsToOpen): <NEW_LINE> <INDENT> pass
Open(self: WorksetConfiguration,worksetsToOpen: IList[WorksetId])
625941e630dc7b7665901d9d
def game_loop(self): <NEW_LINE> <INDENT> comm.wait_ml_ready(self._ml_name) <NEW_LINE> while not quit_or_esc(): <NEW_LINE> <INDENT> scene_info = self._scene.get_scene_info() <NEW_LINE> command = self._make_ml_execute(scene_info) <NEW_LINE> scene_info.command = command <NEW_LINE> self._record_handler(scene_info) <NEW_LIN...
The main loop of the game in machine learning mode The execution order in the loop: 1. Send the SceneInfo to the machine learning process. 2. Wait for the key frame (During this period, machine learning process can process the SceneInfo and generate the GameInstruction.) 3. Check if there has a command to receive. ...
625941e6d7e4931a7ee9e35b
def check_number(number, name): <NEW_LINE> <INDENT> if number: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> number = int(number) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise BadRequest( detail="The '%s' must be an integer." % name, source_parameter="%s" % name ) <NEW_LINE> <DEDENT> if number < 1: <NE...
This method converts input to number if possible and check if is valid. :param number: input number, might be string :param name: name of the number :return: converted number
625941e6379a373c97cfaf82
def add_spent(self, destination, spent): <NEW_LINE> <INDENT> spent._id = self.push(spent.attrs, 'destinations', destination._id, 'spents')
Add a spent to the destination
625941e63eb6a72ae02ec924
def install_if_needed(self, packages): <NEW_LINE> <INDENT> LOG.info(_('Preparing Guest as Redis Server.')) <NEW_LINE> if not packager.pkg_is_installed(packages): <NEW_LINE> <INDENT> LOG.info(_('Installing Redis.')) <NEW_LINE> self._install_redis(packages) <NEW_LINE> <DEDENT> LOG.info(_('Redis installed completely.'))
Install redis if needed do nothing if it is already installed.
625941e6ad47b63b2c50a3bb
def raw_headers(self): <NEW_LINE> <INDENT> head = [] <NEW_LINE> head.append('%s %s\r\n' % (self.request_version, self.status)) <NEW_LINE> for header in self.response_headers: <NEW_LINE> <INDENT> head.append('%s: %s\r\n' % header) <NEW_LINE> <DEDENT> head.append('\r\n') <NEW_LINE> return ''.join(head)
Return the available headers as a string, used for low level socket handeling.
625941e67d43ff24873a30df
def main(argv: t.List[str]=sys.argv): <NEW_LINE> <INDENT> if len(argv) < 2: <NEW_LINE> <INDENT> usage_message(argv, additional_params='[var=value]') <NEW_LINE> <DEDENT> config_uri = get_config_uri(argv) <NEW_LINE> request = init_websauna(config_uri) <NEW_LINE> url = request.registry.settings.get('sqlalchemy.url') <NEW_...
Run pgcli shell on the database specified on the configuration file. :param argv: Command line arguments, second one needs to be the uri to a configuration file.
625941e6187af65679ca555c
def getCurrentTranslate(self): <NEW_LINE> <INDENT> return _osgSim.DOFTransform_getCurrentTranslate(self)
getCurrentTranslate(DOFTransform self) -> Vec3f
625941e67047854f462a1841
@register.assignment_tag <NEW_LINE> def get_latest_comments(**kwargs): <NEW_LINE> <INDENT> count = kwargs['count'] <NEW_LINE> query = Comment.objects.select_related( 'user', 'anonymous' ).order_by( '-timestamp' ) <NEW_LINE> return query[:count]
Select and return *count* latest discussion comments. Usage: {% get_latest_comments count=<int> as result %} Example: {% get_latest_comments count=10 as latest_comments %}
625941e68a43f66fc4b5449d
def _hash_digest(uin, ptwebqq): <NEW_LINE> <INDENT> N = [0, 0, 0, 0] <NEW_LINE> for t in range(len(ptwebqq)): <NEW_LINE> <INDENT> N[t % 4] ^= ord(ptwebqq[t]) <NEW_LINE> <DEDENT> U = ["EC", "OK"] <NEW_LINE> V = [0, 0, 0, 0] <NEW_LINE> V[0] = int(uin) >> 24 & 255 ^ ord(U[0][0]) <NEW_LINE> V[1] = int(uin) >> 16 & 255 ^ or...
计算hash,貌似TX的这个算法会经常变化,暂时不使用 get_group_list_with_group_code 会依赖此数据 提取自http://pub.idqqimg.com/smartqq/js/mq.js :param uin: :param ptwebqq: :return:
625941e64f88993c3716c49f
def byte_split(self, number, total_bytes): <NEW_LINE> <INDENT> negative = number < 0 and True or False <NEW_LINE> byte_form = number.to_bytes( total_bytes, byteorder='little', signed=negative, ) <NEW_LINE> return ["{0}".format(int(byte)) for byte in byte_form]
Converts and integer number into a defined length list of byte sized integers Used to convert a large number into 8 bit chunks so it can fit inside a C byte array. Little endian byte order is used.
625941e66e29344779a62a4c
def __hasDuplicateFiles(self): <NEW_LINE> <INDENT> last = None <NEW_LINE> for i in sorted(self.__srcfiles): <NEW_LINE> <INDENT> if i == last: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> last = i <NEW_LINE> <DEDENT> return False
检测self.__srcfiles(列表)中是否有重复的项目 self.__srcfiles是一个元素均为字符串的列表 返回值: True 有重复的项目 False 没有重复的项目
625941e68e05c05ec3eea7b4
def is_empty(queue): <NEW_LINE> <INDENT> if type(queue) is tuple: <NEW_LINE> <INDENT> t,q = queue <NEW_LINE> assert t == '__Queue__', 'Type Error: Expected __Queue__ but received '+t <NEW_LINE> return len(q) == 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert False, 'Type Error: Expected __Queue__ but received '+...
Purpose checks if the given queue has no data in it Pre-conditions: queue is a queue created by create() Return: True if the queue has no data, or false otherwise
625941e6d8ef3951e324397a
def read_message(self): <NEW_LINE> <INDENT> self._buffer.seek(0, os.SEEK_END) <NEW_LINE> buffer_size = self._buffer.tell() <NEW_LINE> if buffer_size < structures.MessageHeader.calcsize(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._buffer.seek(0, os.SEEK_SET) <NEW_LINE> header = structures.MessageHeader() <NEW...
This method is called inside the loop() method to receive a message from the stream (socket) and then deserialize it.
625941e66fece00bbac2db80
def choose(self, pvalues, outcome): <NEW_LINE> <INDENT> random.seed() <NEW_LINE> p = self.Vdataentry["parents"] <NEW_LINE> if (not p): <NEW_LINE> <INDENT> distribution = self.Vdataentry["cprob"] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pvalues = [str(outcome[t]) for t in self.Vdataentry["parents"]] <NEW_LINE> for ...
Randomly choose state of node from a probability distribution conditioned on parent values *pvalues*. This method has two parts: (1) determining the proper probability distribution, and (2) using that probability distribution to determine an outcome. Arguments: 1. *pvalues* -- An array containing the assigned sta...
625941e6377c676e912725e3
@pytest.mark.xfail <NEW_LINE> def test_message_disappeared_after_adding_product_to_basket(browser): <NEW_LINE> <INDENT> page = ProductPage(browser, link) <NEW_LINE> page.open() <NEW_LINE> page.add_product_to_basket() <NEW_LINE> page.should_be_disappeared_success_message()
Тест проверяет, что сообщение об успешном добавлении товара исчезает после появления
625941e61b99ca400220aef0
def set_voltage(self, volt_val): <NEW_LINE> <INDENT> if not self.mock_mode: <NEW_LINE> <INDENT> self.write(':SOUR:VOLT %f' % volt_val)
set the voltage for the output, does not turn output on
625941e6236d856c2ad44c1c
def imports() -> list: <NEW_LINE> <INDENT> _imports = [] <NEW_LINE> for name, val in globals().items(): <NEW_LINE> <INDENT> if isinstance(val, ModuleType): <NEW_LINE> <INDENT> _imports.append(val.__name__) <NEW_LINE> <DEDENT> <DEDENT> return _imports
List all imports
625941e6711fe17d8254279e
def find_email(bodystr, a): <NEW_LINE> <INDENT> lines = [l for l in bodystr.split('\r\n') if l.startswith(a)] <NEW_LINE> if len(lines) > 0: <NEW_LINE> <INDENT> words = [w for w in lines[0].split(' ') if '@' in w and len(w) > MIN_LEN_OF_VALID_EMAIL] <NEW_LINE> if len(words) > 0: <NEW_LINE> <INDENT> email = re.search(r'[...
入力を改行して最初の[From / To]から始まる行を見つけ、メールアドレスを抽出する
625941e60c0af96317bb8624
def fix_mileage(mileage): <NEW_LINE> <INDENT> if isinstance(mileage, float): <NEW_LINE> <INDENT> mileage_ = fix_mileage(str(mileage)) <NEW_LINE> <DEDENT> elif mileage and mileage != '0': <NEW_LINE> <INDENT> if '.' in mileage: <NEW_LINE> <INDENT> miles, yards = mileage.split('.') <NEW_LINE> if miles == '': <NEW_LINE> <I...
Fix mileage data (associated with an ELR). :param mileage: Network Rail mileage :type mileage: str or float :return: fixed mileage data in the conventional format used by Network Rail :rtype: str **Examples**:: >>> from pyrcs.utils import fix_mileage >>> fixed_mileage = fix_mileage(mileage=29.011) >>> f...
625941e6ac7a0e7691ed4500
def __init__(self, name=None): <NEW_LINE> <INDENT> self._name = None <NEW_LINE> if name is not None: <NEW_LINE> <INDENT> self.name = name
IoK8sApiCoreV1LocalObjectReference - a model defined in Swagger
625941e621bff66bcd684d8a
def verify_callback(self, origin_authorization, url, body, content_type='application/x-www-form-urlencoded'): <NEW_LINE> <INDENT> token = self.token_of_request(url, body, content_type) <NEW_LINE> authorization = 'QBox {0}'.format(token) <NEW_LINE> return origin_authorization == authorization
回调验证 Args: origin_authorization: 回调时请求Header中的Authorization字段 url: 回调请求的url body: 回调请求的body content_type: 回调请求body的Content-Type Returns: 返回true表示验证成功,返回false表示验证失败
625941e6b830903b967e9d43
def torso(height): <NEW_LINE> <INDENT> while height > 0: <NEW_LINE> <INDENT> print(' |-X-|') <NEW_LINE> height -= 1
This function will print out the avatar's torso. The length of the torso will change based on the variable passed into the function.
625941e6d268445f265b52ab
@register.inclusion_tag('blog_app/menu_tpl.html') <NEW_LINE> def show_menu(menu_class='menu', request=None): <NEW_LINE> <INDENT> categories = Categories.objects.annotate(cnt=Count('posts')).filter(cnt__gt=0) <NEW_LINE> return {'categories': categories, 'menu_class': menu_class, 'request': request}
Кастомный тег для вывода футера и хедера :param menu_class: аргумент, определяющий класс меню тега "div" в шаблоне :param request: для передачи данных о запросе пользователя
625941e63cc13d1c6d3c77b4
def queryIteration(self, qPi): <NEW_LINE> <INDENT> oldDominatingIndices = self.findRewardSetQuery(qPi) <NEW_LINE> oldEUS = self.computeEUS(qPi, oldDominatingIndices) <NEW_LINE> while True: <NEW_LINE> <INDENT> newQPi = [] <NEW_LINE> for piIdx in range(len(qPi)): <NEW_LINE> <INDENT> dominatedRewards = oldDominatingIndice...
iteratively improve one policy while fixing other policies in the query :return: local optimum policy query
625941e682261d6c526ab8e2
def _get_simple_var_xy(self, var, order='F', mode='r'): <NEW_LINE> <INDENT> if var in self.auxxyvars: <NEW_LINE> <INDENT> fsuffix = '_XY.aux' <NEW_LINE> idx = self.auxxyvars.index(var) <NEW_LINE> filename = self.file_root + fsuffix <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(('_get_simple_var_xy: var...
Reads a given 2D variable from the _XY.aux file
625941e6be383301e01b58ba
def maxArea(self, height): <NEW_LINE> <INDENT> start=0 <NEW_LINE> end=len(height)-1 <NEW_LINE> max_ar=0 <NEW_LINE> while start<end: <NEW_LINE> <INDENT> length=end-start <NEW_LINE> width=min(height[start],height[end]) <NEW_LINE> area=length*width <NEW_LINE> if area>max_ar: <NEW_LINE> <INDENT> max_ar=area <NEW_LINE> <DED...
:type height: List[int] :rtype: int
625941e6099cdd3c635f1095
def advance_row_check(self, address): <NEW_LINE> <INDENT> sq_1, sq_2 = {1, 2, 3} - {(ord(address[0]) - 97) // 3 + 1} <NEW_LINE> sq_1 = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]][sq_1 - 1] <NEW_LINE> sq_2 = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]][sq_2 - 1] <NEW_LINE> to_remove = [] <NEW_LINE> for nu...
need to be checked :param address: :return:
625941e6bde94217f3683229
def get_cro_day_playlist(station="radiozurnal", date: datetime.date=None): <NEW_LINE> <INDENT> url = "https://croapi.cz/data/v2/playlist/day/" <NEW_LINE> if date: <NEW_LINE> <INDENT> url += f"{date:%Y/%m/%d/}" <NEW_LINE> <DEDENT> url += f"{station}.json" <NEW_LINE> r = requests.get(url).json() <NEW_LINE> for i in r.get...
Download the playlist from CRo API for a day.
625941e6a219f33f34628da0
@pytest.mark.xfail <NEW_LINE> @pytest.mark.data_dir("external_target_project") <NEW_LINE> def test_target2(): <NEW_LINE> <INDENT> logging.info("Target set using context.") <NEW_LINE> with ProjectTree("p.gpr", context={"TARGET_NAME": "new-target"}) as tree: <NEW_LINE> <INDENT> assert tree.target == "new-target" <NEW_LIN...
Target test.
625941e6be7bc26dc91cda34
def open_spider(self, spider): <NEW_LINE> <INDENT> self.client = MongoClient(self.mongo_uri) <NEW_LINE> self.db = self.client[self.mongo_db] <NEW_LINE> self.generic_words = set([doc["_id"] for doc in self.db[self.generic_words_collection].find()])
Opens DB connection.
625941e6097d151d1a223294
def test_device_exclusion_logic_no_name(self): <NEW_LINE> <INDENT> self.run_check({'instances': [{'use_mount': 'yes', 'excluded_mountpoint_re': '^/run$', 'all_partitions': 'yes'}]}, mocks={'collect_metrics': lambda: None}, force_reload=True) <NEW_LINE> exclude_disk = self.check._exclude_disk_psutil <NEW_LINE> self.asse...
Same as above but with default configuration values and device='' to expose a bug in #2359
625941e601c39578d7e75278
def on_progress(self, *args): <NEW_LINE> <INDENT> sm = sum(args) <NEW_LINE> if sm != self._vars.last_progress: <NEW_LINE> <INDENT> self._vars.last_progress = sm <NEW_LINE> self.on_progress_change(*args) <NEW_LINE> <DEDENT> return None
pycurl on_progress callback gives progress statistics
625941e6be7bc26dc91cda35
def update(self): <NEW_LINE> <INDENT> virus_list = self.viruses <NEW_LINE> new_viruses = [] <NEW_LINE> for virus in self.viruses: <NEW_LINE> <INDENT> if virus.doesClear(): <NEW_LINE> <INDENT> self.viruses.remove(virus) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.population_density = self.getTotalPop() / self.max...
Update the state of the virus population in this patient for a single time step. update() should execute these actions in order: - Determine whether each virus particle survives and update the list of virus particles accordingly - The current population density is calculated. This population density value is u...
625941e6b5575c28eb68e440
def crypt_b(self, bigr: str) -> str: <NEW_LINE> <INDENT> first_x, first_y = self.alph1.index(bigr[0]) // 5, self.alph1.index(bigr[0]) % 5 <NEW_LINE> second_x, second_y = self.alph2.index(bigr[1]) // 5, self.alph2.index(bigr[1]) % 5 <NEW_LINE> if first_x == second_x: <NEW_LINE> <INDENT> first_y, second_y = second_y, fir...
Функция шифрования биграмм :param bigr: шифруемая биграмма :returns: зашифрованная биграмма
625941e63346ee7daa2b31ac
def load_config(self, config): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> od = config[blockNames.ConfigParams.output_dir] <NEW_LINE> self.output_dir = od <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> rod = config[blockNames.ConfigParams.raw_output_dir] <NEW...
Loads configuration in dict Loads configuration in dict Args: config_desc(dict): Desc dict
625941e685dfad0860c3b298
def output_feed(all_items, item_root, output_root, config): <NEW_LINE> <INDENT> feed = RssFeed(item_root, all_items[:config['num_items']], config) <NEW_LINE> with open(os.path.join(output_root, 'rss.xml'), 'w') as out_file: <NEW_LINE> <INDENT> feed.write(out_file, 'utf-8')
Produce an RSS feed of the items.
625941e694891a1f4081bee8
def find_max_height_sorted(boxes, index): <NEW_LINE> <INDENT> max_height = boxes[index][2] <NEW_LINE> for i in range(index + 1, len(boxes)): <NEW_LINE> <INDENT> if compatible(boxes[index], boxes[i]): <NEW_LINE> <INDENT> height = stacks[i] if i in stacks else find_max_height_sorted(boxes, i) <NEW_LINE> if height + boxes...
Function to calculate tallest possible stack Parameters ---------- boxes: list A list of boxes, sorted by height, where each box is represented as a tuple of (L,W,H) index: int Tallest stack possible using only boxes[index:]. Time Complexity --------------- O(N), where N is the number of boxes. Space Comple...
625941e64e4d5625662d480f
def _communicate_thread(self, input): <NEW_LINE> <INDENT> output = self._process.communicate(input) <NEW_LINE> cothread.Callback(self._communicate_callback, output)
Executes in separate OS thread. Wait for communication then return the output to the cothread context.
625941e6596a897236089ef8
def test_multi_payment_transaction(): <NEW_LINE> <INDENT> transaction = MultiPayment() <NEW_LINE> transaction.set_type_group(TRANSACTION_TYPE_GROUP.CORE) <NEW_LINE> transaction.set_nonce(1) <NEW_LINE> transaction.add_payment(1, 'AHXtmB84sTZ9Zd35h9Y1vfFvPE2Xzqj8ri') <NEW_LINE> transaction.add_payment(2, 'ATK14wxyYxbELq2...
Test if multi payment transaction gets built
625941e6e8904600ed9f2370
def set_weights(self, seeds, strength): <NEW_LINE> <INDENT> rands = [np.random.RandomState(s) for s in seeds] <NEW_LINE> for w, i in zip(self.weights, self.inits): <NEW_LINE> <INDENT> new_w = np.copy(i) <NEW_LINE> size = i.shape <NEW_LINE> for r in rands: <NEW_LINE> <INDENT> new_w += r.normal(0, strength, size=size) <N...
Sets the graph weights given a sequence of random seeds to do so. Reruns the initializer, reads the variable value, adds noise to it in numpy according to the provided seeds, strength, then directly loads the new value into the Variable. It is important that this function does not add ops to the graph. Args: see...
625941e697e22403b379d3d8
def GetForegroundValue(self): <NEW_LINE> <INDENT> return _itkBinaryStatisticsKeepNObjectsImageFilterPython.itkBinaryStatisticsKeepNObjectsImageFilterIUC3IUC3_GetForegroundValue(self)
GetForegroundValue(self) -> unsigned char
625941e68e7ae83300e4b40b
def find_app(app: str, *, symbol_by_name: Callable = symbol_by_name, imp: Callable = import_from_cwd, attr_name: str = 'app') -> AppT: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = symbol_by_name(app, imp=imp) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> val = imp(app) <NEW_LINE> <DEDENT> if isin...
Find app by string like ``examples.simple``. Notes: This function uses ``import_from_cwd`` to temporarily add the current working directory to :envvar:`PYTHONPATH`, such that when importing the app it will search the current working directory last. You can think of it as temporarily running wi...
625941e6435de62698dfe08a
def setup_font_styles(self): <NEW_LINE> <INDENT> self.title_font = QtGui.QFont() <NEW_LINE> self.title_font.setBold(True) <NEW_LINE> self.title_font.setPixelSize(15) <NEW_LINE> self.subtitle_font = QtGui.QFont() <NEW_LINE> self.subtitle_font.setPixelSize(12) <NEW_LINE> self.subtitle_font.setBold(True) <NEW_LINE> self.t...
Give settings for fonts to use in widget
625941e64e696a04525c988a
def grid_values(grid): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for box, val in zip(boxes, grid): <NEW_LINE> <INDENT> if val == ".": <NEW_LINE> <INDENT> result.append((box, cols)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result.append((box, val)) <NEW_LINE> <DEDENT> <DEDENT> return dict(result)
Convert grid into a dict of {square: char} with '123456789' for empties. Args: grid(string) - A grid in string form. Returns: A grid in dictionary form Keys: The boxes, e.g., 'A1' Values: The value in each box, e.g., '8'. If the box has no value, then the value will be '123456789'.
625941e6baa26c4b54cb1558
def _psplit(self): <NEW_LINE> <INDENT> nsplit_list = self._nsplit() <NEW_LINE> psplit_list = [ ] <NEW_LINE> for si in nsplit_list: <NEW_LINE> <INDENT> psplit_list.extend(si._ssplit()) <NEW_LINE> <DEDENT> return psplit_list
Split `self` at both north and south poles :return: A list of split StridedIntervals
625941e616aa5153ce3628b5