repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
deapplegate/wtgpipeline
|
adam-nedgals2mygals/match_specz_and_bpz_cats.py
|
#! /usr/bin/env python
#adam-does# matches the redshifts from our pipeline/bpz to external reference redshifts
#adam-example# ipython -i -- ./match_specz_and_bpz_cats.py nedcat bpzcat =astropy.io.ascii.read("/u/ki/awright/bonnpipeline/adam_ned_MACS1226+21_galaxies.tsv")
#adam-example# ipython -i -- ./match_specz_and_bpz_cats.py /u/ki/awright/bonnpipeline/adam_ned_MACS1226+21_galaxies.tsv /nfs/slac/g/ki/ki18/anja/SUBARU/MACS1226+21/PHOTOMETRY_W-C-RC_aper/MACS1226+21.calibrated.bpztab.cat
import sys,os,inspect ; sys.path.append('/u/ki/awright/InstallingSoftware/pythons')
from import_tools import *
curfile=os.path.abspath(inspect.getfile(inspect.currentframe()))
FileString=os.path.basename(curfile)
args=imagetools.ArgCleaner(sys.argv,FileString)
import numpy as np
import matplotlib.pyplot as plt
import astropy
from astropy.coordinates import SkyCoord
from astropy import units as u
ned_file= "/u/ki/awright/bonnpipeline/adam-nedgals2mygals/sdssj1226_redshifts_converted.tsv"
bpz_file= "/nfs/slac/g/ki/ki18/anja/SUBARU/MACS1226+21/PHOTOMETRY_W-C-RC_aper/MACS1226+21.calibrated.bpztab.cat"
sdss_file="/u/ki/awright/bonnpipeline/adam-nedgals2mygals/cat_additions_from_sdss_zspecs.tsv" #'Survey', 'RA', 'Dec', 'Redshift', 'SN', 'Class'
sdsscat=astropy.io.ascii.read(sdss_file)
nedcat=astropy.io.ascii.read(ned_file)
bpzcat=astropy.io.fits.open(bpz_file)
#adam-example# bpzcat=astropy.io.fits.open("/nfs/slac/g/ki/ki18/anja/SUBARU/MACS1226+21/PHOTOMETRY_W-C-RC_aper/MACS1226+21.calibrated.bpztab.cat")
# os.system("ldacdesc -i /nfs/slac/g/ki/ki18/anja/SUBARU/MACS1226+21/PHOTOMETRY_W-C-RC_aper/MACS1226+21.calibrated.bpztab.cat")
# primary OBJECTS PHOTINFO FIELDS BPZTAB
bpztab=bpzcat[-1]
objtab=bpzcat[1]
bpzdat=bpztab.data
objdat=objtab.data
raw_bpz_z=bpzdat.field("BPZ_Z_B")
raw_bpz_z_min=bpzdat.field("BPZ_Z_B_MIN")
raw_bpz_z_max=bpzdat.field("BPZ_Z_B_MAX")
raw_bpz_odds=bpzdat.field("BPZ_ODDS")
raw_bpz_SeqNr=objdat.field('SeqNr')
raw_bpz_ra=objdat.field('ALPHA_J2000')
raw_bpz_dec=objdat.field('DELTA_J2000')
#raw_bpz_rmag=objdat.field("MAG_AUTO1-SUBARU-10_3-1-W-C-RC")
raw_bpz_rmag=objdat.field("MAG_APER1-SUBARU-10_3-1-W-C-RC")
raw_bpz_imag=objdat.field("MAG_APER1-SUBARU-10_3-1-W-C-IC")
raw_bpz_rmagerr=objdat.field("MAGERR_APER1-SUBARU-10_3-1-W-C-RC")
raw_bpz_imagerr=objdat.field("MAGERR_APER1-SUBARU-10_3-1-W-C-IC")
raw_r_ok=raw_bpz_rmag>0
raw_i_ok=raw_bpz_imag>0
## now clip down to the bpz catalog that actually has a similar magnitude range:
ok_bpz=(raw_bpz_rmag<23)*(raw_bpz_imag<23)
if ok_bpz.any():
bpz_z=raw_bpz_z[ok_bpz]
bpz_z_min=raw_bpz_z_min[ok_bpz]
bpz_z_max=raw_bpz_z_max[ok_bpz]
bpz_odds=raw_bpz_odds[ok_bpz]
bpz_ra=raw_bpz_ra[ok_bpz]
bpz_dec=raw_bpz_dec[ok_bpz]
bpz_rmag=raw_bpz_rmag[ok_bpz]
bpz_imag=raw_bpz_imag[ok_bpz]
bpz_rmagerr=raw_bpz_rmagerr[ok_bpz]
bpz_imagerr=raw_bpz_imagerr[ok_bpz]
r_ok=raw_r_ok[ok_bpz]
i_ok=raw_i_ok[ok_bpz]
bpz_SeqNr=raw_bpz_SeqNr[ok_bpz]
#fk5 is J2000 by default!
mycoords=SkyCoord(bpz_ra*u.degree,bpz_dec*u.degree,frame="fk5")
## now get ned/sdss info
sdsscoords=SkyCoord(sdsscat["RA"].data*u.degree,sdsscat["Dec"].data*u.degree,frame="fk5")
nedcoords=SkyCoord(nedcat["ra"],nedcat["dec"],frame="fk5")
# ned_gmag=nedcat['g'].data ned_imag=nedcat['i'].data ned_rmag=nedcat['r'].data
sdss_z=sdsscat["Redshift"].data
ned_z=nedcat['z'].data
##combine ned and sdss info
zspec_dec=append(nedcoords.dec.deg,sdsscoords.dec.deg)
zspec_ra=append(nedcoords.ra.deg,sdsscoords.ra.deg)
zspec_z=append(ned_z,sdss_z)
zspeccoords=SkyCoord(zspec_ra*u.degree,zspec_dec*u.degree,frame="fk5")
idx, d2d, d3d = zspeccoords.match_to_catalog_sky(mycoords)
d2d_arcsec=d2d.deg*3600
matches=mycoords[idx]
Mbpz_ra=matches.ra.deg
Mbpz_dec=matches.dec.deg
Mbpz_z=bpz_z[idx]
Mbpz_z_min=bpz_z_min[idx]
Mbpz_z_max=bpz_z_max[idx]
Mbpz_odds=bpz_odds[idx]
Mbpz_rmag=bpz_rmag[idx]
Mbpz_imag=bpz_imag[idx]
Mbpz_rmagerr=bpz_rmagerr[idx]
Mbpz_imagerr=bpz_imagerr[idx]
Mbpz_i_ok=i_ok[idx]
Mbpz_r_ok=r_ok[idx]
Mbpz_SeqNr=bpz_SeqNr[idx]
## save catalog with all relevent matched information
from astropy.io import ascii
#outtable=astropy.table.table.Table(data=[Mbpz_ra,Mbpz_dec,zspec_ra,zspec_dec,zspec_z,Mbpz_z, Mbpz_odds, d2d_arcsec],names=["Mbpz_ra","Mbpz_dec","zspec_ra","zspec_dec","zspec_z","Mbpz_z"," Mbpz_odds","d2d_arcsec"])
#outtable.write("match_specz_and_bpz_cats_uncut_final_zspecgals2mygals.tsv",format="ascii.commented_header")
## check and see how things look if I exclude detections that have a -99 anywhere
## matches are "good" if they are less than 6 pixels apart and z>.01
#adam-SHNT# the below:
## So, I run bpz on a catalog that's got both stars and galaxies in it, but I have ZMIN=.01, so it's safe to say that the BPZ results are going to be meaningless for stars, and I should remove them from the plots evaluating the effectiveness of BPZ.
#also, I've got some doubles, are these by any chance from cat_additions_from_sdss_zspecs.tsv overlapping with the zspecs?
#I think that's it, but I might need to make some of these changes in other adam_match_nedgals2mygals*.py files too!
lt6pix_apart=d2d_arcsec<1.2
gtpt01_z=zspec_z>.01
match_goodenough=lt6pix_apart*gtpt01_z
bpzra=Mbpz_ra[match_goodenough]
bpzdec=Mbpz_dec[match_goodenough]
inds=arange(len(zspec_z))
goodinds=inds[match_goodenough]
goodzspec= zspec_z[match_goodenough]
doubles=[]
doubles_ra=[]
doubles_dec=[]
for i in range(len(bpzra)):
ra=bpzra[i]
ra_matches=bpzra==ra
dec=bpzdec[i]
dec_matches=bpzdec==dec
if dec_matches.sum()>1:
if not i==dec_matches.argmax():
doubles.append((i,dec_matches.argmax()))
doubles_ra.append(ra)
doubles_dec.append(dec)
doubles_zspec_inds=[]
match_goodsingles=match_goodenough.copy()
for (i1,i2) in doubles:
print goodzspec[i1],goodzspec[i2],goodzspec[i1]-goodzspec[i2]
doubles_zspec_inds.append((goodinds[i1],goodinds[i2]))
gi1,gi2=(goodinds[i1],goodinds[i2])
d2d1=d2d_arcsec[gi1]
d2d2=d2d_arcsec[gi2]
if d2d1<d2d2:
print match_goodenough[gi2]
match_goodsingles[gi2]=False
else:
print match_goodenough[gi1]
match_goodsingles[gi1]=False
# turns out the doubles (where two zspec objects are matched to the same bpz object) are from zspec having two z's listed for a single object (one side of galaxy and the other side of the galaxy)
Mbpz_ra=matches.ra.deg
Mbpz_dec=matches.dec.deg
Mbpz_z=bpz_z[idx]
Mbpz_z_min=bpz_z_min[idx]
Mbpz_z_max=bpz_z_max[idx]
Mbpz_odds=bpz_odds[idx]
Mbpz_rmag=bpz_rmag[idx]
Mbpz_imag=bpz_imag[idx]
Mbpz_rmagerr=bpz_rmagerr[idx]
Mbpz_imagerr=bpz_imagerr[idx]
Mbpz_i_ok=i_ok[idx]
Mbpz_r_ok=r_ok[idx]
Mbpz_SeqNr=bpz_SeqNr[idx]
good={}
good['dist']= d2d_arcsec[match_goodsingles]
good['Mbpz_ra']= Mbpz_ra[match_goodsingles]
good['Mbpz_dec']= Mbpz_dec[match_goodsingles]
good['Mbpz_z']= Mbpz_z[match_goodsingles]
good['Mbpz_z_min']= Mbpz_z_min[match_goodsingles]
good['Mbpz_z_max']= Mbpz_z_max[match_goodsingles]
good['Mbpz_odds']= Mbpz_odds[match_goodsingles]
good['Mbpz_imag']= Mbpz_imag[match_goodsingles]
good['Mbpz_rmag']= Mbpz_rmag[match_goodsingles]
good['Mbpz_imagerr']= Mbpz_imagerr[match_goodsingles]
good['Mbpz_rmagerr']= Mbpz_rmagerr[match_goodsingles]
good['Mbpz_i_ok']= Mbpz_i_ok[match_goodsingles]
good['Mbpz_r_ok']= Mbpz_r_ok[match_goodsingles]
good['Mbpz_SeqNr']= Mbpz_SeqNr[match_goodsingles]
good['zspec_z']= zspec_z[match_goodsingles]
good['zspec_ra']= zspec_ra[match_goodsingles]
good['zspec_dec']= zspec_dec[match_goodsingles]
allok=Mbpz_i_ok*Mbpz_r_ok
good['Mbpz_allok']= allok[match_goodsingles]
## save catalog of the good matches
outtable=astropy.table.table.Table( data=[good['zspec_ra'],good['zspec_dec'],good['zspec_z'],good['Mbpz_z'],good['Mbpz_ra'],good['Mbpz_dec'],good['Mbpz_SeqNr'],good['Mbpz_z_min'],good['Mbpz_z_max'],good['Mbpz_odds'],good['Mbpz_imag'],good['Mbpz_rmag'],good['Mbpz_imagerr'],good['Mbpz_rmagerr'],good['Mbpz_i_ok'],good['Mbpz_r_ok'],good['Mbpz_allok'],good['dist']], \
names=['ref_ra','ref_dec','ref_z','bpz_z','bpz_ra','bpz_dec','bpz_SeqNr','bpz_z_min','bpz_z_max','bpz_odds','bpz_I','bpz_R','bpz_Ierr','bpz_Rerr','bpz_I_ok','bpz_R_ok','bpz_allok','dist'])
outtable.write("match_specz_and_bpz_cats.tsv",format="ascii.commented_header")
#outtable=astropy.table.table.Table( data=[Mbpz_ra[match_goodsingles],Mbpz_dec[match_goodsingles],zspec_ra[match_goodsingles],zspec_dec[match_goodsingles],zspec_z[match_goodsingles],Mbpz_z[match_goodsingles], Mbpz_odds[match_goodsingles], d2d_arcsec[match_goodsingles]], \
# names=["Mbpz_ra","Mbpz_dec","zspec_ra","zspec_dec","zspec_z","Mbpz_z","Mbpz_odds","d2d_arcsec"])
#outtable.write("match_specz_and_bpz_cats.tsv",format="ascii.commented_header")
#adam-SHNT# OK, i've got to save the Z_S to the catalog now, and that's the catalog adam_do_photometry.py has to use!
Z_S_SeqNr=Mbpz_SeqNr[match_goodsingles]
Z_S_z=zspec_z[match_goodsingles]
## save catalog of the good matches
bpz_path=os.path.split(bpz_file)
outtable=astropy.table.table.Table( data=[ Z_S_SeqNr, Z_S_z ], names=['SeqNr','z'])
outtable.write(bpz_path[0]+"/match_specz_and_bpz_cats.txt",format="ascii.commented_header")
|
weucode/COMFORT
|
artifact_evaluation/data/codeCoverage/codealchemist_generate/164.js
|
<reponame>weucode/COMFORT<gh_stars>10-100
var v0 = (function (v1, v2, v3){
var v4 = v3(217), v5 = v3(169), v6 = "[object AsyncFunction]", v7 = "[object Function]", v8 = "[object GeneratorFunction]", v9 = "[object Proxy]";
(v1.exports) = (function (v1){
if(! v5(v1)){
return ! 1;
}
var v2 = v4(v1);
return ((((v2) == (v7)) || ((v2) == (v8))) || ((v2) == (v6))) || ((v2) == (v9));
});
});
(v0.prototype.getOrAddWithFactory) = (function (v1, v2){
var v3 = this.get(v1);
if((v3) !== (undefined)){
return v3;
}
(v3) = v2(v1);
if(v3){
this.add(v1, v3);
}
return v3;
});
var v1 = ({get : v0, writable : false});
(v0.prototype['break']) = (function (){
this.notify(v1);
});
var v2 = (function (v1){
this._setProperty('-webkit-font-smoothing', v1);
});
var v3 = (function (v1){
(this.m_maxMotorForce) = v1;
});
(v1.viewOpenTitle) = "Open this pad in read-only mode in a new tab";
v2(v3, v0);
|
trettstadtnlb/openjpa
|
openjpa-lib/src/main/java/org/apache/openjpa/lib/util/Localizer.java
|
<reponame>trettstadtnlb/openjpa
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openjpa.lib.util;
import java.security.AccessController;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* The Localizer provides convenient access to localized
* strings. It inlcudes built-in support for parameter substitution through
* the use of the {@link MessageFormat} utility.
* Strings are stored in per-package {@link Properties} files.
* The property file for the default locale must be named
* <code>localizer.properties</code>. Additional locales can be supported
* through additional property files using the naming conventions specified
* in the {@link ResourceBundle} class. For example, the german locale
* could be supported through a <code>localizer_de_DE.properties</code> file.
*
* @author <NAME>
*/
public class Localizer {
// static cache of package+loc name to localizer mappings
private static final Map<String,Localizer> _localizers = new ConcurrentHashMap<>();
// list of resource providers to delegate to when locating resources
private static final Collection<ResourceBundleProvider> _providers =
new CopyOnWriteArraySet<>
(Arrays.asList(new ResourceBundleProvider[]{
new SimpleResourceBundleProvider(),
new StreamResourceBundleProvider(),
new ZipResourceBundleProvider(), }));
/**
* Return a Localizer instance that will access the properties file
* in the package of the given class using the system default locale.
*
* @see #forPackage(Class,Locale)
*/
public static Localizer forPackage(Class<?> cls) {
return forPackage(cls, null);
}
/**
* Return a Localizer instance that will access the properties file
* in the package of the given class using the given locale.
*
* @param cls the class whose package to check for the localized
* properties file; if null, the system will check for
* a top-level properties file
* @param locale the locale to which strings should be localized; if
* null, the system default will be assumed
*/
public static Localizer forPackage(Class<?> cls, Locale locale) {
if (locale == null)
locale = Locale.getDefault();
int dot = (cls == null) ? -1 : cls.getName().lastIndexOf('.');
String pkg;
String file;
if (dot == -1) {
pkg = "";
file = "localizer";
} else {
pkg = cls.getName().substring(0, dot);
file = pkg + ".localizer";
}
String key = file + locale.toString();
// no locking; ok if bundle created multiple times
// check for cached version
Localizer loc = (Localizer) _localizers.get(key);
if (loc != null)
return loc;
else {
loc = new Localizer(pkg, file, locale,
cls == null ? null:AccessController.doPrivileged(
J2DoPrivHelper.getClassLoaderAction(cls)));
_localizers.put(key, loc);
return loc;
}
}
/**
* Register a resource provider.
*/
public static void addProvider(ResourceBundleProvider provider) {
_providers.add(provider);
}
/**
* Remove a resource provider.
*/
public static boolean removeProvider(ResourceBundleProvider provider) {
return _providers.remove(provider);
}
private String _file;
private String _pkg;
private ResourceBundle _bundle = null;
private Locale _locale;
private ClassLoader _loader;
private Localizer(String pkg, String f, Locale locale, ClassLoader loader) {
_pkg = pkg;
_file = f;
_locale = locale;
_loader = loader;
}
private ResourceBundle getBundle() {
// no locking; it's ok to create multiple bundles
if (_bundle == null) {
// find resource bundle
for (Iterator<ResourceBundleProvider> itr = _providers.iterator();
itr.hasNext() && _bundle == null; ) {
_bundle = itr.next().findResource(_file, _locale, _loader);
}
}
return _bundle;
}
/**
* Return the localized string matching the given key.
*/
public Message get(String key) {
return get(key, null);
}
/**
* Return the localized string matching the given key.
*/
public Message getFatal(String key) {
return getFatal(key, null);
}
/**
* Return the localized string matching the given key. The given
* <code>sub</code> object will be packed into an array and substituted
* into the found string according to the rules of the
* {@link MessageFormat} class.
*
* @see #get(String)
*/
public Message get(String key, Object sub) {
return get(key, new Object[]{ sub });
}
/**
* Return the localized string matching the given key. The given
* <code>sub</code> object will be packed into an array and substituted
* into the found string according to the rules of the
* {@link MessageFormat} class.
*
* @see #getFatal(String)
*/
public Message getFatal(String key, Object sub) {
return getFatal(key, new Object[]{ sub });
}
/**
* Return the localized string for the given key.
*
* @see #get(String,Object)
*/
public Message get(String key, Object sub1, Object sub2) {
return get(key, new Object[]{ sub1, sub2 });
}
/**
* Return the localized string for the given key.
*
* @see #getFatal(String,Object)
*/
public Message getFatal(String key, Object sub1, Object sub2) {
return getFatal(key, new Object[]{ sub1, sub2 });
}
/**
* Return the localized string for the given key.
*
* @see #get(String,Object)
*/
public Message get(String key, Object sub1, Object sub2, Object sub3) {
return get(key, new Object[]{ sub1, sub2, sub3 });
}
/**
* Return the localized string matching the given key. The given
* <code>subs</code> objects will be substituted
* into the found string according to the rules of the
* {@link MessageFormat} class.
*
* @see #get(String)
*/
public Message get(String key, Object[] subs) {
return new Message(_pkg, getBundle(), key, subs, false);
}
/**
* Return the localized string matching the given key. The given
* <code>subs</code> objects will be substituted
* into the found string according to the rules of the
* {@link MessageFormat} class.
*
* @see #getFatal(String)
*/
public Message getFatal(String key, Object[] subs) {
return new Message(_pkg, getBundle(), key, subs, true);
}
/**
* A <code>Message</code> can provide a localized message via the
* {@link #getMessage} method call, and can also provide the original key,
* package, and substitution array that were used to assemble the message.
*/
public static class Message {
private final String _pkg;
private final String _key;
private final Object[] _subs;
private final String _localizedMessage;
private boolean _localizedMessageFound;
private Message(String packageName, ResourceBundle bundle, String key,
Object[] subs, boolean fatal) {
if (bundle == null && fatal)
throw new MissingResourceException(key, key, key);
_pkg = packageName;
_key = key;
_subs = subs;
if (bundle == null) {
_localizedMessage = key;
_localizedMessageFound = false;
} else {
String localized = null;
try {
localized = bundle.getString(key);
_localizedMessageFound = true;
} catch (MissingResourceException mre) {
if (fatal)
throw mre;
_localizedMessageFound = false;
}
_localizedMessage = (localized == null) ? key : localized;
}
}
/**
* The localized message.
*/
public String getMessage() {
if (_localizedMessageFound)
return MessageFormat.format(_localizedMessage, _subs);
else if (_subs == null || _subs.length == 0)
return "localized message key: " + _localizedMessage;
else
return "localized message key: " + _localizedMessage
+ "; substitutions: " + Arrays.asList(_subs).toString();
}
/**
* The unique key for the localized message.
*/
public String getKey() {
return _key;
}
/**
* Substitutions inserted into the message.
*/
public Object[] getSubstitutions() {
return _subs;
}
public String getPackageName() {
return _pkg;
}
@Override
public String toString() {
return getMessage();
}
}
}
|
mdger/uboote
|
client/LaserPiratesClient/src/game/gui/component/PlayerInput.java
|
<reponame>mdger/uboote
package game.gui.component;
import game.controller.LevelController;
import game.level.SubmitObject;
import game.module.geometry.shape.LinearFunction;
import javafx.scene.Node;
/**
* PlayerInput interface
* @author Marco
*/
public interface PlayerInput {
public void draw();
public Node getSubmitInput(LevelController controller);
public SubmitObject submitFunction(LevelController levelController);
public void setFalseInput(SubmitObject submit);
}
|
dkupchenko/spring-sandbox
|
scheduled-timezone/src/main/java/info/kupchenko/sandbox/spring/scheduled/family/Pet.java
|
package info.kupchenko.sandbox.spring.scheduled.family;
/**
* The Pet ...
*
* @author by <NAME>
* @version 1.0
* Created on 07.03.2020
* Last review on 07.03.2020
*/
public interface Pet extends Essence {
void stroke(Essence sender);
void play(Essence sender) throws InterruptedException;
}
|
securekey/fabric-snaps
|
metrics/pkg/util/util.go
|
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package util
import (
"regexp"
"strings"
kitstatsd "github.com/go-kit/kit/metrics/statsd"
"github.com/hyperledger/fabric-sdk-go/pkg/common/logging"
"github.com/hyperledger/fabric/common/metrics"
"github.com/hyperledger/fabric/common/metrics/disabled"
"github.com/hyperledger/fabric/common/metrics/prometheus"
"github.com/hyperledger/fabric/common/metrics/statsd"
"github.com/securekey/fabric-snaps/util/configcache"
"github.com/securekey/fabric-snaps/util/errors"
)
const (
peerConfigFileName = "core"
cmdRootPrefix = "core"
)
var reg = regexp.MustCompile("[^a-zA-Z0-9_]+")
var peerConfigCache = configcache.New(peerConfigFileName, cmdRootPrefix, "/etc/hyperledger/fabric")
var log = logging.NewLogger("metricsutil")
var provider metrics.Provider
//GetMetricsInstance return metrics instance
func GetMetricsInstance() metrics.Provider {
if provider == nil {
panic("provider instance is nil you need to call InitializeMetricsProvider first")
}
return provider
}
//FilterMetricName filter metric name
func FilterMetricName(name string) string {
return reg.ReplaceAllString(name, "_")
}
// InitializeMetricsProvider initialize metrics provider
func InitializeMetricsProvider(peerConfigPath string) error {
peerConfig, err := peerConfigCache.Get(peerConfigPath)
if err != nil {
return errors.WithMessage(errors.InitializeConfigError, err, "Failed to get peer config from cache")
}
providerType := peerConfig.Get("metrics.provider")
switch providerType {
case "statsd":
prefix := peerConfig.GetString("metrics.statsd.prefix")
if prefix != "" && !strings.HasSuffix(prefix, ".") {
prefix = prefix + "."
}
ks := kitstatsd.New(prefix, &logger{})
provider = &statsd.Provider{Statsd: ks}
return nil
case "prometheus":
provider = &prometheus.Provider{}
return nil
default:
if providerType != "disabled" {
log.Warnf("Unknown provider type: %s; metrics disabled", providerType)
}
provider = &disabled.Provider{}
return nil
}
}
type logger struct {
}
func (l *logger) Log(keyvals ...interface{}) error {
log.Warn(keyvals...)
return nil
}
|
wfu8/lightwave
|
vmidentity/samlauthority/src/main/java/com/vmware/identity/saml/PrincipalAttributeDefinition.java
|
/*
* Copyright (c) 2012-2015 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.vmware.identity.saml;
import org.apache.commons.lang.Validate;
/**
* Represents an principal attribute definition, without the value.
*/
public class PrincipalAttributeDefinition {
private final String name;
private final String friendlyName;
private final String nameFormat;
/**
* @param name
* required
* @param nameFormat
* required
* @param friendlyName
* mandatory
*/
public PrincipalAttributeDefinition(String name, String nameFormat,
String friendlyName) {
Validate.notNull(name);
Validate.notNull(nameFormat);
this.name = name;
this.nameFormat = nameFormat;
this.friendlyName = friendlyName;
}
/**
* @return name, not null
*/
public String getName() {
return name;
}
/**
* @return name format, not null
*/
public String getNameFormat() {
return nameFormat;
}
/**
* @return friendly name, mandatory
*/
public String getFriendlyName() {
return friendlyName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((friendlyName == null) ? 0 : friendlyName.hashCode());
result = prime * result + name.hashCode();
result = prime * result + nameFormat.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
PrincipalAttributeDefinition other = (PrincipalAttributeDefinition) obj;
boolean equalFriendlyName = (friendlyName == null && other.friendlyName == null)
|| (friendlyName != null && other.friendlyName != null && friendlyName
.equals(other.friendlyName));
return equalFriendlyName && name.equals(other.name)
&& nameFormat.equals(other.nameFormat);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("PrincipalAttributeDefinition [name=").append(name);
sb.append(", format=").append(nameFormat);
sb.append(", friendly name=").append(friendlyName).append("]");
return sb.toString();
}
}
|
panosant/ocp
|
src/main/java/com/antonakospanos/oca/m09exceptions/examples/MyResource.java
|
<gh_stars>0
package com.antonakospanos.oca.m09exceptions.examples;
import java.io.IOException;
public class MyResource implements AutoCloseable {
@Override
public void close() throws IOException {
try {
// close resource
} catch (Exception e) {
throw new IOException("Could not close resource. Cause: ", e);
}
}
}
|
tdiprima/code
|
recipes/Python/578471_Multiple_unique_class_instances__tentative/recipe-578471.py
|
>>> import base
>>> class UniqueSub(base.UniqueBase):
def __init__(self, unique_id, a=1, b=2, **kw_args):
super(UniqueSub, self).__init__(unique_id, **kw_args)
self.a = a
self.b = b
>>> first = UniqueSub("item 1")
>>> second = UniqueSub("item 2", a=4, b=7) # keyword arguments are required
>>> third = UniqueSub("item 1", a=3, b=6) # new argument values are ignored
>>> third.a
1
>>> third.b
2
>>> first == third
True
>>> import pickle
>>> with open("/tmp/test.pkl", "wb") as handle:
pickle.dump(first, handle, 0) # protocol level zero just to prove that it also works
>>> with open("/tmp/test.pkl", "rb") as handle:
fourth = pickle.load(handle)
>>> fourth == first
True
|
nistefan/cmssw
|
RecoVertex/NuclearInteractionProducer/plugins/NuclearInteractionEDProducer.cc
|
#include "RecoVertex/NuclearInteractionProducer/interface/NuclearInteractionEDProducer.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DataFormats/VertexReco/interface/NuclearInteractionFwd.h"
#include "RecoVertex/NuclearInteractionProducer/interface/NuclearVertexBuilder.h"
#include "RecoVertex/NuclearInteractionProducer/interface/NuclearLikelihood.h"
#include "FWCore/Framework/interface/EventSetup.h"
namespace {
void print(std::ostringstream& str, const reco::NuclearInteraction& nucl, const NuclearVertexBuilder& builder);
}
NuclearInteractionEDProducer::NuclearInteractionEDProducer(const edm::ParameterSet& iConfig) :
conf_(iConfig)
{
token_primaryTrack = consumes<reco::TrackCollection>(iConfig.getParameter<std::string>("primaryProducer"));
token_secondaryTrack = consumes<reco::TrackCollection>(iConfig.getParameter<std::string>("secondaryProducer"));
token_additionalSecTracks = consumes<reco::TrackCollection>(iConfig.getParameter<std::string>("additionalSecondaryProducer"));
token_primaryTrajectory = consumes<TrajectoryCollection>(iConfig.getParameter<std::string>("primaryProducer"));
token_refMapH = consumes<TrajTrackAssociationCollection>(iConfig.getParameter<std::string>("primaryProducer"));
token_nuclMapH = consumes<TrajectoryToSeedsMap>(iConfig.getParameter<std::string>("seedsProducer"));
produces<reco::NuclearInteractionCollection>();
}
NuclearInteractionEDProducer::~NuclearInteractionEDProducer()
{
}
//
// member functions
//
// ------------ method called to produce the data ------------
void
NuclearInteractionEDProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup)
{
if ( magFieldWatcher_.check(iSetup) || transientTrackWatcher_.check(iSetup) ) {
/// Get magnetic field
edm::ESHandle<MagneticField> magField;
iSetup.get<IdealMagneticFieldRecord>().get(magField);
edm::ESHandle<TransientTrackBuilder> builder;
iSetup.get<TransientTrackRecord>().get("TransientTrackBuilder",builder);
vertexBuilder = std::make_unique< NuclearVertexBuilder >(magField.product(), builder.product(), conf_);
likelihoodCalculator = std::make_unique< NuclearLikelihood >();
}
/// Get the primary tracks
edm::Handle<reco::TrackCollection> primaryTrackCollection;
iEvent.getByToken(token_primaryTrack, primaryTrackCollection);
/// Get the primary trajectories (produced by the Refitter)
edm::Handle< TrajectoryCollection > primaryTrajectoryCollection;
iEvent.getByToken(token_primaryTrajectory, primaryTrajectoryCollection);
/// Get the AssociationMap between primary tracks and trajectories
edm::Handle< TrajTrackAssociationCollection > refMapH;
iEvent.getByToken(token_refMapH, refMapH);
const TrajTrackAssociationCollection& refMap = *(refMapH.product());
/// Get the AssociationMap between seeds and primary trajectories
edm::Handle<TrajectoryToSeedsMap> nuclMapH;
iEvent.getByToken(token_nuclMapH, nuclMapH);
const TrajectoryToSeedsMap& nuclMap = *(nuclMapH.product());
/// Get the secondary tracks
edm::Handle<reco::TrackCollection> secondaryTrackCollection;
iEvent.getByToken(token_secondaryTrack, secondaryTrackCollection);
// Get eventual additional secondary tracks
edm::Handle<reco::TrackCollection> additionalSecTracks;
iEvent.getByToken(token_additionalSecTracks, additionalSecTracks);
/// Definition of the output
auto theNuclearInteractions = std::make_unique<reco::NuclearInteractionCollection>();
typedef edm::Ref<TrajectoryCollection> TrajectoryRef;
/// Loop on all primary trajectories
for(unsigned int i = 0; i < primaryTrajectoryCollection->size() ; i++) {
TrajectoryRef trajRef( primaryTrajectoryCollection, i );
/// 1. Get the primary track from the trajectory
TrajTrackAssociationCollection::const_iterator itPrimTrack = refMap.find( trajRef );
if( itPrimTrack == refMap.end() || (itPrimTrack->val).isNull() ) continue;
const reco::TrackRef& primary_track = itPrimTrack->val;
/// 2. Get the seeds from the trajectory
TrajectoryToSeedsMap::const_iterator itSeeds = nuclMap.find( trajRef );
if( itSeeds == nuclMap.end() || (itSeeds->val).isNull()) continue;
const TrajectorySeedRefVector& seeds = itSeeds->val;
/// 3. Get the secondary tracks
std::vector<reco::TrackRef> secondary_tracks;
for( unsigned int k=0; k < secondaryTrackCollection->size(); k++) {
reco::TrackRef currentTrk(secondaryTrackCollection, k);
if( isInside( currentTrk, seeds ) ) secondary_tracks.push_back(currentTrk);
}
/// 4. Get the vertex and the likelihood
vertexBuilder->build(primary_track, secondary_tracks);
likelihoodCalculator->calculate( vertexBuilder->getVertex() );
/// 5. Build the nuclear interaction
reco::NuclearInteraction nuclInter(seeds, vertexBuilder->getVertex(), likelihoodCalculator->result() );
/// 6. Search for additional secondary tracks in an other track collection
/// and recompute the nuclear interaction
if( additionalSecTracks.isValid() )
findAdditionalSecondaryTracks(nuclInter, additionalSecTracks);
theNuclearInteractions->push_back( nuclInter );
std::ostringstream str;
print(str, nuclInter, *vertexBuilder);
edm::LogInfo("NuclearInteractionMaker") << str.str();
}
LogDebug("NuclearInteractionMaker") << "End of NuclearInteractionMaker - Number of nuclear interactions found :" << theNuclearInteractions->size();
iEvent.put(std::move(theNuclearInteractions));
}
// ------ method used to check whether the seed of a track belong to the vector of seeds --
bool NuclearInteractionEDProducer::isInside( const reco::TrackRef& track, const TrajectorySeedRefVector& seeds) {
unsigned int seedKey = track->seedRef().key();
for (unsigned int i=0; i< seeds.size(); i++) { if( seeds[i].key() == seedKey ) return true; }
return false;
}
void NuclearInteractionEDProducer::findAdditionalSecondaryTracks( reco::NuclearInteraction& nucl,
const edm::Handle<reco::TrackCollection>& additionalSecTracks) const {
LogDebug("NuclearInteractionMaker") << "Check if one of the " << additionalSecTracks->size()
<< " additional secondary track is compatible";
reco::TrackRefVector allSecondary;
for(unsigned int i=0; i< additionalSecTracks->size(); i++) {
reco::TrackRef sec(additionalSecTracks, i);
if( vertexBuilder->isCompatible( sec ) ) {
// check if sec is already a secondary track (with id = tkId)
// else add this new track
vertexBuilder->addSecondaryTrack( sec );
}
}
likelihoodCalculator->calculate( vertexBuilder->getVertex() );
nucl = reco::NuclearInteraction(nucl.seeds(), vertexBuilder->getVertex(), likelihoodCalculator->result() );
}
// -- print out
namespace {
void print(std::ostringstream& out, const reco::NuclearInteraction& nucl, const NuclearVertexBuilder& builder) {
out<<"Nuclear Interaction with vertex position : (";
out<< nucl.vertex().position().x() << " , "
<< nucl.vertex().position().y() << " , "
<< nucl.vertex().position().z() << ")";
reco::TrackRef primTrack = (nucl.primaryTrack()).castTo<reco::TrackRef>();
out<<"\tLikelihood : " << nucl.likelihood() << std::endl;
out<<"\tPrimary Track : Pt = " << primTrack->pt() << " - Nhits = "
<< primTrack->numberOfValidHits() << std::endl;
out << "\tNumber of seeds : " << nucl.seedsSize() << std::endl;
out << "\tNumber of secondary Tracks : " << nucl.secondaryTracksSize() << std::endl;
int it=0;
for( reco::NuclearInteraction::trackRef_iterator itr_=nucl.secondaryTracks_begin(); itr_ != nucl.secondaryTracks_end(); itr_++, it++) {
reco::TrackRef secTrack = (*itr_).castTo<reco::TrackRef>();
ClosestApproachInRPhi* theApproach = builder.closestApproach(primTrack, secTrack);
out << "\t\t Secondary track " << it << " : Pt = " << (*itr_)->pt()
<< " - Nhits = " << (*itr_)->numberOfValidHits()
<< " - Dist = " << theApproach->distance()
<< " - chi2 = " << (*itr_)->normalizedChi2() << std::endl;
delete theApproach;
}
out << "----------------" << std::endl;
}
}
|
exialym/React
|
React-example/modules/ReduxTodo/Component/Footer.js
|
<filename>React-example/modules/ReduxTodo/Component/Footer.js
import React, { Component } from 'react'
import {setFilter} from '../actions'
//Filter子组件
const Link = ({active,children,onClick}) => {
if (active) {
return <span>{children}</span>
}
return (
<a href="#" onClick={e => {
e.preventDefault();
onClick();
}}>
{children}
</a>
)
};
//Filter容器,以便state参数不用从顶一直传到这里
class FilterLink extends Component {
componentDidMount() {
const {store} = this.context;
this.unsubscribe = store.subscribe(() => this.forceUpdate());
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
const props = this.props;
const {store} = this.context;
const state = store.getState();
return (
<Link
active={
props.filter===state.visibilityFilter
}
onClick={() => {
store.dispatch(setFilter(props.filter));
}}
>
{props.children}
</Link>
)
}
}
FilterLink.contextTypes = {
store: React.PropTypes.object
};
//Fliters子组件
const Footer = () => (
<p>
Show:{' '}
<FilterLink filter="SHOW_ALL">All</FilterLink>{' '}
<FilterLink filter="SHOW_ACTIVE">Active</FilterLink>{' '}
<FilterLink filter="SHOW_COMPLETED">Completed</FilterLink>
</p>
);
export default Footer;
|
hackervipvhp/CoinExchange
|
00_framework/core/src/main/java/com/bizzan/bitrade/dao/ActivityDao.java
|
package com.bizzan.bitrade.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.stereotype.Repository;
import com.bizzan.bitrade.constant.CommonStatus;
import com.bizzan.bitrade.dao.base.BaseDao;
import com.bizzan.bitrade.entity.Activity;
import com.bizzan.bitrade.entity.Coin;
import com.bizzan.bitrade.entity.MemberTransaction;
@Repository
public interface ActivityDao extends BaseDao<Activity> {
List<Activity> findAllByStep(int step);
List<Activity> findAllByTypeAndStep(int type, int step);
}
|
samuVillegas/peckyPet
|
backend/useCases/Post/CreatePost/index.js
|
const FileRepositoryPostgres = require('../../../repositories/implementations/FileRepositoryPostgres');
const PostRepositoryPostgres = require('../../../repositories/implementations/PostRepositoryPostgres');
const CreatePostUseCase = require('./CreatePostUseCase')
const CreatePostController = require('./CreatePostController')
const fileRepositoryPostgres = new FileRepositoryPostgres();
const postRepositoryPostgres = new PostRepositoryPostgres();
const createPostUseCase = new CreatePostUseCase(
fileRepositoryPostgres,
postRepositoryPostgres
);
const createPostController = new CreatePostController(
createPostUseCase
);
module.exports = {createPostController};
|
Klebert-Engineering/zserio-1
|
test/errors/templates_error/java/templates_error/TemplatesErrorTest.java
|
<filename>test/errors/templates_error/java/templates_error/TemplatesErrorTest.java
package templates_error;
import static org.junit.Assert.*;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import test_utils.ZserioErrors;
public class TemplatesErrorTest
{
@BeforeClass
public static void readZserioErrors() throws IOException
{
zserioErrors = new ZserioErrors();
}
@Test
public void constUsedAsType()
{
final String errors[] =
{
"constant_used_as_type_error.zs:12:16: Unresolved referenced type 'CONST'!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void constraintExpressionsExpectsConstant()
{
final String errors[] =
{
"constraint_expression_expects_constant_error.zs:10:5: " +
"In instantiation of 'TestStruct' required from here",
"constraint_expression_expects_constant_error.zs:5:27: " +
"Unresolved symbol 'uint32' within expression scope!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void duplicatedFieldName()
{
final String errors[] =
{
"duplicated_field_name_error.zs:5:7: First defined here",
"duplicated_field_name_error.zs:6:7: 'value' is already defined in this scope!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void enumNotATemplate()
{
final String error = "enum_not_a_template_error.zs:11:5: 'Enumeration' is not a template!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void fieldNotAvailableInFunction()
{
final String errors[] =
{
"field_not_available_in_function_error.zs:21:5: " +
"In instantiation of 'TestStruct' required from here",
"field_not_available_in_function_error.zs:16:5: " +
"In instantiation of 'FieldNotAvailable' required from here",
"field_not_available_in_function_error.zs:5:30: In function 'getField2' called from here",
"field_not_available_in_function_error.zs:10:16: " +
"Unresolved symbol 'field2' within expression scope!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiateDuplicated()
{
final String errors[] =
{
"instantiate_duplicated_error.zs:8:13: In instantiation of 'Test' required from here",
"instantiate_duplicated_error.zs:8:26: First requested here",
"instantiate_duplicated_error.zs:9:26: Ambiguous request to instantiate template 'Test'!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiateDuplicatedName()
{
final String errors[] =
{
"instantiate_duplicated_name_error.zs:8:26: First defined here",
"instantiate_duplicated_name_error.zs:9:27: 'Str' is already defined in this package!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiateDuplicatedViaImport()
{
final String errors[] =
{
"instantiate_duplicated_via_import_error.zs:5:13: In instantiation of 'Test' required from here",
"instantiate_duplicated_via_import_error.zs:5:26: First requested here",
"pkg.zs:8:26: Ambiguous request to instantiate template 'Test'!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiateMissingTemplateArguments()
{
final String error = "instantiate_missing_template_arguments_error.zs:8:13: " +
"Missing template arguments for template 'Test'!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void instantiateNameClash()
{
final String errors[] =
{
"instantiate_name_clash_error.zs:13:26: First defined here",
"instantiate_name_clash_error.zs:14:27: 'U32' is already defined in this package!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiateNameClashWithTemplate()
{
final String errors[] =
{
"instantiate_name_clash_with_template_error.zs:10:5: In instantiation of 'Test' required from here",
"instantiate_name_clash_with_template_error.zs:13:26: First defined here",
"instantiate_name_clash_with_template_error.zs:3:8: " +
"'Test_uint32' is already defined in package 'instantiate_name_clash_with_template_error'!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiateNameClashWithType()
{
final String errors[] =
{
"instantiate_name_clash_with_type_error.zs:3:8: First defined here",
"instantiate_name_clash_with_type_error.zs:13:26: 'Other' is already defined in this package!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiateNoTemplate()
{
final String error = "instantiate_no_template_error.zs:3:8: 'Test' is not a template!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void instantiateSubtype()
{
final String error = "instantiate_subtype_error.zs:8:22: 'T32' is not a template!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void instantiateTypeInInstantiate()
{
final String error = "instantiate_type_in_instantiate_error.zs:8:26: 'T32' is not a template!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void instantiateTypeIsSqlTable()
{
final String error = "instantiate_type_is_sql_table_error.zs:13:14: " +
"Field 'field' cannot be a sql table!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void instantiationNameClashAcrossPackages()
{
final String errors[] =
{
"pkg2.zs:12:5: In instantiation of 'TestStruct' required from here",
"pkg1.zs:12:5: First instantiated here",
"test_struct.zs:3:8: Instantiation name 'TestStruct_Test' already exits!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiationNameClash()
{
final String errors[] =
{
"instantiation_name_clash_error.zs:38:5: In instantiation of 'TestStruct' required from here",
"instantiation_name_clash_error.zs:33:5: In instantiation of 'Template' required from here",
"instantiation_name_clash_error.zs:32:5: First instantiated here",
"instantiation_name_clash_error.zs:38:5: Required in instantiation of 'TestStruct' from here",
"instantiation_name_clash_error.zs:23:8: Instantiation name 'Template_A_B_C' already exits!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void instantiationNameClashOtherTemplate()
{
final String errors[] =
{
"instantiation_name_clash_other_template_error.zs:21:5: " +
"In instantiation of 'Test' required from here",
"instantiation_name_clash_other_template_error.zs:20:5: " +
" First seen in instantiation of 'Test_A' from here",
"instantiation_name_clash_other_template_error.zs:8:8: " +
"Instantiation name 'Test_A_uint32' already exits!"
};
assertTrue(zserioErrors.isPresent(errors));
};
@Test
public void instantiationNameClashWithType()
{
final String errors[] =
{
"instantiation_name_clash_with_type_error.zs:15:5: In instantiation of 'Test' required from here",
"instantiation_name_clash_with_type_error.zs:3:8: First defined here",
"instantiation_name_clash_with_type_error.zs:8:8: " +
"'Test_uint32' is already defined in package 'instantiation_name_clash_with_type_error'!",
};
assertTrue(zserioErrors.isPresent(errors));
};
@Test
public void instantiationViaSubtype()
{
final String errors[] =
{
"instantiation_via_subtype_error.zs:13:9: In instantiation of 'TestStructure' required from here",
"instantiation_via_subtype_error.zs:9:16: Unexpected dot expression 'field'!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void missingTemplateArguments()
{
final String error = "missing_template_arguments_error.zs:10:5: " +
"Missing template arguments for template 'TestStruct'!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void missingTypeParameters()
{
final String errors[] =
{
"missing_type_parameters_error.zs:15:5: In instantiation of 'TestStruct' required from here",
"missing_type_parameters_error.zs:5:5: " +
"Referenced type 'Parameterized' is defined as parameterized type!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void parameterizedBuiltinType()
{
final String errors[] =
{
"parameterized_builtin_type_error.zs:11:5: In instantiation of 'TestStruct' required from here",
"parameterized_builtin_type_error.zs:6:5: Referenced type 'uint32' is not a parameterized type!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void parameterizedCompoundType()
{
final String errors[] =
{
"parameterized_compound_type_error.zs:16:5: In instantiation of 'TestStruct' required from here",
"parameterized_compound_type_error.zs:11:5: " +
"Referenced type 'Compound' is not a parameterized type!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void symbolWithTemplateParameterClash()
{
final String errors[] =
{
"symbol_with_template_parameter_clash_error.zs:3:19: First defined here",
"symbol_with_template_parameter_clash_error.zs:5:12: 'T' is already defined in this scope!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void symbolWithTypeNameClash()
{
final String errors[] =
{
"symbol_with_type_name_clash_error.zs:15:5: In instantiation of 'TestStruct' required from here",
"symbol_with_type_name_clash_error.zs:5:7: 'Field' is a defined type in this package!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void templatableNotATemplate()
{
final String error = "templatable_not_a_template_error.zs:10:5: 'Templatable' is not a template!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void templatedTemplateParameter()
{
final String error = "templated_template_parameter_error.zs:5:5: " +
"Template parameter cannot be used as a template!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void unresolvedReferenceInTemplate()
{
final String errors[] =
{
"unresolved_reference_in_template_error.zs:10:5: " +
"In instantiation of 'TestStruct' required from here",
"unresolved_reference_in_template_error.zs:5:5: Unresolved referenced type 'Unresolved'!",
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void unresolvedTemplateInstantiation()
{
final String error = "unresolved_template_instantiation_error.zs:5:5: " +
"Unresolved referenced type 'TemplatedStruct'!";
assertTrue(zserioErrors.isPresent(error));
}
@Test
public void unresolvedTemplateInstantiationInTemplate()
{
final String errors[] =
{
"unresolved_template_instantiation_in_template_error.zs:15:5: " +
"In instantiation of 'TestStruct' required from here",
"unresolved_template_instantiation_in_template_error.zs:10:5: " +
"In instantiation of 'InnerStruct' required from here",
"unresolved_template_instantiation_in_template_error.zs:5:5: " +
"Unresolved referenced type 'Unresolved'!"
};
assertTrue(zserioErrors.isPresent(errors));
}
@Test
public void wrongNumberOfArguments()
{
final String error = "wrong_number_of_arguments_error.zs:11:5: " +
"Wrong number of template arguments for template 'TestStruct'! Expecting 2, got 1!";
assertTrue(zserioErrors.isPresent(error));
}
private static ZserioErrors zserioErrors;
}
|
Nuthi-Sriram/C
|
Pointers/Dereferencing a void pointer.c
|
/*P9.26 Dereferencing a void pointer*/
#include<stdio.h>
int main(void)
{
int a=3;
float b=3.4,*fp=&b;
void *vp;
vp=&a;
printf("Value of a = %d\n",*(int *)vp);
*(int *)vp = 12;
printf("Value of a = %d\n",*(int *)vp);
vp=fp;
printf("Value of b = %f\n",*(float *)vp);
return 0;
}
|
Uniandes-isis2603/s1_MaratonesProgramacion_201910
|
s1_maratones-back/src/test/java/co/edu/uniandes/csw/maratones/test/persistence/CompetenciaPersistenceTest.java
|
<gh_stars>0
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package co.edu.uniandes.csw.maratones.test.persistence;
import co.edu.uniandes.csw.maratones.entities.CompetenciaEntity;
import co.edu.uniandes.csw.maratones.persistence.CompetenciaPersistence;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import uk.co.jemos.podam.api.PodamFactory;
import uk.co.jemos.podam.api.PodamFactoryImpl;
/**
*
* @author <NAME> <<EMAIL>>
*/
@RunWith(Arquillian.class)
public class CompetenciaPersistenceTest {
@Inject
private CompetenciaPersistence competenciaPersistence;
@PersistenceContext
private EntityManager em;
@Inject
UserTransaction utx;
private List<CompetenciaEntity> data = new ArrayList<CompetenciaEntity>();
/**
* @return Devuelve el jar que Arquillian va a desplegar en Payara embebido.
* El jar contiene las clases, el descriptor de la base de datos y el
* archivo beans.xml para resolver la inyección de dependencias.
*/
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addPackage(CompetenciaEntity.class.getPackage())
.addPackage(CompetenciaPersistence.class.getPackage())
.addAsManifestResource("META-INF/persistence.xml", "persistence.xml")
.addAsManifestResource("META-INF/beans.xml", "beans.xml");
}
/**
* Configuración inicial de la prueba.
*/
@Before
public void configTest() {
try {
utx.begin();
em.joinTransaction();
clearData();
insertData();
utx.commit();
} catch (Exception e) {
e.printStackTrace();
try {
utx.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
/**
* Limpia las tablas que están implicadas en la prueba.
*/
private void clearData() {
em.createQuery("delete from CompetenciaEntity").executeUpdate();
}
/**
* Inserta los datos iniciales para el correcto funcionamiento de las
* pruebas.
*/
private void insertData() {
PodamFactory factory = new PodamFactoryImpl();
for (int i = 0; i < 3; i++) {
CompetenciaEntity entity = factory.manufacturePojo(CompetenciaEntity.class);
em.persist(entity);
data.add(entity);
}
}
/**
* Prueba para crear una Competencia.
*/
@Test
public void createCompetenciaTest() {
PodamFactory factory = new PodamFactoryImpl();
CompetenciaEntity newEntity = factory.manufacturePojo(CompetenciaEntity.class);
CompetenciaEntity result = competenciaPersistence.create(newEntity);
Assert.assertNotNull(result);
CompetenciaEntity entity = em.find(CompetenciaEntity.class, result.getId());
Assert.assertEquals(newEntity.getNombre(), entity.getNombre());
}
/**
* Prueba para consultar la lista de competencias.
*/
@Test
public void getEditorialsTest() {
List<CompetenciaEntity> list = competenciaPersistence.findAll();
Assert.assertEquals(data.size(), list.size());
for (CompetenciaEntity ent : list) {
boolean found = false;
for (CompetenciaEntity entity : data) {
if (ent.getEjercicioEntitys().equals(entity.getEjercicioEntitys())) {
found = true;
}
}
Assert.assertTrue(found);
}
}
/**
* Prueba para consultar una Editorial.
*/
@Test
public void getEditorialTest() {
CompetenciaEntity entity = data.get(0);
CompetenciaEntity newEntity = competenciaPersistence.find(entity.getId());
Assert.assertNotNull(newEntity);
Assert.assertEquals(entity.getNombre(), newEntity.getNombre());
}
/**
* Prueba para eliminar una Editorial.
*/
@Test
public void deleteEditorialTest() {
CompetenciaEntity entity = data.get(0);
competenciaPersistence.delete(entity.getId());
CompetenciaEntity deleted = em.find(CompetenciaEntity.class, entity.getId());
Assert.assertNull(deleted);
}
/**
* Prueba para actualizar una Editorial.
*/
@Test
public void updateEditorialTest() {
CompetenciaEntity entity = data.get(0);
PodamFactory factory = new PodamFactoryImpl();
CompetenciaEntity newEntity = factory.manufacturePojo(CompetenciaEntity.class);
newEntity.setId(entity.getId());
competenciaPersistence.update(newEntity);
CompetenciaEntity resp = em.find(CompetenciaEntity.class, entity.getId());
Assert.assertEquals(newEntity.getNombre(), resp.getNombre());
}
/**
* Prueba para consultar una Editorial por nombre.
*/
@Test
public void findEditorialByNameTest() {
CompetenciaEntity entity = data.get(0);
CompetenciaEntity newEntity = competenciaPersistence.findByName(entity.getNombre());
Assert.assertNotNull(newEntity);
Assert.assertEquals(entity.getNombre(), newEntity.getNombre());
newEntity = competenciaPersistence.findByName(null);
Assert.assertNull(newEntity);
}
}
|
cybervisiontech/coopr
|
coopr-server/src/main/java/co/cask/coopr/spec/TenantSpecification.java
|
/*
* Copyright © 2012-2014 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package co.cask.coopr.spec;
import com.google.common.base.Objects;
/**
* A tenant as seen from external world, meaning it contains the name and settings for a tenant, but no id.
*/
public final class TenantSpecification extends NamedEntity {
private final String description;
private final int workers;
private final int maxClusters;
private final int maxNodes;
public TenantSpecification(String name, String description, Integer workers, Integer maxClusters, Integer maxNodes) {
super(name);
this.description = description;
this.workers = workers == null ? 0 : workers;
this.maxClusters = maxClusters == null ? Integer.MAX_VALUE : maxClusters;
this.maxNodes = maxNodes == null ? Integer.MAX_VALUE : maxNodes;
}
// TODO: add builder so optional fields are easier to handle
public TenantSpecification(String name, Integer workers, Integer maxClusters, Integer maxNodes) {
this(name, "", workers, maxClusters, maxNodes);
}
public String getDescription() {
return description;
}
public int getWorkers() {
return workers;
}
public int getMaxClusters() {
return maxClusters;
}
public int getMaxNodes() {
return maxNodes;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof TenantSpecification)) {
return false;
}
TenantSpecification other = (TenantSpecification) o;
return Objects.equal(name, other.name) &&
Objects.equal(description, other.description) &&
Objects.equal(workers, other.workers) &&
Objects.equal(maxClusters, other.maxClusters) &&
Objects.equal(maxNodes, other.maxNodes);
}
@Override
public int hashCode() {
return Objects.hashCode(name, description, workers, maxClusters, maxNodes);
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("name", name)
.add("description", description)
.add("workers", workers)
.add("maxClusters", maxClusters)
.add("maxNodes", maxNodes)
.toString();
}
}
|
liulinru13/HXGraph
|
Test/hxgraph/src/main/java/com/hxgraph/model/imp/raw/BarsModel.java
|
package com.hxgraph.model.imp.raw;
import com.hxgraph.model.IPoint;
/**
* 多柱并列的柱状图的数据结构,最基本的数据结构
* Created by liulinru on 2017/4/24.
*/
public class BarsModel implements IPoint {
private BarModel[] barModels;
public BarModel[] getBarModels() {
return barModels;
}
public void setBarModels(BarModel[] barModels) {
this.barModels = barModels;
}
}
|
manhluna/slice
|
filter.go
|
package slice
// FilterBool performs in place filtering of a bool slice based on a predicate
func FilterBool(a []bool, keep func(x bool) bool) []bool {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterByte performs in place filtering of a byte slice based on a predicate
func FilterByte(a []byte, keep func(x byte) bool) []byte {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterComplex128 performs in place filtering of a complex128 slice based on a predicate
func FilterComplex128(a []complex128, keep func(x complex128) bool) []complex128 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterComplex64 performs in place filtering of a complex64 slice based on a predicate
func FilterComplex64(a []complex64, keep func(x complex64) bool) []complex64 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterFloat32 performs in place filtering of a float32 slice based on a predicate
func FilterFloat32(a []float32, keep func(x float32) bool) []float32 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterFloat64 performs in place filtering of a float64 slice based on a predicate
func FilterFloat64(a []float64, keep func(x float64) bool) []float64 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterInt performs in place filtering of an int slice based on a predicate
func FilterInt(a []int, keep func(x int) bool) []int {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterInt16 performs in place filtering of an int16 slice based on a predicate
func FilterInt16(a []int16, keep func(x int16) bool) []int16 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterInt32 performs in place filtering of an int32 slice based on a predicate
func FilterInt32(a []int32, keep func(x int32) bool) []int32 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterInt64 performs in place filtering of an int64 slice based on a predicate
func FilterInt64(a []int64, keep func(x int64) bool) []int64 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterInt8 performs in place filtering of an int8 slice based on a predicate
func FilterInt8(a []int8, keep func(x int8) bool) []int8 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterRune performs in place filtering of a rune slice based on a predicate
func FilterRune(a []rune, keep func(x rune) bool) []rune {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterString performs in place filtering of a string slice based on a predicate
func FilterString(a []string, keep func(x string) bool) []string {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterUint performs in place filtering of a uint slice based on a predicate
func FilterUint(a []uint, keep func(x uint) bool) []uint {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterUint16 performs in place filtering of a uint16 slice based on a predicate
func FilterUint16(a []uint16, keep func(x uint16) bool) []uint16 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterUint32 performs in place filtering of a uint32 slice based on a predicate
func FilterUint32(a []uint32, keep func(x uint32) bool) []uint32 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterUint64 performs in place filtering of a uint64 slice based on a predicate
func FilterUint64(a []uint64, keep func(x uint64) bool) []uint64 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterUint8 performs in place filtering of a uint8 slice based on a predicate
func FilterUint8(a []uint8, keep func(x uint8) bool) []uint8 {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
// FilterUintptr performs in place filtering of a uintptr slice based on a predicate
func FilterUintptr(a []uintptr, keep func(x uintptr) bool) []uintptr {
if len(a) == 0 {
return a
}
n := 0
for _, v := range a {
if keep(v) {
a[n] = v
n++
}
}
return a[:n]
}
|
nhnent/toast-haste.framework
|
objectpool/src/main/java/com/nhnent/haste/objectpool/ObjectPool.java
|
<reponame>nhnent/toast-haste.framework
/*
* Copyright 2016 NHN Entertainment Corp.
*
* NHN Entertainment Corp. licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nhnent.haste.objectpool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.WeakHashMap;
/**
* The object pool based on thread-local. (inspired by Recycler of Netty)
* @param <T> the type of a pooled target object
*/
public abstract class ObjectPool<T extends Poolable> {
private static final Logger logger = LoggerFactory.getLogger(ObjectPool.class);
// TODO Use lambda when upgrading java 1.8
public interface Initializer<PooledType extends Poolable> {
void initialize(PooledType target, Object... parameters);
}
private ThreadLocal<Stack> internalStack;
static ThreadLocal<Map<Stack, DelayedPool>> delayedPooMap = new ThreadLocal<Map<Stack, DelayedPool>>() {
@Override
protected Map<Stack, DelayedPool> initialValue() {
// TODO Consider to change WeakHashMap.
return new WeakHashMap<>();
}
};
static final int DEFAULT_MAX_CAPACITY = 262144;
public ObjectPool() {
this(DEFAULT_MAX_CAPACITY, false, 0);
}
public ObjectPool(final boolean isPreCreate, final int preCreatedCount) {
this(DEFAULT_MAX_CAPACITY, isPreCreate, preCreatedCount);
}
public ObjectPool(final int maxCapacity, final boolean isPreCreate, final int preCreatedCount) {
final ObjectPool<T> thisObject = this;
internalStack = new ThreadLocal<Stack>() {
@Override
protected Stack initialValue() {
int maxStackcapacity = Math.min(maxCapacity, DEFAULT_MAX_CAPACITY);
return new Stack(thisObject, Thread.currentThread(), maxStackcapacity, isPreCreate, preCreatedCount);
}
};
}
DefaultHandle<T> createNewHandle(Stack dstStack) {
DefaultHandle<T> newHandle = new DefaultHandle<>(dstStack);
newHandle.object = newInstance(newHandle);
return newHandle;
}
@SuppressWarnings("unchecked")
public T take() {
return take(null);
}
@SuppressWarnings("unchecked")
public T take(Initializer<T> initializer, Object... parameters) {
Stack stack = internalStack.get();
if (stack != null) {
DefaultHandle<?> handle = stack.pop();
if (handle == null) {
handle = createNewHandle(stack);
}
if (initializer != null) {
initializer.initialize((T) handle.object, parameters);
}
return (T) handle.object;
}
return null;
}
public boolean release(T item, Handle handle) {
if (item == null)
throw new NullPointerException("item");
if (handle == null)
throw new NullPointerException("handle");
Stack stack = internalStack.get();
if (stack == null) {
return false;
}
if (stack.getParent() != this) {
return false;
}
handle.release();
return true;
}
boolean scavengeAll() {
Stack stack = internalStack.get();
if (stack == null) {
return false;
}
return stack.scavengeAll();
}
int getStackCount() {
Stack stack = internalStack.get();
return stack.count();
}
int getStackCapacity() {
Stack stack = internalStack.get();
return stack.currentCapacity;
}
protected abstract T newInstance(Handle handle);
@Override
public String toString() {
Stack stack = internalStack.get();
return stack.toString();
}
}
|
shisa/kame-shisa
|
openbsd/sys/dev/pci/isp_pci.c
|
/* $OpenBSD: isp_pci.c,v 1.35 2003/12/06 14:40:33 grange Exp $ */
/*
* PCI specific probe and attach routines for Qlogic ISP SCSI adapters.
*
*---------------------------------------
* Copyright (c) 1997, 1998, 1999 by <NAME>
* NASA/Ames Research Center
* All rights reserved.
*---------------------------------------
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice immediately at the beginning of the file, without modification,
* this list of conditions, and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#include <dev/ic/isp_openbsd.h>
#include <dev/pci/pcireg.h>
#include <dev/pci/pcivar.h>
#include <dev/pci/pcidevs.h>
static u_int16_t isp_pci_rd_reg(struct ispsoftc *, int);
static void isp_pci_wr_reg(struct ispsoftc *, int, u_int16_t);
#if !(defined(ISP_DISABLE_1080_SUPPORT) && defined(ISP_DISABLE_12160_SUPPORT))
static u_int16_t isp_pci_rd_reg_1080(struct ispsoftc *, int);
static void isp_pci_wr_reg_1080(struct ispsoftc *, int, u_int16_t);
#endif
static int
isp_pci_rd_isr(struct ispsoftc *, u_int16_t *, u_int16_t *, u_int16_t *);
#ifndef ISP_DISABLE_2300_SUPPORT
static int
isp_pci_rd_isr_2300(struct ispsoftc *, u_int16_t *, u_int16_t *, u_int16_t *);
#endif
static int isp_pci_mbxdma(struct ispsoftc *);
static int isp_pci_dmasetup(struct ispsoftc *, struct scsi_xfer *,
ispreq_t *, u_int16_t *, u_int16_t);
static void
isp_pci_dmateardown (struct ispsoftc *, struct scsi_xfer *, u_int16_t);
static void isp_pci_reset1 (struct ispsoftc *);
static void isp_pci_dumpregs (struct ispsoftc *, const char *);
static int isp_pci_intr (void *);
#ifdef ISP_COMPILE_FW
#define ISP_COMPILE_1040_FW 1
#define ISP_COMPILE_1080_FW 1
#define ISP_COMPILE_12160_FW 1
#define ISP_COMPILE_2100_FW 1
#define ISP_COMPILE_2200_FW 1
#define ISP_COMPILE_2300_FW 1
#endif
#if defined(ISP_DISABLE_1040_SUPPORT) || !defined(ISP_COMPILE_1040_FW)
#define ISP_1040_RISC_CODE NULL
#else
#define ISP_1040_RISC_CODE (u_int16_t *) isp_1040_risc_code
#include <dev/microcode/isp/asm_1040.h>
#endif
#if defined(ISP_DISABLE_1080_SUPPORT) || !defined(ISP_COMPILE_1080_FW)
#define ISP_1080_RISC_CODE NULL
#else
#define ISP_1080_RISC_CODE (u_int16_t *) isp_1080_risc_code
#include <dev/microcode/isp/asm_1080.h>
#endif
#if defined(ISP_DISABLE_12160_SUPPORT) || !defined(ISP_COMPILE_12160_FW)
#define ISP_12160_RISC_CODE (u_int16_t *) NULL
#else
#define ISP_12160_RISC_CODE (u_int16_t *) isp_12160_risc_code
#include <dev/microcode/isp/asm_12160.h>
#endif
#if defined(ISP_DISABLE_2100_SUPPORT) || !defined(ISP_COMPILE_2100_FW)
#define ISP_2100_RISC_CODE NULL
#else
#define ISP_2100_RISC_CODE (u_int16_t *) isp_2100_risc_code
#include <dev/microcode/isp/asm_2100.h>
#endif
#if defined(ISP_DISABLE_2200_SUPPORT) || !defined(ISP_COMPILE_2200_FW)
#define ISP_2200_RISC_CODE NULL
#else
#define ISP_2200_RISC_CODE (u_int16_t *) isp_2200_risc_code
#include <dev/microcode/isp/asm_2200.h>
#endif
#if defined(ISP_DISABLE_2300_SUPPORT) || !defined(ISP_COMPILE_2300_FW)
#define ISP_2300_RISC_CODE NULL
#else
#define ISP_2300_RISC_CODE (u_int16_t *) isp_2300_risc_code
#include <dev/microcode/isp/asm_2300.h>
#endif
#ifndef ISP_DISABLE_1020_SUPPORT
static struct ispmdvec mdvec = {
isp_pci_rd_isr,
isp_pci_rd_reg,
isp_pci_wr_reg,
isp_pci_mbxdma,
isp_pci_dmasetup,
isp_pci_dmateardown,
NULL,
isp_pci_reset1,
isp_pci_dumpregs,
ISP_1040_RISC_CODE,
BIU_BURST_ENABLE|BIU_PCI_CONF1_FIFO_64
};
#endif
#ifndef ISP_DISABLE_1080_SUPPORT
static struct ispmdvec mdvec_1080 = {
isp_pci_rd_isr,
isp_pci_rd_reg_1080,
isp_pci_wr_reg_1080,
isp_pci_mbxdma,
isp_pci_dmasetup,
isp_pci_dmateardown,
NULL,
isp_pci_reset1,
isp_pci_dumpregs,
ISP_1080_RISC_CODE,
BIU_BURST_ENABLE|BIU_PCI_CONF1_FIFO_64
};
#endif
#ifndef ISP_DISABLE_12160_SUPPORT
static struct ispmdvec mdvec_12160 = {
isp_pci_rd_isr,
isp_pci_rd_reg_1080,
isp_pci_wr_reg_1080,
isp_pci_mbxdma,
isp_pci_dmasetup,
isp_pci_dmateardown,
NULL,
isp_pci_reset1,
isp_pci_dumpregs,
ISP_12160_RISC_CODE,
BIU_BURST_ENABLE|BIU_PCI_CONF1_FIFO_64
};
#endif
#ifndef ISP_DISABLE_2100_SUPPORT
static struct ispmdvec mdvec_2100 = {
isp_pci_rd_isr,
isp_pci_rd_reg,
isp_pci_wr_reg,
isp_pci_mbxdma,
isp_pci_dmasetup,
isp_pci_dmateardown,
NULL,
isp_pci_reset1,
isp_pci_dumpregs,
ISP_2100_RISC_CODE
};
#endif
#ifndef ISP_DISABLE_2200_SUPPORT
static struct ispmdvec mdvec_2200 = {
isp_pci_rd_isr,
isp_pci_rd_reg,
isp_pci_wr_reg,
isp_pci_mbxdma,
isp_pci_dmasetup,
isp_pci_dmateardown,
NULL,
isp_pci_reset1,
isp_pci_dumpregs,
ISP_2200_RISC_CODE
};
#endif
#ifndef ISP_DISABLE_2300_SUPPORT
static struct ispmdvec mdvec_2300 = {
isp_pci_rd_isr_2300,
isp_pci_rd_reg,
isp_pci_wr_reg,
isp_pci_mbxdma,
isp_pci_dmasetup,
isp_pci_dmateardown,
NULL,
isp_pci_reset1,
isp_pci_dumpregs,
ISP_2300_RISC_CODE
};
#endif
#ifndef PCI_VENDOR_QLOGIC
#define PCI_VENDOR_QLOGIC 0x1077
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP1020
#define PCI_PRODUCT_QLOGIC_ISP1020 0x1020
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP1080
#define PCI_PRODUCT_QLOGIC_ISP1080 0x1080
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP1240
#define PCI_PRODUCT_QLOGIC_ISP1240 0x1240
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP1280
#define PCI_PRODUCT_QLOGIC_ISP1280 0x1280
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP10160
#define PCI_PRODUCT_QLOGIC_ISP10160 0x1016
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP12160
#define PCI_PRODUCT_QLOGIC_ISP12160 0x1216
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP2100
#define PCI_PRODUCT_QLOGIC_ISP2100 0x2100
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP2200
#define PCI_PRODUCT_QLOGIC_ISP2200 0x2200
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP2300
#define PCI_PRODUCT_QLOGIC_ISP2300 0x2300
#endif
#ifndef PCI_PRODUCT_QLOGIC_ISP2312
#define PCI_PRODUCT_QLOGIC_ISP2312 0x2312
#endif
#define PCI_QLOGIC_ISP ((PCI_PRODUCT_QLOGIC_ISP1020 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP1080 \
((PCI_PRODUCT_QLOGIC_ISP1080 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP1240 \
((PCI_PRODUCT_QLOGIC_ISP1240 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP1280 \
((PCI_PRODUCT_QLOGIC_ISP1280 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP10160 \
((PCI_PRODUCT_QLOGIC_ISP10160 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP12160 \
((PCI_PRODUCT_QLOGIC_ISP12160 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP2100 \
((PCI_PRODUCT_QLOGIC_ISP2100 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP2200 \
((PCI_PRODUCT_QLOGIC_ISP2200 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP2300 \
((PCI_PRODUCT_QLOGIC_ISP2300 << 16) | PCI_VENDOR_QLOGIC)
#define PCI_QLOGIC_ISP2312 \
((PCI_PRODUCT_QLOGIC_ISP2312 << 16) | PCI_VENDOR_QLOGIC)
/*
* Odd case for some AMI raid cards... We need to *not* attach to this.
*/
#define AMI_RAID_SUBVENDOR_ID 0x101e
#define IO_MAP_REG 0x10
#define MEM_MAP_REG 0x14
#define PCIR_ROMADDR 0x30
#define PCI_DFLT_LTNCY 0x40
#define PCI_DFLT_LNSZ 0x10
#ifndef SCSI_ISP_PREFER_MEM_MAP
#ifdef __alpha__
#define SCSI_ISP_PREFER_MEM_MAP 1
#else
#define SCSI_ISP_PREFER_MEM_MAP 0
#endif
#endif
#ifndef BUS_DMA_COHERENT
#define BUS_DMA_COHERENT BUS_DMAMEM_NOSYNC
#endif
static int isp_pci_probe (struct device *, void *, void *);
static void isp_pci_attach (struct device *, struct device *, void *);
struct isp_pcisoftc {
struct ispsoftc pci_isp;
pci_chipset_tag_t pci_pc;
pcitag_t pci_tag;
bus_space_tag_t pci_st;
bus_space_handle_t pci_sh;
bus_dmamap_t *pci_xfer_dmap;
void * pci_ih;
int16_t pci_poff[_NREG_BLKS];
};
struct cfattach isp_pci_ca = {
sizeof (struct isp_pcisoftc), isp_pci_probe, isp_pci_attach
};
#ifdef DEBUG
const char vstring[] =
"Qlogic ISP Driver, NetBSD (pci) Platform Version %d.%d Core Version %d.%d";
#endif
const struct pci_matchid ispdev[] = {
#ifndef ISP_DISABLE_1020_SUPPORT
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP1020 },
#endif
#ifndef ISP_DISABLE_1080_SUPPORT
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP1080 },
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP1240 },
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP1280 },
#endif
#ifndef ISP_DISABLE_12160_SUPPORT
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP10160 },
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP12160 },
#endif
#ifndef ISP_DISABLE_2100_SUPPORT
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP2100 },
#endif
#ifndef ISP_DISABLE_2200_SUPPORT
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP2200 },
#endif
#ifndef ISP_DISABLE_2300_SUPPORT
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP2300 },
{ PCI_VENDOR_QLOGIC, PCI_PRODUCT_QLOGIC_ISP2312 },
#endif
{ 0, 0 }
};
static int
isp_pci_probe(struct device *parent, void *match, void *aux)
{
struct pci_attach_args *pa = aux;
#ifndef ISP_DISABLE_12160_SUPPORT
/*
* Sigh. Check for subvendor id match here. Too bad we
* can't give an exclude mask in matchbyid.
*/
if (pa->pa_id == PCI_QLOGIC_ISP12160) {
pcireg_t subvid =
pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_SUBVEND_0);
if (PCI_VENDOR(subvid) == AMI_RAID_SUBVENDOR_ID) {
return (0);
}
}
#endif
return (pci_matchbyid(pa, ispdev, sizeof(ispdev)/sizeof(ispdev[0])));
}
static void
isp_pci_attach(struct device *parent, struct device *self, void *aux)
{
#ifdef DEBUG
static char oneshot = 1;
#endif
static const char nomem[] = ": no mem for sdparam table\n";
u_int32_t data, rev, linesz = PCI_DFLT_LNSZ;
struct pci_attach_args *pa = aux;
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *) self;
struct ispsoftc *isp = &pcs->pci_isp;
bus_space_tag_t st, iot, memt;
bus_space_handle_t sh, ioh, memh;
pci_intr_handle_t ih;
const char *intrstr;
int ioh_valid, memh_valid;
bus_addr_t iobase, mbase;
bus_size_t iosize, msize;
ioh_valid = memh_valid = 0;
#if SCSI_ISP_PREFER_MEM_MAP == 1
if (pci_mem_find(pa->pa_pc, pa->pa_tag, MEM_MAP_REG, &mbase, &msize,
NULL)) {
printf(": can't find mem space\n");
} else if (bus_space_map(pa->pa_memt, mbase, msize, 0, &memh)) {
printf(": can't map mem space\n");
} else {
memt = pa->pa_memt;
st = memt;
sh = memh;
memh_valid = 1;
}
if (memh_valid == 0) {
if (pci_io_find(pa->pa_pc, pa->pa_tag, IO_MAP_REG, &iobase,
&iosize)) {
printf(": can't find i/o space\n");
} else if (bus_space_map(pa->pa_iot, iobase, iosize, 0, &ioh)) {
printf(": can't map i/o space\n");
} else {
iot = pa->pa_iot;
st = iot;
sh = ioh;
ioh_valid = 1;
}
}
#else
if (pci_io_find(pa->pa_pc, pa->pa_tag, IO_MAP_REG, &iobase, &iosize)) {
printf(": can't find i/o space\n");
} else if (bus_space_map(pa->pa_iot, iobase, iosize, 0, &ioh)) {
printf(": can't map i/o space\n");
} else {
iot = pa->pa_iot;
st = iot;
sh = ioh;
ioh_valid = 1;
}
if (ioh_valid == 0) {
if (pci_mem_find(pa->pa_pc, pa->pa_tag, MEM_MAP_REG, &mbase,
&msize, NULL)) {
printf(": can't find mem space\n");
} else if (bus_space_map(pa->pa_memt, mbase, msize, 0, &memh)) {
printf(": can't map mem space\n");
} else {
memt = pa->pa_memt;
st = memt;
sh = memh;
memh_valid = 1;
}
}
#endif
if (ioh_valid == 0 && memh_valid == 0) {
printf(": unable to map device registers\n");
return;
}
#if 0
printf("\n");
#endif
pcs->pci_st = st;
pcs->pci_sh = sh;
pcs->pci_pc = pa->pa_pc;
pcs->pci_tag = pa->pa_tag;
pcs->pci_poff[BIU_BLOCK >> _BLK_REG_SHFT] = BIU_REGS_OFF;
pcs->pci_poff[MBOX_BLOCK >> _BLK_REG_SHFT] = PCI_MBOX_REGS_OFF;
pcs->pci_poff[SXP_BLOCK >> _BLK_REG_SHFT] = PCI_SXP_REGS_OFF;
pcs->pci_poff[RISC_BLOCK >> _BLK_REG_SHFT] = PCI_RISC_REGS_OFF;
pcs->pci_poff[DMA_BLOCK >> _BLK_REG_SHFT] = DMA_REGS_OFF;
rev = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_CLASS_REG) & 0xff;
#ifndef ISP_DISABLE_1020_SUPPORT
if (pa->pa_id == PCI_QLOGIC_ISP) {
isp->isp_mdvec = &mdvec;
isp->isp_type = ISP_HA_SCSI_UNKNOWN;
isp->isp_param = malloc(sizeof (sdparam), M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, sizeof (sdparam));
}
#endif
#ifndef ISP_DISABLE_1080_SUPPORT
if (pa->pa_id == PCI_QLOGIC_ISP1080) {
isp->isp_mdvec = &mdvec_1080;
isp->isp_type = ISP_HA_SCSI_1080;
isp->isp_param = malloc(sizeof (sdparam), M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, sizeof (sdparam));
pcs->pci_poff[DMA_BLOCK >> _BLK_REG_SHFT] =
ISP1080_DMA_REGS_OFF;
}
if (pa->pa_id == PCI_QLOGIC_ISP1240) {
isp->isp_mdvec = &mdvec_1080;
isp->isp_type = ISP_HA_SCSI_1240;
isp->isp_param = malloc(2 * sizeof (sdparam),
M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, sizeof (sdparam));
pcs->pci_poff[DMA_BLOCK >> _BLK_REG_SHFT] =
ISP1080_DMA_REGS_OFF;
}
if (pa->pa_id == PCI_QLOGIC_ISP1280) {
isp->isp_mdvec = &mdvec_1080;
isp->isp_type = ISP_HA_SCSI_1280;
isp->isp_param = malloc(2 * sizeof (sdparam),
M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, sizeof (sdparam));
pcs->pci_poff[DMA_BLOCK >> _BLK_REG_SHFT] =
ISP1080_DMA_REGS_OFF;
}
#endif
#ifndef ISP_DISABLE_12160_SUPPORT
if (pa->pa_id == PCI_QLOGIC_ISP10160) {
isp->isp_mdvec = &mdvec_12160;
isp->isp_type = ISP_HA_SCSI_10160;
isp->isp_param = malloc(sizeof (sdparam), M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, sizeof (sdparam));
pcs->pci_poff[DMA_BLOCK >> _BLK_REG_SHFT] =
ISP1080_DMA_REGS_OFF;
}
if (pa->pa_id == PCI_QLOGIC_ISP12160) {
isp->isp_mdvec = &mdvec_12160;
isp->isp_type = ISP_HA_SCSI_12160;
isp->isp_param = malloc(2 * sizeof (sdparam),
M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, 2 * sizeof (sdparam));
pcs->pci_poff[DMA_BLOCK >> _BLK_REG_SHFT] =
ISP1080_DMA_REGS_OFF;
}
#endif
#ifndef ISP_DISABLE_2100_SUPPORT
if (pa->pa_id == PCI_QLOGIC_ISP2100) {
isp->isp_mdvec = &mdvec_2100;
isp->isp_type = ISP_HA_FC_2100;
isp->isp_param = malloc(sizeof (fcparam), M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, sizeof (fcparam));
pcs->pci_poff[MBOX_BLOCK >> _BLK_REG_SHFT] =
PCI_MBOX_REGS2100_OFF;
if (rev < 3) {
/*
* XXX: Need to get the actual revision
* XXX: number of the 2100 FB. At any rate,
* XXX: lower cache line size for early revision
* XXX; boards.
*/
linesz = 1;
}
}
#endif
#ifndef ISP_DISABLE_2200_SUPPORT
if (pa->pa_id == PCI_QLOGIC_ISP2200) {
isp->isp_mdvec = &mdvec_2200;
isp->isp_type = ISP_HA_FC_2200;
isp->isp_param = malloc(sizeof (fcparam), M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, sizeof (fcparam));
pcs->pci_poff[MBOX_BLOCK >> _BLK_REG_SHFT] =
PCI_MBOX_REGS2100_OFF;
data = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_CLASS_REG);
}
#endif
#ifndef ISP_DISABLE_2300_SUPPORT
if (pa->pa_id == PCI_QLOGIC_ISP2300 ||
pa->pa_id == PCI_QLOGIC_ISP2312) {
isp->isp_mdvec = &mdvec_2300;
if (pa->pa_id == PCI_QLOGIC_ISP2300) {
isp->isp_type = ISP_HA_FC_2300;
} else {
isp->isp_type = ISP_HA_FC_2312;
isp->isp_port = pa->pa_function;
}
isp->isp_param = malloc(sizeof (fcparam), M_DEVBUF, M_NOWAIT);
if (isp->isp_param == NULL) {
printf(nomem);
return;
}
bzero(isp->isp_param, sizeof (fcparam));
pcs->pci_poff[MBOX_BLOCK >> _BLK_REG_SHFT] =
PCI_MBOX_REGS2300_OFF;
data = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_CLASS_REG);
}
#endif
/*
* Set up logging levels.
*/
#ifdef ISP_LOGDEFAULT
isp->isp_dblev = ISP_LOGDEFAULT;
#else
isp->isp_dblev = ISP_LOGWARN|ISP_LOGERR;
#ifdef SCSIDEBUG
isp->isp_dblev |= ISP_LOGDEBUG1|ISP_LOGDEBUG2;
#endif
#ifdef DEBUG
isp->isp_dblev |= ISP_LOGDEBUG0|ISP_LOGCONFIG|ISP_LOGINFO;
#endif
#endif
#ifdef DEBUG
if (oneshot) {
oneshot = 0;
isp_prt(isp, ISP_LOGCONFIG, vstring,
ISP_PLATFORM_VERSION_MAJOR, ISP_PLATFORM_VERSION_MINOR,
ISP_CORE_VERSION_MAJOR, ISP_CORE_VERSION_MINOR);
}
#endif
isp->isp_dmatag = pa->pa_dmat;
isp->isp_revision = rev;
/*
* Make sure that command register set sanely.
*/
data = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG);
if (IS_2300(isp)) { /* per QLogic errata */
data &= ~PCI_COMMAND_PARITY_ENABLE;
}
if (IS_23XX(isp)) {
isp->isp_touched = 1;
}
data |= PCI_COMMAND_MASTER_ENABLE | PCI_COMMAND_INVALIDATE_ENABLE;
/*
* Not so sure about these- but I think it's important that they get
* enabled......
*/
data |= PCI_COMMAND_PARITY_ENABLE | PCI_COMMAND_SERR_ENABLE;
pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG, data);
/*
* Make sure that the latency timer, cache line size,
* and ROM is disabled.
*/
data = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_BHLC_REG);
data &= ~(PCI_LATTIMER_MASK << PCI_LATTIMER_SHIFT);
data &= ~(PCI_CACHELINE_MASK << PCI_CACHELINE_SHIFT);
data |= (0x40 << PCI_LATTIMER_SHIFT);
data |= (0x10 << PCI_CACHELINE_SHIFT);
pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_BHLC_REG, data);
data = pci_conf_read(pa->pa_pc, pa->pa_tag, PCIR_ROMADDR);
data &= ~1;
pci_conf_write(pa->pa_pc, pa->pa_tag, PCIR_ROMADDR, data);
if (pci_intr_map(pa, &ih)) {
printf(": couldn't map interrupt\n");
free(isp->isp_param, M_DEVBUF);
return;
}
intrstr = pci_intr_string(pa->pa_pc, ih);
if (intrstr == NULL)
intrstr = "<I dunno>";
pcs->pci_ih = pci_intr_establish(pa->pa_pc, ih, IPL_BIO, isp_pci_intr,
isp, isp->isp_name);
if (pcs->pci_ih == NULL) {
printf(": couldn't establish interrupt at %s\n",
intrstr);
free(isp->isp_param, M_DEVBUF);
return;
}
printf(": %s\n", intrstr);
if (IS_FC(isp)) {
DEFAULT_NODEWWN(isp) = 0x400000007F000003ULL;
DEFAULT_PORTWWN(isp) = 0x400000007F000003ULL;
}
isp->isp_confopts = self->dv_cfdata->cf_flags;
isp->isp_role = ISP_DEFAULT_ROLES;
ISP_LOCK(isp);
isp->isp_osinfo.no_mbox_ints = 1;
isp_reset(isp);
if (isp->isp_state != ISP_RESETSTATE) {
ISP_UNLOCK(isp);
free(isp->isp_param, M_DEVBUF);
return;
}
ENABLE_INTS(isp);
isp_init(isp);
if (isp->isp_state != ISP_INITSTATE) {
isp_uninit(isp);
ISP_UNLOCK(isp);
free(isp->isp_param, M_DEVBUF);
return;
}
/*
* Do Generic attach now.
*/
isp_attach(isp);
if (isp->isp_state != ISP_RUNSTATE) {
isp_uninit(isp);
ISP_UNLOCK(isp);
free(isp->isp_param, M_DEVBUF);
} else {
ISP_UNLOCK(isp);
}
}
#define IspVirt2Off(a, x) \
(((struct isp_pcisoftc *)a)->pci_poff[((x) & _BLK_REG_MASK) >> \
_BLK_REG_SHFT] + ((x) & 0xff))
#define BXR2(pcs, off) \
bus_space_read_2(pcs->pci_st, pcs->pci_sh, off)
#define BXW2(pcs, off, v) \
bus_space_write_2(pcs->pci_st, pcs->pci_sh, off, v)
static INLINE int
isp_pci_rd_debounced(struct ispsoftc *isp, int off, u_int16_t *rp)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *) isp;
u_int16_t val0, val1;
int i = 0;
do {
val0 = BXR2(pcs, IspVirt2Off(isp, off));
val1 = BXR2(pcs, IspVirt2Off(isp, off));
} while (val0 != val1 && ++i < 1000);
if (val0 != val1) {
return (1);
}
*rp = val0;
return (0);
}
static int
isp_pci_rd_isr(struct ispsoftc *isp, u_int16_t *isrp,
u_int16_t *semap, u_int16_t *mbp)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *) isp;
u_int16_t isr, sema;
if (IS_2100(isp)) {
if (isp_pci_rd_debounced(isp, BIU_ISR, &isr)) {
return (0);
}
if (isp_pci_rd_debounced(isp, BIU_SEMA, &sema)) {
return (0);
}
} else {
isr = BXR2(pcs, IspVirt2Off(isp, BIU_ISR));
sema = BXR2(pcs, IspVirt2Off(isp, BIU_SEMA));
}
isp_prt(isp, ISP_LOGDEBUG3, "ISR 0x%x SEMA 0x%x", isr, sema);
isr &= INT_PENDING_MASK(isp);
sema &= BIU_SEMA_LOCK;
if (isr == 0 && sema == 0) {
return (0);
}
*isrp = isr;
if ((*semap = sema) != 0) {
if (IS_2100(isp)) {
if (isp_pci_rd_debounced(isp, OUTMAILBOX0, mbp)) {
return (0);
}
} else {
*mbp = BXR2(pcs, IspVirt2Off(isp, OUTMAILBOX0));
}
}
return (1);
}
#ifndef ISP_DISABLE_2300_SUPPORT
static int
isp_pci_rd_isr_2300(struct ispsoftc *isp, u_int16_t *isrp,
u_int16_t *semap, u_int16_t *mbox0p)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *) isp;
u_int32_t r2hisr;
if (!(BXR2(pcs, IspVirt2Off(isp, BIU_ISR)) & BIU2100_ISR_RISC_INT)) {
*isrp = 0;
return (0);
}
r2hisr = bus_space_read_4(pcs->pci_st, pcs->pci_sh,
IspVirt2Off(pcs, BIU_R2HSTSLO));
isp_prt(isp, ISP_LOGDEBUG3, "RISC2HOST ISR 0x%x", r2hisr);
if ((r2hisr & BIU_R2HST_INTR) == 0) {
*isrp = 0;
return (0);
}
switch (r2hisr & BIU_R2HST_ISTAT_MASK) {
case ISPR2HST_ROM_MBX_OK:
case ISPR2HST_ROM_MBX_FAIL:
case ISPR2HST_MBX_OK:
case ISPR2HST_MBX_FAIL:
case ISPR2HST_ASYNC_EVENT:
*isrp = r2hisr & 0xffff;
*mbox0p = (r2hisr >> 16);
*semap = 1;
return (1);
case ISPR2HST_RIO_16:
*isrp = r2hisr & 0xffff;
*mbox0p = ASYNC_RIO1;
*semap = 1;
return (1);
case ISPR2HST_FPOST:
*isrp = r2hisr & 0xffff;
*mbox0p = ASYNC_CMD_CMPLT;
*semap = 1;
return (1);
case ISPR2HST_FPOST_CTIO:
*isrp = r2hisr & 0xffff;
*mbox0p = ASYNC_CTIO_DONE;
*semap = 1;
return (1);
case ISPR2HST_RSPQ_UPDATE:
*isrp = r2hisr & 0xffff;
*mbox0p = 0;
*semap = 0;
return (1);
default:
return (0);
}
}
#endif
static u_int16_t
isp_pci_rd_reg(struct ispsoftc *isp, int regoff)
{
u_int16_t rv;
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *) isp;
int oldconf = 0;
if ((regoff & _BLK_REG_MASK) == SXP_BLOCK) {
/*
* We will assume that someone has paused the RISC processor.
*/
oldconf = BXR2(pcs, IspVirt2Off(isp, BIU_CONF1));
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1),
oldconf | BIU_PCI_CONF1_SXP);
}
rv = BXR2(pcs, IspVirt2Off(isp, regoff));
if ((regoff & _BLK_REG_MASK) == SXP_BLOCK) {
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1), oldconf);
}
return (rv);
}
static void
isp_pci_wr_reg(struct ispsoftc *isp, int regoff, u_int16_t val)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *) isp;
int oldconf = 0;
if ((regoff & _BLK_REG_MASK) == SXP_BLOCK) {
/*
* We will assume that someone has paused the RISC processor.
*/
oldconf = BXR2(pcs, IspVirt2Off(isp, BIU_CONF1));
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1),
oldconf | BIU_PCI_CONF1_SXP);
}
BXW2(pcs, IspVirt2Off(isp, regoff), val);
if ((regoff & _BLK_REG_MASK) == SXP_BLOCK) {
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1), oldconf);
}
}
#if !(defined(ISP_DISABLE_1080_SUPPORT) && defined(ISP_DISABLE_12160_SUPPORT))
static u_int16_t
isp_pci_rd_reg_1080(struct ispsoftc *isp, int regoff)
{
u_int16_t rv, oc = 0;
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *) isp;
if ((regoff & _BLK_REG_MASK) == SXP_BLOCK ||
(regoff & _BLK_REG_MASK) == (SXP_BLOCK|SXP_BANK1_SELECT)) {
u_int16_t tc;
/*
* We will assume that someone has paused the RISC processor.
*/
oc = BXR2(pcs, IspVirt2Off(isp, BIU_CONF1));
tc = oc & ~BIU_PCI1080_CONF1_DMA;
if (regoff & SXP_BANK1_SELECT)
tc |= BIU_PCI1080_CONF1_SXP1;
else
tc |= BIU_PCI1080_CONF1_SXP0;
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1), tc);
} else if ((regoff & _BLK_REG_MASK) == DMA_BLOCK) {
oc = BXR2(pcs, IspVirt2Off(isp, BIU_CONF1));
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1),
oc | BIU_PCI1080_CONF1_DMA);
}
rv = BXR2(pcs, IspVirt2Off(isp, regoff));
if (oc) {
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1), oc);
}
return (rv);
}
static void
isp_pci_wr_reg_1080(struct ispsoftc *isp, int regoff, u_int16_t val)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *) isp;
int oc = 0;
if ((regoff & _BLK_REG_MASK) == SXP_BLOCK ||
(regoff & _BLK_REG_MASK) == (SXP_BLOCK|SXP_BANK1_SELECT)) {
u_int16_t tc;
/*
* We will assume that someone has paused the RISC processor.
*/
oc = BXR2(pcs, IspVirt2Off(isp, BIU_CONF1));
tc = oc & ~BIU_PCI1080_CONF1_DMA;
if (regoff & SXP_BANK1_SELECT)
tc |= BIU_PCI1080_CONF1_SXP1;
else
tc |= BIU_PCI1080_CONF1_SXP0;
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1), tc);
} else if ((regoff & _BLK_REG_MASK) == DMA_BLOCK) {
oc = BXR2(pcs, IspVirt2Off(isp, BIU_CONF1));
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1),
oc | BIU_PCI1080_CONF1_DMA);
}
BXW2(pcs, IspVirt2Off(isp, regoff), val);
if (oc) {
BXW2(pcs, IspVirt2Off(isp, BIU_CONF1), oc);
}
}
#endif
static int
isp_pci_mbxdma(struct ispsoftc *isp)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *)isp;
bus_dma_tag_t dmat = isp->isp_dmatag;
bus_dma_segment_t sg;
bus_size_t len;
fcparam *fcp;
int rs, i;
if (isp->isp_rquest_dma) /* been here before? */
return (0);
len = isp->isp_maxcmds * sizeof (XS_T *);
isp->isp_xflist = (XS_T **) malloc(len, M_DEVBUF, M_WAITOK);
if (isp->isp_xflist == NULL) {
isp_prt(isp, ISP_LOGERR, "cannot malloc xflist array");
return (1);
}
bzero(isp->isp_xflist, len);
len = isp->isp_maxcmds * sizeof (bus_dmamap_t);
pcs->pci_xfer_dmap = (bus_dmamap_t *) malloc(len, M_DEVBUF, M_WAITOK);
if (pcs->pci_xfer_dmap == NULL) {
free(isp->isp_xflist, M_DEVBUF);
isp->isp_xflist = NULL;
isp_prt(isp, ISP_LOGERR, "cannot malloc dma map array");
return (1);
}
for (i = 0; i < isp->isp_maxcmds; i++) {
if (bus_dmamap_create(dmat, MAXPHYS, (MAXPHYS / NBPG) + 1,
MAXPHYS, 0, BUS_DMA_NOWAIT, &pcs->pci_xfer_dmap[i])) {
isp_prt(isp, ISP_LOGERR, "cannot create dma maps");
break;
}
}
if (i < isp->isp_maxcmds) {
while (--i >= 0) {
bus_dmamap_destroy(dmat, pcs->pci_xfer_dmap[i]);
}
free(isp->isp_xflist, M_DEVBUF);
free(pcs->pci_xfer_dmap, M_DEVBUF);
isp->isp_xflist = NULL;
pcs->pci_xfer_dmap = NULL;
return (1);
}
/*
* Allocate and map the request queue.
*/
len = ISP_QUEUE_SIZE(RQUEST_QUEUE_LEN(isp));
if (bus_dmamem_alloc(dmat, len, PAGE_SIZE, 0, &sg, 1, &rs,
BUS_DMA_NOWAIT) ||
bus_dmamem_map(isp->isp_dmatag, &sg, rs, len,
(caddr_t *)&isp->isp_rquest, BUS_DMA_NOWAIT|BUS_DMA_COHERENT)) {
goto dmafail;
}
if (bus_dmamap_create(dmat, len, 1, len, 0, BUS_DMA_NOWAIT,
&isp->isp_rqdmap) || bus_dmamap_load(dmat, isp->isp_rqdmap,
(caddr_t)isp->isp_rquest, len, NULL,
BUS_DMA_NOWAIT)) {
goto dmafail;
}
isp->isp_rquest_dma = isp->isp_rqdmap->dm_segs[0].ds_addr;
/*
* Allocate and map the result queue.
*/
len = ISP_QUEUE_SIZE(RESULT_QUEUE_LEN(isp));
if (bus_dmamem_alloc(dmat, len, PAGE_SIZE, 0, &sg, 1, &rs,
BUS_DMA_NOWAIT) ||
bus_dmamem_map(dmat, &sg, rs, len, (caddr_t *)&isp->isp_result,
BUS_DMA_NOWAIT|BUS_DMA_COHERENT)) {
goto dmafail;
}
if (bus_dmamap_create(dmat, len, 1, len, 0, BUS_DMA_NOWAIT,
&isp->isp_rsdmap) || bus_dmamap_load(isp->isp_dmatag,
isp->isp_rsdmap, (caddr_t)isp->isp_result, len, NULL,
BUS_DMA_NOWAIT)) {
goto dmafail;
}
isp->isp_result_dma = isp->isp_rsdmap->dm_segs[0].ds_addr;
if (IS_SCSI(isp)) {
return (0);
}
fcp = isp->isp_param;
len = ISP2100_SCRLEN;
if (bus_dmamem_alloc(dmat, len, PAGE_SIZE, 0, &sg, 1, &rs,
BUS_DMA_NOWAIT) ||
bus_dmamem_map(dmat, &sg, rs, len, (caddr_t *)&fcp->isp_scratch,
BUS_DMA_NOWAIT|BUS_DMA_COHERENT)) {
goto dmafail;
}
if (bus_dmamap_create(dmat, len, 1, len, 0, BUS_DMA_NOWAIT,
&isp->isp_scdmap) || bus_dmamap_load(dmat,
isp->isp_scdmap, (caddr_t)fcp->isp_scratch, len, NULL,
BUS_DMA_NOWAIT)) {
goto dmafail;
}
fcp->isp_scdma = isp->isp_scdmap->dm_segs[0].ds_addr;
return (0);
dmafail:
isp_prt(isp, ISP_LOGERR, "mailbox dma setup failure");
for (i = 0; i < isp->isp_maxcmds; i++) {
bus_dmamap_destroy(dmat, pcs->pci_xfer_dmap[i]);
}
free(isp->isp_xflist, M_DEVBUF);
free(pcs->pci_xfer_dmap, M_DEVBUF);
isp->isp_xflist = NULL;
pcs->pci_xfer_dmap = NULL;
return (1);
}
static int
isp_pci_dmasetup(struct ispsoftc *isp, XS_T *xs, ispreq_t *rq,
u_int16_t *nxtip, u_int16_t optr)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *)isp;
bus_dmamap_t dmap;
u_int16_t starti = isp->isp_reqidx, nxti = *nxtip;
ispreq_t *qep;
int segcnt, seg, error, ovseg, seglim, drq;
qep = (ispreq_t *) ISP_QUEUE_ENTRY(isp->isp_rquest, starti);
dmap = pcs->pci_xfer_dmap[isp_handle_index(rq->req_handle)];
if (xs->datalen == 0) {
rq->req_seg_count = 1;
goto mbxsync;
}
if (xs->flags & SCSI_DATA_IN) {
drq = REQFLAG_DATA_IN;
} else {
drq = REQFLAG_DATA_OUT;
}
if (IS_FC(isp)) {
seglim = ISP_RQDSEG_T2;
((ispreqt2_t *)rq)->req_totalcnt = xs->datalen;
((ispreqt2_t *)rq)->req_flags |= drq;
} else {
rq->req_flags |= drq;
if (XS_CDBLEN(xs) > 12)
seglim = 0;
else
seglim = ISP_RQDSEG;
}
error = bus_dmamap_load(isp->isp_dmatag, dmap, xs->data, xs->datalen,
NULL, (xs->flags & SCSI_NOSLEEP) ? BUS_DMA_NOWAIT : BUS_DMA_WAITOK);
if (error) {
XS_SETERR(xs, HBA_BOTCH);
return (CMD_COMPLETE);
}
segcnt = dmap->dm_nsegs;
isp_prt(isp, ISP_LOGDEBUG2, "%d byte %s %p in %d segs",
xs->datalen, (xs->flags & SCSI_DATA_IN)? "read to" :
"write from", xs->data, segcnt);
for (seg = 0, rq->req_seg_count = 0;
seg < segcnt && rq->req_seg_count < seglim;
seg++, rq->req_seg_count++) {
if (isp->isp_type & ISP_HA_FC) {
ispreqt2_t *rq2 = (ispreqt2_t *)rq;
rq2->req_dataseg[rq2->req_seg_count].ds_count =
dmap->dm_segs[seg].ds_len;
rq2->req_dataseg[rq2->req_seg_count].ds_base =
dmap->dm_segs[seg].ds_addr;
} else {
rq->req_dataseg[rq->req_seg_count].ds_count =
dmap->dm_segs[seg].ds_len;
rq->req_dataseg[rq->req_seg_count].ds_base =
dmap->dm_segs[seg].ds_addr;
}
isp_prt(isp, ISP_LOGDEBUG2, "seg0.[%d]={0x%lx,%lu}",
rq->req_seg_count, (long) dmap->dm_segs[seg].ds_addr,
(unsigned long) dmap->dm_segs[seg].ds_len);
}
if (seg == segcnt) {
goto dmasync;
}
do {
u_int16_t onxti;
ispcontreq_t *crq, *cqe, local;
crq = &local;
cqe = (ispcontreq_t *) ISP_QUEUE_ENTRY(isp->isp_rquest, nxti);
onxti = nxti;
nxti = ISP_NXT_QENTRY(onxti, RQUEST_QUEUE_LEN(isp));
if (nxti == optr) {
isp_prt(isp, ISP_LOGDEBUG0, "Request Queue Overflow++");
bus_dmamap_unload(isp->isp_dmatag, dmap);
XS_SETERR(xs, HBA_BOTCH);
return (CMD_EAGAIN);
}
rq->req_header.rqs_entry_count++;
bzero((void *)crq, sizeof (*crq));
crq->req_header.rqs_entry_count = 1;
crq->req_header.rqs_entry_type = RQSTYPE_DATASEG;
for (ovseg = 0; seg < segcnt && ovseg < ISP_CDSEG;
rq->req_seg_count++, seg++, ovseg++) {
crq->req_dataseg[ovseg].ds_count =
dmap->dm_segs[seg].ds_len;
crq->req_dataseg[ovseg].ds_base =
dmap->dm_segs[seg].ds_addr;
isp_prt(isp, ISP_LOGDEBUG2, "seg%d.[%d]={0x%lx,%lu}",
rq->req_header.rqs_entry_count - 1,
rq->req_seg_count, (long)dmap->dm_segs[seg].ds_addr,
(unsigned long) dmap->dm_segs[seg].ds_len);
}
isp_put_cont_req(isp, crq, cqe);
MEMORYBARRIER(isp, SYNC_REQUEST, onxti, QENTRY_LEN);
} while (seg < segcnt);
dmasync:
bus_dmamap_sync(isp->isp_dmatag, dmap, 0, dmap->dm_mapsize,
(xs->flags & SCSI_DATA_IN) ? BUS_DMASYNC_PREREAD :
BUS_DMASYNC_PREWRITE);
mbxsync:
switch (rq->req_header.rqs_entry_type) {
case RQSTYPE_REQUEST:
isp_put_request(isp, rq, qep);
break;
case RQSTYPE_CMDONLY:
isp_put_extended_request(isp, (ispextreq_t *)rq,
(ispextreq_t *)qep);
break;
case RQSTYPE_T2RQS:
isp_put_request_t2(isp, (ispreqt2_t *) rq, (ispreqt2_t *) qep);
break;
}
*nxtip = nxti;
return (CMD_QUEUED);
}
static int
isp_pci_intr(void *arg)
{
u_int16_t isr, sema, mbox;
struct ispsoftc *isp = (struct ispsoftc *)arg;
isp->isp_intcnt++;
if (ISP_READ_ISR(isp, &isr, &sema, &mbox) == 0) {
isp->isp_intbogus++;
return (0);
} else {
isp->isp_osinfo.onintstack = 1;
isp_intr(isp, isr, sema, mbox);
isp->isp_osinfo.onintstack = 0;
return (1);
}
}
static void
isp_pci_dmateardown(struct ispsoftc *isp, XS_T *xs, u_int16_t handle)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *)isp;
bus_dmamap_t dmap = pcs->pci_xfer_dmap[isp_handle_index(handle)];
bus_dmamap_sync(isp->isp_dmatag, dmap, 0, dmap->dm_mapsize,
(xs->flags & SCSI_DATA_IN)?
BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
bus_dmamap_unload(isp->isp_dmatag, dmap);
}
static void
isp_pci_reset1(struct ispsoftc *isp)
{
/* Make sure the BIOS is disabled */
isp_pci_wr_reg(isp, HCCR, PCI_HCCR_CMD_BIOS);
if (isp->isp_osinfo.no_mbox_ints == 0) {
ENABLE_INTS(isp);
}
}
static void
isp_pci_dumpregs(struct ispsoftc *isp, const char *msg)
{
struct isp_pcisoftc *pcs = (struct isp_pcisoftc *)isp;
if (msg)
isp_prt(isp, ISP_LOGERR, "%s", msg);
isp_prt(isp, ISP_LOGERR, "PCI Status Command/Status=%x\n",
pci_conf_read(pcs->pci_pc, pcs->pci_tag, PCI_COMMAND_STATUS_REG));
}
|
zywaited/leetcode
|
Interview/1_1_9/8/one/set_zeroes.go
|
package one
// 题目没有明确说数值的范围
// 不然就可以标记删除
func SetZeroes(matrix [][]int) {
row := make(map[int]byte)
col := make(map[int]byte)
for i := range matrix {
for j := range matrix[i] {
if matrix[i][j] == 0 {
row[i] = 1
col[j] = 1
}
}
}
for i := range row {
for j := range matrix[i] {
matrix[i][j] = 0
}
}
for j := range col {
for i := len(matrix) - 1; i >= 0; i-- {
matrix[i][j] = 0
}
}
}
|
canhnt/hippo-repo-xacml
|
hippo-repository-3.1.x-xacml/modules/src/main/java/org/hippoecm/repository/jackrabbit/facetnavigation/FacNavNodeType.java
|
/*
* Copyright 2010-2013 <NAME>.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.repository.jackrabbit.facetnavigation;
public interface FacNavNodeType {
/**
*
*/
public static final String NT_ABSTRACTFACETNAVIGATION = "hippofacnav:abstractfacetnavigation";
/**
*
*/
public static final String NT_FACETNAVIGATION = "hippofacnav:facetnavigation";
/**
*
*/
public static final String NT_FACETSAVAILABLENAVIGATION = "hippofacnav:facetsavailablenavigation";
/**
*
*/
public static final String NT_FACETSUBNAVIGATION = "hippofacnav:facetsubnavigation";
/**
*
*/
public static final String HIPPOFACNAV_FACETS = "hippofacnav:facets";
/**
*
*/
public static final String HIPPOFACNAV_FACETNODENAMES = "hippofacnav:facetnodenames";
/**
*
*/
public static final String HIPPOFACNAV_FACETLIMIT = "hippofacnav:limit";
/**
*
*/
public static final String HIPPOFACNAV_LEAF = "hippofacnav:leaf";
/**
*
*/
public static final String HIPPOFACNAV_FACETSORTBY = "hippofacnav:sortby";
/**
*
*/
public static final String HIPPOFACNAV_FACETSORTORDER = "hippofacnav:sortorder";
/**
*
*/
public static final String HIPPOFACNAV_FILTERS = "hippofacnav:filters";
/**
*
*/
public static final String HIPPOFACNAV_SKIP_RESULTSET_FOR_FACET_NAVIGATION_ROOT = "hippofacnav:skipresultsetfacetnavigationroot";
/**
*
*/
public static final String HIPPOFACNAV_SKIP_RESULTSET_FOR_FACETS_AVAILABLE = "hippofacnav:skipresultsetfacetsavailable";
}
|
temanbrcom/che-che4z-lsp-for-cobol
|
server/src/main/java/com/broadcom/lsp/cobol/core/preprocessor/delegates/writer/CobolLineWriter.java
|
<filename>server/src/main/java/com/broadcom/lsp/cobol/core/preprocessor/delegates/writer/CobolLineWriter.java<gh_stars>0
/*
* Copyright (c) 2020 Broadcom.
* The term "Broadcom" refers to Broadcom Inc. and/or its subsidiaries.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Broadcom, Inc. - initial API and implementation
*
*/
package com.broadcom.lsp.cobol.core.preprocessor.delegates.writer;
import com.broadcom.lsp.cobol.core.model.CobolLine;
import java.util.List;
/**
* This interface describes a class that should convert a list of COBOL lines to a String for the
* further processing
*/
public interface CobolLineWriter {
/**
* Convert a list of COBOL lines into one string
*
* @param lines - list of lines
* @return a string representation of the COBOL program
*/
String serialize(List<CobolLine> lines);
}
|
khurtado/WMCore
|
src/python/WMCore/WMBS/MySQL/Jobs/GetAllJobs.py
|
#!/usr/bin/env python
"""
_GetLocation_
MySQL implementation of Jobs.GetAllJobs
"""
from WMCore.Database.DBFormatter import DBFormatter
from future.utils import listvalues
class GetAllJobs(DBFormatter):
"""
_GetLocation_
Retrieve all files that are associated with the given job from the
database.
"""
sql_all = "SELECT id FROM wmbs_job"
sql_state = "SELECT id FROM wmbs_job WHERE state = (SELECT id FROM wmbs_job_state WHERE name = :state)"
sql_state_type = """SELECT wmbs_job.id FROM wmbs_job
INNER JOIN wmbs_jobgroup ON wmbs_job.jobgroup = wmbs_jobgroup.id
INNER JOIN wmbs_subscription ON wmbs_jobgroup.subscription = wmbs_subscription.id
INNER JOIN wmbs_job_state ON wmbs_job.state = wmbs_job_state.id
INNER JOIN wmbs_sub_types ON wmbs_subscription.subtype = wmbs_sub_types.id
WHERE wmbs_job_state.name = :state
AND wmbs_sub_types.name = :type"""
limit_sql = " limit %d"
def format(self, results):
"""
_formatDict_
Cast the file attribute to an integer, and also handle changing the
column name in Oracle from FILEID to FILE.
"""
if len(results) == 0:
return False
else:
tempList = results[0].fetchall()
final = []
for i in tempList:
final.append(listvalues(i)[0])
return final
def execute(self, state=None, jobType=None, conn=None,
transaction=False, limitRows=None):
"""
_execute_
Execute the SQL for the given job ID and then format and return
the result.
"""
if limitRows:
extraSql = self.limit_sql % limitRows
else:
extraSql = ""
if state is None:
result = self.dbi.processData(self.sql_all + extraSql, {}, conn=conn,
transaction=transaction)
else:
if jobType:
result = self.dbi.processData(self.sql_state_type + extraSql, {'state': state.lower(), 'type': jobType},
conn=conn, transaction=transaction)
else:
result = self.dbi.processData(self.sql_state + extraSql, {'state': state.lower()},
conn=conn, transaction=transaction)
res = self.format(result)
return res
|
HopeBayMobile/hcfs
|
build/third_party/libzip/lib/zip_utf-8.c
|
<reponame>HopeBayMobile/hcfs<gh_stars>0
/*
* Copyright (c) 2021 HopeBayTech.
*
* This file is part of Tera.
* See https://github.com/HopeBayMobile for further info.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "zipint.h"
#include <stdlib.h>
static const zip_uint16_t _cp437_to_unicode[256] = {
/* 0x00 - 0x0F */
0x2007, 0x263A, 0x263B, 0x2665, 0x2666, 0x2663, 0x2660, 0x2022,
0x25D8, 0x25CB, 0x25D9, 0x2642, 0x2640, 0x266A, 0x266B, 0x263C,
/* 0x10 - 0x1F */
0x25BA, 0x25C4, 0x2195, 0x203C, 0x00B6, 0x00A7, 0x25AC, 0x21A8,
0x2191, 0x2193, 0x2192, 0x2190, 0x221F, 0x2194, 0x25B2, 0x25BC,
/* 0x20 - 0x2F */
0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027,
0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F,
/* 0x30 - 0x3F */
0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037,
0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F,
/* 0x40 - 0x4F */
0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047,
0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F,
/* 0x50 - 0x5F */
0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057,
0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F,
/* 0x60 - 0x6F */
0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067,
0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F,
/* 0x70 - 0x7F */
0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077,
0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x2302,
/* 0x80 - 0x8F */
0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,
0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,
/* 0x90 - 0x9F */
0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,
0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192,
/* 0xA0 - 0xAF */
0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,
0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,
/* 0xB0 - 0xBF */
0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,
0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,
/* 0xC0 - 0xCF */
0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,
/* 0xD0 - 0xDF */
0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,
0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,
/* 0xE0 - 0xEF */
0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4,
0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229,
/* 0xF0 - 0xFF */
0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248,
0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0
};
#define UTF_8_LEN_2_MASK 0xe0
#define UTF_8_LEN_2_MATCH 0xc0
#define UTF_8_LEN_3_MASK 0xf0
#define UTF_8_LEN_3_MATCH 0xe0
#define UTF_8_LEN_4_MASK 0xf8
#define UTF_8_LEN_4_MATCH 0xf0
#define UTF_8_CONTINUE_MASK 0xc0
#define UTF_8_CONTINUE_MATCH 0x80
zip_encoding_type_t
_zip_guess_encoding(zip_string_t *str, zip_encoding_type_t expected_encoding)
{
zip_encoding_type_t enc;
const zip_uint8_t *name;
zip_uint32_t i, j, ulen;
if (str == NULL)
return ZIP_ENCODING_ASCII;
name = str->raw;
if (str->encoding != ZIP_ENCODING_UNKNOWN)
enc = str->encoding;
else {
enc = ZIP_ENCODING_ASCII;
for (i=0; i<str->length; i++) {
if ((name[i] > 31 && name[i] < 128) || name[i] == '\r' || name[i] == '\n' || name[i] == '\t')
continue;
enc = ZIP_ENCODING_UTF8_GUESSED;
if ((name[i] & UTF_8_LEN_2_MASK) == UTF_8_LEN_2_MATCH)
ulen = 1;
else if ((name[i] & UTF_8_LEN_3_MASK) == UTF_8_LEN_3_MATCH)
ulen = 2;
else if ((name[i] & UTF_8_LEN_4_MASK) == UTF_8_LEN_4_MATCH)
ulen = 3;
else {
enc = ZIP_ENCODING_CP437;
break;
}
if (i + ulen >= str->length) {
enc = ZIP_ENCODING_CP437;
break;
}
for (j=1; j<=ulen; j++) {
if ((name[i+j] & UTF_8_CONTINUE_MASK) != UTF_8_CONTINUE_MATCH) {
enc = ZIP_ENCODING_CP437;
goto done;
}
}
i += ulen;
}
}
done:
str->encoding = enc;
if (expected_encoding != ZIP_ENCODING_UNKNOWN) {
if (expected_encoding == ZIP_ENCODING_UTF8_KNOWN && enc == ZIP_ENCODING_UTF8_GUESSED)
str->encoding = enc = ZIP_ENCODING_UTF8_KNOWN;
if (expected_encoding != enc && enc != ZIP_ENCODING_ASCII)
return ZIP_ENCODING_ERROR;
}
return enc;
}
static zip_uint32_t
_zip_unicode_to_utf8_len(zip_uint32_t codepoint)
{
if (codepoint < 0x0080)
return 1;
if (codepoint < 0x0800)
return 2;
if (codepoint < 0x10000)
return 3;
return 4;
}
static zip_uint32_t
_zip_unicode_to_utf8(zip_uint32_t codepoint, zip_uint8_t *buf)
{
if (codepoint < 0x0080) {
buf[0] = codepoint & 0xff;
return 1;
}
if (codepoint < 0x0800) {
buf[0] = (zip_uint8_t)(UTF_8_LEN_2_MATCH | ((codepoint >> 6) & 0x1f));
buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f));
return 2;
}
if (codepoint < 0x10000) {
buf[0] = (zip_uint8_t)(UTF_8_LEN_3_MATCH | ((codepoint >> 12) & 0x0f));
buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 6) & 0x3f));
buf[2] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f));
return 3;
}
buf[0] = (zip_uint8_t)(UTF_8_LEN_4_MATCH | ((codepoint >> 18) & 0x07));
buf[1] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 12) & 0x3f));
buf[2] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | ((codepoint >> 6) & 0x3f));
buf[3] = (zip_uint8_t)(UTF_8_CONTINUE_MATCH | (codepoint & 0x3f));
return 4;
}
zip_uint8_t *
_zip_cp437_to_utf8(const zip_uint8_t * const _cp437buf, zip_uint32_t len,
zip_uint32_t *utf8_lenp, zip_error_t *error)
{
zip_uint8_t *cp437buf = (zip_uint8_t *)_cp437buf;
zip_uint8_t *utf8buf;
zip_uint32_t buflen, i, offset;
if (len == 0) {
if (utf8_lenp)
*utf8_lenp = 0;
return NULL;
}
buflen = 1;
for (i=0; i<len; i++)
buflen += _zip_unicode_to_utf8_len(_cp437_to_unicode[cp437buf[i]]);
if ((utf8buf=(zip_uint8_t*)malloc(buflen)) == NULL) {
zip_error_set(error, ZIP_ER_MEMORY, 0);
return NULL;
}
offset = 0;
for (i=0; i<len; i++)
offset += _zip_unicode_to_utf8(_cp437_to_unicode[cp437buf[i]],
utf8buf+offset);
utf8buf[buflen-1] = 0;
if (utf8_lenp)
*utf8_lenp = buflen-1;
return utf8buf;
}
|
beads123/ikacn
|
public/static/js/twgoods_twgoods.js
|
<reponame>beads123/ikacn
app.controller("ctrlArea", function ($scope, $http ,approve,complete_info) {
$scope.approve = approve
$scope.complete_info = complete_info
$scope.sell_graphic = sell_graphic;
$scope.seeAd = [];
$scope.o_status = o_status;
$scope.data = {};
$scope.data.px = 1 //页数
$scope.data.pz = 10 // 每页条数
$scope.scrollDisabled = false;
$scope.s_type = ["所有", "上架", "下架"];
$scope.types = ["全部", "图片广告", "文字广告"];
//时间实例化
$scope.formatDate = function (time) {
if (!time) return;
return new Date(time * 1000).format('yyyy-MM-dd hh:mm')
}
$scope.data_type = '所有';
$scope.changeTypes = function (k) {
$scope.data_type = k;
$scope.submitData();
}
$scope.type = '全部';
$scope.changetw = function (k) {
$scope.type = k;
$scope.submitData();
}
$scope.submitData = function (t) {
if (!t) $scope.data.px = 1;
if ($scope.data_type == '所有') {
$scope.data.status = '';
} else {
$scope.data.status = $scope.data_type;
}
if ($scope.type == '全部') {
$scope.data.type = '';
} else {
$scope.data.type = $scope.type;
}
$scope.data.stime = $scope.stime;
$scope.data.etime = $scope.etime;
$http.post('/member/goods/twgoods', $scope.data).success(function (data) {
if (data.statusCode == 200) {
if ($scope.data.px == 1) { //如果是第一页,那么把变量重新赋值
$scope.sell_graphic = data.data;
} else {//否则把返回的结果累加进变量里面
if (data.data.length > 0) {
for (var g in data.data) {
$scope.sell_graphic.push(data.data[g]);
}
}
}
if ($scope.data.px >= data.page.num_page) { //如果当前页面大于等于总页面,那么不可以禁用滚动
$scope.scrollDisabled = true;
return false;
}
} else {
modal_alert(data.message)
}
$scope.scrollDisabled = false;
});
}
$scope.loadMore = function () {
if ($scope.scrollDisabled) return false;
$scope.scrollDisabled = true;
$scope.data.px += 1;
$scope.submitData(true);
}
// 商品上架
$scope.upGoods = function (item) {
$http.post("/member/goods/upDownState", { gid: item.gid, state: "上架" }).success(function (data) {
$scope.adv_type = item.type
if (data.statusCode == 200) {
item.sellstatus = "上架"
modal_alert(data.message)
}else if(data.statusCode == 508){
$(".modal-auth").modal("show")
$scope.web_wid = item.wid
$scope.wurl = item.weburl
}else{
modal_alert(data.message)
}
})
}
$scope.go_auth = function(){
$(".checkwebsite").modal("show")
$scope.approve.web_url = $scope.wurl
$scope.approve.webWid = $scope.web_wid
$scope.approve.getApproveInfo()
}
$scope.dowmGoods_text = "";
// 商品下架
$scope.downGoods = function (item) {
$scope.dowmGoods_text = item.carding == 1 ? "该商品设置了商品推荐,如果下架将取消推荐,确认下架?" : "确认下架该广告?"
modal_confirm($scope.dowmGoods_text,function(){
$http.post("/member/goods/upDownState", { gid: item.gid, state: "下架" }).success(function (data) {
modal_alert(data.message)
if (data.statusCode == 200) {
item.sellstatus = "下架"
}
})
})
}
// 出售广告
$scope.sellAd = function () {
$scope.complete_info.check_user(memberUrl('/twgoods/twSell')) //检测用户信息是否完善
}
var int
// 检查手机号
$scope.btnDisabled = true
$scope.checkPhone = function () {
if (!$scope.phone) {
$scope.tipMsg = ""
}
$http.post("/member/goods/checkPhone", { phone: $scope.phone }).success(function (data) {
if (data.statusCode == 200) {
$scope.btnDisabled = false
$scope.tipMsg = ''
} else {
$scope.btnDisabled = true
$scope.tipMsg = data.message
}
})
}
// 发送验证码
$scope.authCode = function () {
$scope.timeNum = 59
if ((preg.mobile.test($scope.phone)) || $scope.userInfo.phone != "") {
if ($scope.userInfo.phone == "") {
$http.post("/member/Sms/add", { mobile: $scope.phone, type: 1 }).success(function (data) {
if (data.statusCode == 200) {
$("#timeCount").removeClass("hidden")
$("#getCode").addClass("hidden")
// 验证码倒计时
int = setInterval(function () {
$scope.timeNum--
$("#d-sec").text($scope.timeNum)
if ($scope.timeNum <= 0) {
$("#getCode").removeClass("hidden")
$("#timeCount").addClass("hidden")
$scope.msg = ""
$("#d-sec").text('')
clearInterval(int)
}
}, 1000)
} else {
$scope.msg = data.message
setTimeout(function () {
$scope.msg = ''
}, 2000);
}
})
} else {
$http.post("/member/Sms/add", { mobile: $scope.userInfo.phone, type: 1 }).success(function (data) {
if (data.statusCode == 200) {
$("#timeCount").removeClass("hidden")
$("#getCode").addClass("hidden")
// 验证码倒计时
int = setInterval(function () {
$scope.timeNum--
$("#d-sec").text($scope.timeNum)
if ($scope.timeNum <= 0) {
$("#getCode").removeClass("hidden")
$("#timeCount").addClass("hidden")
$scope.msg = ""
$("#d-sec").text('')
clearInterval(int)
}
}, 1000)
} else {
$scope.msg = data.message
setTimeout(function () {
$scope.msg = ''
}, 2000);
}
})
}
} else {
$scope.btnDisabled = true
}
}
// 保存个人资料
$scope.siveEdit = function () {
if ($scope.userInfo.phone == "" && $scope.userInfo.qq == "" && $scope.userInfo.email == "") {
$http.post('/member/goods/savedata', { phone: $scope.phone, qq: $scope.qq, email: $scope.email, verify: $scope.verify }).success(function (data) {
if (data.statusCode == 200) {
location.href = memberUrl("/twgoods/twsell")
} else {
modal_alert(data.message)
}
})
} else if ($scope.userInfo.phone != "" && $scope.userInfo.qq == "" && $scope.userInfo.email == "") {
$http.post('/member/goods/savedata', { qq: $scope.qq, email: $scope.email, verify: $scope.verify }).success(function (data) {
if (data.statusCode == 200) {
location.href = memberUrl("/twgoods/twsell")
} else {
modal_alert(data.message)
}
})
} else if ($scope.userInfo.phone == "" && $scope.userInfo.qq != "" && $scope.userInfo.email == "") {
$http.post('/member/goods/savedata', { phone: $scope.phone, email: $scope.email, verify: $scope.verify }).success(function (data) {
if (data.statusCode == 200) {
location.href = memberUrl("/twgoods/twsell")
} else {
modal_alert(data.message)
}
})
} else if ($scope.userInfo.phone == "" && $scope.userInfo.qq == "" && $scope.userInfo.email != "") {
$http.post('/member/goods/savedata', { phone: $scope.phone, qq: $scope.qq, verify: $scope.verify }).success(function (data) {
if (data.statusCode == 200) {
location.href = memberUrl("/twgoods/twsell")
} else {
modal_alert(data.message)
}
})
} else if ($scope.userInfo.phone != "" && $scope.userInfo.qq == "" && $scope.userInfo.email != "") {
$http.post('/member/goods/savedata', { qq: $scope.qq, verify: $scope.verify }).success(function (data) {
if (data.statusCode == 200) {
location.href = memberUrl("/twgoods/twsell")
} else {
modal_alert(data.message)
}
})
} else if ($scope.userInfo.phone == "" && $scope.userInfo.qq != "" && $scope.userInfo.email != "") {
$http.post('/member/goods/savedata', { phone: $scope.phone, verify: $scope.verify }).success(function (data) {
if (data.statusCode == 200) {
location.href = memberUrl("/twgoods/twsell")
} else {
modal_alert(data.message)
}
})
}
}
$scope.delete = function(gid,index){
$scope.delete_gid = gid
$scope.delete_index = index
$('.del_mfgoods').modal('show')
}
$scope.sure_delete = function(){
$http.post('/member/goods/goodsdel',{gid:$scope.delete_gid}).success(function(data){
if(data.statusCode == 200){
$scope.sell_graphic.splice($scope.delete_index,1)
}else{
modal_alert(data.message)
}
})
}
})
|
mstate/volt
|
lib/volt/page/bindings/base_binding.rb
|
# The BaseBinding class is the base for all bindings. It takes
# 4 arguments that should be passed up from the children (via super)
#
# 1. page - this class instance should provide:
# - a #templates methods that returns a hash for templates
# - an #events methods that returns an instance of DocumentEvents
# 2. target - an DomTarget or AttributeTarget
# 3. context - the context object the binding will be evaluated in
# 4. binding_name - the id for the comment (or id for attributes) where the
# binding will be inserted.
module Volt
class BaseBinding
attr_accessor :target, :context, :binding_name, :volt_app
def initialize(volt_app, target, context, binding_name)
@volt_app = volt_app
@target = target
@context = context
@binding_name = binding_name
@@binding_number ||= 10_000
end
def browser
@volt_app.browser
end
def dom_section
@dom_section ||= target.dom_section(@binding_name)
end
def remove
@dom_section.remove if @dom_section
# Clear any references
@target = nil
@context = nil
@dom_section = nil
end
def remove_anchors
@dom_section.remove_anchors if @dom_section
end
# log out a message about a failed computation or Promise.
def getter_fail(error)
message = "#{self.class.to_s} Error: #{error.inspect}"
if RUBY_PLATFORM == 'opal'
if `#{@getter}`
message += "\n" + `#{@getter}.toString()`
end
else
if error.respond_to?(:backtrace)
message += "\n" + error.backtrace.join("\n")
end
end
Volt.logger.error(message)
end
end
end
|
vovanmozg/rocketjob
|
lib/rocket_job/plugins/job/state_machine.rb
|
<filename>lib/rocket_job/plugins/job/state_machine.rb
require 'active_support/concern'
module RocketJob
module Plugins
module Job
# State machine for RocketJob::Job
module StateMachine
extend ActiveSupport::Concern
included do
# State Machine events and transitions
#
# :queued -> :running -> :completed
# -> :paused -> :running (if started )
# -> :queued ( if no started )
# -> :aborted
# -> :failed -> :aborted
# -> :queued
# -> :aborted
# -> :queued (when a worker dies)
# -> :aborted
aasm column: :state, whiny_persistence: true do
# Job has been created and is queued for processing ( Initial state )
state :queued, initial: true
# Job is running
state :running
# Job has completed processing ( End state )
state :completed
# Job is temporarily paused and no further processing will be completed
# until this job has been resumed
state :paused
# Job failed to process and needs to be manually re-tried or aborted
state :failed
# Job was aborted and cannot be resumed ( End state )
state :aborted
event :start do
transitions from: :queued, to: :running
end
event :complete do
transitions from: :running, to: :completed
end
event :fail do
transitions from: :queued, to: :failed
transitions from: :running, to: :failed
transitions from: :paused, to: :failed
end
event :retry do
transitions from: :failed, to: :queued
end
event :pause do
transitions from: :running, to: :paused, if: :pausable?
# All jobs are pausable prior to starting the job.
transitions from: :queued, to: :paused
end
event :resume do
transitions from: :paused, to: :running, if: -> { pausable? && started_at }
# All jobs paused before processing started are pausable.
transitions from: :paused, to: :queued, unless: -> { started_at }
end
event :abort do
transitions from: :running, to: :aborted
transitions from: :queued, to: :aborted
transitions from: :failed, to: :aborted
transitions from: :paused, to: :aborted
end
event :requeue do
transitions from: :running, to: :queued,
if: ->(server_name) { worker_on_server?(server_name) },
after: :rocket_job_clear_started_at
end
end
# @formatter:on
# By default all jobs are not pausable / resumable
class_attribute(:pausable)
self.pausable = false
# Define a before and after callback method for each event
state_machine_define_event_callbacks(*aasm.state_machine.events.keys)
before_start :rocket_job_set_started_at
before_complete :rocket_job_set_completed_at, :rocket_job_mark_complete
before_fail :rocket_job_set_completed_at, :rocket_job_increment_failure_count, :rocket_job_set_exception
before_pause :rocket_job_set_completed_at
before_abort :rocket_job_set_completed_at
before_retry :rocket_job_clear_exception
before_resume :rocket_job_clear_completed_at
after_complete :rocket_job_destroy_on_complete
# Pause all running jobs
def self.pause_all
running.each(&:pause!)
end
# Resume all paused jobs
def self.resume_all
paused.each(&:resume!)
end
end
private
# Sets the exception child object for this job based on the
# supplied Exception instance or message
def rocket_job_set_exception(worker_name = nil, exc_or_message = nil)
if exc_or_message.is_a?(Exception)
self.exception = JobException.from_exception(exc_or_message)
exception.worker_name = worker_name
else
build_exception(
class_name: 'RocketJob::JobException',
message: exc_or_message,
backtrace: [],
worker_name: worker_name
)
end
end
def rocket_job_set_started_at
self.started_at = Time.now
end
def rocket_job_mark_complete
self.percent_complete = 100
end
def rocket_job_increment_failure_count
self.failure_count += 1
end
def rocket_job_clear_exception
self.completed_at = nil
self.exception = nil
self.worker_name = nil
end
def rocket_job_set_completed_at
self.completed_at = Time.now
self.worker_name = nil
end
def rocket_job_clear_completed_at
self.completed_at = nil
end
def rocket_job_clear_started_at
self.started_at = nil
self.worker_name = nil
end
def rocket_job_destroy_on_complete
destroy if destroy_on_complete && !new_record?
end
end
end
end
end
|
brondani/QCA400x_Host_Driver_SDK
|
port/QCA400x.h
|
<filename>port/QCA400x.h
#ifndef __QCA400X_H__
#define __QCA400X_H__
#include "stdint.h"
#include "a_osapi.h"
#include "QCA400x_Config.h"
// Joined multicast groups
typedef struct _mcb_struct {
uint8_t GROUP[6];
uint8_t reserved[2];
uint32_t HASH;
struct _mcb_struct *NEXT;
} MCB_STRUCT, *MCB_STRUCT_PTR;
#if WIFI_QCA400x_MODE_PASSTHROUGH
// Frame received callback
typedef void (*FrameReceived)(A_NETBUF *a_netbuf_ptr);
#endif
// QCA400x WiFi
typedef struct _QCA400x_WiFi {
A_CUSTOM_DRIVER_CONTEXT *MAC_CONTEXT_PTR;
uint8_t ADDRESS[6];
uint8_t reserved[2];
#if WIFI_QCA400x_MODE_PASSTHROUGH
FrameReceived FrameReceived_cb;
#endif
} QCA400x_WiFi, *QCA400x_WiFi_PTR;
typedef struct {
int32_t (*INIT) (QCA400x_WiFi *);
int32_t (*STOP) (QCA400x_WiFi *);
int32_t (*SEND) (QCA400x_WiFi *, void *, uint32_t, uint32_t, uint32_t);
int32_t (*PHY_READ) (QCA400x_WiFi *, uint32_t, uint32_t *, uint32_t);
int32_t (*PHY_WRITE)(QCA400x_WiFi *, uint32_t, uint32_t, uint32_t);
int32_t (*JOIN) (QCA400x_WiFi *, MCB_STRUCT *);
int32_t (*REJOIN) (QCA400x_WiFi *);
int32_t (*MEDIACTL) (uint8_t, uint32_t, void *);
} MAC_IF, *MAC_IF_PTR;
#endif
|
juagarfer4/Condominium-Manager
|
src/test/java/services/RenterServicePositiveTest.java
|
<reponame>juagarfer4/Condominium-Manager<filename>src/test/java/services/RenterServicePositiveTest.java
package services;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.*;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;
import com.mchange.util.AssertException;
import domain.Administrator;
import domain.Renter;
import repositories.AdministratorRepository;
import security.LoginService;
import security.UserAccount;
import utilities.AbstractTest;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/datasource.xml",
"classpath:spring/config/packages.xml" })
@Transactional
@TransactionConfiguration(defaultRollback = false)
public class RenterServicePositiveTest extends AbstractTest {
// Service under test ------------------------------------------------
@Autowired
private RenterService renterService;
// Tests --------------------------------------------------------------
// List of renters of a property. ------------
@Test
public void listRentersPositiveTest() {
this.authenticate("manager1");
Collection<Renter> renters;
Integer size;
renters = renterService.findAllRentersByProperty(62);
size = renters.size();
Assert.isTrue(size == 2);
this.unauthenticate();
}
// Create a renter. ------------
@Test
public void createRenterPositiveTest() {
this.authenticate("manager1");
Renter renter;
String name;
String surname;
String email;
Date arrivalDate;
renter = renterService.create(53);
name="NAME";
surname="SURNAME";
email="<EMAIL>";
arrivalDate=new Date(2015 - 1900, 8 - 1, 8);
renter.setName(name);
renter.setSurname(surname);
renter.setEmail(email);
renter.setArrivalDate(arrivalDate);
renterService.save(renter);
}
// Set the departure date of a renter. ---------------
@Test
public void editRenterPositiveTest() {
this.authenticate("manager1");
Renter renter;
Date departureDate;
renter = renterService.findOne(63);
departureDate=new Date(2016 - 1900, 8 - 1, 8);
renter.setDepartureDate(departureDate);
renterService.save(renter);
}
}
|
wilebeast/FireFox-OS
|
B2G/gecko/layout/svg/nsSVGGlyphFrame.h
|
<filename>B2G/gecko/layout/svg/nsSVGGlyphFrame.h<gh_stars>1-10
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef __NS_SVGGLYPHFRAME_H__
#define __NS_SVGGLYPHFRAME_H__
#include "mozilla/Attributes.h"
#include "gfxFont.h"
#include "nsISVGGlyphFragmentNode.h"
#include "nsISVGChildFrame.h"
#include "nsSVGGeometryFrame.h"
#include "nsSVGUtils.h"
#include "nsTextFragment.h"
#include "gfxSVGGlyphs.h"
class CharacterIterator;
class gfxContext;
class nsDisplaySVGGlyphs;
class nsIDOMSVGRect;
class nsRenderingContext;
class nsSVGGlyphFrame;
class nsSVGTextFrame;
class nsSVGTextPathFrame;
class gfxTextObjectPaint;
struct CharacterPosition;
typedef gfxFont::DrawMode DrawMode;
typedef nsSVGGeometryFrame nsSVGGlyphFrameBase;
class nsSVGGlyphFrame : public nsSVGGlyphFrameBase,
public nsISVGGlyphFragmentNode,
public nsISVGChildFrame
{
class AutoCanvasTMForMarker;
friend class AutoCanvasTMForMarker;
friend class CharacterIterator;
friend nsIFrame*
NS_NewSVGGlyphFrame(nsIPresShell* aPresShell, nsStyleContext* aContext);
protected:
nsSVGGlyphFrame(nsStyleContext* aContext)
: nsSVGGlyphFrameBase(aContext),
mTextRun(nullptr),
mStartIndex(0),
mGetCanvasTMForFlag(nsISVGChildFrame::FOR_OUTERSVG_TM),
mCompressWhitespace(true),
mTrimLeadingWhitespace(false),
mTrimTrailingWhitespace(false)
{}
~nsSVGGlyphFrame()
{
ClearTextRun();
}
public:
NS_DECL_QUERYFRAME
NS_DECL_FRAMEARENA_HELPERS
// These do not use the global transform if NS_STATE_NONDISPLAY_CHILD
nsresult GetStartPositionOfChar(uint32_t charnum, nsIDOMSVGPoint **_retval);
nsresult GetEndPositionOfChar(uint32_t charnum, nsIDOMSVGPoint **_retval);
nsresult GetExtentOfChar(uint32_t charnum, nsIDOMSVGRect **_retval);
nsresult GetRotationOfChar(uint32_t charnum, float *_retval);
/**
* @param aForceGlobalTransform controls whether to use the
* global transform even when NS_STATE_NONDISPLAY_CHILD
*/
float GetAdvance(bool aForceGlobalTransform);
void SetGlyphPosition(gfxPoint *aPosition, bool aForceGlobalTransform);
nsSVGTextPathFrame* FindTextPathParent();
bool IsStartOfChunk(); // == is new absolutely positioned chunk.
void GetXY(mozilla::SVGUserUnitList *aX, mozilla::SVGUserUnitList *aY);
void SetStartIndex(uint32_t aStartIndex);
/*
* Returns inherited x and y values instead of parent element's attribute
* values.
*/
void GetEffectiveXY(int32_t strLength,
nsTArray<float> &aX, nsTArray<float> &aY);
/*
* Returns inherited dx and dy values instead of parent element's attribute
* values.
*/
void GetEffectiveDxDy(int32_t strLength,
nsTArray<float> &aDx,
nsTArray<float> &aDy);
/*
* Returns inherited rotate values instead of parent element's attribute
* values.
*/
void GetEffectiveRotate(int32_t strLength,
nsTArray<float> &aRotate);
uint16_t GetTextAnchor();
bool IsAbsolutelyPositioned();
bool IsTextEmpty() const {
return mContent->GetText()->GetLength() == 0;
}
void SetTrimLeadingWhitespace(bool aTrimLeadingWhitespace) {
if (mTrimLeadingWhitespace != aTrimLeadingWhitespace) {
mTrimLeadingWhitespace = aTrimLeadingWhitespace;
ClearTextRun();
}
}
void SetTrimTrailingWhitespace(bool aTrimTrailingWhitespace) {
if (mTrimTrailingWhitespace != aTrimTrailingWhitespace) {
mTrimTrailingWhitespace = aTrimTrailingWhitespace;
ClearTextRun();
}
}
bool EndsWithWhitespace() const;
bool IsAllWhitespace() const;
// nsIFrame interface:
NS_IMETHOD CharacterDataChanged(CharacterDataChangeInfo* aInfo);
virtual void DidSetStyleContext(nsStyleContext* aOldStyleContext);
NS_IMETHOD IsSelectable(bool* aIsSelectable, uint8_t* aSelectStyle) const;
NS_IMETHOD Init(nsIContent* aContent,
nsIFrame* aParent,
nsIFrame* aPrevInFlow);
/**
* Get the "type" of the frame
*
* @see nsGkAtoms::svgGlyphFrame
*/
virtual nsIAtom* GetType() const;
virtual bool IsFrameOfType(uint32_t aFlags) const
{
// Set the frame state bit for text frames to mark them as replaced.
// XXX kipp: temporary
return nsSVGGlyphFrameBase::IsFrameOfType(aFlags & ~(nsIFrame::eReplaced));
}
#ifdef DEBUG
NS_IMETHOD GetFrameName(nsAString& aResult) const
{
return MakeFrameName(NS_LITERAL_STRING("SVGGlyph"), aResult);
}
#endif
NS_IMETHOD BuildDisplayList(nsDisplayListBuilder* aBuilder,
const nsRect& aDirtyRect,
const nsDisplayListSet& aLists);
// nsISVGChildFrame interface:
// These four always use the global transform, even if NS_STATE_NONDISPLAY_CHILD
NS_IMETHOD PaintSVG(nsRenderingContext *aContext,
const nsIntRect *aDirtyRect);
NS_IMETHOD_(nsIFrame*) GetFrameForPoint(const nsPoint &aPoint) MOZ_OVERRIDE;
virtual SVGBBox GetBBoxContribution(const gfxMatrix &aToBBoxUserspace,
uint32_t aFlags) MOZ_OVERRIDE;
NS_IMETHOD_(nsRect) GetCoveredRegion() MOZ_OVERRIDE;
virtual void ReflowSVG() MOZ_OVERRIDE;
virtual void NotifySVGChanged(uint32_t aFlags) MOZ_OVERRIDE;
NS_IMETHOD_(bool) IsDisplayContainer() MOZ_OVERRIDE { return false; }
// nsSVGGeometryFrame methods
gfxMatrix GetCanvasTM(uint32_t aFor);
// nsISVGGlyphFragmentNode interface:
// These do not use the global transform if NS_STATE_NONDISPLAY_CHILD
virtual uint32_t GetNumberOfChars();
virtual float GetComputedTextLength() MOZ_OVERRIDE;
virtual float GetSubStringLength(uint32_t charnum, uint32_t fragmentChars) MOZ_OVERRIDE;
virtual int32_t GetCharNumAtPosition(nsIDOMSVGPoint *point) MOZ_OVERRIDE;
NS_IMETHOD_(nsSVGGlyphFrame *) GetFirstGlyphFrame() MOZ_OVERRIDE;
NS_IMETHOD_(nsSVGGlyphFrame *) GetNextGlyphFrame() MOZ_OVERRIDE;
NS_IMETHOD_(void) SetWhitespaceCompression(bool aCompressWhitespace) MOZ_OVERRIDE {
if (mCompressWhitespace != aCompressWhitespace) {
mCompressWhitespace = aCompressWhitespace;
ClearTextRun();
}
}
private:
/**
* This class exists purely because it would be too messy to pass the "for"
* flag for GetCanvasTM through the call chains to the GetCanvasTM() call in
* EnsureTextRun.
*/
class AutoCanvasTMForMarker {
public:
AutoCanvasTMForMarker(nsSVGGlyphFrame *aFrame, uint32_t aFor)
: mFrame(aFrame)
{
mOldFor = mFrame->mGetCanvasTMForFlag;
mFrame->mGetCanvasTMForFlag = aFor;
}
~AutoCanvasTMForMarker()
{
// Default
mFrame->mGetCanvasTMForFlag = mOldFor;
}
private:
nsSVGGlyphFrame *mFrame;
uint32_t mOldFor;
};
// Use a power of 2 here. It's not so important to match
// nsDeviceContext::AppUnitsPerDevPixel, but since we do a lot of
// multiplying by 1/GetTextRunUnitsFactor, it's good for it to be a
// power of 2 to avoid accuracy loss.
static uint32_t GetTextRunUnitsFactor() { return 64; }
/**
* @aParam aDrawScale font drawing must be scaled into user units
* by this factor
* @param aMetricsScale font metrics must be scaled into user units
* by this factor
* @param aForceGlobalTransform set to true if we should force use of
* the global transform; otherwise we won't use the global transform
* if we're a NONDISPLAY_CHILD
*/
bool EnsureTextRun(float *aDrawScale, float *aMetricsScale,
bool aForceGlobalTransform);
void ClearTextRun();
bool GetCharacterData(nsAString & aCharacterData);
bool GetCharacterPositions(nsTArray<CharacterPosition>* aCharacterPositions,
float aMetricsScale);
uint32_t GetTextRunFlags(uint32_t strLength);
void AddCharactersToPath(CharacterIterator *aIter,
gfxContext *aContext);
void AddBoundingBoxesToPath(CharacterIterator *aIter,
gfxContext *aContext);
void DrawCharacters(CharacterIterator *aIter,
gfxContext *aContext,
DrawMode aDrawMode,
gfxTextObjectPaint *aObjectPaint = nullptr);
void NotifyGlyphMetricsChange();
void SetupGlobalTransform(gfxContext *aContext, uint32_t aFor);
nsresult GetHighlight(uint32_t *charnum, uint32_t *nchars,
nscolor *foreground, nscolor *background);
float GetSubStringAdvance(uint32_t charnum, uint32_t fragmentChars,
float aMetricsScale);
gfxFloat GetBaselineOffset(float aMetricsScale);
virtual void GetDxDy(SVGUserUnitList *aDx, SVGUserUnitList *aDy);
virtual const SVGNumberList *GetRotate();
// Used to support GetBBoxContribution by making GetConvasTM use this as the
// parent transform instead of the real CanvasTM.
nsAutoPtr<gfxMatrix> mOverrideCanvasTM;
// Owning pointer, must call gfxTextRunWordCache::RemoveTextRun before deleting
gfxTextRun *mTextRun;
gfxPoint mPosition;
// The start index into the position and rotation data
uint32_t mStartIndex;
uint32_t mGetCanvasTMForFlag;
bool mCompressWhitespace;
bool mTrimLeadingWhitespace;
bool mTrimTrailingWhitespace;
private:
DrawMode SetupCairoState(gfxContext *aContext,
gfxTextObjectPaint *aOuterObjectPaint,
gfxTextObjectPaint **aThisObjectPaint);
// Slightly horrible callback for deferring application of opacity
struct SVGTextObjectPaint : public gfxTextObjectPaint {
already_AddRefed<gfxPattern> GetFillPattern(float aOpacity,
const gfxMatrix& aCTM);
already_AddRefed<gfxPattern> GetStrokePattern(float aOpacity,
const gfxMatrix& aCTM);
void SetFillOpacity(float aOpacity) { mFillOpacity = aOpacity; }
float GetFillOpacity() { return mFillOpacity; }
void SetStrokeOpacity(float aOpacity) { mStrokeOpacity = aOpacity; }
float GetStrokeOpacity() { return mStrokeOpacity; }
struct Paint {
Paint() {
mPatternCache.Init();
}
void SetPaintServer(nsIFrame *aFrame, const gfxMatrix& aContextMatrix,
nsSVGPaintServerFrame *aPaintServerFrame) {
mPaintType = eStyleSVGPaintType_Server;
mPaintDefinition.mPaintServerFrame = aPaintServerFrame;
mFrame = aFrame;
mContextMatrix = aContextMatrix;
}
void SetColor(const nscolor &aColor) {
mPaintType = eStyleSVGPaintType_Color;
mPaintDefinition.mColor = aColor;
}
void SetObjectPaint(gfxTextObjectPaint *aObjectPaint,
nsStyleSVGPaintType aPaintType) {
NS_ASSERTION(aPaintType == eStyleSVGPaintType_ObjectFill ||
aPaintType == eStyleSVGPaintType_ObjectStroke,
"Invalid object paint type");
mPaintType = aPaintType;
mPaintDefinition.mObjectPaint = aObjectPaint;
}
union {
nsSVGPaintServerFrame *mPaintServerFrame;
gfxTextObjectPaint *mObjectPaint;
nscolor mColor;
} mPaintDefinition;
nsIFrame *mFrame;
// CTM defining the user space for the pattern we will use.
gfxMatrix mContextMatrix;
nsStyleSVGPaintType mPaintType;
// Device-space-to-pattern-space
gfxMatrix mPatternMatrix;
nsRefPtrHashtable<nsFloatHashKey, gfxPattern> mPatternCache;
already_AddRefed<gfxPattern> GetPattern(float aOpacity,
nsStyleSVGPaint nsStyleSVG::*aFillOrStroke,
const gfxMatrix& aCTM);
};
Paint mFillPaint;
Paint mStrokePaint;
float mFillOpacity;
float mStrokeOpacity;
};
/**
* Sets up the stroke style in |aContext| and stores stroke pattern
* information in |aThisObjectPaint|.
*/
bool SetupCairoStroke(gfxContext *aContext,
gfxTextObjectPaint *aOuterObjectPaint,
SVGTextObjectPaint *aThisObjectPaint);
/**
* Sets up the fill style in |aContext| and stores fill pattern information
* in |aThisObjectPaint|.
*/
bool SetupCairoFill(gfxContext *aContext,
gfxTextObjectPaint *aOuterObjectPaint,
SVGTextObjectPaint *aThisObjectPaint);
/**
* Sets the current pattern to the fill or stroke style of the outer text
* object. Will also set the paint opacity to transparent if the paint is set
* to "none".
*/
bool SetupObjectPaint(gfxContext *aContext,
nsStyleSVGPaint nsStyleSVG::*aFillOrStroke,
float& aOpacity,
gfxTextObjectPaint *aObjectPaint);
/**
* Stores in |aTargetPaint| information on how to reconstruct the current
* fill or stroke pattern. Will also set the paint opacity to transparent if
* the paint is set to "none".
* @param aOuterObjectPaint pattern information from the outer text object
* @param aTargetPaint where to store the current pattern information
* @param aFillOrStroke member pointer to the paint we are setting up
* @param aProperty the frame property descriptor of the fill or stroke paint
* server frame
*/
void SetupInheritablePaint(gfxContext *aContext,
float& aOpacity,
gfxTextObjectPaint *aOuterObjectPaint,
SVGTextObjectPaint::Paint& aTargetPaint,
nsStyleSVGPaint nsStyleSVG::*aFillOrStroke,
const FramePropertyDescriptor *aProperty);
};
#endif
|
Denia-Vargas-Araya/ApartamentosR
|
packrat/lib/x86_64-w64-mingw32/3.6.1/Rcpp/include/Rcpp/sugar/functions/clamp.h
|
<gh_stars>100-1000
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*-
//
// clamp.h: Rcpp R/C++ interface class library -- clamp
//
// Copyright (C) 2012 <NAME> and <NAME>
//
// This file is part of Rcpp.
//
// Rcpp is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Rcpp is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Rcpp. If not, see <http://www.gnu.org/licenses/>.
#ifndef Rcpp__sugar__clamp_h
#define Rcpp__sugar__clamp_h
namespace Rcpp{
namespace sugar{
template <int RTYPE, bool NA>
struct clamp_operator{
typedef typename Rcpp::traits::storage_type<RTYPE>::type STORAGE ;
clamp_operator(STORAGE lhs_, STORAGE rhs_ ) : lhs(lhs_), rhs(rhs_){}
inline STORAGE operator()(STORAGE x) const {
return x < lhs ? lhs : (x > rhs ? rhs : x ) ;
}
STORAGE lhs, rhs ;
} ;
// need to write this special version
template <>
struct clamp_operator<REALSXP,true> {
clamp_operator(double lhs_, double rhs_ ) : lhs(lhs_), rhs(rhs_){}
inline double operator()(double x) const {
if( Rcpp::traits::is_na<REALSXP>(x) ) return x ;
return x < lhs ? lhs : (x > rhs ? rhs : x ) ;
}
double lhs, rhs ;
} ;
template <
int RTYPE,
bool NA, typename T
>
class Clamp_Primitive_Vector_Primitive : public VectorBase<
RTYPE ,
NA ,
Clamp_Primitive_Vector_Primitive<RTYPE,NA,T>
> {
public:
typedef typename Rcpp::traits::storage_type<RTYPE>::type STORAGE ;
typedef clamp_operator<RTYPE,NA> OPERATOR ;
Clamp_Primitive_Vector_Primitive( STORAGE lhs_, const T& vec_, STORAGE rhs_) : vec(vec_), op(lhs_,rhs_) {}
inline STORAGE operator[]( R_xlen_t i ) const {
return op( vec[i] ) ;
}
inline R_xlen_t size() const { return vec.size() ; }
private:
const T& vec ;
OPERATOR op ;
} ;
} // sugar
template <int RTYPE, bool NA, typename T>
inline sugar::Clamp_Primitive_Vector_Primitive<RTYPE,NA,T>
clamp(
typename Rcpp::traits::storage_type<RTYPE>::type lhs,
const Rcpp::VectorBase<RTYPE,NA,T>& vec,
typename Rcpp::traits::storage_type<RTYPE>::type rhs
){
return sugar::Clamp_Primitive_Vector_Primitive<RTYPE,NA,T>( lhs, vec.get_ref(), rhs ) ;
}
} // Rcpp
#endif
|
holmes07/pulsar-beat-output
|
vendor/github.com/aws/aws-sdk-go-v2/service/ec2/api_op_CancelExportTask.go
|
<reponame>holmes07/pulsar-beat-output
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package ec2
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/internal/awsutil"
"github.com/aws/aws-sdk-go-v2/private/protocol"
"github.com/aws/aws-sdk-go-v2/private/protocol/ec2query"
)
// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelExportTaskRequest
type CancelExportTaskInput struct {
_ struct{} `type:"structure"`
// The ID of the export task. This is the ID returned by CreateInstanceExportTask.
//
// ExportTaskId is a required field
ExportTaskId *string `locationName:"exportTaskId" type:"string" required:"true"`
}
// String returns the string representation
func (s CancelExportTaskInput) String() string {
return awsutil.Prettify(s)
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *CancelExportTaskInput) Validate() error {
invalidParams := aws.ErrInvalidParams{Context: "CancelExportTaskInput"}
if s.ExportTaskId == nil {
invalidParams.Add(aws.NewErrParamRequired("ExportTaskId"))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelExportTaskOutput
type CancelExportTaskOutput struct {
_ struct{} `type:"structure"`
}
// String returns the string representation
func (s CancelExportTaskOutput) String() string {
return awsutil.Prettify(s)
}
const opCancelExportTask = "CancelExportTask"
// CancelExportTaskRequest returns a request value for making API operation for
// Amazon Elastic Compute Cloud.
//
// Cancels an active export task. The request removes all artifacts of the export,
// including any partially-created Amazon S3 objects. If the export task is
// complete or is in the process of transferring the final disk image, the command
// fails and returns an error.
//
// // Example sending a request using CancelExportTaskRequest.
// req := client.CancelExportTaskRequest(params)
// resp, err := req.Send(context.TODO())
// if err == nil {
// fmt.Println(resp)
// }
//
// Please also see https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15/CancelExportTask
func (c *Client) CancelExportTaskRequest(input *CancelExportTaskInput) CancelExportTaskRequest {
op := &aws.Operation{
Name: opCancelExportTask,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &CancelExportTaskInput{}
}
req := c.newRequest(op, input, &CancelExportTaskOutput{})
req.Handlers.Unmarshal.Remove(ec2query.UnmarshalHandler)
req.Handlers.Unmarshal.PushBackNamed(protocol.UnmarshalDiscardBodyHandler)
return CancelExportTaskRequest{Request: req, Input: input, Copy: c.CancelExportTaskRequest}
}
// CancelExportTaskRequest is the request type for the
// CancelExportTask API operation.
type CancelExportTaskRequest struct {
*aws.Request
Input *CancelExportTaskInput
Copy func(*CancelExportTaskInput) CancelExportTaskRequest
}
// Send marshals and sends the CancelExportTask API request.
func (r CancelExportTaskRequest) Send(ctx context.Context) (*CancelExportTaskResponse, error) {
r.Request.SetContext(ctx)
err := r.Request.Send()
if err != nil {
return nil, err
}
resp := &CancelExportTaskResponse{
CancelExportTaskOutput: r.Request.Data.(*CancelExportTaskOutput),
response: &aws.Response{Request: r.Request},
}
return resp, nil
}
// CancelExportTaskResponse is the response type for the
// CancelExportTask API operation.
type CancelExportTaskResponse struct {
*CancelExportTaskOutput
response *aws.Response
}
// SDKResponseMetdata returns the response metadata for the
// CancelExportTask request.
func (r *CancelExportTaskResponse) SDKResponseMetdata() *aws.Response {
return r.response
}
|
APeche/OGS-HYSTEM-EXTRAN
|
GEM/verror.h
|
<filename>GEM/verror.h
//-------------------------------------------------------------------
// $Id: verror.h 725 2012-10-02 15:43:37Z kulik $
/// \file verror.h
/// Declarations of classes TError and TFatalError for error handling.
//
// Copyright (C) 1996-2012 A.Rysin, S.Dmytriyeva
// <GEMS Development Team, mailto:<EMAIL>>
//
// This file is part of the GEMS3K code for thermodynamic modelling
// by Gibbs energy minimization <http://gems.web.psi.ch/GEMS3K/>
//
// GEMS3K is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of
// the License, or (at your option) any later version.
// GEMS3K is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with GEMS3K code. If not, see <http://www.gnu.org/licenses/>.
//-------------------------------------------------------------------
#ifndef _verror_h_
#define _verror_h_
#ifdef IPMGEMPLUGIN
#include <string>
using namespace std;
typedef string gstring;
static const size_t npos = string::npos;
// static const size_t npos = static_cast<size_t>(-1);
// static const size_t npos=32767; /wp sergey 2004 from below assignment
void strip(string& str);
#else
#include "gstring.h"
#endif
struct TError
{
gstring mess;
gstring title;
TError()
{}
TError(const gstring& titl, const gstring& msg):
mess(msg),
title(titl)
{}
virtual ~TError()
{}
};
struct TFatalError:
public TError
{
TFatalError()
{}
TFatalError(TError& err):
TError(err)
{}
TFatalError(const gstring& titl, const gstring& msg):
TError( titl, msg )
{}
};
inline
void Error(const gstring& title, const gstring& message)
{
throw TError(title, message);
}
inline
void ErrorIf(bool error, const gstring& title, const gstring& message)
{
if(error)
throw TError(title, message);
}
#endif
// _verror_h
|
pec017/kubernetes
|
cmd/kubeadm/app/cmd/phases/init/bootstraptoken.go
|
/*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package phases
import (
"fmt"
"k8s.io/kubernetes/cmd/kubeadm/app/cmd/options"
"k8s.io/kubernetes/cmd/kubeadm/app/cmd/phases/workflow"
cmdutil "k8s.io/kubernetes/cmd/kubeadm/app/cmd/util"
clusterinfophase "k8s.io/kubernetes/cmd/kubeadm/app/phases/bootstraptoken/clusterinfo"
nodebootstraptokenphase "k8s.io/kubernetes/cmd/kubeadm/app/phases/bootstraptoken/node"
"github.com/pkg/errors"
)
var (
bootstrapTokenLongDesc = cmdutil.LongDesc(`
Bootstrap tokens are used for establishing bidirectional trust between a node joining
the cluster and a control-plane node.
This command makes all the configurations required to make bootstrap tokens works
and then creates an initial token.
`)
bootstrapTokenExamples = cmdutil.Examples(`
# Make all the bootstrap token configurations and create an initial token, functionally
# equivalent to what generated by kubeadm init.
kubeadm init phase bootstrap-token
`)
)
// NewBootstrapTokenPhase returns the phase to bootstrapToken
func NewBootstrapTokenPhase() workflow.Phase {
return workflow.Phase{
Name: "bootstrap-token",
Aliases: []string{"bootstraptoken"},
Short: "Generates bootstrap tokens used to join a node to a cluster",
Example: bootstrapTokenExamples,
Long: bootstrapTokenLongDesc,
InheritFlags: []string{
options.CfgPath,
options.KubeconfigPath,
options.SkipTokenPrint,
},
Run: runBootstrapToken,
}
}
func runBootstrapToken(c workflow.RunData) error {
data, ok := c.(InitData)
if !ok {
return errors.New("bootstrap-token phase invoked with an invalid data struct")
}
client, err := data.Client()
if err != nil {
return err
}
if !data.SkipTokenPrint() {
tokens := data.Tokens()
if len(tokens) == 1 {
fmt.Printf("[bootstrap-token] Using token: %s\n", tokens[0])
} else if len(tokens) > 1 {
fmt.Printf("[bootstrap-token] Using tokens: %v\n", tokens)
}
}
fmt.Println("[bootstrap-token] Configuring bootstrap tokens, cluster-info ConfigMap, RBAC Roles")
// Create the default node bootstrap token
if err := nodebootstraptokenphase.UpdateOrCreateTokens(client, false, data.Cfg().BootstrapTokens); err != nil {
return errors.Wrap(err, "error updating or creating token")
}
// Create RBAC rules that makes the bootstrap tokens able to get nodes
if err := nodebootstraptokenphase.AllowBoostrapTokensToGetNodes(client); err != nil {
return errors.Wrap(err, "error allowing bootstrap tokens to get Nodes")
}
// Create RBAC rules that makes the bootstrap tokens able to post CSRs
if err := nodebootstraptokenphase.AllowBootstrapTokensToPostCSRs(client); err != nil {
return errors.Wrap(err, "error allowing bootstrap tokens to post CSRs")
}
// Create RBAC rules that makes the bootstrap tokens able to get their CSRs approved automatically
if err := nodebootstraptokenphase.AutoApproveNodeBootstrapTokens(client); err != nil {
return errors.Wrap(err, "error auto-approving node bootstrap tokens")
}
// Create/update RBAC rules that makes the nodes to rotate certificates and get their CSRs approved automatically
if err := nodebootstraptokenphase.AutoApproveNodeCertificateRotation(client); err != nil {
return err
}
// Create the cluster-info ConfigMap with the associated RBAC rules
if err := clusterinfophase.CreateBootstrapConfigMapIfNotExists(client, data.KubeConfigPath()); err != nil {
return errors.Wrap(err, "error creating bootstrap ConfigMap")
}
if err := clusterinfophase.CreateClusterInfoRBACRules(client); err != nil {
return errors.Wrap(err, "error creating clusterinfo RBAC rules")
}
return nil
}
|
fduminy/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/progress/util/PotemkinProgress.java
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.progress.util;
import com.intellij.ide.IdeEventQueue;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.util.concurrency.Semaphore;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import sun.awt.SunToolkit;
import javax.swing.*;
import java.awt.*;
import java.awt.event.InputEvent;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* A progress indicator for write actions. Paints itself explicitly, without resorting to normal Swing's delayed repaint API.
* Doesn't dispatch Swing events, except for handling manually those that can cancel it or affect the visual presentation.
*
* @author peter
*/
public class PotemkinProgress extends ProgressWindow implements PingProgress {
private long myLastUiUpdate = System.currentTimeMillis();
private final LinkedBlockingQueue<InputEvent> myEventQueue = new LinkedBlockingQueue<>();
public PotemkinProgress(@NotNull String title, @Nullable Project project, @Nullable JComponent parentComponent, @Nullable String cancelText) {
super(cancelText != null,false, project, parentComponent, cancelText);
setTitle(title);
ApplicationManager.getApplication().assertIsDispatchThread();
startStealingInputEvents();
}
private void startStealingInputEvents() {
IdeEventQueue.getInstance().addPostEventListener(event -> {
if (event instanceof InputEvent) {
myEventQueue.offer((InputEvent)event);
return true;
}
return false;
}, this);
}
@NotNull
@Override
protected ProgressDialog getDialog() {
return Objects.requireNonNull(super.getDialog());
}
@Override
public void interact() {
if (ApplicationManager.getApplication().isDispatchThread()) {
long now = System.currentTimeMillis();
if (shouldDispatchAwtEvents(now)) {
dispatchAwtEventsWithoutModelAccess(0);
}
updateUI(now);
}
}
private void dispatchAwtEventsWithoutModelAccess(int timeoutMs) {
SunToolkit.flushPendingEvents();
try {
while (true) {
InputEvent event = myEventQueue.poll(timeoutMs, TimeUnit.MILLISECONDS);
if (event == null) return;
dispatchInputEvent(event);
}
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private long myLastShouldDispatchCheck;
private boolean shouldDispatchAwtEvents(long now) {
if (now == myLastShouldDispatchCheck) return false;
myLastShouldDispatchCheck = now;
return getDialog().getPanel().isShowing();
}
private void dispatchInputEvent(@NotNull InputEvent e) {
if (isCancellationEvent(e)) {
cancel();
return;
}
Object source = e.getSource();
if (source instanceof Component && isInDialogWindow((Component)source)) {
((Component)source).dispatchEvent(e);
}
}
private boolean isInDialogWindow(Component source) {
Window dialogWindow = SwingUtilities.windowForComponent(getDialog().getPanel());
return dialogWindow instanceof JDialog && SwingUtilities.isDescendingFrom(source, dialogWindow);
}
private void updateUI(long now) {
JRootPane rootPane = getDialog().getPanel().getRootPane();
if (rootPane == null) {
rootPane = considerShowingDialog(now);
}
if (rootPane != null && timeToPaint(now)) {
paintProgress();
}
}
@Nullable
private JRootPane considerShowingDialog(long now) {
if (now - myLastUiUpdate > myDelayInMillis) {
getDialog().myRepaintRunnable.run();
showDialog();
return getDialog().getPanel().getRootPane();
}
return null;
}
private boolean timeToPaint(long now) {
if (now - myLastUiUpdate <= ProgressDialog.UPDATE_INTERVAL) {
return false;
}
myLastUiUpdate = now;
return true;
}
private void progressFinished() {
getDialog().hideImmediately();
}
/**
* Repaint just the dialog panel. We must not call custom paint methods during write action,
* because they might access the model which might be inconsistent at that moment.
*/
private void paintProgress() {
getDialog().myRepaintRunnable.run();
JPanel dialogPanel = getDialog().getPanel();
dialogPanel.validate();
dialogPanel.paintImmediately(dialogPanel.getBounds());
}
/** Executes the action in EDT, paints itself inside checkCanceled calls. */
public void runInSwingThread(@NotNull Runnable action) {
ApplicationManager.getApplication().assertIsDispatchThread();
try {
ProgressManager.getInstance().runProcess(action, this);
}
catch (ProcessCanceledException ignore) { }
finally {
progressFinished();
}
}
/** Executes the action in a background thread, block Swing thread, handles selected input events and paints itself periodically. */
public void runInBackground(@NotNull Runnable action) {
ApplicationManager.getApplication().assertIsDispatchThread();
enterModality();
try {
ensureBackgroundThreadStarted(action);
while (isRunning()) {
dispatchAwtEventsWithoutModelAccess(10);
updateUI(System.currentTimeMillis());
}
}
finally {
exitModality();
progressFinished();
}
}
private void ensureBackgroundThreadStarted(@NotNull Runnable action) {
Semaphore started = new Semaphore();
started.down();
ApplicationManager.getApplication().executeOnPooledThread(() -> ProgressManager.getInstance().runProcess(() -> {
started.up();
action.run();
}, this));
started.waitFor();
}
}
|
openDSME/CometOS
|
src/communication/ieee802154/mac/MacConfig.cc
|
<reponame>openDSME/CometOS
/*
* CometOS --- a component-based, extensible, tiny operating system
* for wireless networks
*
* Copyright (c) 2015, Institute of Telematics, Hamburg University of Technology
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/**
* @author <NAME>
*/
#include "MacConfig.h"
namespace cometos {
void MacConfig::doSerialize(ByteVector & buf) const {
serialize(buf, this->ccaMode);
serialize(buf, this->ccaThreshold);
serialize(buf, this->nwkId);
serialize(buf, this->channel);
serialize(buf, this->minBE);
serialize(buf, this->maxBE);
serialize(buf, this->maxFrameRetries);
serialize(buf, this->maxBackoffRetries);
serialize(buf, this->ackWaitDuration);
serialize(buf, this->unitBackoff);
serialize(buf, this->macMode);
serialize(buf, this->txPower);
serialize(buf, this->promiscuousMode);
}
void MacConfig::doUnserialize(ByteVector & buf) {
unserialize(buf, this->promiscuousMode);
unserialize(buf, this->txPower);
unserialize(buf, this->macMode);
unserialize(buf, this->unitBackoff);
unserialize(buf, this->ackWaitDuration);
unserialize(buf, this->maxBackoffRetries);
unserialize(buf, this->maxFrameRetries);
unserialize(buf, this->maxBE);
unserialize(buf, this->minBE);
unserialize(buf, this->channel);
unserialize(buf, this->nwkId);
unserialize(buf, this->ccaThreshold);
unserialize(buf, this->ccaMode);
}
bool MacConfig::isValid() {
// TODO define constants for border values
return txPower >= mac_getMinTxPowerLvl()
&& txPower <= mac_getMaxTxPowerLvl()
&& macMode < 8
&& unitBackoff == 320
&& ackWaitDuration >= 544
&& ackWaitDuration <= 864
&& maxBackoffRetries <= 5
&& maxFrameRetries <= 15
&& maxBE <= 8
&& minBE >= 0
&& minBE <= maxBE
&& channel >= MAC_MIN_CHANNEL
&& channel <= MAC_MAX_CHANNEL
&& ccaThreshold <= -60
&& ccaThreshold >= -90
&& ccaMode >= 0
&& ccaMode <= 3;
}
} // namespace cometos
|
anushakeren/JSONoverHTTP-
|
utils.js
|
<filename>utils.js
/*
* utils.js contains functions from eleven-gsjs
* https://github.com/ElevenGiants/eleven-gsjs
*/
//jscs:disable requireCamelCaseOrUpperCaseIdentifiers
var romanMap = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
};
exports.to_roman_numerals = function to_roman_numerals(num) {
var n = parseInt(num, 10);
var res = '';
for (var roman in romanMap) {
var number = romanMap[roman];
var matches = parseInt(n / number, 10);
for (var i = 0; i < matches; i++) {
res += roman;
}
n = n % number;
}
return res;
};
//jscs:enable requireCamelCaseOrUpperCaseIdentifiers
|
FrederickOberg/frederickoberg.github.io
|
fbwiki/mediawiki/extensions/WikiEditor/modules/ext.wikiEditor.js
|
/*
* JavaScript for WikiEditor
*/
( function () {
var editingSessionId, logEditEvent, logEditFeature,
actionPrefixMap = {
firstChange: 'first_change',
saveIntent: 'save_intent',
saveAttempt: 'save_attempt',
saveSuccess: 'save_success',
saveFailure: 'save_failure'
},
trackdebug = !!mw.util.getParamValue( 'trackdebug' );
// This sets $.wikiEditor and $.fn.wikiEditor
require( './jquery.wikiEditor.js' );
function log() {
// mw.log is a no-op unless resource loader is in debug mode, so
// this allows trackdebug to work independently (T211698)
// eslint-disable-next-line no-console
console.log.apply( console, arguments );
}
function sampledLogger( schema, callback ) {
return function () {
var args;
if ( mw.loader.getState( 'ext.eventLogging' ) === null ) {
return;
}
args = Array.prototype.slice.call( arguments );
mw.loader.using( [ 'ext.eventLogging' ] ).done( function () {
// Sampling
// We have to do this on the client too because the unload handler
// can cause an editingSessionId to be generated on the client
// Not using mw.eventLog.inSample() because we need to be able to pass our own editingSessionId
var data,
inSample = mw.eventLog.randomTokenMatch(
1 / mw.config.get( 'wgWMESchemaEditAttemptStepSamplingRate' ),
editingSessionId
);
if ( !inSample && !mw.config.get( 'wgWMESchemaEditAttemptStepOversample' ) && !trackdebug ) {
return;
}
data = callback.apply( this, [ inSample ].concat( args ) );
if ( trackdebug ) {
log( schema, data );
} else {
mw.eventLog.logEvent( schema, data );
}
} );
};
}
logEditEvent = sampledLogger( 'EditAttemptStep', function ( inSample, action, data ) {
var actionPrefix = actionPrefixMap[ action ] || action;
/* eslint-disable camelcase */
data = $.extend( {
version: 1,
action: action,
is_oversample: !inSample,
editing_session_id: editingSessionId,
page_token: mw.user.getPageviewToken(),
session_token: mw.user.sessionId(),
editor_interface: 'wikitext',
platform: 'desktop', // FIXME T249944
integration: 'page',
page_id: mw.config.get( 'wgArticleId' ),
page_title: mw.config.get( 'wgPageName' ),
page_ns: mw.config.get( 'wgNamespaceNumber' ),
revision_id: mw.config.get( 'wgRevisionId' ),
user_id: mw.user.getId(),
user_editcount: mw.config.get( 'wgUserEditCount', 0 ),
mw_version: mw.config.get( 'wgVersion' )
}, data );
if ( mw.user.isAnon() ) {
data.user_class = 'IP';
}
// Schema's kind of a mess of special properties
if ( data.action === 'init' || data.action === 'abort' || data.action === 'saveFailure' ) {
data[ actionPrefix + '_type' ] = data.type;
}
if ( data.action === 'init' || data.action === 'abort' ) {
data[ actionPrefix + '_mechanism' ] = data.mechanism;
}
if ( data.action !== 'init' ) {
data[ actionPrefix + '_timing' ] = data.timing === undefined ? 0 : Math.floor( data.timing );
}
/* eslint-enable camelcase */
// Remove renamed properties
delete data.type;
delete data.mechanism;
delete data.timing;
return data;
} );
logEditFeature = sampledLogger( 'VisualEditorFeatureUse', function ( inSample, feature, action ) {
/* eslint-disable camelcase */
return {
feature: feature,
action: action,
editingSessionId: editingSessionId,
user_id: mw.user.getId(),
user_editcount: mw.config.get( 'wgUserEditCount', 0 ),
platform: 'desktop', // FIXME T249944
integration: 'page',
editor_interface: 'wikitext'
};
/* eslint-enable camelcase */
} );
function logAbort( switchingToVE, unmodified ) {
var abortType;
if ( switchingToVE ) {
logEditFeature( 'editor-switch', 'visual-desktop' );
}
if ( switchingToVE && unmodified ) {
abortType = 'switchnochange';
} else if ( switchingToVE ) {
abortType = 'switchwithout';
} else if ( unmodified ) {
abortType = 'nochange';
} else {
abortType = 'abandon';
}
logEditEvent( 'abort', {
type: abortType
} );
}
$( function () {
var $textarea = $( '#wpTextbox1' ),
$editingSessionIdInput = $( '#editingStatsId' ),
origText = $textarea.val(),
submitting, onUnloadFallback, dialogsConfig, readyTime;
if ( $editingSessionIdInput.length ) {
editingSessionId = $editingSessionIdInput.val();
if ( window.performance && window.performance.timing ) {
// We want to track from the time the user started to try to
// launch the editor which navigationStart approximates. All
// of our supported browsers *should* allow this. Rather than
// fall back to the timestamp when the page loaded for those
// that don't, we just ignore them, so as to not skew the
// results towards better-performance in those cases.
readyTime = Date.now();
logEditEvent( 'ready', {
timing: readyTime - window.performance.timing.navigationStart
} );
$textarea.on( 'wikiEditor-toolbar-doneInitialSections', function () {
logEditEvent( 'loaded', {
timing: Date.now() - window.performance.timing.navigationStart
} );
} ).one( 'input', function () {
logEditEvent( 'firstChange', {
timing: Date.now() - readyTime
} );
} );
}
$textarea.closest( 'form' ).on( 'submit', function () {
submitting = true;
} );
onUnloadFallback = window.onunload;
window.onunload = function () {
var fallbackResult,
unmodified = mw.config.get( 'wgAction' ) !== 'submit' && origText === $textarea.val(),
caVeEdit = $( '#ca-ve-edit' )[ 0 ],
switchingToVE = caVeEdit && (
document.activeElement === caVeEdit ||
$.contains( caVeEdit, document.activeElement )
);
if ( onUnloadFallback ) {
fallbackResult = onUnloadFallback();
}
if ( !submitting ) {
logAbort( switchingToVE, unmodified );
}
// If/when the user uses the back button to go back to the edit form
// and the browser serves this from bfcache, regenerate the session ID
// so we don't use the same ID twice. Ideally we'd do this by listening to the pageshow
// event and checking e.originalEvent.persisted, but that doesn't work in Chrome:
// https://code.google.com/p/chromium/issues/detail?id=344507
// So instead we modify the DOM here, after sending the abort event.
editingSessionId = mw.user.generateRandomSessionId();
$editingSessionIdInput.val( editingSessionId );
return fallbackResult;
};
$textarea.on( 'wikiEditor-switching-visualeditor', function () {
var unmodified = mw.config.get( 'wgAction' ) !== 'submit' && origText === $textarea.val();
// A non-navigation switch to VE has occurred. As such, avoid eventually
// double-logging an abort when VE is done.
window.onunload = onUnloadFallback;
logAbort( true, unmodified );
} );
}
// The old toolbar is still in place and needs to be removed so there aren't two toolbars
$( '#toolbar' ).remove();
// Add toolbar module
// TODO: Implement .wikiEditor( 'remove' )
$textarea.wikiEditor(
'addModule', require( './jquery.wikiEditor.toolbar.config.js' )
);
dialogsConfig = require( './jquery.wikiEditor.dialogs.config.js' );
// Replace icons
dialogsConfig.replaceIcons( $textarea );
// Add dialogs module
$textarea.wikiEditor( 'addModule', dialogsConfig.getDefaultConfig() );
} );
}() );
|
howkj1/telepharm-dsmjs
|
test/modules/authentication/middleware.spec.js
|
<gh_stars>1-10
import { AuthContext, createTokenAsync } from '../../../src/modules/authentication'
import { anyString, anyStrings } from '../../util/any'
describe('Authentication Middleware', () => {
const expectedDefaultAuthContext = {
authenticated: false
}
async function expectMiddlewareToSetAuthContextAsync (token, expectedAuthContext, options) {
const middleware = new AuthContext(options).middleware,
expectedResult = anyString(),
nextStub = sinon.stub().returns(expectedResult),
context = {
req: {
headers: {
authorization: token ? 'Bearer ' + token : void 0
}
}
},
result = await middleware(context, nextStub)
expect(result).to.equal(expectedResult)
expect(context.authContext).to.eql(expectedAuthContext)
}
it('should provide a default context if no token is provided', () => {
return expectMiddlewareToSetAuthContextAsync('', expectedDefaultAuthContext)
})
it('should set a valid auth context if the token is valid', async () => {
const accountId = anyString(),
claims = anyStrings(),
randomPropertyKey = anyString(),
randomPropertyValue = anyString(),
token = await createTokenAsync({
accountId,
claims,
[randomPropertyKey]: randomPropertyValue
})
expect(token).to.be.a('string')
expect(token.indexOf(accountId)).to.equal(-1, 'token must obfuscate the auth context!')
await expectMiddlewareToSetAuthContextAsync(token, {
authenticated: true,
accountId,
claims,
[randomPropertyKey]: randomPropertyValue
})
})
it('should provide a default context if an invalid token is provided', () => {
return expectMiddlewareToSetAuthContextAsync(anyString(), expectedDefaultAuthContext)
})
it('should allow an override for the authContextFactory', async () => {
const accountId = anyString(),
claims = anyStrings(),
randomPropertyKey = anyString(),
randomPropertyValue = anyString(),
expectedTokenContents = {
accountId,
claims,
[randomPropertyKey]: randomPropertyValue
},
token = await createTokenAsync(expectedTokenContents),
expectedAuthContext = anyString(),
authContextFactory = (parsedToken) => {
expectedTokenContents.authenticated = true
expect(parsedToken).to.eql(expectedTokenContents)
return expectedAuthContext
}
return expectMiddlewareToSetAuthContextAsync(token, expectedAuthContext, {
authContextFactory
})
})
})
|
mcgizzle/weaver-test
|
modules/core/cats/src-ce3/weaver/BaseIOSuite.scala
|
<gh_stars>100-1000
package weaver
import cats.effect.IO
trait BaseIOSuite extends RunnableSuite[IO] with BaseCatsSuite {
implicit protected def effectCompat: UnsafeRun[IO] = CatsUnsafeRun
def getSuite: EffectSuite[IO] = this
}
trait BaseFunIOSuite extends FunSuiteF[IO] with BaseCatsSuite {
implicit protected def effectCompat: UnsafeRun[EffectType] = CatsUnsafeRun
def getSuite: EffectSuite[IO] = this
}
|
rubicon/tabler-icons
|
icons-react/icons-js/mug-off.js
|
import * as React from "react";
function IconMugOff({
size = 24,
color = "currentColor",
stroke = 2,
...props
}) {
return <svg xmlns="http://www.w3.org/2000/svg" className="icon icon-tabler icon-tabler-mug-off" width={size} height={size} viewBox="0 0 24 24" strokeWidth={stroke} stroke={color} fill="none" strokeLinecap="round" strokeLinejoin="round" {...props}><path stroke="none" d="M0 0h24v24H0z" fill="none" /><path d="M9 5h5.917a1.08 1.08 0 0 1 1.083 1.077v5.923m-.167 3.88a4.33 4.33 0 0 1 -4.166 3.12h-4.334c-2.393 0 -4.333 -1.929 -4.333 -4.308v-8.615a1.08 1.08 0 0 1 1.083 -1.077h.917" /><path d="M16 8h2.5c1.38 0 2.5 1.045 2.5 2.333v2.334c0 1.148 -.89 2.103 -2.06 2.297" /><path d="M3 3l18 18" /></svg>;
}
export default IconMugOff;
|
nicktar/modelmapper
|
core/src/test/java/org/modelmapper/functional/deepmapping/NestedMappingTest5.java
|
<reponame>nicktar/modelmapper
package org.modelmapper.functional.deepmapping;
import org.modelmapper.AbstractTest;
import org.testng.annotations.Test;
/**
* @author <NAME>
*/
@Test(groups = "functional")
@SuppressWarnings("unused")
public class NestedMappingTest5 extends AbstractTest {
private static class Address {
int id;
String street;
String city;
}
private static class AddressDTO {
String id;
String city;
}
private static class Customer {
int id;
Address homeAddress;
Address mailingAddress;
}
private static class Order {
int id;
Customer customer;
Shipper shipper;
Address companyAddress;
}
private static class OrderDTO1 {
String id;
int customerId;
String homeStreet;
String mailingCity;
}
private static class OrderDTO2 {
String id;
String shipperStreet;
String mailingCity;
}
private static class OrderDTO3 {
AddressDTO homeAddress;
}
private static class Shipper {
Address address;
}
/**
* Order/id to OrderDTO1/id Order/customer/id to OrderDTO1/customerId homeStreet is ambiguous
* mailingCity is ambiguous
*/
public void shouldMapOrderToOrderDTO1() {
}
}
|
pentaho/hive-0.7.0
|
src/serde/src/java/org/apache/hadoop/hive/serde2/objectinspector/primitive/JavaFloatObjectInspector.java
|
/*!
* Copyright 2010 - 2013 Pentaho Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.hadoop.hive.serde2.objectinspector.primitive;
import org.apache.hadoop.io.FloatWritable;
/**
* A JavaFloatObjectInspector inspects a Java Float Object.
*/
public class JavaFloatObjectInspector extends
AbstractPrimitiveJavaObjectInspector implements
SettableFloatObjectInspector {
JavaFloatObjectInspector() {
super(PrimitiveObjectInspectorUtils.floatTypeEntry);
}
@Override
public Object getPrimitiveWritableObject(Object o) {
return o == null ? null : new FloatWritable(((Float) o).floatValue());
}
@Override
public float get(Object o) {
return ((Float) o).floatValue();
}
@Override
public Object create(float value) {
return Float.valueOf(value);
}
@Override
public Object set(Object o, float value) {
return Float.valueOf(value);
}
}
|
oi-analytics/argentina-transport
|
src/atra/plot/network_water.py
|
"""Plot water network
"""
import os
import cartopy.crs as ccrs
import geopandas
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
from atra.utils import load_config, get_axes, plot_basemap, scale_bar, plot_basemap_labels, save_fig
def main(config):
"""Read shapes, plot map
"""
data_path = config['paths']['data']
# data
output_file = os.path.join(config['paths']['figures'], 'network-water-map.png')
water_edge_file = os.path.join(data_path, 'network', 'port_edges.shp')
water_node_file = os.path.join(data_path, 'network', 'port_nodes.shp')
# basemap
proj_lat_lon = ccrs.PlateCarree()
ax = get_axes()
plot_basemap(ax, data_path)
scale_bar(ax, location=(0.8, 0.05))
plot_basemap_labels(ax, data_path, include_regions=True)
colors = {
'Waterway': '#045a8d',
'Port': '#54278f'
}
# edges
edges = geopandas.read_file(water_edge_file)
ax.add_geometries(
list(edges.geometry.buffer(0.02)),
crs=proj_lat_lon,
edgecolor='none',
facecolor=colors['Waterway'],
zorder=4
)
# nodes
nodes = geopandas.read_file(water_node_file)
nodes = nodes[nodes['name']!='none']
ax.scatter(
list(nodes.geometry.x),
list(nodes.geometry.y),
transform=proj_lat_lon,
facecolor=colors['Port'],
s=4,
zorder=5
)
# legend
legend_handles = [
mpatches.Patch(color=color, label=label)
for label, color in colors.items()
]
plt.legend(handles=legend_handles, loc='lower left')
# save
save_fig(output_file)
if __name__ == '__main__':
CONFIG = load_config()
main(CONFIG)
|
miladajilian/MimMessenger
|
submodules/LegacyComponents/LegacyComponents/PSLMDBKeyValueStore.h
|
<reponame>miladajilian/MimMessenger<gh_stars>1-10
#import <LegacyComponents/PSKeyValueStore.h>
@interface PSLMDBKeyValueStore : NSObject <PSKeyValueStore>
+ (instancetype)storeWithPath:(NSString *)path size:(NSUInteger)size;
- (void)close;
@end
|
Abd4llA/kyma
|
components/event-bus/api/publish/v2/validators.go
|
package v2
import (
"regexp"
"time"
api "github.com/kyma-project/kyma/components/event-bus/api/publish"
)
var (
isValidEventID = regexp.MustCompile(api.AllowedEventIDChars).MatchString
// channel name components
isValidSourceID = regexp.MustCompile(api.AllowedSourceIDChars).MatchString
isValidEventType = regexp.MustCompile(api.AllowedEventTypeChars).MatchString
isValidEventTypeVersion = regexp.MustCompile(api.AllowedEventTypeVersionChars).MatchString
)
//ValidatePublish validates a publish POST request
func ValidatePublish(r *EventRequestV2, opts *api.EventOptions) *api.Error {
if len(r.ID) == 0 {
return ErrorResponseMissingFieldEventID()
}
if len(r.Source) == 0 {
return ErrorResponseMissingFieldSourceID()
}
if len(r.SpecVersion) == 0 {
return ErrorResponseMissingFieldSpecVersion()
}
if len(r.Type) == 0 {
return ErrorResponseMissingFieldEventType()
}
if len(r.TypeVersion) == 0 {
return ErrorResponseMissingFieldEventTypeVersion()
}
if len(r.Time) == 0 {
return ErrorResponseMissingFieldEventTime()
}
if r.Data == nil {
return api.ErrorResponseMissingFieldData()
} else if d, ok := (r.Data).(string); ok && d == "" {
return api.ErrorResponseMissingFieldData()
}
//validate the event components lengths
if len(r.Source) > opts.MaxSourceIDLength {
return api.ErrorInvalidSourceIDLength(opts.MaxSourceIDLength)
}
if len(r.Type) > opts.MaxEventTypeLength {
return api.ErrorInvalidEventTypeLength(opts.MaxEventTypeLength)
}
if len(r.TypeVersion) > opts.MaxEventTypeVersionLength {
return api.ErrorInvalidEventTypeVersionLength(opts.MaxEventTypeVersionLength)
}
// validate the fully-qualified topic name components
if !isValidSourceID(r.Source) {
return ErrorResponseWrongSourceID()
}
if !isValidEventType(r.Type) {
return ErrorResponseWrongEventType()
}
if !isValidEventTypeVersion(r.TypeVersion) {
return ErrorResponseWrongEventTypeVersion()
}
if r.SpecVersion != SpecVersionV3 {
return ErrorResponseWrongSpecVersion()
}
if _, err := time.Parse(time.RFC3339, r.Time); err != nil {
return ErrorResponseWrongEventTime()
}
if len(r.ID) > 0 && !isValidEventID(r.ID) {
return ErrorResponseWrongEventID()
}
return nil
}
|
rebpdx/metal-by-example
|
objc/06-Texturing/Texturing/MBERenderer.h
|
<filename>objc/06-Texturing/Texturing/MBERenderer.h
#import "MBEMetalView.h"
@interface MBERenderer : NSObject <MTKViewDelegate>
- (nonnull instancetype)initWithMetalKitView:(nonnull MBEMetalView *) mtkView;
@end
|
tschaffter/apl-core-library
|
aplcore/src/component/touchablecomponent.cpp
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include "apl/component/componentpropdef.h"
#include "apl/component/touchablecomponent.h"
#include "apl/content/rootconfig.h"
#include "apl/engine/keyboardmanager.h"
#include "apl/engine/propdef.h"
#include "apl/time/sequencer.h"
#include "apl/touch/gesture.h"
namespace apl {
static std::map<PropertyKey, std::string> sPropertyHandlers = {
{kPropertyOnCancel, "Cancel"},
{kPropertyOnDown, "Down"},
{kPropertyOnMove, "Move"},
{kPropertyOnPress, "Press"},
{kPropertyOnUp, "Up"}
};
static std::map<PropertyKey, bool> sPropertyExecutesFast = {
{kPropertyOnCancel, true},
{kPropertyOnDown, true},
{kPropertyOnMove, true},
{kPropertyOnPress, false},
{kPropertyOnUp, true}
};
void
TouchableComponent::setGestureHandlers()
{
auto handlers = getCalculated(kPropertyGestures).getArray();
for (auto& handler : handlers) {
auto gesture = Gesture::create(std::dynamic_pointer_cast<TouchableComponent>(shared_from_this()), handler);
if (gesture) {
mGestureHandlers.emplace_back(gesture);
}
}
}
PointerCaptureStatus
TouchableComponent::processPointerEvent(const PointerEvent& event, apl_time_t timestamp)
{
auto pointerStatus = ActionableComponent::processPointerEvent(event, timestamp);
if (pointerStatus != kPointerStatusNotCaptured)
return pointerStatus;
// Exit as we processed it as pressed.
return event.pointerEventType == kPointerUp ? kPointerStatusCaptured
: kPointerStatusNotCaptured;
}
void
TouchableComponent::invokeStandardAccessibilityAction(const std::string& name)
{
auto onPressHandler = getCalculated(kPropertyOnPress);
if (name == "activate" && !onPressHandler.empty())
executeEventHandler(sPropertyHandlers.at(kPropertyOnPress),
onPressHandler, false, createTouchEventProperties(Point()));
else
ActionableComponent::invokeStandardAccessibilityAction(name);
}
const ComponentPropDefSet &
TouchableComponent::propDefSet() const
{
static ComponentPropDefSet sTouchableComponentProperties(ActionableComponent::propDefSet(), {
{kPropertyOnCancel, Object::EMPTY_ARRAY(), asCommand, kPropIn},
{kPropertyOnDown, Object::EMPTY_ARRAY(), asCommand, kPropIn},
{kPropertyOnMove, Object::EMPTY_ARRAY(), asCommand, kPropIn},
{kPropertyOnPress, Object::EMPTY_ARRAY(), asCommand, kPropIn},
{kPropertyOnUp, Object::EMPTY_ARRAY(), asCommand, kPropIn},
{kPropertyGestures, Object::EMPTY_ARRAY(), asArray, kPropIn}
});
return sTouchableComponentProperties;
}
void
TouchableComponent::executePreEventActions(PropertyKey handlerKey)
{
switch (handlerKey) {
case kPropertyOnUp:
case kPropertyOnCancel:
case kPropertyOnPress:
case kPropertyHandleKeyUp:
setState(kStatePressed, false);
mReceivedOnDown = false;
break;
case kPropertyOnDown:
case kPropertyHandleKeyDown:
setState(kStatePressed, true);
mReceivedOnDown = true;
break;
case kPropertyOnMove:
default:
break;
}
}
void
TouchableComponent::executePostEventActions(PropertyKey handlerKey, const Point &localPoint)
{
switch (handlerKey) {
case kPropertyOnUp:
if (containsLocalPosition(localPoint)) {
executePointerEventHandler(kPropertyOnPress, localPoint);
}
break;
case kPropertyOnCancel:
case kPropertyOnDown:
case kPropertyOnPress:
case kPropertyOnMove:
default:
break;
}
}
void
TouchableComponent::addHandlerEventProperties(PropertyKey handlerKey,
const Point& localPoint,
const ObjectMapPtr& eventProperties) const
{
switch (handlerKey) {
case kPropertyOnMove:
case kPropertyOnUp:
eventProperties->emplace("inBounds", containsLocalPosition(localPoint));
break;
case kPropertyOnCancel:
case kPropertyOnDown:
case kPropertyOnPress:
default:
break;
}
}
void
TouchableComponent::executePointerEventHandler(PropertyKey handlerKey, const Point& localPoint)
{
if (mState.get(kStateDisabled)) return;
// If not pressed - do not propagate any "finishing" event.
if (!mReceivedOnDown && (handlerKey == kPropertyOnUp || handlerKey == kPropertyOnCancel)) return;
executePreEventActions(handlerKey);
auto& commands = getCalculated(handlerKey);
if (!commands.empty()) {
auto fastMode = sPropertyExecutesFast.at(handlerKey);
ObjectMapPtr props = nullptr;
if (handlerKey != kPropertyOnPress) {
props = createTouchEventProperties(localPoint);
}
addHandlerEventProperties(handlerKey, localPoint, props);
executeEventHandler(sPropertyHandlers.at(handlerKey), commands, fastMode, props);
}
executePostEventActions(handlerKey, localPoint);
}
bool
TouchableComponent::executeIntrinsicKeyHandlers(KeyHandlerType type, const Keyboard& keyboard)
{
if (!mState.get(kStateDisabled)) {
auto handlerKey = KeyboardManager::getHandlerPropertyKey(type);
if ((Keyboard::ENTER_KEY().sameKey(keyboard) || Keyboard::NUMPAD_ENTER_KEY().sameKey(keyboard))
&& !getCalculated(kPropertyOnPress).empty()) {
executePreEventActions(handlerKey);
handleEnterKey(handlerKey);
return true;
}
}
return ActionableComponent::executeIntrinsicKeyHandlers(type, keyboard);
}
void
TouchableComponent::handleEnterKey(PropertyKey handlerKey)
{
switch (handlerKey) {
case kPropertyHandleKeyDown:
break;
case kPropertyHandleKeyUp:
executeEventHandler(sPropertyHandlers.at(kPropertyOnPress), getCalculated(kPropertyOnPress), false);
break;
default:
break;
}
}
bool
TouchableComponent::getTags(rapidjson::Value &outMap, rapidjson::Document::AllocatorType &allocator)
{
CoreComponent::getTags(outMap, allocator);
outMap.AddMember("clickable", true, allocator);
return true;
}
Object
TouchableComponent::getValue() const
{
return mState.get(kStateChecked);
}
void
TouchableComponent::initialize()
{
CoreComponent::initialize();
setGestureHandlers();
}
// TODO: remove once we support handing intrinsic/reserved keys
void
TouchableComponent::update(UpdateType type, float value)
{
if (type == kUpdatePressed) {
// don't bother with setting pressed state and unsetting it here, although this should only
// be triggered from the enter key/dpad center, we've lost the timings of key up/down. Will
// be rectified once intrinsic key handling is complete. This is not spec compliant, but meets
// parity with the old touchwrapper impl
executePointerEventHandler(kPropertyOnPress, {-1, -1});
} else
CoreComponent::update(type, value);
}
} // namespace apl
|
tsingqguo/ABA
|
utils/neuron/data/datasets/vot.py
|
<gh_stars>10-100
import os
import os.path as osp
import glob
import numpy as np
import json
import hashlib
import neuron.ops as ops
from neuron.config import registry
from .dataset import SeqDataset
__all__ = ['VOT']
@registry.register_module
class VOT(SeqDataset):
r"""`VOT <http://www.votchallenge.net/>`_ Datasets.
Publication:
``The Visual Object Tracking VOT2017 challenge results``, <NAME>, <NAME>
and <NAME>, etc. 2017.
Args:
root_dir (string): Root directory of dataset where sequence
folders exist.
version (integer, optional): Specify the benchmark version. Specify as
one of 2013~2018. Default is 2017.
anno_type (string, optional): Returned annotation types, chosen as one of
``rect`` and ``corner``. Default is ``rect``.
download (boolean, optional): If True, downloads the dataset from the internet
and puts it in root directory. If dataset is downloaded, it is not
downloaded again.
list_file (string, optional): If provided, only read sequences
specified by the file.
"""
__valid_versions = [2013, 2014, 2015, 2016, 2017, 2018, 'LT2018',
2019, 'LT2019', 'RGBD2019', 'RGBT2019']
def __init__(self, root_dir=None, version=2019, anno_type='rect',
download=True, list_file=None):
assert version in self.__valid_versions, 'Unsupport VOT version.'
assert anno_type in ['default', 'rect', 'inner_rect'], \
'Unknown annotation type.'
if root_dir is None:
root_dir = osp.expanduser('~/data/vot{}'.format(version))
self.root_dir = root_dir
self.version = version
self.anno_type = anno_type
if download:
self._download(root_dir, version)
if list_file is None:
list_file = osp.join(root_dir, 'list.txt')
# initialize the dataset
super(VOT, self).__init__(
name='VOT-{}'.format(self.version),
root_dir=self.root_dir,
list_file=list_file)
def _construct_seq_dict(self, root_dir, list_file):
# image and annotation paths
with open(list_file, 'r') as f:
seq_names = f.read().strip().split('\n')
seq_dirs = [osp.join(root_dir, s) for s in seq_names]
anno_files = [osp.join(s, 'groundtruth.txt')
for s in seq_dirs]
# construct seq_dict
seq_dict = {}
for s, seq_name in enumerate(seq_names):
img_files = sorted(glob.glob(
osp.join(seq_dirs[s], '*.jpg')))
anno = np.loadtxt(anno_files[s], delimiter=',')
anno = self._format(anno)
# meta information
seq_len = len(img_files)
img0 = ops.read_image(img_files[0])
meta = self._fetch_meta(seq_dirs[s], seq_len)
meta.update({
'width': img0.shape[1],
'height': img0.shape[0],
'frame_num': seq_len,
'target_num': 1,
'total_instances': seq_len})
# update seq_dict
seq_dict[seq_name] = {
'img_files': img_files,
'target': {
'anno': anno,
'meta': meta}}
return seq_dict
def _download(self, root_dir, version):
assert version in self.__valid_versions
if not osp.isdir(root_dir):
os.makedirs(root_dir)
elif osp.isfile(osp.join(root_dir, 'list.txt')):
with open(osp.join(root_dir, 'list.txt')) as f:
seq_names = f.read().strip().split('\n')
if all([osp.isdir(osp.join(root_dir, s)) for s in seq_names]):
ops.sys_print('Files already downloaded.')
return
url = 'http://data.votchallenge.net/'
if version in range(2013, 2015 + 1):
# main challenge (2013~2015)
homepage = url + 'vot{}/dataset/'.format(version)
elif version in range(2015, 2019 + 1):
# main challenge (2016~2019)
homepage = url + 'vot{}/main/'.format(version)
elif version.startswith('LT'):
# long-term tracking challenge
year = int(version[2:])
homepage = url + 'vot{}/longterm/'.format(year)
elif version.startswith('RGBD'):
# RGBD tracking challenge
year = int(version[4:])
homepage = url + 'vot{}/rgbd/'.format(year)
elif version.startswith('RGBT'):
# RGBT tracking challenge
year = int(version[4:])
url = url + 'vot{}/rgbtir/'.format(year)
homepage = url + 'meta/'
# download description file
bundle_url = homepage + 'description.json'
bundle_file = osp.join(root_dir, 'description.json')
if not osp.isfile(bundle_file):
ops.sys_print('Downloading description file...')
ops.download(bundle_url, bundle_file)
# read description file
ops.sys_print('\nParsing description file...')
with open(bundle_file) as f:
bundle = json.load(f)
# md5 generator
def md5(filename):
hash_md5 = hashlib.md5()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
# download all sequences
seq_names = []
for seq in bundle['sequences']:
seq_name = seq['name']
seq_names.append(seq_name)
# download channel (color/depth/ir) files
channels = seq['channels'].keys()
seq_files = []
for cn in channels:
seq_url = seq['channels'][cn]['url']
if not seq_url.startswith(('http', 'https')):
seq_url = url + seq_url[seq_url.find('sequence'):]
seq_file = osp.join(
root_dir,
'{}_{}.zip'.format(seq_name, cn))
if not osp.isfile(seq_file) or \
md5(seq_file) != seq['channels'][cn]['checksum']:
ops.sys_print('\nDownloading %s...' % seq_name)
ops.download(seq_url, seq_file)
seq_files.append(seq_file)
# download annotations
anno_url = homepage + '%s.zip' % seq_name
anno_file = osp.join(root_dir, seq_name + '_anno.zip')
if not osp.isfile(anno_file) or \
md5(anno_file) != seq['annotations']['checksum']:
ops.download(anno_url, anno_file)
# unzip compressed files
seq_dir = osp.join(root_dir, seq_name)
if not osp.isfile(seq_dir) or len(os.listdir(seq_dir)) < 10:
ops.sys_print('\nExtracting %s...' % seq_name)
os.makedirs(seq_dir)
for seq_file in seq_files:
ops.extract(seq_file, seq_dir)
ops.extract(anno_file, seq_dir)
# save list.txt
list_file = osp.join(root_dir, 'list.txt')
with open(list_file, 'w') as f:
f.write(str.join('\n', seq_names))
return root_dir
def _format(self, anno):
if anno.shape[1] == 8:
if self.anno_type == 'rect':
anno = self._corner2rect(anno)
elif self.anno_type == 'inner_rect':
anno = self._corner2rect_inner(anno)
if anno.shape[1] == 4:
anno[:, 2:] = anno[:, :2] + anno[:, 2:] - 1
return anno
def _corner2rect(self, corners, center=False):
x1 = np.min(corners[:, 0::2], axis=1)
x2 = np.max(corners[:, 0::2], axis=1)
y1 = np.min(corners[:, 1::2], axis=1)
y2 = np.max(corners[:, 1::2], axis=1)
w = x2 - x1
h = y2 - y1
if center:
cx = np.mean(corners[:, 0::2], axis=1)
cy = np.mean(corners[:, 1::2], axis=1)
return np.array([cx, cy, w, h]).T
else:
return np.array([x1, y1, w, h]).T
def _corner2rect_inner(self, corners, center=False):
cx = np.mean(corners[:, 0::2], axis=1)
cy = np.mean(corners[:, 1::2], axis=1)
x1 = np.min(corners[:, 0::2], axis=1)
x2 = np.max(corners[:, 0::2], axis=1)
y1 = np.min(corners[:, 1::2], axis=1)
y2 = np.max(corners[:, 1::2], axis=1)
area1 = np.linalg.norm(corners[:, 0:2] - corners[:, 2:4], axis=1) * \
np.linalg.norm(corners[:, 2:4] - corners[:, 4:6], axis=1)
area2 = (x2 - x1) * (y2 - y1)
scale = np.sqrt(area1 / area2)
w = scale * (x2 - x1) + 1
h = scale * (y2 - y1) + 1
if center:
return np.array([cx, cy, w, h]).T
else:
return np.array([cx - w / 2, cy - h / 2, w, h]).T
def _fetch_meta(self, seq_dir, frame_num):
meta = {}
# attributes
tag_files = glob.glob(osp.join(seq_dir, '*.label')) + \
glob.glob(osp.join(seq_dir, '*.tag'))
for f in tag_files:
if not osp.exists(f):
continue
tag = osp.basename(f)
tag = tag[:tag.rfind('.')]
meta[tag] = np.loadtxt(f)
# practical
practical_file = osp.join(seq_dir, 'practical')
if osp.isfile(practical_file + '.value'):
meta['practical'] = np.loadtxt(practical_file + '.value')
if osp.isfile(practical_file + '.txt'):
meta['practical_txt'] = np.loadtxt(practical_file + '.txt')
# pad zeros if necessary
for tag, val in meta.items():
if len(val) < frame_num:
meta[tag] = np.pad(
val, (0, frame_num - len(val)), 'constant')
return meta
|
MarkStega/CQC
|
Source/AllProjects/RemBrws/CQCRemBrws/CQCRemBrws_AppShellAdminClientProxy.cpp
|
<filename>Source/AllProjects/RemBrws/CQCRemBrws/CQCRemBrws_AppShellAdminClientProxy.cpp
// ----------------------------------------------------------------------------
// FILE: CQCRemBrws_AppShellAdminClientProxy.cpp
// DATE: Fri, Feb 12 21:14:15 2021 -0500
// ID: 78E315ECD585BF17-A16F26D604EC670D
//
// This file was generated by the Charmed Quark CIDIDL compiler. Do not make
// changes by hand, because they will be lost if the file is regenerated.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------------
#include "CQCRemBrws_.hpp"
// ----------------------------------------------------------------------------
// Magic macros
// ----------------------------------------------------------------------------
AdvRTTIDecls(TCQCAppShellAdminClientProxy,TOrbClientBase)
// ----------------------------------------------------------------------------
// TCQCAppShellAdminClientProxy: Public, static data
// ----------------------------------------------------------------------------
const TString TCQCAppShellAdminClientProxy::strInterfaceId(L"78E315ECD585BF17-A16F26D604EC670D");
const TString TCQCAppShellAdminClientProxy::strScope(L"/CQC/CQCAppShell");
// ----------------------------------------------------------------------------
// TCQCAppShellAdminClientProxy: Constructors and Destructor
// ----------------------------------------------------------------------------
TCQCAppShellAdminClientProxy::TCQCAppShellAdminClientProxy()
{
}
TCQCAppShellAdminClientProxy::
TCQCAppShellAdminClientProxy(const TOrbObjId& ooidSrc, const TString& strNSBinding)
{
#if CID_DEBUG_ON
if (!ooidSrc.oidKey().bIsInterfaceId(strInterfaceId))
{
facCIDOrb().ThrowErr
(
CID_FILE
, CID_LINE
, kOrbErrs::errcClient_BadIntfId
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::BadParms
, ooidSrc.oidKey().mhashInterface()
, strInterfaceId
);
}
#endif
SetObjId(ooidSrc, strNSBinding, kCIDLib::False);
}
TCQCAppShellAdminClientProxy::~TCQCAppShellAdminClientProxy()
{
}
// ----------------------------------------------------------------------------
// TCQCAppShellAdminClientProxy: Public, non-virtual methods
// ----------------------------------------------------------------------------
tCIDLib::TBoolean TCQCAppShellAdminClientProxy::bQueryNewMsgs
(
CIOP tCIDLib::TCard4& c4MsgIndex
, TVector<TString>& colMsgs
, const tCIDLib::TBoolean bAddNewLines)
{
#pragma warning(suppress : 26494)
tCIDLib::TBoolean retVal;
TCmdQItem* pcqiToUse = pcqiGetCmdItem(ooidThis().oidKey());
TOrbCmd& ocmdToUse = pcqiToUse->ocmdData();
try
{
ocmdToUse.strmOut() << TString(L"bQueryNewMsgs");
ocmdToUse.strmOut() << c4MsgIndex;
ocmdToUse.strmOut() << bAddNewLines;
Dispatch(10000, pcqiToUse);
ocmdToUse.strmIn().Reset();
ocmdToUse.strmIn() >> retVal;
if (retVal)
{
ocmdToUse.strmIn() >> c4MsgIndex;
ocmdToUse.strmIn() >> colMsgs;
}
GiveBackCmdItem(pcqiToUse);
}
catch(TError& errToCatch)
{
GiveBackCmdItem(pcqiToUse);
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}
return retVal;
}
tCIDLib::TCard4 TCQCAppShellAdminClientProxy::c4QueryApps
(
COP TVector<TKeyValuePair>& colApps)
{
#pragma warning(suppress : 26494)
tCIDLib::TCard4 retVal;
TCmdQItem* pcqiToUse = pcqiGetCmdItem(ooidThis().oidKey());
TOrbCmd& ocmdToUse = pcqiToUse->ocmdData();
try
{
ocmdToUse.strmOut() << TString(L"c4QueryApps");
Dispatch(30000, pcqiToUse);
ocmdToUse.strmIn().Reset();
ocmdToUse.strmIn() >> retVal;
ocmdToUse.strmIn() >> colApps;
GiveBackCmdItem(pcqiToUse);
}
catch(TError& errToCatch)
{
GiveBackCmdItem(pcqiToUse);
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}
return retVal;
}
tCIDLib::TVoid TCQCAppShellAdminClientProxy::CycleApps()
{
TCmdQItem* pcqiToUse = pcqiGetCmdItem(ooidThis().oidKey());
TOrbCmd& ocmdToUse = pcqiToUse->ocmdData();
try
{
ocmdToUse.strmOut() << TString(L"CycleApps");
Dispatch(60000, pcqiToUse);
ocmdToUse.strmIn().Reset();
GiveBackCmdItem(pcqiToUse);
}
catch(TError& errToCatch)
{
GiveBackCmdItem(pcqiToUse);
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
throw;
}
}
|
dexterchan/beam
|
sdks/python/apache_beam/runners/dataflow/ptransform_overrides.py
|
<filename>sdks/python/apache_beam/runners/dataflow/ptransform_overrides.py
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Ptransform overrides for DataflowRunner."""
from __future__ import absolute_import
from apache_beam.pipeline import PTransformOverride
class CreatePTransformOverride(PTransformOverride):
"""A ``PTransformOverride`` for ``Create`` in streaming mode."""
def matches(self, applied_ptransform):
# Imported here to avoid circular dependencies.
# pylint: disable=wrong-import-order, wrong-import-position
from apache_beam import Create
from apache_beam.runners.dataflow.internal import apiclient
if isinstance(applied_ptransform.transform, Create):
return not apiclient._use_fnapi(
applied_ptransform.outputs[None].pipeline._options)
else:
return False
def get_replacement_transform(self, ptransform):
# Imported here to avoid circular dependencies.
# pylint: disable=wrong-import-order, wrong-import-position
from apache_beam import PTransform
# Return a wrapper rather than ptransform.as_read() directly to
# ensure backwards compatibility of the pipeline structure.
class LegacyCreate(PTransform):
def expand(self, pbegin):
return pbegin | ptransform.as_read()
return LegacyCreate().with_output_types(ptransform.get_output_type())
class ReadPTransformOverride(PTransformOverride):
"""A ``PTransformOverride`` for ``Read(BoundedSource)``"""
def matches(self, applied_ptransform):
from apache_beam.io import Read
from apache_beam.io.iobase import BoundedSource
# Only overrides Read(BoundedSource) transform
if (isinstance(applied_ptransform.transform, Read)
and not getattr(applied_ptransform.transform, 'override', False)):
if isinstance(applied_ptransform.transform.source, BoundedSource):
return True
return False
def get_replacement_transform(self, ptransform):
from apache_beam import pvalue
from apache_beam.io import iobase
class Read(iobase.Read):
override = True
def expand(self, pbegin):
return pvalue.PCollection(
self.pipeline, is_bounded=self.source.is_bounded())
return Read(ptransform.source).with_output_types(
ptransform.get_type_hints().simple_output_type('Read'))
class JrhReadPTransformOverride(PTransformOverride):
"""A ``PTransformOverride`` for ``Read(BoundedSource)``"""
def matches(self, applied_ptransform):
from apache_beam.io import Read
from apache_beam.io.iobase import BoundedSource
return (isinstance(applied_ptransform.transform, Read)
and isinstance(applied_ptransform.transform.source, BoundedSource))
def get_replacement_transform(self, ptransform):
from apache_beam.io import Read
from apache_beam.transforms import core
from apache_beam.transforms import util
# Make this a local to narrow what's captured in the closure.
source = ptransform.source
class JrhRead(core.PTransform):
def expand(self, pbegin):
return (
pbegin
| core.Impulse()
| 'Split' >> core.FlatMap(lambda _: source.split(
Read.get_desired_chunk_size(source.estimate_size())))
| util.Reshuffle()
| 'ReadSplits' >> core.FlatMap(lambda split: split.source.read(
split.source.get_range_tracker(
split.start_position, split.stop_position))))
return JrhRead().with_output_types(
ptransform.get_type_hints().simple_output_type('Read'))
|
npocmaka/Windows-Server-2003
|
sdktools/gutils/status.c
|
<gh_stars>10-100
/*
* status line handler
*
*/
/*---includes-----------------------------------------------------------*/
#include "windows.h"
#include "string.h"
#include "gutils.h"
/* --- data structures ------------------------------------------------- */
#define SF_MAXLABEL 80 /* no more than 80 in an item within the bar */
/* Is this adequate for long pathnames on a
hi-res screen?
*/
typedef struct statel {
int type; /* SF_BUTTON or SF_STATIC */
int flags; /* SF_VAR => variable width
SF_LEFT=> left aligned (else right)
SF_RAISE=> paint as 'raised' 3d rect
SF_LOWER=> paint as lowered 3D rect
SF_SZMIN=>together with SF_VAR
allows minimum size for
var sized item
SF_SZMAX=>see SZMIN and use nouse
*/
int id; /* control id */
int width; /* width of control in chars */
char text[SF_MAXLABEL+1]; /* null-term string for label */
RECT rc; /* used by status.c */
} STATEL, * PSTATEL;
typedef struct itemlist {
int nitems;
PSTATEL statels;
int selitem; /* used by status.c */
BOOL isselected; /* used by status.c */
} ILIST, * PILIST;
/* ------------------------------------------------------------------*/
/* prototypes of routines in this module */
void StatusCreateTools(void);
void StatusDeleteTools(void);
INT_PTR APIENTRY StatusWndProc(HWND, UINT, WPARAM, LPARAM);
void StatusResize(HWND hWnd, PILIST pilist);
int StatusCalcHeight(HWND hWnd, PSTATEL ip);
int StatusCalcWidth(HWND hWnd, PSTATEL ip);
PSTATEL StatusGetItem(PILIST plist, int id);
void LowerRect(HDC hDC, LPRECT rcp);
void RaiseRect(HDC hDC, LPRECT rcp);
void StatusPaint(HWND hWnd, PILIST iplistp);
void BottomRight(HDC hDC, LPRECT rcp, HPEN hpen, BOOL bCorners);
void TopLeft(HDC hDC, LPRECT rcp, HPEN hpen, BOOL bCorners);
void StatusButtonDown(HDC hDC, PSTATEL ip);
void StatusButtonUp(HDC hDC, PSTATEL ip);
void InitDC(HDC hdc);
/*--global data---------------------------------------------------------*/
HPEN hpenHilight, hpenLowlight;
HPEN hpenBlack, hpenNeutral;
HBRUSH hbrBackground; /* pieces and board */
HFONT hFont;
int status_charheight, status_charwidth;
/* default pt size for font (tenths of a pt) */
#define DEF_PTSIZE 80
/*-public functions----------------------------------------------------------*/
/* StatusInit
*
* - create window class
*/
BOOL
StatusInit(
HANDLE hInstance
)
{
WNDCLASS wc;
BOOL resp;
TEXTMETRIC tm = {0};
HDC hDC;
StatusCreateTools();
wc.style = CS_HREDRAW|CS_VREDRAW|CS_GLOBALCLASS;
wc.lpfnWndProc = StatusWndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = sizeof(HANDLE);
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = hbrBackground;
wc.lpszClassName = (LPSTR) "gdstatusclass";
wc.lpszMenuName = NULL;
resp = RegisterClass(&wc);
hDC = GetDC(NULL);
if (hDC)
{
InitDC(hDC);
GetTextMetrics(hDC, &tm);
ReleaseDC(NULL, hDC);
}
else
{
// arbitrary, whatever...
tm.tmHeight = 14;
tm.tmAveCharWidth = 5;
}
status_charheight = (int)(tm.tmHeight + tm.tmExternalLeading);
status_charwidth = (int)tm.tmAveCharWidth;
return(resp);
}
/*
* create and show the window
*/
HWND APIENTRY
StatusCreate(
HANDLE hInst,
HWND hParent,
INT_PTR id,
LPRECT rcp,
HANDLE hmem
)
{
HWND hWnd;
/* create a child window of status class */
hWnd = CreateWindow("gdstatusclass",
NULL,
WS_CHILD | WS_VISIBLE,
rcp->left,
rcp->top,
(rcp->right - rcp->left),
(rcp->bottom - rcp->top),
hParent,
(HANDLE) id,
hInst,
(LPVOID) hmem);
return(hWnd);
}
/* return default height of this window */
int APIENTRY
StatusHeight(
HANDLE hmem
)
/* The window has a number of items which are arranged horizontally,
so the window height is the maximum of the individual heights
*/
{
PILIST plist;
int i;
int sz;
int maxsize = 0;
plist = (PILIST) GlobalLock(hmem);
if (plist != NULL) {
for (i = 0; i<plist->nitems; i++) {
sz = StatusCalcHeight(NULL, &plist->statels[i]);
maxsize = max(sz, maxsize);
}
}
GlobalUnlock(hmem);
if (maxsize > 0) {
return(maxsize + 4);
} else {
return(status_charheight + 4);
}
}
/* alloc the plist struct and return handle to caller */
HANDLE
StatusAlloc(
int nitems
)
{
HANDLE hmem;
PILIST pilist;
LPSTR chp;
hmem = GlobalAlloc(GMEM_MOVEABLE|GMEM_ZEROINIT,
sizeof(ILIST) + (sizeof(STATEL) * nitems));
chp = GlobalLock(hmem);
if (chp == NULL) {
return(NULL);
}
pilist = (PILIST) chp;
pilist->nitems = nitems;
pilist->statels = (PSTATEL) &chp[sizeof(ILIST)];
GlobalUnlock(hmem);
return(hmem);
}
/* insert an item into the plist */
BOOL
StatusAddItem(
HANDLE hmem,
int itemnr,
int type,
int flags,
int id,
int width,
LPSTR text
)
{
PILIST pilist;
PSTATEL pel;
pilist = (PILIST) GlobalLock(hmem);
if ((pilist == NULL) || (itemnr >= pilist->nitems)) {
GlobalUnlock(hmem);
return(FALSE);
}
pel = &pilist->statels[itemnr];
pel->type = type;
pel->flags = flags;
pel->id = id;
pel->width = width;
if (text == NULL) {
pel->text[0] = '\0';
} else {
lstrcpy(pel->text, text);
}
GlobalUnlock(hmem);
return(TRUE);
}
/* ---- internal functions ------------------------------------------*/
void
InitDC(HDC hdc)
{
SetBkColor(hdc, RGB(192,192,192));
SelectObject(hdc, hbrBackground);
SelectObject(hdc, hFont);
}
void
StatusCreateTools()
{
LOGFONT lf;
HDC hdc;
int scale;
hbrBackground = CreateSolidBrush(RGB(192,192,192));
hpenHilight = CreatePen(0, 1, RGB(255, 255, 255));
hpenLowlight = CreatePen(0, 1, RGB(128, 128, 128));
hpenNeutral = CreatePen(0, 1, RGB(192, 192, 192));
hpenBlack = CreatePen(0, 1, RGB(0, 0, 0));
hdc = GetDC(NULL);
if (hdc)
{
scale = GetDeviceCaps(hdc, LOGPIXELSY);
ReleaseDC(NULL, hdc);
}
else
{
// arbitrary, whatever...
scale = 72;
}
lf.lfHeight = -MulDiv(DEF_PTSIZE, scale, 720);
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_REGULAR;
lf.lfItalic = 0;
lf.lfUnderline = 0;
lf.lfStrikeOut = 0;
lf.lfCharSet = ANSI_CHARSET;
lf.lfOutPrecision = OUT_DEFAULT_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = PROOF_QUALITY;
lf.lfPitchAndFamily = VARIABLE_PITCH | FF_SWISS;
lf.lfFaceName[0] = '\0';
#ifdef COMPLEX
hFont = CreateFontIndirect(&lf);
#else
hFont = GetStockObject(SYSTEM_FONT);
#endif
}
void
StatusDeleteTools()
{
DeleteObject(hbrBackground);
DeleteObject(hpenHilight);
DeleteObject(hpenLowlight);
DeleteObject(hpenBlack);
DeleteObject(hpenNeutral);
#ifdef COMPLEX
DeleteObject(hFont);
#endif
}
/* Main winproc for status windows
*
* handles create/destroy and paint requests
*/
INT_PTR
StatusWndProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam
)
{
HANDLE hitems;
PSTATEL ip;
PILIST plist;
CREATESTRUCT * cp;
int i;
HDC hDC;
RECT rc;
POINT pt;
switch (message) {
case WM_CREATE:
cp = (CREATESTRUCT *) lParam;
hitems = (HANDLE) cp->lpCreateParams;
SetWindowLongPtr(hWnd, 0, (LONG_PTR)hitems);
plist = (PILIST) GlobalLock(hitems);
if (plist != NULL) {
plist->selitem = -1;
GlobalUnlock(hitems);
}
break;
case WM_SIZE:
hitems = (HANDLE) GetWindowLongPtr(hWnd, 0);
plist = (PILIST) GlobalLock(hitems);
if (plist != NULL) {
StatusResize(hWnd, plist);
GlobalUnlock(hitems);
}
break;
case WM_PAINT:
hitems = (HANDLE) GetWindowLongPtr(hWnd, 0);
plist = (PILIST) GlobalLock(hitems);
StatusPaint(hWnd, plist);
GlobalUnlock(hitems);
break;
case WM_LBUTTONUP:
hitems = (HANDLE) GetWindowLongPtr(hWnd, 0);
plist = (PILIST) GlobalLock(hitems);
pt.x = LOWORD(lParam);
pt.y = HIWORD(lParam);
if (plist == NULL) {
break;
}
if (plist->selitem != -1) {
ip = &plist->statels[plist->selitem];
if (plist->isselected) {
hDC = GetDC(hWnd);
if (hDC)
{
InitDC(hDC);
StatusButtonUp(hDC, ip);
ReleaseDC(hWnd, hDC);
}
}
plist->selitem = -1;
ReleaseCapture();
if (PtInRect(&ip->rc, pt)) {
SendMessage(GetParent(hWnd), WM_COMMAND, MAKELONG(ip->id, WM_LBUTTONUP), (LPARAM)hWnd);
}
}
GlobalUnlock(hitems);
break;
case WM_LBUTTONDOWN:
hitems = (HANDLE) GetWindowLongPtr(hWnd, 0);
plist = (PILIST) GlobalLock(hitems);
if (plist == NULL) {
break;
}
pt.x = LOWORD(lParam);
pt.y = HIWORD(lParam);
if (plist->selitem == -1) {
for (i = 0; i< plist->nitems; i++) {
ip = &plist->statels[i];
if (PtInRect(&ip->rc, pt)) {
if (ip->type != SF_BUTTON) {
break;
}
plist->selitem = i;
SetCapture(hWnd);
plist->isselected = TRUE;
hDC = GetDC(hWnd);
if (hDC)
{
InitDC(hDC);
StatusButtonDown(hDC, ip);
ReleaseDC(hWnd, hDC);
}
break;
}
}
}
GlobalUnlock(hitems);
break;
case WM_MOUSEMOVE:
hitems = (HANDLE) GetWindowLongPtr(hWnd, 0);
plist = (PILIST) GlobalLock(hitems);
if (plist == NULL) {
break;
}
pt.x = LOWORD(lParam);
pt.y = HIWORD(lParam);
if (plist->selitem != -1) {
ip = &plist->statels[plist->selitem];
if (PtInRect(&ip->rc, pt)) {
if (!plist->isselected) {
hDC = GetDC(hWnd);
if (hDC)
{
InitDC(hDC);
StatusButtonDown(hDC, ip);
ReleaseDC(hWnd, hDC);
}
plist->isselected = TRUE;
}
} else {
if (plist->isselected) {
hDC = GetDC(hWnd);
if (hDC)
{
InitDC(hDC);
StatusButtonUp(hDC, ip);
ReleaseDC(hWnd, hDC);
}
plist->isselected = FALSE;
}
}
}
GlobalUnlock(hitems);
break;
case WM_DESTROY:
hitems = (HANDLE) GetWindowLongPtr(hWnd, 0);
GlobalUnlock(hitems);
GlobalFree(hitems);
SetWindowLongPtr(hWnd, 0, 0);
break;
case SM_NEW:
hitems = (HANDLE) GetWindowLongPtr(hWnd, 0);
if (hitems != NULL) {
GlobalFree(hitems);
}
hitems = (HANDLE) wParam;
if (hitems == NULL) {
SetWindowLongPtr(hWnd, 0, 0);
InvalidateRect(hWnd, NULL, TRUE);
break;
}
plist = (PILIST) GlobalLock(hitems);
if (plist == NULL) {
SetWindowLongPtr(hWnd, 0, 0);
InvalidateRect(hWnd, NULL, TRUE);
break;
}
plist->selitem = -1;
StatusResize(hWnd, plist);
GlobalUnlock(hitems);
SetWindowLongPtr(hWnd, 0, (LONG_PTR)hitems);
InvalidateRect(hWnd, NULL, TRUE);
break;
case SM_SETTEXT:
hitems = (HANDLE) GetWindowLongPtr(hWnd, 0);
if (hitems == NULL) {
break;
}
plist = (PILIST) GlobalLock(hitems);
ip = StatusGetItem(plist, (int)wParam);
if (ip != NULL) {
if (lParam == 0) {
ip->text[0] = '\0';
} else {
My_mbsncpy(ip->text, (LPSTR) lParam, SF_MAXLABEL);
ip->text[SF_MAXLABEL] = '\0';
}
/* if this is a variable width field, we need to redo
* all size calcs in case the field width has changed.
* in that case, we need to repaint the entire window
* and not just this field - so set rc to indicate the
* area to be redrawn.
*/
if (ip->flags & SF_VAR) {
StatusResize(hWnd, plist);
GetClientRect(hWnd, &rc);
RedrawWindow(hWnd, &rc, NULL,
RDW_INVALIDATE|RDW_ERASE|RDW_UPDATENOW);
} else {
/* instead of just invalidating the window, we can
* force the window to be repainted now. This is
* essential for status updates during a busy
* loop when no messages are being processed,
* but we should still update the user on what's
* happening.
*/
RedrawWindow(hWnd, &ip->rc, NULL,
RDW_INVALIDATE|RDW_NOERASE|RDW_UPDATENOW);
}
}
GlobalUnlock(hitems);
break;
default:
return(DefWindowProc(hWnd, message, wParam, lParam));
}
return 0;
}
/*
* position the labels and buttons within the status window */
void
StatusResize(HWND hWnd, PILIST iplistp)
{
RECT rc;
int curpos_right, curpos_left;
int height, width;
int i;
PSTATEL ip;
if (iplistp == NULL) {
return;
}
GetClientRect(hWnd, &rc);
curpos_left = rc.left + status_charwidth / 2;
curpos_right = rc.right - (status_charwidth / 2);
/* loop through all items setting their position rects.
* items are flagged as being left or right. We place them
* in order starting at the left and the right, with a single
* char's width between each item
*/
for (i = 0; i < iplistp->nitems; i++) {
ip = &iplistp->statels[i];
width = StatusCalcWidth(hWnd, ip);
height = StatusCalcHeight(hWnd, ip);
ip->rc.top = (rc.bottom - height) / 2;
ip->rc.bottom = ip->rc.top + height;
/* see if this item fits. Items that partially fit
* are placed reduced in size.
*/
if (ip->flags & SF_LEFT) {
if (curpos_left+width >= curpos_right) {
/* doesn't completely fit-does it partly? */
if ((curpos_left + 1) >= curpos_right) {
/* no - this item does not fit */
ip->rc.left = 0;
ip->rc.right = 0;
} else {
/* partial fit */
ip->rc.left = curpos_left;
ip->rc.right = curpos_right - 1;
curpos_left = curpos_right;
}
} else {
/* complete fit */
ip->rc.left = curpos_left;
ip->rc.right = curpos_left + width;
curpos_left += width + 1;
}
} else {
/* same size check for right-aligned items */
if (curpos_right-width <= curpos_left) {
/* partial fit ? */
if (curpos_right <= curpos_left+1) {
ip->rc.left = 0;
ip->rc.right = 0;
} else {
/* yes - partial fit */
ip->rc.left = curpos_left + 1;
ip->rc.right = curpos_right;
curpos_right = curpos_left;
}
} else {
/* complete fit */
ip->rc.right = curpos_right;
ip->rc.left = curpos_right - width;
curpos_right -= (width + 1);
}
}
}
}
void
StatusPaint(HWND hWnd, PILIST iplistp)
{
RECT rc;
HDC hDC;
PAINTSTRUCT ps;
int i;
PSTATEL ip;
HPEN hpenOld;
GetClientRect(hWnd, &rc);
hDC = BeginPaint(hWnd, &ps);
InitDC(hDC);
RaiseRect(hDC, &rc);
if (iplistp == NULL) {
EndPaint(hWnd, &ps);
return;
}
for (i =0; i < iplistp->nitems; i++) {
ip = &iplistp->statels[i];
if (ip->rc.left == ip->rc.right) {
continue;
}
if (ip->type == SF_STATIC) {
if (ip->flags & SF_RAISE) {
RaiseRect(hDC, &ip->rc);
} else if (ip->flags & SF_LOWER) {
LowerRect(hDC, &ip->rc);
}
rc = ip->rc;
rc.left += (status_charwidth / 2);
rc.right--;
rc.top++;
rc.bottom--;
hpenOld = SelectObject(hDC, hpenNeutral);
Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom);
SelectObject(hDC, hpenOld);
DrawText(hDC, ip->text, lstrlen(ip->text), &rc,
DT_LEFT | DT_VCENTER);
} else {
StatusButtonUp(hDC, ip);
}
}
EndPaint(hWnd, &ps);
}
void
RaiseRect(HDC hDC, LPRECT rcp)
{
TopLeft(hDC, rcp, hpenHilight, FALSE);
BottomRight(hDC, rcp, hpenLowlight, FALSE);
}
void
LowerRect(HDC hDC, LPRECT rcp)
{
TopLeft(hDC, rcp, hpenLowlight, FALSE);
BottomRight(hDC, rcp, hpenHilight, FALSE);
}
void
StatusButtonUp(HDC hDC, PSTATEL ip)
{
RECT rc;
HPEN hpenOld;
TEXTMETRIC tm;
rc = ip->rc;
TopLeft(hDC, &rc, hpenBlack, TRUE);
BottomRight(hDC, &rc, hpenBlack, FALSE);
rc.top++;
rc.bottom--;
rc.left++;
rc.right--;
TopLeft(hDC, &rc, hpenHilight, FALSE);
BottomRight(hDC, &rc, hpenLowlight, TRUE);
rc.top++;
rc.bottom--;
rc.left++;
rc.right--;
BottomRight(hDC, &rc, hpenLowlight, TRUE);
rc.bottom--;
rc.right--;
hpenOld = SelectObject(hDC, hpenNeutral);
Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom);
SelectObject(hDC, hpenOld);
GetTextMetrics(hDC, &tm);
rc.top += tm.tmExternalLeading;
DrawText(hDC, ip->text, lstrlen(ip->text), &rc, DT_CENTER | DT_VCENTER);
}
void
StatusButtonDown(HDC hDC, PSTATEL ip)
{
RECT rc;
HPEN hpenOld;
TEXTMETRIC tm;
rc = ip->rc;
TopLeft(hDC, &rc, hpenBlack, TRUE);
BottomRight(hDC, &rc, hpenBlack, FALSE);
rc.top++;
rc.bottom--;
rc.left++;
rc.right--;
TopLeft(hDC, &rc, hpenLowlight, TRUE);
rc.top++;
rc.left++;
TopLeft(hDC, &rc, hpenNeutral, TRUE);
rc.top++;
rc.left++;
TopLeft(hDC, &rc, hpenNeutral, TRUE);
rc.top++;
rc.left++;
hpenOld = SelectObject(hDC, hpenNeutral);
Rectangle(hDC, rc.left, rc.top, rc.right, rc.bottom);
SelectObject(hDC, hpenOld);
GetTextMetrics(hDC, &tm);
rc.top += tm.tmExternalLeading;
DrawText(hDC, ip->text, lstrlen(ip->text), &rc, DT_CENTER | DT_VCENTER);
}
void
TopLeft(HDC hDC, LPRECT rcp, HPEN hpen, BOOL bCorners)
{
HPEN hpenOld;
int x, y;
hpenOld = SelectObject(hDC, hpen);
x = rcp->right - 1;
y = rcp->bottom;
if (!bCorners) {
x--;
y--;
}
MoveToEx(hDC, x, rcp->top, NULL);
LineTo(hDC, rcp->left, rcp->top);
LineTo(hDC, rcp->left, y);
SelectObject(hDC, hpenOld);
}
void
BottomRight(HDC hDC, LPRECT rcp, HPEN hpen, BOOL bCorners)
{
HPEN hpenOld;
int x, y;
hpenOld = SelectObject(hDC, hpen);
x = rcp->left - 1;
y = rcp->top;
if (!bCorners) {
x++;
y++;
}
MoveToEx(hDC, rcp->right-1, y, NULL);
LineTo(hDC, rcp->right-1, rcp->bottom-1);
LineTo(hDC, x, rcp->bottom-1);
SelectObject(hDC, hpenOld);
}
PSTATEL
StatusGetItem(PILIST plist, int id)
{
int i;
if (plist == NULL) {
return(NULL);
}
for (i = 0; i < plist->nitems; i++) {
if (plist->statels[i].id == id) {
return(&plist->statels[i]);
}
}
return(NULL);
}
/*
* calculate the width of a given field. This is the width in characters
* multiplied by the average character width, plus a few units for
* borders.
*
* if SF_VAR is set, this field size varies depending on the text, so
* we use GetTextExtent for the field size. If SF_VAR is selected, the caller
* can specify that the size is not to exceed the (width * avecharwidth)
* size (using SF_SZMAX) or that it is not be less than it (SF_SZMIN).
*/
int
StatusCalcWidth(HWND hWnd, PSTATEL ip)
{
int ch_size, t_size;
SIZE sz = {0};
HDC hDC;
ch_size = ip->width * status_charwidth;
if (ip->flags & SF_VAR) {
hDC = GetDC(hWnd);
if (hDC)
{
InitDC(hDC);
GetTextExtentPoint(hDC, ip->text, lstrlen(ip->text), &sz);
ReleaseDC(hWnd, hDC);
}
t_size = sz.cx;
/*
* check this size against min/max size if
* requested
*/
if (ip->flags & SF_SZMIN) {
if (ch_size > t_size) {
t_size = ch_size;
}
}
if (ip->flags & SF_SZMAX) {
if (ch_size < t_size) {
t_size = ch_size;
}
}
ch_size = t_size;
}
if (ch_size != 0) {
if (ip->type == SF_BUTTON) {
return(ch_size+6);
} else {
return(ch_size+4);
}
} else {
return(0);
}
}
int
StatusCalcHeight(HWND hWnd, PSTATEL ip)
{
int size;
size = status_charheight;
if (ip->type == SF_BUTTON) {
return(size + 6);
} else {
return(size + 2);
}
}
|
Teino1978-Corp/Teino1978-Corp-helix
|
helix-core/src/main/java/org/apache/helix/controller/serializer/DefaultStringSerializer.java
|
package org.apache.helix.controller.serializer;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import org.apache.helix.HelixException;
import org.apache.log4j.Logger;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Default serializer implementation for converting to/from strings. Uses the Jackson JSON library
* to do the conversion
*/
public class DefaultStringSerializer implements StringSerializer {
private static Logger logger = Logger.getLogger(DefaultStringSerializer.class);
@Override
public <T> String serialize(final T data) {
if (data == null) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
SerializationConfig serializationConfig = mapper.getSerializationConfig();
serializationConfig.set(SerializationConfig.Feature.INDENT_OUTPUT, true);
serializationConfig.set(SerializationConfig.Feature.AUTO_DETECT_FIELDS, true);
serializationConfig.set(SerializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
StringWriter sw = new StringWriter();
try {
mapper.writeValue(sw, data);
} catch (Exception e) {
logger.error("Exception during payload data serialization.", e);
throw new HelixException(e);
}
return sw.toString();
}
@Override
public <T> T deserialize(final Class<T> clazz, final String string) {
if (string == null || string.length() == 0) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
ByteArrayInputStream bais = new ByteArrayInputStream(string.getBytes());
DeserializationConfig deserializationConfig = mapper.getDeserializationConfig();
deserializationConfig.set(DeserializationConfig.Feature.AUTO_DETECT_FIELDS, true);
deserializationConfig.set(DeserializationConfig.Feature.AUTO_DETECT_SETTERS, true);
deserializationConfig.set(DeserializationConfig.Feature.AUTO_DETECT_CREATORS, true);
deserializationConfig.set(DeserializationConfig.Feature.CAN_OVERRIDE_ACCESS_MODIFIERS, true);
try {
T payload = mapper.readValue(bais, clazz);
return payload;
} catch (Exception e) {
logger.error("Exception during deserialization of payload bytes: " + string, e);
return null;
}
}
}
|
SupriyaPandarge/com-cg-java-demo
|
src/com/cg/demo/ex/UserDefinedException2.java
|
package com.cg.demo.ex;
class InvalidData extends Exception{
public InvalidData(String s) {
super(s);
}
}
public class UserDefinedException2 {
public static void main(String[] args) {
int i,j;
i=8;
j=9;
try {
int k = i/j;
if(k==0)
throw new InvalidData("Input data is invalid");
System.out.println(k);
}
catch(InvalidData e) {
System.out.println("Error " + e.getMessage());
}
}
}
|
Brian-Acosta/dairlib
|
systems/controllers/linear_controller.cc
|
<reponame>Brian-Acosta/dairlib<gh_stars>10-100
#include "systems/controllers/linear_controller.h"
namespace dairlib {
namespace systems {
LinearController::LinearController(int num_positions, int num_velocities,
int num_inputs) {
output_input_port_ =
this->DeclareVectorInputPort(
"x, u, t",
OutputVector<double>(num_positions, num_velocities, num_inputs))
.get_index();
config_input_port_ =
this->DeclareVectorInputPort(
"K, x_des, t", LinearConfig(num_positions + num_velocities, num_inputs))
.get_index();
this->DeclareVectorOutputPort("u", TimestampedVector<double>(num_inputs),
&LinearController::CalcControl);
}
void LinearController::CalcControl(const Context<double>& context,
TimestampedVector<double>* control) const {
const OutputVector<double>* output =
(OutputVector<double>*)this->EvalVectorInput(context, output_input_port_);
const auto* config = dynamic_cast<const LinearConfig*>(
this->EvalVectorInput(context, config_input_port_));
VectorXd x_tilde = config->GetDesiredState() - output->GetState();
for (int i = 0; i < x_tilde.size(); ++i) {
if (x_tilde[i] > kMaxError) {
x_tilde[i] = kMaxError;
} else if (x_tilde[i] < -kMaxError) {
x_tilde[i] = -kMaxError;
}
}
VectorXd u = config->GetK() * (x_tilde);
control->SetDataVector(u);
control->set_timestamp(output->get_timestamp());
}
} // namespace systems
} // namespace dairlib
|
nhs-digital-gp-it-futures/order-form
|
app/pages/sections/order-items/catalogue-solutions/delete/confirmation/controller.test.js
|
import { fakeSessionManager } from 'buying-catalogue-library';
import { getDeleteCatalogueSolutionConfirmationContext } from './controller';
import { logger } from '../../../../../../logger';
import * as contextCreator from './contextCreator';
jest.mock('./contextCreator', () => ({
getContext: jest.fn(),
}));
describe('Delete Catalogue Confirmation controller', () => {
afterEach(() => {
jest.resetAllMocks();
});
describe('getDeleteCatalogueSolutionConfirmationContext', () => {
it('should call getContext with the correct params', async () => {
const orderId = 'order-id';
const solutionName = 'catalogue-solution';
const accessToken = 'access-token';
await getDeleteCatalogueSolutionConfirmationContext({
req: { params: { orderId, solutionName } },
sessionManager: fakeSessionManager,
accessToken,
logger,
});
expect(contextCreator.getContext.mock.calls.length).toEqual(1);
expect(contextCreator.getContext).toHaveBeenCalledWith({ orderId, solutionName });
});
it('should return the expected result', async () => {
const expectedContext = { context: 'contextData' };
contextCreator.getContext.mockResolvedValueOnce(expectedContext);
const actualContext = await getDeleteCatalogueSolutionConfirmationContext({
req: { params: { orderId: 'order-id', solutionName: 'catalogue-solution' } },
sessionManager: fakeSessionManager,
accessToken: 'access-token',
logger,
});
expect(actualContext).toEqual(expectedContext);
});
});
});
|
xuanlv886/Android
|
HomeShoppingMall/HomeShoppingMallForMerchant/app/src/main/java/app/cn/extra/mall/merchant/vo/StoreLogin.java
|
package app.cn.extra.mall.merchant.vo;
/**
* Description
* Data 2018/7/11-15:10
* Content
*
* @author L
*/
public class StoreLogin {
/**
* errorString :
* flag : true
* data : {"acId":"37","uId":"194a0051-512e-4a75-b1f6-215e1661d242","sType":1,"errorString":"未通过审核!审核意见:3245435436","sId":"4833b19c-96be-4f2c-8579-a95b6b719efb","needVerification":"true","status":"false"}
*/
private String errorString;
private String flag;
private DataBean data;
public String getErrorString() {
return errorString;
}
public void setErrorString(String errorString) {
this.errorString = errorString;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* acId : 37
* uId : 194a0051-512e-4a75-b1f6-215e1661d242
* sType : 1
* errorString : 未通过审核!审核意见:3245435436
* sId : 4833b19c-96be-4f2c-8579-a95b6b719efb
* needVerification : true
* status : false
*/
private String acId;
private String uId;
private int sType;
private String errorString;
private String sId;
private String needVerification;
private String status;
private String sChecked;
private String token;
private String accid;
public String getAccid() {
return accid;
}
public void setAccid(String accid) {
this.accid = accid;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getsChecked() {
return sChecked;
}
public void setsChecked(String sChecked) {
this.sChecked = sChecked;
}
public String getAcId() {
return acId;
}
public void setAcId(String acId) {
this.acId = acId;
}
public String getUId() {
return uId;
}
public void setUId(String uId) {
this.uId = uId;
}
public int getSType() {
return sType;
}
public void setSType(int sType) {
this.sType = sType;
}
public String getErrorString() {
return errorString;
}
public void setErrorString(String errorString) {
this.errorString = errorString;
}
public String getSId() {
return sId;
}
public void setSId(String sId) {
this.sId = sId;
}
public String getNeedVerification() {
return needVerification;
}
public void setNeedVerification(String needVerification) {
this.needVerification = needVerification;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
}
|
luaks/vind
|
monitoring/monitoring-api/src/main/java/com/rbmhtechnology/vind/monitoring/model/session/SimpleSession.java
|
package com.rbmhtechnology.vind.monitoring.model.session;
/**
* @author <NAME> (<EMAIL>)
* @since 13.07.16.
*/
public class SimpleSession implements Session {
public String sessionId;
public SimpleSession(String sessionId) {
this.sessionId = sessionId;
}
@Override
public String getSessionId() {
return sessionId;
}
}
|
JetBrains/teamcity-nuget-support
|
nuget-tests/src/jetbrains/buildServer/nuget/tests/server/entity/MetadataParseResult.java
|
<filename>nuget-tests/src/jetbrains/buildServer/nuget/tests/server/entity/MetadataParseResult.java
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.nuget.tests.server.entity;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
/**
* Created by <NAME> (<EMAIL>)
* Date: 07.01.12 9:49
*/
public final class MetadataParseResult {
private final Collection<MetadataBeanProperty> myKey;
private final Collection<MetadataBeanProperty> myData;
public MetadataParseResult(@NotNull final Collection<MetadataBeanProperty> key,
@NotNull final Collection<MetadataBeanProperty> data) {
myKey = key;
myData = data;
}
@NotNull
public Collection<MetadataBeanProperty> getKey() {
return myKey;
}
@NotNull
public Collection<MetadataBeanProperty> getData() {
return myData;
}
}
|
zemlni/CellSociety
|
src/user_interface/ControlPanel.java
|
/**
*
*/
package user_interface;
import cellsociety_team18.Game;
import cellsociety_team18.Parameter;
import cellsociety_team18.Simulation;
import cellsociety_team18.XMLParser;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Separator;
import javafx.scene.control.Slider;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
/**
* @author elliott This class represents the Control Panel of the UI. This
* Control Panel is comprised of description labels, combo boxes, and
* action buttons.
*/
public class ControlPanel extends ScrollPane {
private final static int HORIZONTAL_SPACING = 8;
private final static int VERTICAL_SPACING = 16;
private ViewController viewController;
private Simulation myCurrentSimulation;
private ResourceBundle resources;
private String dataFolder = "data/";
private VBox panelElements;
private Text myDescription;
private Text myTitle;
private ComboBox<String> myGames;
private ComboBox<String> myConfigurations;
private Slider myDelaySlider;
private TextField myGridSizeField;
private ToggleButton myOutlineToggle;
private ComboBox<String> myGridEdges;
private ComboBox<String> myCells;
private ComboBox<String> myCellDistributions;
private TextField myNeighborsField;
private TextField myCellSizeField;
private Node myConfigurationControls;
private ParameterTable myParameterTable;
private boolean gameLoaded = false;
/**
* @param viewController
* The owner of the control panel.
* @param resources
* The ResourceBundle for the control panel.
* @param width
* The control panel's width.
* @return A control panel.
*/
public ControlPanel(ViewController viewController, ResourceBundle resources, int width) {
this.viewController = viewController;
this.resources = resources;
setWidth(width);
setHbarPolicy(ScrollBarPolicy.NEVER);
setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
setup();
}
private Game getGame() {
return myCurrentSimulation.getGame();
}
private void setup() {
panelElements = new VBox(VERTICAL_SPACING);
panelElements.setPadding(new Insets(20, 30, 20, 20));
setContent(panelElements);
panelElements.getChildren().addAll(getGameLabels(), getSimulationSelector(), getConfigurationSelector());
getChildren().addAll(panelElements, getDivider());
}
/**
* @return A divider for the grid and control panel.
*/
private Node getDivider() {
Group result = new Group();
Rectangle separator = new Rectangle(1, 500);
separator.setFill(Color.LIGHTGRAY);
result.getChildren().add(separator);
return result;
}
private void addControls() {
if (gameLoaded == false) {
myConfigurationControls = createConfigurationControls();
HBox box = new HBox(HORIZONTAL_SPACING);
box.getChildren().addAll(makeButton("LoadTitle", e -> loadGame()),
makeButton("SaveTitle", e -> saveConfiguration()));
Node controlButtons = setupControlButtons();
panelElements.getChildren().addAll(myConfigurationControls, makeSeparator(false), box, makeSeparator(false),
controlButtons, getDelaySlider());
gameLoaded = true;
}
}
/**
* @return The control panel's game labels.
*/
private Node getGameLabels() {
VBox result = new VBox(VERTICAL_SPACING);
myTitle = new Text(resources.getString("PlaceholderTitle"));
myTitle.setFont(Font.font("Helvetica", FontWeight.BOLD, 24));
myDescription = new Text(resources.getString("PlaceholderDescription"));
myDescription.setFont(Font.font("Helvetica", 16));
myDescription.setWrappingWidth(260);
myDescription.setTextAlignment(TextAlignment.JUSTIFY);
Separator separator = new Separator();
result.getChildren().addAll(myTitle, myDescription, separator);
return result;
}
/**
* @return The game combo box and its label.
*/
private Node getSimulationSelector() {
HBox result = new HBox(HORIZONTAL_SPACING);
myGames = new ComboBox<String>();
myGames.valueProperty().addListener(e -> newSimulation());
addOptionsFromDisk(myGames, false);
result.getChildren().addAll(addLabelToNode(myGames, "PickGameString"));
result.setAlignment(Pos.CENTER_LEFT);
return result;
}
/**
* @return The configuration combo box and its label.
*/
private Node getConfigurationSelector() {
HBox result = new HBox(HORIZONTAL_SPACING);
myConfigurations = new ComboBox<String>();
myConfigurations.valueProperty().addListener(e -> newSimulation());
addOptionsFromDisk(myConfigurations, true);
result.getChildren().addAll(addLabelToNode(myConfigurations, "PickConfigurationString"));
result.setAlignment(Pos.CENTER_LEFT);
return result;
}
private void addOptionsFromDisk(ComboBox<String> box, boolean configurationFiles) {
List<File> options = Arrays.asList(new File(dataFolder).listFiles());
Collections.sort(options);
for (File file : options) {
String name = file.getName();
if (XMLParser.isXMLFile(name)) {
if (configurationFiles && name.contains("Configuration")
|| !(configurationFiles || name.contains("Configuration"))) {
box.getItems().add(name.substring(0, name.length() - 4));
}
}
}
}
/**
* @return The control panel's buttons.
*/
private Node setupControlButtons() {
HBox result = new HBox(HORIZONTAL_SPACING);
Button start = makeButton("StartTitle", e -> viewController.start((int) myDelaySlider.getValue()));
Button stop = makeButton("StopTitle", e -> viewController.stop());
Button step = makeButton("StepTitle", e -> viewController.step());
Button reload = makeButton("ReloadTitle", e -> viewController.shuffleGrid());
result.getChildren().addAll(start, makeSeparator(true), stop, makeSeparator(true), step, makeSeparator(true),
reload);
return result;
}
private Button makeButton(String property, EventHandler<ActionEvent> handler) {
Button button = new Button(resources.getString(property));
button.setOnAction(handler);
return button;
}
private Node makeSeparator(boolean vertical) {
Separator separator = new Separator();
if (vertical) {
separator.setOrientation(Orientation.VERTICAL);
}
return separator;
}
/**
* @return The control panel's input fields.
*/
private Node createConfigurationControls() {
VBox result = new VBox(VERTICAL_SPACING);
HBox sizeBox = makeSizeBox();
HBox cellBox = new HBox(HORIZONTAL_SPACING);
myCells = createComboBox(new String[] { "Square", "Triangle", "Hexagon" },
myCurrentSimulation.getSettings().getParameter("cellType"));
cellBox.getChildren().addAll(addLabelToNode(myCells, "CellType"));
cellBox.setAlignment(Pos.CENTER_LEFT);
HBox edgeBox = makeEdgeBox();
HBox distributionBox = makeDistributionBox();
myNeighborsField = createField(myCurrentSimulation.getSettings().getParameter("numberOfNeighbors"));
myOutlineToggle = new ToggleButton(resources.getString("OutlineGrid"));
myOutlineToggle
.setSelected(Boolean.parseBoolean(myCurrentSimulation.getSettings().getParameter("outlineGrid")));
result.getChildren().addAll(sizeBox, myOutlineToggle, cellBox, edgeBox, distributionBox,
addLabelToNode(myNeighborsField, "NumberNeighbors"));
return result;
}
private HBox makeSizeBox() {
HBox sizeBox = new HBox(HORIZONTAL_SPACING);
myGridSizeField = createField(myCurrentSimulation.getSettings().getParameter("gridSize"));
myCellSizeField = createField(myCurrentSimulation.getSettings().getParameter("cellSize"));
sizeBox.getChildren().addAll(addLabelToNode(myGridSizeField, "GridSizeString"),
addLabelToNode(myCellSizeField, "CellSize"));
return sizeBox;
}
private HBox makeEdgeBox() {
HBox edgeBox = new HBox(HORIZONTAL_SPACING);
myGridEdges = new ComboBox<String>();
myGridEdges.getItems().addAll("Bounded", "Toroidal");
myGridEdges.setValue(myCurrentSimulation.getSettings().getParameter("gridEdge"));
edgeBox.getChildren().addAll(addLabelToNode(myGridEdges, "GridEdge"));
edgeBox.setAlignment(Pos.CENTER_LEFT);
return edgeBox;
}
private HBox makeDistributionBox() {
HBox distributionBox = new HBox(HORIZONTAL_SPACING);
myCellDistributions = new ComboBox<String>();
myCellDistributions.getItems().addAll("Probabilistic", "Random");
myCellDistributions.setValue(myCurrentSimulation.getSettings().getParameter("cellDistribution"));
distributionBox.getChildren().addAll(addLabelToNode(myCellDistributions, "CellDistribution"));
distributionBox.setAlignment(Pos.CENTER_LEFT);
return distributionBox;
}
private ComboBox<String> createComboBox(String[] values, String value) {
ComboBox<String> result = new ComboBox<String>();
result.getItems().addAll(values);
result.setValue(value);
return result;
}
private TextField createField(String value) {
TextField field = new TextField(value);
field.setPrefWidth(40);
return field;
}
private Node addLabelToNode(Node node, String property) {
HBox box = new HBox(HORIZONTAL_SPACING);
Label label = new Label(resources.getString(property));
box.getChildren().addAll(label, node);
box.setAlignment(Pos.CENTER_LEFT);
return box;
}
private ParameterTable createParameters() {
return new ParameterTable(getGame().getParametersAndValues());
}
private void setupParameters() {
panelElements.getChildren().remove(myParameterTable);
panelElements.getChildren().remove(myConfigurationControls);
myParameterTable = createParameters();
myConfigurationControls = createConfigurationControls();
panelElements.getChildren().add(3, myParameterTable);
panelElements.getChildren().add(4, myConfigurationControls);
}
private void newSimulation() {
if (myGames.getValue() != null && myConfigurations.getValue() != null) {
getSimulation();
myTitle.setText(getGame().getTitle());
myDescription.setText(getGame().getDescription());
addControls();
setupParameters();
}
}
private void loadGame() {
if (checkParameters()) {
updateParameters();
viewController.stop();
viewController.displaySimulation(myCurrentSimulation);
getSimulation();
}
}
private void getSimulation() {
myCurrentSimulation = viewController.newSimulation(myGames.getValue(), myConfigurations.getValue());
}
private void updateGameParameters() {
ObservableList<Parameter> data = myParameterTable.getData();
for (Parameter entry : data) {
getGame().getSettings().put(entry.getParameter(), entry.getValue());
}
}
private Node makeLabel(String property, int fontSize) {
Text label = new Text(resources.getString(property));
label.setFont(Font.font("Helvetica", fontSize));
return label;
}
private Node getDelaySlider() {
configureSlider();
VBox box = new VBox(0);
box.getChildren().addAll(myDelaySlider, makeLabel("DelayString", 14));
box.setAlignment(Pos.CENTER);
return box;
}
private void configureSlider() {
myDelaySlider = new Slider();
myDelaySlider.setMin(20);
myDelaySlider.setMax(1000);
myDelaySlider.setValue(myCurrentSimulation.getSettings().getIntParameter("delay"));
myDelaySlider.setShowTickLabels(true);
myDelaySlider.setShowTickMarks(false);
myDelaySlider.setMajorTickUnit(500);
myDelaySlider.setMinorTickCount(0);
myDelaySlider.setBlockIncrement(10);
}
private void updateParameters() {
updateGameParameters();
updateConfigurationParameters();
}
private void updateConfigurationParameters() {
myCurrentSimulation.getSettings().put("gridSize", myGridSizeField.getText());
myCurrentSimulation.getSettings().put("cellType", myCells.getValue());
myCurrentSimulation.getSettings().put("gridEdge", myGridEdges.getValue());
myCurrentSimulation.getSettings().put("cellDistribution", myCellDistributions.getValue());
myCurrentSimulation.getSettings().put("cellSize", myCellSizeField.getText());
myCurrentSimulation.getSettings().put("outlineGrid", String.valueOf(myOutlineToggle.isSelected()));
myCurrentSimulation.getSettings().put("numberOfNeighbors", myNeighborsField.getText());
}
private void saveConfiguration() {
if (checkParameters()) {
updateConfigurationParameters();
XMLParser.write(myCurrentSimulation.getSettings().getMap());
resetConfigurations();
}
}
private void resetConfigurations() {
String current = myConfigurations.getValue();
myConfigurations.getItems().removeAll(myConfigurations.getItems());
addOptionsFromDisk(myConfigurations, true);
myConfigurations.setValue(current);
}
private void showMessage() {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Error");
alert.setHeaderText("CellSociety encountered an error.");
alert.setContentText("One of your input values is incomplete or of the wrong type.");
alert.showAndWait();
}
private Boolean checkParameters() {
try {
Integer.parseInt(myGridSizeField.getText());
Integer.parseInt(myNeighborsField.getText());
Double.parseDouble(myCellSizeField.getText());
} catch (Exception e) {
showMessage();
return false;
}
return true;
}
}
|
KindDragon/all-repos
|
tests/autofix/azure_pipelines_autoupdate_test.py
|
from __future__ import annotations
import subprocess
from unittest import mock
import pytest
from all_repos import clone
from all_repos.autofix import azure_pipelines_autoupdate
from all_repos.config import load_config
from testing.auto_namedtuple import auto_namedtuple
from testing.git import init_repo
from testing.git import write_file_commit
@pytest.fixture
def fake_clone(tmpdir_factory):
src = tmpdir_factory.mktemp('repo')
init_repo(src)
write_file_commit(src, 'job--pre-commit.yml', 'jobs: []')
subprocess.check_call(('git', '-C', src, 'tag', 'v1.0.0'))
write_file_commit(src, 'README.md', '# template repo')
def clone_func(service, repo, path):
subprocess.check_call(('git', 'clone', src, path))
subprocess.check_call(('git', 'fetch', 'origin', 'HEAD'), cwd=path)
with mock.patch.object(azure_pipelines_autoupdate, '_clone', clone_func):
yield
SAMPLE = '''\
resources:
repositories:
- repository: self
checkoutOptions:
submodules: true
- repository: asottile
type: github
endpoint: github
# formatting comment
name: asottile/azure-pipeline-templates
ref: refs/tags/v0.0.1 # line comment
- repository: asottile
type: github
endpoint: github
name: asottile/azure-pipeline-templates
ref: refs/tags/v0.0.1
jobs:
- template: job--pre-commit.yml@asottile
'''
@pytest.fixture
def repo(tmpdir):
src_repo = tmpdir.join('hook_repo')
init_repo(src_repo)
write_file_commit(src_repo, 'azure-pipelines.yml', SAMPLE)
update_repo = tmpdir.join('update_repo')
subprocess.check_call(('git', 'clone', src_repo, update_repo))
return auto_namedtuple(src_repo=src_repo, update_repo=update_repo)
def test_clone(tmpdir):
repo = tmpdir.join('repo')
azure_pipelines_autoupdate._clone('github', 'asottile/astpretty', repo)
rev = subprocess.check_output(('git', 'rev-parse', 'v1.7.0'), cwd=repo)
assert rev.strip().decode() == '1bdab8a7e9c9591669e91de5c1c9584db7267ec6'
@pytest.mark.usefixtures('fake_clone')
def test_basic_rewrite(file_config, repo):
ret = azure_pipelines_autoupdate.main((
'--config-filename', str(file_config.cfg),
'--repos', str(repo.update_repo),
))
assert not ret
expected = '''\
resources:
repositories:
- repository: self
checkoutOptions:
submodules: true
- repository: asottile
type: github
endpoint: github
# formatting comment
name: asottile/azure-pipeline-templates
ref: refs/tags/v1.0.0 # line comment
- repository: asottile
type: github
endpoint: github
name: asottile/azure-pipeline-templates
ref: refs/tags/v1.0.0
jobs:
- template: job--pre-commit.yml@asottile
'''
assert repo.src_repo.join('azure-pipelines.yml').read() == expected
def test_find_repos_finds_a_repo(file_config_files):
write_file_commit(file_config_files.dir1, 'azure-pipelines.yml', SAMPLE)
clone.main(('--config-filename', str(file_config_files.cfg)))
config = load_config(str(file_config_files.cfg))
ret = azure_pipelines_autoupdate.find_repos(config)
assert ret == {str(file_config_files.output_dir.join('repo1'))}
|
robjporter/go-functions2
|
format/round/round.go
|
package round
import (
"math"
)
const Epsilon = 0.0000001
func Round(x float64) float64 {
return ToNearestEven(x)
}
func RoundTo(x float64, dp float64) float64 {
x = x * math.Pow(10, dp)
return ToNearestEven(x) / math.Pow(10, dp)
}
func ToNearestEven(x float64) float64 {
return toNearest(x, true)
}
func ToNearestAway(x float64) float64 {
return toNearest(x, false)
}
func ToZero(x float64) float64 {
return math.Trunc(x)
}
func AwayFromZero(x float64) float64 {
if x >= 0 {
return math.Ceil(x)
} else {
return math.Floor(x)
}
}
func ToPositiveInf(x float64) float64 {
return math.Ceil(x)
}
func ToNegativeInf(x float64) float64 {
return math.Floor(x)
}
func toNearest(x float64, tiesToEven bool) float64 {
if x == 0 || math.IsNaN(x) || math.IsInf(x, 0) {
return x
}
if x < 0.0 {
return -toNearest(-x, tiesToEven)
}
intPart, fracPart := math.Modf(x)
if math.Abs(fracPart-0.5) < Epsilon {
if tiesToEven {
if math.Mod(intPart, 2.0) < Epsilon {
return intPart
}
}
return math.Ceil(intPart + 0.5)
}
return math.Floor(x + 0.5)
}
|
V1Kin9/wh_sdk
|
software/uart_test/uart_test.c
|
/*******************************************************************
*
* PROJECT: W01
*
* FILENAME: uart_test.c
*
* FUNCTION: UART test demo
*
* AUTHOR: yexc
*
* DATE: 2018/01/30
*
* IS_FINISH: YES
*
********************************************************************/
/* Includes --------------------------------------------------------*/
#include "platform.h"
/* Private define --------------------------------------------------*/
/* Private macro ---------------------------------------------------*/
/* Private variables -----------------------------------------------*/
/* Extern variables ------------------------------------------------*/
/* Private function prototypes -------------------------------------*/
/* Private functions -----------------------------------------------*/
/********************************************************************
* Function Name : UART_IRQ_Handler
* Description : UART interrupt handler function
* Input : none
* Output : none
* Return : 0
********************************************************************/
void UART_IRQ_Handler(void)
{
uint8_t ch;
ch = uart_getchar();
UART_REG(UART_IS) &= ~UART_IS_FIFO_NE;
uart_putchar(ch);
}
/********************************************************************
* Function Name : main
* Description : main routine
* Input : none
* Output : none
* Return : 0
********************************************************************/
int main(void)
{
// initialize all interrupts
int_init();
// enable global interrupt
global_int_enable(1);
// set priority
global_int_priority(1, 2);
// bind handler function
global_int_bind_handler(1, UART_IRQ_Handler);
// enable global interrupts
set_csr(mie, MIE_MEIE);
// enable all interrupts
int_enable();
uart_init(115200);
uart_set_IE(UART_IE_FIFO_NE);
//uart_puts("Please input character...\r\n");
uart_putchar('a');
uart_puts("Please input character...\r\n");
while(1)
continue;
return 0;
}
|
kbore/pbis-open
|
lsass/server/include/lsasrvapi.h
|
/* Editor Settings: expandtabs and use 4 spaces for indentation
* ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
* -*- mode: c, c-basic-offset: 4 -*- */
/*
* Copyright © BeyondTrust Software 2004 - 2019
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
* WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
* BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
* SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
* NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
* A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
* BEYONDTRUST AT beyondtrust.com/contact
*/
/*
* Copyright (C) BeyondTrust Software. All rights reserved.
*
* Module Name:
*
* lsasrvapi.h
*
* Abstract:
*
* BeyondTrust Security and Authentication Subsystem (LSASS)
*
* Server API
*
* Authors: <NAME> (<EMAIL>)
* <NAME> (<EMAIL>)
*/
#ifndef __LSASRVAPI_H__
#define __LSASRVAPI_H__
#include <lsa/provider.h>
DWORD
LsaSrvApiInit(
PLSA_STATIC_PROVIDER pStaticProviders
);
DWORD
LsaSrvApiShutdown(
VOID
);
DWORD
LsaSrvOpenServer(
uid_t peerUID,
gid_t peerGID,
pid_t peerPID,
PHANDLE phServer
);
VOID
LsaSrvGetClientId(
HANDLE hServer,
uid_t* pUid,
gid_t* pGid,
pid_t* pPid
);
void
LsaSrvCloseServer(
HANDLE hServer
);
DWORD
LsaSrvAuthenticateUserPam(
HANDLE hServer,
PLSA_AUTH_USER_PAM_PARAMS pParams,
PLSA_AUTH_USER_PAM_INFO* ppPamAuthInfo
);
DWORD
LsaSrvAuthenticateUserEx(
HANDLE hServer,
PCSTR pszTargetProvider,
PLSA_AUTH_USER_PARAMS pUserParms,
PLSA_AUTH_USER_INFO *ppUserInfo
);
DWORD
LsaSrvValidateUser(
HANDLE hServer,
PCSTR pszLoginId,
PCSTR pszPassword
);
DWORD
LsaSrvCheckUserInList(
HANDLE hServer,
PCSTR pszLoginId,
PCSTR pszListName
);
DWORD
LsaSrvChangePassword(
HANDLE hServer,
PCSTR pszLoginId,
PCSTR pszPassword,
PCSTR pszOldPassword
);
DWORD
LsaSrvSetPassword(
HANDLE hServer,
PCSTR pszLoginId,
PCSTR pszPassword
);
DWORD
LsaSrvAddGroup2(
HANDLE hServer,
PCSTR pszTargetProvider,
PLSA_GROUP_ADD_INFO pGroupAddInfo
);
DWORD
LsaSrvModifyGroup2(
HANDLE hServer,
PCSTR pszTargetProvider,
PLSA_GROUP_MOD_INFO_2 pGroupModInfo
);
DWORD
LsaSrvDeleteObject(
HANDLE hServer,
PCSTR pszTargetProvider,
PCSTR pszSid
);
DWORD
LsaSrvAddUser2(
HANDLE hServer,
PCSTR pszTargetProvider,
PLSA_USER_ADD_INFO pUserAddInfo
);
DWORD
LsaSrvModifyUser2(
HANDLE hServer,
PCSTR pszTargetProvider,
PLSA_USER_MOD_INFO_2 pUserModInfo
);
DWORD
LsaSrvFindNSSArtefactByKey(
HANDLE hServer,
PCSTR pszKeyName,
PCSTR pszMapName,
LSA_NIS_MAP_QUERY_FLAGS dwFlags,
DWORD dwMapInfoLevel,
PVOID* ppNSSArtefactInfo
);
DWORD
LsaSrvBeginEnumNSSArtefacts(
HANDLE hServer,
PCSTR pszMapName,
LSA_NIS_MAP_QUERY_FLAGS dwFlags,
DWORD dwGroupInfoLevel,
DWORD dwNumMaxGroups,
PHANDLE phState
);
DWORD
LsaSrvEnumNSSArtefacts(
HANDLE hServer,
HANDLE hState,
PDWORD pdwGroupInfoLevel,
PVOID** pppGroupInfoList,
PDWORD pdwNumGroupsFound
);
DWORD
LsaSrvEndEnumNSSArtefacts(
HANDLE hServer,
HANDLE hState
);
DWORD
LsaSrvComputeLMHash(
PCSTR pszPassword,
PBYTE* ppszHash,
PDWORD pdwHashLen
);
DWORD
LsaSrvComputeNTHash(
PCSTR pszPassword,
PBYTE* ppszHash,
PDWORD pdwHashLen
);
DWORD
LsaSrvOpenSession(
HANDLE hServer,
PCSTR pszLoginId
);
DWORD
LsaSrvCloseSession(
HANDLE hServer,
PCSTR pszLoginId
);
DWORD
LsaSrvSetTraceFlags(
HANDLE hServer,
PLSA_TRACE_INFO pTraceFlagArray,
DWORD dwNumFlags
);
DWORD
LsaSrvGetTraceInfo(
HANDLE hServer,
DWORD dwTraceFlag,
PLSA_TRACE_INFO* ppTraceInfo
);
DWORD
LsaSrvEnumTraceFlags(
HANDLE hServer,
PLSA_TRACE_INFO* ppTraceFlagArray,
PDWORD pdwNumFlags
);
DWORD
LsaSrvGetMetrics(
HANDLE hServer,
DWORD dwInfoLevel,
PVOID* ppMetricPack
);
DWORD
LsaSrvGetStatus(
HANDLE hServer,
PCSTR pszTargetProvider,
PLSASTATUS* ppLsaStatus
);
DWORD
LsaSrvRefreshConfiguration(
HANDLE hServer
);
//
// For targeting specific providers
//
DWORD
LsaSrvProviderIoControl(
IN HANDLE hServer,
IN PCSTR pszProvider,
IN DWORD dwIoControlCode,
IN DWORD dwInputBufferSize,
IN PVOID pInputBuffer,
OUT DWORD* pdwOutputBufferSize,
OUT PVOID* ppOutputBuffer
);
//
// Server-Side only APIs for calling specific providers
//
DWORD
LsaSrvProviderGetMachineAccountInfoA(
IN PCSTR pszProvider,
IN OPTIONAL PCSTR DnsDomainName,
OUT PLSA_MACHINE_ACCOUNT_INFO_A* ppAccountInfo
);
DWORD
LsaSrvProviderGetMachineAccountInfoW(
IN PCSTR pszProvider,
IN OPTIONAL PCSTR DnsDomainName,
OUT PLSA_MACHINE_ACCOUNT_INFO_W* ppAccountInfo
);
DWORD
LsaSrvProviderGetMachinePasswordInfoA(
IN PCSTR pszProvider,
IN OPTIONAL PCSTR DnsDomainName,
OUT PLSA_MACHINE_PASSWORD_INFO_A* ppPasswordInfo
);
DWORD
LsaSrvProviderGetMachinePasswordInfoW(
IN PCSTR pszProvider,
IN OPTIONAL PCSTR DnsDomainName,
OUT PLSA_MACHINE_PASSWORD_INFO_W* ppPasswordInfo
);
VOID
LsaSrvFreeMachineAccountInfoA(
IN PLSA_MACHINE_ACCOUNT_INFO_A pAccountInfo
);
VOID
LsaSrvFreeMachineAccountInfoW(
IN PLSA_MACHINE_ACCOUNT_INFO_W pAccountInfo
);
VOID
LsaSrvFreeMachinePasswordInfoA(
IN PLSA_MACHINE_PASSWORD_INFO_A pPasswordInfo
);
VOID
LsaSrvFreeMachinePasswordInfoW(
IN PLSA_MACHINE_PASSWORD_INFO_W pPasswordInfo
);
DWORD
LsaSrvDuplicateMachineAccountInfoA(
IN PLSA_MACHINE_ACCOUNT_INFO_A pAccountInfo,
OUT PLSA_MACHINE_ACCOUNT_INFO_A* ppNewAccountInfo
);
DWORD
LsaSrvDuplicateMachineAccountInfoW(
IN PLSA_MACHINE_ACCOUNT_INFO_W pAccountInfo,
OUT PLSA_MACHINE_ACCOUNT_INFO_W* ppNewAccountInfo
);
DWORD
LsaSrvDuplicateMachinePasswordInfoA(
IN PLSA_MACHINE_PASSWORD_INFO_A pPasswordInfo,
OUT PLSA_MACHINE_PASSWORD_INFO_A* ppNewPasswordInfo
);
DWORD
LsaSrvDuplicateMachinePasswordInfoW(
IN PLSA_MACHINE_PASSWORD_INFO_W pPasswordInfo,
OUT PLSA_MACHINE_PASSWORD_INFO_W* ppNewPasswordInfo
);
DWORD
LsaSrvProviderServicesDomain(
IN PCSTR pszProvider,
IN PCSTR pszDomainName,
OUT PBOOLEAN pbServicesDomain
);
DWORD
LsaSrvGetPamConfig(
IN HANDLE hServer,
OUT PLSA_PAM_CONFIG *ppPamConfig
);
VOID
LsaSrvFreePamConfig(
IN PLSA_PAM_CONFIG pConfig
);
#endif /* __LSASRVAPI_H__ */
|
FernandoSBorges/netpyne
|
examples/evolCell/init.py
|
"""
init.py
Starting script to run NetPyNE-based model.
Usage: python init.py # Run simulation, optionally plot a raster
MPI usage: mpiexec -n 4 nrniv -python -mpi init.py
Contributors: <EMAIL>
"""
from netpyne import sim
cfg, netParams = sim.readCmdLineArgs() # read cfg and netParams from command line arguments
sim.createSimulateAnalyze(simConfig = cfg, netParams = netParams)
|
keylockerbv/secrethub-cli
|
internals/cli/io.go
|
<reponame>keylockerbv/secrethub-cli<filename>internals/cli/io.go
package cli
import (
"encoding/json"
)
// PrettyJSON returns a 4-space indented JSON text.
// Can be useful for printing out structs.
func PrettyJSON(data interface{}) (string, error) {
pretty, err := json.MarshalIndent(data, "", " ")
if err != nil {
return "", err
}
return string(pretty), nil
}
|
jazznerd206/SennaBox
|
frontend/src/components/Header/Header.js
|
import React from 'react';
import './style.css';
// import ActiveList from '../ActiveList/ActiveList';
import Login from '../Login/Login';
function Header() {
return (
<div className="header">
<div className="title">
<h1>SennaBox</h1>
<Login />
</div>
</div>
)
}
export default Header;
|
NearTox/Skia
|
bench/CodecBench.h
|
<filename>bench/CodecBench.h
/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef CodecBench_DEFINED
#define CodecBench_DEFINED
#include "bench/Benchmark.h"
#include "include/core/SkData.h"
#include "include/core/SkImageInfo.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkString.h"
#include "src/core/SkAutoMalloc.h"
/**
* Time SkCodec.
*/
class CodecBench : public Benchmark {
public:
// Calls encoded->ref()
CodecBench(SkString basename, SkData* encoded, SkColorType colorType, SkAlphaType alphaType);
protected:
const char* onGetName() override;
bool isSuitableFor(Backend backend) override;
void onDraw(int n, SkCanvas* canvas) override;
void onDelayedSetup() override;
private:
SkString fName;
const SkColorType fColorType;
const SkAlphaType fAlphaType;
sk_sp<SkData> fData;
SkImageInfo fInfo; // Set in onDelayedSetup.
SkAutoMalloc fPixelStorage;
using INHERITED = Benchmark;
};
#endif // CodecBench_DEFINED
|
RednoseHatake003/ZeroTwodiscord
|
commands/utility/urban.js
|
const { MessageEmbed } = require('discord.js')
const { textTrunctuate } = require('../../helper.js')
const urban = require('relevant-urban')
module.exports = {
config:{
name: "urban",
aliases: ['define','ud'],
guildOnly: true,
ownerOnly: false,
adminOnly: false,
permissions: null,
clientPermissions: null,
cooldown: null,
group: "utility",
description: "Searches for your query on Urban Dictionary!",
examples: ["urban [term]","define [term]"],
parameters: []
},
run: async ( client, message, args) => {
let def;
if (args.length) {
const defs = await urban(args.join(' ')).catch(()=>{})
if (!defs) return message.channel.send( new MessageEmbed().setColor('RED').setDescription(`\u200B\n\nNo match found for **${args.join(' ')}**`).setThumbnail('https://files.catbox.moe/kkkxw3.png'))
if (defs.constructor.name === 'Array') {
total = Object.keys(defs).length
if (!defs || !total) return message.channel.send( new MessageEmbed().setColor('RED').setDescription(`\u200B\n\nNo match found for **${args.join(' ')}**`).setThumbnail('https://files.catbox.moe/kkkxw3.png'))
def = defs[1]
} else if (defs.constructor.name === 'Definition') {
def = defs
}
return message.channel.send( new MessageEmbed()
.setAuthor(`Urban Dictionary`,`https://files.catbox.moe/kkkxw3.png`,`https://www.urbandictionary.com/`)
.setTitle(`Definition of ${defs.word}`)
.setURL(defs.urbanURL)
.addField(`Definition`,textTrunctuate(defs.definition,1000))
.addField('Example(s)', defs.example ? defs.example : 'N/A')
.setColor('#e86222')
.setFooter(`Submitted by ${defs.author}`)
)
} else {
return message.channel.send( new MessageEmbed()
.setAuthor(`Urban Dictionary`,`https://files.catbox.moe/kkkxw3.png`,`https://www.urbandictionary.com/`)
.setTitle(`Definition of Best Girl`)
.setURL('https://ao-buta.com/tv/?innerlink')
.addField(`Definition`,`No arguing, Mai Sakurajima indeed is the best anime girl!`)
.addField('Example(s)', '[Mai sakurajima] is the best girl around. No one could beat her, not even zero two.')
.setColor('#e86222')
.setFooter(`Submitted by <NAME>`))
}
}
}
|
Davidislit/mimic
|
lib/ui/components/common/Frame.js
|
<filename>lib/ui/components/common/Frame.js
import React from 'react';
import styled from 'styled-components';
import { DropTarget } from 'react-dnd';
import API from 'api';
import UIState from 'ui/states/UIState';
import { connectToState } from 'ui/states/connector';
import MainControls from 'ui/components/BottomBar/MainControls';
import ResizeHandle from 'ui/components/common/ResizeHandle';
import Dropzone from 'ui/components/common/Dropzone';
import SettingsState from 'ui/states/SettingsState';
import { Div } from 'ui/components/common/base';
import DnD from 'ui/components/common/DnD';
const dropTarget = {
drop(props, monitor) {
if (monitor.didDrop()) {
return;
}
try {
const file = monitor.getItem().files[0];
const reader = new FileReader();
reader.onload = function handleFileUpload() {
API.import(this.result, { mode: 'append' })
.then((status) => {
if (status.success) {
UIState.setViewMode('mocks');
} else {
SettingsState.setError(status.error);
UIState.setViewMode('settings');
}
});
};
reader.readAsText(file);
} catch (error) {
UIState.setViewMode('settings');
}
}
};
function collect(connector, monitor) {
return {
connectDropTarget: connector.dropTarget(),
isHovered: monitor.isOver()
};
}
const Container = styled(Div)`
width: 100%;
overflow: hidden;
height: calc(100% - 29px);
background-color: white;
border-top: ${(props) => props.theme.lightBorder};
bottom: 25px;
z-index: 2147483645;
`;
const Actions = styled(Div)`
display: flex;
align-items: center;
padding-left: 8px;
position: relative;
justify-content: flex-end;
`;
const Overlay = styled(Div)`
position: absolute;
top: 3px;
bottom: 25px;
width: 100%;
background: transparent;
z-index: 2147483646;
`;
const ControlBar = styled(Div)`
display: flex;
margin-left: 104px;
background: white;
position: fixed;
bottom: 0;
left: 0;
border-top: ${(props) => props.theme.lightBorder};
height: 25px;
width: calc(100% - 104px);
z-index: 2147483645;
`;
const FiltersBar = styled(Div)`
display: flex;
align-items: center;
background: white;
position: fixed;
bottom: 25px;
left: 0;
border-top: ${(props) => props.theme.lightBorder};
height: 25px;
width: 100%;
`;
class Frame extends React.Component {
componentDidMount() {
window.addEventListener('keydown', this.closeOnEscape);
window.addEventListener('resize', UIState.adjustEditorHeightOnResize);
}
componentWillUnmount() {
window.removeEventListener('keydown', this.closeOnEscape);
window.removeEventListener('resize', UIState.adjustEditorHeightOnResize);
}
closeOnEscape = (event) => {
if (event.keyCode === 27) {
UIState.setViewMode('closed');
}
};
render() {
const style = {
width: '100%',
height: UIState.editorHeight + 'px'
};
const disabledStyle = {
filter: 'grayscale(100%)',
opacity: 0.25
};
return (
<DnD style={ style } connect={ this.props.connectDropTarget }>
{ this.props.isHovered && <Dropzone overlay>Drop file to import mocks</Dropzone> }
<ResizeHandle value="editorHeight"/>
<Container style={ !UIState.mimicEnabled ? disabledStyle : {} }>
{ !UIState.mimicEnabled && <Overlay/> }
{ this.props.children }
</Container>
{
this.props.filters && <FiltersBar>{ this.props.filters }</FiltersBar>
}
<ControlBar>
{
UIState.mimicEnabled &&
<Actions>
{ this.props.controls }
</Actions>
}
<MainControls/>
</ControlBar>
</DnD>
);
}
}
export default DropTarget('__NATIVE_FILE__', dropTarget, collect)(connectToState(UIState, Frame));
|
eliasga/CS_EnterpriseI_archive
|
10 prev work/2014 Orsten/Simulation files/slprj/_sfprj/Model_justmodel/_self/sfun/src/c10_Model_justmodel.c
|
<reponame>eliasga/CS_EnterpriseI_archive
/* Include files */
#include <stddef.h>
#include "blas.h"
#include "Model_justmodel_sfun.h"
#include "c10_Model_justmodel.h"
#include "mwmathutil.h"
#define CHARTINSTANCE_CHARTNUMBER (chartInstance->chartNumber)
#define CHARTINSTANCE_INSTANCENUMBER (chartInstance->instanceNumber)
#include "Model_justmodel_sfun_debug_macros.h"
#define _SF_MEX_LISTEN_FOR_CTRL_C(S) sf_mex_listen_for_ctrl_c(sfGlobalDebugInstanceStruct,S);
/* Type Definitions */
/* Named Constants */
#define CALL_EVENT (-1)
/* Variable Declarations */
/* Variable Definitions */
static const char * c10_debug_family_names[17] = { "x1", "y1", "x2", "y2",
"beta", "alpha", "L", "x", "y", "psi", "nargin", "nargout", "WP", "L_rope",
"L_fast", "Offset_direction", "eta_ref" };
/* Function Declarations */
static void initialize_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance);
static void initialize_params_c10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance);
static void enable_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance);
static void disable_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance);
static void c10_update_debugger_state_c10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance);
static const mxArray *get_sim_state_c10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance);
static void set_sim_state_c10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance, const mxArray *c10_st);
static void finalize_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance);
static void sf_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance);
static void initSimStructsc10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance);
static void registerMessagesc10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance);
static void init_script_number_translation(uint32_T c10_machineNumber, uint32_T
c10_chartNumber);
static const mxArray *c10_sf_marshallOut(void *chartInstanceVoid, void
*c10_inData);
static void c10_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_eta_ref, const char_T *c10_identifier,
real_T c10_y[3]);
static void c10_b_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_u, const emlrtMsgIdentifier *c10_parentId,
real_T c10_y[3]);
static void c10_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c10_mxArrayInData, const char_T *c10_varName, void *c10_outData);
static const mxArray *c10_b_sf_marshallOut(void *chartInstanceVoid, void
*c10_inData);
static const mxArray *c10_c_sf_marshallOut(void *chartInstanceVoid, void
*c10_inData);
static real_T c10_c_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_u, const emlrtMsgIdentifier *c10_parentId);
static void c10_b_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c10_mxArrayInData, const char_T *c10_varName, void *c10_outData);
static void c10_info_helper(c10_ResolvedFunctionInfo c10_info[13]);
static const mxArray *c10_d_sf_marshallOut(void *chartInstanceVoid, void
*c10_inData);
static int32_T c10_d_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_u, const emlrtMsgIdentifier *c10_parentId);
static void c10_c_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c10_mxArrayInData, const char_T *c10_varName, void *c10_outData);
static uint8_T c10_e_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_b_is_active_c10_Model_justmodel, const
char_T *c10_identifier);
static uint8_T c10_f_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_u, const emlrtMsgIdentifier *c10_parentId);
static void init_dsm_address_info(SFc10_Model_justmodelInstanceStruct
*chartInstance);
/* Function Definitions */
static void initialize_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance)
{
chartInstance->c10_sfEvent = CALL_EVENT;
_sfTime_ = (real_T)ssGetT(chartInstance->S);
chartInstance->c10_is_active_c10_Model_justmodel = 0U;
}
static void initialize_params_c10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance)
{
}
static void enable_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance)
{
_sfTime_ = (real_T)ssGetT(chartInstance->S);
}
static void disable_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance)
{
_sfTime_ = (real_T)ssGetT(chartInstance->S);
}
static void c10_update_debugger_state_c10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance)
{
}
static const mxArray *get_sim_state_c10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance)
{
const mxArray *c10_st;
const mxArray *c10_y = NULL;
int32_T c10_i0;
real_T c10_u[3];
const mxArray *c10_b_y = NULL;
uint8_T c10_hoistedGlobal;
uint8_T c10_b_u;
const mxArray *c10_c_y = NULL;
real_T (*c10_eta_ref)[3];
c10_eta_ref = (real_T (*)[3])ssGetOutputPortSignal(chartInstance->S, 1);
c10_st = NULL;
c10_st = NULL;
c10_y = NULL;
sf_mex_assign(&c10_y, sf_mex_createcellarray(2), FALSE);
for (c10_i0 = 0; c10_i0 < 3; c10_i0++) {
c10_u[c10_i0] = (*c10_eta_ref)[c10_i0];
}
c10_b_y = NULL;
sf_mex_assign(&c10_b_y, sf_mex_create("y", c10_u, 0, 0U, 1U, 0U, 1, 3), FALSE);
sf_mex_setcell(c10_y, 0, c10_b_y);
c10_hoistedGlobal = chartInstance->c10_is_active_c10_Model_justmodel;
c10_b_u = c10_hoistedGlobal;
c10_c_y = NULL;
sf_mex_assign(&c10_c_y, sf_mex_create("y", &c10_b_u, 3, 0U, 0U, 0U, 0), FALSE);
sf_mex_setcell(c10_y, 1, c10_c_y);
sf_mex_assign(&c10_st, c10_y, FALSE);
return c10_st;
}
static void set_sim_state_c10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance, const mxArray *c10_st)
{
const mxArray *c10_u;
real_T c10_dv0[3];
int32_T c10_i1;
real_T (*c10_eta_ref)[3];
c10_eta_ref = (real_T (*)[3])ssGetOutputPortSignal(chartInstance->S, 1);
chartInstance->c10_doneDoubleBufferReInit = TRUE;
c10_u = sf_mex_dup(c10_st);
c10_emlrt_marshallIn(chartInstance, sf_mex_dup(sf_mex_getcell(c10_u, 0)),
"eta_ref", c10_dv0);
for (c10_i1 = 0; c10_i1 < 3; c10_i1++) {
(*c10_eta_ref)[c10_i1] = c10_dv0[c10_i1];
}
chartInstance->c10_is_active_c10_Model_justmodel = c10_e_emlrt_marshallIn
(chartInstance, sf_mex_dup(sf_mex_getcell(c10_u, 1)),
"is_active_c10_Model_justmodel");
sf_mex_destroy(&c10_u);
c10_update_debugger_state_c10_Model_justmodel(chartInstance);
sf_mex_destroy(&c10_st);
}
static void finalize_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance)
{
}
static void sf_c10_Model_justmodel(SFc10_Model_justmodelInstanceStruct
*chartInstance)
{
int32_T c10_i2;
int32_T c10_i3;
real_T c10_hoistedGlobal;
real_T c10_b_hoistedGlobal;
real_T c10_c_hoistedGlobal;
int32_T c10_i4;
real_T c10_WP[4];
real_T c10_L_rope;
real_T c10_L_fast;
real_T c10_Offset_direction;
uint32_T c10_debug_family_var_map[17];
real_T c10_x1;
real_T c10_y1;
real_T c10_x2;
real_T c10_y2;
real_T c10_beta;
real_T c10_alpha;
real_T c10_L;
real_T c10_x;
real_T c10_y;
real_T c10_psi;
real_T c10_nargin = 4.0;
real_T c10_nargout = 1.0;
real_T c10_eta_ref[3];
real_T c10_b_y;
real_T c10_b_x;
real_T c10_c_y;
real_T c10_c_x;
real_T c10_a;
real_T c10_d_y;
real_T c10_A;
real_T c10_d_x;
real_T c10_e_x;
real_T c10_e_y;
real_T c10_f_x;
real_T c10_g_x;
real_T c10_b_a;
real_T c10_b;
real_T c10_f_y;
real_T c10_h_x;
real_T c10_i_x;
real_T c10_c_a;
real_T c10_b_b;
real_T c10_g_y;
int32_T c10_i5;
real_T *c10_b_Offset_direction;
real_T *c10_b_L_fast;
real_T *c10_b_L_rope;
real_T (*c10_b_eta_ref)[3];
real_T (*c10_b_WP)[4];
c10_b_Offset_direction = (real_T *)ssGetInputPortSignal(chartInstance->S, 3);
c10_b_L_fast = (real_T *)ssGetInputPortSignal(chartInstance->S, 2);
c10_b_L_rope = (real_T *)ssGetInputPortSignal(chartInstance->S, 1);
c10_b_eta_ref = (real_T (*)[3])ssGetOutputPortSignal(chartInstance->S, 1);
c10_b_WP = (real_T (*)[4])ssGetInputPortSignal(chartInstance->S, 0);
_sfTime_ = (real_T)ssGetT(chartInstance->S);
_SFD_CC_CALL(CHART_ENTER_SFUNCTION_TAG, 9U, chartInstance->c10_sfEvent);
for (c10_i2 = 0; c10_i2 < 4; c10_i2++) {
_SFD_DATA_RANGE_CHECK((*c10_b_WP)[c10_i2], 0U);
}
for (c10_i3 = 0; c10_i3 < 3; c10_i3++) {
_SFD_DATA_RANGE_CHECK((*c10_b_eta_ref)[c10_i3], 1U);
}
_SFD_DATA_RANGE_CHECK(*c10_b_L_rope, 2U);
_SFD_DATA_RANGE_CHECK(*c10_b_L_fast, 3U);
_SFD_DATA_RANGE_CHECK(*c10_b_Offset_direction, 4U);
chartInstance->c10_sfEvent = CALL_EVENT;
_SFD_CC_CALL(CHART_ENTER_DURING_FUNCTION_TAG, 9U, chartInstance->c10_sfEvent);
c10_hoistedGlobal = *c10_b_L_rope;
c10_b_hoistedGlobal = *c10_b_L_fast;
c10_c_hoistedGlobal = *c10_b_Offset_direction;
for (c10_i4 = 0; c10_i4 < 4; c10_i4++) {
c10_WP[c10_i4] = (*c10_b_WP)[c10_i4];
}
c10_L_rope = c10_hoistedGlobal;
c10_L_fast = c10_b_hoistedGlobal;
c10_Offset_direction = c10_c_hoistedGlobal;
_SFD_SYMBOL_SCOPE_PUSH_EML(0U, 17U, 17U, c10_debug_family_names,
c10_debug_family_var_map);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_x1, 0U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_y1, 1U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_x2, 2U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_y2, 3U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_beta, 4U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_alpha, 5U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_L, 6U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_x, 7U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_y, 8U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_psi, 9U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_nargin, 10U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(&c10_nargout, 11U, c10_b_sf_marshallOut,
c10_b_sf_marshallIn);
_SFD_SYMBOL_SCOPE_ADD_EML(c10_WP, 12U, c10_c_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML(&c10_L_rope, 13U, c10_b_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML(&c10_L_fast, 14U, c10_b_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML(&c10_Offset_direction, 15U, c10_b_sf_marshallOut);
_SFD_SYMBOL_SCOPE_ADD_EML_IMPORTABLE(c10_eta_ref, 16U, c10_sf_marshallOut,
c10_sf_marshallIn);
CV_EML_FCN(0, 0);
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 4);
c10_x1 = c10_WP[0];
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 5);
c10_y1 = c10_WP[2];
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 7);
c10_x2 = c10_WP[1];
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 8);
c10_y2 = c10_WP[3];
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 10);
c10_b_y = c10_y2 - c10_y1;
c10_b_x = c10_x2 - c10_x1;
c10_c_y = c10_b_y;
c10_c_x = c10_b_x;
c10_beta = muDoubleScalarAtan2(c10_c_y, c10_c_x);
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 11);
c10_a = c10_Offset_direction;
c10_d_y = c10_a * 3.1415926535897931;
c10_A = c10_d_y;
c10_d_x = c10_A;
c10_e_x = c10_d_x;
c10_e_y = c10_e_x / 10.0;
c10_alpha = c10_beta + c10_e_y;
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 13);
c10_L = c10_L_rope + c10_L_fast;
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 14);
c10_f_x = c10_alpha;
c10_g_x = c10_f_x;
c10_g_x = muDoubleScalarCos(c10_g_x);
c10_b_a = c10_L;
c10_b = c10_g_x;
c10_f_y = c10_b_a * c10_b;
c10_x = c10_f_y + c10_x1;
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 15);
c10_h_x = c10_alpha;
c10_i_x = c10_h_x;
c10_i_x = muDoubleScalarSin(c10_i_x);
c10_c_a = c10_L;
c10_b_b = c10_i_x;
c10_g_y = c10_c_a * c10_b_b;
c10_y = c10_g_y + c10_y1;
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 16);
c10_psi = c10_alpha;
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, 18);
c10_eta_ref[0] = c10_x;
c10_eta_ref[1] = c10_y;
c10_eta_ref[2] = c10_psi;
_SFD_EML_CALL(0U, chartInstance->c10_sfEvent, -18);
_SFD_SYMBOL_SCOPE_POP();
for (c10_i5 = 0; c10_i5 < 3; c10_i5++) {
(*c10_b_eta_ref)[c10_i5] = c10_eta_ref[c10_i5];
}
_SFD_CC_CALL(EXIT_OUT_OF_FUNCTION_TAG, 9U, chartInstance->c10_sfEvent);
_SFD_CHECK_FOR_STATE_INCONSISTENCY(_Model_justmodelMachineNumber_,
chartInstance->chartNumber, chartInstance->instanceNumber);
}
static void initSimStructsc10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance)
{
}
static void registerMessagesc10_Model_justmodel
(SFc10_Model_justmodelInstanceStruct *chartInstance)
{
}
static void init_script_number_translation(uint32_T c10_machineNumber, uint32_T
c10_chartNumber)
{
}
static const mxArray *c10_sf_marshallOut(void *chartInstanceVoid, void
*c10_inData)
{
const mxArray *c10_mxArrayOutData = NULL;
int32_T c10_i6;
real_T c10_b_inData[3];
int32_T c10_i7;
real_T c10_u[3];
const mxArray *c10_y = NULL;
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *)chartInstanceVoid;
c10_mxArrayOutData = NULL;
for (c10_i6 = 0; c10_i6 < 3; c10_i6++) {
c10_b_inData[c10_i6] = (*(real_T (*)[3])c10_inData)[c10_i6];
}
for (c10_i7 = 0; c10_i7 < 3; c10_i7++) {
c10_u[c10_i7] = c10_b_inData[c10_i7];
}
c10_y = NULL;
sf_mex_assign(&c10_y, sf_mex_create("y", c10_u, 0, 0U, 1U, 0U, 1, 3), FALSE);
sf_mex_assign(&c10_mxArrayOutData, c10_y, FALSE);
return c10_mxArrayOutData;
}
static void c10_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_eta_ref, const char_T *c10_identifier,
real_T c10_y[3])
{
emlrtMsgIdentifier c10_thisId;
c10_thisId.fIdentifier = c10_identifier;
c10_thisId.fParent = NULL;
c10_b_emlrt_marshallIn(chartInstance, sf_mex_dup(c10_eta_ref), &c10_thisId,
c10_y);
sf_mex_destroy(&c10_eta_ref);
}
static void c10_b_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_u, const emlrtMsgIdentifier *c10_parentId,
real_T c10_y[3])
{
real_T c10_dv1[3];
int32_T c10_i8;
sf_mex_import(c10_parentId, sf_mex_dup(c10_u), c10_dv1, 1, 0, 0U, 1, 0U, 1, 3);
for (c10_i8 = 0; c10_i8 < 3; c10_i8++) {
c10_y[c10_i8] = c10_dv1[c10_i8];
}
sf_mex_destroy(&c10_u);
}
static void c10_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c10_mxArrayInData, const char_T *c10_varName, void *c10_outData)
{
const mxArray *c10_eta_ref;
const char_T *c10_identifier;
emlrtMsgIdentifier c10_thisId;
real_T c10_y[3];
int32_T c10_i9;
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *)chartInstanceVoid;
c10_eta_ref = sf_mex_dup(c10_mxArrayInData);
c10_identifier = c10_varName;
c10_thisId.fIdentifier = c10_identifier;
c10_thisId.fParent = NULL;
c10_b_emlrt_marshallIn(chartInstance, sf_mex_dup(c10_eta_ref), &c10_thisId,
c10_y);
sf_mex_destroy(&c10_eta_ref);
for (c10_i9 = 0; c10_i9 < 3; c10_i9++) {
(*(real_T (*)[3])c10_outData)[c10_i9] = c10_y[c10_i9];
}
sf_mex_destroy(&c10_mxArrayInData);
}
static const mxArray *c10_b_sf_marshallOut(void *chartInstanceVoid, void
*c10_inData)
{
const mxArray *c10_mxArrayOutData = NULL;
real_T c10_u;
const mxArray *c10_y = NULL;
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *)chartInstanceVoid;
c10_mxArrayOutData = NULL;
c10_u = *(real_T *)c10_inData;
c10_y = NULL;
sf_mex_assign(&c10_y, sf_mex_create("y", &c10_u, 0, 0U, 0U, 0U, 0), FALSE);
sf_mex_assign(&c10_mxArrayOutData, c10_y, FALSE);
return c10_mxArrayOutData;
}
static const mxArray *c10_c_sf_marshallOut(void *chartInstanceVoid, void
*c10_inData)
{
const mxArray *c10_mxArrayOutData = NULL;
int32_T c10_i10;
int32_T c10_i11;
int32_T c10_i12;
real_T c10_b_inData[4];
int32_T c10_i13;
int32_T c10_i14;
int32_T c10_i15;
real_T c10_u[4];
const mxArray *c10_y = NULL;
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *)chartInstanceVoid;
c10_mxArrayOutData = NULL;
c10_i10 = 0;
for (c10_i11 = 0; c10_i11 < 2; c10_i11++) {
for (c10_i12 = 0; c10_i12 < 2; c10_i12++) {
c10_b_inData[c10_i12 + c10_i10] = (*(real_T (*)[4])c10_inData)[c10_i12 +
c10_i10];
}
c10_i10 += 2;
}
c10_i13 = 0;
for (c10_i14 = 0; c10_i14 < 2; c10_i14++) {
for (c10_i15 = 0; c10_i15 < 2; c10_i15++) {
c10_u[c10_i15 + c10_i13] = c10_b_inData[c10_i15 + c10_i13];
}
c10_i13 += 2;
}
c10_y = NULL;
sf_mex_assign(&c10_y, sf_mex_create("y", c10_u, 0, 0U, 1U, 0U, 2, 2, 2), FALSE);
sf_mex_assign(&c10_mxArrayOutData, c10_y, FALSE);
return c10_mxArrayOutData;
}
static real_T c10_c_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_u, const emlrtMsgIdentifier *c10_parentId)
{
real_T c10_y;
real_T c10_d0;
sf_mex_import(c10_parentId, sf_mex_dup(c10_u), &c10_d0, 1, 0, 0U, 0, 0U, 0);
c10_y = c10_d0;
sf_mex_destroy(&c10_u);
return c10_y;
}
static void c10_b_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c10_mxArrayInData, const char_T *c10_varName, void *c10_outData)
{
const mxArray *c10_nargout;
const char_T *c10_identifier;
emlrtMsgIdentifier c10_thisId;
real_T c10_y;
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *)chartInstanceVoid;
c10_nargout = sf_mex_dup(c10_mxArrayInData);
c10_identifier = c10_varName;
c10_thisId.fIdentifier = c10_identifier;
c10_thisId.fParent = NULL;
c10_y = c10_c_emlrt_marshallIn(chartInstance, sf_mex_dup(c10_nargout),
&c10_thisId);
sf_mex_destroy(&c10_nargout);
*(real_T *)c10_outData = c10_y;
sf_mex_destroy(&c10_mxArrayInData);
}
const mxArray *sf_c10_Model_justmodel_get_eml_resolved_functions_info(void)
{
const mxArray *c10_nameCaptureInfo;
c10_ResolvedFunctionInfo c10_info[13];
const mxArray *c10_m0 = NULL;
int32_T c10_i16;
c10_ResolvedFunctionInfo *c10_r0;
c10_nameCaptureInfo = NULL;
c10_nameCaptureInfo = NULL;
c10_info_helper(c10_info);
sf_mex_assign(&c10_m0, sf_mex_createstruct("nameCaptureInfo", 1, 13), FALSE);
for (c10_i16 = 0; c10_i16 < 13; c10_i16++) {
c10_r0 = &c10_info[c10_i16];
sf_mex_addfield(c10_m0, sf_mex_create("nameCaptureInfo", c10_r0->context, 15,
0U, 0U, 0U, 2, 1, strlen(c10_r0->context)), "context", "nameCaptureInfo",
c10_i16);
sf_mex_addfield(c10_m0, sf_mex_create("nameCaptureInfo", c10_r0->name, 15,
0U, 0U, 0U, 2, 1, strlen(c10_r0->name)), "name", "nameCaptureInfo",
c10_i16);
sf_mex_addfield(c10_m0, sf_mex_create("nameCaptureInfo",
c10_r0->dominantType, 15, 0U, 0U, 0U, 2, 1, strlen(c10_r0->dominantType)),
"dominantType", "nameCaptureInfo", c10_i16);
sf_mex_addfield(c10_m0, sf_mex_create("nameCaptureInfo", c10_r0->resolved,
15, 0U, 0U, 0U, 2, 1, strlen(c10_r0->resolved)), "resolved",
"nameCaptureInfo", c10_i16);
sf_mex_addfield(c10_m0, sf_mex_create("nameCaptureInfo", &c10_r0->fileTimeLo,
7, 0U, 0U, 0U, 0), "fileTimeLo", "nameCaptureInfo", c10_i16);
sf_mex_addfield(c10_m0, sf_mex_create("nameCaptureInfo", &c10_r0->fileTimeHi,
7, 0U, 0U, 0U, 0), "fileTimeHi", "nameCaptureInfo", c10_i16);
sf_mex_addfield(c10_m0, sf_mex_create("nameCaptureInfo",
&c10_r0->mFileTimeLo, 7, 0U, 0U, 0U, 0), "mFileTimeLo", "nameCaptureInfo",
c10_i16);
sf_mex_addfield(c10_m0, sf_mex_create("nameCaptureInfo",
&c10_r0->mFileTimeHi, 7, 0U, 0U, 0U, 0), "mFileTimeHi", "nameCaptureInfo",
c10_i16);
}
sf_mex_assign(&c10_nameCaptureInfo, c10_m0, FALSE);
sf_mex_emlrtNameCapturePostProcessR2012a(&c10_nameCaptureInfo);
return c10_nameCaptureInfo;
}
static void c10_info_helper(c10_ResolvedFunctionInfo c10_info[13])
{
c10_info[0].context = "";
c10_info[0].name = "atan2";
c10_info[0].dominantType = "double";
c10_info[0].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/atan2.m";
c10_info[0].fileTimeLo = 1343830372U;
c10_info[0].fileTimeHi = 0U;
c10_info[0].mFileTimeLo = 0U;
c10_info[0].mFileTimeHi = 0U;
c10_info[1].context =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/atan2.m";
c10_info[1].name = "eml_scalar_eg";
c10_info[1].dominantType = "double";
c10_info[1].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalar_eg.m";
c10_info[1].fileTimeLo = 1286818796U;
c10_info[1].fileTimeHi = 0U;
c10_info[1].mFileTimeLo = 0U;
c10_info[1].mFileTimeHi = 0U;
c10_info[2].context =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/atan2.m";
c10_info[2].name = "eml_scalexp_alloc";
c10_info[2].dominantType = "double";
c10_info[2].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalexp_alloc.m";
c10_info[2].fileTimeLo = 1352424860U;
c10_info[2].fileTimeHi = 0U;
c10_info[2].mFileTimeLo = 0U;
c10_info[2].mFileTimeHi = 0U;
c10_info[3].context =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/atan2.m";
c10_info[3].name = "eml_scalar_atan2";
c10_info[3].dominantType = "double";
c10_info[3].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/eml_scalar_atan2.m";
c10_info[3].fileTimeLo = 1286818720U;
c10_info[3].fileTimeHi = 0U;
c10_info[3].mFileTimeLo = 0U;
c10_info[3].mFileTimeHi = 0U;
c10_info[4].context = "";
c10_info[4].name = "mtimes";
c10_info[4].dominantType = "double";
c10_info[4].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mtimes.m";
c10_info[4].fileTimeLo = 1289519692U;
c10_info[4].fileTimeHi = 0U;
c10_info[4].mFileTimeLo = 0U;
c10_info[4].mFileTimeHi = 0U;
c10_info[5].context = "";
c10_info[5].name = "mrdivide";
c10_info[5].dominantType = "double";
c10_info[5].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mrdivide.p";
c10_info[5].fileTimeLo = 1357951548U;
c10_info[5].fileTimeHi = 0U;
c10_info[5].mFileTimeLo = 1319729966U;
c10_info[5].mFileTimeHi = 0U;
c10_info[6].context =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/mrdivide.p";
c10_info[6].name = "rdivide";
c10_info[6].dominantType = "double";
c10_info[6].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m";
c10_info[6].fileTimeLo = 1346510388U;
c10_info[6].fileTimeHi = 0U;
c10_info[6].mFileTimeLo = 0U;
c10_info[6].mFileTimeHi = 0U;
c10_info[7].context =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m";
c10_info[7].name = "eml_scalexp_compatible";
c10_info[7].dominantType = "double";
c10_info[7].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_scalexp_compatible.m";
c10_info[7].fileTimeLo = 1286818796U;
c10_info[7].fileTimeHi = 0U;
c10_info[7].mFileTimeLo = 0U;
c10_info[7].mFileTimeHi = 0U;
c10_info[8].context =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/ops/rdivide.m";
c10_info[8].name = "eml_div";
c10_info[8].dominantType = "double";
c10_info[8].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/eml/eml_div.m";
c10_info[8].fileTimeLo = 1313347810U;
c10_info[8].fileTimeHi = 0U;
c10_info[8].mFileTimeLo = 0U;
c10_info[8].mFileTimeHi = 0U;
c10_info[9].context = "";
c10_info[9].name = "cos";
c10_info[9].dominantType = "double";
c10_info[9].resolved = "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/cos.m";
c10_info[9].fileTimeLo = 1343830372U;
c10_info[9].fileTimeHi = 0U;
c10_info[9].mFileTimeLo = 0U;
c10_info[9].mFileTimeHi = 0U;
c10_info[10].context = "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/cos.m";
c10_info[10].name = "eml_scalar_cos";
c10_info[10].dominantType = "double";
c10_info[10].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/eml_scalar_cos.m";
c10_info[10].fileTimeLo = 1286818722U;
c10_info[10].fileTimeHi = 0U;
c10_info[10].mFileTimeLo = 0U;
c10_info[10].mFileTimeHi = 0U;
c10_info[11].context = "";
c10_info[11].name = "sin";
c10_info[11].dominantType = "double";
c10_info[11].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/sin.m";
c10_info[11].fileTimeLo = 1343830386U;
c10_info[11].fileTimeHi = 0U;
c10_info[11].mFileTimeLo = 0U;
c10_info[11].mFileTimeHi = 0U;
c10_info[12].context = "[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/sin.m";
c10_info[12].name = "eml_scalar_sin";
c10_info[12].dominantType = "double";
c10_info[12].resolved =
"[ILXE]$matlabroot$/toolbox/eml/lib/matlab/elfun/eml_scalar_sin.m";
c10_info[12].fileTimeLo = 1286818736U;
c10_info[12].fileTimeHi = 0U;
c10_info[12].mFileTimeLo = 0U;
c10_info[12].mFileTimeHi = 0U;
}
static const mxArray *c10_d_sf_marshallOut(void *chartInstanceVoid, void
*c10_inData)
{
const mxArray *c10_mxArrayOutData = NULL;
int32_T c10_u;
const mxArray *c10_y = NULL;
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *)chartInstanceVoid;
c10_mxArrayOutData = NULL;
c10_u = *(int32_T *)c10_inData;
c10_y = NULL;
sf_mex_assign(&c10_y, sf_mex_create("y", &c10_u, 6, 0U, 0U, 0U, 0), FALSE);
sf_mex_assign(&c10_mxArrayOutData, c10_y, FALSE);
return c10_mxArrayOutData;
}
static int32_T c10_d_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_u, const emlrtMsgIdentifier *c10_parentId)
{
int32_T c10_y;
int32_T c10_i17;
sf_mex_import(c10_parentId, sf_mex_dup(c10_u), &c10_i17, 1, 6, 0U, 0, 0U, 0);
c10_y = c10_i17;
sf_mex_destroy(&c10_u);
return c10_y;
}
static void c10_c_sf_marshallIn(void *chartInstanceVoid, const mxArray
*c10_mxArrayInData, const char_T *c10_varName, void *c10_outData)
{
const mxArray *c10_b_sfEvent;
const char_T *c10_identifier;
emlrtMsgIdentifier c10_thisId;
int32_T c10_y;
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *)chartInstanceVoid;
c10_b_sfEvent = sf_mex_dup(c10_mxArrayInData);
c10_identifier = c10_varName;
c10_thisId.fIdentifier = c10_identifier;
c10_thisId.fParent = NULL;
c10_y = c10_d_emlrt_marshallIn(chartInstance, sf_mex_dup(c10_b_sfEvent),
&c10_thisId);
sf_mex_destroy(&c10_b_sfEvent);
*(int32_T *)c10_outData = c10_y;
sf_mex_destroy(&c10_mxArrayInData);
}
static uint8_T c10_e_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_b_is_active_c10_Model_justmodel, const
char_T *c10_identifier)
{
uint8_T c10_y;
emlrtMsgIdentifier c10_thisId;
c10_thisId.fIdentifier = c10_identifier;
c10_thisId.fParent = NULL;
c10_y = c10_f_emlrt_marshallIn(chartInstance, sf_mex_dup
(c10_b_is_active_c10_Model_justmodel), &c10_thisId);
sf_mex_destroy(&c10_b_is_active_c10_Model_justmodel);
return c10_y;
}
static uint8_T c10_f_emlrt_marshallIn(SFc10_Model_justmodelInstanceStruct
*chartInstance, const mxArray *c10_u, const emlrtMsgIdentifier *c10_parentId)
{
uint8_T c10_y;
uint8_T c10_u0;
sf_mex_import(c10_parentId, sf_mex_dup(c10_u), &c10_u0, 1, 3, 0U, 0, 0U, 0);
c10_y = c10_u0;
sf_mex_destroy(&c10_u);
return c10_y;
}
static void init_dsm_address_info(SFc10_Model_justmodelInstanceStruct
*chartInstance)
{
}
/* SFunction Glue Code */
#ifdef utFree
#undef utFree
#endif
#ifdef utMalloc
#undef utMalloc
#endif
#ifdef __cplusplus
extern "C" void *utMalloc(size_t size);
extern "C" void utFree(void*);
#else
extern void *utMalloc(size_t size);
extern void utFree(void*);
#endif
void sf_c10_Model_justmodel_get_check_sum(mxArray *plhs[])
{
((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2984638193U);
((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2817324692U);
((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1457416717U);
((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2634252847U);
}
mxArray *sf_c10_Model_justmodel_get_autoinheritance_info(void)
{
const char *autoinheritanceFields[] = { "checksum", "inputs", "parameters",
"outputs", "locals" };
mxArray *mxAutoinheritanceInfo = mxCreateStructMatrix(1,1,5,
autoinheritanceFields);
{
mxArray *mxChecksum = mxCreateString("G64yU3zmbafFuwxSzxbspC");
mxSetField(mxAutoinheritanceInfo,0,"checksum",mxChecksum);
}
{
const char *dataFields[] = { "size", "type", "complexity" };
mxArray *mxData = mxCreateStructMatrix(1,4,3,dataFields);
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(2);
pr[1] = (double)(2);
mxSetField(mxData,0,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,0,"type",mxType);
}
mxSetField(mxData,0,"complexity",mxCreateDoubleScalar(0));
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(1);
pr[1] = (double)(1);
mxSetField(mxData,1,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,1,"type",mxType);
}
mxSetField(mxData,1,"complexity",mxCreateDoubleScalar(0));
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(1);
pr[1] = (double)(1);
mxSetField(mxData,2,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,2,"type",mxType);
}
mxSetField(mxData,2,"complexity",mxCreateDoubleScalar(0));
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(1);
pr[1] = (double)(1);
mxSetField(mxData,3,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,3,"type",mxType);
}
mxSetField(mxData,3,"complexity",mxCreateDoubleScalar(0));
mxSetField(mxAutoinheritanceInfo,0,"inputs",mxData);
}
{
mxSetField(mxAutoinheritanceInfo,0,"parameters",mxCreateDoubleMatrix(0,0,
mxREAL));
}
{
const char *dataFields[] = { "size", "type", "complexity" };
mxArray *mxData = mxCreateStructMatrix(1,1,3,dataFields);
{
mxArray *mxSize = mxCreateDoubleMatrix(1,2,mxREAL);
double *pr = mxGetPr(mxSize);
pr[0] = (double)(3);
pr[1] = (double)(1);
mxSetField(mxData,0,"size",mxSize);
}
{
const char *typeFields[] = { "base", "fixpt" };
mxArray *mxType = mxCreateStructMatrix(1,1,2,typeFields);
mxSetField(mxType,0,"base",mxCreateDoubleScalar(10));
mxSetField(mxType,0,"fixpt",mxCreateDoubleMatrix(0,0,mxREAL));
mxSetField(mxData,0,"type",mxType);
}
mxSetField(mxData,0,"complexity",mxCreateDoubleScalar(0));
mxSetField(mxAutoinheritanceInfo,0,"outputs",mxData);
}
{
mxSetField(mxAutoinheritanceInfo,0,"locals",mxCreateDoubleMatrix(0,0,mxREAL));
}
return(mxAutoinheritanceInfo);
}
mxArray *sf_c10_Model_justmodel_third_party_uses_info(void)
{
mxArray * mxcell3p = mxCreateCellMatrix(1,0);
return(mxcell3p);
}
static const mxArray *sf_get_sim_state_info_c10_Model_justmodel(void)
{
const char *infoFields[] = { "chartChecksum", "varInfo" };
mxArray *mxInfo = mxCreateStructMatrix(1, 1, 2, infoFields);
const char *infoEncStr[] = {
"100 S1x2'type','srcId','name','auxInfo'{{M[1],M[5],T\"eta_ref\",},{M[8],M[0],T\"is_active_c10_Model_justmodel\",}}"
};
mxArray *mxVarInfo = sf_mex_decode_encoded_mx_struct_array(infoEncStr, 2, 10);
mxArray *mxChecksum = mxCreateDoubleMatrix(1, 4, mxREAL);
sf_c10_Model_justmodel_get_check_sum(&mxChecksum);
mxSetField(mxInfo, 0, infoFields[0], mxChecksum);
mxSetField(mxInfo, 0, infoFields[1], mxVarInfo);
return mxInfo;
}
static void chart_debug_initialization(SimStruct *S, unsigned int
fullDebuggerInitialization)
{
if (!sim_mode_is_rtw_gen(S)) {
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *) ((ChartInfoStruct *)
(ssGetUserData(S)))->chartInstance;
if (ssIsFirstInitCond(S) && fullDebuggerInitialization==1) {
/* do this only if simulation is starting */
{
unsigned int chartAlreadyPresent;
chartAlreadyPresent = sf_debug_initialize_chart
(sfGlobalDebugInstanceStruct,
_Model_justmodelMachineNumber_,
10,
1,
1,
5,
0,
0,
0,
0,
0,
&(chartInstance->chartNumber),
&(chartInstance->instanceNumber),
ssGetPath(S),
(void *)S);
if (chartAlreadyPresent==0) {
/* this is the first instance */
init_script_number_translation(_Model_justmodelMachineNumber_,
chartInstance->chartNumber);
sf_debug_set_chart_disable_implicit_casting
(sfGlobalDebugInstanceStruct,_Model_justmodelMachineNumber_,
chartInstance->chartNumber,1);
sf_debug_set_chart_event_thresholds(sfGlobalDebugInstanceStruct,
_Model_justmodelMachineNumber_,
chartInstance->chartNumber,
0,
0,
0);
_SFD_SET_DATA_PROPS(0,1,1,0,"WP");
_SFD_SET_DATA_PROPS(1,2,0,1,"eta_ref");
_SFD_SET_DATA_PROPS(2,1,1,0,"L_rope");
_SFD_SET_DATA_PROPS(3,1,1,0,"L_fast");
_SFD_SET_DATA_PROPS(4,1,1,0,"Offset_direction");
_SFD_STATE_INFO(0,0,2);
_SFD_CH_SUBSTATE_COUNT(0);
_SFD_CH_SUBSTATE_DECOMP(0);
}
_SFD_CV_INIT_CHART(0,0,0,0);
{
_SFD_CV_INIT_STATE(0,0,0,0,0,0,NULL,NULL);
}
_SFD_CV_INIT_TRANS(0,0,NULL,NULL,0,NULL);
/* Initialization of MATLAB Function Model Coverage */
_SFD_CV_INIT_EML(0,1,1,0,0,0,0,0,0,0,0);
_SFD_CV_INIT_EML_FCN(0,0,"eML_blk_kernel",0,-1,330);
_SFD_TRANS_COV_WTS(0,0,0,1,0);
if (chartAlreadyPresent==0) {
_SFD_TRANS_COV_MAPS(0,
0,NULL,NULL,
0,NULL,NULL,
1,NULL,NULL,
0,NULL,NULL);
}
{
unsigned int dimVector[2];
dimVector[0]= 2;
dimVector[1]= 2;
_SFD_SET_DATA_COMPILED_PROPS(0,SF_DOUBLE,2,&(dimVector[0]),0,0,0,0.0,
1.0,0,0,(MexFcnForType)c10_c_sf_marshallOut,(MexInFcnForType)NULL);
}
{
unsigned int dimVector[1];
dimVector[0]= 3;
_SFD_SET_DATA_COMPILED_PROPS(1,SF_DOUBLE,1,&(dimVector[0]),0,0,0,0.0,
1.0,0,0,(MexFcnForType)c10_sf_marshallOut,(MexInFcnForType)
c10_sf_marshallIn);
}
_SFD_SET_DATA_COMPILED_PROPS(2,SF_DOUBLE,0,NULL,0,0,0,0.0,1.0,0,0,
(MexFcnForType)c10_b_sf_marshallOut,(MexInFcnForType)NULL);
_SFD_SET_DATA_COMPILED_PROPS(3,SF_DOUBLE,0,NULL,0,0,0,0.0,1.0,0,0,
(MexFcnForType)c10_b_sf_marshallOut,(MexInFcnForType)NULL);
_SFD_SET_DATA_COMPILED_PROPS(4,SF_DOUBLE,0,NULL,0,0,0,0.0,1.0,0,0,
(MexFcnForType)c10_b_sf_marshallOut,(MexInFcnForType)NULL);
{
real_T *c10_L_rope;
real_T *c10_L_fast;
real_T *c10_Offset_direction;
real_T (*c10_WP)[4];
real_T (*c10_eta_ref)[3];
c10_Offset_direction = (real_T *)ssGetInputPortSignal(chartInstance->S,
3);
c10_L_fast = (real_T *)ssGetInputPortSignal(chartInstance->S, 2);
c10_L_rope = (real_T *)ssGetInputPortSignal(chartInstance->S, 1);
c10_eta_ref = (real_T (*)[3])ssGetOutputPortSignal(chartInstance->S, 1);
c10_WP = (real_T (*)[4])ssGetInputPortSignal(chartInstance->S, 0);
_SFD_SET_DATA_VALUE_PTR(0U, *c10_WP);
_SFD_SET_DATA_VALUE_PTR(1U, *c10_eta_ref);
_SFD_SET_DATA_VALUE_PTR(2U, c10_L_rope);
_SFD_SET_DATA_VALUE_PTR(3U, c10_L_fast);
_SFD_SET_DATA_VALUE_PTR(4U, c10_Offset_direction);
}
}
} else {
sf_debug_reset_current_state_configuration(sfGlobalDebugInstanceStruct,
_Model_justmodelMachineNumber_,chartInstance->chartNumber,
chartInstance->instanceNumber);
}
}
}
static const char* sf_get_instance_specialization(void)
{
return "SLGExYOQbgHwOhnjPAxnnH";
}
static void sf_opaque_initialize_c10_Model_justmodel(void *chartInstanceVar)
{
chart_debug_initialization(((SFc10_Model_justmodelInstanceStruct*)
chartInstanceVar)->S,0);
initialize_params_c10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*)
chartInstanceVar);
initialize_c10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*)
chartInstanceVar);
}
static void sf_opaque_enable_c10_Model_justmodel(void *chartInstanceVar)
{
enable_c10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*)
chartInstanceVar);
}
static void sf_opaque_disable_c10_Model_justmodel(void *chartInstanceVar)
{
disable_c10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*)
chartInstanceVar);
}
static void sf_opaque_gateway_c10_Model_justmodel(void *chartInstanceVar)
{
sf_c10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*) chartInstanceVar);
}
extern const mxArray* sf_internal_get_sim_state_c10_Model_justmodel(SimStruct* S)
{
ChartInfoStruct *chartInfo = (ChartInfoStruct*) ssGetUserData(S);
mxArray *plhs[1] = { NULL };
mxArray *prhs[4];
int mxError = 0;
prhs[0] = mxCreateString("chart_simctx_raw2high");
prhs[1] = mxCreateDoubleScalar(ssGetSFuncBlockHandle(S));
prhs[2] = (mxArray*) get_sim_state_c10_Model_justmodel
((SFc10_Model_justmodelInstanceStruct*)chartInfo->chartInstance);/* raw sim ctx */
prhs[3] = (mxArray*) sf_get_sim_state_info_c10_Model_justmodel();/* state var info */
mxError = sf_mex_call_matlab(1, plhs, 4, prhs, "sfprivate");
mxDestroyArray(prhs[0]);
mxDestroyArray(prhs[1]);
mxDestroyArray(prhs[2]);
mxDestroyArray(prhs[3]);
if (mxError || plhs[0] == NULL) {
sf_mex_error_message("Stateflow Internal Error: \nError calling 'chart_simctx_raw2high'.\n");
}
return plhs[0];
}
extern void sf_internal_set_sim_state_c10_Model_justmodel(SimStruct* S, const
mxArray *st)
{
ChartInfoStruct *chartInfo = (ChartInfoStruct*) ssGetUserData(S);
mxArray *plhs[1] = { NULL };
mxArray *prhs[4];
int mxError = 0;
prhs[0] = mxCreateString("chart_simctx_high2raw");
prhs[1] = mxCreateDoubleScalar(ssGetSFuncBlockHandle(S));
prhs[2] = mxDuplicateArray(st); /* high level simctx */
prhs[3] = (mxArray*) sf_get_sim_state_info_c10_Model_justmodel();/* state var info */
mxError = sf_mex_call_matlab(1, plhs, 4, prhs, "sfprivate");
mxDestroyArray(prhs[0]);
mxDestroyArray(prhs[1]);
mxDestroyArray(prhs[2]);
mxDestroyArray(prhs[3]);
if (mxError || plhs[0] == NULL) {
sf_mex_error_message("Stateflow Internal Error: \nError calling 'chart_simctx_high2raw'.\n");
}
set_sim_state_c10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*)
chartInfo->chartInstance, mxDuplicateArray(plhs[0]));
mxDestroyArray(plhs[0]);
}
static const mxArray* sf_opaque_get_sim_state_c10_Model_justmodel(SimStruct* S)
{
return sf_internal_get_sim_state_c10_Model_justmodel(S);
}
static void sf_opaque_set_sim_state_c10_Model_justmodel(SimStruct* S, const
mxArray *st)
{
sf_internal_set_sim_state_c10_Model_justmodel(S, st);
}
static void sf_opaque_terminate_c10_Model_justmodel(void *chartInstanceVar)
{
if (chartInstanceVar!=NULL) {
SimStruct *S = ((SFc10_Model_justmodelInstanceStruct*) chartInstanceVar)->S;
if (sim_mode_is_rtw_gen(S) || sim_mode_is_external(S)) {
sf_clear_rtw_identifier(S);
unload_Model_justmodel_optimization_info();
}
finalize_c10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*)
chartInstanceVar);
utFree((void *)chartInstanceVar);
ssSetUserData(S,NULL);
}
}
static void sf_opaque_init_subchart_simstructs(void *chartInstanceVar)
{
initSimStructsc10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*)
chartInstanceVar);
}
extern unsigned int sf_machine_global_initializer_called(void);
static void mdlProcessParameters_c10_Model_justmodel(SimStruct *S)
{
int i;
for (i=0;i<ssGetNumRunTimeParams(S);i++) {
if (ssGetSFcnParamTunable(S,i)) {
ssUpdateDlgParamAsRunTimeParam(S,i);
}
}
if (sf_machine_global_initializer_called()) {
initialize_params_c10_Model_justmodel((SFc10_Model_justmodelInstanceStruct*)
(((ChartInfoStruct *)ssGetUserData(S))->chartInstance));
}
}
static void mdlSetWorkWidths_c10_Model_justmodel(SimStruct *S)
{
if (sim_mode_is_rtw_gen(S) || sim_mode_is_external(S)) {
mxArray *infoStruct = load_Model_justmodel_optimization_info();
int_T chartIsInlinable =
(int_T)sf_is_chart_inlinable(S,sf_get_instance_specialization(),infoStruct,
10);
ssSetStateflowIsInlinable(S,chartIsInlinable);
ssSetRTWCG(S,sf_rtw_info_uint_prop(S,sf_get_instance_specialization(),
infoStruct,10,"RTWCG"));
ssSetEnableFcnIsTrivial(S,1);
ssSetDisableFcnIsTrivial(S,1);
ssSetNotMultipleInlinable(S,sf_rtw_info_uint_prop(S,
sf_get_instance_specialization(),infoStruct,10,
"gatewayCannotBeInlinedMultipleTimes"));
sf_update_buildInfo(S,sf_get_instance_specialization(),infoStruct,10);
if (chartIsInlinable) {
ssSetInputPortOptimOpts(S, 0, SS_REUSABLE_AND_LOCAL);
ssSetInputPortOptimOpts(S, 1, SS_REUSABLE_AND_LOCAL);
ssSetInputPortOptimOpts(S, 2, SS_REUSABLE_AND_LOCAL);
ssSetInputPortOptimOpts(S, 3, SS_REUSABLE_AND_LOCAL);
sf_mark_chart_expressionable_inputs(S,sf_get_instance_specialization(),
infoStruct,10,4);
sf_mark_chart_reusable_outputs(S,sf_get_instance_specialization(),
infoStruct,10,1);
}
{
unsigned int outPortIdx;
for (outPortIdx=1; outPortIdx<=1; ++outPortIdx) {
ssSetOutputPortOptimizeInIR(S, outPortIdx, 1U);
}
}
{
unsigned int inPortIdx;
for (inPortIdx=0; inPortIdx < 4; ++inPortIdx) {
ssSetInputPortOptimizeInIR(S, inPortIdx, 1U);
}
}
sf_set_rtw_dwork_info(S,sf_get_instance_specialization(),infoStruct,10);
ssSetHasSubFunctions(S,!(chartIsInlinable));
} else {
}
ssSetOptions(S,ssGetOptions(S)|SS_OPTION_WORKS_WITH_CODE_REUSE);
ssSetChecksum0(S,(2179481285U));
ssSetChecksum1(S,(1628351255U));
ssSetChecksum2(S,(521812663U));
ssSetChecksum3(S,(3310433740U));
ssSetmdlDerivatives(S, NULL);
ssSetExplicitFCSSCtrl(S,1);
ssSupportsMultipleExecInstances(S,1);
}
static void mdlRTW_c10_Model_justmodel(SimStruct *S)
{
if (sim_mode_is_rtw_gen(S)) {
ssWriteRTWStrParam(S, "StateflowChartType", "Embedded MATLAB");
}
}
static void mdlStart_c10_Model_justmodel(SimStruct *S)
{
SFc10_Model_justmodelInstanceStruct *chartInstance;
chartInstance = (SFc10_Model_justmodelInstanceStruct *)utMalloc(sizeof
(SFc10_Model_justmodelInstanceStruct));
memset(chartInstance, 0, sizeof(SFc10_Model_justmodelInstanceStruct));
if (chartInstance==NULL) {
sf_mex_error_message("Could not allocate memory for chart instance.");
}
chartInstance->chartInfo.chartInstance = chartInstance;
chartInstance->chartInfo.isEMLChart = 1;
chartInstance->chartInfo.chartInitialized = 0;
chartInstance->chartInfo.sFunctionGateway =
sf_opaque_gateway_c10_Model_justmodel;
chartInstance->chartInfo.initializeChart =
sf_opaque_initialize_c10_Model_justmodel;
chartInstance->chartInfo.terminateChart =
sf_opaque_terminate_c10_Model_justmodel;
chartInstance->chartInfo.enableChart = sf_opaque_enable_c10_Model_justmodel;
chartInstance->chartInfo.disableChart = sf_opaque_disable_c10_Model_justmodel;
chartInstance->chartInfo.getSimState =
sf_opaque_get_sim_state_c10_Model_justmodel;
chartInstance->chartInfo.setSimState =
sf_opaque_set_sim_state_c10_Model_justmodel;
chartInstance->chartInfo.getSimStateInfo =
sf_get_sim_state_info_c10_Model_justmodel;
chartInstance->chartInfo.zeroCrossings = NULL;
chartInstance->chartInfo.outputs = NULL;
chartInstance->chartInfo.derivatives = NULL;
chartInstance->chartInfo.mdlRTW = mdlRTW_c10_Model_justmodel;
chartInstance->chartInfo.mdlStart = mdlStart_c10_Model_justmodel;
chartInstance->chartInfo.mdlSetWorkWidths =
mdlSetWorkWidths_c10_Model_justmodel;
chartInstance->chartInfo.extModeExec = NULL;
chartInstance->chartInfo.restoreLastMajorStepConfiguration = NULL;
chartInstance->chartInfo.restoreBeforeLastMajorStepConfiguration = NULL;
chartInstance->chartInfo.storeCurrentConfiguration = NULL;
chartInstance->S = S;
ssSetUserData(S,(void *)(&(chartInstance->chartInfo)));/* register the chart instance with simstruct */
init_dsm_address_info(chartInstance);
if (!sim_mode_is_rtw_gen(S)) {
}
sf_opaque_init_subchart_simstructs(chartInstance->chartInfo.chartInstance);
chart_debug_initialization(S,1);
}
void c10_Model_justmodel_method_dispatcher(SimStruct *S, int_T method, void
*data)
{
switch (method) {
case SS_CALL_MDL_START:
mdlStart_c10_Model_justmodel(S);
break;
case SS_CALL_MDL_SET_WORK_WIDTHS:
mdlSetWorkWidths_c10_Model_justmodel(S);
break;
case SS_CALL_MDL_PROCESS_PARAMETERS:
mdlProcessParameters_c10_Model_justmodel(S);
break;
default:
/* Unhandled method */
sf_mex_error_message("Stateflow Internal Error:\n"
"Error calling c10_Model_justmodel_method_dispatcher.\n"
"Can't handle method %d.\n", method);
break;
}
}
|
gochaorg/cxel
|
src/main/java/xyz/cofe/cxel/js/op/BitOrOperator.java
|
package xyz.cofe.cxel.js.op;
import xyz.cofe.cxel.eval.FnName;
import xyz.cofe.cxel.js.Undef;
import java.util.List;
public class BitOrOperator extends BitOperator {
@FnName("|")
public static Double bitOr( Object left, Object right ){
long l = toBit(left);
long r = toBit(right);
long bits = l | r;
return (double)bits;
}
}
|
cisco-ie/cisco-proto
|
codegen/go/xr/66x/cisco_ios_xr_invmgr_oper/inventory/racks/rack/powershelf/slot/tsi1s/tsi1/tsi2s/tsi2/tsi3s/tsi3/attributes/fru_info/inv_card_fru_info.pb.go
|
/*
Copyright 2019 Cisco Systems
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: inv_card_fru_info.proto
package cisco_ios_xr_invmgr_oper_inventory_racks_rack_powershelf_slot_tsi1s_tsi1_tsi2s_tsi2_tsi3s_tsi3_attributes_fru_info
import (
fmt "fmt"
proto "github.com/golang/protobuf/proto"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type InvCardFruInfo_KEYS struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Name_1 string `protobuf:"bytes,2,opt,name=name_1,json=name1,proto3" json:"name_1,omitempty"`
Name_2 string `protobuf:"bytes,3,opt,name=name_2,json=name2,proto3" json:"name_2,omitempty"`
Name_3 string `protobuf:"bytes,4,opt,name=name_3,json=name3,proto3" json:"name_3,omitempty"`
Name_4 string `protobuf:"bytes,5,opt,name=name_4,json=name4,proto3" json:"name_4,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *InvCardFruInfo_KEYS) Reset() { *m = InvCardFruInfo_KEYS{} }
func (m *InvCardFruInfo_KEYS) String() string { return proto.CompactTextString(m) }
func (*InvCardFruInfo_KEYS) ProtoMessage() {}
func (*InvCardFruInfo_KEYS) Descriptor() ([]byte, []int) {
return fileDescriptor_3004b1b322cece9c, []int{0}
}
func (m *InvCardFruInfo_KEYS) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_InvCardFruInfo_KEYS.Unmarshal(m, b)
}
func (m *InvCardFruInfo_KEYS) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_InvCardFruInfo_KEYS.Marshal(b, m, deterministic)
}
func (m *InvCardFruInfo_KEYS) XXX_Merge(src proto.Message) {
xxx_messageInfo_InvCardFruInfo_KEYS.Merge(m, src)
}
func (m *InvCardFruInfo_KEYS) XXX_Size() int {
return xxx_messageInfo_InvCardFruInfo_KEYS.Size(m)
}
func (m *InvCardFruInfo_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_InvCardFruInfo_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_InvCardFruInfo_KEYS proto.InternalMessageInfo
func (m *InvCardFruInfo_KEYS) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *InvCardFruInfo_KEYS) GetName_1() string {
if m != nil {
return m.Name_1
}
return ""
}
func (m *InvCardFruInfo_KEYS) GetName_2() string {
if m != nil {
return m.Name_2
}
return ""
}
func (m *InvCardFruInfo_KEYS) GetName_3() string {
if m != nil {
return m.Name_3
}
return ""
}
func (m *InvCardFruInfo_KEYS) GetName_4() string {
if m != nil {
return m.Name_4
}
return ""
}
type InvTimespec struct {
TimeInSeconds int32 `protobuf:"zigzag32,1,opt,name=time_in_seconds,json=timeInSeconds,proto3" json:"time_in_seconds,omitempty"`
TimeInNanoSeconds int32 `protobuf:"zigzag32,2,opt,name=time_in_nano_seconds,json=timeInNanoSeconds,proto3" json:"time_in_nano_seconds,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *InvTimespec) Reset() { *m = InvTimespec{} }
func (m *InvTimespec) String() string { return proto.CompactTextString(m) }
func (*InvTimespec) ProtoMessage() {}
func (*InvTimespec) Descriptor() ([]byte, []int) {
return fileDescriptor_3004b1b322cece9c, []int{1}
}
func (m *InvTimespec) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_InvTimespec.Unmarshal(m, b)
}
func (m *InvTimespec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_InvTimespec.Marshal(b, m, deterministic)
}
func (m *InvTimespec) XXX_Merge(src proto.Message) {
xxx_messageInfo_InvTimespec.Merge(m, src)
}
func (m *InvTimespec) XXX_Size() int {
return xxx_messageInfo_InvTimespec.Size(m)
}
func (m *InvTimespec) XXX_DiscardUnknown() {
xxx_messageInfo_InvTimespec.DiscardUnknown(m)
}
var xxx_messageInfo_InvTimespec proto.InternalMessageInfo
func (m *InvTimespec) GetTimeInSeconds() int32 {
if m != nil {
return m.TimeInSeconds
}
return 0
}
func (m *InvTimespec) GetTimeInNanoSeconds() int32 {
if m != nil {
return m.TimeInNanoSeconds
}
return 0
}
type InvCardFruInfo struct {
CardAdministrativeState int32 `protobuf:"zigzag32,50,opt,name=card_administrative_state,json=cardAdministrativeState,proto3" json:"card_administrative_state,omitempty"`
PowerAdministrativeState int32 `protobuf:"zigzag32,51,opt,name=power_administrative_state,json=powerAdministrativeState,proto3" json:"power_administrative_state,omitempty"`
CardOperationalState int32 `protobuf:"zigzag32,52,opt,name=card_operational_state,json=cardOperationalState,proto3" json:"card_operational_state,omitempty"`
CardMonitorState int32 `protobuf:"zigzag32,53,opt,name=card_monitor_state,json=cardMonitorState,proto3" json:"card_monitor_state,omitempty"`
CardResetReason string `protobuf:"bytes,54,opt,name=card_reset_reason,json=cardResetReason,proto3" json:"card_reset_reason,omitempty"`
LastOperationalStateChange *InvTimespec `protobuf:"bytes,55,opt,name=last_operational_state_change,json=lastOperationalStateChange,proto3" json:"last_operational_state_change,omitempty"`
PowerCurrentMeasurement int32 `protobuf:"zigzag32,56,opt,name=power_current_measurement,json=powerCurrentMeasurement,proto3" json:"power_current_measurement,omitempty"`
CardUpTime *InvTimespec `protobuf:"bytes,57,opt,name=card_up_time,json=cardUpTime,proto3" json:"card_up_time,omitempty"`
PowerOperationalState int32 `protobuf:"zigzag32,58,opt,name=power_operational_state,json=powerOperationalState,proto3" json:"power_operational_state,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *InvCardFruInfo) Reset() { *m = InvCardFruInfo{} }
func (m *InvCardFruInfo) String() string { return proto.CompactTextString(m) }
func (*InvCardFruInfo) ProtoMessage() {}
func (*InvCardFruInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_3004b1b322cece9c, []int{2}
}
func (m *InvCardFruInfo) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_InvCardFruInfo.Unmarshal(m, b)
}
func (m *InvCardFruInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_InvCardFruInfo.Marshal(b, m, deterministic)
}
func (m *InvCardFruInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_InvCardFruInfo.Merge(m, src)
}
func (m *InvCardFruInfo) XXX_Size() int {
return xxx_messageInfo_InvCardFruInfo.Size(m)
}
func (m *InvCardFruInfo) XXX_DiscardUnknown() {
xxx_messageInfo_InvCardFruInfo.DiscardUnknown(m)
}
var xxx_messageInfo_InvCardFruInfo proto.InternalMessageInfo
func (m *InvCardFruInfo) GetCardAdministrativeState() int32 {
if m != nil {
return m.CardAdministrativeState
}
return 0
}
func (m *InvCardFruInfo) GetPowerAdministrativeState() int32 {
if m != nil {
return m.PowerAdministrativeState
}
return 0
}
func (m *InvCardFruInfo) GetCardOperationalState() int32 {
if m != nil {
return m.CardOperationalState
}
return 0
}
func (m *InvCardFruInfo) GetCardMonitorState() int32 {
if m != nil {
return m.CardMonitorState
}
return 0
}
func (m *InvCardFruInfo) GetCardResetReason() string {
if m != nil {
return m.CardResetReason
}
return ""
}
func (m *InvCardFruInfo) GetLastOperationalStateChange() *InvTimespec {
if m != nil {
return m.LastOperationalStateChange
}
return nil
}
func (m *InvCardFruInfo) GetPowerCurrentMeasurement() int32 {
if m != nil {
return m.PowerCurrentMeasurement
}
return 0
}
func (m *InvCardFruInfo) GetCardUpTime() *InvTimespec {
if m != nil {
return m.CardUpTime
}
return nil
}
func (m *InvCardFruInfo) GetPowerOperationalState() int32 {
if m != nil {
return m.PowerOperationalState
}
return 0
}
func init() {
proto.RegisterType((*InvCardFruInfo_KEYS)(nil), "cisco_ios_xr_invmgr_oper.inventory.racks.rack.powershelf.slot.tsi1s.tsi1.tsi2s.tsi2.tsi3s.tsi3.attributes.fru_info.inv_card_fru_info_KEYS")
proto.RegisterType((*InvTimespec)(nil), "cisco_ios_xr_invmgr_oper.inventory.racks.rack.powershelf.slot.tsi1s.tsi1.tsi2s.tsi2.tsi3s.tsi3.attributes.fru_info.inv_timespec")
proto.RegisterType((*InvCardFruInfo)(nil), "cisco_ios_xr_invmgr_oper.inventory.racks.rack.powershelf.slot.tsi1s.tsi1.tsi2s.tsi2.tsi3s.tsi3.attributes.fru_info.inv_card_fru_info")
}
func init() { proto.RegisterFile("inv_card_fru_info.proto", fileDescriptor_3004b1b322cece9c) }
var fileDescriptor_3004b1b322cece9c = []byte{
// 498 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x54, 0x4f, 0x6b, 0x13, 0x41,
0x14, 0x67, 0x6b, 0x53, 0x70, 0xac, 0xd4, 0x0c, 0xfd, 0x33, 0x16, 0x84, 0x92, 0x83, 0x14, 0x91,
0x91, 0xec, 0xc6, 0xaa, 0xc5, 0x8b, 0x14, 0x0f, 0x22, 0x55, 0x48, 0xf4, 0xe0, 0x69, 0x98, 0x6e,
0x5e, 0xd2, 0xc1, 0xec, 0x9b, 0x65, 0x66, 0x36, 0xea, 0xcd, 0xa3, 0xdf, 0xc3, 0xaf, 0xe2, 0xe7,
0x12, 0x99, 0x37, 0x69, 0x56, 0x9b, 0x9c, 0xa5, 0x97, 0xb7, 0x6f, 0x7f, 0x7f, 0x76, 0xde, 0x9f,
0x61, 0xd9, 0x81, 0xc1, 0xb9, 0x2a, 0xb5, 0x1b, 0xab, 0x89, 0x6b, 0x94, 0xc1, 0x89, 0x95, 0xb5,
0xb3, 0xc1, 0x72, 0x57, 0x1a, 0x5f, 0x5a, 0x65, 0xac, 0x57, 0x5f, 0x9d, 0x32, 0x38, 0xaf, 0xa6,
0x4e, 0xd9, 0x1a, 0x9c, 0x34, 0x38, 0x07, 0x0c, 0xd6, 0x7d, 0x93, 0x4e, 0x97, 0x9f, 0x3d, 0x45,
0x59, 0xdb, 0x2f, 0xe0, 0xfc, 0x25, 0xcc, 0x26, 0xd2, 0xcf, 0x6c, 0x90, 0xc1, 0x9b, 0xbe, 0xa7,
0x18, 0x43, 0x4e, 0x69, 0x1e, 0x43, 0x41, 0x69, 0x21, 0x75, 0x08, 0xce, 0x5c, 0x34, 0x01, 0xbc,
0xbc, 0x3a, 0xb9, 0xf7, 0x23, 0x63, 0xfb, 0x2b, 0xf5, 0xa8, 0xb7, 0xaf, 0x3f, 0x8d, 0x38, 0x67,
0x9b, 0xa8, 0x2b, 0x10, 0xd9, 0x51, 0x76, 0x7c, 0x7b, 0x48, 0x39, 0xdf, 0x63, 0x5b, 0xf1, 0xa9,
0xfa, 0x62, 0x83, 0xd0, 0x4e, 0x7c, 0xeb, 0x2f, 0xe1, 0x5c, 0xdc, 0x6a, 0xe1, 0x7c, 0x09, 0x17,
0x62, 0xb3, 0x85, 0x8b, 0x25, 0x3c, 0x10, 0x9d, 0x16, 0x1e, 0xf4, 0xa6, 0x6c, 0x3b, 0x56, 0x12,
0x4c, 0x05, 0xbe, 0x86, 0x92, 0x3f, 0x64, 0x3b, 0x31, 0x57, 0x06, 0x95, 0x87, 0xd2, 0xe2, 0xd8,
0x53, 0x29, 0xdd, 0xe1, 0xdd, 0x08, 0xbf, 0xc1, 0x51, 0x02, 0xf9, 0x13, 0xb6, 0x7b, 0xa5, 0x43,
0x8d, 0x76, 0x29, 0xde, 0x20, 0x71, 0x37, 0x89, 0xdf, 0x69, 0xb4, 0x0b, 0x43, 0xef, 0x77, 0x87,
0x75, 0x57, 0x7a, 0xe6, 0xa7, 0xec, 0x3e, 0x01, 0x7a, 0x5c, 0x19, 0x34, 0x3e, 0x38, 0x1d, 0xcc,
0x1c, 0x94, 0x0f, 0x3a, 0x80, 0xc8, 0xe9, 0x5b, 0x07, 0x51, 0xf0, 0xea, 0x1f, 0x7e, 0x14, 0x69,
0xfe, 0x92, 0x1d, 0xd2, 0x36, 0xd6, 0x9b, 0x0b, 0x32, 0x0b, 0x52, 0xac, 0x73, 0x0f, 0xd8, 0x3e,
0x9d, 0x1c, 0x57, 0xad, 0x83, 0xb1, 0xa8, 0x67, 0x0b, 0xe7, 0x80, 0x9c, 0xbb, 0x91, 0x7d, 0xdf,
0x92, 0xc9, 0xf5, 0x98, 0x71, 0x72, 0x55, 0x16, 0x4d, 0xb0, 0x6e, 0xe1, 0x78, 0x4a, 0x8e, 0x7b,
0x91, 0x39, 0x4f, 0x44, 0x52, 0x3f, 0x62, 0x5d, 0x52, 0x3b, 0xf0, 0x10, 0x94, 0x03, 0xed, 0x2d,
0x8a, 0x13, 0x1a, 0xff, 0x4e, 0x24, 0x86, 0x11, 0x1f, 0x12, 0xcc, 0x7f, 0x65, 0xec, 0xc1, 0x4c,
0xfb, 0xb0, 0x5a, 0x90, 0x2a, 0x2f, 0x35, 0x4e, 0x41, 0x3c, 0x3b, 0xca, 0x8e, 0xef, 0xe4, 0xdf,
0x33, 0xf9, 0xff, 0x6f, 0xac, 0xfc, 0xfb, 0x8e, 0x0c, 0x0f, 0x63, 0x9d, 0xd7, 0x47, 0x73, 0x46,
0x45, 0xc6, 0x85, 0xa6, 0xa5, 0x94, 0x8d, 0x73, 0x80, 0x41, 0x55, 0xa0, 0x7d, 0xe3, 0xa0, 0x02,
0x0c, 0xe2, 0x79, 0x5a, 0x28, 0x09, 0xce, 0x12, 0x7f, 0xde, 0xd2, 0xfc, 0x67, 0xc6, 0xb6, 0x69,
0x5e, 0x4d, 0x4d, 0x87, 0x89, 0x17, 0x37, 0xa5, 0x63, 0x16, 0xcb, 0xfa, 0x58, 0x7f, 0x30, 0x15,
0xf0, 0x13, 0x96, 0x1a, 0x58, 0x73, 0x73, 0x4e, 0xa9, 0xbf, 0x3d, 0xa2, 0xaf, 0xcf, 0xe7, 0x62,
0x8b, 0xfe, 0x37, 0xc5, 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x75, 0xc8, 0x83, 0xdf, 0x8a, 0x04,
0x00, 0x00,
}
|
ElthaTeng/multiline-ngc3351
|
one_pixel/line_flux_marginalize.py
|
<gh_stars>1-10
import numpy as np
import matplotlib.pyplot as plt
import time
'''This script computes the marginalized likelihoods of the line intensities, and then
plots the 1D likelihood distributions given a chosen bin size and intensity range.'''
region = 'arms'
log_bins = False
start_time = time.time()
model = '6d_coarse'
sou_model = 'radex_model/'
sou_data = 'data_cube/'
# Set parameter ranges
N_co = np.arange(16.,21.1,0.2)
T_k = np.arange(1.,2.4,0.1)
n_h2 = np.arange(2.,5.1,0.2)
X_13co = np.arange(10,205,10)
X_c18o = np.arange(2,21,1.5)
phi = np.arange(0.05, 1.01, 0.05)
size_N = N_co.shape[0]
size_T = T_k.shape[0]
size_n = n_h2.shape[0]
size_X1 = X_13co.shape[0]
size_X2 = X_c18o.shape[0]
size_phi = phi.shape[0]
size_6d = size_N*size_T*size_n*size_X1*size_X2*size_phi
fit_result = np.load(sou_data+'fitting_'+region+'_2.npy')[6:,:]
fit_err = np.load(sou_data+'fitting_'+region+'_errors_2.npy')[6:,:]
flux_obs = 1.0645 * fit_result[:,0] * fit_result[:,2]
flux_err = np.full((2,),np.nan)
if region == 'arms':
flux_err[0] = flux_obs[0] * (0.001/fit_result[0,0] + fit_err[0,2]/fit_result[0,2])
flux_err[1] = 1.0645 * 1 * 0.002 * fit_result[0,2] # 1 sigma upper bound + assume CO 2-1 line width
else:
flux_err = flux_obs * (np.array((0.002,0.001))/fit_result[:,0] + fit_err[:,2]/fit_result[:,2])
noise_10 = np.sqrt((0.1*flux_obs)**2 + flux_err**2)
# Compute chi2 and prob
chi2 = np.load(sou_model+'chi2_'+model+'_rmcor_'+region+'.npy').reshape(-1)
mask = np.load(sou_model+'mask_'+model+'_rmcor_'+region+'_los100.npy')
prob = np.exp(-0.5*chi2).reshape(-1) * mask
# Load line intensity grids
if log_bins:
flux_mod_13co10 = np.log10(np.load(sou_model+'flux_'+model+'_10_13co10.npy').reshape(-1))
flux_mod_c18o10 = np.log10(np.load(sou_model+'flux_'+model+'_10_c18o10.npy').reshape(-1))
else:
flux_mod_13co10 = np.load(sou_model+'flux_'+model+'_10_13co10.npy').reshape(-1)
flux_mod_c18o10 = np.load(sou_model+'flux_'+model+'_10_c18o10.npy').reshape(-1)
flux_mod = np.array((flux_mod_13co10, flux_mod_c18o10))
model_time = time.time()
print('Models loaded.', round(model_time - start_time, 1), 'sec elapsed.')
print('Start marginalizing intensity grids...')
# 1D likelihoods of line intensities
if log_bins:
if region == 'arms':
num_bins = np.array((15, 15))
ranges = np.array(([-1, -2],[0.5, -0.5]))
else:
num_bins = np.array((15, 15))
#ranges = np.array(([0.3, -0.5],[1.3, 0.5]))
ranges = np.array(([0., -0.8],[1.5, 0.7]))
else:
if region == 'arms':
num_bins = np.array((20, 20))
ranges = np.array(([0, 0],[2, 0.2]))
else:
num_bins = np.array((15, 12))
ranges = np.array(([0, 0],[15, 3]))
line = np.array(('13CO10', 'C18O10'))
title = np.array((r'$^{13}$CO 1-0', r'C$^{18}$O 1-0'))
plt.figure(figsize=(7,3))
for i in range(2):
plt.subplot(1,2,i+1)
plt.title(title[i])
counts_noweight, bins = np.histogram(flux_mod[i], bins=num_bins[i], range=ranges[:,i], weights=None, density=True)
counts_weighted, bins = np.histogram(flux_mod[i], bins=num_bins[i], range=ranges[:,i], weights=prob, density=True)
counts_norm = np.nan_to_num(counts_weighted / counts_noweight)
quantile_values = np.array((0.16,0.5,0.84),dtype='float32')
cdf = np.cumsum(counts_norm)
cdf /= cdf[-1]
pos1sig = np.interp(quantile_values[2], cdf, bins[:-1])
neg1sig = np.interp(quantile_values[0], cdf, bins[:-1])
plt.hist(bins[:-1], bins, weights=counts_norm, log=False, histtype='step', color='k')
ax = plt.gca()
ax.axes.yaxis.set_visible(False)
if log_bins:
plt.axvline(x=np.log10(flux_obs[i]+noise_10[i]), linewidth=1, color='b', linestyle='--')
plt.axvline(x=np.log10(flux_obs[i]-noise_10[i]), linewidth=1, color='b', linestyle='--')
plt.xlabel(r'$\log$ Intensity (K km $\rm s^{-1}$)')
else:
if region == 'arms' and i == 1:
plt.axvspan(0, flux_obs[i]+noise_10[i], alpha=0.2, color='gray')
plt.axvline(x=flux_obs[i]+noise_10[i], linewidth=1, color='k', linestyle='dotted')
else:
plt.axvspan(flux_obs[i]-noise_10[i], flux_obs[i]+noise_10[i], alpha=0.2, color='gray')
plt.axvline(x=flux_obs[i], linewidth=1, color='k', linestyle='dotted')
plt.xlabel(r'Intensity (K km $\rm s^{-1}$)')
#plt.axvline(x=pos1sig, linewidth=1, color='r', linestyle='--')
#plt.axvline(x=neg1sig, linewidth=1, color='r', linestyle='--')
plt.subplots_adjust(wspace=0.1)
#plt.subplots_adjust(hspace=0.5)
#plt.savefig('radex_model/prob1d_flux10_marg_'+region+'_cal10_lin_2.pdf', bbox_inches='tight', pad_inches=0.1)
end_time = time.time()
print('1D likelihoods generated.', round(end_time - model_time, 1), 'sec elapsed.')
print(flux_err, noise_10)
plt.show()
|
DrakonPL/Andromeda-Lib
|
Libs/JellyPhysics/PressureBody.h
|
#ifndef _PRESSURE_BODY_H
#define _PRESSURE_BODY_H
#include "SpringBody.h"
namespace JellyPhysics
{
class PressureBody : public SpringBody
{
protected:
float mVolume;
float mGasAmount;
Vector2* mNormalList;
public:
PressureBody(World* w, const ClosedShape& s, float mpp,
float gasPressure, float shapeK, float shapeD,
float edgeK, float edgeD,
const Vector2& pos, float angleInRadians, const Vector2& scale,
bool kinematic) :
SpringBody(w, s, mpp, shapeK, shapeD, edgeK, edgeD, pos, angleInRadians, scale, kinematic)
{
mGasAmount = gasPressure;
mNormalList = new Vector2[mPointCount];
mVolume = 0.0f;
}
~PressureBody();
void setGasPressure( float val ) { mGasAmount = val; }
float getGasPressure() { return mGasAmount; }
float getVolume() { return mVolume; }
void accumulateInternalForces();
};
}
#endif // _PRESSURE_BODY_H
|
nlugic/LSystems
|
LSystems/LSystemRenderer/LSystemRenderer.h
|
#ifndef LSYSTEMRENDERER_H
#define LSYSTEMRENDERER_H
#include "..\LSystemGenerator\LSystemContext.h"
#include "OGLRenderer.h"
namespace lrend
{
class LSystemRenderer
{
private:
std::vector<lsys::LSystemContext *> contexts;
static bool test_mode;
inline LSystemRenderer() = default;
explicit inline LSystemRenderer(lsys::LSystemContext *cxt) { addContext(cxt); }
LSystemRenderer(const LSystemRenderer&) = delete;
LSystemRenderer(LSystemRenderer&&) = delete;
LSystemRenderer& operator=(const LSystemRenderer&) = delete;
~LSystemRenderer();
public:
inline void addContext(lsys::LSystemContext *cxt) { if (cxt) contexts.push_back(cxt); }
void levelUp();
void levelDown();
inline static void setTestMode(bool test) { LSystemRenderer::test_mode = test; }
static void drawKochSnowflake(std::size_t level, float length, float angle = 60.0f);
static void drawKochIslandA(std::size_t level, float length, float angle = 90.0f);
static void drawKochIslandB(std::size_t level, float length, float angle = 90.0f);
static void drawKochIslandC(std::size_t level, float length, float angle = 90.0f);
static void drawKochIslandD(std::size_t level, float length, float angle = 90.0f);
static void drawKochIslandE(std::size_t level, float length, float angle = 90.0f);
static void drawKochIslandF(std::size_t level, float length, float angle = 90.0f);
static void drawKochIslandG(std::size_t level, float length, float angle = 90.0f);
static void drawDragonCurve(std::size_t level, float length, float angle = 90.0f);
static void drawSierpinskiGasket(std::size_t level, float length, float angle = 60.0f);
static void drawGeneric2DTreeA(std::size_t level, float length, float angle = 25.7f);
static void drawGeneric2DTreeB(std::size_t level, float length, float angle = 20.0f);
static void drawGeneric2DTreeC(std::size_t level, float length, float angle = 22.5f);
static void drawGeneric2DTreeD(std::size_t level, float length, float angle = 20.0f);
static void drawGeneric2DTreeE(std::size_t level, float length, float angle = 25.7f);
static void drawGeneric2DTreeF(std::size_t level, float length, float angle = 22.5f);
static void drawGeneric2DTreeS(std::size_t level, float length, float angle = 22.5f);
static void drawGeneric2DTreeSD(std::size_t level, float length,
float reduction = 1.456f, float angle = 85.0f);
static void drawHilbertCurve3D(std::size_t level, float width, float length,
float red = 0.0f, float green = 0.0f, float blue = 0.0f, float angle = 90.0f);
static void drawGeneric3DTree(std::size_t level, unsigned short slices, float radius,
float height, float angle = 22.5f);
static void drawTesselatedGeneric3DTree(std::size_t level, float radius, float height, float angle = 22.5f);
static void drawMultipleKochSnowflakes(std::size_t level, const std::vector<glm::vec3>& positions,
const std::vector<float>& lengths, float angle = 60.0f);
static void drawGeneric3DForest(std::size_t level, unsigned short slices, const std::vector<glm::vec3>& positions,
const std::vector<float>& radii, const std::vector<float>& heights, float angle = 22.5f);
};
}
#endif
|
SweydAbdul/estudos-python
|
CursoIntensivoPython/Aula15_visualizacao_de_dados/die.py
|
from random import randint
class Die:
"""Uma classe que representa um unico dado."""
def __init__(self, num_sides=6):
"""Supoe que seja um dado de seis lados."""
self.num_sides = num_sides
def roll(self):
"""Devolve um valor aleatorio entre 1 e o numero de lados."""
return randint(1, self.num_sides)
|
ducis/operating-system-labs
|
src.clean/lib/libtimers/tmrs_set.c
|
#include "timers.h"
/*===========================================================================*
* tmrs_settimer *
*===========================================================================*/
clock_t tmrs_settimer(tmrs, tp, exp_time, watchdog, new_head)
timer_t **tmrs; /* pointer to timers queue */
timer_t *tp; /* the timer to be added */
clock_t exp_time; /* its expiration time */
tmr_func_t watchdog; /* watchdog function to be run */
clock_t *new_head; /* new earliest timer, if non NULL */
{
/* Activate a timer to run function 'fp' at time 'exp_time'. If the timer is
* already in use it is first removed from the timers queue. Then, it is put
* in the list of active timers with the first to expire in front.
* The caller responsible for scheduling a new alarm for the timer if needed.
*/
timer_t **atp;
clock_t old_head = 0;
if(*tmrs)
old_head = (*tmrs)->tmr_exp_time;
/* Set the timer's variables. */
(void) tmrs_clrtimer(tmrs, tp, NULL);
tp->tmr_exp_time = exp_time;
tp->tmr_func = watchdog;
/* Add the timer to the active timers. The next timer due is in front. */
for (atp = tmrs; *atp != NULL; atp = &(*atp)->tmr_next) {
if (exp_time < (*atp)->tmr_exp_time) break;
}
tp->tmr_next = *atp;
*atp = tp;
if(new_head)
(*new_head) = (*tmrs)->tmr_exp_time;
return old_head;
}
|
tohotforice/onos-sdwsn
|
core/api/src/main/java/org/onosproject/net/multicast/Group.java
|
package org.onosproject.net.multicast;
import org.onlab.packet.IpAddress;
import org.onlab.packet.MacAddress;
import org.onosproject.net.sensor.SensorNodeAddress;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Created by aca on 4/30/15.
*/
public class Group {
public static final String MULTICAST_SCHEME = "multicast";
private URI id;
private MacAddress macAddress;
private IpAddress ipAddress;
private SensorNodeAddress sensorNodeAddress;
public Group(URI id, MacAddress macAddress, IpAddress ipAddress) {
this.id = id;
this.macAddress = macAddress;
this.ipAddress = ipAddress;
}
public Group(MacAddress macAddress, IpAddress ipAddress) {
this.macAddress = macAddress;
this.ipAddress = ipAddress;
try {
this.id = new URI(MULTICAST_SCHEME, ipAddress.toString(), macAddressToString(macAddress));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
public Group(MacAddress macAddress) {
byte[] mac = macAddress.toBytes();
byte[] ipOctet = {(byte) 224, mac[3], mac[4], mac[5]};
this.macAddress = macAddress;
this.ipAddress = IpAddress.valueOf(IpAddress.Version.INET, ipOctet);
this.sensorNodeAddress = new SensorNodeAddress(mac[3], (new byte[] {mac[4], mac[5]}));
try {
this.id = new URI(MULTICAST_SCHEME, ipAddress.toString(), macAddressToString(macAddress));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
public Group(IpAddress ipAddress) {
this.ipAddress = ipAddress;
byte[] addr = ipAddress.toOctets();
byte[] mac = {0x01, 0x00, 0x5e, addr[1], addr[2], addr[3]};
macAddress = MacAddress.valueOf(mac);
this.sensorNodeAddress = new SensorNodeAddress(mac[3], (new byte[] {mac[4], mac[5]}));
try {
this.id = new URI(MULTICAST_SCHEME, ipAddress.toString(), macAddressToString(macAddress));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
public Group(SensorNodeAddress sensorNodeAddress) {
this.sensorNodeAddress = sensorNodeAddress;
byte[] sensAddr = sensorNodeAddress.getAddr();
byte[] mac = {0x01, 0x00, 0x5e, sensorNodeAddress.getNetId(), sensAddr[1], sensAddr[0]};
macAddress = MacAddress.valueOf(mac);
byte[] ipOctet = {(byte) 224, mac[3], mac[4], mac[5]};
this.ipAddress = IpAddress.valueOf(IpAddress.Version.INET, ipOctet);
try {
this.id = new URI(MULTICAST_SCHEME, ipAddress.toString(), macAddressToString(macAddress));
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
private String macAddressToString(MacAddress macAddress) {
String mac = macAddress.toString();
String macString = mac.replaceAll(":", "-");
return macString;
}
public URI getId() {
return id;
}
public void setId(URI id) {
this.id = id;
}
public MacAddress getMacAddress() {
return macAddress;
}
public void setMacAddress(MacAddress macAddress) {
this.macAddress = macAddress;
}
public IpAddress getIpAddress() {
return ipAddress;
}
public void setIpAddress(IpAddress ipAddress) {
this.ipAddress = ipAddress;
}
public SensorNodeAddress getSensorNodeAddress() {
return sensorNodeAddress;
}
public void setSensorNodeAddress(SensorNodeAddress sensorNodeAddress) {
this.sensorNodeAddress = sensorNodeAddress;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Group)) {
return false;
}
Group group = (Group) o;
if (id != null ? !id.equals(group.id) : group.id != null) {
return false;
}
if (macAddress != null ? !macAddress.equals(group.macAddress) : group.macAddress != null) {
return false;
}
return !(ipAddress != null ? !ipAddress.equals(group.ipAddress) : group.ipAddress != null);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (macAddress != null ? macAddress.hashCode() : 0);
result = 31 * result + (ipAddress != null ? ipAddress.hashCode() : 0);
return result;
}
}
|
RizaevDima/glinova-gatsby-site
|
src/components/Footer/Footer.styles.js
|
import styled from "styled-components"
export const Wrapper = styled.footer`
background-color: #6a6a6a;
p {
color: #fff;
text-align: center;
}
`
|
johnwebbcole/jscad-utils
|
src/triangle.js
|
<filename>src/triangle.js<gh_stars>10-100
/** @module triangle */
/**
* Convert degrees to radians.
* @param {Number} deg value in degrees
* @return {Number} value in radians
*/
export const toRadians = function toRadians(deg) {
return (deg / 180) * Math.PI;
};
/**
* Convert radians to degrees.
* @param {Number} rad value in radians
* @return {Number} value in degrees
*/
export const toDegrees = function toDegrees(rad) {
return rad * (180 / Math.PI);
};
/**
* Solve a 90 degree triangle from two points.
* @param {Number} p1.x Point 1 x coordinate
* @param {Number} p1.y Point 1 y coordinate
* @param {Number} p2.x Point 2 x coordinate
* @param {Number} p2.y Point 2 y coordinate
* @return {Object} A triangle object {A,B,C,a,b,c}
*/
export const solve = function (p1, p2) {
var r = {
c: 90,
A: Math.abs(p2.x - p1.x),
B: Math.abs(p2.y - p1.y)
};
var brad = Math.atan2(r.B, r.A);
r.b = this.toDegrees(brad);
// r.C = Math.sqrt(Math.pow(r.B, 2) + Math.pow(r.A, 2));
r.C = r.B / Math.sin(brad);
r.a = 90 - r.b;
return r;
};
/**
* Solve a partial triangle object. Angles are in degrees.
* Angle `C` is set to 90 degrees. Requires a Side and an
* Angle.
*
* /\
* / B\
* c / \ a
* / \
* /A C\
* /----------\
* b
*
* /|
* /B|
* / |
* c/ |a
* /A C|
* /_____|
* b
*
* @param {Number} r.a Length of side `a`
* @param {Number} r.A Angle `A` in degrees
* @param {Number} r.b Length of side `b`
* @param {Number} r.B Angle `B` in degrees
* @param {Number} r.c Length of side `c`
* @return {Object} A solved triangle object {A,B,C,a,b,c}
*/
export const solve90SA = function (r) {
r = Object.assign(r, {
C: 90
});
r.A = r.A || 90 - r.B;
r.B = r.B || 90 - r.A;
var arad = toRadians(r.A);
// sinA = a/c
// a = c * sinA
// tanA = a/b
// a = b * tanA
r.a = r.a || (r.c ? r.c * Math.sin(arad) : r.b * Math.tan(arad));
// sinA = a/c
r.c = r.c || r.a / Math.sin(arad);
// tanA = a/b
r.b = r.b || r.a / Math.tan(arad);
return r;
};
export const solve90ac = function (r) {
r = Object.assign(r, { C: 90 });
// sinA = a/c
// a = arcsin(a/c)
var arad = Math.asin(r.a / r.c);
r.A = toDegrees(arad);
r.B = 90 - r.A;
// tanA = a/b
// r.b = r.a / Math.tan(arad);
// or
// a*a + b*b = c*c
// b*b = c*c - a*a
// b = sqr(c*c - a*a)
r.b = Math.sqrt(Math.pow(r.c, 2) - Math.pow(r.a, 2));
return r;
};
/**
* @function solveab
* Solve a partial right triangle object from two sides (a and b). Angles are in degrees.
* Angle `C` is set to 90 degrees. Requires a Side and an
* Angle.
*
* /|
* /B|
* / |
* c/ |a
* /A C|
* /_____|
* b
*
* @param {Number} r.a Length of side `a`
* @param {Number} r.b Length of side `b`
* @return {Object} A solved triangle object {A,B,C,a,b,c}
*/
export function solveab(r) {
r = Object.assign(r, { C: 90 });
// c = sqr(a*a + b*b)
r.c = Math.sqrt(Math.pow(r.a, 2) + Math.pow(r.b, 2));
// A = arcsin(a/c)
r.A = toDegrees(Math.asin(r.a / r.c));
// B = arcsin(b/c);
r.B = toDegrees(Math.asin(r.b / r.c));
return r;
}
|
soyzhc/agge
|
tests/agge.text/TextEngineTests.cpp
|
<gh_stars>10-100
#include <agge.text/text_engine.h>
#include "helpers.h"
#include "helpers_layout.h"
#include "mocks.h"
#include "outlines.h"
#include <agge/path.h>
#include <agge.text/limit.h>
#include <algorithm>
#include <tests/common/helpers.h>
#include <tests/common/scoped_ptr.h>
#include <ut/assert.h>
#include <ut/test.h>
using namespace std;
namespace agge
{
namespace tests
{
namespace
{
font_metrics c_fm1 = { 1.1f, 2.2f, 3.3f };
font_metrics c_fm2 = { 4.4f, 5.6f, 7.1f };
template <typename ContainerT>
vector<font_descriptor> get_descriptors(const ContainerT &created_log)
{
vector<font_descriptor> result;
for (typename ContainerT::const_iterator i = created_log.begin(); i != created_log.end(); ++i)
result.push_back(i->first);
return result;
}
}
begin_test_suite( TextEngineTests )
test( CreatingDifferentFontsReturnsDifferentObjects )
{
// INIT
mocks::fonts_loader loader;
text_engine_base e(loader);
// ACT
font::ptr fonts[] = {
e.create_font(font_descriptor::create("arial", 13, regular, false, hint_strong)),
e.create_font(font_descriptor::create("helvetica", 13, regular, false, hint_strong)),
e.create_font(font_descriptor::create("tahoma", 13, regular, false, hint_strong)),
e.create_font(font_descriptor::create("tahoma", 14, regular, false, hint_strong)),
e.create_font(font_descriptor::create("helvetica", 13, bold, false, hint_strong)),
e.create_font(font_descriptor::create("helvetica", 13, regular, true, hint_strong)),
e.create_font(font_descriptor::create("helvetica", 13, bold, true, hint_strong)),
e.create_font(font_descriptor::create("helvetica", 13, bold, true, hint_vertical)),
e.create_font(font_descriptor::create("helvetica", 13, bold, true, hint_none)),
e.create_font(font_descriptor::create("helvetica", 15, bold, true, hint_none)),
};
// ASSERT
sort(tests::begin(fonts), tests::end(fonts));
assert_equal(tests::end(fonts), unique(tests::begin(fonts), tests::end(fonts)));
}
test( CreatingTheSameFontReturnsTheSameObject )
{
// INIT
mocks::fonts_loader loader;
text_engine_base e(loader);
// ACT
font::ptr fonts[] = {
e.create_font(font_descriptor::create("arial", 13, regular, false, hint_strong)),
e.create_font(font_descriptor::create("ARial", 13, regular, false, hint_strong)),
e.create_font(font_descriptor::create("arial", 15, regular, false, hint_vertical)),
e.create_font(font_descriptor::create("Arial", 15, regular, false, hint_vertical)),
e.create_font(font_descriptor::create("arial", 13, regular, true, hint_none)),
e.create_font(font_descriptor::create("arial", 13, regular, true, hint_none)),
e.create_font(font_descriptor::create("tahoma", 143, bold, false, hint_strong)),
e.create_font(font_descriptor::create("taHOMA", 143, bold, false, hint_strong)),
};
// ASSERT
assert_equal(fonts[0], fonts[1]);
assert_equal(fonts[2], fonts[3]);
assert_equal(fonts[4], fonts[5]);
assert_equal(fonts[6], fonts[7]);
// ACT
font::ptr f2 = e.create_font(font_descriptor::create("arial", 13, regular, false, hint_strong));
// ASSERT
assert_equal(fonts[0], f2);
}
test( CreatingTheFontCreatesFontAccessor )
{
// INIT
mocks::fonts_loader loader;
text_engine_base e(loader);
// ACT
font::ptr f11 = e.create_font(font_descriptor::create("arial", 13, regular, false, hint_strong));
font::ptr f12 = e.create_font(font_descriptor::create("tahoma", 29, bold, false, hint_vertical));
font::ptr f13 = e.create_font(font_descriptor::create("helvetica", 15, regular, true, hint_none /* freely scalable */));
// ASSERT
font_descriptor fd1[] = {
font_descriptor::create("arial", 13, regular, false, hint_strong),
font_descriptor::create("tahoma", 29, bold, false, hint_vertical),
font_descriptor::create("helvetica", 1000, regular, true, hint_none),
};
assert_equal(fd1, get_descriptors(loader.created_log));
// INIT
loader.created_log.clear();
// ACT
font::ptr f21 = e.create_font(font_descriptor::create("arial", 15, bold, true, hint_none /* freely scalable */));
// ASSERT
font_descriptor fd2[] = {
font_descriptor::create("arial", 1000, bold, true, hint_none),
};
assert_equal(fd2, get_descriptors(loader.created_log));
}
test( ScalableFontAccessorIsCreatedOnceForDifferentFontSizes )
{
// INIT
mocks::fonts_loader loader;
text_engine_base e(loader);
// ACT
font::ptr f11 = e.create_font(font_descriptor::create("arial", 13, regular, true, hint_none));
font::ptr f12 = e.create_font(font_descriptor::create("arial", 29, regular, true, hint_none));
font::ptr f13 = e.create_font(font_descriptor::create("arial", 140, regular, true, hint_none));
// ASSERT
font_descriptor fd1[] = {
font_descriptor::create("arial", 1000, regular, true, hint_none),
};
assert_equal(fd1, get_descriptors(loader.created_log));
// ACT
font::ptr f21 = e.create_font(font_descriptor::create("times", 31, bold, false, hint_none));
font::ptr f22 = e.create_font(font_descriptor::create("times", 91, bold, false, hint_none));
// ASSERT
font_descriptor fd2[] = {
font_descriptor::create("arial", 1000, regular, true, hint_none),
font_descriptor::create("times", 1000, bold, false, hint_none),
};
assert_equal(fd2, get_descriptors(loader.created_log));
}
test( ScalableFontsReuseOutlinesReturnedByFontAccessor )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'A', 0 }, { L'B', 1 }, { L'C', 2 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(1.1, 1.2, c_outline_1),
mocks::glyph(1.3, 1.4, c_outline_2),
mocks::glyph(2.3, 2.4, c_outline_diamond),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 1000, regular, false, hint_none),
mocks::font_accessor(c_fm1, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
mocks::font_accessor &arial_accessor = loader.fonts[font_descriptor::create("Arial", 1000, regular, false,
hint_none)];
text_engine_base e(loader);
font::ptr f1 = e.create_font(font_descriptor::create("Arial", 17, regular, false, hint_none));
font::ptr f2 = e.create_font(font_descriptor::create("Arial", 210, regular, false, hint_none));
// ACT
f1->get_glyph(0);
f2->get_glyph(1);
// ASSERT
assert_equal(2u, *arial_accessor.glyphs_loaded);
// ACT
f2->get_glyph(0);
f1->get_glyph(1);
// ASSERT
assert_equal(2u, *arial_accessor.glyphs_loaded);
// ACT
f1->get_glyph(2);
// ASSERT
assert_equal(3u, *arial_accessor.glyphs_loaded);
// ACT
f2->get_glyph(2);
// ASSERT
assert_equal(3u, *arial_accessor.glyphs_loaded);
}
test( FontCreatedReceivesTheAccessorAndTheScalingNecessary )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'A', 0 }, };
mocks::font_accessor::glyph glyphs1[] = {
mocks::glyph(1.1, 1.2, c_outline_1), mocks::glyph(1.3, 1.4, c_outline_2),
};
mocks::font_accessor::glyph glyphs2[] = {
mocks::glyph(2.1, 2.2, c_outline_2), mocks::glyph(3.3, 3.4, c_outline_1),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Tahoma", 1000, regular, false, hint_none),
mocks::font_accessor(c_fm1, indices, glyphs1)),
make_pair(font_descriptor::create("Verdana", 1000, bold, false, hint_none),
mocks::font_accessor(c_fm2, indices, glyphs2)),
};
mocks::fonts_loader loader(fonts);
text_engine_base e(loader);
// ACT
font::ptr f = e.create_font(font_descriptor::create("Tahoma", 17, regular, false, hint_none));
const glyph *g1 = f->get_glyph(0);
pod_vector<glyph::path_point> o1 = convert_copy(g1->get_outline());
const glyph *g2 = f->get_glyph(1);
pod_vector<glyph::path_point> o2 = convert_copy(g2->get_outline());
// ASSERT
assert_equal(0.017 * c_fm1, f->get_metrics());
assert_is_true(equal(0.017f * 1.1f, g1->metrics.advance_x));
assert_is_true(equal(0.017f * 1.2f, g1->metrics.advance_y));
assert_equal(c_outline_1, (1 / 0.017) * o1);
assert_is_true(equal(0.017f * 1.3f, g2->metrics.advance_x));
assert_is_true(equal(0.017f * 1.4f, g2->metrics.advance_y));
assert_equal(c_outline_2, (1 / 0.017) * o2);
// ACT
f = e.create_font(font_descriptor::create("Verdana", 710, bold, false, hint_none));
g1 = f->get_glyph(0);
pod_vector<glyph::path_point> o3 = convert_copy(g1->get_outline());
g2 = f->get_glyph(1);
pod_vector<glyph::path_point> o4 = convert_copy(g2->get_outline());
// ASSERT
assert_equal(0.71 * c_fm2, f->get_metrics());
assert_equal(c_outline_2, (1 / 0.71) * o3);
assert_equal(c_outline_1, (1 / 0.71) * o4);
}
test( DifferentNamesCanProduceTheSameFont )
{
// INIT
mocks::font_accessor accessors[] = { mocks::font_accessor(), mocks::font_accessor(), };
accessors[0].descriptor = font_descriptor::create("plain #1", 10, bold, false);
accessors[1].descriptor = font_descriptor::create("plain #2", 1000, regular, false);
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Tahoma", 11, regular, false, hint_strong), accessors[0]),
make_pair(font_descriptor::create("Segoe", 10, regular, false, hint_strong), accessors[0]),
make_pair(font_descriptor::create("Verdana", 1000, bold, false, hint_vertical), accessors[1]),
make_pair(font_descriptor::create("Verdana,Helvetica", 1000, bold, false, hint_vertical), accessors[1]),
make_pair(font_descriptor::create("Verdana,sans-serif", 1000, bold, false, hint_vertical), accessors[1]),
make_pair(font_descriptor::create("Verdana,Helvetica", 100, bold, false, hint_none), accessors[1]),
make_pair(font_descriptor::create("Verdana,sans-serif", 10, bold, false, hint_none), accessors[1]),
};
mocks::fonts_loader loader(fonts);
text_engine_base e(loader);
// ACT
shared_ptr<font> f1 = e.create_font(font_descriptor::create("Tahoma", 11, regular, false, hint_strong));
shared_ptr<font> f2 = e.create_font(font_descriptor::create("Verdana", 1000, bold, false, hint_vertical));
shared_ptr<font> f3 = e.create_font(font_descriptor::create("Verdana,Helvetica", 100, bold, false, hint_none));
// ACT / ASSERT
assert_equal(f1, e.create_font(font_descriptor::create("Segoe", 10, regular, false, hint_strong)));
assert_equal(f2, e.create_font(font_descriptor::create("verdana,helvetica", 1000, bold, false, hint_vertical)));
assert_equal(f2, e.create_font(font_descriptor::create("Verdana,Sans-Serif", 1000, bold, false, hint_vertical)));
assert_not_equal(f3, e.create_font(font_descriptor::create("Verdana,Sans-Serif", 10, bold, false, hint_none)));
}
test( GlyphsRequestedAreRenderedIntoRasterizerProvidedAtAnExpectedIntegerPosition )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, { L'b', 1 }, { L'c', 2 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(0, 0, c_outline_1), mocks::glyph(0, 0, c_outline_2), mocks::glyph(0, 0, c_outline_diamond),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm1, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader);
mocks::rasterizer target;
font::ptr f = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
// ACT
e.render_glyph(target, *f, 1, 19.0f, 3.0f);
// ASSERT
assert_equal(1u, target.append_log.size());
assert_equal(c_outline_2, target.append_log[0].first->path);
assert_equal(mkpoint(19, 3), target.append_log[0].second);
// ACT
e.render_glyph(target, *f, 1, 119.0f, -30.0f);
// ASSERT
assert_equal(2u, target.append_log.size());
assert_equal(c_outline_2, target.append_log[1].first->path);
assert_equal(mkpoint(119, -30), target.append_log[1].second);
// ACT
e.render_glyph(target, *f, 2, -1719.0f, 29.0f);
// ASSERT
assert_equal(3u, target.append_log.size());
assert_equal(c_outline_diamond, target.append_log[2].first->path);
assert_equal(mkpoint(-1719, 29), target.append_log[2].second);
}
test( GlyphRastersAreCachedAcrossCalls )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, { L'b', 1 }, { L'c', 2 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(0, 0, c_outline_1), mocks::glyph(0, 0, c_outline_2), mocks::glyph(0, 0, c_outline_diamond),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm1, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader);
mocks::rasterizer target;
font::ptr f = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
e.render_glyph(target, *f, 1, 19.0f, 3.0f);
e.render_glyph(target, *f, 0, 1.0f, 2.0f);
e.render_glyph(target, *f, 2, 0.0f, 0.0f);
// ACT
e.render_glyph(target, *f, 1, 29.0f, -113.0f);
e.render_glyph(target, *f, 0, 19.0f, -13.0f);
// ASSERT
assert_equal(5u, target.append_log.size());
assert_equal(target.append_log[0].first, target.append_log[3].first);
assert_equal(target.append_log[1].first, target.append_log[4].first);
// ACT
e.render_glyph(target, *f, 1, 29.0f, -113.0f);
e.render_glyph(target, *f, 2, 19.0f, -13.0f);
// ASSERT
assert_equal(7u, target.append_log.size());
assert_equal(target.append_log[0].first, target.append_log[5].first);
assert_equal(target.append_log[2].first, target.append_log[6].first);
}
test( GlyphRastersAreCachedAtAllowedPresetFractionalPrecisionX2 )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(0, 0, c_outline_2),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm1, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader, 1);
mocks::rasterizer target;
font::ptr f = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
// ACT
e.render_glyph(target, *f, 0, 1.0f, 1.0f);
e.render_glyph(target, *f, 0, 1.49f, 1.0f);
e.render_glyph(target, *f, 0, 1.0f, 1.49f);
e.render_glyph(target, *f, 0, 1.49f, 1.49f);
// ASSERT
assert_equal(4u, target.append_log.size());
assert_equal(1.1f + 0.0f, target.append_log[0].first->path[0].x);
assert_equal(2.4f + 0.0f, target.append_log[0].first->path[0].y);
assert_equal(target.append_log[0].first, target.append_log[1].first);
assert_equal(target.append_log[0].first, target.append_log[2].first);
assert_equal(target.append_log[0].first, target.append_log[3].first);
// ACT
e.render_glyph(target, *f, 0, 1.5f, 1.0f);
e.render_glyph(target, *f, 0, 1.99f, 1.0f);
e.render_glyph(target, *f, 0, 1.5f, 1.49f);
e.render_glyph(target, *f, 0, 1.99f, 1.49f);
// ASSERT
assert_equal(8u, target.append_log.size());
assert_not_equal(target.append_log[0].first, target.append_log[4].first);
assert_equal(1.1f + 0.5f, target.append_log[4].first->path[0].x);
assert_equal(2.4f + 0.0f, target.append_log[4].first->path[0].y);
assert_equal(target.append_log[4].first, target.append_log[5].first);
assert_equal(target.append_log[4].first, target.append_log[6].first);
assert_equal(target.append_log[4].first, target.append_log[7].first);
// ACT
e.render_glyph(target, *f, 0, 1.0f, 1.5f);
e.render_glyph(target, *f, 0, 1.49f, 1.5f);
e.render_glyph(target, *f, 0, 1.0f, 1.99f);
e.render_glyph(target, *f, 0, 1.49f, 1.99f);
// ASSERT
assert_equal(12u, target.append_log.size());
assert_not_equal(target.append_log[0].first, target.append_log[4].first);
assert_not_equal(target.append_log[4].first, target.append_log[8].first);
assert_equal(1.1f + 0.0f, target.append_log[8].first->path[0].x);
assert_equal(2.4f + 0.5f, target.append_log[8].first->path[0].y);
assert_equal(target.append_log[8].first, target.append_log[9].first);
assert_equal(target.append_log[8].first, target.append_log[10].first);
assert_equal(target.append_log[8].first, target.append_log[11].first);
// ACT
e.render_glyph(target, *f, 0, 1.5f, 1.5f);
e.render_glyph(target, *f, 0, 1.99f, 1.5f);
e.render_glyph(target, *f, 0, 1.5f, 1.99f);
e.render_glyph(target, *f, 0, 1.99f, 1.99f);
// ASSERT
assert_equal(16u, target.append_log.size());
assert_not_equal(target.append_log[0].first, target.append_log[12].first);
assert_not_equal(target.append_log[4].first, target.append_log[12].first);
assert_not_equal(target.append_log[8].first, target.append_log[12].first);
assert_equal(1.1f + 0.5f, target.append_log[12].first->path[0].x);
assert_equal(2.4f + 0.5f, target.append_log[12].first->path[0].y);
assert_equal(4.1f + 0.5f, target.append_log[12].first->path[1].x);
assert_equal(7.5f + 0.5f, target.append_log[12].first->path[1].y);
assert_equal(4.1f + 0.5f, target.append_log[12].first->path[2].x);
assert_equal(4.5f + 0.5f, target.append_log[12].first->path[2].y);
assert_equal(5.5f + 0.5f, target.append_log[12].first->path[3].x);
assert_equal(1.1f + 0.5f, target.append_log[12].first->path[3].y);
assert_equal(target.append_log[12].first, target.append_log[13].first);
assert_equal(target.append_log[12].first, target.append_log[14].first);
assert_equal(target.append_log[12].first, target.append_log[15].first);
// ACT (different whole cell)
e.render_glyph(target, *f, 0, 11.5f, 113.5f);
e.render_glyph(target, *f, 0, 11.99f, 113.5f);
e.render_glyph(target, *f, 0, 11.5f, 113.99f);
e.render_glyph(target, *f, 0, 11.99f, 113.99f);
// ASSERT
assert_equal(20u, target.append_log.size());
assert_equal(target.append_log[12].first, target.append_log[16].first);
assert_equal(target.append_log[16].first, target.append_log[17].first);
assert_equal(target.append_log[16].first, target.append_log[18].first);
assert_equal(target.append_log[16].first, target.append_log[19].first);
// ACT (negative whole cell)
e.render_glyph(target, *f, 0, -11.52f, -113.53f);
e.render_glyph(target, *f, 0, -11.98f, -113.54f);
e.render_glyph(target, *f, 0, -11.55f, -113.97f);
e.render_glyph(target, *f, 0, -11.96f, -113.95f);
// ASSERT
assert_equal(24u, target.append_log.size());
assert_equal(target.append_log[0].first, target.append_log[20].first);
assert_equal(target.append_log[20].first, target.append_log[21].first);
assert_equal(target.append_log[20].first, target.append_log[22].first);
assert_equal(target.append_log[20].first, target.append_log[23].first);
}
test( ReferenceGlyphsAreRenderedAtGivenSubpixelGrid )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(0, 0, c_outline_2),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm1, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e1(loader, 2);
text_engine<mocks::rasterizer> e2(loader, 3);
mocks::rasterizer target;
font::ptr f1 = e1.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
font::ptr f2 = e2.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
// ACT
e1.render_glyph(target, *f1, 0, 1.15f, 1.3f);
e1.render_glyph(target, *f1, 0, 1.55f, 1.9f);
e2.render_glyph(target, *f2, 0, 1.15f, 1.3f);
e2.render_glyph(target, *f2, 0, 1.55f, 1.9f);
// ASSERT
assert_equal(1.1f + 0.0f, target.append_log[0].first->path[0].x);
assert_equal(2.4f + 0.25f, target.append_log[0].first->path[0].y);
assert_equal(1.1f + 0.5f, target.append_log[1].first->path[0].x);
assert_equal(2.4f + 0.75f, target.append_log[1].first->path[0].y);
assert_equal(1.1f + 0.125f, target.append_log[2].first->path[0].x);
assert_equal(2.4f + 0.25f, target.append_log[2].first->path[0].y);
assert_equal(1.1f + 0.5f, target.append_log[3].first->path[0].x);
assert_equal(2.4f + 0.875f, target.append_log[3].first->path[0].y);
}
test( GlyphRunIsRenderedInTheProperOrder )
{
// INIT
mocks::font_accessor::char_to_index font_indices[] = { { L'a', 0 }, { L'w', 1 }, };
mocks::font_accessor::glyph font_glyphs[] = {
mocks::glyph(5, 0, c_outline_1),
mocks::glyph(7, 0, c_outline_2),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, font_indices, font_glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader, 0);
font::ptr f = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
mocks::rasterizer target;
positioned_glyph glyphs_[] = {
{ 0, { 5.0f, 0.0f } }, { 1, { 7.0f, 0.0f } }, { 1, { 7.0f, 2.0f } }, { 0, { 5.0f, -3.0f } }, { 0, { 7.0f, 2.0f } }
};
positioned_glyphs_container_t glyphs = mkpodvector(glyphs_ + 0, glyphs_ + 5);
glyph_run gr(glyphs);
gr.begin_index = 0, gr.end_index = 3;
gr.font_ = f;
gr.offset = zero();
// ACT
e.render(target, gr, create_point(0.0f, 3.0f));
// ASSERT
assert_equal(3u, target.append_log.size());
assert_equal(0, target.append_log[0].second.x);
assert_equal(3, target.append_log[0].second.y);
assert_equal(c_outline_1, target.append_log[0].first->path);
assert_equal(5, target.append_log[1].second.x);
assert_equal(3, target.append_log[1].second.y);
assert_equal(c_outline_2, target.append_log[1].first->path);
assert_equal(12, target.append_log[2].second.x);
assert_equal(3, target.append_log[2].second.y);
assert_equal(c_outline_2, target.append_log[2].first->path);
// INIT
target.append_log.clear();
gr.begin_index = 1, gr.end_index = 5;
gr.font_ = f;
gr.offset = zero();
// ACT
e.render(target, gr, create_point(17.0f, 90.0f));
// ASSERT
assert_equal(4u, target.append_log.size());
assert_equal(17, target.append_log[0].second.x);
assert_equal(90, target.append_log[0].second.y);
assert_equal(c_outline_2, target.append_log[0].first->path);
assert_equal(24, target.append_log[1].second.x);
assert_equal(90, target.append_log[1].second.y);
assert_equal(c_outline_2, target.append_log[1].first->path);
assert_equal(31, target.append_log[2].second.x);
assert_equal(92, target.append_log[2].second.y);
assert_equal(c_outline_1, target.append_log[2].first->path);
assert_equal(36, target.append_log[3].second.x);
assert_equal(89, target.append_log[3].second.y);
assert_equal(c_outline_1, target.append_log[3].first->path);
}
test( SingleLineLayoutGlyphsAreRenderedInTheProperOrder1 )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, { L'w', 1 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(5, 0, c_outline_1),
mocks::glyph(7, 0, c_outline_2),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader, 0);
mocks::rasterizer target;
layout l1;
l1.process(simple_richtext("aww", "Arial", 10, regular, false, hint_strong), limit::none(), e);
// ACT
e.render(target, l1, create_point(0.0f, 0.0f));
// ASSERT
assert_equal(3u, target.append_log.size());
assert_equal(0, target.append_log[0].second.x);
assert_equal(4, target.append_log[0].second.y);
assert_equal(c_outline_1, target.append_log[0].first->path);
assert_equal(5, target.append_log[1].second.x);
assert_equal(4, target.append_log[1].second.y);
assert_equal(c_outline_2, target.append_log[1].first->path);
assert_equal(12, target.append_log[2].second.x);
assert_equal(4, target.append_log[2].second.y);
assert_equal(c_outline_2, target.append_log[2].first->path);
}
test( SingleLineLayoutGlyphsAreRenderedInTheProperOrder2 )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, { L'w', 1 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(5, 0, c_outline_1),
mocks::glyph(7, 0, c_outline_2),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm1, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader, 0);
mocks::rasterizer target;
layout l;
l.process(simple_richtext("wa", "Arial", 10, regular, false, hint_strong), limit::none(), e);
// ACT
e.render(target, l, create_point(0.0f, 0.0f));
// ASSERT
assert_equal(2u, target.append_log.size());
assert_equal(0, target.append_log[0].second.x);
assert_equal(1, target.append_log[0].second.y);
assert_equal(c_outline_2, target.append_log[0].first->path);
assert_equal(7, target.append_log[1].second.x);
assert_equal(1, target.append_log[1].second.y);
assert_equal(c_outline_1, target.append_log[1].first->path);
}
test( MultiLineLayoutGlyphsAreRenderedInTheProperOrder )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, { L'w', 1 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(5, 0, c_outline_1),
mocks::glyph(7, 0, c_outline_2),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader, 0);
mocks::rasterizer target;
layout l;
l.process(simple_richtext("aww\nww\na", "Arial", 10, regular, false, hint_strong), limit::none(), e);
// ACT
e.render(target, l, create_point(0.0f, 0.0f));
// ASSERT
assert_equal(6u, target.append_log.size());
assert_equal(0, target.append_log[0].second.x);
assert_equal(4, target.append_log[0].second.y);
assert_equal(c_outline_1, target.append_log[0].first->path);
assert_equal(5, target.append_log[1].second.x);
assert_equal(4, target.append_log[1].second.y);
assert_equal(c_outline_2, target.append_log[1].first->path);
assert_equal(12, target.append_log[2].second.x);
assert_equal(4, target.append_log[2].second.y);
assert_equal(c_outline_2, target.append_log[2].first->path);
assert_equal(0, target.append_log[3].second.x);
assert_equal(21, target.append_log[3].second.y);
assert_equal(c_outline_2, target.append_log[3].first->path);
assert_equal(7, target.append_log[4].second.x);
assert_equal(21, target.append_log[4].second.y);
assert_equal(c_outline_2, target.append_log[4].first->path);
assert_equal(0, target.append_log[5].second.x);
assert_equal(38, target.append_log[5].second.y);
assert_equal(c_outline_1, target.append_log[5].first->path);
}
test( TextLayoutIsPositionedAccordinglyToOffset )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = {
mocks::glyph(5.2, 0, c_outline_1),
};
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader, 0);
mocks::rasterizer target;
layout l;
l.process(simple_richtext("aaa", "Arial", 10, regular, false, hint_strong), limit::none(), e);
// ACT
e.render(target, l, create_point(7.7f, 13.2f));
// ASSERT
assert_equal(3u, target.append_log.size());
assert_equal(7, target.append_log[0].second.x);
assert_equal(17, target.append_log[0].second.y);
assert_equal(c_outline_1, target.append_log[0].first->path);
assert_equal(12, target.append_log[1].second.x);
assert_equal(17, target.append_log[1].second.y);
assert_equal(c_outline_1, target.append_log[1].first->path);
assert_equal(18, target.append_log[2].second.x);
assert_equal(17, target.append_log[2].second.y);
assert_equal(c_outline_1, target.append_log[2].first->path);
}
ignored_test( ReleasedFontIsNotifiedAboutImmidiatelyWhenNoCollectionIsRequired )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = { mocks::glyph(5.2, 0, c_outline_1), };
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
mocks::logging_text_engine e(loader, 0);
font::ptr f = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
void *pvf = f.get();
// ACT
f.reset();
// ASSERT
void *reference[] = { pvf, };
assert_equal(reference, e.deletion_log);
}
ignored_test( DestroyedFontReleasesUnderlyingAccessor )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = { mocks::glyph(5.2, 0, c_outline_1), };
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 1000, regular, false, hint_none),
mocks::font_accessor(c_fm2, indices, glyphs)),
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
mocks::logging_text_engine e(loader, 0);
font::ptr f[] = {
e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_none)),
e.create_font(font_descriptor::create("Arial", 11, regular, false, hint_none)),
e.create_font(font_descriptor::create("Arial", 11, regular, false, hint_strong)),
};
// ACT
f[0].reset();
// ASSERT
assert_equal(2u, *loader.allocated);
// ACT
f[1].reset();
// ASSERT
assert_equal(1u, *loader.allocated);
// ACT
f[2].reset();
// ASSERT
assert_equal(0u, *loader.allocated);
}
ignored_test( DestroyedAccessorGetsReacquiredOnFontReCreation )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = { mocks::glyph(5.2, 0, c_outline_1), };
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 1000, regular, false, hint_none),
mocks::font_accessor(c_fm2, indices, glyphs)),
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
mocks::logging_text_engine e(loader, 0);
font::ptr f = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_none));
f.reset();
// ACT
f = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_none));
// ASSERT
font_descriptor fd[] = {
font_descriptor::create("Arial", 1000, regular, false, hint_none),
font_descriptor::create("Arial", 1000, regular, false, hint_none),
};
assert_equal(fd, get_descriptors(loader.created_log));
}
ignored_test( ReleasedFontIsNotifiedUponOnPredefinedCollectionCycle )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = { mocks::glyph(5.2, 0, c_outline_1), };
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
make_pair(font_descriptor::create("Tahoma", 10, bold, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
mocks::logging_text_engine e1(loader, 2);
font::ptr f1 = e1.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
font::ptr f2 = e1.create_font(font_descriptor::create("Tahoma", 10, bold, false, hint_strong));
void *pvf1 = f1.get();
void *pvf2 = f2.get();
mocks::logging_text_engine e2(loader, 5);
font::ptr f3 = e2.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
void *pvf3 = f3.get();
// ACT
f1.reset();
e1.collect();
// ASSERT
assert_is_empty(e1.deletion_log);
assert_equal(3u, *loader.allocated);
// ACT
f2.reset();
e1.collect();
// ASSERT
void *reference1[] = { pvf1, };
assert_equal(reference1, e1.deletion_log);
assert_equal(2u, *loader.allocated);
// ACT
e1.collect();
// ASSERT
void *reference2[] = { pvf1, pvf2, };
assert_equal(reference2, e1.deletion_log);
assert_equal(1u, *loader.allocated);
// ACT
f3.reset();
e2.collect();
e2.collect();
e2.collect();
e2.collect();
// ASSERT
assert_is_empty(e2.deletion_log);
assert_equal(1u, *loader.allocated);
// ACT
e2.collect();
// ASSERT
void *reference3[] = { pvf3, };
assert_equal(reference3, e2.deletion_log);
assert_equal(0u, *loader.allocated);
}
test( GarbageFontIsReusedForTheSameRequest )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = { mocks::glyph(5.2, 0, c_outline_1), };
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
make_pair(font_descriptor::create("Tahoma", 10, bold, false, hint_strong),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
mocks::logging_text_engine e(loader, 1);
font::ptr f1 = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
font::ptr f2 = e.create_font(font_descriptor::create("Tahoma", 10, bold, false, hint_strong));
void *pvf1 = f1.get();
void *pvf2 = f2.get();
loader.created_log.clear();
f1.reset();
f2.reset();
// ACT
f2 = e.create_font(font_descriptor::create("Tahoma", 10, bold, false, hint_strong));
// ASSERT
assert_equal(pvf2, f2.get());
assert_is_empty(loader.created_log);
// ACT
f1 = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_strong));
// ASSERT
assert_equal(pvf1, f1.get());
assert_is_empty(loader.created_log);
// ACT
e.collect();
// ASSERT
assert_equal(2u, *loader.allocated);
}
test( DestructionOfEngineWithNonEmptyGarbageDestroysGarbageFonts )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = { mocks::glyph(5.2, 0, c_outline_1), };
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 10, regular, false, hint_none),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
scoped_ptr<mocks::logging_text_engine> e(new mocks::logging_text_engine(loader, 1));
font::ptr f1 = e->create_font(font_descriptor::create("Arial", 101, regular, false, hint_none));
font::ptr f2 = e->create_font(font_descriptor::create("Arial", 15, regular, false, hint_none));
f1.reset();
f2.reset();
// ACT
e.reset();
// ASSERT
assert_equal(0u, *loader.allocated);
}
test( DifferentFontsHaveDistinctRasterCaches )
{
// INIT
mocks::font_accessor::char_to_index indices[] = { { L'a', 0 }, };
mocks::font_accessor::glyph glyphs[] = { mocks::glyph(5.2, 0, c_outline_1), };
pair<font_descriptor, mocks::font_accessor> fonts[] = {
make_pair(font_descriptor::create("Arial", 1000, regular, false, hint_none),
mocks::font_accessor(c_fm2, indices, glyphs)),
};
mocks::fonts_loader loader(fonts);
text_engine<mocks::rasterizer> e(loader, 1);
mocks::rasterizer target;
font::ptr f1 = e.create_font(font_descriptor::create("Arial", 101, regular, false, hint_none));
font::ptr f2 = e.create_font(font_descriptor::create("Arial", 15, regular, false, hint_none));
font::ptr f3 = e.create_font(font_descriptor::create("Arial", 10, regular, false, hint_none));
// ACT
e.render_glyph(target, *f1, 0, 19.0f, -13.49f);
e.render_glyph(target, *f2, 0, 19.0f, -13.0f);
e.render_glyph(target, *f3, 0, 19.0f, -13.0f);
// ASSERT
assert_equal(3u, target.append_log.size());
assert_not_equal(target.append_log[1].first, target.append_log[0].first);
assert_not_equal(target.append_log[2].first, target.append_log[1].first);
assert_not_equal(target.append_log[2].first, target.append_log[0].first);
}
end_test_suite
}
}
|
yashgolwala/Software_Measurement_Team_M
|
ProjectSourceCode/Apache Commons Math v3.5/src/main/java/org/apache/commons/math3/geometry/spherical/twod/Vertex.java
|
version https://git-lfs.github.com/spec/v1
oid sha256:816bf5775a03c5c0e816af83c84e4bb494f50200f465512a076a1543b698cc6b
size 3649
|
eluinstra/fs-core
|
src/main/java/dev/luin/file/server/core/KeyStoreManager.java
|
/*
* Copyright 2020 E.Luinstra
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.luin.file.server.core;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.val;
import lombok.var;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class KeyStoreManager
{
public enum KeyStoreType {JCEKS, JKS, DKS, PKCS11, PKCS12};
private static Map<String,KeyStore> keystores = new ConcurrentHashMap<>();
public static KeyStore getKeyStore(@NonNull final KeyStoreType type, @NonNull final String path, @NonNull final String password) throws GeneralSecurityException, IOException
{
if (!keystores.containsKey(path))
keystores.put(path,loadKeyStore(type,path,password));
return keystores.get(path);
}
private static KeyStore loadKeyStore(final KeyStoreType type, final String location, final String password) throws GeneralSecurityException, IOException
{
//location = ResourceUtils.getURL(SystemPropertyUtils.resolvePlaceholders(location)).getFile();
try (val in = getInputStream(location))
{
val keyStore = KeyStore.getInstance(type.name());
keyStore.load(in,password.toCharArray());
return keyStore;
}
}
private static InputStream getInputStream(final String location) throws FileNotFoundException
{
try
{
return new FileInputStream(location);
}
catch (FileNotFoundException e)
{
var result = KeyStoreManager.class.getResourceAsStream(location);
if (result == null)
result = KeyStoreManager.class.getResourceAsStream("/" + location);
if (result == null)
throw e;
return result;
}
}
}
|
IsaacAsante/hackerrank
|
Problem Solving/Algorithms/Bit Manipulation/Lonely Integer/lonely integer.cpp
|
<reponame>IsaacAsante/hackerrank<filename>Problem Solving/Algorithms/Bit Manipulation/Lonely Integer/lonely integer.cpp
/* Author: <NAME>
* HackerRank URL for this exercise: https://www.hackerrank.com/challenges/lonely-integer/problem
* Original video explanation: https://www.youtube.com/watch?v=la980b2X268
* Last verified on: 20 February, 2021
*/
/* IMPORTANT:
* This code is meant to be used as a solution on HackerRank (link above).
* It is not meant to be executed as a standalone program.
*/
// Complete the lonelyinteger function below.
int lonelyinteger(vector<int>& a) {
sort(a.begin(), a.end());
int i = 0;
while ((i <= a.size() - 1) && !(a[i] ^ a[i + 1])) {
i += 2;
}
cout << a[i] << endl;
return a[i];
}
|
lemkova/Yorozuya
|
library/ATF/_unmannedtrader_regist_item_error_result_zocl.hpp
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
#pragma pack(push, 1)
struct _unmannedtrader_regist_item_error_result_zocl
{
char byRet;
unsigned __int16 wItemSerial;
unsigned int dwRetParam1;
};
#pragma pack(pop)
END_ATF_NAMESPACE
|
VerkhovtsovPavel/BSUIR_Labs
|
Labs/SAiMMod/SAiMMod-4/src/main/Main.java
|
<filename>Labs/SAiMMod/SAiMMod-4/src/main/Main.java
package main;
import other.Processor;
import other.TimePeriodGenerator;
public class Main {
private static Processor[] querySystems;
private static TimePeriodGenerator taskInterval;
private static int countOfQuerySystems = 3;
private static long GeneratedTaskCounter;
private static double intensityOfService = 4.5;
private static double intensityOfTasks = 12;
private static int workHours = 10000;
public static void main(String[] args) {
long workTime = workHours * 3600;
taskInterval = new TimePeriodGenerator(intensityOfTasks);
createQuerySystems();
int nextTaskInterval = taskInterval.getInterval();
startWork(nextTaskInterval, workTime);
statictic(workTime);
}
private static void statictic(long workTime) {
System.out.println("Work time> " +workTime/3600+" hours");
System.out.println("Generated task> " + GeneratedTaskCounter);
System.out.println("Processed task> " + Processor.getProcessedTask());
System.out.println("Absolutely bandwidth> "
+ (double) Processor.getProcessedTask() / workHours
+ " task/hours");
System.out.println("Average queue length> "
+ (float) Processor.getCountTasksInQueue() / (workTime * countOfQuerySystems));
System.out.println("Average tasks in system> "
+ (float) Processor.getCountTasksInSystem() / (workTime * countOfQuerySystems));
System.out.println("Average time in queue> "
+ Processor.getAverageTimeInQueue() + " hours");
System.out.println("Average time in system> "
+ Processor.getAverageTimeInSystem() + " hours");
}
private static void createQuerySystems() {
querySystems = new Processor[countOfQuerySystems];
for (int i = 0; i < countOfQuerySystems; i++) {
querySystems[i] = new Processor(intensityOfService);
}
}
private static void startWork(int nextTaskInterval, long workTime) {
for (int i = 0; i < workTime; i++) {
if (nextTaskInterval == 0) {
querySystems[(int) (GeneratedTaskCounter % countOfQuerySystems)]
.setTask(GeneratedTaskCounter);
nextTaskInterval = taskInterval.getInterval();
GeneratedTaskCounter++;
}
nextTaskInterval--;
decrimentQuerySystem();
}
}
private static void decrimentQuerySystem() {
for (Processor proc : querySystems) {
proc.decrimentTimer();
}
}
}
|
shaojiankui/iOS10-Runtime-Headers
|
PrivateFrameworks/FuseUI.framework/MusicContextualActionsConfiguration.h
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/FuseUI.framework/FuseUI
*/
@interface MusicContextualActionsConfiguration : NSObject <MusicClientContextConsuming> {
bool _allowsAddToPlaylistActions;
bool _allowsCreateGeniusPlaylist;
bool _allowsLibraryAddRemoveActions;
bool _allowsLibraryKeepLocalActions;
bool _allowsShareActions;
bool _allowsShowGeniusPlaylistDetail;
bool _allowsShowInStoreActions;
bool _allowsStartRadioActions;
bool _allowsUpNextActions;
MusicClientContext * _clientContext;
NSArray * _customJSActionTitles;
id /* block */ _didDismissHandler;
MusicEntityValueContext * _entityValueContext;
NSDictionary * _extraInfo;
bool _includesPostActionForDefaultContainer;
<MusicEntityProviding> * _libraryAddRemoveOverrideItemEntityProvider;
long long _preferredAlertControllerStyle;
MusicViewControllerPresenter * _presenter;
}
@property (nonatomic) bool allowsAddToPlaylistActions;
@property (nonatomic) bool allowsCreateGeniusPlaylist;
@property (nonatomic) bool allowsLibraryAddRemoveActions;
@property (nonatomic) bool allowsLibraryKeepLocalActions;
@property (nonatomic) bool allowsShareActions;
@property (nonatomic) bool allowsShowGeniusPlaylistDetail;
@property (nonatomic) bool allowsShowInStoreActions;
@property (nonatomic) bool allowsStartRadioActions;
@property (nonatomic) bool allowsUpNextActions;
@property (nonatomic, retain) SKUIClientContext *clientContext;
@property (nonatomic, retain) NSArray *customJSActionTitles;
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (nonatomic, copy) id /* block */ didDismissHandler;
@property (nonatomic, retain) MusicEntityValueContext *entityValueContext;
@property (nonatomic, retain) NSDictionary *extraInfo;
@property (readonly) unsigned long long hash;
@property (nonatomic) bool includesPostActionForDefaultContainer;
@property (nonatomic, retain) <MusicEntityProviding> *libraryAddRemoveOverrideItemEntityProvider;
@property (nonatomic) long long preferredAlertControllerStyle;
@property (nonatomic, readonly) MusicViewControllerPresenter *presenter;
@property (readonly) Class superclass;
+ (id)defaultEntityValueContext;
- (void).cxx_destruct;
- (void)_didSelectHeaderFromAlertController:(id)arg1;
- (void)_getAdditionalPresentationHandler:(id /* block */*)arg1 shouldDismissHandler:(id /* block */*)arg2 forAlertController:(id)arg3;
- (struct { long long x1; unsigned long long x2; })_headerSelectionHandlingInformation;
- (id)_newContextualActionsAlertController;
- (bool)allowsAddToPlaylistActions;
- (bool)allowsCreateGeniusPlaylist;
- (bool)allowsLibraryAddRemoveActions;
- (bool)allowsLibraryKeepLocalActions;
- (bool)allowsShareActions;
- (bool)allowsShowGeniusPlaylistDetail;
- (bool)allowsShowInStoreActions;
- (bool)allowsStartRadioActions;
- (bool)allowsUpNextActions;
- (id)clientContext;
- (void)configureWithPresentationViewController:(id)arg1 popoverTarget:(id)arg2;
- (id)customJSActionTitles;
- (id /* block */)didDismissHandler;
- (id)entityValueContext;
- (id)extraInfo;
- (bool)includesPostActionForDefaultContainer;
- (id)init;
- (id)libraryAddRemoveOverrideItemEntityProvider;
- (id)newShareViewController;
- (id)newViewController;
- (long long)preferredAlertControllerStyle;
- (id)presenter;
- (void)setAllowsAddToPlaylistActions:(bool)arg1;
- (void)setAllowsCreateGeniusPlaylist:(bool)arg1;
- (void)setAllowsLibraryAddRemoveActions:(bool)arg1;
- (void)setAllowsLibraryKeepLocalActions:(bool)arg1;
- (void)setAllowsShareActions:(bool)arg1;
- (void)setAllowsShowGeniusPlaylistDetail:(bool)arg1;
- (void)setAllowsShowInStoreActions:(bool)arg1;
- (void)setAllowsStartRadioActions:(bool)arg1;
- (void)setAllowsUpNextActions:(bool)arg1;
- (void)setClientContext:(id)arg1;
- (void)setCustomJSActionTitles:(id)arg1;
- (void)setDidDismissHandler:(id /* block */)arg1;
- (void)setEntityValueContext:(id)arg1;
- (void)setExtraInfo:(id)arg1;
- (void)setIncludesPostActionForDefaultContainer:(bool)arg1;
- (void)setLibraryAddRemoveOverrideItemEntityProvider:(id)arg1;
- (void)setPreferredAlertControllerStyle:(long long)arg1;
@end
|
immbudden/buddeen
|
node_modules/@material-ui/icons/DevicesOtherTwoTone.js
|
<reponame>immbudden/buddeen
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _react = _interopRequireDefault(require("react"));
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _default = (0, _createSvgIcon.default)(_react.default.createElement(_react.default.Fragment, null, _react.default.createElement("path", {
fill: "none",
d: "M0 0h24v24H0V0z"
}), _react.default.createElement("g", null, _react.default.createElement("path", {
d: "M17 10h4v8h-4z",
opacity: ".3"
}), _react.default.createElement("circle", {
cx: "11",
cy: "16",
r: "1.5",
opacity: ".3"
}), _react.default.createElement("path", {
d: "M3 6h18V4H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h4v-2H3V6z"
}), _react.default.createElement("path", {
d: "M22 8h-6c-.5 0-1 .5-1 1v10c0 .5.5 1 1 1h6c.5 0 1-.5 1-1V9c0-.5-.5-1-1-1zm-1 10h-4v-8h4v8zM13 12H9v1.78c-.61.55-1 1.33-1 2.22s.39 1.67 1 2.22V20h4v-1.78c.61-.55 1-1.34 1-2.22s-.39-1.67-1-2.22V12zm-2 5.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"
}))), 'DevicesOtherTwoTone');
exports.default = _default;
|
marpme/lib-ledger-core
|
api/core/react-native/LibLedgerCore/android/src/main/java/com/ledger/reactnative/GetEthreumLikeWalletCallbackImpl.java
|
package com.ledger.reactnative;
import com.facebook.react.bridge.ReactApplicationContext;
public class GetEthreumLikeWalletCallbackImpl extends co.ledger.core.GetEthreumLikeWalletCallback {
private ReactApplicationContext reactContext;
public GetEthreumLikeWalletCallbackImpl(ReactApplicationContext reactContext) {
this.reactContext = reactContext;
}
public void onSuccess(co.ledger.core.EthereumLikeWallet wallet, boolean isCreated) {
}
public void onError(co.ledger.core.Error error) {
}
}
|
saulmaldonado/ds-and-algorithms
|
strings/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.js
|
<gh_stars>0
/**
* @param {string} s
* @return {number}
*/
function lengthOfLongestSubstring(s) {
const n = s.length;
let maxLength = 0;
const indexMap = {};
let j = 0;
for (let i = 0; i < n; i++) {
const curr = s[i];
if (indexMap[curr]) {
j = Math.max(indexMap[curr], j);
}
const currLength = i - j + 1;
maxLength = Math.max(currLength, maxLength);
indexMap[curr] = i + 1;
}
return maxLength;
}
|
DarthUdp/yasl
|
yasl_conf.h
|
#ifndef YASL_YASL_CONF_H_
#define YASL_YASL_CONF_H_
#include <inttypes.h>
#if defined __GNUC__ || defined __clang__
#define YASL_DEPRECATE __attribute__((deprecated))
#elif defined _MSC_VER
#define YASL_DEPRECATE __declspec(deprecated)
#else
#define YASL_DEPRECATE
#endif
#if defined __GNUC__ || defined __clang__
#define YASL_FORMAT_CHECK __attribute__((format (printf, 2, 3)))
#else
#define YASL_FORMAT_CHECK
#endif
#if defined __GNUC__ || defined __clang__
#define YASL_NORETURN __attribute__((noreturn))
#elif defined _MSC_VER
#define YASL_NORETURN __declspec(noreturn)
#else
#define YASL_NORETURN
#endif
#if defined(WIN32) || defined(_WIN32)
#define YASL_USE_WIN
#elif defined(__unix__)
#define YASL_USE_UNIX
#elif defined(__APPLE__)
#define YASL_USE_APPLE
#endif
// @@ yasl_float
// Which floating point type YASL will use.
#define yasl_float double
// @@ yasl_int
// Which integral type YASL will use.
#define yasl_int int64_t
// @@ STACK_SIZE
// How big the stack is for the YASL VM
#define STACK_SIZE 1024
// @@ YASL_PATH_SEP
// What to use to separate paths.
#define YASL_PATH_SEP ';'
// @@ YASL_PATH_MARK
// What to use to use to mark the substitution in the path.
#define YASL_PATH_MARK '?'
// @@ YASL_DEFAULT_CPATH
// Where to search for C modules.
#if defined(YASL_USE_UNIX) || defined(YASL_USE_APPLE)
#define YASL_DEFAULT_CPATH "/usr/local/lib/yasl/lib?.so;" "./?.so;"
#define YASL_DEFAULT_PATH "/usr/local/lib/yasl/?.yasl;" "./?.yasl;"
#endif
#ifndef YASL_DEFAULT_CPATH
#define YASL_DEFAULT_CPATH ""
#endif
#ifndef YASL_DEFAULT_PATH
#define YASL_DEFAULT_PATH ""
#endif
#endif
|
jianoaix/ray
|
python/ray/train/tests/test_utils.py
|
<filename>python/ray/train/tests/test_utils.py<gh_stars>0
from pathlib import Path
from ray.train._internal.utils import construct_path
def test_construct_path():
assert construct_path(Path("/a"), Path("/b")) == Path("/a")
assert construct_path(Path("/a"), Path("~/b")) == Path("/a")
assert construct_path(Path("/a"), Path("b")) == Path("/a")
assert construct_path(Path("~/a"), Path("~/b")) == Path("~/a").expanduser()
assert construct_path(Path("~/a"), Path("/b")) == Path("~/a").expanduser()
assert construct_path(Path("~/a"), Path("b")) == Path("~/a").expanduser()
assert construct_path(Path("a"), Path("/b")) == Path("/b/a")
assert construct_path(Path("a"), Path("~/b")) == Path("~/b/a").expanduser()
assert construct_path(Path("a"), Path("b")) == Path("b/a").resolve()
if __name__ == "__main__":
import pytest
import sys
sys.exit(pytest.main(["-v", "-x", __file__]))
|
shunp/three.js
|
examples/jsm/lines/LineGeometry.js
|
<reponame>shunp/three.js<filename>examples/jsm/lines/LineGeometry.js
/**
* @author WestLangley / http://github.com/WestLangley
*
*/
import { LineSegmentsGeometry } from "../lines/LineSegmentsGeometry.js";
var LineGeometry = function () {
LineSegmentsGeometry.call( this );
this.type = 'LineGeometry';
};
LineGeometry.prototype = Object.assign( Object.create( LineSegmentsGeometry.prototype ), {
constructor: LineGeometry,
isLineGeometry: true,
setPositions: function ( array ) {
// converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format
var length = array.length - 3;
var points = new Float32Array( 2 * length );
for ( var i = 0; i < length; i += 3 ) {
points[ 2 * i ] = array[ i ];
points[ 2 * i + 1 ] = array[ i + 1 ];
points[ 2 * i + 2 ] = array[ i + 2 ];
points[ 2 * i + 3 ] = array[ i + 3 ];
points[ 2 * i + 4 ] = array[ i + 4 ];
points[ 2 * i + 5 ] = array[ i + 5 ];
}
LineSegmentsGeometry.prototype.setPositions.call( this, points );
return this;
},
setColors: function ( array ) {
// converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format
var length = array.length - 3;
var colors = new Float32Array( 2 * length );
for ( var i = 0; i < length; i += 3 ) {
colors[ 2 * i ] = array[ i ];
colors[ 2 * i + 1 ] = array[ i + 1 ];
colors[ 2 * i + 2 ] = array[ i + 2 ];
colors[ 2 * i + 3 ] = array[ i + 3 ];
colors[ 2 * i + 4 ] = array[ i + 4 ];
colors[ 2 * i + 5 ] = array[ i + 5 ];
}
LineSegmentsGeometry.prototype.setColors.call( this, colors );
return this;
},
fromLine: function ( line ) {
var geometry = line.geometry;
if ( geometry.isGeometry ) {
this.setPositions( geometry.vertices );
} else if ( geometry.isBufferGeometry ) {
this.setPositions( geometry.attributes.position.array ); // assumes non-indexed
}
// set colors, maybe
return this;
},
copy: function ( /* source */ ) {
// todo
return this;
}
} );
export { LineGeometry };
|
mshafiei/DifferentiableSolver
|
Smoothness_test/Hyperparam_1px_grad_descent.py
|
import os
import jax
from jaxopt._src import gradient_descent
import tqdm
import jax.numpy as np
from jax import random
import cvgutils.Image as cvgim
import cvgutils.Viz as cvgviz
from jaxopt.implicit_diff import custom_fixed_point
import argparse
import matplotlib.pyplot as plt
from jax.experimental import optimizers
from jax import grad, jit, vmap, value_and_grad
# solve interpolation by grad decent solver
# define implicit_jax_grad
# evaluate implicit_jax_grad(x_0)
# plot
# write the same functions for 3pix
# write the same functions for 3pix with smoothness term
# write the same functions for 2d
# create stencil
i1 = 0
i2 = 1
alpha_gt = 0.8
lr = 0.6
maxiter=20
x_0=0.
def f_t(x,alpha):
return (1-alpha)*(x-i1) ** 2 + alpha * (x-i2) ** 2
F = jax.grad(f_t,argnums=0)
@custom_fixed_point(F)
def x(alpha):
g_f_t = jax.grad(f_t,argnums=0)
x = x_0
for _ in range(maxiter):
x = x - lr * g_f_t(x,alpha)
return x
def f_v(alpha):
return (x(alpha) - x(alpha_gt))**2
def finite_grad(alpha,delta):
d_r = f_v(alpha+delta/2)
d_l = f_v(alpha-delta/2)
return (d_r - d_l) / delta
def implicit_analytic_grad(alpha):
return 2*(x(alpha) - x(alpha_gt)) * (-i1 + i2)
step_size = 0.5
opt_init, opt_update, get_params = optimizers.adam(step_size)
opt_state = opt_init(params)
implicit_autodiff_grad = jax.grad(f_v)
grid = np.linspace(0.1,2,20)
fd_val = np.stack([finite_grad(i,0.01) for i in tqdm.tqdm(grid)],axis=-1)
analytic_val = np.stack([implicit_analytic_grad(i) for i in tqdm.tqdm(grid)],axis=-1)
autodiff_val = np.stack([implicit_autodiff_grad(i) for i in tqdm.tqdm(grid)],axis=-1)
dxl_fd = np.stack((fd_val,np.ones_like(fd_val)),axis=-1)
dxl_analytic = np.stack((analytic_val,np.ones_like(analytic_val)),axis=-1)
dxl_autodiff = np.stack((autodiff_val,np.ones_like(autodiff_val)),axis=-1)
dxl_fd = dxl_fd / np.linalg.norm(dxl_fd,axis=-1)[:,None] * np.linalg.norm(fd_val[:,None],axis=1,keepdims=True)
dxl_analytic = dxl_analytic / np.linalg.norm(dxl_analytic,axis=-1)[:,None] * np.linalg.norm(analytic_val[:,None],axis=1,keepdims=True)
dxl_autodiff = dxl_autodiff / np.linalg.norm(dxl_autodiff,axis=-1)[:,None] * np.linalg.norm(analytic_val[:,None],axis=1,keepdims=True)
loss_val = np.stack([f_v(i) for i in tqdm.tqdm(grid)])
plt.plot(grid,loss_val,'r')
for i in range(grid.shape[0]):
plt.arrow(grid[i],loss_val[i],dxl_fd[i,1],dxl_fd[i,0],color='lightgreen')
plt.arrow(grid[i],loss_val[i],dxl_analytic[i,1],dxl_analytic[i,0],color='blue')
plt.arrow(grid[i],loss_val[i],dxl_autodiff[i,1],dxl_autodiff[i,0],color='blue')
plt.legend(['Validation loss','Finite difference','Analytic gradient','Autodiff gradient'])
# plt.legend(['Validation loss','Finite difference'])
plt.savefig('out/plot.pdf')
plt.close()
|
intellisysdcorp/covid-safe-paths
|
app/components/DR/ActivityIndicator.js
|
import React from 'react';
import { ActivityIndicator } from 'react-native';
import Colors from '../../constants/colors';
const activityIndicatorLoadingView = center => {
//making a view to show to while loading the webpage
return (
<ActivityIndicator
color={Colors.BLUE_RIBBON}
size='large'
style={{
backgroundColor: Colors.WHITE,
flex: 1,
justifyContent: center ? 'center' : 'flex-start',
}}
/>
);
};
export default activityIndicatorLoadingView;
|
aulonm/okr-tracker
|
src/store/actions/reset_state.js
|
<reponame>aulonm/okr-tracker
import { firestoreAction } from 'vuexfire';
export default firestoreAction(async ({ unbindFirestoreRef, state, commit }) => {
commit('SET_ACTIVE_ITEM_REF', null);
state.organizationsUnsubscribe();
state.departmentsUnsubscribe();
state.productsUnsubscribe();
commit('SET_COLLECTION', { type: 'organizations', data: [] });
commit('SET_COLLECTION', { type: 'departments', data: [] });
commit('SET_COLLECTION', { type: 'products', data: [] });
return Promise.all(Object.keys(state).map(unbindFirestoreRef));
});
|
gsrivast31/devdesign
|
packages/devdesign-rss/package.js
|
Package.describe({summary: "DevDesign RSS package"});
Npm.depends({rss: "0.3.2"});
Package.onUse(function (api) {
api.use(['devdesign-base', 'devdesign-lib'], ['server']);
api.add_files(['lib/server/rss.js', 'lib/server/routes.js'], ['server']);
api.export(['serveRSS']);
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.