language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Matrix4d translationRotateScaleMulAffine(double tx, double ty, double tz, double qx, double qy, double qz, double qw, double sx, double sy, double sz, Matr...
java
public void enableUniformSize(final boolean enable) { if (mUniformSize != enable) { mUniformSize = enable; if (mContainer != null) { mContainer.onLayoutChanged(this); } } }
python
def on_old_request(self, task, old_task): '''Called when a crawled task is arrived''' now = time.time() _schedule = task.get('schedule', self.default_schedule) old_schedule = old_task.get('schedule', {}) if _schedule.get('force_update') and self.projects[task['project']].task_q...
python
def get_matrix(self, x1, x2=None): """ Get the covariance matrix at a given set or two of independent coordinates. :param x1: ``(nsamples,)`` or ``(nsamples, ndim)`` A list of samples. :param x2: ``(nsamples,)`` or ``(nsamples, ndim)`` (optional) A secon...
python
def model_prior(self, t): """Returns the prior probability of the HMM Runs forward-backward without any data, showing the prior distribution of the model (for comparison with a posterior). Parameters ---------- t: int Number of timepoints Returns ...
java
@Override public void close() { val bk = this.bookKeeper.getAndSet(null); if (bk != null) { try { bk.close(); } catch (Exception ex) { log.error("Unable to close BookKeeper client.", ex); } } }
java
public static WindowOver<Long> countDistinct(Expression<?> expr) { return new WindowOver<Long>(Long.class, Ops.AggOps.COUNT_DISTINCT_AGG, expr); }
python
def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0): """Convert TEME position and velocity into standard ITRS coordinates. This converts a position and velocity vector in the idiosyncratic True Equator Mean Equinox (TEME) frame of reference used by the SGP4 theory into vectors into the more standard...
java
@Override protected void resizeDynamicText() { double oneThirdWidth = width / 3; double fontSize = size * 0.1; description.setFont(Fonts.latoRegular(fontSize)); description.setLayoutY(height * 0.175); fontSize = size * 0.075; leftValueLabel.setFont(Fonts.latoRegul...
java
public ApnsClientBuilder setClientCredentials(final InputStream p12InputStream, final String p12Password) throws SSLException, IOException { final X509Certificate x509Certificate; final PrivateKey privateKey; try { final KeyStore.PrivateKeyEntry privateKeyEntry = P12Util.getFirstPri...
java
private static int[] makeFields(int[] fields, TupleTypeInfo<?> type) { int inLength = type.getArity(); // null parameter means all fields are considered if (fields == null || fields.length == 0) { fields = new int[inLength]; for (int i = 0; i < inLength; i++) { fields[i] = i; } return fields; ...
python
def create_next_candidates(prev_candidates, length): """ Returns the apriori candidates as a list. Arguments: prev_candidates -- Previous candidates as a list. length -- The lengths of the next candidates. """ # Solve the items. item_set = set() for candidate in prev_candida...
java
public void shutdown() { if (_producer != null) { _producer.close(); } _executorService.shutdown(); try { if (!_executorService.awaitTermination(10, TimeUnit.SECONDS)) { _logger.warn("Shutdown of Kafka executor service timed out after 10 seconds.")...
java
@Nullable public Date getDateModified(@Nullable TimeZone timeZone) { Directory parent = getParent(); if (parent instanceof ExifIFD0Directory) { TimeZone timeZoneModified = getTimeZone(TAG_OFFSET_TIME); return parent.getDate(TAG_DATETIME, getString(TAG_SUBSECOND_TIME), ...
java
public static long map( final FileChannel fileChannel, final FileChannel.MapMode mode, final long offset, final long length) { try { return (long)MappingMethods.MAP_ADDRESS.invoke(fileChannel, getMode(mode), offset, length); } catch (final IllegalAccessException |...
java
public void setCacheNodeIdsToRemove(java.util.Collection<String> cacheNodeIdsToRemove) { if (cacheNodeIdsToRemove == null) { this.cacheNodeIdsToRemove = null; return; } this.cacheNodeIdsToRemove = new com.amazonaws.internal.SdkInternalList<String>(cacheNodeIdsToRemove); ...
java
public @NotNull List<Page> getPages(@Nullable final Predicate<Page> filter, @Nullable final Page basePage) { Resource baseResourceToUse = null; // detect pages page to use if (basePage == null) { PageManager pageManager = AdaptTo.notNull(request.getResourceResolver(), PageManager.class); Page c...
python
def chimera(args): """ %prog chimera bamfile Parse BAM file from `bwasw` and list multi-hit reads and breakpoints. """ import pysam from jcvi.utils.natsort import natsorted p = OptionParser(chimera.__doc__) p.set_verbose() opts, args = p.parse_args(args) if len(args) != 1: ...
python
def does_field_exist(self,collection,field_name): ''' Checks if the field exists will return a boolean True (exists) or False(doesn't exist). :param string collection: Name of the collection for the action :param string field_name: String name of the field. ''' schema = ...
java
protected JCTree resource() { JCModifiers optFinal = optFinal(Flags.FINAL); JCExpression type = parseType(); int pos = token.pos; Name ident = ident(); return variableDeclaratorRest(pos, optFinal, type, ident, true, null); }
java
public void addTranslation (String oldname, String newname) { if (_translations == null) { _translations = Maps.newHashMap(); } _translations.put(oldname, newname); }
python
def show_and_run(self): """Show the main widget in a window and run the gtk loop""" self.display_widget = gtk.Window() self.display_widget.add(self.widget) self.display_widget.show() BaseDelegate.show_and_run(self)
python
def _underscore_run_program(name, *args, **kwargs): """Runs the 'name' program, use this if there are illegal python method characters in the program name >>> _underscore_run_program("echo", "Hello") 'Hello' >>> _underscore_run_program("echo", "Hello", return_object=True).stdout 'Hello' >>> _un...
python
def convert(b): ''' takes a number of bytes as an argument and returns the most suitable human readable unit conversion. ''' if b > 1024**3: hr = round(b/1024**3) unit = "GB" elif b > 1024**2: hr = round(b/1024**2) unit = "MB" else: hr = round(b/1024) ...
python
def _set_flow(self, v, load=False): """ Setter method for flow, mapped from YANG variable /openflow_state/flow (container) If this variable is read-only (config: false) in the source YANG file, then _set_flow is considered as a private method. Backends looking to populate this variable should do...
python
def api_column_add(self, col_name): """ Returns list of (pk, object) nice to use on select2. Use only for related columns. Always filters with add_form_query_rel_fields, and accepts extra filters on endpoint arguments. :param col_name: The related column n...
java
public Reflector set(String name, Object value) throws ReflectException { try { Field field = field0(name); field.setAccessible(true); field.set(obj, unwrap(value)); return this; } catch (Exception e) { throw new ReflectException(e); } ...
python
def list_images(img_dpath_, ignore_list=[], recursive=False, fullpath=False, full=None, sort=True): r""" Returns a list of images in a directory. By default returns relative paths. TODO: rename to ls_images TODO: Change all instances of fullpath to full Args: img_dpath_ (st...
java
public ParseTreeNode parse(SourceCode sourceCode, String production) throws ParserException { try { initialize(sourceCode); MemoEntry progress = applyRule(production, 0, 1); if (progress.getDeltaPosition() != text.length()) { throw new ParserException(getParserErrorMessage()); } Object answe...
java
@Override public EClass getIfcAsset() { if (ifcAssetEClass == null) { ifcAssetEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(27); } return ifcAssetEClass; }
java
protected JournalInputFile openNextFile() throws JournalException { File[] journalFiles = MultiFileJournalHelper .getSortedArrayOfJournalFiles(journalDirectory, filenamePrefix); if (journalFiles.length == 0) {...
java
@Override public boolean commitTransaction(Connection conn) { try { return DbcHelper.commitTransaction(conn); } catch (SQLException e) { throw new DaoException(e); } }
python
def getBirthdate(self, string=True): """ Returns the birthdate as string object Parameters ---------- None Examples -------- >>> import pyedflib >>> f = pyedflib.data.test_generator() >>> f.getBirthdate()=='30 jun 1969' True ...
python
def com_google_fonts_check_version_bump(ttFont, api_gfonts_ttFont, github_gfonts_ttFont): """Version number has increased since previous release on Google Fonts?""" v_number = ttFont["head"].fontRevision api_gfonts_v_number = api_gfon...
python
def _get_all_containing(self, containing_contigs, name, exclude=None, max_depth=10): '''containing_contigs is a dict: key=contig name. Value = set of contigs that contain the key. Returns alls contigs called "name" that contain that contig''' contains_name = set() # fa...
python
def iteritems(self): """ Wow this class is messed up. I had to overwrite items when moving to python3, just because I haden't called it yet """ for (key, val) in six.iteritems(self.__dict__): if key in self._printable_exclude: continue yiel...
python
def load(cli, yaml_filename): """Creates waybill shims from a given yaml file definiations""" """Expected Definition: - name: NAME docker_id: IMAGE - name: NAME docker_id: IMAGE """ with open(yaml_filename, 'rb') as filehandle: for waybill ...
java
public CustomEmojiBuilder setImage(BufferedImage image, String type) { delegate.setImage(image, type); return this; }
python
def exists_orm(session: Session, ormclass: DeclarativeMeta, *criteria: Any) -> bool: """ Detects whether a database record exists for the specified ``ormclass`` and ``criteria``. Example usage: .. code-block:: python bool_exists = exists_orm(session, MyClass,...
python
def get_stanza(self, peer_jid): """ Return the last presence recieved for the given bare or full `peer_jid`. If the last presence was unavailable, the return value is :data:`None`, as if no presence was ever received. If no presence was ever received for the given bare JID, :dat...
java
public Observable<ServiceResponse<Page<ApplicationGatewaySslPredefinedPolicyInner>>> listAvailableSslPredefinedPoliciesNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } ...
java
private void fillRequestContext(RequestContext context) { IdManager.makeSureMsgId(context); context.setNodeStatus(getSimpleStatus()); context.setMessageType(MessageType.request); context.setSourceNodeId(nodeId);//this node id }
java
@Override @FFDCIgnore(Exception.class) public String getUserDisplayName(final String inputUserSecurityName) throws EntryNotFoundException, RegistryException { try { // bridge the APIs String returnValue = displayBridge.getUserDisplayName(inputUserSecurityName); return...
python
def point_from_cols_vals(cols, vals): """Create a dict from columns and values lists. :param cols: List of columns :param vals: List of values :return: Dict where keys are columns. """ point = {} for col_index, col_name in enumerate(cols): point[col_n...
python
def train(cls, data, minSupport=0.3, numPartitions=-1): """ Computes an FP-Growth model that contains frequent itemsets. :param data: The input data set, each element contains a transaction. :param minSupport: The minimal support level. (default: 0.3) ...
java
public static Row getRowFromCells(Cells cells) { Object[] values = cells.getCellValues().toArray(); return RowFactory.create(values); }
python
def subscribe(object_type: str, subscriber: str, callback_handler: Callable = None) -> EventQueue: """Subscribe to the specified object type. Returns an EventQueue object which can be used to query events associated with the object type for this subscriber. Args: object_type (str...
python
def close(self): """ Close this session, and any open channels that are tied to it. """ if not self.active: return self.stop_thread() for chan in list(self._channels.values()): chan._unlink() self.sock.close()
java
public static boolean contains(File file, String pattern) throws IOException { try (Scanner fileScanner = new Scanner(file, UTF_8)) { final Pattern regex = Pattern.compile(pattern); if (fileScanner.findWithinHorizon(regex, 0) != null) { return true; } ...
java
@Override public synchronized void update(long sessionId, String sessionName) throws DatabaseException { SqlPreparedStatementWrapper psUpdate = null; try { psUpdate = DbSQL.getSingleton().getPreparedStatement("session.ps.update"); psUpdate.getPs().setLong(2, sessionId); psUpdate.getPs...
python
def node_is_result_assignment(node: ast.AST) -> bool: """ Args: node: An ``ast`` node. Returns: bool: ``node`` corresponds to the code ``result =``, assignment to the ``result `` variable. Note: Performs a very weak test that the line starts with 'result =' rather ...
python
def connectionLost(self, reason): """ Called when the transport loses connection to the bus """ if self.busName is None: return for cb in self._dcCallbacks: cb(self, reason) for d, timeout in self._pendingCalls.values(): if timeout: ...
python
def header(self): """Generates HTTP header for this cookie.""" if self._send_cookie: morsel = Morsel() cookie_value = Session.encode_sid(self._config.secret, self._sid) if self._config.encrypt_key: cipher = AESCipher(self._config.encrypt_key) ...
java
public final AbstractItemLink get(final long key) { AbstractItemLink link = null; synchronized (_getLock(key)) { if(null != _entry) // 666212 { // 666212 int i = _indexOfKey(key); AbstractItemLink entry = _entry[i]; while (nul...
java
public final StringBuffer format(Object obj, StringBuffer appendTo, FieldPosition fieldPosition) { if ( obj instanceof DateInterval ) { return format( (DateInterval)obj, appendTo, fieldPosition); } else { throw new IllegalArgumentException("Cannot format give...
python
def build_response_card(title, subtitle, options): """ Build a responseCard with a title, subtitle, and an optional set of options which should be displayed as buttons. """ buttons = None if options is not None: buttons = [] for i in range(min(5, len(options))): buttons.a...
java
protected Expression number(int opPos) throws TransformerException { return compileUnary(new org.apache.xpath.operations.Number(), opPos); }
java
public Observable<Page<String>> listWebAppsByHybridConnectionNextAsync(final String nextPageLink) { return listWebAppsByHybridConnectionNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<String>>, Page<String>>() { @Override public Page<Str...
java
public BeanQuery<Map<String,Object>> nested(){ if(!(this.selector instanceof KeyValueMapSelector)){ throw new IllegalStateException("This is only for BeanQueries which has a KeyValueMapSelector selector. The current selector is a "+this.selector); } BeanQuery<Map<String,Object>> result= new BeanQuery<...
python
def run(self): """Run TensorBoard process.""" port, tensorboard_process = self.create_tensorboard_process() LOGGER.info('TensorBoard 0.1.7 at http://localhost:{}'.format(port)) while not self.estimator.checkpoint_path: self.event.wait(1) with self._temporary_director...
java
public ListRuleResponse listRules(ListRuleRequest request) { InternalRequest internalRequest = createRequest(request, HttpMethodName.GET, RULES); if (request.getPageNo() > 0) { internalRequest.addParameter("pageNo", String.valueOf(request.getPageNo())); } if (...
java
@Override public EClass getIfcShadingDeviceType() { if (ifcShadingDeviceTypeEClass == null) { ifcShadingDeviceTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(594); } return ifcShadingDeviceTypeEClass; }
java
public void logDomNode (String msg, Node node) { StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement (); logDomNode (msg, node, Level.FINER, caller); }
java
public final FFDCLogger append(String info) { lines.add(new StringBuffer().append(info).append(AdapterUtil.EOLN).toString()); return this; }
python
def query(self, constraint, sortby=None, typenames=None, maxrecords=10, startposition=0): """ Query records from underlying repository """ # run the raw query and get total # we want to exclude layers which are not valid, as it is done in the search engine if 'where' in ...
java
@Override public int drainTo(Collection<E> collection) { int size = queue.drainTo(collection); addCapacity(-size); return size; }
python
def conf_merger(user_dict, variable): """ Merge global configuration with user's personal configuration. Global configuration has always higher priority. """ if variable not in globals().keys(): raise NameError("Unknown variable '%s'." % variable) if variable not in user_dict: ...
python
def infos(self, type=None, failed=False): """Get infos that originate from this node. Type must be a subclass of :class:`~dallinger.models.Info`, the default is ``Info``. Failed can be True, False or "all". """ if type is None: type = Info if not issubclass...
java
@Override public RowSet getNextRowSet(FetchOrientation orientation, long maxRows) throws HiveSQLException { validateDefaultFetchOrientation(orientation); if (orientation.equals(FetchOrientation.FETCH_FIRST)) { resetResultReader(); } List<String> rows = readResults((int) maxRows); RowSet rowS...
python
def list_processed_parameter_group_histogram(self, group=None, start=None, stop=None, merge_time=20): """ Reads index records related to processed parameter groups between the specified start and stop time. Each iteration returns a chunk of chronologically-sorted records. :para...
python
def make_request(self, request, captcha_response=None): """Make api request helper function :param request: vk_requests.api.Request instance :param captcha_response: None or dict, e.g {'sid': <sid>, 'key': <key>} :return: dict: json decoded http response """ logger.debug...
python
def keys(self): """Return a list of all keys in the dictionary. Returns: list of str: [key1,key2,...,keyN] """ all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()] return all_keys
java
public static void fail(String message, Object... args) { throw new IllegalStateException(message == null ? "" : String.format(message, args)); }
java
public static ByteBuffer getImageByteBuffer(RenderedImage image) { ColorModel cm = image.getColorModel(); WritableRaster wr = image.getData().createCompatibleWritableRaster(image.getWidth(), image.getHeight()); image.copyData(wr); BufferedImage bi = new BufferedImage(cm, wr, cm.isAlphaPr...
java
public Method get(final MethodIdentifier identifier) { // search for available methods readWriteLock.readLock().lock(); try { final Optional<? extends IdentifiableMethod> method = availableMethods.stream().filter(m -> m.matches(identifier)).findAny(); if (method.isPresent...
java
private NormalVersion parseVersionCore() { int major = Integer.parseInt(numericIdentifier()); consumeNextCharacter(CharType.DOT); int minor = Integer.parseInt(numericIdentifier()); consumeNextCharacter(CharType.DOT); int patch = Integer.parseInt(numericIdentifier()); return new NormalVersion(maj...
java
public static void createFile(final File dest, final InputStream sourceInput) throws IOException { if (sourceInput == null || dest == null) return; FileOutputStream fos = null; try { if (!dest.getParentFile().exists()) { if (!dest.getParentFile().mkdirs()...
python
def read_parquet(cls, path, engine, columns, **kwargs): """Load a parquet object from the file path, returning a DataFrame. Ray DataFrame only supports pyarrow engine for now. Args: path: The filepath of the parquet file. We only support local files for now. ...
java
public void setAlarms(java.util.Collection<Alarm> alarms) { if (alarms == null) { this.alarms = null; return; } this.alarms = new com.amazonaws.internal.SdkInternalList<Alarm>(alarms); }
python
def json(self, json_string=None): """ Convenience method allowing easy dumping to and loading from json. """ if json_string is not None: return self.__init__(loads(json_string)) dump = self if isinstance(self, HAR.log): dump = {"log": dump} ...
java
@Override public CloseInstancePublicPortsResult closeInstancePublicPorts(CloseInstancePublicPortsRequest request) { request = beforeClientExecution(request); return executeCloseInstancePublicPorts(request); }
java
Observable<ChatResult> handleConversationCreated(ComapiResult<ConversationDetails> result) { if (result.isSuccessful()) { return persistenceController.upsertConversation(ChatConversation.builder().populate(result.getResult(), result.getETag()).build()).map(success -> adapter.adaptResult(result, succ...
java
protected void mergeParent(CmsADEConfigDataInternal parent) { List<CmsResourceTypeConfig> parentTypes = null; if (parent != null) { parentTypes = parent.m_ownResourceTypes; } else { parentTypes = Collections.emptyList(); } List<CmsPropertyConfig> parentP...
python
def migrateDown(self): """ Assuming that self.avatars is a SubStore which should contain *only* the LoginAccount for the user I represent, remove all LoginAccounts and LoginMethods from that store and copy all methods from the site store down into it. """ ss = sel...
python
def __get_ra_index_indices(self): """ Returns a list containing indices of the ra_index array, which correspond to the separate trajectory fragments, i.e., ra_indices[fragment_indices[itraj]] are the ra indices for itraj (plus some offset by cumulative length) """ fragmen...
java
public List<CmsLogEntry> getLogEntries(CmsRequestContext context, CmsLogFilter filter) throws CmsException { List<CmsLogEntry> result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { result = m_driverManager.getLogEntries(dbc, filter); } catch (Exce...
java
@Override public void setValuesIfMultiReadofPostdataEnabled() { if(!httpUpdatedwMultiReadValues) { WebApp webapp = getDispatchContext().getWebApp(); if (webapp != null){ multiReadPropertyEnabled = webapp.getConfiguration().isEnablemultireadofpostdata(); ...
java
private void generateDefaultProfile(final DaoManager storage, final String profileSourcePath) throws SQLException, IOException{ Profile profile = storage.getProfilesDao().getProfile(DEFAULT_PROFILE_SID); if (profile == null) { if(logger.isDebugEnabled()) { logger.debug("defa...
python
def str_eta(self): """Returns a formatted ETA value for the progress bar.""" eta = eta_letters(self._eta.elapsed) if self.done else self._eta_string if not eta: return '' if eta.count(' ') > 1: eta = ' '.join(eta.split(' ')[:2]) # Only show up to two units (h and...
java
public void marshall(GetConnectionStatusRequest getConnectionStatusRequest, ProtocolMarshaller protocolMarshaller) { if (getConnectionStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(g...
python
def hessian_component(self, index1, index2): """Compute the hessian of the energy for one atom pair""" result = np.zeros((3, 3), float) if index1 == index2: for index3 in range(self.numc): if self.scaling[index1, index3] > 0: d_1 = 1/self.distances...
python
def ecef2nedv(x: float, y: float, z: float, lat0: float, lon0: float, deg: bool = True) -> Tuple[float, float, float]: """ for VECTOR between two points Parameters ---------- x : float or numpy.ndarray of float ECEF x coordinate (meters) y : float or numpy.nd...
java
NameAndType nameType(Symbol sym) { return new NameAndType(fieldName(sym), retrofit ? sym.erasure(types) : sym.externalType(types), types); // if we retrofit, then the NameAndType has been read in as is /...
java
public Field getIdentityProperty(Class clazz) { Field info = _idPropertyCache.get(clazz); if (info != null) { return info; } try { Field idField = Arrays.stream(Introspector.getBeanInfo(clazz).getPropertyDescriptors()) .filter(x -> _findIdenti...
python
def update(cls): """ Update rows to include known network interfaces """ ifaddrs = getifaddrs() # Create new interfaces for ifname in ifaddrs.keys(): if filter(ifname.startswith, cls.NAME_FILTER): cls.objects.get_or_create(name=ifname) ...
python
def _dK_ode_dtheta(self, target): """Do all the computations for the ode parts of the covariance function.""" t_ode = self._t[self._index>0] dL_dK_ode = self._dL_dK[self._index>0, :] index_ode = self._index[self._index>0]-1 if self._t2 is None: if t_ode.size==0: ...
java
@Override protected HtmlToken produce() { HtmlToken token = parseToken(); if (null == token) { return null; } // Handle escape-exempt blocks. // The parse() method is only dimly aware of escape-excempt blocks, so // here we detect the beginning and ends of escape exempt blocks, and // reclass...
python
def _argsort(y_score, k=None): """ Returns the indexes in descending order of the top k score or all scores if k is None """ ranks = y_score.argsort() argsort = ranks[::-1] if k is not None: argsort = argsort[0:k] return argsort
python
def add_osm_layer(self): """Add OSM tile layer to the map. This uses a gdal wrapper around the OSM tile service - see the WorldOSM.gdal file for how it is constructed. """ path = resources_path('osm', 'WorldOSM.gdal') layer = QgsRasterLayer(path, self.tr('OpenStreetMap')...
java
private void clearDeckPreview(TrackMetadataUpdate update) { if (previewHotCache.remove(DeckReference.getDeckReference(update.player, 0)) != null) { deliverWaveformPreviewUpdate(update.player, null); } }