language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def find_videos_by_show(self, show_id, show_videotype=None, show_videostage=None, orderby='videoseq-asc', page=1, count=20): """doc: http://open.youku.com/docs/doc?id=64 """ url = 'https://openapi.youku.com/v2/shows/videos.json' par...
python
def get_template_options(): """ Returns a list of all templates that can be used for CMS pages. The paths that are returned are relative to TURRENTINE_TEMPLATE_ROOT. """ template_root = turrentine_settings.TURRENTINE_TEMPLATE_ROOT turrentine_dir = turrentine_settings.TURR...
python
def tell(self): """Return the file's current position. Returns: int, file's current position in bytes. """ self._check_open_file() if self._flushes_after_tell(): self.flush() if not self._append: return self._io.tell() if self._...
java
private static int getDay(Calendar cal, int dayOfWeek, int orderNum){ int day = cal.getActualMaximum(Calendar.DAY_OF_MONTH); cal.set(Calendar.DAY_OF_MONTH, day); int lastWeekday = cal.get(Calendar.DAY_OF_WEEK); int shift = lastWeekday >= dayOfWeek ? (lastWeekday - dayOfWeek) : (lastWeek...
java
public static <T> EditableTextArea<T> of(final String id, final IModel<T> model, final IModel<String> labelModel, final ModeContext modeContext) { final EditableTextArea<T> editableTextArea = new EditableTextArea<>(id, model, labelModel, modeContext); return editableTextArea; }
python
def _publish( tgt, fun, arg=None, tgt_type='glob', returner='', timeout=5, form='clean', wait=False, via_master=None): ''' Publish a command from the minion out to other minions, publications need to be enabled on the Salt master and th...
python
def take_screen_shot_to_array(self, screen_id, width, height, bitmap_format): """Takes a guest screen shot of the requested size and format and returns it as an array of bytes. in screen_id of type int The guest monitor to take screenshot from. in width of type int ...
java
private static int searchLocal( long localSecs, ZonalTransition[] transitions ) { int low = 0; int high = transitions.length - 1; while (low <= high) { int middle = (low + high) / 2; ZonalTransition zt = transitions[middle]; int offset = ...
python
def searchString( self, instring, maxMatches=_MAX_INT ): """ Another extension to :class:`scanString`, simplifying the access to the tokens found to match the given parse expression. May be called with optional ``maxMatches`` argument, to clip searching after 'n' matches are found. ...
python
def call_no_reply(self, fn, *args, **kwargs): """ See :meth:`CallChain.call_no_reply`. """ self.default_call_chain.call_no_reply(fn, *args, **kwargs)
python
def lipid_box(self): """The box containing all of the lipids. """ if self._lipid_box: return self._lipid_box else: self._lipid_box = self.lipid_components.boundingbox # Add buffer around lipid box. self._lipid_box.mins -= np.array([0.5*np.sqrt(self...
python
def get_parameters(self, packet_count=None): """ Returns the special tshark parameters to be used according to the configuration of this class. """ params = super(LiveCapture, self).get_parameters(packet_count=packet_count) # Read from STDIN params += ['-r', '-'] ...
java
public TreeSet<String> getParamNameSet(HtmlParameter.Type type) { TreeSet<String> set = new TreeSet<>(); Map<String, String> paramMap = Model.getSingleton().getSession().getParams(this, type); for (Entry<String, String> param : paramMap.entrySet()) { set.add(param.getKey()); } return set; }
python
def get_page(self, page_number): """ :param page_number: The page number to fetch (1-indexed) :return: The requested page fetched from the API for the query """ if page_number: kwargs = dict(self._list_kwargs) kwargs['limit'] = self.limit kwar...
java
@Override public Map<String, String> getAllMessages(Locale... locales) { Map<String, String> messages = new HashMap<>(); List<I18nExtension> extensionForLocale; for (Locale locale : locales) { extensionForLocale = getExtension(locale); for (I18nExtension extension : e...
python
def start(self): """ Starts the watchdog timer. """ self._timer = Timer(self.time, self.handler) self._timer.daemon = True self._timer.start() return
python
def newton_iterate(evaluate_fn, s, t): r"""Perform a Newton iteration. In this function, we assume that :math:`s` and :math:`t` are nonzero, this makes convergence easier to detect since "relative error" at ``0.0`` is not a useful measure. There are several tolerance / threshold quantities used be...
python
def find(objs, selector, context=None): ''' Query a collection of Bokeh models and yield any that match the a selector. Args: obj (Model) : object to test selector (JSON-like) : query selector context (dict) : kwargs to supply callable query attributes Yields: Model : o...
python
def poll_error(self): """ Append lines from stderr to self.errors. Returns: list: The lines added since last call """ if self.block: return self.error new_list = self.error[self.old_error_size:] self.old_error_size += len(new_list) ...
python
def _rows_page_start(iterator, page, response): """Grab total rows when :class:`~google.cloud.iterator.Page` starts. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type page: :class:`~google.api_core.page_iterator.Page` :pa...
java
public static Part<File> file(String name, String fileName, File file) { return new Part<>(name, fileName, file, ContentTypes.probeContentType(file), null, (body, out, charset) -> { try (InputStream in = new FileInputStream(body)) { InputStreams.transferTo(in, out); } ...
java
public static void twoLoopHp(Vec x_grad, List<Double> rho, List<Vec> s, List<Vec> y, Vec q, double[] alphas) { //q ← ∇ fk; x_grad.copyTo(q); if(s.isEmpty()) return;//identity, we are done //for i = k−1,k−2,...,k−m for(int i = 0; i < s.size(); i++) { ...
python
def make_dict_config(graph): """ Build a dictionary configuration from conventions and configuration. """ formatters = {} handlers = {} loggers = {} # create the console handler formatters["ExtraFormatter"] = make_extra_console_formatter(graph) handlers["console"] = make_stream_han...
java
public void setDeclType(int declType) { if (!(declType == Token.FUNCTION || declType == Token.LP || declType == Token.VAR || declType == Token.LET || declType == Token.CONST)) throw new IllegalArgumentException("Invalid declType: " + declType);...
python
def run(command): ''' Run command in shell, accepts command construction from list Return (return_code, stdout, stderr) stdout and stderr - as list of strings ''' if isinstance(command, list): command = ' '.join(command) out = subprocess.run(command, shell=True, stdout=subprocess.PIP...
python
def IsAllSpent(self): """ Flag indicating if all balance is spend. Returns: bool: """ for item in self.Items: if item == CoinState.Confirmed: return False return True
python
def plot_throat(self, throats, fig=None): r""" Plot a throat or list of throats in 2D showing key data Parameters ---------- throats : list or array containing throat indices tp include in figure fig : matplotlib figure object to place plot in """ throat...
java
private void resizeSemiUnique(int newCapacity) { SemiUniqueEntry[] oldTable = getNonDatedTable(); int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { semiUniqueThreshold = Integer.MAX_VALUE; return; } SemiUniqueEntry[] n...
java
public ImmutableList<Symbol> getFileAsSymbolList(String param) throws IOException { return FileUtils.loadSymbolList(Files.asCharSource(getExistingFile(param), Charsets.UTF_8)); }
python
def fun_residuals(params, xnor, ynor, w, bbox, k, ext): """Compute fit residuals""" spl = LSQUnivariateSpline( x=xnor, y=ynor, t=[item.value for item in params.values()], w=w, bbox=bbox, k=k, ext=ext, check_finite=False ) return spl.get_re...
java
public void onPartCreate(PartCreationEvent event) { final File part = event.getPart(); final UploadPartRequest reqUploadPart = newUploadPartRequest(event, part); final OnFileDelete fileDeleteObserver = event.getFileDeleteObserver(); appendUserAgent(reqUploadPart, AmazonS3Encr...
python
def gen_version(do_write=True, txt=None): """ Generate a version based on git tag info. This will write the couchbase/_version.py file. If not inside a git tree it will raise a CantInvokeGit exception - which is normal (and squashed by setup.py) if we are running from a tarball """ if txt i...
python
def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3): """ Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matr...
python
def _storage_init(self): """ Ensure that storage is initialized. """ if not self._storage.initialized: self._storage.init(self._module._py3_wrapper, self._is_python_2)
java
public static /*@pure@*/ int minIndex(int[] ints) { int minimum = 0; int minIndex = 0; for (int i = 0; i < ints.length; i++) { if ((i == 0) || (ints[i] < minimum)) { minIndex = i; minimum = ints[i]; } } return minIndex; }
python
def get_client_key_exchange_record( cls, robot_payload_enum: RobotPmsPaddingPayloadEnum, tls_version: TlsVersionEnum, modulus: int, exponent: int ) -> TlsRsaClientKeyExchangeRecord: """A client key exchange record with a hardcoded pre_master_secret...
java
public Observable<ServiceResponse<CertificatePolicy>> getCertificatePolicyWithServiceResponseAsync(String vaultBaseUrl, String certificateName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (certificat...
python
def project_top_dir(self, *args) -> str: """ Project top-level directory """ return os.path.join(self.project_dir, *args)
java
public boolean hasDiscriminator() { boolean hasDiscriminator = false; for (Entry<String, String> entry : _inputs.entrySet()) { String key = entry.getKey(); if (StagingData.STANDARD_LOOKUP_KEYS.contains(key)) continue; String value = entry.getValue()...
java
private static String urlencode( final String content, final Charset charset, final BitSet safechars, final boolean blankAsPlus) { if (content == null) { return null; } StringBuilder buf = new StringBuilder(); ByteBuffer bb = ch...
java
@JRubyMethod public static IRubyObject yaml_initialize(IRubyObject self, IRubyObject klass, IRubyObject ivars) { ((RubyObject)self).fastSetInstanceVariable("@class", klass); ((RubyObject)self).fastSetInstanceVariable("@ivars", ivars); return self; }
python
def get_distribute_verbatim_metadata(self): """Gets the metadata for the distribute verbatim rights flag. return: (osid.Metadata) - metadata for the distribution rights fields *compliance: mandatory -- This method must be implemented.* """ # Implemented from tem...
java
public void marshall(FulfillmentActivity fulfillmentActivity, ProtocolMarshaller protocolMarshaller) { if (fulfillmentActivity == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(fulfillmentActivity.ge...
java
@SuppressWarnings("SameParameterValue") private int getStatusCode(final byte[] response, final int request) throws UnknownResponseException { if (response == null || response.length < 3 || response[0] != OP_CODE_RESPONSE_CODE_KEY || response[1] != request || (response[2] != DFU_STATUS_SUCCESS && response[2] != S...
java
public StartExportTaskRequest withExportDataFormat(String... exportDataFormat) { if (this.exportDataFormat == null) { setExportDataFormat(new java.util.ArrayList<String>(exportDataFormat.length)); } for (String ele : exportDataFormat) { this.exportDataFormat.add(ele); ...
python
def has_started(self): """Tests if this assessment has begun. return: (boolean) - ``true`` if the assessment has begun, ``false`` otherwise *compliance: mandatory -- This method must be implemented.* """ assessment_offered = self.get_assessment_offered() ...
java
@Override public Object processTask(String taskName, Map<String, String[]> parameterMap) { if ("createAdmin".equalsIgnoreCase(taskName)) { return userService.createDefaultAdmin(); } return null; }
java
public Observable<ServiceResponse<Page<DatabaseInner>>> listByElasticPoolNextWithServiceResponseAsync(final String nextPageLink) { return listByElasticPoolNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<DatabaseInner>>, Observable<ServiceResponse<Page<DatabaseInner>>>>() ...
java
public void aget(Local<?> target, Local<?> array, Local<Integer> index) { addInstruction(new ThrowingInsn(Rops.opAget(target.type.ropType), sourcePosition, RegisterSpecList.make(array.spec(), index.spec()), catches)); moveResult(target, true); }
java
public static void unitize1(double[] x) { double n = norm1(x); for (int i = 0; i < x.length; i++) { x[i] /= n; } }
python
def create_response( self, data: dict = None, response: requests.Response = None, errors: list = None ) -> Response: """ Helper function to generate a :class:`~notifiers.core.Response` object :param data: The data that was used to send the notification :param response: :clas...
java
public void setTeamMembers(java.util.Collection<TeamMember> teamMembers) { if (teamMembers == null) { this.teamMembers = null; return; } this.teamMembers = new java.util.ArrayList<TeamMember>(teamMembers); }
java
public static InputStream getStream (String path, ClassLoader loader) { // first try the supplied class loader InputStream in = getResourceAsStream(path, loader); if (in != null) { return in; } // if that didn't work, try the system class loader (but only if it's...
java
private void processDependencies() throws MojoExecutionException { processDependency( getProject().getArtifact() ); AndArtifactFilter filter = new AndArtifactFilter(); // filter.add( new ScopeArtifactFilter( dependencySet.getScope() ) ); if ( dependencies != null && de...
python
def bitmap2RRlist(bitmap): """ Decode the 'Type Bit Maps' field of the NSEC Resource Record into an integer list. """ # RFC 4034, 4.1.2. The Type Bit Maps Field RRlist = [] while bitmap: if len(bitmap) < 2: warning("bitmap too short (%i)" % len(bitmap)) re...
java
public T getBand(int band) { if (band >= bands.length || band < 0) throw new IllegalArgumentException("The specified band is out of bounds: "+band); return bands[band]; }
python
def _clean_fields(self): """ Overriding the default cleaning behaviour to exit early on errors instead of validating each field. """ try: super(OAuthForm, self)._clean_fields() except OAuthValidationError, e: self._errors.update(e.args[0])
java
private static CmsXmlContainerPage getCache(CmsObject cms, CmsResource resource, boolean keepEncoding) { if (resource instanceof I_CmsHistoryResource) { return null; } return getCache().getCacheContainerPage( getCache().getCacheKey(resource.getStructureId(), keepEncoding...
java
public void marshall(DescribePlayerSessionsRequest describePlayerSessionsRequest, ProtocolMarshaller protocolMarshaller) { if (describePlayerSessionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.m...
python
def blog_following(self, blogname, **kwargs): """ Gets the publicly exposed list of blogs that a blog follows :param blogname: the name of the blog you want to get information on. eg: codingjester.tumblr.com :param limit: an int, the number of blogs you want re...
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.GSLJ__LINEJOIN: return getLINEJOIN(); } return super.eGet(featureID, resolve, coreType); }
python
def match_and(self, tokens, item): """Matches and.""" for match in tokens: self.match(match, item)
java
public Termination withCallingRegions(String... callingRegions) { if (this.callingRegions == null) { setCallingRegions(new java.util.ArrayList<String>(callingRegions.length)); } for (String ele : callingRegions) { this.callingRegions.add(ele); } return thi...
java
private synchronized void decreaseClientCount(Entry<K, V> entry) { Preconditions.checkNotNull(entry); Preconditions.checkState(entry.clientCount > 0); entry.clientCount--; }
java
@Indexable(type = IndexableType.REINDEX) @Override public CommerceShippingFixedOption addCommerceShippingFixedOption( CommerceShippingFixedOption commerceShippingFixedOption) { commerceShippingFixedOption.setNew(true); return commerceShippingFixedOptionPersistence.update(commerceShippingFixedOption); }
python
def get_valid_actions(self) -> List[Dict[str, Tuple[torch.Tensor, torch.Tensor, List[int]]]]: """ Returns a list of valid actions for each element of the group. """ return [state.get_valid_actions() for state in self.grammar_state]
python
def _validate_nullable(self, nullable, field, value): """ {'type': 'boolean'} """ if value is None: if not nullable: self._error(field, errors.NOT_NULLABLE) self._drop_remaining_rules( 'allowed', 'empty', 'forbidden'...
python
def maps_re_apply_policy_input_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_re_apply_policy = ET.Element("maps_re_apply_policy") config = maps_re_apply_policy input = ET.SubElement(maps_re_apply_policy, "input") rbridge...
python
def _fusion_to_json(self): """Convert this modification to a FUSION data dictionary. Don't use this without checking ``self.type == FUSION`` first. :rtype: dict """ if self.p5_reference: range_5p = fusion_range( reference=str(self.p5_referen...
java
public synchronized void startConsumers(Class<? extends Consumer> consumerClass) throws IOException { List<ConsumerHolder> consumerHolderSubList = filterConsumersForClass(consumerClass); enableConsumers(consumerHolderSubList); }
java
public JSONObject getLogs(int offset, int length) throws AlgoliaException { return getLogs(offset, length, LogType.LOG_ALL); }
python
def tangential_component(data_x, data_y, index='index'): r"""Obtain the tangential component of a cross-section of a vector field. Parameters ---------- data_x : `xarray.DataArray` The input DataArray of the x-component (in terms of data projection) of the vector field. data_y : `xa...
java
public CreateLoadBalancerRequest withSubnetMappings(SubnetMapping... subnetMappings) { if (this.subnetMappings == null) { setSubnetMappings(new java.util.ArrayList<SubnetMapping>(subnetMappings.length)); } for (SubnetMapping ele : subnetMappings) { this.subnetMappings.add...
java
@Override public void write(byte[] data, int offset, int length) throws IllegalStateException, IOException{ // validate state if (isClosed()) { throw new IllegalStateException("Serial connection is not open; cannot 'write()'."); } // write serial data to transmit buffer ...
java
@Override public boolean hasNext() { boolean hasNext = bundlesIterator.hasNext(); if (null != currentBundle && null != currentBundle.getExplorerConditionalExpression()) commentCallbackHandler.closeConditionalComment(); return hasNext; }
java
public void setProvider(Object pObj) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "setProvider pre: pObj(class)=" + pObj.getClass() + " isProxy=" + Proxy.isProxyClass(pObj.getClass()) + " provider=" + (provider==null?"null":provider.getClass()) + ...
java
public void output(PrintWriter out) { Map<String, Entry> entries = config.getSortedEntries(); if ( entries.isEmpty() ) { return; } ColumnPrinter printer = build(entries); out.println("Configuration Details"); printer.print(out); }
python
def from_lasio(cls, l, remap=None, funcs=None): """ Make a Location object from a lasio object. Assumes we're starting with a lasio object, l. Args: l (lasio). remap (dict): Optional. A dict of 'old': 'new' LAS field names. funcs (dict): Optional. A d...
java
public DeploymentExportResultInner exportTemplate(String resourceGroupName, String deploymentName) { return exportTemplateWithServiceResponseAsync(resourceGroupName, deploymentName).toBlocking().single().body(); }
python
def _ExtractPathSpecsFromFileSystem( self, path_spec, find_specs=None, recurse_file_system=True, resolver_context=None): """Extracts path specification from a file system within a specific source. Args: path_spec (dfvfs.PathSpec): path specification of the root of the file system. ...
java
@Override public E remove(int index) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; E oldValue = get(elements, index); int numMoved = len - index - 1; if (numMov...
java
static PublicKey parseRecord(int alg, byte [] data) { ByteArrayInputStream bytes = new ByteArrayInputStream(data); DataInputStream in = new DataInputStream(bytes); try { switch (alg) { case DNSSEC.RSAMD5: case DNSSEC.RSASHA1: case DNSSEC.RSA_NSEC3_SHA1: return parseRSA(in); case DNSSEC.DH: ret...
python
def existingInStore(cls, store, storeID, attrs): """Create and return a new instance from a row from the store.""" self = cls.__new__(cls) self.__justCreated = False self.__subinit__(__store=store, storeID=storeID, __everInserted=True) ...
java
public void addRemoveProduct(String source, String name, String value, boolean regex, Confidence confidence) { removeProduct.add(new EvidenceMatcher(source, name, value, regex, confidence)); }
java
private byte[] embiggen(byte[] b, int len) { if (b == null || b.length < len) { return new byte[len]; } else { return b; } }
java
public ArrayList<String> overTheBox_new_GET(String deviceId, String offer, String voucher) throws IOException { String qPath = "/order/overTheBox/new"; StringBuilder sb = path(qPath); query(sb, "deviceId", deviceId); query(sb, "offer", offer); query(sb, "voucher", voucher); String resp = exec(qPath, "GET", ...
python
def annotations(self, qname=True): """ wrapper that returns all triples for an onto. By default resources URIs are transformed into qnames """ if qname: return sorted([(uri2niceString(x, self.namespaces) ), (uri2niceString(y, self.namespace...
java
public List<Sentence> readString(String dataStr){ String [] lines = dataStr.split("\n"); List<Sentence> data = new ArrayList<Sentence>(); for (String line : lines){ Sentence sentence = new Sentence(); if (line.startsWith("#")) continue; StringTokenizer tk = new StringTokenizer(line, ...
java
@Override public GetCommandInvocationResult getCommandInvocation(GetCommandInvocationRequest request) { request = beforeClientExecution(request); return executeGetCommandInvocation(request); }
java
public static @Nullable String getSuffix(@NonNull View view) { return suffixes.get(view.getId()); }
python
def turbulent_Churchill_Zajic(Re, Pr, fd): r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [2]_ as developed in [1]_. Has yet to obtain popularity. .. math:: Nu = \left\{\left(\frac{Pr_T}{Pr}\right)\frac{1}{Nu_{di}} + \left[1-\left(\frac{Pr_T}{...
java
private ApiDoc getApiDoc(Class<?> controller, MethodDisplay displayMethodAs) { log.debug("Getting JSONDoc for class: " + controller.getName()); ApiDoc apiDoc = initApiDoc(controller); apiDoc.setSupportedversions(JSONDocApiVersionDocBuilder.build(controller)); apiDoc.setAuth(JSONDocApiAuthDocBuilder.getApiAuthD...
python
def tail(fpath, n=2, trailing=True): """ Alias for path_ndir_split """ return path_ndir_split(fpath, n=n, trailing=trailing)
python
def _create_aural_content_element(self, content, data_property_value): """ Create a element to show the content, only to aural displays. :param content: The text content of element. :type content: str :param data_property_value: The value of custom attribute used to ...
java
private List<File> loadFiles(File workingDir) { List<File> dataFile = new ArrayList<>(); if (workingDir.exists()) { File[] files = workingDir.listFiles(); for (File eachFile : files) { if (eachFile.isDirectory()) { dataFile.addAll(loadFiles(eac...
java
public static void iconComponent(Component component, UiIcon icon) { component.add(AttributeModifier.append("class", "ui-icon " + icon.getCssClass())); }
python
def _pfp__add_child(self, name, child, stream=None): """Add a child to the Union field :name: The name of the child :child: A :class:`.Field` instance :returns: The resulting field """ res = super(Union, self)._pfp__add_child(name, child) self._pfp__buff.seek(0, ...
python
def p_lconcat(self, p): 'lconcat : LBRACE lconcatlist RBRACE' p[0] = LConcat(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
java
public static JSONArray readJSONArray(File file, Charset charset) throws IORuntimeException { return parseArray(FileReader.create(file, charset).readString()); }
python
def roll(cls, num, sides, add): """Rolls a die of sides sides, num times, sums them, and adds add""" rolls = [] for i in range(num): rolls.append(random.randint(1, sides)) rolls.append(add) return rolls