code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
@bot.command('convert') <NEW_LINE> def convert(bot, channel, sender, args): <NEW_LINE> <INDENT> amount = float(args[0]) <NEW_LINE> unit_from = args[1] <NEW_LINE> unit_to = args[2] <NEW_LINE> try: <NEW_LINE> <INDENT> ureg = pint.UnitRegistry() <NEW_LINE> unit = ureg.Quantity(amount, unit_from) <NEW_LINE> to = unit.to(un...
Converts units from one measurement to another. ie: {bot.trigger}convert 100 cm inches
625941c5a8ecb033257d30df
def check_state(dirs): <NEW_LINE> <INDENT> reqids = [] <NEW_LINE> for dir in dirs: <NEW_LINE> <INDENT> reqids.extend(get_requests_for_dir(dir)) <NEW_LINE> <DEDENT> return reqids
Given a set of directories and nicknames verify that we are no longer tracking certificates. dirs is a list of directories to test for. We will return a tuple of nicknames for any tracked certificates found. This can only check for NSS-based certificates.
625941c507d97122c417889a
def reset_vars(self): <NEW_LINE> <INDENT> self.conf = {} <NEW_LINE> self.keys = []
reset conf retult
625941c563d6d428bbe44501
def fail(state, msg="fail"): <NEW_LINE> <INDENT> state.report(msg) <NEW_LINE> return state
Always fails the SCT, with an optional msg. This function takes a single argument, ``msg``, that is the feedback given to the student. Note that this would be a terrible idea for grading submissions, but may be useful while writing SCTs. For example, failing a test will highlight the code as if the previous test/check...
625941c5d7e4931a7ee9df2f
def maxSubArray(self, nums): <NEW_LINE> <INDENT> sumNow = 0 <NEW_LINE> maxSum = 0 <NEW_LINE> for num in nums: <NEW_LINE> <INDENT> sumNow += num <NEW_LINE> if sumNow > maxSum: <NEW_LINE> <INDENT> maxSum = sumNow <NEW_LINE> <DEDENT> if sumNow < 0: <NEW_LINE> <INDENT> sumNow = 0 <NEW_LINE> <DEDENT> <DEDENT> if maxSum == 0...
:type nums: List[int] :rtype: int
625941c5167d2b6e31218ba8
def _safe_getdoc(obj: Any) -> str: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> doc = inspect.getdoc(obj) or "" <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> warnings.warn(f"inspect.getdoc({obj!r}) raised an exception: {e!r}") <NEW_LINE> return "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return do...
Like `inspect.getdoc()`, but never raises. Always returns a stripped string.
625941c55f7d997b87174aa8
def search(self, query, single=False): <NEW_LINE> <INDENT> results = self.execute(query) <NEW_LINE> if not results: <NEW_LINE> <INDENT> raise ResourceNotFound('Query returned 0 results') <NEW_LINE> <DEDENT> if single: <NEW_LINE> <INDENT> return results[0] <NEW_LINE> <DEDENT> return results
Execute a search query. This method executes `query`, but expects one or more results to be returned. Args: :param query: query to execute :param single: boolean flag to determine if more than one record should be returned Raises: ResourceNotFound: if no results are found
625941c5d99f1b3c44c675a2
def get_cached_token(self): <NEW_LINE> <INDENT> token_info = None <NEW_LINE> try: <NEW_LINE> <INDENT> f = open(self.cache_path) <NEW_LINE> token_info_string = f.read() <NEW_LINE> f.close() <NEW_LINE> token_info = json.loads(token_info_string) <NEW_LINE> if "scope" not in token_info or not self._is_scope_subset( self.sc...
Gets a cached auth token
625941c5b830903b967e991e
def drawcounts(counts,num): <NEW_LINE> <INDENT> x_aixs = [] <NEW_LINE> y_aixs = [] <NEW_LINE> c_order = sorted(counts.items(),key = lambda x:x[1],reverse = True) <NEW_LINE> for c in c_order[:num]: <NEW_LINE> <INDENT> x_aixs.append(c[0]) <NEW_LINE> y_aixs.append(c[1]) <NEW_LINE> <DEDENT> matplotlib.rcParams['font.sans-s...
根据词频绘制统计表 return:none
625941c50a366e3fb873e82b
def blog_post_detail(request, slug, year=None, month=None, day=None, template="blog/blog_post_detail.html", extra_context=None): <NEW_LINE> <INDENT> blog_posts = BlogPost.objects.published( for_user=request.user).select_related() <NEW_LINE> blog_post = get_object_or_404(blog_posts, slug=slug) <NEW_LINE> blog_post.incre...
. Custom templates are checked for using the name ``blog/blog_post_detail_XXX.html`` where ``XXX`` is the blog posts's slug.
625941c573bcbd0ca4b2c088
def _get_value_and_line_offset(self, key, values): <NEW_LINE> <INDENT> values_list = self._construct_values_list(values) <NEW_LINE> current_value_list_index = 0 <NEW_LINE> output = [] <NEW_LINE> lines_modified = False <NEW_LINE> first_line_regex = re.compile(r'^\s*{}[ :=]+{}'.format( key, values_list[current_value_list...
Returns the index of the location of key, value pair in lines. :type key: str :param key: key, in config file. :type values: str :param values: values for key, in config file. This is plural, because you can have multiple values per key. Eg. >>> key = ... value1 ... value2 :type lines: list ...
625941c55fcc89381b1e16d0
def _set_advertise_inactive_routes(self, v, load=False): <NEW_LINE> <INDENT> if hasattr(v, "_utype"): <NEW_LINE> <INDENT> v = v._utype(v) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> t = YANGDynClass( v, base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="advertise-inactive-routes", parent=self, path_hel...
Setter method for advertise_inactive_routes, mapped from YANG variable /network_instances/network_instance/protocols/protocol/bgp/global/afi_safis/afi_safi/route_selection_options/config/advertise_inactive_routes (boolean) If this variable is read-only (config: false) in the source YANG file, then _set_adve...
625941c545492302aab5e2d4
def flipCard(self): <NEW_LINE> <INDENT> self.hidden = not self.hidden
Cacher/Monter la carte.
625941c5b545ff76a8913e28
def model_to_dict(model): <NEW_LINE> <INDENT> def convert_datetime(value): <NEW_LINE> <INDENT> return ( ( value.strftime("%Y-%m-%d %H:%M:%S") if hasattr(value, "strftime") else value ) if value else "" ) <NEW_LINE> <DEDENT> data = {} <NEW_LINE> for col in model.__table__.columns: <NEW_LINE> <INDENT> value = getattr(mod...
model to dict
625941c5be383301e01b549a
def __SVNDelProp(self): <NEW_LINE> <INDENT> names = [] <NEW_LINE> for itm in self.browser.getSelectedItems(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> names.append(unicode(itm.fileName())) <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> names.append(unicode(itm.dirName())) <NEW_LINE> <DEDENT> <DEDENT...
Private slot called by the context menu to delete a subversion property of a file.
625941c5a17c0f6771cbe064
def test_can_send_signals(handler, nonstop_signal): <NEW_LINE> <INDENT> triggered = {"value": False} <NEW_LINE> def flip_bit(signum, frame): <NEW_LINE> <INDENT> triggered["value"] = True <NEW_LINE> <DEDENT> signal.signal(nonstop_signal, flip_bit) <NEW_LINE> handler.send(nonstop_signal) <NEW_LINE> assert triggered["valu...
Test that the manager can send signals to a process.
625941c5d486a94d0b98e157
def send_files(client, files): <NEW_LINE> <INDENT> sftp = SFTPClient.from_transport(client.get_transport()) <NEW_LINE> for conf in files: <NEW_LINE> <INDENT> sftp.put(conf['local'], conf['remote']) <NEW_LINE> <DEDENT> sftp.close()
Send a list of files to the remote, formatted as a list of dicts, with local and remote entries.
625941c592d797404e30419b
def listen(): <NEW_LINE> <INDENT> keyboard.hook(print_key) <NEW_LINE> keyboard.wait('esc')
Main function to call, will hook the keyboard
625941c57cff6e4e81117998
def post(self, request): <NEW_LINE> <INDENT> context = { 'signed_in_volunteers': VolunteerLog.logged_in_volunteers_objects.all(), 'log_sign_in_form': LogSignInForm } <NEW_LINE> if request.method == 'POST': <NEW_LINE> <INDENT> log_sign_out_form = LogSignOutForm(request.POST) <NEW_LINE> if log_sign_out_form.is_valid(): <...
Sign in and out forms each have a prefix. Checks which form is posted
625941c58a43f66fc4b54079
def partition(self, head, x): <NEW_LINE> <INDENT> lessList = ListNode(0) <NEW_LINE> greaterList = ListNode(0) <NEW_LINE> lessPointer = lessList <NEW_LINE> greaterPointer = greaterList <NEW_LINE> pointer = head <NEW_LINE> while pointer != None: <NEW_LINE> <INDENT> if pointer.val < x: <NEW_LINE> <INDENT> lessPointer.next...
:type head: ListNode :type x: int :rtype: ListNode
625941c591f36d47f21ac503
def __init__(self): <NEW_LINE> <INDENT> self._directory_name = None <NEW_LINE> self.dir_fil = [] <NEW_LINE> self.file_list = [] <NEW_LINE> self.x_lists = [] <NEW_LINE> self.y_lists = []
This method initializes the class Parameters ---------- self Returns ------- None
625941c54e4d5625662d43ec
def foo_fun(): <NEW_LINE> <INDENT> called[0] = True
Foo function
625941c5ac7a0e7691ed40e1
def is_empty(self): <NEW_LINE> <INDENT> return self.items.head is None
:returns: True if the LinkedList is empty anf False if it isn't
625941c5a219f33f3462897e
def get_latest_bar_value(self, symbol, val_type): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> bars_list = self.get_latest_bar(symbol) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> print("这个 symbol 在历史数据库中不可用") <NEW_LINE> raise <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return bars_list[-1][val_type]
返回最新 bar 的一条信息
625941c5498bea3a759b9ac2
def __init__(self): <NEW_LINE> <INDENT> pass
void NET.__init__()
625941c53617ad0b5ed67f0a
def _f1_score(pred, answers): <NEW_LINE> <INDENT> def _score(g_tokens, a_tokens): <NEW_LINE> <INDENT> common = Counter(g_tokens) & Counter(a_tokens) <NEW_LINE> num_same = sum(common.values()) <NEW_LINE> if num_same == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> precision = 1. * num_same / len(g_tokens) <NEW_LIN...
Compute the F1 score.
625941c5851cf427c661a522
def testDefaultMappingWithClass(self): <NEW_LINE> <INDENT> mapping = service_handlers.service_mapping([MyService]) <NEW_LINE> mapped_services = mapping[2:-1] <NEW_LINE> self.assertEquals(1, len(mapped_services)) <NEW_LINE> path, factory = mapped_services[0] <NEW_LINE> self.assertEquals( '/test_package/MyService' + serv...
Test setting path just from the class. Path of the mapping will be the fully qualified ProtoRPC service name with '.' replaced with '/'. For example: com.nowhere.service.TheService -> /com/nowhere/service/TheService
625941c56aa9bd52df036db5
def _get_mf_gp_options(tune_noise): <NEW_LINE> <INDENT> options = load_options(mf_gp.all_mf_gp_args) <NEW_LINE> options.noise_var_type = 'tune' if tune_noise else options.noise_var_type <NEW_LINE> return options
Gets the options for the dataset.
625941c5851cf427c661a523
def pitch_shift(x, shift, w, h, win_fn, n_iters): <NEW_LINE> <INDENT> S = np.abs(stft(x, w, h, win_fn)) <NEW_LINE> N = S.shape[0] <NEW_LINE> plt.figure(figsize=(18, 6)) <NEW_LINE> plt.subplot(121) <NEW_LINE> plt.imshow(np.log10(np.abs(S)), aspect='auto', cmap='magma_r') <NEW_LINE> plt.gca().invert_yaxis() <NEW_LINE> pl...
Pitch shift audio without changing the timing by taking its absolute value STFT and warping it nonlinearly, then performing Griffin-Lim phase retrieval Parameters ---------- x: ndarray(N) Original audio samples shift: int Number of halfsteps by which to shift audio w: int Window length h: int Hop leng...
625941c58a349b6b435e8186
def __init__(self, inputs: TNCMGroupInputs, outputs: TOutputs, conv_layers_params: MultipleLayersParams, model_seed: Optional[int] = 321, image_size: Tuple[int, int, int] = (24, 24, 3), name: str = "TA Model"): <NEW_LINE> <INDENT> super().__init__(name=name, inputs=inputs, outputs=outputs) <NEW_LINE> self._num_layers =...
Create the multilayer topology of configuration: N conv layers Args: conv_layers_params: parameters for each layer (or default ones) model_seed: seed of the topology image_size: small resolution by default
625941c5442bda511e8be42c
def calculate(model): <NEW_LINE> <INDENT> boundaries = model['boundaries'] <NEW_LINE> nodes = model['nodes'] <NEW_LINE> unfixed = unfixed_coos(keys(nodes), values(boundaries)) <NEW_LINE> coo_indexes = index_dict(unfixed) <NEW_LINE> section_keys = 'Ax', 'Iz', 'Iy', 'Ay', 'Az', 'theta', 'J' <NEW_LINE> sections = calculat...
Calculate displacements of nodes in frame structure. [TODO] detailed discription. 'nodes' : { id(hashable): { x:Real, y:Real, z:Real } } 'lines' : { id(hashable): { n1:id, n2:id, EA:Real } } 'boundaries' : { id(hashable): { node:id, x:Real or Bool, y:Real or Bool, z:Real or Bool, rx:Real or Bool, ry:Real or Bool, r...
625941c5b57a9660fec33895
def __str__(self): <NEW_LINE> <INDENT> return self.name
Cette méthode que nous définirons dans tous les modèles nous permettra de reconnaître facilement les différents objets que nous traiterons plus tard et dans l'administration
625941c55fdd1c0f98dc0245
def create_conversation(project_id, conversation_profile_id): <NEW_LINE> <INDENT> client = dialogflow.ConversationsClient() <NEW_LINE> conversation_profile_client = dialogflow.ConversationProfilesClient() <NEW_LINE> project_path = client.common_project_path(project_id) <NEW_LINE> conversation_profile_path = conversatio...
Creates a conversation with given values Args: project_id: The GCP project linked with the conversation. conversation_profile_id: The conversation profile id used to create conversation.
625941c5097d151d1a222e6e
def release_network_resources(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.connection_reader.terminate() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> self.connection_writer.terminate() <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <...
Close the active connection to the server, if any. Note: this private method should be actually "protected" for the ServerSession states, but Python doesn't have such a protection level.
625941c54428ac0f6e5ba804
def spsp(n, base, s=None, t=None): <NEW_LINE> <INDENT> if not s or not t: <NEW_LINE> <INDENT> s, t = arith1.vp(n-1, 2) <NEW_LINE> <DEDENT> z = pow(base, t, n) <NEW_LINE> if z != 1 and z != n-1: <NEW_LINE> <INDENT> j = 0 <NEW_LINE> while j < s: <NEW_LINE> <INDENT> j += 1 <NEW_LINE> z = pow(z, 2, n) <NEW_LINE> if z == n-...
Strong Pseudo-Prime test. Optional third and fourth argument s and t are the numbers such that n-1 = 2**s * t and t is odd.
625941c5ad47b63b2c509f92
def countdigit(st): <NEW_LINE> <INDENT> return len([c for c in st if c.isdigit()])
This function count the number of digits inside the input string >>> countdigit("hello") 0 >>> countdigit("hel3333lo") 4 >>> countdigit("hel3333lo666") 7 >>> countdigit("222hel3333lo666") 11 >>> c = countdigit("abc1ab2c3") >>> print c 3 >>> c = countd...
625941c54d74a7450ccd41d6
def forward(self, input, sentence, context): <NEW_LINE> <INDENT> idf, ih, iw = input.size(1), input.size(2), input.size(3) <NEW_LINE> queryL = ih * iw <NEW_LINE> batch_size, sourceL = context.size(0), context.size(2) <NEW_LINE> target = input.view(batch_size, -1, queryL) <NEW_LINE> targetT = torch.transpose(target, 1, ...
input: batch x idf x ih x iw (queryL=ihxiw) context: batch x cdf x sourceL
625941c5377c676e912721bc
def test_required_xor_default(self): <NEW_LINE> <INDENT> no_required_or_default = [] <NEW_LINE> required_and_default = [] <NEW_LINE> for resource, domain in self.app.config['DOMAIN'].items(): <NEW_LINE> <INDENT> for field, definition in domain['schema'].items(): <NEW_LINE> <INDENT> if definition.get('readonly'): <NEW_L...
Fields must be either required xor have a default value. Per default, this is not necessary, as fields can simply be 'missing'. However, this can cause confusion and problems: Using PATCH, fields *cannot* be removed. As a result, missing fields can result in unreachable state as soon as item is created. To avoid head...
625941c50383005118ecf5f6
def push(self, text): <NEW_LINE> <INDENT> text = '' if text is None else text.strip() <NEW_LINE> if not text: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> index = self.index_of(text) <NEW_LINE> old_value = list(self._items) <NEW_LINE> if index == -1: <NEW_LINE> <INDENT> self._items.insert(0, text) <NEW_LINE> del self...
Adds the specified string to the front of the list, or moves it to the front if it's already in the list. :type text: str - the string to add
625941c5d18da76e235324e7
def get_country_code(country_name): <NEW_LINE> <INDENT> for code, name in COUNTRIES.items(): <NEW_LINE> <INDENT> if name == country_name: <NEW_LINE> <INDENT> return code <NEW_LINE> <DEDENT> <DEDENT> return None
根据国家名字返回国家的两位编码
625941c556b00c62f0f1466b
def getWindowsList(self): <NEW_LINE> <INDENT> regexp = re.compile(constants.REGEX_LIST_APP_COMMAND) <NEW_LINE> terminalResponse = self.connection.performCommand(constants.LIST_APP_COMMAND) <NEW_LINE> print(terminalResponse) <NEW_LINE> matches = regexp.findall(terminalResponse) <NEW_LINE> toReturn = [] <NEW_LINE> for ma...
Returns the list of opened windows in the connected host
625941c566673b3332b920a3
def run(self): <NEW_LINE> <INDENT> raise IOError("This shows an example error")
docstring
625941c556ac1b37e62641e5
def get_right_child(self, k, index): <NEW_LINE> <INDENT> c = 0 <NEW_LINE> if (k == self.NOT_FOUND): <NEW_LINE> <INDENT> return self.NOT_FOUND <NEW_LINE> <DEDENT> for i in range(self.tree.count(),k,-1): <NEW_LINE> <INDENT> if (self.tree.get_head(i) == k): <NEW_LINE> <INDENT> c += 1 <NEW_LINE> if (c == index): <NEW_LINE>...
Get the right most node, whose head is the kth token; index = 1, first rightmost index = 2, second rightmost
625941c5293b9510aa2c32aa
def get_slidelist_from_uids(uids, process_all=True): <NEW_LINE> <INDENT> slide_list_out = [] <NEW_LINE> labels = [] <NEW_LINE> for uid in uids: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> slide_list = uid2slide[uid] <NEW_LINE> if len(slide_list) > 0: <NEW_LINE> <INDENT> if process_all: <NEW_LINE> <INDENT> slide_list_o...
Translate the numpy name into a path to some slides Each case can have multiple slides, so decide what to do with them
625941c571ff763f4b54969c
def __init__(self, quete): <NEW_LINE> <INDENT> BaseObj.__init__(self) <NEW_LINE> self.type = "etape" <NEW_LINE> self.quete = quete <NEW_LINE> self.niveau = () <NEW_LINE> self.titre = "non renseigné" <NEW_LINE> self.description = Description("", self) <NEW_LINE> self.test = None <NEW_LINE> self._construire()
Constructeur de l'étape.
625941c5b830903b967e991f
def after_class(home=None, **kwargs): <NEW_LINE> <INDENT> kwargs.update({'run_after_class':True}) <NEW_LINE> return test(home=home, **kwargs)
Like @test but indicates this should run after other class methods. All of the arguments sent to @test work with this decorator as well. This will be skipped if a class method test fails; set always_run if that is not desired. See `issue #5 <https://github.com/rackspace/python-proboscis/issues/5>`__.
625941c5e1aae11d1e749cc9
def findsource(object): <NEW_LINE> <INDENT> file = getsourcefile(object) <NEW_LINE> if file: <NEW_LINE> <INDENT> linecache.checkcache(file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> file = getfile(object) <NEW_LINE> if not (file.startswith('<') and file.endswith('>')): <NEW_LINE> <INDENT> raise OSError('source code...
Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An OSError is raised if the source code ca...
625941c599cbb53fe6792bf9
def GetPointer(self): <NEW_LINE> <INDENT> return _itkDirectedHausdorffDistanceImageFilterPython.itkDirectedHausdorffDistanceImageFilterIUL3IUL3_GetPointer(self)
GetPointer(self) -> itkDirectedHausdorffDistanceImageFilterIUL3IUL3
625941c5090684286d50ecf7
def showpreferences(): <NEW_LINE> <INDENT> print() <NEW_LINE> for property,value in middleware.preference.__dict__.items(): <NEW_LINE> <INDENT> if property.startswith('_') and not callable(property): continue <NEW_LINE> print('\t{0}: {1}'.format(property, value)) <NEW_LINE> <DEDENT> print()
Show user defined preferences
625941c5627d3e7fe0d68e62
def save_figure(self,event=None): <NEW_LINE> <INDENT> self.plotpanel.save_figure(event=event)
save figure image to file
625941c5cc0a2c11143dcea3
def testManualOffAxis(self): <NEW_LINE> <INDENT> targ = Target('OFF_AXIS', 42.333, -111.6778, 'W', 'SEMICIRCLE','BROWN', 'F', 'YELLOW', None, False) <NEW_LINE> self.verifyGoodTargetPost(targ)
submit manual off_axis target
625941c5d7e4931a7ee9df30
def __init__(self, room_filters=[], node_filters=[], house_filters=[]): <NEW_LINE> <INDENT> self.room_filters = room_filters <NEW_LINE> self.node_filters = node_filters <NEW_LINE> self.house_filters = house_filters
Parameters ---------- house_filters (list[house_filter]): where a house_filter takes a House as input and returns whether the House should be included or not room_filters (list[room_filter]): see house.House.filter_rooms node_filters (list[node_filter]): see house.Room.filter_nodes
625941c5099cdd3c635f0c6e
def __lt__(self, other): <NEW_LINE> <INDENT> return self.__idFourmi < other.get_id
For sorting the ants via the identifier :param other: :return:
625941c5be8e80087fb20c58
def testcode_data(fname): <NEW_LINE> <INDENT> test_data = {} <NEW_LINE> for (key, dat) in extract_test_data(fname, False).items(): <NEW_LINE> <INDENT> dat_dict = dat.to_dict('list') <NEW_LINE> for dat_key, dat_entry in dat_dict.items(): <NEW_LINE> <INDENT> if dat_key in test_data: <NEW_LINE> <INDENT> test_data[dat_key]...
Extract test data in the format required by testcode2. Parameters ---------- fname : string filename containing HANDE calculation output. Returns ------- output : dict A dictionary consisting of key, value pairs of a data name and list of associated values. This is essentially the output from ``extr...
625941c5d18da76e235324e8
def forwardoutpre(bot, event): <NEW_LINE> <INDENT> if event.how == "background": return False <NEW_LINE> chan = str(event.channel).lower() <NEW_LINE> if not chan: return <NEW_LINE> logging.debug("forward - pre - %s" % event.channel) <NEW_LINE> if chan in forward.data.channels and not event.isremote() and not event.forw...
preconditon to check if forward callbacks is to be fired.
625941c5b7558d58953c4f2a
def generate_vgg16(): <NEW_LINE> <INDENT> input_shape = (224, 224, 3) <NEW_LINE> model = Sequential([ Conv2D(64, (3, 3), input_shape=input_shape, padding='same', activation='relu'), Conv2D(64, (3, 3), padding='same', activation='relu'), MaxPooling2D(pool_size=(2,2),strides=(2,2),), MaxPooling2D(pool_size=(2,2),strides=...
搭建VGG16网络结构 :return: VGG16网络
625941c5adb09d7d5db6c7a3
def set_data(self, data: PseudoData): <NEW_LINE> <INDENT> self.image = data.image <NEW_LINE> self.target: MultiOutput = data.target
Unpack input _data from the dataloader and perform necessary pre-processing steps.
625941c5de87d2750b85fda4
def space_heat_effy(self, _Q_space): <NEW_LINE> <INDENT> space_mult = 1 / (self.space_heat_charging_factor * self.distribution_loss_factor) <NEW_LINE> return 100 * space_mult
Calculate the space heating efficiency. .. note: Requires that apply_4c3 has been run on this system in order to set space_heat_charging_factor This happens when we apply_table_4e() TODO: avoid this requirement by applying the table to the system on initialisation Efficiencies work a bit differently for commun...
625941c529b78933be1e56c1
def compose(scripts, name='main', description=None, prog=None, version=None): <NEW_LINE> <INDENT> assert len(scripts) >= 1, scripts <NEW_LINE> parentparser = argparse.ArgumentParser( description=description, add_help=False) <NEW_LINE> parentparser.add_argument( '--version', '-v', action='version', version=version) <NEW...
Collects together different scripts and builds a single script dispatching to the subparsers depending on the first argument, i.e. the name of the subparser to invoke. :param scripts: a list of script instances :param name: the name of the composed parser :param description: description of the composed parser :param p...
625941c5c432627299f04c58
def test_rejected_raises(self, caplog): <NEW_LINE> <INDENT> def handle(event): <NEW_LINE> <INDENT> raise NotImplementedError("Exception description") <NEW_LINE> <DEDENT> self.ae = ae = AE() <NEW_LINE> ae.require_called_aet = True <NEW_LINE> ae.add_supported_context(Verification) <NEW_LINE> ae.add_requested_context(Veri...
Test the handler for EVT_REJECTED raising exception.
625941c550812a4eaa59c336
def get_random_exit_router(self): <NEW_LINE> <INDENT> exit_relays = [] <NEW_LINE> for onion_router in self._parsed_consensus: <NEW_LINE> <INDENT> if "exit" in onion_router.flags: <NEW_LINE> <INDENT> exit_relays.append(onion_router) <NEW_LINE> <DEDENT> <DEDENT> return random.choice(exit_relays)
:return: A random exit router. :rtype: OnionRouter
625941c5f7d966606f6aa016
def getScheduleURL(self, forPrinting = False): <NEW_LINE> <INDENT> if not self.courses: <NEW_LINE> <INDENT> raise ScheduleError("no course list provided") <NEW_LINE> <DEDENT> if not self.term: <NEW_LINE> <INDENT> raise ScheduleError("no term provided") <NEW_LINE> <DEDENT> return ((BASE_URL_PRINT if forPrinting else BAS...
Creates a URL that searches for the specified courses at the given term using the UCSD Schedule of Classes. This will return an empty string if the list of desired courses is empty. :param self: the schedule object :param forPrinting: whether or not the print URL is needed :raises: ScheduleError :returns: the URL as a...
625941c52eb69b55b151c8c0
def go_reverse(self, speed, desired_angle,max_speed=127,accuracy=0.8): <NEW_LINE> <INDENT> k_p = 2.9 <NEW_LINE> k_i = 0.01 <NEW_LINE> k_d = 0.05 <NEW_LINE> self.drive_at_angle(max_speed, -1*abs(speed), desired_angle, k_p, k_d, k_i, accuracy)
#:WARNING ONLY WORKS INSIDE A LOOP!calling it only once does not drive straight #:param speed: the forward speed you want Zumi to drive at. Should only input a positive number #:param duration: number of seconds you want Zumi to try to drive forward #:param desired_angle: the desired angle #:return: nothing # uses driv...
625941c53539df3088e2e35e
@post('/bundles/<uuid:re:%s>/netcurl/<port:int>/<path:re:.*>' % spec_util.UUID_STR, name='netcurl_bundle') <NEW_LINE> @put('/bundles/<uuid:re:%s>/netcurl/<port:int>/<path:re:.*>' % spec_util.UUID_STR, name='netcurl_bundle') <NEW_LINE> @delete('/bundles/<uuid:re:%s>/netcurl/<port:int>/<path:re:.*>' % spec_util.UUID_STR,...
Forward an HTTP request into the specified port of the running bundle with uuid. Return the HTTP response from this bundle.
625941c521bff66bcd684967
def estimate_arpu(region, timestep, global_parameters, country_parameters): <NEW_LINE> <INDENT> timestep = timestep - 2020 <NEW_LINE> if region['mean_luminosity_km2'] > country_parameters['luminosity']['high']: <NEW_LINE> <INDENT> arpu = country_parameters['arpu']['high'] <NEW_LINE> return discount_arpu(arpu, timestep,...
Allocate consumption category given a specific luminosity.
625941c597e22403b379cfad
def __eq__(self, other: 'PdfHeadingDetection') -> bool: <NEW_LINE> <INDENT> if not isinstance(other, self.__class__): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Return `true` when self and other are equal, false otherwise.
625941c5507cdc57c6306ceb
def subclass_of(*args: Type): <NEW_LINE> <INDENT> return SubclassOf(frozenset(args))
A validator for an :class:`Attribute` to verify that the passed value is a subclass (in the contravariant sense) of some class in the whitelist.. :param args: whitelist of types :return: validator instance :raises ValueError: if no whitelist specified :raises TypeError: if not all of whitelist are types
625941c58e71fb1e9831d7bd
def compute_hessian(self, x): <NEW_LINE> <INDENT> G = empty((self.n, self.n)) <NEW_LINE> for i in range(self.n): <NEW_LINE> <INDENT> for j in range(self.n): <NEW_LINE> <INDENT> direction1 = zeros((self.n, 1)) <NEW_LINE> direction2 = zeros((self.n, 1)) <NEW_LINE> direction1[i] = self.epsilon <NEW_LINE> direction2[j] = s...
Computes the inverse hessian of f at the given point x by forward-difference (p.201 Nocedal, Wright) :return: nxn matrix
625941c5e8904600ed9f1f3e
def energy_cutoff(roo, energy=0.95): <NEW_LINE> <INDENT> roo = numpy.abs(roo) <NEW_LINE> return numpy.searchsorted(numpy.cumsum(roo)/roo.sum(), energy)
Determine the index when the energy drops below cutoff :Parameters: roo : array 1-D rotatational average of the power spectra energy : float Energy cutoff :Returns: offset : int Offset when energy drops below cutoff
625941c5293b9510aa2c32ab
def get_views(self): <NEW_LINE> <INDENT> return self.views
Return the view definitions.
625941c594891a1f4081babc
def do_set_huge_font(self, params): <NEW_LINE> <INDENT> pass
Todo: ApiDoc. :param params: :return:
625941c52c8b7c6e89b357d5
def square_window(N,wfilt, real_valued_filter=True): <NEW_LINE> <INDENT> lp,fp = wfilt <NEW_LINE> if lp>N:lp = int(N) <NEW_LINE> if lp-fp<0:lp,fp=fp,lp <NEW_LINE> One = np.ones(lp-fp) <NEW_LINE> z2 = np.zeros(N-lp) <NEW_LINE> if fp==0: Hp = np.hstack((One, z2)) <NEW_LINE> else: <NEW_LINE> <INDENT> z1 = np.zeros(f...
square window in range 0:fs//2. Parameters ------------- * N: int, filter length (sample length). * wfilt: [int,int], cut-off low and high points. Returns -------- * H: window
625941c54428ac0f6e5ba805
def _update_sibling_offsets(self, changed_subchunk, size_diff): <NEW_LINE> <INDENT> index = self.__subchunks.index(changed_subchunk) <NEW_LINE> sibling_chunks = self.__subchunks[index + 1:len(self.__subchunks)] <NEW_LINE> for sibling in sibling_chunks: <NEW_LINE> <INDENT> sibling.offset -= size_diff <NEW_LINE> sibling....
Update the offsets of subchunks after `changed_subchunk`.
625941c58e7ae83300e4afdf
def copy(self): <NEW_LINE> <INDENT> new = copy.copy(self) <NEW_LINE> return new
Creates a copy of a modification. Does not copy the underlying sequence object. Returns ------- mod : :class:`.Modification`
625941c54527f215b584c46c
def create_files_to_compare_list(method_name, indices=test_indices(), root=get_collection_root()): <NEW_LINE> <INDENT> method_root_filepath = get_method_root(method_name) <NEW_LINE> return [FilesToCompare( get_opin_filepath(i, is_etalon=False, root=method_root_filepath), get_opin_filepath(i, is_etalon=True, root=root),...
Create list of comparable opinion files for the certain method. method_name: str
625941c5566aa707497f457f
def ArmijoLineSearch(func, value, grad, x, d_k, a0=1, sigma=0.25, beta=0.5): <NEW_LINE> <INDENT> a = a0 <NEW_LINE> new_value = func(x+a*d_k) <NEW_LINE> y_k = new_value - value <NEW_LINE> c = np.matmul(grad.T, d_k) <NEW_LINE> while y_k > sigma * a * c: <NEW_LINE> <INDENT> a = beta*a <NEW_LINE> new_value = func(x + a * d...
performing inexact line search, in order to find an acceptable step length that reduces the objective function 'sufficiently'. :param func: the function to reduce :param value: func value at current guess :param grad: func grad at current guess :param x: current guess :param d_k: current direction :return: a: best step...
625941c5dd821e528d63b1be
def _datecategorytuples(timecoord, catfun): <NEW_LINE> <INDENT> dates = _coorddatetimes(timecoord) <NEW_LINE> cats = np.array([catfun(d) for d in dates]) <NEW_LINE> catset = np.unique(cats) <NEW_LINE> return [np.where(cats == cs) for cs in catset]
Generate a list of tuples of indices sorted by category. timecoord: an iris time coordinate catfun: a function that accepts a datetime and returns an integer representing a category.
625941c5167d2b6e31218baa
def checkAI(connection:Connectionfour)->None: <NEW_LINE> <INDENT> AIinfo=input() <NEW_LINE> write(connection,AIinfo) <NEW_LINE> expect(connection,'READY')
Send the AI_GAME mesg and check if the received mesg is correct in format
625941c526238365f5f0ee80
def __gt__(self, other): <NEW_LINE> <INDENT> return float(self) > float(other)
Tests whether other is greater than self :param other: a object that implements __float__ :return: True or False
625941c550812a4eaa59c337
def cycle(initial_state, rules, cycles): <NEW_LINE> <INDENT> all_states = [initial_state] <NEW_LINE> c = 0 <NEW_LINE> state = initial_state <NEW_LINE> leftpot = 0 <NEW_LINE> while cycles > 0: <NEW_LINE> <INDENT> c += 1 <NEW_LINE> state = '.......' + state + '.......' <NEW_LINE> leftpot -= 7 <NEW_LINE> new_state = [] <N...
Perform generation of new cycles, give an initial state. For generation, need to prefix and postfix the state with some blanks.
625941c5eab8aa0e5d26db6b
def find_largest_path(self): <NEW_LINE> <INDENT> self.path_lengths[self.num_rows-1] = self.triangle[self.num_rows-1] <NEW_LINE> for row in range(self.num_rows - 1)[::-1]: <NEW_LINE> <INDENT> self.path_lengths[row] = [ (self.triangle[row][column] + self.find_largest_child(row, column)) for column in range(len(self.trian...
Find the highest value path through the triangle, starting from the bottom.
625941c5a05bb46b383ec837
def process_valid_form(self, request, form_instance, **kwargs): <NEW_LINE> <INDENT> process_result = self.form.process(form_instance, request) <NEW_LINE> context = RequestContext( request, { 'content': self, 'message': self.success_message or process_result or u''}) <NEW_LINE> return render_to_string(self.template, con...
Process form and return response (hook method).
625941c507f4c71912b11495
def all_apps_func(request): <NEW_LINE> <INDENT> all_apps = App.objects.filter(active=True) <NEW_LINE> all_apps_fmt = [_app_to_obj(app) for app in all_apps if app.has_releases] <NEW_LINE> return json_response(all_apps_fmt)
Gets all App objects that are active with releases :param request: :return: active App objects with releases in json format
625941c56fece00bbac2d751
def patch(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'method': 'PATCH'})
partial Update
625941c516aa5153ce36248c
@contextlib.contextmanager <NEW_LINE> def task(ctx, config): <NEW_LINE> <INDENT> if config is None: <NEW_LINE> <INDENT> config = { 'all': None } <NEW_LINE> <DEDENT> norm_config = config <NEW_LINE> if isinstance(config, dict): <NEW_LINE> <INDENT> norm_config = teuthology.replace_all_with_clients(ctx.cluster, config) <NE...
Create and mount an rbd image. For example, you can specify which clients to run on:: tasks: - ceph: - rbd: [client.0, client.1] There are a few image options:: tasks: - ceph: - rbd: client.0: # uses defaults client.1: image_name: foo image_size: 2048 ...
625941c5e5267d203edcdcb2
def AnimationNodeNotify(self,pAnimationNode,pEvaluateInfo,pConstraintInfo): <NEW_LINE> <INDENT> pass
Notification callback for connectors. pAnimationNode : Animation node being notified. pEvaluateInfo : Information for evaluation. pConstraintInfo : Information for constraint. return : <b>true</b> if successful.
625941c538b623060ff0ae02
def getRecordAtXref(self, xref, xrefType='indi'): <NEW_LINE> <INDENT> if xrefType == 'indi': <NEW_LINE> <INDENT> table = self.indexXrefsI <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> table = self.indexXrefsF <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> indice = table[xref] <NEW_LINE> <DEDENT> except KeyError: <NEW_LIN...
Finds a record corresponding to xref and type ('indi', 'fam')
625941c5435de62698dfdc60
def loadData(filename_users, filename_hashData): <NEW_LINE> <INDENT> userDict = {0:[]} <NEW_LINE> with open(filename_users, 'r') as file: <NEW_LINE> <INDENT> for line in file: <NEW_LINE> <INDENT> userDict[0].append(line) <NEW_LINE> <DEDENT> <DEDENT> with open(filename_hashData, 'r') as file: <NEW_LINE> <INDENT> for lin...
Fills given user dict from given .csv file, returns user dict.
625941c54e4d5625662d43ed
def execute_sql_from_files(self, paths): <NEW_LINE> <INDENT> for path in paths: <NEW_LINE> <INDENT> self.execute_sql_from_file(path=path)
Shortcut for calling :meth:`.execute_sql_from_file` with multiple files. Calls :meth:`.execute_sql_from_file` once for each file in ``paths``. Args: paths (list): A list of paths. See :meth:`.get_sql_from_file` for the format of each path.
625941c55166f23b2e1a516d
def eval_hp_loop(self, i: 'int', j: 'int') -> "int": <NEW_LINE> <INDENT> return _RNA.fold_compound_eval_hp_loop(self, i, j)
eval_hp_loop(fold_compound self, int i, int j) -> int
625941c555399d3f055886c7
def __init__(self, df, partition=1): <NEW_LINE> <INDENT> self.partition = partition <NEW_LINE> self.df = df <NEW_LINE> self.df_bert = self.get_df_bert()
Class initilization Parameters ---------- df: pandas.DataFrame partition: int choose to return size(df) / partition
625941c592d797404e30419d
def routers_with_identifier(cloud_name, identifier): <NEW_LINE> <INDENT> conn = openstack.connect(cloud=cloud_name) <NEW_LINE> router_list = [] <NEW_LINE> for router in conn.network.routers(): <NEW_LINE> <INDENT> if identifier in router['name']: <NEW_LINE> <INDENT> router_list.append(router['id']) <NEW_LINE> <DEDENT> <...
This function fetches list of routers that have a particular text(identifier) in their name. If there are no router with text(identifier) in their name it returns an empty list.
625941c5a934411ee37516a7
def voronoi_smooth_poly(pts, niter=3, weigths=[1, 6, 1], scaling=1.0): <NEW_LINE> <INDENT> vor = Voronoi(pts) <NEW_LINE> xmin, ymin = np.min(pts, axis=0) <NEW_LINE> xmax, ymax = np.max(pts, axis=0) <NEW_LINE> polys = [] <NEW_LINE> weights = [1, 6, 1] <NEW_LINE> for poly in vor.regions: <NEW_LINE> <INDENT> vertices = np...
Smoothed polygons from the Voronoi tesselation of a pointset The smoothing is done with subdivision algorithm. Parameters ---------- pts : array like (npts, 2) Set of points to compute the Voronoi tesselation. niter : int Number of subdivisions to use. weights : list Weights for the the corners of the smo...
625941c5baa26c4b54cb1135
def highpass_butterworth_filter(shape, cutoff_frequency, order=2): <NEW_LINE> <INDENT> filter_frequency_domain = np.zeros(shape) <NEW_LINE> for v,u in itertools.product(range(shape[0]), range(shape[1])): <NEW_LINE> <INDENT> filter_frequency_domain[v][u] = 1/(1+(power_distance(shape, (v,u))/cutoff_frequency)**(2*order))...
Returns butterworth lowpass filter(image) according to given parameters
625941c560cbc95b062c6557
def get_net( self, network_id ): <NEW_LINE> <INDENT> self.feature_names = {} <NEW_LINE> self.feature_graph_ids = {} <NEW_LINE> self._map_classes() <NEW_LINE> self._retrieve_data_network_features( network_id ) <NEW_LINE> self._retrieve_data_feature_graphs( network_id ) <NEW_LINE> self._retrieve_data_generic_attributes( ...
Retrieve the electrical network as pandapower model.
625941c5f9cc0f698b140611
def generate_map_layer(width, height, center=(0, 0), scale=1, seed=0, offset_x=0.0, offset_y=0.0, octaves=1, persistence=0.5, lacunarity=2.0, repeat_x=None, repeat_y=None): <NEW_LINE> <INDENT> max_x = width // 2 <NEW_LINE> max_y = height // 2 <NEW_LINE> rows = [] <NEW_LINE> for y in range(center[1] + max_y, center[1] -...
Generate one layer of map data using simplex noise. :param int width: The width of the map :param int height: The height of the map :param tuple(int, int) center: The center of the map in (x, y) form :param scale: The scale of the base plane :param seed: A third dimensional coordinate to use as a seed :param float off...
625941c5d6c5a1020814405e
def sample_random_points(image, n=2000): <NEW_LINE> <INDENT> if image is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if not isinstance(n, int) or n <= 0: <NEW_LINE> <INDENT> raise ValueError("`n` should be a positive integer") <NEW_LINE> <DEDENT> points = np.array(np.nonzero(image)).T <NEW_LINE> points = ...
Sample `n` random points from non-zero values in the `image`. Arguments: image {numpy.array} -- image (axes order: Z, Y, X) Keyword Arguments: n {int} -- number of points (default: {2000}) Returns: [numpy.array] -- array of points (x, y, z)
625941c5a219f33f34628980
def getShortIsoTimestamp(): <NEW_LINE> <INDENT> return formatShortIsoTimestamp(datetime.datetime.utcnow());
Returns the current UTC timestamp as a string, but w/o microseconds.
625941c5f548e778e58cd591
def is_inside(self, p): <NEW_LINE> <INDENT> p = np.array(p) <NEW_LINE> halfspaces = self.halfspaces <NEW_LINE> return np.min([h.contains(p) for h in halfspaces])
:param p: 3d point as list or np.array :return True if p is inside the pyramid, else False
625941c5be7bc26dc91cd616
def __init__(self, filename=None, data=None): <NEW_LINE> <INDENT> if filename is None and data is None: <NEW_LINE> <INDENT> raise QasmError("Missing input file and/or data") <NEW_LINE> <DEDENT> if filename is not None and data is not None: <NEW_LINE> <INDENT> raise QasmError("File and data must not both be specified" "...
Create an OPENQASM circuit object.
625941c53cc13d1c6d3c738f