code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def connect(self, callback, close_callback=None): <NEW_LINE> <INDENT> if self.status is not status.CLOSED: <NEW_LINE> <INDENT> raise AmqpStatusError('Connection status is %s' % self.status) <NEW_LINE> <DEDENT> self.status = status.OPENING <NEW_LINE> sock = socket.socket() <NEW_LINE> sock.setsockopt(socket.SOL_TCP, sock... | open the connection to the server | 625941e17d847024c06be65c |
def p_simple_selector_sequence2(p): <NEW_LINE> <INDENT> p[0] = p[1][0] <NEW_LINE> for extra in p[1][1:]: <NEW_LINE> <INDENT> p[0].append(extra) | simple_selector_sequence : repeatable_selector_sequence | 625941e1711fe17d82542700 |
def get_recipients(self, name): <NEW_LINE> <INDENT> to_str = self.render_string(self.data[name]) <NEW_LINE> formatted_emails = [ email.utils.formataddr(addr_pair) for addr_pair in email.utils.getaddresses([to_str]) ] <NEW_LINE> return [i for i in formatted_emails if i] | For example get_recipients('to') | 625941e166656f66f7cbc54a |
def __init__(self, master): <NEW_LINE> <INDENT> Frame.__init__(self, master) <NEW_LINE> master.minsize(width=500, height=200) <NEW_LINE> self.grid() <NEW_LINE> self.create_widgets() <NEW_LINE> self.number = random.randrange(MIN, MAX + 1) <NEW_LINE> self.tries = 0 | Initialize Frame. | 625941e1287bf620b61d3dff |
def test_string(self): <NEW_LINE> <INDENT> self.assertEquals( 2455242, chrono.calendar.Calendar.julian("2010", "2", "14") ) | Calendar.julian() accepts string input | 625941e1cad5886f8bd27376 |
def list( self, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> def internal_paging(next_link=None, raw=False): <NEW_LINE> <INDENT> if not next_link: <NEW_LINE> <INDENT> url = '/subscriptions/{subscriptionId}/providers/Microsoft.Network/routeFilters' <NEW_LINE> path_format_arguments = { 'subscr... | Gets all route filters in a subscription.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like in... | 625941e130c21e258bdfa83d |
def get_parquet_from_s3(bucket, keyname): <NEW_LINE> <INDENT> s3 = boto3.client('s3') <NEW_LINE> s3_response_object = s3.get_object(Bucket=bucket, Key=keyname) <NEW_LINE> df = s3_response_object['Body'].read() <NEW_LINE> df = pd.read_parquet(BytesIO(df)) <NEW_LINE> return df | get_parquet_from_s3 docstring | 625941e1a934411ee3751a32 |
def to_train_boolean_dataset(self, data, labels = None, batch_size = 16, buffer = 1e4): <NEW_LINE> <INDENT> data = self.to_train_dataset(data) <NEW_LINE> if labels: <NEW_LINE> <INDENT> assert isinstance(labels, dict), "Labels must be a dict" <NEW_LINE> assert len(labels) == 3, "Labels must have no/yes/neutral keys" <NE... | format pandas.DataFrame to create dataset for training BooleanQA
:param data: dataframe with question, context and answer
:param labels: dict of labels, by default {'no':0, 'yes':1, 'neutral':2}
:param batch_size: batch size
:param buffer: buffer for shuffle
:return: tensorflow dataset of (n, boolean_length) size
:rtyp... | 625941e1f548e778e58cd91d |
@task <NEW_LINE> def save(path, source, data_items=[]): <NEW_LINE> <INDENT> db = MongoClient(config.catalog_uri) <NEW_LINE> consol_data = consolidate(data_items) <NEW_LINE> sourcepath = os.path.join(path, 'WaterQuality', 'data') <NEW_LINE> call(['mkdir', '-p', sourcepath]) <NEW_LINE> urls = [] <NEW_LINE> host = get_hos... | Based function to all source imports in Download module | 625941e14e4d5625662d4770 |
def nonpruned_leaves(self): <NEW_LINE> <INDENT> if self.nodes() is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return [node for node in self.nodes() if node.is_leaf() and not node.abort] | Returns all the pruned leaves
in a tree
:return: Array of nodes | 625941e1097d151d1a2231f5 |
def create_new_submission_string( submission_string: str, run_id: str, swift_path: str, parameter_file_name: str ) -> str: <NEW_LINE> <INDENT> new_submission_string = ( submission_string.replace("$RUN_ID", run_id) .replace("$SWIFT_PATH", swift_path) .replace("$PARAMETER_FILE", f"{parameter_file_name}") ) <NEW_LINE> ret... | Uses the submission string read from file to create a copy which will contain
the input SWIFT usage parameters. | 625941e14d74a7450ccd4562 |
def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None): <NEW_LINE> <INDENT> assert {old_representation, new_representation} < {"storage", "editor", "view", "export_view"} <NEW_LINE> request_data = {"value": str(content_data), "representation": old_representation} ... | Converts between content body representations.
Not all representations can be converted to/from other formats. Supported conversions:
Source Representation | Destination Representation Supported
--------------------------------------------------------------
"storage" | "view","export_view","editor"
... | 625941e1507cdc57c6307080 |
def _warn_nearing_exceed_budget(self, budget: Budget, exceeded_percent: int) -> None: <NEW_LINE> <INDENT> print(f'[WARNING] You are about to exceed the {budget.name} budget! ' f'You went over {exceeded_percent}% of the total ' f'${budget.total_amount}.') | Issues a warning to the user that they are about to exceed this
budget.
:param budget: a Budget, the budget that they are about to
exceed
:param exceeded_percent: an int, the percent that they have
already exceeded
:return: None | 625941e107f4c71912b11822 |
def load_project(self, path): <NEW_LINE> <INDENT> xml_project.XmlProjectParser.load_project(path, self) | Initialise this project instance using the project file supplied
by path. | 625941e10a366e3fb873ebbb |
def __init__(self, key, **kwargs): <NEW_LINE> <INDENT> if "inst_cls" not in kwargs: <NEW_LINE> <INDENT> kwargs["inst_cls"] = DateTimeFieldInstance <NEW_LINE> <DEDENT> if "allow_none" not in kwargs: <NEW_LINE> <INDENT> kwargs["allow_none"] = False <NEW_LINE> <DEDENT> super().__init__(key, **kwargs) | Default Properties Overrided:
- ``allow_none`` - ``False``
- ``inst_cls`` - :class:`DateTimeFieldInstance`
.. seealso::
Check the document of :class:`BaseField` for other default properties.
.. note::
All time get from this field will be in UTC. | 625941e1b5575c28eb68e3a1 |
@asyncio.coroutine <NEW_LINE> def async_setup_platform(hass, config, async_add_devices, discovery_info=None): <NEW_LINE> <INDENT> import aiolifx <NEW_LINE> server_addr = config.get(CONF_SERVER) <NEW_LINE> lifx_manager = LIFXManager(hass, async_add_devices) <NEW_LINE> coro = hass.loop.create_datagram_endpoint( partial(a... | Setup the LIFX platform. | 625941e173bcbd0ca4b2c413 |
def summarize_report(self, df): <NEW_LINE> <INDENT> if len(df) == 0: <NEW_LINE> <INDENT> df = df.set_index( ['interaction', 'sequence', 'scribble_idx', 'object_id']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> df = df.groupby( ['interaction', 'sequence', 'scribble_idx', 'object_id']).mean() <NEW_LINE> <DEDENT> if 'fr... | Given a report it will reconstruct the missing entries and compute
a summarization of it.
# Arguments
df: Pandas DataFrame. The report to summarize.
# Returns
Dictionary: with different scores computed and the curve values | 625941e13617ad0b5ed68294 |
def save_config(self): <NEW_LINE> <INDENT> new_data_section = self.properties.local.data._replace(**self.previous_filename) <NEW_LINE> new_local_section = self.properties.local._replace( data=new_data_section, last_check=self.rpps_data.last_check_date ) <NEW_LINE> new_props = self.properties._replace(local=new_local_se... | Save configuration file with new processed files
:return: - | 625941e1a05bb46b383ecbbc |
def set_volume(ai_settings, sb): <NEW_LINE> <INDENT> if ai_settings.u_volume: <NEW_LINE> <INDENT> ai_settings.volume += 10 <NEW_LINE> if ai_settings.volume > 100: <NEW_LINE> <INDENT> ai_settings.volume = 30 <NEW_LINE> <DEDENT> <DEDENT> if ai_settings.d_volume: <NEW_LINE> <INDENT> ai_settings.volume -= 10 <NEW_LINE> if ... | 音量设置 | 625941e123849d37ff7b342a |
def add_user(self, items): <NEW_LINE> <INDENT> self.userList[items[1]] = items[0] | A method that adds the given user to memory
(or updates an existing user).
:param items: The username and IP, format (username, ip).
:type items: tuple or list | 625941e163f4b57ef00014ac |
def test_registration_form_m_ex(self): <NEW_LINE> <INDENT> form = RegisterForm(data=self.form_data) <NEW_LINE> self.assertFalse(form.is_valid()) | Test RegisterForm validation fails when email already exists. | 625941e1e5267d203edce036 |
def parser( subparsers: argparse._SubParsersAction, ) -> argparse.ArgumentParser: <NEW_LINE> <INDENT> login_parser: argparse.ArgumentParser = subparsers.add_parser( "login", help="Save a token for a GitLab instance" ) <NEW_LINE> login_parser.add_argument("--host", help="GitLab host (e.g invent.kde.org)", required=True)... | Subparser for login command
:param subparsers: subparsers object from global parser
:return: login subparser | 625941e1442bda511e8be7b1 |
def setup_platform(hass, config, add_entities, discovery_info=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> nearby_bulbs = avea.discover_avea_bulbs() <NEW_LINE> for bulb in nearby_bulbs: <NEW_LINE> <INDENT> bulb.get_name() <NEW_LINE> bulb.get_brightness() <NEW_LINE> <DEDENT> <DEDENT> except OSError as err: <NEW_L... | Set up the Avea platform. | 625941e1ab23a570cc250523 |
def test_retrieve_logs(self): <NEW_LINE> <INDENT> LogModels.Log.objects.create( time=timezone.now(), level=LogModels.LevelChoice.WARNING.value, message='Warning message body', details={ 'kwargs': {'k1': 'v1', 'k2': 'v2'}, 'exec_time': timezone.now().isoformat(), 'traceback': ['line1', 'line2'], } ) <NEW_LINE> LogModels... | Test retrieving logs | 625941e13c8af77a43ae3b41 |
def register(self, object_class, *args, **kwargs): <NEW_LINE> <INDENT> logging.info("Registering Plugin id: %s from class: %s " % (object_class.plugin_name, object_class)) <NEW_LINE> o = object_class <NEW_LINE> self.plugins.append(o) <NEW_LINE> self.plugins_dict[object_class.plugin_name] = o <NEW_LINE> def _d(fn): <NEW... | Registers a object with the plugin registry, typically used as a decorator.
:param object_class: the class to register as a plugin
Example:
.. doctest::
:options: +SKIP
>>> @libmarvin.plugin_registry.register
>>> class Foo(Plugin)
>>> ... | 625941e1ac7a0e7691ed4463 |
def prototype(self, nftol=[10, 50, 100, 200, 500], fftol=500): <NEW_LINE> <INDENT> if not os.path.isdir('prototypes'): <NEW_LINE> <INDENT> os.makedirs('prototypes') <NEW_LINE> <DEDENT> if isinstance(fftol, float) or isinstance(fftol, int): <NEW_LINE> <INDENT> fftol = [fftol] * len(nftol) <NEW_LINE> <DEDENT> nlines = []... | Function to compare multiple simplification distance tolerance values for the model nearfield.
Parameters:
-----------
nftol : list
Contains the tolerance values to be compared.
fftol : numeric
Single tolerance value to be used for the farfield in all comparisons.
Returns:
--------
A new directory called "pro... | 625941e166673b3332b9242f |
def test_user_update_with_custom_schema(self): <NEW_LINE> <INDENT> import ckan.logic.schema <NEW_LINE> user = factories.User() <NEW_LINE> mock_validator = mock.MagicMock() <NEW_LINE> schema = ckan.logic.schema.default_update_user_schema() <NEW_LINE> schema["id"].append(mock_validator) <NEW_LINE> helpers.call_action( "u... | Test that custom schemas passed to user_update do get used.
user_update allows a custom validation schema to be passed to it in the
context dict. This is just a simple test that if you pass a custom
schema user_update does at least call a custom method that's given in
the custom schema. We assume this means it did use... | 625941e126238365f5f0f211 |
def preorderTraversal(self, root): <NEW_LINE> <INDENT> visitlist = [] <NEW_LINE> waitlist = [] <NEW_LINE> while root or waitlist: <NEW_LINE> <INDENT> if root: <NEW_LINE> <INDENT> visitlist.append(root.val) <NEW_LINE> waitlist.append(root.right) <NEW_LINE> root = root.left <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r... | :type root: TreeNode
:rtype: List[int] | 625941e13317a56b86939fee |
@cli.command() <NEW_LINE> @click.argument('operation', type=click.Choice(["list", "purposes", "remove", "scan"]), default="list" ) <NEW_LINE> @click.argument('name', type=str, default="") <NEW_LINE> def storage(operation, name): <NEW_LINE> <INDENT> if operation == "purposes": <NEW_LINE> <INDENT> click.echo('; '.join(sc... | Manage storage. List your own storage & check mounted, remove them, or list possible purposes. | 625941e13317a56b86939fed |
def DrawButtonBarBackground(self, dc, wnd, rect): <NEW_LINE> <INDENT> self.DrawPartialPageBackground(dc, wnd, rect, True) | Draw the background for a :class:`~lib.agw.ribbon.buttonbar.RibbonButtonBar` control.
:param `dc`: The device context to draw onto;
:param `wnd`: The window which is being drawn onto (which will typically be
the button bar itself, though this is not guaranteed);
:param `rect`: The rectangle within which to draw. | 625941e1956e5f7376d71209 |
def draw(self,screen): <NEW_LINE> <INDENT> screen.blit(self.image,self.pos) | Draws the image on screen | 625941e1851cf427c661a8aa |
def __exit__(self, *args): <NEW_LINE> <INDENT> self.sock.close() | Context manager method for 'with' statements | 625941e123849d37ff7b342b |
def get_right_thumbstick_axis(self): <NEW_LINE> <INDENT> ax, ay = self._axes_mapping['right_thumbstick'] <NEW_LINE> ax_val = self._clip_range(self.getAxis(ax)) <NEW_LINE> ay_val = self._clip_range(self.getAxis(ay)) <NEW_LINE> return ax_val, ay_val | Get the axis displacement values of the right thumbstick.
Returns a tuple (X,Y) indicating thumbstick displacement between -1.0
and +1.0. Positive values indicate the stick is displaced right or up.
:return: tuple, zero centered X, Y values. | 625941e163b5f9789fde7484 |
def check_vector(self): <NEW_LINE> <INDENT> if self.current_vector == EAST: <NEW_LINE> <INDENT> if self.living_sprite(self.rightmost_col).rect.right >= self.window_size[0]: <NEW_LINE> <INDENT> self.current_vector = WEST <NEW_LINE> return SOUTH <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.current_vector <NE... | Helper function for update
Checks whether the formation can move in the current direction
if border collision will happen, returns a down-pointing vector
otherwise returns the current direction vector | 625941e17047854f462a17a3 |
def click_link_by_partial_text(self, partial_text): <NEW_LINE> <INDENT> return self.find_link_by_partial_text(partial_text).first.click() | Click in a link by partial content of its text.
Arguments:
partial_text (str): text of the element to click. | 625941e1d4950a0f3b08c6e8 |
def get_nat(nat_list:list)->list: <NEW_LINE> <INDENT> url = '' <NEW_LINE> r = requests.get(url) <NEW_LINE> return [] | 625941e1b545ff76a89141b3 | |
def open_new_set(): <NEW_LINE> <INDENT> with open('cambridge_dic.csv', 'r', encoding='utf-8') as english: <NEW_LINE> <INDENT> for line in english.readlines(): <NEW_LINE> <INDENT> word_sep = separate_slogs(line.rstrip(), vow='eng') <NEW_LINE> translit = transliterate_word(begin_end(word_sep)) <NEW_LINE> print(line.rstri... | Open and process the new set of data to transliterate | 625941e17b25080760e397f5 |
def exec_sacct_cmd(command, emonth, eyear, suffix, resultdir, execute): <NEW_LINE> <INDENT> emonth = str(emonth).zfill(2) <NEW_LINE> eyear = str(eyear).zfill(4) <NEW_LINE> filepath = os.path.join( resultdir, ("{0}-{1}-HPC-slurm-{2}.txt".format(eyear, emonth, suffix))) <NEW_LINE> if execute: <NEW_LINE> <INDENT> command ... | Execute sacct command
Arguments:
command {string} -- full sacct command
eyear {int} -- accounting end year
resultdir {string} -- location of output file
execute {boolean} -- if set, execute. otherwise just print
Returns:
string: -- output of the command | 625941e1498bea3a759b9e4c |
def test_detail_001(self): <NEW_LINE> <INDENT> r = self.obj.post1(row=23,data=DTtime1(23)) <NEW_LINE> self.assertEqual(r.status_code, 200) <NEW_LINE> self.assertEqual(r.json()['code'], "0") <NEW_LINE> self.assertEqual(r.json()['msg'], "操作成功") <NEW_LINE> print(r.text) | 短信发送详情 | 625941e1627d3e7fe0d691ef |
def invoke_dput(changes, args): <NEW_LINE> <INDENT> profile = dput.profile.load_profile(args.host) <NEW_LINE> check_modules(profile) <NEW_LINE> fqdn = None <NEW_LINE> if "fqdn" in profile: <NEW_LINE> <INDENT> fqdn = profile['fqdn'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fqdn = profile['name'] <NEW_LINE> <DEDENT>... | .. warning::
This method may change names. Please use it via :func:`dput.upload`.
also, please don't depend on args, that's likely to change shortly.
Given a changes file ``changes``, and arguments to dput ``args``,
upload a package to the archive that makes sense. | 625941e1be383301e01b581d |
def export_getSiteVO(self, siteName): <NEW_LINE> <INDENT> gLogger.info('getSiteVO') <NEW_LINE> vos = BESUtils.getSiteVO( siteName ) <NEW_LINE> return S_OK( vos ) | Returns the VO for the given site. | 625941e1596a897236089e5a |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, S3SettingsGlobalSettings): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e150812a4eaa59c6bc |
def save_user(self): <NEW_LINE> <INDENT> User.user_array.append(self) | save_user method saves user objects into user_array | 625941e13c8af77a43ae3b42 |
def remove_old( db, today=None ): <NEW_LINE> <INDENT> if today is None: <NEW_LINE> <INDENT> today= datetime.datetime.today().date() <NEW_LINE> <DEDENT> docs= [] <NEW_LINE> for r in db.view('status/all'): <NEW_LINE> <INDENT> object= r['value'] <NEW_LINE> published= datetime.datetime.strptime(object['date'],'%Y-%m-%d').d... | Remove old Route, RouteStop and Vehicle reports.
This should only be run once in a great while.
:return: sequence of {id:..., rev:..., ok:true} status responses. | 625941e1090684286d50f088 |
def check_topology(self, *args, **kwargs): <NEW_LINE> <INDENT> return _ruiy_swig.carrier_offset_sptr_check_topology(self, *args, **kwargs) | check_topology(carrier_offset_sptr self, int ninputs, int noutputs) -> bool | 625941e18e05c05ec3eea716 |
def get_data_path(): <NEW_LINE> <INDENT> path = os.path.join( os.path.dirname(__file__), __indicator_cpufreq_data_directory__) <NEW_LINE> abs_data_path = os.path.abspath(path) <NEW_LINE> if not os.path.exists(abs_data_path): <NEW_LINE> <INDENT> raise project_path_not_found <NEW_LINE> <DEDENT> return abs_data_path | Retrieve indicator-cpufreq data path
This path is by default <indicator_cpufreq_lib_path>/../data/ in trunk
and /usr/share/indicator-cpufreq in an installed version but this path
is specified at installation time. | 625941e132920d7e50b28571 |
def _alternate_is_lequal(self, i, j): <NEW_LINE> <INDENT> return j in self._leq_storage[i] | Return ``True`` if ``i`` is less than or equal to ``j`` in
``self``, and ``False`` otherwise.
.. NOTE::
If the :meth:`lequal_matrix` has been computed, then
:meth:`is_lequal` is redefined to use the cached data.
EXAMPLES::
sage: from sage.combinat.posets.hasse_diagram import HasseDiagram
sage: H = H... | 625941e1656771135c3ebc11 |
def __init__(self, body, seq=-1, **kwargs): <NEW_LINE> <INDENT> self.type = 'event' <NEW_LINE> self.event = 'stopped' <NEW_LINE> if body is None: <NEW_LINE> <INDENT> self.body = StoppedEventBody() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.body = StoppedEventBody(**body) if body.__class__ != StoppedEventBody e... | :param string type:
:param string event:
:param StoppedEventBody body:
:param integer seq: Sequence number. | 625941e176e4537e8c351a13 |
def readPowerAndValidate(self): <NEW_LINE> <INDENT> fullCode = self._write_and_read_serial("PM:PWS?\r") <NEW_LINE> splitCode = fullCode.split() <NEW_LINE> if len(splitCode) != 4: <NEW_LINE> <INDENT> raise ValueError("Returned improper value: {}".format(fullCode)) <NEW_LINE> <DEDENT> channelOne = {} <NEW_LINE> channelTw... | Read power and break down components. | 625941e1fb3f5b602dac3a35 |
def __init__(self, root, visualize=False, img_loader=pil_loader, crop_transform=None, img_transform=None, target_transform=None): <NEW_LINE> <INDENT> self.data = self._make_dataset(root, visualize) <NEW_LINE> self.image_as_item = visualize <NEW_LINE> self.img_loader = img_loader <NEW_LINE> self.crop_transform = crop_tr... | :param root:
:param visualize: If true, each item will be an image which may includes multiple person instances.
Otherwise, each item will be a person instance cropped from the original image. | 625941e15f7d997b87174e39 |
def download_thumbnail_from_another_instance(model_name, model_id): <NEW_LINE> <INDENT> from zou.app import app <NEW_LINE> with app.app_context(): <NEW_LINE> <INDENT> file_path = "/tmp/thumbnails-%s.png" % str(model_id) <NEW_LINE> path = "/pictures/thumbnails/%ss/%s.png" % (model_name, model_id) <NEW_LINE> try: <NEW_LI... | Download into the local storage the thumbnail for a given model instance. | 625941e1d10714528d600085 |
def get_available_letters(letters_guessed): <NEW_LINE> <INDENT> l = list(string.ascii_lowercase) <NEW_LINE> for letter in l: <NEW_LINE> <INDENT> for guess in letters_guessed: <NEW_LINE> <INDENT> if guess == letter: <NEW_LINE> <INDENT> l.remove(letter) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return ''.join(l) | letters_guessed: list (of letters), which letters have been guessed so far
returns: string (of letters), comprised of letters that represents which letters have not
yet been guessed. | 625941e18c3a87329515875d |
def calc_smpnafeff_timestamp(port_timestamp_sampleint, L0_dissgas_sampleint, gas_mode_sampleint, port_timestamp_sampleint_mcu, ph_meter_sampleint_mcu, inlet_temp_sampleint_mcu, massp_rga_initial_mass, massp_rga_final_mass, massp_rga_steps_per_amu, calibration_table): <NEW_LINE> <INDENT> mass_table = rga_status_process(... | This is a wrapper function to calculate the MASSP timestamp while in Nafion mode. | 625941e1d18da76e23532878 |
def response_content(self, url, request): <NEW_LINE> <INDENT> scheme, host, path, _, query, _ = urlparse(url.geturl()) <NEW_LINE> data_dirname = join(dirname(__file__), '..', '..', 'tests', 'data') <NEW_LINE> local_path = None <NEW_LINE> if (host, path) == ('www.carsonproperty.info', '/ArcGIS/rest/services/basemap/MapS... | Fake HTTP responses for use with HTTMock in tests.
| 625941e1566aa707497f4902 |
def rename(env): <NEW_LINE> <INDENT> return lambda x: x.update({k : x[v] for k,v in env}) or x | Return a lambda that adds some aliases specified by env | 625941e1ec188e330fd5ab37 |
def _create_cfgnode(self, sim_successors, call_stack, func_addr, block_id=None, depth=None): <NEW_LINE> <INDENT> sa = sim_successors.artifacts <NEW_LINE> syscall = None <NEW_LINE> is_syscall = False <NEW_LINE> if sim_successors.sort == 'SimProcedure': <NEW_LINE> <INDENT> is_simprocedure = True <NEW_LINE> if sa['is_sysc... | Create a context-sensitive CFGNode instance for a specific block.
:param simuvex.SimSuccessors sim_successors: The SimSuccessors object.
:param CallStack call_stack_suffix: The call stack.
:param int func_addr: Address of the current function.
:param BlockID block_id: ... | 625941e196565a6dacc8fa69 |
def testValidate_003(self): <NEW_LINE> <INDENT> config = LocalConfig() <NEW_LINE> config.mysql = MysqlConfig("user", "password", "gzip", True, None) <NEW_LINE> config.validate() | Test validate on a non-empty mysql section, all=True, databases=None. | 625941e156b00c62f0f149fa |
def create_dataset(training_set_distribution=0.98): <NEW_LINE> <INDENT> w_size = config.get_windows_size() <NEW_LINE> en_dict = preprocessing.Dictionary(config.get_data('embeddings-scaled.EMBEDDING_SIZE=25.txt')) <NEW_LINE> filename = os.path.join(os.path.dirname(__file__), 'data/AnnotatedKeywordsQuestions.txt') <NEW_L... | Function called when bootstraping to train the parser. | 625941e17c178a314d6ef804 |
def output(data, **kwargs): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if "output_indent" not in __opts__: <NEW_LINE> <INDENT> params.update(default_flow_style=False) <NEW_LINE> <DEDENT> elif __opts__["output_indent"] >= 0: <NEW_LINE> <INDENT> params.update(default_flow_style=False, indent=__opts__["output_indent"]) <N... | Print out YAML using the block mode | 625941e1a8370b7717052c3c |
def apply_weights(ads, category, weights): <NEW_LINE> <INDENT> clweights = list(weights.loc[:,category]) <NEW_LINE> weighted = ads.mul(clweights, axis="columns") <NEW_LINE> return weighted | Multiply the columns by the weights.
See: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mul.html#pandas.DataFrame.mul | 625941e107d97122c4178c32 |
def place_image_at(target_image, src_image, roi_mask, x_pos, y_pos): <NEW_LINE> <INDENT> rows, cols = roi_mask.shape <NEW_LINE> background_mask = cv2.bitwise_not(roi_mask) <NEW_LINE> roi = target_image[y_pos:(rows+y_pos), x_pos:(x_pos+cols)] <NEW_LINE> roi_background = cv2.bitwise_and(roi, roi, mask=background_mask) <N... | Patches `src_image` into the `target_image` at the location specified
by `x_pos` and `y_pos` on the pixels identified by the `roi_mask`
.. note::
This function overwrites the roi in target image. | 625941e1435de62698dfdfec |
def create_series(data): <NEW_LINE> <INDENT> cleaned = data.copy() <NEW_LINE> cleaned["session"] = None <NEW_LINE> same_session_threshold = datetime.timedelta(minutes=15) <NEW_LINE> activity_sessions = 0 <NEW_LINE> subjects = pd.unique(data["subject"]) <NEW_LINE> days = pd.unique(data["day"]) <NEW_LINE> for subject in ... | Takes the pandas dataframe and sets an activity_session id to each row
Activity session a successive series of activities
:param data:
:return: | 625941e171ff763f4b549a30 |
def _filespeedtest(): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> from pygmi.misc import getinfo <NEW_LINE> print('Starting') <NEW_LINE> pbar = ProgressBarText() <NEW_LINE> ifile = r"d:\Workdata\compress\New_max_22-55_iMNF15_ferriciron_UTM33s.tif" <NEW_LINE> ifile = r"d:\Downloads\caldefo_o_unwrap_go... | Test. | 625941e1a934411ee3751a33 |
def query_id(self, res_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> query = {'iid': int(res_id)} <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> query = {'_id': ObjId(res_id)} <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.response(400, 'Invalid id key.'... | This method configures the query that will find an object | 625941e18e7ae83300e4b36c |
def CosPositionAngle(self, *args): <NEW_LINE> <INDENT> return _stomp.AngularCoordinate_CosPositionAngle(self, *args) | CosPositionAngle(self, AngularCoordinate ang, Sphere sphere = Equatorial) -> double
CosPositionAngle(self, AngularCoordinate ang) -> double
CosPositionAngle(self, Pixel pix, Sphere sphere = Equatorial) -> double
CosPositionAngle(self, Pixel pix) -> double | 625941e1b5575c28eb68e3a2 |
@_as_safe_operation <NEW_LINE> def get_customer_created(stripe: stripeapi, customer_id: str) -> datetime: <NEW_LINE> <INDENT> timestamp = stripe.Customer.retrieve(customer_id).created <NEW_LINE> return datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.utc) | Gets the time when a customer was created | 625941e16e29344779a629af |
def nearidx(array, value): <NEW_LINE> <INDENT> n = [np.abs(i - value) for i in array] <NEW_LINE> idx = n.index(min(n)) <NEW_LINE> return idx | Find index of value in array closest to target.
No need for array to be sorted. | 625941e1d268445f265b520d |
def complete(self, collection, id_, data, force=False): <NEW_LINE> <INDENT> collection = self.managers['collection'].get_collection(collection) <NEW_LINE> fil = collection.get(id_) <NEW_LINE> if fil is None: <NEW_LINE> <INDENT> raise ValueError("File identifier not valid") <NEW_LINE> <DEDENT> for key, item in collectio... | Completes empty fields with the non empty keys from the new data.
If the requested file doesn't exists raises a ValueError Exception.
If force is set to True, overrides all the keys and not only the
empties. | 625941e15fdd1c0f98dc05d3 |
def split_entry(entry): <NEW_LINE> <INDENT> a = entry.split(':') <NEW_LINE> d = None <NEW_LINE> if entry.lower().startswith("d"): <NEW_LINE> <INDENT> d = True <NEW_LINE> a.pop(0) <NEW_LINE> <DEDENT> if len(a) == 2: <NEW_LINE> <INDENT> a.append(None) <NEW_LINE> <DEDENT> t, e, p = a <NEW_LINE> t = t.lower() <NEW_LINE> if... | splits entry and ensures normalized return | 625941e1bf627c535bc1356e |
def command_posix_integration(args): <NEW_LINE> <INDENT> handle_layout_messages(data_context().content.integration_messages) <NEW_LINE> inventory_relative_path = get_inventory_relative_path(args) <NEW_LINE> inventory_path = os.path.join(ANSIBLE_TEST_DATA_ROOT, os.path.basename(inventory_relative_path)) <NEW_LINE> all_t... | :type args: PosixIntegrationConfig | 625941e15fc7496912cc3d1d |
@blueprint.route("/refresh", methods=["POST"], strict_slashes=False) <NEW_LINE> def refresh(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> token = auth_service.renew_token(request.cookies.get("refreshToken")) <NEW_LINE> response = jsonify({"access_token": token.access_token}) <NEW_LINE> response.set_cookie( "refreshTo... | Returns access token in response body and sets refreshToken as an httpOnly cookie | 625941e116aa5153ce362816 |
def books_to_json(src_file, dst_file): <NEW_LINE> <INDENT> books = [] <NEW_LINE> with open(src_file) as src: <NEW_LINE> <INDENT> reader = csv.reader(src,delimiter=',') <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> print(row) <NEW_LINE> book = { 'title': row[0], 'author': row[1], 'genre': row[2], 'pages': int(row[3]... | CSV 데이터를 JSON 형태로 변환합니다. | 625941e1287bf620b61d3e00 |
def test_patch_detail_dont_update_related_without_permission(self): <NEW_LINE> <INDENT> resource = NoteResource() <NEW_LINE> note = Note.objects.create(author_id=1) <NEW_LINE> user = User.objects.get(pk=1) <NEW_LINE> self.assertEqual(user.password, 'this_is_not_a_valid_password_string') <NEW_LINE> request = MockRequest... | When fields are excluded the value of the field should not be set to a
default value if updated by bmga. | 625941e11f037a2d8b94659c |
def get_cases(self, source=None, recurse=False, flat=False): <NEW_LINE> <INDENT> if self._keys is None: <NEW_LINE> <INDENT> self.list_cases() <NEW_LINE> <DEDENT> if not source: <NEW_LINE> <INDENT> return [self.get_case(key) for key in self._keys] <NEW_LINE> <DEDENT> elif '|' in source: <NEW_LINE> <INDENT> if recurse an... | Get list of case names for cases in the table.
Parameters
----------
source : str, optional
If not None, only cases that have the specified source will be returned
recurse : bool, optional
If True, will enable iterating over all successors in case hierarchy
flat : bool, optional
If False and there are chil... | 625941e126068e7796caf083 |
def strip_colon(message): <NEW_LINE> <INDENT> return message.replace(':', '') | Remove the colons from the message | 625941e14428ac0f6e5bab93 |
@Wopi.app.route("/wopi/cbox/lock", methods=['GET', 'POST']) <NEW_LINE> @Wopi.metrics.counter('lock_by_ext', 'Number of /lock calls by file extension', labels={'open_type': lambda: (flask.request.args['filename'].split('.')[-1] if 'filename' in flask.request.args and '.' in flask.request.args['... | Lock a given filename so that a later WOPI lock call would detect a conflict.
Used for OnlyOffice as they do not use WOPI: this way better interoperability is ensured.
It creates a LibreOffice-compatible lock, which is checked by the WOPI lock call
as well as by LibreOffice.
Method: POST to create a lock, GET to query ... | 625941e1d164cc61757830ee |
def test_buffer(self): <NEW_LINE> <INDENT> mem = memoryview(self.p) <NEW_LINE> self.assertFalse(mem.readonly) <NEW_LINE> self.assertEqual(mem.format, 'ii') <NEW_LINE> self.assertEqual(mem.ndim, 1) <NEW_LINE> self.assertEqual(struct.unpack('ii', mem.tobytes()), (1, 2)) | supports the buffer protocol | 625941e1fff4ab517eb2f7dd |
def query_netcdf(filename, startdate, enddate, interval, parameter_netcdf, lat_N, lon_W, lat_S, lon_E, res_lat, res_lon, username, password, model=None, ens_select=None, interp_select=None, api_base_url=DEFAULT_API_BASE_URL, request_type='GET', cluster_select=None): <NEW_LINE> <INDENT> startdate = sanitize_datetime(sta... | Queries a netCDF file form the Meteomatics API and stores it in filename.
request_type is one of 'GET'/'POST' | 625941e121a7993f00bc8095 |
def main(): <NEW_LINE> <INDENT> setupLogger() <NEW_LINE> console().info("Started CCI ITN Trader v{}".format(config.VERSION)) <NEW_LINE> app = CCITrader() <NEW_LINE> try: <NEW_LINE> <INDENT> console().info("Connecting to TWS API at {}:{}. Client ID: {}" .format(config.HOST, config.PORT, config.CLIENTID)) <NEW_LINE> app.... | Setup Logging and Intialize Algo Trader | 625941e18c0ade5d55d3ed5d |
def analyseProcesses(self): <NEW_LINE> <INDENT> processes = [] <NEW_LINE> for i, line in enumerate(self.vm.processes[2:]): <NEW_LINE> <INDENT> lines = line.split() <NEW_LINE> if len(lines) < 2: continue <NEW_LINE> processes.append((lines[1], lines[2])) <NEW_LINE> <DEDENT> for name, isneed, policy, path in self.vmConf.p... | # vmConf.processes
:return: | 625941e16aa9bd52df037144 |
def apply(self, test, body, evaluation): <NEW_LINE> <INDENT> while test.evaluate(evaluation).is_true(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> evaluation.check_stopped() <NEW_LINE> body.evaluate(evaluation) <NEW_LINE> <DEDENT> except ContinueInterrupt: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except BreakInte... | While[test_, body_] | 625941e1f9cc0f698b140997 |
def before_get_object(self, view_kwargs): <NEW_LINE> <INDENT> if view_kwargs.get('role_id') is not None: <NEW_LINE> <INDENT> panel_perm = safe_query(self, PanelPermission, 'id', view_kwargs['role_id'], 'role_id') <NEW_LINE> if panel_perm.role_id is not None: <NEW_LINE> <INDENT> view_kwargs['id'] = panel_perm.role_id <N... | before get method for user object
:param view_kwargs:
:return: | 625941e16aa9bd52df037145 |
def reset(self) -> None: <NEW_LINE> <INDENT> self._to_use = self._to_use == False <NEW_LINE> self._masses = False <NEW_LINE> self._intensities = False <NEW_LINE> self.read_scans = [] | A method to reset the Spectrum object in its entirety. | 625941e18a349b6b435e8512 |
def test_write(self): <NEW_LINE> <INDENT> reader = ValueReader() <NEW_LINE> self.write({}) <NEW_LINE> del self.values['str'] <NEW_LINE> self.values['new_attr'] = 'new_val' <NEW_LINE> reader.write(self.filename, self.values) <NEW_LINE> filename = resolve_path(self.filename) <NEW_LINE> with open(filename, 'rt', encoding=... | Test `write()` | 625941e17cff6e4e81117d24 |
def test_csp_n_components(data): <NEW_LINE> <INDENT> csp = CSP(n_components=1) <NEW_LINE> csp.fit(data.X, data.y) <NEW_LINE> assert csp.weights_.shape[1] == 1 <NEW_LINE> Z = csp.transform(data.X) <NEW_LINE> assert Z.shape == (100, 1) | Test n_components parameter. | 625941e1cc40096d61595cee |
def should_succeed_json(self, args): <NEW_LINE> <INDENT> return json.loads(self.should_succeed(args)) | Runs the command-line with the given arguments. Raises an exception
if there was an error; otherwise, treats the stdout as JSON and returns
the data in it. | 625941e15e10d32532c5f2c4 |
def validate(self): <NEW_LINE> <INDENT> report = ValidationReport() <NEW_LINE> self.interchange.validate(report) <NEW_LINE> return report | Validate this document and return a validation report | 625941e121bff66bcd684cee |
def __call__(self, img, mask): <NEW_LINE> <INDENT> if random.random() < self.p: <NEW_LINE> <INDENT> img = cv2.flip(img, 1) <NEW_LINE> mask = cv2.flip(mask, 1) <NEW_LINE> <DEDENT> return img, mask | Args:
the image to be flipped
Returns:
flipped image | 625941e14527f215b584c7f2 |
def add(self, value): <NEW_LINE> <INDENT> if not self.created: <NEW_LINE> <INDENT> self.__create_group__() <NEW_LINE> <DEDENT> add_url = URL_ADD_RM_HOSTS.format(host_name=value, inventory_group=self.group_name) <NEW_LINE> response = self.ars_client.http_post(add_url, "", {}) <NEW_LINE> if response.status_code != 200: <... | Add a new host to the group
Create the Ansible Inventory group if it does not exist
: value : The host(string) to add | 625941e1851cf427c661a8ab |
def _get_phase(self): <NEW_LINE> <INDENT> value = api.GenGetPhase(self._handle) <NEW_LINE> library.check_last_status_raise_on_error() <NEW_LINE> return value | Current signal phase. | 625941e1236d856c2ad44b7e |
def getAgent(sess, agentID): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if(sess.mode == 'SAFE'): <NEW_LINE> <INDENT> tpfp = open(GA_UTIL_DIR+"/utilFiles/tmp"+str(sess.sessID)+"/dnaPool/dna" +str(agentID)+".dna", "rb") <NEW_LINE> agentObj = pickle.load(tpfp) <NEW_LINE> tpfp.close() <NEW_LINE> <DEDENT> else: <NEW_LINE>... | INPUT : Session object, agentID
OUTPUT : Agent object
DESCRIPTION : returns the agent in the current session
with its ID = agentID | 625941e1009cb60464c6374e |
def _display_active_widgets(self): <NEW_LINE> <INDENT> if not prefs['hide all'] and not (self.is_fullscreen and prefs['hide all in fullscreen']): <NEW_LINE> <INDENT> if prefs['show toolbar']: <NEW_LINE> <INDENT> self.toolbar.show_all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.toolbar.hide_all() <NEW_LINE> <DE... | Hide and/or show main window widgets depending on the current
state. | 625941e16fece00bbac2dae1 |
def __init__(self, root): <NEW_LINE> <INDENT> super().__init__(root) <NEW_LINE> self.grid() <NEW_LINE> """ Create widgets to get story information and to display story. """ <NEW_LINE> Label(self, text = "Coin War" ).grid(row = 0, column = 1, columnspan = 2, sticky = E + W) <NEW_LINE> Button(self, text = "Click for rule... | Initialize Frame. | 625941e130dc7b7665901d01 |
def crosstab(col1, col2): <NEW_LINE> <INDENT> col1 = np.array(col1) <NEW_LINE> col2 = np.array(col2) <NEW_LINE> col1_unique = np.unique(col1) <NEW_LINE> col2_unique = np.unique(col2) <NEW_LINE> crosstab_rows = [] <NEW_LINE> for col1_val in col1_unique: <NEW_LINE> <INDENT> loc_col1_val = np.where(col1==col1_val)[0] <NEW... | Makes a crosstab of col1 and col2. This is represented as a
structured array with the following properties:
1. The first column is the value of col1 being crossed
2. The name of every column except the first is the value of col2 being
crossed
3. To find the number of cooccurences of x from col1 and y in col2,
fi... | 625941e16fece00bbac2dae2 |
def set_prismatic(joint, lower, upper): <NEW_LINE> <INDENT> bpy.ops.pose.constraint_add(type='LIMIT_LOCATION') <NEW_LINE> cloc = getJointConstraint(joint, 'LIMIT_LOCATION') <NEW_LINE> cloc.use_min_x = True <NEW_LINE> cloc.use_min_y = True <NEW_LINE> cloc.use_min_z = True <NEW_LINE> cloc.use_max_x = True <NEW_LINE> cloc... | Args:
joint:
lower:
upper:
Returns: | 625941e1925a0f43d254a219 |
def lr_decay(init_lr, decay, time_const, global_step): <NEW_LINE> <INDENT> decay = tf.constant(decay) <NEW_LINE> decay_step = tf.cast(global_step, tf.float32) <NEW_LINE> lr = tf.realdiv(init_lr, tf.pow(1.0 + tf.realdiv(decay_step, decay_const), self._decay_exp)) <NEW_LINE> return lr | Gets a decayed learning rate using inverse decay rule.
Args:
init_lr: Initial learning rate at step 0.
decay: Decay exponent.
time_const: Time constant of the inverse decay rule.
global_step: Time step.
Returns:
lr: Learning rate at the current time step. | 625941e11b99ca400220ae52 |
def __get_line(self): <NEW_LINE> <INDENT> line = get_input_line() <NEW_LINE> print('>>>',line) <NEW_LINE> self.buffer = self.buffer + line + '\n' | Grab one line from get_input_line() and append it to the buffer.
| 625941e1fbf16365ca6f656a |
def fft_convolve2d(x,y): <NEW_LINE> <INDENT> fr = fft2(x) <NEW_LINE> fr2 = fft2(np.flipud(np.fliplr(y))) <NEW_LINE> m,n = fr.shape <NEW_LINE> cc = np.real(ifft2(fr*fr2)) <NEW_LINE> cc = np.roll(cc, - int(m / 2) + 1, axis=0) <NEW_LINE> cc = np.roll(cc, - int(n / 2) + 1, axis=1) <NEW_LINE> return cc | 2D convolution, using FFT | 625941e1099cdd3c635f0ff9 |
def help_function(): <NEW_LINE> <INDENT> print(BColors.BOLD + BColors.UNDERLINE + "Usage:" + BColors.ENDC) <NEW_LINE> print(BColors.BOLD + "\tasync_cdp_discovery seed(s)_host(s) username password" + BColors.ENDC) <NEW_LINE> print(BColors.BOLD + "\t\tseed(s)_host(s): This can be a single host or multiple hosts separated... | Function for HELP
:return: NULL | 625941e1a79ad161976cc4e4 |
def get_activities(): <NEW_LINE> <INDENT> r = oneupsdk.integration.api.request("/oneUp/instructors/activitiesList") <NEW_LINE> if r is None or r.status_code != 200: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> s = _bs4.BeautifulSoup(r.content, features="html.parser") <NEW_LINE> pane_tag = s.find("ul", {"id": "sort... | Returns a list of the activity categories for the active course. | 625941e1796e427e537b0968 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.