language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void fireChangeEvent() { ChangeEvent event = createChangeEvent(getSource()); for (ChangeListener listener : this) { listener.stateChanged(event); } }
java
public static List<Resource> parsePath(final SecurityContext securityContext, final HttpServletRequest request, final Map<Pattern, Class<? extends Resource>> resourceMap, final Value<String> propertyView) throws FrameworkException { final String path = request.getPathInfo(); // intercept empty path and send 204 N...
python
def form_valid(self, form): ''' Create slots and return success message. ''' startDate = form.cleaned_data['startDate'] endDate = form.cleaned_data['endDate'] startTime = form.cleaned_data['startTime'] endTime = form.cleaned_data['endTime'] instructor = fo...
java
public static String getPaymentButton(int receiverId, String secret, String email, String bankId, String subject, String body, int amount, Date expiresDate, String notifyUrl, String returnUrl, String cancelUrl, String pictureUrl, String custom, String transactionId, String button) { StringBuilder builder = new String...
java
public static BaseLocale createInstance(String language, String region) { BaseLocale base = new BaseLocale(language, region); CACHE.put(new Key(language, region), base); return base; }
java
private String getTitle(Resource resource) { String title = null; try (InputStream is = resource.getInputStream()) { Iterator<String> iter = IOUtils.lineIterator(is, "UTF-8"); while (iter.hasNext()) { String line = iter.next().trim(); ...
python
def remove_ip(self, IPAddress): """ Release the specified IP-address from the server. """ self.cloud_manager.release_ip(IPAddress.address) self.ip_addresses.remove(IPAddress)
java
public CreateMediaResourceResponse createMediaResource( String title, String description, File file, String transcodingPresetGroupName, int priority, String mode) throws FileNotFoundException { if (!file.exists()) { ...
java
protected final boolean isSatisfied(AnalyzedToken aToken, Map<String, List<String>> uFeatures) { if (allFeatsIn && equivalencesMatched.isEmpty()) { return false; } if (uFeatures == null) { throw new RuntimeException("isSatisfied called without features being set"); } unificationFe...
python
def _new(self, name, parent_dir_num): # type: (bytes, int) -> None ''' An internal method to create a new Path Table Record. Parameters: name - The name for this Path Table Record. parent_dir_num - The directory number of the parent of this Path Table ...
python
def drawpoint(self, x, y, colour = None): """ Most elementary drawing, single pixel, used mainly for testing purposes. Coordinates are those of your initial image ! """ self.checkforpilimage() colour = self.defaultcolour(colour) self.changecolourmode(colour) ...
python
def flatten_dict(data, parent_key='', sep='_'): """Flatten a nested dictionary. :param data: A nested dictionary :type data: dict or MutableMapping :param str parent_key: The parent's key. This is a value for tail recursion, so don't set it yourself. :param str sep: The separator used between dicti...
java
public double getRatioOfDataInIntersectionVolume(List<SpatialEntry>[] split, HyperBoundingBox[] mbrs) { final ModifiableHyperBoundingBox xMBR = SpatialUtil.intersection(mbrs[0], mbrs[1]); if(xMBR == null) { return 0.; } // Total number of entries, intersecting entries int[] numOf = { 0, 0 }; ...
java
@SuppressWarnings("rawtypes") protected Form getForm(HttpServerExchange exchange) throws IOException { final Form form = Application.getInstance(Form.class); if (RequestUtils.isPostPutPatch(exchange)) { final Builder builder = FormParserFactory.builder(); builder.setDefaultCh...
java
public MBeanServerConnection getConnection(String jmxUrl, Hashtable attributes) { return getConnection(jmxUrl, attributes, false); }
java
public String stop(String backupId) throws IOException, BackupExecuteException { // first try to find current repository backup String sURL = path + HTTPBackupAgent.Constants.BASE_URL + HTTPBackupAgent.Constants.OperationType.CURRENT_BACKUPS_REPOSITORY_INFO; ...
java
public static String read(InputStream input) throws IOException, NotFoundException { BufferedImage image = ImageIO.read(input); return read(image); }
java
protected void checkForPrimaryKeys(final Object realObject) throws ClassNotPersistenceCapableException { // if no PKs are specified OJB can't handle this class ! if (m_pkValues == null || m_pkValues.length == 0) { throw createException("OJB needs at least one primary key att...
java
public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException { if (serviceIterator == null) { return spi.engineGeneratePrivate(keySpec); } Exception failure = null; KeyFactorySpi mySpi = spi; do { try { ...
python
def get(self, measurementId): """ Analyses the measurement with the given parameters :param measurementId: :return: """ logger.info('Loading raw data for ' + measurementId) measurement = self._measurementController.getMeasurement(measurementId, MeasurementStatus.C...
python
def _mod_init(self, low): ''' Check the module initialization function, if this is the first run of a state package that has a mod_init function, then execute the mod_init function in the state module. ''' # ensure that the module is loaded try: self.s...
java
public static InetSocketAddress buildInetSocketAddress(String host, int defaultPort) { if (StrUtil.isBlank(host)) { host = LOCAL_IP; } String destHost = null; int port = 0; int index = host.indexOf(":"); if (index != -1) { // host:port形式 destHost = host.substring(0, index); port = In...
java
public static Aggregator get(final String name) { final Aggregator agg = aggregators.get(name); if (agg != null) { return agg; } throw new NoSuchElementException("No such aggregator: " + name); }
java
private Path[] globPathsLevel(Path[] parents, String[] filePattern, int level, boolean[] hasGlob) throws IOException { if (level == filePattern.length - 1) return parents; if (parents == null || parents.length == 0) { return null; } GlobFilter fp = new GlobFilter(filePattern[level]); ...
java
public static <S, T> T findResult(S[] self, @ClosureParams(FirstParam.Component.class) Closure<T> condition) { return findResult(new ArrayIterator<S>(self), condition); }
java
@VisibleForTesting Map<String, String> loadBaseProperties() throws IOException { final Properties props = new Properties(); for (final String property: StringUtils.split(configuration.getProperty(GeneralOption.SONAR_PROPERTIES), ',')){ final File propertyFile = new File(StringUtils.strip...
python
def has_ist_trigger(self): """Return True if this BuildConfig has ImageStreamTag trigger.""" triggers = self.template['spec'].get('triggers', []) if not triggers: return False for trigger in triggers: if trigger['type'] == 'ImageChange' and \ t...
python
def patched_get_site_by_id(self, site_id): """ Monkey patched version of Django's SiteManager._get_site_by_id() function. Adds a configurable timeout to the in-memory SITE_CACHE for each cached Site. This allows for the use of an in-memory cache for Site models, avoiding one or more DB hits on ever...
java
public static synchronized void deleteSoonerOrLater(File fileToDelete) { pendingDeletes.add(fileToDelete); // if things are getting out of hand, force gc/finalization if(pendingDeletes.size()>50) { LOGGER.warning(">50 pending Files to delete; forcing gc/finalization"); Sy...
java
private void handleMatch(Point match) { if (match == null) { int caretPosition = textComponent.getCaretPosition(); Document document = textComponent.getDocument(); caretPosition = Math.max(0, Math.min( document.getLength(), caretPosition)); ...
python
def splitpath(self): """ p.splitpath() -> Return (p.parent, p.name). """ parent, child = os.path.split(self) return self.__class__(parent), child
python
def make_source(self, groups, code_opts, gen_opts): """Build the final source code for all modules.""" modules = self.make_modules(groups, code_opts) var_decls = modules.var_decls relocs = AttrsGetter(modules.relocs) x86, x64 = relocs.get_attrs('x86', 'x64') if code_opts....
java
public static String bytesToBase64Str(byte[] bytes) { if (ArrayUtils.isEmpty(bytes)) { return null; } Base64.Encoder encoder = Base64.getEncoder(); String base64Str = encoder.encodeToString(bytes); return base64Str; }
java
public List<AbstractSequence<? extends AbstractCompound>> getBioSequences(boolean ignoreCase, String forcedSequenceType) { if (forcedSequenceType != null && !(forcedSequenceType.equals(PFAM) || forcedSequenceType.equals(RFAM))) { throw new IllegalArgumentException("Illegal Argument " + forcedSequenceType); } ...
python
def from_file(campaign_file, **kwargs): """Load campaign from YAML file :return: memory representation of the YAML file :rtype: dictionary """ realpath = osp.realpath(campaign_file) if osp.isdir(realpath): campaign_file = osp.join(campaign_file, YAML_CAMPAIGN_FILE) campaign = Config...
java
public Query like(java.io.InputStream is) throws IOException { return like(new InputStreamReader(is)); }
python
def sha_hash_file(filename): """ Compute the SHA1 hash of filename """ hash_sha = hashlib.sha1() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(1024*1024), b""): hash_sha.update(chunk) return hash_sha.hexdigest()
python
def get_date_of_author(_id): """Pass author id and return the name of its associated date.""" _dict = get_date_author() for date, ids in _dict.items(): if _id in ids: return date return None
java
public String post(String url, String payload) throws AuthenticationException, ApiException { return performRequest(url, "POST", null, null, payload); }
python
def get_name_on_date(self, date): """ Get the name of a company on a given date. This takes into accounts and name changes that may have occurred. """ if date is None: return self.name post_name_changes = CompanyNameChange.objects.filter(company=self, ...
python
def init(self, formula, incr=False): """ Initialize the internal SAT oracle. The oracle is used incrementally and so it is initialized only once when constructing an object of class :class:`RC2`. Given an input :class:`.WCNF` formula, the method bootstraps the ...
python
def parse_line(self, line): """Parse a line into a dictionary""" match = re.findall(self.date_regex, line) if match: fields = self.fields elif self.backup_format_regex and not match: match = re.findall(self.backup_date_regex, line) fields = self.backup...
python
def tokenize(self, text, stream=False, wakati=False, baseform_unk=True, dotfile=''): u""" Tokenize the input text. :param text: unicode string to be tokenized :param stream: (Optional) if given True use stream mode. default is False. :param wakati: (Optinal) if given True return...
java
public int tailOf(String srcStr, String searchStr) { if (isBlank(srcStr) || isBlank(searchStr)) { return -1; } int cursor = -1; boolean loop = true; boolean firstTokenAlreadyFound = false; do { int idx = srcStr.indexOf(searchStr); ...
java
private ResultSet read(ConsistencyLevel cl, int retryCount) { System.out.printf("Reading at %s (retry count: %d)%n", cl, retryCount); Statement stmt = SimpleStatement.newInstance( "SELECT sensor_id, date, timestamp, value " + "FROM downgrading.sensor_data " ...
java
static Object removePreserve(Context ctx, Object input, JsonLdOptions opts) throws JsonLdError { // recurse through arrays if (isArray(input)) { final List<Object> output = new ArrayList<Object>(); for (final Object i : (List<Object>) input) { final Object result ...
java
private boolean methodBasedRecoverLease(String src, boolean discardLastBlock) throws IOException { // check if closeRecoverLease(discardLastBlock) is supported if (namenodeProtocolProxy.isMethodSupported( "closeRecoverLease", String.class, String.class, boolean.class)) { try { return n...
java
public static AnnotationTypeFieldBuilder getInstance( Context context, ClassDoc classDoc, AnnotationTypeFieldWriter writer) { return new AnnotationTypeFieldBuilder(context, classDoc, writer, VisibleMemberMap.ANNOTATION_TYPE_FIELDS); }
java
public InputStreamReader getFileStream(File file) throws NoSuchPathException{ try { return new InputStreamReader(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new NoSuchPathException(e); } }
python
def get_label(self, label, lineno): """ Returns a label in the current context or in the global one. If the label does not exists, creates a new one and returns it. """ global NAMESPACE ex_label, namespace = Memory.id_name(label) for i in range(len(self.local_labels) - ...
java
private int binarySearch(SimpleMDAGNode[] mdagDataArray, char node) { if (transitionSetSize < 1) { return -1; } int high = transitionSetBeginIndex + transitionSetSize - 1; int low = transitionSetBeginIndex; while (low <= high) { int mid...
java
public PublicationsFile create(InputStream input) throws KSIException { InMemoryPublicationsFile publicationsFile = new InMemoryPublicationsFile(input); CMSSignature signature = publicationsFile.getSignature(); CMSSignatureVerifier verifier = new CMSSignatureVerifier(trustStore); verifi...
python
def refresh_keys(context, id, etag): """refresh_keys(context, id, etag) Refresh a remoteci key pair. >>> dcictl remoteci-refresh-keys [OPTIONS] :param string id: ID of the remote CI [required] :param string etag: Entity tag of the remote CI resource [required] """ result = remoteci.refres...
java
public void marshall(UpdateAccountRequest updateAccountRequest, ProtocolMarshaller protocolMarshaller) { if (updateAccountRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateAccountReques...
java
public void marshall(DescribeActivityTypeRequest describeActivityTypeRequest, ProtocolMarshaller protocolMarshaller) { if (describeActivityTypeRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def patch_default_retcodes(): """ Sets the default luigi return codes in ``luigi.retcodes.retcode`` to: - already_running: 10 - missing_data: 20 - not_run: 30 - task_failed: 40 - scheduling_error: 50 - unhandled_exception: 60 """ import luigi.retcodes ...
python
def timeit(method): """ Decorator: Compute the execution time of a function :param method: the function :return: the method runtime """ def timed(*arguments, **kw): ts = time.time() result = method(*arguments, **kw) te = time.time() sys.stdout.write('Time: %r %...
python
def long_press_keycode(self, keycode, metastate=None): """Sends a long press of keycode to the device. Android only. See `press keycode` for more details. """ driver = self._current_application() driver.long_press_keycode(int(keycode), metastate)
java
@Override public SIDestinationAddress[] getDefaultForwardRoutingPath() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getDefaultForwardRoutingPath"); // Convert array of names to list of jsDestinationAddresses QualifiedDestinationName[] na...
python
def update_ips(self): """Retrieves the public and private ip of the instance by using the cloud provider. In some cases the public ip assignment takes some time, but this method is non blocking. To check for a public ip, consider calling this method multiple times during a certain timeou...
java
public BooleanExpression equalsIgnoreCase(Expression<String> str) { return Expressions.booleanOperation(Ops.EQ_IGNORE_CASE, mixin, str); }
java
public com.liferay.commerce.shipping.engine.fixed.service.CommerceShippingFixedOptionService getCommerceShippingFixedOptionService() { return commerceShippingFixedOptionService; }
python
def out(*args): """ Outputs its parameters to users stdout. """ for value in args: sys.stdout.write(value) sys.stdout.write(os.linesep)
java
@Override protected void outputPass() { if(!prototype.isOutputSupported()) return; // take a snapshot of the current container state. final LinkedList<Object> toOutput = new LinkedList<Object>(instances.keySet()); final Executor executorService = getOutputExecutorServic...
java
private List<Integer> getAtomNosForRingGroup(IAtomContainer molecule, List<Integer> ringGroup, IRingSet ringSet) { List<Integer> atc = new ArrayList<Integer>(); for (Integer i : ringGroup) { for (IAtom atom : ringSet.getAtomContainer(i).atoms()) { if (atc.size() > 0) { ...
java
private AFTPClient actionExists() throws PageException, IOException { required("item", item); AFTPClient client = getClient(); FTPFile file = existsFile(client, item, false); Struct cfftp = writeCfftp(client); cfftp.setEL(RETURN_VALUE, Caster.toBoolean(file != null)); cfftp.setEL(SUCCEEDED, Boolean.TRUE); ret...
python
def verlet(dfun, xzero, vzero, timerange, timestep): '''Verlet method integration. This function wraps the Verlet class. :param dfun: second derivative function of the system. The differential system arranged as a series of second-order equations: \ddot{X} = dfun(t, x) ...
python
def xml2object(self, content): r"""Convert xml content to python object. :param content: xml content :rtype: dict .. versionadded:: 1.2 """ content = self.xml_filter(content) element = ET.fromstring(content) tree = self.parse(element) if self.__options['...
java
protected void setCurrentPage(WizardPage<DATA> newPage) { currentPage = newPage; updateState(); wizardView.setCurrentPage(currentPage); currentPage.show(); }
python
def save_bookmark(self, slot_num): """Save current line and position as bookmark.""" bookmarks = CONF.get('editor', 'bookmarks') editorstack = self.get_current_editorstack() if slot_num in bookmarks: filename, line_num, column = bookmarks[slot_num] if osp.is...
python
def p_sigtypes(self, p): 'sigtypes : sigtypes sigtype' p[0] = p[1] + (p[2],) p.set_lineno(0, p.lineno(1))
python
def type(self, name: str): """return the first complete definition of type 'name'""" for f in self.body: if (hasattr(f, '_ctype') and f._ctype._storage == Storages.TYPEDEF and f._name == name): return f
java
public SummarizeResultsInner summarizeForResource(String resourceId, QueryOptions queryOptions) { return summarizeForResourceWithServiceResponseAsync(resourceId, queryOptions).toBlocking().single().body(); }
java
@SuppressWarnings("WeakerAccess") @Internal @UsedByGeneratedCode protected final Object getBeanForField(BeanResolutionContext resolutionContext, BeanContext context, FieldInjectionPoint injectionPoint) { Class beanType = injectionPoint.getType(); if (beanType.isArray()) { Collect...
java
@SuppressWarnings("unused") public List<WsByteBuffer> decompress(WsByteBuffer buffer) throws DataFormatException { List<WsByteBuffer> output = new LinkedList<WsByteBuffer>(); output.add(buffer); this.size += buffer.remaining(); return output; }
java
@CodingStyleguideUnaware public static <T extends Collection <?>> T notEmpty (final T aValue, @Nonnull final Supplier <? extends String> aName) { notNull (aValue, aName); if (isEnabled ()) if (aValue.isEmpty ()) throw new IllegalArgumentException ("The value of the collection '" + aName.get ()...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "decimalMinutes") public JAXBElement<BigDecimal> createDecimalMinutes(BigDecimal value) { return new JAXBElement<BigDecimal>(_DecimalMinutes_QNAME, BigDecimal.class, null, value); }
python
def variational_expectations(self, Y, m, v, gh_points=None, Y_metadata=None): """ Use Gauss-Hermite Quadrature to compute E_p(f) [ log p(y|f) ] d/dm E_p(f) [ log p(y|f) ] d/dv E_p(f) [ log p(y|f) ] where p(f) is a Gaussian with mean m and variance v. The shapes...
java
@Override public JsonNode visit(Comparator op, JsonNode input) { JsonNode lhsNode = op.getLhsExpr().accept(this, input); JsonNode rhsNode = op.getRhsExpr().accept(this, input); if (op.matches(lhsNode, rhsNode)) { return BooleanNode.TRUE; } return BooleanNode.FALS...
python
def validate(self, value): """Does value meet parameter requirements?""" if self.type is not None: value = coerce(self.type, value) if self.min is not None and value < self.min: raise ValueError('%s=%s is less than %s' % (self.name, value, ...
java
@Nullable public static String getPathInfo (@Nonnull final HttpServletRequest aHttpRequest) { ValueEnforcer.notNull (aHttpRequest, "HttpRequest"); final String sPathInfo = ServletHelper.getRequestPathInfo (aHttpRequest); if (StringHelper.hasNoText (sPathInfo)) return sPathInfo; return getWit...
java
public static byte[] decode(String s) { int len = s.length(); if (len % 2 != 0) { return null; } byte[] bytes = new byte[len / 2]; int pos = 0; for (int i = 0; i < len; i += 2) { byte hi = (byte) Character.digit(s.charAt(i), 1...
python
def parse_hs2015(heilman_filepath): """convert the output of the Heilman and Sagae (2015) discourse parser into a nltk.ParentedTree instance. Parameters ---------- heilman_filepath : str path to a file containing the output of Heilman and Sagae's 2015 discourse parser Returns ...
python
def findBestMatch(self, needle, similarity): """ Find the best match for ``needle`` that has a similarity better than or equal to ``similarity``. Returns a tuple of ``(position, confidence)`` if a match is found, or ``None`` otherwise. *Developer's Note - Despite the name, this method actually...
java
private void checkErrorStream(Process process) throws Exception { // rrdtool should use platform encoding (unless you did something // very strange with your installation of rrdtool). So let's be // explicit and use the presumed correct encoding to read errors. try ( InputStream is = process.getErrorStream(...
java
public int compareTo(WordTag wordTag) { int first = (word != null ? word().compareTo(wordTag.word()) : 0); if(first != 0) return first; else { if (tag() == null) { if (wordTag.tag() == null) return 0; else return -1; } return tag().c...
java
private int readInt() { String tag = readWord(); try { int radix = 10; if (tag.startsWith("0x") || tag.startsWith("0X")) { tag = tag.substring("0x".length()); radix = 16; } return Integer.valueOf(tag, radix); } catch (Exception e) { throw unexpected("expected an...
java
private void checkFileType() { if ((m_fileInput != null) && (m_replaceInfo != null) && (m_fileWidget != null)) { CmsFileInfo file = m_fileInput.getFiles()[0]; if (!m_replaceInfo.getSitepath().endsWith(file.getFileSuffix())) { Widget warningImage = FontOpenCms.WARNIN...
python
def read_sql(self, code: str) -> pandas.DataFrame: """Evaluate a Spark SQL satatement and retrieve the result. :param code: The Spark SQL statement to evaluate. """ if self.kind != SessionKind.SQL: raise ValueError("not a SQL session") output = self._execute(code) ...
java
public void init(SharedBaseRecordTable sharedTable, RecordOwnerParent parent, FieldList recordMain, Map<String, Object> properties) { m_sharedTable = sharedTable; super.init(parent, recordMain, properties); }
java
Delta newMoveStart(Storage src, String destUuid, String destPlacement, int destShardsLog2) { return Deltas.mapBuilder() .update(STORAGE.key(), Deltas.mapBuilder() .update(src.getUuidString(), Deltas.mapBuilder() .put(Storage.MOVE_TO.key(), ...
python
def get_logs(self, unique_id, logs, directory, pattern=constants.FILTER_NAME_ALLOW_NONE): """deprecated name for fetch_logs""" self.fetch_logs(unique_id, logs, directory, pattern)
java
public void setOutputKeys(java.util.Collection<String> outputKeys) { if (outputKeys == null) { this.outputKeys = null; return; } this.outputKeys = new com.amazonaws.internal.SdkInternalList<String>(outputKeys); }
python
def db_url_from_hass_config(path): """Find the recorder database url from a HASS config dir.""" config = load_hass_config(path) default_path = os.path.join(path, "home-assistant_v2.db") default_url = "sqlite:///{}".format(default_path) recorder = config.get("recorder") if recorder: db_...
java
private AttributesImpl processFormatDitamap(final Attributes atts, final AttributesImpl modified) { if (job == null) { return modified; } AttributesImpl res = modified; final String cls = atts.getValue(ATTRIBUTE_NAME_CLASS); if (MAP_TOPICREF.matches(cls)) { ...
python
def simulationStep(self, step=0): """ Make a simulation step and simulate up to the given millisecond in sim time. If the given value is 0 or absent, exactly one step is performed. Values smaller than or equal to the current sim time result in no action. """ self._queue.a...
java
public JBBPDslBuilder Long(final String name) { final Item item = new Item(BinType.LONG, name, this.byteOrder); this.addItem(item); return this; }
python
def delete(self): """Deletes matching objects from the Repository Does not throw error if no objects are matched. Returns the number of objects matched (which may not be equal to the number of objects deleted if objects rows already have the new value). """ # Fetch ...
python
def run_spec(spec, benchmark_hosts, result_hosts=None, output_fmt=None, logfile_info=None, logfile_result=None, action=None, fail_if=None, sample_mode='reservoir'): """Run a spec file, executing the statements on...
java
private static @CheckForNull TypeQualifierAnnotation getDefaultTypeQualifierAnnotationForParameters(XMethod xmethod, TypeQualifierValue<?> typeQualifierValue, boolean stopAtMethodScope) { if (xmethod.isSynthetic()) { return null; // synthetic methods don't get default annota...