language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static void sendBlockData(Chunk chunk, String identifier, ByteBuf data, EntityPlayerMP player) { MalisisCore.network.sendTo(new Packet(chunk, identifier, data), player); }
java
@Override public double membership(double x) { if (Double.isNaN(x)) { return Double.NaN; } if (xy.isEmpty()) { throw new RuntimeException("[discrete error] term is empty"); } // ______________________ // / ...
java
public static void writeModel(@NonNull Model model, @NonNull OutputStream stream, boolean saveUpdater) throws IOException { writeModel(model,stream,saveUpdater,null); }
java
@Override public String sendLMS(String CorpNum, String sender, String subject, String content, Message[] Messages, Date reserveDT, Boolean adsYN, String UserID) throws PopbillException { return sendMessage(MessageType.LMS, CorpNum, sender, null, subject, content, ...
java
public static WaveletTransform<GrayF32, GrayF32,WlCoef_F32> create_F32( WaveletDescription<WlCoef_F32> waveletDesc , int numLevels, float minPixelValue , float maxPixelValue ) { return new WaveletTransformFloat32(waveletDesc,numLevels,minPixelValue,maxPixelValue); }
python
def build_on_condition(self, runnable, regime, on_condition): """ Build OnCondition event handler code. @param on_condition: OnCondition event handler object @type on_condition: lems.model.dynamics.OnCondition @return: Generated OnCondition code @rtype: list(string) ...
python
def put(self, robj, w=None, dw=None, pw=None, return_body=None, if_none_match=None, timeout=None): """ Stores an object. """ raise NotImplementedError
java
public synchronized void shutdown() { if (!isActive) { return; } log.info("Shutting down the default async job executor [{}].", getClass().getName()); if (timerJobRunnable != null) { timerJobRunnable.stop(); } if (asyncJobsDueRunnable != null) { asyncJobsDueRunnable.stop()...
java
public static <T> Collector<T, ?, Double> averagingLong(ToLongFunction<? super T> mapper) { return new CollectorImpl<>( () -> new long[2], (a, t) -> { a[0] += mapper.applyAsLong(t); a[1]++; }, (a, b) -> { a[0] += b[0]; a[1] += b[1]; return a; }, ...
python
def url_join(base, url, allow_fragments=True): """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter. :param base: the base URL for the join operation. :param url: the URL to join. :param allow_fragments: indicates whether fragments should be allowed. "...
java
public static String printNode(Node node, boolean prettyprint) { StringWriter strw = new StringWriter(); new DOMWriter(strw).setPrettyprint(prettyprint).print(node); return strw.toString(); }
java
static String parsePrefix(String key) { if (key == null) return null; boolean inquotes = false; for (int i = 0; i < key.length(); i++) { char c = key.charAt(i); if (c == '"') { inquotes = !inquotes; } else if ((c == '[' || c == '...
python
def build_wsgi_environ_from_event(event): """Create a WSGI environment from the proxy integration event.""" params = event.get('queryStringParameters') environ = EnvironBuilder(method=event.get('httpMethod') or 'GET', path=event.get('path') or '/', h...
java
public void setIncludes(String includes) { // Split the string into separate file globs. String[] globs = includes.split("[\\s,]+"); // Loop over these globs and create dirsets from them. // Do not set the root directory until the task is // executed. for (String glob :...
java
public final <T> List<T> loadAllObjects(final Class<T> clazz) throws Exception { final Entity entityAnnotation = clazz.getAnnotation(Entity.class); if(entityAnnotation == null){ throw new IllegalArgumentException("Unknown entity: " + clazz.getName()); } return execut...
java
public StreamRecord withKeys(java.util.Map<String, AttributeValue> keys) { setKeys(keys); return this; }
python
def state_transition(history_id_key, table_name, always_set=[], may_spend_tokens=False): """ Decorator for the check() method on state-transition operations. Make sure that: * there is a __table__ field set, which names the table in which this record is stored. * there is a __history_id_key__ field ...
java
public static Object spawn(Context cx, Scriptable thisObj, Object[] args, Function funObj) { Scriptable scope = funObj.getParentScope(); Runner runner; if (args.length != 0 && args[0] instanceof Function) { Object[] newArgs = null; if (a...
java
@Override protected CBORObject EncodeCBORObject() throws CoseException { if (rgbSignature == null) throw new CoseException("sign function not called"); if (rgbProtected == null) throw new CoseException("Internal Error"); CBORObject obj = CBORObject.NewArray(); obj.Add(rgbPro...
python
def mktmp(self): """ Make the I{location} directory if it doesn't already exits. """ try: if not os.path.isdir(self.location): os.makedirs(self.location) except: log.debug(self.location, exc_info=1) return self
java
public void appendHitRange(int start, int end) { hits.add(new Range(start, end)); ranges = null;//キャッシュをクリア }
java
public Observable<Page<CloudJobSchedule>> listNextAsync(final String nextPageLink, final JobScheduleListNextOptions jobScheduleListNextOptions) { return listNextWithServiceResponseAsync(nextPageLink, jobScheduleListNextOptions) .map(new Func1<ServiceResponseWithHeaders<Page<CloudJobSchedule>, JobSch...
java
@Override public PlanExprCol as(PlanColumn column, ServerExpression expression) { return new ExprColCallImpl("op", "as", new Object[]{ column, expression }); }
java
public void initRemoteSkel(ObjectInputStream daIn) { try { int iTypeField = daIn.readInt(); String typeFieldName = daIn.readUTF(); int iTargetValue = daIn.readInt(); this.init(iTypeField, typeFieldName, iTargetValue); } catch (IOException ex...
python
def fetchGroupInfo(self, *group_ids): """ Get groups' info from IDs, unordered :param group_ids: One or more group ID(s) to query :return: :class:`models.Group` objects, labeled by their ID :rtype: dict :raises: FBchatException if request failed """ threa...
python
def save_log_entry(self, log_entry_form, *args, **kwargs): """Pass through to provider LogEntryAdminSession.update_log_entry""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if log_entry_form.is_for_update(): return self.update...
java
private void storeRecentList() { synchronized (recent) { try { OutputStream out = new BufferedOutputStream(new FileOutputStream(RECENT_FILE_NAME)); XMLEncoder encoder = new XMLEncoder(out); encoder.writeObject(recent); encoder.close(); } catch (IOException ex) { LogFactory.getLog(getClass())...
java
public void setText (String text) { if (content instanceof VisLabel) { ((VisLabel) content).setText(text); } else { setContent(new VisLabel(text)); } pack(); }
java
@Pure public int getPointCountInGroup(int groupIndex) { if (groupIndex == 0 && this.pointCoordinates == null) { return 0; } final int firstInGroup = firstInGroup(groupIndex); final int lastInGroup = lastInGroup(groupIndex); return (lastInGroup - firstInGroup) / 2 + 1; }
java
public void combine(SpdLoad other) { if (other == null) return; if (stat.isEnabled() && other.isEnabled()) //stat.combine((BoundedRangeStatisticImpl)other.getStatistic()); stat.combine(other.getStatistic()); }
java
public ArrayList<String> email_pro_service_account_GET(String service, Long number) throws IOException { String qPath = "/order/email/pro/{service}/account"; StringBuilder sb = path(qPath, service); query(sb, "number", number); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1);...
python
def ascii_host(self): """Works exactly like :attr:`host` but will return a result that is restricted to ASCII. If it finds a netloc that is not ASCII it will attempt to idna decode it. This is useful for socket operations when the URL might include internationalized characters. ...
java
@SuppressWarnings("unchecked") private Segment<K,V> segmentForHash(int h) { long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE; return (Segment<K,V>) UNSAFE.getObjectVolatile(segments, u); }
python
def is_directed(self): r"""Check if the graph has directed edges (cached). In this framework, we consider that a graph is directed if and only if its weight matrix is not symmetric. Returns ------- directed : bool True if the graph is directed, False otherwi...
python
def createDeviceObjects(self, interface_id): """Transform the raw device descriptions into instances of devicetypes.generic.HMDevice or availabe subclass.""" global WORKING WORKING = True remote = interface_id.split('-')[-1] LOG.debug( "RPCFunctions.createDeviceObject...
java
public static Properties getSecurityProperties(final String file, final String psw, final String alias) { val p = new Properties(); p.put("org.apache.ws.security.crypto.provider", "org.apache.ws.security.components.crypto.Merlin"); p.put("org.apache.ws.security.crypto.merlin.keystore.type", "jks...
python
def CaptureNamedVariable(self, name, value, depth, limits): """Appends name to the product of CaptureVariable. Args: name: name of the variable. value: data to capture depth: nested depth of dictionaries and vectors so far. limits: Per-object limits for capturing variable data. Ret...
python
def convert(self, json="", table_attributes='border="1"', clubbing=True, encode=False, escape=True): """ Convert JSON to HTML Table format """ # table attributes such as class, id, data-attr-*, etc. # eg: table_attributes = 'class = "table table-bordered sortable"' se...
java
@NonNull Completable overwriteUsingDiffUtil(@NonNull final List<? extends T> newContents, @NonNull final EqualityFunction<? super T> identityEqualityFunction, @NonNull final EqualityFunction<? super T> contentEqualityFunction) { ...
java
public static PolicyConfigurationFactory getPolicyConfigurationFactory() throws ClassNotFoundException, PolicyContextException { // Validate the caller permission SecurityManager sm = System.getSecurityManager(); if (sm != null) sm.checkPermission(new SecurityPermission("setPolicy...
java
public BooleanTerm resolveWith(Features features, boolean coerceUndefinedToFalse) { if (isEmpty()) { return this; } Set<BooleanVar> term = new HashSet<BooleanVar>(); for (BooleanVar var : this) { if (features.contains(var.name) || coerceUndefinedToFalse) { boolean featureState = features.isFeat...
java
CloseableIterator<T> createIterator(PreparedQuery<T> preparedQuery, int resultFlags) throws SQLException { try { SelectIterator<T, ID> iterator = statementExecutor.buildIterator(this, connectionSource, preparedQuery, objectCache, resultFlags); return iterator; } catch (SQLException e) { throw SqlExcep...
java
public Frame<V> init(final Frame<? extends V> src) { returnValue = src.returnValue; System.arraycopy(src.values, 0, values, 0, values.length); top = src.top; return this; }
python
def _checkMetadata(self, variantFile): """ Checks that metadata is consistent """ metadata = self._getMetadataFromVcf(variantFile) if self._metadata is not None and self._metadata != metadata: raise exceptions.InconsistentMetaDataException( variantFile...
python
def destroy(self, request, *args, **kwargs): """Destroy a model instance. If ``delete_content`` flag is set in query parameters, also all Data objects contained in entity will be deleted. """ obj = self.get_object() user = request.user if strtobool(request.query...
java
public Warning createWarning(final String fileName, final int start, final String category, final String message) { return new Warning(fileName, start, getGroup(), category, message); }
java
@SuppressWarnings("PMD.EmptyCatchBlock") public static void sendResponse(HttpRequest request, IOSubchannel channel, int statusCode, String reasonPhrase) { HttpResponse response = request.response().get(); response.setStatusCode(statusCode).setReasonPhrase(reasonPhrase) .setHa...
java
@Override public com.flickr4java.flickr.Response postMultiPart(String path, UploadMetaData metaData, Payload payload, String apiKey, String sharedSecret) throws FlickrException { OAuthRequest request = new OAuthRequest(Verb.POST, buildUrl(path)); Map<String, String> uploadParameters = new HashMap<>...
python
def _check(self, calc_dict, changes=None): ''' cplan._check(calc_dict) should be called only by the calc_dict object itself. The check method makes sure that all of the proactive methods on the calc_dict are run; if the optional keyword argument changes is given, then checks are only run...
python
def dump_data(logdir): """Dumps plugin data to the log directory.""" # Create a tfevents file in the logdir so it is detected as a run. write_empty_event_file(logdir) plugin_logdir = plugin_asset_util.PluginDirectory( logdir, profile_plugin.ProfilePlugin.plugin_name) _maybe_create_directory(plugin_logd...
java
@Override public ListEnvironmentsResult listEnvironments(ListEnvironmentsRequest request) { request = beforeClientExecution(request); return executeListEnvironments(request); }
java
@Override public long getCountHighWaterMark() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getCountHighWaterMark"); long destHigh = _destHighMsgs + getSubscriberCount(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) ...
java
public <Type extends DataSet> OnLineStatistics[] evaluateFeatureImportance(DataSet<Type> data) { if(data instanceof ClassificationDataSet) return evaluateFeatureImportance(data, new MDI(ImpurityScore.ImpurityMeasure.GINI)); else return evaluateFeatureImportance(data, new Impo...
python
def p_parameter(p): '''parameter : VARIABLE | class_name VARIABLE | ARRAY VARIABLE | AND VARIABLE | class_name AND VARIABLE | ARRAY AND VARIABLE | VARIABLE EQUALS static_scalar | class_name VARIABL...
java
public Map<Integer, List<HeronTuples.HeronTupleSet>> getCache() { Map<Integer, List<HeronTuples.HeronTupleSet>> res = new HashMap<>(); for (Map.Entry<Integer, TupleList> entry : cache.entrySet()) { res.put(entry.getKey(), entry.getValue().getTuplesList()); } return res; }
python
def get_all_objects(self): "Return pointers to all GC tracked objects" for i, generation in enumerate(self.gc_generations): generation_head_ptr = pygc_head_ptr = generation.head.get_pointer() generation_head_addr = generation_head_ptr._value while True: ...
java
private Object processPropertyValue(Entity entity, String propName, final String dataType, final String syntax, Object ldapValue) throws WIMException { if (DATA_TYPE_STRING.equals(dataType)) { boolean octet = LDAP_ATTR_SYNTAX_OCTETSTRING.equalsIgnoreCase(syntax); return getString(octet, ...
python
def _acceptance_prob(self, position, position_bar, momentum, momentum_bar): """ Returns the acceptance probability for given new position(position) and momentum """ # Parameters to help in evaluating Joint distribution P(position, momentum) _, logp = self.grad_log_pdf(position, ...
java
private UploadedMedia uploadMediaChunkedInit(long size) throws TwitterException { return new UploadedMedia(post( conf.getUploadBaseURL() + "media/upload.json", new HttpParameter[] { new HttpParameter("command", CHUNKED_INIT), new HttpParameter("media_type", "video/mp4"), new HttpParameter("media_...
python
def cores(self): """ The number of CPU cores required. """ if self._cores is not None: return self._cores elif self._config is not None: return self._config.defaultCores else: raise AttributeError("Default value for 'cores' cannot be de...
python
def _glob_pjoin(*parts): """Join paths for glob processing""" if parts[0] in ('.', ''): parts = parts[1:] return pjoin(*parts).replace(os.sep, '/')
java
private static BigDecimal doAdd(final BigDecimal v1, final BigDecimal v2) { BigDecimal total = v1; if (v1 != null && v2 != null) { total = v1.add(v2); } else if (v2 != null) { total = v2; } return total; }
java
public boolean check(String value, String hashString) { return update(value.getBytes()).asString().equalsIgnoreCase(hashString); }
python
def find_urls(self, text, only_unique=False): """ Find all URLs in given text. :param str text: text where we want to find URLs :param bool only_unique: return only unique URLs :return: list of URLs found in text :rtype: list """ urls = self.gen_urls(text...
java
public static appfwhtmlerrorpage get(nitro_service service, options option) throws Exception{ appfwhtmlerrorpage obj = new appfwhtmlerrorpage(); appfwhtmlerrorpage[] response = (appfwhtmlerrorpage[])obj.get_resources(service,option); return response[0]; }
python
def _edges_intersect(self, edge1, edge2): """ Return 1 if edges intersect completely (endpoints excluded) """ h12 = self._intersect_edge_arrays(self.pts[np.array(edge1)], self.pts[np.array(edge2)]) h21 = self._intersect_edge_arrays(self....
java
public static CmsListOrderEnum valueOf(String value) throws CmsIllegalArgumentException { Iterator<CmsListOrderEnum> iter = VALUES.iterator(); while (iter.hasNext()) { CmsListOrderEnum target = iter.next(); if (value.equals(target.getOrder())) { return target; ...
python
def concat(cls, iterables): """ Similar to #itertools.chain.from_iterable(). """ def generator(): for it in iterables: for element in it: yield element return cls(generator())
java
public void setNetworkProtocol(java.util.Collection<StringFilter> networkProtocol) { if (networkProtocol == null) { this.networkProtocol = null; return; } this.networkProtocol = new java.util.ArrayList<StringFilter>(networkProtocol); }
python
def _default_warning_handler(library_msg, _): """Default warning handler callback.""" library_msg = library_msg.decode('utf-8').rstrip() msg = "OpenJPEG library warning: {0}".format(library_msg) warnings.warn(msg, UserWarning)
python
def check_is_uuid(self, uuid_str: str): """Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check """ # check uuid type if not isinstance(uuid_str, str): raise TypeError("'uuid_str' expected a str value.") else: ...
python
def delete(gandi, fqdn, name, type, force): """Delete record entry for a domain.""" domains = gandi.dns.list() domains = [domain['fqdn'] for domain in domains] if fqdn not in domains: gandi.echo('Sorry domain %s does not exist' % fqdn) gandi.echo('Please use one of the following: %s' % '...
java
public boolean isEdge(final ODocument iRecord) { return iRecord != null ? iRecord.getSchemaClass().isSubClassOf(edgeBaseClass) : false; }
java
@GwtIncompatible("Array.newInstance(Class, int)") public static <T> T[] toArray(Iterable<? extends T> iterable, Class<T> type) { Collection<? extends T> collection = toCollection(iterable); T[] array = ObjectArrays.newArray(type, collection.size()); return collection.toArray(array); }
java
@Override public XExpression getArgument(int idx) { int fixedIdx = idx - receiverFixup; if (fixedIdx < 0) { return null; } return internalGetArgument(fixedIdx); }
java
private <TResponse> TResponse callServiceOwnerGetApi( String path, Map<String, String> queryParams, Class<TResponse> responseClass) throws AuthleteApiException { return callGetApi(mServiceOwnerCredentials, path, queryParams, responseClass); }
java
public static void step(final String name, final ThrowableRunnableVoid runnable) { step(name, () -> { runnable.run(); return null; }); }
java
@Override public void failExternally(Throwable cause) { LOG.info("Attempting to fail task externally {} ({}).", taskNameWithSubtask, executionId); cancelOrFailAndCancelInvokable(ExecutionState.FAILED, cause); }
java
public Elements wrap(String html) { Validate.notEmpty(html); for (Element element : this) { element.wrap(html); } return this; }
python
def _get_add_trustee_cmd(self, trustee): '''Get tmsh command to add a trusted device. :param trustee: ManagementRoot object -- device to add as trusted :returns: str -- tmsh command to add trustee ''' trustee_info = pollster(get_device_info)(trustee) username = trustee....
java
public JsHandlerRegistration addGeometryIndexHighlightBeginHandler(final GeometryIndexHighlightBeginHandler h) { org.geomajas.plugin.editing.client.event.state.GeometryIndexHighlightBeginHandler h2; h2 = new org.geomajas.plugin.editing.client.event.state.GeometryIndexHighlightBeginHandler() { public void onGeom...
python
def get_random_str(length, letters=True, digits=False, punctuation=False): """ 获得指定长度,不同规则的随机字符串,可以包含数字,字母和标点符号 :param: * length: (int) 随机字符串的长度 * letters: (bool) 随机字符串是否包含字母,默认包含 * digits: (bool) 随机字符串是否包含数字,默认不包含 * punctuation: (bool) 随机字符串是否包含特殊标点符号,默认不包含 :return: ...
python
def _process_loop(self): '''Fetch URL including redirects. Coroutine. ''' while not self._web_client_session.done(): self._item_session.request = self._web_client_session.next_request() verdict, reason = self._should_fetch_reason() _logger.debug('Fi...
java
public void free() { if (m_recordOwnerCollection != null) m_recordOwnerCollection.free(); m_recordOwnerCollection = null; if (m_messageFilterList != null) m_messageFilterList.free(); m_messageFilterList = null; // Close all records associated with this SessionObje...
java
public Object read(final InputSource in) throws SAXException, IOException { if ( this.docFragment == null ) { DocumentBuilderFactory f; try { f = DocumentBuilderFactory.newInstance(); } catch ( FactoryConfigurationE...
python
def process(self): """ Receive data from socket and process request """ response = None try: payload = self.receive() method, args, ref = self.parse(payload) response = self.execute(method, args, ref) except AuthenticateError as exception: ...
java
public synchronized int getReceivedDataSegmentType() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "getReceivedDataSegmentType"); checkReleased(); int segmentType = -1; if (receivedData != null) { segmentType = receivedData.getSegmentType(...
python
def read_message( self, callback: Callable[["Future[Union[None, str, bytes]]"], None] = None ) -> Awaitable[Union[None, str, bytes]]: """Reads a message from the WebSocket server. If on_message_callback was specified at WebSocket initialization, this function will never return messa...
python
def get_gallery_file(self, file_id, output_file_path=None, scope='content/read'): """ Get a file in the Mxit user's gallery User authentication required with the following scope: 'content/read' """ data = _get( token=self.oauth.get_user_token(scope), uri='...
python
def show_in_external_file_explorer(fnames=None): """Show files in external file explorer Args: fnames (list): Names of files to show. """ if not isinstance(fnames, (tuple, list)): fnames = [fnames] for fname in fnames: open_file_in_external_explorer(fname)
python
def host_in_set (ip, hosts, nets): """ Return True if given ip is in host or network list. """ if ip in hosts: return True if is_valid_ipv4(ip): n = dq2num(ip) for net in nets: if dq_in_net(n, net): return True return False
python
def pairwise_permutations(i, j): '''Return all permutations of a set of groups This routine takes two vectors: i - the label of each group j - the members of the group. For instance, take a set of two groups with several members each: i | j ------ 1 | 1 1 | 2 1 | 3...
java
public void encode(AsnOutputStream aos) throws EncodeException { if (this.getProblem() == null) throw new EncodeException("Error encoding Reject: RejectProblem must not be null"); try { // tag aos.writeTag(Tag.CLASS_PRIVATE, false, Reject._TAG_REJECT); i...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case BpsimPackage.ELEMENT_PARAMETERS__TIME_PARAMETERS: return timeParameters != null; case BpsimPackage.ELEMENT_PARAMETERS__CONTROL_PARAMETERS: return controlParameters != null; case BpsimPackage.ELEMENT_PARAMETERS__RESOURCE_PARAM...
python
def LDA_discriminants(x, labels): """ Linear Discriminant Analysis helper for determination how many columns of data should be reduced. **Args:** * `x` : input matrix (2d array), every row represents new sample * `labels` : list of labels (iterable), every item should be label for \ s...
java
public boolean setAuthenticationMethod(int methodId, Authentication method) { if (methodId < 0 || methodId > 255) return false; if (method == null) { // Want to remove a particular method return (authMethods.remove(new Integer(methodId)) != null); } else {// Add the method, or rewrite old one authMeth...
python
def _cached_search_compile(pattern, re_verbose, re_version, pattern_type): """Cached search compile.""" return _bre_parse._SearchParser(pattern, re_verbose, re_version).parse()
python
def match(self, subj=None, pred=None, obj=None, attrs=None): ''' Retrieve an iterator of relationship IDs that match a pattern of components subj - optional subject or origin of the relationship, an IRI coded as a unicode object. If omitted any subject will be matched. pred - optional p...
python
def get(binary_name): """return a valid path to the given binary. Return an error if no existing binary can be found. Parameters ---------- binary_name: string a binary name used as a key in the 'binaries' dictionary above Return ------ string full path to binary ""...
python
def sortByColumn(self, index, direction): """ Sorts the data for this widget based on the inputed index & direction. :param index | <int> direction | <Qt.SortOrder """ if self.isPaged() and not self.isFullyLoaded(): self.reord...