file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
resp.go | /*
Copyright 2019 yametech.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distr... |
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 | /*
Copyright 2019 yametech.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distr... |
// 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 | // Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
The agent handles local execution of actions triggered remotely.
It has two execution models:
- listening on an action path for ActionNode objects. When recei... |
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 | // Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
The agent handles local execution of actions triggered remotely.
It has two execution models:
- listening on an action path for ActionNode objects. When recei... | () 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 | // Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
The agent handles local execution of actions triggered remotely.
It has two execution models:
- listening on an action path for ActionNode objects. When recei... | } 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 | // Copyright 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
The agent handles local execution of actions triggered remotely.
It has two execution models:
- listening on an action path for ActionNode objects. When recei... |
// 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 | // Copyright 2017 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// MPSSE is Multi-Protocol Synchronous Serial Engine
//
// MPSSE basics:
// http://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_B... | // MPSSEDBusRead reads all the DBus pins D0~D7.
func (h *handle) MPSSEDBusRead() (byte, error) {
b := [...]byte{gpioReadD, 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]... | 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 | // Copyright 2017 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// MPSSE is Multi-Protocol Synchronous Serial Engine
//
// MPSSE basics:
// http://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_B... | byte, wbits, rbits int, ew, er gpio.Edge, lsbf bool) (byte, error) {
op := byte(dataBit)
if lsbf {
op |= dataLSBF
}
l := wbits
if wbits != 0 {
if wbits > 8 {
return 0, errors.New("ftdi: write buffer too long; max 8")
}
op |= dataOut
if ew == gpio.FallingEdge {
op |= dataOutFall
}
}
if rbits !=... | SSETxShort(w | identifier_name |
mpsse.go | // Copyright 2017 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// MPSSE is Multi-Protocol Synchronous Serial Engine
//
// MPSSE basics:
// http://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_B... | }
return op
}
// MPSSETx runs a transaction on the clock on pins D0, D1 and D2.
//
// It can only do it on a multiple of 8 bits.
func (h *handle) MPSSETx(w, r []byte, ew, er gpio.Edge, lsbf bool) error {
l := len(w)
if len(w) != 0 {
// TODO(maruel): This is easy to fix by daisy chaining operations.
if len(w) > ... | op |= dataInFall
}
| conditional_block |
mpsse.go | // Copyright 2017 The Periph Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
// MPSSE is Multi-Protocol Synchronous Serial Engine
//
// MPSSE basics:
// http://www.ftdichip.com/Support/Documents/AppNotes/AN_135_MPSSE_B... | return 0, errors.New("ftdi: read buffer too long; max 8")
}
op |= dataIn
if er == gpio.FallingEdge {
op |= dataInFall
}
if l != 0 && rbits != l {
return 0, errors.New("ftdi: mismatched buffer lengths")
}
l = rbits
}
b := [3]byte{op, byte(l - 1)}
cmd := b[:2]
if wbits != 0 {
cmd = append(cmd... | if rbits != 0 {
if rbits > 8 { | random_line_split |
subscription_group.go | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required ... | {
return fmt.Sprintf("%v"+core.Separator+"%v"+core.Separator+"%v", p.TypeName(), p.Name(), p.Version())
} | identifier_body | |
subscription_group.go | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required ... | }
// 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 | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required ... |
}
} else {
pool, err := s.pluginRunner.AvailablePlugins().getOrCreatePool(plg.Key())
if err != nil {
serrs = append(serrs, serror.New(err))
return serrs
}
pool.Subscribe(id)
if pool.Eligible() {
err = s.verifyPlugin(plg)
if err != nil {
serrs = append(serrs, serror.New(err))
... | {
serrs = append(serrs, serror.New(err))
return serrs
} | conditional_block |
subscription_group.go | /*
http://www.apache.org/licenses/LICENSE-2.0.txt
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required ... | (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 | package env
// Copyright (c) Microsoft Corporation.
// Licensed under the Apache License 2.0.
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"net"
"os"
"strings"
"time"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autores... |
func (p *prod) E2EStorageAccountName() string {
return p.e2eStorageAccountName
}
func (p *prod) E2EStorageAccountRGName() string {
return p.e2eStorageAccountRGName
}
func (p *prod) E2EStorageAccountSubID() string {
return p.e2eStorageAccountSubID
}
func (p *prod) ShouldDeployDenyAssignment() bool {
return p.en... | {
// ARM ResourceGroup role assignments are not required in production.
return nil
} | identifier_body |
prod.go | package env
// Copyright (c) Microsoft Corporation.
// Licensed under the Apache License 2.0.
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"net"
"os"
"strings"
"time"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autores... |
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 | package env
// Copyright (c) Microsoft Corporation.
// Licensed under the Apache License 2.0.
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"net"
"os"
"strings"
"time"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autores... | 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 | package env
// Copyright (c) Microsoft Corporation.
// Licensed under the Apache License 2.0.
import (
"context"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"net"
"os"
"strings"
"time"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autores... | () bool {
return p.envType == environmentTypeProduction
}
func (p *prod) IsDevelopment() bool {
return p.envType == environmentTypeDevelopment
}
| ShouldDeployDenyAssignment | identifier_name |
pathy.go | package main
import (
"fmt"
"os"
"strings"
"path/filepath"
"strconv"
"time"
"math"
)
type PathyMode int
const (
Draw PathyMode = iota
BenchSingle
BenchAndDrawSingle
BenchMultiple
BenchAndDrawMultiple
)
type PathyParameters struct {
Mode PathyMode
InPath string
OutPath string
Scale int
Algo... | 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 | package main
import (
"fmt"
"os"
"strings"
"path/filepath"
"strconv"
"time"
"math"
)
type PathyMode int
const (
Draw PathyMode = iota
BenchSingle
BenchAndDrawSingle
BenchMultiple
BenchAndDrawMultiple
)
type PathyParameters struct {
Mode PathyMode
InPath string
OutPath string
Scale int
Algo... | () 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 | package main
import (
"fmt"
"os"
"strings"
"path/filepath"
"strconv"
"time"
"math"
)
type PathyMode int
const (
Draw PathyMode = iota
BenchSingle
BenchAndDrawSingle
BenchMultiple
BenchAndDrawMultiple
)
type PathyParameters struct {
Mode PathyMode
InPath string
OutPath string
Scale int
Algo... | 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 | package main
import (
"fmt"
"os"
"strings"
"path/filepath"
"strconv"
"time"
"math"
)
type PathyMode int
const (
Draw PathyMode = iota
BenchSingle
BenchAndDrawSingle
BenchMultiple
BenchAndDrawMultiple
)
type PathyParameters struct {
Mode PathyMode
InPath string
OutPath string
Scale int
Algo... |
func runMultipleMode(p PathyParameters) {
if p.Mode != BenchMultiple && p.Mode != BenchAndDrawMultiple {
panic("Assertion failed: unexpected mode")
}
// Load scenarios
scenarios, err := LoadScenarios(p.InPath)
if err != nil {
fmt.Printf("Error loading scenarios file \"%s\": %s\n", p.InPath, err.Error())
o... | {
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 | //! Stabilizer DAC management interface
//!
//! # Design
//!
//! Stabilizer DACs are connected to the MCU via a simplex, SPI-compatible interface. Each DAC
//! accepts a 16-bit output code.
//!
//! In order to maximize CPU processing time, the DAC code updates are offloaded to hardware using
//! a timer compare channel... | (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 | //! Stabilizer DAC management interface
//!
//! # Design
//!
//! Stabilizer DACs are connected to the MCU via a simplex, SPI-compatible interface. Each DAC
//! accepts a 16-bit output code.
//!
//! In order to maximize CPU processing time, the DAC code updates are offloaded to hardware using
//! a timer compare channel... |
}
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 | //! Stabilizer DAC management interface
//!
//! # Design
//!
//! Stabilizer DACs are connected to the MCU via a simplex, SPI-compatible interface. Each DAC
//! accepts a 16-bit output code.
//!
//! In order to maximize CPU processing time, the DAC code updates are offloaded to hardware using
//! a timer compare channel... |
}
}
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 | //! Stabilizer DAC management interface
//!
//! # Design
//!
//! Stabilizer DACs are connected to the MCU via a simplex, SPI-compatible interface. Each DAC
//! accepts a 16-bit output code.
//!
//! In order to maximize CPU processing time, the DAC code updates are offloaded to hardware using
//! a timer compare channel... | ///
/// # 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 | # -*- coding: utf-8 -*-
import sqlite3
from ..utils.builtins import *
from ..utils import decimal
from ..load.sqltemp import TemporarySqliteTable
from ..utils.misc import _is_nsiterable
from ..__past__.api07_comp import CompareDict
from ..__past__.api07_comp import CompareSet
from .base import BaseSource
sqlite3.r... |
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 | # -*- coding: utf-8 -*-
import sqlite3
from ..utils.builtins import *
from ..utils import decimal
from ..load.sqltemp import TemporarySqliteTable
from ..utils.misc import _is_nsiterable
from ..__past__.api07_comp import CompareDict
from ..__past__.api07_comp import CompareSet
from .base import BaseSource
sqlite3.r... | """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 | # -*- coding: utf-8 -*-
import sqlite3
from ..utils.builtins import *
from ..utils import decimal
from ..load.sqltemp import TemporarySqliteTable
from ..utils.misc import _is_nsiterable
from ..__past__.api07_comp import CompareDict
from ..__past__.api07_comp import CompareSet
from .base import BaseSource
sqlite3.r... | (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 | # -*- coding: utf-8 -*-
import sqlite3
from ..utils.builtins import *
from ..utils import decimal
from ..load.sqltemp import TemporarySqliteTable
from ..utils.misc import _is_nsiterable
from ..__past__.api07_comp import CompareDict
from ..__past__.api07_comp import CompareSet
from .base import BaseSource
sqlite3.r... |
class SqliteSource(SqliteBase):
"""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 l... | """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 | use regex::Regex;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use log::{error, info};
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::params;
use rusqlite_migration::{Migrations, M};
use super::errors::Error;
pub type DatabaseConnection = r2d2::PooledConnection<SqliteConnectionM... |
// 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 | use regex::Regex;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use log::{error, info};
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::params;
use rusqlite_migration::{Migrations, M};
use super::errors::Error;
pub type DatabaseConnection = r2d2::PooledConnection<SqliteConnectionM... | 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 | use regex::Regex;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Mutex;
use log::{error, info};
use r2d2_sqlite::SqliteConnectionManager;
use rusqlite::params;
use rusqlite_migration::{Migrations, M};
use super::errors::Error;
pub type DatabaseConnection = r2d2::PooledConnection<SqliteConnectionM... | (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 | package grid
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"strings"
"github.com/prebid/openrtb/v19/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-server/openrtb_ext"
"github.com/prebid/... | 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 | package grid
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"strings"
"github.com/prebid/openrtb/v19/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-server/openrtb_ext"
"github.com/prebid/... | (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 | package grid
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"strings"
"github.com/prebid/openrtb/v19/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-server/openrtb_ext"
"github.com/prebid/... |
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 | package grid
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"strings"
"github.com/prebid/openrtb/v19/openrtb2"
"github.com/prebid/prebid-server/adapters"
"github.com/prebid/prebid-server/config"
"github.com/prebid/prebid-server/errortypes"
"github.com/prebid/prebid-server/openrtb_ext"
"github.com/prebid/... |
func parseKeywordsFromOpenRTB(keywords, section string) Keywords {
keywordsSplit := strings.Split(keywords, ",")
segments := make([]KeywordSegment, 0, len(keywordsSplit))
for _, v := range keywordsSplit {
if v != "" {
segments = append(segments, KeywordSegment{Name: "keywords", Value: v})
}
}
if len(segmen... | {
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 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use crate::unescape::unescape;
use std::borrow::Cow;
use std::convert::TryFrom;
use thiserror::Error;
use xmlparser::{ElementEnd, Token, Tokenizer};
pub type Depth = usize;
// in general, these errors... | <'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 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use crate::unescape::unescape;
use std::borrow::Cow;
use std::convert::TryFrom;
use thiserror::Error;
use xmlparser::{ElementEnd, Token, Tokenizer};
pub type Depth = usize;
// in general, these errors... |
/// 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 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use crate::unescape::unescape;
use std::borrow::Cow;
use std::convert::TryFrom;
use thiserror::Error;
use xmlparser::{ElementEnd, Token, Tokenizer};
pub type Depth = usize;
// in general, these errors... | /// <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 | package controller
import (
"errors"
"log"
"net/http"
"reflect"
"strings"
"github.com/zaolab/sunnified/mvc"
"github.com/zaolab/sunnified/mvc/view"
"github.com/zaolab/sunnified/web"
)
var ErrControllerNotFound = errors.New("controller not found")
var ErrUnprepared = errors.New("controller has not been prep'ed... | case DatatypeEmail:
val, _ := d.Email(arg.LName())
value = reflect.ValueOf(val)
case DatatypeURL:
val, _ := d.Url(arg.LName())
value = reflect.ValueOf(val)
case DatatypeDate:
val, _ := d.Date(arg.LName())
value = reflect.ValueOf(val)
case DatatypeTime:
val, _ := d.Time(arg.LName())
value = reflect.V... | case DatatypeFloat64:
val, _ := d.Float64(arg.LName())
value = reflect.ValueOf(val) | random_line_split |
controller.go | package controller
import (
"errors"
"log"
"net/http"
"reflect"
"strings"
"github.com/zaolab/sunnified/mvc"
"github.com/zaolab/sunnified/mvc/view"
"github.com/zaolab/sunnified/web"
)
var ErrControllerNotFound = errors.New("controller not found")
var ErrUnprepared = errors.New("controller has not been prep'ed... | () 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 | package controller
import (
"errors"
"log"
"net/http"
"reflect"
"strings"
"github.com/zaolab/sunnified/mvc"
"github.com/zaolab/sunnified/mvc/view"
"github.com/zaolab/sunnified/web"
)
var ErrControllerNotFound = errors.New("controller not found")
var ErrUnprepared = errors.New("controller has not been prep'ed... | 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 | package controller
import (
"errors"
"log"
"net/http"
"reflect"
"strings"
"github.com/zaolab/sunnified/mvc"
"github.com/zaolab/sunnified/mvc/view"
"github.com/zaolab/sunnified/web"
)
var ErrControllerNotFound = errors.New("controller not found")
var ErrUnprepared = errors.New("controller has not been prep'ed... |
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 | import configparser
import difflib
import logging
import os
from pathlib import Path
import pytoml as toml
from .validate import validate_config
from .vendorized.readme.rst import render
import io
log = logging.getLogger(__name__)
class ConfigError(ValueError):
pass
metadata_list_fields = {
'classifiers',
... | 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 | import configparser
import difflib
import logging
import os
from pathlib import Path
import pytoml as toml
from .validate import validate_config
from .vendorized.readme.rst import render
import io
log = logging.getLogger(__name__)
class ConfigError(ValueError):
pass
metadata_list_fields = {
'classifiers',
... |
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 | import configparser
import difflib
import logging
import os
from pathlib import Path
import pytoml as toml
from .validate import validate_config
from .vendorized.readme.rst import render
import io
log = logging.getLogger(__name__)
class ConfigError(ValueError):
pass
metadata_list_fields = {
'classifiers',
... |
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 | import configparser
import difflib
import logging
import os
from pathlib import Path
import pytoml as toml
from .validate import validate_config
from .vendorized.readme.rst import render
import io
log = logging.getLogger(__name__)
class ConfigError(ValueError):
pass
metadata_list_fields = {
'classifiers',
... | (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 | package dynmap
import (
"strings"
"log"
"encoding/json"
"errors"
"fmt"
"net/url"
"time"
"reflect"
)
//Dont make this a map type, since we want the option of
//extending this and adding members.
type DynMap struct {
Map map[string]interface{}
}
type DynMaper interface {
ToDynMap() *DynMap
}
// Creates a n... | 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 | package dynmap
import (
"strings"
"log"
"encoding/json"
"errors"
"fmt"
"net/url"
"time"
"reflect"
)
//Dont make this a map type, since we want the option of
//extending this and adding members.
type DynMap struct {
Map map[string]interface{}
}
type DynMaper interface {
ToDynMap() *DynMap
}
// Creates a n... |
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 | package dynmap
import (
"strings"
"log"
"encoding/json"
"errors"
"fmt"
"net/url"
"time"
"reflect"
)
//Dont make this a map type, since we want the option of
//extending this and adding members.
type DynMap struct {
Map map[string]interface{}
}
type DynMaper interface {
ToDynMap() *DynMap
}
// Creates a n... |
// 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 | package dynmap
import (
"strings"
"log"
"encoding/json"
"errors"
"fmt"
"net/url"
"time"
"reflect"
)
//Dont make this a map type, since we want the option of
//extending this and adding members.
type DynMap struct {
Map map[string]interface{}
}
type DynMaper interface {
ToDynMap() *DynMap
}
// Creates a n... | (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 | // Copyright 2017 Joel Scoble
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing... |
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 | // Copyright 2017 Joel Scoble
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing... | (l *lexer) stateFn {
r := l.next()
t := key[string(r)] // don't need to check ok, as the zero value won't match
if t == tokenTab {
l.emit(tokenTab)
}
return lexText
}
// This scans until end of the space sequence is encountered. If no spaces were
// found, nothing will be emitted. The prior token should already... | lexTab | identifier_name |
lex.go | // Copyright 2017 Joel Scoble
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing... |
switch t {
case tokenCR:
return true, classCR
case tokenNL:
return true, classNL
case tokenTab:
return true, classTab
}
if isSpace(t) {
return true, classSpace
}
if isHyphen(t) {
return true, classHyphen
}
// it really shouldn't get to here, but if it does, treat it like classText
return false, cl... | {
return false, classText
} | conditional_block |
lex.go | // Copyright 2017 Joel Scoble
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing... | tokenEmDash: "em dash",
tokenHorizontalBar: "horizontal bar",
tokenSwungDash: "swung dash",
tokenSuperscriptMinus: "superscript minus",
tokenSubScriptMinus: "subscript minus",
tokenTwoEmDash: ... | random_line_split | |
se-spam-helper.user.js | // ==UserScript==
// @name Stack Exchange spam helper
// @description filter for the stack exchange real time question viewer,
// @description aiding in identification and removal of network-wide obvious spam
// @include http://stackexchange.com/questions?tab=realtime
// @version 3.1.6
// ==/Us... | (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 | // ==UserScript==
// @name Stack Exchange spam helper
// @description filter for the stack exchange real time question viewer,
// @description aiding in identification and removal of network-wide obvious spam
// @include http://stackexchange.com/questions?tab=realtime
// @version 3.1.6
// ==/Us... | ontimeout: getPage.bind(null, page),
onerror: function(response) {
console.log(response);
getPage(page); // retry
},
onload: function(response) {
response = JSON.parse(response.responseText);
if(response.error_message) throw respons... | url: "http://api.stackexchange.com/2.2/" + path.join('/') + "?" + $.param(options), | random_line_split |
se-spam-helper.user.js | // ==UserScript==
// @name Stack Exchange spam helper
// @description filter for the stack exchange real time question viewer,
// @description aiding in identification and removal of network-wide obvious spam
// @include http://stackexchange.com/questions?tab=realtime
// @version 3.1.6
// ==/Us... |
if(!response.quota_remaining){
alert ("I'm out of API quota!");
atGMT(10*hours, function(){apiQueueDeferred.resolve();});
}else if(response.backoff){
console.log("got backoff! " + response.backoff);
setTimeout(function(){apiQueueDeferred.r... | {
console.log("collected " + results.length + " results");
responseDeferred.resolve({items: results, partial: !!response.has_more});
} | conditional_block |
se-spam-helper.user.js | // ==UserScript==
// @name Stack Exchange spam helper
// @description filter for the stack exchange real time question viewer,
// @description aiding in identification and removal of network-wide obvious spam
// @include http://stackexchange.com/questions?tab=realtime
// @version 3.1.6
// ==/Us... |
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 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | 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 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (&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 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | } 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 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
}
#[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 | use std::collections::HashSet;
use std::io::{self, Write};
use crate::disk::bam::BamRef;
use crate::disk::block::{BlockDeviceRef, Location, BLOCK_SIZE};
use crate::disk::directory::DirectoryEntry;
use crate::disk::error::DiskError;
/// A "zero" chain link is a link that indicates that this is a tail block, and
/// it... | 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 | use std::collections::HashSet;
use std::io::{self, Write};
use crate::disk::bam::BamRef;
use crate::disk::block::{BlockDeviceRef, Location, BLOCK_SIZE};
use crate::disk::directory::DirectoryEntry;
use crate::disk::error::DiskError;
/// A "zero" chain link is a link that indicates that this is a tail block, and
/// it... | (&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 Drop for ChainWriter {
fn drop(&mut self) {
let _result = self.... | write_current_block | identifier_name |
TTA.py | #!/usr/bin/env python
# _*_coding:utf-8 _*_
# @Time :2021/6/19 15:58
# @Author :Jiawei Lian
# @FileName: defect_detector
# @Software: PyCharm
from copy import deepcopy
import cv2
import ensemble_boxes
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision
from PIL import Image
from torc... | 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 | #!/usr/bin/env python
# _*_coding:utf-8 _*_
# @Time :2021/6/19 15:58
# @Author :Jiawei Lian
# @FileName: defect_detector
# @Software: PyCharm
from copy import deepcopy
import cv2
import ensemble_boxes
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision
from PIL import Image
from torc... |
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 | #!/usr/bin/env python
# _*_coding:utf-8 _*_
# @Time :2021/6/19 15:58
# @Author :Jiawei Lian
# @FileName: defect_detector
# @Software: PyCharm
from copy import deepcopy
import cv2
import ensemble_boxes
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision
from PIL import Image
from torc... |
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 | #!/usr/bin/env python
# _*_coding:utf-8 _*_
# @Time :2021/6/19 15:58
# @Author :Jiawei Lian
# @FileName: defect_detector
# @Software: PyCharm
from copy import deepcopy
import cv2
import ensemble_boxes
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision
from PIL import Image
from torc... | :
""" 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 | package dao
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"go-common/app/job/main/search/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/queue/databus"
)
// AppMultipleDatabus .
type AppMultipleDatabus struct {
d *Dao
appid ... | 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 | package dao
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"go-common/app/job/main/search/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/queue/databus"
)
// AppMultipleDatabus .
type AppMultipleDatabus struct {
d *Dao
appid ... | amd.attrs.Table.TableSplit == "int" || amd.attrs.Table.TableSplit == "single" { // 兼容只传后缀,不传表名
for i := amd.attrs.Table.TableFrom; i <= amd.attrs.Table.TableTo; i++ {
tableName := fmt.Sprintf("%s%0"+amd.attrs.Table.TableZero+"d", amd.attrs.Table.TablePrefix, i)
if err = amd.d.CommitOffset(c, amd.offsets[i], ... |
if | identifier_name |
app_multiple_databus.go | package dao
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"go-common/app/job/main/search/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/queue/databus"
)
// AppMultipleDatabus .
type AppMultipleDatabus struct {
d *Dao
appid ... | t) (err error) {
if amd.d.c.Business.Index {
if amd.attrs.Table.TableSplit == "int" || amd.attrs.Table.TableSplit == "single" { // 兼容只传后缀,不传表名
for i := amd.attrs.Table.TableFrom; i <= amd.attrs.Table.TableTo; i++ {
tableName := fmt.Sprintf("%s%0"+amd.attrs.Table.TableZero+"d", amd.attrs.Table.TablePrefix, i)
... | 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 | package dao
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strings"
"time"
"go-common/app/job/main/search/model"
xsql "go-common/library/database/sql"
"go-common/library/log"
"go-common/library/queue/databus"
)
// AppMultipleDatabus .
type AppMultipleDatabus struct {
d *Dao
appid ... | log.Error("AppMultipleDatabus.Commit error(%v)", err)
continue
}
delete(amd.commits, k)
}
}
amd.mapData = []model.MapData{}
return
}
// Sleep .
func (amd *AppMultipleDatabus) Sleep(c context.Context) {
time.Sleep(time.Second * time.Duration(amd.attrs.Other.Sleep))
}
// Size .
func (amd *AppMultipleDat... | 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 | /*
Copyright 2020 The Crossplane Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// 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 | /*
Copyright 2020 The Crossplane Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// ConvertTransformFormat defines the expected format of an input value of a
// conversion transform.
type ConvertTransformFormat string
// Possible ConvertTransformFormat values.
const (
ConvertTransformFormatNone ConvertTransformFormat = "none"
ConvertTransformFormatQuantity ConvertTransformFormat = "quantit... | {
switch c {
case TransformIOTypeString, TransformIOTypeBool, TransformIOTypeInt, TransformIOTypeInt64, TransformIOTypeFloat64, TransformIOTypeObject, TransformIOTypeArray:
return true
}
return false
} | identifier_body |
zz_generated.composition_transforms.go | /*
Copyright 2020 The Crossplane Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | () 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 | /*
Copyright 2020 The Crossplane Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
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 | #!/usr/bin/env python3
#
# input.py
"""
Input functions (prompt, choice etc.).
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... | 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 | #!/usr/bin/env python3
#
# input.py
"""
Input functions (prompt, choice etc.).
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
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 | #!/usr/bin/env python3
#
# input.py
"""
Input functions (prompt, choice etc.).
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
@overload
def choice(
options: List[str],
text: str = ...,
default: Optional[str] = ...,
prompt_suffix: str = ...,
show_default: bool = ...,
err: bool = ...,
start_index: int = ...
) -> int: ...
@overload
def choice(
options: Mapping[str, str],
text: str = ...,
default: Optional[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 | #!/usr/bin/env python3
#
# input.py
"""
Input functions (prompt, choice etc.).
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... | 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 | package main
import (
"bytes"
"crypto/sha256"
"flag"
"fmt"
"github.com/D4-project/d4-pretensor/pretensorhit"
"golang.org/x/net/proxy"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/D4-project/d4-golang-utils/config"
"github.com/gomodule/re... | (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 | package main
import (
"bytes"
"crypto/sha256"
"flag"
"fmt"
"github.com/D4-project/d4-pretensor/pretensorhit"
"golang.org/x/net/proxy"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/D4-project/d4-golang-utils/config"
"github.com/gomodule/re... | var err error
redisGR, err = redisPretensorPool.Dial()
if err != nil {
logger.Fatal("Could not connect routine to pretensor Redis")
}
graphGR := rg.GraphNew("pretensor", redisGR)
if *debug {
logger.Println("Fetching " + vi.url)
}
// Set some options for our TCP dialer
diale... | if _, ok := binurls[vi.url]; !ok {
//do something here | random_line_split |
main.go | package main
import (
"bytes"
"crypto/sha256"
"flag"
"fmt"
"github.com/D4-project/d4-pretensor/pretensorhit"
"golang.org/x/net/proxy"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/D4-project/d4-golang-utils/config"
"github.com/gomodule/re... |
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 | package main
import (
"bytes"
"crypto/sha256"
"flag"
"fmt"
"github.com/D4-project/d4-pretensor/pretensorhit"
"golang.org/x/net/proxy"
"io"
"log"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/D4-project/d4-golang-utils/config"
"github.com/gomodule/re... |
// 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 | # -*- coding: utf-8 -*-
__author__ = 'Adônis Gasiglia'
import argparse, os, pickle, sys, ConfigParser, math
from PIL import Image, ImageDraw, ImageFont
### AUXILIAR FUNCTIONS ###
def getKey0(item):
return item[0]
def getKey1(item):
return item[1]
def calcPixelLuminance(pixel):
return pixel[0]*0.2126 + ... | else:
conf.output = args.output
if args.lumitable != None:
if os.path.isfile("lumitables/" + args.lumitable) :
v_print(1,"EXITING: Lumitable " + args.lumitable + " not found on /lumitables folder!")
sys.exit(-1)
else:
conf.lumitable = args.lumitable
... | 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 | # -*- coding: utf-8 -*-
__author__ = 'Adônis Gasiglia'
import argparse, os, pickle, sys, ConfigParser, math
from PIL import Image, ImageDraw, ImageFont
### AUXILIAR FUNCTIONS ###
def getKey0(item):
return item[0]
def getKey1(item):
return item[1]
def calcPixelLuminance(pixel):
return pixel[0]*0.2126 + ... |
### 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 | # -*- coding: utf-8 -*-
__author__ = 'Adônis Gasiglia'
import argparse, os, pickle, sys, ConfigParser, math
from PIL import Image, ImageDraw, ImageFont
### AUXILIAR FUNCTIONS ###
def getKey0(item):
return item[0]
def getKey1(item):
return item[1]
def calcPixelLuminance(pixel):
return pixel[0]*0.2126 + ... | 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 | # -*- coding: utf-8 -*-
__author__ = 'Adônis Gasiglia'
import argparse, os, pickle, sys, ConfigParser, math
from PIL import Image, ImageDraw, ImageFont
### AUXILIAR FUNCTIONS ###
def getKey0(item):
return item[0]
def getKey1(item):
return item[1]
def calcPixelLuminance(pixel):
return pixel[0]*0.2126 + ... | 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 | use std::{
collections::HashSet,
fmt,
fs::{File, OpenOptions},
io::{self, prelude::*, BufRead, Cursor},
net::{IpAddr, Ipv4Addr},
process::Command,
};
use failure::Fail;
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{alpha1, alphanumeric1, digit1, hex_digit1, on... | <'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 | use std::{
collections::HashSet,
fmt,
fs::{File, OpenOptions},
io::{self, prelude::*, BufRead, Cursor},
net::{IpAddr, Ipv4Addr},
process::Command,
};
use failure::Fail;
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{alpha1, alphanumeric1, digit1, hex_digit1, on... | #[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 | ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS 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 | ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS 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 | ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS 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 | ##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS 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 | package player
import (
gameevent "fgame/fgame/game/event"
"fgame/fgame/game/global"
"fgame/fgame/game/goldequip/dao"
goldequipeventtypes "fgame/fgame/game/goldequip/event/types"
goldequiptemplate "fgame/fgame/game/goldequip/template"
goldequiptypes "fgame/fgame/game/goldequip/types"
inventorytypes "fgame/fgame... | temId))
if itemTemplate == nil {
continue
}
goldequipTemplate := itemTemplate.GetGoldEquipTemplate()
if goldequipTemplate == nil {
continue
}
if !goldequipTemplate.IsGodCastingEquip() {
continue
}
Loop:
for soulType, info := range obj.ForgeSoulInfo {
forgeSoulTemplate := goldequiptemplate.G... | {
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 | package player
import (
gameevent "fgame/fgame/game/event"
"fgame/fgame/game/global"
"fgame/fgame/game/goldequip/dao"
goldequipeventtypes "fgame/fgame/game/goldequip/event/types"
goldequiptemplate "fgame/fgame/game/goldequip/template"
goldequiptypes "fgame/fgame/game/goldequip/types"
inventorytypes "fgame/fgame... | {
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 | package player
import (
gameevent "fgame/fgame/game/event"
"fgame/fgame/game/global"
"fgame/fgame/game/goldequip/dao"
goldequipeventtypes "fgame/fgame/game/goldequip/event/types"
goldequiptemplate "fgame/fgame/game/goldequip/template"
goldequiptypes "fgame/fgame/game/goldequip/types"
inventorytypes "fgame/fgame... | 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 | package player
import (
gameevent "fgame/fgame/game/event"
"fgame/fgame/game/global"
"fgame/fgame/game/goldequip/dao"
goldequipeventtypes "fgame/fgame/game/goldequip/event/types"
goldequiptemplate "fgame/fgame/game/goldequip/template"
goldequiptypes "fgame/fgame/game/goldequip/types"
inventorytypes "fgame/fgame... | }
Loop:
for soulType, info := range obj.ForgeSoulInfo {
forgeSoulTemplate := goldequiptemplate.GetGoldEquipTemplateService().GetForgeSoulTemplate(obj.GetSlotId(), soulType)
if forgeSoulTemplate == nil {
continue
}
soulLevelTemplate := forgeSoulTemplate.GetLevelTemplate(info.Level)
if soulLevelTemp... | {
continue
| identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.