code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _reduce(v): <NEW_LINE> <INDENT> if reduction == 'concat' and _collective_all_reduce_multi_worker(strategy): <NEW_LINE> <INDENT> return _multi_worker_concat(v, strategy) <NEW_LINE> <DEDENT> if not _is_per_replica_instance(v): <NEW_LINE> <INDENT> return v <NEW_LINE> <DEDENT> elif reduction == 'first': <NEW_LINE> <IND...
Reduce a single `PerReplica` object.
625941d83eb6a72ae02ec752
def get_files_with_ext_mask(dir_name, ext_mask): <NEW_LINE> <INDENT> if ext_mask[0] == '.': <NEW_LINE> <INDENT> ext_mask = ext_mask[1:] <NEW_LINE> <DEDENT> files = directory_listing(dir_name) <NEW_LINE> output = list() <NEW_LINE> for f in files: <NEW_LINE> <INDENT> dummy, ext = get_filename_and_ext(f) <NEW_LINE> if len...
Get all files in directory with specified extension :param dir_name: :param ext_mask: :return: list of files :rtype: list()
625941d88e71fb1e9831da19
def launch_training_job(parent_dir, data_dir, job_name, params): <NEW_LINE> <INDENT> model_dir = os.path.join(parent_dir, job_name) <NEW_LINE> if not os.path.exists(model_dir): <NEW_LINE> <INDENT> os.makedirs(model_dir) <NEW_LINE> <DEDENT> json_path = os.path.join(model_dir, 'params.json') <NEW_LINE> params.save(json_p...
Launch training of the model with a set of hyperparameters in parent_dir/job_name Args: parent_dir: (string) directory containing config, weights and log data_dir: (string) directory containing the dataset params: (dict) containing hyperparameters
625941d85fdd1c0f98dc04a4
def test_tjp_id_attribute_returns_a_plausible_id(self): <NEW_LINE> <INDENT> self.test_studio.id = 432 <NEW_LINE> assert self.test_studio.tjp_id == 'Studio_432'
testing if the tjp_id is returning something meaningful
625941d85f7d997b87174d0a
def put(self, key: str, value: object) -> None: <NEW_LINE> <INDENT> index = self.hash_function(key) % self.capacity <NEW_LINE> destination = self.buckets[index] <NEW_LINE> if destination.length() > 0: <NEW_LINE> <INDENT> for node in destination: <NEW_LINE> <INDENT> if node.key == key: <NEW_LINE> <INDENT> node.value = v...
Adds a new value to the hash table
625941d8091ae356686671cb
def _reload(self): <NEW_LINE> <INDENT> if self._lastreload + self._reloaddeadtime < time.time(): <NEW_LINE> <INDENT> logger.debug("Checking change time of config file...") <NEW_LINE> self._lastreload = time.time() <NEW_LINE> if self._mtime != os.path.getmtime(self._filename): <NEW_LINE> <INDENT> self._load()
" reloads data from file if file has changed recently
625941d88a43f66fc4b542d3
def buffer_quilts(quilts, patch_shape): <NEW_LINE> <INDENT> bsize = (int(patch_shape[0] / 2), int(patch_shape[1] / 2)) <NEW_LINE> buffers = [ [[0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [bsize[1], 0], [0, 0]], [[0, 0], [bsize[0], 0], [0, 0], [0, 0]], [[0, 0], [bsize[0], 0], [bsize[1], 0], [0, 0]], ] <NEW_LINE> q...
Adds a buffer (shift) to the edge of each quilt to align each pixel across the quilts.
625941d84428ac0f6e5baa63
def __periodic_maintenance__(self): <NEW_LINE> <INDENT> for child in self.__dict__: <NEW_LINE> <INDENT> try: child.__periodic_maintenance__() <NEW_LINE> except AttributeError: pass
A method called down the server object tree to perform maintanence
625941d826068e7796caef52
def predict_proba(self, X): <NEW_LINE> <INDENT> res = [] <NEW_LINE> for item in X: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> pred = self._retrieve_preds(item) <NEW_LINE> res.append(list(zip(pred.index[:self.num_items], pred.values[:self.num_items]))) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> res.append(np.full...
Predicts the desired number of outputs and returns normalized scores with them.
625941d8cc0a2c11143dd101
def unsafe_index( builder: IRBuilder, target: Value, index: Value, line: int ) -> Value: <NEW_LINE> <INDENT> if is_list_rprimitive(target.type): <NEW_LINE> <INDENT> return builder.primitive_op(list_get_item_unsafe_op, [target, index], line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return builder.gen_method_call(ta...
Emit a potentially unsafe index into a target.
625941d83346ee7daa2b2fdd
def pack(self): <NEW_LINE> <INDENT> buffer = bytearray() <NEW_LINE> buffer.extend(LMCPObject.LMCPObject.pack(self)) <NEW_LINE> buffer.extend(struct.pack(">q", self.FootprintRequestID)) <NEW_LINE> buffer.extend(struct.pack(">q", self.VehicleID)) <NEW_LINE> buffer.extend(struct.pack(">H", len(self.EligibleWavelengths) ))...
Packs the object data and returns a string that contains all of the serialized members.
625941d871ff763f4b5498ff
def list_policys(args, vault): <NEW_LINE> <INDENT> policy_list = vault.policy.list() <NEW_LINE> for policy in policy_list: <NEW_LINE> <INDENT> print(policy)
Run this module :returns: None
625941d86fece00bbac2d9b1
def instance_or_null_side_effect(self, *args): <NEW_LINE> <INDENT> if len(args) == 2: <NEW_LINE> <INDENT> raise TypeError
Side effect to raise TypeError.
625941d80c0af96317bb8459
def receive_message(sock, request_id, max_message_size=MAX_MESSAGE_SIZE): <NEW_LINE> <INDENT> length, _, response_to, op_code = _UNPACK_HEADER( _receive_data_on_socket(sock, 16)) <NEW_LINE> if op_code != _OpReply.OP_CODE: <NEW_LINE> <INDENT> raise ProtocolError("Got opcode %r but expected " "%r" % (op_code, _OpReply.OP...
Receive a raw BSON message or raise socket.error.
625941d8f8510a7c17cf996d
def getStatistics(self): <NEW_LINE> <INDENT> self.statistics() <NEW_LINE> return self.stats
Return a Statistics class for statistics :rtype: the :class:`Statistics.Statistics` instance
625941d8099cdd3c635f0eca
def setUp(self): <NEW_LINE> <INDENT> test_utils.setup_test_storage() <NEW_LINE> folder = '{0}/storage/test_fixtures/updatetest'.format(settings.ROOT_PATH) <NEW_LINE> with open('{0}/storage-global.json'.format(folder), 'rb') as storagein: <NEW_LINE> <INDENT> self.storage_json = json.load(storagein) <NEW_LINE> <DEDENT> w...
Creates a new storage object instance for testing.
625941d8236d856c2ad44a4d
def show_messages_for_view(view): <NEW_LINE> <INDENT> window = view.window() <NEW_LINE> paths = WINDOW_MESSAGES.get(window.id(), {}).get('paths', {}) <NEW_LINE> messages = paths.get(view.file_name(), None) <NEW_LINE> if messages: <NEW_LINE> <INDENT> _show_messages_for_view(view, messages)
Adds all phantoms and region outlines for a view.
625941d8b57a9660fec33af7
def load_region_mask_iris(*regions): <NEW_LINE> <INDENT> cubes = [] <NEW_LINE> names = [] <NEW_LINE> for i, fil in enumerate(get_htap_mask_files(*regions)): <NEW_LINE> <INDENT> names.append(regions[i]) <NEW_LINE> cubes.append(load_cube(fil)) <NEW_LINE> <DEDENT> if len(cubes) == 1: <NEW_LINE> <INDENT> out = cubes[0] <NE...
Loads regional mask to iris. Parameters ----------- region_id : str Chosen region. Returns --------- iris.cube.Cube cube representing merged mask from input regions
625941d8eab8aa0e5d26ddc9
def __repr__(self): <NEW_LINE> <INDENT> return pformat(self.getSwaggerApiDeclaration())
Mainly for testing, this displays the Swagger declaration in properly formatted JSON when you print an instance of this class.
625941d892d797404e3043fb
def _unique_user(user): <NEW_LINE> <INDENT> def txn(): <NEW_LINE> <INDENT> voter = _get_or_create_voter(user) <NEW_LINE> voter.count += 1 <NEW_LINE> voter.hasAddedQuote = True <NEW_LINE> voter.put() <NEW_LINE> return voter.count <NEW_LINE> <DEDENT> count = db.run_in_transaction(txn) <NEW_LINE> return hashlib.md5(user.e...
Creates a unique string by using an increasing counter sharded per user. The resulting string is hashed to keep the users email address private.
625941d8e8904600ed9f21a0
def generate_swig_interface_files(swig_outdir: str = None, with_hdf5: bool = None) -> None: <NEW_LINE> <INDENT> swig_exe = find_swig() <NEW_LINE> swig_version = get_swig_version(swig_exe) <NEW_LINE> swig_args = [ '-c++', '-python', '-py3', '-threads', '-Wall', f'-Iamici{os.sep}swig', f'-Iamici{os.sep}include', ] <NEW_L...
Compile the swig python interface to amici
625941d8a8ecb033257d333d
def distance_2D(point_A, point_B): <NEW_LINE> <INDENT> x_diff = point_A[0] - point_B[0] <NEW_LINE> y_diff = point_A[1] - point_B[1] <NEW_LINE> return math.sqrt(x_diff ** 2 + y_diff ** 2)
This code computes the 2D euclidian distance between two points A and B Inputs: Point_A : the coordinates of the first point as a tuple (x_a,y_a) Point_B : the coordinates of the second point as a tuple (x_b,y_b) Output: Return the 2D distance between A and D
625941d8d8ef3951e32437ae
def clean_url(self): <NEW_LINE> <INDENT> data = self.cleaned_data['url'].lower() <NEW_LINE> check = re.match(r'^([a-z0-9]+[-]*)+[a-z0-9]+$', data) <NEW_LINE> if not check: <NEW_LINE> <INDENT> raise ValidationError(_("Only lowercase letters, numbers, or hyphens are admitted. It cannot start or end with a hyphen.")) <NEW...
Use the same regex used by the URLconf for matching the public blog URLs.
625941d8bde94217f368305f
def run(self, inp): <NEW_LINE> <INDENT> print(inp) <NEW_LINE> return (inp, Runner.UNRESOLVED)
Print the given input
625941d80a50d4780f667105
def build_graph(*, addresses: List, creditlines: List, balances: List): <NEW_LINE> <INDENT> assert len(creditlines) == len(addresses) - 1 <NEW_LINE> gr = nx.graph.Graph() <NEW_LINE> for a, b, creditline, balance in zip( addresses, addresses[1:], creditlines, balances ): <NEW_LINE> <INDENT> edge = zero_edge_data() <NEW_...
build a simple graph with zero balances and creditlines between each consecutive pairs in addresses. creditlines[i] is set as the creditline given from addresses[i+1] to addresses[i]. I.e. this is setup in a way that a payment from addresses[0] to addresses[-1] could work, given that sufficient creditlines are availabl...
625941d8d58c6744b4257ecf
def test_revoke_role_from_user_on_domain(self): <NEW_LINE> <INDENT> self.k.create_domain(v.default_domain_name) <NEW_LINE> self.k.create_role(v.member_role_name) <NEW_LINE> res = self.k.revoke_role_from_user_on_domain( ou_name=v.default_domain_name, target_name=v.user01_userid, role_name=v.member_role_name) <NEW_LINE> ...
not implemented An unexpected error prevented the server from fulfilling your request. 'Identity' object has no attribute 'delete_grant'
625941d8d10714528d5fff56
def get_dom_id(self): <NEW_LINE> <INDENT> return '{}_{}'.format(self.filterlist.get_dom_id_prefix(), self.get_slug())
Get the DOM ID of this filter. The base template adds this to the wrapping DIV, but you can also use this if you need DOM IDs for components of a filter (E.g.: Field ID to attach a labels to a form field).
625941d88e7ae83300e4b23e
def func2(): <NEW_LINE> <INDENT> with tf.variable_scope("var1"): <NEW_LINE> <INDENT> v1=tf.get_variable('v1',[1],initializer=tf.constant_initializer(1.0)) <NEW_LINE> print(v1.name) <NEW_LINE> <DEDENT> with tf.variable_scope("var1",reuse=True): <NEW_LINE> <INDENT> v = tf.get_variable('v1') <NEW_LINE> print(v==v1) <NEW_L...
tf.variable_scope()控制tf.get_variable()获取已创建的变量
625941d8925a0f43d254a0e9
def round_coords(coords): <NEW_LINE> <INDENT> if coords: <NEW_LINE> <INDENT> return {"lat": round(float(coords["lat"]), 4), "lon": round(float(coords["lon"]), 4)} <NEW_LINE> <DEDENT> return None
Round lat/lon to 4 decimal points -- OSM often returns artificially precise values
625941d8d486a94d0b98e3b7
def running(name, container=None, port_bindings=None, binds=None, publish_all_ports=False, links=None, lxc_conf=None, privileged=False): <NEW_LINE> <INDENT> is_running = __salt('docker.is_running')(container) <NEW_LINE> if is_running: <NEW_LINE> <INDENT> return _valid( comment='Container {!r} is started'.format(contain...
Ensure that a container is running. (`docker inspect`) name name of the service container name of the container to start binds like -v of docker run command .. code-block:: yaml - binds: - /var/log/service: /var/log/service publish_all_ports links Link several container to...
625941d823849d37ff7b32fe
def _log_epoch(self, ep: int, modules: nn.ModuleDict) -> None: <NEW_LINE> <INDENT> flds = [] <NEW_LINE> for _, module in modules.items(): <NEW_LINE> <INDENT> flds.extend(module.epoch_log_fields()) <NEW_LINE> <DEDENT> flds.append(time.time() - self._train_start) <NEW_LINE> self._logger.log(ep, flds)
Log the results of the epoch :param ep: Epoch number :param modules: Modules to log
625941d860cbc95b062c67b4
def update_parameters_with_adam(parameters, grads, v, s, t, learning_rate = 0.01, beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8): <NEW_LINE> <INDENT> L = len(parameters) // 2 <NEW_LINE> v_corrected = {} <NEW_LINE> s_corrected = {} <NEW_LINE> for l in range(L): <NEW_LINE> <INDENT> v["dW" + str(l+1)] = beta1 * v["dW" + str...
Update parameters using Adam Arguments: parameters -- python dictionary containing your parameters: parameters['W' + str(l)] = Wl parameters['b' + str(l)] = bl grads -- python dictionary containing your gradients for each parameters: grads['dW' + str(l)] = dWl ...
625941d810dbd63aa1bd2e13
def find_partners(iou_matrix, threshold=0.0): <NEW_LINE> <INDENT> assert (0.0 < threshold < 1.0), "IoU threshold must lie between (0, 1)" <NEW_LINE> iou_matrix[iou_matrix <= threshold] = 0.0 <NEW_LINE> partners = iou_matrix.argmax(axis=1) <NEW_LINE> partners[np.all(iou_matrix == 0.0, axis=1)] = -1 <NEW_LINE> return par...
Given a matrix of intersection-over-union (IoU) values between clusters, find matching partners. For each row (cluster), find highest IoU counterpart and return the corresponding column index. Applies high-pass thresholding to cut out weak overlaps; default to 0.0 which means no thresholding. Args: iou_matrix:: 2D...
625941d8bde94217f3683060
def addAnnualizedRates(trs): <NEW_LINE> <INDENT> for tr in trs: <NEW_LINE> <INDENT> if tr.bond.latestPrice is not None: <NEW_LINE> <INDENT> if tr.transactionType.factor == -1: <NEW_LINE> <INDENT> tr.annualizedRate = computeAnnualizedRate(tr.bond.latestPrice, tr.totalPrice, tr.quantity, tr.bond.latestPriceDate, tr.trans...
Given a list of transactions, add an annualized rate property
625941d894891a1f4081bd1b
def parse_input_line(line): <NEW_LINE> <INDENT> a = line.split() <NEW_LINE> return Instruction(a[0], a[1], int(a[2]), a[4], a[5], int(a[6]))
>>> parse_input_line("b inc 5 if a > 1") Instruction(register='b', op='inc', arg=5, check='a', compare='>', val=1)
625941d8bf627c535bc13440
def _decode_train(self, decoder, encoder_output, _features, labels): <NEW_LINE> <INDENT> target_embedded = tf.nn.embedding_lookup(self.target_embedding, labels["target_ids"]) <NEW_LINE> return decoder(encoder_output.outputs, target_embedded[:, 1:-1])
Runs decoding in training mode
625941d831939e2706e4d0d8
def _convert_to_example(image_data, filename, label, label_text, height, width): <NEW_LINE> <INDENT> colorspace = b'RGB' <NEW_LINE> channels = 3 <NEW_LINE> image_format = b'JPEG' <NEW_LINE> obj = [] <NEW_LINE> verb = [] <NEW_LINE> for text in label_text: <NEW_LINE> <INDENT> assert len(text) == 2 <NEW_LINE> obj.append(t...
Build an Example proto for an example. Args: image_data: string, JPEG encoding of RGB image filename: string, filename of an image label: list of floats, identifier for the ground truth label_text: list of strings, e.g. ['airplane board', 'airplane ride'] height: integer, image height in pixels width: integ...
625941d8a219f33f34628bd8
def setChannelConversion(self, channelName, conversion): <NEW_LINE> <INDENT> self._setChannel(channelName, conversion, field = conversionField)
Modifies conversion dict of channel Parameters ---------------- channelName : str channel name conversion : dict conversion dictionnary
625941d823849d37ff7b32ff
def accuracy(self, accuracy_op, feed_dict, batch_size): <NEW_LINE> <INDENT> return self.run_op_in_batches(self.session, accuracy_op, feed_dict, batch_size).mean()
Return the average value of an accuracy op by running the network on small batches of feed_dict.
625941d87cff6e4e81117bf6
def enu2xyz (refpos_wgs84,enu): <NEW_LINE> <INDENT> refpos = me.measure(refpos_wgs84,'itrf') <NEW_LINE> lon,lat,rad = [ refpos[x]['value'] for x in ('m0','m1','m2') ] <NEW_LINE> xyz0 = rad*np.array([math.cos(lat)*math.cos(lon),math.cos(lat)*math.sin(lon),math.sin(lat)]) <NEW_LINE> xform = np.array([ [-math.sin(lon),mat...
converts xyz0 + ENU (Nx3 array) into xyz
625941d8d53ae8145f87a4dd
def test_train_supervised(): <NEW_LINE> <INDENT> gsn = GSN.new( layer_sizes=[ds.X.shape[1], 1000, ds.y.shape[1]], activation_funcs=["sigmoid", "tanh", rescaled_softmax], pre_corruptors=[GaussianCorruptor(0.5)] * 3, post_corruptors=[SaltPepperCorruptor(.3), None, SmoothOneHotCorruptor(.5)], layer_samplers=[BinomialSampl...
Train a supervised GSN.
625941d88e05c05ec3eea5e7
def has_file( path_or_repo: Union[str, os.PathLike], filename: str, revision: Optional[str] = None, mirror: Optional[str] = None, proxies: Optional[Dict[str, str]] = None, use_auth_token: Optional[Union[bool, str]] = None, ): <NEW_LINE> <INDENT> if os.path.isdir(path_or_repo): <NEW_LINE> <INDENT> return os.path.isfile(...
Checks if a repo contains a given file wihtout downloading it. Works for remote repos and local folders. <Tip warning={false}> This function will raise an error if the repository `path_or_repo` is not valid or if `revision` does not exist for this repo, but will return False for regular connection errors. </Tip>
625941d80fa83653e465722b
def get_queryset(self): <NEW_LINE> <INDENT> post_list = Post.objects.filter(tags=self.kwargs['tag_id']) <NEW_LINE> for post in post_list: <NEW_LINE> <INDENT> post.body = markdown.markdown(post.body, extension=[ 'markdown.extension.extra', 'markdown.extension.codehilite', 'markdown.extension.toc', ]) <NEW_LINE> <DEDENT>...
设置查询集为特定标签下的文章列表 :return: 文章列表
625941d8d99f1b3c44c677fc
def __get_root(self, x): <NEW_LINE> <INDENT> while self.__roots_by_vertex[x] != x: <NEW_LINE> <INDENT> self.__roots_by_vertex[x] = self.__roots_by_vertex[self.__roots_by_vertex[x]] <NEW_LINE> x = self.__roots_by_vertex[x] <NEW_LINE> <DEDENT> return x
Returns root of vertex x
625941d8f548e778e58cd7f0
def test_post_and_get_drone_category(self): <NEW_LINE> <INDENT> new_drone_category_name = 'Hexacopter' <NEW_LINE> response = self.post_drone_category(new_drone_category_name) <NEW_LINE> print("nPK {0}n".format(DroneCategory.objects.get().pk)) <NEW_LINE> assert response.status_code == status.HTTP_201_CREATED <NEW_LINE> ...
Test if we can create a new DroneCategory and then retrieve it
625941d838b623060ff0b05f
def allProcessed(self, page=1): <NEW_LINE> <INDENT> return self._query( 'all_processed', { 'page':page }, 'GET' )
Return the last fully processed 20 stories (ie. with sentences pulled out)
625941d85fc7496912cc3bef
def create_slider_mag_layout(self): <NEW_LINE> <INDENT> _ = QSlider(Qt.Vertical) <NEW_LINE> slider_mag = _ <NEW_LINE> _.setMinimum(1) <NEW_LINE> _.setMaximum(19) <NEW_LINE> _.setSingleStep(1) <NEW_LINE> _.setPageStep(1) <NEW_LINE> _.setValue(SLIDER_MAG_INIT_VAL) <NEW_LINE> _.valueChanged.connect(self.slider_mag_changed...
Create y-axis magnification slider layout and return the layout and generated slider widget to the caller NOTE: This slider holds 10 times the actual value because QSlider can't treat floating values.
625941d8b545ff76a8914086
def _move_from(self, event): <NEW_LINE> <INDENT> self.canvas.scan_mark(event.x, event.y)
Remember previous coordinates for scrolling with the mouse
625941d88c3a87329515862e
def select_nested_rnn(maybe_tuple, time_step): <NEW_LINE> <INDENT> if isinstance(maybe_tuple, tuple): <NEW_LINE> <INDENT> select = tuple([select_nested_rnn(item, time_step) for item in maybe_tuple]) <NEW_LINE> if hasattr(maybe_tuple, '_make'): <NEW_LINE> <INDENT> select = maybe_tuple._make(select) <NEW_LINE> <DEDENT> <...
return possibly nested tensor at the time_step (time major).
625941d89c8ee82313fbb9e7
def resolve(self, target): <NEW_LINE> <INDENT> dest = next(target, None) <NEW_LINE> if dest is None: <NEW_LINE> <INDENT> if self._callback is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return ResolvedRequest(self._callback, target.arguments) <NEW_LINE> <DEDENT> if dest not in self._fixed: <NEW_LINE> <IND...
Resolve the *target* url. *target* is an instance of :class:`URLTarget`. If the router finds a route matching, it returns an instance of :class:`ResolvedRequest` with the callback and the arguments from the url. Else it returns ``None``.
625941d85e10d32532c5f198
def _calculate_evpi(self, column): <NEW_LINE> <INDENT> baseline_uncertainty = self.eol(self.last_run) <NEW_LINE> mu = self.last_run[column].mean() <NEW_LINE> fixed = self.last_run.copy() <NEW_LINE> fixed[column] = mu <NEW_LINE> for key, item in self.deterministic.items(): <NEW_LINE> <INDENT> var = patsy.dmatrix(f"I({it...
Calculate information value for a single specified variable Our information value
625941d8462c4b4f79d1d941
def MailExceptionMiddleware(mail, error_message): <NEW_LINE> <INDENT> def decorator(app): <NEW_LINE> <INDENT> @functools.wraps(app) <NEW_LINE> def wrapper(environ, start_response): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> appiter = app(environ, start_response) <NEW_LINE> for item in appiter: <NEW_LINE> <INDENT> yie...
Sends the traceback to (mail) and displays (error_message) to the user
625941d8097d151d1a2230c9
def list_directories(s): <NEW_LINE> <INDENT> def dir_list(d): <NEW_LINE> <INDENT> nonlocal tab_stop <NEW_LINE> files = os.listdir(d) <NEW_LINE> for f in files: <NEW_LINE> <INDENT> current_dir = os.path.join(d, f) <NEW_LINE> if os.path.isdir(current_dir): <NEW_LINE> <INDENT> print("\t"*tab_stop + "Directory " + f) <NEW_...
x
625941d8d10714528d5fff57
def calculation(self): <NEW_LINE> <INDENT> self.B = self._B = self.dec2bin(self.num1) <NEW_LINE> temp = self.B <NEW_LINE> self.C = self.dec2bin(self.num2) <NEW_LINE> self.B = self.change_Complement(temp, self.STATE_COMPLEMENT_CODE) <NEW_LINE> self._B = self.change_Complement(self.B, self.STATE_CHANGE_COMPLEMENT) <NEW_L...
整个代码的计算,总框架 :return: None
625941d826238365f5f0f0e3
def do_predictions(self, query): <NEW_LINE> <INDENT> data = self.load_predictions() <NEW_LINE> data, rotate = query_json(data, query) <NEW_LINE> return flatten_to_table(data, rotate)
Respond to a request for predictions.
625941d8090684286d50ef59
def __init__(self): <NEW_LINE> <INDENT> self.by_user_id = ProjectUserSearch() <NEW_LINE> self.search = ProjectKeywordSearch() <NEW_LINE> self.by_project_id = ProjectLookup()
Create local objects for sub tree items.
625941d8d8ef3951e32437af
def plot_systems_compare(homer_output_systems1,homer_output_systems2): <NEW_LINE> <INDENT> ax_y={'Architecture/PV NG Base (kW)':'PV Capacity (kW)'} <NEW_LINE> ax_x={'Architecture/Batt 1kWh LA':'Battery Capacity (kWh)'} <NEW_LINE> z_list={'System/Ren Frac (%)':'Renewable Fraction (%)','Carbon Emissions (tCO2e/y)':'Carbo...
Plots distribution of difference between performance metrics for two variables (e.g. PV capacity vs. battery capacity). Interpolates metrics onto same mesh and then subtracts them.
625941d84e4d5625662d4647
def data(self): <NEW_LINE> <INDENT> data0 = self._bus.read_i2c_block_data(self.addr, (self.CMD | self.DATA0), 2) <NEW_LINE> data1 = self._bus.read_i2c_block_data(self.addr, (self.CMD | self.DATA1), 2) <NEW_LINE> ch0 = data0[1] * 256 + data0[0] <NEW_LINE> ch1 = data1[1] * 256 + data1[0] <NEW_LINE> if self._gain16: <NEW_...
Return measured values (after gain normalization)
625941d8435de62698dfdebf
def test___init__(self): <NEW_LINE> <INDENT> value = SCons.Node.Python.Value('v') <NEW_LINE> node = SCons.Node.Node() <NEW_LINE> node._func_get_contents = 2 <NEW_LINE> node.add_to_implicit([value]) <NEW_LINE> contents = node.get_contents() <NEW_LINE> expected_contents = '%s %s\n' % (value.get_csig(), value.name) <NEW_L...
Test support for a Value() being an implicit dependency of a Node
625941d8097d151d1a2230ca
def parse_gs_spin(gs_spin): <NEW_LINE> <INDENT> result = {} <NEW_LINE> gs_spin = gs_spin.strip() <NEW_LINE> result['extrapolated'] = True if gs_spin.count('#') > 0 else False <NEW_LINE> if result['extrapolated']: <NEW_LINE> <INDENT> gs_spin = gs_spin.replace('#', ' ') <NEW_LINE> <DEDENT> result['value'] = gs_spin <NEW_...
Parses nubase style spin information returns dictionary {value, extrapolated}
625941d8de87d2750b860006
def collect(self, a_xg, broadcast=False): <NEW_LINE> <INDENT> if self.comm.size == 1: <NEW_LINE> <INDENT> return a_xg <NEW_LINE> <DEDENT> xshape = a_xg.shape[:-3] <NEW_LINE> if self.rank != 0: <NEW_LINE> <INDENT> self.comm.ssend(a_xg, 0, 301) <NEW_LINE> if broadcast: <NEW_LINE> <INDENT> A_xg = self.empty(xshape, a_xg.d...
Collect distributed array to master-CPU or all CPU's.
625941d8460517430c3943f2
def test_update_boot_invalid(make_mock_vm): <NEW_LINE> <INDENT> domain_mock = make_mock_vm() <NEW_LINE> with pytest.raises(SaltInvocationError): <NEW_LINE> <INDENT> virt.update( "my_vm", boot={ "loader": "/usr/share/OVMF/OVMF_CODE.fd", "initrd": "/root/f8-i386-initrd", }, ) <NEW_LINE> <DEDENT> with pytest.raises(SaltIn...
Test virt.update(), change boot, invalid values
625941d816aa5153ce3626e9
def get_puzzle(self): <NEW_LINE> <INDENT> print('solution') <NEW_LINE> self.print_board() <NEW_LINE> self.is_valid_board() <NEW_LINE> b = deepcopy(self.board) <NEW_LINE> nums = set() <NEW_LINE> nums_to_remove = self.n + 1 <NEW_LINE> while len(nums) < nums_to_remove: <NEW_LINE> <INDENT> num = randint(1, self.n**2) <NEW_...
Remove numbers from generated solution and return puzzle board.
625941d84f6381625f114cad
def RandomWalk_hard(Weight, NearestNeighbor, pheromone, Option): <NEW_LINE> <INDENT> Gamma = Option['Gamma'] <NEW_LINE> N_walk = Option['NumberOfSteps'] <NEW_LINE> NumOfVisit = np.zeros(len(pheromone)) <NEW_LINE> CurrentPos = np.random.randint(len(pheromone), size=1) <NEW_LINE> NumOfVisit[CurrentPos] = NumOfVisit[Curre...
a random walk on a manifold with known intrinsic dimensionality :param Weight: a matrix containing the weight to neighbors for each data point :param NearestNeighbor: the list of neighbors for each samples :param pheromone: a vector containing the pheromone distribution :param Option: the parameters values for the ant ...
625941d8d6c5a102081442be
def load_app(frame_app): <NEW_LINE> <INDENT> self.root.change_page(frame_app.name)
Call Back: switches page to the application frame and loads the application
625941d80383005118ecf854
def _login(self): <NEW_LINE> <INDENT> payload = {'action':'query', 'format':'json', 'meta':'tokens', 'type':'login'} <NEW_LINE> r = requests.post(self.url, data=payload) <NEW_LINE> if r.status_code != 200: <NEW_LINE> <INDENT> raise Exception <NEW_LINE> <DEDENT> self.cookies = r.cookies <NEW_LINE> response = json.loads(...
Logs into Mediawiki using the URL, Username, and Password created on init. A cookiejar containing the reponse must be passed with all subsequent responses Logging in is a two step process: 1. Request a login token 2. Request a session with the token, username, and password
625941d8711fe17d825425d8
def readFrameRawData(self, frameType) : <NEW_LINE> <INDENT> if frameType == FrameType.DISTANCE_GRAYSCALE: <NEW_LINE> <INDENT> dataArray = self._comm.getDistanceGrayscale() <NEW_LINE> return dataArray[TOF_635_IMAGE_HEADER_SIZE : len(dataArray)] <NEW_LINE> <DEDENT> elif frameType == FrameType.DISTANCE_AMPLITUDE: <NEW_LIN...
To request raw data of a frame from camera. You may use readFrameRawData(frameType) only when you consider a two-step read-and-compose a Frame object, which readFrameRawData(frameType) to obtain a frame raw data, and then use FrameBuilder.composeFrame(dataArray, frameType) to create an Frame object, normally in a sepa...
625941d8293b9510aa2c3506
def test_old_connection_lost(active_client, protocol): <NEW_LINE> <INDENT> assert active_client.protocol is protocol <NEW_LINE> old_conn = object() <NEW_LINE> active_client._connection_lost(old_conn) <NEW_LINE> assert active_client.protocol is protocol
An old connection closing is a no-op
625941d885dfad0860c3b0cd
def get_scanner_status(self): <NEW_LINE> <INDENT> url_scanner_status = "http://{0}/eSCL/ScannerStatus".format(self.ip_address) <NEW_LINE> log.debug(url_scanner_status) <NEW_LINE> r = requests.get(url_scanner_status, verify=False, timeout=6) <NEW_LINE> log.debug("r.status_code == {}".format(r.status_code)) <NEW_LINE> if...
This will return the scanner status Args: Returns: ScannerStatus: NamedTuple that will contain state and AdfState Raises: requests.exceptions.HTTPError: if status code is not 200
625941d8cb5e8a47e48b7d19
def alphabet_position(letter): <NEW_LINE> <INDENT> alphabet_lower = "abcdefghijklmnopqrstuvwxyz" <NEW_LINE> alphabet_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" <NEW_LINE> position = 0 <NEW_LINE> found = False <NEW_LINE> if letter in alphabet_lower: <NEW_LINE> <INDENT> while position < len(alphabet_lower) and not found: <NEW_...
Returns a 0-based numerical position of a given letter within the alphabet based on upper or lower case.
625941d8d4950a0f3b08c5be
def test_multiple_factories_nested(self): <NEW_LINE> <INDENT> mgr1 = enginefacade.transaction_context() <NEW_LINE> mgr1.configure( connection=self.engine_uri, slave_connection=self.slave_uri ) <NEW_LINE> mgr2 = enginefacade.transaction_context() <NEW_LINE> mgr2.configure( connection=self.engine_uri, slave_connection=se...
Test that the instrumentation applied to a context class supports nested calls among multiple _TransactionContextManager objects.
625941d8a4f1c619b28b02a6
def task_test_elf_to_hex () : <NEW_LINE> <INDENT> def elf_to_hex (f, m): <NEW_LINE> <INDENT> cmd = [elfmanip,"-f","-s","0x80000000","-o","{:s}.hex".format(test_name(f, m))] <NEW_LINE> cmd += ["--only-section",".text.init",".text",".data","--"] <NEW_LINE> cmd += ["{:s}".format(f),"hex","-w",str(int(m/8))] <NEW_LINE> sub...
Converts an elf test to a hex
625941d83617ad0b5ed68168
def __ne__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, BillingPlansResponse): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return self.to_dict() != other.to_dict()
Returns true if both objects are not equal
625941d88e71fb1e9831da1a
def UpdateCombatantStates(self): <NEW_LINE> <INDENT> for combatant in self.combatants: <NEW_LINE> <INDENT> combatant.UpdateState()
Go through all the combatants and update their states.
625941d801c39578d7e750ae
def find_chapter(self, version, book, chapter_number): <NEW_LINE> <INDENT> book = self.normalize_book(book) <NEW_LINE> bk = self.find_book(version, book) <NEW_LINE> return Chapter(bk, chapter_number)
Find a chapter object in book :param version: bible version instance :param book: book instance :param chapter_number: number of chapter :return: Instance of chapter
625941d830c21e258bdfa710
def load_coo(filename): <NEW_LINE> <INDENT> raw = np.loadtxt(filename, delimiter='\t', dtype=int) <NEW_LINE> sparse = coo_matrix((raw[:,2], (raw[:,0],raw[:,1]))) <NEW_LINE> return sparse
Load a sparse coo matrix Assumes first column (dense row ids) are cells, second column (dense column ids) are genes, and third column are nonzero counts. Also assumes row and column ids are 0-indexed. Parameters ---------- filename : str file to load Returns ------- coo : coo_matrix
625941d863d6d428bbe44761
def showHelpScreen1(self): <NEW_LINE> <INDENT> self.canvas1_hs1.place(x=368, y=205) <NEW_LINE> self.button1_hs1.place(x=378, y=525) <NEW_LINE> self.button2_hs1.place(x=508, y=525)
Add the help screen1 widgets to the main gui.
625941d80fa83653e465722c
def connectSuccess(self): <NEW_LINE> <INDENT> self.setInterestZones([1, 2, 3]) <NEW_LINE> if self.haveCreateAuthority(): <NEW_LINE> <INDENT> self.gotCreateReady() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.accept(self.uniqueName('createReady'), self.gotCreateReady)
Successfully connected. But we still can't really do anything until we've got the doID range.
625941d8596a897236089d30
@api_view(['GET']) <NEW_LINE> @authentication_classes((TokenAuthentication,)) <NEW_LINE> @exceptions_to_http_status <NEW_LINE> def get_warning_points(request): <NEW_LINE> <INDENT> return generate_warning_points(request)
Controller that will returned generated warning points in json format
625941d8adb09d7d5db6ca00
def shuffle(self): <NEW_LINE> <INDENT> shuffle(self.cards)
This method shuffles the deck. :return: Shuffles the deck.
625941d807f4c71912b116f6
def main(): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> screen = pygame.display.set_mode((1000,1000)) <NEW_LINE> pygame.display.set_caption('Boat simulator') <NEW_LINE> background = pygame.Surface(screen.get_size()) <NEW_LINE> background = background.convert() <NEW_LINE> background.fill((50, 50, 250)) <NEW_LINE> if py...
this function is called when the program starts. it initializes everything it needs, then runs in a loop until the function returns.
625941d8b830903b967e9b7b
def sigmoid_f(w,X): <NEW_LINE> <INDENT> n_samples = X.shape[0] <NEW_LINE> A = np.zeros([n_samples, ]) <NEW_LINE> for i in range(n_samples): <NEW_LINE> <INDENT> A[i] = 1 / (1 + np.exp(-np.inner(w, X[i,:]))) <NEW_LINE> <DEDENT> return A
Compute sigmoid function
625941d8cc40096d61595bc2
def test_get_board_topn_scores(self): <NEW_LINE> <INDENT> with self.app.app_context(): <NEW_LINE> <INDENT> game = models.Game.first_or_create('nunu') <NEW_LINE> game2 = models.Game.first_or_create('nunu2') <NEW_LINE> mode1_board_game2 = models.Board.first_or_create('mode1', game) <NEW_LINE> mode1_board = models.Board.f...
Validate the listing of top n players in a board
625941d83eb6a72ae02ec754
def unit_time_vector (): <NEW_LINE> <INDENT> return array([1,0,0,0])
Returns the unit vector (1,0,0,0) along the time axis.
625941d857b8e32f5248370e
def get_area_of_triangle(v): <NEW_LINE> <INDENT> matrix = np.ones((3, 3)) <NEW_LINE> matrix[0] = v[np.array((0, 2, 4))] <NEW_LINE> matrix[1] = v[np.array((1, 3, 5))] <NEW_LINE> return 0.5 * np.linalg.det(matrix)
Returns the area of a triangle. Computed via determinant. Given that the variables are floats between 0 and 1, the max area is 0.5 :param v: v = (x1,y2,x2,y2,x3,y3) :return:
625941d84d74a7450ccd4436
def result_store(domain: str): <NEW_LINE> <INDENT> domain_name = urlparse(domain).netloc <NEW_LINE> with open(f"{domain_name}_internal_links.txt", "w") as int_file: <NEW_LINE> <INDENT> for internal_link in internal_urls: <NEW_LINE> <INDENT> print(internal_link.strip(), file=int_file) <NEW_LINE> <DEDENT> <DEDENT> with o...
Save the found link to a file.
625941d8ec188e330fd5aa0d
def copy_test_to(from_file,to_file): <NEW_LINE> <INDENT> F_from_file = open(from_file,"r") <NEW_LINE> from_file_lines = F_from_file.read().split('\n') <NEW_LINE> F_from_file.close() <NEW_LINE> F_to_file = open(to_file,"w") <NEW_LINE> to_file_root = os.path.split(to_file)[0] <NEW_LINE> for line in from_file_lines: <NEW_...
Reads in test ups file at from_file and writes to to_file while replacing absolute references to prescribed deformation files with relative ones. Also copys deformation file to same root folder.
625941d8cdde0d52a9e532a7
def __init__(self, context, renderer, name='run', description=DESC_SYNC_RUN, method=None): <NEW_LINE> <INDENT> super(RunSyncRepositoryCommand, self).__init__(name, description, method, context, renderer)
:type renderer: pulp.client.commands.repo.sync_publish.StatusRenderer
625941d84428ac0f6e5baa65
def PlotSurvival(complete): <NEW_LINE> <INDENT> thinkplot.PrePlot(3, rows=2) <NEW_LINE> cdf = thinkbayes2.Cdf(complete, label='cdf') <NEW_LINE> sf = MakeSurvivalFromCdf(cdf, label='survival') <NEW_LINE> print(cdf[13]) <NEW_LINE> print(sf[13]) <NEW_LINE> thinkplot.Plot(sf) <NEW_LINE> thinkplot.Cdf(cdf, alpha=0.2) <NEW_L...
Plots survival and hazard curves. complete: list of complete lifetimes
625941d8be7bc26dc91cd86e
def generateUniqueName (): <NEW_LINE> <INDENT> return datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
Genere un nom de fichier unique à partir de la date et heure courante
625941d8e76e3b2f99f3aa7a
def get_data(self): <NEW_LINE> <INDENT> self._groups.extend(self._values.keys()) <NEW_LINE> for i, val in enumerate(self._values.keys()): <NEW_LINE> <INDENT> self.set_and_get("", val, self._values[val]) <NEW_LINE> hist, edges = np.histogram( np.array(self._data[val]), density=self.density, bins=self.bins ) <NEW_LINE> s...
Take the Histogram data from the input **value. It calculates the chart properties accordingly. Then build a dict containing references to all the calculated points to be used by the quad and line glyphs inside the ``draw`` method.
625941d8004d5f362079a5a4
def extractWithoutOrder(query, choices, processor=default_processor, scorer =default_scorer, score_cutoff=0): <NEW_LINE> <INDENT> def no_process(x): <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> if choices is not None or len(choices) == 0: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <...
Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a generator of tuples containing the match and its score. If a dictionary is used, also returns the key for each match. Arguments: query: An object representing the thing we want to find. cho...
625941d816aa5153ce3626ea
def get_status(self, element_id): <NEW_LINE> <INDENT> element_status_d = self.collection.status(element_id) <NEW_LINE> if not element_status_d: <NEW_LINE> <INDENT> self.logger.debug( "Failed to get element %s status" % element_id ) <NEW_LINE> return "" <NEW_LINE> <DEDENT> return element_status_d["status"]
Get element status :param element_id: element id :type element_id: str :return: element status :rtype: str
625941d89c8ee82313fbb9e8
def has_ip(self, ipaddr): <NEW_LINE> <INDENT> return ipaddr in self._ips
Determine if this context has the given ip address. NOTE: This does not update when config changes!
625941d8004d5f362079a5a5
def _mesh(self): <NEW_LINE> <INDENT> x = np.array([0.0, 1.0]) <NEW_LINE> if self.spacing == 'uniform': <NEW_LINE> <INDENT> y = self._uniform_y(self._central_N()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> y = self._proportional_y() <NEW_LINE> <DEDENT> if self._use_auto_colorbar_locator(): <NEW_LINE> <INDENT> y = sel...
Return X,Y, the coordinate arrays for the colorbar pcolormesh. These are suitable for a vertical colorbar; swapping and transposition for a horizontal colorbar are done outside this function.
625941d84a966d76dd551283
def auto_register_inlines(admin_site, metadata_class): <NEW_LINE> <INDENT> inline_class = get_inline(metadata_class) <NEW_LINE> for model, admin_class_instance in admin_site._registry.items(): <NEW_LINE> <INDENT> _monkey_inline(model, admin_class_instance, metadata_class, inline_class, admin_site) <NEW_LINE> <DEDENT> a...
This is a questionable function that automatically adds our metadata inline to all relevant models in the site.
625941d85166f23b2e1a53cb
def rent_in(dict_inventory, number): <NEW_LINE> <INDENT> dict_inventory[number]['quantity'] += 1 <NEW_LINE> return dict_inventory
{}, int ->
625941d826068e7796caef55
def get_animation(self, axes=None, slider=0, startframe=0, endframe=None, stepframe=1, **kwargs): <NEW_LINE> <INDENT> if not axes: <NEW_LINE> <INDENT> axes = plt.gca() <NEW_LINE> <DEDENT> anim_fig = axes.get_figure() <NEW_LINE> if endframe is None: <NEW_LINE> <INDENT> endframe = self.slider_ranges[slider][1] <NEW_LINE>...
Return a matplotlib.animation.FuncAnimation instance for the selected slider. This will allow easy saving of the animation to a file. Parameters ---------- slider: int The slider to animate along startframe: int The frame to start the animation endframe: int The frame to end the animation stepframe: i...
625941d8cad5886f8bd2724b
def delete_photo(self, contact_entry_or_url, auth_token=None, **kwargs): <NEW_LINE> <INDENT> uri = None <NEW_LINE> ifmatch_header = None <NEW_LINE> if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry): <NEW_LINE> <INDENT> photo_link = contact_entry_or_url.GetPhotoLink() <NEW_LINE> if photo_link.etag: <...
Delete the contact's profile photo. Args: contact_entry_or_url: a gdata.contacts.ContactEntry object or a string containing the photo link's URL.
625941d8f8510a7c17cf9970
def _feature_file(self, image): <NEW_LINE> <INDENT> return os.path.join(self._feature_path(), image + '.npz')
Return path of feature file for specified image :param image: Image name, with extension (i.e. 123.jpg)
625941d8e64d504609d74ab2