language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void load() { Source source = getSource(); Target target = getTarget(); source.beginExport(); target.beginImport(); Set<String> propertyNames = mode.equals(MappingMode.AUTO) ? target.getPropertyNames() : sou...
python
def get_mime_data(self, mime_type): """Return mime data previously attached to surface using the specified mime type. :param mime_type: The MIME type of the image data. :type mime_type: ASCII string :returns: A CFFI buffer object, or :obj:`None` if no dat...
java
public ElasticsearchDomainStatus withEndpoints(java.util.Map<String, String> endpoints) { setEndpoints(endpoints); return this; }
java
String getTypeName() { return typeSub == Types.TYPE_SUB_IGNORECASE ? Types.getTypeName(Types.VARCHAR_IGNORECASE) : Types.getTypeName(type); }
python
def restrict(self, support): """Restrict the features to those in support using feature selection. This function modifies the estimator in-place. """ if self.has_been_restricted == True: return self new_numerical_cols = [] new_categorical_cols = [] ...
python
def init_with_validation(cls, function, arguments): """Return a `FunctionCall` given some validation for the function and args. Args: function: A function name or id, to be converted into a function id enum. arguments: An iterable of function arguments. Arguments that are enum types can b...
python
def addConnection( self, cls = None ): """ Creates a new connection instance in the scene. If the optional cls \ parameter is not supplied, then the default connection class will \ be used when creating the connection. :param cls subclass of <XNodeConnection> ...
java
protected ConsumerJournalEntry readJournalEntry(XMLEventReader reader) throws JournalException, XMLStreamException { StartElement startTag = getJournalEntryStartTag(reader); String methodName = getRequiredAttributeValue(startTag, QNAME_ATTR_METHOD); JournalEntryConte...
java
public int agendaSize() { int size = 0; for ( InternalAgendaGroup internalAgendaGroup : this.agendaGroups.values() ) { size += internalAgendaGroup.size(); } return size; }
python
def enter_new_scope(ctx): """ we inside new scope with it onw :param ctx: :return: """ ctx = ctx.clone() ctx.waiting_for = ctx.compiled_story().children_matcher() return ctx
python
def annotate_variant(variant, var_obj=None): """Annotate a cyvcf variant with observations Args: variant(cyvcf2.variant) var_obj(dict) Returns: variant(cyvcf2.variant): Annotated variant """ if var_obj: variant.INFO['Obs'] = var_obj['observations'] ...
java
public String htmlStartStyle(String title, String stylesheet) { return pageHtmlStyle(HTML_START, title, stylesheet); }
python
def slack_message(): """When we receive a message from Slack, generate a Trello card and reply""" # Incoming request format: # token=TOKEN # team_id=T0001 # team_domain=example # channel_id=C12345 # channel_name=test # user_id=U12345 # user_name=Steve # command=/weather # tex...
java
private void connect() { ClientInfo.Builder info = ClientInfo.newBuilder().setFormat("protobuf"); executeMessage(ScopeMessage.CONNECT, info); }
python
def restart_apppool(name): ''' Restart an IIS application pool. .. versionadded:: 2016.11.0 Args: name (str): The name of the IIS application pool. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.restart_appp...
java
public ListVpcsResponse listVpcs(ListVpcsRequest request) { checkNotNull(request, "request should not be null."); InternalRequest internalRequest = this.createRequest(request, HttpMethodName.GET, VPC_PREFIX); if (request.getMarker() != null) { internalRequest.addParameter("marker", r...
java
@Nonnull public static JSOpBinary eeq (@Nonnull final IJSExpression aLeft, @Nonnull final IJSExpression aRight) { return new JSOpBinary (aLeft, "===", aRight); }
python
def replace_with(self, other): """Replace this element with the given DOMElement.""" self.after(other) self.parent.pop(self._own_index) return other
java
synchronized EvictionResult evictBefore(int oldestGeneration) { // Remove those entries that have a generation below the oldest permissible one. long sizeRemoved = 0; ArrayList<Short> removedGroups = new ArrayList<>(); for (val e : this.cacheEntries.entrySet()) { CacheEntry e...
python
def update_url(self, url=None): """ Accepts a fully-qualified url. Returns True if successful, False if not successful. """ if not url: raise ValueError("Neither a url or regex was provided to update_url.") post_url = "%s%s" % (self.BASE_URL, url) r = ...
python
def add_cmd_method(self, name, method, argc=None, complete=None): """Adds a command to the command line interface loop. Parameters ---------- name : string The command. method : function(args) The function to execute when this command is issued. The argu...
java
public String[] getContext(Object o) { String s = (String)o; int prevIndex = -1; int index = s.indexOf(' '); List cuts = new ArrayList(); while (index != -1) { cuts.add(s.substring(prevIndex+1, index)); prevIndex = index; index = s.indexOf(' ', ++index); } cuts.add(s.substring(prevIndex+1, s.lengt...
python
def EQ(classical_reg1, classical_reg2, classical_reg3): """ Produce an EQ instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalEqual instan...
python
def get_connection_string(connection=None): """return SQLAlchemy connection string if it is set :param connection: get the SQLAlchemy connection string #TODO :rtype: str """ if not connection: config = configparser.ConfigParser() cfp = defaults.config_file_path if os.path.ex...
python
def _int_values(self, shape): """ Return uniformly-distributed integers between 0 and 100. """ return (self.state.randint(low=0, high=100, size=shape) .astype('int64'))
java
public TagStreamRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
python
def validate_object(obj, field_validators=None, non_field_validators=None, schema=None, context=None): """ Takes a mapping and applies a mapping of validator functions to it collecting and reraising any validation errors that occur. """ if schema is None: schema = {} ...
python
def bust_caches(cls, obj, excludes=()): """Bust the cache for all :class:`.cached_property` objects on `obj` :param obj: The instance on which to bust the caches. """ for name, _ in cls.get_cached_properties(obj): if name in obj.__dict__ and not name in excludes: ...
java
@Override public CreateOrUpdateTagsResult createOrUpdateTags(CreateOrUpdateTagsRequest request) { request = beforeClientExecution(request); return executeCreateOrUpdateTags(request); }
python
def _mark_unknowns(self): """ Mark all unmapped regions. :return: None """ for obj in self.project.loader.all_objects: if isinstance(obj, cle.ELF): # sections? if obj.sections: for section in obj.sections: ...
python
def post_events(self, events): """ Posts a single event to the Keen IO API. The write key must be set first. :param events: an Event to upload """ url = "{0}/{1}/projects/{2}/events".format(self.base_url, self.api_version, sel...
java
public static WorkflowCreator creator(final String pathWorkspaceSid, final String friendlyName, final String configuration) { return new WorkflowCreator(pathWorkspaceSid, friendlyName, configuration); }
python
def integers(start, count): '''Generates in sequence the integral numbers within a range. Note: This method uses deferred execution. Args: start: The first integer in the sequence. count: The number of sequential integers to generate. Returns: A Queryable over the sp...
python
def update_configuration(self): """ Asynchronously applies or re-applies the SAS Logical Interconnect configuration to all managed interconnects of a SAS Logical Interconnect. Returns: dict: SAS Logical Interconnect. """ uri = "{}/configuration".format(self.d...
java
public boolean remove(T element) { for (Iterator<Node<T>> it = nodes.iterator(); it.hasNext(); ) if (ObjectUtil.equalsOrNull(it.next().element, element)) { it.remove(); return true; } return false; }
java
public void setWorkflowInstanceLinkLocalService( com.liferay.portal.kernel.service.WorkflowInstanceLinkLocalService workflowInstanceLinkLocalService) { this.workflowInstanceLinkLocalService = workflowInstanceLinkLocalService; }
python
def link_file(f, fldr): """ creates a html link for a file using folder fldr """ fname = os.path.join(fldr,f) if os.path.isfile(fname): return '<a href="/aikif/data/core/' + f + '">' + f + '</a>' else: return f
java
public ImageInner getByResourceGroup(String resourceGroupName, String imageName, String expand) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, imageName, expand).toBlocking().single().body(); }
java
public void setup() { introspector = JadeAgentIntrospector.getMyInstance(this); // Initializes the message count // introspector.storeBeliefValue(this, Definitions.RECEIVED_MESSAGE_COUNT, 0); // introspector.storeBeliefValue(this, Definitions.SENDED_MESSAGE_COUNT, 0); Moc...
python
def _get_arguments(self, action_node): """ Returns a dictionary of arguments for the given action_node. """ arguments = {} argument_nodes = action_node.iterfind( r'./ns:argumentList/ns:argument', namespaces={'ns': self.namespace}) for argument_node in argument...
python
def query(logfile, jobID = None): """If jobID is an integer then return False if the job has finished and True if it is still running. Otherwise, returns a table of jobs run by the user.""" joblist = logfile.readFromLogfile() if jobID and type(jobID) == type(1): command = ['qstat', '-j',...
python
def pretty_table(rows, header=None): """ Returns a string with a simple pretty table representing the given rows. Rows can be: - Sequences such as lists or tuples - Mappings such as dicts - Any object with a __dict__ attribute (most plain python objects) which is equivalent to passing ...
python
def get_rows_fieldnames_from_raw_sql( session: Union[Session, Engine, Connection], sql: str) -> Tuple[Sequence[Sequence[Any]], Sequence[str]]: """ Returns results and column names from a query. Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Conne...
python
def set_source_tags(self, id, **kwargs): # noqa: E501 """Set all tags associated with a specific source # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.set_so...
python
def build_layers(node, disambiguate_names=True): """ Return a list of GeoJSON FeatureCollections, one for each folder in the given KML DOM node that contains geodata. Name each FeatureCollection (via a ``'name'`` attribute) according to its corresponding KML folder name. If ``disambiguate_names == True...
python
def encode(cls, array): """ Encode a string numpy array, or an enum item numpy array, into an :any:`EnumArray`. See :any:`EnumArray.decode` for decoding. :param numpy.ndarray array: Numpy array of string identifiers, or of enum items, to encode. :returns: An :any:`EnumArray...
java
public static com.liferay.commerce.price.list.model.CommercePriceList fetchCommercePriceListByUuidAndGroupId( String uuid, long groupId) { return getService().fetchCommercePriceListByUuidAndGroupId(uuid, groupId); }
python
def get_group_line(self, data): """Get the next group-style key's line. :param data: the data to proceed :returns: the line number """ idx = -1 for key in self.groups: i = self.get_group_key_line(data, key) if (i < idx and i != -1) or idx == -1: ...
python
def package(input_dir, output_dir, meta_path=None, create_meta=False, force=False): """ Generate Python package for model data, including meta and required installation files. A new directory will be created in the specified output directory, and model data will be copied over. If --create-meta is s...
python
def saml_provider_present(name, saml_metadata_document, region=None, key=None, keyid=None, profile=None): ''' .. versionadded:: 2016.11.0 Ensure the SAML provider with the specified name is present. name (string) The name of the SAML provider. saml_metadata_document (string) The x...
java
public void setHost( String host ) { _host = null; if ( host != null && host.length() > 0 ) { // // Here's some very minimal support for IPv6 addresses. // If the literal IPv6 address is not enclosed in square brackets // then add them. ...
python
def _encode_personality(self, personality): """ Personality files must be base64-encoded before transmitting. """ if personality is None: personality = [] else: personality = utils.coerce_to_list(personality) for pfile in personality: ...
java
public ArrayList<OvhDslamLineProfile> serviceName_lines_number_dslamPort_availableProfiles_GET(String serviceName, String number) throws IOException { String qPath = "/xdsl/{serviceName}/lines/{number}/dslamPort/availableProfiles"; StringBuilder sb = path(qPath, serviceName, number); String resp = exec(qPath, "GE...
java
public static boolean isValidSerializeFormat(final String serializeFormat) throws SerializationException { if (!StringUtils.hasText(serializeFormat)) { throw new SerializationException("serialization format is either null or empty!"); } else if (serializeFormat.equalsIgnoreCase(XML_SERIALIZE_FORMAT) || serialize...
python
def dispatch(self,request,*args,**kwargs): ''' Always check that the temporary registration has not expired ''' regSession = self.request.session.get(REG_VALIDATION_STR,{}) if not regSession: return HttpResponseRedirect(reverse('registration')) try: reg = Tempor...
python
def ast_from_module_name(self, modname, context_file=None): """given a module name, return the astroid object""" if modname in self.astroid_cache: return self.astroid_cache[modname] if modname == "__main__": return self._build_stub_module(modname) old_cwd = os.get...
python
def _client(self, id, secret): """Performs client login with the provided credentials""" url = self.api_url + self.auth_token_url auth_string = '%s:%s' % (id, secret) authorization = base64.b64encode(auth_string.encode()).decode() headers = { 'Authorization': "Basic "...
python
def solidangle(twotheta, sampletodetectordistance, pixelsize=None): """Solid-angle correction for two-dimensional SAS images Inputs: twotheta: matrix of two-theta values sampletodetectordistance: sample-to-detector distance pixelsize: the pixel size in mm The output matrix is of th...
python
def format_delay(self, delay, limit, bucket, environ, start_response): """ Formats the over-limit response for the request. May be overridden in subclasses to allow alternate responses. """ # Set up the default status status = self.conf.status # Set up the retr...
java
private void preInvokeScript(ScriptWrapper script) throws ScriptException { if (script.getEngine() == null) { // Scripts loaded from the configs my have loaded before all of the engines script.setEngine(this.getEngineWrapper(script.getEngineName())); } if (script.getEngine() == null) { throw ne...
python
def add_on_channel_close_callback(self): """ Tell pika to call the on_channel_closed method if RabbitMQ unexpectedly closes the channel. """ self._logger.info('Adding channel close callback') self._channel.add_on_close_callback(self.on_channel_closed)
java
public ApiResponse<CharacterFwStatsResponse> getCharactersCharacterIdFwStatsWithHttpInfo(Integer characterId, String datasource, String ifNoneMatch, String token) throws ApiException { com.squareup.okhttp.Call call = getCharactersCharacterIdFwStatsValidateBeforeCall(characterId, datasource, ...
python
def get_all(jail=None): ''' Return a list of all available services .. versionchanged:: 2016.3.4 jail: optional jid or jail name CLI Example: .. code-block:: bash salt '*' service.get_all ''' ret = [] service = _cmd(jail) for srv in __salt__['cmd.run']('{0} -l'.forma...
python
def _apply_incoming_copying_manipulators(self, son, collection): """Apply incoming copying manipulators to `son`.""" for manipulator in self.__incoming_copying_manipulators: son = manipulator.transform_incoming(son, collection) return son
python
def wait(self, container, timeout=None, condition=None): """ Block until a container stops, then return its exit code. Similar to the ``docker wait`` command. Args: container (str or dict): The container to wait on. If a dict, the ``Id`` key is used. ...
java
@BetaApi public final ListBackendServicesPagedResponse listBackendServices(String project) { ListBackendServicesHttpRequest request = ListBackendServicesHttpRequest.newBuilder().setProject(project).build(); return listBackendServices(request); }
python
def action(args): """Roll back commands on a refpkg. *args* should be an argparse object with fields refpkg (giving the path to the refpkg to operate on) and n (giving the number of operations to roll back). """ log.info('loading reference package') r = refpkg.Refpkg(args.refpkg, create=Fa...
python
def main_module_name() -> str: """Returns main module and module name pair.""" if not hasattr(main_module, '__file__'): # running from interactive shell return None main_filename = os.path.basename(main_module.__file__) module_name, ext = os.path.splitext(main_filename) return modul...
java
@Override public List<CPDefinitionGroupedEntry> findByCPDefinitionId( long CPDefinitionId) { return findByCPDefinitionId(CPDefinitionId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
python
def tune(runner, kernel_options, device_options, tuning_options): """ Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type...
python
def _commit(self, path, title, source_id=None, description=None, author=None, language=None, license=None, copyright_holder=None, license_description=None, thumbnail=None): """ _commit: Adds folder/file to map Args: path: (str) where in zip to write file title: (str) ...
java
@Override public void reduceToSegmentKeys() { if (segmentRegistration != null && size > 0) { int sizeCopy = size; String[] keyListCopy = keyList.clone(); T1[] basicValueSumListCopy = basicValueSumList.clone(); long[] basicValueNListCopy = basicValueNList.clone(); size = 0; for ...
java
public void writeTo(Writer destination) { Element eltRuleset = new Element("ruleset"); addAttribute(eltRuleset, "name", name); addChild(eltRuleset, "description", description); for (PmdRule pmdRule : rules) { Element eltRule = new Element("rule"); addAttribute(elt...
python
def GET(self): """ Show page """ todos = model.get_todos() form = self.form() return render.index(todos, form)
python
def set_params(self, **params): """Set parameters on this object Safe setter method - attributes should not be modified directly as some changes are not valid. Valid parameters: - n_landmark - n_svd Parameters ---------- params : key-value pairs ...
python
def get_task_quota(self, task_name): """ Get queueing info of the task. Note that time between two calls should larger than 30 seconds, otherwise empty dict is returned. :param task_name: name of the task :return: quota info in dict format """ params = OrderedDic...
python
def matlabstr2py(string): """Return Python object from Matlab string representation. Return str, bool, int, float, list (Matlab arrays or cells), or dict (Matlab structures) types. Use to access ScanImage metadata. >>> matlabstr2py('1') 1 >>> matlabstr2py("['x y z' true false; 1 2.0 -3e4;...
python
def _split_path(path): """split a path return by the api return - the sentinel: - the rest of the path as a list. - the original path stripped of / for normalisation. """ path = path.strip('/') list_path = path.split('/') sentinel = list_path.pop(0) return sentinel, ...
python
def __add_bootstrap_tour_step(self, message, selector=None, name=None, title=None, alignment=None, duration=None): """ Allows the user to add tour steps for a website. @Params message - The message to display. selector - The CSS Selector of t...
java
public void applyAll(long index) { if (!log.isOpen()) return; // If the effective commit index is greater than the last index applied to the state machine then apply remaining entries. long lastIndex = Math.min(index, log.lastIndex()); if (lastIndex > lastApplied) { for (long i = lastApplie...
python
def temperature(self, what): """Set temperature.""" self._temperature = units.validate_quantity(what, u.K)
python
def handleHttpPost(request, endpoint): """ Handles the specified HTTP POST request, which maps to the specified protocol handler endpoint and protocol request class. """ if request.mimetype and request.mimetype != MIMETYPE: raise exceptions.UnsupportedMediaTypeException() request = reque...
java
public static StrLookup newOgnlLookup(final Object root) { return new OgnlStrLookup(INSTANCE.getEvaluators(getRootClass(root)), root); }
java
public final void synpred37_DRL5Expressions_fragment() throws RecognitionException { // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:653:9: ( DOT new_key ) // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:653:10: DOT new_key { match(input,DOT,FOLLOW_DOT_in_synpred37_DRL5Expressi...
java
private final void forwardResponseStatefully(final SipServletResponseImpl sipServletResponse) { final Response response = sipServletResponse.getResponse(); final ListIterator<ViaHeader> viaHeadersLeft = response.getHeaders(ViaHeader.NAME); // we cannot remove the via header on the original response (and we don't ...
java
@GetMapping public ResponseEntity<Greeting> greetingSync( @RequestParam(value = "name", defaultValue = "World") String name) { return ResponseEntity.ok(new Greeting(String.format(template, name))); }
python
def numbering_part(self): """ A |NumberingPart| object providing access to the numbering definitions for this document. Creates an empty numbering part if one is not present. """ try: return self.part_related_by(RT.NUMBERING) except KeyError: ...
python
def approximate_predict(clusterer, points_to_predict): """Predict the cluster label of new points. The returned labels will be those of the original clustering found by ``clusterer``, and therefore are not (necessarily) the cluster labels that would be found by clustering the original data combined with...
python
def open(self): """Toggle state to open switch disconnector""" if self._state != 'open': if self._line is not None: self._state = 'open' self._nodes = self.grid.graph.nodes_from_line(self._line) self.grid.graph.remove_edge( ...
java
public SearchResults query(WaybackRequest wbRequest) throws ResourceIndexNotAvailableException, ResourceNotInArchiveException, BadQueryException, AccessControlException { // throw new ResourceIndexNotAvailableException("oops"); ClosestTrackingCaptureFilterGroup closestGroup = new ClosestTrackingCaptureFilterGr...
java
@SuppressWarnings("unchecked") public static synchronized <T> IExpectationSetters<T> expectNew(String fullyQualifiedName, Object... arguments) throws Exception { final Class<?> forName = Class.forName(fullyQualifiedName); return (IExpectationSetters<T>) doExpectNew(forName, new DefaultMo...
java
public DateMidnight minusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().subtract(getMillis(), years); return withMillis(instant); }
java
public int moveControlInput(String strSuffix) throws DBException { int iDefaultParamsFound = DBConstants.NO_PARAMS_FOUND; if (!(this.getScreenField() instanceof BasePanel)) { // Regular input field if (this.getScreenField().isInputField()) { ...
python
def process_image_field(self, data): """ Process perseus fields like questions and hints, which look like: .. code-block:: python { "content": "md string including imgs like ![](URL-key) and ![](URL-key2)", "images": { "URL-key": {"width": 4...
java
@Override public ZMatrixRMaj getT(ZMatrixRMaj T ) { T = UtilDecompositons_ZDRM.checkZeros(T,N,N); T.data[0] = QT.data[0]; T.data[1] = QT.data[1]; for( int i = 1; i < N; i++ ) { T.set(i,i, QT.getReal(i,i), QT.getImag(i,i)); double real = QT.getReal(i-1,i); ...
java
public static <T> Stream<T> ofNullable(Iterable<T> iterable) { return null == iterable ? Stream.empty() : stream(iterable); }
java
public static ExpectedCondition<Boolean> currentUrlIsNotEmpty() { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { return !driver.getCurrentUrl().equals(""); } @Override public String toString() { return "current URL to be not empty"; } }; }
java
@SuppressWarnings("unchecked") private static void appendComposite(UriComponentsBuilder builder, String name, Object value) { if (value instanceof Iterable) { ((Iterable<?>) value).forEach(it -> builder.queryParam(name, it)); } else if (value instanceof Map) { ((Map<Object, Object>) value).entrySet() // ...
python
def create_bitcoind_connection( rpc_username, rpc_password, server, port, use_https, timeout ): """ Creates an RPC client to a bitcoind instance. It will have ".opts" defined as a member, which will be a dict that stores the above connection options. """ from .bitcoin_blockchain import AuthServ...
java
@Override public Predicate le(Expression<? extends Number> arg0, Number arg1) { // TODO Auto-generated method stub return new ComparisonPredicate(arg0, arg1, ConditionalOperator.LTE); }