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 |
|---|---|---|---|---|
add.go | * Sync paths (sync)
* Forwarded ports (port)
#######################################################
`,
Args: cobra.NoArgs,
}
rootCmd.AddCommand(addCmd)
addSyncCmd := &cobra.Command{
Use: "sync",
Short: "Add a sync path to the devspace",
Long: `
######################################################... |
output := blackfriday.MarkdownCommon([]byte(content))
f, err := os.OpenFile(filepath.Join(os.TempDir(), "Readme.html"), os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
log.Fatal(err)
}
defer f.Close()
_, err = f.Write(output)
if err != nil {
log.Fatal(err)
}
f.Close()
open.Start(f.Name())
}
// RunAddSy... | {
log.Fatal(err)
} | conditional_block |
add.go | AvailableCharts()
return
}
log.StartWait("Search Chart")
repo, version, err := helm.SearchChart(args[0], cmd.packageFlags.ChartVersion, cmd.packageFlags.AppVersion)
log.StopWait()
if err != nil {
log.Fatal(err)
}
log.Done("Chart found")
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
requi... | {
portMappings := make([]*v1.PortMapping, 0, 1)
portMappingsSplitted := strings.Split(portMappingsString, ",")
for _, v := range portMappingsSplitted {
portMapping := strings.Split(v, ":")
if len(portMapping) != 1 && len(portMapping) != 2 {
return nil, fmt.Errorf("Error parsing port mapping: %s", v)
}
... | identifier_body | |
add.go | package mysql --chart-version=0.10.3
#######################################################
`,
Run: cmd.RunAddPackage,
}
addPackageCmd.Flags().StringVar(&cmd.packageFlags.AppVersion, "app-version", "", "App version")
addPackageCmd.Flags().StringVar(&cmd.packageFlags.ChartVersion, "chart-version", "", "Chart v... | isMapEqual | identifier_name | |
add.go |
* Sync paths (sync)
* Forwarded ports (port)
#######################################################
`,
Args: cobra.NoArgs,
}
rootCmd.AddCommand(addCmd)
addSyncCmd := &cobra.Command{
Use: "sync",
Short: "Add a sync path to the devspace",
Long: `
####################################################... | if len(args) != 1 {
helm.PrintAllAvailableCharts()
return
}
log.StartWait("Search Chart")
repo, version, err := helm.SearchChart(args[0], cmd.packageFlags.ChartVersion, cmd.packageFlags.AppVersion)
log.StopWait()
if err != nil {
log.Fatal(err)
}
log.Done("Chart found")
cwd, err := os.Getwd()
if err ... | random_line_split | |
builder.rs | fn debug(&mut self, level: DebugLevel) -> &mut Self |
/// generic attribute.
/// Required. Determines the type of the PLC protocol.
#[inline]
pub fn protocol(&mut self, protocol: Protocol) -> &mut Self {
self.protocol = Some(protocol);
self
}
/// generic attribute.
/// Optional. All tags are treated as arrays. Tag... | {
self.debug = Some(level);
self
} | identifier_body |
builder.rs | pub fn debug(&mut self, level: DebugLevel) -> &mut Self {
self.debug = Some(level);
self
}
/// generic attribute.
/// Required. Determines the type of the PLC protocol.
#[inline]
pub fn protocol(&mut self, protocol: Protocol) -> &mut Self {
self.protocol = Some(pro... | (&mut self, gateway: impl AsRef<str>) -> &mut Self {
self.gateway = Some(gateway.as_ref().to_owned());
self
}
/// - EIP
/// This is the full name of the tag. For program tags, prepend Program:<program name>. where <program name> is the name of the program in which the tag is created
... | gateway | identifier_name |
builder.rs | pub fn debug(&mut self, level: DebugLevel) -> &mut Self {
self.debug = Some(level);
self
}
/// generic attribute.
/// Required. Determines the type of the PLC protocol.
#[inline]
pub fn protocol(&mut self, protocol: Protocol) -> &mut Self {
self.protocol = Some(pro... | }
if let Some(yes) = self.use_connected_msg {
path_buf.push(format!("use_connected_msg={}", yes as u8));
}
}
Protocol::ModBus => {}
}
if let Some(ref gateway) = self.gateway {
path_buf.pus... | random_line_split | |
protocol.go | tedious but need to check for errors on all buffer writes ..
//
func CreateRequestBytes(cmd *Command, args [][]byte) ([]byte, os.Error) | buffer.Write(CRLF);
}
return buffer.Bytes(), nil
}
// Creates a specific Future type for the given Redis command
// and returns it as a generic reference.
//
func CreateFuture(cmd *Command) (future interface{}) {
switch cmd.RespType {
case BOOLEAN:
future = newFutureBool()
case BULK:
future = newFutureByt... | {
cmd_bytes := []byte(cmd.Code)
buffer := bytes.NewBufferString("")
buffer.WriteByte (COUNT_BYTE);
buffer.Write ([]byte (strconv.Itoa(len(args)+1)))
buffer.Write (CRLF);
buffer.WriteByte (SIZE_BYTE);
buffer.Write ([]byte (strconv.Itoa(len(cmd_bytes))))
buffer.Write (CRLF);
buffer.Write (cmd_bytes);
buffer... | identifier_body |
protocol.go | tedious but need to check for errors on all buffer writes ..
//
func CreateRequestBytes(cmd *Command, args [][]byte) ([]byte, os.Error) {
cmd_bytes := []byte(cmd.Code)
buffer := bytes.NewBufferString("")
buffer.WriteByte (COUNT_BYTE);
buffer.Write ([]byte (strconv.Itoa(len(args)+1)))
buffer.Write (CRLF);
buf... | multibulkdata[i] = bulkdata
}
}
return newMultiBulkResponse(multibulkdata, false), nil
}
// ----------------------------------------------------------------------------
// Response
// ----------------------------------------------------------------------------
type Response interface {
IsError() bool
GetMe... | {
sbuf, e := readToCRLF(conn)
if e != nil {
return nil, e
}
if sbuf[0] != SIZE_BYTE {
return nil, os.NewError("<BUG> Expecting a SIZE_BYTE for data item in getMultiBulkResponse")
}
size, e2 := btoi64(sbuf[1:len(sbuf)])
if e2 != nil {
return nil, e2
}
// log.Println("item: bulk data size: ", ... | conditional_block |
protocol.go | line := bytes.NewBuffer(buff).String()
// fmt.Printf("getStatusResponse: %s\n", line);
resp = newStatusResponse(line, error)
}
return resp, fault
}
func getBooleanResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
... | writeNum | identifier_name | |
protocol.go | : tedious but need to check for errors on all buffer writes ..
//
func CreateRequestBytes(cmd *Command, args [][]byte) ([]byte, os.Error) {
cmd_bytes := []byte(cmd.Code)
buffer := bytes.NewBufferString("")
buffer.WriteByte (COUNT_BYTE);
buffer.Write ([]byte (strconv.Itoa(len(args)+1)))
buffer.Write (CRLF);
bu... | }
}
return newMultiBulkResponse(multibulkdata, false), nil
}
// ----------------------------------------------------------------------------
// Response
// ----------------------------------------------------------------------------
type Response interface {
IsError() bool
GetMessage() string
GetBooleanValue(... | random_line_split | |
teste.py |
#retorna a posição de um pixel branco
def encontrar_prox_branco(ponto, img):
i, j = ponto
row, col = img.shape
while(i<row):
while (j<col):
if img[i,j] >= BRANCO:
return(i,j)
j+=1
j=0
i+=1
return (i-1,j)
#retorna o proximo po... | for f in listaDeFronteiras:
if boolPontoNaBorda(ponto, f):
return True
return False | identifier_body | |
teste.py | i+=1
return 0
def boolPontoNaBorda(ponto, fronteira):
return ponto in fronteira #encontrou o primeiro pronto da lista de fronteira
#encontra o primeiro pixel diferente de branco
def find_no_white(img):
row, col = img.shape
for i in range(row):
for j in range(col):
i... | j=ponto_branco[1]
continue
j+=1
j=0 | random_line_split | |
teste.py |
j+=1
j=0
i+=1
return (i-1,j)
#retorna o proximo ponto diferente de branco e que não esta na lista de fronteiras
def find_next_point(img, last_pixel, listaDeFronteiras):
i, j = last_pixel
row, col = img.shape
i+=1
while(i<row):
while (j<col):
... | turn(i,j) | conditional_block | |
teste.py | .shape
for i in range(row):
for j in range(col):
if img[i,j] < BRANCO:
return (i,j)#retorna a posição do pixel
#retorna a posição do array vizinhos
def obterVizinhoID(x, y):
for i in range(9):
if(x == vizinhos[i][0] and y == vizinhos[i][1]):
retu... | listaDeFronteiras=[]
first_no_white_pixel = find_no_white(img)
next_pixel = first_no_white_pixel
i=0
while(next_pixel!=0):
try:
is_fronteira, fronteira = seguidorDeFronteira(img, next_pixel, i)
if is_fronteira: #caso seja uma fronteira valida
... | identifier_name | |
ekhoshim.py | @classmethod
def final_id(cls):
return cls.next_id - 2 # Account for main_start and send_id functions declared in c programs
def __str__(self):
return "{}: {} of {} at line {} in file {}, dependencies are {}".format(self.id, self.funcName, self.name, self.line, self.file, self.funcList)
... |
ELSE_HELPER = "0xDEADFAAB && 0xFEEDBEEF"
NAME_TABLE = {
"if": c_ast.If,
"else": "else",
"dowhile": c_ast.DoWhile,
"for": c_ast.For,
"funcdef": c_ast.FuncDef,
"while": c_ast.While,
"case": c_ast.Case,... | random_line_split | |
ekhoshim.py |
@classmethod
def _get_id(cls):
i = cls.next_id
cls.next_id += 1
return i
@classmethod
def final_id(cls):
return cls.next_id - 2 # Account for main_start and send_id functions declared in c programs
def __str__(self):
return "{}: {} of {} at line {} in file... | self.line = line
self.file = file
self.name = name
self.funcName = funcName
self.funcList = funcList
self.id = self.__class__._get_id() | identifier_body | |
ekhoshim.py | @classmethod
def final_id(cls):
return cls.next_id - 2 # Account for main_start and send_id functions declared in c programs
def __str__(self):
return "{}: {} of {} at line {} in file {}, dependencies are {}".format(self.id, self.funcName, self.name, self.line, self.file, self.funcList)
cla... |
writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
writer.writerow(["ID", "AST Node Type", "Line Number", "File", "Function Name", "Dependencies"])
for r in records:
writer.writerow([r.id, r.name, r.line, r.file, r.funcName, r.funcList])
if record_path not in ("-", "+"):
csvfile.... | csvfile = open(record_path, 'w') | conditional_block |
ekhoshim.py | @classmethod
def final_id(cls):
return cls.next_id - 2 # Account for main_start and send_id functions declared in c programs
def __str__(self):
return "{}: {} of {} at line {} in file {}, dependencies are {}".format(self.id, self.funcName, self.name, self.line, self.file, self.funcList)
... | (input_path, output_path, record_path, track=None, generator_class=DefaultGenerator):
input_lines = lines_from_file(input_path)
output_lines, records = generate(input_lines, track, generator_class)
output = "\n".join(output_lines)
write_to_file(output, args.outputfile)
dump_record_index(records, re... | generate_from_file | identifier_name |
listener.go | struct{})
go func() {
defer close(c.exitchan)
defer c.client.Unregister(registration)
receiveFilteredBlockEvent(blkChan, c.handler, c.stopchan)
}()
case EventChaincode:
// register and wait for one chaincode event
registration, ccChan, err := c.client.RegisterChaincodeEvent(c.chaincodeID, c.eventFilt... | if err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal channel header")
}
td := TransactionDetail{
TxType: common.HeaderType_name[chdr.Type],
TxID: chdr.TxId,
TxTime: time.Unix(chdr.Timestamp.Seconds, int64(chdr.Timestamp.Nanos)).UTC().String(),
ChannelID: chdr.ChannelId,
Actions: ... |
// channel header
chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader) | random_line_split |
listener.go | struct{})
go func() {
defer close(c.exitchan)
defer c.client.Unregister(registration)
receiveFilteredBlockEvent(blkChan, c.handler, c.stopchan)
}()
case EventChaincode:
// register and wait for one chaincode event
registration, ccChan, err := c.client.RegisterChaincodeEvent(c.chaincodeID, c.eventFilt... | (blkEvent *fab.FilteredBlockEvent) *BlockEventDetail {
blk := blkEvent.FilteredBlock
// blkjson, _ := json.Marshal(blk)
// fmt.Println(string(blkjson))
bed := BlockEventDetail{
SourceURL: blkEvent.SourceURL,
Number: blk.Number,
Transactions: []*TransactionDetail{},
}
for _, d := range blk.Filtere... | unmarshalFilteredBlockEvent | identifier_name |
listener.go | *Spec) string {
return fmt.Sprintf("%s.%s.%s.%t", spec.Name, spec.UserName, spec.OrgName, spec.EventType != EventFiltered)
}
// getEventClient returns cached event client or create a new event client if it does not exist
func getEventClient(spec *Spec) (*event.Client, error) {
cid := clientID(spec)
client, ok := c... | {
tm := make(map[string]string)
for k, v := range proposalPayload.TransientMap {
tm[k] = string(v)
}
if tb, err := json.Marshal(tm); err != nil {
logger.Errorf("failed to marshal transient map to JSON: %+v", err)
} else {
ccInput.TransientMap = string(tb)
}
} | conditional_block | |
listener.go | struct{})
go func() {
defer close(c.exitchan)
defer c.client.Unregister(registration)
receiveFilteredBlockEvent(blkChan, c.handler, c.stopchan)
}()
case EventChaincode:
// register and wait for one chaincode event
registration, ccChan, err := c.client.RegisterChaincodeEvent(c.chaincodeID, c.eventFilt... | if actions != nil {
for _, ta := range actions.ChaincodeActions {
ce := ta.GetChaincodeEvent()
if ce != nil && ce.ChaincodeId != "" {
action := ActionDetail{
Chaincode: &ChaincodeID{Name: ce.ChaincodeId},
Result: &ChaincodeResult{
Event: &ChaincodeEvent{
Name: ce.EventNam... | {
blk := blkEvent.FilteredBlock
// blkjson, _ := json.Marshal(blk)
// fmt.Println(string(blkjson))
bed := BlockEventDetail{
SourceURL: blkEvent.SourceURL,
Number: blk.Number,
Transactions: []*TransactionDetail{},
}
for _, d := range blk.FilteredTransactions {
td := TransactionDetail{
TxType:... | identifier_body |
som.py | mode=ig.ALL),dtype=np.int32)
print("Done!")
def build_model(self):
X = self.X_placeholder
W = self.W_placeholder
nsize = self.nborhood_size_placeholder
sigma = self.sigma_placeholder
eps = self.eps_placeholder
#Step 3: Calculate di... | inputScatter3D | identifier_name | |
som.py | d]
#Get topographic error
if (self.s2_1d in self.g.neighbors(self.s1_1d)):
topographic_error = 0
else:
topographic_error = 1
#print("ERROR {}-{};{}-{}".format(self.s1_2d,self.squared_distances[self.s1_1d],\
# ... | OUTPATH += str(k)+ "=" + str(v) + ";" | conditional_block | |
som.py | : Calculate l1 distances
#self.l1 = tf.map_fn(lambda x: tf.norm(x-self.s1_2d,ord=1),self.ID)
self.l1 = tf.gather(self.D,self.s1_1d)
self.mask = tf.reshape(tf.where(self.l1 <= nsize),\
tf.convert_to_tensor([-1]))
#Step 6: Calculate neighborhood fun... |
trace0 = self.input_pca_scatter
W = self.pca.transform(self.W) | random_line_split | |
som.py | self.ds = temp
#Store number of dataset elements and input dimension
self.ds_size = self.getNumElementsOfDataset(self.ds)
self.ds_inputdim = self.getInputShapeOfDataset(self.ds)
#Normalize dataset
temp = self.normalizedDataset(self.ds)
self.d... |
def toOneDim(x):
return x[0]*self.N2 + x[1]
def sum_tuple(x,y):
return(tuple(sum(pair) for pair in zip(x,y)))
edges = []
#Add edges
for i in np.arange(self.N1):
for j in np.arange(self.N2):
curr = (i,j)
... | return(x[0] >= 0 and x[0] < self.N1 and\
x[1] >= 0 and x[1] < self.N2) | identifier_body |
lib.rs | right">
//!
//! # Logos
//!
//! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos).
// The `quote!` macro requires deep recursion.
#![recursion_limit = "196"]
mod generator;
mod error;
mod graph;
mod util;
mod leaf;
use error::Error;
use generator::Generator;
use graph::{G... | let span = item.generics.span();
errors.push(Error::new("Logos currently supports permits a single lifetime generic.").span(span));
None
}
};
let mut parse_attr = |attr: &Attribute| -> Result<(), error::SpannedError> {
if attr.path.is_ident("logos") {
... | {
let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums");
let super_span = item.span();
let size = item.variants.len();
let name = &item.ident;
let mut extras: Option<Ident> = None;
let mut error = None;
let mut mode = Mode::Utf8;
let mut errors = Vec::n... | identifier_body |
lib.rs | right">
//!
//! # Logos
//!
//! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos).
// The `quote!` macro requires deep recursion.
#![recursion_limit = "196"]
mod generator;
mod error;
mod graph;
mod util;
mod leaf;
use error::Error;
use generator::Generator;
use graph::{G... | (input: TokenStream) -> TokenStream {
let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums");
let super_span = item.span();
let size = item.variants.len();
let name = &item.ident;
let mut extras: Option<Ident> = None;
let mut error = None;
let mut mode = Mod... | logos | identifier_name |
lib.rs | ="right">
//!
//! # Logos
//!
//! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos).
// The `quote!` macro requires deep recursion.
#![recursion_limit = "196"]
mod generator;
mod error;
mod graph;
mod util;
mod leaf;
use error::Error;
use generator::Generator;
use graph::... | #[extras] attribute is deprecated. Use #[logos(extras = Type)] instead.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases";
return Err(Error::new(ERR).span(attr.span()));
}
Ok(())
};
for attr in &item.attrs {
... | const ERR: &str = "\ | random_line_split |
lib.rs | right">
//!
//! # Logos
//!
//! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos).
// The `quote!` macro requires deep recursion.
#![recursion_limit = "196"]
mod generator;
mod error;
mod graph;
mod util;
mod leaf;
use error::Error;
use generator::Generator;
use graph::{G... |
}
let root = graph.push(root);
graph.shake(root);
// panic!("{:#?}\n\n{} nodes", graph, graph.nodes().iter().filter_map(|n| n.as_ref()).count());
let generator = Generator::new(name, &this, root, &graph);
let body = generator.generate();
let tokens = impl_logos(quote! {
use ::lo... | {
break;
} | conditional_block |
login.go | err.(translatableerror.MinimumCFAPIVersionNotMetError); ok {
cmd.ui.Warn("Your API version is no longer supported. Upgrade to a newer version of the API.")
} else {
return err
}
}
defer func() {
cmd.ui.Say("")
cmd.ui.ShowConfiguration(cmd.config)
}()
// We thought we would never need to explicitly ... | {
cmd.config.SetSpaceFields(space.SpaceFields)
cmd.ui.Say(T("Targeted space {{.SpaceName}}\n",
map[string]interface{}{"SpaceName": terminal.EntityNameColor(space.Name)}))
} | identifier_body | |
login.go | \"\\\"password\\\"\" (escape quotes if used in password)"),
T("CF_NAME login --sso (CF_NAME will provide a url to obtain a one-time passcode to login)"),
},
Flags: fs,
}
}
func (cmd *Login) Requirements(requirementsFactory requirements.Factory, fc flags.FlagContext) ([]requirements.Requirement, error) {
reqs... | if err != nil {
return errors.New(T("Error finding available spaces\n{{.Err}}", | random_line_split | |
login.go | ", Usage: T("Password")}
fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Org")}
fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")}
fs["sso"] = &flags.BoolFlag{Name: "sso", Usage: T("Prompt for a one-time passcode to login")}
fs["sso-passcode"] = &flags.StringFlag{Name: "sso-passcode", Usage: T("On... | (c flags.FlagContext) (string, bool) {
endpoint := c.String("a")
skipSSL := c.Bool("skip-ssl-validation")
if endpoint == "" {
endpoint = cmd.config.APIEndpoint()
skipSSL = cmd.config.IsSSLDisabled() || skipSSL
}
if endpoint == "" {
endpoint = cmd.ui.Ask(T("API endpoint"))
} else {
cmd.ui.Say(T("API endpo... | decideEndpoint | identifier_name |
login.go | ", Usage: T("Password")}
fs["o"] = &flags.StringFlag{ShortName: "o", Usage: T("Org")}
fs["s"] = &flags.StringFlag{ShortName: "s", Usage: T("Space")}
fs["sso"] = &flags.BoolFlag{Name: "sso", Usage: T("Prompt for a one-time passcode to login")}
fs["sso-passcode"] = &flags.StringFlag{Name: "sso-passcode", Usage: T("On... | else {
credentials["passcode"] = cmd.ui.AskForPassword(passcode.DisplayName)
}
cmd.ui.Say(T("Authenticating..."))
err = cmd.authenticator.Authenticate(credentials)
if err == nil {
cmd.ui.Ok()
cmd.ui.Say("")
break
}
cmd.ui.Say(err.Error())
}
if err != nil {
return errors.New(T("Unable to... | {
credentials["passcode"] = c.String("sso-passcode")
} | conditional_block |
audio.py | "r",
(3000, 4000):"sh",
}
male_fricative_dict = {
(2000, 5000):"s",
(2100, 3000):"z",
(4100,0):"sh",
(3200,4500):"f",
(1500,5500):"j",
}
images_dict = {
" ": "silence.jpeg",
"i": "ee.jpg", #Vowels
"y": "i-y.jpg",
"e": "a-e-i.jpg",
"ɛ": "a-e-i.jpg",
"œ": "a-e-i.jpg",
... | else: # u
nvoiced
if past_status == 'sound':
past_status = 'sound'
formants = GetPeaks(spectrum, fs, start_freq=500,end_freq=6500)
F1 = formants[0]
F2 = formants[1]
return FormantsToPhoneme(F1,F2,sex, male_fricative_dict... | .is_lf:
if past_status == 'sound':
if speech_features.is_sonorant:
past_status = 'sound'
formants = GetPeaks(spectrum, fs, start_freq=100,end_freq=4500)
F1 = formants[0]
F2 = formants[1]
... | conditional_block |
audio.py | "r",
(3000, 4000):"sh",
}
male_fricative_dict = {
(2000, 5000):"s",
(2100, 3000):"z",
(4100,0):"sh",
(3200,4500):"f",
(1500,5500):"j",
}
images_dict = {
" ": "silence.jpeg",
"i": "ee.jpg", #Vowels
"y": "i-y.jpg",
"e": "a-e-i.jpg",
"ɛ": "a-e-i.jpg",
"œ": "a-e-i.jpg",
... | oneme(f1,f2,sex, inv_dict):
if sex == "male":
keys_array = list(inv_dict.keys())
tree = spatial.KDTree(keys_array)
index = tree.query([(f1,f2)])[1][0]
phoneme = inv_dict[keys_array[index]]
return phoneme
elif sex == "female": #change
keys_array = list(male_vowel_i... | tart_freq*(len(buffer)/fs)) #Start looking from start_freq
end_indx = int(end_freq*(len(buffer)/fs)) #End search at end_freq
peaks = peak_pick(spectrum[start_indx:end_indx], pre_max=2, post_max=2, pre_avg=3, post_avg=3, delta=0, wait=0)
return (start_indx+peaks)*(fs/len(buffer))
def FormantsToPh | identifier_body |
audio.py | (F1,F2,sex, male_sonorant_dict)
else: # vowel
past_status = 'sound'
formants = GetPeaks(spectrum, fs)
F1 = formants[0]
F2 = formants[1]
return FormantsToPhoneme(F1,F2,sex, male_vow... | start_indx = int(2000*(len(windowed_frame)/sr)) #Start calculation from 2000Hz
end_indx = int(3000*(len(windowed_frame)/sr)) #End calculation at 300Hz
high_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy | random_line_split | |
audio.py | "r",
(3000, 4000):"sh",
}
male_fricative_dict = {
(2000, 5000):"s",
(2100, 3000):"z",
(4100,0):"sh",
(3200,4500):"f",
(1500,5500):"j",
}
images_dict = {
" ": "silence.jpeg",
"i": "ee.jpg", #Vowels
"y": "i-y.jpg",
"e": "a-e-i.jpg",
"ɛ": "a-e-i.jpg",
"œ": "a-e-i.jpg",
... | rt_freq=150, end_freq=3400):
start_indx = int(start_freq*(len(buffer)/fs)) #Start looking from start_freq
end_indx = int(end_freq*(len(buffer)/fs)) #End search at end_freq
peaks = peak_pick(spectrum[start_indx:end_indx], pre_max=2, post_max=2, pre_avg=3, post_avg=3, delta=0, wait=0)
return (start_indx+... | fs, sta | identifier_name |
main.py | .bat в папке install чтобы автоматически установить библиотеки")
print("EN: Please install packages and try again.")
print("**Open file \"install_packages.bat\" in folder \"install\", it's automatically install needed packages.")
input()
quit()
banner = """
___________________________________... | asyncio.run_coroutine_threadsafe(send_to_all_ids(text), zalupa)
async def send_to_all_ids(text):
uzs = _u.get_user_ids()
for u in uzs:
try:
await send_reply(text, u)
except Exception as e:
print(f'send_to_all_ids error: {e}')
async def send_reply(text,... | dp = Dispatcher(bot)
zalupa = asyncio.new_event_loop()
def notification(text): | random_line_split |
main.py | в папке install чтобы автоматически установить библиотеки")
print("EN: Please install packages and try again.")
print("**Open file \"install_packages.bat\" in folder \"install\", it's automatically install needed packages.")
input()
quit()
banner = """
_______________________________________... | o_all_ids(text):
uzs = _u.get_user_ids()
for u in uzs:
try:
await send_reply(text, u)
except Exception as e:
print(f'send_to_all_ids error: {e}')
async def send_reply(text, user_id):
try:
text = str(text)
if not text: text = 'Empty messa... | c def send_t | identifier_name |
main.py | в папке install чтобы автоматически установить библиотеки")
print("EN: Please install packages and try again.")
print("**Open file \"install_packages.bat\" in folder \"install\", it's automatically install needed packages.")
input()
quit()
banner = """
_______________________________________... | if not text: text = 'Empty message'
if len(text) > message_limit:
for x in _u.split_text(text, message_limit):
await bot.send_message(user_id, x, parse_mode='html', disable_web_page_preview=True)
else:
await bot.send_message(user_id, text, parse_mode='h... | except Exception as e:
print(f'send_to_all_ids error: {e}')
async def send_reply(text, user_id):
try:
text = str(text)
| identifier_body |
main.py | в папке install чтобы автоматически установить библиотеки")
print("EN: Please install packages and try again.")
print("**Open file \"install_packages.bat\" in folder \"install\", it's automatically install needed packages.")
input()
quit()
banner = """
_______________________________________... | tokens['CPU_STAKED'] = accounts_db[account]['tokens']['cpu_staked']
# check tokens
if tokens != accounts_db[account]['tokens']:
# add new token or balance changed
for k, v in tokens.items():
if k not in account... | ed' in accounts_db[account]['tokens'].keys():
| conditional_block |
substrate_like.rs | "))
}
let partial = input.take(
(nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) /
nibble_ops::NIBBLE_PER_BYTE,
)?;
let partial_padding = nibble_ops::number_padding(nibble_count);
let bitmap_range = input.take(BITMAP_LENGTH)?;
let bitmap = Bitmap::decode(&data[bitmap_range])?;
l... | fn extension_node(
_partial: impl Iterator<Item = u8>,
_nbnibble: usize,
_child: ChildReference<<H as Hasher>::Out>,
) -> Vec<u8> {
unreachable!("Codec without extension.")
}
fn branch_node(
_children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>,
_maybe_value: Option<V... | output
}
| random_line_split |
substrate_like.rs | }
let partial = input.take(
(nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) /
nibble_ops::NIBBLE_PER_BYTE,
)?;
let partial_padding = nibble_ops::number_padding(nibble_count);
let bitmap_range = input.take(BITMAP_LENGTH)?;
let bitmap = Bitmap::decode(&data[bitmap_range])?;
let v... | value,
})
}
,
}
}
}
impl<H> NodeCodecT for NodeCodec<H>
where
H: Hasher,
{
const ESCAPE_HEADER: Option<u8> = Some(trie_constants::ESCAPE_COMPACT_HEADER);
type Error = Error;
type HashOut = H::Out;
fn hashed_null_node() -> <H as Hasher>::Out {
H::hash(<Self as NodeCodecT>::empty_node())
}
fn d... | {
let padding = nibble_count % nibble_ops::NIBBLE_PER_BYTE != 0;
// check that the padding is valid (if any)
if padding && nibble_ops::pad_left(data[input.offset]) != 0 {
return Err(CodecError::from("Bad format"))
}
let partial = input.take(
(nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1... | conditional_block |
substrate_like.rs | "))
}
let partial = input.take(
(nibble_count + (nibble_ops::NIBBLE_PER_BYTE - 1)) /
nibble_ops::NIBBLE_PER_BYTE,
)?;
let partial_padding = nibble_ops::number_padding(nibble_count);
let bitmap_range = input.take(BITMAP_LENGTH)?;
let bitmap = Bitmap::decode(&data[bitmap_range])?;
l... | {
Leaf,
BranchNoValue,
BranchWithValue,
HashedValueLeaf,
HashedValueBranch,
}
impl Encode for NodeHeader {
fn encode_to<T: Output + ?Sized>(&self, output: &mut T) {
match self {
NodeHeader::Null => output.push_byte(trie_constants::EMPTY_TRIE),
NodeHeader::Branch(true, nibble_count) =>
encode_size_an... | NodeKind | identifier_name |
substrate_like.rs | mut output = if contains_hash {
partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueLeaf)
} else {
partial_from_iterator_encode(partial, number_nibble, NodeKind::Leaf)
};
match value {
Value::Inline(value) => {
Compact(value.len() as u32).encode_to(&mut output);
output.exte... | {
for b in size_and_prefix_iterator(size, prefix, prefix_mask) {
out.push_byte(b)
}
} | identifier_body | |
table_schema_cache.go | return tableSchemaCache, err
}
tableLog.Debugf("using pagination key %s", paginationKey)
tableSchema.PaginationKey = paginationKey
}
tableSchemaCache[tableSchema.String()] = tableSchema
}
}
logger.WithField("tables", tableSchemaCache.AllTableNames()).Info("table schemas cached")
return ta... | showTablesFrom | identifier_name | |
table_schema_cache.go | (*schema.TableColumn, int, error) {
for i, column := range t.Columns {
if column.Name == name {
return &column, i, nil
}
}
return nil, -1, NonExistingPaginationKeyColumnError(t.Schema, t.Name, name)
}
// NonExistingPaginationKeyColumnError exported to facilitate black box testing
func NonExistingPaginationK... | {
return tables, err
} | conditional_block | |
table_schema_cache.go | Select[0] = quoteField(t.PaginationKey.Columns[0].Name)
columnsToSelect[1] = t.RowMd5Query()
i := 2
for columnName, _ := range t.CompressedColumnsForVerification {
columnsToSelect[i] = quoteField(columnName)
i += 1
}
return fmt.Sprintf(
"SELECT %s FROM %s WHERE %s IN (%s)",
strings.Join(columnsToSelect, "... |
if !targetPaginationKeyExists {
// potential race in the setup
logger.Debugf("tracking as unpaginated table (no pagination key)")
unpaginatedTables = append(unpaginatedTables, table)
continue
}
logger.Debugf("tracking as paginated table with target-pagination %s", targetPaginationKey)
paginatedTab... | } | random_line_split |
table_schema_cache.go | ), nil
}
func (t *TableSchema) RowMd5Query() string {
if t.rowMd5Query != "" {
return t.rowMd5Query
}
columns := make([]schema.TableColumn, 0, len(t.Columns))
for _, column := range t.Columns {
_, isCompressed := t.CompressedColumnsForVerification[column.Name]
_, isIgnored := t.IgnoredColumnsForVerificati... | {
if !t.PaginationKey.IsLinearUnsignedKey() {
return "", UnsupportedPaginationKeyError(t.Schema, t.Name, t.PaginationKey.String())
}
columnsToSelect := make([]string, 2+len(t.CompressedColumnsForVerification))
columnsToSelect[0] = quoteField(t.PaginationKey.Columns[0].Name)
columnsToSelect[1] = t.RowMd5Query()
... | identifier_body | |
metrics.rs | _cfg_fails: SharedMetric,
}
/// Metrics specific to PUT API Requests for counting user triggered actions and/or failures.
#[derive(Default, Serialize)]
pub struct PutRequestsMetrics {
/// Number of PUTs triggering an action on the VM.
pub actions_count: SharedMetric,
/// Number of failures in triggering an... | {
serializer.serialize_i64(chrono::Utc::now().timestamp_millis())
} | identifier_body | |
metrics.rs | /// Errors triggered while using the i8042 device.
pub error_count: SharedMetric,
/// Number of superfluous read intents on this i8042 device.
pub missed_read_count: SharedMetric,
/// Number of superfluous read intents on this i8042 device.
pub missed_write_count: SharedMetric,
/// Bytes rea... | M2_INITIAL_COUNT + NUM_THREADS_TO_SPAWN * NUM_INCREMENTS_PER_THREAD
);
}
| random_line_split | |
metrics.rs | atomic across multiple threads, simply because of the
// fetch_and_add (as opposed to "store(load() + 1)") implementation for atomics.
// TODO: would a stronger ordering make a difference here?
fn add(&self, value: usize) {
self.0.fetch_add(value, Ordering::Relaxed);
}
fn count(&self) -> u... | default | identifier_name | |
metrics.rs | self, value: usize) {
let ref count = self.0;
count.store(count.load(Ordering::Relaxed) + value, Ordering::Relaxed);
}
fn count(&self) -> usize {
self.0.load(Ordering::Relaxed)
}
}
impl Serialize for SimpleMetric {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::... |
res
}
}
// The following structs are used to define a certain organization for the set of metrics we
// are interested in. Whenever the name of a field differs from its ideal textual representation
// in the serialized form, we can use the #[serde(rename = "name")] attribute to, well, rename it.
/// Metr... | {
self.1.store(snapshot, Ordering::Relaxed);
} | conditional_block |
collocations.py | .
"""
def __init__(self, word_fd, ngram_fd):
self.word_fd = word_fd
self.N = word_fd.N()
self.ngram_fd = ngram_fd
@classmethod
def _build_new_documents(
cls, documents, window_size, pad_left=False, pad_right=False, pad_symbol=None
):
"""
Pad the docu... | (self, score_fn):
"""Returns a sequence of (ngram, score) pairs ordered from highest to
lowest score, as determined by the scoring function provided.
"""
return sorted(self._score_ngrams(score_fn), key=lambda t: (-t[1], t[0]))
def nbest(self, score_fn, n):
"""Returns the top... | score_ngrams | identifier_name |
collocations.py | .
"""
def __init__(self, word_fd, ngram_fd):
self.word_fd = word_fd
self.N = word_fd.N()
self.ngram_fd = ngram_fd
@classmethod
def _build_new_documents(
cls, documents, window_size, pad_left=False, pad_right=False, pad_symbol=None
):
"""
Pad the docu... |
def apply_ngram_filter(self, fn):
"""Removes candidate ngrams (w1, w2, ...) where fn(w1, w2, ...)
evaluates to True.
"""
self._apply_filter(lambda ng, f: fn(*ng))
def apply_word_filter(self, fn):
"""Removes candidate ngrams (w1, w2, ...) where any of (fn(w1), fn(w2),
... | """Removes candidate ngrams which have frequency less than min_freq."""
self._apply_filter(lambda ng, freq: freq < min_freq) | identifier_body |
collocations.py | .
"""
def __init__(self, word_fd, ngram_fd):
self.word_fd = word_fd
self.N = word_fd.N()
self.ngram_fd = ngram_fd
@classmethod
def _build_new_documents(
cls, documents, window_size, pad_left=False, pad_right=False, pad_symbol=None
):
"""
Pad the docu... |
n_ix = self.word_fd[w1]
n_xi = self.word_fd[w2]
return score_fn(n_ii, (n_ix, n_xi), n_all)
class TrigramCollocationFinder(AbstractCollocationFinder):
"""A tool for the finding and ranking of trigram collocations or other
association measures. It is often useful to use from_words() rat... | return | conditional_block |
collocations.py |
appearances of words and (possibly non-contiguous) bigrams.
"""
AbstractCollocationFinder.__init__(self, word_fd, bigram_fd)
self.window_size = window_size
@classmethod
def from_words(cls, words, window_size=2):
"""Construct a BigramCollocationFinder for all bigrams in ... | compare_scorer = BigramAssocMeasures.raw_freq
from nltk.corpus import stopwords, webtext | random_line_split | |
decode.rs | DBREF: u8 = 0x0C;
static JSCRIPT: u8 = 0x0D;
static JSCOPE: u8 = 0x0F;
static INT32: u8 = 0x10;
static TSTAMP: u8 = 0x11;
static INT64: u8 = 0x12;
static MINKEY: u8 = 0xFF;
static MAXKEY: u8 = 0x7F;
///Parser object for BSON. T is constrained to Stream<u8>.
pub struct BsonParser<T> {
stream: T
}
///Collects up t... | fn _jscript(&mut self) -> Result<Document, ~str> {
let s = self._string();
//using this to avoid irrefutable pattern error
match s {
UString(s) => Ok(JScript(s)),
_ => Err(~"invalid string found in javascript")
}
}
///Parse a scoped javascript object.... | ///Parse a javascript object. | random_line_split |
decode.rs | REF: u8 = 0x0C;
static JSCRIPT: u8 = 0x0D;
static JSCOPE: u8 = 0x0F;
static INT32: u8 = 0x10;
static TSTAMP: u8 = 0x11;
static INT64: u8 = 0x12;
static MINKEY: u8 = 0xFF;
static MAXKEY: u8 = 0x7F;
///Parser object for BSON. T is constrained to Stream<u8>.
pub struct BsonParser<T> {
stream: T
}
///Collects up to 8... |
///Parse a javascript object.
fn _jscript(&mut self) -> Result<Document, ~str> {
let s = self._string();
//using this to avoid irrefutable pattern error
match s {
UString(s) => Ok(JScript(s)),
_ => Err(~"invalid string found in javascript")
}
}
/... | {
let s = match self._string() {
UString(rs) => rs,
_ => return Err(~"invalid string found in dbref")
};
let d = self.stream.aggregate(12);
Ok(DBRef(s, ~ObjectId(d)))
} | identifier_body |
decode.rs | ,TSTAMP,INT64,MINKEY,MAXKEY]);
self.stream.pass(1);
let mut ret = BsonDocument::new();
while elemcode != None {
let key = self.cstring();
let val: Document = match elemcode {
Some(DOUBLE) => self._double(),
Some(STRING) => self._string(),
... | test_dbref_encode | identifier_name | |
main.go | "cloud.google.com/go/bigtable"
"cloud.google.com/go/pubsub"
"cloud.google.com/go/storage"
"go.skia.org/infra/go/auth"
"go.skia.org/infra/go/common"
"go.skia.org/infra/go/git/gitinfo"
"go.skia.org/infra/go/httputils"
"go.skia.org/infra/go/metrics2"
"go.skia.org/infra/go/paramtools"
"go.skia.org/infra/go/query"... | "strings"
"sync"
"time"
| random_line_split | |
main.go | tools.Params, []float32, paramtools.ParamSet) {
params := []paramtools.Params{}
values := []float32{}
ps := paramtools.ParamSet{}
for testName, allConfigs := range b.Results {
for configName, result := range allConfigs {
key := paramtools.Params(b.Key).Copy()
key["test"] = testName
key["config"] = config... | {
// Wait for PubSub events.
err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
// Set success to true if we should Ack the PubSub message, otherwise
// the message will be Nack'd, and PubSub will try to send the message
// again.
success := false
defer func() {
if s... | conditional_block | |
main.go | "Name of the perf ingester config to use.")
local = flag.Bool("local", false, "Running locally if true. As opposed to in production.")
port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')")
promPort = flag.String("prom_port", ":20000", "Metrics service address (e.g., ':10110')")
)
... |
// processSingleFile parses the contents of a single JSON file and writes the values into BigTable.
//
// If 'branches' is not empty then restrict to ingesting just the branches in the slice.
func processSingleFile(ctx context.Context, store *btts.BigTableTraceStore, vcs vcsinfo.VCS, filename string, r io.Reader, tim... | {
mutex.Lock()
defer mutex.Unlock()
hashCache[hash] = index
} | identifier_body |
main.go | "Name of the perf ingester config to use.")
local = flag.Bool("local", false, "Running locally if true. As opposed to in production.")
port = flag.String("port", ":8000", "HTTP service address (e.g., ':8000')")
promPort = flag.String("prom_port", ":20000", "Metrics service address (e.g., ':10110')")
)
... | (hash string, index int) {
mutex.Lock()
defer mutex.Unlock()
hashCache[hash] = index
}
// processSingleFile parses the contents of a single JSON file and writes the values into BigTable.
//
// If 'branches' is not empty then restrict to ingesting just the branches in the slice.
func processSingleFile(ctx context.C... | indexToCache | identifier_name |
interop.rs | browser_name: "firefox".to_owned(),
status: status.clone(),
})),
}));
}
if !labels.is_empty() {
let mut labels_clause = OrClause {
or: Vec::with_capacity(labels.len()),
};
for label in labels {
labels_clause.push(Clause::Label... |
pub fn write_browser_interop_scores(
browsers: &[&str],
scores: &[interop::ScoreRow],
interop_2023_data: &interop::YearData,
) -> Result<()> {
let browser_columns = interop_columns(&interop_2023_data.focus_areas);
let data_path = Path::new("../docs/interop-2023/scores.csv");
let out_f = File:... | {
let mut total_score: u64 = 0;
for column in columns {
let column = format!("{}-{}", browser, column);
let score = row
.get(&column)
.ok_or_else(|| anyhow!("Failed to get column {}", column))?;
let value: u64 = score
.parse::<u64>()
.map_e... | identifier_body |
interop.rs | browser_name: "firefox".to_owned(),
status: status.clone(),
})),
}));
}
if !labels.is_empty() {
let mut labels_clause = OrClause {
or: Vec::with_capacity(labels.len()),
};
for label in labels {
labels_clause.push(Clause::Label... |
let browser_list = maybe_browser_list.unwrap();
writer.write_record([
"Test",
"Firefox Failures",
"Chrome Failures",
"Safari Failures",
"Bugs",
])?;
for result in results.results.iter() {
let mut scores = vec![String::new(), String::new(), String::new()]... | {
return Err(anyhow!("Didn't get results for all three browsers"));
} | conditional_block |
interop.rs | browser_name: "firefox".to_owned(),
status: status.clone(),
})),
}));
}
if !labels.is_empty() {
let mut labels_clause = OrClause {
or: Vec::with_capacity(labels.len()),
};
for label in labels {
labels_clause.pus... | (wptfyi: &Wptfyi, client: &reqwest::blocking::Client) -> Result<Vec<result::Run>> {
let mut runs = wptfyi.runs();
for product in ["chrome", "firefox", "safari"].iter() {
runs.add_product(product, "experimental")
}
runs.add_label("master");
runs.set_max_count(100);
Ok(run::parse(&get(clie... | get_run_data | identifier_name |
interop.rs | browser_name: "firefox".to_owned(),
status: status.clone(),
})),
}));
}
if !labels.is_empty() {
let mut labels_clause = OrClause {
or: Vec::with_capacity(labels.len()),
};
for label in labels {
labels_clause.pus... | let out_f = File::create(data_path)?;
let mut writer = csv::WriterBuilder::new()
.quote_style(csv::QuoteStyle:: | random_line_split | |
lambda-classes.js | is the param passed in.
// * `grade` receives a `student` object and a `subject` string as arguments and logs out '{student.name} receives a perfect score on {subject}'
class Instructor extends Person {
constructor (instructorAttrs) {
super (instructorAttrs);
this.specialty = instructorAttrs.specialty;
... | // console.log(jimBob.favLanguage) // 'JavaScript',
// console.log(jimBob.catchPhrase) // 'Let\'s take a 5-minute break!'
// jimBob.demo('Banjo');
// jimBob.grade(bigRae, 'Banjo');
// // janeBeth tests:
// console.log(janeBeth.name) // 'JaneBeth'
// console.log(janeBeth.age) // '37',
// console.log(janeBeth.location) ... | // console.log(jimBob.gender) // 'M',
// console.log(jimBob.specialty) // 'Frontend', | random_line_split |
lambda-classes.js | the param passed in.
// * `grade` receives a `student` object and a `subject` string as arguments and logs out '{student.name} receives a perfect score on {subject}'
class Instructor extends Person {
constructor (instructorAttrs) {
super (instructorAttrs);
this.specialty = instructorAttrs.specialty;
t... |
}
// Student Class
// * Now we need some students!
// * Student uses the same attributes that have been set up by Person
// * Student has the following unique props:
// * `previousBackground` i.e. what the Student used to do before Lambda School
// * `className` i.e. CS132
// * `favSubjects`. i.e. an array of t... | {
const points = Math.ceil(Math.random() * 10);
console.log(`${this.name} gives pop Quiz on ${subject}!`);
if (Math.random() > .5){
console.log(`Good answer! ${student.name} receives ${points} points.`);
student.grade += points;
} else {
console.log(`Back to the TK for you! ${student.n... | identifier_body |
lambda-classes.js | the param passed in.
// * `grade` receives a `student` object and a `subject` string as arguments and logs out '{student.name} receives a perfect score on {subject}'
class Instructor extends Person {
constructor (instructorAttrs) {
super (instructorAttrs);
this.specialty = instructorAttrs.specialty;
t... | {
super (pmAttrs);
this.gradClassName = pmAttrs.gradClassName;
this.favInstructor = pmAttrs.favInstructor;
}
standUp (channel) {
console.log(`${this.name} announces to ${channel}, @channel standy times!`)
}
debugsCode (student, subject) {
console.log(`${this.name} debugs ${student.name... | r (pmAttrs) | identifier_name |
lambda-classes.js | the param passed in.
// * `grade` receives a `student` object and a `subject` string as arguments and logs out '{student.name} receives a perfect score on {subject}'
class Instructor extends Person {
constructor (instructorAttrs) {
super (instructorAttrs);
this.specialty = instructorAttrs.specialty;
t... |
}
}
// Student Class
// * Now we need some students!
// * Student uses the same attributes that have been set up by Person
// * Student has the following unique props:
// * `previousBackground` i.e. what the Student used to do before Lambda School
// * `className` i.e. CS132
// * `favSubjects`. i.e. an array ... | {
console.log(`Back to the TK for you! ${student.name} is docked ${points} points.`);
student.grade -= points;
} | conditional_block |
disk.py | s.strip() != '']
# Set disk name
details['Name'] = tmp[4]
# Split each line on ':' skipping those without ':'
tmp = [s.split(':') for s in tmp if ':' in s]
# Add key/value pairs to the details variable and return dict
details.update({key.strip(): value.strip() for (key, value) in tmp})
retur... | def scan_disks():
"""Get details about the attached disks"""
disks = get_disks() | random_line_split | |
disk.py | ValueEx(reg_key, 'PEFirmwareType')[0]
if reg_value == 2:
boot_mode = 'UEFI'
except:
boot_mode = 'Unknown'
return boot_mode
def get_disk_details(disk):
"""Get disk details using DiskPart."""
details = {}
script = [
'select disk {}'.format(disk['Number']),
'detail disk']
# Run
try:... |
def remove_volume_letters(keep=None):
"""Remove all assigned volume letters using DiskPart."""
if not keep:
keep = ''
script = []
for vol in get_volumes():
if vol['Letter'].upper() != keep.upper():
script.append('select volume {}'.format(vol['Number']))
script.append('remove noerr')
#... | """Assign a new letter to a volume using DiskPart."""
if not letter:
# Ignore
return None
script = [
'select volume {}'.format(letter),
'remove noerr',
'assign letter={}'.format(new_letter)]
try:
run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
return new_l... | identifier_body |
disk.py | ValueEx(reg_key, 'PEFirmwareType')[0]
if reg_value == 2:
boot_mode = 'UEFI'
except:
boot_mode = 'Unknown'
return boot_mode
def get_disk_details(disk):
"""Get disk details using DiskPart."""
details = {}
script = [
'select disk {}'.format(disk['Number']),
'detail disk']
# Run
try:... |
return disks
def get_partition_details(disk, partition):
"""Get partition details using DiskPart and fsutil."""
details = {}
script = [
'select disk {}'.format(disk['Number']),
'select partition {}'.format(partition['Number']),
'detail partition']
# Diskpart details
try:
# Run script
... | output = result.stdout.decode().strip()
for tmp in re.findall(r'Disk (\d+)\s+\w+\s+(\d+\s+\w+)', output):
num = tmp[0]
size = human_readable_size(tmp[1])
disks.append({'Number': num, 'Size': size}) | conditional_block |
disk.py |
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# Set disk name
details['Name'] = tmp[4]
# Split each line on ':' skipping those without ':'
tmp = [s.split(':') for s in tmp if ':' in s]
# Add key/value pairs to the details variable and return dict
details.update({key.stri... | scan_disks | identifier_name | |
wiki.py | _salt(length = 5):
return ''.join(random.choice(letters) for x in range(length))
def make_pw_hash(name, pw, salt = None):
if not salt:
salt = make_salt()
h = hashlib.sha256(name + pw + salt).hexdigest()
return '%s,%s' % (salt, h)
def valid_pw(name, password, h):
salt = h.split(',')[0]
... |
# /.json gives json of last 10 entries
class JsonMainHandler(BlogHandler):
def get(self):
self.response.headers['Content-Type']= 'application/json; charset=UTF-8'
posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
posts = list(posts)
js = []
for p in posts:#json libraries in pyth... | self.redirect("/login") | conditional_block |
wiki.py | _salt(length = 5):
return ''.join(random.choice(letters) for x in range(length))
def make_pw_hash(name, pw, salt = None):
if not salt:
salt = make_salt()
h = hashlib.sha256(name + pw + salt).hexdigest()
return '%s,%s' % (salt, h)
def valid_pw(name, password, h):
salt = h.split(',')[0]
... | (self):
self.render_content("login-form.html")
def post(self):
user_name = self.request.get('username')
user_password = self.request.get('password')
u = User.gql("WHERE username = '%s'"%user_name).get()
if u and valid_pw(user_name, user_pa... | get | identifier_name |
wiki.py | _salt(length = 5):
return ''.join(random.choice(letters) for x in range(length))
def make_pw_hash(name, pw, salt = None):
if not salt:
salt = make_salt()
h = hashlib.sha256(name + pw + salt).hexdigest()
return '%s,%s' % (salt, h)
def valid_pw(name, password, h):
salt = h.split(',')[0]
... | email_error = "That's not a valid email"
have_error = True
if have_error:
self.render_content("signup.html"
, username=user_name
, username_error=name_error
, password_error=password_error
, verify_error=verify_error
, email=user_email
, email_error=email_... |
if not valid_email(user_email): | random_line_split |
wiki.py | _salt(length = 5):
return ''.join(random.choice(letters) for x in range(length))
def make_pw_hash(name, pw, salt = None):
if not salt:
salt = make_salt()
h = hashlib.sha256(name + pw + salt).hexdigest()
return '%s,%s' % (salt, h)
def valid_pw(name, password, h):
salt = h.split(',')[0]
... |
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render_str_escaped(self, template, **params):
t = jinja_env_escaped.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
d... | self.response.out.write(*a, **kw) | identifier_body |
keyvault.pb.go | VaultResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_4c3d44d2a4b8394c, []int{1}
}
func (m *KeyVaultResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_KeyVaultResponse.Unmarshal(m, b)
}
func (m *KeyVaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_mess... |
func (m *KeyVault) String() string { return proto.CompactTextString(m) }
func (*KeyVault) ProtoMessage() {}
func (*KeyVault) Descriptor() ([]byte, []int) {
return fileDescriptor_4c3d44d2a4b8394c, []int{2}
}
func (m *KeyVault) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_KeyVault.Unmarshal(m, b)
}
func ... | { *m = KeyVault{} } | identifier_body |
keyvault.pb.go | , 0xa4, 0xa5, 0xae,
0x29, 0x6c, 0x8b, 0x12, 0x5b, 0x2f, 0x1d, 0xea, 0x60, 0x2b, 0xdf, 0xad, 0x9e, 0x94, 0x44, 0x65,
0x8d, 0x19, 0xcb, 0x36, 0xe1, 0x3c, 0xfb, 0x69, 0x0b, 0x63, 0xd0, 0xba, 0xbe, 0x71, 0x75, 0xa4,
0xa9, 0x69, 0xa8, 0x1d, 0x4e, 0x0e, 0xb5, 0xc5, 0x3d, 0x34, 0xf9, 0x15, 0xc1, 0xfd, 0x8f, 0xd8,
0x9d, 0x... | Invoke(context.Context, *KeyVaultRequest) (*KeyVaultResponse, error)
} | random_line_split | |
keyvault.pb.go | Response) Descriptor() ([]byte, []int) {
return fileDescriptor_4c3d44d2a4b8394c, []int{1}
}
func (m *KeyVaultResponse) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_KeyVaultResponse.Unmarshal(m, b)
}
func (m *KeyVaultResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageIn... |
return ""
}
func (m *KeyVault) GetId() string {
if m != nil {
return m.Id
}
return ""
}
func (m *KeyVault) GetSecrets() []*Secret {
if m != nil {
return m.Secrets
}
return nil
}
func (m *KeyVault) GetGroupName() string {
if m != nil {
return m.GroupName
}
return ""
}
func (m *KeyVault) GetStatus() ... | {
return m.Name
} | conditional_block |
keyvault.pb.go | () { *m = KeyVaultRequest{} }
func (m *KeyVaultRequest) String() string { return proto.CompactTextString(m) }
func (*KeyVaultRequest) ProtoMessage() {}
func (*KeyVaultRequest) Descriptor() ([]byte, []int) {
return fileDescriptor_4c3d44d2a4b8394c, []int{0}
}
func (m *KeyVaultRequest) XXX_Unmarshal(b []byte)... | Reset | identifier_name | |
types.d.ts | , SymbolDeclaration, SymbolQuery, SymbolTable } from '@angular/compiler-cli/src/language_services';
export { BuiltinType, DeclarationKind, Definition, PipeInfo, Pipes, Signature, Span, Symbol, SymbolDeclaration, SymbolQuery, SymbolTable }; | *
* A host interface; see `LanguageSeriviceHost`.
*
* @publicApi
*/
export interface TemplateSource {
/**
* The source of the template.
*/
readonly source: string;
/**
* The version of the source. As files are modified the version should change. That is, if the
* `LanguageService` r... | /**
* The information `LanguageService` needs from the `LanguageServiceHost` to describe the content of
* a template and the language context the template is in. | random_line_split |
assets.js | ('a.disabled').removeClass('disabled');
});
$('form').on('click', '.ft-choose-asset:not(.assets-disabled) a', function(e){
e.preventDefault();
var link = $(this);
if (link.is('.disabled')) return;
var self = link.parent('.ft-choose-asset');
target_field = self.attr('data-fiel... | e.preventDefault();
w.trigger('Perch.asset_deselected');
close_asset_chooser();
});
$.getScript(Perch.path+'/core/assets/js/dropzone.js');
$.getScript(Perch.path+'/core/assets/js/spin.min.js');
$.ajax({
url: Perch.path+'/core/apps/assets/async/asset-filter.php',
cache: false,
success: functi... | });
$('.asset-topbar .close').on('click', function(e){ | random_line_split |
assets.js | });
$.getScript(Perch.path+'/core/assets/js/jquery.slimscroll.min.js', function(){
var wh = $(window).height();
var bh = $('body').height();
$('.asset-field .inner').slimScroll({
height: (wh-160)+'px',
railVisible: true,
alwaysVisible: true,
}).bind('slimscroll', function(e, pos){
... | {
var i, l;
for(i=0, l=result.assets.length; i<l; i++) {
asset_index[result.assets[i].id] = result.assets[i];
}
current_page++;
} | conditional_block | |
lib.rs | : 7);
require_root!(WiringPi, Gpio, Phys);
pub trait Pin {}
pub trait Pwm: RequiresRoot + Sized {
fn pwm_pin() -> PwmPin<Self>;
}
pub trait GpioClock: RequiresRoot + Sized {
fn clock_pin() -> ClockPin<Self>;
}
pub trait RequiresRoot: Pin {}
#[derive(Debug, Clone, Cop... | }
///This returns the value read on the supplied analog input pin. You
///will need to register additional analog modules to enable this
///function for devices such as the Gertboard, quick2Wire analog
///board, etc.
pub fn analog_read(&self) -> u16 {
unsafe {
... | High
}
| conditional_block |
lib.rs | passed to the wiringpi library,
/// and called from C code.
///
/// Unfortunately the C implementation does not allow userdata to be passed around,
/// so the callback must be able to determine what caused the interrupt just by the
/// function that was invoked.
///
... | &self, m | identifier_name | |
lib.rs | : 7);
require_root!(WiringPi, Gpio, Phys);
pub trait Pin {}
pub trait Pwm: RequiresRoot + Sized {
fn pwm_pin() -> PwmPin<Self>;
}
pub trait GpioClock: RequiresRoot + Sized {
fn clock_pin() -> ClockPin<Self>;
}
pub trait RequiresRoot: Pin {}
#[derive(Debug, Clone, Cop... | #[inline]
pub fn number(&self) -> libc::c_int {
let &SoftPwmPin(number, _) = self;
number
}
/// Sets the duty cycle.
///
/// `value` has to be in the interval [0,100].
pub fn pwm_write(&self, value: libc::c_int) {
unsafe {
... | unsafe {
bindings::softPwmCreate(pin, 0, 100);
}
SoftPwmPin(pin, PhantomData)
}
| identifier_body |
lib.rs | Phys: 7);
require_root!(WiringPi, Gpio, Phys);
pub trait Pin {}
pub trait Pwm: RequiresRoot + Sized {
fn pwm_pin() -> PwmPin<Self>;
}
pub trait GpioClock: RequiresRoot + Sized {
fn clock_pin() -> ClockPin<Self>;
}
pub trait RequiresRoot: Pin {}
#[derive(Debug, Clone... | ///
/// Unfortunately the C implementation does not allow userdata to be passed around,
/// so the callback must be able to determine what caused the interrupt just by the
/// function that was invoked.
///
/// See https://github.com/Ogeon/rust-wiringpi/pull/28 for
... | /// The callback function does not need to be reentrant.
///
/// The callback must be an actual function (not a closure!), and must be using
/// the extern "C" modifier so that it can be passed to the wiringpi library,
/// and called from C code. | random_line_split |
utils.py | esfully downloaded', filename, statinfo.st_size, 'bytes.')
if is_zipfile:
with zipfile.ZipFile(filepath) as zf:
# zip_dir = zf.namelist()[0]
zf.extractall(dir_path)
elif is_tarfile:
tarfile.open(file_path, 'r:gz').extractall(dir_path)
# def get_vg... |
return image
def flip(image, random_flip):
if random_flip and np.random.choice([True, False]):
image = np.fliplr(image)
return image
def random_rotate_image(image):
angle = np.random.uniform(low=-10.0, high=10.0)
return misc.imrotate(image, angle, 'bicubic')
def random_crop(img, image_si... | sz1 = int(image.shape[1]//2)
sz2 = int(image_size//2)
if random_crop:
diff = sz1-sz2
(h, v) = (np.random.randint(-diff, diff+1), np.random.randint(-diff, diff+1))
else:
(h, v) = (0, 0)
image = image[(sz1-sz2+v):(sz1+sz2+v + 1), (sz1-sz2+h):(sz1+sz2+h +... | conditional_block |
utils.py | esfully downloaded', filename, statinfo.st_size, 'bytes.')
if is_zipfile:
with zipfile.ZipFile(filepath) as zf:
# zip_dir = zf.namelist()[0]
zf.extractall(dir_path)
elif is_tarfile:
tarfile.open(file_path, 'r:gz').extractall(dir_path)
# def get_vg... |
return img[y:y+height, x:x+width]
def get_center_loss(features, labels, alpha, num_classes):
"""获取center loss及center的更新op
Arguments:
features: Tensor,表征样本特征,一般使用某个fc层的输出,shape应该为[batch_size, feature_length].
labels: Tensor,表征样本label,非one-hot编码,shape应为[batch_size].
alpha: 0-1之间的数字... | def random_crop(img, image_size):
width = height = image_size
x = random.randint(0, img.shape[1] - width)
y = random.randint(0, img.shape[0] - height) | random_line_split |
utils.py | esfully downloaded', filename, statinfo.st_size, 'bytes.')
if is_zipfile:
with zipfile.ZipFile(filepath) as zf:
# zip_dir = zf.namelist()[0]
zf.extractall(dir_path)
elif is_tarfile:
tarfile.open(file_path, 'r:gz').extractall(dir_path)
# def get_vg... | (image, mean):
return image+mean
def to_categorial(labels):
one_hot = np.zeros(labels.shape[0], labels.max() + 1)
one_hot[np.array(labels.shape[0], labels)] = 1
return one_hot
def compute_euclidean_distance(x, y, positive=True):
"""
Computes the euclidean distance between two tensorflow variab... | unprocess_image | identifier_name |
utils.py | esfully downloaded', filename, statinfo.st_size, 'bytes.')
if is_zipfile:
with zipfile.ZipFile(filepath) as zf:
# zip_dir = zf.namelist()[0]
zf.extractall(dir_path)
elif is_tarfile:
tarfile.open(file_path, 'r:gz').extractall(dir_path)
# def get_vg... |
def get_variable(weights, name):
init = tf.constant_initializer(weights, dtype=tf.float32)
var = tf.get_variable(name=name, initializer=init, shape=weights.shape)
return var
def weights_variable(shape, stddev=0.02, name=None):
initial = tf.truncated_normal(shape, stddev=stddev)
if name is None:
... | b = tf.Variable(tf.zeros([num], dtype=tf.float32), name=name)
return b | identifier_body |
bloom-atlas.js | };
getAllElementsWithAttribute = function(attr) {
var all, el, matching, _i, _len;
matching = [];
all = document.getElementsByTagName('*');
for (_i = 0, _len = all.length; _i < _len; _i++) {
el = all[_i];
if (el.getAttribute(attr)) {
matching.push(el);
}
}
return ma... | if (useBIRD === false) {
data.BIRD = hash[1]; | random_line_split | |
QTofflineTemplate.py | ():
def __init__(self,dataSource = None,nameList=['Plot1','Plot2','Plot3','Plot4','Plot5','Plot6']):
'''
construct GUI
'''
self.numOfDataToPlot = 500 #nuber of point of x
self.ScalerNum = 2 # every self.ScalerNum we sample once - not used
self.numofPlotWidget=3
self.plotNum = 3 # how many line to... | MyRealTimePlot | identifier_name | |
QTofflineTemplate.py |
plotWidget.setXRange(0, self.numOfDataToPlot)
# set Y range
if i == 0 :
plotWidget.setYRange(-2, 2)
elif i == 1:
plotWidget.setYRange(-180, 180)
else:
plotWidget.setYRange(-2, 2)
layout.addWidget(plotWidget)
self.plotWidgetList.append(plotWidget)
self.startLabel= QtGui.QLabel("St... |
def DrawPic(self):
self.ResetGraph()
startWindowsIdx = int(self.startWindows.text())
endWindowsIdx = int(self.endWindows.text())
startIDX = self.workingIdx[startWindowsIdx][0]
endIDX = self.workingIdx[endWindowsIdx][1]
#start:stop:step
ret = self.RegionWindows(endIDX)
print ret,endIDX
data... | for Dir in Dirs:
# print axis,Dir,"------------------------"
for idx in ret[axis][Dir]:
if idx[1] - idx[0] < 40:
# print idx[0],idx[1],"not enough"
idx.append("not enough")
else:
# print idx[0],idx[1],np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.