code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def ex_save_image(self, node, name): <NEW_LINE> <INDENT> image_elm = ET.Element( 'image', {'xmlns': self.XML_NAMESPACE, 'name': name, 'serverId': node.id}) <NEW_LINE> return self._to_image(self.connection.request("/images", method="POST", data=ET.tostring(image_elm)).object)
Create an image for node. @keyword node: node to use as a base for image @param node: L{Node} @keyword name: name for new image @param name: C{string}
625941d7796e427e537b0825
def __init__(self, frequency, amplitude=None, amplitude_multiplier=1): <NEW_LINE> <INDENT> if frequency <= 0: <NEW_LINE> <INDENT> raise ValueError("Oscillator.frequency cannot be <= 0") <NEW_LINE> <DEDENT> self.frequency = frequency <NEW_LINE> self.last_played_sample = 0 <NEW_LINE> if amplitude: <NEW_LINE> <INDENT> sel...
Args: frequency (float): Frequency in herz of the oscillator amplitude (AmplitudeHandler): Amplitude handler for the oscillator amplitude_multiplier (float): A factor to multiply amplitudes by during sample generation in addition to transformations occuring within ``self.amplitude``.
625941d7287bf620b61d3cc0
def transfer_file(name, login_username, login_password, local_file, remote_file): <NEW_LINE> <INDENT> ssh = paramiko.SSHClient() <NEW_LINE> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) <NEW_LINE> ssh.connect(name, username=login_username, password=login_password) <NEW_LINE> sftp = ssh.open_sftp() <NEW_LINE...
Transfers a local file on to a remote host via SFTP
625941d75f7d997b87174cf7
def main(context, event): <NEW_LINE> <INDENT> scene = context.scene <NEW_LINE> region = context.region <NEW_LINE> rv3d = context.region_data <NEW_LINE> coord = event.mouse_region_x, event.mouse_region_y <NEW_LINE> view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coord) <NEW_LINE> ray_origin = view3d_util...
Run this function on left mouse, execute the ray cast
625941d701c39578d7e7509a
def configure(self, params): <NEW_LINE> <INDENT> self._params = params <NEW_LINE> max_processes = int(params.get('max_processes', 4)) <NEW_LINE> max_threads = int(params.get('max_threads', 4)) <NEW_LINE> self._pool = ComplexProcessPool(max_processes=max_processes, max_threads=max_threads, init_func=self.__in...
Configures request processor. @param params:
625941d76aa9bd52df037002
def _ao(self, tt, dd, diff=2): <NEW_LINE> <INDENT> A = np.log(dd) <NEW_LINE> At = 0. <NEW_LINE> Ad = 0. <NEW_LINE> Att = 0. <NEW_LINE> Atd = 0. <NEW_LINE> Add = 0. <NEW_LINE> if diff>0: <NEW_LINE> <INDENT> At = 0 <NEW_LINE> Ad = 1./dd <NEW_LINE> if diff>1: <NEW_LINE> <INDENT> Add = -Ad/dd <NEW_LINE> Att = 0. <NEW_LINE>...
Dimensionless ideal gas helmholtz free energy (primative routine) Evaluates an ideal gas equation of the form a = log(dd) + logt*log(tt) + p(t) + ... c log(1-exp(-theta*tt)) + ... where dd = d / dscale tt = Tscale / T In the AOgroup dictionary defined by the mp1 data, the polynomial, p, is defined by ...
625941d791f36d47f21ac752
def pylogging_pandas(log_text="pylogging_pandas", **kwargs): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> df = pd.DataFrame(columns=['log_text']) <NEW_LINE> df = df.append({"log_text": log_text}, ignore_index=True) <NEW_LINE> logging.error(df)
Ensure pandas dataframes are handled properly https://github.com/googleapis/python-logging/issues/409
625941d72eb69b55b151cb0f
def test_add_submits(self): <NEW_LINE> <INDENT> data = { "simplemixedtest_set-TOTAL_FORMS": 3, "simplemixedtest_set-INITIAL_FORMS": 0, "simplemixedtest_set-MAX_NUM_FORMS": 1000, "_save": "Save", "name": "Mr", "slug": "mr", "simplemixedtest_set-0-name": "Test 1", "simplemixedtest_set-0-tags": "tag1, tag2", } <NEW_LINE> ...
Check inline add saves without error, and increments tag model
625941d7f9cc0f698b140858
def stroke_vertices_end(self): <NEW_LINE> <INDENT> pass
Returns a StrokeVertexIterator pointing after the last StrokeVertex of the Stroke. :rtype: StrokeVertexIterator :return: A StrokeVertexIterator pointing after the last StrokeVertex.
625941d74d74a7450ccd4421
def split_broadcast_domain(self): <NEW_LINE> <INDENT> domain_obj = netapp_utils.zapi.NaElement('net-port-broadcast-domain-split') <NEW_LINE> domain_obj.add_new_child("broadcast-domain", self.parameters['from_name']) <NEW_LINE> domain_obj.add_new_child("new-broadcast-domain", self.parameters['name']) <NEW_LINE> if self....
split broadcast domain
625941d72eb69b55b151cb10
def next_random_value(data: List, max_val: int) -> int: <NEW_LINE> <INDENT> if max_val > 0: <NEW_LINE> <INDENT> return data[random.randint(0, max_val - 1)]
Следующее случайное значение :param data: исходный список :param max_val: :return:
625941d794891a1f4081bd08
def evaluate(self, time): <NEW_LINE> <INDENT> for k in six.iterkeys(self.propMap): <NEW_LINE> <INDENT> if k == "brat" or k == "b": <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.pal[k] = self[self.propMap[k]] <NEW_LINE> <DEDENT> df = ((1.0 - self.pal.evaluate(time)) / self["p"]**2 * self["brat"]) <NEW_LINE> y = ...
Calculate a light curve for secondary transit. Parameters ---------- time : array An array of time points at which the light curve shall be calculated. .. note:: time = 0 -> Planet is exactly in the line of sight (phase = 0). Returns ------- Model : array The analytical light curve.
625941d76aa9bd52df037003
def n_pentagonals(n): <NEW_LINE> <INDENT> pentagon = [1] <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> pentagon.append(pentagon[i-1] + 3*(i) + 1) <NEW_LINE> <DEDENT> return pentagon
Returns a list of the first n pentagonal numbers according to the relation P_n - P_(n-1) + 3n + 1.
625941d75f7d997b87174cf8
def generate_targets(network, ports): <NEW_LINE> <INDENT> return [(urlparse(x).geturl()) for x in [''.join([ 'https://' if 's' in port else 'http://', str(ip), ':', str(port).replace('s', '') ]) for ip in network.iter_hosts() for port in ports]]
A generator for compiled URLs
625941d7e1aae11d1e749f17
def send(tensor, dst, group=None, tag=0): <NEW_LINE> <INDENT> _check_single_tensor(tensor, "tensor") <NEW_LINE> if _rank_not_in_group(group): <NEW_LINE> <INDENT> _warn_not_in_group("send") <NEW_LINE> return <NEW_LINE> <DEDENT> if group is None or group is GroupMember.WORLD: <NEW_LINE> <INDENT> default_pg = _get_default...
Sends a tensor synchronously. Args: tensor (Tensor): Tensor to send. dst (int): Destination rank. group (ProcessGroup, optional): The process group to work on. If None, the default process group will be used. tag (int, optional): Tag to match send with remote recv
625941d7f548e778e58cd7dd
def get_slices(large_array_shape, small_array_shape, position): <NEW_LINE> <INDENT> y_min = int(position[1] + 0.5 - small_array_shape[0] / 2.) <NEW_LINE> x_min = int(position[0] + 0.5 - small_array_shape[1] / 2.) <NEW_LINE> y_max = int(position[1] + 0.5 + small_array_shape[0] / 2.) <NEW_LINE> x_max = int(position[0] + ...
Get slices for the overlapping part of a small and a large array. Given a certain position of the center of the small array, with respect to the large array, four slices are computed, which can be used to extract, add or subtract the small array at the given position. This function takes care of the correct behavior a...
625941d7ac7a0e7691ed4327
def test_01(self): <NEW_LINE> <INDENT> fir = tm10.FeedInformationRequest(generate_message_id()) <NEW_LINE> msg = make_request(COLLECTION_MGMT_11_PATH, fir.to_xml(), get_headers(VID_TAXII_SERVICES_10, False), MSG_FEED_INFORMATION_RESPONSE)
Send a feed information request, look to get a feed information response back
625941d78a43f66fc4b542c1
def parse_config(self, file): <NEW_LINE> <INDENT> log.debug("parsing config file: {}".format(file)) <NEW_LINE> config = configparser.ConfigParser() <NEW_LINE> config.read(file) <NEW_LINE> self._run_dir = config['warcraft']['run_dir'] <NEW_LINE> self._guilds = {} <NEW_LINE> for gkey in re.compile(r',').split(config['war...
Read the local configuration from the file specified.
625941d7627d3e7fe0d690af
def before_all(context): <NEW_LINE> <INDENT> tooling.init() <NEW_LINE> context.samples_dir = os.getcwd() <NEW_LINE> context.config.setup_logging(configfile=os.path.join(context.samples_dir, 'logging.ini')) <NEW_LINE> context.log = logging.getLogger('pivotal') <NEW_LINE> context.log.info("Steeltoe Samples test suite") <...
behave hook called before running test features :type context: behave.runner.Context
625941d757b8e32f524836fa
def comparison_negative(logical_line): <NEW_LINE> <INDENT> match = COMPARE_NEGATIVE_REGEX.search(logical_line) <NEW_LINE> if match: <NEW_LINE> <INDENT> pos = match.start(1) <NEW_LINE> if match.group(2) == 'in': <NEW_LINE> <INDENT> yield pos, "E713 test for membership should be 'not in'" <NEW_LINE> <DEDENT> else: <NEW_L...
Negative comparison should be done using "not in" and "is not". Okay: if x not in y:\n pass Okay: assert (X in Y or X is Z) Okay: if not (X in Y):\n pass Okay: zz = x is not y E713: Z = not X in Y E713: if not X.B in Y:\n pass E714: if not X is Y:\n pass E714: Z = not X.B is Y
625941d74527f215b584c6b3
def is_gcs_url(url) -> bool: <NEW_LINE> <INDENT> if not isinstance(url, str): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return parse_url(url).scheme in ["gcs", "gs"]
Check for a gcs url
625941d726068e7796caef40
def view_gui(self): <NEW_LINE> <INDENT> def set_value(val): <NEW_LINE> <INDENT> self.chosen_val = val <NEW_LINE> frame.quit() <NEW_LINE> <DEDENT> menu = tkinter.Menu(self.root) <NEW_LINE> self.root.config(menu=menu) <NEW_LINE> help_menu = tkinter.Menu(menu) <NEW_LINE> menu.add_cascade(label="Help", menu=help_menu) <NEW...
Lunches GUI structure
625941d7ab23a570cc2503e2
def _get_all_oai_tasks_full_name(): <NEW_LINE> <INDENT> return [watch_registry_harvest_task.__name__, harvest_task.__name__]
Get all OAI-PMH tasks name. Returns: List of OAI-PMH tasks name.
625941d7442bda511e8be674
def __init__(self, expression=None, range_variable=None, item_type=None): <NEW_LINE> <INDENT> self._expression = None <NEW_LINE> self._range_variable = None <NEW_LINE> self._item_type = None <NEW_LINE> self.discriminator = None <NEW_LINE> if expression is not None: <NEW_LINE> <INDENT> self.expression = expression <NEW_...
FilterClause - a model defined in Swagger
625941d74f6381625f114c9a
def memo(f): <NEW_LINE> <INDENT> cache = {} <NEW_LINE> def _f(*args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return cache[args] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> cache[args] = result = f(*args) <NEW_LINE> return result <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return f(args)...
Decorator that caches the return value for each call to f(args). Then when called again with same args, we can just look it up.
625941d799cbb53fe6792e45
def display_write_to_list(): <NEW_LINE> <INDENT> print('Data written to file')
Prints a message confirming data written to list
625941d766673b3332b922f0
def activate_rocket_launcher(self, _setting, newVal): <NEW_LINE> <INDENT> if not newVal: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from pyrocket_backend import RocketManager <NEW_LINE> self.rocket_controller = RocketManager() <NEW_LINE> err_msg = self.rocket_controller.acquire_devices() <NEW_LINE> if err_msg: <NEW_L...
only called if not remote_only -> the rocket launcher is attached to this peer
625941d771ff763f4b5498ed
def compare_elements_title_by_class(self, css_class, text, first_only, without_space="False"): <NEW_LINE> <INDENT> self._info("Compare elements title with class '%s'." % css_class) <NEW_LINE> elems = None <NEW_LINE> if first_only == 'True': <NEW_LINE> <INDENT> elems = self._element_find("css=" + css_class, True, False)...
Compare all elements' title which find by cas class
625941d776e4537e8c3518d2
def __init__(self): <NEW_LINE> <INDENT> self.W = 0 <NEW_LINE> self.H = 0 <NEW_LINE> self.get_params().append(self.get_parent().get_parent().Param( block=self, n=odict({ 'name': 'GUI Coordinate', 'key': '_coordinate', 'type': 'raw', 'value': '(0, 0)', 'hide': 'all', }) )) <NEW_LINE> self.get_params().append(self.get_par...
Block contructor. Add graphics related params to the block.
625941d75166f23b2e1a53b7
def __init__(self, num_units, memory, memory_sequence_length=None, scale=False, score_mask_value=None, sigmoid_noise=0., sigmoid_noise_seed=None, score_bias_init=0., mode="parallel", dtype=None, name="LuongMonotonicAttention"): <NEW_LINE> <INDENT> if dtype is None: <NEW_LINE> <INDENT> dtype = dtypes.float32 <NEW_LINE> ...
Construct the Attention mechanism. Args: num_units: The depth of the query mechanism. memory: The memory to query; usually the output of an RNN encoder. This tensor should be shaped `[batch_size, max_time, ...]`. memory_sequence_length (optional): Sequence lengths for the batch entries in memory. If pr...
625941d7cc40096d61595baf
def test_simple(self): <NEW_LINE> <INDENT> log.debug('===== START TEST SIMPLE RECOVERED =====') <NEW_LINE> in_file = self.open_file(FILE2) <NEW_LINE> parser = self.create_rec_parser(in_file) <NEW_LINE> for expected in EXPECTED_FILE2: <NEW_LINE> <INDENT> expected_particle = FlortDjDclRecoveredInstrumentDataParticle(expe...
Read data from a file and pull out data particles one at a time. Verify that the results are those we expected.
625941d7a8ecb033257d332b
def __wait_for_symbol(self): <NEW_LINE> <INDENT> while not {'instrument', 'trade', 'quote'} <= set(self.data): <NEW_LINE> <INDENT> sleep(0.1)
On subscribe, this data will come down. Wait for it.
625941d791f36d47f21ac753
def GetParameter(self, request: Any, context: Any) -> Any: <NEW_LINE> <INDENT> get_parameter_values_response = GetParameterResponse() <NEW_LINE> state_machine = self.state_machine_pointer.state_machine <NEW_LINE> parameter_path = request.parameter_name <NEW_LINE> data_model = self.state_machine_pointer.state_machine.da...
Sends a GetParameterValues message. Used for testing only.
625941d791af0d3eaac9bc79
def json_dumps(*pargs, **kwargs): <NEW_LINE> <INDENT> return json.dumps(*pargs, cls=IEncoder, **kwargs)
Special json dumper to use our __json__ function where appropriate.
625941d73617ad0b5ed68155
def validSelf(self): <NEW_LINE> <INDENT> logger.info('Check 员工管理 begin') <NEW_LINE> API().assertElementByName(self.testcase, self.driver, self.logger, Name.employeeManager) <NEW_LINE> logger.info('Check 员工管理 end')
验证员工管理 :return:
625941d7be7bc26dc91cd85b
def construct_shape_token(self, d: Dict) -> List[Dict]: <NEW_LINE> <INDENT> result = [] <NEW_LINE> if not d["shapes"]: <NEW_LINE> <INDENT> this_token = {attrs.IS_ASCII: True} <NEW_LINE> result.append(this_token) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for shape in d["shapes"]: <NEW_LINE> <INDENT> this_shape = sel...
Construct a shape token Args: d: Dict Returns: List[Dict]
625941d7e64d504609d74a9f
def __init__(self, hass): <NEW_LINE> <INDENT> self.hass = hass <NEW_LINE> self.entity_id = "sensor.octopus_agile_previous_rate" <NEW_LINE> self._state = None <NEW_LINE> self._attributes = {} <NEW_LINE> region_code = hass.states.get("octopusagile.region_code").state <NEW_LINE> self.myrates = Agile(region_code) <NEW_LINE...
Initialize the sensor.
625941d750485f2cf553cff9
def findWords(self, board, words): <NEW_LINE> <INDENT> res = [] <NEW_LINE> visited = [[False for j in xrange(len(board[0]))] for i in xrange(len(board))] <NEW_LINE> root = Trie() <NEW_LINE> for word in words: <NEW_LINE> <INDENT> root.insert(word) <NEW_LINE> <DEDENT> for i in xrange(len(board)): <NEW_LINE> <INDENT> for ...
:type board: List[List[str]] :type words: List[str] :rtype: List[str]
625941d70a50d4780f6670f2
def print_stats(stats): <NEW_LINE> <INDENT> print("Clientid: %s" % stats["clientid"]) <NEW_LINE> print("Total clients tracked: %s" % stats["client_count"]) <NEW_LINE> print("Total messages: %d" % stats["msg_count"]) <NEW_LINE> print("Total time: %0.2f secs" % stats["time_total"]) <NEW_LINE> print("Messages per second: ...
pretty print a listen stats object
625941d7b7558d58953c516f
def pesquisar(self): <NEW_LINE> <INDENT> filtro = self.texto_pesquisa.get() <NEW_LINE> if filtro == self.pesquisa_default: <NEW_LINE> <INDENT> filtro = '' <NEW_LINE> <DEDENT> self.text_programas.configure(state='normal') <NEW_LINE> self.text_programas.delete('1.0', tkinter.END) <NEW_LINE> if not filtro: <NEW_LINE> <IND...
Método para efetuar a pesquisa dos programas, filtrando a lista de acordo com o informado no campo de pesquisa. :return: None.
625941d7b57a9660fec33ae6
def minimax(self, game, depth): <NEW_LINE> <INDENT> def terminal_test(game, self): <NEW_LINE> <INDENT> if len(game.get_legal_moves(self)) == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def max_value(self, game, depth): <NEW_LINE> <INDENT> if...
Implement depth-limited minimax search algorithm as described in the lectures. This should be a modified version of MINIMAX-DECISION in the AIMA text. https://github.com/aimacode/aima-pseudocode/blob/master/md/Minimax-Decision.md ********************************************************************** You MAY add a...
625941d7d10714528d5fff44
def test_activity_date_not_given(self): <NEW_LINE> <INDENT> new_activity = dict(name="tech congress", description="all about tech", activityTypeId=self.get_activity_type_id( "Tech Event")) <NEW_LINE> response = self.client.post('/api/v1/activities', data=json.dumps(new_activity), headers=self.successops_token, content_...
Test of activity date is not provided.
625941d7b7558d58953c5170
def distance_from_inclusion(geometry, p, **kwargs): <NEW_LINE> <INDENT> import scipy.ndimage as _spim <NEW_LINE> net = geometry._net <NEW_LINE> x = net._shape[0] <NEW_LINE> y = net._shape[1] <NEW_LINE> z = net._shape[2] <NEW_LINE> img = _sp.rand(x, y, z) > p <NEW_LINE> a = _sp.tile(img, [3, 3, 3]) <NEW_LINE> b = a[x:-x...
Genrate spatially correlated pore seeds by calculating distance from random locations (inclusions) in the domain Parameters ---------- p : float The fraction of pores in the domain that are set as 'seeds' for the distance calculation Returns ------- A list of distance values (in voxels) between each pore and ...
625941d72ae34c7f2600d390
def combine(self, n, k): <NEW_LINE> <INDENT> return list(combinations(range(1, n+1), k))
:type n: int :type k: int :rtype: List[List[int]] beats 49.34%
625941d792d797404e3043ea
def _extract_word2freq(self, texts): <NEW_LINE> <INDENT> assert texts is not None <NEW_LINE> word2freq = {} <NEW_LINE> for words in texts: <NEW_LINE> <INDENT> for word in words: <NEW_LINE> <INDENT> if (not word.startswith('#')) and (not word.startswith('@')): <NEW_LINE> <INDENT> if word not in word2freq: <NEW_LINE> <IN...
Count word frequency :param texts: :return:
625941d738b623060ff0b04c
def torsionAngleCalc(atoms, molecule): <NEW_LINE> <INDENT> if self.distanceMatrix[atoms[0]][atoms[1]] >= 4 or self.distanceMatrix[atoms[1]][atoms[2]] >= 4 or self.distanceMatrix[atoms[2]][atoms[3]] >= 4: <NEW_LINE> <INDENT> return "too far" <NEW_LINE> <DEDENT> cross_product1 = np.cross(self.UnitVectorCalculator(atoms[...
Calculates the torsional angle between 4 atoms input: atoms: a tuple of numbers representing atoms molecule: a tuple as generated by the dataReader function distanceMatrix: a matrix that holds the interatomic distances output: the torsion angle note: the distanceMatrix is a global variable. It needs to be set before...
625941d7d486a94d0b98e3a5
def connection_made(self, transport): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.client = self.server.new_client(transport) <NEW_LINE> <DEDENT> except ClientError: <NEW_LINE> <INDENT> transport.close() <NEW_LINE> return <NEW_LINE> <DEDENT> if not self.server.client_manager.new_client_preauth(self.client): <NEW_L...
Called upon a new client connecting :param transport: the transport object
625941d7aad79263cf390ca3
def add_init_command_to_parser(parser): <NEW_LINE> <INDENT> init_parser = parser.add_parser( 'init', help='Initializes a new back-up configuration.') <NEW_LINE> init_parser.set_defaults(func=lambda parsed_args: init()) <NEW_LINE> return parser
Add the configuration initialization command to a parser. :param parser: argparse.ArgumentParser :return: argparse.ArgumentParser
625941d74a966d76dd551270
def statistics(data, groupby=None, mode="default"): <NEW_LINE> <INDENT> if isinstance(data, pd.Series): <NEW_LINE> <INDENT> df_columns = [data.name] <NEW_LINE> <DEDENT> elif isinstance(data, pd.DataFrame): <NEW_LINE> <INDENT> df_columns = data.columns.values <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError...
Calculate statistics for data. # example: >>> statistics(data, groupby="squid") # which is roughly equivalent to >>> data.groupby("squid").describe() args: data pandas.DataFrame() or pandas.Series() groupby=None str/ list/ np.array() mode="default" "count" = coun...
625941d7283ffb24f3c55b5e
def clear_collection(self, *classes): <NEW_LINE> <INDENT> for c in classes: <NEW_LINE> <INDENT> self.db[c.get_collection_name()].remove()
Clear all objects from the collections associated with the objects in `*cls`. **use with caution!**
625941d77cff6e4e81117be4
def gen_state(): <NEW_LINE> <INDENT> state = np.array([np.random.choice([-1,1]) for _ in range(L*L)], dtype=np.int32) <NEW_LINE> return state
generate random start state with lenght L*L and [-1,1] components
625941d7d7e4931a7ee9e17d
@app.route('/users/<username>/delete', methods=['POST']) <NEW_LINE> def delete_user(username): <NEW_LINE> <INDENT> if session['username'] != username: <NEW_LINE> <INDENT> raise Unauthorized("Sorry, you're not authorized to do that!") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> user = User.query.filter_by(username=use...
When delete user is selected, remove user and children posts from DB
625941d724f1403a92600dc3
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> end = 0 <NEW_LINE> start = end <NEW_LINE> end += 24 <NEW_LINE> self.ned_xyz = _get_struct_3d().unpack(str[start:end]) <NEW_LINE> start = end <NEW_LINE> end += 24 <NEW_LINE> self.ned_uvw = _get_struct_3d().unpack(str[start:end]) <NEW_LINE> _x = sel...
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
625941d7090684286d50ef46
def create_db(dbFile): <NEW_LINE> <INDENT> if not os.path.isfile(dbFile): <NEW_LINE> <INDENT> db_file = open(dbFile, 'w') <NEW_LINE> db_file.close()
Create database if there is not dbFile(argument) :param dbFile: Name of database
625941d7d18da76e23532737
def test_set_good_changeset_get(self): <NEW_LINE> <INDENT> self.client.login(username=self.user.username, password='password') <NEW_LINE> response = self.client.get( reverse('changeset:set-good', args=[self.changeset_2]), ) <NEW_LINE> self.assertEqual(response.status_code, 405) <NEW_LINE> self.changeset_2.refresh_from_...
GET is not an allowed method in the set_good URL.
625941d73cc13d1c6d3c75d9
def set_rholib(self, rholib): <NEW_LINE> <INDENT> self.rholib = rholib
Set the rho library (electron density shape of the atoms)
625941d74e696a04525c96ab
def setup_platform(hass, config, add_entities, discovery_info=None): <NEW_LINE> <INDENT> accounts = hass.data[BMW_DOMAIN] <NEW_LINE> _LOGGER.debug('Found BMW accounts: %s', ', '.join([a.name for a in accounts])) <NEW_LINE> devices = [] <NEW_LINE> for account in accounts: <NEW_LINE> <INDENT> if not account.read_only: <N...
Set up the BMW Connected Drive lock.
625941d7507cdc57c6306f3e
def loadGroupAndMsg(self): <NEW_LINE> <INDENT> f = open(config.KEYSPATH+"msgmap", "r") <NEW_LINE> return json.load(f)
Loads the msg/group association map
625941d744b2445a339322f4
@commandWrap <NEW_LINE> def MediumQualityDisplay(*args, **kwargs): <NEW_LINE> <INDENT> return cmds.MediumQualityDisplay(*args, **kwargs)
:rtype: list|str|DagNode|AttrObject|ArrayAttrObject|Components1Base
625941d7046cf37aa974cfa5
def containsNearbyAlmostDuplicate(self, nums, k, t): <NEW_LINE> <INDENT> if k <= t: <NEW_LINE> <INDENT> for i in range(len(nums)): <NEW_LINE> <INDENT> for j in range(1, k+1): <NEW_LINE> <INDENT> if i+j >= len(nums): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if abs(nums[i+j] - nums[i]) <= t: <NEW_LINE> <INDENT> retu...
:type nums: List[int] :type k: int :type t: int :rtype: bool
625941d7377c676e91272407
def max_growth_rate(l): <NEW_LINE> <INDENT> k = 0 <NEW_LINE> idx = sorted_eigen(k, l) <NEW_LINE> return solver.eigenvalues[idx[-1]].imag
Finds maximum growth rate for given wavenumbers k, l.
625941d7d164cc6175782fae
def setFilterEnabled(self, filterEnabled): <NEW_LINE> <INDENT> self.filterEnabled = filterEnabled
:param filterEnabled: (Optional) 过滤器是否启用。当appcode为custom时必填
625941d78c3a87329515861c
def get_all_repo_list(): <NEW_LINE> <INDENT> if get_config('isLogin') == 'False' or get_config('isLogin') == '': <NEW_LINE> <INDENT> get_cookie() <NEW_LINE> login() <NEW_LINE> <DEDENT> d = get_repo_list(1) <NEW_LINE> all_repo_list = d[0] <NEW_LINE> repo_nums = int(d[1]) <NEW_LINE> if repo_nums < 31: <NEW_LINE> <INDENT>...
获取当前账号所有项目名称集合 :return:all_repo_list==>>所有项目名称集合
625941d7eab8aa0e5d26ddb8
def testCacheNXWithNoRR(self): <NEW_LINE> <INDENT> misses = 0 <NEW_LINE> name = 'nxwithnorr.cache.tests.powerdns.com.' <NEW_LINE> query = dns.message.make_query(name, 'A', 'IN') <NEW_LINE> response = dns.message.make_response(query) <NEW_LINE> response.set_rcode(dns.rcode.NXDOMAIN) <NEW_LINE> (receivedQuery, receivedRe...
Cache: NX with no RR
625941d7d8ef3951e324379d
def prepare_workers_for_html(workers): <NEW_LINE> <INDENT> worker_items = [] <NEW_LINE> for worker in workers: <NEW_LINE> <INDENT> worker['url'] = {} <NEW_LINE> worker['url']['single'] = ViewUrlGenerator.get_worker_url(worker['id']) <NEW_LINE> worker['url']['feed_report'] = ViewUrlGenerator.get_feed_report_form_worker_...
Prepares workers for html template
625941d773bcbd0ca4b2c2d6
def Bellman_Ford(g, source, destination): <NEW_LINE> <INDENT> g.reset() <NEW_LINE> edges = g._getEdges() <NEW_LINE> ne = len(edges) <NEW_LINE> start = g._getVertex(source) <NEW_LINE> end = g._getVertex(destination) <NEW_LINE> start._setDistance(0) <NEW_LINE> for _ in range(ne): <NEW_LINE> <INDENT> for a, b, w in edges:...
Bellman-Ford shortest path algorithm. NOTE: - It is a dynamic programming algorithm. - Compared to Dijkstra, handles multigraphs as well as graphs with negative edge weights. Args: g (graph): a graph object. source (node val data type): the data of the source node. destination (node val data type)...
625941d7711fe17d825425c7
def createDimension(self, name, length): <NEW_LINE> <INDENT> dim = self.dimensions[name] = PseudoNetCDFDimension(self, name, length) <NEW_LINE> return dim
name - string name for dimension length - maximum length of dimension
625941d7b5575c28eb68e261
def _call_exe_order(self, col_data): <NEW_LINE> <INDENT> exe_stack = [] <NEW_LINE> for obj in self.exe_order: <NEW_LINE> <INDENT> if isinstance(obj, _Rule): <NEW_LINE> <INDENT> self._perform_operation(obj, exe_stack, col_data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> exe_stack.append(obj) <NEW_LINE> <DEDENT> <DEDE...
Do stored expression. :param col_data: cleaned data assigned to each column :type col_data: dict :returns: expression result :rtype: bool
625941d756ac1b37e626442c
def will_be_allston_course_canonical_cn(cn): <NEW_LINE> <INDENT> start = cn.find(' ') <NEW_LINE> subject = cn[:start] <NEW_LINE> catalog = cn[start+1:] <NEW_LINE> assert subject == subject.upper().strip() <NEW_LINE> assert catalog == catalog.upper().strip() <NEW_LINE> return will_be_allston_course_subj_catalog(subject,...
Given canonical course name, determine whether this course will be taught in Allston in the future. :param cn, e.g., "COMPSCI 50" :return boolean indicating whether the course will be taught in Alston.
625941d7ad47b63b2c50a1df
def test_entropy(self): <NEW_LINE> <INDENT> env_spec = TfEnv(DummyBoxEnv()) <NEW_LINE> init_std = 1. <NEW_LINE> obs = torch.Tensor([0, 0, 0, 0]).float() <NEW_LINE> policy = TanhGaussianMLPPolicy(env_spec=env_spec, hidden_sizes=(1, ), init_std=init_std, hidden_nonlinearity=None, std_parameterization='exp', hidden_w_init...
Test get_entropy method of the policy.
625941d7435de62698dfdead
def read_data(filename): <NEW_LINE> <INDENT> filename = os.path.join(os.path.dirname(__file__), 'testdata', filename) <NEW_LINE> with open(filename) as f: <NEW_LINE> <INDENT> return f.read()
return the data of testdata/${filename}
625941d7dd821e528d63b407
def update(self, instance, validated_data): <NEW_LINE> <INDENT> instance.id_material_id = validated_data['materialId'] <NEW_LINE> instance.oper_date = validated_data['date'] <NEW_LINE> instance.oper_value = validated_data['total'] <NEW_LINE> instance.save()
Неоконченный код!!!!!!!!!!!!!
625941d7e8904600ed9f218f
def split_time(value: float) -> Tuple[int, int]: <NEW_LINE> <INDENT> seconds = int(value) <NEW_LINE> microseconds = int(1e6 * (value - seconds)) <NEW_LINE> return seconds, microseconds
Given seconds as a float, return whole seconds and microseconds
625941d7090684286d50ef47
def login_required(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def decorated_function(*args, **kwargs): <NEW_LINE> <INDENT> if 'user' not in login_session: <NEW_LINE> <INDENT> return redirect(url_for('show_login', next=request.url)) <NEW_LINE> <DEDENT> return f(*args, **kwargs) <NEW_LINE> <DEDENT> return decorated_fun...
Decorator method to make checking if the user is logged in easier. Returns: Redirect the client to the log in page.
625941d767a9b606de4a8118
@cli.command() <NEW_LINE> def upload(): <NEW_LINE> <INDENT> current_version, _, _ = parse_version_from_module() <NEW_LINE> tag_name = f"v{current_version}" <NEW_LINE> pypi_asset_names = [ f"matrix_synapse-{current_version}-py3-none-any.whl", f"matrix-synapse-{current_version}.tar.gz", ] <NEW_LINE> with TemporaryDirecto...
Upload release to pypi.
625941d7656771135c3ebad1
def test_add_existing_farm(two_farms): <NEW_LINE> <INDENT> with pytest.raises(ValueError): <NEW_LINE> <INDENT> two_farms.add({ 'Name': 'Horns Rev 3', 'Country': 'Denmark', 'Commissioning Year': 2019, 'Capacity MW': 407 })
Should raise an error since 'Horns Rev 3' is included in two_farms already.
625941d77c178a314d6ef6c2
@commands('ratid','id') <NEW_LINE> @ratlib.sopel.filter_output <NEW_LINE> @parameterize('w', usage='<ratname>') <NEW_LINE> def cmd_ratid(bot, trigger, rat): <NEW_LINE> <INDENT> id = getRatId(bot=bot, ratname=rat) <NEW_LINE> bot.say('Rat id for '+str(id['name'])+' is '+str(id['id']))
Get a rats' id from the api required parameters: rat name
625941d78e05c05ec3eea5d6
def shift(self,amount): <NEW_LINE> <INDENT> self.pos += amount <NEW_LINE> if self.pos < 0: <NEW_LINE> <INDENT> self.pos = 0 <NEW_LINE> <DEDENT> if self.pos > self.h - self.slidersize: <NEW_LINE> <INDENT> self.pos = self.h - self.slidersize
Shift the scrollbar up or down.
625941d75fc7496912cc3bde
def hp_max_capacity_5F(self): <NEW_LINE> <INDENT> cop_5F = np.interp(5.0, HomeHeatModel.TEMPS_FIT, HomeHeatModel.COPS_FIT) <NEW_LINE> max_from_curve = cop_5F * self.hp_model.in_pwr_5F_max * 3412. <NEW_LINE> return min(max_from_curve, self.hp_model.capacity_5F_max)
Returns the maximum capacity of the heat pump at 5 deg F. Uses the COP curve unless the manufacturer's spec is lower. Returns is Btu/hour.
625941d7379a373c97cfada6
def _set_required(self, config_path): <NEW_LINE> <INDENT> self['path']['user'] = str(Path.home()) if 'MEG_USER_PATH' not in os.environ else os.environ['MEG_USER_PATH'] <NEW_LINE> self['path']['config'] = config_path <NEW_LINE> if 'downloads' not in self['path']: <NEW_LINE> <INDENT> downloads_path = os.path.join('$(path...
Set the default values
625941d7fbf16365ca6f6426
def run_local_bears_on_file(message_queue, timeout, file_dict, local_bear_list, local_result_dict, control_queue, filename): <NEW_LINE> <INDENT> if filename not in file_dict: <NEW_LINE> <INDENT> send_msg(message_queue, timeout, LOG_LEVEL.ERROR, _("An internal error occurred."), Constants.THIS_IS_A_BUG) <NEW_LINE> send_...
This method runs a list of local bears on one file. :param message_queue: A queue that contains messages of type errors/warnings/debug statements to be printed in the Log. :param timeout: The queue blocks at most timeout seconds for a ...
625941d70383005118ecf842
def running(self): <NEW_LINE> <INDENT> return self._state == RUNNING_STATE
Indicates if the future is in running state
625941d7796e427e537b0827
def get_ranked_phrases(self) -> List[Sentence]: <NEW_LINE> <INDENT> return self.ranked_phrases
Method to fetch ranked keyword strings. :return: List of strings where each string represents an extracted keyword string.
625941d7283ffb24f3c55b5f
def expand_country(self, *countries, debug=False): <NEW_LINE> <INDENT> log = self._get_log(debug) <NEW_LINE> count = 0 <NEW_LINE> for country in countries: <NEW_LINE> <INDENT> log('Have country code {0}', country) <NEW_LINE> zones = country_timezones[country] <NEW_LINE> log('Country code {0} has {1} timezones', country...
:param countries: Zero or more country codes. :param debug: Print an explanation of the process followed to stdout? :return: A sequence of timezones for the countries given.
625941d701c39578d7e7509b
def sum_fib(n): <NEW_LINE> <INDENT> s = 0 <NEW_LINE> for i in range(n+1): <NEW_LINE> <INDENT> s += fib(i) <NEW_LINE> <DEDENT> return s
Return the sum from fib(0) to fib(n)
625941d7c432627299f04ea7
def create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): <NEW_LINE> <INDENT> document = all_documents[document_index] <NEW_LINE> instances = [] <NEW_LINE> raw_text_list_list = get_raw_instance(document, max_seq_length)...
Creates `TrainingInstance`s for a single document.
625941d7bd1bec0571d90890
def mutate_one_gene(self, genome): <NEW_LINE> <INDENT> layer_to_mutate = random.choice(genome.layers) <NEW_LINE> index_layer_to_mutate = genome.layers.index(layer_to_mutate) <NEW_LINE> gene_type_to_mutate = random.choice(list(layer_to_mutate)) <NEW_LINE> new_gene_val = random.choice(self.config['hyperparams'][gene_type...
Mutate a gene (CNN hyper-paramater) within a genome. - First choose a random layer to mutate. - Then choose a random gene-type (i.e. activation or dropout) to mutate. - Then choose a random new value for the gene in that layer based on its type.
625941d731939e2706e4d0c7
@app.route("/history") <NEW_LINE> @login_required <NEW_LINE> def history(): <NEW_LINE> <INDENT> stocks = db.execute("SELECT symbol, shares, price, timewhen FROM portfolio WHERE user_id = :user_id ORDER BY timewhen", user_id=session["user_id"]) <NEW_LINE> for stock in stocks: <NEW_LINE> <INDENT> stock["price"] = usd(sto...
Show history of transactions
625941d799fddb7c1c9de5f1
def test_log_recv(self): <NEW_LINE> <INDENT> self.logger.open_test_case(self.some_test_case_id, name=self.some_test_case_name, index=self.some_test_case_index) <NEW_LINE> self.logger.log_recv(self.some_recv_data) <NEW_LINE> self.virtual_file.seek(0) <NEW_LINE> self.assertRegexpMatches(self.virtual_file.readline(), LOGG...
Given: FuzzLoggerCsv with a virtual file handle. When: Calling open_test_case with some test_case_id. and: Calling log_recv with some data. Then: open_test_case logs as expected. and: log_recv logs as expected.
625941d7796e427e537b0828
def target(self): <NEW_LINE> <INDENT> """Defines surfaces touching other surfaces"""
Defines the target pizza
625941d7a8ecb033257d332c
def new_chain_and_ball(game_state): <NEW_LINE> <INDENT> c = Composite() <NEW_LINE> set_item_components(c, game_state) <NEW_LINE> set_melee_weapon_component(c) <NEW_LINE> c.set_child(Description("Chain and Spike Ball", "A huge metal ball on a chain, hard to use but can deal massive damage.")) <NEW_LINE> c.set_child(Grap...
A composite component representing a Sword item.
625941d7bf627c535bc1342f
def test_server_update_server_flavor_failed(self): <NEW_LINE> <INDENT> return_server = self.fc.servers.list()[1] <NEW_LINE> return_server.id = '1234' <NEW_LINE> server = self._create_test_server(return_server, 'srv_update2') <NEW_LINE> self._stub_glance_for_update() <NEW_LINE> update_template = copy.deepcopy(server.t) ...
If the status after a resize is not VERIFY_RESIZE, it means the resize call failed, so we raise an explicit error.
625941d7004d5f362079a593
def _get_templates(self): <NEW_LINE> <INDENT> return ('scout/notifications/email/unexpected.txt', 'scout/notifications/email/expected.txt')
Returns a two element tuple of template paths. The first one being for errors, and the second one for recovery use.
625941d78e7ae83300e4b22d
def startgame(): <NEW_LINE> <INDENT> rand_m = random.randint(1, 5) <NEW_LINE> n = int(input('Введите целое число от 1 до 5: ')) <NEW_LINE> if n != rand_m: <NEW_LINE> <INDENT> print('Повторите еще раз') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Победа')
Запускает игру 'Угадай число'
625941d707f4c71912b116e4
def __init__(self, api_key=""): <NEW_LINE> <INDENT> if api_key == "": <NEW_LINE> <INDENT> api_key = self.DEMO_KEY <NEW_LINE> <DEDENT> self.api_key = api_key <NEW_LINE> user_agent = "{0} {1}".format(requests.utils.default_headers()['User-Agent'], platform.system()) <NEW_LINE> self.headers = {'User-Agent': user_agent}
Initializes the API client object :param api_key:
625941d7f548e778e58cd7df
def setLEDDrive(self, drive): <NEW_LINE> <INDENT> self._write_byte_data(REG_CONTROL, (self._read_byte_data(REG_CONTROL) & ~0xc0) | (drive << 6))
Sets LED drive strength for proximity and ALS. Value LED Current 0 100 mA 1 50 mA 2 25 mA 3 12.5 mA Args: drive (int): value for the LED drive strength
625941d7cc0a2c11143dd0f1
def create_dummy_server(file_with_content, mimetype): <NEW_LINE> <INDENT> current_script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) <NEW_LINE> dummy_server_file = os.path.join(current_script_dir, 'servers', 'dummy-response-server.py') <NEW_LINE> port = find_open_port() <NEW_LINE> cm...
Helper method that creates a dummy server that always returns the contents of the file specified with the mimetype specified
625941d7287bf620b61d3cc3
def __init__(self, response=None, status=None, _configuration=None): <NEW_LINE> <INDENT> if _configuration is None: <NEW_LINE> <INDENT> _configuration = Configuration() <NEW_LINE> <DEDENT> self._configuration = _configuration <NEW_LINE> self._response = None <NEW_LINE> self._status = None <NEW_LINE> self.discriminator ...
ResponseContainerListIntegrationManifestGroup - a model defined in Swagger
625941d7cad5886f8bd27239
def test(self) : <NEW_LINE> <INDENT> from supy.utils.root import Dot <NEW_LINE> import random,ROOT as r <NEW_LINE> LV = r.Math.LorentzVector(r.Math.PxPyPzM4D('double')) <NEW_LINE> random.seed(201207241726) <NEW_LINE> for i in range(1,30) : <NEW_LINE> <INDENT> a_,b_ = zip(*[( i**2*random.random(),i**2*random.random()) f...
supy.utils.root.Dot
625941d7627d3e7fe0d690b1
def from_output(self, msg, severity=INFO): <NEW_LINE> <INDENT> self.log(self.machine_name, severity, msg)
Formats log messages
625941d7e5267d203edcdefb