code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def pop(self): <NEW_LINE> <INDENT> if self.stack1: <NEW_LINE> <INDENT> x = self.stack1.pop() <NEW_LINE> if self.stack2 and x == self.stack2[-1]: <NEW_LINE> <INDENT> self.stack2.pop() | :rtype: void | 625941c0097d151d1a222dba |
def run_inference_on_image(image): <NEW_LINE> <INDENT> if not tf.gfile.Exists(image): <NEW_LINE> <INDENT> tf.logging.fatal('File does not exist %s', image) <NEW_LINE> <DEDENT> image_data = tf.gfile.FastGFile(image, 'rb').read() <NEW_LINE> start_time = time.time() <NEW_LINE> create_graph() <NEW_LINE> graph_time = time.time() - start_time <NEW_LINE> with tf.Session() as sess: <NEW_LINE> <INDENT> softmax_tensor = sess.graph.get_tensor_by_name('softmax:0') <NEW_LINE> for i in range(FLAGS.warmup_runs): <NEW_LINE> <INDENT> predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) <NEW_LINE> <DEDENT> runs = [] <NEW_LINE> for i in range(FLAGS.num_runs): <NEW_LINE> <INDENT> start_time = time.time() <NEW_LINE> predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) <NEW_LINE> runs.append(time.time() - start_time) <NEW_LINE> <DEDENT> for i, run in enumerate(runs): <NEW_LINE> <INDENT> print('Run %03d:\t%0.4f seconds' % (i, run)) <NEW_LINE> <DEDENT> print('---') <NEW_LINE> print('Best run: %0.4f' % min(runs)) <NEW_LINE> print('Worst run: %0.4f' % max(runs)) <NEW_LINE> print('Average run: %0.4f' % float(sum(runs) / len(runs))) <NEW_LINE> print('Build graph time: %0.4f' % graph_time) <NEW_LINE> print('Number of warmup runs: %d' % FLAGS.warmup_runs) <NEW_LINE> print('Number of test runs: %d' % FLAGS.num_runs) | Runs inference on an image.
Args:
image: Image file name.
Returns:
Nothing | 625941c07cff6e4e811178e5 |
def __call__(self, dx): <NEW_LINE> <INDENT> return np.copy(self.const_) | Operador (). Retorna o vetor força. | 625941c032920d7e50b2812d |
def _train_epoch(self, train_batches, dropout_keep_prob): <NEW_LINE> <INDENT> total_num, total_loss = 0, 0 <NEW_LINE> log_every_n_batch, n_batch_loss = 1, 0 <NEW_LINE> t1 = time.time() <NEW_LINE> for bitx, batch in enumerate(train_batches, 1): <NEW_LINE> <INDENT> t2 = time.time() <NEW_LINE> passage_len = len(batch['passage_token_ids'][0]) <NEW_LINE> label_batch = len(batch['start_id']) <NEW_LINE> all_passage = len(batch['passage_token_ids']) <NEW_LINE> concat_passage_len = all_passage // label_batch * passage_len <NEW_LINE> feed_dict = {self.p: batch['passage_token_ids'], self.q: batch['question_token_ids'], self.p_length: batch['passage_length'], self.q_length: batch['question_length'], self.start_label: batch['start_id'], self.end_label: batch['end_id'], self.dropout_keep_prob: dropout_keep_prob} <NEW_LINE> _, loss, lr = self.sess.run([self.train_op, self.loss, self.lr], feed_dict) <NEW_LINE> t3 = time.time() <NEW_LINE> data_t = t2 - t1 <NEW_LINE> train_t = t3 - t2 <NEW_LINE> t1 = t3 <NEW_LINE> total_loss += loss * len(batch['raw_data']) <NEW_LINE> total_num += len(batch['raw_data']) <NEW_LINE> n_batch_loss += loss <NEW_LINE> if log_every_n_batch > 0 and bitx % log_every_n_batch == 0: <NEW_LINE> <INDENT> self.logger.info('Average loss from batch {} to {} is {}, lr:{:.6}, data_t:{:.3}, train_t:{:.3}'.format( bitx - log_every_n_batch + 1, bitx, n_batch_loss / log_every_n_batch, lr, data_t, train_t)) <NEW_LINE> n_batch_loss = 0 <NEW_LINE> <DEDENT> <DEDENT> return 1.0 * total_loss / total_num | Trains the model for a single epoch.
Args:
train_batches: iterable batch data for training
dropout_keep_prob: float value indicating dropout keep probability | 625941c097e22403b379cef8 |
def build_scan_command(motor_info, absolute=True, wtime=1.0, dim=None): <NEW_LINE> <INDENT> motor_count = len(motor_info) <NEW_LINE> if dim is None: <NEW_LINE> <INDENT> dim = motor_count <NEW_LINE> <DEDENT> if dim <= 0: <NEW_LINE> <INDENT> raise ValueError('Invalid dimension') <NEW_LINE> <DEDENT> scan_command = find_scan_command_by_dimension(dim, absolute, motor_count) <NEW_LINE> if dim == 1: <NEW_LINE> <INDENT> motor_str = ' '.join('%s %g %g' % tuple(motor[:3]) for motor in motor_info) <NEW_LINE> return '%s %s %d %g' % (scan_command, motor_str, motor_info[0][-1], wtime) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> motor_str = ' '.join('%s %g %g %d' % tuple(motor) for motor in motor_info) <NEW_LINE> return '%s %s %g' % (scan_command, motor_str, wtime) | The first parameter should be a sequence of tuples:
(motor_name, start pos, end pos, data points)
For 1d scans (ascan, d2scan, etc.) the first motor must have data
points specified -- the rest will be ignored. | 625941c0d486a94d0b98e0a4 |
def random_robot_start_position(self): <NEW_LINE> <INDENT> startx = random.randint(0,self.matrix_size) <NEW_LINE> starty = random.randint(0,self.matrix_size) <NEW_LINE> self.robot_start_position = (startx, starty) | This will just randomise the starting position of the robot node | 625941c0d18da76e23532433 |
def gettilenumber(row, col): <NEW_LINE> <INDENT> even = row % 2 <NEW_LINE> tile = row * 4 <NEW_LINE> col += 1 <NEW_LINE> if even == 1: <NEW_LINE> <INDENT> col += 1 <NEW_LINE> tile += col / 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> col += 2 <NEW_LINE> tile += col / 2 <NEW_LINE> <DEDENT> if tile.is_integer(): <NEW_LINE> <INDENT> tile = int(tile) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'error' <NEW_LINE> <DEDENT> if even == 1: <NEW_LINE> <INDENT> return tile - 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return tile - 2 | Gets the tile number for the tile with the specified row and col numbers.
:param row: row (0-indexed)
:param col: col (0-indexed)
:return: tile number, 0-indexed | 625941c03cc13d1c6d3c72da |
def _prepare_dst_dir(self, dst, src=None, perm=None, **kwargs): <NEW_LINE> <INDENT> dst = self._unscheme(dst) <NEW_LINE> if self.isdir(dst): <NEW_LINE> <INDENT> if src: <NEW_LINE> <INDENT> full_dst = os.path.join(dst, os.path.basename(src)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> full_dst = dst <NEW_LINE> <DEDENT> <DEDENT> elif self.isfile(dst): <NEW_LINE> <INDENT> full_dst = dst <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dst_dir = self.dirname(dst) <NEW_LINE> if dst_dir and self.create_file_dir and not self.isdir(dst_dir): <NEW_LINE> <INDENT> self.mkdir(dst_dir, perm=perm, recursive=True) <NEW_LINE> <DEDENT> full_dst = dst <NEW_LINE> <DEDENT> return full_dst | Prepares the directory of a target located at *dst* for copying and returns its full
location as specified below. *src* can be the location of a source file target, which is
(e.g.) used by a file copy or move operation. When *dst* is already a directory, calling
this method has no effect and the *dst* path is returned, optionally joined with the
basename of *src*. When *dst* is a file, the absolute *dst* path is returned. Otherwise,
when *dst* does not exist yet, it is interpreted as a file path and missing directories are
created when :py:attr:`create_file_dir` is *True*, using *perm* to set the directory
permission. The absolute path to *dst* is returned. | 625941c029b78933be1e560f |
def display_menu(menu, value_type, prompt): <NEW_LINE> <INDENT> selection = get_value(prompt, value_type) <NEW_LINE> while selection.lower() not in ('q', 'quit'): <NEW_LINE> <INDENT> if selection in menu.keys(): <NEW_LINE> <INDENT> output = menu[selection]() <NEW_LINE> if output: <NEW_LINE> <INDENT> print(output) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print('Invalid Input') <NEW_LINE> <DEDENT> selection = get_value(prompt, value_type) | Displays a menu and prompts the user for input
:param menu: Dictionary of functions to select from
:param value_type: Type of input requested (int, str, etc...)
:param prompt: Prompt that is displayed to the user | 625941c0167d2b6e31218af5 |
def check_running_pid(pid): <NEW_LINE> <INDENT> return pid in [child for parent, child in get_running_gid_pid()] | check if :const:`pid` is in the process list
:param int pid: process ID
:return: process exists?
:rtype: bool | 625941c04527f215b584c3b9 |
def landing_transition(self): <NEW_LINE> <INDENT> print("landing transition") <NEW_LINE> self.land() <NEW_LINE> self.flight_state = States.LANDING | 1. Command the drone to land ok
2. Transition to the LANDING state | 625941c0baa26c4b54cb1081 |
def run(self, options): <NEW_LINE> <INDENT> service = self.project.get_service(options['SERVICE']) <NEW_LINE> detach = options.get('--detach') <NEW_LINE> if options['--publish'] and options['--service-ports']: <NEW_LINE> <INDENT> raise UserError( 'Service port mapping and manual port mapping ' 'can not be used together' ) <NEW_LINE> <DEDENT> if options['COMMAND'] is not None: <NEW_LINE> <INDENT> command = [options['COMMAND']] + options['ARGS'] <NEW_LINE> <DEDENT> elif options['--entrypoint'] is not None: <NEW_LINE> <INDENT> command = [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> command = service.options.get('command') <NEW_LINE> <DEDENT> options['stdin_open'] = service.options.get('stdin_open', True) <NEW_LINE> container_options = build_one_off_container_options(options, detach, command) <NEW_LINE> run_one_off_container( container_options, self.project, service, options, self.toplevel_options, self.toplevel_environment ) | Run a one-off command on a service.
For example:
$ docker-compose run web python manage.py shell
By default, linked services will be started, unless they are already
running. If you do not want to start linked services, use
`docker-compose run --no-deps SERVICE COMMAND [ARGS...]`.
Usage:
run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] [--]
SERVICE [COMMAND] [ARGS...]
Options:
-d, --detach Detached mode: Run container in the background, print
new container name.
--name NAME Assign a name to the container
--entrypoint CMD Override the entrypoint of the image.
-e KEY=VAL Set an environment variable (can be used multiple times)
-l, --label KEY=VAL Add or override a label (can be used multiple times)
-u, --user="" Run as specified username or uid
--no-deps Don't start linked services.
--rm Remove container after run. Ignored in detached mode.
-p, --publish=[] Publish a container's port(s) to the host
--service-ports Run command with the service's ports enabled and mapped
to the host.
--use-aliases Use the service's network aliases in the network(s) the
container connects to.
-v, --volume=[] Bind mount a volume (default [])
-T Disable pseudo-tty allocation. By default `docker-compose run`
allocates a TTY.
-w, --workdir="" Working directory inside the container | 625941c07b180e01f3dc4762 |
def records_to_string(records): <NEW_LINE> <INDENT> records_str = ' date|time|location|nodeID|lightStatus' <NEW_LINE> for r in records: <NEW_LINE> <INDENT> records_str += '\n {}|{}|{}|{}|{}'.format( r.get('date', ''), r.get('time', ''), r.get('location', ''), r.get('nodeID', ''), r.get('lightStatus', '')) <NEW_LINE> <DEDENT> return records_str | Helper function:
Make a string based on records that are passed in
Parameters
----------
records : list
List of records read from DB
Returns
-------
records_str : str
String representation of records from DB | 625941c0de87d2750b85fcf0 |
def online_training(self, epsilon=.0000001, max_iters=15, debug=False): <NEW_LINE> <INDENT> for i in range(max_iters): <NEW_LINE> <INDENT> for in_vec, out_vec in zip(self.input_vectors, self.output_vectors): <NEW_LINE> <INDENT> self.train_one(in_vec, out_vec) <NEW_LINE> self.update_weights() <NEW_LINE> <DEDENT> squared_error = self.calc_squared_error() <NEW_LINE> if debug: <NEW_LINE> <INDENT> print("After {}, squared_error = {}".format(i, squared_error)) <NEW_LINE> <DEDENT> if squared_error < epsilon: <NEW_LINE> <INDENT> print("Went below epsilon threshold ({})".format(epsilon)) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> return | Online training calculates the output and hidden additives for each
vector and then updates the weights prior to the next input, output
pair being run | 625941c050485f2cf553ccf8 |
def wiggleSort(self, nums: List[int]) -> None: <NEW_LINE> <INDENT> temp = sorted(nums) <NEW_LINE> small = temp[:len(nums)//2] <NEW_LINE> big = temp[len(nums)//2:] <NEW_LINE> if len(small) < len(big): <NEW_LINE> <INDENT> small.append(big.pop(0)) <NEW_LINE> <DEDENT> total_idx = min(len(small),len(big)) <NEW_LINE> s = 0 <NEW_LINE> b = 0 <NEW_LINE> for i in range(len(big) + len(small)): <NEW_LINE> <INDENT> if i % 2 == 0: <NEW_LINE> <INDENT> nums[i] = small[s] <NEW_LINE> s += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> nums[i] = big[b] <NEW_LINE> b += 1 <NEW_LINE> <DEDENT> <DEDENT> print(nums) | Do not return anything, modify nums in-place instead. | 625941c0293b9510aa2c31f8 |
def _check_win(self): <NEW_LINE> <INDENT> n_whites = self.pieces['W'] <NEW_LINE> n_blacks = self.pieces['B'] <NEW_LINE> if n_whites >= 2 and n_blacks >= 2: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> elif n_whites < 2 and n_blacks >= 2: <NEW_LINE> <INDENT> self.winner = 'B' <NEW_LINE> self.phase = 'completed' <NEW_LINE> <DEDENT> elif n_blacks < 2 and n_whites >= 2: <NEW_LINE> <INDENT> self.winner = 'W' <NEW_LINE> self.phase = 'completed' <NEW_LINE> <DEDENT> elif n_whites < 2 and n_blacks < 2: <NEW_LINE> <INDENT> self.winner = 'draw' <NEW_LINE> self.phase = 'completed' | Check the board to see if the game has concluded.
Count the number of pieces remaining for each player: if either player
has run out of pieces, decide the winner and transition to the
'completed' state | 625941c097e22403b379cef9 |
def load_input(self, context): <NEW_LINE> <INDENT> filepath = self._get_path(context.upstream_output) <NEW_LINE> context.log.debug(f"Loading file from: {filepath}") <NEW_LINE> with open(filepath, self.read_mode) as read_obj: <NEW_LINE> <INDENT> return pickle.load(read_obj) | Unpickle the file and Load it to a data object. | 625941c0e5267d203edcdbff |
def pseudodojo_database(): <NEW_LINE> <INDENT> return _OFFICIAL_DATABASE | Returns an instance of `PseudoDojoDatabase`. | 625941c0bde94217f3682d53 |
def initialize_segments(self, alignment, frame_shift=0.01): <NEW_LINE> <INDENT> self.segments = [] <NEW_LINE> assert len(alignment) > 0 <NEW_LINE> prev_label = None <NEW_LINE> prev_length = 0 <NEW_LINE> for i, text_label in enumerate(alignment): <NEW_LINE> <INDENT> if prev_label is not None and int(text_label) != prev_label: <NEW_LINE> <INDENT> if prev_label == 2: <NEW_LINE> <INDENT> self.segments.append( [float(i - prev_length) * frame_shift, float(i) * frame_shift, prev_label]) <NEW_LINE> self.stats.initial_duration += (prev_length * frame_shift) <NEW_LINE> <DEDENT> prev_label = process_label(text_label) <NEW_LINE> prev_length = 0 <NEW_LINE> <DEDENT> elif prev_label is None: <NEW_LINE> <INDENT> prev_label = process_label(text_label) <NEW_LINE> <DEDENT> prev_length += 1 <NEW_LINE> <DEDENT> if prev_length > 0 and prev_label == 2: <NEW_LINE> <INDENT> self.segments.append( [float(len(alignment) - prev_length) * frame_shift, float(len(alignment)) * frame_shift, prev_label]) <NEW_LINE> self.stats.initial_duration += (prev_length * frame_shift) <NEW_LINE> <DEDENT> self.stats.num_segments_initial = len(self.segments) <NEW_LINE> self.stats.num_segments_final = len(self.segments) <NEW_LINE> self.stats.final_duration = self.stats.initial_duration | Initializes segments from input alignment.
The alignment is frame-level speech-activity detection marks,
each of which must be 1 or 2. | 625941c060cbc95b062c64a2 |
def show_catalog_channel(self, channel): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> items = self._vtm_go.get_items() <NEW_LINE> <DEDENT> except ApiUpdateRequired: <NEW_LINE> <INDENT> self._kodi.show_ok_dialog(message=self._kodi.localize(30705)) <NEW_LINE> return <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> self._kodi.log("%s" % ex, LOG_ERROR) <NEW_LINE> self._kodi.show_ok_dialog(message="%s" % ex) <NEW_LINE> return <NEW_LINE> <DEDENT> listing = [] <NEW_LINE> for item in items: <NEW_LINE> <INDENT> if item.channel == channel: <NEW_LINE> <INDENT> listing.append(self._menu.generate_titleitem(item)) <NEW_LINE> <DEDENT> <DEDENT> self._kodi.show_listing(listing, 30003, content='tvshows', sort='label') | Show a category in the catalog
:type channel: str | 625941c08c3a873295158317 |
def run(self): <NEW_LINE> <INDENT> self._read_config_file() <NEW_LINE> Initializer.run(self) | Run method overriding the standard one | 625941c0be383301e01b53ea |
def typeInteger(obj): <NEW_LINE> <INDENT> if obj.get("enum"): <NEW_LINE> <INDENT> return obj.get("enum")[random.randint(0,len(obj.get("enum"))-1)] <NEW_LINE> <DEDENT> multiPle = obj.get("multipleOf") if obj.get("multipleOf") else 1 <NEW_LINE> miniMum = obj.get("minimum") if obj.get("minimum") else -5*multiPle <NEW_LINE> maxiMum = obj.get("maximum") if obj.get("maximum") else 20*multiPle <NEW_LINE> miniMum = miniMum if obj.get("exclusiveMinimum") else miniMum + 1 <NEW_LINE> maxiMum = maxiMum if obj.get("exclusiveMaximum") else maxiMum - 1 <NEW_LINE> if math.ceil(miniMum/multiPle)== 0 and math.ceil(maxiMum/multiPle) == 0: <NEW_LINE> <INDENT> raise "get Integer failed,please check" <NEW_LINE> <DEDENT> return random.randrange(math.ceil(miniMum/multiPle),math.ceil(maxiMum/multiPle)) * multiPle | multipleOf default = 1
minimum default = multiple * -5
maximum default = maximum * 20
如果 -multiple < minimum & maximum < multiple rasie error
:param obj:
:return: | 625941c05510c4643540f34a |
def __and__(self, other): <NEW_LINE> <INDENT> return self.conjoin(other) | Bitwise subversion: conjunction | 625941c026068e7796caec3b |
def test_microvm_initrd_with_serial( test_microvm_with_initrd): <NEW_LINE> <INDENT> vm = test_microvm_with_initrd <NEW_LINE> vm.jailer.daemonize = False <NEW_LINE> vm.spawn() <NEW_LINE> vm.memory_events_queue = None <NEW_LINE> vm.basic_config( add_root_device=False, vcpu_count=1, boot_args='console=ttyS0 reboot=k panic=1 pci=off', use_initrd=True ) <NEW_LINE> vm.start() <NEW_LINE> serial = Serial(vm) <NEW_LINE> serial.open() <NEW_LINE> serial.rx(token='login: ') <NEW_LINE> serial.tx("root") <NEW_LINE> serial.rx(token='Password: ') <NEW_LINE> serial.tx("root") <NEW_LINE> serial.rx(token='# ') <NEW_LINE> serial.tx(f"findmnt /") <NEW_LINE> serial.rx( token=f"/ {INITRD_FILESYSTEM} {INITRD_FILESYSTEM}") | Check microvm started with an inird has / mounted as rootfs. | 625941c05166f23b2e1a50b9 |
def run(self, reset_timestamp=False, output_fname=None, external=False, pad=None, version=False): <NEW_LINE> <INDENT> args = [] <NEW_LINE> if external: <NEW_LINE> <INDENT> args.append('-E') <NEW_LINE> <DEDENT> if pad: <NEW_LINE> <INDENT> args += ['-p', f'{pad:x}'] <NEW_LINE> <DEDENT> if reset_timestamp: <NEW_LINE> <INDENT> args.append('-t') <NEW_LINE> <DEDENT> if output_fname: <NEW_LINE> <INDENT> args += ['-F', output_fname] <NEW_LINE> <DEDENT> if version: <NEW_LINE> <INDENT> args.append('-V') <NEW_LINE> <DEDENT> return self.run_cmd(*args) | Run mkimage
Args:
reset_timestamp: True to update the timestamp in the FIT
output_fname: Output filename to write to
external: True to create an 'external' FIT, where the binaries are
located outside the main data structure
pad: Bytes to use for padding the FIT devicetree output. This allows
other things to be easily added later, if required, such as
signatures
version: True to get the mkimage version | 625941c007f4c71912b113e0 |
def list_endpoints(self, **kwargs): <NEW_LINE> <INDENT> all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version'] <NEW_LINE> all_params.append('callback') <NEW_LINE> params = locals() <NEW_LINE> for key, val in iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method list_endpoints" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> resource_path = '/api/v1/endpoints'.replace('{format}', 'json') <NEW_LINE> method = 'GET' <NEW_LINE> path_params = {} <NEW_LINE> query_params = {} <NEW_LINE> if 'pretty' in params: <NEW_LINE> <INDENT> query_params['pretty'] = params['pretty'] <NEW_LINE> <DEDENT> if 'label_selector' in params: <NEW_LINE> <INDENT> query_params['labelSelector'] = params['label_selector'] <NEW_LINE> <DEDENT> if 'field_selector' in params: <NEW_LINE> <INDENT> query_params['fieldSelector'] = params['field_selector'] <NEW_LINE> <DEDENT> if 'watch' in params: <NEW_LINE> <INDENT> query_params['watch'] = params['watch'] <NEW_LINE> <DEDENT> if 'resource_version' in params: <NEW_LINE> <INDENT> query_params['resourceVersion'] = params['resource_version'] <NEW_LINE> <DEDENT> header_params = {} <NEW_LINE> form_params = {} <NEW_LINE> files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client. select_header_accept(['application/json']) <NEW_LINE> if not header_params['Accept']: <NEW_LINE> <INDENT> del header_params['Accept'] <NEW_LINE> <DEDENT> header_params['Content-Type'] = self.api_client. select_header_content_type(['application/json']) <NEW_LINE> auth_settings = [] <NEW_LINE> response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, response_type='V1EndpointsList', auth_settings=auth_settings, callback=params.get('callback')) <NEW_LINE> return response | list or watch objects of kind Endpoints
This method makes a synchronous HTTP request by default.To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_endpoints(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: a selector to restrict the list of returned objects by their labels; defaults to everything
:param str field_selector: a selector to restrict the list of returned objects by their fields; defaults to everything
:param bool watch: watch for changes to the described resources and return them as a stream of add, update, and remove notifications; specify resourceVersion
:param str resource_version: when specified with a watch call, shows changes that occur after that particular version of a resource; defaults to changes from the beginning of history
:return: V1EndpointsList
If the method is called asynchronously,
returns the request thread. | 625941c030dc7b76659018c8 |
def __setitem__(self, item: str, val: Union[str, JID]): <NEW_LINE> <INDENT> if item in ['to', 'from']: <NEW_LINE> <INDENT> if not isinstance(val, JID): <NEW_LINE> <INDENT> val = JID.from_string(val) <NEW_LINE> <DEDENT> <DEDENT> self.setAttr(item, val) | Set the item 'item' to the value 'val' | 625941c026238365f5f0edcb |
def reorder_items(self): <NEW_LINE> <INDENT> items = MenuItem.objects.filter( lang=self.lang, menu=self.menu ).order_by('position') <NEW_LINE> for pos, item in enumerate(items): <NEW_LINE> <INDENT> item.position = pos + 1 <NEW_LINE> item.save() | repositions items after deletion or exception | 625941c063d6d428bbe4444f |
def size(self): <NEW_LINE> <INDENT> return self.arr_size | Return size of the array. | 625941c031939e2706e4cdcd |
def struct(*name): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> def wrapper(*args, **kw): <NEW_LINE> <INDENT> for i in range(len(name)): <NEW_LINE> <INDENT> setattr(args[0], name[i], args[i+1]) <NEW_LINE> <DEDENT> return func(*args, **kw) <NEW_LINE> <DEDENT> return wrapper <NEW_LINE> <DEDENT> return decorator | 装饰器函数
用途:用于在类定义中,自动设置self.value = value | 625941c045492302aab5e221 |
def verbose_type(verbosity): <NEW_LINE> <INDENT> levels = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG] <NEW_LINE> verbosity = int(verbosity) <NEW_LINE> if verbosity > len(levels) - 1: <NEW_LINE> <INDENT> verbosity = levels[-1] <NEW_LINE> <DEDENT> elif verbosity < 0 or verbosity == None: <NEW_LINE> <INDENT> verbosity = levels[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> verbosity = levels[verbosity] <NEW_LINE> <DEDENT> return verbosity | Clamp the verbosity to a valid value | 625941c091af0d3eaac9b976 |
def test_deserialize_a_product(self): <NEW_LINE> <INDENT> data = { "name": "iPhone", "price": 649, "id": 0, "image_id": "0005", "description": "Latest phone model." } <NEW_LINE> product = Product(id=data["id"]) <NEW_LINE> product.deserialize(data) <NEW_LINE> self.assertNotEqual(product, None) <NEW_LINE> self.assertEqual(product.name, "iPhone") <NEW_LINE> self.assertEqual(product.price, 649) <NEW_LINE> self.assertEqual(product.id, 0) <NEW_LINE> self.assertEqual(product.image_id, "0005") <NEW_LINE> self.assertEqual(product.description, "Latest phone model.") | Test deserialization of a product | 625941c07c178a314d6ef3bb |
def toggled_single_frequency(self): <NEW_LINE> <INDENT> self.set_state(dict(single_frequency=bool(self.__single_frequency_int_var.get()))) <NEW_LINE> self.update_n_freqs_sc() | Enable a single frequency request.
Sets the state of the component to the current choice of single or multiple frequencies and validates the input. | 625941c071ff763f4b5495e7 |
def execute_deferred(fn): <NEW_LINE> <INDENT> utils.executeDeferred(fn) | Executes given function in deferred mode (once DCC UI has been loaded)
:param callable fn: Function to execute in deferred mode
:return: | 625941c071ff763f4b5495e8 |
def getModifiedBy(entity, *args): <NEW_LINE> <INDENT> profile_key = ( task_model.GCITask.modified_by.get_value_for_datastore(entity)) <NEW_LINE> if not profile_key: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> profile = ndb.Key.from_old_key(profile_key).get() <NEW_LINE> return profile.public_name | Helper function to get value for modified_by column. | 625941c0a934411ee37515f3 |
def _process_while_stmt(self, node: parso.python.tree.WhileStmt) -> None: <NEW_LINE> <INDENT> children = iter(node.children) <NEW_LINE> self._process(next(children)) <NEW_LINE> self._process(next(children)) <NEW_LINE> self._process(next(children)) <NEW_LINE> self._process_suite_node(next(children)) <NEW_LINE> try: <NEW_LINE> <INDENT> key = next(children) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self._process(key) <NEW_LINE> self._process(next(children)) <NEW_LINE> self._process_suite_node(next(children)) | Process while statement (:token:`while_stmt`).
Args:
node (parso.python.tree.WhileStmt): while node
This method processes the indented suite under the *while* and optional
*else* statements. | 625941c032920d7e50b2812e |
def getWorkload(g, workloadType, AssignmentTag, RoutingActionList, workTimeThreshold): <NEW_LINE> <INDENT> listAction = list(g['EntityAction']) <NEW_LINE> listActionTime = list(g['EventDateTime']) <NEW_LINE> OriginatingSystem = list(g['OriginatingSystem'])[0] <NEW_LINE> W = ['NoWorkload'] * len(listAction) <NEW_LINE> shift = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> selectedAgentAssigned = min(idx for idx, val in enumerate(listAction) if val == AssignmentTag) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> priorRouting = max(idx for idx, val in enumerate(listAction[ : selectedAgentAssigned]) if val in RoutingActionList) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> priorRouting = selectedAgentAssigned <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> posteriorRouting = selectedAgentAssigned+1 + min(idx for idx, val in enumerate(listAction[selectedAgentAssigned + 1: ]) if val in RoutingActionList + [AssignmentTag]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> W[priorRouting + shift] = 'Workload_' + str(listAction[priorRouting]) <NEW_LINE> break <NEW_LINE> <DEDENT> workTime = (listActionTime[posteriorRouting] - listActionTime[selectedAgentAssigned]).total_seconds() / 60.0 <NEW_LINE> if workTime > workTimeThreshold: <NEW_LINE> <INDENT> W[priorRouting + shift] = 'Workload_' + str(listAction[priorRouting]) <NEW_LINE> <DEDENT> listAction = listAction[selectedAgentAssigned+1 : ] <NEW_LINE> shift += selectedAgentAssigned+1 <NEW_LINE> <DEDENT> if workloadType == 'MainWorkloadType' and any('Workload_' in w for w in W) and OriginatingSystem not in ['Rave', 'RAVE']: <NEW_LINE> <INDENT> creationIx = min(idx for idx, val in enumerate(W) if val.find('Workload_') != -1) <NEW_LINE> W[creationIx] = 'Workload_IncidentCreation' <NEW_LINE> <DEDENT> g[workloadType] = W <NEW_LINE> return g | Extract and compute workload from the event data. In other words, tag whether or not an event generates workload and keep track of what typ of workload is being generated (if any).
The idea behind the workload tagging is to make sure that some form of work was performed by an engineer before she/he reroutes the case or task that was routed to her/his queue.
Hence, the methodology not only checks when a case or task is being (re)routed to a queue, but also makes sure an agent was assigned and that a significant amount of time elapsed
before a new rerouting event took place (e.g. 15 minutes minimum). If for instance an agent reroutes a case to another queue a few seconds after the case was assigned to her/him,
no workload will be counted at this step of the incident.
:parameter g: the dataframe of the incident to compute workload on (pandas group)
:parameter workloadType: the name of the workload to be computed (e.g. MainWorkloadType or AdditionalWorkloadType) (string) - will become a new column name in the dataframe the function is run against
:parameter AssignmentTag: the entity action that is considered as case/task assignment (e.g. AgentAssigned or TaskAssignedToAgent) (string)
:parameter RoutingActionList: the list of entity actions that can be considered as routing events (e.g. ['CaseRouted', 'CaseRerouted', 'CaseManuallyRerouted', 'CaseReopened']) (list)
:parameter workTimeThreshold: the time threshold (in minute) after which it is assumed that the agent worked on a case/task long enough that some workload is generated
:return g: the modified group (with an additional workloadType column) (pandas group) | 625941c021bff66bcd6848b5 |
def __init__(self, parent): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> tk.Canvas.__init__(self, parent, relief=tk.GROOVE, background=self.parent.cols['menu']['canvas'], borderwidth=5, width=300, height=200) <NEW_LINE> self._currPolytope = Polytope([]) <NEW_LINE> self._sphere = Sphere(SPHERENUM, RADIUS) <NEW_LINE> self._axes = Axes() <NEW_LINE> self._noSnub = False | Construct Canvas class.
parent: the parent of canvas (Main) | 625941c076d4e153a657ea90 |
def thermostat(self, id): <NEW_LINE> <INDENT> logger.debug('fetch thermostat {}'.format(id)) <NEW_LINE> try: <NEW_LINE> <INDENT> return self._data[int(id)] <NEW_LINE> <DEDENT> except (ValueError, KeyError): <NEW_LINE> <INDENT> raise UnknownThermostatError(id) | Return information about a specific thermostat.
If the id matches a managed thermostat the related data will be
returned
>>> Service().thermostat(100)
{'name': 'Upstairs Thermostat', 'operating-mode': 'heat', 'cool-setpoint': 75, 'heat-setpoint': 65, 'fan-mode': 'auto', 'current-temp': 71, 'id': 100}
If the provided id attribute is unknown then an
UnknownThermostatError will be raised instead.
>>> Service().thermostat(102)
Traceback (most recent call last):
...
UnknownThermostatError
>>> Service().thermostat('sdf')
Traceback (most recent call last):
...
UnknownThermostatError | 625941c03617ad0b5ed67e59 |
def _get_params_for_weight_decay_optimization(modules): <NEW_LINE> <INDENT> weight_decay_params = {'params': []} <NEW_LINE> no_weight_decay_params = {'params': [], 'weight_decay': 0.0} <NEW_LINE> for module in modules: <NEW_LINE> <INDENT> for module_ in module.modules(): <NEW_LINE> <INDENT> if isinstance(module_, LayerNorm): <NEW_LINE> <INDENT> no_weight_decay_params['params'].extend( [p for p in list(module_._parameters.values()) if p is not None and p.requires_grad]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> weight_decay_params['params'].extend( [p for n, p in list(module_._parameters.items()) if p is not None and p.requires_grad and n != 'bias']) <NEW_LINE> no_weight_decay_params['params'].extend( [p for n, p in list(module_._parameters.items()) if p is not None and p.requires_grad and n == 'bias']) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return weight_decay_params, no_weight_decay_params | Divide params into with-weight-decay and without-weight-decay groups.
Layernorms and baises will have no weight decay but the rest will. | 625941c09f2886367277a7ef |
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SwitchboardPassControlAllOfPayload): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict() | Returns true if both objects are not equal | 625941c0796e427e537b0524 |
def InitVelocityConstraints(self, *args): <NEW_LINE> <INDENT> return _Box2D.b2LineJoint_InitVelocityConstraints(self, *args) | InitVelocityConstraints(b2LineJoint self, b2TimeStep step) | 625941c04428ac0f6e5ba752 |
def GetPointer(self): <NEW_LINE> <INDENT> return _itkFFTShiftImageFilterPython.itkFFTShiftImageFilterIVF22IVF22_GetPointer(self) | GetPointer(self) -> itkFFTShiftImageFilterIVF22IVF22 | 625941c05e10d32532c5ee88 |
def prg(x): <NEW_LINE> <INDENT> return q(DWILIB / x) | Quoted program path. | 625941c03d592f4c4ed1cfd4 |
def setUp(self): <NEW_LINE> <INDENT> super(GnuBackendtests, self).setUp() <NEW_LINE> create_distro(self.session) <NEW_LINE> self.create_project() | Set up the environnment, ran before every tests. | 625941c0bf627c535bc1312f |
def get_test_file(fileType='seq', settings=False, **kwargs): <NEW_LINE> <INDENT> zmxfp = os.path.join(pyzddedirectory, 'ZMXFILES') <NEW_LINE> lensFile = ["Cooke_40_degree_field.zmx", "Double_Gauss_5_degree_field.ZMX", "LENS.ZMX",] <NEW_LINE> settingsFile = ["Cooke_40_degree_field_unittest.CFG", ] <NEW_LINE> popFiles = ["Fiber_Coupling.ZMX", ] <NEW_LINE> popSettingsFile = ["Fiber_Coupling_POPunittest.CFG", "Fiber_Coupling_POPunittest_Irradiance.CFG", "Fiber_Coupling_POPunittest_Phase.CFG", "Fiber_Coupling_POPunittest_NoFiberCompute.CFG", ] <NEW_LINE> lenFileIndex = 0 <NEW_LINE> setFileIndex = 0 <NEW_LINE> if len(kwargs): <NEW_LINE> <INDENT> if 'loadfile' in kwargs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lenFileIndex = lensFile.index(kwargs['loadfile']) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print("Couldn't find the specified lens file. Loading default file") <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> files = [] <NEW_LINE> if fileType == 'seq': <NEW_LINE> <INDENT> files.append(lensFile[lenFileIndex]) <NEW_LINE> if settings: <NEW_LINE> <INDENT> files.append(settingsFile[setFileIndex]) <NEW_LINE> <DEDENT> <DEDENT> elif fileType == 'pop': <NEW_LINE> <INDENT> if settings: <NEW_LINE> <INDENT> if len(kwargs): <NEW_LINE> <INDENT> if kwargs['sfile'] == 'nofibint': <NEW_LINE> <INDENT> lenFileIndex, setFileIndex = 0, 3 <NEW_LINE> <DEDENT> elif kwargs['sfile'] == 'nzstbirr': <NEW_LINE> <INDENT> lenFileIndex, setFileIndex = 0, 1 <NEW_LINE> <DEDENT> elif kwargs['sfile'] == 'nzstbpha': <NEW_LINE> <INDENT> lenFileIndex, setFileIndex = 0, 2 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lenFileIndex, setFileIndex = 0, 0 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> lenFileIndex, setFileIndex = 0, 0 <NEW_LINE> <DEDENT> files.append(popFiles[lenFileIndex]) <NEW_LINE> files.append(popSettingsFile[setFileIndex]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> files.append(popFiles[lenFileIndex]) <NEW_LINE> <DEDENT> <DEDENT> files = [os.path.join(zmxfp, f) for f in files] <NEW_LINE> if len(files) > 1: <NEW_LINE> <INDENT> return tuple(files) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return files[0] | helper function to get test lens file(s) for each unit test function
Parameters
----------
fileType : string, optional
3-character code for loading different (pre-specified) lens files:
"seq" = file for sequential ray tracing function tests;
"pop" = file for physical optics propagation tests;
settings : bool, optional
if ``True``, a tuple is returned with the second element being the name
of the settings file associated with the lens file.
kwargs : keyword arguments
sfile : string (for POP settings)
"default" = use default settings file associated with the lens file;
"nofibint" = settings with fiber integral calculation disabled;
"nzstbirr" = non-zero surface to beam setting, irradiance data;
"nzstbpha" = non-zero surface to beam setting, phase data;
loadfile : string (for loading a particular lens file)
"LENS.ZMX" = the default lens, LENS.ZMX is loaded in to the LDE
This is really a hack. Use the exact name inlucing the exact upper/
lower case letters in the name, else it will not be found.
Returns
-------
file : string/ tuple
filenames are complete complete paths | 625941c0462c4b4f79d1d631 |
def testDetWrongDim(self): <NEW_LINE> <INDENT> print(self.typeStr, "... ", end=' ', file=sys.stderr) <NEW_LINE> det = Matrix.__dict__[self.typeStr + "Det"] <NEW_LINE> matrix = [8, 7] <NEW_LINE> self.assertRaises(TypeError, det, matrix) | Test det function with wrong dimensions | 625941c05fc7496912cc38de |
def get_event_op_rs_with_http_info(self, event_key, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ 'event_key', 'if_modified_since' ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_event_op_rs" % key ) <NEW_LINE> <DEDENT> local_var_params[key] = val <NEW_LINE> <DEDENT> del local_var_params['kwargs'] <NEW_LINE> if self.api_client.client_side_validation and ('event_key' not in local_var_params or local_var_params['event_key'] is None): <NEW_LINE> <INDENT> raise ApiValueError("Missing the required parameter `event_key` when calling `get_event_op_rs`") <NEW_LINE> <DEDENT> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> if 'event_key' in local_var_params: <NEW_LINE> <INDENT> path_params['event_key'] = local_var_params['event_key'] <NEW_LINE> <DEDENT> query_params = [] <NEW_LINE> header_params = {} <NEW_LINE> if 'if_modified_since' in local_var_params: <NEW_LINE> <INDENT> header_params['If-Modified-Since'] = local_var_params['if_modified_since'] <NEW_LINE> <DEDENT> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) <NEW_LINE> auth_settings = ['apiKey'] <NEW_LINE> return self.api_client.call_api( '/event/{event_key}/oprs', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='EventOPRs', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | get_event_op_rs # noqa: E501
Gets a set of Event OPRs (including OPR, DPR, and CCWM) for the given Event. # 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_event_op_rs_with_http_info(event_key, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str event_key: TBA Event Key, eg `2016nytr` (required)
:param str if_modified_since: Value of the `Last-Modified` header in the most recently cached response by the client.
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(EventOPRs, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread. | 625941c0046cf37aa974ccaa |
def on_aboutMenuitem_activate(self, menuitem): <NEW_LINE> <INDENT> self.aboutDialog.set_version(MBRAT_VER) <NEW_LINE> response = self.aboutDialog.run() <NEW_LINE> self.aboutDialog.hide() | Handler for 'About' menu item Dialog. | 625941c0460517430c3940eb |
def getProductStock(self): <NEW_LINE> <INDENT> return self.product_stock.text() | Metodo que retorna el texto capturado del componente caja de texto 'product_stock'
:return: | 625941c08e05c05ec3eea2d3 |
def summarise(html, maxchars=280): <NEW_LINE> <INDENT> p = Summarizer(maxchars) <NEW_LINE> p.feed(html) <NEW_LINE> p.close() <NEW_LINE> truncated = p.done <NEW_LINE> p.finish() <NEW_LINE> return p.out.getvalue(), truncated | Take the first maxchars characters of the given HTML.
Return a tuple (short_html, was_truncated). | 625941c05fc7496912cc38df |
def is_directory_path(self, file_path): <NEW_LINE> <INDENT> is_directory_path = os.path.isdir(file_path) <NEW_LINE> return is_directory_path | Tests if the given file path refers a directory path in
the current environment.
@type file_path: String
@param file_path: The file path to be tested
for directory referral.
@rtype: bool
@return: The result of the test for
directory referral. | 625941c0ec188e330fd5a704 |
def add_lines_with_ghosts(self, version_id, parents, lines, parent_texts=None, nostore_sha=None, random_id=False, check_content=True, left_matching_blocks=None): <NEW_LINE> <INDENT> self._check_write_ok() <NEW_LINE> return self._add_lines_with_ghosts(version_id, parents, lines, parent_texts, nostore_sha, random_id, check_content, left_matching_blocks) | Add lines to the versioned file, allowing ghosts to be present.
This takes the same parameters as add_lines and returns the same. | 625941c07d847024c06be21a |
def test_parsevalue_no_int(self): <NEW_LINE> <INDENT> testvalue = "foo bar" <NEW_LINE> self.assertRaises(ValueError, mcfg.Mcfg.parsevalue, testvalue) <NEW_LINE> try: <NEW_LINE> <INDENT> mcfg.Mcfg.parsevalue(testvalue) <NEW_LINE> <DEDENT> except ValueError as exc: <NEW_LINE> <INDENT> self.assertEqual( "Increment value must numeric: >>>foo<<< bar", str(exc)) | test a value that has no valid integer before the space | 625941c010dbd63aa1bd2b05 |
def p_expression_plus(p): <NEW_LINE> <INDENT> p[0] = p[1] + p[3] | expression : expression PLUS term | 625941c091f36d47f21ac451 |
def requires_accuracy_level(accuracy_level): <NEW_LINE> <INDENT> def accuracy_decorator(func): <NEW_LINE> <INDENT> func.func_dict['accuracy required'] = accuracy_level <NEW_LINE> return func <NEW_LINE> <DEDENT> return accuracy_decorator | A decoeator which associates a required activity level with a given task (a_j in Hanakawa 2002)
:param accuracy_level:
:return: | 625941c04a966d76dd550f6e |
def mod11ini(value): <NEW_LINE> <INDENT> length = len(value) <NEW_LINE> s = 0 <NEW_LINE> for i in xrange(0, length): <NEW_LINE> <INDENT> s += int(value[length - i - 1]) * (i + 2) <NEW_LINE> <DEDENT> res = s % 11 <NEW_LINE> if res > 1: <NEW_LINE> <INDENT> res = 11 - res <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res = 0 <NEW_LINE> <DEDENT> return str(res) | Compute mod11ini | 625941c094891a1f4081ba09 |
def rm(fpath, p=""): <NEW_LINE> <INDENT> fpath = path_expand(fpath) <NEW_LINE> if len(fpath) < 2: return <NEW_LINE> if "r" not in p: <NEW_LINE> <INDENT> os.remove(fpath) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> shutil.rmtree(fpath) | remove(fpath: string, dst: string, p="")
remove a file or directory
p = [r] remove directory | 625941c0d99f1b3c44c674f5 |
def hammingDistance(self, x, y): <NEW_LINE> <INDENT> sx = bin(x)[2:] <NEW_LINE> sy = bin(y)[2:] <NEW_LINE> lx = len(sx) <NEW_LINE> ly = len(sy) <NEW_LINE> if lx > ly: <NEW_LINE> <INDENT> sy = '0' * (lx - ly) + sy <NEW_LINE> <DEDENT> elif ly > lx: <NEW_LINE> <INDENT> sx = '0' * (ly - lx) + sx <NEW_LINE> <DEDENT> cnt = 0 <NEW_LINE> for i in range(len(sx)): <NEW_LINE> <INDENT> if sx[i] != sy[i]: <NEW_LINE> <INDENT> cnt += 1 <NEW_LINE> <DEDENT> <DEDENT> return cnt | :type x: int
:type y: int
:rtype: int | 625941c0046cf37aa974ccab |
def _handle_l2pop(self, context, new_remote_macs): <NEW_LINE> <INDENT> for mac in new_remote_macs: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> agent_l2_pop_enabled = self._get_agent_by_mac(context, mac) <NEW_LINE> <DEDENT> except l2gw_exc.L2AgentNotFoundByHost as e: <NEW_LINE> <INDENT> LOG.debug(e.message) <NEW_LINE> continue <NEW_LINE> <DEDENT> physical_switches = self._get_physical_switch_ips(context, mac) <NEW_LINE> for physical_switch in physical_switches: <NEW_LINE> <INDENT> other_fdb_entries = self._get_fdb_entries( context, physical_switch, mac.get('logical_switch_id')) <NEW_LINE> if agent_l2_pop_enabled: <NEW_LINE> <INDENT> self.tunnel_call.trigger_l2pop_sync(context, other_fdb_entries) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.tunnel_call.trigger_tunnel_sync(context, physical_switch) | handle vxlan tunnel creation based on whether l2pop is enabled or not.
if l2pop is enabled in L2 agent on a host to which port belongs, then
call add_fdb_entries. otherwise, call tunnel_sync. | 625941c08a43f66fc4b53fc8 |
def build_process_tomography_circuits(Q_program, name, qubits, qreg, creg, prep_basis='SIC', meas_basis='Pauli'): <NEW_LINE> <INDENT> logger.warning( 'WARNING: `build_process_tomography_circuits` is depreciated. ' 'Use `tomography_set` and `create_tomography_circuits` instead') <NEW_LINE> tomoset = tomography_set(qubits, meas_basis, prep_basis) <NEW_LINE> return create_tomography_circuits( Q_program, name, qreg, creg, tomoset) | Depreciated function: Use `create_tomography_circuits` function instead.
| 625941c0a219f33f346288ce |
def set_config(self, existing_l3_interfaces_facts): <NEW_LINE> <INDENT> config = self._module.params.get("config") <NEW_LINE> want = [] <NEW_LINE> if config: <NEW_LINE> <INDENT> for w in config: <NEW_LINE> <INDENT> w.update({"name": normalize_interface(w["name"])}) <NEW_LINE> want.append(remove_empties(w)) <NEW_LINE> <DEDENT> <DEDENT> have = deepcopy(existing_l3_interfaces_facts) <NEW_LINE> self.init_check_existing(have) <NEW_LINE> resp = self.set_state(want, have) <NEW_LINE> return to_list(resp) | Collect the configuration from the args passed to the module,
collect the current configuration (as a dict from facts)
:rtype: A list
:returns: the commands necessary to migrate the current configuration
to the desired configuration | 625941c0eab8aa0e5d26dab8 |
def draw_circle(self, x0, y0, r, color=1): <NEW_LINE> <INDENT> if self.is_off_grid(x0 - r, y0 - r, x0 + r, y0 + r): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> f = 1 - r <NEW_LINE> dx = 1 <NEW_LINE> dy = -r - r <NEW_LINE> x = 0 <NEW_LINE> y = r <NEW_LINE> self.back_buffer[y0 + r, x0] = color <NEW_LINE> self.back_buffer[y0 - r, x0] = color <NEW_LINE> self.back_buffer[y0, x0 + r] = color <NEW_LINE> self.back_buffer[y0, x0 - r] = color <NEW_LINE> while x < y: <NEW_LINE> <INDENT> if f >= 0: <NEW_LINE> <INDENT> y -= 1 <NEW_LINE> dy += 2 <NEW_LINE> f += dy <NEW_LINE> <DEDENT> x += 1 <NEW_LINE> dx += 2 <NEW_LINE> f += dx <NEW_LINE> self.back_buffer[y0 + y, x0 + x] = color <NEW_LINE> self.back_buffer[y0 + y, x0 - x] = color <NEW_LINE> self.back_buffer[y0 - y, x0 + x] = color <NEW_LINE> self.back_buffer[y0 - y, x0 - x] = color <NEW_LINE> self.back_buffer[y0 + x, x0 + y] = color <NEW_LINE> self.back_buffer[y0 + x, x0 - y] = color <NEW_LINE> self.back_buffer[y0 - x, x0 + y] = color <NEW_LINE> self.back_buffer[y0 - x, x0 - y] = color | Draws a circle on the back buffer
Args:
x0, y0 (int): Pixel coordinates of center point
r (int): Radius
color (Optional int): 0 = pixel off, 1 = pixel on (default)
Note:
The center point is the center of the x0,y0 pixel.
Since pixels are not divisible, the radius is integer rounded
up to complete on a full pixel. Therefore diameter = 2 x r + 1. | 625941c0dc8b845886cb5495 |
def isEqual(self, date2): <NEW_LINE> <INDENT> return self.year == date2.year and self.month == date2.month and self.day == date2.day | Decides if self and date2 represent the same calendar date..
>>> date1 = Date(11, 3, 2015)
>>> newDate = date1.copy()
>>> date1.isEqual(newDate)
True | 625941c04d74a7450ccd4124 |
def include(urlconf_module): <NEW_LINE> <INDENT> if isinstance(urlconf_module, str): <NEW_LINE> <INDENT> urlconf_module = import_module(urlconf_module) <NEW_LINE> <DEDENT> app_name = getattr(urlconf_module, 'app_name') <NEW_LINE> return urlconf_module, app_name | 他のurls.pyの設定を読み込む. | 625941c01f037a2d8b94615f |
def check_scope_manager(self): <NEW_LINE> <INDENT> return True | If true, the test suite will validate the `ScopeManager` propagation
to ensure correct parenting. If false, it will only use the API without
asserting. The latter mode is only useful for no-op tracer. | 625941c04f6381625f11499e |
def build_value_function_mlp(obs_ph, layer_sizes, vscope='vf'): <NEW_LINE> <INDENT> with tf.variable_scope(vscope): <NEW_LINE> <INDENT> val_func = tf.layers.dense(obs_ph, units=layer_sizes[0], activation=tf.nn.relu) <NEW_LINE> for size in layer_sizes[1:]: <NEW_LINE> <INDENT> val_func = tf.layers.dense(val_func, units=size, activation=tf.nn.relu) <NEW_LINE> <DEDENT> val_func = tf.layers.dense(val_func, units=1) <NEW_LINE> <DEDENT> return val_func | Builds the value function mlp | 625941c0bd1bec0571d90590 |
def testExportAuditorAccessWalletRequest(self): <NEW_LINE> <INDENT> pass | Test ExportAuditorAccessWalletRequest | 625941c00383005118ecf545 |
def list_plot3d_array_of_arrays(v, interpolation_type, **kwds): <NEW_LINE> <INDENT> m = matrix(RDF, len(v), len(v[0]), v) <NEW_LINE> G = list_plot3d(m, interpolation_type, **kwds) <NEW_LINE> G._set_extra_kwds(kwds) <NEW_LINE> return G | A 3-dimensional plot of a surface defined by a list of lists ``v``
defining points in 3-dimensional space.
This is done by making the list of lists into a matrix and passing
back to :func:`list_plot3d`. See :func:`list_plot3d` for full
details.
INPUT:
- ``v`` - a list of lists, all the same length
- ``interpolation_type`` - (default: 'linear')
OPTIONAL KEYWORDS:
- ``**kwds`` - all other arguments are passed to the surface function
OUTPUT: a 3d plot
EXAMPLES:
The resulting matrix does not have to be square::
sage: show(list_plot3d([[1, 1, 1, 1], [1, 2, 1, 2], [1, 1, 3, 1]])) # indirect doctest
The normal route is for the list of lists to be turned into a matrix
and use :func:`list_plot3d_matrix`::
sage: show(list_plot3d([[1, 1, 1, 1], [1, 2, 1, 2], [1, 1, 3, 1], [1, 2, 1, 4]]))
With certain extra keywords (see :func:`list_plot3d_matrix`), this function
will end up using :func:`list_plot3d_tuples`::
sage: show(list_plot3d([[1, 1, 1, 1], [1, 2, 1, 2], [1, 1, 3, 1], [1, 2, 1, 4]], interpolation_type='spline')) | 625941c032920d7e50b2812f |
def test_serverError(self): <NEW_LINE> <INDENT> return self._rcodeTest(dns.ESERVER, error.DNSServerError) | Like L{test_formatError} but for C{ESERVER}/L{DNSServerError}. | 625941c0236d856c2ad44738 |
def svg_str_to_pixbuf(svg_string): <NEW_LINE> <INDENT> pl = gtk.gdk.PixbufLoader('svg') <NEW_LINE> pl.write(svg_string) <NEW_LINE> pl.close() <NEW_LINE> pixbuf = pl.get_pixbuf() <NEW_LINE> return pixbuf | Load pixbuf from SVG string | 625941c0b7558d58953c4e7a |
def register(self, coro: Coroutine, name: Optional[str] = None) -> None: <NEW_LINE> <INDENT> _name: str = coro.__name__ if name is None else name <NEW_LINE> event = self.events.get(_name, []) <NEW_LINE> event.append(coro) <NEW_LINE> self.events[_name] = event <NEW_LINE> log.debug(f"REGISTER: {self.events[_name]}") | Registers a given coroutine as an event to be listened to.
If the name of the event is not given, it will then be
determined by the coroutine's name.
i.e. : async def on_guild_create -> "ON_GUILD_CREATE" dispatch.
:param coro: The coroutine to register as an event.
:type coro: Coroutine
:param name?: The name to associate the coroutine with. Defaults to None.
:type name: Optional[str] | 625941c07d43ff24873a2c00 |
def say_hello_to_boy(friend_name): <NEW_LINE> <INDENT> card_title = "Greeting Message" <NEW_LINE> greeting_string = "Hi "+friend_name+"! Welcome to Mayank's adobe. This is unusual to have a guy in mikki's room. Anyway, I welcome you here." <NEW_LINE> should_end_session = True <NEW_LINE> session_attributes = { "speech_output": greeting_string, "friend_name" : friend_name } <NEW_LINE> return build_response(session_attributes, build_speechlet_response(card_title, greeting_string, "Ask me to say hello...", should_end_session)) | Return a suitable greeting... | 625941c0956e5f7376d70dcf |
def _competing_needs(self, actionA, actionB): <NEW_LINE> <INDENT> for effect in actionA.preconditions: <NEW_LINE> <INDENT> for affect in actionB.preconditions: <NEW_LINE> <INDENT> if self.parent_layer.is_mutex(effect, affect): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for effect in actionB.preconditions: <NEW_LINE> <INDENT> for affect in actionA.preconditions: <NEW_LINE> <INDENT> if self.parent_layer.is_mutex(effect, affect): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False | Return True if any preconditions of the two actions are pairwise mutex in the parent layer
See Also
--------
layers.ActionNode
layers.BaseLayer.parent_layer | 625941c0d4950a0f3b08c2b2 |
def _check_signature(signature, template): <NEW_LINE> <INDENT> pick = _LockPick() <NEW_LINE> template.format_map(pick) <NEW_LINE> path_vars = {name for name, _ in _get_parameters(Path, signature)} <NEW_LINE> path_vars_diff = pick.keys - path_vars <NEW_LINE> if path_vars_diff: <NEW_LINE> <INDENT> raise FurnishError( "missing Path parameters: {}".format(path_vars_diff)) <NEW_LINE> <DEDENT> for type_ in [Body, Json]: <NEW_LINE> <INDENT> if len(list(_get_parameters(type_, signature))) > 1: <NEW_LINE> <INDENT> raise FurnishError( "multiple parameters annotated as {}".format(type_.__name__)) | Check that the given `Signature` is valid. | 625941c0a17c0f6771cbdfb4 |
def get_time(f, args=[]): <NEW_LINE> <INDENT> if type(args) != list: <NEW_LINE> <INDENT> args = [args] <NEW_LINE> <DEDENT> key = f.__name__ <NEW_LINE> if args != []: <NEW_LINE> <INDENT> key += "-" + "-".join([str(arg) for arg in args]) <NEW_LINE> <DEDENT> return timing[key] | After using timeit we can get the duration of the function f
when it was applied in parameters args. Normally it is expected
that args is a list of parameters, but it can be also a single parameter.
:type f: function
:type args: list
:rtype: float | 625941c0d18da76e23532435 |
def redirect_to_express(self): <NEW_LINE> <INDENT> wpp = PayPalWPP(self.request) <NEW_LINE> nvp_obj = wpp.setExpressCheckout(self.item) <NEW_LINE> if not nvp_obj.flag: <NEW_LINE> <INDENT> pp_params = dict(token=nvp_obj.token, AMT=self.item['amt'], RETURNURL=self.item['returnurl'], CANCELURL=self.item['cancelurl']) <NEW_LINE> if TEST: <NEW_LINE> <INDENT> express_endpoint = SANDBOX_EXPRESS_ENDPOINT <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> express_endpoint = EXPRESS_ENDPOINT <NEW_LINE> <DEDENT> pp_url = express_endpoint % urlencode(pp_params) <NEW_LINE> return HttpResponseRedirect(pp_url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.context = {'errors': 'There was a problem contacting PayPal. Please try again later.'} <NEW_LINE> return self.render_payment_form() | First step of ExpressCheckout. Redirect the request to PayPal using the
data returned from setExpressCheckout. | 625941c0293b9510aa2c31f9 |
def test(self, embedding_file): <NEW_LINE> <INDENT> word_freq = Counter() <NEW_LINE> total_count = 0 <NEW_LINE> with open(self.label_file, 'r') as f_l: <NEW_LINE> <INDENT> for line in f_l: <NEW_LINE> <INDENT> word = line[:-1] <NEW_LINE> word_freq[word] += 1 <NEW_LINE> total_count += 1 <NEW_LINE> <DEDENT> <DEDENT> print ('number of total words: '+ str(total_count)) <NEW_LINE> enc, loss, first_products, neighbor_encs, target_encs = self.model.build_model() <NEW_LINE> init = tf.global_variables_initializer() <NEW_LINE> config = tf.ConfigProto(log_device_placement=False) <NEW_LINE> config.gpu_options.allow_growth = True <NEW_LINE> sess = tf.Session(config=config) <NEW_LINE> sess.run(init) <NEW_LINE> saver = tf.train.Saver(tf.all_variables(), max_to_keep=100) <NEW_LINE> ckpt = tf.train.get_checkpoint_state(self.model_dir) <NEW_LINE> global_step = 0 <NEW_LINE> if ckpt and ckpt.model_checkpoint_path: <NEW_LINE> <INDENT> saver.restore(sess, ckpt.model_checkpoint_path) <NEW_LINE> global_step = int(ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]) <NEW_LINE> print ("Model restored.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print ('No checkpoint file found.') <NEW_LINE> exit() <NEW_LINE> <DEDENT> print ("Start testing.") <NEW_LINE> self.feats, self.labels, utters, spks = load_data(self.example_file, self.label_file, self.utter_file) <NEW_LINE> count = 0 <NEW_LINE> self.n_feats, self.feat_idx, self.skip_feat_idx, self.spk2idx, self.idx2spk, self.masks = subsample_data(self.feats, self.labels, utters, spks, word_freq, total_count, self.min_count, self.gram_num, self.sampling_factor) <NEW_LINE> self.n_batches = self.n_feats // self.batch_size <NEW_LINE> print ('# of testing batches: ' + str(self.n_batches)) <NEW_LINE> count += 1 <NEW_LINE> self.compute_test_loss(sess, None, None, None, loss, enc, embedding_file, global_step) | Testing for Audio-Word2Vec. | 625941c01f037a2d8b946160 |
def customer_active(self, appid, openid): <NEW_LINE> <INDENT> self.send_customer_active(appid, openid) <NEW_LINE> return self.recv_customer_active() | Parameters:
- appid
- openid | 625941c0796e427e537b0525 |
def right(self, count, fill): <NEW_LINE> <INDENT> if self.get_position() + count >= self._max_size: <NEW_LINE> <INDENT> raise IndexError(f"TuringTape has reached its maximum size of {self._max_size}.") <NEW_LINE> <DEDENT> if self.get_position() + count >= len(self._tape): <NEW_LINE> <INDENT> self._tape += [self._new_cell_value] * (1 + self.get_position() + count - len(self._tape)) <NEW_LINE> <DEDENT> if fill != '*': <NEW_LINE> <INDENT> for i in range(self.get_position() + 1, self.get_position() + count + 1): <NEW_LINE> <INDENT> self._tape[i] = fill <NEW_LINE> <DEDENT> <DEDENT> self._position += count | Moves the tape to the right and returns the selected value after the move. | 625941c015fb5d323cde0a6e |
def adapterFromLiveConnect(self, parentObj, oldApi): <NEW_LINE> <INDENT> return KParts.ScriptableExtension() | static KParts.ScriptableExtension KParts.ScriptableExtension.adapterFromLiveConnect(QObject parentObj, KParts.LiveConnectExtension oldApi) | 625941c031939e2706e4cdce |
def create_key_list(key_column): <NEW_LINE> <INDENT> key_list = list(key_column.unique()) <NEW_LINE> return key_list | This function creates a list of all the different
elements present in a column of the dataset | 625941c0656771135c3eb7ce |
def write(self, line): <NEW_LINE> <INDENT> self.outstream.write(line + "\n") | Write a line of output to the output stream | 625941c096565a6dacc8f62d |
def getAnyCertificate(self, certificateName): <NEW_LINE> <INDENT> return self._identityStorage.getCertificate(certificateName, True) | Get a certificate even if the certificate is not valid anymore.
:param Name certificateName: The name of the requested certificate.
:return: The requested certificate.
:rtype: IdentityCertificate | 625941c04527f215b584c3bb |
def file_name(self): <NEW_LINE> <INDENT> messagebox.showinfo("Filename", self.gui_instance.get_cur_filename()) | Displays current file name and path
| 625941c0de87d2750b85fcf2 |
def __init__(self, df, transform=None): <NEW_LINE> <INDENT> self.image_files = df["ImageIndex"].values <NEW_LINE> self.labels = df["Label"].values <NEW_LINE> self.transform = transform <NEW_LINE> self.image_path = PATH/"images_250" | Args:
dataframe with data: image_file, label
transform: if True apply transforms to images | 625941c024f1403a92600aca |
def addWindowProps(self, winProps): <NEW_LINE> <INDENT> relTo = winProps.get("layout relative to") <NEW_LINE> if relTo is None: <NEW_LINE> <INDENT> if len(self.windowPropsList) > 0: <NEW_LINE> <INDENT> raise WinLayoutException(u"All except first window must relate " u"to another window. %s is not first window" % winProps["name"]) <NEW_LINE> <DEDENT> self.windowPropsList.append(winProps) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> relation = winProps.get("layout relation") <NEW_LINE> if relation not in ("above", "below", "left", "right"): <NEW_LINE> <INDENT> raise WinLayoutException((u"Window %s must relate to previously " u"entered window") % winProps["name"]) <NEW_LINE> <DEDENT> for pr in self.windowPropsList: <NEW_LINE> <INDENT> if pr["name"] == relTo: <NEW_LINE> <INDENT> self.windowPropsList.append(winProps) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise WinLayoutException((u"Window %s must relate to previously " u"entered window") % winProps["name"]) | Add window props of new window which should be layed out.
winProps is then owned by addWindowProps, do not reuse it. | 625941c0eab8aa0e5d26dab9 |
def remove_defaults_nav(portal): <NEW_LINE> <INDENT> items_removable = ['news', 'events', 'Members', 'front-page'] <NEW_LINE> for item in items_removable: <NEW_LINE> <INDENT> if hasattr(portal, item): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> api.content.delete(obj=portal[item]) <NEW_LINE> logger.info("Deleted {0} item".format(item)) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> logger.info("No {0} item detected. Hmm... strange. Continuing....".format(item)) | Remove defaults navegations and contents | 625941c0507cdc57c6306c37 |
def post(request, context): <NEW_LINE> <INDENT> data = request.json() <NEW_LINE> url = cache_key(request.url + '/' + data['metadata']['name'] + '/') <NEW_LINE> resource_type = get_type(request.url) <NEW_LINE> if resource_type != 'namespaces': <NEW_LINE> <INDENT> namespace = get_namespace(url, resource_type) <NEW_LINE> if cache.get(namespace) is None: <NEW_LINE> <INDENT> context.status_code = 404 <NEW_LINE> context.reason = 'Not Found' <NEW_LINE> return {} <NEW_LINE> <DEDENT> <DEDENT> if cache.get(url) is not None: <NEW_LINE> <INDENT> context.status_code = 409 <NEW_LINE> context.reason = 'Conflict' <NEW_LINE> return {} <NEW_LINE> <DEDENT> timestamp = str(datetime.utcnow().strftime(MockSchedulerClient.DATETIME_FORMAT)) <NEW_LINE> data['metadata']['creationTimestamp'] = timestamp <NEW_LINE> data['metadata']['resourceVersion'] = 1 <NEW_LINE> data['metadata']['uid'] = str(uuid.uuid4()) <NEW_LINE> if resource_type not in ['nodes', 'namespaces']: <NEW_LINE> <INDENT> namespace = request.url.replace(settings.SCHEDULER_URL + '/api/v1/namespaces/', '') <NEW_LINE> namespace = namespace.replace(settings.SCHEDULER_URL + '/apis/extensions/v1beta1/namespaces/', '') <NEW_LINE> namespace = namespace.split('/')[0] <NEW_LINE> data['metadata']['namespace'] = namespace <NEW_LINE> <DEDENT> if resource_type in ['replicationcontrollers', 'replicasets', 'deployments']: <NEW_LINE> <INDENT> data['status'] = { 'observedGeneration': 1 } <NEW_LINE> data['metadata']['generation'] = 1 <NEW_LINE> if resource_type in ['replicationcontrollers', 'replicasets']: <NEW_LINE> <INDENT> upsert_pods(data, url) <NEW_LINE> <DEDENT> elif resource_type == 'deployments': <NEW_LINE> <INDENT> manage_replicasets(data, url) <NEW_LINE> <DEDENT> <DEDENT> if resource_type == 'pods': <NEW_LINE> <INDENT> create_pods(url, data['metadata']['labels'], data, 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> add_cache_item(url, resource_type, data) <NEW_LINE> <DEDENT> context.status_code = 201 <NEW_LINE> context.reason = 'Created' <NEW_LINE> return data | Process a POST request to the kubernetes API | 625941c05fdd1c0f98dc0194 |
def pick_temp_directory(): <NEW_LINE> <INDENT> if sys.platform == 'linux2': <NEW_LINE> <INDENT> return "/dev/shm" <NEW_LINE> <DEDENT> return tempfile.mkdtemp() | Select a temporary directory for the test files.
Set the tmproot global variable. | 625941c050485f2cf553ccfa |
def __repr__(self): <NEW_LINE> <INDENT> return f"<{self.__class__.__name__} {self.name} hp={self.current_health} lvl={self.level}>" | Returns a representation of the entity | 625941c0498bea3a759b9a11 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, ProductParameterOptions): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.to_dict() == other.to_dict() | Returns true if both objects are equal | 625941c0e64d504609d747a1 |
def fetch_user(self, room_name: str, user) -> Optional[Row]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> query = text(f"SELECT * FROM user WHERE username = '{user.name}' AND chatango_room = '{room_name}';") <NEW_LINE> return self.db.execute(query).fetchone() <NEW_LINE> <DEDENT> except SQLAlchemyError as e: <NEW_LINE> <INDENT> print(f"SQLAlchemyError occurred while fetching user {user.name}: {e}") <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(f"Failed to execute SQL query while fetching user {user.name}: {e}") | Run a SELECT query.
:param str room_name: Chatango room.
:param user: User responsible for triggering command.
:returns: Optional[Row] | 625941c0d99f1b3c44c674f6 |
def rmsprop(self, tparams, grads, func_input, cost, lr): <NEW_LINE> <INDENT> zipped_grads = self.get_shared(tparams, 'grad') <NEW_LINE> running_grads = self.get_shared(tparams, 'rgrad') <NEW_LINE> running_grads2 = self.get_shared(tparams, 'rgrad2') <NEW_LINE> zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)] <NEW_LINE> rgup = [(rg, 0.95 * rg + 0.05 * g) for rg, g in zip(running_grads, grads)] <NEW_LINE> rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2)) for rg2, g in zip(running_grads2, grads)] <NEW_LINE> f_grad_shared = theano.function(func_input, cost, updates=zgup + rgup + rg2up, name='rmsprop_f_grad_shared') <NEW_LINE> updir = self.get_shared(tparams, 'updir') <NEW_LINE> updir_new = [(ud, 0.9 * ud - 1e-4 * zg / tensor.sqrt(rg2 - rg ** 2 + 1e-4)) for ud, zg, rg, rg2 in zip(updir, zipped_grads, running_grads, running_grads2)] <NEW_LINE> param_up = [(p, p + udn[1]) for p, udn in zip(tparams.values(), updir_new)] <NEW_LINE> f_update = theano.function([lr], [], updates=updir_new + param_up, on_unused_input='ignore', name='rmsprop_f_update') <NEW_LINE> return f_grad_shared, f_update | A variant of SGD that scales the step size by running average of the
recent step norms.
Notes
-----
For more information, see [Hint2014]_.
.. [Hint2014] Geoff Hinton, *Neural Networks for Machine Learning*,
lecture 6a,
http://cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf | 625941c0f548e778e58cd4de |
def parseElseIf(tokens, j): <NEW_LINE> <INDENT> tempTree = []; <NEW_LINE> j = parseIf(tokens[:], j+1, tempTree, 'else if'); <NEW_LINE> [_, cond, code] = tempTree[0]; <NEW_LINE> tree[-1].append(cond); <NEW_LINE> tree[-1].append(code); <NEW_LINE> return j; | Helps parseElse() in parsing else-if statements. | 625941c0090684286d50ec45 |
def __init__(self, setting_repositories: List[str]=None, default_setting_extensions: List[str]=None, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.setting_repositories = setting_repositories if setting_repositories is not None else [] <NEW_LINE> self.default_setting_extensions = default_setting_extensions if default_setting_extensions is not None else [] | Constructor.
:param setting_repositories: directories that may contain variable source files (highest preference first)
:param default_setting_extensions: file extensions that variable source files could have if that given is not
found(highest preference first, e.g. ["json", "init"])
:param kwargs: named arguments required for `ProjectVariablesUpdater` | 625941c07d847024c06be21b |
def gamma_sn(x, params): <NEW_LINE> <INDENT> shape, scale = params <NEW_LINE> retval = 1. / (gamma_func(shape) * scale) * (x / scale) ** (shape - 1.) * np.exp(-x / scale) <NEW_LINE> return retval | Gamma distribution for shot-noise process in terms of
shape and scale parameter.
shape: gamma = <Phi>^2/Phi_rms^2
scale: Phi_rms^2 / <Phi>
PDF(Phi) = 1 / (scale * Gamma(shape)) * (x/scale) ** (shape - 1) *
exp(-x / scale) | 625941c097e22403b379cefb |
def fill_area(self, x, y, width, height, color, opacity = 1): <NEW_LINE> <INDENT> self.save_context() <NEW_LINE> self.rectangle(x, y, width, height) <NEW_LINE> self._add_instruction("clip") <NEW_LINE> self.rectangle(x, y, width, height) <NEW_LINE> self.fill(color, opacity) <NEW_LINE> self.restore_context() | fill rectangular area with specified color | 625941c026068e7796caec3c |
def doQuotesSwapping(aString): <NEW_LINE> <INDENT> s = [] <NEW_LINE> foundlocs = redoublequotedstring.finditer(aString) <NEW_LINE> prevend = 0 <NEW_LINE> for loc in foundlocs: <NEW_LINE> <INDENT> start, end = loc.span() <NEW_LINE> s.append(aString[prevend:start]) <NEW_LINE> tempstr = aString[start:end] <NEW_LINE> endchar = tempstr[-1] <NEW_LINE> ts1 = tempstr[1:-2] <NEW_LINE> ts1 = ts1.replace("'", escapedSingleQuote) <NEW_LINE> ts1 = "'%s'%s" % (ts1, endchar) <NEW_LINE> s.append(ts1) <NEW_LINE> prevend = end <NEW_LINE> <DEDENT> s.append(aString[prevend:]) <NEW_LINE> return ''.join(s) | rewrite doublequoted strings with single quotes as singlequoted strings with
escaped single quotes | 625941c04d74a7450ccd4125 |
def findMaxNeibor(data,r,checklist): <NEW_LINE> <INDENT> cities = data[0] <NEW_LINE> neibors=[] <NEW_LINE> i=0 <NEW_LINE> for city in cities: <NEW_LINE> <INDENT> CityUnserved=CitynotServed(city, r, data,checklist) <NEW_LINE> neibors.append(len(CityUnserved)) <NEW_LINE> <DEDENT> maxNeibor=max(neibors) <NEW_LINE> if maxNeibor==0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> i=neibors.index(maxNeibor) <NEW_LINE> return cities[i] | return a city that can serve the most cities within the rage r to minimize the cost | 625941c0566aa707497f44ce |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.