language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_form(self, key, form_class=None): """ Returns an instance of the form to be used in this view. """ if form_class is None: form_class = self.get_form_class(key) return form_class(**self.get_form_kwargs(key))
python
def bearer_auth(): """Prompts the user for authorization using bearer authentication. --- tags: - Auth parameters: - in: header name: Authorization schema: type: string produces: - application/json responses: 200: description: Sucessful a...
java
public T withCroppedThumbnail(double scale, int maxWidth, int maxHeight) { return withCroppedThumbnail(Paths.get(location.toString(), "./thumbnails").toString(), "thumb_" + fileName, scale, maxWidth,maxHeight); }
java
public static Date addMinutes(@NotNull final Date date, int amount) { return DateUtils.addMinutes(date, amount); }
java
@Override public DBSecurityGroup authorizeDBSecurityGroupIngress(AuthorizeDBSecurityGroupIngressRequest request) { request = beforeClientExecution(request); return executeAuthorizeDBSecurityGroupIngress(request); }
python
def stream_to_file(self, filename): """ :param filename: str of the file name to stream the data to :return: None """ stream_size = 0 try: partial_chunk = '' chunk_size = 1024 m3u8_dir = None if filename[-5:].lower() == '.m3...
java
public JSONObject put(String key, long value) throws JSONException { put(key, Long.valueOf(value)); return this; }
python
def get_item_data(self, item): """Get tree item user data: (filename, line_number)""" filename, line_number_str = get_item_user_text(item).split(self.SEP) return filename, int(line_number_str)
python
def isHandlerPresent(self, event_name): """Check if an event has an handler.""" if event_name not in self.handlers: raise ValueError('{} is not a valid event'.format(event_name)) return self.handlers[event_name] is not None
java
public ImageDescriptor image(SarlAction action) { final JvmOperation jvmElement = this.jvmModelAssociations.getDirectlyInferredOperation(action); return this.images.forOperation( action.getVisibility(), this.adornments.get(jvmElement)); }
python
def servers_with_roles(self, roles, env=None, match_all=False): """ Get servers with the given roles. If env is given, then the environment must match as well. If match_all is True, then only return servers who have all of the given roles. Otherwise, return servers that have one or mor...
java
@Override public EClass getIfcGeographicElement() { if (ifcGeographicElementEClass == null) { ifcGeographicElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(300); } return ifcGeographicElementEClass; }
python
def delete_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, **kwargs): """Delete FreeShippingCoupon Delete an instance of FreeShippingCoupon by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >...
java
@Override public StartContinuousExportResult startContinuousExport(StartContinuousExportRequest request) { request = beforeClientExecution(request); return executeStartContinuousExport(request); }
python
def split_css_for_ie_selector_limit(input_file, output_file): """ Splits a large CSS file into several smaller files, each one containing less than the IE 4096 selector limit. """ from .modules import bless, utils if not isinstance(input_file, str): raise RuntimeError('CSS splitter take...
python
def get_pmap_from_csv(oqparam, fnames): """ :param oqparam: an :class:`openquake.commonlib.oqvalidation.OqParam` instance :param fnames: a space-separated list of .csv relative filenames :returns: the site mesh and the hazard curves read by the .csv files """ if not oqpar...
java
public PushRules updatePushRules(Object projectIdOrPath, PushRules pushRule) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm() .withParam("deny_delete_tag", pushRule.getDenyDeleteTag()) .withParam("member_check", pushRule.getMemberCheck()) .withParam("p...
java
private Map<String, VariantSet> getVariants(String defaultSkin, Set<String> skinNames, String defaultLocaleName, Set<String> localeVariants) { Map<String, VariantSet> skinVariants = new HashMap<>(); if (!skinNames.isEmpty()) { skinVariants.put(JawrConstant.SKIN_VARIANT_TYPE, new VariantSet(JawrConstant....
java
@RequiresApi(Build.VERSION_CODES.KITKAT) @NonNull public static ProviderClient getProviderClient( @NonNull final Context context, @NonNull final String authority) { final Uri contentUri = new Uri.Builder() .scheme(ContentResolver.SCHEME_CONTENT) .a...
java
@SuppressWarnings("unchecked") public static final void getXMLPermissions(ArrayList[] securityRoles, boolean[] permitAll, boolean[] denyAll, int type, ...
java
@Deprecated public synchronized void start(String emulatorDir, String projectId, String... commandLineOptions) throws DatastoreEmulatorException { checkNotNull(emulatorDir, "emulatorDir cannot be null"); checkNotNull(projectId, "projectId cannot be null"); checkState(state == State.NEW, "Cannot call...
java
@Override public GoogleCloudStorageFileSet finish(Collection<? extends OutputWriter<ByteBuffer>> writers) throws IOException { List<String> fileNames = new ArrayList<>(); for (OutputWriter<ByteBuffer> writer : writers) { SizeSegmentingGoogleCloudStorageFileWriter segWriter = (SizeSegment...
java
@BetaApi public final void deleteZoneOperation(String operation) { DeleteZoneOperationHttpRequest request = DeleteZoneOperationHttpRequest.newBuilder().setOperation(operation).build(); deleteZoneOperation(request); }
java
public static Calendar parse(final String date, final DateTimeFormatter format) { return format.parseDateTime(date).toGregorianCalendar(); }
java
public static <T extends ImageGray<T>> PyramidFloat<T> scaleSpacePyramid( double scaleSpace[], Class<T> imageType ) { double[] sigmas = new double[ scaleSpace.length ]; sigmas[0] = scaleSpace[0]; for( int i = 1; i < scaleSpace.length; i++ ) { // the desired amount of blur double c = scaleSpace[i]; // ...
java
public static Executor monitor(MeterRegistry registry, Executor executor, String executorName, Tag... tags) { return monitor(registry, executor, executorName, asList(tags)); }
java
private static boolean match(String string, String pattern) { if (string == null || string.isEmpty()) { return false; } String[] wcs = tokenize(pattern); boolean anyChars = false; int textIdx = 0; int wcsIdx = 0; Stack<int[]> backtrack = new Stack<int[]>(); // loop around a backtrack sta...
python
def load_labware_by_name(self, name: str) -> Labware: """ Specify the presence of a piece of labware on the module. :param name: The name of the labware object. :returns: The initialized and loaded labware object. """ lw = load(name, self._geometry.location) return self....
java
@Override protected URL buildResource(final StyleSheetItem ssi, final StyleSheetParams ssp) { URL cssURL = null; if (ssp instanceof StyleSheet) { // Build the requested font cssURL = buildStyleSheetUrl((StyleSheet) ssp); } return cssURL; }
python
def getInputOrder(ast, input_order=None): """Derive the input order of the variables in an expression. """ variables = {} for a in ast.allOf('variable'): variables[a.value] = a variable_names = set(variables.keys()) if input_order: if variable_names != set(input_order): ...
python
def to_dict(self): # cls, self): """Convert Docpie into a JSONlizable dict. Use it in this way: pie = Docpie(__doc__) json.dumps(pie.convert_2_dict()) Note the `extra` info will be lost if you costomize that, because a function is not JSONlizable. You can use `...
java
@Override @SuppressWarnings({"checkstyle:methodlength", "checkstyle:cyclomaticcomplexity", "checkstyle:npathcomplexity", "checkstyle:booleanexpressioncomplexity"}) protected void transform(final XtendFunction source, final JvmGenericType container, boolean allowDispatch) { final GenerationContext context = getCo...
python
def show_top(queue=False, **kwargs): ''' Return the top data that the minion will use for a highstate CLI Example: .. code-block:: bash salt '*' state.show_top ''' if 'env' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('env') conflict = _check_que...
python
def sigma_s2(self, r, R, kwargs_profile, kwargs_anisotropy, kwargs_light): """ projected velocity dispersion :param r: :param R: :param r_ani: :param a: :param gamma: :param phi_E: :return: """ beta = self.anisotropy.beta_r(r, kwarg...
java
public void put(SimpleEntry simpleEntry) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "put", simpleEntry); simpleEntry.previous = last; simpleEntry.list = this; if(last != null) last.next = simpleEntry; else first = simpleEntr...
java
public LabelCache labels(String monitorId) { LabelCache cache = labels.get(monitorId); if(cache == null) labels.put(monitorId, cache = new LabelCache(monitorId)); return cache; }
java
public static OnLineStatistics remove(OnLineStatistics A, OnLineStatistics B) { OnLineStatistics toRet = A.clone(); toRet.remove(B); return toRet; }
java
@Override public IPortletEntity getPortletEntity( HttpServletRequest request, String portletEntityIdString) { final IPortletEntityId portletEntityId = this.parseConsistentPortletEntityId(request, portletEntityIdString); return this.getPortletEntity(request, portletEntityI...
python
def convert_color(color): """ Converts a color from "color", (255, 255, 255) or "#ffffff" into a color tk should understand. """ if color is not None: # is the color a string if isinstance(color, str): # strip the color of white space color = color.strip() ...
java
public HtmlPolicyBuilder disallowUrlProtocols(String... protocols) { invalidateCompiledState(); for (String protocol : protocols) { protocol = Strings.toLowerCase(protocol); allowedProtocols.remove(protocol); } return this; }
python
def _find_fuzzy_line( py_line_no, py_by_line_no, cheetah_by_line_no, prefer_first ): """Attempt to fuzzily find matching lines.""" stripped_line = _fuzz_py_line(py_by_line_no[py_line_no]) cheetah_lower_bound, cheetah_upper_bound = _find_bounds( py_line_no, py_by_line_no, cheetah_by_line_no, ...
java
@Override protected void paintComponent(Graphics g) { if (img != null) { setOpaque(false); Map<RenderingHints.Key, Object> hints = new HashMap<RenderingHints.Key, Object>(); hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); ...
python
def automatic_slug_renaming(slug, is_slug_safe): """Helper to add numbers to slugs""" if not isinstance(is_slug_safe, collections.Callable): raise TypeError('is_slug_safe must be callable') if is_slug_safe(slug): return slug count = 2 new_slug = slug + "-" + str(count) while no...
python
def create(self, request, *args, **kwargs): """ See the *Annotator* documentation regarding the `create <http://docs.annotatorjs.org/en/v1.2.x/storage.html#create>`_ endpoint. :param request: incoming :class:`rest_framework.request.Request`. :return: ...
java
private void reset(boolean skipBuffer) { // expected diff with AnsiOutputStream.java if (!skipBuffer) { ps.write(buffer, 0, pos); // expected diff with AnsiOutputStream.java } pos = 0; startOfValue = 0; options.clear(); state = LOOKING_FOR_FIRST_ESC_CHAR; ...
java
public Object setSessionAttribute(final String _key, final Object _value) { return this.sessionAttributes.put(_key, _value); }
java
public void initalised() throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "initalised"); try { _lockManager.lockExclusive(); // Flag that we are in a started state. _started = true; // If the Neigh...
python
def _set_ldp_eol(self, v, load=False): """ Setter method for ldp_eol, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/ldp/ldp_holder/ldp_eol (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_eol is considered as a private method. Bac...
java
public void marshall(Backend backend, ProtocolMarshaller protocolMarshaller) { if (backend == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(backend.getVirtualService(), VIRTUALSERVICE_BINDING); ...
java
public static ParityFilePair getParityFile(Codec codec, FileStatus srcStat, Configuration conf, boolean skipHarChecking) throws IOException { if (srcStat == null) { return null; } Path srcPath = srcStat.getPath(); FileSystem fsSrc = srcPath.getFileSystem(conf); if (codec.isDirRaid) { ...
java
private static Rule parseRule(String description) throws ParseException { if (description.length() == 0) { return DEFAULT_RULE; } description = description.toLowerCase(Locale.ENGLISH); int x = description.indexOf(':'); if (x == -1) { throw new ParseExcep...
java
@Override public void dismiss(int i) { if (mAdapterListener != null) { if (mHeaderView != null) { i--; } mTracks.remove(i); mAdapterListener.onTrackDismissed(i); } }
python
def _check_cutoff(self): """ Returns a function to stop the search of the investigated node of the ArciDispatch algorithm. :return: A function to stop the search. :rtype: (int | float) -> bool """ if self.cutoff is not None: cutoff = sel...
java
@Indexable(type = IndexableType.DELETE) @Override public CommerceShippingFixedOption deleteCommerceShippingFixedOption( long commerceShippingFixedOptionId) throws PortalException { return commerceShippingFixedOptionPersistence.remove(commerceShippingFixedOptionId); }
python
def download_dataset(self, dataset_key): """Return a .zip containing all files within the dataset as uploaded. :param dataset_key : Dataset identifier, in the form of owner/id :type dataset_key: str :returns: .zip file contain files within dataset :rtype: file object :ra...
python
def detect_json_strings(raw_text): """ Use regex with lookaround to spot the boundaries between JSON objects. Unfortunately, it has to match *something*, so at least one character must be removed and replaced. """ strings = re.split('}\s*(?={)', raw_text) # put back the stripped character ...
python
def json_register(self): ''' The first char of 'code' stands for the different field. '1' for user_name '2' for user_email '3' for user_pass '4' for user_role The seconde char of 'code' stands for different status. '1' for invalide '2' for already ...
java
public static IdentifierExtension findFirst(Collection<? extends Extension> extensions) { for (Extension extension : extensions) { if (IDENTIFIER_EXTENSION_ID == extension.getId()) return (IdentifierExtension)extension; } return null; }
java
private float calculateScale(int x, int y) { final float centerX = getWidth() / 2f; final float centerY = getHeight() / 2f; final float maxDistance = (float) Math.sqrt(centerX * centerX + centerY * centerY); final float deltaX = centerX - x; final float deltaY = centerY - y; final float distance = (float) ...
java
public static AssociationValue createEmptyAssociationValue(AssociationAttributeInfo attributeInfo) { AssociationValue value = new AssociationValue(); Map<String, Attribute<?>> attributes = new HashMap<String, Attribute<?>>(); for (AbstractAttributeInfo attrInfo : attributeInfo.getFeature().getAttributes()) { a...
python
def map_images_in_tex(tex_files, image_mapping, output_directory, context=False): """Return caption and context for image references found in TeX sources.""" extracted_image_data = [] for tex_file in tex_files: # Extract images, captions and labels based on tex file and images ...
java
public static <U> U[] copyOf(U[] objectArray) { Class<?> arrayClass = objectArray.getClass(); @SuppressWarnings("unchecked") Class<U> componentClass = (Class<U>) arrayClass.getComponentType(); @SuppressWarnings("unchecked") U[] copy = (U[]) Array.newInstance(componentClass, objectArray.lengt...
java
public Connector getStandardMetaData(File root) throws Exception { Connector result = null; File metadataFile = new File(root, "/META-INF/ra.xml"); if (metadataFile.exists()) { InputStream input = null; String url = metadataFile.getAbsolutePath(); try { ...
java
public ColumnModel singleIndex(String indexName) { makeSureTableModelExist(); DialectException.assureNotEmpty(indexName, "indexName can not be empty"); this.tableModel.index(indexName).columns(this.getColumnName()); return this; }
python
def map_(self, lat, long, zoom=13, tiles="map"): """ Returns a map """ try: return self._map(lat, long, zoom, tiles) except Exception as e: self.err(e, self.map_, "Can not get map")
java
@Override public String getName(String languageId, boolean useDefault) { return _commerceUserSegmentEntry.getName(languageId, useDefault); }
python
def humanize_filesize(bytes_size): """Returns human readable filesize. :param int bytes_size: :rtype: str """ if not bytes_size: return '0 B' names = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB') name_idx = int(math.floor(math.log(bytes_size, 1024))) size = round(b...
java
public void marshall(Handshake handshake, ProtocolMarshaller protocolMarshaller) { if (handshake == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(handshake.getId(), ID_BINDING); protocol...
python
def shutdown(cls, dir_): """ :param dir_: The directory that will contain the cache state file. """ cacheInfo = cls._CacheState._load(os.path.join(dir_, '_cacheState')) cls.findAndHandleDeadJobs(cacheInfo, batchSystemShutdown=True) shutil.rmtree(dir_)
python
def as_gradient(self, name=None, style=None, rgb_mode=False): """ Wrap each frame in a Colr object, using `Colr.gradient`. Arguments: name : Starting color name. One of `Colr.gradient_names`. """ return self._as_gradient( ('wrapper', ), name=n...
java
public boolean isValidExprForIndexesAndMVs(StringBuffer msg, boolean isMV) { if (containsFunctionById(FunctionSQL.voltGetCurrentTimestampId())) { msg.append("cannot include the function NOW or CURRENT_TIMESTAMP."); return false; } else if (hasAnySubexpressionOfClass(AggregateExpr...
python
def moral_graph(model, format='raw', prog='dot', path=None, name=None): """ moral_graph(model,format='raw', prog='dot', path=None) Draws the moral graph for this model and writes it to path with filename name. Returns the pydot 'dot' object for further user manipulation. GraphViz and PyDot must be...
java
@RequestMapping(method = RequestMethod.POST, params = "action=addFolder") public ModelAndView addFolder( HttpServletRequest request, HttpServletResponse response, @RequestParam("targetId") String targetId, @RequestParam(value = "siblingId", required = false) String si...
python
def _add_relations(self, relations): """Add all of the relations for the services.""" for k, v in six.iteritems(relations): self.d.relate(k, v)
java
public String getAxisName(int controller, int axis) { return ((Controller) controllers.get(controller)).getAxisName(axis); }
java
private void checkMethodNames(Expression expression) { if (expression instanceof MethodCallExpr) { MethodCallExpr methodCall = ((MethodCallExpr) expression); if (!methodCall.getScope().isPresent()) { String methodName = methodCall.getName().getIdentifier(); if (!context.hasMethod(methodN...
java
public DateTimeFormatterBuilder appendLiteral(String literal) { Jdk8Methods.requireNonNull(literal, "literal"); if (literal.length() > 0) { if (literal.length() == 1) { appendInternal(new CharLiteralPrinterParser(literal.charAt(0))); } else { appen...
java
@Api public void setValue(String name, ShortAttribute attribute) { FormItem item = formWidget.getField(name); if (item != null) { item.setValue(attribute.getValue()); } }
python
def _iso_week_of_month(date_value): "0-starting index which ISO-week in the month this date is" weekday_of_first = date_value.replace(day=1).weekday() return (date_value.day + weekday_of_first - 1) // 7
java
public void setFormatJavadoc(boolean val) { if (val && !formatJavadoc) { startDelim = "* " + startDelim; endDelim = "* " + endDelim; } else if (!val && formatJavadoc) { startDelim = StringUtils.removeStart("* ", startDelim); endDelim = StringUtils.removeStart("* ", endDelim); } t...
python
def _move_stream_token(coordinator, token): """Move to the Stream position described by the token. The following rules are applied when interpolation is required: - If a shard does not exist (past the trim_horizon) it is ignored. If that shard had children, its children are also checked against the ...
java
private void isReferenceToLoggedInUser(Root root) throws WIMApplicationException { // Get unique name if (root.getEntities().size() == 0) return; Entity entity = root.getEntities().get(0); IdentifierType identifier = entity.getIdentifier(); if (identifier == null) ...
java
protected void checkTimerAccess() { BeanO beanO = EJSContainer.getCallbackBeanO(); if (beanO != null) { beanO.checkTimerServiceAccess(); } else if (EJSContainer.getDefaultContainer().allowTimerAccessOutsideBean) { // Beginning with EJB 3.2, the specification was updated ...
python
def register_blueprint(self, *args, **kwargs): """ Proxy method provided for invoking the :func:`blueprint` method .. note:: To be deprecated in 1.0. Use :func:`blueprint` instead. :param args: Blueprint object or (list, tuple) thereof :param kwargs: option dictiona...
java
public BranchEvent setTransactionID(String transactionID) { return addStandardProperty(Defines.Jsonkey.TransactionID.getKey(), transactionID); }
java
public List<Example> actionCells(Example row) { List<Example> actionCells = ExampleUtil.asList( row.at(0,1) ); CollectionUtil.removeLast( actionCells ); return actionCells; }
java
private void processEmbeddableAttribute(Object entity, MetamodelImpl metamodel, Row row, Table schemaTable, EntityMetadata metadata, Attribute attribute) { // process on embeddables. EmbeddableType embeddable = metamodel.embeddable(((AbstractAttribute) attribute).getBindableJavaType()); ...
python
def write_config(cfg): '''try writing config file to a default directory''' cfg_path = '/usr/local/etc/freelan' cfg_file = 'freelan_TEST.cfg' cfg_lines = [] if not isinstance(cfg, FreelanCFG): if not isinstance(cfg, (list, tuple)): print("Freelan write input can not be processe...
python
def switch_on(self, *args): """ Sets the state of the switch to True if on_check() returns True, given the arguments provided in kwargs. :param kwargs: variable length dictionary of key-pair arguments :return: Boolean. Returns True if the operation is successful """ ...
python
def get_weather_data(filename='weather.csv', **kwargs): r""" Imports weather data from a file. The data include wind speed at two different heights in m/s, air temperature in two different heights in K, surface roughness length in m and air pressure in Pa. The file is located in the example folder ...
java
public ScheduledFuture<?> queueAfter(long delay, TimeUnit unit, ScheduledExecutorService executor) { return queueAfter(delay, unit, null, executor); }
python
def distance(self, word1, word2, metric='levenshtein'): """Get the similarity of the words, using the supported distance metrics.""" if metric in self.distances: distance_func = self.distances[metric] return distance_func(self.phonetics(word1), self.phonetics(word2)) else...
python
def get_outputs_from_cm(index, cm): """Return indices of the outputs of node with the given index.""" return tuple(i for i in range(cm.shape[0]) if cm[index][i])
java
private void handleGenericHNIError(Throwable t, HttpInboundServiceContextImpl hisc) { hisc.setHeadersParsed(); sendErrorMessage(t); setPartiallyParsed(false); }
python
def _galaxy_library_upload(finfo, sample_info, config): """Upload results to galaxy library. """ folder_name = "%s_%s" % (config["fc_date"], config["fc_name"]) storage_dir = utils.safe_makedir(os.path.join(config["dir"], folder_name)) if finfo.get("type") == "directory": storage_file = None ...
java
private ProtectionDomain getProtectionDomain(CodeSource cs) { if (cs == null) return null; ProtectionDomain pd = null; synchronized (pdcache) { pd = pdcache.get(cs); if (pd == null) { PermissionCollection perms = getPermissions(cs); ...
python
def kindex(matrix, k): """ Returns indices to select the kth nearest neighbour""" ix = (np.arange(len(matrix)), matrix.argsort(axis=0)[k]) return ix
python
def computeFrequencyOfSignificantSNPs(options): """Computes the frequency of the significant markers. :param options: the options. :type options: argparse.Namespace Extract a list of markers (significant after plate bias analysis) and computes their frequencies. """ # The plink command ...
python
def top_x_meteor(query_dic, mark, x=1): """ Calculate METEOR score of the top result :param query_dic: dict, key is qid, value is (item, meteor) tuple list, which will be ranked by 'item' as key :param mark: string, which indicates which method is evaluated, also used as output file name here. ...
java
public DescribeAvailabilityZonesRequest withZoneIds(String... zoneIds) { if (this.zoneIds == null) { setZoneIds(new com.amazonaws.internal.SdkInternalList<String>(zoneIds.length)); } for (String ele : zoneIds) { this.zoneIds.add(ele); } return this; }