code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(LocationWebAddressForm, self).__init__(*args, **kwargs) <NEW_LINE> self.fields['web_address'].widget.attrs.update({'class': 'form-control dm-form label-up-can'}) <NEW_LINE> self.fields['web_address_type'].widget.attrs.update({'class': 'form-control drop-me...
:param args: :param kwargs:
625941d26aa9bd52df036f63
def _init_export_dir(self): <NEW_LINE> <INDENT> export_dir = '/'.join([x for x in self._export_path.split('/')[:-1]]) <NEW_LINE> if not os.path.exists(export_dir): <NEW_LINE> <INDENT> os.makedirs(export_dir) <NEW_LINE> <DEDENT> if os.path.isfile(self._export_path) == False: <NEW_LINE> <INDENT> headers = ['time', 'actio...
Init export dir and file if needed
625941d23317a56b86939e15
def fetch_feed_content(url): <NEW_LINE> <INDENT> r = requests.get(url) <NEW_LINE> if r.status_code == 200: <NEW_LINE> <INDENT> return r.content <NEW_LINE> <DEDENT> return ""
Fetches the content from the supplied url
625941d2e1aae11d1e749e77
def setUp(self) -> None: <NEW_LINE> <INDENT> self.ts = datetime.datetime.now() <NEW_LINE> self.settings = Settings() <NEW_LINE> self.window_list = WindowList() <NEW_LINE> self.group_id = group_name_to_group_id('test_group')
Pre-test actions.
625941d230c21e258bdfa65d
def getBaseExpConfig(args): <NEW_LINE> <INDENT> if not os.path.isfile(args.base_config): <NEW_LINE> <INDENT> printRed("You must specify a valid --base-config json file") <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> args.data_folder = parseDataFolder(args.data_folder) <NEW_LINE> dataset_path = "data/{}".format(args.data_f...
:param args: (parsed args object) :return: (str)
625941d2f9cc0f698b1407ba
def login_required(f): <NEW_LINE> <INDENT> @wraps(f) <NEW_LINE> def x(*args, **kwargs): <NEW_LINE> <INDENT> if 'username' not in login_session: <NEW_LINE> <INDENT> print ('username not in login_session') <NEW_LINE> return redirect('/login') <NEW_LINE> <DEDENT> return f(*args, **kwargs) <NEW_LINE> <DEDENT> return x
Checks to see whether a user is currently logged in.
625941d223849d37ff7b324e
def hexbin(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def func_wrapper(inst, *args, **kwargs): <NEW_LINE> <INDENT> newargs = [] <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> if isinstance(arg, (list, tuple)): <NEW_LINE> <INDENT> newargs.append(listchanger(arg)) <NEW_LINE> <DEDENT> elif isinstance(arg, dict): ...
Decorator for functions of taker and maker receiving over the wire AMP arguments that may be in hex or hextxid:n format and converting all to binary. Functions to which this decorator applies should have all arguments be one of: - hex string (keys), converted here to binary - lists of keys or txid:n strings (converted ...
625941d25fdd1c0f98dc03f3
def enhance_next(self, instruction): <NEW_LINE> <INDENT> next_addr = None <NEW_LINE> if instruction.condition in (True, None): <NEW_LINE> <INDENT> next_addr = self.next(instruction) <NEW_LINE> <DEDENT> instruction.target = None <NEW_LINE> if next_addr is None: <NEW_LINE> <INDENT> next_addr = instruction.address + instr...
Adds a ``next`` field to the instruction. By default, it is set to the address of the next linear instruction. If the instruction is a non-"call" branch and either: - Is unconditional - Is conditional, but is known to be taken And the target can be resolved, it is set to the address of the jump target.
625941d2ec188e330fd5a95c
def test02_types(self): <NEW_LINE> <INDENT> typecodes = ['int8', 'int16', 'int32', 'int64', 'uint8', 'uint16', 'uint32', 'uint64', 'float32', 'float64', 'complex64', 'complex128'] <NEW_LINE> for name in ('float16', 'float96', 'float128', 'complex192', 'complex256'): <NEW_LINE> <INDENT> atomname = name.capitalize() + 'A...
Data integrity during recovery (numerical types)
625941d2851cf427c661a6cd
def setShiftedSpacecraftPosition(header, xyz, shiftedDate): <NEW_LINE> <INDENT> x,y,z = xyz <NEW_LINE> date = getPhotoTime(header) <NEW_LINE> if date is None: <NEW_LINE> <INDENT> raise ValueError('DATE-OBS needs to be set before setting the shifted date') <NEW_LINE> <DEDENT> delta = (shiftedDate - date).total_seconds()...
Add the spacecraft position at the given shifted photo time in cartesian GCRS coordinates to header cards POSXSHIF, POSYSHIF, POSZSHIF, DATESHIF. :param ndarray xyz: [x,y,z] position of spacecraft at 'date' :param datetime shiftedDate: the shifted photo time
625941d23c8af77a43ae3960
def linear_regression(): <NEW_LINE> <INDENT> with tf.variable_scope("prepare_data"): <NEW_LINE> <INDENT> X = tf.random_normal(shape=[100, 1], name="feature") <NEW_LINE> y_true = tf.matmul(X, [[0.8]]) + 0.7 <NEW_LINE> <DEDENT> with tf.variable_scope("creat_model"): <NEW_LINE> <INDENT> weights = tf.Variable(initial_value...
自实现一个线性回归 :return:
625941d291af0d3eaac9bbd9
def update(self, data): <NEW_LINE> <INDENT> if "options" in data: <NEW_LINE> <INDENT> self.options = data["options"] <NEW_LINE> <DEDENT> if "members" in data: <NEW_LINE> <INDENT> self.members = data["members"] <NEW_LINE> <DEDENT> if "teams" in data: <NEW_LINE> <INDENT> self.teams = data["teams"] <NEW_LINE> <DEDENT> if ...
Updates the github configuration with the configuration data passed in
625941d23617ad0b5ed680b7
def add_start_end_token_2_list_token(list_of_list_token): <NEW_LINE> <INDENT> return list(map(lambda x: [TOKEN_START] + x + [TOKEN_END], list_of_list_token))
add <start> and <end> tokens to the start and the end of list_token respectively
625941d2a17c0f6771cbe20f
def __delitem__(self, *args): <NEW_LINE> <INDENT> return _pypl.StringVector___delitem__(self, *args)
__delitem__(StringVector self, std::vector< std::string >::difference_type i) __delitem__(StringVector self, PySliceObject * slice)
625941d2b5575c28eb68e1c0
def save(self, commit=True): <NEW_LINE> <INDENT> project = super(ProjectForm, self).save(commit=False) <NEW_LINE> viewers_group = project.get_viewers_group() <NEW_LINE> collaborators_group = project.get_collaborators_group() <NEW_LINE> users = User.objects.all().exclude(id=project.ownerID) <NEW_LINE> viewers = self.cle...
Overriden method that add and remove users from groups
625941d2d7e4931a7ee9e0de
def getone(self, key): <NEW_LINE> <INDENT> key = self._encode_key(key) <NEW_LINE> return self._decode_value(self.multi.getone(key))
Get one value matching the key, raising a KeyError if multiple values were found.
625941d28c3a87329515857b
def pattern_search(search_pattern): <NEW_LINE> <INDENT> needle = search_pattern <NEW_LINE> try: <NEW_LINE> <INDENT> if needle.startswith("0x"): <NEW_LINE> <INDENT> needle = needle[2:] <NEW_LINE> needle = bytearray.fromhex(needle).decode("ascii") <NEW_LINE> needle = needle[::-1] <NEW_LINE> <DEDENT> <DEDENT> except (Valu...
Search for search_pattern in pattern. Convert from hex if needed Looking for needle in haystack
625941d24a966d76dd5511cf
def test_transaction_nesting(self): <NEW_LINE> <INDENT> if connection.vendor != 'mysql': <NEW_LINE> <INDENT> raise unittest.SkipTest('Only works on MySQL.') <NEW_LINE> <DEDENT> def do_nothing(): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> commit_on_success_with_read_committed(do_nothing)() <NEW_LINE> with commit_on_...
Test that the decorator raises an error if there are already more than 1 levels of nested transactions.
625941d27c178a314d6ef620
@memberOf(SConsEnvironment) <NEW_LINE> def ProductDir(env, product): <NEW_LINE> <INDENT> from . import eupsForScons <NEW_LINE> global _productDirs <NEW_LINE> try: <NEW_LINE> <INDENT> _productDirs <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _productDirs = eupsForScons.productDir(eu...
Return the product directory. Parameters ---------- product : `str` The EUPS product name. Returns ------- dir : `str` The product directory. `None` if the product is not known.
625941d24e696a04525c960b
def forwardFD(u,x,h): <NEW_LINE> <INDENT> return (u(x+h)-u(x))/h
Esquema de diferencias finitas hacia adelante. Parameters ---------- u : función. Función a evaluar. x : array Lugar(es) donde se evalúa la función h : array Tamaño(s) de la diferencia entre u(x+h) y u(x). Returns ------- Cálculo de la derivada numérica hacia adelante.
625941d27c178a314d6ef621
def get_sale_base_subtotal(self): <NEW_LINE> <INDENT> subtotal = self.get_items().sum(Round(LoanItem.quantity * LoanItem.base_price, DECIMAL_PRECISION)) <NEW_LINE> return currency(subtotal)
Get the base subtotal of items Just a helper that, unlike :meth:`.get_sale_subtotal`, will return the total based on item's base price. :returns: the base subtotal
625941d267a9b606de4a8078
def menu_context(): <NEW_LINE> <INDENT> menu, created = MenuOptions.objects.get_or_create() <NEW_LINE> menu_data = {'menu_data': json.loads(menu.JSON_menu)} <NEW_LINE> return menu_data
Helper function for navigation. :return: dictionary object containing available charts
625941d2046cf37aa974cf06
def item(*args, **kwargs): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> for arg in args: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ret[arg] = __grains__[arg] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if salt.utils.data.is_true(kwargs.get("sanitize")): <NEW_LINE> <INDENT> f...
Return one or more grains CLI Example: .. code-block:: bash salt '*' grains.item os salt '*' grains.item os osrelease oscodename Sanitized CLI Example: .. code-block:: bash salt '*' grains.item host sanitize=True
625941d2442bda511e8be5d6
def run_it(command): <NEW_LINE> <INDENT> logger.info(f"Executing command: {command}") <NEW_LINE> try: <NEW_LINE> <INDENT> if sys.version_info >= (3, 7): <NEW_LINE> <INDENT> completed_process = subprocess.run( command, capture_output=True, shell=True, check=True ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> completed_...
External command execution helper. Returns the completed process.
625941d2293b9510aa2c3455
def process_preference(preferences, preference, source): <NEW_LINE> <INDENT> key=preference.get("key",None) <NEW_LINE> site=preference.get("site",None) <NEW_LINE> group=preference.get("group",None) <NEW_LINE> user=preference.get("user",None) <NEW_LINE> namespace=preference.get("namespace",None) <NEW_LINE> language_code...
Process a preference :param preferences: common preferences dict :param preference: simple dict
625941d2d4950a0f3b08c50d
def change_units(self): <NEW_LINE> <INDENT> success = self._validate_input() <NEW_LINE> if not success: <NEW_LINE> <INDENT> return success <NEW_LINE> <DEDENT> self.power = int(self.power_input.text()) <NEW_LINE> flux_string = self.flux_combo.currentText() <NEW_LINE> self.spectral_flux_density = u.Unit(flux_string) <NEW...
This function is called when accept is pressed on the unit conversion gui :return: (bool) True if unit update is successful
625941d2796e427e537b0787
def flatten(items): <NEW_LINE> <INDENT> for x in items: <NEW_LINE> <INDENT> if isinstance(x, Iterable) and not ( isinstance(x, six.string_types) or isinstance(x, six.binary_type) ): <NEW_LINE> <INDENT> for item in flatten(x): <NEW_LINE> <INDENT> yield item <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> yield x
https://stackoverflow.com/a/40857703
625941d215baa723493c4136
def create_organization(self, slug=None): <NEW_LINE> <INDENT> if not slug: <NEW_LINE> <INDENT> slug = generate_random_slug() <NEW_LINE> while Organization.objects.filter(slug=slug).exists(): <NEW_LINE> <INDENT> slug = generate_random_slug() <NEW_LINE> <DEDENT> <DEDENT> organization = Organization(slug=slug) <NEW_LINE> ...
Create a 'default' organization with some standard values so it can be saved to the database, but allow for overriding. The returned object is not yet saved to the database.
625941d2ad47b63b2c50a13f
def has_unique(word): <NEW_LINE> <INDENT> all_unique = True <NEW_LINE> for index, letter in enumerate(word): <NEW_LINE> <INDENT> for next_letter in word[index + 1:]: <NEW_LINE> <INDENT> if letter == next_letter: <NEW_LINE> <INDENT> all_unique = False <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> if not all_unique: <NEW...
:returns: True if the <word> has all unique characters, False otherwise without additional structure :param str word: a string O(n2)
625941d229b78933be1e586a
def run_encoder(self, sess, batch): <NEW_LINE> <INDENT> feed_dict = self._make_feed_dict(batch, just_enc=True) <NEW_LINE> (enc_states, query_states, dec_in_state, global_step) = sess.run( [self._enc_states, self._query_states, self._dec_in_state, self.global_step], feed_dict) <NEW_LINE> if FLAGS.mode == 'decode' and FL...
For beam search decoding. Run the encoder on the batch and return the encoder states and decoder initial state. Args: sess: Tensorflow session. batch: Batch object that is the same example repeated across the batch (for beam search) Returns: enc_states: The encoder states. A tensor of shape [batch_size, <...
625941d2b545ff76a8913fd5
def add_observer_(module): <NEW_LINE> <INDENT> for child in module.children(): <NEW_LINE> <INDENT> if type(child) == nnq.FloatFunctional: <NEW_LINE> <INDENT> if hasattr(child, 'qconfig') and child.qconfig is not None: <NEW_LINE> <INDENT> child.activation_post_process = child.qconfig.activation() <NEW_LINE> <DEDENT> <DE...
Add observer for the leaf child of the module. This function insert observer module to all leaf child module that has a valid qconfig attribute. Args: module: input module with qconfig attributes for all the leaf modules that we want to quantize Return: None, module is modified inplace with added observer mo...
625941d245492302aab5e484
def boxify(astr, border="#", margin=1): <NEW_LINE> <INDENT> if len(border) > 1: <NEW_LINE> <INDENT> raise ValueError("border must be one character long") <NEW_LINE> <DEDENT> lstr = astr.split("\n") <NEW_LINE> width = max([len(x) for x in lstr]) <NEW_LINE> lstr_padded = ['{:<{width}}'.format(x, width=width) for x in lst...
Prints the string in a pretty box e.g. >> print(boxify("hello")) ######### # # # hello # # # #########
625941d20a366e3fb873e9db
def postprocess_batch_so_far(self): <NEW_LINE> <INDENT> pre_batches = {} <NEW_LINE> for agent_id, builder in self.agent_builders.items(): <NEW_LINE> <INDENT> pre_batches[agent_id] = ( self.policy_map[self.agent_to_policy[agent_id]], builder.build_and_reset()) <NEW_LINE> <DEDENT> post_batches = {} <NEW_LINE> for agent_i...
Apply policy postprocessors to any unprocessed rows. This pushes the postprocessed per-agent batches onto the per-policy builders, clearing per-agent state.
625941d250812a4eaa59c4e0
def test_get_capabilities(self): <NEW_LINE> <INDENT> capabilities = json.loads(self._cliconf.get_capabilities()) <NEW_LINE> mock_capabilities = { 'network_api': 'cliconf', 'rpc': [ 'get_config', 'edit_config', 'get_capabilities', 'get', 'enable_response_logging', 'disable_response_logging' ], 'device_info': { 'network_...
Test get_capabilities
625941d2d8ef3951e32436fd
def run(self): <NEW_LINE> <INDENT> vehicle = Vehicle(self.width / 2, self.height / 2) <NEW_LINE> n_walls = 10 <NEW_LINE> walls = [Wall(Vector2(randint(0, self.width), randint(0, self.height)), Vector2(randint(0, self.width), randint(0, self.height))) for n in range(n_walls)] <NEW_LINE> while not self.exit: <NEW_LINE> <...
Run project.
625941d2956e5f7376d7102c
def testTrendingTrendingEntry(self): <NEW_LINE> <INDENT> pass
Test TrendingTrendingEntry
625941d2cc0a2c11143dd050
def create_app(self): <NEW_LINE> <INDENT> test_app = app <NEW_LINE> test_app.config['SECRET_KEY'] = 'sekrit!' <NEW_LINE> test_app.config['TESTING'] = True <NEW_LINE> test_app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = False <NEW_LINE> test_app.config['WTF_CSRF_ENABLED'] = False <NEW_LINE> return test_app
creates app instance
625941d2d53ae8145f87a42e
def render_jump_targets(area, scr): <NEW_LINE> <INDENT> player_loc = area.find_actor(area.get_player()) <NEW_LINE> for target, cell in area.cells.items(): <NEW_LINE> <INDENT> delta = target - player_loc <NEW_LINE> if ((abs(delta.x) != JUMP_RANGE or delta.y) and (abs(delta.y) != JUMP_RANGE or delta.x)): <NEW_LINE> <INDE...
Indicate all valid jump targets on the map. Args: area (Area): The map. scr: A curses screen to render to.
625941d2956e5f7376d7102d
def test02(self): <NEW_LINE> <INDENT> t = blaze.array(self.ddesc) <NEW_LINE> st = t.where("(f0 < 10) & (f1 > 4)") <NEW_LINE> cr = list(st) <NEW_LINE> nr = [dict(zip(x.dtype.names, x)) for x in self.npt[ (self.npt['f0'] < 10) & (self.npt['f1'] > 4)]] <NEW_LINE> self.assertEqual(cr, nr, "where does not work correctly")
Testing with two fields
625941d266673b3332b92251
def __init__(self, weight_fundamentalist, weight_chartist, weight_random, c_share_strat, money, assets, covariance_matrix, init_price, active_orders): <NEW_LINE> <INDENT> self.weight_fundamentalist = [weight_fundamentalist] <NEW_LINE> self.weight_chartist = [weight_chartist] <NEW_LINE> self.weight_random = [weight_rand...
Initializes variables for the trader :param weight_fundamentalist: float fundamentalist expectation component :param weight_chartist: float trend-following chartism expectation component :param weight_random: float random or heterogeneous expectation component :param weight_mean_reversion: float mean-reversion chartism...
625941d226068e7796caeea0
def install(self): <NEW_LINE> <INDENT> self.logger.info('Installing CMake') <NEW_LINE> self.install_package(url=self.cmake_url, file_from_make=self.file_from_make, overwrite_on_exist=self.overwrite_on_exist) <NEW_LINE> self.logger.info('Installation completed successfully')
Installs the CMake package
625941d2d53ae8145f87a42f
def clear_preferred_id(self): <NEW_LINE> <INDENT> self.preferred_id = None
Removed preferred id, set to None.
625941d26e29344779a627d1
def start_script(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> cmd = input('SERRYz -> ') <NEW_LINE> if cmd == 'list': <NEW_LINE> <INDENT> self.list_connections() <NEW_LINE> continue <NEW_LINE> <DEDENT> elif 'select' in cmd: <NEW_LINE> <INDENT> target, conn = self.get_target(cmd) <NEW_LINE> if conn is not N...
Interactive prompt for sending commands remotely
625941d2cb5e8a47e48b7c69
def flush(self) -> None: <NEW_LINE> <INDENT> if self.flush_hook: <NEW_LINE> <INDENT> self.flush_hook(self) <NEW_LINE> <DEDENT> if self.buf.tell() <= 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.buf.seek(0) <NEW_LINE> if self.sql_from: <NEW_LINE> <INDENT> sql = self.sql_from <NEW_LINE> <DEDENT> else: <NEW_LINE...
Send data out.
625941d257b8e32f5248365c
def GetPointer(self): <NEW_LINE> <INDENT> return _itkConstrainedValueAdditionImageFilterPython.itkConstrainedValueAdditionImageFilterIUS2IUS2IUS2_Superclass_GetPointer(self)
GetPointer(self) -> itkConstrainedValueAdditionImageFilterIUS2IUS2IUS2_Superclass
625941d2c4546d3d9de72bf5
@step("we know the formats") <NEW_LINE> def step_impl(context): <NEW_LINE> <INDENT> print("This should actually be a unit test so I will assume that they pass. ")
:type context: behave.runner.Context
625941d27cff6e4e81117b46
def ShowImagePowerSpectrum(data, width = None, **plot_args): <NEW_LINE> <INDENT> from matplotlib import pyplot <NEW_LINE> freqs, power, cnts = PowerSpectrum(data, width) <NEW_LINE> pyplot.plot(freqs, power, **plot_args) <NEW_LINE> pyplot.yticks([]) <NEW_LINE> pyplot.xlabel('Cycles per Pixel') <NEW_LINE> pyplot.ylabel('...
Display the 1-D power spectrum of an image. :param data: Image data. :type data: 2D ndarray :param int width: Effective width of image (with padding) for FFT. Any remaining keyword arguments will be passed to :func:`matplotlib.pyplot.plot`.
625941d2be8e80087fb20e01
def vcsCheckout(self, vcsDataDict, projectDir, noDialog=False): <NEW_LINE> <INDENT> noDialog = False <NEW_LINE> try: <NEW_LINE> <INDENT> tag = vcsDataDict["tag"] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> tag = None <NEW_LINE> <DEDENT> vcsDir = self.svnNormalizeURL(vcsDataDict["url"]) <NEW_LINE> if vcsDir...
Public method used to check the project out of the Subversion repository. @param vcsDataDict dictionary of data required for the checkout @param projectDir project directory to create (string) @param noDialog flag indicating quiet operations @return flag indicating an execution without errors (boolean)
625941d2004d5f362079a4f3
def _GetPossibleBrowser(self, test, finder_options): <NEW_LINE> <INDENT> possible_browser = self._FindBrowser(finder_options) <NEW_LINE> finder_options.browser_options.browser_type = ( possible_browser.browser_type) <NEW_LINE> enabled, msg = decorators.IsEnabled(test, possible_browser) <NEW_LINE> if not enabled and not...
Return a possible_browser with the given options for |test|.
625941d24f88993c3716c226
def __init__( self, data, variable, levels=0 ): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.data = data <NEW_LINE> self.variable = variable <NEW_LINE> self.vmin, self.vmax = get_data_limits(self.data[self.variable]) <NEW_LINE> self.cmap = getPalette(self.variable) <NEW_LINE> self.levels = int(np.abs(levels))
:param dataframe data: data to be visualized. :param str variable: variable name. :param int levels: number of contour levels. If zero, heatmap is created. If greater than zero, contour lines are superimposed on the heatmap. Currently, contour graphs are created by plotly library.
625941d23d592f4c4ed1d22b
def __init__(self, dict_df_versioned): <NEW_LINE> <INDENT> self.dict_df_versioned = dict_df_versioned
Constructor.
625941d2d10714528d5ffea5
def render_to_file(self, url, file_object): <NEW_LINE> <INDENT> format = self.format <NEW_LINE> image = self.render(url) <NEW_LINE> qBuffer = QBuffer() <NEW_LINE> image.save(qBuffer, format, quality=self.quality) <NEW_LINE> file_object.write(qBuffer.buffer().data()) <NEW_LINE> return qBuffer.size()
Renders the image into a File resource. Returns the size of the data that has been written.
625941d26fece00bbac2d900
def p_classes(p): <NEW_LINE> <INDENT> if len(p) == 2: <NEW_LINE> <INDENT> p[0] = (p[1],) <NEW_LINE> <DEDENT> elif len(p) == 3: <NEW_LINE> <INDENT> p[0] = (p[1],) + p[2] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise SyntaxError('Invalid number of symbols')
classes : class | class classes
625941d207f4c71912b11643
def multi_tensor(gtab, mevals, S0=100, angles=[(0, 0), (90, 0)], fractions=[50, 50], snr=20): <NEW_LINE> <INDENT> if np.round(np.sum(fractions), 2) != 100.0: <NEW_LINE> <INDENT> raise ValueError('Fractions should sum to 100') <NEW_LINE> <DEDENT> fractions = [f / 100. for f in fractions] <NEW_LINE> S = np.zeros(len(gtab...
Simulate a Multi-Tensor signal. Parameters ----------- gtab : GradientTable mevals : array (K, 3) each tensor's eigenvalues in each row S0 : float Unweighted signal value (b0 signal). angles : array (K,2) or (K,3) List of K tensor directions in polar angles (in degrees) or unit vectors fractions : float ...
625941d250485f2cf553cf5a
def is_balanced(s): <NEW_LINE> <INDENT> bracket_dict = {"(": ")", "[": "]", "{": "}"} <NEW_LINE> right_bracket_set = {")", "]", "}"} <NEW_LINE> right_bracket_stack = [] <NEW_LINE> for char in s: <NEW_LINE> <INDENT> right_bracket = bracket_dict.get(char) <NEW_LINE> if right_bracket: <NEW_LINE> <INDENT> right_bracket_sta...
Returns True iff all types of brackets in s are balanced.
625941d2be7bc26dc91cd7be
def auto_login(self, username, pw_encrypt, phone=False): <NEW_LINE> <INDENT> data = self.ne.login(username, pw_encrypt, phone) <NEW_LINE> if not self.is_data_avaible(data): <NEW_LINE> <INDENT> return data <NEW_LINE> <DEDENT> self.uid = data['account']['id'] <NEW_LINE> data = access_user(data) <NEW_LINE> data['code'] = ...
login into website with username and password which has been ecrypted
625941d2b545ff76a8913fd6
def verify_password(self, password): <NEW_LINE> <INDENT> return check_password_hash(self.userPasswordHash, password)
Check if hashed password matches actual password
625941d23d592f4c4ed1d22c
def checkDmg(self) -> bool: <NEW_LINE> <INDENT> for atk in filter( lambda x: x.parent is not self, filter(lambda x: isinstance(x, Attack), self.sprite_list.sprites()), ): <NEW_LINE> <INDENT> atk: Attack <NEW_LINE> if collide_rect(self, atk): <NEW_LINE> <INDENT> self.health.damage(atk.damage) <NEW_LINE> atk.kill() <NEW_...
Method to check if the pleyer has been hit ### Returns `bool`: true if the player is dead, false otherwise
625941d2046cf37aa974cf07
def test_invalid_params(self): <NEW_LINE> <INDENT> res = self.app.post('/details', params={'license-uri':self.uris[0], 'foo':'bar' }) <NEW_LINE> assert relax_validate(RELAX_ISSUE, res.body) <NEW_LINE> res = self.app.get('/details?license-uri=%s&foo=bar' % self.uris[0]) <NEW_LINE> assert relax_validate(RELAX_ISSUE, res....
Invalid parameters are ignored.
625941d297e22403b379d15a
def csvTables(): <NEW_LINE> <INDENT> tables = loadTables() <NEW_LINE> dir_path = os.path.join(table_dir, 'csv') <NEW_LINE> filenames = [os.path.join(dir_path, x + '.csv') for x in list(tables.keys())] <NEW_LINE> for name, path in zip(list(tables.keys()), filenames): <NEW_LINE> <INDENT> df = tables[name] <NEW_LINE> df.t...
This function fetches tables saved as feather objects and saves them as csv files.
625941d2e8904600ed9f20ee
def bleu_score(predictions, labels, **unused_kwargs): <NEW_LINE> <INDENT> bleu = tf.py_func(compute_bleu_np, (labels, predictions), tf.float32) <NEW_LINE> return bleu
BLEU score computation between labels and predictions. An approximate BLEU scoring method since we do not glue word pieces or decode the ids and tokenize the output. By default, we use ngram order of 4 and use brevity penalty. Also, this does not have beam search. Args: predictions: tensor, model predicitons labe...
625941d2596a897236089c80
def execute_take(item_id): <NEW_LINE> <INDENT> for e in current_room["items"]: <NEW_LINE> <INDENT> if e["id"] == item_id: <NEW_LINE> <INDENT> total_mass = 0 <NEW_LINE> for m in inventory: <NEW_LINE> <INDENT> total_mass += m["mass"] <NEW_LINE> <DEDENT> total_mass += e["mass"] <NEW_LINE> max_mass=5 <NEW_LINE> if total_ma...
This function takes an item_id as an argument and moves this item from the list of items in the current room to the player's inventory. However, if there is no such item in the room, this function prints "You cannot take that."
625941d24527f215b584c616
@utils.supported_filters([]) <NEW_LINE> @database.run_in_session() <NEW_LINE> @user_api.check_user_permission( permission.PERMISSION_DEL_CLUSTERHOST_CONFIG ) <NEW_LINE> @utils.wrap_to_dict(RESP_CLUSTERHOST_CONFIG_FIELDS) <NEW_LINE> def delete_clusterhost_config(clusterhost_id, user=None, session=None): <NEW_LINE> <INDE...
Delet a clusterhost config by clusterhost id.
625941d27b25080760e39619
def write_main(argv): <NEW_LINE> <INDENT> if len(argv) != 1: <NEW_LINE> <INDENT> print("Please provide the name of a file to write.") <NEW_LINE> return 1 <NEW_LINE> <DEDENT> filename = argv[0] <NEW_LINE> resource_name = "files/" + filename <NEW_LINE> tweaks_name = amend_filename(filename, "_tweaks") <NEW_LINE> if not p...
write FILENAME Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.
625941d250485f2cf553cf5b
def event_m50_37_25000(): <NEW_LINE> <INDENT> assert (event_m50_37_x161(flag24=537000081, z156=504, z157=5037030, z158=537020080, z159=5, z160=537020083, z161=2500000)) <NEW_LINE> EndMachine() <NEW_LINE> Quit()
Boss: Tiger Battle
625941d2a8370b7717052a5f
def __init__(self, flags = {}): <NEW_LINE> <INDENT> self.flags = flags
Each table in the database has a flag that can be set when the error is raised to indicate which tables are in working order.
625941d232920d7e50b28392
def generate_anv_json(fdct_flight, f_coords): <NEW_LINE> <INDENT> global M_MSG <NEW_LINE> l_now = time.time() <NEW_LINE> ls_buf = "{{ \"now\" : {:.1f},\n" " \"messages\" : {:d},\n" " \"aircraft\" : [".format(l_now, M_MSG) <NEW_LINE> lv_first = True <NEW_LINE> l_anv = None <NEW_LINE> for l_anv ...
DOCUMENT ME! @param fdct_flight: dicionário de flight engines @param f_coords: coordinate system
625941d2dd821e528d63b369
def TagGroupOpenBrowserWindow(*args): <NEW_LINE> <INDENT> return _DigitalMicrograph.TagGroupOpenBrowserWindow(*args)
TagGroupOpenBrowserWindow(TagGroup tagGroup, bool isFileBased) -> Window
625941d25fcc89381b1e1880
def recursive_delete_dir(fullpath): <NEW_LINE> <INDENT> dirs, files = xbmcvfs.listdir(fullpath) <NEW_LINE> for file in files: <NEW_LINE> <INDENT> xbmcvfs.delete(os.path.join(fullpath, file)) <NEW_LINE> <DEDENT> for directory in dirs: <NEW_LINE> <INDENT> recursive_delete_dir(os.path.join(fullpath, directory)) <NEW_LINE>...
helper to recursively delete a directory
625941d2283ffb24f3c55ac0
def ping_auth(session, url, username, password, ssl_verify=True, timeout_value=30): <NEW_LINE> <INDENT> logon_url = "https://sso.connect.pingidentity.com/sso/sp/initsso?saasid=d6ebf792-3796-4686-b44b-ed7654f29a66&idpid=monsanto-aws2-prod" <NEW_LINE> init_resp = session.get(logon_url, verify=ssl_verify, timeout=timeout_...
PingID validation using username and password and return the new page. :param session: Requests session :type session: Requests object :param url: Initial URL for PingID login :type url: string :param username: User name :type username: string :param password: User password :type password: string :param ssl_verify: Fl...
625941d2a05bb46b383ec9e2
def get_reward(self, death, zombies_killed, blocks, episode_steps): <NEW_LINE> <INDENT> reward = 0 <NEW_LINE> for r in self.world_state.rewards: <NEW_LINE> <INDENT> add = r.getValue() <NEW_LINE> reward += add <NEW_LINE> <DEDENT> if blocks: <NEW_LINE> <INDENT> print("attacked a block get reward") <NEW_LINE> reward += (-...
:return: integer of the reward the agent received
625941d231939e2706e4d029
def activate_session(session, options): <NEW_LINE> <INDENT> if isinstance(options, dict): <NEW_LINE> <INDENT> options = optparse.Values(options) <NEW_LINE> <DEDENT> noauth = options.authtype == "noauth" or getattr(options, 'noauth', False) <NEW_LINE> runas = getattr(options, 'runas', None) <NEW_LINE> if noauth: <NEW_LI...
Test and login the session is applicable
625941d266656f66f7cbc36c
def get_arguments(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( prog='chpl2rst', usage='%(prog)s file.chpl [options] ', description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) <NEW_LINE> parser.add_argument('chapelfiles', nargs='+', help='Chapel files to convert to rst') <NEW_LINE> parser...
Get arguments from command line
625941d263b5f9789fde72a6
def create_job(self, name, job_type, mains, libs=None, **kwargs): <NEW_LINE> <INDENT> uri = 'jobs' <NEW_LINE> body = kwargs.copy() <NEW_LINE> body.update({ 'name': name, 'type': job_type, 'mains': mains, 'libs': libs or list(), }) <NEW_LINE> return self._request_check_and_parse_resp(self.post, uri, 202, body=json.dumps...
Creates job with specified params. It supports passing additional params using kwargs and returns created object.
625941d2e64d504609d74a01
def plot_summary(self, **kwargs): <NEW_LINE> <INDENT> return self.plot_parameter_posterior('p', **kwargs)
Plot posterior pdfs for all parameters.
625941d2dc8b845886cb56f6
def testMonthAndYearAsInteger(self): <NEW_LINE> <INDENT> expiry = ExpiryDate(month=10, year=2009) <NEW_LINE> self.assertEqual(expiry.month, 10) <NEW_LINE> self.assertEqual(expiry.year, 2009)
Integers are valid month/year parameters.
625941d231939e2706e4d02a
def indiceP( self, origine, cellule ): <NEW_LINE> <INDENT> cout = self.getCoutCellule( cellule ) <NEW_LINE> cout = 1 if cout == 0 else cout <NEW_LINE> production = cellule.getProduction() <NEW_LINE> nbVoisins = len( cellule.getVoisins() ) <NEW_LINE> distance = self.getRobot().getTerrain().getLienEntreCellules( origine,...
Calcule l'indice P d'une cellule par rapport à la cellule d'origine voulant envoyer ses unités. :param origine: La cellule d'origine :type origine: Cellule :param cellule: La cellule dont on veut calculer l'indice P :type cellule: Cellule :return: l'indice P de la cellule cible :rtype: float
625941d2aad79263cf390c03
def reverseKGroup(self, head, k): <NEW_LINE> <INDENT> if not head or k==1: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> p = head <NEW_LINE> for i in range(k-1): <NEW_LINE> <INDENT> p = p.next <NEW_LINE> if not p: <NEW_LINE> <INDENT> return head <NEW_LINE> <DEDENT> <DEDENT> tail = self.reverseKGroup(p.next, k) <N...
:type head: ListNode :type k: int :rtype: ListNode
625941d2fbf16365ca6f6388
def gram(self, m): <NEW_LINE> <INDENT> if isspmatrix_csr(m): <NEW_LINE> <INDENT> num_samps, d = m.shape <NEW_LINE> <DEDENT> elif isspmatrix_csc(m): <NEW_LINE> <INDENT> d, num_samps = m.shape <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("mtest is not a CSR or CSC vector") <NEW_LINE> <DEDENT> m.sort_ind...
Return the kernel gram matrix between from the sparse matrix 'm' if 'self.center == True', then center the Gram matrix in the feature space induced by the kernel, and additionally set the Kernel parameters (array of the column means and 1/n*mean of all the kernel evaluations) needed to center in the same way the futur...
625941d229b78933be1e586b
def displayfield(*args, **kw): <NEW_LINE> <INDENT> return virtualfield(DisplayField(*args, **kw))
Decorator shortcut to turn a method into a DisplayField.
625941d276e4537e8c351834
def render(request: Optional[IRequest]) -> "Flattenable": <NEW_LINE> <INDENT> pass
Get the document for this L{IRenderable}. @param request: The request in response to which this method is being invoked. @return: An object which can be flattened.
625941d263f4b57ef00012d8
def _connection_failed(self, link, message): <NEW_LINE> <INDENT> print("Connection failed on {}: {}".format(link, message)) <NEW_LINE> sys.exit(-1)
Callback for a failed Crazyflie connection
625941d2bd1bec0571d907f1
def _get_dir_size(target_dirpath): <NEW_LINE> <INDENT> cur_size = 0 <NEW_LINE> for dirpath, dirnames, filenames in os.walk(target_dirpath): <NEW_LINE> <INDENT> for f in filenames: <NEW_LINE> <INDENT> path = os.path.join(dirpath, f) <NEW_LINE> if os.path.exists(path): <NEW_LINE> <INDENT> cur_size += os.path.getsize(path...
Sums up only files size, and does not include directory metadata size Returns size in bytes
625941d2fb3f5b602dac3855
def get_daemon_stats(self, details=False): <NEW_LINE> <INDENT> res = super(Satellite, self).get_daemon_stats(details=details) <NEW_LINE> counters = res['counters'] <NEW_LINE> counters['broks'] = len(self.broks) <NEW_LINE> counters['events'] = len(self.events) <NEW_LINE> counters['workers'] = len(self.workers) <NEW_LINE...
Increase the stats provided by the Daemon base class :return: stats dictionary :rtype: dict
625941d224f1403a92600d26
def linkdir(self, olddir, newname, mode='link'): <NEW_LINE> <INDENT> if not os.path.isdir(olddir): <NEW_LINE> <INDENT> raise Exception('需要移动到output目录的文件夹不存在。') <NEW_LINE> <DEDENT> newdir = os.path.join(self.output_dir, newname) <NEW_LINE> if not os.path.exists(newdir): <NEW_LINE> <INDENT> if mode == 'link': <NEW_LINE> ...
移动一个目录下的所有文件/文件夹到workflow输出文件夹下
625941d24428ac0f6e5ba9b4
def overlay_predictions(image, predictions): <NEW_LINE> <INDENT> labels = predictions['labels'] <NEW_LINE> labels = [CATEGORIES[label] for label in labels] <NEW_LINE> boxes = predictions['bbox'] <NEW_LINE> template = "{}" <NEW_LINE> for box, label in zip(boxes, labels): <NEW_LINE> <INDENT> x1, y1, x2, y2 = box <NEW_LIN...
Adds detected class names and scores in the positions defined by the top-left corner of the predicted bounding box Arguments: image (np.ndarray): an image as returned by OpenCV predictions: the result of the computation by the model. It should contain the field `labels` and `bbox`.
625941d23617ad0b5ed680b8
def get_class(kls): <NEW_LINE> <INDENT> parts = kls.split(".") <NEW_LINE> module = ".".join(parts[:-1]) <NEW_LINE> m = __import__(module) <NEW_LINE> for comp in parts[1:]: <NEW_LINE> <INDENT> m = getattr(m, comp) <NEW_LINE> <DEDENT> return m
* Function: Implement reflection in python * -----------{returns}------------ * returns a class based on a string . . .
625941d22ae34c7f2600d2f2
def stepwise_kpca(X, gamma, n_components): <NEW_LINE> <INDENT> sq_dists = pdist(X, 'sqeuclidean') <NEW_LINE> mat_sq_dists = squareform(sq_dists) <NEW_LINE> K = exp(-gamma * mat_sq_dists) <NEW_LINE> N = K.shape[0] <NEW_LINE> one_n = np.ones((N,N)) / N <NEW_LINE> K_norm = K - one_n.dot(K) - K.dot(one_n) + one_n.dot(K).do...
Implementation of a RBF kernel PCA. Arguments: X: A MxN dataset as NumPy array gamma: Parameter for the RBF kernel. n_components: The number of components to be returned. Returns the k eigenvectors (alphas) that correspond to the k largest eigenvalues (lambdas).
625941d23617ad0b5ed680b9
def check_elb_cross_zone(client, elb): <NEW_LINE> <INDENT> name = elb['LoadBalancerName'] <NEW_LINE> enabled = get_elb_cross_zone_attr(client, name) <NEW_LINE> status = "OK" if enabled else "NOK" <NEW_LINE> return name, status
Check if the elb has the cross az option active. :param client: boto3 client. :param elb: elb information as return by describe elb call. :return: typle (name, result) name is the elb name being checked, and result is True/False i.e success/failed the check
625941d2a8ecb033257d328e
def register_file_creation(self, temporary, *files): <NEW_LINE> <INDENT> if not files: <NEW_LINE> <INDENT> raise errors.LetsEncryptReverterError( "Forgot to provide files to registration call") <NEW_LINE> <DEDENT> if temporary: <NEW_LINE> <INDENT> cp_dir = self.direc['temp'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Register the creation of all files during letsencrypt execution. Call this method before writing to the file to make sure that the file will be cleaned up if the program exits unexpectedly. (Before a save occurs) :param bool temporary: If the file creation registry is for a temp or permanent save. :param \*files:...
625941d221bff66bcd684b13
def get_test_diff(test_a, test_b): <NEW_LINE> <INDENT> state_index = {'active': 3, 'succeeded': 2, 'finished': 1, 'failed': 0} <NEW_LINE> result_translation = { -1: 'active', 0: 'ok', 1: 'warning_b', 2: 'warning', 3: 'warning_w', 4: 'alert', } <NEW_LINE> diff_matrix = [ [4, 2, 0, -1], [4, 9, 0, -1], [4, 2, 0, ...
Finding difference in 2 test results :param test_1: dict, {finalstatus, subresults} - previous. :param test_2: dict, {finalstatus, subresults} - current. :return: index
625941d2187af65679ca52e0
def ldap_login(self, username, password): <NEW_LINE> <INDENT> self.connect() <NEW_LINE> if self.config.get('USER_SEARCH'): <NEW_LINE> <INDENT> result = self.bind_search(username, password) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = self.direct_bind(username, password) <NEW_LINE> <DEDENT> return result
Authenticate a user using ldap. This will return a userdata dict if successfull. ldap_login will return None if the user does not exist or if the credentials are invalid
625941d28c0ade5d55d3eb7d
def get_all_shared_key_derivation_service_instances_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> all_params = [] <NEW_LINE> all_params.append('async_req') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_...
Get the all key derivers that the org has access to - including shared cloud instances # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_all_shared_key_derivation_service_instances_with_http_info(async_req=True) ...
625941d207d97122c4178a4f
def test_float_array(): <NEW_LINE> <INDENT> x=float_array() <NEW_LINE> assert type(x) == np.ndarray <NEW_LINE> assert x.ndim == 2 <NEW_LINE> assert x.shape == (2,3) <NEW_LINE> assert x.dtype == np.float <NEW_LINE> assert x[0,0] ==0.1 <NEW_LINE> assert x[1,1] ==0.5 <NEW_LINE> assert x[0,-1] ==0.3 <NEW_LINE> assert x[1,-...
(2 points) float_array
625941d24a966d76dd5511d1
def get_processed_data(self, y_true=None, y_pred=None, decimal=None): <NEW_LINE> <INDENT> decimal = self.decimal if decimal is None else decimal <NEW_LINE> if (y_true is not None) and (y_pred is not None): <NEW_LINE> <INDENT> y_true, y_pred = self.__format_data_type(y_true, y_pred) <NEW_LINE> y_true, y_pred, one_dim = ...
Args: y_true (tuple, list, np.ndarray): The ground truth values y_pred (tuple, list, np.ndarray): The prediction values clean (bool): Remove all rows contain 0 value in y_pred (some methods have denominator is y_pred) decimal (int): The number of fractional parts after the decimal point Returns: y_...
625941d238b623060ff0afaf
def test_scale_row_sum_naive(self): <NEW_LINE> <INDENT> m = array([[1.0,2,3,4],[2,4,4,0],[1,1,1,1],[0,0,0,100]]) <NEW_LINE> scale_row_sum_naive(m) <NEW_LINE> self.assertFloatEqual(m, [[0.1,0.2,0.3,0.4],[0.2,0.4,0.4,0], [0.25,0.25,0.25,0.25],[0,0,0,1.0]]) <NEW_LINE> scale_row_sum_naive(m,4) <NEW_LINE> sel...
scale_row_sum_naive should scale rows to correct values
625941d28da39b475bd65136
def cross_validation(scheme_class, num_examples, num_folds, strict=True, **kwargs): <NEW_LINE> <INDENT> if strict and num_examples % num_folds != 0: <NEW_LINE> <INDENT> raise ValueError(("{} examples are not divisible in {} evenly-sized " + "folds. To allow this, have a look at the " + "`strict` argument.").format(num_...
Return pairs of schemes to be used for cross-validation. Parameters ---------- scheme_class : subclass of :class:`IndexScheme` or :class:`BatchScheme` The type of the returned schemes. The constructor is called with an iterator and `**kwargs` as arguments. num_examples : int The number of examples in the d...
625941d2d18da76e23532699
@pytest.fixture(params=[LocalFSProvider]) <NEW_LINE> def init_tmp_dir(request): <NEW_LINE> <INDENT> dir_path = tempfile.mkdtemp() <NEW_LINE> yield (request.param, dir_path) <NEW_LINE> shutil.rmtree(dir_path)
Create a temporary folder
625941d2293b9510aa2c3456
def _translate_key_from_subgrid(subgrid_indices, key): <NEW_LINE> <INDENT> return tuple([subgrid_indices[var_name][index] for var_name, index in zip(subgrid_indices, key)])
:type key: tuple, the indices (describing the point) in subgrid :type subgrid_indices: OrderedDict, the indices of values taken to form subgrid :rtype: tuple, the indices in grid
625941d23c8af77a43ae3963
@cache <NEW_LINE> def group_info(name, recursive=True): <NEW_LINE> <INDENT> path = os.path.join(conf.groups_path, name) <NEW_LINE> packages = [] <NEW_LINE> depends = [] <NEW_LINE> removed = [] <NEW_LINE> if recursive: <NEW_LINE> <INDENT> all_packages = [] <NEW_LINE> all_depends = [] <NEW_LINE> all_removed = [] <NEW_LIN...
Return informations about a given group name.
625941d2090684286d50eea8