language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _derive_charge(self, config): """Use a temperature window to identify the roast charge. The charge will manifest as a sudden downward trend on the temperature. Once found, we save it and avoid overwriting. The charge is needed in order to derive the turning point. :param co...
java
void _setToDefault() { resizeAttributes(m_description.getTotalComponentCount()); Point.attributeCopy(m_description._getDefaultPointAttributes(), m_attributes, m_description.getTotalComponentCount()); m_attributes[0] = NumberUtils.NaN(); m_attributes[1] = NumberUtils.NaN(); }
java
public boolean referencesMethod(ExecutableElement method) { TypeElement declaringClass = (TypeElement) method.getEnclosingElement(); String fullyQualifiedname = declaringClass.getQualifiedName().toString(); String name = method.getSimpleName().toString(); assert name.indexOf('.') == ...
java
private static BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> bodySendDelegate(final HttpRequest restRequest) { BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> sendDelegate = (reactorNettyRequest, reactorNettyOutbound) -> { for (HttpHeader header : restRequest.headers())...
java
public boolean hasPermission(IConnection conn, String permissionName) { final Collection<String> permissions = getPermissions(conn); return permissions.contains(permissionName); }
python
def label(self) -> str: """A latex formatted label representing constant expression and united value.""" label = self.expression.replace("_", "\\;") if self.units_kind: symbol = wt_units.get_symbol(self.units) for v in self.variables: vl = "%s_{%s}" % (sym...
python
def element(self, *args, **kwargs): """ Add a child element to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: a new Builder that represents the child element. Delegates to :meth:`xml4h.nodes.Element.add_element`. """ child_element = ...
java
public String relative(String url) { try { final URI uri = absolute(url).build(); return new URI(null, null, uri.getPath(), uri.getQuery(), uri.getFragment()).toString(); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
java
public void send(Address dst, byte[] buf, int offset, int length) throws Exception { ch.send(dst, buf, offset, length); }
java
@Pure @SuppressWarnings("static-method") public List<Object> getOptionValues(String optionLabel) { final List<Object> options = getCommandLineOption(optionLabel); if (options == null) { return Collections.emptyList(); } return Collections.unmodifiableList(options); }
python
def continue_oauth(self, oauth_callback_data=None): """ Continuation of OAuth procedure. Method must be explicitly called in order to complete OAuth. This allows external entities, e.g. websites, to provide tokens through callback URLs directly. :param oauth_callback_data: The callback U...
python
def plot_diagrams( diagrams, plot_only=None, title=None, xy_range=None, labels=None, colormap="default", size=20, ax_color=np.array([0.0, 0.0, 0.0]), diagonal=True, lifetime=False, legend=True, show=False, ax=None ): """A helper function to plot persistence diagra...
python
def from_dict(cls, ctx): 'Instance a new structure from a Python native type.' ctx = Context(ctx) s = cls() ContextFlags = ctx['ContextFlags'] s.ContextFlags = ContextFlags for key in cls._others: if key != 'VectorRegister': setattr(s, key, ctx...
java
@Override public CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { LOGGER.info("###Used SSL Enabled Http Client for http/https/TLS connections"); SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null...
java
private void FQ( double[] F_Q, double[] Q, double[] U_I, double[] U, double[][] idrgeo, List<RiverPoint> riverPoints, double delta_T, double qin, double qout ) { double coeff; /* Coefficient of Coriolis in the sections i e i+1 */ double alfa, alfa_i, alfa_ii; /* Average velo...
python
def get_next(self, tag="<"): """ This function is tricky and took me a while to figure out. The tag specifies the direction where the current edge came from. tag ntag ---> V >----> U cur next This means the next vertex should follow the outs sinc...
java
public static boolean deleteDir(File dir) { if (dir.isDirectory()) { String[] children = dir.list(); for (String file : children) { boolean success = deleteDir(new File(dir, file)); if (!success) { return false; ...
java
public void setMax(int max) { this.max = max; if (this.max < Alterable.MIN) { this.max = Alterable.MIN; } set(cur); }
java
private static void populateReplyToFromHeader(JmsDestinationImpl tempReplyTo, JsJmsMessage _msg, List<SIDestinationAddress> rrp) throws JMSException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "populateReplyToFromHeader", new Object[] { tempReplyTo, _msg, rrp }...
java
public static int checkElementIndex( int index, int size, final Eid eid, final String messageFormat, final Object... parameters ) { if (isSizeIllegal(size)) { throw new EidIllegalArgumentException( ensureEid(eid).message(messageFormat, para...
java
@Override public void cacheResult( CommerceNotificationTemplateUserSegmentRel commerceNotificationTemplateUserSegmentRel) { entityCache.putResult(CommerceNotificationTemplateUserSegmentRelModelImpl.ENTITY_CACHE_ENABLED, CommerceNotificationTemplateUserSegmentRelImpl.class, commerceNotificationTemplateUserSeg...
python
def bibitem_as_plaintext(bibitem): """ Return a plaintext representation of a bibitem from the ``.bbl`` file. .. note:: This plaintext representation can be super ugly, contain URLs and so \ on. .. note:: You need to have ``delatex`` installed system-wide, or to build it in \...
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static <T> Ix<T> concat(Iterable<? extends Iterable<? extends T>> sources) { return new IxFlattenIterable<Iterable<? extends T>, T>( (Iterable)nullCheck(sources, "sources is null"), IdentityHelper.<Iterable<? extends T>>in...
java
public Observable<ResourceHealthMetadataInner> getBySiteSlotAsync(String resourceGroupName, String name, String slot) { return getBySiteSlotWithServiceResponseAsync(resourceGroupName, name, slot).map(new Func1<ServiceResponse<ResourceHealthMetadataInner>, ResourceHealthMetadataInner>() { @Override ...
java
public static boolean isSecure(final Component component) { if (AnnotationExtensions.isAnnotationPresentInSuperClassesOrInterfaces(component.getClass(), RequireHttps.class)) { return true; } return false; }
java
private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) { if (null == response) { return null; } final JSONObject suggestions = new JSONObject(); final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap(); // Add suggestions to t...
python
def _toolkit_serialize_summary_struct(model, sections, section_titles): """ Serialize model summary into a dict with ordered lists of sections and section titles Parameters ---------- model : Model object sections : Ordered list of lists (sections) of tuples (field,value) [ [(fi...
java
public static boolean containsOccurrences( Multiset<?> superMultiset, Multiset<?> subMultiset) { checkNotNull(superMultiset); checkNotNull(subMultiset); for (Entry<?> entry : subMultiset.entrySet()) { int superCount = superMultiset.count(entry.getElement()); if (superCount < entry.getCount...
python
def check_install_conflicts(to_install): # type: (List[InstallRequirement]) -> Tuple[PackageSet, CheckResult] """For checking if the dependency graph would be consistent after \ installing given requirements """ # Start from the current state package_set, _ = create_package_set_from_installed() ...
java
private static void radixPass(int[] src, int[] dst, int[] v, int vi, final int n, final int K, int start, int[] cnt) { // check counter array's size. assert cnt.length >= K + 1; Arrays.fill(cnt, 0, K + 1, 0); // count occurrences for (int i = 0;...
java
private void splitAt(long t) { if (data.containsKey(t)) return; // already split at this timestamp SortedMap<Long, int[]> head = data.headMap(t); int v = head.isEmpty() ? 0 : data.get(head.lastKey())[0]; data.put(t, new int[]{v}); }
python
def dimensionNames(self): """ Returns a list with the dimension names of the underlying NCDF variable """ nSubDims = len(self._subArrayShape) subArrayDims = ['SubDim{}'.format(dimNr) for dimNr in range(nSubDims)] return dimNamesFromDataset(self._h5Dataset) + subArrayDims
java
public static String escapeSpecialChar(String keyword) { if (!isEmpty(keyword)) { String[] fbsArr = {"\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|"}; for (String key : fbsArr) { if (keyword.contains(key)) { keyword = keyword.repl...
python
def serialize_footnote(ctx, document, el, root): "Serializes footnotes." footnote_num = el.rid if el.rid not in ctx.footnote_list: ctx.footnote_id += 1 ctx.footnote_list[el.rid] = ctx.footnote_id footnote_num = ctx.footnote_list[el.rid] note = etree.SubElement(root, 'sup') li...
python
def validate_owner_repo(ctx, param, value): """Ensure that owner/repo is formatted correctly.""" # pylint: disable=unused-argument form = "OWNER/REPO" return validate_slashes(param, value, minimum=2, maximum=2, form=form)
java
@Override protected void onInitialize() { super.onInitialize(); add(this.swapPanel = new SwapComponentsFragmentPanel<T>("swapPanel", getModel()) { /** The serialVersionUID. */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override protected Component newEditCom...
python
def getLocalID(self): """Return the identifier that should be sent as the openid.identity parameter to the server.""" # I looked at this conditional and thought "ah-hah! there's the bug!" # but Python actually makes that one big expression somehow, i.e. # "x is x is x" is not the...
python
def spf_rec(rdata): ''' Validate and parse DNS record data for SPF record(s) :param rdata: DNS record data :return: dict w/fields ''' spf_fields = rdata.split(' ') if not spf_fields.pop(0).startswith('v=spf'): raise ValueError('Not an SPF record') res = OrderedDict() mods = ...
java
@GwtIncompatible("incompatible method") public static Iterable<Class<?>> hierarchy(final Class<?> type, final Interfaces interfacesBehavior) { final Iterable<Class<?>> classes = new Iterable<Class<?>>() { @Override public Iterator<Class<?>> iterator() { final Mutable...
java
private static double[] adjustSize (double[] array, int newSize) { if (newSize <= array.length) { return array; } double[] newArray = new double[2 * newSize]; System.arraycopy(array, 0, newArray, 0, array.length); return newArray; }
python
def cudnnGetConvolutionForwardWorkspaceSize(handle, srcDesc, wDesc, convDesc, destDesc, algo): """" This function returns the amount of GPU memory workspace the user needs to allocate to be able to call cudnnConvolutionForward with the specified algorithm. Pa...
java
private void startGeneralJobConfigFileMonitor() throws Exception { SchedulerUtils.addPathAlterationObserver(this.pathAlterationDetector, this.listener, jobConfigFileDirPath); this.pathAlterationDetector.start(); this.closer.register(new Closeable() { @Override public void close() throws IO...
python
def dict_key(self): """ Find the next key in a dict. We skip any newlines and check for if the dict has ended. """ while True: token = self.next() t_value = token["value"] if t_value == "\n": continue if t_value == ...
python
def vip_create_event(self, vip_info): """Process vip create event.""" vip_data = vip_info.get('vip') port_id = vip_data.get('port_id') vip_id = vip_data.get('id') self.add_lbaas_port(port_id, vip_id)
java
private boolean loadMatchRulesFromJar(String rulesUrl) { //load match rules from a local file try { mCallbacks.printOutput("Loading match rules from local jar: " + rulesUrl); InputStream in = getClass().getClassLoader().getResourceAsStream(rulesUrl); BufferedReader reader = new BufferedR...
python
def rebuild(): """ Deletes and re-creates your DB. Needs django-extensions and South. """ drop_db() create_db() if StrictVersion(django.get_version()) < StrictVersion('1.7'): local('python{} manage.py syncdb --all --noinput'.format( PYTHON_VERSION)) local('python{} m...
java
public void onScrollChanged(int scrollY, Scrollable s) { FlexibleSpaceWithImageBaseFragment fragment = (FlexibleSpaceWithImageBaseFragment) mPagerAdapter.getItemAt(mPager.getCurrentItem()); if (fragment == null) { return; } View view = fragment.getView(); ...
python
def compile_pythrancode(module_name, pythrancode, specs=None, opts=None, cpponly=False, pyonly=False, output_file=None, module_dir=None, **kwargs): '''Pythran code (string) -> c++ code -> native module if `cpponly` is set to true, return the generated C++ filenam...
python
def list_streams(region=None, key=None, keyid=None, profile=None): ''' Return a list of all streams visible to the current account CLI example: .. code-block:: bash salt myminion boto_kinesis.list_streams ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) s...
python
def create_or_update_resource(resource_name, identifier_fields, data, diff=None, profile='pagerduty', subdomain=None, api_key=None): ''' create or update any pagerduty resource Helper method for present(). Determining if two resources are the same is different for different PD resource, so this method ...
java
public Production getBeta() { Production production = new Production("beta"); for (int pos = getPosition() + 1; pos < getProduction() .getConstructions().size(); pos++) { production.addConstruction(getProduction().getConstructions().get( pos)); } return production; }
java
public final void logInfo(@NonNull final Class<?> tag, @NonNull final String message) { Condition.INSTANCE.ensureNotNull(tag, "The tag may not be null"); Condition.INSTANCE.ensureNotNull(message, "The message may not be null"); Condition.INSTANCE.ensureNotEmpty(message, "The message may not be e...
python
def report(self, fraction=None): """report the total progress for the current stack, optionally given the local fraction completed. fraction=None: if given, used as the fraction of the local method so far completed. runtimes=None: if given, used as the expected runtimes for the current stack. """ r = Dict() ...
python
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT): """Dump rows to ``fileobj`` with the given ``encoding`` and CSV ``dialect``.""" csvwriter = csv.writer(fileobj, dialect=dialect) csv_writerows(csvwriter, rows, encoding)
java
@SuppressWarnings("unchecked") public static <K, V> Map<K, V> fieldValueMap(Iterator<V> iter, String fieldName) { final Map<K, V> result = new HashMap<>(); if (null != iter) { V value; while (iter.hasNext()) { value = iter.next(); result.put((K) ReflectUtil.getFieldValue(value, fieldName), val...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.FONT_CODED_GRAPHIC_CHARACTER_SET_GLOBAL_IDENTIFIER__GCSGID: return GCSGID_EDEFAULT == null ? gcsgid != null : !GCSGID_EDEFAULT.equals(gcsgid); case AfplibPackage.FONT_CODED_GRAPHIC_CHARACTER_SET_GLOBAL_IDENTIFIER__CPGI...
python
def node_validate(node_dict, node_num, cmd_name): """Validate that command can be performed on target node.""" # cmd: [required-state, action-to-displayed, error-statement] req_lu = {"run": ["stopped", "Already Running"], "stop": ["running", "Already Stopped"], "connect": ["runni...
python
def show_version_queue(a_device, output_q): """ Use Netmiko to execute show version. Use a queue to pass the data back to the main process. """ output_dict = {} remote_conn = ConnectHandler(**a_device) hostname = remote_conn.base_prompt output = ("#" * 80) + "\n" output += remote_con...
python
def _get_dataset(dataset_name, dataset_prefix=None, data_dir=None, default_paths=None, verbose=1): """ Create if necessary and returns data directory of given dataset. data_dir: str Path of the data directory. Used to force data storage in a specified location. ...
python
def get_lr(lr, epoch, steps, factor): """Get learning rate based on schedule.""" for s in steps: if epoch >= s: lr *= factor return lr
python
def compute_classpath_entries(cls, targets, classpath_products, extra_classpath_tuples, confs): """Return the list of classpath entries for a classpath covering the passed targets. Filters and adds paths from extra_classpath_tuples to the end of the resulting list. :param targets: The targets to generate ...
python
def filter_top_level(stmts_in, **kwargs): """Filter to statements that are at the top-level of the hierarchy. Here top-level statements correspond to most specific ones. Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[st...
java
@Override public String getText(final Object... stringParameters) { String res = get().getMessage(); if (stringParameters.length > 0) { try { // Use the message formatter res = MessageFormat.format(res, stringParameters); if (res.startsW...
python
def headgrid2(self, x1, x2, nx, y1, y2, ny, layers=None, printrow=False): """Grid of heads Parameters ---------- x1, x2, nx : x values are generated as linspace(x1, x2, nx) y1, y2, ny : y values are generated as linspace(y1, y2, ny) laye...
java
public static void scanUpdateCallbacks(ScanStaticModel scanModel, Registry registry) { // 扫描出来 ScanDynamicModel scanDynamicModel = analysis4DisconfUpdate(scanModel, registry); // 写到仓库中 transformUpdateService(scanDynamicModel.getDisconfUpdateServiceInverseIndexMap()); transformP...
java
public SharedFlowController createSharedFlow( RequestContext context, String sharedFlowClassName ) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class sharedFlowClass = getFlowControllerClass( sharedFlowClassName ); return createSharedFlow( context, shar...
python
def message(self, msg='', level=1, tab=0): '''Print a message to the console''' if self.verbosity >= level: self.stdout.write('{}{}'.format(' ' * tab, msg))
python
def iteritems(self, raw=False): """ Iterate self items. """ for key in self: yield key, self.__getitem__(key, raw=raw)
python
def annotate_image(self, request, retry=None, timeout=None): """Run image detection and annotation for an image. Example: >>> from google.cloud.vision_v1 import ImageAnnotatorClient >>> client = ImageAnnotatorClient() >>> request = { ... 'image': { ...
java
public String convertIfcEngineTypeEnumToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
python
def to_dict(self): """ Return a dictionary representation of the dataset. """ d = dict(individual_doses=self.individual_doses, responses=self.responses) d.update(self.kwargs) return d
python
def __load_settings_from_file(self): """ Loads settings info from the settings json file :returns: True if the settings info is valid :rtype: boolean """ filename = self.get_base_path() + 'settings.json' if not exists(filename): raise OneLogin_Saml2_...
python
def _expand_probes(probes, defaults): ''' Updates the probes dictionary with different levels of default values. ''' expected_probes = {} for probe_name, probe_test in six.iteritems(probes): if probe_name not in expected_probes.keys(): expected_probes[probe_name] = {} ...
python
def create_unassociated(self, attachment, inline=False, file_name=None, content_type=None): """ You can use this endpoint for bulk imports. It lets you upload a file without associating it to an article until later. Check Zendesk documentation `important notes <https://developer....
java
public ByteBuffer getFloats(int index, ByteBuffer buffer) { MemUtil.INSTANCE.putf(this, index, buffer); return buffer; }
python
def main(argv=None): """Main entry point for iotile-ship recipe runner. This is the iotile-ship command line program. Args: argv (list of str): An optional set of command line parameters. If not passed, these are taken from sys.argv. """ if argv is None: a...
java
private void validateAttributeGeneralization(final Attributes atts) { final QName[][] d = domains.peekFirst(); if (d != null) { for (final QName[] spec: d) { for (int i = spec.length - 1; i > -1; i--) { if (atts.getValue(spec[i].getNamespaceURI(), spec[i]....
python
def get_capture(self): """Return the capture board or None if can't find it.""" # game game_image = self._game_image_from_screen('capture') if game_image is None: return # board board = self._board_from_game_image(game_image) if board is None: ...
java
public static Map<String,Object> escapeInjections(Map<String,Object> m){ if(m==null) return null; return Objects.iterate(m, new Closure<ObjectIterator.IterateBean, Object>() { @Override public Object call(ObjectIterator.IterateBean input) { if(input.ge...
java
public void addPayloadProperties(Object msg, BaseMessage message) { MessageDataDesc messageDataDesc = message.getMessageDataDesc(null); // Top level only if (messageDataDesc != null) { Map<String,Class<?>> mapPropertyNames = messageDataDesc.getPayloadPropertyNames(null); ...
java
static public String getFormattedBytes(long bytes, String units, String format) { double num = bytes; String[] prefix = {"", "K", "M", "G", "T"}; int count = 0; while(num >= 1024.0) { num = num/1024.0; ++count; } DecimalFormat f = new...
java
protected int selectSplitOffset( int indexStart , int length ) { int bestOffset = -1; int indexEnd = (indexStart + length) % N; Point2D_I32 startPt = contour.get(indexStart); Point2D_I32 endPt = contour.get(indexEnd); line.p.set(startPt.x,startPt.y); line.slope.set(endPt.x-startPt.x,endPt.y-startPt.y); ...
java
public long getApproxSubmitTime(Result value) throws MissingColumnInResultException { if (value == null) { throw new IllegalArgumentException( "Cannot get last modification time from " + "a null hbase result"); } Cell cell = value.getColumnLatestCell(Constants.INFO_FAM_BYTES, ...
python
def human__decision_tree(): """ Decision Tree """ # build data N = 1000000 M = 3 X = np.zeros((N,M)) X.shape y = np.zeros(N) X[0, 0] = 1 y[0] = 8 X[1, 1] = 1 y[1] = 8 X[2, 0:2] = 1 y[2] = 4 # fit model xor_model = sklearn.tree.DecisionTreeRegressor(max_d...
java
private void loadRecentList() { recent.clear(); File file = new File(RECENT_FILE_NAME); if (file.exists()) { try { InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); XMLDecoder decoder = new XMLDecoder(inputStream); List result = (List) decoder.readObject(); decoder...
java
protected void tick () { // if we're not connected, skip it if (_comm == null) { return; } long now = RunAnywhere.currentTimeMillis(); if (_dcalc != null) { // if our current calculator is done, clear it out if (_dcalc.isDone()) { ...
python
def extract_chunks(blob): """Splits the blob into chucks grouped by kind.""" chunks = [] stream = BytesIO(blob.bytes) current_pos = stream.tell() stream.seek(0, 2) length = stream.tell() stream.seek(current_pos, 0) while stream.tell() < length: chunks.append(read_chunk(stream)) ...
java
@Override public CommerceNotificationQueueEntry fetchByCommerceNotificationTemplateId_First( long commerceNotificationTemplateId, OrderByComparator<CommerceNotificationQueueEntry> orderByComparator) { List<CommerceNotificationQueueEntry> list = findByCommerceNotificationTemplateId(commerceNotificationTemplateId,...
python
def extract_symbol_app(parser, _, args): # pragma: no cover """ Extract a symbol from an ELF file. """ parser.add_argument('file', help='ELF file to extract a symbol from') parser.add_argument('symbol', help='the symbol to extract') args = parser.parse_args(args) return ELF(args.file).get_...
python
def list_build_records(page_size=200, page_index=0, sort="", q=""): """ List all BuildRecords """ data = list_build_records_raw(page_size, page_index, sort, q) if data: return utils.format_json_list(data)
java
public void init(Compiler compiler, int opPos, int stepType) throws javax.xml.transform.TransformerException { initPredicateInfo(compiler, opPos); // int testType = compiler.getOp(nodeTestOpPos); }
python
def intersection(self, another_moc, *args): """ Intersection between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the intersection with self. args : `~mocpy.moc.MOC` Other additi...
java
@Override public void visitClassContext(ClassContext classContext) { try { JavaClass cls = classContext.getJavaClass(); if (isSingleton(cls)) { syncBlockBranchResetValues = new HashMap<>(); stack = new OpcodeStack(); super.visitClassCon...
python
def fcontext_get_policy(name, filetype=None, sel_type=None, sel_user=None, sel_level=None): ''' .. versionadded:: 2017.7.0 Returns the current entry in the SELinux policy list as a dictionary. Returns None if no exact match was found. Returned keys are: * filespec (the name supplied and match...
java
public void set(Property.Builder prop, String channelName) { Collection<String> ch = new ArrayList<String>(); ch.add(channelName); wrappedSubmit(new SetProperty(prop.toXml(), ch)); }
python
def _create_placeholders(self): """Create the computational graph's placeholders.""" self.input_data = tf.placeholder( tf.int32, [self.batch_size, self.num_steps]) self.input_labels = tf.placeholder( tf.int32, [self.batch_size, self.num_steps])
java
public Map<BsonValue, ChangeEvent<BsonDocument>> getEventsForNamespace( final MongoNamespace namespace ) { this.instanceLock.readLock().lock(); final NamespaceChangeStreamListener streamer; try { streamer = nsStreamers.get(namespace); } finally { this.instanceLock.readLock().unlock()...
python
def interpolate2dStructuredIDW(grid, mask, kernel=15, power=2, fx=1, fy=1): ''' replace all values in [grid] indicated by [mask] with the inverse distance weighted interpolation of all values within px+-kernel [power] -> distance weighting factor: 1/distance**[power] ''' weights = ...
java
private OriginalMapping getOriginalMappingForEntry(Entry entry) { if (entry.getSourceFileId() == UNMAPPED) { return null; } else { // Adjust the line/column here to be start at 1. Builder x = OriginalMapping.newBuilder() .setOriginalFile(sources[entry.getSourceFileId()]) .setLi...
java
public static boolean validateDateString(String dateString) { if (dateString == null || dateString.equals("")) { return false; } // 日期格式YYYYMMDD的正则表达式,世纪年为闰年,如2000 String regDate = "^(((([02468][048])|([13579][26]))[0]{2})(02)(([0][1-9])|([1-2][0-9])))" + ...