language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def check_is_a_string(var, allow_none=False): """ Calls is_a_string and raises a type error if the check fails. """ if not is_a_string(var, allow_none=allow_none): raise TypeError("var must be a string, however type(var) is {}" .format(type(var)))
java
public long foldLeft(long seed, LongBinaryOperator accumulator) { long[] box = new long[] { seed }; forEachOrdered(t -> box[0] = accumulator.applyAsLong(box[0], t)); return box[0]; }
python
def transChicane(bend_length=None, bend_field=None, drift_length=None, gamma=None): """ Transport matrix of chicane composed of four rbends and three drifts between them :param bend_length: rbend width in [m] :param bend_field: rbend magnetic field in [T] :param drift_length: drift length, list...
python
def _index_document(self, document, force=False): """ Adds document to the index. """ query = text(""" INSERT INTO dataset_index(vid, title, keywords, doc) VALUES(:vid, :title, :keywords, :doc); """) self.backend.library.database.connection.execute(query, **docume...
java
public Observable<ServiceResponse<LanguageBatchResult>> detectLanguageWithServiceResponseAsync(List<Input> documents) { if (this.client.azureRegion() == null) { throw new IllegalArgumentException("Parameter this.client.azureRegion() is required and cannot be null."); } Validator.vali...
java
public void setTranslationArrayStandaloneLongMonthNames(String[] newTranslationArray) { if (newTranslationArray == null) { String[] defaultLongMonthNames = ExtraDateStrings.getDefaultStandaloneLongMonthNamesForLocale(locale); this.translationArrayStandaloneLongMonthNames ...
java
protected boolean generatePythonConstructors(String container, List<? extends XtendMember> members, PyAppendable it, IExtraLanguageGeneratorContext context) { // Prepare field initialization boolean hasConstructor = false; for (final XtendMember member : members) { if (context.getCancelIndicator().isCancele...
java
void setInstallOrOpenCallback(Branch.BranchReferralInitListener callback) { synchronized (reqQueueLockObject) { for (ServerRequest req : queue) { if (req != null) { if (req instanceof ServerRequestRegisterInstall) { ((ServerRequestRegisterI...
python
def sfs_folded(ac, n=None): """Compute the folded site frequency spectrum given reference and alternate allele counts at a set of biallelic variants. Parameters ---------- ac : array_like, int, shape (n_variants, 2) Allele counts array. n : int, optional The total number of chro...
python
def is_same(type1, type2): """returns True, if type1 and type2 are same types""" nake_type1 = remove_declarated(type1) nake_type2 = remove_declarated(type2) return nake_type1 == nake_type2
python
def _get_bin_width(stdev, count): """Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501 """ w = int(round((3.5 * stdev) / (count ** (1.0 / 3)))) if w: return w else: return 1
java
public static snmpmib get(nitro_service service, options option) throws Exception{ snmpmib obj = new snmpmib(); snmpmib[] response = (snmpmib[])obj.get_resources(service,option); return response[0]; }
java
private Object[] getPersonGroupMemberKeys(IGroupMember gm) { Object[] keys = null; EntityIdentifier ei = gm.getUnderlyingEntityIdentifier(); IPersonAttributes attr = personAttributeDao.getPerson(ei.getKey()); if (attr != null && attr.getAttributes() != null && !attr.getAttributes().isEmp...
python
def strip_sdist_extras(filelist): """Strip generated files that are only present in source distributions. We also strip files that are ignored for other reasons, like command line arguments, setup.cfg rules or MANIFEST.in rules. """ return [name for name in filelist if not file_matches(...
java
AvroYarnJobSubmissionParameters fromInputStream(final InputStream inputStream) throws IOException { final JsonDecoder decoder = DecoderFactory.get().jsonDecoder( AvroYarnJobSubmissionParameters.getClassSchema(), inputStream); final SpecificDatumReader<AvroYarnJobSubmissionParameters> reader = new Sp...
java
public static Object toArray( JSONArray jsonArray, Object root, JsonConfig jsonConfig ) { Class objectClass = root.getClass(); if( jsonArray.size() == 0 ){ return Array.newInstance( objectClass, 0 ); } int[] dimensions = JSONArray.getDimensions( jsonArray ); Object array = Array....
python
def mutator(arg=None): """Structures mutator functions by allowing handlers to be registered for different types of event. When the decorated function is called with an initial value and an event, it will call the handler that has been registered for that type of event. It works like singledisp...
java
@Override public HandlerRegistration addGeometryIndexHighlightBeginHandler(GeometryIndexHighlightBeginHandler handler) { return editingService.getEventBus().addHandler(GeometryIndexHighlightBeginHandler.TYPE, handler); }
java
public Object remove(Object key) { if (key == null) return null; purge(); int hash = hashCode(key); int index = indexFor(hash); Entry previous = null; Entry entry = table[index]; while (entry != null) { if ((hash == entry.hash) &&...
java
public DirectConnectGatewayAssociationProposal withExistingAllowedPrefixesToDirectConnectGateway( RouteFilterPrefix... existingAllowedPrefixesToDirectConnectGateway) { if (this.existingAllowedPrefixesToDirectConnectGateway == null) { setExistingAllowedPrefixesToDirectConnectGateway(new c...
python
def set_mrl(self, mrl, *options): """Set the MRL to play. Warning: most audio and video options, such as text renderer, have no effects on an individual media. These options must be set at the vlc.Instance or vlc.MediaPlayer instanciation. @param mrl: The MRL @param opt...
java
final public void decrement(long val) { if (!enabled) return; lastSampleTime = System.currentTimeMillis(); if (!sync) { count -= val; } else { synchronized (this) { count -= val; } } }
python
def load(self, laser_plugin: LaserPlugin) -> None: """ Loads the plugin :param laser_plugin: plugin that will be loaded in the symbolic virtual machine """ log.info("Loading plugin: {}".format(str(laser_plugin))) laser_plugin.initialize(self.symbolic_vm) self.laser_plugi...
java
public boolean hasEquivalentTransitions(TimeZone tz, long start, long end) { return hasEquivalentTransitions(tz, start, end, false); }
java
public String convertIfcDamperTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
private MessageBuffer getNextBuffer() throws IOException { MessageBuffer next = in.next(); if (next == null) { throw new MessageInsufficientBufferException(); } assert (buffer != null); totalReadBytes += buffer.size(); return next; }
python
def gridsearch(self, X, y, weights=None, return_scores=False, keep_best=True, objective='auto', progress=True, **param_grids): """ Performs a grid search over a space of parameters for a given objective Warnings -------- ``gridsearch...
java
public String doSecurePost(String host, String path, String postData, int port, Map<String, String> headers, int timeout) throws UnknownHostException, ConnectException, IOException { return doHttpCall(host, path, postData, port, hea...
java
static void register(Transcoder transcoder) { Entry entry = makeEntry(transcoder.source, transcoder.destination); if (entry.transcoder != null) throw new TranscoderException(ErrorMessages.ERR_TRANSCODER_ALREADY_REGISTERED, new String(transcoder.source + " to " + new Strin...
python
def convert_l_to_rgba(self, row, result): """ Convert a grayscale image to RGBA. This method assumes the alpha channel in result is already correctly initialized. """ for i in range(len(row) // 3): for j in range(3): result[(4 * i) + j] = row[...
java
public static Map<String,String> unserializeBuildInfo(final String buildInfo) throws IOException { final ObjectMapper mapper = new ObjectMapper(); mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS); return mapper.readValue(buildInfo, new TypeReference<Map<String, Object>>(){}); }
java
public ListFleetsResult withFleetSummaryList(FleetSummary... fleetSummaryList) { if (this.fleetSummaryList == null) { setFleetSummaryList(new java.util.ArrayList<FleetSummary>(fleetSummaryList.length)); } for (FleetSummary ele : fleetSummaryList) { this.fleetSummaryList.a...
java
private static boolean pointEqualsPoint_(Point2D pt_a, Point2D pt_b, double tolerance, ProgressTracker progress_tracker) { if (Point2D.sqrDistance(pt_a, pt_b) <= tolerance * tolerance) return true; return false; }
java
protected final String getForEFSave(final Class<?> pClass) { if (SeGoodsSpecifics.class == pClass) { return PrcSeGdSpecEmbFlSave.class.getSimpleName(); } else if (SeServiceSpecifics.class == pClass) { return PrcSeSrvSpecEmbFlSave.class.getSimpleName(); } return null; }
python
def setBendField(self, x): """ set bend magnetic field :param x: new bend field to be assigned, [T] :return: None """ if x != self.bend_field: self.bend_field = x self.refresh = True
python
def acc_difference(points): """ Computes the accelaration difference between each adjacent point Args: points (:obj:`Point`) Returns: :obj:`list` of int: Indexes of changepoints """ data = [0] for before, after in pairwise(points): data.append(before.acc - after.acc) ...
java
public void setUserImage(CmsObject cms, CmsUser user, String rootPath) throws CmsException { CmsFile tempFile = cms.readFile(cms.getRequestContext().removeSiteRoot(rootPath)); CmsImageScaler scaler = new CmsImageScaler(tempFile.getContents(), tempFile.getRootPath()); if (scaler.isValid()) { ...
python
def get_hexagram(method='THREE COIN'): """ Return one or two hexagrams using any of a variety of divination methods. The ``NAIVE`` method simply returns a uniformally random ``int`` between ``1`` and ``64``. All other methods return a 2-tuple where the first value represents the starting hexag...
java
private boolean isDerived(JavaClass fqCls, FQMethod key) { try { for (JavaClass infCls : fqCls.getInterfaces()) { for (Method infMethod : infCls.getMethods()) { if (key.getMethodName().equals(infMethod.getName())) { if (infMethod.getGeneric...
python
def venues(self): """Get a list of all venue objects. >>> venues = din.venues() """ response = self._request(V2_ENDPOINTS['VENUES']) # Normalize `dateHours` to array for venue in response["result_data"]["document"]["venue"]: if venue.get("id") in VENUE_NAME...
python
def applyQuery( self ): """ Sets the query for this widget from the quick query text builder. """ query = Q.fromString(nativestring(self.uiQueryTXT.text())) self.setQuery(query) self.uiQueryTXT.setText('')
python
def p_iteration_statement_5(self, p): """ iteration_statement : \ FOR LPAREN VAR identifier IN expr RPAREN statement """ p[0] = ast.ForIn(item=ast.VarDecl(p[4]), iterable=p[6], statement=p[8])
java
public WellRestedRequestBuilder globalHeaders(Map<String, String> globalHeaders) { this.globalHeaders = WellRestedUtil.buildHeaders(globalHeaders); return this; }
java
public static void exports(Xml root, Animation animation) { Check.notNull(root); Check.notNull(animation); final Xml node = root.createChild(ANIMATION); node.writeString(ANIMATION_NAME, animation.getName()); node.writeInteger(ANIMATION_START, animation.getFirst()); ...
java
public static String serializeSet(Set<?> set) { if (set == null) { set = new HashSet<String>(); } XStream xstream = new XStream(new DomDriver()); return xstream.toXML(set); }
python
def encoded(self): """ This function will encode all the attributes to 256 bit integers :return: """ encoded = {} for i in range(len(self.credType.names)): self.credType.names[i] attr_types = self.credType.attrTypes[i] for at in attr...
java
@Override protected void perturbation(List<DoubleSolution> swarm) { nonUniformMutation.setCurrentIteration(currentIteration); for (int i = 0; i < swarm.size(); i++) { if (i % 3 == 0) { nonUniformMutation.execute(swarm.get(i)); } else if (i % 3 == 1) { uniformMutation.exec...
python
def license_fallback(vendor_dir, sdist_name): """Hardcoded license URLs. Check when updating if those are still needed""" libname = libname_from_dir(sdist_name) if libname not in HARDCODED_LICENSE_URLS: raise ValueError('No hardcoded URL for {} license'.format(libname)) url = HARDCODED_LICENSE_...
python
def cp(args): """ find folder -type l | %prog cp Copy all the softlinks to the current folder, using absolute paths """ p = OptionParser(cp.__doc__) fp = sys.stdin for link_name in fp: link_name = link_name.strip() if not op.exists(link_name): continue ...
java
public static void join(Writer writer, List<? extends EncodedPair> pairs, char pairSep, char nameValSep) throws IOException { join(writer, pairs, pairSep, nameValSep, false, false); }
java
public ServiceFuture<ContainerServiceInner> getByResourceGroupAsync(String resourceGroupName, String containerServiceName, final ServiceCallback<ContainerServiceInner> serviceCallback) { return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, containerServiceName), servic...
java
public static CharSequence getJSDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return getJSDate(calendar); }
java
public static Bitmap scale(Bitmap src, int dw, int dh) { Bitmap res = Bitmap.createBitmap(dw, dh, Bitmap.Config.ARGB_8888); scale(src, res); return res; }
java
public Vector3f mul(float x, float y, float z) { return mul(x, y, z, thisOrNew()); }
java
public Map<String, I_CmsFormatterBean> getFormatterSelection(String containerTypes, int containerWidth) { Map<String, I_CmsFormatterBean> result = new LinkedHashMap<String, I_CmsFormatterBean>(); for (I_CmsFormatterBean formatter : Collections2.filter( m_allFormatters, new Match...
python
def split_type(cls, type_name): """Split type of a type name with CardinalityField suffix into its parts. :param type_name: Type name (as string). :return: Tuple (type_basename, cardinality) """ if cls.matches_type(type_name): basename = type_name[:-1] c...
java
public SectionHeader getSectionHeader(String sectionName) { for (SectionHeader entry : headers) { if (entry.getName().equals(sectionName)) { return entry; } } throw new IllegalArgumentException( "invalid section name, no section header foun...
python
def within_bbox(self, bbox): """ :param bbox: a quartet (min_lon, min_lat, max_lon, max_lat) :returns: site IDs within the bounding box """ min_lon, min_lat, max_lon, max_lat = bbox lons, lats = self.array['lon'], self.array['lat'] if cross...
java
public Timestamp withLocalOffset(Integer offset) { Precision precision = getPrecision(); if (precision.alwaysUnknownOffset() || safeEquals(offset, getLocalOffset())) { return this; } Timestamp ts = createFromUtcFields(precision, ...
java
@Requires("label != null") protected static boolean labelIsResolved(Label label) { try { label.getOffset(); } catch (IllegalStateException e) { return false; } return true; }
python
def _calc_overlap_coef( markers1: dict, markers2: dict, ): """Calculate overlap coefficient between the values of two dictionaries Note: dict values must be sets """ overlap_coef=np.zeros((len(markers1), len(markers2))) j=0 for marker_group in markers1: tmp = [len(markers2[i].i...
java
public String getLevel() { try { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); return loggerContext.getLogger("root").getLevel().toString(); } catch (Exception e) { e.printStackTrace(); return ""; } }
python
def parse_xrefs(self, token): """Search token for +value+ and !variable! style references. Be careful to not xref a new variable. """ out, end = [], 0 token = token.replace("\\n", "\n") for m in re.finditer(self.xref_registry, token, re.VERBOSE | re.DOTALL): if m.star...
python
def _get_args(cls, **kwargs): """Parse style and locale. Argument location precedence: kwargs > view_args > query """ csl_args = { 'style': cls._default_style, 'locale': cls._default_locale } if has_request_context(): parser = FlaskPa...
python
def register(): """Register DDO of a new asset --- tags: - ddo consumes: - application/json parameters: - in: body name: body required: true description: DDO of the asset. schema: type: object required: - "@context" ...
java
@Override protected BundleRenderer createRenderer(FacesContext context) { ResourceBundlesHandler rsHandler = getResourceBundlesHandler(context); String type = (String) getAttributes().get(JawrConstant.TYPE_ATTR); boolean async = Boolean.parseBoolean((String) getAttributes().get(JawrConstant.ASYNC_ATTR)); bool...
python
def _diff_(src, dst, ret=None, jp=None, exclude=[], include=[]): """ compare 2 dict/list, return a list containing json-pointer indicating what's different, and what's diff exactly. - list length diff: (jp, length of src, length of dst) - dict key diff: (jp, None, None) - when src is dict or list, ...
java
@Override public synchronized SnapshotContentItem read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { if (this.items == null) { this.items = new StreamingIterator<>(new JpaIteratorSource<SnapshotContentItemRepo, SnapshotCont...
python
def update_iptables(self): """Update iptables based on information in the rule_info.""" # Read the iptables iptables_cmds = ['iptables-save', '-c'] all_rules = dsl.execute(iptables_cmds, root_helper=self._root_helper, log_output=False) # For each...
java
public void handleTrace(HttpRequest request, HttpResponse response) throws IOException { boolean trace=getHttpContext().getHttpServer().getTrace(); // Handle TRACE by returning request header response.setField(HttpFields.__ContentType, ...
java
public static int serialize(final File directory, String name, Object obj) { try (FileOutputStream stream = new FileOutputStream(new File(directory, name))) { return serialize(stream, obj); } catch (IOException e) { throw new ReportGenerationException(e); } }
java
public java.util.Map<String, java.util.List<String>> getOverriddenParameters() { return overriddenParameters; }
java
@Override public void onError(InvocationContext context, Exception error) { throw InvocationException.newInstance(context, error); }
java
public List<IAssociativeReducer> deserializeReducerList(String str) { return load(str, ListWrappers.ReducerList.class).getList(); }
python
def get_url( width, height=None, background_color="cccccc", text_color="969696", text=None, random_background_color=False ): """ Craft the URL for a placeholder image. You can customize the background color, text color and text using the optional keyword arguments If you want to use a rand...
python
def print_agi_and_mpe_balances(self): """ Print balance of ETH, AGI, and MPE wallet """ if (self.args.account): account = self.args.account else: account = self.ident.address eth_wei = self.w3.eth.getBalance(account) agi_cogs = self.call_contract_command(...
python
def gsum_(self, col: str, index_col: bool=True) -> "Ds": """ Group by and sum column :param col: column to group :type col: str :param index_col: :type index_col: bool :return: a dataswim instance :rtype: Ds :example: ``ds2 = ds.gsum("Col 1")`` ...
python
def handle_aggregated_quotas(sender, instance, **kwargs): """ Call aggregated quotas fields update methods """ quota = instance # aggregation is not supported for global quotas. if quota.scope is None: return quota_field = quota.get_field() # usage aggregation should not count another us...
python
def _iter_module_subclasses(package, module_name, base_cls): """inspect all modules in this directory for subclasses of inherit from ``base_cls``. inpiration from http://stackoverflow.com/q/1796180/564709 """ module = importlib.import_module('.' + module_name, package) for name, obj in inspect.getme...
java
public static double cdf(double x, double mu, double sigma) { if(x <= 0.) { return 0.; } return .5 * (1 + NormalDistribution.erf((FastMath.log(x) - mu) / (MathUtil.SQRT2 * sigma))); }
python
def _gather_field_values( item, *, fields=None, field_map=FIELD_MAP, normalize_values=False, normalize_func=normalize_value): """Create a tuple of normalized metadata field values. Parameter: item (~collections.abc.Mapping, str, os.PathLike): Item dict or filepath. fields (list): A list of fields used to compa...
python
def request(self, method, endpoint, body=None, timeout=-1): """ Perform a request with a given body to a given endpoint in UpCloud's API. Handles errors with __error_middleware. """ if method not in set(['GET', 'POST', 'PUT', 'DELETE']): raise Exception('Invalid/Forb...
python
def get_cluster_custom_object_status(self, group, version, plural, name, **kwargs): # noqa: E501 """get_cluster_custom_object_status # noqa: E501 read status of the specified cluster scoped custom object # noqa: E501 This method makes a synchronous HTTP request by default. To make an ...
python
def get_config_path(): """Put together the default configuration path based on OS.""" dir_path = (os.getenv('APPDATA') if os.name == "nt" else os.path.expanduser('~')) return os.path.join(dir_path, '.vtjp')
python
def inserir( self, id_equipamento, fqdn, user, password, id_tipo_acesso, enable_pass): """Add new relationship between equipment and access type and returns its id. :param id_equipamento: Equipment identifier. :...
python
def handle_pause(self): """Read pause signal from server""" flag = self.reader.byte() if flag > 0: logger.info(" -> pause: on") self.controller.playing = False else: logger.info(" -> pause: off") self.controller.playing = True
java
public static Field getDeclaredFieldWithPath(Class<?> clazz, String path) { int lastDot = path.lastIndexOf('.'); if (lastDot > -1) { String parentPath = path.substring(0, lastDot); String fieldName = path.substring(lastDot + 1); Field parentField = getDeclaredFieldW...
python
async def get_data(self): """Retrieve the data.""" try: with async_timeout.timeout(5, loop=self._loop): response = await self._session.get(self.url) _LOGGER.debug( "Response from Volkszaehler API: %s", response.status) self.data = awai...
python
def replace_all(self, text=None): """ Replaces all occurrences in the editor's document. :param text: The replacement text. If None, the content of the lineEdit replace will be used instead """ cursor = self.editor.textCursor() cursor.beginEditBlock(...
java
void endOptional(boolean successful) { if (successful) { parsed.remove(parsed.size() - 2); } else { parsed.remove(parsed.size() - 1); } }
java
public boolean containsAnnotation(BackedAnnotatedType<?> annotatedType, Class<? extends Annotation> requiredAnnotation) { // class level annotations if (containsAnnotation(annotatedType.getAnnotations(), requiredAnnotation, true)) { return true; } for (Class<?> clazz = annota...
java
public void addLine(String line) { try { writer.append(line); writer.newLine(); } catch (IOException e) { e.printStackTrace(); } }
java
public static base_response update(nitro_service client, nshttpparam resource) throws Exception { nshttpparam updateresource = new nshttpparam(); updateresource.dropinvalreqs = resource.dropinvalreqs; updateresource.markhttp09inval = resource.markhttp09inval; updateresource.markconnreqinval = resource.markconnr...
python
def check_can_approve(self, request, application, roles): """ Check the person's authorization. """ try: authorised_persons = self.get_authorised_persons(application) authorised_persons.get(pk=request.user.pk) return True except Person.DoesNotExist: ...
python
def get_library_version(): """ Get the version number of the underlying gphoto2 library. :return: The version :rtype: tuple of (major, minor, patch) version numbers """ version_str = ffi.string(lib.gp_library_version(True)[0]).decode() return tuple(int(x) for x in version_str.split('.'))
java
public static void main(final String[] args) { Switch about = new Switch("a", "about", "display about message"); Switch help = new Switch("h", "help", "display help message"); StringListArgument snpIdFilter = new StringListArgument("s", "snp-ids", "filter by snp id", true); FileArgument ...
java
@Override public Object get(PageContext pc, Collection.Key key) throws PageException { return COMUtil.toObject(this, Dispatch.call(dispatch, key.getString()), key.getString()); }
java
Rule NonQuoteOneTextLine() { //TODO TexText? return FirstOf(SP(), '!', CharRange('#', ':'), CharRange('<', '~'), LatinExtendedAndOtherAlphabet() ).label(NonQuoteOneTextLine).suppressSubnodes(); }
java
void setValidityCheck(PassFactory validityCheck) { this.validityCheck = validityCheck; this.changeVerifier = new ChangeVerifier(compiler).snapshot(jsRoot); }
python
def insertDataset(self, businput): """ input dictionary must have the following keys: dataset, primary_ds_name(name), processed_ds(name), data_tier(name), acquisition_era(name), processing_version It may have following keys: physics_group(name), xtcrosssection, creation_d...