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 |
|---|---|---|---|---|
resp.go | return "Integer"
case '$':
return "BulkString"
case '*':
return "Array"
case 'R':
return "RDB"
}
}
// Value represents the data of a valid RESP type.
type Value struct {
Typ Type
IntegerV int
Str []byte
ArrayV []Value
Null bool
RDB bool
Size int
}
func (v Value) ReplInfo() (... |
return string(buf[1]), _offset
}
// Integer converts Value to an int. If Value cannot be converted, Zero is returned.
func (v Value) Integer() int {
switch v.Typ {
default:
n, _ := strconv.ParseInt(v.String(), 10, 64)
return int(n)
case ':':
return v.IntegerV
}
}
// String converts Value to a string.
func... | {
return
} | conditional_block |
resp.go | return "Integer"
case '$':
return "BulkString"
case '*':
return "Array"
case 'R':
return "RDB"
}
}
// Value represents the data of a valid RESP type.
type Value struct {
Typ Type
IntegerV int
Str []byte
ArrayV []Value
Null bool
RDB bool
Size int
}
func (v Value) ReplInfo() (... |
// NullValue returns a RESP null bulk string.
func NullValue() Value { return Value{Typ: '$', Null: true} }
// ErrorValue returns a RESP error.
func ErrorValue(err error) Value {
if err == nil {
return Value{Typ: '-'}
}
return Value{Typ: '-', Str: []byte(err.Error())}
}
// IntegerValue returns a RESP integer.
... | { return Value{Typ: '$', Str: []byte(s)} } | identifier_body |
agent.go | /go/vt/dbconfigs"
"github.com/youtube/vitess/go/vt/env"
"github.com/youtube/vitess/go/vt/logutil"
"github.com/youtube/vitess/go/vt/mysqlctl"
"github.com/youtube/vitess/go/vt/tabletmanager/actionnode"
"github.com/youtube/vitess/go/vt/tabletmanager/actor"
"github.com/youtube/vitess/go/vt/tabletserver"
"github.com/... |
func (agent *ActionAgent) resolvePaths() error {
var p string
if *vtactionBinaryPath != "" {
p = *vtactionBinaryPath
} else {
vtroot, err := env.VtRoot()
if err != nil {
return err
}
p = path.Join(vtroot, "bin/vtaction")
}
if _, err := os.Stat(p); err != nil {
return fmt.Errorf("vtaction binary %s... | {
agent.mutex.Lock()
tablet := agent._tablet
agent.mutex.Unlock()
return tablet
} | identifier_body |
agent.go | /go/vt/dbconfigs"
"github.com/youtube/vitess/go/vt/env"
"github.com/youtube/vitess/go/vt/logutil"
"github.com/youtube/vitess/go/vt/mysqlctl"
"github.com/youtube/vitess/go/vt/tabletmanager/actionnode"
"github.com/youtube/vitess/go/vt/tabletmanager/actor"
"github.com/youtube/vitess/go/vt/tabletserver"
"github.com/... | () error {
tablet, err := agent.TopoServer.GetTablet(agent.TabletAlias)
if err != nil {
return err
}
agent.mutex.Lock()
agent._tablet = tablet
agent.mutex.Unlock()
return nil
}
func (agent *ActionAgent) Tablet() *topo.TabletInfo {
agent.mutex.Lock()
tablet := agent._tablet
agent.mutex.Unlock()
return tabl... | readTablet | identifier_name |
agent.go | /go/vt/dbconfigs"
"github.com/youtube/vitess/go/vt/env"
"github.com/youtube/vitess/go/vt/logutil"
"github.com/youtube/vitess/go/vt/mysqlctl"
"github.com/youtube/vitess/go/vt/tabletmanager/actionnode"
"github.com/youtube/vitess/go/vt/tabletmanager/actor"
"github.com/youtube/vitess/go/vt/tabletserver"
"github.com/... | } else {
if updatedTablet := actor.CheckTabletMysqlPort(agent.TopoServer, agent.Mysqld, agent.Tablet()); updatedTablet != nil {
agent.mutex.Lock()
agent._tablet = updatedTablet
agent.mutex.Unlock()
}
agent.runChangeCallback(oldTablet, context)
}
// Maybe invalidate the schema.
// This adds a depend... | random_line_split | |
agent.go | /go/vt/dbconfigs"
"github.com/youtube/vitess/go/vt/env"
"github.com/youtube/vitess/go/vt/logutil"
"github.com/youtube/vitess/go/vt/mysqlctl"
"github.com/youtube/vitess/go/vt/tabletmanager/actionnode"
"github.com/youtube/vitess/go/vt/tabletmanager/actor"
"github.com/youtube/vitess/go/vt/tabletserver"
"github.com/... |
// register the RPC services from the agent
agent.registerQueryService()
// start health check if needed
agent.initHeathCheck()
return agent, nil
}
func (agent *ActionAgent) runChangeCallback(oldTablet *topo.Tablet, context string) {
agent.mutex.Lock()
// Access directly since we have the lock.
newTablet :... | {
return nil, err
} | conditional_block |
mpsse.go | .mpsseVerify(); err != nil {
return err
}
}
// Initialize MPSSE to a known state.
// Reset the clock since it is impossible to read back the current clock rate.
// Reset all the GPIOs are inputs since it is impossible to read back the
// state of each GPIO (if they are input or output).
cmd := []byte{
clo... | b := [...]byte{gpioReadC, flush}
if _, err := h.Write(b[:]); err != nil {
return 0, err
}
ctx, cancel := context200ms()
defer cancel()
if _, err := h.ReadAll(ctx, b[:1]); err != nil {
return 0, err
}
return b[0], nil
}
| identifier_body | |
mpsse.go |
// Disables adaptive clocking.
clockNormal byte = 0x97
// CPU mode.
//
// Access the device registers like a memory mapped device.
//
// <op>, <addrLow>
cpuReadShort byte = 0x90
// <op>, <addrHi>, <addrLow>
cpuReadFar byte = 0x91
// <op>, <addrLow>, <data>
cpuWriteShort byte = 0x92
// <op>, <addrHi>, <ad... | SSETxShort(w | identifier_name | |
mpsse.go | - 0(1) 6MHz / 30MHz
// - 1(2) 3MHz / 15MHz
// - 2(3) 2MHz / 10MHz
// - 3(4) 1.5MHz / 7.5MHz
// - 4(5) 1.25MHz / 6MHz
// - ...
// - 0xFFFF(65536) 91.553Hz / 457.763Hz
//
// <op>, <valueL-1>, <valueH-1>
clockSetDivisor byte = 0x86
// Uses 3 phases data clocking: data is valid on both clock edges. Needed
// fo... | op |= dataInFall
}
| conditional_block | |
mpsse.go | 0x91
// Buffer operations.
//
// Flush the buffer back to the host.
flush byte = 0x87
// Wait until D5 (JTAG) or I/O1 (CPU) is high. Once it is detected as
// high, the MPSSE engine moves on to process the next instruction.
waitHigh byte = 0x88
waitLow byte = 0x89
)
// InitMPSSE sets the device into MPSSE mo... | if rbits != 0 {
if rbits > 8 { | random_line_split | |
subscription_group.go | metric")
}
}
if impacted {
serr = serror.New(ErrPluginCannotBeUnloaded, map[string]interface{}{
"task-id": id,
"plugin-to-unload": plgToUnload.Key(),
})
}
return serr
}
func (s *subscriptionGroup) process(id string) (serrs []serror.SnapError) {
// gathers collectors based on requested metric... | {
return fmt.Sprintf("%v"+core.Separator+"%v"+core.Separator+"%v", p.TypeName(), p.Name(), p.Version())
} | identifier_body | |
subscription_group.go | != nil {
return errs
}
s.subscriptionMap[id] = subscriptionGroup
return nil
}
// Remove removes a subscription group given a subscription group ID.
func (s subscriptionGroups) Remove(id string) []serror.SnapError {
s.Lock()
defer s.Unlock()
return s.remove(id)
}
func (s subscriptionGroups) remove(id string) ... | }
// pluginIsSubscribed returns true if a provided plugin has been found among subscribed plugins
// in the following subscription group
func (s *subscriptionGroup) pluginIsSubscribed(plugin *loadedPlugin) bool {
// range over subscribed plugins to find if the plugin is there
for _, sp := range s.plugins {
if sp.T... | }
}
return serrs | random_line_split |
subscription_group.go | fmt.Errorf("no metric found cannot subscribe: (%s) version(%d)",
metric.Namespace(), metric.Version())))
continue
}
m.config = metric.Config()
typ, serr := core.ToPluginType(m.Plugin.TypeName())
if serr != nil {
serrs = append(serrs, serror.New(err))
continue
}
// merge global plugin conf... | {
serrs = append(serrs, serror.New(err))
return serrs
} | conditional_block | |
subscription_group.go | != nil {
return errs
}
s.subscriptionMap[id] = subscriptionGroup
return nil
}
// Remove removes a subscription group given a subscription group ID.
func (s subscriptionGroups) Remove(id string) []serror.SnapError {
s.Lock()
defer s.Unlock()
return s.remove(id)
}
func (s subscriptionGroups) remove(id string) ... | (plugin *loadedPlugin) bool {
// range over subscribed plugins to find if the plugin is there
for _, sp := range s.plugins {
if sp.TypeName() == plugin.TypeName() && sp.Name() == plugin.Name() && sp.Version() == plugin.Version() {
return true
}
}
return false
}
// validatePluginUnloading verifies if a given... | pluginIsSubscribed | identifier_name |
prod.go | [0]
p.fpServicePrincipalID = "f1dd0a37-89c6-4e07-bcd1-ffd3d43d8875"
clustersGenevaLoggingPrivateKey, clustersGenevaLoggingCertificates, err := p.GetCertificateSecret(ctx, ClusterLoggingSecretName)
if err != nil {
return nil, err
}
p.clustersGenevaLoggingPrivateKey = clustersGenevaLoggingPrivateKey
p.clustersG... | {
// ARM ResourceGroup role assignments are not required in production.
return nil
} | identifier_body | |
prod.go | P/pkg/util/pem"
"github.com/Azure/ARO-RP/pkg/util/refreshable"
"github.com/Azure/ARO-RP/pkg/util/version"
)
type prod struct {
instancemetadata.InstanceMetadata
armClientAuthorizer clientauthorizer.ClientAuthorizer
adminClientAuthorizer clientauthorizer.ClientAuthorizer
keyvault basekeyvault.BaseClient
acrN... |
keys, err := databaseaccounts.ListKeys(ctx, p.ResourceGroup(), *(*accts.Value)[0].Name)
if err != nil {
return err
}
p.cosmosDBAccountName = *(*accts.Value)[0].Name
p.cosmosDBPrimaryMasterKey = *keys.PrimaryMasterKey
return nil
}
func (p *prod) populateDomain(ctx context.Context, rpAuthorizer autorest.Auth... | {
return fmt.Errorf("found %d database accounts, expected 1", len(*accts.Value))
} | conditional_block |
prod.go | -RP/pkg/util/pem"
"github.com/Azure/ARO-RP/pkg/util/refreshable"
"github.com/Azure/ARO-RP/pkg/util/version"
)
type prod struct {
instancemetadata.InstanceMetadata
armClientAuthorizer clientauthorizer.ClientAuthorizer
adminClientAuthorizer clientauthorizer.ClientAuthorizer
keyvault basekeyvault.BaseClient
ac... | func (p *prod) ACRResourceID() string {
return os.Getenv("ACR_RESOURCE_ID")
}
func (p *prod) ACRName() string {
return p.acrName
}
func (p *prod) AROOperatorImage() string {
return fmt.Sprintf("%s.azurecr.io/aro:%s", p.acrName, version.GitCommit)
}
func (p *prod) populateCosmosDB(ctx context.Context, rpAuthorizer... | random_line_split | |
prod.go | GenevaLoggingPrivateKey
p.clustersGenevaLoggingCertificate = clustersGenevaLoggingCertificates[0]
p.e2eStorageAccountName = "arov4e2e"
p.e2eStorageAccountRGName = "global"
p.e2eStorageAccountSubID = "0923c7de-9fca-4d9e-baf3-131d0c5b2ea4"
if p.ACRResourceID() != "" { // TODO: ugh!
acrResource, err := azure.Pars... | ShouldDeployDenyAssignment | identifier_name | |
pathy.go | . N is the amount of scenarios to pick from the file. They are evenly spread out in terms of problem size.")
os.Exit(0)
}
readNextArg() // Skip program name
modeString := readNextArg()
var p PathyParameters
// Read command-line arguments
switch (strings.ToLower(modeString)) {
case "draw":
p = getDrawMode... | else {
p.Mode = BenchMultiple
}
return p
}
func runDrawMode(p PathyParameters) {
if p.Mode != Draw {
panic("Assertion failed: unexpected mode")
}
var err error
grid, err = LoadMap(p.InPath)
if err != nil {
fmt.Printf("Error reading file \"%s\": %s\n", p.InPath, err.Error())
os.Exit(1)
}
img := MakeMa... | {
p.Mode = BenchAndDrawMultiple
p.OutPath = readNextArg()
p.Scale = MustParseInt(readNextArg())
} | conditional_block |
pathy.go | . N is the amount of scenarios to pick from the file. They are evenly spread out in terms of problem size.")
os.Exit(0)
}
readNextArg() // Skip program name
modeString := readNextArg()
var p PathyParameters
// Read command-line arguments
switch (strings.ToLower(modeString)) {
case "draw":
p = getDrawMode... | () PathyParameters {
if len(os.Args) != 5 {
fmt.Printf("Wrong number of arguments. Run %s without parameters for more info.\n", os.Args[0])
os.Exit(1)
}
p := PathyParameters{}
p.Mode = Draw
p.InPath = readNextArg()
p.OutPath = readNextArg()
p.Scale = MustParseInt(readNextArg())
return p
}
func getSin... | getDrawModeParameters | identifier_name |
pathy.go | . N is the amount of scenarios to pick from the file. They are evenly spread out in terms of problem size.")
os.Exit(0)
}
readNextArg() // Skip program name
modeString := readNextArg()
var p PathyParameters
// Read command-line arguments
switch (strings.ToLower(modeString)) {
case "draw":
p = getDrawMode... | img = DrawPath(img, path, p.Scale)
err = SaveImage(img, p.OutPath)
if err != nil {
fmt.Printf("Error writing image \"%s\": %s\n", p.OutPath, err.Error())
os.Exit(1)
}
}
}
func runMultipleMode(p PathyParameters) {
if p.Mode != BenchMultiple && p.Mode != BenchAndDrawMultiple {
panic("Assertion failed... |
if p.Mode == BenchAndDrawSingle {
img := MakeMapImage(p.Scale) | random_line_split |
pathy.go | . N is the amount of scenarios to pick from the file. They are evenly spread out in terms of problem size.")
os.Exit(0)
}
readNextArg() // Skip program name
modeString := readNextArg()
var p PathyParameters
// Read command-line arguments
switch (strings.ToLower(modeString)) {
case "draw":
p = getDrawMode... | if err != nil {
fmt.Printf("Error writing image \"%s\": %s\n", p.OutPath, err.Error())
os.Exit(1)
}
}
}
func runMultipleMode(p PathyParameters) {
if p.Mode != BenchMultiple && p.Mode != BenchAndDrawMultiple {
panic("Assertion failed: unexpected mode")
}
// Load scenarios
scenarios, err := LoadScenar... | {
if p.Mode != BenchSingle && p.Mode != BenchAndDrawSingle {
panic("Assertion failed: unexpected mode")
}
var err error
grid, err = LoadMap(p.InPath)
if err != nil {
fmt.Printf("Error reading file \"%s\": %s\n", p.InPath, err.Error())
os.Exit(1)
}
start := NewNode(p.StartX, p.StartY)
goal := NewNode(p.G... | identifier_body |
dac.rs | to avoid losing any
//! transfer events generated by the timer (for example, when 2 update cycles occur before the DMA
//! transfer completion is handled). In this mode, by the time DMA swaps buffers, there is always a valid buffer in the
//! "next-transfer" double-buffer location for the DMA transfer. Once a transfer... | (value: u16) -> Self {
Self(value)
}
}
macro_rules! dac_output {
($name:ident, $index:literal, $data_stream:ident,
$spi:ident, $trigger_channel:ident, $dma_req:ident) => {
/// $spi is used as a type for indicating a DMA transfer into the SPI TX FIFO
struct $spi {
spi: h... | from | identifier_name |
dac.rs | avoid losing any
//! transfer events generated by the timer (for example, when 2 update cycles occur before the DMA
//! transfer completion is handled). In this mode, by the time DMA swaps buffers, there is always a valid buffer in the
//! "next-transfer" double-buffer location for the DMA transfer. Once a transfer co... |
}
macro_rules! dac_output {
($name:ident, $index:literal, $data_stream:ident,
$spi:ident, $trigger_channel:ident, $dma_req:ident) => {
/// $spi is used as a type for indicating a DMA transfer into the SPI TX FIFO
struct $spi {
spi: hal::spi::Spi<hal::stm32::$spi, hal::spi::Disable... | {
Self(value)
} | identifier_body |
dac.rs | avoid losing any
//! transfer events generated by the timer (for example, when 2 update cycles occur before the DMA
//! transfer completion is handled). In this mode, by the time DMA swaps buffers, there is always a valid buffer in the
//! "next-transfer" double-buffer location for the DMA transfer. Once a transfer co... |
}
}
impl From<DacCode> for f32 {
fn from(code: DacCode) -> f32 {
i16::from(code) as f32 * DacCode::VOLT_PER_LSB
}
}
impl From<DacCode> for i16 {
fn from(code: DacCode) -> i16 {
(code.0 as i16).wrapping_sub(i16::MIN)
}
}
impl From<i16> for DacCode {
/// Encode signed 16-bit va... | {
Ok(DacCode::from(code as i16))
} | conditional_block |
dac.rs | to avoid losing any
//! transfer events generated by the timer (for example, when 2 update cycles occur before the DMA
//! transfer completion is handled). In this mode, by the time DMA swaps buffers, there is always a valid buffer in the
//! "next-transfer" double-buffer location for the DMA transfer. Once a transfer... | ///
/// # Args
/// * `spi` - The SPI interface used to communicate with the ADC.
/// * `stream` - The DMA stream used to write DAC codes over SPI.
/// * `trigger_channel` - The sampling timer output compare channel for update triggers.
pub fn new(
... | >,
}
impl $name {
/// Construct the DAC output channel. | random_line_split |
sqlite.py | **kwds):
if cls is SqliteBase:
msg = 'cannot instantiate SqliteBase directly - make a subclass'
raise NotImplementedError(msg)
return super(SqliteBase, cls).__new__(cls)
def __init__(self, connection, table):
"""Initialize self."""
self._connection = connect... |
if not _is_nsiterable(keys):
keys = (keys,)
group_clause = [self._normalize_column(x) for x in keys]
group_clause = ', '.join(group_clause)
select_clause = '{0}, {1}'.format(group_clause, ', '.join(sql_function))
trailing_clause = 'GROUP BY ' + group_clause
... | sql_function = ', '.join(sql_function)
cursor = self._execute_query(sql_function, **kwds_filter)
result = cursor.fetchone()
if len(result) == 1:
return result[0]
return result # <- EXIT! | conditional_block |
sqlite.py | **kwds):
if cls is SqliteBase:
msg = 'cannot instantiate SqliteBase directly - make a subclass'
raise NotImplementedError(msg)
return super(SqliteBase, cls).__new__(cls)
def __init__(self, connection, table):
"""Initialize self."""
self._connection = connect... | """Loads *table* data from given SQLite *connection*:
::
conn = sqlite3.connect('mydatabase.sqlite3')
subject = datatest.SqliteSource(conn, 'mytable')
"""
@classmethod
def from_records(cls, data, columns=None):
"""Alternate constructor to load an existing collection of
... | column = '_empty_'
return '"' + column + '"'
class SqliteSource(SqliteBase): | random_line_split |
sqlite.py | **kwds):
if cls is SqliteBase:
msg = 'cannot instantiate SqliteBase directly - make a subclass'
raise NotImplementedError(msg)
return super(SqliteBase, cls).__new__(cls)
def __init__(self, connection, table):
"""Initialize self."""
self._connection = connect... | (self):
"""Return iterable of dictionary rows (like csv.DictReader)."""
cursor = self._connection.cursor()
cursor.execute('SELECT * FROM ' + self._table)
column_names = self.columns()
dict_row = lambda x: dict(zip(column_names, x))
return (dict_row(row) for row in cursor... | __iter__ | identifier_name |
sqlite.py |
def columns(self):
"""Return list of column names."""
cursor = self._connection.cursor()
cursor.execute('PRAGMA table_info(' + self._table + ')')
return [x[1] for x in cursor.fetchall()]
def __iter__(self):
"""Return iterable of dictionary rows (like csv.DictReader)."""... | """Base class four SqliteSource and CsvSource (not intended to be
instantiated directly).
"""
def __new__(cls, *args, **kwds):
if cls is SqliteBase:
msg = 'cannot instantiate SqliteBase directly - make a subclass'
raise NotImplementedError(msg)
return super(SqliteBase... | identifier_body | |
storage.rs | _name = "database.db";
let db_manager = r2d2_sqlite::SqliteConnectionManager::file(file_name);
return r2d2::Pool::new(db_manager).unwrap();
};
}
pub fn create_main_database_if_needed() {
let pool = &MAIN_POOL;
let conn = pool.get().unwrap();
create_main_tables_if_needed(&conn);
}
fn cr... |
// Rooms
pub const PENDING_TOKEN_EXPIRATION: i64 = 10 * 60;
pub const TOKEN_EXPIRATION: i64 = 7 * 24 * 60 * 60;
pub const FILE_EXPIRATION: i64 = 15 * 24 * 60 * 60;
lazy_static::lazy_static! {
static ref POOLS: Mutex<HashMap<String, DatabaseConnectionPool>> = Mutex::new(HashMap::new());
}
pub fn pool_by_room_i... | {
let main_table_cmd = "CREATE TABLE IF NOT EXISTS main (
id TEXT PRIMARY KEY,
name TEXT,
image_id TEXT
)";
conn.execute(&main_table_cmd, params![]).expect("Couldn't create main table.");
} | identifier_body |
storage.rs | file_name = "database.db";
let db_manager = r2d2_sqlite::SqliteConnectionManager::file(file_name);
return r2d2::Pool::new(db_manager).unwrap();
};
}
pub fn create_main_database_if_needed() {
let pool = &MAIN_POOL;
let conn = pool.get().unwrap();
create_main_tables_if_needed(&conn);
}
... | Ok(_) => (),
Err(e) => return error!("Couldn't prune pending tokens due to error: {}.", e),
};
}
info!("Pruned pending tokens.");
}
fn get_expired_file_ids(
pool: &DatabaseConnectionPool, file_expiration: i64,
) -> Result<Vec<String>, ()> {
let now = chrono::Utc::now().t... | };
let stmt = "DELETE FROM pending_tokens WHERE timestamp < (?1)";
let now = chrono::Utc::now().timestamp();
let expiration = now - PENDING_TOKEN_EXPIRATION;
match conn.execute(&stmt, params![expiration]) { | random_line_split |
storage.rs | file_name = "database.db";
let db_manager = r2d2_sqlite::SqliteConnectionManager::file(file_name);
return r2d2::Pool::new(db_manager).unwrap();
};
}
pub fn create_main_database_if_needed() {
let pool = &MAIN_POOL;
let conn = pool.get().unwrap();
create_main_tables_if_needed(&conn);
}
... | (conn: &DatabaseConnection) {
let main_table_cmd = "CREATE TABLE IF NOT EXISTS main (
id TEXT PRIMARY KEY,
name TEXT,
image_id TEXT
)";
conn.execute(&main_table_cmd, params![]).expect("Couldn't create main table.");
}
// Rooms
pub const PENDING_TOKEN_EXPIRATION: i64 = 10 * 60;
pub ... | create_main_tables_if_needed | identifier_name |
grid.go | .keywords, request.user.keywords,
// and request.imp[0].ext.keywords, and request.ext.keywords. Invalid keywords in request.imp[0].ext.keywords are not incorporated.
// Invalid keywords in request.ext.keywords.site and request.ext.keywords.user are dropped.
func buildConsolidatedKeywordsReqExt(openRTBUser, openRTBSite ... | for publisherKey, publisherValue := range section {
// publisher value must be a slice
publisherValueSlice, ok := publisherValue.([]interface{})
if !ok {
continue
}
for _, publisherValueItem := range publisherValueSlice {
// item must be an object
publisherItem, ok := publisherValueItem.(map[string]... | random_line_split | |
grid.go | , request.user.keywords,
// and request.imp[0].ext.keywords, and request.ext.keywords. Invalid keywords in request.imp[0].ext.keywords are not incorporated.
// Invalid keywords in request.ext.keywords.site and request.ext.keywords.user are dropped.
func buildConsolidatedKeywordsReqExt(openRTBUser, openRTBSite string, f... | (extKeywords map[string]interface{}) Keywords {
keywords := make(Keywords)
for k, v := range extKeywords {
// keywords may only be provided in the site and user sections
if k != "site" && k != "user" {
continue
}
// the site or user sections must be an object
if section, ok := v.(map[string]interface{});... | parseKeywordsFromMap | identifier_name |
grid.go | , request.user.keywords,
// and request.imp[0].ext.keywords, and request.ext.keywords. Invalid keywords in request.imp[0].ext.keywords are not incorporated.
// Invalid keywords in request.ext.keywords.site and request.ext.keywords.user are dropped.
func buildConsolidatedKeywordsReqExt(openRTBUser, openRTBSite string, f... |
sort.Strings(publisherItemKeys)
// compose compatible alternate segment format
for _, potentialSegmentName := range publisherItemKeys {
potentialSegmentValues := publisherItem[potentialSegmentName]
// values must be an array
if valuesSlice, ok := potentialSegmentValues.([]interface{}); ok {
f... | {
publisherItemKeys = append(publisherItemKeys, v)
} | conditional_block |
grid.go | .keywords, request.user.keywords,
// and request.imp[0].ext.keywords, and request.ext.keywords. Invalid keywords in request.imp[0].ext.keywords are not incorporated.
// Invalid keywords in request.ext.keywords.site and request.ext.keywords.user are dropped.
func buildConsolidatedKeywordsReqExt(openRTBUser, openRTBSite ... | // extract valid segments
if segmentsSlice, exists := maputil.ReadEmbeddedSlice(publisherItem, "segments"); exists {
for _, segment := range segmentsSlice {
if segmentMap, ok := segment.(map[string]interface{}); ok {
name, hasName := maputil.ReadEmbeddedString(segmentMap, "name")
value, hasVa... | {
keywordsPublishers := make(KeywordsPublisher)
for publisherKey, publisherValue := range section {
// publisher value must be a slice
publisherValueSlice, ok := publisherValue.([]interface{})
if !ok {
continue
}
for _, publisherValueItem := range publisherValueSlice {
// item must be an object
pub... | identifier_body |
decode.rs | <'a> {
pub prefix: &'a str,
pub local: &'a str,
}
impl Name<'_> {
/// Check if a given name matches a tag name composed of `prefix:local` or just `local`
pub fn matches(&self, tag_name: &str) -> bool {
let split = tag_name.find(':');
match split {
None => tag_name == self.lo... | Name | identifier_name | |
decode.rs | ())
}
/// Returns whether this `StartEl` matches a given name
/// in `prefix:local` form.
pub fn matches(&self, pat: &str) -> bool {
self.name.matches(pat)
}
/// Local component of this element's name
///
/// ```xml
/// <foo:bar>
/// ^^^
/// ```
pub fn loca... |
/// Prefix component of this elements name (or empty string)
/// ```xml
/// <foo:bar>
/// ^^^
/// ```
pub fn prefix(&self) -> &str {
self.name.prefix
}
/// Returns true of `el` at `depth` is a match for this `start_el`
fn end_el(&self, el: ElementEnd, depth: Depth) -> boo... | {
self.name.local
} | identifier_body |
decode.rs | _ref())
}
/// Returns whether this `StartEl` matches a given name
/// in `prefix:local` form.
pub fn matches(&self, pat: &str) -> bool {
self.name.matches(pat)
}
/// Local component of this element's name
///
/// ```xml
/// <foo:bar>
/// ^^^
/// ```
pub fn ... | /// <Nested /> <-- next call returns this
/// <MoreNested>hello</MoreNested> <-- then this:
/// </A>
/// <B/> <-- second call to next_tag returns this
/// </Response>
/// ```
pub fn next_start_element<'a>(&'a mut self) -> Option<StartEl<'inp>> {
next_start_element(sel... | random_line_split | |
controller.go | ) ControllerName() string {
if c.controlmeta != nil {
return c.controlmeta.Name()
}
return ""
}
func (c *ControlManager) ActionName() string {
return c.action
}
func (c *ControlManager) Controller() reflect.Value {
return c.control
}
func (c *ControlManager) ActionMeta() *ActionMeta {
return c.controlmeta.Ac... | case DatatypeFloat64:
val, _ := d.Float64(arg.LName())
value = reflect.ValueOf(val) | random_line_split | |
controller.go | : context,
controlmeta: cm,
action: action,
}
}
type ControlManager struct {
control reflect.Value
context *web.Context
controlmeta *Meta
action string
prepared bool
executed bool
state int
vw mvc.View
}
func (c *ControlManager) SetControllerMeta(cm *Meta) (ok b... | () string {
if c.controlmeta != nil {
return c.controlmeta.Name()
}
return ""
}
func (c *ControlManager) ActionName() string {
return c.action
}
func (c *ControlManager) Controller() reflect.Value {
return c.control
}
func (c *ControlManager) ActionMeta() *ActionMeta {
return c.controlmeta.ActionFromRequest(... | ControllerName | identifier_name |
controller.go | : context,
controlmeta: cm,
action: action,
}
}
type ControlManager struct {
control reflect.Value
context *web.Context
controlmeta *Meta
action string
prepared bool
executed bool
state int
vw mvc.View
}
func (c *ControlManager) SetControllerMeta(cm *Meta) (ok b... | else {
reses = []string{res}
}
for _, r := range reses {
rinterface := c.context.Resource(strings.TrimSpace(r))
if rinterface != nil {
if parser, ok := rinterface.(StructValueFeeder); ok {
var err error
value, err = parser.FeedStructValue(c.context, field, value)
... | {
reses = strings.Split(res, ",")
} | conditional_block |
controller.go | : context,
controlmeta: cm,
action: action,
}
}
type ControlManager struct {
control reflect.Value
context *web.Context
controlmeta *Meta
action string
prepared bool
executed bool
state int
vw mvc.View
}
func (c *ControlManager) SetControllerMeta(cm *Meta) (ok b... |
func getVMap(context *web.Context) map[string]reflect.Value {
return map[string]reflect.Value{
"context": reflect.ValueOf(context),
"w": reflect.ValueOf(context.Response),
"r": reflect.ValueOf(context.Request),
"upath": reflect.ValueOf(context.UPath),
"pdata": reflect.Va... | {
if c.prepared && c.controlmeta.T() == ContypeScontroller {
ctrler := c.control.Interface().(mvc.Controller)
ctrler.Destruct_()
}
} | identifier_body |
inifile.py | pyproject.toml` or `flit.ini` file with data about the package.
"""
if path.suffix == '.toml':
with path.open() as f:
d = toml.load(f)
res = prep_toml_config(d, path)
else:
# Treat all other extensions as the older flit.ini format
cp = _read_pkg_ini(path)
... | raise ConfigError(
"Description file {} does not exist".format(description_file)
)
ext = description_file.suffix
try:
mimetype = readme_ext_to_content_type[ext]
except KeyError:
log.warning("Unknown extension %r for description file... | description_file = path.parent / md_sect.get('description-file')
try:
with description_file.open(encoding='utf-8') as f:
raw_desc = f.read()
except FileNotFoundError: | random_line_split |
inifile.py | pyproject.toml` or `flit.ini` file with data about the package.
"""
if path.suffix == '.toml':
with path.open() as f:
d = toml.load(f)
res = prep_toml_config(d, path)
else:
# Treat all other extensions as the older flit.ini format
cp = _read_pkg_ini(path)
... |
else:
entrypoints['console_scripts'] = scripts_dict
def _read_pkg_ini(path):
"""Reads old-style flit.ini
"""
cp = configparser.ConfigParser()
with path.open(encoding='utf-8') as f:
cp.read_file(f)
return cp
readme_ext_to_content_type = {
'.rst': 'text/x-rst',
... | raise EntryPointsConflict | conditional_block |
inifile.py | pyproject.toml` or `flit.ini` file with data about the package.
"""
if path.suffix == '.toml':
with path.open() as f:
d = toml.load(f)
res = prep_toml_config(d, path)
else:
# Treat all other extensions as the older flit.ini format
cp = _read_pkg_ini(path)
... |
def prep_toml_config(d, path):
"""Validate config loaded from pyproject.toml and prepare common metadata
Returns a dictionary with keys: module, metadata, scripts, entrypoints,
raw_config.
"""
if ('tool' not in d) or ('flit' not in d['tool']) \
or (not isinstance(d['tool']['flit']... | def __str__(self):
return ('Please specify console_scripts entry points, or [scripts] in '
'flit config, not both.') | identifier_body |
inifile.py | pyproject.toml` or `flit.ini` file with data about the package.
"""
if path.suffix == '.toml':
with path.open() as f:
d = toml.load(f)
res = prep_toml_config(d, path)
else:
# Treat all other extensions as the older flit.ini format
cp = _read_pkg_ini(path)
... | (entrypoints, scripts_dict):
if scripts_dict:
if 'console_scripts' in entrypoints:
raise EntryPointsConflict
else:
entrypoints['console_scripts'] = scripts_dict
def _read_pkg_ini(path):
"""Reads old-style flit.ini
"""
cp = configparser.ConfigParser()
with pa... | _add_scripts_to_entrypoints | identifier_name |
dynmap.go | for k, v := range(this.Map) {
submp, ok := ToDynMap(this.Map[k])
if ok {
v = submp.ToMap()
}
mp[k] = v
}
return mp
}
// recursively clones this DynMap. all sub maps will be clones as well
func (this *DynMap) Clone() *DynMap {
mp := New()
for k, v := range(this.Map) {
submp, ok := ToDynMap(this.Map[... | random_line_split | ||
dynmap.go | rails style (key[key2][key2]=value)
// TODO: we should sort the keynames so ordering is consistent and then this
// can be used a cache key
func (this *DynMap) MarshalURL() (string, error) {
vals := &url.Values{}
for key, value := range this.Map {
err := this.urlEncode(vals, key, value)
if err != nil {
return... |
for k, v := range mp.Map {
//encode in rails style key[key2]=value
this.urlEncode(vals, fmt.Sprintf("%s[%s]", key, k), v)
}
return nil
}
r := reflect.ValueOf(value)
//now test if it is an array
if r.Kind() == reflect.Array || r.Kind() == reflect.Slice {
for i :=0; i < r.Len(); i++ {
this.urlEncode... | {
return fmt.Errorf("Unable to convert %s", mp)
} | conditional_block |
dynmap.go | rails style (key[key2][key2]=value)
// TODO: we should sort the keynames so ordering is consistent and then this
// can be used a cache key
func (this *DynMap) MarshalURL() (string, error) {
vals := &url.Values{}
for key, value := range this.Map {
err := this.urlEncode(vals, key, value)
if err != nil {
return... |
// gets a string. if string is not available in the map, then the default
//is returned
func (this *DynMap) MustString(key string, def string) string {
tmp, ok := this.GetString(key)
if !ok {
return def
}
return tmp
}
func (this *DynMap) GetTime(key string) (time.Time, bool) {
tmp, ok := this.Get(key)
if !ok... | {
tmp, ok := this.Get(key)
if !ok {
return ToString(tmp), ok
}
return ToString(tmp), true
} | identifier_body |
dynmap.go | rails style (key[key2][key2]=value)
// TODO: we should sort the keynames so ordering is consistent and then this
// can be used a cache key
func (this *DynMap) MarshalURL() (string, error) {
vals := &url.Values{}
for key, value := range this.Map {
err := this.urlEncode(vals, key, value)
if err != nil {
return... | (key string, def time.Time) time.Time {
tmp, ok := this.GetTime(key)
if !ok {
return def
}
return tmp
}
func (this *DynMap) GetBool(key string) (bool, bool) {
tmp, ok := this.Get(key)
if !ok {
return false, ok
}
b, err := ToBool(tmp)
if err != nil {
return false, false
}
return b, true
}
func (this *... | MustTime | identifier_name |
lex.go |
func (t token) Error() string {
return fmt.Sprintf("lex error at %d: %s", int(t.pos), t.value)
}
type tokenType int
const (
tokenNone tokenType = iota
tokenError
tokenEOF
tokenText // anything that isn't one of the following
tokenZeroWidthNoBreakSpace // U+FEFF used for unwrappable
tokenNL ... | {
switch {
case t.typ == tokenEOF:
return "EOF"
case t.typ == tokenError:
return t.value
}
return t.value
} | identifier_body | |
lex.go | 012": tokenFigureDash,
"\u2013": tokenEnDash,
"\u2014": tokenEmDash,
"\u2015": tokenHorizontalBar,
"\u2053": tokenSwungDash,
"\u207B": tokenSuperscriptMinus,
"\u208B": tokenSubScriptMinus,
"\u2E3A": tokenTwoEmDash,
"\u2E3B": tokenThreeEmDash,
"\uFE31": tokenPresentationFormForVerticalEmDash,
"\uFE32": tokenPr... | lexTab | identifier_name | |
lex.go | U+FE58
tokenSmallHyphenMinus // U+FE63
tokenFullWidthHyphenMinus // U+FF0D
)
var key = map[string]tokenType{
"\r": tokenCR,
"\n": tokenNL,
"\t": tokenTab,
"\uFEFF": tokenZeroWidthNoBreakSpace,
"\u0020": tokenSpace,
"\u1680": tokenOghamSpaceMark,
"\u180E": tokenMongolianVowelSeparator,
"\u200... | {
return false, classText
} | conditional_block | |
lex.go |
tokenSixPerEmSpace // U+2006
tokenFigureSpace // U+2007
tokenPunctuationSpace // U+2008
tokenThinSpace // U+2009
tokenHairSpace // U+200A
tokenZeroWidthSpace // U+200B
tokenMediumMathematicalSpace // U+205F
tokenIdeographicSpace // U+3000
// dash tokens from http... | tokenEmDash: "em dash",
tokenHorizontalBar: "horizontal bar",
tokenSwungDash: "swung dash",
tokenSuperscriptMinus: "superscript minus",
tokenSubScriptMinus: "subscript minus",
tokenTwoEmDash: ... | random_line_split | |
se-spam-helper.user.js | Of = {}, notifiedOfToday = {};
var ooflagSites = {};
var questionQueue = {};
var siteWebsocketIDs = {};
var sitesByWebsocketID = {};
var onQuestionQueueTimeout = flushQuestionQueue;
var checkAnswer = checkPost, checkQuestion = checkPost;
menu_init();
notification_init();
window.addEventListener("unl... | (site){
if(siteWebsocketIDs[site] === undefined){
siteWebsocketIDs[site] = false; // prevent double fetching
GM_xmlhttpRequest({
method: "GET",
url: "http://" + siteNameToHostName(site),
ontimeout: checkSiteHasSocket.bind(null, site),
onerror: function(response) {
... | checkSiteHasSocket | identifier_name |
se-spam-helper.user.js | .head.querySelectorAll("script:not([src])");
[].forEach.call(scripts, function(script){
var match = /StackExchange\.realtime\.subscribeToActiveQuestions\(["']?(\d+)/.exec(script.innerHTML);
if(match){
siteWebsocketIDs[site] = match[1];
sitesByWeb... | url: "http://api.stackexchange.com/2.2/" + path.join('/') + "?" + $.param(options), | random_line_split | |
se-spam-helper.user.js | ", site);
}
}
});
}
}
function parseRealtimeSocket(wsData){
return{
body: wsData.bodySummary,
link: wsData.url,
site: wsData.apiSiteParameter,
tags: wsData.tags,
title: htmlUnescape(wsData.titleEncodedFancy),
question_id: wsData.id,
};... | {
console.log("collected " + results.length + " results");
responseDeferred.resolve({items: results, partial: !!response.has_more});
} | conditional_block | |
se-spam-helper.user.js | Of = {}, notifiedOfToday = {};
var ooflagSites = {};
var questionQueue = {};
var siteWebsocketIDs = {};
var sitesByWebsocketID = {};
var onQuestionQueueTimeout = flushQuestionQueue;
var checkAnswer = checkPost, checkQuestion = checkPost;
menu_init();
notification_init();
window.addEventListener("unl... |
function scrapePerSiteQuestion(html, site){
var question = new DOMParser().parseFromString(html, "text/html")
.getElementsByClassName("question-summary")[0];
var qLink = "http://" + siteNameToHostName(site)
+ question.querySelector("a.question-hyperlink").getAttribute("href");
onQ... | {
$(".realtime-question:visible").each(function(){
var qLink = this.querySelector("a.realtime-question-url");
onQuestionActive({
body: undefined,
link: qLink.href,
site: hostNameToSiteName(qLink.hostname),
tags: $(".post-tag", this).map(function(){return this.textContent;... | identifier_body |
channel_router.rs | See the License for the specific language governing permissions and
// limitations under the License.
use std::cmp;
use std::collections::HashMap;
struct Ranges {
ranges: Vec<std::ops::Range<usize>>,
}
impl Ranges {
fn new() -> Self {
Ranges { ranges: Vec::new() }
}
fn add(&mut self, start:... | else {
self.tasks.insert(from, vec![to]);
}
}
fn into_tasks(mut self, src: &ChannelLayout) -> Vec<Task> {
self.tasks
.drain()
.map(|(k, v)| {
let net = match src[k] {
ChannelState::Net(i) => i,
_ => unr... | {
k.push(to);
} | conditional_block |
channel_router.rs | See the License for the specific language governing permissions and
// limitations under the License.
use std::cmp;
use std::collections::HashMap;
struct Ranges {
ranges: Vec<std::ops::Range<usize>>,
}
impl Ranges {
fn new() -> Self {
Ranges { ranges: Vec::new() }
}
fn add(&mut self, start:... | (&self) -> bool {
self == &ChannelState::Free
}
pub fn contains_net(&self) -> bool {
matches!(self, ChannelState::Net(_))
}
pub fn is_constant_on(&self) -> bool {
matches!(self, ChannelState::Constant)
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ChannelOp {
M... | is_free | identifier_name |
channel_router.rs | See the License for the specific language governing permissions and
// limitations under the License.
use std::cmp;
use std::collections::HashMap;
struct Ranges {
ranges: Vec<std::ops::Range<usize>>,
}
impl Ranges {
fn new() -> Self {
Ranges { ranges: Vec::new() }
}
fn add(&mut self, start:... | } else {
self.tasks.insert(from, vec![to]);
}
}
fn into_tasks(mut self, src: &ChannelLayout) -> Vec<Task> {
self.tasks
.drain()
.map(|(k, v)| {
let net = match src[k] {
ChannelState::Net(i) => i,
... | if let Some(k) = self.tasks.get_mut(&from) {
k.push(to); | random_line_split |
channel_router.rs | the License for the specific language governing permissions and
// limitations under the License.
use std::cmp;
use std::collections::HashMap;
struct Ranges {
ranges: Vec<std::ops::Range<usize>>,
}
impl Ranges {
fn new() -> Self {
Ranges { ranges: Vec::new() }
}
fn add(&mut self, start: usi... |
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ChannelState {
Free,
// Occupied means no connection. This is the same as a constant false.
Occupied,
// Constant true.
Constant,
Net(usize),
}
pub type ChannelLayout = [ChannelState];
impl ChannelState {
pub fn is_free(&self) -> bool {
... | {
self.ranges.iter().map(|r| r.end - r.start).sum()
} | identifier_body |
chain.rs | how much of
// this sector is actually used.
if block[1] < 1 {
// It's not valid for a chain sector to not include the first two bytes
// as allocated.
return Err(DiskError::InvalidChainLink.into());
}
Ok(ChainLink::Tail(bl... | visited_sectors: HashSet<Location>,
block: [u8; BLOCK_SIZE],
}
impl ChainIterator {
/// Create a new chain iterator starting at the specified location.
pub fn new(blocks: BlockDeviceRef, starting_sector: Location) -> ChainIterator {
ChainIterator {
blocks,
next_sector: S... | /// Returns a ChainSector which includes the NTS (next track and sector) link.
pub struct ChainIterator {
blocks: BlockDeviceRef,
next_sector: Option<Location>, | random_line_split |
chain.rs | how much of
// this sector is actually used.
if block[1] < 1 {
// It's not valid for a chain sector to not include the first two bytes
// as allocated.
return Err(DiskError::InvalidChainLink.into());
}
Ok(ChainLink::Tail(bl... | (&mut self) -> io::Result<()> {
// Write the current block
let mut blocks = self.blocks.borrow_mut();
blocks
.sector_mut(self.location)?
.copy_from_slice(&self.block);
Ok(())
}
}
impl | write_current_block | identifier_name |
TTA.py | 0:index]
arr2 = arr[index + 1:]
return torch.cat((arr1, arr2), dim=0)
def del_under_threshold(result, threshold=0.):
idxes = []
for idx in range(len(result[0]['scores'])):
if result[0]['scores'][idx] < threshold:
idxes.append(idx)
for i in idxes:
result[0]['scores'] = d... | pos = i + 1
if i != N - 1:
maxscore = np.max(scores[pos:], axis=0)
maxpos = np.argmax(scores[pos:], axis=0)
else:
maxscore = scores[-1]
maxpos = 0
# 如果当前 i 的得分小于后面的最大 score, 则与之交换, 确保 i 上的 score 最大
if scores[i] < maxscore:
... | scores = scores.detach().numpy()
for i in range(N):
# 找出 i 后面的最大 score 及其下标 | random_line_split |
TTA.py | 0:index]
arr2 = arr[index + 1:]
return torch.cat((arr1, arr2), dim=0)
def del_under_threshold(result, threshold=0.):
idxes = []
for idx in range(len(result[0]['scores'])):
if result[0]['scores'][idx] < threshold:
|
for i in idxes:
result[0]['scores'] = del_tensor_ele(result[0]['scores'], len(result[0]['scores']) - 1)
result[0]['labels'] = del_tensor_ele(result[0]['labels'], len(result[0]['labels']) - 1)
result[0]['boxes'] = del_tensor_ele(result[0]['boxes'], len(result[0]['boxes']) - 1)
return res... | idxes.append(idx) | conditional_block |
TTA.py |
class TTAVerticalFlip(BaseWheatTTA):
""" author: @shonenkov """
def augment(self, image):
return image
def batch_augment(self, images):
return images.flip(3)
def deaugment_boxes(self, boxes, image):
height = image.height
boxes[:, [3, 1]] = height - boxes[:, [1, 3]]
... | width = image.width
boxes[:, [2, 0]] = width - boxes[:, [0, 2]]
return boxes | identifier_body | |
TTA.py | :
""" author: @shonenkov """
image_size = 512
def augment(self, image):
raise NotImplementedError
def batch_augment(self, images):
raise NotImplementedError
def deaugment_boxes(self, boxes, image):
raise NotImplementedError
def get_object_detector(num_classes):
# loa... | BaseWheatTTA | identifier_name | |
app_multiple_databus.go | time time.Time) (index string) {
var (
week = map[int]string{
0: "0108",
1: "0916",
2: "1724",
3: "2531",
}
)
return strings.Replace(time.Format(format), "week", week[time.Day()/9], -1)
}
// NewAppMultipleDatabus .
func NewAppMultipleDatabus(d *Dao, appid string) (amd *AppMultipleDatabus) {
var er... | if t, ok := parseMap["attr"]; ok {
if t.(int64)>>0&1 == 0 || (m.Action == "insert" && t.(int64)>>1&1 == 1) {
continue
}
}
}
var newParseMap map[string]interface{}
newParseMap, err = amd.newParseMap(c, m.Table, parseMap)
if err != nil {
if amd.attrs.AppID == "c... | } | random_line_split |
app_multiple_databus.go | string
indexEntityName string
)
indexFormat := strings.Split(amd.attrs.Index.IndexFormat, ",")
aliases, aliasErr := amd.d.GetAliases(amd.attrs.ESName, amd.attrs.Index.IndexAliasPrefix)
if indexFormat[0] == "int" || indexFormat[0] == "single" {
for i := amd.attrs.Index.IndexFrom; i <= amd.attrs.Index.IndexTo; i... |
if | identifier_name | |
app_multiple_databus.go | context.Context) {
var (
err error
indexAliasName string
indexEntityName string
)
indexFormat := strings.Split(amd.attrs.Index.IndexFormat, ",")
aliases, aliasErr := amd.d.GetAliases(amd.attrs.ESName, amd.attrs.Index.IndexAliasPrefix)
if indexFormat[0] == "int" || indexFormat[0] == "single" {
... | err = amd.d.BulkDBData(c, amd.attrs, writeEntityIndex, partData...)
} else {
err = amd.d.BulkDatabusData(c, amd.attrs, writeEntityIndex, partData...)
}
return
}
// Commit .
func (amd *AppMultipleDatabus) Commit(c context.Contex | identifier_body | |
app_multiple_databus.go | ESName, indexAliasName, indexEntityName, amd.attrs.Index.IndexMapping)
} else {
amd.d.InitIndex(c, aliases, amd.attrs.ESName, indexAliasName, indexEntityName, amd.attrs.Index.IndexMapping)
}
}
} else {
if amd.indexNameSuffix, err = amd.IndexNameSuffix(indexFormat[0], indexFormat[1]); err != nil {
log.... | log.Error("Commit error(%v)", err)
continue
}
}
}
} else {
for k, c := range amd.commits {
if err = c.Commit(); err != nil {
| conditional_block | |
zz_generated.composition_transforms.go | return field.Required(field.NewPath("map"), "given transform type map requires configuration")
}
return verrors.WrapFieldError(t.Map.Validate(), field.NewPath("map"))
case TransformTypeMatch:
if t.Match == nil {
return field.Required(field.NewPath("match"), "given transform type match requires configuration"... |
// MatchTransformPattern is a transform that returns the value that matches a
// pattern.
type MatchTransformPattern struct {
// Type specifies how the pattern matches the input.
//
// * `literal` - the pattern value has to exactly match (case sensitive) the
// input string. This is the default.
//
// * `regexp`... | // Valid MatchTransformPatternTypes.
const (
MatchTransformPatternTypeLiteral MatchTransformPatternType = "literal"
MatchTransformPatternTypeRegexp MatchTransformPatternType = "regexp"
) | random_line_split |
zz_generated.composition_transforms.go | ) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, &m.Pairs)
}
// MarshalJSON from this MapTransform.
func (m *MapTransform) MarshalJSON() ([]byte, error) {
return json.Marshal(m.Pairs)
}
// MatchFallbackTo defines how a match operation will fallback.
type MatchFallbackTo string
// Valid MatchFallbackTo.
c... | {
switch c {
case TransformIOTypeString, TransformIOTypeBool, TransformIOTypeInt, TransformIOTypeInt64, TransformIOTypeFloat64, TransformIOTypeObject, TransformIOTypeArray:
return true
}
return false
} | identifier_body | |
zz_generated.composition_transforms.go | return field.Required(field.NewPath("map"), "given transform type map requires configuration")
}
return verrors.WrapFieldError(t.Map.Validate(), field.NewPath("map"))
case TransformTypeMatch:
if t.Match == nil {
return field.Required(field.NewPath("match"), "given transform type match requires configuration"... | () MathTransformType {
if m.Type == "" {
return MathTransformTypeMultiply
}
return m.Type
}
// Validate checks this MathTransform is valid.
func (m *MathTransform) Validate() *field.Error {
switch m.GetType() {
case MathTransformTypeMultiply:
if m.Multiply == nil {
return field.Required(field.NewPath("mult... | GetType | identifier_name |
zz_generated.composition_transforms.go | return field.Required(field.NewPath("map"), "given transform type map requires configuration")
}
return verrors.WrapFieldError(t.Map.Validate(), field.NewPath("map"))
case TransformTypeMatch:
if t.Match == nil {
return field.Required(field.NewPath("match"), "given transform type match requires configuration"... |
return m.Type
}
// Validate checks this MathTransform is valid.
func (m *MathTransform) Validate() *field.Error {
switch m.GetType() {
case MathTransformTypeMultiply:
if m.Multiply == nil {
return field.Required(field.NewPath("multiply"), "must specify a value if a multiply math transform is specified")
}
... | {
return MathTransformTypeMultiply
} | conditional_block |
input.py | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# prompt and confirm based on https://github.com/pallets/click
# Copyright 2014 Pallets
# | Redistribution and use in source and binary forms, with or without modification,
# | are permitted provided that the follo... | prompt: str = '', file: IO = sys.stdout) -> str: # pragma: no cover
"""
Read a string from standard input, but prompt to standard error.
The trailing newline is stripped.
If the user hits EOF (Unix: :kbd:`Ctrl-D`, Windows: :kbd:`Ctrl-Z+Return`), raise :exc:`EOFError`.
On Unix, GNU readline is used if enabled.
... | tderr_input( | identifier_name |
input.py | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# prompt and confirm based on https://github.com/pallets/click
# Copyright 2014 Pallets
# | Redistribution and use in source and binary forms, with or without modification,
# | are permitted provided that the follo... |
while True:
value2 = prompt_func("Repeat for confirmation: ")
if value2:
break
if value == value2:
return result
click.echo("Error: the two entered values do not match", err=err)
def confirm(
text: str,
default: bool = False,
abort: bool = False,
prompt_suffix: str = ": ",
show_default... | eturn result
| conditional_block |
input.py | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# prompt and confirm based on https://github.com/pallets/click
# Copyright 2014 Pallets
# | Redistribution and use in source and binary forms, with or without modification,
# | are permitted provided that the follo... |
@overload
def choice(
options: List[str],
| f sys.platform != "linux":
# Write the prompt separately so that we get nice
# coloring through colorama on Windows
click.echo(text, nl=False, err=err)
text = ''
if hide_input:
return hidden_prompt_func(text)
elif err:
return stderr_input(text, file=sys.stderr)
else:
return click.termui.visible_prompt... | identifier_body |
input.py | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# prompt and confirm based on https://github.com/pallets/click
# Copyright 2014 Pallets
# | Redistribution and use in source and binary forms, with or without modification,
# | are permitted provided that t... | return line[:-1]
return line
def _prompt(text, err: bool, hide_input: bool):
if sys.platform != "linux":
# Write the prompt separately so that we get nice
# coloring through colorama on Windows
click.echo(text, nl=False, err=err)
text = ''
if hide_input:
return hidden_prompt_func(text)
elif err:
r... | raise EOFError
elif line[-1] == '\n': | random_line_split |
main.go | rrg.redisHost = sss[0]
rrg.redisPort = sss[1]
} else {
logger.Fatal("Redis-pretensor config error.")
}
// Create a new redis-pretensor connection pool
redisPretensorPool = newPool(rrg.redisHost+":"+rrg.redisPort, 400)
redisConnPretensor, err = redisPretensorPool.Dial()
if err != nil {
logger.Fatal("Could n... | (filechan chan filedesc, sortie chan os.Signal, graph *rg.Graph) error {
logger.Println("Entering pretensorparse")
defer wg.Done()
for {
select {
case file := <-filechan:
if *debug {
logger.Println(file.path)
}
info := file.info
path := file.path
if !info.IsDir() {
content, err := os.ReadF... | pretensorParse | identifier_name |
main.go | }
}
if tmp.GetParsedTimeStamp().After(ls) {
query = `MATCH (b:Bot {ip:"` + tmp.GetIp() + `"})
SET b.lastseen="` + tmp.GetTimestamp() + `"`
result, err = graph.Query(query)
if err != nil {
fmt.Println(err)
}
}
}
// Create CC if no... | if _, ok := binurls[vi.url]; !ok {
//do something here | random_line_split | |
main.go | g.redisHost = sss[0]
rrg.redisPort = sss[1]
} else {
logger.Fatal("Redis-pretensor config error.")
}
// Create a new redis-pretensor connection pool
redisPretensorPool = newPool(rrg.redisHost+":"+rrg.redisPort, 400)
redisConnPretensor, err = redisPretensorPool.Dial()
if err != nil {
logger.Fatal("Could not... |
graph.AddNode(tmp.GetBotNode())
_, err := graph.Flush()
if err != nil {
fmt.Println(err)
}
// Update Firstseen / Lastseen if already seen
} else {
result.Next()
r := result.Record()
fsstr, _ := r.Get("b.firstseen")
lsstr, _ := r.Get("b.lastse... | {
logger.Println(tmp.GetBotNode())
} | conditional_block |
main.go | g.redisHost = sss[0]
rrg.redisPort = sss[1]
} else {
logger.Fatal("Redis-pretensor config error.")
}
// Create a new redis-pretensor connection pool
redisPretensorPool = newPool(rrg.redisHost+":"+rrg.redisPort, 400)
redisConnPretensor, err = redisPretensorPool.Dial()
if err != nil {
logger.Fatal("Could not... |
// Parsing whatever is thrown into filechan
func pretensorParse(filechan chan filedesc, sortie chan os.Signal, graph *rg.Graph) error {
logger.Println("Entering pretensorparse")
defer wg.Done()
for {
select {
case file := <-filechan:
if *debug {
logger.Println(file.path)
}
info := file.info
pat... | {
for {
buf, err := redis.String(redisConnD4.Do("LPOP", redisd4Queue))
// If redis return empty: EOF (user should not stop)
if err == redis.ErrNil {
// no new record we break until the tick
return io.EOF
// oops
} else if err != nil {
logger.Println(err)
return err
}
fileinfo, err := os.Stat... | identifier_body |
trixer.py | .table = []
def generateFontStrip(self):
if self.fontName is not None:
base = Image.new('RGBA', (self.charNumber*self.blockWidth,self.blockHeight), (255,255,255,255))
txt = Image.new('RGBA', base.size, (255,255,255,0))
fnt = ImageFont.truetype(("lumitables/" + self.fon... | p = raw_input("Output file already exists. Overwrite existing file? (Y/N)")
if(op == "n" or op == "N"):
v_print(1,"EXITING: Process canceled. Output file already exists.")
sys.exit(-1)
| conditional_block | |
trixer.py | umitable.blockHeight*lumitable.blockWidth)
return luminance
### LUMITABLE CLASS ###
class lumitable:
def __init__(self,fontname,fontsize,range,blockheight,blockwidth):
self.fontName = fontname
self.fontSize = fontsize
self.charRange = range
self.charNumber = range[1] - range[... |
### Trix Class ###
class trix:
def __init__(self,name,lumi,imagetb):
self.name = name
self.lumitable = lumi
self.imagetable = imagetb
self.imagetable.table.reverse()
self.image = Image.new('RGBA', (self.imagetable.xBlocks*self.lumitable.blockWidth,self.imagetable.yBlocks... | m = Image.open(self.file)
px = im.load()
red = 0
green = 0
blue = 0
for x in xrange(blockx*lumitable.blockWidth,(blockx*lumitable.blockWidth)+lumitable.blockWidth):
for y in xrange(blocky*lumitable.blockHeight,(blocky*lumitable.blockHeight)+lumitable.blockHeight):
... | identifier_body |
trixer.py | umitable.blockHeight*lumitable.blockWidth)
return luminance
### LUMITABLE CLASS ###
class lumitable:
def __init__(self,fontname,fontsize,range,blockheight,blockwidth):
self.fontName = fontname
self.fontSize = fontsize
self.charRange = range
self.charNumber = range[1] - range[... | blue = self.imagetable.colorTable[tuple[0]][tuple[1]][2]
d.text((x,y), chr(currtrix[0]), font=fnt, fill=(red,green,blue,255))
else:
d.text((x,y), chr(currtrix[0]), font=fnt, fill=(0,0,0,255))
... | x = tuple[0] * self.lumitable.blockWidth
y = tuple[1] * self.lumitable.blockHeight
if self.imagetable.colorMode == "colors":
red = self.imagetable.colorTable[tuple[0]][tuple[1]][0]
... | random_line_split |
trixer.py | umitable.blockHeight*lumitable.blockWidth)
return luminance
### LUMITABLE CLASS ###
class lumitable:
def __init__(self,fontname,fontsize,range,blockheight,blockwidth):
self.fontName = fontname
self.fontSize = fontsize
self.charRange = range
self.charNumber = range[1] - range[... | self,name,lumi,imagetb):
self.name = name
self.lumitable = lumi
self.imagetable = imagetb
self.imagetable.table.reverse()
self.image = Image.new('RGBA', (self.imagetable.xBlocks*self.lumitable.blockWidth,self.imagetable.yBlocks*self.lumitable.blockHeight), (255,255,255,255))
... | _init__( | identifier_name |
main.rs | -> Error {
match error.kind() {
io::ErrorKind::PermissionDenied => Error::MustRunAsRoot,
_e => Error::IoError(dbg!(error)),
}
}
}
fn octet<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, u8, E> {
map_res(digit1, |s: &str| s.parse::<u8>())(input)
}
fn do... | <'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {
preceded(tag("#"), rest)(input)
}
#[derive(Debug)]
struct HostsLine {
ip: IpAddr,
canonical_hostname: String,
aliases: Vec<String>,
comment: Option<String>,
}
impl HostsLine {
fn new(ip: IpAddr, canonical_hostname: ... | comment | identifier_name |
main.rs | -> Error {
match error.kind() {
io::ErrorKind::PermissionDenied => Error::MustRunAsRoot,
_e => Error::IoError(dbg!(error)),
}
}
}
fn octet<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, u8, E> {
map_res(digit1, |s: &str| s.parse::<u8>())(input)
}
fn do... | #[derive(Debug)]
struct HostsLine {
ip: IpAddr,
canonical_hostname: String,
aliases: Vec<String>,
comment: Option<String>,
}
impl HostsLine {
fn new(ip: IpAddr, canonical_hostname: String) -> HostsLine {
let aliases = Vec::new();
let comment = None;
HostsLine {
i... |
fn comment<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, &'a str, E> {
preceded(tag("#"), rest)(input)
}
| random_line_split |
dummy.py | zope.container.contained import notifyContainerModified
from zope.datetime import rfc1123_date
from zope.event import notify
from zope.interface import implementer
from ...ActionProviderBase import ActionProviderBase
from ...interfaces import IContentish
from ...interfaces import ISiteRoot
from ...interfaces import I... |
def userdefined_roles(self):
return ('Member', 'Reviewer')
def getProperty(self, id, default=None):
return getattr(self, id, default)
class DummyUserFolder(Implicit):
""" A dummy User Folder with 2 dummy Users.
"""
id = 'acl_users'
def __init__(self):
setattr(self,... | obj = self
for id in path[3:]:
obj = getattr(obj, id)
return obj | conditional_block |
dummy.py | zope.container.contained import notifyContainerModified
from zope.datetime import rfc1123_date
from zope.event import notify
from zope.interface import implementer
from ...ActionProviderBase import ActionProviderBase
from ...interfaces import IContentish
from ...interfaces import ISiteRoot
from ...interfaces import I... | return self.acl_users
else:
obj = self
for id in path[3:]:
obj = getattr(obj, id)
return obj
def userdefined_roles(self):
return ('Member', 'Reviewer')
def getProperty(self, id, default=None):
return getattr(self, id, defa... |
def unrestrictedTraverse(self, path, default=None, restricted=0):
if path == ['acl_users']: | random_line_split |
dummy.py | zope.container.contained import notifyContainerModified
from zope.datetime import rfc1123_date
from zope.event import notify
from zope.interface import implementer
from ...ActionProviderBase import ActionProviderBase
from ...interfaces import IContentish
from ...interfaces import ISiteRoot
from ...interfaces import I... |
def __call__(self):
if self.view_id is None:
return DummyContent.inheritedAttribute('__call__')(self)
else:
# view_id control for testing
template = getattr(self, self.view_id)
if getattr(aq_base(template), 'isDocTemp', 0):
return tem... | return 'Dummy Content Title' | identifier_body |
dummy.py | zope.container.contained import notifyContainerModified
from zope.datetime import rfc1123_date
from zope.event import notify
from zope.interface import implementer
from ...ActionProviderBase import ActionProviderBase
from ...interfaces import IContentish
from ...interfaces import ISiteRoot
from ...interfaces import I... | (self):
return self._safe_get('created_date')
def modified(self):
return self._safe_get('modified_date')
def Type(self):
return 'Dummy Content Title'
def __call__(self):
if self.view_id is None:
return DummyContent.inheritedAttribute('__call__')(self)
e... | created | identifier_name |
player.go | 0
obj.createTime = now
obj.SetModified()
m.goldEquipObject = obj
return
}
//获取金装背包
func (m *PlayerGoldEquipDataManager) GetGoldEquipBag() *BodyBag {
return m.goldEquipBag
}
//加载身上金装
func (m *PlayerGoldEquipDataManager) loadGoldEquipSlot() (err error) {
//加载金装槽位
goldEquipSlotList, err := dao.GetGoldEquipDao().... | {
return m.equipSettingObj
}
//获取特殊技能
func (m *PlayerGoldEquipDataManager) GetTeShuSkillList() (skillList []*scene.TeshuSkillObject) {
for _, obj := range m.goldEquipBag.GetAll() {
if obj.IsEmpty() {
continue
}
itemTemplate := item.GetItemService().GetItem(int(obj.i | identifier_body | |
player.go | DataManager) Heartbeat() {
}
//加载金装日志
func (m *PlayerGoldEquipDataManager) loadLog() (err error) {
entityList, err := dao.GetGoldEquipDao().GetPlayerGoldEquipLogEntityList(m.p.GetId())
if err != nil {
return
}
for _, entity := range entityList {
logObj := NewPlayerGoldEquipLogObject(m.p)
logObj.FromEntity(... | {
m.initGoldEquipObject()
}
return
}
// 初始化设置
func (m *PlayerGoldEquipDataManager) initEquipSeting() {
obj := NewPlayerGoldEquipSettingObject(m.p)
id, _ := idutil.GetId()
now := global.GetGame().GetTimeService().Now()
obj.id = id
obj.fenJieIsAuto = 0
obj.fenJieQuality = 0
//zrc: 修改过的
//TODO:cjb 默认是检测过的,看完... | obj
} else | conditional_block |
player.go | DataManager) Heartbeat() {
}
//加载金装日志
func (m *PlayerGoldEquipDataManager) loadLog() (err error) {
entityList, err := dao.GetGoldEquipDao().GetPlayerGoldEquipLogEntityList(m.p.GetId())
if err != nil {
return
}
for _, entity := range entityList {
logObj := NewPlayerGoldEquipLogObject(m.p)
logObj.FromEntity(... | func (m *PlayerGoldEquipDataManager) GetGoldEquipByPos(pos inventorytypes.BodyPositionType) *PlayerGoldEquipSlotObject {
item := m.goldEquipBag.GetByPosition(pos)
if item == nil {
return nil
}
return item
}
//使用装备
func (m *PlayerGoldEquipDataManager) PutOn(pos inventorytypes.BodyPositionType, itemId int32, leve... | itemObj.SetModified()
}
}
//获取装备 | random_line_split |
player.go | *PlayerGoldEquipDataManager) loadGoldEquipSlot() (err error) {
//加载金装槽位
goldEquipSlotList, err := dao.GetGoldEquipDao().GetGoldEquipSlotList(m.p.GetId())
if err != nil {
return
}
slotList := make([]*PlayerGoldEquipSlotObject, 0, len(goldEquipSlotList))
for _, slot := range goldEquipSlotList {
pio := NewPlaye... | {
continue
| identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.