code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def test_clear_emtpy_markers(self): <NEW_LINE> <INDENT> dat = self.dat.copy() <NEW_LINE> dat.markers = [] <NEW_LINE> dat2 = clear_markers(dat) <NEW_LINE> self.assertEqual(dat, dat2) | Clearing emtpy markers has no effect. | 625941c3596a897236089a78 |
def _check_description(description: str, starts_with_verb: bool) -> Optional[str]: <NEW_LINE> <INDENT> if description == "": <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if not description[:1].isalpha(): <NEW_LINE> <INDENT> return "description should start with alphanumeric character" <NEW_LINE> <DEDENT> if desc... | Check whether a description is well-styled.
:param description: the description
:param starts_with_verb:
if True, check that the description should start with a verb in third person singular (stem -s).
:return: the failed check, if any | 625941c3d486a94d0b98e0fa |
def test_returns_list(self): <NEW_LINE> <INDENT> self.assertIsInstance(self.products, list) | Test returns a list instance. | 625941c350812a4eaa59c2d8 |
def save_as(self): <NEW_LINE> <INDENT> if self.filename: <NEW_LINE> <INDENT> prev_dir = os.path.dirname(self.filename) <NEW_LINE> prev_name = os.path.basename(self.filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> prev_dir = None <NEW_LINE> prev_name = None <NEW_LINE> <DEDENT> saved = save_dialog(self.save_filena... | Show the save dialog. Return True if was saved. | 625941c3a8370b7717052855 |
def __init__(self, name): <NEW_LINE> <INDENT> assert not '/' in name <NEW_LINE> assert not '.java' in name <NEW_LINE> Declaration.__init__(self, name) | The name of the dependency, initially what the user types "com.biicode.Class"
The Case is stored as typed by the user, no changes until it is found and managed by biicode | 625941c385dfad0860c3ae0f |
def peek(self): <NEW_LINE> <INDENT> if not self.heap: <NEW_LINE> <INDENT> return None, None <NEW_LINE> <DEDENT> item = self.heap[0] <NEW_LINE> return item[1][0], item[1][1] | Returns the first item in the heap (with the highest priority (smallest value))
with popping from the heap
Returns:
dp_id, pkt | 625941c3dc8b845886cb54e9 |
def get_wait_game(): <NEW_LINE> <INDENT> f = open(DATABASE_FILE, 'r') <NEW_LINE> game_list = json.loads(f.read()) <NEW_LINE> f.close() <NEW_LINE> wait_game_list = [] <NEW_LINE> for cur_game in game_list: <NEW_LINE> <INDENT> if cur_game['status'] == 'wait': <NEW_LINE> <INDENT> wait_game_list.append(cur_game) <NEW_LINE> ... | 获取正在等待中的游戏列表
:return: | 625941c3f9cc0f698b1405b2 |
def _lookup_iocs(self, all_iocs, resource_per_req=25): <NEW_LINE> <INDENT> threat_info = {} <NEW_LINE> cache_file_name = config_get_deep('virustotal.LookupDomainsFilter.cache_file_name', None) <NEW_LINE> vt = VirusTotalApi(self._api_key, resource_per_req, cache_file_name=cache_file_name) <NEW_LINE> iocs = [x for x in a... | Caches the VirusTotal info for a set of domains.
Domains on a whitelist will be ignored.
Args:
all_iocs - a list of domains.
Returns:
A dict with domain as key and threat info as value | 625941c350812a4eaa59c2d9 |
def insertResource( self, resourceName, resourceType, serviceType, siteName, gridSiteName, meta = None ): <NEW_LINE> <INDENT> return self.__query( 'insert', 'Resource', locals() ) | Inserts on Resource a new row with the arguments given.
:Parameters:
**resourceName** - `string`
name of the resource
**resourceType** - `string`
it has to be a valid resource type, any of the defaults: `CE` | `CREAMCE` ...
**serviceType** - `string`
type of the service it belongs, defaults ... | 625941c37c178a314d6ef411 |
def _set_param(self, name, value): <NEW_LINE> <INDENT> if name in self.PARAMS: <NEW_LINE> <INDENT> if self._validate_param(name, value): <NEW_LINE> <INDENT> self._params[name] = value <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> return False | set parameter, with validation | 625941c3c4546d3d9de729e7 |
def _on_message(self, sender, message): <NEW_LINE> <INDENT> logger.info("Received message {0} from {1}".format(message, sender)) <NEW_LINE> if len(message) < 3: <NEW_LINE> <INDENT> logger.info('Message is too short to be something!') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if message[:1] == b'\x02': <NEW_LINE> <I... | Message receiving callback
:param sender: Message sender
:param message: The message | 625941c3bf627c535bc13184 |
def test_update_g(): <NEW_LINE> <INDENT> color = Color(100, 142, 438) <NEW_LINE> assert color.get_r() == 100 <NEW_LINE> assert color.get_g() == 142 <NEW_LINE> assert color.get_b() == 438 <NEW_LINE> update_g(color, 239) <NEW_LINE> assert color.get_r() == 100 <NEW_LINE> assert color.get_g() == 239 <NEW_LINE> assert color... | Test function for update_g function
:return: Tests pass if g component is updated properly, false if otherwise. | 625941c3b57a9660fec33837 |
def test_ObjectNotDictError(): <NEW_LINE> <INDENT> assert_equals( 'Try to inialize with a non-dict object: test', str(ObjectNotDictError('test')) ) | 测试stock_price_crawler.config的ObjectNotDictError异常类
:return: | 625941c345492302aab5e277 |
def _find_obj(self, obj): <NEW_LINE> <INDENT> for _, provider_class in self.providers.items(): <NEW_LINE> <INDENT> if obj == provider_class or obj == provider_class.__class__: <NEW_LINE> <INDENT> return_obj = provider_class <NEW_LINE> self.fire_hook('resolve', obj, return_obj) <NEW_LINE> return return_obj <NEW_LINE> <D... | Find an object in the container.
Arguments:
obj {object} -- Any object in the container
Raises:
MissingContainerBindingNotFound -- Raised when the object cannot be found.
Returns:
object -- Returns the object in the container | 625941c37b25080760e3940f |
def calcLikeness(dist1, dist2): <NEW_LINE> <INDENT> likeness = 1-((np.sum(abs(dist1-dist2))/2)) <NEW_LINE> return likeness | Computes the likeness metric on 2 samples.
Parameters
----------
dist1, dist2 : Relative probability distributions (e.g., PDP, KDE)
Returns
-------
sim : float
likeness metric
Notes
-----
dist1 and dist2 must have the same length.
Based on Saylor and Sundell, 2016: Geosphere, v. 12, doi:10.1130/GES01237.1 | 625941c3a17c0f6771cbe007 |
def list_cmd(self) -> Dict[str, Dict[str, Any]]: <NEW_LINE> <INDENT> data = self.run_cmd("list", "--json") <NEW_LINE> return json.loads(data) | Executes "eden list --json" to list the Eden checkouts and returns the result as
a dictionary. | 625941c35fdd1c0f98dc01e8 |
def CrossProduct(self, *args): <NEW_LINE> <INDENT> return _stomp.AngularCoordinate_CrossProduct(self, *args) | CrossProduct(AngularCoordinate self, AngularCoordinate ang, Stomp::AngularCoordinate::Sphere sphere=Equatorial) -> AngularCoordinate
CrossProduct(AngularCoordinate self, AngularCoordinate ang) -> AngularCoordinate | 625941c397e22403b379cf4e |
def test_extract_new_page(soup) -> None: <NEW_LINE> <INDENT> result = extract_next_page(parser=soup) <NEW_LINE> assert result == "?nextpagelink" | Test to check if "extract_new_page" func returns correct next page link | 625941c3de87d2750b85fd46 |
def update_chat_read_count(self, game_id: int, messages_read: int): <NEW_LINE> <INDENT> headers = { "User-Agent": "WebFeudClient/3.0.17 (Android 10)", "Content-Type": "application/json; charset=UTF-8", "Content-Length": "0", "Host": "api.wordfeud.com", "Connection": "Keep-Alive", "Accept-Encoding": "gzip", "Cookie": f"... | Inform the server about the number of messages in chat you have seen (in total, not new)
Args:
game_id (int): ID of the game with a chat
messages_read (int): The amount of messages you have read
Returns:
dict: Parsed server response | 625941c3377c676e9127215e |
def checkLanguage(text): <NEW_LINE> <INDENT> global validLanguageList <NEW_LINE> from langdetect import detect <NEW_LINE> wordCaption = getPlainText(text) <NEW_LINE> if detect(wordCaption) not in validLanguageList: <NEW_LINE> <INDENT> print(" foreign: ", detect(wordCaption)); <NEW_LINE> return False <NEW_LINE> <DEDEN... | check if item is in the english language, prints if foreign | 625941c3656771135c3eb822 |
def __init__(self, json_dict, lt_id): <NEW_LINE> <INDENT> self.book_id = json_dict[lt_id]["book_id"] <NEW_LINE> self.book_title = json_dict[lt_id]["title"] <NEW_LINE> self.book_author_lf = json_dict[lt_id]["author_lf"] <NEW_LINE> self.book_author_fl = json_dict[lt_id]["author_fl"] <NEW_LINE> self.book_author_code = jso... | Collects the individual book data from Library Thing's JSON export
Args:
json_dict (dictionary): Expects a JSON object
lt_id (integer): Key for the JSON object. In the LT import, this is LT's internal book ID.
Structure: (curly braces indicate generic explanations)
self.{SQLite field name} = json_dict[{Ke... | 625941c394891a1f4081ba5e |
@app.route('/') <NEW_LINE> @app.route('/home') <NEW_LINE> def home(): <NEW_LINE> <INDENT> name = 'Sherline' <NEW_LINE> return render_template( 'index.html', name = name ) | Renders the home page. | 625941c3cc0a2c11143dce45 |
def get_prediction(probability_setting, opposite): <NEW_LINE> <INDENT> mu = probability_setting['mu'] <NEW_LINE> if opposite: <NEW_LINE> <INDENT> mu = 1 - mu <NEW_LINE> <DEDENT> return np.random.normal(mu, probability_setting['sigma']) | Returns a normally distributed random number. | 625941c33cc13d1c6d3c7330 |
def setUp(self): <NEW_LINE> <INDENT> pass | _setUp_
Do nothing | 625941c3cc0a2c11143dce46 |
def t_MODULE(self, t): <NEW_LINE> <INDENT> return t | module | 625941c3091ae35668666f17 |
@app.route('/theme/<theme_id:request_theme>/rss.xml') <NEW_LINE> @cache.cached(timeout=CACHE_TTL) <NEW_LINE> def theme(request_theme): <NEW_LINE> <INDENT> items = db.video.select().where(db.video.themes.contains(request_theme.id)) <NEW_LINE> logo_url = '/logo/theme/%s.png' % request_theme.id <NEW_LINE> theme_feed = pod... | theme feed | 625941c3507cdc57c6306c8c |
def show_window_commands(self): <NEW_LINE> <INDENT> self.window.show_commands() | print the available commands for the selected display application | 625941c3167d2b6e31218b4b |
def _serialize_field(self, obj, field_name, parent): <NEW_LINE> <INDENT> self.obj = obj <NEW_LINE> if self.source == '*': <NEW_LINE> <INDENT> return self.serialize(obj) <NEW_LINE> <DEDENT> self.field_name = self.source or field_name <NEW_LINE> return self.serialize_field(obj, self.field_name) | The entry point into a field, as called by it's parent serializer. | 625941c3dd821e528d63b160 |
def _ReadIslandQuality86(): <NEW_LINE> <INDENT> with winreg.OpenKey( winreg.HKEY_LOCAL_MACHINE, x86regpath) as qualitystring: <NEW_LINE> <INDENT> quality = winreg.QueryValueEx(qualitystring, "Island Quality") <NEW_LINE> <DEDENT> quality = quality[0] <NEW_LINE> return quality | Read x86 'Island Quality' string | 625941c3d7e4931a7ee9ded2 |
def get_common_word_threshold(fdist): <NEW_LINE> <INDENT> threshold = get_word_frequency_at(fdist, COMMON_THRESH) <NEW_LINE> if threshold: <NEW_LINE> <INDENT> return threshold <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 2 | Returns frequency threshold for a common word. | 625941c326238365f5f0ee21 |
def launch_gateway(port=0, jarpath="", classpath="", javaopts=[], die_on_exit=False): <NEW_LINE> <INDENT> if not jarpath: <NEW_LINE> <INDENT> jarpath = find_jar_path() <NEW_LINE> <DEDENT> if not os.path.exists(jarpath): <NEW_LINE> <INDENT> raise Py4JError("Could not find py4j jar at {0}".format(jarpath)) <NEW_LINE> <DE... | Launch a `Gateway` in a new Java process.
:param port: the port to launch the Java Gateway on. If no port is
specified then an ephemeral port is used.
:param jarpath: the path to the Py4J jar. Only necessary if the jar
was installed at a non-standard location or if Python is using
a different `sys.prefix... | 625941c3a17c0f6771cbe008 |
def write(row, output, method='a'): <NEW_LINE> <INDENT> if not os.path.isfile(output) and method == 'a': <NEW_LINE> <INDENT> write(['uid','content','source','url','date','author','label'], output, 'w') <NEW_LINE> <DEDENT> with open(output, method) as f: <NEW_LINE> <INDENT> writer = csv.writer(f) <NEW_LINE> writer.write... | Writes result to file. | 625941c3167d2b6e31218b4c |
def is_number(var: Any) -> bool: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> float(var) <NEW_LINE> return True <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> return False | Check if variable is a numeric value.
Parameters
----------
var : object
Returns
-------
is_number : bool
True if var is numeric, False otherwise. | 625941c31d351010ab855ad2 |
@when('I ask Gremlin to find the package {package:S} version {version} in the ecosystem ' '{ecosystem}') <NEW_LINE> def gremlin_find_package_version(context, package, version, ecosystem): <NEW_LINE> <INDENT> query = Query().has("pecosystem", ecosystem).has("pname", package).has("version", version) <NEW_LINE> post_query... | Try to find the package with version in the selected ecosystem. | 625941c3004d5f362079a2ea |
def test_current_func(self): <NEW_LINE> <INDENT> self.assert_selector( self.MARKUP, ":current(p, div, a)", [], flags=util.HTML ) | Test the functional form of current (should match nothing). | 625941c3be7bc26dc91cd5b9 |
def load_file(fname): <NEW_LINE> <INDENT> mat = loadmat(fname) <NEW_LINE> mdata = mat['dataStruct'] <NEW_LINE> mtype = mdata.dtype <NEW_LINE> ndata = {n: mdata[n][0,0] for n in mtype.names} <NEW_LINE> data_headline = ndata['channelIndices'][0] <NEW_LINE> data_raw = ndata['data'] <NEW_LINE> pdata = pd.DataFrame(data_raw... | Load sample from file | 625941c34e4d5625662d4390 |
def _dumpAccessLogs(self) -> None: <NEW_LINE> <INDENT> if len(self._accessLog) > 0: <NEW_LINE> <INDENT> logger.warning('Failed job accessed files:') <NEW_LINE> for item in self._accessLog: <NEW_LINE> <INDENT> if len(item) == 2: <NEW_LINE> <INDENT> logger.warning('Downloaded file \'%s\' to path \'%s\'', *item) <NEW_LINE... | When something goes wrong, log a report.
Includes the files that were accessed while the file store was open. | 625941c399fddb7c1c9de347 |
def __predict(self, x): <NEW_LINE> <INDENT> labels = np.zeros(x.shape[0]).astype(np.int) <NEW_LINE> distance = np.full(x.shape[0], np.inf) <NEW_LINE> for i in range(self.k): <NEW_LINE> <INDENT> current_distance = np.sum((x - self.means[i]) ** 2, axis=1) <NEW_LINE> mask = distance > current_distance <NEW_LINE> labels[ma... | Predict the labels for input data, by calculating square Euclidean distance.
Args:
x: Array-like. Contains data to be predicted.
Return:
Array of size[amount of data,], contains labels of data.
| 625941c34428ac0f6e5ba7a7 |
def academic_degree(self): <NEW_LINE> <INDENT> degrees = self.data['academic_degree'] <NEW_LINE> return choice(degrees) | Get a random academic degree.
:return: Degree.
:Example:
Bachelor. | 625941c3711fe17d82542325 |
def sparse_matrix(self): <NEW_LINE> <INDENT> if sparse.issparse(self.matrix): <NEW_LINE> <INDENT> return self.matrix <NEW_LINE> <DEDENT> return sparse.csr_matrix(self.matrix) | return the sparse representation of this matrix, as a scipy matrix | 625941c3e8904600ed9f1ee0 |
def update(self, event=None): <NEW_LINE> <INDENT> user = os.getlogin() <NEW_LINE> date_formatted = time.strftime("%c") <NEW_LINE> classname = self._entity.__class__.__name__ <NEW_LINE> msg = 'Class : ' + classname + 'Name : ' + self._name + 'Date : ' + date_formatted + 'Event : ' + event <NEW_LINE> if event:... | Logs an activity update. | 625941c391af0d3eaac9b9cd |
def min(self): <NEW_LINE> <INDENT> if not self.sublocations: <NEW_LINE> <INDENT> return self.start <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> m = reduce(lambda x, y: min(x,y), map(lambda x: x.min(), self.sublocations), sys.maxint) <NEW_LINE> return m | Returns the minimum start value for this location.
:returns: int Minimum start value of this location | 625941c307d97122c417883d |
def my_load_dataset(dataset = 'mnist'): <NEW_LINE> <INDENT> if dataset == 'cifar10': <NEW_LINE> <INDENT> (x_train, y_train), (x_test, y_test) = cifar10.load_data() <NEW_LINE> img_rows, img_cols, img_chns = 32, 32, 3 <NEW_LINE> <DEDENT> elif dataset == 'mnist': <NEW_LINE> <INDENT> (x_train, y_train), (x_test, y_test) = ... | 625941c3e5267d203edcdc55 | |
def create_contributors(): <NEW_LINE> <INDENT> for contributor in repo_data.top_contributors(): <NEW_LINE> <INDENT> add_contributor(contributor) | method to add all current contributors to the database | 625941c3ac7a0e7691ed4086 |
def wait_connect(self) -> bool: <NEW_LINE> <INDENT> self._auth_event.wait() <NEW_LINE> if not self._auth_success: <NEW_LINE> <INDENT> log.error("Invalid credentials for connecting to XMPP server.") <NEW_LINE> return False <NEW_LINE> <DEDENT> self._connect_event.wait() <NEW_LINE> return True | Wait for client to connect.
Returns:
Success or not. | 625941c392d797404e30413f |
def __init__(self): <NEW_LINE> <INDENT> self.N = 0 <NEW_LINE> self.x = [] <NEW_LINE> self.y = [] <NEW_LINE> self.z = [] <NEW_LINE> self.a = [] <NEW_LINE> self.materials = [] | Creates empty collection of spheres. Use child classes for non-empty! | 625941c3be8e80087fb20bfb |
def print_upper_words_start(words, must_start_with): <NEW_LINE> <INDENT> for word in words: <NEW_LINE> <INDENT> for letter in must_start_with: <NEW_LINE> <INDENT> if word[0].upper() == letter.upper(): <NEW_LINE> <INDENT> print(word.upper()) | print words that start with letter | 625941c3009cb60464c63369 |
def validate(self): <NEW_LINE> <INDENT> return self._validate(self.root) | verify the tree by traversing the nodes and reproduce the hash | 625941c35fc7496912cc3934 |
def test_s_mtp_stat_router_get_all_aggregate_sub_account_provider_smtp_stats(self): <NEW_LINE> <INDENT> pass | Test case for s_mtp_stat_router_get_all_aggregate_sub_account_provider_smtp_stats
| 625941c33d592f4c4ed1d028 |
def abort(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.request('ABOR', *args, **kwargs) | Sends a ABOR request. Returns :class:`FTPResponse` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes. | 625941c34f6381625f1149f2 |
def pensize(turtle, width=None): <NEW_LINE> <INDENT> if type(turtle) != _turtle.Turtle: <NEW_LINE> <INDENT> raise(TypeError("turtle argument to pensize is not a valid turtle")) <NEW_LINE> <DEDENT> return turtle.pensize(width) | Set or return the line thickness.
Aliases: pensize | width
Arguments:
turtle -- the turtle
width -- positive number
Set the line thickness to width or return it. If resizemode is set
to "auto" and turtleshape is a polygon, that polygon is drawn with
the same line thickness. If no argument is given, current pensize
... | 625941c3097d151d1a222e11 |
def get_volumes(self): <NEW_LINE> <INDENT> self.lv_list = self.get_all_volumes(self.vg_name) <NEW_LINE> return self.lv_list | Get all LV's associated with this instantiation (VG).
:returns: List of Dictionaries with LV info | 625941c391f36d47f21ac4a7 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(SeqGen, self).__init__(reduce_alignment=False, **kwargs) | Instantiate. Mandatory arguments are a tree and GTR model.
| 625941c3fbf16365ca6f6176 |
def update_skill_name_dict(self, message): <NEW_LINE> <INDENT> self.skill_names[message.data['id']] = message.data['name'] | Messagebus handler, updates dictionary of if to skill name
conversions. | 625941c367a9b606de4a7e71 |
def searchByCritirea(crit1, crit2, crit2value): <NEW_LINE> <INDENT> result = df.loc[df[crit2] == crit2value, crit1].sum() <NEW_LINE> return result | Recieves problem to search for and returns that problem
when value of crit2 matches value given to function as crit2value.
Returns int. | 625941c33eb6a72ae02ec48e |
def sign_in(self, username='', password=''): <NEW_LINE> <INDENT> with open(self.DB_CONN, self.READ_MODE) as file: <NEW_LINE> <INDENT> records = file.readlines() <NEW_LINE> for record in records: <NEW_LINE> <INDENT> __username, __password = record.split(',')[:2] <NEW_LINE> if username == __username and password == __pas... | Provided the username and password the user sign-in
Keyword Arguments:
username {str} -- [description] (default: {''})
password {str} -- [description] (default: {''})
Returns:
Custom msg defined in the constructor | 625941c385dfad0860c3ae10 |
def data_to_message(self, data): <NEW_LINE> <INDENT> return [ self.child.data_to_message(item) for item in data ] | List of protobuf messages <- List of dicts of python primitive datatypes. | 625941c323e79379d52ee51c |
def get_val_outputs(self, use_one_hot=None): <NEW_LINE> <INDENT> if self._data['val_inds'] is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> out_data = self._data['out_data'][self._data['val_inds'], :] <NEW_LINE> return self._get_outputs(out_data, use_one_hot) | Get the outputs (targets) of all validation samples.
See documentation of method "get_train_outputs" for details.
Args:
use_one_hot: See "get_train_outputs".
Returns:
A 2D numpy array. Returns None if no validation set exists. | 625941c39b70327d1c4e0d8a |
def __getattr__(self, name): <NEW_LINE> <INDENT> return self.get_endpoint(name) | Summons endpoints.
E.g. api.mailing
:returns: EndpointProxy | 625941c36aa9bd52df036d59 |
def _collect_stix2_mappings(): <NEW_LINE> <INDENT> if not STIX2_OBJ_MAPS: <NEW_LINE> <INDENT> top_level_module = importlib.import_module('stix2') <NEW_LINE> path = top_level_module.__path__ <NEW_LINE> prefix = str(top_level_module.__name__) + '.' <NEW_LINE> for module_loader, name, is_pkg in pkgutil.walk_packages(path=... | Navigate the package once and retrieve all object mapping dicts for each
v2X package. Includes OBJ_MAP, OBJ_MAP_OBSERVABLE, EXT_MAP. | 625941c3e76e3b2f99f3a7c5 |
def test_port_v2(self): <NEW_LINE> <INDENT> conf.properties['main.server.port'] = '1234' <NEW_LINE> conf.properties['main.server.scheme'] = '' <NEW_LINE> self.assertEqual(get_server_url(), 'https://example.com:1234') | Hostname and port set, scheme blank. | 625941c35510c4643540f39f |
def home(request): <NEW_LINE> <INDENT> qs = Deck.objects.all <NEW_LINE> context = {} <NEW_LINE> return render(request, 'flashcards/home.html') | Render the FLASHCARD app home template | 625941c3ec188e330fd5a759 |
def __init__(self, A, B, pi): <NEW_LINE> <INDENT> self.A = np.array(A) <NEW_LINE> self.B = np.array(B) <NEW_LINE> self.pi = np.array(pi) <NEW_LINE> self.N = self.A.shape[0] <NEW_LINE> self.M = self.B.shape[1] | ''
A: 状态转移概率矩阵
B: 输出观察概率矩阵
pi: 初始化状态向量 | 625941c3bd1bec0571d905e5 |
def save_monitor_command(self, server, timestamp, command, keyname, argument): <NEW_LINE> <INDENT> epoch = timestamp.strftime('%s') <NEW_LINE> current_date = timestamp.strftime('%y%m%d') <NEW_LINE> pipeline = self.conn.pipeline() <NEW_LINE> command_count_key = server + ":CommandCount:" + epoch <NEW_LINE> pipeline.zincr... | save information about every command
Args:
server (str): Server ID
timestamp (datetime): Timestamp.
command (str): The Redis command used.
keyname (str): The key the command acted on.
argument (str): The args sent to the command. | 625941c38c0ade5d55d3e96f |
def _get_last_pose(self): <NEW_LINE> <INDENT> return pose2tf(self.keyframes[-1].pose.param) | Get last pose | 625941c37b180e01f3dc47b8 |
def solve_row0_tile(self, target_col): <NEW_LINE> <INDENT> self.update_puzzle('l') <NEW_LINE> self.update_puzzle('d') <NEW_LINE> target_tile = self.current_position(0, target_col) <NEW_LINE> if target_tile == (0, target_col): <NEW_LINE> <INDENT> return 'ld' <NEW_LINE> <DEDENT> up_moves = ['u'] * (1 - target_tile[0]) <N... | Solve the tile in row zero at the specified column
Updates puzzle and returns a move string | 625941c31b99ca400220aa68 |
def __init__(self, name="outputtriggerstep"): <NEW_LINE> <INDENT> OutputTrigger.__init__(self, name) <NEW_LINE> return | Constructor.
| 625941c399cbb53fe6792b9d |
def adjust_group_result(weight_dic, group_list, n_groups): <NEW_LINE> <INDENT> group_dic = dict() <NEW_LINE> group_weight_dic = dict() <NEW_LINE> n = len(weight_dic.keys()) <NEW_LINE> for sub_id in range(1, n + 1): <NEW_LINE> <INDENT> group_id = group_list[sub_id - 1] <NEW_LINE> group_dic.setdefault(group_id, []).appen... | Adjust group result | 625941c3ab23a570cc250137 |
def readin_temp(temp_file): <NEW_LINE> <INDENT> with open(temp_file, 'r') as fid: <NEW_LINE> <INDENT> temp = np.loadtxt(fid, skiprows=1, usecols=[2]) <NEW_LINE> <DEDENT> return temp | The temperature file should be in mag-format: header + 3 columns with
coordinates and value of temperature. The coordinates have to be the same
as from the resistivity data.
Such a temperature file can be produced with ############# | 625941c39c8ee82313fbb72b |
def associate_connection_with_lag(connectionId=None, lagId=None): <NEW_LINE> <INDENT> pass | Associates an existing connection with a link aggregation group (LAG). The connection is interrupted and re-established as a member of the LAG (connectivity to AWS will be interrupted). The connection must be hosted on the same AWS Direct Connect endpoint as the LAG, and its bandwidth must match the bandwidth for the L... | 625941c356b00c62f0f1460f |
def __init__(self, mdp, discount = 0.9, iterations = 100): <NEW_LINE> <INDENT> self.mdp = mdp <NEW_LINE> self.discount = discount <NEW_LINE> self.iterations = iterations <NEW_LINE> self.values = util.Counter() <NEW_LINE> "*** YOUR CODE HERE ***" <NEW_LINE> for i in range(0,self.iterations): <NEW_LINE> <INDENT> Vi = uti... | Your value iteration agent should take an mdp on
construction, run the indicated number of iterations
and then act according to the resulting policy.
Some useful mdp methods you will use:
mdp.getStates()
mdp.getPossibleActions(state)
mdp.getTransitionStatesAndProbs(state, action)
mdp.getReward(state, a... | 625941c330bbd722463cbd7b |
def get_image_plane_shapes_from_camera(cam_tfm, cam_shp): <NEW_LINE> <INDENT> assert isinstance(cam_tfm, (str, unicode, basestring)) <NEW_LINE> assert len(cam_tfm) > 0 <NEW_LINE> assert maya.cmds.objExists(cam_tfm) <NEW_LINE> assert isinstance(cam_shp, (str, unicode, basestring)) <NEW_LINE> assert len(cam_shp) > 0 <NEW... | Get the list of image plane shape nodes connected to the given camera.
:param cam_tfm: Camera transform node.
:type cam_tfm: str
:param cam_shp: Camera shape node.
:type cam_shp: str
:returns: The list of image shape nodes, may be an empty list.
:rtype: [str, ..] | 625941c330dc7b766590191f |
def test_add_floats(self): <NEW_LINE> <INDENT> result = mymath.add(10.5, 2) <NEW_LINE> self.assertEqual(result, 12.5) | Test that the addition of two floats returns the correct
result | 625941c33317a56b86939c13 |
def ReqQryDepthMarketData(self, qry_depth_market_data, request_id): <NEW_LINE> <INDENT> return super(TraderApi, self).ReqQryDepthMarketData(qry_depth_market_data, request_id) | 请求查询行情
:param qry_depth_market_data:
:param request_id: int
:return: int | 625941c3fff4ab517eb2f3f1 |
def generate_label(self, label_text: str) -> object: <NEW_LINE> <INDENT> raise NotImplementedError("generate_label not implemented") | Generates a label widget that shows text
:param label_text: The text to be displayed by the label
:return: the label widget | 625941c355399d3f0558866a |
def handle(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> meta = self.platform.platformmeta_set.get(key='subject_prepend') <NEW_LINE> subject = '%s: %s' % (meta.value, self.telegram.subject) <NEW_LINE> <DEDENT> except PlatformMeta.DoesNotExist: <NEW_LINE> <INDENT> subject = self.telegram.subject <NEW_LINE> <DEDENT... | Will try to use settings.TELEGRAM_EMAIL_HANDLER_FROM,
the platformmeta setting "subject_prepend", and the subscriptionmeta
setting "email_address". | 625941c30a50d4780f666e47 |
def invertTree(self, root): <NEW_LINE> <INDENT> if root is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if root.left is not None: <NEW_LINE> <INDENT> self.invertTree(root.left) <NEW_LINE> <DEDENT> if root.right is not None: <NEW_LINE> <INDENT> self.invertTree(root.right) <NEW_LINE> <DEDENT> root.left, root.righ... | :type root: TreeNode
:rtype: TreeNode | 625941c37d847024c06be270 |
def __virtual__(): <NEW_LINE> <INDENT> disable = [ 'Windows', ] <NEW_LINE> if __grains__['os'] in disable: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return 'locate' | Only work on posix-like systems | 625941c32ae34c7f2600d0e8 |
def _set_override_role_caught_exc(self): <NEW_LINE> <INDENT> self.__override_role_caught_exc = True | Helper for tracking whether exception was thrown inside
``override_role``. | 625941c3596a897236089a79 |
@pytest.fixture <NEW_LINE> def reg_comp(): <NEW_LINE> <INDENT> y_true = np.random.normal(size=100) <NEW_LINE> y_pred = np.random.normal(0.25, 0.3, size=y_true.shape) + y_true <NEW_LINE> eval1 = RegressionEvaluation( y_true=y_true, y_pred=y_pred, value_name='variable', model_name='test', ) <NEW_LINE> y_true = np.random.... | Setup an example RegressionComparison | 625941c3ab23a570cc250138 |
def save_function_effect(module): <NEW_LINE> <INDENT> for intr in module.itervalues(): <NEW_LINE> <INDENT> if isinstance(intr, dict): <NEW_LINE> <INDENT> save_function_effect(intr) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fe = FunctionEffects(intr) <NEW_LINE> IntrinsicArgumentEffects[intr] = fe <NEW_LINE> if isins... | Recursively save function effect for pythonic functions. | 625941c3498bea3a759b9a66 |
def get_map(tokens): <NEW_LINE> <INDENT> token_index = enumerate(tokens) <NEW_LINE> token_map = {} <NEW_LINE> for k, v in token_index: <NEW_LINE> <INDENT> if v in token_map.keys(): <NEW_LINE> <INDENT> token_map[v].append(k) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> token_map[v] = [k] <NEW_LINE> <DEDENT> <DEDENT> re... | Returns a dictionary with each unique token in @tokens as keys. The values are lists:
the index of the position/s in global @TEXT that the token is found. | 625941c37d847024c06be271 |
def angle_features(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return [ "_".join((F_ANGLE, str(n))) for n in range(1, self.ncontrol_points() - 1) ] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> logging.error( "Failed to get # of control points from training file. Unknown number of angle measurements", exc_inf... | Return a list of angle feature names | 625941c3097d151d1a222e12 |
def decrypt(self, data, client): <NEW_LINE> <INDENT> decryptor = self.CLIENTS[client]['enc-dec'].decryptor() <NEW_LINE> data = decryptor.update(data) + decryptor.finalize() <NEW_LINE> unpadder = padding.PKCS7(128).unpadder() <NEW_LINE> data = unpadder.update(data) + unpadder.finalize() <NEW_LINE> return data | Decrypt a message | 625941c3236d856c2ad4478f |
def resetPlayers(self): <NEW_LINE> <INDENT> if len(self.spawns) >= 2: <NEW_LINE> <INDENT> self.p1 = self.spawns[int(random.random() * len(self.spawns))] <NEW_LINE> self.p2 = self.spawns[int(random.random() * len(self.spawns))] <NEW_LINE> while self.p1 == self.p2: <NEW_LINE> <INDENT> self.p2 = self.spawns[int(random.ran... | Resets players to spawn points. If spawns are invalid, places randomly. | 625941c3cb5e8a47e48b7a63 |
def get_raw_fields(): <NEW_LINE> <INDENT> pass | Returns a list of fields, each represents ticket field
dictionary. For example:
* name: field name
* type: field type
* label: the label to display, preferably wrapped with N_()
* format: field format
* other appropriate field properties | 625941c3d6c5a10208144000 |
def check_duplicate_class_names(class_names): <NEW_LINE> <INDENT> duplicates = get_duplicates(class_names) <NEW_LINE> if duplicates: <NEW_LINE> <INDENT> logger.error(f'Only globally unique class names are allowed. Found duplicates {duplicates}') <NEW_LINE> raise SystemExit(0) | Raises an exception if there are duplicates in the given class names
:param class_names: List of class names
:type class_names: list | 625941c3925a0f43d2549e2c |
def send_null_provenance(self, stmt, for_what, reason=''): <NEW_LINE> <INDENT> content_fmt = ('<h4>No supporting evidence found for {statement} from ' '{cause}{reason}.</h4>') <NEW_LINE> content = KQMLList('add-provenance') <NEW_LINE> stmt_txt = EnglishAssembler([stmt]).make_model() <NEW_LINE> content.sets('html', cont... | Send out that no provenance could be found for a given Statement. | 625941c36e29344779a625ca |
@receiver(pre_save, sender=RhinitisDetails) <NEW_LINE> def create_related_rhinits_diagnosis( sender, instance, **kwargs ): <NEW_LINE> <INDENT> if not instance.id: <NEW_LINE> <INDENT> Diagnosis.objects.create( episode=instance.episode, category=Diagnosis.RHINITIS, condition=Diagnosis.RHINITIS, date=instance.date ) <NEW_... | If its new create a diagnosis.
If its an update that updates the date,
update the diagnosis date. | 625941c3596a897236089a7a |
def test_add_over_existing_vote_to_db(): <NEW_LINE> <INDENT> with mock.patch('annotran.languages.models.Language') as language: <NEW_LINE> <INDENT> language.get_by_public_language_id = MagicMock(return_value=language) <NEW_LINE> with mock.patch('annotran.pages.models.Page') as page: <NEW_LINE> <INDENT> page.get_by_uri ... | This should delete an existing vote from the db and add a new one.
After successfully adding a new vote it should redirect. | 625941c3dd821e528d63b161 |
def get_sel(self): <NEW_LINE> <INDENT> return self.selected | Return the selected icon or -1 (no selection yet)
| 625941c3566aa707497f4523 |
def get_random_position(self): <NEW_LINE> <INDENT> x_max = self._width <NEW_LINE> y_max = self._height <NEW_LINE> pos_x = round(random.uniform(0, x_max), 2) % x_max <NEW_LINE> pos_y = round(random.uniform(0, y_max), 2) % y_max <NEW_LINE> random_pos = Position(pos_x,pos_y) <NEW_LINE> assert self.is_position_in_room(rand... | Returns: a Position object; a valid random position (inside the room). | 625941c3f9cc0f698b1405b4 |
def __init__(self, tokenized_text: List[str] = None, unk_sample_prob: float = 0.0) -> None: <NEW_LINE> <INDENT> self.word_to_index = {} <NEW_LINE> self.index_to_word = [] <NEW_LINE> self.word_count = {} <NEW_LINE> self.alphabet = {tok for tok in _SPECIAL_TOKENS} <NEW_LINE> self.correct_counts = False <NEW_LINE> self.un... | Create a new instance of a vocabulary.
Arguments:
tokenized_text: The initial list of words to add. | 625941c32ae34c7f2600d0e9 |
def signed_out_message(request): <NEW_LINE> <INDENT> if request.user.is_authenticated(): <NEW_LINE> <INDENT> return HttpResponseRedirect('/') <NEW_LINE> <DEDENT> return render_to_response('registration/logged_out.html', request, request.get_node('Q/Web/myesp'), {}) | If the user is indeed logged out, show them a "Goodbye" message. | 625941c3498bea3a759b9a67 |
def choose_file(self, selector, file_path, by=By.CSS_SELECTOR, timeout=None): <NEW_LINE> <INDENT> if not timeout: <NEW_LINE> <INDENT> timeout = settings.LARGE_TIMEOUT <NEW_LINE> <DEDENT> if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT: <NEW_LINE> <INDENT> timeout = self.__get_new_timeout(timeout) <NEW_... | This method is used to choose a file to upload to a website.
It works by populating a file-chooser "input" field of type="file".
A relative file_path will get converted into an absolute file_path.
Example usage:
self.choose_file('input[type="file"]', "my_dir/my_file.txt") | 625941c3287bf620b61d3a1c |
def get_names (self, themes=None, match_all=False): <NEW_LINE> <INDENT> names = Name.objects.filter(topic__topic_map=self.topic_map) <NEW_LINE> names = self._get_constructs(names, themes, match_all) <NEW_LINE> return names | Returns the `Name`s in the topic map whose scope
property contains at least one of the specified `themes`.
If `themes` is None, all `Name`s in the unconstrained
scope are returned.
If `match_all` is True, the scope property of a name
must match all `themes`.
The return value may be empty but must never be None.
:pa... | 625941c34e4d5625662d4391 |
def map_found(self, map_name): <NEW_LINE> <INDENT> map_list = [] <NEW_LINE> append = map_list.append <NEW_LINE> for maps in self.game.get_all_maps(): <NEW_LINE> <INDENT> if map_name.lower() == maps or ('ut4_%s' % map_name.lower()) == maps: <NEW_LINE> <INDENT> append(maps) <NEW_LINE> break <NEW_LINE> <DEDENT> elif map_n... | return True and map name or False and message text | 625941c33c8af77a43ae3756 |
def loadCompounds(path=os.path.join(config.confdir, 'compounds.xml'), clear=True): <NEW_LINE> <INDENT> container = {} <NEW_LINE> document = xml.dom.minidom.parse(path) <NEW_LINE> groupTags = document.getElementsByTagName('group') <NEW_LINE> if groupTags: <NEW_LINE> <INDENT> for groupTag in groupTags: <NEW_LINE> <INDENT... | Parse compounds XML and get data. | 625941c38e7ae83300e4af83 |
def match(self, aggressor_side): <NEW_LINE> <INDENT> trades = [] <NEW_LINE> for bid_i in range(len(self.bid) - 1, -1, -1): <NEW_LINE> <INDENT> bid = self.bid[bid_i] <NEW_LINE> size_offer = len(self.offer) <NEW_LINE> offer_i = 0 <NEW_LINE> while offer_i < size_offer: <NEW_LINE> <INDENT> offer = self.offer[offer_i] <NEW_... | Match orders and return a list of trades | 625941c3b545ff76a8913dce |
def gen_keypair() -> Tuple[ecdsa.Private_key, ecdsa.Public_key]: <NEW_LINE> <INDENT> g = ecdsa.generator_secp256k1 <NEW_LINE> d = SystemRandom().randrange(1, g.order()) <NEW_LINE> pub = ecdsa.Public_key(g, g * d) <NEW_LINE> priv = ecdsa.Private_key(pub, d) <NEW_LINE> return priv, pub | generate a new ecdsa keypair | 625941c3009cb60464c6336a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.