language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def tooltip_ellipsis(source, length=0): ''' return the plain text representation of markdown encoded text. That is the texted without any html tags. If ``length`` is 0 then it will not be truncated.''' try: length = int(length) except ValueError: # invalid literal for int() return...
java
protected static GenericsType fullyResolve(GenericsType gt, Map<GenericsTypeName, GenericsType> placeholders) { GenericsType fromMap = placeholders.get(new GenericsTypeName(gt.getName())); if (gt.isPlaceholder() && fromMap != null) { gt = fromMap; } ClassNode type = fullyRes...
python
def fetch_from_pgdb(self, tables, cxn, limit=None, force=False): """ Will fetch all Postgres tables from the specified database in the cxn connection parameters. This will save them to a local file named the same as the table, in tab-delimited format, including a header. ...
python
def arguments(self, args=None): ''' Read in arguments for the current subcommand. These are added to the cmd line without '--' appended. Any others are redirected as standard options with the double hyphen prefixed. ''' # permits deleting elements rather than using slices...
java
public String onQueryOverCQL3(EntityMetadata m, Client client, MetamodelImpl metaModel, List<String> relations) { // select column will always be of entity field only! // where clause ordering Class compoundKeyClass = m.getIdAttribute().getBindableJavaType(); EmbeddableType compoundKey ...
python
def _datetime_to_epoch(self, dt): """Convert the datetime to unix epoch (properly).""" if dt: td = (dt - datetime.datetime.fromtimestamp(0, tzutc())) # don't use total_seconds(), that's only available in 2.7 total_secs = int((td.microseconds + ...
java
private void compileColumns() { log.debug("Compiling columns string: " + getColumns()); String[] chunks = JMeterPluginsUtils.replaceRNT(getColumns()).split("\\|"); log.debug("Chunks " + chunks.length); compiledFields = new int[chunks.length]; compiledVars = new int[chunks.length]...
java
@Override public TableIdx getJoinTableIdx(final SQLSelect _sqlSelect) throws EFapsException { final String linktoColName = this.attribute.getSqlColNames().get(0); final String tableName = ((SQLTable) getTable()).getSqlTable(); final Attribute joinAttr = this.attribute.getLink().g...
python
def __ProcessHttpResponse(self, method_config, http_response, request): """Process the given http response.""" if http_response.status_code not in (http_client.OK, http_client.CREATED, http_client.NO_CONTENT): ...
python
def __zip_file(self): """Get a file object of the FA zip file.""" if self.zip_path: # If using a local file, just open it: self.__print('Opening local zipfile: %s' % self.zip_path) return open(self.zip_path, 'rb') # Otherwise, download it and make a file obje...
java
void releaseId(Id id) { Integer pos = idPosMap.get(id); if (pos != null) { idPosMap.remove(id); freePositions.add(pos); for (HierarchicalTypeStore s : superTypeStores) { s.releaseId(id); } } }
java
private static Class checkClass(ProtoFile protoFile, TypeElement type, Map<String, String> mappedUniName, boolean isUniName) { String packageName = protoFile.packageName(); String defaultClsName = type.name(); // to check if has "java_package" option and "java_outer_classname" ...
python
def _do_strong_search(self, obj, recursive=True): """Search for the specific element *obj* within the node list. *obj* can be either a :class:`.Node` or a :class:`.Wikicode` object. If found, we return a tuple (*context*, *index*) where *context* is the :class:`.Wikicode` that contains ...
java
public static StringBuilder collectorConfigString(@NonNull String name, @NonNull CollectorBuilder builder) { StringBuilder buf = new StringBuilder() .append("collect ") .append(name); /* * Handle main argument. */ if (builder instanceof MainNone...
python
def _flds_append(flds, addthese, dont_add): """Retain order of fields as we add them once to the list.""" for fld in addthese: if fld not in flds and fld not in dont_add: flds.append(fld)
python
def reciprocal_grid(grid, shift=True, axes=None, halfcomplex=False): """Return the reciprocal of the given regular grid. This function calculates the reciprocal (Fourier/frequency space) grid for a given regular grid defined by the nodes:: x[k] = x[0] + k * s, where ``k = (k[0], ..., k[d-1])`...
java
public Matrix4f shadow(float lightX, float lightY, float lightZ, float lightW, float a, float b, float c, float d) { return shadow(lightX, lightY, lightZ, lightW, a, b, c, d, thisOrNew()); }
python
def create_pipeline_box(self, pipeline_key, name, **kwargs): '''Creates a box int the pipeline specified with the provided attributes. Args: name required name string kwargs {...} see StreakBox object for details return (status code, box dict) ''' #req sanity check if not (pipeline_key and name): ...
python
def list_mapping(html_cleaned): """将预处理后的网页文档映射成列表和字典,并提取虚假标题 Keyword arguments: html_cleaned -- 预处理后的网页源代码,字符串类型 Return: unit_raw -- 网页文本行 init_dict -- 字典的key是索引,value是网页文本行,并按照网页文本行长度降序排序 fake_title -- 虚假标题,即网页源代码<title>中的文本...
java
@NonNull @SuppressWarnings("unused") public ReportBuilder customData(@NonNull Map<String, String> customData) { this.customData.putAll(customData); return this; }
python
def send_request(self, method, action, body=None, headers=None, ipaddr=None): """Perform the HTTP request. The response is in either JSON format or plain text. A GET method will invoke a JSON response while a PUT/POST/DELETE returns message from the the server in pla...
python
def export_mesh(mesh, file_obj, file_type=None, **kwargs): """ Export a Trimesh object to a file- like object, or to a filename Parameters --------- file_obj : str, file-like Where should mesh be exported to file_type : str or None Represents file type (eg: 'stl') Returns -...
java
private String normalise(String str) { str = str.replaceAll("\\s+", " "); str = tc.toSimp(str); str = ChineseTrans.toHalfWidth(str); return str; }
python
def extract_response(self, extractors): """ extract value from requests.Response and store in OrderedDict. Args: extractors (list): [ {"resp_status_code": "status_code"}, {"resp_headers_content_type": "headers.content-type"}, ...
java
public static LocalVariableNode findLocalVariableNodeForInstruction(List<LocalVariableNode> lvnList, InsnList insnList, final AbstractInsnNode insnNode, int idx) { Validate.notNull(insnList); Validate.notNull(insnNode); Validate.isTrue(idx >= 0); int insnIdx = insnLi...
java
public static String getCacheBustedUrl(String url, ResourceReaderHandler rsReader, JawrConfig jawrConfig) throws IOException, ResourceNotFoundException { String checksum = getChecksum(url, rsReader, jawrConfig); String result = JawrConstant.CACHE_BUSTER_PREFIX; boolean generatedBinaryResource = jawrConfig.get...
python
def create_patch(self, patch_name): """Creates a patch based on the changes in the current repository. In case the specified patch *patch_name* already exists, ask the user to overwrite the patch. In case creating the patch was successful, all changes in the current repository are revert...
python
def set(cls, *anchors): """ Args: *anchors (str | unicode | list): Optional paths to use as anchors for short() """ cls.paths = sorted(flattened(anchors, split=SANITIZED | UNIQUE), reverse=True)
java
private void onMessageRead(MessageReadEvent event) { handler.post(() -> listener.onMessageRead(event)); log("Event published " + event.toString()); }
java
public static boolean isIntValue(final String value) { try { Integer.parseInt(value); return true; } catch (final NumberFormatException ex) { return false; } }
java
@Override public void foundGuaranteedNullDeref(@Nonnull Set<Location> assignedNullLocationSet, @Nonnull Set<Location> derefLocationSet, SortedSet<Location> doomedLocations, ValueNumberDataflow vna, ValueNumber refValue, @CheckForNull BugAnnotation variableAnnotation, ...
python
def _lookup_used_entity_id(self, file_details): """ Return the file_version_id associated with the path from file_details. The file_version_id is looked up from a dictionary in the activity. :param file_details: dict: response from DukeDS POST to /files/ :return: str: file_versio...
java
public JenkinsServer createJob(String jobName, String jobXml) throws IOException { return createJob(null, jobName, jobXml, false); }
python
def is_matching(cls, file_path): """ Return whether the given absolute file path is an ndata file. """ if file_path.endswith(".ndata") and os.path.exists(file_path): try: with open(file_path, "r+b") as fp: local_files, dir_files, eocd =...
python
def _compute_f5(self, C, pga_rock): """ Compute f5 term (non-linear soil response) """ return C['a10'] + C['a11'] * np.log(pga_rock + C['c5'])
java
public void populateLineString(LineString lineString, List<LatLng> latLngs) { for (LatLng latLng : latLngs) { Point point = toPoint(latLng, lineString.hasZ(), lineString.hasM()); lineString.addPoint(point); } }
python
def get(key, default=KeyError, merge=False, merge_nested_lists=None, delimiter=DEFAULT_TARGET_DELIM, pillarenv=None, saltenv=None): ''' .. versionadded:: 0.14 Attempt to retrieve the named value from :ref:`in-memory pillar data <pillar-in-memory>`. If the...
python
def _factln(num): # type: (int) -> float """ Computes logfactorial regularly for tractable numbers, uses Ramanujans approximation otherwise. """ if num < 20: log_factorial = log(factorial(num)) else: log_factorial = num * log(num) - num + log(num * (1 + 4 * num * ( 1...
java
private void paintRule(final Rule rule, final XmlStringBuilder xml) { if (rule.getCondition() == null) { throw new SystemException("Rule cannot be painted as it has no condition"); } paintCondition(rule.getCondition(), xml); for (Action action : rule.getOnTrue()) { paintAction(action, "ui:onTrue", xml);...
python
def draw(self): """ Draws the precision-recall curves computed in score on the axes. """ if self.iso_f1_curves: for f1 in self.iso_f1_values: x = np.linspace(0.01, 1) y = f1 * x / (2 * x - f1) self.ax.plot(x[y>=0], y[y>=0], colo...
java
public ValidatorType<TldTaglibType<T>> getOrCreateValidator() { Node node = childNode.getOrCreate("validator"); ValidatorType<TldTaglibType<T>> validator = new ValidatorTypeImpl<TldTaglibType<T>>(this, "validator", childNode, node); return validator; }
python
def generate(basename, xml): '''generate complete python implemenation''' if basename.endswith('.lua'): filename = basename else: filename = basename + '.lua' msgs = [] enums = [] filelist = [] for x in xml: msgs.extend(x.message) enums.extend(x.enum) ...
java
public StartBuildRequest withEnvironmentVariablesOverride(EnvironmentVariable... environmentVariablesOverride) { if (this.environmentVariablesOverride == null) { setEnvironmentVariablesOverride(new java.util.ArrayList<EnvironmentVariable>(environmentVariablesOverride.length)); } for ...
java
@Override public DataModelIF<U, I>[] split(final DataModelIF<U, I> data) { try { File dir = new File(outPath); if (!dir.exists()) { dir.mkdir(); } final FileWriter[] splits = new FileWriter[2 * nFolds]; for (int i = 0; i < nFolds; i...
python
def L_diffuser_inner(sed_inputs=sed_dict): """Return the inner length of each diffuser in the sedimentation tank. Parameters ---------- sed_inputs : dict A dictionary of all of the constant inputs needed for sedimentation tank calculations can be found in sed.yaml Returns -------...
java
@Override public boolean addAll(final int index, final Collection<? extends V> c) { return this.list.addAll(index, c); }
python
def create_assessment(self, assessment): """ To create Assessment :param assessment: Assessment """ raw_assessment = self.http.post('/Assessment', assessment) return Schemas.Assessment(assessment=raw_assessment)
python
def flush(self, meta=None): '''Flush all model keys from the database''' pattern = self.basekey(meta) if meta else self.namespace return self.client.delpattern('%s*' % pattern)
python
def zscore(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that Z-Scores each day's results. The Z-Score of a row is defined as:: (row - row.mean()) / row.stddev() If ``mask`` is supplied, ignore values where ``mask`` returns False when compu...
python
def noclip(args): """ %prog noclip bamfile Remove clipped reads from BAM. """ p = OptionParser(noclip.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) bamfile, = args noclipbam = bamfile.replace(".bam", ".noclip.bam") cmd = "samt...
java
public double randInverseCDF() { final double a0 = 2.50662823884; final double a1 = -18.61500062529; final double a2 = 41.39119773534; final double a3 = -25.44106049637; final double b0 = -8.47351093090; final double b1 = 23.08336743743; final double b2 = -21.0622...
python
def timeout_at(clock, 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 an a...
python
def update(self, redraw=True): """redraw interface""" # get the main urwid.Frame widget mainframe = self.root_widget.original_widget # body if self.current_buffer: mainframe.set_body(self.current_buffer) # footer lines = [] if self._notificat...
java
public Map<ComponentJob, AnalyzerResult> getUnsafeResultElements() { if (_unsafeResultElements == null) { _unsafeResultElements = new LinkedHashMap<>(); final Map<ComponentJob, AnalyzerResult> resultMap = _analysisResult.getResultMap(); for (final Entry<ComponentJob, Analyzer...
java
public static void writeToFile(byte[] catalogBytes, File file) throws IOException { JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(file)); JarInputStream jarIn = new JarInputStream(new ByteArrayInputStream(catalogBytes)); JarEntry catEntry = null; JarInputStreamReader...
python
def is_class_file(filename): """ checks whether the given file is a Java class file, by opening it and checking for the magic header """ with open(filename, "rb") as fd: c = fd.read(len(JAVA_CLASS_MAGIC)) if isinstance(c, str): # Python 2 c = map(ord, c) ret...
python
def media(request, path, hproPk=None): """Ask the server for a media and return it to the client browser. Forward cache headers""" if not settings.PIAPI_STANDALONE: (plugIt, baseURI, _) = getPlugItObject(hproPk) else: global plugIt, baseURI try: (media, contentType, cache_contr...
java
int estimateFieldValueSize(int accessor) { int size = 0; try { if (jmfPart.isPresent(accessor)) { size = jmfPart.estimateUnassembledValueSize(accessor); } } catch (JMFException e) { FFDCFilter.processException(e, "estimateFieldValueSize", "221", this); if (TraceComponent....
python
def find_repo_by_name(name, repo_dir=None): """ Searches the given repo name inside the repo_dir (will use the config value 'template_repos' if no repo dir passed), will rise an exception if not found Args: name (str): Name of the repo to search repo_dir (str): Directory where to se...
python
def create_constraints(self, courses): """Internal use. Creates all constraints in the problem instance for the given courses. """ for i, course1 in enumerate(courses): for j, course2 in enumerate(courses): if i <= j: continue ...
java
public static float calculateMaxTextHeight(Paint _Paint, String _Text) { Rect height = new Rect(); String text = _Text == null ? "MgHITasger" : _Text; _Paint.getTextBounds(text, 0, text.length(), height); return height.height(); }
python
def _update_data(self, data): # type: (Any) -> Dict[str, List] """Set our data and notify any subscribers of children what has changed Args: data (object): The new data Returns: dict: {child_name: [path_list, optional child_data]} of the change t...
python
def send(kwargs, opts): ''' Send an email with the data ''' opt_keys = ( 'smtp.to', 'smtp.from', 'smtp.host', 'smtp.port', 'smtp.tls', 'smtp.username', 'smtp.password', 'smtp.subject', 'smtp.gpgowner', 'smtp.content', ) ...
python
def get_credentials_from_env(): """Get credentials from environment variables. Preference of credentials is: - No credentials if DATASTORE_EMULATOR_HOST is set. - Google APIs Signed JWT credentials based on DATASTORE_SERVICE_ACCOUNT and DATASTORE_PRIVATE_KEY_FILE environments variables - Google Applicati...
java
private void writeToFile(MemoryCommitResult mcr) { // Rename the current file so it may be used as a backup during the next read if (mFile.exists()) { if (!mcr.changesMade) { // If the file already exists, but no changes were // made to the underlying map, it'...
java
public void marshall(TagOptionDetail tagOptionDetail, ProtocolMarshaller protocolMarshaller) { if (tagOptionDetail == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(tagOptionDetail.getKey(), KEY_BIND...
python
def control_high_limit(self) -> Optional[Union[int, float]]: """ Control high limit setting for a special sensor. For LS-10/LS-20 base units only. """ return self._get_field_value(SpecialDevice.PROP_CONTROL_HIGH_LIMIT)
python
def _RegisterFlagByModule(self, module_name, flag): """Records the module that defines a specific flag. We keep track of which flag is defined by which module so that we can later sort the flags by module. Args: module_name: A string, the name of a Python module. flag: A Flag object, a fla...
java
public SearchResults query(WaybackRequest wbRequest) throws ResourceIndexNotAvailableException, ResourceNotInArchiveException, BadQueryException, AccessControlException { return index.query(wbRequest); }
java
@Nonnull public static <T> JPAExecutionResult <T> createFailure (@Nullable final Exception ex) { return new JPAExecutionResult <> (ESuccess.FAILURE, null, ex); }
java
@Override public void onClose( @Nonnull final WebSocket webSocket, final boolean wasClean, final int code, @Nullable final String reason ) { }
python
async def get_xy_address(self, xy): '''Get address of the agent residing in *xy* coordinate, or ``None`` if no such agent is in this multi-environment. ''' manager_addr = self.get_xy_environment(xy) if manager_addr is None: return None else: r_agen...
python
def _exclusion_indices_for_range(self, start_idx, end_idx): """ Returns ------- List of tuples of (start, stop) which represent the ranges of minutes which should be excluded when a market minute window is requested. """ itree = self._minute_exclusion_tree ...
java
protected void updateRepositoryPolicy(RepositoryPolicy value, String xmlTag, Counter counter, Element element) { boolean shouldExist = value != null; Element root = updateElement(counter, element, xmlTag, shouldExist); if (shouldExist) { Counter innerCount = new Counter(counter.getDe...
java
public void resetAllFiltersForWebApp(String resourceGroupName, String siteName) { resetAllFiltersForWebAppWithServiceResponseAsync(resourceGroupName, siteName).toBlocking().single().body(); }
python
def RemoveClientLabels(self, client_id, owner, labels, cursor=None): """Removes a list of user labels from a given client.""" query = ("DELETE FROM client_labels " "WHERE client_id = %s AND owner_username_hash = %s " "AND label IN ({})").format(", ".join(["%s"] * len(labels))) arg...
python
def prepare(self): """ Reorganizes the data such that the deployment logic can find it all where it expects to be. The raw configuration file is intended to be as human-friendly as possible partly through the following mechanisms: - In order to minimize repetition, ...
java
public <RET> RET save(final Object iContent, OPERATION_MODE iMode, final ORecordCallback<? extends Number> iCallback) { return (RET) save(iContent, null, iMode, iCallback); }
java
public void endDocument() throws IOException { checkAndPop(JsonTokenType.BEGIN_DOCUMENT); if (isArray) { writer.endArray(); } else { writer.endObject(); } }
java
public void uncheckTypes(Collection<String> types) { for (String type : types) { CmsListItem item = (CmsListItem)m_scrollList.getItem(type); if (item != null) { item.getCheckBox().setChecked(false); } } }
java
private static int getYearInCycle(int cycleNumber, long dayOfCycle) { Integer[] cycles = getAdjustedCycle(cycleNumber); if (dayOfCycle == 0) { return 0; } if (dayOfCycle > 0) { for (int i = 0; i < cycles.length; i++) { if (dayOfCycle < cycles[i].i...
java
protected void addListeners() { // Listen for result changes, including the one we monitor context.addResultListener(this); context.addVisualizationListener(this); // Listen for database events only when needed. if(task.has(UpdateFlag.ON_DATA)) { context.addDataStoreListener(this); } }
python
def git_remote(git_repo): """Return the URL for remote git repository. Depending on the system setup it returns ssh or https remote. """ github_token = os.getenv(GITHUB_TOKEN_KEY) if github_token: return 'https://{0}@github.com/{1}'.format( github_token, git_repo) return 'gi...
java
public final Map<String, Set<String>> getExtensionMimeMap() throws OSException { initializeMimeExtensionArrays(); return Collections.unmodifiableMap(extensionMime); }
java
public Resource withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
python
def get_version_info(self, key_name='ver_sw_release'): """ get the (major, minor, patch, type) version information as tuple. Returns None if not found definition of type is: >= 0: development >= 64: alpha version >= 128: beta version >= 192: RC version...
python
def revoke_sudo_privileges(request): """ Revoke sudo privileges from a request explicitly """ request._sudo = False if COOKIE_NAME in request.session: del request.session[COOKIE_NAME]
java
public void putLocal(final Props p) { for (final String key : p.localKeySet()) { this.put(key, p.get(key)); } }
python
def load_param(params, ctx=None): """same as mx.model.load_checkpoint, but do not load symnet and will convert context""" if ctx is None: ctx = mx.cpu() save_dict = mx.nd.load(params) arg_params = {} aux_params = {} for k, v in save_dict.items(): tp, name = k.split(':', 1) ...
java
public Content getMemberTree(Content memberTree, boolean isLastContent) { if (isLastContent) return HtmlTree.UL(HtmlStyle.blockListLast, memberTree); else return HtmlTree.UL(HtmlStyle.blockList, memberTree); }
python
def load_parameters(self, filename, ctx=None, allow_missing=False, ignore_extra=False): """Load parameters from file previously saved by `save_parameters`. Parameters ---------- filename : str Path to parameter file. ctx : Context or list of C...
java
void write(ByteCodeWriter out) throws IOException { out.write(ConstantPool.CP_INTEGER); out.writeInt(_value); }
python
def readerForDoc(cur, URL, encoding, options): """Create an xmltextReader for an XML in-memory document. The parsing flags @options are a combination of xmlParserOption. """ ret = libxml2mod.xmlReaderForDoc(cur, URL, encoding, options) if ret is None:raise treeError('xmlReaderForDoc() failed') ret...
python
def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT): """ Execute a command with 'command', check the result code and throw an appropriate FatalError if it fails. Returns the "result" of a successful command. """ val, data = self.com...
java
private static <K, V> void makeSetsImmutable(Map<K, Set<V>> map) { Set<K> keys = map.keySet(); for (K key : keys) { Set<V> value = map.get(key); map.put(key, Collections.unmodifiableSet(value)); } }
java
@Override public void beginExport() { if (m_emf == null) { m_emf = Persistence.createEntityManagerFactory(m_persistenceUnitName); } m_em = m_emf.createEntityManager(); }
java
@Override protected void preparePaintComponent(final Request request) { if (!isInitialised()) { // Defaults rbsSelect.setSelected(WDataTable.SelectMode.NONE); rbsSelectAll.setSelected(WDataTable.SelectAllType.NONE); rbsExpand.setSelected(WDataTable.ExpandMode.NONE); rbsPaging.setSelected(WDataTable.Pa...
java
static public List<String> interpretPath(String path) throws Exception { if( null == path ) { throw new Exception("path parameter should not be null"); } if( path.codePointAt(0) == '/' ) { throw new Exception("absolute path is not acceptable"); } // Verify path List<String> pathFragments = new Vector...
java
long refreshAndGetTotal() { long total = 0; for (ResultSubpartition part : partition.getAllPartitions()) { total += part.unsynchronizedGetNumberOfQueuedBuffers(); } return total; }
java
@Nonnull public static FileIOError copyDirRecursive (@Nonnull final File aSourceDir, @Nonnull final File aTargetDir) { ValueEnforcer.notNull (aSourceDir, "SourceDirectory"); ValueEnforcer.notNull (aTargetDir, "TargetDirectory"); // Does the source directory exist? if (!FileHelper.existsDir (aSource...