code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, id, red=0, green=0, blue=0): <NEW_LINE> <INDENT> if not id.isdigit(): <NEW_LINE> <INDENT> raise ValueError('"' + id + '" is not a correct "id" for a Color.') <NEW_LINE> <DEDENT> self.id = id <NEW_LINE> self.red = red <NEW_LINE> self.green = green <NEW_LINE> self.blue = blue <NEW_LINE> _colors[id] = s...
Register a new color for the color table. Arguments: - id: (str) containing only digits. - red, green, blue: (int) Numbers in range 0-255.
625941d4498bea3a759b9cac
def _write(self, config, datacenter=None): <NEW_LINE> <INDENT> for dc, data in config.items(): <NEW_LINE> <INDENT> if datacenter is not None and dc != datacenter: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> errors = self._validate(config, datacenter) <NEW_LINE> if errors: <NEW_LINE> <INDENT> return ActionResult(Fa...
Write the given config, if valid, to the datastore.
625941d46fece00bbac2d93d
def get_dir(self, alp_idx, char_idx, drawer_idx): <NEW_LINE> <INDENT> alp = list(self.data_dict.keys())[alp_idx] <NEW_LINE> char = list(self.data_dict[alp].keys())[char_idx] <NEW_LINE> return os.path.join(self.root_dir, alp, char, self.data_dict[alp][char][drawer_idx])
get img_dir from alp, char, drawer's idx
625941d4e8904600ed9f212c
def initialize_chain(test_dir): <NEW_LINE> <INDENT> if not os.path.isdir(os.path.join("cache", "node0")): <NEW_LINE> <INDENT> devnull = open("/dev/null", "w+") <NEW_LINE> for i in range(4): <NEW_LINE> <INDENT> datadir=initialize_datadir("cache", i) <NEW_LINE> args = [ os.getenv("BITCOIND", "parqd"), "-keypool=1", "-dat...
Create (or copy from cache) a 200-block-long chain and 4 wallets. parqd and parq-cli must be in search path.
625941d4b5575c28eb68e1fe
def __allowedValue(self, pos, problem): <NEW_LINE> <INDENT> row = pos[0] <NEW_LINE> col = pos[1] <NEW_LINE> val = [1,2,3,4,5,6,7,8,9] <NEW_LINE> for i in range(9): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val.remove(problem[row][i]) <NEW_LINE> val.remove(problem[i][col]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDE...
Calculated the values allowed at a position and return the value. if no value is possible to fit to the position then return a random value. @input : position = [x , y, value] , problem = sample conbined with the problem matrix @output : the value for the position
625941d40fa83653e46571b7
def get_topics( self, topic_name=None, names_only=False, fetch_partition_state=True, ): <NEW_LINE> <INDENT> topic_ids = [topic_name] if topic_name else self.get_children( "/brokers/topics", ) <NEW_LINE> if names_only: <NEW_LINE> <INDENT> return topic_ids <NEW_LINE> <DEDENT> topics_data = {} <NEW_LINE> for topic_id in t...
Get information on all the available topics. Topic-data format with fetch_partition_state as False :- topic_data = { 'version': 1, 'partitions': { <p_id>: { replicas: <broker-ids> } } } Topic-data format with fetch_partition_state as True:- topic_data = { 'version': 1, ...
625941d45f7d997b87174c96
def scharr(image, mask=None, *, axis=None, mode='reflect', cval=0.0): <NEW_LINE> <INDENT> image = img_as_float(image) <NEW_LINE> output = _generic_edge_filter(image, smooth_weights=SCHARR_SMOOTH, axis=axis, mode=mode, cval=cval) <NEW_LINE> output = _mask_filter_result(output, mask) <NEW_LINE> return output
Find the edge magnitude using the Scharr transform. Parameters ---------- image : array The input image. mask : array of bool, optional Clip the output image to this mask. (Values where mask=0 will be set to 0.) axis : int or sequence of int, optional Compute the edge filter along this axis. If not pro...
625941d4adb09d7d5db6c98c
def _splitdict(tk, v, cut_minus=True, conv=None): <NEW_LINE> <INDENT> t = tk.splitlist(v) <NEW_LINE> if len(t) % 2: <NEW_LINE> <INDENT> raise RuntimeError( "Tcl list representing a dict is expected " "to contain an even number of elements" ) <NEW_LINE> <DEDENT> it = iter(t) <NEW_LINE> dict = {} <NEW_LINE> for key, valu...
Return a properly formatted dict built from Tcl list pairs. If cut_minus is True, the supposed '-' prefix will be removed from keys. If conv is specified, it is used to convert values. Tcl list is expected to contain an even number of elements.
625941d4a05bb46b383eca1e
def make_resource_immutable(self, resource_uuid): <NEW_LINE> <INDENT> meta = self.get_resource_metadata(resource_uuid) <NEW_LINE> if not meta['immutable']: <NEW_LINE> <INDENT> meta['immutable'] = True <NEW_LINE> self.assert_resource_metadata(meta)
Make a resource immutable (admin or owner only) :type group_uuid: basestring :param group_uuid: UUID of resource to change
625941d4aad79263cf390c40
def processUnsubscribe(self, session, unsubscribe): <NEW_LINE> <INDENT> if unsubscribe.subscription in self._subscription_to_sessions: <NEW_LINE> <INDENT> topic, subscribers = self._subscription_to_sessions[unsubscribe.subscription] <NEW_LINE> subscribers.discard(session) <NEW_LINE> if not subscribers: <NEW_LINE> <INDE...
Implements :func:`autobahn.wamp.interfaces.IBroker.processUnsubscribe`
625941d426068e7796caeede
def OsawaDiscard(observation): <NEW_LINE> <INDENT> unplayable = [] <NEW_LINE> for card in observation['card_knowledge'][0]: <NEW_LINE> <INDENT> unplayable.append((CardUnplayable(card, observation['fireworks']))) <NEW_LINE> <DEDENT> if True not in unplayable: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif unpl...
Discards a card if it cannot be played at the end of the turn. This will discard cards that we know enough about to disqualify them from being playable. For example, a card with an unknown suit but a rank of 1 will not be playable if all the stacks have been started. This rule also considers cards that can not be playe...
625941d438b623060ff0afeb
def test_getContactEditorialParameters(self): <NEW_LINE> <INDENT> contactTypes = [StubContactType( (), None, [], theDescriptiveIdentifier=u'So Descriptive')] <NEW_LINE> contactPowerup = StubOrganizerPlugin( store=self.store, contactTypes=contactTypes) <NEW_LINE> self.store.powerUp(contactPowerup, IOrganizerPlugin) <NEW...
L{Organizer.getContactEditorialParameters} should return a list containing a L{ListChangeParameter} for each contact type available in the system which supports multiple contact items.
625941d4d58c6744b4257e5c
def show_CDF(self): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> x = np.linspace(0, self._max_dist, 1000) <NEW_LINE> cdf = self._cdf(x) <NEW_LINE> plt.plot(x, cdf, '-', color='black', linewidth=3, label='Theory', zorder=1) <NEW_LINE> y = [(i + 1.) / len(self._dist) for i in range(len(self._dist))] <NEW_LINE> plt.step([0...
Plot the cumulative distribution function (CDF) of source-target distances.
625941d407f4c71912b11681
def validate_amqp_config_tracker(f): <NEW_LINE> <INDENT> def _validate_amqp_config_tracker(*args, **kwargs): <NEW_LINE> <INDENT> if not is_leader(): <NEW_LINE> <INDENT> kvstore = kv() <NEW_LINE> tracker = kvstore.get('amqp_config_tracker') <NEW_LINE> if tracker: <NEW_LINE> <INDENT> for rid in tracker: <NEW_LINE> <INDEN...
Decorator to mark all existing tracked amqp configs as stale so that they are refreshed the next time the current unit leader.
625941d48a349b6b435e8371
def base64_getint(buf, pos=0): <NEW_LINE> <INDENT> v = 0 <NEW_LINE> for z, ch in enumerate(buf[pos:]): <NEW_LINE> <INDENT> c = base64_getint.zvalue[0x7f&ch] <NEW_LINE> if c < 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> v = (v<<6) + c <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> z += 1 <NEW_LINE> <DEDENT> return (...
Returns the encoded integer and consumed string length.
625941d47cff6e4e81117b83
def get_branches_map(branchitems): <NEW_LINE> <INDENT> branchesmap = {} <NEW_LINE> logging.debug('get_branches_map: str(branchitems): ' + str(branchitems)) <NEW_LINE> if len(branchitems) > 0: <NEW_LINE> <INDENT> for branches in sorted(branchitems): <NEW_LINE> <INDENT> if (branches[0].startswith('branches-')): <NEW_LINE...
Get list of branches from configuration to be auto merged, only these branches are going to be taken into account when auto merging. Args: branchitems: The list of branches to be analyzed.
625941d4a17c0f6771cbe24d
def _get_groupby(self): <NEW_LINE> <INDENT> definition = self.column_json <NEW_LINE> if self.groupby is not None: <NEW_LINE> <INDENT> return self.groupby <NEW_LINE> <DEDENT> main_table = self.table <NEW_LINE> column_name = self.id <NEW_LINE> main_keys = definition.get('keys', []) <NEW_LINE> linked_keys = definition.get...
Return a pandas groupby object for the link column. If it is not present then it is returned.
625941d455399d3f055888b2
def resolve_conflicts(self): <NEW_LINE> <INDENT> new_chain = None <NEW_LINE> max_length = len(self.chain()) <NEW_LINE> for node in self.nodes(): <NEW_LINE> <INDENT> response = requests.get("http://{0}/chain".format(node['name'])) <NEW_LINE> if response.status_code != 200: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT...
This is the consensus algorithm. It resolves conflicts by replacing our chain with the longest one in the network. :return: True if our chain was replaced, False if not.
625941d4287bf620b61d3c61
def reducePoints(cont, n): <NEW_LINE> <INDENT> if n >= len(cont): <NEW_LINE> <INDENT> return cont <NEW_LINE> <DEDENT> cont = list(cont) <NEW_LINE> cont.insert(0, cont[-1]) <NEW_LINE> cont.append(cont[1]) <NEW_LINE> a = [(__vImp(cont[i-1:i+2]), i) for i in range(1, len(cont)-1)] <NEW_LINE> a.sort() <NEW_LINE> ind = [x[1...
reducePoints(cont, n) - remove points of the contour 'cont', return a new contour with 'n' points. *Very simple* approach to reduce the number of points of a contour. Each point gets an associated 'value of importance' which is the product of the lengths and absolute angle of the left and right vertex. The points are s...
625941d4baa26c4b54cb131b
def distance_dialog(self, widget): <NEW_LINE> <INDENT> self.widget.dialog = True <NEW_LINE> self.message = gtk.Dialog(title='ruler') <NEW_LINE> self.message.connect('destroy', self.toggle_dialog) <NEW_LINE> table = gtk.Table(rows=4, columns=3, homogeneous=True) <NEW_LINE> table.set_row_spacings(5) <NEW_LINE> table.set_...
a dialog like google earth distance tool
625941d401c39578d7e75039
def checker_track(self, temp_output_file, local_gap): <NEW_LINE> <INDENT> track_a_file = self.phase.temp_folder + 'track-a.wav' <NEW_LINE> track_b_file = self.phase.temp_folder + 'track-b.wav' <NEW_LINE> half, remainder = divmod(self.phase.repeat_count, 2) <NEW_LINE> track_a_repeat_count = half + remainder - 1 <NEW_LIN...
Repeat the sample on alternating tracks so the fade in and out can overlap
625941d4956e5f7376d7106a
def is_url(monitor_url, status_code=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> response = requests.get(monitor_url) <NEW_LINE> LOG.debug('URL %s status %s', monitor_url, response.status_code) <NEW_LINE> if status_code: <NEW_LINE> <INDENT> if response.status_code == status_code: <NEW_LINE> <INDENT> return True ...
Determins if the URL is reachable and optionally returns a status code
625941d4851cf427c661a70b
def normalize_space(s): <NEW_LINE> <INDENT> return ' '.join(s.split())
Normalize whitespace.
625941d48a43f66fc4b54261
def add_contributor(self, user, at_time=None): <NEW_LINE> <INDENT> _, created = get_contributor_relation_model().objects.get_or_create( organization=self, user=user) <NEW_LINE> return created
Add user as a contributor to organization.
625941d4ec188e330fd5a99a
def create_output_object(self, account_path): <NEW_LINE> <INDENT> organization_information = self.organizations.get_organization_info() <NEW_LINE> return { 'account_id': self.account_id, 'cross_account_access_role': self.cross_account_access_role, 'deployment_account_id': self.deployment_account_id, 'regions': self.reg...
Creates the output object to be passed to the next step of the Step Function
625941d4a17c0f6771cbe24e
def getLastSubdir(directory): <NEW_LINE> <INDENT> dirList = [ name for name in os.listdir(directory) if os.path.isdir(os.path.join(directory, name)) ] <NEW_LINE> if len(dirList) > 0: <NEW_LINE> <INDENT> lastSubDir = sorted(dirList)[-1] <NEW_LINE> lastSubDir = os.path.join(directory, lastSubDir) <NEW_LINE> <DEDENT> else...
Scan for directories and return most recent
625941d48e7ae83300e4b1cb
def append_to_tail(self, node: ListNode): <NEW_LINE> <INDENT> node.prev = self.tail.prev <NEW_LINE> node.next = self.tail <NEW_LINE> self.tail.prev.next = node <NEW_LINE> self.tail.prev = node
将 node 节点(最近访问的节点)加到表尾 表尾节点(tail.prev)的 next 指针指向node node 的 prev 指针指向表尾节点, next 指针指向 tail tail 的 prev 指针指向 node :param node: 要加到表尾的节点 :return:
625941d41f037a2d8b9463fb
def _user_for_cookie(self, cookie_name, cookie_value=None): <NEW_LINE> <INDENT> cookie_id = self.get_secure_cookie( cookie_name, cookie_value, max_age_days=self.cookie_max_age_days, ) <NEW_LINE> def clear(): <NEW_LINE> <INDENT> self.clear_cookie(cookie_name) <NEW_LINE> <DEDENT> if cookie_id is None: <NEW_LINE> <INDENT>...
Get the User for a given cookie, if there is one
625941d4a79ad161976cc343
def get_avatar_url(self): <NEW_LINE> <INDENT> return self.account.extra_data.get('gravatar')
Get the profile image url
625941d467a9b606de4a80b6
def __init__(self, evaler=None, db=None, *args, **kwargs): <NEW_LINE> <INDENT> self._ctx = ctx = {} <NEW_LINE> self.evaler = evaler or evaluator.Evaluator(db) <NEW_LINE> import cymetric as cym <NEW_LINE> ctx['cym'] = cym <NEW_LINE> ctx['np'] = np <NEW_LINE> ctx['pd'] = pd <NEW_LINE> ctx['uuid'] = uuid <NEW_LINE> try: <...
Parameters ---------- evaler : cymetric.evaluator.Evaluator, optional The evaluator for the metrics, required if db not given. db : database, optional Required if evaler not given. args, kwargs : tuple, dict Other arguments to the mutable mapping.
625941d44c3428357757c525
def test_5_auth_token_in_json(self): <NEW_LINE> <INDENT> create_user(username='admin', password='admin') <NEW_LINE> token = get_token(self.client, username='admin', password='admin') <NEW_LINE> response = self.client.delete( url_for('user_token_bp.users_token_api'), json=dict(token=token, token_type='Bearer') ) <NEW_LI...
测试放在json里的token
625941d4dc8b845886cb5734
def getzudui_4308(data1,plist,msg,zy): <NEW_LINE> <INDENT> from app.scense.protoFile.zudui import GroupBattle4308_pb2 <NEW_LINE> response=GroupBattle4308_pb2.FightResponse() <NEW_LINE> response.result = True <NEW_LINE> response.data.battleResult = data1.battleResult <NEW_LINE> response.data.centerX = data1.center <NEW_...
多人副本战斗 @param data1: obj 战斗信息 @param plist: [角色id] 托送的角色id列表 @param msg: str 战斗结束后的消息 @param zy: int 场景资源id
625941d4b830903b967e9b08
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, AccountMaster): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941d47d43ff24873a2e9e
def my_align(self, _string, _length, _type='L'): <NEW_LINE> <INDENT> _str_len = len(_string) <NEW_LINE> for _char in _string: <NEW_LINE> <INDENT> if u'\u4e00' <= _char <= u'\u9fa5': <NEW_LINE> <INDENT> _str_len += 1 <NEW_LINE> <DEDENT> <DEDENT> _space = _length-_str_len <NEW_LINE> if _type == 'L': <NEW_LINE> <INDENT> _...
中英文混合字符串对齐函数 my_align(_string, _length[, _type]) -> str :param _string:[str]需要对齐的字符串 :param _length:[int]对齐长度 :param _type:[str]对齐方式('L':默认,左对齐;'R':右对齐;'C'或其他:居中对齐) :return:[str]输出_string的对齐结果 作者:Roi_Rio 原文地址:https://www.jianshu.com/p/74500b7dc278
625941d4d268445f265b506c
def student_register(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> students_obj = pickle.load(open(setting.STUDENT_DB,'rb')) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> students_obj = StudentAdmin.get_students() <NEW_LINE> <DEDENT> students_obj.register()
注册学生
625941d497e22403b379d198
def get_report(self, status): <NEW_LINE> <INDENT> self.report.status = status <NEW_LINE> return self.report
This method sets the status of the Report object with the one received in arguments.
625941d41b99ca400220acaf
def getIntersectionNode(headA, headB): <NEW_LINE> <INDENT> pa, pb = headA, headB <NEW_LINE> a, b = 0, 0 <NEW_LINE> while pa: <NEW_LINE> <INDENT> pa = pa.next <NEW_LINE> a += 1 <NEW_LINE> <DEDENT> while pb: <NEW_LINE> <INDENT> pb = pb.next <NEW_LINE> b += 1 <NEW_LINE> <DEDENT> pa, pb = headA, headB <NEW_LINE> for i in r...
160. 相交链表 编写一个程序,找到两个单链表相交的起始节点。 例如: A = [1,2,3,4,5], B = [6,7,3,4,5], return 3 因为[3,4,5] :param headA: ListNode :param headB: ListNode :return: ListNode
625941d49f2886367277aa8a
def check_result_ignore(result, ignore_ranges): <NEW_LINE> <INDENT> for bears, range in ignore_ranges: <NEW_LINE> <INDENT> orig = result.origin.lower() <NEW_LINE> if (result.overlaps(range) and (len(bears) == 0 or orig in bears or fnmatch(orig, bears))): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> retu...
Determines if the result has to be ignored. :param result: The result that needs to be checked. :param ignore_ranges: A list of tuples, each containing a list of lower cased affected bearnames and a SourceRange to ignore. If any of the bearname lists is empty, it ...
625941d4d7e4931a7ee9e11c
def test_insert_if(self): <NEW_LINE> <INDENT> item = object() <NEW_LINE> iterable = range(4) <NEW_LINE> condition = lambda item: item % 2 == 0 <NEW_LINE> iterator = dnf.util.insert_if(item, iterable, condition) <NEW_LINE> self.assertEqual(next(iterator), item) <NEW_LINE> self.assertEqual(next(iterator), 0) <NEW_LINE> s...
Test insert_if with sometimes fulfilled condition.
625941d49c8ee82313fbb974
def setup(hass, config): <NEW_LINE> <INDENT> if None in (hass.config.latitude, hass.config.longitude): <NEW_LINE> <INDENT> _LOGGER.error("Latitude or longitude not set in Home Assistant config") <NEW_LINE> return False <NEW_LINE> <DEDENT> latitude = util.convert(hass.config.latitude, float) <NEW_LINE> longitude = util....
Tracks the state of the sun.
625941d43d592f4c4ed1d269
def _(text, disambiguation=None, context='Key'): <NEW_LINE> <INDENT> return unicode( qt4.QCoreApplication.translate(context, text, disambiguation))
Translate text.
625941d4925a0f43d254a076
def runtool(self, *args): <NEW_LINE> <INDENT> txt = str(self.inputx.text()).strip() <NEW_LINE> if not len(txt): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for field in ( self.alt, self.b64, self.b64unsafe, self.rot13, self.urlenc, self.urlencp, self.snake, self.spine, self.asci, self.camel, self.swp, self.tran): <N...
Run all text transformation tools.
625941d407f4c71912b11682
def isPeakAssigned(peak, fully=0): <NEW_LINE> <INDENT> n = 0 <NEW_LINE> for peakDim in peak.peakDims: <NEW_LINE> <INDENT> if len(peakDim.peakDimContribs) > 0: <NEW_LINE> <INDENT> n +=1 <NEW_LINE> <DEDENT> <DEDENT> if n == len(peak.peakDims): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif n > 0: <NEW_LINE> <INDEN...
Descrn: Determines if a peak is assigned, ether fully or partially Inputs: Peak, Boolean Output: Boolean
625941d416aa5153ce362676
def _xavier_initializer(shape, **kwargs): <NEW_LINE> <INDENT> epsilon = tf.sqrt(6. / sum(shape)) <NEW_LINE> out = tf.Variable(tf.random_uniform(shape,-epsilon,epsilon),**kwargs) <NEW_LINE> return out
Defines an initializer for the Xavier distribution. Specifically, the output should be sampled uniformly from [-epsilon, epsilon] where epsilon = sqrt(6) / <sum of the sizes of shape's dimensions> e.g., if shape = (2, 3), epsilon = sqrt(6 / (2 + 3)) This function will be used as a variable initializer. Args: ...
625941d4eab8aa0e5d26dd56
def lookup_all_by_type(self, typ): <NEW_LINE> <INDENT> for cls in get_mro(typ): <NEW_LINE> <INDENT> if cls in self.type_map or self._in_name_map(cls): <NEW_LINE> <INDENT> objs = self.type_map[cls] <NEW_LINE> if objs: <NEW_LINE> <INDENT> return objs <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for abstract, objs in six.iterite...
Look up all the registered objects for a type. Parameters ---------- typ : type The type to look up. Returns ------- objs : list of objects The list of registered objects for the type. If the given type is not registered, its superclasses are searched. If none of the superclasses are registered, sear...
625941d48c3a8732951585b9
def getDistanceDuPoint(self, posX, posY): <NEW_LINE> <INDENT> return abs(self.centreX - posX) + abs(self.centreY - posY)
@summary:Retourne la distance séparant posX;posY du centre de ce piège.
625941d421a7993f00bc7ef0
def encode_documents(documents: list, tokenizer, max_input_length=256): <NEW_LINE> <INDENT> tokenized_documents = [tokenizer.tokenize(document) for document in documents] <NEW_LINE> max_sequences_per_document = math.ceil(max(len(x) / (max_input_length - 2) for x in tokenized_documents)) <NEW_LINE> assert max_sequences_...
Returns a len(documents) * max_sequences_per_document * 3 * 512 tensor where len(documents) is the batch dimension and the others encode bert input. This is the input to any of the document bert architectures. :param max_input_length: :param documents: a list of text documents :param tokenizer: the sentence piece bert ...
625941d4be7bc26dc91cd7fc
def _encode(obj): <NEW_LINE> <INDENT> if not PY3 and isinstance(obj, unicode): <NEW_LINE> <INDENT> return obj.encode('utf8', 'strict') <NEW_LINE> <DEDENT> return obj
Identity, except when obj is unicode then return a UTF-8 string. This assumes UTF-8 is good enough for libsolv and always will be. Else we'll have to deal with some encoding configuration. Since we use this to match string queries, we have to enforce 'strict' and potentially face exceptions rather than bizarre result...
625941d4507cdc57c6306edc
def error_msg_from_exception(e): <NEW_LINE> <INDENT> msg = '' <NEW_LINE> if hasattr(e, 'message'): <NEW_LINE> <INDENT> if isinstance(e.message, dict): <NEW_LINE> <INDENT> msg = e.message.get('message') <NEW_LINE> <DEDENT> elif e.message: <NEW_LINE> <INDENT> msg = "{}".format(e.message) <NEW_LINE> <DEDENT> <DEDENT> retu...
Translate exception into error message Database have different ways to handle exception. This function attempts to make sense of the exception object and construct a human readable sentence. TODO(bkyryliuk): parse the Presto error message from the connection created via create_engine. engine = create...
625941d4a934411ee3751892
def _sample_valid_ids(self, visible, num_ids=1, min_id=None, max_id=None): <NEW_LINE> <INDENT> if num_ids == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if min_id is None or min_id < 2: <NEW_LINE> <INDENT> min_id = 2 <NEW_LINE> <DEDENT> if max_id is None or max_id > len(visible): <NEW_LINE> <INDENT> max_id = l...
Samples num_ids frames between min_id and max_id for which dumped data is useful args: visible - 1d Tensor indicating whether target is visible for each frame num_ids - number of frames to be sampled min_id - Minimum allowed frame number max_id - Maximum allowed frame number returns: list - List o...
625941d4b545ff76a8914014
def _choose_split(self, col: ndarray, label: ndarray) -> Node: <NEW_LINE> <INDENT> node = Node() <NEW_LINE> unique = set(col) <NEW_LINE> if len(unique) == 1: <NEW_LINE> <INDENT> return node <NEW_LINE> <DEDENT> unique.remove(min(unique)) <NEW_LINE> info = self._get_info(label.mean()) <NEW_LINE> ite = map(lambda x: self....
Iterate each xi and split x, y into two pieces, and the best split point is the xi when we get maximum information gain. Arguments: col {ndarray} -- A feature of training data. label {ndarray} -- Target values. Returns: Node -- The best choice of information gain, split point and prob.
625941d4b7558d58953c5110
def input_values(data): <NEW_LINE> <INDENT> data = (data.split()) <NEW_LINE> k = int(data[0]) <NEW_LINE> m = int((data[1])) <NEW_LINE> t = int(data[2]) <NEW_LINE> c = float(data[3]) <NEW_LINE> dis = list(map(float, data[4:])) <NEW_LINE> x=0 <NEW_LINE> N = k*m*t <NEW_LINE> distances = [] <NEW_LINE> for i in range(N): <N...
function which takes data provided by the user and returns the values of all parameters such as k, m t, c, distances matrix and totla no of shops(K)
625941d4d8ef3951e324373c
def symbolIcon(symbol): <NEW_LINE> <INDENT> icon = QIcon(':images/tickers/%s.png' % (symbol.lower(), )) <NEW_LINE> if icon.pixmap(16,16).isNull(): <NEW_LINE> <INDENT> pixmap = QPixmap(16, 16) <NEW_LINE> pixmap.fill(QColor(0, 0, 0, 0)) <NEW_LINE> icon = QIcon(pixmap) <NEW_LINE> <DEDENT> return icon
Icon for a symbol. @param symbol name of symbol @return QIcon instance; transparent but valid if symbol icon not found
625941d48c0ade5d55d3ebba
def format_filename(pair): <NEW_LINE> <INDENT> directory = pair[0] <NEW_LINE> filename = pair[1] <NEW_LINE> return thread_first( directory, os.path.split, snd, lambda date: "{} {}".format(date,filename))
Given a pair of (directory,filename) return a string with the date and filename.
625941d4090684286d50eee5
def parse_file(self): <NEW_LINE> <INDENT> idstring = self.inFile.readBytes(4) <NEW_LINE> unk, unk, numMesh, numMat, numTex = self.inFile.read("5L") <NEW_LINE> self.inFile.read('27f') <NEW_LINE> self.inFile.readUInt() <NEW_LINE> texInfo = [] <NEW_LINE> for i in range(numTex + 1): <NEW_LINE> <INDENT> texInfo.append(self....
Main parser method
625941d482261d6c526ab69f
def testBias(self): <NEW_LINE> <INDENT> exp = self.butler.get("cpBias", self.dataId) <NEW_LINE> print("dataId: %s" % self.dataId) <NEW_LINE> print("detector id: %s" % exp.getDetector().getId()) <NEW_LINE> self.assertEqual(exp.getDetector().getId(), self.dataId["ccdnum"]) <NEW_LINE> self.assertTrue(exp.hasWcs())
Test retrieval of bias image
625941d463f4b57ef0001314
def __init__(self, cameraYamlFile=None): <NEW_LINE> <INDENT> if not cameraYamlFile: <NEW_LINE> <INDENT> cameraYamlFile = os.path.join(utils.getPackageDir(self.packageName), "policy", "camera.yaml") <NEW_LINE> <DEDENT> YamlCamera.__init__(self, cameraYamlFile)
Construct atlas
625941d4460517430c394380
def get_file_extension(filename): <NEW_LINE> <INDENT> terms = filename.split('.') <NEW_LINE> return terms[len(terms)-1]
Get file extension.
625941d44527f215b584c654
def set_summary(self, message): <NEW_LINE> <INDENT> if not isinstance(message, ValidationMessage): <NEW_LINE> <INDENT> raise TypeError("Argument must of type ValidationMessage") <NEW_LINE> <DEDENT> self.summary = message
Sets a summary message on this instance. The summary is optional. Args: message (ValidationMessage): A validation message to set as this instance's summary.
625941d4e5267d203edcde99
def set_item_category(session, item, category): <NEW_LINE> <INDENT> item_cat = session.query(ItemCategory).filter_by( item=item, category=category).first() <NEW_LINE> if item_cat is None: <NEW_LINE> <INDENT> item_cat = ItemCategory(item=item, category=category) <NEW_LINE> session.add(item_cat)
Check for item cat relationship if not exist create one.
625941d4ac7a0e7691ed42c8
def __init__(self, nodes, job_graph, log_dir, callback=None, sleep=None): <NEW_LINE> <INDENT> self.nodes = nodes <NEW_LINE> self.job_graph = job_graph <NEW_LINE> self.completed_jobs = [] <NEW_LINE> self.running = [] <NEW_LINE> self.log_dir = log_dir <NEW_LINE> self.queued_jobs = list(job_graph.keys()) <NEW_LINE> if cal...
Create a Runner Parameters ---------- nodes: list[Node] Nodes available to run on job_graph: dict{Job:Job} Indicates what jobs are to be run and which other jobs they depend on log_dir: str Dir where the logs are put callback: function(event_type: str, event_info: dict) A function called when jobs l...
625941d48e71fb1e9831d9a7
def get_user_by_id(id): <NEW_LINE> <INDENT> r = requests.get(base_url + "/user/" + str(id)) <NEW_LINE> user = r.json() <NEW_LINE> return user
Return users specified by ID.
625941d45fc7496912cc3b7c
def _handle_doubleclick(self, item, col): <NEW_LINE> <INDENT> data = item.data(0, Qt.UserRole).toPyObject() <NEW_LINE> if data is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> (coord, notes) = data <NEW_LINE> axes = self.topLevelOperatorView.InputImages.meta.getAxisKeys() <NEW_LINE> axes = axes[:-1] <NEW_LINE> a...
Navigate to the bookmark
625941d4a4f1c619b28b0235
def mySqrt(self, x): <NEW_LINE> <INDENT> start, end, preMid = 0, x, -1 <NEW_LINE> if not x or x <= 0 or x == 1: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> while start < end: <NEW_LINE> <INDENT> mid = start + (end-start)/2 <NEW_LINE> if math.fabs(mid*mid - x) <= 0.5 or preMid == mid: <NEW_LINE> <INDENT> return int...
:type x: int :rtype: int
625941d4596a897236089cbd
def update(self): <NEW_LINE> <INDENT> raise NotImplementedError("This must be implemented in the base class")
This funciton is called to update the weather form the given API. Generally, you should not need to call this, unless you want
625941d43539df3088e2e549
def _set_thermo_shift(self, device_id, name, value): <NEW_LINE> <INDENT> min_shift = int(COMMAND_MAP[name]["min"]) <NEW_LINE> max_shift = int(COMMAND_MAP[name]["max"]) <NEW_LINE> if min_shift <= value <= max_shift: <NEW_LINE> <INDENT> unsigned_value = uint32(value * 10) <NEW_LINE> self._set_value(device_id, COMMAND_MAP...
Public method to set thermo shift temperature.
625941d43346ee7daa2b2f6b
def getDateOfBirth(id): <NEW_LINE> <INDENT> y,m,d=getDate(id) <NEW_LINE> return(y+'/'+m+'/'+d)
return format string "yyy/mm/dd"
625941d476e4537e8c351872
def vec2RGB( lin_image, n_channels, image_size, channel_order=(0,1,2), amplitude_scaling=(1,1,1) ): <NEW_LINE> <INDENT> image = vec2image( lin_image, n_channels, image_size ) <NEW_LINE> RGB = np.zeros((image_size[0],image_size[1],3)) <NEW_LINE> if n_channels > 1: <NEW_LINE> <INDENT> for nr,ch in enumerate(channel_order...
Constructs a 3d RGB image from a single 1d vector lin_image: 1d image vector with all pixels concatenated n_channels: Number of image channels image_size: 2 dimensional size of the image (y,x) channel_order: tuple indicating which channels are R, G and B amplitude_scaling: Additional scaling of each channel separ...
625941d410dbd63aa1bd2da1
def train(config, total_loss, global_step): <NEW_LINE> <INDENT> num_batches_per_epoch = int(config.get('main', 'num_examples_per_epoch_train')) / int(config.get('main', 'batch_size')) <NEW_LINE> decay_steps = int(num_batches_per_epoch * float(config.get('main', 'num_epochs_per_decay'))) <NEW_LINE> lr = tf...
Train CIFAR-10 model. Create an optimizer and apply to all trainable variables. Add moving average for all trainable variables. Args: total_loss: Total loss from loss(). global_step: Integer Variable counting the number of training steps processed. Returns: train_op: op for training.
625941d4e5267d203edcde9a
def get_offset_message(self): <NEW_LINE> <INDENT> return ' (At bit offset: {})'.format(self.offset)
Get offset details to add to error message :return:
625941d4d10714528d5ffee3
def forward(self): <NEW_LINE> <INDENT> if self._histPtr == len(self._history): <NEW_LINE> <INDENT> raise IndexError("Tries to got beyond end of history.") <NEW_LINE> <DEDENT> self._histPtr += 1 <NEW_LINE> if self._histPtr == len(self._history): <NEW_LINE> <INDENT> return self._current <NEW_LINE> <DEDENT> return self._h...
Move forward by one element in the history. Raises an IndexError if already at the end of the history. :returns: Item in the history after moving forward one step.
625941d46e29344779a62810
def dump_constant_database(self): <NEW_LINE> <INDENT> constant_dump = [] <NEW_LINE> for stream, value in sorted(self.constant_database.items(), key=lambda x: x[0].encode()): <NEW_LINE> <INDENT> constant_dump.append("'{}' {}".format(stream, value)) <NEW_LINE> <DEDENT> return constant_dump
Dump all of the constants in this sensor graph as a list of strings.
625941d430bbd722463cbfc6
def entropy(p): <NEW_LINE> <INDENT> p = p[p != 0] <NEW_LINE> H = -np.dot(p, np.log(p)) <NEW_LINE> return _eps_filter(H)
Calculates the Shannon entropy for a marginal distribution. Args: p (np.ndarray): the marginal distribution. Returns: (float): the entropy of p
625941d4097d151d1a223057
def test_simple_get(self): <NEW_LINE> <INDENT> unknown_key = dollar_value_to_key('UNKNOWN') <NEW_LINE> self.assertNotEqual( dollar_value_to_key('$50,001 - $100,000'), unknown_key)
Single key by name
625941d43c8af77a43ae39a0
def test_coadd_scores(self): <NEW_LINE> <INDENT> nspec, nwave = 10, 20 <NEW_LINE> s1 = self._random_spectra(nspec, nwave) <NEW_LINE> s1.fibermap['TARGETID'] = np.arange(nspec) // 3 <NEW_LINE> coadd(s1) <NEW_LINE> ntargets = len(np.unique(s1.fibermap['TARGETID'])) <NEW_LINE> self.assertEqual(s1.flux['b'].shape[0], ntarg...
Test coaddition
625941d445492302aab5e4c4
def _StopMonitoringProcesses(self): <NEW_LINE> <INDENT> for pid in list(self._process_information_per_pid.keys()): <NEW_LINE> <INDENT> self._RaiseIfNotRegistered(pid) <NEW_LINE> process = self._processes_per_pid[pid] <NEW_LINE> self._StopMonitoringProcess(process)
Stops monitoring all processes.
625941d4d268445f265b506d
def test_schedule_list_filter_task_type(self): <NEW_LINE> <INDENT> request_body_1 = { 'periodic_task': { 'minute': '0', 'hour': '2', 'day_of_week': '*', 'day_of_month': '*', 'month_of_year': '*', }, 'customer': self.customer.id, 'task_type': 'watchman' } <NEW_LINE> request_body_2 = { 'periodic_task': { 'minute': '0', '...
Tests that schedules are listed if they match the id filter parameter.
625941d415fb5d323cde0d10
def _complete(self, completer, get_line_buffer, text, state): <NEW_LINE> <INDENT> get_line_buffer.return_value = text <NEW_LINE> res = completer.complete(None, state) <NEW_LINE> get_line_buffer.reset_mock() <NEW_LINE> return res
Make the readline line buffer mock return the value we want, and then check completer.complete with that in mind.
625941d421bff66bcd684b50
def test_func_negative(): <NEW_LINE> <INDENT> assert ytl('-9') == 'Error. The values entered must be positive integer.' <NEW_LINE> assert ytl('hey') == 'Error. The values entered must be positive integer.' <NEW_LINE> assert ytl('1001') == 'Error. The values entered are to large.' <NEW_LINE> assert ytl('') == 'Error. Th...
Test negative cases
625941d4462c4b4f79d1d8cf
def _reward(self, action): <NEW_LINE> <INDENT> raise NotImplementedError
Return the reward associated with performing a given action and ending up in the current state. :param action: the last action performed :return: the reward
625941d4956e5f7376d7106b
def test_no_udevadm_cmd(self): <NEW_LINE> <INDENT> dsac.CMD_UDEVADM_SETTLE = self.cmd_not_found <NEW_LINE> dsrc = dsac.DataSourceAltCloud({}, None, self.paths) <NEW_LINE> self.assertEqual(False, dsrc.user_data_rhevm())
Test user_data_rhevm() with no udevadm command.
625941d44a966d76dd55120f
def relative_angle(self, p_me, p_you, d_you): <NEW_LINE> <INDENT> self.pass_p_me = p_me <NEW_LINE> self.pass_p_you = p_you <NEW_LINE> self.pass_d_you = d_you <NEW_LINE> self.v_yoko = p_me - p_you <NEW_LINE> theta_mae = np.arctan2(d_you[1], d_you[0]) <NEW_LINE> theta_yoko = absolute_angle(p_you, p_me) <NEW_LINE> theta =...
unit test required
625941d4bd1bec0571d9082f
def __gamma(self, x, ks, out=None): <NEW_LINE> <INDENT> if isinstance(x, np.ndarray) == False: <NEW_LINE> <INDENT> return self.__gamma(np.array([x], dtype='float'), np.array([ks], dtype='float'))[0] <NEW_LINE> <DEDENT> if out is None: <NEW_LINE> <INDENT> out = np.zeros_like(x) <NEW_LINE> <DEDENT> mask = (x > 0.01) <NEW...
Calculate tangential shear of halo. @param x Radial coordinate in units of rs (scale radius of halo), i.e., `x=r/rs`. @param ks Lensing strength prefactor. @param out NumPy array into which results should be placed. [default: None]
625941d46fb2d068a760f29e
def delete(self): <NEW_LINE> <INDENT> LajiStoreAPI.delete_device(self.id)
Deletes the device from LajiStore. Note that the object is not destroyed!
625941d4c4546d3d9de72c34
def shannon_entropy(p): <NEW_LINE> <INDENT> p = p.flatten() <NEW_LINE> return -sum(pi*np.log2(pi) for pi in p if pi)
Shannon entropy H(X) is the negative sum of P(X)log(P(X)) for probability distribution P(X).
625941d44a966d76dd551210
def _conclude(self): <NEW_LINE> <INDENT> n_blocks = len(self._results) <NEW_LINE> if n_blocks == 1: <NEW_LINE> <INDENT> self.mean = self._results[0, 0] <NEW_LINE> self.sumsquares = self._results[0, 1] <NEW_LINE> self.rmsf = np.sqrt(self.sumsquares.sum(axis=1) / self.n_frames) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
self._results : Array (n_blocks x 2 x N x 3) array
625941d4aad79263cf390c42
def loop(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.setup() <NEW_LINE> while self.continueReceiveLoop: <NEW_LINE> <INDENT> if self.requireToken: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> m = self.receiveMessage(messaging.Message.CSendToken, messaging.Message.Close) <NEW_LINE> <DEDENT> except Unexpected...
wait for client messages, process them, until client closes the connection
625941d4e76e3b2f99f3aa08
def get_average_rating(self, movie_id): <NEW_LINE> <INDENT> pass
Returns an average rating for a given movie id.
625941d40fa83653e46571ba
def _showView(self, win, fn = None): <NEW_LINE> <INDENT> if fn is not None and self.lastFN != fn: <NEW_LINE> <INDENT> self.lastFN = fn <NEW_LINE> win.hide() <NEW_LINE> <DEDENT> win.show() <NEW_LINE> win.setFocus()
Private method to show a view (i.e. window) @param win editor window to be shown @param fn filename of this editor
625941d48c0ade5d55d3ebbb
def get_raw_data(start_date, end_date): <NEW_LINE> <INDENT> if not end_date: <NEW_LINE> <INDENT> end_date = datetime.datetime.now() <NEW_LINE> <DEDENT> if not start_date: <NEW_LINE> <INDENT> start_date = end_date - datetime.timedelta(days=SETA_WINDOW) <NEW_LINE> <DEDENT> url = HOST + "data/seta/?startDate=%s&endDate=%s...
Reach the data/seta endpoint for all failures that have been marked as "fixed by commit" The endpoint returns a dictionary with a key per revision or bug ID (the bug ID is used for intermittent failures and the revision is used for real failures). The failures for *real failures* will contain all jobs that have been s...
625941d40a366e3fb873ea1a
def __init__(self, file=None, idx="data_config"): <NEW_LINE> <INDENT> self.idx = idx <NEW_LINE> self.path = {} <NEW_LINE> self.data_idx = None <NEW_LINE> if file is not None: <NEW_LINE> <INDENT> if not os.path.exists(file): sys.exit("data-config [%s] does not exists" % file) <NEW_LINE> else: cfg = json.load(open(file, ...
data configurations
625941d407f4c71912b11683
def approx_pattern_and_reverse_complement_count(pattern: str, text: str, d: int) -> int: <NEW_LINE> <INDENT> pattern_frequency = approx_pattern_count(pattern, text, d) <NEW_LINE> rc_pattern_frequency = approx_pattern_count(reverse_complement(pattern), text, d) <NEW_LINE> return pattern_frequency + rc_pattern_frequency
Finds the frequency of a pattern and its reverse complement in a text, and all patterns within a hamming distance d
625941d430c21e258bdfa69d
def combine_batch_tables(batches, source, table_name): <NEW_LINE> <INDENT> print('Combining batch summary tables:') <NEW_LINE> table_list = [] <NEW_LINE> for batch in batches: <NEW_LINE> <INDENT> sys.stdout.write(f'\r{source} {batch}/{batches[-1]}') <NEW_LINE> batch_table = load_batch_table(batch, source=source, table_...
Combines summary files of given batches into single table
625941d496565a6dacc8f8ca
def run_loop(loop_init_object: Loop_init, leave_message: str = "Bye!"): <NEW_LINE> <INDENT> from threading import Thread <NEW_LINE> from time import sleep <NEW_LINE> set_namespace("main", callback=False if gget("preload_command") else True) <NEW_LINE> gset("leave_message", leave_message) <NEW_LINE> t = Thread(target=lo...
run_loop Args: loop_init_object (Loop_init): Loop Init class leave_message (str, optional): The message when you leave. Defaults to 'Bye!'.
625941d485dfad0860c3b05a
def update(self): <NEW_LINE> <INDENT> with self.mutex: <NEW_LINE> <INDENT> if (time.time() - self._updatets) >= self.scan_interval: <NEW_LINE> <INDENT> _LOGGER.debug("Updating") <NEW_LINE> try: <NEW_LINE> <INDENT> self.cube.update() <NEW_LINE> <DEDENT> except timeout: <NEW_LINE> <INDENT> _LOGGER.error("Max!Cube connect...
Pull the latest data from the MAX! Cube.
625941d4090684286d50eee6
def on_status(self, status: Status) -> Union[bool, None]: <NEW_LINE> <INDENT> if time() >= self.start + self.max_exec_time: <NEW_LINE> <INDENT> log('Stream closed due to filter constraints being met.') <NEW_LINE> self.current_analyses_table.delete(id=self.current_analysis_id) <NEW_LINE> return False <NEW_LINE> <DEDENT>...
Handler called every time a new status appears on the stream. Here, we get information about the Tweet and store it in the database. This is also possibly where the call to the analyser will go, although Twitter mandates a certain processing speed so analysis may have to be done by a cron job. If False is returned, ...
625941d4a219f33f34628b67
def get_tag(self) -> int: <NEW_LINE> <INDENT> return self._tag
returns the tag of the node :return: tag: float
625941d4097d151d1a223058
def _build_lh_01(self): <NEW_LINE> <INDENT> basis_index0 = self.basis_index[0] <NEW_LINE> basis_index1 = self.basis_index[1] <NEW_LINE> func_00 = self.func_lh(basis_index0, basis_index0, 0, 1) <NEW_LINE> func_01 = self.func_lh(basis_index0, basis_index1, 0, 1) <NEW_LINE> func_10 = self.func_lh(basis_index1, basis_index...
Build the LH_01 matrix LH_01 = [[L(0, 0) * H(0, 1), L(0, 0) * H(1, 1)], [L(1, 0) * H(0, 1), L(1, 0) * H(1, 1)]] Sets: LH_01 Returns: None
625941d4cc40096d61595b50
def sort(arr: list) -> list: <NEW_LINE> <INDENT> import timsortyer as so <NEW_LINE> if str(type(arr[0])) == "<class 'int'>": <NEW_LINE> <INDENT> return so.sort_int(arr) <NEW_LINE> <DEDENT> elif str(type(arr[0])) == "<class 'float'>": <NEW_LINE> <INDENT> return so.sort_float(arr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IN...
Timsort built in Rust.
625941d455399d3f055888b4
def plus_one(number): <NEW_LINE> <INDENT> return number + 1
Adds one to the number
625941d4287bf620b61d3c63