language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
AtomSymbol generatePeriodicSymbol(final int number, final int hydrogens, final int mass, final int charge, final int unpaired, HydrogenPosition position) { TextOutline element = number == 0 ? new TextOutline("*", font) : new TextOu...
java
protected List<TokenList.Token> parseParameterCommaBlock( TokenList tokens, Sequence sequence ) { // find all the comma tokens List<TokenList.Token> commas = new ArrayList<TokenList.Token>(); TokenList.Token token = tokens.first; int numBracket = 0; while( token != null ) { ...
java
public NamedQuery<Entity<T>> getOrCreateNamedQuery() { List<Node> nodeList = childNode.get("named-query"); if (nodeList != null && nodeList.size() > 0) { return new NamedQueryImpl<Entity<T>>(this, "named-query", childNode, nodeList.get(0)); } return createNamedQuery(); }
python
def get_vr(self, epoch=None): """get VR string from .spec Version, Release and Epoch epoch is None: prefix epoch if present (default) epoch is True: prefix epoch even if not present (0:) epoch is False: omit epoch even if present """ version = self.get_tag('Version', exp...
python
def _load_models(self) -> None: """Maybe load all the models to be assembled together and save them to the ``self._models`` attribute.""" if self._models is None: logging.info('Loading %d models', len(self._model_paths)) def load_model(model_path: str): logging.d...
python
def callback(self, provider): """ Handles 3rd party callback and processes it's data """ provider = self.get_provider(provider) try: return provider.authorized_handler(self.login)(provider=provider) except OAuthException as ex: logging.error("Data:...
java
public synchronized boolean isLoaded(LCMSDataSubset subset) { for (Map.Entry<Object, Set<LCMSDataSubset>> entry : cache.asMap().entrySet()) { Object user = entry.getKey(); if (user == null) { // it has already been reclaimed, move on // this condition should not be triggered though, bec...
java
public static boolean isEmbedded(String driverClassName) { return databases .stream() .filter(JdbcDatabase::isEmbedded) .anyMatch(db -> db.driverClassName.equals(driverClassName)); }
java
public ListDomainAppResponse listDomainApp(ListDomainAppRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getPlayDomain(), "playDomain should NOT be empty."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, ...
java
public final Tuple7<T9, T10, T11, T12, T13, T14, T15> skip8() { return new Tuple7<>(v9, v10, v11, v12, v13, v14, v15); }
java
@SuppressWarnings("unchecked") public static <T> T[] newArrayInstance(Class<T> baseClass, int length) { return (T[]) Array.newInstance(baseClass, length); }
java
public static RgbaColor fromHsl(String hsl) { String[] parts = getHslParts(hsl).split(","); if (parts.length == 3) { float[] HSL = new float[] { parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2]) }; return fromHsl(HSL); } else { return getDefau...
java
public static Long getCurrentNid() { Node node = ArbitrateConfigRegistry.getConfig().currentNode(); if (node != null) { return node.getId(); } else { return null; } }
java
private void maybeUpdateScrollbars() { if (!isAttached()) { return; } /* * Measure the height and width of the content directly. Note that measuring * the height and width of the container element (which should be the same) * doesn't work correct...
python
def put_multipart(self, local_path, destination_s3_path, part_size=DEFAULT_PART_SIZE, **kwargs): """ Put an object stored locally to an S3 path using S3 multi-part upload (for files > 8Mb). :param local_path: Path to source local file :param destination_s3_path: URL for target S3...
python
def rdtxt_gos(go_file, prt): """Read GO IDs from a file.""" goids_all = set() if not os.path.exists(go_file): raise RuntimeError("CAN NOT READ GO FILE: {FILE}\n".format(FILE=go_file)) re_go = re.compile(r'(GO:\d{7})+?') re_com = re.compile(r'^\s*#') # Lines starting ...
java
private RdfStream getResourceTriples(final int limit, final FedoraResource resource) { final PreferTag returnPreference; if (prefer != null && prefer.hasReturn()) { returnPreference = prefer.getReturn(); } else if (prefer != null && prefer.hasHandling()) { returnPrefere...
java
@Override public ByteBuffer getBuffer() { // If we are expected to read large message, we'll opt for zero- // copy, i.e. we'll ask caller to fill the data directly to the // message. Note that subsequent read(s) are non-blocking, thus // each single read reads at most SO_RCVB...
java
public BigDecimal toBigDecimal() { StringBuilder sb = new StringBuilder(); this.createNumber(sb); return new BigDecimal(sb.toString()); }
python
def preserve_sig(wrapper, orig_func, force=False): """ Decorates a wrapper function. It seems impossible to presever signatures in python 2 without eval (Maybe another option is to write to a temporary module?) Args: wrapper: the function wrapping orig_func to change the signature of ...
python
def trial(request): """View for a single trial.""" job_id = request.GET.get("job_id") trial_id = request.GET.get("trial_id") recent_trials = TrialRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time") recent_results = ResultRecord.objects \ .filter(trial_id=trial_...
python
def flatten_zip_dataset(*args): """A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` dif...
java
public Object readValue(InputStream is, Class<Object> clazz) { try { return this.mapper.readValue(is, clazz); } catch (Exception e) { LogFactory.getLog(JsonHandler.class).info("deserialize json to object", e); return null; } }
python
def next_row(self): """Move to next row from currently selected row.""" row = self.currentIndex().row() rows = self.source_model.rowCount() if row + 1 == rows: row = -1 self.selectRow(row + 1)
java
public Object accept(QueryNodeVisitor visitor, Object data) throws RepositoryException { return visitor.visit(this, data); }
python
def kpl_status(self, address, group): """Get the status of a KPL button.""" addr = Address(address) device = self.plm.devices[addr.id] device.states[group].async_refresh_state()
java
public static <K, V> Map<K, V> cast(Map<?, ?> map) { return map == null ? null : new CastingMap<K, V>(map); }
python
def generate_ngram_data_set(self, token_list, n=2): ''' Generate the N-gram's pair. Args: token_list: The list of tokens. n N Returns: zip of Tuple(Training N-gram data, Target N-gram data) ''' n_gram_tupl...
java
public static Map<String, ValueCommand> createParameterMap(Object... params) { assert params.length % 2 == 0; Map<String, ValueCommand> ret = new HashMap<String, ValueCommand>(); for (int i = 0; i < params.length; i = i + 2) { String param = params[i].toString(); Value va...
java
final public SwitchExpressionBuilder<T> switchOn() { return new SwitchExpressionBuilder<T>(new ExpressionHandler<SwitchBuilder<T>>() { public SwitchBuilder<T> handleExpression(final Expression e) { return new SwitchBuilder<T>(e, new SwitchStatementsHandler<T>() { public T handleStatement(Swi...
java
private Glyph createGlyphBasics(Entity e, boolean idIsFinal) { Glyph g = factory.createGlyph(); g.setId(convertID(e.getUri())); String s = typeMatchMap.get(e.getModelInterface()); if(( //use 'or' sbgn class for special generic physical entities e instanceof Complex && !((Complex)e).getMemberPhysicalEntity(...
java
protected JButton createLeftOneTouchButton() { SeaGlassArrowButton b = new SeaGlassArrowButton(SwingConstants.NORTH); int oneTouchSize = lookupOneTouchSize(); b.setName("SplitPaneDivider.leftOneTouchButton"); b.setMinimumSize(new Dimension(oneTouchSize, oneTou...
java
@Override protected List<Object> populateEntities(EntityMetadata m, Client client) { ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata(); try { String query = appMetadata.getQuery(getJPAQuery()); boolean isNative = kunderaQuery.isNative();...
python
def timeout_after(seconds, coro=None, *args): '''Execute the specified coroutine and return its result. However, issue a cancellation request to the calling task after seconds have elapsed. When this happens, a TaskTimeout exception is raised. If coro is None, the result of this function serves as...
java
private String parseErrorCodeFromHeader(Map<String, String> httpHeaders) { String headerValue = httpHeaders.get(X_AMZN_ERROR_TYPE); if (headerValue != null) { int separator = headerValue.indexOf(':'); if (separator != -1) { headerValue = headerValue.substring(0, s...
java
@Override public DeleteNamedQueryResult deleteNamedQuery(DeleteNamedQueryRequest request) { request = beforeClientExecution(request); return executeDeleteNamedQuery(request); }
python
def remove(self, item): """Remove either an unparsed argument string or an argument object. :param Union[str,Arg] item: Item to remove >>> arguments = TexArgs([RArg('arg0'), '[arg2]', '{arg3}']) >>> arguments.remove('{arg0}') >>> len(arguments) 2 >>> arguments[0...
python
def phone_numbers(self): """ :rtype: twilio.rest.lookups.v1.phone_number.PhoneNumberList """ if self._phone_numbers is None: self._phone_numbers = PhoneNumberList(self) return self._phone_numbers
java
public static List<CommercePriceEntry> findByCompanyId(long companyId, int start, int end) { return getPersistence().findByCompanyId(companyId, start, end); }
python
def __load_functions(self): ''' Find out what functions are available on the minion ''' return set(self.local.cmd(self.minion, 'sys.list_functions').get(self.minion, []))
java
@Override public Builder claimFrom(String jsonOrJwt, String claim) throws InvalidClaimException, InvalidTokenException { if (JwtUtils.isNullEmpty(claim)) { String err = Tr.formatMessage(tc, "JWT_INVALID_CLAIM_ERR", new Object[] { claim }); throw new InvalidClaimException(err); ...
python
def mxarray_to_ndarray(libmx, pm): """Convert MATLAB object `pm` to numpy equivalent.""" ndims = libmx.mxGetNumberOfDimensions(pm) dims = libmx.mxGetDimensions(pm) numelems = libmx.mxGetNumberOfElements(pm) elem_size = libmx.mxGetElementSize(pm) class_name = libmx.mxGetClassName(pm) is_nume...
java
public static MozuUrl updateUrl(String cardId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/payments/commerce/payments/cards/{cardId}?responseFields={responseFields}"); formatter.formatUrl("cardId", cardId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(...
java
public String readToken(String remainder) { final String token; try { Stack<Character> parens = new Stack<Character>(); int nextExpression; for (nextExpression = 0; nextExpression < remainder.length(); nextExpression++) { char c = remainder.charAt(nex...
python
def flatten(args): """ %prog flatten filename > ids Convert a list of IDs (say, multiple IDs per line) and move them into one per line. For example, convert this, to this: A,B,C | A 1 | B a,4 | C ...
java
private void handleContainerCompletion(ContainerStatus containerStatus) { Map.Entry<Container, String> completedContainerEntry = this.containerMap.remove(containerStatus.getContainerId()); String completedInstanceName = completedContainerEntry.getValue(); LOGGER.info(String.format("Container %s running Hel...
java
public static BitcoinTransaction convertToBitcoinTransaction(HiveBitcoinTransaction transaction) { List<BitcoinTransactionOutput> newTransactionsOutputList = new ArrayList<>(); for (int j = 0; j < transaction.getListOfOutputs().size(); j++) { HiveBitcoinTransactionOutput currentOutput = transaction.getListOfOutp...
java
public static <T> Predicate<T> in(Collection<? extends T> target) { return t -> { try { return target.contains(t); } catch (ClassCastException | NullPointerException e) { return false; } }; }
python
def erase_down (self): # <ESC>[0J -or- <ESC>[J '''Erases the screen from the current line down to the bottom of the screen.''' self.erase_end_of_line () self.fill_region (self.cur_r + 1, 1, self.rows, self.cols)
python
def _update_xyz(self, change): """ Keep x,y,z in sync with position """ self.x,self.y,self.z = self.position.X(),self.position.Y(),self.position.Z()
java
@Override public IAuthorizationPrincipal newPrincipal(String key, Class type) { final Tuple<String, Class> principalKey = new Tuple<>(key, type); final Element element = this.principalCache.get(principalKey); // principalCache is self populating, it can never return a null entry retu...
java
@InService(SegmentServiceImpl.class) private Type writeCheckpointFull(TableKelp table, OutputStream os, int saveTail) throws IOException { os.write(getMinKey()); os.write(getMaxKey()); /* db/2310 if (Arrays.equals(getMinK...
java
public java.util.List<Type> getType() { if (myType == null) { myType = new java.util.ArrayList<Type>(); } return myType; }
python
def get(self, key: str, *, prompt: Optional[Message_T] = None, arg_filters: Optional[List[Filter_T]] = None, **kwargs) -> Any: """ Get an argument with a given key. If the argument does not exist in the current session, a pause exception will be raise...
java
protected void assertEndBraceExists(Method executeMethod, String urlPattern, int index) { if (index >= 0) { throwUrlPatternEndBraceNotFoundException(executeMethod, urlPattern, index); } }
java
public static <E extends Enum<E>> EnumSet<E> processBits(final Class<E> enumClass, final long value) { return EnumUtils.processBitVector(enumClass, value); }
java
public void setTargetCertConstraints(CertSelector selector) { if (selector != null) certSelector = (CertSelector) selector.clone(); else certSelector = null; }
java
@Nonnull public static String readFile(@Nonnull File file, @Nonnull String charset) throws IOException { return readFile(file, Charset.forName(charset)); }
python
def color_text(text, color): r""" SeeAlso: highlight_text lexer_shortnames = sorted(ut.flatten(ut.take_column(pygments.lexers.LEXERS.values(), 2))) """ import utool as ut if color is None or not ENABLE_COLORS: return text elif color == 'python': return highlight_t...
python
def method_already_there(object_type, method_name, this_class_only=False): """ Returns True if method `method_name` is already implemented by object_type, that is, its implementation differs from the one in `object`. :param object_type: :param method_name: :param this_class_only: :return: ...
java
public static String joinOptions(String[] optionArray) { String optionString = ""; for (int i = 0; i < optionArray.length; i++) { if (optionArray[i].equals("")) { continue; } boolean escape = false; for (int n = 0; n < optionArray[i].length(); n++) { if (Character.isWhitespace(optionA...
java
public void writeToExcel(List<? extends Object> datas, boolean hasTitle, String path, boolean transverse) throws IOException { writeToExcel(datas, hasTitle, path, IN_MEMORY, transverse); }
java
public java.util.List<String> getRejectedPatches() { if (rejectedPatches == null) { rejectedPatches = new com.amazonaws.internal.SdkInternalList<String>(); } return rejectedPatches; }
python
def logs_for_job(self, job_name, wait=False, poll=10): # noqa: C901 - suppress complexity warning for this method """Display the logs for a given training job, optionally tailing them until the job is complete. If the output is a tty or a Jupyter cell, it will be color-coded based on which inst...
python
def import_obj(cls, i_datasource, import_time=None): """Imports the datasource from the object to the database. Metrics and columns and datasource will be overrided if exists. This function can be used to import/export dashboards between multiple superset instances. Audit metadata is...
java
@Override public V put(K key, V value) { BinarySet<Entry<K,V>> es = (BinarySet<Entry<K,V>>) entrySet; Entry<K,V> oldEntry = es.addEntry(entry(key, value)); if (oldEntry != null) { return oldEntry.getValue(); } return null; }
python
def getall(self): """Returns all ACLs in a dict object. Returns: A Python dictionary object containing all ACL configuration indexed by ACL name:: { "<ACL1 name>": {...}, "<ACL2 name>": {...} } """...
java
public static Object invokeReadMethodOptional( Object bean, String propertyName) { Class<?> c = bean.getClass(); Method method = getReadMethodOptional(c, propertyName); if (method == null) { return null; } return Methods.invokeOptional(met...
python
def search_for_parent_dir(start_at: str=None, with_files: set=None, with_dirs: set=None) -> str: """Return absolute path of first parent directory of `start_at` that contains all files `with_files` and all dirs `with_dirs` (including `start_at`). If `start_at` not specif...
java
private static MethodRef getBuilderMethod(Descriptor descriptor) { TypeInfo message = messageRuntimeType(descriptor); TypeInfo builder = builderRuntimeType(descriptor); return MethodRef.createStaticMethod( message, new Method("newBuilder", builder.type(), NO_METHOD_ARGS)) .asNonNullable(...
java
public void clear(String layerName) { synchronized (this) { log.info("clearing cache for layer " + layerName); for (String key : cache.keySet()) { if (key.contains(layerName)) remove(key); } } }
java
public static PolicyLimit findPolicyLimitByUserAndCounter(EntityManager em, PrincipalUser user, PolicyCounter counter) { TypedQuery<PolicyLimit> query = em.createNamedQuery("PolicyLimit.findPolicyLimitByUserAndCounter", PolicyLimit.class); try { query.setParameter("user", user); ...
java
@Override public long dynamicQueryCount(DynamicQuery dynamicQuery, Projection projection) { return commerceDiscountRelPersistence.countWithDynamicQuery(dynamicQuery, projection); }
python
def domains(self, history=None): """ Get the set of I{all} domain names. @param history: A history of nodes checked to prevent circular hunting. @type history: [L{Properties},..] @return: A set of domain names. @rtype: list """ if history is No...
java
@Override public void clearCache(CPDefinitionGroupedEntry cpDefinitionGroupedEntry) { entityCache.removeResult(CPDefinitionGroupedEntryModelImpl.ENTITY_CACHE_ENABLED, CPDefinitionGroupedEntryImpl.class, cpDefinitionGroupedEntry.getPrimaryKey()); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION)...
java
public static List<UIComponent> resolveComponents(FacesContext context, UIComponent source, String expressions) { return resolveComponents(context, source, expressions, SearchExpressionHint.NONE); }
python
def logout(request): """View to forget the user""" request.response.headers.extend(forget(request)) return {'redirect': request.POST.get('came_from', '/')}
java
public static Slice wrappedBooleanArray(boolean[] array, int offset, int length) { if (length == 0) { return EMPTY_SLICE; } return new Slice(array, offset, length); }
python
def _set_tracker_uri(self, uri): """ Called when we start a new resumable upload or get a new tracker URI for the upload. Saves URI and resets upload state. Raises InvalidUriError if URI is syntactically invalid. """ parse_result = urlparse.urlparse(uri) if (pars...
python
def dns(self): """DNS details.""" dns = { 'elb': self.dns_elb(), 'elb_region': self.dns_elb_region(), 'global': self.dns_global(), 'region': self.dns_region(), 'instance': self.dns_instance(), } return dns
java
public static String doGet(final String url, final int retryTimes) { try { return doGetByLoop(url, retryTimes); } catch (HttpException e) { throw new HttpException(format("Failed to download content for url: '%s'. Tried '%s' times", url, Math.max(retryTimes + 1, 1))); } }
python
def BinToTri(self, a, b): ''' Turn an a-b coord to an x-y-z triangular coord . if z is negative, calc with its abs then return (a, -b). :param a,b: the numbers of the a-b coord :type a,b: float or double are both OK, just numbers :return: the corresponding x-y-z triangu...
python
def files(self): """ Yield relative file paths specified in :attr:`metainfo` Each paths starts with :attr:`name`. Note that the paths may not exist. See :attr:`filepaths` for existing files. """ info = self.metainfo['info'] if 'length' in info: # Sing...
java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException { servletRequest.setCharacterEncoding("UTF-8"); httpRequest.set(servletRequest); httpResponse.set(servletResponse); Request appRequest = null; try { // String sess...
python
def list_statistics(self, begin_date, end_date, shop_id=-1): """ Wi-Fi数据统计 详情请参考 http://mp.weixin.qq.com/wiki/8/dfa2b756b66fca5d9b1211bc18812698.html :param begin_date: 起始日期时间,最长时间跨度为30天 :param end_date: 结束日期时间戳,最长时间跨度为30天 :param shop_id: 可选,门店 ID,按门店ID搜索,-1为总统计...
java
public int getNumPoints() { if (isEmpty()) { return 0; } int total = 0; for (Polygon polygon : polygons) { total += polygon.getNumPoints(); } return total; }
python
def serialize(self, value): """Convert the external Python value to a type that is suitable for storing in a Mutagen file object. """ if isinstance(value, float) and self.as_type is six.text_type: value = u'{0:.{1}f}'.format(value, self.float_places) value = self....
python
def set_cookie(self, cookie=None): """Set the Cookie header.""" if cookie: self._cookie = cookie.encode() else: self._cookie = None
python
def _get_dynamic_attr(self, attname, obj, default=None): """ Copied from django.contrib.syndication.views.Feed (v1.7.1) """ try: attr = getattr(self, attname) except AttributeError: return default if callable(attr): # Check co_argcount ...
java
public static String combine(String str1, String str2, String separator) { if (separator == null || separator.isEmpty()) { return str1 == null ? str2 : str1.concat(str2); } if (str1 == null) str1 = ""; if (str2 == null) str2 = ""; StringBuild...
java
@Override public int compareTo(Enhancement o) { if (this.equals(o)) return 0; if (this.confidence > o.getConfidence()) return -1; else if (this.confidence < o.getConfidence()) return 1; else return 0; }
java
public ServiceFuture<List<PhraseListFeatureInfo>> listPhraseListsAsync(UUID appId, String versionId, ListPhraseListsOptionalParameter listPhraseListsOptionalParameter, final ServiceCallback<List<PhraseListFeatureInfo>> serviceCallback) { return ServiceFuture.fromResponse(listPhraseListsWithServiceResponseAsync(...
python
def _parse(self, date_str, format='%Y-%m-%d'): """ helper function for parsing FRED date string into datetime """ rv = pd.to_datetime(date_str, format=format) if hasattr(rv, 'to_pydatetime'): rv = rv.to_pydatetime() return rv
python
def get_feature(self, croplayer_id, cropfeature_id): """ Gets a crop feature :param int croplayer_id: ID of a cropping layer :param int cropfeature_id: ID of a cropping feature :rtype: CropFeature """ target_url = self.client.get_url('CROPFEATURE', 'GET', 'single...
java
public Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException { throw new DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR, null); }
java
public static List<AvailableNumber> searchLocal(final BandwidthClient client, final Map<String, Object>params) throws Exception { final String tollFreeUri = BandwidthConstants.AVAILABLE_NUMBERS_LOCAL_URI_PATH; final JSONArray array = toJSONArray(client.get(tollFreeUri, ...
python
def collision_rate(Temperature, element, isotope): r"""This function recieves the temperature of an atomic vapour (in Kelvin), the element, and the isotope of the atoms, and returns the angular frequency rate of collisions (in rad/s) in a vapour assuming a Maxwell-Boltzmann velocity distribution, and ta...
java
@NotNull @ObjectiveCName("validatePasswordCommand:") public Command<AuthState> validatePassword(String password) { return modules.getAuthModule().requestValidatePassword(password); }
java
public void log(int level, String message, Throwable exception) { doLog(message, level, null, exception); }
python
def _do_tcp_check(self, ip, results): """ Attempt to establish a TCP connection. If not successful, record the IP in the results dict. Always closes the connection at the end. """ try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc...