code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def romans_to_num(x): <NEW_LINE> <INDENT> roman = x[x.index('T') + 1:] <NEW_LINE> translate = {'I': 1, 'II': 2, 'III': 3, 'IV': 4} <NEW_LINE> if any(map(lambda y: roman == y, translate.keys())): <NEW_LINE> <INDENT> return x[:x.index('T')+1] + str(translate[roman]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return x | Reemplaza los numeros romanos del 1 al 4 por el caracter númerico.
----------
ej:
romans_to_num('II') == 2 | 625941d0a17c0f6771cbe1cb |
def check_auth(username, password): <NEW_LINE> <INDENT> return (username == current_app.config['rpcuser'] and password == current_app.config['rpcpassword']) | This function is called to check if a username /
password combination is valid. | 625941d08e7ae83300e4b148 |
def test_all_instruments(kiteconnect): <NEW_LINE> <INDENT> instruments = kiteconnect.instruments() <NEW_LINE> mock_resp = kiteconnect._parse_instruments(utils.get_response("market.instruments")) <NEW_LINE> utils.assert_responses(instruments, mock_resp) | Test mf instruments fetch. | 625941d0d268445f265b4fe9 |
def insert_journal_link(html_string, journal_name, issue, ln): <NEW_LINE> <INDENT> def replace_body(match_obj): <NEW_LINE> <INDENT> header = wjt.tmpl_admin_alert_header_html(journal_name, ln, issue) <NEW_LINE> return match_obj.group() + header <NEW_LINE> <DEDENT> return re.sub('<body.*?>', replace_body, html_string, 1) | Insert a warning regarding HTML formatting inside mail client and
link to journal page just after the body of the page.
@param html_string: the HTML newsletter
@param journal_name: the journal name
@param issue: journal issue for which the alert is sent (in the form number/year)
@param ln: language | 625941d0f8510a7c17cf9877 |
def _run_query(self, query: str, *values): <NEW_LINE> <INDENT> self.cursor.execute(query, values) <NEW_LINE> data = {} <NEW_LINE> data['columns'] = self.cursor.column_names <NEW_LINE> data['count'] = self.cursor.rowcount <NEW_LINE> data['id'] = self.cursor.lastrowid <NEW_LINE> data['rows'] = self.cursor.fetchall() <NEW... | Run query and fetch data | 625941d01d351010ab855c97 |
def print_versions(): <NEW_LINE> <INDENT> import numpy <NEW_LINE> import netCDF4 <NEW_LINE> import sys <NEW_LINE> print("-=" * 38) <NEW_LINE> print("SHyFT version: %s" % __version__) <NEW_LINE> print("NumPy version: %s" % numpy.__version__) <NEW_LINE> print("netCDF4 version: %s" % netCDF4.__version__) <NEW_LI... | Print all the versions for packages that SHyFT relies on. | 625941d09c8ee82313fbb8f1 |
def digGet(c): <NEW_LINE> <INDENT> pass | __NATIVE__
pPmObj_t pc = C_NULL;
pPmObj_t pr = C_NULL;
S8 chan;
PmReturn_t retval;
/* If wrong number of args, throw type exception */
if (NATIVE_GET_NUM_ARGS() != 1)
{
PM_RAISE(retval, PM_RET_EX_TYPE);
return retval;
}
/* Get the arg, throw exception if needed */
pc = NATIVE_GET_LOCAL(0);
if (OBJ_GET_TYPE(pc... | 625941d071ff763f4b549808 |
def defaultComment(self): <NEW_LINE> <INDENT> return "bash script composed by hex version %s on %s" % (__version__,str(datetime.now())) | Default comment string placed at the top of each script | 625941d007f4c71912b115fe |
def to_python(self, value): <NEW_LINE> <INDENT> if not value: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(value, str): <NEW_LINE> <INDENT> return int(Version(value, self.number_bits)) <NEW_LINE> <DEDENT> return Version(convert_version_int_to_string(value, self.number_bits), self.number_bits) | Verifies that value can be converted to a Version object | 625941d030dc7b7665901ae1 |
def searchInsert(self, nums, target): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> if nums[0] >= target: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> for i in range(1,len(nums)): <NEW_LINE> <INDENT> if nums[i] == target: <NEW_LINE> <INDENT> return i <NEW_LINE> <DEDENT> if target... | :type nums: List[int]
:type target: int
:rtype: int | 625941d0293b9510aa2c3411 |
def setFormula(self, sheet, row, column, formula, format=None): <NEW_LINE> <INDENT> raise NotImplementedError | same as setValue, but with formulas (with comma as argument separator and without leading '=' sign) | 625941d0796e427e537b0742 |
def test_validate_ip(self): <NEW_LINE> <INDENT> validate_ip('127.0.0.1') <NEW_LINE> validate_ip('::1') <NEW_LINE> self.assertRaises(ParamValidationError, validate_ip, 'test') | Test packstack.installer.validators.validate_ip. | 625941d0cdde0d52a9e531b0 |
def is_en_passant(self, move): <NEW_LINE> <INDENT> diff = abs(move.to_square - move.from_square) <NEW_LINE> if diff not in (7, 9): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self.pawns & BB_SQUARES[move.from_square]: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.occupied & BB_SQUARES[mov... | Checks if the given pseudo-legal move is an en-passant capture. | 625941d0d99f1b3c44c67709 |
def input_transform(upscale_factor=2, im_dim=DIM): <NEW_LINE> <INDENT> return Compose([ BlurTransform(), Resize(im_dim // upscale_factor), ToTensor(), ]) | Define transform for input data, i.e. blurred | 625941d060cbc95b062c66bf |
def read_header(script_file): <NEW_LINE> <INDENT> with open(script_file) as f: <NEW_LINE> <INDENT> script = f.read() <NEW_LINE> m = re.match(r'IMAGE_TEST\s*=\s*({.*})', script, re.DOTALL) <NEW_LINE> if m: <NEW_LINE> <INDENT> header = None <NEW_LINE> depth = 0 <NEW_LINE> for i, c in enumerate(m.group(1)): <NEW_LINE> <IN... | Check if script has a IMAGE_TEST dictionary defined at the top and return it's content. | 625941d0c4546d3d9de72bb0 |
def set_failed_state(self, err): <NEW_LINE> <INDENT> self.error = err <NEW_LINE> self.task.handle_job_results({'error': str(err)}) | Mark the job as failed from an exception that was thrown. | 625941d050485f2cf553cf16 |
def run(self): <NEW_LINE> <INDENT> self.world_comm.send( self.world_comm.rank, tag=WORKER_READY) <NEW_LINE> run_id, shuffle, strain, num_runs, k = self.world_comm.recv( source=0, tag=WORKER_JOB ) <NEW_LINE> self.k = k <NEW_LINE> if num_runs > 0: <NEW_LINE> <INDENT> run_log, gpu_sqs_msgs, data_sqs_msgs = ([],[],[]) <NEW... | Main logic, recieves from data master a strain,
whether to shuffle samples or not, and a
number of times to generate data.
Then generates the described matrices, uploads them to
s3, then sends the data descriptions to sqs for both the
data aggregation nodes and the gpu nodes.
It keeps a detai... | 625941d00a366e3fb873e996 |
def __init__(self, hass: HomeAssistant, client: JellyfinClient) -> None: <NEW_LINE> <INDENT> super().__init__(DOMAIN) <NEW_LINE> self.hass = hass <NEW_LINE> self.client = client <NEW_LINE> self.api = client.jellyfin <NEW_LINE> self.url = jellyfin_url(client, "") | Initialize the Jellyfin media source. | 625941d0dc8b845886cb56b1 |
def p_start(p): <NEW_LINE> <INDENT> pass | start : header definition | 625941d045492302aab5e440 |
def calculate_transition_cost(self, source_candidate, target_candidate): <NEW_LINE> <INDENT> raise NotImplementedError() | Should return transition cost from the source candidate to
the target candidate. | 625941d0de87d2750b85ff0f |
def set_secrets(self, secrets): <NEW_LINE> <INDENT> secret_set = False <NEW_LINE> for (plugin, secret) in secrets.items(): <NEW_LINE> <INDENT> if not isinstance(plugin, tuple) or len(plugin) != 3: <NEW_LINE> <INDENT> raise ValueError('got "%s" as secrets key, need 3-tuple' % plugin) <NEW_LINE> <DEDENT> if secret is not... | :param secrets: dict, {(plugin type, plugin name, argument name): secret name}
for example {('exit_plugins', 'sendmail', 'pdc_secret_path'): 'pdc_secret', ...} | 625941d094891a1f4081bc26 |
@passport_blue.route("/logout", methods=["GET", "POST"]) <NEW_LINE> def logout(): <NEW_LINE> <INDENT> session.pop("user_id", None) <NEW_LINE> session.pop("nick_name", None) <NEW_LINE> session.pop("mobile", None) <NEW_LINE> session.pop('is_admin', None) <NEW_LINE> return jsonify(errno=RET.OK, errmsg="退出登录成功") | 登出 | 625941d050812a4eaa59c49d |
def set_consumed(self, data): <NEW_LINE> <INDENT> if data is not None: <NEW_LINE> <INDENT> self._state = data.get(self._element) | set the consumer for the water reading | 625941d07cff6e4e81117b01 |
def name(self): <NEW_LINE> <INDENT> return _atsc_swig.atsc_field_sync_demux_sptr_name(self) | name(atsc_field_sync_demux_sptr self) -> std::string | 625941d0460517430c3942ff |
def _get_indentation(self): <NEW_LINE> <INDENT> if self._last_data is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> toks = self._last_data.splitlines() <NEW_LINE> if not toks or self._last_data[-1] in '\n\r': <NEW_LINE> <INDENT> toks.append('') <NEW_LINE> <DEDENT> if len(toks) == 1 and self._last_data_posit... | Returns the indentation of an opening or closing tag.
It works by storing the last data seen and checking that there are only
spaces in the last line.
Tabs are assumed to be equivalent to two spaces. | 625941d0187af65679ca529b |
def parse(self, xmlData): <NEW_LINE> <INDENT> doc = xml.dom.minidom.parseString(xmlData) <NEW_LINE> addons = {} <NEW_LINE> for addonElement in doc.getElementsByTagName('add-on'): <NEW_LINE> <INDENT> name = None <NEW_LINE> version = None <NEW_LINE> authors = [] <NEW_LINE> description = None <NEW_LINE> size = None <NEW_L... | Parse XML data and return name->info dictionary object | 625941d029b78933be1e5826 |
def next_parse(self,response): <NEW_LINE> <INDENT> if self.start_time: <NEW_LINE> <INDENT> li_list = response.css('div.articleList ul li') <NEW_LINE> for group in li_list: <NEW_LINE> <INDENT> datetime = group.css('a span.fr::text').extract_first() <NEW_LINE> if time.mktime(time.strptime(datetime,'%Y-%m-%d')) <= self.st... | 获取页面的 内容链接 列表 | 625941d0cc40096d61595acc |
def __add__(self, other): <NEW_LINE> <INDENT> if self.h != other.h or self.w != other.w: <NEW_LINE> <INDENT> raise (ValueError, "Matrices can only be added if the dimensions are the same") <NEW_LINE> <DEDENT> if not isinstance(other, Matrix): <NEW_LINE> <INDENT> raise (ValueError, "Paramter must be an instance of matri... | Defines the behavior of the + operator | 625941d0fbf16365ca6f6342 |
def get_axis_poise(self, ratio, axis_id, frame_id): <NEW_LINE> <INDENT> return _pycbf.cbf_handle_struct_get_axis_poise(self, ratio, axis_id, frame_id) | Returns : Float vector1,Float vector2,Float vector3,Float offset1,Float offset2,
Float offset3,Float angle
*args : Float ratio,String axis_id,String frame_id
C prototype: int cbf_get_axis_poise(cbf_handle handle, double ratio,
double * vector1, double * vector2, double * vector3,
... | 625941d07b180e01f3dc4978 |
def __init__(self, outer_index, inner_index): <NEW_LINE> <INDENT> if outer_index.batch_dims != inner_index.batch_dims: <NEW_LINE> <INDENT> raise ValueError("outer_index.batch_dims and inner_index.batch_dims " "must be the same.") <NEW_LINE> <DEDENT> super(ProductIndexMap, self).__init__( indices=(inner_index.indices + ... | Combines indices i and j into pairs (i, j). The result is an index where each segment (i, j) is the
intersection of segments i and j. For example if the inputs represent table cells indexed by respectively rows
and columns the output will be a table indexed by (row, column) pairs, i.e. by cell. The implementation
combi... | 625941d007f4c71912b115ff |
def main(): <NEW_LINE> <INDENT> args = parse_arguments() <NEW_LINE> dbgc = DebugConsole(args.color, args.verbose) <NEW_LINE> if not os.path.exists(args.dir) or not os.path.isdir(args.dir): <NEW_LINE> <INDENT> dbgc.fatal("Input directory does not exist: {}.", args.dir) <NEW_LINE> dbgc.fatal("Cannot read data - please en... | The application entry point.
:return: An exit code. | 625941d07c178a314d6ef5dd |
def check_minimum(path_to_file): <NEW_LINE> <INDENT> vib_dict = extract_vibrations(path_to_file) <NEW_LINE> vib_imag = [i for i in vib_dict.values() if i < 0.00] <NEW_LINE> if vib_imag == []: <NEW_LINE> <INDENT> is_minimum = True <NEW_LINE> print("No imaginary frequencies found. Structure is a minimum.") <NEW_LINE> <DE... | Returns a boolean value telling whether the structure is or is not a minimum. | 625941d07cff6e4e81117b02 |
def patch_fenced_rule(self): <NEW_LINE> <INDENT> config = self.getConfigs() <NEW_LINE> fenced = SuperFencesBlockPreprocessor(self.md) <NEW_LINE> fenced.config = config <NEW_LINE> fenced.extension = self <NEW_LINE> self.superfences[0]["formatter"] = fenced.highlight <NEW_LINE> self.md.preprocessors.register(fenced, "fen... | Patch Python Markdown with our own fenced block extension.
We don't attempt to protect against a user loading the `fenced_code` extension with this.
Most likely they will have issues, but they shouldn't have loaded them together in the first place :). | 625941d030bbd722463cbf42 |
def parse_instance_locally(self, path: str, instance_url: str or None = None) -> XbrlInstance: <NEW_LINE> <INDENT> if path.split('.')[-1] == 'xml' or path.split('.')[-1] == 'xbrl': <NEW_LINE> <INDENT> return parse_xbrl(path, self.cache, instance_url) <NEW_LINE> <DEDENT> return parse_ixbrl(path, self.cache, instance_url... | Parses a locally stored xbrl instance (either xbrl or ixbrl)
NOTE:
If the instance document or extension taxonomy have relative imports the parser will also search for those
files locally!
Example: your instance document is located at './data/aapl/2020/aapl-20200926.html' and the instance document
impor... | 625941d0cc0a2c11143dd00c |
def test_purchase_a_pet(self): <NEW_LINE> <INDENT> pet = self.get_pet("fido")[0] <NEW_LINE> resp = self.app.put( "/pets/{}/purchase".format(pet["_id"]), content_type="application/json" ) <NEW_LINE> self.assertEqual(resp.status_code, status.HTTP_200_OK) <NEW_LINE> resp = self.app.get( "/pets/{}".format(pet["_id"]), cont... | Purchase a Pet | 625941d01b99ca400220ac2d |
def forward(self, inputs): <NEW_LINE> <INDENT> if self.attention: <NEW_LINE> <INDENT> p3_out, p4_out, p5_out, p6_out, p7_out = self._forward_fast_attention(inputs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p3_out, p4_out, p5_out, p6_out, p7_out = self._forward(inputs) <NEW_LINE> <DEDENT> return p3_out, p4_out, p5_o... | 特征其实就是按照下面这张图进行组合的,组合的方式按照权重比例融合(attendtion),也可以等比例融合。
illustration of a minimal bifpn unit
P7_0 -------------------------> P7_2 -------->
|-------------| ↑
↓ |
P6_0 ---------> P6_1 ---------> P6_2 -------->
|-------------|--------------↑ ↑
... | 625941d0eab8aa0e5d26dcd4 |
def plant(self, value): <NEW_LINE> <INDENT> wrapper = self._value <NEW_LINE> wrappers = [] <NEW_LINE> if hasattr(wrapper, '_value'): <NEW_LINE> <INDENT> wrappers = [wrapper] <NEW_LINE> while isinstance(wrapper._value, ChainWrapper): <NEW_LINE> <INDENT> wrapper = wrapper._value <NEW_LINE> wrappers.insert(0, wrapper) <NE... | Return a clone of the chained sequence planting `value` as the
wrapped value.
Args:
value (mixed): Value to plant as the initial chain value. | 625941d08a349b6b435e82ef |
def test_scoped_within_course(self): <NEW_LINE> <INDENT> teams_per_topic = 10 <NEW_LINE> first_course_topics = self.setup_topics(num_topics=self.NUM_TOPICS, teams_per_topic=teams_per_topic) <NEW_LINE> duplicate_topic = first_course_topics[0] <NEW_LINE> second_course = CourseFactory.create( teams_configuration=TeamsConf... | Verify that team counts are scoped within a course. | 625941d029b78933be1e5827 |
def step(self, closure=None): <NEW_LINE> <INDENT> loss = None <NEW_LINE> if closure is not None: <NEW_LINE> <INDENT> loss = closure() <NEW_LINE> <DEDENT> if self.idx % self.n_pull == 0: <NEW_LINE> <INDENT> send_message(MessageCode.ParameterRequest, self.accumulated_gradients) <NEW_LINE> <DEDENT> lr = self.param_groups[... | Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss. | 625941d08a349b6b435e82f0 |
def ready(self): <NEW_LINE> <INDENT> autodiscover_collections('variables.collections') <NEW_LINE> autodiscover_collections('variables.collections.sites.%s' % settings.RUN_VER) <NEW_LINE> from pipeline.models import VariableModel <NEW_LINE> from pipeline.core.data.library import VariableLibrary <NEW_LINE> try: <NEW_LINE... | @summary: 注册公共部分和RUN_VER下的变量到数据库
@return: | 625941d0566aa707497f46e3 |
def get_color(self): <NEW_LINE> <INDENT> color = askcolor()[0] <NEW_LINE> if color: <NEW_LINE> <INDENT> hsbk = [min(c, 65535) for c in RGBtoHSBK(color)] <NEW_LINE> config["PresetColors"][self.preset_color_name.get()] = str(hsbk) | Present user with color palette dialog and return color in HSBK | 625941d010dbd63aa1bd2d20 |
def latch(self, open=False): <NEW_LINE> <INDENT> if self.DOOR_PIN: <NEW_LINE> <INDENT> GPIO.output(self.DOOR_PIN, open) <NEW_LINE> <DEDENT> if open : <NEW_LINE> <INDENT> print('OPEN') <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> print('CLOSE') | Open the latch when True | 625941d06fb2d068a760f21a |
def filter_waveform_trigger_true(self, signal_1, signal_2, param_1, param_2, param_3): <NEW_LINE> <INDENT> time.sleep(param_3 + 0.1) <NEW_LINE> ret_1, ret_2 = self.signal_processor.filter_waveform(signal_1, signal_2, param_1, param_2, param_3) <NEW_LINE> ret_1, ret_2 = self.signal_processor.filter_waveform(signal_1, re... | Called by test generators in test_filter_waveform_trigger_true | 625941d0167d2b6e31218d12 |
def GetFormatSpecification(self): <NEW_LINE> <INDENT> format_specification = specification.FormatSpecification( self.type_indicator) <NEW_LINE> format_specification.AddNewSignature( b'<Parallels_disk_image ', offset=0x27) <NEW_LINE> return format_specification | Retrieves the format specification.
Returns:
FormatSpecification: format specification or None if the format cannot
be defined by a specification object. | 625941d01f5feb6acb0c4ccc |
def _is_total_line(self, line): <NEW_LINE> <INDENT> return self._get_total_line() in line.lower() | Check if line has total anount of the check | 625941d0d8ef3951e32436ba |
def HybridRatio(line1, line2): <NEW_LINE> <INDENT> @hybrid_property <NEW_LINE> def hybridRatio(self): <NEW_LINE> <INDENT> if type(line1) == tuple: <NEW_LINE> <INDENT> myline1 = getattr(self, line1[0]) + getattr(self, line1[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> myline1 = getattr(self, line1) <NEW_LINE> <DEDE... | produces emission line ratio hybrid properties | 625941d00fa83653e4657137 |
def match(apikey, path, meta=DEFAULT_META, parse=True): <NEW_LINE> <INDENT> path = os.path.abspath(os.path.expanduser(path)) <NEW_LINE> try: <NEW_LINE> <INDENT> with audioread.audio_open(path) as f: <NEW_LINE> <INDENT> duration = f.duration <NEW_LINE> fp = fingerprint(f.samplerate, f.channels, iter(f)) <NEW_LINE> <DEDE... | Look up the metadata for an audio file. If ``parse`` is true,
then ``parse_lookup_result`` is used to return an iterator over
small tuple of relevant information; otherwise, the full parsed JSON
response is returned. | 625941d0d268445f265b4fea |
def create_room(room_type, room_name, dojo): <NEW_LINE> <INDENT> room_name_stripped = room_name.strip() <NEW_LINE> room_type_stripped = room_type.strip() <NEW_LINE> if len(room_type_stripped) == 0: <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> room_type_cleaned = room_type_stripped <NEW_LINE> if len(room_name... | input : room_type -> string represent type of room_type
room_name -> string represent name of room_name
output : returns -> return Room with name -> room_name
Raises -> TypeError if room_name exists
'Invalid name ' if room_name exists | 625941d063f4b57ef0001294 |
def aggregate( self, aggregation_pipeline: List[Any], projection_model: Optional[Type[FindQueryProjectionType]] = None, session: Optional[ClientSession] = None, ignore_cache: bool = False, **pymongo_kwargs, ) -> Union[ AggregationQuery[Dict[str, Any]], AggregationQuery[FindQueryProjectionType], ]: <NEW_LINE> <INDENT> s... | Provide search criteria to the [AggregationQuery](https://roman-right.github.io/beanie/api/queries/#aggregationquery)
:param aggregation_pipeline: list - aggregation pipeline. MongoDB doc:
<https://docs.mongodb.com/manual/core/aggregation-pipeline/>
:param projection_model: Type[BaseModel] - Projection Model
:param se... | 625941d085dfad0860c3afd7 |
def circle(t, r): <NEW_LINE> <INDENT> arc(t, r, angle=360) | Re writing circle to use arc | 625941d0dd821e528d63b325 |
def _change_incall_btn_states(self, pm_call_off=False): <NEW_LINE> <INDENT> self.btn_hangup.setEnabled(not pm_call_off) <NEW_LINE> self.btn_switch_camera.setEnabled(not pm_call_off) <NEW_LINE> if self.advanced_interface: <NEW_LINE> <INDENT> self.contacts_combobox.setEnabled(pm_call_off) <NEW_LINE> self.btn_call.setEnab... | Change btn states based on call status
pm_call_off True means call is not in progress | 625941d0a79ad161976cc2c2 |
def gradient_descent(f, init_x, lr=0.01, step_num=100): <NEW_LINE> <INDENT> x = init_x <NEW_LINE> for i in range(step_num): <NEW_LINE> <INDENT> grad = numerical_gradient(f, x) <NEW_LINE> x -= lr * grad <NEW_LINE> <DEDENT> return x | f: target function to optimize
init_x: initial value
lr: learning rate
step_num: repeat count for descent method | 625941d08e7ae83300e4b149 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_2I.pack(_x.x, _x.y)) <NEW_LINE> <DEDENT> except struct.error as se: self._check_types(se) <NEW_LINE> except TypeError as te: self._check_types(te) | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941d05510c4643540f55f |
def GetHistogram(self, *args): <NEW_LINE> <INDENT> return _itkLabelStatisticsImageFilterPython.itkLabelStatisticsImageFilterID3IUL3_GetHistogram(self, *args) | GetHistogram(self, unsigned long label) | 625941d091af0d3eaac9bb96 |
def __init__(self): <NEW_LINE> <INDENT> super(TaskMeasurements, self).__init__() <NEW_LINE> self.completed_time = None <NEW_LINE> self.created_time = None <NEW_LINE> self.merging_duration = None <NEW_LINE> self.merging_time = None <NEW_LINE> self.pending_merge_time = None <NEW_LINE> self.processed_time = None <NEW_LINE... | Initializes a task measurement. | 625941d05fc7496912cc3afa |
def set_progress_handler(self, progress_callback, n_instructions): <NEW_LINE> <INDENT> self.__conn.set_progress_handler(progress_callback, n_instructions) | callback for sqlite3.connection.set_progress_handler | 625941d031939e2706e4cfe6 |
def select_tag_elements(tags): <NEW_LINE> <INDENT> elements = [] <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> elements.extend(get_all_tag_elements(tag)) <NEW_LINE> <DEDENT> revit.get_selection().set_to(elements) | Select elements of the given tag.
Args:
tag (Tag): tag object | 625941d03c8af77a43ae391d |
def lanczos_resampling(arr, target_r, target_c): <NEW_LINE> <INDENT> origin_r = arr.shape[0] <NEW_LINE> origin_c = arr.shape[1] <NEW_LINE> s_r, s_c = get_sampling_scale(origin_r, origin_c, target_r, target_c) <NEW_LINE> arr_padded = np.pad(arr, ((2, 3), (2, 3), (0, 0)), 'edge') <NEW_LINE> output = np.ndarray([target_r,... | Lanczos Resampling method with a = 3
:param arr: input image
:param target_r: output image rows (height)
:param target_c: output image columns (width)
:return: output image | 625941d030c21e258bdfa61a |
@csrf_exempt <NEW_LINE> def update_project(request, project): <NEW_LINE> <INDENT> if not appsettings.ENABLE_HOOKS: <NEW_LINE> <INDENT> return HttpResponseNotAllowed([]) <NEW_LINE> <DEDENT> obj = get_project(request, project, True) <NEW_LINE> if appsettings.BACKGROUND_HOOKS: <NEW_LINE> <INDENT> thread = threading.Thread... | API hook for updating git repos. | 625941d0be383301e01b5601 |
def crossover(self, mate, debug=False): <NEW_LINE> <INDENT> midpoint = random.randrange(1, len(self.genome)-1) <NEW_LINE> new_genome = [] <NEW_LINE> for index in range(0, midpoint + 1): <NEW_LINE> <INDENT> new_genome.append(self.genome[index]) <NEW_LINE> <DEDENT> for dna in mate.genome: <NEW_LINE> <INDENT> if not dna i... | This function crosses the genome of self with
another given offspring and returns a new offspring.
The function picks a random midpoint and takes the genetic information
from before the midpoint in self's genome and combines it with the genetic
information of parent 2 after that midpoint. It then makes a new
offspring... | 625941d038b623060ff0af6a |
def menu_urls(real_localtz): <NEW_LINE> <INDENT> dd = "%d" % (real_localtz.day) <NEW_LINE> mm = "%d" % (real_localtz.month) <NEW_LINE> if len(dd) < 2: <NEW_LINE> <INDENT> dd = "0"+dd <NEW_LINE> <DEDENT> if len(mm) < 2: <NEW_LINE> <INDENT> mm = "0"+mm <NEW_LINE> <DEDENT> menus = ['menus/bplc/menu_'+mm+dd+'.htm','menus/b... | Returns a list of the URLs where the menus for Wellesley dining halls can be found.
Args:
real_localtz: A datetime object aware to the local timezone of America/New_York.
Returns:
A list of strings corresponding to the URL location of each of the Wellesley dining halls. | 625941d0bde94217f3682f6d |
def _test(self, check=False): <NEW_LINE> <INDENT> print("Just a test:") <NEW_LINE> if self.attack['doprint']: <NEW_LINE> <INDENT> self.pp.pprint(self.attack) <NEW_LINE> <DEDENT> return True | does nothing | 625941d00a50d4780f667010 |
def test_check_volume_signature(self): <NEW_LINE> <INDENT> test_source = unittest.source <NEW_LINE> if not test_source: <NEW_LINE> <INDENT> raise unittest.SkipTest("missing source") <NEW_LINE> <DEDENT> result = pyluksde.check_volume_signature(test_source) <NEW_LINE> self.assertTrue(result) | Tests the check_volume_signature function. | 625941d0b830903b967e9a87 |
def get_X_mtx(self): <NEW_LINE> <INDENT> return self.point_X_arr | Index mapping from the global array of coordinates. | 625941d0f7d966606f6aa181 |
def test_remove_connection(self): <NEW_LINE> <INDENT> connection = MagicMock() <NEW_LINE> connection.id = '123' <NEW_LINE> self.controller.connections = {connection.id: connection} <NEW_LINE> self.controller.remove_connection(connection) <NEW_LINE> self.assertEqual(self.controller.connections, {}) | Test remove_connection method. | 625941d08e71fb1e9831d925 |
def test_db_str_provided_db_string(self): <NEW_LINE> <INDENT> dbstr = 'sillyexample' <NEW_LINE> options = {'dbstring': dbstr,} <NEW_LINE> self.assertEqual(self.bhs._generate_db_str(options), dbstr) | Checks that if a dbstring is provided it will not be respected above
other options | 625941d0eab8aa0e5d26dcd5 |
def __init__(self): <NEW_LINE> <INDENT> self.RsgAsGroup = None <NEW_LINE> self.RequestId = None | :param RsgAsGroup: 资源组的伸缩组
:type RsgAsGroup: :class:`tencentcloud.tiems.v20190416.models.RsgAsGroup`
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str | 625941d0a4f1c619b28b01b4 |
def reservoir_sample(lines, sample_size, seed=None): <NEW_LINE> <INDENT> lines = (l.strip() for l in lines) <NEW_LINE> lines = iter(lines) <NEW_LINE> yield next(lines) <NEW_LINE> rnd = random.Random(seed) <NEW_LINE> buckets = [] <NEW_LINE> k = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> for i in range(sample_size): <NEW_LINE... | Performs reservoir sampling with given `sample_size`, and returns
generator containing sampled CSV.
Sampling with the same `seed` always yields the same result.
:param lines: list or generator of CSV rows
:param sample_size: sample size
:param seed: initial seed value for random function (default: random) | 625941d05510c4643540f560 |
def _check_get_metas_remove(self, ks): <NEW_LINE> <INDENT> keys = [KeyInfo('A', 1, 'meta1', 'wrap1', 0), KeyInfo('A', 1, 'meta1', 'wrap2', 0), KeyInfo('A', 1, 'meta2', 'wrap3', 0), KeyInfo('A', 1, 'meta2', 'wrap4', 0), KeyInfo('B', 1, 'meta1', 'wrap5', 0), KeyInfo('B', 1, 'meta1', 'wrap6', 0)] <NEW_LINE> ks.batch_inser... | Test interaction of get_metadatas and remove_revoked_keys
| 625941d0c432627299f04dc3 |
def get_attributes_and_headers(object, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if object.approved: <NEW_LINE> <INDENT> is_approved = 'Approved' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> is_approved = 'Not Approved' <NEW_LINE> <DEDENT> <DEDENT> except AttributeError as e: <NEW_LINE> <INDENT> print(e) ... | Returns a tuple with the desired values from objects and headings for the csv file
based on the instance type | 625941d023e79379d52ee6e0 |
def testNCCF(): <NEW_LINE> <INDENT> import nccf <NEW_LINE> testFile = 'baseline.1900-1909.salt_temp_e.nc' <NEW_LINE> dump(testFile) <NEW_LINE> print('======= dump finished') ; print() <NEW_LINE> T, d, a = nccf.readVar(testFile,'Temp',0,4,list(range(580,593)),list(range(40,50))) <NEW_LINE> print('T=',T) <NEW_LINE> print... | A simple test of writing a netcdf file | 625941d0f7d966606f6aa182 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(setStringResponse, self).__init__(*args, **kwds) <NEW_LINE> if self.setAnswer is None: <NEW_LINE> <INDENT> self.setAnswer = '' <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.setAnswer = '' | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
setAnswer
:param args: complete s... | 625941d0fb3f5b602dac3811 |
def show_year_info(year=None): <NEW_LINE> <INDENT> def year_info(i): <NEW_LINE> <INDENT> v = LUNAR_DATA[i] <NEW_LINE> year = i + LUNAR_DATA_START_YEAE <NEW_LINE> days = DAYS_OF_YEAR[year] <NEW_LINE> animal = ANIMALS[(year - 1900 ) % 12] <NEW_LINE> s = '%s%s%s(%s) %d%s: ' % (LUNAR_NAME, year, YEAR, animal, days , DAYS ... | show lunar year data info, to help check LUNAR_DATA right | 625941d073bcbd0ca4b2c1f3 |
@requires_data <NEW_LINE> @requires_fits <NEW_LINE> @pytest.mark.parametrize("infile", ["9774.pi", "3c273.pi"]) <NEW_LINE> def test_pha_mask_default(infile, make_data_path): <NEW_LINE> <INDENT> import sherpa.astro.io <NEW_LINE> pha = sherpa.astro.io.read_pha(make_data_path(infile)) <NEW_LINE> assert pha.mask | Make sure we have some tests (these may exist elsewhere) | 625941d03d592f4c4ed1d1e9 |
def totalHammingDistance(self, nums): <NEW_LINE> <INDENT> bits = [[0, 0] for _ in range(32)] <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> for i in range(32): <NEW_LINE> <INDENT> bits[i][num & 1] += 1 <NEW_LINE> num = num >> 1 <NEW_LINE> <DEDENT> <DEDENT> return sum(x * y for x, y in bits) | :type nums: List[int]
:rtype: int | 625941d0d7e4931a7ee9e09b |
def set_MinLength(self, value): <NEW_LINE> <INDENT> super(RandomWordsInputSet, self)._set_input('MinLength', value) | Set the value of the MinLength input for this Choreo. ((optional, integer) ?Minimum word length.) | 625941d0b57a9660fec33a02 |
def getVertices(self) -> numpy.ndarray: <NEW_LINE> <INDENT> return self._vertices | Get the array of vertices | 625941d07b25080760e395d6 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(BHandSpreadVelRequest, self).__init__(*args, **kwds) <NEW_LINE> if self.velocity is None: <NEW_LINE> <INDENT> self.velocity = 0. <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.velocity = 0. | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
velocity
:param args: complete se... | 625941d071ff763f4b549809 |
@vectorize( [float64(float64, float64, float64), float32(float32, float32, float32)], nopython=True, ) <NEW_LINE> def drhodt(s, t, p): <NEW_LINE> <INDENT> p = 0.1 * p <NEW_LINE> p2 = p * p <NEW_LINE> t2 = t * t <NEW_LINE> sqr = np.sqrt(s) <NEW_LINE> DRDT0 = ( eosJMDCFw[1] + 2 * eosJMDCFw[2] * t + (3 * eosJMDCFw[3] + 4 ... | Computes partial derivative of density with respect to potential temperature
using Jackett and McDougall 1995 polynomial [1]_.
Parameters
----------
s : array_like
practical salinity [psu (PSS-78)]
t : array_like
potential temperature [degree C (IPTS-68)];
same shape as s
p : array_like
pressure [dbar]... | 625941d07d43ff24873a2e1e |
def fitness(combo, attempt): <NEW_LINE> <INDENT> grade = 0 <NEW_LINE> for i, j in zip(combo, attempt): <NEW_LINE> <INDENT> if i == j: <NEW_LINE> <INDENT> grade += 1 <NEW_LINE> <DEDENT> <DEDENT> return grade | Compare items in 2 lists and count number of matches. | 625941d0ad47b63b2c50a0fd |
def stacktrace(test): <NEW_LINE> <INDENT> error_string = 'Traceback (most recent call last):' <NEW_LINE> strength = 1.0 <NEW_LINE> tags = ["APPLICATION_FAIL"] <NEW_LINE> slug = "STACKTRACE_PRESENT" <NEW_LINE> check_name = "STACKTRACE" <NEW_LINE> if not test.init_signals.ran_check(check_name): <NEW_LINE> <INDENT> resp =... | Checks if a stacktrace is returned by the response.
If a stacktrace is returned, attempts to identity if it was an
application failure or a server failure and return appropriate
tags.
returns a signal with the stacktrace slug.
:returns: SynSignal | 625941d03eb6a72ae02ec65c |
def isPalindrome(self, s): <NEW_LINE> <INDENT> if len(s) == 0: <NEW_LINE> <INDENT> return True; <NEW_LINE> <DEDENT> start = 0 <NEW_LINE> end = len(s)-1 <NEW_LINE> while start < end: <NEW_LINE> <INDENT> while self.getAscii(s[start]) == -1 and start < end: <NEW_LINE> <INDENT> start += 1 <NEW_LINE> <DEDENT> while self.get... | :type s: str
:rtype: bool | 625941d0e64d504609d749bd |
def getEdge(self, vertexIndex1, vertexIndex2): <NEW_LINE> <INDENT> Parameter.checkIndex(vertexIndex1, 0, self.vList.getNumVertices()) <NEW_LINE> Parameter.checkIndex(vertexIndex2, 0, self.vList.getNumVertices()) <NEW_LINE> if self.W[vertexIndex1, vertexIndex2]==0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> els... | Get the value of an edge, or None if no edge exists.
:param vertexIndex1: The index of the first vertex.
:type vertexIndex1: :class:`int`
:param vertexIndex2: The index of the second vertex.
:type vertexIndex2: :class:`int`
:returns: The value of the edge between the given vertex indices. | 625941d071ff763f4b54980a |
def resumeChart(instanceId): <NEW_LINE> <INDENT> if not instanceId: <NEW_LINE> <INDENT> raise KeyError("Invalid UUID string: {}".format(instanceId)) | Resumes a chart that was paused.
Steps which were previously paused will be resumed, and chart will
enter Resuming state.
Args:
instanceId: The ID of the chart instance to resume.
Raises:
KeyError: If the ID does not match any running chart instance. | 625941d001c39578d7e74fb9 |
def get_spatial_resolution_in_2D_as_BakerNayar(self, p, in_pixels = False, in_radians = True, use_spatial_resolution = True): <NEW_LINE> <INDENT> eta_cam = self.get_spatial_resolution_as_BakerNayar(p) <NEW_LINE> eta_cam_2D = np.sqrt(eta_cam) / convert_steradian_to_radian(1) <NEW_LINE> if use_spatial_resolution == False... | Spatial resolution (in 2D) for the conventional perspective camera using Baker & Nayar's equations
@param p: The ndarray of 3d point(s) of shape (rows, cols, vect_size) to compute the resolution at
Note: p must be given already transformed on the respective frame (e.g. when using mirror 2 it must be in the v... | 625941d03eb6a72ae02ec65d |
def command_binaries(options): <NEW_LINE> <INDENT> with session_scope() as session: <NEW_LINE> <INDENT> debcheck, repo, scan_suites = _create_debcheck(session, options.suite) <NEW_LINE> for suite in scan_suites: <NEW_LINE> <INDENT> issues = debcheck.depcheck_issues(suite) <NEW_LINE> _update_debcheck_issues(session, rep... | Check binary packages | 625941d007f4c71912b11600 |
def test_invalid_cell_type(self): <NEW_LINE> <INDENT> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> grapple.read_correction(self._test_file, cell_type='not_a_cell_type') | Should raise an exception when an invalid cell type is given | 625941d05e10d32532c5f0a4 |
def choose_office_random(dojo): <NEW_LINE> <INDENT> number_of_offices = len(dojo.office) <NEW_LINE> if number_of_offices > 0: <NEW_LINE> <INDENT> index = random.randrange(number_of_offices) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "NoRoomException" <NEW_LINE> <DEDENT> list_offices = list(dojo.office) <NEW_L... | choose an office at random | 625941d0d486a94d0b98e2c3 |
def p_patterns_empty(prod): <NEW_LINE> <INDENT> prod[0] = [] | _patterns : empty
_patterns_comma_trail : empty | 625941d0cad5886f8bd27157 |
def sinh(x): <NEW_LINE> <INDENT> x = DualNumber.promote(x) <NEW_LINE> output = exp(x)/2 - exp(-x)/2 <NEW_LINE> return output | Takes the hyperbolic sine of a DualNumber object and returns a DualNumber object with updated value and derivatives. | 625941d044b2445a33932213 |
def get_action_list_id(self): <NEW_LINE> <INDENT> return self._action_list_id | Return the id of the ActionList that is currently assigned to this MenuItem
If there is no ActionList assigned, returns null | 625941d015baa723493c40f3 |
def delete_institute(self, institute): <NEW_LINE> <INDENT> return | Institute was deleted. | 625941d0435de62698dfddcb |
def execute(self, context): <NEW_LINE> <INDENT> if not (1 <= self.count <= 0x7d0): <NEW_LINE> <INDENT> return self.do_exception(ModbusExceptions.IllegalValue) <NEW_LINE> <DEDENT> if not context.validate(self.function_code, self.address, self.count): <NEW_LINE> <INDENT> return self.do_exception(ModbusExceptions.IllegalA... | Run a read coils request against a datastore
Before running the request, we make sure that the request is in
the max valid range (0x001-0x7d0). Next we make sure that the
request is valid against the current datastore.
:param context: The datastore to request from
:returns: The initializes response message, exception... | 625941d050812a4eaa59c49e |
def getElement(*args, **kwargs): <NEW_LINE> <INDENT> pass | getElement(index) -> (uIndex, vIndex)
Returns the index'th element of the component as a tuple containing the
element's U and V indices. | 625941d0711fe17d825424e8 |
def check(self, *args): <NEW_LINE> <INDENT> return _yarp.Bottle_check(self, *args) | check(Bottle self, yarp::os::ConstString const & key) -> bool
check(Bottle self, yarp::os::ConstString const & key, yarp::os::ConstString const & comment) -> bool
check(Bottle self, yarp::os::ConstString const & key, Value fallback, yarp::os::ConstString const & comment="") -> Value
check(Bottle self, yarp::os::ConstSt... | 625941d0d18da76e23532654 |
def get_lcoe_for_node (results, node): <NEW_LINE> <INDENT> def get_fixed_costs (component, nv): <NEW_LINE> <INDENT> if nv is None: <NEW_LINE> <INDENT> nv = component.nominal_value <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return nv * component.fixed_costs <NEW_LINE> <DEDENT> except (AttributeError, TypeError): <NEW_... | Returns LCOE for current node split up into investment-, OPEX- and
"fuel"-LCOE. Thereby, investment, OPEX and "fuel" costs are calculated as
follows:
- Investment is calculated by multiplication of all investments
(input and output flow as well as node-internal investment) with their
correlated ep_costs.
- OPEX are der... | 625941d05f7d997b87174c16 |
def loadPixels(): <NEW_LINE> <INDENT> load_pixels() | Load a snapshot of the display window into the ``pixels`` Image.
This context manager loads data into the global ``pixels`` Image.
Once the program execution leaves the context manager, all changes
to the image are written to the main display. | 625941d05166f23b2e1a52d7 |
def add_plugin(self, plugin_identifier, config): <NEW_LINE> <INDENT> if not self.rows: <NEW_LINE> <INDENT> self.begin_row() <NEW_LINE> <DEDENT> if not self.rows[-1].cells: <NEW_LINE> <INDENT> self.begin_column() <NEW_LINE> <DEDENT> cell = self.rows[-1].cells[-1] <NEW_LINE> cell.plugin_identifier = force_text(plugin_ide... | Configure a plugin in the last row and cell of the layout.
If no rows or cells exist, one row and one cell is implicitly created.
This is internally used by `LayoutPartExtension`, but could just as well be
used to programmatically create layouts for whichever purpose.
:param plugin_identifier: Plugin identifier stri... | 625941d015baa723493c40f4 |
def loop_through_return_abs_file_path(looped_dir): <NEW_LINE> <INDENT> re_list = [] <NEW_LINE> if not os.path.isdir(looped_dir): <NEW_LINE> <INDENT> raise Exception("looped_dir: a directory.") <NEW_LINE> <DEDENT> for thing in os.listdir(looped_dir): <NEW_LINE> <INDENT> thing = os.path.join(looped_dir, thing) <NEW_LINE>... | function to loop through nested directories and return file absolute path in a list.
:param looped_dir:
:return: list | 625941d0091ae356686670db |
def run(): <NEW_LINE> <INDENT> env = Environment() <NEW_LINE> agent = env.create_agent(LearningAgent, learning=True, epsilon=1, alpha=0.01) <NEW_LINE> env.set_primary_agent(agent, enforce_deadline=True) <NEW_LINE> sim = Simulator(env, update_delay=0.01, log_metrics=True, optimized=True) <NEW_LINE> sim.run(n_test=100, t... | Driving function for running the simulation.
Press ESC to close the simulation, or [SPACE] to pause the simulation. | 625941d0627d3e7fe0d68fce |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.