language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _count_counters(self, counter): """Return all elements count from Counter """ if getattr(self, 'as_set', False): return len(set(counter)) else: return sum(counter.values())
java
public void addAddress(PeerAddress peerAddress) { int newMax; lock.lock(); try { if (addInactive(peerAddress)) { newMax = getMaxConnections() + 1; setMaxConnections(newMax); } } finally { lock.unlock(); } }
python
def copy_value(self, orig_name, new_name): """Copy a variable""" code = u"get_ipython().kernel.copy_value('%s', '%s')" % (orig_name, new_name) if self._reading: self.kernel_client.input(u'!' + code) else: ...
python
def calculate_boundingbox(lng, lat, miles): """ Given a latitude, longitude and a distance in miles, calculate the co-ordinates of the bounding box 2*miles on long each side with the given co-ordinates at the center. """ latChange = change_in_latitude(miles) latSouth = lat - latChange l...
java
private void ins(int k) { //if(last > 0) last = sapp[-1] += k; //else last = *sapp++ = (k); if(last > 0) last = sapp[sappPos-1] += k; else last = sapp[(sappPos++)] = (k); }
python
def add_coordinates(network): """ Add coordinates to nodes based on provided geom Parameters ---------- network : PyPSA network container Returns ------- Altered PyPSA network container ready for plotting """ for idx, row in network.buses.iterrows(): wkt_geom = to_shape...
java
public static <T> void insertHeader(List<T> list, T headerValue, int headerSize) { for (int i = 0; i < headerSize; i++) list.add(0, headerValue); }
python
def submit_commands(self, devices, execution): """Submit device command executions. Returns: a list of concurrent.futures for scheduled executions. """ fs = [] for device in devices: if device[key_id_] != self.device_id: logging.warning('Ignoring comm...
java
public static String toCountSql(String sql) { sql = sql.replaceAll("select .*? from", "select count(*) from"); sql = sql.replaceAll("SELECT .*? FROM", "SELECT count(*) FROM"); sql = sql.replaceAll(" LIMIT.*", ""); sql = sql.replaceAll(" limit.*", ""); return sql; }
java
public FieldType<BeanType<T>> getOrCreateField() { List<Node> nodeList = childNode.get("field"); if (nodeList != null && nodeList.size() > 0) { return new FieldTypeImpl<BeanType<T>>(this, "field", childNode, nodeList.get(0)); } return createField(); }
python
def parse_expmethodcall(self, tup_tree): """ :: <!ELEMENT EXPMETHODCALL (EXPPARAMVALUE*)> <!ATTLIST EXPMETHODCALL %CIMName;> """ self.check_node(tup_tree, 'EXPMETHODCALL', ('NAME',), (), ('EXPPARAMVALUE',)) para...
java
public static void writeObjects(OutputStream out, boolean isCloseOut, Serializable... contents) throws IORuntimeException { ObjectOutputStream osw = null; try { osw = out instanceof ObjectOutputStream ? (ObjectOutputStream) out : new ObjectOutputStream(out); for (Object content : contents) { if (cont...
java
public <T extends Enum<T>> Cases<T, EnumExpression<T>> then(T then) { return thenEnum(ConstantImpl.create(then)); }
python
def is_instance(self, model): """ Is instance? Checks if provided object is instance of this service's model. :param model: object :return: bool """ result = isinstance(model, self.__model__) if result is True: return ...
java
public ReturnCode stop() { System.out.println(MessageFormat.format(BootstrapConstants.messages.getString("info.serverStopping"), serverName)); // Use initialized bootstrap configuration to find the server lock file. ServerLock serverLock = ServerLock.createTestLock(bootProps); // we ca...
java
public Matrix4x3d shadow(double lightX, double lightY, double lightZ, double lightW, Matrix4x3dc planeTransform) { return shadow(lightX, lightY, lightZ, lightW, planeTransform, this); }
java
public GuacamoleTunnel assignGuacamoleTunnel(final GuacamoleSocket socket, String connectionID) { // Create tunnel with given socket this.tunnel = new AbstractGuacamoleTunnel() { @Override public GuacamoleSocket getSocket() { return socket; ...
java
@Deprecated public ProxyHandler addRequestHeader(final HttpString header, final String attribute, final ClassLoader classLoader) { requestHeaders.put(header, ExchangeAttributes.parser(classLoader).parse(attribute)); return this; }
java
static Node inject( AbstractCompiler compiler, Node node, Node parent, Map<String, Node> replacements) { return inject(compiler, node, parent, replacements, /* replaceThis */ true); }
java
public static void log(int logLevel, String format, Object... args) { assertInitialization(); sLogger.log(logLevel, format, args); }
java
private SectionContainer buildSectionStructure(List<SectionContent> scl) { SectionContainer result = new SectionContainer(0); for (SectionContent sContent : scl) { int contentLevel = sContent.getLevel(); SectionContainer sContainer = result; // get the right SectionContainer or create it for (int c...
java
@Override public EEnum getIfcDuctSegmentTypeEnum() { if (ifcDuctSegmentTypeEnumEEnum == null) { ifcDuctSegmentTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(972); } return ifcDuctSegmentTypeEnumEEnum; }
python
def get_limits(self): """ Return all known limits for this service, as a dict of their names to :py:class:`~.AwsLimit` objects. :returns: dict of limit names to :py:class:`~.AwsLimit` objects :rtype: dict """ if self.limits != {}: return self.limits ...
python
def get_content( cls, abspath: str, start: int = None, end: int = None ) -> Generator[bytes, None, None]: """Retrieve the content of the requested resource which is located at the given absolute path. This class method may be overridden by subclasses. Note that its signatur...
java
@SuppressWarnings("unchecked") public void popContext(Set unsharableResources) throws ResourceException { LinkedList<Context> stack = threadContexts.get(); if (stack == null || stack.isEmpty()) return; Context context = stack.removeLast(); if (log.isTraceEnabled()) { ...
java
public static boolean isAbsoluteAndSchemeAuthorityNull(Path path) { return (path.isAbsolute() && path.toUri().getScheme() == null && path.toUri().getAuthority() == null); }
python
def get_callable(key, dct): """Get the callable mapped by a key from a dictionary. This is necessary for pickling (so we don't try to pickle an unbound method). Parameters ---------- key : str The key for the ``dct`` dictionary. dct : dict The dictionary of callables. """ ...
python
def get_onchain_exchange_rates(deposit_crypto=None, withdraw_crypto=None, **modes): """ Gets exchange rates for all defined on-chain exchange services. """ from moneywagon.onchain_exchange import ALL_SERVICES rates = [] for Service in ALL_SERVICES: srv = Service(verbose=modes.get('verbo...
python
def select_from_drop_down_by_text(self, drop_down_locator, option_locator, option_text, params=None): """ Select option from drop down widget using text. :param drop_down_locator: locator tuple (if any, params needs to be in place) or WebElement instance :param option_locator: locator t...
java
public static Validator<CharSequence> noWhitespace(@NonNull final Context context, @StringRes final int resourceId) { return new NoWhitespaceValidator(context, resourceId); }
python
def validate_identifier(self, field): """Validate field identifier.""" if field.data: field.data = field.data.lower() if Community.get(field.data, with_deleted=True): raise validators.ValidationError( _('The identifier already exists. ' ...
java
public boolean startDiscovery() { if (mScanning) { Log.e(TAG, "Already discovering"); return true; } if (mListener == null) { throw new NullPointerException("Listener cannot be null"); } return scan(); }
java
private void handleAddWanConfig(HttpPostCommand command) throws UnsupportedEncodingException { String res; String[] params = decodeParams(command, 1); String wanConfigJson = params[0]; try { WanReplicationConfigDTO dto = new WanReplicationConfigDTO(new WanReplicationConfig())...
java
public static FieldValueFetcher fetcher(final String pathAssistantSid, final String pathFieldTypeSid, final String pathSid) { return new FieldValueFetcher(pathAssistantSid, pathFieldTypeSid, pathSid); }
java
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case XtypePackage.XIMPORT_SECTION__IMPORT_DECLARATIONS: return ((InternalEList<?>)getImportDeclarations()).basicRemove(otherEnd, msgs); } return super.eInverseRemove...
python
def _parse_data(self, raw_data, var_filter, time_extents): """ Transforms raw HADS observations into a dict: station code -> [(variable, time, value), ...] Takes into account the var filter (if set). """ retval = defaultdict(list) p = parser() begin...
java
void executeHandlers(AuditEvent event) { String formattedEvent = configContext.getLayout().format(event); for (final Handler handler : configContext.getHandlers()) { handler.setAuditEvent(event); handler.setQuery(formattedEvent); try { handler.handle()...
java
private String parseParams(ParameterSet params, JSONObject obj) throws Exception { String path = null; if (params.toArray().length != 1) { return "Incorrect number of arguments to @SnapshotScan (expects 1, received " + params.toArray().length + ")"; } ...
java
private void handleChangeConfigurationRequest(final int executorId, final String actionName, final HttpServletRequest req, final HashMap<String, Object> ret) throws ServletException, IOException { try { final Map<String, Object> result = this.execManagerAdapter .callExecuto...
java
public static <T> Spliterator<T> of(ThrowingSpliterator<T, Nothing> itr) { return of(itr, Nothing.class); }
java
@Override public Optional<WSCookie> getCookie(String name) { for (Cookie ahcCookie : ahcResponse.getCookies()) { // safe -- cookie.getName() will never return null if (ahcCookie.name().equals(name)) { return Optional.of(asCookie(ahcCookie)); } } ...
java
private synchronized static Cluster getCluster(URI baseUrl, String[] personalities) throws IOException { final Entry<URI, Set<String>> key = Maps.immutableEntry(baseUrl, (Set<String>)ImmutableSet.copyOf(personalities)); Cluster result = CLUSTERS.get(key); if (result != null) { r...
python
def errors(self, errors: List[str], code: Union[int, Tuple[int, str, str]] = HTTPStatus.BAD_REQUEST, key: str = 'errors', headers: Optional[Dict[str, str]] = None, ): """ Convenience method to return errors as json. :par...
python
def works(self, prefix_id): """ This method retrieve a iterable of Works of the given prefix. args: Crossref Prefix (String) return: Works() """ context = '%s/%s' % (self.ENDPOINT, str(prefix_id)) return Works(context=context)
python
def set_attrs(self, **attrs): """Set model attributes, e.g. input resistance of a cell.""" self.attrs.update(attrs) self._backend.set_attrs(**attrs)
python
def process_package(self, package_name): """ Build artifacts declared for the given package. """ metadata = super(ArtifactRegistry, self).process_package(package_name) if metadata: self.update_artifact_metadata(package_name, metadata)
python
def add_arguments(self, parser): """ Define optional arguments with default values """ parser.add_argument('--length', default=self.length, type=int, help=_('SECRET_KEY length default=%d' % self.length)) parser.add_argument('--alphabet', default=self....
python
def _raw_config_setting(config_obj, section, param, default=None, config_filename='', warn_on_none_level=logging.WARN): """Read (section, param) from `config_obj`. If not found, return `default` If the setting is not found and `default` is None, then an warn-level message is logged. `config_filename` can b...
java
public static <T> CompletableFuture<T> failed(Throwable throwable) { LettuceAssert.notNull(throwable, "Throwable must not be null"); CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(throwable); return future; }
python
def _fillVolumesAndPaths(self, paths): """ Fill in paths. :arg paths: = { Store.Volume: ["linux path",]} """ with self.btrfs as mount: for bv in mount.subvolumes: if not bv.readOnly: continue vol = self._btrfsVol2StoreVol(...
python
def update_user_entitlements(self, document, do_not_send_invite_for_new_users=None): """UpdateUserEntitlements. [Preview API] Edit the entitlements (License, Extensions, Projects, Teams etc) for one or more users. :param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.member_entitlement_manage...
python
def get_domain_name(self, domain_name, route53=True): """ Scan our hosted zones for the record of a given name. Returns the record entry, else None. """ # Make sure api gateway domain is present try: self.apigateway_client.get_domain_name(domainName=domain_n...
python
def inject(self, filename, content): """ add the injection content to the dictionary """ # ensure content always has one trailing newline content = _unicode(content).rstrip() + "\n" if filename not in self.inject_dict: self.inject_dict[filename] = "" self.inject_dict[...
java
private void putObject(String bucketName, String objectName, Long size, Object data, Map<String, String> headerMap, ServerSideEncryption sse) throws InvalidBucketNameException, NoSuchAlgorithmException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseExce...
python
def _cleanup(self): """ Frees lots of non-textual information, such as the fonts and images and the objects that were needed to parse the PDF. """ self.device = None self.doc = None self.parser = None self.resmgr = None self.interpreter = N...
java
public static boolean isVisargadi(String str) { Log.logInfo(" Checking if is_visargadi:::"); String s1 = VarnaUtil.getAdiVarna(str); if(isVisarga(s1) ) { Log.logInfo("I am visargadi"); return true; } return false; }
java
@SuppressWarnings("unchecked") protected void addStatusMessage(final String statusMessage, final String solution) { this.json.put(ProtocolConstants.SOLUTION, solution); this.json.put(ProtocolConstants.STATUS_MESSAGE, statusMessage); }
java
public String getBucketName(String spaceId) { // Determine if there is an existing bucket that matches this space ID. // The bucket name may use any access key ID as the prefix, so there is // no way to know the exact bucket name up front. List<Bucket> buckets = listAllBuckets(); ...
java
public void setResourceAwsEc2InstanceIamInstanceProfileArn(java.util.Collection<StringFilter> resourceAwsEc2InstanceIamInstanceProfileArn) { if (resourceAwsEc2InstanceIamInstanceProfileArn == null) { this.resourceAwsEc2InstanceIamInstanceProfileArn = null; return; } this...
python
def add_sample_meta(self, source, reference, method='', filename='', md5='', sha1='', sha256='', size='', ...
java
Object getDataService(T session, Class cls) throws DataServiceException { String dataServiceClassName = cls.getName(); logger.debug("Looking for dataservice : {}", dataServiceClassName); if (cls.isAnnotationPresent(DataService.class)) { return _getDataService(session, cls); } else { throw new DataSe...
java
public void putAlias(String alias) throws JSONException { if (alias != null) { this.alias = alias; this.put(Defines.LinkParam.Alias.getKey(), alias); } }
python
def prioritize(self, item, force=False): """ Moves the item to the very left of the queue. """ with self.condition: # If the job is already running (or about to be forced), # there is nothing to be done. if item in self.working or item in self.force: ...
python
def put_motion_detection_xml(self, xml): """ Put request with xml Motion Detection """ _LOGGING.debug('xml:') _LOGGING.debug("%s", xml) headers = DEFAULT_HEADERS headers['Content-Length'] = len(xml) headers['Host'] = self._host response = requests.put(self.motio...
python
def _increment(self, n=1): """Move forward n tokens in the stream.""" if self._cur_position >= self.num_tokens-1: self._cur_positon = self.num_tokens - 1 self._finished = True else: self._cur_position += n
java
public boolean getRollbackOnly() { TransactionImpl tx = registry.getTransaction(); if (tx == null) throw new IllegalStateException(); return tx.getRollbackOnly(); }
java
public static long nextLong(long n) { // error checking and 2^x checking removed for simplicity. long bits, val; do { bits = (RND.nextLong() << 1) >>> 1; val = bits % n; } while (bits-val+(n-1) < 0L); return val; }
python
def resize_by_factor(im, factor): """ Resizes the image according to a factor. The image is pre-filtered with a Gaussian and then resampled with bilinear interpolation. This function uses scikit-image and essentially combines its `pyramid_reduce` with `pyramid_expand` into one function. Return...
java
@WebOperationMethod public Map<String,Object> download(Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception { String database = Objects.get(params, "database"); String collection = Objects.get(params, "collection", COLLECTION); String id = Ob...
java
public URL getServiceURL() { return new URL(this.protocol, this.adapterAddress, this.deviceAddress, this.deviceAttributes, this.serviceUUID, null, null); }
python
def lanczos(A, order, x): r""" TODO short description Parameters ---------- A: ndarray Returns ------- """ try: N, M = np.shape(x) except ValueError: N = np.shape(x)[0] M = 1 x = x[:, np.newaxis] # normalization q = np.divide(x, np.kron(...
python
def frames_to_ms(frames, fps): """ Convert frame-based duration to milliseconds. Arguments: frames: Number of frames (should be int). fps: Framerate (must be a positive number, eg. 23.976). Returns: Number of milliseconds (rounded to int). Raises: V...
java
@Override public void addResponse(Response response) { logger.warn("Security response " + response.getAction() + " triggered for user: " + response.getUser().getUsername()); String json = gson.toJson(response); try { client.execute( new UpdateSet.Builder( responses, new SetUpdate().add(json) ...
python
def balance_of(self, b58_address: str) -> int: """ This interface is used to call the BalanceOf method in ope4 that query the ope4 token balance of the given base58 encode address. :param b58_address: the base58 encode address. :return: the oep4 token balance of the base58 encod...
python
def plotly( data: typing.Union[dict, list] = None, layout: dict = None, scale: float = 0.5, figure: dict = None, static: bool = False ): """ Creates a Plotly plot in the display with the specified data and layout. :param data: The Plotly trace data to be ...
java
public static cspolicy_binding get(nitro_service service, String policyname) throws Exception{ cspolicy_binding obj = new cspolicy_binding(); obj.set_policyname(policyname); cspolicy_binding response = (cspolicy_binding) obj.get_resource(service); return response; }
java
private void createElementsForSequence(String className, String typeName, String nextTypeName, String apiName, List<XsdElement> sequenceElements) { ClassWriter classWriter = generateInnerSequenceClass(typeName, className, apiName); sequenceElements.forEach(sequenceElement -> ...
java
public static Automaton getDeepestAutomaton(Agent agent) { Automaton a1 = agent.getAutomaton(); Automaton a2 = agent.getAutomaton().currentState; while (a2 != null || !(a2 instanceof SimpleState)) { a1 = a2; a2 = a2.currentState; } return a1; }
java
public boolean isExpired() { final var expiryDate = get(EXPIRATION_DATE).getDate(); final var today = new Date(); return today.getTime() > expiryDate.getTime(); }
python
def event_detected(channel): """ This function is designed to be used in a loop with other things, but unlike polling it is not going to miss the change in state of an input while the CPU is busy working on other things. This could be useful when using something like Pygame or PyQt where there is a ...
java
public static KeyManagerFactory getKeyManagerFactory(String keyStoreFilename, StoreProperties storeProperties) throws IOException, GeneralSecurityException { InputStream is = getResourceAsStream(keyStoreFilename); if (is == null) { throw new FileNotFoundException("Certificate file not found: " + get...
python
def calculate_slice_output_shapes(operator): ''' Allowed input/output patterns are 1. [N, C, H, W] ---> [N, C', H, W] 2. [N, C, H, W] ---> [N, C, H', W] 3. [N, C, H, W] ---> [N, C, H, W'] ''' check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1) ...
python
def get_default_config(self): """ Returns the default collector settings """ config = super(ZookeeperCollector, self).get_default_config() config.update({ 'path': 'zookeeper', # Which rows of 'status' you would like to publish. # 'telnet h...
java
public List<WsByteBuffer> finish() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "finish"); } List<WsByteBuffer> list = new LinkedList<WsByteBuffer>(); if (isFinished()) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEn...
java
public Stream getStream(String sessionId, String streamId) throws OpenTokException { String stream = this.client.getStream(sessionId, streamId); try { return streamReader.readValue(stream); } catch (Exception e) { throw new RequestException("Exception mapping json: " + e....
java
public Project getProjectByKey(String projectKey) throws RedmineException { return transport.getObject(Project.class, projectKey, new BasicNameValuePair("include", "trackers")); }
python
def render(self, path): """Render the component to a javascript file.""" return ReactComponent( self.layout, self.src_file, self.component_id, props=self.props, static_path=path)
python
def max_width(self): """ :return: The max width of the rendered text (across all images if an animated renderer). """ if len(self._plain_images) <= 0: self._convert_images() if self._max_width == 0: for image in self._plain_images: ...
java
public void setLinkedEmitter(ConfigurableEmitter emitter) { // set the title Window w = SwingUtilities.windowForComponent(this); if (w instanceof Frame) ((Frame) w).setTitle("Whiskas Gradient Editor (" + emitter.name + ")"); // clear all values properties.removeAllItems(); values.clear(); ...
python
def lines_to_notebook(lines, name=None): """ Convert the lines of an m file into an IPython notebook Parameters ---------- lines : list A list of strings. Each element is a line in the m file Returns ------- notebook : an IPython NotebookNode class instance, containing the ...
java
@Override public R visitIdentifier(IdentifierTree node, P p) { return defaultAction(node, p); }
java
@Override public CPDisplayLayout removeByUUID_G(String uuid, long groupId) throws NoSuchCPDisplayLayoutException { CPDisplayLayout cpDisplayLayout = findByUUID_G(uuid, groupId); return remove(cpDisplayLayout); }
java
public static String getResourceFolderPath(ResourceType type) { String cachePath = getSystemConfiguration().getCacheDirectory() .getAbsolutePath(); File cacheDir = new File(cachePath); if (!cacheDir.exists()) { throw new IllegalStateException( "Th...
python
def clear_cache(cls): """Call this before closing tk root""" #Prevent tkinter errors on python 2 ?? for key in cls._cached: cls._cached[key] = None cls._cached = {}
java
public static double regularizedIncompleteGamma(double s, double x) { if (s < 0.0) { throw new IllegalArgumentException("Invalid s: " + s); } if (x < 0.0) { throw new IllegalArgumentException("Invalid x: " + x); } double igf = 0.0; if (x < s + 1...
java
public QualifiedJobId getQualifiedJobIdFromResult(Result result) throws RowKeyParseException { if (result == null) { throw new RowKeyParseException( "Cannot parse empty row key from result in HBase table: " + Constants.HISTORY_RAW_TABLE); } return idConv.fromBytes(result...
java
@Override public void openWarningDialog() { final Dialog dialog = new Dialog( DialogType.WARNING, bean.getTitle(), bean.getHeader(), bean....
java
public void setParsedInputRecords(java.util.Collection<java.util.List<String>> parsedInputRecords) { if (parsedInputRecords == null) { this.parsedInputRecords = null; return; } this.parsedInputRecords = new java.util.ArrayList<java.util.List<String>>(parsedInputRecords);...
python
def serve_concatenated_pdf_from_memory( pdf_plans: Iterable[PdfPlan], start_recto: bool = True, offered_filename: str = "crate_download.pdf") -> HttpResponse: """ Concatenates PDFs into memory and serves it. WATCH OUT: may not apply e.g. wkhtmltopdf options as you'd wish. """ ...
python
def _refresh(self, **kwargs): """wrapped by `refresh` override that in a subclass to customize""" requests_params = self._handle_requests_params(kwargs) refresh_session = self._meta_data['bigip']._meta_data['icr_session'] if self._meta_data['uri'].endswith('/stats/'): # Slic...