language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def url_is(white_list): """ Function generator. Args: white_list (dict): dict with PREFIXES and CONSTANTS keys (list values). Returns: func: a function to check if a URL is... """ def func(url): prefixes = white_list.get('PREFIXES', ()) for prefix in prefixes: ...
python
def __getDecision(self, result, multiple=False, **values): """ The main method for decision picking. Args: result (array of str): What values you want to get in return array. multiple (bolean, optional): Do you want multiple result if it finds many maching decisions. **values (dict): What should finder ...
python
def set(self, attr_dict): """Sets attributes of this user object. :type attr_dict: dict :param attr_dict: Parameters to set, with attribute keys. :rtype: :class:`.Base` :return: The current object. """ for key in attr_dict: if key == self._id_attribute: setattr(self, self._i...
python
def launchApplication(self, pchAppKey): """ Launches the application. The existing scene application will exit and then the new application will start. This call is not valid for dashboard overlay applications. """ fn = self.function_table.launchApplication result = fn(p...
java
public synchronized void setFactoryMethod(String factoryMethodName) { Method newMethod = null; this.factoryMethodName = factoryMethodName; if (factoryMethodName != null) { try { // see if we have a publicly accessible method by the na...
java
public static <T> T convertTo(String in, TypeReference<T> mapTo) throws IOException { try { return mapper.readValue(in, mapTo); } catch (Exception e) { log.error("Can not convert:{} to {}", in, mapTo, e); throw new OvhServiceException("local", "conversion Error to " + mapTo); } }
java
public org.inferred.freebuilder.processor.property.Property.Builder setAllCapsName( String allCapsName) { this.allCapsName = Objects.requireNonNull(allCapsName); _unsetProperties.remove(Property.ALL_CAPS_NAME); return (org.inferred.freebuilder.processor.property.Property.Builder) this; }
java
public static CompletableFuture<MessageSet> getMessagesBeforeUntil( TextChannel channel, Predicate<Message> condition, long before) { return getMessagesUntil(channel, condition, before, -1); }
python
def build_map(function: Callable[[Any], Any] = None, unpack: bool = False): """ Decorator to wrap a function to return a Map operator. :param function: function to be wrapped :param unpack: value from emits will be unpacked (*value) """ def _build_map(function: Callable[[Any], Any]): ...
python
def _is_user_directory(self, pathname): """Check whether `pathname` is a valid user data directory This method is meant to be called on the contents of the userdata dir. As such, it will return True when `pathname` refers to a directory name that can be interpreted as a users' userID. """...
java
public AddStepsRequest withStep(StepConfig step) { if (this.steps == null) { this.steps = new ArrayList<StepConfig>(); } this.steps.add(step); return this; }
java
private String getUrl(final IRI identifier) { return getServices().getResourceService().toExternal(identifier, getBaseUrl()).getIRIString(); }
python
def scramble_string(s, key): """ s is the puzzle's solution in column-major order, omitting black squares: i.e. if the puzzle is: C A T # # A # # R solution is CATAR Key is a 4-digit number in the range 1000 <= key <= 9999 """ key = key_digits(key) for k in key...
python
def parameterSpace( self ): """Return the parameter space of the experiment as a list of dicts, with each dict mapping each parameter name to a value. :returns: the parameter space as a list of dicts""" ps = self.parameters() if len(ps) == 0: return [] else: ...
python
def spotlight_search_route(context, request): """The spotlight search route """ catalogs = [ CATALOG_ANALYSIS_REQUEST_LISTING, "portal_catalog", "bika_setup_catalog", "bika_catalog", "bika_catalog_worksheet_listing" ] search_results = [] for catalog in ca...
java
public void init(CmsImagePreviewHandler handler) { m_handler = handler; m_propertiesTab = new CmsPropertiesTab(m_galleryMode, m_dialogHeight, m_dialogWidth, m_handler); m_tabbedPanel.add(m_propertiesTab, Messages.get().key(Messages.GUI_PREVIEW_TAB_PROPERTIES_0)); if ((m_galleryMode == G...
java
@Override public java.util.concurrent.Future<UnsubscribeResult> unsubscribeAsync(String subscriptionArn) { return unsubscribeAsync(new UnsubscribeRequest().withSubscriptionArn(subscriptionArn)); }
java
public static Authorization append(Authorization a, Authorization b) { if (a instanceof AclRuleSetSource && b instanceof AclRuleSetSource) { return RuleEvaluator.createRuleEvaluator( merge((AclRuleSetSource) a, (AclRuleSetSource) b) ); } return new Mul...
python
def reassign_comment_to_book(self, comment_id, from_book_id, to_book_id): """Moves a ``Credit`` from one ``Book`` to another. Mappings to other ``Books`` are unaffected. arg: comment_id (osid.id.Id): the ``Id`` of the ``Comment`` arg: from_book_id (osid.id.Id): the ``Id`` of the ...
java
@Override public <B> CompletableFutureT<W,B> map(final Function<? super T, ? extends B> f) { return new CompletableFutureT<W,B>( run.map(o -> o.thenApply(f))); }
java
@Override public EClass getIfcPump() { if (ifcPumpEClass == null) { ifcPumpEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(485); } return ifcPumpEClass; }
java
public static double getSquaredDistanceToPoint( final double pFromX, final double pFromY, final double pToX, final double pToY) { final double dX = pFromX - pToX; final double dY = pFromY - pToY; return dX * dX + dY * dY; }
java
private void initSystemRoutingStrategies(Cluster cluster) { HashMap<String, RoutingStrategy> routingStrategyMap = createRoutingStrategyMap(cluster, makeStoreDefinitionMap(getSystemStoreDefList())); this.metadataCache....
java
public static List<String> readStringList(String filePath, Charset charset) throws IOException { FileInputStream stream = new FileInputStream(filePath); return readStringList(stream, charset); }
python
def _get_result(self, method_name="kaze"): """获取特征点.""" method_object = self.method_object_dict.get(method_name) # 提取结果和特征点: try: result = method_object.find_best_result() except Exception: import traceback traceback.print_exc() ret...
python
def post_event_unpublish(self, id, **data): """ POST /events/:id/unpublish/ Unpublishes an event. In order for a free event to be unpublished, it must not have any pending or completed orders, even if the event is in the past. In order for a paid event to be unpublished, it must not have...
python
def extract_grid(self, longmin, longmax, latmin, latmax): ''' Extract part of the image ``img`` Args: longmin (float): Minimum longitude of the window longmax (float): Maximum longitude of the window latmin (float): Minimum latitude of the window latmax (...
python
def dilute_solution_model(structure, e0, vac_defs, antisite_defs, T, trial_chem_pot=None, generate='plot'): """ Compute the defect densities using dilute solution model. Args: structure: pymatgen.core.structure.Structure object representing the primitive or unitcell of the crystal. ...
java
public Observable<DataLakeAnalyticsAccountInner> updateAsync(String resourceGroupName, String accountName, UpdateDataLakeAnalyticsAccountParameters parameters) { return updateWithServiceResponseAsync(resourceGroupName, accountName, parameters).map(new Func1<ServiceResponse<DataLakeAnalyticsAccountInner>, DataLa...
python
def project(self, projection): ''' Return coordinates transformed to a given projection Projection should be a basemap or pyproj projection object or similar ''' x, y = projection(self.lon.decimal_degree, self.lat.decimal_degree) return (x, y)
java
@Override public void eSet(int featureID, Object newValue) { switch (featureID) { case SarlPackage.SARL_FORMAL_PARAMETER__DEFAULT_VALUE: setDefaultValue((XExpression)newValue); return; } super.eSet(featureID, newValue); }
python
def generate_prediction_data(self): """ Create data that caches intermediate results used for predicting the label of new/unseen points. This data is only useful if you are intending to use functions from ``hdbscan.prediction``. """ if self.metric in FAST_METRICS: ...
python
def insert_into_range(self, operations: ops.OP_TREE, start: int, end: int) -> int: """Writes operations inline into an area of the circuit. Args: start: The start of the range (inclusive) to write the ...
java
private Icon getSynthIcon(AbstractButton b, int synthConstant) { return style.getIcon(getContext(b, synthConstant), getPropertyPrefix() + "icon"); }
java
@Override public List<CommerceOrderNote> findAll() { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
public static void appendUnpaddedInteger(Appendable appendable, long value) throws IOException { int intValue = (int)value; if (intValue == value) { appendUnpaddedInteger(appendable, intValue); } else { appendable.append(Long.toString(value)); } }
python
def check_rst(code, ignore): """Yield errors in nested RST code.""" filename = '<string>' for result in check(code, filename=filename, ignore=ignore): yield result
java
private static int configurationInteger(Properties properties, String key, int defaultValue) { if (properties != null) { if (properties.containsKey(key)) return Integer.valueOf(properties.getProperty(key)); } return defaultValue; }
java
private void redirectToTarget(HttpServletRequest req, HttpServletResponse res, String link, boolean isPermanent) throws IOException, CmsResourceInitException { CmsResourceInitException resInitException = new CmsResourceInitException(getClass()); if (res != null) { // preserve request pa...
java
private synchronized void initBuckets() { final SparseIntArray bucketSizes = mPoolParams.bucketSizes; // create the buckets if (bucketSizes != null) { fillBuckets(bucketSizes); mAllowNewBuckets = false; } else { mAllowNewBuckets = true; } }
python
def create_statement(self, connection_id): """Creates a new statement. :param connection_id: ID of the current connection. :returns: New statement ID. """ request = requests_pb2.CreateStatementRequest() request.connection_id = connection_id ...
java
public java.util.List<Option> getOptions() { if (options == null) { options = new com.amazonaws.internal.SdkInternalList<Option>(); } return options; }
python
def get_generic_fields(): """Return a list of all GenericForeignKeys in all models.""" generic_fields = [] for model in apps.get_models(): for field_name, field in model.__dict__.items(): if isinstance(field, GenericForeignKey): generic_fields.append(field) return gen...
java
public static void setProvider(Provider provider) throws SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new JodaTimePermission("DateTimeZone.setProvider")); } if (provider == null) { provider = getDefault...
java
public static Parser<Void> nestableBlockComment(String begin, String end) { return nestableBlockComment(begin, end, Patterns.isChar(CharPredicates.ALWAYS)); }
java
public void setFormatters(Formatter<?>[] formatters) { if (formatters != null && formatters.length > 0) { for (Formatter<?> formatter : formatters) { if (formatter != null) { Class<?> type = ClassUtils.getGenericClass(formatter.getClass()); if ...
java
@Override public void setParameters(Map<String, ?> parameters) { if (parameters != null) { Object value = null; value = parameters.get(PARAM_KEY_VERBOSE); if (value != null) { verbose = Boolean.parseBoolean(String.valueOf(value)); } value = parameters.get(PARAM_KEY_LOG); if (value != null) { ...
python
def add(self, response, condition=None): """ Add a new Response object :param response: The Response object :type response: parser.trigger.response.Response :param condition: An optional Conditional statement for the Response :type condition: parser.condition.Condition...
java
@Pure public Iterator<BusHub> busHubIterator() { return Iterators.unmodifiableIterator( Iterators.concat(this.validBusHubs.iterator(), this.invalidBusHubs.iterator())); }
python
def find_elements_by_class_name(self, name): """ Finds elements by class name. :Args: - name: The class name of the elements to find. :Returns: - list of WebElement - a list with elements if any was found. An empty list if not :Usage: ...
java
private File getNextTempDirectory() throws AnalysisException { File directory; // getting an exception for some directories not being able to be // created; might be because the directory already exists? do { final int dirCount = DIR_COUNT.incrementAndGet(); dire...
python
def check_perms(name, ret, user, group, mode, attrs=None, follow_symlinks=False, seuser=None, serole=None, setype=None, serange=None): ''' .. versionchanged:: Neon Added selinux options Check the permissions on files, modify attributes and chown if needed. File attributes are o...
java
@Override public void delete(Object entity, Object pKey) { s = getStatelessSession(); Transaction tx = null; tx = onBegin(); s.delete(entity); onCommit(tx); EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass()); ...
java
public ApiResponse<ApiSuccessResponse> inviteByQueueWithHttpInfo(String id, InviteData1 inviteData) throws ApiException { com.squareup.okhttp.Call call = inviteByQueueValidateBeforeCall(id, inviteData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessResponse>(){}.getType(); return...
python
def dcnm_network_create_event(self, network_info): """Process network create event from DCNM.""" # 1. Add network info to database before sending request to # neutron to create the network. # Check if network is already created. pre_seg_id = network_info.get('segmentation_id') ...
java
private void checkJodaGetDay() { int COUNT = COUNT_VERY_FAST; DateTime dt = new DateTime(GJChronology.getInstance()); for (int i = 0; i < AVERAGE; i++) { start("Joda", "getDay"); for (int j = 0; j < COUNT; j++) { int val = dt.getDayOfMonth(); ...
java
public static RegistryEntry[] getValues(String branch, short type) throws RegistryException, IOException, InterruptedException { String[] cmd = new String[] { "reg", "query", branch }; return filter(executeQuery(cmd), cleanBrunch(branch), type); }
java
synchronized public void closeInbound() throws SSLException { /* * Currently closes the outbound side as well. The IETF TLS * working group has expressed the opinion that 1/2 open * connections are not allowed by the spec. May change * someday in the future. */ ...
python
def absent(name, auth=None, **kwargs): ''' Ensure group does not exist name Name of the group domain The name or id of the domain ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} kwargs = __utils__['args.clean_kwargs']...
java
public static List<Point> spin(Collection<Point> points, double angle) { double SIN, COS; //判断用户的值是否是内置的几个特殊角度对应的弧度值 if (angle == ANGLE_30) { SIN = SIN_30; COS = COS_30; } else if (angle == ANGLE_45) { SIN = SIN_45; COS = COS_45; }...
python
def read_file(self): '''load config from local file''' if os.path.exists(self.experiment_file): try: with open(self.experiment_file, 'r') as file: return json.load(file) except ValueError: return {} return {}
java
@Override public void validate() { boolean valid = true; if (hasValue()) { Long value = getValue(); if (value != null) { // scrub the value to format properly setText(value2text(value)); } else { // empty...
python
def _generate_noise_temporal_autoregression(timepoints, noise_dict, dimensions, mask, ): """Generate the autoregression noise Make a sl...
python
def generate_output_asn(self, json_data=None, hr=True, show_name=False, colorize=True): """ The function for generating CLI output ASN results. Args: json_data (:obj:`dict`): The data to process. Defaults to None. hr (:obj:`bool`): Enable huma...
java
private void mapAndSetOffset() { try { final RandomAccessFile backingFile = new RandomAccessFile(this.file, "rw"); backingFile.setLength(this.size); final FileChannel ch = backingFile.getChannel(); this.addr = (Long) mmap.invoke(ch, 1, 0L, this.size); ...
python
def get_deps_list(self, pkg_name, installed_distros=None): """ For a given package, returns a list of required packages. Recursive. """ # https://github.com/Miserlou/Zappa/issues/1478. Using `pkg_resources` # instead of `pip` is the recommended approach. The usage is nearly ...
python
def rept(ctx, text, number_times): """ Repeats text a given number of times """ if number_times < 0: raise ValueError("Number of times can't be negative") return conversions.to_string(text, ctx) * conversions.to_integer(number_times, ctx)
python
def bulk_edit(self, _fields, ids=None, filter=None, type=None, all=False, testvars=None): # pylint: disable=redefined-builtin """Bulk edit a set of configs. :param _fields: :class:`configs.Config <configs.Config>` object :param ids: (optional) Int list of config IDs. :param filter: (opt...
python
def search(self, search_phrase, limit=None): """ Finds partitions by search phrase. Args: search_phrase (str or unicode): limit (int, optional): how many results to generate. None means without limit. Yields: PartitionSearchResult instances. """ ...
java
public <E extends Enum<?>> DataSetBuilder value(String column, E enumConstant) { return value(column, enumConstant.toString()); }
java
public String convertIfcConnectionTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def write_h5ad( self, filename: Optional[PathLike] = None, compression: Optional[str] = None, compression_opts: Union[int, Any] = None, force_dense: Optional[bool] = None ): """Write ``.h5ad``-formatted hdf5 file. .. note:: Setting compression to...
python
def get_current_term(): """ Returns a uw_sws.models.Term object, for the current term. """ url = "{}/current.json".format(term_res_url_prefix) term = _json_to_term_model(get_resource(url)) # A term doesn't become "current" until 2 days before the start of # classes. That's too late to ...
python
def certificate_object(self): """ Returns the certificate as an OpenSSL object Returns the certificate as an OpenSSL object (rather than as a file object). """ if not self.certificate: return None self.certificate.seek(0) return crypto.parse_c...
java
public static void addEvidences(Network bn, Map<String, String> evidences) throws ShanksException { if (bn == null || evidences.isEmpty()) { throw new ShanksException("Null parameter in addEvidences method."); } for (Entry<String, String> evidence : evidences.entrySet()) ...
java
@Override public boolean accept(final File f) { if (f.isDirectory()) return true; int len = extensions.size(); if (len == 0) return true; for (int i=0; i<len; i++) { String suffix = extensions.get(i); if (suffix.equals("*")) return true; if (f.getName().toLowerCase().endsWith('.' + suffix)) return ...
python
def disable_vlan_on_trunk_int(self, nexus_host, vlanid, intf_type, interface, is_native): """Disable a VLAN on a trunk interface.""" starttime = time.time() path_snip, body_snip = self._get_vlan_body_on_trunk_int( nexus_host, vlanid, intf_type, int...
java
public void marshall(VirtualRouterServiceProvider virtualRouterServiceProvider, ProtocolMarshaller protocolMarshaller) { if (virtualRouterServiceProvider == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
python
def add_auto_increment(self, table, name): """Modify an existing column.""" # Get current column definition and add auto_incrementing definition = self.get_column_definition(table, name) + ' AUTO_INCREMENT' # Concatenate and execute modify statement self.execute("ALTER TABLE {0}...
python
def Stephan_Abdelsalam(rhol, rhog, mul, kl, Cpl, Hvap, sigma, Tsat, Te=None, q=None, kw=401, rhow=8.96, Cpw=384, angle=None, correlation='general'): r'''Calculates heat transfer coefficient for a evaporator operating in the nucleate boiling regime according to [2]...
java
private void validateClusterNameOfWorkItem( long woitRefNum ){ WorkItem woit = workItemDao.findByRefNum( woitRefNum ); validateClusterNameOfWorkflowInstance( woit.getWoinRefNum() ); }
java
@Override public IDocumentQuery<T> orderByDistanceDescending(String fieldName, double latitude, double longitude) { _orderByDistanceDescending(fieldName, latitude, longitude); return this; }
python
def check(self, password: str) -> bool: """ Checks the given password with the one stored in the database """ return ( pbkdf2_sha512.verify(password, self.password) or pbkdf2_sha512.verify(password, pbkdf2_sha512.encrypt(se...
python
def log_erase_send(self, target_system, target_component, force_mavlink1=False): ''' Erase all logs target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(se...
python
def mmGetPlotUnionSDRActivity(self, title="Union SDR Activity Raster", showReset=False, resetShading=0.25): """ Returns plot of the activity of union SDR bits. @param title an optional title for the figure @param showReset if true, the first set of activities after a reset ...
python
def enhance_json_encode(api_instance, extra_settings=None): """use `JSONEncodeManager` replace default `output_json` function of Flask-RESTful for the advantage of use `JSONEncodeManager`, please see https://github.com/anjianshi/json_encode_manager""" api_instance.json_encoder = JSONEncodeManager() dum...
python
def render_user(self, *args, **kwargs): ''' render, with userinfo fun(kind, num) fun(kind, num, with_tag = val1) fun(kind, num, with_tag = val1, user_id = val2) fun(kind, num, with_tag = val1, user_id = val2, glyph = val3) ''' kind = kwargs.get('kind', ar...
python
def parse(page_to_parse): """Return a parse of page.content. Wraps PyQuery.""" global _parsed if not isinstance(page_to_parse, page.Page): raise TypeError("parser.parse requires a parker.Page object.") if page_to_parse.content is None: raise ValueError("parser.parse requires a fetched p...
java
public void marshall(Principal principal, ProtocolMarshaller protocolMarshaller) { if (principal == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(principal.getId(), ID_BINDING); protocol...
java
public FatFileSystem format() throws IOException { final int sectorSize = device.getSectorSize(); final int totalSectors = (int)(device.getSize() / sectorSize); final FsInfoSector fsi; final BootSector bs; if (sectorsPerCluster == 0) throw new AssertionError(); ...
python
def parse_children(parent): """Recursively parse child tags until match is found""" components = [] for tag in parent.children: matched = parse_tag(tag) if matched: components.append(matched) elif hasattr(tag, 'contents'): components += parse_children(tag) ...
python
def log_entry_encode(self, id, num_logs, last_log_num, time_utc, size): ''' Reply to LOG_REQUEST_LIST id : Log id (uint16_t) num_logs : Total number of logs (uint16_t) last_log_num : Hig...
python
def from_data(data): """Create a chunk from data including header and length bytes.""" header, length = struct.unpack('4s<I', data[:8]) data = data[8:] return RiffDataChunk(header, data)
java
@Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (cmd.equals("Cancel")) { setVisible(false); value = null; } else if (cmd.equals("Select")) { if (list.getSelectedIndex() < 0) { return; ...
python
def pos_to_linecol(text, pos): """Return a tuple of line and column for offset pos in text. Lines are one-based, columns zero-based. This is how Jedi wants it. Don't ask me why. """ line_start = text.rfind("\n", 0, pos) + 1 line = text.count("\n", 0, line_start) + 1 col = pos - line_start...
java
public static CPDefinitionSpecificationOptionValue fetchByCPDefinitionId_First( long CPDefinitionId, OrderByComparator<CPDefinitionSpecificationOptionValue> orderByComparator) { return getPersistence() .fetchByCPDefinitionId_First(CPDefinitionId, orderByComparator); }
python
def extract_status_code(error): """ Extract an error code from a message. """ try: return int(error.code) except (AttributeError, TypeError, ValueError): try: return int(error.status_code) except (AttributeError, TypeError, ValueError): try: ...
python
def template_exists(form, field): """Form validation: check that selected template exists.""" try: current_app.jinja_env.get_template(field.data) except TemplateNotFound: raise ValidationError(_("Template selected does not exist"))
java
public void addFileAttachment(String description, byte fileStore[], String file, String fileDisplay) throws IOException { addFileAttachment(description, PdfFileSpecification.fileEmbedded(stamper, file, fileDisplay, fileStore)); }
java
public void unpublish(final WebApp webApp) { NullArgumentException.validateNotNull(webApp, "Web app"); LOG.debug("Unpublishing web application [{}]", webApp); final ServiceTracker<WebAppDependencyHolder, WebAppDependencyHolder> tracker = webApps .remove(webApp); if (tracker != null) { tracker.close...