code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def getSubtweet( text, tweet, subType ): <NEW_LINE> <INDENT> subStatus = tweet[subType]["full_text"] <NEW_LINE> subStatus = re.sub(r'@[A-Za-z0-9]', '', subStatus, flags=re.MULTILINE) <NEW_LINE> text = text + " " + subStatus + " @" + tweet[subType]["user"]["screen_name"] <NEW_LINE> return text | Obtains subtweets from quoted_status and retweeted_status and strips handles.
args:
- text : the tweet text of the original tweeter.
- tweet : the tweet metadata.
- subType : the type of subtweet (quoted_status vs retweeted_status)
returns: the concatenation of the original text and the subtweeted text. | 625941dc67a9b606de4a81b7 |
def export(self): <NEW_LINE> <INDENT> LOG.info("Exporting credentials to password store") <NEW_LINE> if self.prefix: <NEW_LINE> <INDENT> prefix = f"{self.prefix}/" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prefix = self.prefix <NEW_LINE> <DEDENT> LOG.debug("Using pass prefix '%s'", prefix) <NEW_LINE> for address in... | Export given passwords to password store
Format of "to_export" should be:
{"address": {"login": "password", ...}, ...} | 625941dc0a366e3fb873eb1c |
def switch_ctx(self, *args, **kwargs): <NEW_LINE> <INDENT> with Context(self.path): <NEW_LINE> <INDENT> return func(self, *args, **kwargs) | Allows Package methods to easily operate within /
change paths by wrapping them with Context. | 625941dccc0a2c11143dd190 |
def __init__(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> factory = Gtk.IconFactory() <NEW_LINE> pixbuf = GdkPixbuf.Pixbuf.new_from_file(ICONPATH) <NEW_LINE> iconset = Gtk.IconSet.new_from_pixbuf(pixbuf) <NEW_LINE> factory.add("thg_logo", iconset) <NEW_LINE> factory.add_default() <NEW_LINE> <DEDENT> except: pass | Nautilus crashes if a plugin doesn't implement the __init__ method | 625941dcd486a94d0b98e446 |
def check_dir(adir): <NEW_LINE> <INDENT> if not os.path.exists(adir): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not os.path.isdir(adir): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True | Check that a directory exists. | 625941dc4f88993c3716c364 |
def restoreCheckpoint(self): <NEW_LINE> <INDENT> self.conn.send("world.checkpoint.restore") | Restore the world state to the checkpoint | 625941dc3617ad0b5ed681f6 |
def to_der(self, point_encoding="uncompressed"): <NEW_LINE> <INDENT> if point_encoding != "uncompressed": <NEW_LINE> <INDENT> raise ValueError(point_encoding) <NEW_LINE> <DEDENT> return self.pubkey.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) | Pub key as ASN.1/DER | 625941dc236d856c2ad44add |
def stop(self): <NEW_LINE> <INDENT> self.active = False <NEW_LINE> self.thread.join() | Call to shut down the threaded stats collector | 625941dce8904600ed9f2230 |
def global_settings(request): <NEW_LINE> <INDENT> def clean_safe_url(url): <NEW_LINE> <INDENT> if "://" not in url: <NEW_LINE> <INDENT> url = "http://" + url <NEW_LINE> <DEDENT> parsed = urlparse(url) <NEW_LINE> if "@" in parsed.netloc: <NEW_LINE> <INDENT> parsed = parsed._replace( netloc="username:secret@" + parsed.ne... | Adds settings to the context. | 625941dcbe7bc26dc91cd8fa |
def MultiReadStats(self, process_ids=None, metric_name=None, timestamp=ALL_TIMESTAMPS, limit=10000): <NEW_LINE> <INDENT> if not process_ids: <NEW_LINE> <INDENT> process_ids = self.ListUsedProcessIds() <NEW_LINE> <DEDENT> multi_metadata = self.MultiReadMetadata(process_ids=process_ids) <NEW_LINE> subjects = [ self.DATA_... | Reads historical data for multiple process ids at once. | 625941dc21bff66bcd684c4f |
def results_per_page(num): <NEW_LINE> <INDENT> _select = version.pick({ version.LOWEST: Select(_locator + _num_results), "5.5": AngularSelect('ppsetting')}) <NEW_LINE> sel.select(_select, sel.ByText(str(num))) | Changes the number of results on a page.
Args:
num: Number of results per page | 625941dc711fe17d82542664 |
def _use_payment_microfrontend(request): <NEW_LINE> <INDENT> return ( request.site.siteconfiguration.enable_microfrontend_for_basket_page and request.site.siteconfiguration.payment_microfrontend_url and not waffle.flag_is_active(request, DISABLE_MICROFRONTEND_FOR_BASKET_PAGE_FLAG_NAME) ) | Return whether the current request should use the payment MFE. | 625941dcb545ff76a8914115 |
def attribute_has_changed(self, attribute, from_cloud: bool): <NEW_LINE> <INDENT> if from_cloud: <NEW_LINE> <INDENT> attribute.set_value(attribute.get_value()) | This method gets called when an attribute was updated from the cloud.
CloudioAttributeListener interface implementation.
:param attribute Attribute that has changed.
:param from_cloud True if attribute was changed from cloud. False means attribute did
change internally (from endpoint). | 625941dcd7e4931a7ee9e21e |
@pytest.mark.parametrize("validator_name", VALIDATORS) <NEW_LINE> def test_nb4custom(validator_name): <NEW_LINE> <INDENT> set_validator(validator_name) <NEW_LINE> with TestsBase.fopen(u'test4custom.ipynb', u'r') as f: <NEW_LINE> <INDENT> nb = read(f, as_version=4) <NEW_LINE> <DEDENT> validate(nb) <NEW_LINE> assert isva... | Test that a notebook with a custom JSON mimetype passes validation | 625941dc56ac1b37e62644ca |
def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, audio): <NEW_LINE> <INDENT> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> sys.exit() <NEW_LINE> <DEDENT> elif event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> check_keydown_even... | Respond to keypresses and mouse events. | 625941dc6fb2d068a760f3a1 |
def on_rotation_center(self): <NEW_LINE> <INDENT> self.revert_pressed('rotation_center') <NEW_LINE> is_checked = self.actions['rotation_center'].isChecked() <NEW_LINE> if not is_checked: <NEW_LINE> <INDENT> self.setup_mouse_buttons(mode='default') <NEW_LINE> return <NEW_LINE> <DEDENT> style = RotationCenterStyle(parent... | http://osdir.com/ml/lib.vtk.user/2002-09/msg00079.html | 625941dc2eb69b55b151cbb2 |
def alive(self, initiator, correspondent): <NEW_LINE> <INDENT> console.terse("\nAlive Transaction **************\n") <NEW_LINE> initiator.alive() <NEW_LINE> self.service() | Utility method to do alive. Call from test method. | 625941dcd486a94d0b98e447 |
def _verify_arguments(self): <NEW_LINE> <INDENT> if len(self._data) == 0: <NEW_LINE> <INDENT> raise ValueError("Input data is empty (size: '%d')." % len(self._data)) <NEW_LINE> <DEDENT> if self._amount <= 0: <NEW_LINE> <INDENT> raise ValueError("Amount of cluster (current value: '%d') for allocation should be greater t... | !
@brief Verify input parameters for the algorithm and throw exception in case of incorrectness. | 625941dc56ac1b37e62644cb |
def remove_address(self, address: str): <NEW_LINE> <INDENT> receiver = self.receivers.pop(address) <NEW_LINE> receiver.close() | Stop receiving messages from the given address.
Args:
address: Queue or exchange address to stop receiving from. | 625941dc4e4d5625662d46d4 |
def setUp(self): <NEW_LINE> <INDENT> super(XBlockAcidBase, self).setUp() <NEW_LINE> self.setup_fixtures() <NEW_LINE> AutoAuthPage(self.browser, course_id=self.course_id).visit() <NEW_LINE> self.courseware_page = CoursewarePage(self.browser, self.course_id) | Create a unique identifier for the course used in this test. | 625941dcad47b63b2c50a27e |
def is_css(self): <NEW_LINE> <INDENT> START_RATIO = 100 <NEW_LINE> return len(self.error_list) < 2 and self.block_started > int(len(self.rawdata)/START_RATIO) | Is it css ? | 625941dc090684286d50efe8 |
def fetch_data(self, start_date=date(1980, 1, 1), end_date=date.today(), timeout=5): <NEW_LINE> <INDENT> self.read_list() <NEW_LINE> num_tickers = len(self.ticker_list) <NEW_LINE> progress = 0 <NEW_LINE> exception_tickers = [] <NEW_LINE> for c in self.ticker_list: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data = get... | Fetches OHLC data and stores as static CSVs
Parameters
----------
start_date: datetime.date (1/1/1980)
Starting date of OHLC data
end_date: datetime.date (Today)
Ending date of OHLC data
timeout: int (5)
Pause between every OHLC fetch. Keep > 0 if you don't want to be
blacklisted by provider | 625941dcadb09d7d5db6ca8e |
@view.add('global_hmaps') <NEW_LINE> def view_global_hmaps(token, dstore): <NEW_LINE> <INDENT> oq = dstore['oqparam'] <NEW_LINE> dt = numpy.dtype([('%s-%s' % (imt, poe), F32) for imt in oq.imtls for poe in oq.poes]) <NEW_LINE> array = dstore['hmaps/mean'][()].view(dt)[:, 0] <NEW_LINE> res = numpy.zeros(1, array.dtype) ... | Display the global hazard maps for the calculation. They are
used for debugging purposes when comparing the results of two
calculations. They are the mean over the sites of the mean hazard
maps. | 625941dc91f36d47f21ac7f5 |
def test_visual_arti_ref_one_ref(self): <NEW_LINE> <INDENT> edge_dic = visual_arti_ref(db, 6)[1] <NEW_LINE> self.assertTrue(len(edge_dic.keys())==1) <NEW_LINE> self.assertTrue(edge_dic[('CNNTitle1', 'cbslocal.com')] == 1) | (TestDBArticle) -> None
Test getting only one reference for article based on id | 625941dcd99f1b3c44c6788a |
def _task_submit_elaborate_specific_parameter(key, value, opts, args): <NEW_LINE> <INDENT> if key in ("--update-personid",): <NEW_LINE> <INDENT> bibtask.task_set_option("update_personid", True) <NEW_LINE> <DEDENT> elif key in ("--record-ids", '-i'): <NEW_LINE> <INDENT> if value.count("="): <NEW_LINE> <INDENT> value = v... | Given the string key it checks it's meaning, eventually using the
value. Usually, it fills some key in the options dict.
It must return True if it has elaborated the key, False, if it doesn't
know that key. | 625941dcaad79263cf390d45 |
def cre_annot(lnk, xref_dst, list_src, height): <NEW_LINE> <INDENT> r = lnk["from"] <NEW_LINE> rect = "%g %g %g %g" % (r.x0, height - r.y0, r.x1, height - r.y1) <NEW_LINE> if lnk["kind"] == LINK_GOTO: <NEW_LINE> <INDENT> txt = annot_goto <NEW_LINE> idx = list_src.index(lnk["page"]) <NEW_LINE> annot = txt % (xref_dst[id... | Create annotation object string for a passed-in link. | 625941dcf9cc0f698b1408f9 |
def alert(self): <NEW_LINE> <INDENT> super().alert() <NEW_LINE> if self.active: <NEW_LINE> <INDENT> self.logger.debug('posting HTTPAlert: {}'.format(self.request_kwargs)) <NEW_LINE> requests.post(**self.request_kwargs) | Emit Alert | 625941dc236d856c2ad44ade |
def setText(self, text): <NEW_LINE> <INDENT> self.text = text | Sets the text that makes up this PriceBarChartTextArtifact.
Arguments:
text - str value for the text to display. | 625941dc2eb69b55b151cbb3 |
def getfile(self, path, follow_symlinks=True): <NEW_LINE> <INDENT> if path == '/': <NEW_LINE> <INDENT> return self.fs <NEW_LINE> <DEDENT> pieces = path.strip('/').split('/') <NEW_LINE> cwd = '' <NEW_LINE> p = self.fs <NEW_LINE> for piece in pieces: <NEW_LINE> <INDENT> if piece not in [x[A_NAME] for x in p[A_CONTENTS]]:... | This returns the Cowrie file system object for a path | 625941dcdc8b845886cb5836 |
def callProcedure(self,procedure_name): <NEW_LINE> <INDENT> conn = self.conn.getConnection() <NEW_LINE> cursor = conn.cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> cursor.callproc(procedure_name) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print("插入出错:", e) <NEW_LINE> traceback.print_exc() <NEW_LINE> ... | 调用无参存储过程
:param procedure_name:
:return: | 625941dc7cff6e4e81117c86 |
def test_fromstring(self): <NEW_LINE> <INDENT> part = SVGFigure.fromstring(load_svg('dimension.svg')) <NEW_LINE> self.assertEqual((800, 600), part.get_size()) | Test SVGPart creation froms a string | 625941dc50812a4eaa59c61f |
def log_of(n, count=-1) -> int: <NEW_LINE> <INDENT> if n == 0: return count <NEW_LINE> n = math.floor(n/2) <NEW_LINE> count += 1 <NEW_LINE> return log_of(n, count) | This will count the depth (log) of the recursive calls to find the log2^n... | 625941dccad5886f8bd272d9 |
def build_augmentation_transform( zoom=(1.0, 1.0), rotation=0, shear=0, translation=(0, 0), flip=False): <NEW_LINE> <INDENT> if flip: <NEW_LINE> <INDENT> shear += 180 <NEW_LINE> rotation += 180 <NEW_LINE> <DEDENT> tform_augment = skimage.transform.AffineTransform( scale=(1 / zoom[0], 1 / zoom[1]), rotation=np.deg2rad(r... | Augmentation transform.
It performs zooming, rotation, shear, translation and flip operation
Affine Transformation on the input image
Args:
zoom: a tuple(zoom_rows, zoom_cols)
rotation: float, Rotation angle in counter-clockwise direction as radians.
shear: float, shear angle in counter-clockwise directio... | 625941dc01c39578d7e7513c |
def ntk_fn(x1, x2, params, keys=None): <NEW_LINE> <INDENT> key1, key2 = _read_keys(keys) <NEW_LINE> if x2 is None: <NEW_LINE> <INDENT> x2 = x1 <NEW_LINE> <DEDENT> f_dummy = partial(f, rng=random.PRNGKey(1)) <NEW_LINE> fx2_struct = eval_shape(f_dummy, params, x2) <NEW_LINE> fx_dummy = np.ones(fx2_struct.shape, fx2_struc... | Computes the empirical ntk.
Args:
x1: A first `np.ndarray` of inputs, of shape [n1, ...], over which we
would like to compute the NTK.
x2: A second `np.ndarray` of inputs, of shape [n2, ...], over which we
would like to compute the NTK.
params: A PyTree of parameters about which we would like to compute t... | 625941dc9c8ee82313fbba76 |
def index(self, address): <NEW_LINE> <INDENT> if isinstance(address, unicode): <NEW_LINE> <INDENT> address = str(address) <NEW_LINE> <DEDENT> elif not isinstance(address, str): <NEW_LINE> <INDENT> raise TypeError("Address must be a string") <NEW_LINE> <DEDENT> if self.is_numeric: <NEW_LINE> <INDENT> if not address.isdi... | Convert the given address (a string) to a 0-based index.
Raises a ValueError if the address cannot be converted. | 625941dc442bda511e8be715 |
def bit_reader(self) -> bitarray: <NEW_LINE> <INDENT> bit_string = bitarray() <NEW_LINE> with open(self.file_path, 'rb') as file: <NEW_LINE> <INDENT> bit_string.fromfile(file) <NEW_LINE> <DEDENT> symbol_number = bit_string.length() // SYMBOL_SIZE <NEW_LINE> slice_limit = symbol_number * SYMBOL_SIZE <NEW_LINE> return bi... | Читает битовое сообщение из файла
:return экземпляр класса bitarray | 625941dc23849d37ff7b338e |
def __init__(self): <NEW_LINE> <INDENT> self.num_layers = len([block for block in self.architecture if 'pool' in block or 'strided' in block]) + 1 | Class Initialyser | 625941dc76e4537e8c351976 |
def exptest(time_delta): <NEW_LINE> <INDENT> mean_time = np.mean(time_delta) <NEW_LINE> normalized_time_delta = time_delta / mean_time <NEW_LINE> mask = normalized_time_delta < 1 <NEW_LINE> sum_time = 1 - normalized_time_delta[mask] / 1 <NEW_LINE> sum_time_all = np.sum([sum_time]) <NEW_LINE> m_value = sum_time_all / le... | Compute the level of variability for a certain period of time.
The level of variability is quantified by ``mr``, as defined in Prahl (1999).
For constant rate events, it follows a standard normal distribution,
i.e. it can be used directly as the significance of variability.
For example usage, see :ref:`time-variabil... | 625941dcad47b63b2c50a27f |
def _LIKE(self, expression, pattern): <NEW_LINE> <INDENT> return "(%s LIKE '%s')" % (self.render(expression), pattern) | The LIKE Operator. | 625941dcb5575c28eb68e303 |
def join_domains(domains): <NEW_LINE> <INDENT> domains = set(domains) - set((None,)) <NEW_LINE> if not domains: <NEW_LINE> <INDENT> return () <NEW_LINE> <DEDENT> gdims = set() <NEW_LINE> for domain in domains: <NEW_LINE> <INDENT> gdims.add(domain.geometric_dimension()) <NEW_LINE> <DEDENT> if len(gdims) != 1: <NEW_LINE>... | Take a list of domains and return a tuple with only unique domain objects.
Checks that domains with the same id are compatible. | 625941dc76d4e153a657ee33 |
def gen(input_string=None, dictionary='./en', debug=False): <NEW_LINE> <INDENT> with open(dictionary, 'r') as f: <NEW_LINE> <INDENT> word_list = f.read().split('\n') <NEW_LINE> word_list = list(filter(None, word_list)) <NEW_LINE> word_list = [word.casefold() for word in word_list] <NEW_LINE> <DEDENT> if input_string is... | generates a 'my first is in x but not in y' type riddle
from an arbitrary string.
Wordlist is from dictionary. - can specify | 625941dc71ff763f4b549991 |
def create_orders_file(self, orders, filename): <NEW_LINE> <INDENT> with open(filename, 'w') as f: <NEW_LINE> <INDENT> for response_order in orders: <NEW_LINE> <INDENT> order = Order.objects.get(number=response_order['detail']) <NEW_LINE> f.write("%s\n" % order.number) <NEW_LINE> <DEDENT> <DEDENT> f.close() | Create a file with order numbers - one per line | 625941dc24f1403a92600e64 |
def pc_work_time(self): <NEW_LINE> <INDENT> return _pmt_cpp_swig.pmt_extract_sptr_pc_work_time(self) | pc_work_time(pmt_extract_sptr self) -> float | 625941dc63f4b57ef0001412 |
def mineable(self): <NEW_LINE> <INDENT> nonce = self._nonce <NEW_LINE> self._nonce = BlockConf.MINEABLE_NONCE_PLACEHOLDER <NEW_LINE> rep = self.json() <NEW_LINE> self._nonce = nonce <NEW_LINE> return rep | to make the block ready for mining
you can always returns a partial json
string and the miner can replace the nonce in string
and mine it, it sounds lliek and efficient process | 625941dcb545ff76a8914116 |
def setContainerProperty(self, strProperty: str, strValue: str) -> None: <NEW_LINE> <INDENT> pass | Sets a container property, similar to an infolabel.
:param key: string - property name.
:param value: string or unicode - value of property.
.. note::
Key is NOT case sensitive. You can use the above as keywords for
arguments and skip certain optional arguments. Once you use a
keyword, all following argum... | 625941dc56b00c62f0f1495c |
def test_take_ownership(): <NEW_LINE> <INDENT> if os.path.isfile(TEST_FILE): <NEW_LINE> <INDENT> os.remove(TEST_FILE) <NEW_LINE> <DEDENT> with open(TEST_FILE, "w") as file_handle: <NEW_LINE> <INDENT> file_handle.write("SOME TEXT") <NEW_LINE> <DEDENT> owner = get_ownership(TEST_FILE) <NEW_LINE> print("Current file owner... | Let's create a file, check it's owner, than change it and test again | 625941dc2ae34c7f2600d432 |
def update(self, feedback_value): <NEW_LINE> <INDENT> error = self.SetPoint - feedback_value <NEW_LINE> if error > 180: <NEW_LINE> <INDENT> error = error - 360 <NEW_LINE> <DEDENT> if error < -180: <NEW_LINE> <INDENT> error = error + 360 <NEW_LINE> <DEDENT> self.current_time = time.time() <NEW_LINE> delta_time = self.cu... | Calculates PID value for given reference feedback
.. math::
u(t) = K_p e(t) + K_i \int_{0}^{t} e(t)dt + K_d {de}/{dt}
.. figure:: images/pid_1.png
:align: center
Test PID with Kp=1.2, Ki=1, Kd=0.001 (test_pid.py) | 625941dc8e7ae83300e4b2ce |
def expand_env_var(env_var): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> interpolated = os.path.expanduser(os.path.expandvars(str(env_var))) <NEW_LINE> if interpolated == env_var: <NEW_LINE> <INDENT> return interpolated <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env_var = interpolated | Expands (potentially nested) env vars by repeatedly applying
`expandvars` and `expanduser` until interpolation stops having
any effect. | 625941dccad5886f8bd272da |
def pretty_print(self): <NEW_LINE> <INDENT> pt = PrettyTable() <NEW_LINE> pt._set_field_names(self.header) <NEW_LINE> for train in self.trains: <NEW_LINE> <INDENT> pt.add_row(train) <NEW_LINE> <DEDENT> print(pt) | 数据已经获取到了,剩下的就是提取我们想要的信息并将他显示出来。
‘prettytabl‘这个库可以让我们像mysql 数据库那样格式化显示数据。 | 625941dc5fdd1c0f98dc0535 |
def __apply_action(self, action, player): <NEW_LINE> <INDENT> self.board[action[0]][action[1]] = player <NEW_LINE> winner = self.__check_winner() <NEW_LINE> if winner != PLAYER_N or len(self.__get_actions()) == 0 : <NEW_LINE> <INDENT> self.board = self.__init_board() <NEW_LINE> if winner == self.__player_mark(): <NEW_L... | Modify state, given the action
@returns True if the game has restarted | 625941dc6e29344779a62911 |
def get_if_cleaned_dict(site_dict, prop): <NEW_LINE> <INDENT> if_cleaned_dict = {} <NEW_LINE> amb_list = ["-","?","X"] <NEW_LINE> for key, value in site_dict.items(): <NEW_LINE> <INDENT> unambs = sum([v for k,v in Counter(value).items() if k not in amb_list]) <NEW_LINE> if unambs > len(value)*prop: <NEW_LINE> <INDENT> ... | Given a site dict, replace the value of each site with True if the site is cleaned and False if otherwise | 625941dc63f4b57ef0001413 |
def tsel(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.t[self.use] <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> return self.t | Return table of selected galaxies. | 625941dcab23a570cc250485 |
def __init__( self, simplisafe: SimpliSafe, system: SystemV3, sensor: SensorV3, device_class: str, ) -> None: <NEW_LINE> <INDENT> super().__init__(simplisafe, system, device=sensor) <NEW_LINE> self._attr_device_class = device_class <NEW_LINE> self._device: SensorV3 | Initialize. | 625941dc38b623060ff0b0ee |
def __dir__(self): <NEW_LINE> <INDENT> result = list(NEW_MODULE.__all__) <NEW_LINE> result.extend(('__file__', '__path__', '__doc__', '__all__', '__docformat__', '__name__', '__path__', '__package__', '__version__')) <NEW_LINE> return result | Just show what we want to show. | 625941dc3617ad0b5ed681f7 |
def np_emb_op(weights, input_node, output_node): <NEW_LINE> <INDENT> input_data = input_node.get_data() <NEW_LINE> output_data = output_node.get_data() <NEW_LINE> output_data[:] = weights[input_data] | embedding operation for numpy matrix | 625941dcf7d966606f6aa309 |
def p_statement(p): <NEW_LINE> <INDENT> global statement_count <NEW_LINE> statement_count +=1 <NEW_LINE> if(len(p) >1): <NEW_LINE> <INDENT> pn = StatementNode([p[1]]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("empty statement") <NEW_LINE> pn = StatementNode([ValLiteralNode([0])]) <NEW_LINE> <DEDENT> p[0] = pn | statement : expr ';'
| declaration ';'
| break_arg ';'
| ';' | 625941dc71ff763f4b549992 |
def test_invalid_form_existing_password_no_lowercase_letter(self): <NEW_LINE> <INDENT> data = {'username':'testeLogin', 'email': 'teste@teste.com', 'senha':'A1@23456', 'conf_senha':'A1@23456'} <NEW_LINE> form = UserCreateForm(data=data) <NEW_LINE> self.assertFalse(form.is_valid(), 'error validating form with invalid us... | check if the form is not creating a user with date wrongs: no lowercase letter | 625941dc30bbd722463cc0ca |
def key_for_collection_id(collection_id, client=None): <NEW_LINE> <INDENT> channel = resource_for_entity_id('channels', 'collection', collection_id, client) <NEW_LINE> if channel is None: <NEW_LINE> <INDENT> raise ChannelNotFoundError() <NEW_LINE> <DEDENT> if channel.get('key') is None: <NEW_LINE> <INDENT> raise Channe... | :param collection_id: collection id of the SMS item to match the JWPlatform video
:param client: (options) an authenticated JWPlatform client as returned by
:py:func:`.get_jwplatform_client`. If ``None``, call :py:func:`.get_jwplatform_client`.
:raises: :py:class:`.ChannelNotFoundError`
if the clip id does not ... | 625941dc57b8e32f5248379e |
def get_all_asset_metadata(self, course_key, asset_type, start=0, maxresults=-1, sort=None, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError() | For now this is not implemented, but others should feel free to implement using the asset.json
which export produces. | 625941dc046cf37aa974d047 |
def _hash_it(self, artworkdata): <NEW_LINE> <INDENT> m = hashlib.sha256(artworkdata) <NEW_LINE> length = "b'{}Kb'".format(int(len(artworkdata)/1024 + 0.5)) <NEW_LINE> if m.hexdigest() not in self.hashed_graphics: <NEW_LINE> <INDENT> self.hashed_graphics[m.hexdigest()] = artworkdata <NEW_LINE> <DEDENT> return m.hexdiges... | put artworkdata (is bytes) into hashedgraphics
and return hashtag and length str | 625941dc091ae3566866725b |
def sample(self, use_trigger=False): <NEW_LINE> <INDENT> self._samples = [] <NEW_LINE> self.drv.sample_clk_div = int(LogicSnifferDriver.MAX_SAMPLE_CLK / self._sample_clk) <NEW_LINE> if use_trigger: <NEW_LINE> <INDENT> self.drv.trigger_en = self._trigger_en <NEW_LINE> self.drv.trigger_val = self._trigger_val <NEW_LINE> ... | :param use_trigger:
:return: | 625941dccc40096d61595c51 |
def test_enqueues_query_with_correct_data_source(self): <NEW_LINE> <INDENT> query = self.factory.create_query( schedule="60", data_source=self.factory.create_data_source()) <NEW_LINE> query2 = self.factory.create_query( schedule="60", query_text=query.query_text, query_hash=query.query_hash) <NEW_LINE> retrieved_at = u... | Queries from different data sources will be reported by
Query.outdated_queries() even if they have the same query text. | 625941dc63b5f9789fde73e7 |
def __del__(self): <NEW_LINE> <INDENT> pass | Called when an instance of Test is about to be destroyed. | 625941dc956e5f7376d7116d |
def history_info(): <NEW_LINE> <INDENT> history_text_1 = "In 2013, three radical Black organizers —" <NEW_LINE> history_text_2 = "Alicia Garza, Patrisse Cullors, and Opal" <NEW_LINE> history_text_3 = "Tometi — created a Black-centered political" <NEW_LINE> history_text_4 = "will and movement building project called" <N... | Fills in info for history section
Returns
-------
None. | 625941dcd486a94d0b98e448 |
def isSEISAN(filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> f = open(filename, 'rb') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> data = f.read(12 * 80) <NEW_LINE> f.close() <NEW_LINE> if _getVersion(data): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Checks whether a file is SEISAN or not.
:type filename: str
:param filename: Name of the audio SEISAN file to be checked.
:rtype: bool
:return: ``True`` if a SEISAN file.
.. rubric:: Example
>>> isSEISAN("/path/to/1996-06-03-1917-52S.TEST__002") #doctest: +SKIP
True | 625941dcd58c6744b4257f60 |
def cb_destroy(self, confirmed): <NEW_LINE> <INDENT> if confirmed: <NEW_LINE> <INDENT> self.destroyed = True <NEW_LINE> if self.game: <NEW_LINE> <INDENT> def1 = self.user.callRemote("withdraw", self.game.name) <NEW_LINE> def1.addErrback(self.failure) <NEW_LINE> <DEDENT> if self.guimap is not None: <NEW_LINE> <INDENT> s... | Withdraw from the game, and destroy the GUIMasterBoard. | 625941dc5fcc89381b1e19c3 |
def __init__(self,V,q4): <NEW_LINE> <INDENT> self.q1 = V.x <NEW_LINE> self.q2 = V.y <NEW_LINE> self.q3 = V.z <NEW_LINE> self.q4 = q4 | Quaternion constructor | 625941dc4f88993c3716c366 |
def draw_obstacles(self): <NEW_LINE> <INDENT> self.map_img = cv2.imread('../images/map.png') <NEW_LINE> if self.map_img is None: <NEW_LINE> <INDENT> self.map_img = np.zeros((self.height, self.width, 3), dtype=np.uint8) <NEW_LINE> self.map_img.fill(255) <NEW_LINE> self.draw_circle(self.map_img) <NEW_LINE> self.draw_squa... | Draw map using half-plane equations
:return: map-image with all obstacles | 625941dc627d3e7fe0d69152 |
def remove_parameter(self, entity_name, param_name): <NEW_LINE> <INDENT> view = self.navigate_to(self, 'Edit', entity_name=entity_name) <NEW_LINE> view.parameters.params.remove(param_name) <NEW_LINE> view.submit_button.click() <NEW_LINE> view.validations.assert_no_errors() <NEW_LINE> view.flash.assert_no_error() <NEW_L... | Remove parameter from existing domain entity
:param entity_name: Domain name to be edited
:param param_name: Name of a parameter to be removed | 625941dca8370b7717052ba0 |
def update(self, namespace, object_name, **kwargs): <NEW_LINE> <INDENT> obj = self.get(namespace, object_name) <NEW_LINE> for (key, value) in kwargs.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(obj, key, value) <NEW_LINE> <DEDENT> except warlock.InvalidOperation as e: <NEW_LINE> <INDENT> raise TypeErro... | Update an object.
:param namespace: Name of a namespace the object belongs.
:param object_name: Name of an object (old one).
:param kwargs: Unpacked object. | 625941dce8904600ed9f2232 |
def bootStrapSubscriber(event): <NEW_LINE> <INDENT> db, connection, root, root_folder = getInformationFromEvent(event) <NEW_LINE> ensureUtility( root_folder, IClientIdManager, 'CookieClientIdManager', CookieClientIdManager) <NEW_LINE> ensureUtility( root_folder, ISessionDataContainer, 'PersistentSessionDataContainer', ... | Subscriber to the IDataBaseOpenedEvent
Create utility at that time if not yet present | 625941dc01c39578d7e7513d |
def get_unit_status(unit_name: str) -> Dict[str, Any]: <NEW_LINE> <INDENT> bus = SystemBus() <NEW_LINE> systemd = bus.get('org.freedesktop.systemd1') <NEW_LINE> path = systemd.GetUnit(unit_name) <NEW_LINE> unit = bus.get('org.freedesktop.systemd1', path) <NEW_LINE> properties = dict_from_attributes(unit['org.freedeskto... | Get the status of a given systemd unit.
:param unit_name: The name of the unit.
:returns: A dictionary of the unit properties | 625941dcfb3f5b602dac3998 |
def fetch_all_sequences(query_folder, uniprot_ids, database_file): <NEW_LINE> <INDENT> if not query_folder.endswith("/"): <NEW_LINE> <INDENT> query_folder += "/" <NEW_LINE> <DEDENT> print("Processing the list of ids...") <NEW_LINE> for line in uniprot_ids: <NEW_LINE> <INDENT> fastaContent = fetch_one_fasta(line) <NEW_L... | Fetch the fasta formatted sequence for each uniProtID in the list.
:param query_folder: folder containing fasta files.
:param uniprot_ids: File with the list of protein IDs
:param database_file: database files to save the results of the fetching. | 625941dc3d592f4c4ed1d369 |
def fabrik_solver(xi, yi, xf, yf, l1=1, l2=1, elbow=1, precision = 0.000001): <NEW_LINE> <INDENT> theta1, theta2 = ik_solver(xf, yf, l1, l2, elbow) <NEW_LINE> ef_pos = np.array([xi, yi]) <NEW_LINE> final_pos = np.array([xf, yf]) <NEW_LINE> error_xy = precision <NEW_LINE> error = np.linalg.norm((final_pos-ef_pos)) <NEW_... | Function to return end effector position given current arm positions
Inputs:
xi - x coordinate of current end-effector position
yi - y coordinate of current end-effector position
xf - x coordinate of the desired position
yf - y coordinate of the desired position
l1 - length of first link
l2 - le... | 625941dc5166f23b2e1a545b |
def test(self, t, query, single=True, print_result=True, print_query=True): <NEW_LINE> <INDENT> start_time = datetime.datetime.now() <NEW_LINE> if print_query: print("QUERY: " + query) <NEW_LINE> s = self.nc.commit_list([query]) <NEW_LINE> end_time = datetime.datetime.now() <NEW_LINE> diff = end_time - start_time <NEW_... | Runs Cypher query.
Tests if query failed else
Tests length of results,
Tests results validity against schema.
query = cypher query,
t = QueryRollerTest object,
single = True if results list length should be one
print results: wot it sez on the tin | 625941dc85dfad0860c3b15d |
def make_instance(self, include_optional): <NEW_LINE> <INDENT> if include_optional : <NEW_LINE> <INDENT> return UpdateLicense( first_name = 'John', id = 3995, last_name = 'Doe', role = 'creator | viewer | Admin | User' ) <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> return UpdateLicense( first_name = 'John', id = 3995... | Test UpdateLicense
include_option is a boolean, when False only required
params are included, when True both required and
optional params are included | 625941dc956e5f7376d7116e |
def _default_echo_handler(self, message, addr): <NEW_LINE> <INDENT> self.send({"result": message.get("params", None), "error": None, "id": message['id']}, addr=addr) | Message handler for the OVSDB server's echo request. | 625941dcbaa26c4b54cb141e |
def fit(self, data: np.ndarray): <NEW_LINE> <INDENT> self.centroid = self._init_centroid(data) <NEW_LINE> for _ in range(self.max_iter): <NEW_LINE> <INDENT> distance = self._calc_distance(data) <NEW_LINE> cluster = self._assign_cluster(distance) <NEW_LINE> new_centroid = self._update_centroid(data, cluster) <NEW_LINE> ... | Fit K-Means algorithm to given data
Parameters
----------
data : np.ndarray
Data matrix to be fitted | 625941dc009cb60464c636b1 |
def get_generos(self, origen=None): <NEW_LINE> <INDENT> genre_list =[] <NEW_LINE> if not origen: <NEW_LINE> <INDENT> origen = self.result <NEW_LINE> <DEDENT> if "genre_ids" in origen: <NEW_LINE> <INDENT> for i in origen.get("genre_ids"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> genre_list.append(Tmdb.dic_generos[se... | :param origen: Diccionario origen de donde se obtiene los infoLabels, por omision self.result
:type origen: Dict
:return: Devuelve la lista de generos a los que pertenece la pelicula o serie.
:rtype: str | 625941dc66673b3332b92393 |
@pytest.fixture <NEW_LINE> def subset_of_vms(vms): <NEW_LINE> <INDENT> vm_num = 4 if len(vms) >= 4 else len(vms) <NEW_LINE> return sample(vms, vm_num) | We'll pick a host with median number of vms | 625941dccc0a2c11143dd193 |
def get_final_ranking(self): <NEW_LINE> <INDENT> competing_teams = self.get_competing_teams() <NEW_LINE> robotics = self.get_robotics_results() <NEW_LINE> research = self.get_research_evaluation_results() <NEW_LINE> jury = self.get_team_evaluation_results() <NEW_LINE> bonus = self.get_team_bonus_results() <NEW_LINE> no... | Computes and returns the tournament final ranking, as a list of tuples, containing each the rank and
corresponding list of team numbers.
Only competing teams are included in the final ranking result. | 625941dc56ac1b37e62644cc |
def tweet_search(api, query, max_tweets, max_id, since_id): <NEW_LINE> <INDENT> searched_tweets = [] <NEW_LINE> while len(searched_tweets) < max_tweets: <NEW_LINE> <INDENT> remaining_tweets = max_tweets - len(searched_tweets) <NEW_LINE> try: <NEW_LINE> <INDENT> new_tweets = api.search(q=query, count=remaining_tweets, s... | Function that takes in a search string 'query', the maximum
number of tweets 'max_tweets', and the minimum (i.e., starting)
tweet id. It returns a list of tweepy.models.Status objects. | 625941dcd8ef3951e324383f |
def get_field_value_to_many(self, field_name): <NEW_LINE> <INDENT> if field_name in self.data: <NEW_LINE> <INDENT> return self.data[field_name] <NEW_LINE> <DEDENT> if self.instance: <NEW_LINE> <INDENT> return getattr(self.instance, field_name).all() <NEW_LINE> <DEDENT> return () | Returns an object representing to-many field values. | 625941dce76e3b2f99f3ab09 |
def _list_once(self, resource_type, value=None, **attrs): <NEW_LINE> <INDENT> res = self._get_resource(resource_type, value, **attrs) <NEW_LINE> return res.list_once(self._session, **attrs) | List a resource
:param resource_type: The type of resource to delete. This should
be a :class:`~openstack.resource2.Resource`
subclass with a ``from_id`` method.
:param value: The resource to list. It can be the ID of a resource, or
a :class:`~openstack.resourc... | 625941dc60cbc95b062c6845 |
def test_questions_by_product(self): <NEW_LINE> <INDENT> firefox_os = product(slug='firefox-os', save=True) <NEW_LINE> firefox = product(slug='firefox', save=True) <NEW_LINE> q = question(save=True) <NEW_LINE> q.products.add(firefox_os) <NEW_LINE> a = answer(question=q, save=True) <NEW_LINE> q.solution = a <NEW_LINE> q... | Test product filtering of questions API call. | 625941dc379a373c97cfae48 |
def load(self, conv_opt_model): <NEW_LINE> <INDENT> solver_model = super(CvxoptModel, self).load(conv_opt_model) <NEW_LINE> for variable in conv_opt_model.variables: <NEW_LINE> <INDENT> if variable.type != VariableType.continuous: <NEW_LINE> <INDENT> raise ConvOptError('Unsupported variable of type "{}"'.format(variabl... | Load a model to CVXPY's data structure
Args:
conv_opt_model (:obj:`cvxpy.Problem`): model
Returns:
:obj:`dict`: the model in CVXPY's data structure
Raises:
:obj:`ConvOptError`: if a variable has an unsupported type | 625941dc293b9510aa2c3594 |
def _translate(df, dct_dimension, dct_col, is_dimension=False): <NEW_LINE> <INDENT> temp = df.copy() <NEW_LINE> if is_dimension: <NEW_LINE> <INDENT> temp = temp.apply(lambda x:x.map(dct_dimension[x.name]) if ((x.name in dct_dimension) and (9999 not in dct_dimension.get(x.name))) else x) <NEW_LINE> <DEDENT> else: <NEW_L... | 翻译字段 | 625941dc0c0af96317bb84ea |
def run(self): <NEW_LINE> <INDENT> if not self._scrape_types: <NEW_LINE> <INDENT> scraping_to_do = self.scrape_types <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if set(self._scrape_types).difference(set(self.scrape_types)): <NEW_LINE> <INDENT> raise ValueError("Actions must be one of {}".format(", ".join(self.scrape_... | Run the scraper with the initialized configuration from the constructor. | 625941dc07d97122c4178b93 |
def cdms_datetime_to_datetime(value): <NEW_LINE> <INDENT> if isinstance(value, datetime.datetime): <NEW_LINE> <INDENT> return value <NEW_LINE> <DEDENT> match = DATETIME_RE.match(value or '') <NEW_LINE> if match: <NEW_LINE> <INDENT> parsed_val = int(match.group(1)) <NEW_LINE> parsed_val = datetime.datetime.utcfromtimest... | Parses a cdms datetime as string and returns the equivalent datetime value.
Dates in CDMS are always UTC. | 625941dc7b180e01f3dc4afa |
def __init__(self, zipfile, entry=''): <NEW_LINE> <INDENT> if isinstance(zipfile, compat.string_types): <NEW_LINE> <INDENT> zipfile = OpenOnDemandZipFile(os.path.abspath(zipfile)) <NEW_LINE> <DEDENT> entry = normalize_resource_name(entry) <NEW_LINE> if entry: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> zipfile.getinfo... | Create a new path pointer pointing at the specified entry
in the given zipfile.
:raise IOError: If the given zipfile does not exist, or if it
does not contain the specified entry. | 625941dc56ac1b37e62644cd |
def _mkanchors(ws, hs, x_ctr, y_ctr): <NEW_LINE> <INDENT> ws = ws[:, np.newaxis] <NEW_LINE> hs = hs[:, np.newaxis] <NEW_LINE> anchors = np.hstack((x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1), x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1))) <NEW_LINE> return anchors | Given a vector of widths (ws) and heights (hs) around a center
(x_ctr, y_ctr), output a set of anchors (windows).
围绕中心坐标点生成高宽向量,输出为anchor集合 | 625941dc55399d3f055889b7 |
@templatefilter("isodatesec") <NEW_LINE> def isodatesec(text): <NEW_LINE> <INDENT> return util.datestr(text, "%Y-%m-%d %H:%M:%S %1%2") | Date. Returns the date in ISO 8601 format, including
seconds: "2009-08-18 13:00:13 +0200". See also the rfc3339date
filter. | 625941dc5510c4643540f6df |
def fit_transform(self, X, y=None): <NEW_LINE> <INDENT> return self.transform(X) | Transform the provided Dataframe.
:param pd.DataFrame X: Dataframe with data to be processed.
:return: Dataframe with processed data.
:rtype: pd.DataFrame | 625941dcad47b63b2c50a280 |
def __init__(self, points: List[Point]): <NEW_LINE> <INDENT> BaseLine.__init__(self, points) | create a b-spline based on given control points
:param points: the data points defining a curve | 625941dc462c4b4f79d1d9d2 |
def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> return self | Brief:
If they call this as a method, just return self | 625941dcde87d2750b860097 |
def split_sentence(content): <NEW_LINE> <INDENT> last_sent = '' <NEW_LINE> sentences = [] <NEW_LINE> splits = sent_re.split(content) <NEW_LINE> for ss in splits: <NEW_LINE> <INDENT> if not sent_re.search(ss): <NEW_LINE> <INDENT> last_sent = ss.strip() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(last_sent) > 3:... | 按照句号等分割成若干个句子
:param content: | 625941dc99fddb7c1c9de692 |
def load_model(): <NEW_LINE> <INDENT> context_len = 5 <NEW_LINE> batch_size = 100 <NEW_LINE> num_filters = 900 <NEW_LINE> filter_size = 5 <NEW_LINE> num_layers = 8 <NEW_LINE> pos_words_num = 5 <NEW_LINE> neg_words_num = 10 <NEW_LINE> num_residual = 1 <NEW_LINE> k_max = 3 <NEW_LINE> max_doc_len = 45 <NEW_LINE> embed_dim... | Load the CNN model | 625941dc45492302aab5e5c8 |
def add_label (label, line_color, line_width = 2, line_style = '-', marker = '', marker_size = 6): <NEW_LINE> <INDENT> plt.plot([], [], c = line_color, linewidth = line_width, ls = line_style, marker= marker, ms =marker_size, label = label) <NEW_LINE> plt.legend(handler_map=handler_map) <NEW_LINE> return | Adds special tri-color legend label to curent plot
Parameters
----------
label : string
legend label string
line_color : string
color of label object
line_width : int
line width if there is a line
line_style : string
possible options - -, --, -., :
marker : string
possible option... | 625941dc8e71fb1e9831daaa |
def flip_fights(n, m): <NEW_LINE> <INDENT> if not m: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif n == 1: <NEW_LINE> <INDENT> return 2 <NEW_LINE> <DEDENT> elif n == 2: <NEW_LINE> <INDENT> return 4 if m > 1 else 3 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 4 if m == 1 else 7 if m == 2 else 8 | :type n: int
:type m: int
:rtype: int | 625941dcadb09d7d5db6ca90 |
def op_JMP( ): <NEW_LINE> <INDENT> JUMP_OP( ) | JMP <address>
: Set the CP to <address>.
#BRANCH | 625941dc9b70327d1c4e10d8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.