language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public GoogleMapShapeMarkers addShapeToMapAsMarkers(GoogleMap map, GoogleMapShape shape, MarkerOptions markerOptions, MarkerOptions polylineMarkerOptions, ...
java
private void defineTrees(UIDefaults d) { //Initialize Tree String p = "Tree"; String c = PAINTER_PREFIX + "TreePainter"; d.put(p + ".contentMargins", new InsetsUIResource(0, 0, 0, 0)); d.put(p + ".opaque", Boolean.TRUE); d.put(p + ".textForeground", d.get("text")); ...
python
def explore_path_encompass(self, task_num, dirpath): """ Explore path to discover unsearched directories and save filepaths :param task_num: Processor ID :param dirpath: Tuple (base directory, path), path information pulled from unsearched Queue :return: Directories to add to uns...
python
def _get_uploaded_file(session, file_info, fragment_count=0): """ :param session: locked session (with self._session_resource as >> session <<) :param file_info: contains file information to save or query :param fragment_count: amount of fragments associated to the file :return: ...
java
public void addExperiment(byte[] source) throws IOException { AceExperiment experiment = new AceExperiment(source); String eid = experiment.getId(); if(this.experimentMap.containsKey("eid")) { LOG.error("Duplicate data found for experiment: {}", experiment.getValueOr("exname", "")); ...
java
public boolean add(int left, int right) { if (line[left] == null) { line[left] = new IntBitSet(); } else { if (line[left].contains(right)) { return false; } } line[left].add(right); return true; }
python
def _get_po_paths(locales=[]): """Returns paths to all relevant po files in the current project.""" basedirs = [os.path.join('conf', 'locale'), 'locale'] if os.environ.get('DJANGO_SETTINGS_MODULE'): from django.conf import settings basedirs.extend(settings.LOCALE_PATHS) # Gather existin...
python
def get_mesos_task(task_name): """ Get a mesos task with a specific task name """ tasks = get_mesos_tasks() if tasks is not None: for task in tasks: if task['name'] == task_name: return task return None
python
def set_dataset_date_from_datetime(self, dataset_date, dataset_end_date=None): # type: (datetime, Optional[datetime]) -> None """Set dataset date from datetime.datetime object Args: dataset_date (datetime.datetime): Dataset date dataset_end_date (Optional[datetime.dateti...
python
def samReferencesToStr(filenameOrSamfile, indent=0): """ List SAM/BAM file reference names and lengths. @param filenameOrSamfile: Either a C{str} SAM/BAM file name or an instance of C{pysam.AlignmentFile}. @param indent: An C{int} number of spaces to indent each line. @return: A C{str} desc...
python
def show_endpoint_group(self, endpointgroup, **_params): """Fetches information for a specific VPN endpoint group.""" return self.get(self.endpoint_group_path % endpointgroup, params=_params)
java
public static <T, L extends List<T>> T getLast(List<T> list) { return isNullOrEmpty(list) ? null : list.get(list.size() - 1); }
python
def str2tuple(str_in): ''' Extracts a tuple from a string. Args: str_in (string) that contains python tuple Returns: (dict) or None if no valid tuple was found Raises: - ''' tuple_out = safe_eval(str_in) if not isinstance(tuple_out, tuple): tuple_out = No...
java
public Enumeration<String> getElements() { AttributeNameEnumeration elements = new AttributeNameEnumeration(); elements.addElement(ALGORITHM); return (elements.elements()); }
java
private void setMsgSizeValue(int value, boolean allowOverwrite) { String absPath = getPath() + ".MsgHead.msgsize"; SyntaxElement msgsizeElem = getElement(absPath); if (msgsizeElem == null) throw new NoSuchPathException(absPath); int size = ((DE) msgsizeElem).getMinSize(); ...
java
@SuppressWarnings("static-method") protected JvmType newType(String pythonName) { final JvmGenericType type = TypesFactory.eINSTANCE.createJvmGenericType(); final int index = pythonName.indexOf("."); //$NON-NLS-1$ if (index <= 0) { type.setSimpleName(pythonName); } else { type.setPackageName(pythonName.s...
java
public static String encodeStringURL(byte[] source, boolean wrap) { return Encoder.encodeString(source, 0, source.length, wrap, true); }
java
public static <T> T newCheckedInstanceOf(final String className, final Class<T> clazz) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { return clazz.cast(newInstanceOf(className)); }
python
def forwards(apps, schema_editor): """ Create sample events. """ starts = timeutils.round_datetime( when=timezone.now(), precision=timedelta(days=1), rounding=timeutils.ROUND_DOWN) ends = starts + appsettings.DEFAULT_ENDS_DELTA recurrence_rules = dict( Recurrence...
java
public <T> Flow<T> map(Mapper<? super B, T> mapper) { return then(new FlowMap<B, T>(mapper)); }
java
public <T> RemoteService.Response call(long pause, Functor<T, String> reporter) throws Exception { String message = null; while (true) { RemoteService.Response response = _caller.call(); String news = response.params.get("message"); if (news == null) { ...
java
@Override public CommerceTaxFixedRate findByCPTaxCategoryId_Last( long CPTaxCategoryId, OrderByComparator<CommerceTaxFixedRate> orderByComparator) throws NoSuchTaxFixedRateException { CommerceTaxFixedRate commerceTaxFixedRate = fetchByCPTaxCategoryId_Last(CPTaxCategoryId, orderByComparator); if (commerc...
python
def valid_project(self): """Handle an invalid active project.""" try: path = self.projects.get_active_project_path() except AttributeError: return if bool(path): if not self.projects.is_valid_project(path): if path: ...
python
def extend_selection(): """Checks is the selection is to be extended The selection is to be extended, if a special modifier key (typically <Ctrl>) is being pressed. :return: If to extend the selection :rtype: True """ from rafcon.gui.singleton import main_window_controller currently_presse...
python
def iglob(pathname): """Return an iterator which yields the paths matching a pathname pattern. The pattern may contain simple shell-style wildcards a la fnmatch. """ if not has_magic(pathname): yield pathname return dirname, basename = os.path.split(pathname) if not dirname: ...
python
def get_atx_heading(line: str, keep_header_levels: int = 3, parser: str = 'github', no_links: bool = False): r"""Given a line extract the link label and its type. :parameter line: the line to be examined. :parameter keep_header_levels: the maximum...
java
public static RelationType create(@NonNull String name) { RelationType toReturn = DynamicEnum.register(new RelationType(name)); values.add(toReturn); return toReturn; }
java
@Override protected void logIncrementalStatsByAccount(String account, RunStats stats) { log.info("Session stats by account (incremental): account={} tasksAdded={}", account, ((BitIntegrityRunStats) stats).getAdded()); }
java
public List<Vec> getDataVectors() { List<Vec> vecs = new ArrayList<>(size()); for(int i = 0; i < size(); i++) vecs.add(getDataPoint(i).getNumericalValues()); return vecs; }
java
public LinePlot line(String id, double[] y) { double[] lowerBound = {0, Math.min(y)}; double[] upperBound = {y.length, Math.max(y)}; extendBound(lowerBound, upperBound); double[][] data = new double[y.length][2]; for (int i = 0; i < data.length; i++) { data[i][0] = i...
python
def by_period(self, field=None, period=None, timezone=None, start=None, end=None): """ Create a date histogram aggregation using the last added aggregation for the current object. Add this date_histogram aggregation into self.aggregations :param field: the index field to create the hist...
java
private ImmutableList<Element> getNodeListForTagElement(Document dom, CrawlElement crawlElement, EventableConditionChecker eventableConditionChecker) { Builder<Element> result = ImmutableList.builder(); if (crawlElement.getTagName() == null) { return result.build(); } EventableCondition eventableCon...
java
public void startHFTA() throws IOException { int hftaCount = MetaInformationParser.getHFTACount(new File(this.hubDataStore.getBinaryLocation().toURI())); for (int i = 0; i < hftaCount; i++) { List<String> com = Lists.newArrayList(); com.add(getHostPort(hubDataStore.getHubAddress())); com.add(h...
python
def FlowResponseForLegacyResponse(legacy_msg): """Helper function to convert legacy client replies to flow responses.""" if legacy_msg.type == legacy_msg.Type.MESSAGE: response = FlowResponse( client_id=_ClientIDFromSessionID(legacy_msg.session_id), flow_id=legacy_msg.session_id.Basename(), ...
java
boolean isCompactionRequired(SegmentProperties info) { long startOffset = getCompactionStartOffset(info); long lastIndexOffset = this.indexReader.getLastIndexedOffset(info); if (startOffset + this.connector.getMaxCompactionSize() >= lastIndexOffset) { // Either: // 1. Not...
java
public void removeQueuePointOutputHandler(SIBUuid8 meUuid) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "removeQueuePointOutputHandler", new Object[] { meUuid }); synchronized(_queuePointOutputHandlers) { _queuePointOutputHandlers.remove(meUuid); } ...
java
public static <E> Set<E> difference(Set<? extends E> s1, Set<? extends E> s2) { Set<E> copy1 = new HashSet<>(s1); copy1.removeAll(new HashSet<>(s2)); return copy1; }
java
public boolean contains(String search) { if (search == null) return _value == null; if (search.length() == 0) return false; if (_value == null) return false; if (search.equals(_value)) return true; search = StringUtils.asciiToLower...
java
public Migration read() { try (StringReader reader = new StringReader(info.getModelDiff())) { JAXBContext jaxbContext = JAXBContext.newInstance(Migration.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); return (Migration) unmarshaller.unmarshal(reader); ...
java
public void recordMetrics(String processName, JsonObject metricsData) { for (Map.Entry<String, JsonElement> entry : metricsData.entrySet()) { metrics.count(processName + "." + entry.getKey(), Math.round(entry.getValue().getAsFloat())); } }
java
public static void proxy(Method method, InvocationHandler invocationHandler) { assertInvocationHandlerNotNull(invocationHandler); MockRepository.putMethodProxy(method, invocationHandler); }
java
public void billingAccount_miniPabx_serviceName_hunting_PUT(String billingAccount, String serviceName, OvhMiniPabxHunting body) throws IOException { String qPath = "/telephony/{billingAccount}/miniPabx/{serviceName}/hunting"; StringBuilder sb = path(qPath, billingAccount, serviceName); exec(qPath, "PUT", sb.toStr...
java
public static List<String> getLabels(Set dataSet) { char[] c = getLabelsArray(dataSet); List<String> l = new ArrayList<>(c.length); for (char c2 : c) { l.add(String.valueOf(c2)); } return l; }
python
def underlying_likelihood(self, binary_outcomes, modelparams, expparams): """ Given outcomes hypothesized for the underlying model, returns the likelihood which which those outcomes occur. """ original_mps = modelparams[..., self._orig_mps_slice] return self.underlying_mo...
python
def factory(coords, dependent_variables, helper_functions): """Fields factory generating specialized container build around a triflow Model and xarray. Parameters ---------- coords: iterable of str: coordinates name. First co...
java
public static Integer getPropertyInteger(Class<?> aClass, String key, int defaultValue) { return getSettings().getPropertyInteger(key, defaultValue); }
java
@Override @SuppressWarnings("unchecked") public <E> E getState(Class<E> stateType) { return stateType == CxDxSessionState.class ? (E) this.sessionData.getCxDxSessionState() : null; }
python
def get_actor(name): """Get a named actor which was previously created. If the actor doesn't exist, an exception will be raised. Args: name: The name of the named actor. Returns: The ActorHandle object corresponding to the name. """ actor_name = _calculate_key(name) pickle...
python
def import_sbml(document): """ Import a model from a SBMLDocument. Parameters ---------- document : SBMLDocument Returns ------- model : NetworkModel y0 : dict Initial condition. volume : Real or Real3, optional A size of the simulation volume. """ from...
java
public Matrix4 setToRotation (float angle, IVector3 axis) { return setToRotation(angle, axis.x(), axis.y(), axis.z()); }
java
public OtpErlangObject read_any() throws OtpErlangDecodeException { // calls one of the above functions, depending on o final int tag = peek1skip_version(); switch (tag) { case OtpExternal.smallIntTag: case OtpExternal.intTag: case OtpExternal.smallBigTag: case O...
java
public static void scheduleWithFixedDelay(ScheduledExecutorService exec, Duration delay, Callable<Signal> callable) { scheduleWithFixedDelay(exec, delay, delay, callable); }
python
def make_abstract_dist(req): # type: (InstallRequirement) -> DistAbstraction """Factory to make an abstract dist object. Preconditions: Either an editable req with a source_dir, or satisfied_by or a wheel link, or a non-editable req with a source_dir. :return: A concrete DistAbstraction. """ ...
java
public ApiResponse<ApiSuccessResponse> singleStepConferenceWithHttpInfo(String id, SingleStepConferenceData singleStepConferenceData) throws ApiException { com.squareup.okhttp.Call call = singleStepConferenceValidateBeforeCall(id, singleStepConferenceData, null, null); Type localVarReturnType = new Type...
java
@Override public Collection<ConfigKeyPath> getImportedByRecursively(ConfigKeyPath configKey) { return getImportedByRecursively(configKey, Optional.<Config>absent()); }
java
public char[] toCharArray() { // check if there is a cached single charbuffer if (firstChunk == lastChunk && firstChunk instanceof CharBufferChunk && allocBuffer.charsUsed() == 0 && ((CharBufferChunk) firstChunk).isSingleBuffer()) { return ((CharBu...
java
private static void configureLoggerWrapper (Node configNode) { Node lwNameNode = configNode.getAttributes ().getNamedItem ("name"); String lwName; if (lwNameNode != null) { lwName = lwNameNode.getTextContent (); } else { lwName = "LoggerWrapper_" + String.valueOf ((new Date ()).getTime ()); } LoggerW...
python
def intersection(self, other): """ Create a new DateRange representing the maximal range enclosed by this range and other """ startopen = other.startopen if self.start is None \ else self.startopen if other.start is None \ else other.startopen if self.start < othe...
python
def parse_mappings(mappings, key_rvalue=False): """By default mappings are lvalue keyed. If key_rvalue is True, the mapping will be reversed to allow multiple configs for the same lvalue. """ parsed = {} if mappings: mappings = mappings.split() for m in mappings: p =...
python
def combine_dicts(*args, **kwargs): """ Combines all arguments (if they are dictionaries) and kwargs to a final dict :param args: dict, any dictionaries the user wants combined :param kwargs: dict, kwargs. :return: dict, compiled dictionary """ dicts = [arg for arg in args if isinstance(arg, di...
python
def parse_model(self, model): """Split the given model_name into controller and model parts. If the controller part is empty, the current controller will be used. If the model part is empty, the current model will be used for the controller. The returned model name will always be...
java
public T modifyModule(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) { final ContentItem item = createModuleItem(moduleName, slot, newHash); addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash)); return return...
python
def temporal_segmentation(segments, min_time): """ Segments based on time distant points Args: segments (:obj:`list` of :obj:`list` of :obj:`Point`): segment points min_time (int): minimum required time for segmentation """ final_segments = [] for segment in segments: final_...
java
@Override public AssociateConnectionWithLagResult associateConnectionWithLag(AssociateConnectionWithLagRequest request) { request = beforeClientExecution(request); return executeAssociateConnectionWithLag(request); }
java
@Override public String[] listResources() { return new File(mStorageConfig.mFile, StorageConfiguration.Paths.Data.getFile().getName()).list(); }
python
def __download_file(self, url, path_file, timeout): """ download a file from the server using a request with retries policy :param url: server url to request :param path_file: path and file where to download :param timeout: threshold until the video file is downloaded :re...
java
public void marshall(CreateAssociationRequest createAssociationRequest, ProtocolMarshaller protocolMarshaller) { if (createAssociationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createA...
java
public static Properties parseArgs(Class<?> caller, String[] args, Configuration conf) throws IOException { try { // Parse command-line options if (conf != null) { args = new GenericOptionsParser(conf, args).getCommandLine().getArgs(); } CommandLine cmd = new DefaultParser().parse(o...
java
public PBConstraint cc(final CType comparator, final int rhs, final Collection<Variable> variables) { final int[] coefficients = new int[variables.size()]; Arrays.fill(coefficients, 1); final Variable[] vars = new Variable[variables.size()]; int count = 0; for (final Variable var : variables) ...
python
def format_context( context: Context, formatter: typing.Union[str, Formatter] = "full" ) -> str: """Output the a context dictionary as a string.""" if not context: return "" if callable(formatter): formatter_func = formatter else: if formatter in CONTEXT_FORMATTERS: ...
java
public boolean matches(String xpath, boolean includeParent) { if (xpath == null || xpath.equals("")) { throw new IllegalArgumentException("xpath cannot be null or empty"); } // make sure xpath doesn't end with an / if (xpath.endsWith("/")) { throw new IllegalArgu...
java
@Override public final GeoCodeItem find(final String placeName, final String modernPlaceName) { if (modernPlaceName == null || modernPlaceName.isEmpty()) { return find(placeName); } logger.debug( "find(\"" + placeName + "\", \"" + modernPlaceName + "\"...
python
def decode_sql(self, sql): """Base64 decode a string. This should only be used for sql in calls. :param str sql: The base64 encoded form of the original utf-8 string :return str: The decoded utf-8 string """ # JSON is defined as using "unicode", we'll go a step further and ...
python
def _input_arg(self, a): """ Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action """ # if action of an argument that suppresses any other, just return if a.dest == SUPPRES...
python
def delete_collection_namespaced_pod_template(self, namespace, **kwargs): """ delete collection of PodTemplate This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_p...
java
public synchronized void logoutAllUsers(Context context) { getAuthInfoMap(context); for (String userId : mCurrentAccessInfo.keySet()) { BoxSession session = new BoxSession(context, userId); logout(session); } authStorage.clearAuthInfoMap(context); }
python
def comment_issue(self, issue_id, body): """ Comment to an issue. :param issue_id: the id of the comment :param body: the comment body :return: """ request_url = "{}issue/{}/comment".format(self.create_basic_url(), ...
python
def update_batch(self, **kwargs): """ Simplistic batch update operation implemented in terms of `replace()`. Assumes that: - Request and response schemas contains lists of items. - Request items define a primary key identifier - The entire batch succeeds or fails tog...
python
def get_variables(scope=None, suffix=None): """Gets the list of variables, filtered by scope and/or suffix. Args: scope: an optional scope for filtering the variables to return. suffix: an optional suffix for filtering the variables to return. Returns: a copied list of variables with scope and suffi...
python
def removeAll(self): """Remove all objects Returns: len(int): affected rows """ before_len = len(self.model.db) self.model.db = [] if not self._batch.enable.is_set(): self.model.save_db() return before_len - len(self.model.db)
python
def setup(self): """Setup cache tables.""" for table_spec in self._table_specs: with self._conn: table_spec.setup(self._conn)
java
public Observable<UserAccessList> listAsync(UUID appId) { return listWithServiceResponseAsync(appId).map(new Func1<ServiceResponse<UserAccessList>, UserAccessList>() { @Override public UserAccessList call(ServiceResponse<UserAccessList> response) { return response.body();...
java
@Override public CompoundSelection<Object[]> array(Selection<?>... arg0) { return new DefaultCompoundSelection<Object[]>(Arrays.asList(arg0), Object.class); }
java
public void deleteIfNoneMatch(URI uri, String eTag, String assertedUserId) throws IOException { deleteIfNoneMatch(uri, eTag, assertedUserId, null); }
java
public float getTotalLeading() { if (list.size() < 1) { return -1; } ListItem item = (ListItem) list.get(0); return item.getTotalLeading(); }
python
def config(self, handle, attributes=None, **kwattrs): """Sets or modifies one or more object attributes or relations. Arguments can be supplied either as a dictionary or as keyword arguments. Examples: stc.config('port1', location='//10.1.2.3/1/1') stc.config('port2', {...
python
async def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None): """A coroutine which goes through a stream and calls a given callback for each XML packet seen in it.""" packets_captured = 0 self._log.debug('Starting to go through packets') psml_struct, data = await ...
java
public CellConstraints rc(int row, int col, String encodedAlignments) { return rchw(row, col, 1, 1, encodedAlignments); }
python
def endElement(self, name): """ Handle closing elements :param name: Name of the element :type name: String """ if name in self.ignore_end: return try: handler = getattr(self, '_handle_end_%s' % name) except AttributeError: ...
python
def _parse_show_output(cmd_ret): ''' Parse the output of an aptly show command. :param str cmd_ret: The text of the command output that needs to be parsed. :return: A dictionary containing the configuration data. :rtype: dict ''' parsed_data = dict() list_key = None for line in cm...
python
def sample(self, label): """ generate random padding boxes according to parameters if satifactory padding generated, apply to ground-truth as well Parameters: ---------- label : numpy.array (n x 5 matrix) ground-truths Returns: ---------- ...
python
def _convert_signed_hex(s): """Takes a signed hex string that begins with '0x' and converts it to a 16-character string representing an unsigned hex value. Examples: '0xd68adf75f4cfd13' => 'd68adf75f4cfd13' '-0x3ab5151d76fb85e1' => 'c54aeae289047a1f' """ if s.startswith('0x') or s.st...
python
def _load_includes(self, tag, ssh=False): """Extracts all additional libraries that should be included when linking the unit testing executables. """ import re includes = [] for child in tag: if child.tag == "include" and "path" in child.attrib: ...
java
public void createNestedEntitiesForChoicePath(CmsEntity value, List<String> choicePath) { CmsEntity parentValue = value; for (String attributeChoice : choicePath) { CmsType choiceType = m_entityBackEnd.getType(parentValue.getTypeName()).getAttributeType( CmsType.CHOICE_...
java
public static Info eye( final Variable A , ManagerTempVariables manager) { Info ret = new Info(); final VariableMatrix output = manager.createMatrix(); ret.output = output; if( A instanceof VariableMatrix ) { ret.op = new Operation("eye-m") { @Override ...
java
public TableWriteItems withItemsToPut(Collection<Item> itemsToPut) { if (itemsToPut == null) this.itemsToPut = null; else this.itemsToPut = new ArrayList<Item>(itemsToPut); return this; }
python
def all(self, array, role = None): """ Return ``True`` if ``array`` is ``True`` for all members of the entity. ``array`` must have the dimension of the number of persons in the simulation If ``role`` is provided, only the entity member with the given role are taken into acc...
java
public Project.Layouts.Layout.CodeOptions.CodeOption createProjectLayoutsLayoutCodeOptionsCodeOption() { return new Project.Layouts.Layout.CodeOptions.CodeOption(); }
java
@Override public void saveDataFrame(DataFrame dataFrame, Class<?> entityClazz, Map<String, Object> properties) { throw new KunderaException("Dataframe persistence in teradata is currently not supported. "); }
java
protected AApplyExp getApplyExp(PExp root, PExp... arglist) { return getApplyExp(root, Arrays.asList(arglist)); }