language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public Expression<Enum<?>> eq(Enum<?> value) { String valueString = "'" + EnumPath.getValue(value) + "'"; return new Expression<Enum<?>>(this, Operation.eq, valueString); }
python
def start(self, timer=True): """ 引擎启动 timer:是否要启动计时器 """ # 将引擎设为启动 self.__active = True # 启动事件处理线程 self.__thread.start() # 启动计时器,计时器事件间隔默认设定为1秒 if timer: self.__timer.start(1000)
python
def fetch_replace_restriction(self, ): """Fetch whether unloading is restricted :returns: True, if unloading is restricted :rtype: :class:`bool` :raises: None """ inter = self.get_refobjinter() restricted = self.status() is None return restricted or inter...
java
private String getWeekDayLabel(Calendar day) { Locale locale = mController.getLocale(); // Localised short version of the string is not available on API < 18 if (Build.VERSION.SDK_INT < 18) { String dayName = new SimpleDateFormat("E", locale).format(day.getTime()); Strin...
python
def photo_url(self): """获取话题头像图片地址. :return: 话题头像url :rtype: str """ img = self.soup.find('a', id='zh-avartar-edit-form').img['src'] return img.replace('_m', '_r')
java
public void process() { try { Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources("META-INF/persistence.xml"); XMLInputFactory factory = XMLInputFactory.newInstance(); List<String> persistenceUnits = new ArrayList<String>(); while (urls.hasMoreElements()) { URL url ...
python
def make_commodity_future_info(first_sid, root_symbols, years, month_codes=None, multiplier=500): """ Make futures testing data that simulates the notice/expiration date behavior of ph...
java
public File createDumpFile(final File dir, final String extension, final String urlString, final String additionalInfo) { URI uri = URI.create(urlString); String path = uri.getPath(); if (path == null) { log.warn("Cannot create dump file for URI: " + uri); return null; } String name = PATTERN_FIRST_LAS...
java
public static Set<InvokableAnnotatedMethod<?>> getDecoratorMethods(BeanManagerImpl beanManager, WeldDecorator<?> decorator) { ImmutableSet.Builder<InvokableAnnotatedMethod<?>> builder = ImmutableSet.builder(); for (Type type : decorator.getDecoratedTypes()) { EnhancedAnnotatedType<?> weldCla...
java
private void obtainShowRestoreDefaultsButton() { boolean show = ThemeUtil.getBoolean(getActivity(), R.attr.showRestoreDefaultsButton, false); showRestoreDefaultsButton(show); }
java
public static void executeHelp(String[] args, PrintStream stream) throws Exception { String subCmd = (args.length > 0) ? args[0] : ""; args = CoordinatorAdminUtils.copyArrayCutFirst(args); if(subCmd.equals("get")) { SubCommandGet.printHelp(stream); } else if(subCmd.equals("pu...
java
public static String buildSelectProperty( CmsObject cms, String selectValue, String attributes, String selectedValue) { List propertyDef = new ArrayList(); try { // get all property definitions propertyDef = cms.readAllPropertyDefinitions(); ...
python
def parse_headers(buff): """ Parses buffer and returns command and headers as strings """ preamble_lines = list(map( lambda x: six.u(x).decode(), iter(lambda: buff.readline().strip(), b'')) ) if not preamble_lines: raise EmptyBuffer() return preamble_lines[0], Ordered...
python
def to_dict(self, index=True, ordered=False): """ Returns a dict where the keys are the column names and the values are lists of the values for that column. :param index: If True then include the index in the dict with the index_name as the key :param ordered: If True then return an Ord...
python
def fit(self, X, y=None, **fit_params): """ This method performs preliminary computations in order to set up the figure or perform other analyses. It can also call drawing methods in order to set up various non-instance related figure elements. This method must return self. ...
java
public static StringBuffer formatInput(StringBuffer appendTo, ReplaceableString input, Transliterator.Position pos) { if (0 <= pos.contextStart && pos.contextStart <= pos.start && pos.start <= pos.limit...
java
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // update element stack stack.add(localName); // <context-param> if (elements("web-app", "context-param")) { currentName = null; curre...
python
def get_section_key_line(self, data, key, opt_extension=''): """Get the next section line for a given key. :param data: the data to proceed :param key: the key :param opt_extension: an optional extension to delimit the opt value """ start = 0 init = 0 wh...
python
def verify_precompiled_checksums(self, precompiled_path: Path) -> None: """ Compare source code checksums with those from a precompiled file. """ # We get the precompiled file data contracts_precompiled = ContractManager(precompiled_path) # Silence mypy assert self.contracts_ch...
java
public void delete(boolean notifyUser, boolean force) { String queryString = new QueryStringBuilder() .appendParam("notify", String.valueOf(notifyUser)) .appendParam("force", String.valueOf(force)) .toString(); URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI()...
python
def weighted_maximum_cut(G, sampler=None, **sampler_args): """Returns an approximate weighted maximum cut. Defines an Ising problem with ground states corresponding to a weighted maximum cut and uses the sampler to sample from it. A weighted maximum cut is a subset S of the vertices of G that maxi...
python
def get_chunks(self, boundingbox=None): """ Return a list of all chunks. Use this function if you access the chunk list frequently and want to cache the result. Use iter_chunks() if you only want to loop through the chunks once or have a very large world. """ if s...
python
def _search_url(search_term:str, size:str='>400*300', format:str='jpg') -> str: "Return a Google Images Search URL for a given search term." return ('https://www.google.com/search?q=' + quote(search_term) + '&espv=2&biw=1366&bih=667&site=webhp&source=lnms&tbm=isch' + _url_params(size, fo...
python
def _polytree_node_to_shapely(node): """ Recurses down a Clipper PolyTree, extracting the results as Shapely objects. Returns a tuple of (list of polygons, list of children) """ polygons = [] children = [] for ch in node.Childs: p, c = _polytree_node_to_shapely(ch) poly...
python
def _get_spec(self, index): user_data = self.itemData(index) """ :type: QVariant""" spec = user_data.toPyObject() return {str(key): value for key, value in spec.items()}
java
private void writePageAndReport(CmsXmlPage page, boolean report) throws CmsException { CmsFile file = page.getFile(); byte[] content = page.marshal(); file.setContents(content); // check lock CmsLock lock = getCms().getLock(file); if (lock.isNullLock() || lock.isOwnedBy(...
python
def rename_annotations(self, sentence): """Function that renames and restructures clause information.""" annotations = [] for token in sentence: data = {CLAUSE_IDX: token[CLAUSE_IDX]} if CLAUSE_ANNOT in token: if 'KINDEL_PIIR' in token[CLAUSE_ANNOT]: ...
python
def _parse_docstring(self, docstring): """Parse the method docstring.""" match = re.match(r""" # Following PEP 257 \s* (?P<summary>[^\n]+?) \s* # First line ( # Description and YAML are optional (\n \s*){2} ...
python
def get(self, name): """ Returns the struct, enum, or interface with the given name, or raises RpcException if no elements match that name. :Parameters: name Name of struct/enum/interface to return """ if self.structs.has_key(name): retu...
python
def mousePressEvent(self, e): """ Starts selecting """ self._selecting = True self._sel_start = e.pos().y() start = end = TextHelper(self.editor).line_nbr_from_position( self._sel_start) self._start_line = start TextHelper(self.editor).select_l...
python
def list_huisnummers_by_straat(self, straat, sort=1): ''' List all `huisnummers` in a `Straat`. :param straat: The :class:`Straat` for which the \ `huisnummers` are wanted. :rtype: A :class: `list` of :class:`Huisnummer` ''' try: id = straat.id ...
python
def run(self): """This function needs to be called to start the computation.""" (task_id, tasks) = self.server.get_task() self.task_store.from_dict(tasks) for (index, task) in self.task_store: result = self.compute(index, task) self.results.append(result) ...
python
def AtMaximumDepth(self, search_depth): """Determines if the find specification is at maximum depth. Args: search_depth (int): number of location path segments to compare. Returns: bool: True if at maximum depth, False if not. """ if self._location_segments is not None: if search...
python
def update_vm(vm_name, cpu=None, memory=None, image=None, version=None, interfaces=None, disks=None, scsi_devices=None, serial_ports=None, datacenter=None, datastore=None, cd_dvd_drives=None, sata_controllers=None, advanced_configs=None, service_instance=None): ...
python
async def release(self, delay=None): """ Put the task back into the queue. May contain a possible new `delay` before the task is executed again. Returns `True` is task is released (task state is 'ready' or 'delayed' if `delay` is set now). """ the_tuple = await ...
java
public void addWorkplaceServer(String workplaceServer, String sslmode) { if (m_frozen) { throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0)); } if (!m_workplaceServers.containsKey(workplaceServer)) { m_workplaceServers.put(workplaceServe...
python
def fetch(self, id_, return_fields=None): """ Wrapper for fetching details of game by ID :param id_: int :param return_fields: tuple :return: pybomb.clients.Response """ game_params = {"id": id_} if return_fields is not None: self._validate_...
java
public void marshall(DescribeProjectRequest describeProjectRequest, ProtocolMarshaller protocolMarshaller) { if (describeProjectRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeProje...
java
@Override protected int findInstanceIdInfo(String s) { int id; // #generated# Last update: 2014-12-08 17:32:09 PST L0: { id = 0; String X = null; int c; int s_length = s.length(); if (s_length==6) { X="buffer";id=Id_buffer; } else if (s_length==10) { ...
python
def cmd_subset( self, tgt, fun, arg=(), timeout=None, tgt_type='glob', ret='', kwarg=None, sub=3, **kwargs): ''' Execute a command on a random subset of the targeted systems T...
python
def short_timesince(date): """ A shorter version of Django's built-in timesince filter. Selects only the first part of the returned string, splitting on the comma. Falls back on default Django timesince if it fails. Example: 3 days, 20 hours becomes "3 days". """ try: t = time...
python
def infer(self, bottomUpInput): """ Parameters: -------------------------------------------- input: Current bottom-up input, dense retval: ? """ self.iterationIdx = self.iterationIdx + 1 if self.verbosity >= 3: print "\n==== Iteration: %d =====" % (self.iterationIdx)...
java
@SuppressWarnings("unchecked") public int getBlackLListByPhone(final String phone) { DetachedCriteria criteria = DetachedCriteria.forClass(Blacklist.class); criteria.add(Restrictions.eq(Blacklist.PROP_BLA_PHONE, phone)); List<Blacklist> bla = getHibernateTemplate().findByCriteria(criteria); return bla....
java
@Override public Set<Principal> getPrincipals(final HttpServletRequest request) { LOGGER.debug("Checking for principals using {}", HttpHeaderPrincipalProvider.class.getSimpleName()); if (headerName == null || separator == null) { LOGGER.debug("headerName or separator not initialized"); ...
python
def bytes(self): """ Returns the provided data as bytes. """ if self._filename: with open(self._filename, "rb") as f: return f.read() else: return self._bytes
java
public ForEachRuleContext<DPO, RI, RO> forEach() { // Change context return new ForEachRuleContext<DPO, RI, RO>(addedTriggers, addedDataProviders, dataProviderToRuleMapping, addedRuleInputTransformers, addedRules); }
java
public void writeOutParamsToStub(VariableElement param, ParamType paramType, String paramName, MethodSpec.Builder methodBuilder) { if (paramType != ParamType.IN) { methodBuilder.addStatement("int " + paramName + "_length = data.readInt()"); methodBuilder.beginControlFlow("if (" + paramNa...
java
@Override public Subject authenticate(@Sensitive byte[] tokenBytes) throws AuthenticationException { AuthenticationData authenticationData = createAuthenticationData(tokenBytes); return authenticationService.authenticate(jaasEntryName, authenticationData, null); }
python
def unpacked_contents(self): """ :return: """ from nbformat import read import msgpack if self.mime_type == 'text/plain': return self.contents.decode('utf-8') elif self.mime_type == 'application/msgpack': # FIXME: Note: I'm not sure that...
java
public static <T> List<T> concat(List<List<T>> lists) { List<T> list = new ArrayList<T>(); for (List<? extends T> l : lists) { list.addAll(l); } return list; }
python
def close(self): """Close the cursor""" if self.closed or self.connection.closed: return self._cursor.close() self.closed = True
python
def create_gnu_header(self, info, encoding, errors): """Return the object as a GNU header block sequence. """ info["magic"] = GNU_MAGIC buf = b"" if len(info["linkname"]) > LENGTH_LINK: buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK, encoding,...
python
def _transstat(status, grouppath, dictpath, line): """Executes processing steps when reading a line""" if status == 0: raise MTLParseError( "Status should not be '%s' after reading line:\n%s" % (STATUSCODE[status], line)) elif status == 1: currentdict = dictpath[-1] ...
python
def upload_to_cloud(file_handles, staging_bucket, replica, from_cloud=False): """ Upload files to cloud. :param file_handles: If from_cloud, file_handles is a aws s3 directory path to files with appropriate metadata uploaded. Else, a list of binary file_handles to upload. :para...
python
def get_work_item_type_category(self, project, category): """GetWorkItemTypeCategory. [Preview API] Get specific work item type category by name. :param str project: Project ID or project name :param str category: The category name :rtype: :class:`<WorkItemTypeCategory> <azure.de...
python
def get_preferred(self, addr_1, addr_2): '''Return the preferred address.''' if addr_1 > addr_2: addr_1, addr_2 = addr_2, addr_1 return self._cache.get((addr_1, addr_2))
java
@Override public PayQueryResponse retcode(int retcode) { this.retcode = retcode; this.retinfo = PayRetCodes.retInfo(retcode); return this; }
java
public static CmsBasicFormField createField( CmsXmlContentProperty propertyConfig, Map<String, String> additionalParams) { return createField( propertyConfig, propertyConfig.getName(), CmsWidgetFactoryRegistry.instance(), additionalParams, ...
java
@RequestMapping(method = RequestMethod.POST, params = "action=renameTab") public ModelAndView renameTab(HttpServletRequest request, HttpServletResponse response) throws IOException { IUserInstance ui = userInstanceManager.getUserInstance(request); UserPreferencesManager upm = (UserPrefe...
java
private synchronized FileServiceMXBean getFileService() { if (fileService == null) { try { fileService = JMX.newMXBeanProxy(ManagementFactory.getPlatformMBeanServer(), new ObjectName(FileServiceMXBean.OBJECT_NAME), FileServiceMXBean.class); } catch (MalformedObjectNameExc...
java
public java.util.List<String> getInstanceGroupIds() { if (instanceGroupIds == null) { instanceGroupIds = new com.amazonaws.internal.SdkInternalList<String>(); } return instanceGroupIds; }
java
public void startDockerMachine(String cliPathExec, String machineName) { commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec), "start", machineName); this.manuallyStarted = true; }
python
def update_delisting(self, num_iid, session): '''taobao.item.update.delisting 商品下架 单个商品下架 输入的num_iid必须属于当前会话用户''' request = TOPRequest('taobao.item.update.delisting') request['num_iid'] = num_iid self.create(self.execute(request, session)['item']) return...
python
def initStats(self): """Query and parse Apache Web Server Status Page.""" url = "%s://%s:%d/%s?auto" % (self._proto, self._host, self._port, self._statuspath) response = util.get_url(url, self._user, self._password) self._statusDict = {} f...
python
def eat_line(self): """Move current position forward until the next line.""" if self.eos: return None eat_length = self.eat_length get_char = self.get_char has_space = self.has_space while has_space() and get_char() != '\n': eat_length(1) e...
java
private long calculatePartSize(long fileSize) { long partSize = MINIMUM_PART_SIZE; int approxNumParts = 1; while (partSize * approxNumParts < fileSize && partSize*2 <= MAXIMUM_UPLOAD_PART_SIZE) { partSize *= 2; approxNumParts *= 2; } return partSize; }
python
def set(conf): """Applies a configuration to the global config object""" for name, value in conf.items(): if value is not None: setattr(Conf, name.upper(), value)
java
public static Class isAssignableTo(final Class<?> reference, final Class<?> toValue, final String message) { return precondition(reference, new Predicate<Class>() { @Override public boolean test(Class testValue) { return toValue.isAssignableFrom(testValue); } ...
java
public static int getCatalogIndexSize(Index index) { int indexSize = 0; String jsonstring = index.getExpressionsjson(); if (jsonstring.isEmpty()) { indexSize = getSortedCatalogItems(index.getColumns(), "index").size(); } else { try { indexSize = A...
java
public static List<List<Writable>> executeSequenceToSeparate(List<List<List<Writable>>> inputSequence, TransformProcess transformProcess) { if (transformProcess.getFinalSchema() instanceof SequenceSchema) { throw new IllegalStateExcept...
python
def angularFrontendAppDir(self) -> str: """ Angular Frontend Dir This directory will be linked into the angular app when it is compiled. :return: The absolute path of the Angular2 app directory. """ relDir = self._packageCfg.config.plugin.title(require_string) dir = os....
java
public final HttpServer proxyProtocol(boolean proxyProtocolEnabled) { if (proxyProtocolEnabled) { if (!HAProxyMessageReader.hasProxyProtocol()) { throw new UnsupportedOperationException( "To enable proxyProtocol, you must add the dependency `io.netty:netty-codec-haproxy`" + " to...
python
def retrieve(self, request, *args, **kwargs): """ User fields can be updated by account owner or user with staff privilege (is_staff=True). Following user fields can be updated: - organization (deprecated, use `organization plugin <http://waldur_core-organization.readthedocs.o...
python
def black(cls): "Make the text foreground color black." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK #wAttributes |= win32.FOREGROUND_BLACK cls._set_text_attributes(wAttributes)
python
def read_namespace_status(self, name, **kwargs): # noqa: E501 """read_namespace_status # noqa: E501 read status of the specified Namespace # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>...
python
def nPercentile(requestContext, seriesList, n): """Returns n-percent of each series in the seriesList.""" assert n, 'The requested percent is required to be greater than 0' results = [] for s in seriesList: # Create a sorted copy of the TimeSeries excluding None values in the # values l...
java
@Override protected int msd(Long a, Long b) { /* * Value equal */ if (a.longValue() == b.longValue()) { return -1; } /* * This is a fast way to compute floor(log_2(a xor b)). */ double axorb = a ^ b; return Math.getExpon...
python
def load_image(self, idx): """ Load input image and preprocess for Caffe: - cast to float - switch channels RGB -> BGR - subtract mean - transpose to channel x height x width order """ im = Image.open('{}/data/images/img_{}.png'.format(self.nyud_dir, idx))...
java
public void setVpcEndpoints(java.util.Collection<VpcEndpoint> vpcEndpoints) { if (vpcEndpoints == null) { this.vpcEndpoints = null; return; } this.vpcEndpoints = new com.amazonaws.internal.SdkInternalList<VpcEndpoint>(vpcEndpoints); }
java
public void fieldsToControls() { for (int iFileSeq = 0; ; iFileSeq++) { FieldList fieldList = this.getFieldList(iFileSeq); if (fieldList == null) break; for (int iFieldSeq = 0; ; iFieldSeq++) { Converter converter = fiel...
python
def _speak_as( self, element, regular_expression, data_property_value, operation ): """ Execute a operation by regular expression for element only. :param element: The element. :type element: hatemile.util.html.htmldomelement.HTMLDOMElement ...
python
def zip_dict(*dicts): """Iterate over items of dictionaries grouped by their keys.""" for key in set(itertools.chain(*dicts)): # set merge all keys # Will raise KeyError if the dict don't have the same keys yield key, tuple(d[key] for d in dicts)
python
def authenticate(self, username=None, password=None, **kwargs): """ "username" being passed is really email address and being compared to as such. """ try: user = User.objects.get(email=username) if user.check_password(password): return user ...
python
def _is_target_a_directory(link, rel_target): """ If creating a symlink from link to a target, determine if target is a directory (relative to dirname(link)). """ target = os.path.join(os.path.dirname(link), rel_target) return os.path.isdir(target)
python
def noperiodic(r_array, periodic, reference=None): '''Rearrange the array of coordinates *r_array* in a way that doensn't cross the periodic boundary. Parameters ---------- r_array : :class:`numpy.ndarray`, (Nx3) Array of 3D coordinates. periodic: :class:`numpy.ndarray`, ...
java
public byte readControl(GroupAddress dst) throws KNXTimeoutException, KNXRemoteException, KNXLinkClosedException, KNXFormatException { final byte[] apdu = readFromGroup(dst, priority, 0, 0); final DPTXlator3BitControlled t = new DPTXlator3BitControlled(DPTXlator3BitControlled.DPT_CONTROL_DIMMING); ext...
java
public static double negativeBinomial(int n, int r, double p) { //tested its validity with http://www.mathcelebrity.com/binomialneg.php if(n<0 || r<0 || p<0) { throw new IllegalArgumentException("All the parameters must be positive."); } n = Math.max(n,r);//obvisouly the tota...
python
async def build( self, *, remote: str = None, fileobj: BinaryIO = None, path_dockerfile: str = None, tag: str = None, quiet: bool = False, nocache: bool = False, buildargs: Mapping = None, pull: bool = False, rm: bool = True, ...
java
protected final void validateSignature(final Signature signature, final String idpEntityId, final SignatureTrustEngine trustEngine) { final SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator(); try { validator.validate(sign...
java
protected Map<String, Object> getContinuationData() { Map<String, Object> data = new HashMap<String, Object>(); data.put("proxyBuilder", localProxyBuilder.get()); data.put("contexts", contexts.get()); return data; }
python
def full_data(self): """ Returns all the info available for the user in the following format: name [username] <id> (locale) bot_or_user If any data is not available, it is not added. """ data = [ self.full_name, self._username(), se...
java
@Override public SequenceRange get(String schemaName, String tableName, int step) throws Exception { Map<String, String> param = new HashMap<>(); param.put("clientId", clientId); param.put("accessToken", accessToken); param.put("schemaName", schemaName); param.put("tableName"...
java
public static <InnerT> Observable<InnerT> convertPageToInnerAsync(Observable<Page<InnerT>> innerPage) { return innerPage.flatMap(new Func1<Page<InnerT>, Observable<InnerT>>() { @Override public Observable<InnerT> call(Page<InnerT> pageInner) { return Observable.from(pageI...
java
public void write(OWLOntologyDocument document, OutputStream dos) throws IOException { write(document, dos, new BinaryOWLMetadata()); }
python
def search(self, **kwargs): """ Method to search vip's based on extends search. :param search: Dict containing QuerySets to find vip's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param ...
java
public ObjectBindingAssert<T> hasSameValue(ObservableObjectValue<T> expectedValue) { new ObservableValueAssertions<>(actual).hasSameValue(expectedValue); return this; }
java
@Pure public Rectangle2d toBounds2D() { int startIndex = this.id.indexOf('#'); if (startIndex <= 0) { return null; } try { int endIndex = this.id.indexOf(';', startIndex); if (endIndex <= startIndex) { return null; } final long minx = Long.parseLong(this.id.substring(startIndex + 1, endInde...
java
public JsonObject add(String name, JsonValue value) { if (name == null) { throw new NullPointerException(NAME_IS_NULL); } if (value == null) { throw new NullPointerException(VALUE_IS_NULL); } table.add(name, names.size()); names.add(name); values.add(value); return this; }
java
public CmsUUID publishProject( CmsObject cms, I_CmsReport report, CmsResource directPublishResource, boolean directPublishSiblings) throws CmsException { return publishProject(cms, report, getPublishList(cms, directPublishResource, directPublishSiblings)); }
python
def _method_error_handler(self, response: Dict[str, Any]): """处理400~499段状态码,为对应的任务设置异常. Parameters: (response): - 响应的python字典形式数据 Return: (bool): - 准确地说没有错误就会返回True """ exp = response.get('MESSAGE') code = response.get("CODE") ID = exp.g...