code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def update(self, state, action, nextState, reward): <NEW_LINE> <INDENT> legalActions = self.getLegalActions(nextState) <NEW_LINE> if legalActions: <NEW_LINE> <INDENT> self.Qvalue[(state, action)] = (1 - self.alpha) * self.Qvalue[(state, action)] + self.alpha * ( reward + self.discount * self.computeValueFromQValues(nex... | The parent class calls this to observe a
state = action => nextState and reward transition.
You should do your Q-Value update here
NOTE: You should never call this function,
it will be called on your behalf | 625941e691f36d47f21ac94b |
def ponovnaIgra(self): <NEW_LINE> <INDENT> return self.ponastaviIgro() | Ponovna igra | 625941e6236d856c2ad44c34 |
def isGoalState(self, state): <NEW_LINE> <INDENT> for n in range(0,4): <NEW_LINE> <INDENT> if (not state[1][n] and not state[0] == self.corners[n]): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True | Returns whether this search state is a goal state of the problem. | 625941e624f1403a92600fb7 |
def run(args): <NEW_LINE> <INDENT> os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = args.gcred <NEW_LINE> client = bigquery.Client() <NEW_LINE> dataset_ref = client.dataset(args.bqds) <NEW_LINE> table_ref = dataset_ref.table(args.bqtbl) <NEW_LINE> table = client.get_table(table_ref) <NEW_LINE> table_schema = bbq.TableSch... | run method
:param args: | 625941e69f2886367277acde |
def graph_bags(): <NEW_LINE> <INDENT> rules = get_input() <NEW_LINE> graph = {} <NEW_LINE> for rule in rules: <NEW_LINE> <INDENT> bags = rule.split(' bags contain ') <NEW_LINE> if graph.get(bags[0]) is not None: <NEW_LINE> <INDENT> graph[bags[0]] += parse_bag_rules(bags[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>... | Collects the input, and starts parsing it. First it'll
split the string to collect the bag that contains other
bags. Then it'll parse the 2nd half of the string to see
what bags that bag contained. | 625941e685dfad0860c3b2b0 |
def _startKey(self, attrs): <NEW_LINE> <INDENT> code = self._getControlCode(attrs, Key.findCodeFor) <NEW_LINE> if self._parent == "virtualState": <NEW_LINE> <INDENT> value = self._getIntAttribute(attrs, "value") <NEW_LINE> if value<0 or value>1: <NEW_LINE> <INDENT> self._fatal("the value should be 0 or 1 for a key") <N... | Handle the key start tag.
It is handled by this function for the case when ther parent element is
'virtualState'. For other parents _handleStartKey() is called with the
key's code. | 625941e6283ffb24f3c55d51 |
def _partition_or_replicate_on_host(self, tensor, dims): <NEW_LINE> <INDENT> self._check_input_partition_dims(tensor, dims) <NEW_LINE> if dims is None: <NEW_LINE> <INDENT> return itertools.repeat(tensor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> output = [tensor] <NEW_LINE> for axis, dim in enumerate(dims): <NEW_LI... | Partitions or replicates the input tensor.
The ops inside this function are placed on the host side.
Args:
tensor: The input tensor which will be partioned or replicated.
dims: A list of integer describes how to partition the input tensor.
Returns:
An iterator of `Tensor`s or a list of partioned tensors. | 625941e61f5feb6acb0c4f9e |
def stats(args): <NEW_LINE> <INDENT> p = OptionParser(stats.__doc__) <NEW_LINE> p.add_option("--gene", default="mRNA", help="The gene type [default: %default]") <NEW_LINE> p.add_option("--exon", default="CDS", help="The exon type [default: %default]") <NEW_LINE> opts, args = p.parse_args(args) <NEW_LINE> if len(args) !... | %prog stats infile.gff
Collect gene statistics based on gff file. There are some terminology issues
here and so normally we call "gene" are actually mRNA, and sometimes "exon"
are actually CDS, but they are configurable.
Thee numbers are written to text file in four separate folders,
corresponding to the four metrics... | 625941e63346ee7daa2b31c4 |
def test_emb_document(self): <NEW_LINE> <INDENT> self.assertTrue(issubclass(EmbeddedDocument, Helper)) | Embedded Document should inhert Helper. | 625941e6d268445f265b52c3 |
def get_GPA(s: Student) -> float: <NEW_LINE> <INDENT> return s.GPA | Return student's GPA | 625941e6e5267d203edce0eb |
def getEvents(self, indices = None): <NEW_LINE> <INDENT> if indices is None: <NEW_LINE> <INDENT> request = struct.pack('HHI', VERSION, GET_EVT, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> indS = int(indices[0]) <NEW_LINE> if len(indices)==1: <NEW_LINE> <INDENT> indE = indS <NEW_LINE> <DEDENT> else: <NEW_LINE> <IND... | getEvents([indices]) -- retrieve events and return them as a list of Event objects.
The 'indices'=[start end] argument is optional, and if given, must be a tuple or list with
inclusive, zero-based start/end indices. The 'type' and 'value' fields of the event
will be converted to strings or Numpy arrays. | 625941e6e1aae11d1e74a110 |
def printProperly(text, printSpeed = 0.0,end = "\n"): <NEW_LINE> <INDENT> import time <NEW_LINE> linePos = 0 <NEW_LINE> for letter in text: <NEW_LINE> <INDENT> if letter == "$": <NEW_LINE> <INDENT> print("\n") <NEW_LINE> linePos = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(letter, end="") <NEW_LINE> time.sle... | Prints 66 characters then starts looking to make a new line. | 625941e6cdde0d52a9e5348a |
def test_invalid(self): <NEW_LINE> <INDENT> tests = [[1, 2, 3, 4], {1: 2, 2: 3}] <NEW_LINE> port = 1000 <NEW_LINE> for test in tests: <NEW_LINE> <INDENT> with pytest.raises(TypeError): <NEW_LINE> <INDENT> VideoSrc(port=port, pattern=test) | Test when pattern is not a valid integer | 625941e601c39578d7e75290 |
def dragEnterEvent(self, QGraphicsSceneDragDropEvent): <NEW_LINE> <INDENT> pass | dragEnterEvent(self, QGraphicsSceneDragDropEvent) | 625941e660cbc95b062c6998 |
def test_volume_max_size_bytes_integer(self): <NEW_LINE> <INDENT> config = dict( version=1, applications={ 'mysql-hybridcluster': { 'image': 'clusterhq/mysql:v1.0.0', 'ports': [dict(internal=3306, external=3306)], 'volume': {'mountpoint': '/var/lib/mysql', 'maximum_size': 1000000}, }, } ) <NEW_LINE> parser = FlockerCon... | A volume maximum_size config value given as an integer raises a
``ConfigurationError`` in ``FlockerConfiguration.applications``. | 625941e6566aa707497f49b7 |
def run(self): <NEW_LINE> <INDENT> self.clearUI() <NEW_LINE> self.loadLayers() <NEW_LINE> self.dlg.show() <NEW_LINE> result = self.dlg.exec_() <NEW_LINE> if result: <NEW_LINE> <INDENT> self.runAlgorithm() | Run method that performs all the real work | 625941e6cb5e8a47e48b7ef8 |
def is_action_allowed(self, name): <NEW_LINE> <INDENT> return name not in self.action_disallowed_list | Override this method to allow or disallow actions based
on some condition.
Default implementation only checks if particular action
is not in `action_disallowed_list`. | 625941e6ab23a570cc2505db |
def test_ingredient_detail_editor(self): <NEW_LINE> <INDENT> self.user_login('admin') <NEW_LINE> self.ingredient_detail(editor=True) | Tests the ingredient details page as a logged in user with editor rights | 625941e6aad79263cf390e9c |
def addE3PlannedMessage(self, id): <NEW_LINE> <INDENT> objNewE3PlannedMessage = E3PlannedMessage(id) <NEW_LINE> self._setObject(id, objNewE3PlannedMessage) <NEW_LINE> return "New E3PlannedMessage created." | New E3PlannedMessage action | 625941e6cdde0d52a9e5348b |
def clear(self): <NEW_LINE> <INDENT> self._chat_lines.insert(0, "") <NEW_LINE> self._current_chat_line_idx += 1 <NEW_LINE> if len(self._chat_lines) > 100: <NEW_LINE> <INDENT> self._chat_lines = self._chat_lines[0:99] <NEW_LINE> <DEDENT> self._swap_to_chat_line(0) | clears the widget's contents, saving them | 625941e676e4537e8c351aca |
def init_xml_tree(self, xml_root): <NEW_LINE> <INDENT> version_tag = BaseXML.create_tag('Easy-Karabiner', __version__) <NEW_LINE> item_tag = BaseXML.create_tag('item') <NEW_LINE> item_tag.append(BaseXML.create_tag('name', 'Easy-Karabiner')) <NEW_LINE> xml_root.append(version_tag) <NEW_LINE> xml_root.append(item_tag) <N... | <Easy-Karabiner>{version}</Easy-Karabiner>
<item>
<name>Easy-Karabiner</name>
<!-- REMAIN NODES HERE -->
</item> | 625941e6cc0a2c11143dd2e6 |
def draw_rect(x, y, width, height, color=(255, 255, 255), line_width=5): <NEW_LINE> <INDENT> screen = pygame.display.get_surface() <NEW_LINE> pygame.draw.rect(screen, color, (x, y, width, height), line_width) | Draw rectangle of dimensions (width, height) at position (x, y) | 625941e629b78933be1e5afb |
def _seeds_stored(self, p): <NEW_LINE> <INDENT> return self._seeds[self._board.stores[p]] | Returns the number of seeds in the store for the given player.
p -- the index of a player; either 0 or 1 | 625941e623e79379d52ee9b3 |
def provider_id(self): <NEW_LINE> <INDENT> return self.__class__.__name__.replace("Provider", "").lower() | Id of this provider (there can only be one active at a time) | 625941e6bde94217f3683241 |
def finalize(self): <NEW_LINE> <INDENT> return self.deque | Final steps the visitor needs to take, plus the
return value or .visit, if any. | 625941e645492302aab5e71c |
def victory_dance(self): <NEW_LINE> <INDENT> self.x += 5 <NEW_LINE> self.y += 5 <NEW_LINE> self.say('I... AM... GOD!') | The victory_dance() method is called if your bot wins a match. Since it
is only called at the end, do whatever you want in here. Go crazy! | 625941e6460517430c3945ce |
def test_space_only_added_if_necessary(): <NEW_LINE> <INDENT> msg = netsyslog.MsgPart("program", content=" hello") <NEW_LINE> assert str(msg) == "program hello" | Check space only added to CONTENT if necessary | 625941e682261d6c526ab8fb |
def enroll(self, user): <NEW_LINE> <INDENT> if self.authenticator is None: <NEW_LINE> <INDENT> self.authenticator = Authenticator.objects.create( user=user, type=self.type, config=self.config, ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not self.allow_multi_enrollment: <NEW_LINE> <INDENT> raise RuntimeError('Alr... | Invoked to enroll a user for this interface. If already enrolled
an error is raised. | 625941e67d43ff24873a30f8 |
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, V1InterfaceSlirp): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ | Returns true if both objects are equal | 625941e6e64d504609d74c95 |
def read_csv_as_nested_dict(filename, keyfield, separator, quote): <NEW_LINE> <INDENT> table = {} <NEW_LINE> with open(filename, newline='') as csvfile: <NEW_LINE> <INDENT> reader = csv.DictReader(csvfile, delimiter = separator, quotechar = quote) <NEW_LINE> for row in reader: <NEW_LINE> <INDENT> table[row[keyfield]] =... | read csv as nested list | 625941e64e4d5625662d4826 |
def test_dict_serialization(self): <NEW_LINE> <INDENT> alert_message = ndr.AlertMessage(self._ncc) <NEW_LINE> alert_message.raised_by = "unittest" <NEW_LINE> alert_message.contents = "Test" <NEW_LINE> alert_dict = alert_message.to_dict() <NEW_LINE> self.assertEqual(alert_dict['raised_by'], 'unittest') <NEW_LINE> self.a... | Tests exporting to dict form | 625941e694891a1f4081bf00 |
def removeNthFromEnd_twice(self, head: ListNode, n: int): <NEW_LINE> <INDENT> before_head = ListNode(0) <NEW_LINE> before_head.next = head <NEW_LINE> length = 0 <NEW_LINE> node = before_head <NEW_LINE> while node: <NEW_LINE> <INDENT> length += 1 <NEW_LINE> node = node.next <NEW_LINE> <DEDENT> length = length - n <NEW_L... | 双遍历法,
第一次得出链表长度;
第二次删除结点。
时间复杂度O(L)L为链表长度,操作执行了 2L-n2L−n 步,时间复杂度为 O(L)O(L)。
空间复杂度:O(1)常量级额外空间。
:param head:
:param n:
:return:ListNode | 625941e626238365f5f0f2c9 |
def prefork( num=None, fork=fork, do_seed=True, do_wait=True, do_kill=True ): <NEW_LINE> <INDENT> if not num: <NEW_LINE> <INDENT> num = cpu_count() <NEW_LINE> <DEDENT> pids = [] <NEW_LINE> for n in range(num): <NEW_LINE> <INDENT> pid = fork() <NEW_LINE> if pid: <NEW_LINE> <INDENT> pids.append( pid ) <NEW_LINE> <DEDENT>... | Forks current process num times.
fork -- a forking function
do_seed -- True to reseed a pseudo-random generator of a child
do_wait -- True to wait for all children to exit
do_kill -- True to pass a recieved signal (INT,TERM,QUIT) to all children
Returns a list of child pids for master or an empty list for a child. | 625941e6e76e3b2f99f3ac59 |
def get_power_real(freq,bandwidth,diameter, hour, print_values=False): <NEW_LINE> <INDENT> Power_mer = [] <NEW_LINE> Power_mars = [] <NEW_LINE> Power_nep = [] <NEW_LINE> Power_jup = [] <NEW_LINE> Power_ur = [] <NEW_LINE> Power_ven = [] <NEW_LINE> Power_sat = [] <NEW_LINE> Power_sun = [] <NEW_LINE> aperture = np.pi*(dia... | Power of the planets + sun at a certain time, frequency, and bandwidth
Arguments:
freq: frequencie at which to measure the power
bandwidth: bandwidth corresponding to the frequency
diameter: diameter of the aperture of the telescope in meters
hour: index of the time at which the calculation will be done... | 625941e6f8510a7c17cf9b54 |
def eveluator(orig_img,target): <NEW_LINE> <INDENT> result = discriminator([target,orig_img], training=False) <NEW_LINE> ev_loss = mse(tf.ones_like(result),result) <NEW_LINE> return ev_loss | 这里只测试,原图和变换过的图片 | 625941e6eab8aa0e5d26dfae |
def histoClassification(self, channel, ksize, kstep, dst_metric, numCluster, showDendogram=True, view=True): <NEW_LINE> <INDENT> channel = channel.lower()[0] <NEW_LINE> if self.bw: <NEW_LINE> <INDENT> ch = [0] <NEW_LINE> <DEDENT> elif 'b' in channel: <NEW_LINE> <INDENT> ch = [0] <NEW_LINE> <DEDENT> elif 'g' in channel:... | classify areas according to histogram
Arguments:
channel {string} -- channel on which to compute histogram. If image is BW this value is ignored (R,r,Red,red)(G,g,Green,green)(B,b,Blue,blue)
ksize {[int, int]} -- size of areas to be classified
kstep {[int, int]} -- step of area shift. kstep[0] is horizonta... | 625941e6d58c6744b42580b3 |
def tokenize(self, string, column="graphemes"): <NEW_LINE> <INDENT> if self.orthography_profile and self.orthography_profile_rules: <NEW_LINE> <INDENT> return self.rules(self.transform(string, column)) <NEW_LINE> <DEDENT> if not self.orthography_profile and not self.orthography_profile_rules: <NEW_LINE> <INDENT> return... | This function determines what to do given any combination
of orthography profiles and rules or not orthography profiles
or rules.
Parameters
----------
string : str
The input string to be tokenized.
column : str (default = "graphemes")
The column label for the transformation, if specified.
Returns
-------
re... | 625941e6462c4b4f79d1db24 |
def test_access_admin_not_owner_else_member(user_1, user_2, user_3): <NEW_LINE> <INDENT> admin_userpermission_change(user_1["token"], user_3["u_id"], OWNER) <NEW_LINE> with pytest.raises(AccessError): <NEW_LINE> <INDENT> admin_userpermission_change(user_2["token"], user_3["u_id"], MEMBER) <NEW_LINE> <DEDENT> clear() | Testing whether a member can change someone else's permissions to member
| 625941e6cc40096d61595da4 |
def write_seqs(filename): <NEW_LINE> <INDENT> struct_name = os.path.splitext(os.path.basename(filename))[0] <NEW_LINE> is_CIF = False <NEW_LINE> try: <NEW_LINE> <INDENT> parser = PDBParser() <NEW_LINE> structure = parser.get_structure(struct_name, filename) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE... | Process a given structure file to extract sequences and save them into files.
| 625941e63539df3088e2e7a0 |
def encode(self, tags): <NEW_LINE> <INDENT> l = [] <NEW_LINE> for tag in tags: <NEW_LINE> <INDENT> if self.mutable: <NEW_LINE> <INDENT> if tag not in self.index: <NEW_LINE> <INDENT> new_idx = len(self.index) <NEW_LINE> self.index[tag] = new_idx <NEW_LINE> self.rev_index[new_idx] = tag <NEW_LINE> <DEDENT> <DEDENT> l.app... | tags : iterable of tags | 625941e645492302aab5e71d |
def smell_of(agent, tokens, _): <NEW_LINE> <INDENT> return Sense('smell', agent, template='[agent/s] [smell/v] [direct/o]', direct=tokens[1], modality='smell') | to perceive something by the sense of smell | 625941e6adb09d7d5db6cbe2 |
def background(self): <NEW_LINE> <INDENT> return KColorScheme.BackgroundRole() | KColorScheme.BackgroundRole KColorScheme.background() | 625941e6004d5f362079a786 |
def _explorer_view_factory(self, window, **traits): <NEW_LINE> <INDENT> from pyface.workbench.traits_ui_view import TraitsUIView <NEW_LINE> explorer = self._get_explorer(window) <NEW_LINE> tui_engine_view = TraitsUIView(obj=explorer, id='explorer3d.Explorer3D', name='Explorer3D', window=window, position=... | Factory method for explorer views. | 625941e623849d37ff7b34e1 |
def __set_hp(self, hit_points): <NEW_LINE> <INDENT> old_hit_points = self.__hit_points <NEW_LINE> new_hit_points = hit_points <NEW_LINE> self.__hit_points = hit_points <NEW_LINE> self.raise_event( new_hit_points_changed_event(character=self, old_hit_points=old_hit_points, new_hit_points=new_hit_points)) | Current hitpoints | 625941e68da39b475bd653ce |
def log_file_names(ifile_paths,log_file_outfile_path): <NEW_LINE> <INDENT> rootnames = [os.path.basename(f) for f in ifile_paths] <NEW_LINE> print('Logging files used to create median flat.') <NEW_LINE> with open(log_file_outfile_path,'a') as f: <NEW_LINE> <INDENT> for rootname in rootnames: <NEW_LINE> <INDENT> f.write... | Creates a log file of the rootnames of files that went in to making the median
flat for each filter.
Parameters
----------
ifile_paths: list of strings
list of input files to write out to log file
log_file_outfile_path: string
full path to txt file that file names should be logged in
Outputs
-------
A ... | 625941e6f548e778e58cd9d5 |
@never_cache <NEW_LINE> @login_maybe_required <NEW_LINE> def profile_details(request, profile_id): <NEW_LINE> <INDENT> profile = get_object_or_404(model.Profile, pk=profile_id) <NEW_LINE> return TemplateResponse( request, "manage/environment/profile_list/_profile_details.html", { "profile": profile } ) | Get details snippet for a profile. | 625941e6293b9510aa2c36e7 |
def make_python_script_from_current_run(script_file=""): <NEW_LINE> <INDENT> list_optical_elements = [] <NEW_LINE> sourceB = Shadow.Source() <NEW_LINE> sourceB.load("start.00") <NEW_LINE> list_optical_elements.append(sourceB) <NEW_LINE> for file in open("systemfile.dat","r").readlines(): <NEW_LINE> <INDENT> if file!=""... | program to build automatically a python script to run shadow3
the system is read from start.00 Aand systemfile.dat, that must exist in the current directory
srio@esrf.eu
:param script_file: a string with the name of the output file (default="", no output file)
:return: template with the script | 625941e6a17c0f6771cbe4a5 |
def get_entry_points(self): <NEW_LINE> <INDENT> return self.entry_point_names | returns a set of all the entry points tracked internally | 625941e6d7e4931a7ee9e374 |
def test_genericerror_already_in_done(self): <NEW_LINE> <INDENT> self.response.state = PutContentResponse.states.done <NEW_LINE> called = [] <NEW_LINE> self.response._send_protocol_error = called.append <NEW_LINE> self.response._generic_error(NameError('foo')) <NEW_LINE> self.assertFalse(called) <NEW_LINE> self.handler... | Just log if already in done. | 625941e6a8370b7717052cf3 |
def __test_collision_of_all_units(self): <NEW_LINE> <INDENT> self.collide_list = [] <NEW_LINE> for sprite_1 in self.all_COLOR1_units_list: <NEW_LINE> <INDENT> for sprite_2 in self.all_COLOR2_units_list: <NEW_LINE> <INDENT> if sprite_1.is_collided_with(sprite_2): <NEW_LINE> <INDENT> self.collide_list += [(sprite_1, spri... | Checks if anything is collided. | 625941e6462c4b4f79d1db25 |
def __init__(self, back_plane_ip_address=None, subscriber_port='43125', publisher_port='43124', process_name=None): <NEW_LINE> <INDENT> super().__init__(back_plane_ip_address, subscriber_port, publisher_port, process_name=process_name) <NEW_LINE> time.sleep(.03) <NEW_LINE> self.set_subscriber_topic('user_motor_command'... | :param back_plane_ip_address:
:param subscriber_port:
:param publisher_port: | 625941e6f9cc0f698b140a4d |
def scalebox(self, key=None, pattern=None) -> bool: <NEW_LINE> <INDENT> if key==None: <NEW_LINE> <INDENT> key = lambda x: 1 <NEW_LINE> <DEDENT> if pattern==None: <NEW_LINE> <INDENT> pattern = r"\scalebox{%s}[%s]{%s}" <NEW_LINE> <DEDENT> temp = None <NEW_LINE> for i in range(self.length): <NEW_LINE> <INDENT> temp = key(... | Scale.
----------
Arg(s):
key: Lambda function with one
parameter.
Return(s):
True. | 625941e607d97122c4178ceb |
def bipartite(G: Graph): <NEW_LINE> <INDENT> discovered = {} <NEW_LINE> color = {} <NEW_LINE> X = set() <NEW_LINE> Y = set() <NEW_LINE> partition = None <NEW_LINE> for node in G.vertices(): <NEW_LINE> <INDENT> if node not in color: <NEW_LINE> <INDENT> color[node] = False <NEW_LINE> <DEDENT> <DEDENT> for v in G.vertices... | La funzione verifica se G è bipartito e restituisce una partizione (X, Y) dei vertici di G tale che
tutti gli archi del grafo collegano un vertice di X ad un vertice di Y. Nel caso in cui il grafo non
sia bipartito la funzione deve restituire None.
:param G: grafo non diretto da ispezionare
:return: None se il grafo no... | 625941e63eb6a72ae02ec93e |
def augment(self, item, aug_index=0): <NEW_LINE> <INDENT> angle = self.angular_step * aug_index <NEW_LINE> item.rotate(angle, self.axis) | Displaces points objects points along their normals
Args:
item: Points object to augment | 625941e666673b3332b924e6 |
def test_dvidir(self): <NEW_LINE> <INDENT> self.check_decl('dvidir', '${docdir}') | test AcDirVars.declare_gvars()['dvidir'] | 625941e691af0d3eaac9be72 |
def getCriteriaItems(self): <NEW_LINE> <INDENT> topic = Acquisition.aq_parent(Acquisition.aq_inner(self)) <NEW_LINE> if not interfaces.IFormTopic.providedBy(topic) or ( self.Field() != 'unsorted' and ( self.getId() in self.REQUEST or Acquisition.aq_base(self) is Acquisition.aq_base( topic.listSortCriteria()[0]))): <NEW... | Only use this sort if it is the default or is specified | 625941e6091ae356686673ac |
def main(*args): <NEW_LINE> <INDENT> base_path = path.dirname(path.abspath(__file__)) <NEW_LINE> options = handle_args(args) <NEW_LINE> log = {} <NEW_LINE> data_file = options.pop('in_file') or path.join(base_path, DATA_INPUT_FILE) <NEW_LINE> main_data = load_csv_data(data_file, log) <NEW_LINE> nat_coords_data = load_c... | Command line entry point. | 625941e660cbc95b062c6999 |
def __init__(self,dirname,log_prefix,log_suffix=".log",cache_ext=".cifpk", inactive_files=None, inactive_timeout=24*3600, cache_dir=None): <NEW_LINE> <INDENT> self.cdInit(logCompleted, dirname, log_prefix, log_suffix, cache_ext, inactive_files, inactive_timeout, cache_dir) | @param inactive_files: if ==None, will be reloaded from cache
@param inactive_timeout: how much time must elapse before
@param cache_dir: if None, use dirname | 625941e6167d2b6e31218fea |
def get_estimates(input_file): <NEW_LINE> <INDENT> with gzip.open(input_file, "rb") as f: <NEW_LINE> <INDENT> return pickle.load(f) | Reads density, and probability estimates from a output file produced by the NTCIR Math Density
Estimator package.
Parameters
----------
input_file : file
An input file with density, and probability estimates.
Returns
-------
six-tuple of (sequence of float)
Estimates of P(relevant), p(position), p(position | ... | 625941e6711fe17d825427b7 |
def from_affine_weyl(self, w): <NEW_LINE> <INDENT> WF = self.realization_of().WF() <NEW_LINE> return self(WF.from_affine_weyl(w)) | Return the image of `w` under the homomorphism from the affine Weyl group
into ``self``.
EXAMPLES::
sage: E = ExtendedAffineWeylGroup(['A',3,1]); PW0=E.PW0()
sage: W = E.affine_weyl()
sage: w = W.from_reduced_word([2,1,3,0])
sage: x = PW0.from_affine_weyl(w); x
t[Lambdacheck[1] - 2*Lambdacheck[2] ... | 625941e6b830903b967e9d5c |
def GetNumberOfBins(self): <NEW_LINE> <INDENT> return _itkLabelImageToStatisticsLabelMapFilterPython.itkLabelImageToStatisticsLabelMapFilterIUL3IUC3LM3_GetNumberOfBins(self) | GetNumberOfBins(self) -> unsigned int | 625941e6442bda511e8be868 |
def write_csv(path, field_template, csv_dict): <NEW_LINE> <INDENT> with open(path, "w") as csv_file: <NEW_LINE> <INDENT> writer = csv.DictWriter(csv_file, lineterminator="\n", fieldnames=field_template) <NEW_LINE> writer.writeheader() <NEW_LINE> writer.writerows(csv_dict) | Args:
path(str): Location to copy file to. Must include filename and extension.
field_template(list): List of column names for final csv data.
csv_dict(list of dict): List of formatted task dictionaries where keys match the field template key names.
Returns: Writes a csv of the given data to the given loca... | 625941e6656771135c3ebcc9 |
def update(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.updated_at = datetime.now(UTC) <NEW_LINE> self.event = ActionCatalog.PLAN_UPDATE <NEW_LINE> self.session.commit() <NEW_LINE> return self | Updates ONLY the plan name. By design the only updateable field is
the name.
To change other params create a new plan.
:param name: The new display name for the plan
:raise NotFoundError: if plan not found.
:returns: New Plan object | 625941e673bcbd0ca4b2c4cb |
def display_mancala_board(mancala_board): <NEW_LINE> <INDENT> p1_buckets = [bucket for bucket in mancala_board.buckets if bucket.owner == 1 and not bucket.scoring] <NEW_LINE> p2_buckets = [bucket for bucket in mancala_board.buckets if bucket.owner == 2 and not bucket.scoring] <NEW_LINE> print("-------", end=' ') <NEW_L... | Used to print the board state. | 625941e62c8b7c6e89b35c13 |
def test_invalid_target_result_type(self, db: Session): <NEW_LINE> <INDENT> create_dependencies(db, self.dependencies()) <NEW_LINE> model = self.create_model(True) <NEW_LINE> evaluator_results = model.target_results[0]["evaluator-target-1"] <NEW_LINE> recharge_results = model.target_results[0]["recharge-target-1"] <NEW... | Tests that an exception is raised when results are uploaded but
do not contain results for all of the expected targets. | 625941e65510c4643540f82f |
def get(self, key): <NEW_LINE> <INDENT> bucket_index = hash(key) % self.__capacity <NEW_LINE> node = self.__array[bucket_index] <NEW_LINE> while node: <NEW_LINE> <INDENT> if node.key == key: <NEW_LINE> <INDENT> return node.value <NEW_LINE> <DEDENT> node = node.next_node | Get value corresponding to key | 625941e694891a1f4081bf01 |
@contextlib.contextmanager <NEW_LINE> def tempdir(): <NEW_LINE> <INDENT> temp_path = tempfile.mkdtemp() <NEW_LINE> yield temp_path <NEW_LINE> shutil.rmtree(temp_path) | Creates a temporary directory that is deleted outside the context scope. | 625941e663b5f9789fde753c |
def get_key(self, id): <NEW_LINE> <INDENT> assert isinstance(id, (int, long)), id <NEW_LINE> headers, data = self._requester.requestJsonAndCheck( "GET", "/user/keys/" + str(id), None, None ) <NEW_LINE> return github.UserKey.UserKey(self._requester, data, completed=True) | :calls: `GET /user/keys/:id <http://developer.github.com/v3/todo>`_
:param id: integer
:rtype: :class:`github.UserKey.UserKey` | 625941e6d8ef3951e3243994 |
def test_secret_create_defaults_bad_content_type_check_message(self): <NEW_LINE> <INDENT> test_model = secret_models.SecretModel(**secret_create_defaults_data) <NEW_LINE> overrides = {"payload_content_type": 'plain-text'} <NEW_LINE> test_model.override_values(**overrides) <NEW_LINE> resp, secret_ref = self.behaviors.cr... | will create a secret with an "invalid" content type
(plain-text, rather than text/plain). This will result in
an error, and we need to ensure that the error msg is
reasonable. | 625941e6a8ecb033257d3521 |
def __sub__(self, other): <NEW_LINE> <INDENT> T = ReversibleCompoundTransform(self) <NEW_LINE> T.add(-other) <NEW_LINE> return T | returns the concatenation of this transform and the reverse of other | 625941e6009cb60464c63804 |
def test_documet_access_open(self): <NEW_LINE> <INDENT> self.assertEqual( self.document.is_authorized()[0], 0 ) | Test the document if it's open to everyone by default. | 625941e62ae34c7f2600d587 |
def itkExtractImageFilterIUC3IUC3_cast(*args): <NEW_LINE> <INDENT> return _itkExtractImageFilterPython.itkExtractImageFilterIUC3IUC3_cast(*args) | itkExtractImageFilterIUC3IUC3_cast(itkLightObject obj) -> itkExtractImageFilterIUC3IUC3 | 625941e60c0af96317bb863e |
def post_process_message(self, message): <NEW_LINE> <INDENT> message.delete() | override this method for custom handling of the message
after consumption
for now it just deletes the message | 625941e6851cf427c661a961 |
def read(self, file_name, file_type=None): <NEW_LINE> <INDENT> self.logger.info('Reading NN correlations from %s',file_name) <NEW_LINE> data, params = treecorr.util.gen_read(file_name, file_type=file_type) <NEW_LINE> self.rnom = data['R_nom'] <NEW_LINE> self.logr = numpy.log(self.rnom) <NEW_LINE> self.meanr = data['mea... | Read in values from a file.
This should be a file that was written by TreeCorr, preferably a FITS file, so there
is no loss of information.
Warning: The NNCorrelation object should be constructed with the same configuration
parameters as the one being read. e.g. the same min_sep, max_sep, etc. This is not
checked ... | 625941e64f88993c3716c4b9 |
def create_credentials(fname,lname,phone,email): <NEW_LINE> <INDENT> new_user = Credentials(fname,lname,phone,email) <NEW_LINE> return new_user | Create new User | 625941e6fff4ab517eb2f895 |
def hermite( order, mu=0., sigma=1., physicist=False, normed=False, retall=False, ): <NEW_LINE> <INDENT> multiplier = 2 if physicist else 1 <NEW_LINE> _, [polynomials], [norms] = chaospy.recurrence.analytical_stieltjes( order, chaospy.Normal(mu, sigma), multiplier=multiplier) <NEW_LINE> if normed: <NEW_LINE> <INDENT> p... | Hermite orthogonal polynomial expansion.
Args:
order (int):
The quadrature order.
mu (float):
Non-centrality parameter.
sigma (float):
Scale parameter.
physicist (bool):
Use physicist weights instead of probabilist variant.
normed (bool):
If True orthonormal ... | 625941e6236d856c2ad44c36 |
def msg(self, text=None, **kwargs): <NEW_LINE> <INDENT> if isinstance(text, tuple) and "type" in text[1] and text[1]["type"] == "whisper": <NEW_LINE> <INDENT> self.db.bot.msg(text=text, user=self.db.nick, **kwargs) | Whilst the listener sends everything to the Session Bot. We only want
to send private messages. Otherwise the Server bot would get 50 msgs
each time something is said. | 625941e685dfad0860c3b2b2 |
def calibrate(hbridge): <NEW_LINE> <INDENT> GPIO.setmode(GPIO.BOARD) <NEW_LINE> GPIO.setup(hbridge['FM'], GPIO.OUT) <NEW_LINE> GPIO.setup(hbridge['BM'], GPIO.OUT) <NEW_LINE> GPIO.setup(hbridge['R'], GPIO.OUT) <NEW_LINE> GPIO.setup(hbridge['L'], GPIO.OUT) <NEW_LINE> GPIO.setup(hbridge['B'], GPIO.OUT) <NEW_LINE> GPIO.set... | Straightens out the front wheel set and set pins to OUTPUT | 625941e6b545ff76a891426b |
def add(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Install the tool into the tools directory
| 625941e69f2886367277ace0 |
def insertBulkBlock(self, blockDump): <NEW_LINE> <INDENT> currentInfo = [] <NEW_LINE> if os.path.getsize(self.dbsPath): <NEW_LINE> <INDENT> inFileHandle = open(self.dbsPath, 'r') <NEW_LINE> currentInfo = json.load(inFileHandle) <NEW_LINE> inFileHandle.close() <NEW_LINE> <DEDENT> outFileHandle = open(self.dbsPath, 'w') ... | _insertBulkBlock_
Insert a block into fake DBS, only insert the block specific information
and no file information in the file given in the dbsPath.
There is 20% chance of a proxy error! | 625941e6187af65679ca5576 |
def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.update(*args, **kwargs) | Do whatever is needed to have the box Working, like connecting to
databases, getting needed parameters, etc | 625941e60fa83653e465740f |
def _parse_min_max_values_single(self, limits): <NEW_LINE> <INDENT> out = dict() <NEW_LINE> if len(limits) == 0: <NEW_LINE> <INDENT> return out <NEW_LINE> <DEDENT> for (key, value) in limits.items(): <NEW_LINE> <INDENT> if key not in self._fit_parameters: <NEW_LINE> <INDENT> raise ValueError( 'Key provided in limits: {... | change dict that has str as key to index as key | 625941e63346ee7daa2b31c5 |
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> buff.write(_struct_i.pack(self.errorCnt)) <NEW_LINE> _x = self.errorStrings <NEW_LINE> length = len(_x) <NEW_LINE> if python3 or type(_x) == unicode: <NEW_LINE> <INDENT> _x = _x.encode('utf-8') <NEW_LINE> length = len(_x) <NEW_LINE> <DEDENT> if pyt... | serialize message into buffer
:param buff: buffer, ``StringIO`` | 625941e6e1aae11d1e74a112 |
def _repo_stats(output_file: str, account_number: str = "") -> None: <NEW_LINE> <INDENT> role_ids: Iterable[str] <NEW_LINE> if account_number: <NEW_LINE> <INDENT> access_advisor_datasource = AccessAdvisorDatasource() <NEW_LINE> access_advisor_datasource.seed(account_number) <NEW_LINE> iam_datasource = IAMDatasource() <... | Create a csv file with stats about roles, total permissions, and applicable filters over time
Args:
output_file (string): the name of the csv file to write
account_number (string): if specified only display roles from selected account, otherwise display all
Returns:
None | 625941e6e5267d203edce0ed |
def job_reviewers(jobname,ignore_author=None): <NEW_LINE> <INDENT> return parse_p4_review(p4 + ' reviews ' + jobpath,ignore_author) | For a given job, return list of reviewers' email addresses,
plus a list of email addresses + full names.
If ignore_author is given then the given user will not be included
in the lists. | 625941e6d268445f265b52c5 |
def test__defect_178106k(self): <NEW_LINE> <INDENT> myteal = teal.Teal('data/gear_ruleset_test/bugs/d178106/config.conf', 'stderr', msgLevel=self.msglevel, commit_alerts=False, commit_checkpoints=False) <NEW_LINE> event_q = get_service(SERVICE_EVENT_Q) <NEW_LINE> event_q.put_nowait(self._crt_isnm_event(1, 'BD700025', '... | Ensure that defect does not get regressed -- Case 1 | 625941e660cbc95b062c699a |
def course_content_count(json_data): <NEW_LINE> <INDENT> content_count_dict = {} <NEW_LINE> if 'weeks' not in json_data: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for k, v in json_data['content_units'].items(): <NEW_LINE> <INDENT> if k in json_data['weeks']: <NEW_LINE> <INDENT> content... | Counts how many lessons there are in each week of a course.
Parameters
----------
json_data : {dict} a JSON structure as read from a file using read_json_file().
Returns
-------
dict : a dictionary giving for each week of the course the number of lessons.
Notes
-----
look at data/course_1_full.json for an example of... | 625941e6b545ff76a891426c |
def construct_exemplar_sets(self, images, image_means, le_maps, image_bbs, m, cl, curr_iter, overwrite=False): <NEW_LINE> <INDENT> if image_bbs is None: <NEW_LINE> <INDENT> image_bbs = [None] * len(images) <NEW_LINE> <DEDENT> for c, image, le_map, image_bb in zip(cl, images, le_maps, image_bbs): <NEW_LINE> <INDENT> sel... | Construct exemplar sets for each class given images
Args:
images: list containing np.array of images for each class
image_means: cropped out parts of the dataset mean image for
image patches
le_maps: list containing np.array of learning exposure indices and
frame indices within... | 625941e6ab23a570cc2505dc |
def _group_url(self, group_id, sub_path=''): <NEW_LINE> <INDENT> egid = quote_plus(group_id) <NEW_LINE> if egid == '': <NEW_LINE> <INDENT> raise ValueError("Empty group ID given") <NEW_LINE> <DEDENT> return self._url('/groups/' + egid + sub_path) | Builds an endpoint URL for the given group and sub-path.
:param str group_id: a group identifier
:param str sub_path: additional sub-path
:returns: a complete URL
:rtype: str
:raises ValueError: if given an invalid group ID | 625941e6956e5f7376d712c2 |
def formatMapping(self, action): <NEW_LINE> <INDENT> mapping = self.__map.get(action) <NEW_LINE> if not mapping: <NEW_LINE> <INDENT> return "Unmapped" <NEW_LINE> <DEDENT> label = mapping[1].replace('_', ' ').title() <NEW_LINE> if mapping[0] == "axis": <NEW_LINE> <INDENT> return "Axis: " + label <NEW_LINE> <DEDENT> else... | Returns a string label describing the mapping for a given action,
for displaying in a GUI. | 625941e67b180e01f3dc4c4b |
def cosine_sentence_similarity(self): <NEW_LINE> <INDENT> import re, math <NEW_LINE> from collections import Counter <NEW_LINE> processor = TwitterKoreanProcessor() <NEW_LINE> def get_cosine(vec1, vec2): <NEW_LINE> <INDENT> intersection = set(vec1.keys()) & set(vec2.keys()) <NEW_LINE> numerator = sum([vec1[x] * vec2[x]... | http://stackoverflow.com/questions/15173225/how-to-calculate-cosine-similarity-given-2-sentence-strings-python
cosine similarity with pure python | 625941e6e64d504609d74c96 |
def load(paths=None): <NEW_LINE> <INDENT> if paths is None: <NEW_LINE> <INDENT> paths = {'A': '/home/newuser/code/cremi-resnet/data/test_like_training_all_augmentedA.h5'} <NEW_LINE> <DEDENT> print("path, ", paths.values()) <NEW_LINE> if not all([os.path.exists(path) for path in paths.values()]): <NEW_LINE> <INDENT> rai... | Load and reshape data from file. | 625941e6596a897236089f11 |
def __init__(self): <NEW_LINE> <INDENT> fig, self.axes = subplots() <NEW_LINE> self.axes.ticklabel_format(style="sci", scilimits=(0, 0)) <NEW_LINE> super().__init__(fig) <NEW_LINE> Toolbar(self, None).pan() | Initializes a CustomCanvas object with the following attributes:
axes: contains most of the figure elements ready to be
customized through various functions. Displays
scientific notation right from the start.
The `__init__` function is then called, representing the constructo... | 625941e6fbf16365ca6f6624 |
def getState(self): <NEW_LINE> <INDENT> return _pilot.Node_getState(self) | getState(Node self) -> YACS::StatesForNode | 625941e68e05c05ec3eea7cf |
def test_invalid_loopcnt_len(self): <NEW_LINE> <INDENT> with self.assertRaisesRegexp(ValueError, 'NestedLoopDesc: .*loopcnt.*'): <NEW_LINE> <INDENT> _ = NestedLoopDesc(loopcnt=(3, 8), usize_gbuf=(20, 30, 9), usize_regf=(3, 3, 1), unit_access=((19, 29, 9), (18, 28, 8), (35, 45, 15), (1, 1, 2)), data_loops=(DataDimLoops(... | Invalid loopcnt len. | 625941e663f4b57ef0001563 |
def raw_measure(self): <NEW_LINE> <INDENT> return self._run_profile(["raw_measure", [0x20, 0x50], 2, 0.025]) | Measure Raw Signals | 625941e6cc0a2c11143dd2e8 |
def compute_gab(g0a,g0b): <NEW_LINE> <INDENT> g0a_inv = inv(g0a) <NEW_LINE> gab = np.dot(g0a_inv,g0b) <NEW_LINE> return gab | Creates a rigid body transform g_{ab} the converts between frame A and B
given the coordinate frame A,B in relation to the origin
Args:
g0a - (4,4) ndarray : the rigid body transform from the origin to frame A
g0b - (4,4) ndarray : the rigid body transform from the origin to frame B
Returns:
gab - (4,4) ndarray : the... | 625941e629b78933be1e5afd |
def IsValid(self): <NEW_LINE> <INDENT> return _lldb.SBTraceOptions_IsValid(self) | IsValid(self) -> bool | 625941e615baa723493c43cf |
def savexmlas(self, event=None): <NEW_LINE> <INDENT> ok, name = self.gui.file_to_save() <NEW_LINE> if ok: <NEW_LINE> <INDENT> self.xmlfn = name <NEW_LINE> self.writexml() <NEW_LINE> self.gui.set_node_title(self.gui.top, self.xmlfn) <NEW_LINE> self.mark_dirty(False) <NEW_LINE> <DEDENT> return ok | ask for filename, then save | 625941e697e22403b379d3f2 |
def _AdjustColHeadings(colHeadings, maxColLabelLen): <NEW_LINE> <INDENT> for i in xrange(len(colHeadings)): <NEW_LINE> <INDENT> colHeadings[i] = colHeadings[i].strip() <NEW_LINE> colHeadings[i] = colHeadings[i].replace(' ', '_') <NEW_LINE> colHeadings[i] = colHeadings[i].replace('-', '_') <NEW_LINE> colHeadings[i] = co... | *For Internal Use*
removes illegal characters from column headings
and truncates those which are too long. | 625941e6cc0a2c11143dd2e9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.