code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, simulate = False): <NEW_LINE> <INDENT> self.simulate = True <NEW_LINE> if self.simulate == False: <NEW_LINE> <INDENT> self.drv = self.connect_to_controller() <NEW_LINE> self.m0 = self.drv.motor0 <NEW_LINE> self.m1 = self.drv.motor1 <NEW_LINE> m0_pos, m1_pos = self.get_joint_pos() <NEW_LINE> self.join...
This is the constructor for the leg class. Whenever you make a new leg this code will be called. We can optionally make a leg that will simulate the computations without needing to be connected to the ODrive
625941cd15baa723493c4082
def report_compiling(task): <NEW_LINE> <INDENT> _read({"action":"report_compiling", "task":task.id})
now compiling @task data: action=report_compiling, task=...(id:int) return: NULL
625941cde5267d203edcddaa
def checkWinner(self, player, x, y): <NEW_LINE> <INDENT> grid = self.board <NEW_LINE> rows = grid[x][0] == grid[x][1] == grid[x][2] == player.getMark() <NEW_LINE> cols = grid[0][y] == grid[1][y] == grid[2][y] == player.getMark() <NEW_LINE> prim_diag = grid[0][0] == grid[1][1] == grid[2][2] == player.getMark() <NEW_LINE...
x -> int: row of board y -> int: col of board return -> bool Check if the player that made a move has won
625941cd44b2445a339321a3
def test_init_with_custom_empty_categories(self): <NEW_LINE> <INDENT> category_names = ['test1', 'test2', 'test3'] <NEW_LINE> categories = [DynamicTable(name=val, description=val+" description") for val in category_names] <NEW_LINE> AlignedDynamicTable( name='test_aligned_table', description='Test aligned container', c...
Test that we can create an empty table with custom categories
625941cd7d847024c06be3c9
def testEval_1D(self): <NEW_LINE> <INDENT> self.assertEquals(self.comp.run(0.4),self.x_array[0]) <NEW_LINE> self.assertEquals(self.comp.run(1.3),self.x_array[1])
Test 1D model for a HardsphereStructure with evalDistribution
625941cdd4950a0f3b08c45c
def getPlugins(self): <NEW_LINE> <INDENT> plugins = [] <NEW_LINE> plugins_classes = {} <NEW_LINE> for root, dirnames, filenames in os.walk(self.plugins_directory): <NEW_LINE> <INDENT> for filename in fnmatch.filter(filenames, '*.py'): <NEW_LINE> <INDENT> plugins.append(os.path.join(root, filename)) <NEW_LINE> <DEDENT> ...
walks through plugins directory and returns list of plugins
625941cd5166f23b2e1a5266
def multiclass_accuracy(prediction, ground_truth): <NEW_LINE> <INDENT> accuracy = 0.0 <NEW_LINE> for i in range(prediction.shape[0]): <NEW_LINE> <INDENT> if (prediction[i] == ground_truth[i]): <NEW_LINE> <INDENT> accuracy += 1.0 <NEW_LINE> <DEDENT> <DEDENT> accuracy /= prediction.shape[0] <NEW_LINE> return accuracy
Computes metrics for multiclass classification Arguments: prediction, np array of int (num_samples) - model predictions ground_truth, np array of int (num_samples) - true labels Returns: accuracy - ratio of accurate predictions to total samples
625941cd01c39578d7e74f49
def copy_assets(dest_dir=None, april_asset_dir_name=None): <NEW_LINE> <INDENT> global _DEFAULT_ASSET_DEST_DIR <NEW_LINE> global _DEFAULT_ASSET_OUTPUT_DIR_NAME <NEW_LINE> if dest_dir is None: <NEW_LINE> <INDENT> dest_dir = _DEFAULT_ASSET_DEST_DIR <NEW_LINE> <DEDENT> if april_asset_dir_name is None: <NEW_LINE> <INDENT> i...
Copy the April assets to a directory. This function copies assets from the package_data of april to your destination directory dest_dir. It will copy to one directory within dest_dir, which is specified as dest_dir/april_asset_dir_name.
625941cd4527f215b584c564
def test_rule_C0100(self): <NEW_LINE> <INDENT> self.check_result('C0100', '#/resources/res/links/self', Result.PASSED, 'resources:\n' ' res:\n' ' type: object\n' ' links:\n' ' self:\n' ' path: "/path"\n') <NEW_LINE> self.check_result('C0100', '#/resources/res/links/self', Result.FAILED, 'resources:\n...
Standard links must not have a description field.
625941cd7cff6e4e81117a93
def load_api_keys(path="{}/etc/tokens".format(CUR_DIR)): <NEW_LINE> <INDENT> if not os.path.exists(path): <NEW_LINE> <INDENT> os.mkdir(path) <NEW_LINE> <DEDENT> for key in API_KEYS.keys(): <NEW_LINE> <INDENT> if not os.path.isfile(API_KEYS[key][0]): <NEW_LINE> <INDENT> access_token = lib.output.prompt("enter your {} AP...
load the API keys from their .key files
625941cda17c0f6771cbe15e
def _get_cleaned_wrapped_and_styled_text(self, text, app_name): <NEW_LINE> <INDENT> def pad_name(name): <NEW_LINE> <INDENT> return r"{{:>{}s}}".format(self._app_name_width).format(name) <NEW_LINE> <DEDENT> if type(text) != str: <NEW_LINE> <INDENT> text = repr(text) <NEW_LINE> <DEDENT> cleaned_lines = [] <NEW_LINE> wrap...
This beast is a definite candidate for refactoring and is a pretty slow text processor at the moment.
625941cd167d2b6e31218ca3
def finish(self, parser, app): <NEW_LINE> <INDENT> if self.bigendian: <NEW_LINE> <INDENT> self.endian = '>' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.endian = '<' <NEW_LINE> <DEDENT> if 'ammo' in self.unlock: <NEW_LINE> <INDENT> self.maxammo = True <NEW_LINE> <DEDENT> if any([var is not None for var in [self.n...
Some extra sanity checks on our options. "parser" should be an active ArgumentParser object we can use to raise errors. "app" is an App object which we use for a couple lookups.
625941cd627d3e7fe0d68f5d
def test_constant_scalar(Simulator, nl): <NEW_LINE> <INDENT> N = 30 <NEW_LINE> val = 0.5 <NEW_LINE> m = nengo.Network(label='test_constant_scalar', seed=123) <NEW_LINE> with m: <NEW_LINE> <INDENT> m.config[nengo.Ensemble].neuron_type = nl() <NEW_LINE> input = nengo.Node(output=val, label='input') <NEW_LINE> A = nengo.E...
A Network that represents a constant value.
625941cd5e10d32532c5f034
def open_specified_layers(model, open_layers): <NEW_LINE> <INDENT> if isinstance(model, nn.DataParallel): <NEW_LINE> <INDENT> model = model.module <NEW_LINE> <DEDENT> for layer in open_layers: <NEW_LINE> <INDENT> assert hasattr(model, layer), "'{}' is not an attribute of the model, please provide the correct name".form...
Open specified layers in model for training while keeping other layers frozen. Args: - model (nn.Module): neural net model. - open_layers (list): list of layers names.
625941cd442bda511e8be526
def newThread(self): <NEW_LINE> <INDENT> index = self.index <NEW_LINE> self.index += 1 <NEW_LINE> while True: <NEW_LINE> <INDENT> print(time.strftime("%H:%M:%S", time.localtime()) + "开始爬取页面 " + str(index)) <NEW_LINE> startTime = time.time() <NEW_LINE> t = self.getItems(index) <NEW_LINE> if t == 'over': <NEW_LINE> <INDE...
一个单线程
625941cd956e5f7376d70f7b
@dataframe_empty_handler <NEW_LINE> def get_market_cap_by_ticker(date, market="ALL"): <NEW_LINE> <INDENT> market = {"ALL": "ALL", "KOSPI": "STK", "KOSDAQ": "KSQ", "KONEX": "KNX"}.get(market, "ALL") <NEW_LINE> df = MKD30015().fetch(date, market) <NEW_LINE> df = df[['종목코드', '시가총액', '거래량', '거래대금', '상장주식수', '외국인 보유주식수']] <...
시가 총액 :param date : 조회 일자 (YYYYMMDD) :param market : 조회 시장 (KOSPI/KOSDAQ/ALL) :return : DataFrame 종목명 시가 종가 대비 등락률 거래량 거래대금 티커 000020 동화약품 11550 11250 -300 -2.60 1510666 16851737550 000030 우리은행 16050 15400 -650 -4.05 11623346 18124...
625941cd26068e7796caedec
def drawLine(line, forceShape=False): <NEW_LINE> <INDENT> if len(line.points) > 1: <NEW_LINE> <INDENT> v1 = vec(line.points[0]) <NEW_LINE> v2 = vec(line.points[1]) <NEW_LINE> if not DraftVecUtils.equals(v1, v2): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if (dxfCreateDraft or dxfCreateSketch) and (not forceShape): <N...
Return a Part shape (Wire or Edge) from a DXF line. Parameters ---------- line : drawing.entities The DXF object of type `'line'`. forceShape : bool, optional It defaults to `False`. If it is `True` it will produce a `Part.Edge`, otherwise it produces a `Draft Wire`. Returns ------- Part::Part2DObject or...
625941cd4e4d5625662d44e5
def set_RefreshToken(self, value): <NEW_LINE> <INDENT> super(RetrieveSpreadsheetsInputSet, self)._set_input('RefreshToken', value)
Set the value of the RefreshToken input for this Choreo. ((optional, string) An OAuth Refresh Token used to generate a new Access Token when the original token is expired. Required when authenticating with OAuth unless providing a valid AccessToken.)
625941cd4e696a04525c9559
@error_context.context_aware <NEW_LINE> def run(test, params, env): <NEW_LINE> <INDENT> error_context.context("Get host numa topological structure", logging.info) <NEW_LINE> timeout = float(params.get("login_timeout", 240)) <NEW_LINE> host_numa_node = utils_misc.NumaInfo() <NEW_LINE> node_list = host_numa_node.online_n...
Qemu numa basic test: 1) Get host numa topological structure 2) Start a guest and bind it on the cpus of one node 3) Check the memory status of qemu process. It should mainly use the memory in the same node. 4) Destroy the guest 5) Repeat step 2 ~ 4 on every node in host :param test: QEMU test object :param params:...
625941cdb57a9660fec33992
def getType(in_string): <NEW_LINE> <INDENT> if isInt(in_string): <NEW_LINE> <INDENT> return int(in_string) <NEW_LINE> <DEDENT> elif isFloat(in_string): <NEW_LINE> <INDENT> return float(in_string) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return in_string
Checks for the different possible types in which to convert the string. If one of the conversions is possible, the string gets converted and the new typed value gets returned. If not conversion is possible, the string itself is returned Supports currently int, float and string data types Inputs: in_string: String...
625941cd3617ad0b5ed68005
def _create_or_update_user(self, user=None, uid=None, username=None, displayname=None, email=None, validating=True): <NEW_LINE> <INDENT> UserModel = get_user_model() <NEW_LINE> if user is None: <NEW_LINE> <INDENT> user = UserModel.objects.create_user( id=uid, username=username, displayname=displayname, email=email, ) <...
Creates the user in the local database or updates the fields if a user with that id already exists.
625941cd7b180e01f3dc490a
def test_step6(): <NEW_LINE> <INDENT> assert check(["dirname", "//fuck"]).stdout == "/\n"
6. If the remaining string is "//", it is implementation defined whether to skip the remaining steps. We chose _not_ to skip them.
625941cd73bcbd0ca4b2c184
def run_tests(test_case): <NEW_LINE> <INDENT> loader = ut.TestLoader().loadTestsFromTestCase(test_case) <NEW_LINE> result = ut.TestResult() <NEW_LINE> loader(result) <NEW_LINE> print("=" * 60) <NEW_LINE> print("TEST RESULTS FOR", test_case.__name__) <NEW_LINE> print("*FAILURES*") <NEW_LINE> print("-" * 60) <NEW_LINE> f...
test_case: unittest.TestCase object that has been extended with tests
625941cd5f7d997b87174ba6
@register.filter(name='group_str2') <NEW_LINE> def group_str2(group_list): <NEW_LINE> <INDENT> if len(group_list) < 3: <NEW_LINE> <INDENT> return ' '.join([user.name for user in group_list]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '%s ...' % ''.join([user.name for user in group_list[0:2]])
将角色转换为 str
625941cd91f36d47f21ac601
def put_theta(self, S, K, tau, sigma, r): <NEW_LINE> <INDENT> d1, d2 = self.d1_and_d2(S=S, K=K, tau=tau, sigma=sigma, r=r) <NEW_LINE> theta = - (S * sigma * stats.norm.pdf(d1, 0.0, 1.0) / (2.0 * np.sqrt(tau))) + r * K * np.exp( -r * tau) * stats.norm.cdf(-d2, 0.0, 1.0) <NEW_LINE> return theta
"Plain-Vanilla put option Theta
625941cd82261d6c526ab5ad
def get_next_piece(self): <NEW_LINE> <INDENT> n_piece = random.randint(2, 8) <NEW_LINE> piece = Piece(self.matrices[n_piece], self.display, self.slot) <NEW_LINE> return piece
Creates a random next piece
625941cd004d5f362079a441
def map_subnets(subnets: list, route_tables: list) -> dict: <NEW_LINE> <INDENT> subnet_has_internet_gateway = {} <NEW_LINE> for table in route_tables: <NEW_LINE> <INDENT> has_internet_gateway = False <NEW_LINE> for route in table.routes: <NEW_LINE> <INDENT> if route.gateway_id and route.gateway_id.startswith('igw-'): <...
Map VPC subnets to layers
625941cd4f88993c3716c175
def run(self, wf, jsonyaml, attachments): <NEW_LINE> <INDENT> attachments = list(expand_globs(attachments)) <NEW_LINE> parts = build_wes_request(wf, jsonyaml, attachments) <NEW_LINE> postresult = requests.post( f"{self.proto}://{self.host}/ga4gh/wes/v1/runs", files=parts, headers=self.auth, ) <NEW_LINE> return wes_repo...
Composes and sends a post request that signals the wes server to run a workflow. :param str workflow_file: A local/http/https path to a cwl/wdl/python workflow file. :param str jsonyaml: A local path to a json or yaml file. :param list attachments: A list of local paths to files that will be uploaded to the server. :p...
625941cda05bb46b383ec92f
def profiles_select_input_lines(self): <NEW_LINE> <INDENT> self.profiles_input_lines_paths = QFileDialog.getOpenFileNames(self.dlg, "Select input profile lines", filter = "*.shp") <NEW_LINE> if len(self.profiles_input_lines_paths) != 0: <NEW_LINE> <INDENT> self.dlg.profiles_input_lines_textEdit.clear() <NEW_LINE> self....
Bring up a screen allowing the user to select multiple .shp files. Store this as an attribute list and check if valid.
625941cd236d856c2ad448e8
def most_and_least_common_type(treats): <NEW_LINE> <INDENT> types = {} <NEW_LINE> for treat in treats: <NEW_LINE> <INDENT> types[treat['type']] = types.get(treat['type'], 0) + 1 <NEW_LINE> <DEDENT> most_count = most_type = None <NEW_LINE> least_count = least_type = None <NEW_LINE> for ttype, count in types.items(): <NE...
Given list of treats, return {most, least} common types. >>> treats=[{'type': 'dessert'}, {'type': 'dessert'}, {'type': 'appetizer'}, {'type': 'dessert'}, {'type': 'appetizer'}, {'type': 'drink'}] >>> most_and_least_common_type(treats) ('dessert', 'drink') >>> treats1=[{'type': 'dessert'},{'type': 'dessert'},{'type':...
625941cddd821e528d63b2b7
def has_ship(data, coor): <NEW_LINE> <INDENT> if data[coor[1] - 1][ord(coor[0]) - 65] == "*": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False
(data, tuple) -> (bool) Check if there is ship in the cell
625941cdf7d966606f6aa112
def __init__(self, host, user, password, db): <NEW_LINE> <INDENT> self.conn = SC3dbconnection(host, user, password, db) <NEW_LINE> self.log = logging.getLogger('VirtualNetAPI') <NEW_LINE> cfgfile = configparser.RawConfigParser() <NEW_LINE> cfgfile.read('sc3microapi.cfg')
Constructor of the NetworksAPI class.
625941cd0a50d4780f666fa0
def initialize_subtask_info(entry, action_name, total_num, subtask_id_list): <NEW_LINE> <INDENT> task_progress = { 'action_name': action_name, 'attempted': 0, 'failed': 0, 'skipped': 0, 'succeeded': 0, 'total': total_num, 'duration_ms': int(0), 'start_time': time() } <NEW_LINE> entry.task_output = InstructorTask.create...
Store initial subtask information to InstructorTask object. The InstructorTask's "task_output" field is initialized. This is a JSON-serialized dict. Counters for 'attempted', 'succeeded', 'failed', 'skipped' keys are initialized to zero, as is the 'duration_ms' value. A 'start_time' is stored for later duration calcu...
625941cd8e05c05ec3eea483
def __init__(self, brother): <NEW_LINE> <INDENT> pass
Copy constructor. :param brother: A SVertex object. :type brother: SVertex
625941cd26068e7796caeded
def start(self): <NEW_LINE> <INDENT> self._nsObject.startAnimation_(None)
Start the animation. *Only available in indeterminate progress bars.*
625941cdeab8aa0e5d26dc66
def load_fsdump(self, analysis_report_json): <NEW_LINE> <INDENT> file_entries = {} <NEW_LINE> all_infos = analysis_report_json.get('file_list', {}).get('files.allinfo', {}).get('base', {}) <NEW_LINE> file_perms = analysis_report_json.get('file_list', {}).get('files.all', {}).get('base', {}) <NEW_LINE> md5_checksums = a...
Returns a single FSDump entity composed of a the compressed and hashed json of the fs entries along with some statistics. This function will pull necessariy bits from the fully analysis to construct a view of the FS suitable for gate eval. :param analysis_report_json: the full json analysis report :return:
625941cd283ffb24f3c55a0f
def bind_namespaces(graph: Graph): <NEW_LINE> <INDENT> graph.bind("dct", DCT) <NEW_LINE> graph.bind("ecrm", CRM) <NEW_LINE> graph.bind("geo", GEO) <NEW_LINE> graph.bind("gvp", GVP) <NEW_LINE> graph.bind("skos", SKOS) <NEW_LINE> graph.bind("wgs84", WGS84) <NEW_LINE> graph.bind("mmms", MMMS) <NEW_LINE> graph.bind("mmmp",...
Bind common namespaces to the graph
625941cdd486a94d0b98e254
def post(self, request, *args, **kwargs): <NEW_LINE> <INDENT> for fav_id in self.request.POST.getlist('favs[]'): <NEW_LINE> <INDENT> favs = get_favs(self.request) <NEW_LINE> favs = favs.filter(tour_operator__pk=fav_id) <NEW_LINE> if favs.exists(): <NEW_LINE> <INDENT> for fav in favs.all(): <NEW_LINE> <INDENT> fav.date_...
Delete several Favs at a time set date_deleted = now
625941cdd4950a0f3b08c45d
def cmd_set_label(self, label): <NEW_LINE> <INDENT> self.label = label if label is not None else self.name <NEW_LINE> hook.fire("changegroup")
Set the display name of current group to be used in GroupBox widget. If label is None, the name of the group is used as display name. If label is the empty string, the group is invisible in GroupBox.
625941cd851cf427c661a61d
def check_keydown_events(event, ai_settings, screen, ship, bullets): <NEW_LINE> <INDENT> if event.key == pygame.K_RIGHT: <NEW_LINE> <INDENT> ship.moving_right = True <NEW_LINE> <DEDENT> elif event.key == pygame.K_LEFT: <NEW_LINE> <INDENT> ship.moving_left = True <NEW_LINE> <DEDENT> elif event.key == pygame.K_SPACE: <NE...
按键按下
625941cd21a7993f00bc7dfe
def get_quotation(self, code=None, start=None, end=None, frequence=None, market=None, source=None, output=None): <NEW_LINE> <INDENT> pass
Arguments: code {str/list} -- 证券/股票的代码 start {str} -- 开始日期 end {str} -- 结束日期 frequence {enum} -- 频率 QA.FREQUENCE market {enum} -- 市场 QA.MARKET_TYPE source {enum} -- 来源 QA.DATASOURCE output {enum} -- 输出类型 QA.OUTPUT_FORMAT
625941cd7b25080760e39567
def apply_dict(self, target, d): <NEW_LINE> <INDENT> if isinstance(target, list): <NEW_LINE> <INDENT> for entry in target: <NEW_LINE> <INDENT> entry.update(d) <NEW_LINE> <DEDENT> return target <NEW_LINE> <DEDENT> if isinstance(target, dict): <NEW_LINE> <INDENT> target.update(d) <NEW_LINE> return target <NEW_LINE> <DEDE...
Apply a dictionary to one or more elements.
625941cd6aa9bd52df036eb3
def pantilt_callback(self, data): <NEW_LINE> <INDENT> req = [np.deg2rad(data.azimuth), np.deg2rad(data.elevation)] <NEW_LINE> self.goal_pose = self.validate_orientation(req)
Get current orientation request and execute the movement
625941cda934411ee37517a2
def p_vector_declaration_expr(p): <NEW_LINE> <INDENT> p[0] = Node() <NEW_LINE> chk_vector_declaration_expr(p) <NEW_LINE> format_vector_declaration_expr(p)
vector_declaration_expr : '[' vector_elements ']'
625941cdd99f1b3c44c6769c
def computeDataNChipVector(self, chipAll_idx, carrierSignal, message, code): <NEW_LINE> <INDENT> chipAll_long = chipAll_idx.astype(numpy.long) <NEW_LINE> dataBits = message.getDataBits( chipAll_long / carrierSignal.CHIP_TO_SYMBOL_DIVIDER) <NEW_LINE> result = code.combineData(chipAll_long, dataBits) <NEW_LINE> return re...
Helper for computing vector that combines data and code chips. Parameters ---------- chipAll_idx : ndarray vector of chip phases carrierSignal : object Signal description object message : object Data bits source code : objects Code chips source Returns ------- ndarray Array of code chips multiplied with dat...
625941cda8370b77170529ae
def family_time_spans_q(self): <NEW_LINE> <INDENT> family_ids = self.get_descendants(include_self=True).values_list('id', flat=True) <NEW_LINE> return TimeSpan.objects.filter(bucket__in=family_ids)
Returns queryset of all timespans in this bucket and its descendant buckets.
625941cd7047854f462a1518
def FixMarkerInUncal(self): <NEW_LINE> <INDENT> for m in [self.bgMarkers, self.regionMarkers, self.peakMarkers]: <NEW_LINE> <INDENT> m.FixInUncal()
Fix marker in uncalibrated space
625941cdd10714528d5ffdf1
def bundle_changed(self, event): <NEW_LINE> <INDENT> kind = event.get_kind() <NEW_LINE> bundle = event.get_bundle() <NEW_LINE> if kind == BundleEvent.STOPPING_PRECLEAN: <NEW_LINE> <INDENT> self._unregister_bundle_factories(bundle) <NEW_LINE> <DEDENT> elif kind == BundleEvent.STARTED: <NEW_LINE> <INDENT> self._register_...
A bundle event has been triggered :param event: The bundle event
625941cdcc0a2c11143dcf9f
def _collate_subnetwork_reports(self, iteration_number): <NEW_LINE> <INDENT> materialized_reports_all = (self._report_accessor.read_iteration_reports()) <NEW_LINE> previous_ensemble_reports = [] <NEW_LINE> all_reports = [] <NEW_LINE> for i, iteration_reports in enumerate(materialized_reports_all): <NEW_LINE> <INDENT> i...
Prepares subnetwork.Reports to be passed to Generator. Reads subnetwork.MaterializedReports from past iterations, collates those that were included in previous_ensemble into previous_ensemble_reports as a List of subnetwork.MaterializedReports, and collates all reports from previous iterations into all_reports as anot...
625941cd63f4b57ef0001228
def load_shapes(self, count, img_floder, mask_floder, imglist, dataset_root_path): <NEW_LINE> <INDENT> self.add_class("shapes", 1, "ctk") <NEW_LINE> self.add_class("shapes", 2, "yt") <NEW_LINE> self.add_class("shapes", 3, "tst") <NEW_LINE> self.add_class("shapes", 4, "ys") <NEW_LINE> for i in range(count): <NEW_LINE> <...
Generate the requested number of synthetic images. count: number of images to generate. height, width: the size of the generated images.
625941cd596a897236089bcf
def on_epoch_end(self): <NEW_LINE> <INDENT> self.epoch_bar.update()
Close the current bar
625941cd10dbd63aa1bd2cb2
def set_sourcefont_glyph_widths(self): <NEW_LINE> <INDENT> for glyph in self.sourceFont.glyphs(): <NEW_LINE> <INDENT> if (glyph.width == self.font_dim['width']): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if (glyph.width != 0): <NEW_LINE> <INDENT> self.remove_glyph_neg_bearings(glyph) <NEW_LINE> <DEDENT> self.set...
Makes self.sourceFont monospace compliant
625941cd15fb5d323cde0c1e
def switch_command(self, module_path: str, state: Optional[bool] = None) -> None: <NEW_LINE> <INDENT> plugin = self.get_plugin(module_path) <NEW_LINE> if not plugin: <NEW_LINE> <INDENT> warnings.warn(f"Plugin {module_path} not found") <NEW_LINE> return <NEW_LINE> <DEDENT> for command in plugin.commands: <NEW_LINE> <IND...
根据 `state` 修改 plugin 中 commands 的状态。仅对当前消息有效。 参数: module_path: 模块路径 state: - `None(default)`: 切换状态,即 开 -> 关、关 -> 开 - `bool`: 切换至指定状态,`True` -> 开、`False` -> 关 用法: ```python from nonebot import message_preprocessor # 关闭插件 path.to.plugin 中所有命令, 仅对当前消息生效 @message_preprocessor ...
625941cda79ad161976cc254
def send_mails(mails): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> connection = get_connection() <NEW_LINE> connection.send_messages( [mail for mail in mails if mail is not None] ) <NEW_LINE> <DEDENT> except SMTPException as error: <NEW_LINE> <INDENT> LOGGER.error('Failed to send email: %s', error) <NEW_LINE> report_e...
Send multiple mails in single connection.
625941cd60cbc95b062c6652
def gatherResults(deferredList): <NEW_LINE> <INDENT> d = DeferredList(deferredList, fireOnOneErrback=1, consumeErrors=1) <NEW_LINE> d.addCallback(_parseDListResult) <NEW_LINE> return d
Our version of twisted gatherResults() to consume errors raised in deferreds callbacks, as by default, they will not be handled (but errback will call anyway).
625941cd3617ad0b5ed68006
def get_memberships(user, filter=None): <NEW_LINE> <INDENT> memberships = GroupMembership.objects.filter(member=user) <NEW_LINE> if filter: <NEW_LINE> <INDENT> pks = [group.pk for group in filter] <NEW_LINE> memberships = memberships.filter(group__pk__in = pks) <NEW_LINE> <DEDENT> return memberships
Returns the memberships of a given user. if filter is given it will filter the user's memberships based on it. filter is assumed to be a QuerySet or a SearchQuerySet of Group.
625941cd4e4d5625662d44e6
def data(self, qurl): <NEW_LINE> <INDENT> DBG('DiskCache: data() for "{}"'.format(qurl.url())) <NEW_LINE> path = utils.cache_path_for_url(qurl.url()) <NEW_LINE> f = QtCore.QFile(path, self) <NEW_LINE> if f.open(QtCore.QIODevice.ReadOnly) is False: <NEW_LINE> <INDENT> ERR('Cannot open "{}" for reading'.format(path)) <NE...
Qt request an opened file for reading the cached data from
625941cd8da39b475bd65083
def __init__(self, app): <NEW_LINE> <INDENT> from .receivers import connect_receivers <NEW_LINE> self.app = app <NEW_LINE> connect_receivers()
Initialize state.
625941cd76e4537e8c351781
def GetFixedImage(self): <NEW_LINE> <INDENT> return _itkMultiResolutionImageRegistrationMethodPython.itkMultiResolutionImageRegistrationMethodIUS2IUS2_GetFixedImage(self)
GetFixedImage(self) -> itkImageUS2
625941cd56b00c62f0f14768
def random_point(self): <NEW_LINE> <INDENT> m = randint(1, self.p) <NEW_LINE> p = self.mul(self.g, m) <NEW_LINE> while p == self.identity(): <NEW_LINE> <INDENT> m = randint(1, self.p) <NEW_LINE> p = self.mul(self.g, m) <NEW_LINE> <DEDENT> return p
Generate a random point (not identity) on the curve.
625941cd8e7ae83300e4b0db
def _qsimplify_pauli_product(a, b): <NEW_LINE> <INDENT> if not (isinstance(a, SigmaOpBase) and isinstance(b, SigmaOpBase)): <NEW_LINE> <INDENT> return Mul(a, b) <NEW_LINE> <DEDENT> if a.name != b.name: <NEW_LINE> <INDENT> if a.name < b.name: <NEW_LINE> <INDENT> return Mul(a, b) <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND...
Internal helper function for simplifying products of Pauli operators.
625941cd91af0d3eaac9bb28
def switch_data_slot(self, group_id: Groupid, battle_id: int): <NEW_LINE> <INDENT> group = Clan_group.get_or_none(group_id=group_id) <NEW_LINE> if group is None: <NEW_LINE> <INDENT> raise GroupNotExist <NEW_LINE> <DEDENT> group.battle_id = battle_id <NEW_LINE> last_challenge = self._get_group_previous_challenge(group) ...
switch data_slot for challenge data and reset boss status. challenge data should be backuped and comfirm and permission should be checked before this function is called. Args: group_id: group id
625941cde64d504609d7494f
def getAverageContigCoverage(fn, contigLengths): <NEW_LINE> <INDENT> coverage = dict([(cid, 0.0) for cid in contigLengths]) <NEW_LINE> for line in open(fn): <NEW_LINE> <INDENT> line = line.strip().split() <NEW_LINE> coverage[line[0]] += int(line[3]) <NEW_LINE> <DEDENT> for cid in coverage: <NEW_LINE> <INDENT> coverage[...
Returns the average read coverage for a contig
625941cdb5575c28eb68e10f
def exact_group_size(size): <NEW_LINE> <INDENT> return pinned_group_size(size, size)
Returns a function that will test its argument -- expected to be a (k,g) tuple with a key and a collection -- and return True iff the length of the collection is exactly `size` This is intended to used like `chan.filter(exact_group_size(5))`.
625941cd15fb5d323cde0c1f
def getSuccessor(self, gameState, action): <NEW_LINE> <INDENT> successor = gameState.generateSuccessor(self.index, action) <NEW_LINE> pos = successor.getAgentState(self.index).getPosition() <NEW_LINE> if pos != nearestPoint(pos): <NEW_LINE> <INDENT> return successor.generateSuccessor(self.index, action) <NEW_LINE> <DED...
Finds the next successor which is a grid position (location tuple).
625941cd4a966d76dd55111e
@yield_fixture(scope='session', autouse=True) <NEW_LINE> def make_synthesis(request): <NEW_LINE> <INDENT> yield <NEW_LINE> test_synthesis_contains_everything(request)
This checks that the session-scoped fixture teardown hook works as well
625941cdd58c6744b4257d6f
def test_detach_volume(self): <NEW_LINE> <INDENT> volume = self.client.volumes()[2] <NEW_LINE> with self.mock_post(f'volumes/{volume.id}') as mock: <NEW_LINE> <INDENT> result = volume.detach() <NEW_LINE> assert mock.call_url == f'/volumes/{volume.id}/detach' <NEW_LINE> assert result is True
Tests that detaching the volume succeeds
625941cd4c3428357757c437
def get_value(self, key:any) -> any: <NEW_LINE> <INDENT> return self.__local.get(key, None)
return the value for a given key, None if key doesnt exist
625941cd9c8ee82313fbb884
def variations(seq, n, repetition=False): <NEW_LINE> <INDENT> if n == 0: <NEW_LINE> <INDENT> yield [] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not repetition: <NEW_LINE> <INDENT> for i in xrange(len(seq)): <NEW_LINE> <INDENT> for cc in variations(seq[:i] + seq[i + 1:], n - 1, False): <NEW_LINE> <INDENT> yield [...
Returns a generator of the variations (size n) of the list `seq` (size N). `repetition` controls whether items in seq can appear more than once; Examples: variations(seq, n) will return N! / (N - n)! permutations without repetition of seq's elements: >>> from sympy.utilities.iterables import variations >>> li...
625941cd44b2445a339321a5
def setUp(self): <NEW_LINE> <INDENT> sys.stdout.write('\nDownloading the repository of soletta...') <NEW_LINE> sys.stdout.flush() <NEW_LINE> soletta_url = 'https://github.com/solettaproject/soletta.git' <NEW_LINE> get_test_module_repo(soletta_url, 'soletta') <NEW_LINE> sys.stdout.write('\nCopying necessary files to tar...
Copy all files related to testing to device @fn setup @param self
625941cd8e71fb1e9831d8b8
def plotPDF(boro,df): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> ind = np.arange(5) <NEW_LINE> plt.bar(ind,df['C'],color = 'r', label = 'C') <NEW_LINE> plt.bar(ind,df['B'],color = 'b',bottom = df['C'],label = 'B') <NEW_LINE> plt.bar(ind,df['A'],color = 'g',bottom = df['C'] + df['B'],label = 'A') <NEW_LINE> plt.ylabel(...
question 5: plots the number of restaurants in a boro with each grade over time
625941cd656771135c3eb97e
def _rhs_rho_deterministic(L, rho_t, t, dt, args): <NEW_LINE> <INDENT> drho_t = spmv(L.data, L.indices, L.indptr, rho_t) * dt <NEW_LINE> return drho_t
Deterministic contribution to the density matrix change
625941cdadb09d7d5db6c89f
def _BuildAndroidGameLoopTestSpec(self): <NEW_LINE> <INDENT> spec = self._BuildGenericTestSpec() <NEW_LINE> app_apk, app_bundle = self._BuildAppReference(self._args.app) <NEW_LINE> spec.androidTestLoop = self._messages.AndroidTestLoop( appApk=app_apk, appBundle=app_bundle, appPackageId=self._args.app_package) <NEW_LINE...
Build a TestSpecification for an AndroidTestLoop.
625941cd9f2886367277a99c
def test_introduction(): <NEW_LINE> <INDENT> alice = User('Alice', 21) <NEW_LINE> intro = alice.get_introduction() <NEW_LINE> assert alice.name in intro <NEW_LINE> assert str(alice.age) in intro
Check that user introduses herself properly.
625941cd097d151d1a222f69
def get_troubleshooting( self, resource_group_name, network_watcher_name, parameters, custom_headers=None, raw=False, **operation_config): <NEW_LINE> <INDENT> raw_result = self._get_troubleshooting_initial( resource_group_name=resource_group_name, network_watcher_name=network_watcher_name, parameters=parameters, custom...
Initiate troubleshooting on a specified resource. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param network_watcher_name: The name of the network watcher resource. :type network_watcher_name: str :param parameters: Parameters that define the resource to troubleshoot. :t...
625941cdd4950a0f3b08c45e
def log_in_employee(request): <NEW_LINE> <INDENT> request.session.set_expiry(300) <NEW_LINE> if 'ca_user' in request.session and request.session['ca_user'] != '': <NEW_LINE> <INDENT> print('Login method') <NEW_LINE> try: <NEW_LINE> <INDENT> emp = sf_instance.execute_soql( "select id,Name,username__c,address__c,designat...
:param request: :return:
625941cd73bcbd0ca4b2c185
def compile_pattern(self,pattern): <NEW_LINE> <INDENT> return re.compile(pattern,flags=self.flags)
Method to compile the final pattern using the default flags set
625941cd01c39578d7e74f4b
def checkCommitWithEmptyData(self): <NEW_LINE> <INDENT> stor = self._storage <NEW_LINE> for description in (u'commit with empty data', u''): <NEW_LINE> <INDENT> t = TransactionMetaData(description=description) <NEW_LINE> stor.tpc_begin(t) <NEW_LINE> stor.tpc_vote(t) <NEW_LINE> head = stor.tpc_finish(t) <NEW_LINE> self....
Verify that transaction is persisted even if it has no data, or even both no data and empty metadata.
625941cd7cff6e4e81117a95
def warning(self, s): <NEW_LINE> <INDENT> self.__stderr__.write("*** Warning: ") <NEW_LINE> self.__stderr__.write(s.encode(IO_ENCODING, 'replace')) <NEW_LINE> self.__stderr__.write(os.linesep)
displays a warning message unicode string to stderr this appends a newline to that message
625941cd15baa723493c4085
def updateModel(self, data, x): <NEW_LINE> <INDENT> self.sigma = x[0] <NEW_LINE> self.mu = x[1] <NEW_LINE> DataStorage.updateAll(self, data.time, data.delta, data.value)
:param data: Data of Degradation Process consist of new time, increments and value experiment. :param x: New array included models parameters such as sigma, mu
625941cd8c3a8732951584ca
def test_3(self): <NEW_LINE> <INDENT> A, B, K = 11, 345, 17 <NEW_LINE> expected_result = 20 <NEW_LINE> self.assertEqual(countdiv.countdiv(A, B, K), expected_result)
Proposed Test 3.
625941cd090684286d50edf5
def custom_loss(self): <NEW_LINE> <INDENT> lossL2 = tf.add_n([tf.nn.l2_loss(v) for v in vars if 'bias' not in v.name]) * 0.001
As presented in 'Deep Q-learning from Demonstrations', the loss value is highly impacted by the :return: Loss Value
625941cd97e22403b379d0a9
def decode_list(data): <NEW_LINE> <INDENT> rv = [] <NEW_LINE> for item in data: <NEW_LINE> <INDENT> if isinstance(item, unicode): <NEW_LINE> <INDENT> item = item.encode('utf-8') <NEW_LINE> <DEDENT> elif isinstance(item, list): <NEW_LINE> <INDENT> item = decode_list(item) <NEW_LINE> <DEDENT> elif isinstance(item, dict):...
Decode json list data.
625941cdf548e778e58cd68d
@register.tag <NEW_LINE> def get_answer_count(parser, token): <NEW_LINE> <INDENT> return AnswerCountNode.handle_token(parser, token)
Gets the answer count for the given params and populates the template context with a variable containing that value, whose name is defined by the 'as' clause. Syntax:: {% get_answer_count for [object] as [varname] %} Example usage:: {% get_answer_count for object as answer_count %}
625941cd566aa707497f4678
def product_except_index(num_list): <NEW_LINE> <INDENT> out_list = list() <NEW_LINE> for index, val in enumerate(num_list): <NEW_LINE> <INDENT> if isinstance(val, (int, long, float, complex)) == False: <NEW_LINE> <INDENT> return "Invalid input, non-number in array" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> product ...
Accepts a list (1D array) of numbers and returns a list of the products for all products at each position excepting the current postion. Example: product_except_index([1, 7, 3, 4]) = [84, 12, 28, 21]
625941cd956e5f7376d70f7d
def __init__(self, init_state, heuristic, depth_limit): <NEW_LINE> <INDENT> self.heuristic = heuristic <NEW_LINE> self.states = [[self.priority(init_state), init_state]] <NEW_LINE> self.num_tested = 0 <NEW_LINE> self.depth_limit = depth_limit
constructor for a GreedySearcher object inputs: * init_state - a State object for the initial state * heuristic - an integer specifying which heuristic function should be used when computing the priority of a state * depth_limit - the depth limit of the searcher
625941cd6fece00bbac2d84e
def send_tg_message_reply_or_private(self, update: Update, text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.updater.bot.send_message(update.message.from_user.id, text) <NEW_LINE> <DEDENT> except TelegramError: <NEW_LINE> <INDENT> if update.message.from_user.username is None: <NEW_LINE> <INDENT> text_to_send = "...
Send a reply in private; when not possible, send in group @:param update: an object that represents an incoming message. @:param text: text to send
625941cd91f36d47f21ac602
@pytest.mark.parametrize(('point', ), points_on_vertices) <NEW_LINE> def test_point_on_vertex(point): <NEW_LINE> <INDENT> p1 = point_in_poly(poly1_ccw, np.asarray(point, dtype=np.float64)) <NEW_LINE> p2 = point_in_poly(poly2_ccw, np.asarray(point, dtype=np.float64)) <NEW_LINE> assert p1 ^ p2
tests points that are on the vertex between two polygons it should be computed as being only in one and only one of them
625941cd4e4d5625662d44e7
def __init__(self, jsondict=None): <NEW_LINE> <INDENT> self.actual = None <NEW_LINE> self.characteristic = None <NEW_LINE> self.code = None <NEW_LINE> self.identifier = None <NEW_LINE> self.member = None <NEW_LINE> self.name = None <NEW_LINE> self.quantity = None <NEW_LINE> self.type = None <NEW_LINE> super(Group, self...
Initialize all valid properties.
625941cd7b180e01f3dc490c
def tokenize_refgene_annotation(bed_row): <NEW_LINE> <INDENT> token_list = list() <NEW_LINE> if bed_row['strand'] == '+': <NEW_LINE> <INDENT> is_fwd = True <NEW_LINE> <DEDENT> elif bed_row['strand'] == '-': <NEW_LINE> <INDENT> is_fwd = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Bad strand (...
Get a list of refGene annotations for a region. :param bed_row: Pandas Series of one record with refGene fields (UCSC refGene). :return: A list of annotations, one for each region (UTR5, CDS, etc). The last record is "END" with the first base after the transcribed region.
625941cd5f7d997b87174ba8
def _xdmfVectorFieldType(self, vectorFieldString): <NEW_LINE> <INDENT> vtype = "Matrix" <NEW_LINE> if vectorFieldString.lower() == "scalar": <NEW_LINE> <INDENT> vtype = "Scalar" <NEW_LINE> <DEDENT> elif vectorFieldString.lower() == "vector": <NEW_LINE> <INDENT> vtype = "Vector" <NEW_LINE> <DEDENT> elif vectorFieldStrin...
Get Xdmf vector field type.
625941cd099cdd3c635f0d6a
def main(): <NEW_LINE> <INDENT> show(input())
main func
625941cd30bbd722463cbed6
def move(self, mv_cmd): <NEW_LINE> <INDENT> steering = mv_cmd[0] <NEW_LINE> dist = mv_cmd[1] <NEW_LINE> if steering > Robot.max_steering_angle: <NEW_LINE> <INDENT> raise(ValueError, 'exceeds maximum steering angle') <NEW_LINE> <DEDENT> if dist < 0: <NEW_LINE> <INDENT> raise(ValueError, 'the robot cannot move backwards'...
:param mv_cmd: [steering angle, distance passed by rear wheel] :return: a new Robot object
625941cd004d5f362079a443
def __init__(self,link,pointer=0): <NEW_LINE> <INDENT> if pointer==0: <NEW_LINE> <INDENT> f=link.o2scl.o2scl_create_comm_option_s <NEW_LINE> f.restype=ctypes.c_void_p <NEW_LINE> f.argtypes=[] <NEW_LINE> self._ptr=f() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ptr=pointer <NEW_LINE> self._owner=False <NEW_LINE>...
Init function for class comm_option_s | Parameters: | *link* :class:`linker` object | *pointer* ``ctypes.c_void_p`` pointer
625941cdd53ae8145f87a380
@all_parameters_as_numpy_arrays <NEW_LINE> def point_intersect_rectangle(point, rect): <NEW_LINE> <INDENT> left, right, bottom, top = rect.bounds(rect) <NEW_LINE> if point[0] < left or point[0] > right or ...
Calculates the intersection point of a point and a 2D rectangle. For 3D points, the Z axis will be ignored. :return: Returns True if the point is touching or within the rectangle.
625941cd26238365f5f0ef7e
def __write_aliases_file(lines): <NEW_LINE> <INDENT> afn = __get_aliases_filename() <NEW_LINE> adir = os.path.dirname(afn) <NEW_LINE> out = tempfile.NamedTemporaryFile(dir=adir, delete=False) <NEW_LINE> if not __opts__.get('integration.test', False): <NEW_LINE> <INDENT> if os.path.isfile(afn): <NEW_LINE> <INDENT> afn_s...
Write a new copy of the aliases file. Lines is a list of lines as returned by __parse_aliases.
625941cd56b00c62f0f14769
def __init__(self, version, payload, workspace_sid): <NEW_LINE> <INDENT> super(WorkspaceCumulativeStatisticsInstance, self).__init__(version) <NEW_LINE> self._properties = { 'account_sid': payload.get('account_sid'), 'avg_task_acceptance_time': deserialize.integer(payload.get('avg_task_acceptance_time')), 'start_time':...
Initialize the WorkspaceCumulativeStatisticsInstance :returns: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance :rtype: twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics.WorkspaceCumulativeStatisticsInstance
625941cdff9c53063f47c303
def angle(self, other): <NEW_LINE> <INDENT> return math.acos(self.normalize().dot(other.normalize()))
Return the angle between this vector and another
625941cd8e05c05ec3eea484
def dc(self, **kwargs): <NEW_LINE> <INDENT> self._add_analysis(DCAnalysisParameters(**kwargs))
Compute the DC transfer fonction of the circuit with capacitors open and inductors shorted. Examples of usage:: analysis = simulator.dc(Vinput=slice(-2, 5, .01)) analysis = simulator.dc(Ibase=slice(0, 100e-6, 10e-6)) analysis = simulator.dc(Vcollector=slice(0, 5, .1), Ibase=slice(micro(10), micro(100), mi...
625941cd2c8b7c6e89b358d0
def debug(self, msg): <NEW_LINE> <INDENT> if self.verbose: <NEW_LINE> <INDENT> self.errprint("({},{}) {}".format(self.x, self.y, msg))
Print a debug message.
625941cd94891a1f4081bbb9