code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __init__(self): <NEW_LINE> <INDENT> self._cache = {} <NEW_LINE> self._updated = False <NEW_LINE> self._last_dump_time = time.perf_counter() <NEW_LINE> self._interval = self._default_interval <NEW_LINE> self.__lock = threading.Lock() | Creates a new CachedCounters object. | 625941cf2c8b7c6e89b35914 |
def has_three_digit_factors(value): <NEW_LINE> <INDENT> i = 100 <NEW_LINE> while i*i <= value and i <= 999: <NEW_LINE> <INDENT> if value/i == int(value/i) and value/i >= 100 and value/i <= 999: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> i += 1 <NEW_LINE> <DEDENT> return False | This method checks if the input value has three digit factors, i.e.
if the input is x, and it has any factors y and z, both of which are three
digit, it returns True. Otherwise it returns False. | 625941cfe5267d203edcddf0 |
def parse(self, value): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> keyword = 'Failed' <NEW_LINE> _logger.debug('Got None') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> keyword, the_rest = value <NEW_LINE> <DEDENT> samf = self.samf <NEW_LINE> if keyword == 'pong': <NEW_LINE> <INDENT> _id, pid, pong_time,... | Parse the value returned from the workers.
Parameters
----------
value: tuple of the form (keyword, the_rest)
Keyword currently can be one of ['pong', 'Error', 'result']. For
each of the keywords, "the_rest" is a tuple of different elements,
but generally the first one is always the worker_id that the resu... | 625941cfa79ad161976cc299 |
def __init__(self, manager, table, tree=None, files=None, job_id=None, strategy=None, update_policy=None, conflict_policy=None, last_sync=None, onconflict=None): <NEW_LINE> <INDENT> self.manager = manager <NEW_LINE> db = current.db <NEW_LINE> xml = manager.xml <NEW_LINE> self.error = None <NEW_LINE> self.error_tree = e... | Constructor
@param manager: the S3RequestManager instance performing this job
@param tree: the element tree to import
@param files: files attached to the import (for upload fields)
@param job_id: restore job from database (record ID or job_id)
@param strategy: the import strategy
@param update_policy: the update polic... | 625941cf0c0af96317bb833c |
def create_form_params(range_start='', range_end=''): <NEW_LINE> <INDENT> return { 'length_0': range_end, 'length_1': range_start } | Return range form parameter as used in geotrek.core.filters.PathFilter | 625941cf8e7ae83300e4b120 |
def encode_z(ht): <NEW_LINE> <INDENT> phi_size = 2 <NEW_LINE> z_size = D <NEW_LINE> ht = tf.expand_dims(ht,0) <NEW_LINE> with tf.variable_scope("phi"): <NEW_LINE> <INDENT> phi = fc_act(ht, phi_size, act=tf.nn.relu, name="fc_phi") <NEW_LINE> <DEDENT> with tf.variable_scope("phi_mu"): <NEW_LINE> <INDENT> phi_mu = fc_act(... | encode the latent values given hidden state, i.e. z ~ p(z|h) | 625941cfb5575c28eb68e155 |
def _integrate_elastic_peak(self, ws): <NEW_LINE> <INDENT> sigmaE = self._calculate_epp_energy_width(ws) <NEW_LINE> max_energy = np.max(sigmaE) <NEW_LINE> bin_width = 2.0 * max_energy <NEW_LINE> for entry in mtd[ws]: <NEW_LINE> <INDENT> Integration(InputWorkspace=entry, OutputWorkspace=entry, RangeLowerList=-sigmaE, Ra... | Integrates bins around the elastic peak in energy exchange units. | 625941cf004d5f362079a487 |
@csrf_exempt <NEW_LINE> @http.json_response() <NEW_LINE> @http.verify_csrf() <NEW_LINE> @http.require_http_methods("POST") <NEW_LINE> def get_users(request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> users = MainUser.objects.all().defer('avatar') <NEW_LINE> return { 'result': [ i.get_object() for i in users ] } <NEW... | @api {post} /moderators/get_users/ Poll feed method
@apiName get_users
@apiGroup Moderators
@apiHeader {String} Csrf-Token CSRF token.
@apiHeader {String} Auth-Token Authentication token.
@apiSuccess {Json[]} result Json representation of users. | 625941cf45492302aab5e418 |
def divide(self, dividend, divisor): <NEW_LINE> <INDENT> MAX_INT, MIN_INT = 2147483647, -2147483648 <NEW_LINE> flag = (dividend < 0) ^ (divisor < 0) <NEW_LINE> dividend, divisor = abs(dividend), abs(divisor) <NEW_LINE> ret = 0 <NEW_LINE> while dividend >= divisor: <NEW_LINE> <INDENT> temp = divisor <NEW_LINE> i = 1 <NE... | :type dividend: int
:type divisor: int
:rtype: int | 625941cf85dfad0860c3afaf |
def __init__(self): <NEW_LINE> <INDENT> self.swagger_types = { 'status': 'ResponseStatus', 'response': 'PagedSavedSearch' } <NEW_LINE> self.attribute_map = { 'status': 'status', 'response': 'response' } <NEW_LINE> self._status = None <NEW_LINE> self._response = None | ResponseContainerPagedSavedSearch - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition. | 625941cff8510a7c17cf984f |
def __init__(self, func): <NEW_LINE> <INDENT> self.fallback = func <NEW_LINE> self.accept_handlers = { mimetype: func for mimetype in self.mimetypes } <NEW_LINE> functools.update_wrapper(self, func) | Initialize a new Acceptor and create the accept handlers
:param func: the endpoint function to fall back upon | 625941cf498bea3a759b9c03 |
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'TradingView.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are you ... | Run administrative tasks. | 625941cfe76e3b2f99f3a95e |
def plugin_adjustment(): <NEW_LINE> <INDENT> duration_adjustments = [gv.sd[entry] for entry in gv.sd if entry.startswith(u"wl_")] <NEW_LINE> result = reduce(lambda x, y: x * y / 100.0, duration_adjustments, 1.0) <NEW_LINE> return result | Sums irrigation time (water level) adjustments from multiple plugins.
The adjustment value output from a plugin must be
a unique element in the gv.sd dictionary with a key starting with "wl_" | 625941cf3539df3088e2e49f |
def keyup(e): <NEW_LINE> <INDENT> global h <NEW_LINE> if(e.keycode in h): <NEW_LINE> <INDENT> h.pop(h.index(e.keycode)) | funcion para leer la tecla cuando deja de presionarse | 625941cfe64d504609d74994 |
def _previous(self, idx): <NEW_LINE> <INDENT> return max(filter(lambda x_: x_ < idx, self.root.active)) | The index of previous active node of idx.
Example: 0(active), 1, 2(active), 3, 4, ...
self._previous(4) => 2
:param index idx: Index. | 625941cf3eb6a72ae02ec633 |
def select_test_based_on_attributes( attrs1, attrs2, result ): <NEW_LINE> <INDENT> if attrs1 == None: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> elif attrs2 == None: <NEW_LINE> <INDENT> return -1 <NEW_LINE> <DEDENT> if result != None: <NEW_LINE> <INDENT> if result.startswith( 'state=' ): <NEW_LINE> <INDENT> rs = ... | Given the result attributes from two different executions of the same
test, this returns -1 if the first execution wins, 1 if the second
execution wins, or zero if the tie could not be broken. The 'result'
argument is None or a result string produced from the
TestResults.collectResults() method. | 625941cf15fb5d323cde0c64 |
def getCurrentDefinition(self): <NEW_LINE> <INDENT> definition = {} <NEW_LINE> definitions = IDefinitions(self.context) <NEW_LINE> if self.context.getDefinition(): <NEW_LINE> <INDENT> definition = definitions.getDefinition(self.context.getDefinition()) <NEW_LINE> <DEDENT> columns = self.context.getColumns() <NEW_LINE> ... | Returns the definition for this article
| 625941cfd268445f265b4fc2 |
def dummy_retrieve_func(query, start, count): <NEW_LINE> <INDENT> data = { 'total_results': 0, 'results':[], } <NEW_LINE> return simplejson.dumps(data) | This is a dummy function for retrieving results.
It should be replaced by a real function that
return data in the same format. | 625941cff9cc0f698b14074f |
def plot_samples(ax, samples): <NEW_LINE> <INDENT> Y = samples[:, -1] <NEW_LINE> position_p = Y == 1 <NEW_LINE> position_m = Y == -1 <NEW_LINE> ax.scatter(samples[position_p, 0], samples[position_p, 1], samples[position_p, 2], marker='+', label='+', color='b') <NEW_LINE> ax.scatter(samples[position_m, 0], samples[posit... | 绘制样本点
:param ax: 绘制图形所在的 Axes
:param samples: 样本数据集
:return: None | 625941cf1f5feb6acb0c4ca4 |
def run(self, forever, coro, retry, debug=False): <NEW_LINE> <INDENT> loop = asyncio.get_event_loop() <NEW_LINE> async def async_main(connection): <NEW_LINE> <INDENT> self.__tasks = [] <NEW_LINE> dispatch_forever_task = asyncio.ensure_future( self._async_dispatch_forever(connection, loop)) <NEW_LINE> result = await cor... | Convenience method to start a program.
Connects to the API endpoint, begins an asyncio event loop, and runs
the passed in coroutine. Exceptions will be caught and printed to
stdout.
:param forever: Don't terminate after main returns?
:param coro: A coroutine (async function) to run after connecting.
:param retry: Kee... | 625941cf3317a56b86939dab |
def mime_types_disabled(self): <NEW_LINE> <INDENT> pass | Check SV-36309r2_rule: MIME types for csh or sh shell
programs must be disabled.
Finding ID: V-2225
:returns: bool -- True if rule is satisfied, False otherwise | 625941cf8da39b475bd650c8 |
def add_face(descriptor, name) : <NEW_LINE> <INDENT> if name not in face_data : <NEW_LINE> <INDENT> face_data[name] = descriptor <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> face_data[name] = (face_data[name] + descriptor) / 2 <NEW_LINE> <DEDENT> save() | Adds descriptor and name to face_data, or averages current descriptor for name
Parameters
-----------
descriptor: ndarray
descriptor for face, returned by face_recognition.detections.face_detection
name: str
name of person to be stored in database with given descriptor | 625941cf92d797404e3042de |
def select_time(df, first_day, last_day=None, years=None, months=None, weeks=None, days=None): <NEW_LINE> <INDENT> date_format = '%Y/%m/%d' <NEW_LINE> first_datetime = pd.to_datetime(first_day, format=date_format) <NEW_LINE> if last_day: <NEW_LINE> <INDENT> last_datetime = pd.to_datetime(last_day, format=date_format) <... | Extract a period of time. Notice that the input dataframe must not contain
more than one station.
:param df: input dataframe
:param first_day: date of the first day in YYYY/MM/DD format
:param last_day: date of the last day in YYYY/MM/DD format (optional)
:param years: number of years (optional)
:param months: number ... | 625941cf4c3428357757c47c |
def log(self, log_type, code, message, debug=False): <NEW_LINE> <INDENT> if debug: <NEW_LINE> <INDENT> print(datetime.now(), log_type, code, message) <NEW_LINE> <DEDENT> log_id = self.insert('tb_log', type=log_type, code=code, message=message) <NEW_LINE> if int(code)>0: <NEW_LINE> <INDENT> self.update('users', id=code,... | :param log_type: ENTRY when a user gets in or INFO/WARNING/ERROR for technical issue
:param code: either the member id concerned by the log entry OR the error code
:param message: the log message
:return: last inserted row id | 625941cfbe7bc26dc91cd753 |
def inputs_subgraph(self): <NEW_LINE> <INDENT> with tf.name_scope('inputs'), tf.device('/cpu:0'): <NEW_LINE> <INDENT> static_keep_prob = tf.placeholder(dtype=self.float_type, name='static_keep_prob') <NEW_LINE> rnn_keep_prob = tf.placeholder(dtype=self.float_type, name='rnn_keep_prob') <NEW_LINE> <DEDENT> return static... | Creates the placeholders used to feed data to the model. | 625941cf460517430c3942d8 |
def __init__( self, *, email: Optional[str] = None, name_first: Optional[str] = None, name_last: Optional[str] = None, phone: Optional[str] = None, **kwargs ): <NEW_LINE> <INDENT> super(CertificateOrderContact, self).__init__(**kwargs) <NEW_LINE> self.email = email <NEW_LINE> self.name_first = name_first <NEW_LINE> sel... | :keyword email:
:paramtype email: str
:keyword name_first:
:paramtype name_first: str
:keyword name_last:
:paramtype name_last: str
:keyword phone:
:paramtype phone: str | 625941cf96565a6dacc8f81f |
def decode(self, y): <NEW_LINE> <INDENT> decode_y = [] <NEW_LINE> for i in range(len(y)): <NEW_LINE> <INDENT> for cls in self.code_dic: <NEW_LINE> <INDENT> if self.code_dic[cls] == i: <NEW_LINE> <INDENT> decode_y.append(cls) <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return np.array(decode_y) | decode an array_like labels | 625941cf596a897236089c14 |
def serialize_Rm(x,name,iter): <NEW_LINE> <INDENT> x_json="[ " <NEW_LINE> for i in range(x.size): <NEW_LINE> <INDENT> x_json += str(x[i]) + ", " <NEW_LINE> <DEDENT> x_json=x_json[0:-2] <NEW_LINE> x_json +=" ]" <NEW_LINE> return x_json | Serializes a numpy array for the vector space Optizelle.Rm | 625941cf3cc13d1c6d3c74ce |
def get_format_time(strftime = None): <NEW_LINE> <INDENT> dn = datetime.now() <NEW_LINE> if strftime is None: <NEW_LINE> <INDENT> format_time = dn.strftime('%Y-%m-%d %H:%M:%S') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> format_time = dn.strftime(strftime) <NEW_LINE> <DEDENT> return format_time | 格式化时间戳为本地的时间
# '%Y-%m-%d %H:%M:%S.%f' | 625941cf5fdd1c0f98dc0388 |
def test_size_metrics(self): <NEW_LINE> <INDENT> p1 = Parameter() <NEW_LINE> p2 = Parameter(3, nonpos=True) <NEW_LINE> p3 = Parameter((4, 4), nonneg=True) <NEW_LINE> c1 = numpy.random.randn(2, 1) <NEW_LINE> c2 = numpy.random.randn(1, 2) <NEW_LINE> constants = [2, c2.dot(c1)] <NEW_LINE> p = Problem(cvx.Minimize(p1), [se... | Test the size_metrics method.
| 625941cf009cb60464c63505 |
def test_update_tweets(self): <NEW_LINE> <INDENT> test_user = User.objects.create( userid="337282", twitterhandle="test1", email="test1@test.com", password="PASSWORD", ) <NEW_LINE> Posts.objects.create( postid="1485402", tweet="test1", userid=test_user, ) <NEW_LINE> Posts.objects.create( postid="1487602", tweet="test2"... | Updates two tweets from the database | 625941cf7d847024c06be411 |
def return_score_message(score): <NEW_LINE> <INDENT> if score < 0 or score > 100: <NEW_LINE> <INDENT> result_message = "Invalid score" <NEW_LINE> <DEDENT> elif 90 < score <= 100: <NEW_LINE> <INDENT> result_message = "Excellent" <NEW_LINE> <DEDENT> elif 50 < score: <NEW_LINE> <INDENT> result_message = "Passable" <NEW_LI... | Return the correct score message | 625941cf4a966d76dd551164 |
def protesting_communities(partition, active_nodes): <NEW_LINE> <INDENT> communities = defaultdict(int) <NEW_LINE> for node in active_nodes: <NEW_LINE> <INDENT> communities[partition[node]] += 1 <NEW_LINE> <DEDENT> return communities | Gets the communities with protesters, and the size of each.
Args:
partition: node -> community ID dict
active_nodes: set of nodes who are protesting
Returns:
community ID -> int dict, where int is the size of comm | 625941cfaad79263cf390b96 |
def isComplete(word, word_attempt): <NEW_LINE> <INDENT> ret = ("".join(word_attempt) == word) <NEW_LINE> return ret | Returns true if the word_attempt has no blanks.
Returns false otherwise.
Returns a boolean. | 625941cffff4ab517eb2f591 |
def sync_one_account(db, bridge, uname): <NEW_LINE> <INDENT> ac = Factory.get('Account')(db) <NEW_LINE> co = Factory.get('Constants')(db) <NEW_LINE> auth_data = bridge.get_auth_data(uname) <NEW_LINE> if auth_data is None: <NEW_LINE> <INDENT> logger.warning("No account with username=%r on Caesar, ignoring", uname) <NEW_... | Sync passwords for a single account.
:param db: A database connection to sync to
:param bridge: An AccountBridge object to sync from
:param uname: A username to sync | 625941cf31939e2706e4cfbe |
def exist(self, board, word): <NEW_LINE> <INDENT> if len(word) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> row_len = len(board) <NEW_LINE> if row_len == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> col_len = len(board[0]) <NEW_LINE> letter = word[0] <NEW_LINE> indexes = [] <NEW_LINE> for i in rang... | :type board: List[List[str]]
:type word: str
:rtype: bool | 625941cf379a373c97cfac9a |
def test_ability_score_get_view_query_by_wisdom_no_results(self): <NEW_LINE> <INDENT> client = APIClient() <NEW_LINE> response = client.get("/api/ability-scores?wisdom=31", format="json") <NEW_LINE> self.assertEqual(response.status_code, 200) <NEW_LINE> results = response.data["results"] <NEW_LINE> self.assertTrue(len(... | Unit test to verify that querying by a wisdom that doesn't exist works correctly
:return: None | 625941cfab23a570cc2502d7 |
def process_booking(conn, c, df, booking, name, num_pass, level): <NEW_LINE> <INDENT> print(name, "has a booking for", num_pass) <NEW_LINE> seats = c.execute("SELECT seats FROM rows_cols;").fetchall()[0][0]; <NEW_LINE> nrows = c.execute("SELECT nrows FROM rows_cols;").fetchall()[0][0]; <NEW_LINE> upd_seat = "UPDATE sea... | first try to assign consecutive seats in a row
then either reject the booking if there are too few seats in total
or split the booking and seat passengers individually in next available seat | 625941cf4f6381625f114b8f |
def abrir_dados_car_str(csv_file): <NEW_LINE> <INDENT> import csv <NEW_LINE> x = np.array([]) <NEW_LINE> target = [] <NEW_LINE> with open(csv_file, 'rb') as csvfile: <NEW_LINE> <INDENT> csvreader = csv.reader(csvfile, delimiter=',', quotechar='|') <NEW_LINE> for row in csvreader: <NEW_LINE> <INDENT> x = np.append(x, ro... | Acessa a base de dados car evaluation localizada em CSV_FILE. | 625941cff9cc0f698b140750 |
def get_cv_classification_metrics (cv_targets, cv_preds, cv_probs=None): <NEW_LINE> <INDENT> targets, preds, probs, labels = enlist_cv_results(cv_targets, cv_preds, cv_probs) <NEW_LINE> metrics = np.zeros((len(targets), 6)) <NEW_LINE> for i in range(len(targets)): <NEW_LINE> <INDENT> y_true = targets[i] <NEW_LINE> y_pr... | Returns a matrix of size [n_folds x 6],
where 6 are: acc, sens, spec, prec, f1, roc_auc
@param cv_targets:
@param cv_preds:
@param cv_probs:
@return: | 625941cfd10714528d5ffe39 |
def run_command(runtime, output=None, timeout=0.01, redirect_x=False): <NEW_LINE> <INDENT> PIPE = subprocess.PIPE <NEW_LINE> cmdline = runtime.cmdline <NEW_LINE> if redirect_x: <NEW_LINE> <INDENT> exist_xvfb, _ = _exists_in_path('xvfb-run', runtime.environ) <NEW_LINE> if not exist_xvfb: <NEW_LINE> <INDENT> raise Runtim... | Run a command, read stdout and stderr, prefix with timestamp.
The returned runtime contains a merged stdout+stderr log with timestamps | 625941cff7d966606f6aa159 |
def unzip_files(buffer): <NEW_LINE> <INDENT> results = {} <NEW_LINE> with zipfile.ZipFile(buffer) as z: <NEW_LINE> <INDENT> for filename in z.namelist(): <NEW_LINE> <INDENT> unzipped_buffer = io.BytesIO() <NEW_LINE> unzipped_buffer.write(z.read(filename)) <NEW_LINE> unzipped_buffer.seek(0) <NEW_LINE> results.update({fi... | Return the contents of a zip file. | 625941cf4f6381625f114b90 |
def test_baseWithPrerelease(self): <NEW_LINE> <INDENT> self.assertEqual(Version("foo", 1, 0, 0, prerelease=8).base(), "1.0.0rc8") | The base version includes 'preX' for versions with prereleases. | 625941cf283ffb24f3c55a55 |
def start(self): <NEW_LINE> <INDENT> if not rospy.get_param('/enable_statistics', False): <NEW_LINE> <INDENT> raise rospy.ROSInitException("Rosparam '/enable_statistics' has not been set to true. Aborting") <NEW_LINE> <DEDENT> if self._monitor_timer is not None: <NEW_LINE> <INDENT> raise Exception("Monitor Timer alread... | Starts the Profiler
:raises: ROSInitException when /enable_statistics has not been set to True | 625941cf3617ad0b5ed6804c |
def draw_bond(self, glpane, dispdef, col, detailLevel, highlighted = False, special_drawing_handler = None, special_drawing_prefs = USE_CURRENT ): <NEW_LINE> <INDENT> atom1 = self.atom1 <NEW_LINE> atom2 = self.atom2 <NEW_LINE> disp = max(atom1.display, atom2.display) <NEW_LINE> if disp == diDEFAULT: <NEW_LINE> <INDENT>... | Draw the bond 'self'. This function is only meant to be called as the
implementation of Bond.draw.
See that method's docstring for details of how it's called.
The highlighted option says to modify our appearance as appropriate for
being highlighted (but the highlight color, if any, is passed as a non-false
value of c... | 625941cf44b2445a339321ea |
def post_all_incidents(self): <NEW_LINE> <INDENT> time_now = datetime.now() <NEW_LINE> start_date = datetime.fromisoformat(self.payload_vars['start_date']) if self.payload_vars['start_date'] else time_now <NEW_LINE> end_date = datetime.fromisoformat(self.payload_vars['end_date']) if self.payload_vars['end_date'] else t... | Process all incidents between the start and end dates
If either date variable is a null value, it is set to today's datetime | 625941cf1f5feb6acb0c4ca5 |
def parse_adsp_manifest(reader, name): <NEW_LINE> <INDENT> adsp_mft = AdspManifest(name, reader.get_offset()) <NEW_LINE> adsp_mft.add_comp(parse_adsp_manifest_hdr(reader)) <NEW_LINE> num_module_entries = adsp_mft.cdir['adsp_mft_hdr'].adir['num_module_entries'].val <NEW_LINE> for i in range(0, num_module_entries): <NEW_... | Parses ADSP manifest from sof binary
| 625941cfbf627c535bc13324 |
def put_char(self, c): <NEW_LINE> <INDENT> self._verify_opened() <NEW_LINE> if not self._is_writable(): <NEW_LINE> <INDENT> raise IOError(errno.EBADF, 'Bad file descriptor') <NEW_LINE> <DEDENT> if self._output_buffer[0] == 0: <NEW_LINE> <INDENT> if not isinstance(c, basestring): <NEW_LINE> <INDENT> c = chr(c) <NEW_LINE... | Write a character to an output stream.
This method writes one character (byte) to the output stream.
Arguments:
c - The character to be written. If c is not a string
instance, an attempt will be made to convert it to
a chr.
Return Value(s):
The character that was written.
Side Effects:
... | 625941cf26068e7796caee34 |
def sentence_normalizer(sentence): <NEW_LINE> <INDENT> replacements = { '. _.': ' ._.', } <NEW_LINE> pattern = re.compile(r'\w+', re.U) <NEW_LINE> sentences = [word.strip() for word in re.split(r'(\.)', sentence) if word] <NEW_LINE> ending = '.' <NEW_LINE> output = [] <NEW_LINE> for word in sentences: <NEW_LINE> <INDEN... | >>> print(sentence_normalizer("чот рофл, ходил "))
Чот рофл, ходил.
>>> print(sentence_normalizer("как же так("))
Как же так(
>>> print(sentence_normalizer('Рофел'))
Рофел.
>>> print(sentence_normalizer('а'))
А.
>>> print(sentence_normalizer('.один... два, три .. четыре. пять'))
Один... Два, три.. Четыре. Пять.
>>> pri... | 625941cf99fddb7c1c9de4e6 |
@WebApp.route('/digest/comments/<SumCheck>', methods=['GET', 'POST']) <NEW_LINE> def digest_comments(SumCheck): <NEW_LINE> <INDENT> if (False == IsSessValid()): <NEW_LINE> <INDENT> return redirect(url_for("login")) <NEW_LINE> <DEDENT> if IsShowPage(session["user_id"], MENU_DIC['Digest']) == FALSE: <NEW_LINE> <INDENT> r... | @note 前台MySQL Digest某一sumcheck提交的comment存入数据库
:param SumCheck:
:return: | 625941cf56b00c62f0f147af |
def normalizeRatings(Y, R): <NEW_LINE> <INDENT> m, n = Y.shape <NEW_LINE> Ymean = np.zeros((m, 1)) <NEW_LINE> Ynorm = np.zeros((m, n)) <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> idx = np.where(R[i, :] == 1) <NEW_LINE> Ymean[i] = np.mean(Y[i, idx]) <NEW_LINE> Ynorm[i, idx] = Y[i, idx] - Ymean[i] <NEW_LINE> <DEDEN... | Preprocess data by subtracting mean rating for every
movie (every row)
Ynorm, Ymean = NORMALIZERATINGS(Y, R) normalized Y so that each movie
has a rating of 0 on average, and returns the mean rating in Ymean. | 625941cf4527f215b584c5ab |
def WDL(x1,x2): <NEW_LINE> <INDENT> x1,x2=list(x1),list(x2) <NEW_LINE> w,d,l=0,0,0 <NEW_LINE> for i,j in zip(x1,x2): <NEW_LINE> <INDENT> i,j=round(i,3),round(j,3) <NEW_LINE> if(i<j): <NEW_LINE> <INDENT> l+=1 <NEW_LINE> <DEDENT> elif(i>j): <NEW_LINE> <INDENT> w+=1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> d+=1 <NEW_... | x1的wdl值 | 625941cf10dbd63aa1bd2cf9 |
def __init__(self, conditions): <NEW_LINE> <INDENT> self.conditions = conditions <NEW_LINE> self.widgets = [] <NEW_LINE> for c in conditions: <NEW_LINE> <INDENT> c.register_switcher(self) | __init__
:param conditions:
| 625941cff548e778e58cd6d3 |
def get_sent_pkts_times_at(self, node_id, flow_id, lvl = 'MAC'): <NEW_LINE> <INDENT> sent_times = [] <NEW_LINE> for line in self.input_lines: <NEW_LINE> <INDENT> send_event_found = find_send_event.search(line) <NEW_LINE> if send_event_found: <NEW_LINE> <INDENT> trac_lvl_found = get_trace_lvl.search(line) <NEW_LINE> if ... | Gets sent pkts times | 625941cfdc8b845886cb568a |
def export_resource(storage, table, schema, data): <NEW_LINE> <INDENT> helpers.ensure_dir(schema) <NEW_LINE> with io.open(schema, mode=helpers.WRITE_MODE, encoding=helpers.WRITE_ENCODING) as file: <NEW_LINE> <INDENT> schema = storage.describe(table) <NEW_LINE> json.dump(schema, file, indent=4) <NEW_LINE> <DEDENT> helpe... | Export JSONTableSchema resource from storage's table.
Parameters
----------
storage: object
Storage object.
table: str
Table name.
schema: str
Path to schema file.
data: str
Path to data file. | 625941cf656771135c3eb9c4 |
def image(self, filename, load_callback=None, post_callback=None, **kwargs): <NEW_LINE> <INDENT> data = Cache.get('kv.loader', filename) <NEW_LINE> if data not in (None, False): <NEW_LINE> <INDENT> return ProxyImage(data, loading_image=self.loading_image, loaded=True, **kwargs) <NEW_LINE> <DEDENT> client = ProxyImage(s... | Load a image using the Loader. A ProxyImage is returned with a
loading image. You can use it as follows::
from kivy.app import App
from kivy.uix.image import Image
from kivy.loader import Loader
class TestApp(App):
def _image_loaded(self, proxyImage):
if proxyImage.image.texture:
... | 625941cf82261d6c526ab5f5 |
def sfl_thsph_temp_th(tc_rawdec_H, e2l_H, l2s_H, ts_rawdec_r, e2l_r, l2s_r, s2v_r): <NEW_LINE> <INDENT> V_tc_actual_H = sfl_thsph_temp_labcal_h(tc_rawdec_H, e2l_H) <NEW_LINE> T_ts_r = sfl_thsph_temp_ref(ts_rawdec_r, e2l_r, l2s_r) <NEW_LINE> T_ts_r[np.equal(T_ts_r, fill_value)] = np.nan <NEW_LINE> V_ts_r = eval_poly(T_t... | Description:
OOI Level 1 THSPH data product THSPHTE-TH (final temperature at position
"H" near sample inlet), which is calculated using data from the Hydrothermal
Vent Fluid In-situ Chemistry (THSPH) instrument, series A (one series for all
instruments).
Implemented by:
2014-05-01: Russell Deside... | 625941cf24f1403a92600cba |
def auto_login(self, hotReload=False, statusStorageDir='tars.pkl', enableCmdQR=False, picDir=None, qrCallback=None, loginCallback=None, exitCallback=None): <NEW_LINE> <INDENT> raise NotImplementedError() | log in like web wechat does
for log in
- a QR code will be downloaded and opened
- then scanning status is logged, it paused for you confirm
- finally it logged in and show your nickName
for options
- hotReload: enable hot reload
- statusStorageDir: dir for storing log in status
- enableCmdQR: s... | 625941cf460517430c3942d9 |
def compHorizontal(p1, p2): <NEW_LINE> <INDENT> return p1[Y] - p2[Y] | Compare according to Y coordinate for horizontal partitioning. | 625941cfa4f1c619b28b018d |
@main.command() <NEW_LINE> @click.argument('tmdb_id') <NEW_LINE> @click.pass_context <NEW_LINE> def delete(ctx, tmdb_id): <NEW_LINE> <INDENT> ctx.obj.delete(tmdb_id) <NEW_LINE> ctx.obj.write_config() | Remove movie indicated by TMDB_ID from your list. | 625941cf01c39578d7e74f90 |
def __init__(self, variable_name: str, context: JSGContext, value: Any, **kwargs): <NEW_LINE> <INDENT> match = False <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> self.val = JSGArray(variable_name, context, AnyType, 0, None, value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for t in any_types: <NEW_LIN... | Construct a wild card variable
:param variable_name: name of attribute for error reporting
:param context: context for use in JSGArrays
:param val: value
:param kwargs: named arguments | 625941cf9f2886367277a9e2 |
def get_guessed_word(secret_word, letters_guessed): <NEW_LINE> <INDENT> res_string = "" <NEW_LINE> for c in secret_word: <NEW_LINE> <INDENT> if c in letters_guessed: <NEW_LINE> <INDENT> res_string += c <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> res_string += "_ " <NEW_LINE> <DEDENT> <DEDENT> return res_string | secret_word: string, the word the user is guessing
letters_guessed: list (of letters), which letters have been guessed so far
returns: string, comprised of letters, underscores (_), and spaces that represents
which letters in secret_word have been guessed so far. | 625941cfde87d2750b85fee8 |
def query_object(self, channel_id, database_id, do_id, callback, dclass=None, field_names=()): <NEW_LINE> <INDENT> ctx = self.get_context() <NEW_LINE> self._callbacks[ctx] = callback <NEW_LINE> self._dclasses[ctx] = dclass <NEW_LINE> dg = io.NetworkDatagram() <NEW_LINE> if not field_names: <NEW_LINE> <INDENT> dg.add_he... | Query object `do_id` out of the database.
On success, the callback will be invoked as callback(dclass, fields)
where dclass is a DCClass instance and fields is a dict.
On failure, the callback will be invoked as callback(None, None). | 625941cf07d97122c41789e2 |
def machine_cellular_modules_status(self, machine_id, cellular_module_id, tenant_id=None, api_version="v2.0"): <NEW_LINE> <INDENT> if tenant_id is None and self._parent_class.tenant_id: <NEW_LINE> <INDENT> tenant_id = self._parent_class.tenant_id <NEW_LINE> <DEDENT> elif not tenant_id: <NEW_LINE> <INDENT> raise TypeErr... | GET Machine_Cellular_Modules_Status API Function
**Parameters:**:
- **machine_id**: Machine ID
- **cellular_module_id**: Cellular Module ID
- **tenant_id**: Tenant ID
- **api_version**: API version to use (default v2.0)
**Returns:** requests.Response object extended with cgx_status and cgx_content properti... | 625941cfb57a9660fec339da |
def plot_implicit(fn, bbox=(-2.5,2.5)): <NEW_LINE> <INDENT> ax = orthogonal_plot() <NEW_LINE> xmin, xmax, ymin, ymax, zmin, zmax = bbox*3 <NEW_LINE> A = np.linspace(xmin, xmax, 100) <NEW_LINE> B = np.linspace(xmin, xmax, 15) <NEW_LINE> A1,A2 = np.meshgrid(A,A) <NEW_LINE> for z in B: <NEW_LINE> <INDENT> X,Y = A1,A2 <NEW... | create a plot of an implicit function
fn ...implicit function (plot where fn==0)
bbox ..the x,y,and z limits of plotted interval | 625941cf287bf620b61d3bb9 |
def _handle_jenkins(self, job): <NEW_LINE> <INDENT> notif_time = strftime("%H:%M", gmtime()) <NEW_LINE> if job['inprogress']: <NEW_LINE> <INDENT> return State.NEUTRAL <NEW_LINE> <DEDENT> job_name = job['name'] <NEW_LINE> result = job['result'] <NEW_LINE> state = State.NEUTRAL <NEW_LINE> if 'last_result' not in job: <NE... | Handles giving Jenkins notifications. | 625941cf498bea3a759b9c04 |
def do_inference_viterbi(ps, L, M, unary_params, pw_params, unary_features, pw_features, y_true=None, y_true_list=None): <NEW_LINE> <INDENT> assert(L > 1) <NEW_LINE> assert(L <= M) <NEW_LINE> assert(ps >= 0) <NEW_LINE> assert(ps < M) <NEW_LINE> if y_true is not None: <NEW_LINE> <INDENT> assert(y_true_list is not None a... | Inference using the Viterbi algorithm, could be:
- Train/prediction inference for single-label SSVM
- Prediction inference for multi-label SSVM | 625941cf23e79379d52ee6b9 |
def _hash(self, key): <NEW_LINE> <INDENT> return sum([ord(c) for c in str(key)]) % self._size | ::Additive Hash::
hashes the key provided(note that this is an internal api)
this method prefers a string or integer. | 625941cf8c3a873295158510 |
def _http_call(the_url, method, token, **kw): <NEW_LINE> <INDENT> body = None <NEW_LINE> params = None <NEW_LINE> boundary = None <NEW_LINE> if 'body' in kw.keys(): <NEW_LINE> <INDENT> body = kw['body'] <NEW_LINE> del kw['body'] <NEW_LINE> <DEDENT> if method == _HTTP_FILE: <NEW_LINE> <INDENT> filename = kw['file'] <NEW... | send an http request and return a json object if no error occurred. | 625941cf004d5f362079a488 |
def draw(cursor, out=sys.stdout, paginate=True, max_fieldsize=100): <NEW_LINE> <INDENT> def heading_line(sizes): <NEW_LINE> <INDENT> for size in sizes: <NEW_LINE> <INDENT> write_bytes('+' + '-' * (size + 2), out) <NEW_LINE> <DEDENT> write_bytes('+\n', out) <NEW_LINE> <DEDENT> def draw_headings(headings, sizes): <NEW_LI... | Render an result set as an ascii-table.
Renders an SQL result set to `out`, some file-like object.
Assumes that we can determine the current terminal height and
width via the termsize module.
Args:
cursor: An iterable of rows. Each row is a list or tuple
with index access to each cell. The cursor
... | 625941cfb830903b967e9a60 |
def generate_cpp(self): <NEW_LINE> <INDENT> True | Nothing to do...
| 625941cfcdde0d52a9e53189 |
def var_limits(plotdata,vars,padding=0.1): <NEW_LINE> <INDENT> varlim = {} <NEW_LINE> vmin,vmax = var_minmax(plotdata,'all',vars) <NEW_LINE> varmin = {} <NEW_LINE> varmax = {} <NEW_LINE> for var in vars: <NEW_LINE> <INDENT> varmin[var] = vmin[var]['all'] <NEW_LINE> varmax[var] = vmax[var]['all'] <NEW_LINE> v1 = varmin[... | Determine range of values encountered in data for all frames
in the most recent computation in order to determine appropriate
y-axis limits for plots.
vars is a list of variables to return the limits for.
Each element of the list can be a number, indicating the
corresponding element of the q vector, or a function that... | 625941cf5fdd1c0f98dc0389 |
def negate_surrounding_sites (map_data, xray_structure, iselection, radius=1.5) : <NEW_LINE> <INDENT> import mmtbx.refinement.real_space <NEW_LINE> negate_selection = mmtbx.refinement.real_space.selection_around_to_negate( xray_structure = xray_structure, selection_within_radius = 5, iselection = ... | Makes the target map negative around an atom selection. | 625941cf8c3a873295158511 |
def errortokenpos(tokenoffset): <NEW_LINE> <INDENT> if isinstance(tokenoffset, ParserError): <NEW_LINE> <INDENT> for prevexc in iter(lambda: tokenoffset.prevexc, None): <NEW_LINE> <INDENT> tokenoffset = prevexc <NEW_LINE> <DEDENT> tokenoffset = tokenoffset.pos <NEW_LINE> <DEDENT> return tokenoffset | Find the root cause in the chain of parser errors
and return the token position where the parser could
no longer advance. | 625941cf377c676e912722fe |
def _convert_slice_v9(builder, node, graph, err): <NEW_LINE> <INDENT> INT_MAX = 2 ** 30 <NEW_LINE> logging.warn(graph.shape_dict) <NEW_LINE> data_shape = graph.shape_dict[node.inputs[0]] <NEW_LINE> len_of_data = len(data_shape) <NEW_LINE> begin_masks = [True] * len_of_data <NEW_LINE> end_masks = [True] * len_of_data <N... | convert to CoreML Slice Static Layer:
https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L5082 | 625941cf7b180e01f3dc4952 |
@set_module('numpy') <NEW_LINE> def ascontiguousarray(a, dtype=None): <NEW_LINE> <INDENT> return array(a, dtype, copy=False, order='C', ndmin=1) | Return a contiguous array (ndim >= 1) in memory (C order).
Parameters
----------
a : array_like
Input array.
dtype : str or dtype object, optional
Data-type of returned array.
Returns
-------
out : ndarray
Contiguous array of same shape and content as `a`, with type `dtype`
if specified.
See Also
---... | 625941cfbd1bec0571d90785 |
@celery_instance.task <NEW_LINE> def monitor_check_platform_telemetry_data(): <NEW_LINE> <INDENT> logger.info("Monitor MonitorPlatformTelemetryData started") <NEW_LINE> monitor = MonitorPlatformTelemetryData() <NEW_LINE> rt = False <NEW_LINE> if monitor.start(): <NEW_LINE> <INDENT> rt = True <NEW_LINE> <DEDENT> logger.... | Uses the AV Doctor to get data from the deployed systems, and returns telemetry data.
Returns:
True if successful, False otherwise | 625941cf293b9510aa2c33eb |
def build_graph(self): <NEW_LINE> <INDENT> tf.logging.info('Building graph...') <NEW_LINE> t0 = time.time() <NEW_LINE> self._add_placeholders() <NEW_LINE> with tf.device("/gpu:0"): <NEW_LINE> <INDENT> self._add_seq2seq() <NEW_LINE> <DEDENT> self.global_step = tf.Variable(0, name='global_step', trainable=False) <NEW_LIN... | Add the placeholders, models, global step, train_op and summaries to the graph | 625941cf5f7d997b87174bee |
def _g_check_name(self, name): <NEW_LINE> <INDENT> if name.startswith('_i_'): <NEW_LINE> <INDENT> raise ValueError( "node name starts with reserved prefix ``_i_``: %s" % name) | Check validity of name for this particular kind of node.
This is invoked once the standard HDF5 and natural naming checks
have successfully passed. | 625941cf236d856c2ad44931 |
def test_empty_anonymous_struct(self): <NEW_LINE> <INDENT> expected = {'fields': []} <NEW_LINE> code = 'struct {};' <NEW_LINE> self.assert_parse_equal(code, expected) | A.4.1. Hello Messages | 625941cfa934411ee37517e9 |
@app.route('/books/<int:isbn>') <NEW_LINE> def get_single_books(isbn): <NEW_LINE> <INDENT> return_value = {} <NEW_LINE> for book in books: <NEW_LINE> <INDENT> if book["isbn"] == isbn: <NEW_LINE> <INDENT> return_value = { 'name': book["name"], 'price': book["price"], 'isbn': book["isbn"], } <NEW_LINE> <DEDENT> <DEDENT> ... | This end point returns a single books
| 625941cf4527f215b584c5ac |
@pytest.mark.filterwarnings("ignore:some coarse channel files were not submitted") <NEW_LINE> @pytest.mark.filterwarnings("ignore:cable length correction is now defaulted to True") <NEW_LINE> def test_start_flag(tmp_path): <NEW_LINE> <INDENT> uv1 = UVData() <NEW_LINE> uv1.read_mwa_corr_fits( filelist[0:2], flag_init=Tr... | Test the default value of start_flag. | 625941cfd18da76e2353262c |
def getBestMovies(ratingsArr, num): <NEW_LINE> <INDENT> ratingsMap = dict() <NEW_LINE> countsMap = dict() <NEW_LINE> allNumRatings = [] <NEW_LINE> lstOfValidMovies = [] <NEW_LINE> bestMovies = [] <NEW_LINE> for i in ratingsArr: <NEW_LINE> <INDENT> currentMovie = i[1] <NEW_LINE> if currentMovie not in ratingsMap: <NEW_L... | This returns the IDs of the top highest rated movies | 625941cf2c8b7c6e89b35916 |
def __len__(self): <NEW_LINE> <INDENT> if self.drop_remainder: <NEW_LINE> <INDENT> return int(np.floor(self._n_sample / self._batch_size)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return int(np.ceil(self._n_sample / self._batch_size)) | :return: the number of batches per epoch | 625941cfdd821e528d63b2fe |
def vectorize_data(texts): <NEW_LINE> <INDENT> vectorizer = TfidfVectorizer() <NEW_LINE> transformation = vectorizer.fit_transform(texts) <NEW_LINE> dimensionality_notion = len(transformation.toarray()[0]) <NEW_LINE> return transformation, dimensionality_notion | This function vectorizes text to matrices. | 625941cfa79ad161976cc29b |
def unprotect_floating_ip(self, floating_ip, ignore_missing=True): <NEW_LINE> <INDENT> return self._delete(_floating_ip.FloatingIP, floating_ip, ignore_missing=ignore_missing) | Diable anti-ddos on the given Floating IP
:param floating_ip_id: The EIP id or an instance of
:class:`~otcextensions.sdk.anti_ddos.v1.floating_ip.FloatingIP`
:param bool ignore_missing: When set to ``False``
:class:`~otcextensions.sdk.exceptions.ResourceNotFound` will be
raised when the floating IP does no... | 625941cf21bff66bcd684aa8 |
def _unicode(self, octave_modifier=0): <NEW_LINE> <INDENT> ustr = self._ln <NEW_LINE> if self._modifier_value: <NEW_LINE> <INDENT> ustr = "".join([ustr, self._modifier.u]) <NEW_LINE> <DEDENT> if self._v._has_octave: <NEW_LINE> <INDENT> ustr = "".join([ustr, str(self._v.o + octave_modifier)]) <NEW_LINE> <DEDENT> return ... | Returns a human readable representation of the note, with Unicode modifiers (♯, ♭).
The octave_modifier can be used to set the octave designation for middle C.
(In OMK, middle C == C0. In MIDI etc., middle C == C4).
Examples
--------
>>> TonalVector((0,1)).note._unicode()
'C♯'
>>> TonalVector((1,1,0)).note._unicode(... | 625941cf26238365f5f0efc4 |
def parse_type_condition(self) -> NamedTypeNode: <NEW_LINE> <INDENT> self.expect_keyword("on") <NEW_LINE> return self.parse_named_type() | TypeCondition: NamedType | 625941cfac7a0e7691ed4221 |
def main() -> None: <NEW_LINE> <INDENT> parser = argparse.ArgumentParser( description="Unicron task scheduler.", epilog="Run against the test var directory by using TEST=true as a prefix.", ) <NEW_LINE> parser.add_argument( "-v", "--verbose", help="If supplied, print all app log messages to the console and not" " just ... | Main command-line argument parser.
Exit app with error code if there are any task failures. | 625941cf9f2886367277a9e3 |
def loads(jsonText): <NEW_LINE> <INDENT> m = Metadata(**json.loads(jsonText)) <NEW_LINE> interpret_all_date_tags(m) <NEW_LINE> return m | Converts the JSON text given into a Metadata object. | 625941cf45492302aab5e41a |
def _AddAnomalyForTest(self, sheriff_key, test_key, revision, median_before, median_after, bug_id=None): <NEW_LINE> <INDENT> if bug_id > 0: <NEW_LINE> <INDENT> bug = ndb.Key('Bug', bug_id).get() <NEW_LINE> if not bug: <NEW_LINE> <INDENT> bug_data.Bug(id=bug_id).put() <NEW_LINE> <DEDENT> <DEDENT> return anomaly.Anomaly(... | Adds a sample Anomaly and returns the key. | 625941cf004d5f362079a489 |
def is_centered_plant(self, plant): <NEW_LINE> <INDENT> delta = min(self.get_dynamic_delta(plant), 120) <NEW_LINE> log.info("Acceptance interval: {}".format(delta)) <NEW_LINE> left = self.frame_midpoint - delta <NEW_LINE> right = self.frame_midpoint + delta <NEW_LINE> bb_midpoint = self.get_bb_midpoint(plant) <NEW_LINE... | Checks if object is located in the [midpoint-delta, midpoint+delta] interval.
:param plant:
:return: | 625941cff8510a7c17cf9851 |
@pytest.mark.parametrize('socket', [ ('tcp://127.0.0.1:8126'), ('udp://127.0.0.1:8125'), ]) <NEW_LINE> def test_sockets(host, socket): <NEW_LINE> <INDENT> assert host.socket(socket).is_listening | Test all statsd sockets | 625941cf3eb6a72ae02ec635 |
def sessionattendancelog_get_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ 'id', 'photosize' ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_... | View details of a class attendance log # noqa: E501
Allows the user to view an individual class attendance log and its details. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.sessionattendancelog_get_with_http_in... | 625941cf15fb5d323cde0c66 |
def __init__(self): <NEW_LINE> <INDENT> self.url = "http://" + service_ip + "/compute/v2.1/os-hypervisors" <NEW_LINE> self.requests = api_request() | Class initialization. | 625941cfe76e3b2f99f3a960 |
def run(self): <NEW_LINE> <INDENT> s = sampling(self.prob) <NEW_LINE> x, y, self.prob.conrhs, self.prob.contype, self.convio, self.condropind = s.create(self.condropind, self.convio) <NEW_LINE> self.nsample += x.shape[0] <NEW_LINE> if self.condropind: <NEW_LINE> <INDENT> self.yall = np.delete(self.yall, self.condropind... | Main function for surrogate-based optimization. This class performs
sampling, surrogate modeling, and optimization until convergence.
Returns:
stat: convergence status; 1 for convergence; 0 else
xbest: best optimal solution for x
ybest: best optimal solution for y
viobest: constraint violation of the... | 625941cf99cbb53fe6792d3c |
@pytest.yield_fixture() <NEW_LINE> def admin_user(db): <NEW_LINE> <INDENT> perms = [ location_update_all, bucket_read_all, bucket_read_versions_all, bucket_update_all, bucket_listmultiparts_all, object_read_all, object_read_version_all, object_delete_all, object_delete_version_all, multipart_read_all, multipart_delete_... | Permission for admin users. | 625941cf6e29344779a62767 |
def test_one2one_reference_field(): <NEW_LINE> <INDENT> pass | >>> db = get_connection('sqlite://')
>>> db.metadata.drop_all()
>>> class Test(Model):
... username = Field(str)
... year = Field(int)
>>> class Test1(Model):
... test = OneToOne(Test, reference_fieldname='username')
... name = Field(str)
>>> a1 = Test(username='limodou1')
>>> a1.save()
True
>>> b1 = Te... | 625941cfa05bb46b383ec977 |
def rgate(seed: Optional[int] = None, angle_scale: float = 1.0): <NEW_LINE> <INDENT> if seed: <NEW_LINE> <INDENT> np.random.seed(seed) <NEW_LINE> <DEDENT> theta, alpha, phi = np.random.rand(3) * 2 * np.pi <NEW_LINE> mx = np.sin(alpha) * np.cos(phi) <NEW_LINE> my = np.sin(alpha) * np.sin(phi) <NEW_LINE> mz = np.cos(alph... | Returns the random single qubit gate described in
https://arxiv.org/abs/2002.07730.
Args:
seed: Seed for random number generator.
angle_scale: Floating point value to scale angles by. Default 1. | 625941cfff9c53063f47c349 |
def twoSum(self, nums, target): <NEW_LINE> <INDENT> if len(nums) <= 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> hash = {} <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> if target - nums[i] in hash: <NEW_LINE> <INDENT> return [hash[target - nums[i]], i] <NEW_LINE> <DEDENT> hash[nums[i]] = i <NEW_L... | :type nums: List[int]
:type target: int
:rtype: List[int] | 625941cf85dfad0860c3afb1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.