language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public ActorComponent addActor() { //3 ActorComponent t = new ActorComponent(); if (this.actor == null) this.actor = new ArrayList<ActorComponent>(); this.actor.add(t); return t; }
java
public static void scale( double alpha , DMatrix5 a , DMatrix5 b ) { b.a1 = a.a1*alpha; b.a2 = a.a2*alpha; b.a3 = a.a3*alpha; b.a4 = a.a4*alpha; b.a5 = a.a5*alpha; }
java
@Override public CreateResponse createFlowConfig(FlowConfig flowConfig) throws FlowConfigLoggedException { String flowName = flowConfig.getId().getFlowName(); String flowGroup = flowConfig.getId().getFlowGroup(); checkHelixConnection(ServiceConfigKeys.HELIX_FLOWSPEC_ADD, flowName, flowGroup); ...
python
def is_ignored(self, event): """ :param event: :return: boolean """ for each in self._ignored: if event.name == each: return True return False
python
def get_simplex_solution_graph(self): ''' API: get_simplex_solution_graph(self): Description: Assumes a feasible flow solution stored in 'flow' attribute's of arcs. Returns the graph with arcs that have flow between 0 and capacity. Pre: ...
python
def delete(self, force=False, volumes=False, **kwargs): """ remove this container; kwargs indicate that some container runtimes might accept more parameters :param force: bool, if container engine supports this, force the functionality :param volumes: bool, remove also associate...
python
def _get_exception_log_path(): """Return the normalized path for the connection log, raising an exception if it can not written to. :return: str """ app = sys.argv[0].split('/')[-1] for exception_log in ['/var/log/%s.errors' % app, '/var/tm...
java
public RequestCtx makeRequestCtx(String request) throws MelcoeXacmlException { RequestCtx reqCtx = null; try { ByteArrayInputStream is = new ByteArrayInputStream(request.getBytes()); reqCtx = BasicRequestCtx.getInstance(is); } catch (Parsin...
python
def formfield_for_dbfield(self, db_field, **kwargs): """ Override the default widget for Foreignkey fields if they are specified in the related_search_fields class attribute. """ if isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields: ...
python
def loglevel(leveltype=None, isequal=False): """ Set or get the logging level of Quilt :type leveltype: string or integer :param leveltype: Choose the logging level. Possible choices are none (0), debug (10), info (20), warning (30), error (40) and critical (50). :type isequal: boolean :param ...
python
def query(self, jsonq, operator="and", count=False): """ returns a Django orm query from json input: { "app": "auth", "model": "User", "filters": { "is_superuser": False, "username__icontains": "foo" } """ model = self._get_...
java
@Deprecated public void bind(String name, Object value) { if (name2Index == null) { throw new RuntimeException("申明的绑定和代码里实际绑定不一致"); } Integer index = name2Index.get(name); if (index == null) { throw new RuntimeException("申明的绑定和代码里实际绑定不一致:试图绑定未申明的变量" + name); } ctx.vars[index] = value; }
java
public WellRestedRequest globalHeaders(Map<String, String> globalHeaders) { this.globalHeaders = WellRestedUtil.buildHeaders(globalHeaders); return this; }
python
def delete_pb_devices(): """Delete PBs devices from the Tango database.""" parser = argparse.ArgumentParser(description='Register PB devices.') parser.add_argument('num_pb', type=int, help='Number of PBs devices to register.') args = parser.parse_args() log = logging.getLogg...
java
private static void checkAttachmentPoint(Monomer mon, String str) throws AttachmentException { if (!(mon.getAttachmentListString().contains(str))) { if (!(str.equals("?") || str.equals("pair")) && !mon.getAlternateId().equals("?")) { LOG.info("Attachment point for source is not there"); throw new Attac...
python
def AddIndex(node, index=None): """ Recursively add the current index (with respect to a repeated section) in all data dictionaries. """ if isinstance(node, list): for i, item in enumerate(node): AddIndex(item, index=i) elif isinstance(node, dict): if index is not None: node['index'] = i...
java
private static DNASequence getDNASequence(String str) { try { DNASequence s = new DNASequence(str); return s; } catch (CompoundNotFoundException e) { logger.error("Unexpected error when creating DNASequence ",e); } return null; }
python
def patch_namespaced_network_policy(self, name, namespace, body, **kwargs): """ partially update the specified NetworkPolicy This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced...
java
public String getOrderedObjectName(ObjectName pName) { // For patterns we always return the canonical name if (pName.isPattern()) { return pName.getCanonicalName(); } if (getParameterAsBool(ConfigKey.CANONICAL_NAMING)) { return pName.getCanonicalName(); } ...
java
public Observable<ManagedClusterInner> updateTagsAsync(String resourceGroupName, String resourceName) { return updateTagsWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<ManagedClusterInner>, ManagedClusterInner>() { @Override public ManagedClusterI...
java
private synchronized String getMatchingURI(String incomingURI) { String[] incomingURIParts = incomingURI.split("/"); ArrayList<String[]> tockenizedEndpoints = new ArrayList<String[]>(); for (String endpointURI : serverEndpointConfigMap.keySet()) { // Since the endpoint paths are eit...
java
protected final int doSelect(Connection c) throws SQLException { Statement stmt = null; ResultSet rs = null; try { stmt = c.createStatement(); rs = stmt.executeQuery("select * from foo"); int count = 0; while (rs.next()) { count++; } return count; } finally { if (rs != null)...
java
@Override public StartEntitiesDetectionJobResult startEntitiesDetectionJob(StartEntitiesDetectionJobRequest request) { request = beforeClientExecution(request); return executeStartEntitiesDetectionJob(request); }
python
def unwind(self, path, include_array_index=None, preserve_null_and_empty_arrays=False): """ Adds an unwind stage to deconstruct an array :param path: Field path to an array field :param include_array_index: The name of a new field to hold the array index of the element. :param pr...
python
def expand_ipv6 (ip, num): """ Expand an IPv6 address with included :: to num octets. @raise: ValueError on invalid IP addresses """ i = ip.find("::") prefix = ip[:i] suffix = ip[i + 2:] count = prefix.count(":") + suffix.count(":") if prefix: count += 1 prefix = pre...
java
public CharacterFittingResponse postCharactersCharacterIdFittings(Integer characterId, String datasource, String token, CharacterFitting characterFitting) throws ApiException { ApiResponse<CharacterFittingResponse> resp = postCharactersCharacterIdFittingsWithHttpInfo(characterId, dat...
python
def extract(filepath, taxonomy, output_mode, output_limit, spires, match_mode, detect_author_keywords, extract_acronyms, rebuild_cache, only_core_tags, no_cache): """Run keyword extraction on given PDF file for given taxonomy.""" if not filepath or not taxonomy: print("No PDF fil...
java
public Issue createIssue(String name, Map<String, Object> attributes) { return getInstance().create().issue(name, this, attributes); }
java
private String getDatabaseProductName(WSDataSource dataSource) throws Exception { String dbProductName = dataSource.getDatabaseProductName(); if (dbProductName == null) { // Query the metadata under a new transaction and commit right away LocalTransactionCurrent localTranCurrent ...
python
def get_scss_files(self, skip_partials=True, with_source_path=False): """Gets all SCSS files in the source directory. :param bool skip_partials: If True, partials will be ignored. Otherwise, all SCSS files, including ones that begin ...
python
def font(self): """Font object controlling text format defaults for this chart.""" defRPr = ( self._chartSpace .get_or_add_txPr() .p_lst[0] .get_or_add_pPr() .get_or_add_defRPr() ) return Font(defRPr)
python
def make_axis_dummies(frame, axis='minor', transform=None): """ Construct 1-0 dummy variables corresponding to designated axis labels Parameters ---------- frame : DataFrame axis : {'major', 'minor'}, default 'minor' transform : function, default None Function to apply to axis l...
java
private static boolean isGeneratedFactoryType(ClassSymbol symbol, VisitorState state) { // TODO(ronshapiro): check annotation creators, inaccessible map key proxies, or inaccessible // module constructor proxies? return GENERATED_BASE_TYPES.stream() .anyMatch(baseType -> isGeneratedBaseType(symbol, ...
python
def persist(self, name): """ clear any expiration TTL set on the object :param name: str the name of the redis key :return: Future() """ with self.pipe as pipe: return pipe.persist(self.redis_key(name))
python
def ptmsiReallocationComplete(): """P-TMSI REALLOCATION COMPLETE Section 9.4.8""" a = TpPd(pd=0x3) b = MessageType(mesType=0x11) # 00010001 packet = a / b return packet
python
def deserialize(cls, value, *args, **kwargs): """Deserialize a value just after importing it `cls.deserialize` should always return a value of type `cls.TYPE` or `None`. """ if isinstance(value, cls.TYPE): return value elif is_null(value): return...
java
public <T> HystrixRequestVariable<T> getRequestVariable(final HystrixRequestVariableLifecycle<T> rv) { return new HystrixLifecycleForwardingRequestVariable<T>(rv); }
python
def handle_attached(sender, device): """ Handles attached events from USBDevice.start_detection(). """ # Create the device from the specified device arguments. dev = create_device(device) __devices[dev.id] = dev print('attached', dev.id)
python
def _recursive_getitem(d, key): """ Descend into a dict of dicts to return the one that contains a given key. Every value in the dict must be another dict. """ if key in d: return d else: for v in d.values(): return _recursive_getitem(v, key) else: ...
python
def streaming_op(name, labels, predictions, num_thresholds=None, weights=None, metrics_collections=None, updates_collections=None, display_name=None, description=None): """Computes a...
java
MolgenisValidationException translateForeignKeyViolation(PSQLException pSqlException) { ServerErrorMessage serverErrorMessage = pSqlException.getServerErrorMessage(); String tableName = serverErrorMessage.getTable(); String detailMessage = serverErrorMessage.getDetail(); Matcher m = Pattern.compile("\\(...
java
private void closeFileChannel() { try { if (this.databaseIndexCache != null) { this.databaseIndexCache.destroy(); } if (this.inputChannel != null) { this.inputChannel.close(); } } catch (Exception e) { LOGGER.log...
python
def com(self): """Center of mass, calculated from the mean of the PMT positions""" if self._com is None: self._com = np.mean(self.pmts.pos, axis=0) return self._com
java
public static <T> Set<Set<T>> combinations(Set<T> elements, int subsetSize) { return combinationsStream(elements, subsetSize).collect(Collectors.toSet()); }
python
def _addToBuffers(self, logname, data): """ Add data to the buffer for logname Start a timer to send the buffers if BUFFER_TIMEOUT elapses. If adding data causes the buffer size to grow beyond BUFFER_SIZE, then the buffers will be sent. """ n = len(data) ...
java
private String emitInnerTypes() { StringBuilder itDefs = new StringBuilder(); while(emittedInnerTypes.size() < innerTypes.size()) { for (Pair<StructureDefinition, ElementDefinition> it : new HashSet<Pair<StructureDefinition, ElementDefinition>>(innerTypes)) { if (!emittedInnerTypes.contains(it...
java
public static BulkheadMetrics ofBulkheadRegistry(String prefix, BulkheadRegistry bulkheadRegistry) { return new BulkheadMetrics(prefix, bulkheadRegistry.getAllBulkheads()); }
java
public void prepareStep8b() { if (!isInitialized()) { return; } if ((m_workplaceImportThread != null) && (m_workplaceImportThread.isFinished())) { // setup is already finished, just wait for client to collect final data return; } if (m_workp...
java
@Override public void handle(RequestContext context) throws SecurityProviderException, IOException { RedirectUtils.redirect(context.getRequest(), context.getResponse(), getTargetUrl()); }
java
public void actionReport() throws JspException { // save initialized instance of this class in request attribute for included sub-elements getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, this); switch (getAction()) { case ACTION_REPORT_UPDATE: setParamAct...
python
def log_entries_in_range(entries, start, end): '''filter out entries before start and after end''' start = _timestamp_from_string(start) end = _timestamp_from_string(end) for entry in entries: log_timestamp = entry.get('timestamp', 0) if log_timestamp >= start and log_timestamp <= end: ...
python
def parse_form_request(api_secret, request): """ >>> parse_form_request("123456",{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"}) <Storage {'nonce': 1451122677, 'msg': 'helllo', 'code': 0, 'sign': 'DB30F4D1112C20DFA736F65458F89C64'}> """ if not c...
python
def load(self, path): """ Load and return the corpus from the given path. Args: path (str): Path to the data set to load. Returns: Corpus: The loaded corpus Raises: IOError: When the data set is invalid, for example because required files (a...
python
def selection(self): """A complete |Selection| object of all "supplying" and "routing" elements and required nodes. >>> from hydpy import RiverBasinNumbers2Selection >>> rbns2s = RiverBasinNumbers2Selection( ... (111, 113, 1129, 11269, 1125, 11261, ...
python
def isPartitionMarkedForEvent(self, db_name, tbl_name, part_vals, eventType): """ Parameters: - db_name - tbl_name - part_vals - eventType """ self.send_isPartitionMarkedForEvent(db_name, tbl_name, part_vals, eventType) return self.recv_isPartitionMarkedForEvent()
python
def hashtag_links(uri, s): """ Turns hashtag-like strings into HTML links @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |#|hashtags in -> #str HTML link |<a href="/uri/hashtag">hashtag</a>| """ for tag, after in hashtag_re.findall(s): _uri = '...
java
public static double round(double value, int decimals, RoundingMode roundingMode) { if (decimals < 0) { throw new IllegalArgumentException("Invalid number of decimal places"); } BigDecimal bd = new BigDecimal(value); return bd.setScale(decimals, roundingMode).doubleValue(); }
python
def calldata(vcf_fn, region=None, samples=None, ploidy=2, fields=None, exclude_fields=None, dtypes=None, arities=None, fills=None, vcf_types=None, count=None, progress=0, logstream=None, condition=None, slice_args=None, verbose=True, cache=False, cachedir=None, skip_c...
python
def check_off_chain_batch_roles(self, batch): """ Check the batch signing key against the allowed off-chain transactor permissions. The roles being checked are the following, from first to last: "transactor.batch_signer" "transactor" The first...
java
public static <T> Method[] getAllMethodsExcept(Class<T> type, String methodNameToExclude, Class<?>[] argumentTypes) { Method[] methods = getAllMethods(type); List<Method> methodList = new ArrayList<Method>(); outer: for (Method method : methods) { if (method.getName().equals(...
python
def _convert_folded_blocks(folded_ir_blocks): """Convert Filter/Traverse blocks and LocalField expressions within @fold to Gremlin objects.""" new_folded_ir_blocks = [] def folded_context_visitor(expression): """Transform LocalField objects into their Gremlin-specific counterpart.""" if not...
java
public void apply(Matrix H, int column, int i1, int i2) { double temp = c * H.get(i1, column) + s * H.get(i2, column); H.set(i2, column, -s * H.get(i1, column) + c * H.get(i2, column)); H.set(i1, column, temp); }
java
public Duration minusMinutes(long minutesToSubtract) { return (minutesToSubtract == Long.MIN_VALUE ? plusMinutes(Long.MAX_VALUE).plusMinutes(1) : plusMinutes(-minutesToSubtract)); }
python
def split_batches(self, data, minibatch_size= None): """Split data into minibatches with a specified size Parameters ---------- data: iterable and indexable List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames. minibatch_size: int Expected sizes of minibatc...
java
@Override public void run() { super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { @Override public void onMissionAccomplished(final Subject subject) { DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { ...
java
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Only if we have no state if (mCurrentPath == null) { if (savedInstanceState != null) { mode = savedInstanceState.getInt(KEY_MODE, mode); ...
java
public Ids pushMessages(String[] msg, long delay) throws IOException { ArrayList<Message> messages = new ArrayList<Message>(); for (String messageName: msg){ Message message = new Message(); message.setBody(messageName); message.setDelay(delay); messages.a...
java
private String getFormattedDate(int dateTimeFormat) { DateFormat df; String result; if (isWholeDay()) { df = DateFormat.getDateInstance(dateTimeFormat, m_series.getLocale()); result = df.format(getStart()); if (getLastDay().after(getStart())) { ...
java
public String simpleTypeName() { String typeName = qualifiedTypeName(); int lastDot = typeName.lastIndexOf('.'); if (lastDot < 0) return typeName; return typeName.substring(lastDot + 1); }
python
def run_information(self): """Basic information about this run.""" run_information = self.run_info.get_as_dict() target_data = run_information.get('target_data', None) if target_data: run_information['target_data'] = ast.literal_eval(target_data) return run_information
python
def start(self, listen_ip=LISTEN_IP, listen_port=0): """Start discovery task.""" coro = self.loop.create_datagram_endpoint( lambda: self, local_addr=(listen_ip, listen_port)) self.task = self.loop.create_task(coro) return self.task
python
def supervisor(self): """Return an authenticated connection for use, open new if required. Returns: SupervisorWebService: New or existing session with the Five9 Statistics API. """ supervisor = self._cached_client('supervisor') if not self._api_supervisor...
java
public static boolean isUncommitted(Transaction tx) { if (tx == null) return false; try { int status = tx.getStatus(); return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK; } catch (SystemException error) { th...
java
private void process(String tebase) { deleteConfigFile(tebase); docMain = builder.newDocument(); config = docMain.createElement("config"); docMain.appendChild(config); scripts = docMain.createElement("scripts"); config.appendChild(scripts); String scriptsDir = tebase + "scripts"; LOGR.info("Scripts dire...
python
def _elimination_trees(theta, decision_variables): """From Theta and the decision variables, determine the elimination order and the induced trees. """ # auxiliary variables are any variables that are not decision auxiliary_variables = set(n for n in theta.linear if n not in decision_variables) ...
python
def rmdir(self, paths): ''' Delete a directory :param paths: Paths to delete :type paths: list :returns: a generator that yields dictionaries .. note: directories have to be empty. ''' if not isinstance(paths, list): raise InvalidInputException("Path...
python
def VerifyStructure(self, parser_mediator, line): """Verify that this file is a Mac Wifi log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. line (str): line from a text file. Returns: bool: Tr...
java
public void setMinorTickMarksVisible(final boolean VISIBLE) { if (null == minorTickMarksVisible) { _minorTickMarksVisible = VISIBLE; fireUpdateEvent(REDRAW_EVENT); } else { minorTickMarksVisible.set(VISIBLE); } }
python
def parse_datetime(record: str) -> Optional[datetime]: """ Parse a datetime string into a python datetime object """ # NEM defines Date8, DateTime12 and DateTime14 format_strings = {8: '%Y%m%d', 12: '%Y%m%d%H%M', 14: '%Y%m%d%H%M%S'} if record == '': return None return datetime.strptime(recor...
java
public static void main(String[] args) { EnvironmentInformation.logEnvironmentInfo(LOG, "YARN TaskExecutor runner", args); SignalHandler.register(LOG); JvmShutdownSafeguard.installAsShutdownHook(LOG); run(args); }
python
def parameterize(string, separator='-'): """ Replace special characters in a string so that it may be used as part of a 'pretty' URL. Example:: >>> parameterize(u"Donald E. Knuth") 'donald-e-knuth' """ string = transliterate(string) # Turn unwanted chars into the separator...
java
public JSONObject toJSONObject( JSONArray names ) { if( names == null || names.size() == 0 || size() == 0 ){ return null; } JSONObject jo = new JSONObject(); for( int i = 0; i < names.size(); i++ ){ jo.element( names.getString( i ), this.opt( i ) ); } return jo; ...
python
def adapter_add_nio_binding(self, adapter_number, port_number, nio): """ Adds a adapter NIO binding. :param adapter_number: adapter number :param port_number: port number :param nio: NIO instance to add to the adapter/port """ try: adapter = self._ad...
python
def cli(env, sortby, datacenter): """List number of block storage volumes per datacenter.""" block_manager = SoftLayer.BlockStorageManager(env.client) mask = "mask[serviceResource[datacenter[name]],"\ "replicationPartners[serviceResource[datacenter[name]]]]" block_volumes = block_manager.list...
python
def cleanup_email_addresses(request, addresses): """ Takes a list of EmailAddress instances and cleans it up, making sure only valid ones remain, without multiple primaries etc. Order is important: e.g. if multiple primary e-mail addresses exist, the first one encountered will be kept as primary. ...
java
@Override public final int delete(int handle) throws DataStoreException { if (SAFE_MODE) checkHandle(handle); int previousHandle = previousBlock[handle]; int current = handle; int nextHandle = -1; while (current != -1) { nextHandle = n...
python
def get_hierarchies(self): """Pass through to provider HierarchyLookupSession.get_hierarchies""" # Implemented from kitosid template for - # osid.resource.BinLookupSession.get_bins_template catalogs = self._get_provider_session('hierarchy_lookup_session').get_hierarchies() cat_li...
java
public static <A, S, C extends Comparable<C>, N extends CostNode<A, S, C, N>> BellmanFord<A, S, C, N> createBellmanFord( SearchProblem<A, S, N> components) { return new BellmanFord<A, S, C, N>(components.getInitialNode(), components.getExpander()); }
python
def win_verify_env( path, dirs, permissive=False, pki_dir='', skip_extra=False): ''' Verify that the named directories are in place and that the environment can shake the salt ''' import salt.utils.win_functions import salt.utils.win_dacl import salt.u...
java
public static <S, O> Transition<S, O> to(S newState, Stream<O> outputs) { return new Transition<>(newState, outputs); }
java
private int findElementOrRemoved(int element) { assert element >= 0; int index = toIndex(IntHashCode.hashCode(element)); int offset = 1; int removed = -1; while (cells[index] != EMPTY) { // element found! if (cells[index] == element) { return index; } ...
java
public static Double asDouble(String expression, Node node) throws XPathExpressionException { return asDouble(expression, node, xpath()); }
java
public void setDatapoints(java.util.Collection<Datapoint> datapoints) { if (datapoints == null) { this.datapoints = null; return; } this.datapoints = new java.util.ArrayList<Datapoint>(datapoints); }
python
def getAppExt(self, loops=float('inf')): """ getAppExt(loops=float('inf')) Application extention. This part specifies the amount of loops. If loops is 0 or inf, it goes on infinitely. """ if loops == 0 or loops == float('inf'): loops = 2 ** 16 - 1 # bb ...
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "extension", scope = CreateDocumentResponse.class) public JAXBElement<CmisExtensionType> createCreateDocumentResponseExtension( CmisExtensionType value) { return new JAXBElement<CmisExtensionType>( _GetPropertiesExt...
java
@InterfaceAudience.Private public void pullRemoteRevision(final RevisionInternal rev) { Log.d(TAG, "%s: pullRemoteRevision with rev: %s", this, rev); ++httpConnectionCount; // Construct a query. We want the revision history, and the bodies of attachments that have // been added si...
java
private void writeLibraryToStreamInternal(final String libraryFileName, final DataOutput out) throws IOException { if (libraryFileName == null) { throw new IOException("libraryName is null!"); } final Path storePath = new Path(this.libraryCachePath + "/" + libraryFileName); synchronized (this.fs) { if...
python
def create_missing(self): """Automagically populate all required instance attributes. Iterate through the set of all required class :class:`nailgun.entity_fields.Field` defined on ``type(self)`` and create a corresponding instance attribute if none exists. Subclasses should over...
java
public BUILDER setStorageRuntime() { removeFlag(AttributeAccess.Flag.STORAGE_CONFIGURATION); return addFlag(AttributeAccess.Flag.STORAGE_RUNTIME); }
java
private void newTodo(Event event) { if (Key.Enter.match(event)) { String text = newTodo.value.trim(); if (text.length() != 0) { TodoItem item = repository.add(text); list.appendChild(new TodoItemElement(this, repository, item).element()); n...