language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private static boolean matchRuleRegex(String regex, String value) { if (value == null) { value = ""; } if (regex == null) { return true; } if ((regex.length() > 0) && (regex.charAt(0) == '!')) { return !value.matches(regex.substring(1)); ...
java
@Override public int size() { final Segment<K, V>[] segments = this.segments; long sum = 0; long check = 0; int[] mc = new int[segments.length]; // Try a few times to get accurate count. On failure due to // continuous async changes in table, resort to locking. for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {...
java
public static <T> TaggedValue<T> taggedValue(String tag, T rep) { return new TaggedValueImpl<T>(tag, rep); }
java
static <T extends Annotation> T findAnnotation(Method method, Class<T> clazz) { T annotation = AnnotationUtils.findAnnotation(method, clazz); if (annotation == null) { try { annotation = AnnotationUtils.findAnnotation(method.getDeclaringClass() .getMethod(method.getName(), method.getParameterTypes()), ...
python
def _spill(self): """ dump already partitioned data into disks. """ global MemoryBytesSpilled, DiskBytesSpilled path = self._get_spill_dir(self.spills) if not os.path.exists(path): os.makedirs(path) used_memory = get_used_memory() if not self....
java
public static Node newSeq(Object value) { Node n = allocSeq(); n.seqAdd(value); return n; }
java
@Override public java.util.concurrent.Future<ChangeMessageVisibilityBatchResult> changeMessageVisibilityBatchAsync(String queueUrl, java.util.List<ChangeMessageVisibilityBatchRequestEntry> entries) { return changeMessageVisibilityBatchAsync(new ChangeMessageVisibilityBatchRequest().withQueueUrl...
java
public static String getAttributeString(Tag tag, String attrName, String defaultValue) { Literal lit = getAttributeLiteral(tag, attrName, null); if (lit == null) return defaultValue; return lit.getString(); }
python
def _get_span(self, m): """ Gets a tuple that identifies a span for the specific mention class that m belongs to. """ return (m.sentence.id, m.char_start, m.char_end)
java
public static byte[] readBytes(InputStream in) throws IORuntimeException { final FastByteArrayOutputStream out = new FastByteArrayOutputStream(); copy(in, out); return out.toByteArray(); }
java
public List<TagFileType<TldTaglibType<T>>> getAllTagFile() { List<TagFileType<TldTaglibType<T>>> list = new ArrayList<TagFileType<TldTaglibType<T>>>(); List<Node> nodeList = childNode.get("tag-file"); for(Node node: nodeList) { TagFileType<TldTaglibType<T>> type = new TagFileTypeImp...
java
private static InputElement createHiddenInput(String name, String value) { InputElement input = Document.get().createHiddenInputElement(); input.setName(name); input.setValue(value); return input; }
java
public Concept lowestCommonAncestor(Concept v, Concept w) { if (v.taxonomy != w.taxonomy) { throw new IllegalArgumentException("Concepts are not from the same taxonomy."); } List<Concept> vPath = v.getPathFromRoot(); List<Concept> wPath = w.getPathFromRoot(); Iterat...
java
public final Table getTable(String name) { GetTableRequest request = GetTableRequest.newBuilder().setName(name).build(); return getTable(request); }
java
public static String removeNotation(String name) { if (name.matches("^m[A-Z]{1}")) { return name.substring(1, 2).toLowerCase(); } else if (name.matches("m[A-Z]{1}.*")) { return name.substring(1, 2).toLowerCase() + name.substring(2); } return name; }
python
def override_language(self, language): """ Context manager to override the instance language. """ previous_language = self._linguist.language self._linguist.language = language yield self._linguist.language = previous_language
java
public List<Instance> getInstances4Attribute(final String _attributeName) throws EFapsException { final OneSelect oneselect = this.attr2OneSelect.get(_attributeName); return oneselect == null ? null : oneselect.getInstances(); }
python
def dialogues(self): """ Access the dialogues :returns: twilio.rest.autopilot.v1.assistant.dialogue.DialogueList :rtype: twilio.rest.autopilot.v1.assistant.dialogue.DialogueList """ if self._dialogues is None: self._dialogues = DialogueList(self._version, ass...
python
def build_fault_model(self, collapse=False, rendered_msr=WC1994(), mfd_config=None): ''' Constructs a full fault model with epistemic uncertainty by enumerating all the possible recurrence models of each fault as separate faults, with the recurrence rates multip...
java
public <T extends OmiseObject> Map<String, Object> serializeToMap(T model) { return objectMapper.convertValue(model, new TypeReference<Map<String, Object>>() { }); }
python
async def create_connection(self): '''Initiate a connection.''' connector = self.proxy or self.loop return await connector.create_connection( self.session_factory, self.host, self.port, **self.kwargs)
java
public static long[] hashToLongs(final double datum, final long seed) { final double d = (datum == 0.0) ? 0.0 : datum; //canonicalize -0.0, 0.0 final long[] data = { Double.doubleToLongBits(d) };//canonicalize all NaN forms return hash(data, seed); }
java
public IPAddress toAddress(IPVersion version) throws AddressStringException, IncompatibleAddressException { validate(); // call validate so that we throw consistently, cover type == INVALID, and ensure the addressProvider exists return addressProvider.getProviderAddress(version); }
java
public List<String> getUnsavedResources() { List<String> list = new ArrayList<>(); List<String> l; for (int i = 0; i < getExtensionCount(); i++) { l = getExtension(i).getUnsavedResources(); if (l != null) { list.addAll(l); } }...
java
public void runUncachedQuery() throws TimeoutException, InterruptedException { // [START bigquery_query_no_cache] // BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); String query = "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;"; QueryJobConfigurati...
python
def _point_scalar(self, name=None): """ Returns point scalars of a vtk object Parameters ---------- name : str Name of point scalars to retrive. Returns ------- scalars : np.ndarray Numpy array of scalars """ if n...
python
def _compile_pvariable_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> ...
java
public static InsightsLogger newLogger(Context context, String clientToken) { return new InsightsLogger(context, null, null); }
python
def _astoref(ins): ''' Stores a floating point value into a memory address. ''' output = _addr(ins.quad[1]) value = ins.quad[2] if value[0] == '*': value = value[1:] indirect = True else: indirect = False if indirect: output.append('push hl') output....
python
def install_egg(self, egg_name): """ Install an egg into the egg directory """ if not os.path.exists(self.egg_directory): os.makedirs(self.egg_directory) self.requirement_set.add_requirement( InstallRequirement.from_line(egg_name, None)) try: self.requ...
java
public void renderMozillaStyle(StringBuilder sb) { if (functionName != null) { sb.append(functionName).append("()"); } sb.append('@').append(fileName); if (lineNumber > -1) { sb.append(':').append(lineNumber); } }
python
def _set_ipv6_network(self, v, load=False): """ Setter method for ipv6_network, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_local_anycast_gateway/ipv6_track/ipv6_network (list) If this variable is read-only (config: false) in the source YANG file, then _set_ipv6_network is considered as...
python
def node_to_xml(node, output=sys.stdout, nsmap=None): """ Convert a Node object into a pretty .xml file without keeping everything in memory. If you just want the string representation use tostring(node). :param node: a Node-compatible object (ElementTree nodes are fine) :param nsmap: if given,...
java
@Get("/projects") public CompletableFuture<List<ProjectDto>> listProjects(@Param("status") Optional<String> status) { if (status.isPresent()) { checkStatusArgument(status.get()); return CompletableFuture.supplyAsync(() -> projectManager().listRemoved().stream() ...
python
def write(self, outfile): """Write this shape list to a region file. Parameters ---------- outfile : str File name """ if len(self) < 1: print("WARNING: The region list is empty. The region file " "'{:s}' will be empty.".format(o...
java
@Override public List<Object> getTable(final Object table) { List<Object> data = new ArrayList<>(); String tableName; if (table instanceof TableWithNullOption) { // Get source table name tableName = ((TableWithNullOption) table).getTableName(); // Insert null option data.add(null); } else { tab...
java
protected void validateSignature(ConsumerAuthentication authentication) throws AuthenticationException { SignatureSecret secret = authentication.getConsumerDetails().getSignatureSecret(); String token = authentication.getConsumerCredentials().getToken(); OAuthProviderToken authToken = null; if (token !=...
python
def docgen(): """ Build documentation. """ hitchpylibrarytoolkit.docgen( _storybook({}), DIR.project, DIR.key / "story", DIR.gen )
java
@Override public GetCredentialReportResult getCredentialReport(GetCredentialReportRequest request) { request = beforeClientExecution(request); return executeGetCredentialReport(request); }
python
def make_grid_with_coordtransform(numPix, deltapix, subgrid_res=1, left_lower=False, inverse=True): """ same as make_grid routine, but returns the transformaton matrix and shift between coordinates and pixel :param numPix: :param deltapix: :param subgrid_res: :param left_lower: sets the zero po...
java
public static int cuDeviceGetP2PAttribute(int value[], int attrib, CUdevice srcDevice, CUdevice dstDevice) { return checkResult(cuDeviceGetP2PAttributeNative(value, attrib, srcDevice, dstDevice)); }
java
@SuppressWarnings("unchecked") public <T> T get(String key, Class<T> clazz) { return (T) datas.get(key); }
java
public static void main(String[] args) throws Exception { // Checking input parameters final ParameterTool params = ParameterTool.fromArgs(args); // set up execution environment final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); // make parameters available in the web interfac...
python
def _get_single_depth(self, multi_index): ''' Helper method for determining how many single index entries there are in a particular multi-index ''' single_depth = 0 for subind in multi_index: if is_slice_or_dim_range(subind): break ...
java
@Override public BlockChannelReader<MemorySegment> createBlockChannelReader(FileIOChannel.ID channelID, LinkedBlockingQueue<MemorySegment> returnQueue) throws IOException { checkState(!isShutdown.get(), "I/O-Manager is shut down."); return new AsynchronousBlockReader(channelID, this.readers[channelID.ge...
java
public static void validateLesserThan( long value, long limit, String identifier ) throws PostConditionException { if( value < limit ) { return; } throw new PostConditionException( identifier + " was not lesser than " + limit + ". Was: " + value ); }
python
def get_all_operators(self): """|coro| Checks the player stats for all operators, loading them all again if any aren't found This is significantly more efficient than calling get_operator for every operator name. Returns ------- dict[:class:`Operator`] the d...
python
def _load(self): """ Function load. :return: file contents :raises: NotFoundError if file not found """ if self.is_exists(): return open(self._ref, "rb").read() raise NotFoundError("File %s not found" % self._ref)
python
def valid_batch(self): """ Returns a single batch with all the validation cases.""" valid_fns = list(zip(*self.corpus.get_valid_fns())) return self.load_batch(valid_fns)
java
@Override public HTableDescriptor[] disableTables(String regex) throws IOException { HTableDescriptor[] tableDescriptors = listTables(regex); for (HTableDescriptor descriptor : tableDescriptors) { disableTable(descriptor.getTableName()); } return tableDescriptors; }
python
def from_json(cls, jsonmsg): """ Create an object directly from a JSON string. Applies general validation after creating the object to check whether all required fields are present. Args: jsonmsg (str): An object encoded as a JSON string Returns: ...
python
def ipv6(self, network=False): """Produce a random IPv6 address or network with a valid CIDR""" address = str(ip_address(self.generator.random.randint( 2 ** IPV4LENGTH, (2 ** IPV6LENGTH) - 1))) if network: address += '/' + str(self.generator.random.randint(0, IPV6LENGTH))...
python
def set_handler(self, language, obj): """Define a custom language handler for RiveScript objects. Pass in a ``None`` value for the object to delete an existing handler (for example, to prevent Python code from being able to be run by default). Look in the ``eg`` folder of the rivescrip...
python
def _parse_attribute_details(self, prop=ATTRIBUTES): """ Concatenates a list of Attribute Details data structures parsed from a remote file """ parsed_attributes = self._parse_attribute_details_file(prop) if parsed_attributes is None: # If not in the (official) remote location, try ...
java
private final void setState(int newAction, boolean validateOnly) throws TransactionException { final String methodName = "setState"; final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(this, tc, methodName, getStateAsString...
java
public Vector2f setComponent(int component, float value) throws IllegalArgumentException { switch (component) { case 0: x = value; break; case 1: y = value; break; default: throw new IllegalArgume...
java
@Override public void onToken(Context context, String token, Bundle bundle) { updateAVInstallation(token); }
java
public void setPrimaryButtonHoverColor(String color) throws HelloSignException { if (white_labeling_options == null) { white_labeling_options = new WhiteLabelingOptions(); } white_labeling_options.setPrimaryButtonHoverColor(color); }
java
public Node previousSibling() { if (parentNode == null) return null; // root if (siblingIndex > 0) return parentNode.ensureChildNodes().get(siblingIndex-1); else return null; }
python
def uncompress_files(original, destination): """ Move file from original path to destination path. :type original: str :param original: The location of zip file :type destination: str :param destination: The extract path """ with zipfile.ZipFile(original) as zips: ...
java
public void addLinkValue(String ownerObjID, FieldDefinition linkDef, String targetObjID) { addColumn(SpiderService.objectsStoreName(linkDef.getTableDef()), ownerObjID, SpiderService.linkColumnName(linkDef, targetObjID)); }
java
@Override public synchronized ServiceTicket grantServiceTicket(final String id, final Service service, final ExpirationPolicy expirationPolicy, final boolean credentialProvided, final boolean onlyTrackMostRecentSession) { val serviceTicket = new Servi...
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WSubMenu menu = (WSubMenu) component; XmlStringBuilder xml = renderContext.getWriter(); xml.appendTagOpen("ui:submenu"); xml.appendAttribute("id", component.getId()); xml.appendOptionalAttribute("class", co...
java
public void marshall(DeleteProjectRequest deleteProjectRequest, ProtocolMarshaller protocolMarshaller) { if (deleteProjectRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteProjectReques...
python
async def create(self, model_, **data): """Create a new object saved to database. """ inst = model_(**data) query = model_.insert(**dict(inst.__data__)) pk = await self.execute(query) if inst._pk is None: inst._pk = pk return inst
python
def iter_orgs(username, number=-1, etag=None): """List the organizations associated with ``username``. :param str username: (required), login of the user :param int number: (optional), number of orgs to return. Default: -1, return all of the issues :param str etag: (optional), ETag from a previ...
java
public void pushLoop(List<String> labelNames) { pushState(); continueLabel = new Label(); breakLabel = new Label(); if (labelNames != null) { for (String labelName : labelNames) { initLoopLabels(labelName); } } }
java
public void preClose(HashMap exclusionSizes) throws IOException, DocumentException { if (preClosed) throw new DocumentException("Document already pre closed."); preClosed = true; AcroFields af = writer.getAcroFields(); String name = getFieldName(); boolean fieldExists...
python
def save_and_close_attributes(self): ''' Performs the same function as save_attributes but also closes the attribute file. ''' if not self.saveable(): raise AttributeError("Cannot save attribute file without a valid file") if not self._db_closed: s...
python
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the VeSync switch platform.""" if discovery_info is None: return switches = [] manager = hass.data[DOMAIN]['manager'] if manager.outlets is not None and manager.outlets: if len(manager.outlets) == 1: ...
java
protected void fixPropertyValues(PropertyData prop) throws RepositoryException { final List<ValueData> vals = prop.getValues(); for (int i = 0; i < vals.size(); i++) { ValueData vd = vals.get(i); if (!vd.isByteArray()) { // check if file is correct ...
java
public static int executeUpdate(PreparedStatement ps, Object... params) throws SQLException { StatementUtil.fillParams(ps, params); return ps.executeUpdate(); }
python
def _connect_pipeline(self, pipeline, required_outputs, workflow, subject_inds, visit_inds, filter_array, force=False): """ Connects a pipeline to a overarching workflow that sets up iterators over subjects|visits present in the repository (if required) and repo...
java
public byte[][] keypair() { byte[][] pair = new byte[2][]; byte[] publicKey = new byte[Size.PUBLICKEY.bytes()]; byte[] secretKey = new byte[Size.SECRETKEY.bytes()]; int rc = curve25519xsalsa20poly1305.crypto_box_keypair(publicKey, secretKey); assert (rc == 0); pair...
python
def _get_supported_for_any_abi(version=None, platform=None, impl=None, force_manylinux=False): """Generates supported tags for unspecified ABI types to support more intuitive cross-platform resolution.""" unique_tags = { tag for abi in _gen_all_abis(impl, version) for tag in _get_supported(version=vers...
python
def get_surface_equilibrium(self, slab_entries, delu_dict=None): """ Takes in a list of SlabEntries and calculates the chemical potentials at which all slabs in the list coexists simultaneously. Useful for building surface phase diagrams. Note that to solve for x equations ...
python
def vlos(self,*args,**kwargs): """ NAME: vlos PURPOSE: return the line-of-sight velocity (in km/s) INPUT: t - (optional) time at which to get vlos (can be Quantity) obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer ...
java
protected void removeEditOverlays() { CmsInlineEditOverlay.removeAll(); m_editOverlay = null; if (m_resizeHandlerRegistration != null) { m_resizeHandlerRegistration.removeHandler(); m_resizeHandlerRegistration = null; } }
java
public Stream<Branch> getBranchesStream(Object projectIdOrPath) throws GitLabApiException { return (getBranches(projectIdOrPath, getDefaultPerPage()).stream()); }
python
def send_message(self, message, sign=True): """Send the given message to the connection. @type message: OmapiMessage @param sign: whether the message needs to be signed @raises OmapiError: @raises socket.error: """ if sign: message.sign(self.authenticators[self.defauth]) logger.debug("sending %s", L...
java
protected static Boolean isRooted() { if (android.os.Build.TAGS != null && android.os.Build.TAGS.contains("test-keys")) { return true; } String[] probableRootPaths = { "/data/local/bin/su", "/data/local/su", "/data/local/xbin/su", "/sb...
java
@Override public String[] getCacheStatistics(String[] names) throws javax.management.AttributeNotFoundException { if (names == null) return null; DCache cache = null; if (ServerCache.servletCacheEnabled) { cache = ServerCache.cache; } String stats[] ...
java
@Override public void write(final File filename) throws DITAOTException { assert filename.isAbsolute(); setCurrentFile(filename.toURI()); super.write(filename); }
java
private boolean addStatement(StringBuffer statementBuffer) { if (statementBuffer.length() > 0) { elements.add(new Predicate(statementBuffer.toString())); elementsArray = elements.toArray(); statementBuffer.delete(0, statementBuffer.length()); return true; } return false; }
python
def indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level): """ Use 4 spaces per indentation level. For really old code that you don't want to mess up, you can continue to use 8-space tabs. """ if indent_char == ' ' and indent_level % 4: ...
java
private CmsADESessionCache getSessionCache() { if (m_sessionCache == null) { m_sessionCache = CmsADESessionCache.getCache(getRequest(), getCmsObject()); } return m_sessionCache; }
python
async def _query( self, path, method="GET", *, params=None, data=None, headers=None, timeout=None, chunked=None ): """ Get the response object by performing the HTTP request. The caller is responsible to finalize the res...
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { ContactServiceInterface contactService = adManagerServices.get(session, ContactServiceInterface.class); // Create a statement to select contacts. StatementBuilder statementBui...
java
public String[] getValues() { return value == null || value.isEmpty() ? new String[0] : len == 1 ? new String[] { value } : value.split("\\s+"); }
python
def constrain_horizon( r, strict=False, cust=None, years=0, quarters=0, months=0, days=0, weeks=0, year=None, month=None, day=None, ): """Constrain a Series/DataFrame to a specified lookback period. See the documentation for dateutil.relativedelta: ...
java
private List<Pair<Integer, Integer>> doGenerateEdgesWithOmitList() { final int numberOfNodes = getConfiguration().getNumberOfNodes(); final int numberOfEdges = getConfiguration().getNumberOfEdges(); final long maxEdges = numberOfNodes * (numberOfNodes - 1) / 2; final List<Pair<Integer, ...
python
def host_names(urls): ''' Takes a StringCounter of normalized URL and parses their hostnames N.B. this assumes that absolute URLs will begin with http:// in order to accurately resolve the host name. Relative URLs will not have host names. ''' host_names = StringCounter() for url ...
java
@Override public List<CPDAvailabilityEstimate> findByCommerceAvailabilityEstimateId( long commerceAvailabilityEstimateId, int start, int end, OrderByComparator<CPDAvailabilityEstimate> orderByComparator) { return findByCommerceAvailabilityEstimateId(commerceAvailabilityEstimateId, start, end, orderByComparato...
java
@Override public List<CommerceWarehouseItem> findByCPI_CPIU(long CProductId, String CPInstanceUuid, int start, int end, OrderByComparator<CommerceWarehouseItem> orderByComparator) { return findByCPI_CPIU(CProductId, CPInstanceUuid, start, end, orderByComparator, true); }
java
public void setInterval(ReadableInterval interval) { if (interval == null) { throw new IllegalArgumentException("Interval must not be null"); } long startMillis = interval.getStartMillis(); long endMillis = interval.getEndMillis(); Chronology chrono = interval.getChro...
java
private boolean isJawrImageTag(ComponentTag tag) { String tagName = tag.getName(); return (tagName.equalsIgnoreCase("img") || (tagName .equalsIgnoreCase("input") && tag.getAttribute("type").equals( "image"))); }
java
public void formatLine(String line, PrintWriter writer) { processingState.setLine(line); processingState.pwriter = writer; processingState = processingState.formatState.formatPartialLine(processingState); while (!processingState.isDoneWithLine()) { processi...
java
@Override public SparkAppHandle startApplication(SparkAppHandle.Listener... listeners) throws IOException { if (builder.isClientMode(builder.getEffectiveConfig())) { LOG.warning("It's not recommended to run client-mode applications using InProcessLauncher."); } Method main = findSparkSubmit(); ...
java
private void pushBasicProfile(JSONObject baseProfile) { try { String guid = getCleverTapID(); JSONObject profileEvent = new JSONObject(); if (baseProfile != null && baseProfile.length() > 0) { Iterator i = baseProfile.keys(); while (i.hasNext...
java
public JobInner create(String resourceGroupName, String accountName, String transformName, String jobName, JobInner parameters) { return createWithServiceResponseAsync(resourceGroupName, accountName, transformName, jobName, parameters).toBlocking().single().body(); }