language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def multilayer_fully_connected(images, labels): """Creates a multi layer network of fully_connected layers. Each layer is 100 neurons. Please change this to experiment with architectures. Args: images: The input images. labels: The labels as dense one-hot vectors. Returns: A softmax result. "...
python
def _run_task_internal(self, task): ''' run a particular module step in a playbook ''' hosts = self._list_available_hosts() self.inventory.restrict_to(hosts) runner = cirruscluster.ext.ansible.runner.Runner( pattern=task.play.hosts, inventory=self.inventory, module_name=tas...
java
@Nullable public AlluxioURI getParent() { String path = mUri.getPath(); int lastSlash = path.lastIndexOf('/'); int start = hasWindowsDrive(path, true) ? 3 : 0; if ((path.length() == start) || // empty path (lastSlash == start && path.length() == start + 1)) { // at root return null; ...
python
def follow_target_encode(self, timestamp, est_capabilities, lat, lon, alt, vel, acc, attitude_q, rates, position_cov, custom_state): ''' current motion information from a designated system timestamp : Timestamp in milliseconds since system boot (uint64_t)...
python
def _commit_change(alias_table, export_path=None, post_commit=True): """ Record changes to the alias table. Also write new alias config hash and collided alias, if any. Args: alias_table: The alias table to commit. export_path: The path to export the aliases to. Default: GLOBAL_ALIAS_PA...
python
def track_time(self, name, description='', max_rows=None): """ Create a Timer object in the Tracker. """ if name in self._tables: raise TableConflictError(name) if max_rows is None: max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE self.register_...
java
public static Object get(PageContext pc, Object coll, int[] types, Key[] keys, Object[][] args, Object defaultValue) throws PageException { if (coll == null) return defaultValue; int to = keys.length - 1; VariableUtilImpl vu = (VariableUtilImpl) pc.getVariableUtil(); for (int i = 0; i <= to; i++) { switch (typ...
java
public static base_responses update(nitro_service client, appqoeaction resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { appqoeaction updateresources[] = new appqoeaction[resources.length]; for (int i=0;i<resources.length;i++){ updateresources[i...
python
def sign_bitcoin(self, message, compressed=False): """ Signs a message using this private key such that it is compatible with bitcoind, bx, and other Bitcoin clients/nodes/utilities. Note: 0x18 + b\"Bitcoin Signed Message:" + newline + len(message) is prepended t...
python
def hessian(self, x, y, kwargs, k=None): """ hessian matrix :param x: x-position (preferentially arcsec) :type x: numpy array :param y: y-position (preferentially arcsec) :type y: numpy array :param kwargs: list of keyword arguments of lens model parameters match...
python
def load_many(self, fobjs=None): """Loads as many files as the number of pages Args: fobjs: [filename or DataFile obj, ...]""" if fobjs is not None: # tolerance if not hasattr(fobjs, "__iter__"): fobjs = [fobjs] for inde...
java
public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) { return this.setupTableLookup(itsLocation, targetScreen, iDisplayFieldDesc, this.makeReferenceRecord(), null, MessageProcessInfo.DESCRIPTION...
java
@OverrideOnDemand protected void onInsertAfter (@Nonnull final AbstractMicroNode aChildNode, @Nonnull final IMicroNode aPredecessor) { throw new MicroException ("Cannot insert children in class " + getClass ().getName ()); }
python
def wrap_get_channel(cls, response): """Wrap the response from getting a channel into an instance and return it :param response: The response from getting a channel :type response: :class:`requests.Response` :returns: the new channel instance :rtype: :class:`list` of :cl...
java
public static double[] latLonToMeters( double lat, double lon ) { double mx = lon * originShift / 180.0; double my = Math.log(Math.tan((90 + lat) * Math.PI / 360.0)) / (Math.PI / 180.0); my = my * originShift / 180.0; return new double[]{mx, my}; }
java
public void loadFrom(String modelfile) throws IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream(new BufferedInputStream( new GZIPInputStream(new FileInputStream(modelfile)))); templets = (TempletGroup) in.readObject(); cl = (Linear) in.readObject(); in.close(); }
java
private CmsSitemapHoverbar getHoverbar() { for (Widget w : getListItemWidget().getContentPanel()) { if (!(w instanceof CmsSitemapHoverbar)) { continue; } return (CmsSitemapHoverbar)w; } return null; }
python
def set_flair_csv(self, subreddit, flair_mapping): """Set flair for a group of users in the given subreddit. flair_mapping should be a list of dictionaries with the following keys: `user`: the user name, `flair_text`: the flair text for the user (optional), `flair_css_clas...
python
def tune_in_no_block(self): ''' Executes the tune_in sequence but omits extra logging and the management of the event bus assuming that these are handled outside the tune_in sequence ''' # Instantiate the local client self.local = salt.client.get_local_client( ...
java
@Override public File getFile() throws IOException { String realPath = RequestUtils.getRealPath(this.servletContext, this.path); return new File(realPath); }
java
public CmsResource readDefaultFile(CmsDbContext dbc, CmsResource resource, CmsResourceFilter resourceFilter) { // resource exists, lets check if we have a file or a folder if (resource.isFolder()) { // the resource is a folder, check if PROPERTY_DEFAULT_FILE is set on folder try...
java
protected String binaryOperator(final BinaryOperator operator, final String opString) { final String leftString = operator.type().precedence() < operator.left().type().precedence() ? this.toString(operator.left()) : this.bracket(operator.left()); final String rightString = operator.type(...
java
public static URI createUri(final String url, final boolean strict) { try { return newUri(url, strict); } catch (URISyntaxException e) { throw new AssertionError("Error creating URI: " + e.getMessage()); } }
python
def init_app(self, app): """ Initiate the extension on the application :param app: Flask Application :return: Blueprint for Flask Nautilus registered in app :rtype: Blueprint """ self.init_blueprint(app) if self.flaskcache is not None: for func, ext...
python
async def paginate(self): """Actually paginate the entries and run the interactive loop if necessary.""" await self.show_page(1, first=True) while self.paginating: react = await self.bot.wait_for_reaction(message=self.message, check=self.react_check, timeout=120.0) if re...
python
def hkeys(self, key, *, encoding=_NOTSET): """Get all the fields in a hash.""" return self.execute(b'HKEYS', key, encoding=encoding)
python
def unpack_header_extensions(extension_profile: int, extension_value: bytes) -> List[Tuple[int, bytes]]: """ Parse header extensions according to RFC 5285. """ extensions = [] pos = 0 if extension_profile == 0xBEDE: # One-Byte Header while pos < len(...
java
public static xen_health_resource[] get(nitro_service client) throws Exception { xen_health_resource resource = new xen_health_resource(); resource.validate("get"); return (xen_health_resource[]) resource.get_resources(client); }
java
public ArrayList<OvhCreationRule> rules_POST(OvhCreationRulesActionEnum action, String address, String area, String birthCity, String birthDay, String city, String companyNationalIdentificationNumber, String corporationType, OvhCountryEnum country, String email, String fax, String firstname, OvhLanguageEnum language, O...
java
public void setTabindex(java.lang.String tabindex) { getStateHelper().put(PropertyKeys.tabindex, tabindex); handleAttribute("tabindex", tabindex); }
java
private void onContainerStatus(final ContainerStatus value) { final String containerId = value.getContainerId().toString(); final boolean hasContainer = this.containers.hasContainer(containerId); if (hasContainer) { LOG.log(Level.FINE, "Received container status: {0}", containerId); final Res...
python
def display(self, stats, cs_status=None): """Display stats on the screen. stats: Stats database to display cs_status: "None": standalone or server mode "Connected": Client is connected to a Glances server "SNMP": Client is connected to a SNMP server ...
java
public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{ // retry count is optional so this is ok if(value == null || value.trim().equals("")) return FormValidation.ok(); if (!value.matches("[0-9]*")) { return FormValidatio...
python
def find_following_working_day(self, day): """Looks for the following working day, if not already a working day. **WARNING**: this function doesn't take into account the calendar holidays, only the days of the week and the weekend days parameters. """ day = cleaned_date(day) ...
java
@Override public AdminDisableUserResult adminDisableUser(AdminDisableUserRequest request) { request = beforeClientExecution(request); return executeAdminDisableUser(request); }
python
def _enum_lines(self): """Enumerate lines from the attached file.""" with _open_table(self.path, self.encoding) as lines: for i, line in enumerate(lines): yield i, line
python
def sign(self, payload): """ Signature method which wraps signature and nonce parameters around a payload dictionary. :param payload: :return: """ nonce = str(int(time.time() * 1000)) package = {'apikey': self.key, 'message': {'nonce': n...
python
def PReLU(x, init=0.001, name='output'): """ Parameterized ReLU as in the paper `Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification <http://arxiv.org/abs/1502.01852>`_. Args: x (tf.Tensor): input init (float): initial value for the learnable ...
python
def get_page_tags_from_request(request, page_lookup, lang, site, title=False): """ Get the list of tags attached to a Page or a Title from a request from usual `page_lookup` parameters. :param request: request object :param page_lookup: a valid page_lookup argument :param lang: a language code...
java
public boolean deleteUser(String name) { if (ADMIN_USER_ID.equals(name)) { throw new SystemException(String.format("Cannot delete '%s' user.", ADMIN_USER_ID)); } if (!isUserExist(name)) { throw new SystemException(String.format("User '%s' does not exist.", name)); } allAssociations.remove(name); ...
java
private void evaluateConstraints(DoubleSolution solution) { double [] constraint = new double[this.getNumberOfConstraints()]; double[] x = new double[getNumberOfVariables()] ; for (int i = 0; i < getNumberOfVariables(); i++) { x[i] = solution.getVariableValue(i) ; } double x1, x2, x3, x4; ...
java
@Override public Properties getJawrBundleMapping() { final Properties bundleMapping = new Properties(); InputStream is = null; try { is = getBundleMappingStream(); if (is != null) { ((Properties) bundleMapping).load(is); } else { LOGGER.info("The jawr bundle mapping '" + mappingFileName + "' is...
java
private void addDocumentInstances(I_CmsSearchDocument document) throws SolrServerException, IOException { List<String> serialDates = document.getMultivaluedFieldAsStringList(CmsSearchField.FIELD_SERIESDATES); SolrInputDocument inputDoc = (SolrInputDocument)document.getDocument(); String id = in...
java
public void executeQuery(boolean mustExecuteOnMaster, Results results, final ClientPrepareResult clientPrepareResult, ParameterHolder[] parameters) throws SQLException { cmdPrologue(); try { if (clientPrepareResult.getParamCount() == 0 && !clientPrepareResult .isQueryMultiValuesRewr...
python
def prox_zero(X, step): """Proximal operator to project onto zero """ return np.zeros(X.shape, dtype=X.dtype)
python
def get_nodes(self, node_type=""): """ Gets all nodes of requested type. If no type is provided by user, all nodes in BPMN diagram graph are returned. Returns a dictionary, where key is an ID of node, value is a dictionary of all node attributes. :param node_type: string with valid BPMN...
python
def parse_blob_snapshot_parameter(url): # type: (str) -> str """Retrieves the blob snapshot parameter from a url :param url str: blob url :rtype: str :return: snapshot parameter """ if blob_is_snapshot(url): tmp = url.split('?snapshot=') if len(tmp) == 2: return t...
python
def word_for_char(string_matrix: List[List[str]], character: str) -> List[str]: """ Diagnostic function, collect the words where a character appears :param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :param character: :return: >>> word_for...
python
def _add_work_spec_args(self, parser): '''Add ``--work-spec`` to an :mod:`argparse` `parser`.''' parser.add_argument('-w', '--work-spec', dest='work_spec_path', metavar='FILE', type=existing_path, required=True, help='pa...
java
public void performWork(String submissionDocId) throws Exception { // Get submission document CouchDb submissionDb = submissionDbDesignDocument.getDatabase(); JSONObject submissionDoc = submissionDb.getDocument(submissionDocId); JSONObject submissionInfo = submissionDoc.getJSONObject("nunaliit_submission"); ...
python
def c_metadata(api, args, verbose=False): """ Set or get metadata associated with an object:: usage: cdstar metadata <URL> [<JSON>] <JSON> Path to metadata in JSON, or JSON literal. """ obj = api.get_object(args['<URL>'].split('/')[-1]) if not set_metadata(args['<JSON>'], obj): return jso...
java
public Long createBatch(String batchTaskName, String data, String key1, String key2, List<TedTask> tedTasks) { return tedDriverImpl.createBatch(batchTaskName, data, key1, key2, tedTasks); }
java
@Override protected Object handleGetObject(String key) { for (ResourceBundle b : bundles) { try { return b.getObject(key); } catch (MissingResourceException mre) { // iterate } } throw new MissingResourceException(null, null, key); }
java
public INDArray asImageMiniBatches(File f, int numMiniBatches, int numRowsPerSlice) { try { INDArray d = asMatrix(f); return Nd4j.create(numMiniBatches, numRowsPerSlice, d.columns()); } catch (Exception e) { throw new RuntimeException(e); } }
java
@Override protected void visitRawTextNode(RawTextNode node) { Expression textArg = stringLiteral(node.getRawText()); JsCodeBuilder jsCodeBuilder = getJsCodeBuilder(); switch (node.getHtmlContext()) { case JS: case CSS: case HTML_RCDATA: case HTML_PCDATA: // Note - we don't ...
python
def run_direct(self, **kwargs): """ Run the motor at the duty cycle specified by `duty_cycle_sp`. Unlike other run commands, changing `duty_cycle_sp` while running *will* take effect immediately. """ for key in kwargs: setattr(self, key, kwargs[key]) s...
java
private SoyMsgBundle doExtractMsgs() { // extractMsgs disables a bunch of passes since it is typically not configured with things // like global definitions, type definitions, plugins, etc. SoyFileSetNode soyTree = parse( passManagerBuilder() .allowUnknownGlobals(...
java
public <K, V> StatefulRedisConnection<K, V> connect(RedisCodec<K, V> codec) { checkForRedisURI(); return getConnection(connectStandaloneAsync(codec, this.redisURI, timeout)); }
java
public void write(Workspace workspace, Writer writer) throws WorkspaceWriterException { if (workspace == null) { throw new IllegalArgumentException("Workspace cannot be null."); } if (writer == null) { throw new IllegalArgumentException("Writer cannot be null."); ...
python
def get_subgraph(self, subvertices, normalize=False): """Constructs a subgraph of the current graph Arguments: | ``subvertices`` -- The vertices that should be retained. | ``normalize`` -- Whether or not the vertices should renumbered and reduced to the given...
java
public synchronized void executeTaskWithUnifiedListener(@NonNull DownloadTask task, @NonNull DownloadListener listener) { attachListener(task, listener); task.execute(hostListener); }
python
def status(ctx, client, revision, no_output, path): """Show a status of the repository.""" graph = Graph(client) # TODO filter only paths = {graph.normalize_path(p) for p in path} status = graph.build_status(revision=revision, can_be_cwl=no_output) click.echo('On branch {0}'.format(client.repo.acti...
python
def wait(self): """ Wait for all running containers to stop. """ try: SpawningProxy(self.containers, abort_on_error=True).wait() except Exception: # If a single container failed, stop its peers and re-raise the # exception self.stop() ...
java
@Expose public static String camelize(final String text, final Locale locale) { return camelize(text, false, locale); }
python
def delete_collection_volume_attachment(self, **kwargs): """ delete collection of VolumeAttachment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_volume_attachment(async_...
python
def make_get_thread_stack_message(self, py_db, seq, thread_id, topmost_frame, fmt, must_be_suspended=False, start_frame=0, levels=0): """ Returns thread stack as XML. :param must_be_suspended: If True and the thread is not suspended, returns None. """ try: # If frame...
java
private void appendJoin(StringBuffer where, StringBuffer buf, Join join) { buf.append(","); appendTableWithJoins(join.right, where, buf); if (where.length() > 0) { where.append(" AND "); } join.appendJoinEqualities(where); }
python
def get_orientation(k, i, j): from pylocus.basics_angles import from_0_to_2pi """calculate angles theta_ik and theta_jk theta produce point Pk. Should give the same as get_absolute_angle! """ theta_ij = own.abs_angles[i, j] theta_ji = own.abs_angles[j, i] # complicated ...
java
@SuppressWarnings("unchecked") public static <T> T[] deepCopy(T[] array, Function<T, T> copyFunction) { Assert.notNull(array, "Array is required"); Assert.notNull(copyFunction, "Copy Function is required"); T[] arrayCopy = (T[]) Array.newInstance(array.getClass().getComponentType(), array.length); ...
python
def new_geom(geom_type, size, pos=(0, 0, 0), rgba=RED, group=0, **kwargs): """ Creates a geom element with attributes specified by @**kwargs. Args: geom_type (str): type of the geom. see all types here: http://mujoco.org/book/modeling.html#geom size: geom size parameters. ...
python
def On_close_criteria_box(self, dia): """ after criteria dialog window is closed. Take the acceptance criteria values and update self.acceptance_criteria """ criteria_list = list(self.acceptance_criteria.keys()) criteria_list.sort() #---------------------...
java
public void handlePut(HttpServletRequest request, HttpServletResponse response, String pathInContext, Resource resource) throws ServletException, IOException { boolean exists = resource != null && resource.exists(); if (exists && !passConditionalHeaders(request, response, resource)) retu...
java
public static boolean init(Object initableObj) { if (initableObj instanceof Initable) { ((Initable) initableObj).init(); return true; } return false; }
python
def process_method(self, method, args, kwargs, request_id=None, **context): """ Executes the actual method with args, kwargs provided. This step is broken out of the process_requests flow to allow for ease of overriding the call in your subclass of this class. In some cases it'...
java
public static PDFont chooseMatchingTimes(Font font) { if ((font.getStyle() & (Font.ITALIC | Font.BOLD)) == (Font.ITALIC | Font.BOLD)) return PDType1Font.TIMES_BOLD_ITALIC; if ((font.getStyle() & Font.ITALIC) == Font.ITALIC) return PDType1Font.TIMES_ITALIC; if ((font.getStyle() & Font.BOLD) == Font.BOLD) ...
java
public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName, Object columnValue, Class entityClazz) { // TODO Auto-generated method stub return null; }
python
def state_probability(self, direction, repertoire, purview,): """Compute the probability of the purview in its current state given the repertoire. Collapses the dimensions of the repertoire that correspond to the purview nodes onto their state. All other dimension are already si...
python
def record_is_valid(record): "Checks if a record is valid for processing." # No random contigs if record.CHROM.startswith('GL'): return False # Skip results with a read depth < 5. If no read depth is specified then # we have no choice but to consider this record as being valid. if 'DP'...
python
def fork(self, server_address: str = None, *, namespace: str = None) -> "State": r""" "Forks" this State object. Takes the same args as the :py:class:`State` constructor, except that they automatically default to the values provided during the creation of this State object. If ...
python
async def set_update_cb(self, cb): """Register the update callback.""" if self._report_task is not None and not self._report_task.cancelled(): self.loop.create_task(self._report_task.cancel()) self._update_cb = cb if cb is not None: self._report_task = self.loop.c...
python
def pad_aes256(s): """ Pads an input string to a given block size. :param s: string :returns: The padded string. """ if len(s) % AES.block_size == 0: return s return Padding.appendPadding(s, blocksize=AES.block_size)
java
public void foundActiveMaster(Protocol newMasterProtocol) { if (isMasterHostFail()) { if (isExplicitClosed()) { newMasterProtocol.close(); return; } if (!waitNewMasterProtocol.compareAndSet(null, newMasterProtocol)) { newMasterProtocol.close(); } } else { ne...
python
def update(self, ttl=values.unset): """ Update the SyncStreamInstance :param unicode ttl: Stream TTL. :returns: Updated SyncStreamInstance :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamInstance """ return self._proxy.update(ttl=ttl, )
java
protected int charGroup(char c) { int result; result = 0; if ( (c >= 'a') && (c <= 'z') ) result = 2; else if ( (c >= '0') && (c <= '9') ) result = 1; return result; }
python
def actors(context): """Display a list of actors""" fritz = context.obj fritz.login() for actor in fritz.get_actors(): click.echo("{} ({} {}; AIN {} )".format( actor.name, actor.manufacturer, actor.productname, actor.actor_id, )) i...
java
public final void removeRun(RunT run) { if (!builds.remove(run)) { LOGGER.log(Level.WARNING, "{0} did not contain {1} to begin with", new Object[] {asJob(), run}); } }
python
def downzip(url, destination="./sample_data/"): """Download, unzip and delete. Warning: function with strong side effects! Returns downloaded data. :param str url: url from which data should be donloaded :param destination: destination to which data should be downloaded """ # url = "http://14...
java
public static String generateApiString(ApplicationContext ctx, String remotingVarName, String pollingApiVarName) throws JsonProcessingException { RemotingApi remotingApi = new RemotingApi(ctx.getBean(ConfigurationService.class) .getConfiguration().getProviderType(), "router", null); for (Map.Entry<MethodInf...
java
public static JinxConstants.GeoContext flickrContextIdToGeoContext(int contextId) { JinxConstants.GeoContext ret; switch (contextId) { case 0: ret = JinxConstants.GeoContext.not_defined; break; case 1: ret = JinxConstants.GeoContext...
java
public FacesConfigValidatorType<FacesConfigType<T>> getOrCreateValidator() { List<Node> nodeList = childNode.get("validator"); if (nodeList != null && nodeList.size() > 0) { return new FacesConfigValidatorTypeImpl<FacesConfigType<T>>(this, "validator", childNode, nodeList.get(0)); }...
java
public static void setFieldValue(final Object target, final String name, final Object value) { Field field = FieldUtils.getDeclaredField(target.getClass(), name, true); if (field == null) { throw new IllegalArgumentException("Could not find field [" + name + "] on target [" + target + ']'); } try { ...
python
def identity_to_string(identity_dict): """Dump Identity dictionary into its string representation.""" result = [] if identity_dict.get('proto'): result.append(identity_dict['proto'] + '://') if identity_dict.get('user'): result.append(identity_dict['user'] + '@') result.append(identi...
java
public static void initCustomerSession(@NonNull Context context, @NonNull EphemeralKeyProvider keyProvider) { setInstance(new CustomerSession(context, keyProvider)); }
python
def get(self, request,pk): """ If the user requests his profile return it, else return a 403 (Forbidden) """ requested_profile = Profile.objects.get(user=pk) if requested_profile.user == self.request.user: return render(request, self.template...
python
def merge_configurations(configurations): """Merge configurations together and raise error if a conflict is detected :param configurations: configurations to merge together :type configurations: list of :attr:`~pyextdirect.configuration.Base.configuration` dicts :return: merged configurations as a sing...
python
def _aggregate_on_chunks(x, f_agg, chunk_len): """ Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on consecutive chunks of length chunk_len :param x: the time series to calculate the aggregation of :type x: numpy.ndarray :param f_...
python
def parse_soap_enveloped_saml_thingy(text, expected_tags): """Parses a SOAP enveloped SAML thing and returns the thing as a string. :param text: The SOAP object as XML string :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelo...
java
public void addInitConstraint (InitComponent lhs, Constraint constraint, InitComponent rhs) { if (lhs == null || rhs == null) { throw new IllegalArgumentException("Cannot add constraint about null component."); } InitComponent before = (constraint == Constraint.RUNS_BEFORE) ? lhs...
java
public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException { return appendTo(appendable, parts.iterator()); }
java
public void readImage() { if (ifd.containsTagId(TiffTags.getTagId("StripOffsets")) || ifd.containsTagId(TiffTags.getTagId("StripBYTECount"))) { readStrips(); } if (ifd.containsTagId(TiffTags.getTagId("TileOffsets")) || ifd.containsTagId(TiffTags.getTagId("TileBYTECounts"))) { rea...