code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self, poly, prec, print_mode, names, element_class): <NEW_LINE> <INDENT> self._given_poly = poly <NEW_LINE> R = poly.base_ring() <NEW_LINE> print_mode['unram_name'] = names[2] <NEW_LINE> print_mode['ram_name'] = names[3] <NEW_LINE> print_mode['var_name'] = names[0] <NEW_LINE> names = names[0] <NEW_LINE> pA... | Initialization
EXAMPLES::
sage: R = Zp(5,5)
sage: S.<x> = R[]
sage: f = x^5 + 75*x^3 - 15*x^2 +125*x - 5
sage: W.<w> = R.ext(f) #indirect doctest | 625941ca23849d37ff7b313d |
def _aggregate_region( df, variable, region, subregions=None, components=False, method="sum", weight=None, drop_negative_weights=True, ): <NEW_LINE> <INDENT> if not isstr(variable) and components is not False: <NEW_LINE> <INDENT> raise ValueError( "Aggregating by list of variables with components is not supported!" ) <... | Internal implementation for aggregating data over subregions | 625941ca91af0d3eaac9bac6 |
def pagepanel(self, d): <NEW_LINE> <INDENT> _ = self.request.getText <NEW_LINE> dummy = self.getImageURI('1-pix.png') <NEW_LINE> if self.shouldShowEditbar(d['page']): <NEW_LINE> <INDENT> html = [ u'<div class="bottompanel">', u'<div style="width:0%;height:0px;">', u'<a name="edit" id="edit" title="%s">' % _('Edit and a... | Create page panel | 625941cad58c6744b4257d0e |
def visit(self, node): <NEW_LINE> <INDENT> if not isinstance(node, list): <NEW_LINE> <INDENT> return super().visit(node) <NEW_LINE> <DEDENT> for elem in node: <NEW_LINE> <INDENT> super().visit(elem) <NEW_LINE> <DEDENT> return node | Like super-visit but supports iteration over lists. | 625941ca99fddb7c1c9de43f |
def _call_eject_later(self, device, timeout): <NEW_LINE> <INDENT> eventloop.add_timeout(timeout, self.eject_device, 'ejecting device', args=(device,)) | Call eject_device after a short delay. | 625941caa4f1c619b28b00e8 |
def Create(self, the_points = None): <NEW_LINE> <INDENT> self.ClearPoints() <NEW_LINE> if not the_points: <NEW_LINE> <INDENT> self._originalPoints = [] <NEW_LINE> self._points = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._originalPoints = the_points <NEW_LINE> self._points = [] <NEW_LINE> for point in the_po... | Takes a list of :class:`wx.Points` or tuples; each point is an offset
from the centre. | 625941ca44b2445a33932144 |
def merge(output, *profiles): <NEW_LINE> <INDENT> raw_x, raw_y = [],[] <NEW_LINE> model = 0 <NEW_LINE> for profile in profiles: <NEW_LINE> <INDENT> print("Reading " + profile + "...") <NEW_LINE> try: <NEW_LINE> <INDENT> with open(PROFILE_FILE.format(profile),'rb') as profileFile: <NEW_LINE> <INDENT> x, y, model = pickl... | merge profile raw data, the model needs to be generated again. | 625941ca1b99ca400220ab5f |
def unique_id(self): <NEW_LINE> <INDENT> return _foo_swig.periodic_msg_source_sptr_unique_id(self) | unique_id(self) -> long | 625941ca507cdc57c6306d87 |
def get_logs(self, cr, uid, ids, cron_mode=True, context=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = get_sys_logs(cr, uid) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> if cron_mode: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> _logger.debug("Exception while... | Send a message to OpenERP's publisher warranty server to check the validity of
the contracts, get notifications, etc...
@param cron_mode: If true, catch all exceptions (appropriate for usage in a cron).
@type cron_mode: boolean | 625941cad10714528d5ffd90 |
def bad_singing(): <NEW_LINE> <INDENT> time.sleep(2) <NEW_LINE> port = 'sim' <NEW_LINE> hal = new_create.Create(port) <NEW_LINE> hal.toSafeMode() <NEW_LINE> for k in range(31, 127): <NEW_LINE> <INDENT> hal.playNote(k, 16) <NEW_LINE> <DEDENT> song = [(60, 32), (64, 32), (67, 32), (72, 32)] <NEW_LINE> hal.playSong(song) ... | Demonstrates the effect of sending a new note/song before the
old one has finished. Try running this both in the simulator
and with a real robot (expect strange results with the latter). | 625941ca7c178a314d6ef50d |
def on_new(self,evnt): <NEW_LINE> <INDENT> bar_pos = self.GetScreenPosition()-self.parent.GetScreenPosition() <NEW_LINE> tool_index = self.GetToolPos(evnt.GetId()) <NEW_LINE> tool_size = self.GetToolSize() <NEW_LINE> lower_left_pos = (bar_pos[0]+self.GetToolSeparation()*(tool_index+1)+tool_size[0]*tool_index, bar_pos[1... | Handle 'new' button pressed.
Creates a popup menu over the tool button containing the same entries as
the File->New menu. | 625941ca38b623060ff0ae9b |
@app.route('/api/posts/', methods=['GET']) <NEW_LINE> def posts_get(): <NEW_LINE> <INDENT> from ghostwriter.Post import Post, PostManager <NEW_LINE> pm = PostManager() <NEW_LINE> posts = pm.getAllPosts() <NEW_LINE> if len(posts) <= 0: <NEW_LINE> <INDENT> return jsonify({'error': 'No posts found'}), 404 <NEW_LINE> <DEDE... | Gets all posts
Returns a JSON with their information, without content data | 625941ca10dbd63aa1bd2c51 |
def VerifyScript(scriptSig, scriptPubKey, txTo, inIdx, flags=()): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> EvalScript(stack, scriptSig, txTo, inIdx, flags=flags) <NEW_LINE> if SCRIPT_VERIFY_P2SH in flags: <NEW_LINE> <INDENT> stackCopy = list(stack) <NEW_LINE> <DEDENT> EvalScript(stack, scriptPubKey, txTo, inIdx, flags... | Verify a scriptSig satisfies a scriptPubKey
scriptSig - Signature
scriptPubKey - PubKey
txTo - Spending transaction
inIdx - Index of the transaction input containing scriptSig
Raises a ValidationError subclass if the validation fails. | 625941ca0fa83653e4657069 |
def get_csv_data(data): <NEW_LINE> <INDENT> row = dict() <NEW_LINE> for item in _CSV_ANALYSIS_HEADER_MEASURES: <NEW_LINE> <INDENT> row[item] = data[item] <NEW_LINE> <DEDENT> for item in NOMINALIZATION_SUFFIXES: <NEW_LINE> <INDENT> row[item] = data['Nominalizations'].get(item, None) <NEW_LINE> <DEDENT> for item in ADDIT... | Converts a dictionary of analyzed file data to a list of CSV row
entries.
Arguments:
data (dict): The data to format.
Returns:
(list): A list of CSV columns for the given data.
Use CSV_ANALYSIS_HEADER to get a header for the data produced by this
function. | 625941ca187af65679ca51cc |
def generate_local_index(directory: str) -> List[Metadata]: <NEW_LINE> <INDENT> metadata = get_metadata_for_directory(directory) <NEW_LINE> get_track_data = get_musicbrainz_data() <NEW_LINE> enriched_metadata = [get_track_data(i) for i in metadata] <NEW_LINE> return enriched_metadata | generate_local_index : generate an index (list of dicts) of music data
arguments:
- directory : full path to root of media for which we want to generate index
returns list of dict with musicbrainz ids and names and file format | 625941caa8ecb033257d317b |
@files(None, tempdir + 'a.5') <NEW_LINE> @follows(mkdir(tempdir)) <NEW_LINE> @posttask(lambda: do_write(test_file, "Task 5 Done\n")) <NEW_LINE> def task5(infiles, outfiles, *extra_params): <NEW_LINE> <INDENT> with open(tempdir + "jobs.start", "a") as oo: <NEW_LINE> <INDENT> oo.write('job = %s\n' % json.dumps([infiles,... | Fifth task is extra slow | 625941ca66673b3332b9213f |
def replaceAfterMRWithBlank(s): <NEW_LINE> <INDENT> s = _replaceAfterStrWithBlank(s, "M=") <NEW_LINE> s = _replaceAfterStrWithBlank(s, "R=") <NEW_LINE> return s | @description
With input string 's', everything after M=, or R= on each line is replaced
with nothing.
Helper for _compareStrings3() of library unit tests.
@arguments
s -- string
@return
modified_s -- string
@exceptions
@notes | 625941ca56ac1b37e626427e |
def get_remote_ip(self, process): <NEW_LINE> <INDENT> gw2 = psutil.Process(self.get_pid(process)) <NEW_LINE> connections = gw2.connections() <NEW_LINE> if connections and len(connections) > 2: <NEW_LINE> <INDENT> return gw2.connections()[-1].raddr[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None | Returns the most recent remote connection IP address for a given process. | 625941ca507cdc57c6306d88 |
def test14_search_roles(self): <NEW_LINE> <INDENT> print_test_name() <NEW_LINE> try: <NEW_LINE> <INDENT> roles = review.find_roles(Role(name='Customer*')) <NEW_LINE> for role in roles: <NEW_LINE> <INDENT> print_role(role) <NEW_LINE> <DEDENT> <DEDENT> except RbacError as e: <NEW_LINE> <INDENT> print_exception(e) <NEW_LI... | Search for roles that match the characters passed into with wildcard appended. Will return zero or more records, one for each user in result set. | 625941ca38b623060ff0ae9c |
def get_martian_version(): <NEW_LINE> <INDENT> return _INSTANCE.jobinfo.version["martian"] | Get the martian version from the jobinfo. | 625941ca090684286d50ed93 |
def model_get_cover(self, model): <NEW_LINE> <INDENT> cover = '' <NEW_LINE> if MF.v2 in model.meta.flags: <NEW_LINE> <INDENT> if MF.normal in model.meta.flags: <NEW_LINE> <INDENT> cover = model.cover <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if ModelType(model.meta.model_type) in (ModelType.album, ModelType.video):... | Get the model cover url
:return: cover url if exists, else '' | 625941ca5fcc89381b1e176d |
def rule_from_pv(volume, storage_class, use_claim_name=False): <NEW_LINE> <INDENT> provisioner = storage_class.get('provisioner') <NEW_LINE> if provisioner != 'kubernetes.io/gce-pd': <NEW_LINE> <INDENT> logger.debug('Volume {volume} not a GCE persistent disk (provisioner={provisioner})'.format(volume=volume.name, provi... | Given a persistent volume object, create a backup role
object. Can return None if this volume is not configured for
backups, or is not suitable.
`use_claim_name` - if the persistent volume is bound, and it's
name is auto-generated, then prefer to use the name of the claim
for the snapshot. | 625941ca236d856c2ad44888 |
def get_payment(self, name): <NEW_LINE> <INDENT> Payment = Pool().get('sale.payment') <NEW_LINE> payments = Payment.search([('sale', '=', self.id)]) <NEW_LINE> if name == 'payment_total': <NEW_LINE> <INDENT> return Decimal(sum([payment.amount for payment in payments])) <NEW_LINE> <DEDENT> elif name == 'payment_availabl... | Return amount from payments.
| 625941ca435de62698dfdcfb |
def main(): <NEW_LINE> <INDENT> print('Loading data for map 27') <NEW_LINE> m = mapparser.MapParser.fromURL('http://dominating12.com/lib/ajax/api/map-info.php?map_id=27') <NEW_LINE> print('Loaded the map:', m.name) <NEW_LINE> for v in m.territories.values(): <NEW_LINE> <INDENT> print(v.name, 'at', v.x, ',', v.y) | The main entrypoint for this application | 625941caaad79263cf390aef |
def int_to_darkened_color(color_int): <NEW_LINE> <INDENT> return int_to_color((color_int >> 1) & 0x7f7f7f) | Returns a color string from a 24bits integer with all components halved | 625941ca3617ad0b5ed67fa6 |
def _out(self, X, y, added_var, other_var, alpha_out, df, iter_): <NEW_LINE> <INDENT> n, p = X.shape <NEW_LINE> t_out_critical = critical_value('t', alpha_out, dfs=(n-len(added_var)-1)) <NEW_LINE> lr = LinearRegression() <NEW_LINE> lr.fit(X[:,added_var], y) <NEW_LINE> if np.all(np.abs(lr.t_) > t_out_critical): <NEW_LIN... | Take out a variable from added_var to other_var based on given information.
It will return the tag and df, which tag is mean to success to delete a variable
from model if tag is True, otherwise is False.
And df is the updated df.
The result of added_var and other_var is modified inplace. | 625941ca1f5feb6acb0c4c00 |
def release(self): <NEW_LINE> <INDENT> result = stack_lock_object.StackLock.release(self.stack_id, self.engine_id) <NEW_LINE> if result is True: <NEW_LINE> <INDENT> LOG.warn(_LW("Lock was already released on stack %s!"), self.stack_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> LOG.debug("Engine %(engine)s released ... | Release a stack lock. | 625941cafbf16365ca6f6272 |
def sample_ingredient(user, name='Rice noodles'): <NEW_LINE> <INDENT> return Ingredient.objects.create(user=user, name=name) | Create and return a sample ingredient | 625941ca6fb2d068a760f14b |
def fit(self, X, y=None): <NEW_LINE> <INDENT> self.fill = pd.Series([X[c].value_counts().index[0] if X[c].dtype == np.dtype('O') else X[c].median() for c in X], index=X.columns) <NEW_LINE> return self | Replace NaN with median if noncategorical, otherwise mode | 625941ca8c0ade5d55d3ea69 |
def upload_batch_to_s3(location): <NEW_LINE> <INDENT> uploaded_files = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for root, dirs, files in os.walk(location): <NEW_LINE> <INDENT> for file in files: <NEW_LINE> <INDENT> if file.endswith(".json"): <NEW_LINE> <INDENT> s3.upload_file( os.path.join(root, file), S3_BUCKET_NAME, fi... | Upload batch to Amazon S3
:param location: Local file path
:return: S3 link otherwise exception | 625941cadc8b845886cb55e3 |
def get_random_user_agent(self): <NEW_LINE> <INDENT> return random.choice(self.ua_list) | Get a random user agent string.
Returns:
str: Random user agent string. | 625941ca3346ee7daa2b2e19 |
def __new__(cls, *args, **kwargs): <NEW_LINE> <INDENT> if cls is not AoAStitcher: <NEW_LINE> <INDENT> return super(AoAStitcher, cls).__new__(cls) <NEW_LINE> <DEDENT> return AoAStitcherHorn() | Legacy: by default returns AoAStitcherHorn instance. | 625941ca23e79379d52ee613 |
def get_cleanup_directory_path(root_directory_path): <NEW_LINE> <INDENT> cleanup_directory_path = os.path.join(root_directory_path, 'Tools', 'lmbr_aws') <NEW_LINE> if not os.path.isdir(cleanup_directory_path): <NEW_LINE> <INDENT> raise RuntimeError('The lmbr_aws tool does not contain a test directory: {}'.format(cleanu... | Determines the path to the cleanup.py module | 625941ca046cf37aa974cdf7 |
def __init__(self, parent, name, namespace, count, source): <NEW_LINE> <INDENT> display = self.fmt % (name, count) if count > 1 else name <NEW_LINE> super(CapaExplorerRuleItem, self).__init__(parent, [display, "", namespace]) <NEW_LINE> self._source = source | initialize item
@param parent: parent node
@param name: rule name
@param namespace: rule namespace
@param count: number of match for this rule
@param source: rule source (tooltip) | 625941cac4546d3d9de72ae2 |
def setSettingString(self, id, value): <NEW_LINE> <INDENT> return self.setSetting(id, ensure_unicode(value)) | Sets a script setting.
:param str id: string - id of the setting that the module needs to access.
:param value: string or unicode - value of the setting.
:returns: True if the value of the setting was set, false otherwise
:rtype: bool
.. note:: You can use the above as keywords for arguments.
Example::
self.Ad... | 625941ca2c8b7c6e89b35870 |
def test_default_values(self): <NEW_LINE> <INDENT> image = self._get_image() <NEW_LINE> self.assertIsNotNone(image.pub_date) <NEW_LINE> self.assertEqual('', image.legend) <NEW_LINE> self.assertEqual('', image.description) <NEW_LINE> self.assertIsNone(image.license) <NEW_LINE> self.assertIsNotNone('', image.img_original... | Test default values of newly created image attachment. | 625941ca5f7d997b87174b46 |
def load(self): <NEW_LINE> <INDENT> self.group = [] <NEW_LINE> with open(self.group_file, 'r') as f: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> rawline = f.readline() <NEW_LINE> if not rawline: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> line = rawline.strip() <NEW_LINE> if not line: <NEW_LINE> <INDENT> cont... | Load /etc/group | 625941ca56ac1b37e626427f |
def cmdloop(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> cmd = input(self.prompt() + ' > ') <NEW_LINE> if cmd == self._exitcmd: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> b = self.exec(cmd) <NEW_LINE> if b: <NEW_LINE> <INDENT> print('[Execute failure]', cmd) <NEW_LINE> <DEDENT>... | startup a command loop | 625941caa05bb46b383ec8d0 |
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'volumes': 'list[V2appsContainerVolumes]', 'type': 'str', 'docker': 'V2appsContainerDocker' } <NEW_LINE> self.attribute_map = { 'volumes': 'volumes', 'type': 'type', 'docker': 'docker' } <NEW_LINE> self._volumes = None <NEW_LINE> self._type = None <NEW_LINE... | V2appsContainer - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941caab23a570cc250231 |
def query_room(self, room): <NEW_LINE> <INDENT> return self._bot.query_room(room=room) | Query a room for information.
:param room:
The JID/identifier of the room to query for.
:returns:
An instance of :class:`~errbot.backends.base.MUCRoom`.
:raises:
:class:`~errbot.backends.base.RoomDoesNotExistError` if the room doesn't exist. | 625941ca4f6381625f114ae9 |
def read(url=""): <NEW_LINE> <INDENT> with open(url, 'r') as f: <NEW_LINE> <INDENT> cnt = f.read() <NEW_LINE> <DEDENT> return cnt | Read and return content of resource
__plugin__: node
Args:
url: (url) path to resource
Returns:
(str) content of resource | 625941ca462c4b4f79d1d77f |
def test_stopObserving(self): <NEW_LINE> <INDENT> self.result.done() <NEW_LINE> self.stream.seek(0) <NEW_LINE> self.stream.truncate() <NEW_LINE> self.publisher.msg( warning=RuntimeWarning("some message"), category="exceptions.RuntimeWarning", filename="file/name.py", lineno=17, ) <NEW_LINE> self.assertEqual(self.stream... | L{reporter.Reporter} stops observing log events when its C{done} method
is called. | 625941cade87d2750b85fe41 |
def migrate_compsoc_memberinfo(): <NEW_LINE> <INDENT> websites = WebsiteDetails.objects.using('old_data').all() <NEW_LINE> nicks = NicknameDetails.objects.using('old_data').all() <NEW_LINE> shell_accounts = OldShellAccount.objects.using('old_data').all() <NEW_LINE> db_accounts = OldDatabaseAccount.objects.using('old_da... | Amalgamates the old user detail objects into the new CompsocUser and other models | 625941ca91f36d47f21ac5a1 |
def plot_result(self): <NEW_LINE> <INDENT> if self.run_completed == False: <NEW_LINE> <INDENT> print("Warning calling the plot_result() method: \nGA is not executed yet and there are no results to display. Please call the run() method before calling the plot_result() method.\n") <NEW_LINE> <DEDENT> matplotlib.pyplot.fi... | Creating 2 plots that summarizes how the solutions evolved.
The first plot is between the iteration number and the function output based on the current parameters for the best solution.
The second plot is between the iteration number and the fitness value of the best solution. | 625941cab830903b967e99ba |
def clicked(self, _event_box, _event_button): <NEW_LINE> <INDENT> pass | User clicks on camera widget | 625941ca4f6381625f114aea |
def setZeroes(self, matrix: List[List[int]]) -> None: <NEW_LINE> <INDENT> m = len(matrix) <NEW_LINE> n = len(matrix[0]) <NEW_LINE> i = 0 <NEW_LINE> j = 0 <NEW_LINE> row_zero = set() <NEW_LINE> col_zero = set() <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> for j in range(n): <NEW_LINE> <INDENT> if matrix[i][j] == 0:... | Do not return anything, modify matrix in-place instead. | 625941ca6aa9bd52df036e53 |
def get_result_dir_name(fullpathname): <NEW_LINE> <INDENT> for i, c in enumerate(reversed(fullpathname)): <NEW_LINE> <INDENT> if c == '.': <NEW_LINE> <INDENT> return fullpathname[:(-i - 1)] | Iterates over path chars, get the first dot position, drop each char after and return the name
:param fullpathname: file path
:return: result directory name | 625941ca379a373c97cfabf3 |
def get_conditional_probability(self, values, evidents): <NEW_LINE> <INDENT> res = 1 <NEW_LINE> if self.varsMap[list(values.keys())[0]].is_child_of(self.varsMap[list(evidents.keys())[0]]): <NEW_LINE> <INDENT> if all(self.varsMap[list(values.keys())[0]].is_child_of(self.varsMap[evident]) for evident in evidents.keys()):... | returns the conditional probability.
Here I do not introduce advanced algorithms for inference (e.g. junctions trees)
this method implement only simple inference, namely: the joint probability of children given their parents
or the probability of parents given their children.
assumption: variables in each level are ind... | 625941ca97e22403b379d048 |
def __init__(self, structure, device, temp_unit): <NEW_LINE> <INDENT> self._unit = temp_unit <NEW_LINE> self.structure = structure <NEW_LINE> self.device = device <NEW_LINE> self._fan_list = [STATE_ON, STATE_AUTO] <NEW_LINE> self._operation_list = [STATE_OFF] <NEW_LINE> if self.device.can_heat: <NEW_LINE> <INDENT> self... | Initialize the thermostat. | 625941ca8e7ae83300e4b07b |
def same(formula1, formula2): <NEW_LINE> <INDENT> if isinstance(formula1, compile.Literal): <NEW_LINE> <INDENT> if isinstance(formula2, compile.Rule): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif formula1.is_negated() != formula2.is_negated(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_L... | Check formulas are the same.
Determine if FORMULA1 and FORMULA2 are the same up to a variable
renaming. Treats FORMULA1 and FORMULA2 as having different
variable namespaces. Returns None or the pair of unifiers. | 625941ca73bcbd0ca4b2c125 |
def result_url(request, uri, headers): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert request.headers["content-type"] == "application/json", ( "ckanserviceprovider should post to result URLs with " "content-type application/json") <NEW_LINE> data = json.loads(request.body) <NEW_LINE> data.pop('requested_timestamp'... | Handle a request to the mocked result URL. | 625941caf548e778e58cd62c |
def TransformBasedRegistration(fix_image, moving_image, target_image, register_method=sitk.sitkBSpline, transform_method=sitk.sitkNearestNeighbor): <NEW_LINE> <INDENT> fix_image = sitk.GetImageFromArray(fix_image) <NEW_LINE> moving_image = sitk.GetImageFromArray(moving_image) <NEW_LINE> target_image = sitk.GetImageFrom... | Calculate the transform based on the registration from the moving image
to the fixed image, then applied this transform on the target image.
Yang Song, Sep-21-2017 | 625941ca8e71fb1e9831d858 |
def nd_reduced_pressure(self, depthFn, temperatureField, depthPh, clapPh, tempPh): <NEW_LINE> <INDENT> return (depthFn - depthPh) - clapPh*(temperatureField - tempPh) | Creates an Underworld function, representing the 'reduced pressure' | 625941ca4f88993c3716c116 |
def empty(self) -> bool: <NEW_LINE> <INDENT> if len(self.deque1) ==0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False | Returns whether the stack is empty. | 625941ca442bda511e8be4c8 |
def test_api_can_create_an_employee(self): <NEW_LINE> <INDENT> employee_data = { 'name': 'Person One', 'email': 'person.one@testcompany.com', 'department_id': self.department.id } <NEW_LINE> response = self.client.post( reverse('employees'), employee_data, format='json' ) <NEW_LINE> self.assertEqual(response.status_cod... | Test if api has employee creation capability. | 625941cadd821e528d63b258 |
def check_versions(provided_version=None): <NEW_LINE> <INDENT> if provided_version is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> agent_version = get_current_versions() <NEW_LINE> if provided_version != agent_version: <NEW_LINE> <INDENT> LOG.warning('Mismatched hardware managers versions. Agent version: ' '%(a... | Ensure the version of hardware managers hasn't changed.
:param provided_version: Hardware manager versions used by ironic.
:raises: errors.VersionMismatch if any hardware manager version on
the currently running agent doesn't match the one stored in
provided_version.
:returns: None | 625941ca32920d7e50b2827e |
def shearXY3(x, y): <NEW_LINE> <INDENT> out = identity(3) <NEW_LINE> out[0][3] = x <NEW_LINE> out[1][3] = y <NEW_LINE> return out | Shear on XY. | 625941ca6fb2d068a760f14c |
def add(self, key, val): <NEW_LINE> <INDENT> if self.tree.insert(key, val): <NEW_LINE> <INDENT> self.length += 1 | param key: numero o stringa
param val: numero o stringa | 625941ca67a9b606de4a7f69 |
def practice_problem3e(sequence): <NEW_LINE> <INDENT> seq = [] <NEW_LINE> for k in range(len(sequence)): <NEW_LINE> <INDENT> if k % 2 == 0: <NEW_LINE> <INDENT> seq = seq + [sequence[k]] <NEW_LINE> <DEDENT> <DEDENT> total = 0 <NEW_LINE> for k in range(len(seq)): <NEW_LINE> <INDENT> total = total + seq[k] <NEW_LINE> <DED... | What comes in:
A sequence of numbers.
What goes out:
Returns the sum of the numbers at EVEN INDICES of the sequence.
Side effects: None.
Examples:
If the sequence is:
(12, 33, 18, 9, 13, 3, 99, 20, 19, 20)
then this function returns
12 + 18 + 13 + 99 + 19, which is 161.
Type hints:
:type sequence... | 625941ca566aa707497f4619 |
def find_homography_normalized(p1,p2,robust=True): <NEW_LINE> <INDENT> p1,p2,N1,N2 = normalize_points(p1,p2) <NEW_LINE> if robust: <NEW_LINE> <INDENT> method=cv2.LMEDS <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> method=0 <NEW_LINE> <DEDENT> H_, inliers = cv2.findHomography(p1.astype('float32'), p2.astype('float32'), ... | Get best estimate of homography.
Parameters:
robust : bool, optional
If set to True (default), use LMedS estimation. If set to False,
use least squares. | 625941ca498bea3a759b9b5e |
def get_most_freq(data, n): <NEW_LINE> <INDENT> data_dict = defaultdict(int) <NEW_LINE> for name, sex in data: <NEW_LINE> <INDENT> data_dict[name] += 1 <NEW_LINE> <DEDENT> most_freq = sorted(data_dict, key=data_dict.get, reverse=True) <NEW_LINE> return [(name, data_dict[name]) for name in most_freq[:n]] | Finds the n most frequent items in data
args: data (list of tuples (name, sex)), n
returns: list of names (str) | 625941ca462c4b4f79d1d780 |
def filter_by_callsign(self, model, iter, data): <NEW_LINE> <INDENT> value = model.get_value(iter, 1) <NEW_LINE> callsign = self.application.toolbar.filter_source.get_text() <NEW_LINE> if(callsign is None or callsign == ""): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return callsign.u... | Filter all the logs in the logbook by the callsign field, based on a user-defined expression.
:arg Gtk.TreeModel model: The model used to filter the log data.
:arg Gtk.TreeIter iter: A pointer to a particular row in the model.
:arg data: The user-defined expression to filter by.
:returns: True if a record matches the ... | 625941cab545ff76a8913ec6 |
def sce2s(sc, et): <NEW_LINE> <INDENT> return _cspyce0.sce2s(sc, et) | sce2s(SpiceInt sc, SpiceDouble et) | 625941ca66673b3332b92140 |
def _group_xys_by_adjacency(self, xys): <NEW_LINE> <INDENT> d = defaultdict(list) <NEW_LINE> for x, y in xys: <NEW_LINE> <INDENT> d[y].append((x,y)) <NEW_LINE> <DEDENT> for k, v in d.items(): <NEW_LINE> <INDENT> d[k] = self._group_xys_by_consective_x(v) <NEW_LINE> <DEDENT> ys = sorted(d.keys()) <NEW_LINE> groups = [com... | Get the groups of consective xys given scattered xys.
Args:
xys (list): the xys to be grouped | 625941ca004d5f362079a3e2 |
def encode_auth_token(self, user): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return jwt_encode_handler(user) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return e | django user 对象 或者包含Django user对象的一个列表
:param user:
:return:
| 625941ca627d3e7fe0d68efe |
def colours(self, data): <NEW_LINE> <INDENT> if isinstance(data, numpy.ndarray): <NEW_LINE> <INDENT> if data.dtype != numpy.uint32: <NEW_LINE> <INDENT> return self.rgba(data) <NEW_LINE> <DEDENT> self._loadScalar(data, LavaVuPython.lucRGBAData) <NEW_LINE> return <NEW_LINE> <DEDENT> if isinstance(data, str): <NEW_LINE> <... | Load colour data for object
Parameters
----------
data : str or list or array
Pass a list or numpy uint32 array of colours
if a string or list of strings is provided, colours are parsed as html colour string values
if a numpy array is passed, colours are loaded as 4 byte ARGB unsigned integer values | 625941cabf627c535bc1327e |
def deinit(self): <NEW_LINE> <INDENT> for pixel_index in range(len(self)): <NEW_LINE> <INDENT> self[pixel_index] = BLACK | Blank out the NeoPixels and release the pin. | 625941ca99cbb53fe6792c96 |
def _safe(self): <NEW_LINE> <INDENT> with open(self.versions_file, 'w') as f: <NEW_LINE> <INDENT> json.dump(self.version_dict, f) | Safe version json file to remember everything.
| 625941ca377c676e91272258 |
def total_product(dec_conf={}, param_conf={}, attr_conf={}, fman_conf={}, param_trial_conf={}, sequential_keys=False): <NEW_LINE> <INDENT> full_conf = deepcopy(dec_conf) <NEW_LINE> full_conf.update(param_conf) <NEW_LINE> full_conf.update(attr_conf) <NEW_LINE> full_conf.update(param_trial_conf) <NEW_LINE> full_conf.upda... | Combines multiple types of model changes into a single configuration
for the Ensemble object. | 625941cabe383301e01b5536 |
def returns(data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> trading_days = len(data) <NEW_LINE> logger.info( "Calculating Returns for {} trading days".format(trading_days)) <NEW_LINE> df = pd.DataFrame() <NEW_LINE> df['daily_returns'] = data.pct_change(1) <NEW_LINE> mean_daily_returns = df['daily_returns'].mean() <... | Returns for any number of days | 625941cad4950a0f3b08c3fe |
def elementValue(self, dom_element): <NEW_LINE> <INDENT> r = StringIO() <NEW_LINE> advene.model.util.dom.printElementText(dom_element, r) <NEW_LINE> return r.getvalue() | Return the text content of the DOM element.
| 625941cad4950a0f3b08c3ff |
def turn_clockwise(self): <NEW_LINE> <INDENT> oldblock = self.block <NEW_LINE> self.block = clockwise(self.block) <NEW_LINE> for (add_x, add_y) in [(0, 0), (1, 0), (0, -1), (-1, 0)]: <NEW_LINE> <INDENT> self.x, self.y = (self.x + add_x, self.y + add_y) <NEW_LINE> if not self.hit(): <NEW_LINE> <INDENT> return True <NEW_... | ブロックを回転(時計回り)させる | 625941cad58c6744b4257d0f |
def items(self): <NEW_LINE> <INDENT> return Entry.objects.filter(date__lte=datetime.utcnow().replace(tzinfo=utc), draft=False).order_by("-date") | All entries that are published before datetime.now
Corrected for timezone | 625941ca3317a56b86939d09 |
def addressbalance(moniker): <NEW_LINE> <INDENT> asset = get_asset_definition(moniker) <NEW_LINE> return controller.get_address_balance(asset) | Returns the balance in Satoshi for a particular asset/color.
"bitcoin" is the generic uncolored coin. | 625941ca8da39b475bd65022 |
def set_stopwords(self, stopwords): <NEW_LINE> <INDENT> for word in STOP_WORDS.union(set(stopwords)): <NEW_LINE> <INDENT> lexeme = nlp.vocab[word] <NEW_LINE> lexeme.is_stop = True | Set stop words | 625941cade87d2750b85fe42 |
def test_create(self): <NEW_LINE> <INDENT> data = {'name': ''} <NEW_LINE> self.json_post_value(reverse('album_create'), 'html', data) <NEW_LINE> data = {'name': 'album1'} <NEW_LINE> self.json_post_value(reverse('album_create'), 'url', data) | Test that album creation works properly. | 625941ca50812a4eaa59c3d2 |
def save_to_db(self): <NEW_LINE> <INDENT> db.session.add(self) <NEW_LINE> db.session.commit() | save user to db | 625941ca57b8e32f5248354a |
def get_cost_policies_grid_column_names_by_order(self): <NEW_LINE> <INDENT> self.column_name_list = self.get_grid_column_names_by_order(self.price_policies_grid_div_id) <NEW_LINE> return self.column_name_list | Implementing get cost policies grid column names by order functionality
:return: column_name_list | 625941ca9b70327d1c4e0e84 |
def Strongly_Connected_Component_Decomposition(D,Mode=0): <NEW_LINE> <INDENT> N=D.N <NEW_LINE> Group=[0]*N <NEW_LINE> Order=[] <NEW_LINE> adj_out=D.adjacent_out; adj_in=D.adjacent_in <NEW_LINE> for v in range(N): <NEW_LINE> <INDENT> if Group[v]==-1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> S=[v] <NEW_LINE> Grou... | 有向グラフDを強連結成分に分解
Mode:
0(Defalt)---各強連結成分の頂点のリスト
1 ---各頂点が属している強連結成分の番号
2 ---0,1の両方
※0で帰ってくるリストは各強連結成分に関してトポロジカルソートである. | 625941ca63d6d428bbe4459f |
def write_read_data(self, command, short=False): <NEW_LINE> <INDENT> command_line = command <NEW_LINE> for count in range(0, 5): <NEW_LINE> <INDENT> self.write_data(command_line) <NEW_LINE> result = self.read_data(command_line, short) <NEW_LINE> if result != -1: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> <... | Выполнение команды и получение результата | 625941cae5267d203edcdd4e |
def _1d_fused_lasso_crossprod(x): <NEW_LINE> <INDENT> return -np.ediff1d(x, to_begin=x[0], to_end=-x[-1]) | Efficiently compute the cross-product D^T x, where D is the first-differences matrix. | 625941ca097d151d1a222f0a |
def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkMorphologicalWatershedImageFilterIUC3IUC3.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj | New() -> itkMorphologicalWatershedImageFilterIUC3IUC3
Create a new object of the class itkMorphologicalWatershedImageFilterIUC3IUC3 and set the input and the parameters if some
named or non-named arguments are passed to that method.
New() tries to assign all the non named parameters to the input of the new objects - ... | 625941cacc0a2c11143dcf40 |
def a_word_forms(self, form, mapping=AccentsTable.PL): <NEW_LINE> <INDENT> result = set() <NEW_LINE> for dic_name in self.dictionaries.keys(): <NEW_LINE> <INDENT> for vector in self.dictionaries[dic_name].a_word_forms(form): <NEW_LINE> <INDENT> result.add(tuple(vector)) <NEW_LINE> <DEDENT> <DEDENT> return filter(lambda... | Accent agnostic version of word_forms method.
:param form: word form
:type form: unicode
:return: list of lists of unicode strings or empty list | 625941ca460517430c394236 |
def updateShaderState(self): <NEW_LINE> <INDENT> if not self.ready(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> opts = self.opts <NEW_LINE> shader = self.shader <NEW_LINE> colour = self.getColour() <NEW_LINE> threshold = list(self.getThreshold()) <NEW_LINE> if opts.invert: threshold += [ 1, 0] <NEW_... | Updates all shader program variables. | 625941cacb5e8a47e48b7b5b |
def upload (request): <NEW_LINE> <INDENT> msg = None <NEW_LINE> form_data = None <NEW_LINE> u = User.objects.get (id=get_uid ()) <NEW_LINE> w5u = W5User.object_withid (u.id) <NEW_LINE> if request.POST.has_key ('update'): <NEW_LINE> <INDENT> redirect, form_data, msg = get_form_data (request) <NEW_LINE> if redirect: <NEW... | Render the basic Facebook profile page, accepts data with
different labels and saves it to the DB. | 625941ca099cdd3c635f0d0a |
def cmp_directories(self, dir_1='./', dir_2='./'): <NEW_LINE> <INDENT> dirs_cmp = filecmp.dircmp(dir_1, dir_2) <NEW_LINE> list_dirs_json = dict() <NEW_LINE> path_in = self.make_path_in(dir_1, dir_2) <NEW_LINE> equal_files_json = self.equal_files_to_json( dirs_cmp.same_files, dir_1, dir_2 ) <NEW_LINE> diff_files_json = ... | Receive 2 path of directories.
return the report of compare both in a json. | 625941ca8e71fb1e9831d859 |
def add_to_collected(wtype, option): <NEW_LINE> <INDENT> collected.append('{} = {}'.format(wtype, option, )) <NEW_LINE> return | add collected options to list | 625941caf548e778e58cd62d |
def acquire_source(): <NEW_LINE> <INDENT> base_path = '/data/extract/' <NEW_LINE> yang_base_path = os.path.join(base_path, 'yang/') <NEW_LINE> cisco_yang_base_path = os.path.join(yang_base_path, 'vendor/cisco/') <NEW_LINE> if os.path.exists(yang_base_path): <NEW_LINE> <INDENT> logging.debug('YANG repo exists! Pulling l... | Acquire the YANG models in to the
/data/extract/yang location. Relies on priori knowledge
to know where to parse.
TODO: Generalize a priori knowledge to configuration. | 625941ca76e4537e8c351722 |
def test_peekleft_on_empty_deque(create_empty_deque): <NEW_LINE> <INDENT> assert create_empty_deque.peekleft() is None | Test peekleft on an empty deque to return head value. | 625941cae64d504609d748f0 |
def Start(self): <NEW_LINE> <INDENT> for l_module in self.m_module_apis.values(): <NEW_LINE> <INDENT> l_module.Start() <NEW_LINE> <DEDENT> LOG.info('Started.') | Start processing | 625941cabaa26c4b54cb11d0 |
def CreateWebsList(AssetInfo, TimePause, TimesFetch): <NEW_LINE> <INDENT> AssetTickers = list(AssetInfo.keys()) <NEW_LINE> WebsLists = dict() <NEW_LINE> for s in AssetTickers: <NEW_LINE> <INDENT> WebsLists[s] = WebLinkedList.WebList() <NEW_LINE> <DEDENT> for t in range(TimesFetch): <NEW_LINE> <INDENT> for s in AssetTic... | Get web pages | 625941cadd821e528d63b259 |
def filename(path: PathLike) -> str: <NEW_LINE> <INDENT> return split_path(path)[1] | Equivalent to `split_path(path)[1]`.
Args:
The path
Returns:
The filename part of `path` | 625941ca67a9b606de4a7f6a |
@api_experimental.route('/dags/<string:dag_id>', methods=['DELETE']) <NEW_LINE> @requires_authentication <NEW_LINE> def delete_dag(dag_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> count = delete.delete_dag(dag_id) <NEW_LINE> <DEDENT> except AirflowException as err: <NEW_LINE> <INDENT> log.error(err) <NEW_LINE> res... | Delete all DB records related to the specified Dag. | 625941ca10dbd63aa1bd2c54 |
def testCreateTwitterUserAddsToStore(self): <NEW_LINE> <INDENT> user = createUser(u'username', u'secret', u'User', u'user@example.com') <NEW_LINE> twitterUser = createTwitterUser(user, 91845202) <NEW_LINE> self.assertIdentical(twitterUser, self.store.find(TwitterUser).one()) | L{createTwitterUser} adds the new L{TwitterUser} to the main store. | 625941ca85dfad0860c3af0b |
def init(self, key, value): <NEW_LINE> <INDENT> ckeys, cvals = _ctype_key_value(key, value) <NEW_LINE> check_call(_LIB.MXKVStoreInit( self.handle, mx_uint(len(ckeys)), ckeys, cvals)) | Initialize a single or a sequence of key-value pairs into the store.
For each key, one must init it before push and pull
Parameters
----------
key : int or sequence of int
The keys.
value : NDArray or sequence of NDArray
The values.
Examples
--------
>>> # init a single key-value pair
>>> shape = (2,3)
>>> k... | 625941ca16aa5153ce362528 |
def construct(object, form_fields): <NEW_LINE> <INDENT> dynamic = WTFormsDynamicFields() <NEW_LINE> for field in form_fields: <NEW_LINE> <INDENT> label = field['COLUMN_COMMENT'] <NEW_LINE> if field['COLUMN_TYPE'] == 'datetime': <NEW_LINE> <INDENT> dynamic.add_field(field['COLUMN_NAME'], label, DateTimeField) <NEW_LINE>... | Функция фабрика.
Собирает форму по указанным параметрам
Принимает:
oject: Экземпляр класса формы
form_fields(list[dicts]): Параметры формы. Список словарей
Возвращает:
Экземпляр класса формы | 625941ca5fc7496912cc3a2e |
def test_3_peaks(self): <NEW_LINE> <INDENT> pn = 3 <NEW_LINE> ints = unidip.test_unidip(f"{EXAMPLES}peak3.csv", plot=False) <NEW_LINE> assert len(ints) == pn, f"Found wrong number of peaks! Should be {pn}, is {len(ints)}." | test 3 peaks | 625941ca56b00c62f0f14709 |
def __init__(self): <NEW_LINE> <INDENT> root = tkinter.Tk() <NEW_LINE> root.wm_title("Temperature Converter") <NEW_LINE> self.model = model.Model() <NEW_LINE> self.view = view.View(self) <NEW_LINE> self.view.mainloop() <NEW_LINE> root.destroy() | Initialize MVC components | 625941ca435de62698dfdcfc |
def load_domainset(self, domainset: typing.List[str], keytype: str) -> None: <NEW_LINE> <INDENT> logger.debug(f"Loading domainset {domainset} for keytype {keytype}") <NEW_LINE> self.domainset = domainset <NEW_LINE> self.keytype = keytype <NEW_LINE> assert isinstance(self.conf["path"], str) <NEW_LINE> filename = self.ge... | Prepare paths and create/load private key.
Args:
domainset: The list of hostnames to load
keytype: The keytype to use, "rsa" or "ecdsa".
Returns:
None | 625941ca82261d6c526ab54e |
def vdd_volt(self, val): <NEW_LINE> <INDENT> assert val in VDDS <NEW_LINE> self.cmd('v', val) <NEW_LINE> self.vdd_volt_cache = val | VDD: set voltage enum | 625941ca63b5f9789fde7195 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.