language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public ListSentimentDetectionJobsResult listSentimentDetectionJobs(ListSentimentDetectionJobsRequest request) { request = beforeClientExecution(request); return executeListSentimentDetectionJobs(request); }
python
def save(self, fn:PathOrStr): "Save the image to `fn`." x = image2np(self.data*255).astype(np.uint8) PIL.Image.fromarray(x).save(fn)
java
public java.util.List<Object> getDefListOrListOrNotes() { if (defListOrListOrNotes == null) { defListOrListOrNotes = new ArrayList<Object>(); } return this.defListOrListOrNotes; }
python
def new_uid_validity(cls) -> int: """Generate a new UID validity value for a mailbox, where the first two bytes are time-based and the second two bytes are random. """ time_part = int(time.time()) % 4096 rand_part = random.randint(0, 1048576) return (time_part << 20) + r...
java
public static Intent newShareTextIntent(String subject, String message, String chooserDialogTitle) { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, message); shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject); shareIntent.setType(MIME_TYPE_T...
java
public boolean contains( Object o ) { boolean result = false; if( o == null ) { result = false; } else if( o instanceof String ) { result = super.contains(convertAddress((String)o)); } else if( o instanceof InternetAddress ) { result = super.contains(o);; } return res...
java
public static void consumeProcessOutput(Process self, OutputStream output, OutputStream error) { consumeProcessOutputStream(self, output); consumeProcessErrorStream(self, error); }
python
def get_arcpy(): ''' Allows arcpy to imported on 'unmanaged' python installations (i.e. python installations arcgis is not aware of). Gets the location of arcpy and related libs and adds it to sys.path ''' install_dir = locate_arcgis() arcpy = path.join(install_dir, "arcpy") # Check we have the arcp...
java
private synchronized Producer<Void> getNetworkFetchToEncodedMemoryPrefetchSequence() { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection( "ProducerSequenceFactory#getNetworkFetchToEncodedMemoryPrefetchSequence"); } if (mNetworkFetchToEncodedMemoryPrefetchSequence == null) { ...
java
public <T> Observable<Notification<T>> channel( final DeliveryMethod type, final ObservableFactoryNoArg<T> observableFactoryNoArg) { return channel(type, new Func1<Object, Observable<Notification<T>>>() { @Override public Observable<Notification<T>> call(Object ignored) ...
java
@Override public void validate() { String target = getTargetName(); //validate the parameters if (delay() < 0) { throw new FaultToleranceDefinitionException(Tr.formatMessage(tc, "circuitBreaker.parameter.delay.invalid.value.CWMFT5012E", "delay", delay(), target)); } ...
java
protected FacesConfigImpl createFacesConfig(Map<Class<? extends Annotation>, Set<Class<?>>> map) { FacesConfigImpl facesConfig = new FacesConfigImpl(); Set<Class<?>> classes = map.get(FacesComponent.class); if (classes != null && !classes.isEmpty()) { for (Class<?> claz...
python
def getNumNetworkWithConnection(self, connection): """Return the number of network interfaces with id ``connection``.""" i = 0 while True: value = self.getValue("net_interface.%d.connection" % i, None) if not value: return None if value == con...
java
public static Set<String> getBuildFilesForSourceDirs( List<String> sourceDirs, String[] includes, String[] excludes ) throws MojoExecutionException { Set<String> result = new LinkedHashSet<String>(); for ( String sourceDir : sourceDirs ) { try { ...
python
def convert_activation(builder, layer, input_names, output_names, keras_layer): """ Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get ...
python
def span_in_context(span): """ Create a context manager that stores the given span in the thread-local request context. This function should only be used in single-threaded applications like Flask / uWSGI. ## Usage example in WSGI middleware: .. code-block:: python from opentracing_ins...
python
def run( self, inputs: Dict[str, Union[float, Iterable]], torch_size: Optional[int] = None, ) -> Union[float, Iterable]: """Executes the GrFN over a particular set of inputs and returns the result. Args: inputs: Input set where keys are the names of input...
java
@Override public List<CPDefinitionOptionValueRel> getCPDefinitionOptionValueRels( int start, int end) { return cpDefinitionOptionValueRelPersistence.findAll(start, end); }
java
public SpringApplicationBuilder profiles(String... profiles) { this.additionalProfiles.addAll(Arrays.asList(profiles)); this.application.setAdditionalProfiles( StringUtils.toStringArray(this.additionalProfiles)); return this; }
python
def value(self): """Returns the current value of this slot. Returns: The value of the slot (a serializable Python type). Raises: SlotNotFilledError if the value hasn't been filled yet. """ if not self.filled: raise SlotNotFilledError('Slot with name "%s", key "%s" not yet filled....
python
def replace_color(self, before, after): """ Replaces a color on a surface with another one. :param before: Change all pixels with this color :param after: To that color :type before: tuple :type after: tuple """ #TODO: find out if this actually works ...
python
def user_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users#create-user" api_path = "/api/v2/users.json" return self.call(api_path, method="POST", data=data, **kwargs)
java
@Override protected void flushAndSync(boolean durable) throws IOException { if (fp == null) { throw new IOException("Trying to use aborted output stream"); } preallocate(); // preallocate file if necessary if (doubleBuf.isFlushed()) { return; } doubleBuf.flushTo(fp); if (durabl...
java
public static MapBlock createMapBlockInternal( int startOffset, int positionCount, Optional<boolean[]> mapIsNull, int[] offsets, Block keyBlock, Block valueBlock, HashTables hashTables, Type keyType, MethodHandle...
python
def command(self, resource, obj, operation_timeout=None, max_envelope_size=None, locale=None): """ resource can be a URL or a ResourceLocator """ if isinstance(resource, str): resource = ResourceLocator(resource) headers = self._build_headers(resource...
python
def configure_health(graph): """ Configure the health endpoint. :returns: a handle to the `Health` object, allowing other components to manipulate health state. """ ns = Namespace( subject=Health, ) include_build_info = strtobool(graph.config.health_convention.include...
python
def reflect_well(value, bounds): """Given some boundaries, reflects the value until it falls within both boundaries. This is done iteratively, reflecting left off of the `boundaries.max`, then right off of the `boundaries.min`, etc. Parameters ---------- value : float The value to apply...
python
def shutdown(self): """Start the connection shutdown process, cancelling any active consuming and closing the channel if the connection is not active. """ if self.is_shutting_down: self.logger.debug('Already shutting down') return self.set_state(self.STA...
python
def _convert_unit(unit): """Convert different names into SI units. Parameters ---------- unit : str unit to convert to SI Returns ------- str unit in SI format. Notes ----- SI unit such as mV (milliVolt, mVolt), μV (microVolt, muV). """ if unit is None...
python
def discoverPoints(bacnetapp, address, devID): """ Discover the BACnet points in a BACnet device. :param bacnetApp: The app itself so we can call read :param address: address of the device as a string (ex. '2:5') :param devID: device ID of the bacnet device as a string (ex. '1001') :returns: a...
java
protected WsTraceRouterImpl getTraceRouter() { if (traceRouter == null) { // First activation. traceRouter = WsTraceRouterSingleton.singleton; // Pass the MessageRouter to the TrService via the TrConfigurator. TrConfigurator.setTraceRouter(traceRouter); }...
java
private static String negate(String conditionTemplate) { if (conditionTemplate.startsWith("!") && !BOOLEAN_BINARY_OPERATOR.matcher(conditionTemplate).find()) { return conditionTemplate.substring(1); } else if (ANY_OPERATOR.matcher(conditionTemplate).find()) { // The condition might already e...
java
@Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { IdleStateEvent e = (IdleStateEvent) evt; // See class comment for timeout semantics. In addition to ensuring we only timeout while // there are outstanding requ...
python
def p_methodDeclaration(p): # pylint: disable=line-too-long """methodDeclaration : dataType methodName '(' ')' ';' | dataType methodName '(' parameterList ')' ';' | qualifierList dataType methodName '(' ')' ';' | qualifierList dataType m...
java
public static String getImagePath(String imageTag) { int indexOfSlash = imageTag.indexOf("/"); int indexOfLastColon = imageTag.lastIndexOf(":"); String imageName; String imageVersion; if (indexOfLastColon < 0 || indexOfLastColon < indexOfSlash) { imageName = imageTag...
java
private static int findExpressionType(OptFunctionNode fn, Node n, int[] varTypes) { switch (n.getType()) { case Token.NUMBER: return Optimizer.NumberType; case Token.CALL: case Token.NEW: case Token.RE...
python
def _single_load(self, addr, offset, size, inspect=True, events=True): """ Performs a single load. """ try: d = self._contents[addr] except KeyError: d = self._handle_uninitialized_read(addr, inspect=inspect, events=events) self._contents[addr]...
java
public static void write(Object value, MediaEncoder encoder, Writer out) throws IOException { if(encoder==null) { write(value, out); } else { // Otherwise, if A is null, then the result is "". // Write nothing if(value != null) { // Unwrap out to avoid unnecessary validation of known valid output ...
java
public GetQueueAttributesResult withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
java
public static Xml exports(ActionConfig config) { Check.notNull(config); final Xml nodeAction = new Xml(NODE_ACTION); nodeAction.writeString(ATT_NAME, config.getName()); nodeAction.writeString(ATT_DESCRIPTION, config.getDescription()); nodeAction.writeInteger(ATT_X, co...
python
def unwrap_single(self): """ Unwrap the single Result item. Call this from single-operation methods to return the actual result :return: The actual result """ try: return next(self.itervalues()) except AttributeError: return next(iter(self....
java
public List<Article> get(String url, String search) { if(search == null) return articleMap.get(url); return articleMap.get(url + "?s=" + Uri.encode(search)); }
python
async def service_observer(self, limit) -> int: """ Service the observer's inBox and outBox :return: the number of messages successfully serviced """ if not self.isReady(): return 0 return await self._observer.serviceQueues(limit)
java
public ProgramElementDoc owner() { Symbol osym = type.tsym.owner; if ((osym.kind & Kinds.TYP) != 0) { return env.getClassDoc((ClassSymbol)osym); } Names names = osym.name.table.names; if (osym.name == names.init) { return env.getConstructorDoc((MethodSymbo...
java
public double removeD(int index) { boundsCheck(index); double ret = array[index]; for(int i = index; i < end-1; i++) array[i] = array[i+1]; decreaseSize(1); return ret; }
python
def symlink_abiext(self, inext, outext): """ Create a simbolic link (outext --> inext). The file names are implicitly given by the ABINIT file extension. Example: outdir.symlink_abiext('1WF', 'DDK') creates the link out_DDK that points to out_1WF Return: 0...
python
def get_dir_indices(msg, dirs): '''Return path(s) indices of directory list from user input Args ---- msg: str String with message to display before pass selection input dir_list: array-like list of paths to be displayed and selected from Return ------ input_dir_indices...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.EPF__PF_NAME: setPFName(PF_NAME_EDEFAULT); return; case AfplibPackage.EPF__TRIPLETS: getTriplets().clear(); return; } super.eUnset(featureID); }
java
public SoySauce build() { if (scopedData == null) { scopedData = new SoySimpleScope(); } if (loader == null) { loader = SoySauceBuilder.class.getClassLoader(); } return new SoySauceImpl( new CompiledTemplates(readDelTemplatesFromMetaInf(loader), loader), scopedData.entera...
python
def eval_single(self, key, data, data_store): """ Evaluate the value of a single parameter taking into account callables . Native types are not touched and simply returned, while callable methods are executed and their return value is returned. Args: key (str): The name of ...
java
public int getLeftIndexFromSNode(SSpan s) { RelannisNodeFeature feat = (RelannisNodeFeature) s.getFeature(SaltUtil.createQName(ANNIS_NS, FEAT_RELANNIS_NODE)).getValue(); return (int) feat.getLeftToken(); }
python
def prepare_service(args=None): """Configures application and setups logging.""" options.register_opts(cfg.CONF) services.load_service_opts(cfg.CONF) _configure(args) _setup_logging() cfg.CONF.log_opt_values(logging.getLogger(), logging.DEBUG)
python
def transform_non_affine(self, values): """Transform an array of GPS times. This method is designed to filter out transformations that will generate text elements that require exact precision, and use `Decimal` objects to do the transformation, and simple `float` otherwise. ...
python
def bias(self): """ Frequency Bias. Formula: (a+b)/(a+c)""" return (self.table[0, 0] + self.table[0, 1]) / (self.table[0, 0] + self.table[1, 0])
python
def benchmark_annualize_return(self): """基准组合的年化收益 Returns: [type] -- [description] """ return round( float( self.calc_annualize_return( self.benchmark_assets, self.time_gap ) ),...
java
public void userCompletedAction(@NonNull final String action, JSONObject metadata, BranchViewHandler.IBranchViewEvents callback) { ServerRequest req = new ServerRequestActionCompleted(context_, action, metadata, callback); if (!req.constructError_ && !req.handleErrors(context_)) { ...
java
private void updateTitle() { String title; if (this.getCurrentComponent() == null) { title = "Example Picker"; } else { title = this.getCurrentComponent().getClass().getName(); } WApplication app = WebUtilities.getAncestorOfClass(WApplication.class, this); if (app != null) { app.setTitle(title);...
java
private void checkUnicity(ValidationStampFilter filter) { // Check project vs branch if (filter.getProject() != null && filter.getBranch() != null) { throw new IllegalStateException("Filter cannot be associated with both a project and a branch."); } // Gets the existing filte...
python
def get_swagger_objects(settings, route_info, registry): """Returns appropriate swagger handler and swagger spec schema. Swagger Handler contains callables that isolate implementation differences in the tween to handle both Swagger 1.2 and Swagger 2.0. Exception is made when `settings.prefer_20_routes...
python
def doc_reader(infile): """Parse docx and odf files.""" if infile.endswith('.docx'): docid = 'word/document.xml' else: docid = 'content.xml' try: zfile = zipfile.ZipFile(infile) except: print('Sorry, can\'t open {}.'.format(infile)) return body = ET.fromst...
java
public static void processBndAndExt(Map<JNDIEnvironmentRefType, Map<String, String>> allBindings, Map<String, String> envEntryValues, ResourceRefConfigList resRefList, RefBindingsGroup refBindingsGrou...
java
@Override public EClass getIfcWorkSchedule() { if (ifcWorkScheduleEClass == null) { ifcWorkScheduleEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(773); } return ifcWorkScheduleEClass; }
python
def valueByLabel(self, label): """ Determine a given value based on the inputted label. :param label <str> :return <int> """ keys = self.keys() labels = [text.pretty(key) for key in keys] if label in labels: return self[key...
java
@Override public com.liferay.commerce.model.CPDefinitionInventory deleteCPDefinitionInventory( long CPDefinitionInventoryId) throws com.liferay.portal.kernel.exception.PortalException { return _cpDefinitionInventoryLocalService.deleteCPDefinitionInventory(CPDefinitionInventoryId); }
python
def sort_by_padding(instances: List[Instance], sorting_keys: List[Tuple[str, str]], # pylint: disable=invalid-sequence-index vocab: Vocabulary, padding_noise: float = 0.0) -> List[Instance]: """ Sorts the instances by their padding lengths, using the ...
java
public void marshall(RegexPatternSetSummary regexPatternSetSummary, ProtocolMarshaller protocolMarshaller) { if (regexPatternSetSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(regexPatternS...
python
def percent_initiated_interactions(records, user): """ The percentage of calls initiated by the user. """ if len(records) == 0: return 0 initiated = sum(1 for r in records if r.direction == 'out') return initiated / len(records)
java
@Nullable public static InetSocketAddress parseInetSocketAddress(String address) throws IOException { if (address == null) { return null; } String[] strArr = address.split(":"); if (strArr.length != 2) { throw new IOException("Invalid InetSocketAddress " + address); } return new In...
python
def cli(ctx, key, metadata=""): """Add a canned key Output: A dictionnary containing canned key description """ return ctx.gi.cannedkeys.add_key(key, metadata=metadata)
java
protected TreeMap<String, Object> prepareOrderedMap(Object form, Set<ConstraintViolation<Object>> vioSet) { final Map<String, Object> vioPropMap = new HashMap<>(vioSet.size()); for (ConstraintViolation<Object> vio : vioSet) { final String propertyPath = extractPropertyPath(vio); ...
python
def get_plural(amount, variants, absence=None): """ Get proper case with value @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode}...
java
public void restoreAllMockSubnet(final Collection<MockSubnet> subnets) { allMockSubnets.clear(); if (null != subnets) { for (MockSubnet instance : subnets) { allMockSubnets.put(instance.getSubnetId(), instance); } } }
java
public static Operator getReversedOperator(Operator e) { if ( e.equals( Operator.NOT_EQUAL ) ) { return Operator.EQUAL; } else if ( e.equals( Operator.EQUAL ) ) { return Operator.NOT_EQUAL; } else if ( e.equals( Operator.GREATER ) ) { return Operator.LESS_OR_E...
java
public static <T extends MatchResult, S extends MatchType> Predicate<T> greaterOrEqualTo(S matchType) { return Predicates.or(greaterThan(matchType), equalTo(matchType)); }
python
def do_program(self, program: Program) -> 'AbstractQuantumSimulator': """ Perform a sequence of gates contained within a program. :param program: The program :return: self """ for gate in program: if not isinstance(gate, Gate): raise ValueErro...
python
def close(self): """Logs out and quits the current web driver/selenium session.""" if not self.driver: return try: self.driver.implicitly_wait(1) self.driver.find_element_by_id('link-logout').click() except NoSuchElementException: pass ...
java
public boolean containsCollectionDef( java.lang.String key) { if (key == null) { throw new java.lang.NullPointerException(); } return internalGetCollectionDef().getMap().containsKey(key); }
python
def log(*args, level=INFO): """ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file). """ Logger.CURRENT.log(*args, level=level)
java
static void validateChecksum(int expectedChecksum, ByteBuf data, int offset, int length) { final int actualChecksum = calculateChecksum(data, offset, length); if (actualChecksum != expectedChecksum) { throw new DecompressionException( "mismatching checksum: " + Integer.to...
java
public Table leftOuter(Table table2, String col2Name) { return leftOuter(table2, false, col2Name); }
python
def xd(self): """get xarray dataset file handle to LSM files""" if self._xd is None: # download files if the user requests if None not in (self.download_start_datetime, self.download_end_datetime): self._download() self._xd = super(ERAtoGSSHA, self).x...
python
def fetch_config(filename): """Fetch the Configuration schema information Finds the schema file, loads the file and reads the JSON, then converts to a dictionary that is returned """ # This trick gets the directory of *this* file Configuration.py thus # allowing to find the schema files relative ...
java
public static void initialize(BeanManagerImpl deploymentManager, ServiceRegistry deploymentServices) { Container instance = new Container(RegistrySingletonProvider.STATIC_INSTANCE, deploymentManager, deploymentServices); Container.instance.set(RegistrySingletonProvider.STATIC_INSTANCE, instance); }
java
protected int getPropIntValue(String aPropName, String aDefaultValue) { int retValue; String temp = dbPoolingProperties.getProperty(aPropName, aDefaultValue); retValue = Integer.valueOf(temp); return retValue; }
python
def create(self, path): """ Creates a new Registry key. @type path: str @param path: Registry key path. @rtype: L{RegistryKey} @return: The newly created Registry key. """ path = self._sanitize_path(path) hive, subpath = self._parse_path(path) ...
java
public FormInput inputField(InputType type, Identification identification) { FormInput input = new FormInput(type, identification); this.formInputs.add(input); return input; }
java
public void modifyRequest(ResponseBuilder rb, SearchComponent who, ShardRequest sreq) { if (sreq.params.getBool(MtasSolrSearchComponent.PARAM_MTAS, false)) { if (sreq.params.getBool(PARAM_MTAS_TERMVECTOR, false)) { // compute keys Set<String> keys = MtasSolrResultUtil .getIds...
python
def get_response_dict(self, helper, context, is_formset): """ Returns a dictionary with all the parameters necessary to render the form/formset in a template. :param context: `django.template.Context` for the node :param is_formset: Boolean value. If set to True, indicates we are workin...
java
@Override public void backward() { Tensor depAdj = depIn.getOutputAdj(); int n = depAdj.getDims()[1]; for (int v=0; v<yAdj.varBeliefs.length; v++) { if (yAdj.varBeliefs[v] != null) { Var var = y.varBeliefs[v].getVars().get(0); if (var instanceof Li...
python
def load_inv_result(self, filename, columns=2): """Load one parameter set from a rho*.mag or rho*.pha file produced by CRTomo. Parameters ---------- filename : string, file path Filename to loaded data from columns : int or iterable of ints, optional ...
python
def _add_fragment(cls, syncmap, identifier, lines, begin, end, language=None): """ Add a new fragment to ``syncmap``. :param syncmap: the syncmap to append to :type syncmap: :class:`~aeneas.syncmap.SyncMap` :param identifier: the identifier :type identifier: string ...
java
public static ConfigurableEmitter loadEmitter(InputStream ref, ConfigurableEmitterFactory factory) throws IOException { if (factory == null) { factory = new ConfigurableEmitterFactory() { public ConfigurableEmitter createEmitter(String name) { return new ConfigurableEmitter(name); } }; ...
java
private void configureRetryIntervalFunction(BackendProperties properties, RetryConfig.Builder<Object> builder) { if (properties.getWaitDuration() != 0) { long waitDuration = properties.getWaitDuration(); if (properties.getEnableExponentialBackoff()) { if (properties.getExponentialBackoffMultiplier() != 0) {...
python
def download_object(self, container, obj, directory, structure=True): """ Fetches the object from storage, and writes it to the specified directory. The directory must exist before calling this method. If the object name represents a nested folder structure, such as "foo/bar/baz...
python
def list_cert_bindings(site): ''' List certificate bindings for an IIS site. .. versionadded:: 2016.11.0 Args: site (str): The IIS site name. Returns: dict: A dictionary of the binding names and properties. CLI Example: .. code-block:: bash salt '*' win_iis.list...
python
def count_scts_in_sct_extension(certificate: cryptography.x509.Certificate) -> Optional[int]: """Return the number of Signed Certificate Timestamps (SCTs) embedded in the certificate. """ scts_count = 0 try: # Look for the x509 extension sct_ext = certificate.exte...
java
@Override public int getDepIdsSizeDisk() { final String methodName = "getDepIdsSizeDisk()"; if (this.swapToDisk) { // TODO write code to support getDepIdsSizeDisk function if (tc.isDebugEnabled()) { Tr.debug(tc, methodName + " cacheName=" + cacheName + " ERROR...
python
def contains_if(self, include_loop=True): """ Check if the node is a IF node Returns: bool: True if the node is a conditional node (IF or IFLOOP) """ if include_loop: return self.type in [NodeType.IF, NodeType.IFLOOP] return self.type == NodeTy...
python
def supports_service_desk(self): """Returns whether or not the JIRA instance supports service desk. :rtype: bool """ url = self._options['server'] + '/rest/servicedeskapi/info' headers = {'X-ExperimentalApi': 'opt-in'} try: r = self._session.get(url, headers=...
java
public void setPreferredAvailabilityZones(java.util.Collection<String> preferredAvailabilityZones) { if (preferredAvailabilityZones == null) { this.preferredAvailabilityZones = null; return; } this.preferredAvailabilityZones = new com.amazonaws.internal.SdkInternalList<S...