code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def OpenValve(self, valve_no): <NEW_LINE> <INDENT> raise NotImplementedError() | Returns a context manager than holds open the specified valve.
| 625941dc0fa83653e46572b0 |
def angle_between(self, other): <NEW_LINE> <INDENT> return(math.acos(self.dot(other))) | angle between self and other vector | 625941dc3617ad0b5ed681ed |
def get_script_path(): <NEW_LINE> <INDENT> return os.path.dirname(os.path.realpath(sys.argv[0])) | Gets the absolute filepath of the script calling it | 625941dcd53ae8145f87a562 |
def value(self, mode): <NEW_LINE> <INDENT> candidates = super(mn_mep, self).value(mode) <NEW_LINE> if mode == "l": <NEW_LINE> <INDENT> for i in range(len(candidates)): <NEW_LINE> <INDENT> tmp = candidates[i][1] + candidates[i][0] <NEW_LINE> if len(candidates[i]) == 4: <NEW_LINE> <INDENT> tmp += candidates[i][3] + candi... | Adjust the assembled instruction based on the endianness
Note: code inspired by miasm/arch/mips32/arch.py | 625941dc460517430c394476 |
def axes_grid(n, sharex=False, sharey=False, subplot_kw=None, **fig_kw): <NEW_LINE> <INDENT> r = np.floor(np.sqrt(n)) <NEW_LINE> r, c = int(r), int(np.ceil(n / r)) <NEW_LINE> fig, axes = plt.subplots(nrows=r, ncols=c, figsize=(c*4, r*4), squeeze=False, sharex=sharex, sharey=sharey, subplot_kw=subplot_kw, **fig_kw) <NEW... | Finds a reasonable arrangement of n axes. Returns (fig, axes) tuple.
For keyword arguments descriptions, see matplotlib.pyplot.subplots | 625941dc7b25080760e3974f |
def add(self, categorize): <NEW_LINE> <INDENT> if inspect.isfunction(categorize): <NEW_LINE> <INDENT> argspec = inspect.getargspec(categorize) <NEW_LINE> if len(argspec.args) != 1: <NEW_LINE> <INDENT> categorize = None <NEW_LINE> <DEDENT> <DEDENT> elif type(categorize) != partial_func: <NEW_LINE> <INDENT> categorize = ... | Add given method to categorize messages. When a message is received,
each of the added methods (most recently added method first) is called
with the message. The method should return a category (any hashable
object) or None (in which case next recently added method is called with
the same message). If all the methods r... | 625941dccb5e8a47e48b7d9d |
def _random(self, n=None, re_min=-1, im_min=-1, re_max=1, im_max=1): <NEW_LINE> <INDENT> free = self.free_symbols <NEW_LINE> prec = 1 <NEW_LINE> if free: <NEW_LINE> <INDENT> from sympy.testing.randtest import random_complex_number <NEW_LINE> a, c, b, d = re_min, re_max, im_min, im_max <NEW_LINE> reps = dict(list(zip(fr... | Return self evaluated, if possible, replacing free symbols with
random complex values, if necessary.
Explanation
===========
The random complex value for each free symbol is generated
by the random_complex_number routine giving real and imaginary
parts in the range given by the re_min, re_max, im_min, and im_max
valu... | 625941dc3d592f4c4ed1d35e |
def test_preview_validation(self): <NEW_LINE> <INDENT> browser = self.layer.get_browser(topic_settings) <NEW_LINE> browser.login('dummy', 'dummy') <NEW_LINE> self.assertEqual(browser.open('/root/forum'), 200) <NEW_LINE> self.assertEqual(browser.get_link('Test Topic').click(), 200) <NEW_LINE> form = browser.get_form('po... | Try to preview an empty or incomplete comment.
| 625941dca8ecb033257d33c3 |
def display_map(self, state:dict = None): <NEW_LINE> <INDENT> if state is not None: <NEW_LINE> <INDENT> _,ax = plt.subplots(1) <NEW_LINE> ax.set_aspect('equal') <NEW_LINE> color_code = {'R':'red','B':'blue','G':'green'} <NEW_LINE> for key, value in state.items(): <NEW_LINE> <INDENT> y_shift = 0.0 <NEW_LINE> for c in va... | Displays an image of the Australia map with the current color(s)
for each region for the given 'state'.
Displays a blank map if 'state' is None.
Parameter
------------
state: dict [default None]
The current state of the map. | 625941dcfff4ab517eb2f735 |
def typeCheck(*types): <NEW_LINE> <INDENT> def _typeCheck_(func): <NEW_LINE> <INDENT> def wrapped_f(*args, **kwargs): <NEW_LINE> <INDENT> arguments = args[1:] <NEW_LINE> if len(arguments) == len(types): <NEW_LINE> <INDENT> final_types = [] <NEW_LINE> for type in types: <NEW_LINE> <INDENT> if type == "SELF": <NEW_LINE> ... | Decorator which reduces the amount of code to type-check attributes.
Its allows to replace the following code:
::
@id.setter
def id(self, id):
if not isinstance(id, uuid.UUID):
raise TypeError("Invalid types for argument id, must be an UUID")
self.__id = id
with:
::
@id.setter
... | 625941dc7d847024c06be5b6 |
def connect(self): <NEW_LINE> <INDENT> HTTPConnection.connect(self) <NEW_LINE> if self._tunnel_host: <NEW_LINE> <INDENT> server_hostname = self._tunnel_host <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> server_hostname = self.host <NEW_LINE> <DEDENT> self.sock = self._context.wrap_socket(self.sock, server_hostname=serv... | Connect to a host on a given (SSL) port. | 625941dc67a9b606de4a81af |
@pytest.mark.parametrize('word', ('Selenium', 'Python', 'Groovy')) <NEW_LINE> def test_search_in_google_com(page, word): <NEW_LINE> <INDENT> page.clear_search_box() <NEW_LINE> page.search_for_a_word(word) <NEW_LINE> assert word in page.search_top_result | verifies is Google Search page returns results for the words given as parameters | 625941dc26068e7796caefda |
def center_to_zero(signal): <NEW_LINE> <INDENT> mn = np.mean(signal) <NEW_LINE> return NormalizationResult(signal - mn, 1., mn) | Normalize signal by subtracting its mean
Does not perform any factor normalization
Returns
-------
A NormalizationResult() object.
Use .data to access the data
Use .factor to access the factor that signal was divided by
Use .offset to access the offset that was subtracted from signal | 625941dc30c21e258bdfa796 |
def get_result_count(self): <NEW_LINE> <INDENT> temp = self.pages <NEW_LINE> self.pages = 1 <NEW_LINE> result_count = 0 <NEW_LINE> search_results = self.__search__() <NEW_LINE> if not search_results: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> result_count = search_results[0] <NEW_LINE> if... | Returns the number of results | 625941dc63b5f9789fde73dd |
def on_message(_, __, msg) -> None: <NEW_LINE> <INDENT> logger.debug(f"Received message {msg.topic}: {msg.payload}") <NEW_LINE> if util.is_arduino_timer_action_topic(msg.topic): <NEW_LINE> <INDENT> logger.debug(f"Process the timer action") <NEW_LINE> TimeProcessor.process_timer_action_request(msg.payload.decode("utf-8"... | Callback function for when a new message is received. | 625941dcfbf16365ca6f64c0 |
def endPolygon(self): <NEW_LINE> <INDENT> self.polygon = False <NEW_LINE> for i in range(2,len(self.listOfVectors)): <NEW_LINE> <INDENT> triangle(vs = [vertex(pos = self.listOfVectors[0], color = self.currentColor), vertex(pos = self.listOfVectors[i-1],color = self.currentColor), vertex(pos = self.listOfVectors[i],colo... | Only works for convex polygons in a single plane.
This is just simple fan triangulation | 625941dca8370b7717052b96 |
def test_get_size(settings_mock): <NEW_LINE> <INDENT> engine = MultiThreadedRealEngine(settings_mock) <NEW_LINE> engine.write({'lol': 'kek'}) <NEW_LINE> assert engine.queue_size() == 1 <NEW_LINE> engine.write({'lol': 'kek'}) <NEW_LINE> assert engine.queue_size() == 2 <NEW_LINE> engine.stop() | Проверяем, что счетчик числа элементов в очереди работает. | 625941dc26238365f5f0f169 |
def wait_for_state(self, state, func, poll_interval=2, timeout=60, *args, **kwargs): <NEW_LINE> <INDENT> cnt = 0 <NEW_LINE> result = None <NEW_LINE> object_state = None <NEW_LINE> while cnt < timeout / poll_interval: <NEW_LINE> <INDENT> result = func(*args, **kwargs) <NEW_LINE> if isinstance(result, Node): <NEW_LINE> <... | Wait for the function which returns a instance with field status/state
to match.
Keep polling func until one of the desired states is matched
:param state: Either the desired state (`str`) or a `list` of states
:type state: ``str`` or ``list``
:param func: The function to call, e.g. ex_get_vlan. Note: This
... | 625941dc3617ad0b5ed681ee |
def testMergeByYear(self): <NEW_LINE> <INDENT> loadData() <NEW_LINE> d = merge_by_year(2000) <NEW_LINE> self.assertTrue('Region' in d.columns.values) <NEW_LINE> self.assertTrue('Country' in d.columns.values) <NEW_LINE> self.assertTrue('Income' in d.columns.values) | Loads data and checks for an arbitrary year (2000) that the column names are correct
and have been loaded properly | 625941dc38b623060ff0b0e5 |
def calc_favorability(interval, mean): <NEW_LINE> <INDENT> return min(1, max(0, mean-interval[0])/(interval[1]-interval[0])) | Range of 0-1. Low number means our belief range is above the market average, high means we're below. | 625941dc0a50d4780f66718c |
def run(self, image, flavor, force_delete=False, **kwargs): <NEW_LINE> <INDENT> server = self._boot_server(image, flavor, **kwargs) <NEW_LINE> self._suspend_server(server) <NEW_LINE> self._resume_server(server) <NEW_LINE> self._delete_server(server, force=force_delete) | Create a server, suspend, resume and then delete it
:param image: image to be used to boot an instance
:param flavor: flavor to be used to boot an instance
:param force_delete: True if force_delete should be used
:param kwargs: Optional additional arguments for server creation | 625941dc5166f23b2e1a5450 |
def lock(zk_hosts, path, max_concurrency, timeout=None, ephemeral_lease=False): <NEW_LINE> <INDENT> ret = {'name': path, 'changes': {}, 'result': False, 'comment': ''} <NEW_LINE> if __opts__['test']: <NEW_LINE> <INDENT> ret['result'] = None <NEW_LINE> ret['comment'] = 'attempt to aqcuire lock' <NEW_LINE> return ret <NE... | Block state execution until you are able to get the lock (or hit the timeout) | 625941dcd53ae8145f87a563 |
def axcolor(color): <NEW_LINE> <INDENT> plt.rc('xtick', color=color) <NEW_LINE> plt.rc('ytick', color=color) <NEW_LINE> plt.rc('axes', edgecolor=color) <NEW_LINE> plt.rc('axes', labelcolor=color) | Sets the color of all future axis lines and labels.
Parameters
----------
color : string or tuple
Any acceptable matplotlib color. | 625941dc656771135c3ebb69 |
def test_transform_simple_list(self): <NEW_LINE> <INDENT> self.bhp.transform.return_value = [[1]] <NEW_LINE> self.chp.transform.return_value = [[0]] <NEW_LINE> self.ihp.transform.return_value = [[1]] <NEW_LINE> values = [True, 'dog', 2] <NEW_LINE> result = self.instance.transform(values) <NEW_LINE> self.bhp.transform.a... | Test that the method transform performs a transformation over a list with a single
combination of hyperparameter valid values. | 625941dc21bff66bcd684c47 |
def run(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> time.sleep(self.__sleep_interval) <NEW_LINE> with self: <NEW_LINE> <INDENT> for key in tuple(self): <NEW_LINE> <INDENT> if not super().__getitem__(key): <NEW_LINE> <INDENT> del self[key] | Remove old sessions from memory as needed.
This method is executed by calling .start() on a SessionManager
object. The "daemon" attribute may need be set to True before
activating this feature. Please note that once this cleanup
routine begins, it must run until the program terminates. | 625941dc627d3e7fe0d69149 |
@pytest.mark.skipif('not HAS_SCIPY') <NEW_LINE> def test_z_at_value_roundtrip(): <NEW_LINE> <INDENT> z = 0.5 <NEW_LINE> skip = ('Ok', 'angular_diameter_distance_z1z2', 'clone', 'de_density_scale', 'w') <NEW_LINE> import inspect <NEW_LINE> methods = inspect.getmembers(core.Planck13, predicate=inspect.ismethod) <NEW_LINE... | Calculate values from a known redshift, and then check that
z_at_value returns the right answer. | 625941dcb57a9660fec33b80 |
def infiltrate(app): <NEW_LINE> <INDENT> global piter, faviter, bsto, populatedcallback <NEW_LINE> bstoinfo.Bsto.FavFile = bstoinfo.os.path.join(app.prefix, bstoinfo.bspconfig.favorites) <NEW_LINE> bsto = bstoinfo.Bsto() <NEW_LINE> piter = app.treestore.append(None, [ "Serien Online", "", "bs.to", "", "", "Now", "", la... | This function is called, after the main filetree is build. It has full access
to gktgui.MainWindow instance, so be careful. | 625941dcd4950a0f3b08c643 |
def validate_options(self, options): <NEW_LINE> <INDENT> options.dcos_account_enabled = (options.dcos_cluster_url is not None) <NEW_LINE> if not options.dcos_account_enabled: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if options.dcos_account_uid is None: <NEW_LINE> <INDENT> raise ValueError('--dcos_account_uid is n... | Implements interface. | 625941dc293b9510aa2c358a |
def output(self, obj): <NEW_LINE> <INDENT> if hasattr(obj, '_vzlog_output_'): <NEW_LINE> <INDENT> obj._vzlog_output_(self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.log(obj) | Outputs an object. This will look for `obj._vzlog_output_` and pass
itself along as the only argument. If the object does not have such a
function, it will fall back to calling `VzLog.log`. | 625941dcb545ff76a891410d |
def is_prime(n): <NEW_LINE> <INDENT> i = 2 <NEW_LINE> while i < n: <NEW_LINE> <INDENT> if n % i == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if i > n / i: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> return True | Return True if n is prime, False otherwise
Avoids wasting cycles where no multiple is able to be found | 625941dccc0a2c11143dd189 |
def insert_dash(num): <NEW_LINE> <INDENT> num_str = str(num) <NEW_LINE> new_str = num_str[0] <NEW_LINE> for i in range(1, len(num_str)): <NEW_LINE> <INDENT> if is_odd(num_str[i]) and is_odd(num_str[i - 1]): <NEW_LINE> <INDENT> new_str += ("-" + num_str[i]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_str += num_st... | insert_dash() inserts dashes between each pair of odd numbers
and returns it. | 625941dc956e5f7376d71164 |
def get_schedulable_types(skip_permission_check=False): <NEW_LINE> <INDENT> schedulable_types = [] <NEW_LINE> for (key, ti) in capi.iter_type_info(): <NEW_LINE> <INDENT> if ti.workflow and ti.workflow.has_feature("schedule"): <NEW_LINE> <INDENT> schedulable_types.append((key, ti)) <NEW_LINE> <DEDENT> <DEDENT> return di... | Get types that may be scheduled. Limit to those that the current user
has the right to transition to a scheduled state.
You can skip the `limit to allowed types` behaviour by calling with
`skip_permission_check` set to `True` | 625941dc1f5feb6acb0c4e44 |
def format(self, lines): <NEW_LINE> <INDENT> return map(ensure_newline_terminator, lines) | Args:
lines: An iterable series of strings, each with a newline terminator.
Yields:
An iterable series of strings, each with a newline terminator. | 625941dc5fc7496912cc3c76 |
@pytest.fixture <NEW_LINE> def popen_mock_command(): <NEW_LINE> <INDENT> replacer = testfixtures.Replacer() <NEW_LINE> popen = testfixtures.popen.MockPopen() <NEW_LINE> def add_command(cmd, stdout=b"", stderr=b"", returncode=0): <NEW_LINE> <INDENT> popen.set_command(cmd, stdout, stderr, returncode) <NEW_LINE> replacer.... | Fixture for adding a command with specified output and return to the popen mock. | 625941dc596a897236089db5 |
def strat_J4(Li): <NEW_LINE> <INDENT> L = [] <NEW_LINE> for k in Li: <NEW_LINE> <INDENT> L.append(abs(k)) <NEW_LINE> <DEDENT> return L | entrée : liste Li des cases et leurs valeurs de départ
sortie : liste L des cases du joueur 4
Le joueur 4 peut acheter toutes les cases
Fonction créant la liste des cases achetables par le joueur 4 | 625941dc5510c4643540f6d5 |
def tail(self, n=5): <NEW_LINE> <INDENT> return self.data.tail(n) | piping pandas tail function
| 625941dc82261d6c526ab79b |
def test(self): <NEW_LINE> <INDENT> extrinsicstate = 22 <NEW_LINE> fly = FlyweightFactory() <NEW_LINE> fx = fly.get_flyweight('X') <NEW_LINE> fx.operation(extrinsicstate - 1) <NEW_LINE> fy = fly.get_flyweight('Y') <NEW_LINE> fy.operation(extrinsicstate - 2) <NEW_LINE> fz = fly.get_flyweight('Z') <NEW_LINE> fz.operation... | 测试
:return: | 625941dcac7a0e7691ed43bf |
def flush_queue(queue): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> queue.get(block=False) <NEW_LINE> <DEDENT> except Empty: <NEW_LINE> <INDENT> break | Flush the queue.
:param queue: queue to flush
:return: Nothing | 625941dc63d6d428bbe447e8 |
def utf(text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> output = unicode(text, encoding='utf-8') <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> output = text <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> output = text <NEW_LINE> <DEDENT> except NameError: <NEW_LINE> <INDENT> output =... | Shortcut funnction for encoding given text with utf-8 | 625941dc6fb2d068a760f399 |
def weighted_projected_graph(B, nodes, ratio=False): <NEW_LINE> <INDENT> if B.is_multigraph(): <NEW_LINE> <INDENT> raise nx.NetworkXError("not defined for multigraphs") <NEW_LINE> <DEDENT> if B.is_directed(): <NEW_LINE> <INDENT> pred=B.pred <NEW_LINE> G=nx.DiGraph() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pred=B.... | Return a weighted unipartite projection of B onto the nodes of
one bipartite node set.
The weighted projected graph is the projection of the bipartite
network B onto the specified nodes with weights representing the
number of shared neighbors or the ratio between actual shared
neighbors and possible shared neighbors ... | 625941dc4d74a7450ccd44bb |
def test_positive_login(driver): <NEW_LINE> <INDENT> usarname_field = driver.find_element_by_id("input-username") <NEW_LINE> usarname_field.send_keys("admin") <NEW_LINE> time.sleep(1) <NEW_LINE> password_field = driver.find_element_by_id("input-password") <NEW_LINE> password_field.send_keys("12345") <NEW_LINE> password... | Docstring | 625941dc07d97122c4178b89 |
def db_for_read(self, model, **hints): <NEW_LINE> <INDENT> if model._meta.app_label == 'app1': <NEW_LINE> <INDENT> return 'form1_db' <NEW_LINE> <DEDENT> return None | Send all read operations on Example app models to `example_db`. | 625941dc91f36d47f21ac7ed |
def move(self, y, x, game_map, replacement=EmptyTile): <NEW_LINE> <INDENT> c = self.y, self.x <NEW_LINE> game_map.objects[c] = replacement(*c) <NEW_LINE> self.y, self.x = y, x <NEW_LINE> game_map.objects[y, x] = self | Moving a Ground will replace the Ground with an EmptyTile.
:param y:
:param x:
:param game_map:
:param replacement:
:return: | 625941dc23849d37ff7b3385 |
def base_domains(self): <NEW_LINE> <INDENT> return [s.base_domains() for s in self._strands] | Returns a list of the non-composite domain breakdown for each
strand in the complex. | 625941dcbe7bc26dc91cd8f3 |
def test_testing(): <NEW_LINE> <INDENT> sct.config.set_micro() <NEW_LINE> sweep_pars = dict(screen_keys = ['None', 'Antigen every 1w teach&staff', 'Antigen every 4w', 'PCR every 1w']) <NEW_LINE> mgr = sct.Manager(sweep_pars=sweep_pars, cfg=sct.config) <NEW_LINE> mgr.run(force=True) <NEW_LINE> sct.config.set_default() ... | Test COVID testing scenarios | 625941dc4e696a04525c9744 |
def cancel(self): <NEW_LINE> <INDENT> self.cancel_button.click() <NEW_LINE> self._wait_for_results_refresh() <NEW_LINE> return Conditions(self.testsetup) | Clicks on Cancel button and returns back to the PolicyView
@return: PolicyView | 625941dc45492302aab5e5bf |
def mult_inplace(self, x, y): <NEW_LINE> <INDENT> x *= y <NEW_LINE> return x | Multiplies `y` to `x`, in-place. `x` will be modified, but `y` will not.
Operation: :math:`x[i] *= y[i]`
Parameters
----------
x, y : NumPy arrays, shape (n,)
The arrays to multiply.
Returns
-------
x : NumPy array, shape (n,)
The resultant array. | 625941dc7cff6e4e81117c7d |
def test_1_2_simpl_iter(self): <NEW_LINE> <INDENT> options = {'minimize_every_iter': False} <NEW_LINE> run_test(test2_1, n=None, iters=7, options=options, sampling_method='simplicial') | Iterative simplicial on TestFunction 2 (univariate) | 625941dc21bff66bcd684c48 |
def test_80_newtask_age_ignore(self): <NEW_LINE> <INDENT> self.newtask_queue.put({ 'taskid': 'taskid', 'project': 'test_project', 'url': 'url', 'fetch': { 'data': 'abc', }, 'process': { 'data': 'abc', }, 'schedule': { 'age': 30, }, }) <NEW_LINE> time.sleep(0.1) <NEW_LINE> self.assertEqual(self.rpc.size(), 0) | processing = [ ] | 625941dc236d856c2ad44ad6 |
@conf <NEW_LINE> def load_android_tools(ctx): <NEW_LINE> <INDENT> android_sdk_home = ctx.env['ANDROID_SDK_HOME'] <NEW_LINE> build_tools_version = ctx.get_android_build_tools_version() <NEW_LINE> build_tools_dir = os.path.join(android_sdk_home, 'build-tools', build_tools_version) <NEW_LINE> try: <NEW_LINE> <INDENT> ctx.... | Loads the necessary build tools from the Android SDK | 625941dc377c676e912724a0 |
def load_data(time,info): <NEW_LINE> <INDENT> print(time) <NEW_LINE> atm=load_atm(time,info) <NEW_LINE> sfc=load_sfc(time,info) <NEW_LINE> return Bunch(sfc=sfc,atm=atm) | docstring for load_data | 625941dc7d847024c06be5b7 |
def export_iterobject(iterable, filename=None, logging=True): <NEW_LINE> <INDENT> def is_tty(): <NEW_LINE> <INDENT> return sys.stdout.isatty() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if filename: <NEW_LINE> <INDENT> with open(filename, 'w') as handle: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> handle.write(json.... | Summary:
pretty prints json, list, and tuple objects or exports iter
object schema to filesystem object on the local filesystem
Args:
:iterable (dict): dictionary, list, tuple, or complex object
:filename (str): name of file to be exported (optional)
Returns:
True | False Boolean export status | 625941dc0a50d4780f66718d |
def get_chapter_item(self, citem): <NEW_LINE> <INDENT> image_urls = self.get_chapter_image_urls(citem) <NEW_LINE> return ChapterItem( site=self.SITE, comicid=self.comicid, source_name=self.SOURCE_NAME, title=citem.title, chapter_number=citem.chapter_number, source_url=citem.source_url, image_urls=image_urls) | :return ChapterItem instance: | 625941dc4428ac0f6e5baaec |
def trial(self, seed): <NEW_LINE> <INDENT> if self.logNormal(): <NEW_LINE> <INDENT> self.log.header2("Trial "+str(seed+1)) <NEW_LINE> <DEDENT> obs = obsutils.sim(self.obs, nbins=self.m_enumbins, seed=seed, binsz=self.m_binsz, ... | Create the pull for a single trial.
Parameters:
seed - Random number generator seed | 625941dc94891a1f4081bda3 |
def lines(context): <NEW_LINE> <INDENT> pass | return lines | 625941dc6aa9bd52df03709d |
def set_alignments(self, alignment: list[swat_parser.AlignmentRecord]) -> None: <NEW_LINE> <INDENT> if alignment: <NEW_LINE> <INDENT> self.al_list.extend(alignment) <NEW_LINE> self.al_count = len(self.al_list) | A setter to update the list of AlignmentRecords for the sequence. Also
updates the count of AlignmentRecords.
Args:
alignment (list[swat_parser.AlignmentRecord]): a list of AlignmentRecord
objects belonging to this sequence. | 625941dc9f2886367277ab84 |
def soma(*x): <NEW_LINE> <INDENT> y = sum(x) <NEW_LINE> print ("A soma dos elementos é",y) | A funcao recebe uma sequencia de argumentos variaveis e retorna a soma destes. | 625941dc10dbd63aa1bd2e9b |
@mock.patch('spotifyconnect.player.lib', spec=spotifyconnect.lib) <NEW_LINE> @mock.patch('spotifyconnect.connection.lib', spec=spotifyconnect.lib) <NEW_LINE> def create_real_session(lib_mock, conn_lib_mock, player_lib_mock): <NEW_LINE> <INDENT> lib_mock.SpInit.return_value = spotifyconnect.ErrorType.Ok <NEW_LINE> playe... | Create a real :class:`spotifyconnect.Session` using ``lib_mock``. | 625941dc5510c4643540f6d6 |
def to_str_with_nl(array): <NEW_LINE> <INDENT> return '\n'.join(array) | Convert list to string by joining by new line.
Arguments:
array {list} -- List of strings
Returns:
str -- List of string joined by new linw | 625941dc3cc13d1c6d3c7672 |
def index_queryset(self, using=None): <NEW_LINE> <INDENT> return self.get_model().objects.all() | Cuando el index completo se actualiza | 625941dcbf627c535bc134c8 |
def test_commit_false_records_modified_by(self): <NEW_LINE> <INDENT> f = self.form({"name": "Foo", "cc_version": "0"}) <NEW_LINE> product = f.save(commit=False, user=self.user) <NEW_LINE> product.save() <NEW_LINE> self.assertEqual(product.modified_by, self.user) | modified_by user is still recorded even with commit=False. | 625941dc4527f215b584c74d |
def _create_example_context( self, platform_type='Android', browser_type=None, app_version='1.2.3', mode='DEV'): <NEW_LINE> <INDENT> return parameter_domain.EvaluationContext.from_dict( { 'platform_type': platform_type, 'browser_type': browser_type, 'app_version': app_version, }, { 'server_mode': getattr(ServerModes, m... | Creates and returns an EvaluationContext using the given
arguments. | 625941dce1aae11d1e749fb3 |
def eval(self, packet): <NEW_LINE> <INDENT> result = None <NEW_LINE> if self._when is None or self._when.eval(packet): <NEW_LINE> <INDENT> result = self._equation.eval(packet) <NEW_LINE> <DEDENT> return result | Returns the result of evaluating this DNToEUConversion in the
context of the given Packet. | 625941dc73bcbd0ca4b2c36f |
def extract_dependency_check(self, extracts=None): <NEW_LINE> <INDENT> child = aliased(Extract) <NEW_LINE> parent = aliased(Extract) <NEW_LINE> dependency_hold = 0 <NEW_LINE> if extracts is not None: <NEW_LINE> <INDENT> parent_files_hold = ( self.session.query(parent) .join(parent, ExtractDependency.parent_extract) .jo... | Determine if the extract file has any unloaded dependencies before trying to load the file.
:param extracts: List of ExtractTracking SQLAlchemy objects, provided if bulk updating status.
:return: | 625941dcb7558d58953c5208 |
def predict(self, data, num_iteration=-1, raw_score=False, pred_leaf=False, data_has_header=False, is_reshape=True): <NEW_LINE> <INDENT> if isinstance(data, Dataset): <NEW_LINE> <INDENT> raise TypeError("Cannot use Dataset instance for prediction, please use raw data instead") <NEW_LINE> <DEDENT> data = _data_from_pand... | Predict logic
Parameters
----------
data : string/numpy array/scipy.sparse
Data source for prediction
When data type is string, it represents the path of txt file
num_iteration : int
Used iteration for prediction
raw_score : bool
True for predict raw score
pred_leaf : bool
True for predict leaf ind... | 625941dc7047854f462a16ff |
def add_columns(self, other): <NEW_LINE> <INDENT> for i, j in zip(self._data, other.get_table()): <NEW_LINE> <INDENT> i += j <NEW_LINE> <DEDENT> return self | Concatenates rows self table with rows other table and return this table
Keyword arguments:
other -- table | 625941dc66673b3332b9238a |
def linear_mixing(self): <NEW_LINE> <INDENT> A = self.Job.Def['A'] <NEW_LINE> self.rhotot = (1-A)*self.rhotot + A*self.rho | Mix the new and the old density matrix by linear mixing.
The form of this mixing is
rho_out = (1-A)*rho_old + A*rho_new
for which, using our notation, rho_new is self.rho, rho_old is
self.rhotot and we overwrite self.rhotot to make rho_out. | 625941dcd4950a0f3b08c644 |
def get_cudnn_version(): <NEW_LINE> <INDENT> key = "cudnn_ver" <NEW_LINE> cmds = cmds_all[PLATFORM.lower()][key] <NEW_LINE> out, err = run_shell_cmd(cmds[0]) <NEW_LINE> if err and FLAGS.debug: <NEW_LINE> <INDENT> print("Error in finding `cudnn.h`:\n %s" % str(err)) <NEW_LINE> <DEDENT> if len(out.split(" ")) > 1: <NEW_L... | Retrieves the version of cuDNN library detected.
Returns:
String that is the version of cuDNN library detected.
e.g. '7.5.0' | 625941dccad5886f8bd272d2 |
def _update_firewall(self): <NEW_LINE> <INDENT> devices_to_filter = self.devices_to_filter <NEW_LINE> self.devices_to_filter = set() <NEW_LINE> self.refresh_firewall_required = False <NEW_LINE> device_list = set() <NEW_LINE> for device in devices_to_filter: <NEW_LINE> <INDENT> if device in self.ports_dict: <NEW_LINE> <... | Helper method to monitor devices added.
If devices_to_filter is not empty, we update the OVS firewall
for those devices. | 625941dc0fa83653e46572b2 |
@login_required <NEW_LINE> def list_(request): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> if user.is_superuser: <NEW_LINE> <INDENT> cluster_list = Cluster.objects.all() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cluster_list = user.get_objects_all_perms(Cluster, ['admin',]) <NEW_LINE> <DEDENT> return render_... | List all clusters | 625941dc004d5f362079a62b |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> for method in self.methods: <NEW_LINE> <INDENT> if method in kwargs: <NEW_LINE> <INDENT> self.method = method <NEW_LINE> <DEDENT> <DEDENT> if not self.method: <NEW_LINE> <INDENT> raise ValueError('Unknown method') <NEW_LINE> <DEDENT> if self.method == 'scale': <NEW_LINE... | :param kwargs: dict | 625941dc5fdd1c0f98dc052d |
def game_over(self, winner): <NEW_LINE> <INDENT> if winner == provided.DRAW: <NEW_LINE> <INDENT> self._label.set_text("It's a tie!") <NEW_LINE> <DEDENT> elif winner == provided.PLAYERX: <NEW_LINE> <INDENT> self._label.set_text("X Wins!") <NEW_LINE> <DEDENT> elif winner == provided.PLAYERO: <NEW_LINE> <INDENT> self._lab... | Game over | 625941dcd18da76e235327d2 |
def update_centroid_locations(self): <NEW_LINE> <INDENT> changes = [] <NEW_LINE> for clstr in self.clusters: <NEW_LINE> <INDENT> clstr.get_mean() <NEW_LINE> changes.append(clstr.is_changed()) <NEW_LINE> <DEDENT> self._any_changed = sum(changes) | Move centroid to the avg. location of its points | 625941dcab23a570cc25047d |
def _get_default_lstm_init( use_peepholes=False, use_projection=False): <NEW_LINE> <INDENT> initializers = copy.deepcopy(_DEFAULT_LSTM_INITIALIZERS) <NEW_LINE> if not use_peepholes: <NEW_LINE> <INDENT> for p_key in _PEEPHOLE_KEYS: <NEW_LINE> <INDENT> initializers.pop(p_key) <NEW_LINE> <DEDENT> <DEDENT> if not use_proje... | Returns LSTM initializers, possibly with some keys removed. | 625941dc57b8e32f52483796 |
def limit(value, v_min, v_max): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return min(max(value, v_min), v_max) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return None | limit a float or int python var
:param value: value to limit
:param v_min: minimum value
:param v_max: maximum value
:return: limited value | 625941dc3317a56b86939f4b |
def ids(self, content_ids, object_ids): <NEW_LINE> <INDENT> content_ids = self.split(content_ids, False) <NEW_LINE> object_ids = self.split(object_ids) <NEW_LINE> for cid in content_ids: <NEW_LINE> <INDENT> yield "{}:{}".format(cid, ":".join(object_ids)) | Appends the content and object ids how RETS expects them | 625941dceab8aa0e5d26de52 |
def execute_sql(self, query): <NEW_LINE> <INDENT> conn = self.psycopg2() <NEW_LINE> cur = conn.cursor() <NEW_LINE> cur.execute(query) <NEW_LINE> conn.commit() <NEW_LINE> conn.close() | Executes a sql command using a psycopg2 connection
:param query: query string
:return: none | 625941dc3d592f4c4ed1d360 |
def msg_check(template_id, length=[0]): <NEW_LINE> <INDENT> return { 'T_ID': 0, 'T_FLAG': 0, 'CLASS_NAME': UINT8 * 8, 'MSG_TYPE': UINT8, 'SRC_IPV4': UINT32, 'DST_IPV4': UINT32, 'SRC_PORT': UINT16, 'DST_PORT': UINT16, 'PROTO': UINT8, 'PKT_COUNT': UINT32, 'KBYTE_COUNT': UINT32, 'TIME_TYPE': UINT8, 'TIMEOUT': UINT16, 'ACT... | Checks the template ID and returns the hex length corresponding to it
Parameters
----------
template_id: int
The current position inside the data list
length:
The length of ACT PAR
Returns
-------
The hex length for the corresponding length name or 0 if no match | 625941dc796e427e537b08c1 |
def getTransMesh(self): <NEW_LINE> <INDENT> if self.mesh is None: <NEW_LINE> <INDENT> self.getMesh() <NEW_LINE> <DEDENT> lst = [self.selectedTransforms.item(i).obj for i in xrange(self.selectedTransforms.count())] <NEW_LINE> self.transMesh = transform_mesh(self.mesh, lst) <NEW_LINE> return 1 | Apply transformations to the domain. | 625941dc7d847024c06be5b8 |
def test_wrap_long_type(): <NEW_LINE> <INDENT> wrapped = _wrap_value(long_type(0)) <NEW_LINE> assert type(wrapped) == HyInteger | Test conversion of integers. | 625941dc956e5f7376d71165 |
def check_conflict_on_del(self, session, _id, db_content): <NEW_LINE> <INDENT> if session["force"]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> descriptor = db_content <NEW_LINE> descriptor_id = descriptor.get("id") <NEW_LINE> if not descriptor_id: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> _filter = self._get_p... | Check that there is not any NSD that uses this VNFD. Only NSDs belonging to this project are considered. Note
that VNFD can be public and be used by NSD of other projects. Also check there are not deployments, or vnfr
that uses this vnfd
:param session: contains "username", "admin", "force", "public", "project_id", "se... | 625941dc167d2b6e31218e8e |
def __init__(self, *args, **kwargs) -> None: <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._visited_ifs: Set[ast.If] = set() | We need to store visited ``if`` not to duplicate violations. | 625941dc3539df3088e2e644 |
def uniquePathsWithObstacles(self, obstacleGrid): <NEW_LINE> <INDENT> if obstacleGrid == []: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> height = len(obstacleGrid) <NEW_LINE> width = len(obstacleGrid[0]) <NEW_LINE> dp = [[0] * (width + 1) for _ in range(height + 1)] <NEW_LINE> for i in range(height - 1, -1, -1): <... | :type obstacleGrid: List[List[int]]
:rtype: int | 625941dcd486a94d0b98e440 |
def regression_residuals(phases): <NEW_LINE> <INDENT> num_traces = len(phases) <NEW_LINE> x = np.arange(num_traces) <NEW_LINE> slope, intercept, r_value, p_value, std_err = linregress(x,phases) <NEW_LINE> residuals = phases - (intercept + slope*x) <NEW_LINE> return slope, intercept, residuals | conducts a linear regression on the phases extracted with get_phases()
INPUT:
phases: Phase differences computed by function get_phases
---------------------------------------------------------------------------
OUTPUT:
slope: Slope of the regression line
intercept: Intercept of the regression line
residuals: Respect... | 625941dc91af0d3eaac9bd15 |
def main(): <NEW_LINE> <INDENT> args = parse_cli_args() <NEW_LINE> if args.api_scheme == 'http+unix': <NEW_LINE> <INDENT> adapter = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> adapter = adapters.UnixSocketRequest <NEW_LINE> <DEDENT> consul = consulate.Consul(args.api_host, args.api_port, args.dc, args.token, arg... | Entrypoint for the consulate cli application | 625941dcd58c6744b4257f58 |
def mergeAndSortIssues(dbd_issues, updated_issues): <NEW_LINE> <INDENT> def ascendingTimeOrder(t1, t2): <NEW_LINE> <INDENT> return cmp(t1['total_seconds'], t2['total_seconds']) <NEW_LINE> <DEDENT> def descendingTimeOrder(t1, t2): <NEW_LINE> <INDENT> return -cmp((t1['days'], t1['hours'], t1['minutes']), (t2['days'], t2[... | Add the issues that were updated to the lists of issues on the
dashboard and (re)sort them by priority. The priority will be the time, but
which order we want them in depends on the type of issue. | 625941dc1d351010ab855e15 |
def test_edit_vendor_get(self): <NEW_LINE> <INDENT> content_type = ContentType.objects.get_for_model( models.Vendor) <NEW_LINE> permission = Permission.objects.get( codename='change_vendor', content_type=content_type) <NEW_LINE> self.user.user_permissions.add(permission) <NEW_LINE> self.user.refresh_from_db() <NEW_LINE... | Test get url for creating edit vendor | 625941dc85dfad0860c3b155 |
def clear(): <NEW_LINE> <INDENT> globals()["_config"].clear() | Reset configuration to en empty state | 625941dcb7558d58953c5209 |
def _test_stembridge_local_axioms(self, index_set=None, verbose=False, **options): <NEW_LINE> <INDENT> tester = self._tester(**options) <NEW_LINE> goodness=True <NEW_LINE> if index_set is None: index_set=self.index_set() <NEW_LINE> for (i,j) in Subsets(index_set, 2): <NEW_LINE> <INDENT> if self.e(i) is not None and sel... | This implements tests for the Stembridge local characterization
on the element of a crystal ``self``.
The current implementation only uses the axioms for simply-laced
types. Crystals of other types should still pass the test, but
in non-simply-laced types, passing is not a guarantee that the
crystal arises from a rep... | 625941dc15fb5d323cde0e0d |
def __delitem__(self, key): <NEW_LINE> <INDENT> data = object.__getattribute__(self, 'data') <NEW_LINE> if key not in data: <NEW_LINE> <INDENT> raise AttributeError(key) <NEW_LINE> <DEDENT> order = object.__getattribute__(self, 'order') <NEW_LINE> comments = object.__getattribute__(self, 'comments') <NEW_LINE> del data... | Remove an item | 625941dc4f88993c3716c35f |
def icons_dir(name): <NEW_LINE> <INDENT> return os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + os.sep + os.path.pardir + os.sep + "iconsets" + os.sep + name + os.sep) | Returns the standard icon-sets directory. | 625941dc30dc7b7665901c5d |
def test_GHz(self): <NEW_LINE> <INDENT> q = quantity.Frequency(1.0,"GHz") <NEW_LINE> self.assertAlmostEqual(q.value, 1e9/(constants.c*100.), delta=1e-08) <NEW_LINE> self.assertAlmostEqual(q.value_si, 1e9/(constants.c*100.), delta=1e-08) <NEW_LINE> self.assertEqual(q.units, "cm^-1") | Test the creation of a frequency quantity with units of GHz. | 625941dc5fc7496912cc3c78 |
def expandGroups(self, templateGroups): <NEW_LINE> <INDENT> templateDict = self.templateDict <NEW_LINE> def expand(group): <NEW_LINE> <INDENT> group.name = group.name.format(**templateDict) <NEW_LINE> group.expandScenarios(self, templateDict) <NEW_LINE> self.groupDict[group.name] = group <NEW_LINE> <DEDENT> for templat... | Expand the `templateGroups`, which may contain names based
on iterators, into final scenarioGroups without iterators.
Recursively expands scenarios within groups. | 625941dc2eb69b55b151cbac |
def stopNode(context, peer): <NEW_LINE> <INDENT> nodeId = context.networkInfo["nodes"][peer]["nodeID"] <NEW_LINE> url = context.networkInfo["urls"]["stopURL"].format(IPaddress=context.networkInfo["IPaddress"], port=context.networkInfo["port"], networkID=context.networkInfo["networkID"], nodeID=nodeId) <NEW_LINE> body =... | Stops the peer node on a specific network. | 625941dcd8ef3951e3243838 |
def stratify(self, strata): <NEW_LINE> <INDENT> strata = ensure_list(strata) <NEW_LINE> check_columns(self, strata) <NEW_LINE> return self._handy._stratify(strata) | Stratify the HandyFrame.
Stratified operations should be more efficient than group by operations, as they
rely on three iterative steps, namely: filtering the underlying HandyFrame, performing
the operation and aggregating the results. | 625941dc21a7993f00bc7fee |
def __len__(self): <NEW_LINE> <INDENT> return len(self._nodes) | -------------------------------------------------------
Returns the number of nodes in the graph.
Use: n = len(g)
-------------------------------------------------------
Returns:
The number of node names in graph (int)
------------------------------------------------------- | 625941dca05bb46b383ecb1a |
def var_quadratic_sum(A, C, H, beta, x0): <NEW_LINE> <INDENT> A, C, H = list(map(np.atleast_2d, (A, C, H))) <NEW_LINE> x0 = np.atleast_1d(x0) <NEW_LINE> Q = scipy.linalg.solve_discrete_lyapunov(sqrt(beta) * A.T, H) <NEW_LINE> cq = dot(dot(C.T, Q), C) <NEW_LINE> v = np.trace(cq) * beta / (1 - beta) <NEW_LINE> q0 = dot(d... | Computes the expected discounted quadratic sum
.. math::
q(x_0) = \mathbb{E} \Big[ \sum_{t=0}^{\infty} \beta^t x_t' H x_t \Big]
Here :math:`{x_t}` is the VAR process :math:`x_{t+1} = A x_t + C w_t`
with :math:`{x_t}` standard normal and :math:`x_0` the initial condition.
Parameters
----------
A : array_like(flo... | 625941dc07d97122c4178b8b |
def _json_object_hook(d: Dict[Any, Any]) -> Tuple: <NEW_LINE> <INDENT> return namedtuple('params', d.keys())(*d.values()) | Transform a dictionary into a namedtuple. | 625941dc5fcc89381b1e19bc |
def test_get_window(self): <NEW_LINE> <INDENT> expected_gate = np.ones(self.stop_pos - self.start_pos) <NEW_LINE> expected_gate_list = expected_gate.tolist() <NEW_LINE> returned_gate_list = self.sample_gate.get_window().tolist() <NEW_LINE> for idx in range(len(expected_gate_list)): <NEW_LINE> <INDENT> self.assertAlmost... | Verify the base UltrasonicGate class returns a no-op window | 625941dc45492302aab5e5c0 |
def test_lut_transform(self): <NEW_LINE> <INDENT> log.basicConfig( format='%(levelname)s %(asctime)s %(message)s', level=log.INFO ) <NEW_LINE> input_symbols_list = [np.array([-4, 31, 90, 172], np.uint64), np.array([], np.uint64), np.array([0, 0, 0, 0, 0, 0], np.uint64)] <NEW_LINE> log.info( "testing {} input symbol s... | Test all round trips.
:return: | 625941dca219f33f34628c60 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.