language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def df_to_tsv(df, tsvfile, suffix): """ Serialize the dataframe as a tsv """ tsvfile += suffix columns = ["SampleKey"] + sorted(x for x in df.columns if x.endswith(suffix)) tf = df.reindex_axis(columns, axis='columns') tf.sort_values("SampleKey") tf.to_cs...
python
def _validate_hue(df, hue): """ The top-level ``hue`` parameter present in most plot types accepts a variety of input types. This method condenses this variety into a single preferred format---an iterable---which is expected by all submethods working with the data downstream of it. Parameters -...
java
public ServiceFuture<EnvironmentSettingInner> updateAsync(String resourceGroupName, String labAccountName, String labName, String environmentSettingName, EnvironmentSettingFragment environmentSetting, final ServiceCallback<EnvironmentSettingInner> serviceCallback) { return ServiceFuture.fromResponse(updateWithS...
java
public Object execute(final Object dataIn) throws DevFailed { xlogger.entry(name); Object result; try { result = behavior.execute(dataIn); } catch (final DevFailed e) { lastError = e; throw e; } xlogger.exit(name); return result...
python
def create_new(cls, oldvalue, *args): "Raise if the old value already exists" if oldvalue is not None: raise AlreadyExistsException('%r already exists' % (oldvalue,)) return cls.create_instance(*args)
java
void write_attribute_reply(int timeout) { DevError[] errors = null; try { if (timeout==NO_TIMEOUT) dev.write_attribute_reply(id); else dev.write_attribute_reply(id, 0); } catch(AsynReplyNotArrived e) { errors = e.errors; } catch(DevFailed e) { errors = e.errors; } cb.attr_writ...
java
public DiffBuilder append(final String fieldName, final double lhs, final double rhs) { validateFieldNameNotNull(fieldName); if (objectsTriviallyEqual) { return this; } if (Double.doubleToLongBits(lhs) != Double.doubleToLongBits(rhs)) { diffs.add(new ...
java
public static ByteBuf copyShort(int value) { ByteBuf buf = buffer(2); buf.writeShort(value); return buf; }
python
def send(self, data): """ Tries to send data to the client. :param data: Data to be sent :return: True if the data was sent, False on error """ if data is not None: data = data.encode("UTF-8") try: self.wfile.write(data) self....
python
def convert(from_currency, to_currency, from_currency_price=1): """ convert from from_currency to to_currency using cached info """ get_cache() from_currency, to_currency = validate_currency(from_currency, to_currency) update_cache(from_currency, to_currency) return ccache[from_currency][to_currency]['value'] * fr...
java
public static MotionDirection getVerticalMotionDirection(MotionEvent e1, MotionEvent e2, float threshold) { float delta = getVerticalMotionRawDelta(e1, e2); return getVerticalMotionDirection(delta, threshold); }
java
protected ProxyArtifactStore createProxyArtifactStore() { return new ProxyArtifactStore( repositoryMetadataManager, remoteArtifactRepositories, remotePluginRepositories, localRepository, artifactFactory, artifactResolver, archetypeManager, getLog() ); }
python
def swap_columns(self, column_name_1, column_name_2, inplace=False): """ Returns an SFrame with two column positions swapped. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the...
java
@Override public Iterable<T> findAll(@NonNull Sort sort) { Assert.notNull(sort, "sort of findAll should not be null"); final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)).with(sort); return operation.find(query, information.getJavaType(), information.getCol...
python
def make(id, client, cls, parent_id=None, json=None): """ Makes an api object based on an id and class. :param id: The id of the object to create :param client: The LinodeClient to give the new object :param cls: The class type to instantiate :param parent_id: The parent...
python
def read_sphinx_environment(pth): """Read the sphinx environment.pickle file at path `pth`.""" with open(pth, 'rb') as fo: env = pickle.load(fo) return env
java
@Override public void serialize(JsonObject value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException { gen.writeObject(value.getMap()); }
python
def _zm_request(self, method, api_url, data=None, timeout=DEFAULT_TIMEOUT) -> dict: """Perform a request to the ZoneMinder API.""" try: # Since the API uses sessions that expire, sometimes we need to # re-auth if the call fails. for _ in range(Zone...
java
public static String getPippoVersion() { // and the key inside the properties file. String pippoVersionPropertyKey = "pippo.version"; String pippoVersion; try { Properties prop = new Properties(); URL url = ClasspathUtils.locateOnClasspath(PippoConstants.LOCATIO...
python
def get_b(self): """Returns the bottom border of the cell""" start_point, end_point = self._get_bottom_line_coordinates() width = self._get_bottom_line_width() color = self._get_bottom_line_color() return CellBorder(start_point, end_point, width, color)
python
def event_source_mapping_present(name, EventSourceArn, FunctionName, StartingPosition, Enabled=True, BatchSize=100, region=None, key=None, keyid=None, profile=None): ''' Ensure event source mapping exists. na...
java
public <R> SingleOutputStreamOperator<R> apply(WindowFunction<T, R, K, W> function, TypeInformation<R> resultType) { function = input.getExecutionEnvironment().clean(function); return apply(new InternalIterableWindowFunction<>(function), resultType, function); }
java
protected String getOpenGalleryCall( CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param, long hashId) { StringBuffer sb = new StringBuffer(128); sb.append("javascript:cmsOpenDialog('"); // the gallery title sb.append(widgetDialog.g...
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { version_matrix_status_responses result = (version_matrix_status_responses) service.get_payload_formatter().string_to_resource(version_matrix_status_responses.class, response); if(result.errorcode != 0) ...
python
def fave_mentions(api, dry_run=None): ''' Fave (aka like) recent mentions from user authenicated in 'api'. :api twitter_bot_utils.api.API :dry_run bool don't actually favorite, just report ''' f = api.favorites(include_entities=False, count=150) favs = [m.id_str for m in f] try: ...
python
def on_get(resc, req, resp, rid): """ Find the model by id & serialize it back """ signals.pre_req.send(resc.model) signals.pre_req_find.send(resc.model) model = find(resc.model, rid) props = to_rest_model(model, includes=req.includes) resp.last_modified = model.updated resp.serialize(pro...
python
def standardize(self): """ Standardize data. """ if self.preprocessed_data.empty: data = self.original_data else: data = self.preprocessed_data scaler = preprocessing.StandardScaler() data = pd.DataFrame(scaler.fit_transform(data), columns=data.c...
python
def prepareToCalcEndOfPrdvP(self): ''' Prepare to calculate end-of-period marginal value by creating an array of market resources that the agent could have next period, considering the grid of end-of-period normalized assets, the grid of persistent income levels, and the distribu...
python
def strptime(cls, value, format): """ Parse a datetime string using the provided format. This also emulates `%z` support on Python 2. :param value: Datetime string :type value: str :param format: Format to use for parsing :type format: str :rtype: datetime ...
java
public void marshall(UpdateVPCEConfigurationRequest updateVPCEConfigurationRequest, ProtocolMarshaller protocolMarshaller) { if (updateVPCEConfigurationRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshalle...
python
def get_all_parents(go_objs): """Return a set containing all GO Term parents of multiple GOTerm objects.""" go_parents = set() for go_obj in go_objs: go_parents |= go_obj.get_all_parents() return go_parents
java
@Override public KamNode getKamNode(final Kam kam, String belTermString) { if (noLength(belTermString)) throw new InvalidArgument("belTermString", belTermString); KamInfo ki = kam.getKamInfo(); if (!exists(ki)) return null; KamNode kamNode; Integer nodeID; ...
python
def _create_tc_dirs(self): """Create app directories for logs and data files.""" tc_log_path = self.profile.get('args', {}).get('tc_log_path') if tc_log_path is not None and not os.path.isdir(tc_log_path): os.makedirs(tc_log_path) tc_out_path = self.profile.get('args', {}).ge...
python
def main(): """Read GeoTiff raster data and print statistics. The output will be:: rows: 130, cols: 100 LLCornerX: 755145.28, LLCornerY: 654294.06 cell size: 10.0 mean: 203.92, max: 284.07, min: 139.11 std: 32.32, sum: 2650967.00 """ input_tif = "../tests/data/J...
python
def parent_workspace(context): """ Return containing workspace Returns None if not found. """ if IWorkspaceFolder.providedBy(context): return context for parent in aq_chain(context): if IWorkspaceFolder.providedBy(parent): return parent
python
def colorbrewer2_url(self): """ URL that can be used to view the color map at colorbrewer2.org. """ url = 'http://colorbrewer2.org/index.html?type={0}&scheme={1}&n={2}' return url.format(self.type.lower(), self.name, self.number)
python
def value_derived_from_wavefunction(self, state: np.ndarray, qubit_map: Dict[raw_types.Qid, int] ) -> Any: """The value of the display, derived from the full wavefunction. Args: ...
python
def make_stmt_from_sort_key(key, verb): """Make a Statement from the sort key. Specifically, the sort key used by `group_and_sort_statements`. """ def make_agent(name): if name == 'None' or name is None: return None return Agent(name) StmtClass = get_statement_by_name(v...
java
private void linkEntities() { for (int i =0; i< allModels.size() ; i++){ for (Chain chain : allModels.get(i)) { //logger.info("linking entities for " + chain.getId() + " " + chain.getName()); String entityId = asymId2entityId.get(chain.getId()); if (entityId==null) { // this can happen for inst...
python
def get(self, name=None): """ Returns the plugin object with the given name. Or if a name is not given, the complete plugin dictionary is returned. :param name: Name of a plugin :return: None, single plugin or dictionary of plugins """ if name is None: ...
python
def is_safe_attribute(self, obj, attr, value): """The sandboxed environment will call this method to check if the attribute of an object is safe to access. Per default all attributes starting with an underscore are considered private as well as the special attributes of internal python ...
python
def collect(self): """ Collect interrupt data """ if not os.access(self.PROC, os.R_OK): return False # Open PROC file file = open(self.PROC, 'r') # Get data for line in file: if not line.startswith('softirq'): con...
python
def scan_band(self, band, **kwargs): """Run Kalibrate for a band. Supported keyword arguments: gain -- Gain in dB device -- Index of device to be used error -- Initial frequency error in ppm """ kal_run_line = fn.build_kal_scan_band_string(self.kal_bin, ...
python
def interpolate(x, y, z, interp_type='linear', hres=50000, minimum_neighbors=3, gamma=0.25, kappa_star=5.052, search_radius=None, rbf_func='linear', rbf_smooth=0, boundary_coords=None): """Wrap interpolate_to_grid for deprecated interpolate function.""" return int...
python
def put_directory(self, target_path, local_directory, **kwargs): """Upload a directory with all its contents :param target_path: path of the directory to upload into :param local_directory: path to the local directory to upload :param \*\*kwargs: optional arguments that ``put_file`` acc...
python
def kill(timeout=15): ''' Kill the salt minion. timeout int seconds to wait for the minion to die. If you have a monitor that restarts ``salt-minion`` when it dies then this is a great way to restart after a minion upgrade. CLI example:: >$ salt minion[12] minion.kill ...
java
@Override public boolean isOn(Date date) { synchronized(calendar) { calendar.setTime(date); int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTime(computeInYear(calendar.getTime(), calendar)); return calendar.get(Calendar.DAY_OF_YEAR) == da...
python
def range_min(self, i, k): """:returns: min{ t[i], t[i + 1], ..., t[k - 1]} :complexity: O(log len(t)) """ return self._range_min(1, 0, self.N, i, k)
python
def as_XYZ100_w(whitepoint): """A convenience function for getting whitepoints. ``whitepoint`` can be either a string naming a standard illuminant (see :func:`standard_illuminant_XYZ100`), or else a whitepoint given explicitly as an array-like of XYZ values. We internally call this function anywhe...
python
def aes_decrypt(value, secret, block_size=AES.block_size): """ AES decrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES decrypted @value .. from vital.security import aes_encrypt, aes_decrypt ae...
java
public static Money total(Iterable<Money> monies) { MoneyUtils.checkNotNull(monies, "Money iterator must not be null"); Iterator<Money> it = monies.iterator(); if (it.hasNext() == false) { throw new IllegalArgumentException("Money iterator must not be empty"); } ...
python
def _save_token_on_disk(self): """Helper function that saves the token on disk""" token = self._token.copy() # Client secret is needed for token refreshing and isn't returned # as a pared of OAuth token by default token.update(client_secret=self._client_secret) with cod...
java
private void rewriteCall(Node getprop, String newMethodName) { checkArgument(getprop.isGetProp(), getprop); Node call = getprop.getParent(); checkArgument(call.isCall(), call); Node receiver = getprop.getFirstChild(); // This rewriting does not exactly preserve order of operations; the newly insert...
java
public static CommerceDiscountRel fetchByCD_CN_Last( long commerceDiscountId, long classNameId, OrderByComparator<CommerceDiscountRel> orderByComparator) { return getPersistence() .fetchByCD_CN_Last(commerceDiscountId, classNameId, orderByComparator); }
java
private boolean countClassAccess(final int classAtStackIndex) { String calledClass; try { if (stack.getStackDepth() > classAtStackIndex) { OpcodeStack.Item itm = stack.getStackItem(classAtStackIndex); JavaClass cls = itm.getJavaClass(); if (cl...
python
def from_bson_voronoi_list(bson_nb_voro_list, structure): """ Returns the voronoi_list needed for the VoronoiContainer object from a bson-encoded voronoi_list (composed of vlist and bson_nb_voro_list). :param vlist: List of voronoi objects :param bson_nb_voro_list: List of periodic sites involved in...
java
public Range<T> leftHalfOpen(T lower, T upper) { return new DenseRange<T>(sequencer, comparator, Endpoint.Exclude, lower, Optional.of(upper), Endpoint.Include); }
python
def removeContainer(tag): '''Check if a container with a given tag exists. Kill it if it exists. No extra side effects. Handles and reraises TypeError, and APIError exceptions. ''' container = getContainerByTag(tag) if container: # Build an Image using the dockerfile in the path ...
java
public OperationStatus updatePhraseList(UUID appId, String versionId, int phraselistId, UpdatePhraseListOptionalParameter updatePhraseListOptionalParameter) { return updatePhraseListWithServiceResponseAsync(appId, versionId, phraselistId, updatePhraseListOptionalParameter).toBlocking().single().body(); }
java
public static BitSet getBitSet(IAtomContainer atomContainer) { BitSet bitSet; int size = atomContainer.getBondCount(); if (size != 0) { bitSet = new BitSet(size); for (int i = 0; i < size; i++) { bitSet.set(i); } } else { b...
java
@Override protected void preparePaintComponent(final Request request) { super.preparePaintComponent(request); if (!isInitialised()) { // Needs to be set per user as the model holds the current page index and total row per user. ExampleScrollableModel model = new ExampleScrollableModel(table, new String[...
java
public static <T> Specification<T> not(Specification<T> proposition) { return new NotSpecification<T>(proposition); }
java
private int readChecksumChunk(byte b[], int off, int len) throws IOException { // invalidate buffer count = pos = 0; int read = 0; boolean retry = true; int retriesLeft = numOfRetries; do { retriesLeft--; try { read = readChunk(chunkPos, b, off, len, checksum);...
java
public void statementErrorOccurred(StatementEvent event) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(this, tc, "statementErrorOccurred", "Notification of a fatal statement error received from the JDBC...
java
public Object getFormatFor() { Transformer mapFunction = new Transformer() { public Object transform(Object param) { if (m_functionBean == null) { return new CmsDynamicFunctionFormatWrapper(m_cms, null); } int width = -1...
python
def _request_callback(self, request_id): """Construct a request callback for the given request ID.""" def callback(future): # Remove the future from the client requests map self._client_request_futures.pop(request_id, None) if future.cancelled(): futu...
java
@Override public List<ComponentType> children() { synchronized (this) { List<ComponentType> children = new ArrayList<ComponentType>(); for (ComponentVertex child : this.children) { children.add(child.component()); } return Collections.unmodifia...
java
public void updatePoolProperties(String poolId, StartTask startTask, Collection<CertificateReference> certificateReferences, Collection<ApplicationPackageReference> applicationPackageReferences, Collection<MetadataItem> metadata, Iterable<BatchClientBehavior> additionalBehaviors) thr...
python
def ob_is_tty(ob): """ checks if an object (like a file-like object) is a tty. """ fileno = get_fileno(ob) is_tty = False if fileno: is_tty = os.isatty(fileno) return is_tty
python
def sendHeartbeat(self): """ Posts the current state to the server. :param serverURL: the URL to ping. :return: """ for name, md in self.cfg.recordingDevices.items(): try: data = marshal(md, recordingDeviceFields) data['serviceU...
java
public static <T extends Comparable<? super T>> @NonNull List<T> orderedTopologicalSort(final @NonNull Graph<T> graph) { return topologicalSort(graph, SortType.comparable()); }
python
def get_invalid_txn_info(self, batch_id): """Fetches the id of the Transaction that failed within a particular Batch, as well as any error message or other data about the failure. Args: batch_id (str): The id of the Batch containing an invalid txn Returns: list ...
java
public WebSocketExtension setParameter(String key, String value) { // Check the validity of the key. if (Token.isValid(key) == false) { // The key is not a valid token. throw new IllegalArgumentException("'key' is not a valid token."); } // If the val...
java
public final void changeStartDate(LocalDate date, boolean keepDuration) { requireNonNull(date); Interval interval = getInterval(); LocalDateTime newStartDateTime = getStartAsLocalDateTime().with(date); LocalDateTime endDateTime = getEndAsLocalDateTime(); if (keepDuration) { ...
java
protected void showFinishing(LaJobRuntime runtime, long before, Throwable cause) { final String msg = buildFinishingMsg(runtime, before, cause); // also no use enabled if (noticeLogHook != null) { noticeLogHook.hookFinishing(runtime, msg, OptionalThing.ofNullable(cause, () -> { ...
python
def get_logging_session_for_log(self, log_id, proxy): """Gets the ``OsidSession`` associated with the logging service for the given log. arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LoggingSession) - a ``LoggingSe...
java
protected void doForwardViterbi(Node[][] lattice, Instance carrier) { for (int l = 1; l < lattice.length; l++) { for (int c = 0; c < lattice[l].length; c++) { if (lattice[l][c] == null) continue; float bestScore = Float.NEGATIVE_INFINITY; int bestPath = -1; for (int p = 0; p < lattice...
python
def makepath(s, as_file=False): """Make a path from a string Expand out any variables, home squiggles, and normalise it See also http://stackoverflow.com/questions/26403972 """ if s is None: return None result = FilePath(s) if (os.path.isfile(s) or as_file) else DirectPath(s) return...
java
public static void insertFromDevState(final DevState devStateValue, final DeviceAttribute deviceAttributeWritten) throws DevFailed { final Integer integerValue = Integer.valueOf(devStateValue.value()); switch (deviceAttributeWritten.getType()) { case TangoConst.Tango_DEV_SHORT: deviceAttributeWritten.inse...
java
@SuppressWarnings({ "unchecked" }) public static <V> V put(Map<? super TypedIdKey<V>, ? super V> map, Serializable id, V value) { map.put(new TypedIdKey<V>((Class<V>) value.getClass(), id), value); return value; }
java
public void buildInterfaceSummary(XMLNode node, Content packageSummaryContentTree) { String interfaceTableSummary = configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Interface_Summary"), configuration.getText("doclet.interfaces"));...
python
def build_config(ctx, target, config_path, c, extra_path, ignore, verbose, silent, debug): """ Creates a LintConfig object based on a set of commandline parameters. """ config_builder = LintConfigBuilder() try: # Config precedence: # First, load default config or config from configfile ...
java
@Override @SuppressWarnings("unchecked") protected T convert(JsonNode data) { // The (T) cast prevents the commandline javac from choking "no unique maximal instance" return (T)this.mapper.convertValue(data, this.resultType); }
python
def parse_brome_config_from_browser_config(browser_config): """Parse the browser config and look for brome specific config Args: browser_config (dict) """ config = {} brome_keys = [key for key in browser_config if key.find(':') != -1] for brome_key in brome_keys: section, opt...
java
public String getInitParameter(String param) { if (_initParams==null) return null; return (String)_initParams.get(param); }
python
def add_transitions_from_selected_state_to_parent(): """ Generates the default success transition of a state to its parent success port :return: """ task_string = "create transition" sub_task_string = "to parent state" selected_state_m, msg = get_selected_single_state_model_and_check_for_its_p...
java
public static <T> Iterator<T> singleIterator(T t) { Require.nonNull(t, "t"); return Collections.singleton(t).iterator(); }
python
def _add_url_routes(self, app): """Configure a list of URLs to route to their corresponding view method..""" # Because methods contain an extra ``self`` parameter, URL routes are mapped # to stub functions, which simply call the corresponding method. # For testing purposes, we map all ...
python
def tree_render(request, upy_context, vars_dictionary): """ It renders template defined in upy_context's page passed in arguments """ page = upy_context['PAGE'] return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request))
java
public NotificationChain basicSetInterruptible(Parameter newInterruptible, NotificationChain msgs) { Parameter oldInterruptible = interruptible; interruptible = newInterruptible; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, BpsimPackage.PRIORITY_...
java
@Override public EnableVolumeIOResult enableVolumeIO(EnableVolumeIORequest request) { request = beforeClientExecution(request); return executeEnableVolumeIO(request); }
java
@Override public Request<DeleteRouteTableRequest> getDryRunRequest() { Request<DeleteRouteTableRequest> request = new DeleteRouteTableRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
java
public void record (ChatChannel channel, String source, UserMessage msg, Name ...usernames) { // fill in the message's time stamp if necessary if (msg.timestamp == 0L) { msg.timestamp = System.currentTimeMillis(); } Entry entry = new Entry(channel, source, msg); ...
python
def build_swagger_spec(user, repo, sha, serverName): """Build grlc specification for the given github user / repo in swagger format """ if user and repo: # Init provenance recording prov_g = grlcPROV(user, repo) else: prov_g = None swag = swagger.get_blank_spec() swag['host'...
python
def run(self): '''compile the JS, then run superclass implementation''' if subprocess.call(['npm', '--version']) != 0: raise RuntimeError('npm is required to build the HTML renderer.') self.check_call(['npm', 'install'], cwd=HTML_RENDERER_DIR) self.check_call(['npm', 'run',...
java
public static SipMessage frame(final Buffer buffer) throws IOException { if (true) return frame2(buffer); if (!couldBeSipMessage(buffer)) { throw new SipParseException(0, "Cannot be a SIP message because is doesnt start with \"SIP\" " + "(for responses) or a ...
java
@Override public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) { return cpdAvailabilityEstimatePersistence.findWithDynamicQuery(dynamicQuery); }
java
@Override public void addTargetORBInitProperties(Properties initProperties, Map<String, Object> configProps, List<IIOPEndpoint> endpoints, Map<String, Object> extraProperties) { StringBuilder sb = new StringBuilder(); Map<String, List<TransportAddress>> addrMap = extractTransportAddresses(configProp...
python
def get_model_args_kwargs(self): """ Inspect the model (or view in the case of no model) and return the args and kwargs. This functin is necessary because argspec returns in a silly format by default. """ source = self.get_model() if not source: return...
python
def Beta(alpha: vertex_constructor_param_types, beta: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ One to one constructor for mapping some tensorShape of alpha and beta to a matching tensorShaped Beta. :param alpha: the alpha of the Beta with either the same tensorShape...