code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def _error(self, *args): <NEW_LINE> <INDENT> print(self._file_path + ': ' + self._ERROR_TAG, *args, file=sys.stderr)
Emit an error to stderr.
625941e915fb5d323cde0fc8
def inquire_index_name(model, column, title, parent_widget): <NEW_LINE> <INDENT> index_name = model.headerData(column, Qt.Horizontal) <NEW_LINE> dialog_flags = Qt.Dialog | Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowCloseButtonHint <NEW_LINE> new_name, ok = QInputDialog.getText(parent_widget, title, "Index n...
Asks for indexed parameter's index name and updates model accordingly. Args: model (IndexedValueTableModel or ArrayModel): a model with header that contains index names column (int): column index title (str): input dialog's title parent_widget (QWidget): dialog's parent widget
625941e98c0ade5d55d3ee70
def generate_summary(data: dict) -> ElectionSummary: <NEW_LINE> <INDENT> total_vote_count = reduce((lambda x, y: x + y), data.values()) <NEW_LINE> sorted_candidates = [k for k in sorted(data, key=data.get, reverse=True)] <NEW_LINE> candidate_stats = [] <NEW_LINE> for candidate in sorted_candidates: <NEW_LINE> <INDENT> ...
Generates the election summary given the total vote count for each candidate :param dict data: Dictionary for candidate-vote count :return: Election summary that contains total vote count, winner name and statistics for each candidate :rtype: ElectionSummary
625941e921a7993f00bc81aa
def __repr__(self) -> str: <NEW_LINE> <INDENT> return "<LDAPURL %s>" % str(self)
The LDAPURL representation.
625941e963d6d428bbe449a2
def emit(self, level, message, prefix=None, color=None): <NEW_LINE> <INDENT> self.level = update_level() <NEW_LINE> if color is None: <NEW_LINE> <INDENT> color = level <NEW_LINE> <DEDENT> if prefix is not None: <NEW_LINE> <INDENT> prefix = self.addColor(color, "%s " % (prefix)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
emit is the main function to print the message optionally with a prefix :param level: the level of the message :param message: the message to print :param prefix: a prefix for the message
625941e9377c676e91272658
def prune_vocabulary(training_counts, target_data, min_counts): <NEW_LINE> <INDENT> vocab = [] <NEW_LINE> new_target_data = copy.deepcopy(target_data) <NEW_LINE> for key, value in enumerate(target_data): <NEW_LINE> <INDENT> for i in value: <NEW_LINE> <INDENT> if training_counts[i] < min_counts: <NEW_LINE> <INDENT> del ...
prune target_data to only words that appear at least min_counts times in training_counts :param training_counts: aggregated Counter for training data :param target_data: list of Counters containing dev bow's :returns: new list of Counters, with pruned vocabulary :returns: list of words in pruned vocabulary :rtype: lis...
625941e9f9cc0f698b140aa9
@bp.route('/<id>') <NEW_LINE> def details(id): <NEW_LINE> <INDENT> response = requests.get(API_LINK + id, params={'api_key': API_KEY}) <NEW_LINE> return render_template('details.html', details=response.json())
Blueprint for the movie details page
625941e95fcc89381b1e1b74
def test_invalid_unique_identifier(self): <NEW_LINE> <INDENT> kwargs = {'unique_identifier': 0} <NEW_LINE> self.assertRaisesRegex( TypeError, "Unique identifier must be a string.", payloads.ObtainLeaseRequestPayload, **kwargs ) <NEW_LINE> payload = payloads.ObtainLeaseRequestPayload() <NEW_LINE> args = (payload, 'uniqu...
Test that a TypeError is raised when an invalid value is used to set the unique identifier of an ObtainLease request payload.
625941e9d6c5a10208144500
def build_image(self): <NEW_LINE> <INDENT> params = dict( path=self.build_path, tag=self.name, rm=self.rm, nocache=self.nocache, timeout=self.http_timeout, pull=self.pull, forcerm=self.rm, dockerfile=self.dockerfile, decode=True, ) <NEW_LINE> if self.client.docker_py_version < LooseVersion('3.0.0'): <NEW_LINE> <INDENT>...
Build an image :return: image dict
625941e99f2886367277ad3b
def load_cifar10_data(filepath,filename,num_files,num_images): <NEW_LINE> <INDENT> IMG_SIZE = 32 <NEW_LINE> CHANNELS = 3 <NEW_LINE> NUM_CLASSES = 10 <NEW_LINE> IMG_PER_FILE = 10000 <NEW_LINE> offset = (num_images%IMG_PER_FILE != 0) <NEW_LINE> num_files_load = num_images//IMG_PER_FILE +offset <NEW_LINE> images = np.zero...
Loads the cifar-10 training data and labels and val data and labels
625941e9e64d504609d74cf2
def testManySegfault(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results = self._execute("test_manysegfault.sf.xml") <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> assert isinstance(e, sciflo.grid.executor.ScifloExecutorError) <NEW_LINE> assert SEGFAULT_RE.search(str(e)) <NEW_LINE> return <NEW_L...
Test execution of test_manysegfault.sf.xml.
625941e9adb09d7d5db6cc3e
def scp(from_path, to_path, create_if_missing=False): <NEW_LINE> <INDENT> command = 'scp -o StrictHostKeychecking=no "%s" "%s"' % (from_path, to_path) <NEW_LINE> log('Command: \'%s\'' % command) <NEW_LINE> pipe = subprocess.Popen( command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=Tru...
Call out to the command line scp. Note: We don't do any authentication. You must have a ssh key set up. IMPORTANT: If you try to write to a file you don't have write permissions on you will not get an error!
625941e992d797404e30463e
def glFogiv(*argv): <NEW_LINE> <INDENT> pass
no string
625941e90c0af96317bb8699
def set_epoch(epoch): <NEW_LINE> <INDENT> global _epoch <NEW_LINE> if _epoch is not None: <NEW_LINE> <INDENT> raise RuntimeError('set_epoch must be called before dates plotted.') <NEW_LINE> <DEDENT> _epoch = epoch
Set the epoch (origin for dates) for datetime calculations. The default epoch is :rc:`dates.epoch` (by default 1970-01-01T00:00). If microsecond accuracy is desired, the date being plotted needs to be within approximately 70 years of the epoch. Matplotlib internally represents dates as days since the epoch, so floati...
625941e9cb5e8a47e48b7f55
def IMPORT_FROM(self,pc,namei): <NEW_LINE> <INDENT> raise NotImplementedError
Loads the attribute co_names[namei] from the module found in TOS. The resulting object is pushed onto the stack, to be subsequently stored by a STORE_FAST instruction.
625941e97cff6e4e81117e37
def registerPlayer(name): <NEW_LINE> <INDENT> db = connect() <NEW_LINE> c = db.cursor() <NEW_LINE> c.execute("insert into players(name) values(%s)", (name,)) <NEW_LINE> db.commit() <NEW_LINE> c.execute("select * from players where name = %s", (name,)) <NEW_LINE> result = c.fetchall() <NEW_LINE> this_id = result[(len(re...
Adds a player to the tournament database. Args: name: the player's full name (need not be unique).
625941e9287bf620b61d3f12
def create_filter_from_args(self, args: dict) -> Filter: <NEW_LINE> <INDENT> keys = set(args.keys()) <NEW_LINE> filter_args = {} <NEW_LINE> if 'search' in keys: <NEW_LINE> <INDENT> filter_args.update({"text_filter": args.get('search')}) <NEW_LINE> <DEDENT> if 'category' in keys: <NEW_LINE> <INDENT> if not args.get('cat...
Takes the arguments of a Flask request, and returns a corresponding Filter.
625941e9090684286d50f19f
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, LoanStatisticModel): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941e976d4e153a657efe4
@app.route('/tokenReset', methods=['POST']) <NEW_LINE> def tokenReset(): <NEW_LINE> <INDENT> logger.debug('token reset requested') <NEW_LINE> if not check_admin(): <NEW_LINE> <INDENT> PasswdApiError('Not Authorized. This route only for admins') <NEW_LINE> <DEDENT> users = request.form.getlist('user') <NEW_LINE> logger....
/tokenReset route: POST POST - form body users (list of str) req - list of users to kick off email reset for service (str) req - slack | email
625941e9460517430c39462a
def build_argparser(): <NEW_LINE> <INDENT> parser = ArgumentParser() <NEW_LINE> parser.add_argument("-f", "--face_detection_model", required=True, type=str, help="Path to .xml file of Face Detection model.") <NEW_LINE> parser.add_argument("-fl", "--facial_landmarks_model", required=True, type=str, help="Path to .xml fi...
Parse command line arguments. :return: command line arguments
625941e9187af65679ca55d2
def load_series(self, **kwargs): <NEW_LINE> <INDENT> physical_quantity = kwargs['physical_quantity'] <NEW_LINE> generator = self.load(**kwargs) <NEW_LINE> for chunk in generator: <NEW_LINE> <INDENT> if chunk.empty: <NEW_LINE> <INDENT> yield chunk <NEW_LINE> continue <NEW_LINE> <DEDENT> chunk_to_yield = chunk[physical_q...
Parameters ---------- ac_type : str physical_quantity : str We sum across ac_types of this physical quantity. **kwargs : passed through to load(). Returns ------- generator of pd.Series. If a single ac_type is found for the physical_quantity then the series.name will be a normal tuple. If more than 1 ac_type is ...
625941e93cc13d1c6d3c782a
def reLoginBaseapp( ): <NEW_LINE> <INDENT> pass
功能说明: 请求重登录到KBEngine服务端(通常在掉线之后希望更及时的连接到服务端并继续控制服务端角色时使用)。 注意:如果插件与UI层使用事件交互模式,在UI层不要直接调用,请触发一个"reLoginBaseapp"事件给插件,事件附带数据为空。
625941e9be383301e01b592e
def GetStatusOfVideo(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!')
Gets the status of an uploaded video
625941e9435de62698dfe0ff
def create_app(config_mapping=None): <NEW_LINE> <INDENT> logging.basicConfig(level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT, force=True) <NEW_LINE> app = Flask(__name__) <NEW_LINE> app.config.from_object("reana_server.config") <NEW_LINE> if config_mapping: <NEW_LINE> <INDENT> app.config.from_mapping(config_mapping) <NE...
REANA Server application factory.
625941e9236d856c2ad44c93
def test_future_form(self): <NEW_LINE> <INDENT> create_form(form_id="future01", days=30) <NEW_LINE> response = self.client.get(reverse('loaders:index')) <NEW_LINE> self.assertContains(response, "No forms are available.") <NEW_LINE> self.assertQuerysetEqual(response.context['latest_commission_form_list'], [])
Forms with a pub_date in the future aren't displayed on the index page.
625941e924f1403a92601014
def has_instruction_at(self, address): <NEW_LINE> <INDENT> return address in self.instructions
Query whether an instruction at the given address exists.
625941e955399d3f05588b69
def reset(self, nwalkers, ndim): <NEW_LINE> <INDENT> self.nwalkers = int(nwalkers) <NEW_LINE> self.ndim = int(ndim) <NEW_LINE> self.iteration = 0 <NEW_LINE> self.accepted = np.zeros(self.nwalkers, dtype=self.dtype) <NEW_LINE> self.chain = np.empty((0, self.nwalkers, self.ndim), dtype=self.dtype) <NEW_LINE> self.log_pro...
Clear the state of the chain and empty the backend Args: nwakers (int): The size of the ensemble ndim (int): The number of dimensions
625941e91d351010ab855fcd
@app.task <NEW_LINE> def cleanup_unused_media(): <NEW_LINE> <INDENT> management.call_command("cleanup_unused_media", "--noinput")
Очищает неисползуемые файлы
625941e982261d6c526ab959
@api_view(["POST"]) <NEW_LINE> @permission_classes((AllowAny, )) <NEW_LINE> def reset_passwd(request): <NEW_LINE> <INDENT> data = request.DATA.copy() <NEW_LINE> phone = data.get('phone', None) <NEW_LINE> captcha = data.get('captcha', None) <NEW_LINE> new_password1 = data.get('new_password1', None) <NEW_LINE> new_passwo...
根据用户输入重置密码,其中需要带上用户手机号与验证码
625941e9004d5f362079a7e2
def bash_cmd(self, cmd): <NEW_LINE> <INDENT> return "bash --login -c \"{cmd}\"".format(cmd=cmd)
docker exec commands must be wrapped in bash -c or they fail due to not being run from the shell
625941e963b5f9789fde7598
def add(self, sparse_matrix): <NEW_LINE> <INDENT> for k, v in sparse_matrix.columns.iteritems(): <NEW_LINE> <INDENT> self.columns[k].extend(v) <NEW_LINE> <DEDENT> for k, v in sparse_matrix.rows.iteritems(): <NEW_LINE> <INDENT> self.rows[k].extend(v) <NEW_LINE> <DEDENT> for k, v in sparse_matrix.rows_batch.iteritems(): ...
Performs in-place addition of ``sparse_matrix``. Parameters ---------- sparse_matrix : :class:`~quagga.matrix.SparseMatrix`
625941e9f7d966606f6aa4bc
def __init__(self, win): <NEW_LINE> <INDENT> base = Circle(Point(0,0), 3) <NEW_LINE> base.setFill("red") <NEW_LINE> base.setOutline("red") <NEW_LINE> base.draw(win) <NEW_LINE> self.win = win <NEW_LINE> self.angle = radians(45.0) <NEW_LINE> self.vel = 40.0 <NEW_LINE> self.magnetic = Circle(Point(100,100), 30) <NEW_LINE>...
Create inital launcher with angle 45 degrees and velocity 40 win is the GraphWin to draw the launcher in.
625941e916aa5153ce36292a
def build_metamodel(self, id_generator=None): <NEW_LINE> <INDENT> m = model.MetaModel(id_generator) <NEW_LINE> self.populate(m) <NEW_LINE> return m
Build and return a meta model from previously parsed input.
625941e91f5feb6acb0c4ffb
def calc(string): <NEW_LINE> <INDENT> result = eval(string) <NEW_LINE> print(string, '=', result) <NEW_LINE> return result
calculator function; for convenience
625941e90fa83653e465746a
@njit <NEW_LINE> def is_csr_indexing(rows: np.ndarray, cols: np.ndarray) -> bool: <NEW_LINE> <INDENT> return rows.ndim == cols.ndim == 1 and rows.size > 0 and rows[ 0] >= 0 and np.all(rows[:-1] <= rows[1:]) and rows[-1] <= cols.size
Check whether a set of arrays satisfies the requirements for CSR indexing. The requirements for CSR (compressed sparse row) indexing are: * :code:`rows.ndim == 1` * :code:`cols.ndim == 1` * :code:`rows.size > 0` * :code:`rows[0] >= 0` * :code:`rows[:-1] <= rows[1:]` * :code:`rows[-1] <= len(cols)` Args: rows (nu...
625941e9d8ef3951e32439f0
def showData(): <NEW_LINE> <INDENT> global SDS_P10, SDS_P25, temp, humi, press, client, s <NEW_LINE> print('SDS P10:',SDS_P10) <NEW_LINE> print('SDS_P25:',SDS_P25) <NEW_LINE> print('Temperatur: ',temp) <NEW_LINE> print('Feuchte: ',humi) <NEW_LINE> print('Druck (local): ', press) <NEW_LINE> if use_ssd1306: <NEW_LINE> <I...
print data to console and to display
625941e9287bf620b61d3f13
def main(): <NEW_LINE> <INDENT> pygame.init() <NEW_LINE> screen = pygame.display.set_mode(size) <NEW_LINE> clock = pygame.time.Clock() <NEW_LINE> screen.fill(colors['WHITE']) <NEW_LINE> pygame.draw.rect(screen, colors['BLACK'], [(size[0] - botX) / 2, (size[1] - botY) / 2, botX, botY]) <NEW_LINE> pygame.display.update()...
Create Arena for SLAM_Lidar.py, SLAM_Lidar_BW.py Drag to create obstacles Exit the screen to save the image Image saved as 'map.jpg' in the current directory
625941e967a9b606de4a8369
def custom_score_2(game, player): <NEW_LINE> <INDENT> if game.is_loser(player): <NEW_LINE> <INDENT> return float('-inf') <NEW_LINE> <DEDENT> if game.is_winner(player): <NEW_LINE> <INDENT> return float('inf') <NEW_LINE> <DEDENT> own_moves = len(game.get_legal_moves(player)) <NEW_LINE> opp_moves = len(game.get_legal_move...
Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` encodi...
625941e9be7bc26dc91cdaa9
def predictOne(self, samples: Signal) -> Signal: <NEW_LINE> <INDENT> max = np.max(samples.values) <NEW_LINE> min = np.min(samples.values) <NEW_LINE> result = copy.copy(samples) <NEW_LINE> result.values = ((samples.values - min) / (max - min)).tolist() <NEW_LINE> return (result, )
Normalize the signal's values
625941e9091ae35668667408
def initialize_capture(device_cfg, capture_cfg): <NEW_LINE> <INDENT> ot = device.OpenTitan(device_cfg["fpga_bitstream"], device_cfg["fw_bin"], device_cfg["pll_frequency"], device_cfg["baudrate"], capture_cfg["scope_gain"], capture_cfg["num_samples"], capture_cfg["output_len_bytes"]) <NEW_LINE> print(f'Scope setup with ...
Initialize capture.
625941e926068e7796caf199
@view_config(route_name="tag_bmarks", renderer="/bmark/recent.mako") <NEW_LINE> @view_config(route_name="user_tag_bmarks", renderer="/bmark/recent.mako") <NEW_LINE> def bmark_list(request): <NEW_LINE> <INDENT> return bmarks.recent(request)
Display the list of bookmarks for this tag
625941e9a8ecb033257d357d
def test_svd_argfail_basis_tensors(self): <NEW_LINE> <INDENT> align_tensor.init(align_id='a', params=(0.0, 0.0, 0.0, 0.0, 0.0)) <NEW_LINE> for data in DATA_TYPES: <NEW_LINE> <INDENT> if data[0] == 'None' or data[0] == 'str list': <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> self.assertRaises(RelaxNoneListStrError, ...
The tensors arg unit test of the align_tensor.svd() user function.
625941e9956e5f7376d7131e
def process_rec(self, record): <NEW_LINE> <INDENT> msg = self.format(record) <NEW_LINE> if record.levelno == logging.INFO and msg and msg[0] == "{": <NEW_LINE> <INDENT> self.aggregate_stats(msg) <NEW_LINE> if time.time() - self.last_stat_flush >= self.stat_flush_period: <NEW_LINE> <INDENT> self.flush_stats(_job_name) <...
Aggregate stats if needed, and send to logdb.
625941e971ff763f4b549b46
def Send(self): <NEW_LINE> <INDENT> if self.frm_top_btn_change["text"] == "USB": <NEW_LINE> <INDENT> self.serial_send() <NEW_LINE> <DEDENT> elif self.frm_top_btn_change["text"] == "Serial": <NEW_LINE> <INDENT> self.usb_send()
发送数据
625941e95510c4643540f88a
def make_discriminator_model(input_tensor=None, input_shape=(28, 28, 1)): <NEW_LINE> <INDENT> if input_tensor is None: <NEW_LINE> <INDENT> img_input = layers.Input(shape=input_shape) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not backend.is_keras_tensor(input_tensor): <NEW_LINE> <INDENT> img_input = layers.Input(...
Returns: tf.keras.Model
625941e9de87d2750b86024a
def nmap_host_all(host): <NEW_LINE> <INDENT> nm = nmap.PortScanner() <NEW_LINE> nm.scan(host, '0-65535') <NEW_LINE> if nm[host].state() == 'up': <NEW_LINE> <INDENT> return nm[host]['tcp']
全端口扫描
625941e95fc7496912cc3e30
def __maskScatterChanged(self, event): <NEW_LINE> <INDENT> if (event is ItemChangedType.VISUALIZATION_MODE and self._mask_scatter is not None): <NEW_LINE> <INDENT> self._mask_scatter.setVisualization(Scatter.Visualization.POINTS)
Handles update of mask scatter
625941e9dc8b845886cb59e9
def clear(self): <NEW_LINE> <INDENT> self.ui.out_label.setText("0")
Обнуление label
625941e9d6c5a10208144501
def stylize_frame(d): <NEW_LINE> <INDENT> d.drop(["donor contact_name", "donor email", "recipient contact_name", "recipient email", "recipient phone"], axis=1, inplace=True) <NEW_LINE> d.columns = ["Donation Quantity", "PPE Type", "Recipient Facility Name", "Recipient Address"] <NEW_LINE> d = d[["Recipient Facility Nam...
formats the dataframe subsection and converts it to html so that it can be pasted into the email as a table parameters: d (dataframe): subsection of match sheet dataframe, df, that matches donor email returns: d converted to an html table
625941e9cdde0d52a9e534e9
def __init__(self, fieldRef=None, resourceFieldRef=None, configMapKeyRef=None, secretKeyRef=None): <NEW_LINE> <INDENT> self.swagger_types = { 'fieldRef': 'V1ObjectFieldSelector', 'resourceFieldRef': 'V1ResourceFieldSelector', 'configMapKeyRef': 'V1ConfigMapKeySelector', 'secretKeyRef': 'V1SecretKeySelector' } <NEW_LINE...
V1EnvVarSource - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
625941e98da39b475bd6542c
def add_metadata_from_stoqs(self): <NEW_LINE> <INDENT> pass
Look for data matching samples from biomFile in the specified STOQS database and add to the biom-format file.
625941e90a50d4780f667349
def login_for_modal(request): <NEW_LINE> <INDENT> login_form = LoginModalForm(request.POST) <NEW_LINE> if login_form.is_valid(): <NEW_LINE> <INDENT> user = login_form.cleaned_data['user'] <NEW_LINE> auth.login(request, user) <NEW_LINE> data = {'status': 'SUCCESS'} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = {'...
模态框 :param request: 请求对象 :return: json数据
625941e9925a0f43d254a32e
def delete (self,request,lab_pk,pk): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> (lab,perm) = get_valid_lab(lab_pk,user,'laboratory.delete_laboratoryroom') <NEW_LINE> if perm: <NEW_LINE> <INDENT> lab_room = get_object_room(lab,pk) <NEW_LINE> if lab_room: <NEW_LINE> <INDENT> lab_room.delete() <NEW_LINE> return Re...
Delete: Use this to delete your laboratoryrooms build your delete with your user token valid Header: [{"key":"Authorization","value":"Token a98fa58aacb028eb6aa83cd3ab8a827d919db399"}, {"key":"Content-Type","value":"application/json" }]
625941e9bde94217f368329f
def dispatch_request(self, **kwargs): <NEW_LINE> <INDENT> if request.method in self.methods: <NEW_LINE> <INDENT> new_kwargs = self.resolve_kwargs(**kwargs) <NEW_LINE> return getattr(self, request.method.lower())(**new_kwargs) <NEW_LINE> <DEDENT> abort(400)
If this method is supported, run its function. Otherwise abort 400.
625941e9596a897236089f6d
def importCableData(db, filepath): <NEW_LINE> <INDENT> import importCSVData as importCSV <NEW_LINE> import mongoengine as me <NEW_LINE> me.connect(db) <NEW_LINE> generator = importCSV.import_data_generator(filepath) <NEW_LINE> try: <NEW_LINE> <INDENT> for each in generator: <NEW_LINE> <INDENT> if isinstance(each, dict)...
Import cable data and add to the database
625941e9711fe17d82542813
def process_peak(self, frame_idx, level): <NEW_LINE> <INDENT> pass
This function is called for the highest sample detected during a bit level is at given frame_idx. Note: this function is not synchrone with process_sample() calls, eg. frame_idx might be in the past.
625941e9d10714528d60019b
def get_lt_status(self) -> 'lt.torrent_status': <NEW_LINE> <INDENT> self.status = self.handle.status() <NEW_LINE> return self.status
Get the torrent status fresh, not from cache. This should be used when a guaranteed fresh status is needed rather than `torrent.handle.status()` because it will update the cache as well.
625941e950812a4eaa59c7cf
def get_notifications(self, request): <NEW_LINE> <INDENT> if not ShuupSettings.get_setting("SHUUP_ENABLE_MULTIPLE_SHOPS"): <NEW_LINE> <INDENT> from shuup.admin.shop_provider import get_shop <NEW_LINE> shop = get_shop(request) <NEW_LINE> if sample_manager.has_installed_samples(shop): <NEW_LINE> <INDENT> messages.warning...
Injects a message to the user and also a notification
625941e9bd1bec0571d90ae1
def short(o) -> str: <NEW_LINE> <INDENT> if isinstance(o, list): <NEW_LINE> <INDENT> return f"[{', '.join(short(x) for x in o)}]" <NEW_LINE> <DEDENT> elif isinstance(o, tuple): <NEW_LINE> <INDENT> return f"({', '.join(short(x) for x in o)})" <NEW_LINE> <DEDENT> elif isinstance(o, set): <NEW_LINE> <INDENT> return f"{{{'...
Returns a short string representation of o. If o has a .short() method define, we call it and return its result. Otherwise we return str(o).
625941e94428ac0f6e5baca9
def plane_fit(X, Y, Z): <NEW_LINE> <INDENT> A = np.c_[X, Y, np.ones(len(Z))] <NEW_LINE> C, _, _, _ = scipy.linalg.lstsq(A, Z) <NEW_LINE> return C
Fit a plane to data. Parameters ---------- X : np.ndarray Y : np.ndarray Z : np.ndarray Returns ------- C : np.ndarray Coefficients for plane fit
625941e9627d3e7fe0d69304
def __init__(self, offsets): <NEW_LINE> <INDENT> self.offsets = array(offsets) <NEW_LINE> self._shape() <NEW_LINE> self.s = None
Constructor for the list of offsets in N-D (neighbours) offsets must be a m x N matrix, where m is the number of offsets (neighbours) and N is the dimensions of the image
625941e94c3428357757c7d8
def loss(y_true, y_pred): <NEW_LINE> <INDENT> y_pred /= kerasbackend.sum(y_pred, axis=-1, keepdims=True) <NEW_LINE> y_pred = kerasbackend.clip(y_pred, kerasbackend.epsilon(), 1 - kerasbackend.epsilon()) <NEW_LINE> loss = y_true * kerasbackend.log(y_pred) * weights <NEW_LINE> loss = -kerasbackend.sum(loss, -1) <NEW_LINE...
Calculate categorical_crossentropy including the weights
625941e991af0d3eaac9bed0
def sha1(message): <NEW_LINE> <INDENT> h0 = 0x67452301 <NEW_LINE> h1 = 0xEFCDAB89 <NEW_LINE> h2 = 0x98BADCFE <NEW_LINE> h3 = 0x10325476 <NEW_LINE> h4 = 0xC3D2E1F0 <NEW_LINE> original_byte_len = len(message) <NEW_LINE> original_bit_len = original_byte_len * 8 <NEW_LINE> message += b'\x80' <NEW_LINE> message += b'\x00' *...
SHA-1 Hashing Function A custom SHA-1 hashing function implemented entirely in Python. Arguments: message: The input message string to hash. Returns: A hex SHA-1 digest of the input message.
625941e9d164cc6175783202
def __init__(self, w0: np.ndarray, lambda_: float, x_shape: int, s0: float = s0_default, p: float = p_default): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.eta = lambda k: lambda_ * (s0 / (s0 + k)) ** p <NEW_LINE> self.w = np.copy(w0) <NEW_LINE> self.v = np.zeros((x_shape, w0.shape[0])) <NEW_LINE> self.d = 0
:param w0: weight initialization :param lambda_: learning rate parameter (float) :param s0: learning rate parameter (float) :param p: learning rate parameter (float)
625941e9bd1bec0571d90ae2
def totalFruit(self, tree): <NEW_LINE> <INDENT> i = 0 <NEW_LINE> while i < len(tree) - 1 and tree[i] == tree[i + 1]: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> <DEDENT> if i >= len(tree) - 1: <NEW_LINE> <INDENT> return len(tree) <NEW_LINE> <DEDENT> pre, cur = tree[i], tree[i + 1] <NEW_LINE> ret = i + 2 <NEW_LINE> start = 0...
:type tree: List[int] :rtype: int
625941e985dfad0860c3b30f
def __init__(self, replicas=None, local_vars_configuration=None): <NEW_LINE> <INDENT> if local_vars_configuration is None: <NEW_LINE> <INDENT> local_vars_configuration = Configuration() <NEW_LINE> <DEDENT> self.local_vars_configuration = local_vars_configuration <NEW_LINE> self._replicas = None <NEW_LINE> self.discrimi...
AppsV1beta1ScaleSpec - a model defined in OpenAPI
625941e992d797404e30463f
def get_Reportes2_id(request): <NEW_LINE> <INDENT> egreso = Alquiler.objects.all() <NEW_LINE> egreso_list = serializers.serialize('json', egreso) <NEW_LINE> return JsonResponse(egreso_list, safe=False)
Funcion para obtener id del egreso
625941e9a05bb46b383eccd0
def update_cdp_table(host, neighbor, local_port, remote_port): <NEW_LINE> <INDENT> info = Cdp_Main(unique_id=f'{host}|{local_port}', id=host, neighbor=neighbor, local_port=local_port, remote_port=remote_port, query_time=time.ctime()) <NEW_LINE> session.add(info) <NEW_LINE> db_commit()
Insert cdp row in to table
625941e98e05c05ec3eea82c
def setUp(self): <NEW_LINE> <INDENT> self.status = ToxicPoison() <NEW_LINE> self.pkmn = BuildPokemonBattleWrapper()
Builds the ToxicPoison status
625941e9be7bc26dc91cdaaa
def push(self): <NEW_LINE> <INDENT> src_dir = os.path.join(self.local_dir, '') <NEW_LINE> logging.info("Push from %s to %s", src_dir, self.remote_host_dir) <NEW_LINE> self.rsync(src_dir, self.remote_host_dir, ['--delete'])
Push local files to remote directory
625941e9dc8b845886cb59ea
def _drawNode(self, canvas, node): <NEW_LINE> <INDENT> return TextBox(self, node.getLabel(), 0, 0, bgColor="#99DAE8", textColor='black')
Default implementation to draw nodes as textboxes.
625941e9796e427e537b0a7d
def __init__(self, identification=None, services=None): <NEW_LINE> <INDENT> self._identification = None <NEW_LINE> self._services = None <NEW_LINE> self.discriminator = None <NEW_LINE> self.identification = identification <NEW_LINE> self.services = services
PhoneChannel - a model defined in Swagger
625941e98da39b475bd6542d
def find_accuracy(model_predictions, conf_thresh, actual_labels=None, num_mon_sites=None, num_mon_inst_test=None, num_unmon_sites_test=None, num_unmon_sites=None): <NEW_LINE> <INDENT> actual_labels = np.argmax(actual_labels, axis=1) <NEW_LINE> thresh_model_labels = np.zeros(len(model_predictions)) <NEW_LINE> for inst_n...
Compute TPR and FPR based on softmax output predictions.
625941e96e29344779a62ac3
def test_simple_equation(self): <NEW_LINE> <INDENT> @equation.EquationSet.from_dict_def <NEW_LINE> def equationset(x): <NEW_LINE> <INDENT> return dict(x=x) <NEW_LINE> <DEDENT> x = expression.Variable("x") <NEW_LINE> expected_set = equation.EquationSet([equation.Equation(x, x)]) <NEW_LINE> self.assertEqual(equationset, ...
Test creating a simple equation
625941e9b545ff76a89142c8
def __init__(self): <NEW_LINE> <INDENT> self.head = None <NEW_LINE> self.tail = None
Initialize the linked list.
625941e98a43f66fc4b54513
def test_ellipse_plot_2(self, image_path): <NEW_LINE> <INDENT> fig = Ellipse(20, 10, 90).plot(color='r') <NEW_LINE> fig = Ellipse(20, 10, 45).plot(fig=fig, color='b') <NEW_LINE> fig = Ellipse(20, 10, 0, center=(10, 10)).plot(fig=fig, color='g') <NEW_LINE> _ = Ellipse(20, 10, -45).plot(fig=fig, outfile=image_path)
Test Ellipse.plot() with multi-ellipses
625941e973bcbd0ca4b2c529
def custom_score_3(game, player): <NEW_LINE> <INDENT> if game.is_loser(player): <NEW_LINE> <INDENT> return float("-inf") <NEW_LINE> <DEDENT> if game.is_winner(player): <NEW_LINE> <INDENT> return float("inf") <NEW_LINE> <DEDENT> own_moves = game.get_legal_moves(player) <NEW_LINE> opp_moves = game.get_legal_moves(game.ge...
Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` enco...
625941e94e696a04525c9901
def test_multiple_per_file(self): <NEW_LINE> <INDENT> code, out, _ = run_vhdeps('vsim', '-i', DIR+'/complex/multi-tc-per-file') <NEW_LINE> self.assertEqual(code, 0) <NEW_LINE> self.assertTrue('working!' in out) <NEW_LINE> self.assertTrue('PASSED work.foo_tc' in out) <NEW_LINE> self.assertTrue('PASSED work.bar_tc' in ...
Test running vsim on a file with multiple test cases
625941e9dd821e528d63b658
def _validate_artifact_id(self, artifact_id): <NEW_LINE> <INDENT> artifact_prefix = _sha512("artifact".encode("utf-8"))[0:6] <NEW_LINE> address = _sha512(artifact_id.encode("utf-8"))[0:64] <NEW_LINE> address = artifact_prefix + address <NEW_LINE> return self._send_request("state/{}".format(address))
Validates if the artifact UUID exists in the ledger. Args: artifact_id (str): The uuid of the artifact Returns: type: str Data as string if UUID exist in the ledger. or type: None None object if UUID does not exist in the ledger.
625941e98c3a873295158874
def save_csv_s3(self, aws_key, aws_secret, bucket): <NEW_LINE> <INDENT> for DF in self.DFs: <NEW_LINE> <INDENT> self.__save_csv(DF.df, bucket, DF.title, aws_key, aws_secret) <NEW_LINE> <DEDENT> self.__save_csv(self.location.df, bucket, self.location.title, aws_key, aws_secret)
save to s3
625941e963d6d428bbe449a4
def get_build_with_project(self, bt_locator, build_locator, **kwargs): <NEW_LINE> <INDENT> return self.serve_build_with_project( bt_locator, build_locator, **kwargs)
:param async_req: bool :param str bt_locator: (required) :param str build_locator: (required) :param str fields: :return: Build
625941e9435de62698dfe100
def load_key(self, data): <NEW_LINE> <INDENT> return OpenSSL.crypto.load_privatekey(self.typ, data)
Load private key.
625941e99f2886367277ad3d
def update_global_time(self, global_time): <NEW_LINE> <INDENT> if global_time > self._global_time: <NEW_LINE> <INDENT> logger.debug("updating global time %d -> %d", self._global_time, global_time) <NEW_LINE> self._global_time = global_time <NEW_LINE> self._check_for_pruning()
Increase the local global time if the given GLOBAL_TIME is larger.
625941e9b7558d58953c53be
def get_services(self): <NEW_LINE> <INDENT> self.__load_System_class() <NEW_LINE> pid = self.get_pid() <NEW_LINE> return [d for d in System.get_active_services() if d.ProcessId == pid]
Retrieves the list of system services that are currently running in this process. @see: L{System.get_services} @rtype: list( L{win32.ServiceStatusProcessEntry} ) @return: List of service status descriptors.
625941e9e64d504609d74cf3
def resize_image(image, screen_size=(1920, 1080)): <NEW_LINE> <INDENT> width, height = screen_size <NEW_LINE> image_width, image_height = image.size <NEW_LINE> if image_width/image_height > 16/9: <NEW_LINE> <INDENT> image_height = (image_height * width) // image_width <NEW_LINE> image_width = width <NEW_LINE> <DEDENT> ...
Takes an image and new dimensions, and return the image resized accordingly. If one of the dimensions is None, it will be resized to keep current proportions
625941e9e76e3b2f99f3acb8
def depth_first(self, filter=None): <NEW_LINE> <INDENT> if filter is None or not callable(filter): <NEW_LINE> <INDENT> filter = lambda e: True <NEW_LINE> <DEDENT> elems = [] <NEW_LINE> if filter(self): <NEW_LINE> <INDENT> elems.append(self) <NEW_LINE> <DEDENT> for sub in self.sub: <NEW_LINE> <INDENT> if not isinstance(...
Returns a list of the nodes in the tree in depth-first order.
625941e9507cdc57c630719a
def process_response(self, req, resp, resource, req_succeeded): <NEW_LINE> <INDENT> session = req.context['session'] <NEW_LINE> if config.DB_AUTOCOMMIT: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> session.commit() <NEW_LINE> <DEDENT> except SQLAlchemyError as ex: <NEW_LINE> <INDENT> session.rollback() <NEW_LINE> <DEDE...
Post-processing of the response (after routing). Args: req: Request object. resp: Response object. resource: Resource object to which the request was routed. May be None if no route was found for the request. req_succeeded: True if no exceptions were raised while the framework p...
625941e95fc7496912cc3e31
def test_setting_xyz_on_las_data(): <NEW_LINE> <INDENT> las = laspy.read(simple_las) <NEW_LINE> new_las = laspy.create() <NEW_LINE> new_las.xyz = las.xyz <NEW_LINE> assert np.all(new_las.x == las.x) <NEW_LINE> assert np.all(new_las.X == las.X) <NEW_LINE> assert np.all(new_las.y == las.y) <NEW_LINE> assert np.all(new_la...
The goal of this test if to make sure that when setting the `xyz` attribute of a LasData object, the X,Y,Z version of the coordinates are properly set in the inner point record
625941e9e64d504609d74cf4
def dupn(self, count=2, idx=-1): <NEW_LINE> <INDENT> y = [] <NEW_LINE> for i in range(count): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> y.append(self._stk[idx - i]) <NEW_LINE> <DEDENT> except LookupError as err: <NEW_LINE> <INDENT> if idx == 1: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
( x y -- x y x y ) dup count items from an idx
625941e97b25080760e3990a
def __init__(self, facets, backend=None): <NEW_LINE> <INDENT> self._facets = facets <NEW_LINE> self._backend = backend
Initializer. :param facets: Dictionary of "facets" for the item. Ideally it should be a dictionary of string keys and simple types (e.g., int, float, string, dates) as values. Which can be serialized with msgpack. An important fe...
625941e992d797404e304640
def update_list(self, new_list): <NEW_LINE> <INDENT> self.list = new_list
Updates list of cards to repeat
625941e90c0af96317bb869b
def load_dependency(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> dependency_feature = self.dependency_box.currentText() <NEW_LINE> dependency = self.feature.dependencies[dependency_feature] <NEW_LINE> self.dependency_software.setText(dependency.software) <NEW_LINE> self.dependency_feature.setText(dependency.feat...
* Loads dependency
625941e921bff66bcd684e02
def _update_screen(self): <NEW_LINE> <INDENT> self.screen.blit(self.background, (0, 0)) <NEW_LINE> self.sprite.draw() <NEW_LINE> pygame.display.flip()
Update images on the screen, and flip to the new screen.
625941e963f4b57ef00015bf
def testMetadataFileDelete(self): <NEW_LINE> <INDENT> self.createTestSubmissionDataset() <NEW_LINE> resp = self.doHTTP_DELETE( resource="datasets/TestSubmission/manifest.rdf", expect_status=403, expect_reason="Forbidden") <NEW_LINE> (resp, rdfdata) = self.doHTTP_GET( resource="datasets/TestSubmission", expect_status=20...
Delete manifest in dataset - DELETE /silo_name/datasets/dataset_name/manifest.rdf
625941e9656771135c3ebd28
def transform_tables_representation(tbl_list): <NEW_LINE> <INDENT> for i, table in enumerate(tbl_list): <NEW_LINE> <INDENT> if '.' not in table: <NEW_LINE> <INDENT> tbl_list[i] = pg_quote_identifier('public.%s' % table.strip(), 'table') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> tbl_list[i] = pg_quote_identifier(tab...
Add 'public.' to names of tables where a schema identifier is absent and add quotes to each element. Args: tbl_list (list): List of table names. Returns: tbl_list (list): Changed list.
625941e929b78933be1e5b5a
def skillBiasedDraws (player, dm, rollsPerHand) : <NEW_LINE> <INDENT> rollWins = 0 <NEW_LINE> rollLoses = 0 <NEW_LINE> drawn_dice = 0 <NEW_LINE> for roll in range(rollsPerHand) : <NEW_LINE> <INDENT> if player[roll] > dm[roll] : <NEW_LINE> <INDENT> rollWins += 1 <NEW_LINE> <DEDENT> elif dm[roll] > player[roll]: <NEW_LIN...
Propsed model 2 by Griff & Fletch Individual dice ties go to side with most dice. If sides have equal dice, draws are ignored. Tied number of successes goes side with most dice
625941e956b00c62f0f14b10
def dijkstra_path_length(G,source,target, weight = 'weight'): <NEW_LINE> <INDENT> (length,path)=single_source_dijkstra(G,source, weight = weight) <NEW_LINE> try: <NEW_LINE> <INDENT> return length[target] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise nx.NetworkXNoPath("node %s not reachable from %s"%(so...
Returns the shortest path length from source to target in a weighted graph G. Parameters ---------- G : NetworkX graph, weighted source : node label starting node for path target : node label ending node for path weight: string, optional Edge data key corresponding to the edge weight Returns --...
625941e93c8af77a43ae3c5a
def fahr_to_kelvin(temp): <NEW_LINE> <INDENT> return ((temp - 32) * (5.0/9.0)) + 273.15
Convert temperature, temp, from F to K
625941e93eb6a72ae02ec99e
def get(self, acceptable_length, ndef_message): <NEW_LINE> <INDENT> log.debug("get method called") <NEW_LINE> log.debug(ndef_message.encode("hex")) <NEW_LINE> return 0xE0
Handle Get requests. This method should be overwritten by a subclass of SnepServer to customize it's behavior. The default implementation simply returns Not Implemented.
625941e924f1403a92601016
def member_roles_by_person_id(person_id): <NEW_LINE> <INDENT> q_args = {"personId": str(person_id)} <NEW_LINE> resp = _call_members_service("GetMemberRolesByPersonId", **q_args) <NEW_LINE> return _parse_list_response(resp, "AllMembersRoles", "Role")
Returns a list of all roles held by specific MLA
625941e9e1aae11d1e74a170