code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def compute_pagerank(urls, inlinks, outlinks, b=.85, iters=20): <NEW_LINE> <INDENT> pass <NEW_LINE> pagerank = defaultdict.fromkeys(urls,1.0) <NEW_LINE> for iter in range(iters): <NEW_LINE> <INDENT> for url in urls: <NEW_LINE> <INDENT> sum_temp = 0.0 <NEW_LINE> for cs in inlinks[url]: <NEW_LINE> <INDENT> length = len(o... | Return a dictionary mapping each url to its PageRank.
The formula is R(u) = (1/N)(1-b) + b * (sum_{w in B_u} R(w) / (|F_w|)
Initialize all scores to 1.0.
Params:
urls.......SortedList of urls (names)
inlinks....SortedDict mapping url to list of in links (backlinks)
outlinks...Sorteddict mapping url to list of o... | 625941cba17c0f6771cbe120 |
def test_request_unknown(self): <NEW_LINE> <INDENT> self.call_api('request', body={'task_id': '12310'}, status=404) | Asserts that 404 is raised for unknown tasks. | 625941cb85dfad0860c3af2a |
def pointed_awarded_for(user, action): <NEW_LINE> <INDENT> return settings.AWARD_POINTS[action] | user not currently used
:param user:
:param action:
:return: | 625941cb9b70327d1c4e0ea4 |
def test_dict_init(self): <NEW_LINE> <INDENT> self.assertIs(type(self.model3.name), str) <NEW_LINE> self.assertEqual(self.model3.name, "Erwin") <NEW_LINE> self.assertIs(type(self.model3.my_number), int) <NEW_LINE> self.assertEqual(self.model3.my_number, 42) <NEW_LINE> self.assertIs(type(self.model3.test), str) <NEW_LIN... | testing the dictionary initilization of this model | 625941cb796e427e537b0695 |
def resolve(self): <NEW_LINE> <INDENT> t2resolv = [] <NEW_LINE> if hasattr(self._sig, 'tret'): <NEW_LINE> <INDENT> t2resolv.append(self._sig.tret) <NEW_LINE> <DEDENT> if hasattr(self._sig, 'tparams') and self._sig.tparams is not None: <NEW_LINE> <INDENT> for p in self._sig.tparams: <NEW_LINE> <INDENT> t2resolv.append(p... | Process the signature and find definition for type. | 625941cb94891a1f4081bb78 |
def global_pose_clb(data): <NEW_LINE> <INDENT> global origin_pose, current_global_pose, local_pose_msg, heiht <NEW_LINE> if origin_pose is None: <NEW_LINE> <INDENT> rospy.logwarn("%s: Geodetic reference point is not set!" "Set it as Geodetic world_frame pose." % rospy.get_name()) <NEW_LINE> return <NEW_LINE> <DEDENT> c... | Robot Geodetic coordinates from GPS callback.
:param data: GPS data
:type data: sensor_msgs.msg.NavSatFix
:type origin_pose: sensor_msgs.msg.NavSatFix
:type current_global_pose: NavSatFix
:type local_pose_msg: PoseStamped | 625941cb956e5f7376d70f3d |
def convertToTitle(self, n): <NEW_LINE> <INDENT> res = "" <NEW_LINE> while n: <NEW_LINE> <INDENT> h = (n - 1) % 26 <NEW_LINE> res = chr(ord('A') + h) + res <NEW_LINE> n = (n - 1) / 26 <NEW_LINE> <DEDENT> return res | :type n: int
:rtype: str | 625941cbdd821e528d63b278 |
def get_day_off(person_id, date): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> day_off = DayOff.get_by(person_id=person_id, date=date) <NEW_LINE> <DEDENT> except DataError: <NEW_LINE> <INDENT> raise WrongDateFormatException <NEW_LINE> <DEDENT> if day_off is not None: <NEW_LINE> <INDENT> return day_off.serialize() <NEW_... | Return day off for given person and date. | 625941cb004d5f362079a402 |
def documentPage(self, path): <NEW_LINE> <INDENT> index = self.documentIndex(path) <NEW_LINE> if index != -1: <NEW_LINE> <INDENT> return index / (self.rows * self.columns) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return -1 | Return the browser page index for the document specified by the path. | 625941cb7c178a314d6ef52e |
def output(pin_number, pin_voltage): <NEW_LINE> <INDENT> if __LOCAL_MODE__: <NEW_LINE> <INDENT> logger.info("Set pin {} to {}".format(pin_number, pin_voltage)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> GPIO.output(pin_number, pin_voltage) | GPIO pin output. | 625941cb96565a6dacc8f79b |
def findJudge(self, n: int, trust: List[List[int]]) -> int: <NEW_LINE> <INDENT> if n == 1 and not trust: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> n_set = set(range(1, n + 1)) <NEW_LINE> trust_set = dict() <NEW_LINE> for t in trust: <NEW_LINE> <INDENT> if t[0] in n_set: <NEW_LINE> <INDENT> n_set.remove(t[0]) <NE... | Runtime: 1354 ms, faster than 5.04%
Memory Usage: 18.8 MB, less than 97.64%
1 <= n <= 1000
0 <= trust.length <= 10^4
trust[i].length == 2
All the pairs of trust are unique.
ai != bi
1 <= ai, bi <= n
:param n:
:param trust:
:return: | 625941cb507cdc57c6306da9 |
def get_derived_fluent_value(self, fluent_name, params): <NEW_LINE> <INDENT> raise NotImplementedError() | Returns the current value of the given derived fluent with the given parameters.
:param str fluent_name: the name of the derived fluent.
:param params:
:rtype: object | 625941cbe64d504609d7490f |
@cross_origin() <NEW_LINE> @app.route('/bar') <NEW_LINE> def barchart(): <NEW_LINE> <INDENT> if 'stress' in request.args: <NEW_LINE> <INDENT> return json.dumps({ 'bar-{}'.format(k): rr_list(max_range=STRESS_MAX_POINTS) for k in range(STRESS_MAX_POINTS) }) <NEW_LINE> <DEDENT> return json.dumps({ "bar1": [1, 2, 30, 12, 1... | Fake endpoint. | 625941cb8a43f66fc4b54135 |
@pytest.mark.parametrize( 'actual, expected', [ ((9.6, 3.4), 6.2), ((-7.5, -2.6), -4.9), ((0, 0), 0), ]) <NEW_LINE> def test_sub(actual, expected): <NEW_LINE> <INDENT> assert calc.sub(*actual) == pytest.approx(expected) | Test corner cases of sub function | 625941cb656771135c3eb93e |
def getMaxKey(self) -> str: <NEW_LINE> <INDENT> cur_node = self.tail.prev <NEW_LINE> if not cur_node.keys: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> key = cur_node.keys.pop() <NEW_LINE> cur_node.keys.add(key) <NEW_LINE> return key | Returns one of the keys with maximal value. | 625941cb460517430c394255 |
def iter_chunkify(mylist, n_chunks): <NEW_LINE> <INDENT> for indices in _iter_chunkify_nrange(len(mylist), n_chunks): <NEW_LINE> <INDENT> yield [mylist[i] for i in indices] | Makes n_chunks chunks out of mylist. | 625941cb8a349b6b435e8243 |
def check_installed(name, path): <NEW_LINE> <INDENT> return show_current(name) == path | Check if the current highest-priority match for a given alternatives link
is set to the desired path
CLI Example::
salt '*' alternatives.check_installed name path | 625941cb0a366e3fb873e8e9 |
def _add_userdatas_custom_headers(writer, query): <NEW_LINE> <INDENT> from autonomie_base.models.base import DBSESSION <NEW_LINE> from autonomie.models.user.user import COMPANY_EMPLOYEE <NEW_LINE> query = DBSESSION().query( func.count(COMPANY_EMPLOYEE.c.company_id).label('nb') ) <NEW_LINE> query = query.group_by(COMPAN... | Specific to userdatas exports
Add custom headers that are not added through automation
Add headers for code_compta | 625941cb1b99ca400220ab81 |
def load_amazon(source_name, target_name, data_folder=None): <NEW_LINE> <INDENT> if data_folder is None: <NEW_LINE> <INDENT> data_folder = '../data/' <NEW_LINE> <DEDENT> source_file = data_folder + source_name + '_train.svmlight' <NEW_LINE> target_file = data_folder + target_name + '_train.svmlight' <NEW_LINE> test_fil... | Load the amazon sentiment datasets from svmlight format files
inputs:
source_name : name of the source dataset
target_name : name of the target dataset
data_folder : path to the folder containing the files
outputs:
xs : training source data matrix
ys : training source label vector
xt : training ... | 625941cbcc0a2c11143dcf60 |
def listMetadataFormats(self, identifier=None): <NEW_LINE> <INDENT> return [ ( OAI_DC_MDPREFIX, "http://www.openarchives.org/OAI/2.0/oai_dc.xsd", "http://www.openarchives.org/OAI/2.0/oai_dc/", ), ( OAI_FAIRDATA_DATACITE_MDPREFIX, "https://schema.datacite.org/meta/kernel-4.1/metadata.xsd", "https://schema.datacite.org/m... | Implement OAI-PMH verb listMetadataFormats . | 625941cbdc8b845886cb5604 |
def insert_secret_in_settings(): <NEW_LINE> <INDENT> secret = secret_gen() <NEW_LINE> settings_file = find_settings() <NEW_LINE> with open(settings_file, 'r') as f: <NEW_LINE> <INDENT> content = f.read() <NEW_LINE> <DEDENT> regex = re.compile(SECRET_KEY_REGEX, re.MULTILINE) <NEW_LINE> settings_with_secret = regex.sub('... | Finds settings.py and replaces its secret key phrase. | 625941cbff9c53063f47c2c3 |
def start_driver(self, browser_type, capabilities, remote_driver_url, config_section): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> extensions = capabilities['chromeOptions']['extensions'] <NEW_LINE> capabilities['chromeOptions']['extensions'] = ['...'] <NEW_LINE> print("Starting remote driver", capabilities) <NEW_LINE... | Call remote browser (driver) | 625941cbb5575c28eb68e0d0 |
def to_dict(self): <NEW_LINE> <INDENT> W = self.W.asarray() if self.on_gpu else self.W <NEW_LINE> result = { "type": self._name, "conn": self.conn, "W": W, } <NEW_LINE> return result | Convert self into a dict. | 625941cbd7e4931a7ee9dfed |
def toggle(self, **kwargs) -> None: <NEW_LINE> <INDENT> if self.is_closed: <NEW_LINE> <INDENT> self.open_cover(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.close_cover(**kwargs) | Toggle the entity. | 625941cbd164cc6175782e1d |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _x = self <NEW_LINE> buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) <NEW_LINE> _x = self.header.frame_id <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941cbec188e330fd5a86f |
def test(request=None): <NEW_LINE> <INDENT> if request: <NEW_LINE> <INDENT> logging.info(request) <NEW_LINE> response = "OK" <NEW_LINE> return Response(response) <NEW_LINE> <DEDENT> return None | Used for testing | 625941cb7d847024c06be38b |
def write_cars_to_csv(csv_name, csv_header, csv_rows): <NEW_LINE> <INDENT> if os.path.exists(csv_name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.remove(csv_name) <NEW_LINE> print("delete previous {}".format(csv_name)) <NEW_LINE> <DEDENT> except OSError: <NEW_LINE> <INDENT> print("error in deleting {}".format(csv... | create csv file and write rows to the csv file
Args:
csv_name: csv filename
csv_header: csv header name
csv_rows: csv rows | 625941cb63b5f9789fde71b5 |
def lengthOfLastWord(self, s): <NEW_LINE> <INDENT> s = s.strip() <NEW_LINE> for index, item in enumerate(s[::-1]): <NEW_LINE> <INDENT> if item == ' ' and index != 0: <NEW_LINE> <INDENT> return index <NEW_LINE> <DEDENT> <DEDENT> return len(s) | :type s: str
:rtype: int | 625941cb099cdd3c635f0d2b |
def __init__(self, phrase): <NEW_LINE> <INDENT> self.weighted_values_dict = { "aggressive": 5, "passive": 1, "mentoring": 2, "inquisitive": 1, "transaction": 2, "explanatory": 1, "planning": 2, "social": 3 } <NEW_LINE> self.behavior = Behavior(phrase) <NEW_LINE> self.behavior.find_behaviors() <NEW_LINE> self.behavior_d... | Initialization
Method arguments:
-----------------
phrase(string) -- phrase passed in | 625941cb15fb5d323cde0bdf |
def SetDrawnBackgroundColour(self, colour): <NEW_LINE> <INDENT> self._metafiles[self._currentAngle].SetBackgroundColour(colour) | Set the current background colour for the current metafile. | 625941cb097d151d1a222f2a |
def unregister_resource_for_model(model): <NEW_LINE> <INDENT> del _model_to_resources[model] | Remove the official location for a model.
Args:
model (Model): The model associated with the resource to remove. | 625941cb30c21e258bdfa56d |
def _minx(points): <NEW_LINE> <INDENT> assert points <NEW_LINE> num_dim = len(points[0]) <NEW_LINE> minx = numpy.array([min([point[var_j] for point in points]) for var_j in range(num_dim)]) <NEW_LINE> return minx | Returns a 1d array where entry i is the minimum value
encountered in the ith dimension from among the points. | 625941cb187af65679ca51ef |
def main(): <NEW_LINE> <INDENT> VERSION = '1.1' <NEW_LINE> parser = argparse.ArgumentParser(description='pounce argument information.') <NEW_LINE> parser.add_argument('-f', '--file', nargs=1, action='store', dest='file', help='Given the full path,load each URL in the file.') <NEW_LINE> parser.add_argument('-u', '--url... | Parses arguments and calls relevant functions and methods. | 625941cb73bcbd0ca4b2c146 |
def odd_or_even(arr): <NEW_LINE> <INDENT> return 'even' if sum(arr) % 2 == 0 else 'odd' | Returns even if sum of arr is even else odd | 625941cbac7a0e7691ed419d |
@login_required <NEW_LINE> def account_settings(request): <NEW_LINE> <INDENT> show_success = False <NEW_LINE> member = models.UserProfile.objects.get(user=request.user) <NEW_LINE> if request.method == 'GET': <NEW_LINE> <INDENT> form = forms.AccountSettingForm(initial={'member_id': member.id, 'handle':member.handle, 'em... | Go to Edit account settings | 625941cb3eb6a72ae02ec5ac |
def move_unit(self, start_cell, end_cell): <NEW_LINE> <INDENT> u = self.units[start_cell] <NEW_LINE> path = self.find_path(start_cell, end_cell, True) <NEW_LINE> u.move_path = path <NEW_LINE> self.remove_unit(start_cell, move=True) <NEW_LINE> if not self.add_unit(end_cell, u.unit_id, u, move=True): <NEW_LINE> <INDENT> ... | Handles movement of a unit.
Args:
start_cell (Hexagon): cell the unit is moving from.
end_cell (Hexagon): cell a unit is moving to. | 625941cb236d856c2ad448aa |
def put(self, data): <NEW_LINE> <INDENT> self._elements.insert(0, data) | Inserts an element at the front of the stack.
:param data: The data.
>>> my_stack = Stack()
>>> my_stack.put(1)
>>> my_stack
[1]
>>> my_stack = Stack([2, 3, 4])
>>> my_stack.put(1)
>>> my_stack
[1, 2, 3, 4] | 625941cb5fcc89381b1e178f |
def __init__(self, mention_line, trreader): <NEW_LINE> <INDENT> mention_line = mention_line.strip() <NEW_LINE> split = mention_line.split("\t") <NEW_LINE> (self.mid, self.wid, self.wikititle) = split[0:3] <NEW_LINE> self.start_token = int(split[3]) <NEW_LINE> self.end_token = int(split[4]) <NEW_LINE> self.surface = spl... | mention_line : Is the string line stored for each mention
mid wid wikititle start_token end_token surface tokenized_sentence all_types | 625941cbcad5886f8bd270a9 |
def test_get_characters_character_id_calendar_event_id(self, api): <NEW_LINE> <INDENT> pass | Test case for get_characters_character_id_calendar_event_id
Get an event | 625941cb6fb2d068a760f16d |
def find_match(list1, list2, nr1, nr2, mincount=3): <NEW_LINE> <INDENT> len1 = len(list1) <NEW_LINE> len2 = len(list2) <NEW_LINE> hit1 = None <NEW_LINE> hit2 = None <NEW_LINE> idx1 = nr1 <NEW_LINE> idx2 = nr2 <NEW_LINE> while ((idx1 < len1) or (idx2 < len2)): <NEW_LINE> <INDENT> i = nr1 <NEW_LINE> while i <= idx1: <NE... | searches next matching pattern with lenght mincount
if no pattern is found len of the both lists is returned | 625941cb7047854f462a14da |
def __call__(self, doc): <NEW_LINE> <INDENT> pkgname = self.db.get_pkgname(doc) <NEW_LINE> if self.available_only: <NEW_LINE> <INDENT> if (not pkgname in self.cache and not doc.get_value(XapianValues.ARCHIVE_CHANNEL) == AVAILABLE_FOR_PURCHASE_MAGIC_CHANNEL_NAME): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DE... | return True if the package should be displayed | 625941cbe8904600ed9f1ffd |
def __init__(self, activated=None, authorities=None, card_cvc=None, card_exp_month=None, card_exp_year=None, card_number=None, company_id=None, created_date=None, email=None, first_name=None, id=None, lang_key=None, last_modified_by=None, last_modified_date=None, last_name=None, login=None, password=None, phone_number=... | ManagedUserDTO - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941cbab23a570cc250252 |
def ageoff(self, remove_from): <NEW_LINE> <INDENT> edge_time = (self.edge_time).copy() <NEW_LINE> for key, value in edge_time.iteritems(): <NEW_LINE> <INDENT> if value <= remove_from: <NEW_LINE> <INDENT> edges = key.split('~') <NEW_LINE> source_vertex = edges[0] <NEW_LINE> end_vertex = edges[1] <NEW_LINE> self.delete(... | Removes edges and their corresponding vertices if it is <= time window of the latest tweet | 625941cba8ecb033257d319d |
def test_sender_not_allowed(self): <NEW_LINE> <INDENT> test_message = email.message.Message() <NEW_LINE> test_message['From'] = 'sender@test.com' <NEW_LINE> test_message['Subject'] = 'Test' <NEW_LINE> test_message['Date'] = datetime.datetime(2016, 1, 1, 12, 44, 57) <NEW_LINE> test_message.set_payload("Test Message") <N... | Test not whitelisted emails. | 625941cb956e5f7376d70f3e |
def load_mnist(path, kind='train'): <NEW_LINE> <INDENT> images_path = glob('./%s/%s*3-ubyte' % (path, kind))[0] <NEW_LINE> labels_path = glob('./%s/%s*1-ubyte' % (path, kind))[0] <NEW_LINE> with open(labels_path, 'rb') as lbpath: <NEW_LINE> <INDENT> magic, n = struct.unpack('>II', lbpath.read(8)) <NEW_LINE> labels = np... | Load MNIST data from `path` | 625941cbd7e4931a7ee9dfee |
def value_changed(self, value): <NEW_LINE> <INDENT> if self._value.value_id == value.value_id or self._value.node == value.node: <NEW_LINE> <INDENT> _LOGGER.debug('Value changed for label %s', self._value.label) <NEW_LINE> self.update_properties() <NEW_LINE> self.schedule_update_ha_state() | Called when a value has changed on the network. | 625941cb71ff763f4b54975b |
def testCode5Case3(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> print('Code5Case3') <NEW_LINE> print("run helper...") <NEW_LINE> code = str(51) <NEW_LINE> args = ['python', 'helper.py', code] <NEW_LINE> p = subprocess.Popen(args, cwd=(helper_dir)) <NEW_LINE> time.sleep(connect_worst_timeout) <NEW_LINE> client.cr... | subscribe same topic twice | 625941cb2ae34c7f2600d201 |
def test_append_invalid_element(self): <NEW_LINE> <INDENT> self.assertRaises(TypeError, self.bundle.append, {}) | Test appending an invalid element. | 625941cb9b70327d1c4e0ea5 |
def read_namespaced_replica_set_with_http_info(self, name, namespace, **kwargs): <NEW_LINE> <INDENT> all_params = ['name', 'namespace', 'pretty', 'exact', 'export'] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE... | read the specified ReplicaSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_replica_set_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of t... | 625941cb5fdd1c0f98dc0303 |
def merge(self, story, *keys): <NEW_LINE> <INDENT> meta = {key: i for i, key in enumerate(keys, 1)} <NEW_LINE> return story.merge(meta=meta) | Returns a story containing the requested meta keys. | 625941cb046cf37aa974ce18 |
def addComplexResult(self, fNames, perfToolName, metricName, values, units, startTimes, endTimes): <NEW_LINE> <INDENT> if self.debug >= self.NO_WRITE: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> metric_id = self.findResourceByName(metricName) <NEW_LINE> if metric_id == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <D... | Adds a new complex result to the database
This method is for the PTDF type COMPLEXRESULT. COMPLEXRESULT is very close
to RESULT, but COMPLEXRESULT has an array of values and timestamps for a single
focus, metric, and performance tool.
Returns 0 if fName, perfToolName, metricName are not already defined in DB
Return... | 625941cb6aa9bd52df036e75 |
def get_median_distance(points): <NEW_LINE> <INDENT> projected_points = [] <NEW_LINE> for point in points: <NEW_LINE> <INDENT> projected_points.append(convert_to_3d(point)) <NEW_LINE> <DEDENT> distance = find_median_min_distance(projected_points) <NEW_LINE> return distance | Given a list of lat/long pairs, find the median of the minimum distances
between any two points. Distance is in kilometers.
Inputs:
- points: A list of tuples of lat/long pairs
Returns:
- An integer of the median kilometer distance | 625941cb851cf427c661a5e0 |
def DEFAULT_HOOK(self, *args, **kwargs): <NEW_LINE> <INDENT> pass | empty hook, return nothing | 625941cb7b25080760e3952a |
def import_realm(self, payload): <NEW_LINE> <INDENT> data_raw = self.raw_post(URL_ADMIN_REALMS, data=json.dumps(payload)) <NEW_LINE> return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[201]) | Import a new realm from a RealmRepresentation. Realm name must be unique.
RealmRepresentation
https://www.keycloak.org/docs-api/8.0/rest-api/index.html#_realmrepresentation
:param payload: RealmRepresentation
:return: RealmRepresentation | 625941cb16aa5153ce362549 |
def double_find(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def double_func(*args, **kwargs): <NEW_LINE> <INDENT> result = func(*args, **kwargs) <NEW_LINE> if result: <NEW_LINE> <INDENT> return result <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return func(*args, **kwargs) <NEW_LINE> <DEDENT> <DEDENT> return d... | this is a wrapper. if the func return None then re-execute again. | 625941cb0a50d4780f666f63 |
def format_for_server(self): <NEW_LINE> <INDENT> self._setup_installed() <NEW_LINE> final = [val for (key, val) in list(self.installed.items())] <NEW_LINE> return final | Convert the format we store in this object (which is a little
easier to work with) into the format the server expects for the
consumer. | 625941cb8e71fb1e9831d87a |
def i_book_ticket(intent_request): <NEW_LINE> <INDENT> source = intent_request['invocationSource'] <NEW_LINE> slots = get_slots(intent_request) <NEW_LINE> user_id = intent_request['userId'] if intent_request['userId'] is not None else '0' <NEW_LINE> if source == 'DialogCodeHook': <NEW_LINE> <INDENT> check_res = validat... | Called when the user triggers the BookTickets intent. | 625941cb91af0d3eaac9bae9 |
def search_col(self, j, invert): <NEW_LINE> <INDENT> fg = 1 <NEW_LINE> if invert: <NEW_LINE> <INDENT> fg = 0 <NEW_LINE> <DEDENT> col = self.data[:, j] <NEW_LINE> found = np.argwhere(col == fg) <NEW_LINE> if len(set(found.flatten())) >= 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret... | "
add description | 625941cbcc0a2c11143dcf61 |
def add(self, widget): <NEW_LINE> <INDENT> BaseRadioGroup.add(self, widget) <NEW_LINE> if widget.state: <NEW_LINE> <INDENT> self._set_active(widget) <NEW_LINE> <DEDENT> return widget | Add a widget to the group
If if is active, it becomes the group's new active widget, possibly
disabling the previously active one. | 625941cb4e696a04525c951c |
def router(environ, start_response): <NEW_LINE> <INDENT> routes = [ (r'^$', index), (r'packages/?$', pkg_index), (r'packages/([^\/]+)/$', pkg_files), (r'packages/([^/]+)/([^/]+)$', download_dist) ] <NEW_LINE> parameters = parse_qs(environ.get('QUERY_STRING', '')) <NEW_LINE> path = environ.get('PATH_INFO', '').lstrip('/... | Dispatch incoming requests to the appropriate
handlers. | 625941cbab23a570cc250253 |
def test_sync_date(self): <NEW_LINE> <INDENT> xknx = XKNX(loop=self.loop) <NEW_LINE> datetime = DateTime(xknx, "TestDateTime", group_address='1/2/3', broadcast_type=DateTimeBroadcastType.DATE) <NEW_LINE> with patch('time.localtime') as mock_time: <NEW_LINE> <INDENT> mock_time.return_value = time.struct_time([2017, 1, 7... | Test sync function / sending group reads to KNX bus. | 625941cb0383005118ecf6b3 |
def update_command(self, handler: Handler, doc: str) -> None: <NEW_LINE> <INDENT> self._handler = handler <NEW_LINE> self.doc = doc | update handler and doc in command | 625941cbd486a94d0b98e216 |
def get_emulsifiation_wind(self, time): <NEW_LINE> <INDENT> wave_height = self.water.wave_height <NEW_LINE> U = self.wind.get_value(time)[0] <NEW_LINE> if wave_height is None: <NEW_LINE> <INDENT> return U <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return max( U, self.comp_psuedo_wind(wave_height) ) | Return the right wind for the wave climate
If a wave height was specified, then you need the greater of the real or
psuedo wind.
If not, then you need the actual wind.
The idea here is that if there is a low wind, but the user specified waves,
we really want emulsification that makes sense for the waves. But if the... | 625941cbf548e778e58cd64e |
def parse_intuitive_duration(intuitive_string): <NEW_LINE> <INDENT> intuitive_duration_regex = re.compile( r'^{amount}(\s+)?({minutes}|{hours}|{days}|{weeks}|{months})$'.format( amount=r'(?P<amount>\d+(\.\d+)?|(\d+)?\.\d+)', minutes=r'(?P<minutes>m|minute(s)?)', hours=r'(?P<hours>h|hour(s)?)', days=r'(?P<days>d|day(s)?... | Takes an intuitive duration string returns a duration object.
Examples for valid input:
'15m': 15 minutes
'20h': Twenty hours
'6d': Six days
'1w': One week
:param intuitive_string: a python string
:return: timedelta or input value | 625941cb7b180e01f3dc48ce |
def separate_left(sc, sci): <NEW_LINE> <INDENT> if sci.buttons & 1 << 31: <NEW_LINE> <INDENT> if sci.buttons & Masks.LPADTOUCH: <NEW_LINE> <INDENT> pad_x, pad_y = sci.lpad_x, sci.lpad_y <NEW_LINE> joy_x, joy_y = separate_left.prev <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pad_x, pad_y = separate_left.prev <NEW_LINE... | Detangle the left touchpad and joystick values and return both. | 625941cbf9cc0f698b1406cd |
def disable_old_files(self): <NEW_LINE> <INDENT> if self.channel == amo.RELEASE_CHANNEL_LISTED: <NEW_LINE> <INDENT> qs = File.objects.filter(version__addon=self.addon_id, version__lt=self.id, version__deleted=False, status__in=[amo.STATUS_AWAITING_REVIEW, amo.STATUS_PENDING]) <NEW_LINE> for f in qs: <NEW_LINE> <INDENT>... | Disable files from versions older than the current one and awaiting
review. Used when uploading a new version.
Does nothing if the current instance is unlisted. | 625941cb627d3e7fe0d68f20 |
def __call__(self, file_path, file_name=None): <NEW_LINE> <INDENT> if file_name is None: <NEW_LINE> <INDENT> file_name = os.path.basename(file_path) <NEW_LINE> <DEDENT> with open(file_path, 'rb') as file_data: <NEW_LINE> <INDENT> files = {'files': (file_name, file_data)} <NEW_LINE> return self._server.put('file/upload/... | Top-level File Upload API call.
Upload a file.
.. note:: According to Fleep Docs, their endpoint supports
multiple-files, however, even though it doesn't fail, it seems to
always return a single file_id. Until we clear what happens here,
this method is supporting single-file upload only.
Returns file_id which needs ... | 625941cb5166f23b2e1a522a |
def test_flow_exception_expected(self): <NEW_LINE> <INDENT> flow_exception = FlowException("error message") <NEW_LINE> self.assertEqual(flow_exception.message, "error message") | Test for FlowException class
| 625941cb73bcbd0ca4b2c147 |
def getUnaryOperators(self): <NEW_LINE> <INDENT> return self.__unary_ops | Gets the unary operators known to this parser.
:rtype: list | 625941cb92d797404e30425b |
def pretty_print(self): <NEW_LINE> <INDENT> print(self.pretty_format()) | Pretty-print the computation steps of this integrator. | 625941cb01c39578d7e74f0c |
def __call__(self, initial_state, helper): <NEW_LINE> <INDENT> with tf.variable_scope('attention_decoder', reuse=self.reuse): <NEW_LINE> <INDENT> if self.initial_state is None: <NEW_LINE> <INDENT> self._setup(initial_state, helper) <NEW_LINE> <DEDENT> if self.mode == tf.contrib.learn.ModeKeys.TRAIN: <NEW_LINE> <INDENT>... | Args:
initial_state: A tensor or tuple of tensors used as the initial
rnn_cell state. Set to the final state of the encoder by default.
helper: An instance of `tf.contrib.seq2seq.Helper` to assist
decoding
Returns:
A tuple of `(outputs, final_state)`
outputs: A tensor of `[T_out, B, ... | 625941cb7d847024c06be38c |
def binContactBrowseInputContactFile(self): <NEW_LINE> <INDENT> file_choices = " Text file (*.txt *.dat);; All file (*.*)" <NEW_LINE> path = QFileDialog.getOpenFileName(self, 'Open File', guiHelpers.lastVisitedDir, file_choices) <NEW_LINE> guiHelpers.lastVisitedDir = os.path.dirname(path[0]) if path is not None else Fa... | To get compressed file with full path
| 625941cbbe7bc26dc91cd6d1 |
def loggamma_vec(x_vec, a, b): <NEW_LINE> <INDENT> p_x = a * np.log(b) - np.log(factorial(a - 1.0)) + (a - 1.0) * np.log(x_vec) - b * x_vec <NEW_LINE> return np.sum(p_x) | sum_i log Gamma(x_vec[i], a[i], b[i])
Parameters
----------
x_vec : np.array
a : np.array or float
b : np.array or float
Returns
-------
float | 625941cbd6c5a1020814411c |
def parseClassPages(context): <NEW_LINE> <INDENT> def parse_context(url): <NEW_LINE> <INDENT> return getPages(url) <NEW_LINE> <DEDENT> index = 1 <NEW_LINE> while index <= count: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if index == 1: <NEW_LINE> <INDENT> html = parse_context(context['url']) <NEW_LINE> <DEDENT> else:... | 解析分类页面 | 625941cb96565a6dacc8f79c |
def height(self): <NEW_LINE> <INDENT> return self.rank()+1 | Return the height (number of elements in a longest chain) of the poset.
EXAMPLES::
sage: P = Poset({0:[1],2:[3,4],4:[5,6]})
sage: P.height()
3
sage: Posets.PentagonPoset().height()
4
TESTS::
sage: Poset().height()
0 | 625941cb56ac1b37e62642a1 |
@pytest.mark.django_db <NEW_LINE> def test_associate_user_already_in_company(logged_client, user): <NEW_LINE> <INDENT> company = CompanyFactory.create() <NEW_LINE> user_company = UserCompanyProfileFactory.create(company=company, user=user) <NEW_LINE> ERROR_USER_ALREADY_IN_COMPANY = ('Le usuarie que desea vincular ya ' ... | Should fail, redirect and send a warning message if the user is already in the company | 625941cb0383005118ecf6b4 |
def __init__(self, x, y, z=None, kind='spline'): <NEW_LINE> <INDENT> self._interp_function = None <NEW_LINE> if z is None: <NEW_LINE> <INDENT> self._interp_function = self.__get_1d_function(x, y, kind) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if len(x) == 1: <NEW_LINE> <INDENT> executor_1d = self.__get_1d_function... | Initialisation responsible also for finding coefficients of interpolation function.
If z is None then we assume that dataset if 1-D and is made by X and Y columns.
In case z is not None, then we interpret the data as 2-D.
:param x: array_like
The 1-d array of data-points x-coordinates, must be in strictly ascending or... | 625941cb63f4b57ef00011eb |
def create_volume(self, capacity, access_capabilities=None, capacity_sources=None, replica_infos=None, bootable=None): <NEW_LINE> <INDENT> properties = self._create_volume_request( capacity=capacity, access_capabilities=access_capabilities, capacity_sources=capacity_sources, replica_infos=replica_infos, bootable=bootab... | Create a new volume
:param capacity: Requested volume capacity in bytes
:param access_capabilities: List of volume access capabilities
:param capacity_sources: JSON for volume providing source
:param replica_infos: JSON for volume replica infos
:param bootable: Determines if the volume should be bootable
:returns: The... | 625941cbd268445f265b4f3f |
def lookup_by_keywords(self, keywords): <NEW_LINE> <INDENT> query = '"'+' '.join(keywords)+'"' <NEW_LINE> return self.lookup_by('keyword', query, list_func=True) | Returns a list of at most *max_seqs*
:class:`Sequence <sequence.Sequence>` objects which are
tagged with *keywords*. | 625941cb2eb69b55b151c980 |
def _code_error_syndrome(code, error_dicts, measurement_error_indices): <NEW_LINE> <INDENT> assert len(error_dicts) == len(measurement_error_indices) <NEW_LINE> step_errors = [] <NEW_LINE> step_syndromes = [] <NEW_LINE> for error_dict in error_dicts: <NEW_LINE> <INDENT> step_error_pauli = code.new_pauli() <NEW_LINE> fo... | Resolve to code, error and periodic FT syndrome.
:param code: Rotated planar code
:type code: RotatedPlanarCode
:param error_dicts: List of error dicts, e.g. [{'X': [(0, 0)]}, {'Y': [(1, 1), (1, 2)]}, ...]
:type error_dicts: list of dict
:param measurement_error_indices: List of measurement error indices, e.g. [[(1, 1... | 625941cb8e7ae83300e4b09e |
def __rand__(other): <NEW_LINE> <INDENT> pass | Given BTrees.IFBTree data structure, return weighted intersection | 625941cba79ad161976cc217 |
def file_and_parent(path): <NEW_LINE> <INDENT> folder, file_name = ntpath.split(path) <NEW_LINE> _, parent = ntpath.split(folder) <NEW_LINE> return (file_name, parent) | For a given path return the filename and name of the parent directory | 625941cb76e4537e8c351744 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, WithdrawCoin): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941cb4f88993c3716c139 |
def find_top_rpn_proposals( proposals, pred_objectness_logits, images, image_sizes, nms_thresh, pre_nms_topk, post_nms_topk, min_box_side_len, training, ): <NEW_LINE> <INDENT> num_images = len(images) <NEW_LINE> device = proposals[0].device <NEW_LINE> topk_scores = [] <NEW_LINE> topk_proposals = [] <NEW_LINE> level_ids... | Args:
proposals (list[Tensor]): (L, N, Hi*Wi*A, 4).
pred_objectness_logits: tensors of lenngth L.
nms_thresh (float): IoU threshold to use for NMS
pre_nms_topk (int): before nms
post_nms_topk (int): after nms
min_box_side_len (float): minimum proposal box side
training (bool): True if propos... | 625941cb8a43f66fc4b54137 |
def serialize(self) -> Dict[str, Any]: <NEW_LINE> <INDENT> return { 'is_complete': self.is_complete, 'matched_acquisitions': [x.serialize() for x in self.matched_acquisitions], } | Turn to a dict to be returned by the API and shown in the UI | 625941cb8a349b6b435e8244 |
def get_device_name(self, identity, device): <NEW_LINE> <INDENT> device_info = self._get_device(identity, device) <NEW_LINE> return device_info.get('Name', identity) | Get virtual media device name
:param identity: parent resource ID
:param device: device name
:returns: virtual media device name
:raises: `error.FishyError` | 625941cb656771135c3eb940 |
def set_precedence(self, precedence): <NEW_LINE> <INDENT> self.options['precedence'] = precedence | This sets the precedence between RULE-based and URL-based policies on the content switching
virtual server. The default precedence is RULE.
With the precedence set to RULE, incoming requests are evaluated against the content switching policies
created with the -rule argument (using the add cs policy CLI command).
If no... | 625941cbd4950a0f3b08c421 |
def _parse_timezone(val): <NEW_LINE> <INDENT> if not val: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if val == 'Z' or val == '+00:00': <NEW_LINE> <INDENT> return pytz.utc <NEW_LINE> <DEDENT> negative = val.startswith('-') <NEW_LINE> minutes = int(val[-2:]) <NEW_LINE> minutes += int(val[1:3]) * 60 <NEW_LINE> if nega... | Return a pytz.tzinfo object | 625941cb63d6d428bbe445c1 |
def _generate_fuzz_urls(self, url): <NEW_LINE> <INDENT> templates = open(Registry().get('wr_path') + "/bases/fuzzer-templates.txt").readlines() <NEW_LINE> result = [] <NEW_LINE> url = urlparse(url) <NEW_LINE> if len(url.query): <NEW_LINE> <INDENT> params = self._parse_params(url.query.strip()) <NEW_LINE> for template i... | Parse urls and make a fuzzer urls from it | 625941cbadb09d7d5db6c861 |
def get(self, *args, **kwargs): <NEW_LINE> <INDENT> items = list(kwargs) <NEW_LINE> inst = None <NEW_LINE> if len(items) == 1: <NEW_LINE> <INDENT> key = items[0] <NEW_LINE> if key.endswith("__exact"): <NEW_LINE> <INDENT> key = key[: -len("__exact")] <NEW_LINE> <DEDENT> if key in ("pk", self.model._meta.pk.attname): <NE... | Data entity lookup. | 625941cb460517430c394257 |
@conf.commands.register <NEW_LINE> def computeNIGroupAddr(name): <NEW_LINE> <INDENT> name = name.lower().split(".")[0] <NEW_LINE> record = chr(len(name))+name <NEW_LINE> h = md5(record.encode("utf8")) <NEW_LINE> h = h.digest() <NEW_LINE> addr = "ff02::2:%2x%2x:%2x%2x" % struct.unpack("BBBB", h[:4]) <NEW_LINE> return ad... | Compute the NI group Address. Can take a FQDN as input parameter | 625941cb283ffb24f3c559d3 |
def render(self) -> None: <NEW_LINE> <INDENT> for uuid, agent in zip(self.uuids, self.allSnaps): <NEW_LINE> <INDENT> if len(agent) == 0: <NEW_LINE> <INDENT> with Color.red(), Color.bold(): <NEW_LINE> <INDENT> print('** ERROR: no snapshots for {}'.format(uuid)) <NEW_LINE> <DEDENT> continue <NEW_LINE> <DEDENT> _agent = [... | Print these agents' snapshots in nice visual columns. | 625941cb4c3428357757c3f9 |
def optimal_string_alignment_similarity(s1, s2): <NEW_LINE> <INDENT> max_cost = max(len(s1), len(s2)) <NEW_LINE> if max_cost == 0: <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> return 1.0 - float(optimal_string_alignment_distance(s1, s2)) / max_cost | Computed as 1 - optimal_string_alignment_distance / max(len(s1), len(s2)) | 625941cb0a366e3fb873e8eb |
def test_fertility(): <NEW_LINE> <INDENT> test_path = tempfile.mkdtemp() <NEW_LINE> x_train, metadata = fertility(test_path) <NEW_LINE> try: <NEW_LINE> <INDENT> assert x_train.shape == (333, 10) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> shutil.rmtree(test_path) <NEW_LINE> raise() | Test module fertility.py by downloading
fertility.csv and testing shape of
extracted data has 333 rows and 10 columns | 625941cbd58c6744b4257d32 |
def get_angle_degrees_between(self, other: "Vec2d") -> float: <NEW_LINE> <INDENT> return math.degrees(self.get_angle_between(other)) | Get the angle between the vector and the other in degrees
:return: The angle (in degrees) | 625941cb1b99ca400220ab83 |
def is_SetSubSampling(hCam, mode): <NEW_LINE> <INDENT> if _is_SetSubSampling is None: <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> _hCam = _value_cast(hCam, ctypes.c_uint) <NEW_LINE> _mode = _value_cast(mode, ctypes.c_int) <NEW_LINE> ret = _is_SetSubSampling(_hCam, _mode) <NEW_LINE> return ret | :param hCam: c_uint (aka c-type: HIDS)
:param mode: c_int (aka c-type: INT)
:returns: success, or no success, that is the answer
:raises NotImplementedError: if function could not be loaded | 625941cb99fddb7c1c9de463 |
@step(r'I am on Busine.me loginpage') <NEW_LINE> def i_am_on_busineme_login_page(step): <NEW_LINE> <INDENT> name = "/login/" <NEW_LINE> full_url = django_url(name) <NEW_LINE> world.browser.response = world.browser.visit(full_url) | Verify if the actual page is the loginpage of the application. | 625941cbff9c53063f47c2c5 |
def _render_on_subplot(self, subplot): <NEW_LINE> <INDENT> options = self.options() <NEW_LINE> cmap = get_cmap(options['cmap']) <NEW_LINE> x0,x1 = float(self.xrange[0]), float(self.xrange[1]) <NEW_LINE> y0,y1 = float(self.yrange[0]), float(self.yrange[1]) <NEW_LINE> subplot.imshow(self.xy_data_array, origin='lower', cm... | TESTS:
A somewhat random plot, but fun to look at::
sage: x,y = var('x,y')
sage: density_plot(x^2-y^3+10*sin(x*y), (x, -4, 4), (y, -4, 4),plot_points=121,cmap='hsv')
Graphics object consisting of 1 graphics primitive | 625941cb97e22403b379d06b |
def get_atom(residue, atomname): <NEW_LINE> <INDENT> atoms = residue.get_list() <NEW_LINE> for atom in atoms: <NEW_LINE> <INDENT> if atom.get_name().lower() == atomname.lower() : <NEW_LINE> <INDENT> return atom <NEW_LINE> <DEDENT> <DEDENT> return "@@" | Given a residue and an atomname, this method sequentially
goes through the list and tries to find an atomname with
the given name ... on success this atom will be returned,
otherwise a trigger sequence will be returned.
@param residue: an Bio.PDB.Residue
@type residue: Bio.PDB.Residue
@param atomname: an atomname
@... | 625941cb29b78933be1e577e |
def __init__(self, data_path, keep_img=False, config=None): <NEW_LINE> <INDENT> self.path = None <NEW_LINE> if isinstance(data_path, str) and os.path.isdir(data_path): <NEW_LINE> <INDENT> self.path = data_path <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("[GenericDatasource] Path does not correspond t... | @param data_path <str>: path to directory where image patches are stored
@param config <argparse>: configuration object
@param keepImg <boolean>: keep image data in memory | 625941cb099cdd3c635f0d2c |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.