code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def init(self): <NEW_LINE> <INDENT> self.num_cols = self.get_property("numCols") <NEW_LINE> self.num_rows = self.get_property("numRows") <NEW_LINE> self.num_drops = self.get_property("numDrops") <NEW_LINE> self.reference_pos_x = self.get_property("referencePosX") <NEW_LINE> if not self.reference_pos_x: <NEW_LINE> <INDE... | Descript. : | 625941ea0a366e3fb873ece0 |
def __init__(self): <NEW_LINE> <INDENT> self.SceneId = None <NEW_LINE> self.Type = None <NEW_LINE> self.Channels = None | :param SceneId: 场景ID
:type SceneId: int
:param Type: 1: 绑定 2: 解绑
:type Type: int
:param Channels: 通道列表
:type Channels: list of ChannelItem | 625941ea004d5f362079a7f1 |
def merge_dict(row): <NEW_LINE> <INDENT> target_column_exists = True <NEW_LINE> target_columns = 0 <NEW_LINE> target_dict = OrderedDict() <NEW_LINE> while target_column_exists: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> target_name = 'Target' + str(target_columns + 1).zfill(2) <NEW_LINE> target_dose = 'TargetDose' + ... | A variable number of input targets may be used in the csv file
this function returns a dictionary that can be used to merge target columns
Arguments:
row {dataframe row} -- input row from the plan_data dataframe
Returns:
[dict] -- dictionary of the form {'PTV1_6000': 6000, ...} | 625941eacb5e8a47e48b7f64 |
def portfolio_returns(df_long, df_short, lookahead_returns, n_stocks): <NEW_LINE> <INDENT> portfolio_returns = lookahead_returns*(df_long-df_short)/n_stocks <NEW_LINE> return portfolio_returns | Compute expected returns for the portfolio, assuming equal investment in each long/short stock.
Parameters
----------
df_long : DataFrame
Top stocks for each ticker and date marked with a 1
df_short : DataFrame
Bottom stocks for each ticker and date marked with a 1
lookahead_returns : DataFrame
Lookahead r... | 625941ea73bcbd0ca4b2c537 |
def test_graph_edge_attr_singleedge_set(self): <NEW_LINE> <INDENT> edge = self.graph.getedges((1, 2), directed=True) <NEW_LINE> edge.weight = 4.5 <NEW_LINE> edge['key'] = 'edge_set' <NEW_LINE> edge.set('value', False) <NEW_LINE> self.assertEqual(edge.edges[(1, 2)]['weight'], 4.5) <NEW_LINE> self.assertEqual(edge.edges[... | Test setting edge attribute values directly using the single edge
Graph API which has the required methods (edge_tools) added to it. | 625941ea3d592f4c4ed1d522 |
def removeNode( self, a_node ): <NEW_LINE> <INDENT> nodeNorm = os.path.normpath( a_node ) <NEW_LINE> for edge in self.xmlRoot.find('edges'): <NEW_LINE> <INDENT> if edge.find('to').text == nodeNorm: <NEW_LINE> <INDENT> self.removeEdge( edge.find('from').text, nodeNorm ) <NEW_LINE> <DEDENT> <DEDENT> nodeExists = self.nod... | Remove a node if it exists. | 625941eae5267d203edce158 |
def build_amg_index_sets(L_sizes): <NEW_LINE> <INDENT> neqns = L_sizes[0][0] <NEW_LINE> velocityDOF=[] <NEW_LINE> for start in range(1,3): <NEW_LINE> <INDENT> velocityDOF.append(np.arange(start=start, stop=1+neqns, step=3, dtype='i')) <NEW_LINE> velocityDOF_full=np.vstack(velocityDOF).transpose().flatten() <NEW_LINE> <... | Create PETSc index sets for the velocity components of a saddle
point matrix
Parameters
----------
L_sizes :
Sizes of original saddle-point system
Returns:
--------
Index_Sets : lst
List of velocity index sets | 625941ea8c3a873295158882 |
def add_grid_lines(map_file, op_file, grid_spacing): <NEW_LINE> <INDENT> from PIL import Image <NEW_LINE> from PIL import ImageDraw <NEW_LINE> img = Image.open(map_file) <NEW_LINE> width, height = img.size <NEW_LINE> draw = ImageDraw.Draw(img) <NEW_LINE> y_start = 0 <NEW_LINE> y_end = img.height <NEW_LINE> for x in ran... | makes a new image 'op_file' from 'map_file' with
a grid overlayed on it | 625941eadd821e528d63b666 |
def set_state(self, kwargs): <NEW_LINE> <INDENT> if 'ls_sector_phases' in kwargs: <NEW_LINE> <INDENT> self.sects = sectors.Sectors( ls_phases=kwargs['ls_sector_phases'] ) <NEW_LINE> <DEDENT> elif 'number_of_values' in kwargs: <NEW_LINE> <INDENT> self.sects = sectors.Sectors( num_sectors=kwargs['number_of_values'] ) <NE... | Either 'ls_sector_phases' or 'number_of_values' must be specified
while setting state of this class/creating this class.
@see Transformation.get_state | 625941ea5fc7496912cc3e3f |
def _add_http(self, tcpdata, dport): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> http = dpkt.http.Request() <NEW_LINE> http.unpack(tcpdata) <NEW_LINE> <DEDENT> except dpkt.dpkt.UnpackError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> entry = {} <NEW_LINE> if "host" in http.headers: <NEW_LINE>... | Adds an HTTP flow.
@param tcpdata: TCP data flow.
@param dport: destination port. | 625941eae64d504609d74d01 |
def menu(self): <NEW_LINE> <INDENT> print("Display this (m)enu.") <NEW_LINE> print("Make an (i)tem.") <NEW_LINE> print("(g)ive an item.") <NEW_LINE> print("(v)iew a player.") <NEW_LINE> print("(e)quip a player.") <NEW_LINE> print("(c)reate a player.") <NEW_LINE> print("e(n)counter mobs.") <NEW_LINE> print("(q)uit.") | Prints a list of command options. | 625941eaf8510a7c17cf9bc1 |
def __eq__(self, other) : <NEW_LINE> <INDENT> if not isinstance(other, Task): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not hasattr(other, 'to_dict'): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.to_dict() != other.to_dict(): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.top... | When comparing Tasks, they are the same if they:
1. are both instances of the same class
2. have the same properties and values
3. are in the same topic | 625941eade87d2750b860259 |
def get_services(self): <NEW_LINE> <INDENT> self.select([0x7F, 0x20]) <NEW_LINE> if self.coms()[2] != (0x90, 0x00): <NEW_LINE> <INDENT> if self.dbg >= 2: <NEW_LINE> <INDENT> log(3, '(get_services) %s' % self.coms()) <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> sst = self.select([0x6F, 0x38]) <NEW_LINE> if self.c... | self.get_services() -> None
reads SIM Service Table at address [0x6F, 0x38]
returns list of services allowed / activated | 625941eab545ff76a89142d7 |
def update(self): <NEW_LINE> <INDENT> if self.left < 0 or self.right > games.screen.width: <NEW_LINE> <INDENT> self.dx = -self.dx <NEW_LINE> <DEDENT> elif random.randrange(self.odds_change) == 0: <NEW_LINE> <INDENT> self.dx = -self.dx <NEW_LINE> <DEDENT> self.check_drop() | Определяет, надо ли сменить направление. | 625941ea9c8ee82313fbbc38 |
def set_thread_priority(self, priority): <NEW_LINE> <INDENT> return _transmit_nodes_swig.howto_ekf2_ff_sptr_set_thread_priority(self, priority) | set_thread_priority(howto_ekf2_ff_sptr self, int priority) -> int | 625941ea7047854f462a18c6 |
def load_module(self): <NEW_LINE> <INDENT> if not self._modules or self.mount_type in kernel_filesystems: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> for module in self._modules: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> rc = util.run_program(["modprobe", module]) <NEW_LINE> <DEDENT> except OSError as e: <NEW_LIN... | Load whatever kernel module is required to support this filesystem. | 625941ea30c21e258bdfa964 |
def test_unauthorized_exception(exception_app): <NEW_LINE> <INDENT> request, response = exception_app.test_client.get('/401') <NEW_LINE> assert response.status == 401 <NEW_LINE> request, response = exception_app.test_client.get('/401/basic') <NEW_LINE> assert response.status == 401 <NEW_LINE> assert response.headers.ge... | Test the built-in Unauthorized exception | 625941ea8c0ade5d55d3ee81 |
def __call__(self, parent_weight_map): <NEW_LINE> <INDENT> if not isinstance(parent_weight_map, dict): <NEW_LINE> <INDENT> parent_weight_map = dict(parent_weight_map) <NEW_LINE> <DEDENT> total_weight = self.get_total_weight(parent_weight_map) <NEW_LINE> chromosome_ids = set() <NEW_LINE> for parent in parent_weight_map:... | Apply the crossover operator to the parents, biasing selection of
genetic material from each parent according to its given weight.
NOTE:
Fitness must be >= 0.0. For the unweighted case, use 1.0 for each
parent, not 0.0. | 625941eabde94217f36832ae |
def app_fetchlist(url=None, name=None): <NEW_LINE> <INDENT> try: os.listdir(repo_path) <NEW_LINE> except OSError: os.makedirs(repo_path) <NEW_LINE> if url is None: <NEW_LINE> <INDENT> url = 'https://app.yunohost.org/official.json' <NEW_LINE> name = 'yunohost' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if name is Non... | Fetch application list from app server
Keyword argument:
name -- Name of the list (default yunohost)
url -- URL of remote JSON list (default https://app.yunohost.org/official.json) | 625941ea3eb6a72ae02ec9ac |
@auth.route("/resetpassword/<token>", methods=["GET", "POST"]) <NEW_LINE> def reset_password(token): <NEW_LINE> <INDENT> if not current_user.is_anonymous(): <NEW_LINE> <INDENT> return redirect(url_for("forum.index")) <NEW_LINE> <DEDENT> form = ResetPasswordForm() <NEW_LINE> if form.validate_on_submit(): <NEW_LINE> <IND... | Handles the reset password process. | 625941ea377c676e91272668 |
def get_distance(d): <NEW_LINE> <INDENT> delta_d = d[1:]-d[:-1] <NEW_LINE> return np.cumsum(np.sum(delta_d**2, axis =1)**0.5) | Calculates distance from coordinates
d (2D array): X,Y GPS coordinates | 625941ea9c8ee82313fbbc39 |
def __init__(self, url='', credentials=None, get_credentials=True, http=None, model=None, log_request=False, log_response=False, credentials_args=None, default_global_params=None, additional_http_headers=None, response_encoding=None): <NEW_LINE> <INDENT> url = url or self.BASE_URL <NEW_LINE> super(EventflowV1beta2, sel... | Create a new eventflow handle. | 625941ea3539df3088e2e80d |
def blob(infile, outfile, nr_blobs, radius, count_tries): <NEW_LINE> <INDENT> gt = cv2.imread(infile) <NEW_LINE> print("Infile", infile, "size:", gt.shape) <NEW_LINE> out = np.zeros(gt.shape, dtype=gt.dtype) <NEW_LINE> tries = 0 <NEW_LINE> successes = 0 <NEW_LINE> bar = tqdm.tqdm(total=nr_blobs) <NEW_LINE> while tries ... | Do the blobbing thing.
Read infile, create nr_blobs blobs of radius radius that make the image
more like the infile, and write the result to outfile. | 625941ea91f36d47f21ac9b9 |
def get_fields_with_their_position(found_headers, defined_headers): <NEW_LINE> <INDENT> field_positions = dict() <NEW_LINE> for fieldname in defined_headers: <NEW_LINE> <INDENT> defined_header = defined_headers[fieldname] <NEW_LINE> if defined_header in found_headers: <NEW_LINE> <INDENT> position = found_headers.index(... | Returns the positions, as defined in the defined_headers, of the available headers
as found in the file. First position has index: 0 | 625941ea2ae34c7f2600d5f2 |
def __add__(self,b): <NEW_LINE> <INDENT> c = self.copy() <NEW_LINE> c += b <NEW_LINE> return c | Implement the c = self + b where b is JonesVector then componenst add, else complex(b)
added to both componnets | 625941ea24f1403a92601024 |
def clear(self): <NEW_LINE> <INDENT> del self[:] | Python 3 backport | 625941ea56b00c62f0f14b1e |
def _out_order(self, node): <NEW_LINE> <INDENT> return reversed(self._in_order(node)) | Utility method for computing out-order
of a binary tree using iterative algorithm. | 625941ea566aa707497f4a24 |
def _fetch_device_configuration(self) -> None: <NEW_LINE> <INDENT> self.information = self.dsm.information <NEW_LINE> self.network = self.dsm.network <NEW_LINE> self.network.update() <NEW_LINE> if self._with_security: <NEW_LINE> <INDENT> _LOGGER.debug("Enable security api updates for '%s'", self._entry.unique_id) <NEW_... | Fetch initial device config. | 625941ea82261d6c526ab969 |
def constructModel(pars, annuli): <NEW_LINE> <INDENT> defpars = {} <NEW_LINE> mpars = pars['model']['params'] <NEW_LINE> ne = constructCmpt(mpars['ne_logpcm3'], annuli, 'ne', defpars) <NEW_LINE> Z = constructCmpt(mpars['Z_solar'], annuli, 'Z', defpars) <NEW_LINE> T = constructCmpt(mpars['T_logkeV'], annuli, 'T', defpar... | Make Model object from input parameters. | 625941ea01c39578d7e752fd |
def task_killed(self, task): <NEW_LINE> <INDENT> pass | Notification of a task being killed
Args:
task (Task): the task that failed | 625941ea57b8e32f52483960 |
def stop_output(self): <NEW_LINE> <INDENT> if self.options_channels['state_shutdown'][0] == 1: <NEW_LINE> <INDENT> self.output_switch('on', output_channel=0) <NEW_LINE> <DEDENT> elif self.options_channels['state_shutdown'][0] == 0: <NEW_LINE> <INDENT> self.output_switch('off', output_channel=0) <NEW_LINE> <DEDENT> self... | Called when Output is stopped | 625941ea29b78933be1e5b68 |
def getDnGUCDict(self): <NEW_LINE> <INDENT> tmpDict = {} <NEW_LINE> tmpDict["ssl"] = "on" <NEW_LINE> tmpDict["ssl_cert_file"] = "'server.crt'" <NEW_LINE> tmpDict["ssl_key_file"] = "'server.key'" <NEW_LINE> tmpDict["ssl_ca_file"] = "'cacert.pem'" <NEW_LINE> return tmpDict | function : get init DB install guc parameter
input : String,String,String,int
output : String | 625941ea167d2b6e31219057 |
def parse_gcs_url(self, gsurl): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> from urllib.parse import urlparse <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> from urlparse import urlparse <NEW_LINE> <DEDENT> parsed_url = urlparse(gsurl) <NEW_LINE> if not parsed_url.netloc: <NEW_LINE> <INDENT> raise Airflow... | Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a
tuple containing the corresponding bucket and blob. | 625941ea26068e7796caf1a9 |
def fields(item): <NEW_LINE> <INDENT> yield item.name <NEW_LINE> for i in item.tracker_domains: <NEW_LINE> <INDENT> yield i.lstrip("*.") <NEW_LINE> <DEDENT> for i in _make_state(item): <NEW_LINE> <INDENT> yield i | Which fields to search in... | 625941ead58c6744b4258120 |
def __init__(self, action: Optional[typing.Action] = None) -> None: <NEW_LINE> <INDENT> self.is_disposed = False <NEW_LINE> self.action = action or noop <NEW_LINE> self.lock = RLock() <NEW_LINE> super().__init__() | Creates a disposable object that invokes the specified
action when disposed.
Args:
action: Action to run during the first call to dispose.
The action is guaranteed to be run at most once.
Returns:
The disposable object that runs the given action upon
disposal. | 625941ea0fa83653e465747a |
def count_levels(coded_godict): <NEW_LINE> <INDENT> dicts = OrderedDict() <NEW_LINE> for g in range(1, 7): <NEW_LINE> <INDENT> s = set() <NEW_LINE> d = {} <NEW_LINE> for gene, codes in coded_godict.items(): <NEW_LINE> <INDENT> for code in codes: <NEW_LINE> <INDENT> levels = code.split('.')[:g] <NEW_LINE> if len(levels)... | Receives a dictionary where keys are gene names (perhaps ordered locus)
and values are lists of hierarchical GO codes.
Outputs 4 dictionaries, one per level, where keys are the partial codes
and values are counts. | 625941ea293b9510aa2c3753 |
def genProtectString(self, protect_str): <NEW_LINE> <INDENT> protect_if_str = '' <NEW_LINE> protect_end_str = '' <NEW_LINE> if not protect_str: <NEW_LINE> <INDENT> return (protect_if_str, protect_end_str) <NEW_LINE> <DEDENT> if ',' in protect_str: <NEW_LINE> <INDENT> protect_list = protect_str.split(",") <NEW_LINE> pro... | Generate protection string.
Protection strings are the strings defining the OS/Platform/Graphics
requirements for a given OpenXR command. When generating the
language header files, we need to make sure the items specific to a
graphics API or OS platform are properly wrapped in #ifs. | 625941ea66673b3332b92553 |
def getuploaddir(self, macaddress, reference_date=None): <NEW_LINE> <INDENT> upload_dir = self.get(macaddress, 'upload_dir', '~/eyefi') <NEW_LINE> upload_dir = os.path.expanduser(upload_dir) <NEW_LINE> if reference_date is None: <NEW_LINE> <INDENT> upload_tmpdir = re.sub('%.', '', upload_dir) <NEW_LINE> regexp = os.pat... | Returns the upload directory from the configuration file
It can be card specific base on macaddress
~ are expanded to $HOME
If refenrence_date is provided, resolved %Y and such, see strftime
If refenrence_date is not provided, %Y and such are removed, so that
the result is suitable for temporary files. | 625941ea10dbd63aa1bd3064 |
def update_url(shell, replacement_items, old_string, new_string): <NEW_LINE> <INDENT> if old_string == new_string: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> f = TemporaryFile() <NEW_LINE> for item in replacement_items: <NEW_LINE> <INDENT> query = "UPDATE `%s` SET `%s` = REPLACE(`%s`, \'%s\', \'%s\');\n" % ( item['... | 데이터베이스 안의 내용을 치환. | 625941ea99fddb7c1c9de851 |
def mean_perc_rank_batch(train_data, heldout_data, Et, Eb, user_idx, mu=None, vad_data=None): <NEW_LINE> <INDENT> batch_users = user_idx.stop - user_idx.start <NEW_LINE> X_pred = _make_prediction(train_data, Et, Eb, user_idx, batch_users, mu=mu, vad_data=vad_data) <NEW_LINE> all_perc = np.argsort(np.argsort(-X_pred, ax... | mean percentile rank for a batch of users
MPR of the full set is the sum of batch MPR's divided by the sum of all the
feedbacks. (Eq. 8 in Hu et al.)
This metric not necessarily constrains the data to be binary | 625941ea283ffb24f3c55dbe |
@as_array <NEW_LINE> def is_substochastic(mat, tol=1e-6): <NEW_LINE> <INDENT> return (mat.ndim == 2) and (mat.shape[0] == mat.shape[1]) and (np.all([row >= 0 for row in mat])) and (all(np.sum(row) <= 1+tol for row in mat)) | Check if a matrix is (right) substochastic. | 625941eaa8ecb033257d358d |
def get(self): <NEW_LINE> <INDENT> template = JINJA_ENVIRONMENT.get_template('ttt4x4.html') <NEW_LINE> self.response.write(template.render({})) | Renders the game html page
:return: None | 625941ea7cff6e4e81117e48 |
def _filter_with_hooks(self, svc_event, listeners): <NEW_LINE> <INDENT> svc_ref = svc_event.get_service_reference() <NEW_LINE> hook_refs = self._registry.find_service_references( SERVICE_EVENT_LISTENER_HOOK ) <NEW_LINE> if hook_refs: <NEW_LINE> <INDENT> ctx_listeners = {} <NEW_LINE> for listener in listeners: <NEW_LINE... | Filters listeners with EventListenerHooks
:param svc_event: ServiceEvent being triggered
:param listeners: Listeners to filter
:return: A list of listeners with hook references | 625941eaa8ecb033257d358e |
def clean_tweets(list_of_tweets): <NEW_LINE> <INDENT> mentions = re.compile('(@.*?)(?=\s|\:)') <NEW_LINE> links = re.compile('(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?') <NEW_LINE> no_mentions = [re.sub(mentions, "@USER", i) for i in list_of_tweets] <NEW_LINE> no_links = [re.su... | :param list_of_tweets: list of unique tweets (no duplicates)
:return: list of preprocessed tweets
the function standardizes mentions --> @USER
and URLs --> @URL
removes BOM character | 625941ea4527f215b584c914 |
def createSession(self): <NEW_LINE> <INDENT> if self.system_calm: <NEW_LINE> <INDENT> self.system_calm.wait(self) <NEW_LINE> <DEDENT> self.info("Create session") <NEW_LINE> self.step = 0 <NEW_LINE> self.session_index += 1 <NEW_LINE> self.use_timeout = bool(self.session_timeout) <NEW_LINE> self.session_start = time() <N... | Create a new session:
- make sure that system load is under 50%
- activate all project agents
- send project_start (only for the first session)
and session_start messages | 625941ea3346ee7daa2b3232 |
def test_that_when_checking_if_a_rest_api_exists_and_a_rest_api_exists_the_api_exists_method_returns_true(boto_conn): <NEW_LINE> <INDENT> boto_conn.get_rest_apis.return_value = {'items': [{'name': 'myapi', 'id': '1234def'}]} <NEW_LINE> api_exists_result = boto_apigateway.api_exists(name='myapi', **pytest.conn_parameter... | Tests checking an apigateway rest api existence when api's name exists | 625941ea23849d37ff7b354d |
def get_parent(self, kq): <NEW_LINE> <INDENT> if self.root is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current = self.root <NEW_LINE> while current is not None: <NEW_LINE> <INDENT> if current.val == kq: <NEW_LINE> <INDENT> return parent <NEW_LINE> <DEDENT> if kq < current.val:... | Helper function - returns the parent node of a node passed to it.
:param kq: Node whose parent to search for
:return: Parent node of kq | 625941ead164cc6175783211 |
def _genStick(length, thickness = 2, plotname="dumbbell"): <NEW_LINE> <INDENT> this_dir, this_filename = os.path.split(__file__) <NEW_LINE> cylinderpath = Filename.fromOsSpecific(os.path.join(this_dir, "geomprim", "cylinder.egg")) <NEW_LINE> stick = NodePath(plotname) <NEW_LINE> stickbody = loader.loadModel(cylinderpat... | Generate a stick node for plot
This function should not be called explicitly
## input
length:
length of the stick
thickness:
thickness of the stick, set to 0.005 as default
## output | 625941ea55399d3f05588b7a |
def name_is_unique(name, used_names): <NEW_LINE> <INDENT> if name not in used_names: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | Check if name is contained in the used_names list and return boolean value | 625941eacdde0d52a9e534f9 |
def get_simulations_to_run(): <NEW_LINE> <INDENT> print("\nHow many simulations should be run?") <NEW_LINE> simulations_to_run = validate_positive_integer(input("(Must be positive integer, less than 10,000): ")) <NEW_LINE> if simulations_to_run != "invalid_input" and simulations_to_run > 9999: <NEW_LINE> <INDENT> print... | Request number of simulations to run, validate input, recursive until input is valid. | 625941ea66673b3332b92554 |
def test_correct_login(self): <NEW_LINE> <INDENT> args = {'name': 'admin', 'password': 'admin'} <NEW_LINE> with self.app.test_client() as c: <NEW_LINE> <INDENT> self.assertNotIn('formLogin', c.post('dashboard/login', data=args).data.decode()) | Try whether logging with correct credentials does not return the login page | 625941ea596a897236089f7c |
def removeDuplicates(self, s: str, k: int) -> str: <NEW_LINE> <INDENT> pass | put solution here | 625941ea30c21e258bdfa965 |
def assertHasProps(d, props): <NEW_LINE> <INDENT> missing_props = [] <NEW_LINE> for kpath, v in nested_items(props): <NEW_LINE> <INDENT> dv = get_path(d, kpath) <NEW_LINE> if dv != v: <NEW_LINE> <INDENT> missing_props.append(kpath) <NEW_LINE> <DEDENT> <DEDENT> if len(missing_props) > 0: <NEW_LINE> <INDENT> raise Assert... | All the properties and values in props must also exist in d for this
assertion to be True. | 625941ea091ae35668667418 |
def bounding_box(self): <NEW_LINE> <INDENT> bbox = bounding_box() <NEW_LINE> if self.subpath_len(): <NEW_LINE> <INDENT> for subPath in self.paths: <NEW_LINE> <INDENT> for path in subPath: <NEW_LINE> <INDENT> bbox.add_bounding_box(path.bounding_box()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return bbox | return the path's bounding box | 625941ea44b2445a33932555 |
def save(self, bulk=False, id=None, parent=None, routing=None, force=False, force_insert=False, using=None): <NEW_LINE> <INDENT> meta = self.get_meta() <NEW_LINE> if using: <NEW_LINE> <INDENT> index = meta.index <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> index = meta.index <NEW_LINE> <DEDENT> conn = self.connect_if_... | Save the object and returns id | 625941ea66656f66f7cbc66f |
def max_pooling2d(X,name,filter_shape,stride,padding_type): <NEW_LINE> <INDENT> with tf.variable_scope(name): <NEW_LINE> <INDENT> fh,fw=filter_shape <NEW_LINE> net_filter_shape=(1,fh,fw,1) <NEW_LINE> sh,sw=stride <NEW_LINE> net_stride=(1,sh,sw,1) <NEW_LINE> A=tf.nn.max_pool(X,net_filter_shape,net_stride,padding_type,na... | DESCRIPTION:
This function will perform maxpooling on the input 'image'
from the previous stage of convolutional layer.The parameters
are similar to conv2d layer.
But there are no trainable papameters in this layer.
USAGE:
INPUT:
OUTPUT:
A : the maxpooled map of the input 'image' ... | 625941eacc40096d61595e11 |
@click.command() <NEW_LINE> @click.option("--config-file", "config", type=str, default="./conf/basic_config.json") <NEW_LINE> @click.option("--seed", type=int, default=1) <NEW_LINE> def main(config, seed): <NEW_LINE> <INDENT> random.seed(seed) <NEW_LINE> Faker.seed(seed) <NEW_LINE> print(f"Loading game config from {con... | main funciton to run hearts games | 625941eacc0a2c11143dd355 |
def get(self, index): <NEW_LINE> <INDENT> if index < 0 or index >= self.size: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if not self.head: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> cur = self.head <NEW_LINE> for i in range(index): <NEW_LINE> <INDENT> cur = cur.next <NEW_LINE> <DEDENT> return cur.val | Get the value of the index-th node in the linked list. If the index is invalid, return -1.
:type index: int
:rtype: int | 625941ea8e7ae83300e4b491 |
def test_init(testing_user): <NEW_LINE> <INDENT> (email, password) = testing_user <NEW_LINE> user = User(email) <NEW_LINE> assert isinstance(user.email, str) <NEW_LINE> assert user.email == email <NEW_LINE> assert isinstance(user.host, str) <NEW_LINE> assert user.host == constants.DEFAULT_HOST <NEW_LINE> assert isinsta... | Tests proper initialization of a user.
| 625941ea4d74a7450ccd4687 |
def in_progress_events(self): <NEW_LINE> <INDENT> if self._get_queue(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> res = self.queue.get_in_progress() <NEW_LINE> if res is None: <NEW_LINE> <INDENT> return dict() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return res <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <I... | Returns the in_progress dict, an empty dict or None | 625941ea4d74a7450ccd4688 |
def generate_image(self, document_file_info): <NEW_LINE> <INDENT> input_file_name = self.document_file_manager.get_file_path(document_file_info) <NEW_LINE> tmp_file = tempfile.NamedTemporaryFile(mode="wb", suffix='.jpg', delete=False) <NEW_LINE> tmp_file.close() <NEW_LINE> output_file_name = tmp_file.name <NEW_LINE> st... | Uses ffmpeg to write a frame of the given video as jpg file that then will
be read into a PIL image and the file removed. | 625941ea6fb2d068a760f568 |
def invest(amount, rate, time): <NEW_LINE> <INDENT> print("principal amount: ${}".format(amount)) <NEW_LINE> print("annual rate of return: {}".format(rate)) <NEW_LINE> for i in range(1, time + 1): <NEW_LINE> <INDENT> res = amount + (amount * rate) <NEW_LINE> amount = res <NEW_LINE> print("year {}: ${}".format(i, res)) | Track the growing amount of an investment over time | 625941eaec188e330fd5ac58 |
def xyz_to_cct_HA(xyzw, verbosity = 1): <NEW_LINE> <INDENT> if len(xyzw.shape)>2: <NEW_LINE> <INDENT> raise Exception('xyz_to_cct_HA(): Input xyzw.ndim must be <= 2 !') <NEW_LINE> <DEDENT> out_of_range_code = np.nan <NEW_LINE> xe = [0.3366, 0.3356] <NEW_LINE> ye = [0.1735, 0.1691] <NEW_LINE> A0 = [-949.86315, 36284.489... | Convert XYZ tristimulus values to correlated color temperature (CCT).
Args:
:xyzw:
| ndarray of tristimulus values
Returns:
:cct:
| ndarray of correlated color temperatures estimates
References:
1. `Hernández-Andrés, Javier; Lee, RL; Romero, J (September 20, 1999).
Calculating... | 625941ea66656f66f7cbc670 |
def check_is_bearer_token(self, base_url): <NEW_LINE> <INDENT> if base_url: <NEW_LINE> <INDENT> giturl = urllib.parse.unquote(base_url) <NEW_LINE> urlval = urllib.parse.urlparse(giturl) <NEW_LINE> if urlval.netloc.endswith('azure.com'): <NEW_LINE> <INDENT> self.is_bearer_token = True | Is it a bearer token to pass as an additional header to clone | 625941eaa8370b7717052d60 |
def test_group(self): <NEW_LINE> <INDENT> result = roles.utils.register_group("Brights") <NEW_LINE> self.failUnless(isinstance(result, Group)) <NEW_LINE> group = Group.objects.get(name="Brights") <NEW_LINE> self.assertEqual(group.name, "Brights") <NEW_LINE> result = roles.utils.register_group("Brights") <NEW_LINE> self... | Tests registering/unregistering of a group.
| 625941ea30bbd722463cc28c |
def subsetsWithDup(self, nums): <NEW_LINE> <INDENT> def helper(res, tmpList, nums, begin): <NEW_LINE> <INDENT> res.append(tmpList) <NEW_LINE> for i in xrange(begin, len(nums)): <NEW_LINE> <INDENT> if i == begin or (nums[i] != nums[i-1]): <NEW_LINE> <INDENT> helper(res, tmpList+[nums[i]], nums, i+1) <NEW_LINE> <DEDENT> ... | :type nums: List[int]
:rtype: List[List[int]] | 625941eaf548e778e58cda43 |
def IsEqual(self,other): <NEW_LINE> <INDENT> pass | IsEqual(self: AnalysisDisplayLegendSettings,other: AnalysisDisplayLegendSettings) -> bool
Compares two legend settings objects.
other: Legend settings object to compare to.
Returns: True if objects are equal,false otherwise. | 625941ea1f037a2d8b9466c0 |
def fit(self, ts): <NEW_LINE> <INDENT> self.symbols = self.sax_symbolize(ts) <NEW_LINE> reduced_symbols, self.reduced_symbols_indices = self.numerosity_reduce(self.symbols) <NEW_LINE> self.word_occurrences = self.grammar_induce(reduced_symbols) <NEW_LINE> return self | build necessary strucuture for a time series for later query
self.symbols: SAX reprsentation of time series
reduced_symbols: symbols after numerosity_reduce
self.reduced_symbols_indices: range(slices) of reduced_symbols in original symbols
self.word_occurrences: word occurrences (in rules) from reduced_symbols | 625941ea94891a1f4081bf6e |
def grab_cords(input_str="Position: "): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> data = input(input_str) <NEW_LINE> try: <NEW_LINE> <INDENT> pos_x = ord(data[0].upper()) - 65 <NEW_LINE> pos_y = int(data[1:]) - 1 <NEW_LINE> assert 0 <= pos_x < 10 <NEW_LINE> assert 0 <= pos_y < 10 <NEW_LINE> <DEDENT> except Ex... | Translate user import into matrix coordinates | 625941eab57a9660fec33d4e |
def parse_dictionary(filter_dict, model): <NEW_LINE> <INDENT> if len(filter_dict) == 0: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> conditions = [] <NEW_LINE> for k, v in filter_dict.items(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conditions += parse('{0}{1}'.format(k, v), model) <NEW_LINE> <DEDENT> except ... | Parse a dictionary into a list of SQLAlchemy BinaryExpressions to be used
in query filters.
:param filter_dict: Dictionary to convert
:param model: SQLAlchemy model class used to create the BinaryExpressions
:return list: List of conditions as SQLAlchemy BinaryExpressions | 625941ea5510c4643540f89b |
def class_to_json(obj): <NEW_LINE> <INDENT> return obj.__dict__ | Returns the dictionary of object
Arguments:
obj {[type]} -- object to convert | 625941eaa17c0f6771cbe512 |
def getWafConfigIdByName(self, session, wrapper_object, config_name): <NEW_LINE> <INDENT> config_detail = dict() <NEW_LINE> config_detail['Found'] = False <NEW_LINE> waf_configs_response = wrapper_object.getWafConfigurations(session) <NEW_LINE> if waf_configs_response.status_code == 200: <NEW_LINE> <INDENT> configurati... | Function to get WAF config ID and version | 625941eabe7bc26dc91cdaba |
def test_show(self): <NEW_LINE> <INDENT> pass | Test case for show
Get current state of the journal on this node. | 625941eadc8b845886cb59fa |
def main(): <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description= 'Runs benchmark and checks for correct exit status and output.') <NEW_LINE> parser.add_argument('--enable-proof', action='store_true') <NEW_LINE> parser.add_argument('--with-lfsc', action='store_true') <NEW_LINE> parser.add_argument('--dump'... | Parses the command line arguments and then calls the core of the
script. | 625941ea851cf427c661a9ce |
def generateParenthesis(self, n): <NEW_LINE> <INDENT> ans = [] <NEW_LINE> self.test('', 0, 0, ans, n) <NEW_LINE> return ans | :type n: int
:rtype: List[str] | 625941ead268445f265b5332 |
def test_totalozone_monthly_generation(self): <NEW_LINE> <INDENT> contents = util.read_file(resolve_test_data_path( 'data/totalozone/totalozone-all300.csv')) <NEW_LINE> ecsv = dummy_extCSV(contents) <NEW_LINE> ecsv.validate_metadata_tables() <NEW_LINE> ecsv.validate_dataset_tables() <NEW_LINE> reporter = ecsv.reports <... | Test derivation and checks related to TotalOzone MONTHLY table | 625941ead10714528d6001ac |
def debug_stdout(self, sfunc): <NEW_LINE> <INDENT> pass | print(sfunc) | 625941ea7c178a314d6ef92a |
def drawGrid(surface,playfieldWidth,playfieldHeight,camera): <NEW_LINE> <INDENT> GRIDSIZE = 50 <NEW_LINE> BLACK = (0,0,0) <NEW_LINE> H_Start = 0 <NEW_LINE> H_End = playfieldWidth <NEW_LINE> V_Start = 0 <NEW_LINE> V_End = playfieldHeight <NEW_LINE> for i in range(H_Start,H_End+1,GRIDSIZE): <NEW_LINE> <INDENT> pygame.dra... | (object),(int),(int),(object) ---> (none)
This method is used to make a grid that is diplayed on your screen. The grid is not static but scales based off your camera
and your position on the field. | 625941ea8a43f66fc4b54523 |
def print_columns_to_drop(self): <NEW_LINE> <INDENT> for ci, cn in zip(self._indices_to_drop, self.columns_to_drop): <NEW_LINE> <INDENT> selector_attributes = self.selector.__dict__ <NEW_LINE> if 'threshold' in selector_attributes: <NEW_LINE> <INDENT> if self.selector.__class__.__name__ == 'VarianceThreshold': <NEW_LIN... | Print information if and why a column was dropped. | 625941ea004d5f362079a7f3 |
@cli.command('jinja_to_mapping') <NEW_LINE> @click.argument('template', type=click.File('r'), default='-') <NEW_LINE> @click.argument('output', type=click.File('w'), default='-') <NEW_LINE> @click.option('--context_path', multiple=True, help='Context templates. It can either be a directory ' + 'containing jinja files o... | Generate Elasticsearch mapping from jinja import templates. | 625941ea4e696a04525c9911 |
def _load_bed(self): <NEW_LINE> <INDENT> self.bed = pd.read_csv(self.input_bed, sep="\t", header=None) <NEW_LINE> self.original_bed_size = self.bed.shape[1] <NEW_LINE> self.bed['region'] = self.bed[0] + ":" + self.bed[1].astype('str') + '-' + self.bed[2].astype('str') | load region bed into class | 625941eacb5e8a47e48b7f66 |
def num_matched_columns(self): <NEW_LINE> <INDENT> return tf.shape(self.matched_column_indices())[0] | Returns number (int32 scalar tensor) of matched columns. | 625941ea23e79379d52eea21 |
def run(test, params, env): <NEW_LINE> <INDENT> options_ref = params.get("list_options_ref", "") <NEW_LINE> status_error = params.get("status_error", "no") <NEW_LINE> filter_name = [] <NEW_LINE> uri = params.get("virsh_uri") <NEW_LINE> unprivileged_user = params.get('unprivileged_user') <NEW_LINE> if unprivileged_user:... | Test command: virsh nwfilter-list.
1) Prepare parameters.
2) Run nwfilter-list command.
3) Check result. | 625941ea4f88993c3716c526 |
@task <NEW_LINE> def run(command, show=True): <NEW_LINE> <INDENT> if show: <NEW_LINE> <INDENT> print_command(command) <NEW_LINE> <DEDENT> with hide("running"): <NEW_LINE> <INDENT> return _run(command) | Runs a shell command on the remote server. | 625941ead99f1b3c44c67a49 |
def get_arch_prefix(arch): <NEW_LINE> <INDENT> if arch: <NEW_LINE> <INDENT> return "arch_" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return "" | return archive table prefix | 625941ea29b78933be1e5b69 |
def merge(self, intervals: List[List[int]]) -> List[List[int]]: <NEW_LINE> <INDENT> if intervals is None or len(intervals) == 0 or (not any(intervals)): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> intervals.sort(key=lambda x: x[0]) <NEW_LINE> ans = [] <NEW_LINE> for lst in intervals: <NEW_LINE> <INDENT> if len(an... | T(n) = O(nlogn) -- sorting takes nlogn time and it traverses the list one time
S(n) = O(1) -- const space | 625941eae64d504609d74d03 |
def executeWithOuput(self,cmd): <NEW_LINE> <INDENT> p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) <NEW_LINE> result=p.communicate()[0] <NEW_LINE> return result.strip() | Executes a command and returns the output | 625941eaf8510a7c17cf9bc3 |
def initGui(self): <NEW_LINE> <INDENT> icon_path = ':/plugins/SaveAttributes/icon.png' <NEW_LINE> self.add_action( icon_path, text=self.tr(u'Save Trributes as CSV'), callback=self.run, parent=self.iface.mainWindow()) | Create the menu entries and toolbar icons inside the QGIS GUI. | 625941eaa8370b7717052d61 |
def multilook(x,ratio): <NEW_LINE> <INDENT> L=x.shape[0]; <NEW_LINE> P=x.shape[1]; <NEW_LINE> outL=floor(float(L)/ratio[0]) <NEW_LINE> outP=floor(float(P)/ratio[1]) <NEW_LINE> x=x[0:ratio[0]*outL,0:ratio[1]*outP] <NEW_LINE> out=x.reshape(outL,ratio[0],outP,ratio[1]); <NEW_LINE> return out.mean(axis=3).mean(axis=1); | multilook(data,ratio)
data: is a numpy array.
ratio: is a list of ratios with number of elements equal to number of data dimensions.
CURRENTLY only 2D data is SUPPORTED. | 625941ea1d351010ab855fde |
def load_to_s3(self, df): <NEW_LINE> <INDENT> df.to_parquet(self.s3_obj, engine="fastparquet", index=False, compression='gzip') | convert dataframe to parquet and load to s3_path
:param df: dataFrame to write
:return: | 625941eabaa26c4b54cb15de |
def __init__(self, data, from_string=False): <NEW_LINE> <INDENT> if from_string: <NEW_LINE> <INDENT> self.data = dedent(data) <NEW_LINE> self.recipes = yaml.safe_load(data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.data = os.path.join(os.path.dirname(__file__), data) <NEW_LINE> self.recipes = yaml.safe_load(op... | Handles the creation of a directory of recipes.
This class, combined with YAML files describing test cases, can be used
for building test cases of interdependent recipes in an isolated
directory.
Recipes are specified in a YAML file. Each top-level key represents
a recipe, and the recipe will be written in a temp dir... | 625941ea090684286d50f1b1 |
def checkMsgToEvent(self, testName ): <NEW_LINE> <INDENT> self.sent = {} <NEW_LINE> mp = MessageProcessor( self.zem, 2 ) <NEW_LINE> message = mail_data[testName]['msg'] <NEW_LINE> mp.process( message ) <NEW_LINE> expected_evt = mail_data[testName]['event'] <NEW_LINE> for field, value in expected_evt.items(): <NEW_LINE>... | Check that an e-mail was translated as expected | 625941ea3eb6a72ae02ec9ae |
def test_many(self): <NEW_LINE> <INDENT> self.assertEqual( -3, compose(self.add_one, self.times_two, self.minus_three)(1)) | Functions are applied from last to first. | 625941eabde94217f36832b0 |
def __getattr__(self, name: str) -> typing.Any: <NEW_LINE> <INDENT> if name == 'backend_session_': <NEW_LINE> <INDENT> return self.__session <NEW_LINE> <DEDENT> if name == '_requests_session': <NEW_LINE> <INDENT> return self.__session <NEW_LINE> <DEDENT> if name == 'client_' or name == '_client': <NEW_LINE> <INDENT> re... | Forward any method invocation to actual client with session. | 625941ea377c676e9127266a |
def __filter_fields(self, field_names, obj, many=False): <NEW_LINE> <INDENT> if obj and many: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> obj_prototype = obj[0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return self.declared_fields <NEW_LINE> <DEDENT> obj = obj_prototype <NEW_LINE> <DEDENT> ret = self.... | Return only those field_name:field_obj pairs specified by
``field_names``.
:param set field_names: Field names to include in the final
return dictionary.
:returns: An dict of field_name:field_obj pairs. | 625941eabf627c535bc13693 |
def test_simple_get(self): <NEW_LINE> <INDENT> obj = get_object_or_404_or_403('wiki.hello', self.user, Document, name='shortcut_test') <NEW_LINE> eq_(self.obj.pk, obj.pk) | get_object_or_404_or_403 shortcut should return an object | 625941ea3539df3088e2e80f |
def compare_end_date_column_value_in_origin_reference_price_list_grid(self, expected_value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.logger.info('Start: Compare End Date Column Value in Origin Reference Price List Grid') <NEW_LINE> return self._price_page.compare_end_date_column_value_in_origin_reference_pric... | Returning Compare End Date Column Value in Origin Reference Price List Grid
Implementing logging for Compare End Date Column Value in Origin Reference Price List Grid functionality
:param expected_value:
:return: | 625941ea76e4537e8c351b3a |
def transform_y(self, tfms:TfmList=None, **kwargs): <NEW_LINE> <INDENT> _check_kwargs(self.y, tfms, **kwargs) <NEW_LINE> self.tfm_y=True <NEW_LINE> if tfms is None: self.tfms_y,self.tfmargs_y = self.tfms,{**self.tfmargs, **kwargs} <NEW_LINE> else: self.tfms_y,self.tfmargs_y = tfms,kwargs <NEW_LINE> return se... | Set `tfms` to be applied to the targets only. | 625941ea656771135c3ebd38 |
def prepare_vm_backup(self, context): <NEW_LINE> <INDENT> if 'uuid' in self.options: <NEW_LINE> <INDENT> vmname = self.options['uuid'] <NEW_LINE> if not self.get_vm_details_by_uuid(context): <NEW_LINE> <INDENT> bareosfd.DebugMessage( context, 100, "Error getting details for VM %s\n" % (vmname)) <NEW_LINE> return bRCs['... | prepare VM backup:
- get vm details
- take snapshot
- get disk devices | 625941ea377c676e9127266b |
def startProcess(self): <NEW_LINE> <INDENT> self.st_button.state="disabled" <NEW_LINE> bgFileName = self.bg_sv.get() <NEW_LINE> directory = bgFileName[0:bgFileName.rindex("/")+1] <NEW_LINE> dataFiles = self.dat_entry.get(0,tk.END) <NEW_LINE> intRange= map(lambda x: float(x), self.ir_sv.get().split(",")) <NEW_LINE> plot... | Grabs all relevant values from user input and starts processing of data | 625941ea2c8b7c6e89b35c81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.