language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static DbColumn.Builder dbColumn(String name, DbColumnType type, boolean autoInc) { return new DbColumn.Builder().name(name).type(type).autoInc(autoInc); }
java
public void marshall(ConfigurationAggregator configurationAggregator, ProtocolMarshaller protocolMarshaller) { if (configurationAggregator == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(configurat...
python
def _encoder(self, obj): """ Encode a toc element leaf-node """ return {'__class__': obj.__class__.__name__, 'ident': obj.ident, 'group': obj.group, 'name': obj.name, 'ctype': obj.ctype, 'pytype': obj.pytype, ...
java
@Override public boolean isTransacted() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(this, tc, "isTransacted"); SibTr.exit(this, tc, "isTransacted", Boolean.valueOf(transacted)); } return transacted; }
java
public static QPathEntry parse(String qEntry) throws IllegalNameException, NumberFormatException { int delimIndex = qEntry.lastIndexOf(QPath.PREFIX_DELIMITER); String qnameString = qEntry.substring(0, delimIndex); String indexString = qEntry.substring(delimIndex + 1); InternalQName q...
java
public List<Metric> getAverages(int span) { Map<String,Metric> accum = new LinkedHashMap<>(); int count = span / period; if (count > dataList.size()) count = dataList.size(); for (int i = dataList.size() - count; i < dataList.size(); i++) { MetricData metricData =...
java
public void visitApply(JCMethodInvocation tree) { if (TreeInfo.name(tree.meth) == names._super) { Symbol constructor = TreeInfo.symbol(tree.meth); ClassSymbol c = (ClassSymbol)constructor.owner; if (c.hasOuterInstance() && !tree.meth.hasTag...
python
def DESCRIBE(self): """Request description of what services RTSP server make available.""" message = "DESCRIBE " + self.session.url + " RTSP/1.0\r\n" message += self.sequence message += self.authentication message += self.user_agent message += "Accept: application/sdp\r\n...
java
public static Object convertClob(Connection conn, InputStream input) throws SQLException { return convertClob(conn, toByteArray(input)); }
java
@JsonCreator public static HostAddress fromString(String hostPortString) { requireNonNull(hostPortString, "hostPortString is null"); String host; String portString = null; if (hostPortString.startsWith("[")) { // Parse a bracketed host, typically an IPv6 literal. ...
java
public boolean removeAll(final IntHashSet coll) { boolean acc = false; for (final int value : coll.values) { if (value != MISSING_VALUE) { acc |= remove(value); } } if (coll.containsMissingValue) { acc ...
python
def parse_payment_result(self, xml): """解析微信支付结果通知""" try: data = xmltodict.parse(xml) except (xmltodict.ParsingInterrupted, ExpatError): raise InvalidSignatureException() if not data or 'xml' not in data: raise InvalidSignatureException() da...
python
def interrupt(self, threadId=None): """ Interrupts the thread at the given id. :param threadId | <int> || None """ back = self.backend() if back: back.interrupt(threadId)
python
def make_mon_removed_dir(path, file_name): """ move old monitor data """ try: os.makedirs('/var/lib/ceph/mon-removed') except OSError as e: if e.errno != errno.EEXIST: raise shutil.move(path, os.path.join('/var/lib/ceph/mon-removed/', file_name))
java
public static void writeHash(File file, HashType hashType) throws IOException { SparkeyWriter writer = append(file); writer.writeHash(hashType); writer.close(); }
java
public static double[] randomDoubleArray(int len, Random r) { final double[] ret = new double[len]; for(int i = 0; i < len; i++) { ret[i] = r.nextDouble(); } return ret; }
python
def create(image, name=None, start=False, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, client_timeout=salt.utils.docker.CLIENT_TIMEOUT, **kwargs): ''' Create a new container image Image from which ...
python
def parse_keytab(keytab): """Read the contents of a KRB5 keytab file, returning a list of credentials listed within Parameters ---------- keytab : `str` path to keytab file Returns ------- creds : `list` of `tuple` the (unique) list of `(username, realm, kvno)` as read ...
java
public ServerBuilder tls( File keyCertChainFile, File keyFile, @Nullable String keyPassword) throws SSLException { defaultVirtualHostBuilderUpdated(); defaultVirtualHostBuilder.tls(keyCertChainFile, keyFile, keyPassword); return this; }
java
@Override public void clearCache() { entityCache.clearCache(CommerceCountryImpl.class); finderCache.clearCache(FINDER_CLASS_NAME_ENTITY); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION); }
java
public DoubleIntIndex getTransactionIDList() { writeLock.lock(); try { DoubleIntIndex lookup = new DoubleIntIndex(10, false); lookup.setKeysSearchTarget(); Iterator it = this.rowActionMap.keySet().iterator(); for (; it.hasNext(); ) { l...
python
def _load_data(self, band): """In-flight effective areas for the Swift UVOT, as obtained from the CALDB. See Breeveld+ 2011. XXX: confirm that these are equal-energy, not quantum-efficiency. """ d = bandpass_data_fits('sw' + self._band_map[band] + '_20041120v106.arf')[1].data ...
python
def skips(self, user): """ Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__. """ return self._get(self._build_url(self.endpoint.skips(id=user)))
python
def var_replace(self, text): """Replaces all instances of @VAR with their values in the specified text. """ result = text for var in self._vardict: result = result.replace("@{}".format(var), self._vardict[var]) return result
java
public int pkHash(DbMapping dbMapping, Map<String, Object> d) { return pkHash(dbMapping, d, null); }
java
protected void storeAdminObject(AdminObject ao, XMLStreamWriter writer) throws Exception { writer.writeStartElement(CommonXML.ELEMENT_ADMIN_OBJECT); if (ao.getClassName() != null) writer.writeAttribute(CommonXML.ATTRIBUTE_CLASS_NAME, ao.getValue(CommonXML.ATTRIBUT...
python
def remover(self, id_logicalenvironment): """Remove Logical Environment from by the identifier. :param id_logicalenvironment: Identifier of the Logical Environment. Integer value and greater than zero. :return: None :raise InvalidParameterError: The identifier of Logical Environment i...
java
public java.lang.String getPath() { java.lang.Object ref = path_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValid...
python
def get_all_build_config_set_records(self, id, **kwargs): """ Get all build config set execution records associated with this build config set, returns empty list if none are found This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, ple...
python
def main(): """ NAME quick_hyst.py DESCRIPTION makes plots of hysteresis data SYNTAX quick_hyst.py [command line options] OPTIONS -h prints help message and quits -usr USER: identify user, default is "" -f: specify input file, default is magic_mea...
python
def key_value_contents(use_dict=None, as_class=dict, key_values=()): """Return the contents of an object as a dict.""" if _debug: key_value_contents._debug("key_value_contents use_dict=%r as_class=%r key_values=%r", use_dict, as_class, key_values) # make/extend the dictionary of content if use_dict is ...
python
def use_comparative_objective_view(self): """Pass through to provider ObjectiveLookupSession.use_comparative_objective_view""" self._object_views['objective'] = COMPARATIVE # self._get_provider_session('objective_lookup_session') # To make sure the session is tracked for session in self....
java
private HeaderEntry getEntry(CharSequence name, CharSequence value) { if (length() == 0 || name == null || value == null) { return null; } int h = AsciiString.hashCode(name); int i = index(h); for (HeaderEntry e = headerFields[i]; e != null; e = e.next) { ...
python
def alt_triangle_coordinates(i, j, k): """ Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangules are parallel to the lower axis on the upper side. Parameters ---------- i,j,k: enumeration of the desired triangle Returns ------- A num...
python
def sinh(x): """ Hyperbolic sine """ if isinstance(x, UncertainFunction): mcpts = np.sinh(x._mcpts) return UncertainFunction(mcpts) else: return np.sinh(x)
python
def login(self, broker_name, account_cookie, account=None): """login 登录到交易前置 2018-07-02 在实盘中,登录到交易前置后,需要同步资产状态 Arguments: broker_name {[type]} -- [description] account_cookie {[type]} -- [description] Keyword Arguments: account {[type]} -- [descript...
java
public static boolean isExtender(int ch) { return 0x00B7 == ch || 0x02D0 == ch || 0x02D1 == ch || 0x0387 == ch || 0x0640 == ch || 0x0E46 == ch || 0x0EC6 == ch || 0x3005 == ch || (0x3031 <= ch && ch <= 0x3035) || (0x309D <= ch && ch <= 0x309E) || (0x30FC <= ch && ch <= 0x30FE); }
python
def fillstats(args): """ %prog fillstats genome.fill Build stats on .fill file from GapCloser. """ from jcvi.utils.cbook import SummaryStats, percentage, thousands p = OptionParser(fillstats.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help(...
java
public static double getLPNormP(AbstractMaterializeKNNPreprocessor<?> kNN) { DistanceFunction<?> distanceFunction = kNN.getDistanceQuery().getDistanceFunction(); if(LPNormDistanceFunction.class.isInstance(distanceFunction)) { return ((LPNormDistanceFunction) distanceFunction).getP(); } return Doub...
java
private double factor(int dimension) { return maxima[dimension] > minima[dimension] ? maxima[dimension] - minima[dimension] : maxima[dimension] > 0 ? maxima[dimension] : 1; }
python
def _linux_brdel(br): ''' Internal, deletes the bridge ''' brctl = _tool_path('brctl') return __salt__['cmd.run']('{0} delbr {1}'.format(brctl, br), python_shell=False)
python
async def wait_for_all_empty(self, *queues): """ Wait for multiple queues to be empty at the same time. Require delegate when calling from coroutines running in other containers """ matchers = [m for m in (q.waitForEmpty() for q in queues) if m is not None] while matcher...
java
public MDecimal getMMHg() { MDecimal result = new MDecimal(currentUnit.getConverterTo( MILLIMETER_OF_MERCURY).convert(doubleValue())); logger.trace(MMarker.GETTER, "Converting from {} to millimetres of Mecrcury : {}", currentUnit, result); return result; }
java
public ParallelTaskBuilder setReplaceVarMapToSingleTargetSingleVar( String variable, List<String> replaceList, String uniformTargetHost) { if (Strings.isNullOrEmpty(uniformTargetHost)) { logger.error("uniform target host is empty or null. skil setting."); return this; ...
java
public void setAttributeNS( String namespaceURI, String qualifiedName, String value) throws DOMException { error(XMLErrorResources.ER_FUNCTION_NOT_SUPPORTED); //"setAttributeNS not supported!"); }
java
static void populateResponse(final ModelNode response, final ServiceController<?> serviceController) { response.set(serviceController.getState().toString()); }
python
async def add(self, useriden, query: str, reqs, incunit=None, incvals=None): ''' Persistently adds an appointment Args: query (str): storm query to run reqs (Union[None, Dict[TimeUnit, Union[int, Tuple[int]], List[...]): one or more dicts ...
python
def _load_records(self, record_type_idstrs): """Loads query records""" for record_type_idstr in record_type_idstrs: try: self._init_record(record_type_idstr) except (ImportError, KeyError): pass
python
def _pool_put(pool_semaphore, tasks, put_to_pool_in, pool_size, id_self, \ is_stopping): """ (internal) Intended to be run in a seperate thread. Feeds tasks into to the pool whenever semaphore permits. Finishes if self._stopping is set. """ log.debug(...
python
def _read_info_as_dict(fid, values): """Convenience function to read info in axon data to a nicely organized dict. """ output = {} for key, fmt in values: val = unpack(fmt, fid.read(calcsize(fmt))) if len(val) == 1: output[key] = val[0] else: output[ke...
java
@Override public CreatePolicyVersionResult createPolicyVersion(CreatePolicyVersionRequest request) { request = beforeClientExecution(request); return executeCreatePolicyVersion(request); }
python
def convert_rst_to_basic_text(contents): """Convert restructured text to basic text output. This function removes most of the decorations added in restructured text. This function is used to generate documentation we can show to users in a cross platform manner. Basic indentation and list for...
java
@BetaApi public final AggregatedListAddressesPagedResponse aggregatedListAddresses(ProjectName project) { AggregatedListAddressesHttpRequest request = AggregatedListAddressesHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .build(); return aggre...
java
public ServiceFuture<ClusterMonitoringResponseInner> getMonitoringStatusAsync(String resourceGroupName, String clusterName, final ServiceCallback<ClusterMonitoringResponseInner> serviceCallback) { return ServiceFuture.fromResponse(getMonitoringStatusWithServiceResponseAsync(resourceGroupName, clusterName), serv...
java
public <T> T invokeRetry( Callable<T> invoker ) throws CStorageException { int currentTries = 0; while ( true ) { currentTries++; try { if ( currentTries > 1 ) { LOGGER.debug( "Invocation #{}/{}", currentTries, nbTriesMax ); ...
python
def sortByIndex(self, index): """Implement a Index sort.""" self.table_level.horizontalHeader().setSortIndicatorShown(True) sort_order = self.table_level.horizontalHeader().sortIndicatorOrder() self.table_index.model().sort(index, sort_order) self._sort_update()
python
def stop_capture(self, slot_number, port_number): """ Stops a packet capture. :param slot_number: slot number :param port_number: port number """ try: adapter = self._slots[slot_number] except IndexError: raise DynamipsError('Slot {slot_n...
python
def get_theming_attribute(self, mode, name, part=None): """ looks up theming attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: identifier of the atttribute :type name: str :rtype: urwid.AttrSpec """ colours = ...
java
private void computeLinkFanouts(TableDefinition tableDef, Map<String, MutableFloat> tableLinkFanoutMap) { m_logger.info("Computing link field fanouts for table: {}", tableDef.getTableName()); StringBuilder buffer = new StringBuilder(); for (Field...
python
def apply_time_offset(time, years=0, months=0, days=0, hours=0): """Apply a specified offset to the given time array. This is useful for GFDL model output of instantaneous values. For example, 3 hourly data postprocessed to netCDF files spanning 1 year each will actually have time values that are offs...
python
async def eval(self, text, opts=None, user=None): ''' Run a storm query and yield Node() objects. ''' if user is None: user = self.user # maintained for backward compatibility query = self.core.getStormQuery(text) with self.getStormRuntime(opts=opts, ...
python
def last_updated(self): ''' This is used only when SEND_IF_MODIFIED_LAST_MODIFIED_HEADERS is eet. :return: A DateTime object :rettype: datetime.datetime ''' derived_path = self.context.request.url timestamp_key = self.timestamp_key_for(derived_path) if s...
python
def _remove_non_propagating_yields(self): """Remove yield with no variables e.g. `yield 123` and plain `yield` from vulnerability.""" for node in list(self.reassignment_nodes): if isinstance(node, YieldNode) and len(node.right_hand_side_variables) == 1: self.reassignment_node...
python
def get_network(self, name, batch_size=None, callback=None): '''Create a variable graph given network by name Returns: NnpNetwork ''' network_proto = nnabla_pb2.Network() network_proto.CopyFrom(self.network_dict[name]) return NnpNetwork(network_proto, self._params, bat...
python
def validateInterfaceName(n): """ Verifies that the supplied name is a valid DBus Interface name. Throws an L{error.MarshallingError} if the format is invalid @type n: C{string} @param n: A DBus interface name """ try: if '.' not in n: raise Exception('At least two compo...
python
def add(self, port, pkt): ''' Add new input port + packet to buffer. ''' id = len(self._buffer) + 1 if id > self._buffsize: raise FullBuffer() self._buffer[id] = (port, deepcopy(pkt)) return id
java
public void updateSizes(@ProgressDrawableSize int size) { if (size == LARGE) { setSizeParameters(CIRCLE_DIAMETER_LARGE, CIRCLE_DIAMETER_LARGE, CENTER_RADIUS_LARGE, STROKE_WIDTH_LARGE, ARROW_WIDTH_LARGE, ARROW_HEIGHT_LARGE); } else { setSizeParameters(CIRCLE_DI...
python
def add_photo_to_observation(observation_id: int, file_object: BinaryIO, access_token: str): """Upload a picture and assign it to an existing observation. :param observation_id: the ID of the observation :param file_object: a file-like object for the picture. Example: open('/Users/nicolasnoe/vespa.jpg', 'r...
python
def formatter(self, key, value): """ Format messages for collectd to consume. """ template = "PUTVAL {host}/fedmsg/fedmsg_wallboard-{key} " +\ "interval={interval} {timestamp}:{value}" timestamp = int(time.time()) interval = self.hub.config['collectd_interval'] return...
python
def get_xname(self, var, coords=None): """Get the name of the x-dimension This method gives the name of the x-dimension (which is not necessarily the name of the coordinate if the variable has a coordinate attribute) Parameters ---------- var: xarray.Variables ...
python
def filter(filter_creator): """ Creates a decorator that can be used as a filter. .. warning:: This is currently not compatible with most other decorators, if you are using a decorator that isn't part of `hurler` you should take caution. """ filter_func = [None] def fun...
java
public void objectTerminated(Object object, Exception e) { if (e != null) { VdmDebugPlugin.log(e); final Job job = new Job("ServerRestart") { protected IStatus run(IProgressMonitor monitor) { restartServer(serverPort); return Status.OK_STATUS; } }; job.schedule(2000); } }
python
def create_language_model(list_words, grammar_filename, wdnet_filename): """Create a language model (wdnet) for HTK using a very simple single-word grammar""" # Create the temporary grammar file grammar = u'' grammar += u'$possible_words = ' gramm...
java
protected PackageInfo processPackageInfo(InputStream packageInfoResource) { if (packageInfoResource == null) return null; PackageInfo packageInfo = null; try { ClassReader cr = new ClassReader(packageInfoResource); TraceConfigPackageVisitor packageVisitor = n...
python
def get_next(self): """Return next task from the stack that has all dependencies resolved. Return None if there are no tasks with resolved dependencies or is there are no more tasks on stack. Use `count` to check is there are still some task left on the stack. raise ValueError if total ...
python
def delete(self, redis): ''' Deletes this field's value from the databse. Should be implemented in special cases ''' if self.index: redis.hdel(self.key(), getattr(self.obj, self.name))
python
def start(self): """ Start worker processes and a control loop """ setproctitle('oq-zworkerpool %s' % self.ctrl_url[6:]) # strip tcp:// # start workers self.workers = [] for _ in range(self.num_workers): sock = z.Socket(self.task_out_port, z.zmq.PULL,...
java
@Override public double readDouble() throws IOException { long doubleAsLong = readLong(); if ((doubleAsLong >>> 63) > 0) { doubleAsLong ^= 0x7FFFFFFFFFFFFFFFL; } return Double.longBitsToDouble(doubleAsLong); }
java
public static Set<String> dotGetKeysIn(final Map map, final String pathString) { return dotGetMap(map, pathString) .map(m -> m .keySet() .stream() .map(Object::toString) .collect(Collectors.toSet()) ...
java
public void set(int i, T label2, float d) { labels[i] = label2; scores[i] = d; }
java
public static String getCharset(HttpEntity entity) { final String guess = EntityUtils.getContentCharSet(entity); return guess == null ? HTTP.DEFAULT_CONTENT_CHARSET : guess; }
java
@JsonProperty("stack_trace") public String getStackTraceString() { if (_stackTrace != null) return _stackTrace; StackTraceElement[] ste = getStackTrace(); StringBuilder builder = new StringBuilder(); if (ste != null) { for (int i = 0; i < ste.length; i++) { if (builder.length() > 0) builder.app...
java
private Set<Node> checkNegationSpecifier(NegationSpecifier specifier) throws NodeSelectorException { List<Selector> parts = new ArrayList<Selector>(1); parts.add(specifier.getSelector()); return check(parts); }
java
public void errFormat(String format, Object... args){ format(System.err, format, args); }
python
def LDR(self, params): """ LDR Ra, [PC, #imm10_4] LDR Ra, label LDR Ra, =equate LDR Ra, [Rb, Rc] LDR Ra, [Rb, #imm7_4] LDR Ra, [SP, #imm10_4] Load a word from memory into Ra Ra, Rb, and Rc must be low registers """ # TODO definitio...
java
public ScheduledFuture<?> schedule(Options options, Runnable task) { if (!started) { startThreads(); } DelayedTask t = new DelayedTask(clock, options, task); queue.put(t); return t; }
java
private double loglikelihoodAnomalous(DBIDs anomalousObjs) { return anomalousObjs.isEmpty() ? 0 : anomalousObjs.size() * -FastMath.log(anomalousObjs.size()); }
java
@Override public <T> Entity parseBean(T bean, boolean isToUnderlineCase, boolean ignoreNullValue) { if (StrUtil.isBlank(this.tableName)) { String simpleName = bean.getClass().getSimpleName(); this.setTableName(isToUnderlineCase ? StrUtil.toUnderlineCase(simpleName) : StrUtil.lowerFirst(simpleName)); } ...
java
@Override protected Observable resumeWithFallback() { if (commandActions.hasFallbackAction()) { MetaHolder metaHolder = commandActions.getFallbackAction().getMetaHolder(); Throwable cause = getExecutionException(); if (cause instanceof CommandActionExecutionException) { ...
python
def filename(self): """ Returns readable filename for a transcript """ client_id, __ = os.path.splitext(self.video.client_video_id) file_name = u'{name}-{language}.{format}'.format( name=client_id, language=self.language_code, format=self.file_...
python
def indented_tree_line_generator(el, max_lines=None): """ Like tree_line_generator, but yields tuples (start_ref, end_ref, line), where the line already takes the indentation into account by having "> " prepended. If a line already starts with ">", it is escaped ("\\>"). This makes it possible to re...
python
def run(self): """Render and display Python package documentation. """ os.environ['JARN_RUN'] = '1' self.python.check_valid_python() args = self.parse_options(self.args) if args: arg = args[0] else: arg = os.curdir if arg: ...
python
def initialize(self, session=None, force=False): """ Initializes TensorFlow variables, which are returned by `initializables` property and uses feed dictionary returned by `initializable_feeds` property defined at ICompilable interface and implemented by descendants. :param sess...
python
def run(self, args=(), env={}): """ Calls the package manager with the arguments. Returns decoded output of stdout and stderr; decoding determine by locale. """ # the following will call self._get_exec_binary return self._exec(self.binary, args=args, env=env)
python
def clear_to_enc_filename(fname): """ Converts the filename of a cleartext file and convert it to an encrypted filename :param fname: :return: filename of encrypted secret file if found, else None """ if not fname.lower().endswith('.json'): raise CredkeepException('Invalid filetype') ...
java
void update(final T item, final double weight, final boolean mark) { if (item == null) { return; } if (weight <= 0.0) { throw new SketchesArgumentException("Item weights must be strictly positive: " + weight + ", for item " + item.toString()); } ++n_; if (r_ == 0) { ...
java
public static String toStringLow(long[] v) { if(v == null) { return "null"; } final int mag = magnitude(v); if(mag == 0) { return "0"; } char[] digits = new char[mag]; int pos = 0; outer: for(int w = 0; w < v.length; w++) { long f = 1L; for(int i = 0; i < Long.SI...
python
def what_time_is_it_in(self, message, place): """what time is it in ___: Say the time in almost any city on earth.""" location = get_location(place) if location is not None: tz = get_timezone(location.lat, location.long) if tz is not None: ct = datetime.da...
python
def name(self) -> Optional[str]: """Returns name specified in Content-Disposition header or None if missed or header is malformed. """ _, params = parse_content_disposition( self.headers.get(CONTENT_DISPOSITION)) return content_disposition_filename(params, 'name')
java
private static int maxFinishIndexedBinarySearch( List<? extends TemporalProposition> list, long tstamp) { int low = 0; int high = list.size() - 1; while (low <= high) { /* * We use >>> instead of >> or /2 to avoid overflow. Sun's * implementatio...