content
stringlengths
22
815k
id
int64
0
4.91M
def Pow_sca(x_e, c_e, g, R0, R1, omega, epM): """Calculate the power scattered by an annulus with a 'circling' electron as exciting source inside and an electron moving on a slightly curved trajectory outside (vertical) The trajectory of the electron derives from a straight vertical trajectory in th...
19,700
def read_images_binary(path_to_model_file): """ see: src/base/reconstruction.cc void Reconstruction::ReadImagesBinary(const std::string& path) void Reconstruction::WriteImagesBinary(const std::string& path) """ images = {} with open(path_to_model_file, "rb") as fid: num_reg_i...
19,701
def index(): """Render upload page.""" log_cmd('Requested upload.index', 'green') return render_template('upload.html', page_title='Upload', local_css='upload.css', )
19,702
def pin_rsconnect(data, pin_name, pretty_pin_name, connect_server, api_key): """ Make a pin on RStudio Connect. Parameters: data: any object that has a to_json method (eg. pandas DataFrame) pin_name (str): name of pin, only alphanumeric and underscores pretty_pin_name (str): displ...
19,703
def partial_to_full(dic1, dic2): """This function relates partial curves to full curves, according to the distances between them The inputs are two dictionaries""" C = [] D = [] F = [] # Calculate the closest full curve for all the partial curves under # evaluation for i in tqdm(dic1.ke...
19,704
def _sample(probabilities, population_size): """Return a random population, drawn with regard to a set of probabilities""" population = [] for _ in range(population_size): solution = [] for probability in probabilities: # probability of 1.0: always 1 # probability of ...
19,705
def nodal_scoping(node_ids, server = None): """Helper function to create a specific ``ansys.dpf.core.Scoping`` associated to a mesh. Parameters ---------- node_ids : List of int server : server.DPFServer, optional Server with channel connected to the remote or local instance. When...
19,706
def print_func(val): """test function""" print(val)
19,707
def user_active(request): """Prevents auto logout by updating the session's last active time""" # If auto logout is disabled, just return an empty body. if not settings.AUTO_LOGOUT_SECONDS: return HttpResponse(json.dumps({}), content_type="application/json", status=200) last_active_at = set_ses...
19,708
def decode_labels(labels): """Validate labels.""" labels_decode = [] for label in labels: if not isinstance(label, str): if isinstance(label, int): label = str(label) else: label = label.decode('utf-8').replace('"', '') labels_decode...
19,709
def indent(text, num=2): """Indent a piece of text.""" lines = text.splitlines() return '\n'.join(indent_iterable(lines, num=num))
19,710
def random_lever_value(lever_name): """Moves a given lever (lever_name) to a random position between 1 and 3.9""" rand_val = random.randint(10, 39)/10 # Generate random value between 1 and 3.9 return move_lever([lever_name], [round(rand_val, 2)], costs = True)
19,711
def create_clean_dataset(input_train_csv_path: str, input_test_csv_path: str, output_rootdir: str, output_train_csv_file: str, output_test_csv_file: str, train_fname_prefix: str, test_fname_prefix: str, xforms: Sequence[dg_transform.Transform], ...
19,712
def back(update, context): """Кнопка назад.""" user = get_user_or_raise(update.effective_user.id) update.message.reply_text( messages.MAIN_MENU_MESSAGE, reply_markup=get_start_keyboard(user) ) return ConversationHandler.END
19,713
def patch_redhat_subscription(mocker): """ Function used for mocking some parts of redhat_subscription module """ mocker.patch('ansible_collections.community.general.plugins.modules.packaging.os.redhat_subscription.RegistrationBase.REDHAT_REPO') mocker.patch('ansible_collections.community.general.pl...
19,714
def pandas_config(): """ pandas config 적용 :return: """ for key, value in CONFIG['pandas'].items(): pd.set_option(key, value)
19,715
def get_norm_residuals(vecs, word): """ computes normalized residuals of vectors with respect to a word Args: vecs (ndarray): word (ndarray): Returns: tuple : (rvecs_n, rvec_flag) CommandLine: python -m ibeis.algo.hots.smk.smk_residuals --test-get_norm_residuals ...
19,716
def euler(): """ Plots the solution to the differential equation with the given initial conditions to verify they equal sin(x) and cos(x) using Euler's Method """ t = np.linspace(0.0, 5*2*np.pi, 1000, dtype = float) x = np.zeros_like(t) v = np.zeros_like(t) x[0]= 1 v[0] = 0 s ...
19,717
def user_closed_ticket(request): """ Returns all closed tickets opened by user :return: JsonResponse """ columns = _no_priority if settings.SIMPLE_USER_SHOW_PRIORITY: columns = _ticket_columns ticket_list = Ticket.objects.filter(created_by=request.user, ...
19,718
def review_lock_status(review_id): """ return status of review included trials (locked = T or F) @param review_id: pmid of review @return: boolean """ conn = dblib.create_con(VERBOSE=True) cur = conn.cursor() cur.execute( "SELECT included_complete FROM systematic_reviews WHERE re...
19,719
def cancel(foreign_id): """Cancel all queued tasks for the dataset.""" collection = get_collection(foreign_id) cancel_queue(collection)
19,720
def get_placekey_from_address(street_address:str, city:str, state:str, postal_code:str, iso_country_code:str='US', placekey_api_key: str = None) -> str: """ Look up the full Placekey for a given address string. :param street_address: Street address with suite, floor, or apartm...
19,721
async def upload_image( request: Request, file: UploadFile = File(...) ): """ upload image(jpg/jpeg/png/gif) to server and store locally :return: upload result """ save_file_path = os.path.join(os.getcwd().split("app")[0], r"app/static/images") # pic_uuid = str(uuid.uuid4()) ...
19,722
def _path_to_str(var): """Make sure var is a string or Path, return string representation.""" if not isinstance(var, (Path, str)): raise ValueError("All path parameters must be either strings or " "pathlib.Path objects. Found type %s." % type(var)) else: return str(v...
19,723
def netconf_edit_config(task: Task, config: str, target: str = "running") -> Result: """ Edit configuration of device using Netconf Arguments: config: Configuration snippet to apply target: Target configuration store Examples: Simple example:: > nr.run(task=netcon...
19,724
def _cve_id_field_name(): """ Key name for a solr field that contains cve_id """ return "cve_id"
19,725
def mapRuntime(dataFrame1, dataFrame2): """ Add the scraped runtimes of the titles in the viewing activity dataframe Parameters: dataFrame1: string The name of the dataFrame to which the user wants to add the runtime dataFrame2: string The name of the dataFrame ...
19,726
def main(): """Mainline""" parser = argparse.ArgumentParser( description='Start a scan', ) parser.add_argument('--smartcheck-host', action='store', default=os.environ.get('DSSC_SMARTCHECK_HOST', None), help='The hostname of the Deep Security Smar...
19,727
def get_circ_center_2pts_r(p1, p2, r): """ Find the centers of the two circles that share two points p1/p2 and a radius. From algorithm at http://mathforum.org/library/drmath/view/53027.html. Adapted from version at https://rosettacode.org/wiki/Circles_of_given_radius_through_two_points#Python. :p...
19,728
def bing_generator(subkey, limit=150, start=0): """ Uses the Bing search API to get all crawled Devpost urls. This should be around 700 in total as of summer 2017. :param subkey: Bing Web Search subscription key :param limit: Cap the number of devpost names :param start: What offset to start at...
19,729
def test_load_entity(query_factory): """Tests loading a basic query with an entity""" markup_text = 'When does the {Elm Street|store_name} store close?' processed_query = markup.load_query(markup_text, query_factory) assert len(processed_query.entities) == 1 entity = processed_query.entit...
19,730
def crext_MaxFragmentLength(length_exponent): """Create a MaxFragmentLength extension. Allowed lengths are 2^9, 2^10, 2^11, 2^12. (TLS default is 2^14) `length_exponent` should be 9, 10, 11, or 12, otherwise the extension will contain an illegal value. """ maxlen = (length_exponent-8).to_bytes(1...
19,731
def display_status_lcd(obj_lcd, *args): """ Display in LCD display status """ # If getSensorStatus is the function, then call it with objDB as argument if args[0].__name__ == 'getSensorStatus': messages = args[0](args[1]) elif type(args) is list: messages = args else: message...
19,732
def perform_intervention(intervention, model, effect_types=('indirect', 'direct')): """Perform intervention and return results for specified effects""" x = intervention.base_strings_tok[0] # E.g. The doctor asked the nurse a question. She x_alt = intervention.base_strings_tok[1] # E.g. The doctor asked th...
19,733
def nice_size( self: complex, unit: str = 'bytes', long: bool = False, lower: bool = False, precision: int = 2, sep: str = '-', omissions: list = 'mono deca hecto'.split(), ): """ This should behave well on int subclasses """ mag = magnitude(self, omissions) ...
19,734
def from_callback(func: Callable, mapper: Optional[typing.Mapper] = None ) -> Callable[[], Observable]: """Converts a callback function to an observable sequence. Args: func: Function with a callback as the last argument to convert to an Observable sequen...
19,735
def EVLAUVFITS(inUV, filename, outDisk, err, compress=False, \ exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], \ include=[], headHi=False, logfile=""): """ Write UV data as FITS file Write a UV data set as a FITAB format file History written to heade...
19,736
def form_cleaner(querydict): """ Hacky way to transform form data into readable data by the model constructor :param querydict: QueryDict :return: dict """ r = dict(querydict.copy()) # Delete the CRSF Token del r['csrfmiddlewaretoken'] for key in list(r): # Take first element...
19,737
def has_1080p(manifest): """Return True if any of the video tracks in manifest have a 1080p profile available, else False""" return any(video['width'] >= 1920 for video in manifest['videoTracks'][0]['downloadables'])
19,738
def visualize_table(filename: str, table: str) -> bool: """ Formats the contents of a db table using the texttable package :param filename: .db file name (String) :param table: Name of the table to plot (String) :return: Bool """ conn, cursor = get_connection(filename) ta...
19,739
async def test_platform_manually_configured(hass): """Test that we do not discover anything or try to set up a controller.""" assert ( await async_setup_component( hass, sensor.DOMAIN, {sensor.DOMAIN: {"platform": "unifi"}} ) is True ) assert unifi.DOMAIN not in hass....
19,740
def extractIsekaiMahou(item): """ # Isekai Mahou Translations! """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Isekai Mahou Chapter' in item['title'] and 'Release' in item['title']: return buildReleaseMes...
19,741
def delete_version_from_file(fname, par, ctype=gu.PIXEL_MASK, vers=None, cmt=None, verb=False) : """Delete specified version from calibration constants. Parameters - fname : full path to the hdf5 file - par : psana.Event | psana.Env | float - tsec event time - ctype : gu.CTYPE - enumerat...
19,742
def get_filename(filePath): """get filename without file extension from file path """ absFilePath = os.path.abspath(filePath) return os.path.basename(os.path.splitext(absFilePath)[0])
19,743
def create_midi_file(notes: List[Tuple[int, int]]) -> io.BytesIO: """Create a MIDI file from the given list of notes. Notes are played with piano instrument. """ byte_stream = io.BytesIO() mid = mido.MidiFile() track = mido.MidiTrack() mid.tracks.append(track) for note, t in notes: ...
19,744
def brainprep_quasiraw(anatomical, mask, outdir, target=None, no_bids=False, verbose=0): """ Define quasi-raw pre-processing workflow. Parameters ---------- anatomical: str path to the anatomical T1w Nifti file. mask: str a binary mask to be applied. outdi...
19,745
async def get_programs(request: Request) -> Response: """ description: Get a list of all programs responses: 200: description: A list of programs. """ ow: "OpenWater" = request.app.ow return ToDictJSONResponse([p.to_dict() for p in ow.programs.store.all])
19,746
def create_dataframe(dictionary_to_convert, cols): """ From a Dictionary which is passed, and the desired column to create, this function returns a Dataframe. """ dataframe_converted = pd.DataFrame.from_dict(dictionary_to_convert, orient='index', columns = cols) dataframe_converted = dataframe_convert...
19,747
def version_keyword(dist, attr, value): """ Implements the actual version setup() keyword. """ if value == "PBR": from pbr.util import setup_cfg_to_setup_kwargs path = "setup.cfg" parser = ConfigParser() if not os.path.exists(path): raise ValueError("file '%s...
19,748
def test_smoke1_reboot(): """Test reboot""" return_value, _ = subprocess.getstatusoutput('meshtastic --reboot') assert return_value == 0 # pause for the radio to reset (10 seconds for the pause, and a few more seconds to be back up) time.sleep(18)
19,749
def br_candidates(data, br_remaining, commit): """Find candidates not yet included to be added to br(r,*) Given the list of remaining, that is not yet taken into account bug fixes, split this list into part that has been created (fixed) before creation time of given bug report, and those that were ...
19,750
def aggregate_dataframe(mails_per_sender, datetimes_per_sender): """Engineer features and aggregate them in a dataframes. :param dict mails_per_sender: A dictionary with email counts for each sender :param dict datetimes_per_sender: A dictionary with datetime objects for each sender :raises InputEr...
19,751
def setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, aliases=None, **kwargs): """Create the test databases. This function is a copy of the Django setup_databases with one addition. A Tenant object is created and saved when setting up the database. """ test_database...
19,752
def about_view(request): """ This view gives information about the version and software we have loaded. """ evaluation = get_session_evaluation(request.session) definitions = evaluation.definitions system_info = mathics_system_info(definitions) return render( request, "about...
19,753
def doDeploy(): """Deploys the lambda package and associated resources, based on the configuration file config.yaml supplied in the root directory""" packageDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, os.path.pardir) path_to_config_file = os.path.join(packageDir, 'config.y...
19,754
def is_trace_directory(path: str) -> bool: """ Check recursively if a path is a trace directory. :param path: the path to check :return: `True` if it is a trace directory, `False` otherwise """ path = os.path.expanduser(path) if not os.path.isdir(path): return False return impl....
19,755
def traj2points(traj, npoints, OS): """ Transform spoke trajectory to point trajectory Args: traj: Trajectory with shape [nspokes, 3] npoints: Number of readout points along spokes OS: Oversampling Returns: array: Trajectory with shape [nspokes, npoints, 3] """ ...
19,756
def parse_headings(raw_contents, file_): """Parse contents looking for headings. Return a tuple with number of TOC elements, the TOC fragment and the number of warnings.""" # Remove code blocks parsable_contents = re.sub(r"```[\s\S]+?```", "", raw_contents) # Parse H1,H2,H3 headings = re.findall...
19,757
def current_umask(): """Get the current umask which involves having to set it temporarily.""" mask = os.umask(0) os.umask(mask) return mask
19,758
def label_on(): """Sets the next label to the ON value""" global NEXT_LABEL NEXT_LABEL = "1"
19,759
def model_variable(name, shape=None, dtype=None, initializer=None, regularizer=None, constraint=None, trainable=True, collections=None, **kwargs): """ Get or cr...
19,760
def default_k_pattern(n_pattern): """ the default number of pattern divisions for crossvalidation minimum number of patterns is 3*k_pattern. Thus for n_pattern <=9 this returns 2. From there it grows gradually until 5 groups are made for 40 patterns. From this point onwards the number of groups is kept ...
19,761
def test_character_references_336(): """ Test case 336: (part 4) Entity and numeric character references cannot be used in place of symbols indicating structure in CommonMark documents. """ # Arrange source_markdown = """&#9;foo""" expected_tokens = [ "[para(1,1):]", "[text(1,1...
19,762
def resize_basinData(): """ read in global data and make the new bt with same length this step can be elimated if we are using ibtracks in the future CHAZ development """ basinName = ['atl','wnp','enp','ni','sh'] nd = 0 for iib in range(0,len(basinName),1): ib = basin...
19,763
def _cast_wf(wf): """Cast wf to a list of ints""" if not isinstance(wf, list): if str(type(wf)) == "<class 'numpy.ndarray'>": # see https://stackoverflow.com/questions/2060628/reading-wav-files-in-python wf = wf.tolist() # list(wf) does not convert int16 to int else: ...
19,764
def encoded_path(root, identifiers, extension = ".enc", depth = 3, digest = True): """generate a unique file-accessible path from the given list of identifiers starting at the given root directory.""" ident = string.join(identifiers, "_") if digest: ident = sha.new(ident).hexdigest() i...
19,765
def block_gen(rows, cols, bs=64, random_flag=False): """Generate block indices for reading rasters/arrays as blocks Return the row (y/i) index, then the column (x/j) index Args: rows (int): number of rows in raster/array cols (int): number of columns in raster/array bs (int): gdal_...
19,766
def centralize_scene(points): """In-place centralize a whole scene""" assert points.ndim == 2 and points.shape[1] >= 3 points[:, 0:2] -= points[:, 0:2].mean(0) points[:, 2] -= points[:, 2].min(0) return points
19,767
def ms(val): """ Turn a float value into milliseconds as an integer. """ return int(val * 1000)
19,768
def cancel_member(sess: SQLASession, member: Member, keep_groups: bool = False) -> Collect[None]: """ Suspend the user account of a member. """ user = unix.get_user(member.uid) yield unix.enable_user(user, False) yield bespoke.clear_crontab(member) yield bespoke.slay_user(member) # TODO:...
19,769
def prepare_wordclouds( clusters: Dict[str, List[int]], test_texts: Union[np.ndarray, pd.Series] ): """Pre-render the wordcloud for each cluster, this makes switching the main wordcloud figure faster. :param clusters: Dictionary of clusters where the values are the lists of dataframe indices for the entrie...
19,770
def render_doc(stig_rule, deployer_notes): """Generate documentation RST for each STIG configuration.""" template = JINJA_ENV.get_template('template_doc_rhel7.j2') return template.render( rule=stig_rule, notes=deployer_notes )
19,771
def official_evaluate(reference_csv_path, prediction_csv_path): """Evaluate metrics with official SED toolbox. Args: reference_csv_path: str prediction_csv_path: str """ reference_event_list = sed_eval.io.load_event_list(reference_csv_path, delimiter='\t', csv_header=False, ...
19,772
def get_notebooks(): """Read `notebooks.yaml` info.""" path = Path("tutorials") / "notebooks.yaml" with path.open() as fh: return yaml.safe_load(fh)
19,773
def getSimData(startDate, endDate, region): """ Get all boundary condition data needed for a simulation run Args: startDate (string): Start date DD.MM.YYYY (start time is hard coded to 00:00) endDate (string): End date DD.MM.YYYY (end day is...
19,774
def get_dag_path(pipeline, module=None): """ Gets the DAG path. :@param pipeline: The Airflow Variable key that has the config. :@type pipeline: str. :@param module: The module that belongs to the pipeline. :@type module: str. :@return: The DAG path of the pipeline. """ if module is...
19,775
def blow_up(polygon): """Takes a ``polygon`` as input and adds pixels to it according to the following rule. Consider the line between two adjacent pixels in the polygon (i.e., if connected via an egde). Then the method adds additional equidistand pixels lying on that line (if the value is double, convert t...
19,776
def x_sogs_raw( s: SigningKey, B: PublicKey, method: str, full_path: str, body: Optional[bytes] = None, *, b64_nonce: bool = True, blinded: bool = False, timestamp_off: int = 0, ): """ Calculates X-SOGS-* headers. Returns 4 elements: the headers dict, the nonce bytes, ti...
19,777
def get_param(param, content, num=0): """ 在内容中获取某一参数的值 :param param: 从接口返回值中要提取的参数 :param content: 接口返回值 :param num: 返回值中存在list时,取指定第几个 :return: 返回非变量的提取参数值 """ param_val = None if "." in param: patt = param.split('.') param_val = httprunner_extract(content, patt) ...
19,778
def make_thebig_df_from_data(strat_df_list, strat_names): """Joins strategy data frames into a single df - **The Big DF** - Signature of The Big DF: df(strategy, sim_prefix, exec, node)[metrics] """ thebig_df = pd.concat(strat_df_list, axis=0, keys=strat_names) thebig_df.index.set_names("strate...
19,779
def first_weekday_date(date): """ Filter - returns the date of the first weekday for the date Usage (in template): {{ some_date|first_weekday_date }} """ week_start = date - datetime.timedelta(days=date.weekday()) return week_start.date()
19,780
def isLto(): """*bool* = "--lto" """ return options.lto
19,781
def runtime(): """Get the CumulusCI runtime for the current working directory.""" init_logger() return CliRuntime()
19,782
def order_json_objects(obj): """ Recusively orders all elemts in a Json object. Source: https://stackoverflow.com/questions/25851183/how-to-compare-two-json-objects-with-the-same-elements-in-a-different-order-equa """ if isinstance(obj, dict): return sorted((k, order_json_objects(v)) for...
19,783
def _add_var_summary(var, name, collection=None): """ attaches a lot of summaries to a given tensor""" with tf.name_scope(name): with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean, collections=collection) with tf.name_scope('std...
19,784
def CalculatePEOEVSA(mol, bins=None): """ ################################################################# MOE-type descriptors using partial charges and surface area contributions. chgBins=[-.3,-.25,-.20,-.15,-.10,-.05,0,.05,.10,.15,.20,.25,.30] You can specify your own bins to compute som...
19,785
def plot_pre_post_errors( data: Optional[pd.DataFrame] = None, ) -> None: """ Input data should be the "flattened" dataset. """ # Load default data if data is None: data = flatten_access_eval_2021_dataset() # Make pre post chart with split by contacted chart = ( alt.Char...
19,786
def install_pyheif_from_pip() -> int: """ Install the python module pyheif from PIP. Assumes required libraries already installed :return: return code from pip """ print("Installing Python support for HEIF / HEIC...") cmd = make_pip_command( 'install {} -U --disable-pip-version-che...
19,787
def start_transfer(sip, accession_id, archivematica_id=None): """Start the archive process for a sip. Start the transfer of the sip in asynchronous mode. See :py:mod:`invenio_archivematica.tasks` :param sip: the sip to archive :type sip: :py:class:`invenio_sipstore.api.SIP` :param str accessio...
19,788
def adjust_mlb_names(mlb_id, fname, lname): """ Adjusts a prospect's first and last name (fname, lname) given their mlb.com player_id for better usage in matching to the professional_prospects table. """ player_mapper = { } qry = """SELECT wrong_name , right_fname , right_lname FROM...
19,789
def all_predicates(*predicates: Callable[[Any], bool]) -> Callable[[Any], bool]: """Takes a set of predicates and returns a function that takes an entity and checks if it satisfies all the predicates. >>> even_and_prime = all_predicates(is_even, is_prime) >>> even_and_prime(2) True >>> even_and...
19,790
def centered_rand(l): """Sample from U(-l, l)""" return l*(2.*np.random.rand()-1.)
19,791
def compute_rays_length(rays_d): """Compute ray length. Args: rays_d: [R, 3] float tensor. Ray directions. Returns: rays_length: [R, 1] float tensor. Ray lengths. """ rays_length = torch.norm(rays_d, dim=-1, keepdim=True) # [N_rays, 1] return rays_length
19,792
def _repeat_elements(arr, n): """ Repeats the elements int the input array, e.g. [1, 2, 3] -> [1, 1, 1, 2, 2, 2, 3, 3, 3] """ ret = list(itertools.chain(*[list(itertools.repeat(elem, n)) for elem in arr])) return ret
19,793
def get_neighbors_table(embeddings, method, ntrees=None): """ This is a factory method for cosine distance nearest neighbor methods. Args: embeddings (ndarray): The embeddings to index method (string): The nearest neighbor method to use ntrees (int): number of trees for annoy Returns: Nearest ne...
19,794
def _compute_positional_encoding( attention_type, position_encoding_layer, hidden_size, batch_size, total_length, seq_length, clamp_length, bi_data, dtype=tf.float32): """Computes the relative position encoding. Args: attention_type: str, the attention type. Can be "uni" (di...
19,795
def _get_instance_id(instance_list, identity): """ Return instance UUID by name or ID, if found. """ for i in instance_list.items: if identity in (i.properties.name, i.id): return i.id return None
19,796
def DBConnect(dwhName=None): """ Parameters ---------- dwhName : Default value = None) Returns ------- """ conn = mysql.connect(host=os.getenv('DBT_MYSQL_HOST'), user="root", database=dwhName, buffered=True) cur = conn.cursor() print("Successfu...
19,797
def isPageWatched(user, trunk): """Is the page being watched by the user?""" result = (models.Subscription.all(). filter('user =', user). filter('trunk =', trunk). filter('method !=', models.Subscription.METH_MEH)) return result.count(1) != 0
19,798
def main(): """主函数:设置窗口部件,指定按钮点击事件处理函数 """ window = tk.Tk() window.geometry("600x480") window.title("简单的图片查看器") canvas = tk.Canvas(window, width=600, height=440) canvas.pack(side="bottom") button = tk.Button(window, text="打开图片", command=lambda: openimage(c...
19,799