language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def has_isotropic_cells(self): """``True`` if `grid` is uniform and `cell_sides` are all equal. Always ``True`` for 1D partitions. Examples -------- >>> part = uniform_partition([0, -1], [1, 1], (5, 10)) >>> part.has_isotropic_cells True >>> part = unifo...
python
def read(self, entity=None, attrs=None, ignore=None, params=None): """Provide a default value for ``entity``. By default, ``nailgun.entity_mixins.EntityReadMixin.read`` provides a default value for ``entity`` like so:: entity = type(self)() However, :class:`SyncPlan` requi...
java
public final void deleteSshPublicKey(String name) { DeleteSshPublicKeyRequest request = DeleteSshPublicKeyRequest.newBuilder().setName(name).build(); deleteSshPublicKey(request); }
python
def write_generator_data(self, file): """ Writes generator data in MATPOWER format. """ gen_attr = ["p", "q", "q_max", "q_min", "v_magnitude", "base_mva", "online", "p_max", "p_min", "mu_pmax", "mu_pmin", "mu_qmax", "mu_qmin"] file.write("\n%%%% generator data\n"...
python
def get_activities(self, activity_ids=None, max_records=50): """ Get all activies for this group. """ return self.connection.get_all_activities(self, activity_ids, max_records)
python
def get_access_token(self, refresh_token): """ Use a refresh token to obtain a new access token """ token = requests.post(GOOGLE_OAUTH2_TOKEN_URL, data=dict( refresh_token=refresh_token, grant_type='refresh_token', client_id=self.client_id, ...
java
public synchronized void enqueue(final T o) throws IOException { assert o != null; fbaos.reset(); BinIO.storeObject(o, fbaos); byteDiskQueue.enqueueInt(fbaos.length); byteDiskQueue.enqueue(fbaos.array, 0, fbaos.length); size++; }
java
private void call(final Element e, final String arg) { JQuery.jQuery(e).popover(arg); }
java
public void setStartDate(Date dateStart) { try { // NOTE: I ignore dateStart and use the date as it appears on the screen dateStart = m_productItem.getStartDate(); // Date as it appears on the screen Date timeNew = m_productItem.setRemoteStartDate(dateStart); ...
java
public I_CmsXmlSchemaType getContentType(Element typeElement, Set<CmsXmlContentDefinition> nestedDefinitions) throws CmsXmlException { if (!CmsXmlContentDefinition.XSD_NODE_ELEMENT.equals(typeElement.getQName())) { throw new CmsXmlException(Messages.get().container(Messages.ERR_INVALID_CD_SCHEM...
java
public static long parseBE4BytesAsUnsigned(byte[] data, int offset) { long value = ((long)(data[offset + 0] & 0xFF) << 24) | ((long)(data[offset + 1] & 0xFF) << 16) | ((long)(data[offset + 2] & 0xFF) << 8) | ((long)(data[offset + 3] & 0xFF) << 0); ...
python
def init_graph(self): """ Initialize graph Load all nodes and set dependencies. To avoid errors about missing nodes all nodes get loaded first before setting the dependencies. """ self._graph = Graph() # First add all nodes for key in self.loader...
python
def get_intel_compiler_top(version, abi): """ Return the main path to the top-level dir of the Intel compiler, using the given version. The compiler will be in <top>/bin/icl.exe (icc on linux), the include dir is <top>/include, etc. """ if is_windows: if not SCons.Util.can_read_reg:...
java
public void fill(Graphics2D g, Shape s, boolean isRounded, boolean paintRightShadow) { if (isRounded) { fillInternalShadowRounded(g, s); } else { fillInternalShadow(g, s, paintRightShadow); } }
python
def case_study_social_link_facebook(value): """ Confirms that the social media url is pointed at the correct domain. Args: value (string): The url to check. Raises: django.forms.ValidationError """ parsed = parse.urlparse(value.lower()) if not parsed.netloc.endswith('face...
python
def reorder(self, single_column=False): """Force a reorder of the displayed items""" if single_column: columns = self.sortOrder[:1] else: columns = self.sortOrder for ascending,column in columns[::-1]: # Python 2.2+ guarantees stable sort, so sort by e...
python
def set_purpose(self, channel_name, purpose): """ https://api.slack.com/methods/channels.setPurpose """ channel_id = self.get_channel_id(channel_name) self.params.update({ 'channel': channel_id, 'purpose': purpose, }) return FromUrl('https://sl...
java
@Override public void addSipConnector(String ipAddress, int port, String transport) throws LifecycleException { SipConnector sipConnector = mssContainer.createSipConnector(ipAddress, port, transport); mssContainer.addSipConnector(sipConnector); }
python
def old_decode_aes(key, iv_plus_encrypted): """ Utility method to decode a payload consisting of the hexed IV + the hexed ciphertext using the given key. See above for more details. :param key: string, <= 32 bytes long :param iv_plus_encrypted: string, a hexed IV + hexed ciphertext """ # gr...
java
public Stream<IntPair> adjacent8Points(final int i, final int j) { final IntPair up = i == 0 ? null : IntPair.of(i - 1, j); final IntPair right = j == cols - 1 ? null : IntPair.of(i, j + 1); final IntPair down = i == rows - 1 ? null : IntPair.of(i + 1, j); final IntPair left = j == 0...
python
def summarize(self, text, length=5, binary_matrix=True): """ Implements the method of summarization by relevance score, as described by Gong and Liu in the paper: Y. Gong and X. Liu (2001). Generic text summarization using relevance measure and latent semantic analysis. Proceedings of t...
java
public ApiResponse<InlineResponse2003> chatMessagesWithHttpInfo(String id) throws ApiException { com.squareup.okhttp.Call call = chatMessagesValidateBeforeCall(id, null, null); Type localVarReturnType = new TypeToken<InlineResponse2003>(){}.getType(); return apiClient.execute(call, localVarRetur...
java
public FlowVariable createFlowVariable(final Flow flow, final String id, final Class type) { val opt = Arrays.stream(flow.getVariables()).filter(v -> v.getName().equalsIgnoreCase(id)).findFirst(); if (opt.isPresent()) { return opt.get(); } val flowVar = new FlowVariable(id, n...
java
private void initializeNavigationWidth(final SharedPreferences sharedPreferences) { String key = getString(R.string.navigation_width_preference_key); String defaultValue = getString(R.string.navigation_width_preference_default_value); int width = Integer.valueOf(sharedPreferences.getString(key, ...
python
def camelcase(text, acronyms=None): """Return text in camelCase style. Args: text: input string to convert case detect_acronyms: should attempt to detect acronyms acronyms: a list of acronyms to detect >>> camelcase("hello world") 'helloWorld' >>> camelcase("HELLO_HTML_WORL...
python
def setImageItem(self, img): """Set an ImageItem to have its levels and LUT automatically controlled by this HistogramLUTItem. """ self.imageItem = weakref.ref(img) img.sigImageChanged.connect(self.imageChanged) img.setLookupTable(self.getLookupTable) ## send function po...
python
def get_brain_info(brain): """Extract the brain info """ icon = api.get_icon(brain) # avoid 404 errors with these guys if "document_icon.gif" in icon: icon = "" id = api.get_id(brain) url = api.get_url(brain) title = api.get_title(brain) description = api.get_description(bra...
python
def export_net_json(net, net_type, indent='no-indent'): ''' export json string of dat ''' import json from copy import deepcopy if net_type == 'dat': exp_dict = deepcopy(net.dat) if type(exp_dict['mat']) is not list: exp_dict['mat'] = exp_dict['mat'].tolist() if 'mat_orig' in exp_dict: ...
java
public static void setInputCQLPageRowSize(Configuration conf, String cqlPageRowSize) { if (cqlPageRowSize == null) { throw new UnsupportedOperationException("cql page row size may not be null"); } conf.set(INPUT_CQL_PAGE_ROW_SIZE_CONFIG, cqlPageRowSize); }
java
public void add( float value ) { // see if it needs to grow the queue if( size >= data.length) { data[start] = value; start = (start+1)%data.length; } else { data[(start+size)%data.length] = value; size++; } }
java
private String readLine(boolean trim) throws IOException { boolean done = false; boolean sawCarriage = false; // bytes to trim (the \r and the \n) int removalBytes = 0; while (!done) { if (isReadBufferEmpty()) { offset = 0; end = 0; int bytesRead = inputStream.read(buff...
python
def Ft_aircooler(Thi, Tho, Tci, Tco, Ntp=1, rows=1): r'''Calculates log-mean temperature difference correction factor for a crossflow heat exchanger, as in an Air Cooler. Method presented in [1]_, fit to other's nonexplicit work. Error is < 0.1%. Requires number of rows and tube passes as well as stream...
java
private void doInterceptBeforeInsert(Object t) { List<Object> list = new ArrayList<Object>(); list.add(t); doInterceptBeforeInsertList(list); }
python
def _list(self, path, dim_key=None, **kwargs): """Get a list of metrics.""" url_str = self.base_url + path if dim_key and dim_key in kwargs: dim_str = self.get_dimensions_url_string(kwargs[dim_key]) kwargs[dim_key] = dim_str if kwargs: url_str += '?%s...
java
void releaseTransaction(@NotNull final Thread thread, final int permits) { try (CriticalSection ignored = criticalSection.enter()) { int currentThreadPermits = getThreadPermits(thread); if (permits > currentThreadPermits) { throw new ExodusException("Can't release more pe...
java
AddIfStandalone addIfStandalone(Object... objects) { if (addIfStandalone == null) { addIfStandalone = new AddIfStandalone(getWebServer().isStandalone()); } addIfStandalone.ifAdd(objects); return addIfStandalone; }
python
def create_namespaced_role_binding(self, namespace, body, **kwargs): """ create a RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_namespaced_role_binding(namespace, body,...
python
def new(self, flags, sys_ident, vol_ident, set_size, seqnum, log_block_size, vol_set_ident, pub_ident_str, preparer_ident_str, app_ident_str, copyright_file, abstract_file, bibli_file, vol_expire_date, app_use, xa, version, escape_sequence): # type: (int, bytes, bytes, int, i...
python
def _get_project(msg, key='project'): ''' Return the project as `foo` or `user/foo` if the project is a fork. ''' project = msg[key]['name'] ns = msg[key].get('namespace') if ns: project = '/'.join([ns, project]) if msg[key]['parent']: user = msg[key]['user']['name'] ...
java
public void replace(ClassNode type) { int size = ensureStackNotEmpty(stack); stack.set(size - 1, type); }
java
public static void multAddTransB(double realAlpha , double imagAlpha , ZMatrixRMaj a , ZMatrixRMaj b , ZMatrixRMaj c ) { // TODO add a matrix vectory multiply here MatrixMatrixMult_ZDRM.multAddTransB(realAlpha,imagAlpha,a,b,c); }
python
def _dims_in_order(self, dimension_order): ''' :param list dimension_order: A list of axes :rtype: bool :return: Returns True if the dimensions are in order U*, T, Z, Y, X, False otherwise ''' regx = regex.compile(r'^[^TZYX]*T?Z?Y?X?$') dimension_...
java
@Override public R visitVariable(VariableTree node, P p) { R r = scan(node.getModifiers(), p); r = scanAndReduce(node.getType(), p, r); r = scanAndReduce(node.getNameExpression(), p, r); r = scanAndReduce(node.getInitializer(), p, r); return r; }
java
public Observable<ServiceResponse<Void>> exportWithServiceResponseAsync(String vaultName, String resourceGroupName, String filter) { if (vaultName == null) { throw new IllegalArgumentException("Parameter vaultName is required and cannot be null."); } if (resourceGroupName == null) { ...
java
public void createRepository(String backupId, RepositoryEntry rEntry, StorageCreationProperties creationProps) throws RepositoryConfigurationException, RepositoryCreationException { String rToken = reserveRepositoryName(rEntry.getName()); if (creationProps instanceof DBCreationProperties) ...
python
def append_dictionary_to_file(localization_key_to_comment, file_path, section_name): """ Appends dictionary of localization keys and comments to a file Args: localization_key_to_comment (dict): A mapping between localization keys and comments. file_path (str): The path of the file to append to....
python
def exc_emailer(send_mail_func, logger=None, catch=Exception, print_to_stderr=True): """ Catch exceptions and email them using `send_mail_func` which should accept a single string argument which will be the traceback to be emailed. Will re-raise original exception if calling `send_mail_func`...
java
public void moveMessage(boolean discard) throws SIMPControllableNotFoundException, SIMPRuntimeOperationFailedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "moveMessage", Boolean.valueOf(discard)); ...
java
private void removeOldLogs() { try { Path path = getPath(); Path parent = path.getParent(); ArrayList<String> matchList = new ArrayList<String>(); Pattern archiveRegexp = getArchiveRegexp(); Files.list(parent).forEach(child->{ String subPath = child.getFileName().toString()...
python
def change(self) -> Tuple[bool, dict]: """ Default case, override in subclass as necessary. """ next = self.next self.next = None if self.next or not self.running: message = "The Scene.change interface is deprecated. Use the events commands instead." ...
python
def create_request_url(self, interface, method, version, parameters): """Create the URL to submit to the Steam Web API interface: Steam Web API interface containing methods. method: The method to call. version: The version of the method. paramters: Parameters to supply to the me...
java
private void pdb_EXPDTA_Handler(String line) { String technique ; if (line.length() > 69) technique = line.substring (10, 70).trim() ; else technique = line.substring(10).trim(); for (String singleTechnique: technique.split(";\\s+")) { pdbHeader.setExperimentalTechnique(singleTechnique); } }
java
public void createNewDatabaseServerSecurityDomain72(String securityDomainName, String dsJndiName, String principalsQuery, String rolesQuery, String hashAlgorithm, String hashEncoding) throws Exception { Address addr = Address.root().add(SUBSYSTEM, SUBSYSTEM_SECURITY, SECURITY_DOMAIN, se...
java
public static <T> BloomFilter<T> create(BiConsumer<? super T, ? super Hasher> funnel, int expectedInsertions) { return create(funnel, (long) expectedInsertions); }
java
public LoadZone getLoadZone(String id) { return invoke(LOAD_ZONES, id, null, null, new RequestClosure<JsonArray>() { @Override public JsonArray call(Invocation.Builder request) { return request.get(JsonArray.class); ...
java
protected void doDelete(int n) throws CorruptIndexException, IOException { if (transientDeletions) { deletedDocs.add(n); modCount.incrementAndGet(); // doDelete won't be executed, so incrementing modCount } else { super.doDelete(n); modCount.incrementAndGe...
java
public void marshall(BatchImportFindingsRequest batchImportFindingsRequest, ProtocolMarshaller protocolMarshaller) { if (batchImportFindingsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(b...
python
def _finish_filter(self, lst, key, include_self, exclusive, biggest_first): """Finish filtering a GIS operation. Can optionally exclude the input key, sort results, and exclude overlapping results. Internal function, not normally called directly.""" key = self._actual_key(key) locations = [x[0] ...
python
def _ParseCString(self, page_data, string_offset): """Parses a C string from the page data. Args: page_data (bytes): page data. string_offset (int): offset of the string relative to the start of the page. Returns: str: string. Raises: ParseError: when the string cann...
java
public final boolean ifContains(final String pName) { for (String key : integersMap.keySet()) { if (key.equals(pName)) { return true; } } for (String key : longsMap.keySet()) { if (key.equals(pName)) { return true; } } for (String key : floatsMap.keySet()) { ...
python
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])...
python
def start(self, phase, stage, **kwargs): """Start a new routine, stage or phase""" return ProgressSection(self, self._session, phase, stage, self._logger, **kwargs)
java
public CalendarPeriod GetCalendarPeriod() { CalendarPeriod res = new CalendarPeriod(); List<Period> periods = new ArrayList<Period>(); for( int i = 0; i < this.periods.size(); i++ ) { PeriodAssociative<T> p = this.periods.get( i ); periods.add( new Period( p.getFrom(), p.getTo() ) ); } // use merge t...
java
public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) { Validate.isTrue(cls != null, "The class must not be null"); Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty"); // FIXME is this workaround still needed...
python
def get_delegates(self, patient_id): """ invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :return: JSON response """ magic = self._magic_json( action=TouchWorksMagicConstants.ACTION_GET_DELEGATES, app_name=self._app_name, ...
python
def compact(paths): """Compact a path set to contain the minimal number of paths necessary to contain all paths in the set. If /a/path/ and /a/path/to/a/file.txt are both in the set, leave only the shorter path.""" sep = os.path.sep short_paths = set() for path in sorted(paths, key=len): ...
java
public static <R extends Random> void using( final R random, final Consumer<? super R> consumer ) { CONTEXT.with(() -> random, r -> { consumer.accept(random); return null; }); }
java
private void addDisabledExamples() { add(new WHeading(HeadingLevel.H2, "Disabled WCheckBoxSelect examples")); WFieldLayout layout = new WFieldLayout(); add(layout); WCheckBoxSelect select = new WCheckBoxSelect("australian_state"); select.setDisabled(true); layout.addField("Disabled with no default selectio...
java
protected boolean producesOneRowOutput () { if (m_tableAliasMap.size() != 1) { return false; } // Get the table. There's only one. StmtTableScan scan = m_tableAliasMap.values().iterator().next(); Table table = getTableFromDB(scan.getTableName()); // May be s...
python
def scan(): """ scan for available ports. return a list of tuples (num, name) Returns: """ available = [] for i in range(256): try: s = serial.Serial('COM'+str(i)) available.append((i, s.portstr)) s.close() except serial.SerialException: ...
java
public UpdateMethodResult withRequestModels(java.util.Map<String, String> requestModels) { setRequestModels(requestModels); return this; }
python
def _parse_plt_segment(self, fptr): """Parse the PLT segment. The packet headers are not parsed, i.e. they remain uninterpreted raw data buffers. Parameters ---------- fptr : file Open file object. Returns ------- PLTSegment ...
python
def daily_occurrences(self, dt=None): ''' Convenience method wrapping ``Occurrence.objects.daily_occurrences``. ''' return Occurrence.objects.daily_occurrences(dt=dt, event=self)
python
def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O """ get len of transitive closure assume type items is tree... """ return len(item[1]) + sum(tcsort(kv) for kv in item[1].items())
java
public PagedList<RouteFilterRuleInner> listByRouteFilter(final String resourceGroupName, final String routeFilterName) { ServiceResponse<Page<RouteFilterRuleInner>> response = listByRouteFilterSinglePageAsync(resourceGroupName, routeFilterName).toBlocking().single(); return new PagedList<RouteFilterRule...
java
@Override public int compare(String o1, String o2) { if (C_ELEMENT_SYMBOL.equals(o1)) { if (C_ELEMENT_SYMBOL.equals(o2)) { return 0; } else { return -1; } } else if (H_ELEMENT_SYMBOL.equals(o1)) { if (C_ELEMENT_SYMBOL.eq...
python
def add_fileformat(self, fileformat): """ Add fileformat line to the header. Arguments: fileformat (str): The id of the info line """ self.fileformat = fileformat logger.info("Adding fileformat to vcf: {0}".format(fileformat)) return
java
@Override public void setNClob(String parameterName, Reader reader) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
python
def parse(self, words): """A general method for parsing word-representations of numbers. Supports floats and integers. Args: words (str): Description of an arbitrary number. Returns: A double representation of the words. """ def exact(words): ...
python
def json_numpy_obj_hook(dct): """Decodes a previously encoded numpy ndarray with proper shape and dtype. Parameters ---------- dct : :obj:`dict` The encoded dictionary. Returns ------- :obj:`numpy.ndarray` The ndarray that `dct` was encoding. """ if isinstance(dct, ...
python
def passageLoop(parent, new_tree, xpath1, xpath2=None, preceding_siblings=False, following_siblings=False): """ Loop over passages to construct and increment new tree given a parent and XPaths :param parent: Parent on which to perform xpath :param new_tree: Parent on which to add nodes :param xpath1: L...
python
def build_from_queue(cls, input_queue, replay_size, batch_size): """Builds a `ReplayableQueue` that draws from a regular `input_queue`. Args: input_queue: The queue to draw from. replay_size: The size of the replay buffer. batch_size: The size of each batch. Returns: A ReplayableQu...
java
public static <F, T> Copier<F, T> createCglib(Class<F> sourceClass, Class<T> targetClass) { return CopierFactory.getOrCreateCglibCopier(sourceClass, targetClass); }
java
@Beta public static <T> Consumer<T> sc(final Object mutex, final Consumer<T> consumer) { N.checkArgNotNull(mutex, "mutex"); N.checkArgNotNull(consumer, "consumer"); return new Consumer<T>() { @Override public void accept(T t) { synchronized (m...
python
def is_displayed(self): """ :return: False if element is not present in the DOM or invisible, otherwise True. Ignore implicit and element timeouts and execute immediately. To wait when element displayed or not, use ``waiter.wait_displayed`` or ``waiter.wait_not_displayed`` ...
java
@Override public Object put(String key, Object value) { DeserializationState deserializationState = _deserState.get(); if (deserializationState.isDeserialized()) { return deserializationState.deserialized.put(key, value); } return deserializationState.overrides.put(key, v...
java
public static ByteBuffer decodeURL(byte[] source, int off, int limit) throws IOException { return Decoder.decode(source, off, limit, true); }
python
def extend_peaks(self, prop_thresh=50): """Each peak in the peaks of the object is checked for its presence in other octaves. If it does not exist, it is created. prop_thresh is the cent range within which the peak in the other octave is expected to be present, i.e., only if ...
python
def is_port_profile_created(self, vlan_id, device_id): """Indicates if port profile has been created on UCS Manager.""" entry = self.session.query(ucsm_model.PortProfile).filter_by( vlan_id=vlan_id, device_id=device_id).first() return entry and entry.created_on_ucs
java
public static int hoursDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / HOUR_MILLIS) - (earlierDate.getTime() / HOUR_MILLIS)); }
python
def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2): ''' Separable kernels for convolution executed on the GPU device The outputted kernels are in this order: z, y, x ''' xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5) ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2...
python
def retrieve_exposure_classes_lists(exposure_keywords): """Retrieve exposures classes. Only if the exposure has some classifications. :param exposure_keywords: exposure keywords :type exposure_keywords: dict :return: lists of classes used in the classifications. :rtype: list(dict) """ ...
java
public <V> V convertFrom(final String text) { if (text == null) return null; return (V) convertFrom(Utility.charArray(text)); }
python
def create_security_group(self): # noqa """Send a POST to spinnaker to create or update a security group. Returns: boolean: True if created successfully Raises: ForemastConfigurationFileError: Missing environment configuration or misconfigured Security ...
python
def asdim(dimension): """Convert the input to a Dimension. Args: dimension: tuple, dict or string type to convert to Dimension Returns: A Dimension object constructed from the dimension spec. No copy is performed if the input is already a Dimension. """ if isinstance(dimens...
python
def _prop(self, rho, T, x): """Thermodynamic properties of ammonia-water mixtures Parameters ---------- T : float Temperature [K] rho : float Density [kg/m³] x : float Mole fraction of ammonia in mixture [mol/mol] Returns ...
java
private void trimCandidatesNotMeetingMinimumRequirements() { Iterator<Entry<String, FunctionState>> i; for (i = fns.entrySet().iterator(); i.hasNext(); ) { FunctionState functionState = i.next().getValue(); if (!functionState.hasExistingFunctionDefinition() || !functionState.canInline()) { i...
java
protected void marshallElementContent(XMLObject xmlObject, Element domElement) throws MarshallingException { GenderType gender = (GenderType) xmlObject; if (gender.getGender() != null && gender.getGender().getValue() != null) { XMLHelper.appendTextContent(domElement, gender.getGender().getValue()); } ...
java
public RgbaColor[] getPaletteVaryLightness(int count) { // a max of 80 and an offset of 10 keeps us away from the // edges float[] spread = getSpreadInRange(l(), count, 80, 10); RgbaColor[] ret = new RgbaColor[count]; for (int i = 0; i < count; i++) { ret[i] = withLig...
python
def instance(cls, public_keys_dir): '''Please avoid create multi instance''' if public_keys_dir in cls._authenticators: return cls._authenticators[public_keys_dir] new_instance = cls(public_keys_dir) cls._authenticators[public_keys_dir] = new_instance return new_insta...