language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public void marshall(ListWebACLsRequest listWebACLsRequest, ProtocolMarshaller protocolMarshaller) { if (listWebACLsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listWebACLsRequest.getNex...
java
@Override public RecordWriter<K, V> getRecordWriter(TaskAttemptContext context) throws IOException, InterruptedException { Configuration conf = context.getConfiguration(); return getDelegate(conf).getRecordWriter(context); }
java
SnapshotDescriptor copyTo(Buffer buffer) { this.buffer = buffer .writeLong(index) .writeLong(timestamp) .writeInt(version) .writeBoolean(locked) .skip(BYTES - buffer.position()) .flush(); return this; }
java
static boolean shouldExpireAfterRead(Request request) { return Boolean.TRUE.toString().equalsIgnoreCase(request.header(CACHE_EXPIRE_AFTER_READ_HEADER)); }
python
def dottable_getitem(data, dottable_key, default=None): """Return item as ``dict.__getitem__` but using keys with dots. It does not address indexes in iterables. """ def getitem(value, *keys): if not keys: return default elif len(keys) == 1: key = keys[0] ...
python
def get_current_m2m_diff(self, instance, new_objects): """ :param instance: Versionable object :param new_objects: objects which are about to be associated with instance :return: (being_removed id list, being_added id list) :rtype : tuple """ new_ids =...
python
def native(s, encoding='utf-8', fallback='iso-8859-1'): """Convert a given string into a native string.""" if isinstance(s, str): return s if str is unicode: # Python 3.x -> return unicodestr(s, encoding, fallback) return bytestring(s, encoding, fallback)
python
def _apply_tracing(self, handler, attributes): """ Helper function to avoid rewriting for middleware and decorator. Returns a new span from the request with logged attributes and correct operation name from the func. """ operation_name = self._get_operation_name(handler) ...
python
def t_IDENTIFIER(self, t): r'[a-zA-Z_][a-zA-Z0-9_]*' t.type = self.reserved_words.get(t.value, 'IDENTIFIER') return t
java
public static Object decodeObjectContent(Object content, MediaType contentMediaType) { try { if (content == null) return null; if (contentMediaType == null) { throw new NullPointerException("contentMediaType cannot be null!"); } String strContent; String ty...
java
public void align(Structure s1, Structure s2) throws StructureException { align(s1, s2, params); }
python
def weighted(weights): """ Return a random integer 0 <= N <= len(weights) - 1, where the weights determine the probability of each possible integer. Based on this StackOverflow post by Ned Batchelder: http://stackoverflow.com/questions/3679694/a-weighted-version-of-random-choic...
java
public final void creator() throws RecognitionException { try { // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:649:5: ( ( nonWildcardTypeArguments )? createdName ( arrayCreatorRest | classCreatorRest ) ) // src/main/resources/org/drools/compiler/lang/DRL6Expressions.g:649:7: ( nonWildcardTypeA...
python
def encode(cls, value): """ encode a floating point number to bytes in redis :param value: float :return: bytes """ try: if float(value) + 0 == value: return repr(value) except (TypeError, ValueError): pass raise I...
java
private boolean isPublicAccessible(Member member) { if (((AccessibleObject) member).isAccessible()) { return true; } if (!Modifier.isPublic(member.getModifiers())) { return false; } if (Modifier.isPublic(member.getDeclaringClass().getModifiers())) { return true; } return f...
python
def shallow_repr(self, max_depth=8, explicit_length=False, details=LITE_REPR): """ Returns a string representation of this AST, but with a maximum depth to prevent floods of text being printed. :param max_depth: The maximum depth to print. :param explicit_length: P...
java
@Override protected void _fit(Dataframe trainingData) { ModelParameters modelParameters = knowledgeBase.getModelParameters(); Map<Object, Double> minColumnValues = modelParameters.getMinColumnValues(); Map<Object, Double> maxColumnValues = modelParameters.getMaxColumnValues(); boolea...
java
public com.google.privacy.dlp.v2.KmsWrappedCryptoKey getKmsWrapped() { if (sourceCase_ == 3) { return (com.google.privacy.dlp.v2.KmsWrappedCryptoKey) source_; } return com.google.privacy.dlp.v2.KmsWrappedCryptoKey.getDefaultInstance(); }
python
def remote_upload(apikey, picture_url, resize=None, rotation='00', noexif=False): """ prepares post for remote upload :param str apikey: Apikey needed for Autentication on picflash. :param str picture_url: URL to picture allowd Protocols are: ftp, http, https :param str re...
java
@SuppressWarnings("unchecked") private void decreaseKey(ReflectedHandle<K, V> n, K newKey) { if (n.inner == null && free != n) { throw new IllegalArgumentException("Invalid handle!"); } int c; if (comparator == null) { c = ((Comparable<? super K>) newKey).com...
java
public DateTime toDateTimeAtMidnight(DateTimeZone zone) { Chronology chrono = getChronology().withZone(zone); return new DateTime(getYear(), getMonthOfYear(), getDayOfMonth(), 0, 0, 0, 0, chrono); }
python
def publish(**kwargs): """ Runs the version task before pushing to git and uploading to pypi. """ current_version = get_current_version() click.echo('Current version: {0}'.format(current_version)) retry = kwargs.get("retry") debug('publish: retry=', retry) if retry: # The "new" ...
java
public static <T> AddQuery<T> start(T query, long correlationId, String type) { return start(query, correlationId, type, null); }
java
private String generateValue() { String result = ""; for (CmsCheckBox checkbox : m_checkboxes) { if (checkbox.isChecked()) { result += checkbox.getInternalValue() + ","; } } if (result.contains(",")) { result = result.substrin...
java
void registerAndConnect(SocketChannel sock, InetSocketAddress addr) throws IOException { selectionKey = sock.register(selector, SelectionKey.OP_CONNECT); boolean immediateConnect = sock.connect(addr); if(LOGGER.isTraceEnabled()){ LOGGER.trace("Connect to host=" + addr.ge...
java
private void parseData(byte[] data) { int bytesRead = 0; if (grouped) { group = data[bytesRead]; bytesRead ++; } if (encrypted) { encrType = data[bytesRead]; bytesRead ++; } if (lengthIndicator) { dataLength = Helpers.convertDWordToInt(data, bytesRead); bytesRead += 4; } frame...
python
def set_away(self, away=True): """ :param away: a boolean of true (away) or false ('home') :return nothing This function handles both ecobee and nest thermostats which use a different field for away/home status. """ if self.profile() is not None: if a...
python
def drop_zombies(feed: "Feed") -> "Feed": """ In the given "Feed", drop stops with no stop times, trips with no stop times, shapes with no trips, routes with no trips, and services with no trips, in that order. Return the resulting "Feed". """ feed = feed.copy() # Drop stops of location...
java
final public void print(Object v) { if (v == null) write(_nullChars, 0, _nullChars.length); else { String s = v.toString(); write(s, 0, s.length()); } }
java
public int getExpandedTypeID(String namespace, String localName, int type) { ExpandedNameTable ent = m_expandedNameTable; return ent.getExpandedTypeID(namespace, localName, type); }
java
public void deleteBuildVariable(Integer projectId, String key) throws IOException { String tailUrl = GitlabProject.URL + "/" + projectId + GitlabBuildVariable.URL + "/" + key; retrieve().method(DELETE).to(tailUrl, Void.class); }
python
def isinstance(self, types): """ Checks if the instance if one of the types provided or if any of the inner_field child is one of the types provided, returns True if field or any inner_field is one of ths provided, False otherwise :param types: Iterable of types to check inclusion of ins...
java
void markAsProcessed(final CtClass ctClass) { final ClassFile classFile = ctClass.getClassFile(); for (final Object attributeObject : classFile.getAttributes()) { if (attributeObject instanceof AnnotationsAttribute) { final AnnotationsAttribute annotationAttribute = (Annotati...
python
def config(key): """ Decorator to map this class directly to a configuration node. It uses `<parentbase>.key` for configuration base and configuration mapping. """ def decorator(cls): parent = cls.getConfigurableParent() if parent is None: parentbase = None else: ...
java
public ImplementationGuidePackageComponent addPackage() { //3 ImplementationGuidePackageComponent t = new ImplementationGuidePackageComponent(); if (this.package_ == null) this.package_ = new ArrayList<ImplementationGuidePackageComponent>(); this.package_.add(t); return t; }
java
public static org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement p2( final Curve curve, final FieldElement X, final FieldElement Y, final FieldElement Z) { return new org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement(curve, Represent...
python
def image(self, x, y, image, width=None, height=None): """ Inserts an image into the drawing, position by its top-left corner. :param int x: The x position to insert the image. :param int y: The y position to insert the image. :param str image: ...
python
def add_vts(self, task_name, targets, cache_key, valid, phase): """ Add a single VersionedTargetSet entry to the report. :param InvalidationCacheManager cache_manager: :param CacheKey cache_key: :param bool valid: :param string phase: """ if task_name not in self._task_reports: self.ad...
java
void updateDataFields(int why) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "updateDataFields"); super.updateDataFields(why); if (bodyMap != null && bodyMap.isChanged()) { getPayload().setField(JmsMapBodyAccess.BODY_DATA_ENTRY_NAME, bodyMap.getKeyList()); ...
java
protected static String decodePercent(String str) { String decoded = null; try { decoded = URLDecoder.decode(str, "UTF8"); } catch (UnsupportedEncodingException ignored) { NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored); } retu...
java
private void passivateSession(BackedSession sess) { synchronized (sess) { // Keep PropertyWriter thread from sneaking in.. if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) { LoggingUtil.SESSION_LOGGER_WAS.logp(L...
java
public static PreparedStatement createTrackTable(Connection connection, String trackTableName,boolean isH2) throws SQLException { try (Statement stmt = connection.createStatement()) { StringBuilder sb = new StringBuilder("CREATE TABLE "); sb.append(trackTableName).append(" ("); ...
java
public void incrementWaitingRequests(String browserName) { logger.entering(browserName); validateBrowserName(browserName); BrowserStatistics lStatistics = createStatisticsIfNotPresent(browserName); lStatistics.incrementWaitingRequests(); logger.exiting(); }
python
def set_def_canned_acl(self, acl_str, key_name='', headers=None): """sets or changes a bucket's default object acl to a predefined (canned) value""" return self.set_canned_acl_helper(acl_str, key_name, headers, query_args=DEF_OBJ_ACL)
java
public EList<Double> getValues() { if (values == null) { values = new EDataTypeEList<Double>(Double.class, this, TypesPackage.JVM_DOUBLE_ANNOTATION_VALUE__VALUES); } return values; }
java
public Observable<EnqueueTrainingResponse> trainVersionAsync(UUID appId, String versionId) { return trainVersionWithServiceResponseAsync(appId, versionId).map(new Func1<ServiceResponse<EnqueueTrainingResponse>, EnqueueTrainingResponse>() { @Override public EnqueueTrainingResponse call(Se...
python
def check_value_error_for_parity(value_error: ValueError, call_type: ParityCallType) -> bool: """ For parity failing calls and functions do not return None if the transaction will fail but instead throw a ValueError exception. This function checks the thrown exception to see if it's the correct one and...
java
@Ok("json:full") @At("/api/purchase") public NutMap purchase(String userId, String commodityCode, int orderCount, boolean dofail) { try { businessService.purchase(userId, commodityCode, orderCount, dofail); return new NutMap("ok", true); } catch (Throwable e) { ...
python
def update(self, key, content, **metadata): """ :param key: Document unique identifier. :param str content: Content to store and index for search. :param metadata: Arbitrary key/value pairs to store for document. Update the given document. Existing metadata will be preserved and...
python
def iterator(self, *argv): """ Iterator returning any list of elements via attribute lookup in `self` This iterator retains the order of the arguments """ for arg in argv: if hasattr(self, arg): for item in getattr(self, arg): yield item
java
public static boolean is_yanadi(String str) { String s1 = VarnaUtil.getAdiVarna(str); if (is_yan(s1)) return true; return false; }
java
@Override public java.util.concurrent.Future<ReceiveMessageResult> receiveMessageAsync(String queueUrl, com.amazonaws.handlers.AsyncHandler<ReceiveMessageRequest, ReceiveMessageResult> asyncHandler) { return receiveMessageAsync(new ReceiveMessageRequest().withQueueUrl(queueUrl), asyncHandler); ...
python
def firmware_download_input_protocol_type_ftp_protocol_ftp_host(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware_download = ET.Element("firmware_download") config = firmware_download input = ET.SubElement(firmware_download, "input") ...
python
def top_charts_for_genre(self, genre_id): """Get a listing of top charts for a top chart genre. Parameters: genre_id (str): A top chart genre ID as found with :meth:`top_charts_genres`. """ response = self._call(mc_calls.BrowseTopChartForGenre, genre_id) top_chart_for_genre = response.body return top_...
java
@Override @FFDCIgnore(Exception.class) public String getGroupSecurityName(final String inputUniqueGroupId) throws EntryNotFoundException, RegistryException { try { // bridge the APIs String returnValue = securityBridge.getGroupSecurityName(inputUniqueGroupId); return ...
python
def show_minimum_needs_configuration(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) dialog = NeedsManagerDialog( parent=self.iface....
python
def __shapeIndex(self, i=None): """Returns the offset in a .shp file for a shape based on information in the .shx index file.""" shx = self.shx if not shx: return None if not self._offsets: # File length (16-bit word * 2 = bytes) - header length ...
python
def get_clients_groups(self) -> typing.Iterator['Group']: """ Gets all clients groups Returns: generator of Groups """ for group in self.groups: if group.group_is_client_group: yield group
java
public IfcCommunicationsApplianceTypeEnum createIfcCommunicationsApplianceTypeEnumFromString(EDataType eDataType, String initialValue) { IfcCommunicationsApplianceTypeEnum result = IfcCommunicationsApplianceTypeEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The valu...
java
public String getErrorString() { StringBuffer ret = new StringBuffer(); String linesep = System.getProperty("line.separator"); List<Exception> exc = getExceptions(); if (exc != null && exc.size() != 0) { // ret.append(HBCIUtils.getLocMsg("STAT_EXCEPTIONS")).append(":").appe...
java
public final EObject ruleXVariableDeclaration() throws RecognitionException { EObject current = null; Token lv_writeable_1_0=null; Token otherlv_2=null; Token lv_extension_3_0=null; Token lv_extension_4_0=null; Token lv_writeable_5_0=null; Token otherlv_6=null; ...
java
public void setUserAttributes(java.util.Collection<AttributeType> userAttributes) { if (userAttributes == null) { this.userAttributes = null; return; } this.userAttributes = new java.util.ArrayList<AttributeType>(userAttributes); }
java
public com.squareup.okhttp.Call getUniversePlanetsPlanetIdAsync(Integer planetId, String datasource, String ifNoneMatch, final ApiCallback<PlanetResponse> callback) throws ApiException { com.squareup.okhttp.Call call = getUniversePlanetsPlanetIdValidateBeforeCall(planetId, datasource, ifNoneMatch, ...
java
@Override public LogProperties logProperties() { if (tc.isEntryEnabled()) Tr.entry(tc, "logProperties", this); final LogProperties lprops = _recoveryLog.logProperties(); if (tc.isEntryEnabled()) Tr.exit(tc, "logProperties", lprops); return lprops; }
java
protected final void run(Block block) { if (stopping) { return; } final Authentication auth = Jenkins.getAuthentication(); task = GeneralNonBlockingStepExecutionUtils.getExecutorService().submit(() -> { threadName = Thread.currentThread().getName(); tr...
java
@Override public void addStatus(Status status) { StatusManager sm = context.getStatusManager(); sm.add(status); }
java
public static int findIndexOf(Object self, int startIndex, Closure condition) { return findIndexOf(InvokerHelper.asIterator(self), condition); }
java
@Override public Double getUserItemPreference(U u, I i) { if (userItemPreferences.containsKey(u) && userItemPreferences.get(u).containsKey(i)) { return userItemPreferences.get(u).get(i); } return Double.NaN; }
python
def bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4", scatter_size=10, fill_alpha=0.4, line_alpha=0.4, court_line_color='gray', court_line_width=1, hover_tool=False, tooltips=None, **kwargs): # TODO: Settings for hover tooltip """ ...
python
def write_bsedebug(basis): '''Converts a basis set to BSE Debug format ''' s = '' for el, eldata in basis['elements'].items(): s += element_data_str(el, eldata) return s
python
def load(obj, env=None, silent=True, key=None): """Loads envvars with prefixes: `DYNACONF_` (default global) or `$(ENVVAR_PREFIX_FOR_DYNACONF)_` """ global_env = obj.get("ENVVAR_PREFIX_FOR_DYNACONF") if global_env is False or global_env.upper() != "DYNACONF": load_from_env(IDENTIFIER + "_gl...
python
def info(self): """Delivers some info to you about the class.""" print("Sorry, but I don't have much to share.") print("This is me:") print(self) print("And these are the experiments assigned to me:") print(self.experiments)
python
def pipe_value(self, message): 'Send a new value into the ws pipe' jmsg = json.dumps(message) self.send(jmsg)
java
public Observable<ServiceResponse<List<String>>> listDomainsWithServiceResponseAsync() { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } String parameterizedHost = Joiner.on(", ").join("{E...
python
def subset(self, used_indices, params=None): """Get subset of current Dataset. Parameters ---------- used_indices : list of int Indices used to create the subset. params : dict or None, optional (default=None) These parameters will be passed to Dataset co...
java
public static void log(final Level level, final Throwable exception, final String message) { String nameOfException = exception.getClass().getName(); String messageOfException = exception.getMessage(); StringBuilder builder = new StringBuilder(BUFFER_SIZE); builder.append(level); builder.append(": "); buil...
java
public Vector2f lerp(Vector2fc other, float t, Vector2f dest) { dest.x = x + (other.x() - x) * t; dest.y = y + (other.y() - y) * t; return dest; }
java
public static List<KeyedStateHandle> getManagedKeyedStateHandles( OperatorState operatorState, KeyGroupRange subtaskKeyGroupRange) { final int parallelism = operatorState.getParallelism(); List<KeyedStateHandle> subtaskKeyedStateHandles = null; for (int i = 0; i < parallelism; i++) { if (operatorState.g...
java
private Predicate<HelpPage> query(final Predicate<HelpPage> predicate) { Predicate<HelpPage> query = predicate; if (includeAll == null || !includeAll) { if (includeAliases != null && !includeAliases) { query = query.and(TypePredicate.of(AliasHelpPage.class).negate()); } if (includeMet...
python
def get_sorted_source_files( self, source_filenames_or_globs: Union[str, List[str]], recursive: bool = True) -> List[str]: """ Returns a sorted list of filenames to process, from a filename, a glob string, or a list of filenames/globs. Args: ...
python
def isordv(array, n): """ Determine whether an array of n items contains the integers 0 through n-1. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/isordv_c.html :param array: Array of integers. :type array: Array of ints :param n: Number of integers in array. :type n: int ...
java
public static <T> Collection<T> reject( Iterable<T> iterable, Predicate<? super T> predicate, boolean allowReorderedResult) { return ParallelIterate.reject(iterable, predicate, null, allowReorderedResult); }
python
def sort_servers_closest(servers: Sequence[str]) -> Sequence[Tuple[str, float]]: """Sorts a list of servers by http round-trip time Params: servers: sequence of http server urls Returns: sequence of pairs of url,rtt in seconds, sorted by rtt, excluding failed servers (possibly empty...
java
@Override public Object render(Map<String, Object> context, LNode... nodes) { // The group-name is either the first token-expression, or if that is // null (indicating there is no name), give it the name PREPEND followed // by the number of expressions in the cycle-group. String gro...
python
def parse_point_source_node(node, mfd_spacing=0.1): """ Returns an "areaSource" node into an instance of the :class: openquake.hmtk.sources.area.mtkAreaSource """ assert "pointSource" in node.tag pnt_taglist = get_taglist(node) # Get metadata point_id, name, trt = (node.attrib["id"], ...
python
def flush(self): """Synchronously wait until this work item is processed. This has the effect of waiting until all work items queued before this method has been called have finished. """ done = threading.Event() def _callback(): done.set() self.def...
java
private static String firstCharToLowerCase(String word) { if (word.length() == 1) { return word.toLowerCase(); } char c = word.charAt(0); char newChar; if (c >= 'A' && c <= 'Z') { newChar = (char) (c + 32); } else { newChar = c; } return newChar + word.substring(1); }
python
def update_by_function(self, extra_doc, index, doc_type, id, querystring_args=None, update_func=None, attempts=2): """ Update an already indexed typed JSON document. The update happens client-side, i.e. the current document is retrieved, updated locally and fi...
java
@Deprecated public ServerBuilder port(int port, String protocol) { return port(port, SessionProtocol.of(requireNonNull(protocol, "protocol"))); }
python
def get_rows(runSetResults): """ Create list of rows with all data. Each row consists of several RunResults. """ rows = [] for task_results in zip(*[runset.results for runset in runSetResults]): rows.append(Row(task_results)) return rows
python
def loads(s, cls=None, **kwargs): """Load string""" if not isinstance(s, string_types): raise TypeError('the YAML object must be str, not {0!r}'.format(s.__class__.__name__)) cls = cls or YAMLDecoder return cls(**kwargs).decode(s)
python
def convertTimestamps(column): """Convert a dtype of a given column to a datetime. This method tries to do this by brute force. Args: column (pandas.Series): A Series object with all rows. Returns: column: Converted to datetime if no errors occured, else the original colum...
java
@Benchmark public ExampleInterface baseline() { return new ExampleInterface() { public boolean method(boolean arg) { return false; } public byte method(byte arg) { return 0; } public short method(short arg) { ...
java
public static base_response flush(nitro_service client, nssimpleacl resource) throws Exception { nssimpleacl flushresource = new nssimpleacl(); flushresource.estsessions = resource.estsessions; return flushresource.perform_operation(client,"flush"); }
python
async def spawn(self, agent_cls, *args, addr=None, **kwargs): """Spawn a new agent in a slave environment. :param str agent_cls: `qualname`` of the agent class. That is, the name should be in the form ``pkg.mod:cls``, e.g. ``creamas.core.agent:CreativeAgent``. ...
python
def render_payment_form(self): """Display the DirectPayment for entering payment information.""" self.context[self.form_context_name] = self.payment_form_cls() return TemplateResponse(self.request, self.payment_template, self.context)
java
public void info( String msg, Throwable t ) { if( m_delegate.isInfoEnabled() ) { m_delegate.inform( msg, t ); } }
python
def from_fqdn(cls, fqdn): """Retrieve domain id associated to a FQDN.""" result = cls.list({'fqdn': fqdn}) if len(result) > 0: return result[0]['id']
java
@SuppressWarnings("unchecked") private final void instantiateDeserializationUtils() { if (this.serializers == null) { this.serializers = new TypeSerializer[this.serializerFactories.length]; for (int i = 0; i < this.serializers.length; i++) { this.serializers[i] = this.serializerFactories[i].getSerializer()...
python
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['...