language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_staff_url(self): """ Return the Admin URL for the current view. By default, it uses the :func:`get_staff_object` function to base the URL on. """ object = self.get_staff_object() if object is not None: # View is likely using SingleObjectMixin ...
java
public Properties getSystemProperties() throws Exception { final String[] address = { CORE_SERVICE, PLATFORM_MBEAN, "type", "runtime" }; final ModelNode op = createReadAttributeRequest(true, "system-properties", Address.root().add(address)); final ModelNode results = execute(op); if (isS...
java
public void registerGraph(long graphId, @NonNull SameDiff graph, ExecutorConfiguration configuration) { val g = graph.asFlatGraph(graphId, configuration); val v = blockingStub.registerGraph(g); if (v.status() != 0) throw new ND4JIllegalStateException("registerGraph() gRPC call failed...
python
def _set_windows(self, ticks, bars): """ be aware of default windows """ self.tick_window = ticks self.bar_window = bars
python
def get_user_data_triplet(username, password): """Print out user data triplet: username, password verifier, salt.""" context = SRPContext(username, password) username, password_verifier, salt = context.get_user_data_triplet(base64=True) click.secho('Username: %s' % username) click.secho('Password v...
python
def compile(stream_spec, cmd='ffmpeg', overwrite_output=False): """Build command-line for invoking ffmpeg. The :meth:`run` function uses this to build the commnad line arguments and should work in most cases, but calling this function directly is useful for debugging or if you need to invoke ffmpeg ...
java
private static List<ProtoFile> findRelateProtoFiles(File file, Set<String> dependencyNames) throws IOException { LinkedList<ProtoFile> protoFiles = new LinkedList<ProtoFile>(); ProtoFile protoFile = ProtoSchemaParser.parse(file); protoFiles.addFirst(protoFile); String parent = file.getP...
java
public void removeNotificationHandler(String serviceName, NotificationHandler handler){ ServiceInstanceUtils.validateServiceName(serviceName); if (handler == null) { throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR, ErrorCode.SERVICE_DIRECTORY_N...
java
protected boolean containsFlag(final char flag, final String flags) { if (flags == null) return false; return flags.indexOf(flag) >= 0; }
java
public ElementWithOptions setOptions(LinkedHashMap<String, String> options) { this.optionGroups.clear(); for (Map.Entry<String, String> entry : options.entrySet()) { this.addOption(entry.getKey(), entry.getValue()); } return this; }
python
def get_interface_detail_output_interface_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output"...
java
@Override public CommerceOrder findByG_C_Last(long groupId, long commerceAccountId, OrderByComparator<CommerceOrder> orderByComparator) throws NoSuchOrderException { CommerceOrder commerceOrder = fetchByG_C_Last(groupId, commerceAccountId, orderByComparator); if (commerceOrder != null) { return commerc...
java
public static <T extends Enum<T>> T valueOf(final Class<T> enumType, final String name) { return valueOf(enumType, name, null); }
python
def save(self, data=None, shape=None, dtype=None, returnoffset=False, photometric=None, planarconfig=None, extrasamples=None, tile=None, contiguous=True, align=16, truncate=False, compress=0, rowsperstrip=None, predictor=False, colormap=None, description=None, datetim...
python
def login_required(f): """Decorator function to check if user is loged in. :raises: :class:`FMBaseError` if not logged in """ @wraps(f) def check_login(cls, *args, **kwargs): if not cls.logged_in: raise FMBaseError('Please login to use this method') return f(cls, *args...
java
public void reset() { Arrays.fill(mean, 0.); Arrays.fill(nmea, 0.); if(elements != null) { for(int i = 0; i < elements.length; i++) { Arrays.fill(elements[i], 0.); } } else { elements = new double[mean.length][mean.length]; } wsum = 0.; }
python
def _openssl_key_iv(passphrase, salt): """ Returns a (key, iv) tuple that can be used in AES symmetric encryption from a *passphrase* (a byte or unicode string) and *salt* (a byte array). """ def _openssl_kdf(req): if hasattr(passphrase, 'encode'): passwd = passphrase.encode('asc...
python
def get_objective_hierarchy_design_session(self): """Gets the session for designing objective hierarchies. return: (osid.learning.ObjectiveHierarchyDesignSession) - an ObjectiveHierarchyDesignSession raise: OperationFailed - unable to complete request raise: Unimplemen...
java
public Type glb(Type t, Type s) { if (s == null) return t; else if (t.isPrimitive() || s.isPrimitive()) return syms.errType; else if (isSubtypeNoCapture(t, s)) return t; else if (isSubtypeNoCapture(s, t)) return s; List<Type> closu...
python
def check_bounds(self, addr): """ Check whether the given address is within the array bounds. """ def is_boolean_array(arr): return hasattr(arr, 'dtype') and arr.dtype == bool def check_axis(x, size): if isinstance(x, (int, long, numpy.integer)): ...
python
def is_cep(numero, estrito=False): """Uma versão conveniente para usar em testes condicionais. Apenas retorna verdadeiro ou falso, conforme o argumento é validado. :param bool estrito: Padrão ``False``, indica se apenas os dígitos do número deverão ser considerados. Se verdadeiro, potenciais caract...
python
def split_seconds(seconds): """Split seconds into [day, hour, minute, second, ms] `divisor: 1, 24, 60, 60, 1000` `units: day, hour, minute, second, ms` >>> split_seconds(6666666) [77, 3, 51, 6, 0] """ ms = seconds * 1000 divisors = (1, 24, 60, 60, 1000) quotient, result = ...
java
@Override public R visitStartElement(StartElementTree node, P p) { return defaultAction(node, p); }
python
def load(self, filenames=None, goto=None, word='', editorwindow=None, processevents=True, start_column=None, set_focus=True, add_where='end'): """ Load a text file editorwindow: load in this editorwindow (useful when clicking on outline explorer with multi...
java
@VisibleForTesting static Iterable<SSTableReader> filterOldSSTables(List<SSTableReader> sstables, long maxSSTableAge, long now) { if (maxSSTableAge == 0) return sstables; final long cutoff = now - maxSSTableAge; return Iterables.filter(sstables, new Predicate<SSTableReader>()...
java
public static Date addDays(Date d, int days) { Calendar cal = Calendar.getInstance(); cal.setTime(d); cal.add(Calendar.DAY_OF_YEAR, days); return cal.getTime(); }
python
def db_url_config(cls, url, engine=None): """Pulled from DJ-Database-URL, parse an arbitrary Database URL. Support currently exists for PostgreSQL, PostGIS, MySQL, Oracle and SQLite. SQLite connects to file based databases. The same URL format is used, omitting the hostname, and using t...
python
def ln_from_etree(self, ln_element, context=''): """Parse rs:ln element from an etree, returning a dict of the data. Parameters: md_element - etree element <rs:md> context - context string for error reporting """ ln = {} # grab all understood attribute...
java
public static void changeSign( DMatrix6 a ) { a.a1 = -a.a1; a.a2 = -a.a2; a.a3 = -a.a3; a.a4 = -a.a4; a.a5 = -a.a5; a.a6 = -a.a6; }
python
def fit(self, X, y): """Build an accelerated failure time model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator ...
python
def clamped(values, output_min=0, output_max=1): """ Returns *values* clamped from *output_min* to *output_max*, i.e. any items less than *output_min* will be returned as *output_min* and any items larger than *output_max* will be returned as *output_max* (these default to 0 and 1 respectively). For...
java
private int assertToken(final StreamTokenizer tokeniser, Reader in, final String token) throws IOException, ParserException { return assertToken(tokeniser, in, token, false, false); }
python
def cj(job_ids): '''Simple implementation where joblist is expected to be a list of integers (job ids). The full grammar for this command allows more granular control.''' for job_id in job_ids: job_id_types = set(map(type, job_ids)) assert(len(job_id_types) == 1 and type(1) == j...
java
public Project updateProject(String oldProjectName, Project project) throws GreenPepperServerException { Project projectUpdated; try { sessionService.startSession(); sessionService.beginTransaction(); projectUpdated = projectDao.update(oldProjectName, project); ...
java
public static dbuser[] get(nitro_service service) throws Exception{ dbuser obj = new dbuser(); dbuser[] response = (dbuser[])obj.get_resources(service); return response; }
java
public static String absorbInputStream(InputStream input) throws IOException { byte[] bytes = StreamSupport.absorbInputStream(input); return new String(bytes); }
python
def relabel_map(label_image, mapping, key=lambda x, y: x[y]): r""" Relabel an image using the supplied mapping. The ``mapping`` can be any kind of subscriptable object. The respective region id is used to access the new value from the ``mapping``. The ``key`` keyword parameter can be used to su...
java
protected int max(int[] v) { int x = 0; for (int i : v) { if (i > x) x = i; } return x; }
java
public Object querySingleResult(String sql, String[] args, int column) { return db.querySingleResult(sql, args, column); }
java
protected final PrcBeginningInventoryLineGfr lazyGetPrcBeginningInventoryLineGfr( final Map<String, Object> pAddParam) throws Exception { @SuppressWarnings("unchecked") PrcBeginningInventoryLineGfr<RS> proc = (PrcBeginningInventoryLineGfr<RS>) this.processorsMap .get(PrcBeginningInventor...
java
public static String findTitle(final Document doc) { if (doc == null) return null; // loop through the child nodes until the title element is found final NodeList childNodes = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node n...
java
public ItemRef on(StorageEvent eventType, final OnItemSnapshot onItemSnapshot, final OnError onError) { if(eventType == StorageEvent.PUT) { this.get(onItemSnapshot, onError); } Event ev = new Event(eventType, this.table.name, this.primaryKeyValue, this.secondaryKeyValue, false, false, pushNotificationsEnabled,...
java
public void removeAtRange(int index, int size) { final int end = Math.min(mSize, index + size); for (int i = index; i < end; i++) { removeAt(i); } }
java
private String buildMessage(String firstMessageLine, int exceptionLine) { if (additionalLines.size() == 0) { return firstMessageLine; } StringBuffer message = new StringBuffer(); if (firstMessageLine != null) { message.append(firstMessageLine); } int linesToProcess = (exceptionLine ...
java
public void cleanup() { keys.cleanup(); counts.cleanup(); dictionary.cleanup(); // Decrement the dictionary memory by the total size of all the elements memoryEstimate.decrementDictionaryMemory(SizeOf.SIZE_OF_LONG * numElements); }
java
public Connector withParameters(java.util.Map<String, String> parameters) { setParameters(parameters); return this; }
java
@Override public void send(final SipMessage msg) { final DatagramPacket pkt = new DatagramPacket(toByteBuf(msg), getRemoteAddress()); channel().writeAndFlush(pkt); }
java
public void delete(String resourceGroupName, String name, Boolean forceDelete) { deleteWithServiceResponseAsync(resourceGroupName, name, forceDelete).toBlocking().last().body(); }
python
def ncores_used(self): """ Returns the number of cores used in this moment. A core is used if there's a job that is running on it. """ return sum(task.manager.num_cores for task in self if task.status == task.S_RUN)
python
def server(self): """ Returns :class:`plexapi.myplex.MyPlexResource` with server of current item. """ server = [s for s in self._server.resources() if s.clientIdentifier == self.machineIdentifier] if len(server) == 0: raise NotFound('Unable to find server with uuid %s' % self.machine...
python
def smoothed(mesh, angle): """ Return a non- watertight version of the mesh which will render nicely with smooth shading by disconnecting faces at sharp angles to each other. Parameters --------- mesh : trimesh.Trimesh Source geometry angle : float Angle in radians, adjacent...
python
def get_vnetwork_vms_input_datacenter(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_vms = ET.Element("get_vnetwork_vms") config = get_vnetwork_vms input = ET.SubElement(get_vnetwork_vms, "input") datacenter = ET.SubElement(...
python
def on_epoch_end(self, epoch, **kwargs:Any)->None: "Compare the value monitored to its best and maybe reduce lr." current = self.get_monitor_value() if current is None: return if self.operator(current - self.min_delta, self.best): self.best,self.wait = current,0 else: ...
java
public T error(CharSequence error) { if (view!=null && view instanceof TextView) { ((TextView) view).setError(error); } return self(); }
python
def item_enclosure_mime_type(self, item): """ Guess the enclosure's mimetype. Note: this method is only called if item_enclosure_url has returned something. """ mime_type, encoding = guess_type(self.cached_enclosure_url) if mime_type: return mime_type ...
python
def split_input(cls, mapper_spec): """Returns a list of shard_count input_spec_shards for input_spec. Args: mapper_spec: The mapper specification to split from. Must contain 'blob_keys' parameter with one or more blob keys. Returns: A list of BlobstoreInputReaders corresponding to th...
python
def add_process(self, name, cmd, quiet=False, env=None, cwd=None): """ Add a process to this manager instance. The process will not be started until :func:`~honcho.manager.Manager.loop` is called. """ assert name not in self._processes, "process names must be unique" proc...
java
public static Path leftShift(Path self, byte[] bytes) throws IOException { append(self, bytes); return self; }
java
public ScreenModel doServletCommand(ScreenModel screenParent) { String strCommand = this.getProperty(DBParams.COMMAND); if (strCommand != null) if (this.getTask() != null) if (this.getTask().getApplication() != null) if (strCommand.equalsIgnoreCase(thi...
python
def chart_range(self): """ Calculates the chart range from start and end. Downloads larger datasets (5y and 2y) when necessary, but defaults to 1y for performance reasons """ delta = datetime.datetime.now().year - self.start.year if 2 <= delta <= 5: return "5y...
java
public double getEstimate(final byte[] key) { if (key == null) { return Double.NaN; } checkMethodKeySize(key); final double est = maps_[0].getEstimate(key); if (est >= 0.0) { return est; } //key has been promoted final int level = -(int)est; final Map map = maps_[level]; return map.getEs...
python
def incoming_messages(self) -> t.List[t.Tuple[float, bytes]]: """Consume the receive buffer and return the messages. If there are new messages added to the queue while this funciton is being processed, they will not be returned. This ensures that this terminates in a timely manner. ...
java
public String getNodeData(String nodePath,String formId,String tableName,String dataColName,String idColName){ MicroMetaDao microDao=getInnerDao(); String select=dataColName+"->>'$."+dianNode(nodePath)+"' as dyna_data"; String sql="select "+select+" from "+tableName+" where "+idColName+"=?"; Object[] para...
java
public static ShortBuffer allocate (int capacity) { if (capacity < 0) { throw new IllegalArgumentException(); } ByteBuffer bb = ByteBuffer.allocateDirect(capacity * 2); bb.order(ByteOrder.nativeOrder()); return bb.asShortBuffer(); }
java
public String createPreparedStatementString(ControlBeanContext context, Connection connection, Method method, Object[] arguments) { final boolean callableStatement = setCallableStatement(arguments); StringBuilder sqlString = new StringBuilder(getPreparedS...
java
@Override public HandlerRegistration addClickHandler(final ClickHandler handler) { return anchor.addHandler(handler, ClickEvent.getType()); }
python
def simple_tokenize(name): """Simple tokenizer function to be used with the normalizers.""" last_names, first_names = name.split(',') last_names = _RE_NAME_TOKEN_SEPARATOR.split(last_names) first_names = _RE_NAME_TOKEN_SEPARATOR.split(first_names) first_names = [NameToken(n) if len(n) > 1 else Name...
java
private char matchPrefix(String str1, String str2) { //here always str1.startsWith(str2) colorless!color char rel = IMappingElement.IDK; int spacePos1 = str1.indexOf(' '); String suffix = str1.substring(str2.length()); if (-1 < spacePos1 && !suffixes.containsKey(suffix)) {//...
java
public void setCloudWatchLoggingOptionDescriptions(java.util.Collection<CloudWatchLoggingOptionDescription> cloudWatchLoggingOptionDescriptions) { if (cloudWatchLoggingOptionDescriptions == null) { this.cloudWatchLoggingOptionDescriptions = null; return; } this.cloudWatc...
python
def save(self, *args, **kwargs): """ **uid**: :code:`electiontype:{name}` """ self.uid = 'electiontype:{}'.format(self.slug) super(ElectionType, self).save(*args, **kwargs)
java
@SuppressWarnings("unchecked") public static <E> E createRecord(Class<E> type, Schema schema) { // Don't instantiate SpecificRecords or interfaces. if (isGeneric(type) && !type.isInterface()) { if (GenericData.Record.class.equals(type)) { return (E) GenericData.get().newRecord(null, schema); ...
java
public void addAnnotation(final Class<? extends Annotation> clazz) { if (field.isAnnotationPresent(clazz)) { addAnnotation(clazz, field.getAnnotation(clazz)); } }
python
def get_form(): """ Return the form to use for commenting. """ global form_class from fluent_comments import appsettings if form_class is None: if appsettings.FLUENT_COMMENTS_FORM_CLASS: from django.utils.module_loading import import_string form_class = import_str...
python
def get_command_line(self): """ Retrieves the command line with wich the program was started. @rtype: str @return: Command line string. @raise WindowsError: On error an exception is raised. """ (Buffer, MaximumLength) = self.get_command_line_block() Com...
python
def enterEvent( self, event ): """ Toggles the display for the tracker item. """ item = self.trackerItem() if ( item ): item.setVisible(True)
python
def PositionBox(position, *args, **kwargs): " Delegate the boxing. " obj = position.target return getattr(position.target, 'box_class', Box)(obj, *args, **kwargs)
java
public void start() throws IOException{ remote_sock.setSoTimeout(iddleTimeout); client_sock.setSoTimeout(iddleTimeout); log("Starting UDP relay server on "+relayIP+":"+relayPort); log("Remote socket "+remote_sock.getLocalAddress()+":"+ remote_sock.getLocalPort())...
python
def sliver_reader(filename_end_mask="*[0-9].mhd", sliver_reference_dir="~/data/medical/orig/sliver07/training/", read_orig=True, read_seg=False): """ Generator for reading sliver data from directory structure. :param filename_end_mask: file selection can be controlled with this parameter :param sliver_...
java
public static void addSpoiler(Message message, String lang, String hint) { message.addExtension(new SpoilerElement(lang, hint)); }
python
def generate_gdt(self, fs, gs, fs_size=0xFFFFFFFF, gs_size=0xFFFFFFFF): """ Generate a GlobalDescriptorTable object and populate it using the value of the gs and fs register :param fs: value of the fs segment register :param gs: value of the gs segment register :param ...
python
def console_map_ascii_codes_to_font( firstAsciiCode: int, nbCodes: int, fontCharX: int, fontCharY: int ) -> None: """Remap a contiguous set of codes to a contiguous set of tiles. Both the tile-set and character codes must be contiguous to use this function. If this is not the case you may want to use ...
python
def plot_confusion_matrix(cm, title="Confusion Matrix"): """Plots a confusion matrix for each subject """ import matplotlib.pyplot as plt import math plt.figure() subjects = len(cm) root_subjects = math.sqrt(subjects) cols = math.ceil(root_subjects) rows = math.ceil(subjects/cols) ...
java
@Trivial public static String doValidate(String value, ValueType valueType) { String vMsg = null; switch (valueType) { case VT_CLASS_RESOURCE: if (value.contains("\\")) { vMsg = "ANNO_UTIL_UNEXPECTED_BACKSLASH"; } else if (!value.endsW...
java
@Override public CPDefinitionLocalization[] findByCPDefinitionId_PrevAndNext( long cpDefinitionLocalizationId, long CPDefinitionId, OrderByComparator<CPDefinitionLocalization> orderByComparator) throws NoSuchCPDefinitionLocalizationException { CPDefinitionLocalization cpDefinitionLocalization = findByPrimaryKe...
java
public Matrix3d rotation(double angle, Vector3fc axis) { return rotation(angle, axis.x(), axis.y(), axis.z()); }
python
def autocomplete(request, app_label=None, model=None): """returns ``\\n`` delimited strings in the form <tag>||(#) GET params are ``q``, ``limit``, ``counts``, ``q`` is what the user has typed, ``limit`` defaults to 10, and ``counts`` can be "model", "all" or, if absent, will default to all - ie a site...
java
public static String findFirstWord(String buffer) { if (buffer.indexOf(SPACE_CHAR) < 0) return buffer; else { buffer = Parser.trim(buffer); int index = buffer.indexOf(SPACE_CHAR); if (index > 0) return buffer.substring(0, index); ...
python
def qnormal(mu, sigma, q, random_state): ''' mu: float or array_like of floats sigma: float or array_like of floats q: sample step random_state: an object of numpy.random.RandomState ''' return np.round(normal(mu, sigma, random_state) / q) * q
python
def filter_needs(needs, filter_string="", filter_parts=True, merge_part_with_parent=True): """ Filters given needs based on a given filter string. Returns all needs, which pass the given filter. :param merge_part_with_parent: If True, need_parts inherit options from their parent need :param filter_...
python
def parse_keyring(self, namespace=None): """Find settings from keyring.""" results = {} if not keyring: return results if not namespace: namespace = self.prog for option in self._options: secret = keyring.get_password(namespace, option.name) ...
python
def invoke(self, ctx): """Given a context, this invokes the attached callback (if it exists) in the right way. """ _maybe_show_deprecated_notice(self) if self.callback is not None: return ctx.invoke(self.callback, **ctx.params)
python
def load_from_output_metadata(output_metadata): """Set Impact Function based on an output of an analysis's metadata. If possible, we will try to use layers already in the legend and to not recreating new ones. We will keep the style for instance. :param output_metadata: Metadata from a...
python
def genty_repeat(count): """ To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @g...
java
private void initialize() { this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); this.setContentPane(getJPanel()); if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) { this.setSize(282, 118); } this.setDefaultCloseO...
java
private CompletableFuture<Void> executeConditionally(Function<Duration, CompletableFuture<Long>> indexOperation, Duration timeout) { TimeoutTimer timer = new TimeoutTimer(timeout); return UPDATE_RETRY .runAsync(() -> executeConditionallyOnce(indexOperation, timer), this.executor) ...
python
def rename(self, node): """ Renames given Node associated path. :param node: Node. :type node: ProjectNode or DirectoryNode or FileNode :return: Method success. :rtype: bool """ source = node.path base_name, state = QInputDialog.getText(self, "Re...
java
public static Function<Flux<Long>, Publisher<?>> instant() { return iterations -> iterations .flatMap(iteration -> Mono .just(0L) .doOnSubscribe(logDelay(Duration.ZERO)), 1); }
python
def log(self, logfile=None): """Log the ASCII traceback into a file object.""" if logfile is None: logfile = sys.stderr tb = self.plaintext.encode('utf-8', 'replace').rstrip() + '\n' logfile.write(tb)
java
@Override public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) { return cpDefinitionInventoryPersistence.findWithDynamicQuery(dynamicQuery); }
java
public EdgeIteratorState getOtherContinue(double prevLat, double prevLon, double prevOrientation) { int tmpSign; for (EdgeIteratorState edge : allowedOutgoingEdges) { GHPoint point = InstructionsHelper.getPointForOrientationCalculation(edge, nodeAccess); tmpSign = InstructionsHel...