content
stringlengths
22
815k
id
int64
0
4.91M
def load(trange=['2013-11-5', '2013-11-6'], probe='15', instrument='fgm', datatype='1min', suffix='', downloadonly=False, no_update=False, time_clip=False): """ This function loads data from the GOES mission; this function is not meant to be...
72,100
def map_data_ea(*args): """ map_data_ea(insn, addr, opnum=-1) -> ea_t map_data_ea(insn, op) -> ea_t Map a data address. @param insn: the current instruction (C++: const insn_t &) @param addr: the referenced address to map (C++: ea_t) @param opnum: operand number (C++: int) """ return _ida...
72,101
def act(q, v): """ Returns the transformation (rotation) of a vector v by a unit-quaternion q. """ return compose(compose(q, np.insert(v, 0, 0)), invert(q))[1:]
72,102
def untile_data3D(data,(lentZ,lentY,lentX),(lenZ,lenY,lenX)): """ Reorganize tiled sparky data into 3D data Parameters: * data 1D numpy array of tile data * lentZ size of tile in Z (w1) dim * lentY size of tile in Y (w2) dim * lentX size of tile in X (w3) dim * lenZ size o...
72,103
def evenly_combine(objects, select=None): """ Evenly combine multiple objects into a single object. Parameters ----------- values: list of objects A list of objects to combine, the objects can be of any type as long as the selected object is either an iterable or a dict. select: fun...
72,104
def list_flavors(as_list=False): """ Print `openstack` server size (flavor) options. Set ``as_list`` to return a python list object. Usage: fab provider.list_flavors Flavors: +----+-------------------------+-----------+------+----------+-------+-------------+ | ID | ...
72,105
def shark_saved_queries(): """ Retrieve saved queries for a user/account GetParams: account: an account user: a user Returns: A json object conatining a list of saved queries """ error, user, account, _, handle = getRequestParameters(forceCluster=False) if error is ...
72,106
def do_StopDLJob(client, args): """Stop the DLJob.""" client.StopDLJob(args.id)
72,107
def is_remote_a_wordpress(base_url, error_page, downloader): """ This functions checks if remote host contains a WordPress installation. :param base_url: Base url :type base_url: basestring :param error_page: error page content :type error_page: basestring :param downloader: download func...
72,108
def CNOT(control: int, target: int) -> QCircuit: """ Convenience CNOT initialization Parameters ---------- control: int control qubit target: int target qubit Returns ------- QCircuit object """ return X(target=target, control=control)
72,109
def _find_latest_updates(): """Generate update documents from firestore in reverse order.""" query = ( get_db() .collection_group("updates") .order_by("date", direction=firestore.Query.DESCENDING) ) for doc_ref in query.stream(): doc = doc_ref.to_dict() location =...
72,110
def get_python_version(): """ A convenience function to get the python version used to run this tutorial. This ensures that the conda environment is created with an available version of python. """ import platform versions = {'3': '3.8'} return versions[platform.python_version_tuple()[0]...
72,111
def read_json(file_path: str) -> dict: """Reads json file from the given path. Args: file_path (str): Location of the file Returns: dict: Json content formatted as python dictionary in most cases """ with open(file_path, "r") as f: return json.load(f)
72,112
def backwards(apps, schema_editor): """ As the ManyToMany relationship between units & referrals is created in 0040, we do not need to do anything as all existing relations will disappear along with the relationship. """ pass
72,113
def join_stmts( stmts: List[str], opts: PrintOptions, delimiter: str = "," ) -> str: """A convenience method for joining statements when the entire stmt list is already known""" return JoinPrinter(delimiter=delimiter, stmt_list=stmts).to_string(opts)
72,114
def create_tables(): """create db if don't exists and fill it with tables""" connect = sqlite3.connect("db.db") conn = connect.cursor() conn.execute("""CREATE TABLE IF NOT EXISTS assets( timestamp TEXT, amount REAL, currency TEXT, note ...
72,115
def ensure_gh_token(token: str): """ Raise token error if token is valid by requesting github """ httpx_headers = httpx.Headers( {"User-Agent": "GitHubClassroomUtils/1.0", "Authorization": f"token {token}",} ) res = httpx.get("https://api.github.com/user", headers=httpx_headers) if r...
72,116
def str_is_none(source): """ 判断字符串不为空 """ if source == '' or source == 'NULL' or source == 'None' or source is None: return True return False
72,117
def initialize_pt( blk, state_args=None, outlvl=idaeslog.NOTSET, solver=None, optarg=None ): """ Initialization routine for pass-through unit models. Keyword Arguments: state_args : a dict of arguments to be passed to the property package(s) to provide an initial state fo...
72,118
def atttyp(att: str) -> str: """ Helper function to return attribute type as string :param str: attribute type e.g. 'U002' :return type of attribute as string e.g. 'U' :rtype str """ return att[0:1]
72,119
def lin2freq(n_lin): """Compatibility hack to allow for linearly spaced cosine filters with `make_erb_cos_filters_nx`; intended to generalize the functionality of `make_lin_cos_filters`. """ return _identity(n_lin)
72,120
def lower_confidence_bound(num_class_A: int, num_samples: int, alpha: float) -> float: """ Computes a lower bound on the probability of the event occuring in a Bernoulli distribution. Parameters ---------- num_class_A: int The number of times the event occured in the samples. num_samples...
72,121
def get_weather_units(units): """returns a str representation of units of measurement that corresponds to given system of units. if units is 'metric' return °C if units is 'kelvin' return K by default if units is 'imperial' return °F Parameters ---------- :param str units: the system of un...
72,122
def trca_feature(W: ndarray, X: ndarray, n_components: int = 1) -> ndarray: """Return trca features. Modified from https://github.com/mnakanishi/TRCA-SSVEP/blob/master/src/test_trca.m Parameters ---------- W : ndarray spatial filters from csp_kernel, shape (n_channels, n_filters) ...
72,123
def check_multiple_shot_nodes(progress_controller=None): """Single shot node in the scene checks if there are multiple shot nodes """ if progress_controller is None: progress_controller = ProgressControllerBase() shot_nodes = pm.ls(type='shot') progress_controller.maximum = len(shot_no...
72,124
def get_data(flist): """ Extract data to pandas dataframes from all files in flist. All coordinates should be same within all phi files in this directory. Parameters ---------- flist - list of phi file names to read from CHARMM PBEQ output Returns ------- crds - X Y Z coordinates f...
72,125
def arm_and_takeoff(vehicle, aTargetAltitude): """ Arms vehicle and fly to aTargetAltitude. """ print("Basic pre-arm checks") # Don't let the user try to arm until autopilot is ready while not vehicle.is_armable: print(" Waiting for vehicle to initialise...") time.sleep(1) ...
72,126
def unescaper(msg): """ unescape message this function undoes any escape sequences in a received message @param msg: the message to unescape @return: the unescaped message """ out = [] escape = False for x in msg: if x == 0x5c: escape = True continue ...
72,127
def motor_display_status(): """ display motors status """ print "------------------------------------------" print "Left motor direction is ", fpga_read(motorPwmDirectionLeftRegister) print "Left motor speed is ", fpga_read(motorPwmSpeedLeftRegister) print "Right motor direction is ", ...
72,128
def test_kmeans(): """ Helper function to check the correctness of kmeans clustering algorithm Tests: - kmeans with 4 clusters and scale=1 returns a plot similar to that of the provided example - kmeans returns an error if the provided k<2 - kmeans returns an error if the number of observations < provided ...
72,129
def public_tables(self, node=None): """Check that a user with no privilege is able to select from public tables.""" user_name = f"user_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name}"): with When("I check the user is able to select on system.one"): ...
72,130
def db_revision(c, dir=DEFAULT_MIGRATION_DIR): """ Generate new empty revision script. """ with app.app_context(): migrate.revision(directory=dir)
72,131
def squarest_of(c, sort_key=None, reverse_on_key=False): """Returns the :term:`squarest` member of `c`, a collection of numbers. If there are multiple perfect squares, `sort_key` is used to pick a single one. Parameters ---------- c : iterable of int A collection of integers. so...
72,132
def compute_curvature(point1: geom.Point, point2: geom.Point, point3: geom.Point) -> float: """ Estimate signed curvature along the three points. :param point1: First point of a circle. :param point2: Second point of a circle. :param point3: Third point of a circle. :return signed curvature of t...
72,133
def groupby_many_reduce(key: Callable, reducer: Callable, seq: Iterable): """Group a collection by a key function, when the value is given by a reducer function. Parameters: key (Callable): Key function (given object in collection outputs key). reducer (Callable): Reducer function (given object in coll...
72,134
def compare_modules(file_, imports): """Compare modules in a file to imported modules in a project. Args: file_ (str): File to parse for modules to be compared. imports (tuple): Modules being imported in the project. Returns: tuple: The modules not imported in the project, but do e...
72,135
def categorize(state): """ Given a state, categorize it as winning(good)=0/ losing(bad)=1/ tie=2 or incomplete game=3 state""" if (state[0][0] == 2 and state[0][1] == 2 and state[0][2] == 2) or ( state[1][0] == 2 and state[1][1] == 2 and state[1][2] == 2) or ( state[2][0] == 2 and state[2][1] == 2 and state[2...
72,136
def run_command(cmd, cwd=os.getcwd(), stdout=False, stderr=False): """Execute a single command and return STDOUT and STDERR.""" stdout, stdout_str = output_handler(stdout) stderr, stderr_str = output_handler(stderr, redirect='2>') p = subprocess.Popen(cmd, stdout=stdout, stderr=stderr, cwd=cwd) ou...
72,137
def _FetchAllFiles(input_api, white_list, black_list): """Hack to fetch all files.""" # We cannot use AffectedFiles here because we want to test every python # file on each single python change. It's because a change in a python file # can break another unmodified file. # Use code similar to InputApi.FilterSo...
72,138
def __split2contiguous(levels): """ Function __split2contiguous(levels) takes list of split intervals and make it contiguous if possible """ tmplevs = [] for il in range(len(levels)): lv = levels[il] if not (isinstance(lv, list) or isinstance(lv, tuple)): raise VCSUtilsEr...
72,139
def create_app(): """Create and configure an instance of the Flask application.""" app = Flask(__name__, static_folder='react') app.secret_key = b'cs3235privatepartsyo' # Initialize firebase # register api commands from . import api app.register_blueprint(api.bp) @app.route('/pwn/<path...
72,140
def test_clock_datetime_timezone(fake_qtile, monkeypatch, fake_window): """ test clock with datetime timezone """ class FakeDateutilTZ: class TZ: @classmethod def gettz(cls, val): None tz = TZ # Set up references to pytz and dateutil so we know these...
72,141
def _programs_with_attribute(attr): """ get a list of modules with a given attribute """ progs = [] for prog in PROGRAM_MODULE_NAMES.keys(): module = _import_module(prog) if hasattr(module, attr): progs.append(prog) return progs
72,142
def recursive_decode(s:str, level=9, method=[]) -> str: """ Recursive decode `s`(encoded by `recursive_encode`) using base64, `level` is depth of recursive, the max value is 32 """ assert 0 < level <= 32 if not isinstance(s, (bytearray, bytes)): s = bytes(s, 'utf-8') if method: f...
72,143
def _load_data(dataset, is_training=False): """Load input data, target values and file names for a dataset. The input data is assumed to be a dataset of feature vectors. These feature vectors are standardized using a scaler that is either loaded from disk (if it exists) or computed on-the-fly. The latt...
72,144
def get_envelope(t_note_length, t_attack=0.010, t_release=0.3, sr=16000): """Create an attack sustain release amplitude envelope.""" t_note_length = min(t_note_length, 3.0) i_attack = int(sr * t_attack) i_sustain = int(sr * t_note_length) i_release = int(sr * t_release) i_tot = i_sustain + i_release # atta...
72,145
def create_update(table, columns: dict, filters: dict): """ :param table: :param columns: dict: :param filters: dict: """ table = Table(table) query = Query.update(table) for k, v in columns.items(): query = query.set(k, v) query = set_query_filters(filters, query, table) ...
72,146
def new_recipe(request): """Создание рецепта '/new' """ user = User.objects.get(username=request.user) form = RecipeForm(request.POST or None, files=request.FILES or None) ingredients = get_ingredients(request) if not form.is_valid(): return render( request, 'new_re...
72,147
def assign_random_category(resource): """ Assign a random category to a resource """ random_index = randint(0, TopicCategory.objects.all().count() - 1) tc = TopicCategory.objects.all()[random_index] resource.category = tc resource.save()
72,148
def get_nameservers(): """Returns the available nameservers.""" return requests.get( 'https://api.cloudns.net/dns/available-name-servers.json', params=get_auth_params())
72,149
def gather_models(): """ Inspect sqlalchemy models from current context and set global dictionary to be used in url conversion. """ global MODELS from flask import current_app if 'sqlalchemy' not in current_app.extensions: return check = current_app.config['AUTHORIZE_IGNORE_PROP...
72,150
def touch(fs: FileSystem, name: str): """ 新建文件 :param fs: :param name: :return: """ if name == '-h': print(""" 新建文件 touch file_name 不可跨目录层级调用 """) return pwd_cat = fs.load_pwd_obj() # 当前目录 flag, info = pwd_cat.check_name(name)...
72,151
def test_figure_saver_instance(debug, expected_filetype): """An FigureSaver instance should be used to set defaults, not the class. This is to avoid unintentionally overriding defaults for different modules. """ def get_defaults(): return [ getattr(FigureSaver, attr) f...
72,152
def load_data(raw=None): """ load data to development workspaces Parameters -------------- raw: (bool) if True, function returns cleaned dataset. return (df) data frame of data and its labels """ raw_data = [] with open('./data/cyber_data.json') as f: for line in f: ...
72,153
def nearer(lons, lats, lon, lat, tolerance=np.inf, max_sites=None): """Nearer stations in (lons, lats) to site (lon, lat). Args: lons (array): Longitudes of stations to search. lats (array): Latitudes of stations to search. lon (float): Longitude of of station to locate from lons. ...
72,154
def draw_perm_reps_diff_mean(x, y, size=1): """Generate array of permuation replicates.""" out = np.empty(size) for i in range(size): x_perm, y_perm = draw_perm_sample(x, y) out[i] = np.mean(x_perm) - np.mean(y_perm) return out
72,155
def del_files_by_ext(dir, *exts): """Delete file(s) from 'dir' based the passed file extensions Accepts one or more file extensions (with no '.') """ files_to_delete = dir_list_filter_by_ext( dir, *exts, derivedDir=True ) for f in files_to_delete: delete_file(f)
72,156
def pois_llik(y, eta): """Return ln p(y | eta) assuming y ~ Poisson(exp(eta)) This implementation supports broadcasting eta (i.e., sharing parameters across observations). :param y: tensor :param eta: tensor :returns llik: tensor (y.shape) """ return y * eta - safe_exp(eta) - torch.lgamma(y + 1)
72,157
def drop_db(): """Drops the database""" client = MongoClient("mongodb://localhost:27017/") client.drop_database("exchange4students") print("Database successfully dropped") print("----------------------------------------------")
72,158
def set_interface(iface): """Helper to set the global internet interface""" global _the_interface # pylint: disable=invalid-name, global-statement _the_interface = iface socket.set_interface(iface)
72,159
def plot_with_gradient(xs: List[datetime], ys: List[float], color: str, ax=None, **kwargs) -> None: """ Plot the given lists of x-values and y-values with a gradient color fill under it. Credit to https://stackoverflow.com/a/29331211 and https://stackoverflow.com/a/31163913 ...
72,160
def get_docx_text(path): """ Take the path of a docx file as argument, return the text in unicode. """ document = zipfile.ZipFile(path) xml_content = document.read('word/document.xml') document.close() tree = XML(xml_content) paragraphs = [] for paragraph in tree.getiterator(PARA): ...
72,161
def buildPlots(): """ Builds the histograms from the simulated games. """ # Candidate words are those of the top 100 starting entropy data = Data("DUMMY") candidates = [] top = data.giveTop(100) for row in top: candidates.append(row[0]) # Simulate these and plot their histog...
72,162
def config_unconfig_interface_ip_addresses(dut, if_data_list=[], config='add',cli_type='',ip_type=''): """ Configure IP addresses on multiple interfaces Author: Naveena Suvarna (naveen.suvarna@broadcom.com) :param dut: :param if_data_list: :param config: :return: """ if config != 'a...
72,163
async def rank(botti, message, botData): """ Für alle ausführbar Dieser Befehl zeigt deine Position im Cookie-Ranking an. !rank {@USER} {@USER} leer, Nutzer-Erwähnung !rank\r!rank @ETIT-Chef """ user = message.author if len(message.mentions) != 0: user = message.mention...
72,164
def compare_with_ties(a, b): """ Comparison function for two items with the condition that if they are equal, one of the two values is randomly selected to be greater than the other. Arguments a - the first item to compare b - the second item to compare Returns: -1 if a < b...
72,165
def store(src, rel, dst): """ Returns an SQL statement to store an edge into the SQL backing store. :param src: The source node. :param rel: The relation. :param dst: The destination node. """ smt = 'INSERT INTO %s (src, dst) VALUES (?, ?)' return smt % rel, (src, dst)
72,166
def make_node_dict(node_dict, xml_dict, hch_id, hch_tag, parent, classification_orpha): """ Recursively parse xml_dict to output a collection of Disorder with all their children :param node_dict: Dictionary of Disorders i.e. {2846: { "Preferred term": "Congenital pericardium anomaly", "...
72,167
def fateman_poly_F_1(n): """Fateman's GCD benchmark: trivial GCD """ Y = [Symbol('y_' + str(i)) for i in range(n + 1)] y_0, y_1 = Y[0], Y[1] u = y_0 + Add(*[y for y in Y[1:]]) v = y_0**2 + Add(*[y**2 for y in Y[1:]]) F = ((u + 1)*(u + 2)).as_poly(*Y) G = ((v + 1)*(-3*y_1*y_0**2 + y_1**2 -...
72,168
def markdown(value): """ Converts the specified markdown string to HTML Args: value (str): Markdown string Returns: string: HTML equivalent """ return markdown2.markdown(value)
72,169
def irpf(base, porcentaje=12.5,prorrateado=False): """ irpf (sueldo,porcentaje, prorrateado=boolean) """ if prorrateado: cantidad_prorateada = base/6 if type(base)==float and type(porcentaje)==float: return (base/100) * porcentaje else: return None
72,170
def get_data_loader(data_config: dict, split: str) -> Optional[DataLoader]: """ Return the corresponding data loader. Can't be placed in the same file of loader interfaces as it causes import cycle. :param data_config: a dictionary containing configuration for data :param split: must be train/vali...
72,171
def generatepin(length=4): """Generates a PIN number of the specified length.""" return generatepass(length, string.digits, exclude_similar_chars=False)
72,172
def read_p2g(path): """Read graph in p2g format from path. Returns an MultiDiGraph. If you want a DiGraph (with no self loops allowed and no edge data) use D=networkx.DiGraph(read_p2g(path)) """ fh=_get_fh(path,mode='r') G=parse_p2g(fh) return G
72,173
def get_by_index(items, index): """ Return an element of a list based on its index. Usage in template:: {% load list_to_columns %} {{ items|get_by_index:0 }} Args: ``items`` (list): A list of elements. ``index`` (int): The position of the element to be returned. ...
72,174
def admin_ide_stop_id(id: str): """ Stop a specific IDE :return: """ # Search for the theia session session = TheiaSession.query.filter( TheiaSession.id == id, TheiaSession.course_id == course_context.id, ).first() # Verify it exists req_assert(session is not None,...
72,175
def test_upper_to_full(): """Test upper_to_full function.""" a = np.arange(9).reshape(3, 3) a += a.T upper = a[np.triu_indices(3)] assert_array_equal(utils.upper_to_full(upper), a)
72,176
def lci_instance_id(): """Id for the low-cost instance.""" return f"lci-instance-{uuid.uuid4().hex[:10]}"
72,177
def lookup_in_cdx(qurl, target_date=None): """ Checks if a resource is in the CDX index, closest to a specific date: :return: """ matches = list_from_cdx(qurl) if len(matches) == 0: return None, None, None # Set up default: if target_date is None: target_date = datetime...
72,178
def command_exists(command): """ Check if the given command was registered. In another words if it exists. """ for category, commands in command_categories.items(): for existing_command in commands: if existing_command.match(command): return True return False
72,179
def users_search(client: Client, args: Dict) -> CommandResults: """Search users Args: client: Client object with request. args: Usually demisto.args() Returns: Outputs. """ email = str(args.get('email', '')) query = str(args.get('query', '')) size = str(args.get('si...
72,180
def test_dataset_download(nids_url): """Test using the download method to download entire dataset.""" cat = TDSCatalog(nids_url) temp = os.path.join(tempfile.gettempdir(), 'siphon-test.temp') try: assert not os.path.exists(temp) cat.datasets[0].download(temp) assert os.path.exist...
72,181
def plot_donut_chart(df, col, **kwargs): """ Creates a custom donut chart for a specific column Parameters ---------- :param df: dataset used for plotting [type: pd.DataFrame] :param col: column name to be plotted [type: string] :param **kwargs: additional parameters :arg figsiz...
72,182
def list_files(): """ List some of the files on the Drive. :returns: A dictionary containing the list of file-details. """ results = file_service.list( pageSize=10, fields="files(id, name)").execute() return results
72,183
def onwindowcreate(window_name, fn_name, *args): """ On window create, call the function with given arguments @param window_name: Window name to look for, either full name, LDTP's name convention, or a Unix glob. @type window_name: string @param fn_name: Callback function @type fn_name: fun...
72,184
def expand(entity_id): """Returns a list of diagrams for the role --- get: summary: Expand an entity to get its adjacent entities description: >- Get the property-wise list of entities adjacent to the entity with id `entity_id`. parameters: - in: path name: en...
72,185
def main(): """Running main functions""" if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_...
72,186
def test_ret_tuple(): """Test tuple return type. Check types and semantic equivalence.""" mod = tvm.IRModule() shape = (10, 10) dtype = "float32" t = relay.TensorType(shape, dtype) x = relay.var("x", t) # f(x) = (x,x) func = relay.Function([x], relay.Tuple([x, x * relay.const(2.0)])) ...
72,187
def all_global_vars(x): """ Find all globals accessed by an object. """ # Define internal recursively called function to enable tracking of the # recursion level: def recursive(x, seen=set(), level=0): # Get locals of scope in which allglobalvars() was invoked; the # following ...
72,188
def profiler(*args, **kwargs): """ The profiler is used to record timing information from key events within Maya, as an aid in tuning the performance of scenes, scripts and plug-ins. User written plug-ins and Python scripts can also generate profiling information for their own code through the MProfilin...
72,189
def upgrade(): """Upgrade the database to a newer revision.""" pass
72,190
def get_model_preds(CP): """Reads in or generates model predictions. Parameters ---------- CP : dict Containins directory locations for loading data and storing predictions. Returns ------- craters : h5py Model predictions. """ n_imgs, dtype = CP['n_imgs'], ...
72,191
def detach(): """ Detaches a specified device """ scsi_id = request.form.get("scsi_id") unit = request.form.get("unit") process = ractl.detach_by_id(scsi_id, unit) if process["status"]: flash(_("Detached SCSI ID %(id_number)s LUN %(unit_number)s", id_number=scsi_id, unit_...
72,192
def es_cleaned(es_instance, _client): """Pass-through of es_instance, but ensures ES is cleaned on every test invocation.""" try: _client.indices.delete("_all") except TransportError as e: raise Exception("Could not clean ES.") from e yield es_instance
72,193
def test_atomic_unsigned_byte_min_exclusive_1_nistxml_sv_iv_atomic_unsigned_byte_min_exclusive_2_3(mode, save_output, output_format): """ Type atomic/unsignedByte is restricted by facet minExclusive with value 172. """ assert_bindings( schema="nistData/atomic/unsignedByte/Schema+Instance/NIS...
72,194
def _sync_validated_visa_authorization( gen3_user, ga4gh_visas, expiration, db_session=None ): """ Wrapper around UserSyncer.sync_single_user_visas method, which parses authorization information from the provided visas, persists it in Fence, and syncs it to Arborist. IMPORTANT NOTE: THIS DOES N...
72,195
def weld_range(start, stop, step): """Create a vector for the range parameters above. Parameters ---------- start : int stop : int or WeldObject Could be the lazily computed length of a WeldObject vec. step : int Returns ------- WeldObject Representation of this com...
72,196
def _capture(which='stdout', printonly=None): """private method, should not be called directly (cf. capture_stdout() and capture_stderr()) """ assert which in ('stdout', 'stderr' ), "Can only capture stdout or stderr, not %s" % which if which == 'stdout': fd = 1 else: fd ...
72,197
def flatten(d): """Return a dict as a list of lists. >>> flatten({"a": "b"}) [['a', 'b']] >>> flatten({"a": [1, 2, 3]}) [['a', [1, 2, 3]]] >>> flatten({"a": {"b": "c"}}) [['a', 'b', 'c']] >>> flatten({"a": {"b": {"c": "e"}}}) [['a', 'b', 'c', 'e']] >>> flatten({"a": {"b": "c", "...
72,198
def plot_pair(img, adv, model=None, suptitle=None): """ Visualize clean image, purturbation, and adversarial example # Arguments img: np.array The clean image with shape (w, h, 3) adv: np.array The adversarial example with shape (w, h, 3) model: keras model ...
72,199