code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def clean(self): <NEW_LINE> <INDENT> if FEEDBACK_ANTISPAM['CHECKING_HIDDEN_FIELD']: <NEW_LINE> <INDENT> if len(self.cleaned_data.get('message_', '')): <NEW_LINE> <INDENT> self._errors['message_'] = 'unhuman message found' <NEW_LINE> <DEDENT> <DEDENT> if FEEDBACK_ANTISPAM['BLOCKING_EXTERNAL_LINKS']: <NEW_LINE> <INDENT> ... | Check spam in fields | 625941cc7b25080760e39551 |
def fill_repair_car_table(conn): <NEW_LINE> <INDENT> for k in range(8, 11): <NEW_LINE> <INDENT> for j in range(1, 30): <NEW_LINE> <INDENT> date = datetime.date(2018, k, j) <NEW_LINE> for i in range(10): <NEW_LINE> <INDENT> wid = workshops[random.randint(0, len(workshops) - 1)] <NEW_LINE> car_id = cars[random.randint(0,... | Method for filling the reparation car table
:param conn: Database connection
:return: 0: table has filled, otherwise -1 | 625941cc7b25080760e39552 |
def generate_impact_report(impact_function, iface): <NEW_LINE> <INDENT> extra_layers = [] <NEW_LINE> print_atlas = setting('print_atlas_report', False, bool) <NEW_LINE> if print_atlas: <NEW_LINE> <INDENT> extra_layers.append(impact_function.aggregation_summary) <NEW_LINE> <DEDENT> report_metadata = ReportMetadata( meta... | Generate the impact report from an impact function.
:param impact_function: The impact function used.
:type impact_function: ImpactFunction
:param iface: QGIS QGisAppInterface instance.
:type iface: QGisAppInterface | 625941cc4e4d5625662d44d0 |
def check_filteraction(option, opt, value): <NEW_LINE> <INDENT> match = re.match(r"RATE_LIMIT\s+(\d+)", value) <NEW_LINE> if match: <NEW_LINE> <INDENT> n = int(match.group(1)) <NEW_LINE> return ["RATE_LIMIT", n] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return value | Custom parser for filter rule actions.
Takes a string, returns an action as a Python object (list or string).
The string "RATE_LIMIT n" becomes `["RATE_LIMIT", n]`.
All other strings stay as they are. | 625941ccd486a94d0b98e23e |
@pass_context <NEW_LINE> def sync_do_rejectattr( context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any ) -> "t.Iterator[V]": <NEW_LINE> <INDENT> return select_or_reject(context, value, args, kwargs, lambda x: not x, True) | Filters a sequence of objects by applying a test to the specified
attribute of each object, and rejecting the objects with the test
succeeding.
If no test is specified, the attribute's value will be evaluated as
a boolean.
.. sourcecode:: jinja
{{ users|rejectattr("is_active") }}
{{ users|rejectattr("email",... | 625941cc4d74a7450ccd42bc |
def clone(self, repo, subpath=None): <NEW_LINE> <INDENT> cwd = self.docroot <NEW_LINE> name = None <NEW_LINE> if subpath: <NEW_LINE> <INDENT> subpath = subpath.strip("/") <NEW_LINE> if subpath.endswith(".git"): <NEW_LINE> <INDENT> subpath, name = os.path.split(subpath) <NEW_LINE> <DEDENT> if subpath: <NEW_LINE> <INDENT... | Clone LocalPath repo and return remote for client to add. | 625941cc287bf620b61d3b5c |
def add_community(self, community): <NEW_LINE> <INDENT> community.assign_to_polity(self) <NEW_LINE> self.communities.append(community) | Incorporate a community to the polity.
Args:
community (Community): The community to add.
Notes:
This routine is not safe as it does not check whether the community
already belongs to a polity. It is only used in testing. | 625941cc60cbc95b062c663c |
@app.route("/api/v1.0/<min_date_str>") <NEW_LINE> def get_temperatures_from_start(min_date_str): <NEW_LINE> <INDENT> rs = session .query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)) .filter(Measurement.date >= min_date_str) .all() <NEW_LINE> tobs_list = rs[0] ... | Return a json list of the minimum temperature, the average temperature, and
the max temperature for a given start or start-end range.
When given the start only, calculate `TMIN`, `TAVG`, and `TMAX` for all
dates greater than and equal to the start date. | 625941cc3cc13d1c6d3c7473 |
def deserialize_view_instance(data, view_instance): <NEW_LINE> <INDENT> data = _json.loads(data) <NEW_LINE> id = data['id'] <NEW_LINE> type_id = data['type_id'] <NEW_LINE> filter_ids = data['filter_ids'] <NEW_LINE> sorter_ids = data['sorter_ids'] <NEW_LINE> result_id = data['result_id'] <NEW_LINE> view_instance.id = id... | Populates `view_instance` with values extracted from `data`.
Args:
data (str): Raw JSON string containing ``ViewInstance`` data.
view_instance (ViewInstance): An ``ViewInstance`` instance to be
populated with `data`.
Returns:
None | 625941cc3d592f4c4ed1d166 |
def removeDuplicates(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0 or len(nums) == 1: return len(nums) <NEW_LINE> flag = 0 <NEW_LINE> count = 1 <NEW_LINE> for i in range(1, len(nums)): <NEW_LINE> <INDENT> if nums[flag] == nums[i] and count == 2: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif nums[flag] == n... | :type nums: List[int]
:rtype: int | 625941cc91af0d3eaac9bb11 |
def destroy(self, request, pk=None): <NEW_LINE> <INDENT> return Response({'http_method','DELETE'}) | Deletes an object from the database | 625941cc76d4e153a657ec29 |
def _get_controller(event, context): <NEW_LINE> <INDENT> user = User.Factory().load_by_session(event['session_uuid']) <NEW_LINE> return Volunteer.Controller(user) | Creates and returns the Controller object | 625941cccc0a2c11143dcf89 |
def terminate(self, timeoutMs=3000): <NEW_LINE> <INDENT> if self.stdin is not None: <NEW_LINE> <INDENT> self.closeStdin() <NEW_LINE> <DEDENT> self.terminateCommand() <NEW_LINE> timer = timeoutMs / 1000 <NEW_LINE> interval = 0.1 <NEW_LINE> while timer > 0 and self.isAlive(): <NEW_LINE> <INDENT> timer = timer - interval ... | Terminate both the target process (the command) and reader queues.
Use :meth:`terminate` to gracefully stop the target process (the
command) and readers once you're done reading. Use :meth:`shutdown`
if you are just trying to clean up, as it will trigger
:meth:`terminate`.
Args:
timeoutMs (int): Milliseconds :met... | 625941cc32920d7e50b282c8 |
def OnMoreSquareToggle(self, event): <NEW_LINE> <INDENT> self.squareMap.square_style = not self.squareMap.square_style <NEW_LINE> self.squareMap.Refresh() <NEW_LINE> self.moreSquareViewItem.Check(self.squareMap.square_style) | Toggle the more-square view (better looking, but more likely to filter records) | 625941cc3c8af77a43ae3899 |
def compute_vfr_loss(self): <NEW_LINE> <INDENT> idxs = self.replay_buffer.sample_idxs(self.aux_batch_size) <NEW_LINE> vision, scent, state, reward = self.get_io_from_replay_buffer(idxs, batch_size=self.aux_batch_size, seq_len=self.seq_len) <NEW_LINE> val, _ = self.A.forward(vision, scent, state) <NEW_LINE> return self.... | Computes Value Function Replay Loss. | 625941cc31939e2706e4cf63 |
def time_in_traffic_sec(origin, destination, api_key): <NEW_LINE> <INDENT> endpoint = 'https://maps.googleapis.com/maps/api/directions/json?' <NEW_LINE> departure_time = 'now' <NEW_LINE> nav_req = 'origin={}&destination={}&departure_time={}&key={}'.format( origin, destination, departure_time, api_key) <NE... | Returns time in traffic from origin to destination | 625941cc596a897236089bb9 |
def flatten(self, layers=[]): <NEW_LINE> <INDENT> if layers == []: <NEW_LINE> <INDENT> layers = range(1, len(self.layers)) <NEW_LINE> <DEDENT> background = self.layers._get_bg() <NEW_LINE> background.name = "Background" <NEW_LINE> for i in layers: <NEW_LINE> <INDENT> layer = self.layers[i] <NEW_LINE> x = max(0, layer.x... | Flattens all layers according to their blend modes.
Merges all layers to the canvas,
using the blend mode and opacity defined for each layer.
Once flattened, the stack of layers is emptied except
for the transparent background (bottom layer). | 625941cc4e696a04525c9544 |
def test_startlaniperror(self): <NEW_LINE> <INDENT> L.info("test_startlaniperror START:开始ip地址范围非法,提示信息检查") <NEW_LINE> driver = self.driver <NEW_LINE> print("caseid:006") <NEW_LINE> driver.get(self.baseurl) <NEW_LINE> login(driver) <NEW_LINE> time.sleep(2) <NEW_LINE> driver.find_element_by_xpath("//div[@id='want_more_id... | 开始ip地址范围非法,提示信息检查 | 625941ccb545ff76a8913f0f |
def noise_reduction(x, env, feed_through=False): <NEW_LINE> <INDENT> if feed_through: <NEW_LINE> <INDENT> return x <NEW_LINE> <DEDENT> largest = np.max(env, axis=1) <NEW_LINE> smallest = np.min(env, axis=1) <NEW_LINE> snr = 10 * np.log10(largest/smallest) <NEW_LINE> w = snr / (1 + snr) <NEW_LINE> y = x * np.tile(w, (x.... | Reduces the noise in the signal by applying a gain between 0 and 1.
This gain's value is:
closer to 1 if the Signal-to-Noise Ratio (SNR) is high
closer to 0 if the SNR is low.
This means that the buffers with a poor SNR are reduced in volume.
Parameters
----------
x: ndarray
the input data
env: ndarray
... | 625941cce76e3b2f99f3a904 |
def repeatedSubstringPattern(self, s: str) -> bool: <NEW_LINE> <INDENT> n = len(s) <NEW_LINE> for i in range(n // 2): <NEW_LINE> <INDENT> x = s[:(i + 1)] <NEW_LINE> if x * (n // len(x)) == s: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False | >>> solution = Solution()
>>> solution.repeatedSubstringPattern('aaa')
True
>>> solution.repeatedSubstringPattern('aba')
False
>>> solution.repeatedSubstringPattern('ababab')
True
>>> solution.repeatedSubstringPattern('abababc')
False
>>> solution.repeatedSubstringPattern('abababa')
False
>>> solution.repeatedSubstring... | 625941cc293b9510aa2c338f |
def __init__(self, token: str = '', plugins: Iterable[PluginConfig] = None, max_workers: int = None) -> None: <NEW_LINE> <INDENT> super().__init__(plugins=plugins, max_workers=max_workers) <NEW_LINE> self.client = self.setup_client(token=token) <NEW_LINE> self.message_id = 0 <NEW_LINE> self.ws = None <NEW_LINE> self.co... | Initializer.
:param token: Access token provided by Slack.
:param plugins: List of plugin modules.
:param max_workers: Optional number of worker threads.
:return: None | 625941cc4c3428357757c420 |
def parse_string_factory( alg: NSType, sep: StrOrBytes, splitter: StrSplitter, input_transform: StrToStr, component_transform: StrTransformer, final_transform: FinalTransformer, ) -> StrParser: <NEW_LINE> <INDENT> orig_after_xfrm = not (alg & NS_DUMB and alg & ns.LOCALEALPHA) <NEW_LINE> original_func = input_transform ... | Create a function that will split and format a *str* into a tuple.
Parameters
----------
alg : ns enum
Indicate how to format and split the *str*.
sep : str
The string character to be inserted between adjacent numeric
objects in the returned tuple.
splitter : callable
A function the will accept a strin... | 625941cc2eb69b55b151c9a8 |
def setModelFromParams(self): <NEW_LINE> <INDENT> parameters = self.getParams() <NEW_LINE> self._model.removeRows(0, self._model.rowCount()) <NEW_LINE> for parameter in list(parameters.keys()): <NEW_LINE> <INDENT> item1 = QtGui.QStandardItem(parameter) <NEW_LINE> if isinstance(parameters[parameter], bool): <NEW_LINE> <... | Set up the Qt model for data handling between controls | 625941cc97e22403b379d092 |
def draw_all_text_cmd(input_pic, output_pic, text_content=None, label_color=None, value_color=None, font="simhei", font_size=20, unit_opacity=1, board_display=0, board_color=None, board_opacity=0.5): <NEW_LINE> <INDENT> all_text_info = text_content <NEW_LINE> drawed_text = str() <NEW_LINE> for each in all_text_info: <N... | draw text on one pic | 625941cc66656f66f7cbc2a3 |
def __init__(self, **kwargs): <NEW_LINE> <INDENT> ProcessingNode.__init__(self, name = 'highpass filter', mode = 'editable', category = 'frequency', tags = ['filter', 'highpass'], **kwargs ) <NEW_LINE> item = FloatSpinPrefItem(name = 'frequ.', value = 1, limit = (0, None), digits = 1, increment = 1 ) <NEW_LINE> self.pr... | The constructor
| 625941cc66673b3332b9218a |
def job_result_format(self, job_id, format): <NEW_LINE> <INDENT> return self.api.job_result_format(job_id, format) | Params:
job_id (str): job id
format (str): output format of result set
Returns: a list of each rows in result set | 625941cc63d6d428bbe445e8 |
def _set_g_time_now(self): <NEW_LINE> <INDENT> g_time = datetime.datetime.now( self.location.tz).replace(tzinfo=self.location.tzinfo) <NEW_LINE> return g_time | Updates the g_datetime to reflect current time. | 625941cc0c0af96317bb82e1 |
def elapseTime(self, gameState): <NEW_LINE> <INDENT> self.particles = [util.sample(self.getPositionDistribution(self.setGhostPosition(gameState, particle))) for particle in self.particles] | Update beliefs for a time step elapsing.
As in the elapseTime method of ExactInference, you should use:
newPosDist = self.getPositionDistribution(self.setGhostPosition(gameState, oldPos))
to obtain the distribution over new positions for the ghost, given its
previous position (oldPos) as well as Pacman's current p... | 625941cc76e4537e8c35176c |
def setPalette(self, QPalette): <NEW_LINE> <INDENT> pass | setPalette(self, QPalette) | 625941cccc40096d61595a4a |
def __init__(self, title=None, save_to_filepath=None, show_regressions=True, show_averages=True, show_plot_window=True, x_label=None, y_label=None): <NEW_LINE> <INDENT> assert save_to_filepath is not None or show_plot_window <NEW_LINE> self.title = title <NEW_LINE> self.title_fontsize = 14 <NEW_LINE> self.show_regressi... | Constructs the plotter.
Args:
title: An optional title which will be shown at the top of the
plot. E.g. the name of the experiment or some info about it.
If set to None, no title will be shown. (Default is None.)
save_to_filepath: The path to a file in which the plot will be saved,
e.g.... | 625941cc01c39578d7e74f34 |
def start(self): <NEW_LINE> <INDENT> with self._proc.open(self._enabled_path, "w") as fobj: <NEW_LINE> <INDENT> fobj.write("1") | Start the latency measurements. | 625941cc07f4c71912b1157b |
def getoutfile(sfpath, outpath, ntimes): <NEW_LINE> <INDENT> os.system('ncks -O -dVAR,0 -vSFMOIS,TFLAG %s mettemp.nc' % sfpath) <NEW_LINE> os.system('ncdump -vTFLAG mettemp.nc > mettemp.cdl') <NEW_LINE> os.system('sed -E -e \'s/VAR-LIST = .*/VAR-LIST = "NMFM ";/\' -e "s/SFMOIS/NMFM/g" -e \'s/units = "perce... | Requires
sfpath - path to SFMOIS file
outpath - path for output file
Returns
open NetCDF output file | 625941cc29b78933be1e57a5 |
def add_completion(self, cmd_def, proto_cmd): <NEW_LINE> <INDENT> tgt_dict = self._complete <NEW_LINE> for i in range(len(cmd_def[0])): <NEW_LINE> <INDENT> if i == len(cmd_def[0]) - 1: <NEW_LINE> <INDENT> tgt_dict[cmd_def[0][i]] = proto_cmd <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tgt_dict = tgt_dict.setdefault(cm... | Register completion for cmd_def = (user_cmds, proto_args),
and point to apropriate protocol command | 625941cc7cff6e4e81117a7f |
def is_bv_add(self): <NEW_LINE> <INDENT> return self.node_type() == BV_ADD | Test whether the node is the BVAdd operator. | 625941ccbe7bc26dc91cd6f9 |
def authenticate_user(self, login, password): <NEW_LINE> <INDENT> raise AttributeError( "%s does not support this method" % self.__class__.__name__ ) | Authenticate a user.
:param login: Login of the user
:param password: Password of the user
:return: | 625941cc5166f23b2e1a5252 |
def load_meals(meals_filename): <NEW_LINE> <INDENT> print("Meals") <NEW_LINE> for i, row in enumerate(open(meals_filename)): <NEW_LINE> <INDENT> row = row.rstrip() <NEW_LINE> meal = Meal(user_id=user_id,) <NEW_LINE> db.session.add(meal) <NEW_LINE> if i % 1000 == 0: <NEW_LINE> <INDENT> print(i) <NEW_LINE> db.session.com... | Load ratings from u.data into database. | 625941cc30dc7b7665901a60 |
def get_thermo_data(self, molecule): <NEW_LINE> <INDENT> self.initialize() <NEW_LINE> if self.settings.software == 'mopac': <NEW_LINE> <INDENT> if self.settings.method == 'pm3': <NEW_LINE> <INDENT> qm_molecule_calculator = rmgpy.qm.mopac.MopacMolPM3(molecule, self.settings) <NEW_LINE> <DEDENT> elif self.settings.method... | Generate thermo data for the given :class:`Molecule` via a quantum mechanics calculation.
Ignores the settings onlyCyclics and maxRadicalNumber and does the calculation anyway if asked.
(I.e. the code that chooses whether to call this method should consider those settings). | 625941cc462c4b4f79d1d7ca |
def less_than_cut_out(self, u_mag): <NEW_LINE> <INDENT> return self.c_t_design * ((tanh(10*(u_mag-self.cut_in_speed))+1)/2) | The function describing the thrust coefficient for velocities <
cut_out_speed | 625941cc63b5f9789fde71df |
def padding(self): <NEW_LINE> <INDENT> padding = b"\x80" + b"\x00" * (63 - (len(self.data) + 8) % 64) <NEW_LINE> padded_data = self.data + padding + struct.pack(">Q", 8 * len(self.data)) <NEW_LINE> return padded_data | Дополняет данные нулями до 64байт/512бит | 625941ccd7e4931a7ee9e017 |
def get_value_by_ref_des(self, ref_des): <NEW_LINE> <INDENT> raise DeprecationWarning('Use Segment.get_value') | @param ref_des: X12 Reference Designator
@type ref_des: string
@attention: Deprecated - use get_value | 625941cc0383005118ecf6dc |
def applyGlobalOpts(self, plotOpts): <NEW_LINE> <INDENT> return plotOpts | if global options, add them | 625941cc15baa723493c406f |
def use_integer_ipv4(): <NEW_LINE> <INDENT> _roottypes[18] = StructType("ipv4address", 18, "L") | Use integers instead of ipaddress.IPv4Address to store IPv4 addresses.
Changes behavior globally; should be called before using any IPFIX types.
Designed for use with numpy arrays, to not require a Python object for
storing IP addresses. | 625941cc7d847024c06be3b5 |
def applyGravity(self, crawlerGravity=None, gravityMovements=None, crawlerRegen=None): <NEW_LINE> <INDENT> ArenaBasic.applyGravity(self, crawlerGravity, gravityMovements, crawlerRegen) <NEW_LINE> if gravityMovements is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> gravityDir = gravityMovements.direction <NEW_LIN... | zob | 625941cc01c39578d7e74f35 |
def serialize_deprecated(src, fields=None, related=None): <NEW_LINE> <INDENT> if (isinstance(src, models.Manager) or isinstance(src, models.query.QuerySet)): <NEW_LINE> <INDENT> return [serialize_deprecated(item, fields, related) for item in src.all()] <NEW_LINE> <DEDENT> if isinstance(src, list): <NEW_LINE> <INDENT> r... | Serialize Model or QuerySet to JSON format.
By default, all of the model fields (including 'id') are serialized, and
foreign key fields are serialized as the id of the referenced object.
If 'fields' tuple/list is specified, only fields listed in it are
serialized. If 'related' dict is specified, fields listed in it
w... | 625941ccd268445f265b4f67 |
def rpc_queue_task(self, request, jobname=None, **kw): <NEW_LINE> <INDENT> result = yield self.queue_task(request, jobname, **kw) <NEW_LINE> coroutine_return(task_to_json(result)) | Queue a new ``jobname`` in the task queue.
The task can be of any type as long as it is registered in the
task queue registry. To check the available tasks call the
:meth:`rpc_job_list` function.
It returns the task :attr:`~Task.id`. | 625941cc7b180e01f3dc48f7 |
def check_func_item(self, defn: FuncItem, type_override: Optional[CallableType] = None, name: Optional[str] = None) -> None: <NEW_LINE> <INDENT> self.dynamic_funcs.append(defn.is_dynamic() and not type_override) <NEW_LINE> with self.enter_partial_types(is_function=True): <NEW_LINE> <INDENT> typ = self.function_type(def... | Type check a function.
If type_override is provided, use it as the function type. | 625941ccac7a0e7691ed41c6 |
def test_get_related_genes(self): <NEW_LINE> <INDENT> sc35 = self.comp.Dmelanogaster.get_gene_by_stableid("FBgn0265298") <NEW_LINE> orthologs = self.comp.get_related_genes( gene_region=sc35, relationship="ortholog_one2one" ) <NEW_LINE> self.assertEqual("ortholog_one2one", list(orthologs)[0].relationship) | should correctly return the related gene regions from each genome | 625941cc9f2886367277a987 |
def get_user_name(self, uid): <NEW_LINE> <INDENT> results = self.server.search_s( "ou=Users,dc=sns,dc=ornl,dc=gov", ldap.SCOPE_SUBTREE, "(&(objectClass=posixAccount)(uid=%s))" % uid, ["cn",] ) <NEW_LINE> return results[0][1]['cn'][0].decode('UTF-8') | @return: list of {'Whitaker, Tracy H', 'Williamson, Richard L'...] | 625941cc004d5f362079a42c |
def SetURL(self,URL:'Any',InFlags:'Any'=0) -> 'None': <NEW_LINE> <INDENT> pass | Sets the URL for the shortcut
Args:
URL(Any):The url to be set
InFlags(Any):One of the shellcon.IURL_SETURL* flags
Returns:
None
| 625941ccf548e778e58cd677 |
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(TestGitDialog, self).__init__(parent) <NEW_LINE> self.setupUi(self) | Constructor. | 625941cccc0a2c11143dcf8a |
def test008_get_vdiskstorage_details(self): <NEW_LINE> <INDENT> self.lg.info(' [*] Get vdisk (VDS0), should succeed with 200') <NEW_LINE> response = self.vdisks_api.get_vdiskstorage_info(self.vdiskstoragedata["id"]) <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> for key in self.vdiskstoragedata.keys(... | GAT-145
*GET:/vdiskstorage/{vdiskstorageid}*
**Test Scenario:**
#. Create vdiskstorage (VDS0).
#. Get vdiskstorage (VDS0), should succeed with 200.
#. Get nonexisting vdiskstorage, should fail with 404. | 625941cc4e696a04525c9545 |
def dynamic_programming(items, capacity): <NEW_LINE> <INDENT> table = np.zeros((capacity+1, len(items)+1)) <NEW_LINE> for item in items: <NEW_LINE> <INDENT> j = item.index+1 <NEW_LINE> table[:,j] = table[:,j-1] <NEW_LINE> if item.weight > capacity: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for k in range(0, capa... | Table is of form:
j
k 0 . . N-1
0
1
.
.
K
where k is remaining capacity and j is the item number | 625941cc31939e2706e4cf64 |
def _buildencodefun(): <NEW_LINE> <INDENT> e = '_' <NEW_LINE> winreserved = [ord(x) for x in '\\:*?"<>|'] <NEW_LINE> cmap = dict([(chr(x), chr(x)) for x in xrange(127)]) <NEW_LINE> for x in (range(32) + range(126, 256) + winreserved): <NEW_LINE> <INDENT> cmap[chr(x)] = "~%02x" % x <NEW_LINE> <DEDENT> for x in range(ord... | >>> enc, dec = _buildencodefun()
>>> enc('nothing/special.txt')
'nothing/special.txt'
>>> dec('nothing/special.txt')
'nothing/special.txt'
>>> enc('HELLO')
'_h_e_l_l_o'
>>> dec('_h_e_l_l_o')
'HELLO'
>>> enc('hello:world?')
'hello~3aworld~3f'
>>> dec('hello~3aworld~3f')
'hello:world?'
>>> enc('thequickshot')
'the~... | 625941cc6e29344779a6270b |
def __init__(self, context, socket=None): <NEW_LINE> <INDENT> if not isinstance(context, Context): <NEW_LINE> <INDENT> raise TypeError("context must be a Context instance") <NEW_LINE> <DEDENT> ssl = _lib.SSL_new(context._context) <NEW_LINE> self._ssl = _ffi.gc(ssl, _lib.SSL_free) <NEW_LINE> _lib.SSL_set_mode(self._ssl,... | Create a new Connection object, using the given OpenSSL.SSL.Context
instance and socket.
:param context: An SSL Context to use for this connection
:param socket: The socket to use for transport layer | 625941cc8c3a8732951584b4 |
def Random(self) : <NEW_LINE> <INDENT> probas = np.random.rand(self.number_of_nodes(), self.number_of_nodes()) <NEW_LINE> return probas | returns a 2d array filled with only random value between 0 and 1 | 625941cc4f88993c3716c161 |
def parseNsOptionFromCommandline(commandline): <NEW_LINE> <INDENT> args = cmdlineutils.splitArgs(commandline)[1:] <NEW_LINE> options = cmdlineutils.Options() <NEW_LINE> nsOption = cmdlineutils.Option('ns', hasArg=True) <NEW_LINE> options.addOption(nsOption) <NEW_LINE> try: <NEW_LINE> <INDENT> commandLine = cmdlineutils... | Parses CMS host:port the current server is registered with
@types: str -> str or None
@tito: {r'"E:\Business Objects\BusinessObjects Enterprise 12.0\win32_x86\crcache.exe" -loggingPath "E:/Business Objects/BusinessObjects Enterprise 12.0/logging/" -cache -nops -documentType CrystalEnterprise.Report -fg -restart -name h... | 625941cc63f4b57ef0001213 |
def assemble_distribution(self): <NEW_LINE> <INDENT> self._copy_in_final_files() <NEW_LINE> self.distribution.save_info(self.dist_dir) | Copies all the files into the distribution (this function is
overridden by the specific bootstrap classes to do this)
and add in the distribution info. | 625941ccbe7bc26dc91cd6fa |
def dataset_generation(qa_list,objects): <NEW_LINE> <INDENT> data = [] <NEW_LINE> for sample in qa_list: <NEW_LINE> <INDENT> image_id = sample[0] <NEW_LINE> qa_id = sample[1] <NEW_LINE> question = sample[2] <NEW_LINE> answer = sample[3] <NEW_LINE> object1 = objects[qa_id][0][0] <NEW_LINE> object2 = objects[qa_id][0][-1... | write filtered training samples into csv file
:param qa_list:
return by qa_text_handler()
:param objects:
return by bound_box_position_handler() | 625941cc91f36d47f21ac5ec |
def __init__(self, learning_rate, beta=0.9, use_locking=False, name="SVAG"): <NEW_LINE> <INDENT> super(SVAGOptimizer, self).__init__(use_locking, name=name) <NEW_LINE> self._lr = learning_rate <NEW_LINE> self._beta = beta <NEW_LINE> self._lr_t = None <NEW_LINE> self._beta_t = None | Construct a new SVAGOptimizer optimizer.
Args:
:learning_rate: Learning rate (scalar tensor or float value).
:beta: Moving average constant (scalar tensor or float value).
:use_locking: If True use locks for update operations.
:name: Optional name prefix for the created ops (default: "SVAG"). | 625941cc0fa83653e46570b5 |
def get_slugs(url): <NEW_LINE> <INDENT> return "stanford-melee-biweekly", "melee-singles" | Input: smash.gg tournament URL, a string
Output: two strings: a tournament_slug and an event_slug
Suggestion: urllib.parse: https://docs.python.org/3/library/urllib.parse.html | 625941cc82261d6c526ab599 |
def SetLongHelp(self, help): <NEW_LINE> <INDENT> if self._kind == wx.ITEM_NORMAL: <NEW_LINE> <INDENT> self._longHelp = help | Sets the tool long help string (displayed in the parent frame :class:`StatusBar`).
:param string `help`: the new tool long help string. | 625941cce76e3b2f99f3a905 |
def convert_to_state_json(self): <NEW_LINE> <INDENT> self.validate_attributes() <NEW_LINE> json_species = [species_obj.convert_to_json() for species_obj in self.species] <NEW_LINE> json_hand = [trait_card.convert_to_json() for trait_card in self.hand] <NEW_LINE> return [self.food_bag, json_species, json_hand] | Converts tgis PlayerState to a remote protocol JSON player state
:return: a remote protocol JSON player state as specified in
http://www.ccs.neu.edu/home/matthias/4500-s16/r_remote.html | 625941cc91f36d47f21ac5ed |
def _npmi_score(self): <NEW_LINE> <INDENT> if self.model is None: <NEW_LINE> <INDENT> raise ValueError("You must call fit before you can score the quality of topics.") <NEW_LINE> <DEDENT> if self.doc_token2freq is None or self.token2freq is None: <NEW_LINE> <INDENT> self.token2freq, self.doc_token2freq = get_word_count... | Normalized pair-wise mutual information method of scoring
the quality of topics.
Note: this is not being calculated in the traditional way. This doesn't
use context windows for calculating word co-occurences, rather
words count as co-occuring if this both appear in the document, the
denominator in thi... | 625941cc73bcbd0ca4b2c170 |
def note_search(self, query): <NEW_LINE> <INDENT> return self._get('note/search', {'query': query}) | Search specific note.
Parameters:
query (str): A word or phrase to search for. | 625941cc6e29344779a6270c |
def read_hdf5_structure(h5file): <NEW_LINE> <INDENT> nodes = {} <NEW_LINE> for node in h5file: <NEW_LINE> <INDENT> path = node._v_pathname <NEW_LINE> if isinstance(node, tb.Table): <NEW_LINE> <INDENT> nodes[path] = node <NEW_LINE> <DEDENT> <DEDENT> return nodes | read all table-nodes from a hdf5-file
:param h5file:
:return: | 625941ccb545ff76a8913f10 |
def _getextension(fast): <NEW_LINE> <INDENT> extension = get_extension(fast) <NEW_LINE> if extension in ('.fa', '.fasta'): <NEW_LINE> <INDENT> extension = "fasta" <NEW_LINE> <DEDENT> elif extension in ('.fq', '.fastq'): <NEW_LINE> <INDENT> extension = "fastq" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise Exceptio... | finds and check for the correct extension. If extension is not correct it will return Exception and exit.
:param fast: fastq or fasta file
:return: "fastq" or "fasta"
:rtype: str | 625941cc1d351010ab855c15 |
def _find_descriptors(self, datamap, base_name='', base_offset=0): <NEW_LINE> <INDENT> for desc in datamap: <NEW_LINE> <INDENT> name = (desc.name if desc.external_name is None else desc.external_name) <NEW_LINE> if name is None: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> name = base_name + name <NEW_LINE> offset ... | Find descriptors and yield their values. | 625941cc24f1403a92600c60 |
def normalized_scalar_product(x1, x2): <NEW_LINE> <INDENT> return numpy.dot(x1, x2) / math.sqrt(numpy.dot(x1,x1) * numpy.dot(x2,x2)) | Computes the normalized scalar product (also known as the cosine between the two vectors).
This is a similarity measure, the results are in the range [-1,1],
or [0,1] when both vectors only have positive coefficients. | 625941ccd164cc6175782e47 |
def random_text(length=32): <NEW_LINE> <INDENT> res = list() <NEW_LINE> choice = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" <NEW_LINE> for _ in range(32): <NEW_LINE> <INDENT> res.append(random.choice(choice)) <NEW_LINE> <DEDENT> return "".join(res) | Generate fixed-length random string.
**中文文档**
生成定长随机字符串。 | 625941ccd486a94d0b98e23f |
def forward(self, state, action): <NEW_LINE> <INDENT> if state.dim()==1: state = torch.unsqueeze(state, 0) <NEW_LINE> xs = F.leaky_relu(self.fcs1(state), self.leak) <NEW_LINE> xs = self.bn1(xs) <NEW_LINE> x = torch.cat((xs, action), dim=1) <NEW_LINE> x = F.leaky_relu(self.fc2(x), self.leak) <NEW_LINE> x = self.fc3(x) <... | Build a critic (value) network that maps (state, action) pairs -> Q-values. | 625941ccdd821e528d63b2a3 |
def is_valid_property_value(bb): <NEW_LINE> <INDENT> return bool(_propvalue_re.search(bb)) | Check whether 'bb' is a well-formed PropValue.
bb -- bytes-like object
This accepts the same values as the tokeniser: any string that doesn't
contain an unescaped ] or end with an unescaped \ . | 625941cc711fe17d82542466 |
def test_sign_data_with_private_key_sha1(self): <NEW_LINE> <INDENT> alipay = self.get_web_client("RSA") <NEW_LINE> result1 = alipay._sign("hello\n", self.__web_private_key_path) <NEW_LINE> result2 = subprocess.check_output( "echo hello | openssl sha -sha1 -sign {} | openssl base64".format( self.__web_private_key_path )... | openssl 以及aliapy分别对数据进行签名,得到同样的结果
| 625941ccf8510a7c17cf97f7 |
def p_nestedParenCaptured_notParen(self, p): <NEW_LINE> <INDENT> p[0] = p[1] + p[2] | nestedParenCaptured : nestedParenCaptured notParen | 625941cc30bbd722463cbec0 |
def map(self, callback, iterable, *args, **kwargs): <NEW_LINE> <INDENT> taskName = kwargs.get("taskName", "default") <NEW_LINE> self.inputThread = threading.Thread(target=self.feedQueue, args=(callback, iterable, args, kwargs)) <NEW_LINE> self.inputThread.start() <NEW_LINE> self.start() <NEW_LINE> sleep(.1) <NEW_LINE> ... | Args:
iterable: each entry will be passed as the first argument to the function
callback: the function to thread
args: additional arguments to pass to callback function
kwargs: keyword arguments to pass to callback function
Yields:
return values from completed callback function | 625941cc56b00c62f0f14753 |
def createStrFromGif(gifFile): <NEW_LINE> <INDENT> return base64.encodestring(gifFile.read()) | Create the base64 representation of a file | 625941cc0a50d4780f666f8c |
def näytä_tiedot(self): <NEW_LINE> <INDENT> if self.__tiedot_ikkuna_avoin: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def sulje(): <NEW_LINE> <INDENT> self.__tiedot_ikkuna_avoin = False <NEW_LINE> ikkuna.destroy() <NEW_LINE> <DEDENT> ikkuna = Toplevel() <NEW_LINE> ikkuna.resizable(0, 0) <NEW_LINE> ikkuna.protocol('... | Näyttää ohjelman tiedot omassa ikkunassaan.
Metodi sallii vain yhden ikkunan olla näkyvissä
:return: | 625941cc8e05c05ec3eea46f |
def c_order(a): <NEW_LINE> <INDENT> return tuple(a.strides)==tuple(sorted(a.strides,reverse=1)) | Check whether the elements of the array are in C order. | 625941cc6aa9bd52df036e9e |
def format_course_info_for_json(course): <NEW_LINE> <INDENT> location = course.location <NEW_LINE> course_id = '.'.join([location.org, location.course, location.name]) <NEW_LINE> print("===================") <NEW_LINE> print(course.id) <NEW_LINE> print(course_id) <NEW_LINE> print("-----------------------------") <NEW_L... | format data so as to return json | 625941cce8904600ed9f2027 |
def _portfolio_data(self, nodes): <NEW_LINE> <INDENT> operating_currency = self.ledger.options["operating_currency"][0] <NEW_LINE> acct_type = ("account", str(str)) <NEW_LINE> bal_type = ("balance", str(Decimal)) <NEW_LINE> alloc_type = ("allocation", str(Decimal)) <NEW_LINE> types = [acct_type, bal_type, alloc_type] <... | Turn a portfolio of tree nodes into querytable-style data.
Args:
nodes: Account tree nodes.
Return:
types: Tuples of column names and types as strings.
rows: Dictionaries of row data by column names. | 625941ccd164cc6175782e48 |
def addTagDlg(self): <NEW_LINE> <INDENT> dlg = DialogAddEditTag('Add') <NEW_LINE> if dlg.exec_(): <NEW_LINE> <INDENT> cur = self.db_addTag(dlg.data) <NEW_LINE> if cur.rowcount > 0: <NEW_LINE> <INDENT> dlg.data[tagcol['id']] = cur.lastrowid <NEW_LINE> self.tags.appendRow(dlg.data) <NEW_LINE> self.statusBar().showMessage... | Open add tag dialog. | 625941cc5166f23b2e1a5253 |
def parse_exerciser_log(log_file): <NEW_LINE> <INDENT> if os.path.exists(log_file): <NEW_LINE> <INDENT> with open(log_file, encoding="utf8", errors='ignore') as lines: <NEW_LINE> <INDENT> for line in lines: <NEW_LINE> <INDENT> if 'pkg:' in line: <NEW_LINE> <INDENT> return line.split('pkg:')[1].replace('\n', '') | Parse UIExerciser_FlowIntent_FP_PY.log and get the pkg name.
:param log_file:
:return: | 625941ccd18da76e235325d0 |
def test_format_email_body__new(self): <NEW_LINE> <INDENT> body_html = notifier.format_email_body( False, self.feature_1, []) <NEW_LINE> self.assertIn('Blink', body_html) <NEW_LINE> self.assertIn('creator@example.com added', body_html) <NEW_LINE> self.assertIn('chromestatus.com/feature/%d' % self.feature_1.key.integer_... | We generate an email body for new features. | 625941ccaad79263cf390b3b |
def memory_usage(since=0, render=True, pid=None): <NEW_LINE> <INDENT> if pid is None: <NEW_LINE> <INDENT> pid = os.getpid() <NEW_LINE> <DEDENT> proc_status = '/proc/%d/status' % pid <NEW_LINE> try: <NEW_LINE> <INDENT> status = open(proc_status).read() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return 0 <NEW_LINE> ... | Return resident memory usage in bytes. | 625941cc8e71fb1e9831d8a3 |
def addProperty(self, prop, value): <NEW_LINE> <INDENT> editable = True <NEW_LINE> if prop == "routing": <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif prop == "target": <NEW_LINE> <INDENT> value = value.getName() <NEW_LINE> editable = False <NEW_LINE> <DEDENT> elif not self.currentItem.device_type == "Wireless_ac... | Add a property to display in the window. | 625941cc66673b3332b9218b |
def find_worker( self, worker_type: 'WorkerType', worker_key: 'Optional[WorkerKey]' = None ) -> 'Optional[CircleWorker]': <NEW_LINE> <INDENT> for worker in self.workers: <NEW_LINE> <INDENT> if worker.worker_type != worker_type: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if worker_key is not None and worker.worker... | 合致するワーカーを取得する.
Args:
worker_type: ワーカーのタイプ
worker_key: ワーカーのキー
Returns:
合致するワーカー | 625941cc50485f2cf553ce94 |
def __len__(self): <NEW_LINE> <INDENT> return len(self.graph_lists) | Return the number of graphs in the dataset. | 625941cceab8aa0e5d26dc52 |
def parse_rating(rate_str: str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return float(re.match(r"^(\d\.\d{2})\d* из 10$", rate_str).group(1)) <NEW_LINE> <DEDENT> except (AttributeError, ValueError): <NEW_LINE> <INDENT> return 0.0 | >>> parse_rating("9.439212799072266 из 10")
9.43 | 625941cc3cc13d1c6d3c7474 |
def klhessh(V,W,H): <NEW_LINE> <INDENT> K = V.shape[1] <NEW_LINE> R = W.shape[1] <NEW_LINE> data = np.zeros(K * R ** 2) <NEW_LINE> row_ind1 = np.tile(np.repeat(np.arange(R), R), K) <NEW_LINE> row_ind2 = np.repeat(np.arange(0, K * R, R), R ** 2) <NEW_LINE> row_ind = row_ind1 + row_ind2 <NEW_LINE> col_ind1 = np.tile(np.a... | Returns Hessian of KL divergence over H as a sparse CSR matrix.
Note that because H is a R*K matrix, Hessian has dimensions RK*RK with a block-diagonal structure. | 625941cc187af65679ca5219 |
def itkReconstructionByDilationImageFilterIUC3IUC3_cast(*args): <NEW_LINE> <INDENT> return _itkReconstructionByDilationImageFilterPython.itkReconstructionByDilationImageFilterIUC3IUC3_cast(*args) | itkReconstructionByDilationImageFilterIUC3IUC3_cast(itkLightObject obj) -> itkReconstructionByDilationImageFilterIUC3IUC3 | 625941ccd6c5a10208144145 |
def initials(name): <NEW_LINE> <INDENT> return ".".join([x[0].upper() for x in name.split()[:-1]] + [name.split()[-1].title()]) | Converts a name to initials form.
:param name: a string of words.
:return: the string in initials form. | 625941ccd7e4931a7ee9e018 |
def threshold_multiotsu(image=None, classes=3, nbins=256, *, hist=None): <NEW_LINE> <INDENT> if image is not None and image.ndim > 2 and image.shape[-1] in (3, 4): <NEW_LINE> <INDENT> warn(f'threshold_multiotsu is expected to work correctly only for ' f'grayscale images; image shape {image.shape} looks like ' f'that of... | Generate `classes`-1 threshold values to divide gray levels in `image`,
following Otsu's method for multiple classes.
The threshold values are chosen to maximize the total sum of pairwise
variances between the thresholded graylevel classes. See Notes and [1]_
for more details.
Either image or hist must be provided. I... | 625941cc10dbd63aa1bd2c9e |
def setup_info_msgs(supervisor): <NEW_LINE> <INDENT> supervisor.data['waiting'] = 0 <NEW_LINE> supervisor.data['skipped'] = 0 <NEW_LINE> def add_skipped(headers): <NEW_LINE> <INDENT> supervisor.data['skipped'] += 1 <NEW_LINE> <DEDENT> def report_skipped(): <NEW_LINE> <INDENT> if supervisor.data['skipped'] > 0: <NEW_LIN... | Setup text info printing for given supervisor | 625941cc7047854f462a1504 |
def _update_mean_vector(self, labelset, labels_to_vectors_dict): <NEW_LINE> <INDENT> updated_mean = 0 <NEW_LINE> for label in labelset: <NEW_LINE> <INDENT> updated_mean += labels_to_vectors_dict[label] <NEW_LINE> <DEDENT> euclidean_norm = updated_mean.dot( updated_mean.transpose()).toarray()[0][0] <NEW_LINE> euclidean_... | Computes a mean label vector from a set of labels.
:param labelset: set of labels for which a mean vector is to be obtained.
:param labels_to_vectors_dict: a dictionary containing labels (strings) as its keys and
their numerical vector representations as its values.
:returns: the mean label vector. | 625941cc32920d7e50b282ca |
def init_bandwidth_account_client(): <NEW_LINE> <INDENT> account_api = account.Client(BANDWIDTH_USER_ID, BANDWIDTH_API_TOKEN, BANDWIDTH_API_SECRET) <NEW_LINE> return account_api | Initialize a Bandwidth account client. | 625941cc3c8af77a43ae389b |
def update_ui(self, weather_forecast): <NEW_LINE> <INDENT> self._set_location(location=weather_forecast['location']) <NEW_LINE> self._set_date(date=self._get_date()) <NEW_LINE> self._set_weather_status(weather_forecast['weather_status']) <NEW_LINE> self.set_weather_image(image_path=self.cuban_weather.weather_statuses[ ... | Update all elements in the UI.
This method update all the elements in UI.
:param weather_forecast: dictionary with forecast data | 625941cc8c0ade5d55d3eab5 |
def md5(self): <NEW_LINE> <INDENT> if self.mode == FILEINMEMORY: <NEW_LINE> <INDENT> return md5(self.data()).hexdigest() <NEW_LINE> <DEDENT> elif self.mode == FILEONDISK: <NEW_LINE> <INDENT> m = md5() <NEW_LINE> fh = open(self.diskpath, 'r') <NEW_LINE> m.update(fh.read()) <NEW_LINE> fh.close() <NEW_LINE> return m.hexdi... | Returns md5 of file
Calculate based on reassembly from FILEINMEMORY
or loads from FILEONDISK | 625941cc5fdd1c0f98dc032e |
def test_binary_search(path, low, high, actual): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> path = "exercise4.py" <NEW_LINE> exercise4 = imp.load_source("exercise4", path) <NEW_LINE> BASE2 = 2 <NEW_LINE> b = None <NEW_LINE> b = exercise4.binary_search(low, high, actual) <NEW_LINE> b["WorstCaseO"] = math.log(high - lo... | Test the binary search function.
checks to see that it's searching better than O(log n) | 625941cc627d3e7fe0d68f4a |
def test_add_multiply(): <NEW_LINE> <INDENT> c1 = Circle(10) <NEW_LINE> c2 = Circle(20) <NEW_LINE> assert c1 + c2 == 30 <NEW_LINE> assert c1 + 10 == 20 <NEW_LINE> assert 10 + c1 == 20 <NEW_LINE> assert c1 * c2 == 200 <NEW_LINE> assert c1 * 10 == 100 <NEW_LINE> assert 10 * c1 == 100 | Testing variations of Circle addition and multiplication | 625941cc596a897236089bbb |
def test_sentence_input(self, sentence): <NEW_LINE> <INDENT> sentence = sentence.text <NEW_LINE> reject_pat = re.compile(r"(^')|('$)|\s'|'\s|[\"(\(\)\[\])]") <NEW_LINE> if sentence.__class__.__name__ == "str": <NEW_LINE> <INDENT> decoded = sentence <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> decoded = unidecode(sente... | A basic sentence filter. This one rejects sentences that contain
the type of punctuation that would look strange on its own
in a randomly-generated sentence. | 625941cc76d4e153a657ec2c |
def sort_tracks(trk, data, theta, grade, sort_by, n_tracks): <NEW_LINE> <INDENT> for i, jet in tqdm.tqdm(trk.iterrows()): <NEW_LINE> <INDENT> trk_selection = grade[i] != -10 <NEW_LINE> tracks = np.array( [v[trk_selection].tolist() for v in jet.get_values()], dtype='float32' )[:, (np.argsort(jet[sort_by][trk_selection])... | Definition:
Sort tracks by sort_by and put them into an ndarray called data.
Pad missing tracks with -999 --> net will have to have Masking layer
Args:
-----
trk: a dataframe or pandas serier
data: an array of shape (nb_samples, nb_tracks, nb_features)
theta: pandas series with the jet_trk_theta va... | 625941cc379a373c97cfac3f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.