code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
def get_children(self): <NEW_LINE> <INDENT> return [ c for (z, c) in self.children ]
|
Return a list with the node's childs, order is back to front
:rtype: list of CocosNode
:return: childs of this node, ordered back to front
|
625941b5cad5886f8bd26dda
|
def build_decoder(self, code): <NEW_LINE> <INDENT> en_brick_0, concat_0, en_brick_1, concat_1, en_brick_2, concat_2, en_brick_3, concat_3, code = code <NEW_LINE> with tf.variable_scope('Decoder'): <NEW_LINE> <INDENT> dec_brick_0 = self._decode_brick(code, concat_3, 8 * self.nf, self.is_training, scope='decode_brick_0') <NEW_LINE> dec_brick_1 = self._decode_brick(dec_brick_0, concat_2, 4 * self.nf, self.is_training, scope='decode_brick_1') <NEW_LINE> dec_brick_2 = self._decode_brick(dec_brick_1, concat_1, 2 * self.nf, self.is_training, scope='decode_brick_2') <NEW_LINE> dec_brick_3 = self._decode_brick(dec_brick_2, concat_0, self.nf, self.is_training, scope='decode_brick_3') <NEW_LINE> <DEDENT> return dec_brick_3
|
Decoder layers
|
625941b55fdd1c0f98dc0029
|
def auth(self, msg): <NEW_LINE> <INDENT> if self._private_only(msg): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> log('i', 'User attempting to authenticate: ' + str(msg.user)) <NEW_LINE> if msg.params == msg.user.password: <NEW_LINE> <INDENT> msg.user.trusted = True <NEW_LINE> return msg.prefix + _("You're authenticated by now.") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return msg.prefix + _("Passwords do NOT match. DO NOT TRY TO FOOL ME!")
|
If a user uses auth with the correct password he can use all
possibilities of the level associated with his account.
|
625941b5a79ad161976cbf3d
|
def _ShouldInsertBlankLine(decorated_move_span, next_decorated_move_span, file_lines, flags): <NEW_LINE> <INDENT> if decorated_move_span[0] != next_decorated_move_span[0]: <NEW_LINE> <INDENT> next_line = _NextNondeletedLine(file_lines, decorated_move_span[0][1] - 1) <NEW_LINE> while (next_line and next_line < len(file_lines) and file_lines[next_line].type == _COMMENT_LINE_RE): <NEW_LINE> <INDENT> next_line += 1 <NEW_LINE> <DEDENT> return (next_line and next_line < len(file_lines) and file_lines[next_line].type in (_NAMESPACE_START_RE, None)) <NEW_LINE> <DEDENT> (this_kind, next_kind) = (decorated_move_span[1], next_decorated_move_span[1]) <NEW_LINE> if this_kind == next_kind or next_kind == _EOF_KIND: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if (this_kind in [_C_SYSTEM_INCLUDE_KIND, _CXX_SYSTEM_INCLUDE_KIND] and next_kind in [_C_SYSTEM_INCLUDE_KIND, _CXX_SYSTEM_INCLUDE_KIND]): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if this_kind == _FORWARD_DECLARE_KIND or next_kind == _FORWARD_DECLARE_KIND: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if flags.blank_lines: <NEW_LINE> <INDENT> return this_kind != next_kind <NEW_LINE> <DEDENT> return False
|
Returns true iff we should insert a blank line between the two spans.
Given two decorated move-spans, of the form
(reorder_range, kind, noncomment_lines, all_lines)
returns true if we should insert a blank line between them. We
always put a blank line when transitioning from an #include to a
forward-declare and back. When the appropriate commandline flag is
set, we also put a blank line between the 'main' includes (foo.h)
and the C/C++ system includes, and another between the system
includes and the rest of the Google includes.
If the two move spans are in different reorder_ranges, that means
the first move_span is at the end of a reorder range. In that case,
a different rule for blank lines applies: if the next line is
contentful (eg 'static int x = 5;'), or a namespace start, we want
to insert a blank line to separate the move-span from the next
block. When figuring out if the next line is contentful, we skip
over comments.
Arguments:
decorated_move_span: a decorated_move_span we may want to put a blank
line after.
next_decorated_move_span: the next decorated_move_span, which may
be a sentinel decorated_move_span at end-of-file.
file_lines: an array of LineInfo objects with .deleted filled in.
flags: commandline flags, as parsed by optparse. We use
flags.blank_lines, which controls whether we put blank
lines between different 'kinds' of #includes.
Returns:
true if we should insert a blank line after decorated_move_span.
|
625941b530c21e258bdfa295
|
def update_adminisation_file(): <NEW_LINE> <INDENT> INFO.update({"currently_under_test": str(int(False)), "last_test": strftime("%s")})
|
Update what should be updated.
|
625941b550812a4eaa59c11e
|
def ppo(agent: Agent, solution_score: float = 30, n_episodes: int = 1000) -> List[float]: <NEW_LINE> <INDENT> all_scores = [] <NEW_LINE> latest_scores = deque(maxlen=100) <NEW_LINE> for i in range(n_episodes): <NEW_LINE> <INDENT> score = agent.train_for_episode() <NEW_LINE> latest_scores.append(score) <NEW_LINE> all_scores.append(score) <NEW_LINE> print('\rEpisode {}\tAverage Score: {:.2f}'.format(i, np.mean(latest_scores)), end="") <NEW_LINE> if i % 100 == 0: <NEW_LINE> <INDENT> print('\rEpisode {}\tAverage Score: {:.2f}'.format(i, np.mean(latest_scores))) <NEW_LINE> <DEDENT> if np.mean(latest_scores) >= solution_score: <NEW_LINE> <INDENT> print("\nEnvironment solved in {} episodes".format(i + 1)) <NEW_LINE> agent.save() <NEW_LINE> np.save('scores.npy', np.array(all_scores)) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return all_scores
|
Train the PPO agent.
:param agent: agent to be trained
:param solution_score: score at which agent's environment is considered to be solved
:param n_episodes: maximum number of episodes for which to train the agent
:return: list of agent's scores for all episodes of training
|
625941b5287bf620b61d3868
|
def dynregDevice(self, timeout=10,dynregDomain=None): <NEW_LINE> <INDENT> return self.__hub.dynregDevice(timeout, dynregDomain)
|
Dynamic register
Get the device secret from the Cloud
Args:
timeout: request timeout
Returns:
success: return zero and device secret
fail: -1 and error message
|
625941b5bf627c535bc12fcf
|
def __init__( self, app=None, requests=None, access_token=None, graph_version=None, timeout=None, ): <NEW_LINE> <INDENT> graph_version = graph_version or DEFAULT_GRAPH_VERSION <NEW_LINE> super(FacebookBatchRequest, self).__init__( app=app, access_token=access_token, graph_version=graph_version, method=METHOD_POST, endpoint='', timeout=timeout, ) <NEW_LINE> self.requests = [] <NEW_LINE> if requests: <NEW_LINE> <INDENT> self.add(request=requests)
|
:param requests: a list of FacebookRequest
:param access_token: the access token for the batch request
:param graph_version: the graph version for the batch request
|
625941b5925a0f43d2549c6b
|
def test_no_question(self): <NEW_LINE> <INDENT> response = self.client.get(reverse('polls:index')) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> self.assertContains(response, "No polls are available.") <NEW_LINE> self.assertQuerysetEqual(response.context['latest_question_list'], [])
|
If no question exist, an appropriate message is diplayed.
:return:
|
625941b5627d3e7fe0d68c46
|
def is_position_valid(self, pos): <NEW_LINE> <INDENT> if self.is_position_in_room(pos): <NEW_LINE> <INDENT> return not self.is_position_furnished(pos) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False
|
Determine if position is valid and unfurnished.
Args
----
pos (Position): A position to be determined if unfurnished
Returns
-------
isValid (bool): set True if position is valid and unfurnished
|
625941b54527f215b584c253
|
def mkdir(directory): <NEW_LINE> <INDENT> if not os.path.exists(directory): <NEW_LINE> <INDENT> os.makedirs(directory)
|
Make a directory.
|
625941b54527f215b584c254
|
def _format_info(data): <NEW_LINE> <INDENT> return {'name': data.gr_name, 'gid': data.gr_gid, 'passwd': data.gr_passwd, 'members': data.gr_mem}
|
Return formatted information in a pretty way.
|
625941b5eab8aa0e5d26d957
|
def determine_db_dir(): <NEW_LINE> <INDENT> if platform.system() == "Darwin": <NEW_LINE> <INDENT> return os.path.expanduser("~/Library/Application Support/Dudgx/") <NEW_LINE> <DEDENT> elif platform.system() == "Windows": <NEW_LINE> <INDENT> return os.path.join(os.environ['APPDATA'], "Dudgx") <NEW_LINE> <DEDENT> return os.path.expanduser("~/.dudgx")
|
Return the default location of the dudgx data directory
|
625941b545492302aab5e0b8
|
def checkset(self, vrs): <NEW_LINE> <INDENT> if self.label not in vrs: <NEW_LINE> <INDENT> return self.neg or self.opt <NEW_LINE> <DEDENT> if self.group: <NEW_LINE> <INDENT> return all(self.check(x) for x in vrs[self.label]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.check(vrs[self.label])
|
Given a set of variable values, verify that self's conditions are met.
|
625941b5b545ff76a8913c19
|
def length_of_longest_increasing_subsequence(array): <NEW_LINE> <INDENT> memo = [1 for _ in range(len(array))] <NEW_LINE> for i in range(1,len(array)): <NEW_LINE> <INDENT> if array[i] > array[i-1]: <NEW_LINE> <INDENT> memo[i] = memo[i-1] + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> memo[i] = 1 <NEW_LINE> <DEDENT> <DEDENT> max_length = memo[0] <NEW_LINE> max_index = 0 <NEW_LINE> for i in range(1,len(array)): <NEW_LINE> <INDENT> if memo[i] > max_length: <NEW_LINE> <INDENT> max_length = memo[i] <NEW_LINE> max_index = i <NEW_LINE> <DEDENT> <DEDENT> print_sub_eles(array, max_index, max_length)
|
Given an array of integers, return length of the
longest increasing subsequence in the array
|
625941b5435de62698dfda4d
|
def a_star(vertices, edges, start, goal): <NEW_LINE> <INDENT> coords = {name:(x,y) for name, x, y in vertices} <NEW_LINE> if start not in coords or goal not in coords: <NEW_LINE> <INDENT> raise ValueError("Start and goal vertices must be in vertex list") <NEW_LINE> <DEDENT> graph = {vertex:[] for vertex in coords} <NEW_LINE> for edge in edges: <NEW_LINE> <INDENT> graph[edge[0]].append(edge[1]) <NEW_LINE> <DEDENT> distances = {vertex:float("inf") for vertex in coords} <NEW_LINE> distances[start] = 0.0 <NEW_LINE> visited = set() <NEW_LINE> queue = [(_get_dist(coords[start], coords[goal]), start)] <NEW_LINE> while len(queue) > 0: <NEW_LINE> <INDENT> current = heapq.heappop(queue)[1] <NEW_LINE> if current == goal: <NEW_LINE> <INDENT> return distances[goal] <NEW_LINE> <DEDENT> if current in visited: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> visited.add(current) <NEW_LINE> for neighbor in graph[current]: <NEW_LINE> <INDENT> if neighbor in visited: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> edge_distance = _get_dist(coords[current], coords[neighbor]) <NEW_LINE> new_score = distances[current] + edge_distance <NEW_LINE> if new_score >= distances[neighbor]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> distances[neighbor] = new_score <NEW_LINE> remaining_dist = _get_dist(coords[neighbor], coords[goal]) <NEW_LINE> heapq.heappush(queue, (new_score + remaining_dist, neighbor)) <NEW_LINE> <DEDENT> <DEDENT> return distances[goal]
|
Returns the distance of the shortest path from start to goal.
Using the A* heuristic, finds the length of the shortest path
from start to goal.
Args:
vertices: A list of vertex tuples in the following format:
(name, x coordinate, y coordinate)
name may be a number or string. x and y must be numbers,
but can be positive, negative, or zero floating point values.
edges: A list of edge tuples in the form (v1, v2), where
v1 and v2 are vertex names, and may be numbers or strings.
All edges are treated as directed, with the edge going from
v1 to v2. All vertex names must also be included in the vertices
parameter.
start: The name of the vertex from which to find a path to goal.
May be a string or number, but must be included in vertices.
goal: The name of the end/destination vertex. May be a string or number,
but must be included in vertices.
start and goal must be both included in edges in order to return a
non-infinite result.
Returns:
A floating point number that shows the shortest path distance
from start to goal using a subset of the edges in edges.
Returns the float value for infinity if there is no path from start
to goal.
|
625941b5046cf37aa974cb43
|
def _iterative_precondition(A, n, ss_args): <NEW_LINE> <INDENT> if settings.debug: <NEW_LINE> <INDENT> print('Starting preconditioner...',) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> P = spilu(A, permc_spec=ss_args['permc_spec'], drop_tol=ss_args['drop_tol'], diag_pivot_thresh=ss_args['diag_pivot_thresh'], fill_factor=ss_args['fill_factor'], options=dict(ILU_MILU=ss_args['ILU_MILU'])) <NEW_LINE> P_x = lambda x: P.solve(x) <NEW_LINE> M = LinearOperator((n ** 2, n ** 2), matvec=P_x) <NEW_LINE> if settings.debug: <NEW_LINE> <INDENT> print('Preconditioning succeeded.') <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> warnings.warn("Preconditioning failed. Continuing without.", UserWarning) <NEW_LINE> M = None <NEW_LINE> <DEDENT> return M
|
Internal function for preconditioning the steadystate problem for use
with iterative solvers.
|
625941b5be8e80087fb20a47
|
def getPrecAvg(avgPrec, table, se, query=None): <NEW_LINE> <INDENT> if (query == None): <NEW_LINE> <INDENT> query = se.query(table).filter(table.c.precipitation_amount >= avgPrec) <NEW_LINE> return query <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> query = query.filter(table.c.precipitation_amount >= avgPrec) <NEW_LINE> return query
|
Method gets all entries with average precipitation higher than/equal to input average precipitation
:param avgPrec: desired average temperature
:param table: which weather table is going to be used
:param se: Session Object containing connection information
:param query: Query Object which contains SQL query, if empty one will be created
:returns: Query Object, can be reused for other queries
|
625941b57b25080760e39254
|
def test_1loging_success(self): <NEW_LINE> <INDENT> success = self.Tpa.tpa_login_base('testyzc','123456') <NEW_LINE> self.add_img() <NEW_LINE> self.assertFalse(success)
|
Tpa 登录验证
|
625941b571ff763f4b549486
|
def interface_hundredgigabitethernet_ip_ip_config_address_ospf_ignore(**kwargs): <NEW_LINE> <INDENT> config = ET.Element("config") <NEW_LINE> interface = ET.SubElement(config, "interface", xmlns="urn:brocade.com:mgmt:brocade-interface") <NEW_LINE> if kwargs.pop('delete_interface', False) is True: <NEW_LINE> <INDENT> delete_interface = config.find('.//*interface') <NEW_LINE> delete_interface.set('operation', 'delete') <NEW_LINE> <DEDENT> hundredgigabitethernet = ET.SubElement(interface, "hundredgigabitethernet") <NEW_LINE> if kwargs.pop('delete_hundredgigabitethernet', False) is True: <NEW_LINE> <INDENT> delete_hundredgigabitethernet = config.find('.//*hundredgigabitethernet') <NEW_LINE> delete_hundredgigabitethernet.set('operation', 'delete') <NEW_LINE> <DEDENT> name_key = ET.SubElement(hundredgigabitethernet, "name") <NEW_LINE> name_key.text = kwargs.pop('name') <NEW_LINE> if kwargs.pop('delete_name', False) is True: <NEW_LINE> <INDENT> delete_name = config.find('.//*name') <NEW_LINE> delete_name.set('operation', 'delete') <NEW_LINE> <DEDENT> ip = ET.SubElement(hundredgigabitethernet, "ip") <NEW_LINE> if kwargs.pop('delete_ip', False) is True: <NEW_LINE> <INDENT> delete_ip = config.find('.//*ip') <NEW_LINE> delete_ip.set('operation', 'delete') <NEW_LINE> <DEDENT> ip_config = ET.SubElement(ip, "ip-config", xmlns="urn:brocade.com:mgmt:brocade-ip-config") <NEW_LINE> if kwargs.pop('delete_ip_config', False) is True: <NEW_LINE> <INDENT> delete_ip_config = config.find('.//*ip-config') <NEW_LINE> delete_ip_config.set('operation', 'delete') <NEW_LINE> <DEDENT> address = ET.SubElement(ip_config, "address") <NEW_LINE> if kwargs.pop('delete_address', False) is True: <NEW_LINE> <INDENT> delete_address = config.find('.//*address') <NEW_LINE> delete_address.set('operation', 'delete') <NEW_LINE> <DEDENT> address_key = ET.SubElement(address, "address") <NEW_LINE> address_key.text = kwargs.pop('address') <NEW_LINE> if kwargs.pop('delete_address', False) is True: <NEW_LINE> <INDENT> delete_address = config.find('.//*address') <NEW_LINE> delete_address.set('operation', 'delete') <NEW_LINE> <DEDENT> ospf_ignore = ET.SubElement(address, "ospf-ignore") <NEW_LINE> if kwargs.pop('delete_ospf_ignore', False) is True: <NEW_LINE> <INDENT> delete_ospf_ignore = config.find('.//*ospf-ignore') <NEW_LINE> delete_ospf_ignore.set('operation', 'delete') <NEW_LINE> <DEDENT> callback = kwargs.pop('callback', _callback) <NEW_LINE> return callback(config, mgr=kwargs.pop('mgr'))
|
Auto Generated Code
|
625941b5cb5e8a47e48b78a9
|
def __str__(self): <NEW_LINE> <INDENT> return self.choice_text
|
returns `choice_text` value when Choice object is called.
|
625941b563f4b57ef0000f1c
|
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, RoutesQuery): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
|
Return true if both objects are equal.
|
625941b566656f66f7cbbfa2
|
def setUp(self): <NEW_LINE> <INDENT> self.data = { 'time': 1, 'url': 'https://git.openstack.org/openstack/openstack-ansible', 'filters': [ { 'model': 'Environment', 'prop': 'name', 'operator': 'CONTAINS', 'value': 'james' } ] } <NEW_LINE> self.patcher = mock.patch('reports.git.GitSerializer.git_urls') <NEW_LINE> self.mock_git_urls = self.patcher.start() <NEW_LINE> self.mock_git_urls.return_value = [ 'https://git.openstack.org/openstack/openstack-ansible', 'https://repoa', 'https://repob' ]
|
Patch urls returned from neo4j query.
|
625941b5e64d504609d74639
|
def fill_excepted(self, excepted_result): <NEW_LINE> <INDENT> self._ws.cell(self._ws.max_row, EXPECTED_RESULT_COL).value = str(excepted_result) <NEW_LINE> self._log.debug('成功回写当前用例预期结果:{}'.format(excepted_result))
|
回写预期结果
:param excepted_result: 预期结果
:return: None
|
625941b5be7bc26dc91cd3ff
|
def on_menuitemActivitiesFilterShowOnlySyscall_activate(self, widget): <NEW_LINE> <INDENT> selection = self.ui.tvwActivities.get_selection() <NEW_LINE> if selection: <NEW_LINE> <INDENT> model, iter = selection.get_selected() <NEW_LINE> if iter: <NEW_LINE> <INDENT> while len(self.filtered_items): <NEW_LINE> <INDENT> self.filtered_items.pop() <NEW_LINE> <DEDENT> self.filtered_items.extend(SYSCALL_NAMES.values()) <NEW_LINE> self.filtered_items.remove(self.modelActivities.get_syscall( self.ui.filterActivities.convert_iter_to_child_iter(iter))) <NEW_LINE> self.ui.filterActivities.refilter()
|
Show only the selected syscall from the results
|
625941b5796e427e537b03bb
|
@celery_app.task(acks_late=True) <NEW_LINE> def example_task(word: str) -> str: <NEW_LINE> <INDENT> return f"test task returns {word}"
|
example_task サンプルタスク
Args:
word (str): 返したい単語
Returns:
str: テストタスクが返す文字列
|
625941b58e71fb1e9831d5a6
|
def ouvrir_list_perso(self): <NEW_LINE> <INDENT> name_mdi = self.tabWidget.currentWidget().objectName()[:-4] + "_mdi" <NEW_LINE> mdi_area = self.findChild(QMdiArea, name_mdi) <NEW_LINE> new_list_perso = ListPerso(mdi_area=mdi_area) <NEW_LINE> mdi_area.addSubWindow(new_list_perso) <NEW_LINE> new_list_perso.show() <NEW_LINE> self._list_sub_windows.append(new_list_perso)
|
ouvre la list de personnage
|
625941b5ff9c53063f47bff7
|
def similarRGB(self, color): <NEW_LINE> <INDENT> if not color or color[0] != '#' or len(color) != 7: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> c1, c2, c3 = color[1:3], color[3:5], color[5:] <NEW_LINE> return '#' + self.closest(c1) + self.closest(c2) + self.closest(c3)
|
:type color: str
:rtype: str
|
625941b523e79379d52ee361
|
def set_config(config, args): <NEW_LINE> <INDENT> config.gamma = args.discount <NEW_LINE> config.tau = args.tau <NEW_LINE> config.hdl1 = args.hdl1 <NEW_LINE> config.hdl2 = args.hdl2 <NEW_LINE> config.hdl3 = args.hdl3 <NEW_LINE> config.lr_actor = args.lr_actor <NEW_LINE> config.lr_critic = args.lr_critic <NEW_LINE> config.batch_size = args.batch_size <NEW_LINE> config.weight_decay = args.weight_decay <NEW_LINE> config.seed = args.seed <NEW_LINE> config.leak = args.leak <NEW_LINE> config.memory_capacity = args.memory_capacity <NEW_LINE> config.repeat_learning = args.repeat_learning <NEW_LINE> config.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
Args:
param1: (args): args
Return config
|
625941b58a43f66fc4b53e63
|
def graphics_array(array, n=None, m=None): <NEW_LINE> <INDENT> if not n is None: <NEW_LINE> <INDENT> n = int(n) <NEW_LINE> m = int(m) <NEW_LINE> array = reshape(array, n, m) <NEW_LINE> <DEDENT> return GraphicsArray(array)
|
``graphics_array`` take a list of lists (or tuples) of
graphics objects and plots them all on one canvas (single plot).
INPUT:
- ``array`` - a list of lists or tuples
- ``n, m`` - (optional) integers - if n and m are
given then the input array is flattened and turned into an n x m
array, with blank graphics objects padded at the end, if
necessary.
EXAMPLE: Make some plots of `\sin` functions::
sage: f(x) = sin(x)
sage: g(x) = sin(2*x)
sage: h(x) = sin(4*x)
sage: p1 = plot(f,(-2*pi,2*pi),color=hue(0.5)) # long time
sage: p2 = plot(g,(-2*pi,2*pi),color=hue(0.9)) # long time
sage: p3 = parametric_plot((f,g),(0,2*pi),color=hue(0.6)) # long time
sage: p4 = parametric_plot((f,h),(0,2*pi),color=hue(1.0)) # long time
Now make a graphics array out of the plots::
sage: graphics_array(((p1,p2),(p3,p4))) # long time
Graphics Array of size 2 x 2
One can also name the array, and then use :meth:`~sage.plot.graphics.GraphicsArray.show`
or :meth:`~sage.plot.graphics.GraphicsArray.save`::
sage: ga = graphics_array(((p1,p2),(p3,p4))) # long time
sage: ga.show() # long time
Here we give only one row::
sage: p1 = plot(sin,(-4,4))
sage: p2 = plot(cos,(-4,4))
sage: g = graphics_array([p1, p2]); print g
Graphics Array of size 1 x 2
sage: g.show()
It is possible to use ``figsize`` to change the size of the plot
as a whole::
sage: L = [plot(sin(k*x),(x,-pi,pi)) for k in [1..3]]
sage: G = graphics_array(L)
sage: G.show(figsize=[5,3]) # smallish and compact
::
sage: G.show(figsize=[10,20]) # bigger and tall and thin; long time (2s on sage.math, 2012)
::
sage: G.show(figsize=8) # figure as a whole is a square
|
625941b5099cdd3c635f0a55
|
def V_vertical_conical(D, a, h): <NEW_LINE> <INDENT> if h < a: <NEW_LINE> <INDENT> Vf = pi/4*(D*h/a)**2*(h/3.) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Vf = pi*D**2/4*(h - 2*a/3.) <NEW_LINE> <DEDENT> return Vf
|
Calculates volume of a vertical tank with a convex conical bottom,
according to [1]_. No provision for the top of the tank is made here.
.. math::
V_f = \frac{\pi}{4}\left(\frac{Dh}{a}\right)^2\left(\frac{h}{3}\right),\; h < a
V_f = \frac{\pi D^2}{4}\left(h - \frac{2a}{3}\right),\; h\ge a
Parameters
----------
D : float
Diameter of the main cylindrical section, [m]
a : float
Distance the cone head extends under the main cylinder, [m]
h : float
Height, as measured up to where the fluid ends, [m]
Returns
-------
V : float
Volume [m^3]
Examples
--------
Two examples from [1]_, and at empty and h=D.
>>> [V_vertical_conical(132., 33., i)/231. for i in [24, 60, 0, 132]]
[250.67461381371024, 2251.175535772343, 0.0, 6516.560761446257]
References
----------
.. [1] Jones, D. "Calculating Tank Volume." Text. Accessed December 22, 2015.
http://www.webcalc.com.br/blog/Tank_Volume.PDF
|
625941b524f1403a92600963
|
def __exit__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.session.autoflush = self.autoflush
|
Restore autoflush to its entrant state. Args unused.
|
625941b5ab23a570cc24ff78
|
def discount_factor(self, date): <NEW_LINE> <INDENT> raise NotImplementedError("DiscountCurve is an abstract base class")
|
Discount Factor implied by curve's term structure
|
625941b5ab23a570cc24ff79
|
def gen_tasks(self): <NEW_LINE> <INDENT> kw = { 'cache_folder': self.site.config['CACHE_FOLDER'], 'themes': self.site.THEMES, } <NEW_LINE> targets_path = utils.get_asset_path(os.path.join(self.sources_folder, "targets"), self.site.THEMES) <NEW_LINE> try: <NEW_LINE> <INDENT> with codecs.open(targets_path, "rb", "utf-8") as inf: <NEW_LINE> <INDENT> targets = [x.strip() for x in inf.readlines()] <NEW_LINE> <DEDENT> <DEDENT> except Exception: <NEW_LINE> <INDENT> targets = [] <NEW_LINE> <DEDENT> for theme_name in kw['themes']: <NEW_LINE> <INDENT> src = os.path.join(utils.get_theme_path(theme_name), self.sources_folder) <NEW_LINE> for task in utils.copy_tree(src, os.path.join(kw['cache_folder'], self.sources_folder)): <NEW_LINE> <INDENT> yield task <NEW_LINE> <DEDENT> <DEDENT> base_path = utils.get_theme_path(self.site.THEMES[0]) <NEW_LINE> dst_dir = os.path.join(base_path, "assets", "css") <NEW_LINE> deps = glob.glob(os.path.join( base_path, self.sources_folder, "*{0}".format(self.sources_ext))) <NEW_LINE> def compile_target(target, dst): <NEW_LINE> <INDENT> if not os.path.isdir(dst_dir): <NEW_LINE> <INDENT> os.makedirs(dst_dir) <NEW_LINE> <DEDENT> src = os.path.join(kw['cache_folder'], self.sources_folder, target) <NEW_LINE> compiled = subprocess.check_output([self.compiler_name, src]) <NEW_LINE> with open(dst, "wb+") as outf: <NEW_LINE> <INDENT> outf.write(compiled) <NEW_LINE> <DEDENT> <DEDENT> for target in targets: <NEW_LINE> <INDENT> dst = os.path.join(dst_dir, target.replace(self.sources_ext, ".css")) <NEW_LINE> yield { 'basename': self.name, 'name': dst, 'targets': [dst], 'file_dep': deps, 'actions': ((compile_target, [target, dst]), ), 'uptodate': [utils.config_changed(kw)], 'clean': True } <NEW_LINE> <DEDENT> if not targets: <NEW_LINE> <INDENT> yield {'basename': self.name, 'actions': []}
|
Generate CSS out of LESS sources.
|
625941b54a966d76dd550e04
|
def test_expression(self): <NEW_LINE> <INDENT> feature = self._feature_factory( { 'text_not_nullable': 'a text', 'integer_not_nullable': 12345, 'long_not_nullable': 12345, 'float_not_nullable': 12345, 'bool_not_nullable': True, 'date_not_nullable': '2020-02-01', 'datetime_not_nullable': '2020-02-01 00:00:00', 'text_nullable': '124', 'integer_nullable': 124, 'long_nullable': 124, 'float_nullable': 124, 'date_nullable': '1000-02-04', 'datetime_nullable': '1000-02-04 00:00:00'}, 'point( 9 45 )') <NEW_LINE> errors = feature_validator( feature, self.validator_project_test_expressions) <NEW_LINE> self.assertEqual(errors, {}) <NEW_LINE> feature.setAttribute('text_nullable', '123') <NEW_LINE> errors = feature_validator( feature, self.validator_project_test_expressions) <NEW_LINE> self.assertEqual(errors, { 'text_nullable': ["My constraint Expression: text_nullable != '123'"] }) <NEW_LINE> feature = self.validator_project_test.getFeature(1) <NEW_LINE> feature.setId(0) <NEW_LINE> feature.setAttribute(0, 0) <NEW_LINE> errors = feature_validator( feature, self.validator_project_test_expressions) <NEW_LINE> self.assertEqual(errors['text_nullable'][0], "My constraint Expression: text_nullable != '123'") <NEW_LINE> self.assertEqual(errors['integer_nullable'][0], "Expression check violation Expression: integer_nullable != 123") <NEW_LINE> self.assertEqual(errors['long_nullable'][0], "Expression check violation Expression: long_nullable != 123") <NEW_LINE> self.assertEqual(errors['float_nullable'][0], "Expression check violation Expression: float_nullable != 123") <NEW_LINE> self.assertEqual(errors['date_nullable'][0], "Expression check violation Expression: date_nullable != '1000-02-03'") <NEW_LINE> self.assertEqual(errors['datetime_nullable'][0], "Expression check violation Expression: datetime_nullable != to_datetime('1000-02-03 00:00:00')")
|
Test project level expression constraints
|
625941b5ec188e330fd5a5a1
|
def get_mem_usage(): <NEW_LINE> <INDENT> usage = resource.getrusage(resource.RUSAGE_SELF) <NEW_LINE> return ('usertime=%s systime=%s ' 'mem=%s mb') % (usage[0], usage[1], (usage[2] * resource.getpagesize()) / 1000000.0)
|
Get the current memory usage.
Returns:
A human-readable string.
|
625941b56aa9bd52df036b9b
|
def request( self, tasks ): <NEW_LINE> <INDENT> if ( not self._manager._is_interactive ) or ( self._manager._spout is None ): <NEW_LINE> <INDENT> raise LcApiException( 'Manager provided was not created with is_interactive set to True, cannot track responses.' ) <NEW_LINE> <DEDENT> thisTrackingId = '%s/%s' % ( self._manager._inv_id, str( uuid.uuid4() ) ) <NEW_LINE> future = FutureResults() <NEW_LINE> self._manager._spout.registerFutureResults( thisTrackingId, future ) <NEW_LINE> self.task( tasks, inv_id = thisTrackingId ) <NEW_LINE> return future
|
Send a task (or list of tasks) to the Sensor and returns a FutureResults where the results will be sent; requires Manager is_interactive.
Args:
tasks (str or list of str): tasks to send in the command line format described in official documentation.
Returns:
a FutureResults object.
|
625941b596565a6dacc8f4ce
|
@app.route('/stations/') <NEW_LINE> def stations(): <NEW_LINE> <INDENT> return jsonify({'data': settings.STATIONS})
|
Manual endpoint for listing sensor stations.
|
625941b566656f66f7cbbfa3
|
def _delete(self, state=None): <NEW_LINE> <INDENT> mutation_val = data_v2_pb2.Mutation.DeleteFromRow() <NEW_LINE> mutation_pb = data_v2_pb2.Mutation(delete_from_row=mutation_val) <NEW_LINE> self._get_mutations(state).append(mutation_pb)
|
Helper for :meth:`delete`
Adds a delete mutation (for the entire row) to the accumulated
mutations.
``state`` is unused by :class:`DirectRow` but is used by
subclasses.
:type state: bool
:param state: (Optional) The state that is passed along to
:meth:`_get_mutations`.
|
625941b5dc8b845886cb532d
|
def test_absolute_pose_single_shot(): <NEW_LINE> <INDENT> parameters = config.default_config() <NEW_LINE> synthetic_data, synthetic_tracks = synthetic_reconstruction() <NEW_LINE> shot_id = 'shot1' <NEW_LINE> camera_id = 'camera1' <NEW_LINE> metadata = types.ShotMetadata() <NEW_LINE> camera = synthetic_data.cameras[camera_id] <NEW_LINE> shot_before = synthetic_data.shots[shot_id] <NEW_LINE> status, report = reconstruction.resect(synthetic_tracks, synthetic_data, shot_id, camera, metadata, parameters['resection_threshold'], parameters['resection_min_inliers']) <NEW_LINE> shot_after = synthetic_data.shots[shot_id] <NEW_LINE> assert status is True <NEW_LINE> assert report['num_inliers'] is len(synthetic_data.points) <NEW_LINE> np.testing.assert_almost_equal( shot_before.pose.rotation, shot_after.pose.rotation, 1) <NEW_LINE> np.testing.assert_almost_equal( shot_before.pose.translation, shot_after.pose.translation, 1)
|
Single-camera resection on a toy reconstruction with
1/1000 pixel noise and zero outliers.
|
625941b52c8b7c6e89b355bd
|
def test_store_three_responses(self): <NEW_LINE> <INDENT> for response in self.responses: <NEW_LINE> <INDENT> self.my_survey.store_response(response) <NEW_LINE> <DEDENT> for response in self.responses: <NEW_LINE> <INDENT> self.assertIn(response, self.my_survey.responses)
|
测试三个答案会被妥善地存储
|
625941b55166f23b2e1a4f52
|
def delete_table_metadata_with_http_info(self, table_metadata_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['table_metadata_id'] <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> all_params.append('_request_timeout') <NEW_LINE> params = locals() <NEW_LINE> for key, val in six.iteritems(params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise TypeError( "Got an unexpected keyword argument '%s'" " to method delete_table_metadata" % key ) <NEW_LINE> <DEDENT> params[key] = val <NEW_LINE> <DEDENT> del params['kwargs'] <NEW_LINE> if self.api_client.client_side_validation and ('table_metadata_id' not in params or params['table_metadata_id'] is None): <NEW_LINE> <INDENT> raise ValueError("Missing the required parameter `table_metadata_id` when calling `delete_table_metadata`") <NEW_LINE> <DEDENT> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> if 'table_metadata_id' in params: <NEW_LINE> <INDENT> path_params['tableMetadataId'] = params['table_metadata_id'] <NEW_LINE> <DEDENT> query_params = [] <NEW_LINE> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) <NEW_LINE> auth_settings = ['api_key'] <NEW_LINE> return self.api_client.call_api( '/table-metadata/{tableMetadataId}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type=None, auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
|
Delete table metadata by ID # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_table_metadata_with_http_info(table_metadata_id, async_req=True)
>>> result = thread.get()
:param async_req bool
:param int table_metadata_id: The ID of the table metadata to delete (required)
:return: None
If the method is called asynchronously,
returns the request thread.
|
625941b58e7ae83300e4adc5
|
def rl_routing_step(): <NEW_LINE> <INDENT> global _root <NEW_LINE> global _routing_canvas <NEW_LINE> global _active_net <NEW_LINE> global _done_routing_attempt <NEW_LINE> global _net_dict <NEW_LINE> global _wavefront <NEW_LINE> global _target_sink <NEW_LINE> global _all_nets_routed <NEW_LINE> global _failed_nets <NEW_LINE> global _done_circuit <NEW_LINE> global _final_route_initiated <NEW_LINE> global _debug_counter <NEW_LINE> if _done_circuit: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if _done_routing_attempt: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if _active_net is None: <NEW_LINE> <INDENT> _active_net = _net_queue.get() <NEW_LINE> if _active_net.sinksRemaining == 0: <NEW_LINE> <INDENT> print("ERROR: Attempted to route a completed net") <NEW_LINE> <DEDENT> <DEDENT> if _wavefront is None: <NEW_LINE> <INDENT> _target_sink, best_start_cell = find_best_routing_pair() <NEW_LINE> _wavefront = [_active_net.source.get_coords()] <NEW_LINE> for cell in _active_net.wireCells: <NEW_LINE> <INDENT> _wavefront.append((cell.x, cell.y)) <NEW_LINE> <DEDENT> <DEDENT> if len(_wavefront) == 0: <NEW_LINE> <INDENT> if _active_net.num not in _failed_nets: <NEW_LINE> <INDENT> _failed_nets.append(_active_net.num) <NEW_LINE> <DEDENT> if VERBOSE_ENV: <NEW_LINE> <INDENT> print("Failed to route net " + str(_active_net.num) + " with colour " + NET_COLOURS[_active_net.num]) <NEW_LINE> <DEDENT> _all_nets_routed = False <NEW_LINE> _wavefront = None <NEW_LINE> cleanup_candidates() <NEW_LINE> if _net_queue.empty(): <NEW_LINE> <INDENT> if VERBOSE_ENV: <NEW_LINE> <INDENT> print("Routing attempt complete") <NEW_LINE> print("Failed nets: " + str(_failed_nets)) <NEW_LINE> <DEDENT> _done_routing_attempt = True <NEW_LINE> _active_net = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _active_net = _net_queue.get() <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> a_star_step()
|
Perform one iteration of A*, including algorithm overheads without doing any rip-ups
:return: void
|
625941b5b5575c28eb68ddf6
|
def authenticate(self, db, login, password, user_agent_env): <NEW_LINE> <INDENT> uid = self.login(db, login, password) <NEW_LINE> if uid == openerp.SUPERUSER_ID: <NEW_LINE> <INDENT> if user_agent_env and user_agent_env.get('base_location'): <NEW_LINE> <INDENT> cr = self.pool.cursor() <NEW_LINE> try: <NEW_LINE> <INDENT> base = user_agent_env['base_location'] <NEW_LINE> ICP = self.pool['ir.config_parameter'] <NEW_LINE> if not ICP.get_param(cr, uid, 'web.base.url.freeze'): <NEW_LINE> <INDENT> ICP.set_param(cr, uid, 'web.base.url', base) <NEW_LINE> <DEDENT> cr.commit() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> _logger.exception("Failed to update web.base.url configuration parameter") <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> cr.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return uid
|
Verifies and returns the user ID corresponding to the given
``login`` and ``password`` combination, or False if there was
no matching user.
:param str db: the database on which user is trying to authenticate
:param str login: username
:param str password: user password
:param dict user_agent_env: environment dictionary describing any
relevant environment attributes
|
625941b5377c676e91271fa4
|
def kmeans(boxes,k=9,dist=np.median): <NEW_LINE> <INDENT> rows = boxes.shape[0] <NEW_LINE> distances = np.empty((rows,k)) <NEW_LINE> last_clusters = np.zeros((rows,)) <NEW_LINE> np.random.seed() <NEW_LINE> clusters = boxes[np.random.choice(rows,k,replace=False)] <NEW_LINE> while True: <NEW_LINE> <INDENT> for row in range(rows): <NEW_LINE> <INDENT> distances[row] = 1 - kmeans_iou(boxes[row],clusters) <NEW_LINE> <DEDENT> neareset_clusters = np.argmin(distances,axis=1) <NEW_LINE> if(last_clusters==neareset_clusters).all(): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> for index_clu in range(k): <NEW_LINE> <INDENT> optional_boxes = sort_anchors(boxes[neareset_clusters==index_clu]) <NEW_LINE> clusters[index_clu] = dist(optional_boxes,axis=0) <NEW_LINE> <DEDENT> last_clusters = neareset_clusters <NEW_LINE> <DEDENT> return sort_anchors(clusters)
|
Calculates k-means clustering with the Intersection over Union (IoU) metric.
:param boxes: numpy array of shape (r, 2), where r is the number of rows (w,h)
:param k: number of clusters
:param dist: distance function,这次为取聚集点中的中位数
:return: numpy array of shape (k, 2)
|
625941b58a349b6b435e7f6e
|
def purple_blist_find_chat(*args): <NEW_LINE> <INDENT> return _purple.purple_blist_find_chat(*args)
|
purple_blist_find_chat(PurpleAccount account, char name) -> PurpleChat
|
625941b57d43ff24873a2a9d
|
def make_packs_and_alt_repo(self, write_lock=False): <NEW_LINE> <INDENT> tree = self.make_branch_and_tree('.', format=self.get_format()) <NEW_LINE> tree.lock_write() <NEW_LINE> self.addCleanup(tree.unlock) <NEW_LINE> rev1 = tree.commit('one') <NEW_LINE> rev2 = tree.commit('two') <NEW_LINE> rev3 = tree.commit('three') <NEW_LINE> r = repository.Repository.open('.') <NEW_LINE> if write_lock: <NEW_LINE> <INDENT> r.lock_write() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> r.lock_read() <NEW_LINE> <DEDENT> self.addCleanup(r.unlock) <NEW_LINE> packs = r._pack_collection <NEW_LINE> packs.ensure_loaded() <NEW_LINE> return tree, r, packs, [rev1, rev2, rev3]
|
Create a pack repo with 3 packs, and access it via a second repo.
|
625941b5498bea3a759b98ac
|
def mangle_for_marketo(snaps, minimum=10): <NEW_LINE> <INDENT> mangled = copy.deepcopy(snaps) <NEW_LINE> for snap in mangled: <NEW_LINE> <INDENT> metrics = snap["channelMapWithMetrics"] <NEW_LINE> if metrics["channelMap"] and metrics["weeklyActive"] >= minimum: <NEW_LINE> <INDENT> snap["channelMapWithMetrics"] = json.dumps(metrics) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> snap["channelMapWithMetrics"] = "" <NEW_LINE> <DEDENT> del snap["snapID"] <NEW_LINE> <DEDENT> return mangled
|
Filter out snaps that are not released to any channel or have fewer
installs than the specified minimum (setting their metrics to empty).
Reformat data for Marketo as key/string pairs.
|
625941b591f36d47f21ac2ef
|
@require_POST <NEW_LINE> @csrf_exempt <NEW_LINE> def webhook_view(request): <NEW_LINE> <INDENT> payload = request.body <NEW_LINE> sig_header = request.META['HTTP_STRIPE_SIGNATURE'] <NEW_LINE> event = None <NEW_LINE> try: <NEW_LINE> <INDENT> event = stripe.Webhook.construct_event( payload, sig_header, stripe_endpoint_secret ) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return HttpResponse(status=400) <NEW_LINE> <DEDENT> except stripe.error.SignatureVerificationError: <NEW_LINE> <INDENT> return HttpResponse(status=400) <NEW_LINE> <DEDENT> if event.type == 'payment_intent.succeeded': <NEW_LINE> <INDENT> payment_intent = event.data.object <NEW_LINE> payment_id = payment_intent.id <NEW_LINE> billing_details = payment_intent.charges.data[0].billing_details <NEW_LINE> return send_customer_emails(request, event.type, payment_id, billing_details) <NEW_LINE> <DEDENT> elif event.type == 'payment_intent.payment_failed': <NEW_LINE> <INDENT> payment_intent = event.data.object <NEW_LINE> return HttpResponse( content=f'Webhook OK:{event.type}, pay intent FAILED', status=200) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return HttpResponse( content=f'Webhook OK:{event.type}, NOT handled', status=200)
|
Function to listen and process the Stripe webhooks
|
625941b5dc8b845886cb532e
|
def extract_mosaic_ids_from_df(df): <NEW_LINE> <INDENT> mosaics = df[~df.mosaic_position.isnull()] .sort_values(["mosaic_idx", "mosaic_position"]) .groupby("mosaic_idx") .agg({ "img_id": lambda x: list(x) }) .reset_index() <NEW_LINE> non_mosaics = df[df.mosaic_position.isnull()] <NEW_LINE> return mosaics, non_mosaics
|
Regroups Emil's df in a way to be used with `combine_masks` and `combine_images` (watch the order!)
|
625941b5c432627299f04a3e
|
def setcurvevalue(ph, curveIndex, pointIndex, x, y): <NEW_LINE> <INDENT> return _toolkit.setcurvevalue(ph, curveIndex, pointIndex, x, y)
|
setcurvevalue(ph, curveIndex, pointIndex, x, y) -> int
Parameters
----------
ph: EN_Project
curveIndex: int
pointIndex: int
x: double
y: double
|
625941b507f4c71912b11280
|
def on_click_pressure(pos_x: int, pos_y: int) -> None: <NEW_LINE> <INDENT> toggle_option("Pressure")
|
Handles the click in one of the options pressure button.
|
625941b507d97122c4178684
|
def radians(degree: int) -> float: <NEW_LINE> <INDENT> pi_on_180 = 0.017453292519943295 <NEW_LINE> return degree * pi_on_180
|
radians.
helper function converts degrees to radians.
Args:
degree: degrees.
|
625941b5d164cc6175782b47
|
def _quant_create( self, cr, uid, qty, move, lot_id=False, owner_id=False, src_package_id=False, dest_package_id=False, force_location_from=False, force_location_to=False, context=None): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> price_unit = self.pool.get('stock.move').get_price_unit( cr, uid, move, context=context) <NEW_LINE> location = force_location_to or move.location_dest_id <NEW_LINE> rounding = move.product_id.uom_id.rounding <NEW_LINE> if move.has_validate_picking_after_move_date(): <NEW_LINE> <INDENT> quant_date = datetime.now().strftime( DEFAULT_SERVER_DATETIME_FORMAT) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> quant_date = move.date <NEW_LINE> <DEDENT> vals = { 'product_id': move.product_id.id, 'location_id': location.id, 'qty': float_round(qty, precision_rounding=rounding), 'cost': price_unit, 'history_ids': [(4, move.id)], 'in_date': quant_date, 'company_id': move.company_id.id, 'lot_id': lot_id, 'owner_id': owner_id, 'package_id': dest_package_id, } <NEW_LINE> if move.location_id.usage == 'internal': <NEW_LINE> <INDENT> negative_vals = vals.copy() <NEW_LINE> negative_vals['location_id'] = force_location_from and force_location_from.id or move.location_id.id <NEW_LINE> negative_vals['qty'] = float_round(-qty, precision_rounding=rounding) <NEW_LINE> negative_vals['cost'] = price_unit <NEW_LINE> negative_vals['negative_move_id'] = move.id <NEW_LINE> negative_vals['package_id'] = src_package_id <NEW_LINE> negative_quant_id = self.create(cr, SUPERUSER_ID, negative_vals, context=context) <NEW_LINE> vals.update({'propagated_from_id': negative_quant_id}) <NEW_LINE> <DEDENT> quant_id = self.create(cr, SUPERUSER_ID, vals, context=context) <NEW_LINE> return self.browse(cr, uid, quant_id, context=context)
|
NOTE: This method is a copy of the original one in odoo
Here we set in_date taking into account the move date
This method is call from the quant_move after action_done.
|
625941b50383005118ecf3de
|
def auto_install_service(service, cluster, ha=False): <NEW_LINE> <INDENT> req = 'ha' if ha else 'default' <NEW_LINE> for s in config['services']: <NEW_LINE> <INDENT> if s['name'] == service: <NEW_LINE> <INDENT> for c in s['components']: <NEW_LINE> <INDENT> if c['name'] in s['auto_install']: <NEW_LINE> <INDENT> auto_assign_service_comp(c, req, cluster, check=False)
|
Auto-install the service clients on the fitting hosts.
:param service: Service name
:type service: str
:param cluster: Cluster name
:type cluster: str
|
625941b556b00c62f0f14456
|
def writeAll(self, writeAtFileNodesFlag=False, writeDirtyAtFileNodesFlag=False, toString=False ): <NEW_LINE> <INDENT> trace = False and not g.unitTesting <NEW_LINE> at = self ; c = at.c <NEW_LINE> if trace: scanAtPathDirectivesCount = c.scanAtPathDirectivesCount <NEW_LINE> writtenFiles = [] <NEW_LINE> force = writeAtFileNodesFlag <NEW_LINE> at.canCancelFlag = True <NEW_LINE> at.cancelFlag = False <NEW_LINE> at.yesToAll = False <NEW_LINE> if writeAtFileNodesFlag: <NEW_LINE> <INDENT> p = c.p <NEW_LINE> after = p.nodeAfterTree() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p = c.rootPosition() <NEW_LINE> after = c.nullPosition() <NEW_LINE> <DEDENT> at.clearAllOrphanBits(p) <NEW_LINE> while p and p != after: <NEW_LINE> <INDENT> if p.isAtIgnoreNode() and not p.isAtAsisFileNode(): <NEW_LINE> <INDENT> if p.isAnyAtFileNode() : <NEW_LINE> <INDENT> c.ignored_at_file_nodes.append(p.h) <NEW_LINE> <DEDENT> p.moveToNodeAfterTree() <NEW_LINE> <DEDENT> elif p.isAnyAtFileNode(): <NEW_LINE> <INDENT> self.writeAllHelper(p,force,toString,writeAtFileNodesFlag,writtenFiles) <NEW_LINE> p.moveToNodeAfterTree() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p.moveToThreadNext() <NEW_LINE> <DEDENT> <DEDENT> at.canCancelFlag = False <NEW_LINE> at.cancelFlag = False <NEW_LINE> at.yesToAll = False <NEW_LINE> if not g.unitTesting: <NEW_LINE> <INDENT> if writeAtFileNodesFlag or writeDirtyAtFileNodesFlag: <NEW_LINE> <INDENT> if len(writtenFiles) > 0: <NEW_LINE> <INDENT> g.es("finished") <NEW_LINE> <DEDENT> elif writeAtFileNodesFlag: <NEW_LINE> <INDENT> g.es("no @<file> nodes in the selected tree") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> g.es("no dirty @<file> nodes") <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if trace: g.trace('%s calls to c.scanAtPathDirectives()' % ( c.scanAtPathDirectivesCount-scanAtPathDirectivesCount))
|
Write @file nodes in all or part of the outline
|
625941b58da39b475bd64d70
|
def square(num1): <NEW_LINE> <INDENT> return num1**2
|
Squares num1
|
625941b515baa723493c3d6c
|
def get_Tweets(username): <NEW_LINE> <INDENT> consumer_key = "UZaefZdzkPNYnZi8fN9HIPzim" <NEW_LINE> consumer_secret = "tXGE5YUfqUxz4sLUOJohKJKApyWfTyrVi7Mg9ivGFPd0mn135t" <NEW_LINE> access_key = "1665830713-gWWMNp5q26j3XxgYQB4v3kgudijpjzBlipFjQQb" <NEW_LINE> access_secret = "RZVr5x1GteJHjhAfrPAJ47WEegUpSvKythIMK9fPA8KXr" <NEW_LINE> auth = tweepy.OAuthHandler(consumer_key, consumer_secret) <NEW_LINE> auth.set_access_token(access_key, access_secret) <NEW_LINE> api = tweepy.API(auth) <NEW_LINE> screen_name = username <NEW_LINE> alltweets = [] <NEW_LINE> new_tweets = api.user_timeline(screen_name = screen_name,count=200) <NEW_LINE> alltweets.extend(new_tweets) <NEW_LINE> oldest = alltweets[-1].id - 1 <NEW_LINE> while len(new_tweets) > 0: <NEW_LINE> <INDENT> print(f"getting tweets before {oldest}") <NEW_LINE> new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest) <NEW_LINE> alltweets.extend(new_tweets) <NEW_LINE> oldest = alltweets[-1].id - 1 <NEW_LINE> print(f"...{len(alltweets)} tweets downloaded so far") <NEW_LINE> <DEDENT> outtweets = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets] <NEW_LINE> with open(f'new_{screen_name}_tweets.csv', 'w') as f: <NEW_LINE> <INDENT> writer = csv.writer(f) <NEW_LINE> writer.writerow(["id","created_at","text"]) <NEW_LINE> writer.writerows(outtweets) <NEW_LINE> <DEDENT> pass <NEW_LINE> return
|
Function that will get information on Elon Musk's tweets, such as
number of tweets per day.
|
625941b5baa26c4b54cb0f1d
|
def execCommand(self, qry): <NEW_LINE> <INDENT> logger.debug('Executing command: ' + qry) <NEW_LINE> if (self.dbconn.status != 1): <NEW_LINE> <INDENT> logger.info("DB Connection bad, attempting reset") <NEW_LINE> self.dbconn.reset() <NEW_LINE> <DEDENT> result = self.dbconn.query(qry)
|
Executes a SQL statement, ignoring the results
|
625941b5d6c5a10208143e41
|
def __init__(self, color): <NEW_LINE> <INDENT> super(MachinePlayerAbstract, self).__init__(color) <NEW_LINE> self._type = "IA" <NEW_LINE> self._difficulty = 5
|
Constructor
:param color: character entered in the grid for example: `o` or `x`
:return:
|
625941b5a05bb46b383ec628
|
def loss(self, X, y=None, reg=0.0): <NEW_LINE> <INDENT> W1, b1 = self.params['W1'], self.params['b1'] <NEW_LINE> W2, b2 = self.params['W2'], self.params['b2'] <NEW_LINE> N, D = X.shape <NEW_LINE> scores = None <NEW_LINE> inputs_hidden = X.dot(W1) + b1 <NEW_LINE> outputs_hidden = np.maximum(0, inputs_hidden) <NEW_LINE> scores = outputs_hidden.dot(W2) + b2 <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss = None <NEW_LINE> scores_exp = np.exp(scores) <NEW_LINE> scores_norm = scores_exp / np.sum(scores_exp, axis=1, keepdims=True) <NEW_LINE> y_scores_norm = scores_norm[range(N), y] <NEW_LINE> y_scores_log = -np.log(y_scores_norm) <NEW_LINE> cross_entropy_loss = np.sum(y_scores_log) / N <NEW_LINE> reg_loss = 0.5 * reg * (np.sum(W1*W1) + np.sum(W2*W2)) <NEW_LINE> loss = cross_entropy_loss + reg_loss <NEW_LINE> grads = {} <NEW_LINE> dscores = scores_norm <NEW_LINE> dscores[range(N), y] -= 1 <NEW_LINE> dscores /= N <NEW_LINE> dW2 = outputs_hidden.T.dot(dscores) <NEW_LINE> dW2 += reg * W2 <NEW_LINE> grads['W2'] = dW2 <NEW_LINE> grads['b2'] = np.sum(dscores, axis=0) <NEW_LINE> dInputs_hidden = dscores.dot(W2.T) <NEW_LINE> dInputs_hidden[inputs_hidden <= 0] = 0 <NEW_LINE> dW1 = X.T.dot(dInputs_hidden) <NEW_LINE> dW1 += reg * W1 <NEW_LINE> grads['W1'] = dW1 <NEW_LINE> grads['b1'] = np.sum(dInputs_hidden, axis=0) <NEW_LINE> return loss, grads
|
Compute the loss and gradients for a two layer fully connected neural
network.
Inputs:
- X: Input data of shape (N, D). Each X[i] is a training sample.
- y: Vector of training labels. y[i] is the label for X[i], and each y[i] is
an integer in the range 0 <= y[i] < C. This parameter is optional; if it
is not passed then we only return scores, and if it is passed then we
instead return the loss and gradients.
- reg: Regularization strength.
Returns:
If y is None, return a matrix scores of shape (N, C) where scores[i, c] is
the score for class c on input X[i].
If y is not None, instead return a tuple of:
- loss: Loss (data loss and regularization loss) for this batch of training
samples.
- grads: Dictionary mapping parameter names to gradients of those parameters
with respect to the loss function; has the same keys as self.params.
|
625941b5adb09d7d5db6c58d
|
def to_json(template, clean_up=False): <NEW_LINE> <INDENT> data = load_yaml(template) <NEW_LINE> if clean_up: <NEW_LINE> <INDENT> data = clean(data) <NEW_LINE> <DEDENT> return dump_json(data)
|
Assume the input is YAML and convert to JSON
|
625941b5dd821e528d63afa5
|
def test_exponential_longchain_dependent(self): <NEW_LINE> <INDENT> self.ms.add_serial_dependency(self.ms2) <NEW_LINE> self.ms2.add_serial_dependency(self.ms5) <NEW_LINE> self.ms5.add_serial_dependency(self.ms3) <NEW_LINE> for x in range(1, self.BIG_ENOUGH_SAMPLES): <NEW_LINE> <INDENT> self.ms.calculate_latency() <NEW_LINE> <DEDENT> mydata = pd.Series(self.ms.latency_history) <NEW_LINE> self.assertLess(shapiro(mydata).pvalue, 0.05)
|
An exponential system in a chain is non-normally distributed at root.
|
625941b5f9cc0f698b140400
|
def test_func(self): <NEW_LINE> <INDENT> post = self.get_object() <NEW_LINE> if self.request.user == post.author: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
|
Test if the user is equal to author
|
625941b550812a4eaa59c120
|
def trainNB0(trainMatrix, trainCategory): <NEW_LINE> <INDENT> numTrainDocs = len(trainMatrix) <NEW_LINE> numWords = len(trainMatrix[0]) <NEW_LINE> pAbusive = sum(trainCategory) / float(numTrainDocs) <NEW_LINE> p0Num = np.ones(numWords) <NEW_LINE> p1Num = np.ones(numWords) <NEW_LINE> p0Denom = 2 <NEW_LINE> p1Denom = 2 <NEW_LINE> for i in range(numTrainDocs): <NEW_LINE> <INDENT> if trainCategory[i] == 1: <NEW_LINE> <INDENT> p1Num += trainMatrix[i] <NEW_LINE> p1Denom += sum(trainMatrix[i]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p0Num += trainMatrix[i] <NEW_LINE> p0Denom += sum(trainMatrix[i]) <NEW_LINE> <DEDENT> <DEDENT> p1Vect = np.log(p1Num / p1Denom) <NEW_LINE> p0Vect = np.log(p0Num / p0Denom) <NEW_LINE> return p0Vect, p1Vect, pAbusive
|
训练
@ param trainMatrix: 训练集
@ param trainCategory: 分类
|
625941b54d74a7450ccd3fbc
|
def _check_recursion(self, cr, uid, ids, context=None, parent=None): <NEW_LINE> <INDENT> return super(budget_item, self)._check_recursion( cr, uid, ids, parent=parent or 'parent_id', context=context)
|
use in _constraints[]: return false
if there is a recursion in the budget items structure
|
625941b54e4d5625662d41d8
|
def line_factory(a, k): <NEW_LINE> <INDENT> return lambda y: line_function(y, a, k)
|
Factory funktio
|
625941b599fddb7c1c9de18d
|
def toTypedArray(type, elements): <NEW_LINE> <INDENT> arr = System.Array.CreateInstance(type, len(elements)) <NEW_LINE> for index, elem in enumerate(elements): <NEW_LINE> <INDENT> arr[index] = elem <NEW_LINE> <DEDENT> return arr
|
Copy an iterable sequence into a typed .NET array.
|
625941b523849d37ff7b2e8c
|
def read_schema_from_db(cur, table): <NEW_LINE> <INDENT> num_rows = cur.execute("""DESCRIBE {}""".format(table)) <NEW_LINE> tbl_schema = [] <NEW_LINE> for i in range(num_rows): <NEW_LINE> <INDENT> row = cur.fetchone() <NEW_LINE> tbl_schema.append([row[0], row[1]]) <NEW_LINE> <DEDENT> return tbl_schema
|
Reads schema information from a table in the database.
Used to define mappings for import into Elasticsearch.
|
625941b521bff66bcd68474f
|
def clear_uwsgi_cache(self): <NEW_LINE> <INDENT> uwsgi.cache_clear()
|
Clear ENTIRE uwsgi cache
You probably dont need this
|
625941b5b5575c28eb68ddf7
|
def insert(self, idx, a, copy=True): <NEW_LINE> <INDENT> self._uncache('labels') <NEW_LINE> adup = copy and QEAtom(a) or a <NEW_LINE> adup.lattice = self.lattice <NEW_LINE> list.insert(self, idx, adup) <NEW_LINE> if hasattr(self, '_qeInput') and self._qeInput != None: <NEW_LINE> <INDENT> self._qeInput.update() <NEW_LINE> <DEDENT> return
|
Insert atom a before position idx in this Structure.
idx -- position in atom list
a -- instance of QEAtom
copy -- flag for inserting a copy of a.
When False, append a and update a.lattice.
No return value.
|
625941b5627d3e7fe0d68c48
|
def search(values): <NEW_LINE> <INDENT> values = reduce_puzzle(values) <NEW_LINE> if values is False: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> all_solved_values = [box for box in values if len(values[box]) == 1] <NEW_LINE> if len(all_solved_values) == len(values): <NEW_LINE> <INDENT> return values <NEW_LINE> <DEDENT> n, pick_min_box = min((len(values[s]), s) for s in boxes if len(values[s]) > 1) <NEW_LINE> for digit in values[pick_min_box]: <NEW_LINE> <INDENT> new_values = values.copy() <NEW_LINE> new_values[pick_min_box] = digit <NEW_LINE> attempt = search(new_values) <NEW_LINE> if attempt: <NEW_LINE> <INDENT> return attempt
|
Apply depth first search to solve Sudoku puzzles in order to solve puzzles
that cannot be solved by repeated reduction alone.
Parameters
----------
values(dict)
a dictionary of the form {'box_name': '123456789', ...}
Returns
-------
dict or False
The values dictionary with all boxes assigned or False
Notes
-----
You should be able to complete this function by copying your code from the classroom
and extending it to call the naked twins strategy.
|
625941b57b25080760e39255
|
def weights(self): <NEW_LINE> <INDENT> n = self.n <NEW_LINE> k = self.kappa <NEW_LINE> W = np.full(2*n+1, .5 / (n + k)) <NEW_LINE> W[0] = k / (n+k) <NEW_LINE> return W, W
|
Computes the weights for the unscented Kalman filter. In this
formulatyion the weights for the mean and covariance are the same.
**Returns**
Wm : ndarray[2n+1]
weights for mean
Wc : ndarray[2n+1]
weights for the covariances
|
625941b5bf627c535bc12fd1
|
def test_iter_for_one_cycle_graph(self): <NEW_LINE> <INDENT> str_answer = "\n".join(sorted(["VERTEX{ ID=_i_am_Groot_;Parents=[];Children=[21];Type=VERTEX }", "VERTEX{ ID=21;Parents=[u'_i_am_Groot_'];Children=[22, 23];Type=VERTEX }", "VERTEX{ ID=22;Parents=[21];Children=[24];Type=VERTEX }", "VERTEX{ ID=23;Parents=[21];Children=[24];Type=VERTEX }", "VERTEX{ ID=24;Parents=[22, 23];Children=[];Type=VERTEX }"])) <NEW_LINE> cur_graph = self.func_make_one_cycle_graph() <NEW_LINE> lstr_traversal = [] <NEW_LINE> for vtx_node in cur_graph: <NEW_LINE> <INDENT> lstr_traversal.append(vtx_node.func_detail()) <NEW_LINE> <DEDENT> str_result = "\n".join(sorted(lstr_traversal)) <NEW_LINE> self.func_test_equals(str_answer, str_result)
|
Iter should give a breadth first traversal across all graphs.
|
625941b521bff66bcd684750
|
def show_table(self): <NEW_LINE> <INDENT> log.info("Showing the weights table ...") <NEW_LINE> print("") <NEW_LINE> print(self.table)
|
This function ...
:return:
|
625941b555399d3f055884ad
|
def setPerspectiveName(self, perspectiveName): <NEW_LINE> <INDENT> return self.getDbRecord().setColumnValue(PERSPECTIVE_NAME_COLUMN, perspectiveName)
|
Set your perspective.
|
625941b5dd821e528d63afa6
|
def handle_vulnerabilities(self, obj): <NEW_LINE> <INDENT> is_valid_vul = [] <NEW_LINE> for threat in obj: <NEW_LINE> <INDENT> assert threat['external_id'] is not None <NEW_LINE> is_vul = isinstance(threat, dict) <NEW_LINE> is_valid_vul.append(is_vul) <NEW_LINE> <DEDENT> return all(is_valid_vul)
|
validate vulnerability json
|
625941b55fdd1c0f98dc002c
|
def test_file_content(self): <NEW_LINE> <INDENT> log_files_a = [file for file in glob.glob(A_DIR_PATH + '/*')] <NEW_LINE> log_files_b = [file for file in glob.glob(B_DIR_PATH + '/*')] <NEW_LINE> for log_file in log_files_a + log_files_b: <NEW_LINE> <INDENT> with open(log_file, 'r') as file: <NEW_LINE> <INDENT> for line_num, line in enumerate(file): <NEW_LINE> <INDENT> assert line.startswith(LINES[line_num])
|
assert the content of the log file is correct
|
625941b54527f215b584c256
|
def __init__(self, dt): <NEW_LINE> <INDENT> state_labels = [("Left velocity", "m/s"), ("Right velocity", "m/s")] <NEW_LINE> u_labels = [("Left voltage", "V"), ("Right voltage", "V")] <NEW_LINE> self.set_plot_labels(state_labels, u_labels) <NEW_LINE> u_min = np.array([[-12.0], [-12.0]]) <NEW_LINE> u_max = np.array([[12.0], [12.0]]) <NEW_LINE> frccnt.System.__init__(self, np.zeros((2, 1)), u_min, u_max, dt)
|
Drivetrain subsystem.
Keyword arguments:
dt -- time between model/controller updates
|
625941b56fece00bbac2d535
|
def downloadOne(self, remotename, localpath): <NEW_LINE> <INDENT> if self.isTextKind(remotename): <NEW_LINE> <INDENT> localfile = open(localpath, 'w', encoding=self.connection.encoding) <NEW_LINE> def callback(line): <NEW_LINE> <INDENT> localfile.write(line + '\n') <NEW_LINE> <DEDENT> self.connection.retrlines('RETR ' + remotename, callback) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> localfile = open(localpath, 'wb') <NEW_LINE> self.connection.retrbinary('RETR ' + remotename, localfile.write) <NEW_LINE> <DEDENT> localfile.close()
|
download one file by FTP in text or binary mode
local name need not be same as remote name
|
625941b57d847024c06be0ba
|
def compute_circular_fragments_sets(self, fragments_sets_filters=()): <NEW_LINE> <INDENT> def generator(): <NEW_LINE> <INDENT> seen_hashes = set() <NEW_LINE> for cycle in nx.simple_cycles(self.filtered_connections_graph): <NEW_LINE> <INDENT> cycle = [self.fragments_dict[i] for i in cycle] <NEW_LINE> cycle = FragmentChain(cycle, is_cycle=True).standardized() <NEW_LINE> cycle_hash = hash(cycle) <NEW_LINE> if cycle_hash in seen_hashes: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> seen_hashes.add(cycle_hash) <NEW_LINE> if all(fl(cycle.fragments) for fl in fragments_sets_filters): <NEW_LINE> <INDENT> yield cycle.fragments <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return generator()
|
Return an iterator over all the lists of fragments [f1, f2, f3...fn]
that can assemble into a circular construct.
This means that fragment f1 will clip with f2 (in this order),
f2 with f3... and fn with f1.
Parameters
----------
fragments_sets_filters
A list of test functions of the form (set->True/False) where "set" is
a list of fragments from the mix (which assemble into a circular
construct). Only circular fragments sets passing all these tests
will be returned
|
625941b51f5feb6acb0c494f
|
def updatePositionAndAppearance(self): <NEW_LINE> <INDENT> self.setPos(*self.point()) <NEW_LINE> isLeft = False if self._is_drawn_5to3 else True <NEW_LINE> self._updateLabel(isLeft)
|
Same as XoverItem3, but exposes 3' end
|
625941b57cff6e4e81117780
|
def points(self): <NEW_LINE> <INDENT> if not check_permission(self.get_status(), "points"): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> global mariadb <NEW_LINE> points = mariadb.get_points(self.user.id) <NEW_LINE> embed = Embed(color=0x00ff00) <NEW_LINE> embed.set_author(name=str(self.user.name), icon_url=str(self.user.avatar_url)) <NEW_LINE> embed.add_field(name="Статистика", value="{0} догекойнов\n{1} место в топе".format(str(points[0]), str(points[1])), inline = True) <NEW_LINE> return ["embed", embed]
|
Посчитать поинты пользователя.
|
625941b5be8e80087fb20a49
|
def get_gcal_service(credentials): <NEW_LINE> <INDENT> if credentials == None: <NEW_LINE> <INDENT> return flask.redirect(flask.url_for('index')) <NEW_LINE> <DEDENT> app.logger.debug("Entering get_gcal_service") <NEW_LINE> http_auth = credentials.authorize(httplib2.Http()) <NEW_LINE> service = discovery.build('calendar', 'v3', http=http_auth) <NEW_LINE> app.logger.debug("Returning service") <NEW_LINE> return service
|
We need a Google calendar 'service' object to obtain
list of calendars, busy times, etc. This requires
authorization. If authorization is already in effect,
we'll just return with the authorization. Otherwise,
control flow will be interrupted by authorization, and we'll
end up redirected back to /choose *without a service object*.
Then the second call will succeed without additional authorization.
|
625941b59b70327d1c4e0bce
|
def listener(self, output): <NEW_LINE> <INDENT> count = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self.result_out.recv() <NEW_LINE> if result is None: <NEW_LINE> <INDENT> count += 1 <NEW_LINE> if count == self.processes: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> result, cpu = result <NEW_LINE> output.write("{0} (cpu {1})\n".format(result, cpu)) <NEW_LINE> <DEDENT> output.flush() <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> pass
|
Monitor result queue and write to stdout
|
625941b5a79ad161976cbf40
|
def objects(self, attribute_name=None): <NEW_LINE> <INDENT> if attribute_name is None: <NEW_LINE> <INDENT> objects = [ node for ( node, data) in self.nodes( data=True) if data['type'] == 'object'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> objects = self[attribute_name] <NEW_LINE> <DEDENT> objects = sorted(objects) <NEW_LINE> return(objects)
|
Returns objects corresponding to an attribute.
Parameters:
-----------------------------------
attribute_name : str
Attribute whose objects are to found
Returns:
-----------------------------------
objects : list
Array of objects corresponding to the given attribute_name
|
625941b53c8af77a43ae3599
|
def federal_mindessitzzahl(parties, mindessitzzahl): <NEW_LINE> <INDENT> return [sum_party_across_states(mindessitzzahl, x) for x in parties]
|
Return the Mindessitzzahl for each party across all states.
>>> mindessitzzahl = [(3, [('CDU', 11), ('SPD', 24), ('MLPD', 3)]), (11, [('CDU', 7), ('SPD', 60)]), (13, [('CDU', 1), ('SPD', 40)])]
>>> federal_mindessitzzahl(['CDU', 'SPD'], mindessitzzahl)
[('CDU', 19), ('SPD', 124)]
|
625941b5293b9510aa2c3094
|
@module.register("while") <NEW_LINE> def while_(env) -> "(c c -- )": <NEW_LINE> <INDENT> global shouldbreak <NEW_LINE> cond, code = env.stack.popN(2) <NEW_LINE> while True: <NEW_LINE> <INDENT> env.eval(cond.val) <NEW_LINE> if not env.stack.pop().val or shouldbreak: <NEW_LINE> <INDENT> shouldbreak = False <NEW_LINE> break <NEW_LINE> <DEDENT> env.eval(code.val)
|
Pops two code objects. While running the first code object results in #t, the second code object is run.
The second code object might not run at all
|
625941b585dfad0860c3ac53
|
def get_error(self): <NEW_LINE> <INDENT> return self._error
|
After executing a validation process, if it fails this method returns the cause
|
625941b501c39578d7e74c3e
|
def test_05(self): <NEW_LINE> <INDENT> self.pkg("list -aHf foo@1.0-0 pkg://test2/foo@1.1-0") <NEW_LINE> expected = "foo 1.0-0 ---\n" "foo (test2) 1.1-0 ---\n" "foo (test2) 1.0-0 ---\n" "hier/foo 1.0-0 ---\n" "hier/foo (test2) 1.0-0 ---\n" <NEW_LINE> output = self.reduceSpaces(self.output) <NEW_LINE> expected = self.reduceSpaces(expected) <NEW_LINE> self.assertEqualDiff(expected, output) <NEW_LINE> self.pkg("list -aHf foo@1.0-0 pkg://test2/foo@1.1-0") <NEW_LINE> expected = "foo 1.0-0 ---\n" "foo (test2) 1.1-0 ---\n" "foo (test2) 1.0-0 ---\n" "hier/foo 1.0-0 ---\n" "hier/foo (test2) 1.0-0 ---\n" <NEW_LINE> output = self.reduceSpaces(self.output) <NEW_LINE> expected = self.reduceSpaces(expected) <NEW_LINE> self.assertEqualDiff(expected, output)
|
Show foo@1.0 from both depots, but 1.1 only from test2.
|
625941b57cff6e4e81117781
|
def IC_resonance_frequency(B=3.7, species='H'): <NEW_LINE> <INDENT> m, q = ion_mass_and_charge(species) <NEW_LINE> return q*B/(2*pi*m)/1e6
|
Returns the fundamental cyclotron resonance frequency (in MHz)
Arguments:
B: magnetic field magnitude [T] (default: 3.7)
species: '1H', '2H', '3H', '4He', '3He' (more possibilities, cf ion_mass_and_charge definition)
Returns:
f: fundamental cyclotron resonance frequency [MHz]
|
625941b55166f23b2e1a4f53
|
def do_acc(self, elm): <NEW_LINE> <INDENT> c_dict = self.process_children_dict(elm) <NEW_LINE> latex_s = get_val(c_dict['accPr'].chr, default=CHR_DEFAULT.get('ACC_VAL'), store=CHR) <NEW_LINE> return latex_s.format(c_dict['e'])
|
the accent function
|
625941b5be7bc26dc91cd401
|
def get_filter(self, identifiers, resource, request): <NEW_LINE> <INDENT> return self._get_filter_recursive([], identifiers, resource.model, resource, request)
|
:param identifiers: list of identifiers that conclusively identifies a filter.
:param resource: resource object.
:param request: django HTTP request.
:return: method returns filter object according to input identifiers, resource and request.
|
625941b5d164cc6175782b48
|
def __getitem__(self, i): <NEW_LINE> <INDENT> if not self.__full: <NEW_LINE> <INDENT> if i < 0: <NEW_LINE> <INDENT> self.__fill_list__() <NEW_LINE> <DEDENT> elif i >= list.__len__(self): <NEW_LINE> <INDENT> diff=i-list.__len__(self)+1 <NEW_LINE> for j in range(diff): <NEW_LINE> <INDENT> value = next(self.iter) <NEW_LINE> self.append(value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return super(_indexable_generator, self).__getitem__(i)
|
Support indexing positive/negative elements of the generator,
but no slices. If you want those, use list(generator)
|
625941b58a43f66fc4b53e64
|
def forward(self, x): <NEW_LINE> <INDENT> branch1 = self.branch1_3x3(x) <NEW_LINE> branch2 = self.branch2_1x1(x) <NEW_LINE> branch2 = self.branch2_3x3_1(branch2) <NEW_LINE> branch2 = self.branch2_3x3_2(branch2) <NEW_LINE> branch3 = self.branch3_maxpool(x) <NEW_LINE> return torch.cat([branch1, branch2, branch3], 1)
|
Pytorch forward function implementation
|
625941b5bde94217f3682bf7
|
def script_path_user(): <NEW_LINE> <INDENT> path = _user_resource('SCRIPTS') <NEW_LINE> return _os.path.normpath(path) if path else None
|
returns the env var and falls back to home dir or None
|
625941b5e8904600ed9f1d24
|
def _merge_default_with_oplog(graph, op_log=None, run_meta=None): <NEW_LINE> <INDENT> tmp_op_log = tfprof_log_pb2.OpLog() <NEW_LINE> logged_ops = _get_logged_ops(graph, run_meta) <NEW_LINE> if not op_log: <NEW_LINE> <INDENT> tmp_op_log.log_entries.extend(logged_ops.values()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> all_ops = dict() <NEW_LINE> for entry in op_log.log_entries: <NEW_LINE> <INDENT> all_ops[entry.name] = entry <NEW_LINE> <DEDENT> for op_name, entry in logged_ops.iteritems(): <NEW_LINE> <INDENT> if op_name in all_ops: <NEW_LINE> <INDENT> all_ops[op_name].types.extend(entry.types) <NEW_LINE> if entry.float_ops > 0 and all_ops[op_name].float_ops == 0: <NEW_LINE> <INDENT> all_ops[op_name].float_ops = entry.float_ops <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> all_ops[op_name] = entry <NEW_LINE> <DEDENT> <DEDENT> tmp_op_log.log_entries.extend(all_ops.values()) <NEW_LINE> <DEDENT> return tmp_op_log
|
Merge the tfprof default extra info with caller's op_log.
Args:
graph: tf.Graph.
op_log: OpLog proto.
run_meta: RunMetadata proto used to complete shape information.
Returns:
tmp_op_log: Merged OpLog proto.
|
625941b57b180e01f3dc4601
|
def main(): <NEW_LINE> <INDENT> rundata = { 'olx' : True, 'wuzzuf' : False, 'tanqeeb': True } <NEW_LINE> for rundata, value in rundata.items(): <NEW_LINE> <INDENT> if value: <NEW_LINE> <INDENT> if rundata == 'olx': <NEW_LINE> <INDENT> countryparams = [ {"country":"jordan", "url":"https://olx.jo/en/", "timezone":"Asia/Amman"}, {"country":"egypt", "url":"https://olx.com.eg/en/", "timezone":"Africa/Cairo"} ] <NEW_LINE> for params in countryparams: <NEW_LINE> <INDENT> od = OLXDownloader(params) <NEW_LINE> od.run_all() <NEW_LINE> <DEDENT> <DEDENT> elif rundata == 'tanqeeb': <NEW_LINE> <INDENT> countryparams = [ {"country":"algeria", "webname":"algerie", "timezone":"Africa/Algiers"}, {"country":"egypt", "webname":"egypt", "timezone":"Africa/Cairo"}, {"country":"jordan", "webname":"jordan", "timezone":"Asia/Amman"}, {"country":"morocco", "webname":"morocco", "timezone":"Africa/Casablanca"}, {"country":"tunisia", "webname":"tunisia", "timezone":"Africa/Tunis"} ] <NEW_LINE> for params in countryparams: <NEW_LINE> <INDENT> td = TanQeebDownloader(params) <NEW_LINE> td.run_all() <NEW_LINE> <DEDENT> <DEDENT> elif rundata == 'wuzzuf': <NEW_LINE> <INDENT> wd = WuzzufDownloader() <NEW_LINE> wd.run_all()
|
Function to run downloads of various data.
|
625941b515fb5d323cde0903
|
def set_version(self, version): <NEW_LINE> <INDENT> self._version = version
|
Sets the version number to be returned.
|
625941b5ab23a570cc24ff7a
|
def make_parser(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser("Get stats from time series dataset files") <NEW_LINE> parser.add_argument( "-tr", "--train", default="train.txt", help="path to training data file") <NEW_LINE> parser.add_argument( "-te", "--test", default="test.txt", help="path to test data file") <NEW_LINE> parser.add_argument( "-v", "--verbosity", type=int, default=1, help="verbosity level for logging; default=1 (INFO)") <NEW_LINE> return parser
|
Create CLI parser.
|
625941b57b180e01f3dc4602
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.