code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def lowercase(text): <NEW_LINE> <INDENT> return text.lower() | casefolding menjadi huruf kecil
:return: lower case string
:rtype: string | 625941d84a966d76dd551294 |
def GetPageText(self, page): <NEW_LINE> <INDENT> return self._pages.GetPageText(page) | Returns the string for the given page.
:param `page`: an integer specifying the page index. | 625941d88e05c05ec3eea5f9 |
def call_comp(self, inputstring): <NEW_LINE> <INDENT> if ".." in inputstring: <NEW_LINE> <INDENT> self.unclean() <NEW_LINE> funclist = [] <NEW_LINE> for item in inputstring.split(".."): <NEW_LINE> <INDENT> funclist.append(self.wrap(self.eval_call(item))) <NEW_LINE> <DEDENT> return strfunc(strlist(funclist, "(")+"("*boo... | Performs Function Composition. | 625941d844b2445a33932317 |
def memory_usage_by_process(): <NEW_LINE> <INDENT> pass | https://pypi.python.org/pypi/memory_profiler
http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended
module "resource" - only for UNix | 625941d830dc7b7665901be7 |
def insert_region_info_to_hbase(self, insert_data=DataFrame): <NEW_LINE> <INDENT> join_title = ["nvl(connect_id, rowkey) as rowkey", "country", "province", "city", "phone", "code", "platform"] <NEW_LINE> tmp = self.join_id(insert_data, *join_title) <NEW_LINE> def func(x): <NEW_LINE> <INDENT> _result = {} <NEW_LINE> row... | :param insert_data: Region 表
:return: 插入状态 | 625941d87cff6e4e81117c08 |
def svg_dependencies(self): <NEW_LINE> <INDENT> svg = svgwrite.container.Group() <NEW_LINE> for t in self.tasks: <NEW_LINE> <INDENT> trepr = t.svg_dependencies() <NEW_LINE> if trepr is not None: <NEW_LINE> <INDENT> svg.add(trepr) <NEW_LINE> <DEDENT> <DEDENT> return svg | Draws svg dependencies between tasks according to coordinates cached
when drawing tasks | 625941d8283ffb24f3c55b82 |
def _is_load_subscript(index_node: astroid.Name, for_node: astroid.For) -> bool: <NEW_LINE> <INDENT> iterable = _iterable_if_range(for_node.iter) <NEW_LINE> if not (isinstance(index_node.parent, astroid.Index) and isinstance(index_node.parent.parent, astroid.Subscript) and index_node.parent.parent.value.name == iterabl... | Return whether or not <index_node> is used to subscript the iterable of <for_node>
and the subscript item is being loaded from, e.g., s += iterable[index_node]. | 625941d8167d2b6e31218e18 |
def __contains__(self,X): <NEW_LINE> <INDENT> return X.parent() == self and is_DualAbelianGroupElement(X) | Implements "in".
EXAMPLES::
sage: F = AbelianGroup(5,[2, 3, 5, 7, 8], names="abcde")
sage: a,b,c,d,e = F.gens()
sage: Fd = F.dual_group(names = "ABCDE")
sage: A,B,C,D,E = Fd.gens()
sage: A*B^2*D^7 in Fd
True | 625941d823849d37ff7b3311 |
def euler476(): <NEW_LINE> <INDENT> pass | >>> euler476()
'to-do' | 625941d84f88993c3716c2e9 |
def populate_queue(self,params): <NEW_LINE> <INDENT> return glob.glob(params['images_dir']+"/*.jpg") | Load parameters and prepare the tweet queue.
This is actually just a list of image files, indexed by
the day of the year that they should be tweeted out.
This method is only called by the public tweet() method. | 625941d80fa83653e465723d |
def destroy(self, request, pk): <NEW_LINE> <INDENT> self.check_permissions(request) <NEW_LINE> user = get_object_or_404(User, pk=pk) <NEW_LINE> self.check_object_permissions(request, user) <NEW_LINE> user.delete() <NEW_LINE> return Response(status=status.HTTP_204_NO_CONTENT) | API de borrado de usuarios
:param request: Petición
:param pk: identificador del usuario a borrar
:return: | 625941d8b5575c28eb68e285 |
def get_embed(self) -> discord.Embed: <NEW_LINE> <INDENT> return discord.Embed( title="Tic Tac Toe", description="\n".join( ( "".join(self.emojis[state] for state in column) for column in self.status ) ), color=discord.Color.blurple(), ) | Generate the board embed. | 625941d850485f2cf553d01e |
def trigger_shutdown(): <NEW_LINE> <INDENT> global port <NEW_LINE> global kill_code <NEW_LINE> post("http://localhost:" + str(port) + "/" + kill_code) | Sends a GET with the generated kill_code to trigger a shutdown of Flask. | 625941d8f548e778e58cd802 |
def parse(self, exclusive = False): <NEW_LINE> <INDENT> meta = self.meta <NEW_LINE> ext = '.parsed' <NEW_LINE> history = os.path.join('net', 'yolo', 'parse-history.txt'); <NEW_LINE> if not os.path.isfile(history): <NEW_LINE> <INDENT> file = open(history, 'w') <NEW_LINE> file.close() <NEW_LINE> <DEDENT> with open(histor... | Decide whether to parse the annotation or not,
If the parsed file is not already there, parse. | 625941d856b00c62f0f148de |
def render_to_string(self, template_name, vars = None): <NEW_LINE> <INDENT> if isinstance(template_name, (list, tuple)): <NEW_LINE> <INDENT> t = self.select_template(template_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t = self.get_template(template_name) <NEW_LINE> <DEDENT> return t.render(vars) | Loads the given template_name and renders it with the given dictionary as
context. The template_name may be a string to load a single template using
get_template, or it may be a tuple to use select_template to find one of
the templates in the list. Returns a string. | 625941d832920d7e50b28455 |
def random_string(charset, min_length, max_length): <NEW_LINE> <INDENT> length = random.randint(min_length, max_length) <NEW_LINE> return ''.join([random.choice(charset) for i in range(length)]) | Generate a string from the given character set (charset), between min_length
and max_length, inclusive. | 625941d8460517430c394403 |
def composeHeader(translations, *args): <NEW_LINE> <INDENT> num = len(args) <NEW_LINE> lastColumns = string.split(args[-1], ' ') <NEW_LINE> startcut = 0 <NEW_LINE> new = [] <NEW_LINE> for segment in lastColumns: <NEW_LINE> <INDENT> endcut = startcut + len(segment) <NEW_LINE> new.append(string.lstrip(string.join( map(st... | Convert a series of string headers into a list of named qualifiers. | 625941d8fbf16365ca6f644a |
def array_to_hexstr(self, a): <NEW_LINE> <INDENT> s = '' <NEW_LINE> for b in a: <NEW_LINE> <INDENT> s += self.int_to_hex(b) <NEW_LINE> <DEDENT> return s | Args:
a <ctypes.Array> [(ctypes.c_uint8 * N)()]
Returns:
<str> : A hex-string representing the bytes in the array ('AAB203F1....', for example) | 625941d896565a6dacc8f94e |
def decode(self, input, mask=None, leading_symbolic=0): <NEW_LINE> <INDENT> energy = self(input, mask=mask) <NEW_LINE> energy_transpose = energy.transpose(0, 1) <NEW_LINE> energy_transpose = energy_transpose[:, :, leading_symbolic:-1, leading_symbolic:-1] <NEW_LINE> length, batch_size, num_label, _ = energy_transpose.s... | Args:
input: Tensor
the input tensor with shape = [batch, length, model_dim]
mask: Tensor or None
the mask tensor with shape = [batch, length]
leading_symbolic: nt
number of symbolic labels leading in type alphabets (set it to 0 if you are not sure)
Returns: Tensor
decoding resu... | 625941d860cbc95b062c67c7 |
def output_has(self, lines, output_file="output/winlogbeat"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(os.path.join(self.working_dir, output_file), "r") as f: <NEW_LINE> <INDENT> return len([1 for line in f]) >= lines <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> return False | Returns true if the output has a given number of lines. | 625941d8ad47b63b2c50a201 |
def enable_compression(self, lun): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> lun.enable_compression(ignore_thresholds=True) <NEW_LINE> <DEDENT> except storops_ex.VNXCompressionAlreadyEnabledError: <NEW_LINE> <INDENT> LOG.warning(_LW("Compression has already been enabled on %s."), lun.name) | Enables compression on lun.
:param lun: instance of VNXLun | 625941d86e29344779a62894 |
def updateBeat(self): <NEW_LINE> <INDENT> if self.beat != self.beatsPerBar - 1: <NEW_LINE> <INDENT> self.beat += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.beat = 0 <NEW_LINE> self.bar += 1 <NEW_LINE> if self.loopBar != self.loopBars - 1: <NEW_LINE> <INDENT> self.loopBar += 1 <NEW_LINE> <DEDENT> else: <NEW_LI... | Progress the timing by one beat, and update the number of bars, and
the bar position within the loop | 625941d8e8904600ed9f21b3 |
def revoke_task(task_id: str) -> tuple: <NEW_LINE> <INDENT> response = requests.delete(url=f'{config.RDF_VALIDATOR_API_SERVICE}/tasks/{task_id}') <NEW_LINE> return response.json(), response.status_code | Method to kill celery tasks from api
:param task_id: celery task to kill
:return: api response
:rtype: dict, int | 625941d8d486a94d0b98e3ca |
def parameter_uids_are_related(self, uid1, uid2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _, related_uid1 = get_related_parameter_uid(uid1, self.elem_cmdows) <NEW_LINE> <DEDENT> except AssertionError: <NEW_LINE> <INDENT> related_uid1 = None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> _, related_uid2 = get_related... | Check if two UIDs are related with the same basic schema node.
Parameters
----------
uid1 : str
First UID
uid2 : str
Second UID
Returns
-------
Boolean on whether they are related. | 625941d866656f66f7cbc430 |
def OnSize(self, dummyEvent): <NEW_LINE> <INDENT> if self.GetAutoLayout(): <NEW_LINE> <INDENT> self.Layout() <NEW_LINE> self.dragBoxImage.SetBitmap(self.dragBoxBitmap) | Handles the wx.EVT_SIZE events. | 625941d8a934411ee3751917 |
def route(self, path, limit=False, time=None, key=lambda data: data.get("key"), reset=100000): <NEW_LINE> <INDENT> _a = (key, limit, time, reset) <NEW_LINE> def decorator(handler): <NEW_LINE> <INDENT> def ratelimited(handler): <NEW_LINE> <INDENT> @self.thread(START) <NEW_LINE> def connect(): <NEW_LINE> <INDENT> g.rate ... | The @app.route(path) decorator defines the handler function for the given path.
The function can take arguments (path) and keyword arguments (query data), e.g.,
if no handler exists for URL "/api/1/en", but a handler exists for URL "/api/1",
this handler will be called with 1 argument: "en".
It returns a string, a gene... | 625941d8a8370b7717052b22 |
def compute_nl_loss(y, tx, w): <NEW_LINE> <INDENT> epsilon = 1e-15 <NEW_LINE> pred = sigmoid(tx.dot(w)) <NEW_LINE> pred = np.clip(pred, epsilon, 1-epsilon) <NEW_LINE> y, pred = _check_dimension(y, pred) <NEW_LINE> loss = y.T.dot(np.log(pred)) + (1 - y).T.dot(np.log(1 - pred)) <NEW_LINE> return np.squeeze(- loss).item() | Compute the loss by negative log likelihood. | 625941d8566aa707497f47e9 |
def precision(tp, fp): <NEW_LINE> <INDENT> return tp / float(tp + fp) | the percentage of true-positive to false-positives i.e. the number
we got right to the number we got wrong | 625941d826238365f5f0f0f5 |
def put_cash(self, amount): <NEW_LINE> <INDENT> print('put cash %s' % amount) <NEW_LINE> try: <NEW_LINE> <INDENT> if amount < 0: <NEW_LINE> <INDENT> raise ValueError(ErrorCode.AMOUNT_MUST_BE_POSITIVE) <NEW_LINE> <DEDENT> self.shared_context.update_transaction_command.execute( self.shared_context.bank_system, self.share... | Put amount into selected account in `AtmProcessingDeposit`
Args:
amount: Amount the customer wants to deposit | 625941d8097d151d1a2230db |
def count_records(scores): <NEW_LINE> <INDENT> low_count, high_count = 0, 0 <NEW_LINE> low_score = high_score = scores.pop(0) <NEW_LINE> for score in scores: <NEW_LINE> <INDENT> if score < low_score: <NEW_LINE> <INDENT> low_count += 1 <NEW_LINE> low_score = score <NEW_LINE> <DEDENT> elif score > high_score: <NEW_LINE> ... | Tracks each score in array.
Returns number of times record for most and least points scored was
broken.
>>> print(count_records([10, 5, 20, 20, 4, 5, 2, 25, 1]))
2 4
>>> print(count_records([3, 4, 21, 36, 10, 28, 35, 5, 24, 42]))
4 0 | 625941d80a366e3fb873ea9f |
def predict_final(each_weight = 24, each_width = 24, weight_step = 12, width_step = 12, gpu_index = "1", model_path = MODEL_PATH, threshold = 0.5): <NEW_LINE> <INDENT> num = 0 <NEW_LINE> os.environ["CUDA_VISIBLE_DEVICES"] = gpu_index <NEW_LINE> im_2015 = tiff.imread(FILE_2015).transpose([1, 2, 0]) <NEW_LINE> im_2017 = ... | 该函数是预测2015和2017图像拼接在一起的24*24的图像的结果,
然后将结果拼接成一个矩阵,存储为tif格式
Parameters
----------
each_weight: 每个预测图像的高度
each_width: 每个预测图像的宽度
weight_step: 沿高度方向滑动步长
width_step: 沿宽度方向滑动步长
gpu_index: 使用gpu的编号 | 625941d88a43f66fc4b542e6 |
def set_keys(self, params): <NEW_LINE> <INDENT> prev_enable_templating = self.enable_templating <NEW_LINE> self.enable_templating = False <NEW_LINE> for key in sorted(params.keys()): <NEW_LINE> <INDENT> if key in self._config.keys(): <NEW_LINE> <INDENT> self[key] = params[key] <NEW_LINE> self.log.info("setting easyconf... | Set keys in this EasyConfig instance based on supplied easyconfig parameter values.
If any unknown easyconfig parameters are encountered here, an error is raised.
:param params: a dict value with names/values of easyconfig parameters to set | 625941d85510c4643540f663 |
def vgg11(pretrained=False, progress=True, model_path=None, **kwargs): <NEW_LINE> <INDENT> return _vgg('vgg11', 'A', False, pretrained, progress, model_path, **kwargs) | VGG 11-layer model (configuration "A") from
`"Very Deep Convolutional Networks For Large-Scale Image Recognition" <https://arxiv.org/pdf/1409.1556.pdf>`_
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
progress (bool): If True, displays a progress bar of the download to stderr | 625941d816aa5153ce3626fb |
@tier2 <NEW_LINE> def test_positive_search_by_parameter_with_different_values(session, module_org, module_loc): <NEW_LINE> <INDENT> param_name = gen_string('alpha') <NEW_LINE> param_values = [gen_string('alpha'), gen_string('alphanumeric')] <NEW_LINE> hosts = [ entities.Host( organization=module_org, location=module_lo... | Search for the host by global parameter assigned to it by its value
:id: c3a4551e-d759-4a9d-ba90-8db4cab3db2c
:expectedresults: Only one specific host is returned by search
:CaseLevel: Integration | 625941d8a79ad161976cc3c9 |
def translate(T, embedding, origin=(0,0)): <NEW_LINE> <INDENT> tiling = DWaveNetworkXTiling(T) <NEW_LINE> shape = tiling.shape <NEW_LINE> offset = shape <NEW_LINE> for v,chain in embedding.items(): <NEW_LINE> <INDENT> for q in chain: <NEW_LINE> <INDENT> tile = np.array(tiling.get_tile(q)) <NEW_LINE> offset = [min(t,o) ... | Transport the embedding on the same graph to re-distribute qubit
assignments.
Optional arguments:
origin: (tuple)
A tuple of tile coordinates pointing to where the left-uppermost
occupied tile in the embedding should move to. All other tiles
are moved relative to the origin.
Example:
>... | 625941d8d6c5a102081442d0 |
def p_dots(p): <NEW_LINE> <INDENT> p[0] = MathObject(content = p[1], kind = 'Dots') | symbol : DOTS | 625941d87b25080760e396dc |
def __createWXGLParent(self): <NEW_LINE> <INDENT> import wx <NEW_LINE> class DummyFrame(wx.Frame): <NEW_LINE> <INDENT> def ShouldPreventAppExit(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> log.debug('Creating dummy wx.Frame for GL context creation') <NEW_LINE> self.__parent = DummyFrame(None, st... | Create a dummy ``wx.Frame`` to be used as the parent for the
dummy ``wx.glcanvas.GLCanvas``. | 625941d8d268445f265b50f2 |
def send_cli(self, command=None, *args, **kwargs): <NEW_LINE> <INDENT> pos_args = [arg_to_cli(arg) for arg in args] <NEW_LINE> named_args = [str(key) + "=" + arg_to_cli(value) for (key, value) in kwargs.items()] <NEW_LINE> assert not (pos_args and named_args), "Cannot use positional arguments and named arguments in the... | Run bitcoin-cli command. Deserializes returned string as python object. | 625941d84527f215b584c6d8 |
def scale(self, r): <NEW_LINE> <INDENT> return r * (self.max - self.min) + self.min | give [0,1] value and returns the scaled value | 625941d83617ad0b5ed6817a |
def experiment(type, n, t): <NEW_LINE> <INDENT> cases = [] <NEW_LINE> for _ in range(t): <NEW_LINE> <INDENT> case = [] <NEW_LINE> for _ in range(n): <NEW_LINE> <INDENT> rand = random.choice(type) <NEW_LINE> case.append(rand) <NEW_LINE> <DEDENT> cases.append(tuple(case)) <NEW_LINE> <DEDENT> return cases | :param type: 실험 타입(동전 던지기 or 주사위 던지기, ...)
:param n: 동전의 개수
:param t: 실험 회수
:return: 리스트 | 625941d866673b3332b92315 |
def orbit_derivs(t, x, Pot): <NEW_LINE> <INDENT> X=x[0] <NEW_LINE> Y=x[1] <NEW_LINE> Z=x[2] <NEW_LINE> return np.concatenate((x[3:],Pot.tot_force(X, Y, Z))) | Simple interface for derivatives for orbit integration
t = time
x = Cartesian coordinates
Pot is an object which has a function tot_force(x, y, z) which
calculates the total force at Cartesian x, y, z | 625941d8236d856c2ad44a60 |
def anyDataToStr(usrData, sigDig=None, seqBrace='tuple'): <NEW_LINE> <INDENT> if drawer.isStr(usrData): <NEW_LINE> <INDENT> return usrData <NEW_LINE> <DEDENT> elif drawer.isInt(usrData): <NEW_LINE> <INDENT> return '%i' % usrData <NEW_LINE> <DEDENT> elif drawer.isFloat(usrData): <NEW_LINE> <INDENT> if sigDig != None: <N... | convert any data to a proper string, taking type into account
lists are recursive examined with the same function
note: this will convert a list [] into a tuple representation
depending on optional arg
will automatically remove space between comma-separated lists
>>> anyDataToStr('test')
'test'
>>> anyDataToStr([3, 'm... | 625941d8dd821e528d63b42c |
def _reorder_keys(self, dic, msg_base = ''): <NEW_LINE> <INDENT> di = {} <NEW_LINE> for key, value in dic.iteritems(): <NEW_LINE> <INDENT> new_key = (min(key[0], key[1]), max(key[0], key[1])) <NEW_LINE> if not new_key == key: <NEW_LINE> <INDENT> self.assertTrue(not new_key in dic, '{}: Found edges {} and reversed edge ... | Reorders the keys of the result dictionary to be inside itslef ordered. | 625941d855399d3f05588939 |
def __init__(self): <NEW_LINE> <INDENT> wx.Frame.__init__(self, parent=None, title="ColorWrite") <NEW_LINE> menubar = wx.MenuBar() <NEW_LINE> fileMenu = wx.Menu() <NEW_LINE> menubar.Append(fileMenu, '&File') <NEW_LINE> self.SetMenuBar(menubar) <NEW_LINE> self.fSizer = wx.BoxSizer(wx.VERTICAL) <NEW_LINE> panel = ColorWr... | Constructor | 625941d899cbb53fe6792e6a |
def create_features(datestrs): <NEW_LINE> <INDENT> feature_data = [] <NEW_LINE> for datestr in datestrs: <NEW_LINE> <INDENT> current_date = datetime.datetime.strptime(datestr, '%Y-%m-%d').date() <NEW_LINE> current_weekday = current_date.weekday() <NEW_LINE> day_of_week = np.zeros(7) <NEW_LINE> day_of_week[current_weekd... | Find the features associated with a set of dates.
These will include:
weekday / weekend
day of week
season
month of year
Parameters
----------
datestrs: list of strings
Date strings of the format YYYY-MM-DD.
Returns
-------
features: DataFrame
Each row corrsponds to one date. The datestring is... | 625941d801c39578d7e750bf |
def filter_synapses(self, gid, syn_sections=None, syn_indexes=None, syn_types=None, layers=None, sources=None, swc_types=None, cache=False): <NEW_LINE> <INDENT> matches = lambda items: all( map(lambda query_item: (query_item[0] is None) or (query_item[1] in query_item[0]), items)) <NEW_LINE> if cache: <NEW_LINE> <INDEN... | Returns a subset of the synapses of the given cell according to the given criteria.
:param gid: int
:param syn_sections: array of int
:param syn_indexes: array of int: syn_ids
:param syn_types: list of enumerated type: synapse category
:param layers: list of enumerated type: layer
:param sources: list of enumerated ty... | 625941d801c39578d7e750c0 |
def hyperEccentricity(peri, r, v, M): <NEW_LINE> <INDENT> h = peri + r <NEW_LINE> sma = h * G * M / (2 * G * M - h * v ** 2) <NEW_LINE> e = (sma - h) / sma <NEW_LINE> return e | Return the eccentricity of a hyperbolic orbit.
The eccentricity() function can't be used for hyperbolic orbits because
hyperbolic orbits lack an apoapsis. This function uses other orbital
parameters instead, removing the need for an apoapsis. This can also be
used for parabolic orbits, but I don't know why you would e... | 625941d863d6d428bbe44774 |
def TimeSinceLastLogEntry(self, log_type="ALL"): <NEW_LINE> <INDENT> if log_type == "ALL": <NEW_LINE> <INDENT> log_return = self.GetLastLogTimestamp() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> log_return = self.GetLastLogTimestamp(log_type) <NEW_LINE> <DEDENT> dict = {} <NEW_LINE> if log_return["status"] == 200: <N... | Denne funktion returnerer antal sekunder fra sidste log record i databasen, til
nuværende klokkelset. Hvis antal sekunder siden sidste loghendelse af en bestemt
type ønskes, kan der tilføjes "INFO", "WARN" eller "ERROR" til funktionskaldet. | 625941d8293b9510aa2c3518 |
def populate_db(session, num_participants=100, num_tips=50, num_teams=5): <NEW_LINE> <INDENT> participants = [] <NEW_LINE> for i in xrange(num_participants): <NEW_LINE> <INDENT> p = fake_participant() <NEW_LINE> session.add(p) <NEW_LINE> participants.append(p) <NEW_LINE> <DEDENT> for p in participants: <NEW_LINE> <INDE... | Populate DB with fake data | 625941d87d847024c06be542 |
def new_doc(self): <NEW_LINE> <INDENT> self.doc = xml.dom.minidom.Document() <NEW_LINE> self.urlset = self.doc.createElement('urlset') <NEW_LINE> self.urlset.setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9') <NEW_LINE> self.doc.appendChild(self.urlset) <NEW_LINE> self.url_count = 0 | Creates new sitemap document and resets the url_count. | 625941d8ab23a570cc250408 |
def post(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> StatsClientSingleton().incr('input.mobile', count=1) <NEW_LINE> StatsClientSingleton().incr('amqp.output', count=1) <NEW_LINE> routing_key = self.request.uri.replace('/', '.')[1:] <NEW_LINE> payload = self.request.body <NEW_LINE> content_encoding = self.reque... | HTTP Post handler
* Forward request: publish to AMQP
:return: HTTPStatus 200 | 625941d891f36d47f21ac778 |
def set_outputcollector(self, collector): <NEW_LINE> <INDENT> self.outputcollector = collector | set the output collector for reduce task
@param collector: the ouput collector to collect output | 625941d8cb5e8a47e48b7d2b |
def __init__(self, Filter): <NEW_LINE> <INDENT> self.FF = Filter | Constructor inisiates filter. | 625941d84428ac0f6e5baa77 |
def staging(): <NEW_LINE> <INDENT> env.alias = "staging" <NEW_LINE> env.hosts = [PRODUCTION] <NEW_LINE> env.path = '/var/www/stage.hawksworx.com' <NEW_LINE> env.user = 'ubuntu' <NEW_LINE> env.key_filename = '/Users/philha/.ssh/philhawksworth-aws.pem' <NEW_LINE> env.apache = ['stage.hawksworx.com', ] <NEW_LINE> env.rele... | Staging site | 625941d8adb09d7d5db6ca12 |
def __init__(self, **kwds): <NEW_LINE> <INDENT> if not kwds.has_key("tablename"): <NEW_LINE> <INDENT> kwds["tablename"]="dsl" <NEW_LINE> <DEDENT> super(DSL, self).__init__(**kwds) | Creates a connection to the database
__init__(hostname=.., user=.., password=.., database=.., tablename=..)
__init__(dbhandle=.., tablename=..) | 625941d8dc8b845886cb57ba |
def render_product(children): <NEW_LINE> <INDENT> if len(children) == 1: <NEW_LINE> <INDENT> return children[0] <NEW_LINE> <DEDENT> position = "numerator" <NEW_LINE> fraction_mode_ever = False <NEW_LINE> numerator = [] <NEW_LINE> denominator = [] <NEW_LINE> latex = "" <NEW_LINE> for kid in children: <NEW_LINE> <INDENT>... | Format products and division nicely.
Group bunches of adjacent, equal operators. Every time it switches from
denominator to the next numerator, call `render_frac`. Join these groupings
together with '\cdot's, ending on a numerator if needed.
Examples: (`children` is formed indirectly by the string on the left)
'a*b... | 625941d86fece00bbac2d9c5 |
def testConnectionSQL(address,port,database,login,password): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conn = psycopg2.connect(host=address,port=int(port),database='postgres',user=str(login),password=str(password)) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> erreur=str(e) <NEW_LINE> if re.search('... | Cette fonction permet de verifier que l'utilisateur puisse:
- se connecter a la base
- que l'utilisateur ait le droit de créer une base | 625941d876d4e153a657edb6 |
def normalize_zeitzone(s): <NEW_LINE> <INDENT> if s == unknown: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> s = rem_brackets(s) <NEW_LINE> trenner = [ "/", "und", "<br>", ] <NEW_LINE> for el in trenner: <NEW_LINE> <INDENT> s = s.replace(el, ",") <NEW_LINE> <DEDENT> s = s.replace("GMT", "UTC") <NEW_LINE> s = re.sub... | Normalisiert Zeitzonenangaben | 625941d82c8b7c6e89b35a44 |
def __subsets(self, input_sets): <NEW_LINE> <INDENT> if not (isinstance(input_sets, dict) or isinstance(input_sets, list)): <NEW_LINE> <INDENT> input_type = type(input_sets) <NEW_LINE> raise ValueError( f'subsets expected a list or dict as input, but got "{input_type}"' ) <NEW_LINE> <DEDENT> if len(input_sets) == 1: <N... | Generate all possible combinations of the input set as subsets
Arguments:
input_sets {dict or list} -- [A dict or list containing all input sets]
Raises:
ValueError -- [Unexcpeted input format]
Returns:
[dict or list] -- [A dict or list containing all possible __subsets] | 625941d8ac7a0e7691ed434c |
def reorderList(head): <NEW_LINE> <INDENT> if not head: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> slow = head <NEW_LINE> fast = head <NEW_LINE> while fast != None and fast.next != None: <NEW_LINE> <INDENT> slow = slow.next <NEW_LINE> fast = fast.next.next <NEW_LINE> <DEDENT> mid = slow <NEW_LINE> prev = None ... | Do not return anything, modify head in-place instead. | 625941d84428ac0f6e5baa78 |
def import_data(self): <NEW_LINE> <INDENT> client = MongoClient('mongodb://localhost:27017/') <NEW_LINE> db = client.TuyenSinhDB <NEW_LINE> collection = db.WordSegmentation <NEW_LINE> print('bat dau luu du lieu vao database') <NEW_LINE> for question, answer, date in zip(self.question, self.answer, self.date): <NEW_LINE... | lưu dữ liệu tách từ vào một csdl mới
:return: | 625941d8004d5f362079a5b6 |
def saveOtpBlob(self, did, data, sigs): <NEW_LINE> <INDENT> did = Did(did).did <NEW_LINE> certifiable_data = { "otp_data": data, "signatures": sigs } <NEW_LINE> self.db.save(did, certifiable_data) <NEW_LINE> return certifiable_data | Store a otp encrypted key and signatures
:param did: string
W3C did string
:param data: dict
A dict containing the otp encrypted keys and signatures
:param sigs: dict
A dict containing the otp encrypted keys signatures | 625941d88e71fb1e9831da2d |
@keras_export('keras.backend.conv1d') <NEW_LINE> def conv1d(x, kernel, strides=1, padding='valid', data_format=None, dilation_rate=1): <NEW_LINE> <INDENT> if data_format is None: <NEW_LINE> <INDENT> data_format = image_data_format() <NEW_LINE> <DEDENT> if data_format not in {'channels_first', 'channels_last'}: <NEW_LIN... | 1D convolution.
Arguments:
x: Tensor or variable.
kernel: kernel tensor.
strides: stride integer.
padding: string, `"same"`, `"causal"` or `"valid"`.
data_format: string, one of "channels_last", "channels_first".
dilation_rate: integer dilate rate.
Returns:
A tensor, result of 1D convoluti... | 625941d8009cb60464c63634 |
def __init__(self,xInterpolators,y_values,z_values): <NEW_LINE> <INDENT> self.xInterpolators = xInterpolators <NEW_LINE> self.y_list = y_values <NEW_LINE> self.y_n = y_values.size <NEW_LINE> self.z_list = z_values <NEW_LINE> self.z_n = z_values.size <NEW_LINE> self.distance_criteria = ['xInterpolators','y_list','z_list... | Constructor for the class, generating an approximation to a function of
the form f(x,y,z) using interpolations over f(x,y_0,z_0) for a fixed grid
of y_0 and z_0 values.
Parameters
----------
xInterpolators : [[HARKinterpolator1D]]
A list of lists of 1D interpolations over the x variable. The i,j-th
element of... | 625941d8e5267d203edcdf1e |
def get_hint_pool_idxs(self, normalized_query): <NEW_LINE> <INDENT> with tf.device(self.nn_device): <NEW_LINE> <INDENT> similarities = tf.matmul( tf.stop_gradient(normalized_query), self.mem_keys, transpose_b=True, name='nn_mmul') <NEW_LINE> <DEDENT> _, hint_pool_idxs = tf.nn.top_k(tf.stop_gradient(similarities), k=sel... | Get small set of idxs to compute nearest neighbor queries on.
This is an expensive look-up on the whole memory that is used to
avoid more expensive operations later on.
Args:
normalized_query: A Tensor of shape [None, key_dim].
Returns:
A Tensor of shape [None, choose_k] of indices in memory
that are closest t... | 625941d84a966d76dd551295 |
def send_sms(self, message, phone, sender_id=None): <NEW_LINE> <INDENT> response = requests.post( url=self.service_url, headers={ 'Content-Type': 'application/json', 'x-api-key': self.api_token, }, json={ 'phone': phone, 'country_code': self.country_code, 'sender_id': sender_id, 'message': message, } ).json() <NEW_LINE... | Send SMS | 625941d85fc7496912cc3c02 |
def add_saltnpeppar_noise(im, prop): <NEW_LINE> <INDENT> N = int(np.round(np.prod(im.shape) * prop)) <NEW_LINE> index = np.unravel_index(np.random.permutation(np.prod(im.shape))[1:N], im.shape) <NEW_LINE> im2 = np.copy(im) <NEW_LINE> im2[index] = 1 - im2[index] <NEW_LINE> return im2 | Adds salt and pepper noise (flipped pixels) to an image
:param im: input image
:param prop: proportion of pixels to have noise added
:return: im2: original image with added salt and pepper noise | 625941d89c8ee82313fbb9fa |
def toDict(self): <NEW_LINE> <INDENT> dictVer = self.version + '-' + self.build <NEW_LINE> dictRepr = { "Download_Size": "", "Version_Number": dictVer, "Link_Path": "", "Display_Name": "", "File_Name": self.filename, "Link_Text": "", "Type": self.package, "Edge_Cast_Path": "", "OS": "Ubuntu", "MD5": "" } <NEW_LINE> ret... | Return of a dictionary that is used to build json. | 625941d8f8510a7c17cf9981 |
def pop_short(self): <NEW_LINE> <INDENT> self.offset += 2 <NEW_LINE> return struct.unpack_from('H', self.data, self.offset - 2)[0] | Pops a short from the data and returns it
:return: The short at the current message offset | 625941d8e76e3b2f99f3aa8c |
def test_disconnectedReason(self): <NEW_LINE> <INDENT> sm = self.streamManager <NEW_LINE> handler = FailureReasonXMPPHandler() <NEW_LINE> handler.setHandlerParent(sm) <NEW_LINE> xs = xmlstream.XmlStream(xmlstream.Authenticator()) <NEW_LINE> sm._disconnected(failure.Failure(Exception("no reason"))) <NEW_LINE> self.asser... | A L{STREAM_END_EVENT} results in L{StreamManager} firing the handlers
L{connectionLost} methods, passing a L{failure.Failure} reason. | 625941d8be8e80087fb20ec4 |
def scrape_books(url): <NEW_LINE> <INDENT> res = requests.get(url) <NEW_LINE> soup = BeautifulSoup(res.text, 'html.parser') <NEW_LINE> books = soup.find_all(class_ = 'product_pod') <NEW_LINE> all_books = [] <NEW_LINE> for book in books: <NEW_LINE> <INDENT> book_data = get_title(book), get_price(book), get_rating(book) ... | Function To Scrape Books Details and Insert into DB | 625941d8b830903b967e9b8d |
def get_simple_string(self) -> List[str]: <NEW_LINE> <INDENT> return [self.column_type] | Return a list of simple string representations of the column types | 625941d89f2886367277ab10 |
def cycle(): <NEW_LINE> <INDENT> return VarItem.cycle | Solely for printing.
| 625941d8f8510a7c17cf9982 |
def is_diquark(pdgid: PDGID_TYPE) -> bool: <NEW_LINE> <INDENT> if _extra_bits(pdgid) > 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if abspid(pdgid) <= 100: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if 0 < int(_fundamental_id(pdgid)) <= 100: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> ret... | Does this PDG ID correspond to a diquark? | 625941d8e5267d203edcdf1f |
def isValid(self, s): <NEW_LINE> <INDENT> stack = [] <NEW_LINE> d = {'[':']','(':')','{':'}'} <NEW_LINE> for e in s: <NEW_LINE> <INDENT> if e in d: <NEW_LINE> <INDENT> stack.append(d[e]) <NEW_LINE> <DEDENT> elif e in d.values(): <NEW_LINE> <INDENT> if len(stack) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT... | :type s: str
:rtype: bool | 625941d8be383301e01b5707 |
def search(self, nums, target): <NEW_LINE> <INDENT> low, high = 0, len(nums) - 1 <NEW_LINE> while low <= high: <NEW_LINE> <INDENT> mid = (low + high) // 2 <NEW_LINE> if nums[mid] == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if nums[mid] < nums[high]: <NEW_LINE> <INDENT> if nums[mid] < target <= nums[... | :type nums: List[int]
:type target: int
:rtype: bool | 625941d826068e7796caef66 |
def test_password_reset_confirm_invalid_uid(self): <NEW_LINE> <INDENT> response = self.client.post( reverse("password_reset_api"), data={"email": "john@example.com"} ) <NEW_LINE> response = self.client.post( reverse("password_reset_confirm_api"), data={ "uid": "uid", "token": "token", "new_password1": "newpass", "new_p... | A ``POST`` with an invalid uid should raise ``ValidationError``.
| 625941d8b57a9660fec33b0c |
def add_incoming_flow(node_id, from_node_id, bpmn_diagram): <NEW_LINE> <INDENT> if bpmn_diagram.diagram_graph.node[node_id].get(consts.Consts.incoming_flow) is None: <NEW_LINE> <INDENT> bpmn_diagram.diagram_graph.node[node_id][consts.Consts.incoming_flow] = [] <NEW_LINE> <DEDENT> bpmn_diagram.diagram_graph.node[node_id... | :param node_id:
:param from_node_id:
:param bpmn_diagram: | 625941d86fb2d068a760f325 |
def _get_file_path(self) -> str: <NEW_LINE> <INDENT> pass | Gets the default file path for saving to | 625941d89b70327d1c4e105a |
def __init__(self, slots, initial_slot=0): <NEW_LINE> <INDENT> self.slots = [{} for _ in xrange(slots)] <NEW_LINE> self.position = initial_slot % slots | :type slots: int
:param slots: how many slots the wheel will have. Keep in mind that the
furthest slot you can add to is less by one.
:type initial_slot: int
:param initial_slot: the index of a starting slot. Notice that it will
be fitted into the size of the wheel by ignoring
... | 625941d8ac7a0e7691ed434d |
def _login(self, username=None, password=None, store_password=False, reenter_password=False): <NEW_LINE> <INDENT> if username is None: <NEW_LINE> <INDENT> if self.USERNAME == "": <NEW_LINE> <INDENT> raise LoginError("If you do not pass a username to login(), " "you should configure a default one!") <NEW_LINE> <DEDENT> ... | Login to the CosmoSim database.
Parameters
----------
username : str, optional
Username to the CosmoSim database. If not given, it should be
specified in the config file.
store_password : bool, optional
Stores the password securely in your keyring. Default is False.
reenter_password : bool, optional
As... | 625941d88e7ae83300e4b251 |
def lpt_system_tracks_output_ascii(fn, TIMECLUSTERS): <NEW_LINE> <INDENT> print('Writing LPT system track ASCII output to: ' + fn) <NEW_LINE> fmt=' %4d%02d%02d%02d %8d %10.2f %10.2f %2d\n' <NEW_LINE> os.makedirs(os.path.dirname(fn), exist_ok=True) <NEW_LINE> file = open(fn, 'w') <NEW_LINE> file.write("LPT nnnnn.... | This function outputs the "bulk" LPT system properties (centroid, date, area)
to an ascii file. Does NOT give LPO list. | 625941d830bbd722463cc04c |
def test_deploy_crowdsale(project, chain, accounts, example_yaml_filename): <NEW_LINE> <INDENT> chain_data = load_crowdsale_definitions(example_yaml_filename, "unit_test") <NEW_LINE> chain_data["unlock_deploy_address"] = False <NEW_LINE> chain_data['pending_block_timestamp'] = chain.web3.eth.getBlock('latest').timestam... | Deploy multiple contracts from a crowdsale definition file. | 625941d8d58c6744b4257ee3 |
def test_admin_import_subscribers_duplicates(self): <NEW_LINE> <INDENT> with patch_logger('newsletter.addressimport.parsers', 'warning') as messages: <NEW_LINE> <INDENT> response = self.admin_import_subscribers( 'addresses_duplicates.csv', ignore_errors='true' ) <NEW_LINE> <DEDENT> self.assertContains( response, "2 sub... | Test importing a file with duplicate addresses. | 625941d8d7e4931a7ee9e1a2 |
def __ior__(self, other: Thread): <NEW_LINE> <INDENT> if not isinstance(other, Thread): <NEW_LINE> <INDENT> message = "unsupported operand type(s) for |=: 'thread' and '{}'". format(type(other)) <NEW_LINE> raise TypeError(message) <NEW_LINE> <DEDENT> if self.name != other.name: <NEW_LINE> <INDENT> raise ... | Execute the in-place union operation of this thread with other
:param other: the other thread | 625941d82ae34c7f2600d3b5 |
def test_get_whitelist(self): <NEW_LINE> <INDENT> pass | Test case for get_whitelist
Get whitelisted vdids of a device type. | 625941d807d97122c4178b14 |
def testORCA_ORCA4_1_single_atom_freq_out(logfile): <NEW_LINE> <INDENT> assert len(logfile.data.vibdisps) == 0 <NEW_LINE> assert len(logfile.data.vibfreqs) == 0 <NEW_LINE> assert len(logfile.data.vibirs) == 0 <NEW_LINE> numpy.testing.assert_almost_equal(logfile.data.enthalpy, -460.14376, 5) <NEW_LINE> numpy.testing.ass... | ORCA frequency with single atom. | 625941d83d592f4c4ed1d2ed |
def horiz_center(self): <NEW_LINE> <INDENT> return self._horiz_center | Get the averaged horizontal center of cluster | 625941d885dfad0860c3b0e0 |
def setUpZope(self, app, configurationContext): <NEW_LINE> <INDENT> import abita.development <NEW_LINE> self.loadZCML(package=abita.development) <NEW_LINE> z2.installProduct(app, 'abita.development') | Set up Zope. | 625941d863b5f9789fde736a |
def test_login(self): <NEW_LINE> <INDENT> pass | 点击微信登录 | 625941d810dbd63aa1bd2e27 |
def get_json(url): <NEW_LINE> <INDENT> call = requests.get(url) <NEW_LINE> call.raise_for_status() <NEW_LINE> return call.json() | GET some JSON, raising an HTTPError if we don't get a 200 status.
First calls make_url using the arguments, then makes the web requests and
returns the JSON. If the received JSON is empty, throw a ValueError. | 625941d882261d6c526ab727 |
@then('a coordenada Y da estrela esta entre 0 e 600') <NEW_LINE> def then_avalia_coordenada_Y_estrela(context): <NEW_LINE> <INDENT> observado = context.resultado[1] <NEW_LINE> assert (0 <= observado <= 600) is True | Testa se a coordenada Y esta na faixa valida. | 625941d8711fe17d825425eb |
def require_login_func(request): <NEW_LINE> <INDENT> o_user = get_user_from_session(request) <NEW_LINE> return o_user is not None | 需要登录装饰器 | 625941d830bbd722463cc04d |
def test_clinical_risk(self): <NEW_LINE> <INDENT> self.assertEqual(self.ews_activity.data_ref.clinical_risk, self.expected_risk, msg='Risk not matching') | Test that the Clinical Risk is correct | 625941d8de87d2750b860019 |
def assign_from_line_request(request): <NEW_LINE> <INDENT> rtn = True <NEW_LINE> logger = logging.getLogger('django') <NEW_LINE> if not validate_sig(request): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> request_json = json.loads(request.body.decode('utf-8')) <NEW_LINE> if request.method == 'POST': <NEW_LINE> <... | description : line からのwebhookに対して、処理を振り分ける
args : request -> lineからのrequest
return : True/False | 625941d856ac1b37e6264451 |
def __sub__(self, other): <NEW_LINE> <INDENT> d = tasdata() <NEW_LINE> if self.binned: <NEW_LINE> <INDENT> d.x = self.x <NEW_LINE> other.hist(self.bin_edges) <NEW_LINE> d.I = self.I - other.I <NEW_LINE> d.err = np.sqrt(self.err**2 + other.err**2) <NEW_LINE> <DEDENT> elif other.binned: <NEW_LINE> <INDENT> d.x = other.x ... | subtraction given that one object is binned
returns an object with x, I, err rather than counts and monitor
err is added in quadrature | 625941d83346ee7daa2b2ff2 |
def does_redirect_outside_target(self): <NEW_LINE> <INDENT> redirect_destination = self.get_redirect_destination() <NEW_LINE> if redirect_destination is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> original_proto = self.get_url().get_protocol() <NEW_LINE> redirect_proto = redirect_destination.get_protocol... | :return: True when the redirect destination is not the same
domain and protocol than the originally requested URL | 625941d88e05c05ec3eea5fb |
def main(eap): <NEW_LINE> <INDENT> while afl.loop(ROUNDS): <NEW_LINE> <INDENT> rcv = sys.stdin.read() <NEW_LINE> data = None <NEW_LINE> try: <NEW_LINE> <INDENT> data = bytearray.fromhex(rcv) <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if eap: <NEW_LINE> <INDENT> te... | Run AFL repeatedly with externally supplied generated packet from STDIN. | 625941d8b7558d58953c5195 |
def create_puzzle(puzzle_id, joey_words, kangaroo_words, joey_clues): <NEW_LINE> <INDENT> df = pd.DataFrame({ "joey_word":joey_words, "kangaroo_word":kangaroo_words }) <NEW_LINE> df = append_columns(df) <NEW_LINE> df["joey_clue"] = joey_clues <NEW_LINE> letter_bank = [x.upper() for x in "".join(df.joey_word)] <NEW_LINE... | saves a json object of the form puzzle_<id> | 625941d85fc7496912cc3c03 |
def get_subreddit_breakdown(self, subreddit): <NEW_LINE> <INDENT> cursor = self.datastore.execute( 'SELECT comic_id, COUNT(*) FROM xkcd_comic_references WHERE subreddit = ? GROUP BY comic_id ORDER BY COUNT(*) DESC', (subreddit,) ) <NEW_LINE> for v in cursor: <NEW_LINE> <INDENT> yield v | Get comic reference count filtered by a subreddit.
:param subreddit: The subreddit to filter by.
:return: A generator of tuples of the format (comic_id, reference_count) in descending order. | 625941d84e4d5625662d465a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.