language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def clean(self): """ >>> import django.forms >>> class MyForm(CleanWhiteSpacesMixin, django.forms.Form): ... some_field = django.forms.CharField() >>> >>> form = MyForm({'some_field': ' a weird value '}) >>> assert form.is_valid() >>> assert form.cleaned_data == {'some_field': 'a weird value'} """ cleaned_data = super(CleanWhiteSpacesMixin, self).clean() for k in self.cleaned_data: if isinstance(self.cleaned_data[k], six.string_types): cleaned_data[k] = re.sub(extra_spaces_pattern, ' ', self.cleaned_data[k] or '').strip() return cleaned_data
python
def select2_modelform_meta(model, meta_fields=None, widgets=None, attrs=None, **kwargs): """ Return `Meta` class with Select2-enabled widgets for fields with choices (e.g. ForeignKey, CharField, etc) for use with ModelForm. Arguments: model - a model class to create `Meta` class for. meta_fields - dictionary with `Meta` class fields, for example, {'fields': ['id', 'name']} attrs - select2 widget attributes (width, for example), must be of type `dict`. **kwargs - will be merged with meta_fields. """ widgets = widgets or {} meta_fields = meta_fields or {} # TODO: assert attrs is of type `dict` for field in model._meta.fields: if isinstance(field, ForeignKey) or field.choices: widgets.update({field.name: Select2(select2attrs=attrs)}) for field in model._meta.many_to_many: widgets.update({field.name: Select2Multiple(select2attrs=attrs)}) meta_fields.update({ 'model': model, 'widgets': widgets, }) if 'exclude' not in kwargs and 'fields' not in kwargs: meta_fields.update({'exclude': []}) meta_fields.update(**kwargs) meta = type('Meta', (object,), meta_fields) return meta
java
@SuppressWarnings("rawtypes") protected PojoPathFunction getFunction(String functionName, PojoPathContext context) throws ObjectNotFoundException { PojoPathFunction function = null; // context overrides functions... PojoPathFunctionManager manager = context.getAdditionalFunctionManager(); if (manager != null) { function = manager.getFunction(functionName); } if (function == null) { // global functions as fallback... manager = getFunctionManager(); if (manager != null) { function = manager.getFunction(functionName); } } if (function == null) { throw new ObjectNotFoundException(PojoPathFunction.class, functionName); } return function; }
python
def handle_qbytearray(obj, encoding): """Qt/Python2/3 compatibility helper.""" if isinstance(obj, QByteArray): obj = obj.data() return to_text_string(obj, encoding=encoding)
python
def unique_iter(seq): """ See http://www.peterbe.com/plog/uniqifiers-benchmark Originally f8 written by Dave Kirby """ seen = set() return [x for x in seq if x not in seen and not seen.add(x)]
python
def karma(nick, rest): "Return or change the karma value for some(one|thing)" karmee = rest.strip('++').strip('--').strip('~~') if '++' in rest: Karma.store.change(karmee, 1) elif '--' in rest: Karma.store.change(karmee, -1) elif '~~' in rest: change = random.choice([-1, 0, 1]) Karma.store.change(karmee, change) if change == 1: return "%s karma++" % karmee elif change == 0: return "%s karma shall remain the same" % karmee elif change == -1: return "%s karma--" % karmee elif '==' in rest: t1, t2 = rest.split('==') try: Karma.store.link(t1, t2) except SameName: Karma.store.change(nick, -1) return "Don't try to link a name to itself!" except AlreadyLinked: return "Those names were previously linked." score = Karma.store.lookup(t1) return "%s and %s are now linked and have a score of %s" % (t1, t2, score) else: karmee = rest or nick score = Karma.store.lookup(karmee) return "%s has %s karmas" % (karmee, score)
python
def relation(x_start, x_end, y_start, y_end): """ Returns the relation between two intervals. :param int x_start: The start point of the first interval. :param int x_end: The end point of the first interval. :param int y_start: The start point of the second interval. :param int y_end: The end point of the second interval. :rtype: int|None """ if (x_end - x_start) < 0 or (y_end - y_start) < 0: return None diff_end = y_end - x_end if diff_end < 0: return -Allen.relation(y_start, y_end, x_start, x_end) diff_start = y_start - x_start gab = y_start - x_end if diff_end == 0: if diff_start == 0: return Allen.X_EQUAL_Y if diff_start < 0: return Allen.X_FINISHES_Y return Allen.X_FINISHES_Y_INVERSE if gab > 1: return Allen.X_BEFORE_Y if gab == 1: return Allen.X_MEETS_Y if diff_start > 0: return Allen.X_OVERLAPS_WITH_Y if diff_start == 0: return Allen.X_STARTS_Y if diff_start < 0: return Allen.X_DURING_Y
python
def dict_merge(a, b): """ Recursively merge dicts. recursively merges dict's. not just simple a['key'] = b['key'], if both a and bhave a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. @see http://www.xormedia.com/recursively-merge-dictionaries-in-python/ """ if not isinstance(b, dict): return b result = deepcopy(a) for k, v in b.iteritems(): if k in result and isinstance(result[k], dict): result[k] = dict_merge(result[k], v) else: result[k] = deepcopy(v) return result
java
public static boolean isEmpty(String value) { int strLen; if (value == null || (strLen = value.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if ((Character.isWhitespace(value.charAt(i)) == false)) { return false; } } return true; }
python
def GE(classical_reg1, classical_reg2, classical_reg3): """ Produce an GE instruction. :param classical_reg1: Memory address to which to store the comparison result. :param classical_reg2: Left comparison operand. :param classical_reg3: Right comparison operand. :return: A ClassicalGreaterEqual instance. """ classical_reg1, classical_reg2, classical_reg3 = prepare_ternary_operands(classical_reg1, classical_reg2, classical_reg3) return ClassicalGreaterEqual(classical_reg1, classical_reg2, classical_reg3)
java
public void setLicenseType(com.google.api.ads.admanager.axis.v201811.LicenseType licenseType) { this.licenseType = licenseType; }
python
def close(self): """Close all connections """ keys = set(self._conns.keys()) for key in keys: self.stop_socket(key) self._conns = {}
python
def calc_csd(self): """ Sum all the CSD contributions from every layer. """ CSDarray = np.array([]) CSDdict = {} i = 0 for y in self.y: fil = os.path.join(self.populations_path, self.output_file.format(y, 'CSD.h5')) f = h5py.File(fil) if i == 0: CSDarray = np.zeros((len(self.y), f['data'].shape[0], f['data'].shape[1])) #fill in CSDarray[i, ] = f['data'].value CSDdict.update({y : f['data'].value}) f.close() i += 1 return CSDdict, CSDarray.sum(axis=0)
java
void set_composite_vector() { composite_.clear(); for (Document<K> document : documents_) { composite_.add_vector(document.feature()); } }
python
def get_reserved_resources(role=None): """ resource types from state summary include: reserved_resources :param role: the name of the role if for reserved and if None all reserved :type role: str :return: resources(cpu,mem) :rtype: Resources """ rtype = 'reserved_resources' cpus = 0.0 mem = 0.0 summary = DCOSClient().get_state_summary() if 'slaves' in summary: agents = summary.get('slaves') for agent in agents: resource_reservations = agent.get(rtype) reservations = [] if role is None or '*' in role: reservations = resource_reservations.values() elif role in resource_reservations: reservations = [resource_reservations.get(role)] for reservation in reservations: if reservation.get('cpus') is not None: cpus += reservation.get('cpus') if reservation.get('mem') is not None: mem += reservation.get('mem') return Resources(cpus, mem)
java
@Override public List<IScan> parse(LCMSDataSubset subset) throws FileParsingException { I idx = fetchIndex(); // make sure, that the index is parsed if (idx.getMapByNum().isEmpty()) { // if the index was empty - there's nothing to parse return Collections.emptyList(); } LCMSRunInfo inf = fetchRunInfo(); // make sure we have the runInfo // figure out which scans are to be read NavigableMap<Integer, E> idxMap = idx.getMapByNum(); Integer scanNumLo = subset.getScanNumLo() == null ? idxMap.firstKey() : idxMap.ceilingKey(subset.getScanNumLo()); ; Integer scanNumHi = subset.getScanNumHi() == null ? idxMap.lastKey() : idxMap.floorKey(subset.getScanNumHi()); NavigableMap<Integer, E> subIdx = idxMap.subMap(scanNumLo, true, scanNumHi, true); if (subIdx.isEmpty()) { throw new FileParsingException( "The run does not contain any spectra in the number range you provided!"); } List<IScan> scans = new ArrayList<>(subIdx.size()); int numThreads = getNumThreadsForParsing(); int numSpectraPerThread = getTasksPerCpuPerBatch(); ExecutorService exec = Executors.newFixedThreadPool(numThreads); Set<? extends Map.Entry<Integer, ? extends XMLBasedIndexElement>> entrySet = subIdx.entrySet(); Iterator<? extends Map.Entry<Integer, ? extends XMLBasedIndexElement>> idxEntriesIter = entrySet .iterator(); // set up read buffers int readLen = 1 << 18; // 256k default read buffer size byte[] readBuf1 = new byte[readLen]; byte[] readBuf2 = new byte[readLen]; byte[] readBufTmp; try { RandomAccessFile raf = this.getRandomAccessFile(); ArrayList<OffsetLength> readTasks = null; do { // This is needed for cancellable tasks if (Thread.interrupted()) { log.debug( "Main AbstractXMLBasedDataSource read thread was interrupted, parsing cancelled."); throw new FileParsingException("Thread interrupted, parsing was cancelled."); } // check if we have read something in the previous iteration, if we did, then use the 2nd read buffer if (readTasks != null && !readTasks.isEmpty()) { // if we did read something on the previous iteration before submitting parsing tasks, use it // just flip buffers readBufTmp = readBuf1; readBuf1 = readBuf2; readBuf2 = readBufTmp; } else { // figure out which spectra to read in this batch and read them int numScansToRead = numThreads * numSpectraPerThread; readTasks = new ArrayList<>(numScansToRead); readBuf1 = readContinuousBatchOfSpectra(idxEntriesIter, raf, readBuf1, readTasks, numScansToRead); } // distribute the spectra between workers int[] workerScanCounts = distributeParseLoad(numThreads, readTasks); // submit the tasks to executor service ArrayList<Future<List<IScan>>> parseTasks = submitParseTasks(subset, runInfo, numThreads, exec, readBuf1, readTasks, workerScanCounts, true); // before blocking on waiting for the parsing tasks to complete, // initiate another read // figure out which spectra to read in this batch and read them int maxScansToReadInBatch = numThreads * numSpectraPerThread; readTasks = new ArrayList<>(maxScansToReadInBatch); if (idxEntriesIter.hasNext()) { readBuf2 = readContinuousBatchOfSpectra(idxEntriesIter, raf, readBuf2, readTasks, maxScansToReadInBatch); } // block and wait for all the parsers to finish, at this point // we already have the next chunk read-in while the parsers were busy for (Future<List<IScan>> parseTask : parseTasks) { try { List<IScan> parsedScans = parseTask.get(getParsingTimeout(), TimeUnit.SECONDS); if (parsedScans != null) { for (IScan scan : parsedScans) { scans.add(scan); } } } catch (InterruptedException | TimeoutException | ExecutionException | NullPointerException e) { throw new FileParsingException(e); } } } while (idxEntriesIter.hasNext() || !readTasks.isEmpty()); this.close(); } catch (IOException ex) { throw new FileParsingException(ex); } finally { this.close(); exec.shutdown(); } // wait for the executor pool to shut down try { exec.awaitTermination(getParsingTimeout(), TimeUnit.SECONDS); } catch (InterruptedException e) { throw new FileParsingException( String.format("Executor pool failed to shut down in %d sec!", getParsingTimeout()), e); } return scans; }
java
@PostConstruct public void initialize() { final IRI root = rdf.createIRI(TRELLIS_DATA_PREFIX); final IRI rootAuth = rdf.createIRI(TRELLIS_DATA_PREFIX + "#auth"); try (final TrellisDataset dataset = TrellisDataset.createDataset()) { dataset.add(rdf.createQuad(Trellis.PreferAccessControl, rootAuth, ACL.mode, ACL.Read)); dataset.add(rdf.createQuad(Trellis.PreferAccessControl, rootAuth, ACL.mode, ACL.Write)); dataset.add(rdf.createQuad(Trellis.PreferAccessControl, rootAuth, ACL.mode, ACL.Control)); dataset.add(rdf.createQuad(Trellis.PreferAccessControl, rootAuth, ACL.agentClass, FOAF.Agent)); dataset.add(rdf.createQuad(Trellis.PreferAccessControl, rootAuth, ACL.accessTo, root)); LOGGER.debug("Preparing to initialize Trellis at {}", root); trellis.getResourceService().get(root).thenCompose(res -> initialize(root, res, dataset)) .exceptionally(err -> { LOGGER.warn("Unable to auto-initialize Trellis: {}. See DEBUG log for more info", err.getMessage()); LOGGER.debug("Error auto-initializing Trellis", err); return null; }).toCompletableFuture().join(); } }
python
def show_linkinfo_output_show_link_info_linkinfo_version(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_linkinfo = ET.Element("show_linkinfo") config = show_linkinfo output = ET.SubElement(show_linkinfo, "output") show_link_info = ET.SubElement(output, "show-link-info") linkinfo_rbridgeid_key = ET.SubElement(show_link_info, "linkinfo-rbridgeid") linkinfo_rbridgeid_key.text = kwargs.pop('linkinfo_rbridgeid') linkinfo_version = ET.SubElement(show_link_info, "linkinfo-version") linkinfo_version.text = kwargs.pop('linkinfo_version') callback = kwargs.pop('callback', self._callback) return callback(config)
java
private void addClickHandlerToCheckBox(final CmsCheckBox check, final Widget unzipWidget, final CmsFileInfo file) { check.addClickHandler(new ClickHandler() { /** * @see com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event.dom.client.ClickEvent) */ public void onClick(ClickEvent event) { // add or remove the file from the list of files to upload if (check.isChecked()) { getFilesToUpload().put(file.getFileName(), file); if (unzipWidget != null) { enableUnzip(unzipWidget); } } else { getFilesToUpload().remove(file.getFileName()); if (unzipWidget != null) { disableUnzip(unzipWidget); } } // disable or enable the OK button if (getFilesToUpload().isEmpty()) { disableOKButton(Messages.get().key(Messages.GUI_UPLOAD_NOTIFICATION_NO_FILES_0)); } else { enableOKButton(); } // update summary updateSummary(); } /** * Disables the 'unzip' button * * @param unzip the unzip button */ private void disableUnzip(Widget unzip) { ((CmsToggleButton)unzip).setEnabled(false); } /** * Enables the 'unzip' button * * @param unzip the unzip button */ private void enableUnzip(Widget unzip) { ((CmsToggleButton)unzip).setEnabled(true); } }); }
java
public void syntaxError(String state, String event, List<String> legalEvents, String uri, Integer line) { formatter.syntaxError(state, event, legalEvents, uri, line); }
python
def to_ipv6(key): """Get IPv6 address from a public key.""" if key[-2:] != '.k': raise ValueError('Key does not end with .k') key_bytes = base32.decode(key[:-2]) hash_one = sha512(key_bytes).digest() hash_two = sha512(hash_one).hexdigest() return ':'.join([hash_two[i:i+4] for i in range(0, 32, 4)])
python
def generate_categories(): """Generates the categories JSON data file from the unicode specification. :return: True for success, raises otherwise. :rtype: bool """ # inspired by https://gist.github.com/anonymous/2204527 code_points_ranges = [] iso_15924_aliases = [] categories = [] match = re.compile(r'([0-9A-F]+)(?:\.\.([0-9A-F]+))?\W+(\w+)\s*#\s*(\w+)', re.UNICODE) url = 'ftp://ftp.unicode.org/Public/UNIDATA/Scripts.txt' file = get(url) for line in file: p = re.findall(match, line) if p: code_point_range_from, code_point_range_to, alias, category = p[0] alias = u(alias.upper()) category = u(category) if alias not in iso_15924_aliases: iso_15924_aliases.append(alias) if category not in categories: categories.append(category) code_points_ranges.append(( int(code_point_range_from, 16), int(code_point_range_to or code_point_range_from, 16), iso_15924_aliases.index(alias), categories.index(category)) ) code_points_ranges.sort() categories_data = { 'iso_15924_aliases': iso_15924_aliases, 'categories': categories, 'code_points_ranges': code_points_ranges, } dump('categories.json', categories_data)
python
def importFile(self, srcUrl, sharedFileName=None, hardlink=False): """ Imports the file at the given URL into job store. The ID of the newly imported file is returned. If the name of a shared file name is provided, the file will be imported as such and None is returned. Currently supported schemes are: - 's3' for objects in Amazon S3 e.g. s3://bucket/key - 'wasb' for blobs in Azure Blob Storage e.g. wasb://container/blob - 'file' for local files e.g. file:///local/file/path - 'http' e.g. http://someurl.com/path - 'gs' e.g. gs://bucket/file :param str srcUrl: URL that points to a file or object in the storage mechanism of a supported URL scheme e.g. a blob in an Azure Blob Storage container. :param str sharedFileName: Optional name to assign to the imported file within the job store :return: The jobStoreFileId of the imported file or None if sharedFileName was given :rtype: toil.fileStore.FileID or None """ # Note that the helper method _importFile is used to read from the source and write to # destination (which is the current job store in this case). To implement any # optimizations that circumvent this, the _importFile method should be overridden by # subclasses of AbstractJobStore. srcUrl = urlparse.urlparse(srcUrl) otherCls = self._findJobStoreForUrl(srcUrl) return self._importFile(otherCls, srcUrl, sharedFileName=sharedFileName, hardlink=hardlink)
python
def save(self, *args, **kwargs): """ BUG: Django save-the-change, which all oTree models inherit from, doesn't recognize changes to JSONField properties. So saving the model won't trigger a database save. This is a hack, but fixes it so any JSONFields get updated every save. oTree uses a forked version of save-the-change so a good alternative might be to fix that to recognize JSONFields (diff them at save time, maybe?). """ super().save(*args, **kwargs) if self.pk is not None: update_fields = kwargs.get('update_fields') json_fields = {} for field in self._meta.get_fields(): if isinstance(field, JSONField) and (update_fields is None or field.attname in update_fields): json_fields[field.attname] = getattr(self, field.attname) self.__class__._default_manager.filter(pk=self.pk).update(**json_fields)
java
public void addCondition( Condition condition, String transitionName ){ conditions.add( Pair.of( condition, transitionName ) ); }
java
@Override public void close() throws IOException { if (!_closed) { _closed = true; _nodeCursor = null; _currToken = null; } }
python
def set_plot_CO_mass(self,fig=3123,xaxis='mass',linestyle=['-'],marker=['o'],color=['r'],age_years=True,sparsity=500,markersparsity=200,withoutZlabel=False,t0_model=[]): ''' PLots C/O surface number fraction ''' if len(t0_model)==0: t0_model = len(self.runs_H5_surf)*[0] plt.figure(fig) for i in range(len(self.runs_H5_surf)): sefiles=se(self.runs_H5_surf[i]) cycles=range(int(sefiles.se.cycles[0]),int(sefiles.se.cycles[-1]),sparsity) mini=sefiles.get("mini") zini=sefiles.get("zini") label=str(mini)+'$M_{\odot}$, Z='+str(zini) if xaxis=='cycles': x=cycles if xaxis=='age': x=sefiles.get(cycles,'age') if age_years==True: x=np.array(x)*sefiles.get('age_unit')/(365*24*3600) x = x - x[t0_model[i]] if xaxis=='mass': x=sefiles.get(cycles,'mass') x=x[t0_model[i]:] c12=sefiles.get(cycles,'C-12')[t0_model[i]:] o16=sefiles.get(cycles,'O-16')[t0_model[i]:] if withoutZlabel==True: plt.plot(x,4./3.*np.array(c12)/np.array(o16),label=label.split(',')[0],marker=marker[i],linestyle=linestyle[i],markevery=markersparsity,color=color[i]) else: plt.plot(x,4./3.*np.array(c12)/np.array(o16),label=label,marker=marker[i],linestyle=linestyle[i],markevery=markersparsity,color=color[i]) if xaxis=='mass': plt.xlim(7,0.5) #plt.gca().invert_xaxis() plt.xlabel('$M/M_{\odot}$',fontsize=18) plt.ylabel('C/O Ratio', fontsize=18) plt.legend(loc=1)
python
def to_next_bank(self): """ Change the current :class:`Bank` for the next bank. If the current bank is the last, the current bank is will be the first bank. The current pedalboard will be the first pedalboard of the new current bank **if it contains any pedalboard**, else will be ``None``. .. warning:: If the current :attr:`.pedalboard` is ``None``, a :class:`.CurrentPedalboardError` is raised. """ if self.pedalboard is None: raise CurrentPedalboardError('The current pedalboard is None') next_index = self.next_bank_index(self.bank.index) self.set_bank(self._manager.banks[next_index])
java
private static <X extends CopyableValue<X>> CopyableValueSerializer<X> createCopyableValueSerializer(Class<X> clazz) { return new CopyableValueSerializer<X>(clazz); }
java
public boolean recordConstancy() { if (!currentInfo.hasConstAnnotation()) { currentInfo.setConstant(true); populated = true; return true; } else { return false; } }
java
@SuppressWarnings("unchecked") protected Map<String, Collection<AttributeBean>> getAttributeMap(EvaluationCtx eval) throws URISyntaxException { final URI defaultCategoryURI = SUBJECT_CATEGORY_DEFAULT; Map<String, String> im = null; Map<String, Collection<AttributeBean>> attributeMap = new HashMap<String, Collection<AttributeBean>>(); Map<String, AttributeBean> attributeBeans = null; im = indexMap.get(SUBJECT_KEY); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getSubjectAttribute(new URI(im.get(attributeId)), new URI(attributeId), defaultCategoryURI); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put(SUBJECT_KEY, attributeBeans.values()); im = indexMap.get(RESOURCE_KEY); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getResourceAttribute(new URI(im.get(attributeId)), new URI(attributeId), null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } if (attributeId.equals(XACML_RESOURCE_ID) && value.encode().startsWith("/")) { String[] components = makeComponents(value.encode()); if (components != null && components.length > 0) { for (String c : components) { ab.addValue(c); } } else { ab.addValue(value.encode()); } } else { ab.addValue(value.encode()); } } } } } } attributeMap.put(RESOURCE_KEY, attributeBeans.values()); im = indexMap.get(ACTION_KEY); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { EvaluationResult result = eval.getActionAttribute(new URI(im.get(attributeId)), new URI(attributeId), null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put(ACTION_KEY, attributeBeans.values()); im = indexMap.get(ENVIRONMENT_KEY); attributeBeans = new HashMap<String, AttributeBean>(); for (String attributeId : im.keySet()) { URI imAttrId = new URI(im.get(attributeId)); URI attrId = new URI(attributeId); EvaluationResult result = eval.getEnvironmentAttribute(imAttrId, attrId, null); if (result.getStatus() == null && !result.indeterminate()) { AttributeValue attr = result.getAttributeValue(); if (attr.returnsBag()) { Iterator<AttributeValue> i = ((BagAttribute) attr).iterator(); if (i.hasNext()) { while (i.hasNext()) { AttributeValue value = i.next(); String attributeType = im.get(attributeId); AttributeBean ab = attributeBeans.get(attributeId); if (ab == null) { ab = new AttributeBean(); ab.setId(attributeId); ab.setType(attributeType); attributeBeans.put(attributeId, ab); } ab.addValue(value.encode()); } } } } } attributeMap.put(ENVIRONMENT_KEY, attributeBeans.values()); return attributeMap; }
python
def calibrate(self, data, calibration): """Calibrate the data""" tic = datetime.now() if calibration == 'counts': return data if calibration in ['radiance', 'reflectance', 'brightness_temperature']: data = self.convert_to_radiance(data) if calibration == 'reflectance': data = self._vis_calibrate(data) elif calibration == 'brightness_temperature': data = self._ir_calibrate(data) logger.debug("Calibration time " + str(datetime.now() - tic)) return data
python
def list_nodes_full(**kwargs): ''' Return all data on nodes ''' nodes = _query('server/list') ret = {} for node in nodes: name = nodes[node]['label'] ret[name] = nodes[node].copy() ret[name]['id'] = node ret[name]['image'] = nodes[node]['os'] ret[name]['size'] = nodes[node]['VPSPLANID'] ret[name]['state'] = nodes[node]['status'] ret[name]['private_ips'] = nodes[node]['internal_ip'] ret[name]['public_ips'] = nodes[node]['main_ip'] return ret
python
def user(name, id='', user='', priv='', password='', status='active'): ''' Ensures that a user is configured on the device. Due to being unable to verify the user password. This is a forced operation. .. versionadded:: 2019.2.0 name: The name of the module function to execute. id(int): The user ID slot on the device. user(str): The username of the user. priv(str): The privilege level of the user. password(str): The password of the user. status(str): The status of the user. Can be either active or inactive. SLS Example: .. code-block:: yaml user_configuration: cimc.user: - id: 11 - user: foo - priv: admin - password: mypassword - status: active ''' ret = _default_ret(name) user_conf = __salt__['cimc.get_users']() try: for entry in user_conf['outConfigs']['aaaUser']: if entry['id'] == str(id): conf = entry if not conf: ret['result'] = False ret['comment'] = "Unable to find requested user id on device. Please verify id is valid." return ret updates = __salt__['cimc.set_user'](str(id), user, password, priv, status) if 'outConfig' in updates: ret['changes']['before'] = conf ret['changes']['after'] = updates['outConfig']['aaaUser'] ret['comment'] = "User settings modified." else: ret['result'] = False ret['comment'] = "Error setting user configuration." return ret except Exception as err: ret['result'] = False ret['comment'] = "Error setting user configuration." log.error(err) return ret ret['result'] = True return ret
java
@Override public java.util.concurrent.Future<SetQueueAttributesResult> setQueueAttributesAsync(String queueUrl, java.util.Map<String, String> attributes, com.amazonaws.handlers.AsyncHandler<SetQueueAttributesRequest, SetQueueAttributesResult> asyncHandler) { return setQueueAttributesAsync(new SetQueueAttributesRequest().withQueueUrl(queueUrl).withAttributes(attributes), asyncHandler); }
python
def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, pad_idx:int=1) -> nn.Module: "Create a text classifier from `arch` and its `config`, maybe `pretrained`." meta = _model_meta[arch] config = ifnone(config, meta['config_clas'].copy()) for k in config.keys(): if k.endswith('_p'): config[k] *= drop_mult if lin_ftrs is None: lin_ftrs = [50] if ps is None: ps = [0.1]*len(lin_ftrs) layers = [config[meta['hid_name']] * 3] + lin_ftrs + [n_class] ps = [config.pop('output_p')] + ps init = config.pop('init') if 'init' in config else None encoder = MultiBatchEncoder(bptt, max_len, arch(vocab_sz, **config), pad_idx=pad_idx) model = SequentialRNN(encoder, PoolingLinearClassifier(layers, ps)) return model if init is None else model.apply(init)
python
def table(self, table): """Returns the provided Spark SQL table as a L{DataFrame} Parameters ---------- table: string The name of the Spark SQL table to turn into a L{DataFrame} Returns ------- Sparkling Pandas DataFrame. """ return DataFrame.from_spark_rdd(self.sql_ctx.table(table), self.sql_ctx)
java
public int getIntHeader(String name) { if (_header != null) { int headerVal = _header.getIntHeader(name); if (headerVal != -1) return headerVal; } if (this.headerTable != null) { int i = 0; for (Object obj : headerTable[0]) { String strVal = (String) obj; if (name.equals(strVal)) { return Integer.valueOf((String) headerTable[1].get(i)); } i++; } } return -1; }
python
def endSubscription(self, subscriber): """ Unregister a live subscription. """ self._reqId2Contract.pop(subscriber.reqId, None) self.reqId2Subscriber.pop(subscriber.reqId, None)
java
private static StackTraceElement normalizeClassName(final StackTraceElement element) { String className = element.getClassName(); int dollarIndex = className.indexOf("$"); if (dollarIndex == -1) { return element; } else { className = stripAnonymousPart(className); return new StackTraceElement(className, element.getMethodName(), element.getFileName(), element.getLineNumber()); } }
java
public int dimensions(Type t) { int result = 0; while (t.hasTag(ARRAY)) { result++; t = elemtype(t); } return result; }
java
public int compareTo(TextIntWritable o) { int c = t.compareTo(o.t); if (c != 0) return c; return position - o.position; }
java
public void saveTo(File propertyFile) throws IOException { Properties props = new Properties(); props.put("username", username); props.put("key", accessKey); FileOutputStream out = new FileOutputStream(propertyFile); try { props.store(out, "Sauce OnDemand access credential"); } finally { out.close(); } }
python
def from_json(json_data): """ Returns a pyalveo.OAuth2 given a json string built from the oauth.to_json() method. """ #If we have a string, then decode it, otherwise assume it's already decoded if isinstance(json_data, str): data = json.loads(json_data) else: data = json_data oauth = Cache(cache_dir=data.get('cache_dir',None), max_age=data.get('max_age',None)) return oauth
java
@Override protected List<Resource> prepareTreeItems(ResourceHandle resource, List<Resource> items) { if (!nodesConfig.getOrderableNodesFilter().accept(resource)) { Collections.sort(items, new Comparator<Resource>() { @Override public int compare(Resource r1, Resource r2) { return getSortName(r1).compareTo(getSortName(r2)); } }); } return items; }
java
public static HashMap<String, String> resolveIds(final TSDB tsdb, final ArrayList<byte[]> tags) throws NoSuchUniqueId { try { return resolveIdsAsync(tsdb, tags).joinUninterruptibly(); } catch (NoSuchUniqueId e) { throw e; } catch (DeferredGroupException e) { final Throwable ex = Exceptions.getCause(e); if (ex instanceof NoSuchUniqueId) { throw (NoSuchUniqueId)ex; } // TODO process e.results() throw new RuntimeException("Shouldn't be here", e); } catch (Exception e) { throw new RuntimeException("Shouldn't be here", e); } }
python
async def Prune(self, max_history_mb, max_history_time): ''' max_history_mb : int max_history_time : int Returns -> None ''' # map input types to rpc msg _params = dict() msg = dict(type='ActionPruner', request='Prune', version=1, params=_params) _params['max-history-mb'] = max_history_mb _params['max-history-time'] = max_history_time reply = await self.rpc(msg) return reply
java
public FieldPresenceEnvelope getFieldPresence(Long startDate, Long endDate, String interval, String sdid, String fieldPresence) throws ApiException { ApiResponse<FieldPresenceEnvelope> resp = getFieldPresenceWithHttpInfo(startDate, endDate, interval, sdid, fieldPresence); return resp.getData(); }
java
@Override public IssueResponse issue(String CorpNum, MgtKeyType KeyType, String MgtKey, String Memo) throws PopbillException { return issue(CorpNum, KeyType, MgtKey, Memo, null); }
python
def enable_directory_service(self, check_peer=False): """Enable the directory service. :param check_peer: If True, enables server authenticity enforcement. If False, enables directory service integration. :type check_peer: bool, optional :returns: A dictionary describing the status of the directory service. :rtype: ResponseDict """ if check_peer: return self.set_directory_service(check_peer=True) return self.set_directory_service(enabled=True)
python
def sort(self): """ Sort the tribe, sorts by template name. .. rubric:: Example >>> tribe = Tribe(templates=[Template(name='c'), Template(name='b'), ... Template(name='a')]) >>> tribe.sort() Tribe of 3 templates >>> tribe[0] # doctest: +NORMALIZE_WHITESPACE Template a: 0 channels; lowcut: None Hz; highcut: None Hz; sampling rate None Hz; filter order: None; process length: None s """ self.templates = sorted(self.templates, key=lambda x: x.name) return self
python
def filter_that(self, criteria, data): ''' this method just use the module 're' to check if the data contain the string to find ''' import re prog = re.compile(criteria) return True if prog.match(data) else False
java
List<Expression> parseArrayValueList( IType componentType ) { while( componentType instanceof TypeVariableType ) { componentType = ((TypeVariableType)componentType).getBoundingType(); } List<Expression> valueExpressions = new ArrayList<>(); do { parseExpression( new ContextType( componentType ) ); Expression e = popExpression(); valueExpressions.add( e ); } while( match( null, ',' ) ); return valueExpressions; }
python
def _PrintEnums(proto_printer, enum_types): """Print all enums to the given proto_printer.""" enum_types = sorted(enum_types, key=operator.attrgetter('name')) for enum_type in enum_types: proto_printer.PrintEnum(enum_type)
java
public double[] map( Map<String, Double> row, double data[] ) { String[] colNames = getNames(); for( int i=0; i<colNames.length-1; i++ ) { Double d = row.get(colNames[i]); data[i] = d==null ? Double.NaN : d; } return data; }
java
public int[] getSelectedComponents () { int[] values = new int[_selected.size()]; Iterator<Integer> iter = _selected.values().iterator(); for (int ii = 0; iter.hasNext(); ii++) { values[ii] = iter.next().intValue(); } return values; }
java
private DefiningClassLoader getQueryClassLoader(CubeClassLoaderCache.Key key) { if (classLoaderCache == null) return classLoader; return classLoaderCache.getOrCreate(key); }
python
def new_transfer_transaction(self, asset: str, b58_from_address: str, b58_to_address: str, amount: int, b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction: """ This interface is used to generate a Transaction object for transfer. :param asset: a string which is used to indicate which asset we want to transfer. :param b58_from_address: a base58 encode address which indicate where the asset from. :param b58_to_address: a base58 encode address which indicate where the asset to. :param amount: the amount of asset that will be transferred. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which can be used for transfer. """ if not isinstance(b58_from_address, str) or not isinstance(b58_to_address, str) or not isinstance( b58_payer_address, str): raise SDKException(ErrorCode.param_err('the data type of base58 encode address should be the string.')) if len(b58_from_address) != 34 or len(b58_to_address) != 34 or len(b58_payer_address) != 34: raise SDKException(ErrorCode.param_err('the length of base58 encode address should be 34 bytes.')) if amount <= 0: raise SDKException(ErrorCode.other_error('the amount should be greater than than zero.')) if gas_price < 0: raise SDKException(ErrorCode.other_error('the gas price should be equal or greater than zero.')) if gas_limit < 0: raise SDKException(ErrorCode.other_error('the gas limit should be equal or greater than zero.')) contract_address = self.get_asset_address(asset) raw_from = Address.b58decode(b58_from_address).to_bytes() raw_to = Address.b58decode(b58_to_address).to_bytes() raw_payer = Address.b58decode(b58_payer_address).to_bytes() state = [{"from": raw_from, "to": raw_to, "amount": amount}] invoke_code = build_native_invoke_code(contract_address, b'\x00', "transfer", state) return Transaction(0, 0xd1, int(time()), gas_price, gas_limit, raw_payer, invoke_code, bytearray(), list())
python
def _order_antisense_column(cov_file, min_reads): """ Move counts to score columns in bed file """ new_cov = op.join(op.dirname(cov_file), 'feat_antisense.txt') with open(cov_file) as in_handle: with open(new_cov, 'w') as out_handle: print("name\tantisense", file=out_handle, end="") for line in in_handle: cols = line.strip().split("\t") cols[6] = 0 if cols[6] < min_reads else cols[6] print("%s\t%s" % (cols[3], cols[6]), file=out_handle, end="") return new_cov
java
public void addImplicitHydrogens(IAtomContainer container, IAtom atom) throws CDKException { if (atom.getAtomTypeName() == null) throw new CDKException("IAtom is not typed! " + atom.getSymbol()); if ("X".equals(atom.getAtomTypeName())) { if (atom.getImplicitHydrogenCount() == null) atom.setImplicitHydrogenCount(0); return; } IAtomType type = atomTypeList.getAtomType(atom.getAtomTypeName()); if (type == null) throw new CDKException("Atom type is not a recognized CDK atom type: " + atom.getAtomTypeName()); if (type.getFormalNeighbourCount() == CDKConstants.UNSET) throw new CDKException( "Atom type is too general; cannot decide the number of implicit hydrogen to add for: " + atom.getAtomTypeName()); // very simply counting: each missing explicit neighbor is a missing hydrogen atom.setImplicitHydrogenCount(type.getFormalNeighbourCount() - container.getConnectedBondsCount(atom)); }
java
public static String ipV6Address() { StringBuffer sb = new StringBuffer(); sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535))); sb.append(":"); sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535))); sb.append(":"); sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535))); sb.append(":"); sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535))); sb.append(":"); sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535))); sb.append(":"); sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535))); sb.append(":"); sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535))); sb.append(":"); sb.append(String.format("%04X", JDefaultNumber.randomIntBetweenTwoNumbers(1, 65535))); return sb.toString(); }
java
public static byte[] longToBytes(long rmid) { return new byte[] { (byte)(rmid>>56), (byte)(rmid>>48), (byte)(rmid>>40), (byte)(rmid>>32), (byte)(rmid>>24), (byte)(rmid>>16), (byte)(rmid>>8), (byte)(rmid)}; }
python
def create_cfg_segment(filename, filecontent, description, auth, url): """ Takes a str into var filecontent which represents the entire content of a configuration segment, or partial configuration file. Takes a str into var description which represents the description of the configuration segment :param filename: str containing the name of the configuration segment. :param filecontent: str containing the entire contents of the configuration segment :param description: str contrianing the description of the configuration segment :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: If successful, Boolena of type True :rtype: Boolean >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.icc import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> filecontent = 'sample file content' >>> create_new_file = create_cfg_segment('CW7SNMP.cfg', filecontent, 'My New Template', auth.creds, auth.url) >>> template_id = get_template_id('CW7SNMP.cfg', auth.creds, auth.url) >>> assert type(template_id) is str >>> """ payload = {"confFileName": filename, "confFileType": "2", "cfgFileParent": "-1", "confFileDesc": description, "content": filecontent} f_url = url + "/imcrs/icc/confFile" response = requests.post(f_url, data=(json.dumps(payload)), auth=auth, headers=HEADERS) try: if response.status_code == 201: print("Template successfully created") return response.status_code elif response.status_code is not 201: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " create_cfg_segment: An Error has occured"
java
public static MavenRemoteRepository createRemoteRepository(final String id, final String url, final String layout) throws IllegalArgumentException { try { return createRemoteRepository(id, new URL(url), layout); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid URL", e); } }
python
def join_paths(*paths, **kwargs): """ Join multiple paths together and return the absolute path of them. If 'safe' is specified, this function will 'clean' the path with the 'safe_path' function. This will clean root decelerations from the path after the first item. Would like to do 'safe=False' instead of '**kwargs' but stupider versions of python *cough 2.6* don't like that after '*paths'. .. code: python reusables.join_paths("var", "\\log", "/test") 'C:\\Users\\Me\\var\\log\\test' os.path.join("var", "\\log", "/test") '/test' :param paths: paths to join together :param kwargs: 'safe', make them into a safe path it True :return: abspath as string """ path = os.path.abspath(paths[0]) for next_path in paths[1:]: path = os.path.join(path, next_path.lstrip("\\").lstrip("/").strip()) path.rstrip(os.sep) return path if not kwargs.get('safe') else safe_path(path)
java
public static String getEventDateVar(String event, String var) { var = var.toLowerCase(); if (event == null || var.endsWith("date") || var.endsWith("dat")) return var; if (event.equals("planting")) { var = "pdate"; } else if (event.equals("irrigation")) { var = "idate"; } else if (event.equals("fertilizer")) { var = "fedate"; } else if (event.equals("tillage")) { var = "tdate"; } else if (event.equals("harvest")) { var = "hadat"; } else if (event.equals("organic_matter")) { var = "omdat"; } else if (event.equals("chemicals")) { var = "cdate"; } else if (event.equals("mulch-apply")) { var = "mladat"; } else if (event.equals("mulch-remove")) { var = "mlrdat"; } return var; }
java
protected CmsAlias internalReadAlias(ResultSet resultset) throws SQLException { String siteRoot = resultset.getString(1); String path = resultset.getString(2); int mode = resultset.getInt(3); String structId = resultset.getString(4); return new CmsAlias(new CmsUUID(structId), siteRoot, path, CmsAliasMode.fromInt(mode)); }
python
def match(tgt, opts=None): ''' Matches based on range cluster ''' if not opts: opts = __opts__ if HAS_RANGE: range_ = seco.range.Range(opts['range_server']) try: return opts['grains']['fqdn'] in range_.expand(tgt) except seco.range.RangeException as exc: log.debug('Range exception in compound match: %s', exc) return False return False
java
public ServiceCall<RecognitionJob> createJob(CreateJobOptions createJobOptions) { Validator.notNull(createJobOptions, "createJobOptions cannot be null"); String[] pathSegments = { "v1/recognitions" }; RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments)); Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("speech_to_text", "v1", "createJob"); for (Entry<String, String> header : sdkHeaders.entrySet()) { builder.header(header.getKey(), header.getValue()); } builder.header("Accept", "application/json"); if (createJobOptions.contentType() != null) { builder.header("Content-Type", createJobOptions.contentType()); } if (createJobOptions.model() != null) { builder.query("model", createJobOptions.model()); } if (createJobOptions.callbackUrl() != null) { builder.query("callback_url", createJobOptions.callbackUrl()); } if (createJobOptions.events() != null) { builder.query("events", createJobOptions.events()); } if (createJobOptions.userToken() != null) { builder.query("user_token", createJobOptions.userToken()); } if (createJobOptions.resultsTtl() != null) { builder.query("results_ttl", String.valueOf(createJobOptions.resultsTtl())); } if (createJobOptions.languageCustomizationId() != null) { builder.query("language_customization_id", createJobOptions.languageCustomizationId()); } if (createJobOptions.acousticCustomizationId() != null) { builder.query("acoustic_customization_id", createJobOptions.acousticCustomizationId()); } if (createJobOptions.baseModelVersion() != null) { builder.query("base_model_version", createJobOptions.baseModelVersion()); } if (createJobOptions.customizationWeight() != null) { builder.query("customization_weight", String.valueOf(createJobOptions.customizationWeight())); } if (createJobOptions.inactivityTimeout() != null) { builder.query("inactivity_timeout", String.valueOf(createJobOptions.inactivityTimeout())); } if (createJobOptions.keywords() != null) { builder.query("keywords", RequestUtils.join(createJobOptions.keywords(), ",")); } if (createJobOptions.keywordsThreshold() != null) { builder.query("keywords_threshold", String.valueOf(createJobOptions.keywordsThreshold())); } if (createJobOptions.maxAlternatives() != null) { builder.query("max_alternatives", String.valueOf(createJobOptions.maxAlternatives())); } if (createJobOptions.wordAlternativesThreshold() != null) { builder.query("word_alternatives_threshold", String.valueOf(createJobOptions.wordAlternativesThreshold())); } if (createJobOptions.wordConfidence() != null) { builder.query("word_confidence", String.valueOf(createJobOptions.wordConfidence())); } if (createJobOptions.timestamps() != null) { builder.query("timestamps", String.valueOf(createJobOptions.timestamps())); } if (createJobOptions.profanityFilter() != null) { builder.query("profanity_filter", String.valueOf(createJobOptions.profanityFilter())); } if (createJobOptions.smartFormatting() != null) { builder.query("smart_formatting", String.valueOf(createJobOptions.smartFormatting())); } if (createJobOptions.speakerLabels() != null) { builder.query("speaker_labels", String.valueOf(createJobOptions.speakerLabels())); } if (createJobOptions.customizationId() != null) { builder.query("customization_id", createJobOptions.customizationId()); } if (createJobOptions.grammarName() != null) { builder.query("grammar_name", createJobOptions.grammarName()); } if (createJobOptions.redaction() != null) { builder.query("redaction", String.valueOf(createJobOptions.redaction())); } builder.bodyContent(createJobOptions.contentType(), null, null, createJobOptions.audio()); return createServiceCall(builder.build(), ResponseConverterUtils.getObject(RecognitionJob.class)); }
python
def fundb(self, fields=None, min_volume=0, min_discount=0, forever=False): """以字典形式返回分级B数据 :param fields:利率范围,形如['+3.0%', '6.0%'] :param min_volume:最小交易量,单位万元 :param min_discount:最小折价率, 单位% :param forever: 是否选择永续品种,默认 False """ if fields is None: fields = [] # 添加当前的ctime self.__fundb_url = self.__fundb_url.format(ctime=int(time.time())) # 请求数据 rep = requests.get(self.__fundb_url) # 获取返回的json字符串 fundbjson = json.loads(rep.text) # 格式化返回的json字符串 data = self.formatfundbjson(fundbjson) # 过滤小于指定交易量的数据 if min_volume: data = { k: data[k] for k in data if float(data[k]["fundb_volume"]) > min_volume } if len(fields): data = { k: data[k] for k in data if data[k]["coupon_descr_s"] in "".join(fields) } if forever: data = { k: data[k] for k in data if data[k]["fundb_left_year"].find("永续") != -1 } if min_discount: data = { k: data[k] for k in data if float(data[k]["fundb_discount_rt"][:-1]) > min_discount } self.__fundb = data return self.__fundb
java
@Override public void run() throws Exception { setActiveMigration(); try { doRun(); } catch (Throwable t) { logMigrationFailure(t); failureReason = t; } finally { onMigrationComplete(); if (!success) { onExecutionFailure(failureReason); } } }
java
public void marshall(PurchaseProvisionedCapacityRequest purchaseProvisionedCapacityRequest, ProtocolMarshaller protocolMarshaller) { if (purchaseProvisionedCapacityRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(purchaseProvisionedCapacityRequest.getAccountId(), ACCOUNTID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
java
protected void notifyObservers (final Name username, final boolean muted) { _observers.apply(new ObserverList.ObserverOp<MuteObserver>() { public boolean apply (MuteObserver observer) { observer.muteChanged(username, muted); return true; } }); }
python
def enumerate_scope(ast_rootpath, root_env=None, include_default_builtins=False): """Return a dict of { name => Completions } for the given tuple node. Enumerates all keys that are in scope in a given tuple. The node part of the tuple may be None, in case the binding is a built-in. """ with util.LogTime('enumerate_scope'): scope = {} for node in reversed(ast_rootpath): if is_tuple_node(node): for member in node.members: if member.name not in scope: scope[member.name] = Completion(member.name, False, member.comment.as_string(), member.location) if include_default_builtins: # Backwards compat flag root_env = gcl.default_env if root_env: for k in root_env.keys(): if k not in scope and not hide_from_autocomplete(root_env[k]): v = root_env[k] scope[k] = Completion(k, True, dedent(v.__doc__ or ''), None) return scope
java
public static OutputMapping createOutputMapping( Element outputElement ){ if( outputElement == null ){ return null; } switch( outputElement.getType() ) { case VARIABLE: return new ValueMapping( outputElement.getString( 0 ) ); case VARIABLES: Map<String, String> mappings = new LinkedHashMap<>(); for( String mapping : outputElement.getStringArray( 0 ) ){ String[] pair = mapping.split( "=" ); mappings.put( pair[1], pair[0] ); } return new MapEntryMapping( mappings ); default : throw new IllegalStateException( "No strategy defined for creating an OutputMapping based on: " + outputElement ); } }
java
static String countDuplicatesAndAddTypeInfo(Iterable<?> itemsIterable) { Collection<?> items = iterableToCollection(itemsIterable); Optional<String> homogeneousTypeName = getHomogeneousTypeName(items); return homogeneousTypeName.isPresent() ? lenientFormat("%s (%s)", countDuplicates(items), homogeneousTypeName.get()) : countDuplicates(addTypeInfoToEveryItem(items)); }
java
private static int getDeterministicAssignment(double[] distribution) { int assignment = -1; for (int i = 0; i < distribution.length; i++) { if (distribution[i] == 1.0) { if (assignment == -1) assignment = i; else return -1; } else if (distribution[i] != 0.0) return -1; } return assignment; }
java
public boolean outgoingEdgesAreSlowerByFactor(double factor) { double tmpSpeed = getSpeed(currentEdge); double pathSpeed = getSpeed(prevEdge); // Speed-Change on the path indicates, that we change road types, show instruction if (pathSpeed != tmpSpeed || pathSpeed < 1) { return false; } double maxSurroundingSpeed = -1; for (EdgeIteratorState edge : allOutgoingEdges) { tmpSpeed = getSpeed(edge); if (tmpSpeed < 1) { // This might happen for the DataFlagEncoder, might create unnecessary turn instructions return false; } if (tmpSpeed > maxSurroundingSpeed) { maxSurroundingSpeed = tmpSpeed; } } // Surrounding streets need to be slower by a factor return maxSurroundingSpeed * factor < pathSpeed; }
python
def fwdl_status_output_fwdl_entries_blade_slot(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fwdl_status = ET.Element("fwdl_status") config = fwdl_status output = ET.SubElement(fwdl_status, "output") fwdl_entries = ET.SubElement(output, "fwdl-entries") blade_slot = ET.SubElement(fwdl_entries, "blade-slot") blade_slot.text = kwargs.pop('blade_slot') callback = kwargs.pop('callback', self._callback) return callback(config)
python
def make_config(path): """Creates a config file. Attempts to load data from legacy config files if they exist. """ apps, user = load_legacy_config() apps = {a.instance: a._asdict() for a in apps} users = {user_id(user): user._asdict()} if user else {} active_user = user_id(user) if user else None config = { "apps": apps, "users": users, "active_user": active_user, } print_out("Creating config file at <blue>{}</blue>".format(path)) # Ensure dir exists os.makedirs(dirname(path), exist_ok=True) with open(path, 'w') as f: json.dump(config, f, indent=True)
python
def blockSignals(self, state): """ Sets whether or not updates will be enabled. :param state | <bool> """ super(XGanttWidget, self).blockSignals(state) self.treeWidget().blockSignals(state) self.viewWidget().blockSignals(state)
python
def set(self, varname, value, idx=0, units=None): '''set a variable value''' if not varname in self.mapping.vars: raise fgFDMError('Unknown variable %s' % varname) if idx >= self.mapping.vars[varname].arraylength: raise fgFDMError('index of %s beyond end of array idx=%u arraylength=%u' % ( varname, idx, self.mapping.vars[varname].arraylength)) if units: value = self.convert(value, units, self.mapping.vars[varname].units) # avoid range errors when packing into 4 byte floats if math.isinf(value) or math.isnan(value) or math.fabs(value) > 3.4e38: value = 0 self.values[self.mapping.vars[varname].index + idx] = value
java
public void expectMax(String name, double maxLength) { expectMax(name, maxLength, messages.get(Validation.MAX_KEY.name(), name, maxLength)); }
java
public void setDelHints(String delHints) { if (delHints == null || delHints.isEmpty()) { throw new IllegalArgumentException("DelHints is empty"); } this.delHints = delHints; }
java
public void handleStateEvent(String callbackKey) { if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) { ((StateEventHandler) handlers.get(callbackKey)).handle(); } else { System.err.println("Error in handle: " + callbackKey + " for state handler "); } }
python
def daisy_chain_graph(self): """ Directed graph with edges from knob residue to each hole residue for each KnobIntoHole in self. """ g = networkx.DiGraph() for x in self.get_monomers(): for h in x.hole: g.add_edge(x.knob, h) return g
java
@Override public ModifyVpcTenancyResult modifyVpcTenancy(ModifyVpcTenancyRequest request) { request = beforeClientExecution(request); return executeModifyVpcTenancy(request); }
python
def range_mac(mac_start, mac_end, step=1): """Iterate over mac addresses (given as string).""" start = int(EUI(mac_start)) end = int(EUI(mac_end)) for i_mac in range(start, end, step): mac = EUI(int(EUI(i_mac)) + 1) ip = ['10'] + [str(int(i, 2)) for i in mac.bits().split('-')[-3:]] yield str(mac).replace('-', ':'), '.'.join(ip)
java
private List<OntologyTermSynonym> createSynonyms(OWLClass ontologyTerm) { return loader .getSynonyms(ontologyTerm) .stream() .map(this::createSynonym) .collect(Collectors.toList()); }
java
private String check() throws InvalidExpressionException { expression = expression.replaceAll("\\s",""); expression = expression.toLowerCase(); String var = ""; if(expression.length() == 0) { throw new InvalidExpressionException("Empty Expression"); } if(!expression.matches("[a-zA-Z0-9+*/^()-]+")) { // contains only operators, numbers, or letters throw new InvalidExpressionException("Syntax Error"); } if(expression.matches("[+*/^()-]+")) { // doesn't contain any operands throw new InvalidExpressionException("Syntax Error"); } String firstChar = expression.substring(0, 1); String lastChar = expression.substring(expression.length() - 1, expression.length()); if(!firstChar.equals("-") && isOperator(firstChar) || firstChar.equals(")") || isOperator(lastChar) || lastChar.equals("(")) { throw new InvalidExpressionException("Syntax Error"); } for(int i = 0; i < expression.length(); i++) { String temp = ""; while(i < expression.length() && expression.substring(i, i + 1).matches("[a-zA-Z]")) { temp += expression.substring(i, i + 1); i++; } if(temp.length() == 1) { //i--; // ?? i must be decremented from the above while loop in this if block so the program can check the last character in the string if(var.length() == 0) var = temp; if(!temp.equals(var)) { throw new InvalidExpressionException("For now, expression must contain a single variable"); } else if(i < expression.length() && expression.substring(i, i + 1).matches("[0-9]+")) { throw new InvalidExpressionException("Syntax Error"); } } else if(isFunction(temp)) { if(i < expression.length()) { if(!expression.substring(i, i + 1).equals("(")) { //System.out.println("Syntax Error: " + temp + " needs a parenthesis after it");// no parenthesis after function (EX: sin5) throw new InvalidExpressionException("Syntax Error"); } } else { //System.out.println("Syntax Error: " + temp + " needs an input"); // nothing after function (EX: 5 + sin) throw new InvalidExpressionException("Syntax Error"); } } else if(temp.length() != 0){ //System.out.println(temp + ": function not found"); throw new InvalidExpressionException(temp + ": function not found"); } //i--; // ?? i must be decremented since it was left incremented in the above while loop } int cntOpenParen = 0; int cntCloseParen = 0; for(int i = 0; i < expression.length() - 1; i++) { String tmp1 = expression.substring(i, i + 1); String tmp2 = expression.substring(i + 1, i + 2); if(tmp1.equals("-")) { if(isOperator(tmp2) || tmp2.equals(")")) { //System.out.println("Syntax Error: " + tmp1 + tmp2); throw new InvalidExpressionException("Syntax Error"); } } else if(tmp2.equals("-")) { // Also prevents next else if from rejecting an operator followed by a unary minus if(tmp1.equals("(")) { //System.out.println("Syntax Error: " + tmp1 + tmp2); throw new InvalidExpressionException("Syntax Error"); } } else if((isOperator(tmp1) || tmp1.equals("(")) && (isOperator(tmp2) || tmp2.equals(")"))) { //System.out.println("Syntax Error: " + tmp1 + tmp2); // two operands in a row (examples: ++, (+, ()) throw new InvalidExpressionException("Syntax Error"); } else if(expression.substring(i, i + 1).equals("(")) cntOpenParen++; else if(expression.substring(i, i + 1).equals(")")) cntCloseParen++; } if(cntOpenParen < cntCloseParen) { // found a ")" when the end of the expression was expected //System.out.println("Syntax Error: found ')' but expected end of expression"); throw new InvalidExpressionException("Syntax Error"); } return var; }
python
def formatted_str(self, format): """Return formatted str. :param format: one of 'json', 'csv' are supported """ assert(format in ('json', 'csv')) ret_str_list = [] for rec in self._records: if format == 'json': ret_str_list.append('{') for i in xrange(len(rec)): colname, colval = self._rdef[i].name, rec[i] ret_str_list.append('"%s":"%s"' % (colname, str(colval).replace('"', r'\"'))) ret_str_list.append(',') ret_str_list.pop() # drop last comma ret_str_list.append('}%s' % (os.linesep)) elif format == 'csv': for i in xrange(len(rec)): colval = rec[i] ret_str_list.append('"%s"' % (str(colval).replace('"', r'\"'))) ret_str_list.append(',') ret_str_list.pop() # drop last comma ret_str_list.append('%s' % (os.linesep)) else: assert(False) return ''.join(ret_str_list)
python
def today(self, symbol): """ GET /today/:symbol curl "https://api.bitfinex.com/v1/today/btcusd" {"low":"550.09","high":"572.2398","volume":"7305.33119836"} """ data = self._get(self.url_for(PATH_TODAY, (symbol))) # convert all values to floats return self._convert_to_floats(data)
java
public synchronized void noGuessesInStream() throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "noGuessesInStream"); if(TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "oldContainesGuesses:" + containsGuesses + "firstMsgOutsideWindow: " + firstMsgOutsideWindow + ", oldSendWindow: " + sendWindow); containsGuesses = false; // If we have reduced our sendWindow below the definedSendWindow // we now need to send all the messages between the two if( definedSendWindow > sendWindow ) { long oldSendWindow = sendWindow; sendWindow = definedSendWindow; persistSendWindow(sendWindow, null); // Send the messages up to the new send window // this will update firstMsgOutsideWindow sendMsgsInWindow(oldSendWindow, sendWindow); } else { if(TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { SibTr.debug(tc, "no processing : definedSendWindow=" + definedSendWindow + ", sendWindow=" +sendWindow); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "noGuessesInStream"); }
java
private long getLongInternal(final String key, final long defaultValue) { long retVal = defaultValue; try { synchronized (this.confData) { if (this.confData.containsKey(key)) { retVal = Long.parseLong(this.confData.get(key)); } } } catch (NumberFormatException e) { if (LOG.isDebugEnabled()) { LOG.debug(StringUtils.stringifyException(e)); } } return retVal; }
java
private boolean loadMore(int available) throws IOException { mByteCount += (mByteBufferEnd - available); // Bytes that need to be moved to the beginning of buffer? if (available > 0) { /* 11-Nov-2008, TSa: can only move if we own the buffer; otherwise * we are stuck with the data. */ if (mBytePtr > 0 && canModifyBuffer()) { for (int i = 0; i < available; ++i) { mByteBuffer[i] = mByteBuffer[mBytePtr+i]; } mBytePtr = 0; mByteBufferEnd = available; } } else { /* Ok; here we can actually reasonably expect an EOF, * so let's do a separate read right away: */ int count = readBytes(); if (count < 1) { if (count < 0) { // -1 freeBuffers(); // to help GC? return false; } // 0 count is no good; let's err out reportStrangeStream(); } } /* Need at least 4 bytes; if we don't get that many, it's an * error. */ while (mByteBufferEnd < 4) { int count = readBytesAt(mByteBufferEnd); if (count < 1) { if (count < 0) { // -1, EOF... no good! freeBuffers(); // to help GC? reportUnexpectedEOF(mByteBufferEnd, 4); } // 0 count is no good; let's err out reportStrangeStream(); } } return true; }
python
def tournament(self,individuals,tourn_size, num_selections=None): """conducts tournament selection of size tourn_size""" winners = [] locs = [] if num_selections is None: num_selections = len(individuals) for i in np.arange(num_selections): # sample pool with replacement pool_i = self.random_state.choice(len(individuals),size=tourn_size) pool = [] for i in pool_i: pool.append(np.mean(individuals[i].fitness)) # winner locs.append(pool_i[np.argmin(pool)]) winners.append(copy.deepcopy(individuals[locs[-1]])) return winners,locs
java
public final double[] getDpiSuggestions() { if (this.dpiSuggestions == null) { List<Double> list = new ArrayList<>(); for (double suggestion: DEFAULT_DPI_VALUES) { if (suggestion <= this.maxDpi) { list.add(suggestion); } } double[] suggestions = new double[list.size()]; for (int i = 0; i < suggestions.length; i++) { suggestions[i] = list.get(i); } return suggestions; } return this.dpiSuggestions; }
java
@SuppressWarnings({"deprecation", "WeakerAccess"}) protected boolean isFlagPresent(final AttributeAccess.Flag flag) { if (flags == null) { return false; } for (AttributeAccess.Flag f : flags) { if (f.equals(flag)) { return true; } } return false; }
python
def frames_to_tc(self, frames): """Converts frames back to timecode :returns str: the string representation of the current time code """ if frames == 0: return 0, 0, 0, 0 ffps = float(self._framerate) if self.drop_frame: # Number of frames to drop on the minute marks is the nearest # integer to 6% of the framerate drop_frames = int(round(ffps * .066666)) else: drop_frames = 0 # Number of frames in an hour frames_per_hour = int(round(ffps * 60 * 60)) # Number of frames in a day - timecode rolls over after 24 hours frames_per_24_hours = frames_per_hour * 24 # Number of frames per ten minutes frames_per_10_minutes = int(round(ffps * 60 * 10)) # Number of frames per minute is the round of the framerate * 60 minus # the number of dropped frames frames_per_minute = int(round(ffps)*60) - drop_frames frame_number = frames - 1 if frame_number < 0: # Negative time. Add 24 hours. frame_number += frames_per_24_hours # If frame_number is greater than 24 hrs, next operation will rollover # clock frame_number %= frames_per_24_hours if self.drop_frame: d = frame_number // frames_per_10_minutes m = frame_number % frames_per_10_minutes if m > drop_frames: frame_number += (drop_frames * 9 * d) + \ drop_frames * ((m - drop_frames) // frames_per_minute) else: frame_number += drop_frames * 9 * d ifps = self._int_framerate frs = frame_number % ifps secs = (frame_number // ifps) % 60 mins = ((frame_number // ifps) // 60) % 60 hrs = (((frame_number // ifps) // 60) // 60) return hrs, mins, secs, frs
java
public static <T> TypeSerializer<T> tryReadSerializer(DataInputView in, ClassLoader userCodeClassLoader) throws IOException { return tryReadSerializer(in, userCodeClassLoader, false); }