code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_object_as_xml(value, cls=None, root_tag_name=None, no_namespace=False): <NEW_LINE> <INDENT> if cls is None: <NEW_LINE> <INDENT> cls = value.__class__ <NEW_LINE> <DEDENT> xml_object = XmlDocument() <NEW_LINE> parent = etree.Element("parent") <NEW_LINE> xml_object.to_parent_element(cls, value, cls.get_namespace()...
Returns an ElementTree representation of a :class:`spyne.model.complex.ComplexModel` subclass. :param value: The instance of the class to be serialized. :param value: The root tag string to use. Defaults to the output of ``value.__class__.get_type_name_ns()``.
625941d391f36d47f21ac6c4
def toggleVertColor(): <NEW_LINE> <INDENT> sel = selection() <NEW_LINE> for obj in sel.selection.keys(): <NEW_LINE> <INDENT> cmds.polyOptions(obj,cs=1-cmds.polyOptions(obj,q=1,cs=1)[0],cm='none')
Util for toggling the vertex color per obj selected
625941d3d7e4931a7ee9e0ee
def __setup_init2(self): <NEW_LINE> <INDENT> self.jamedia.setup_init() <NEW_LINE> self.jamedia.pack_standar() <NEW_LINE> self.__cancel_toolbar() <NEW_LINE> self.paneltube.cancel_toolbars_flotantes() <NEW_LINE> map(self.__ocultar, [ self.toolbar_descarga, self.alerta_busqueda]) <NEW_LINE> if self.pistas: <NEW_LINE> <IND...
Inicializa la aplicación a su estado fundamental.
625941d39b70327d1c4e0fa5
def pdf_out (out): <NEW_LINE> <INDENT> if 'savefig' in dir(out): <NEW_LINE> <INDENT> out.savefig(pdf_out_tmp_file, format='pdf') <NEW_LINE> name = pdf_out_tmp_file <NEW_LINE> <DEDENT> elif isinstance(out, str): <NEW_LINE> <INDENT> if out.find('\n') > 0: <NEW_LINE> <INDENT> name = None <NEW_LINE> <DEDENT> else: <NEW_LIN...
Outputs PDF within TeXmacs. According the the type of the argument the following scenarios can take place: If the argument is an instance of matplotlib.pyplot.Figure then its method savefig() will be used to produce a PDF figure. Note that you need to be using a backend which supports this format. If the argument is...
625941d33eb6a72ae02ec6b0
def __idiv__(self, *args): <NEW_LINE> <INDENT> return _almathswig.Quaternion___idiv__(self, *args)
__idiv__(self, float pVal) -> Quaternion
625941d34d74a7450ccd4394
def _post_chroot_block(self): <NEW_LINE> <INDENT> pass
commands to run after the exiting the chroot, but before unmounting / finalizing
625941d3f8510a7c17cf98cc
def getVisibilityMaps(environment: np.ndarray, resolution: int, screen: bool) -> np.ndarray: <NEW_LINE> <INDENT> width, height = environment.shape <NEW_LINE> def calculate_local_visibility(col: int, row: int) -> np.ndarray: <NEW_LINE> <INDENT> radius = 4*resolution <NEW_LINE> radii = np.linspace(0, radius, 30) <NEW_LIN...
Parameters ---------- environment : matrix In correct dimensions, i.e resolution has already been applied resolution : int Use this for scale, i.e if we decide that one original square is 50x50 cm, then one square in the environment is 50/res x 50/res cm. Need this for the radius of particle emission. ...
625941d3a934411ee3751864
@app.route('/new_game', methods=['POST']) <NEW_LINE> def new_game_handler(): <NEW_LINE> <INDENT> state = request.json['state'] <NEW_LINE> if 'item' in request.json: <NEW_LINE> <INDENT> item = request.json['item'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> item = '' <NEW_LINE> <DEDENT> if 'menu_id' in request.json: <...
Goes through the steps of creating a new character and game.
625941d3711fe17d8254253a
def test_enum_size(self) -> None: <NEW_LINE> <INDENT> assert_that(len(CashDenomination), is_(12))
Test size of enum.
625941d30383005118ecf7b2
def GetMops(self,memid,pBstrMops): <NEW_LINE> <INDENT> pass
GetMops(self: ITypeInfo,memid: int) -> str Retrieves marshaling information. memid: The member ID that indicates which marshaling information is needed.
625941d3097d151d1a223029
def __ilshift__(self, y): <NEW_LINE> <INDENT> pass
x.__ilshift__(y) <==> x<<=y
625941d3293b9510aa2c3465
@commandWrap <NEW_LINE> def Snap2PointsTo2Points(*args, **kwargs): <NEW_LINE> <INDENT> return cmds.Snap2PointsTo2Points(*args, **kwargs)
:rtype: list|str|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941d3be8e80087fb20e12
def testArrayOfEvents(self): <NEW_LINE> <INDENT> pass
Test ArrayOfEvents
625941d32c8b7c6e89b35991
def replace_hero(self, initial_position): <NEW_LINE> <INDENT> self.current_direction = "down" <NEW_LINE> (self.x, self.y) = initial_position
Défini un sprite de direction par défaut et une position donnée en argument.
625941d37b25080760e39629
def set_Address(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'Address', value)
Set the value of the Address input for this Choreo. ((required, string) The new physical address to be used for this Identity.)
625941d382261d6c526ab671
def update_field_multilang(records, field, method): <NEW_LINE> <INDENT> installed_langs = [(records.env.lang or "en_US", "English")] <NEW_LINE> if records._fields[field].translate: <NEW_LINE> <INDENT> installed_langs = records.env["res.lang"].get_installed() <NEW_LINE> <DEDENT> for lang_code, lang_name in installed_lan...
Update a field in all available languages in the database. :param records: Recordset to be updated. :param str field: Field to be updated. :param callable method: Method to execute to update the field. It will be called with: ``(old_value, lang_code, record)``
625941d3566aa707497f4737
def test_env(self, capfd, runner): <NEW_LINE> <INDENT> runner(Command('env').env('FOO', 'bar')) <NEW_LINE> out_lines, _ = captured_lines(capfd) <NEW_LINE> cmd_env = parse_env_output(out_lines) <NEW_LINE> assert_that(cmd_env['FOO'], Equals('bar'))
When environment variables are added to a command, those variables should reflect in the child process when the command is run.
625941d3d486a94d0b98e317
def setTextSelectedColor(self, color): <NEW_LINE> <INDENT> self._textSelectedColor = color
Set the text color when an item is selected. :type color: QtWidgets.QtColor
625941d30383005118ecf7b3
def plot_bar_charts(dataframe,filename,title,xaxis,yaxis,truncate): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> logger.info('Plotting charts...') <NEW_LINE> if truncate > 0: <NEW_LINE> <INDENT> dataframe = dataframe.ix[:truncate] <NEW_LINE> <DEDENT> dataframe.plot(kind='bar', legend=None) <NEW_L...
Takes a two-column dataframe and plots it :params: a dataframe with two columns (one labels, the other a count), a filename for the resulting chart, a title, and titles for the two axes (if title is None, then nothing is plotted), and a truncate variable which cuts down the number of rows plotted (unless it's 0 at whic...
625941d30fa83653e465718b
def markdown2html(source, no_p=False): <NEW_LINE> <INDENT> if __mdx_checklist__: <NEW_LINE> <INDENT> mkd = markdown.Markdown(output_format='html5', extensions=['smarty', 'extra', CustomSpanClassExtension(), ChecklistExtension(), MathJaxExtension()]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mkd = markdown.Markdown(...
Convert markdown source to html. Parameters ---------- source : str string (as single stream) containing the source no_p : bool, optional if True the converted contents is not inserted into the <p></p> tags Returns ------- str converted source
625941d35fcc89381b1e1891
def unpack_lsun_image(image_data): <NEW_LINE> <INDENT> value = tf.parse_single_example( image_data, features={"image/encoded": tf.FixedLenFeature([], tf.string)}) <NEW_LINE> image = tf.image.decode_jpeg(value["image/encoded"], channels=3) <NEW_LINE> image = tf.image.resize_image_with_crop_or_pad( image, target_height=1...
Returns a LSUN-Bedrooms image as a 128x128x3 Tensor, with label 0.
625941d33539df3088e2e51c
def event_list(request): <NEW_LINE> <INDENT> namespace = request.session['URL_NAMESPACE'] <NEW_LINE> return render(request, 'atriacalendar/event_list.html', context={'active_view': namespace + 'calendar_list'})
List/Manage Calendar Events shell view.
625941d3be7bc26dc91cd7cf
def logout(self): <NEW_LINE> <INDENT> logout = self.out_payload <NEW_LINE> logout.Clear() <NEW_LINE> logout.type = seto.PAYLOAD_ETO <NEW_LINE> logout.eto_payload.type = eto.PAYLOAD_LOGOUT <NEW_LINE> logout.eto_payload.logout.reason = eto.LOGOUT_NONE <NEW_LINE> self.logger.info("sending logout payload") <NEW_LINE> self....
Disconnects from the API
625941d3b830903b967e9adb
@pytest.mark.parametrize( "index, create_document_value_provider", enumerate([DocumentValueProvider, TraceDocumentValueProvider]) ) <NEW_LINE> @pytest.mark.repeat(5) <NEW_LINE> def test_rearrange(source_doc: Dict, source_spec: Dict, target_docs: List[Dict], target_spec: Dict, index, create_document_value_provider): <NE...
Verify that translate respects the sort order property of the variables in the target spec, and ignores the order in which the variables happen to be defined in the spec.
625941d3fff4ab517eb2f60d
def test_set(pmeter): <NEW_LINE> <INDENT> for cmd in pmeter.commands: <NEW_LINE> <INDENT> verify = True <NEW_LINE> if not cmd.startswith("set-"): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if "-range" in cmd: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if cmd == "set-remote-mode": <NEW_LINE> <INDENT> verify ...
Verify some of the the "get something" commands.
625941d315fb5d323cde0ce2
def load_noisemap(self): <NEW_LINE> <INDENT> return _moduleconnectorwrapper.PyX4M200_load_noisemap(self)
load_noisemap(PyX4M200 self) Send command to module to load a previously stored noisemap. Not yet functional as of FW 1.3
625941d360cbc95b062c6714
def IsRunning(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response, _ = self._SendJsonRequest('GET', _EmulatorPath(), timeout_secs=1.0) <NEW_LINE> return response.status == six.moves.http_client.OK <NEW_LINE> <DEDENT> except RequestError: <NEW_LINE> <INDENT> return False
Returns True iff the broker is known to be running.
625941d307d97122c4178a5f
def visualize_examples(self, n_examples=-1, data_dir=None, seed=None): <NEW_LINE> <INDENT> if data_dir is None: <NEW_LINE> <INDENT> data_dir = os.path.join(self.base_dir, self.gridworld_name) <NEW_LINE> <DEDENT> visual_dir = os.path.join(data_dir, 'visualized_data') <NEW_LINE> if os.path.exists(visual_dir): <NEW_LINE> ...
Visualize generated data examples
625941d3f7d966606f6aa1d7
def get_robot(name): <NEW_LINE> <INDENT> rospy.loginfo("Constructing robot {}".format(name)) <NEW_LINE> robot_class = ROBOTS.get(name.lower()) <NEW_LINE> if robot_class is not None: <NEW_LINE> <INDENT> return robot_class() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> error_msg = "Cannot construct robot '{}'\n".format(...
Constructs a robot (api) object based on the provided name :param name: (str) robot name :return: (Robot) :raises: RuntimeError
625941d338b623060ff0afbf
def test_default_image_in_contact_edit_page(self): <NEW_LINE> <INDENT> self.client.login(username='admin', password='admin') <NEW_LINE> response = self.client.get(reverse('edit_person')) <NEW_LINE> self.assertIn('/static/img/img.png', response.content)
is default image in contact edit page
625941d30a366e3fb873e9ec
def _add_source(self, source_handle, bkref_class, bkref_handle): <NEW_LINE> <INDENT> if len(self.obj_dict[Source][source_handle]) > 0: <NEW_LINE> <INDENT> for bkref in self.bkref_dict[Source][source_handle]: <NEW_LINE> <INDENT> if bkref_handle == bkref[1]: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> <DEDENT...
Add source to the Source object list @param: source_handle -- The handle for the source to add @param: bkref_class -- The class associated to this handle (source) @param: bkref_handle -- The handle associated to this source
625941d3a05bb46b383ec9f3
def arrayToXml(self, arr): <NEW_LINE> <INDENT> xml = ["<xml>"] <NEW_LINE> for k, v in arr.items(): <NEW_LINE> <INDENT> if v.isdigit(): <NEW_LINE> <INDENT> xml.append("<{0}>{1}</{0}>".format(k, v)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xml.append("<{0}><![CDATA[{1}]]></{0}>".format(k, v)) <NEW_LINE> <DEDENT> <DE...
array转xml
625941d3de87d2750b85ff65
def authorize(self): <NEW_LINE> <INDENT> return self.gateway._send_transaction(self, '_authorize')
Authorize the transaction. Transaction must be captured to complete. Requires:: Transaction.amount # For credit card Transaction.card_number Transaction.expiration_month Transaction.expiration_year # For check Transaction.check_account_number Transaction.check_routing_number Returns...
625941d3a17c0f6771cbe221
def test_unpickleable(self): <NEW_LINE> <INDENT> obj = datetime.datetime.now() <NEW_LINE> pickler = jsonpickle.Pickler(unpicklable=False) <NEW_LINE> flattened = pickler.flatten(obj) <NEW_LINE> self.assertEqual(str(obj), flattened)
If 'unpickleable' is set on the Pickler, the date objects should be simple, human-readable strings.
625941d3aad79263cf390c14
def vulnerability(self, msg_string, new_line=True, severity=MEDIUM): <NEW_LINE> <INDENT> _id = self.get_log_id() <NEW_LINE> m = Message(VULNERABILITY, self._clean_string(msg_string), _id) <NEW_LINE> m.set_severity(severity) <NEW_LINE> self.log[_id] = m
This method is called from the output object. The output object was called from a plugin or from the framework. This method should take an action when a vulnerability is found.
625941d3097d151d1a22302a
def append(self, *args): <NEW_LINE> <INDENT> return _stomp.ScalarVector_append(self, *args)
append(ScalarVector self, ScalarPixel x)
625941d366656f66f7cbc37e
def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <...
Returns the model properties as a dict
625941d3c432627299f04e18
def get_user(user_id): <NEW_LINE> <INDENT> pass
Return the user object that represents the given userid, or None if there is no user for that ID.
625941d36aa9bd52df036f76
def __init__(self, login_session): <NEW_LINE> <INDENT> self.cookiejar = login_session <NEW_LINE> self.log = logging.getLogger('ipsv.scraper.licenses')
Initialize a License Scraper instance @type login_session: cookielib.CookieJar
625941d3a219f33f34628b39
def __encode(self, tree: Node, text_encoding: str, packet_encoding: int) -> bytes: <NEW_LINE> <INDENT> if packet_encoding == EAmuseProtocol.BINARY: <NEW_LINE> <INDENT> binary = BinaryEncoding() <NEW_LINE> return binary.encode(tree, encoding=text_encoding) <NEW_LINE> <DEDENT> elif packet_encoding == EAmuseProtocol.XML: ...
Given a Node tree, encode the data into the given packet encoding. Parameters: tree - A Node object representing the root of the tree to encode. text_encoding - The text encoding for any strings that will be encoded. Should be EAmuseProtocol.SHIFT_JIS, EAmuseProtocol.EUC_JP or ...
625941d3009cb60464c63582
def gen_system_facts(name=None): <NEW_LINE> <INDENT> if name is None or name == '': <NEW_LINE> <INDENT> fqdn = gen_domain() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fqdn = gen_domain(*name.split('.')) <NEW_LINE> <DEDENT> kernel = '{}.{}.{}'.format( *[gen_integer(min_value=0, max_value=9) for _ in range(3)]) <NEW_L...
Generate system facts. See https://docs.puppet.com/facter/3.6/core_facts.html for more information. :param str name: Name to be used as the system's hostname. :returns: A Dictionary representing a system's facts. :rtype: dict
625941d3cad5886f8bd271aa
def save_cookies(self): <NEW_LINE> <INDENT> print("save_cookies()") <NEW_LINE> cookies = dict_from_cookiejar(self.session.cookies) <NEW_LINE> self.write_config(self.config_section,self.config_cookies,str(cookies))
保存cookies
625941d324f1403a92600d37
def read_json(filename, prefix): <NEW_LINE> <INDENT> with open(filename) as inf: <NEW_LINE> <INDENT> data = re.sub(r'//.*', '', inf.read()) <NEW_LINE> data = re.sub(r'/\*.*?\*/', '', data, flags=re.DOTALL) <NEW_LINE> try: <NEW_LINE> <INDENT> obj = json.loads(data) <NEW_LINE> path = re.sub(prefix, '', filename).replace(...
read file fn as JSON; remove path prefix with
625941d3a8370b7717052a70
def events() -> List[Event]: <NEW_LINE> <INDENT> return get()
Returns a list of game events.
625941d3bf627c535bc133a1
def edit_map(map_name): <NEW_LINE> <INDENT> return _edit_map(_find_map(map_name, SavegameManager.get_maps()))
Start editing the map file specified by the name. @param map_name: name of map or path to map @return: bool, whether loading succeeded
625941d38e05c05ec3eea547
def IsProperSubsetOf(self,other): <NEW_LINE> <INDENT> pass
IsProperSubsetOf(self: SortedSet[T],other: IEnumerable[T]) -> bool Determines whether a System.Collections.Generic.SortedSet object is a proper subset of the specified collection. other: The collection to compare to the current System.Collections.Generic.SortedSet object. Returns: true if the System.Col...
625941d3baa26c4b54cb12f0
@require_context <NEW_LINE> def message_get_all(context): <NEW_LINE> <INDENT> messages = models.Message <NEW_LINE> query = (model_query(context, messages, read_deleted="no", project_only="yes")) <NEW_LINE> results = query.all() <NEW_LINE> return _translate_messages(results)
Fetch all messages for the contexts project.
625941d33317a56b86939e27
def test_retrieve_session_too_late(self): <NEW_LINE> <INDENT> with freeze_time(self.t_answer_too_late): <NEW_LINE> <INDENT> response = self.client.get(self.session_url) <NEW_LINE> <DEDENT> response_json = response.json() <NEW_LINE> self.assertEqual(response.status_code, 410) <NEW_LINE> self.assertEqual(response_json['d...
Retrieve session after it expired.
625941d396565a6dacc8f89d
def test_missing_split_char(self): <NEW_LINE> <INDENT> self.assertIsNone( dataset.load_config(os.path.join('.', 'data', 'wrong_configs', 'config_4')))
Config without split_char.
625941d31b99ca400220ac83
def xafsift(r, chir, group=None, rmin=0, rmax=20, dr=1, dr2=None, rw=0, window='kaiser', qmax_out=None, nfft=2048, kstep=0.05, _larch=None, **kws): <NEW_LINE> <INDENT> if _larch is None: <NEW_LINE> <INDENT> raise Warning("cannot do xafsft -- larch broken?") <NEW_LINE> <DEDENT> if 'rweight' in kws: <NEW_LINE> <INDENT> r...
calculate reverse XAFS Fourier transform This assumes that chir_re and (optional chir_im are on a uniform r-grid given by r.
625941d3187af65679ca52f1
def SetUseShrinkImageFilter(self, *args): <NEW_LINE> <INDENT> return _itkMultiResolutionPyramidImageFilterPython.itkMultiResolutionPyramidImageFilterIF3IF3_SetUseShrinkImageFilter(self, *args)
SetUseShrinkImageFilter(self, bool _arg)
625941d3d99f1b3c44c6775e
def get_db(): <NEW_LINE> <INDENT> if 'db' not in g: <NEW_LINE> <INDENT> g.db = sqlite3.connect( current_app.config['DATABASE'], detect_types=sqlite3.PARSE_DECLTYPES ) <NEW_LINE> g.db.row_factory = sqlite3.Row <NEW_LINE> <DEDENT> return g.db
Initializes connection to SQLite database if one hasn't already been created, otherwise returns the singleton Connection object. #### Return Value **sqlite3.Connection** - A Connection object to the SQLite database.
625941d363d6d428bbe446c1
def shouldPrintMessage(self, timestamp, message): <NEW_LINE> <INDENT> while len(self.heap): <NEW_LINE> <INDENT> if self.heap[0][0] <= timestamp: <NEW_LINE> <INDENT> temp = heapq.heappop(self.heap) <NEW_LINE> self.cache.pop(temp[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if time...
Returns true if the message should be printed in the given timestamp, otherwise returns false. If this method returns false, the message will not be printed. The timestamp is in seconds granularity. :type timestamp: int :type message: str :rtype: bool
625941d323849d37ff7b3261
def uptime_from_start_time(start_time): <NEW_LINE> <INDENT> return time.time() - start_time
Returns the uptime for the process given its ``start_time``. @param start_time: The time the process started in seconds past epoch. @type start_time: float @return: The seconds since the process started. @rtype: float
625941d330dc7b7665901b37
def test_has_cycle(self): <NEW_LINE> <INDENT> g = { 'A': ['B'], 'B': ['C', 'E'], 'C': ['F'], 'D': ['A'], 'E': ['D'], 'F': [], } <NEW_LINE> self.assertTrue(graph.has_cycle(g)) <NEW_LINE> g['D'] = [] <NEW_LINE> self.assertFalse(graph.has_cycle(g)) <NEW_LINE> g['A'].append('C') <NEW_LINE> self.assertFalse(graph.has_cycle(...
A------ ^ \ / v v D B -> C ^ / \ v v E F
625941d3a8370b7717052a71
@click.command() <NEW_LINE> @click.option('--token', envvar='FRUNDE_TOKEN', help='Telegram bot token.', required=True) <NEW_LINE> @click.option('--refresh-interval', envvar='FRUNDE_REFRESH_INTERVAL', default=60, help='Interval in seconds in which the bot should check if the Freitagsrunde is open.', show_default=True) <...
All options are also available as environment variables, e.g. "--refresh-interval=30" can be set by "export REFRESH_INTERVAL=30".
625941d316aa5153ce36264a
def harvest(x, fs, f0_floor=DEFAULT_F0_FLOOR, f0_ceil=DEFAULT_F0_CEIL, frame_period=DEFAULT_FRAME_PERIOD, **dummy): <NEW_LINE> <INDENT> option = structures.HarvestOption() <NEW_LINE> apidefinitions._InitializeHarvestOption(option) <NEW_LINE> option.f0_floor = f0_floor <NEW_LINE> option.f0_ceil = f0_ceil <NEW_LINE> opti...
F0 extract by Harvest Args: x (ndarray(dtype=double, ndim=1)): Input waveform fs (int): Sampling frequency [Hz] f0_floor (double, optional): Floor of F0 estimation f0_ceil (double, optional): Ceil of F0 estimation frame_period (double, optional): Frame shift [ms] Returns: ndarray(dtype=double,...
625941d397e22403b379d16c
def test_render(): <NEW_LINE> <INDENT> output = io.StringIO() <NEW_LINE> e = hr.Element("Testing, 1 2 3..") <NEW_LINE> e.append("More tests! We need more tests!") <NEW_LINE> e.render(output, " ") <NEW_LINE> file_cont = output.getvalue() <NEW_LINE> assert("Testing, 1 2 3..") in file_cont <NEW_LINE> assert("More tests...
Tests whether render successfully writes content to file by creating instance of element, adding content to it using the append function and calling the render funtion on it.
625941d3596a897236089c91
def getDivisions(self, dim): <NEW_LINE> <INDENT> if len(dim) == 1 and dim in 'xyz': <NEW_LINE> <INDENT> idx = 'xyz'.find(dim) <NEW_LINE> return [self.imesh.getVtxCoords(i)[idx] for i in self.iterateVtx(dim)] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ScdMeshError('Invalid dimension: '+str(dim))
Get the mesh divisions on a given dimension Given a dimension 'x', 'y', or 'z', return a list of the mesh vertices along that dimension
625941d34428ac0f6e5ba9c5
def json(self) -> Dict: <NEW_LINE> <INDENT> with self.load().open() as f: <NEW_LINE> <INDENT> return json.load(f)
Load file content as Json object. Returns ------- dict
625941d3851cf427c661a6e0
def validate_user(email, school): <NEW_LINE> <INDENT> if school is None: <NEW_LINE> <INDENT> return INVALID_EMAIL_DOMAIN <NEW_LINE> <DEDENT> if not '@' in email: <NEW_LINE> <INDENT> return MALFORMED_EMAIL <NEW_LINE> <DEDENT> parts = email.split('@') <NEW_LINE> if len(parts) != 2: <NEW_LINE> <INDENT> return MALFORMED_EM...
:returns: None if there is no error, or an error code if there is an error. >>> from src.models import School >>> validate_user('scroopy@noopers.edu', School('n', ['noopers.edu'])) >>> validate_user('scroopy@noopers.edu', None) == INVALID_EMAIL_DOMAIN True >>> validate_user('scroopy@noopers.edu', school=School('n', [])...
625941d3fbf16365ca6f639a
def stream(self, limit=None, page_size=None): <NEW_LINE> <INDENT> limits = self._version.read_limits(limit, page_size) <NEW_LINE> page = self.page(page_size=limits['page_size'], ) <NEW_LINE> return self._version.stream(page, limits['limit'], limits['page_limit'])
Streams WebhookInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. :param int limit: Upper limit for the number of records to return. stream() ...
625941d366673b3332b92264
def __neighcom(node, graph, status) : <NEW_LINE> <INDENT> weights = {} <NEW_LINE> for neighbor, datas in graph[node].items() : <NEW_LINE> <INDENT> if neighbor != node : <NEW_LINE> <INDENT> weight = datas.get("weight", 1) <NEW_LINE> neighborcom = status.node2com[neighbor] <NEW_LINE> weights[neighborcom] = weights.get(ne...
Compute the communities in the neighborood of node in the graph given with the decomposition node2com Returns a dic: a comm and the sum of weights of edges between the given node and all nodes in it.
625941d3046cf37aa974cf19
def p_repetedBlock(p): <NEW_LINE> <INDENT> p[0]=AST.RepNode([p[3],p[8]])
repetedBlock : REP '(' expression ')' NEWLINE '{' NEWLINE codeBlock '}'
625941d391f36d47f21ac6c6
def partitionDisjoint(self, A): <NEW_LINE> <INDENT> maxleft = [None]*len(A) <NEW_LINE> minright = [None]*len(A) <NEW_LINE> maxleft[0] = A[0] <NEW_LINE> for i in range(1,len(A)): <NEW_LINE> <INDENT> maxleft[i] = max(maxleft[i-1],A[i]) <NEW_LINE> <DEDENT> minright[len(A)-1] = A[-1] <NEW_LINE> for i in range(len(A)-2,-1,...
:type A: List[int] :rtype: int
625941d35e10d32532c5f0f9
def get_cpu_percent(pid: int, iterations: int, omit: int) -> dict: <NEW_LINE> <INDENT> assert iterations > 0 <NEW_LINE> time.sleep(omit) <NEW_LINE> cpu_percentages = dict() <NEW_LINE> for _ in range(iterations): <NEW_LINE> <INDENT> current_cpu_percentages = ProcessManager.get_cpu_percent(pid) <NEW_LINE> assert len(curr...
Get total PID CPU percentage, as in system time plus user time. If the PID has corresponding threads, creates a dictionary with the lists of instant loads for each thread.
625941d35fcc89381b1e1892
def run_carddav_sync(args): <NEW_LINE> <INDENT> now = time.strftime("%Y-%m-%d %H:%M:%S") <NEW_LINE> logging.info("Starting carddav sync at %s with arguments: %s", now, args) <NEW_LINE> carddav_dir = pathlib.Path("carddav") <NEW_LINE> carddav_dir.mkdir(parents=True, exist_ok=True) <NEW_LINE> sync_template = "vdirsyncer....
Fetch contacts from CardDAV source and sync with Hatchbuck
625941d3e64d504609d74a12
def _create_capacity_grid(self): <NEW_LINE> <INDENT> grid = self._get_empty_grid() <NEW_LINE> for i in range(len(self._components)): <NEW_LINE> <INDENT> c = self._components[i] <NEW_LINE> assert grid[c.loc[1], c.loc[0]] == 0, "locations of _components are not unique" <NEW_LINE> grid[c.loc[1], c.loc[0]] = c.capacity <NE...
Creates a capacity grid of all the components. The capacity of each component will be placed on the corresponding position. All other position (i.e. spots where the components are not placed) are 0. :return: 2D numpy array of comp_need capabilities
625941d34c3428357757c4fa
def plot_data(data, epoch, out_dir): <NEW_LINE> <INDENT> make_tiles(to_numpy(data), os.path.join(out_dir, f"data_ep{epoch}.png"))
Plots input data :param data: a data batch to plot :param epoch: epoch nr :param out_dir: directory where to save the plot
625941d3cdde0d52a9e53206
def processPages(self, path): <NEW_LINE> <INDENT> self.type = Worker.DO_WORK <NEW_LINE> self.path = path <NEW_LINE> self.start()
Processes all pages that were gotten in the countWork() method
625941d35f7d997b87174c6b
def attr_matches(self, text): <NEW_LINE> <INDENT> import re <NEW_LINE> m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text) <NEW_LINE> if not m: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> expr, attr = m.group(1, 3) <NEW_LINE> try: <NEW_LINE> <INDENT> thisobject = eval(expr, self.namespace) <NEW_LINE> <DEDENT> except Exce...
Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluable in self.namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are also considered.) WARNING: this can still invoke...
625941d3d268445f265b5040
def mobilenet_v1_arg_scope( is_training=True, weight_decay=0.00004, stddev=0.09, regularize_depthwise=False, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, batch_norm_updates_collections=tf.GraphKeys.UPDATE_OPS, normalizer_fn=slim.batch_norm): <NEW_LINE> <INDENT> batch_norm_params = { 'center': True, 'scale': True,...
Defines the default MobilenetV1 arg scope. Args: is_training: Whether or not we're training the model. If this is set to None, the parameter is not added to the batch_norm arg_scope. weight_decay: The weight decay to use for regularizing the model. stddev: The standard deviation of the trunctated normal weig...
625941d3b830903b967e9adc
def digit_one(length): <NEW_LINE> <INDENT> t.penup() <NEW_LINE> t.forward(length/2) <NEW_LINE> t.pendown() <NEW_LINE> t.left(90) <NEW_LINE> t.forward(length) <NEW_LINE> t.left(90+45) <NEW_LINE> t.forward(length*sin(45*3.14/180)) <NEW_LINE> t.backward(length*sin(45*3.14/180)) <NEW_LINE> t.right(90+45) <NEW_LINE> t.backw...
Рисует цифру с высотой length слева от направления черепахи контракт (договорённость): черепаха возвращается в исходную точку, и имеет исходную ориентацию перо по оканчанию функции поднято
625941d3d486a94d0b98e318
def __init__(self, parent=None): <NEW_LINE> <INDENT> QtGui.QTabWidget.__init__(self, parent) <NEW_LINE> self.__tabs = list() <NEW_LINE> self.tabBar().setContextMenuPolicy(QtCore.Qt.CustomContextMenu) <NEW_LINE> QtCore.QObject.connect(self.tabBar(), QtCore.SIGNAL("customContextMenuRequested(QPoint)"), self.showTabBarCon...
Constructor. @param tabWidget: TabWidget that you want to decorate. @type tabWidget: C{QtGui.QTabWidget} @param parent: Parent of this L{QtCore.QObject}. @type parent: C{QtCore.QObject}
625941d3925a0f43d254a04a
def user_name_age(name, age=None): <NEW_LINE> <INDENT> print('His/Her name: ', name) <NEW_LINE> print('His/Her age: ', age)
Display owner name and his/her age
625941d37d847024c06be490
def create_user(self, username, password, email=None, **extra_fields): <NEW_LINE> <INDENT> if not username: <NEW_LINE> <INDENT> raise ValueError('Users must have an username') <NEW_LINE> <DEDENT> user = self.model( username=username, email=email, ) <NEW_LINE> user.set_password(password) <NEW_LINE> user.save(using=self....
username是唯一标识,没有会报错
625941d3f8510a7c17cf98ce
def test_missing_bic(): <NEW_LINE> <INDENT> payment = simple_payment() <NEW_LINE> with pytest.raises(MissingBICError): <NEW_LINE> <INDENT> payment.add_transaction(amount=1, account=foreign_acct, creditor=biz, rmtinfo='Test')
If the creditor has a foreign account, the BIC must be supplied.
625941d301c39578d7e7500e
def run(self, root): <NEW_LINE> <INDENT> blocks = root.getiterator('pre') <NEW_LINE> for block in blocks: <NEW_LINE> <INDENT> pass
Find code blocks and store in htmlStash.
625941d34527f215b584c628
def observations(self): <NEW_LINE> <INDENT> def has_all_fixefs(ind, effects): <NEW_LINE> <INDENT> if not effects: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> for effect in effects: <NEW_LINE> <INDENT> if effect not in ind.phenotypes: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> elif ind.phenotypes[effec...
Returns a list of the fully observed individuals in the model Fully observed individuals have observations for each fixed effect and and observation for the outcome variable. :returns: the fully observed individuals :rtype: list of Individuals
625941d3ad47b63b2c50a152
def get_records_by_type(self, query: str, match_type: str) -> List[Dict]: <NEW_LINE> <INDENT> assert match_type in ('alias', 'label') <NEW_LINE> label_and_type = f'{query}##{match_type.lower()}' <NEW_LINE> records_lookup = self.records.get(label_and_type, None) <NEW_LINE> if records_lookup: <NEW_LINE> <INDENT> return [...
Retrieve records for given query and match type. :param query: string to match against :param str match_type: type of match to look for. Should be one of "alias" or "label" (use get_record_by_id for concept ID lookup) :return: list of matching records. Empty if lookup fails.
625941d35166f23b2e1a532b
def _get_running_loop(): <NEW_LINE> <INDENT> running_loop, pid = _running_loop.loop_pid <NEW_LINE> if running_loop is not None and pid == os.getpid(): <NEW_LINE> <INDENT> return running_loop
Return the running event loop or None. This is a low-level function intended to be used by event loops. This function is thread-specific.
625941d3442bda511e8be5e9
def list_measurements(self, name): <NEW_LINE> <INDENT> if not self.has_category(name): <NEW_LINE> <INDENT> raise ValueError("The category '{}' does not exist!".format(name)) <NEW_LINE> <DEDENT> category = self._session.query(Category).filter_by(name=name).first() <NEW_LINE> return [measurement for measurement in catego...
Get all measurements of the category.
625941d3e5267d203edcde6e
def fetch_Landsat8_tile(amazon_url, tilename, outdir, bands = None): <NEW_LINE> <INDENT> if bands is None: <NEW_LINE> <INDENT> bands = map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, "QA"]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bands = map(str, (core.enf_list(bands))) <NEW_LINE> <DEDENT> connection = urllib.urlope...
This function makes use of the amazon web service hosted Landsat 8 OLI data. It recieves an amazon web url for a single landsat tile, and downloads the desired files :param amazon_url: url to amazons page hosting these landsat tiles :param tilename: landsat tile name :param outdir: output directory to place l...
625941d33346ee7daa2b2f40
def read_bitcoin_config(dbdir): <NEW_LINE> <INDENT> from ConfigParser import SafeConfigParser <NEW_LINE> class FakeSecHead(object): <NEW_LINE> <INDENT> def __init__(self, fp): <NEW_LINE> <INDENT> self.fp = fp <NEW_LINE> self.sechead = '[all]\n' <NEW_LINE> <DEDENT> def readline(self): <NEW_LINE> <INDENT> if self.sechead...
Read the kplus.conf file from dbdir, returns dictionary of settings
625941d321a7993f00bc7ec4
def build_ks(id): <NEW_LINE> <INDENT> spin = get_spin(id) <NEW_LINE> folder = "%s%s_%s/" % (settings.CACHE, spin.id, spin.name) <NEW_LINE> link = "%s/cache" % settings.MEDIA_ROOT <NEW_LINE> if not os.path.exists(folder): <NEW_LINE> <INDENT> os.makedirs(folder) <NEW_LINE> <DEDENT> if not os.path.exists(link): <NEW_LINE>...
Build Modified KS file
625941d3090684286d50eeb9
def test_role_invalidate(self): <NEW_LINE> <INDENT> self._identity_view_factory.add_policy("policy1", ["PERMIT_KEY key"]) <NEW_LINE> self._identity_view_factory.add_role( "network", "policy1") <NEW_LINE> self._identity_cache.invalidate("network") <NEW_LINE> self.assertEquals(self._identity_cache["network"], None) <NEW_...
Test that a role can be invalidated.
625941d3eab8aa0e5d26dd2b
def get_avg_cpu_utilization_percentage_for_environment(config): <NEW_LINE> <INDENT> logger = logging.getLogger(__name__) <NEW_LINE> instances = aws_ec2.get_running_instances(config) <NEW_LINE> cw = boto.ec2.cloudwatch.connect_to_region(config.get('region')) <NEW_LINE> env_metric = EnvMetric() <NEW_LINE> for instance in...
Return average CPU utilization for the given environment within number of minutes specified in config
625941d382261d6c526ab673
def find_elements_by_id(self, id): <NEW_LINE> <INDENT> return self._find_elements('id', id)
Find all elements with the given id.
625941d3377c676e9127237b
def canOverlap(self): <NEW_LINE> <INDENT> return False
Can the agent overlap with this?
625941d376e4537e8c351846
def parse_ix(self, x): <NEW_LINE> <INDENT> final_path = os.path.basename(x) <NEW_LINE> path = os.path.dirname(x) <NEW_LINE> output = namedtuple("ImageXpress", self.metadata_names) <NEW_LINE> well = final_path.split("_")[1] <NEW_LINE> row = self.get_row(well) <NEW_LINE> column = self.get_column(well) <NEW_LINE> site = i...
parse metadata from an MolDev Imagexpress filepath
625941d31f5feb6acb0c4d21
def itertools_cool_tools(): <NEW_LINE> <INDENT> seq = itt.chain(itt.repeat(7, 3), itt.cycle(range(4))) <NEW_LINE> for num in seq: <NEW_LINE> <INDENT> print(num)
This is a never ending one :-)
625941d3bde94217f3682fc2
def GetUnitOperatingState(self): <NEW_LINE> <INDENT> return str(self.query('1.3.6.1.4.1.476.1.42.3.9.20.1.20.1.2.1.4706'))
Unit Operating State
625941d35fcc89381b1e1893
def register(request): <NEW_LINE> <INDENT> if request.method != 'POST': <NEW_LINE> <INDENT> form = RegisterUserForm() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> form = RegisterUserForm(data=request.POST) <NEW_LINE> if form.is_valid(): <NEW_LINE> <INDENT> new_user = form.save() <NEW_LINE> authenticate_user = authenti...
注册新用户
625941d34e4d5625662d45a9
def test_kill_isolated_pixels_stats_example_nan_1(self): <NEW_LINE> <INDENT> input_img = np.array([[np.nan, 0, 1, 3, 0, np.nan], [ 0, 0, 0, 1, 0, 0], [ 5, 1, 0, 0, 1, 0], [np.nan, 0, 0, 1, 0, np.nan]]) <NEW_LINE> delta_pe, delta_abs_pe, delta_num_pixels = kill_isolated_pixels_stats(input_img, threshol...
Check the output of the kill_isolated_pixels_stats function.
625941d30fa83653e465718d
def get_organization_prototype_permissions(self, orgname, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.get_organization_prototype_permissions_with_http_info(orgname, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (...
get_organization_prototype_permissions # noqa: E501 List the existing prototypes for this organization. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_organization_prototype_permissions(orgname, async_req=Tru...
625941d3956e5f7376d7103f
def centerWidgetOnScreen(widget): <NEW_LINE> <INDENT> widget.move(QApplication.desktop().width() / 2 - widget.width() / 2, QApplication.desktop().height() / 2 - widget.height() / 2)
Centers given Widget middle of the screen. :param widget: Current Widget. :type widget: QWidget
625941d373bcbd0ca4b2c249
def get_orphanet_mappings_per_doid(self, doid): <NEW_LINE> <INDENT> return self.doid2orpha.get(doid, ['NA'])
This function return the orphanet mappings for the DO term queried. :param doid: DOID :return: orphanet mappings
625941d3462c4b4f79d1d8a3
def _handle_animal_type(hunter_class, prey_class): <NEW_LINE> <INDENT> if hunter_class == Carnivore: <NEW_LINE> <INDENT> hunter_list, prey_list = _carnivores, _herbivores <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hunter_list, prey_list = _herbivores, _plants <NEW_LINE> <DEDENT> born_hunters = [] <NEW_LINE> for hunt...
lets all animals of the hunter class act. eaten prey will be removed from the corresponding prey list. newborn/starved hunters will be added/removed from the corresponding hunter lists. :param hunter_class: the hunter class :param prey_class: the prey class
625941d3bd1bec0571d90802
def _findCommonPath(self, paths): <NEW_LINE> <INDENT> paths = [ [ y for y in x.split(os.path.sep) if y ] for x in paths ] <NEW_LINE> commonPath = [] <NEW_LINE> idx = 0 <NEW_LINE> maxIdx = min([ len(x) for x in paths ]) <NEW_LINE> found = False <NEW_LINE> while not found: <NEW_LINE> <INDENT> elements = set([ x[idx] for ...
Find the path that common amongst all paths involved.
625941d35166f23b2e1a532c
def experimental_distribute_datasets_from_function(self, dataset_fn): <NEW_LINE> <INDENT> if ops.executing_eagerly_outside_functions(): <NEW_LINE> <INDENT> return self._extended._experimental_distribute_datasets_from_function( dataset_fn) <NEW_LINE> <DEDENT> raise RuntimeError("`experimental_distribute_datasets_from_fu...
Distributes `tf.data.Dataset` instances created by calls to `dataset_fn`. Note: This API can only be used in eager mode. `dataset_fn` will be called once for each worker in the strategy. Each replica on that worker will dequeue one batch of inputs from the local `Dataset` (i.e. if a worker has two replicas, two batch...
625941d385dfad0860c3b02e