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 |
|---|---|---|---|---|
index.ts | (v: T) => TResult | Promise<TResult>,
onRejected?: (reason: any) => Promise<never>,
): Promise<TResult> {
return this._promise.then<TResult>(onFulfilled, onRejected);
}
public catch<TResult>(onRejected?: (reason: any) => Promise<TResult>): Promise<TResult | T> {
return this._promise... | {
protected _abiEncoderByFunctionSignature: AbiEncoderByFunctionSignature;
protected _web3Wrapper: Web3Wrapper;
public abi: ContractAbi;
public address: string;
public contractName: string;
public constructorArgs: any[] = [];
public _deployedBytecodeIfExists?: Buffer;
private _evmIfExis... | BaseContract | identifier_name |
index.ts | ContractEvent,
SendTransactionOpts,
AwaitTransactionSuccessOpts,
ContractFunctionObj,
ContractTxFunctionObj,
SubscriptionErrors,
} from './types';
export interface AbiEncoderByFunctionSignature {
[key: string]: AbiEncoder.Method;
}
const ARBITRARY_PRIVATE_KEY = 'e331b6d69882b4cb4ea581d88e0... | export { | random_line_split | |
cluster.go | PgStorageSpec `json:replicastorage`
BackrestStorage PgStorageSpec `json:backreststorage`
// Resources behaves just like the "Requests" section of a Kubernetes
// container definition. You can set individual items such as "cpu" and
// "memory", e.g. "{ cpu: "0.5", memory: "2Gi" }"
Resources v1.ResourceList `json:"... | random_line_split | ||
cluster.go | badgerport"`
ExporterPort string `json:"exporterport"`
PrimaryStorage PgStorageSpec `json:primarystorage`
WALStorage PgStorageSpec `json:walstorage`
ArchiveStorage PgStorageSpec `json:archivestorage`
ReplicaStorage PgStorageSpec `json:replicastorage`
BackrestStorage PgStorageSpec `json:backrests... | {
return (t.TLSSecret != "" && t.CASecret != "")
} | identifier_body | |
cluster.go | Crunchy PG Cluster Spec
// swagger:ignore
type PgclusterSpec struct {
Namespace string `json:"namespace"`
Name string `json:"name"`
ClusterName string `json:"clustername"`
Policies string `json:"policies"`
CCPImage string `json:"ccpimage"`
CCP... | () bool {
return s.Replicas > 0
}
// TLSSpec contains the information to set up a TLS-enabled PostgreSQL cluster
type TLSSpec struct {
// CASecret contains the name of the secret to use as the trusted CA for the
// TLSSecret
// This is our own format and should contain at least one key: "ca.crt"
// It can also co... | Enabled | identifier_name |
service.go | err != nil {
return errors.Wrap(err, "failed to process channels")
}
}
}
}
// RSSFeed generates RSS feed for given channel
func (s *Service) RSSFeed(fi FeedInfo) (string, error) | }
duration := ""
if entry.Duration > 0 {
duration = fmt.Sprintf("%d", entry.Duration)
}
items = append(items, rssfeed.Item{
Title: entry.Title,
Description: entry.Media.Description,
Link: entry.Link.Href,
PubDate: entry.Published.In(time.UTC).Format(time.RFC1123Z),
GUID: ... | {
entries, err := s.Store.Load(fi.ID, s.keep(fi))
if err != nil {
return "", errors.Wrap(err, "failed to get channel entries")
}
if len(entries) == 0 {
return "", nil
}
items := []rssfeed.Item{}
for _, entry := range entries {
fileURL := s.RootURL + "/" + path.Base(entry.File)
var fileSize int
if f... | identifier_body |
service.go |
for _, f := range s.Feeds {
log.Printf("[INFO] youtube feed %+v", f)
}
tick := time.NewTicker(s.CheckDuration)
defer tick.Stop()
if err := s.procChannels(ctx); err != nil {
return errors.Wrap(err, "failed to process channels")
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-tick.C:
... | {
log.Printf("[DEBUG] skip youtube episodes shorter than %v", s.SkipShorts)
} | conditional_block | |
service.go | INFO] new entry [%d] %s, %s, %s, %s", i+1, entry.VideoID, entry.Title, feedInfo.Name, entry.String())
file, downErr := s.Downloader.Get(ctx, entry.VideoID, s.makeFileName(entry))
if downErr != nil {
allStats.ignored++
if downErr == ytfeed.ErrSkip { // downloader decided to skip this entry
log.Printf... | totalEntriesToKeep | identifier_name | |
service.go | return errors.Wrapf(err, "failed to check if entry %s is relevant", entry.VideoID)
}
if !isAllowed {
log.Printf("[DEBUG] skipping filtered %s", entry.String())
allStats.ignored++
continue
}
ok, err := s.isNew(entry, feedInfo)
if err != nil {
return errors.Wrapf(err, "failed to check if ... | log.Printf("[DEBUG] updated entry: %s", entry.String()) | random_line_split | |
mod.rs | _mem: usize,
show_gc: bool,
show_allocates: bool,
show_heap_map: bool,
show_free_list: bool,
}
impl<'a> IntoIterator for &'a Memory {
type Item = usize;
type IntoIter = MemoryIntoIterator<'a>;
fn into_iter(self) -> Self::IntoIter {
MemoryIntoIterator {
mem: self,
scan: 0,
free: 0,
... | (&mut self, obj: usize, next: usize) {
self.mem[obj + 1] = next;
}
fn mark_object(&mut self, obj: usize) {
self.mark_bits[obj / MARK_BITS_PER_SLOT] |= 1 << (obj % MARK_BITS_PER_SLOT);
}
fn unmark_object(&mut self, obj: usize) {
self.mark_bits[obj / MARK_BITS_PER_SLOT] &= !(1 << (obj % MARK_BITS_P... | set_fl_next | identifier_name |
mod.rs | #[cfg(not(feature="dynamic_mem"))]
const MAX_MEMORY_SLOTS: usize = 1024 * 128;
type Bits = u128;
const MARK_BITS_PER_SLOT: usize = mem::size_of::<Bits>();
const MARK_BITS: usize = MAX_MEMORY_SLOTS / MARK_BITS_PER_SLOT;
#[cfg(feature="dynamic_mem")]
type Mem = Vec<usize>;
#[cfg(not(feature="dynamic_mem"))]
type Mem =... |
#[cfg(feature="dynamic_mem")]
const MAX_MEMORY_SLOTS: usize = 1024 * 1024 * 2; | random_line_split | |
mod.rs | _free_list: bool,
}
impl<'a> IntoIterator for &'a Memory {
type Item = usize;
type IntoIter = MemoryIntoIterator<'a>;
fn into_iter(self) -> Self::IntoIter {
MemoryIntoIterator {
mem: self,
scan: 0,
free: 0,
}
}
}
pub struct MemoryIntoIterator<'a> {
mem: &'a Memory,
scan: usize,
... | {
return;
} | conditional_block | |
utils.py | ignore_columns)
columns = list(set(df.columns) - set(ignore_columns))
## define possible strategies
if how == "binarizer":
strategy = lambda x: pd.get_dummies(x)
elif how == "ordinal":
enc = OrdinalEncoder()
strategy = lambda x: pd.DataFrame(enc.fit_transform(x), columns = x.col... | '''
flattens a 3D array into 2D array
Parameters:
- X: a 3D array with shape samples x width x height [numpy.array]
Returns:
- flattened_X: 2D array with shape sample x width*height [numpy.array]
'''
flattened_X = X.reshape(X.shape[0], -1)
return flattened_X | identifier_body | |
utils.py | def check_nan(data:pd.Series) -> bool:
'''
checks whether given data contains NaN's
Parameters:
- data: data to check [pandas.Series], can also be pandas.DataFrame
Returns:
- nan's: True, if data contains NaN's, otherwise False [Boolean]
'''
## make sure not to overwrite given da... | plots a scatter showing the transformed dataset (if it is 2D) with different coloring for the different classes
Parameters:
- X: Array containing the original x values [numpy.array]
- y: Array containing the labels [numpy.array]
Returns: | random_line_split | |
utils.py | List of columns that shall be ignored [List, default = []]
- how: strategy to encode. The following are possible [String]
- Binarize: every unique value gets own column, filled with 0's and 1's, using pandas.get_dummies() --> 'binarizer' = Default
- OrdinalEncoder: unique values get rep... |
elif strategy == "mean":
value = df[columns].mean()
elif strategy == "median":
value = df[columns].median()
elif strategy == "min":
value = df[columns].min()
elif strategy == "max":
value = df[columns].max()
else:
print("strategy not implemented (yet). Fillin... | value = [0 for _ in range(columns.__len__())] | conditional_block |
utils.py | (data:pd.DataFrame, approach:str = "reuse") -> pd.DataFrame:
'''
function to balance the appearance of samples from different classes -> tackle distribution shift
Parameters:
- data: data with distribution shift [pandas.DataFrame]
- approach: strategy to tackle the distribution shift. Possib... | tackle_distribution_shift | identifier_name | |
models.go | exported.
ReleasePolicy *KeyReleasePolicy
// Application specific metadata in the form of key-value pairs.
Tags map[string]*string
}
// DeletedKey - A DeletedKey consisting of a WebKey plus its Attributes and deletion info
type DeletedKey struct {
// The key management attributes.
Attributes *KeyAttributes
//... | ExpiryTime *string
// READ-ONLY; The key rotation policy created time in UTC. | random_line_split | |
stateful.go | state will then be the set of rules used for matching
// until another Push or Pop is encountered.
func Push(state string) Action {
return ActionPush{state}
}
type include struct{ state string }
func (i include) applyAction(lexer *Lexer, groups []string) error { panic("should not be called") }
func (i include) app... | {
if candidate.RE != nil {
return candidate.RE, nil
}
// We don't have a compiled RE. This means there are back-references
// that need to be substituted first.
parent := l.stack[len(l.stack)-1]
key := candidate.Pattern + "\000" + strings.Join(parent.groups, "\000")
cached, ok := l.def.backrefCache.Load(key)
... | identifier_body | |
stateful.go | "
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
)
var (
backrefReplace = regexp.MustCompile(`(\\+)(\d)`)
)
// Option for modifying how the Lexer works.
type Option func(d *Definition)
// InitialState overrides the default initial state of "Root".
func InitialState(state string... |
func (p ActionPop) applyAction(lexer *Lexer, groups []string) error {
if groups[0] == "" {
return errors.New("did not consume any input")
}
lexer.stack = lexer.stack[:len(lexer.stack)-1]
return nil
}
// Pop to the previous state.
func Pop() Action {
return ActionPop{}
}
// ReturnRule signals the lexer to retu... | type ActionPop struct{} | random_line_split |
stateful.go | "
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
)
var (
backrefReplace = regexp.MustCompile(`(\\+)(\d)`)
)
// Option for modifying how the Lexer works.
type Option func(d *Definition)
// InitialState overrides the default initial state of "Root".
func InitialState(state string... | () map[string]rune { // nolint: golint
return d.symbols
}
type lexerState struct {
name string
groups []string
}
// Lexer implementation.
type Lexer struct {
stack []lexerState
def *Definition
data string
pos lexer.Position
}
func (l *Lexer) Next() (lexer.Token, error) { // nolint: golint
parent := l.... | Symbols | identifier_name |
stateful.go | "
"github.com/alecthomas/participle/v2"
"github.com/alecthomas/participle/v2/lexer"
)
var (
backrefReplace = regexp.MustCompile(`(\\+)(\d)`)
)
// Option for modifying how the Lexer works.
type Option func(d *Definition)
// InitialState overrides the default initial state of "Root".
func InitialState(state string... |
lexer.stack = append(lexer.stack, lexerState{name: p.State, groups: groups})
return nil
}
// Push to the given state.
//
// The target state will then be the set of rules used for matching
// until another Push or Pop is encountered.
func Push(state string) Action {
return ActionPush{state}
}
type include struct{... | {
return errors.New("did not consume any input")
} | conditional_block |
gaiatools.py | rometric_n_good_obs_al,astrometric_n_bad_obs_al,"+\
"astrometric_gof_al,astrometric_chi2_al,astrometric_excess_noise,astrometric_excess_noise_sig,"+\
"astrometric_params_solved,astrometric_primary_flag,astrometric_weight_al,"+\
"astrometric_pseudo_colour,astrometric... |
h,x = np.histogram(x, bins=bins)
xm = (x[1:]+x[:-1])/2.
ix = np.argmax(h)
return xm[ix]
def get_finite(x,y):
""" Get x and y that are both finite """
finite = np.logical_and(np.isfinite(x), np.isfinite(y))
xf = x[finite]; yf = y[finite]
return xf, yf
def fit_spline(x, y, **kwargs... | x = x[np.isfinite(x)] | conditional_block |
gaiatools.py | rometric_n_good_obs_al,astrometric_n_bad_obs_al,"+\
"astrometric_gof_al,astrometric_chi2_al,astrometric_excess_noise,astrometric_excess_noise_sig,"+\
"astrometric_params_solved,astrometric_primary_flag,astrometric_weight_al,"+\
"astrometric_pseudo_colour,astrometric... | (c):
cstr = "CONTAINS(POINT('ICRS',{0:}.ra,{0:}.dec),CIRCLE('ICRS',{1:},{2:},{3:}))=1".format(
source, c.ra.deg, c.dec.deg, radius.to("deg").value)
return cstr
cstrs = map(_make_contains_str, coords)
out += " or ".join(cstrs)
return out
def create_samples(Nsamp,mu,cov):
Nsta... | _make_contains_str | identifier_name |
gaiatools.py | rometric_n_good_obs_al,astrometric_n_bad_obs_al,"+\
"astrometric_gof_al,astrometric_chi2_al,astrometric_excess_noise,astrometric_excess_noise_sig,"+\
"astrometric_params_solved,astrometric_primary_flag,astrometric_weight_al,"+\
"astrometric_pseudo_colour,astrometric... | stdev = np.nanstd if ignore_nan else np.std
kws = {}
if axis is not None: kws['axis'] = axis
mu = mean(x,**kws)
sig = stdev(x,**kws)
return np.vstack([mu,sig]).T
def medscat(x,sigma=2,ignore_nan=False, axis=None, for_errorbar_plot=False):
percentile = np.nanpercentile if ignore_nan else... | def avgstd(x,ignore_nan=False, axis=None):
mean = np.nanmean if ignore_nan else np.mean | random_line_split |
gaiatools.py | ICRS',{1:},{2:},{3:}))=1".format(
source, c.ra.deg, c.dec.deg, radius.to("deg").value)
return cstr
cstrs = map(_make_contains_str, coords)
out += " or ".join(cstrs)
return out
def create_samples(Nsamp,mu,cov):
Nstars,Nparams = mu.shape
assert Nstars == len(cov)
assert Nparam... | """
Query gaia given source_ids
Return a table in the order of the source_ids
"""
from pyia import GaiaDataNew
unique_arr, indexes = np.unique(source_ids, return_inverse=True)
assert len(unique_arr) == len(source_ids), "Not all IDs are unique"
query = create_source_query_from_ids(source_ids,... | identifier_body | |
langviews.js | = $(this.config.platformSelector).val();
if (endDate.diff(startDate, 'days') === 0) {
startDate.subtract(3, 'days');
endDate.add(3, 'days');
}
return `/pageviews#start=${startDate.format('YYYY-MM-DD')}` +
`&end=${endDate.format('YYYY-MM-DD')}&project=${lang}.${project}.org&platform=${pl... | {
let startDate, endDate, params = this.parseQueryString('pages');
$(this.config.projectInput).val(params.project || this.config.defaults.project);
if (this.validateProject()) return;
// FIXME: only run this when they actually submit
this.patchUsage('lv');
/**
* Check if we're using a va... | identifier_body | |
langviews.js | `);
if (cassandraError) {
if (failureRetries[dbName]) {
failureRetries[dbName]++;
} else {
failureRetries[dbName] = 1;
}
/** maximum of 3 retries */
if (failureRetries[dbName] < 3) {
totalRequestCount++;
return t... | processArticle | identifier_name | |
langviews.js | -badge' src='${badgeImage}' alt='${badgeName}' title='${badgeName}' />`;
}
/**
* Render list of langviews into view
* @returns {null} nothing
*/
renderData() {
/** sort ascending by current sort setting */
const sortedLangViews = this.langData.sort((a, b) => {
const before = this.getSortPr... | totalRequestCount++;
return this.rateLimit(makeRequest, 100, this)(dbName);
}
/** retries exceeded */
failedPages.push(failedPageLink);
} else {
this.writeMessage(
`${failedPageLink}: ${$.i18n('api-error', 'Pageviews API')} - ${errorDa... | failureRetries[dbName] = 1;
}
/** maximum of 3 retries */
if (failureRetries[dbName] < 3) { | random_line_split |
langviews.js | of column sorting
* @param {object} item - langview entry within this.langData
* @param {String} type - type of property to get
* @return {String|Number} - value
*/
getSortProperty(item, type) {
switch (type) {
case 'lang':
return item.lang;
case 'title':
return item.pageName;
... | {
return url.match(/\/wiki\/(.*?)(?:\?|$)/)[1];
} | conditional_block | |
gaia_executor.rs | store_config
} else {
StoreConfig::init()
}
};
let (alive_id, partitions) = get_init_info(&store_config);
info!("alive_id: {:?}, partitions: {:?}", alive_id, partitions);
store_config.update_alive_id(alive_id);
info!("{:?}", store_config);
let worker_num ... | {
let rpc_port = self.rpc_runtime.block_on(async {
let query_vineyard = QueryVineyard::new(
self.graph.clone(),
self.partition_manager.clone(),
self.partition_worker_mapping.clone(),
self.worker_partition_list_mapping.clone(),
... | identifier_body | |
gaia_executor.rs | crate maxgraph_server;
extern crate maxgraph_store;
extern crate pegasus;
extern crate pegasus_server;
extern crate protobuf;
extern crate structopt;
use gaia_runtime::server::init_with_rpc_service;
use gaia_runtime::server::manager::GaiaServerManager;
use grpcio::ChannelBuilder;
use grpcio::EnvBuilder;
use gs_gremli... |
init_log4rs();
let mut store_config = {
let args: Vec<String> = std::env::args().collect();
if args.len() <= 6 && args[1] == "--config" {
let mut store_config = StoreConfig::init_from_file(&args[2], &args[4]);
if args.len() == 6 {
store_config.graph_name ... | {
util::get_build_info();
return;
} | conditional_block |
gaia_executor.rs | extern crate maxgraph_server;
extern crate maxgraph_store;
extern crate pegasus;
extern crate pegasus_server;
extern crate protobuf;
extern crate structopt;
use gaia_runtime::server::init_with_rpc_service;
use gaia_runtime::server::manager::GaiaServerManager;
use grpcio::ChannelBuilder;
use grpcio::EnvBuilder;
use gs_... | server_manager,
store_config.clone(),
Box::new(recover_prepare),
)
.unwrap();
let gaia_service = GaiaService::new(
store_config.clone(),
graph.clone(),
partition_manager.clone(),
partition_worker_mapping,
worker_partition_list_mapping,
);
... | random_line_split | |
gaia_executor.rs | crate maxgraph_server;
extern crate maxgraph_store;
extern crate pegasus;
extern crate pegasus_server;
extern crate protobuf;
extern crate structopt;
use gaia_runtime::server::init_with_rpc_service;
use gaia_runtime::server::manager::GaiaServerManager;
use grpcio::ChannelBuilder;
use grpcio::EnvBuilder;
use gs_gremli... | <V, VI, E, EI>(
store_config: Arc<StoreConfig>,
graph: Arc<GlobalGraphQuery<V = V, E = E, VI = VI, EI = EI>>,
partition_manager: Arc<GraphPartitionManager>,
) where
V: Vertex + 'static,
VI: Iterator<Item = V> + Send + 'static,
E: Edge + 'static,
EI: Iterator<Item = E> + Send + 'static,
{
... | run_main | identifier_name |
conn.go | out.
func (c *Conn) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
// SetWriteDeadline sets the write deadline on the underlying connection.
// A zero value for t means Write will not time out.
// After a Write has timed out, the Noise state is corrupt and all future writes will return the s... | // the first Read or Write will call it automatically.
func (c *Conn) Handshake() (err error) {
c.handshakeMutex.Lock()
defer c.handshakeMutex.Unlock()
if c.handshakeComplete {
return nil
}
var remoteKeyPair *DHKey
if c.config.PeerStatic != nil {
if len(c.config.PeerStatic) != 32 {
return errors.New("noi... | random_line_split | |
conn.go | .
func (c *Conn) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
// SetWriteDeadline sets the write deadline on the underlying connection.
// A zero value for t means Write will not time out.
// After a Write has timed out, the Noise state is corrupt and all future writes will return the same ... | () bool {
return c.isRemoteAuthenticated
}
// RemoteKey returns the static key of the remote peer.
// It is useful in case the static key is only transmitted during the handshake.
func (c *Conn) RemoteKey() ([]byte, error) {
if !c.handshakeComplete {
return nil, errors.New("handshake not completed")
}
return c.h... | IsRemoteAuthenticated | identifier_name |
conn.go | .
func (c *Conn) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
// SetWriteDeadline sets the write deadline on the underlying connection.
// A zero value for t means Write will not time out.
// After a Write has timed out, the Noise state is corrupt and all future writes will return the same ... |
// Noise-related functions
// Handshake runs the client or server handshake protocol if
// it has not yet been run.
// Most uses of this package need not call Handshake explicitly:
// the first Read or Write will call it automatically.
func (c *Conn) Handshake() (err error) {
c.handshakeMutex.Lock()
defer c.handsh... | {
return c.conn.Close()
} | identifier_body |
conn.go | .
func (c *Conn) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
// SetWriteDeadline sets the write deadline on the underlying connection.
// A zero value for t means Write will not time out.
// After a Write has timed out, the Noise state is corrupt and all future writes will return the same ... |
_, c1, c2, err = c.hs.ReadMessage(nil, msg)
if err != nil {
return err
}
}
state = !state
}
if c.isClient {
c.out, c.in = c1, c2
} else {
c.out, c.in = c2, c1
}
c.handshakeComplete = true
return nil
}
// IsRemoteAuthenticated can be used to check if the remote peer has been
// properly aut... | {
return err
} | conditional_block |
barnacle_vcf.py | +base2
return alt1, alt2
elif breakpoint1.endswith('(down)') and breakpoint2.endswith('(down)'):
alt1 = base1+']'+chrom2+':'+str(pos2)+']'
alt2 = base2+']'+chrom1+':'+str(pos1)+']'
return alt1, alt2
#one breakpoint is at the start of the contig region and other breakpoint ... | (member, refseq):
pos = dup_POS(member)
chrom = dup_CHROM(member)
seq = refseq.GetSequence(chrom, int(pos), int(pos))
return seq
def dup_ALT():
alt = '<DUP:TANDEM>'
return alt
def dup_INFO(member):
pos = int(dup_POS(member))
svtype = 'FND'
length | dup_REF | identifier_name |
barnacle_vcf.py | str(dp)+';CTG='
#header output method
def write_header(GIN_user, GIN_pass, LIMS_user, LIMS_pass, refseq_flag, library, filetype_flag, out_file, contig=None):
#file format
out_file.write('##fileformat=VCFv4.1\n')
#file date
out_file.write('##filedate='+time.strftime("%Y%m%d")+'\n')
#tcga version
out_... | info = ptd_INFO(member) | conditional_block | |
barnacle_vcf.py | ['+base2
return alt1, alt2
elif breakpoint1.endswith('(down)') and breakpoint2.endswith('(down)'):
alt1 = base1+']'+chrom2+':'+str(pos2)+']'
alt2 = base2+']'+chrom1+':'+str(pos1)+']'
return alt1, alt2
#one breakpoint is at the start of the contig region and other breakpoin... | seq = refseq.GetSequence(chrom, int(pos), int(pos))
return seq
def dup_ALT():
alt = '<DUP:TANDEM>'
return alt
def dup_INFO(member):
pos = int(dup_POS(member))
svtype = 'FND'
length |
def dup_REF(member, refseq):
pos = dup_POS(member)
chrom = dup_CHROM(member) | random_line_split |
barnacle_vcf.py | ['+base2
return alt1, alt2
elif breakpoint1.endswith('(down)') and breakpoint2.endswith('(down)'):
alt1 = base1+']'+chrom2+':'+str(pos2)+']'
alt2 = base2+']'+chrom1+':'+str(pos1)+']'
return alt1, alt2
#one breakpoint is at the start of the contig region and other breakpoin... |
#header output method
def write_header(GIN_user, GIN_pass, LIMS_user, LIMS_pass, refseq_flag, library, filetype_flag, out_file, contig=None):
#file format
out_file.write('##fileformat=VCFv4.1\n')
#file date
out_file.write('##filedate='+time.strftime("%Y%m%d")+'\n')
#tcga version
out_file.write('##t... | overlap = str(member.meta_fields['ctg_overlap'])
svtype = 'FND'
dp = int(member.avg_read_to_ctg_unique)
if int(overlap) > 0:
return 'SVTYPE='+svtype+';MATEID='+str(id2)+'b;CIPOS=0,'+overlap+';SR='+str(dp)+';CTG=', svtype+';MATEID='+str(id1)+'a;CIPOS=0,'+overlap+';SR='+str(dp)+';CTG='
else:
return 'S... | identifier_body |
MakeGoodGamesBot.py | tit_for_tat(),
# 2) RT followers,
# 3) RT highest ratio of number_of_RT/number_of_followers of previous day Statuses.
def run_schedule(dt=get_date(),ky='#indiedev',mx=150,clean=False,folow=False):
if clean: tit_for_tat()
if folow: RT_followers(key_=ky,max_=mx)
RT_last_day(dt,key_=ky)
def... | ():
print 'Tit for Tat!'
follow_me = twitter_client.followers_ids() #who follows me
follow_you = twitter_client.friends_ids() #who do I follow
erros_ids = []
fol_len = len([1 for id_ in follow_me if id_ not in follow_you])
print 'Following '+str(fol_len)+' new users.'
for id_ in follow_me:
... | tit_for_tat | identifier_name |
MakeGoodGamesBot.py | tit_for_tat(),
# 2) RT followers,
# 3) RT highest ratio of number_of_RT/number_of_followers of previous day Statuses.
def run_schedule(dt=get_date(),ky='#indiedev',mx=150,clean=False,folow=False):
if clean: tit_for_tat()
if folow: RT_followers(key_=ky,max_=mx)
RT_last_day(dt,key_=ky)
def... |
def loop_schedule(date):
while True:
for ky in ['#indiedev','#indiegame']:
print 'Day '+str(date)+' and keyword '+str(ky)
run_schedule(dt=date,ky=ky)
d = get_date()
if date != d:
date = d
break
#Main Functions for... | run_schedule(folow=True)
run_schedule(ky='#indiegame',clean=True,folow=True) | identifier_body |
MakeGoodGamesBot.py | tit_for_tat(),
# 2) RT followers,
# 3) RT highest ratio of number_of_RT/number_of_followers of previous day Statuses.
def run_schedule(dt=get_date(),ky='#indiedev',mx=150,clean=False,folow=False):
if clean: |
if folow: RT_followers(key_=ky,max_=mx)
RT_last_day(dt,key_=ky)
def twice():
run_schedule(folow=True)
run_schedule(ky='#indiegame',clean=True,folow=True)
def loop_schedule(date):
while True:
for ky in ['#indiedev','#indiegame']:
print 'Day '+str(date)+' and keyword '+str(k... | tit_for_tat() | conditional_block |
MakeGoodGamesBot.py | tit_for_tat(),
# 2) RT followers,
# 3) RT highest ratio of number_of_RT/number_of_followers of previous day Statuses.
def run_schedule(dt=get_date(),ky='#indiedev',mx=150,clean=False,folow=False):
if clean: tit_for_tat()
if folow: RT_followers(key_=ky,max_=mx)
RT_last_day(dt,key_=ky)
def... | i,twts=4,twts+1
print 'RTed : '+str(twts)+' at '+str(time.ctime())
time.sleep(sleep_t)
i=5
if type(tweet[11]) != None:
banRT.append(tweet[11])
if len(tweet[27]) > 14:
... | if publish:
try:
twitter_client.retweet(tweet[8]) | random_line_split |
calibrate_gripper_g1r1.py | amp_temp':{
'type': 'adc_linear_3V3', #3V3 supply, no divider
'name': 'Microchip TC1047',
'cb_mV_at_25C': 750.0,
'cb_mV_per_C': 10.0,
'cb_scale': 1.0,
'cb_bias': 0.0,
},
'motor_temp':{
'type': 'adc_linear_3V3', #5V supply, no divider
'name':... | print 'Pos: (mm) : '+'%3.3f'%pos+' Qei On '+'%d'%q_on+' Qei Period '+'%d'%q_p+' Qei Rollover '+'%d'%q_r
raw=self.comp_ec.status.adc_torque
c=self.torque.raw_2_mNm(self.comp_rt.config['calib']['torque'],raw)
mN=c/self.comp_j.config['calib']['cb_drive_radius_m']
print 'Force: (g) : '+'%3.2f'%m3u.mN2g(mN)+'... | q_on=self.comp_ec.status.qei_on
q_p=self.comp_ec.status.qei_period
q_r=self.comp_ec.status.qei_rollover
c=self.theta.raw_2_deg(self.comp_rt.config['calib']['theta'],q_on,q_p,q_r)
pos=1000.0*math.pi*2*self.comp_j.config['calib']['cb_drive_radius_m']*c/360.0 | random_line_split |
calibrate_gripper_g1r1.py | _temp':{
'type': 'adc_linear_3V3', #3V3 supply, no divider
'name': 'Microchip TC1047',
'cb_mV_at_25C': 750.0,
'cb_mV_per_C': 10.0,
'cb_scale': 1.0,
'cb_bias': 0.0,
},
'motor_temp':{
'type': 'adc_linear_3V3', #5V supply, no divider
'name': 'A... |
if ct=='tt':
self.reset_sensor('theta')
self.calibrate_theta()
self.write_config()
return True
if M3CalibrateActuatorEc.do_task(self,ct):
return True
return False
def print_tasks(self):
M3CalibrateActuatorEcR1.print_tasks(self)
print 'ch: calibrate torque'
print 'tt: calibrate theta'
... | self.reset_sensor('torque')
self.calibrate_torque()
self.write_config()
return True | conditional_block |
calibrate_gripper_g1r1.py | _temp':{
'type': 'adc_linear_3V3', #3V3 supply, no divider
'name': 'Microchip TC1047',
'cb_mV_at_25C': 750.0,
'cb_mV_per_C': 10.0,
'cb_scale': 1.0,
'cb_bias': 0.0,
},
'motor_temp':{
'type': 'adc_linear_3V3', #5V supply, no divider
'name': 'A... |
def print_tasks(self):
M3CalibrateActuatorEcR1.print_tasks(self)
print 'ch: calibrate torque'
print 'tt: calibrate theta'
def display_sensors(self):
M3CalibrateActuatorEcR1.display_sensors(self)
q_on=self.comp_ec.status.qei_on
q_p=self.comp_ec.status.qei_period
q_r=self.comp_ec.status.qei_rollov... | if ct=='ch':
self.reset_sensor('torque')
self.calibrate_torque()
self.write_config()
return True
if ct=='tt':
self.reset_sensor('theta')
self.calibrate_theta()
self.write_config()
return True
if M3CalibrateActuatorEc.do_task(self,ct):
return True
return False | identifier_body |
calibrate_gripper_g1r1.py | _temp':{
'type': 'adc_linear_3V3', #3V3 supply, no divider
'name': 'Microchip TC1047',
'cb_mV_at_25C': 750.0,
'cb_mV_per_C': 10.0,
'cb_scale': 1.0,
'cb_bias': 0.0,
},
'motor_temp':{
'type': 'adc_linear_3V3', #5V supply, no divider
'name': 'A... | (self,ct):
if ct=='ch':
self.reset_sensor('torque')
self.calibrate_torque()
self.write_config()
return True
if ct=='tt':
self.reset_sensor('theta')
self.calibrate_theta()
self.write_config()
return True
if M3CalibrateActuatorEc.do_task(self,ct):
return True
return False
def print_t... | do_task | identifier_name |
getfood_base.py | mine = 4
def __init__(self,
agent_start_pos=(1, 1),
health_cap=50,
food_rate=4,
grid_size=8,
obs_vision=False,
reward_type='delta',
fully_observed=False,
only_partial_obs=... |
else:
obs = img.flatten()
else:
if incl_health:
obs = np.concatenate((img.flatten(), full_img.flatten(), np.array([self.health])))
else:
obs = np.concatenate((img.flatten(), full_img.flatten()))
obs_string = obs.tostrin... | obs = np.concatenate((img.flatten(), np.array([self.health]))) | conditional_block |
getfood_base.py | for conditional entropy of s' | s
self.transition_count = {}
self.prev_obs_string = ''
# for mixing time
self.mixing_time_periods = mixing_time_periods
self.max_mixing_time_period = max(mixing_time_periods) if mixing_time_periods else 0
self.mixing_time_period_length = m... | FoodEnvEmptyFullObs | identifier_name | |
getfood_base.py | mine = 4
def __init__(self,
agent_start_pos=(1, 1),
health_cap=50,
food_rate=4,
grid_size=8,
obs_vision=False,
reward_type='delta',
fully_observed=False,
only_partial_obs=... | if self.fully_observed:
if incl_health:
obs = np.concatenate((full_img.flatten(), np.array([self.health]), np.array(self.agent_pos)))
else:
obs = np.concatenate((full_img.flatten(), np.array(self.agent_pos)))
elif self.only_partial_obs:
... | # # ignore second channel since redundant (due to one-to-one mapping btwn color and obj type for now)
# img = np.concatenate([np.eye(len(self.object_to_idx))[ch].transpose(2, 0, 1) for ch in img[:1]])
# full_img = np.concatenate([np.eye(len(self.object_to_idx))[ch].transpose(2, 0, 1) for ch i... | random_line_split |
getfood_base.py | mine = 4
def __init__(self,
agent_start_pos=(1, 1),
health_cap=50,
food_rate=4,
grid_size=8,
obs_vision=False,
reward_type='delta',
fully_observed=False,
only_partial_obs=... |
def place_items(self):
pass
def extra_gen_grid(self):
pass
def place_prob(self, obj, prob, top=None, size=None):
if np.random.binomial(1, prob):
pos = self.place_obj(obj, top, size)
obj.cur_pos = pos
return True
return False
def de... | pass | identifier_body |
codeHost.ts | without bleeding CSS to other code hosts (GitLab also uses .file-actions elements).
fileActions.classList.add('sg-github-file-actions')
// Old GitHub Enterprise PR views have a "☑ show comments" text that we want to insert *after*
const showCommentsElement = codeView.querySelector('.show-file-notes')
... | const actualLine = lines[position.line - 1]
const documentLine = codeElement.textContent || ''
const actualLeadingWhiteSpace = actualLine.length - trimStart(actualLine).length
const documentLeadingWhiteSpace = documentLine.length - trimStart(documentLine).length
... | throw new Error('(adjustPosition) could not find code element for line provided')
}
| conditional_block |
codeHost.ts | without bleeding CSS to other code hosts (GitLab also uses .file-actions elements).
fileActions.classList.add('sg-github-file-actions')
// Old GitHub Enterprise PR views have a "☑ show comments" text that we want to insert *after*
const showCommentsElement = codeView.querySelector('.show-file-notes')
... | /**
* Returns true if the current page is github.com.
*/
export const checkIsGitHubDotCom = (url = window.location.href): boolean => /^https?:\/\/(www\.)?github\.com/.test(url)
/**
* Returns true if the current page is either github.com or GitHub Enterprise.
*/
export const checkIsGitHub = (): boolean => checkIsGi... | const ogSiteName = document.head.querySelector<HTMLMetaElement>('meta[property="og:site_name"]')
return (
!!ogSiteName &&
// GitHub Enterprise v2.14.11 has "GitHub" as og:site_name
(ogSiteName.content === 'GitHub Enterprise' || ogSiteName.content === 'GitHub') &&
document.body.cl... | identifier_body |
codeHost.ts | (codeView: HTMLElement): HTMLElement {
const className = 'github-file-actions-toolbar-mount'
const existingMount = codeView.querySelector('.' + className) as HTMLElement
if (existingMount) {
return existingMount
}
const mountElement = document.createElement('div')
mountElement.className... | createFileActionsToolbarMount | identifier_name | |
codeHost.ts | ',
resolveView: (fileLineContainer: HTMLElement): CodeView | null => {
const embeddedBlobWrapper = fileLineContainer.closest('.blob-wrapper-embedded')
if (embeddedBlobWrapper) {
// This is a snippet embedded in a comment.
// Resolve to `.blob-wrapper-embedded`'s parent elemen... | random_line_split | ||
edgehub.rs | , BrokerBuilder, BrokerHandle, BrokerReady, BrokerSnapshot, FilePersistor,
MakeMqttPacketProcessor, Message, Persist, Server, ServerCertificate, SystemEvent,
VersionedFileFormat,
};
use mqtt_edgehub::{
auth::{
EdgeHubAuthenticator, EdgeHubAuthorizer, LocalAuthenticator, LocalAuthorizer,
Poli... |
snapshot??
}
// one of sidecars exited first
Either::Right(((res, stopped, sidecars), server)) => {
debug!("a sidecar has stopped. shutting down all sidecars...");
if let Err(e) = res {
error!(message = "failed wait... | // wait for the rest to exit
future::join_all(sidecars).await; | random_line_split |
edgehub.rs | , BrokerBuilder, BrokerHandle, BrokerReady, BrokerSnapshot, FilePersistor,
MakeMqttPacketProcessor, Message, Persist, Server, ServerCertificate, SystemEvent,
VersionedFileFormat,
};
use mqtt_edgehub::{
auth::{
EdgeHubAuthenticator, EdgeHubAuthorizer, LocalAuthenticator, LocalAuthorizer,
Poli... |
fn session_expiration(&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().expiration()
}
fn session_cleanup_interval(&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().cleanup_interval()
}
async fn run(
self,
... | {
settings.broker().persistence().time_interval()
} | identifier_body |
edgehub.rs | , BrokerBuilder, BrokerHandle, BrokerReady, BrokerSnapshot, FilePersistor,
MakeMqttPacketProcessor, Message, Persist, Server, ServerCertificate, SystemEvent,
VersionedFileFormat,
};
use mqtt_edgehub::{
auth::{
EdgeHubAuthenticator, EdgeHubAuthorizer, LocalAuthenticator, LocalAuthorizer,
Poli... | (&self, settings: &Self::Settings) -> StdDuration {
settings.broker().session().cleanup_interval()
}
async fn run(
self,
config: Self::Settings,
broker: Broker<Self::Authorizer>,
) -> Result<BrokerSnapshot> {
let broker_handle = broker.handle();
let sidecars ... | session_cleanup_interval | identifier_name |
edgehub.rs | , BrokerBuilder, BrokerHandle, BrokerReady, BrokerSnapshot, FilePersistor,
MakeMqttPacketProcessor, Message, Persist, Server, ServerCertificate, SystemEvent,
VersionedFileFormat,
};
use mqtt_edgehub::{
auth::{
EdgeHubAuthenticator, EdgeHubAuthorizer, LocalAuthenticator, LocalAuthorizer,
Poli... |
};
Ok(state)
}
}
async fn make_server<Z>(
config: Settings,
broker: Broker<Z>,
broker_ready: BrokerReady,
) -> Result<Server<Z, MakeEdgeHubPacketProcessor<MakeMqttPacketProcessor>>>
where
Z: Authorizer + Send + 'static,
{
let broker_handle = broker.handle();
let make_proc... | {
debug!("a sidecar has stopped. shutting down all sidecars...");
if let Err(e) = res {
error!(message = "failed waiting for sidecar shutdown", error = %e);
}
// send shutdown event to each of the rest sidecars
shutdown... | conditional_block |
utils.ts | city) {
const hex = hexColor.replace('#', '');
const r = parseInt(hex.substring(0, 2), 16);
const g = parseInt(hex.substring(2, 4), 16);
const b = parseInt(hex.substring(4, 6), 16);
const result = `rgba(${r}, ${g}, ${b}, ${opacity})`;
return result;
}
/**
*
* @param target {object}
*/
export function is... | lor, opa | identifier_name | |
utils.ts | .dashedConfig && options.dashedConfig.length
? options.dashedConfig
: [5, 5, 5];
ctx.setLineDash(_dashedConfig);
}
const { lineColor, weight, opacity, fillColor } = options;
ctx.beginPath();
ctx.arc(vertex.x, vertex.y, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = hex2rgba(fillColor, opa... | export function getDirection(start: IVertex, end: IVertex) {
let left: boolean = false;
let top: boolean = false;
let right: boolean = false;
let bottom: boolean = false;
if (start.x <= end.x) {
right = true;
} else {
left = true;
}
if (start.y <= end.y) {
bottom = true;
} else {
top... | */ | random_line_split |
utils.ts |
/**
*
* @param ctx
* @param vertex
* @param radius
* @param options
*/
export const drawCircle = (
ctx: any,
vertex: IVertex,
radius,
options: DrawCircleOption
) => {
if (!options.hasOwnProperty('dashed') || options.dashed === false) {
ctx.setLineDash([]);
} else {
const _dashedConfig =
... | et[key] = options[key];
}
}
});
} | conditional_block | |
utils.ts | ashedConfig && options.dashedConfig.length
? options.dashedConfig
: [5, 5, 5];
ctx.setLineDash(_dashedConfig);
}
const { lineColor, weight, opacity, fillColor } = options;
ctx.beginPath();
ctx.arc(vertex.x, vertex.y, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = hex2rgba(fillColor, opaci... | Rect(vertex: IVertex, rect: [IVertex, IVertex]): boolean {
if (
vertex.x > rect[0].x &&
vertex.x < rect[1].x &&
vertex.y > rect[0].y &&
vertex.y < rect[1].y
) {
return true;
}
return false;
}
/**
* 在 canvas 上下文新建一个渐变区域
* @param ctx
* @param option
*/
export const createLinearGradient =... | , offsetY: y } = event;
return { x: x / zoom, y: y / zoom };
}
export function isIn | identifier_body |
v4-signature.go |
// Sign - local variables
type Sign struct {
accessKeyID string
secretAccessKey string
region string
httpRequest *http.Request
extractedSignedHeaders http.Header
}
// AWS Signature Version '4' constants.
const (
signV4Algorithm = "AWS4-HMAC-SHA256"
iso8601Format =... | "github.com/minio/minio/pkg/probe"
) | random_line_split | |
v4-signature.go | es.
func New(accessKeyID, secretAccessKey, region string) (*Sign, *probe.Error) {
if !isValidAccessKey.MatchString(accessKeyID) {
return nil, ErrInvalidAccessKeyID("Invalid access key id.", accessKeyID).Trace(accessKeyID)
}
if !isValidSecretKey.MatchString(secretAccessKey) {
return nil, ErrInvalidAccessKeyID("In... | (presignedQuery string) string {
rawQuery := strings.Replace(presignedQuery, "+", "%20", -1)
encodedPath := getURLEncodedName(s.httpRequest.URL.Path)
// Convert any space strings back to "+".
encodedPath = strings.Replace(encodedPath, "+", "%20", -1)
canonicalRequest := strings.Join([]string{
s.httpRequest.Metho... | getPresignedCanonicalRequest | identifier_name |
v4-signature.go | secretAccessKey).Trace(secretAccessKey)
}
if region == "" {
return nil, ErrRegionISEmpty("Region is empty.").Trace()
}
signature := &Sign{
accessKeyID: accessKeyID,
secretAccessKey: secretAccessKey,
region: region,
}
return signature, nil
}
// SetHTTPRequestToVerify - sets the http request ... | {
continue
} | conditional_block | |
v4-signature.go | .
func New(accessKeyID, secretAccessKey, region string) (*Sign, *probe.Error) |
// SetHTTPRequestToVerify - sets the http request which needs to be verified.
func (s *Sign) SetHTTPRequestToVerify(r *http.Request) *Sign {
// Do not set http request if its 'nil'.
if r == nil {
return s
}
s.httpRequest = r
return s
}
// getCanonicalHeaders generate a list of request headers with their value... | {
if !isValidAccessKey.MatchString(accessKeyID) {
return nil, ErrInvalidAccessKeyID("Invalid access key id.", accessKeyID).Trace(accessKeyID)
}
if !isValidSecretKey.MatchString(secretAccessKey) {
return nil, ErrInvalidAccessKeyID("Invalid secret key.", secretAccessKey).Trace(secretAccessKey)
}
if region == "" ... | identifier_body |
policy_row.ts | _element.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {Conflict, PolicyConflictElement} from './policy_conflict.js';
import {getTemplate} from './policy_row.html.js';
export interface Policy {
ignored?: boolean;
name: string;
level: string;
link?: string;
scope: string;
... | extends CustomElement {
static override get template() {
return getTemplate();
}
policy: Policy;
private unset_: boolean;
private hasErrors_: boolean;
private hasWarnings_: boolean;
private hasInfos_: boolean;
private hasConflicts_: boolean;
private hasSuperseded_: boolean;
private isMergedVal... | PolicyRowElement | identifier_name |
policy_row.ts | _element.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {Conflict, PolicyConflictElement} from './policy_conflict.js';
import {getTemplate} from './policy_row.html.js';
export interface Policy {
ignored?: boolean;
name: string;
level: string;
link?: string;
scope: string;
... |
if (format) {
return JSON.stringify(value, null, 2);
} else {
return JSON.stringify(value, null);
}
};
// If value is longer than 256 characters, truncate and add ellipsis.
const policyValueStr = convertValue(policy.value);
const truncatedValue = pol... | {
return value;
} | conditional_block |
policy_row.ts | _element.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {Conflict, PolicyConflictElement} from './policy_conflict.js';
import {getTemplate} from './policy_row.html.js';
export interface Policy {
ignored?: boolean;
name: string;
level: string;
link?: string;
scope: string;
... |
policy: Policy;
private unset_: boolean;
private hasErrors_: boolean;
private hasWarnings_: boolean;
private hasInfos_: boolean;
private hasConflicts_: boolean;
private hasSuperseded_: boolean;
private isMergedValue_: boolean;
private deprecated_: boolean;
private future_: boolean;
connectedCal... | {
return getTemplate();
} | identifier_body |
policy_row.ts | /custom_element.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.js';
import {Conflict, PolicyConflictElement} from './policy_conflict.js';
import {getTemplate} from './policy_row.html.js';
export interface Policy {
ignored?: boolean;
name: string;
level: string;
link?: string;
scope: s... | }
if (format) {
return JSON.stringify(value, null, 2);
} else {
return JSON.stringify(value, null);
}
};
// If value is longer than 256 characters, truncate and add ellipsis.
const policyValueStr = convertValue(policy.value);
const truncatedVa... | // Skip 'string' policy to avoid unnecessary conversions.
if (typeof value == 'string') {
return value; | random_line_split |
server.go | ok := privateKey.(*ecdsa.PrivateKey); ok {
keyType = cert.ECPrivateKeyBlockType
bytes, err = x509.MarshalECPrivateKey(key)
} else if key, ok := privateKey.(*rsa.PrivateKey); ok {
keyType = cert.RSAPrivateKeyBlockType
bytes = x509.MarshalPKCS1PrivateKey(key)
} else {
keyType = cert.PrivateKeyBlockType
byt... |
if err := s.serveHTTPS(); err != nil {
return err
}
return nil
}
func (s *server) getCertificate(hello *tls.ClientHelloInfo) (_servingCert *tls.Certificate, _err error) {
s.Lock()
changed := false
defer func() {
defer s.Unlock()
if _err != nil {
logrus.Errorf("Get certificate error: %s", _err)
r... | {
return err
} | conditional_block |
server.go | if err := s.userConfigure(); err != nil {
return nil, err
}
lc, err := listenConfigStorage.Get()
if err != nil {
return nil, err
}
return s, s.Update(lc)
}
func (s *server) CACert() (string, error) {
if s.userConfig.NoCACerts {
return "", nil
}
if s.userConfig.CACerts != "" {
return s.userConfig.CAC... | s.ips = map[string]bool{}
s.domains = map[string]bool{}
| random_line_split | |
server.go | , ok := privateKey.(*ecdsa.PrivateKey); ok {
keyType = cert.ECPrivateKeyBlockType
bytes, err = x509.MarshalECPrivateKey(key)
} else if key, ok := privateKey.(*rsa.PrivateKey); ok {
keyType = cert.RSAPrivateKeyBlockType
bytes = x509.MarshalPKCS1PrivateKey(key)
} else {
keyType = cert.PrivateKeyBlockType
by... | () error {
if s.userConfig.HTTPSPort == 0 {
s.userConfig.HTTPSPort = 8443
}
for _, d := range s.userConfig.Domains {
s.domains[d] = true
}
for _, ip := range s.userConfig.KnownIPs {
if netIP := net.ParseIP(ip); netIP != nil {
s.ips[ip] = true
}
}
if bindAddress := net.ParseIP(s.userConfig.BindAddre... | userConfigure | identifier_name |
server.go | ok := privateKey.(*ecdsa.PrivateKey); ok {
keyType = cert.ECPrivateKeyBlockType
bytes, err = x509.MarshalECPrivateKey(key)
} else if key, ok := privateKey.(*rsa.PrivateKey); ok {
keyType = cert.RSAPrivateKeyBlockType
bytes = x509.MarshalPKCS1PrivateKey(key)
} else {
keyType = cert.PrivateKeyBlockType
byt... |
func (s *server) getCertificate(hello *tls.ClientHelloInfo) (_servingCert *tls.Certificate, _err error) {
s.Lock()
changed := false
defer func() {
defer s.Unlock()
if _err != nil {
logrus.Errorf("Get certificate error: %s", _err)
return
}
if changed {
s.save()
}
}()
if hello.ServerName != ... | {
if len(s.listeners) > 0 {
return nil
}
if err := s.shutdown(); err != nil {
return err
}
if err := s.serveHTTPS(); err != nil {
return err
}
return nil
} | identifier_body |
cli.rs | mut remaining_v: libc::tcflag_t = v;
let mut s = String::new();
for &(fname, fvalue) in fs {
if (v & fvalue) != 0 {
let was_empty = s.is_empty();
write!(
&mut s,
"{}{}",
match was_empty {
true => "",
... |
}
impl AbstractStream for Stream {
type Attributes = TerminalAttributes;
fn isatty(&self) -> bool {
let ret = unsafe { libc::isatty(self.to_fd()) };
let error: i32 = errno::errno().into();
match ret {
1 => true,
0 => match error {
libc::EBADF =>... | {
match *self {
Stream::Stdout => libc::STDOUT_FILENO,
Stream::Stderr => libc::STDERR_FILENO,
Stream::Stdin => libc::STDIN_FILENO,
}
} | identifier_body |
cli.rs | SPAR", libc::CMSPAR),
("CRTSCTS", libc::CRTSCTS),
],
)?,
)
.field(
"c_lflag",
&debug_format_flag_field(
self.inner.c_lflag,
&[
("ISIG", libc... | prompt_for_string | identifier_name | |
cli.rs | && self.inner.c_oflag == other.inner.c_oflag
&& self.inner.c_cflag == other.inner.c_cflag
&& self.inner.c_lflag == other.inner.c_lflag
&& self.inner.c_line == other.inner.c_line
&& self.inner.c_cc == other.inner.c_cc
&& self.inner.c_ispeed == other... | random_line_split | ||
helmrepoutils.go | ("package", "utils", "method", "GetHelmRepoClient")
httpClient := http.DefaultClient
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
Idl... | (client client.Client, parentNamespace string, secretRef *corev1.ObjectReference) (secret *corev1.Secret, err error) {
srLogger := log.WithValues("package", "utils", "method", "getSecret")
if secretRef != nil {
srLogger.Info("Retreive secret", "parentNamespace", parentNamespace, "secretRef", secretRef)
ns := secr... | GetSecret | identifier_name |
helmrepoutils.go | Values("package", "utils", "method", "GetHelmRepoClient")
httpClient := http.DefaultClient
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,... | srLogger := log.WithValues("HelmRelease.Namespace", s.Namespace, "SubscrptionRelease.Name", s.Name)
if s.Spec.Source.HelmRepo == nil {
err := fmt.Errorf("HelmRepo type but Spec.HelmRepo is not defined")
return "", err
}
if _, err := os.Stat(chartsDir); os.IsNotExist(err) {
err := os.MkdirAll(chartsDir, 0755)
... | func DownloadChartFromHelmRepo(configMap *corev1.ConfigMap, secret *corev1.Secret, chartsDir string, s *appv1alpha1.HelmRelease) (chartDir string, err error) { | random_line_split |
helmrepoutils.go | namespace: ", ns)
} else {
srLogger.Info("no configMapRef defined ", "parentNamespace", parentNamespace)
}
return configMap, err
}
//GetSecret returns the secret to access the helm-repo
func GetSecret(client client.Client, parentNamespace string, secretRef *corev1.ObjectReference) (secret *corev1.Secret, err err... | {
srLogger.Error(err, "")
return err
} | conditional_block | |
helmrepoutils.go | ("package", "utils", "method", "GetHelmRepoClient")
httpClient := http.DefaultClient
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
Idl... | }
if secret != nil && secret.Data != nil {
srLogger.Info("Add credentials")
options.Auth = &githttp.BasicAuth{
Username: string(secret.Data["user"]),
Password: string(secret.Data["password"]),
}
}
if s.Spec.Source.GitHub.Branch == "" {
options.ReferenceName = plumbing.Master
} else {
op... | {
srLogger := log.WithValues("HelmRelease.Namespace", s.Namespace, "SubscrptionRelease.Name", s.Name)
if s.Spec.Source.GitHub == nil {
err := fmt.Errorf("GitHub type but Spec.GitHub is not defined")
return "", err
}
if _, err := os.Stat(chartsDir); os.IsNotExist(err) {
err := os.MkdirAll(chartsDir, 0755)
if... | identifier_body |
ResNet50_augmentation.py |
def get_dataset(ds_path):
ds_path = pathlib.Path(ds_path)
images = list(ds_path.glob('*/*.jpg'))
images = [str(path) for path in images]
total_images = len(images)
labels = sorted(item.name for item in ds_path.glob('*/') if item.is_dir())
classes = labels
labels = dict((name, index) for... |
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(AUTOTUNE)
return dataset
def residual_block(x, filters, kernel_size=3, stride=1, conv_shortcut=True, name=None):
if conv_shortcut:
shortcut = tf.keras.layers.Conv2D(4 * filters, 1, strides=stride, name=name+'_0_conv', kernel_init... | dataset = dataset.map(partial(process_data), num_parallel_calls=AUTOTUNE) | random_line_split |
ResNet50_augmentation.py |
def get_dataset(ds_path):
ds_path = pathlib.Path(ds_path)
images = list(ds_path.glob('*/*.jpg'))
images = [str(path) for path in images]
total_images = len(images)
labels = sorted(item.name for item in ds_path.glob('*/') if item.is_dir())
classes = labels
labels = dict((name, index) for... |
def make_tf_data(images, labels, augmentation):
images = tf.data.Dataset.from_tensor_slices(images)
images = images.map(preprocess_image, num_parallel_calls=AUTOTUNE)
labels = tf.data.Dataset.from_tensor_slices(labels)
dataset = tf.data.Dataset.zip((images, labels))
dataset = dataset.repeat()
... | aug_img = tf.numpy_function(func=aug_fn, inp=[image], Tout=tf.float32)
return aug_img, label | identifier_body |
ResNet50_augmentation.py |
def get_dataset(ds_path):
ds_path = pathlib.Path(ds_path)
images = list(ds_path.glob('*/*.jpg'))
images = [str(path) for path in images]
total_images = len(images)
labels = sorted(item.name for item in ds_path.glob('*/') if item.is_dir())
classes = labels
labels = dict((name, index) for... | ():
if epoch < LR_RAMPUP_EPOCHS:
lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN
return lr
def tf_d... | lrfn | identifier_name |
ResNet50_augmentation.py | =3, name=name + '_2_bn')(x)
x = tf.keras.layers.Activation('relu', name=name + '_2_relu')(x)
x = tf.keras.layers.Conv2D(4 * filters, 1, name=name + '_3_conv', kernel_initializer='he_uniform', bias_initializer='he_uniform', kernel_regularizer=tf.keras.regularizers.l2(0.0001))(x)
x = tf.keras.layers.BatchNor... | PATIENCE -= 1
if PATIENCE == 0:
break | conditional_block | |
sriov.go | {
return nil, "", fmt.Errorf("failed to load netconf: %v", err)
}
if n.VlanId < 0 || n.VlanId > 4094 {
return nil, "", fmt.Errorf(`invalid VLAN ID %d (must be between 0 and 4095 inclusive)`, n.VlanId)
}
return n, n.CNIVersion, nil
}
func | (conf *NetConf, ifName string, netns ns.NetNS) (*current.Interface, error) {
vf := ¤t.Interface{}
// 申请一个可用的Virtual Function
m, vfIdx, vfDevName, err := allocFreeVF()
if err != nil {
return nil, err
}
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV 成功申请%v网卡的第%v个VF, 名称为: %v\n", m.Attrs().Name, vfIdx, vfDevN... | setupVF | identifier_name |
sriov.go | ().Name, vfIdx, vfDevName)
vfDev, err := netlink.LinkByName(vfDevName)
if err != nil {
return nil, fmt.Errorf("failed to lookup vf device %q: %v", vfDevName, err)
}
if conf.MTU <= 0 {
conf.MTU = m.Attrs().MTU
}
if err = netlink.LinkSetVfHardwareAddr(m, vfIdx, vfDev.Attrs().HardwareAddr); err != nil {
... | result.DNS = n.DNS
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV cmdAdd result = %v\n", result)
return types.PrintResult(result, cniVersion) | random_line_split | |
sriov.go | return nil, "", fmt.Errorf("failed to load netconf: %v", err)
}
if n.VlanId < 0 || n.VlanId > 4094 {
return nil, "", fmt.Errorf(`invalid VLAN ID %d (must be between 0 and 4095 inclusive)`, n.VlanId)
}
return n, n.CNIVersion, nil
}
func setupVF(conf *NetConf, ifName string, netns ns.NetNS) (*current.Interface, ... | tdin | IPAM.Type, args.S | conditional_block |
sriov.go | {
return nil, "", fmt.Errorf("failed to load netconf: %v", err)
}
if n.VlanId < 0 || n.VlanId > 4094 {
return nil, "", fmt.Errorf(`invalid VLAN ID %d (must be between 0 and 4095 inclusive)`, n.VlanId)
}
return n, n.CNIVersion, nil
}
func setupVF(conf *NetConf, ifName string, netns ns.NetNS) (*current.Interfac... | ()
fmt.Fprintf(os.Stderr, "***********CNI SR-IOV releaseVF initns = %v\n", initns)
if err != nil {
return fmt.Errorf("failed to get init netns: %v", err)
}
// for IPAM in cmdDel
return netns.Do(func(_ ns.NetNS) error {
// get VF device
vfDev, err := netlink.LinkByName(ifName)
if err != nil {
return fm... | Dir); err != nil {
return "", fmt.Errorf("failed to open the virtfn%d dir of the device %q: %v", vf, master, err)
}
infos, err := ioutil.ReadDir(vfDir)
if err != nil {
return "", fmt.Errorf("failed to read the virtfn%d dir of the device %q: %v", vf, master, err)
}
if len(infos) != 1 {
return "", fmt.Errorf... | identifier_body |
ngx-grid-table.component.ts | End();
this.api.showLoadingOverlay();
this.setDataLoading(true);
this.dataSource(rowQuery)
.pipe(
takeUntil(this.destroy$),
catchError((err) => {
Console.collapse('grid-table.component RefreshRowsData', 'redBg', 'ERROR', 'redOutline');
console.log(err);
c... | conditional_block | ||
ngx-grid-table.component.ts | (this.showPagination !== false) {
this.showPagination = {
...NgxGridTableConstants.DEFAULT_PAGINATION,
...this.showPagination,
};
}
this.gridOptions = initGridOptions(this.gridOptions, this.rowSelection!, (event) => this.onGridReady(event));
}
private onGridReady(event: GridRe... | data: { | random_line_split | |
ngx-grid-table.component.ts | `, { keys: ids }).subscribe((value) => {
// this.deleted.emit(value);
// });
// }
/**
* 查询
*/
query(pageNum: number, pageSize: number): void {
this.api.clearRangeSelection();
this.api.deselectAll();
if (this.dataLoadModel !== 'pageable') {
console.warn('pageable 模式才能进行分页查询');
... | this.dataL | identifier_name | |
ngx-grid-table.component.ts | = 1;
/** 页大小 */
@Input() pageSize = 20;
/** 表格基础配置 */
@Input() gridOptions!: GridOptions;
/** 表格基础配置 */
@Input() colACLTmpl!: string;
/** 表格主题 */
@Input() gridTheme = 'ag-theme-balham';
/** 表格CSS */
@Input() gridTableClass = [];
/** 数据表格样式 */
@Input() gridTableStyle: { [key: string]: any } = { ... |
if (this.dataLoadModel === 'infinite') {
this.api.setServerSideDatasource(this.infiniteDataSource());
}
if (this.haveInit) {
this.gridReLoadReady.emit({ event, gridTable: this });
} else {
this.gridReady.emit({ event, gridTable: this });
this.haveInit = true;
}
// 当网格数... | ;
buildResizable(this.gridOptions, this.resizable);
buildOptionField(this.gridOptions, this.optionCell);
reuseTabFix(this.router, this.currentUrl, this.destroy$, apiGetter);
repairRowModeType(this.gridOptions, this.dataLoadModel);
buildColACL(this.gridOptions, this.aclService, this.colACLTmpl);
... | identifier_body |
normalizations.py | """Normalization layers."""
from typing import List, Optional, Tuple
import jax
from jax import numpy as jnp
from lingvo.jax import base_layer
from lingvo.jax import py_utils
from lingvo.jax import pytypes
NestedMap = py_utils.NestedMap
WeightInit = py_utils.WeightInit
weight_params = py_utils.weight_params
Instant... |
else:
# Use the batch statistics for normalization.
norm_mean = mean
norm_variance = variance
beta, gamma = self._get_beta_gamma(theta)
return norm_mean, norm_variance, beta, gamma
def fprop(self,
theta: NestedMap,
inputs: JTensor,
paddings:... | norm_mean = theta.moving_mean
norm_variance = theta.moving_variance | conditional_block |
normalizations.py | """Normalization layers."""
from typing import List, Optional, Tuple
import jax
from jax import numpy as jnp
from lingvo.jax import base_layer
from lingvo.jax import py_utils
from lingvo.jax import pytypes
NestedMap = py_utils.NestedMap
WeightInit = py_utils.WeightInit
weight_params = py_utils.weight_params
Instant... |
if enable_cross_replica_sum_on_tpu:
# TODO(shafey, yonghui): Fetch axis_name from globals.
sum_vv = jax.lax.psum(sum_vv, axis_name='batch')
variance = sum_vv / count_v
return mean, variance
class BatchNorm(base_layer.BaseLayer):
"""Batch normalization layer."""
@classmethod
def Params(cls) -> ... | """Computes mean and variance over the valid data points in inputs."""
assert inputs.ndim == padding.ndim
rank = inputs.ndim
assert all([0 <= dim < rank for dim in reduce_over_dims])
mask = 1.0 - padding
sum_v = jnp.sum(inputs * mask, axis=reduce_over_dims, keepdims=keepdims)
count_v = jnp.sum(
jnp.on... | identifier_body |
normalizations.py | """Normalization layers."""
from typing import List, Optional, Tuple
import jax
from jax import numpy as jnp
from lingvo.jax import base_layer
from lingvo.jax import py_utils
from lingvo.jax import pytypes
NestedMap = py_utils.NestedMap
WeightInit = py_utils.WeightInit
weight_params = py_utils.weight_params
Instant... | """
p = self.params
inputs, paddings = self._cast_to_fprop_dtype((inputs, paddings))
if paddings is None:
paddings = self._get_default_paddings(inputs)
assert inputs.ndim == paddings.ndim
assert paddings.shape[-1] == 1
norm_mean, norm_variance, beta, gamma = self.compute_and_update_m... | paddings: The paddings JTensor. Shaped [..., 1].
Returns:
Output after applying batch normalization, with the same shape as
'inputs'. | random_line_split |
normalizations.py | """Normalization layers."""
from typing import List, Optional, Tuple
import jax
from jax import numpy as jnp
from lingvo.jax import base_layer
from lingvo.jax import py_utils
from lingvo.jax import pytypes
NestedMap = py_utils.NestedMap
WeightInit = py_utils.WeightInit
weight_params = py_utils.weight_params
Instant... | (self, theta: NestedMap) -> Tuple[JTensor, JTensor]:
p = self.params
if p.use_moving_avg_in_training:
beta = 0.0
gamma = 1.0
else:
beta = theta.beta
gamma = theta.gamma + 1.0
return beta, gamma
def compute_and_update_moments(
self, theta: NestedMap, inputs: JTensor,
... | _get_beta_gamma | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.