language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def create(dataset, target, feature=None, model = 'resnet-50', l2_penalty=0.01, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level = _DEFAULT_SOLVER...
java
@SuppressWarnings("unchecked") private Object fireEvent(Request request, PageBook.Page page, Object instance) throws IOException { final String method = request.method(); final String pathInfo = request.path(); return page.doMethod(method.toLowerCase(), instance, pathInfo, request); }
python
def stopCommand(self): """Make any currently-running command die, with no further status output. This is used when the worker is shutting down or the connection to the master has been lost. Interrupt the command, silence it, and then forget about it.""" if not self.command: ...
java
public PaginatedResult execute(final Query query, final Map parameters) { final long count = getCount(query, parameters); decorate(query); return new PaginatedResult() .objects(query.executeWithMap(parameters)) .total(count); }
java
public Observable<DocumentFragment<Mutation>> execute(PersistTo persistTo) { return execute(persistTo, ReplicateTo.NONE, 0, null); }
java
public static <T> int detectIndex(Iterable<T> iterable, Predicate<? super T> predicate) { if (iterable instanceof ArrayList<?>) { return ArrayListIterate.detectIndex((ArrayList<T>) iterable, predicate); } if (iterable instanceof List<?>) { return ListI...
java
public static String humanize(final String input) { if (input == null || input.length() == 0) { return ""; } return upperFirst(underscored(input).replaceAll("_", " ")); }
java
public static TokenizerEngine create() { final TokenizerEngine engine = doCreate(); StaticLog.debug("Use [{}] Tokenizer Engine As Default.", StrUtil.removeSuffix(engine.getClass().getSimpleName(), "Engine")); return engine; }
python
def to_json(self, variables=None): """Render the blueprint and return the template in json form. Args: variables (dict): Optional dictionary providing/overriding variable values. Returns: str: the rendered CFN JSON template """ variables...
java
public Defuzzifier constructDefuzzifier(String key, int resolution, WeightedDefuzzifier.Type type) { Defuzzifier result = constructObject(key); if (result instanceof IntegralDefuzzifier) { ((IntegralDefuzzifier) result).setResolution(resolution); } else if (result instanc...
java
@Override public void cacheResult(List<CProduct> cProducts) { for (CProduct cProduct : cProducts) { if (entityCache.getResult(CProductModelImpl.ENTITY_CACHE_ENABLED, CProductImpl.class, cProduct.getPrimaryKey()) == null) { cacheResult(cProduct); } else { cProduct.resetOriginalValues(); } ...
python
def _process_info(raw_info: VideoInfo) -> VideoInfo: """Process raw information about the video (parse date, etc.).""" raw_date = raw_info.date date = datetime.strptime(raw_date, '%Y-%m-%d %H:%M') # 2018-04-05 17:00 video_info = raw_info._replace(date=date) return video_info
java
public void marshall(ListDeviceDefinitionsRequest listDeviceDefinitionsRequest, ProtocolMarshaller protocolMarshaller) { if (listDeviceDefinitionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
java
public List<UserSummary> getUserSummary(Date start, Date end) { if(diffThan6Days(start, end)) { throw new IllegalArgumentException("start和end相差不能超过6天以上"); } String url = WxEndpoint.get("url.stats.user.summary"); String json = "{\"begin_date\":\"%s\",\"end_date\":\"%s\"...
python
def __add_loaded_module(self, event): """ Private method to automatically add new module objects from debug events. @type event: L{Event} @param event: Event object. """ lpBaseOfDll = event.get_module_base() hFile = event.get_file_handle() ## if not...
python
def atomicish_move(source, destination, tmp_suffix="_TMP"): """Move source to destination without risk of partial moves. > from tempfile import mkdtemp > from os.path import join, exists > temp_dir = mkdtemp() > source = join(temp_dir, "the_source") > destination = join(temp_dir, "the_dest") ...
java
private synchronized void resetAllIndexes() { Collection<RaftSessionState> sessions = Lists.newArrayList(this.sessions.values()); // If no sessions are open, skip the keep-alive. if (sessions.isEmpty()) { return; } // Allocate session IDs, command response sequence numbers, and event index a...
java
public final File getLicenseFile(File installLicenseDir, String prefix) throws FileNotFoundException { if (!!!prefix.endsWith("_")) { prefix = prefix + "_"; } Locale locale = Locale.getDefault(); String lang = locale.getLanguage(); String country = locale.getCountry(...
java
private String redisKey(ModelExt<?> m) { Table table = m.table(); StringBuilder key = new StringBuilder(); key.append(RECORDS); key.append(table.getName()); key.append(":"); //fetch primary keys' values String[] primaryKeys = table.getPrimaryKey(); //format key for (int idx = 0; idx < primaryKeys.leng...
java
static Geometry[] intersect(Geometry[] inputGeometries, Geometry geometry, SpatialReference spatialReference) { OperatorIntersection op = (OperatorIntersection) factory .getOperator(Operator.Type.Intersection); SimpleGeometryCursor inputGeometriesCursor = new SimpleGeometryCursor( inputGeometries); Sim...
java
public static <I> List<Word<I>> characterizingSet(UniversalDeterministicAutomaton<?, I, ?, ?, ?> automaton, Collection<? extends I> inputs) { List<Word<I>> result = new ArrayList<>(); characterizingSet(automaton, inputs, result); return resul...
python
def _process_outgoing(self, xmlstream, token): """ Process the current outgoing stanza `token` and also any other outgoing stanza which is currently in the active queue. After all stanzas have been processed, use :meth:`_send_ping` to allow an opportunistic ping to be sent. ...
java
private boolean vfsResourceWithStructureId(CmsUUID importId) { return m_cms.existsResource(importId, CmsResourceFilter.ALL) || m_onlineCms.existsResource(importId, CmsResourceFilter.ALL); }
java
protected Enumeration/*<URL>*/ findResources(String name, boolean parentHasBeenSearched) throws IOException { Enumeration/*<URL>*/ mine = new ResourceEnumeration(name); Enumeration/*<URL>*/ base; if (parent != null && (!parentHasBeenSearch...
python
def column_width(self, width): """Validate and set the column width.""" if isinstance(width, int): if width >= 0: self._column_width = width else: raise ValueError('Column width must be nonnegative.') else: raise TypeError('Colu...
python
def _parse_options(opts, delim): """Helper method for split_options which creates the options dict. Also handles the creation of a list for the URI tag_sets/ readpreferencetags portion and the use of the tlsInsecure option.""" options = _CaseInsensitiveDictionary() for uriopt in opts.split(delim): ...
java
@Override public void close() { // check if the sorter has been closed before synchronized (this) { if (this.closed) { return; } // mark as closed this.closed = true; } // from here on, the code is in a try block, because even through errors might be thrown in this block, // we need to make...
java
public Quaternionf lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) { return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this); }
java
protected void updateProgressNotification(@NonNull final NotificationCompat.Builder builder, final int progress) { // Add Abort action to the notification if (progress != PROGRESS_ABORTED && progress != PROGRESS_COMPLETED) { final Intent abortIntent = new Intent(BROADCAST_ACTION); abortIntent.putExtra(EXTRA_A...
java
@NonNull public static Expression not(@NonNull Expression expression) { if (expression == null) { throw new IllegalArgumentException("expression cannot be null."); } return negated(expression); }
java
public Set<String> stringPropertyNames() { Hashtable<String, String> h = new Hashtable<>(); enumerateStringProperties(h); return h.keySet(); }
python
def get(self): """Return a Deferred that fires with a SourceStamp instance.""" d = self.getBaseRevision() d.addCallback(self.getPatch) d.addCallback(self.done) return d
java
public IGenericSessionManager createCoreSessionManager(boolean removeAttrOnInvalidate) { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_CORE.isLoggable(Level.FINE)) { LoggingUtil.SESSION_LOGGER_CORE.entering(methodClassName, methodNames[CREATE_CORE_SESSION_MAN...
python
def handle_read_length(self, buff, start, end): ''' handle read of number bytes needed to parse the value :param buff: :param start: :param end: ''' self.set_state_length(self._state, self.parse_uint(buff, start, end) * self._state[1].value.multiplier...
java
public Stream maxBy(String inputFieldName) { Aggregator<ComparisonAggregator.State> max = new Max(inputFieldName); return comparableAggregateStream(inputFieldName, max); }
python
def _receive_eol_token(self): """ A simple coroutine that is sent data until the first end of line (EOL) token is found. This sets the EOL_TOKEN member of the parser and pushes all data into the buffer. """ while self.EOL_TOKEN is None: # use yield to have dat...
python
def location_check(lat, lon): """For use by Core client wrappers""" if not (isinstance(lat, number_types) and -90 <= lat <= 90): raise ValueError("Latitude: '{latitude}' invalid".format(latitude=lat)) if not (isinstance(lon, number_types) and -180 <= lon <= 180): raise V...
python
def load(cls, serialized_index): """Load a serialized index""" from lunr import __TARGET_JS_VERSION__ if isinstance(serialized_index, basestring): serialized_index = json.loads(serialized_index) if serialized_index["version"] != __TARGET_JS_VERSION__: logger.war...
java
public <CC extends CellConsumer> CC parseAll(CC cellConsumer) throws IOException { _parseAll(wrapConsumer(cellConsumer), false); return cellConsumer; }
java
private static ModelExtractor tryLoadEngine(String engineClassName) { try { @SuppressWarnings("unchecked") Class<? extends ModelExtractor> engineClass = (Class<? extends ModelExtractor>) Class.forName(engineClassName, false, ModelExtractors.class.getClassLoader()); return eng...
java
private Paint decodeCloseGradient(Shape s, Color top, Color bottom) { Rectangle r = s.getBounds(); int width = r.width; int height = r.height; return createGradient(r.x + width / 2, r.y, r.x + width / 2, r.y + height - 1, new float[] { 0f, 1f }, new Color[] { top, bott...
python
def process_message_notification(request, messages_path): """Process all the msg file found in the message directory""" if not messages_path: return global _MESSAGES_CACHE global _MESSAGES_MTIME # NOTE (lhcheng): Cache the processed messages to avoid parsing # the files every time. Che...
java
private void generateInjectAdapter(TypeElement type, ExecutableElement constructor, List<Element> fields) throws IOException { String packageName = getPackage(type).getQualifiedName().toString(); TypeMirror supertype = getApplicationSupertype(type); if (supertype != null) { supertype = processin...
python
def remove(self): """Remove duplicate lines from text files""" num, sp, newfile = 0, "", [] if os.path.isfile(self.filename): with open(self.filename, "r") as r: oldfile = r.read().splitlines() for line in oldfile: if self.number: ...
python
def get_host_template(resource_root, name, cluster_name): """ Lookup a host template by name in the specified cluster. @param resource_root: The root Resource object. @param name: Host template name. @param cluster_name: Cluster name. @return: An ApiHostTemplate object. @since: API v3 """ return call(...
python
def file_upload(f): """ Return list of `werkzeug.datastructures.FileStorage` objects - files to be uploaded """ @wraps(f) def file_upload_decorator(*args, **kwargs): # If the data is already transformed, we do not transform it any # further. task_data = _get_data_from_ar...
python
def Dump(self, output): """Serialize the IncrementalUploadHelper and store in file-like object. Args: output: a file-like object where the status of the IncrementalUploadHelper will be written. Raises: GoogleAdsError: If a YAMLError occurs while writing to the file. """ data = ...
python
def Coerce(type, message="Not a valid {} value"): """ Creates a validator that attempts to coerce the given value to the specified ``type``. Will raise an error if the coercion fails. A custom message can be specified with ``message``. """ @wraps(Coerce) def built(value): try: ...
python
def to_array(self): """ Convert the RiakLinkPhase to a format that can be output into JSON. Used internally. """ stepdef = {'bucket': self._bucket, 'tag': self._tag, 'keep': self._keep} return {'link': stepdef}
python
def commit(self): """Commits the current transaction.""" if self._transaction_nesting_level == 0: raise DBALConnectionError.no_active_transaction() if self._is_rollback_only: raise DBALConnectionError.commit_failed_rollback_only() self.ensure_connected() ...
python
def update(self): """Update the IRQ stats.""" # Init new stats stats = self.get_init_value() # IRQ plugin only available on GNU/Linux if not LINUX: return self.stats if self.input_method == 'local': # Grab the stats stats = self.irq.g...
java
public static void isInstanceOf(Object obj, Class<?> type, RuntimeException cause) { if (isNotInstanceOf(obj, type)) { throw cause; } }
python
def CreateAllStaticRAPIDFiles(in_drainage_line, river_id, length_id, slope_id, next_down_id, rapid_output_folder, kfac_celerity=1000.0/3600....
java
private static Configuration hibernateConfiguration(Config config) { int transactionTimeout = config.getProperty("hibernate.transaction.timeout", int.class, 0); int min_size = config.getProperty("hibernate.c3p0.min_size", int.class, 0); int max_size = config.getProperty("hibernate.c3p0.max_size", int....
java
public boolean isEmpty() { if (m_filter != null) return false; // Not empty if (m_mapNameValue != null) if (m_mapNameValue.size() != 0) return false; // Not empty; return true; }
python
def _associate_data_cells_with_header_cells_of_row(self, element): """ Associate the data cell with header cell of row. :param element: The table body or table footer. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement """ table = self._get_model_table(elem...
java
@GuardedBy("evictionLock") void increaseWindow() { if (mainProtectedMaximum() == 0) { return; } long quota = Math.min(adjustment(), mainProtectedMaximum()); setMainProtectedMaximum(mainProtectedMaximum() - quota); setWindowMaximum(windowMaximum() + quota); demoteFromMainProtected(); ...
python
def get_status_from_location(self, response): """Process the latest status update retrieved from a 'location' header. :param requests.Response response: latest REST call response. :raises: BadResponse if response has no body and not status 202. """ self._raise_if_bad_htt...
java
public EClass getIfcOpeningElement() { if (ifcOpeningElementEClass == null) { ifcOpeningElementEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(336); } return ifcOpeningElementEClass; }
python
def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True, ContactType=pluginContactTypeAll, MultipleContacts=False): """Creates custom menu item in Skype client's "Do More" menus. :Parameters: MenuItemId : unicode ...
java
private ScopeBlock findScopeBlockWithTarget(ScopeBlock sb, int start, int target) { ScopeBlock parentBlock = null; int finishLocation = sb.getFinish(); if ((sb.getStart() < start) && (finishLocation >= start) && ((finishLocation <= target) || (sb.isGoto() && !sb.isLoop()))) { parentB...
java
public EntityInstanceWrapper getSelected() throws PMException { final EntityContainer container = getEntityContainer(true); if (container == null) { return null; } return container.getSelected(); }
java
public JCRPath parseJCRPath(String path) throws RepositoryException { if (isAbsPathParseable(path)) { return parseAbsPath(path); } else { return parseRelPath(path); } }
java
public Map<String,Object> addMenuProperties(String strSubDomain, Record recMenus, Map<String,Object> mapDomainProperties) { try { recMenus.getField(Menus.CODE).setString(strSubDomain); if (recMenus.seek("=")) { Map<String,Object> properties = ((PropertiesF...
java
public static nstrafficdomain_stats get(nitro_service service, Long td) throws Exception{ nstrafficdomain_stats obj = new nstrafficdomain_stats(); obj.set_td(td); nstrafficdomain_stats response = (nstrafficdomain_stats) obj.stat_resource(service); return response; }
python
def rotz(t): """Rotation about the z-axis.""" c = np.cos(t) s = np.sin(t) return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]])
java
@Override protected final Iterator<DeployListener> findDeployListeners( ClassLoader pluginClassLoader) { final Iterator<DeployListener> listeners = this.serviceLoader.loadService( DeployListener.class, pluginClassLoader); return new Iterator<DeployListener>() { ...
python
def send_feedback(cls, type=FeedbackType.IDEA, referrer=None, text=None, api=None): """ Sends feedback to sevenbridges. :param type: FeedbackType wither IDEA, PROBLEM or THOUGHT. :param text: Feedback text. :param referrer: Feedback referrer. :param ...
python
def node_label_absent(name, node, **kwargs): ''' Ensures that the named label is absent from the node. name The name of the label node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} labels = __...
python
def cells(a, b): ''' # Sum ''' a, b = int(a), int(b) ''' ''' a + b
python
def search_registered_query_for_facet(self, facet, **kwargs): # noqa: E501 """Lists the values of a specific facet over the customer's non-deleted derived metric definitions # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HT...
python
def merge(left, right, merged): """ Merge helper Complexity: O(n) """ left_cursor, right_cursor = 0, 0 while left_cursor < len(left) and right_cursor < len(right): # Sort each one and place into the result if left[left_cursor] <= right[right_cursor]: merged[left_curs...
python
def filter_images_urls(image_urls, image_filter, common_image_filter=None): ''' 图片链接过滤器,根据传入的过滤器规则,对图片链接列表进行过滤并返回结果列表 :param list(str) image_urls: 图片链接字串列表 :param list(str) image_filter: 过滤器字串列表 :param list(str) common_image_filter: 可选,通用的基础过滤器, 会在定制过滤器前对传入图片应用 ...
java
@Override public EEnum getSmtpProtocol() { if (smtpProtocolEEnum == null) { smtpProtocolEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(98); } return smtpProtocolEEnum; }
python
def update_or_create(cls, with_status=False, **kwargs): """ Update or create active directory configuration. :param dict kwargs: kwargs to satisfy the `create` constructor arguments if the element doesn't exist or attributes to change :raises CreateElementFailed: fai...
python
def _construct_divmod_result(left, result, index, name, dtype=None): """divmod returns a tuple of like indexed series instead of a single series. """ return ( _construct_result(left, result[0], index=index, name=name, dtype=dtype), _construct_result(left, result[1],...
python
def compose(self, **kwargs): """ Compose layer and masks (mask, vector mask, and clipping layers). :return: PIL Image object, or None if the layer has no pixels. """ from psd_tools.api.composer import compose return compose(self, **kwargs)
java
private Search search(List<IndexExpression> clause) { IndexExpression indexedExpression = indexedExpression(clause); String json = UTF8Type.instance.compose(indexedExpression.value); return Search.fromJson(json); }
python
def AgregarReceptor(self, cuit, iibb, nro_socio, nro_fet, **kwargs): "Agrego un receptor a la liq." rcpt = dict(cuit=cuit, iibb=iibb, nroSocio=nro_socio, nroFET=nro_fet) self.solicitud['receptor'] = rcpt return True
python
def render_form_field(parser, token): """ Usage is {% render_form_field form.field_name optional_help_text optional_css_classes %} - optional_help_text and optional_css_classes are strings - if optional_help_text is not given, then it is taken from form field object """ try: help_text =...
python
def plot_distance_landscape_projection(self, x_axis, y_axis, ax=None, *args, **kwargs): """ Plots the distance landscape jointly-generated from all the results :param x_axis: symbol to plot on x axis :param y_axis: symbol to plot on y axis :param ax: axis object to plot onto ...
java
@Indexable(type = IndexableType.REINDEX) @Override public CommerceOrder updateCommerceOrder(CommerceOrder commerceOrder) { return commerceOrderPersistence.update(commerceOrder); }
java
public void init(BaseField field, BaseField fldTarget, Converter checkMark, String fieldName) { super.init(field, fldTarget, checkMark, fieldName); }
python
def matrix_multiply(m1, m2): """ Matrix multiplication (iterative algorithm). The running time of the iterative matrix multiplication algorithm is :math:`O(n^{3})`. :param m1: 1st matrix with dimensions :math:`(n \\times p)` :type m1: list, tuple :param m2: 2nd matrix with dimensions :math:`(p \\t...
python
def ledger(self): """Convert to a Ledger transaction (no trailing blank line)""" self.balance() # make sure the transaction balances s = "{0}/{1:02}/{2:02} {3}\n".format( self.date.year, self.date.month, self.date.day, self.desc.replace('\n', ' ...
python
def _write_apt_gpg_keyfile(key_name, key_material): """Writes GPG key material into a file at a provided path. :param key_name: A key name to use for a key file (could be a fingerprint) :type key_name: str :param key_material: A GPG key material (binary) :type key_material: (str, bytes) """ ...
java
public static WebElementFinder create() { return new WebElementFinder(null, null, 0L, 0L, null, null, null, null, false); }
java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { final boolean isTraceOn = svLogger.isLoggable(Level.FINER); if (isTraceOn) svLogger.entering(CLASS_NAME, "readObject"); in.defaultReadObject(); byte[] ec = new byte[Constants.E...
python
def generate(self, text): """Try to get the generated file. Args: text: The text that you want to generate. """ if not text: raise Exception("No text to speak") if len(text) >= self.MAX_CHARS: raise Exception("Number of characters must be les...
python
def delete_device(self, auth_body, device_id): """Deletes the given device, and invalidates any access token associated with it. NOTE: This endpoint uses the User-Interactive Authentication API. Args: auth_body (dict): Authentication params. device_id (str): The device ...
java
public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraph(SEG segment, StyleSpans<S> styles, PS paragraphStyle) { return addPar(new Paragraph<>(argumentOrDefault(paragraphStyle), segmentOps, segment, styles)); }
java
private String escape(final String val) { // TODO: this function is ugly, pass this work off to SQLite, then we // don't have to worry about Unicode 4, other characters needing // escaping, etc. int len = val.length(); StringBuilder buf = new StringBuilder(len); for (int i = 0; i < len; i++) { ...
python
def _get_object(self, o_type, o_name=None): """Get an object from the scheduler Returns None if the required object type (`o_type`) is not known. Else returns the serialized object if found. The object is searched first with o_name as its name and then with o_name as its uuid. ...
java
public static IntegerVector copyOf(IntegerVector source) { IntegerVector result = null; if (source instanceof TernaryVector) { TernaryVector v = (TernaryVector) source; int[] pos = v.positiveDimensions(); int[] neg = v.negativeDimensions(); result = new T...
python
def decision_function(self, pairs): """Returns the decision function used to classify the pairs. Returns the opposite of the learned metric value between samples in every pair, to be consistent with scikit-learn conventions. Hence it should ideally be low for dissimilar samples and high for similar sam...
java
protected Collection<BioPAXElement> generate(Conversion conv, Direction direction, Set<Entity> taboo) { if (direction == null) throw new IllegalArgumentException("Direction cannot be null"); if (!(direction == Direction.BOTHSIDERS || direction == Direction.ONESIDERS)) { Set<BioPAXElement> simples = new Has...
java
public void setProperty(String strProperty, String strValue) { Record record = this.getMainRecord(); BaseTable table = record.getTable(); table.setProperty(strProperty, strValue); }
python
def change_password(self, previous_password, proposed_password): """ Change the User password """ self.check_token() response = self.client.change_password( PreviousPassword=previous_password, ProposedPassword=proposed_password, AccessToken=sel...
java
public int getUnique() { TIntHashSet inUseSet = new TIntHashSet(); for (int i = 0; i < length; i++) { inUseSet.add(get(i)); } return inUseSet.size(); }
python
def _add_devices_from_config(args): """ Add devices from config. """ config = _parse_config(args.config) for device in config['devices']: if args.default: if device == "default": raise ValueError('devicename "default" in config is not allowed if default param is set') ...