code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def create_app(self): <NEW_LINE> <INDENT> a = app.create_app(**{ 'SQLALCHEMY_DATABASE_URI': 'sqlite://', 'SQLALCHEMY_ECHO': False, 'TESTING': True, 'PROPAGATE_EXCEPTIONS': True, 'TRAP_BAD_REQUEST_ERRORS': True, 'SOLR_SERVICE_DEFAULT_ROWS': 10, 'SOLR_SERVICE_MAX_ROWS': 100, 'SOLR_SERVICE_DISALLOWED_FIELDS': ['full', 'ba...
Start the wsgi application
625941d46aa9bd52df036f89
def convert(self, s, numRows): <NEW_LINE> <INDENT> if numRows == 1: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> length = len(s) <NEW_LINE> if length < numRows: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> delta0 = (numRows - 1) * 2 <NEW_LINE> keyFrames = ((length + delta0 - 1) / delta0) - 1 <NEW_LINE> idx = 0 ...
:type s: str :type numRows: int :rtype: str
625941d40a50d4780f667078
def predictions(dataframe): <NEW_LINE> <INDENT> features = dataframe[['tempi']].copy() <NEW_LINE> features['tempi'] = normalise(features.loc[:,'tempi']) <NEW_LINE> dummy_hour = pandas.get_dummies(dataframe['hour'], prefix='hour') <NEW_LINE> dummy_hour.drop(['hour_16'],axis=1,inplace=True) <NEW_LINE> features = features...
The NYC turnstile data is stored in a pandas dataframe called weather_turnstile. Using the information stored in the dataframe, let's predict the ridership of the NYC subway using linear regression with gradient descent. You can download the complete turnstile weather dataframe here: https://www.dropbox.com/s/meyki2wl...
625941d4e76e3b2f99f3a9ee
def _setTilesColor(self, color: Color, i: int, j: int, internal: bool=True): <NEW_LINE> <INDENT> if i is None: <NEW_LINE> <INDENT> if j is None: <NEW_LINE> <INDENT> for k in range(len(self._colorMatrix)): <NEW_LINE> <INDENT> for l in range(len(self._colorMatrix[0])): <NEW_LINE> <INDENT> self._setTileColor(color, k, l, ...
Sets the (i, j) tile's border color Args: color: The color to give to the border of the (i, j) tile i: The row index of the tile j: The column index of the tile internal: If true, sets the internal color of the tile, else, sets the border color
625941d4bd1bec0571d90815
def test_project_search(self): <NEW_LINE> <INDENT> self.do_search( {'q': 'hello'}, 'Fulltext search for' ) <NEW_LINE> self.do_search( {'q': 'hello', 'search': 'ftx'}, 'Fulltext search for' ) <NEW_LINE> self.do_search( {'q': 'hello', 'search': 'substring'}, 'Substring search for' ) <NEW_LINE> self.do_search( {'q': 'Than...
Searching within project.
625941d445492302aab5e4aa
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(*args, **kwargs) <NEW_LINE> self._max_bonds = 4 <NEW_LINE> if "bonds" not in self.arrays: <NEW_LINE> <INDENT> self.new_array( "bonds", np.zeros((len(self), self._max_bonds, 4)), int) <NEW_LINE> <DEDENT> if "types" not in self.arrays: <NEW_LINE> <...
Parameters: args: A variable number of arguments passed to ``super().__init__()``. kwargs: A variable number of named arguments passed to ``super().__init__()``.
625941d4e64d504609d74a25
def stability_aspect(self): <NEW_LINE> <INDENT> act_data_180d = self.operate_record(self.filter_data(gap1=90, gap2=180), name='90_180d') <NEW_LINE> self.act_data[ 'release_ratio'] = self.act_data.return_amount_sum_90d.values / self.act_data.DayShiJiMoney_sum_90d.values <NEW_LINE> dayShiJiMoney_xdbd_90d = self.act_data....
稳定性 :return:
625941d431939e2706e4d04e
def get_sandbox_file_name(my, current_file_name, context, sandbox_dir=None, file_naming=None): <NEW_LINE> <INDENT> pattern = re.compile( r'v(\d+)[\.|_]') <NEW_LINE> matches = pattern.findall(current_file_name) <NEW_LINE> if not matches: <NEW_LINE> <INDENT> version = 0 <NEW_LINE> base, ext = os.path.splitext(current_fil...
function that determines the file name to be saved in the sandbox
625941d4e8904600ed9f2114
def check_transactions_in_new_block(self, block): <NEW_LINE> <INDENT> fee_for_block = self.get_total_fee_on_block(block) <NEW_LINE> fee_for_block += 30 <NEW_LINE> print('fee_for_block: ', fee_for_block) <NEW_LINE> transactions = block['transactions'] <NEW_LINE> counter = 0 <NEW_LINE> for t in transactions: <NEW_LINE> <...
ブロック内のTransactionに不正がないか確認する
625941d46fb2d068a760f284
def WassersteinDualSimplex(h1, h2, M): <NEW_LINE> <INDENT> n = len(h1) <NEW_LINE> m = Model() <NEW_LINE> m.setParam(GRB.Param.NumericFocus, 3) <NEW_LINE> print('1. Start building model') <NEW_LINE> x = {} <NEW_LINE> P = set() <NEW_LINE> D = [] <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> if h1[i] > 0: <NEW_LINE> <...
Find the Wasserstein distance using the dual simplex
625941d4fff4ab517eb2f622
def read_config(): <NEW_LINE> <INDENT> args = parser.parse_args() <NEW_LINE> with open(args.config, mode='r') as f: <NEW_LINE> <INDENT> config = json.load(f) <NEW_LINE> <DEDENT> return config
Reads the specified config file from disk and parses it as JSON. :return:
625941d4656771135c3eba55
def send_async(*args, **kwargs): <NEW_LINE> <INDENT> return thread.start_new_thread(send, args, kwargs)
Send a notification, returning immediately, without waiting for the message to be sent. This function does return the ID of the thread that does the HTTP request.
625941d44a966d76dd5511f6
def enumerate_spans(sentence: List[T], sentence_pos: List[T], offset: int = 0, max_span_width: int = 2, min_span_width: int = 1, filter_function: Callable[[List[T]], bool] = None ) -> List[Tuple[int, int]]: <NEW_LINE> <INDENT> trigger_pos = ['VBN', 'VBP', 'VBZ', 'VBG', 'VBD', 'VB', 'NN', 'NNS', 'NNP', 'PRP', 'TO', 'JJ'...
Given a sentence, return allennlp_span token spans within the sentence. Spans are `inclusive`. Additionally, you can provide a maximum and minimum span width, which will be used to exclude spans outside of this range. Finally, you can provide a function mapping ``List[T] -> bool``, which will be applied to every span ...
625941d48e71fb1e9831d98e
def getUbuntuRelease(self): <NEW_LINE> <INDENT> return self.args.ubuntu_release
Return ubuntu release code name.
625941d438b623060ff0afd3
def supply(request, page_name): <NEW_LINE> <INDENT> _ = page_name <NEW_LINE> return get_quests_from_cache(request.user)
supply the quest view_objects
625941d46fece00bbac2d926
@ElementWise <NEW_LINE> def checkIndex(idx, floatOK=False): <NEW_LINE> <INDENT> if isinstance(idx,(list,tuple,np.ndarray)): <NEW_LINE> <INDENT> isIdx = isNumber(idx) if floatOK else isInt(idx) <NEW_LINE> <DEDENT> elif isinstance(idx,(int,np.integer)) or isinstance(idx,slice): isIdx = True <NEW_LINE> elif floatOK and is...
Check if idx is a valid index or slice; if floatOK=True, floats can also be indices.
625941d4097d151d1a22303e
def canFinish(self, numCourses, prerequisites): <NEW_LINE> <INDENT> from collections import defaultdict, deque <NEW_LINE> graph = defaultdict(GNode) <NEW_LINE> totalDeps = 0 <NEW_LINE> for relation in prerequisites: <NEW_LINE> <INDENT> nextCourse, prevCourse = relation[0], relation[1] <NEW_LINE> graph[prevCourse].outNo...
:type numCourses: int :type prerequisites: List[List[int]] :rtype: bool
625941d430c21e258bdfa683
def load_custom(self, dataset_dir, subset): <NEW_LINE> <INDENT> self.add_class("garbage", 1, "garbage") <NEW_LINE> assert subset in ["train", "val"] <NEW_LINE> dataset_dir = ROOT_DIR+'/'+dataset_dir <NEW_LINE> dataset_dir = os.path.join(dataset_dir, subset) <NEW_LINE> print(dataset_dir) <NEW_LINE> annotations = json.lo...
Load a subset of the Balloon dataset. dataset_dir: Root directory of the dataset. subset: Subset to load: train or val
625941d4de87d2750b85ff7a
def DistanceInformation(self): <NEW_LINE> <INDENT> languages = [{'word':self.positionmatchword,'clause':self.matchedclause,'lname':'sl'}] <NEW_LINE> self.verbdist_byword = dict() <NEW_LINE> self.headdist_bydependents = dict() <NEW_LINE> self.contpos = dict() <NEW_LINE> if self.parallelcontext: <NEW_LINE> <INDENT> try: ...
Calculate distances between elements in the clause of the match
625941d4004d5f362079a518
def __init__(self): <NEW_LINE> <INDENT> self.CameraId = None <NEW_LINE> self.CameraName = None <NEW_LINE> self.CameraFeature = None <NEW_LINE> self.CameraIp = None <NEW_LINE> self.CameraState = None <NEW_LINE> self.Zones = None <NEW_LINE> self.Pixel = None
:param CameraId: 摄像头ID :type CameraId: int :param CameraName: 摄像头名称 :type CameraName: str :param CameraFeature: 摄像头功能: 1: 人脸 2: 人体 :type CameraFeature: int :param CameraIp: 摄像头IP :type CameraIp: str :param CameraState: 摄像头状态: 0: 异常 1: 正常 :t...
625941d421bff66bcd684b37
def get_top_100(info=None): <NEW_LINE> <INDENT> url = urls.get_100_most_popular() <NEW_LINE> data = helper.request_get(url, 'regular') <NEW_LINE> data = helper.filter_data(data, 'instruments') <NEW_LINE> symbols = [stocks.get_symbol_by_url(x) for x in data] <NEW_LINE> data = stocks.get_quotes(symbols) <NEW_LINE> return...
Returns a list of the Top 100 stocks on Robin Hood. :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for each mover. If info parameter is provided, a list of strings is returned where the strings are the value of the...
625941d4090684286d50eecc
def add_IC(self, function, eqn_name=None): <NEW_LINE> <INDENT> if not self.time_dep: <NEW_LINE> <INDENT> raise ValueError( 'Initial condition cannot apply to steady state model') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> function(self.mesh.nodes[1].coords()) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> ...
Associate an initial condition with an equation. Parameters ---------- function : function The formula for the initial condition. eqn_name : str,optional The equation name with which to associate this IC. Default is None (the first). Raises ------ ValueError if the model is steady state TypeError if the functio...
625941d4a8370b7717052a84
def test_alps_release_wait_time(self): <NEW_LINE> <INDENT> arwt = 4.298 <NEW_LINE> self.mom.add_config({'$alps_release_wait_time': arwt}) <NEW_LINE> start_time = int(time.time()) <NEW_LINE> j1 = Job(TEST_USER) <NEW_LINE> jid1 = self.server.submit(j1) <NEW_LINE> self.server.expect(JOB, {ATTR_state: 'R'}, id=jid1) <NEW_L...
Set alps_release_wait_time to a higher value and then notice that subsequest reservation cancellation requests are made at least after the set interval.
625941d463b5f9789fde72cb
def plot_pca_variance(self, n_components=None, axis='columns', ax=None): <NEW_LINE> <INDENT> import matplotlib.pyplot as plt <NEW_LINE> import seaborn as sns <NEW_LINE> pca = self.pca(n_components=n_components, axis=axis, transform=False) <NEW_LINE> if ax is None: <NEW_LINE> <INDENT> _, ax = plt.subplots() <NEW_LINE> <...
Plots variance explained by PCA components.
625941d4091ae35668667142
def __contains__(self, item): <NEW_LINE> <INDENT> return item in self._reverse
Implement the 'in' operator for an item in the queue. item (QueueItem): an item to search. return (bool): True if item is in the queue.
625941d426238365f5f0f056
def breadthFirstSearch(problem): <NEW_LINE> <INDENT> open_list = util.Queue() <NEW_LINE> start = (problem.getStartState(), 0, []) <NEW_LINE> open_list.push(start) <NEW_LINE> visited = set() <NEW_LINE> visited.add(problem.getStartState()) <NEW_LINE> while not open_list.isEmpty(): <NEW_LINE> <INDENT> (node, cost, path) =...
Search the shallowest nodes in the search tree first.
625941d467a9b606de4a809e
def parse_detail(self, response): <NEW_LINE> <INDENT> front_image_url = response.meta.get('front_image_url', '') <NEW_LINE> item_loader = TakeFirstItemLoader(item=JobBoleArticleItem(), response=response) <NEW_LINE> item_loader.add_css('title', ".entry-header h1::text") <NEW_LINE> item_loader.add_value('url', response.u...
提取文章中的具体字段 :param response: :return:
625941d4ab23a570cc250369
def _Get_millivolts(self): <NEW_LINE> <INDENT> return self._get_battery_values()['mv']
Retrieves voltage measurements for the battery.
625941d407f4c71912b11669
def _new_spec_helper(item): <NEW_LINE> <INDENT> name_ = item["name"] <NEW_LINE> raw_name = item.get("raw", name_) <NEW_LINE> type_ = item.get("type") <NEW_LINE> comment = item.get("comment") or _find_default_comment(name_) <NEW_LINE> name = _safe_enum(snake_case(name_)) <NEW_LINE> safe_name = _safe(name) <NEW_LINE> cha...
aggregate the specification as a dict
625941d4d6c5a10208144231
def _render_summary_pages(prj): <NEW_LINE> <INDENT> rep_dir = os.path.basename(get_reports_dir(prj)) <NEW_LINE> j_env = get_jinja_env(TEMPLATES_PATH) <NEW_LINE> html_report_builder = HTMLReportBuilder(prj) <NEW_LINE> globs.summarizer = Summarizer(prj) <NEW_LINE> objs = globs.summarizer.objs <NEW_LINE> stats = globs.sum...
Render the summary pages with caravel navbars and footers :param looper.Project prj: a project the summary pages should be create for :return:
625941d4dc8b845886cb571c
def games(request): <NEW_LINE> <INDENT> games = Game.objects.filter() <NEW_LINE> games_rows = split_list_columns(games[::-1], 2) <NEW_LINE> context = {'games_rows': games_rows} <NEW_LINE> return render(request, 'games.html', context=context)
View function for display Games. :param request: :param game_name: :return:
625941d41f037a2d8b9463e3
def test_add_people_list_plugin_client(self): <NEW_LINE> <INDENT> self.client.login(username=self.su_username, password=self.su_password) <NEW_LINE> plugin_data = { 'plugin_type': 'PeoplePlugin', 'plugin_language': self.language, 'placeholder_id': self.placeholder.pk, } <NEW_LINE> response = self.client.post(URL_CMS_PL...
We log into the PeoplePlugin
625941d4099cdd3c635f0e40
def main(): <NEW_LINE> <INDENT> pid, search_bytes, replace_bytes = parse_inputs() <NEW_LINE> print("{} for {} in PID {}".format(search_bytes, replace_bytes, pid)) <NEW_LINE> heap_start, heap_end = get_heap_positions(pid) <NEW_LINE> print("Heap bytes: 0x{:02x} - 0x{:02x}".format(heap_start, heap_end)) <NEW_LINE> write_i...
Logic to get the user input, obtain the heap positions and overlaps the search string with the replacement string (Sudo permissions are needed)
625941d463d6d428bbe446d5
def _get_current(self): <NEW_LINE> <INDENT> return self.volt()/self.iv_conv*1E12
get_cmd for dmm readout of IV_TAMP parameter
625941d49c8ee82313fbb95b
def raw_entry(self): <NEW_LINE> <INDENT> return self._raw
Return the raw entry of the sequence ``self``, in the OEIS format. OUTPUT: - string. EXAMPLES:: sage: f = oeis(45) ; f # optional -- internet A000045: Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. sage: print(f.raw_entry()) # optional -- int...
625941d485dfad0860c3b041
def __getattr__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return { "astimezone": self.as_timezone, "isocalendar": self.iso_calendar, "isoformat": self.iso_format, "isoweekday": self.iso_weekday, "strftime": self.__format__, "toordinal": self.to_ordinal, "timetuple": self.time_tuple, "utcoffset": self.ut...
Map standard library attribute names to local attribute names, for compatibility.
625941d44f88993c3716c24c
def get_push_creds(self, org_key): <NEW_LINE> <INDENT> push_token = self.quay_api_store[org_key]["push_token"] <NEW_LINE> username = push_token["user"] <NEW_LINE> password = push_token["token"] <NEW_LINE> return f"{username}:{password}"
returns username and password for the given org :param org_key: org_key :type org_key: tuple(instance, org_name) :return: tuple containing username and password :rtype: tuple(str, str)
625941d45e10d32532c5f10d
def test_ssl_client_cert(self): <NEW_LINE> <INDENT> mongo = mongo_class.Server( self.name, self.user, self.japd, host=self.host, port=self.port) <NEW_LINE> self.assertEqual(mongo.ssl_client_cert, None)
Function: test_ssl_client_cert Description: Test with ssl_client_cert attribute. Arguments:
625941d49f2886367277aa73
def is_palindrome_permutation_one(string: str) -> bool: <NEW_LINE> <INDENT> if len(string) == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if len(string) == 1: <NEW_LINE> <INDENT> if string.isalpha(): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDEN...
O(n) time | O(n) space Hashmap approach. Palindrome permutations should have character counts that are all even and can contain only one character (at most) with an odd count.
625941d44f88993c3716c24d
def _box_name(self, box: str): <NEW_LINE> <INDENT> return box.split("box")[0].title() + " Box"
Return box name
625941d499fddb7c1c9de577
def find_hid_tool(self, port): <NEW_LINE> <INDENT> for item in self.portmap: <NEW_LINE> <INDENT> if item["port"] == port: <NEW_LINE> <INDENT> return item["tool"] <NEW_LINE> <DEDENT> <DEDENT> return None
Find HID tool based on virtual serial port name returns: HID tool object or None
625941d42c8b7c6e89b359a6
def min_value(self, game, depth, alpha, beta): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> min_value = float('inf') <NEW_LINE> legal_moves = game.get_legal_moves() <NEW_LINE> if depth == 0 or not legal_moves: <NEW_LINE> <INDENT> return se...
Return MIN
625941d463f4b57ef00012fc
def test_client_connect_no_response(self): <NEW_LINE> <INDENT> d = defer.ensureDeferred( self.cl.get_json("testserv:8008", "foo/bar", timeout=10000) ) <NEW_LINE> self.pump() <NEW_LINE> self.assertNoResult(d) <NEW_LINE> clients = self.reactor.tcpClients <NEW_LINE> self.assertEqual(len(clients), 1) <NEW_LINE> self.assert...
If the HTTP request is connected, but gets no response before being timed out, it'll give a ResponseNeverReceived.
625941d4f9cc0f698b1407e0
def sendQueueMessage(self, message): <NEW_LINE> <INDENT> msg = MessageProcessor.buildMessage(message.command, message.args) <NEW_LINE> self.send(msg)
:type message QueueMessage
625941d47d847024c06be4a4
def setup(self): <NEW_LINE> <INDENT> return
Nothing to do
625941d4ac7a0e7691ed42b0
def schema_init(self, engine, schema): <NEW_LINE> <INDENT> is_exists = False <NEW_LINE> try: <NEW_LINE> <INDENT> engine.execute(CreateSchema(schema)) <NEW_LINE> self.info(f'Creating {schema} schema') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.info(f'Schema {schema} already exists') <NEW_LINE> is_exists = True...
init_schema :param engine: :param schema: str :return: str
625941d4b830903b967e9af0
def conflict(): <NEW_LINE> <INDENT> return HttpError(409)
Send a conflict response. >>> raise conflict() Traceback (most recent call last): ... HttpError: 409 Conflict
625941d4b7558d58953c50f8
def get_vocab_size(tokenizer): <NEW_LINE> <INDENT> return len(tokenizer.word_index) + 1
Returns the vocab size of X. Necessary for the Emebdding Layer of our model. Arguments --------- X (np.array) : an array of the full dataset (train+validation). Returns ------- vocab_size (int) : the number of words in our vocabulary.
625941d4d6c5a10208144232
def quiz_grades_detail_list(request, qid): <NEW_LINE> <INDENT> order_by_default = 'student_name__last_name' <NEW_LINE> row_per_page = 3 <NEW_LINE> query_set = Grade.objects.filter(quiz_name_id=qid).order_by(order_by_default) <NEW_LINE> fields = Grade._meta.get_all_field_names() <NEW_LINE> order_by = request.GET.get('or...
Get list of students and their grades that relative to particular quiz. qid is the id of quez. The list is ordered by students last names.
625941d4925a0f43d254a05e
def get_account_for_iban(iban): <NEW_LINE> <INDENT> user = get_user() <NEW_LINE> accounts = generated.MonetaryAccountBank.list(Client.ctx(), user.id_) <NEW_LINE> for acc in accounts: <NEW_LINE> <INDENT> for a in acc.alias: <NEW_LINE> <INDENT> if a.type_ == 'IBAN' and a.value == iban: <NEW_LINE> <INDENT> return acc
Parameters ---------- iban : str Returns ------- MonetaryAccountBank
625941d4d58c6744b4257e45
def t_EQ(t): <NEW_LINE> <INDENT> t.value = '==' <NEW_LINE> return t
==|=
625941d41b99ca400220ac98
def testBankAccountType(self): <NEW_LINE> <INDENT> pass
Test BankAccountType
625941d4a934411ee375187a
def decade_ratio(self): <NEW_LINE> <INDENT> track_albums = [tr['track']['album'] for tr in self.pl['tracks']['items']] <NEW_LINE> decade_count = {}; <NEW_LINE> for i in range(1900, 2020, 10): <NEW_LINE> <INDENT> decade_count[i] = 0 <NEW_LINE> <DEDENT> for album in track_albums: <NEW_LINE> <INDENT> precision = album['re...
returns a structure with playlist tracks decade ratio :return:
625941d43617ad0b5ed680dc
def calcC_m(A_f, classNum): <NEW_LINE> <INDENT> if A_f <= 0: <NEW_LINE> <INDENT> raise ValueError('Facade area must be a value greater than zero.') <NEW_LINE> <DEDENT> if classNum in np.array(range(5))+1: <NEW_LINE> <INDENT> if classNum == 1: <NEW_LINE> <INDENT> C_m = 80000.0*A_f <NEW_LINE> <DEDENT> elif classNum == 2:...
Class specification per the DIN EN ISO 19790-2008 Table 12 Input: A_f - conditioned floor area [m2] classNum - integer from 1 to 5 corresponding to construction type. Output: C_m - effective mass of the building [J/K]
625941d42eb69b55b151ca97
def check_cell_neighbors(self, row, column): <NEW_LINE> <INDENT> def get_cell(r, c): <NEW_LINE> <INDENT> cell_value = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> cell_value = self.grids[self.active_grid][r][c] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> cell_value = 0 <NEW_LINE> <DEDENT> return cell_value <NEW_LINE> <DED...
Gets the number of alive neighbor cells, and determine the state of the cell for the next generation Determines whether it lives, survives, dies or is born :param row: row number of the cell to check :param row: column number of the cell to check :return: The state the cell should be in next gen (0 or 1)
625941d49b70327d1c4e0fbb
def writeObjectsToFunctor(self, *args): <NEW_LINE> <INDENT> return _AriaPy.ArMapInterface_writeObjectsToFunctor(self, *args)
writeObjectsToFunctor(self, ArFunctor1_CString functor, char endOfLineChars, bool isOverrideAsSingleScan = False, char maxCategory = None) writeObjectsToFunctor(self, ArFunctor1_CString functor, char endOfLineChars, bool isOverrideAsSingleScan = False) writeObjectsToFunctor(self, ArFunctor1_CString functor, char e...
625941d421a7993f00bc7ed8
def run(self): <NEW_LINE> <INDENT> if HAS_ATFORK: <NEW_LINE> <INDENT> atfork() <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> result = self._read_worker_result() <NEW_LINE> if result is None: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> continue <NEW_LINE> <DEDENT> host_name = result._ho...
The main thread execution, which reads from the results queue indefinitely and sends callbacks/etc. when results are received.
625941d4fb3f5b602dac387b
def get_queryset(self, request): <NEW_LINE> <INDENT> qs = super(CommunityTerminalAdmin, self).get_queryset(request) <NEW_LINE> return qs.filter(removed_date__isnull=True)
Override queryset to filter out 'removed' terminals
625941d4377c676e9127238f
def solve(grid,diagonal): <NEW_LINE> <INDENT> values = grid_values(grid) <NEW_LINE> return search(values,diagonal)
Find the solution to a Sudoku grid. Args: grid(string): a string representing a sudoku grid. Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3' Returns: The dictionary representation of the final sudoku grid. False if no solution exists.
625941d44f6381625f114c22
def get_attr_values(self, plugin_api, corpus, attr_map, aligned_corpora=None, autocomplete_attr=None, limit_lists=True): <NEW_LINE> <INDENT> raise NotImplementedError()
Find all the available values of remaining attributes according to the provided attr_map and aligned_corpora arguments: plugin_api -- corpus -- manatee.corpus object attr_map -- a dictionary of attributes and values as selected by a user aligned_corpora -- a list/tuple of corpora names aligned to base one (the 'corpus...
625941d4167d2b6e31218d7c
def _verify_cell_info(self, ad, expected_cell_info_stats, number_of_sample=10, delay_each_sample=5): <NEW_LINE> <INDENT> cell_info_stats = {} <NEW_LINE> for index in range(number_of_sample): <NEW_LINE> <INDENT> info_list = ad.droid.telephonyGetAllCellInfo() <NEW_LINE> self.log.info("Received Cell Info List: {}".format(...
Return if reported cell info from ad matches expected_cell_info_stats or not. Args: ad: android device object. expected_cell_info_stats: expected cell info list. number_of_sample: number of sample to take from DUT. delay_each_sample: time delay between each sample. Returns: True if reported cell i...
625941d4460517430c394369
def formatEditorText(self, storedText): <NEW_LINE> <INDENT> if not storedText: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> linkMatch = imageRegExp.search(storedText) <NEW_LINE> if not linkMatch: <NEW_LINE> <INDENT> raise ValueError <NEW_LINE> <DEDENT> return linkMatch.group(1)
Return text formatted for use in the data editor. Raises a ValueError if the data does not match the format. Arguments: storedText -- the source text to format
625941d463b5f9789fde72cc
def test_get_system_cpu(self): <NEW_LINE> <INDENT> if skiptest is True: <NEW_LINE> <INDENT> raise SkipTest <NEW_LINE> <DEDENT> auth = AOSSAuth(switch, username, password, version=version) <NEW_LINE> cpu = get_system_cpu(auth) <NEW_LINE> self.assertIs(type(cpu), dict) <NEW_LINE> if 'message' in cpu: <NEW_LINE> <INDENT> ...
test case for get_system_cpu
625941d476e4537e8c35185a
def derivative_2 (x,a,l): <NEW_LINE> <INDENT> return sum((-x*np.exp(-1*a*x))**2) *(1+l)
derivative_2 returns the second derivate the cost function wich is approximated with newton methid; here we get d^2f/da^2 =sum(dg/da^2)*(1+l). According to this formula derivative_2 takes 3 parameters x the interval on which the model is calculated, the current approximation of a, and l (writed lambda) wich express...
625941d4bde94217f3682fd6
def get_meta(self, e_meta): <NEW_LINE> <INDENT> return libvlc_media_get_meta(self, e_meta)
Read the meta of the media. If the media has not yet been parsed this will return None. See libvlc_media_parse See L{parse_with_options} See libvlc_MediaMetaChanged. @param e_meta: the meta to read. @return: the media's meta.
625941d4be8e80087fb20e28
def ListZoneFunc(self): <NEW_LINE> <INDENT> return self.api.zone_operations.list
Returns the function for listing operations in a zone.
625941d4bd1bec0571d90816
def iskeyexists(self, key): <NEW_LINE> <INDENT> return self.__redis.exists(key)
true when key exists in cache
625941d45fcc89381b1e18a7
def set_own_login_name(member, loginname): <NEW_LINE> <INDENT> pas = getToolByName(member, 'acl_users') <NEW_LINE> mt = getToolByName(member, 'portal_membership') <NEW_LINE> if member.getId() == mt.getAuthenticatedMember().getId(): <NEW_LINE> <INDENT> pas.updateOwnLoginName(loginname) <NEW_LINE> return <NEW_LINE> <DEDE...
Allow the user to set his/her own login name. If you have the Manage Users permission, you can update the login name of another member too, though the name of this function is a bit weird then. Historical accident.
625941d4cc40096d61595b37
def escape_path(path): <NEW_LINE> <INDENT> return path.replace("\\", "\\\\")
Escapes any characters that might be problematic in shell interactions. :param path: The original path. :return: A potentially modified version of the path with all problematic characters escaped.
625941d4d486a94d0b98e32d
@manage_app.route('/all_offices') <NEW_LINE> @login_required <NEW_LINE> @reject_operator <NEW_LINE> def all_offices(): <NEW_LINE> <INDENT> page = request.args.get('page', 1, type=int) <NEW_LINE> tickets = data.Serial.query.filter(data.Serial.number != 100) .order_by(data.Serial.p, data.Ser...
lists all offices.
625941d41f5feb6acb0c4d35
def train_and_eval(): <NEW_LINE> <INDENT> df_train = pd.read_csv("trainfile.csv", dtype={ 'User_id': str, "Action": str, "Adventure": str, "Animation": str, "Children": str, "Comedy": str, "Crime": str, "Drama": str, "Fantasy": str, "Film-Noir": str, "Horror": str, "Musical": str, "Mystery": str,...
Train and evaluate the model.
625941d4283ffb24f3c55ae7
def iter_terms(self, ontology, size=None, sleep=None): <NEW_LINE> <INDENT> url = self.ontology_terms_fmt.format(ontology=ontology) <NEW_LINE> for term in self._iter_terms_helper(url, size=size, sleep=sleep): <NEW_LINE> <INDENT> yield term
Iterates over all terms, lazily with paging :param str ontology: The name of the ontology :param int size: The size of each page. Defaults to 500, which is the maximum allowed by the EBI. :param int sleep: The amount of time to sleep between pages. Defaults to 0 seconds. :rtype: iter[dict]
625941d430dc7b7665901b4c
def initialize_weights(*models): <NEW_LINE> <INDENT> for model in models: <NEW_LINE> <INDENT> for module in model.modules(): <NEW_LINE> <INDENT> if isinstance(module, nn.Conv2d) or isinstance(module, nn.Linear): <NEW_LINE> <INDENT> xavier_normal_(module.weight) <NEW_LINE> if module.bias is not None: <NEW_LINE> <INDENT>...
Initialize weights of a model.
625941d4fff4ab517eb2f623
def sortArrayByParity(self, A): <NEW_LINE> <INDENT> p = 0 <NEW_LINE> for i in range(len(A)): <NEW_LINE> <INDENT> if (A[i] % 2 == 0): <NEW_LINE> <INDENT> A[i], A[p] = A[p], A[i] <NEW_LINE> p += 1 <NEW_LINE> <DEDENT> <DEDENT> return A
:type A: List[int] :rtype: List[int]
625941d4462c4b4f79d1d8b7
def p_seen_pn_flavor(p): <NEW_LINE> <INDENT> global TypeStack <NEW_LINE> global POper <NEW_LINE> global PilaO <NEW_LINE> global quads <NEW_LINE> global availTemp <NEW_LINE> global DiTemp <NEW_LINE> thirdParam = PilaO.pop() <NEW_LINE> third_type = TypeStack.pop() <NEW_LINE> secondParam = PilaO.pop() <NEW_LINE> second_ty...
seen_pn_flavor :
625941d40fa83653e46571a1
def reduceJoint(self, completeness): <NEW_LINE> <INDENT> return completeness[-1]
The joint completeness is just the minimum completeness for a point/field.
625941d4bd1bec0571d90817
def make_stack_matrix(pair, id_seq_oligo_list): <NEW_LINE> <INDENT> with open('stack.dat', 'a') as stack: <NEW_LINE> <INDENT> a=pair[0] <NEW_LINE> b=pair[1] <NEW_LINE> line = [] <NEW_LINE> line.append(id_seq_oligo_list[a][0]) <NEW_LINE> line.append(id_seq_oligo_list[b][0]) <NEW_LINE> alignment = bpw2.align.globalds(id_...
Using pairwise module from Biopython and employing blosum62 substitution matrix. Called by: OligoState.py:main()
625941d4f7d966606f6aa1ed
def add_text_to_scene(text, plane, height, font='Arial', horizontal_alignment=0, vertical_alignment=5, layer_name=None, attributes=None): <NEW_LINE> <INDENT> txt = rh.Display.Text3d(text, from_plane(plane), height) <NEW_LINE> txt.FontFace = font <NEW_LINE> txt.HorizontalAlignment = AlignmentTypes.horizontal(horizontal_...
Add text to the Rhino sceneusing a text string and ladybug Plane. Args: text: A text string to be added to the Rhino scene. plane: A Ladybug Plane object to locate and orient the text in the Rhino scene. height: A number for the height of the text in the Rhino scene. font: An optional text string for t...
625941d445492302aab5e4ac
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'educa_app.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 su...
Run administrative tasks.
625941d4de87d2750b85ff7b
def update_visualizations(scale, listeners): <NEW_LINE> <INDENT> params = sim_object.params <NEW_LINE> env = sim_object.env <NEW_LINE> fleet = sim_object.fleet <NEW_LINE> for event in pygame.event.get(): <NEW_LINE> <INDENT> if event.type == pygame.QUIT: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> for ...
Visualization function used in main function loop. This is the ground software's understanding of the vehicles' locations and the desired location of the simulation :param scale: (real_meters:simulated_meters) :param listeners: List of threads tied to listening process for each simulated vehicle :return: True if us...
625941d46fece00bbac2d927
def map_line_to_seq(line,inverse_voc): <NEW_LINE> <INDENT> return [inverse_voc[w] if w in inverse_voc else inverse_voc['<below_th>'] for w in tokenize(line)]
Converts a string(sentence) to a sequence of integers Will also tokenize the sentence
625941d4498bea3a759b9c96
def test_add_workspacecontainer(self): <NEW_LINE> <INDENT> self.login_as_portal_owner() <NEW_LINE> api.content.create( self.portal, 'ploneintranet.workspace.workspacecontainer', 'workspaces', title='Workspaces' ) <NEW_LINE> self.assertIn('workspaces', self.portal)
Check that WorkspaceContainer can be added to site root
625941d4fbf16365ca6f63ac
@app.route('/<user>/posts/<int:post_id>') <NEW_LINE> def post(user, post_id): <NEW_LINE> <INDENT> return str(post_id), 'by', user
:param user: user login name :param post_id: post unique id :status 200: when user and post exists :status 404: when user and post doesn't exist
625941d4187af65679ca5306
def insert(self, position, element, name="default", **kwargs): <NEW_LINE> <INDENT> x = kwargs.get('x', 0) <NEW_LINE> y = kwargs.get('y', 0) <NEW_LINE> refresh = kwargs.get('refresh', False) <NEW_LINE> mode = kwargs.get('mode', 'fill') <NEW_LINE> if self.check_type(element): <NEW_LINE> <INDENT> if type(position) == str:...
Inserts a child to the screen before 'position' Position can be a child name (first occurence) or an index Returns True for success Keyword arguments: position -- Index or name to insert before element -- Image x -- x paste location (default 0) y -- y paste location (default 0) refresh -- blank Image after refresh (de...
625941d43cc13d1c6d3c7561
def pip_install(package, commit=None): <NEW_LINE> <INDENT> if commit: <NEW_LINE> <INDENT> package = 'git+git://github.com/{0}.git@{1}'.format(package, commit) <NEW_LINE> <DEDENT> check_call(['pip', 'install', '-q', package])
Install package using pip.
625941d4287bf620b61d3c4a
def get_event_types(connector, event_table): <NEW_LINE> <INDENT> database = connector.connect() <NEW_LINE> cursor = database.cursor() <NEW_LINE> sql = "SELECT (event_uid) FROM {table}".format(table=event_table) <NEW_LINE> cursor.execute(sql) <NEW_LINE> database.commit() <NEW_LINE> database.close() <NEW_LINE> event_type...
Get all the types of events that a test instance can output. :param connector: The connector to the database. :param event_table: The name of the event table. :return: A list of tuples corresponding to the event types.
625941d466656f66f7cbc394
def get_version(*file_paths): <NEW_LINE> <INDENT> filename = os.path.join(os.path.dirname(__file__), *file_paths) <NEW_LINE> version_file = open(filename).read() <NEW_LINE> version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) <NEW_LINE> if version_match: <NEW_LINE> <INDENT> return versio...
Retrieves the version from django_postgres_utils/__init__.py
625941d430c21e258bdfa685
def setNumber(): <NEW_LINE> <INDENT> x = 10 <NEW_LINE> print(x)
Print the value of a local variable.
625941d40a366e3fb873ea03
def amap(self, functorValue): <NEW_LINE> <INDENT> return self.getValue() * functorValue
Applies the function stored in the functor to 'functorValue' returning a new Either value.
625941d4004d5f362079a51a
def sleep(_time): <NEW_LINE> <INDENT> subprocess.run(["sleep", str(_time)+"s"])
genera una pausa la cantidad de segundos indicados por _time Args: _time (int): tiempo de la pausa en segundos
625941d421bff66bcd684b39
def getPlanetH6EnabledFlag(self): <NEW_LINE> <INDENT> return self.planetH6EnabledFlag
Returns the flag that indicates that the planet geocentric longitude movement measurements should be displayed for this planet. Arguments: flag - bool value for the enabled flag.
625941d4cad5886f8bd271c0
@utils.service_type('volume') <NEW_LINE> def do_transfer_list(cs, args): <NEW_LINE> <INDENT> transfers = cs.transfers.list() <NEW_LINE> columns = ['ID', 'Volume ID', 'Name'] <NEW_LINE> utils.print_list(transfers, columns)
Lists all transfers.
625941d4a219f33f34628b4f
def get_corrected_total_rotation(angles): <NEW_LINE> <INDENT> return create_rotation_matrix(angles) * R_corr[:3, :3]
Return the rotation matrix corresponding to the given gripper angles, taking into account the correction matrix :param angles: [roll, pitch, yaw] in radians :return: 3x3 Matrix
625941d4dc8b845886cb571d
def clear_button_press(self, clear_type): <NEW_LINE> <INDENT> if clear_type == 'DEL': <NEW_LINE> <INDENT> entry_val = self.number_entry.get() <NEW_LINE> entry_val = entry_val[:-1] <NEW_LINE> self.number_entry.delete(0, "end") <NEW_LINE> self.number_entry.insert(0, entry_val) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT...
Whenever the AC or DEL button is pressed
625941d4091ae35668667144
def propagating_number(sp): <NEW_LINE> <INDENT> pn = 0 <NEW_LINE> for part in sp: <NEW_LINE> <INDENT> if min(part) < 0 and max(part) > 0: <NEW_LINE> <INDENT> pn += 1 <NEW_LINE> <DEDENT> <DEDENT> return pn
Return the propagating number of the set partition ``sp``. The propagating number is the number of blocks with both a positive and negative number. EXAMPLES:: sage: import sage.combinat.diagram_algebras as da sage: sp1 = da.to_set_partition([[1,-2],[2,-1]]) sage: sp2 = da.to_set_partition([[1,2],[-2,-1]]...
625941d4bf627c535bc133b7
def _open(base, filename, seen, dl_options, override, downloaded): <NEW_LINE> <INDENT> _update_section(dl_options, override) <NEW_LINE> _dl_options = _unannotate_section(dl_options.copy()) <NEW_LINE> newest = _convert_bool('newest', _dl_options.get('newest', 'false')) <NEW_LINE> fallback = newest and not (filename in d...
Open a configuration file and return the result as a dictionary, Recursively open other files based on buildout options found.
625941d40c0af96317bb83d0
def display_splash_screen(self, img_name=None, pos=None, size=(320, 240)): <NEW_LINE> <INDENT> w, h = size <NEW_LINE> image = wx.Image(img_name, wx.BITMAP_TYPE_PNG) <NEW_LINE> image.Rescale(w, h, wx.IMAGE_QUALITY_HIGH) <NEW_LINE> bm = image.ConvertToBitmap() <NEW_LINE> splash = SplashScreen( bitmap=bm, splashStyle=(SPL...
Displays a splash screen and the specified position and size.
625941d49f2886367277aa74
def destroy(self, force = False): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not force: <NEW_LINE> <INDENT> self.join() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._dbg(2, 'Destroying queue...') <NEW_LINE> self.workqueue.destroy() <NEW_LINE> self.account_manager.reset() <NEW_LINE> self.completed...
Like shutdown(), but also removes all accounts, hosts, etc., and does not restart the queue. In other words, the queue can no longer be used after calling this method. @type force: bool @param force: Whether to wait until all jobs were processed.
625941d41f037a2d8b9463e5
def clean_user(self): <NEW_LINE> <INDENT> user = self.cleaned_data.get("user") <NEW_LINE> user_flag = UserInfo.objects.filter(username=user).first() <NEW_LINE> if not user_flag: <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValidationError("用户名已存在!")
用户名局部钩子 :return:
625941d491f36d47f21ac6db
def getTopLevelDefinition(self): <NEW_LINE> <INDENT> return self.body
Get the top level definition for the query
625941d4099cdd3c635f0e42