language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private BasicCredentialsProvider getCredentialsProvider() { return new BasicCredentialsProvider() { private Set<AuthScope> authAlreadyTried = Sets.newHashSet(); @Override public Credentials getCredentials(AuthScope authscope) { if (authAlreadyTried.contains(a...
java
public ArrayList<Long> serviceName_dsRecord_GET(String serviceName, OvhKeyFlagEnum flags, OvhKeyStatusEnum status) throws IOException { String qPath = "/domain/{serviceName}/dsRecord"; StringBuilder sb = path(qPath, serviceName); query(sb, "flags", flags); query(sb, "status", status); String resp = exec(qPath...
java
@Nullable public Map<String, Object> getData() { if (fields == null) { return null; } Map<String, Object> decodedFields = new HashMap<>(); for (Map.Entry<String, Value> entry : fields.entrySet()) { Object decodedValue = decodeValue(entry.getValue()); decodedValue = convertToDateIfNe...
java
public void keepTopNElements(int N){ PriorityQueue<Pair<T, Double>> queue = asPriorityQueue(); clear(); for (int e = 0; e < N; e++) { Pair<T, Double> pair = queue.poll(); if (pair != null) incrementCount(pair.getFirst(), pair.getSecond()); } }
java
@Override public boolean isSelected() { WMenu menu = WebUtilities.getAncestorOfClass(WMenu.class, this); if (menu != null) { return menu.getSelectedMenuItems().contains(this); } return false; }
java
public Observable<Page<LoadBalancerInner>> listByResourceGroupNextAsync(final String nextPageLink) { return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<LoadBalancerInner>>, Page<LoadBalancerInner>>() { @Override pu...
java
protected void doResponseHeaders(final HttpServletResponse response, final String mimeType) { if (mimeType != null) { response.setContentType(mimeType); } }
python
def create(self): """ Override method for creating FormBaseNew form """ self.add_handlers({'^T': self.quit, '^Q': self.quit, '^V': self.toggle_view}) self.add(npyscreen.TitleFixedText, name=self.action['title'], value='') response = self.action['api_action'].in...
java
public String lookingAt(CharSequence text) { try { if (text.length() == 0) { if (acceptEmpty) { return ""; } else { throw new SyntaxErrorExcepti...
python
def remove(self): """ remove the entity from the Ariane server :return: """ LOGGER.debug("InjectorUITreeEntity.remove") if self.id and InjectorUITreeService.find_ui_tree_entity(self.id) is not None: args = {'properties': {'OPERATION': 'UNREGISTER', 'TREE_MENU_...
python
def pelican_init(pelicanobj): """ Loads the mathjax script according to the settings. Instantiate the Python markdown extension, passing in the mathjax script as config parameter. """ # Process settings, and set global var mathjax_settings = process_settings(pelicanobj) # Generate math...
java
private static int removeKamNode(KamNode collapsing, PreparedStatement knps, PreparedStatement knpps) throws SQLException { int collapsingId = collapsing.getId(); int updates = 0; knpps.setInt(1, collapsingId); updates += knpps.executeUpdate(); knps.setIn...
python
def get_next_schedule_brok(self): """ Create next_schedule (next check) brok :return: Brok object :rtype: alignak.Brok """ data = {'uuid': self.uuid} self.fill_data_brok_from(data, 'next_schedule') return Brok({'type': self.my_type + '_next_schedule', 'da...
python
def _get_dispatches(filter_kwargs): """Simplified version. Not distributed friendly.""" dispatches = Dispatch.objects.prefetch_related('message').filter( **filter_kwargs ).order_by('-message__time_created') return list(dispatches)
python
async def _auth_cram_md5(self, username, password): """ Performs an authentication attemps using the CRAM-MD5 mechanism. Protocol: 1. Send 'AUTH CRAM-MD5' to server ; 2. If the server replies with a 334 return code, we can go on: 1) The challenge (sent ...
java
protected boolean isBasename(String potentialPath){ if (ALLOW_VIEW_NAME_PATH_TRAVERSAL) { return true; } else { if (potentialPath.contains("\\") || potentialPath.contains("/")) { // prevent absolute path and folder traversal to find scripts return ...
java
public Money multipliedBy(BigDecimal valueToMultiplyBy, RoundingMode roundingMode) { return with(money.multiplyRetainScale(valueToMultiplyBy, roundingMode)); }
java
public static String[] getSelectColumns(String sql) { Asserts.notBlank(sql); sql = sql.trim(); if (sql.startsWith("select ") || sql.startsWith("SELECT ")) { sql = sql.substring(7).trim(); int idxFrom = sql.indexOf(" from "); if (idxFrom == -1) idxFrom = sql.indexOf(" FROM "); if (idxFrom == -1) ...
java
public SimpleConfiguration getClientConfiguration() { SimpleConfiguration clientConfig = new SimpleConfiguration(); Iterator<String> iter = getKeys(); while (iter.hasNext()) { String key = iter.next(); if (key.startsWith(CONNECTION_PREFIX) || key.startsWith(ACCUMULO_PREFIX) || key.star...
python
def set_nonblock(fd): # type: (int) -> None """Set the given file descriptor to non-blocking mode.""" fcntl.fcntl(fd, fcntl.F_SETFL, fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK)
java
public Observable<List<Tag>> getTagsAsync(UUID projectId, GetTagsOptionalParameter getTagsOptionalParameter) { return getTagsWithServiceResponseAsync(projectId, getTagsOptionalParameter).map(new Func1<ServiceResponse<List<Tag>>, List<Tag>>() { @Override public List<Tag> call(ServiceRespo...
python
def trace_region(self, region_index): """Retrieves the properties of a trace region. Args: self (JLink): the ``JLink`` instance. region_index (int): the trace region index. Returns: An instance of ``JLinkTraceRegion`` describing the specified region. """ ...
python
def bottom(self, z: float = 0.0) -> Location: """ :param z: the z distance in mm :return: a Point corresponding to the absolute position of the bottom-center of the well (with the front-left corner of slot 1 as (0,0,0)). If z is specified, returns a point ...
python
def draw_circle(self, center, radius, array, value, mode="set"): """ Draws a circle of specified radius on the input array and fills it with specified value :param center: a tuple for the center of the circle :type center: tuple (x,y) :param radius: how many pixels in radius the ...
java
public static ModelNode createReadResourceOperation(final ModelNode address, final boolean recursive) { final ModelNode op = createOperation(READ_RESOURCE_OPERATION, address); op.get(RECURSIVE).set(recursive); return op; }
python
def astra_supports(feature): """Return bool indicating whether current ASTRA supports ``feature``. Parameters ---------- feature : str Name of a potential feature of ASTRA. See ``ASTRA_FEATURES`` for possible values. Returns ------- supports : bool ``True`` if the c...
python
def flatten_dict(dict_obj, separator='.', flatten_lists=False): """Flattens the given dict into a single-level dict with flattend keys. Parameters ---------- dict_obj : dict A possibly nested dict. separator : str, optional The character to use as a separator between keys. Defaults ...
python
def logout_callback(): """Route called by the OpenID provider when user logs out. Clear the cookies here. """ resp = make_response('Logging Out') resp.set_cookie('sub', 'null', expires=0) resp.set_cookie('session_id', 'null', expires=0) return resp
python
def list_users(self): """ Get user list from the encrypted passdb file """ crypt = self._decrypt_file() self.logger.info(crypt.stderr) raw_userlist = crypt.stderr.split('\n') userlist = list() for index, line in enumerate(raw_userlist): if 'gp...
java
public JSONObject toJSON() throws JSONException { JSONObject json = new JSONObject(); json.put(JSON_TYPE, this.getType()); return json; }
python
def mavfmt(field): '''work out the struct format for a type''' map = { 'float' : 'f', 'double' : 'd', 'char' : 'c', 'int8_t' : 'b', 'uint8_t' : 'B', 'uint8_t_mavlink_version' : 'B', 'int16_t' : 'h', 'uint16_t' : 'H', 'int32_t'...
python
def add(self, text, checked=False, sort=None): """Add a new sub item to the list. This item must already be attached to a list. Args: text (str): The text. checked (bool): Whether this item is checked. sort (int): Item id for sorting. """ if self.pare...
python
def from_dict(input_dict): """ Instantiate an object of a derived class using the information in input_dict (built by the to_dict method of the derived class). More specifically, after reading the derived class from input_dict, it calls the method _build_from_input_dict of the de...
java
@Override public boolean matches(IAtom atom) { return ringSize < 0 ? invariants(atom).ringConnectivity() > 0 : invariants(atom).ringSize().contains(ringSize); }
python
def cmd_send(self, connection, sender, target, payload): """ Sends a message """ msg_target, topic, content = self.parse_payload(payload) results = self.__herald.send(msg_target, topic, content) self.safe_send(connection, target, "GOT RESULT: {0}".format(results))
java
public void delete(String sitePath) { CmsClientSitemapEntry entry = getEntry(sitePath); CmsClientSitemapEntry parent = getEntry(CmsResource.getParentFolder(entry.getSitePath())); CmsSitemapChange change = new CmsSitemapChange(entry.getId(), entry.getSitePath(), ChangeType.delete); chang...
java
void configure(String tilePath, OnOfflineTilesConfiguredCallback callback) { new ConfigureRouterTask(navigator, tilePath, callback).execute(); }
java
private static HashMap<String, ? super Serializable> convertToSerializable(Map<String, Object> objectMap) { HashMap<String, ? super Serializable> serializableMap = new HashMap<>(objectMap.size()); for (Map.Entry<String, Object> objectEntry : objectMap.entrySet()) { if (objectEntry.getValue()...
java
public JenkinsServer createView(FolderJob folder, String viewName, String viewXml) throws IOException { return createView(folder, viewName, viewXml, false); }
java
@Override public void loadFromXML(final InputStream in) throws IOException { lock.writeLock().lock(); try { properties.loadFromXML(in); } finally { lock.writeLock().unlock(); } }
python
def _set_media_type(self, v, load=False): """ Setter method for media_type, mapped from YANG variable /brocade_interface_ext_rpc/get_interface_detail/output/interface/media_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_media_type is considered as a p...
python
def struct_to_xml(node, struct): """ Turn a list of dicts into XML nodes with tag names taken from the dict keys and element text taken from dict values. This is a list of dicts so that the XML nodes can be ordered in the XML output. """ for obj in struct: for k, v in obj.items(): ...
java
public static String localizeString(String baseString) { if (baseString == null) { return null; } CmsWorkplaceMessages wpMessages = OpenCms.getWorkplaceManager().getMessages(A_CmsUI.get().getLocale()); CmsMacroResolver resolver = new CmsMacroResolver(); resolver.setM...
java
public DoubleMatrix solve(DoubleMatrix b) { DoubleMatrix x = getInstance(b.rows(), b.columns()); solve(b, x); return x; }
java
public void releaseDbResources() { Iterator it = m_rsIterators.iterator(); while (it.hasNext()) { ((OJBIterator) it.next()).releaseDbResources(); } }
java
public void initializeCurrency() { if (!currencyInitialized) { sendConsoleMessage(Level.INFO, getLanguageManager().getString("loading_currency_manager")); currencyManager = new CurrencyManager(); currencyInitialized = true; sendConsoleMessage(Level.INFO, getLangua...
python
def splitText(text): """ Split text into sub segments of size not bigger than MAX_SEGMENT_SIZE. """ segments = [] remaining_text = __class__.cleanSpaces(text) while len(remaining_text) > __class__.MAX_SEGMENT_SIZE: cur_text = remaining_text[:__class__.MAX_SEGMENT_SIZE] # try to split at pu...
java
public static int pitch_fr3( /* output: integer part of pitch period */ float exc[],int excs, /* input : excitation buffer */ float xn[],int xns, /* input : target vector */ float h[], int hs, /* input : impulse response of fi...
python
def inject_scheme(self, b16_scheme): """Inject string $b16_scheme into self.content.""" # correctly formatted start and end of block should have already been # ascertained by _get_temp content_lines = self.content.splitlines() b16_scheme_lines = b16_scheme.splitlines() st...
python
def list(self, order=values.unset, from_=values.unset, bounds=values.unset, limit=None, page_size=None): """ Lists SyncListItemInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. ...
python
def load_class(alias): """ Finds the class registered to the alias. The search is done in order: 1. Checks if the class name has been registered via L{register_class} or L{register_package}. 2. Checks all functions registered via L{register_class_loader}. 3. Attempts to load the ...
python
def compile_query(query: dict) -> PyQuery: """ Compiles a query Syntax: TBA """ def _pair_to_dict(pair): if isinstance(pair, dict): return pair return {pair[0]: pair[1]} def _reduce(pair): try: return {'and': (_pair_to_dict(pair[0]), _pai...
java
public static String joinPaths(String prefix, String path, boolean generatedPath) { String result = null; if (generatedPath) { result = joinDomainToPath(prefix, path); } else { result = joinPaths(prefix, path); } return result; }
java
public static Validator<Object> notNull(@NonNull final Context context) { return new NotNullValidator(context, R.string.default_error_message); }
python
def process(self, ymlfile): """Cleans out all document tags from the YAML file to make it JSON-friendly to work with the JSON Schema. """ output = "" try: # Need a list of line numbers where the documents resides # Used for finding/displaying errors ...
python
def detect_reedsolomon_parameters(message, mesecc_orig, gen_list=[2, 3, 5], c_exp=8): '''Use an exhaustive search to automatically find the correct parameters for the ReedSolomon codec from a sample message and its encoded RS code. Arguments: message is the sample message, eg, "hello world" ; mesecc_orig is the...
python
def type_match(a, b): """Return True of the types of a and b are compatible, False otherwise.""" # If the types are the same, return True if a['type'] == b['type']: return True # Otherwise, look at some special cases eq_groups = [ {'ONT::GENE-PROTEIN', 'ONT::GENE', 'ONT::PROTEIN'}, ...
python
def read_adjacency_matrix(file_path, separator, numbering="matlab"): """ Reads an edge list in csv format and returns the adjacency matrix in SciPy Sparse COOrdinate format. Inputs: - file_path: The path where the adjacency matrix is stored. - separator: The delimiter among values (e.g. ",", ...
python
async def AddCharm(self, channel, url): ''' channel : str url : str Returns -> None ''' # map input types to rpc msg _params = dict() msg = dict(type='Client', request='AddCharm', version=1, params=_...
python
def _view_interval(self, queue_type, queue_id): """Updates the queue interval in SharQ.""" response = { 'status': 'failure' } try: request_data = json.loads(request.data) interval = request_data['interval'] except Exception, e: resp...
java
@Override public MtasSpanWeight createWeight(IndexSearcher searcher, boolean needsScores, float boost) throws IOException { SpanWeight spanWeight = ((SpanQuery) searcher.rewrite(clause)) .createWeight(searcher, needsScores, boost); return new SpanTermWeight(spanWeight, searcher, boost); }
python
def copy(self): """Return a "clean" copy of this instance. Return: (instance): A clean copy of this instance. """ resource = copy.copy(self) # workaround for bytes/str issue in Py3 with copy of instance # TypeError: a bytes-like object is required, not 'str'...
python
def decode_response(client_message, to_object=None): """ Decode response from client message""" parameters = dict(response=None) response_size = client_message.read_int() response = [] for _ in range(0, response_size): response_item = client_message.read_data() response.append(respon...
java
public void collectUnsupportedStatuses( FilterAdapterContext context, Filter filter, List<FilterSupportStatus> statuses) { Preconditions.checkArgument(isFilterAProperSublcass(filter)); unsupportedStatusCollector.collectUnsupportedStatuses( context, unchecked(filter), st...
python
def load_field(wdir, shape_grid): """Extract electric field from simulation file "V_0Ereim.dat" Parameters ---------- wdir: str or pathlib.Path path to the working directory shape_grid: tuple of ints the shape of the simulation data grid Notes ----- These are the files ...
python
def deny_role(role): """Deny a role identified by an email address.""" def processor(action, argument): db.session.add( ActionRoles.deny(action, argument=argument, role_id=role.id) ) return processor
java
public ApiResponse<DogmaAttributeResponse> getDogmaAttributesAttributeIdWithHttpInfo(Integer attributeId, String datasource, String ifNoneMatch) throws ApiException { com.squareup.okhttp.Call call = getDogmaAttributesAttributeIdValidateBeforeCall(attributeId, datasource, ifNoneMatch,...
java
@Override public Enumeration<String> getAttributeNames() { if (isInvalid()) { throw new IllegalStateException("Session is invalid"); } return Collections.enumeration(this.attributes.keySet()); }
java
public synchronized AnimatedLabel addFrame(String text) { String[] lines = splitIntoMultipleLines(text); frames.add(lines); ensurePreferredSize(lines); return this; }
java
private String read(String path) throws IOException { StringBuffer sb = new StringBuffer(); String tempStr; File file = new File(path); // 如果文件不存在,读取失败 if (!file.exists()) throw new FileNotFoundException(); FileInputStream fis = new FileInputStream(file); Buffered...
java
public void clearMetaInfo(FacesContext context, UIComponent table) { context.getAttributes().remove(createKey(table)); }
java
public Collection<AlertCondition> list(List<String> queryParams) { return HTTP.GET("/v2/alerts_conditions.json", null, queryParams, ALERT_CONDITIONS).get(); }
python
def _raise_error_if_not_sframe(dataset, variable_name="SFrame"): """ Check if the input is an SFrame. Provide a proper error message otherwise. """ err_msg = "Input %s is not an SFrame. If it is a Pandas DataFrame," err_msg += " you may use the to_sframe() function to convert it to an SFrame." ...
java
public boolean waitFor(long timeout, TimeUnit unit) { try { return getProcess().waitFor(timeout, unit); } catch (InterruptedException ignore) { Thread.currentThread().interrupt(); return isNotRunning(); } }
python
def value(self): """ Take last known value as the value """ try: value = self.lastValue except IndexError: value = "NaN" except ValueError: value = "NaN" return value
python
def remove(self, context, request): """/@@API/remove: Remove existing object Required parameters: - UID: UID for the object. { runtime: Function running time. error: true or string(message) if error. false if no error. success: true or string(me...
java
public static Boolean toBooleanObject(final Integer value, final Integer trueValue, final Integer falseValue, final Integer nullValue) { if (value == null) { if (trueValue == null) { return Boolean.TRUE; } if (falseValue == null) { return Boole...
java
public boolean compareToBuffer(FieldList record) { boolean bBufferEqual = true; this.resetPosition(); // Start at the first field int iFieldCount = record.getFieldCount(); // Number of fields to read in for (int iFieldSeq = Constants.MAIN_FIELD; iFieldSeq <= iFieldCount + Constants...
java
public static base_response add(nitro_service client, ip6tunnel resource) throws Exception { ip6tunnel addresource = new ip6tunnel(); addresource.name = resource.name; addresource.remote = resource.remote; addresource.local = resource.local; return addresource.add_resource(client); }
java
public static String getSignatureBaseString(String requestMethod, String requestUrl, Map<String, String> protocolParameters) throws AuthException { StringBuilder sb = new StringBuilder(); sb.append(requestMethod.toUpperCase()).append("&") .append(AuthUtils.percentEncode(normalizeUrl(requestUrl)))....
python
def _extractCreations(self, dataSets): """ Find the elements of C{dataSets} which represent the creation of new objects. @param dataSets: C{list} of C{dict} mapping C{unicode} form submission keys to form submission values. @return: iterator of C{tuple}s with the fi...
python
def field_mapping_help(): """Help message for field mapping Dialog. .. versionadded:: 4.1.0 :returns: A message object containing helpful information. :rtype: messaging.message.Message """ message = m.Message() message.add(m.Brand()) message.add(heading()) message.add(content()) ...
python
def dump(self, raw=False): ''' Dump all output currently in the arm's output queue. ''' raw_out = self.ser.read(self.ser.in_waiting) if raw: return raw_out return raw_out.decode(OUTPUT_ENCODING)
java
public final ListCrawledUrlsPagedResponse listCrawledUrls(ScanRunName parent) { ListCrawledUrlsRequest request = ListCrawledUrlsRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .build(); return listCrawledUrls(request); }
java
private static String sectionToHtml( Section s ){ return "<table class=\"Section\">\n"+ "<tr><th class=\"Section\">\n" + "<table class=\"SectionTh\"><tr>\n" + "<th class=\"SectionTh\">\n" + (s.getClass() == SectionContainer.class?"SectionStructure":"SectionContent")+":<br>\n"+ "Level: "+s.getLev...
java
public Set<Type> getChildTypes() throws CacheReloadException { final Set<Type> ret = new HashSet<>(); for (final Long id : this.childTypes) { final Type child = Type.get(id); ret.add(child); ret.addAll(child.getChildTypes()); } return Colle...
java
public void onMessage(Mtp2Buffer rxFrame, Mtp2 mtp2) { // | ----------------------- TO L4 --------------------------- | // | --------------------- SIF ------------------------ | // FSN BSN LEN SIO DPC/OPC,SLS HEADING LEN // b1 b0 0e 01 01 80 00 00 21 70 01 02 03 04 05 06 0f CRC CRC ...
python
def new_dataset(data, identifier=None): """Initialize a new RT-DC dataset Parameters ---------- data: can be one of the following: - dict - .tdms file - .rtdc file - subclass of `RTDCBase` (will create a hierarchy child) identifier: str A u...
java
public static TypeMirror upperBound(Elements elements, TypeMirror type) { if (type.getKind() == TypeKind.WILDCARD) { WildcardType wildcard = (WildcardType) type; type = wildcard.getExtendsBound(); if (type == null) { type = elements.getTypeElement(Object.class.getName()).asType(); } ...
java
public void endDTD() throws org.xml.sax.SAXException { try { if (m_needToOutputDocTypeDecl) { outputDocTypeDecl(m_elemContext.m_elementName, false); m_needToOutputDocTypeDecl = false; } final java.io.Writer writer = m_wr...
java
public PagedList<KeyItem> listKeys(final String vaultBaseUrl, final Integer maxresults) { return getKeys(vaultBaseUrl, maxresults); }
python
def collect_prs_info(self): """Collect all pending merge PRs info. :returns: mapping of PRs by state """ REPO_RE = re.compile( '^(https://github.com/|git@github.com:)' '(?P<owner>.*?)/(?P<repo>.*?)(.git)?$') PULL_RE = re.compile( '^(refs/)?pul...
python
def create_explicit(bounds): """Creates a new instance of distribution with explicit buckets. bounds is an iterable of ordered floats that define the explicit buckets Args: bounds (iterable[float]): initializes the bounds Return: :class:`endpoints_management.gen.servicecontrol_v1_messag...
python
async def get_sleep_timer_settings(self) -> List[Setting]: """Get sleep timer settings.""" return [ Setting.make(**x) for x in await self.services["system"]["getSleepTimerSettings"]({}) ]
python
def feed(self, data = None): '''Provide bytes to encrypt (or decrypt), returning any bytes possible from this or any previous calls to feed. Call with None or an empty string to flush the mode of operation and return any final bytes; no further calls to feed may be m...
java
protected String toFilename(final Resource resource) throws UnsupportedOperationException { if (resource instanceof FileResource) { return ((FileResource) resource).getFile().getPath(); } throw new UnsupportedOperationException("Unsupported resource type: " + resource); }
java
public Map<List<Word>, Float> ngram(List<Word>... sentences){ if("bigram".equals(NGRAM)){ return Bigram.bigram(sentences); } if("trigram".equals(NGRAM)){ return Trigram.trigram(sentences); } return null; }
java
public static Comparator<IntTuple> byDistanceComparator( IntTuple reference, final ToDoubleBiFunction<? super IntTuple, ? super IntTuple> distanceFunction) { final IntTuple fReference = IntTuples.copy(reference); return new Comparator<IntTuple>() { ...
java
public View waitForView(View view, int timeout){ return waitForView(view, timeout, true, true); }
python
def recurse(name, source, keep_source=True, clean=False, require=None, user=None, group=None, dir_mode=None, file_mode=None, sym_mode=None, template=None, context=None, replace...