language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static double diffNormF(DMatrixD1 a , DMatrixD1 b ) { if( a.numRows != b.numRows || a.numCols != b.numCols ) { throw new IllegalArgumentException("Both matrices must have the same shape."); } final int size = a.getNumElements(); DMatrixRMaj diff = new DMatrixRMaj...
java
public void marshall(RemoveTagsFromCertificateRequest removeTagsFromCertificateRequest, ProtocolMarshaller protocolMarshaller) { if (removeTagsFromCertificateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMar...
java
public Canvas draw (Drawable image, float x, float y) { return draw(image, x, y, image.width(), image.height()); }
java
public AnnotationTypeElementDoc wrap(AnnotationTypeElementDoc source) { if (source == null || source instanceof Proxy<?> || !(source instanceof AnnotationTypeElementDocImpl)) { return source; } return new AnnotationTypeElementDocWrapper((AnnotationTypeElementDocImpl) source); }
java
@SuppressWarnings("unchecked") @Override public Boolean execute() { validateCommand(); User sender = CommandUtil.getSfsUser(user, api); sender = sender != null ? sender : newFakeUser(); ISFSObject params = createResponseParams(); getRequestHandler().handleClientRequest(se...
python
def find(self, *args, **kwargs): """collection find method """ wrapper = kwargs.pop('wrapper', False) if wrapper is True: return self._wrapper_find(*args, **kwargs) return self.__collect.find(*args, **kwargs)
python
def _get_or_create_student_item(student_item_dict): """Gets or creates a Student Item that matches the values specified. Attempts to get the specified Student Item. If it does not exist, the specified parameters are validated, and a new Student Item is created. Args: student_item_dict (dict): ...
python
def collect_assets(result, force=False): """collect assets from meta file Collecting assets only when the metafile is updated. If number of assets are decreased, assets are reset and re-collect the assets. """ path_name = result.path_name info_path = os.path.join(path_name, summary.CHAINERUI_AS...
python
def start_redis(node_ip_address, redirect_files, port=None, redis_shard_ports=None, num_redis_shards=1, redis_max_clients=None, redirect_worker_output=False, password=None, use_credis=None, ...
python
def setCursorSize(self, p): 'sets width based on diagonal corner p' self.cursorBox = BoundingBox(self.cursorBox.xmin, self.cursorBox.ymin, p.x, p.y) self.cursorBox.w = max(self.cursorBox.w, self.canvasCharWidth) self.cursorBox.h = max(self.cursorBox.h, self.canvasCharHeight)
python
def nack(self, id, subscription, transaction=None, receipt=None): """ Let the server know that a message was not consumed. :param str id: the unique id of the message to nack :param str subscription: the subscription this message is associated with :param str transaction: includ...
java
private String buildObjectKey(final Object object) { String objectKey = null; final Class<?> objectClass = object.getClass(); final KeyGenerator typeGenerator = objectClass.getAnnotation(KeyGenerator.class); if (typeGenerator == null) { objectKey = generateAggregated...
python
def _restoreItemFromArchive(self): """Callback for item menu.""" if self._current_item is None: return dp = getattr(self._current_item, '_dp', None) if dp and dp.archived: dp.restore_from_archive(parent=self)
java
@FFDCIgnore(NullPointerException.class) protected void addLibraryFile(File f) { if (!!!f.exists()) { if (tc.isWarningEnabled()) { Tr.warning(tc, "cls.library.archive", f, new FileNotFoundException(f.getName())); } return; } // Skip files ...
java
@Override public HTCashbillJobState getJobState(String CorpNum, String JobID, String UserID) throws PopbillException { if ( JobID.length() != 18 ) throw new PopbillException(-99999999, "작업아이디가 올바르지 않습니다."); return httpget("/HomeTax/Cashbill/" + JobID + "/State", CorpNum, UserID, HTCashbillJobState.class); }
python
def leaf_asts(self): """ Return an iterator over the leaf ASTs. """ seen = set() ast_queue = deque([self]) while ast_queue: ast = ast_queue.pop() if isinstance(ast, Base) and id(ast.cache_key) not in seen: seen.add(id(ast.cache_ke...
java
public AnnSchema getSchema(final Class<? extends Ann> klass) { for (AnnSchema ann : annSchemas) if (ann.getKlass().equals(klass)) return ann; return null; }
java
public static boolean isVisarganta(String str) { Log.logInfo(" Checking if is_visarganta:::"); String s1 = VarnaUtil.getAntyaVarna(str); if(isVisarga(s1) ) return true; return false; }
python
def who_has(self, subid): """Return a list of names who own subid in their id range set.""" answer = [] for name in self.__map: if subid in self.__map[name] and not name in answer: answer.append(name) return answer
java
public final AbstractItem _findById(long itemID) throws SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "_findById", Long.valueOf(itemID)); AbstractItem item = null; AbstractItemLink itemLink = getLink(itemID);...
python
def create_project(self, name, description): """ Create a project with the specified name and description :param name: str: unique name for this project :param description: str: long description of this project :return: str: name of the project """ self._cache_pro...
python
def pycache_clean(context): "Remove __pycache__ directories" #pylint: disable=unused-argument dirs = set() for root, dirnames, _ in os.walk(os.curdir): if '__pycache__' in dirnames: dirs.add(os.path.join(root, '__pycache__')) print("Removing __pycache__ directories") rmrf(dir...
java
@Pure public static BusLayerDrawerType getPreferredLineDrawAlgorithm() { final Preferences prefs = Preferences.userNodeForPackage(BusLayerConstants.class); if (prefs != null) { final String algo = prefs.get("DRAWING_ALGORITHM", null); //$NON-NLS-1$ if (algo != null && algo.length() > 0) { try { retu...
python
def write_name(self, name): """Writes a domain name to the packet""" try: # Find existing instance of this name in packet # index = self.names[name] except KeyError: # No record of this name already, so write it # out as normal, record...
python
def _readue(self, pos): """Return interpretation of next bits as unsigned exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ oldpos = pos try: while not self[pos]: pos += 1 ...
python
def pack_epub(directory, file): """Pack the given ``directory`` into an epub (i.e. zip) archive given as ``file``, which can be a file-path or file-like object. """ with zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED) as zippy: base_path = os.path.abspath(directory) for root, dirs, file...
python
def load_files(self, path): """ Loads files in a given path and all its subdirectories """ if self.verbose == 2: print("Indexing {}".format(path)) for filename in os.listdir(path): file_path = path + "/" + filename if os.path.isdir(file_pat...
java
public void stem(CoreLabel label, Class<? extends CoreAnnotation<String>> ann) { String lemma = lemmatize(label.word(), label.tag(), lexer, lexer.option(1)); label.set(ann, lemma); }
python
def secured_apps_copy(self, apps): """ Given the http app list of a website, return what should be in the secure version """ return [[app_name, path] for app_name, path in apps if app_name not in (self.LETSENCRYPT_VERIFY_APP_NAME,)]
java
public WrappedByteBuffer putLongAt(int index, long v) { _checkForWriteAt(index, 8); _buf.putLong(index, v); return this; }
python
def request_control(self, device_id, access_mode=True): """ Request exclusive control of device :param device_id: id of device :type device_id: int :param access_mode: True=exclusive, False=shared :type access_mode: bool :returns: true if successful :rtyp...
java
private void releaseExtractionGuard(ExtractionGuard extractionLatch) { synchronized( extractionsLock ) { extractionLocks.remove( extractionLatch.path ); } extractionLatch.completionLatch.countDown(); }
java
public static boolean[] toPrimitive(Boolean[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_BOOLEAN_ARRAY; } final boolean[] result = new boolean[array.length]; for (int i = 0; i < array.length; i++) { ...
java
public List<CompletionItem> resolve(String filter, int startOffset, int caretOffset) { final Set<ElementHandle<TypeElement>> result = classpath.getClassIndex().getDeclaredTypes("", ClassIndex.NameKind.PREFIX, EnumSet.of(ClassIndex.SearchScope.SOURCE)); List<CompletionItem> ret = new ArrayList<>(); ...
python
def read(self, size=None): """Reads a byte string from the file-like object at the current offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: size (Optional[int]): number of bytes to read, where None is all re...
java
public static String getLabel(FacesContext context, UIComponent comp) { Object o = comp.getAttributes().get("label"); if (o == null || (o instanceof String && ((String) o).length() == 0)) { ValueExpression vex = comp.getValueExpression("label"); if (null != vex) return (String) vex.getValue(context.getELC...
java
@Override public String generateId() { UUID uuid = UUID.randomUUID(); StringBuilder sb = new StringBuilder(); sb.append(Long.toHexString(uuid.getMostSignificantBits())); sb.append(Long.toHexString(uuid.getLeastSignificantBits())); while (sb.length() < 32) { sb.a...
java
@Override public String getValue(int index) { if (index < 0 || index >= attributesList.size()) { return null; } return attributesList.get(index).value; }
python
def block(self, to_block): """ The method serves for imposing a constraint forbidding the hitting set solver to compute a given hitting set. Each set to block is encoded as a hard clause in the MaxSAT problem formulation, which is then added to the underlying orac...
python
def add_user_to_group(self, user_name, group_name): """Adds a user to a group. :param user_name: name of user to be added :param group_name: name of group user is to be added to :returns: True if user added :raises: HTTPResponseError in case an HTTP error status was returned ...
python
def id_to_piece(input, model_file=None, model_proto=None, name=None): """Converts vocabulary id into piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `model_pro...
java
void removeAll(BaseRow sortKey) { Collection<BaseRow> list = treeMap.get(sortKey); if (list != null) { currentTopNum -= list.size(); treeMap.remove(sortKey); } }
java
public Map<String, Object> serialize() { Map<String, Object> serverInfo = new HashMap<String, Object>(); serverInfo.put("totalCount", totalCount); serverInfo.put("cursor", cursor); serverInfo.put("serviceName", serviceName); serverInfo.put("columnNames", columns); s...
java
private Schema readMap(JsonReader reader, Set<String> knownRecords) throws IOException { return Schema.mapOf(readInnerSchema(reader, "keys", knownRecords), readInnerSchema(reader, "values", knownRecords)); }
python
def GetGroupUUID(group,alias=None,location=None): """Given a group name return the unique group ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param group: group name """ if alias is None: alias = clc.v1.Acc...
java
@SuppressWarnings("unchecked") public static List<Node> selectNodes(Node node, String xpathQuery, Map<String, String> namespaceUris) { XPath xpath = DocumentHelper.createXPath(xpathQuery); xpath.setNamespaceURIs(namespaceUris); return xpath.selectNodes(node); }
python
def join(self, glue=" "): """ Javascript's join implementation """ j = glue.join([str(x) for x in self.obj]) return self._wrap(j)
java
public static LocalCall<String> mkdir(String path, String mode) { return mkdir(path, Optional.empty(), Optional.empty(), Optional.of(mode)); }
java
private List getXmlContentResourceTypes() { // get all available resource types and filter XML content resource types List resTypes = OpenCms.getResourceManager().getResourceTypes(); Iterator i = resTypes.iterator(); List resTypeNames = new ArrayList(resTypes.size()); while (i.h...
python
def ichunk(iterable, n): """ Split an iterable into n-sized chunks. """ it = iter(iterable) while True: chunk = tuple(itertools.islice(it, n)) if not chunk: return yield chunk
python
def currentAbove(requestContext, seriesList, n): """ Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the metrics whose value is above N at the end of the time period specified. Example:: &target=currentAbove(server*.instance*.thread...
python
def make_encoded_file_url_and_params(file_service, share, file_dir, file_name, sas_token, safe=SAFE_CHARS): """ Makes the file url using the service. Converts the file directory and name into byte-strings if needed and returns (url, dir, file) as a tuple. This is needed to account for string encoding differ...
java
private void initialize() { this.setTitle(Constant.messages.getString("cfu.manage.title")); //this.setContentPane(getJTabbed()); this.setContentPane(getTopPanel()); this.pack(); centerFrame(); state = State.IDLE; // Handle escape key to close the dialog...
python
def age_to_BP(age, age_unit): """ Convert an age value into the equivalent in time Before Present(BP) where Present is 1950 Returns --------- ageBP : number """ ageBP = -1e9 if age_unit == "Years AD (+/-)" or age_unit == "Years Cal AD (+/-)": if age < 0: age = age+1 ...
java
public static KeyPair generateKeyPair(String jcaAlgorithmName, String jcaProviderName, SignatureAlgorithm alg, SecureRandom random) { Assert.notNull(alg, "SignatureAlgorithm argument cannot be null."); Assert.isTrue(alg.isEllipticCurve(), "SignatureAlgorithm arg...
java
public String transformMessage(String strXML, StreamSource streamTransformer) { Reader reader = new StringReader(strXML); StreamSource source = new StreamSource(reader); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); try { ...
java
public static CmsDocumentDependency load(CmsObject cms, CmsPublishedResource pubRes) { CmsDocumentDependency result = readFromContext(cms, pubRes.getRootPath()); if (result == null) { result = new CmsDocumentDependency(pubRes); result.readDependencies(cms); } ret...
java
public static <T1, T2, R> BiFunction biFunction(final BiFunction<T1, T2, R> lambda) { return lambda; }
python
def get_followers(self, first_user_id=None): """ 获取关注者列表 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=获取关注者列表 :param first_user_id: 可选。第一个拉取的OPENID,不填默认从头开始拉取 :return: 返回的 JSON 数据包 """ params = {"access_token": self.token} if first_user_id: ...
python
def Servers(self,cached=True): """Returns list of server objects, populates if necessary. >>> clc.v2.Servers(["NY1BTDIPHYP0101","NY1BTDIWEB0101"]).Servers() [<clc.APIv2.server.Server object at 0x1065b0d50>, <clc.APIv2.server.Server object at 0x1065b0e50>] >>> print _[0] NY1BTDIPHYP0101 """ if not hasat...
java
@Override public boolean isPunctuationWord(String str) { return chineseCommaAcceptFilter().accept(str) || chineseEndSentenceAcceptFilter().accept(str) || chineseDouHaoAcceptFilter().accept(str) || chineseQuoteMarkAcceptFilter().accept(str) || chineseParenthesisAcceptFilter().accept(str) || chineseColonAcceptFil...
java
@SuppressWarnings("unchecked") @Override public EList<IfcComplexPropertyTemplate> getPartOfComplexTemplate() { return (EList<IfcComplexPropertyTemplate>) eGet( Ifc4Package.Literals.IFC_PROPERTY_TEMPLATE__PART_OF_COMPLEX_TEMPLATE, true); }
python
def _build_full_list(self): """Build a full list of pages. Examples: >>> _SlicedPaginator(1, 7, 5)._build_full_list() [1, 2, 3, 4, 5] >>> _SlicedPaginator(6, 7, 5)._build_full_list() [3, 4, 5, 6, 7] >>> _SlicedPaginator(6, 7, 5)._build_full_list() ...
java
@Override public void process( T image ) { // initialize data structures this.image = image; this.stopRequested = false; modeLocation.reset(); modeColor.reset(); modeMemberCount.reset(); interpolate.setImage(image); pixelToMode.reshape(image.width, image.height); quickMode.reshape(image.width, ima...
python
def setValidityErrorHandler(self, err_func, warn_func, arg=None): """ Register error and warning handlers for Schema validation. These will be called back as f(msg,arg) """ libxml2mod.xmlSchemaSetValidErrors(self._o, err_func, warn_func, arg)
java
public String resolveReposUrl() throws IOException { // Zur Zeit nur für HTTP implementiert. try { URL url; // TODO: Schön machen try { url = new URL(defaultRepositoryUrl); } catch (MalformedURLException e) { url = new File(defaultRepositoryUrl).toURI().toURL(); } if (!url.getProtocol().e...
python
def invoke_ssh_shell(cls, *args, **kwargs): """invoke_ssh(arguments..., pty=False, echo=False) Star a new shell on a remote server. It first calls :meth:`Flow.connect_ssh` using all positional and keyword arguments, then calls :meth:`SSHClient.invoke_shell` with the pty / echo o...
java
public Range<T> extend(T value) { if (value == null) throw new IllegalArgumentException("value must not be null"); return extend(value, value); }
python
def compare(node1, node2): """Compares two Werkzeug hg versions.""" if not os.path.isdir("a"): print("error: comparison feature not initialized", file=sys.stderr) sys.exit(4) print("=" * 80) print("WERKZEUG INTERNAL BENCHMARK -- COMPARE MODE".center(80)) print("-" * 80) def _hg...
python
def main(): """Main function""" parser = argparse.ArgumentParser() parser.add_argument('-u', '--username', required=True, help='EBox account') parser.add_argument('-p', '--password', required=True, help='Password') parser.add_argument('-j', '--json', a...
python
def load_projections(folder, indices=None): """Load geometry and data stored in Mayo format from folder. Parameters ---------- folder : str Path to the folder where the Mayo DICOM files are stored. indices : optional Indices of the projections to load. Accepts advanced index...
java
public void insertParentAfter(Node node) throws ChildNodeException { if (node != null) { // give this node my children node.setFirstChild(getFirstChild()); setFirstChild(null); // clear our list addChild(node); // make our child } }
java
public Surface draw (Tile tile, float x, float y) { return draw(tile, x, y, tile.width(), tile.height()); }
python
def realimag_files(xscript=0, yscript="d[1]+1j*d[2]", eyscript=None, exscript=None, paths=None, g=None, **kwargs): """ This will load a bunch of data files, generate data based on the supplied scripts, and then plot the ydata's real and imaginary parts versus xdata. Parameters ---------- xscrip...
python
def acquire(self, timeout=0, force=False): """Attempt to acquire an exclusive lock on this record. If a timeout is given (in seconds) then the acquire call will block for up to that much time attempting to acquire the lock. If the lock can not be acquired (either because it is already set or we time out) a Loc...
java
public boolean isEncodedWith(Encoder encoder, CharSequence string) { return getIdentityHashCodesForEncoder(encoder).contains(System.identityHashCode(string)); }
python
def close(self, wait=False): """Close session, shutdown pool.""" self.session.close() self.pool.shutdown(wait=wait)
python
def _level_coords(self): """Return a mapping of all MultiIndex levels and their corresponding coordinate name. """ level_coords = OrderedDict() for name, index in self.indexes.items(): if isinstance(index, pd.MultiIndex): level_names = index.names ...
java
public PreparedStatement getPreparedQuery(Query query, String storeName) { String tableName = storeToCQLName(storeName); return m_statementCache.getPreparedQuery(tableName, query); }
java
public int doAfterBody() { if(bodyContent != null) { _appender.append(bodyContent.getString()); bodyContent.clearBody(); } /* this loop exists so that the table is filled out correctly up to the specified or guessed table dimensions. this is a litt...
java
public Observable<Page<FeatureResultInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<FeatureResultInner>>, Page<FeatureResultInner>>() { @Override public Page<FeatureResultInner> call(ServiceResponse<Page<FeatureResultInn...
python
def confd_state_loaded_data_models_data_model_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") loaded_data_models = ET.SubElement(confd_state, "loaded...
python
def get_node(self, index): """ Returns the Node at given index. :param index: Index. :type index: QModelIndex :return: Node. :rtype: AbstractCompositeNode or GraphModelNode """ if not index.isValid(): return self.__root_node return in...
python
def breaks(self, frame, no_remove=False): """Return True if there's a breakpoint at frame""" for breakpoint in set(self.breakpoints): if breakpoint.breaks(frame): if breakpoint.temporary and not no_remove: self.breakpoints.remove(breakpoint) ...
java
protected static String getArray(List<String> paths) { StringBuilder builder = new StringBuilder(); for (String s : paths) { if (builder.length() == 0) { builder.append(s); } else { builder.append(",").append(s); } } r...
java
protected static Invocable resolveJavaMethod( Class<?> clas, String name, Class<?>[] types, boolean staticOnly ) throws UtilEvalError { if ( clas == null ) throw new InterpreterError("null class"); Invocable method = BshClassManager.memberCache .get(c...
java
@Override public EClass getIfcNumericMeasure() { if (ifcNumericMeasureEClass == null) { ifcNumericMeasureEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(847); } return ifcNumericMeasureEClass; }
python
def get_model_file(name, root=os.path.join(base.data_dir(), 'models')): r"""Return location for the pretrained on local file system. This function will download from online model zoo when model cannot be found or has mismatch. The root directory will be created if it doesn't exist. Parameters ----...
python
def leaves_not_empty(self): """ Return the list of leaves not empty in the tree rooted at this node, in DFS order. :rtype: list of :class:`~aeneas.tree.Tree` """ return [n for n in self.dfs if ((n.is_leaf) and (not n.is_empty))]
java
public static Properties getEnvVariables() throws EnvironmentException { if( isUnix() ) { return getUnixShellVariables(); } if( isWindows() ) { return getWindowsShellVariables(); } String message = "Environment operations not s...
python
def setup(app): """Setup.""" # add_html_theme is new in Sphinx 1.6+ if hasattr(app, 'add_html_theme'): theme_path = get_html_theme_path()[0] app.add_html_theme('bootstrap', os.path.join(theme_path, 'bootstrap'))
python
def get_extra_info(self, name, default=None): """Return transport specific data. The following fields are available, in addition to the information exposed by :meth:`Transport.get_extra_info`. ====================== =============================================== Name ...
java
public Integer getSubscriptionsCount(final QueryParams params) { FluentCaseInsensitiveStringsMap map = doHEAD(Subscription.SUBSCRIPTION_RESOURCE, params); return Integer.parseInt(map.getFirstValue(X_RECORDS_HEADER_NAME)); }
java
private Observable<Indexable> processCompletedTaskAsync(final TaskGroupEntry<TaskItem> completedEntry, final InvocationContext context) { reportCompletion(completedEntry); if (isRootEntry(completedEntry)) { return Observable.empty()...
java
public PagedList<SecretItem> listSecretVersions(final String vaultBaseUrl, final String secretName, final Integer maxresults) { return getSecretVersions(vaultBaseUrl, secretName, maxresults); }
java
protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception { // Make sure that we have received at least a short long available = buf.readableBytes(); // Length of control message is 10. // Minimum length of a task message is 6(short taskId, i...
python
def clean_comment(self): """ If COMMENTS_ALLOW_PROFANITIES is False, check that the comment doesn't contain anything in PROFANITIES_LIST. """ comment = self.cleaned_data["text"] if settings.COMMENTS_ALLOW_PROFANITIES is False: bad_words = [w for w in settings....
java
public boolean remove(V value) { // peek at what is in the map K key = value.getKey(); Ref<V> ref = map.get(key); // only try to remove the mapping if it matches the provided class loader return (ref != null && ref.get() == value) ? map.remove(key, ref) : false; }
python
def autopilot_version_send(self, capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid, force_mavlink1=False): ''' Version and capability of autopilot software ...
java
public boolean contains(Right right) { if (isFull) { return true; } if (right.isFull) { return false; } if (!containsRights(isFullSelect, selectColumnSet, right.selectColumnSet, right.isFullSelect)) { return false...