language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@SuppressWarnings("unchecked") public EntityFunction resolveType(final Class<? extends Entity> type) { // Check already resolved EntityFunction resolvedType = resolved.get(Objects.requireNonNull(type)); if (resolvedType != null) { return resolvedType; } // Log type logger.info(String.format("Resolving t...
python
def get_code(self, address, block="latest"): """ https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getcode """ response = self.make_request("eth_getCode", [address, block]) return response['result']
python
def _CreateIndexIfNotExists(self, index_name, mappings): """Creates an Elasticsearch index if it does not exist. Args: index_name (str): mame of the index. mappings (dict[str, object]): mappings of the index. Raises: RuntimeError: if the Elasticsearch index cannot be created. """ ...
java
public Coupons getUniqueCouponCodes(final String couponCode, final QueryParams params) { return doGET(Coupon.COUPON_RESOURCE + "/" + couponCode + Coupon.UNIQUE_CODES_RESOURCE, Coupons.class, params); }
python
def _parse_from_ref(cls, pairs=None, flat=None, reference=None, serialized=None, urlsafe=None, app=None, namespace=None, parent=None): """Construct a Reference; the signature is the same as for Key.""" if cls is not Key: raise TypeError('Cannot construct Key ref...
java
public long addObstacle(float[] pos, float radius, float height) { TileCacheObstacle ob = allocObstacle(); ob.type = TileCacheObstacleType.CYLINDER; vCopy(ob.pos, pos); ob.radius = radius; ob.height = height; return addObstacleRequest(ob).ref; }
java
public void setRoleSelectionAllowed(boolean editRoles) { m_principalTypeSelect.removeItem(CmsRole.PRINCIPAL_ROLE); if (editRoles) { Item item = m_principalTypeSelect.addItem(CmsRole.PRINCIPAL_ROLE); String roleText = CmsVaadinUtils.getMessageText(org.opencms.workplace.commons.Me...
java
@Override public List<String> headers(String name) { return request.headers().get(name); }
java
public void marshall(AssociateConfigurationItemsToApplicationRequest associateConfigurationItemsToApplicationRequest, ProtocolMarshaller protocolMarshaller) { if (associateConfigurationItemsToApplicationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); ...
python
def get_projects(self, **kwargs): """Get a user's project. :param str login: User's login (Default: self._login) :return: JSON """ _login = kwargs.get('login', self._login) search_url = SEARCH_URL.format(login=_login) return self._request_api(url=search_url).jso...
python
def comment_list(self, group_by, limit=None, page=None, body_matches=None, post_id=None, post_tags_match=None, creator_name=None, creator_id=None, is_deleted=None): """Return a list of comments. Parameters: limit (int): How many posts you want to re...
java
static private SnowflakeDateTimeFormat specializedFormatter( Map<String, Object> parameters, String id, String param, String defaultFormat) { String sqlFormat = SnowflakeDateTimeFormat.effectiveSpecializedTimestampFormat( (String) effectiveParamValue(parameters, param),...
python
def _fit_island(self, island_data): """ Take an Island, do all the parameter estimation and fitting. Parameters ---------- island_data : :class:`AegeanTools.models.IslandFittingData` The island to be fit. Returns ------- sources : list ...
java
public static double getRMSD(List<Atom[]> transformed) { double sumSqDist = 0; int comparisons = 0; for (int r1 = 0; r1 < transformed.size(); r1++) { for (int c = 0; c < transformed.get(r1).length; c++) { Atom refAtom = transformed.get(r1)[c]; if (refAtom == null) continue; double nonNullSq...
python
def getslide(self,slide_num): """ Return the triggers with a specific slide number. @param slide_num: the slide number to recover (contained in the event_id) """ slideTrigs = self.copy() slideTrigs.extend(row for row in self if row.get_slide_number() == slide_num) return slideTrigs
java
private JButton getBtnEnableAll() { if (btnEnableAll == null) { btnEnableAll = new JButton(); btnEnableAll.setText(Constant.messages.getString("filter.button.enableall")); btnEnableAll.setEnabled(false); btnEnableAll.addActionListener(new java.awt.event.ActionListener() { @Override publi...
java
public synchronized void makeCustomRequest(AnalyticsRequestData argData) { if (!enabled) { logger.debug("Ignoring tracking request, enabled is false"); return; } if (argData == null) { throw new NullPointerException("Data cannot be null"); } if...
java
public void setReplicationJobList(java.util.Collection<ReplicationJob> replicationJobList) { if (replicationJobList == null) { this.replicationJobList = null; return; } this.replicationJobList = new java.util.ArrayList<ReplicationJob>(replicationJobList); }
python
def interpolate_2d(values, method='pad', axis=0, limit=None, fill_value=None, dtype=None): """ Perform an actual interpolation of values, values will be make 2-d if needed fills inplace, returns the result. """ transf = (lambda x: x) if axis == 0 else (lambda x: x.T) # resha...
python
def writeinfo(self, linelist, colour = None): """ We add a longer chunk of text on the upper left corner of the image. Provide linelist, a list of strings that will be written one below the other. """ self.checkforpilimage() colour = self.defaultcolour(colour) ...
python
def resize(self, lines=None, columns=None): """Resize the screen to the given size. If the requested screen size has more lines than the existing screen, lines will be added at the bottom. If the requested size has less lines than the existing screen lines will be clipped at the...
java
public Observable<Boolean> checkExistenceAsync(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion) { return checkExistenceWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, res...
python
def filesystem_from_config_dict(config_fs): """ Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider. Exits if there is an error. """ if "module" not in config_fs: print("Key 'module' should be defined for the fil...
python
def under_attack(col, queens): """Checks if queen is under attack :param col: Column number :param queens: list of queens :return: True iff queen is under attack """ left = right = col for _, column in reversed(queens): left, right = left - 1, right +...
java
@Override public void removeAllElectronContainers() { removeAllBonds(); lonePairs = new ILonePair[growArraySize]; singleElectrons = new ISingleElectron[growArraySize]; lonePairCount = 0; singleElectronCount = 0; }
java
public String marshalService(ServiceWrapper service) { Service xmlService = composeServiceFromServiceWrapper(service); StringWriter sw = new StringWriter(); try { JAXBContext jaxbContext = JAXBContext.newInstance(Service.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); ...
python
def _name_attribute_to_string(self, name): """ Build a /-separated string from an x509.Name. """ return "".join( "/{}={}".format( self._get_oid_name(attr.oid), attr.value, ) for attr in name )
java
void formatFractionalSeconds(StringBuilder b, ZonedDateTime d, int width) { // format up to 9 digits at nanosecond resolution. int nano = d.getNano(); int f = 100000000; while (width > 0 && f > 0) { int digit = nano / f; nano -= (digit * f); f /= 10; b.append(digit); width-...
python
def iter_init(self) : "creates an iterator for extracting the arguments of the Message." iter = self.ExtractIter(None) if dbus.dbus_message_iter_init(self._dbobj, iter._dbobj) == 0 : iter._nulliter = True #end if return \ iter
python
def build(self, builder): """ Build this element :param builder: :return: """ builder.start(self.__class__.__name__) builder.data(self.country_code) builder.end(self.__class__.__name__)
python
def get_job(self, job_name): """ Returns a Job by name, or None if none exists. """ for job in self.jobs: if job.name == job_name: return job logger.warn('Tried to find job with name {0}, but job not found'.format(job_name)) return None
python
def parse(self, charset=None, headers=None): """ Parse headers. This method is called after Grab instance performs network request. """ if headers: self.headers = headers else: # Parse headers only from last response # There could be ...
java
public static long reverse(long i) { // HD, Figure 7-1 i = (i & 0x5555555555555555L) << 1 | (i >>> 1) & 0x5555555555555555L; i = (i & 0x3333333333333333L) << 2 | (i >>> 2) & 0x3333333333333333L; i = (i & 0x0f0f0f0f0f0f0f0fL) << 4 | (i >>> 4) & 0x0f0f0f0f0f0f0f0fL; i = (i & 0x00ff...
java
protected void verifyAgentName(ILaunchConfiguration configuration) throws CoreException { final String name = getAgentName(configuration); if (name == null) { abort( io.sarl.eclipse.launching.dialog.Messages.MainLaunchConfigurationTab_2, null, SARLEclipseConfig.ERR_UNSPECIFIED_AGENT_NAME); } }
python
def transfer(self, name, local, remote, **kwargs): """ Transfers the file with the given name from the local to the remote storage backend. :param name: The name of the file to transfer :param local: The local storage backend instance :param remote: The remote storage ba...
python
def download_aspera(self, user, host, silent=False): """Download file with Aspera Connect. For details see the documentation ov Aspera Connect Args: user (:obj:`str`): FTP user. host (:obj:`str`): FTP host. Defaults to "ftp-trace.ncbi.nlm.nih.gov". """ a...
java
protected final void init() { checkState(!initialized, "initialized already"); Throwable cause = null; try { final File[] childFiles = rootDir.listFiles(); if (childFiles != null) { for (File f : childFiles) { loadChild(f); ...
java
public EEnum getIfcChillerTypeEnum() { if (ifcChillerTypeEnumEEnum == null) { ifcChillerTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(793); } return ifcChillerTypeEnumEEnum; }
java
public static <T, X extends Exception> CheckedFuture<T, X> checkedFuture(final CheckedAsync<T, X> async) { return Futures.makeChecked(future(async), async); }
python
def auth(self, password): """Request for authentication in a password-protected Redis server. Redis can be instructed to require a password before allowing clients to execute commands. This is done using the ``requirepass`` directive in the configuration file. If the password do...
java
@Override public void exitIdentifierVal(QueryParser.IdentifierValContext ctx) { queryExprMeta.arguments(Val.of(ctx.getText())); }
java
@Override // NameNodeMXBean public String getDecomNodes() { final Map<String, Map<String, Object>> info = new HashMap<String, Map<String, Object>>(); try { final ArrayList<DatanodeDescriptor> decomNodeList = this.getDecommissioningNodesList(); for (DatanodeDescriptor node : decomNo...
java
static String javaScriptPropertyToJavaPropertyName(final String prefix, final String jsPropertyName) { if (jsPropertyName.isEmpty()) { throw new JsiiException("jsPropertyName must not be empty"); } StringBuilder sb = new StringBuilder(); sb.append(prefix); sb.append(...
java
public SpotFleetRequestConfigData withLaunchSpecifications(SpotFleetLaunchSpecification... launchSpecifications) { if (this.launchSpecifications == null) { setLaunchSpecifications(new com.amazonaws.internal.SdkInternalList<SpotFleetLaunchSpecification>(launchSpecifications.length)); } ...
python
def push(stack, x, op_id): """Push a value onto the stack (i.e. record it on the tape). Args: stack: The stack object, which must support appending values. x: The value to append. If it is a mutable object like an array or list, it will be copied before being added onto the stack. op_id: A uniq...
java
private void disposeRulesAndResultHandlers() { for (final Map.Entry<R, List<RH>> entry : rulesToResultHandlers.entrySet()) { // Dispose rule final R rule = entry.getKey(); if (rule instanceof Disposable) { ((Disposable) rule).dispose(); } ...
java
public void markForUpdate() { if (!updated) { updated = true; // Make a copy of the underlying property map, if non-null if (properties != null) { properties = properties.copyOf(); } tx.markForPropertyUpdate(this); ...
python
def run_job(self, name): ''' Run a schedule job now ''' data = self._get_schedule().get(name, {}) if 'function' in data: func = data['function'] elif 'func' in data: func = data['func'] elif 'fun' in data: func = data['fun'] ...
python
def add_value(self, value, row, col): """ Adds a single value (cell) to a worksheet at (row, col). Return the (row, col) where the value has been put. :param value: Value to write to the sheet. :param row: Row where the value should be written. :param col: Column where t...
python
def crop(self, cropping): """ Set `a:srcRect` child to crop according to *cropping* values. """ srcRect = self._add_srcRect() srcRect.l, srcRect.t, srcRect.r, srcRect.b = cropping
python
def str_endswith(arr, pat, na=np.nan): """ Test if the end of each string element matches a pattern. Equivalent to :meth:`str.endswith`. Parameters ---------- pat : str Character sequence. Regular expressions are not accepted. na : object, default NaN Object shown if elemen...
java
private void unlinkLast(Node<E> last, Node<E> prev) { // assert last != null; // assert prev != null; // assert last.item == null; for (Node<E> o = null, p = prev, q;;) { if (p.item != null || (q = p.prev) == null) { if (o != null && p.next != p && ...
python
def get_card_bundles(provider: Provider, deck: Deck) -> Generator: '''get all <deck> card bundles, if they match the protocol''' bundles = find_card_bundles(provider, deck) with concurrent.futures.ThreadPoolExecutor(max_workers=2) as th: for result in th.map(card_bundle_parser, bundles): ...
python
def get_arguments(): """Get the command line arguments""" import argparse parser = argparse.ArgumentParser( description='Plot spectral responses for a set of satellite imagers') parser.add_argument("--platform_name", '-p', nargs='*', help="The Platform name", ...
java
@Override public T newInstance( final Class<T> clazz, final javolution.xml.XMLFormat.InputElement xml ) throws XMLStreamException { try { return _constructor.newInstance( INITARGS ); } catch ( final Exception e ) { throw new XMLStreamException( e ); } }
java
protected boolean onLayout() { boolean changed = isChanged(); boolean runLayout = false; Log.d(Log.SUBSYSTEM.LAYOUT, TAG, "onLayout() called (%s) mChanged = %b ", getName(), changed); FPSCounter.timeCheck("onLayout <START>: " + this + "<" + getName() + "> changed = " + changed); ...
python
def verbosityToLogLevel(verbosity): """ Returns the specfied verbosity level interpreted as a logging level. """ ret = 0 if verbosity == 1: ret = logging.INFO elif verbosity >= 2: ret = logging.DEBUG return ret
python
def kill(self, sig): '''Sends a Unix signal to the subprocess. Use constants from the :mod:`signal` module to specify which signal. ''' if sys.platform == 'win32': if sig in [signal.SIGINT, signal.CTRL_C_EVENT]: sig = signal.CTRL_C_EVENT elif sig ...
python
def dedent(self, func): """ Dedent the docstring of a function and substitute with :attr:`params` Parameters ---------- func: function function with the documentation to dedent and whose sections shall be inserted from the :attr:`params` attribute""" ...
python
def writeFile(self, fname = None): """Writes the `RecordCollection` to a file, the written file's format is identical to those download from WOS. The order of `Records` written is random. # Parameters _fname_ : `optional [str]` > Default `None`, if given the output file will written t...
java
protected Document doGet(String spaceId, String key) throws IOException { Term termGet = buildIdTerm(spaceId, key); IndexSearcher indexSearcher = getIndexSearcher(); TopDocs result = indexSearcher.search(new TermQuery(termGet), 1); ScoreDoc[] hits = result != null ? result.scoreDocs : nu...
java
public static ScorecardModel make(final String name, final double initialScore, RuleTable[] rules) { // Get the list of features String[] colNames = new String[rules.length]; for( int i=0; i<rules.length; i++ ) colNames[i] = rules[i]._name; // javassist support for rewriting class files Class...
python
def open(self, name, mode='rb'): """ Retrieves the specified file from storage. :param name: file name :type name: str :param mode: mode to open the file with :type mode: str :rtype: :class:`~django:django.core.files.File` """ return self.get_stor...
python
def has_basis_notes(family, data_dir=None): '''Check if notes exist for a given basis set Returns True if they exist, false otherwise ''' file_path = _basis_notes_path(family, data_dir) return os.path.isfile(file_path)
java
public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) { return appendIfMissing(str, suffix, true, suffixes); }
java
public static br_device_profile delete(nitro_service client, br_device_profile resource) throws Exception { resource.validate("delete"); return ((br_device_profile[]) resource.delete_resource(client))[0]; }
java
@SuppressWarnings("unchecked") private Object parseEnumParameter(final Enum<?> e, final String serializedObject) { final Object res = Enum.valueOf(e.getClass(), serializedObject); return res; }
java
protected void viewLocationDidChange (int dx, int dy) { // inform our view trackers for (int ii = 0, ll = _trackers.size(); ii < ll; ii++) { _trackers.get(ii).viewLocationDidChange(dx, dy); } // pass the word on to our sprite/anim managers via the meta manager _m...
java
private void obtainButtonBarElevation() { int elevation; try { elevation = ThemeUtil.getDimensionPixelSize(this, R.attr.buttonBarElevation); } catch (NotFoundException e) { elevation = getResources().getDimensionPixelSize(R.dimen.button_bar_elevation); } ...
java
public static <T, S extends BaseConfig> IExtractor<T, S> getExtractorInstance(S config) { try { Class<T> rdd = (Class<T>) config.getExtractorImplClass(); if (rdd == null) { rdd = (Class<T>) Class.forName(config.getExtractorImplClassName()); } Cons...
java
public static void write(Image image, String format, OutputStream out, boolean writeAlpha) throws SlickException { try { ImageWriter writer = ImageWriterFactory.getWriterForFormat(format); writer.saveImage(image, format, out, writeAlpha); } catch (IOException e) { throw new SlickException("Unable to w...
java
void addOutput() { if( output != null ) { outputs.addLast( output ); } output = state.pool.get(); }
python
def linOriginRegression(points): """ computes a linear regression starting at zero """ j = sum([ i[0] for i in points ]) k = sum([ i[1] for i in points ]) if j != 0: return k/j, j, k return 1, j, k
java
private ServiceRegistration.EndpointHealthCheck endpointHealthCheck(String portName) { if (healthCheck() instanceof HttpHealthCheck) { final HttpHealthCheck httpHealthCheck = (HttpHealthCheck) healthCheck(); if (portName.equals(httpHealthCheck.getPort())) { return ServiceRegistration.EndpointHea...
java
private boolean validateServer(String host, int port){ if(host==null || host.isEmpty()){ return false; } if(port <=0 || port > 65535){ return false; } return true; }
python
def generate(env): """Add Builders and construction variables for yacc to an Environment.""" c_file, cxx_file = SCons.Tool.createCFileBuilders(env) # C c_file.add_action('.y', YaccAction) c_file.add_emitter('.y', yEmitter) c_file.add_action('.yacc', YaccAction) c_file.add_emitter('.yacc', ...
java
ThrowsTag[] throwsTags() { ListBuffer<ThrowsTag> found = new ListBuffer<>(); for (Tag next : tagList) { if (next instanceof ThrowsTag) { found.append((ThrowsTag)next); } } return found.toArray(new ThrowsTag[found.length()]); }
python
def StrSubstr(start_idx, count, initial_string): """ Create a concrete version of the substring :param start_idx : starting index of the substring :param end_idx : last index of the substring :param initial_string :return : a concrete version of the substring """ new_value = initial_str...
python
def get_template_sources(template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. """...
python
def enable(app_id, enabled=True): ''' Enable or disable an existing assistive access application. app_id The bundle ID or command to set assistive access status. enabled Sets enabled or disabled status. Default is ``True``. CLI Example: .. code-block:: bash salt '*' ...
python
def search_for_devices_by_serial_number(self, sn): """ Returns a list of device objects that match the serial number in param 'sn'. This will match partial serial numbers. """ import re sn_search = re.compile(sn) matches = [] for dev...
python
def parse_header_tags(): """Parse tags specified in the HTTP request header.""" # Get the value of the custom HTTP header and interpret it as an query # string qs = request.headers.get( current_app.config['FILES_REST_FILE_TAGS_HEADER'], '') tags = {} for key, value in parse_qsl(qs): ...
python
def parse(self, argv): """Parse the given argument vector.""" kwargs, args = self.parse_args(argv) self.result['args'] += args # Annoying that parse_args doesn't just return a dict for dest in self.dests: value = getattr(kwargs, dest) if value is not None:...
python
def get_catalog_query_session(self): """Gets the catalog query session. return: (osid.cataloging.CatalogQuerySession) - a ``CatalogQuerySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_catalog_query()`` is ...
java
protected void activateButtons(boolean activate) { m_acceptButton.setEnabled(activate); m_declineButton.setEnabled(activate); getCloseButton().setEnabled(activate); }
python
def parse_config_file(job, config_file, max_cores=None): """ Parse the config file and spawn a ProTECT job for every input sample. :param str config_file: Path to the input config file :param int max_cores: The maximum cores to use for any single high-compute job. """ sample_set, univ_options, ...
python
def create_db(self): """ Setups the DB, creates admin and public roles if they don't exist. """ self.add_role(self.auth_role_admin) self.add_role(self.auth_role_public) if self.count_users() == 0: log.warning(LOGMSG_WAR_SEC_NO_USER)
python
def p_fn(self, p): """ fn : FUNC LPAREN arguments RPAREN """ fn = getattr(self, 'fn_{0}'.format(p[1])) p[0] = Instruction('fn(*[x.execute() if isinstance(x, Instruction) else x for x in args])', context={ 'fn': fn, 'args': p[3], 'Instruction':...
java
private void readStringChars2(CharArr arr, int middle) throws IOException { if (stringTerm == 0) { readStringBare(arr); return; } char terminator = (char) stringTerm; for (;;) { if (middle>=end) { arr.write(buf,start,middle-start); start=middle; getMore(); ...
python
def _apply_volcanic_front_correction(mean, x_vf, H, imt): """ Implement equation for volcanic front correction as described in equation 3.5.2.-2, page 3-149 of "Technical Reports on National Seismic Hazard Maps for Japan" """ V1 = np.zeros_like(x_vf) if imt.name == 'PGV': idx = x_vf ...
python
def upgrade_cmd(argv=sys.argv[1:]): # pragma: no cover """\ Upgrade the database to the latest version. Usage: pld-ugprade [options] Options: --from=<v> Upgrade from a specific version, overriding the version stored in the database. --to=<v> Upgrade...
java
public static <K extends Comparable<?>, V> ListMultimap<K, V> sortedArrayListMultimap() { Map<K, Collection<V>> map = Maps.newTreeMap(); return Multimaps.newListMultimap(map, new Supplier<List<V>>() { @Override public List<V> get() { return Lists.n...
java
@Override public Node visitJoinRelation(SqlBaseParser.JoinRelationContext context) { Relation left = (Relation) visit(context.left); Relation right; if (context.CROSS() != null) { right = (Relation) visit(context.right); return new Join(getLocation(context), Join...
java
private void addPostParams(final Request request) { if (read != null) { request.addPostParam("Read", read.toString()); } if (write != null) { request.addPostParam("Write", write.toString()); } if (manage != null) { request.addPostParam("Manag...
java
public void marshall(ResourceIdentifier resourceIdentifier, ProtocolMarshaller protocolMarshaller) { if (resourceIdentifier == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resourceIdentifier.getRes...
java
public Iterator<T> headIterator(T key, boolean inclusive) { int point = point(key, !inclusive); return subList(0, point).iterator(); }
java
public ApiResponse<Boolean> deleteEntityPostWithHttpInfo(DeleteEntityRequest request) throws ApiException { com.squareup.okhttp.Call call = deleteEntityPostValidateBeforeCall(request, null, null); Type localVarReturnType = new TypeToken<Boolean>(){}.getType(); return apiClient.execute(call, loca...
python
def sum_obs(A): """summation over axis 0 (obs) equivalent to np.sum(A, 0) """ return A.sum(0).A1 if issparse(A) else np.einsum('ij -> j', A)
java
public static double pbarStd(double pbar, int sampleN) { return Math.sqrt(pbarVariance(pbar, sampleN, Integer.MAX_VALUE)); }
java
public Html getHtml() { if (html == null) { html = new Html(rawText, request.getUrl()); } return html; }