language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void reportOnTomcatInformations() { // NOPMD // CHECKSTYLE:ON final Map<String, TomcatInformations> tcInfos = new LinkedHashMap<String, TomcatInformations>(); for (final TomcatInformations tcInfo : javaInformations.getTomcatInformationsList()) { if (tcInfo.getRequestCount() > 0) { final String...
java
protected synchronized void sendCommandToShard(VoidMessage message) { // if this node is shard - we just step over TCP/IP infrastructure // TODO: we want LocalTransport to be used in such cases if (nodeRole == NodeRole.SHARD) { message.setTargetId(shardIndex); messages.ad...
python
def _set_internal_value(self, new_internal_value): """ This is supposed to be only used by fitting engines :param new_internal_value: new value in internal representation :return: none """ if new_internal_value != self._internal_value: self._internal_value ...
python
def reset(self, path, pretend=False): """ Rolls all of the currently applied migrations back. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool :rtype: count """ self._notes = ...
java
@Override public EClass getIfcFeatureElementAddition() { if (ifcFeatureElementAdditionEClass == null) { ifcFeatureElementAdditionEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(266); } return ifcFeatureElementAdditionEClass; }
python
async def scan_for_units(self, iprange): """Scan local network for GH units.""" units = [] for ip_address in ipaddress.IPv4Network(iprange): sock = socket.socket() sock.settimeout(0.02) host = str(ip_address) try: scan_result = sock...
python
def is_valid_sid_for_chain(pid, sid): """Assert that ``sid`` can be assigned to the single object ``pid`` or to the chain to which ``pid`` belongs. - If the chain does not have a SID, the new SID must be previously unused. - If the chain already has a SID, the new SID must match the existing SID. ...
java
public static X509CertChainValidatorExt buildCertificateValidator( String trustAnchorsDir, ValidationErrorListener validationErrorListener, long updateInterval, boolean lazy) { return buildCertificateValidator(trustAnchorsDir, validationErrorListener, null, updateInterval, DEFAULT_NS_CHECKS, DEFAULT_...
python
def workdir_loaded(func): """ Decorator to make sure that the workdir is loaded when calling the decorated function """ @wraps(func) def decorator(workdir, *args, **kwargs): if not workdir.loaded: workdir.load() return func(workdir, *args, **kwargs) return deco...
java
public final boolean isEmpty() { if (mDatas.isEmpty()) { return true; } for (int i = 0; i < mDatas.size(); i++) { if (!mDatas.get(i).isEmpty()) { return false; } } return true; }
java
public static String generateCacheFileFullPath(String url, File cacheDir) { String fileName = md5(url); File cacheFile = new File(cacheDir, fileName); return cacheFile.getPath(); }
python
def main(start, end, out): """ Scrape a MLBAM Data :param start: Start Day(YYYYMMDD) :param end: End Day(YYYYMMDD) :param out: Output directory(default:"../output/mlb") """ try: logging.basicConfig(level=logging.WARNING) MlbAm.scrape(start, end, out) except MlbAmBadParame...
python
def values(self, *keys): """ Return the values of the record, optionally filtering to include only certain values by index or key. :param keys: indexes or keys of the items to include; if none are provided, all values will be included :return: list of values ...
python
def _read_chunk_from_socket(socket): """ (coroutine) Turn socket reading into coroutine. """ fd = socket.fileno() f = Future() def read_callback(): get_event_loop().remove_reader(fd) # Read next chunk. try: data = socket.recv(1024) except OSError...
java
public static Set<String> tupleToString(Set<Tuple> set) { Set<String> result = new LinkedHashSet<String>(); for (Tuple tuple : set) { String element = tuple.getElement(); result.add(element); } return result; }
python
def fetch_by_client_id(self, client_id): """ Retrieves a client by its identifier. :param client_id: The identifier of a client. :return: An instance of :class:`oauth2.datatype.Client`. :raises: :class:`oauth2.error.ClientError` if no client could be retrieved...
java
public static void checkColorRenderableTexture2D( final JCGLTextureFormat t) throws JCGLExceptionFormatError { if (!isColorRenderable2D(t)) { final String m = String.format( "Format %s is not color-renderable for 2D textures", t); assert m != null; throw new JCGLExceptionFormatEr...
java
public Matrix4x3d lerp(Matrix4x3dc other, double t, Matrix4x3d dest) { dest.m00 = m00 + (other.m00() - m00) * t; dest.m01 = m01 + (other.m01() - m01) * t; dest.m02 = m02 + (other.m02() - m02) * t; dest.m10 = m10 + (other.m10() - m10) * t; dest.m11 = m11 + (other.m11() - m11) * t;...
java
public static <T> Collection<T> findAmongst(Class<T> clazz, Object ... instances) { return findAmongst(clazz, Arrays.asList(instances)); }
python
def _kalman_update_step(k, p_m , p_P, p_meas_model_callable, measurement, calc_log_likelihood= False, calc_grad_log_likelihood=False, p_dm = None, p_dP = None): """ Input: k: int Iteration No. Starts at 0. Total number of iterations equal to the ...
java
private void cleanupInvalidRegistrationIDsForVariant(String variantID, MulticastResult multicastResult, List<String> registrationIDs) { // get the FCM send results for all of the client devices: final List<Result> results = multicastResult.getResults(); // storage for all the invalid registrat...
python
def system_reboot(wait_time_sec=20): """Reboots the system after a specified wait time. Must be run as root :param wait_time_sec: (int) number of sec to wait before performing the reboot :return: None :raises: SystemRebootError, SystemRebootTimeoutError """ log = logging.getLogger(mod_logger +...
python
def uniq(args): """ %prog uniq gffile > uniq.gff Remove redundant gene models. For overlapping gene models, take the longest gene. A second scan takes only the genes selected. --mode controls whether you want larger feature, or higher scoring feature. --best controls how many redundant feature...
python
def load(self, config): """Load the password from the configuration file.""" password_dict = {} if config is None: logger.warning("No configuration file available. Cannot load password list.") elif not config.has_section(self._section): logger.warning("No [%s] se...
java
public void selectValues(String... expectedValues) { String[] values = checkSelectValues(expectedValues, 0, 0); String reason = NO_ELEMENT_FOUND; if (values == null && getElement().is().present()) { reason = ELEMENT_NOT_SELECT; } assertNotNull(reason, values); ...
java
@Override public void visitMethod(Method obj) { methodName = obj.getName(); state = State.SAW_NOTHING; }
python
def nunpack(s, default=0): """Unpacks 1 to 4 byte integers (big endian).""" l = len(s) if not l: return default elif l == 1: return ord(s) elif l == 2: return struct.unpack('>H', s)[0] elif l == 3: return struct.unpack('>L', b'\x00'+s)[0] elif l == 4: ...
java
public static DatePickerDialog newInstance(OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { DatePickerDialog ret = new DatePickerDialog(); ret.initialize(callBack, year, monthOfYear, dayOfMonth); return ret; }
java
public boolean containsFile(SftpFile f) { return unchangedFiles.contains(f) || newFiles.contains(f) || updatedFiles.contains(f) || deletedFiles.contains(f) || recursedDirectories.contains(f.getAbsolutePath()) || failedTransfers.containsKey(f); }
java
@Override public void run() { population = createInitialPopulation() ; evaluatePopulation(population) ; evaluations = populationSize ; while (evaluations < maxEvaluations) { List<S> offspringPopulation = new ArrayList<>(populationSize); for (int i = 0; i < populationSize; i += 2) { ...
java
public JobWithDetails getJob(String jobName) throws IOException { return getJob(null, UrlUtils.toFullJobPath(jobName)); }
java
@Override public void eUnset(int featureID) { switch (featureID) { case XtextPackage.GENERATED_METAMODEL__NAME: setName(NAME_EDEFAULT); return; } super.eUnset(featureID); }
java
public static String getName(String x) { String ret = null; if (x.equals("280")) { ret = "DE"; } else if (x.equals("040")) { ret = "AT"; } else if (x.equals("250")) { ret = "FR"; } else if (x.equals("056")) { ret = "BE"; } ...
java
public static Vector3d[] calcInvertedAxes(Vector3d aAxis, Vector3d bAxis, Vector3d cAxis) { double det = aAxis.x * bAxis.y * cAxis.z - aAxis.x * bAxis.z * cAxis.y - aAxis.y * bAxis.x * cAxis.z + aAxis.y * bAxis.z * cAxis.x + aAxis.z * bAxis.x * cAxis.y - aAxis.z * bAxis.y * cAxis.x; Vect...
python
def next_file(self, close_previous=True): ''' Gets the next file to be scanned (including pending extracted files, if applicable). Also re/initializes self.status. All modules should access the target file list through this method. ''' fp = None # Ensure files ar...
java
private void setAllowedDate(final long date) { mAllowedDate = date; if (mSharedPreferences == null) { mSharedPreferences = mContext.getSharedPreferences( PREFERENCES_GEOCODER, Context.MODE_PRIVATE); } final Editor e = mSharedPreferences.edit(); e.p...
java
public static <Q> Object getPropertyValue(Q bean, String propertyName) { return ObjectUtils.getPropertyValue(bean, propertyName, Object.class); }
python
def getsshkeys(self): """ Gets all the ssh keys for the current user :return: a dictionary with the lists """ request = requests.get( self.keys_url, headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code ==...
java
@Override protected Set<String> extractSslRefs(Map<String, Object> properties, List<IIOPEndpoint> endpoints) { Set<String> result = new HashSet<String>(); for (IIOPEndpoint endpoint : endpoints) { for (Map<String, Object> iiopsOptions : endpoint.getIiopsOptions()) { Strin...
python
def get_patient_expression(job, patient_dict): """ Convenience function to get the expression from the patient dict :param dict patient_dict: dict of patient info :return: The gene and isoform expression :rtype: toil.fileStore.FileID """ expression_archive = job.fileStore.readGlobalFile(pat...
java
public void setScriptExtension(String scriptExtension) { if (scriptExtension.startsWith("*.")) { this.scriptExtension = scriptExtension; } else if (scriptExtension.startsWith(".")) { this.scriptExtension = "*" + scriptExtension; } else { this.scriptExtension =...
java
public void seek(long pos) { try { raFile.seek(pos); } catch (IOException e) { logger.log(Level.SEVERE, null, e); throw new RuntimeException(e); } }
java
public void beginStart(String resourceGroupName, String jobName, StartStreamingJobParameters startJobParameters) { beginStartWithServiceResponseAsync(resourceGroupName, jobName, startJobParameters).toBlocking().single().body(); }
java
private void setValue(Collection<R> values) { Collection<R> oldValues = this.values; this.values = values; maybeNotifyListeners(oldValues, values); }
python
def get_app(app=None, verbosity=0): """Uses django.db.djmodels.get_app and fuzzywuzzy to get the models module for a django app Retrieve an app module from an app name string, even if mispelled (uses fuzzywuzzy to find the best match) To get a list of all the apps use `get_app(None)` or `get_app([]) or get...
java
public javax.servlet.RequestDispatcher getRequestDispatcher(String handler) { MobicentsSipServlet sipServletImpl = (MobicentsSipServlet) getSipSession().getSipApplicationSession().getSipContext().findSipServletByName(handler); if(sipServletImpl == null) { throw new IllegalArgumentException(handler + " is not ...
python
def popen(fn, *args, **kwargs) -> subprocess.Popen: """ Please ensure you're not killing the process before it had started properly :param fn: :param args: :param kwargs: :return: """ args = popen_encode(fn, *args, **kwargs) logging.getLogger(__name__).debug('Start %s', args) ...
python
def spare_disk(self, disk_xml=None): """ Number of spare disk per type. For example: storage.ontap.filer201.disk.SATA """ spare_disk = {} disk_types = set() for filer_disk in disk_xml: disk_types.add(filer_disk.find('effective-disk-type').text) ...
python
def add_rule(self, rule_class, target_class=_Nothing): """Adds an authorization rule. :param rule_class: a class of authorization rule. :param target_class: (optional) a class or an iterable with classes to associate the rule with. """ if isinstance(target_class, Ite...
python
def run_from_argv(self, argv): """ Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments. """ option = '--testrunner=' for arg in argv[2:]: if arg.startswith(op...
java
public double[][] getS() { double[][] S = new double[n][n]; for(int i = 0; i < n; i++) { S[i][i] = this.s[i]; } return S; }
python
def find_one(self, cls, id): """Required functionality.""" db_result = None for rec in read_rec(cls.get_table_name(), id): db_result = rec break # Only read the first returned - which should be all we get if not db_result: return None obj = c...
python
def score(count_bigram, count1, count2, n_words): """Collocation score""" if n_words <= count1 or n_words <= count2: # only one words appears in the whole document return 0 N = n_words c12 = count_bigram c1 = count1 c2 = count2 p = c2 / N p1 = c12 / c1 p2 = (c2 - c12)...
python
def listify(args): """Return args as a list. If already a list - return as is. >>> listify([1, 2, 3]) [1, 2, 3] If a set - return as a list. >>> listify(set([1, 2, 3])) [1, 2, 3] If a tuple - return as a list. >>> listify(tuple([1, 2, 3])) [1, 2, 3] If a generator (als...
python
def queue_path(cls, project, location, queue): """Return a fully-qualified queue string.""" return google.api_core.path_template.expand( "projects/{project}/locations/{location}/queues/{queue}", project=project, location=location, queue=queue, )
java
boolean addOutputToken(Token idToken, Token paraToken) { tokens.add(idToken); tokens.add(paraToken); previousTextToken = null; return prepareNextScan(0); }
java
public static List<Map<String, Object>> getListMap(String sql, Object... arg) { Connection connection = JDBCUtils.getConnection(); PreparedStatement ps = null; ResultSet result = null; List<Map<String, Object>> listMap = new ArrayList<Map<String, Object>>(); try { ps ...
java
public void rebuildNode(String fullPath) throws Exception { Preconditions.checkArgument(ZKPaths.getPathAndNode(fullPath).getPath().equals(path), "Node is not part of this cache: " + fullPath); Preconditions.checkState(!executorService.isShutdown(), "cache has been closed"); ensurePath(); ...
java
@Override public EEnum getIfcStairFlightTypeEnum() { if (ifcStairFlightTypeEnumEEnum == null) { ifcStairFlightTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1070); } return ifcStairFlightTypeEnumEEnum; }
python
def Save(session, filename=None): """ save your session to use it later. Returns the filename of the written file. If not filename is given, a file named `androguard_session_<DATE>.ag` will be created in the current working directory. `<DATE>` is a timestamp with the following format: `%Y-%m-%d...
python
def get_instance(self, payload): """ Build an instance of BalanceInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.balance.BalanceInstance :rtype: twilio.rest.api.v2010.account.balance.BalanceInstance """ return ...
python
def check_token(self, respond): """ Check is the user's token is valid """ if respond.status_code == 401: self.credential.obtain_token(config=self.config) return False return True
python
def simxSetUIButtonLabel(clientID, uiHandle, uiButtonID, upStateLabel, downStateLabel, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if sys.version_info[0] == 3: if type(upStateLabel) is str: upStateLabel=upStateLabel.e...
python
def folder(self) -> typing.Union[str, None]: """ The folder, relative to the project source_directory, where the file resides :return: """ if 'folder' in self.data: return self.data.get('folder') elif self.project_folder: if callable(self...
java
public static FenceWait prepareWait(byte[] fenceId, TransactionSystemClient txClient) throws TransactionFailureException, InterruptedException, TimeoutException { return new DefaultFenceWait(new TransactionContext(txClient, new WriteFence(fenceId))); }
python
def msgbox(message='Shall I continue?', title='', buttonMessage='OK'): """Original doc: Display a messagebox """ return psidialogs.message(message=message, title=title, ok=buttonMessage)
python
def sources(self): """ Returns a dictionary of source methods found on this object, keyed on method name. Source methods are identified by (self, context) arguments on this object. For example: .. code-block:: python def f(self, context): ... ...
java
@Override public byte readDataType() { // prevent the handling of an empty Object if (buf.hasRemaining()) { do { // get the data type currentDataType = buf.get(); log.trace("Data type: {}", currentDataType); switch (currentDataType) { case AMF.TYPE_NULL: case AMF.TYPE_UNDEFINED: ret...
python
def get_url(self, link): """ URL of service """ view_name = SupportedServices.get_detail_view_for_model(link.service) return reverse(view_name, kwargs={'uuid': link.service.uuid.hex}, request=self.context['request'])
python
def plot(self, minx=-1.5, maxx=1.2, miny=-0.2, maxy=2, **kwargs): """Helper function to plot the Muller potential """ import matplotlib.pyplot as pp grid_width = max(maxx-minx, maxy-miny) / 200.0 ax = kwargs.pop('ax', None) xx, yy = np.mgrid[minx:maxx:grid_width, miny:m...
java
protected boolean isQuoteDelimiter( String character ) { String quoteDelimiters = "\"'"; if (quoteDelimiters.indexOf(character) < 0) return false; else return true; }
python
def _get_firmware_embedded_health(self, data): """Parse the get_host_health_data() for server capabilities :param data: the output returned by get_host_health_data() :returns: a dictionary of firmware name and firmware version. """ firmware = self.get_value_as_list(data['GET_EM...
python
def parse_veto_definer(veto_def_filename): """ Parse a veto definer file from the filename and return a dictionary indexed by ifo and veto definer category level. Parameters ---------- veto_def_filename: str The path to the veto definer file Returns: parsed_definition: dict ...
python
def flush(self, indices=None, refresh=None): """ Flushes one or more indices (clear memory) If a bulk is full, it sends it. (See :ref:`es-guide-reference-api-admin-indices-flush`) :keyword indices: an index or a list of indices :keyword refresh: set the refresh paramet...
python
def _as_json(self, response): """Assuming this is not empty, return the content as JSON. Result/exceptions is not determined if you call this method without testing _is_empty. :raises: DeserializationError if response body contains invalid json data. """ # Assume ClientResponse...
python
def crop(stream, x, y, width, height, **kwargs): """Crop the input video. Args: x: The horizontal position, in the input video, of the left edge of the output video. y: The vertical position, in the input video, of the top edge of the output video. width: The width...
java
public List<String> getValuesForFieldInPolicy(String sec, String ptype, int fieldIndex) { List<String> values = new ArrayList<>(); for (List<String> rule : model.get(sec).get(ptype).policy) { values.add(rule.get(fieldIndex)); } Util.arrayRemoveDuplicates(values); r...
python
def solve_dv_dt_v1(self): """Solve the differential equation of HydPy-L. At the moment, HydPy-L only implements a simple numerical solution of its underlying ordinary differential equation. To increase the accuracy (or sometimes even to prevent instability) of this approximation, one can set the v...
java
public void updateItem (T item) { if (_items == null) { return; } int idx = _items.indexOf(item); if (idx == -1) { _items.add(0, item); } else { _items.set(idx, item); } }
python
def update_user(self, user_is_artist="", artist_level="", artist_specialty="", real_name="", tagline="", countryid="", website="", bio=""): """Update the users profile information :param user_is_artist: Is the user an artist? :param artist_level: If the user is an artist, what level are they ...
python
def generate_lines(self, infile): """ Split file into lines return dict with line=input, depth=n """ pound = '#' for line in infile: heading = 0 if line.startswith(pound): heading = self.hash_count(line) yield dict(...
java
public static boolean coreExpandArchive(String sourcePath, String targetPath) throws IOException { ZipArchiveInputStream in = null; OutputStream out = null; try { // make sure we're working with absolute canonical paths File source = new File(sourcePath).getCanonicalFil...
java
synchronized public void recover() { if (tc.isEntryEnabled()) Tr.entry(tc, "recover", this); final int state = _status.getState(); if (_subordinate) { // For a subordinate, first check whether the global outcome is known locally. switch (state) { ...
java
public static PropDefConceptId getInstance(String propId, String propertyName, Value value, Metadata metadata) { List<Object> key = new ArrayList<>(4); key.add(propId); key.add(propertyName); key.add(value); key.add(Boolean.TRUE); //distinguishes these from properties...
python
def copy_data(self, project, logstore, from_time, to_time=None, to_client=None, to_project=None, to_logstore=None, shard_list=None, batch_size=None, compress=None, new_topic=None, new_source=None): """ copy data from one logstore to another one ...
java
@Override public StopApplicationResult stopApplication(StopApplicationRequest request) { request = beforeClientExecution(request); return executeStopApplication(request); }
java
public static <Item extends IItem> void attachToView(final EventHook<Item> event, final RecyclerView.ViewHolder viewHolder, View view) { if (event instanceof ClickEventHook) { view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {...
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case AfplibPackage.GSLJ__LINEJOIN: return LINEJOIN_EDEFAULT == null ? linejoin != null : !LINEJOIN_EDEFAULT.equals(linejoin); } return super.eIsSet(featureID); }
python
def _execute_handling(self, *eopatches, **kwargs): """ Handles measuring execution time and error propagation """ self.private_task_config.start_time = datetime.datetime.now() caught_exception = None try: return_value = self.execute(*eopatches, **kwargs) ...
java
@SuppressWarnings("unchecked") public void fromDmr(Object entity, String javaName, ModelType dmrType, Class<?> propertyType, ModelNode dmrPayload) throws Exception { Method target = entity.getClass().getMethod(javaName, propertyType); List<ModelNode> items = dmrPayload.isDefined() ? dmrPayload.asLi...
java
private List<Object> _jdoExecuteQuery( final String oql, final Object[] params ) { List<Object> results = null; try { results = getExtendedCastorTemplate().findByQuery( oql, params ); } catch (DataAccessException ex) { ...
java
public HostAvailabilityListener withHostUnavailableExceptions(Class<Throwable>... exceptionTypes) { hostUnavailableExceptions = new ArrayList<>(); for ( Class<Throwable> exception : exceptionTypes ) { hostUnavailableExceptions.add(exception); } return this; }
python
def unescape(s): r"""Inverse of `escape`. >>> unescape(r'\x41\n\x42\n\x43') 'A\nB\nC' >>> unescape(r'\u86c7') u'\u86c7' >>> unescape(u'ah') u'ah' """ if re.search(r'(?<!\\)\\(\\\\)*[uU]', s) or isinstance(s, unicode): return unescapeUnicode(s) else: return unescap...
python
def ipv6_generate_random(total=100): """ The generator to produce random, unique IPv6 addresses that are not defined (can be looked up using ipwhois). Args: total (:obj:`int`): The total number of IPv6 addresses to generate. Yields: str: The next IPv6 address. """ count = ...
java
@Override public void characters(char[] ch, int start, int length) throws SAXException { // 得到单元格内容的值 lastContent = lastContent.concat(new String(ch, start, length)); }
java
@Override public void start(Xid xid, int flags) throws XAException { synchronized (cpoXaStateMap) { // see if we are already associated with a global transaction if (cpoXaStateMap.getXaResourceMap().get(this) != null) throw CpoXaError.createXAException(CpoXaError.XAER_PROTO, "Start can not be...
python
def launch_keyword_wizard(self): """Launch keyword creation wizard.""" # make sure selected layer is the output layer if self.iface.activeLayer() != self.output_layer: return # launch wizard dialog keyword_wizard = WizardDialog( self.iface.mainWindow(), s...
python
def commit(self, wait=False, additionalParams={}): """ Commit is called once all parts are uploaded during a multipart Add Item or Update Item operation. The parts are combined into a file, and the original file is overwritten during an Update Item operation. This is an asynchron...
python
def json(self): """ convert webhook data to json :return webhook data as json: """ data = dict() embeds = self.embeds self.embeds = list() # convert DiscordEmbed to dict for embed in embeds: self.add_embed(embed) for key, value ...
java
private Set<String> getStringSet(I_CmsXmlContentLocation val, String path) { Set<String> valueSet = new HashSet<String>(); if ((val != null)) { List<I_CmsXmlContentValueLocation> singleValueLocs = val.getSubValues(path); for (I_CmsXmlContentValueLocation singleValueLoc : singleV...