language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static GISModel trainModel(int iterations, DataIndexer indexer) { return trainModel(iterations,indexer,true,false); }
java
public static <T> T find(Class<T> factoryClass, Descriptor descriptor, ClassLoader classLoader) { Preconditions.checkNotNull(descriptor); Preconditions.checkNotNull(classLoader); return findInternal(factoryClass, descriptor.toProperties(), Optional.of(classLoader)); }
java
@SuppressWarnings("unchecked") public SipServletRequest createAck() { final Response response = getResponse(); if(logger.isDebugEnabled()) { logger.debug("transaction " + getTransaction()); logger.debug("originalRequest " + originalRequest); } // transaction can be null in case of forking if(((getTrans...
python
def reflection_matrix_pow(reflection_matrix: np.ndarray, exponent: float): """Raises a matrix with two opposing eigenvalues to a power. Args: reflection_matrix: The matrix to raise to a power. exponent: The power to raise the matrix to. Returns: The given matrix raised to the given...
python
def _to_DOM(self): """ Dumps object data to a fully traversable DOM representation of the object. :returns: a ``xml.etree.Element`` object """ root_node = ET.Element("forecast") interval_node = ET.SubElement(root_node, "interval") interval_node.text = se...
java
public static double Digamma(double x) { double s = 0; double w = 0; double y = 0; double z = 0; double nz = 0; boolean negative = false; if (x <= 0.0) { negative = true; double q = x; double p = (int) Math.floor(q); ...
java
public boolean addEvent(Hook k, Event n) { Set<Event> l = events.get(k); if (l == null) { l = new HashSet<>(); events.put(k, l); } return l.add(n); }
python
def create_on_task(self, task, params={}, **options): """Adds a comment to a task. The comment will be authored by the currently authenticated user, and timestamped when the server receives the request. Returns the full record for the new story added to the task. Param...
python
def draw_sunpath(self, hoys=None, origin=None, scale=1, sun_scale=1, annual=True, rem_night=True): """Create sunpath geometry. \ This method should only be used from the + libraries. Args: hoys: An optional list of hours...
java
public Object newInstance(String clazz) { try { return Class.forName(clazz).newInstance(); } catch (Exception e) { error(e); return null; } }
java
public static LocalAttribute localAttribute(String name, String customGet, String customSet){ return new LocalAttribute(name, customGet, customSet); }
python
def _loads(s): """ Support decoding bytes. """ if isinstance(s, bytes): s = s.decode("utf-8") return pyjson.loads(s)
python
def create_network_configuration_files(self, file_path, guest_networks, first, active=False): """Generate network configuration files for guest vm :param list guest_networks: a list of network info for the guest. It has one dictionary that conta...
python
def load(self, file_parser, section_name): """The current element is loaded from the configuration file, all constraints and requirements are checked. Then element hooks are applied. """ self._load(file_parser, section_name) self.post_load()
python
def matrix(matrix, xlabel=None, ylabel=None, xticks=None, yticks=None, title=None, colorbar_shrink=0.5, color_map=None, show=None, save=None, ax=None): """Plot a matrix.""" if ax is None: ax = pl.gca() img = ax.imshow(matrix, cmap=color_map) if xlabel is not None: ax.set_xlabel(xla...
java
public org.tensorflow.framework.TensorShapeProto getTensorShape() { return tensorShape_ == null ? org.tensorflow.framework.TensorShapeProto.getDefaultInstance() : tensorShape_; }
python
def cursor(): """Database cursor generator. Commit on context exit.""" try: cur = conn.cursor() yield cur except (db.Error, Exception) as e: cur.close() if conn: conn.rollback() print(e.message) raise else: conn.commit() cur.clo...
java
public Observable<Service> addService(final AddServiceRequest request) { LOGGER.debug("Got instructed to add Service {}, to Node {}", request.type(), request.hostname()); return nodeBy(request.hostname()).addService(request); }
python
def BL(self, params): """ BL label Branch to the label, storing the next instruction in the Link Register """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # TODO check if label is within +- 16 MB ...
python
def _get_pkg_install_time(pkg, arch=None): ''' Return package install time, based on the /var/lib/dpkg/info/<package>.list :return: ''' iso_time = iso_time_t = None loc_root = '/var/lib/dpkg/info' if pkg is not None: locations = [] if arch is not None and arch != 'all': ...
python
def _ProcessFileEntry(self, mediator, file_entry): """Processes a file entry. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_entry (dfvfs.FileEntry): file entry. """ display_name = mediator.G...
python
def page_size(self) -> int: """ A property that returns how large a page is, calculated from the paginator properties. If this exceeds `max_page_size`, an exception is raised upon instantiation. """ page_count = self.page_count return self.paginator.max_size + len(f'\nPa...
python
def p_iteration_statement_4(self, p): """ iteration_statement \ : FOR LPAREN left_hand_side_expr IN expr RPAREN statement """ p[0] = ast.ForIn(item=p[3], iterable=p[5], statement=p[7])
java
private void resize() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "resize", table.length); Entry[] newTable = new Entry[table.length + (table.length / 2)]; /* We have to walk the entire SchemaSet, rehashing each Entry and putting */ /* it in its new home. A...
java
public static IdGenerator getInstance(long nodeId) { IdGenerator idGen = cache.get(nodeId); if (idGen == null) { idGen = new IdGenerator(nodeId); idGen.init(); IdGenerator existing = cache.putIfAbsent(nodeId, idGen); idGen = existing != null ? existing : i...
java
protected boolean isNotModified(Resource resource, SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException { // check resource's modification date against the If-Modified-Since header and send 304 if resource wasn't modified // never send expires header on author or publish ...
java
public PutLogEventsRequest withLogEvents(InputLogEvent... logEvents) { if (this.logEvents == null) { setLogEvents(new com.amazonaws.internal.SdkInternalList<InputLogEvent>(logEvents.length)); } for (InputLogEvent ele : logEvents) { this.logEvents.add(ele); } ...
java
private void addModulesArgument(final String argument, final List<String> arguments, final Module[] modules, final String aditionalpath, final String role) throws MojoExecutionException { StringBuilder buf = new StringBuilder(); if (null != aditionalpath)...
python
def parsing_token_generator(data_dir, tmp_dir, train, source_vocab_size, target_vocab_size): """Generator for parsing as a sequence-to-sequence task that uses tokens. This generator assumes the files parsing_{train,dev}.trees, which contain trees in WSJ format. Args: data_dir: ...
java
public boolean next() { boolean ret = false; if (this.iterator == null) { this.iterator = this.objects.iterator(); } if (this.iterator.hasNext()) { this.current = this.iterator.next(); ret = true; } return ret; }
python
def _construct(self): """ Construct a control dependence graph. This implementation is based on figure 6 of paper An Efficient Method of Computing Static Single Assignment Form by Ron Cytron, etc. """ self._acyclic_cfg = self._cfg.copy() # TODO: Cycle-removing i...
java
public void addAnnotations(/* @Nullable */ JvmAnnotationTarget target, /* @Nullable */ Iterable<? extends XAnnotation> annotations) { if(annotations == null || target == null) return; for (XAnnotation annotation : annotations) { addAnnotation(target, annotation); } }
python
def send_magic_packet(*macs, **kwargs): """ Wake up computers having any of the given mac addresses. Wake on lan must be enabled on the host device. Args: macs (str): One or more macaddresses of machines to wake. Keyword Args: ip_address (str): the ip address of the host to send t...
java
public static sslvserver[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{ sslvserver obj = new sslvserver(); options option = new options(); option.set_filter(filter); sslvserver[] response = (sslvserver[]) obj.getfiltered(service, option); return response; }
java
@Override public synchronized RecordTag insert(long historyId, String tag) throws DatabaseException { try { psInsertTag.setLong(1, historyId); psInsertTag.setString(2, tag); psInsertTag.executeUpdate(); try (ResultSet rs = psGetIdLastInsert.executeQuery()) { rs.next(); long id ...
python
def from_unit_cube(self, x): """ Used by multinest :param x: 0 < x < 1 :param lower_bound: :param upper_bound: :return: """ lower_bound = self.lower_bound.value upper_bound = self.upper_bound.value low = lower_bound spread = floa...
java
@Override public List<ProcessInstanceLog> findProcessInstances(String processId) { EntityManager em = getEntityManager(); Query query = em .createQuery("FROM ProcessInstanceLog p WHERE p.processId = :processId") .setParameter("processId", processId); ...
python
def get_site_dirs(): """ Return a list of 'site' dirs """ sitedirs = [] # start with PYTHONPATH sitedirs.extend(_pythonpath()) prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) for prefix in prefixes: if prefix: ...
java
public static String joinStrings( String separator, String... strings ) { if (separator == null) { separator = ""; } StringBuilder sb = new StringBuilder(); for( int i = 0; i < strings.length; i++ ) { sb.append(strings[i]); if (i < strings.length - 1) ...
python
def pipeline_summary(data): """Provide summary information on processing sample. Handles standard and CWL (single QC output) cases. """ data = utils.to_single_data(data) work_bam = dd.get_align_bam(data) or dd.get_work_bam(data) if not work_bam or not work_bam.endswith(".bam"): work_bam...
java
public PagedList<ResourceMetricInner> listWebWorkerMetrics(final String resourceGroupName, final String name, final String workerPoolName) { ServiceResponse<Page<ResourceMetricInner>> response = listWebWorkerMetricsSinglePageAsync(resourceGroupName, name, workerPoolName).toBlocking().single(); return ne...
java
Symbol accessBase(Symbol sym, DiagnosticPosition pos, Type site, Name name, boolean qualified) { return accessBase(sym, pos, site.tsym, site, name, qualified); }
python
def namespace(self): """ Get the attributes namespace. This may either be the namespace defined by an optional prefix, or its parent's namespace. @return: The attribute's namespace @rtype: (I{prefix}, I{name}) """ if self.prefix is None: return Namesp...
python
def get_engine_name(ec=None): """ Get the name of a engine or session """ ec = ec or __default_engine__ if isinstance(ec, (str, unicode)): return ec elif isinstance(ec, Session): return ec.engine_name else: raise Error("Parameter ec should be an engine_name or Session...
python
def to_ansi_24bit(self): """ Convert to ANSI 24-bit color format :return: """ text = self.text.replace('\x1b', '') if self.color and self.bg_color: c = self.color.scale(255) bg_c = self.bg_color.scale(255) return ansicolor(text, ...
python
def __get_by_fullname(self, asset_class, fullname: str): """ Recursive function """ if asset_class.fullname == fullname: return asset_class if not hasattr(asset_class, "classes"): return None for child in asset_class.classes: found = self.__get_by_fu...
java
@Nonnull public Class <?> loadClass (final String sClassName) throws ClassNotFoundException { if (m_aBestCandidate != null) { try { return m_aBestCandidate.loadClass (sClassName); } catch (final Throwable t) { m_aBestCandidate = null; } } Throwabl...
python
def iszero(computation: BaseComputation) -> None: """ Not """ value = computation.stack_pop(type_hint=constants.UINT256) if value == 0: result = 1 else: result = 0 computation.stack_push(result)
python
def choice(self, obj): """ Overloads the choice method to add the position of the object in the tree for future sorting. """ tree_id = getattr(obj, self.queryset.model._mptt_meta.tree_id_attr, 0) left = getattr(obj, self.queryset.model._mptt_meta.left_attr, 0) ret...
python
def execute_ssh(cls, command, *args, **kwargs): """execute_ssh(command, arguments..., pty=False, echo=False) Execute `command` on a remote server. It first calls :meth:`Flow.connect_ssh` using all positional and keyword arguments, then calls :meth:`SSHClient.execute` with the command ...
python
def nth(iterable, n, default=None): """Returns the nth item or a default value. Example:: >>> nth([0, 1, 2], 1) 1 >>> nth([0, 1, 2], 100) None **中文文档** 取出一个可循环对象中的第n个元素。等效于list(iterable)[n], 但占用极小的内存。 因为list(iterable)要将所有元素放在内存中并生成一个新列表。该方法常用语对于 那些取index操作被改写...
python
def kick_chat_member(self, *args, **kwargs): """See :func:`kick_chat_member`""" return kick_chat_member(*args, **self._merge_overrides(**kwargs)).run()
python
def warmup(self): """ initialize variables necessary to perform a sprinter action """ self.logger.debug("Warming up...") try: if not isinstance(self.source, Manifest) and self.source: self.source = load_manifest(self.source) if not isinstance(self.target,...
java
public HyperlinkListener createHyperLinkListener() { return new HyperlinkListener() { public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (e instanceof HTMLFrameHy...
python
def update_or_create(cls, external_gateway, name, with_status=False, **kw): """ Update or create external endpoints for the specified external gateway. An ExternalEndpoint is considered unique based on the IP address for the endpoint (you cannot add two external endpoints with the same I...
python
def printer(self): """Prints PDA state attributes""" print " ID " + repr(self.id) if self.type == 0: print " Tag: - " print " Start State - " elif self.type == 1: print " Push " + repr(self.sym) elif self.type == 2: print " Pop Stat...
java
public TypeResolver where(Type formal, Type actual) { Map<TypeVariableKey, Type> mappings = new HashMap<TypeVariableKey, Type>(); populateTypeMappings(mappings, formal, actual); return where(mappings); }
java
@Override public void heartbeat() throws InterruptedException { // skips replication in safe mode when not all workers are registered if (mSafeModeManager.isInSafeMode()) { return; } TimeUnit.SECONDS.sleep(mQuietPeriodSeconds); Set<Long> inodes; // Check the set of files that could pos...
java
public boolean addSourceFile(FileSystem fs, PolicyInfo info, FileStatus src, RaidState.Checker checker, long now, int targetReplication) throws IOException { RaidState state = checker.check(info, src, now, false); Counters counters = stateToSourceCounters.get(state); counters.inc(src); if (s...
java
public int getNumberOfParents() { BigInteger nrOfInlinks = new BigInteger("0"); long id = this.__getId(); Session session = this.wiki.__getHibernateSession(); session.beginTransaction(); Object returnValue = session.createNativeQuery("select count(inLinks) from category_inlinks ...
java
public void sendRecoveryTime(String path, long recoveryTime, String taskId) throws IOException { this.blockIntegrityMonitor.sendRecoveryTime(path, recoveryTime, taskId); }
java
@Override public void log(Level level, String msg, Object param1) { super.log(level, maskPassword(msg), param1); }
python
def find_path(start, goal, neighbors_fnct, reversePath=False, heuristic_cost_estimate_fnct=lambda a, b: Infinite, distance_between_fnct=lambda a, b: 1.0, is_goal_reached_fnct=lambda a, b: a == b): """A non-class version of the path finding algorithm""" class FindPath(AStar): def heuristic_cost_estimate...
java
@Override protected void onInitialize() { if (patterns == null && log.isWarnEnabled()) { // Log somewhat log.warn("No Patterns configured for AbstractPatternFilter [" + getClass().getName() + "]. " + "This could imply a configuration problem."); } else ...
java
private void translateCompositeId(final Object record, final EntityMetadata m, TranslationType type, MetamodelImpl metaModel, Map<String, StringBuilder> builders, Map<String, StringBuilder> columnBuilders, Map<String, Object> externalProperties, final KunderaMetadata kunderaMetadata, String tabl...
python
def flatten(iterable): """ flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). :param sequence: any object that implements iterable protocol (see: :ref:`typeiter`) :return: li...
python
def file_key_retire( blockchain_id, file_key, config_path=CONFIG_PATH, wallet_keys=None ): """ Retire the given key. Move it to the head of the old key bundle list @file_key should be data returned by file_key_lookup Return {'status': True} on success Return {'error': ...} on error """ con...
python
def remove(name, stop=False): ''' Remove the named container .. warning:: This function will remove all data associated with the container. It will not, however, remove the btrfs subvolumes created by pulling container images (:mod:`nspawn.pull_raw <salt.modules.nspawn.pull...
python
def trainer_results(trainer, mean=0, std=1, title='', show=True, save=True): """Plot the performance of the Network and SupervisedDataSet in a pybrain Trainer DataSet target and output values are denormalized before plotting with: output * std + mean Which inverses the normalization (out...
java
private int command_inout_asynch_i(final String c, final DeviceData[] dd, final boolean fgt, final boolean fwd, final int rid) throws DevFailed { synchronized (this) { final int gsize = get_size_i(fwd); if (gsize != dd.length) { final String desc = "the size of the input argument list must equal the n...
python
def _set_categories(self, categories, fastpath=False): """ Sets new categories inplace Parameters ---------- fastpath : bool, default False Don't perform validation of the categories for uniqueness or nulls Examples -------- >>> c = pd.Categor...
python
def make_bag(bag_dir, bag_info=None, processes=1, checksums=None, encoding='utf-8', remote_entries=None, spec_version="0.97"): """ Convert a given directory into a bag. You can pass in arbitrary key/value pairs to put into the bag...
java
private long[][] findDimensions(ArrayDBIDs medoids, Relation<V> database, DistanceQuery<V> distFunc, RangeQuery<V> rangeQuery) { // get localities DataStore<DBIDs> localities = getLocalities(medoids, distFunc, rangeQuery); // compute x_ij = avg distance from points in l_i to medoid m_i final int dim = ...
python
def _get_message(self, block=True, timeout=0.1, get_partition_info=None, update_offset=True): """ If no messages can be fetched, returns None. If get_partition_info is None, it defaults to self.partition_info If get_partition_info is True, returns (partition, message...
java
public static List<AbstractModule> getLocalStrictModules(final Class<? extends Nomenclature> nomenclatureClass) { checkNotNull(nomenclatureClass); return ImmutableList.of(new LocalStrictModule(), new CacheModule(), new IdModule(), new AbstractModule() { @Override protecte...
java
@Override public View getView(int position, View convertView, ViewGroup parent) { return (wrapped.getView(position, convertView, parent)); }
python
def hoverLeaveEvent(self, event): """ Processes the hovering information for this node. :param event | <QHoverEvent> """ if self._hoverSpot: if self._hoverSpot.hoverLeaveEvent(event): self.update() self._hoverSpot = None ...
python
def _session_check(self): """Attempt to authenticate the user through a session file. This process is done to avoid having to authenticate the user every single time. It uses a session file that is saved when a valid session is captured and then reused. Because sessions can expire, we n...
java
public void setEnumLiteral(EEnumLiteral newEnumLiteral) { EEnumLiteral oldEnumLiteral = enumLiteral; enumLiteral = newEnumLiteral; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, XtextPackage.ENUM_LITERAL_DECLARATION__ENUM_LITERAL, oldEnumLiteral, enumLiteral)); }
java
public static String getProperty(String property, String defValue) { try { return System.getProperty(property, defValue); } catch (SecurityException se) { return defValue; } }
python
def parse_match_info(self, req: Request, name: str, field: Field) -> typing.Any: """Pull a value from the request's ``match_info``.""" return core.get_value(req.match_info, name, field)
java
public TraceSummary withResponseTimeRootCauses(ResponseTimeRootCause... responseTimeRootCauses) { if (this.responseTimeRootCauses == null) { setResponseTimeRootCauses(new java.util.ArrayList<ResponseTimeRootCause>(responseTimeRootCauses.length)); } for (ResponseTimeRootCause ele : re...
java
private void allocateConnection() throws SQLException { if (m_connection == null) { m_connection = m_dataSource.getConnection(); m_allocatedConnection = true; queryDatabaseMetaData(); } }
python
def update_pass(user_id, newpass): ''' Update the password of a user. ''' out_dic = {'success': False, 'code': '00'} entry = TabMember.update(user_pass=tools.md5(newpass)).where(TabMember.uid == user_id) entry.execute() out_dic['success'] = True return...
java
public void setupSFields() { this.getRecord(Packages.PACKAGES_FILE).getField(Packages.SEQUENCE).setupDefaultView(this.getNextLocation(ScreenConstants.NEXT_LOGICAL, ScreenConstants.ANCHOR_DEFAULT), this, ScreenConstants.DEFAULT_DISPLAY); this.getRecord(Packages.PACKAGES_FILE).getField(Packages.NAME)....
java
public void load(String antecedent, Engine engine) { FuzzyLite.logger().log(Level.FINE, "Antecedent: {0}", antecedent); unload(); setText(antecedent); if (antecedent.trim().isEmpty()) { throw new RuntimeException("[syntax error] antecedent is empty"); } /* ...
java
public Matrix4x3d reflect(Vector3dc normal, Vector3dc point) { return reflect(normal.x(), normal.y(), normal.z(), point.x(), point.y(), point.z()); }
java
public Matrix4f m02(float m02) { this.m02 = m02; properties &= ~PROPERTY_ORTHONORMAL; if (m02 != 0.0f) properties &= ~(PROPERTY_IDENTITY | PROPERTY_PERSPECTIVE | PROPERTY_TRANSLATION); return this; }
java
public TaskResult add(String key, String value) { mBundle.putString(key, value); return this; }
java
public static InvocationHandlerAdapter toField(String name) { return toField(name, FieldLocator.ForClassHierarchy.Factory.INSTANCE); }
python
def create_multi_weather(df, rename_dc): """Create a list of oemof weather objects if the given geometry is a polygon """ weather_list = [] # Create a pandas.DataFrame with the time series of the weather data set # for each data set and append them to a list. for gid in df.gid.unique(): ...
python
def muscle(sequences=None, alignment_file=None, fasta=None, fmt='fasta', as_file=False, maxiters=None, diags=False, gap_open=None, gap_extend=None, muscle_bin=None): ''' Performs multiple sequence alignment with MUSCLE. Args: sequences (list): Sequences to be aligned. ``sequences`` can be ...
java
private void parseRenameFile(List<String> lines, URL url) { // format allows multiple [types] and [enums] so file can be merged boolean types = false; boolean enums = false; for (String line : lines) { try { if (line.equals("[types]")) { ty...
python
def jenkins_last_build_sha(): """ Returns the sha of the last completed jenkins build for this project. Expects JOB_URL in environment """ job_url = os.getenv('JOB_URL') job_json_url = "{0}/api/json".format(job_url) response = urllib.urlopen(job_json_url) ...
java
void printSaxException(String message, SAXException e) { System.err.println(); System.err.println("*** SAX Exception -- " + message); System.err.println(" SystemId = \"" + documentLocator.getSystemId() + "\""); e.printStackTrace(System.err); }
python
def get_previous_version(self): """Query GitHub releases to find the previous production release""" gh = self.get_github_api() repo = gh.repository(self.repo_owner, self.repo_name) most_recent = None for release in repo.releases(): # Return the second release that mat...
python
def load_diagram_from_csv(filepath, bpmn_diagram): """ Reads an CSV file from given filepath and maps it into inner representation of BPMN diagram. Returns an instance of BPMNDiagramGraph class. :param filepath: string with output filepath, :param bpmn_diagram: an instance of Bp...
java
@Override public ICompletableFuture<Void> forceDestroyCPGroup(String groupName) { return invocationManager.invoke(getMetadataGroupId(), new ForceDestroyRaftGroupOp(groupName)); }
python
def output(self): """ Produce a classic generator for this cell's final results. """ starters = self.finalize() try: yield from self._output(starters) finally: self.close()
python
def get_bot_mapping(self): """Retrieves the bot mapping passed to :meth:`send_bot_help`.""" bot = self.context.bot mapping = { cog: cog.get_commands() for cog in bot.cogs.values() } mapping[None] = [c for c in bot.all_commands.values() if c.cog is None] ...