code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def set_offset(axis, deg_val): <NEW_LINE> <INDENT> return self.hdwr("Antenna", "set_offset_one_axis", axis, deg_val) | Shortcut function for setting offset at a specific axis | 625941ef99cbb53fe6793167 |
def import_players_and_times(self, filename): <NEW_LINE> <INDENT> with open(filename, "r") as infile: <NEW_LINE> <INDENT> for player_yaml in yaml.load(infile, Loader = yaml.SafeLoader): <NEW_LINE> <INDENT> player = Player(player_yaml["real_name"], player_yaml["alias"], player_yaml["hex_code"], self) <NEW_LINE> player.i... | This creates the games Players (with their Times) by loading them from a YAML file. | 625941f0fb3f5b602dac3c1b |
def _validate_if_ve_exists(self, device, intf_name, vrrpe_group): <NEW_LINE> <INDENT> if vrrpe_group is None: <NEW_LINE> <INDENT> raise ValueError('VRRPe group cannot be None') <NEW_LINE> <DEDENT> elif int(vrrpe_group) < 1 or int(vrrpe_group) > 255: <NEW_LINE> <INDENT> raise ValueError('VRRPe group has to be in range o... | validate ve
| 625941f04f88993c3716c5e3 |
def divide(self, dividend, divisor): <NEW_LINE> <INDENT> positive = (dividend < 0) is (divisor < 0) <NEW_LINE> dividend, divisor, div = abs(dividend), abs(divisor), abs(divisor) <NEW_LINE> res = 0 <NEW_LINE> q = 1 <NEW_LINE> while dividend >= divisor: <NEW_LINE> <INDENT> dividend -= div <NEW_LINE> res += q <NEW_LINE> q... | :type dividend: int
:type divisor: int
:rtype: int | 625941f0a219f33f34628ee4 |
def samples( model, session, data, sample_range, batch_size, num_points=10000, num_bins=100 ): <NEW_LINE> <INDENT> xs = np.linspace(-sample_range, sample_range, num_points) <NEW_LINE> bins = np.linspace(-sample_range, sample_range, num_bins) <NEW_LINE> db = np.zeros((num_points, 1)) <NEW_LINE> for i in range(num_points... | Return a tuple (db, pd, pg), where db is the current decision
boundary, pd is a histogram of samples from the data distribution,
and pg is a histogram of generated samples. | 625941f01f5feb6acb0c50cc |
def decode_csv(line): <NEW_LINE> <INDENT> parsed_line = tf.decode_csv(line, default) <NEW_LINE> label = parsed_line[-1:] <NEW_LINE> del parsed_line[-1] <NEW_LINE> features = parsed_line <NEW_LINE> d = dict(zip(feature_names, features)), label <NEW_LINE> return d | Parses the csv and creates the appropiate tensor structure for the labels and
a dictionary for features and their values | 625941f071ff763f4b549c18 |
def _check_and_add_components(self, components): <NEW_LINE> <INDENT> for item in components: <NEW_LINE> <INDENT> key = item.id <NEW_LINE> if key == self.id: <NEW_LINE> <INDENT> msg = "Can't add a Component with the same id as its parent." <NEW_LINE> raise ValueError(msg) <NEW_LINE> <DEDENT> self._component_map[key] = i... | Make sure components can be used with constraints.
| 625941f0a8370b7717052e20 |
def index_gzip(pathIn, pathOut, max_idx=10000, idx_len=8, verbose=False, comp_str=-1): <NEW_LINE> <INDENT> if pathIn.endswith("gz"): <NEW_LINE> <INDENT> fileOpen = gzip.open <NEW_LINE> <DEDENT> elif pathIn.lower().endswith("mzml"): <NEW_LINE> <INDENT> fileOpen = open <NEW_LINE> <DEDENT> with GSGW( output_path=pathOut, ... | Convert an mzml file (can be gzipped) into an indexed, gzipped mzML file.
Arguments:
pathIn (str): path to an mzML input File.
pathOut (str): path were the index gzip will be created.
Keyword Arguments:
max_idx (int): number of indexes which can be saved.
idx_len (int): character len of on key
ver... | 625941f0ac7a0e7691ed4643 |
def unorderedSearch(self, target): <NEW_LINE> <INDENT> target = str(target) <NEW_LINE> curNode = self._head <NEW_LINE> while curNode is not None: <NEW_LINE> <INDENT> if curNode.item == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> curNode = curNode.next <NEW_LINE> <DEDENT> return False | Searches for the target.
:param target: item you want to find
:return: True if item is in the list, False if not
:rtype: | 625941f007d97122c4178e1b |
def char1632(self): <NEW_LINE> <INDENT> exe = os.path.join(os.getcwd(), "a.out") <NEW_LINE> target = self.dbg.CreateTarget(exe) <NEW_LINE> self.assertTrue(target, VALID_TARGET) <NEW_LINE> lldbutil.run_break_set_by_file_and_line (self, "main.cpp", self.line) <NEW_LINE> process = target.LaunchSimple (None, None, self.get... | Test that the C++11 support for char16_t and char32_t works correctly. | 625941f0b7558d58953c548a |
def generate_random(table): <NEW_LINE> <INDENT> special_char = ['#', '$', '%', '&', '!'] <NEW_LINE> letter_low = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'w', 'x', 'y', 'z' ] <NEW_LINE> letter_upper = [item.upper() for item in letter_low] <NEW_LINE> digi... | Generates random and unique string. Used for id/key generation.
Args:
table: list containing keys. Generated string should be different then all of them
Returns:
Random and unique string | 625941f00383005118ecfb63 |
def reim(self, inp): <NEW_LINE> <INDENT> if self.signal < 0: <NEW_LINE> <INDENT> return inp.real <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return inp.imag | Return real or imaginary part as a function of signal. | 625941f029b78933be1e5c27 |
def export(self, resource, sheet, title, subtitle=None): <NEW_LINE> <INDENT> T = current.T <NEW_LINE> indicators = self.compute(resource) <NEW_LINE> write = self.write <NEW_LINE> rowindex = 0 <NEW_LINE> write(sheet, rowindex, 0, title, style="header") <NEW_LINE> rowindex += 1 <NEW_LINE> if subtitle: <NEW_LINE> <INDENT>... | Export performance indicators
@param resource: the S3Resource
@param sheet: the XLS worksheet to write to
@param title: the title for the export
@param subtitle: an optional subtitle (e.g. start+end dates) | 625941f0851cf427c661aa8c |
def nGramGenerator(string,n=1,unit=0,caseSensitive=False,ignoreSpecialChars=True): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> assert n>0,unit in (range(2)) <NEW_LINE> if ignoreSpecialChars: <NEW_LINE> <INDENT> string=re.sub(r"\W","",string) <NEW_LINE> <DEDENT> if not caseSensitive: <NEW_LINE> <INDENT> string=string.l... | input a string
returns a list of n-Grams by taking unit level.
If unit=0, grams are generated at character level
If unit=1, grams are generated at word level | 625941f0d6c5a102081445d2 |
@login_required(login_url=login_url) <NEW_LINE> def index(request): <NEW_LINE> <INDENT> if 'order_id' in request.session: <NEW_LINE> <INDENT> order = Order.objects.get(pk=request.session['order_id']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> account = Account.for_user(request.user) <NEW_LIN... | Lists all drinks in the system
and shows current order (cart) | 625941f0d10714528d60026c |
def on_send(self, frame): <NEW_LINE> <INDENT> print('on_send %s %s %s' % (frame.cmd, frame.headers, frame.body)) | :param Frame frame: | 625941f021a7993f00bc827d |
def command1(department, department_id): <NEW_LINE> <INDENT> query = where(select_table(department), "ID", department_id) <NEW_LINE> for i in query: <NEW_LINE> <INDENT> print("{}, {}".format(i[PROPERTY_DEPARTMENT_NAME], i[PROPERTY_DEPARTMENT_CITY])) | Get department name and city for department ID.
example input: Department 42
:param department_id: Department ID | 625941f0f7d966606f6aa58d |
def GetOutsideValue(self): <NEW_LINE> <INDENT> return _itkKappaSigmaThresholdImageFilterPython.itkKappaSigmaThresholdImageFilterIUL3IUC3_GetOutsideValue(self) | GetOutsideValue(self) -> unsigned long | 625941f0d4950a0f3b08c8c9 |
def to_strict(self): <NEW_LINE> <INDENT> if self.lazy: <NEW_LINE> <INDENT> self._rows = list(self._rows) <NEW_LINE> self.lazy = False | Convert this (lazy) exportable into a non-lazy (strict) one. | 625941f030c21e258bdfaa26 |
def show_boxes(img): <NEW_LINE> <INDENT> from PIL import ImageDraw <NEW_LINE> drawing_object=ImageDraw.Draw(img) <NEW_LINE> bounding_boxes=pageseg.segment(img.convert('1'))['boxes'] <NEW_LINE> for box in bounding_boxes: <NEW_LINE> <INDENT> drawing_object.rectangle(box, fill = None, outline ='red') <NEW_LINE> <DEDENT> r... | Modifies the passed image to show a series of bounding boxes on an image as run by kraken
:param img: A PIL.Image object
:return img: The modified PIL.Image object | 625941f0d10714528d60026d |
def parse_hgts(input_f, method): <NEW_LINE> <INDENT> for line in input_f: <NEW_LINE> <INDENT> if hgt_parse_strs[method][0] in line: <NEW_LINE> <INDENT> return line.strip().split( hgt_parse_strs[method][1])[1].split( hgt_parse_strs[method][2])[0] <NEW_LINE> <DEDENT> <DEDENT> return 'NaN' | Extract number of HGTs found.
Parameters
----------
input_f: string
file descriptor for T-REX output results
method: string
HGT detection method
Returns
-------
number_of_hgts: string
number of HGTs reported by a tool, or NaN if an entry was not found | 625941f07d847024c06be843 |
def find_unknown_words(vocab, wds): <NEW_LINE> <INDENT> result = [] <NEW_LINE> for w in wds: <NEW_LINE> <INDENT> if search_linear(vocab, w) < 0: <NEW_LINE> <INDENT> result.append(w) <NEW_LINE> <DEDENT> <DEDENT> return result | Return a list of words in wds that do not occur in vocab. | 625941f02eb69b55b151ce3a |
@app.route('/sql2uri/view/<report>') <NEW_LINE> def view_report(report=None, event=None): <NEW_LINE> <INDENT> report = report if report else event['report'] <NEW_LINE> args = loads(report_info(report).data) <NEW_LINE> data = loads(run_sql( args['backend_name'], args['options'], ).json() ) <NEW_LINE> saved = save_to_uri... | Run all your reports on demand.
Deploy to gdrive and this is also configurable. | 625941f038b623060ff0b36f |
@handle_response_format <NEW_LINE> @treeio_login_required <NEW_LINE> def project_delete(request, project_id, response_format='html'): <NEW_LINE> <INDENT> project = get_object_or_404(Project, pk=project_id) <NEW_LINE> if not request.user.get_profile().has_permission(project, mode='w'): <NEW_LINE> <INDENT> return user_de... | Project delete | 625941f0b545ff76a8914398 |
def parameters(self): <NEW_LINE> <INDENT> parser = ArgumentParser() <NEW_LINE> parser.add_argument("-s", "--speed", help="Регулировка скорости воспроизведения. Целое число. Запускать с правами администратора. Пример: 25000") <NEW_LINE> parser.add_argument("-r", "--read", help="Читать файл. Файл:начало:конец") <NEW_LINE... | установка параметров в файле | 625941f057b8e32f52483a21 |
def init_variables(self): <NEW_LINE> <INDENT> self.init = False <NEW_LINE> self.width, self.height = 0, 0 <NEW_LINE> self.size = None <NEW_LINE> parent = self.GetParent() <NEW_LINE> self.parentsize = parent.GetSize() | Initialize varianbles | 625941f0e1aae11d1e74a240 |
def dataerr(manager, osd, pool, obj): <NEW_LINE> <INDENT> log.info("injecting data err on object") <NEW_LINE> return manager.osd_admin_socket( osd, ['injectdataerr', pool, obj]) | cause an error in the data | 625941f0d8ef3951e3243ac0 |
def to_dict(self, game): <NEW_LINE> <INDENT> return {x[1]: x[0] for x in game} | Return a dictionary representation of the game. | 625941f0167d2b6e31219117 |
def optimize(loss, learning_rate, hparams, variables): <NEW_LINE> <INDENT> loss = tf.identity(loss, name="total_loss") <NEW_LINE> opt = ConditionalOptimizer(hparams.optimizer, learning_rate, hparams) <NEW_LINE> opt_summaries = ["learning_rate", "loss"] <NEW_LINE> if hparams.summarize_grads: <NEW_LINE> <INDENT> opt_summ... | Minimize loss. | 625941f05fc7496912cc3f00 |
def ValidateString(value, name='unused', exception=datastore_errors.BadValueError, max_len=_MAX_STRING_LENGTH, empty_ok=False): <NEW_LINE> <INDENT> if value is None and empty_ok: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not isinstance(value, str) or isinstance(value, Blob): <NEW_LINE> <INDENT> raise exception(... | Raises an exception if value is not a valid string or a subclass thereof.
A string is valid if it's not empty, no more than _MAX_STRING_LENGTH bytes,
and not a Blob. The exception type can be specified with the exception
argument; it defaults to BadValueError.
Args:
value: the value to validate.
name: the name of... | 625941f0287bf620b61d3fe3 |
def remove(self, data): <NEW_LINE> <INDENT> self.denominator = (self.denominator * data_to_num3072(data)) % self.MODULUS | Remove a byte array from the set. | 625941f09c8ee82313fbbcfa |
def build_node_neighbours(self): <NEW_LINE> <INDENT> tmp_nodes = copy.deepcopy(self.nodes) <NEW_LINE> """ 在原本的格子世界最外层的四周 padding 一层 None 对象,避免添加邻居时要对边缘特殊点做判断 """ <NEW_LINE> for i in range(len(tmp_nodes)): <NEW_LINE> <INDENT> tmp_nodes[i] = [None] + tmp_nodes[i] + [None] <NEW_LINE> <DEDENT> tmp_nodes.insert(0, [None] * ... | 为格子世界中每一个 Node 对象添加邻居。
:return: None | 625941f0711fe17d825428e1 |
def addBinary(self, a, b): <NEW_LINE> <INDENT> a_int = int(a, 2) <NEW_LINE> b_int = int(b, 2) <NEW_LINE> result = a_int + b_int <NEW_LINE> return '{0:b}'.format(result) | :type a: str
:type b: str
:rtype: str | 625941f0be383301e01b59fd |
def unserialise(self, data): <NEW_LINE> <INDENT> if self.size() != len(data): <NEW_LINE> <INDENT> raise Exception( "Incorrect input size (expecting %s bytes, got %s)" % (self.size(), len(data)) ) <NEW_LINE> <DEDENT> tlv = TLV() <NEW_LINE> i = 0 <NEW_LINE> for tag, length in self: <NEW_LINE> <INDENT> tlv[tag] = data[i :... | Parse an input stream of bytes and return a TLV object. | 625941f007f4c71912b11a08 |
def __setattr__(self, name, value): <NEW_LINE> <INDENT> self[name] = value | Subclass properties will override dictionary keys. | 625941f04a966d76dd551598 |
def Phone_Data_50bang(js): <NEW_LINE> <INDENT> if isinstance(js, dict): <NEW_LINE> <INDENT> global fa_key <NEW_LINE> for key in js: <NEW_LINE> <INDENT> if isinstance(js[key], dict): <NEW_LINE> <INDENT> Phone_Data_50bang(js[key]) <NEW_LINE> <DEDENT> elif isinstance(js[key], list): <NEW_LINE> <INDENT> len_list_js = len(j... | 对应脚本S001,手机号、pass_id、extend
:param js:
:return: | 625941f0187af65679ca56a3 |
def list_instances(self): <NEW_LINE> <INDENT> nodes = self.connection.baremetal.nodes(associated=True, details=True) <NEW_LINE> instances = [i for i in map(self._get_instance, nodes) if i.state != _instance.InstanceState.UNKNOWN] <NEW_LINE> return instances | List instances deployed by metalsmith.
:return: list of :py:class:`metalsmith.Instance` objects. | 625941f030dc7b7665901ee3 |
def ajouter_obs(self,obstacle,P1,P2): <NEW_LINE> <INDENT> longueur_du_robot = Config().get_longueur_du_robot() <NEW_LINE> ecart_de_surete = Config().get_ecart_de_surete() <NEW_LINE> longueur_terrain = Config().get_longueur_terrain() <NEW_LINE> largeur_terrain = Config().get_largeur_terrain() <NEW_LINE> dx = Config().ge... | Fonction qui realise toutes les procedures pour retirer un obstacle | 625941f0a4f1c619b28b05ae |
def create_dummy(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | Missing associated documentation comment in .proto file | 625941f0627d3e7fe0d693d5 |
def getAction(self, state): <NEW_LINE> <INDENT> if len(self.actions) > 0: <NEW_LINE> <INDENT> action = self.actions.pop() <NEW_LINE> return action <NEW_LINE> <DEDENT> pacman = state.getPacmanPosition() <NEW_LINE> self.goals = state.getFood().asList() <NEW_LINE> self.goals = sorted(self.goals, key=lambda c: manhattanDis... | Parameters:
-----------
- `state`: the current game state as defined pacman.GameState.
(you are free to use the full GameState interface.)
Return:
-------
- A legal move as defined game.Directions. | 625941f0fff4ab517eb2f9c3 |
def _fit_transform_data_container(self, data_container: DataContainer, context: ExecutionContext) -> ('BaseStep', DataContainer): <NEW_LINE> <INDENT> self.create_checkpoint_path(context.get_path()) <NEW_LINE> self.flush_cache() <NEW_LINE> self.wrapped = self.wrapped.fit(data_container.data_inputs, data_container.expect... | Fit transform data container.
:param context: execution context
:param data_container: the data container to transform
:type data_container: neuraxle.data_container.DataContainer
:return: tuple(fitted pipeline, data_container) | 625941f015fb5d323cde109b |
def resnext50_32x4d(pretrained: bool = False, progress: bool = True, **kwargs: Any) -> ResNet: <NEW_LINE> <INDENT> kwargs['groups'] = 32 <NEW_LINE> kwargs['width_per_group'] = 4 <NEW_LINE> return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs) | ResNeXt-50 32x4d model from
`"Aggregated Residual Transformation for Deep Neural Networks" <https://arxiv.org/pdf/1611.05431.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 | 625941f0f548e778e58cdb03 |
def get_type(self): <NEW_LINE> <INDENT> return self._typ | returns this cssPropertySet's type | 625941f0e76e3b2f99f3ad85 |
def add_features_to_http_headers(features, headers): <NEW_LINE> <INDENT> if features: <NEW_LINE> <INDENT> for k, v in features.items(): <NEW_LINE> <INDENT> if k.lower() in FEATURE_BLACKLIST: <NEW_LINE> <INDENT> raise exception.UnsupportedHeaderFeature(feature=k) <NEW_LINE> <DEDENT> if v is not None: <NEW_LINE> <INDENT>... | Adds additional headers representing glance features to be enabled.
:param headers: Base set of headers
:param features: Map of enabled features | 625941f023e79379d52eeadf |
def received_information(update, context): <NEW_LINE> <INDENT> text = update.message.text <NEW_LINE> user_data = context.user_data <NEW_LINE> user_data['count'] += 1 <NEW_LINE> if text == 'выход': <NEW_LINE> <INDENT> update.message.reply_text("Пока играли, были названы города: {}".format(user_data['city'])) <NEW_LINE> ... | Основное тело игры | 625941f0099cdd3c635f11db |
def tablenames(self, body_only=False, include_builtin=False, include_modal=True): <NEW_LINE> <INDENT> tables = set() <NEW_LINE> if not body_only: <NEW_LINE> <INDENT> tables.add(self.head.tablename()) <NEW_LINE> <DEDENT> tables.add(self.trigger.tablename()) <NEW_LINE> for atom in self.body: <NEW_LINE> <INDENT> tables.ad... | Return the set of tablenames occurring in this delta rule. | 625941f0507cdc57c630726c |
def render_text(screen, text, position, size=30, center=True): <NEW_LINE> <INDENT> font = pygame.font.Font('data/fonts/arial.ttf', size) <NEW_LINE> render = font.render(text, True, colour_white, position) <NEW_LINE> rect = render.get_rect(center=(screen.width / 2, position[1]) if center else position) <NEW_LINE> screen... | Renders text and wraps in the TextSprite sprite, binding it
to the provided screen with optional size and centering.
:param screen: screen that we're drawing on.
:param text: text to display.
:param position: tuple of x and y position.
:param size: font size.
:param center: should the text be horizontally ... | 625941f0d7e4931a7ee9e4a3 |
def get_mock_bridge( bridge_id="aabbccddeeff", host="1.2.3.4", mock_create_user=None, username=None ): <NEW_LINE> <INDENT> mock_bridge = Mock() <NEW_LINE> mock_bridge.host = host <NEW_LINE> mock_bridge.username = username <NEW_LINE> mock_bridge.config.name = "Mock Bridge" <NEW_LINE> mock_bridge.id = bridge_id <NEW_LINE... | Return a mock bridge. | 625941f0cb5e8a47e48b8024 |
def _sample(self, logits: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> raise NotImplementedError | Given the logits for each class, return the predicted class and its logit.
Parameters
----------
logits : ``torch.Tensor``
The tensor contains the logits for each class.
Shape: ``(batch_size, class_nums)``
Returns
-------
Tuple[torch.Tensor, torch.Tensor]
Tuple of ``(logprobs, predicted_classes)``, where ``... | 625941f0a934411ee3751c18 |
def test_service(self): <NEW_LINE> <INDENT> out, err, eid = system('systemctl status crond.service') <NEW_LINE> out = out.decode('utf-8') <NEW_LINE> self.assertIn('disabled', out) | Tests the crond service. | 625941f082261d6c526aba2b |
def short_str(self): <NEW_LINE> <INDENT> return self.make_str(print_species=False) | Do not print the species attribute (e.g. 'HLA') | 625941f094891a1f4081c02f |
def __init__(self, agency_id: int, schedules_path: str, local_timezone: str): <NEW_LINE> <INDENT> self._shuttle_data_lock = Lock() <NEW_LINE> self._route_data_lock = Lock() <NEW_LINE> self._paper_schedules_lock = Lock() <NEW_LINE> self._tz = pytz.timezone(local_timezone) <NEW_LINE> self._agency_id = agency_id <NEW_LINE... | Manages all routing and scheduling and determines the timeliness of a shuttle
:param agency_id: The agency for which to compute scheduling
:param schedules_path: The path where the CSVs of the schedules are stored
:param local_timezone: A string representing the local timezone | 625941f02eb69b55b151ce3b |
def delete_random(self, widget): <NEW_LINE> <INDENT> self.delete_task(widget, order='random') | Delete tasks in random order | 625941f0a17c0f6771cbe5d2 |
def __init__(self): <NEW_LINE> <INDENT> super(ArduinoStation, self).__init__() <NEW_LINE> self.serial_port_pattern = '/dev/ttyACM{port_num}' <NEW_LINE> self.serial_port_num = None <NEW_LINE> self.baudrate = 9600 <NEW_LINE> self.ser = self._setup_serial_connection() <NEW_LINE> if config.SCB_CONFIGURATION == 'standard': ... | Setup ArudinoStation object, including Serial data connection. | 625941f0d99f1b3c44c67b07 |
def weighted_attribute_scores(screen_names, user_jaccard_similarities, attribute_exemplars): <NEW_LINE> <INDENT> df = attribute_exemplars <NEW_LINE> exemplars = list(df[df['count']>=5].screen_name) <NEW_LINE> weights = list(df[df['count']>=5]['count']) <NEW_LINE> weights_normed = [x/np.sum(weights) for x in weights] <N... | Screen Names will be a list of twitter screen names for both Brands and Exemplars.
The user_jaccard_similarities is the output from jaccard scores and is a dictionary of dictionaries.
{User 1: {User2: score, User3: score, ...} ...} attribute_exemplars should be a dataframe with 2 columns:
screen_name and count giving t... | 625941f0b57a9660fec33e10 |
def _set_span_xy(self, event): <NEW_LINE> <INDENT> x, y = self._get_data(event) <NEW_LINE> if x is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.prev = x, y <NEW_LINE> if self.direction == 'horizontal': <NEW_LINE> <INDENT> v = x <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> v = y <NEW_LINE> <DEDENT> minv, m... | Set the span coordinates. | 625941f076e4537e8c351bfb |
def rescale(self, factor): <NEW_LINE> <INDENT> self.interpolator.y *= factor <NEW_LINE> if self.error is not None: <NEW_LINE> <INDENT> self.error *= numpy.absolute(factor) <NEW_LINE> <DEDENT> if self.fnu is not None: <NEW_LINE> <INDENT> self.fnu *= factor | Rescale the spectrum by the provided factor.
The spectral data are modified *in-place*; nothing is
returned.
Args:
factor (scalar-like or array-like):
Factor to multiply the fluxes. If it's a vector, it
must have the same length as the existing spectrum. | 625941f0d6c5a102081445d3 |
def ensure_git_path(self, repository, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError(self.__class__.__name__) | Make sure the repository is checked out.
Normally one would use ensure_repository which also ensures the metadata
is cached. However repositories that are not version controlled in the
normal way (e.g. spinnaker.github.io) dont use the metadata so the
assumptions in ensure_repository are not applicable.
Returns: The ... | 625941f0293b9510aa2c3814 |
def isSentinel(self,s,suffix=''): <NEW_LINE> <INDENT> s = s.strip() <NEW_LINE> if self.delim1 and s.startswith(self.delim1): <NEW_LINE> <INDENT> return s.startswith(self.delim1+'@'+suffix) <NEW_LINE> <DEDENT> elif self.delim2: <NEW_LINE> <INDENT> return s.startswith(self.delim2+'@'+suffix) and s.endswith(self.delim3) <... | Return True is line s contains a valid sentinel comment. | 625941f0a79ad161976cc6c9 |
def Purchase_Order_Current_Items(self, purno): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> purno = self.SAS(purno) <NEW_LINE> cnxn = pyodbc.connect('DRIVER={Microsoft Visual FoxPro-Treiber};SOURCETYPE=DBC;SOURCEDB=P:\PRODATA.DBC;NULL=NO') <NEW_LINE> c = cnxn.cursor() <NEW_LINE> SQL = '''SELECT Purno,Item,Descrip,Cost,... | Searches the current fiscal period for Accpac Purchase Order Line Items
------
Searches Table Potran01 | 625941f03617ad0b5ed6847a |
def test_above_eight_hundred(self): <NEW_LINE> <INDENT> assert osd.get_cable_sizing_ocpd(1000) == 1000 <NEW_LINE> assert osd.get_cable_sizing_ocpd(2500) == 2500 | Test for ocpd sizes greater than 800. | 625941f08da39b475bd654ff |
def test_parent_rename_node(): <NEW_LINE> <INDENT> node1 = Node(name="aaaa", props={"a": "b", "c": "d"}) <NEW_LINE> node2 = Node(name="bbbb", props={"a": "b", "c": "d"}) <NEW_LINE> node3 = Node(name="cccc", props={"a": "b", "c": "d"}) <NEW_LINE> assert node1.path == ['aaaa'] <NEW_LINE> assert node2.path == ['bbbb'] <NE... | Renames a node and changes it's parent to test the path functionality
:return: | 625941f0bd1bec0571d90bb2 |
def test_missing_terms_filtered_query(self): <NEW_LINE> <INDENT> terms_filter = TermsFilter.get_missing_terms_filter("field", "group_name") <NEW_LINE> query = ElasticQuery.filtered(Query.match_all(), terms_filter) <NEW_LINE> elastic = Search(query, idx=ElasticSettings.idx('DEFAULT')) <NEW_LINE> docs = elastic.search().... | Test filtered query with a missing terms filter. | 625941f063f4b57ef000168c |
def tearDown(self): <NEW_LINE> <INDENT> with database() as db: <NEW_LINE> <INDENT> db.query("DELETE FROM persons WHERE person_name = 'test_person_a' OR person_name = 'test_person_b'") | Remove the test data from the database | 625941f0236d856c2ad44d66 |
def pc_output_buffers_full(self, *args): <NEW_LINE> <INDENT> return _iio_swig.modulo_const_ff_sptr_pc_output_buffers_full(self, *args) | pc_output_buffers_full(modulo_const_ff_sptr self, int which) -> float
pc_output_buffers_full(modulo_const_ff_sptr self) -> pmt_vector_float | 625941f04e4d5625662d4953 |
def test_mark_all_read(self): <NEW_LINE> <INDENT> now = timezone.now() <NEW_LINE> subjects = ['foo', 'bar', 'woo'] <NEW_LINE> messages = list(map(lambda subject: Message.objects.create(subject=subject), subjects)) <NEW_LINE> m1 = MessageItem.objects.create(user=self.users['Cersei'], message=messages[0]) <NEW_LINE> m2 =... | tests that marking all given messages as read only marks those that aren't already read | 625941f0460517430c3946f9 |
def add_prediction_op(self): <NEW_LINE> <INDENT> x = self.add_embedding() <NEW_LINE> W = tf.get_variable('W',dtype = tf.float32, shape = (self.config.n_features*self.config.embed_size,self.config.hidden_size), initializer = xavier_weight_init()) <NEW_LINE> b1 = tf.get_variable('b1',dtype = tf.float32,shape = (self.conf... | Adds the 1-hidden-layer NN:
h = Relu(xW + b1)
h_drop = Dropout(h, dropout_rate)
pred = h_dropU + b2
Note that we are not applying a softmax to pred. The softmax will instead be done in
the add_loss_op function, which improves efficiency because we can use
tf.nn.softmax_cross_entropy_with_logits
Use the in... | 625941f04c3428357757c8a8 |
def get(self, topic, meta=False): <NEW_LINE> <INDENT> msg = next(self.stream(meta=meta, topic=topic)) <NEW_LINE> self.unsub() <NEW_LINE> return msg | Return just one message from messages() | 625941f091af0d3eaac9bfa2 |
@app.route('/register', methods=['GET', 'POST']) <NEW_LINE> def register(): <NEW_LINE> <INDENT> form = RegisterForm(request.form) <NEW_LINE> if request.method == 'POST' and form.validate(): <NEW_LINE> <INDENT> insert_user(name=form.name.data, email=form.email.data, username=form.username.data, password=form.password.da... | Serves the registeration page
:return: The login page if POST the Registeration page if GET | 625941f00c0af96317bb876b |
def detect_shelf_layers_cb(self, data): <NEW_LINE> <INDENT> result_type = DetectShelfLayersResult <NEW_LINE> action_server = self.detect_shelf_layer_as <NEW_LINE> prefix = 'detect_shelf_layers' <NEW_LINE> self.print_with_prefix('called', prefix) <NEW_LINE> r = result_type() <NEW_LINE> state = self.wait_for( [self.READY... | :type data: DetectShelfLayersGoal | 625941f0bd1bec0571d90bb3 |
def test_tree_two_nodes_left_has_depth_one(one_t): <NEW_LINE> <INDENT> one_t.insert(5) <NEW_LINE> assert one_t.depth() == 1 | 2 node tree with root child on left should have depth one. | 625941f02ae34c7f2600d6b4 |
def create_translator(self): <NEW_LINE> <INDENT> return {x['es_name']: x['csv_name'] for x in self.get_column_dict()} | create dict with structure es_name: csv_name | 625941f001c39578d7e753bf |
def cleanup(self): <NEW_LINE> <INDENT> os.remove(self.tgz_file) <NEW_LINE> shutil.rmtree(self.dirname) | Cleanup
| 625941f031939e2706e4d3e5 |
def __hash__(self): <NEW_LINE> <INDENT> return hash(self.origin) | Get the tree node's hash.
The origin's hash is used for the whole node,
so if two different nodes somehow have the same origin,
it will cause the nodes to be treated as equal by hash-based types. | 625941f015baa723493c44fe |
def _m_step(self, X, logp): <NEW_LINE> <INDENT> p = np.exp(logp) <NEW_LINE> psum = p.sum(axis=0) + 10 * np.finfo(p.dtype).eps <NEW_LINE> if self.gamma_type == "full": <NEW_LINE> <INDENT> gammas_ = psum / psum.sum() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> gammas_ = np.ones(self.n_components) / self.n_components <N... | The Maximization step.
Maximize the expectation of joint distribution and compute the new
parameters. | 625941f02c8b7c6e89b35d40 |
def page_comments(self, url, **args): <NEW_LINE> <INDENT> return self.fetch("/post/comments.json", url=url, **args) | Retrieve excerpts of comments published on a particular page.
Arguments:
url - required; The post url to return comments for.
See http://www.backtype.com/developers/page-comments. | 625941f0656771135c3ebdf9 |
def scenarios_set(self, old, new): <NEW_LINE> <INDENT> s_temp = self._scenarios[old] <NEW_LINE> self._scenarios.pop(old) <NEW_LINE> self._scenarios.insert(new, s_temp) | Change order of a scenario in the scenario list of the project | 625941f01d351010ab85609e |
def isort(context, check=False) -> Result: <NEW_LINE> <INDENT> isort_options = f"{'--check-only --diff' if check else ''}" <NEW_LINE> return context.run(f"isort {isort_options} {' '.join(PYTHON_DIRS)}", warn=True) | Runs isort. | 625941f07d43ff24873a3228 |
def _post(self, label=None, recipients=None, services=None): <NEW_LINE> <INDENT> if label is None: <NEW_LINE> <INDENT> raise DynectInvalidArgumentError <NEW_LINE> <DEDENT> uri = '/Notifier/' <NEW_LINE> self._label = label <NEW_LINE> self._recipients = recipients <NEW_LINE> self._services = services <NEW_LINE> response ... | Create a new :class:`~dyn.tm.accounts.Notifier` object on the
DynECT System | 625941f0bf627c535bc13753 |
def show_jobs(self,textctrl,jobs,none="-- none --"): <NEW_LINE> <INDENT> textctrl.SetValue('') <NEW_LINE> if jobs: <NEW_LINE> <INDENT> for k,v in jobs.iteritems(): <NEW_LINE> <INDENT> textctrl.AppendText("job_id={}\n".format(k)) <NEW_LINE> for kk,vv in v.iteritems(): <NEW_LINE> <INDENT> textctrl.AppendText(" {:<13} :... | show information on a set of jobs in textctrl | 625941f0004d5f362079a8b3 |
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(MoveBaseAction, self).__init__(*args, **kwds) <NEW_LINE> if self.action_goal is None: <NEW_LINE> <INDENT> self.action_goal = msgs_demo.msg.MoveBaseActionGoal() <NEW_LINE> <DEDENT> if self.action_result is None: <NEW_LINE> ... | Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
action_goal,action_result,action_f... | 625941f05510c4643540f95a |
def save(self, prefix): <NEW_LINE> <INDENT> for (name, fig) in self.figures.items(): <NEW_LINE> <INDENT> fig = fig[0] <NEW_LINE> fig.savefig(prefix + name + '.svg') <NEW_LINE> fig.clf() | Save the figures to SVG files.
The files created are named `prefix + figure_name + ".svg"`. | 625941f031939e2706e4d3e6 |
def build_url(self,exclude_key): <NEW_LINE> <INDENT> m = lambda x:x.encode('utf-8') if isinstance(x,unicode) else x <NEW_LINE> encode_to_url_value = {key:m(value) for key,value in self.url_parameter_dict.items() if key != exclude_key} <NEW_LINE> return urllib.urlencode(encode_to_url_value) | 首先将字典的每一个值作成utf-8 | 625941f0baa26c4b54cb169d |
def shutdown(self): <NEW_LINE> <INDENT> logging.handlers = [] <NEW_LINE> logging.shutdown() | Shutdown logging. | 625941f0462c4b4f79d1dc53 |
def p_action_line(p): <NEW_LINE> <INDENT> if p[3] == 'accept': <NEW_LINE> <INDENT> p_info['current_rule'].action = Action(True) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p_info['current_rule'].action = Action(False) | action_line : ACTION COLON WORD | 625941f0a17c0f6771cbe5d3 |
def error_inputs(self, device, **kwargs): <NEW_LINE> <INDENT> return self.error_inputs_func(self, device, **kwargs) | Returns an iterable of ErrorInputs. | 625941f060cbc95b062c6ac8 |
@click.command(cls=LeanCommand) <NEW_LINE> @click.option("--user-id", "-u", type=str, help="QuantConnect user id") <NEW_LINE> @click.option("--api-token", "-t", type=str, help="QuantConnect API token") <NEW_LINE> def login(user_id: Optional[str], api_token: Optional[str]) -> None: <NEW_LINE> <INDENT> logger = container... | Log in with a QuantConnect account.
If user id or API token is not provided an interactive prompt will show.
Credentials are stored in ~/.lean/credentials and are removed upon running `lean logout`. | 625941f066673b3332b92615 |
def export_combineddata(): <NEW_LINE> <INDENT> maxdim = max(Constants.treatmentdims) <NEW_LINE> body = [] <NEW_LINE> session_fns, session_fns_d, group_fns, group_fns_d, participant_fns, participant_fns_d = get_headers_simple() <NEW_LINE> session_fns = ["id"] + get_field_names_for_csv(Session) <NEW_LINE> metadata_fns = ... | Getting ALL the fields in one place
This will not return all Asks (only latest)
This will not return response times
This will not return payment data
:return: csv headers and body for output | 625941f01f5feb6acb0c50cd |
def generate_greedy(texts, input_encoding_dict, model, max_input_length, max_output_length): <NEW_LINE> <INDENT> if not isinstance(texts, list): <NEW_LINE> <INDENT> texts = [texts] <NEW_LINE> <DEDENT> encoder_input = encode_sequences(input_encoding_dict, texts, max_input_length) <NEW_LINE> decoder_input = np.zeros(shap... | Main function for generating output(s) for given input(s)
Parameters:
texts (list/str): List of input strings or single input string.
input_encoding_dict (dict): Encoding dictionary generated from the input strings.
model (kerasl model): Loaded keras model.
max_input_length (int): Max length of input sequences. Al... | 625941f032920d7e50b28759 |
@app.route('/deflate') <NEW_LINE> @filters.deflate <NEW_LINE> def view_deflate_encoded_content(): <NEW_LINE> <INDENT> return jsonify(get_dict( 'origin', 'headers', method=request.method, deflated=True)) | Returns Deflate-Encoded Data. | 625941f050485f2cf553d320 |
def post(self, request): <NEW_LINE> <INDENT> success = False <NEW_LINE> msg = "Unknown Error" <NEW_LINE> account = None <NEW_LINE> try: <NEW_LINE> <INDENT> email = request.data['email'] <NEW_LINE> try: <NEW_LINE> <INDENT> account = Account.objects.get(email=email) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> msg = "... | Request for Password Reset must be POST. | 625941f0be8e80087fb211be |
def mkdir(self): <NEW_LINE> <INDENT> import os <NEW_LINE> cur=Path('./') <NEW_LINE> for intdir in self.split(): <NEW_LINE> <INDENT> cur+=Path(intdir) <NEW_LINE> if not os.path.isdir(cur): <NEW_LINE> <INDENT> os.mkdir(cur) | Make directories in path that don't exist | 625941f044b2445a33932616 |
def create_token(email): <NEW_LINE> <INDENT> token_fields = ['id', 'email', 'name'] <NEW_LINE> user = User.get(email=email) <NEW_LINE> user_roles = [role.title for role in user.roles] <NEW_LINE> user = user.serialize() <NEW_LINE> data = {field: user[field] for field in token_fields} <NEW_LINE> data.update({'roles': use... | Create access token and return it. | 625941f0283ffb24f3c55e80 |
def button_save_wpts_callback(): <NEW_LINE> <INDENT> xmlfile = entry.get() <NEW_LINE> if xmlfile.rsplit(".")[-1] != "gpx": <NEW_LINE> <INDENT> statusText.set("Filename must have a .gpx extension!") <NEW_LINE> message.configure(fg="red") <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> head, tail = os.pat... | what to do when the "Save Modified WPTs" button is pressed | 625941f0091ae356686674d9 |
def get_captcha_result(model_path, filename): <NEW_LINE> <INDENT> image = np.asarray(Image.open(filename).convert('L')) <NEW_LINE> image = (image > 135) * 255 <NEW_LINE> letters = [image[:, 6:18].reshape(20 * 12), image[:, 19:31].reshape(20 * 12), image[:, 33:45].reshape(20 * 12), image[:, 45:57].reshape(20 * 12)] <NEW... | 验证码解析
:param model_path: 之前训练的模型位置
:param filename: 需要解析的验证码全路径
:return: 解析结果 | 625941f073bcbd0ca4b2c5fa |
def add(self, directory, network, params): <NEW_LINE> <INDENT> l = self._slurp() <NEW_LINE> for i in l: <NEW_LINE> <INDENT> if i['dir'] == directory: <NEW_LINE> <INDENT> logger.info('Directory already exported, to export with different params please first remove') <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> f = open... | Add entry to /etc/exports
@param directory: directory to export
@param network: network range allowed
@param params: params for export (eg, 'ro,async,no_root_squash,no_subtree_check') | 625941f0e76e3b2f99f3ad86 |
def send_thank_you_menu(database): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> name = input("Enter a Full Name ('list' to show list of donors, 'q' to quit): ") <NEW_LINE> if name == 'q' or name == '': <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> elif name == 'list': <NEW_LINE> <INDENT> cursor = database.find(... | Prompts for donor name, if not present, adds user to data. Prompts for donation
and adds it to donor's data. Prints a 'Thank You' email populated with the donor's data.
:return: None | 625941f04d74a7450ccd474a |
def __init__(self, config): <NEW_LINE> <INDENT> self.host = config[CONF_HOST] <NEW_LINE> self.username = config[CONF_USERNAME] <NEW_LINE> self.password = config.get(CONF_PASSWORD, '') <NEW_LINE> self.ssh_key = config.get('ssh_key', config.get('pub_key', '')) <NEW_LINE> self.protocol = config[CONF_PROTOCOL] <NEW_LINE> s... | Initialize the scanner. | 625941f08e71fb1e9831dd2b |
def extract(archive, dest_path='./out', verbose=False): <NEW_LINE> <INDENT> if verbose: <NEW_LINE> <INDENT> print('Extracting files from archive "{}"'.format(archive)) <NEW_LINE> <DEDENT> if not os.path.exists(dest_path): <NEW_LINE> <INDENT> os.makedirs(dest_path) <NEW_LINE> <DEDENT> with open(archive, 'rb') as in_file... | Extract files from archive | 625941f076d4e153a657f0b7 |
def untag( self, tag ): <NEW_LINE> <INDENT> req = { 'tag' : str( tag ) } <NEW_LINE> return self._manager._apiCall( '%s/tags' % self.sid, DELETE, req ) | Remove a Tag from the Sensor.
Args:
tag (str): Tag to remove.
Returns:
the REST API response (JSON). | 625941f007f4c71912b11a09 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.