language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_ajax(self, request, *args, **kwargs): """ Called when accessed via AJAX on the request method specified by the Datatable. """ response_data = self.get_json_response_object(self._datatable) response = HttpResponse(self.serialize_to_json(response_data), con...
java
public void doStatus(@Param("pageIndex") int pageIndex, @Param("searchKey") String searchKey, @Param("channelId") Long channelId, @Param("status") String status, Navigator nav) throws Webx...
python
def classify_elements(self, file, file_content_type=None, model=None, **kwargs): """ Classify the elements of a document. Analyzes the structural and semantic elements of a document. ...
python
def get_model_spec_ting(atomic_number): """ X_u_template[0:2] are teff, logg, vturb in km/s X_u_template[:,3] -> onward, put atomic number atomic_number is 6 for C, 7 for N """ DATA_DIR = "/Users/annaho/Data/LAMOST/Mass_And_Age" temp = np.load("%s/X_u_template_KGh_res=1800.npz" %DATA_DIR) ...
python
def _loadHandlers(self): """ creates a dictionary of named handler instances :return: the dictionary """ return {handler.name: handler for handler in map(self.createHandler, self.config['handlers'])}
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case SarlPackage.SARL_SKILL__EXTENDS: return getExtends(); case SarlPackage.SARL_SKILL__IMPLEMENTS: return getImplements(); } return super.eGet(featureID, resolve, coreType); }
python
def _parseAttrs(self, attrsStr): """ Parse the attributes and values """ attributes = dict() for attrStr in self.SPLIT_ATTR_COL_RE.split(attrsStr): name, vals = self._parseAttrVal(attrStr) if name in attributes: raise GFF3Exception( ...
java
private RedBlackTreeNode<Key, Value> rotateRight(RedBlackTreeNode<Key, Value> h) { // assert (h != null) && h.getLeft().isRed(); RedBlackTreeNode<Key, Value> x = h.getLeft(); h.setLeft(x.getRight()); x.setRight(h); x.setColor(x.getRight().getColor()); x.getRight().setColor(RED); x.setSize(h.getSize()); h.setSiz...
java
protected PreparedStatement statement(Connection connection, String query) throws SQLException { return connection.prepareStatement(query); }
java
@Override public T read( String in ) throws JsonDeserializationException { return read( in, JsonDeserializationContext.builder().build() ); }
java
public void writeVisibleDataStyles(final XMLUtil util, final Appendable appendable) throws IOException { final Iterable<DataStyle> dataStyles = this.dataStylesContainer .getValues(Dest.STYLES_COMMON_STYLES); for (final DataStyle dataStyle : dataStyles) { assert !d...
java
public GenericTemplateElementBuilder addLoginButton(String url) { Button button = ButtonFactory.createLoginButton(url); this.element.addButton(button); return this; }
java
public static Context getContextByName(JSONObject parameters, String parameterName) throws ApiException { return getContextByName(parameters.getString(parameterName)); }
java
public List<RuleMatch> check(AnnotatedText annotatedText, boolean tokenizeText, ParagraphHandling paraMode, RuleMatchListener listener) throws IOException { return check(annotatedText, tokenizeText, paraMode, listener, Mode.ALL); }
python
def gotoPrevious(self): """ Goes to the previous panel tab. """ index = self._currentPanel.currentIndex() - 1 if index < 0: index = self._currentPanel.count() - 1 self._currentPanel.setCurrentIndex(index)
python
def parse(cls, datestr): """Parse <DATE> string and make :py:class:`CalendarDate` from it. :param str datestr: String with GEDCOM date. """ m = DATE_RE.match(datestr) if m is not None: day = None if m.group(2) is None else int(m.group(2)) return cls(m.gro...
java
@Override public DBSecurityGroup createDBSecurityGroup(CreateDBSecurityGroupRequest request) { request = beforeClientExecution(request); return executeCreateDBSecurityGroup(request); }
python
def store_custom_data(self, ns, data, user_id): """ Store custom data. Store arbitrary user data as JSON. Arbitrary JSON data can be stored for a User. A typical scenario would be an external site/service that registers users in Canvas and wants to captu...
python
def updateAccount(self, subject, person, vendorSpecific=None): """See Also: updateAccountResponse() Args: subject: person: vendorSpecific: Returns: """ response = self.updateAccountResponse(subject, person, vendorSpecific) return self._rea...
java
@Deprecated public static Scriptable newObjectLiteral(Object[] propertyIds, Object[] propertyValues, Context cx, Scriptable scope) { // Passing null for getterSetters means no getters or setters return ne...
java
public static void register (PerformanceObserver obs, String name, long delta) { // get the observer's action hashtable Map<String, PerformanceAction> actions = _observers.get(obs); if (actions == null) { // create it if it didn't exist _observers.put(obs, actions = M...
python
def make_ttv_yaml(corpora, path_to_ttv_file, ttv_ratio=DEFAULT_TTV_RATIO, deterministic=False): """ Create a test, train, validation from the corpora given and saves it as a YAML filename. Each set will be subject independent, meaning that no one subject can have data in more than one set # Ar...
python
def register_rml_def(self, location_type, location, filename=None, **kwargs): """ Registers the rml file locations for easy access Args: ----- location_type: ['package_all', ...
java
public void dump() { Object allData[] = new Object[] { this, "EJBName = " + ivEjbName, "method name = " + ivMethodName, ...
java
protected void addPColRows(Table t, HsqlArrayList l, String cat, String schem, String pName, String cName, Integer cType, Integer dType, String tName, Integer prec, Integer len, Integer scale, Int...
java
@Override public ImageSource apply(ImageSource source) { int width = source.getWidth(); int height = source.getHeight(); int[][] result = new int[height][width]; if (source.isGrayscale()) { for (int i = 0; i < height; i++) { int iMin = Math.ma...
python
def revoke_user_token(self, user_id): """ Revoke user token Erases user token on file forcing them to re-login and obtain a new one. :param user_id: int :return: """ user = self.get(user_id) user._token = None self.save(user)
java
public boolean audit(Class<?> clazz, Method method, Object[] args) { return audit(new AnnotationAuditEvent(clazz, method, args)); }
python
def review(cls, content, log, parent, window_icon): # pragma: no cover """ Reviews the final bug report. :param content: content of the final report, before review :param parent: parent widget :returns: the reviewed report content or None if the review was ca...
python
def root(self): """Get the top level block device in the ancestry of this device.""" drive = self.drive for device in self._daemon: if device.is_drive: continue if device.is_toplevel and device.drive == drive: return device return N...
python
def _zero_pad_gaps(tr, gaps, fill_gaps=True): """ Replace padded parts of trace with zeros. Will cut around gaps, detrend, then pad the gaps with zeros. :type tr: :class:`osbpy.core.stream.Trace` :param tr: A trace that has had the gaps padded :param gaps: List of dict of start-time and end-ti...
python
def _pure_data(self, data: Any) -> Any: """ If data is dict-like object, convert it to pure dict instance, so it will be possible to pass to default ``jsonschema.validate`` func. :param data: Request or response data. """ if not isinstance(data, dict) and not isinstance(...
java
public static float[] generateMoments(IAtomContainer atomContainer) throws CDKException { // lets check if we have 3D coordinates Iterator<IAtom> atoms; int natom = atomContainer.getAtomCount(); Point3d ctd = getGeometricCenter(atomContainer); Point3d cst = new Point3d(); ...
python
def select(*queries, **kwargs): """ Builds a function that will execute the specified queries against a list of Nodes. """ def make_query(*args): def simple_query(nodes): if len(args) == 0: return nodes pred = args[0] results = [] ...
python
def get_plot(self, normalize_rxn_coordinate=True, label_barrier=True): """ Returns the NEB plot. Uses Henkelman's approach of spline fitting each section of the reaction path based on tangent force and energies. Args: normalize_rxn_coordinate (bool): Whether to normalize the...
java
public static void writeLong(long value, byte[] dest, int offset) throws IllegalArgumentException { if (dest.length < offset + 8) { throw new IllegalArgumentException( "Destination byte array does not have enough space to write long from offset " + offset); } long t = value; for (i...
java
private static int spinsFor(Node pred, boolean haveData) { if (MP && pred != null) { if (pred.isData != haveData) // phase change return FRONT_SPINS + CHAINED_SPINS; if (pred.isMatched()) // probably at front return FRONT_SPINS; ...
python
def safe_repr(self, obj): """Like a repr but without exception""" try: return repr(obj) except Exception as e: return '??? Broken repr (%s: %s)' % (type(e).__name__, e)
python
def active_brokers(self): """Return set of brokers that are not inactive or decommissioned.""" return { broker for broker in self._brokers if not broker.inactive and not broker.decommissioned }
python
def squash_children(self, options): """ reduces the memory footprint of this super-change by converting all child changes into squashed changes """ oldsubs = self.collect() self.changes = tuple(squash(c, options=options) for c in oldsubs) for change in oldsubs: ...
python
def to_weld_type(weld_type, dim): """Summary Args: weld_type (TYPE): Description dim (TYPE): Description Returns: TYPE: Description """ for i in xrange(dim): weld_type = WeldVec(weld_type) return weld_type
java
public static OAuthAccessTokenResponse getAccessTokenResponse(String clientId, String clientSecret, String redirectUri, String authCode) throws OAuthSystemException, OAuthProblemException { OAuthClientRequest request = getAccessTokenRequest(clientId, clientSecret, redirectUri, authCode);...
java
private static final Tensor getFactorMessage(int curVarNum, Tensor logFactorWeights, List<Tensor> variableMarginals, IndexedList<Integer> variableNums) { Tensor factorMessage = logFactorWeights; // Each message is the outer product of all variable marginals, except // variable i, elementwise multiplie...
java
public Boolean hasIndex() { Boolean hasIndex = false; if (this.indexedFastaSequenceFile != null) { hasIndex = this.indexedFastaSequenceFile.isIndexed(); } return hasIndex; }
python
def _find_impl(cls, registry): """Returns the best matching implementation from *registry* for type *cls*. Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. Note: if *registry* does not contain an implementation ...
java
static Function<String, ManagedCloudSdk> newManagedSdkFactory() { return (version) -> { try { if (Strings.isNullOrEmpty(version)) { return ManagedCloudSdk.newManagedSdk(); } else { return ManagedCloudSdk.newManagedSdk(new Version(version)); } } catch (Unsuppor...
java
public OvhFiler serviceName_datacenter_datacenterId_filer_filerId_GET(String serviceName, Long datacenterId, Long filerId) throws IOException { String qPath = "/dedicatedCloud/{serviceName}/datacenter/{datacenterId}/filer/{filerId}"; StringBuilder sb = path(qPath, serviceName, datacenterId, filerId); String resp ...
python
def get_output_docs(self): """Return the output docstrings once formatted :returns: the formatted docstrings :rtype: list """ if not self.parsed: self._parse() lst = [] for e in self.docs_list: lst.append(e['docs'].get_raw_docs()) ...
java
public ServiceInstanceQuery getNotInQueryCriterion(String key, List<String> list){ QueryCriterion c = new NotInQueryCriterion(key, list); addQueryCriterion(c); return this; }
java
public static Point2D.Double snapToNextHigherInActiveRegionResolution( double x, double y, Window activeWindow ) { double minx = activeWindow.getRectangle().getBounds2D().getMinX(); double ewres = activeWindow.getWEResolution(); double xsnap = minx + (Math.ceil((x - minx) / ewres) * ewres); ...
java
@Subscribe public synchronized void renew(final DisabledStateChangedEvent disabledStateChangedEvent) { OrchestrationShardingSchema shardingSchema = disabledStateChangedEvent.getShardingSchema(); if (ShardingConstant.LOGIC_SCHEMA_NAME.equals(shardingSchema.getSchemaName())) { ((Orchestrat...
python
def on_mouse_wheel(self, event): '''handle mouse wheel zoom changes''' rotation = event.GetWheelRotation() / event.GetWheelDelta() if rotation > 0: zoom = 1.0/(1.1 * rotation) elif rotation < 0: zoom = 1.1 * (-rotation) self.change_zoom(zoom) self....
java
public static String foldCase(String str, boolean defaultmapping) { return foldCase(str, defaultmapping ? FOLD_CASE_DEFAULT : FOLD_CASE_EXCLUDE_SPECIAL_I); }
python
def _load_clublogXML(self, url="https://secure.clublog.org/cty.php", apikey=None, cty_file=None): """ Load and process the ClublogXML file either as a download or from file """ if self._download: cty_file = self...
python
def parse_skypos(ra, dec): """ Function to parse RA and Dec input values and turn them into decimal degrees Input formats could be: ["nn","nn","nn.nn"] "nn nn nn.nnn" "nn:nn:nn.nn" "nnH nnM nn.nnS" or "nnD nnM nn.nnS" nn.nnnnnnnn "nn.nnnnnnn" """ ...
python
def read(calc_id, username=None): """ :param calc_id: a calculation ID :param username: if given, restrict the search to the user's calculations :returns: the associated DataStore instance """ if isinstance(calc_id, str) or calc_id < 0 and not username: # get the last calculation in the ...
java
@Deprecated public static String reject(String string, CharPredicate predicate) { return StringIterate.rejectChar(string, predicate); }
java
private void appendCauses(StringBuilder buf, Throwable thrown) { buf.append(thrown.toString()).append(OutputStreamLogger.NEWLINE); StackTraceElement[] stack = thrown.getStackTrace(); int end = stack.length - 1; prune: for(; end >= 0; end--) { String cn = stack[end].getClassName(); for(String...
python
def get_area(self, degrees=True): """ Calculate the total area represented by this region. Parameters ---------- degrees : bool If True then return the area in square degrees, otherwise use steradians. Default = True. Returns ------- ...
java
private static int getSizeNoH(Group g) { int size = 0; for (Atom a:g.getAtoms()) { if (a.getElement()!=Element.H) size++; } return size; }
python
def callback(self, request, **kwargs): """ Called from the Service when the user accept to activate it :param request: request object :return: callback url :rtype: string , path to the template """ try: UserService.objects.filter( ...
java
public MediaState getMovieAccountState(int movieId, String sessionId) throws MovieDbException { return tmdbMovies.getMovieAccountState(movieId, sessionId); }
python
def _unpack(c, tmp, package, version, git_url=None): """ Download + unpack given package into temp dir ``tmp``. Return ``(real_version, source)`` where ``real_version`` is the "actual" version downloaded (e.g. if a Git master was indicated, it will be the SHA of master HEAD) and ``source`` is the s...
python
def build_truncated_gr_mfd(mfd): """ Parses the truncated Gutenberg Richter MFD as a Node :param mfd: MFD as instance of :class: `openquake.hazardlib.mfd.truncated_gr.TruncatedGRMFD` :returns: Instance of :class:`openquake.baselib.node.Node` """ return Node("truncGutenbe...
python
def fileobj(path_or_file, mode='r'): """Returns a file-like object that can be used as a context manager""" if isinstance(path_or_file, six.string_types): try: return open(path_or_file, mode) except IOError: log = logging.getLogger('sos') log.debug("fileobj: %...
python
def model_to_objective(self, x_model): ''' This function serves as interface between model input vectors and objective input vectors ''' idx_model = 0 x_objective = [] for idx_obj in range(self.objective_dimensionality): variable = self.space_expanded[idx...
python
def get_in_net_id(cls, tenant_id): """Retrieve the network ID of IN network. """ if 'in' not in cls.ip_db_obj: LOG.error("Fabric not prepared for tenant %s", tenant_id) return None db_obj = cls.ip_db_obj.get('in') in_subnet_dict = cls.get_in_ip_addr(tenant_id) ...
java
public static AffineTransform createScreenTransform(Rectangle2D userBounds, Rectangle2D screenBounds, boolean keepAspectRatio) { return createScreenTransform(userBounds, screenBounds, keepAspectRatio, new AffineTransform()); }
python
def better_exec_command(ssh, command, msg): """Uses paramiko to execute a command but handles failure by raising a ParamikoError if the command fails. Note that unlike paramiko.SSHClient.exec_command this is not asynchronous because we wait until the exit status is known :Parameter ssh: a paramiko SSH Client...
python
def save_as(self): """Dialog for getting name, location of dataset export.""" filename = splitext(self.filename)[0] filename, _ = QFileDialog.getSaveFileName(self, 'Export events', filename) if filename == '': return ...
python
def strptime(cls, date_string, fmt): """ This is opposite of the :py:meth:`khayyam.JalaliDate.strftime`, and used to parse date strings into date object. `ValueError` is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t ...
python
def setup_logger(logger_name, log_file=None, sentry_url=None): """Run once when the module is loaded and enable logging. :param logger_name: The logger name that we want to set up. :type logger_name: str :param log_file: Optional full path to a file to write logs to. :type log_file: str :para...
python
def _hangul_char_to_jamo(syllable): """Return a 3-tuple of lead, vowel, and tail jamo characters. Note: Non-Hangul characters are echoed back. """ if is_hangul_char(syllable): rem = ord(syllable) - _JAMO_OFFSET tail = rem % 28 vowel = 1 + ((rem - tail) % 588) // 28 lead =...
java
public void setPattern(String pattern) throws IllegalArgumentException{ if (pattern == null) { throw new IllegalArgumentException("The pattern must not be null."); } this.pattern = pattern; parsePattern(this.pattern); }
java
private void handleExpansionRequest(final Request request) { String[] paramValue = request.getParameterValues(getId() + ".expanded"); if (paramValue == null) { paramValue = new String[0]; } Map<List<Integer>, Object> pageRowKeys = getCurrentRowIndexAndKeys(); String[] expandedRows = removeEmptyStrings(p...
python
def get_agile_board_configuration(self, board_id): """ Get the board configuration. The response contains the following fields: id - Id of the board. name - Name of the board. filter - Reference to the filter used by the given board. subQuery (Kanban only) - JQL subquery ...
java
public boolean verifyHost(String host, SshPublicKey pk) throws SshException { return verifyHost(host, pk, true); }
python
def _delete(self, **kwargs): """Delete a resource from a remote Transifex server.""" path = self._construct_path_to_item() return self._http.delete(path)
java
public void list(VersionsListConfiguration configuration) throws AppEngineException { Preconditions.checkNotNull(configuration); List<String> arguments = new ArrayList<>(); arguments.add("app"); arguments.add("versions"); arguments.add("list"); arguments.addAll(GcloudArgs.get("service", configu...
python
def _ssh_client(self): """Gets an SSH client to connect with. """ ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.RejectPolicy()) return ssh
python
def set_phy_mode(self, mode=IxePhyMode.ignore): """ Set phy mode to copper or fiber. :param mode: requested PHY mode. """ if isinstance(mode, IxePhyMode): if mode.value: self.api.call_rc('port setPhyMode {} {}'.format(mode.value, self.uri)) else: ...
python
def __make_var(self, name: str, shape: list): """ Creates a tensorflow variable with the given name and shape. :param name: name to set for the variable. :param shape: list defining the shape of the variable. :return: created TF variable. """ return tf.get_variabl...
java
public BatchMutation<K> addCounterInsertion(K key, List<String> columnFamilies, CounterColumn counterColumn) { Mutation mutation = new Mutation(); mutation.setColumn_or_supercolumn(new ColumnOrSuperColumn().setCounter_column(counterColumn)); addMutation(key, columnFamilies, mutation); return this; }
java
public boolean hasContentType(String... contentTypes) { if (contentTypes == null || contentTypes.length == 0) { return true; } String normalisedContentType = getNormalisedContentTypeValue(); if (normalisedContentType == null) { return false; } ...
java
private int doInvoke() { int s; Thread t; ForkJoinWorkerThread wt; if ((s = doExec()) >= 0) { if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) s = (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue, ...
java
public PacketCaptureResultInner beginCreate(String resourceGroupName, String networkWatcherName, String packetCaptureName, PacketCaptureInner parameters) { return beginCreateWithServiceResponseAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).toBlocking().single().body(); }
python
def compute_frame(self, **kwargs): r"""Compute the associated frame. A filter bank defines a frame, which is a generalization of a basis to sets of vectors that may be linearly dependent. See `Wikipedia <https://en.wikipedia.org/wiki/Frame_(linear_algebra)>`_. The frame of a fi...
python
def converged_electronic(self): """ Checks that electronic step convergence has been reached in the final ionic step """ final_esteps = self.ionic_steps[-1]["electronic_steps"] if 'LEPSILON' in self.incar and self.incar['LEPSILON']: i = 1 to_check ...
python
def external_editor(self, filename, goto=-1): """Edit in an external editor Recommended: SciTE (e.g. to go to line where an error did occur)""" editor_path = CONF.get('internal_console', 'external_editor/path') goto_option = CONF.get('internal_console', 'external_editor/gotoline') ...
python
def randomMails(self, count=1): """ Return random e-mails. :rtype: list :returns: list of random e-mails """ self.check_count(count) random_nicks = self.rn.random_nicks(count=count) random_domains = sample(self.dmails, count) return [ ...
java
public JSONNavi<?> at(int index) { if (failure) return this; if (!(current instanceof List)) return failure("current node is not an Array", index); @SuppressWarnings("unchecked") List<Object> lst = ((List<Object>) current); if (index < 0) { index = lst.size() + index; if (index < 0) index = 0;...
python
def register(classname, cls): """Add a class to the registry of serializer classes. When a class is registered, an entry for both its classname and its full, module-qualified path are added to the registry. Example: :: class MyClass: pass register('MyClass', MyClass) ...
python
def get_other_keys(self, key, including_current=False): """ Returns list of other keys that are mapped to the same value as specified key. @param key - key for which other keys should be returned. @param including_current if set to True - key will also appear on this list.""" ...
java
@Override public String escapeLikePattern(final CharSequence pattern) { if (pattern == null) { return null; } Matcher matcher = escapePattern.matcher(pattern); return matcher.replaceAll(Matcher.quoteReplacement(String.valueOf(escapeChar)) + "$0"); }
python
def _show_documentation(self): """ Shows all documents of the current groundwork app in the console. Documents are sorted bei its names, except "main", which gets set to the beginning. """ documents = [] for key, document in self.app.documents.get().items(): ...
java
public boolean send(T graph, long correlationId) { Object payload = graph; if (m_marshaller != null) { Result result = m_resultFactory.createResult(graph); if (result == null) { throw new MessagingException( "Unable to marshal payload, ResultFactory returned null."); } try { m_marsha...
python
def filter(self, record): """ Returns True if the record shall be logged. False otherwise. https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L607 """ found = self._pattern.search(record.getMessage()) return not found
python
def update_power_state(self, id_or_uri, power_state): """ Sets the power state of the specified power delivery device. The device must be an HP Intelligent Outlet. Args: id_or_uri: Can be either the power device id or the uri power_state: ...
java
private static <T> List<TableFactory> filterByContext( Class<T> factoryClass, Map<String, String> properties, List<TableFactory> foundFactories, List<TableFactory> classFactories) { List<TableFactory> matchingFactories = classFactories.stream().filter(factory -> { Map<String, String> requestedContext = no...
python
def set_input_by_id(self, _id, value): """ Set the value of form element by its `id` attribute. :param _id: id of element :param value: value which should be set to element """ xpath = './/*[@id="%s"]' % _id if self._lxml_form is None: self.choose_fo...