language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def filter_record(self, record): """ Filter record, dropping any that don't meet minimum length """ if len(record) >= self.min_length: return record else: raise FailedFilter(len(record))
python
async def async_get_current_transfer_rates(self, use_cache=True): """Gets current transfer rates calculated in per second in bytes.""" now = datetime.utcnow() data = await self.async_get_bytes_total(use_cache) if self._rx_latest is None or self._tx_latest is None: self._lates...
java
@Override public int read(byte[] buffer, int offset, int len) throws IOException { return this.in.read(buffer, offset, len); }
java
public Pair<List<Node>, List<Node>> splitIntervalPattern(String raw) { List<Node> pattern = parse(raw); Set<Character> seen = new HashSet<>(); List<Node> fst = new ArrayList<>(); List<Node> snd = new ArrayList<>(); // Indicates we've seen a repeated field. boolean boundary = false; for (N...
python
def main(): """Wdb entry point""" sys.path.insert(0, os.getcwd()) args, extrargs = parser.parse_known_args() sys.argv = ['wdb'] + args.args + extrargs if args.file: file = os.path.join(os.getcwd(), args.file) if args.source: print('The source argument cannot be used with...
java
public JvmAnnotationReference findAnnotation(/* @NonNull */ JvmAnnotationTarget annotationTarget, /* @NonNull */ Class<? extends Annotation> lookupType) { // avoid creating an empty list for all given targets but check for #eIsSet first if (annotationTarget.eIsSet(TypesPackage.Literals.JVM_ANNOTATION_TARGET__ANNOTA...
python
def notequal(x, y): """ Return True if x != y and False otherwise. This function returns True whenever x and/or y is a NaN. """ x = BigFloat._implicit_convert(x) y = BigFloat._implicit_convert(y) return not mpfr.mpfr_equal_p(x, y)
java
public static boolean unregister(IEventHandler who) { final Handle handle = Handle.getInstance(); return handle._unregister(who); }
python
def build_latex(hyp): """ Parameters ---------- hyp : dict {'segmentation': [[0, 3], [1, 2]], 'symbols': [{'symbol': ID, 'probability': 0.12}], 'geometry': {'symbol': index, 'bottom': None or dict, 'subscript': None or dict, ...
java
public ToolScreen addToolbars() { ToolScreen screen = new ToolScreen(null, this, null, ScreenConstants.DONT_DISPLAY_FIELD_DESC, null); new SCannedBox(screen.getNextLocation(ScreenConstants.NEXT_LOGICAL, ScreenConstants.SET_ANCHOR), screen, null, ScreenConstants.DEFAULT_DISPLAY, MenuConstants.SUBMIT)...
python
def deconvolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None): """ Deconvolution layer. Args: ...
java
@Override public final boolean hasNext() { resetToLastKey(); while (mAxis.hasNext()) { mAxis.next(); boolean filterResult = true; for (final AbsFilter filter : mAxisFilter) { filterResult = filterResult && filter.filter(); } ...
java
public void replaceOrAdd(String name, String value) { boolean found = false; for (Param param : params) { if (param.getKey().equals(name)) { param.setValue(value); found = true; break; } } if (!found) { a...
python
def _prepare_data_dir(self, data): """Prepare destination directory where the data will live. :param data: The :class:`~resolwe.flow.models.Data` object for which to prepare the private execution directory. :return: The prepared data directory path. :rtype: str """ ...
java
@SuppressWarnings("unchecked") public T withInterval(Duration interval) { Assert.notNull(interval, "interval"); Assert.state(maxInterval == null, "Backoff intervals have already been set"); this.interval = interval; return (T) this; }
java
public void dragUpdate(final INodeXYEvent event) { m_evtx = event.getX(); m_evty = event.getY(); m_dstx = m_evtx - m_begx; m_dsty = m_evty - m_begy; final Point2D p2 = new Point2D(0, 0); m_gtol.transform(new Point2D(m_dstx, m_dsty), p2); m_lclp.setX(p2.g...
java
public void enableDTLS() { if (!this.dtls) { this.rtpChannel.enableSRTP(); if (!this.rtcpMux) { rtcpChannel.enableSRTCP(); } this.dtls = true; if (logger.isDebugEnabled()) { logger.debug(this.mediaType + " channel " + t...
python
def wrap_inference_results(inference_result_proto): """Returns packaged inference results from the provided proto. Args: inference_result_proto: The classification or regression response proto. Returns: An InferenceResult proto with the result from the response. """ inference_proto = inference_pb2.I...
java
public static Point2d WSG84_L4(double lambda, double phi) { final Point2d ntfLambdaPhi = WSG84_NTFLamdaPhi(lambda, phi); return NTFLambdaPhi_NTFLambert( ntfLambdaPhi.getX(), ntfLambdaPhi.getY(), LAMBERT_4_N, LAMBERT_4_C, LAMBERT_4_XS, LAMBERT_4_YS); }
java
public ProjectCalendar addDefaultBaseCalendar() { ProjectCalendar calendar = add(); calendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME); calendar.setWorkingDay(Day.SUNDAY, false); calendar.setWorkingDay(Day.MONDAY, true); calendar.setWorkingDay(Day.TUESDAY, true); calen...
java
public void marshall(RelationalDatabaseDataSourceConfig relationalDatabaseDataSourceConfig, ProtocolMarshaller protocolMarshaller) { if (relationalDatabaseDataSourceConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { proto...
java
public static String partiallyUnqualify(String name, String qualifierBase) { if (name == null || !name.startsWith(qualifierBase)) { return name; } return name.substring(qualifierBase.length() + 1); // +1 to start after the following '.' }
java
@Nonnull public static <IDTYPE extends Serializable> TypedObject <IDTYPE> create (@Nonnull final ObjectType aObjectType, @Nonnull final IDTYPE aID) { return new TypedObject <> (aObjectType, aID); }
java
private void processPropertyPlaceHolders() { Map<String, PropertyResourceConfigurer> prcs = applicationContext.getBeansOfType(PropertyResourceConfigurer.class); if (!prcs.isEmpty() && applicationContext instanceof ConfigurableApplicationContext) { BeanDefinition mapperScannerBean = ((Config...
java
@Override public void log(Exception e, Object... elements) { StringBuilder sb = buildMsg(Level.ERROR, elements); context.log(sb.toString(),e); }
python
def sample(self, bqm, beta_range=None, num_reads=10, num_sweeps=1000): """Sample from low-energy spin states using simulated annealing. Args: bqm (:obj:`.BinaryQuadraticModel`): Binary quadratic model to be sampled from. beta_range (tuple, optional): Beginning a...
java
protected void createClassProperties(HibernatePersistentEntity domainClass, PersistentClass persistentClass, InFlightMetadataCollector mappings, String sessionFactoryBeanName) { final List<PersistentProperty> persistentProperties = domainClass.getPersistentProperties();...
java
protected static MethodType replaceWithMoreSpecificType(Object[] args, MethodType callSiteType) { for (int i=0; i<args.length; i++) { // if argument null, take the static type if (args[i]==null) continue; if (callSiteType.parameterType(i).isPrimitive()) continue; ...
python
def _init_worker(X, X_shape, X_dtype): """Initializer for pool for _mprotate""" # Using a dictionary is not strictly necessary. You can also # use global variables. mprotate_dict["X"] = X mprotate_dict["X_shape"] = X_shape mprotate_dict["X_dtype"] = X_dtype
java
@JSFFaceletAttribute public String getFor() { TagAttribute forAttribute = getAttribute("for"); if (forAttribute == null) { return null; } else { return forAttribute.getValue(); } }
java
public static ArrayList<String> split(String source, String separator, boolean removeEmpty) { if (source == null || source.isEmpty()) return null; ArrayList<String> values = new ArrayList<String>(); if (separator == null || separator.isEmpty()) { values.add(source); ...
java
@Override public IRxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) { if (clazz.equals(ClientRxSession.class)) { ClientRxSessionDataReplicatedImpl data = new ClientRxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getC...
python
def patch_namespaced_service(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_service # noqa: E501 partially update the specified Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass as...
java
public boolean satisfies(String expr) { Parser<Expression> parser = ExpressionParser.newInstance(); return parser.parse(expr).interpret(this); }
java
public final Set<String> getBundleDependencies() { final Set<String> bundles = new TreeSet<>(); updateBundleList(bundles); return bundles; }
python
def boot(cls, *args, **kwargs): """ Function creates the instance of accessor with dynamic positional & keyword arguments. Args ---- args (positional arguments): the positional arguments that are passed to the class of accessor. kwargs (keyword ar...
java
public GetIntegrationResponseResult withResponseParameters(java.util.Map<String, String> responseParameters) { setResponseParameters(responseParameters); return this; }
java
@Override public Array getArray(int index) { synchronized (lock) { final Object obj = getMValue(internalArray, index).asNative(internalArray); return obj instanceof Array ? (Array) obj : null; } }
python
def table_lookup(image, table, border_value, iterations = None): '''Perform a morphological transform on an image, directed by its neighbors image - a binary image table - a 512-element table giving the transform of each pixel given the values of that pixel and its 8-connected neighbors. ...
python
def on_tape(*files): """Determine whether any of the given files are on tape Parameters ---------- *files : `str` one or more paths to GWF files Returns ------- True/False : `bool` `True` if any of the files are determined to be on tape, otherwise `False` """ ...
java
public Observable<OperationStatusResponseInner> beginRedeployAsync(String resourceGroupName, String vmName) { return beginRedeployWithServiceResponseAsync(resourceGroupName, vmName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override p...
java
public static List<CommercePriceList> findByCommerceCurrencyId( long commerceCurrencyId, int start, int end, OrderByComparator<CommercePriceList> orderByComparator) { return getPersistence() .findByCommerceCurrencyId(commerceCurrencyId, start, end, orderByComparator); }
java
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext) throws Exception { SslHandler sslHandler = null; try { sslHandler = newSslHandler(sslContext, ctx.alloc()); ctx.pipeline().replace(this, SslHandler.class.getName(), sslHandler); ...
java
public Object get(ManagedObject mo, String propName) { return get(mo.getMOR(), propName); }
python
def clean(self): """ Make sure there is at least a translation has been filled in. If a default language has been specified, make sure that it exists amongst translations. """ # First make sure the super's clean method is called upon. super(TranslationFormSet, se...
java
public static ChunkHeader read(IoBuffer in) { int remaining = in.remaining(); if (remaining > 0) { byte headerByte = in.get(); ChunkHeader h = new ChunkHeader(); // going to check highest 2 bits h.format = (byte) ((0b11000000 & headerByte) >> 6); ...
java
public void verify(String... filters) throws ManifestVerifyException { if (filters != null) { this.filters = Arrays.asList(filters); logFilters(); } verify(); }
python
def solve(self, value, filter_): """Returns the value of an attribute of the value, or the result of a call to a function. Arguments --------- value : ? A value to solve in combination with the given filter. filter_ : dataql.resource.Filter An instance of...
java
public static String toOriginal(Span span) { String id = span.getId(); if (span.clientSpan()) { int suffixIndex = id.lastIndexOf(CLIENT_ID_SUFFIX); if (suffixIndex > 0) { id = id.substring(0, suffixIndex); } } return id; }
python
def encodeCodon(seq_vec, ignore_stop_codons=True, maxlen=None, seq_align="start", encode_type="one_hot"): """Convert the Codon sequence into 1-hot-encoding numpy array # Arguments seq_vec: List of strings/DNA sequences ignore_stop_codons: boolean; if True, STOP_CODONS are omitted from one-hot e...
python
def get_instance_for_uuid(self, uuid, project_id): """Return instance name for given uuid of an instance and project. :uuid: Instance's UUID :project_id: UUID of project (tenant) """ instance_name = self._inst_info_cache.get((uuid, project_id)) if instance_name: ...
python
def validateNodeMsg(self, wrappedMsg): """ Validate another node's message sent to this node. :param wrappedMsg: Tuple of message and the name of the node that sent the message :return: Tuple of message from node and name of the node """ msg, frm = wrappedMsg ...
python
def add_view_info(self, view_info: ViewInfo): '''Adds view information to error message''' try: next(info for info in self._view_infos if info.view == view_info.view) except StopIteration: indent = len(self._view_infos) * '\t' self._view_infos.append(view_info...
java
public void encode(ByteBuf buf) { buf.writeByte('*'); CommandArgs.IntegerArgument.writeInteger(buf, 1 + (args != null ? args.count() : 0)); buf.writeBytes(CommandArgs.CRLF); CommandArgs.BytesArgument.writeBytes(buf, type.getBytes()); if (args != null) { args.encod...
python
def logging_syslog_server_syslogip(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-ras") syslog_server = ET.SubElement(logging, "syslog-server") use_vrf_key = ET.SubEl...
python
def size(self, fileToCheck, connId='default'): """ Checks size of a file on FTP server. Returns size of a file in bytes (integer). Parameters: - fileToCheck - file name or path to a file on FTP server - connId(optional) - connection identifier. By default equals 'default' ...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "origin") public JAXBElement<XMLGregorianCalendar> createOrigin(XMLGregorianCalendar value) { return new JAXBElement<XMLGregorianCalendar>(_Origin_QNAME, XMLGregorianCalendar.class, null, value); }
java
protected void configure(String[] args) throws IOException { for (String arg : args) { if (arg.startsWith("--input=")) { FileRef ref = createInput(); ref.setPath(arg.substring(arg.indexOf('=') + 1)); } else if (arg.startsWith("--output=")) { FileRef ref = createOutput(); ...
java
public void add(final int[] e) { if (size == list.length) list = Array.copyOf(list, newSize()); list[size++] = e; }
java
public void linkCallbacks(Object... callbackHandlers) { if (callbackHandlers != null) { for (TaskHandler proxyTask : new ArrayList<TaskHandler>(proxyTasks)) { proxyTask.clearCallbacks(); proxyTask.appendCallbacks(callbackHandlers); } } }
python
def _load(self, titles=[], descriptions=[], images=[], urls=[], **kwargs): """ Loads extracted data into Summary. Performs validation and filtering on-the-fly, and sets the non-plural fields to the best specific item so far. If GET_ALL_DATA is False, it gets only the first valid ...
java
public String getReadMethod() { StringBuffer sb = new StringBuffer(); if (getType().equals("boolean")) sb.append("is"); else sb.append("get"); sb.append(getAccessorName()); return sb.toString(); }
java
public SDVariable exponential(String name, double lambda, SDVariable shape) { validateInteger("exponential random", shape); SDVariable ret = f().randomExponential(lambda, shape); return updateVariableNameAndReference(ret, name); }
java
public Closure getClosure(String key) { if (closures != null && !closures.isEmpty()) { return closures.get(key); } return null; }
python
def cnst_A0T(self, Y0): r"""Compute :math:`A_0^T \mathbf{y}_0` component of :math:`A^T \mathbf{y}` (see :meth:`.ADMMTwoBlockCnstrnt.cnst_AT`). """ # This calculation involves non-negligible computational cost. It # should be possible to disable relevant diagnostic information ...
java
protected boolean hasTimeStampHeader() { String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS); boolean result = false; if(originTime != null) { try { // TODO: remove the originTime field from request header, // becaus...
java
public static boolean isClientAbortException(IOException e) { String exceptionClassName = e.getClass().getName(); return exceptionClassName.endsWith(".EofException") || exceptionClassName.endsWith(".ClientAbortException"); }
java
public final ListInstancesPagedResponse listInstances(ProjectName parent) { ListInstancesRequest request = ListInstancesRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listInstances(request); }
python
def clip_action(action, space): """Called to clip actions to the specified range of this policy. Arguments: action: Single action. space: Action space the actions should be present in. Returns: Clipped batch of actions. """ if isinstance(space, gym.spaces.Box): ret...
java
public long removeAll(final String... members) { return doWithJedis(new JedisCallable<Long>() { @Override public Long call(Jedis jedis) { return jedis.srem(getKey(), members); } }); }
java
@SuppressWarnings("unchecked") public static ConnectionObserver childConnectionObserver(ServerBootstrap b) { Objects.requireNonNull(b, "bootstrap"); ConnectionObserver obs = (ConnectionObserver) b.config() .childOptions() ...
java
private boolean checkInetAddress(InetAddress inetAddress) { // Check if not local host if (! inetAddress.getCanonicalHostName().startsWith("local")) { // Check if name is not the address (???) if (!inetAddress.getCanonicalHostName().equalsIgnoreCase(inetAddress.getHostAddress(...
java
@Override public CreateNotificationResult createNotification(CreateNotificationRequest request) { request = beforeClientExecution(request); return executeCreateNotification(request); }
java
public Type unboxedType(Type t) { for (int i=0; i<syms.boxedName.length; i++) { Name box = syms.boxedName[i]; if (box != null && asSuper(t, syms.enterClass(syms.java_base, box)) != null) return syms.typeOfTag[i]; } return Type.noType; }
python
def setitem(self, indexer, value): """Set the value inplace, returning a a maybe different typed block. Parameters ---------- indexer : tuple, list-like, array-like, slice The subset of self.values to set value : object The value being set Return...
python
def get_sonos_favorites(self, start=0, max_items=100): """Get Sonos favorites. See :meth:`get_favorite_radio_shows` for return type and remarks. """ message = 'The output type of this method will probably change in '\ 'the future to use SoCo data structures' wa...
python
def annotate(self, fname, tables, feature_strand=False, in_memory=False, header=None, out=sys.stdout, parallel=False): """ annotate a file with a number of tables Parameters ---------- fname : str or file file name or file-handle tables : list ...
java
private void processOverReplicatedBlock(Block block, short replication, DatanodeDescriptor addedNode, DatanodeDescriptor delNodeHint) { List<DatanodeID> excessReplicateTmp = new ArrayList<DatanodeID>(); List<DatanodeID> originalDatanodes = new ArrayList<DatanodeID>(); ...
java
protected void processHookFinally(ActionHook hook) { if (hook == null) { return; } showFinally(runtime); try { hook.hookFinally(runtime); } finally { hook.godHandEpilogue(runtime); } }
python
def retrieveVals(self): """Retrieve values for graphs.""" apcinfo = APCinfo(self._host, self._port, self._user, self._password, self._monpath, self._ssl, self._extras) stats = apcinfo.getAllStats() if self.hasGraph('php_apc_memory') and stats: ...
python
def get_string_from_view(self, request, view_name, url_kwargs, render_type='string'): """ Returns a string that is a rendering of the view given a request, view_name, and the original url_kwargs. Makes the following changes the view before...
java
public JSONObject getJson() throws JSONException { JSONObject json = create(); if (getDescription() != null && !getDescription().isEmpty()) json.put("description", getDescription()); if (attributes != null && !attributes.isEmpty()) { json.put("attributes", Attribute.getAttr...
python
def render(self, element): """Renders the given element to string. :param element: a element to be rendered. :returns: the output string or any values. """ # Store the root node to provide some context to render functions if not self.root_node: self.root_node...
python
def evaluate_course(self, kcdm, jxbh, r101=1, r102=1, r103=1, r104=1, r105=1, r106=1, r107=1, r108=1, r109=1, r201=3, r202=3, advice=''): """ 课程评价, 数值为 1-5, r1 类选项 1 为最好, 5 为最差, r2 类选项程度由深到浅, 3 为最好. 默认都是最好的选项 :param kcdm: 课程代码 :pa...
python
def get_infos_with_id(self, uid): """Get info about a user based on his id. :return: JSON """ _logid = uid _user_info_url = USER_INFO_URL.format(logid=_logid) return self._request_api(url=_user_info_url).json()
java
protected void addModulePackagesList(Map<ModuleElement, Set<PackageElement>> modules, String text, String tableSummary, Content body, ModuleElement mdle) { Content profNameContent = new StringContent(mdle.getQualifiedName().toString()); Content heading = HtmlTree.HEADING(HtmlConstants.PACKAG...
python
def connectDropzone( self, rect, slot, color = None, style = None, name = '', toolTip = '' ): """ Connects the inputed dropzone to the given slot at t...
java
private void buildNewInstanceMethodForBuilder( MethodSpec.Builder newInstanceMethodBuilder ) { newInstanceMethodBuilder.addStatement( "return new $T(builderDeserializer.deserializeInline(reader, ctx, params, null, null, null, bufferedProperties).build(), bufferedProperties)", parameterizedName( ...
java
private void sortList(ArrayList candidateList) { java.util.Collections.sort(candidateList, new java.util.Comparator() { public int compare(Object o1, Object o2) { double scoreT = ( (TagLink.Candidates) o1).getScore(); double scoreU = ( (TagLink.Candidates) o2).getScore(); if(score...
python
def display_output(arguments): '''Display the ASCII art from the image.''' global _ASCII if arguments['--alt-chars']: _ASCII=_ASCII_2 try: im = Image.open(arguments['FILE']) except: raise IOError('Unable to open the file.') im = im.convert("RGBA") aspect_ratio = fl...
python
def is_valid(self): """ Only retain SNPs or single indels, and are bi-allelic """ return len(self.ref) == 1 and \ len(self.alt) == 1 and \ len(self.alt[0]) == 1
java
public static void setMultiSelectEditorValue( CmsObject cms, Map<String, String[]> formParameters, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) { String[] values = formParameters.get(param.getId()); if ((values != null) && (values.length > 0)) { ...
java
@Override protected Connection proxyConnection(Connection target, ConnectionCallback callback) { return new ConnectionDecorator(target, callback); }
java
private WebSocketMessage<?> receive(WebSocketEndpointConfiguration config, long timeout) { long timeLeft = timeout; WebSocketMessage<?> message = config.getHandler().getMessage(); String path = endpointConfiguration.getEndpointUri(); while (message == null && timeLeft > 0) { ...
java
protected void setBeanPropertyValue(final String property, final Object bean, final Serializable value) { if (bean == null) { return; } if (".".equals(property)) { LOG.error("Set of entire bean is not supported by this model"); return; } try { PropertyUtils.setProperty(bean, property, value); ...
python
def update(self, arr, mask=None): """ update moving average (and variance) with new ndarray (of the same shape as the init array) and an optional mask """ if mask is not None: refI = np.logical_and(mask, self.n == 0) else: refI = self.n == 0 ...
java
public byte[] unwrap(byte []inBuf, int off, int len, MessageProp prop) throws GSSException { checkContext(); logger.debug("enter unwrap"); byte [] token = null; /* * see if the token is a straight SSL packet or * one of ours made by wrap using get_mic ...
java
@Nonnull @ReturnsMutableCopy public ICommonsList <CSSViewportRule> getAllViewportRules () { return m_aRules.getAllMapped (r -> r instanceof CSSViewportRule, r -> (CSSViewportRule) r); }
java
@Nonnull public FineUploader5Session addParam (@Nonnull @Nonempty final String sKey, @Nonnull final String sValue) { ValueEnforcer.notEmpty (sKey, "Key"); ValueEnforcer.notNull (sValue, "Value"); m_aSessionParams.put (sKey, sValue); return this; }
python
def update(self, new_games): """ new_games is a list of .tfrecord.zz new game records. """ new_games.sort(key=os.path.basename) first_new_game = None for idx, game in enumerate(new_games): timestamp = file_timestamp(game) if timestamp <= self.examples[-1][0]: ...