language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _rect_fitness(self, max_rect, width, height): """ Arguments: max_rect (Rectangle): Destination max_rect width (int, float): Rectangle width height (int, float): Rectangle height Returns: None: Rectangle couldn't be placed into max_rect ...
java
private Connection<CL> getConnectionForTokenOnRackNoFallback(BaseOperation<CL, ?> op, Long token, String rack, int duration, TimeUnit unit, RetryPolicy retry) throws NoAvailableHostsException, PoolExhaustedException, PoolTimeoutException, PoolOfflineException { DynoConnectException lastEx = null; ...
java
public static void assertMainThread() { if (imp != null && !DispatchQueue.isMainQueue()) { imp.assertFailed(StringUtils.format("Expected 'main' thread but was '%s'", Thread.currentThread().getName())); } }
java
private boolean versionCheck(String title) { if (this.type != UpdateType.NO_VERSION_CHECK) { final String version = caller.getPluginVersion(); final String remoteVersion = title; // Get the newest file's version number if (this.hasTag(version) || version.contains(remoteVersi...
python
def truck(self, model_mask: str = '#### @@') -> str: """Generate a truck model. :param model_mask: Mask of truck model. Here '@' is a placeholder of characters and '#' is a placeholder of digits. :return: Dummy truck model. :Example: Caledon-966O. """ ...
java
@Override public String getCssText() { final CSSStyleDeclarationImpl style = getStyle(); if (null == style) { return ""; } final String selectorText = selectors_.toString(); final String styleText = style.toString(); if (null == styleText || styleText.le...
python
def get_nbytes(dset): """ If the dataset has an attribute 'nbytes', return it. Otherwise get the size of the underlying array. Returns None if the dataset is actually a group. """ if 'nbytes' in dset.attrs: # look if the dataset has an attribute nbytes return dset.attrs['nbytes'] ...
python
def add_asset(self, filename, asset_type, display_name, encoding_rate=None, frame_width=None, frame_height=None, encode_to=None, encode_multiple=False, h264_preserve_as_rendition=False, h264_no_processing=False): """ Add an asset to the Video object. """ m = hashl...
python
def GetHandle(self): ''' returns an the identifier of the GUI widget. It must be an integer ''' win_id = self.winId() # this returns either an int or voitptr if "%s"%type(win_id) == "<type 'PyCObject'>": # PySide ### with PySide, self.winId() does not return...
python
async def addNodes(self, nodedefs): ''' Add/merge nodes in bulk. The addNodes API is designed for bulk adds which will also set properties and add tags to existing nodes. Nodes are specified as a list of the following tuples: ( (form, valu), {'props':{}, 'tags':{}})...
java
public GetDeploymentsResult withItems(Deployment... items) { if (this.items == null) { setItems(new java.util.ArrayList<Deployment>(items.length)); } for (Deployment ele : items) { this.items.add(ele); } return this; }
python
def get_scope(self, which, labels): """ :param which: str, description of the image this belongs to :param labels: dict, labels on the image """ try: scope_choice = labels[self.SCOPE_LABEL] except (KeyError, TypeError): self.log.debug("no distribu...
python
def error(self, code=500, callback=None): """ Register an output handler for a HTTP error code. Can be used as a decorator or called directly :: def error_handler_500(error): return 'error_handler_500' app.error(code=500, callback=error_handler_5...
java
@Override public List<XMLObject> getOrderedChildren() { ArrayList<XMLObject> children = new ArrayList<XMLObject>(); if (this.poBox != null) { children.add(this.poBox); } if (this.locatorDesignator != null) { children.add(this.locatorDesignator); } if (this.locatorName != null) { ...
python
def toggle_codes(self, event): """ Show/hide method code explanation widget on button click """ btn = event.GetEventObject() if btn.Label == 'Show method codes': self.code_msg_boxsizer.ShowItems(True) btn.SetLabel('Hide method codes') else: ...
python
def get_resource_id(prefix, *data): """Returns a unique ID based on the SHA256 hash of the provided data. The input data is flattened and sorted to ensure identical hashes are generated regardless of the order of the input. Values must be of types `str`, `int` or `float`, any other input type will raise a `...
java
public static Constructor<?> getConstructor2(ClassInjector injector, Class<?>[] classes, String[] prefixes, int observerMode) throws IllegalArgumentException { ...
java
static String getIntervalPattern(ChronoPrinter<?> printer) { AttributeQuery attrs = printer.getAttributes(); if (attrs.contains(Attributes.LANGUAGE)) { Locale locale = attrs.get(Attributes.LANGUAGE); return CalendarText.patternForInterval(locale); } return "{0}...
java
@Override public String remove(Object key) { return this.groupedMap.remove(DEFAULT_GROUP, Convert.toStr(key)); }
python
def make_iml4(R, iml_disagg, imtls=None, poes_disagg=(None,), curves=()): """ :returns: an ArrayWrapper over a 4D array of shape (N, R, M, P) """ if imtls is None: imtls = {imt: [iml] for imt, iml in iml_disagg.items()} N = len(curves) or 1 M = len(imtls) P = len(poes_disagg) arr...
python
def update_Dim(self,name,value): ''' update a dimension by appending the number of added elements to the dimensions :: <upddated dimension> = <old dimension> + <number of added elements along this dimension> ''' oldVal=self._dimensions[name] ...
python
def css_load_time(self): """ Returns aggregate css load time for all pages. """ load_times = self.get_load_times('css') return round(mean(load_times), self.decimal_precision)
java
public void marshall(StreamInfo streamInfo, ProtocolMarshaller protocolMarshaller) { if (streamInfo == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(streamInfo.getDeviceName(), DEVICENAME_BINDING); ...
java
private Integer getPortFromProjectOrSystemProperty(String var) { String sysProp = System.getProperty(var); if (sysProp != null) { return getAsIntOrNull(sysProp); } if (projProperties.containsKey(var)) { return getAsIntOrNull(projProperties.getProperty(var)); ...
java
private static DefaultListableBeanFactory buildListableBeanFactory(Map<String, ?> extraBeans) { //new empty context final DefaultListableBeanFactory parentBeanFactory = new DefaultListableBeanFactory(); //Injection of the new beans in the context for (String key : extraBeans.k...
python
def ascending(self, name): ''' Add a descending index for ``name`` to this index. :param name: Name to be used in the index ''' self.components.append((name, Index.ASCENDING)) return self
java
protected boolean isMemberOnEnhancementOfEnclosingType( AbstractDynamicSymbol symbol ) { if (!_cc().isNonStaticInnerClass()) { return false; } IType enhancement = symbol.getGosuClass(); if (! ( enhancement instanceof IGosuEnhancement ) ) { return false; } IType enhancedType = ((IG...
python
def stop(self): """Disconnect from device.""" if self._outstanding: _LOGGER.warning('There were %d outstanding requests', len(self._outstanding)) self._initial_message_sent = False self._outstanding = {} self._one_shots = {} self.c...
java
@Override public final <B> IO<B> zip(Applicative<Function<? super A, ? extends B>, IO<?>> appFn) { @SuppressWarnings("unchecked") IO<Object> source = (IO<Object>) this; @SuppressWarnings("unchecked") IO<Function<Object, Object>> zip = (IO<Function<Object, Object>>) (Object) appFn; ...
python
def ids(cls, values, itype=None): ''' http://www.elasticsearch.org/guide/reference/query-dsl/ids-filter.html Filters documents that only have the provided ids. Note, this filter does not require the _id field to be indexed since it works using the _uid field. ''' instance = cls(ids={'va...
java
@Override public BufferedImage getRemoteBufferedImage(){ DirectColorModel cm = new DirectColorModel(32, 0x00ff0000, // Red 0x0000ff00, // Green 0x000000ff, // Blue 0xff000000 // Alpha ); DataBufferInt buffer = new DataBuff...
java
@Override public void removeConnectionEventListener( ConnectionEventListener listener ) { if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.remove(listener); }
java
protected final boolean callbackOptionsItemSelected(MenuItem item) { if (DEBUG) Log.d(TAG, "[callbackOptionsItemSelected] item: " + item.getTitleCondensed()); boolean result = false; if (mActivity instanceof OnMenuItemSelectedListener) { OnMenuItemSelectedListener listener = (O...
java
public Matrix4f ortho2D(float left, float right, float bottom, float top) { return ortho2D(left, right, bottom, top, thisOrNew()); }
java
public static String safeRemoveAllTags(String html) { html = removeNonTextTags(html); html = unsafeRemoveAllTags(html); return html; }
java
public void addFeature(FeatureInterface<AbstractSequence<C>, C> feature) { features.add(feature); ArrayList<FeatureInterface<AbstractSequence<C>, C>> featureList = groupedFeatures.get(feature.getType()); if (featureList == null) { featureList = new ArrayList<FeatureInterface<AbstractSequence<C>, C>>(); grou...
java
public CMAWebhook create(String spaceId, CMAWebhook webhook) { assertNotNull(spaceId, "spaceId"); assertNotNull(webhook, "webhook"); final String webhookId = webhook.getId(); final CMASystem system = webhook.getSystem(); webhook.setSystem(null); try { if (webhookId == null) { retu...
python
def _x_visit(H, source_node, b_visit): """General form of the B-Visit algorithm, extended to also perform an implicit F-Visit if the b_visit flag is not set (providing better time/memory performance than explcitily taking the hypergraph's symmetric image and then performing the B-Visit on that). Re...
python
def _safe_db(num, den): """Properly handle the potential +Inf db SIR instead of raising a RuntimeWarning. """ if den == 0: return np.inf return 10 * np.log10(num / den)
java
public void setUpdates(java.util.Collection<RegexMatchSetUpdate> updates) { if (updates == null) { this.updates = null; return; } this.updates = new java.util.ArrayList<RegexMatchSetUpdate>(updates); }
python
def connect(jclassname, driver_args, jars=None, libs=None): """Open a connection to a database using a JDBC driver and return a Connection instance. jclassname: Full qualified Java class name of the JDBC driver. driver_args: Argument or sequence of arguments to be passed to the Java DriverMa...
python
def _reset(self): """ Resets class properties. """ self._name = None self._start_time = None self._owner = os.getuid() self._paths['task_dir'] = None self._paths['task_config'] = None self._loaded = False
python
def variant_matches_reference_sequence(variant, ref_seq_on_transcript, strand): """ Make sure that reference nucleotides we expect to see on the reference transcript from a variant are the same ones we encounter. """ if strand == "-": ref_seq_on_transcript = reverse_complement_dna(ref_seq_on...
java
public static byte[] hexStringToByteArray(String s) throws IOException { int l = s.length(); byte[] data = new byte[l / 2 + (l % 2)]; int n, b = 0; boolean high = true; int i = 0; for (int j = 0; j < l; j++) { char c = s...
java
private void initHashArea() { /* Let's use small hash area of size 4, and one spill; don't * want too big (need to clear up room), nor too small (only * collisions) */ mAttrHashSize = mAttrSpillEnd = 4; if (mAttrMap == null || mAttrMap.length < mAttrHashSize) { ...
java
private Date parseDate(String dateString) throws ParseException { // Return null if no date provided java.util.Date parsedDate = DateField.parse(dateString); if (parsedDate == null) return null; // Convert to SQL Date return new Date(parsedDate.getTime()); ...
java
public int handleRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) // init this field override for other value { if (iChangeType == DBConstants.FIELD_CHANGED_TYPE) { // If a field changed, only pass the first time through if (this.getEditMode() == Constants.EDIT_...
python
def purge(self): """ Purge all undelivered messages from the queue. This method is a :ref:`coroutine <coroutine>`. """ self.sender.send_QueuePurge(self.name) yield from self.synchroniser.wait(spec.QueuePurgeOK) self.reader.ready()
java
private static String trim(String string) { String result = string.trim(); if (result.startsWith("\"") && result.endsWith("\"") && result.length() > 1) { result = result.substring(1, result.length() - 1); } return result; }
java
public GeoMatchSet withGeoMatchConstraints(GeoMatchConstraint... geoMatchConstraints) { if (this.geoMatchConstraints == null) { setGeoMatchConstraints(new java.util.ArrayList<GeoMatchConstraint>(geoMatchConstraints.length)); } for (GeoMatchConstraint ele : geoMatchConstraints) { ...
java
public static Archiver createArchiver(File archive) throws IllegalArgumentException { FileType fileType = FileType.get(archive); if (fileType == FileType.UNKNOWN) { throw new IllegalArgumentException("Unknown file extension " + archive.getName()); } return createArchiver(fi...
java
public static DualInputSemanticProperties addSourceFieldOffsets(DualInputSemanticProperties props, int numInputFields1, int numInputFields2, int offset1, int offset2) { DualInputSemanticProperties offsetProps = new DualInputSemanticProperties(); // add offset to read fields on fi...
python
def render(self, template, filename, context={}, filters={}): """ Renders a Jinja2 template to text. """ filename = os.path.normpath(filename) path, file = os.path.split(filename) try: os.makedirs(path) except OSError as exception: if excep...
python
def execute(self, handler, arg): """ Execute a callback for each config item in the tree; returns zero if successful, else -1. """ return lib.zconfig_execute(self._as_parameter_, handler, arg)
python
def project_destroy(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /project-xxxx/destroy API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fdestroy """ return DXHTTPRequest('/%s/destroy' % object_id,...
python
def _try_services(self, method_name, *args, **kwargs): """ Try each service until one returns a response. This function only catches the bare minimum of exceptions from the service class. We want exceptions to be raised so the service classes can be debugged and fixed quickly. ...
java
public java.util.List<String> getAttributeValues() { if (attributeValues == null) { attributeValues = new com.amazonaws.internal.SdkInternalList<String>(); } return attributeValues; }
java
public void executeWithoutTrigger() throws EFapsException { if (Update.STATUSOK.getStati().isEmpty()) { final Context context = Context.getThreadContext(); ConnectionResource con = null; try { con = context.getConnectionResource(); ...
java
public Set<EnumType> getEnumTypes() { Set<EnumType> ret = Sets.newTreeSet(); for (Entity entity : getEntities().getList()) { for (Attribute attribute : entity.getAttributes().getList()) { if (attribute.isEnum()) { ret.add(attribute.getEnumType()); ...
python
def update_schema(self, catalog="hypermap"): """ set the mapping in solr. :param catalog: core :return: """ schema_url = "{0}/solr/{1}/schema".format(SEARCH_URL, catalog) print schema_url # create a special type to draw better heatmaps. location_r...
python
def get_organism_hosts(cls, entry): """ get list of `models.OrganismHost` objects from XML node entry :param entry: XML node entry :return: list of :class:`pyuniprot.manager.models.OrganismHost` objects """ query = "./organismHost/dbReference[@type='NCBI Taxonomy']" ...
java
@SuppressWarnings("unchecked") public static <T> ChannelOption<T> valueOf(String name) { return (ChannelOption<T>) pool.valueOf(name); }
java
protected final int neighborKey (int dx, int dy) { int nx = MathUtil.floorDiv(_bounds.x, _bounds.width)+dx; int ny = MathUtil.floorDiv(_bounds.y, _bounds.height)+dy; return MisoScenePanel.compose(nx, ny); }
java
public void setText(CharSequence text, boolean animate) { if (view != null) { ((TextView) view).setText(text); } }
python
def remove_diacritics(self_or_cls, identifier): """ Remove diacritics and accents from the input leaving other unicode characters alone.""" chars = '' for c in identifier: replacement = unicodedata.normalize('NFKD', c).encode('ASCII', 'ignore') if replacem...
java
protected Expression string(Data data) throws TemplateException { // check starting character for a string literal if (!data.srcCode.isCurrent('"') && !data.srcCode.isCurrent('\'')) return null; Position line = data.srcCode.getPosition(); // Init Parameter char quoter = data.srcCode.getCurrentLower(); StringBui...
python
def nearest_neighbor(x, tSet): """[summary] Implements the nearest neighbor algorithm Arguments: x {[tupel]} -- [vector] tSet {[dict]} -- [training set] Returns: [type] -- [result of the AND-function] """ assert isinstance(x, tuple) and isinstance(tSet, dict) curren...
python
def _to_fields(self, *values): """ Take a list of values, which must be primary keys of the model linked to the related collection, and return a list of related fields. """ result = [] for related_instance in values: if not isinstance(related_instance, model.R...
python
def num_memory_zones(self): """Returns the number of memory zones supported by the target. Args: self (JLink): the ``JLink`` instance Returns: An integer count of the number of memory zones supported by the target. Raises: JLinkException: on err...
python
def GetCpuUsedMs(self): '''Retrieves the number of milliseconds during which the virtual machine has used the CPU. This value includes the time used by the guest operating system and the time used by virtualization code for tasks for this virtual machine. You can combine this va...
python
def components(models, wrap_script=True, wrap_plot_info=True, theme=FromCurdoc): ''' Return HTML components to embed a Bokeh plot. The data for the plot is stored directly in the returned HTML. An example can be found in examples/embed/embed_multiple.py The returned components assume that BokehJS reso...
java
public long setLongValue(long value) throws ControlException { long v = 0; if(type!=V4L4JConstants.CTRL_TYPE_LONG) throw new UnsupportedMethod("This control is not a long control"); state.get(); try { doSetLongValue(v4l4jObject,id, value); v = doGetLongValue(v4l4jObject, id); } finally { ...
java
synchronized boolean addInterval(Interval i) { if (i == null || containsInterval(i) || !intervals.add(i)) { return false; } Object iStart = i.getStart(); Object iFinish = i.getFinish(); directedGraph.add(iStart); directedGraph.add(iFinish); Weight m...
java
Rule Voice() { return Sequence( ALPHASandDIGITS().label("VoiceNumber"), ZeroOrMoreS( SequenceS(suppr(WSPS()), FirstOfS(VoiceName(), VoiceSubname(), VoiceTranspose(), VoiceMerge(), VoiceStems(), VoiceStaves(), VoiceBracket(), ClefMiddle(), /* clef */ //V: RH1 clef...
java
@Override public boolean addAll(Collection<? extends Object> args) { boolean result = false; for (Object obj : args) { result = true; add(obj); } return result; }
python
def _get_search_page( self, query, page, per_page=1000, mentions=3, data=False, ): """ Retrieve one page of search results from the DocumentCloud API. """ if mentions > 10: raise ValueError("You cannot search for more than 1...
java
public BufferedImage renderWaveform(Wave wave, int width) { // for signed signals, the middle is 0 (-1 ~ 1) double middleLine = 0; // usually 8bit is unsigned if (wave.getWaveHeader().getBitsPerSample() == 8) { // for unsigned signals, the middle is 0.5 (0~1) middleLine = 0.5; ...
java
public CMAArray<CMAWebhookCall> calls(CMAWebhook webhook) { final String spaceId = getSpaceIdOrThrow(webhook, "webhook"); final String webhookId = getResourceIdOrThrow(webhook, "webhook"); return service.calls(spaceId, webhookId).blockingFirst(); }
python
def bs_tt_bblock (times, tstarts, tstops, p0=0.05, nbootstrap=512): """Bayesian Blocks for time-tagged events with bootstrapping uncertainty assessment. THE UNCERTAINTIES ARE NOT VERY GOOD! Arguments: tstarts - Array of input bin start times. tstops - Array of input bin stop times. t...
java
public void setSelectedIndex (int selidx) { // update the display updateSelection(selidx); // let the model know what's up Object item = (selidx == -1) ? null : _model.getElementAt(selidx); _model.setSelectedItem(item); }
java
protected GroovyCodeSource getScriptSource(boolean isScriptFile, String script) throws IOException, URISyntaxException { //check the script is currently valid before starting a server against the script if (isScriptFile) { // search for the file and if it exists don't try to use URIs ... ...
java
@Override public String pageHtml(int segment, String helpUrl) { return pageHtml(segment, helpUrl, null); }
java
public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : new SynchronizedList<>(list)); }
java
public Map<String, List<Item>> getTableItems() { Map<String, List<Map<String, AttributeValue>>> res = result.getResponses(); Map<String, List<Item>> map = new LinkedHashMap<String, List<Item>>(res.size()); for (Map.Entry<String, List<Map<String, AttributeValue>>> e ...
python
def write_config(config, config_path=CONFIG_PATH): """Write the config to the output path. Creates the necessary directories if they aren't there. Args: config (configparser.ConfigParser): A ConfigParser. """ if not os.path.exists(config_path): os.makedirs(os.path.dirname(config_pat...
java
@Override public Snapshot requestRestoreSnapshot(String snapshotId, DuracloudEndPointConfig destination, String userEmail) throws SnapshotException { checkInitialized(); Snapshot snapshot = getSnapshot(snapshotId); String host = destination.getHost(); String port = destina...
python
def node_link_graph(data: Mapping[str, Any]) -> BELGraph: """Return graph from node-link data format. Adapted from :func:`networkx.readwrite.json_graph.node_link_graph` """ graph = BELGraph() graph.graph = data.get('graph', {}) graph.graph[GRAPH_ANNOTATION_LIST] = { keyword: set(values)...
java
@Nonnull @OverrideOnDemand protected TOOLBAR_TYPE createViewToolbar (@Nonnull final WPECTYPE aWPEC, final boolean bCanGoBack, @Nonnull final DATATYPE aSelectedObject) { final Locale aDisplayLocale = aWPEC.getDisplayLocale ...
java
public CreateCaseRequest withCcEmailAddresses(String... ccEmailAddresses) { if (this.ccEmailAddresses == null) { setCcEmailAddresses(new com.amazonaws.internal.SdkInternalList<String>(ccEmailAddresses.length)); } for (String ele : ccEmailAddresses) { this.ccEmailAddresses...
java
private static String validString(Object data) throws IOException { // Null is ok if (data == null) { return ""; } if (!(data instanceof String)) { throw new IOException("Invalid non-String value found!"); } return (String) data; }
java
@Override public int size () { int size = Smb2Constants.SMB2_HEADER_LENGTH + 40; if ( this.inputBuffer != null ) { size += this.inputBuffer.size(); } return size8(size); }
java
public static <T> Format<T> newCSVFormat(Class<T> beanType) { return new CSVFormat<T>(beanType); }
java
public void removeBookmarkedURL(String bookmarkURL) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { retrieveBookmarks(); Iterator<BookmarkedURL> it = bookmarks.getBookmarkedURLS().iterator(); while (it.hasNext()) { BookmarkedURL bookmark ...
python
def export_obo(path_to_file, connection=None): """export database to obo file :param path_to_file: path to export file :param connection: connection string (optional) :return: """ db = DbManager(connection) db.export_obo(path_to_export_file=path_to_file) db.session.close()
python
def GetStopTimes(self, problems=None): """Return a sorted list of StopTime objects for this trip.""" # In theory problems=None should be safe because data from database has been # validated. See comment in _LoadStopTimes for why this isn't always true. cursor = self._schedule._connection.cursor() cu...
java
public static Variable getVariable(NameSpace ns, String name) { if (null == ns) return null; try { return ns.getVariableImpl(name, false); } catch (Exception e) { return null; } }
java
public static servicegroup[] get(nitro_service service, servicegroup_args args) throws Exception{ servicegroup obj = new servicegroup(); options option = new options(); option.set_args(nitro_util.object_to_string_withoutquotes(args)); servicegroup[] response = (servicegroup[])obj.get_resources(service, option);...
java
public void init(FilterConfig filterConfig) throws ServletException { ctx = filterConfig.getServletContext(); String temp = filterConfig.getInitParameter("debug"); debug = (String.valueOf(temp).equals("true")); }
java
public synchronized String generateId() { final StringBuilder sb = new StringBuilder(this.length); sb.append(this.seed); sb.append(this.sequence.getAndIncrement()); return sb.toString(); }
python
def get_canonical_headers(headers): """Canonicalize headers for signing. See: https://cloud.google.com/storage/docs/access-control/signed-urls#about-canonical-extension-headers :type headers: Union[dict|List(Tuple(str,str))] :param headers: (Optional) Additional HTTP headers to be included...