language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static double QuasiEuclidean(double x1, double y1, double x2, double y2) { if (Math.abs(x1 - x2) > Math.abs(y1 - y2)) { return Math.abs(x1 - x2) + (Constants.Sqrt2 - 1) * Math.abs(y1 - y2); } return (Constants.Sqrt2 - 1) * Math.abs(x1 - x2) + Math.abs(y1 - y2); }
java
public static CPDefinitionLink findByPrimaryKey(long CPDefinitionLinkId) throws com.liferay.commerce.product.exception.NoSuchCPDefinitionLinkException { return getPersistence().findByPrimaryKey(CPDefinitionLinkId); }
python
def stats(args): """Create stats from the analysis """ logger.info("Reading sequeces") data = parse_ma_file(args.ma) logger.info("Get sequences from sam") is_align = _read_sam(args.sam) is_json, is_db = _read_json(args.json) res = _summarise_sam(data, is_align, is_json, is_db) _write...
java
@Override public void exportNode( Node node, ContentHandler contentHandler, boolean skipBinary, boolean noRecurse ) throws RepositoryException, SAXException { ExecutionContext executionContext = session.context(); J...
python
def apply(self, q, bindings, ordering, distinct=None): """ Sort on a set of field specifications of the type (ref, direction) in order of the submitted list. """ info = [] for (ref, direction) in self.parse(ordering): info.append((ref, direction)) table, column = ...
java
@BetaApi public final SecurityPolicy getSecurityPolicy(String securityPolicy) { GetSecurityPolicyHttpRequest request = GetSecurityPolicyHttpRequest.newBuilder().setSecurityPolicy(securityPolicy).build(); return getSecurityPolicy(request); }
java
public void buildAnnotationTypeFieldsSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters[VisibleMemberMap.ANNOTATION_TYPE_FIELDS]; VisibleMemberMap visibleMemberMap = visibleMemberMaps[VisibleMemberMap.ANNOTATION_TYPE_FIELD...
python
def get_variation_for_rollout(self, rollout, user_id, attributes=None): """ Determine which experiment/variation the user is in for a given rollout. Returns the variation of the first experiment the user qualifies for. Args: rollout: Rollout for which we are getting the variation. user_id: ID f...
java
public static Node objectlit(Node ... propdefs) { Node objectlit = new Node(Token.OBJECTLIT); for (Node propdef : propdefs) { switch (propdef.getToken()) { case STRING_KEY: case MEMBER_FUNCTION_DEF: case GETTER_DEF: case SETTER_DEF: case SPREAD: case COMPUTE...
java
public static String showBufferContents(WsByteBuffer buffers[]) { if (null == buffers || 0 == buffers.length) { return "null"; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < buffers.length; i++) { sb.append("Buffer ["); sb.append(i); ...
java
public static Function<Node, String> toDotFunction() { return new Function<Node, String>() { @Override public String apply(Node input) { return input.toDot(); } }; }
python
def get_gitdir(self): """Determine the git repository for this request""" if self.gitlookup is None: raise tornado.web.HTTPError(500, 'no git lookup configured') gitdir = self.gitlookup(self.request) if gitdir is None: raise tornado.web.HTTPError(404, 'unable to ...
java
public <R> EtcdResponsePromise<R> send(final EtcdRequest<R> etcdRequest) throws IOException { ConnectionState connectionState = new ConnectionState(uris, lastWorkingUriIndex); if (etcdRequest.getPromise() == null) { etcdRequest.setPromise(new EtcdResponsePromise<R>( etcdRequest.getRetryPolicy(), ...
java
public synchronized List<Analysis> analyze(String word) { requireValidHandle(); List<Analysis> analysisList = new ArrayList<Analysis>(); if (!isValidInput(word)) { return analysisList; } Libvoikko lib = getLib(); Pointer cAnalysisList = lib.voikko...
java
@Configurable public void setSourceExtension(String ext) throws ConfigException { if (! ext.startsWith(".")) throw new ConfigException(L.l("source-extension '{0}' must begin with '.'", ext)); _sourceExt = ext; }
java
public static String addEncodedPaths(String p1, String p2) { if (p1 == null || p1.length() == 0) { if (p1 != null && p2 == null) return p1; return p2; } if (p2 == null || p2.length() == 0) return p1; int split = p1.indexOf(';'); ...
python
def target_key(self, key): """Temporarily retarget the client for one call to route specifically to the one host that the given key routes to. In that case the result on the promise is just the one host's value instead of a dictionary. .. versionadded:: 1.3 """ ...
python
def change_password(self, user, password, send_email=None): """ Service method to change a user's password. Sends signal `password_changed`. :param user: The :class:`User`'s password to change. :param password: The new password. :param send_email: Whether or not to over...
python
def update_uid_state(self, id_or_uri, refresh_state_data): """ Sets the unit identification (UID) light state of the specified power delivery device. The device must be an HP iPDU component with a locator light (HP Intelligent Load Segment, HP AC Module, HP Intelligent Outlet Bar, or HP ...
python
def _print_help(self): """ Help is automatically generated from the __doc__ of the subclass if present and from the names of the args of run(). Therefore args names selection is more important than ever here ! """ options = self._print_usage('\n ', file=sys.stdout) ...
python
def _lowfreq_linear_filter(tumor_index, is_paired): """Linear classifier for removing low frequency false positives. Uses a logistic classifier based on 0.5% tumor only variants from the smcounter2 paper: https://github.com/bcbio/bcbio_validations/tree/master/somatic-lowfreq The classifier uses stran...
python
def search_json_log(filepath, key, value): """Search json log file for a key=value pair. :param filepath: Valid path to a json file :param key: key to match :param value: value to match :returns: First matching line in json log file, parsed by :py:func:`json.loads` """ try: with ope...
java
public T withOutgoingPayload(Map<String, ByteBuffer> outgoingPayload) { getOptions().setOutgoingPayLoad(Optional.of(outgoingPayload)); return getThis(); }
python
def thread_stopped(self): """ :meth:`.WThreadTask._polling_iteration` implementation """ if self.__current_task is not None: task = self.__task_chain[self.__current_task] task.stop() self.__current_task = None
java
public void unlock(Locker locker) { // All access to the lockTable must be synchronized, even just checking // the size. Since this method is for a transaction and not a bean // type, it is difficult to tell when no Option A caching has been // involved. The performance impact shou...
java
private static void setLevel(ArrayList level) { _syncLevel = nextLevel(); if (_syncLevel == _syncLevels.size()) { _syncLevels.add(level); } else { _syncLevels.set(_syncLevel, level); } }
python
def get_host_uuid(self): """Request host UUID of the server. :returns: the host UUID of the server :raises: IloConnectionError if failed connecting to the iLO. """ xml = self._request_host() root = etree.fromstring(xml) data = self._elementtree_to_dict(root) ...
java
private static String formatUTCDateAsLocalDateTime(Date javaDate) { // Now back from start of day in UTC to LocalDateTime to express that we don't know the // timezone. LocalDateTime localDateTime = javaDate.toInstant().atZone(UTC).toLocalDateTime(); // And format to string return localDateTime.toSt...
java
public void saveGroupcontainer( final CmsGroupContainer groupContainer, final CmsGroupContainerElementPanel groupContainerElement) { if (getGroupcontainer() != null) { CmsRpcAction<CmsGroupContainerSaveResult> action = new CmsRpcAction<CmsGroupContainerSaveResult>() { ...
java
public static java.util.List<com.liferay.commerce.discount.model.CommerceDiscount> getCommerceDiscountsByUuidAndCompanyId( String uuid, long companyId, int start, int end, com.liferay.portal.kernel.util.OrderByComparator<com.liferay.commerce.discount.model.CommerceDiscount> orderByComparator) { return getService(...
java
public static double calculateNthMoment( double[] values, int validValues, double mean, double momentOrder, IHMProgressMonitor pm ) { double moment = 0.0; double n = 0.0; if (momentOrder == 1.0) { for( int i = 0; i < validValues; i++ ) { if (!isNovalue(va...
java
private static RetryDeterminer<IOException> createSocketErrorRetryDeterminer( final ApiErrorExtractor errorExtractor) { return new RetryDeterminer<IOException>() { @Override public boolean shouldRetry(IOException e) { return errorExtractor.socketError(e); } }; }
java
public void setLevel(@NonNull LogLevel level) { if (level == null) { throw new IllegalArgumentException("level cannot be null."); } if (logLevel == level) { return; } logLevel = level; setCallbackLevel(level); }
python
async def load(self, request): """Load session from cookies.""" if SESSION_KEY not in request: session = Session(self.cfg.secret, key=self.cfg.session_cookie, max_age=self.cfg.max_age, domain=self.cfg.domain) session.load(request.cookies) ...
python
def scan_to_graph(python_modules, graph, ignore=tuple()): """ Scans `python_modules` with :py:func:`scan` and registers found providers in `graph`. `ignore` argument is passed through to :py:func:`scan`. """ def callback(specification, provider): graph.register_provider(specification, p...
java
void build_feature_space() { kFormInFeaturespace = 0; kNilForm = forms_alphabet.idOf(SpecialOption.NIL); kFeatureSpaceEnd = forms_alphabet.size(); kPostagInFeaturespace = kFeatureSpaceEnd; kNilPostag = kFeatureSpaceEnd + postags_alphabet.idOf(SpecialOption.NIL); kFea...
python
def get_contents(self, element): """ Retrieve the contents of an element :param element: The XML Element object :type element: etree._Element :return: A list of responses :rtype : list of Response """ return [Response(self.trigger, child, self.file_path)...
java
@ObjectiveCName("formatContentTextWithSenderId:withContentType:withText:withRelatedUid:withIsChannel:") public String formatContentText(int senderId, ContentType contentType, String text, int relatedUid, boolean isChannel) { String groupKey = isChannel ? "channels" : "gr...
java
public void setOutputStream(FLACOutputStream fos) { if(fos == null) throw new IllegalArgumentException("FLACOutputStream fos must not be null."); if(flacWriter == null) flacWriter = new FLACStreamController(fos,streamConfig); else flacWriter.setFLACOutputStream(fos); }
java
public static String getDefaultIP(String strInterface) throws UnknownHostException { String[] ips = getIPs(strInterface); return ips[0]; }
python
def verify(self): """ Verify the module IR's correctness. RuntimeError is raised on error. """ with ffi.OutputString() as outmsg: if ffi.lib.LLVMPY_VerifyModule(self, outmsg): raise RuntimeError(str(outmsg))
python
def load_yaml_file(yaml_file): """ load yaml file and check file content format """ with io.open(yaml_file, 'r', encoding='utf-8') as stream: yaml_content = yaml.load(stream) _check_format(yaml_file, yaml_content) return yaml_content
java
public <S extends T> List<S> select(List<EvaluatedCandidate<S>> population, boolean naturalFitnessScores, int selectionSize, Random rng) { if (population.size() < groupSize) { ...
java
public static String[] between(final String value, final String start, final String end) { validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); validate(start, NULL_STRING_PREDICATE, () -> "'start' should be not null."); validate(end, NULL_STRING_PREDICATE, () -> "'end' should be no...
python
def is_valid_op(self, symmop): """ Check if a particular symmetry operation is a valid symmetry operation for a molecule, i.e., the operation maps all atoms to another equivalent atom. Args: symmop (SymmOp): Symmetry operation to test. Returns: (...
python
def effective_patterns(self, context=None): """ Get effective patterns for this rebulk object and its children. :param context: :type context: :return: :rtype: """ patterns = list(self._patterns) for rebulk in self._rebulks: if not rebu...
java
@Override public void setText(final String text) { if (this.text == null) { this.text = new Text(text); add(this.text); } else { this.text.setText(text); } }
java
String getSessionReferredLink() { String link = prefHelper_.getExternalIntentUri(); return (link.equals(PrefHelper.NO_STRING_VALUE) ? null : link); }
java
public static Hosts parse(String hostString, Integer explicitGlobalPort, Integer defaultPort) { List<String> hosts = new ArrayList<>(); List<Integer> ports = new ArrayList<>(); if ( hostString == null || hostString.trim().isEmpty() ) { return Hosts.NO_HOST; } // for each element between commas String[] s...
python
def findfileindirs(filename, dirs=None, use_pythonpath=True, use_searchpath=True, notfound_is_fatal=True, notfound_val=None): """Find file in multiple directories. Inputs: filename: the file name to be searched for. dirs: list of folders or None use_pythonpath: use the Python module sea...
python
def _vertex_net_cost(vertex, v2n, placements, has_wrap_around_links, machine): """Get the total cost of the nets connected to the given vertex. Parameters ---------- vertex The vertex whose nets we're interested in. v2n : {vertex: [:py:class:`rig.netlist.Net`, ...], ...} placements : {v...
java
public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuffer... buffers) { return wrappedBuffer(maxNumComponents, CompositeByteBuf.BYTE_BUFFER_WRAPPER, buffers); }
java
private void checkForFinalBoundary(String boundaryLine) throws IOException { if (boundaryLine.equals(boundary + "--")) { hasNext = false; inputStream.close(); } }
java
public static String percentFormat(final BigDecimal bd) { return bd != null ? NUMBER_FORMAT.format(bd.movePointRight(2)) : ""; }
java
public void terminateOnBye(boolean arg0) throws SipException { this.terminateOnByeCached = arg0; if (wrappedDialog != null) { wrappedDialog.terminateOnBye(arg0); } }
python
def publish(self, topic, payload, QoS): """ **Description** Publish a new message to the desired topic with QoS. **Syntax** .. code:: python # Publish a QoS0 message "myPayload" to topic "myTopic" myAWSIoTMQTTClient.publish("myTopic", "myPayload", 0) ...
java
public String validate() { String result = null; if( this.messagingConfiguration == null || this.messagingConfiguration.isEmpty()) result = "The message configuration cannot be null or empty."; else if( this.messagingConfiguration.get(MessagingConstants.MESSAGING_TYPE_PROPERTY) == null) result = "The messa...
python
def move_item(self, item, origin, destination): """ Moves an item from one cluster to anoter cluster. :param item: the item to be moved. :param origin: the originating cluster. :param destination: the target cluster. """ if self.equality: item_index =...
python
def add_header(self, header): """Add headers to the email globaly or to a specific Personalization :param value: A Header object or a dict of header key/values :type value: Header, dict """ if header.personalization is not None: try: personalization =...
python
def cortex_plot_2D(the_map, color=None, cmap=None, vmin=None, vmax=None, alpha=None, underlay='curvature', mask=None, axes=None, triangulation=None): ''' cortex_plot_2D(map) yields a plot of the given 2D cortical mesh, map. The following options are accepted: * c...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.GCMRKRG__XPOS: return XPOS_EDEFAULT == null ? xpos != null : !XPOS_EDEFAULT.equals(xpos); case AfplibPackage.GCMRKRG__YPOS: return YPOS_EDEFAULT == null ? ypos != null : !YPOS_EDEFAULT.equals(ypos); } return su...
python
def emoticons_filter(content, exclude='', autoescape=None): """ Filter for rendering emoticons. """ esc = autoescape and conditional_escape or (lambda x: x) content = mark_safe(replace_emoticons(esc(content), exclude)) return content
java
public BoxRequestsFile.CommitUploadSession getCommitSessionRequest(List<BoxUploadSessionPart> uploadedParts, Map<String, String> attributes, String ifMatch, String ifNoneMatch, B...
python
def findCaller(self, stack_info=False, callers=0): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. Not only ignore this class's and logger's source, but also as many callers as requested. """ f = logging.curr...
python
def _will_be(self, timeobject, weather_condition): """ Tells if at the specified weather condition will occur at the specified time. The check is performed on the *Weather* item of the forecast which is closest to the time value conveyed by the parameter :param timeobject: may b...
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { ntp_server_responses result = (ntp_server_responses) service.get_payload_formatter().string_to_resource(ntp_server_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == S...
java
public RemoteSendQueue createRemoteSendQueue(String strQueueName, String strQueueType) throws RemoteException { MessageManager messageManager = this.getEnvironment().getMessageManager(this.getApplication(), true); BaseMessageSender sender = (BaseMessageSender)messageManager.getMessageQueue(strQueueN...
python
def get_bibtex(identifier): """ Try to fetch BibTeX from a found identifier. .. note:: Calls the functions in the respective identifiers module. :param identifier: a tuple (type, identifier) with a valid type. :returns: A BibTeX string or ``None`` if an error occurred. # TODO: Should ...
python
def to_dict(self): """Dump episode to a dictionary. :return: Episode dictionary :rtype: :class:`~python:dict` """ result = self.to_identifier() result.update({ 'title': self.title, 'watched': 1 if self.is_watched else 0, 'collected'...
java
public static <T> Collection<T> eachWithIndex(Collection<T> self, @ClosureParams(value=FromString.class, options="T,Integer") Closure closure) { return (Collection<T>) eachWithIndex((Iterable<T>) self, closure); }
java
public <E> void dispatchEvent (Signal<E> signal, E event) { try { signal.emit(event); } catch (Throwable cause) { reportError("Event dispatch failure", cause); } }
java
public void getAllPetID(Callback<List<Integer>> callback) throws NullPointerException { gw2API.getAllPetIDs().enqueue(callback); }
python
def generate_query_batches( self, sql, params=None, param_types=None, partition_size_bytes=None, max_partitions=None, ): """Start a partitioned query operation. Uses the ``PartitionQuery`` API request to start a partitioned query operation. R...
python
def makeExtensionLoginMethod(extensionKey): '''Return a function that will call the vim.SessionManager.Login() method with the given parameters. The result of this function can be passed as the "loginMethod" to a SessionOrientedStub constructor.''' def _doLogin(soapStub): si = vim.Serv...
python
def open_grpc_channel(endpoint): """ open grpc channel: - for http:// we open insecure_channel - for https:// we open secure_channel (with default credentials) - without prefix we open insecure_channel """ if (endpoint.startswith("https://")): return grpc.sec...
python
def add_comment(self, text): """Comment on the submission using the specified text. :returns: A Comment object for the newly created comment. """ # pylint: disable=W0212 response = self.reddit_session._add_comment(self.fullname, text) # pylint: enable=W0212 self...
python
def comment_request(self, request_id, body, commit=None, filename=None, row=None): """ Create a comment on the request. :param request_id: the id of the request :param body: the comment body :param commit: which commit to comment on :param filename...
python
def plural_verb(self, text, count=None): """ Return the plural of text, where text is a verb. If count supplied, then return text if count is one of: 1, a, an, one, each, every, this, that otherwise return the plural. Whitespace at the start and end is preserved. ...
java
private static String formatInt(int number) { String str = Integer.toString(number); return number < 10 ? " " + str : str; }
java
private void unmarshall() { sheetData = sheet.getJaxbElement().getSheetData(); rows = sheetData.getRow(); if(rows != null && rows.size() > 0) { Row r = (Row)rows.get(0); numColumns = r.getC().size(); } }
java
public <T> T map(String beanId, RowData rowData, Class<T> type) { T bean = beanFactory.getBean(beanId, type); Table table = tableMap.get(beanId); for (Column column : table.getColumn()) { map(bean, column, rowData); } return bean; }
python
def revoke_security_group_deprecated(self, group_name, src_security_group_name=None, src_security_group_owner_id=None, ip_protocol=None, from_port=None, to_...
python
def worktree_prune(cwd, dry_run=False, verbose=True, expire=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encodi...
python
def createStyle(self, body, verbose=None): """ Creates a new Visual Style using the message body. Returns the title of the new Visual Style. If the title of the Visual Style already existed in the session, a new one will be automatically generated and returned. :param body: The...
python
def removed(name, cyg_arch='x86_64', mirrors=None): ''' Make sure that a package is not installed. name The name of the package to uninstall cyg_arch : x86_64 The cygwin architecture to remove the package from. Current options are x86 and x86_64 mirrors : None List...
java
public void addJKTableColumn(final JKTableColumn col) { col.setIndex(this.tableColumns.size()); this.tableColumns.add(col); this.visibilityManager.refreshVisibility(); fireTableStructureChanged(); }
java
public static String classFilePathToClassname(String relativePath) { if (relativePath == null) return null; final int pos = relativePath.lastIndexOf(".class"); if (pos < 0 && relativePath.lastIndexOf(".java") < 0) throw new IllegalArgumentException("Not a .class/.jav...
java
private synchronized ZNames loadMetaZoneNames(String mzID) { ZNames mznames = _mzNamesMap.get(mzID); if (mznames == null) { ZNamesLoader loader = new ZNamesLoader(); loader.loadMetaZone(_zoneStrings, mzID); mznames = ZNames.createMetaZoneAndPutInCache(_mzNamesMap, loa...
java
static List<ByteBuffer> convertByteKeys(Collection<byte[]> rowKeys) { List<ByteBuffer> rowKeyList = new ArrayList<ByteBuffer>(); for (byte[] rowKey : rowKeys) { rowKeyList.add(ByteBuffer.wrap(rowKey)); } return rowKeyList; }
python
def parse_project_and_dataset( project: str, dataset: Optional[str] = None ) -> Tuple[str, str, Optional[str]]: """Compute the billing project, data project, and dataset if available. This function figure out the project id under which queries will run versus the project of where the data live as well ...
python
def has_permissions_batch(self, eval_batch): """HasPermissionsBatch. Evaluates multiple permissions for the calling user. Note: This method does not aggregate the results, nor does it short-circuit if one of the permissions evaluates to false. :param :class:`<PermissionEvaluationBatch> <azure.d...
java
static String removeKeyword(String clause, String keyword) { keyword = keyword + " "; if (clause.regionMatches(true, 0, keyword, 0, keyword.length())) { return clause.substring(keyword.length()); } return clause; }
python
def __expire_files(self): """Because files are always unclean""" self.__files = OrderedDict( item for item in self.__files.items() if not item[1].expired )
java
final public void decrement(long decVal) { if (enabled) { // synchronize the update of lastValue lastSampleTime = updateIntegral(); synchronized (this) { current -= decVal; } updateWaterMark(); } else { current -= decVal; ...
java
private synchronized void refreshFlow() { try { initialize(); } catch (Exception e) { throw new IllegalStateException("Error while initializing wizard", e); } int currentFlowPointer = this.flowPointer; try { this.flowPointer = 0; ...
java
public Observable<ServiceResponse<AgreementTermsInner>> createWithServiceResponseAsync(String publisherId, String offerId, String planId, AgreementTermsInner parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is requir...
python
def extract_secrets_from_android_rooted(adb_path='adb'): """Extract Steam Authenticator secrets from a rooted Android device Prerequisite for this to work: - rooted android device - `adb binary <https://developer.android.com/studio/command-line/adb.html>`_ - device in debug mode, conne...
python
def _set_authenticate(self, v, load=False): """ Setter method for authenticate, mapped from YANG variable /ntp/authenticate (empty) If this variable is read-only (config: false) in the source YANG file, then _set_authenticate is considered as a private method. Backends looking to populate this varia...
java
public static Intent generateOpenWithIntentFromUtmContent(String UtmContent) throws DropboxParseException { // Utm content is encoded a base64-encoded marshalled bundle // _action is extracted and becomes intent's action // _uri is extracted and becomes intent's data uri // All o...
java
@Override public Set<URI> listServices() { String queryStr = new StringBuilder() .append("SELECT DISTINCT ?svc WHERE { \n") .append(" GRAPH ?g { \n") .append("?svc ").append("<").append(RDF.type.getURI()).append(">").append(" ").append("<").append(MSM.Service....