language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public List<CouchDbGoogleAuthenticatorAccount> findByUsername(final String username) { try { return queryView("by_username", username); } catch (final DocumentNotFoundException ignored) { return null; } }
java
@Override protected Set<String> getKeySet() { HashSet<String> result = new HashSet<>(); for (ConfigSource config : getConfigSources()) { Map<String, String> props = config.getProperties(); if (props != null) { Set<String> keys = props.keySet(); ...
python
def _try_reconnect(self): """Try to recover an interrupted connection.""" try: if self.connection_interrupted: self.connect_direct(self.connection_string, force=True) self.connection_interrupted = False self.connected = True #...
java
public boolean isValid() { // to be valid a scope must have a type set other than undefined and its name will be set return (type != null && !type.equals(ScopeType.UNDEFINED) && (name != null && !("").equals(name))); }
python
def to_iris_syscal(self, filename): """Export to IRIS Instrument configuration file Parameters ---------- filename : string Path to output filename """ with open(filename, 'w') as fid: # fprintf(fod, '#\t X\t Y\t Z\n'); fid.write('#\t ...
java
@Override public Profile getCCPPProfile(HttpServletRequest httpServletRequest) { ProfileFactory profileFactory = ProfileFactory.getInstance(); if (null == profileFactory) { // no CCPP implementation available, just return null return null; } else { Profile...
java
@Override public final void hndCartChan(final Map<String, Object> pRqVs, final Cart pCart, final TaxDestination pTxRules) throws Exception { @SuppressWarnings("unchecked") List<Deliv> dlvMts = (List<Deliv>) pRqVs.get("dlvMts"); Deliv cdl = null; for (Deliv dl : dlvMts) { if (dl.getItsId().eq...
python
def get_ips(self, interface=None, family=None, scope=None, timeout=0): """ Get a tuple of IPs for the container. """ kwargs = {} if interface: kwargs['interface'] = interface if family: kwargs['family'] = family if scope: k...
python
def get_modules(modulename=None): """Return a list of modules and packages under modulename. If modulename is not given, return a list of all top level modules and packages. """ modulename = compat.ensure_not_unicode(modulename) if not modulename: try: return ([modname for ...
python
def transparency(self): """ Does the current object contain any transparency. Returns ---------- transparency: bool, does the current visual contain transparency """ if 'vertex_colors' in self._data: a_min = self._data['vertex_colors'][:, 3].min() ...
python
def get_based_on_grades_metadata(self): """Gets the metadata for a grade-based designation. return: (osid.Metadata) - metadata for the grade-based designation *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.re...
python
def _get_value(self): """ Return two delegating variables. Each variable should contain a value attribute with the real value. """ x, y = self._point.x, self._point.y self._px, self._py = self._item_point.canvas.get_matrix_i2i(self._item_point, ...
python
def pack_ihex(type_, address, size, data): """Create a Intel HEX record of given data. """ line = '{:02X}{:04X}{:02X}'.format(size, address, type_) if data: line += binascii.hexlify(data).decode('ascii').upper() return ':{}{:02X}'.format(line, crc_ihex(line))
java
private Object getTarget(Map<String, Command> references) throws Exception { if (target == null) { if (isReference()) { Command cmd = references.get(getAttr("idref")); //$NON-NLS-1$ target = (cmd != null) ? cmd.getResultValue() : null; } else if (isExecutable()) { String className = null...
java
@Override public boolean getChildNodesDataByPage(NodeData parent, int fromOrderNum, int offset, int pageSize, List<NodeData> childNodes) throws RepositoryException, IllegalStateException { checkIfOpened(); ResultSet resultSet = null; try { resultSet = findChildNodesByParentI...
java
public LongStreamEx takeWhile(LongPredicate predicate) { return VER_SPEC.callWhile(this, Objects.requireNonNull(predicate), false); }
java
@Override public DecompilationResult decompileClassFile(Path rootDir, Path classFilePath, Path outputDir) throws DecompilationException { Checks.checkDirectoryToBeRead(rootDir.toFile(), "Classes root dir"); File classFile = classFilePath.toFile(); Checks.checkFileToBeRead...
python
def extract_command(outputdir, domain_methods, text_domain, keywords, comment_tags, base_dir, project, version, msgid_bugs_address): """Extracts strings into .pot files :arg domain: domains to generate strings for or 'all' for all domains :arg outputdir: output dir f...
python
def process_new_issues(self, volumes, existing_issues): """Takes a dict of existing volumes missing tags and a dict of existing issues, and finds any new or updated issues. Args: volumes (:obj:`dict` of `str`: `EBSVolume`): Dict of current volumes with issues existing_is...
java
public void setTheta(double theta) { // Next lines are to prevent numbers like -1.8369701E-16 // when working with negative numbers if ((theta < -360) || (theta > 360)) { theta = theta % 360; } if (theta < 0) { theta = 360 + theta; } double oldTheta = getTheta(); if ((theta < -360) || (t...
java
public static java.util.List<com.liferay.commerce.product.model.CPAttachmentFileEntry> getCPAttachmentFileEntriesByUuidAndCompanyId( String uuid, long companyId) { return getService() .getCPAttachmentFileEntriesByUuidAndCompanyId(uuid, companyId); }
java
public static ChainableStatement hover(JsScope over, JsScope out) { return new DefaultChainableStatement("hover", over.render(), out.render()); }
python
def _update_progress_bar(self): # type: (SyncCopy) -> None """Update progress bar :param SyncCopy self: this """ blobxfer.operations.progress.update_progress_bar( self._general_options, 'synccopy', self._synccopy_start_time, self._s...
java
private ColorItem buildColorItem(int colorId, String label) { Color color; String colorName; switch (colorId) { case 0: color = new Color(0, 0, 0, 0); colorName = "No Color"; break; case 1: color = Color.PINK...
java
@SuppressWarnings("unchecked") private void saveToCookie(IExtendedRequest req, String reqURL, AuthenticationResult result, boolean keepInput) { String strParam = null; try { strParam = serializePostParam(req, reqURL, keepInput); } catch (Exception e) { if (tc.isDebugEnabled()) { Tr.debug(tc, "IO Excep...
python
def _get_connected_subgraphs(vertices, vertices_neighbours): """Break a graph containing unconnected subgraphs into a list of connected subgraphs. Returns ------- [set([vertex, ...]), ...] """ remaining_vertices = set(vertices) subgraphs = [] while remaining_vertices: subgra...
python
def _run(self): """Run the receiver. """ port = broadcast_port nameservers = [] if self._multicast_enabled: recv = MulticastReceiver(port).settimeout(2.) while True: try: recv = MulticastReceiver(port).settimeout(2.) ...
java
public static long count_filtered(nitro_service service, String ciphergroupname, String filter) throws Exception{ sslcipher_individualcipher_binding obj = new sslcipher_individualcipher_binding(); obj.set_ciphergroupname(ciphergroupname); options option = new options(); option.set_count(true); option.set_filt...
java
@Action( semantics = SemanticsOf.IDEMPOTENT, command = CommandReification.ENABLED, hidden = Where.EVERYWHERE // otherwise will throw exception: "Only actions can be executed in the background (method _d69setName represents a PROPERTY')" ) @ActionLayout( describedA...
python
def prepend_to_file(path, data, bufsize=1<<15): """TODO: * Add a random string to the backup file. * Restore permissions after copy. """ # Backup the file # backupname = path + os.extsep + 'bak' # Remove previous backup if it exists # try: os.unlink(backupname) except OSError: pass ...
python
def semanticSimilarity(self, text1, text2, distanceMeasure = "cosine"): """ determine the semantic similarity of the two provided documents @param text1: first document to analyze @param text2: second document to analyze @param distanceMeasure: distance measure to use for compari...
python
def print_traceback(self): """ Print the traceback of the exception wrapped by the AbbreviatedException. """ traceback.print_exception(self.etype, self.value, self.traceback)
java
public WritableGridFileChannel getWritableChannel(String pathname, boolean append) throws IOException { return getWritableChannel(pathname, append, defaultChunkSize); }
java
public static Class<?> classForNameOrNull(final String className) { try { return Class.forName(className); } catch (final ReflectiveOperationException | LinkageError e) { return null; } }
java
protected ThreadBase<E> getReadingThread(ExceptionHandler<IOException> exceptionHandler, MutableObjectIterator<E> reader, CircularQueues<E> queues, AbstractInvokable parentTask, TypeSerializer<E> serializer, long startSpillingBytes) { return new ReadingThread<E>(exceptionHandler, reader, queues, serializer.cre...
java
@Override public List<TimephasedWork> getData() { if (m_raw) { m_normaliser.normalise(m_calendar, m_data); m_raw = false; } return m_data; }
python
def peek_many(self, n): """ Actually this can be quite inefficient Example: >>> # DISABLE_DOCTEST >>> import utool as ut >>> items = list(zip(range(256), range(256))) >>> n = 32 >>> ut.shuffle(items) >>> self = ut.PriorityQ...
java
public static void main(final String[] args) throws Exception { if (args.length < 1) { LOG.info("usage: example-class"); System.exit(1); } final ExampleType ex = lookupExample(args[0]); final GLProfile pro = GLProfile.get(GLProfile.GL3); final GLCapabilities caps = new GLCapabili...
python
def save_images(self, directory=None, axis='z', channel=None, global_norm=True, image_format='PNG'): """See cloudvolume.lib.save_images for more information.""" if directory is None: directory = os.path.join('./saved_images', self.dataset_name, self.layer, str(self.mip), self.bounds.to_filename()) re...
python
def codes_get_string_array(handle, key, size, length=None): # type: (cffi.FFI.CData, bytes, int, int) -> T.List[bytes] """ Get string array values from a key. :param bytes key: the keyword whose value(s) are to be extracted :rtype: T.List[bytes] """ if length is None: length = code...
python
def get_base_fields(msg, prefix='', parse_header=True): '''function to get the full names of every message field in the message''' slots = msg.__slots__ ret_val = [] msg_types = dict() for i in slots: slot_msg = getattr(msg, i) if not parse_header and i == 'header': conti...
java
@Override public UpdatePortfolioResult updatePortfolio(UpdatePortfolioRequest request) { request = beforeClientExecution(request); return executeUpdatePortfolio(request); }
python
def upgradePrivateApplication3to4(old): """ Upgrade L{PrivateApplication} from schema version 3 to schema version 4. Copy all existing attributes to the new version and use the L{PrivateApplication} to power up the item it is installed on for L{ITemplateNameResolver}. """ new = old.upgradeV...
python
def ned2aer(n: float, e: float, d: float, deg: bool = True) -> Tuple[float, float, float]: """ converts North, East, Down to azimuth, elevation, range Parameters ---------- n : float or numpy.ndarray of float North NED coordinate (meters) e : float or numpy.ndarray of float...
python
def resetSession(self, username=None, password=None, verify=True) : """resets the session""" self.disconnectSession() self.session = AikidoSession(username, password, verify)
python
def redirect(view=None, url=None, **kwargs): """Redirects to the specified view or url """ if view: if url: kwargs["url"] = url url = flask.url_for(view, **kwargs) current_context.exit(flask.redirect(url))
python
def check_expected_future_model_list_is_empty(target_state_m, msg, delete=True, with_logger=None): """ Checks if the expected future models list/set is empty Return False if there are still elements in and also creates a warning message as feedback. :param StateModel target_state_m: The state model which ...
python
def thumbnail_source_for_display_item(self, ui, display_item: DisplayItem.DisplayItem) -> ThumbnailSource: """Returned ThumbnailSource must be closed.""" with self.__lock: thumbnail_source = self.__thumbnail_sources.get(display_item) if not thumbnail_source: thumb...
java
public static int match(Method[] methods, String name, Type... params) { int paramCount = params.length; int matchCount = methods.length; Method m; int[] costs = new int[matchCount]; // Filter the available methods down to a smaller set, tossing // out candidates that c...
java
public void setInstanceSnapshots(java.util.Collection<InstanceSnapshot> instanceSnapshots) { if (instanceSnapshots == null) { this.instanceSnapshots = null; return; } this.instanceSnapshots = new java.util.ArrayList<InstanceSnapshot>(instanceSnapshots); }
python
def logout(self): """ Logout from the remote server. """ self.client.write('exit\r\n') self.client.read_all() self.client.close()
python
def bulk_invoke(func, args, nargs): """Bulk invoke a function via queues Uses internal implementation details of rq. """ # for comparison, simplest thing that works # for i in nargs: # argv = list(args) # argv.append(i) # func.delay(*argv) # some variances between cpy and ...
python
def set_computable_distance(self, value): ''' setter ''' if isinstance(value, ComputableDistance) is False: raise TypeError() self.__computable_distance = value
python
def stat(self, paths): ''' Stat a fileCount :param paths: Path :type paths: string :returns: a dictionary **Example:** >>> client.stat(['/index.asciidoc']) {'blocksize': 134217728L, 'owner': u'wouter', 'length': 100L, 'access_time': 1367317326510L, 'group': u's...
java
private HDFSSegmentHandle asReadableHandle(SegmentHandle handle) { Preconditions.checkArgument(handle instanceof HDFSSegmentHandle, "handle must be of type HDFSSegmentHandle."); return (HDFSSegmentHandle) handle; }
java
private UserAlias getUserAlias(Object attribute) { if (m_userAlias != null) { return m_userAlias; } if (!(attribute instanceof String)) { return null; } if (m_alias == null) { return null; } if (m_aliasPath == null) { boolean allPathsAliased = true; return new User...
python
def download_session_log(self, scenario_name, timeout=5): """ download the session log file from remote selenoid, renaming the file to scenario name and removing the video file in the server. GGR request: http://<username>:<password>@<ggr_host>:<ggr_port>/logs/<ggr_session_id> ...
python
def loop(self): """ Main control loop runs the following steps: 1. Re-draw the screen 2. Wait for user to press a key (includes terminal resizing) 3. Trigger the method registered to the input key 4. Check if there are any nested pages that need to be loop...
python
def add_dict_to_hash(a_hash, a_dict): """Adds `a_dict` to `a_hash` Args: a_hash (`Hash`): the secure hash, e.g created by hashlib.md5 a_dict (dict[string, [string]]): the dictionary to add to the hash """ if a_dict is None: return for k, v in a_dict.items(): a_hash.up...
python
def _group_by_sample(items): """Group a set of items by sample names + multiple callers for prioritization """ by_sample = collections.defaultdict(list) for d in items: by_sample[dd.get_sample_name(d)].append(d) out = [] for sample_group in by_sample.values(): cur = utils.deepish...
java
public static <T> CloseableReference<T> closeableFrom(@WillNotClose @Nullable final T reference, Closer<T> closer) { return new CloseableReference<>(reference, closer); }
python
def p_for_stmt(p): """ for_stmt : FOR ident EQ expr SEMI stmt_list END_STMT | FOR LPAREN ident EQ expr RPAREN SEMI stmt_list END_STMT | FOR matrix EQ expr SEMI stmt_list END_STMT """ if len(p) == 8: if not isinstance(p[2], node.ident): raise_exception(Syntax...
python
def catch(ignore=[], was_doing="something important", helpfull_tips="you should use a debugger", gbc=None): """ Catch, prepare and log error :param exc_cls: error class :param exc: exception :param tb: exception traceback """ exc_cls, exc, tb=sys.exc_info() ...
python
def agedepth(self, d): """Get calendar age for a depth Parameters ---------- d : float Sediment depth (in cm). Returns ------- Numeric giving true age at given depth. """ # TODO(brews): Function cannot handle hiatus # See line...
java
public LocalTime withPeriodAdded(ReadablePeriod period, int scalar) { if (period == null || scalar == 0) { return this; } long instant = getChronology().add(period, getLocalMillis(), scalar); return withLocalMillis(instant); }
java
public static List<CPOptionValue> findByCPOptionId(long CPOptionId, int start, int end) { return getPersistence().findByCPOptionId(CPOptionId, start, end); }
python
def count(forward_in, reverse_in='NA', kmer_size=31, count_file='mer_counts.jf', hash_size='100M', options='', returncmd=False): """ Runs jellyfish count to kmerize reads to a desired kmer size. :param forward_in: Forward input reads or fasta file. Can be uncompressed or gzip compressed. :para...
java
private void sendAuthResponse(HttpServletResponse response) throws IOException { response.setHeader("WWW-Authenticate", String.format("Basic realm=\"%1$s\"", realm)); //$NON-NLS-1$ //$NON-NLS-2$ response.sendError(HttpServletResponse.SC_UNAUTHORIZED); }
python
def results_by_parameter(res, param, sort_by=None, sort_desc=False): """ Takes a list of evaluation results `res` returned by a LDA evaluation function (a list in the form `[(parameter_set_1, {'<metric_name>': result_1, ...}), ..., (parameter_set_n, {'<metric_name>': result_n, ...})]`) and returns a lis...
java
public int[] extractUShortArray(final DeviceData deviceData) { final short[] argout = DevVarUShortArrayHelper.extract(deviceData.getAny()); final int[] val = new int[argout.length]; for (int i = 0 ; i<argout.length ; i++) { val[i] = 0xFFFF & argout[i]; } return val; ...
python
def run(self): """Main logic for this thread to execute.""" if platform.system() == 'Windows': # Windows doesn't support file-like objects for select(), so fall back # to raw_input(). response = input(''.join((self._message, os.linesep, ...
java
@Override public AddRoleToDBInstanceResult addRoleToDBInstance(AddRoleToDBInstanceRequest request) { request = beforeClientExecution(request); return executeAddRoleToDBInstance(request); }
python
def floyd_warshall(self): ''' API: floyd_warshall(self) Description: Finds all pair shortest paths and stores it in a list of lists. This is possible if the graph does not have negative cycles. It will return a tuple with 3 elements. The first elem...
python
def dispatch_error(self, err): ''' Handles the dispatch of errors ''' try: data = {'error': [l for l in err.args]} body = self._meta.formatter.format(data) except Exception as ex: data = {'error': str(err)} body = self._meta.formatt...
java
public static DispatchQueue createBackgroundQueue(String name, DispatchQueueType type) { if (type == DispatchQueueType.Serial) { return new SerialDispatchQueue(name); } if (type == DispatchQueueType.Concurrent) { return new ConcurrentDispatchQueue(name); } throw new IllegalArgumentException("Unexpected...
python
def revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id): """Create a new revision file.""" _revision(directory, message, autogenerate, sql, head, splice, branch_label, version_path, rev_id)
java
@Override public void deleteAll() throws LockingException { Connection conn = null; Statement stmnt = null; try { String sql = "DELETE FROM " + LOCK_TABLE; if (log.isDebugEnabled()) log.debug("RDBMEntityLockStore.deleteAll(): " + sql); conn = RDBMServices...
java
public Object put(final String key, final Object value) { return additionalData.put(key, value); }
java
@SuppressWarnings("unchecked") @Override public PrefixedPropertiesEnumeration<Object> keys() { lock.readLock().lock(); try { @SuppressWarnings("rawtypes") final Set keys = keySet(); @SuppressWarnings("rawtypes") final Iterator it = keys.iterator(); return new PrefixedPropertiesEnumerationImpl<Objec...
java
public RolloverDescription initialize( final String file, final boolean append) { String newActiveFile = file; explicitActiveFile = false; if (activeFileName != null) { explicitActiveFile = true; newActiveFile = activeFileName; } if (file != null) { explicitActiveFile = true;...
java
public void addFieldQueryMust(String fieldName, String searchQuery) { addFieldQuery(fieldName, searchQuery, BooleanClause.Occur.MUST); }
java
public ValidationConfigType<T> constraintMapping(String ... values) { if (values != null) { for(String name: values) { childNode.createChild("constraint-mapping").text(name); } } return this; }
java
@Nonnull public EChange disableUser (@Nullable final String sUserID) { final User aUser = getOfID (sUserID); if (aUser == null) { AuditHelper.onAuditModifyFailure (User.OT, sUserID, "no-such-user-id", "disable"); return EChange.UNCHANGED; } m_aRWLock.writeLock ().lock (); try ...
python
def _model_count_step(self, count, model): """ Count the number of models in the database. Example: .. code-block:: gherkin Then there should be 0 goals in the database """ model = get_model(model) expected = int(count) found = model.objects.count() assert found == expec...
java
protected Embedder newEmbedder() { Embedder embedder = null; EmbedderClassLoader classLoader = classLoader(); if (injectableEmbedderClass != null) { embedder = classLoader.newInstance(InjectableEmbedder.class, injectableEmbedderClass).injectedEmbedder(); } else { ...
java
public final int bubblePressure(double pressureEstimate,Map<String,Double>vaporFractionsEstimate){ for(Compound c: components){ double fraction = vaporFractionsEstimate.get(c.getName()); getVapor().setFraction(c, fraction); } setPressure(pressureEstimate); return bubblePressu...
java
public ApiSuccessResponse logoutAgentState(MediaLogoutData mediaLogoutData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = logoutAgentStateWithHttpInfo(mediaLogoutData); return resp.getData(); }
python
def _euler_to_q(self, euler): """ Create q array from euler angles :param euler: array [roll, pitch, yaw] in rad :returns: array q which represents a quaternion [w, x, y, z] """ assert(len(euler) == 3) phi = euler[0] theta = euler[1] psi = euler[2]...
python
def read(self, file_or_filename): """ Loads a pickled case. """ if isinstance(file_or_filename, basestring): fname = os.path.basename(file_or_filename) logger.info("Unpickling case file [%s]." % fname) file = None try: file = open(...
java
public ManagedDatabaseInner update(String resourceGroupName, String managedInstanceName, String databaseName, ManagedDatabaseUpdate parameters) { return updateWithServiceResponseAsync(resourceGroupName, managedInstanceName, databaseName, parameters).toBlocking().last().body(); }
java
public static ZonedDateTime leftShift(final ZoneId self, LocalDateTime dateTime) { return ZonedDateTime.of(dateTime, self); }
java
public FaunusPipeline order(final com.tinkerpop.gremlin.Tokens.T order, final String elementKey) { return this.order(com.tinkerpop.gremlin.Tokens.mapOrder(order), elementKey); }
python
def load_parameter_definitions(self, sheet_name: str = None): """ Load variable text from rows in excel file. If no spreadsheet arg is given, all spreadsheets are loaded. The first cell in the first row in a spreadsheet must contain the keyword 'variable' or the sheet is ignored. ...
java
public DateTimeFormatterBuilder appendValue(TemporalField field, int width) { Jdk8Methods.requireNonNull(field, "field"); if (width < 1 || width > 19) { throw new IllegalArgumentException("The width must be from 1 to 19 inclusive but was " + width); } NumberPrinterParser pp =...
python
def add_sub_resource(self, relative_id, sub_resource): """Add sub resource""" existing_sub_resources = self.resources.get(sub_resource.RELATIVE_PATH_TEMPLATE, defaultdict(list)) existing_sub_resources[relative_id].append(sub_resource) self.resources.update({sub_resource.RELATIVE_PATH_TEM...
python
def _get_rest_doc(self, request, start_response): """Sends back HTTP response with API directory. This calls start_response and returns the response body. It will return the discovery doc for the requested api/version. Args: request: An ApiRequest, the transformed request sent to the Discovery ...
java
private int addAlgorithmName(int maxlength) { int result = 0; for (int i = m_algorithm_.length - 1; i >= 0; i --) { result = m_algorithm_[i].add(m_nameSet_, maxlength); if (result > maxlength) { maxlength = result; } } return maxlen...
java
private void refresh(AddressTemplate addressTemplate) { addressTemplate = addressTemplate.subTemplate(0, 3); switch (addressTemplate.getResourceType()) { case WebServicesStore.ENDPOINT_CONFIG: circuit.dispatch(new ReadAllEndpointConfig(addressTemplate)); break...
java
public void writeClassInitialize(boolean bUseInitValues) { Record recClassFields = this.getRecord(ClassFields.CLASS_FIELDS_FILE); try { String strFieldName, strReference; String strFieldClass; // Now, zero out all the class fields recClassFields...
java
public boolean isGroupEnd() { if (getValue() == null || isCommand() || getValue().length() != 1) return false; return getValue().charAt(0) == ')' || getValue().charAt(0) == ']'; }