language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public boolean statusUpdate(final String appName, final String id, final InstanceStatus newStatus, String lastDirtyTimestamp, final boolean isReplication) { if (super.statusUpdate(appName, id, newStatus, lastDirtyTimestamp, isReplicat...
java
public Object invokeStep(String remoteStepInvokerId, String stepTokenId, List<String> params) throws Exception { try { //call the remote method Object[] args = {remoteStepInvokerId, stepTokenId, ChorusContext.getContext().getSnapshot(), params}; String[] signature = {"java.la...
python
def disable_user(cls, username): """ Disable user """ cls.update_roles(username, []) ret = cls.exec_request('user/{}'.format(username), 'put', account_status=0) logger.debug(ret) if cls._response_ok(ret): logger.info("Disabled SeAT user with username %s" % username) ...
java
public void onClickRowView(NotificationBoard board, RowView rowView, NotificationEntry entry) { if (DBG) Log.v(TAG, "onClickRowView - " + entry.ID); }
java
public static short optionalShortAttribute( final XMLStreamReader reader, final String localName, final short defaultValue) { return optionalShortAttribute(reader, null, localName, defaultValue); }
java
protected void generateExpressionAppender() { final TypeReference builderInterface = getExpressionBuilderInterface(); final TypeReference appender = getCodeElementExtractor().getElementAppenderImpl("Expression"); //$NON-NLS-1$ final StringConcatenationClient content = new StringConcatenationClient() { @Overrid...
java
protected <S> S withFreshBuilder(Function<UriComponentsBuilder, S> function) { Assert.notNull(function, "Function must not be null!"); return function.apply(builder.cloneBuilder()); }
java
private static boolean indexesAreDups(Index idx1, Index idx2) { // same attributes? if (idx1.getType() != idx2.getType()) { return false; } if (idx1.getCountable() != idx2.getCountable()) { return false; } if (idx1.getUnique() != idx2.getUnique()) ...
java
public static String getFileAsString(File file) throws FileNotFoundException, IOException { byte[] inputbytes; try (RandomAccessFile inputFile = new RandomAccessFile(file, "r")) { int length = (int) inputFile.length(); inputbytes = new byte[length]; int numread = inp...
java
public double getSum() { double sum = s.zero(); for (int c = 0; c < this.values.length; c++) { sum = s.plus(sum, values[c]); } return sum; }
python
def get_orm_columns(cls: Type) -> List[Column]: """ Gets :class:`Column` objects from an SQLAlchemy ORM class. Does not provide their attribute names. """ mapper = inspect(cls) # type: Mapper # ... returns InstanceState if called with an ORM object # http://docs.sqlalchemy.org/en/latest...
java
public static List<Scanner> getScanners(final Query query) { final List<Scanner> scanners = new ArrayList<Scanner>( Const.SALT_WIDTH() > 0 ? Const.SALT_BUCKETS() : 1); if (Const.SALT_WIDTH() > 0) { for (int i = 0; i < Const.SALT_BUCKETS(); i++) { scanners.add(((TsdbQuery) query).getScanner...
java
private CellFormatResult getErrorCellValue(final Cell cell, final Locale locale) { final CellType cellType = cell.getCellTypeEnum(); assert cellType == CellType.ERROR; return getErrorCellValue(cell.getErrorCellValue(), locale); }
python
def _move_update(sourcepath, destname): """Move source to dest only if source is newer.""" if sys.platform.startswith('linux'): return os.system("/bin/mv -fu '%s' '%s'" % (sourcepath, destname)) else: return os.system("rsync -ua --remove-source-files '%s' '%s'" % (sourcepath, destname))
java
@Override public Object getCurrentVersion(Serializable id, SharedSessionContractImplementor session) throws HibernateException { if ( log.isTraceEnabled() ) { log.trace( "Getting version: " + MessageHelper.infoString( this, id, getFactory() ) ); } final Tuple resultset = getFreshTuple( EntityKeyBuilder.fromP...
java
public static boolean checkSLayer(String layerName, SNode node) { //robustness if (layerName == null || node == null) { return false; } Set<SLayer> sLayers = node.getLayers(); if (sLayers != null) { for (SLayer l : sLayers) { Collection<Label> labels = l.getLabel...
python
def get(self, key, namespace=None): """Retrieve value for key.""" if not self.path: return NO_VALUE logger.debug('Searching %r for key: %s, namepsace: %s', self, key, namespace) full_key = generate_uppercase_key(key, namespace) return get_key_from_envs(self.cfg, full...
java
public static HashMap<String, ArrayList<String>> getIcnDistribution(HashMap data, String icin) { HashMap<String, ArrayList<String>> results = new HashMap<String, ArrayList<String>>(); ArrayList<HashMap<String, String>> soilLayers; soilLayers = getSoilLayer(data); icin = sum(icin); ...
python
def get_protocol_from_name(name): """ Returns the protocol class for the protocol with the given name. :type name: str :param name: The name of the protocol. :rtype: Protocol :return: The protocol class. """ cls = protocol_map.get(name) if not cls: raise ValueError('Unsupp...
python
def init0(self, dae): """Set initial p and q for power flow""" self.p0 = matrix(self.p, (self.n, 1), 'd') self.q0 = matrix(self.q, (self.n, 1), 'd')
java
private static <S extends Solution<?>> double[] getNadirValues(List<S> solutionsList) { ArrayFront front = new ArrayFront(solutionsList); FrontExtremeValues extremeValues = new FrontExtremeValues(); List<Double> list = extremeValues.findHighestValues(front); return toArray(list); }
java
public synchronized void clear() { _layerCache.clear(); _moduleCache.clear(); _gzipCache.clear(); for (IGenericCache cache : _namedCaches.values()) { cache.clear(); } }
python
def validate_query_params(self, request): """ Validate that query params are in the list of valid query keywords in :py:attr:`query_regex` :raises ValidationError: if not. """ # TODO: For jsonapi error object conformance, must set jsonapi errors "parameter" for #...
python
def _post(self, *args, **kwargs): """ Make a POST request. """ data = self._default_data() data.update(kwargs.get('data') or {}) kwargs['data'] = data return self._request(requests.post, *args, **kwargs)
java
public FileServerInner getByResourceGroup(String resourceGroupName, String fileServerName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, fileServerName).toBlocking().single().body(); }
python
def get_ids(self, request_data, parameter_name='ids'): """Extract a list of integers from request data.""" if parameter_name not in request_data: raise ParseError("`{}` parameter is required".format(parameter_name)) ids = request_data.get(parameter_name) if not isinstance(id...
python
def _base64_encode(self, string_to_encode): """ Base64 encodes a string, with either Python 2 or 3. :param string_to_encode: the string to encode """ try: # python 2 return base64.b64encode(string_to_encode) except TypeError: # python 3 ...
python
def send(self, payload): """ Send a payload to exchange to containing command and payload to the queue specified in config. :param command: str: name of the command we want run by WorkQueueProcessor :param payload: str: string data that will be put into the exchange's message body ...
python
def _translate_add(self, oprnd1, oprnd2, oprnd3): """Return a formula representation of an ADD instruction. """ assert oprnd1.size and oprnd2.size and oprnd3.size assert oprnd1.size == oprnd2.size op1_var = self._translate_src_oprnd(oprnd1) op2_var = self._translate_src_...
python
def _Main(self): """The main loop.""" # We need a resolver context per process to prevent multi processing # issues with file objects stored in images. resolver_context = context.Context() for credential_configuration in self._processing_configuration.credentials: resolver.Resolver.key_chain....
python
def create_rl_lin_comb_method(op_name, klass, x_roles, y_roles): """ Creates a new binary special method with left and right versions, such as A.__mul__(B) <=> A*B, A.__rmul__(B) <=> [B*A if B.__mul__(A) fails] for target class. The method is called __op_name__. """ # This function w...
python
def get_instances_in_role(self, role, state_filter=None): """ Get all the instances in a role, filtered by state. @param role: the name of the role @param state_filter: the state that the instance should be in (e.g. "running"), or None for all states """ self._check_role_name(role) in...
python
def save_bookmarks(filename, bookmarks): """Save all bookmarks from specific file to config.""" if not osp.isfile(filename): return slots = load_bookmarks_without_file(filename) for slot_num, content in bookmarks.items(): slots[slot_num] = [filename, content[0], content[1]] CONF.set(...
java
protected final FluentModelTImpl prepareInlineDefine(FluentModelTImpl model) { FluentModelTImpl childResource = find(model.childResourceKey()); if (childResource != null) { throw new IllegalArgumentException(pendingOperationMessage(model.name(), model.childResourceKey())); } ...
java
public static Pair<String, String> getAndValidateKeyValuePair(final String keyValueString) throws InvalidKeyValueException { String tempInput[] = StringUtilities.split(keyValueString, '=', 2); // Remove the whitespace from each value in the split array tempInput = CollectionUtilities.trimStringA...
python
def files_in_to_out(self, in_path, out_path=None): """Write in files to out, calling the line_handler on each line. Calls file_in_to_out under the hood to format the in_path payload. The formatting processing is done by the self.formatter instance. Args: in_path: str, path-...
python
def callback(self): """ Generate callback url for provider """ next = request.args.get('next') or None endpoint = 'social.{}.handle'.format(self.provider) return url_for(endpoint, _external=True, next=next)
java
public Photos search(SearchParameters searchParameters) throws JinxException { JinxUtils.validateParams(searchParameters); Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.search"); if (!JinxUtils.isNullOrEmpty(searchParameters.getUserId())) { params.put("user_id",...
python
def validate(self): """Validate that the Between Expression is correctly representable.""" if not isinstance(self.field, LocalField): raise TypeError(u'Expected LocalField field, got: {} {}'.format( type(self.field).__name__, self.field)) if not isinstance(self.lower...
python
def find_packages( self, name, # type: str constraint=None, # type: Union[VersionConstraint, str, None] extras=None, # type: Union[list, None] allow_prereleases=False, # type: bool ): # type: (...) -> List[Package] """ Find packages on the remote server. ...
java
@SuppressWarnings("TypeParameterUnusedInFormals") public <T extends GraphQLType> T decorate(GraphQLType objectType) { GraphQLType out = objectType; Stack<Class<?>> wrappingStack = new Stack<>(); wrappingStack.addAll(this.decoration); while (!wrappingStack.isEmpty()) { Cl...
java
public BeanConfiguration addAbstractBean(String name) { BeanConfiguration bc = new DefaultBeanConfiguration(name); bc.setAbstract(true); registerBeanConfiguration(name, bc); return bc; }
python
def get_server(server_class, server_address, request_handler_class): """ Return instance of :param:`server_class` with :param:`request_handler` bound to it. This method also binds a :func:`route` method to the server instance. >>> server = get_server(TcpServer, ('localhost', 502), RequestHandler) ...
python
def purge(self): """ Clean old transactions """ while not self.stopped.isSet(): self.stopped.wait(timeout=defines.EXCHANGE_LIFETIME) self._messageLayer.purge()
python
def _timeoutRequest(self, msgId): """ Cancel timedout request. @param msgId: message ID to cancel @type msgId: C{str} """ d, _ = self._requests.pop(msgId, (None, None)) if not d.called: d.errback(ZmqRequestTimeoutError(msgId))
java
public static void appendSchemeHostPort(StringBuilder url, String scheme, String server, int port) { url.append(scheme).append("://").append(HostPort.normalizeHost(server)); if (port > 0) { switch (scheme) { case "http": if (port != 80) ...
java
public void registerFlushDelay (Class<?> objclass, long delay) { _delays.put(objclass, Long.valueOf(delay)); }
java
public static void copy(File source, File dest) throws IOException { if (dest.isDirectory()) { dest = new File(dest + File.separator + source.getName()); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = n...
java
public CreateApplicationRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
private void getParseBytesMethodCode(MethodCode mc) { StringBuilder code = new StringBuilder(); // define return code.append(ClassHelper.getInternalName(cls.getCanonicalName())).append(" ret = new "); code.append(ClassHelper.getInternalName(cls.getCanonicalName())).append("()"); ...
java
@SuppressWarnings("static-method") public boolean isAssigned(final EObject object) { assert object != null; return object.eAdapters().contains(ASSIGNMENT_MARKER); }
java
public static Single<Long> incrementByValue(String cacheKey, long value) { return incrementByValue(CacheService.CACHE_CONFIG_BEAN, cacheKey, value); }
python
def read_message_type(file): """Read the message type from a file.""" message_byte = file.read(1) if message_byte == b'': return ConnectionClosed message_number = message_byte[0] return _message_types.get(message_number, UnknownMessage)
python
def client_get(self, url, **kwargs): """Send GET request with given url.""" response = requests.get(self.make_url(url), headers=self.headers) if not response.ok: raise Exception( '{status}: {reason}.\nCircleCI Status NOT OK'.format( status=response...
python
def gen_tx(self): """Generate a :class:`Transaction <stellar_base.transaction.Transaction>` object from the list of operations contained within this object. :return: A transaction representing all of the operations that have been appended to this builder. :rtype: :cl...
python
def generate_quadrature( order, domain, accuracy=100, sparse=False, rule="C", composite=1, growth=None, part=None, normalize=False, **kws ): """ Numerical quadrature node and weight generator. Args: order (int): The order of the quadrature. domain (numpy.ndarray,...
python
def augment_visit(linter, checker_method, augmentation): """ Augmenting a visit enables additional errors to be raised (although that case is better served using a new checker) or to suppress all warnings in certain circumstances. Augmenting functions should accept a 'chain' function, which runs the ch...
java
public DeleteFleetsRequest withFleetIds(String... fleetIds) { if (this.fleetIds == null) { setFleetIds(new com.amazonaws.internal.SdkInternalList<String>(fleetIds.length)); } for (String ele : fleetIds) { this.fleetIds.add(ele); } return this; }
java
public CacheEntry readCacheEntry(Object id) { // SKS-O Result result = htod.readCacheEntry(id); if (result.returnCode == HTODDynacache.DISK_EXCEPTION) { stopOnError(result.diskException); this.htod.returnToResultPool(result); return null; } CacheEntry ...
python
def _create_permissions(**kwargs): """ Almost exactly the same as django.contrib.auth.management.__init__.py """ from django.contrib.contenttypes.models import ContentType object_tools.autodiscover() tools = object_tools.tools._registry # This will hold the permissions we're looking for as...
python
def sky_within(self, ra, dec, degin=False): """ Test whether a sky position is within this region Parameters ---------- ra, dec : float Sky position. degin : bool If True the ra/dec is interpreted as degrees, otherwise as radians. Def...
java
public static String encodeBase32(final byte[] data, final boolean chunked) { if (chunked) { return BASE32_CHUNKED_ENCODER.encodeToString(data).trim(); } return BASE32_UNCHUNKED_ENCODER.encodeToString(data).trim(); }
java
public static int setSynchronized(int modifier, boolean b) { if (b) { return (modifier | SYNCHRONIZED) & (~VOLATILE & ~TRANSIENT & ~INTERFACE); } else { return modifier & ~SYNCHRONIZED; } }
python
def tarjan(graph): """Strongly connected components by Tarjan, iterative implementation :param graph: directed graph in listlist format, cannot be listdict :returns: list of lists for each component :complexity: linear """ n = len(graph) dfs_num = [None] * n dfs_min = [n] * n waitin...
python
def add(self, child): """ Adds a typed child object to the behavioral object. @param child: Child object to be added. """ if isinstance(child, StateVariable): self.add_state_variable(child) elif isinstance(child, DerivedVariable): self.add_derive...
python
def mkdir(self, path): """ create a directory if it does not exist. """ if not os.path.exists(path): os.makedirs(path)
python
def get_top_submissions(course_id, item_id, item_type, number_of_top_scores, use_cache=True, read_replica=True): """Get a number of top scores for an assessment based on a particular student item This function will return top scores for the piece of assessment. It will consider only the latest and greater ...
python
def getargs(obj): """Get the names and default values of a function's arguments""" if inspect.isfunction(obj) or inspect.isbuiltin(obj): func_obj = obj elif inspect.ismethod(obj): func_obj = get_meth_func(obj) elif inspect.isclass(obj) and hasattr(obj, '__init__'): func_obj = get...
python
def from_dict(doc): """Create a model output file object from a dictionary. """ if 'path' in doc: path = doc['path'] else: path = None return ModelOutputFile( doc['filename'], doc['mimeType'], path=path )
python
def update_by_example(cls, collection, example_data, new_value, keep_null=False, wait_for_sync=None, limit=None): """ This will find all documents in the collection that match the specified example object, and partially update the document body with the new value specified. Note that doc...
java
public @Nonnull <T> T getBean(@Nullable BeanResolutionContext resolutionContext, @Nonnull Class<T> beanType, @Nullable Qualifier<T> qualifier) { ArgumentUtils.requireNonNull("beanType", beanType); return getBeanInternal(resolutionContext, beanType, qualifier, true, true); }
python
def wait_for_reactor(self, function): """ DEPRECATED, use wait_for(timeout) instead. A decorator that ensures the wrapped function runs in the reactor thread. When the wrapped function is called, its result is returned or its exception raised. Deferreds are handled tran...
java
public void displayContent(String repository, String workspace, String path, boolean changeHistory) { contents.show(repository, workspace, path, changeHistory); displayRepository(repository); display(contents); changeRepositoryInURL(repository, changeHistory); }
java
public void start () { if (config.activationKey != null) { input().keyboardEvents.connect(new Slot<Keyboard.Event>() { public void onEmit (Keyboard.Event event) { if (event instanceof Keyboard.KeyEvent) { Keyboard.KeyEvent kevent = (Keyboard.KeyEvent)event; if (kevent...
java
public <T extends Serializer<?> & Serializable>void registerTypeWithKryoSerializer(Class<?> type, T serializer) { if (type == null || serializer == null) { throw new NullPointerException("Cannot register null class or serializer."); } registeredTypesWithKryoSerializers.put(type, new SerializableSerializer<>(s...
python
def contains(self, pt): "Tests if the provided point is in the polygon." if isinstance(pt, Point): ptx, pty = pt.x, pt.y assert (self.spatialReference is None or \ self.spatialReference.wkid is None) or \ (pt.spatialReference is None or \ ...
java
public static void main(String[] args) { try { Twitter twitter = new TwitterFactory().getInstance(); int page = 1; List<User> users; do { users = twitter.getBlocksList(page); for (User user : users) { System.out....
python
def clear(self): """ Removes all data from the buffer. """ self.io.seek(0) self.io.truncate() for item in self.monitors: item[2] = 0
java
@Execute public HtmlResponse index(final ListForm form) { saveToken(); validate(form, messages -> {}, () -> asHtml(path_AdminError_AdminErrorJsp)); return asListHtml(); }
java
public static base_responses update(nitro_service client, systemuser resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { systemuser updateresources[] = new systemuser[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i] = ne...
python
def OPTIONS(self, authenticate=True): """Request options device supports.""" message = "OPTIONS " + self.session.url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication if authenticate else '' message += self.user_agent message += self.session_id ...
java
@Nullable public static int[] optIntArray(@Nullable Bundle bundle, @Nullable String key) { return optIntArray(bundle, key, new int[0]); }
python
def absent(name, vname=None, use_32bit_registry=False): r''' Ensure a registry value is removed. To remove a key use key_absent. Args: name (str): A string value representing the full path of the key to include the HIVE, Key, and all Subkeys. For example: ``HKEY...
java
private CMFolder rawCreateFolder( CMFolder cmParentFolder, String name ) { StringBuilder innerXml = new StringBuilder(); innerXml.append( "<folder id='" ).append( cmParentFolder.getId() ).append( "'/>" ); innerXml.append( "<childFolder>" ).append( XmlUtils.escape( name ) ).append( "</childFo...
java
void clear() { for(int i=0; i<LEVEL; i++) { priorityQueues.get(i).clear(); } raidQueue.clear(); }
java
public static systemcounters[] get(nitro_service service, systemcounters_args args) throws Exception{ systemcounters obj = new systemcounters(); options option = new options(); option.set_args(nitro_util.object_to_string_withoutquotes(args)); systemcounters[] response = (systemcounters[])obj.get_resources(servi...
java
private static void buildBulkMutationsSettings(Builder builder, BigtableOptions options) { BulkOptions bulkOptions = options.getBulkOptions(); BatchingSettings.Builder batchBuilder = builder.bulkMutateRowsSettings().getBatchingSettings().toBuilder(); long autoFlushMs = bulkOptions.getAutoflus...
java
private String buildAncestryKey(final FeatureCode level, final boolean includeSelf) { // if we have reached the root level, stop if (level == null) { return ""; } String keyPart; FeatureCode nextLevel; switch (level) { case ADM4: k...
python
def scan(repos, options): """Given a repository list [(path, vcsname), ...], scan each of them.""" ignore_set = set() repos = repos[::-1] # Create a queue we can push and pop from while repos: directory, dotdir = repos.pop() ignore_this = any(pat in directory for pat in options.ignore_p...
python
def __check_mapping(self, landmarks): """ Checks whether the image, from which the supplied landmarks were extracted, can be transformed to the learned standard intensity space without loss of information. """ sc_udiff = numpy.asarray(self.__sc_umaxs)[1:] - numpy.asarray(...
java
private Node getQualifiedMemberAccess(Node member, ClassDeclarationMetadata metadata) { Node context = member.isStaticMember() ? metadata.getFullClassNameNode().cloneTree() : metadata.getClassPrototypeNode().cloneTree(); // context.useSourceInfoIfMissingFromForTree(member); c...
python
def Construct(self): # pylint: disable-msg=C0103 """Construct nuSTORM from a GDML file""" # Parse the GDML self.world = self.gdml_parser.GetWorldVolume() # Create sensitive detector self.sensitive_detector = ScintSD() # Get logical volume for X view, then attach SD ...
java
public static <T, C extends Cell<T, ?>> VirtualFlow<T, C> createVertical( ObservableList<T> items, Function<? super T, ? extends C> cellFactory, Gravity gravity) { return new VirtualFlow<>(items, cellFactory, new VerticalHelper(), gravity); }
python
def validate_number(self, number): """ Checks if a number looks somewhat like a E.164 number. Not an exhaustive check, as the API takes care of that """ if not isinstance(number, str): raise ElksException('Recipient phone number may not be empty') if number[0] == '+' ...
java
private void buildSectionTitle(MarkupDocBuilder markupDocBuilder, String title) { if (config.getPathsGroupedBy() == GroupBy.AS_IS) { markupDocBuilder.sectionTitleLevel3(title); } else { markupDocBuilder.sectionTitleLevel4(title); } }
java
public Bbox getMaximumBounds() { org.geomajas.gwt.client.spatial.Bbox box = mapView.getMaxBounds(); return new Bbox(box.getX(), box.getY(), box.getWidth(), box.getHeight()); }
java
private String getNameForType( Class<?> type ) { if ( _typeToStringMap.containsKey( type ) ) { return _typeToStringMap.get( type ); } for ( Entry<String, Class<?>> entry : _typeMappings.entrySet() ) { if ( entry.getValue().isAssignableFrom( type ) ) ...
java
@Override public ModelNode getModel() { synchronized (model) { // We return what is effectively a copy; force handlers to use writeModel, setWildcard or setNames to modify ModelNode result = new ModelNode(); ModelNode wildcard = result.get(WILDCARD.getName()); ...
java
public static List<Transaction> parseTransactionsFromPaymentMessage(NetworkParameters params, Protos.Payment paymentMessage) { final List<Transaction> transactions = new ArrayList<>(paymentMessage.getTransactionsCount()); for (final ByteString transaction : paymentMessage.getTransactionsList...
python
def authentication(self, event): """Links the client to the granted account and profile, then notifies the client""" try: self.log("Authorization has been granted by DB check:", event.username, lvl=debug) account, profile, clientconfig = event.userd...