file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
connection.go | package vertigo
// Copyright (c) 2019-2023 Open Text.
//
// 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 applica... | (extraAuthData []byte) error {
passwd, isSet := v.connURL.User.Password()
if !isSet {
passwd = ""
}
hash1 := fmt.Sprintf("%x", md5.Sum([]byte(passwd+v.connURL.User.Username())))
hash2 := fmt.Sprintf("md5%x", md5.Sum(append([]byte(hash1), extraAuthData[0:4]...)))
msg := &msgs.FEPasswordMsg{PasswordData: hash2... | authSendMD5Password | identifier_name |
connection.go | package vertigo
// Copyright (c) 2019-2023 Open Text.
//
// 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 applica... |
msg := &msgs.FEPasswordMsg{PasswordData: passwd}
return v.sendMessage(msg)
}
func (v *connection) authSendMD5Password(extraAuthData []byte) error {
passwd, isSet := v.connURL.User.Password()
if !isSet {
passwd = ""
}
hash1 := fmt.Sprintf("%x", md5.Sum([]byte(passwd+v.connURL.User.Username())))
hash2 := f... | {
passwd = ""
} | conditional_block |
connection.go | package vertigo
// Copyright (c) 2019-2023 Open Text.
//
// 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 applica... |
// 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 | package vertigo
// Copyright (c) 2019-2023 Open Text.
//
// 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 applica... | // 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 | #!/usr/bin/env python3
#
# Generate Synthetic Networks
# First Version: 8/3/2017
#
# An interactive script that generates a JSON file that can be used for
# creating imaginary (enterprise) network profiles
#
# INTERNAL USE ONLY; i.e., user input validation is nearly non-existent.
#
# Cyber Reboot
# alice@cyberreboot.or... |
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 | #!/usr/bin/env python3
#
# Generate Synthetic Networks
# First Version: 8/3/2017
#
# An interactive script that generates a JSON file that can be used for
# creating imaginary (enterprise) network profiles
#
# INTERNAL USE ONLY; i.e., user input validation is nearly non-existent.
#
# Cyber Reboot
# alice@cyberreboot.or... | (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 | #!/usr/bin/env python3
#
# Generate Synthetic Networks
# First Version: 8/3/2017
#
# An interactive script that generates a JSON file that can be used for
# creating imaginary (enterprise) network profiles
#
# INTERNAL USE ONLY; i.e., user input validation is nearly non-existent.
#
# Cyber Reboot
# alice@cyberreboot.or... | subnets.append(nodect)
else:
if MAX_max == -1:
MAX_max = 150
while True:
maximum = int(input('Max hosts in subnet (UP TO 252) [{}]: '.format(MAX_max)) or MAX_max)
if (maxim... | random_line_split | |
gensynet.py | #!/usr/bin/env python3
#
# Generate Synthetic Networks
# First Version: 8/3/2017
#
# An interactive script that generates a JSON file that can be used for
# creating imaginary (enterprise) network profiles
#
# INTERNAL USE ONLY; i.e., user input validation is nearly non-existent.
#
# Cyber Reboot
# alice@cyberreboot.or... |
if __name__ == "__main__":
main()
| 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 | # -*- coding: utf-8 -*-
import urllib2, json, traceback
from django.conf import settings
from django.db import models
from TkManager.order.models import User
from TkManager.juxinli.models import *
from TkManager.juxinli.error_no import *
from TkManager.common.tk_log import TkLog
from datetime import datetime
from djan... | 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 | # -*- coding: utf-8 -*-
import urllib2, json, traceback
from django.conf import settings
from django.db import models
from TkManager.order.models import User
from TkManager.juxinli.models import *
from TkManager.juxinli.error_no import *
from TkManager.common.tk_log import TkLog
from datetime import datetime
from djan... | '''
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 | # -*- coding: utf-8 -*-
import urllib2, json, traceback
from django.conf import settings
from django.db import models
from TkManager.order.models import User
from TkManager.juxinli.models import *
from TkManager.juxinli.error_no import *
from TkManager.common.tk_log import TkLog
from datetime import datetime
from djan... | lif adaptor["data_type"] == "map": #data_list是单条数据
record = data_list
ret_code = self._save_single_obj(record, cls, user, adaptor, version, parent)
if ret_code != 0:
return ret_code
transaction.commit()
return 0
def _save_single_obj(self, record... | _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 | # -*- coding: utf-8 -*-
import urllib2, json, traceback
from django.conf import settings
from django.db import models
from TkManager.order.models import User
from TkManager.juxinli.models import *
from TkManager.juxinli.error_no import *
from TkManager.common.tk_log import TkLog
from datetime import datetime
from djan... | 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 | // Copyright (c) 2020-2022 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package rpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strconv"
"blockwatch.cc/tzgo/tezos"
)
// BakingRight holds simplified information about the right to bake a specific Tezos block
type BakingRight struct {
Delegate strin... |
// 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 | // Copyright (c) 2020-2022 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package rpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strconv"
"blockwatch.cc/tzgo/tezos"
)
// BakingRight holds simplified information about the right to bake a specific Tezos block
type BakingRight struct {
Delegate strin... |
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 | // Copyright (c) 2020-2022 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package rpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strconv"
"blockwatch.cc/tzgo/tezos"
)
// BakingRight holds simplified information about the right to bake a specific Tezos block
type BakingRight struct {
Delegate strin... | idx.Index = 15
// if cycle > p.PreservedCycles+1 {
if idx.Base <= 0 {
log.Debugf("No snapshot for cycle %d", cycle)
} else {
u := fmt.Sprintf("chains/main/blocks/%s/context/selected_snapshot?cycle=%d", id, cycle)
// log.Infof("GET %s", u)
if err := c.Get(ctx, u, &idx.Index); err != nil {
return ... | idx.Base = p.SnapshotBaseCycle(cycle)
idx.Index = info.RollSnapshot
} else {
idx.Cycle = cycle
idx.Base = p.SnapshotBaseCycle(cycle) | random_line_split |
rights.go | // Copyright (c) 2020-2022 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package rpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strconv"
"blockwatch.cc/tzgo/tezos"
)
// BakingRight holds simplified information about the right to bake a specific Tezos block
type BakingRight struct {
Delegate strin... | (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 | mod error;
use std::fs::{self, File, OpenOptions};
use std::io::{self, stdin, stdout, Write};
use std::ops::Deref;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use error_chain::bail;
use hex::FromHex;
use lazy_static::lazy_static;
use seckey::SecBytes;
use serde::{Deserialize, Serialize};
us... | skey_file.encrypt(passwd);
skey_file.save(skey_path)?;
pkey_file.save(pkey_path)?;
println!("Generated {} and {}", pkey_path.display(), skey_path.display());
Ok((pkey_file, skey_file))
}
fn prompt_skey(skey_path: &Path, prompt: impl AsRef<str>) -> Result<SecretKeyFile, Error> {
let mu... | let passwd = Passwd::prompt_new()
.chain_err(|| skey_path )?;
let (pkey_file, mut skey_file) = SecretKeyFile::new();
| random_line_split |
lib.rs | mod error;
use std::fs::{self, File, OpenOptions};
use std::io::{self, stdin, stdout, Write};
use std::ops::Deref;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use error_chain::bail;
use hex::FromHex;
use lazy_static::lazy_static;
use seckey::SecBytes;
use serde::{Deserialize, Serialize};
us... |
/// Get a SecretKeyFile from a path. If the file is encrypted, prompt for a password on stdin.
pub fn get_skey(skey_path: &Path) -> Result<SecretKeyFile, Error> {
prompt_skey(skey_path, "Passphrase for")
}
/// Open, decrypt, re-encrypt with a different passphrase from stdin, and save the newly encrypted
/// sec... | {
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 | mod error;
use std::fs::{self, File, OpenOptions};
use std::io::{self, stdin, stdout, Write};
use std::ops::Deref;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use error_chain::bail;
use hex::FromHex;
use lazy_static::lazy_static;
use seckey::SecBytes;
use serde::{Deserialize, Serialize};
us... | (&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 | from deap import base
from deap import algorithms
from deap import tools
from deap import creator
import random
import functools
import numpy as np
import scipy.signal as signal
creator.create(
'ResponseMismatch', base.Fitness, weights=(1.0,)
)
creator.create(
'IIR', list, fitness=creator.ResponseMismatch, nb... | cxpb=0.7, ndpb=0.5,
mutpb=0.2, mutmean=0.0, mutstd=0.3, coeffpb=0.1,
tournsize=3, nind=1000, eprop=0.005, ngen=400,
verbose=__debug__):
"""
Configura una función de aproximación de filtros digitales IIR en punto
fijo con... | 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 | from deap import base
from deap import algorithms
from deap import tools
from deap import creator
import random
import functools
import numpy as np
import scipy.signal as signal
creator.create(
'ResponseMismatch', base.Fitness, weights=(1.0,)
)
creator.create(
'IIR', list, fitness=creator.ResponseMismatch, nb... | mutpb=0.2, mutmean=0.0, mutstd=0.3, coeffpb=0.1,
tournsize=3, nind=1000, eprop=0.005, ngen=400,
verbose=__debug__):
"""
Configura una función de aproximación de filtros digitales IIR en punto
fijo con una dada respuesta al impulso.... | .7, ndpb=0.5,
| identifier_name |
fwliir.py | from deap import base
from deap import algorithms
from deap import tools
from deap import creator
import random
import functools
import numpy as np
import scipy.signal as signal
creator.create(
'ResponseMismatch', base.Fitness, weights=(1.0,)
)
creator.create(
'IIR', list, fitness=creator.ResponseMismatch, nb... | 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 | from deap import base
from deap import algorithms
from deap import tools
from deap import creator
import random
import functools
import numpy as np
import scipy.signal as signal
creator.create(
'ResponseMismatch', base.Fitness, weights=(1.0,)
)
creator.create(
'IIR', list, fitness=creator.ResponseMismatch, nb... | """
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 | // 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... |
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 | // 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... | (&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 | // 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... |
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 | // 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... | 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 | // MIT/Apache2 License
//! This module defines the `Display` object, which acts as a connection to the X11 server, and the
//! `Connection` trait, which the `Display` object abstracts itself over. See the documentation for
//! these objects for more information.
use crate::{
auth_info::AuthInfo,
auto::{
... |
#[cfg(feature = "std")]
impl DisplayConnection {
/// Create a new connection to the X server, given an optional name and authorization information.
#[inline]
pub fn create(name: Option<Cow<'_, str>>, auth_info: Option<AuthInfo>) -> crate::Result<Self> {
let connection = name::NameConnection::connec... | /// 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 | // MIT/Apache2 License
//! This module defines the `Display` object, which acts as a connection to the X11 server, and the
//! `Connection` trait, which the `Display` object abstracts itself over. See the documentation for
//! these objects for more information.
use crate::{
auth_info::AuthInfo,
auto::{
... | (&mut self) -> crate::Result<Event> {
loop {
match self.event_queue.pop_front() {
Some(event) => break Ok(event),
None => self.wait_async().await?,
}
}
}
/// If there is an event currently in the queue that matches the predicate, returns t... | wait_for_event_async | identifier_name |
solvers.py | """
Functions concerned with solving for decoders or full weight matrices.
Many of the solvers in this file can solve for decoders or weight matrices,
depending on whether the post-population encoders `E` are provided (see below).
Solvers that are only intended to solve for either decoders or weights can
remove the `E... |
def __call__(self, A, Y, rng=None, E=None):
sigma = self.reg * A.max()
X, info = self.solver(A, Y, sigma, **self.kwargs)
return self.mul_encoders(X, E), info
class LstsqL2nz(_LstsqL2Solver):
"""Least-squares with L2 regularization on non-zero components."""
def __call__(self, A, ... | class LstsqL2(_LstsqL2Solver):
"""Least-squares with L2 regularization.""" | random_line_split |
solvers.py | """
Functions concerned with solving for decoders or full weight matrices.
Many of the solvers in this file can solve for decoders or weight matrices,
depending on whether the post-population encoders `E` are provided (see below).
Solvers that are only intended to solve for either decoders or weights can
remove the `E... |
def __call__(self, A, Y, rng=None, E=None):
Y, m, n, d, matrix_in = _format_system(A, Y)
# solve for coefficients using standard solver
X, info0 = self.solver1(A, Y, rng=rng)
X = self.mul_encoders(X, E)
# drop weights close to zero, based on `drop` ratio
Xabs = np... | """
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 | """
Functions concerned with solving for decoders or full weight matrices.
Many of the solvers in this file can solve for decoders or weight matrices,
depending on whether the post-population encoders `E` are provided (see below).
Solvers that are only intended to solve for either decoders or weights can
remove the `E... | (_LstsqL2Solver):
"""Least-squares with L2 regularization on non-zero components."""
def __call__(self, A, Y, rng=None, E=None):
# Compute the equivalent noise standard deviation. This equals the
# base amplitude (noise_amp times the overall max activation) times
# the square-root of th... | LstsqL2nz | identifier_name |
solvers.py | """
Functions concerned with solving for decoders or full weight matrices.
Many of the solvers in this file can solve for decoders or weight matrices,
depending on whether the post-population encoders `E` are provided (see below).
Solvers that are only intended to solve for either decoders or weights can
remove the `E... |
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 | from django.db import models
from django.db import transaction
from django.shortcuts import get_object_or_404
import datetime
import time
from django.utils import timezone
import backoff
import dramatiq
from django.utils.encoding import smart_text as smart_unicode
from django.utils.translation import ugettext_lazy... |
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 | from django.db import models
from django.db import transaction
from django.shortcuts import get_object_or_404
import datetime
import time
from django.utils import timezone
import backoff
import dramatiq
from django.utils.encoding import smart_text as smart_unicode
from django.utils.translation import ugettext_lazy... | )
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 | from django.db import models
from django.db import transaction
from django.shortcuts import get_object_or_404
import datetime
import time
from django.utils import timezone
import backoff
import dramatiq
from django.utils.encoding import smart_text as smart_unicode
from django.utils.translation import ugettext_lazy... | (models.Model):
'''
Notifications for users. Currently used for feed update success/failure events
'''
owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)
feed = models.ForeignKey(Feed, on_delete=models.CASCADE)
state = models.IntegerField(default=ENTRY_UNREAD, choices=(
... | Notification | identifier_name |
models.py | from django.db import models
from django.db import transaction
from django.shortcuts import get_object_or_404
import datetime
import time
from django.utils import timezone
import backoff
import dramatiq
from django.utils.encoding import smart_text as smart_unicode
from django.utils.translation import ugettext_lazy... |
# Enrty #################################################
class Entry(models.Model):
"""
Represents a feed entry object
If creating from a feedparser entry, use Entry.objects.parseFromFeed()
"""
feed = models.ForeignKey(Feed, related_name='feed', on_delete=models.CASCADE)
state = mod... | '''
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 | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::core::config::ApplicationCfg;
use crate::mvt_service::MvtService;
use crate::runtime_config::{config_from_args, service_from_args};
use crate::st... | .service(
web::resource("/{tileset}/{z}/{x}/{y}.pbf").route(
web::route()
.guard(guard::Any(guard::Get()).or(guard::Head()))
.to(tile_pbf),
),
);
if mvt_viewer {
app = app.serv... | random_line_split | |
server.rs | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::core::config::ApplicationCfg;
use crate::mvt_service::MvtService;
use crate::runtime_config::{config_from_args, service_from_args};
use crate::st... | (
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 | //
// Copyright (c) Pirmin Kalberer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
use crate::core::config::ApplicationCfg;
use crate::mvt_service::MvtService;
use crate::runtime_config::{config_from_args, service_from_args};
use crate::st... |
lazy_static! {
static ref STATIC_FILES: StaticFiles = StaticFiles::init();
}
async fn static_file_handler(req: HttpRequest) -> Result<HttpResponse> {
let key = req.path()[1..].to_string();
let resp = if let Some(ref content) = STATIC_FILES.content(None, key) {
HttpResponse::Ok()
.inse... | {
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 | import base64
import hashlib
import json
import os
import subprocess
import sys
import typing
import pexpect
from Configs.Constants import PBNB_ID, PBTC_ID
from Drivers.Connections import RpcConnection
from Helpers.Logging import config_logger
from Helpers.TestHelper import l6, json_extract
from Helpers.Time import W... |
@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 | import base64
import hashlib
import json
import os
import subprocess
import sys
import typing
import pexpect
from Configs.Constants import PBNB_ID, PBTC_ID
from Drivers.Connections import RpcConnection
from Helpers.Logging import config_logger
from Helpers.TestHelper import l6, json_extract
from Helpers.Time import W... | (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 | import base64
import hashlib
import json
import os
import subprocess
import sys
import typing
import pexpect
from Configs.Constants import PBNB_ID, PBTC_ID
from Drivers.Connections import RpcConnection
from Helpers.Logging import config_logger
from Helpers.TestHelper import l6, json_extract
from Helpers.Time import W... |
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 | import base64
import hashlib
import json
import os
import subprocess
import sys
import typing
import pexpect
from Configs.Constants import PBNB_ID, PBTC_ID
from Drivers.Connections import RpcConnection
from Helpers.Logging import config_logger
from Helpers.TestHelper import l6, json_extract
from Helpers.Time import W... | 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 | #!/usr/bin/env python
#dots.py
import sys
import os
import pickle
import time
import random
from VisionEgg.Textures import *
from VisionEgg.Core import *
from VisionEgg.FlowControl import TIME_INDEPENDENT
from VisionEgg.FlowControl import Presentation, FunctionController, TIME_SEC_ABSOLUTE, FRAMES_ABSOL... | (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 | #!/usr/bin/env python
#dots.py
import sys
import os
import pickle
import time
import random
from VisionEgg.Textures import *
from VisionEgg.Core import *
from VisionEgg.FlowControl import TIME_INDEPENDENT
from VisionEgg.FlowControl import Presentation, FunctionController, TIME_SEC_ABSOLUTE, FRAMES_ABSOL... | 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 | #!/usr/bin/env python
#dots.py
import sys
import os
import pickle
import time
import random
from VisionEgg.Textures import *
from VisionEgg.Core import *
from VisionEgg.FlowControl import TIME_INDEPENDENT
from VisionEgg.FlowControl import Presentation, FunctionController, TIME_SEC_ABSOLUTE, FRAMES_ABSOL... |
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 | #!/usr/bin/env python
#dots.py
import sys
import os
import pickle
import time
import random
from VisionEgg.Textures import *
from VisionEgg.Core import *
from VisionEgg.FlowControl import TIME_INDEPENDENT
from VisionEgg.FlowControl import Presentation, FunctionController, TIME_SEC_ABSOLUTE, FRAMES_ABSOL... |
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 | use bevy_math::{Mat4, Quat, Vec2, Vec3};
use bevy_utils::Duration;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::{Deref, Mul},
};
// Note: indices follow WebXR convention. OpenXR's palm joint is missing, but it can be retrieved
// using `XrTrackingSource::hands_pose()`.
pub const X... |
/// 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 | use bevy_math::{Mat4, Quat, Vec2, Vec3};
use bevy_utils::Duration;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::{Deref, Mul},
};
// Note: indices follow WebXR convention. OpenXR's palm joint is missing, but it can be retrieved
// using `XrTrackingSource::hands_pose()`.
pub const X... | else {
XrButtonState::Default
}
}
pub fn button_touched(&self, action: &str) -> bool {
if let Some(XrActionState::Button { state, .. }) = self.current_states.get(action) {
*state != XrButtonState::Default
} else {
false
}
}
pub fn bu... | {
*state
} | conditional_block |
interaction.rs | use bevy_math::{Mat4, Quat, Vec2, Vec3};
use bevy_utils::Duration;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::{Deref, Mul},
};
// Note: indices follow WebXR convention. OpenXR's palm joint is missing, but it can be retrieved
// using `XrTrackingSource::hands_pose()`.
pub const X... | {
pub left_hand: Option<String>,
pub right_hand: Option<String>,
}
| XrProfiles | identifier_name |
interaction.rs | use bevy_math::{Mat4, Quat, Vec2, Vec3};
use bevy_utils::Duration;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::{Deref, Mul},
};
// Note: indices follow WebXR convention. OpenXR's palm joint is missing, but it can be retrieved
// using `XrTrackingSource::hands_pose()`.
pub const X... | }
pub fn binary_value(&self, action: &str) -> bool {
if let Some(XrActionState::Binary(value)) = self.current_states.get(action) {
*value
} else {
self.button_pressed(action)
}
}
pub fn scalar_value(&self, action: &str) -> f32 {
if let Some(XrAct... | 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 | // Copyright 2015 The Cockroach 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 ag... | () 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 | // Copyright 2015 The Cockroach 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 ag... |
if match {
act.Datapoints[0].Value = 0.0
}
}
// Actual comparison is simple: sort the resulting arrays by time and name,
// and use reflect.DeepEqual.
sort.Sort(byTimeAndName(actual))
sort.Sort(byTimeAndName(expected))
if a, e := actual, expected; !reflect.DeepEqual(a, e) {
t.Errorf("recorder did not y... | {
t.Fatal(err)
} | conditional_block |
recorder_test.go | // Copyright 2015 The Cockroach 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 ag... |
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 | // Copyright 2015 The Cockroach 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 ag... | 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 | import IDocumentWriter from '../../documentWriter/IDocumentWriter';
import {
ConcreteDocumentNode,
ConcreteElementNode,
ConcreteNode,
NODE_TYPES
} from '../../domFacade/ConcreteNode';
import IWrappingDomFacade from '../../domFacade/IWrappingDomFacade';
import INodesFactory from '../../nodesFactory/INodesFactory';
i... | (
dynamicContext: DynamicContext,
executionParameters: ExecutionParameters
): ISequence {
// If we were updating, the calling code would have called the evaluateWithUpdateList
// method. We can assume we're not actually updating
const pendingUpdateIterator = this.evaluateWithUpdateList(
dynamicContext,
... | evaluate | identifier_name |
TransformExpression.ts | import IDocumentWriter from '../../documentWriter/IDocumentWriter';
import {
ConcreteDocumentNode,
ConcreteElementNode,
ConcreteNode,
NODE_TYPES
} from '../../domFacade/ConcreteNode';
import IWrappingDomFacade from '../../domFacade/IWrappingDomFacade';
import INodesFactory from '../../nodesFactory/INodesFactory';
i... |
// 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 | import IDocumentWriter from '../../documentWriter/IDocumentWriter';
import {
ConcreteDocumentNode,
ConcreteElementNode,
ConcreteNode,
NODE_TYPES
} from '../../domFacade/ConcreteNode';
import IWrappingDomFacade from '../../domFacade/IWrappingDomFacade';
import INodesFactory from '../../nodesFactory/INodesFactory';
i... |
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 | import IDocumentWriter from '../../documentWriter/IDocumentWriter';
import {
ConcreteDocumentNode,
ConcreteElementNode,
ConcreteNode,
NODE_TYPES
} from '../../domFacade/ConcreteNode';
import IWrappingDomFacade from '../../domFacade/IWrappingDomFacade';
import INodesFactory from '../../nodesFactory/INodesFactory';
i... |
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 | window.onload = function () {
// 初始化首页
getHomePageList(200);
// 初始化话题页
getTopic();
// 初始化小册页
getBrochure();
};
// 打开主菜单时设置相应菜单显示和隐藏
function openMainMenu(event) {
var topic = document.querySelector('.content-container .topic-box');
var homepage = document.querySelector('.content-container .content-box'... | % 24);
let min = parseInt((msec / 1000 / 60) % 60);
let sec = parseInt((msec / 1000) % 60);
let minsec = parseInt((msec % 1000) / 10);
// 个位数前补零
hr = hr > 9 ? hr : '0' + hr;
min = min > 9 ? min : '0' + min;
sec = sec > 9 ? sec : '0' + sec;
minsec = minsec > 9 ? minsec : ... | 60 / 60) | identifier_name |
index.js | window.onload = function () {
// 初始化首页
getHomePageList(200);
// 初始化话题页
getTopic();
// 初始化小册页
getBrochure();
};
// 打开主菜单时设置相应菜单显示和隐藏
function openMainMenu(event) {
var topic = document.querySelector('.content-container .topic-box');
var homepage = document.querySelector('.content-container .content-box'... | 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 | window.onload = function () {
// 初始化首页
getHomePageList(200);
// 初始化话题页
getTopic();
// 初始化小册页
getBrochure();
};
// 打开主菜单时设置相应菜单显示和隐藏
function openMainMenu(event) {
var topic = document.querySelector('.content-container .topic-box');
var homepage = document.querySelector('.content-container .content-box'... | type: 'POST',
contentType: 'application/json',
data: JSON.stringify(obj),
success: function (result) {
initBrochure(result.data);
},
error: function (err) {
console.log(err);
},
});
}
// 初始化小册页
function initBrochure(data) {
var brochureList = '';
data.forEach(function (ite... | 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 | window.onload = function () {
// 初始化首页
getHomePageList(200);
// 初始化话题页
getTopic();
// 初始化小册页
getBrochure();
};
// 打开主菜单时设置相应菜单显示和隐藏
function openMainMenu(event) {
var topic = document.querySelector('.content-container .topic-box');
var homepage = document.querySelector('.content-container .content-box'... | 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 | //! A futures executor as an event source
//!
//! Only available with the `executor` cargo feature of `calloop`.
//!
//! This executor is intended for light futures, which will be polled as part of your
//! event loop. Such futures may be waiting for IO, or for some external computation on an
//! other thread for examp... | (&mut self, poll: &mut Poll) -> crate::Result<()> {
self.ping.unregister(poll)?;
Ok(())
}
}
/// An error arising from processing events in an async executor event source.
#[derive(thiserror::Error, Debug)]
pub enum ExecutorError {
/// Error while reading new futures added via [`Scheduler::sched... | unregister | identifier_name |
futures.rs | //! A futures executor as an event source
//!
//! Only available with the `executor` cargo feature of `calloop`.
//!
//! This executor is intended for light futures, which will be polled as part of your
//! event loop. Such futures may be waiting for IO, or for some external computation on an
//! other thread for examp... |
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
F: ... | {
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 | //! A futures executor as an event source
//!
//! Only available with the `executor` cargo feature of `calloop`.
//!
//! This executor is intended for light futures, which will be polled as part of your
//! event loop. Such futures may be waiting for IO, or for some external computation on an
//! other thread for examp... | 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 | //! A futures executor as an event source
//!
//! Only available with the `executor` cargo feature of `calloop`.
//!
//! This executor is intended for light futures, which will be polled as part of your
//! event loop. Such futures may be waiting for IO, or for some external computation on an
//! other thread for examp... |
// 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 | /******************************************************************************
*
* Copyright 2020 SAP SE
*
* 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/li... | 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 | /******************************************************************************
*
* Copyright 2020 SAP SE
*
* 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/li... |
_, 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 | /******************************************************************************
*
* Copyright 2020 SAP SE
*
* 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/li... | () (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 | /******************************************************************************
*
* Copyright 2020 SAP SE
*
* 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/li... |
var syncManifestRepoSelectQuery = keppel.SimplifyWhitespaceInSQL(`
SELECT r.* FROM repos r
JOIN accounts a ON r.account_name = a.name
WHERE (r.next_manifest_sync_at IS NULL OR r.next_manifest_sync_at < $1)
-- only consider repos in replica accounts
AND a.upstream_peer_hostname != ''
-- repos without any syn... | {
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 | #![allow(clippy::unnecessary_mut_passed)]
#![warn(clippy::unimplemented, clippy::todo)]
// This example is another version of `passthrough.rs` that uses the
// path strings instead of the file descriptors with `O_PATH` flag
// for referencing the underlying file entries.
// It has the advantage of being able to use st... | {
use futures::io::AsyncReadExt;
reader.read_to_end(&mut buf).await?;
}
use tokio::io::AsyncReadExt;
let mut buf = &buf[..];
let mut buf = (&mut buf).take(op.size() as u64);
let written = tokio::io::copy(&mut buf, &mut *file).await?;
Ok(R... | let mut buf = Vec::with_capacity(op.size() as usize); | random_line_split |
path_through.rs | #![allow(clippy::unnecessary_mut_passed)]
#![warn(clippy::unimplemented, clippy::todo)]
// This example is another version of `passthrough.rs` that uses the
// path strings instead of the file descriptors with `O_PATH` flag
// for referencing the underlying file entries.
// It has the advantage of being able to use st... | (&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 | #!/usr/bin/env python
import ROOT
from array import array
from CMGTools.VVResonances.plotting.TreePlotter import TreePlotter
from CMGTools.VVResonances.plotting.MergedPlotter import MergedPlotter
from CMGTools.VVResonances.plotting.StackPlotter import StackPlotter
from CMGTools.VVResonances.statistics.Fitter import Fi... | legend.SetFillColor(0)
legend.SetTextFont(42)
legend.SetTextSize(0.04)
legend.SetTextAlign(12)
legend.AddEntry(graphs["Zjets"],"ratio Z+jets m_{jet1}","lp")
legend.AddEntry(graphs["Zjets"].GetFunction("pol"),"fit m_{jet1}","lp")
legend.Draw("same")
text.DrawLatexNDC(0.13,0.92,"#font[62]{... | random_line_split | |
vvMakeVjetsShapes.py | #!/usr/bin/env python
import ROOT
from array import array
from CMGTools.VVResonances.plotting.TreePlotter import TreePlotter
from CMGTools.VVResonances.plotting.MergedPlotter import MergedPlotter
from CMGTools.VVResonances.plotting.StackPlotter import StackPlotter
from CMGTools.VVResonances.statistics.Fitter import Fi... |
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 | #!/usr/bin/env python
import ROOT
from array import array
from CMGTools.VVResonances.plotting.TreePlotter import TreePlotter
from CMGTools.VVResonances.plotting.MergedPlotter import MergedPlotter
from CMGTools.VVResonances.plotting.StackPlotter import StackPlotter
from CMGTools.VVResonances.statistics.Fitter import Fi... | (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 | #!/usr/bin/env python
import ROOT
from array import array
from CMGTools.VVResonances.plotting.TreePlotter import TreePlotter
from CMGTools.VVResonances.plotting.MergedPlotter import MergedPlotter
from CMGTools.VVResonances.plotting.StackPlotter import StackPlotter
from CMGTools.VVResonances.statistics.Fitter import Fi... |
if "Zjets" in histos.keys() and "TTbar" in histos.keys():
params["ratio_Res_nonRes_"+leg]= {'ratio': scales["Wjets"]/scales_nonRes["Wjets"] , 'ratio_Z': scales["Zjets"]/scales_nonRes["Zjets"],'ratio_TT': scales["TTbar"]/scales_nonRes["TTbar"]}
fitter.drawVjets("Vjets_mjetRes_"+leg+"_"+purity... | 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 | // Copyright 2020 Dolthub, 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 i... | (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 | // Copyright 2020 Dolthub, 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 i... |
// 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, rsr env.RepoStateReader) (bool, error) {
// The error return value is only for propagating unhandled errors from rsr.CWBHeadRef... | {
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 | // Copyright 2020 Dolthub, 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 i... |
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 | // Copyright 2020 Dolthub, 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 i... | }
if dryrun {
return roots, nil
}
roots.Working = newRoot
return roots, nil
}
// mapColumnTags takes a map from table name to schema.Schema and generates
// a map from column tags to table names (see RootValue.GetAllSchemas).
func mapColumnTags(tables map[string]schema.Schema) (m map[uint64]string) {
m = mak... | 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 | package output
import (
"database/sql"
"encoding/json"
"fmt"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
clickhouse "github.com/ClickHouse/clickhouse-go"
"github.com/childe/gohangout/topology"
"github.com/golang/glog"
"github.com/spf13/cast"
)
const (
CLICKHOUSE_DEFAULT_BULK_ACTIONS =... | string, number and ip DEFAULT expression is supported for now
func (c *ClickhouseOutput) setColumnDefault() {
c.setTableDesc()
c.defaultValue = make(map[string]interface{})
var defaultValue *string
for columnName, d := range c.desc {
switch d.DefaultType {
case "DEFAULT":
defaultValue = &(d.DefaultExpres... | {
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 | package output
import (
"database/sql"
"encoding/json"
"fmt"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
clickhouse "github.com/ClickHouse/clickhouse-go"
"github.com/childe/gohangout/topology"
"github.com/golang/glog"
"github.com/spf13/cast"
)
const (
CLICKHOUSE_DEFAULT_BULK_ACTIONS =... | 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 | package output
import (
"database/sql"
"encoding/json"
"fmt"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
clickhouse "github.com/ClickHouse/clickhouse-go"
"github.com/childe/gohangout/topology"
"github.com/golang/glog"
"github.com/spf13/cast"
)
const (
CLICKHOUSE_DEFAULT_BULK_ACTIONS =... | seOutput) convert(event map[string]interface{}) {
for _, key := range c.transIntColumn {
if keyIntValue, ok := event[key]; ok {
if intConverterValue, err := cast.ToInt64E(keyIntValue); err == nil {
event[key] = intConverterValue
} else {
glog.V(10).Infof("ch_output convert intType error: %s", err)
... | 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 | package output
import (
"database/sql"
"encoding/json"
"fmt"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
clickhouse "github.com/ClickHouse/clickhouse-go"
"github.com/childe/gohangout/topology"
"github.com/golang/glog"
"github.com/spf13/cast"
)
const (
CLICKHOUSE_DEFAULT_BULK_ACTIONS =... | }
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 | import Layout from "../components/layout"
import Metadata from "../components/metadata"
import React from "react"
const PrivacyStatement = () => (
<Layout>
<Metadata title="Privacy Statement" />
<section>
<div className="row">
<div className="col-xs-12 col-sm-9 col-md-9 col-lg-9">
<h1... | <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 | // Copyright 2021-2023 Vector 35 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... | {
register(
"DWARF Dump",
"Show embedded DWARF info as a tree structure for you to navigate",
DWARFDump {},
);
true
} | identifier_body | |
lib.rs | // Copyright 2021-2023 Vector 35 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... | 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 | // Copyright 2021-2023 Vector 35 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... | // 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 | // Copyright 2021-2023 Vector 35 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... | <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 | #!/usr/bin/python
import copy
import sys
import random
last_state_list = list()
current_state_list = list()
class tictactoe(object):
def __init__(self, gameState=['.','.','.','.','.','.','.','.','.']):
self.gameState = gameState
#Check if 3 in a row in any way on the board
def three_in_a_row(self, player):
|
#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 | #!/usr/bin/python
import copy
import sys
import random
last_state_list = list()
current_state_list = list()
class tictactoe(object):
def __init__(self, gameState=['.','.','.','.','.','.','.','.','.']):
self.gameState = gameState
#Check if 3 in a row in any way on the board
def three_in_a_row(self, player):
fo... | (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 | #!/usr/bin/python
import copy
import sys
import random
last_state_list = list()
current_state_list = list()
class tictactoe(object):
def __init__(self, gameState=['.','.','.','.','.','.','.','.','.']):
self.gameState = gameState
#Check if 3 in a row in any way on the board
def three_in_a_row(self, player):
fo... | 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 | #!/usr/bin/python
import copy
import sys
import random
last_state_list = list()
current_state_list = list()
class tictactoe(object):
def __init__(self, gameState=['.','.','.','.','.','.','.','.','.']):
self.gameState = gameState
#Check if 3 in a row in any way on the board
def three_in_a_row(self, player):
fo... |
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 | import {djaty} from '@djaty/djaty-nodejs';
import * as glob from 'glob';
import * as fs from 'fs';
import * as path from 'path';
import * as ora from 'ora';
import * as tar from 'tar';
import * as os from 'os';
import * as requestPromise from 'request-promise';
// tslint:disable-next-line no-require-imports
const urlR... |
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').start();
let minifiedFileListPaths: string[] = []... | {
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 | import {djaty} from '@djaty/djaty-nodejs';
import * as glob from 'glob';
import * as fs from 'fs';
import * as path from 'path';
import * as ora from 'ora';
import * as tar from 'tar';
import * as os from 'os';
import * as requestPromise from 'request-promise';
// tslint:disable-next-line no-require-imports
const urlR... | (cmd: UploadSourcemapCMDParams | string) {
if (typeof cmd === 'string') {
throw new ValidationError(`Invalid args params: '${cmd}'`);
}
if (!cmd.apiKey || !cmd.apiSecret || !cmd.release || !cmd.minifiedDir || !cmd.projectRoot) {
throw new ValidationError('Command params (apiKey, apiSecret,' +
... | validateOnCLIInput | identifier_name |
uploadSourcemap.ts | import {djaty} from '@djaty/djaty-nodejs';
import * as glob from 'glob';
import * as fs from 'fs';
import * as path from 'path';
import * as ora from 'ora';
import * as tar from 'tar';
import * as os from 'os';
import * as requestPromise from 'request-promise';
// tslint:disable-next-line no-require-imports
const urlR... | 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 | import {djaty} from '@djaty/djaty-nodejs';
import * as glob from 'glob';
import * as fs from 'fs';
import * as path from 'path';
import * as ora from 'ora';
import * as tar from 'tar';
import * as os from 'os';
import * as requestPromise from 'request-promise';
// tslint:disable-next-line no-require-imports
const urlR... |
};
private static saveRemove(path: string) {
return fs.existsSync(path) && fs.unlinkSync(path);
}
}
| {
throw new ValidationError('Invalid `end-point`.' +
' You should add valid url like `http://your-domain.com`');
} | conditional_block |
decl.go | // Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package noder
import (
"go/constant"
"cmd/compile/internal/base"
"cmd/compile/internal/ir"
"cmd/compile/internal/syntax"
"cmd/compile/internal/typecheck"... | for i, name := range names {
if ir.CurFunc != nil {
out.Append(ir.NewDecl(pos, ir.ODCL, name))
}
if as2 != nil {
as2.Lhs[i] = name
name.Defn = as2
} else {
as := ir.NewAssignStmt(pos, name, nil)
if len(values) != 0 {
as.Y = values[i]
name.Defn = as
} else if ir.CurFunc ==... | 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.