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 |
|---|---|---|---|---|
kubernetes.go | // Copyright (c) 2017 Pulcy.
//
// 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 wri... | () (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 | // Copyright (c) 2017 Pulcy.
//
// 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 wri... | 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 | // Copyright (c) 2017 Pulcy.
//
// 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 wri... |
// 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 | import re
import uuid
import contextlib
from datetime import datetime
import sentry_sdk
from sentry_sdk.utils import capture_internal_exceptions, logger, to_string
from sentry_sdk._compat import PY2
from sentry_sdk._types import MYPY
if PY2:
from collections import Mapping
else:
from collections.abc import ... |
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 | import re
import uuid
import contextlib
from datetime import datetime
import sentry_sdk
from sentry_sdk.utils import capture_internal_exceptions, logger, to_string
from sentry_sdk._compat import PY2
from sentry_sdk._types import MYPY
if PY2:
from collections import Mapping
else:
from collections.abc import ... |
query = _format_sql(cursor, query)
data = {}
if params_list is not None:
data["db.params"] = params_list
if paramstyle is not None:
data["db.paramstyle"] = paramstyle
if executemany:
data["db.executemany"] = True
with capture_internal_exceptions():
hub.add_bre... | params_list = None
paramstyle = None | conditional_block |
tracing.py | import re
import uuid
import contextlib
from datetime import datetime
import sentry_sdk
from sentry_sdk.utils import capture_internal_exceptions, logger, to_string
from sentry_sdk._compat import PY2
from sentry_sdk._types import MYPY
if PY2:
from collections import Mapping
else:
from collections.abc import ... | 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 | import re
import uuid
import contextlib
from datetime import datetime
import sentry_sdk
from sentry_sdk.utils import capture_internal_exceptions, logger, to_string
from sentry_sdk._compat import PY2
from sentry_sdk._types import MYPY
if PY2:
from collections import Mapping
else:
from collections.abc import ... | (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 | #![feature(plugin, decl_macro, custom_derive, type_ascription)] // Compiler plugins
#![plugin(rocket_codegen)] // rocket code generator
extern crate rocket;
extern crate rabe;
extern crate serde;
extern crate serde_json;
extern crate rustc_serialize;
extern crate blake2_rfc;
extern crate rocket_simpleauth;
exter... | (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 | #![feature(plugin, decl_macro, custom_derive, type_ascription)] // Compiler plugins
#![plugin(rocket_codegen)] // rocket code generator
extern crate rocket;
extern crate rabe;
extern crate serde;
extern crate serde_json;
extern crate rustc_serialize;
extern crate blake2_rfc;
extern crate rocket_simpleauth;
exter... |
fn db_get_session_by_api_key(conn: &MysqlConnection, api_key: &String) -> Result<schema::Session, diesel::result::Error> {
use schema::sessions;
sessions::table.filter(sessions::random_session_id.eq(api_key))
.first::<schema::Session>(conn)
}
fn _db_get_user_by_username<'a>(conn: &MysqlConnection, user:... | {
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 | #![feature(plugin, decl_macro, custom_derive, type_ascription)] // Compiler plugins
#![plugin(rocket_codegen)] // rocket code generator
extern crate rocket;
extern crate rabe;
extern crate serde;
extern crate serde_json;
extern crate rustc_serialize;
extern crate blake2_rfc;
extern crate rocket_simpleauth;
exter... | }
// -----------------------------------------------------
// 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 | # -*- coding: utf-8 -*-
from operator import attrgetter
import logging
import StringIO
import struct
import dpkt
from netifaces import interfaces, ifaddresses, AF_INET
from sniff import PcapWrapper
import http
ACK = dpkt.tcp.TH_ACK
SYN = dpkt.tcp.TH_SYN
FIN = dpkt.tcp.TH_FIN
RST = dpkt.tcp.TH_RST
PUSH = dpkt.tcp.TH... |
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 | # -*- coding: utf-8 -*-
from operator import attrgetter
import logging
import StringIO
import struct
import dpkt
from netifaces import interfaces, ifaddresses, AF_INET
from sniff import PcapWrapper
import http
ACK = dpkt.tcp.TH_ACK
SYN = dpkt.tcp.TH_SYN
FIN = dpkt.tcp.TH_FIN
RST = dpkt.tcp.TH_RST
PUSH = dpkt.tcp.TH... |
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 | # -*- coding: utf-8 -*-
from operator import attrgetter
import logging
import StringIO
import struct
import dpkt
from netifaces import interfaces, ifaddresses, AF_INET
from sniff import PcapWrapper
import http
ACK = dpkt.tcp.TH_ACK
SYN = dpkt.tcp.TH_SYN
FIN = dpkt.tcp.TH_FIN
RST = dpkt.tcp.TH_RST
PUSH = dpkt.tcp.TH... | (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 | # -*- coding: utf-8 -*-
from operator import attrgetter
import logging
import StringIO
import struct
import dpkt
from netifaces import interfaces, ifaddresses, AF_INET
from sniff import PcapWrapper
import http
ACK = dpkt.tcp.TH_ACK
SYN = dpkt.tcp.TH_SYN
FIN = dpkt.tcp.TH_FIN
RST = dpkt.tcp.TH_RST
PUSH = dpkt.tcp.TH... |
@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 | // Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//go:build kubeapiserver
package apiserver
import (
"context"
"math"
... | () 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 | // Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//go:build kubeapiserver
package apiserver
import (
"context"
"math"
... |
// 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 | // Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//go:build kubeapiserver
package apiserver
import (
"context"
"math"
... | 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 | // Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
//go:build kubeapiserver
package apiserver
import (
"context"
"math"
... |
if err := UnstructuredIntoWPA(tombstone, deletedWPA); err != nil {
log.Errorf("Tombstone contained object that is not an Autoscaler: %#v", obj)
return
}
log.Debugf("Deleting Metrics from WPA %s/%s", deletedWPA.Namespace, deletedWPA.Name)
toDelete.External = autoscalers.InspectWPA(deletedWPA)
log.Debugf("Delet... | {
log.Errorf("Could not get object from tombstone %#v", obj)
return
} | conditional_block |
splash.go | package splash
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
neturl "net/url"
"os"
"strings"
"time"
"github.com/pquerna/cachecontrol/cacheobject"
"github.com/spf13/viper"
"github.com/slotix/dataflowkit/errs"
)
var logger *log.Logger
func init() {... | }
//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 | package splash
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
neturl "net/url"
"os"
"strings"
"time"
"github.com/pquerna/cachecontrol/cacheobject"
"github.com/spf13/viper"
"github.com/slotix/dataflowkit/errs"
)
var logger *log.Logger
func init() {... | () (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 | package splash
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
neturl "net/url"
"os"
"strings"
"time"
"github.com/pquerna/cachecontrol/cacheobject"
"github.com/spf13/viper"
"github.com/slotix/dataflowkit/errs"
)
var logger *log.Logger
func init() {... | 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 | package splash
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
neturl "net/url"
"os"
"strings"
"time"
"github.com/pquerna/cachecontrol/cacheobject"
"github.com/spf13/viper"
"github.com/slotix/dataflowkit/errs"
)
var logger *log.Logger
func init() {... |
//Fetch content from url through Splash server https://github.com/scrapinghub/splash/
func Fetch(req Request) (io.ReadCloser, error) {
//logger.Println(splashURL)
response, err := GetResponse(req)
if err != nil {
return nil, err
}
logger.Println(err)
content, err := response.GetContent()
if err == nil {
re... | {
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 | package main
import (
"context"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/andygrunwald/go-gerrit"
"github.com/google/go-github/github"
"github.com/gregjones/httpcache"
git "github.com/l... |
}
log.Printf("Processed project %s/%s", owner, repo)
return nil
}
func ProcessAllProjects() error {
log.Printf("Processing all projects")
for i := 0; i < len(allRepos); i++ {
thisRepo := allRepos[i]
err := ProcessProject(thisRepo.Owner, thisRepo.Name)
if err != nil {
return err
}
}
log.Printf("P... | {
return err
} | conditional_block |
main.go | package main
import (
"context"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/andygrunwald/go-gerrit"
"github.com/google/go-github/github"
"github.com/gregjones/httpcache"
git "github.com/l... |
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 | package main
import (
"context"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/andygrunwald/go-gerrit"
"github.com/google/go-github/github"
"github.com/gregjones/httpcache"
git "github.com/l... | _, _, 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 | package main
import (
"context"
"crypto/rand"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/andygrunwald/go-gerrit"
"github.com/google/go-github/github"
"github.com/gregjones/httpcache"
git "github.com/l... | (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 | 'use strict';
/**
* @class TVList
* @constructor
* @author Roman Stoian
*/
function TVList(parent) {
| // extending
TVList.prototype = Object.create(CScrollList.prototype);
TVList.prototype.constructor = TVList;
/**
* Setter for linked component
* @param {CBase} component associated object
*/
TVList.prototype.SetBreadCrumb = function ( component ) {
this.bcrumb = component;
};
/**
* Setter for linked component
... | // 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 | 'use strict';
/**
* @class TVList
* @constructor
* @author Roman Stoian
*/
function TVList(parent) {
// 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}
... |
/**
* 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 | 'use strict';
/**
* @class TVList
* @constructor
* @author Roman Stoian
*/
function TV | 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 | 'use strict';
/**
* @class TVList
* @constructor
* @author Roman Stoian
*/
function TVList(parent) {
// 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}
... | 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 | // Copyright (c) 2019 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not b... | 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 | // Copyright (c) 2019 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not b... |
}
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 | // Copyright (c) 2019 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not b... |
/// 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 | // Copyright (c) 2019 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not b... | <'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 | import datetime
import functools
import json
import logging
import os
import shutil
import subprocess
import sys
import time
import pymongo
import pandas as pd
import pymysql
import schedule
from raven import Client
from sqlalchemy import create_engine
from config import MONGOURL, MYSQLHOST, MYSQLUSER, MYSQLPASSWORD,... | # """
# test gen all codes from mongo today
# t1 = time.time()
# all_codes_now()
# print(time.time() - t1) # 61s
# test wirte code to a file
# t1 = time.time()
# now_codes = all_codes_now()
# write_codes_to_file(now_codes)
# print(time.time() - t1) # 55s
# 写入分散的 csv 文件
... | # ('2019-07-18T00:00:00Z', '2019-07-19T00:00:00Z', '20190718') | random_line_split |
utils.py | import datetime
import functools
import json
import logging
import os
import shutil
import subprocess
import sys
import time
import pymongo
import pandas as pd
import pymysql
import schedule
from raven import Client
from sqlalchemy import create_engine
from config import MONGOURL, MYSQLHOST, MYSQLUSER, MYSQLPASSWORD,... | datetime.time.min).strftime("%Y-%m-%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):
"""
... | 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 | import datetime
import functools
import json
import logging
import os
import shutil
import subprocess
import sys
import time
import pymongo
import pandas as pd
import pymysql
import schedule
from raven import Client
from sqlalchemy import create_engine
from config import MONGOURL, MYSQLHOST, MYSQLUSER, MYSQLPASSWORD,... | # "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 | import datetime
import functools
import json
import logging
import os
import shutil
import subprocess
import sys
import time
import pymongo
import pandas as pd
import pymysql
import schedule
from raven import Client
from sqlalchemy import create_engine
from config import MONGOURL, MYSQLHOST, MYSQLUSER, MYSQLPASSWORD,... | 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 | use core::fmt;
use volatile::Volatile;
use spin::Mutex;
#[allow(dead_code)] // prevents compiler warnings that some enumerations are never used
#[derive(Debug, Clone, Copy, PartialEq, Eq)] // enables copy semantics for the type: makes printable & comparable
#[repr(u8)] // makes each enum variant be stor... | 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 | use core::fmt;
use volatile::Volatile;
use spin::Mutex;
#[allow(dead_code)] // prevents compiler warnings that some enumerations are never used
#[derive(Debug, Clone, Copy, PartialEq, Eq)] // enables copy semantics for the type: makes printable & comparable
#[repr(u8)] // makes each enum variant be stor... | else {
assert_eq!(screen_char, empty_char());
}
}
}
}
}
| { // 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 | use core::fmt;
use volatile::Volatile;
use spin::Mutex;
#[allow(dead_code)] // prevents compiler warnings that some enumerations are never used
#[derive(Debug, Clone, Copy, PartialEq, Eq)] // enables copy semantics for the type: makes printable & comparable
#[repr(u8)] // makes each enum variant be stor... | {
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 | use core::fmt;
use volatile::Volatile;
use spin::Mutex;
#[allow(dead_code)] // prevents compiler warnings that some enumerations are never used
#[derive(Debug, Clone, Copy, PartialEq, Eq)] // enables copy semantics for the type: makes printable & comparable
#[repr(u8)] // makes each enum variant be stor... |
}
// 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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# execfile(PATH + "syntax/03_Deteccion_info/059_Implementacion_plazos.py")
if __name__ == "__main__":
guardaResultados = True
muestraHTML = True
guardaES = True
es_hdfs = False
import sys
import platform
if platform.system() == "Windows":
... |
else:
for igrupo in range(len(gruposUnidos)):
result[val + "_" + str(igrupo + 1)] = dict(descripcion = frasesGrup[igrupo])
result[val + "_" + str(igrupo + 1)]["posiciones"] = dict(inicio = list(aux_data.loc[(gruposUnidos[igrupo])]["PosInicio"]), fin = list(aux_data.loc[(gruposUnidos[igrupo])]["... | 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 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# execfile(PATH + "syntax/03_Deteccion_info/059_Implementacion_plazos.py")
if __name__ == "__main__":
guardaResultados = True
muestraHTML = True
guardaES = True
es_hdfs = False
import sys
import platform
if platform.system() == "Windows":
... | # 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 | #!/usr/bin/env python
"""
Use version of DriverSlave that has pixmap and pixheights
"""
import threading
# import base classes and driver
from bibliopixel import LEDStrip, LEDMatrix
# from bibliopixel.drivers.LPD8806 import DriverLPD8806, ChannelOrder
from bibliopixel.drivers.visualizer import DriverVisualizer, Channel... | (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 | #!/usr/bin/env python
"""
Use version of DriverSlave that has pixmap and pixheights
"""
import threading
# import base classes and driver
from bibliopixel import LEDStrip, LEDMatrix
# from bibliopixel.drivers.LPD8806 import DriverLPD8806, ChannelOrder
from bibliopixel.drivers.visualizer import DriverVisualizer, Channel... | 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 | #!/usr/bin/env python
"""
Use version of DriverSlave that has pixmap and pixheights
"""
import threading
# import base classes and driver
from bibliopixel import LEDStrip, LEDMatrix
# from bibliopixel.drivers.LPD8806 import DriverLPD8806, ChannelOrder
from bibliopixel.drivers.visualizer import DriverVisualizer, Channel... |
#
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 | #!/usr/bin/env python
"""
Use version of DriverSlave that has pixmap and pixheights
"""
import threading
# import base classes and driver
from bibliopixel import LEDStrip, LEDMatrix
# from bibliopixel.drivers.LPD8806 import DriverLPD8806, ChannelOrder
from bibliopixel.drivers.visualizer import DriverVisualizer, Channel... |
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 | package provider
import (
"fmt"
"strings"
"github.com/go-ldap/ldap/v3"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/trevex/terraform-provider-ldap/util"
)
func resourceLDAPObjectAttributes() *schema.Resource {
return &schema.Resource{
Create: resourceLDAPObjectAttributesCreate,
... |
} 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 | package provider
import (
"fmt"
"strings"
"github.com/go-ldap/ldap/v3"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/trevex/terraform-provider-ldap/util"
)
func resourceLDAPObjectAttributes() *schema.Resource {
return &schema.Resource{
Create: resourceLDAPObjectAttributesCreate,
... | 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 | package provider
import (
"fmt"
"strings"
"github.com/go-ldap/ldap/v3"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/trevex/terraform-provider-ldap/util"
)
func resourceLDAPObjectAttributes() *schema.Resource |
func resourceLDAPObjectAttributesCreate(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 lis... | {
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 | package provider
import (
"fmt"
"strings"
"github.com/go-ldap/ldap/v3"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/trevex/terraform-provider-ldap/util"
)
func resourceLDAPObjectAttributes() *schema.Resource {
return &schema.Resource{
Create: resourceLDAPObjectAttributesCreate,
... | (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 | use std::cell::RefCell;
use std::collections::HashSet;
use std::collections::hash_map::HashMap;
use std::fmt;
use std::rc::Rc;
use semver;
use core::{PackageId, Registry, SourceId, Summary, Dependency};
use core::PackageIdSpec;
use util::{CargoResult, Graph, human, ChainError, CargoError};
use util::profile;
use util:... |
}
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 | use std::cell::RefCell;
use std::collections::HashSet;
use std::collections::hash_map::HashMap;
use std::fmt;
use std::rc::Rc;
use semver;
use core::{PackageId, Registry, SourceId, Summary, Dependency};
use core::PackageIdSpec;
use util::{CargoResult, Graph, human, ChainError, CargoError};
use util::profile;
use util:... |
Method::Required{features: requested_features, ..} => {
for feat in requested_features.iter() {
try!(add_feature(s, feat, &mut deps, &mut used, &mut visited));
}
}
}
match method {
Method::Everything |
Method::Required { uses_default_feat... | {
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 | use std::cell::RefCell;
use std::collections::HashSet;
use std::collections::hash_map::HashMap;
use std::fmt;
use std::rc::Rc;
use semver;
use core::{PackageId, Registry, SourceId, Summary, Dependency};
use core::PackageIdSpec;
use util::{CargoResult, Graph, human, ChainError, CargoError};
use util::profile;
use util:... | (&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 | use std::cell::RefCell;
use std::collections::HashSet;
use std::collections::hash_map::HashMap;
use std::fmt;
use std::rc::Rc;
use semver;
use core::{PackageId, Registry, SourceId, Summary, Dependency};
use core::PackageIdSpec;
use util::{CargoResult, Graph, human, ChainError, CargoError};
use util::profile;
use util:... | continue
}
let mut base = feature_deps.remove(dep.name()).unwrap_or(vec![]);
for feature in dep.features().iter() {
base.push(feature.clone());
if feature.contains("/") {
return Err(human(format!("features in dependencies \
... | // 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 | # Xinwu Qian 2019-02-06
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
# This implements independent q learning approach
use_gpu = 1
import os
import config
from multiprocessing import Pool
import taxi_env as te
import scipy
import taxi_util as tu
import time
from datetime import datetime
im... |
global_epi_buffer=global_epi_buffer[trace_length:]
buffer_count-=trace_length
if total_steps % (500) == 0 and i>4:
linubc_train = bandit_buffer.sample(batch_size * 40)
linucb_agent.update(linubc_train[:, 4], linubc_train[:, 1], linubc_train[:... | bufferArray=np.array(global_epi_buffer)
exp_replay.add(bufferArray[it:it+trace_length]) | conditional_block |
new_IDRQN_main.py | # Xinwu Qian 2019-02-06
import warnings
warnings.filterwarnings("ignore", category=RuntimeWarning)
# This implements independent q learning approach
use_gpu = 1
import os
import config
from multiprocessing import Pool
import taxi_env as te
import scipy
import taxi_util as tu
import time
from datetime import datetime
im... | 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 | //! Types used to describe updates on graphs.
use std::convert::TryInto;
use std::fs::File;
use std::sync::Mutex;
use crate::errors::{GraphAnnisCoreError, Result};
use crate::serializer::KeySerializer;
use bincode::Options;
use serde::de::Error as DeserializeError;
use serde::de::{MapAccess, Visitor};
use serde::ser:... | 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 | //! Types used to describe updates on graphs.
use std::convert::TryInto;
use std::fs::File;
use std::sync::Mutex;
use crate::errors::{GraphAnnisCoreError, Result};
use crate::serializer::KeySerializer;
use bincode::Options;
use serde::de::Error as DeserializeError;
use serde::de::{MapAccess, Visitor};
use serde::ser:... | 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 | //! Types used to describe updates on graphs.
use std::convert::TryInto;
use std::fs::File;
use std::sync::Mutex;
use crate::errors::{GraphAnnisCoreError, Result};
use crate::serializer::KeySerializer;
use bincode::Options;
use serde::de::Error as DeserializeError;
use serde::de::{MapAccess, Visitor};
use serde::ser:... | {
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 | //! Types used to describe updates on graphs.
use std::convert::TryInto;
use std::fs::File;
use std::sync::Mutex;
use crate::errors::{GraphAnnisCoreError, Result};
use crate::serializer::KeySerializer;
use bincode::Options;
use serde::de::Error as DeserializeError;
use serde::de::{MapAccess, Visitor};
use serde::ser:... |
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::Result<S::Ok, S::Error>
where
... | {
// 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 | #![warn(clippy::all)]
#![forbid(unsafe_code)]
// Import from other crates.
use csv::ByteRecord;
use humansize::{file_size_opts, FileSize};
use lazy_static::lazy_static;
use log::debug;
use regex::bytes::Regex;
use std::{
borrow::Cow,
fs,
io::{self, prelude::*},
path::PathBuf,
process,
};
use 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 | #![warn(clippy::all)]
#![forbid(unsafe_code)]
// Import from other crates.
use csv::ByteRecord;
use humansize::{file_size_opts, FileSize};
use lazy_static::lazy_static;
use log::debug;
use regex::bytes::Regex;
use std::{
borrow::Cow,
fs,
io::{self, prelude::*},
path::PathBuf,
process,
};
use struct... | // 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 | #![warn(clippy::all)]
#![forbid(unsafe_code)]
// Import from other crates.
use csv::ByteRecord;
use humansize::{file_size_opts, FileSize};
use lazy_static::lazy_static;
use log::debug;
use regex::bytes::Regex;
use std::{
borrow::Cow,
fs,
io::{self, prelude::*},
path::PathBuf,
process,
};
use struct... |
// Remove whitespace from our cells.
if opt.trim_whitespace {
// We do this manually, because the built-in `trim` only
// works on UTF-8 strings, and we work on any
// "ASCII-compatible" encoding.
let first... | {
if null_re.is_match(val) {
val = &[]
}
} | conditional_block |
cmd.go | // Copyright Istio 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 wri... |
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 | // Copyright Istio 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 wri... | () *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 | // Copyright Istio 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 wri... |
}
podIP, _ := netip.ParseAddr(options.InstanceIPVar.Get()) // protobuf encoding of IP_ADDRESS type
if podIP.IsValid() {
proxy.IPAddresses = []string{podIP.String()}
}
// Obtain all the IPs from the node
if ipAddrs, ok := network.GetPrivateIPs(context.Background()); ok {
if len(proxy.IPAddresses) == 1 {
... | {
return nil, fmt.Errorf("Invalid proxy Type: " + string(proxy.Type))
} | conditional_block |
cmd.go | // Copyright Istio 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 wri... | "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 React from "react";
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,
Typograph... | (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 React from "react";
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,
Typograph... |
export default EventForm;
| {
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 React from "react";
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,
Typograph... |
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 React from "react";
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,
Typograph... | <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 | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Benchstat computes and compares statistics about benchmarks.
//
// This package has moved. Please use https://golang.org/x/perf/cmd/benchstat
package main
... | new *Benchstat) (pval float64, err error) {
t, 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
}
func utest(old, new *Benchstat) (pval float64, err error) {
u, err := stats.MannWhitneyUTest(ol... | (old, | identifier_name |
main.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Benchstat computes and compares statistics about benchmarks.
//
// This package has moved. Please use https://golang.org/x/perf/cmd/benchstat
package main
... | c utest(old, new *Benchstat) (pval float64, err error) {
u, err := stats.MannWhitneyUTest(old.RValues, new.RValues, stats.LocationDiffers)
if err != nil {
return -1, err
}
return u.P, nil
}
| 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 | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Benchstat computes and compares statistics about benchmarks.
//
// This package has moved. Please use https://golang.org/x/perf/cmd/benchstat
package main
... | }
func (b *Benchstat) Format(scaler func(float64) string) string {
diff := 1 - b.Min/b.Mean
if d := b.Max/b.Mean - 1; d > diff {
diff = d
}
s := scaler(b.Mean)
if b.Mean == 0 {
s += " "
} else {
s = fmt.Sprintf("%s ±%3s", s, fmt.Sprintf("%.0f%%", diff*100.0))
}
return s
}
// ComputeStats updates the... | } | random_line_split |
main.go | // Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Benchstat computes and compares statistics about benchmarks.
//
// This package has moved. Please use https://golang.org/x/perf/cmd/benchstat
package main
... | }
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 | use crate::{
client,
config::{Configuration, CONFIGURATION},
scanner::SCANNED_URLS,
statistics::{
StatCommand::{self, UpdateUsizeField},
StatField::{LinksExtracted, TotalExpected},
},
utils::{format_url, make_request},
FeroxResponse,
};
use lazy_static::lazy_static;
use regex... |
};
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 | use crate::{
client,
config::{Configuration, CONFIGURATION},
scanner::SCANNED_URLS,
statistics::{
StatCommand::{self, UpdateUsizeField},
StatField::{LinksExtracted, TotalExpected},
},
utils::{format_url, make_request},
FeroxResponse,
};
use lazy_static::lazy_static;
use regex... | (
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 | use crate::{
client,
config::{Configuration, CONFIGURATION},
scanner::SCANNED_URLS,
statistics::{
StatCommand::{self, UpdateUsizeField},
StatField::{LinksExtracted, TotalExpected},
},
utils::{format_url, make_request},
FeroxResponse,
};
use lazy_static::lazy_static;
use regex... |
let links = get_links(&ferox_response, tx).await;
assert!(links.is_empty());
assert_eq!(mock.hits(), 1);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
/// test that /robots.txt is correctly requested given a base url (happy path)
async fn reques... | 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 | use crate::{
client,
config::{Configuration, CONFIGURATION},
scanner::SCANNED_URLS,
statistics::{
StatCommand::{self, UpdateUsizeField},
StatField::{LinksExtracted, TotalExpected},
},
utils::{format_url, make_request},
FeroxResponse,
};
use lazy_static::lazy_static;
use regex... |
}
| {
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 | use crate::input::device::{Device, DeviceType};
use crate::input::event_filter::{EventFilter, EventFilterManager};
use crate::input::events::{InputEvent, KeyboardEvent};
use crate::{config::ConfigManager, input::seat::SeatManager};
use log::debug;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::op... |
}
}
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 | use crate::input::device::{Device, DeviceType};
use crate::input::event_filter::{EventFilter, EventFilterManager};
use crate::input::events::{InputEvent, KeyboardEvent};
use crate::{config::ConfigManager, input::seat::SeatManager};
use log::debug;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::op... | {
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 | use crate::input::device::{Device, DeviceType};
use crate::input::event_filter::{EventFilter, EventFilterManager};
use crate::input::events::{InputEvent, KeyboardEvent};
use crate::{config::ConfigManager, input::seat::SeatManager};
use log::debug;
use serde::{Deserialize, Serialize};
use std::cell::RefCell;
use std::op... | }
}
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 | use {
crossbeam_channel::Sender,
futures_util::stream::StreamExt,
pem::Pem,
pkcs8::{der::Document, AlgorithmIdentifier, ObjectIdentifier},
quinn::{Endpoint, EndpointConfig, ServerConfig},
rcgen::{CertificateParams, DistinguishedName, DnType, SanType},
solana_perf::packet::PacketBatch,
so... | {
#[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 | use {
crossbeam_channel::Sender,
futures_util::stream::StreamExt,
pem::Pem,
pkcs8::{der::Document, AlgorithmIdentifier, ObjectIdentifier},
quinn::{Endpoint, EndpointConfig, ServerConfig},
rcgen::{CertificateParams, DistinguishedName, DnType, SanType},
solana_perf::packet::PacketBatch,
so... | 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 | use {
crossbeam_channel::Sender,
futures_util::stream::StreamExt,
pem::Pem,
pkcs8::{der::Document, AlgorithmIdentifier, ObjectIdentifier},
quinn::{Endpoint, EndpointConfig, ServerConfig},
rcgen::{CertificateParams, DistinguishedName, DnType, SanType},
solana_perf::packet::PacketBatch,
so... |
#[test]
fn test_quic_server_multiple_writes() {
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()... | {
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 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import datetime
from django import template
from django.utils.safestring import mark_safe
from django.utils.html import conditional_... |
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 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import datetime
from django import template
from django.utils.safestring import mark_safe
from django.utils.html import conditional_... | (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 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import datetime
from django import template
from django.utils.safestring import mark_safe
from django.utils.html import conditional_... |
@register.simple_tag
def bob_sort_url(query, field, sort_variable_name, type):
"""Modify the query string of an URL to change the ``sort_variable_name``
argument.
"""
query = query.copy()
if type == 'desc':
query[sort_variable_name] = '-' + field
elif type == 'asc':
query[sort_v... | 'sort_variable_name': sort_variable_name,
}
| random_line_split |
bob.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import json
import datetime
from django import template
from django.utils.safestring import mark_safe
from django.utils.html import conditional_... |
@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 | //! Definitions, constructors, and management for the EnsoGL shapes that are used to draw an edge.
//!
//! The core function of this module is to translate edge layouts into the shape parameters that
//! will implement them.
use crate::prelude::*;
use ensogl::display::shape::*;
use crate::GraphLayers;
use super::lay... |
/// Create a shape object to render the little bit at the target end of the edge, that draws on
/// top of the node.
fn new_target_attachment(&self) -> Rectangle {
let new = Rectangle::new();
new.set_size_x(LINE_WIDTH);
new.set_border_color(color::Rgba::transparent());
new.s... | 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 | //! Definitions, constructors, and management for the EnsoGL shapes that are used to draw an edge.
//!
//! The core function of this module is to translate edge layouts into the shape parameters that
//! will implement them.
use crate::prelude::*;
use ensogl::display::shape::*;
use crate::GraphLayers;
use super::lay... | (
&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 | //! Definitions, constructors, and management for the EnsoGL shapes that are used to draw an edge.
//!
//! The core function of this module is to translate edge layouts into the shape parameters that
//! will implement them.
use crate::prelude::*;
use ensogl::display::shape::*;
use crate::GraphLayers;
use super::lay... |
/// Create a shape object to render the cutout mask for the edge nearby the source node.
fn new_cutout(&self) -> Rectangle {
let cutout = Rectangle::new();
self.display_object().add_child(&cutout);
// FIXME (temporary assumption): Currently we assume that the node background is a recta... | {
let new = SimpleTriangle::from_size(arrow::SIZE);
new.set_pointer_events(false);
self.display_object().add_child(&new);
new.into()
} | identifier_body |
render.rs | //! Definitions, constructors, and management for the EnsoGL shapes that are used to draw an edge.
//!
//! The core function of this module is to translate edge layouts into the shape parameters that
//! will implement them.
use crate::prelude::*;
use ensogl::display::shape::*;
use crate::GraphLayers;
use super::lay... |
} else {
min(a, b)
}
}
fn minor_arc_sector(a: f32, b: f32) -> f32 {
let a = a.abs();
let b = b.abs();
let ab = (a - b).abs();
min(ab, TAU - ab)
}
| {
a
} | conditional_block |
PDDSP_encoder.py | """ Predictive Encoder"""
import sys
sys.path.append('APC')
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import librosa
import ddsp.core as core
import PLP_model.PDDSP_spectral_ops as PDDSP_spectral_ops
def np_diff(a, n=1, axis=-1):
"""Tensorflow implementation of np.diff"""
if... |
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 | """ Predictive Encoder"""
import sys
sys.path.append('APC')
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import librosa
import ddsp.core as core
import PLP_model.PDDSP_spectral_ops as PDDSP_spectral_ops
def np_diff(a, n=1, axis=-1):
"""Tensorflow implementation of np.diff"""
if... |
dominant_tempo = tf.expand_dims(dominant_tempo, axis=0)
out = tf.concat([dominant_tempo, weighted_mean_tempo], axis=0)
return tf.cast(out, dtype=tf.float32)
def encode_song(y, sr, chunks=8,
tempo_min=60,
tempo_max=300,
f_low=400, f_high=450,
... | weighted_mean_tempo = tf.expand_dims(tf.cast(weighted_mean, dtype=tf.float32), axis = 0) | conditional_block |
PDDSP_encoder.py | """ Predictive Encoder"""
import sys
sys.path.append('APC')
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import librosa
import ddsp.core as core
import PLP_model.PDDSP_spectral_ops as PDDSP_spectral_ops
def np_diff(a, n=1, axis=-1):
"""Tensorflow implementation of np.diff"""
if... | (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 | """ Predictive Encoder"""
import sys
sys.path.append('APC')
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import librosa
import ddsp.core as core
import PLP_model.PDDSP_spectral_ops as PDDSP_spectral_ops
def np_diff(a, n=1, axis=-1):
"""Tensorflow implementation of np.diff"""
if... | 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 | import os, sys
import Tkinter
import tkFileDialog
import PIL
from PIL import ImageTk, Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import cv2
from scipy.cluster.vq import kmeans
from skimage import data, img_as_float
#from skimage.measure i... |
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.