language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public List<Epic> getEpics(Object groupIdOrPath, Integer authorId, String labels, EpicOrderBy orderBy, SortOrder sortOrder, String search, int page, int perPage) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm(page, perPage) .withParam("author_id", authorId) ...
python
def filter(self, predicate: Callable[[FileLine], 'FileLineSet'] ) -> 'FileLineSet': """ Returns a subset of the file lines within this set that satisfy a given filtering criterion. """ filtered = [fileline for fileline in self if predicate(fileline)]...
python
def onchange_partner_id(self): ''' When you change partner_id it will update the partner_invoice_id, partner_shipping_id and pricelist_id of the hotel folio as well --------------------------------------------------------------- @param self: object pointer ''' if ...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.CPI__RG: getRg().clear(); return; } super.eUnset(featureID); }
python
def set_basic_params( self, workers=None, zerg_server=None, fallback_node=None, concurrent_events=None, cheap_mode=None, stats_server=None, quiet=None, buffer_size=None, fallback_nokey=None, subscription_key=None, emperor_command_socket=None): """ :param int workers: ...
python
def level(self, level, time=0): """(Helper) Set light to specified level""" if level <= 0: self._elk.send(pf_encode(self._index)) elif level >= 98: self._elk.send(pn_encode(self._index)) else: self._elk.send(pc_encode(self._index, 9, level, time))
python
async def get_offers(connection: Connection) -> dict: """ Retrieves all pending credential offers for a given connection. :param connection: A connection handle :return: A list of dictionary objects representing offers from a given connection. Example: credential = await ...
python
def get(self, select): """ :param select: the variable to extract from list :return: a simple list of the extraction """ if is_list(select): return [(d[s] for s in select) for d in self.data] else: return [d[select] for d in self.data]
python
def inject_print_functions(module_name=None, module_prefix='[???]', DEBUG=False, module=None): """ makes print functions to be injected into the module """ module = _get_module(module_name, module) if SILENT: def print(*args): """ silent builtins.print ...
java
public static String formatMillis(double theMillis) { StringBuilder buf = new StringBuilder(20); if (theMillis > 0.0 && theMillis < 1.0) { buf.append(getSubMillisecondMillisFormat().format(theMillis)); buf.append("ms"); } else if (theMillis < (10 * DateUtils.MILLIS_PER_SECOND)) { buf.append((int) theMill...
java
public static int count(String keyword, String srcText) { int count = 0; int leng = srcText.length(); int j = 0; for (int i = 0; i < leng; i++) { if (srcText.charAt(i) == keyword.charAt(j)) { j++; if (j == keyword.length...
java
public DescribeMetricCollectionTypesResult withGranularities(MetricGranularityType... granularities) { if (this.granularities == null) { setGranularities(new com.amazonaws.internal.SdkInternalList<MetricGranularityType>(granularities.length)); } for (MetricGranularityType ele : granu...
python
def search(self, terms): """ Seraches the documents for the inputed terms. :param terms :return [{'url': <str>, 'title': <str>', 'strength': <int>}] """ # load the search information if not self._searchurls: base = se...
python
def expand_effect_repertoire(self, new_purview=None): """See |Subsystem.expand_repertoire()|.""" return self.subsystem.expand_effect_repertoire( self.effect.repertoire, new_purview)
python
def getSolutions(self): """ Find and return all solutions to the problem Example: >>> problem = Problem() >>> problem.getSolutions() == [] True >>> problem.addVariables(["a"], [42]) >>> problem.getSolutions() [{'a': 42}] @return: All sol...
python
def _pad_data(self, index_len): """ Pad the data in Series with [None] to ensure that data is the same length as index :param index_len: length of index to extend data to :return: nothing """ self._data.extend([None] * (index_len - len(self._data)))
java
public KieBaseModel removeKieSessionModel(String qName) { Map<String, KieSessionModel> newMap = new HashMap<String, KieSessionModel>(); newMap.putAll( this.kSessions ); newMap.remove(qName); setKSessions(newMap); return this; }
java
@Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); if(model.getObject().size() > 0) tag.append("class", "has-error", " "); }
python
def start(self): """Clone objects from one container to another. This method was built to clone a container between data-centers while using the same credentials. The method assumes that an authentication token will be valid within the two data centers. """ LOG.info('Cl...
python
def run(argv=None): """Main CLI entry point.""" cli = InfrascopeCLI() return cli.run(sys.argv[1:] if argv is None else argv)
python
def tcex_json(self): """Return tcex.json file contents.""" file_fqpn = os.path.join(self.app_path, 'tcex.json') if self._tcex_json is None: if os.path.isfile(file_fqpn): try: with open(file_fqpn, 'r') as fh: self._tcex_json ...
java
@Override public int advance(int target) throws IOException { resetQueue(); Integer newTarget = target; do { newTarget = advanceToDoc(newTarget); } while (newTarget != null); return docId; }
python
def register(conf, conf_admin, **options): """ Register a new admin section. :param conf: A subclass of ``djconfig.admin.Config`` :param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin`` :param options: Extra options passed to ``django.contrib.admin.site.register`` """ assert issubcl...
java
public void add(final byte[] buf, final int offset, final int len) { segments.add(new BufferSegment(buf, offset, len)); total_length += len; }
java
@Override public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> env) throws Exception { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); // ----------------------------------------------------------------------- // Is obj ...
java
public int read(long fileOffset, byte []buffer, int offset, int length) throws IOException { log.info("random-read(0x" + Long.toHexString(fileOffset) + "," + length + ")"); return _file.read(fileOffset, buffer, offset, length); }
java
public static IntPoint Add(IntPoint point1, IntPoint point2) { IntPoint result = new IntPoint(point1); result.Add(point2); return result; }
java
public ApiResponse<Void> getHandshakeWithHttpInfo() throws ApiException { com.squareup.okhttp.Call call = getHandshakeValidateBeforeCall(null, null); return apiClient.execute(call); }
python
def lzs (inlist): """ Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist) """ zscores = [] for item in inlist: zscores.append(z(inlist,item)) return zscores
python
def get_bottom_up_likelihood(tree, character, frequencies, sf, kappa=None, is_marginal=True, model=F81): """ Calculates the bottom-up likelihood for the given tree. The likelihood for each node is stored in the corresponding feature, given by get_personalised_feature_name(feature, BU_LH). :param mo...
python
def add_data_point_xy(self, x, y): """Add a new data point to the data set to be smoothed.""" self.x.append(x) self.y.append(y)
java
private static ClassLoader getBootstrapClassLoader() { if (BOOTSTRAP_CLASSLOADER == null) { synchronized(ClassLoaderUtil.class) { if (BOOTSTRAP_CLASSLOADER == null) { ClassLoader cl = null; if (System.getSecurityManager() != null) { ...
python
def _verify(self, token): """Verify that the given token is valid. :param str token: The API token to verify. :returns: The token's corresponding user model as a dict, or None if invalid. :rtype: dict """ # Attempt to authenticate. url = '{}{}/'.format(self._url,...
java
public void renderSoapHeader(final Map<String, String> context, final Result result) { renderSoapHeader(RESULT_MARSHALLER, context, result); }
java
private void processAssignments(ProjectType project) { List<ResourceAssignmentType> assignments = project.getResourceAssignment(); for (ResourceAssignmentType row : assignments) { Task task = m_projectFile.getTaskByUniqueID(mapTaskID(row.getActivityObjectId())); Resource resource ...
python
def build_js(): ''' Build BokehJS files (CSS, JS, etc) under the ``bokehjs`` source subdirectory. Also prints a table of statistics about the generated assets (file sizes, etc.) or any error messages if the build fails. Note this function only builds BokehJS assets, it does not install them in...
java
@SuppressWarnings("unchecked") public static Container create(Application application) throws IllegalAccessException, InstantiationException { String provider = (String) application.getProperty("container.provider"); logger.debug(Messages.get("info.container.provider", provider)); try { ...
python
def api_ebuio_forum(request, key=None, hproPk=None): """Create a topic on the forum of the ioproject. EBUIo only !""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden if settings.PIAPI_STANDALONE: return HttpResponse(json.dumps({'error': 'no-on-ebuio'}), content_typ...
python
def _run_toolkit_function(fnname, arguments, args, kwargs): """ Dispatches arguments to a toolkit function. Parameters ---------- fnname : string The toolkit function to run arguments : list[string] The list of all the arguments the function takes. args : list The ...
python
def xmlFile(path, mode='r'): """lxml cannot parse XML files starting with a BOM (see http://www.w3.org/TR/2000/REC-xml-20001006 in F.1.) In case such XML file is used, we must skip these characters So we open all XML files for read with 'xmlFile'. TODO: File this issue to lxml ML or tracker (feature...
python
def from_bytes(cls, xbytes: bytes) -> 'BlsEntity': """ Creates and Bls entity from bytes representation. :param xbytes: Bytes representation of Bls entity :return: BLS entity intance """ logger = logging.getLogger(__name__) logger.debug("BlsEntity::from_bytes: >>>...
java
public static final void log(Class<?> clazz, String msg) { if (DEBUG) { System.out.println("[" + sSdf.format(new Date()) + "]" + "-" + "[" + clazz.getSimpleName() + "] " + msg); } }
java
public synchronized Iterator idIterator() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "idIterator"); final LinkedList<Integer> linkedList = new LinkedList<Integer>(); final Iterator iterator = table.values().iterator(); while(iterator.hasNext()) ...
java
public static int writeInt(OutputStream target, int value) throws IOException { target.write(value >>> 24); target.write(value >>> 16); target.write(value >>> 8); target.write(value); return Integer.BYTES; }
python
def read_plink(file_prefix, verbose=True): r"""Read PLINK files into Pandas data frames. Parameters ---------- file_prefix : str Path prefix to the set of PLINK files. It supports loading many BED files at once using globstrings wildcard. verbose : bool ``True`` for progress...
python
def export_node(self, n) -> Dict[str, Union[str, List[str]]]: """ Return dict suitable for exporting to JSON. Args: n: A dict representing the data in a networkx AnalysisGraph node. Returns: The node dict with additional fields for name, units, dtype, and ar...
python
def bodfnd(body, item): """ Determine whether values exist for some item for any body in the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/bodfnd_c.html :param body: ID code of body. :type body: int :param item: Item to find ("RADII", "NUT_AMP_RA", etc.). :type i...
python
def commentless(data): """ Generator that removes from a list of strings the double dot reStructuredText comments and its contents based on indentation, removing trailing empty lines after each comment as well. """ it = iter(data) while True: line = next(it) while ":" in line...
python
def account_representative(self, account): """ Returns the representative for **account** :param account: Account to get representative for :type account: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.account_representative( ... account="xrb_39a73oy5...
java
public ActionResponse performMonologue(ActionRuntime runtime) { final RuntimeException cause = runtime.getFailureCause(); RuntimeException translated = null; try { translateException(cause); } catch (RuntimeException e) { translated = e; } final Ru...
java
public static InputStream convertOutputStreamToInputStream(OutputStream outputStream) { byte[] data = ((ByteArrayOutputStream) outputStream).toByteArray(); return new ByteArrayInputStream(data); }
python
def create_binary_array(self, key, value): """Create method of CRUD operation for binary array data. Args: key (string): The variable to write to the DB. value (any): The data to write to the DB. Returns: (string): Result of DB write. """ dat...
java
public String getStdFormatPattern(Locale locale) { return Timezone.NAME_PROVIDER.getStdFormatPattern((this.total == 0) && (this.fraction == 0), locale); }
python
def delete_case(self, case_obj): """Delete a case from the database Args: case_obj (puzzle.models.Case): initialized case model """ for ind_obj in case_obj.individuals: self.delete_individual(ind_obj) logger.info("Deleting case {0} from database".format(c...
java
@SafeVarargs public static void enableBundles(final Class<? extends GuiceyBundle>... bundles) { final String prop = Joiner.on(',').join(toStrings(Lists.newArrayList(bundles))); System.setProperty(BUNDLES_PROPERTY, prop); }
python
def _sort_lines(self): """Haproxy writes its logs after having gathered all information related to each specific connection. A simple request can be really quick but others can be really slow, thus even if one connection is logged later, it could have been accepted before others that are...
java
public void setPendingActions(java.util.Collection<String> pendingActions) { if (pendingActions == null) { this.pendingActions = null; return; } this.pendingActions = new com.amazonaws.internal.SdkInternalList<String>(pendingActions); }
java
public S setParameters(Map<String, String> parameters) { if (this.parameters == null) { this.parameters = new ConcurrentHashMap<String, String>(); } this.parameters.putAll(parameters); return castThis(); }
python
def random_cidr_mask(lowest_mask=16): """ Function to generate a random CIDR value :param lowest_mask: An integer value for the lowest mask you want it to generate :return: A string of a random CIDR mask """ if lowest_mask < 33: return str(__random.randran...
java
public Observable<ServiceResponse<StorageBundle>> getStorageAccountWithServiceResponseAsync(String vaultBaseUrl, String storageAccountName) { if (vaultBaseUrl == null) { throw new IllegalArgumentException("Parameter vaultBaseUrl is required and cannot be null."); } if (storageAccount...
java
public SetPlatformApplicationAttributesRequest withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
java
public void addTask(ReceivedMessageTask task) { tasks.add(task); Packet packet = task.getPacket(); // don't run the deadlock guard if timeout is <= 0 if (packet.getExpirationTime() > 0L) { // run a deadlock guard so hanging tasks will be interrupted task.runDeadlo...
java
private Method findResolver(Class type) throws IOException { List<Method> resolvers = Util.filter(Index.list(CLIResolver.class, Jenkins.get().getPluginManager().uberClassLoader), Method.class); for ( ; type!=null; type=type.getSuperclass()) for (Method m : resolvers) if (m.ge...
python
def multivariate_ess_precision(nmr_params, multi_variate_ess, alpha=0.05): r"""Calculate the precision given your multivariate Effective Sample Size. Given that you obtained :math:`ESS` multivariate effective samples in your estimate you can calculate the precision with which you approximated your desired ...
java
public static String base64Encode(String plainTextString) { String encoded = new String(Base64.getEncoder().encode(plainTextString.getBytes())); return encoded; }
java
protected void printLog(String msg, Object...args) { printLogStatic(this.getClass().getSimpleName(), msg, args); }
java
public static boolean isSimpleValueType(Class<?> clazz) { return isBasicType(clazz) // || clazz.isEnum() // || CharSequence.class.isAssignableFrom(clazz) // || Number.class.isAssignableFrom(clazz) // || Date.class.isAssignableFrom(clazz) // || clazz.equals(URI.class) // || clazz.equals(...
python
def _BuildStations(self, stoplist): """Dispatches the best algorithm for calculating station line position. Args: # Class Stop is defined in transitfeed.py stoplist: [Stop, Stop, ...] # Class Trip is defined in transitfeed.py triplist: [Trip, Trip, ...] Returns: # One integer...
python
def moveListItem(L, fromidx, toidx): "Move element within list `L` and return element's new index." r = L.pop(fromidx) L.insert(toidx, r) return toidx
java
public List<SovereigntyMapResponse> getSovereigntyMap(String datasource, String ifNoneMatch) throws ApiException { ApiResponse<List<SovereigntyMapResponse>> resp = getSovereigntyMapWithHttpInfo(datasource, ifNoneMatch); return resp.getData(); }
java
protected void save(final String fileName, final SessionListener callback) { Thread t = new Thread(new Runnable() { @Override public void run() { Exception thrownException = null; try { save(fileName); } catch (Ex...
python
def launchDashboardOverlay(self, pchAppKey): """ Launches the dashboard overlay application if it is not already running. This call is only valid for dashboard overlay applications. """ fn = self.function_table.launchDashboardOverlay result = fn(pchAppKey) retur...
java
@Override public void introspect(PrintWriter writer) { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); introspectUptime(runtime, writer); introspectVendorVersion(runtime, writer); introspectInputArguments(runtime, writer); Map<String, String> props = introspect...
python
def get_blen_array(data, blen=None): """Try to guess a reasonable block length to use for block-wise iteration over `data`.""" if blen is None: if hasattr(data, 'chunklen'): # bcolz carray return data.chunklen elif hasattr(data, 'chunks') and \ hasa...
python
def child_removed(self, child): """ Reset the item cache when a child is removed """ super(AbstractItemView, self).child_removed(child) self.get_member('_items').reset(self)
java
public void setValue(Object value) { if (value instanceof Iterable<?>) { this.value = stream((Iterable<?>) value).map(this::toValue).collect(toList()); } else { this.value = toValue(value); } }
java
public static String getOracleWkt(final String wkt) { final String oracleWkt; // Strings longer than 4000 characters need to be converted to CLOBs. if (wkt.length() > 4000) { oracleWkt = "' || " + convertToClob(wkt) + " || '"; } else { oracleWkt = wkt; } ret...
python
def login_remove(login, **kwargs): ''' Removes an login. CLI Example: .. code-block:: bash salt minion mssql.login_remove LOGINNAME ''' try: conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() cur.execute("DROP LOGIN [{0}]".format...
java
public static PrettyTime of(Locale locale) { PrettyTime ptime = LANGUAGE_MAP.get(locale); if (ptime == null) { ptime = new PrettyTime( locale, SystemClock.INSTANCE, NUMBER_SYMBOLS.getZeroDigit(locale), ...
java
static String pad(final String data, final char doPadWithThis, final int totalWidth, final Alignment orientation) { final String pad = repeat(new String(new char[]{doPadWithThis}), Math.max(0, totalWidth - data.length())); String returnVal = ""; if (orientation == null) { returnVal ...
python
def rpc_fix_code_with_yapf(self, source, directory): """Formats Python code to conform to the PEP 8 style guide. """ source = get_source(source) return fix_code_with_yapf(source, directory)
java
@Override protected void dumpData(PrintWriter pw) { DateFormat df = new SimpleDateFormat("HH:mm:ss"); pw.println(" [Data"); for (Object item : m_data) { pw.println(" " + df.format((Date) item)); } pw.println(" ]"); }
java
@Override public SchemaManager getSchemaManager(Map<String, Object> puProperties) { if (schemaManager == null) { initializePropertyReader(); setExternalProperties(puProperties); schemaManager = new RethinkDBSchemaManager(RethinkDBClientFactory.class.getName(),...
java
public void setFailedItems(java.util.Collection<ResourceKey> failedItems) { if (failedItems == null) { this.failedItems = null; return; } this.failedItems = new com.amazonaws.internal.SdkInternalList<ResourceKey>(failedItems); }
java
public SQLiteDatabase openWritableDatabase() { lockDb.lock(); try { if (sqliteHelper == null) createHelper(options); status.set(TypeStatus.READ_AND_WRITE_OPENED); if (openCounter.incrementAndGet() == 1) { // open new write database if (database == null) { sqliteHelper.setWriteAheadLoggin...
java
public synchronized void switchProject(String projectName) throws SDKException { try { this.projectId = getProjectIdForProjectName(projectName); // Set the agents to null so that no outdated agent is returned resetAgents(); } catch (SDKException e) { throw new SDKException( "Co...
python
def queryMany(self, query, args): """ Executes a series of the same Insert Statments Each tuple in the args list will be applied to the query and executed. This is the equivilant of MySQLDB.cursor.executemany() @author: Nick Verbeck @since: 9/7/2008 """ self.lastError = None self.affectedRows = ...
python
def _build_split_filenames(self, split_info_list): """Construct the split filenames associated with the split info. The filenames correspond to the pre-processed datasets files present in the root directory of the dataset. Args: split_info_list: (list[SplitInfo]) List of split from which generat...
java
public IPreferenceStore getWritablePreferenceStore(Object context) { if (this.preferenceStore == null) { this.preferenceStore = getPreferenceStoreAccess().getWritablePreferenceStore(context); } return this.preferenceStore; }
python
def update_configuration(self, environment_id, configuration_id, name, description=None, conversions=None, enrichments=None, ...
python
def find_elements_by_name(self, name): """ Finds elements by name. :Args: - name: The name of the elements to find. :Returns: - list of webelement - a list with elements if any was found. an empty list if not :Usage: :: ...
java
public Observable<ComputePolicyInner> createOrUpdateAsync(String resourceGroupName, String accountName, String computePolicyName, CreateOrUpdateComputePolicyParameters parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, computePolicyName, parameters).map(new Func1<Service...
java
public boolean remove(P model) { if (null == model) return false; boolean removed = false; if (presentationModels.containsValue(model)) { removePresentationModelByType(model); presentationModels.remove(model.getId()); for (A attribute : model.getAttributes()) ...
python
def deps_tree(self): """Package dependencies image map file """ dependencies = self.dependencies + [self.name] if self.repo == "sbo": for dep in dependencies: deps = Requires(flag="").sbo(dep) if dep not in self.deps_dict.values(): ...
java
public byte[] init(byte[] key){ keySize = key.length; byte[] iv = new byte[keySize]; new SecureRandom().nextBytes(iv); init(iv, key); return iv; }
java
static boolean isAlphabetic(final int codePoint) { return ((1 << Character.UPPERCASE_LETTER | 1 << Character.LOWERCASE_LETTER | 1 << Character.TITLECASE_LETTER | 1 << Character.MODIFIER_LETTER | 1 << Character.OTHER_LETTER | 1 << Character.LETTER_NUMBER) >> Character .getType(codePoint) & 1) != 0...
java
@Deprecated public IssueRelation createRelation(Integer issueId, Integer issueToId, String type) throws RedmineException { return new IssueRelation(transport, issueId, issueToId, type) .create(); }
python
def is_correct(self): """Check if this object configuration is correct :: * Check our own specific properties * Call our parent class is_correct checker :return: True if the configuration is correct, otherwise False :rtype: bool """ state = True cls = se...
java
public static Histogram constantRangeHistogram(Histogram hist, Map<String, ConstantRange> cRanges) { if (Double.compare(hist.recordsOutput(), 1.0) < 0) return new Histogram(hist.fields()); Histogram crHist = new Histogram(hist); for (String fld : cRanges.keySet()) { Collection<Bucket> crBkts = ne...
java
public static PageFlowStack get( HttpServletRequest request, ServletContext servletContext, boolean createIfNotExist ) { StorageHandler sh = Handlers.get( servletContext ).getStorageHandler(); HttpServletRequest unwrappedRequest = PageFlowUtils.unwrapMultipart( request ); RequestContext rc =...