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 |
|---|---|---|---|---|
kubernetes.go | logging.MustGetLogger(logName),
})
}
// Configure the command line flags needed by the plugin.
func (p *k8sPlugin) Setup(flagSet *pflag.FlagSet) {
flagSet.StringVar(&p.ETCDTLSConfig.CAFile, "kubernetes-etcd-ca-file", "", "CA certificate used by ETCD")
flagSet.StringVar(&p.ETCDTLSConfig.CertFile, "kubernetes-etcd-c... | () (service.PluginUpdate, error) {
if p.client == nil {
return nil, nil
}
// Get nodes
p.log.Debugf("fetching kubernetes nodes")
nodes, nodesErr := p.client.ListNodes(nil)
// Get services
p.log.Debugf("fetching kubernetes services")
services, servicesErr := p.client.ListServices("", nil)
if nodesErr != ni... | Update | identifier_name |
kubernetes.go | logging.MustGetLogger(logName),
})
}
| flagSet.StringVar(&p.ETCDTLSConfig.KeyFile, "kubernetes-etcd-key-file", "", "Private key file used by ETCD")
flagSet.StringVar(&p.KubeletTLSConfig.CAFile, "kubelet-ca-file", "", "CA certificate used by Kubelet")
flagSet.StringVar(&p.KubeletTLSConfig.CertFile, "kubelet-cert-file", "", "Public key file used by Kubelet... | // Configure the command line flags needed by the plugin.
func (p *k8sPlugin) Setup(flagSet *pflag.FlagSet) {
flagSet.StringVar(&p.ETCDTLSConfig.CAFile, "kubernetes-etcd-ca-file", "", "CA certificate used by ETCD")
flagSet.StringVar(&p.ETCDTLSConfig.CertFile, "kubernetes-etcd-cert-file", "", "Public key file used by ... | random_line_split |
kubernetes.go | logging.MustGetLogger(logName),
})
}
// Configure the command line flags needed by the plugin.
func (p *k8sPlugin) Setup(flagSet *pflag.FlagSet) |
// Start the plugin. Send a value on the given channel to trigger an update of the configuration.
func (p *k8sPlugin) Start(config service.ServiceConfig, trigger chan string) error {
if err := util.SetLogLevel(p.LogLevel, config.LogLevel, logName); err != nil {
return maskAny(err)
}
// Setup kubernetes client
p... | {
flagSet.StringVar(&p.ETCDTLSConfig.CAFile, "kubernetes-etcd-ca-file", "", "CA certificate used by ETCD")
flagSet.StringVar(&p.ETCDTLSConfig.CertFile, "kubernetes-etcd-cert-file", "", "Public key file used by ETCD")
flagSet.StringVar(&p.ETCDTLSConfig.KeyFile, "kubernetes-etcd-key-file", "", "Private key file used b... | identifier_body |
tracing.py | ", "open_span_count")
def __init__(self, maxlen):
# type: (int) -> None
self.maxlen = maxlen
self.open_span_count = 0 # type: int
self.finished_spans = [] # type: List[Span]
def start_span(self, span):
# type: (Span) -> None
# This is just so that we don't ru... |
def set_data(self, key, value):
# type: (str, Any) -> None
self._data[key] = value
def set_status(self, value):
# type: (str) -> None
self.set_tag("status", value)
def set_http_status(self, http_status):
# type: (int) -> None
self.set_tag("http.status_code... | self._tags[key] = value | identifier_body |
tracing.py | __enter__(self):
# type: () -> Span
hub = self.hub or sentry_sdk.Hub.current
_, scope = hub._stack[-1]
old_span = scope.span
scope.span = self
self._context_manager_state = (hub, scope, old_span)
return self
def __exit__(self, ty, value, tb):
# type... | params_list = None
paramstyle = None | conditional_block | |
tracing.py | self.prefix = prefix
def __getitem__(self, key):
# type: (str) -> Optional[Any]
return self.environ[self.prefix + key.replace("-", "_").upper()]
def __len__(self):
# type: () -> int
return sum(1 for _ in iter(self))
def __iter__(self):
# type: () -> Generat... | ):
# type: (...) -> None
self.environ = environ | random_line_split | |
tracing.py | ", "open_span_count")
def __init__(self, maxlen):
# type: (int) -> None
self.maxlen = maxlen
self.open_span_count = 0 # type: int
self.finished_spans = [] # type: List[Span]
def start_span(self, span):
# type: (Span) -> None
# This is just so that we don't ru... | (self):
# type: () -> Span
hub = self.hub or sentry_sdk.Hub.current
_, scope = hub._stack[-1]
old_span = scope.span
scope.span = self
self._context_manager_state = (hub, scope, old_span)
return self
def __exit__(self, ty, value, tb):
# type: (Optiona... | __enter__ | identifier_name |
main.rs | _json::from_str(&session.key_material.as_str()).unwrap();
let pk_string : &String = &key_material[0];
let plaintext: &Vec<u8> = &d.plaintext.as_bytes().to_vec();
let pk : bsw::CpAbePublicKey = serde_json::from_str(pk_string.as_str()).unwrap(); // TODO NotNice: need to convert to scheme-specific type here. S... | (d:Json<User>) -> Result<(), BadRequest<String>> {
let ref username: String = d.username;
let ref passwd: String = d.password;
let ref random_session_id = d.random_session_id;
let salt: i32 = 1234; // TODO use random salt when storing hashed user passwords
println!("Adding user {} {} {} {}", &use... | add_user | identifier_name |
main.rs | _json::from_str(&session.key_material.as_str()).unwrap();
let pk_string : &String = &key_material[0];
let plaintext: &Vec<u8> = &d.plaintext.as_bytes().to_vec();
let pk : bsw::CpAbePublicKey = serde_json::from_str(pk_string.as_str()).unwrap(); // TODO NotNice: need to convert to scheme-specific type here. S... | Ok(_usize) | {
use schema::sessions;
println!("Got scheme {}", scheme);
match scheme.parse::<SCHEMES>() {
Ok(_scheme) => {
let session_id: String = OsRng::new().unwrap().next_u64().to_string();
let session = schema::NewSession {
is_initialized: false,
scheme: scheme.to_string(),
random_session_id: session_id.... | identifier_body |
main.rs | }
// -----------------------------------------------------
// Message formats follow
// -----------------------------------------------------
#[derive(Serialize, Deserialize)]
struct Message {
contents: String
}
#[derive(Serialize, Deserialize)]
struct SetupMsg {
scheme: String,
attributes: Vec<S... | return Outcome::Failure((Status::Unauthorized, ()));
}
return Outcome::Success(ApiKey(key.to_string()));
} | random_line_split | |
network_listener.py | addr))
class NetworkFileListener(object):
def __init__(self, interface=None, mime_types=None):
self.pc = None
self.on_file_complete = None
self.packet_streams = {}
self.local_ips = self.detect_local_ips()
logging.info("Local IP Addresses: %s" % ', '.join(self.local_ips)... |
def iter_packets(iterable):
"""Sorts an iterable of packets and removes the duplicates"""
prev = None
for i in sorted(iterable, key=attrgetter('seq')):
if prev is None or prev.seq != i.seq:
prev = i
yield i
def hash_packet(eth, outbound=False):
"""Hashes a packet to... | self.on_file_complete(f) | conditional_block |
network_listener.py | ), addr))
class NetworkFileListener(object):
def __init__(self, interface=None, mime_types=None):
self.pc = None
self.on_file_complete = None
self.packet_streams = {}
self.local_ips = self.detect_local_ips()
logging.info("Local IP Addresses: %s" % ', '.join(self.local_ip... |
class RawFile(object):
def __init__(self, content, mime_type):
self.content = content
self.mime_type = mime_type
class TcpStream(object):
def __init__(self, id):
self.id = id
self.buffer = {}
self.packets = None
self.base_seq = None
self.next_seq ... | result = []
for flag, name in ((ACK, 'ACK'), (SYN, 'SYN'), (PUSH, 'PUSH'), (RST, 'RST')):
if flags & flag:
result.append(name)
return result | identifier_body |
network_listener.py | ), addr))
class NetworkFileListener(object):
def __init__(self, interface=None, mime_types=None):
self.pc = None
self.on_file_complete = None
self.packet_streams = {}
self.local_ips = self.detect_local_ips()
logging.info("Local IP Addresses: %s" % ', '.join(self.local_ip... | (self, stream):
if stream.id in self.packet_streams:
del self.packet_streams[stream.id]
def _handle_response(self, stream, tcp_pkt):
had_headers = (stream.headers is not None)
stream.add_packet(tcp_pkt)
if not had_headers and stream.headers is not None:
# t... | _delete_stream | identifier_name |
network_listener.py | ), addr))
class NetworkFileListener(object):
def __init__(self, interface=None, mime_types=None):
self.pc = None
self.on_file_complete = None
self.packet_streams = {}
self.local_ips = self.detect_local_ips()
logging.info("Local IP Addresses: %s" % ', '.join(self.local_ip... |
@property
def content(self):
return self.packets
@property
def progress(self):
if self.http_content_length is None:
return 0
if self.http_content_length in (0, self.http_bytes_loaded):
return 1
return float(self.http_bytes_loaded) / float(self.... |
def rel_seq(self, packet):
return packet.seq - self.base_seq | random_line_split |
wpa_controller.go | agent/custommetrics"
"github.com/DataDog/datadog-agent/pkg/errors"
"github.com/DataDog/datadog-agent/pkg/util/kubernetes/autoscalers"
"github.com/DataDog/datadog-agent/pkg/util/log"
)
const (
crdCheckInitialInterval = time.Second * 5
crdCheckMaxInterval = 5 * time.Minute
crdCheckMultiplier = 2.0
crdChe... | () bool {
h.mu.Lock()
defer h.mu.Unlock()
return h.wpaEnabled
}
func (h *AutoscalersController) workerWPA() {
for h.processNextWPA() {
}
}
func (h *AutoscalersController) processNextWPA() bool {
key, quit := h.WPAqueue.Get()
if quit {
log.Error("WPA controller HPAqueue is shutting down, stopping processing")... | isWPAEnabled | identifier_name |
wpa_controller.go | /custommetrics"
"github.com/DataDog/datadog-agent/pkg/errors"
"github.com/DataDog/datadog-agent/pkg/util/kubernetes/autoscalers"
"github.com/DataDog/datadog-agent/pkg/util/log"
)
const (
crdCheckInitialInterval = time.Second * 5
crdCheckMaxInterval = 5 * time.Minute
crdCheckMultiplier = 2.0
crdCheckMax... |
// enableWPA adds the handlers to the AutoscalersController to support WPAs
func (h *AutoscalersController) enableWPA(wpaInformerFactory dynamic_informer.DynamicSharedInformerFactory) error {
log.Info("Enabling WPA controller")
genericInformer := wpaInformerFactory.ForResource(gvrWPA)
h.WPAqueue = workqueue.NewN... | {
exp := &backoff.ExponentialBackOff{
InitialInterval: crdCheckInitialInterval,
RandomizationFactor: 0,
Multiplier: crdCheckMultiplier,
MaxInterval: crdCheckMaxInterval,
MaxElapsedTime: crdCheckMaxElapsedTime,
Clock: backoff.SystemClock,
}
exp.Reset()
_ = backoff.... | identifier_body |
wpa_controller.go | agent/custommetrics"
"github.com/DataDog/datadog-agent/pkg/errors"
"github.com/DataDog/datadog-agent/pkg/util/kubernetes/autoscalers"
"github.com/DataDog/datadog-agent/pkg/util/log"
)
const (
crdCheckInitialInterval = time.Second * 5
crdCheckMaxInterval = 5 * time.Minute
crdCheckMultiplier = 2.0
crdChe... | details.Kind == "watermarkpodautoscalers"
}
func checkWPACRD(wpaClient dynamic_client.Interface) backoff.Operation {
check := func() error {
_, err := wpaClient.Resource(gvrWPA).List(context.TODO(), v1.ListOptions{})
return err
}
return func() error {
return tryCheckWPACRD(check)
}
}
func waitForWPACRD(wp... | details := status.Status().Details
return reason == v1.StatusReasonNotFound &&
details.Group == apis_v1alpha1.SchemeGroupVersion.Group && | random_line_split |
wpa_controller.go | cases return a permanent error to prevent from retrying
log.Errorf("WPA CRD check failed: not retryable: %s", err)
return backoff.Permanent(err)
}
log.Info("WPA CRD check successful")
return nil
}
func notifyCheckWPACRD() backoff.Notify {
attempt := 0
return func(err error, delay time.Duration) {
attempt++... | {
log.Errorf("Could not get object from tombstone %#v", obj)
return
} | conditional_block | |
splash.go | }
//GenerateSplashURL Generates Splash URL and return error
func (s *splashConn) GenerateSplashURL(req Request) string {
/*
//"Set-Cookie" from response headers should be sent when accessing for the same domain second time
cookie := `PHPSESSID=ef75e2737a14b06a2749d0b73840354f; path=/; domain=.acer-a500.ru; ... | host: host,
timeout: timeout,
resourceTimeout: resourceTimeout,
wait: wait,
} | random_line_split | |
splash.go | 73840354f; path=/; domain=.acer-a500.ru; HttpOnly
dle_user_id=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=.acer-a500.ru; httponly
dle_password=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=.acer-a500.ru; httponly
dle_hash=deleted; expires=Thu, 01-Jan... | () (io.ReadCloser, error) {
if r == nil {
return nil, errors.New("empty response")
}
if isRobotsTxt(r.Request.URL) {
decoded, err := base64.StdEncoding.DecodeString(r.Response.Content.Text)
if err != nil {
logger.Println("decode error:", err)
return nil, err
}
readCloser := ioutil.NopCloser(bytes.N... | GetContent | identifier_name |
splash.go | 73840354f; path=/; domain=.acer-a500.ru; HttpOnly
dle_user_id=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=.acer-a500.ru; httponly
dle_password=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=.acer-a500.ru; httponly
dle_hash=deleted; expires=Thu, 01-Jan... | else {
LUAScript = baseLUA
}
splashURL := fmt.Sprintf(
"http://%s/execute?url=%s&timeout=%d&resource_timeout=%d&wait=%.1f&cookies=%s&formdata=%s&lua_source=%s",
s.host,
neturl.QueryEscape(req.URL),
s.timeout,
s.resourceTimeout,
s.wait,
neturl.QueryEscape(req.Cookies),
neturl.QueryEscape(paramsToLua... | {
LUAScript = robotsLUA
} | conditional_block |
splash.go | 73840354f; path=/; domain=.acer-a500.ru; HttpOnly
dle_user_id=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=.acer-a500.ru; httponly
dle_password=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/; domain=.acer-a500.ru; httponly
dle_hash=deleted; expires=Thu, 01-Jan... | // CacheIsPrivate: false,
RespDirectives: resDir,
RespHeaders: respHeader,
RespStatusCode: r.Response.Status,
RespExpiresHeader: expiresHeader,
RespDateHeader: dateHeader,
RespLastModifiedHeader: lastModifiedHeader,
ReqDirectives: reqDir,
ReqHeaders: ... | {
respHeader := r.Response.Headers.(http.Header)
reqHeader := r.Request.Headers.(http.Header)
// respHeader := r.Response.castHeaders()
// reqHeader := r.Request.castHeaders()
reqDir, err := cacheobject.ParseRequestCacheControl(reqHeader.Get("Cache-Control"))
if err != nil {
logger.Printf(err.Error())
}
res... | identifier_body |
main.go | /%d", owner, repo, prnum)
message := "Your changes (commit: " + state.CurrentSha1 + ") have been pushed to the Couchbase Review Site:\n"
message += "http://review.couchbase.org/" + strconv.FormatInt(int64(changeNum), 10)
if state.NumOfCommits > 1 {
message += "\n\n"
message += "Note: As your pull request conta... | {
return err
} | conditional_block | |
main.go |
type subError struct {
msg string
err error
}
func (e subError) Error() string {
if e.err != nil {
return e.msg + ": " + e.err.Error()
} else {
return e.msg
}
}
func makeErr(msg string, err error) error {
return subError{msg, err}
}
func SquashHead(repo *git.Repository, squashCount int, mergeCommitTitle,... | {
b := make([]byte, sha1.Size)
rand.Read(b)
encData := sha1.Sum(b)
return "I" + hex.EncodeToString(encData[:])
} | identifier_body | |
main.go | Type) (*git.Cred, error) {
creds, err := git.NewCredSshKey(gerritUser, gerritPublicKey, gerritPrivateKey, "")
return creds, err
}
func initGerritClient() error {
client, err := gerrit.NewClient("https://"+gerritHost+"/", nil)
if err != nil {
return makeErr("failed to create gerrit client", err)
}
client.Authe... | _, _, err := githubClient.PullRequests.Edit(context.Background(), owner, repo, prnum, &github.PullRequest{
State: &newState,
})
if err != nil {
return makeErr("failed to close pull request", err)
}
return SendPrStateComment(owner, repo, prnum, message, state, is_first)
}
func SendPrStateComment(owner, repo s... | newState := "closed" | random_line_split |
main.go | ) (*git.Cred, error) {
creds, err := git.NewCredSshKey(gerritUser, gerritPublicKey, gerritPrivateKey, "")
return creds, err
}
func initGerritClient() error {
client, err := gerrit.NewClient("https://"+gerritHost+"/", nil)
if err != nil {
return makeErr("failed to create gerrit client", err)
}
client.Authentic... | (user *github.User) bool {
if user == nil || user.Login == nil {
return false
}
for i := 0; i < len(botOwners); i++ {
if *user.Login == botOwners[i] {
return true
}
}
return IsGitHubUserBot(user)
}
const (
BOTSTATE_NEW = ""
BOTSTATE_NO_CLA = "no_cla"
BOTSTATE_CREATED = "created"
BOTSTATE_... | IsGitHubUserBotOwner | identifier_name |
tvlist.js |
/**
* type filter for file listing
* @type Number
*/
this.filterType = MEDIA_TYPE_NONE;
/**
* data filter for file listing
* @type String
*/
this.filterText = '';
/**
* hierarchy change flag: no change
* @type {number}
*/
this.LEVEL_CHANGE_NONE = 0;
/**
* hierarchy change flag: go level u... | // parent constructor
CScrollList.call(this, parent);
/**
* link to the object for limited scopes
* @type {TVList}
*/
var self = this;
/**
* link to the BreadCrumb component
* @type {CBreadCrumb}
*/
this.bcrumb = null;
/**
* link to the BreadCrumb component
* @type {CSearchBar}
*/
this.sbar... | identifier_body | |
tvlist.js | ITES_NEW[(data.data[i].sol? data.data[i].sol + ' ' : '') + data.data[i].url] ? true : false});
if(item){
j++;
}
}
}
self.parent.domInfoTitle.innerHTML = self.data[0].name?self.data[0].name:'';
} else {
this.parent.BPanel.Hidden(this.parent.BPanel.btnF1, true);
this.parent.BPanel.Hidden... |
/**
* Setter for linked component
* @param {CBase} component associated object
*/
TVList.prototype.SetBreadCrumb = function ( component ) {
this.bcrumb = component;
};
/**
* Setter for linked component
* @param {CBase} component associated object
*/
TVList.prototype.SetSearchBar = function ( component ) {
t... | TVList.prototype = Object.create(CScrollList.prototype);
TVList.prototype.constructor = TVList; | random_line_split |
tvlist.js | arent) {
// parent constructor
CScrollList.call(this, parent);
/**
* link to the object for limited scopes
* @type {TVList}
*/
var self = this;
/**
* link to the BreadCrumb component
* @type {CBreadCrumb}
*/
this.bcrumb = null;
/**
* link to the BreadCrumb component
* @type {CSearchBar}
*/
... | List(p | identifier_name | |
tvlist.js | ITES_NEW[(data.data[i].sol? data.data[i].sol + ' ' : '') + data.data[i].url] ? true : false});
if(item){
j++;
}
}
}
self.parent.domInfoTitle.innerHTML = self.data[0].name?self.data[0].name:'';
} else {
this.parent.BPanel.Hidden(this.parent.BPanel.btnF1, true);
this.parent.BPanel.Hidden... | self.parent.clearEPG();
this.timer.OnFocusPlay = setTimeout(function () {
if ( item.data.type === MEDIA_TYPE_BACK ){
if(self.filterText){
self.parent.domInfoTitle.innerHTML = _('Contains the list of items corresponding to the given filter request');
} else {
self.parent.domInfoTitle.innerHTML = self.pa... | this.parent.BPanel.Hidden(this.parent.BPanel.btnF3add, true);
this.parent.BPanel.Hidden(this.parent.BPanel.btnF3del, true);
}
| conditional_block |
server.rs | /// Extensions the server supports.
extensions: Vec<Box<dyn Extension + Send>>,
/// Encoding/decoding buffer.
buffer: BytesMut,
}
impl<'a, T: AsyncRead + AsyncWrite + Unpin> Server<'a, T> {
/// Create a new server handshake.
pub fn new(socket: T) -> Self {
Server { socket, protocols: Vec::new(), extensions: Vec... | let mut header_buf = [httparse::EMPTY_HEADER; MAX_NUM_HEADERS];
let mut request = httparse::Request::new(&mut header_buf);
match request.parse(self.buffer.as_ref()) {
Ok(httparse::Status::Complete(_)) => (),
Ok(httparse::Status::Partial) => return Err(Error::IncompleteHttpRequest),
Err(e) => return Err(... | self.socket
}
// Decode client handshake request.
fn decode_request(&mut self) -> Result<ClientRequest, Error> { | random_line_split |
server.rs | /// Extensions the server supports.
extensions: Vec<Box<dyn Extension + Send>>,
/// Encoding/decoding buffer.
buffer: BytesMut,
}
impl<'a, T: AsyncRead + AsyncWrite + Unpin> Server<'a, T> {
/// Create a new server handshake.
pub fn new(socket: T) -> Self {
Server { socket, protocols: Vec::new(), extensions: Vec... |
}
let path = request.path.unwrap_or("/");
Ok(ClientRequest { ws_key, protocols, path, headers })
}
// Encode server handshake response.
fn encode_response(&mut self, response: &Response<'_>) {
match response {
Response::Accept { key, protocol } => {
let accept_value = super::generate_accept_key(&k... | {
protocols.push(p)
} | conditional_block |
server.rs | /// Extensions the server supports.
extensions: Vec<Box<dyn Extension + Send>>,
/// Encoding/decoding buffer.
buffer: BytesMut,
}
impl<'a, T: AsyncRead + AsyncWrite + Unpin> Server<'a, T> {
/// Create a new server handshake.
pub fn new(socket: T) -> Self {
Server { socket, protocols: Vec::new(), extensions: Vec... |
/// Await an incoming client handshake request.
pub async fn receive_request(&mut self) -> Result<ClientRequest<'_>, Error> {
self.buffer.clear();
let mut skip = 0;
loop {
crate::read(&mut self.socket, &mut self.buffer, BLOCK_SIZE).await?;
let limit = std::cmp::min(self.buffer.len(), MAX_HEADERS_SIZE... | {
self.extensions.drain(..)
} | identifier_body |
server.rs | <'a, T> {
socket: T,
/// Protocols the server supports.
protocols: Vec<&'a str>,
/// Extensions the server supports.
extensions: Vec<Box<dyn Extension + Send>>,
/// Encoding/decoding buffer.
buffer: BytesMut,
}
impl<'a, T: AsyncRead + AsyncWrite + Unpin> Server<'a, T> {
/// Create a new server handshake.
pub ... | Server | identifier_name | |
utils.py | dT%H:%M:%SZ")
date_int_str = datetime.datetime.combine(datetime.date.today() - datetime.timedelta(days=1),
datetime.time.min).strftime("%Y%m%d")
return dt1, dt2, date_int_str
def gen_temp_times(start, end):
"""
需要补充数据的特殊情况
end 是先对当前已经过去的时间
:param s... | # ('2019-07-18T00:00:00Z', '2019-07-19T00:00:00Z', '20190718') | random_line_split | |
utils.py | )
# 将该文件夹下的所有文件名存入一个列表
file_list = os.listdir()
# 读取第一个CSV文件并包含表头
df = pd.read_csv(os.path.join(folder_path, file_list[0]))
# 创建要保存的文件夹
os.makedirs(savefile_path, exist_ok=True)
# 将读取的第一个CSV文件写入合并后的文件保存
save_file = os.path.join(savefile_path, savefile_name)
df.to_csv(save_file)
... | dt1 = datetime.datetime.combine(datetime.date.today() - datetime.timedelta(days=1),
datetime.time.min).strftime("%Y-%m-%dT%H:%M:%SZ")
dt2 = datetime.datetime.combine(datetime.date.today(),
datetime.time.min).strftime("%Y-%m-%dT%H:%M:%SZ")
... | autocommit=True,
local_infile=1)
print('Connected to DB: {}'.format(host))
# Create cursor and execute Load SQL
cursor = con.cursor()
cursor.execute(load_sql)
print('Succuessfully loaded the table from csv.')
con.... | identifier_body |
utils.py | )
# 将该文件夹下的所有文件名存入一个列表
file_list = os.listdir()
# 读取第一个CSV文件并包含表头
df = pd.read_csv(os.path.join(folder_path, file_list[0]))
# 创建要保存的文件夹
os.makedirs(savefile_path, exist_ok=True)
# 将读取的第一个CSV文件写入合并后的文件保存
save_file = os.path.join(savefile_path, savefile_name)
df.to_csv(save_file)
... | # "volume": 0,
# # "amount": 0
# # }
# # 现将 dt1 和 dt2 进行转换
# ret = coll.find({"time": {"$gte": dt1, "$lte": dt2}}).count_documents
# return ret
def gene(dt1, dt2, date_int_str):
"""整个生成逻辑"""
logger.info(f"dt1:{dt1}")
logger.info(f"dt2:{dt2}")
mysqlhost = MYSQLHOST
... | atetime.timedelta(days=1)
# def gen_mongo_count(dt1, dt2):
# """
# 计算在dt1 和 dt2之间的增量数量 理论上是一天的增量
# :param dt1:
# :param dt2:
# :return:
# """
# # {
# # "_id": ObjectId("59ce1e1d6e6dc7768c7140dc"),
# # "code": "SH900955",
# # "time": ISODate("1999-07-26T09:59:00Z"),
... | conditional_block |
utils.py | savefile_name:
:return:
"""
# 修改当前工作目录
os.chdir(folder_path)
# 将该文件夹下的所有文件名存入一个列表
file_list = os.listdir()
# 读取第一个CSV文件并包含表头
df = pd.read_csv(os.path.join(folder_path, file_list[0]))
# 创建要保存的文件夹
os.makedirs(savefile_path, exist_ok=True)
# 将读取的第一个CSV文件写入合并后的文件保存
save_fi... | :param | identifier_name | |
vga_buffer.rs | (u8)] // makes each enum variant be stored as a u8
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9, | LightRed = 12,
Pink = 13,
Yellow = 14,
White = 15,
}
// used to represent a full VGA color code (foreground & background)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ColorCode(u8); // creates a type which is essentially an alias for a single byte
impl ColorCode {
// creates a single ... | LightGreen = 10,
LightCyan = 11, | random_line_split |
vga_buffer.rs | 15,
}
// used to represent a full VGA color code (foreground & background)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ColorCode(u8); // creates a type which is essentially an alias for a single byte
impl ColorCode {
// creates a single byte detailing the fore and background colors (based on VGA sp... | { // ensures empty lines are shifted in on a new line and have correct color code
assert_eq!(screen_char.ascii_character, b' ');
assert_eq!(screen_char.color_code, writer.color_code);
} | conditional_block | |
vga_buffer.rs | (u8)] // makes each enum variant be stored as a u8
pub enum | {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
Pink = 13,
Yellow = 14,
White = 15,
}
// used to represent a full VGA color code (for... | Color | identifier_name |
vga_buffer.rs | 8)] // makes each enum variant be stored as a u8
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
Pink = 13,
Yellow = 14,... |
}
// Provides a static Writer object which utilizes non-const functions
// Requires locking to provide interior mutability: since it utilizes &mut self for writing
// it requires mutability, but its mutibility is not provided to users, therefore it is interior
// mutability. The Mutex allows safe usage internally.
la... | {
self.write_string(s);
Ok(())
} | identifier_body |
059_Implementacion_plazos.py | 1]]
plazos.pop(i - 1 - jresta)
jresta += 1
# ================== #
# === Script 051 === #
# ================== #
# === #
# Canvi respecte script 051!!
listRefs = deepcopy(plazos)
listRefs = pd.DataFrame(listRefs)
listRefs.columns = ["PosInicio", "PosFin"]
listRefs["Referencia"]... | esult[val] = dict(descripcion = frasesGrup[0])
result[val]["posiciones"] = dict(inicio = list(aux_data["PosInicio"]), fin = list(aux_data["PosFin"]))
result[val]["referencias"] = list(aux_data["Ref_Orig"])
| conditional_block | |
059_Implementacion_plazos.py | la comunidad", "sancion"],
finales = ['\\bmes\\b', '\\bmeses\\b', '\\bdia\\b', '\\bdias\\b', '\\bano\\b', '\\banos\\b', '\\bsemana']
)
],
bra = [
dict(contiene = ['\\bmes\\b', '\\bmeses\\b', '\\bdia\\b', '\\bdias\\b', '\\bano\\b', '\\banos\\b', '\\bsemana'],
# inicios = ['[0-9]+', "\\buno... | # Buscamos posiciones teniendo en cuenta lo maximo para atras
index_points_max_enrere = []
for dictstr2search in SearchMaxEnrere:
idxAct = []
for str2search in dictstr2search['contiene']:
idxAct.extend(buscaPosicionRegexTexto(str2search, readedFile))
index_points_max_enrere.append(idxAct)
... | random_line_split | |
ConcurrentAnimations.py | range(len(self._ledcopies))] # [[]] * 5 NOT define 5 different lists!
self._led.pixheights = [0] * self._led.numLEDs
# def preRun(self, amt=1):
# self._led.all_off()
# for w, f in self._animcopies:
# w.run(fps=f, max_steps=runtime * f, threaded = True)
def preStep(self, amt... | (self, amt = 1, fps=None, sleep=None, max_steps = 0, untilComplete = False, max_cycles = 0, joinThread = False, callback=None):
#def run(self, amt = 1, fps=None, sleep=None, max_steps = 0, untilComplete = False, max_cycles = 0, threaded = True, joinThread = False, callback=None):
# self.fps = fps
# ... | run | identifier_name |
ConcurrentAnimations.py | self._animcopies = animcopies
self._ledcopies = [a._led for a, f in animcopies]
self._idlelist = []
self.timedata = [[] for _ in range(len(self._ledcopies))] # [[]] * 5 NOT define 5 different lists!
self._led.pixheights = [0] * self._led.numLEDs
# def preRun(self, amt=1):
# ... | """
def __init__(self, led, animcopies, start=0, end=-1):
super(MasterAnimation, self).__init__(led, start, end)
if not isinstance(animcopies, list):
animcopies = [animcopies] | random_line_split | |
ConcurrentAnimations.py | range(len(self._ledcopies))] # [[]] * 5 NOT define 5 different lists!
self._led.pixheights = [0] * self._led.numLEDs
# def preRun(self, amt=1):
# self._led.all_off()
# for w, f in self._animcopies:
# w.run(fps=f, max_steps=runtime * f, threaded = True)
def preStep(self, amt... |
#
def postStep(self, amt=1):
# clear the ones found in preStep
activewormind = [i for i, x in enumerate(self._idlelist) if x == False]
[self._ledcopies[i].driver[0]._updatenow.clear() for i in activewormind]
def step(self, amt=1):
"""
combines the buffers from ... | self.animComplete = True
print 'breaking out'
break | conditional_block |
ConcurrentAnimations.py | range(len(self._ledcopies))] # [[]] * 5 NOT define 5 different lists!
self._led.pixheights = [0] * self._led.numLEDs
# def preRun(self, amt=1):
# self._led.all_off()
# for w, f in self._animcopies:
# w.run(fps=f, max_steps=runtime * f, threaded = True)
def preStep(self, amt... |
def pathgen(nleft=0, nright=15, nbot=0, ntop=9, shift=0, turns=10, rounds=16):
"""
A path around a rectangle from strip wound helically
10 turns high by 16 round.
rounds * turns must be number of pixels on strip
nleft and nright is from 0 to rounds-1,
nbot and ntop from 0 to turns-1
"""
... | if self._activecount == 0:
self._headposition += amt*self._direction
self._headposition %= len(self._path)
# Put worm into strip and blank end
segpos = self._headposition
for x in range(len(self._colors)):
if True: #self._height[x] >= LEDseghe... | identifier_body |
resource_ldap_object_attributes.go | unique among siblings) and its parent's DN. The referenced object should exist to be able to add attributes.",
Required: true,
ForceNew: true,
},
"attributes": {
Type: schema.TypeSet,
Description: "The map of attributes to add to the referenced object; each attribute can be multi-valu... |
} else {
warnLog("ldap_object_attributes::update - didn't actually make changes to %q because there were no changes requested", dn)
}
return resourceLDAPObjectAttributesRead(d, meta)
}
func resourceLDAPObjectAttributesDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*ldap.Conn)
dn := d.... | {
errorLog("ldap_object_attributes::update - error modifying LDAP object %q with values %v", d.Id(), err)
return err
} | conditional_block |
resource_ldap_object_attributes.go | (unique among siblings) and its parent's DN. The referenced object should exist to be able to add attributes.",
Required: true,
ForceNew: true,
},
"attributes": {
Type: schema.TypeSet,
Description: "The map of attributes to add to the referenced object; each attribute can be multi-va... | debugLog("ldap_object_attributes::read - intersection with ldap of %q => %v", dn, set.List())
// If the set is empty the attributes do not exist, yet.
if set.Len() == 0 {
d.SetId("")
return nil
}
// The set contains values, let's set them and indicate that the object
// exists by setting the id as well.
if... | set := unionSet.Intersection(ldapSet) | random_line_split |
resource_ldap_object_attributes.go | MinItems: 0,
Elem: &schema.Schema{
Type: schema.TypeMap,
Description: "The list of values for a given attribute.",
MinItems: 1,
MaxItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
Description: "The individual value for the given attribute.",
... | {
return &schema.Resource{
Create: resourceLDAPObjectAttributesCreate,
Read: resourceLDAPObjectAttributesRead,
Update: resourceLDAPObjectAttributesUpdate,
Delete: resourceLDAPObjectAttributesDelete,
Description: "The `ldap_object_attributes`-resource owns only specific attributes of an object. In case of ... | identifier_body | |
resource_ldap_object_attributes.go | (unique among siblings) and its parent's DN. The referenced object should exist to be able to add attributes.",
Required: true,
ForceNew: true,
},
"attributes": {
Type: schema.TypeSet,
Description: "The map of attributes to add to the referenced object; each attribute can be multi-va... | (d *schema.ResourceData, meta interface{}) error {
client := meta.(*ldap.Conn)
dn := d.Get("dn").(string)
debugLog("ldap_object_attributes::create - adding attributes to object %q", dn)
request := ldap.NewModifyRequest(dn, []ldap.Control{})
// if there is a non empty list of attributes, loop though it and
// c... | resourceLDAPObjectAttributesCreate | identifier_name |
mod.rs |
}
impl fmt::Debug for Resolve {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "graph: {:?}\n", self.graph));
try!(write!(fmt, "\nfeatures: {{\n"));
for (pkg, features) in &self.features {
try!(write!(fmt, " {}: {:?}\n", pkg, features));
}
... | {
self.features.get(pkg)
} | identifier_body | |
mod.rs |
// following requirements:
//
// 1. The version matches the dependency requirement listed for this
// package
// 2. There are no activated versions for this package which are
// semver-compatible, or there's an activated version which is
// precisely equal to `candidate`.
//
... | {
for key in s.features().keys() {
try!(add_feature(s, key, &mut deps, &mut used, &mut visited));
}
for dep in s.dependencies().iter().filter(|d| d.is_optional()) {
try!(add_feature(s, dep.name(), &mut deps, &mut used,
... | conditional_block | |
mod.rs | (&self) -> Nodes<PackageId> {
self.graph.iter()
}
pub fn root(&self) -> &PackageId { &self.root }
pub fn deps(&self, pkg: &PackageId) -> Option<Edges<PackageId>> {
self.graph.edges(pkg)
}
pub fn query(&self, spec: &str) -> CargoResult<&PackageId> {
let spec = try!(PackageI... | iter | identifier_name | |
mod.rs | if {} is already activated", summary.package_id());
let (features, use_default) = match *method {
Method::Required { features, uses_default_features, .. } => {
(features, uses_default_features)
}
Method::Everything => return false,
};
let has_default_feature = summary.f... | // Next, sanitize all requested features by whitelisting all the requested
// features that correspond to optional dependencies
for dep in deps {
// weed out optional dependencies, but not those required
if dep.is_optional() && !feature_deps.contains_key(dep.name()) { | random_line_split | |
new_IDRQN_main.py | = 0.1
# --------------Simulation initialization
sys_tracker = system_tracker()
sys_tracker.initialize(config, distance, travel_time, arrival_rate, int(taxi_input), N_station, num_episodes, max_epLength)
env = te.taxi_simulator(arrival_rate, OD_mat, distance, travel_time, taxi_input)
env.reset()
print('System Successf... | bufferArray=np.array(global_epi_buffer)
exp_replay.add(bufferArray[it:it+trace_length]) | conditional_block | |
new_IDRQN_main.py | from system_tracker import system_tracker
import bandit
from tensorflow.python.client import timeline
np.set_printoptions(precision=2)
if use_gpu == 0:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
# force on gpu
config1 = tf.ConfigProto()
config1.gpu_options.allow_growth = True
reward_out = open('log/IDRQN_reward_... | import DRQN_agent | random_line_split | |
update.rs | Access, Visitor};
use serde::ser::{Error as SerializeError, SerializeMap};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sstable::{SSIterator, Table, TableBuilder, TableIterator};
use tempfile::NamedTempFile;
/// Describes a single update on the graph.
#[derive(Serialize, Deserialize, Clone, Debug... | else {
(0, None)
}
}
}
impl Serialize for GraphUpdate {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let iter = self.iter().map_err(S::Error::custom)?;
let number_of_updates = self.len().map_err(S::Erro... | {
(s, Some(s))
} | conditional_block |
update.rs | Access, Visitor};
use serde::ser::{Error as SerializeError, SerializeMap};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sstable::{SSIterator, Table, TableBuilder, TableIterator};
use tempfile::NamedTempFile;
/// Describes a single update on the graph.
#[derive(Serialize, Deserialize, Clone, Debug... | if let Ok(s) = self.size_hint.try_into() {
(s, Some(s))
} else {
(0, None)
}
}
}
impl Serialize for GraphUpdate {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let iter = self.iter().m... | fn size_hint(&self) -> (usize, Option<usize>) { | random_line_split |
update.rs | Access, Visitor};
use serde::ser::{Error as SerializeError, SerializeMap};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sstable::{SSIterator, Table, TableBuilder, TableIterator};
use tempfile::NamedTempFile;
/// Describes a single update on the graph.
#[derive(Serialize, Deserialize, Clone, Debug... | {
InProgress {
table_builder: Box<TableBuilder<File>>,
outfile: NamedTempFile,
},
Finished {
table: Table,
},
}
/// A list of changes to apply to an graph.
pub struct GraphUpdate {
changesets: Mutex<Vec<ChangeSet>>,
event_counter: u64,
serialization: bincode::config... | ChangeSet | identifier_name |
update.rs | Access, Visitor};
use serde::ser::{Error as SerializeError, SerializeMap};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use sstable::{SSIterator, Table, TableBuilder, TableIterator};
use tempfile::NamedTempFile;
/// Describes a single update on the graph.
#[derive(Serialize, Deserialize, Clone, Debug... | }
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
if let Ok(s) = self.size_hint.try_into() {
(s, Some(s))
} else {
(0, None)
}
}
}
impl Serialize for GraphUpdate {
fn serialize<S>(&self, serializer: S) -> std::result... | {
// Remove all empty table iterators.
self.iterators.retain(|it| it.valid());
if let Some(it) = self.iterators.first_mut() {
// Get the current values
if let Some((key, value)) = sstable::current_key_val(it) {
// Create the actual types
l... | identifier_body |
main.rs | Regular expressions use Rust syntax, as described here:
https://doc.rust-lang.org/regex/regex/index.html#syntax
scrubcsv should work with any ASCII-compatible encoding, but it will not
attempt to transcode.
Exit code:
0 on success
1 on error
2 if more than 10% of rows were bad"
)]
struct | {
/// Input file (uses stdin if omitted).
input: Option<PathBuf>,
/// Character used to separate fields in a row (must be a single ASCII
/// byte, or "tab").
#[structopt(
value_name = "CHAR",
short = "d",
long = "delimiter",
default_value = ","
)]
delimiter:... | Opt | identifier_name |
main.rs | .
Regular expressions use Rust syntax, as described here:
https://doc.rust-lang.org/regex/regex/index.html#syntax
scrubcsv should work with any ASCII-compatible encoding, but it will not
attempt to transcode.
Exit code:
0 on success
1 on error
2 if more than 10% of rows were bad"
)]
struct Opt {
/// ... | // flush, not on every tiny write.
let stdin = io::stdin();
let input: Box<dyn Read> = if let Some(ref path) = opt.input {
Box::new(
fs::File::open(path)
.with_context(|_| format!("cannot open {}", path.display()))?,
)
} else {
Box::new(stdin.lock())
... | // implementing `Read`, stored on the heap." This allows us to do runtime
// dispatch (as if Rust were object oriented). But because `csv` wraps a
// `BufReader` around the box, we only do that dispatch once per buffer | random_line_split |
main.rs | Regular expressions use Rust syntax, as described here:
https://doc.rust-lang.org/regex/regex/index.html#syntax
scrubcsv should work with any ASCII-compatible encoding, but it will not
attempt to transcode.
Exit code:
0 on success
1 on error
2 if more than 10% of rows were bad"
)]
struct Opt {
/// Inp... |
// Remove whitespace from our cells.
if opt.trim_whitespace {
// We do this manually, because the built | {
if null_re.is_match(val) {
val = &[]
}
} | conditional_block |
cmd.go | iptableslog "istio.io/istio/tools/istio-iptables/pkg/log"
)
const (
localHostIPv4 = "127.0.0.1"
localHostIPv6 = "::1"
)
var (
loggingOptions = log.DefaultOptions()
proxyArgs options.ProxyArgs
)
func NewRootCommand() *cobra.Command {
rootCmd := &cobra.Command{
Use: "pilot-agent",
Short: ... |
func initStsServer(proxy *model.Proxy, tokenManager security.TokenManager) (*stsserver.Server, error) {
localHostAddr := localHostIPv4
if proxy.IsIPv6() {
localHostAddr = localHostIPv6
} else {
// if not ipv6-only, it can be ipv4-only or dual-stack
// let InstanceIP decide the localhost
netIP, _ := netip.P... | {
o := options.NewStatusServerOptions(proxy, proxyConfig, agent)
o.EnvoyPrometheusPort = envoyPrometheusPort
o.EnableProfiling = enableProfiling
o.Context = ctx
statusServer, err := status.NewServer(*o)
if err != nil {
return err
}
go statusServer.Run(ctx)
return nil
} | identifier_body |
cmd.go | iptableslog "istio.io/istio/tools/istio-iptables/pkg/log"
)
const (
localHostIPv4 = "127.0.0.1"
localHostIPv6 = "::1"
)
var (
loggingOptions = log.DefaultOptions()
proxyArgs options.ProxyArgs
)
func | () *cobra.Command {
rootCmd := &cobra.Command{
Use: "pilot-agent",
Short: "Istio Pilot agent.",
Long: "Istio Pilot agent runs in the sidecar or gateway container and bootstraps Envoy.",
SilenceUsage: true,
FParseErrWhitelist: cobra.FParseErrWhitelist{
// Allow unknown flags for bac... | NewRootCommand | identifier_name |
cmd.go | Pilot agent runs in the sidecar or gateway container and bootstraps Envoy.",
SilenceUsage: true,
FParseErrWhitelist: cobra.FParseErrWhitelist{
// Allow unknown flags for backward-compatibility.
UnknownFlags: true,
},
}
// Attach the Istio logging options to the command.
loggingOptions.AttachCobraFlags(... | {
return nil, fmt.Errorf("Invalid proxy Type: " + string(proxy.Type))
} | conditional_block | |
cmd.go | "istio.io/istio/pilot/cmd/pilot-agent/config"
"istio.io/istio/pilot/cmd/pilot-agent/options"
"istio.io/istio/pilot/cmd/pilot-agent/status"
"istio.io/istio/pilot/pkg/model"
"istio.io/istio/pilot/pkg/util/network"
"istio.io/istio/pkg/bootstrap"
"istio.io/istio/pkg/cmd"
"istio.io/istio/pkg/collateral"
"istio.io/i... | meshconfig "istio.io/api/mesh/v1alpha1" | random_line_split | |
EventForm.js | import { useHistory } from "react-router";
import * as Yup from "yup";
import { Formik } from "formik";
import Map from "../mapbox/mapbox";
import axios from "axios";
import {
Box,
Button,
Card,
CardContent,
CardHeader,
Divider,
FormHelperText,
Grid,
TextField,
Typography,
makeStyles,
} from "@m... | (src, position, id) {
if (!position) {
return;
}
const script = document.createElement("script");
script.setAttribute("async", "");
script.setAttribute("id", id);
script.src = src;
position.appendChild(script);
}
const autocompleteService = { current: null };
// <===================>
const useStyl... | loadScript | identifier_name |
EventForm.js | import { useHistory } from "react-router";
import * as Yup from "yup";
import { Formik } from "formik";
import Map from "../mapbox/mapbox";
import axios from "axios";
import {
Box,
Button,
Card,
CardContent,
CardHeader,
Divider,
FormHelperText,
Grid,
TextField,
Typography,
makeStyles,
} from "@m... |
loaded.current = true;
}
const fetch = React.useMemo(
() =>
throttle((request, callback) => {
autocompleteService.current.getPlacePredictions(request, callback);
}, 200),
[]
);
React.useEffect(() => {
let active = true;
if (!autocompleteService.current && window.googl... | {
const classes = useStyles();
const history = useHistory();
// const { enqueueSnackbar } = useSnackbar();
const [selectedDate, setSelectedDate] = React.useState(new Date());
// <====================Helper Funtions for AutoFill===========>
// eslint-disable-next-line
const [value, setValue] = React.useSta... | identifier_body |
EventForm.js | import { useHistory } from "react-router";
import * as Yup from "yup";
import { Formik } from "formik";
import Map from "../mapbox/mapbox";
import axios from "axios";
import {
Box,
Button,
Card,
CardContent,
CardHeader,
Divider,
FormHelperText,
Grid,
TextField,
Typography,
makeStyles,
} from "@m... |
const fetch = React.useMemo(
() =>
throttle((request, callback) => {
autocompleteService.current.getPlacePredictions(request, callback);
}, 200),
[]
);
React.useEffect(() => {
let active = true;
if (!autocompleteService.current && window.google) {
autocompleteService.... | {
if (!document.querySelector("#google-maps")) {
loadScript(
`https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_MAP_APP_API_KEY}&libraries=places`,
document.querySelector("head"),
"google-maps"
);
}
loaded.current = true;
} | conditional_block |
EventForm.js | import { useHistory } from "react-router";
import * as Yup from "yup";
import { Formik } from "formik";
import Map from "../mapbox/mapbox";
import axios from "axios";
import {
Box,
Button,
Card,
CardContent,
CardHeader,
Divider,
FormHelperText,
Grid,
TextField,
Typography,
makeStyles,
} from "@m... | <CardHeader title="Location" />
<Divider />
<CardContent>
<Autocomplete
fullWidth
name="location"
getOptionLabel={option =>
typeof option === "string" ? opt... | </CardContent>
</Card>
</Box>
<Box mt={3}>
<Card> | random_line_split |
main.go | :
format, scale = "%.0fs", 1
case x >= 9.95:
format, scale = "%.1fs", 1
case x >= 0.995:
format, scale = "%.2fs", 1
case x >= 0.0995:
format, scale = "%.0fms", 1000
case x >= 0.00995:
format, scale = "%.1fms", 1000
case x >= 0.000995:
format, scale = "%.2fms", 1000
case x >= 0.0000995:
format, scale... | (old, | identifier_name | |
main.go | ", 1000
case x >= 0.00995:
format, scale = "%.1fms", 1000
case x >= 0.000995:
format, scale = "%.2fms", 1000
case x >= 0.0000995:
format, scale = "%.0fµs", 1000*1000
case x >= 0.00000995:
format, scale = "%.1fµs", 1000*1000
case x >= 0.000000995:
format, scale = "%.2fµs", 1000*1000
case x >= 0.000000099... | err := stats.TwoSampleWelchTTest(stats.Sample{Xs: old.RValues}, stats.Sample{Xs: new.RValues}, stats.LocationDiffers)
if err != nil {
return -1, err
}
return t.P, nil
}
fun | identifier_body | |
main.go | } else {
table = append(table, newRow("name", metric))
}
for _, key.Benchmark = range c.Benchmarks {
row := newRow(key.Benchmark)
var scaler func(float64) string
for _, key.Config = range c.Configs {
stat := c.Stats[key]
if stat == nil {
row.add("")
continue
}
if s... | } | random_line_split | |
main.go | }
func main() {
log.SetPrefix("benchstat: ")
log.SetFlags(0)
flag.Usage = usage
flag.Parse()
deltaTest := deltaTestNames[strings.ToLower(*flagDeltaTest)]
if flag.NArg() < 1 || deltaTest == nil {
flag.Usage()
}
// Read in benchmark data.
c := readFiles(flag.Args())
for _, stat := range c.Stats {
stat.Com... |
r.cols = r.cols[:len(r.cols)-1]
}
| conditional_block | |
extractor.rs | !("enter: get_sub_paths_from_path({})", path);
let mut paths = vec![];
// filter out any empty strings caused by .split
let mut parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
let length = parts.len();
for i in 0..length {
// iterate over all parts of the path
... |
};
if SCANNED_URLS.get_scan_by_url(&new_url.to_string()).is_some() {
//we've seen the url before and don't need to scan again
log::trace!("exit: request_feroxresponse_from_new_link -> None");
return None;
}
// make the request and store the response
let new_response = matc... | {
log::trace!("exit: request_feroxresponse_from_new_link -> None");
return None;
} | conditional_block |
extractor.rs | !("enter: get_sub_paths_from_path({})", path);
let mut paths = vec![];
// filter out any empty strings caused by .split
let mut parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
let length = parts.len();
for i in 0..length {
// iterate over all parts of the path
... | (
response: &FeroxResponse,
tx_stats: UnboundedSender<StatCommand>,
) -> HashSet<String> {
log::trace!(
"enter: get_links({}, {:?})",
response.url().as_str(),
tx_stats
);
let mut links = HashSet::<String>::new();
let body = response.text();
for capture in LINKS_REG... | get_links | identifier_name |
extractor.rs | response_from_new_link({}, {:?})",
url,
tx_stats
);
// create a url based on the given command line options, return None on error
let new_url = match format_url(
&url,
&"",
CONFIGURATION.add_slash,
&CONFIGURATION.queries,
None,
tx_stats.clone(... | let (tx, _): FeroxChannel<StatCommand> = mpsc::unbounded_channel();
let response = make_request(&client, &url, tx.clone()).await.unwrap();
let ferox_response = FeroxResponse::from(response, true).await; | random_line_split | |
extractor.rs | ).await;
log::trace!(
"exit: request_feroxresponse_from_new_link -> {:?}",
new_ferox_response
);
Some(new_ferox_response)
}
/// helper function that simply requests /robots.txt on the given url's base url
///
/// example:
/// http://localhost/api/users -> http://localhost/robots.txt
//... | {
let srv = MockServer::start();
let mock = srv.mock(|when, then| {
when.method(GET).path("/robots.txt");
then.status(200).body("this is a test");
});
let mut config = Configuration::default();
let (tx, _): FeroxChannel<StatCommand> = mpsc::unbounded_ch... | identifier_body | |
keyboard.rs | {
RepeatDelay(500)
}
}
#[derive(Default, Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KeyboardConfig {
pub xkb_rules: String,
pub xkb_model: String,
pub xkb_layout: String,
pub xkb_variant: String,
pub xkb_options: Option<String>,
pub repeat_rate: RepeatRate,
... |
}
}
wayland_listener!(
KeyboardEventManager,
Weak<Keyboard>,
[
modifiers => modifiers_func: |this: &mut KeyboardEventManager, _data: *mut libc::c_void,| unsafe {
if let Some(handler) = this.data.upgrade() {
handler.modifiers();
}
};
key => key_func: |this: &mut KeyboardEventMan... | {
unsafe {
// Otherwise, we pass it along to the client.
wlr_seat_set_keyboard(self.seat_manager.raw_seat(), self.device.raw_ptr());
wlr_seat_keyboard_notify_key(
self.seat_manager.raw_seat(),
event.time_msec(),
event.libinput_keycode(),
event.raw_st... | conditional_block |
keyboard.rs | {
RepeatDelay(500)
}
}
#[derive(Default, Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KeyboardConfig {
pub xkb_rules: String,
pub xkb_model: String,
pub xkb_layout: String,
pub xkb_variant: String,
pub xkb_options: Option<String>,
pub repeat_rate: RepeatRate,
... | {
seat_manager: Rc<SeatManager>,
event_filter_manager: Rc<EventFilterManager>,
device: Rc<Device>,
keyboard: *mut wlr_keyboard,
xkb_state: RefCell<xkb::State>,
event_manager: RefCell<Option<Pin<Box<KeyboardEventManager>>>>,
}
impl Keyboard {
fn init(
config_manager: Rc<ConfigManager>,
seat_mana... | Keyboard | identifier_name |
keyboard.rs | {
RepeatDelay(500)
}
}
#[derive(Default, Debug, Eq, PartialEq, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KeyboardConfig {
pub xkb_rules: String,
pub xkb_model: String,
pub xkb_layout: String,
pub xkb_variant: String,
pub xkb_options: Option<String>,
pub repeat_rate: RepeatRate,
... | }
}
pub(crate) trait KeyboardEventHandler {
fn modifiers(&self);
fn key(&self, event: *const wlr_event_keyboard_key);
}
impl KeyboardEventHandler for Keyboard {
fn modifiers(&self) {
unsafe {
// A seat can only have one keyboard, but this is a limitation of the
// Wayland protocol - not wlroot... | config.repeat_delay.0 as i32,
); | random_line_split |
quic.rs | _window((PACKET_DATA_SIZE as u32 * MAX_CONCURRENT_UNI_STREAMS).into());
// disable bidi & datagrams
const MAX_CONCURRENT_BIDI_STREAMS: u32 = 0;
config.max_concurrent_bidi_streams(MAX_CONCURRENT_BIDI_STREAMS.into());
config.datagram_receive_buffer_size(None);
Ok((server_config, cert_chain_pem))
}
... | {
#[error("Server configure failed")]
ConfigureFailed,
#[error("Endpoint creation failed")]
EndpointFailed,
}
// Return true if the server should drop the stream
fn handle_chunk(
chunk: &Result<Option<quinn::Chunk>, quinn::ReadError>,
maybe_batch: &mut Option<PacketBatch>,
remote_addr: &S... | QuicServerError | identifier_name |
quic.rs | contents: cert.0.clone(),
})
.collect();
let cert_chain_pem = pem::encode_many(&cert_chain_pem_parts);
let mut server_config = ServerConfig::with_single_cert(cert_chain, priv_key)
.map_err(|_e| QuicServerError::ConfigureFailed)?;
let config = Arc::get_mut(&mut server_con... | new_cert(identity_keypair, gossip_host).map_err(|_e| QuicServerError::ConfigureFailed)?;
let cert_chain_pem_parts: Vec<Pem> = cert_chain
.iter()
.map(|cert| Pem {
tag: "CERTIFICATE".to_string(), | random_line_split | |
quic.rs | algorithm: AlgorithmIdentifier {
oid: ObjectIdentifier::from_arcs(&ED25519_IDENTIFIER).unwrap(),
parameters: None,
},
private_key: &private_key,
public_key: None,
};
let key_pkcs8_der = key_pkcs8
.to_der()
.expect("Failed to convert keypair to DER... | {
solana_logger::setup();
let s = UdpSocket::bind("127.0.0.1:0").unwrap();
let exit = Arc::new(AtomicBool::new(false));
let (sender, receiver) = unbounded();
let keypair = Keypair::new();
let ip = "127.0.0.1".parse().unwrap();
let server_address = s.local_addr().u... | identifier_body | |
bob.py | white (for dark background).
"""
white = ' icon-white' if is_white else ''
return mark_safe('<i class="icon-%s%s"></i>' % esc(name, white))
@register.inclusion_tag('bob/main_menu.html')
def main_menu(items, selected, title=None, search=None, white=False,
position='', title_url="/"):
""... |
else:
return d
@register.inclusion_tag('bob/form.html')
def form(form, action="", method="POST", fugue_icons=False,
css_class="form-horizontal", title="", submit_label='Save'):
"""
Render a form.
:param form: The form to render.
:param action: The submit URL.
:param method: ... | return d.strftime('%H:%M') | conditional_block |
bob.py | white (for dark background).
"""
white = ' icon-white' if is_white else ''
return mark_safe('<i class="icon-%s%s"></i>' % esc(name, white))
@register.inclusion_tag('bob/main_menu.html')
def main_menu(items, selected, title=None, search=None, white=False,
position='', title_url="/"):
""... | (item, selected):
"""
Show subitems of a menu in a sidebar.
"""
return {
'item': item,
'selected': selected,
}
@register.inclusion_tag('bob/pagination.html')
def pagination(page, show_all=False, show_csv=False,
fugue_icons=False, url_query=None, neighbors=1,
... | sidebar_menu_subitems | identifier_name |
bob.py | is_white else ''
return mark_safe('<i class="icon-%s%s"></i>' % esc(name, white))
@register.inclusion_tag('bob/main_menu.html')
def main_menu(items, selected, title=None, search=None, white=False,
position='', title_url="/"):
"""
Show main menu bar.
:param items: The list of :class:`bo... | 'sort_variable_name': sort_variable_name,
}
| random_line_split | |
bob.py | white (for dark background).
"""
white = ' icon-white' if is_white else ''
return mark_safe('<i class="icon-%s%s"></i>' % esc(name, white))
@register.inclusion_tag('bob/main_menu.html')
def main_menu(items, selected, title=None, search=None, white=False,
position='', title_url="/"):
""... |
@register.inclusion_tag('bob/sidebar_menu.html')
def sidebar_menu(items, selected):
"""
Show menu in a sidebar.
:param items: The list of :class:`bob.menu.MenuItem` instances to show.
:param selected: The :data:`name` of the currently selected item.
"""
return {
'items': items,
... | """
Show a menu in form of tabs.
:param items: The list of :class:`bob.menu.MenuItem` instances to show.
:param selected: The :data:`name` of the currently selected item.
:param side: The direction of tabs, may be on of ``"left"``, ``"right"``,
``"top"`` or ``"bottom"``. Defaults to ``"top"``.
... | identifier_body |
render.rs | .replace(Some(shape));
}
}
/// Redraw the invisible mouse-event-catching edges.
pub(super) fn redraw_hover_sections(
&self,
parent: &impl ShapeParent,
corners: &[Oriented<Corner>],
) {
let hover_factory = self
.hover_sections
.take()
... | arc.stroke_width.set(LINE_WIDTH);
self.display_object().add_child(&arc);
self.layers().edge_below_nodes.add(&arc);
arc
} | random_line_split | |
render.rs | data flow direction.
dataflow_arrow: RefCell<Option<Rectangle>>,
/// An rectangle representing the source node shape when the edge is in detached state. Used
/// to mask out the edge fragment that would otherwise be drawn over the source node.
source_cutout: RefCell<Option<Rectangle>>,
}
impl S... | (
&self,
parent: &impl ShapeParent,
corners: &[Oriented<Corner>],
) {
let hover_factory = self
.hover_sections
.take()
.into_iter()
.chain(iter::repeat_with(|| parent.new_hover_section()));
*self.hover_sections.borrow_mut() = co... | redraw_hover_sections | identifier_name |
render.rs | if it is a split [`Corner`].
pub(super) fn redraw_sections(&self, parent: &impl ShapeParent, parameters: RedrawSections) {
let RedrawSections { corners, source_color, target_color, focus_split, is_attached } =
parameters;
let corner_index =
focus_split.map(|split| split.corn... | {
let new = SimpleTriangle::from_size(arrow::SIZE);
new.set_pointer_events(false);
self.display_object().add_child(&new);
new.into()
} | identifier_body | |
render.rs | _ADJUSTMENT * 2.0);
let offset = Vector2(-LINE_WIDTH / 2.0, - length - attachment::LENGTH_ADJUSTMENT);
shape.set_xy(target + offset);
shape.set_color(color);
self.target_attachment.replace(Some(shape));
}
}
/// Add the given shape to the appropriate layer... | {
a
} | conditional_block | |
PDDSP_encoder.py | tf.reduce_mean(Y_diff, axis=0) # todo tune aggregation function
nov = tf.concat([nov, np.array([0])], axis=0)
Fs_nov = Fs / H
nov -= tf.math.reduce_mean(nov) # todo tune output normalization
nov = tf.clip_by_value(nov, clip_value_min=0., clip_value_max=1000000.)
nov /= tf.math.reduce_max(nov) # no... |
def bandpass_filter_audio(audio, f_low=400, f_high=450):
"""Bandpass filters audio to given frequency range"""
filtered_audio = core.sinc_filter(audio, f_low, window_size=256, high_pass=True)
filtered_audio = core.sinc_filter(filtered_audio, f_high, window_size=256, high_pass=False)
return tf.squeeze... | """Tensorflow-based implementation of librosa.core.fourier_tempo_frequencies"""
return fft_frequencies(sr=sr * 60 / float(hop_length), n_fft=win_length) | identifier_body |
PDDSP_encoder.py | tf.reduce_mean(Y_diff, axis=0) # todo tune aggregation function
nov = tf.concat([nov, np.array([0])], axis=0)
Fs_nov = Fs / H
nov -= tf.math.reduce_mean(nov) # todo tune output normalization
nov = tf.clip_by_value(nov, clip_value_min=0., clip_value_max=1000000.)
nov /= tf.math.reduce_max(nov) # no... |
dominant_tempo = tf.expand_dims(dominant_tempo, axis=0)
out = tf.concat([dominant_tempo, weighted_mean_tempo], axis=0)
return tf.cast(out | weighted_mean_tempo = tf.expand_dims(tf.cast(weighted_mean, dtype=tf.float32), axis = 0) | conditional_block |
PDDSP_encoder.py | tf.reduce_mean(Y_diff, axis=0) # todo tune aggregation function
nov = tf.concat([nov, np.array([0])], axis=0)
Fs_nov = Fs / H
nov -= tf.math.reduce_mean(nov) # todo tune output normalization
nov = tf.clip_by_value(nov, clip_value_min=0., clip_value_max=1000000.)
nov /= tf.math.reduce_max(nov) # no... | (tens):
"""Tensorflow peak picking via local maxima
Returns the indices of the local maxima of the first dimension of the tensor
Based on https://stackoverflow.com/questions/48178286/finding-local-maxima-with-tensorflow
"""
return tf.squeeze(tf.where(tf.equal(label_local_extrema(tens), 'P')))
def ... | find_local_maxima | identifier_name |
PDDSP_encoder.py | tf.reduce_mean(Y_diff, axis=0) # todo tune aggregation function
nov = tf.concat([nov, np.array([0])], axis=0)
Fs_nov = Fs / H
nov -= tf.math.reduce_mean(nov) # todo tune output normalization
nov = tf.clip_by_value(nov, clip_value_min=0., clip_value_max=1000000.)
nov /= tf.math.reduce_max(nov) # no... | def period_from_pulse(pulse, F_mean_in_Hz, sr, loudness_min=0.1, loudness_max=1.):
"""Compute mean period and the next expected onset position"""
# Find last peak in the pulse
peaks = find_local_maxima(tf.clip_by_value(pulse, clip_value_min=loudness_min,
clip_... | random_line_split | |
test2.py | :
def __init__(self, master):
self.video = None
self.frame_rate = 0
self.video_length = 0
# The scaled image used for display. Needs to persist for display
self.display_image = None
self.display_ratio = 0
self.awaiting_corners = False
self.corners ... |
def parse_video(self, crop_window):
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out1 = cv2.VideoWriter('output.avi', fourcc, 30.0, (crop_window.w, crop_window.h))
success, current_frame = self.video.read()
current_frame = current_frame[crop_window.y:crop_window.y + crop_window.h,
... | print "-------------------"
for y in range(19):
string = ""
for x in range(19):
string += frame[x][y]
print string
print "-------------------" | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.