file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
connection.go | _, result = conn.Write([]byte{msgTag})
}
if result == nil {
sizeBytes := v.scratch[:4]
binary.BigEndian.PutUint32(sizeBytes, uint32(len(msgBytes)+4))
_, result = conn.Write(sizeBytes)
if result == nil && len(msgBytes) > 0 {
size := 8192 // Max msg size, consistent with how the server works
pos := 0
... | authSendMD5Password | identifier_name | |
connection.go | , conn net.Conn) error {
var result error = nil
msgBytes, msgTag := msg.Flatten()
if msgTag != 0 {
_, result = conn.Write([]byte{msgTag})
}
if result == nil {
sizeBytes := v.scratch[:4]
binary.BigEndian.PutUint32(sizeBytes, uint32(len(msgBytes)+4))
_, result = conn.Write(sizeBytes)
if result == nil ... | {
passwd = ""
} | conditional_block | |
connection.go | return newTransaction(ctx, v, opts)
}
// Close closes a connection to the Vertica DB. After calling close, you shouldn't use this connection anymore.
// From interface: sql.driver.Conn
func (v *connection) Close() error {
connectionLogger.Trace("connection.Close()")
v.sendMessage(&msgs.FETerminateMsg{})
var resu... |
// Prepare returns a prepared statement, bound to this connection.
// From interface: sql.driver.Conn
func (v *connection) Prepare(query string) (driver.Stmt, error) {
return v.PrepareContext(context.Background(), query)
}
// Ping implements the Pinger interface for connection. Use this to check for a valid connect... | {
s, err := newStmt(v, query)
if err != nil {
return nil, err
}
if v.usePreparedStmts {
if err = s.prepareAndDescribe(); err != nil {
return nil, err
}
}
return s, nil
} | identifier_body |
connection.go | ()")
return newTransaction(ctx, v, opts)
}
// Close closes a connection to the Vertica DB. After calling close, you shouldn't use this connection anymore.
// From interface: sql.driver.Conn
func (v *connection) Close() error {
connectionLogger.Trace("connection.Close()")
v.sendMessage(&msgs.FETerminateMsg{})
var... | // Read OAuth access token flag.
result.oauthaccesstoken = result.connURL.Query().Get("oauth_access_token")
// Read connection load balance flag.
loadBalanceFlag := result.connURL.Query().Get("connection_load_balance")
// Read connection failover flag.
backupHostsStr := result.connURL.Query().Get("backup_server... | random_line_split | |
gensynet.py | groupby = int(254 * .01 *netp)
subnets += math.ceil(subtotal/groupby)
if (sanity_percent < 100):
|
return subnets
def get_default_dev_distro(nodect, printout=True):
"""Prints device type breakdowns using default ratios and returns a count of each device."""
if (printout):
print("Default Device Role Distribution for {} nodes".format(nodect))
dev_breakdown = {
'Business workstation':... | return -1 | conditional_block |
gensynet.py | groupby = int(254 * .01 *netp)
subnets += math.ceil(subtotal/groupby)
if (sanity_percent < 100):
return -1
return subnets
def get_default_dev_distro(nodect, printout=True):
"""Prints device type breakdowns using default ratios and returns a count of each device."""
if (printout):
... | (count, minimum, maximum):
'''Returns an array of host counts (where index = subnet), or None if the input is ridiculous.'''
subnets = []
nodes_left = count
# I mean, this is tested for very large values of count; I haven't tested very small numbers yet.
if count <= 0 or minimum > count or maximum ... | randomize_subnet_breakdown | identifier_name |
gensynet.py | : roles.copy()
})
host_counter.append(grouped_nodes)
if VERBOSE:
print("Initialized subnet {} with {} hosts starting at {}".format(len(jsons), grouped_nodes, start_ip))
q -= 1
if r > 0:
if class_c == 0:
class_b ... | random_line_split | ||
gensynet.py | " : roles.copy()
})
unlabeled_hosts.append(n)
if VERBOSE:
print("start_ip: {}\t number of hosts: {}\t".format(jsons[-1]['start_ip'], jsons[-1]['hosts']))
# divvy up the roles, now that the subnets are defined
labeled_hosts = 0
for dev in dev_div:
dev_... | global VERBOSE, VERSION, NET_SUMMARY, OLDVERSION
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', help='Provide program feedback', action="store_true")
parser.add_argument('-s', '--summarize', help='Prints network configurations to output', action="store_true")
parser.add_argume... | identifier_body | |
base_command.py | _api = settings.JUXINLI_CONF['access_report_data_api']
self._access_raw_data_api = settings.JUXINLI_CONF['access_raw_data_api']
self._access_report_token_api = settings.JUXINLI_CONF['access_report_token_api']
self._access_e_business_raw_data_api = settings.JUXINLI_CONF['access_e_business_raw_dat... | if len(parts) != 2:
TkLog().error("field format error %s" % (field))
return None
res = res[parts[0]][int(parts[1])]
else:
res = res[field]
return res
except Exception, e:
... | ield.split(":")
| identifier_name |
base_command.py | _report_data_api = settings.JUXINLI_CONF['access_report_data_api']
self._access_raw_data_api = settings.JUXINLI_CONF['access_raw_data_api']
self._access_report_token_api = settings.JUXINLI_CONF['access_report_token_api']
self._access_e_business_raw_data_api = settings.JUXINLI_CONF['access_e_busi... | '''
req1 = urllib2.Request(url=url)
html = urllib2.urlopen(req1).read().decode('utf-8')
return json.loads(html.encode("utf-8"))
def _get_token(self):
'''
生成一个新的用来获取数据的token 失败返回None
'''
url = u"%s?client_secret=%s&hours=24&org_name=%s" % (self._ac... |
def _open_url(self, url):
'''
get http request return json | random_line_split |
base_command.py | _api = settings.JUXINLI_CONF['access_report_data_api']
self._access_raw_data_api = settings.JUXINLI_CONF['access_raw_data_api']
self._access_report_token_api = settings.JUXINLI_CONF['access_report_token_api']
self._access_e_business_raw_data_api = settings.JUXINLI_CONF['access_e_business_raw_dat... | 根据data_type来判断是map还是list
'''
if adaptor["data_type"] == "list": #data_list是列表数据
for record in data_list:
ret_code = self._save_single_obj(record, cls, user, adaptor, version, parent)
if ret_code != 0:
return ret_code
e... | _by('-id')[:1]
if len(objs) == 1:
version = objs[0].version
TkLog().info("update %s version %d" % (adaptor["name"], version))
data_list = self._get_data_from_path(data, adaptor["path"])
if not data_list:
TkLog().warn("data not found %s:... | identifier_body |
base_command.py | _api = settings.JUXINLI_CONF['access_report_data_api']
self._access_raw_data_api = settings.JUXINLI_CONF['access_raw_data_api']
self._access_report_token_api = settings.JUXINLI_CONF['access_report_token_api']
self._access_e_business_raw_data_api = settings.JUXINLI_CONF['access_e_business_raw_dat... | if not data_list:
TkLog().warn("data not found %s:%s" % (adaptor["name"], adaptor["path"]))
#return -4 #just skip
ret_code = self._save_obj(data_list, cls, user, adaptor, version)
if ret_code != 0:
return ret_code
return RETURN_SUCCESS... | data, adaptor["path"])
| conditional_block |
rights.go |
// EndorsingRight holds simplified information about the right to endorse
// a specific Tezos block
type EndorsingRight struct {
Delegate string
Level int64
Power int
}
func (r EndorsingRight) Address() tezos.Address {
a, _ := tezos.ParseAddress(r.Delegate)
return a
}
type StakeInfo struct {
ActiveStake... | {
type FullBakingRight struct {
Delegate string `json:"delegate"`
Level int64 `json:"level"`
Priority int `json:"priority"` // until v011
Round int `json:"round"` // v012+
}
var rr FullBakingRight
err := json.Unmarshal(data, &rr)
r.Delegate = rr.Delegate
r.Level = rr.Level
r.Round = rr.Pr... | identifier_body | |
rights.go | 012+
// Slashed []??? "slashed_deposits"
}
type SnapshotIndex struct {
Cycle int64 // the requested cycle that contains rights from the snapshot
Base int64 // the cycle where the snapshot happened
Index int // the index inside base where snapshot happened
}
type SnapshotOwners struct {
Cycle int64 `j... |
for _, r := range list {
rights = append(rights, EndorsingRight{
Level: r.Level,
Delegate: r.Delegate,
Power: len(r.Slots),
})
}
} else {
type V12Rights struct {
Level int64 `json:"level"`
Delegates []struct {
Delegate string `json:"delegate"`
Power int `json:"end... | {
return nil, err
} | conditional_block |
rights.go | dec.UseNumber()
unpacked := make([]any, 0)
err := dec.Decode(&unpacked)
if err != nil {
return err
}
return r.decode(unpacked)
}
func (r *SnapshotRoll) decode(unpacked []any) error {
if l := len(unpacked); l != 2 {
return fmt.Errorf("SnapshotRoll: invalid json array len %d", l)
}
id, err := strconv.ParseIn... | idx.Base = p.SnapshotBaseCycle(cycle)
idx.Index = info.RollSnapshot
} else {
idx.Cycle = cycle
idx.Base = p.SnapshotBaseCycle(cycle) | random_line_split | |
rights.go | 012+
// Slashed []??? "slashed_deposits"
}
type SnapshotIndex struct {
Cycle int64 // the requested cycle that contains rights from the snapshot
Base int64 // the cycle where the snapshot happened
Index int // the index inside base where snapshot happened
}
type SnapshotOwners struct {
Cycle int64 `j... | (ctx context.Context, id BlockID, p *Params) ([]EndorsingRight, error) {
u := fmt.Sprintf("chains/main/blocks/%s/helpers/endorsing_rights?all=true", id)
rights := make([]EndorsingRight, 0)
// Note: future cycles are seen from current protocol (!)
if p.Version < 12 && p.IsPreIthacaNetworkAtStart() {
type Rights st... | ListEndorsingRights | identifier_name |
lib.rs | let mut buf = [0; 80];
buf.copy_from_slice(&secretbox::seal(skey.as_ref(), &nonce, &passwd_key));
*self = SKey::Cipher(buf);
}
}
}
fn decrypt(&mut self, passwd: Passwd, salt: pwhash::Salt, nonce: secretbox::Nonce) -> Result<(), Error> {
... | let passwd = Passwd::prompt_new()
.chain_err(|| skey_path )?;
let (pkey_file, mut skey_file) = SecretKeyFile::new();
| random_line_split | |
lib.rs | )
.ok_or(ErrorKind::KeyInvalid)?);
} else {
*self = SKey::Plain(sign::SecretKey::from_slice(&ciphertext[..64])
.ok_or(ErrorKind::KeyInvalid)?);
}
}
Ok(())
}
/// Returns `None` if encrypted
fn skey(&self) -> ... | {
let mut key_file = SecretKeyFile::open(skey_path)?;
if key_file.is_encrypted() {
let passwd = Passwd::prompt(&format!("{} {}: ", prompt.as_ref(), skey_path.display()))
.chain_err(|| skey_path )?;
key_file.decrypt(passwd)
.chain_err(|| skey_path )?;
}
Ok(key... | identifier_body | |
lib.rs | secretbox, sign};
//TODO: Macro?
pub(crate) fn to_salt<'d, D: Deserializer<'d>>(deser: D) -> Result<pwhash::Salt, D::Error> {
String::deserialize(deser)
.and_then(|s| <[u8; 32]>::from_hex(s)
.map(|val| pwhash::Salt(val) )
.map_err(|err| Error::custom(err... | (&mut self) -> Option<sign::SecretKey> {
match &self.skey {
SKey::Plain(skey) => Some(skey.clone()),
SKey::Cipher(_) => None,
}
}
/// Returns `None` if the secret key is encrypted.
pub fn public_key_file(&self) -> Option<PublicKeyFile> {
Some(PublicKeyFil... | key | identifier_name |
fwliir.py | :] / 2**(iir.nbits - 1)
return t, im
def iir2sos(iir):
"""
Convierte un filtro digital IIR en punto fijo a su representación
como secuencia de secciones de segundo orden en punto flotante (ver
`scipy.signal.sos2tf` como referencia).
:param iir: filtro digital IIR en punto fijo.
:return: f... | for gen in range(1, n | proporción de elitismo.
"""
logbook = tools.Logbook()
logbook.header = ['gen', 'nevals'] + (stats.fields if stats else [])
# Evalua los individuos con aptitud inválida.
invalid_ind = [ind for ind in population if not ind.fitness.valid]
fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
... | identifier_body |
fwliir.py | # Computa el límite númerico de la representación entera signada.
n = 2 ** (nbits - 1)
# Selecciona el orden del filtro en forma aleatoria
# del intervalo [1, nlimit].
order = max(int(random.random() * (nlimit + 1)), 1)
# Si el orden es impar se introduce una etapa de primer orden.
if order % 2... | .7, ndpb=0.5,
| identifier_name | |
fwliir.py | respuesta al impulso renormalizando la salida
# al intervalo [-1, 1)
# salida del
t = ts * np.arange(n)
im = y[-1, 2:] / 2**(iir.nbits - 1)
return t, im
def iir2sos(iir):
"""
Convierte un filtro digital IIR en punto fijo a su representación
como secuencia de secciones de segundo orden... | enumerate(iir, start=1):
b0, b1, b2, a1, a2, k = sos
# Computar la ecuación de diferencias, truncando
# y saturando el resultado para ser representado
# en punto fijo 1.(`nbits`-1)
y[i, j] = np.clip((k * (
b0 * y[i - 1, j] +
b1... | conditional_block | |
fwliir.py | :] / 2**(iir.nbits - 1)
return t, im
def iir2sos(iir):
"""
Convierte un filtro digital IIR en punto fijo a su representación
como secuencia de secciones de segundo orden en punto flotante (ver
`scipy.signal.sos2tf` como referencia).
:param iir: filtro digital IIR en punto fijo.
:return: f... | """
Genera un filtro digital IIR en punto fijo estable en
forma aleatoria.
:param nlimit: orden máximo admitido para el filtro.
:param nbits: cantidad de bits utilizados para la
representación numérica de los coeficientes.
:return: filtro digital IIR en punto fijo generado.
"""
ii... | for sos in iir
])
def genStablePrototype(nlimit, nbits=32): | random_line_split |
main.rs | _urts;
use sgx_types::*;
use sgx_urts::SgxEnclave;
extern crate mio;
use mio::tcp::TcpStream;
use std::os::unix::io::AsRawFd;
use std::ffi::CString;
use std::net::SocketAddr;
use std::str;
use std::io::{self, Write};
const BUFFER_SIZE: usize = 1024;
static ENCLAVE_FILE: &'static str = "enclave.signed.so";
extern {... |
fn read_tls(&self, buf: &mut [u8]) -> isize {
let mut retval = -1;
let result = unsafe {
tls_client_read(self.enclave_id,
&mut retval,
self.tlsclient_id,
buf.as_mut_ptr() as * mut c_void,
... | {
let retval = unsafe {
tls_client_close(self.enclave_id, self.tlsclient_id)
};
if retval != sgx_status_t::SGX_SUCCESS {
println!("[-] ECALL Enclave [tls_client_close] Failed {}!", retval);
}
} | identifier_body |
main.rs | _urts;
use sgx_types::*;
use sgx_urts::SgxEnclave;
extern crate mio;
use mio::tcp::TcpStream;
use std::os::unix::io::AsRawFd;
use std::ffi::CString;
use std::net::SocketAddr;
use std::str;
use std::io::{self, Write};
const BUFFER_SIZE: usize = 1024;
static ENCLAVE_FILE: &'static str = "enclave.signed.so";
extern {... | (&self) -> bool {
let mut retval = -1;
let result = unsafe {
tls_client_wants_read(self.enclave_id,
&mut retval,
self.tlsclient_id)
};
match result {
sgx_status_t::SGX_SUCCESS => { },
... | wants_read | identifier_name |
main.rs | _urts;
use sgx_types::*;
use sgx_urts::SgxEnclave;
extern crate mio;
use mio::tcp::TcpStream;
use std::os::unix::io::AsRawFd;
use std::ffi::CString;
use std::net::SocketAddr;
use std::str;
use std::io::{self, Write};
const BUFFER_SIZE: usize = 1024;
static ENCLAVE_FILE: &'static str = "enclave.signed.so";
extern {... |
if self.is_closed() {
println!("Connection closed");
return false;
}
self.reregister(poll);
true
}
}
impl TlsClient {
fn new(enclave_id: sgx_enclave_id_t, sock: TcpStream, hostname: &str, cert: &str) -> Option<TlsClient> {
println!("[+] TlsCl... | {
self.do_write();
} | conditional_block |
main.rs | x_urts;
use sgx_types::*;
use sgx_urts::SgxEnclave;
extern crate mio;
use mio::tcp::TcpStream;
use std::os::unix::io::AsRawFd;
use std::ffi::CString;
use std::net::SocketAddr;
use std::str;
use std::io::{self, Write};
const BUFFER_SIZE: usize = 1024;
static ENCLAVE_FILE: &'static str = "enclave.signed.so";
extern ... | let result = unsafe {
tls_client_write(self.enclave_id,
&mut retval,
self.tlsclient_id,
buf.as_ptr() as * const c_void,
buf.len() as c_int)
};
match result {
... | }
}
fn write_tls(&self, buf: &[u8]) -> isize {
let mut retval = -1; | random_line_split |
mod.rs | had any information sent into it aside from
/// what is necessary for the underlying protocol. After the object is created, the `Display` will poll
/// the server for setup information.
#[inline]
pub fn from_connection(connection: Conn, auth: Option<AuthInfo>) -> crate::Result<Self> {
let mut d... | /// A variant of `Display` that uses X11's default connection mechanisms to connect to the server. In
/// most cases, you should be using this over any variant of `Display`.
#[cfg(feature = "std")]
pub type DisplayConnection = Display<name::NameConnection>; | random_line_split | |
mod.rs | <RequestCookie<R>>> + Send + 'future>> {
Box::pin(self.send_request_internal_async(req))
}
/// Wait for a request from the X11 server, async redox. See the `resolve_request` function for more
/// information.
#[cfg(feature = "async")]
#[inline]
pub async fn resolve_request_async<R: Requ... | wait_for_event_async | identifier_name | |
solvers.py | alpha * Ap
rsnew = np.dot(r, r)
beta = rsnew / rsold
if np.sqrt(rsnew) < rtol:
break
if beta < 1e-12: # no perceptible change in p
break
# p = r + beta*p
p *= beta
p += r
rsold = rsnew
return x, i+1
def conjgrad(A, Y, s... | class LstsqL2(_LstsqL2Solver):
"""Least-squares with L2 regularization.""" | random_line_split | |
solvers.py | rather than decoders.
Returns
-------
X : np.ndarray (N, D) or (N, N2)
(N, D) array of decoders (if solver.weights == False) or
(N, N2) array of weights (if solver.weights == True).
info : dict
A dictionary of information about the solve. All diction... | """
weights : boolean, optional
If false solve for decoders (default), otherwise solve for weights.
drop : float, optional
Fraction of decoders or weights to set to zero.
solver1 : Solver, optional
Solver for finding the initial decoders.
solver2 : Sol... | identifier_body | |
solvers.py | r + beta*p
p *= beta
p += r
rsold = rsnew
return x, i+1
def conjgrad(A, Y, sigma, X0=None, maxiters=None, tol=1e-2):
"""Solve the least-squares system using conjugate gradient."""
Y, m, n, d, matrix_in = _format_system(A, Y)
damp = m * sigma**2
rtol = tol * np.sqrt(m)
... | LstsqL2nz | identifier_name | |
solvers.py | _, _ = scipy.sparse.linalg.lsmr(
A, Y[:, i], damp=damp, atol=tol, btol=tol)
info = {'rmses': _rmses(A, X, Y), 'iterations': itns}
return X if matrix_in else X.flatten(), info
def _conjgrad_iters(calcAx, b, x, maxiters=None, rtol=1e-6):
"""Solve the single-RHS linear system using conjugate gr... |
elif isinstance(v, collections.Iterable):
hashes.append(hash(tuple(v)))
elif isinstance(v, collections.Callable):
hashes.append(hash(v.__code__))
else:
hashes.append(hash(v))
return hash(tuple(hashes))
def __str__(self):
... | raise ValueError("array is too large to hash") | conditional_block |
models.py | } seconds afters {tries} tries "
"calling function {target} with args {args} and kwargs "
"{kwargs}".format(**details))
feed = details['args'][0]
wait = details['wait']
notification = Notification(feed=feed, owner=feed.owner, title='BackOff', message=f'Feed: {feed.id}, {feed.link} fail... |
with transaction.atomic():
if len(dbEntriesCreate)>0:
Entry.objects.bulk_create(dbEntriesCreate)
if len(dbEntriesupdate)>0:
fields = ['feed', 'state', 'title' , 'content', 'date', 'author', 'url' ,'comments_url']
E... | dbEntriesCreate.append(entry) | conditional_block |
models.py | } seconds afters {tries} tries "
"calling function {target} with args {args} and kwargs "
"{kwargs}".format(**details))
feed = details['args'][0]
wait = details['wait']
notification = Notification(feed=feed, owner=feed.owner, title='BackOff', message=f'Feed: {feed.id}, {feed.link} fail... | )
comments_url = models.TextField(
blank=True,
validators=[URLValidator()],
help_text="URL for HTML comment submission page",
)
guid = models.TextField(
blank=True,
help_text="GUID for the entry, according to the feed",
)
last_updated = models.DateTi... | blank=True,
validators=[URLValidator()],
help_text="URL for the HTML for this entry", | random_line_split |
models.py | .actor
def feed_update_failure(message_data, exception_data):
"""
A dramatiq callback on each failed attempt for a feed update
the user will notified by inserting a notification in the db
only on the final failure
TODO: log all errors to somewhere for metrics and analysis
"""
feed_id = mes... | Notification | identifier_name | |
models.py | } seconds afters {tries} tries "
"calling function {target} with args {args} and kwargs "
"{kwargs}".format(**details))
feed = details['args'][0]
wait = details['wait']
notification = Notification(feed=feed, owner=feed.owner, title='BackOff', message=f'Feed: {feed.id}, {feed.link} fail... |
flagged = models.BooleanField(default=False)
owner = models.ForeignKey('auth.User', related_name='feeds', on_delete=models.CASCADE)
class Meta:
verbose_name = ("Feed")
verbose_name_plural = ("Feeds")
ordering = ('-updated_at',)
unique_together = ('link', 'owner')
... | '''
The feeds model describes a registered field.
Its contains feed related information
as well as user related info and other meta data
'''
link = models.URLField(max_length = 200)
title = models.CharField(max_length=200, null=True)
subtitle = models.CharField(max_length=200, null=True)
... | identifier_body |
server.rs | for Maputnik
async fn fontstacks() -> Result<HttpResponse> {
Ok(HttpResponse::Ok().json(&["Roboto Medium", "Roboto Regular"]))
}
// Include method fonts() which returns HashMap with embedded font files
include!(concat!(env!("OUT_DIR"), "/fonts.rs"));
/// Fonts for Maputnik
/// Example: /fonts/Open%20Sans%20Regul... | random_line_split | ||
server.rs | " xxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxx xxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx... | (
config: web::Data<ApplicationCfg>,
service: web::Data<MvtService>,
params: web::Path<(String, u8, u32, u32)>,
req: HttpRequest,
) -> Result<HttpResponse> {
let params = params.into_inner();
let tileset = params.0;
let z = params.1;
let x = params.2;
let y = params.3;
let gzip =... | tile_pbf | identifier_name |
server.rs | " xxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxx xxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxx... | Some(tile) => {
let mut r = HttpResponse::Ok();
r.content_type("application/x-protobuf");
if gzip {
// data is already gzip compressed
r.insert_header(header::ContentEncoding::Gzip);
}
let cache_max_age = config.webserve... | {
let params = params.into_inner();
let tileset = params.0;
let z = params.1;
let x = params.2;
let y = params.3;
let gzip = req
.headers()
.get(header::ACCEPT_ENCODING)
.and_then(|headerval| {
headerval
.to_str()
.ok()
... | identifier_body |
NeighborChainCli.py | [self.cmd, 'send', '--from', sender, '--to', receiver, '--amount', f'{amount}:BNB', '--json',
'--memo', memo_encoded] + self.get_default_conn()
return self._exe_bnb_cli(command, password)
def send_to_multi(self, sender, receiver_amount_dict: dict, password, memo):
"""
:p... |
@staticmethod
def get_bnb_rpc_url():
return f'{BnbCli._bnb_rpc_protocol}://{BnbCli._bnb_host}:{BnbCli._bnb_rpc_port}'
@staticmethod
def encode_memo(info):
"""
@param info: Expect porting id string, or tuple/list of (redeem id,incognito address)
@return:
"""
... | raise NeighborChainError(stderr) | conditional_block |
NeighborChainCli.py | (self):
return ['--chain-id', self.chain_id, '--node', self.node, self.trust]
def get_balance(self, key):
process = subprocess.Popen([self.cmd, 'account', key] + self.get_default_conn(), stdout=self.stdout,
stderr=self.stderr, universal_newlines=True)
stdo... | get_default_conn | identifier_name | |
NeighborChainCli.py |
class NeighborChainError(BaseException):
pass
class BnbCli:
_bnb_host = 'data-seed-pre-0-s1.binance.org'
_bnb_rpc_port = 443
_bnb_rpc_protocol = 'https'
_path = f'{os.getcwd()}/bin'
_binary = {'darwin': f'{_path}/tbnbcli-mac',
'linux': f'{_path}/tbnbcli-linux',
... | if token_id == PBNB_ID:
return BnbCli()
elif token_id == PBTC_ID:
return BtcGo() | identifier_body | |
NeighborChainCli.py | = [self.cmd, 'send', '--from', sender, '--to', receiver, '--amount', f'{amount}:BNB', '--json',
'--memo', memo_encoded] + self.get_default_conn()
return self._exe_bnb_cli(command, password)
def send_to_multi(self, sender, receiver_amount_dict: dict, password, memo):
"""
... | WAIT(7)
stdout, stderr = process.communicate(f'{more_input}\n')
logger.debug(f"\n"
f"+++ command: {' '.join(command)}\n"
f"+++ out: {stdout}\n"
f"+++ err: {stderr}")
out = json_extract(stdout)
err = json_extract(stder... | random_line_split | |
dots.py | SETTINGS
if os.path.exists("cb.pck"):
f = open("cb.pck")
cb = pickle.load(f)
f.close()
else:
cb = CBalance.Counterbalance(blocks)
blockOrder = cb.advance()
f = open("cb.pck", "w")
pickle.dump(cb, f)
f.close()
stimLib = "stimuli"
screen = get_default_screen()
screen.parameters.bgcolor = (.... | (t_abs):
global phase
global start
if not phase:
start = t_abs
phase = "dots"
t = t_abs - start
if t >= dot_duration and phase == "dots":
texture_object1.put_sub_image(mask_img)
texture_object2.put_sub_image(mask_img)
phase = "mask"
elif t >= (dot_duration + mask_dur) and phase == "mask... | put_image_dual | identifier_name |
dots.py |
if os.path.exists("cb.pck"):
f = open("cb.pck")
cb = pickle.load(f)
f.close()
else:
cb = CBalance.Counterbalance(blocks)
blockOrder = cb.advance()
f = open("cb.pck", "w")
pickle.dump(cb, f)
f.close()
stimLib = "stimuli"
screen = get_default_screen()
screen.parameters.bgcolor = (.52, .51, ... | else:
sub.inputData(trial, "ACC", 0)
if RT <= 0:
sub.inputData(trial, "ACC", 3)
else:
sub.inputData(trial, "ACC", 2)
pressed = True
#fixation pause
#add response handlers
fixText, fixCross = experiments.printWord(screen, '+', crossSize, (0, 0, 0))
blockIns = {}
blockIns['pai... | sub.inputData(trial, "ACC", 1)
| random_line_split |
dots.py |
if os.path.exists("cb.pck"):
f = open("cb.pck")
cb = pickle.load(f)
f.close()
else:
cb = CBalance.Counterbalance(blocks)
blockOrder = cb.advance()
f = open("cb.pck", "w")
pickle.dump(cb, f)
f.close()
stimLib = "stimuli"
screen = get_default_screen()
screen.parameters.bgcolor = (.52, .51, ... |
def keyFunc(event):
global color
global cDict
global yellowB
global blueB
global trial
global block
global side
global pressed
RT = p.time_sec_since_go * 1000
if block == "sequential":
RT-= (dot_duration * 1000)
correct = cDict[color]
sub.inputData(trial, "RT", RT)
if event.ke... | global phase
global start
if not phase:
start = t_abs
phase = "dots"
t = t_abs - start
if t >= dot_duration and phase == "dots":
texture_object.put_sub_image(mask_img)
phase = "mask"
elif t >= (dot_duration + mask_dur) and phase == "mask":
p.parameters.viewports = [fixCross]
phase = "... | identifier_body |
dots.py | SETTINGS
if os.path.exists("cb.pck"):
f = open("cb.pck")
cb = pickle.load(f)
f.close()
else:
cb = CBalance.Counterbalance(blocks)
blockOrder = cb.advance()
f = open("cb.pck", "w")
pickle.dump(cb, f)
f.close()
stimLib = "stimuli"
screen = get_default_screen()
screen.parameters.bgcolor = (.... |
print "entering block %s" % block
ratios = shuffler.Condition([.9, .75, .66, .5, .33, .25], "ratio", 6)
seeds = shuffler.Condition([6, 7, 8, 9, 10], "seed", 6)
size = shuffler.Condition(["con", "incon"], "size", 5)
exemplars = shuffler.Condition([1, 2, 3, 4], "exemplar", 20)
order = ["large", "sm... | instructionText = "In this stage you will see 2 groups of dots.\n%s\n Each group will be either yellow or blue. Your job is to choose which group has more dots in it.\n\nPress %s for yellow.\nPress %s for blue.\n\nPRESS SPACE TO CONTINUE." % (blockIns[block], yellowB, blueB) | conditional_block |
interaction.rs | XR_HAND_JOINT_RING_DISTAL: usize = 18;
pub const XR_HAND_JOINT_RING_TIP: usize = 19;
pub const XR_HAND_JOINT_LITTLE_METACARPAL: usize = 20;
pub const XR_HAND_JOINT_LITTLE_PROXIMAL: usize = 21;
pub const XR_HAND_JOINT_LITTLE_INTERMEDIATE: usize = 22;
pub const XR_HAND_JOINT_LITTLE_DISTAL: usize = 23;
pub const XR_HAND_... |
/// Returns poses that can be used to render a target ray or cursor. The ray is along -Z. The
/// behavior is vendor-specific. Index 0 corresponds to the left hand, index 1 corresponds to
/// the right hand.
pub fn hand_target_ray(&self) -> [Option<XrPose>; 2] {
self.inner.hands_target_ray()
... | {
self.inner.hands_skeleton_pose()
} | identifier_body |
interaction.rs | XR_HAND_JOINT_RING_DISTAL: usize = 18;
pub const XR_HAND_JOINT_RING_TIP: usize = 19;
pub const XR_HAND_JOINT_LITTLE_METACARPAL: usize = 20;
pub const XR_HAND_JOINT_LITTLE_PROXIMAL: usize = 21;
pub const XR_HAND_JOINT_LITTLE_INTERMEDIATE: usize = 22;
pub const XR_HAND_JOINT_LITTLE_DISTAL: usize = 23;
pub const XR_HAND_... | else {
XrButtonState::Default
}
}
pub fn button_touched(&self, action: &str) -> bool {
if let Some(XrActionState::Button { state | {
*state
} | conditional_block |
interaction.rs | /// precision possible. Poses are predicted for the next V-Sync. To obtain poses for an arbitrary
/// point in time, `bevy_openxr` backend provides this functionality with OpenXrTrackingState.
pub struct XrTrackingSource {
inner: Box<dyn implementation::XrTrackingSourceBackend>,
}
impl XrTrackingSource {
pub f... | XrProfiles | identifier_name | |
interaction.rs | a sphere placed at the center of the joint that roughly touches the skin on both
/// sides of the hand.
pub radius: f32,
}
impl Deref for XrJointPose {
type Target = XrPose;
fn deref(&self) -> &Self::Target {
&self.pose
}
}
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug, Serialize, Des... | pub fn button_just_unpressed(&self, action: &str) -> bool {
self.button_states(action)
.map(|(cur, prev)| cur != XrButtonState::Pressed && prev == XrButtonState::Pressed)
.unwrap_or(false) | random_line_split | |
recorder_test.go | AndName is a slice of ts.TimeSeriesData.
type byTimeAndName []ts.TimeSeriesData
// implement sort.Interface for byTimeAndName
func (a byTimeAndName) Len() int { return len(a) }
func (a byTimeAndName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byTimeAndName) Less(i, j int) bool {
if a[i].Name != a[j].Name... | () int { return len(a) }
func (a byStoreDescID) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byStoreDescID) Less(i, j int) bool {
return a[i].Desc.StoreID < a[j].Desc.StoreID
}
var _ sort.Interface = byStoreDescID{}
// fakeStore implements only the methods of store needed by MetricsRecorder to
// interact... | Len | identifier_name |
recorder_test.go | .Interface for byTimeAndName
func (a byTimeAndName) Len() int { return len(a) }
func (a byTimeAndName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byTimeAndName) Less(i, j int) bool {
if a[i].Name != a[j].Name {
return a[i].Name < a[j].Name
}
if a[i].Datapoints[0].TimestampNanos != a[j].Datapoints[0].T... | {
t.Fatal(err)
} | conditional_block | |
recorder_test.go | AndName is a slice of ts.TimeSeriesData.
type byTimeAndName []ts.TimeSeriesData
// implement sort.Interface for byTimeAndName
func (a byTimeAndName) Len() int |
func (a byTimeAndName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byTimeAndName) Less(i, j int) bool {
if a[i].Name != a[j].Name {
return a[i].Name < a[j].Name
}
if a[i].Datapoints[0].TimestampNanos != a[j].Datapoints[0].TimestampNanos {
return a[i].Datapoints[0].TimestampNanos < a[j].Datapoints[0].Time... | { return len(a) } | identifier_body |
recorder_test.go | func (a byTimeAndName) Len() int { return len(a) }
func (a byTimeAndName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byTimeAndName) Less(i, j int) bool {
if a[i].Name != a[j].Name {
return a[i].Name < a[j].Name
}
if a[i].Datapoints[0].TimestampNanos != a[j].Datapoints[0].TimestampNanos {
return a[i]... | // byTimeAndName is a slice of ts.TimeSeriesData.
type byTimeAndName []ts.TimeSeriesData
// implement sort.Interface for byTimeAndName | random_line_split | |
TransformExpression.ts | are required at this point to convert the typed value to a string form.
// If copy-namespaces mode in the static context specifies preserve, all in-scope-namespaces of the original element are retained in the new copy. If copy-namespaces mode specifies no-preserve, the new copy retains only those in-scope namespaces ... | evaluate | identifier_name | |
TransformExpression.ts | /iterators';
import { applyUpdates, mergeUpdates } from './pulRoutines';
import UpdatingExpression from './UpdatingExpression';
import { errXUDY0014, errXUDY0037, errXUTY0013 } from './XQueryUpdateFacilityErrors';
import { IPendingUpdate } from './IPendingUpdate';
import ISequence from '../dataTypes/ISequence';
import ... |
// resulting in a pending update list (denoted $pul) and an XDM instance. The XDM instance is discarded, and does not form part of the result of the copy modify expression.
modifyPul = mv.value.pendingUpdateList;
}
modifyPul.forEach(pu => {
// If the target node of any update primitive in $pul ... | {
return mv;
} | conditional_block |
TransformExpression.ts | /iterators';
import { applyUpdates, mergeUpdates } from './pulRoutines';
import UpdatingExpression from './UpdatingExpression';
import { errXUDY0014, errXUDY0037, errXUTY0013 } from './XQueryUpdateFacilityErrors';
import { IPendingUpdate } from './IPendingUpdate';
import ISequence from '../dataTypes/ISequence';
import ... |
public evaluateWithUpdateList(
dynamicContext: DynamicContext,
executionParameters: ExecutionParameters
): IAsyncIterator<UpdatingExpressionResult> {
const { domFacade, nodesFactory, documentWriter } = executionParameters;
const sourceValueIterators: IAsyncIterator<UpdatingExpressionResult>[] = [];
let m... | {
super(
new Specificity({}),
variableBindings.reduce(
(childExpressions, variableBinding) => {
childExpressions.push(variableBinding.sourceExpr);
return childExpressions;
},
[modifyExpr, returnExpr]
),
{
canBeStaticallyEvaluated: false,
resultOrder: RESULT_ORDERINGS.UNSORTED... | identifier_body |
TransformExpression.ts | /iterators';
import { applyUpdates, mergeUpdates } from './pulRoutines';
import UpdatingExpression from './UpdatingExpression';
import { errXUDY0014, errXUDY0037, errXUTY0013 } from './XQueryUpdateFacilityErrors';
import { IPendingUpdate } from './IPendingUpdate';
import ISequence from '../dataTypes/ISequence';
import ... |
function isCreatedNode(node, createdNodes, domFacade) {
if (createdNodes.includes(node)) {
return true;
}
const parent = domFacade.getParentNode(node);
return parent ? isCreatedNode(parent, createdNodes, domFacade) : false;
}
type VariableBinding = { registeredVariable?: string; sourceExpr: Expression; varRef: ... | }
} | random_line_split |
index.js | '';
item.item_info.tags.forEach(function (tagItem) {
var tag_name =
'<a class="tagname" target="_blank" href="https://juejin.im/tag/' +
tagItem.tag_name +
'">' +
tagItem.tag_name +
'</a>';
category += tag_name;
});
... | 60 / 60) | identifier_name | |
index.js | xOf(className) >= 0) {
titles.forEach(function (item) {
item.classList.remove('active');
});
topic.style.display = 'none';
ad.style.display = 'none';
homepage.style.display = 'none';
brochureSubtitleBox.style.display = 'none';
homePageSubtitleBox.style.display = 'none';
brochure.st... | ;
if (className && classNameArr.inde | conditional_block | |
index.js | brochure.style.display = 'none';
if (className == 'home-page') {
ad.style.display = 'block';
homepage.style.display = 'block';
homePageSubtitleBox.style.display = 'block';
addGroup.innerText = '写文章';
e.classList.add('active');
}
if (className == 'topic') {
topic.style.di... | ' 关注 · ' +
item.topic.msg_count +
' 沸点</span>' +
'<span> + 关注 </span>' +
'</div>' +
'</div>';
topicBox += topicItem;
});
document.querySelector(
'.content-container .topic-box'
).innerHTML = topicBox;
}
}
// 获取小册数据
function getBrochure() {
va... | div>' +
'<div class="topic-list">';
data.forEach(function (item) {
var topicItem =
'<div class="topic-item">' +
'<div class="pic" style="background-image: url(' +
item.topic.icon +
')">' +
'<a target="_blank" href="https://juejin.im/topic/' +
item.topic.to... | identifier_body |
index.js | brochure.style.display = 'none';
if (className == 'home-page') {
ad.style.display = 'block';
homepage.style.display = 'block';
homePageSubtitleBox.style.display = 'block';
addGroup.innerText = '写文章';
e.classList.add('active');
}
if (className == 'topic') {
topic.style.di... | console.log(error);
},
});
}
// 初始化话题页
function initTopic(data) {
if (data.length > 0) {
var topicBox =
'<div class="topic-box-div">' +
'<div class="topic-content">' +
'<div class="topic-title">全部话题</div>' +
'<div class="topic-list">';
data.forEach(function (item) {
... | },
error: function (error) { | random_line_split |
futures.rs | Send a future to an executor.
///
/// This needs to be thread-safe, as it is called from a `Waker` that may be on a different thread.
#[derive(Debug)]
struct Sender {
/// The sender used to send runnables to the executor.
///
/// `mpsc::Sender` is `!Sync`, wrapping it in a `Mutex` makes it `Sync`.
send... | unregister | identifier_name | |
futures.rs | ::Slab;
use std::{
cell::RefCell,
future::Future,
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
mpsc, Arc, Mutex,
},
task::Waker,
};
use crate::{
sources::{
channel::ChannelError,
ping::{make_ping, Ping, PingError, PingSource},
EventSource,
},
... | ))
}
impl<T> EventSource for Executor<T> {
type Event = T;
type Metadata = ();
type Ret = ();
type Error = ExecutorError;
fn process_events<F>(
&mut self,
readiness: Readiness,
token: Token,
mut callback: F,
) -> Result<PostAction, Self::Error>
where
... | {
let (sender, incoming) = mpsc::channel();
let (wake_up, ping) = make_ping()?;
let state = Rc::new(State {
incoming,
active_tasks: RefCell::new(Some(Slab::new())),
sender: Arc::new(Sender {
sender: Mutex::new(sender),
wake_up,
notified: AtomicBoo... | identifier_body |
futures.rs | ::Slab;
use std::{
cell::RefCell,
future::Future,
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
mpsc, Arc, Mutex,
},
task::Waker,
};
use crate::{
sources::{
channel::ChannelError,
ping::{make_ping, Ping, PingError, PingSource},
EventSource,
},
... | pub struct Executor<T> {
/// Shared state between the executor and the scheduler.
state: Rc<State<T>>,
/// Notifies us when the executor is woken up.
ping: PingSource,
}
/// A scheduler to send futures to an executor
#[derive(Clone, Debug)]
pub struct Scheduler<T> {
/// Shared state between the ex... |
/// A future executor as an event source
#[derive(Debug)] | random_line_split |
futures.rs | ::Slab;
use std::{
cell::RefCell,
future::Future,
rc::Rc,
sync::{
atomic::{AtomicBool, Ordering},
mpsc, Arc, Mutex,
},
task::Waker,
};
use crate::{
sources::{
channel::ChannelError,
ping::{make_ping, Ping, PingError, PingSource},
EventSource,
},
... |
// If the executor is already awake, don't bother waking it up again.
if self.notified.swap(true, Ordering::SeqCst) {
return;
}
// Wake the executor.
self.wake_up.ping();
}
}
impl<T> Drop for Executor<T> {
fn drop(&mut self) {
let active_tasks = se... | {
// The runnable must be dropped on its origin thread, since the original future might be
// !Send. This channel immediately sends it back to the Executor, which is pinned to the
// origin thread. The executor's Drop implementation will force all of the runnables to be
/... | conditional_block |
manifests.go | /sql"
"fmt"
"time"
"github.com/opencontainers/go-digest"
"github.com/sapcc/go-bits/logg"
"github.com/sapcc/keppel/internal/keppel"
)
//query that finds the next manifest to be validated
var outdatedManifestSearchQuery = keppel.SimplifyWhitespaceInSQL(`
SELECT * FROM manifests WHERE validated_at < $1
ORDER BY v... | err := j.db.SelectOne(&repo, syncManifestRepoSelectQuery, j.timeNow())
if err != nil {
if err == sql.ErrNoRows {
logg.Debug("no accounts to sync manifests in - slowing down...")
return sql.ErrNoRows
}
return err
}
//find corresponding account
account, err := keppel.FindAccount(j.db, repo.AccountName)
... | random_line_split | |
manifests.go | "
"fmt"
"time"
"github.com/opencontainers/go-digest"
"github.com/sapcc/go-bits/logg"
"github.com/sapcc/keppel/internal/keppel"
)
//query that finds the next manifest to be validated
var outdatedManifestSearchQuery = keppel.SimplifyWhitespaceInSQL(`
SELECT * FROM manifests WHERE validated_at < $1
ORDER BY valid... |
_, err = j.db.Exec(syncManifestDoneQuery, repo.ID, j.timeNow().Add(1*time.Hour))
return err
}
func (j *Janitor) performManifestSync(account keppel.Account, repo keppel.Repository) error {
//enumerate manifests in this repo
var manifests []keppel.Manifest
_, err := j.db.Select(&manifests, `SELECT * FROM manifest... | {
err = j.performManifestSync(*account, repo)
if err != nil {
return err
}
} | conditional_block |
manifests.go | "
"fmt"
"time"
"github.com/opencontainers/go-digest"
"github.com/sapcc/go-bits/logg"
"github.com/sapcc/keppel/internal/keppel"
)
//query that finds the next manifest to be validated
var outdatedManifestSearchQuery = keppel.SimplifyWhitespaceInSQL(`
SELECT * FROM manifests WHERE validated_at < $1
ORDER BY valid... | () (returnErr error) {
defer func() {
if returnErr == nil {
syncManifestsSuccessCounter.Inc()
} else if returnErr != sql.ErrNoRows {
syncManifestsFailedCounter.Inc()
returnErr = fmt.Errorf("while syncing manifests in a replica repo: %s", returnErr.Error())
}
}()
//find repository to sync
var repo ke... | SyncManifestsInNextRepo | identifier_name |
manifests.go | "
"fmt"
"time"
"github.com/opencontainers/go-digest"
"github.com/sapcc/go-bits/logg"
"github.com/sapcc/keppel/internal/keppel"
)
//query that finds the next manifest to be validated
var outdatedManifestSearchQuery = keppel.SimplifyWhitespaceInSQL(`
SELECT * FROM manifests WHERE validated_at < $1
ORDER BY valid... | }
//find corresponding account and repo
var repo keppel.Repository
err = j.db.SelectOne(&repo, `SELECT * FROM repos WHERE id = $1`, manifest.RepositoryID)
if err != nil {
return fmt.Errorf("cannot find repo %d for manifest %s: %s", manifest.RepositoryID, manifest.Digest, err.Error())
}
account, err := keppel.... | {
defer func() {
if returnErr == nil {
validateManifestSuccessCounter.Inc()
} else if returnErr != sql.ErrNoRows {
validateManifestFailedCounter.Inc()
returnErr = fmt.Errorf("while validating a manifest: %s", returnErr.Error())
}
}()
//find manifest
var manifest keppel.Manifest
maxValidatedAt := j.... | identifier_body |
path_through.rs | }
async fn do_forget(&self, forgets: &[Forget]) {
let mut inodes = self.inodes.lock().await;
for forget in forgets {
if let Entry::Occupied(mut entry) = inodes.map.entry(forget.ino()) {
let refcount = {
let mut inode = entry.get_mut().lock().await;
... | let mut buf = Vec::with_capacity(op.size() as usize); | random_line_split | |
path_through.rs | (&self, path: &Path) -> Option<Arc<Mutex<INode>>> {
let ino = self.path_to_ino.get(path).copied()?;
self.get(ino)
}
}
struct VacantEntry<'a> {
table: &'a mut INodeTable,
ino: Ino,
}
impl VacantEntry<'_> {
fn insert(mut self, inode: INode) {
let path = inode.path.clone();
... | get_path | identifier_name | |
vvMakeVjetsShapes.py | histos2D_nonRes[key].Write()
histos2D_nonRes_l2[key].Write()
histos2D[key].Write()
###########################
for leg in legs:
histos = {}
histos_nonRes = {}
scales={}
scales_nonRes={}
purity = "LPLP"
if options.output.find("HPHP")!=-1:purity = "HPHP"
if options.outpu... | random_line_split | ||
vvMakeVjetsShapes.py | .var("sigma").setVal(sigma)
#fitter.w.var("sigma").setConstant(1)
print "_____________________________________"
fitter.importBinnedData(histo,['x'],'data')
fitter.fit('model','data',[ROOT.RooFit.SumW2Error(1),ROOT.RooFit.Save(1),ROOT.RooFit.Range(55,120)]) #55,140 works well with fitting only the resonant part
... |
label = options.output.split(".root")[0]
t = label.split("_")
el=""
for words in t:
if words.find("HP")!=-1 or words.find("LP")!=-1:
continue
el+=words+"_"
label = el
samplenames = options.sample.split(",")
for filename in os.listdir(args[0]):
for samplename in samplenames:
if not (filen... | c=ROOT.TCanvas(name,name)
c.cd()
c.SetFillColor(0)
c.SetBorderMode(0)
c.SetFrameFillStyle(0)
c.SetFrameBorderMode(0)
c.SetLeftMargin(0.13)
c.SetRightMargin(0.08)
c.SetTopMargin( 0.1 )
c.SetBottomMargin( 0.12 )
return c | identifier_body |
vvMakeVjetsShapes.py | (func,ftype,varname):
if ftype.find("pol")!=-1:
st='0'
for i in range(0,func.GetNpar()):
st=st+"+("+str(func.GetParameter(i))+")"+("*{varname}".format(varname=varname)*i)
return st
else:
return ""
def doFit(fitter,histo,histo_nonRes,label,leg):
params={}
pr... | returnString | identifier_name | |
vvMakeVjetsShapes.py | .92,"#font[62]{CMS} #font[52]{Simulation}")
c.SaveAs("debugJ"+leg+"_"+label+"_nonRes.pdf")
params[label+"_Res_"+leg]={"mean": {"val": fitter.w.var("mean").getVal(), "err": fitter.w.var("mean").getError()}, "sigma": {"val": fitter.w.var("sigma").getVal(), "err": fitter.w.var("sigma").getError()}, "alpha"... | keys.append("Zjets")
fitterZ=Fitter(['x'])
fitterZ.jetResonanceVjets('model','x')
Zjets_params = doFit(fitterZ,histos["Zjets"],histos_nonRes["Zjets"],"Zjets",leg)
params.update(Wjets_params)
params.update(Zjets_params)
params["ratio_Res_nonRes_"+leg]= {'ratio': scales["Wj... | conditional_block | |
reset.go | (ctx context.Context, dbData env.DbData, cSpecStr string, roots doltdb.Roots) (*doltdb.Commit, doltdb.Roots, error) {
ddb := dbData.Ddb
rsr := dbData.Rsr
var newHead *doltdb.Commit
if cSpecStr != "" {
cs, err := doltdb.NewCommitSpec(cSpecStr)
if err != nil {
return nil, doltdb.Roots{}, err
}
headRef, e... | resetHardTables | identifier_name | |
reset.go | HardTables(ctx context.Context, dbData env.DbData, cSpecStr string, roots doltdb.Roots) (*doltdb.Commit, doltdb.Roots, error) {
ddb := dbData.Ddb
rsr := dbData.Rsr
var newHead *doltdb.Commit
if cSpecStr != "" {
cs, err := doltdb.NewCommitSpec(cSpecStr)
if err != nil {
return nil, doltdb.Roots{}, err
}
... |
// IsValidRef validates whether the input parameter is a valid cString
// TODO: this doesn't belong in this package
func IsValidRef(ctx context.Context, cSpecStr string, ddb *doltdb.DoltDB | {
newStaged, err := MoveTablesBetweenRoots(ctx, tbls, roots.Head, roots.Staged)
if err != nil {
return doltdb.Roots{}, err
}
roots.Staged = newStaged
return roots, nil
} | identifier_body |
reset.go | HardTables(ctx context.Context, dbData env.DbData, cSpecStr string, roots doltdb.Roots) (*doltdb.Commit, doltdb.Roots, error) {
ddb := dbData.Ddb
rsr := dbData.Rsr
var newHead *doltdb.Commit
if cSpecStr != "" {
cs, err := doltdb.NewCommitSpec(cSpecStr)
if err != nil |
headRef, err := rsr.CWBHeadRef()
if err != nil {
return nil, doltdb.Roots{}, err
}
newHead, err = ddb.Resolve(ctx, cs, headRef)
if err != nil {
return nil, doltdb.Roots{}, err
}
roots.Head, err = newHead.GetRootValue(ctx)
if err != nil {
return nil, doltdb.Roots{}, err
}
}
// mirroring ... | {
return nil, doltdb.Roots{}, err
} | conditional_block |
reset.go | nil {
return nil, doltdb.Roots{}, err
}
newWkRoot, err = newWkRoot.PutTable(ctx, name, tbl)
if err != nil {
return nil, doltdb.Roots{}, fmt.Errorf("failed to write table back to database: %s", err)
}
}
// need to save the state of files that aren't tracked
untrackedTables := make(map[string]*doltdb.T... | newRoot, err = newRoot.RemoveTables(ctx, force, force, toDelete...)
if err != nil {
return doltdb.Roots{}, fmt.Errorf("failed to remove tables; %w", err) | random_line_split | |
clickhouse_output.go | descMap[c] = ""
}
for rows.Next() {
values := make([]interface{}, 0)
for range columns {
var a string
values = append(values, &a)
}
if err := rows.Scan(values...); err != nil {
glog.Fatalf("scan rows error: %s", err)
}
descMap := make(map[string]string)
for i, c := range colum... | {
nextdb := c.dbSelector.Next()
db := nextdb.(*sql.DB)
rows, err := db.Query(query)
if err != nil {
glog.Errorf("query %q error: %s", query, err)
continue
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
glog.Fatalf("could not get columns from query `%s`: %s", query, err)
... | conditional_block | |
clickhouse_output.go | }
b, err := json.Marshal(descMap)
if err != nil {
glog.Fatalf("marshal desc error: %s", err)
}
rowDesc := rowDesc{}
err = json.Unmarshal(b, &rowDesc)
if err != nil {
glog.Fatalf("marshal desc error: %s", err)
}
glog.V(5).Infof("row desc: %#v", rowDesc)
c.desc[rowDesc.Name] = &row... | lt"
if len(dbAndTable) == 2 {
dbName = dbAndTable[0]
}
return dbName
}
func init() {
Register("Clickhouse", newClickhouseOutput)
}
func newClickhouseOutput(config map[interface{}]interface{}) topology.Output {
rand.Seed(time.Now().UnixNano())
p := &ClickhouseOutput{
config: config,
}
if v, ok := config["... | e := "defau | identifier_name |
clickhouse_output.go | }
b, err := json.Marshal(descMap)
if err != nil {
glog.Fatalf("marshal desc error: %s", err)
}
rowDesc := rowDesc{}
err = json.Unmarshal(b, &rowDesc)
if err != nil {
glog.Fatalf("marshal desc error: %s", err)
}
glog.V(5).Infof("row desc: %#v", rowDesc)
c.desc[rowDesc.Name] = &rowD... |
if v, ok := config["hosts"]; ok {
for _, h := range v.([]interface{}) {
p.hosts = append(p.hosts, h.(string))
}
} else {
glog.Fatalf("hosts must be set in clickhouse output")
}
if v, ok := config["username"]; ok {
p.username = v.(string)
}
if v, ok := config["password"]; ok {
p.password = v.(strin... | onfig,
}
if v, ok := config["fields"]; ok {
for _, f := range v.([]interface{}) {
p.fields = append(p.fields, f.(string))
}
}
if v, ok := config["auto_convert"]; ok {
p.autoConvert = v.(bool)
} else {
p.autoConvert = true
}
if v, ok := config["table"]; ok {
p.table = v.(string)
} else {
glog.F... | identifier_body |
clickhouse_output.go | }
| }
rowDesc := rowDesc{}
err = json.Unmarshal(b, &rowDesc)
if err != nil {
glog.Fatalf("marshal desc error: %s", err)
}
glog.V(5).Infof("row desc: %#v", rowDesc)
c.desc[rowDesc.Name] = &rowDesc
}
for key1, value1 := range c.desc {
switch value1.Type {
case "Int64", "UInt64", "Int32"... | b, err := json.Marshal(descMap)
if err != nil {
glog.Fatalf("marshal desc error: %s", err) | random_line_split |
privacy-statement.js | <td>
any applicable law relating to the processing of personal
Data, including but not limited to the Directive 96/46/EC
(Data Protection Directive) or the GDPR, and any national
implementing laws, regulations and secondary legislat... | by this Website are set out in the clause below (Cookies);
</td>
</tr>
<tr>
<th scope="row">Data Protection Laws</th> | random_line_split | |
lib.rs | fn get_info_string<R: Reader>(
view: &BinaryView,
dwarf: &Dwarf<R>,
unit: &Unit<R>,
die_node: &DebuggingInformationEntry<R>,
) -> Vec<DisassemblyTextLine> {
let mut disassembly_lines: Vec<DisassemblyTextLine> = Vec::with_capacity(10); // This is an estimate so "most" things won't need to resize
... | {
register(
"DWARF Dump",
"Show embedded DWARF info as a tree structure for you to navigate",
DWARFDump {},
);
true
} | identifier_body | |
lib.rs | See the License for the specific language governing permissions and
// limitations under the License.
use binaryninja::{
binaryview::{BinaryView, BinaryViewExt},
command::{register, Command},
disassembly::{DisassemblyTextLine, InstructionTextToken, InstructionTextTokenContents},
flowgraph::{BranchType... | else {
let attr_string = format!("{:?}", attr.value());
attr_line.push(InstructionTextToken::new(
BnString::new(attr_string),
InstructionTextTokenContents::Text,
));
}
disassembly_lines.push(DisassemblyTextLine::from(attr_line));
}... | {
let value_string = format!("{}", value);
attr_line.push(InstructionTextToken::new(
BnString::new(value_string),
InstructionTextTokenContents::Integer(value as u64),
));
} | conditional_block |
lib.rs | // See the License for the specific language governing permissions and
// limitations under the License.
use binaryninja::{
binaryview::{BinaryView, BinaryViewExt},
command::{register, Command},
disassembly::{DisassemblyTextLine, InstructionTextToken, InstructionTextTokenContents},
flowgraph::{BranchTy... | // distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split | |
lib.rs | See the License for the specific language governing permissions and
// limitations under the License.
use binaryninja::{
binaryview::{BinaryView, BinaryViewExt},
command::{register, Command},
disassembly::{DisassemblyTextLine, InstructionTextToken, InstructionTextTokenContents},
flowgraph::{BranchType... | <R: Reader>(
view: &BinaryView,
dwarf: &Dwarf<R>,
unit: &Unit<R>,
die_node: &DebuggingInformationEntry<R>,
) -> Vec<DisassemblyTextLine> {
let mut disassembly_lines: Vec<DisassemblyTextLine> = Vec::with_capacity(10); // This is an estimate so "most" things won't need to resize
let label_value =... | get_info_string | identifier_name |
tree.py |
#If there are 3 x's in a row, x's win
def win_state_x(self):
if self.three_in_a_row('x') and not(self.three_in_a_row('o')):
return True
return False
#If there are 3 o's in a row, o's win
def win_state_o(self):
if self.three_in_a_row('o') and not(self.three_in_a_row('x')):
return True
return False... | for it in range(0,3):
if self.gameState[it*3] == player and self.gameState[3*it+1] == player and self.gameState[3*it+2] == player: #horizontally
return True
if self.gameState[it] == player and self.gameState[it+3] == player and self.gameState[it+6] == player: #vertically
return True
if self.gameState[0]... | identifier_body | |
tree.py | If there are 3 o's in a row, o's win
def win_state_o(self):
if self.three_in_a_row('o') and not(self.three_in_a_row('x')):
return True
return False
#Returns the game children of the gameState
def get_game_children(self, player):
empty = []
for pos in range(len(self.gameState)):
if self.gameState[pos] ... | (currentNode, position):
# Converts position 1-9 and returns position x,y or None,None if invalid
position = int(position)
if currentNode.get_gameState()[position-1] != '.':
return None
return position-1
def minimax(turn, currentNode, children):
best_node = 0
most_wins = 0
# Guarantees to make the winning m... | valid_position | identifier_name |
tree.py | #If there are 3 o's in a row, o's win
def win_state_o(self):
if self.three_in_a_row('o') and not(self.three_in_a_row('x')):
return True
return False
#Returns the game children of the gameState
def get_game_children(self, player):
empty = []
for pos in range(len(self.gameState)):
if self.gameState[pos]... | elif self.gameState[0] == player and self.gameState[4] == '.' and self.gameState[8] == player:
return 4
elif self.gameState[0] == '.' and self.gameState[4] == player and self.gameState[8] == player:
return 0
elif self.gameState[6] == player and self.gameState[4] == player and self.gameState[2] == '.':
re... | #Diagonal
if self.gameState[0] == player and self.gameState[4] == player and self.gameState[8] == '.':
return 8 | random_line_split |
tree.py | #If there are 3 o's in a row, o's win
def win_state_o(self):
if self.three_in_a_row('o') and not(self.three_in_a_row('x')):
return True
return False
#Returns the game children of the gameState
def get_game_children(self, player):
empty = []
for pos in range(len(self.gameState)):
if self.gameState[pos]... |
elif turn%2 == 1:
two_in_a_row = currentNode.tictactoe.two_in_a_row('x')
if two_in_a_row != None:
pos = two_in_a_row
for n in range(0, len(children)):
if (turn%2 == 0 and children[n].get_gameState()[pos] == 'x') or (turn%2 == 1 and children[n].get_gameState()[pos] == 'o'):
return n
#Trump move
trump... | two_in_a_row = currentNode.tictactoe.two_in_a_row('o') | conditional_block |
uploadSourcemap.ts | Promise} from '../utils/utils';
interface UploadSourcemapCMDParams {
apiKey: string;
apiSecret: string;
release: string;
minifiedDir: string;
projectRoot: string;
endPoint?: string;
}
export class UploadSourcemap {
static sourcemapApi = 'sourcemap';
static abortSourcemapApi = 'abortUploadingSourcemap'... | action: this.commandAction.bind(this),
};
}
async commandAction(cmd: UploadSourcemapCMDParams) {
UploadSourcemap.validateOnCLIInput(cmd);
const baseURL = cmd.endPoint || config.baseURL;
const absolutePath = path.resolve(cmd.minifiedDir);
const spinner = ora('Compressing sourcemap files'... | {
this.initializationDetails = {
command: 'uploadSourcemap',
description: 'Upload project sourcemap files.',
version: '1.0.0',
optionList: [
['--api-key <key>', 'An API key for project'],
['--api-secret <secret>', 'An API secret for project'],
['--release <v>', 'when ... | identifier_body |
uploadSourcemap.ts | minifiedDir: string;
projectRoot: string;
endPoint?: string;
}
export class UploadSourcemap {
static sourcemapApi = 'sourcemap';
static abortSourcemapApi = 'abortUploadingSourcemap';
static djatyPathPrefix = 'djaty';
static sourcemapFileSuffix = '_sourcemap_files.tgz';
initializationDetails: CommandPa... | validateOnCLIInput | identifier_name | |
uploadSourcemap.ts | AsPromise} from '../utils/utils';
interface UploadSourcemapCMDParams {
apiKey: string;
apiSecret: string;
release: string;
minifiedDir: string;
projectRoot: string;
endPoint?: string;
}
export class UploadSourcemap {
static sourcemapApi = 'sourcemap';
static abortSourcemapApi = 'abortUploadingSourcema... | if (err.statusCode === 400) {
// Handle AJV validation errors.
const error = JSON.parse(err.error.replace(')]}\',\n', ''));
if (error.code === 'NOT_RELEASE_TO_ABORT') {
// noinspection JSIgnoredPromiseFromCall
djaty.trackBug(err);
return;
... | random_line_split | |
uploadSourcemap.ts | the user upload up to 5 releases per project.'],
['--minified-dir <path>', 'Path to the directory that contains the minified and ' +
' sourcemap files (I.e, `dist`). Only `.js` and `.map` files will be uploaded.'],
['--project-root <domain>', 'The path of the project root. It helps us locate th... | {
throw new ValidationError('Invalid `end-point`.' +
' You should add valid url like `http://your-domain.com`');
} | conditional_block | |
decl.go | untyped numeric constants, make sure the value
// representation matches what the rest of the
// compiler (really just iexport) expects.
// TODO(mdempsky): Revisit after #43891 is resolved.
val := obj.(*types2.Const).Val()
switch name.Type() {
case types.UntypedInt, types.UntypedRune:
val = constant.ToI... | as2 = ir.NewAssignListStmt(pos, ir.OAS2, make([]ir.Node, len(names)), values)
}
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.