language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@Override public DescribeDeploymentsResult describeDeployments(DescribeDeploymentsRequest request) { request = beforeClientExecution(request); return executeDescribeDeployments(request); }
python
def get_unspents(address, blockchain_client): """ Get the spendable transaction outputs, also known as UTXOs or unspent transaction outputs. NOTE: this will only return unspents if the address provided is present in the bitcoind server. Use the chain, blockchain, or blockcypher API ...
python
def get_queue_system_lock(self, queue): """ Get system lock timeout Returns time system lock expires or None if lock does not exist """ key = self._key(LOCK_REDIS_KEY, queue) return Semaphore.get_system_lock(self.connection, key)
python
def init(images, num_channels, dim='2d', stride=2, kernel_size=7, maxpool=True, training=True, scope='init'): """Standard ResNet initial block used as first RevNet block. Args: images: [N, H, W, 3] tensor of input images to the model. num_channels: Output depth of convolutional layer in initial bl...
python
def _compute_video_hash(videofile): """ compute videofile's hash reference: https://docs.google.com/document/d/1w5MCBO61rKQ6hI5m9laJLWse__yTYdRugpVyz4RzrmM/preview """ seek_positions = [None] * 4 hash_result = [] with open(videofile, 'rb') as fp: total_size = ...
python
def wrap_once(self, LayoutClass, *args, **kwargs): """ Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with `args` and `kwargs` passed, unless layout object's parent is already a subclass of `LayoutClass`. """ def wrap_object_once(layout_o...
python
def _check_location_part(cls, val, regexp): """Deprecated. See CourseLocator._check_location_part""" cls._deprecation_warning() return CourseLocator._check_location_part(val, regexp)
python
def get_tracking_branch(self): """Returns (remote, branch) tuple, or None,None if there is no remote. """ try: remote_uri = self.git("rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}")[0] return remote_uri.split('/', 1) e...
java
public static String trimLines(String text) { if (text == null) { return null; } try { StringBuffer output = new StringBuffer(); // First we strip multi line comments. I think this is important: BufferedReader in = new BufferedReader(new StringRe...
java
private void overrideConfigFromFile(Configuration config) throws IOException { String configFile = GCS_CONFIG_OVERRIDE_FILE.get(config, config::get); if (configFile != null) { config.addResource(new FileInputStream(configFile)); } }
java
protected void importRelations() { if (m_importedRelations.isEmpty()) { return; } m_report.println(Messages.get().container(Messages.RPT_START_IMPORT_RELATIONS_0), I_CmsReport.FORMAT_HEADLINE); int i = 0; Iterator<Entry<String, List<CmsRelation>>> it = m_importedRe...
java
public static CaseTerminal resultOf(JcValue value) { CaseExpression cx = new CaseExpression(); CaseTerminal ret = CaseFactory.createCaseTerminal(cx); cx.setClauseType(ClauseType.CASE); cx.setCaseValue(value); return ret; }
python
def get_exon_ranges_for_transcript(self, transcript_id): """ obtain the sequence for a transcript from ensembl """ headers = {"content-type": "application/json"} self.attempt = 0 ext = "/overlap/id/{}?feature=exon".format(transcript_id) r = self.ensembl_...
python
def find_or_upsert(self, constructor, props, *, comp=None, return_status=False): """This finds or upserts a model with an auto primary key, and is a bit more flexible than find_or_create. First it looks for the model matching either comp, or props if comp is None. If not found, it will try to upsert t...
python
def element_screen_center(self, element): """ :returns: The center point of the element. :rtype: class:`dict` with the field "left" set to the X coordinate and the field "top" set to the Y coordinate. """ pos = self.element_screen_position(element...
java
private String translatePathExternal(String intpath) { if (fullPath) { return intpath; } else { return PathUtil.appendPath(rootPath.getPath(), intpath); } }
java
@Override public synchronized boolean offer(Runnable runnable) { int allWorkingThreads = this.executor.getActiveCount() + super.size(); return allWorkingThreads < this.executor.getPoolSize() && super.offer(runnable); }
python
def add_dependencies(self, module): """ Adds a module and its dependencies to the list of dependencies. Top-level entry point for adding a module and its dependecies. """ if module in self._processed_modules: return None if hasattr(module, "__name__"): ...
java
public PropertyOwner retrieveUserProperties(String strRegistrationKey) { if ((strRegistrationKey == null) || (strRegistrationKey.length() == 0)) return this; // Use default user properties UserProperties regKey = (UserProperties)m_htRegistration.get(strRegistrationKey); if...
java
public static <T> T fillBeanWithMap(Map<?, ?> map, T bean, CopyOptions copyOptions) { return fillBeanWithMap(map, bean, false, copyOptions); }
java
protected static <O> void updateMatrices(int size, MatrixParadigm mat, DBIDArrayMIter prots, PointerHierarchyRepresentationBuilder builder, Int2ObjectOpenHashMap<ModifiableDBIDs> clusters, DistanceQuery<O> dq, int c) { final DBIDArrayIter ix = mat.ix, iy = mat.iy; // c is the new cluster. // Update entries ...
java
@SuppressWarnings("unchecked") public List<CoreMap> getAnnotatedChunks(List<CoreLabel> tokens, int totalTokensOffset, Class textKey, Class labelKey, Class tokenChunkKey, Class tokenLabelKey) { List<CoreMap> chunks = new Arr...
python
def _segment_index(self, recarr, existing_index, start, new_segments): """ Generate index of datetime64 -> item offset. Parameters: ----------- new_data: new data being written (or appended) existing_index: index field from the versions document of the previous version ...
java
public Result compile(String[] argv, Context context) { if (stdOut != null) { context.put(Log.outKey, stdOut); } if (stdErr != null) { context.put(Log.errKey, stdErr); } log = Log.instance(context); if (argv.length == 0) { OptionHelp...
java
@POST @Path("/_search") public Response searchWithPost() throws IOException { return execute(getResourceRequest(RequestTypeEnum.POST, RestOperationTypeEnum.SEARCH_TYPE)); }
python
def weights_multi_problem(labels, taskid=-1): """Assign weight 1.0 to only the "targets" portion of the labels. Weight 1.0 is assigned to all labels past the taskid. Args: labels: A Tensor of int32s. taskid: an int32 representing the task id for a problem. Returns: A Tensor of floats. Raises: ...
python
def load_manuf(filename): """Load manuf file from Wireshark. param: - filename: the file to load the manuf file from""" manufdb = ManufDA(_name=filename) with open(filename, "rb") as fdesc: for line in fdesc: try: line = line.strip() if not line o...
python
def get_monitored_hosting_devices_info(self, hd_state_filter=None): """ This function returns a list of all hosting devices monitored by this agent """ wait_time = datetime.timedelta( seconds=cfg.CONF.cfg_agent.hosting_device_dead_timeout) resp = [] fo...
java
public void prepare(String sql, com.couchbase.lite.internal.database.sqlite.SQLiteStatementInfo outStatementInfo) { if (sql == null) { throw new IllegalArgumentException("sql must not be null."); } final int cookie = mRecentOperations.beginOperation("prepare", sql, null); tr...
java
public Collection<String> nearestLabels(@NonNull Collection<VocabWord> document, int topN) { if (document.isEmpty()) throw new ND4JIllegalStateException("Impossible to get nearestLabels for empty list of words"); INDArray vector = inferVector(new ArrayList<VocabWord>(document)); ret...
java
public static Vector<Object> toXmlRpcRunnersParameters(Collection<Runner> runners) { Vector<Object> runnersParams = new Vector<Object>(); for(Runner runner : runners) { runnersParams.add(runner.marshallize()); } return runnersParams; }
python
def disconnect(self, close=True): """ Logs off the session :param close: Will close all tree connects in a session """ if not self._connected: # already disconnected so let's return return if close: for open in list(self.open_table.va...
python
def look_at(self, x, y, z): """Converges the two cameras to look at the specific point""" for camera in self.cameras: camera.look_at(x, y, z)
java
static <S, E> GraphTraversal<S, E> union(Iterable<GraphTraversal<? super S, ? extends E>> traversals) { return union(__.identity(), traversals); }
python
def docopt(doc, argv=None, help=True, version=None, options_first=False): """Parse `argv` based on command-line interface described in `doc`. `docopt` creates your command-line interface based on its description that you pass as `doc`. Such description can contain --options, <positional-argument>, comm...
java
ObjectName findMatchingMBeanPattern(ObjectName pName) { // Check all stored patterns for a match and return the pattern if one is found for (ObjectName pattern : patterns) { if (pattern.apply(pName)) { return pattern; } } return null; }
python
def _forward_mode(self, *args): """Forward mode differentiation for a constant""" # Evaluate inner function self.f X: np.ndarray dX: np.ndarray X, dX = self.f._forward_mode(*args) # Alias the power to p for legibility p: float = self.p # The function value...
java
@GwtIncompatible("InputStream") static InputStream asInputStream(final ByteInput input) { checkNotNull(input); return new InputStream() { @Override public int read() throws IOException { return input.read(); } @Override public int read(byte[] b, int off, int len) throws ...
java
protected void updateSequence() throws RepositoryException { checkIfOpened(); try { ResultSet count = updateNextOrderNumber(localMaxOrderNumber); try { if (!count.next()) { throw new RepositoryException("Could not update the sequence...
python
def create_new_address_for_user(self, user_id): """Create a new bitcoin address to accept payments for a User. This is a convenience wrapper around `get_child` that helps you do the right thing. This method always creates a public, non-prime address that can be generated from a BIP32 pu...
java
public static boolean areConvertibleClasses (@Nonnull final Class <?> aSrcClass, @Nonnull final Class <?> aDstClass) { ValueEnforcer.notNull (aSrcClass, "SrcClass"); ValueEnforcer.notNull (aDstClass, "DstClass"); // Same class? if (aDstClass.equals (aSrcClass)) return true; // Default assi...
java
static Map<String, String> resolveHeaders(Method method) { Map<String, String> headerMap = new HashMap<>(); for (Header header : method.getDeclaringClass().getAnnotationsByType(Header.class)) { headerMap.put(header.name(), header.value()); } for (Header header : method.getAnnotationsByType(Header....
java
@Override public <T> AppEngineUpdate<E> set(Property<?, T> property, T value) { if (property == null) { throw new IllegalArgumentException("'property' must not be [" + property + "]"); } properties.put(property, value); return this; }
python
def _normalize_tz(val): """Normalizes all valid ISO8601 time zone variants to the one python will parse. :val: a timestamp string without a timezone, or with a timezone in one of the ISO8601 accepted formats. """ match = _TZ_RE.match(val) if match: ts, tz = match.groups() if len(tz) == 5: ...
java
public static byte[] toByteArray(Streamable streamable) { try { final ByteArrayOutputStream baos = new ByteArrayOutputStream(streamable.size()); final DataOutputStream dos = new DataOutputStream(baos); streamable.write(dos); dos.flush(); baos.clo...
java
public void setDriverClassName(String driver) { try { this.driver = (Driver) Class.forName(driver).newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to load driver: " + driver, e); } }
java
public KeePassFile openDatabase(String password, InputStream keyFileStream) { if (password == null) { throw new IllegalArgumentException(MSG_EMPTY_MASTER_KEY); } if (keyFileStream == null) { throw new IllegalArgumentException("You must provide a non-empty KeePass key...
python
def _to_dict(self): ''' Returns a dictionary representation of this object ''' return dict(minimum=self.minimum._to_dict(), maximum=self.maximum._to_dict())
python
def main(): """Main function for SPEAD receiver module.""" # Check command line arguments. if len(sys.argv) < 2: raise RuntimeError('Usage: python3 async_recv.py <json config>') # Set up logging. sip_logging.init_logger(show_thread=True) # Load SPEAD configuration from JSON file. #...
python
def portTryReduce(root: LNode, port: LPort): """ Check if majority of children is connected to same port if it is the case reduce children and connect this port instead children :note: use reduceUselessAssignments, extractSplits, flattenTrees before this function to maximize it's effect """...
java
final public int[] readInputRegisters(int serverAddress, int startAddress, int quantity) throws ModbusProtocolException, ModbusNumberException, ModbusIOException { ModbusRequest request = ModbusRequestBuilder.getInstance().buildReadInputRegisters(serverAddress, startAddress, quantity); ReadH...
python
def parse_localinstancepath(parser, event, node): """Parse LOCALINSTANCEPATH element returning instancename <!ELEMENT LOCALINSTANCEPATH (LOCALNAMESPACEPATH, INSTANCENAME)> """ #pylint: disable=unused-argument (next_event, next_node) = six.next(parser) if not _is_start(next_event, next_...
python
def asxc(cls, obj): """Convert object into Xcfunc.""" if isinstance(obj, cls): return obj if is_string(obj): return cls.from_name(obj) raise TypeError("Don't know how to convert <%s:%s> to Xcfunc" % (type(obj), str(obj)))
java
public OpenPgpV4Fingerprint generateAndImportKeyPair(BareJid ourJid) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, NoSuchProviderException, PGPException, IOException { throwIfNoProviderSet(); OpenPgpStore store = provider.getStore(); PGPKeyRing key...
java
public static base_responses update(nitro_service client, forwardingsession resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { forwardingsession updateresources[] = new forwardingsession[resources.length]; for (int i=0;i<resources.length;i++){ up...
java
public TableFactor multiply(TableFactor other) { // Calculate the result domain List<Integer> domain = new ArrayList<>(); List<Integer> otherDomain = new ArrayList<>(); List<Integer> resultDomain = new ArrayList<>(); for (int n : neighborIndices) { domain.add(n); resultDomain.add(n); ...
java
public String getValue(Option option) { if (option == null) { return null; } String[] values = getValues(option); return (values == null ? null : values[0]); }
python
def write(self, data): """ Writes data to the device. :param data: data to write :type data: string :returns: number of bytes sent :raises: :py:class:`~alarmdecoder.util.CommError` """ data_sent = None try: if isinstance(data, str): ...
java
public int size() { int size = 0; for(Ta a: getKeys()) { for(Tb b: get2ndValues(a)) { size += get3rdValues(a, b).size(); } } return size; }
python
def HasIndex(self, index): """ Flag indicating the index exists in any of the spent coin items. Args: index (int): Returns: """ for i in self.Items: if i.index == index: return True return False
java
@Deprecated public static Pattern some(int min, int max, CharPredicate predicate) { return times(min, max, predicate); }
python
def lock(self, name, timeout=None, sleep=0.1, blocking_timeout=None, lock_class=None, thread_local=True): """ Return a new Lock object using key ``name`` that mimics the behavior of threading.Lock. If specified, ``timeout`` indicates a maximum life for the lock. By ...
java
private boolean decode_Segmentlist(AnnouncementParmValue annPaVa) throws ParserException { boolean decoded = false; decoded = decode_SegmentDescriptor(annPaVa); if (decoded) { boolean f = true; while (f && index < totalChars) { if (chars[index] == ',') { index++; f = decode_SegmentDescriptor...
python
async def async_delete_api_key(session, host, port, api_key): """Delete API key from deCONZ.""" url = 'http://{host}:{port}/api/{api_key}/config/whitelist/{api_key}'.format( host=host, port=str(port), api_key=api_key) response = await async_request(session.delete, url) _LOGGER.info(response)
python
async def make_response(self, request, response, **response_kwargs): """Convert a handler result to web response.""" while iscoroutine(response): response = await response if isinstance(response, StreamResponse): return response response_kwargs.setdefault('conte...
python
def collect_episodes(local_evaluator=None, remote_evaluators=[], timeout_seconds=180): """Gathers new episodes metrics tuples from the given evaluators.""" pending = [ a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators ] collected, _...
java
protected DataSourceMetadataUpdateResult updateDataSourceMetadataWithHandle( final Handle handle, final String dataSource, final DataSourceMetadata startMetadata, final DataSourceMetadata endMetadata ) throws IOException { Preconditions.checkNotNull(dataSource, "dataSource"); Precond...
python
def process(self, raster): """ Applies the morphological operation to the mask object """ dim = len(raster.shape) if dim == 3: for dim in range(raster.shape[2]): raster[:, :, dim] = self.morph_operation(raster[:, :, dim], self.struct_elem) elif ...
java
private static void doWork() { derivedDoubleGauge.createTimeSeries( labelValues, blockingQueue, new ToDoubleFunction<LinkedBlockingQueue>() { @Override public double applyAsDouble(LinkedBlockingQueue queue) { return queue.size(); } }); /...
java
public void delete_property(String name, String[] propnames) throws DevFailed { databaseDAO.delete_property(this, name, propnames); }
java
public void removeExtension() { try { if (extendedRelationsDao.isTableExists()) { List<ExtendedRelation> extendedRelations = extendedRelationsDao .queryForAll(); for (ExtendedRelation extendedRelation : extendedRelations) { geoPackage.deleteTable(extendedRelation .getMappingTableName());...
python
def Y_less(self): """Decrease the scaling.""" self.parent.value('y_scale', self.parent.value('y_scale') / 2) self.parent.traces.display()
java
@Override public CommerceOrderNote fetchByC_ERC(long companyId, String externalReferenceCode) { return fetchByC_ERC(companyId, externalReferenceCode, true); }
java
private static String readAll(@Nonnull final Reader reader) throws IOException { final StringBuilder buffer = new StringBuilder(); int cp; while ((cp = reader.read()) != -1) { buffer.append((char) cp); } return buffer.toString(); }
python
def get_project_by_network_id(network_id,**kwargs): """ get a project complexmodel by a network_id """ user_id = kwargs.get('user_id') projects_i = db.DBSession.query(Project).join(ProjectOwner).join(Network, Project.id==Network.project_id).filter( ...
java
public void call(Result result) { if (result.isException()) { statistics.exception(); annotable.annotate( Annotations.exception( result.getException() ) ); return; } annotable.annotate( new Annotation() { public void writ...
java
public boolean matches(String prefix, Object actual, Object expected, JSONCompareResult result) throws ValueMatcherException { if (comparator instanceof LocationAwareValueMatcher) { return ((LocationAwareValueMatcher<Object>)comparator).equal(prefix, actual, expected, result); } return comparator.equal(actu...
java
@SuppressWarnings("checkstyle:methodlength") public void registerConfigLocally(IdentifiedDataSerializable newConfig, ConfigCheckMode configCheckMode) { IdentifiedDataSerializable currentConfig = null; if (newConfig instanceof MultiMapConfig) { MultiM...
java
public static <T> boolean anyValuesInCommon(Collection<T> c1, Collection<T> c2) { // Let's always iterate over smaller collection: if (c1.size() > c2.size()) { Collection<T> tmp = c1; c1 = c2; c2 = tmp; } Iterator<T> it = c1.iterator(); whi...
python
def validate_signature(filename): """ Remove invalid signatures from a binary file If the file signature is missing or valid then it will be ignored Invalid signatures are replaced with an ad-hoc signature. This is the closest you can get to removing a signature on MacOS Parameters ---------...
python
def list(path, filename=None, start=None, stop=None, recursive=False, directories=False): """ List files specified by dataPath. Datapath may include a single wildcard ('*') in the filename specifier. Returns sorted list of absolute path strings. """ path = uri_to_path(p...
java
@Override public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { /* * Calculate value of the swap at exercise date on each path (beware of perfect forsight - all rates are simulationTime=exerciseDate) */ RandomVariable valueFixLeg = new...
java
@Override public boolean delete(Path path, boolean recursive) throws IOException { LOG.debug("delete({}, {})", path, recursive); if (mStatistics != null) { mStatistics.incrementWriteOps(1); } AlluxioURI uri = new AlluxioURI(HadoopUtils.getPathWithoutScheme(path)); DeletePOptions options = De...
python
def run(migrations_path=None, url=None, port=None): """Run migrations""" logger = logging.getLogger() logger.setLevel(logging.INFO) if url: url = str(url).rstrip('/') options.url_registry_db = url if port: options.db_port = int(port) if migrations_path: migrati...
python
def setCurrentIndex(self, currentIndex): """ Sets the current item to be the item at currentIndex. Also select the row as to give consistent user feedback. See also the notes at the top of this module on current item vs selected item(s). """ selectionModel = self.selectio...
java
private static <T> void notifyPostInvoke(EJBRequestCollaborator<T> collaborator, EJBRequestData request, Object preInvokeData) throws CSIException { try { @SuppressWarnings("unchecked") T uncheckedCookie = (T) preInvokeData; collaborator.postInvoke(request, uncheckedCookie); ...
java
public int getWidth() { if (format == ImageFormat.GIF && streamMetadata != null) { Node screenDescNode = NodeUtils.getChild(streamMetadata, "LogicalScreenDescriptor"); if (screenDescNode != null) { return NodeUtils.getIntAttr(screenDescNode, "logicalScreenWidth"); ...
java
public int getKeyAsInt(int index) throws IOException { if (index >= structure.keySizes.size()) { throw new IOException("Index " + index + " is out of range."); } return Bytes.toInt(key, structure.keyByteOffsets.get(index)); }
java
public void restoreRepository(File repositoryBackupSetDir, boolean asynchronous) throws BackupOperationException, BackupConfigurationException { File[] cfs = PrivilegedFileHelper.listFiles(repositoryBackupSetDir, new RepositoryBackupLogsFilter()); if (cfs.length == 0) { throw new Ba...
python
def run(self): """ Compile all message catalogs .po files into .mo files. Skips not changed file based on source mtime. """ # thanks to deluge guys ;) po_dir = os.path.join(os.path.dirname(__file__), 'webant', 'translations') print('Compiling po files from "...
java
protected Object getFieldValue(String fieldname) { ActionContext actionCtx = ActionContext.getContext(); ValueStack valueStack = actionCtx.getValueStack(); Object value = valueStack.findValue(fieldname, false); String overwriteValue = getOverwriteValue(fieldname); if ( overwriteValue != null ) { ...
python
def head(self, url: StrOrURL, *, allow_redirects: bool=False, **kwargs: Any) -> '_RequestContextManager': """Perform HTTP HEAD request.""" return _RequestContextManager( self._request(hdrs.METH_HEAD, url, allow_redirects=allow_redirects, ...
java
public static void removeStateParam(String name, HttpServletRequest req, HttpServletResponse res) { setRawCookie(name, "", req, res, false, 0); }
python
def load_from_path(path: str) -> Config: """ Load a config from a file and ensure its structure. Writes a default if necessary """ data = _ensure_load(path) if not data: data = {} values, should_write = _ensure_values(data) values.update({'path': path}) config = Config(**valu...
java
private void initializeShowCustomBottomSheetPreference() { Preference showCustomBottomSheetPreference = findPreference(getString(R.string.show_custom_bottom_sheet_preference_key)); showCustomBottomSheetPreference .setOnPreferenceClickListener(new OnPreferenceClickListener...
python
def rest_delete(url, timeout, show_error=False): '''Call rest delete method''' try: response = requests.delete(url, timeout=timeout) return response except Exception as exception: if show_error: print_error(exception) return None
java
private double link(double d1, double d2) { if (isScoreMatrix) { return Math.max(d1,d2); } else { return Math.min(d1,d2); } }
python
def upsert(self, table, value, update_columns=None, commit=True): """ :type table: string :type value: dict :type update_columns: list :param update_columns: specify the columns which will be updated if record exists :type commit: bool """ if not isinstanc...
java
public static String toHex(final byte[] buffer, final int offset, final int length) { return new String(toHexByteArray(buffer, offset, length), UTF_8); }
python
def initialize_object(B, res, row): """ Do a shallow initialization of an object Arguments: - row<dict>: dict of data like depth=1, i.e. many_refs are only ids """ B = get_backend() field_groups = FieldGroups(B.get_concrete(res)) try: obj = B.get_object(B.get_concrete(res),...