language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static String[] tokenize(String input, boolean lowercase) { String[] tokens = input.split("\\W"); // lower case for (int i = 0; i < tokens.length && lowercase; i++) { tokens[i] = tokens[i].toLowerCase(); } return tokens; }
java
@Override public void runReport(Map<String, Object> extra) { try { rows = new ArrayList<Map<String, Object>>(); Script script = groovyShell.parse(groovyScript); script.setBinding(new Binding()); script.getBinding().setVariable("rows", rows); ...
java
public static int importData(final DataSet dataset, final Collection<String> selectColumnNames, final int offset, final int count, final PreparedStatement stmt) throws UncheckedSQLException { return importData(dataset, selectColumnNames, offset, count, stmt, 200, 0); }
python
def create_external_store(self, project_name, config): """ create log store Unsuccessful opertaion will cause an LogException. :type project_name: string :param project_name: the Project name :type config : ExternalStoreConfig :param config :external store con...
java
public static Element declareInstance(ComponentWorkbench workbench) { Element instance = new Element("instance", ""); instance.addAttribute(new Attribute(COMPONENT, workbench.getType().getClassName())); return instance; }
java
public void applyCommandLineOptions(CommandLine cli, T embeddedGobblin) { try { for (Option option : cli.getOptions()) { if (!this.methodsMap.containsKey(option.getOpt())) { // Option added by cli driver itself. continue; } if (option.hasArg()) { this.meth...
python
def reverse_url(self, scheme: str, path: str) -> str: """ Reverses the url using scheme and path given in parameter. :param scheme: Scheme of the url :param path: Path of the url :return: """ # remove starting slash in path if present path = path.lstrip('...
python
def _get_link_status_code(link, allow_redirects=False, timeout=5): """ Get the status code of a link. If the timeout is exceeded, will return a 404. For a list of available status codes, see: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes """ status_code = None try: ...
python
def get_proficiencies_by_query(self, proficiency_query): """Gets a list of ``Proficiencies`` matching the given proficiency query. arg: proficiency_query (osid.learning.ProficiencyQuery): the proficiency query return: (osid.learning.ProficiencyList) - the returned ...
python
def intrinsic_variables(xmrs): """Return the list of all intrinsic variables in *xmrs*""" ivs = set( ep.intrinsic_variable for ep in xmrs.eps() if not ep.is_quantifier() and ep.intrinsic_variable is not None ) return sorted(ivs, key=var_id)
java
private static ResultPoint[] expandSquare(ResultPoint[] cornerPoints, int oldSide, int newSide) { float ratio = newSide / (2.0f * oldSide); float dx = cornerPoints[0].getX() - cornerPoints[2].getX(); float dy = cornerPoints[0].getY() - cornerPoints[2].getY(); float centerx = (cornerPoints[0].getX() + co...
java
public static String getChannelName(String eventName) { return eventName == null ? null : EVENT_PREFIX + eventName.split("\\.", 2)[0]; }
python
def __get_size_and_entry_point(self): "Get the size and entry point of the module using the Win32 API." process = self.get_process() if process: try: handle = process.get_handle( win32.PROCESS_VM_READ | win32.PROCESS_QUERY_...
java
public static String dumpCursorToString(Cursor cursor) { StringBuilder sb = new StringBuilder(); dumpCursor(cursor, sb); return sb.toString(); }
python
def addLocation(self, locationUri, weight): """ add relevant location to the topic page @param locationUri: uri of the location to add @param weight: importance of the provided location (typically in range 1 - 50) """ assert isinstance(weight, (float, int)), "weight value...
java
Observable<ComapiResult<MessagesQueryResponse>> processOrphanedEvents(ComapiResult<MessagesQueryResponse> result, final ChatController.OrphanedEventsToRemoveListener removeListener) { if (result.isSuccessful() && result.getResult() != null) { final MessagesQueryResponse response = result.getResult...
java
public PowerFormsFormDataResponse getPowerFormData(String accountId, String powerFormId, PowerFormsApi.GetPowerFormDataOptions options) throws ApiException { Object localVarPostBody = "{}"; // verify the required parameter 'accountId' is set if (accountId == null) { throw new ApiException(400...
java
protected CmsObject rootCms(CmsObject cms) throws CmsException { CmsObject result = OpenCms.initCmsObject(cms); result.getRequestContext().setSiteRoot(""); return result; }
python
def _pair_stale(self, pair): """ Returns true of the (connection,time) pair is too old to be used. """ (_conn, return_time) = pair now = time.time() return return_time + ConnectionPool.STALE_DURATION < now
java
public MemberConfig setId(String id) { return setId(id != null ? MemberId.from(id) : null); }
java
protected static <T> T getTracer(Class<T> intf, InterfaceTracer tracer, T ob) { tracer.setAppendable(System.err); tracer.setObj(ob); return (T) Proxy.newProxyInstance( intf.getClassLoader(), new Class<?>[] {intf}, tracer); }
java
@Override public DeleteSlotTypeVersionResult deleteSlotTypeVersion(DeleteSlotTypeVersionRequest request) { request = beforeClientExecution(request); return executeDeleteSlotTypeVersion(request); }
python
def allow_rwe(self, name): """Allow all privileges for a particular name group (user, group, other).""" assert name in PERMISSIONS.keys() os.chmod(self.file_path, PERMISSIONS[name]['all'])
python
def get_parent(self, refobj): """Return the parent of the given :class:`JB_ReftrackNode`. :param refobj: a reftrack node to query :type refobj: str :returns: the parent reftrack node :rtype: refobj | None :raises: None """ c = cmds.listConnections("%s.par...
java
static String dateToStrTs(long dateMs) { SimpleDateFormat df = new SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss.SSS"); return df.format(new Date(dateMs)); }
python
def ipostorder(self): '''Depth-first post-order iteration of tree nodes''' children = [self, ] seen = set() while children: cur_node = children[-1] if cur_node not in seen: seen.add(cur_node) children.extend(reversed(cur_node.childr...
java
public void writeRawLittleEndian32(final int value) throws IOException { writeRawByte((value ) & 0xFF); writeRawByte((value >> 8) & 0xFF); writeRawByte((value >> 16) & 0xFF); writeRawByte((value >> 24) & 0xFF); }
java
private void resetXAResourceTimeout() { // Do a reset of the underlying XAResource timeout if (!(xaResource instanceof LocalXAResource) && xaResourceTimeout > 0) { try { xaResource.setTransactionTimeout(xaResourceTimeout); } catch (XAException e) ...
python
def _parse_entities(self): """enrich the babelfied data with the text an the isEntity items set self._entities with the enriched data """ entities = list() for result in self._data: entity = dict() char_fragment = result.get('charFragment') st...
java
public static DocumentFragment readXMLFragment(String file) throws IOException, SAXException, ParserConfigurationException { return readXMLFragment(file, false); }
java
public void put(String hostname, int netId, InetAddress[] addresses) { cache.put(new AddressCacheKey(hostname, netId), new AddressCacheEntry(addresses)); }
python
def _CheckKeyPath(self, registry_key, search_depth): """Checks the key path find specification. Args: registry_key (WinRegistryKey): Windows Registry key. search_depth (int): number of key path segments to compare. Returns: bool: True if the Windows Registry key matches the find specific...
python
def get_files_for_vetoes(workflow, out_dir, runtime_names=None, in_workflow_names=None, tags=None): """ Get the various sets of veto segments that will be used in this analysis. Parameters ----------- workflow : Workflow object Instance of the workflow object ou...
python
def ParseLSQuarantineRow( self, parser_mediator, query, row, **unused_kwargs): """Parses a launch services quarantine event row. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. query (str): query that cre...
python
def _example_rt_ticker(quote_ctx): """ 获取逐笔,输出 股票代码,时间,价格,成交量,成交金额,暂时没什么意义的序列号 """ stock_code_list = ["HK.00700", "US.AAPL"] # subscribe "TICKER" ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.TICKER) if ret_status != ft.RET_OK: print(ret_data) exit()...
python
def write( structure, name=None ): """ Writes a Structure in PDB format through PDBIO. Simplifies life.. """ from Bio.PDB import PDBIO io = PDBIO() io.set_structure(structure) if not name: s_name = structure.id else: s_name = name name = "%s.p...
python
def validate_seeded_answers(answers, options, algo): """ Validate answers based on selection algorithm This is called when instructor setup the tool and providing seeded answers to the question. This function is trying to validate if instructor provided enough seeds for a give algorithm. e.g. we re...
java
@Override public Tile retrieveTile(int x, int y, int zoom) { GeoPackageTile geoPackageTile = retriever.getTile(x, y, zoom); Tile tile = GeoPackageOverlayFactory.getTile(geoPackageTile); return tile; }
java
@Override protected void initGraphics() { super.initGraphics(); //poiLocations = FXCollections.observableHashMap(); //chartDataLocations = FXCollections.observableHashMap(); //circleHandlerMap = new HashMap<>(); country = tile.getCountry(); if (null == country)...
python
def send(self, content=None, *, wait=False, username=None, avatar_url=None, tts=False, file=None, files=None, embed=None, embeds=None): """|maybecoro| Sends a message using the webhook. If the webhook is constructed with a :class:`RequestsWebhookAdapter` the...
java
static <K, V> void nullifyEvictable(ReferenceEntry<K, V> nulled) { ReferenceEntry<K, V> nullEntry = nullEntry(); nulled.setNextEvictable(nullEntry); nulled.setPreviousEvictable(nullEntry); }
java
@Override public synchronized ChainData[] getRunningChains() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "getRunningChains"); } ChainData chainDataArray[] = new ChainData[chainRunningMap.size()]; ChainDataImpl chainData = null; ...
java
public void useNewRESTService(String address) throws Exception { List<Object> providers = createJAXRSProviders(); org.customer.service.CustomerService customerService = JAXRSClientFactory .createFromModel(address, org.customer.service.CustomerService.class, ...
java
private String getParameterJSDocType(List<JSType> types, int index, int minArgs, int maxArgs) { JSType type = types.get(index); if (index < minArgs) { return type.toAnnotationString(Nullability.EXPLICIT); } boolean isRestArgument = maxArgs == Integer.MAX_VALUE && index == types.size() - 1; if ...
python
def build_vocab(self, *args, **kwargs): """Construct the Vocab object for nesting field and combine it with this field's vocab. Arguments: Positional arguments: Dataset objects or other iterable data sources from which to construct the Vocab object that repre...
java
@Override public boolean setA(DMatrixRMaj A) { if( A.numRows > maxRows || A.numCols > maxCols ) { setMaxSize(A.numRows,A.numCols); } _setA(A); if( !decomposer.decompose(A) ) return false; Q.reshape(numRows,numRows, false); R.reshape(numRows,n...
java
public List<JsonDelta> computeDiff(String node1, String node2) throws IOException { ObjectMapper mapper = new ObjectMapper(); return computeDiff(mapper.readTree(node1), mapper.readTree(node2)); }
java
public static View getCenterXChild(RecyclerView recyclerView) { int childCount = recyclerView.getChildCount(); for (int i = 0; i < childCount; i++) { View child = recyclerView.getChildAt(i); if (isChildInCenterX(recyclerView, child)) { return child; } ...
java
@Override @NullSafe public boolean accept(File pathname) { return (pathname != null && pathname.isHidden() == hidden); }
java
public static List<Field> getColumns(Class<?> clazz) throws NoColumnAnnotationException { if(clazz == null) { throw new NoColumnAnnotationException("class is null"); } List<Field> result = _getAnnotationColumns(clazz, Column.class); if (result.isEmpty()) { throw new NoColumnAnnotationException("cla...
python
def from_search_query(self, search_query): """ Return queryset of objects from SearchQuery.results, **in order**. EXPERIMENTAL: this will only work with results from a single index, with a single doc_type - as we are returning a single QuerySet. This method takes the hits JSON ...
java
@Override public void sawOpcode(int seen) { if (seen != Const.INVOKESPECIAL) { return; } String calledClassName = getClassConstantOperand(); String calledMethodName = getNameConstantOperand(); String calledMethodSig = getSigConstantOperand(); if (calledCl...
python
def create_apirack(self): """Get an instance of Api Rack Variables services facade.""" return ApiRack( self.networkapi_url, self.user, self.password, self.user_ldap)
java
public void marshall(DescribeGroupsRequest describeGroupsRequest, ProtocolMarshaller protocolMarshaller) { if (describeGroupsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeGroupsRe...
python
def interval( value=None, unit='s', years=None, quarters=None, months=None, weeks=None, days=None, hours=None, minutes=None, seconds=None, milliseconds=None, microseconds=None, nanoseconds=None, ): """ Returns an interval literal Parameters ----------...
java
public double[][] inverse() { // Build permuted identity matrix efficiently: double[][] b = new double[piv.length][m]; for(int i = 0; i < piv.length; i++) { b[piv[i]][i] = 1.; } return solveInplace(b); }
java
public void moveMessages(boolean discard) throws SIMPRuntimeOperationFailedException, SIMPControllableNotFoundException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "deleteAllQueuedMessages", new Boolean(discard)); assertValidControllable(); SIMPRuntimeOpe...
python
def get_version(): """ Simple function to extract the current version using regular expressions. """ reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') with open('requests_kerberos/__init__.py') as fd: matches = list(filter(lambda x: x, map(reg.match, fd))) if not matches: r...
java
public void setGroupList(java.util.Collection<Group> groupList) { if (groupList == null) { this.groupList = null; return; } this.groupList = new java.util.ArrayList<Group>(groupList); }
python
def resize_lazy(image, width=None, height=None, crop=False, force=False, namespace="resized", storage=default_storage, as_url=False): """ Returns the name of the resized file. Returns the url if as_url is True """ # First normalize params to determine which file to get ...
java
public static void main(String[] pstrArgs) { IniFile objINI = null; String strFile = null; if (pstrArgs.length == 0) return; strFile = pstrArgs[0]; // Following call will load the strFile if one exists. objINI = new IniFile(strFile); // objINI.a...
java
public static Map<String, Object> convert(Object pojo, Class<? extends Annotation> annotationType, boolean hasNull) { log.debug("获取[{}]的字段映射,使用注解[{}]的值作为别名", pojo, annotationType); Assert.notNull(pojo, "pojo不能为nu...
java
public static String validateIndexName(@Nullable String indexName) { requireNonNull(indexName, "Index name cannot be null"); checkDbIdentifier(indexName, "Index name", INDEX_NAME_MAX_SIZE); return indexName; }
java
public static void whenReady(final EventListener function) { WebshimResources.eventLisenerQueue.add(function); if (WebshimResources.initializationStarted || WebshimResources.isInHeader()) { if (WebshimResources.isInitialized()) { WebshimResources.eventLisenerQueue .forEach(action -> ac...
java
public RosterGroup createGroup(String name) { final XMPPConnection connection = connection(); if (groups.containsKey(name)) { return groups.get(name); } RosterGroup group = new RosterGroup(name, connection); groups.put(name, group); return group; }
java
public static LocalTime now(Clock clock) { Objects.requireNonNull(clock, "clock"); // inline OffsetTime factory to avoid creating object and InstantProvider checks final Instant now = clock.instant(); // called once ZoneOffset offset = clock.getZone().getRules().getOffset(now); ...
python
def or_call(self, _callable, *args, **kwargs): """ Calls **_callable** with supplied args and kwargs if a predicate fails. """ if self._exception: _callable(*args, **kwargs)
java
private static void populateFeatureNameFromManifest(File esa, Map<String, String> shortNameMap) throws IOException { String esaLocation = esa.getCanonicalPath(); ZipFile zip = null; try { zip = new ZipFile(esaLocation); Enumeration<? extends ZipEntry> zipEntries = zip.ent...
python
def md(cls, data, force_field, temperature, nsteps, other_settings=None): """ Example for a simple MD run based on template md.txt. Args: data (LammpsData or str): Data file as a LammpsData instance or path to an existing data file. force_field...
python
def get_compute_environment(self, identifier): """ Get compute environment by name or ARN :param identifier: Name or ARN :type identifier: str :return: Compute Environment or None :rtype: ComputeEnvironment or None """ env = self.get_compute_environment_b...
python
def layers(self): """ If entities have a layer defined, return it. Returns --------- layers: (len(entities), ) list of str """ layer = ['NONE'] * len(self.entities) for i, e in enumerate(self.entities): if hasattr(e, 'layer'): ...
python
def nvmlDeviceSetPowerManagementLimit(handle, limit): r""" /** * Set new power limit of this device. * * For Kepler &tm; or newer fully supported devices. * Requires root/admin permissions. * * See \ref nvmlDeviceGetPowerManagementLimitConstraints to check the allowed ranges of val...
java
private boolean wasResolved(File schemaSourceFile) { final FileDataSchemaLocation schemaLocation = new FileDataSchemaLocation(schemaSourceFile); return _schemaResolver.locationResolved(schemaLocation); }
java
public static String stripPackagePrefix(String className, Class<?> expectedType) { if (className.startsWith(expectedType.getPackage().getName())) { return className.substring(expectedType.getPackage().getName().length() + 1); } return className; }
java
private static Map<VectorLayer, List<Feature>> convertFromDto( Map<String, List<org.geomajas.layer.feature.Feature>> dtoFeatures, MapModel model) { Map<VectorLayer, List<Feature>> result = new LinkedHashMap<VectorLayer, List<Feature>>(); for (Entry<String, List<org.geomajas.layer.feature.Feature>> entry : dtoFea...
java
@Override public EClass getIfcReinforcingBar() { if (ifcReinforcingBarEClass == null) { ifcReinforcingBarEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(511); } return ifcReinforcingBarEClass; }
java
private boolean canSuccessorProceed() { if (predecessor != null && !predecessor.canSuccessorProceed()) { return false; } synchronized (this) { while (responseCount < groups.size()) { try { wait(); } catch (InterruptedE...
java
public ResultList<MovieBasic> getRatedMovies(String sessionId, int accountId, Integer page, String sortBy, String language) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.SESSION_ID, sessionId); parameters.add(Param.ID, accountId); parame...
java
public static LetContentNode forVariable( int id, SourceLocation sourceLocation, String varName, SourceLocation varNameLocation, @Nullable SanitizedContentKind contentKind) { LetContentNode node = new LetContentNode(id, sourceLocation, varName, varNameLocation, contentKind); ...
python
def _begins_with_one_of(sentence, parts_of_speech): """Return True if the sentence or fragment begins with one of the parts of speech in the list, else False""" doc = nlp(sentence) if doc[0].tag_ in parts_of_speech: return True return False
java
public int getIndexFromOffset(int offset) { int result = -1; for (int loop = 0; loop < m_offset.length; loop++) { if (m_offset[loop] == offset) { result = loop; break; } } return (result); }
python
def execute_dry_run(self, dialect=None, billing_tier=None): """Dry run a query, to check the validity of the query and return some useful statistics. Args: dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's stan...
python
def get_image(self, source): """ Given a file-like object, loads it up into a PIL.Image object and returns it. :param file source: A file-like object to load the image from. :rtype: PIL.Image :returns: The loaded image. """ buf = StringIO(source.read()) ...
java
private void validateQuietZone(BitArray row, int startPattern) throws NotFoundException { int quietCount = this.narrowLineWidth * 10; // expect to find this many pixels of quiet zone // if there are not so many pixel at all let's try as many as possible quietCount = quietCount < startPattern ? quietCount...
python
def infer_module_name(filename, fspath): """Convert a python filename to a module relative to pythonpath.""" filename, _ = os.path.splitext(filename) for f in fspath: short_name = f.relative_path(filename) if short_name: # The module name for __init__.py files is the directory. ...
java
public static xen_supplemental_pack[] get_filtered(nitro_service service, String filter) throws Exception { xen_supplemental_pack obj = new xen_supplemental_pack(); options option = new options(); option.set_filter(filter); xen_supplemental_pack[] response = (xen_supplemental_pack[]) obj.getfiltered(servi...
java
public GetDeviceDefinitionResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
python
def update(self, measurement, measurement_matrix): """ After each :py:meth:`predict`, this method may be called repeatedly to provide additional measurements for each time step. Args: measurement (MultivariateNormal): Measurement for this time step with speci...
python
def _validate(self, writing=True): """Verify that the box obeys the specifications.""" if any([box.box_id != 'colr' for box in self.box]): msg = ("Colour group boxes can only contain colour specification " "boxes.") self._dispatch_validation_error(msg, writing=...
java
public final AbstractButton createButton(ButtonFactory buttonFactory, CommandButtonConfigurer buttonConfigurer) { return createButton(getDefaultFaceDescriptorId(), buttonFactory, buttonConfigurer); }
java
private void logRequestHistory(HttpMethod httpMethodProxyRequest, PluginResponse httpServletResponse, History history) { try { if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) { logger.info("Storing history"); ...
java
private void init() { // Add this node to parents children if (null != parent) { parent.getChildren().add(this); } children.addListener((ListChangeListener<TreeNode>) c -> { while (c.next()) { if (c.wasRemoved()) { c.getRemoved().forEach(removedItem -> removedItem.re...
java
public static boolean isClassAccessChange(final int oldAccess, final int newAccess) { if ( not(oldAccess, Opcodes.ACC_ABSTRACT) && has(newAccess, Opcodes.ACC_ABSTRACT) ) { return true; // 13.4.1 #1 } else if ( not(oldAccess, Opcodes.ACC_FINAL) && has(newAccess, Opcodes.ACC_FINAL) ) { ...
java
public FileCollection getClassesDirs(@Nonnull final SourceSet pSourceSet, @Nonnull final DependencyConfig pDepConfig) { FileCollection result = pSourceSet.getOutput().getClassesDirs(); if (!pDepConfig.isDefaultConfig()) { JavaCompile compileTask = null; if (SourceSet....
java
public void init() { if (conv.getConversionDirection() == ConversionDirectionType.REVERSIBLE && this.reverse == null) { reverse = new ConversionWrapper(conv, (GraphL3) graph); this.direction = LEFT_TO_RIGHT; reverse.direction = RIGHT_TO_LEFT; reverse.reverse = this; } else if (conv.get...
java
@Deprecated public static Part<String> param(String name, String value) { return text(name, value); }
python
def object_clean(self): """ Remove large attributes from the metadata objects """ for sample in self.metadata: try: delattr(sample[self.analysistype], 'aaidentity') delattr(sample[self.analysistype], 'aaalign') delattr(sample[se...
java
public static base_response add(nitro_service client, dnssuffix resource) throws Exception { dnssuffix addresource = new dnssuffix(); addresource.Dnssuffix = resource.Dnssuffix; return addresource.add_resource(client); }
java
public long getMaxTime() { lock.lock(); try { if (printMinMax) { return previousIntervalMinMax.maxTime; } return minMax.maxTime; } finally { lock.unlock(); } }
java
public final ListInstancesPagedResponse listInstances(String parent) { ListInstancesRequest request = ListInstancesRequest.newBuilder().setParent(parent).build(); return listInstances(request); }