language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _get_args(args): """Argparse logic lives here. returns: parsed arguments. """ parser = argparse.ArgumentParser( description='A tool to extract features into a simple format.', formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument('--no-cache', action=...
java
@Override public Response deleteApplication( String applicationName ) { this.logger.fine( "Request: delete application " + applicationName + "." ); Response result = Response.ok().build(); try { ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( applicationName ); if( ma ...
python
def save(self, *args, **kwargs): """ **uid**: :code:`cycle:{year}` """ self.slug = slugify(self.name) self.uid = 'cycle:{}'.format(self.slug) super(ElectionCycle, self).save(*args, **kwargs)
python
def notify(self, msg, color='green', notify='true', message_format='text'): """Send notification to specified HipChat room""" self.message_dict = { 'message': msg, 'color': color, 'notify': notify, 'message_format': message_format, } if not...
java
public boolean isSet(String propName) { if (propName.equals("uniqueId")) { return isSetUniqueId(); } if (propName.equals("uniqueName")) { return isSetUniqueName(); } if (propName.equals("externalId")) { return isSetExternalId(); } ...
python
def try_fields(cls, *names) -> t.Optional[t.Any]: """Return first existing of given class field names.""" for name in names: if hasattr(cls, name): return getattr(cls, name) raise AttributeError((cls, names))
java
public FluentMatchingR<T, R> get(Supplier<R> supplier) { return get(fluentMatchingR, supplier); }
python
def val_to_fp(self, sort, signed=True, rm=None): """ Interpret this bitvector as an integer, and return the floating-point representation of that integer. :param sort: The sort of floating point value to return :param signed: Optional: whether this value is a signed integer ...
python
def format_checksum(checksum_pyxb): """Create string representation of a PyXB Checksum object. Args: PyXB Checksum object Returns: str : Combined hexadecimal value and algorithm name. """ return '{}/{}'.format( checksum_pyxb.algorithm.upper().replace('-', ''), checksum_pyxb.va...
python
def getScriptNames(self): """This function returns the list of layouts for the current db.""" if self._db == '': raise FMError, 'No database was selected' request = [] request.append(uu({'-db': self._db })) request.append(uu({'-scriptnames': '' })) result = self._doRequest(request) result = FMResult...
python
def mark_topic_read(self, topic, user): """ Marks a topic as read. """ if not user.is_authenticated: return forum = topic.forum try: forum_track = ForumReadTrack.objects.get(forum=forum, user=user) except ForumReadTrack.DoesNotExist: forum_tra...
python
def create(self, name, description=None, units=None, agg_method="priority_fill", overwrite=False): """ Create, or get if exists, a Symbol. Parameters ---------- name : str A symbol's name is a primary key, used across the Trump ORM....
python
def create_filters(predicate_params, predicate_factory): """Create filter functions from a list of string parameters. :param predicate_params: A list of predicate_param arguments as in `create_filter`. :param predicate_factory: As in `create_filter`. """ filters = [] for predicate_param in predicate_params...
python
def append(self, value): """Add an item to the end of the list.""" return super(Collection, self).append( self._ensure_value_is_valid(value))
python
def serialise(self, default_endianness=None): """ Serialise a message, without including any framing. :param default_endianness: The default endianness, unless overridden by the fields or class metadata. Should usually be left at ``None``. Otherwise, use ``'<'...
python
def ceil(self): """Round `x` and `y` up to integers.""" return Point(int(math.ceil(self.x)), int(math.ceil(self.y)))
python
def prepare_create_transaction(*, signers, recipients=None, asset=None, metadata=None): """Prepares a ``"CREATE"`` transaction payload, ready to be fulfilled. Args: signers (:...
python
def secret_absent(name, namespace='default', **kwargs): ''' Ensures that the named secret is absent from the given namespace. name The name of the secret namespace The name of the namespace ''' ret = {'name': name, 'changes': {}, 'result': False, ...
java
private void processPredecessors() throws SQLException { List<Row> rows = getRows("select * from link where projid=? order by linkid", m_projectID); List<Row> completedSections = getRows("select * from task_completed_section where projid=?", m_projectID); m_reader.processPredecessors(rows, complete...
python
def open(self): """Open a comm to the frontend if one isn't already open.""" if self.comm is None: state, buffer_paths, buffers = _remove_buffers(self.get_state()) args = dict(target_name='jupyter.widget', data={'state': state, 'buffer_paths': buffer_path...
java
public static String calcMoisture33Kpa(String slsnd, String slcly, String omPct) { String ret; if ((slsnd = checkPctVal(slsnd)) == null || (slcly = checkPctVal(slcly)) == null || (omPct = checkPctVal(omPct)) == null) { LOG.error("Invalid input parameters for ...
python
def get_templates_per_page(self, per_page=1000, page=1, params=None): """ Get templates per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :param params: Search parameters. Default: {} :return: list """ ...
java
public MessageDialog build() { MessageDialog messageDialog = new MessageDialog( title, text, buttons.toArray(new MessageDialogButton[buttons.size()])); messageDialog.setHints(extraWindowHints); return messageDialog; }
python
def replace(self, main_type=None, sub_type=None, params=None): """ Return a new MimeType with new values for the specified fields. :param str main_type: The new main type. :param str sub_type: The new sub type. :param dict params: The new parameters. :return: A new instan...
python
def padded_variance_explained(predictions, labels, weights_fn=common_layers.weights_all): """Explained variance, also known as R^2.""" predictions, labels = common_layers.pad_with_zeros(predictions, labels) targets = labels weights = weights_fn(targets...
java
public static void handleReflectionException(Exception ex) { if (ex instanceof NoSuchMethodException) { throw new IllegalStateException("Method not found: " + ex.getMessage()); } if (ex instanceof IllegalAccessException) { throw new IllegalStateException("Could not access...
python
def const(f): ''' const(f) yields f.c if f is a constant potential function; if f is a constant, it yields f or the equivalent numpy array object; if f is a potential function that is not const, or is not a valid potential function constant, yields None. ''' if is_const_potential(f): return ...
java
@MemberOrder(sequence = "40") public StringInterpolatorDemoToDoItem newToDo( @ParameterLayout(named = "Description") @Parameter(regexPattern = "\\w[@&:\\-\\,\\.\\+ \\w]*") final String description, @ParameterLayout(named = "Documentation page") final String documentat...
python
def insert(self, index, value): """ Inserts @value before @index in the list. @index: list index to insert @value before @value: item to insert @where: whether to insert BEFORE|AFTER @refvalue -> #int new length of the list on success or -1 if refvalue is not ...
java
public void generateDummyCoding() throws NumberFormatException, DDFException { DummyCoding dc = new DummyCoding(); // initialize array xCols which is just 0, 1, 2 .. dc.xCols = new int[this.getColumns().size()]; int i = 0; while (i < dc.xCols.length) { dc.xCols[i] = i; i += 1; ...
java
public static final String getString(int index) { StringBuffer buf = new StringBuffer(); // lower than 0 ? Add minus if (index < 0) { buf.append('-'); index = -index; } // greater than 3000 if (index > 3000) { buf.append('|'); buf.append(getString(index / 1000)); buf.append('|'); // rema...
python
def get_activity(self, id_num): """Return the activity with the given id. Note that this contains more detailed information than returned by `get_activities`. """ url = self._build_url('my', 'activities', id_num) return self._json(url)
java
@Benchmark public Object blockingUnary() throws Exception { return ClientCalls.blockingUnaryCall( channels[0].newCall(unaryMethod, CallOptions.DEFAULT), Unpooled.EMPTY_BUFFER); }
python
def tai_timestamp(): """Return current TAI timestamp.""" timestamp = time.time() date = datetime.utcfromtimestamp(timestamp) if date.year < 1972: return timestamp offset = 10 + timestamp leap_seconds = [ (1972, 1, 1), (1972, 7, 1), (1973, 1, 1), (1974, 1, ...
python
def APFSContainerPathSpecGetVolumeIndex(path_spec): """Retrieves the volume index from the path specification. Args: path_spec (PathSpec): path specification. Returns: int: volume index or None if the index cannot be determined. """ volume_index = getattr(path_spec, 'volume_index', None) if volume...
python
def _python3_record_factory(*args, **kwargs): """Python 3 approach to custom logging, using `logging.getLogRecord(...)` Inspireb by: https://docs.python.org/3/howto/logging-cookbook.html#customizing-logrecord :return: A log record augmented with the values required by LOG_FORMAT, as per `_update_record(.....
python
def as_svg_data_uri(matrix, version, scale=1, border=None, color='#000', background=None, xmldecl=False, svgns=True, title=None, desc=None, svgid=None, svgclass='segno', lineclass='qrline', omitsize=False, unit='', encoding='utf-8', svgvers...
python
def _are_nearby_parallel_boxes(self, b1, b2): "Are two boxes nearby, parallel, and similar in width?" if not self._are_aligned_angles(b1.angle, b2.angle): return False # Otherwise pick the smaller angle and see whether the two boxes are close according to the "up" direction wrt that ...
java
@Override public void addSecurityConstraintMappings( final SecurityConstraintMappingModel model) { final ServletContextHandler context = server.getOrCreateContext(model); final SecurityHandler securityHandler = context.getSecurityHandler(); if (securityHandler == null) { throw new IllegalStateException( ...
java
public final Tuple2<Tuple13<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>, Tuple2<T14, T15>> split13() { return new Tuple2<>(limit13(), skip13()); }
java
public static <K, VV, Message, EV> ScatterGatherIteration<K, VV, Message, EV> withEdges( DataSet<Edge<K, EV>> edgesWithValue, ScatterFunction<K, VV, Message, EV> sf, GatherFunction<K, VV, Message> gf, int maximumNumberOfIterations) { return new ScatterGatherIteration<>(sf, gf, edgesWithValue, maximumNumberOfIt...
java
@VisibleForTesting static String makeTargetStringForDirectAddress(SocketAddress address) { try { return new URI(DIRECT_ADDRESS_SCHEME, "", "/" + address, null).toString(); } catch (URISyntaxException e) { // It should not happen. throw new RuntimeException(e); } }
python
def datetime_handler(x): """ Allow serializing datetime objects to JSON """ if isinstance(x, datetime.datetime) or isinstance(x, datetime.date): return x.isoformat() raise TypeError("Unknown type")
python
def defaultannotator(self, annotationtype, set=None): """Obtain the default annotator for the specified annotation type and set. Arguments: annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or...
java
public Schema loadSchema( Connection pConnection, Diagram pRootDiagram ) throws SQLException { Schema lSchema = new Schema(); String lSql = "select table_name from user_tables"; CallableStatement lTableStatement = pConnection.prepareCall( lSql ); ResultSet lTableResultSet = lTableStatement.executeQu...
python
def taf(wxdata: TafData, units: Units) -> TafTrans: """ Translate the results of taf.parse Keys: Forecast, Min-Temp, Max-Temp Forecast keys: Wind, Visibility, Clouds, Altimeter, Wind-Shear, Turbulance, Icing, Other """ translations = {'forecast': []} # type: ignore for line in wxdata.fore...
python
def setTransform(self, T): """ Transform actor position and orientation wrt to its polygonal mesh, which remains unmodified. """ if isinstance(T, vtk.vtkMatrix4x4): self.SetUserMatrix(T) else: try: self.SetUserTransform(T) ...
java
public static Date parseDate(String dateValue, Collection<String> dateFormats, Date startDate) throws ParseException { if (dateValue == null) { throw new IllegalArgumentException("dateValue is null"); } if (dateFormats == null) { dateFormats = DEFAULT_HTTP_CLIENT_PAT...
python
def customize_compiler_for_nvcc(self): '''This is a verbatim copy of the NVCC compiler extension from https://github.com/rmcgibbo/npcuda-example ''' self.src_extensions.append('.cu') default_compiler_so = self.compiler_so super = self._compile def _compile(obj, src, ext, cc_args, extra_post...
java
private boolean handleClosedLedgers(List<Write> writes) { if (writes.size() == 0 || !writes.get(0).getWriteLedger().ledger.isClosed()) { // Nothing to do. We only need to check the first write since, if a Write failed with LedgerClosed, then the // first write must have failed for that r...
python
def _get_abstract_layer_name(self): """ Looks for the name of abstracted layer. Usually these layers appears when model is stacked. :return: List of abstracted layers """ abstract_layers = [] for layer in self.model.layers: if 'layers' in layer.get_config(): abstract_layers.app...
java
public UpdateMethodResponseResult withResponseParameters(java.util.Map<String, Boolean> responseParameters) { setResponseParameters(responseParameters); return this; }
java
public void marshall(DetectKeyPhrasesRequest detectKeyPhrasesRequest, ProtocolMarshaller protocolMarshaller) { if (detectKeyPhrasesRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(detectKeyP...
python
def NameImport(package, as_name=None, prefix=None): """ Accepts a package (Name node), name to import it as (string), and optional prefix and returns a node: import <package> [as <as_name>] """ if prefix is None: prefix = u"" children = [Name(u"import", prefix=prefix), package] i...
python
def check_new_target_system(self): '''handle a new target_system''' sysid = self.get_sysid() if sysid in self.pstate: return self.add_new_target_system(sysid)
java
public void initCircuitBreakerRegistry(CircuitBreakerRegistry circuitBreakerRegistry) { circuitBreakerProperties.getBackends().forEach( (name, properties) -> circuitBreakerRegistry.circuitBreaker(name, circuitBreakerProperties.createCircuitBreakerConfig(properties)) ); }
java
private <IPW extends IndentingPrintWriter> IPW writeNameTo(IPW output) { output.append(name.isEmpty() ? "unnamed" : name).whitespace(); return output; }
java
public static Region[] getExcluding(Region... excludedRegions) { Region[] regions = Regions.getRegions(); if (excludedRegions == null || excludedRegions.length == 0) { return regions; } excludedRegions = removeDuplicates(excludedRegions); int excludedLength = 0; ...
python
def wnreld(a, op, b): """ Compare two double precision windows. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnreld_c.html :param a: First window. :type a: spiceypy.utils.support_types.SpiceCell :param op: Comparison operator. :type op: str :param b: Second window. :t...
python
def template_exception_handler(fn, error_context, filename=None): """Calls the given function, attempting to catch any template-related errors, and converts the error to a Statik TemplateError instance. Returns the result returned by the function itself.""" error_message = None if filename: ...
java
public DenseLU factor(DenseMatrix A) { singular = false; intW info = new intW(0); LAPACK.getInstance().dgetrf(A.numRows(), A.numColumns(), A.getData(), Matrices.ld(A.numRows()), piv, info); if (info.val > 0) singular = true; else if (info.val < 0) ...
python
def present(name, zone, ttl, data, rdtype='A', **kwargs): ''' Ensures that the named DNS record is present with the given ttl. name The host portion of the DNS record, e.g., 'webserver'. Name and zone are concatenated when the entry is created unless name includes a trailing dot, so...
python
def make_error_response(self, validation_error, expose_errors): """ Return an appropriate ``HttpResponse`` on authentication failure. In case of an error, the specification only details the inclusion of the ``WWW-Authenticate`` header. Additionally, when allowed by the specification, we respond with er...
java
public static void loadSeg(String path) throws LoadModelException { if(seg==null) { String file = path+segModel; seg = new CWSTagger(file); seg.setEnFilter(isEnFilter); } }
python
def cache_file(source): ''' Wrapper for cp.cache_file which raises an error if the file was unable to be cached. CLI Example: .. code-block:: bash salt myminion container_resource.cache_file salt://foo/bar/baz.txt ''' try: # Don't just use cp.cache_file for this. Docker ha...
java
public String getResultString() throws TransformerException { return withExceptionHandling(new Trans<String>() { public String transform() { return transformation.transformToString(); } }); }
java
public static void write( String content, Writer writer ) throws IOException { CheckArg.isNotNull(writer, "destination writer"); boolean error = false; try { if (content != null) { writer.write(content); } } catch (IOE...
java
protected void resumeFaxJob(HylaFaxJob faxJob,HylaFAXClient client) throws Exception { //get job Job job=faxJob.getHylaFaxJob(); //get job ID long faxJobID=job.getId(); //resume job client.retry(faxJobID); }
java
public static long max(LongArrayND array) { return array.stream().parallel().reduce( Long.MIN_VALUE, Math::max); }
java
private static Field getField(final Class cls, final String fieldName, boolean declared) { $.checkNotEmpty(fieldName); List<Field> fields = getFieldsList(cls, declared); for (int i = 0; i < fields.size(); i++) { if (fieldName.equals(fields.get(i).getName())) { return fields.get(i); } } retur...
java
public static void tagsToFilters(final Map<String, String> tags, final List<TagVFilter> filters) { mapToFilters(tags, filters, true); }
java
public static void writeField(final Field field, final Object target, final Object value) throws IllegalAccessException { writeField(field, target, value, false); }
python
def monkhorst_automatic(cls, structure, ngkpt, use_symmetries=True, use_time_reversal=True, chksymbreak=None, comment=None): """ Convenient static constructor for an automatic Monkhorst-Pack mesh. Args: structure: :class:`Structure` object. ng...
java
public static void requireAccess (ClientObject clobj, Permission perm, Object context) throws InvocationException { String errmsg = clobj.checkAccess(perm, context); if (errmsg != null) { throw new InvocationException(errmsg); } }
java
public void setFilters(java.util.Collection<DocumentKeyValuesFilter> filters) { if (filters == null) { this.filters = null; return; } this.filters = new com.amazonaws.internal.SdkInternalList<DocumentKeyValuesFilter>(filters); }
java
@SafeVarargs public static <T> SimplePageable<T> of(T... array) { return new SimplePageable<>(Arrays.asList(nullSafeArray(array))); }
python
def InsertArg(self, string="", **_): """Insert an arg to the current expression.""" if self.state == "LIST_ARG": self.list_args.append(string) elif self.current_expression.AddArg(string): # This expression is complete self.stack.append(self.current_expression) self.current_expression...
python
def delete(self, block_type, block_num): """ Deletes a block :param block_type: Type of block :param block_num: Bloc number """ logger.info("deleting block") blocktype = snap7.snap7types.block_types[block_type] result = self.library.Cli_Delete(sel...
java
public java.util.List<JobFlowDetail> getJobFlows() { if (jobFlows == null) { jobFlows = new com.amazonaws.internal.SdkInternalList<JobFlowDetail>(); } return jobFlows; }
java
public static void isTrue(final boolean expression, final String message, final long value) { if (!expression) { throw new IllegalArgumentException(StringUtils.simpleFormat(message, Long.valueOf(value))); } }
java
private static SSLException asSSLException(Exception e) throws SSLException { if (e instanceof SSLException) return (SSLException) e; return new SSLException(e.getMessage(), e); }
python
def get_flexports_output_flexport_list_port_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_flexports = ET.Element("get_flexports") config = get_flexports output = ET.SubElement(get_flexports, "output") flexport_list = ET.SubElemen...
python
def send(self, cmd): """ Send a command to the bridge. :param cmd: List of command bytes. """ self._bridge.send(cmd, wait=self.wait, reps=self.reps)
python
def get_member(self, username, api=None): """ Return specified automation member :param username: Member username :param api: sevenbridges Api instance. :return: AutomationMember object """ member = Transform.to_automation_member(username) api = api or sel...
java
private SessionData load(InputStream is, String expectedId) throws Exception { try { DataInputStream di = new DataInputStream(is); String id = di.readUTF(); // the actual id from inside the file long created = di.readLong(); long accessed = di.readLong(); ...
java
public static <ReqT, RespT> ServerCallHandler<ReqT, RespT> asyncBidiStreamingCall( BidiStreamingMethod<ReqT, RespT> method) { return asyncStreamingRequestCall(method); }
java
@TargetApi(Build.VERSION_CODES.FROYO) public static boolean hasLocationFeature(Context context) { return hasLocationFeature(context.getPackageManager()); }
python
def to_string(self, verbose=0): """String representation.""" lines = [] app = lines.append for i, cycle in enumerate(self): app("") app("RELAXATION STEP: %d" % (i + 1)) app(cycle.to_string(verbose=verbose)) return "\n".join(lines)
python
def _detect(self): """ Detect uninitialized state variables Recursively visit the calls Returns: dict: [contract name] = set(state variable uninitialized) """ results = [] for c in self.slither.contracts_derived: ret = self.detect_uninitialized(c)...
python
def update(self): """ Updates the todo list according to the todos in the view associated with this list. """ old_focus_position = self.todolist.focus id_length = max_id_length(self.view.todolist.count()) del self.todolist[:] for group, todos in self.vie...
java
public static void setJVMProxy(String host, String port) { System.setProperty(JVM_PROXY_HOST_PROPERTY, host); System.setProperty(JVM_PROXY_PORT_PROPERTY, port); }
java
@Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Span setStatus(Data data) { data.spanToSet.setStatus(STATUS_OK); return data.spanToSet; }
java
public static void addFlowContext(final FlowContext flowContext) { if (null == flowContext) { clearFlowcontext(); return; } FLOW_CONTEXT_THREAD_LOCAL.set(flowContext); MDC.put("flowCtxt", flowContext.toString()); }
java
public static ListenableFuture<SnapshotCompletionInterest.SnapshotCompletionEvent> watchSnapshot(final String nonce) { final SettableFuture<SnapshotCompletionInterest.SnapshotCompletionEvent> result = SettableFuture.create(); SnapshotCompletionInterest interest = new SnapshotComplet...
python
def get_series(self, series): """ Returns a census series API handler. """ if series == "acs1": return self.census.acs1dp elif series == "acs5": return self.census.acs5 elif series == "sf1": return self.census.sf1 elif series ==...
java
protected Statement withAfterClasses(Statement statement) { List<FrameworkMethod> afters = testClass .getAnnotatedMethods(AfterClass.class); return afters.isEmpty() ? statement : new RunAfters(statement, afters, null); }
python
def alignVec_quat(vec): """Returns a unit quaternion that will align vec with the z-axis""" alpha = np.arctan2(vec[1], vec[0]) beta = np.arccos(vec[2]) gamma = -alpha*vec[2] cb = np.cos(0.5*beta) sb = np.sin(0.5*beta) return np.array([cb*np.cos(0.5*(alpha + gamma)), sb*n...
python
def add_colorbar(self, *args, **kwargs): """DEPRECATED, use `Plot.colorbar` instead """ warnings.warn( "{0}.add_colorbar was renamed {0}.colorbar, this warnings will " "result in an error in the future".format(type(self).__name__), DeprecationWarning) ...
java
public Observable<ManagedInstanceVulnerabilityAssessmentInner> createOrUpdateAsync(String resourceGroupName, String managedInstanceName, ManagedInstanceVulnerabilityAssessmentInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, managedInstanceName, parameters).map(new Func1<Servi...
python
def install(self, release_id): """Install the local artifact into the remote release directory, optionally with a different name than the artifact had locally. If the directory for the given release ID does not exist on the remote system, it will be created. The directory will be create...