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: `
#######################################################
################# devspace add sync ###################
#######################################################
Add a sync path to the devspace
How to use:
devspace add sync --local=app --container=/app
#######################################################
`,
Args: cobra.NoArgs,
Run: cmd.RunAddSync,
}
addCmd.AddCommand(addSyncCmd)
addSyncCmd.Flags().StringVar(&cmd.syncFlags.ResourceType, "resource-type", "pod", "Selected resource type")
addSyncCmd.Flags().StringVar(&cmd.syncFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)")
addSyncCmd.Flags().StringVar(&cmd.syncFlags.LocalPath, "local", "", "Relative local path")
addSyncCmd.Flags().StringVar(&cmd.syncFlags.ContainerPath, "container", "", "Absolute container path")
addSyncCmd.Flags().StringVar(&cmd.syncFlags.ExcludedPaths, "exclude", "", "Comma separated list of paths to exclude (e.g. node_modules/,bin,*.exe)")
addSyncCmd.MarkFlagRequired("local")
addSyncCmd.MarkFlagRequired("container")
addPortCmd := &cobra.Command{
Use: "port",
Short: "Add a new port forward configuration",
Long: `
#######################################################
################ devspace add port ####################
#######################################################
Add a new port mapping that should be forwarded to
the devspace (format is local:remote comma separated):
devspace add port 8080:80,3000
#######################################################
`,
Args: cobra.ExactArgs(1),
Run: cmd.RunAddPort,
}
addPortCmd.Flags().StringVar(&cmd.portFlags.ResourceType, "resource-type", "pod", "Selected resource type")
addPortCmd.Flags().StringVar(&cmd.portFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)")
addCmd.AddCommand(addPortCmd)
addPackageCmd := &cobra.Command{
Use: "package",
Short: "Add a helm chart",
Long: `
#######################################################
############### devspace add package ##################
#######################################################
Adds an existing helm chart to the devspace
(run 'devspace add package' to display all available
helm charts)
Examples:
devspace add package
devspace add package mysql
devspace add package mysql --app-version=5.7.14
devspace add 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 version")
addPackageCmd.Flags().BoolVar(&cmd.packageFlags.SkipQuestion, "skip-question", false, "Skips the question to show the readme in a browser")
addCmd.AddCommand(addPackageCmd)
}
// RunAddPackage executes the add package command logic
func (cmd *AddCmd) RunAddPackage(cobraCmd *cobra.Command, args []string) {
kubectl, err := kubectl.NewClient()
if err != nil {
log.Fatalf("Unable to create new kubectl client: %v", err)
}
helm, err := helmClient.NewClient(kubectl, false)
if err != nil {
log.Fatalf("Error initializing helm client: %v", err)
}
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 != nil {
log.Fatal(err)
}
requirementsFile := filepath.Join(cwd, "chart", "requirements.yaml")
_, err = os.Stat(requirementsFile)
if os.IsNotExist(err) {
entry := "dependencies:\n" +
"- name: \"" + version.GetName() + "\"\n" +
" version: \"" + version.GetVersion() + "\"\n" +
" repository: \"" + repo.URL + "\"\n"
err = ioutil.WriteFile(requirementsFile, []byte(entry), 0600)
if err != nil {
log.Fatal(err)
}
} else {
yamlContents := map[interface{}]interface{}{}
err = yamlutil.ReadYamlFromFile(requirementsFile, yamlContents)
if err != nil {
log.Fatalf("Error parsing %s: %v", requirementsFile, err)
}
dependenciesArr := []interface{}{}
if dependencies, ok := yamlContents["dependencies"]; ok {
dependenciesArr, ok = dependencies.([]interface{})
if ok == false {
log.Fatalf("Error parsing %s: Key dependencies is not an array", requirementsFile)
}
}
dependenciesArr = append(dependenciesArr, map[interface{}]interface{}{
"name": version.GetName(),
"version": version.GetVersion(),
"repository": repo.URL,
})
yamlContents["dependencies"] = dependenciesArr
err = yamlutil.WriteYamlToFile(yamlContents, requirementsFile)
if err != nil {
log.Fatal(err)
}
}
log.StartWait("Update chart dependencies")
err = helm.UpdateDependencies(filepath.Join(cwd, "chart"))
log.StopWait()
if err != nil {
log.Fatal(err)
}
// Check if key already exists
valuesYaml := filepath.Join(cwd, "chart", "values.yaml")
valuesYamlContents := map[interface{}]interface{}{}
err = yamlutil.ReadYamlFromFile(valuesYaml, valuesYamlContents)
if err != nil {
log.Fatalf("Error parsing %s: %v", valuesYaml, err)
}
if _, ok := valuesYamlContents[version.GetName()]; ok == false {
f, err := os.OpenFile(valuesYaml, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatal(err)
}
defer f.Close()
if _, err = f.WriteString("\n# Here you can specify the subcharts values (for more information see: https://github.com/helm/helm/blob/master/docs/chart_template_guide/subcharts_and_globals.md#overriding-values-from-a-parent-chart)\n" + version.GetName() + ": {}\n"); err != nil {
log.Fatal(err)
}
}
log.Donef("Successfully added %s as chart dependency, you can configure the package in 'chart/values.yaml'", version.GetName())
cmd.showReadme(version)
}
func (cmd *AddCmd) showReadme(chartVersion *repo.ChartVersion) {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
if cmd.packageFlags.SkipQuestion {
return
}
showReadme := *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Do you want to open the package README? (y|n)",
DefaultValue: "y",
ValidationRegexPattern: "^(y|n)",
})
if showReadme == "n" {
return
}
content, err := tar.ExtractSingleFileToStringTarGz(filepath.Join(cwd, "chart", "charts", chartVersion.GetName()+"-"+chartVersion.GetVersion()+".tgz"), chartVersion.GetName()+"/README.md")
if err != nil |
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())
}
// RunAddSync executes the add sync command logic
func (cmd *AddCmd) RunAddSync(cobraCmd *cobra.Command, args []string) {
config := configutil.GetConfig(false)
if cmd.syncFlags.Selector == "" {
cmd.syncFlags.Selector = "release=" + *config.DevSpace.Release.Name
}
labelSelectorMap, err := parseSelectors(cmd.syncFlags.Selector)
if err != nil {
log.Fatalf("Error parsing selectors: %s", err.Error())
}
excludedPaths := make([]string, 0, 0)
if cmd.syncFlags.ExcludedPaths != "" {
excludedPathStrings := strings.Split(cmd.syncFlags.ExcludedPaths, ",")
for _, v := range excludedPathStrings {
excludedPath := strings.TrimSpace(v)
excludedPaths = append(excludedPaths, excludedPath)
}
}
workdir, err := os.Getwd()
if err != nil {
log.Fatalf("Unable to determine current workdir: %s", err.Error())
}
cmd.syncFlags.LocalPath = strings.TrimPrefix(cmd.syncFlags.LocalPath, workdir | {
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)
}
requirementsFile := filepath.Join(cwd, "chart", "requirements.yaml")
_, err = os.Stat(requirementsFile)
if os.IsNotExist(err) {
entry := "dependencies:\n" +
"- name: \"" + version.GetName() + "\"\n" +
" version: \"" + version.GetVersion() + "\"\n" +
" repository: \"" + repo.URL + "\"\n"
err = ioutil.WriteFile(requirementsFile, []byte(entry), 0600)
if err != nil {
log.Fatal(err)
}
} else {
yamlContents := map[interface{}]interface{}{}
err = yamlutil.ReadYamlFromFile(requirementsFile, yamlContents)
if err != nil {
log.Fatalf("Error parsing %s: %v", requirementsFile, err)
}
dependenciesArr := []interface{}{}
if dependencies, ok := yamlContents["dependencies"]; ok {
dependenciesArr, ok = dependencies.([]interface{})
if ok == false {
log.Fatalf("Error parsing %s: Key dependencies is not an array", requirementsFile)
}
}
dependenciesArr = append(dependenciesArr, map[interface{}]interface{}{
"name": version.GetName(),
"version": version.GetVersion(),
"repository": repo.URL,
})
yamlContents["dependencies"] = dependenciesArr
err = yamlutil.WriteYamlToFile(yamlContents, requirementsFile)
if err != nil {
log.Fatal(err)
}
}
log.StartWait("Update chart dependencies")
err = helm.UpdateDependencies(filepath.Join(cwd, "chart"))
log.StopWait()
if err != nil {
log.Fatal(err)
}
// Check if key already exists
valuesYaml := filepath.Join(cwd, "chart", "values.yaml")
valuesYamlContents := map[interface{}]interface{}{}
err = yamlutil.ReadYamlFromFile(valuesYaml, valuesYamlContents)
if err != nil {
log.Fatalf("Error parsing %s: %v", valuesYaml, err)
}
if _, ok := valuesYamlContents[version.GetName()]; ok == false {
f, err := os.OpenFile(valuesYaml, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatal(err)
}
defer f.Close()
if _, err = f.WriteString("\n# Here you can specify the subcharts values (for more information see: https://github.com/helm/helm/blob/master/docs/chart_template_guide/subcharts_and_globals.md#overriding-values-from-a-parent-chart)\n" + version.GetName() + ": {}\n"); err != nil {
log.Fatal(err)
}
}
log.Donef("Successfully added %s as chart dependency, you can configure the package in 'chart/values.yaml'", version.GetName())
cmd.showReadme(version)
}
func (cmd *AddCmd) showReadme(chartVersion *repo.ChartVersion) {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
if cmd.packageFlags.SkipQuestion {
return
}
showReadme := *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Do you want to open the package README? (y|n)",
DefaultValue: "y",
ValidationRegexPattern: "^(y|n)",
})
if showReadme == "n" {
return
}
content, err := tar.ExtractSingleFileToStringTarGz(filepath.Join(cwd, "chart", "charts", chartVersion.GetName()+"-"+chartVersion.GetVersion()+".tgz"), chartVersion.GetName()+"/README.md")
if err != nil {
log.Fatal(err)
}
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())
}
// RunAddSync executes the add sync command logic
func (cmd *AddCmd) RunAddSync(cobraCmd *cobra.Command, args []string) {
config := configutil.GetConfig(false)
if cmd.syncFlags.Selector == "" {
cmd.syncFlags.Selector = "release=" + *config.DevSpace.Release.Name
}
labelSelectorMap, err := parseSelectors(cmd.syncFlags.Selector)
if err != nil {
log.Fatalf("Error parsing selectors: %s", err.Error())
}
excludedPaths := make([]string, 0, 0)
if cmd.syncFlags.ExcludedPaths != "" {
excludedPathStrings := strings.Split(cmd.syncFlags.ExcludedPaths, ",")
for _, v := range excludedPathStrings {
excludedPath := strings.TrimSpace(v)
excludedPaths = append(excludedPaths, excludedPath)
}
}
workdir, err := os.Getwd()
if err != nil {
log.Fatalf("Unable to determine current workdir: %s", err.Error())
}
cmd.syncFlags.LocalPath = strings.TrimPrefix(cmd.syncFlags.LocalPath, workdir)
cmd.syncFlags.LocalPath = "./" + strings.TrimPrefix(cmd.syncFlags.LocalPath, "./")
if cmd.syncFlags.ContainerPath[0] != '/' {
log.Fatal("ContainerPath (--container) must start with '/'. Info: There is an issue with MINGW based terminals like git bash.")
}
syncConfig := append(*config.DevSpace.Sync, &v1.SyncConfig{
ResourceType: configutil.String(cmd.syncFlags.ResourceType),
LabelSelector: &labelSelectorMap,
ContainerPath: configutil.String(cmd.syncFlags.ContainerPath),
LocalSubPath: configutil.String(cmd.syncFlags.LocalPath),
ExcludePaths: &excludedPaths,
})
config.DevSpace.Sync = &syncConfig
err = configutil.SaveConfig()
if err != nil {
log.Fatalf("Couldn't save config file: %s", err.Error())
}
}
// RunAddPort executes the add port command logic
func (cmd *AddCmd) RunAddPort(cobraCmd *cobra.Command, args []string) {
config := configutil.GetConfig(false)
if cmd.portFlags.Selector == "" {
cmd.portFlags.Selector = "release=" + *config.DevSpace.Release.Name
}
labelSelectorMap, err := parseSelectors(cmd.portFlags.Selector)
if err != nil {
log.Fatalf("Error parsing selectors: %s", err.Error())
}
portMappings, err := parsePortMappings(args[0])
if err != nil {
log.Fatalf("Error parsing port mappings: %s", err.Error())
}
cmd.insertOrReplacePortMapping(labelSelectorMap, portMappings)
err = configutil.SaveConfig()
if err != nil {
log.Fatalf("Couldn't save config file: %s", err.Error())
}
}
func (cmd *AddCmd) insertOrReplacePortMapping(labelSelectorMap map[string]*string, portMappings []*v1.PortMapping) {
config := configutil.GetConfig(false)
// Check if we should add to existing port mapping
for _, v := range *config.DevSpace.PortForwarding {
var selectors map[string]*string
if v.LabelSelector != nil {
selectors = *v.LabelSelector
} else {
selectors = map[string]*string{}
}
if *v.ResourceType == cmd.portFlags.ResourceType && isMapEqual(selectors, labelSelectorMap) {
portMap := append(*v.PortMappings, portMappings...)
v.PortMappings = &portMap
return
}
}
portMap := append(*config.DevSpace.PortForwarding, &v1.PortForwardingConfig{
ResourceType: configutil.String(cmd.portFlags.ResourceType),
LabelSelector: &labelSelectorMap,
PortMappings: &portMappings,
})
config.DevSpace.PortForwarding = &portMap
}
func isMapEqual(map1 map[string]*string, map2 map[string]*string) bool {
if len(map1) != len(map2) {
return false
}
for k, v := range map1 {
if *map2[k] != *v {
return false
}
}
return true
}
func parsePortMappings(portMappingsString string) ([]*v1.PortMapping, error) | {
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)
}
portMappingStruct := &v1.PortMapping{}
firstPort, err := strconv.Atoi(portMapping[0])
if err != nil {
return nil, err
}
if len(portMapping) == 1 {
portMappingStruct.LocalPort = &firstPort | 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 version")
addPackageCmd.Flags().BoolVar(&cmd.packageFlags.SkipQuestion, "skip-question", false, "Skips the question to show the readme in a browser")
addCmd.AddCommand(addPackageCmd)
}
// RunAddPackage executes the add package command logic
func (cmd *AddCmd) RunAddPackage(cobraCmd *cobra.Command, args []string) {
kubectl, err := kubectl.NewClient()
if err != nil {
log.Fatalf("Unable to create new kubectl client: %v", err)
}
helm, err := helmClient.NewClient(kubectl, false)
if err != nil {
log.Fatalf("Error initializing helm client: %v", err)
}
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 != nil {
log.Fatal(err)
}
requirementsFile := filepath.Join(cwd, "chart", "requirements.yaml")
_, err = os.Stat(requirementsFile)
if os.IsNotExist(err) {
entry := "dependencies:\n" +
"- name: \"" + version.GetName() + "\"\n" +
" version: \"" + version.GetVersion() + "\"\n" +
" repository: \"" + repo.URL + "\"\n"
err = ioutil.WriteFile(requirementsFile, []byte(entry), 0600)
if err != nil {
log.Fatal(err)
}
} else {
yamlContents := map[interface{}]interface{}{}
err = yamlutil.ReadYamlFromFile(requirementsFile, yamlContents)
if err != nil {
log.Fatalf("Error parsing %s: %v", requirementsFile, err)
}
dependenciesArr := []interface{}{}
if dependencies, ok := yamlContents["dependencies"]; ok {
dependenciesArr, ok = dependencies.([]interface{})
if ok == false {
log.Fatalf("Error parsing %s: Key dependencies is not an array", requirementsFile)
}
}
dependenciesArr = append(dependenciesArr, map[interface{}]interface{}{
"name": version.GetName(),
"version": version.GetVersion(),
"repository": repo.URL,
})
yamlContents["dependencies"] = dependenciesArr
err = yamlutil.WriteYamlToFile(yamlContents, requirementsFile)
if err != nil {
log.Fatal(err)
}
}
log.StartWait("Update chart dependencies")
err = helm.UpdateDependencies(filepath.Join(cwd, "chart"))
log.StopWait()
if err != nil {
log.Fatal(err)
}
// Check if key already exists
valuesYaml := filepath.Join(cwd, "chart", "values.yaml")
valuesYamlContents := map[interface{}]interface{}{}
err = yamlutil.ReadYamlFromFile(valuesYaml, valuesYamlContents)
if err != nil {
log.Fatalf("Error parsing %s: %v", valuesYaml, err)
}
if _, ok := valuesYamlContents[version.GetName()]; ok == false {
f, err := os.OpenFile(valuesYaml, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatal(err)
}
defer f.Close()
if _, err = f.WriteString("\n# Here you can specify the subcharts values (for more information see: https://github.com/helm/helm/blob/master/docs/chart_template_guide/subcharts_and_globals.md#overriding-values-from-a-parent-chart)\n" + version.GetName() + ": {}\n"); err != nil {
log.Fatal(err)
}
}
log.Donef("Successfully added %s as chart dependency, you can configure the package in 'chart/values.yaml'", version.GetName())
cmd.showReadme(version)
}
func (cmd *AddCmd) showReadme(chartVersion *repo.ChartVersion) {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
if cmd.packageFlags.SkipQuestion {
return
}
showReadme := *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Do you want to open the package README? (y|n)",
DefaultValue: "y",
ValidationRegexPattern: "^(y|n)",
})
if showReadme == "n" {
return
}
content, err := tar.ExtractSingleFileToStringTarGz(filepath.Join(cwd, "chart", "charts", chartVersion.GetName()+"-"+chartVersion.GetVersion()+".tgz"), chartVersion.GetName()+"/README.md")
if err != nil {
log.Fatal(err)
}
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())
}
// RunAddSync executes the add sync command logic
func (cmd *AddCmd) RunAddSync(cobraCmd *cobra.Command, args []string) {
config := configutil.GetConfig(false)
if cmd.syncFlags.Selector == "" {
cmd.syncFlags.Selector = "release=" + *config.DevSpace.Release.Name
}
labelSelectorMap, err := parseSelectors(cmd.syncFlags.Selector)
if err != nil {
log.Fatalf("Error parsing selectors: %s", err.Error())
}
excludedPaths := make([]string, 0, 0)
if cmd.syncFlags.ExcludedPaths != "" {
excludedPathStrings := strings.Split(cmd.syncFlags.ExcludedPaths, ",")
for _, v := range excludedPathStrings {
excludedPath := strings.TrimSpace(v)
excludedPaths = append(excludedPaths, excludedPath)
}
}
workdir, err := os.Getwd()
if err != nil {
log.Fatalf("Unable to determine current workdir: %s", err.Error())
}
cmd.syncFlags.LocalPath = strings.TrimPrefix(cmd.syncFlags.LocalPath, workdir)
cmd.syncFlags.LocalPath = "./" + strings.TrimPrefix(cmd.syncFlags.LocalPath, "./")
if cmd.syncFlags.ContainerPath[0] != '/' {
log.Fatal("ContainerPath (--container) must start with '/'. Info: There is an issue with MINGW based terminals like git bash.")
}
syncConfig := append(*config.DevSpace.Sync, &v1.SyncConfig{
ResourceType: configutil.String(cmd.syncFlags.ResourceType),
LabelSelector: &labelSelectorMap,
ContainerPath: configutil.String(cmd.syncFlags.ContainerPath),
LocalSubPath: configutil.String(cmd.syncFlags.LocalPath),
ExcludePaths: &excludedPaths,
})
config.DevSpace.Sync = &syncConfig
err = configutil.SaveConfig()
if err != nil {
log.Fatalf("Couldn't save config file: %s", err.Error())
}
}
// RunAddPort executes the add port command logic
func (cmd *AddCmd) RunAddPort(cobraCmd *cobra.Command, args []string) {
config := configutil.GetConfig(false)
if cmd.portFlags.Selector == "" {
cmd.portFlags.Selector = "release=" + *config.DevSpace.Release.Name
}
labelSelectorMap, err := parseSelectors(cmd.portFlags.Selector)
if err != nil {
log.Fatalf("Error parsing selectors: %s", err.Error())
}
portMappings, err := parsePortMappings(args[0])
if err != nil {
log.Fatalf("Error parsing port mappings: %s", err.Error())
}
cmd.insertOrReplacePortMapping(labelSelectorMap, portMappings)
err = configutil.SaveConfig()
if err != nil {
log.Fatalf("Couldn't save config file: %s", err.Error())
}
}
func (cmd *AddCmd) insertOrReplacePortMapping(labelSelectorMap map[string]*string, portMappings []*v1.PortMapping) {
config := configutil.GetConfig(false)
// Check if we should add to existing port mapping
for _, v := range *config.DevSpace.PortForwarding {
var selectors map[string]*string
if v.LabelSelector != nil {
selectors = *v.LabelSelector
} else {
selectors = map[string]*string{}
}
if *v.ResourceType == cmd.portFlags.ResourceType && isMapEqual(selectors, labelSelectorMap) {
portMap := append(*v.PortMappings, portMappings...)
v.PortMappings = &portMap
return
}
}
portMap := append(*config.DevSpace.PortForwarding, &v1.PortForwardingConfig{
ResourceType: configutil.String(cmd.portFlags.ResourceType),
LabelSelector: &labelSelectorMap,
PortMappings: &portMappings,
})
config.DevSpace.PortForwarding = &portMap
}
func | 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: `
#######################################################
################# devspace add sync ###################
#######################################################
Add a sync path to the devspace
How to use:
devspace add sync --local=app --container=/app
#######################################################
`,
Args: cobra.NoArgs,
Run: cmd.RunAddSync,
}
addCmd.AddCommand(addSyncCmd)
addSyncCmd.Flags().StringVar(&cmd.syncFlags.ResourceType, "resource-type", "pod", "Selected resource type")
addSyncCmd.Flags().StringVar(&cmd.syncFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)")
addSyncCmd.Flags().StringVar(&cmd.syncFlags.LocalPath, "local", "", "Relative local path")
addSyncCmd.Flags().StringVar(&cmd.syncFlags.ContainerPath, "container", "", "Absolute container path")
addSyncCmd.Flags().StringVar(&cmd.syncFlags.ExcludedPaths, "exclude", "", "Comma separated list of paths to exclude (e.g. node_modules/,bin,*.exe)")
addSyncCmd.MarkFlagRequired("local")
addSyncCmd.MarkFlagRequired("container")
addPortCmd := &cobra.Command{
Use: "port",
Short: "Add a new port forward configuration",
Long: `
#######################################################
################ devspace add port ####################
#######################################################
Add a new port mapping that should be forwarded to
the devspace (format is local:remote comma separated):
devspace add port 8080:80,3000
#######################################################
`,
Args: cobra.ExactArgs(1),
Run: cmd.RunAddPort,
}
addPortCmd.Flags().StringVar(&cmd.portFlags.ResourceType, "resource-type", "pod", "Selected resource type")
addPortCmd.Flags().StringVar(&cmd.portFlags.Selector, "selector", "", "Comma separated key=value selector list (e.g. release=test)")
addCmd.AddCommand(addPortCmd)
addPackageCmd := &cobra.Command{
Use: "package",
Short: "Add a helm chart",
Long: `
#######################################################
############### devspace add package ##################
#######################################################
Adds an existing helm chart to the devspace
(run 'devspace add package' to display all available
helm charts)
Examples:
devspace add package
devspace add package mysql
devspace add package mysql --app-version=5.7.14
devspace add 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 version")
addPackageCmd.Flags().BoolVar(&cmd.packageFlags.SkipQuestion, "skip-question", false, "Skips the question to show the readme in a browser")
addCmd.AddCommand(addPackageCmd)
}
// RunAddPackage executes the add package command logic
func (cmd *AddCmd) RunAddPackage(cobraCmd *cobra.Command, args []string) {
kubectl, err := kubectl.NewClient()
if err != nil {
log.Fatalf("Unable to create new kubectl client: %v", err)
}
helm, err := helmClient.NewClient(kubectl, false)
if err != nil {
log.Fatalf("Error initializing helm client: %v", err)
} | 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 != nil {
log.Fatal(err)
}
requirementsFile := filepath.Join(cwd, "chart", "requirements.yaml")
_, err = os.Stat(requirementsFile)
if os.IsNotExist(err) {
entry := "dependencies:\n" +
"- name: \"" + version.GetName() + "\"\n" +
" version: \"" + version.GetVersion() + "\"\n" +
" repository: \"" + repo.URL + "\"\n"
err = ioutil.WriteFile(requirementsFile, []byte(entry), 0600)
if err != nil {
log.Fatal(err)
}
} else {
yamlContents := map[interface{}]interface{}{}
err = yamlutil.ReadYamlFromFile(requirementsFile, yamlContents)
if err != nil {
log.Fatalf("Error parsing %s: %v", requirementsFile, err)
}
dependenciesArr := []interface{}{}
if dependencies, ok := yamlContents["dependencies"]; ok {
dependenciesArr, ok = dependencies.([]interface{})
if ok == false {
log.Fatalf("Error parsing %s: Key dependencies is not an array", requirementsFile)
}
}
dependenciesArr = append(dependenciesArr, map[interface{}]interface{}{
"name": version.GetName(),
"version": version.GetVersion(),
"repository": repo.URL,
})
yamlContents["dependencies"] = dependenciesArr
err = yamlutil.WriteYamlToFile(yamlContents, requirementsFile)
if err != nil {
log.Fatal(err)
}
}
log.StartWait("Update chart dependencies")
err = helm.UpdateDependencies(filepath.Join(cwd, "chart"))
log.StopWait()
if err != nil {
log.Fatal(err)
}
// Check if key already exists
valuesYaml := filepath.Join(cwd, "chart", "values.yaml")
valuesYamlContents := map[interface{}]interface{}{}
err = yamlutil.ReadYamlFromFile(valuesYaml, valuesYamlContents)
if err != nil {
log.Fatalf("Error parsing %s: %v", valuesYaml, err)
}
if _, ok := valuesYamlContents[version.GetName()]; ok == false {
f, err := os.OpenFile(valuesYaml, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
log.Fatal(err)
}
defer f.Close()
if _, err = f.WriteString("\n# Here you can specify the subcharts values (for more information see: https://github.com/helm/helm/blob/master/docs/chart_template_guide/subcharts_and_globals.md#overriding-values-from-a-parent-chart)\n" + version.GetName() + ": {}\n"); err != nil {
log.Fatal(err)
}
}
log.Donef("Successfully added %s as chart dependency, you can configure the package in 'chart/values.yaml'", version.GetName())
cmd.showReadme(version)
}
func (cmd *AddCmd) showReadme(chartVersion *repo.ChartVersion) {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
if cmd.packageFlags.SkipQuestion {
return
}
showReadme := *stdinutil.GetFromStdin(&stdinutil.GetFromStdinParams{
Question: "Do you want to open the package README? (y|n)",
DefaultValue: "y",
ValidationRegexPattern: "^(y|n)",
})
if showReadme == "n" {
return
}
content, err := tar.ExtractSingleFileToStringTarGz(filepath.Join(cwd, "chart", "charts", chartVersion.GetName()+"-"+chartVersion.GetVersion()+".tgz"), chartVersion.GetName()+"/README.md")
if err != nil {
log.Fatal(err)
}
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())
}
// RunAddSync executes the add sync command logic
func (cmd *AddCmd) RunAddSync(cobraCmd *cobra.Command, args []string) {
config := configutil.GetConfig(false)
if cmd.syncFlags.Selector == "" {
cmd.syncFlags.Selector = "release=" + *config.DevSpace.Release.Name
}
labelSelectorMap, err := parseSelectors(cmd.syncFlags.Selector)
if err != nil {
log.Fatalf("Error parsing selectors: %s", err.Error())
}
excludedPaths := make([]string, 0, 0)
if cmd.syncFlags.ExcludedPaths != "" {
excludedPathStrings := strings.Split(cmd.syncFlags.ExcludedPaths, ",")
for _, v := range excludedPathStrings {
excludedPath := strings.TrimSpace(v)
excludedPaths = append(excludedPaths, excludedPath)
}
}
workdir, err := os.Getwd()
if err != nil {
log.Fatalf("Unable to determine current workdir: %s", err.Error())
}
cmd.syncFlags.LocalPath = strings.TrimPrefix(cmd.syncFlags.LocalPath, workdir)
| 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. Tags that are not arrays are considered to have a length of one element. This attribute determines how many elements are in the tag. Defaults to one (1)
#[inline]
pub fn element_count(&mut self, count: usize) -> &mut Self {
self.elem_count = Some(count);
self
}
/// generic attribute
/// Required for some protocols or PLC types. This attribute determines the size of a single element of the tag. All tags are considered to be arrays, even those with only one entry. Ignored for Modbus and for ControlLogix-class Allen-Bradley PLCs. This parameter will become optional for as many PLC types as possible
#[inline]
pub fn element_size(&mut self, size: usize) -> &mut Self {
self.elem_size = Some(size);
self
}
/// generic attribute:
/// Optional. An integer number of milliseconds to cache read data.
/// Use this attribute to cause the tag read operations to cache data the requested number of milliseconds. This can be used to lower the actual number of requests against the PLC. Example read_cache_ms=100 will result in read operations no more often than once every 100 milliseconds.
#[inline]
pub fn read_cache_ms(&mut self, millis: usize) -> &mut Self {
self.read_cache_ms = Some(millis);
self
}
/// Required for EIP. Determines the type of the PLC
#[inline]
pub fn plc(&mut self, plc: PlcKind) -> &mut Self {
self.plc = Some(plc);
self
}
/// - EIP
/// IP address or host name.
/// This tells the library what host name or IP address to use for the PLC or the gateway to the PLC (in the case that the PLC is remote).
/// - ModBus
/// Required IP address or host name and optional port
/// This tells the library what host name or IP address to use for the PLC. Can have an optional port at the end, e.g. gateway=10.1.2.3:502 where the :502 part specifies the port.
#[inline]
pub fn gateway(&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
/// - ModBus
/// Required the type and first register number of a tag, e.g. co42 for coil 42 (counts from zero).
/// The supported register type prefixes are co for coil, di for discrete inputs, hr for holding registers and ir for input registers. The type prefix must be present and the register number must be greater than or equal to zero and less than or equal to 65535. Modbus examples: co21 - coil 21, di22 - discrete input 22, hr66 - holding register 66, ir64000 - input register 64000.
///
/// you might want to use `register()` instead of `name()` for Modbus
#[inline]
pub fn name(&mut self, name: impl AsRef<str>) -> &mut Self {
self.name = Some(name.as_ref().to_owned());
self
}
/// set register for Modbus
pub fn register(&mut self, reg: Register) -> &mut Self {
self.name = Some(format!("{}", reg));
self
}
/// - EIP
/// AB: CIP path to PLC CPU. I.e. 1,0.
/// This attribute is required for CompactLogix/ControlLogix tags and for tags using a DH+ protocol bridge (i.e. a DHRIO module) to get to a PLC/5, SLC 500, or MicroLogix PLC on a remote DH+ link. The attribute is ignored if it is not a DH+ bridge route, but will generate a warning if debugging is active. Note that Micro800 connections must not have a path attribute.
/// - ModBus
/// Required The server/unit ID. Must be an integer value between 0 and 255.
/// Servers may support more than one unit or may bridge to other units.
#[inline]
pub fn path(&mut self, path: impl AsRef<str>) -> &mut Self {
self.path = Some(path.as_ref().to_owned());
self
}
/// EIP only
/// Optional 1 = use CIP connection, 0 = use UCMM.
/// Control whether to use connected or unconnected messaging. Only valid on Logix-class PLCs. Connected messaging is required on Micro800 and DH+ bridged links. Default is PLC-specific and link-type specific. Generally you do not need to set this.
#[inline]
pub fn use_connected_msg(&mut self, yes: bool) -> &mut Self {
self.use_connected_msg = Some(yes);
self
}
/// check required attributes or conflict attributes
fn check(&self) -> Result<()> {
//check protocol, required
if self.protocol.is_none() {
return Err(anyhow!("protocol required"));
}
let protocol = self.protocol.unwrap();
// check required attributes
match protocol {
Protocol::EIP => {
//TODO: check gateway, either ip or host name
//check plc, required
if self.plc.is_none() {
return Err(anyhow!("plc required"));
}
let plc = self.plc.unwrap();
if plc == PlcKind::ControlLogix {
if self.path.is_none() {
return Err(anyhow!("path required for controllogix"));
}
return Ok(()); //skip check for elem_size
} else if plc == PlcKind::Micro800 {
if self.path.is_some() {
return Err(anyhow!("path must not provided for micro800"));
}
}
if self.elem_size.is_none() {
return Err(anyhow!("element size required"));
}
}
Protocol::ModBus => {
//TODO: check gateway, host with port
if self.gateway.is_none() {
return Err(anyhow!("gateway required"));
}
if self.name.is_none() {
return Err(anyhow!("name required"));
}
//path is number [0-255]
match self.path {
Some(ref path) => {
let _: u8 = path
.parse()
.or(Err(anyhow!("path is a number in range [0-255]")))?;
}
None => return Err(anyhow!("path required")),
}
if self.elem_size.is_none() {
return Err(anyhow!("element size required"));
}
}
}
Ok(())
}
/// build full tag path
pub fn build(&self) -> Result<String> {
self.check()?;
let mut path_buf = vec![];
let protocol = self.protocol.unwrap();
path_buf.push(format!("protocol={}", protocol));
match protocol {
Protocol::EIP => {
if let Some(plc) = self.plc {
path_buf.push(format!("plc={}", plc));
}
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.push(format!("gateway={}", gateway));
}
if let Some(ref path) = self.path {
path_buf.push(format!("path={}", path));
}
if let Some(ref name) = self.name {
path_buf.push(format!("name={}", name));
}
if let Some(elem_count) = self.elem_count {
path_buf.push(format!("elem_count={}", elem_count));
}
if let Some(elem_size) = self.elem_size {
path_buf.push(format!("elem_size={}", elem_size));
}
if let Some(read_cache_ms) = self.read_cache_ms {
path_buf.push(format!("read_cache_ms={}", read_cache_ms));
}
if let Some(debug) = self.debug {
let level: u8 = debug.into();
path_buf.push(format!("debug={}", level));
}
let buf = path_buf.join("&");
Ok(buf.to_owned())
}
}
/// library supported protocols
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Protocol {
/// EIP protocol
EIP,
/// Modbus protocol
ModBus,
}
impl fmt::Display for Protocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Protocol::EIP => write!(f, "ab-eip"),
Protocol | {
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(protocol);
self
}
/// generic attribute.
/// Optional. All tags are treated as arrays. Tags that are not arrays are considered to have a length of one element. This attribute determines how many elements are in the tag. Defaults to one (1)
#[inline]
pub fn element_count(&mut self, count: usize) -> &mut Self {
self.elem_count = Some(count);
self
}
/// generic attribute
/// Required for some protocols or PLC types. This attribute determines the size of a single element of the tag. All tags are considered to be arrays, even those with only one entry. Ignored for Modbus and for ControlLogix-class Allen-Bradley PLCs. This parameter will become optional for as many PLC types as possible
#[inline]
pub fn element_size(&mut self, size: usize) -> &mut Self {
self.elem_size = Some(size);
self
}
/// generic attribute:
/// Optional. An integer number of milliseconds to cache read data.
/// Use this attribute to cause the tag read operations to cache data the requested number of milliseconds. This can be used to lower the actual number of requests against the PLC. Example read_cache_ms=100 will result in read operations no more often than once every 100 milliseconds.
#[inline]
pub fn read_cache_ms(&mut self, millis: usize) -> &mut Self {
self.read_cache_ms = Some(millis);
self
}
/// Required for EIP. Determines the type of the PLC
#[inline]
pub fn plc(&mut self, plc: PlcKind) -> &mut Self {
self.plc = Some(plc);
self
}
/// - EIP
/// IP address or host name.
/// This tells the library what host name or IP address to use for the PLC or the gateway to the PLC (in the case that the PLC is remote).
/// - ModBus
/// Required IP address or host name and optional port
/// This tells the library what host name or IP address to use for the PLC. Can have an optional port at the end, e.g. gateway=10.1.2.3:502 where the :502 part specifies the port.
#[inline]
pub fn | (&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
/// - ModBus
/// Required the type and first register number of a tag, e.g. co42 for coil 42 (counts from zero).
/// The supported register type prefixes are co for coil, di for discrete inputs, hr for holding registers and ir for input registers. The type prefix must be present and the register number must be greater than or equal to zero and less than or equal to 65535. Modbus examples: co21 - coil 21, di22 - discrete input 22, hr66 - holding register 66, ir64000 - input register 64000.
///
/// you might want to use `register()` instead of `name()` for Modbus
#[inline]
pub fn name(&mut self, name: impl AsRef<str>) -> &mut Self {
self.name = Some(name.as_ref().to_owned());
self
}
/// set register for Modbus
pub fn register(&mut self, reg: Register) -> &mut Self {
self.name = Some(format!("{}", reg));
self
}
/// - EIP
/// AB: CIP path to PLC CPU. I.e. 1,0.
/// This attribute is required for CompactLogix/ControlLogix tags and for tags using a DH+ protocol bridge (i.e. a DHRIO module) to get to a PLC/5, SLC 500, or MicroLogix PLC on a remote DH+ link. The attribute is ignored if it is not a DH+ bridge route, but will generate a warning if debugging is active. Note that Micro800 connections must not have a path attribute.
/// - ModBus
/// Required The server/unit ID. Must be an integer value between 0 and 255.
/// Servers may support more than one unit or may bridge to other units.
#[inline]
pub fn path(&mut self, path: impl AsRef<str>) -> &mut Self {
self.path = Some(path.as_ref().to_owned());
self
}
/// EIP only
/// Optional 1 = use CIP connection, 0 = use UCMM.
/// Control whether to use connected or unconnected messaging. Only valid on Logix-class PLCs. Connected messaging is required on Micro800 and DH+ bridged links. Default is PLC-specific and link-type specific. Generally you do not need to set this.
#[inline]
pub fn use_connected_msg(&mut self, yes: bool) -> &mut Self {
self.use_connected_msg = Some(yes);
self
}
/// check required attributes or conflict attributes
fn check(&self) -> Result<()> {
//check protocol, required
if self.protocol.is_none() {
return Err(anyhow!("protocol required"));
}
let protocol = self.protocol.unwrap();
// check required attributes
match protocol {
Protocol::EIP => {
//TODO: check gateway, either ip or host name
//check plc, required
if self.plc.is_none() {
return Err(anyhow!("plc required"));
}
let plc = self.plc.unwrap();
if plc == PlcKind::ControlLogix {
if self.path.is_none() {
return Err(anyhow!("path required for controllogix"));
}
return Ok(()); //skip check for elem_size
} else if plc == PlcKind::Micro800 {
if self.path.is_some() {
return Err(anyhow!("path must not provided for micro800"));
}
}
if self.elem_size.is_none() {
return Err(anyhow!("element size required"));
}
}
Protocol::ModBus => {
//TODO: check gateway, host with port
if self.gateway.is_none() {
return Err(anyhow!("gateway required"));
}
if self.name.is_none() {
return Err(anyhow!("name required"));
}
//path is number [0-255]
match self.path {
Some(ref path) => {
let _: u8 = path
.parse()
.or(Err(anyhow!("path is a number in range [0-255]")))?;
}
None => return Err(anyhow!("path required")),
}
if self.elem_size.is_none() {
return Err(anyhow!("element size required"));
}
}
}
Ok(())
}
/// build full tag path
pub fn build(&self) -> Result<String> {
self.check()?;
let mut path_buf = vec![];
let protocol = self.protocol.unwrap();
path_buf.push(format!("protocol={}", protocol));
match protocol {
Protocol::EIP => {
if let Some(plc) = self.plc {
path_buf.push(format!("plc={}", plc));
}
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.push(format!("gateway={}", gateway));
}
if let Some(ref path) = self.path {
path_buf.push(format!("path={}", path));
}
if let Some(ref name) = self.name {
path_buf.push(format!("name={}", name));
}
if let Some(elem_count) = self.elem_count {
path_buf.push(format!("elem_count={}", elem_count));
}
if let Some(elem_size) = self.elem_size {
path_buf.push(format!("elem_size={}", elem_size));
}
if let Some(read_cache_ms) = self.read_cache_ms {
path_buf.push(format!("read_cache_ms={}", read_cache_ms));
}
if let Some(debug) = self.debug {
let level: u8 = debug.into();
path_buf.push(format!("debug={}", level));
}
let buf = path_buf.join("&");
Ok(buf.to_owned())
}
}
/// library supported protocols
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Protocol {
/// EIP protocol
EIP,
/// Modbus protocol
ModBus,
}
impl fmt::Display for Protocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Protocol::EIP => write!(f, "ab-eip"),
Protocol | 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(protocol);
self
}
/// generic attribute.
/// Optional. All tags are treated as arrays. Tags that are not arrays are considered to have a length of one element. This attribute determines how many elements are in the tag. Defaults to one (1)
#[inline]
pub fn element_count(&mut self, count: usize) -> &mut Self {
self.elem_count = Some(count);
self
}
/// generic attribute
/// Required for some protocols or PLC types. This attribute determines the size of a single element of the tag. All tags are considered to be arrays, even those with only one entry. Ignored for Modbus and for ControlLogix-class Allen-Bradley PLCs. This parameter will become optional for as many PLC types as possible
#[inline]
pub fn element_size(&mut self, size: usize) -> &mut Self {
self.elem_size = Some(size);
self
}
/// generic attribute:
/// Optional. An integer number of milliseconds to cache read data.
/// Use this attribute to cause the tag read operations to cache data the requested number of milliseconds. This can be used to lower the actual number of requests against the PLC. Example read_cache_ms=100 will result in read operations no more often than once every 100 milliseconds.
#[inline]
pub fn read_cache_ms(&mut self, millis: usize) -> &mut Self {
self.read_cache_ms = Some(millis);
self
}
/// Required for EIP. Determines the type of the PLC
#[inline]
pub fn plc(&mut self, plc: PlcKind) -> &mut Self {
self.plc = Some(plc);
self
}
/// - EIP
/// IP address or host name.
/// This tells the library what host name or IP address to use for the PLC or the gateway to the PLC (in the case that the PLC is remote).
/// - ModBus
/// Required IP address or host name and optional port
/// This tells the library what host name or IP address to use for the PLC. Can have an optional port at the end, e.g. gateway=10.1.2.3:502 where the :502 part specifies the port.
#[inline]
pub fn gateway(&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
/// - ModBus
/// Required the type and first register number of a tag, e.g. co42 for coil 42 (counts from zero).
/// The supported register type prefixes are co for coil, di for discrete inputs, hr for holding registers and ir for input registers. The type prefix must be present and the register number must be greater than or equal to zero and less than or equal to 65535. Modbus examples: co21 - coil 21, di22 - discrete input 22, hr66 - holding register 66, ir64000 - input register 64000.
///
/// you might want to use `register()` instead of `name()` for Modbus
#[inline]
pub fn name(&mut self, name: impl AsRef<str>) -> &mut Self {
self.name = Some(name.as_ref().to_owned());
self
}
/// set register for Modbus
pub fn register(&mut self, reg: Register) -> &mut Self {
self.name = Some(format!("{}", reg));
self
}
/// - EIP
/// AB: CIP path to PLC CPU. I.e. 1,0.
/// This attribute is required for CompactLogix/ControlLogix tags and for tags using a DH+ protocol bridge (i.e. a DHRIO module) to get to a PLC/5, SLC 500, or MicroLogix PLC on a remote DH+ link. The attribute is ignored if it is not a DH+ bridge route, but will generate a warning if debugging is active. Note that Micro800 connections must not have a path attribute.
/// - ModBus
/// Required The server/unit ID. Must be an integer value between 0 and 255.
/// Servers may support more than one unit or may bridge to other units.
#[inline]
pub fn path(&mut self, path: impl AsRef<str>) -> &mut Self {
self.path = Some(path.as_ref().to_owned());
self
}
/// EIP only
/// Optional 1 = use CIP connection, 0 = use UCMM.
/// Control whether to use connected or unconnected messaging. Only valid on Logix-class PLCs. Connected messaging is required on Micro800 and DH+ bridged links. Default is PLC-specific and link-type specific. Generally you do not need to set this.
#[inline]
pub fn use_connected_msg(&mut self, yes: bool) -> &mut Self {
self.use_connected_msg = Some(yes);
self
}
/// check required attributes or conflict attributes
fn check(&self) -> Result<()> {
//check protocol, required
if self.protocol.is_none() {
return Err(anyhow!("protocol required"));
}
let protocol = self.protocol.unwrap();
// check required attributes
match protocol {
Protocol::EIP => {
//TODO: check gateway, either ip or host name
//check plc, required
if self.plc.is_none() {
return Err(anyhow!("plc required"));
}
let plc = self.plc.unwrap();
if plc == PlcKind::ControlLogix {
if self.path.is_none() {
return Err(anyhow!("path required for controllogix"));
}
return Ok(()); //skip check for elem_size
} else if plc == PlcKind::Micro800 {
if self.path.is_some() {
return Err(anyhow!("path must not provided for micro800"));
}
}
if self.elem_size.is_none() {
return Err(anyhow!("element size required"));
}
}
Protocol::ModBus => {
//TODO: check gateway, host with port
if self.gateway.is_none() {
return Err(anyhow!("gateway required"));
}
if self.name.is_none() {
return Err(anyhow!("name required"));
}
//path is number [0-255]
match self.path {
Some(ref path) => {
let _: u8 = path
.parse()
.or(Err(anyhow!("path is a number in range [0-255]")))?;
}
None => return Err(anyhow!("path required")),
}
if self.elem_size.is_none() {
return Err(anyhow!("element size required"));
}
}
}
Ok(())
}
/// build full tag path
pub fn build(&self) -> Result<String> {
self.check()?;
let mut path_buf = vec![];
let protocol = self.protocol.unwrap();
path_buf.push(format!("protocol={}", protocol));
match protocol {
Protocol::EIP => {
if let Some(plc) = self.plc {
path_buf.push(format!("plc={}", plc));
| }
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.push(format!("gateway={}", gateway));
}
if let Some(ref path) = self.path {
path_buf.push(format!("path={}", path));
}
if let Some(ref name) = self.name {
path_buf.push(format!("name={}", name));
}
if let Some(elem_count) = self.elem_count {
path_buf.push(format!("elem_count={}", elem_count));
}
if let Some(elem_size) = self.elem_size {
path_buf.push(format!("elem_size={}", elem_size));
}
if let Some(read_cache_ms) = self.read_cache_ms {
path_buf.push(format!("read_cache_ms={}", read_cache_ms));
}
if let Some(debug) = self.debug {
let level: u8 = debug.into();
path_buf.push(format!("debug={}", level));
}
let buf = path_buf.join("&");
Ok(buf.to_owned())
}
}
/// library supported protocols
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Protocol {
/// EIP protocol
EIP,
/// Modbus protocol
ModBus,
}
impl fmt::Display for Protocol {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Protocol::EIP => write!(f, "ab-eip"),
Protocol | 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 = newFutureBytes()
case MULTI_BULK:
future = newFutureBytesArray()
case NUMBER:
future = newFutureInt64()
case STATUS:
// future = newFutureString();
future = newFutureBool()
case STRING:
future = newFutureString()
// case VIRTUAL: // TODO
// resp, err = getVirtualResponse ();
}
return
}
// Sets the type specific result value from the response for the future reference
// based on the command type.
//
func SetFutureResult(future interface{}, cmd *Command, r Response) {
if r.IsError() {
future.(FutureResult).onError(NewRedisError(r.GetMessage()))
} else {
switch cmd.RespType {
case BOOLEAN:
future.(FutureBool).set(r.GetBooleanValue())
case BULK:
future.(FutureBytes).set(r.GetBulkData())
case MULTI_BULK:
future.(FutureBytesArray).set(r.GetMultiBulkData())
case NUMBER:
future.(FutureInt64).set(r.GetNumberValue())
case STATUS:
// future.(FutureString).set(r.GetMessage());
future.(FutureBool).set(true)
case STRING:
future.(FutureString).set(r.GetStringValue())
// case VIRTUAL: // TODO
// resp, err = getVirtualResponse ();
}
}
}
// Gets the response to the command.
// Any errors (whether runtime or bugs) are returned as os.Error.
// The returned response (regardless of flavor) may have (application level)
// errors as sent from Redis server.
//
func GetResponse(reader *bufio.Reader, cmd *Command) (resp Response, err os.Error) {
switch cmd.RespType {
case BOOLEAN:
resp, err = getBooleanResponse(reader, cmd)
case BULK:
resp, err = getBulkResponse(reader, cmd)
case MULTI_BULK:
resp, err = getMultiBulkResponse(reader, cmd)
case NUMBER:
resp, err = getNumberResponse(reader, cmd)
case STATUS:
resp, err = getStatusResponse(reader, cmd)
case STRING:
resp, err = getStringResponse(reader, cmd)
// case VIRTUAL:
// resp, err = getVirtualResponse ();
}
return
}
// ----------------------------------------------------------------------------
// internal ops
// ----------------------------------------------------------------------------
func getStatusResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
// fmt.Printf("getStatusResponse: about to read line for %s\n", cmd.Code);
buff, error, fault := readLine(conn)
if fault == nil {
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 {
b := buff[1] == TRUE_BYTE
resp = newBooleanResponse(b, error)
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func getStringResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
buff = buff[1:len(buff)]
str := bytes.NewBuffer(buff).String()
resp = newStringResponse(str, error)
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func getNumberResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
buff = buff[1:len(buff)]
numrep := bytes.NewBuffer(buff).String()
num, err := strconv.Atoi64(numrep)
if err == nil {
resp = newNumberResponse(num, error)
} else {
e = os.NewError("<BUG> Expecting a int64 number representation here: " + err.String())
}
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func btoi64(buff []byte) (num int64, e os.Error) {
numrep := bytes.NewBuffer(buff).String()
num, e = strconv.Atoi64(numrep)
if e != nil {
e = os.NewError("<BUG> Expecting a int64 number representation here: " + e.String())
}
return
}
func getBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) {
buf, e1 := readToCRLF(conn)
if e1 != nil {
return nil, e1
}
if buf[0] == ERR_BYTE {
return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil
}
if buf[0] != SIZE_BYTE {
return nil, os.NewError("<BUG> Expecting a SIZE_BYTE in getBulkResponse")
}
num, e2 := btoi64(buf[1:len(buf)])
if e2 != nil {
return nil, e2
}
// log.Println("bulk data size: ", num);
if num < 0 {
return newBulkResponse(nil, false), nil
}
bulkdata, e3 := readBulkData(conn, num)
if e3 != nil {
return nil, e3
}
return newBulkResponse(bulkdata, false), nil
}
func getMultiBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) {
buf, e1 := readToCRLF(conn)
if e1 != nil {
return nil, e1
}
if buf[0] == ERR_BYTE {
return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil
}
if buf[0] != COUNT_BYTE {
return nil, os.NewError("<BUG> Expecting a NUM_BYTE in getMultiBulkResponse")
}
num, e2 := btoi64(buf[1:len(buf)])
if e2 != nil {
return nil, e2
}
log.Println("multibulk data count: ", num)
if num < 0 {
return newMultiBulkResponse(nil, false), nil
}
multibulkdata := make([][]byte, num)
for i := int64(0); i < num; i++ {
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: ", size);
if size < 0 {
multibulkdata[i] = nil
} else {
bulkdata, e3 := readBulkData(conn, size)
if e3 != nil {
return nil, e3
}
multibulkdata[i] = bulkdata
}
}
return newMultiBulkResponse(multibulkdata, false), nil
}
// ----------------------------------------------------------------------------
// Response
// ----------------------------------------------------------------------------
type Response interface {
IsError() bool
GetMessage() string
GetBooleanValue() bool
GetNumberValue() int64
GetStringValue() string
GetBulkData() []byte
GetMultiBulkData() [][]byte
}
type _response struct {
isError bool
msg string
boolval bool
numval int64
stringval string
bulkdata []byte
multibulkdata [][]byte
}
func (r *_response) IsError() bool { return r.isError }
func (r *_response) GetMessage() string { return r.msg }
func (r *_response) GetBooleanValue() bool { return r.boolval }
func (r *_response) GetNumberValue() int64 { return r.numval }
func (r *_response) GetStringValue | {
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.Write (CRLF);
for _, s := range args {
buffer.WriteByte (SIZE_BYTE);
buffer.Write([]byte(strconv.Itoa(len(s))))
buffer.Write(CRLF);
buffer.Write(s); | 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);
buffer.WriteByte (SIZE_BYTE);
buffer.Write ([]byte (strconv.Itoa(len(cmd_bytes))))
buffer.Write (CRLF);
buffer.Write (cmd_bytes);
buffer.Write (CRLF);
for _, s := range args {
buffer.WriteByte (SIZE_BYTE);
buffer.Write([]byte(strconv.Itoa(len(s))))
buffer.Write(CRLF);
buffer.Write(s);
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 = newFutureBytes()
case MULTI_BULK:
future = newFutureBytesArray()
case NUMBER:
future = newFutureInt64()
case STATUS:
// future = newFutureString();
future = newFutureBool()
case STRING:
future = newFutureString()
// case VIRTUAL: // TODO
// resp, err = getVirtualResponse ();
}
return
}
// Sets the type specific result value from the response for the future reference
// based on the command type.
//
func SetFutureResult(future interface{}, cmd *Command, r Response) {
if r.IsError() {
future.(FutureResult).onError(NewRedisError(r.GetMessage()))
} else {
switch cmd.RespType {
case BOOLEAN:
future.(FutureBool).set(r.GetBooleanValue())
case BULK:
future.(FutureBytes).set(r.GetBulkData())
case MULTI_BULK:
future.(FutureBytesArray).set(r.GetMultiBulkData())
case NUMBER:
future.(FutureInt64).set(r.GetNumberValue())
case STATUS:
// future.(FutureString).set(r.GetMessage());
future.(FutureBool).set(true)
case STRING:
future.(FutureString).set(r.GetStringValue())
// case VIRTUAL: // TODO
// resp, err = getVirtualResponse ();
}
}
}
// Gets the response to the command.
// Any errors (whether runtime or bugs) are returned as os.Error.
// The returned response (regardless of flavor) may have (application level)
// errors as sent from Redis server.
//
func GetResponse(reader *bufio.Reader, cmd *Command) (resp Response, err os.Error) {
switch cmd.RespType {
case BOOLEAN:
resp, err = getBooleanResponse(reader, cmd)
case BULK:
resp, err = getBulkResponse(reader, cmd)
case MULTI_BULK:
resp, err = getMultiBulkResponse(reader, cmd)
case NUMBER:
resp, err = getNumberResponse(reader, cmd)
case STATUS:
resp, err = getStatusResponse(reader, cmd)
case STRING:
resp, err = getStringResponse(reader, cmd)
// case VIRTUAL:
// resp, err = getVirtualResponse ();
}
return
}
// ----------------------------------------------------------------------------
// internal ops
// ----------------------------------------------------------------------------
func getStatusResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
// fmt.Printf("getStatusResponse: about to read line for %s\n", cmd.Code);
buff, error, fault := readLine(conn)
if fault == nil {
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 {
b := buff[1] == TRUE_BYTE
resp = newBooleanResponse(b, error)
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func getStringResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
buff = buff[1:len(buff)]
str := bytes.NewBuffer(buff).String()
resp = newStringResponse(str, error)
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func getNumberResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
buff = buff[1:len(buff)]
numrep := bytes.NewBuffer(buff).String()
num, err := strconv.Atoi64(numrep)
if err == nil {
resp = newNumberResponse(num, error)
} else {
e = os.NewError("<BUG> Expecting a int64 number representation here: " + err.String())
}
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func btoi64(buff []byte) (num int64, e os.Error) {
numrep := bytes.NewBuffer(buff).String()
num, e = strconv.Atoi64(numrep)
if e != nil {
e = os.NewError("<BUG> Expecting a int64 number representation here: " + e.String())
}
return
}
func getBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) {
buf, e1 := readToCRLF(conn)
if e1 != nil {
return nil, e1
}
if buf[0] == ERR_BYTE {
return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil
}
if buf[0] != SIZE_BYTE {
return nil, os.NewError("<BUG> Expecting a SIZE_BYTE in getBulkResponse")
}
num, e2 := btoi64(buf[1:len(buf)])
if e2 != nil {
return nil, e2
}
// log.Println("bulk data size: ", num);
if num < 0 {
return newBulkResponse(nil, false), nil
}
bulkdata, e3 := readBulkData(conn, num)
if e3 != nil {
return nil, e3
}
return newBulkResponse(bulkdata, false), nil
}
func getMultiBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) {
buf, e1 := readToCRLF(conn)
if e1 != nil {
return nil, e1
}
if buf[0] == ERR_BYTE {
return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil
}
if buf[0] != COUNT_BYTE {
return nil, os.NewError("<BUG> Expecting a NUM_BYTE in getMultiBulkResponse")
}
num, e2 := btoi64(buf[1:len(buf)])
if e2 != nil {
return nil, e2
}
log.Println("multibulk data count: ", num)
if num < 0 {
return newMultiBulkResponse(nil, false), nil
}
multibulkdata := make([][]byte, num)
for i := int64(0); i < num; i++ | multibulkdata[i] = bulkdata
}
}
return newMultiBulkResponse(multibulkdata, false), nil
}
// ----------------------------------------------------------------------------
// Response
// ----------------------------------------------------------------------------
type Response interface {
IsError() bool
GetMessage() string
GetBooleanValue() bool
GetNumberValue() int64
GetStringValue() string
GetBulkData() []byte
GetMultiBulkData() [][]byte
}
type _response struct {
isError bool
msg string
boolval bool
numval int64
stringval string
bulkdata []byte
multibulkdata [][]byte
}
func (r *_response) IsError() bool { return r.isError }
func (r *_response) GetMessage() string { return r.msg }
func (r *_response) GetBooleanValue() bool { return r.boolval }
func (r *_response) GetNumberValue() int64 { return r.numval }
func (r *_response) GetStringValue | {
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: ", size);
if size < 0 {
multibulkdata[i] = nil
} else {
bulkdata, e3 := readBulkData(conn, size)
if e3 != nil {
return nil, e3
} | 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 {
b := buff[1] == TRUE_BYTE
resp = newBooleanResponse(b, error)
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func getStringResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
buff = buff[1:len(buff)]
str := bytes.NewBuffer(buff).String()
resp = newStringResponse(str, error)
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func getNumberResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
buff = buff[1:len(buff)]
numrep := bytes.NewBuffer(buff).String()
num, err := strconv.Atoi64(numrep)
if err == nil {
resp = newNumberResponse(num, error)
} else {
e = os.NewError("<BUG> Expecting a int64 number representation here: " + err.String())
}
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func btoi64(buff []byte) (num int64, e os.Error) {
numrep := bytes.NewBuffer(buff).String()
num, e = strconv.Atoi64(numrep)
if e != nil {
e = os.NewError("<BUG> Expecting a int64 number representation here: " + e.String())
}
return
}
func getBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) {
buf, e1 := readToCRLF(conn)
if e1 != nil {
return nil, e1
}
if buf[0] == ERR_BYTE {
return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil
}
if buf[0] != SIZE_BYTE {
return nil, os.NewError("<BUG> Expecting a SIZE_BYTE in getBulkResponse")
}
num, e2 := btoi64(buf[1:len(buf)])
if e2 != nil {
return nil, e2
}
// log.Println("bulk data size: ", num);
if num < 0 {
return newBulkResponse(nil, false), nil
}
bulkdata, e3 := readBulkData(conn, num)
if e3 != nil {
return nil, e3
}
return newBulkResponse(bulkdata, false), nil
}
func getMultiBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) {
buf, e1 := readToCRLF(conn)
if e1 != nil {
return nil, e1
}
if buf[0] == ERR_BYTE {
return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil
}
if buf[0] != COUNT_BYTE {
return nil, os.NewError("<BUG> Expecting a NUM_BYTE in getMultiBulkResponse")
}
num, e2 := btoi64(buf[1:len(buf)])
if e2 != nil {
return nil, e2
}
log.Println("multibulk data count: ", num)
if num < 0 {
return newMultiBulkResponse(nil, false), nil
}
multibulkdata := make([][]byte, num)
for i := int64(0); i < num; i++ {
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: ", size);
if size < 0 {
multibulkdata[i] = nil
} else {
bulkdata, e3 := readBulkData(conn, size)
if e3 != nil {
return nil, e3
}
multibulkdata[i] = bulkdata
}
}
return newMultiBulkResponse(multibulkdata, false), nil
}
// ----------------------------------------------------------------------------
// Response
// ----------------------------------------------------------------------------
type Response interface {
IsError() bool
GetMessage() string
GetBooleanValue() bool
GetNumberValue() int64
GetStringValue() string
GetBulkData() []byte
GetMultiBulkData() [][]byte
}
type _response struct {
isError bool
msg string
boolval bool
numval int64
stringval string
bulkdata []byte
multibulkdata [][]byte
}
func (r *_response) IsError() bool { return r.isError }
func (r *_response) GetMessage() string { return r.msg }
func (r *_response) GetBooleanValue() bool { return r.boolval }
func (r *_response) GetNumberValue() int64 { return r.numval }
func (r *_response) GetStringValue() string { return r.stringval }
func (r *_response) GetBulkData() []byte { return r.bulkdata }
func (r *_response) GetMultiBulkData() [][]byte {
return r.multibulkdata
}
func newAndInitResponse(isError bool) (r *_response) {
r = new(_response)
r.isError = isError
r.bulkdata = nil
r.multibulkdata = nil
return
}
func newStatusResponse(msg string, isError bool) Response {
r := newAndInitResponse(isError)
r.msg = msg
return r
}
func newBooleanResponse(val bool, isError bool) Response {
r := newAndInitResponse(isError)
r.boolval = val
return r
}
func newNumberResponse(val int64, isError bool) Response {
r := newAndInitResponse(isError)
r.numval = val
return r
}
func newStringResponse(val string, isError bool) Response {
r := newAndInitResponse(isError)
r.stringval = val
return r
}
func newBulkResponse(val []byte, isError bool) Response {
r := newAndInitResponse(isError)
r.bulkdata = val
return r
}
func newMultiBulkResponse(val [][]byte, isError bool) Response {
r := newAndInitResponse(isError)
r.multibulkdata = val
return r
}
// ----------------------------------------------------------------------------
// Protocol i/o
// ----------------------------------------------------------------------------
// reads all bytes upto CR-LF. (Will eat those last two bytes)
// return the line []byte up to CR-LF
// error returned is NOT ("-ERR ..."). If there is a Redis error
// that is in the line buffer returned
func readToCRLF(reader *bufio.Reader) (buffer []byte, err os.Error) {
// reader := bufio.NewReader(conn);
var buf []byte
buf, err = reader.ReadBytes(CR_BYTE)
if err == nil {
var b byte
b, err = reader.ReadByte()
if err != nil {
return
}
if b != LF_BYTE {
err = os.NewError("<BUG> Expecting a Linefeed byte here!")
}
// log.Println("readToCRLF: ", buf);
buffer = buf[0 : len(buf)-1]
}
return
}
func readLine(conn *bufio.Reader) (buf []byte, error bool, fault os.Error) {
buf, fault = readToCRLF(conn)
if fault == nil {
error = buf[0] == ERR_BYTE
}
return
}
func readBulkData(conn *bufio.Reader, len int64) ([]byte, os.Error) {
buff := make([]byte, len)
_, e := io.ReadFull(conn, buff)
if e != nil {
return nil, NewErrorWithCause(SYSTEM_ERR, "Error while attempting read of bulkdata", e)
}
// fmt.Println ("Read ", n, " bytes. data: ", buff);
crb, e1 := conn.ReadByte()
if e1 != nil {
return nil, os.NewError("Error while attempting read of bulkdata terminal CR:" + e1.String())
}
if crb != CR_BYTE {
return nil, os.NewError("<BUG> bulkdata terminal was not CR as expected")
}
lfb, e2 := conn.ReadByte()
if e2 != nil {
return nil, os.NewError("Error while attempting read of bulkdata terminal LF:" + e2.String())
}
if lfb != LF_BYTE {
return nil, os.NewError("<BUG> bulkdata terminal was not LF as expected.")
}
return buff, nil
}
// convenience func for now
// but slated to optimize converting ints to their []byte literal representation
func | 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);
buffer.WriteByte (SIZE_BYTE);
buffer.Write ([]byte (strconv.Itoa(len(cmd_bytes))))
buffer.Write (CRLF);
buffer.Write (cmd_bytes);
buffer.Write (CRLF);
for _, s := range args {
buffer.WriteByte (SIZE_BYTE);
buffer.Write([]byte(strconv.Itoa(len(s))))
buffer.Write(CRLF);
buffer.Write(s);
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 = newFutureBytes()
case MULTI_BULK:
future = newFutureBytesArray()
case NUMBER:
future = newFutureInt64()
case STATUS:
// future = newFutureString();
future = newFutureBool()
case STRING:
future = newFutureString()
// case VIRTUAL: // TODO
// resp, err = getVirtualResponse ();
}
return
}
// Sets the type specific result value from the response for the future reference
// based on the command type.
//
func SetFutureResult(future interface{}, cmd *Command, r Response) {
if r.IsError() {
future.(FutureResult).onError(NewRedisError(r.GetMessage()))
} else {
switch cmd.RespType {
case BOOLEAN:
future.(FutureBool).set(r.GetBooleanValue())
case BULK:
future.(FutureBytes).set(r.GetBulkData())
case MULTI_BULK:
future.(FutureBytesArray).set(r.GetMultiBulkData())
case NUMBER:
future.(FutureInt64).set(r.GetNumberValue())
case STATUS:
// future.(FutureString).set(r.GetMessage());
future.(FutureBool).set(true)
case STRING:
future.(FutureString).set(r.GetStringValue())
// case VIRTUAL: // TODO
// resp, err = getVirtualResponse ();
}
}
}
// Gets the response to the command.
// Any errors (whether runtime or bugs) are returned as os.Error.
// The returned response (regardless of flavor) may have (application level)
// errors as sent from Redis server.
//
func GetResponse(reader *bufio.Reader, cmd *Command) (resp Response, err os.Error) {
switch cmd.RespType {
case BOOLEAN:
resp, err = getBooleanResponse(reader, cmd)
case BULK:
resp, err = getBulkResponse(reader, cmd)
case MULTI_BULK:
resp, err = getMultiBulkResponse(reader, cmd)
case NUMBER:
resp, err = getNumberResponse(reader, cmd)
case STATUS:
resp, err = getStatusResponse(reader, cmd)
case STRING:
resp, err = getStringResponse(reader, cmd)
// case VIRTUAL:
// resp, err = getVirtualResponse ();
}
return
}
// ----------------------------------------------------------------------------
// internal ops
// ----------------------------------------------------------------------------
func getStatusResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
// fmt.Printf("getStatusResponse: about to read line for %s\n", cmd.Code);
buff, error, fault := readLine(conn)
if fault == nil {
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 {
b := buff[1] == TRUE_BYTE
resp = newBooleanResponse(b, error)
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func getStringResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
buff = buff[1:len(buff)]
str := bytes.NewBuffer(buff).String()
resp = newStringResponse(str, error)
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func getNumberResponse(conn *bufio.Reader, cmd *Command) (resp Response, e os.Error) {
buff, error, fault := readLine(conn)
if fault == nil {
if !error {
buff = buff[1:len(buff)]
numrep := bytes.NewBuffer(buff).String()
num, err := strconv.Atoi64(numrep)
if err == nil {
resp = newNumberResponse(num, error)
} else {
e = os.NewError("<BUG> Expecting a int64 number representation here: " + err.String())
}
} else {
resp = newStatusResponse(bytes.NewBuffer(buff).String(), error)
}
}
return resp, fault
}
func btoi64(buff []byte) (num int64, e os.Error) {
numrep := bytes.NewBuffer(buff).String()
num, e = strconv.Atoi64(numrep)
if e != nil {
e = os.NewError("<BUG> Expecting a int64 number representation here: " + e.String())
}
return
}
func getBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) {
buf, e1 := readToCRLF(conn)
if e1 != nil {
return nil, e1
}
if buf[0] == ERR_BYTE {
return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil
}
if buf[0] != SIZE_BYTE {
return nil, os.NewError("<BUG> Expecting a SIZE_BYTE in getBulkResponse")
}
num, e2 := btoi64(buf[1:len(buf)])
if e2 != nil {
return nil, e2
}
// log.Println("bulk data size: ", num);
if num < 0 {
return newBulkResponse(nil, false), nil
}
bulkdata, e3 := readBulkData(conn, num)
if e3 != nil {
return nil, e3
}
return newBulkResponse(bulkdata, false), nil
}
func getMultiBulkResponse(conn *bufio.Reader, cmd *Command) (Response, os.Error) {
buf, e1 := readToCRLF(conn)
if e1 != nil {
return nil, e1
}
if buf[0] == ERR_BYTE {
return newStatusResponse(bytes.NewBuffer(buf).String(), true), nil
}
if buf[0] != COUNT_BYTE {
return nil, os.NewError("<BUG> Expecting a NUM_BYTE in getMultiBulkResponse")
}
num, e2 := btoi64(buf[1:len(buf)])
if e2 != nil {
return nil, e2
}
log.Println("multibulk data count: ", num)
if num < 0 {
return newMultiBulkResponse(nil, false), nil
}
multibulkdata := make([][]byte, num)
for i := int64(0); i < num; i++ {
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: ", size);
if size < 0 {
multibulkdata[i] = nil
} else {
bulkdata, e3 := readBulkData(conn, size)
if e3 != nil {
return nil, e3
}
multibulkdata[i] = bulkdata | }
}
return newMultiBulkResponse(multibulkdata, false), nil
}
// ----------------------------------------------------------------------------
// Response
// ----------------------------------------------------------------------------
type Response interface {
IsError() bool
GetMessage() string
GetBooleanValue() bool
GetNumberValue() int64
GetStringValue() string
GetBulkData() []byte
GetMultiBulkData() [][]byte
}
type _response struct {
isError bool
msg string
boolval bool
numval int64
stringval string
bulkdata []byte
multibulkdata [][]byte
}
func (r *_response) IsError() bool { return r.isError }
func (r *_response) GetMessage() string { return r.msg }
func (r *_response) GetBooleanValue() bool { return r.boolval }
func (r *_response) GetNumberValue() int64 { return r.numval }
func (r *_response) GetStringValue() | 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 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):
if img[i,j] < BRANCO and img[i, j-1] >= BRANCO:
if bool_nas_Fronteiras((i,j), listaDeFronteiras) == False: #retorna o ponto
return (i,j)
else:#percorre a imagem ate achar um branco
ponto_branco = encontrar_prox_branco((i,j), img)
i=ponto_branco[0]
j=ponto_branco[1]
continue
j+=1
j=0
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):
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]):
return i
#a partir de um pixel inicial percorre a borda da folha
def seguidorDeFronteira(img, first_pixel, i):
row, col = img.shape
fronteira=[]
fronteira.append(first_pixel) # adiciona o primeiro pixel já na lista de fronteira
x = 0
y = 1 #intuito de deixar o código mais legível
b_0 = [first_pixel[x], first_pixel[y]] #b_0[0] = x , b_0[1] = y
c_0 = [0, -1]
anterior_b0 = [0, 0]
cont = 1
contador_de_vizinhos = 0
find_init_border = True
contador=0
while(find_init_border):
indexVizinho=obterVizinhoID(c_0[x], c_0[y])
while(True):
if(indexVizinho == 8):#zerar o clock
indexVizinho = 0
proxB_0 = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]]
proxVizinho = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] #atualiza para o próximo vizinho
if (img[proxVizinho[x]][proxVizinho[y]]<BRANCO) and cont==0: #verifica se o próximo vizinho é BRANCO
b_0 = [proxB_0[x], proxB_0[y]]
check = (b_0[x],b_0[y])
if (first_pixel == check): # quando encontrar o primeiro pixel novamente acaba o seguidor de fronteira
find_init_border = False
break
else:
fronteira.append((b_0[x],b_0[y])) # adiciona na lista de fronteiras
c_0 = [anterior_b0[x]-b_0[x], anterior_b0[y]-b_0[y]]
contador_de_vizinhos = 0
contador+=1
if proxB_0[x] > row: #para quando sair da imagem
return False, (0,0)
break
contador_de_vizinhos +=1
if contador_de_vizinhos == 9: #para quando estiver um loop infinito
return False, (0,0)
cont = 0
anterior_b0 = [proxB_0[x], proxB_0[y]]
indexVizinho += 1 #incrementa o vizinho
tamanho = len(fronteira)
if tamanho>50 and tamanho<25000: #tratamento da imagem 13
return True, fronteira
return False, (0,0)
def grayscale(img):
row, col, bpp = np.shape(img)
img_gray = []
for i in range(0,row):
for j in range(0,col):
b = int(img[i][j][0])
g = int(img[i][j][1])
r = int(img[i][j][2])
pixel = int((b+g+r) / 3)
img_gray.append(pixel)
return img_gray
def remove_ruidos(imagem):
img = imagem.astype('float')
img = img[:,:,0] # convert to 2D array
gray_img = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) #converte para tom de cinza
_,img = cv2.threshold(gray_img, 225,255, cv2.THRESH_BINARY) #converte para binario
img = cv2.medianBlur(img, 5) # remove o ruido
return img
#inicio do algoritmo seguidor de fronteiras
def init(img):
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
listaDeFronteiras.append(fronteira)
last_pixel = next_pixel
next_pixel = find_next_point(img, last_pixel, listaDeFronteiras)
except Exception as e:
print(e)
i+=1
#este tratamento funciona devido a imagem 13
for front in listaDeFronteiras:
if len(front) > 19000:
listaDeFronteiras.remove(front)
print("NUMERO DE FOLHAS ENCONTRADAS:")
print(len(listaDeFronteiras))
return listaDeFronteiras
#retorna a altura, largura, menor linha e menor coluna
def encontra_dimensoes(fronteira):
x = 0
y = 1
list_y = [cord_y[y] for cord_y in fronteira]
list_x = [cord_x[x] for cord_x in fronteira]
x_menor = list_x[0] #pega a primeira posicao
x_maior = max(list_x)
y_menor = min(list_y)
y_maior = max(list_y)
#+3 serve para adicionar uma borda branca
return (x_maior-x_menor)+3 , (y_maior-y_menor)+3, x_menor, y_menor
#cria a imagem da fronteira e retorna uma imagem com a mascara
def criar_imagem_borda(img_borda, fronteira, menor_x, menor_y, index, name_img):
row, col, bpp = img_borda.shape
img_borda_binaria = np.zeros((row, col))
for pixel in fronteira: #transalada os pixeis
nova_coordenada_x = (int(pixel[0])-menor_x)+1
nova_coordenada_y = (int(pixel[1])-menor_y)+1
img_borda[nova_coordenada_x][nova_coordenada_y][0] = 0
img_borda[nova_coordenada_x][nova_coordenada_y][1] = 0
img_borda[nova_coordenada_x][nova_coordenada_y][2] = 0
#criando imagem binaria
img_borda_binaria[nova_coordenada_x][nova_coordenada_y] = 1
nome_imagem = name_img + '-' + str(index) +"-P"+ ".png"
cv2.imwrite(nome_imagem, img_borda)
img_borda_binaria = ndimage.binary_fill_holes(img_borda_binaria).astype(int)
return img_borda_binaria
def criar_im | 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):
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]):
return i
#a partir de um pixel inicial percorre a borda da folha
def seguidorDeFronteira(img, first_pixel, i):
row, col = img.shape
fronteira=[]
fronteira.append(first_pixel) # adiciona o primeiro pixel já na lista de fronteira
x = 0
y = 1 #intuito de deixar o código mais legível
b_0 = [first_pixel[x], first_pixel[y]] #b_0[0] = x , b_0[1] = y
c_0 = [0, -1]
anterior_b0 = [0, 0]
cont = 1
contador_de_vizinhos = 0
find_init_border = True
contador=0
while(find_init_border):
indexVizinho=obterVizinhoID(c_0[x], c_0[y])
while(True):
if(indexVizinho == 8):#zerar o clock
indexVizinho = 0
proxB_0 = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]]
proxVizinho = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] #atualiza para o próximo vizinho
if (img[proxVizinho[x]][proxVizinho[y]]<BRANCO) and cont==0: #verifica se o próximo vizinho é BRANCO
b_0 = [proxB_0[x], proxB_0[y]]
check = (b_0[x],b_0[y])
if (first_pixel == check): # quando encontrar o primeiro pixel novamente acaba o seguidor de fronteira
find_init_border = False
break
else:
fronteira.append((b_0[x],b_0[y])) # adiciona na lista de fronteiras
c_0 = [anterior_b0[x]-b_0[x], anterior_b0[y]-b_0[y]]
contador_de_vizinhos = 0
contador+=1
if proxB_0[x] > row: #para quando sair da imagem
return False, (0,0)
break
contador_de_vizinhos +=1
if contador_de_vizinhos == 9: #para quando estiver um loop infinito
return False, (0,0)
cont = 0
anterior_b0 = [proxB_0[x], proxB_0[y]]
indexVizinho += 1 #incrementa o vizinho
tamanho = len(fronteira)
if tamanho>50 and tamanho<25000: #tratamento da imagem 13
return True, fronteira
return False, (0,0)
def grayscale(img):
row, col, bpp = np.shape(img)
img_gray = []
for i in range(0,row):
for j in range(0,col):
b = int(img[i][j][0])
g = int(img[i][j][1])
r = int(img[i][j][2])
pixel = int((b+g+r) / 3)
img_gray.append(pixel)
return img_gray
def remove_ruidos(imagem):
img = imagem.astype('float')
img = img[:,:,0] # convert to 2D array
gray_img = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) #converte para tom de cinza
_,img = cv2.threshold(gray_img, 225,255, cv2.THRESH_BINARY) #converte para binario
img = cv2.medianBlur(img, 5) # remove o ruido
return img
#inicio do algoritmo seguidor de fronteiras
def init(img):
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
listaDeFronteiras.append(fronteira)
last_pixel = next_pixel
next_pixel = find_next_point(img, last_pixel, listaDeFronteiras)
except Exception as e:
print(e)
i+=1
#este tratamento funciona devido a imagem 13
for front in listaDeFronteiras:
if len(front) > 19000:
listaDeFronteiras.remove(front)
print("NUMERO DE FOLHAS ENCONTRADAS:")
print(len(listaDeFronteiras))
return listaDeFronteiras
#retorna a altura, largura, menor linha e menor coluna
def encontra_dimensoes(fronteira):
x = 0
y = 1
list_y = [cord_y[y] for cord_y in fronteira]
list_x = [cord_x[x] for cord_x in fronteira]
x_menor = list_x[0] #pega a primeira posicao
x_maior = max(list_x)
y_menor = min(list_y)
y_maior = max(list_y)
#+3 serve para adicionar uma borda branca
return (x_maior-x_menor)+3 , (y_maior-y_menor)+3, x_menor, y_menor
#cria a imagem da fronteira e retorna uma imagem com a mascara
def criar_imagem_borda(img_borda, fronteira, menor_x, menor_y, index, name_img):
row, col, bpp = img_borda.shape
img_borda_binaria = np.zeros((row, col))
for pixel in fronteira: #transalada os pixeis
nova_coordenada_x = (int(pixel[0])-menor_x)+1
nova_coordenada_y = (int(pixel[1])-menor_y)+1
img_borda[nova_coordenada_x][nova_coordenada_y][0] = 0
img_borda[nova_coordenada_x][nova_coordenada_y][1] = 0
img_borda[nova_coordenada_x][nova_coordenada_y][2] = 0
#criando imagem binaria
img_borda_binaria[nova_coordenada_x][nova_coordenada_y] = 1
nome_imagem = name_img + '-' + str(index) +"-P"+ ".png"
cv2.imwrite(nome_imagem, img_borda)
img_borda_binaria = ndimage.binary_fill_holes(img_borda_binaria).astype(int)
return img_borda_binaria
def criar_imagem_unica_folha_colorida(img, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img):
row, col, bpp = np.shape(imagem_branca)
for i in range(row):
for j in range(col):
if img_borda_binaria[i][j] == 1:
nova_coordenada_x = i+menor_x+1
nova_coordenada_y = j+menor_y+1
imagem_branca[i][j][0] = imagem_original[nova_coordenada_x][nova_coordenada_y][0]
imagem_branca[i][j][1] = imagem_original[nova_coordenada_x][nova_coordenada_y][1]
imagem_branca[i][j][2] = imagem_original[nova_coordenada_x][nova_coordenada_y][2]
nome_imagem = name_img + '-' + str(index) + ".png"
cv2.imwrite(nome_imagem, imagem_branca)
return imagem_branca
def recorta_imagem(lista_fronteiras, imagem_sem_ruido, imagem_original, name_img):
index = 1
for fronteira in lista_fronteiras:
row, col, menor_x, menor_y = encontra_dimenso | 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):
if img[i,j] < BRANCO and img[i, j-1] >= BRANCO:
if bool_nas_Fronteiras((i,j), listaDeFronteiras) == False: #retorna o ponto
return (i,j)
else:#percorre a imagem ate achar um branco
ponto_branco = encontrar_prox_branco((i,j), img)
i=ponto_branco[0]
j=ponto_branco[1]
continue
j+=1
j=0
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):
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]):
return i
#a partir de um pixel inicial percorre a borda da folha
def seguidorDeFronteira(img, first_pixel, i):
row, col = img.shape
fronteira=[]
fronteira.append(first_pixel) # adiciona o primeiro pixel já na lista de fronteira
x = 0
y = 1 #intuito de deixar o código mais legível
b_0 = [first_pixel[x], first_pixel[y]] #b_0[0] = x , b_0[1] = y
c_0 = [0, -1]
anterior_b0 = [0, 0]
cont = 1
contador_de_vizinhos = 0
find_init_border = True
contador=0
while(find_init_border):
indexVizinho=obterVizinhoID(c_0[x], c_0[y])
while(True):
if(indexVizinho == 8):#zerar o clock
indexVizinho = 0
proxB_0 = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]]
proxVizinho = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] #atualiza para o próximo vizinho
if (img[proxVizinho[x]][proxVizinho[y]]<BRANCO) and cont==0: #verifica se o próximo vizinho é BRANCO
b_0 = [proxB_0[x], proxB_0[y]]
check = (b_0[x],b_0[y])
if (first_pixel == check): # quando encontrar o primeiro pixel novamente acaba o seguidor de fronteira
find_init_border = False
break
else:
fronteira.append((b_0[x],b_0[y])) # adiciona na lista de fronteiras
c_0 = [anterior_b0[x]-b_0[x], anterior_b0[y]-b_0[y]]
contador_de_vizinhos = 0
contador+=1
if proxB_0[x] > row: #para quando sair da imagem
return False, (0,0)
break
contador_de_vizinhos +=1
if contador_de_vizinhos == 9: #para quando estiver um loop infinito
return False, (0,0)
cont = 0
anterior_b0 = [proxB_0[x], proxB_0[y]]
indexVizinho += 1 #incrementa o vizinho
tamanho = len(fronteira)
if tamanho>50 and tamanho<25000: #tratamento da imagem 13
return True, fronteira
return False, (0,0)
def grayscale(img):
row, col, bpp = np.shape(img)
img_gray = []
for i in range(0,row):
for j in range(0,col):
b = int(img[i][j][0])
g = int(img[i][j][1])
r = int(img[i][j][2])
pixel = int((b+g+r) / 3)
img_gray.append(pixel)
return img_gray
def remove_ruidos(imagem):
img = imagem.astype('float')
img = img[:,:,0] # convert to 2D array
gray_img = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) #converte para tom de cinza
_,img = cv2.threshold(gray_img, 225,255, cv2.THRESH_BINARY) #converte para binario
img = cv2.medianBlur(img, 5) # remove o ruido
return img
#inicio do algoritmo seguidor de fronteiras
def init(img):
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
listaDeFronteiras.append(fronteira)
last_pixel = next_pixel
next_pixel = find_next_point(img, last_pixel, listaDeFronteiras)
except Exception as e:
print(e)
i+=1
#este tratamento funciona devido a imagem 13
for front in listaDeFronteiras:
if len(front) > 19000:
listaDeFronteiras.remove(front)
print("NUMERO DE FOLHAS ENCONTRADAS:")
print(len(listaDeFronteiras))
return listaDeFronteiras
#retorna a altura, largura, menor linha e menor coluna
def encontra_dimensoes(fronteira):
x = 0
y = 1
list_y = [cord_y[y] for cord_y in fronteira]
list_x = [cord_x[x] for cord_x in fronteira]
x_menor = list_x[0] #pega a primeira posicao
x_maior = max(list_x)
y_menor = min(list_y)
y_maior = max(list_y)
#+3 serve para adicionar uma borda branca
return (x_maior-x_menor)+3 , (y_maior-y_menor)+3, x_menor, y_menor
#cria a imagem da fronteira e retorna uma imagem com a mascara
def criar_imagem_borda(img_borda, fronteira, menor_x, menor_y, index, name_img):
row, col, bpp = img_borda.shape
img_borda_binaria = np.zeros((row, col))
for pixel in fronteira: #transalada os pixeis
nova_coordenada_x = (int(pixel[0])-menor_x)+1
nova_coordenada_y = (int(pixel[1])-menor_y)+1
img_borda[nova_coordenada_x][nova_coordenada_y][0] = 0
img_borda[nova_coordenada_x][nova_coordenada_y][1] = 0
img_borda[nova_coordenada_x][nova_coordenada_y][2] = 0
#criando imagem binaria
img_borda_binaria[nova_coordenada_x][nova_coordenada_y] = 1
nome_imagem = name_img + '-' + str(index) +"-P"+ ".png"
cv2.imwrite(nome_imagem, img_borda)
img_borda_binaria = ndimage.binary_fill_holes(img_borda_binaria).astype(int)
return img_borda_binaria
def criar_imagem_unica_folha_colorida(img, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img):
row, col, bpp = np.shape(imagem_branca)
for i in range(row):
for j in range(col):
if img_borda_binaria[i][j] == 1:
nova_coordenada_x = i+ | 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]):
return i
#a partir de um pixel inicial percorre a borda da folha
def seguidorDeFronteira(img, first_pixel, i):
row, col = img.shape
fronteira=[]
fronteira.append(first_pixel) # adiciona o primeiro pixel já na lista de fronteira
x = 0
y = 1 #intuito de deixar o código mais legível
b_0 = [first_pixel[x], first_pixel[y]] #b_0[0] = x , b_0[1] = y
c_0 = [0, -1]
anterior_b0 = [0, 0]
cont = 1
contador_de_vizinhos = 0
find_init_border = True
contador=0
while(find_init_border):
indexVizinho=obterVizinhoID(c_0[x], c_0[y])
while(True):
if(indexVizinho == 8):#zerar o clock
indexVizinho = 0
proxB_0 = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]]
proxVizinho = [b_0[x]+vizinhos[indexVizinho+1][x], b_0[y]+vizinhos[indexVizinho+1][y]] #atualiza para o próximo vizinho
if (img[proxVizinho[x]][proxVizinho[y]]<BRANCO) and cont==0: #verifica se o próximo vizinho é BRANCO
b_0 = [proxB_0[x], proxB_0[y]]
check = (b_0[x],b_0[y])
if (first_pixel == check): # quando encontrar o primeiro pixel novamente acaba o seguidor de fronteira
find_init_border = False
break
else:
fronteira.append((b_0[x],b_0[y])) # adiciona na lista de fronteiras
c_0 = [anterior_b0[x]-b_0[x], anterior_b0[y]-b_0[y]]
contador_de_vizinhos = 0
contador+=1
if proxB_0[x] > row: #para quando sair da imagem
return False, (0,0)
break
contador_de_vizinhos +=1
if contador_de_vizinhos == 9: #para quando estiver um loop infinito
return False, (0,0)
cont = 0
anterior_b0 = [proxB_0[x], proxB_0[y]]
indexVizinho += 1 #incrementa o vizinho
tamanho = len(fronteira)
if tamanho>50 and tamanho<25000: #tratamento da imagem 13
return True, fronteira
return False, (0,0)
def grayscale(img):
row, col, bpp = np.shape(img)
img_gray = []
for i in range(0,row):
for j in range(0,col):
b = int(img[i][j][0])
g = int(img[i][j][1])
r = int(img[i][j][2])
pixel = int((b+g+r) / 3)
img_gray.append(pixel)
return img_gray
def remove_ruidos(imagem):
img = imagem.astype('float')
img = img[:,:,0] # convert to 2D array
gray_img = cv2.cvtColor(imagem, cv2.COLOR_BGR2GRAY) #converte para tom de cinza
_,img = cv2.threshold(gray_img, 225,255, cv2.THRESH_BINARY) #converte para binario
img = cv2.medianBlur(img, 5) # remove o ruido
return img
#inicio do algoritmo seguidor de fronteiras
def init(img):
| 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
listaDeFronteiras.append(fronteira)
last_pixel = next_pixel
next_pixel = find_next_point(img, last_pixel, listaDeFronteiras)
except Exception as e:
print(e)
i+=1
#este tratamento funciona devido a imagem 13
for front in listaDeFronteiras:
if len(front) > 19000:
listaDeFronteiras.remove(front)
print("NUMERO DE FOLHAS ENCONTRADAS:")
print(len(listaDeFronteiras))
return listaDeFronteiras
#retorna a altura, largura, menor linha e menor coluna
def encontra_dimensoes(fronteira):
x = 0
y = 1
list_y = [cord_y[y] for cord_y in fronteira]
list_x = [cord_x[x] for cord_x in fronteira]
x_menor = list_x[0] #pega a primeira posicao
x_maior = max(list_x)
y_menor = min(list_y)
y_maior = max(list_y)
#+3 serve para adicionar uma borda branca
return (x_maior-x_menor)+3 , (y_maior-y_menor)+3, x_menor, y_menor
#cria a imagem da fronteira e retorna uma imagem com a mascara
def criar_imagem_borda(img_borda, fronteira, menor_x, menor_y, index, name_img):
row, col, bpp = img_borda.shape
img_borda_binaria = np.zeros((row, col))
for pixel in fronteira: #transalada os pixeis
nova_coordenada_x = (int(pixel[0])-menor_x)+1
nova_coordenada_y = (int(pixel[1])-menor_y)+1
img_borda[nova_coordenada_x][nova_coordenada_y][0] = 0
img_borda[nova_coordenada_x][nova_coordenada_y][1] = 0
img_borda[nova_coordenada_x][nova_coordenada_y][2] = 0
#criando imagem binaria
img_borda_binaria[nova_coordenada_x][nova_coordenada_y] = 1
nome_imagem = name_img + '-' + str(index) +"-P"+ ".png"
cv2.imwrite(nome_imagem, img_borda)
img_borda_binaria = ndimage.binary_fill_holes(img_borda_binaria).astype(int)
return img_borda_binaria
def criar_imagem_unica_folha_colorida(img, imagem_original, imagem_branca, fronteira, img_borda_binaria, index, menor_x, menor_y, name_img):
row, col, bpp = np.shape(imagem_branca)
for i in range(row):
for j in range(col):
if img_borda_binaria[i][j] == 1:
nova_coordenada_x = i+menor_x+1
nova_coordenada_y = j+menor_y+1
imagem_branca[i][j][0] = imagem_original[nova_coordenada_x][nova_coordenada_y][0]
imagem_branca[i][j][1] = imagem_original[nova_coordenada_x][nova_coordenada_y][1]
imagem_branca[i][j][2] = imagem_original[nova_coordenada_x][nova_coordenada_y][2]
nome_imagem = name_img + '-' + str(index) + ".png"
cv2.imwrite(nome_imagem, imagem_branca)
return imagem_branca
def recorta_imagem(lista_fronteiras, imagem_sem_ruido, imagem_original, name_img):
index = 1
for fronteira in lista_fronteiras:
row, col, menor_x, menor_y = encontra_dimensoes(fronteira)
#salavando a borda
imagem_branca = np.ones((row, col, 3)) * 255
img_borda_binaria = criar_imagem_borda(imagem_branca, fronteira, menor_x, menor_y, index, name_img)
#salvando a folha
criar_imagem_unica_folha_color | 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)
class DefaultGenerator(c_generator.CGenerator):
"""
A C code generator that turns an Abstract Syntax Tree (AST) into an
annotated version of the same file. Extend this class to change the
contents of the debug lines.
"""
|
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,
"default": c_ast.Default
}
def __init__(self, track):
super(DefaultGenerator, self).__init__()
self._current_record = None
self._insert = False
self._tracked = self._pick_trackers(track)
self.records = []
def _pick_trackers(self,track):
if "all" in track:
return list(self.NAME_TABLE.values())
return [ self.NAME_TABLE[x] for x in track if x in self.NAME_TABLE ]
def preprocess(self, input_lines):
lines = self._else_to_elseif(input_lines)
return lines
def _else_to_elseif(self, input_lines):
content = "".join(input_lines)
content = re.sub(r"else(?!\s*if)", r"else if (" + self.ELSE_HELPER + ")", content)
input_lines = content.splitlines(True)
return input_lines
def visit(self, node):
if type(node) in self._tracked:
self._current_record = self._record_from_node(node)
self._insert = True
method = 'visit_' + node.__class__.__name__
return getattr(self, method, self.generic_visit)(node)
def _common_visit(self, node):
d = None
if self._insert:
d = self._build_tracking_line()
self.records.append(self._current_record)
s = getattr(super(DefaultGenerator, self), 'visit_' + node.__class__.__name__)(node)
if d is not None:
s = self._shim_line(s, d)
return s
def _pick_tracking_statement(self, record):
r = record
#return "{} at {} in {}".format(r.name, r.line, r.file)
return "{}".format(r.id)
def _wrap_tracking_statement(self, statement):
#return 'mspsim_printf("{}\\n");'.format(statement)
return 'send_id({});'.format(statement)
def _build_tracking_line(self):
statement = self._pick_tracking_statement(self._current_record)
s = ' ' * self.indent_level + self._wrap_tracking_statement(statement)
self.insert = False
return s
def _shim_line(self, original, shim, n = 1):
s = original.split('\n')
if len(s) < n:
return original
s.insert(n, ' ' + shim)
return '\n'.join(s)
def visit_Compound(self, n):
return self._common_visit(n)
def visit_Case(self, n):
return self._common_visit(n)
def visit_Default(self, n):
return self._common_visit(n)
def visit_If(self, n):
s = ""
if n.cond:
cond = self.visit(n.cond)
if n.cond and cond == self.ELSE_HELPER:
if "else" in self._tracked:
self._insert = True
self._current_record.name = "else"
else:
s = 'if ('
if n.cond: s += cond
s += ')\n'
if c_ast.If not in self._tracked:
self._insert = False
s += self._generate_stmt(n.iftrue, add_indent=True)
if n.iffalse:
s += self._make_indent() + 'else\n'
s += self._generate_stmt(n.iffalse, add_indent=True)
return s
def _create_child_tree(self, node):
global lst
#print "node is " + str(node.show())
my_module_classes = tuple(x[1] for x in inspect.getmembers(c_ast, inspect.isclass))
for (child_name, child) in node.children():
if isinstance(child, c_ast.FuncCall) and child.name.name != "mspsim_printf":
#print "\tChild: " + str(child.name.name)
lst.append(child.name.name)
elif isinstance(child, my_module_classes):
self._create_child_tree(child)
def _record_from_node(self, node):
global lst
c = node.coord
funcName = None
childlist = []
match = {
c_ast.If: "if",
c_ast.DoWhile: "dowhile",
c_ast.For: "for",
c_ast.FuncDef: "funcdef",
c_ast.While: "while",
c_ast.Case: "case",
c_ast.Default: "default",
}
name = match[type(node)]
if isinstance(node, c_ast.FuncDef):
funcName = node.decl.name
lst = []
self._create_child_tree(node)
#if len(lst) > 0:
# print "Parent function " + str(funcName)
# print lst
return Record(c.line, c.file, name, funcName, lst)
class IdGenerator(DefaultGenerator):
def _pick_tracking_statement(self, record):
return "{}".format(record.id)
class PrintGenerator(IdGenerator):
def _wrap_tracking_statement(self, statement):
return 'coverage("{}\\n");'.format(statement)
class SerialGenerator(IdGenerator):
def _wrap_tracking_statement(self, statement):
return 'serial("{}\\n");'.format(statement)
def _extract_directives(input_lines):
extract = ['#include', '#ifdef', '#ifndef', '#endif']
code_lines = []
directive_lines = []
for line in input_lines:
if any(word in line.lower() for word in extract):
directive_lines.append(line.rstrip())
code_lines.insert(0, '\n')
else:
code_lines.append(line)
return (code_lines, directive_lines)
def generate(input_lines, track=None, generator_class=DefaultGenerator):
if track is None:
track = ["all"]
generator = (generator_class)(track)
input_lines = generator.preprocess(input_lines)
code_lines, directive_lines = _extract_directives(input_lines)
temp_file = tempfile.mkstemp()[1]
with open(temp_file, 'w') as t:
t.writelines(code_lines)
ast = parse_file(temp_file, use_cpp=True,
cpp_args=r'-Iutils/fake_libc_include')
os.remove(temp_file)
output_lines = []
output_lines.extend(directive_lines)
output_lines.append('')
output_lines.extend(generator.visit(ast).splitlines())
return (output_lines, generator.records)
def lines_from_file(input_path):
if input_path == '-':
input_lines = sys.stdin.readlines()
else:
with open(input_path, 'r') as f:
input_lines = f.readlines()
return input_lines
def write_to_file(output, output_path):
if output_path == '-':
print(output)
elif output_path == "+":
sys.stderr.write(output)
else:
with open(output_path, 'w') as f:
f.write(output)
def dump_record_index(records, record_path):
if record_path == "-":
csvfile = sys.stdout
elif record_path == "+":
csvfile = sys.stderr
else:
csvfile = open(record_path, 'w')
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.close()
def generate_from_file(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, record_path)
def generate_from_multiple_files(number_of_files, paths, track=None, generator_class=DefaultGenerator):
output_list = []
records_list = []
for i in range(0, number_of_files):
input_lines = lines_from_file(paths[i * 2])
output_lines, records = generate(input_lines, track, generator_class)
output = "\n".join(output_lines)
for record in records:
records_list.append(record)
output_list.append(output)
dump_record_index(records_list, paths[i * 2 + 2])
for j in range(0, len(output_list)):
output_list[j] = output_list[j].replace("int main(void)\n{\n", "int | 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 {}, dependencies are {}".format(self.id, self.funcName, self.name, self.line, self.file, self.funcList)
class DefaultGenerator(c_generator.CGenerator):
"""
A C code generator that turns an Abstract Syntax Tree (AST) into an
annotated version of the same file. Extend this class to change the
contents of the debug lines.
"""
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,
"default": c_ast.Default
}
def __init__(self, track):
super(DefaultGenerator, self).__init__()
self._current_record = None
self._insert = False
self._tracked = self._pick_trackers(track)
self.records = []
def _pick_trackers(self,track):
if "all" in track:
return list(self.NAME_TABLE.values())
return [ self.NAME_TABLE[x] for x in track if x in self.NAME_TABLE ]
def preprocess(self, input_lines):
lines = self._else_to_elseif(input_lines)
return lines
def _else_to_elseif(self, input_lines):
content = "".join(input_lines)
content = re.sub(r"else(?!\s*if)", r"else if (" + self.ELSE_HELPER + ")", content)
input_lines = content.splitlines(True)
return input_lines
def visit(self, node):
if type(node) in self._tracked:
self._current_record = self._record_from_node(node)
self._insert = True
method = 'visit_' + node.__class__.__name__
return getattr(self, method, self.generic_visit)(node)
def _common_visit(self, node):
d = None
if self._insert:
d = self._build_tracking_line()
self.records.append(self._current_record)
s = getattr(super(DefaultGenerator, self), 'visit_' + node.__class__.__name__)(node)
if d is not None:
s = self._shim_line(s, d)
return s
def _pick_tracking_statement(self, record):
r = record
#return "{} at {} in {}".format(r.name, r.line, r.file)
return "{}".format(r.id)
def _wrap_tracking_statement(self, statement):
#return 'mspsim_printf("{}\\n");'.format(statement)
return 'send_id({});'.format(statement)
def _build_tracking_line(self):
statement = self._pick_tracking_statement(self._current_record)
s = ' ' * self.indent_level + self._wrap_tracking_statement(statement)
self.insert = False
return s
def _shim_line(self, original, shim, n = 1):
s = original.split('\n')
if len(s) < n:
return original
s.insert(n, ' ' + shim)
return '\n'.join(s)
def visit_Compound(self, n):
return self._common_visit(n)
def visit_Case(self, n):
return self._common_visit(n)
def visit_Default(self, n):
return self._common_visit(n)
def visit_If(self, n):
s = ""
if n.cond:
cond = self.visit(n.cond)
if n.cond and cond == self.ELSE_HELPER:
if "else" in self._tracked:
self._insert = True
self._current_record.name = "else"
else:
s = 'if ('
if n.cond: s += cond
s += ')\n'
if c_ast.If not in self._tracked:
self._insert = False
s += self._generate_stmt(n.iftrue, add_indent=True)
if n.iffalse:
s += self._make_indent() + 'else\n'
s += self._generate_stmt(n.iffalse, add_indent=True)
return s
def _create_child_tree(self, node):
global lst
#print "node is " + str(node.show())
my_module_classes = tuple(x[1] for x in inspect.getmembers(c_ast, inspect.isclass))
for (child_name, child) in node.children():
if isinstance(child, c_ast.FuncCall) and child.name.name != "mspsim_printf":
#print "\tChild: " + str(child.name.name)
lst.append(child.name.name)
elif isinstance(child, my_module_classes):
self._create_child_tree(child)
def _record_from_node(self, node):
global lst
c = node.coord
funcName = None
childlist = []
match = {
c_ast.If: "if",
c_ast.DoWhile: "dowhile",
c_ast.For: "for",
c_ast.FuncDef: "funcdef",
c_ast.While: "while",
c_ast.Case: "case",
c_ast.Default: "default",
}
name = match[type(node)]
if isinstance(node, c_ast.FuncDef):
funcName = node.decl.name
lst = []
self._create_child_tree(node)
#if len(lst) > 0:
# print "Parent function " + str(funcName)
# print lst
return Record(c.line, c.file, name, funcName, lst)
class IdGenerator(DefaultGenerator):
def _pick_tracking_statement(self, record):
return "{}".format(record.id)
class PrintGenerator(IdGenerator):
def _wrap_tracking_statement(self, statement):
return 'coverage("{}\\n");'.format(statement)
class SerialGenerator(IdGenerator):
def _wrap_tracking_statement(self, statement):
return 'serial("{}\\n");'.format(statement)
def _extract_directives(input_lines):
extract = ['#include', '#ifdef', '#ifndef', '#endif']
code_lines = []
directive_lines = []
for line in input_lines:
if any(word in line.lower() for word in extract):
directive_lines.append(line.rstrip())
code_lines.insert(0, '\n')
else:
code_lines.append(line)
return (code_lines, directive_lines)
def generate(input_lines, track=None, generator_class=DefaultGenerator):
if track is None:
track = ["all"]
generator = (generator_class)(track)
input_lines = generator.preprocess(input_lines)
code_lines, directive_lines = _extract_directives(input_lines)
temp_file = tempfile.mkstemp()[1]
with open(temp_file, 'w') as t:
t.writelines(code_lines)
ast = parse_file(temp_file, use_cpp=True,
cpp_args=r'-Iutils/fake_libc_include')
os.remove(temp_file)
output_lines = []
output_lines.extend(directive_lines)
output_lines.append('')
output_lines.extend(generator.visit(ast).splitlines())
return (output_lines, generator.records)
def lines_from_file(input_path):
if input_path == '-':
input_lines = sys.stdin.readlines()
else:
with open(input_path, 'r') as f:
input_lines = f.readlines()
return input_lines
def write_to_file(output, output_path):
if output_path == '-':
print(output)
elif output_path == "+":
sys.stderr.write(output)
else:
with open(output_path, 'w') as f:
f.write(output)
def dump_record_index(records, record_path):
if record_path == "-":
csvfile = sys.stdout
elif record_path == "+":
csvfile = sys.stderr
else:
csvfile = open(record_path, 'w')
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.close()
def generate_from_file(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, record_path)
def generate_from_multiple_files(number_of_files, paths, track=None, generator_class=DefaultGenerator):
output_list = []
records_list = []
for i in range(0, number_of_files):
input_lines = lines_from_file(paths[i * 2])
output_lines, records = generate(input_lines, track, generator_class)
output = "\n | 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)
class DefaultGenerator(c_generator.CGenerator):
"""
A C code generator that turns an Abstract Syntax Tree (AST) into an
annotated version of the same file. Extend this class to change the
contents of the debug lines.
"""
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,
"default": c_ast.Default
}
def __init__(self, track):
super(DefaultGenerator, self).__init__()
self._current_record = None
self._insert = False
self._tracked = self._pick_trackers(track)
self.records = []
def _pick_trackers(self,track):
if "all" in track:
return list(self.NAME_TABLE.values())
return [ self.NAME_TABLE[x] for x in track if x in self.NAME_TABLE ]
def preprocess(self, input_lines):
lines = self._else_to_elseif(input_lines)
return lines
def _else_to_elseif(self, input_lines):
content = "".join(input_lines)
content = re.sub(r"else(?!\s*if)", r"else if (" + self.ELSE_HELPER + ")", content)
input_lines = content.splitlines(True)
return input_lines
def visit(self, node):
if type(node) in self._tracked:
self._current_record = self._record_from_node(node)
self._insert = True
method = 'visit_' + node.__class__.__name__
return getattr(self, method, self.generic_visit)(node)
def _common_visit(self, node):
d = None
if self._insert:
d = self._build_tracking_line()
self.records.append(self._current_record)
s = getattr(super(DefaultGenerator, self), 'visit_' + node.__class__.__name__)(node)
if d is not None:
s = self._shim_line(s, d)
return s
def _pick_tracking_statement(self, record):
r = record
#return "{} at {} in {}".format(r.name, r.line, r.file)
return "{}".format(r.id)
def _wrap_tracking_statement(self, statement):
#return 'mspsim_printf("{}\\n");'.format(statement)
return 'send_id({});'.format(statement)
def _build_tracking_line(self):
statement = self._pick_tracking_statement(self._current_record)
s = ' ' * self.indent_level + self._wrap_tracking_statement(statement)
self.insert = False
return s
def _shim_line(self, original, shim, n = 1):
s = original.split('\n')
if len(s) < n:
return original
s.insert(n, ' ' + shim)
return '\n'.join(s)
def visit_Compound(self, n):
return self._common_visit(n)
def visit_Case(self, n):
return self._common_visit(n)
def visit_Default(self, n):
return self._common_visit(n)
def visit_If(self, n):
s = ""
if n.cond:
cond = self.visit(n.cond)
if n.cond and cond == self.ELSE_HELPER:
if "else" in self._tracked:
self._insert = True
self._current_record.name = "else"
else:
s = 'if ('
if n.cond: s += cond
s += ')\n'
if c_ast.If not in self._tracked:
self._insert = False
s += self._generate_stmt(n.iftrue, add_indent=True)
if n.iffalse:
s += self._make_indent() + 'else\n'
s += self._generate_stmt(n.iffalse, add_indent=True)
return s
def _create_child_tree(self, node):
global lst
#print "node is " + str(node.show())
my_module_classes = tuple(x[1] for x in inspect.getmembers(c_ast, inspect.isclass))
for (child_name, child) in node.children():
if isinstance(child, c_ast.FuncCall) and child.name.name != "mspsim_printf":
#print "\tChild: " + str(child.name.name)
lst.append(child.name.name)
elif isinstance(child, my_module_classes):
self._create_child_tree(child)
def _record_from_node(self, node):
global lst
c = node.coord
funcName = None
childlist = []
match = {
c_ast.If: "if",
c_ast.DoWhile: "dowhile",
c_ast.For: "for",
c_ast.FuncDef: "funcdef",
c_ast.While: "while",
c_ast.Case: "case",
c_ast.Default: "default",
}
name = match[type(node)]
if isinstance(node, c_ast.FuncDef):
funcName = node.decl.name
lst = []
self._create_child_tree(node)
#if len(lst) > 0:
# print "Parent function " + str(funcName)
# print lst
return Record(c.line, c.file, name, funcName, lst)
class IdGenerator(DefaultGenerator):
def _pick_tracking_statement(self, record):
return "{}".format(record.id)
class PrintGenerator(IdGenerator):
def _wrap_tracking_statement(self, statement):
return 'coverage("{}\\n");'.format(statement)
class SerialGenerator(IdGenerator):
def _wrap_tracking_statement(self, statement):
return 'serial("{}\\n");'.format(statement)
def _extract_directives(input_lines):
extract = ['#include', '#ifdef', '#ifndef', '#endif']
code_lines = []
directive_lines = []
for line in input_lines:
if any(word in line.lower() for word in extract):
directive_lines.append(line.rstrip())
code_lines.insert(0, '\n')
else:
code_lines.append(line)
return (code_lines, directive_lines)
def generate(input_lines, track=None, generator_class=DefaultGenerator):
if track is None:
track = ["all"]
generator = (generator_class)(track)
input_lines = generator.preprocess(input_lines)
code_lines, directive_lines = _extract_directives(input_lines)
temp_file = tempfile.mkstemp()[1]
with open(temp_file, 'w') as t:
t.writelines(code_lines)
ast = parse_file(temp_file, use_cpp=True,
cpp_args=r'-Iutils/fake_libc_include')
os.remove(temp_file)
output_lines = []
output_lines.extend(directive_lines)
output_lines.append('')
output_lines.extend(generator.visit(ast).splitlines())
return (output_lines, generator.records)
def lines_from_file(input_path):
if input_path == '-':
input_lines = sys.stdin.readlines()
else:
with open(input_path, 'r') as f:
input_lines = f.readlines()
return input_lines
def write_to_file(output, output_path):
if output_path == '-':
print(output)
elif output_path == "+":
sys.stderr.write(output)
else:
with open(output_path, 'w') as f:
f.write(output)
def dump_record_index(records, record_path):
if record_path == "-":
csvfile = sys.stdout
elif record_path == "+":
csvfile = sys.stderr
else:
|
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.close()
def generate_from_file(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, record_path)
def generate_from_multiple_files(number_of_files, paths, track=None, generator_class=DefaultGenerator):
output_list = []
records_list = []
for i in range(0, number_of_files):
input_lines = lines_from_file(paths[i * 2])
output_lines, records = generate(input_lines, track, generator_class)
output = "\n".join(output_lines)
for record in records:
records_list.append(record)
output_list.append(output)
dump_record_index(records_list, paths[i * 2 + 2])
for j in range(0, len(output_list)):
output_list[j] = output_list[j].replace("int main(void)\n{\n", " | 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)
class DefaultGenerator(c_generator.CGenerator):
"""
A C code generator that turns an Abstract Syntax Tree (AST) into an
annotated version of the same file. Extend this class to change the
contents of the debug lines.
"""
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,
"default": c_ast.Default
}
def __init__(self, track):
super(DefaultGenerator, self).__init__()
self._current_record = None
self._insert = False
self._tracked = self._pick_trackers(track)
self.records = []
def _pick_trackers(self,track):
if "all" in track:
return list(self.NAME_TABLE.values())
return [ self.NAME_TABLE[x] for x in track if x in self.NAME_TABLE ]
def preprocess(self, input_lines):
lines = self._else_to_elseif(input_lines)
return lines
def _else_to_elseif(self, input_lines):
content = "".join(input_lines)
content = re.sub(r"else(?!\s*if)", r"else if (" + self.ELSE_HELPER + ")", content)
input_lines = content.splitlines(True)
return input_lines
def visit(self, node):
if type(node) in self._tracked:
self._current_record = self._record_from_node(node)
self._insert = True
method = 'visit_' + node.__class__.__name__
return getattr(self, method, self.generic_visit)(node)
def _common_visit(self, node):
d = None
if self._insert:
d = self._build_tracking_line()
self.records.append(self._current_record)
s = getattr(super(DefaultGenerator, self), 'visit_' + node.__class__.__name__)(node)
if d is not None:
s = self._shim_line(s, d)
return s
def _pick_tracking_statement(self, record):
r = record
#return "{} at {} in {}".format(r.name, r.line, r.file)
return "{}".format(r.id)
def _wrap_tracking_statement(self, statement):
#return 'mspsim_printf("{}\\n");'.format(statement)
return 'send_id({});'.format(statement)
def _build_tracking_line(self):
statement = self._pick_tracking_statement(self._current_record)
s = ' ' * self.indent_level + self._wrap_tracking_statement(statement)
self.insert = False
return s
def _shim_line(self, original, shim, n = 1):
s = original.split('\n')
if len(s) < n:
return original
s.insert(n, ' ' + shim)
return '\n'.join(s)
def visit_Compound(self, n):
return self._common_visit(n)
def visit_Case(self, n):
return self._common_visit(n)
def visit_Default(self, n):
return self._common_visit(n)
def visit_If(self, n):
s = ""
if n.cond:
cond = self.visit(n.cond)
if n.cond and cond == self.ELSE_HELPER:
if "else" in self._tracked:
self._insert = True
self._current_record.name = "else"
else:
s = 'if ('
if n.cond: s += cond
s += ')\n'
if c_ast.If not in self._tracked:
self._insert = False
s += self._generate_stmt(n.iftrue, add_indent=True)
if n.iffalse:
s += self._make_indent() + 'else\n'
s += self._generate_stmt(n.iffalse, add_indent=True)
return s
def _create_child_tree(self, node):
global lst
#print "node is " + str(node.show())
my_module_classes = tuple(x[1] for x in inspect.getmembers(c_ast, inspect.isclass))
for (child_name, child) in node.children():
if isinstance(child, c_ast.FuncCall) and child.name.name != "mspsim_printf":
#print "\tChild: " + str(child.name.name)
lst.append(child.name.name)
elif isinstance(child, my_module_classes):
self._create_child_tree(child)
def _record_from_node(self, node):
global lst
c = node.coord
funcName = None
childlist = []
match = {
c_ast.If: "if",
c_ast.DoWhile: "dowhile",
c_ast.For: "for",
c_ast.FuncDef: "funcdef",
c_ast.While: "while",
c_ast.Case: "case",
c_ast.Default: "default",
}
name = match[type(node)]
if isinstance(node, c_ast.FuncDef):
funcName = node.decl.name
lst = []
self._create_child_tree(node)
#if len(lst) > 0:
# print "Parent function " + str(funcName)
# print lst
return Record(c.line, c.file, name, funcName, lst)
class IdGenerator(DefaultGenerator):
def _pick_tracking_statement(self, record):
return "{}".format(record.id)
class PrintGenerator(IdGenerator):
def _wrap_tracking_statement(self, statement):
return 'coverage("{}\\n");'.format(statement)
class SerialGenerator(IdGenerator):
def _wrap_tracking_statement(self, statement):
return 'serial("{}\\n");'.format(statement)
def _extract_directives(input_lines):
extract = ['#include', '#ifdef', '#ifndef', '#endif']
code_lines = []
directive_lines = []
for line in input_lines:
if any(word in line.lower() for word in extract):
directive_lines.append(line.rstrip())
code_lines.insert(0, '\n')
else:
code_lines.append(line)
return (code_lines, directive_lines)
def generate(input_lines, track=None, generator_class=DefaultGenerator):
if track is None:
track = ["all"]
generator = (generator_class)(track)
input_lines = generator.preprocess(input_lines)
code_lines, directive_lines = _extract_directives(input_lines)
temp_file = tempfile.mkstemp()[1]
with open(temp_file, 'w') as t:
t.writelines(code_lines)
ast = parse_file(temp_file, use_cpp=True,
cpp_args=r'-Iutils/fake_libc_include')
os.remove(temp_file)
output_lines = []
output_lines.extend(directive_lines)
output_lines.append('')
output_lines.extend(generator.visit(ast).splitlines())
return (output_lines, generator.records)
def lines_from_file(input_path):
if input_path == '-':
input_lines = sys.stdin.readlines()
else:
with open(input_path, 'r') as f:
input_lines = f.readlines()
return input_lines
def write_to_file(output, output_path):
if output_path == '-':
print(output)
elif output_path == "+":
sys.stderr.write(output)
else:
with open(output_path, 'w') as f:
f.write(output)
def dump_record_index(records, record_path):
if record_path == "-":
csvfile = sys.stdout
elif record_path == "+":
csvfile = sys.stderr
else:
csvfile = open(record_path, 'w')
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.close()
def | (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, record_path)
def generate_from_multiple_files(number_of_files, paths, track=None, generator_class=DefaultGenerator):
output_list = []
records_list = []
for i in range(0, number_of_files):
input_lines = lines_from_file(paths[i * 2])
output_lines, records = generate(input_lines, track, generator_class)
output = "\n".join(output_lines)
for record in records:
records_list.append(record)
output_list.append(output)
dump_record_index(records_list, paths[i * 2 + 2])
for j in range(0, len(output_list)):
output_list[j] = output_list[j].replace("int main(void)\n{\n", " | 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.eventFilter)
if err != nil {
return errors.Wrapf(err, "Failed to register chaincode event")
}
logger.Info("chaincode event registered successfully")
c.stopchan = make(chan struct{})
c.exitchan = make(chan struct{})
go func() {
defer close(c.exitchan)
defer c.client.Unregister(registration)
receiveChaincodeEvent(ccChan, c.handler, c.stopchan)
}()
default:
logger.Infof("event type '%s' is not supported", c.eventType)
}
return nil
}
// Stop stops the event listener
func (c *Listener) Stop() {
logger.Info("Stop listener ...")
close(c.stopchan)
<-c.exitchan
logger.Info("Listener stopped")
}
// Spec defines client for fabric events
type Spec struct {
Name string
NetworkConfig []byte
EntityMatchers []byte
OrgName string
UserName string
ChannelID string
EventType string
ChaincodeID string
EventFilter string
}
func clientID(spec *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 := clientMap[cid]
if ok && client != nil {
return client, nil
}
// create new event client
sdk, err := fabsdk.New(networkConfigProvider(spec.NetworkConfig, spec.EntityMatchers))
if err != nil {
return nil, errors.Wrapf(err, "Failed to create new SDK")
}
opts := []fabsdk.ContextOption{fabsdk.WithUser(spec.UserName)}
if spec.OrgName != "" {
opts = append(opts, fabsdk.WithOrg(spec.OrgName))
}
if spec.EventType == EventFiltered {
client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...))
} else {
client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...), event.WithBlockEvents())
}
if err != nil {
clientMap[cid] = client
}
return client, err
}
func receiveChaincodeEvent(ccChan <-chan *fab.CCEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var ccEvent *fab.CCEvent
select {
case ccEvent = <-ccChan:
cce := unmarshalChaincodeEvent(ccEvent)
handler(cce)
case <-stopchan:
logger.Info("Quit listener for chaincode event")
return
}
}
}
func unmarshalChaincodeEvent(ccEvent *fab.CCEvent) *CCEventDetail {
ced := CCEventDetail{
BlockNumber: ccEvent.BlockNumber,
SourceURL: ccEvent.SourceURL,
TxID: ccEvent.TxID,
ChaincodeID: ccEvent.ChaincodeID,
EventName: ccEvent.EventName,
Payload: string(ccEvent.Payload),
}
return &ced
}
func receiveFilteredBlockEvent(blkChan <-chan *fab.FilteredBlockEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var blkEvent *fab.FilteredBlockEvent
select {
case blkEvent = <-blkChan:
bed := unmarshalFilteredBlockEvent(blkEvent)
handler(bed)
case <-stopchan:
logger.Info("Quit listener for filtered block event")
return
}
}
}
func unmarshalFilteredBlockEvent(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.FilteredTransactions {
td := TransactionDetail{
TxType: common.HeaderType_name[int32(d.Type)],
TxID: d.Txid,
ChannelID: blk.ChannelId,
Actions: []*ActionDetail{},
}
bed.Transactions = append(bed.Transactions, &td)
actions := d.GetTransactionActions()
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.EventName,
Payload: string(ce.Payload),
},
},
}
td.Actions = append(td.Actions, &action)
}
}
}
}
return &bed
}
func receiveBlockEvent(blkChan <-chan *fab.BlockEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var blkEvent *fab.BlockEvent
select {
case blkEvent = <-blkChan:
bed := unmarshalBlockEvent(blkEvent)
handler(bed)
case <-stopchan:
logger.Info("Quit listener for block event")
return
}
}
}
func unmarshalBlockEvent(blkEvent *fab.BlockEvent) *BlockEventDetail {
bed := BlockEventDetail{
SourceURL: blkEvent.SourceURL,
Number: blkEvent.Block.Header.Number,
Transactions: []*TransactionDetail{},
}
for _, d := range blkEvent.Block.Data.Data {
txn, err := unmarshalTransaction(d)
if err != nil {
logger.Errorf("Error unmarshalling transaction: %+v", err)
continue
} else {
bed.Transactions = append(bed.Transactions, txn)
}
}
return &bed
}
func unmarshalTransaction(data []byte) (*TransactionDetail, error) {
envelope, err := GetEnvelopeFromBlock(data)
if err != nil {
return nil, errors.Wrapf(err, "failed to get envelope")
}
payload, err := UnmarshalPayload(envelope.Payload)
if err != nil {
return nil, errors.Wrapf(err, "failed to get payload")
}
if payload.Header == nil {
return nil, errors.Errorf("payload header is empty")
} | 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: []*ActionDetail{},
}
// signature header
shdr := &common.SignatureHeader{}
if err = proto.Unmarshal(payload.Header.SignatureHeader, shdr); err != nil {
logger.Errorf("failed to unmarshal signature header: %+v", err)
} else {
cid, err := unmarshalIdentity(shdr.Creator)
if err != nil {
logger.Errorf("failed to unmarshal creator identity: %+v", err)
} else {
td.CreatorIdentity = cid
}
}
txn, err := UnmarshalTransaction(payload.Data)
if err != nil {
return &td, errors.Wrapf(err, "failed to get transaction")
}
for _, ta := range txn.Actions {
act, err := unmarshalAction(ta.Payload)
if err != nil {
logger.Errorf("Error unmarshalling action: %+v", err)
continue
} else {
td.Actions = append(td.Actions, act)
}
}
return &td, nil
}
func unmarshalIdentity(data []byte) (*Identity, error) {
cid := &msp.SerializedIdentity{}
if err := proto.Unmarshal(data, cid); err != nil {
return nil, err
}
id := Identity{Mspid: cid.Mspid, Cert: string(cid.IdBytes)}
// extract info from x509 certificate
block, _ := pem.Decode(cid.IdBytes)
if block == nil {
logger.Info("creator certificate is empty")
return &id, nil
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
logger.Errorf("failed to parse creator certificate: %+v", err)
return &id, nil
}
id.Subject = cert.Subject.CommonName
id.Issuer = cert.Issuer.CommonName
return &id, nil
}
func unmarshalAction(data []byte) (*ActionDetail, error) {
ccAction, err := UnmarshalChaincodeActionPayload(data)
if err != nil {
return nil, errors.Wrapf(err, "failed to get action payload |
// 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.eventFilter)
if err != nil {
return errors.Wrapf(err, "Failed to register chaincode event")
}
logger.Info("chaincode event registered successfully")
c.stopchan = make(chan struct{})
c.exitchan = make(chan struct{})
go func() {
defer close(c.exitchan)
defer c.client.Unregister(registration)
receiveChaincodeEvent(ccChan, c.handler, c.stopchan)
}()
default:
logger.Infof("event type '%s' is not supported", c.eventType)
}
return nil
}
// Stop stops the event listener
func (c *Listener) Stop() {
logger.Info("Stop listener ...")
close(c.stopchan)
<-c.exitchan
logger.Info("Listener stopped")
}
// Spec defines client for fabric events
type Spec struct {
Name string
NetworkConfig []byte
EntityMatchers []byte
OrgName string
UserName string
ChannelID string
EventType string
ChaincodeID string
EventFilter string
}
func clientID(spec *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 := clientMap[cid]
if ok && client != nil {
return client, nil
}
// create new event client
sdk, err := fabsdk.New(networkConfigProvider(spec.NetworkConfig, spec.EntityMatchers))
if err != nil {
return nil, errors.Wrapf(err, "Failed to create new SDK")
}
opts := []fabsdk.ContextOption{fabsdk.WithUser(spec.UserName)}
if spec.OrgName != "" {
opts = append(opts, fabsdk.WithOrg(spec.OrgName))
}
if spec.EventType == EventFiltered {
client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...))
} else {
client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...), event.WithBlockEvents())
}
if err != nil {
clientMap[cid] = client
}
return client, err
}
func receiveChaincodeEvent(ccChan <-chan *fab.CCEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var ccEvent *fab.CCEvent
select {
case ccEvent = <-ccChan:
cce := unmarshalChaincodeEvent(ccEvent)
handler(cce)
case <-stopchan:
logger.Info("Quit listener for chaincode event")
return
}
}
}
func unmarshalChaincodeEvent(ccEvent *fab.CCEvent) *CCEventDetail {
ced := CCEventDetail{
BlockNumber: ccEvent.BlockNumber,
SourceURL: ccEvent.SourceURL,
TxID: ccEvent.TxID,
ChaincodeID: ccEvent.ChaincodeID,
EventName: ccEvent.EventName,
Payload: string(ccEvent.Payload),
}
return &ced
}
func receiveFilteredBlockEvent(blkChan <-chan *fab.FilteredBlockEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var blkEvent *fab.FilteredBlockEvent
select {
case blkEvent = <-blkChan:
bed := unmarshalFilteredBlockEvent(blkEvent)
handler(bed)
case <-stopchan:
logger.Info("Quit listener for filtered block event")
return
}
}
}
func | (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.FilteredTransactions {
td := TransactionDetail{
TxType: common.HeaderType_name[int32(d.Type)],
TxID: d.Txid,
ChannelID: blk.ChannelId,
Actions: []*ActionDetail{},
}
bed.Transactions = append(bed.Transactions, &td)
actions := d.GetTransactionActions()
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.EventName,
Payload: string(ce.Payload),
},
},
}
td.Actions = append(td.Actions, &action)
}
}
}
}
return &bed
}
func receiveBlockEvent(blkChan <-chan *fab.BlockEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var blkEvent *fab.BlockEvent
select {
case blkEvent = <-blkChan:
bed := unmarshalBlockEvent(blkEvent)
handler(bed)
case <-stopchan:
logger.Info("Quit listener for block event")
return
}
}
}
func unmarshalBlockEvent(blkEvent *fab.BlockEvent) *BlockEventDetail {
bed := BlockEventDetail{
SourceURL: blkEvent.SourceURL,
Number: blkEvent.Block.Header.Number,
Transactions: []*TransactionDetail{},
}
for _, d := range blkEvent.Block.Data.Data {
txn, err := unmarshalTransaction(d)
if err != nil {
logger.Errorf("Error unmarshalling transaction: %+v", err)
continue
} else {
bed.Transactions = append(bed.Transactions, txn)
}
}
return &bed
}
func unmarshalTransaction(data []byte) (*TransactionDetail, error) {
envelope, err := GetEnvelopeFromBlock(data)
if err != nil {
return nil, errors.Wrapf(err, "failed to get envelope")
}
payload, err := UnmarshalPayload(envelope.Payload)
if err != nil {
return nil, errors.Wrapf(err, "failed to get payload")
}
if payload.Header == nil {
return nil, errors.Errorf("payload header is empty")
}
// channel header
chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader)
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: []*ActionDetail{},
}
// signature header
shdr := &common.SignatureHeader{}
if err = proto.Unmarshal(payload.Header.SignatureHeader, shdr); err != nil {
logger.Errorf("failed to unmarshal signature header: %+v", err)
} else {
cid, err := unmarshalIdentity(shdr.Creator)
if err != nil {
logger.Errorf("failed to unmarshal creator identity: %+v", err)
} else {
td.CreatorIdentity = cid
}
}
txn, err := UnmarshalTransaction(payload.Data)
if err != nil {
return &td, errors.Wrapf(err, "failed to get transaction")
}
for _, ta := range txn.Actions {
act, err := unmarshalAction(ta.Payload)
if err != nil {
logger.Errorf("Error unmarshalling action: %+v", err)
continue
} else {
td.Actions = append(td.Actions, act)
}
}
return &td, nil
}
func unmarshalIdentity(data []byte) (*Identity, error) {
cid := &msp.SerializedIdentity{}
if err := proto.Unmarshal(data, cid); err != nil {
return nil, err
}
id := Identity{Mspid: cid.Mspid, Cert: string(cid.IdBytes)}
// extract info from x509 certificate
block, _ := pem.Decode(cid.IdBytes)
if block == nil {
logger.Info("creator certificate is empty")
return &id, nil
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
logger.Errorf("failed to parse creator certificate: %+v", err)
return &id, nil
}
id.Subject = cert.Subject.CommonName
id.Issuer = cert.Issuer.CommonName
return &id, nil
}
func unmarshalAction(data []byte) (*ActionDetail, error) {
ccAction, err := UnmarshalChaincodeActionPayload(data)
if err != nil {
return nil, errors.Wrapf(err, "failed to get action payload | 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 := clientMap[cid]
if ok && client != nil {
return client, nil
}
// create new event client
sdk, err := fabsdk.New(networkConfigProvider(spec.NetworkConfig, spec.EntityMatchers))
if err != nil {
return nil, errors.Wrapf(err, "Failed to create new SDK")
}
opts := []fabsdk.ContextOption{fabsdk.WithUser(spec.UserName)}
if spec.OrgName != "" {
opts = append(opts, fabsdk.WithOrg(spec.OrgName))
}
if spec.EventType == EventFiltered {
client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...))
} else {
client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...), event.WithBlockEvents())
}
if err != nil {
clientMap[cid] = client
}
return client, err
}
func receiveChaincodeEvent(ccChan <-chan *fab.CCEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var ccEvent *fab.CCEvent
select {
case ccEvent = <-ccChan:
cce := unmarshalChaincodeEvent(ccEvent)
handler(cce)
case <-stopchan:
logger.Info("Quit listener for chaincode event")
return
}
}
}
func unmarshalChaincodeEvent(ccEvent *fab.CCEvent) *CCEventDetail {
ced := CCEventDetail{
BlockNumber: ccEvent.BlockNumber,
SourceURL: ccEvent.SourceURL,
TxID: ccEvent.TxID,
ChaincodeID: ccEvent.ChaincodeID,
EventName: ccEvent.EventName,
Payload: string(ccEvent.Payload),
}
return &ced
}
func receiveFilteredBlockEvent(blkChan <-chan *fab.FilteredBlockEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var blkEvent *fab.FilteredBlockEvent
select {
case blkEvent = <-blkChan:
bed := unmarshalFilteredBlockEvent(blkEvent)
handler(bed)
case <-stopchan:
logger.Info("Quit listener for filtered block event")
return
}
}
}
func unmarshalFilteredBlockEvent(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.FilteredTransactions {
td := TransactionDetail{
TxType: common.HeaderType_name[int32(d.Type)],
TxID: d.Txid,
ChannelID: blk.ChannelId,
Actions: []*ActionDetail{},
}
bed.Transactions = append(bed.Transactions, &td)
actions := d.GetTransactionActions()
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.EventName,
Payload: string(ce.Payload),
},
},
}
td.Actions = append(td.Actions, &action)
}
}
}
}
return &bed
}
func receiveBlockEvent(blkChan <-chan *fab.BlockEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var blkEvent *fab.BlockEvent
select {
case blkEvent = <-blkChan:
bed := unmarshalBlockEvent(blkEvent)
handler(bed)
case <-stopchan:
logger.Info("Quit listener for block event")
return
}
}
}
func unmarshalBlockEvent(blkEvent *fab.BlockEvent) *BlockEventDetail {
bed := BlockEventDetail{
SourceURL: blkEvent.SourceURL,
Number: blkEvent.Block.Header.Number,
Transactions: []*TransactionDetail{},
}
for _, d := range blkEvent.Block.Data.Data {
txn, err := unmarshalTransaction(d)
if err != nil {
logger.Errorf("Error unmarshalling transaction: %+v", err)
continue
} else {
bed.Transactions = append(bed.Transactions, txn)
}
}
return &bed
}
func unmarshalTransaction(data []byte) (*TransactionDetail, error) {
envelope, err := GetEnvelopeFromBlock(data)
if err != nil {
return nil, errors.Wrapf(err, "failed to get envelope")
}
payload, err := UnmarshalPayload(envelope.Payload)
if err != nil {
return nil, errors.Wrapf(err, "failed to get payload")
}
if payload.Header == nil {
return nil, errors.Errorf("payload header is empty")
}
// channel header
chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader)
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: []*ActionDetail{},
}
// signature header
shdr := &common.SignatureHeader{}
if err = proto.Unmarshal(payload.Header.SignatureHeader, shdr); err != nil {
logger.Errorf("failed to unmarshal signature header: %+v", err)
} else {
cid, err := unmarshalIdentity(shdr.Creator)
if err != nil {
logger.Errorf("failed to unmarshal creator identity: %+v", err)
} else {
td.CreatorIdentity = cid
}
}
txn, err := UnmarshalTransaction(payload.Data)
if err != nil {
return &td, errors.Wrapf(err, "failed to get transaction")
}
for _, ta := range txn.Actions {
act, err := unmarshalAction(ta.Payload)
if err != nil {
logger.Errorf("Error unmarshalling action: %+v", err)
continue
} else {
td.Actions = append(td.Actions, act)
}
}
return &td, nil
}
func unmarshalIdentity(data []byte) (*Identity, error) {
cid := &msp.SerializedIdentity{}
if err := proto.Unmarshal(data, cid); err != nil {
return nil, err
}
id := Identity{Mspid: cid.Mspid, Cert: string(cid.IdBytes)}
// extract info from x509 certificate
block, _ := pem.Decode(cid.IdBytes)
if block == nil {
logger.Info("creator certificate is empty")
return &id, nil
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
logger.Errorf("failed to parse creator certificate: %+v", err)
return &id, nil
}
id.Subject = cert.Subject.CommonName
id.Issuer = cert.Issuer.CommonName
return &id, nil
}
func unmarshalAction(data []byte) (*ActionDetail, error) {
ccAction, err := UnmarshalChaincodeActionPayload(data)
if err != nil {
return nil, errors.Wrapf(err, "failed to get action payload")
}
// proposal payload
proposalPayload, err := UnmarshalChaincodeProposalPayload(ccAction.ChaincodeProposalPayload)
if err != nil {
return nil, errors.Wrapf(err, "failed to get proposal payload")
}
cis := &pb.ChaincodeInvocationSpec{}
err = proto.Unmarshal(proposalPayload.Input, cis)
if err != nil {
return nil, errors.Wrapf(err, "failed to unmarshal chaincode input")
}
// chaincode spec
ccID := ChaincodeID{
Type: pb.ChaincodeSpec_Type_name[int32(cis.ChaincodeSpec.Type)],
Name: cis.ChaincodeSpec.ChaincodeId.Name,
}
// chaincode input
args := cis.ChaincodeSpec.Input.Args
ccInput := ChaincodeInput{
Function: string(args[0]),
Args: []string{},
}
if len(args) > 1 {
for _, arg := range args[1:] {
ccInput.Args = append(ccInput.Args, string(arg))
}
}
if proposalPayload.TransientMap != nil | {
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.eventFilter)
if err != nil {
return errors.Wrapf(err, "Failed to register chaincode event")
}
logger.Info("chaincode event registered successfully")
c.stopchan = make(chan struct{})
c.exitchan = make(chan struct{})
go func() {
defer close(c.exitchan)
defer c.client.Unregister(registration)
receiveChaincodeEvent(ccChan, c.handler, c.stopchan)
}()
default:
logger.Infof("event type '%s' is not supported", c.eventType)
}
return nil
}
// Stop stops the event listener
func (c *Listener) Stop() {
logger.Info("Stop listener ...")
close(c.stopchan)
<-c.exitchan
logger.Info("Listener stopped")
}
// Spec defines client for fabric events
type Spec struct {
Name string
NetworkConfig []byte
EntityMatchers []byte
OrgName string
UserName string
ChannelID string
EventType string
ChaincodeID string
EventFilter string
}
func clientID(spec *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 := clientMap[cid]
if ok && client != nil {
return client, nil
}
// create new event client
sdk, err := fabsdk.New(networkConfigProvider(spec.NetworkConfig, spec.EntityMatchers))
if err != nil {
return nil, errors.Wrapf(err, "Failed to create new SDK")
}
opts := []fabsdk.ContextOption{fabsdk.WithUser(spec.UserName)}
if spec.OrgName != "" {
opts = append(opts, fabsdk.WithOrg(spec.OrgName))
}
if spec.EventType == EventFiltered {
client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...))
} else {
client, err = event.New(sdk.ChannelContext(spec.ChannelID, opts...), event.WithBlockEvents())
}
if err != nil {
clientMap[cid] = client
}
return client, err
}
func receiveChaincodeEvent(ccChan <-chan *fab.CCEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var ccEvent *fab.CCEvent
select {
case ccEvent = <-ccChan:
cce := unmarshalChaincodeEvent(ccEvent)
handler(cce)
case <-stopchan:
logger.Info("Quit listener for chaincode event")
return
}
}
}
func unmarshalChaincodeEvent(ccEvent *fab.CCEvent) *CCEventDetail {
ced := CCEventDetail{
BlockNumber: ccEvent.BlockNumber,
SourceURL: ccEvent.SourceURL,
TxID: ccEvent.TxID,
ChaincodeID: ccEvent.ChaincodeID,
EventName: ccEvent.EventName,
Payload: string(ccEvent.Payload),
}
return &ced
}
func receiveFilteredBlockEvent(blkChan <-chan *fab.FilteredBlockEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var blkEvent *fab.FilteredBlockEvent
select {
case blkEvent = <-blkChan:
bed := unmarshalFilteredBlockEvent(blkEvent)
handler(bed)
case <-stopchan:
logger.Info("Quit listener for filtered block event")
return
}
}
}
func unmarshalFilteredBlockEvent(blkEvent *fab.FilteredBlockEvent) *BlockEventDetail | 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.EventName,
Payload: string(ce.Payload),
},
},
}
td.Actions = append(td.Actions, &action)
}
}
}
}
return &bed
}
func receiveBlockEvent(blkChan <-chan *fab.BlockEvent, handler EventHandler, stopchan <-chan struct{}) {
for {
var blkEvent *fab.BlockEvent
select {
case blkEvent = <-blkChan:
bed := unmarshalBlockEvent(blkEvent)
handler(bed)
case <-stopchan:
logger.Info("Quit listener for block event")
return
}
}
}
func unmarshalBlockEvent(blkEvent *fab.BlockEvent) *BlockEventDetail {
bed := BlockEventDetail{
SourceURL: blkEvent.SourceURL,
Number: blkEvent.Block.Header.Number,
Transactions: []*TransactionDetail{},
}
for _, d := range blkEvent.Block.Data.Data {
txn, err := unmarshalTransaction(d)
if err != nil {
logger.Errorf("Error unmarshalling transaction: %+v", err)
continue
} else {
bed.Transactions = append(bed.Transactions, txn)
}
}
return &bed
}
func unmarshalTransaction(data []byte) (*TransactionDetail, error) {
envelope, err := GetEnvelopeFromBlock(data)
if err != nil {
return nil, errors.Wrapf(err, "failed to get envelope")
}
payload, err := UnmarshalPayload(envelope.Payload)
if err != nil {
return nil, errors.Wrapf(err, "failed to get payload")
}
if payload.Header == nil {
return nil, errors.Errorf("payload header is empty")
}
// channel header
chdr, err := UnmarshalChannelHeader(payload.Header.ChannelHeader)
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: []*ActionDetail{},
}
// signature header
shdr := &common.SignatureHeader{}
if err = proto.Unmarshal(payload.Header.SignatureHeader, shdr); err != nil {
logger.Errorf("failed to unmarshal signature header: %+v", err)
} else {
cid, err := unmarshalIdentity(shdr.Creator)
if err != nil {
logger.Errorf("failed to unmarshal creator identity: %+v", err)
} else {
td.CreatorIdentity = cid
}
}
txn, err := UnmarshalTransaction(payload.Data)
if err != nil {
return &td, errors.Wrapf(err, "failed to get transaction")
}
for _, ta := range txn.Actions {
act, err := unmarshalAction(ta.Payload)
if err != nil {
logger.Errorf("Error unmarshalling action: %+v", err)
continue
} else {
td.Actions = append(td.Actions, act)
}
}
return &td, nil
}
func unmarshalIdentity(data []byte) (*Identity, error) {
cid := &msp.SerializedIdentity{}
if err := proto.Unmarshal(data, cid); err != nil {
return nil, err
}
id := Identity{Mspid: cid.Mspid, Cert: string(cid.IdBytes)}
// extract info from x509 certificate
block, _ := pem.Decode(cid.IdBytes)
if block == nil {
logger.Info("creator certificate is empty")
return &id, nil
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
logger.Errorf("failed to parse creator certificate: %+v", err)
return &id, nil
}
id.Subject = cert.Subject.CommonName
id.Issuer = cert.Issuer.CommonName
return &id, nil
}
func unmarshalAction(data []byte) (*ActionDetail, error) {
ccAction, err := UnmarshalChaincodeActionPayload(data)
if err != nil {
return nil, errors.Wrapf(err, "failed to get action payload | {
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: common.HeaderType_name[int32(d.Type)],
TxID: d.Txid,
ChannelID: blk.ChannelId,
Actions: []*ActionDetail{},
}
bed.Transactions = append(bed.Transactions, &td)
actions := d.GetTransactionActions() | 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 dist_vecs (vector and magnitude)
self.dist_vecs = tf.map_fn(lambda w: X - w,W)
self.squared_distances = tf.map_fn(lambda w: 2.0*tf.nn.l2_loss(X - w),W)
#Step 4:Calculate 2 best
self.s = tf.math.top_k(-self.squared_distances,k=2)
#1D Index of s1_2d,s2_2d
self.s1_1d = self.s.indices[0]
self.s2_1d = self.s.indices[1]
#2d Index of s1_2d,s2_2d
self.s1_2d = tf.gather(self.ID,self.s1_1d)
self.s2_2d = tf.gather(self.ID,self.s2_1d)
#Step 5: 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 function values
if self.ntype.name == "GAUSSIAN":
self.h = tf.exp(-tf.square(tf.cast(self.l1,dtype=tf.float32))\
/(2.0*sigma*sigma))
elif self.ntype.name == "CONSTANT":
self.h = tf.reshape(tf.where(self.l1 <= nsize,x=tf.ones(self.l1.shape),\
y=tf.zeros(self.l1.shape)),
tf.convert_to_tensor([-1]))
else:
raise ValueError("unknown self.ntype")
#Step 6: Update W
self.W_new = W + eps*tf.matmul(tf.diag(self.h), self.dist_vecs)
def cycle(self, current_iter, mode = Mode["TRAIN"]):
nxt = self.sess.run(self.iter_next)["X"]
if mode.name == "TRAIN":
#Iteration numbers as floats
current_iter_f = float(current_iter)
n_iter_f = float(self.n_iter)
#Get current epsilon and theta
eps = self.eps_i * np.power(self.eps_f/self.eps_i,current_iter_f/n_iter_f)
sigma = self.sigma_i * np.power(self.sigma_f/self.sigma_i,current_iter_f/n_iter_f)
print("Iteration {} - sigma {} - epsilon {}".format(current_iter,sigma,eps))
#Get vector distance, square distance
self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W)))
self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W)))
self.s1_1d = np.argmin(self.squared_distances,axis=-1)
self.s1_2d = self.ID[self.s1_1d]
#Get L1 distances
#self.l1 = np.array(list(map(lambda x: np.linalg.norm(x - self.s1_2d,ord=1),self.ID)))
self.l1 = self.D[self.s1_1d,:]
self.mask = np.reshape(np.where(self.l1 <= sigma),[-1])
if self.ntype.name == "GAUSSIAN":
squared_l1 = np.square(self.l1.astype(np.float32))
self.h = np.exp(-squared_l1 /(2.0*sigma*sigma))
elif self.ntype.name == "CONSTANT":
self.h = np.reshape(np.where(self.l1 <= sigma,1,0),[-1])
for i in np.arange(self.N1*self.N2):
self.W[i,:] += eps * self.h[i] * self.dist_vecs[i,:]
elif mode.name == "TEST":
self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W)))
self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W)))
#Get first and second activation
top_2 = np.argsort(self.squared_distances)[0:2]
self.s1_1d = top_2[0]
self.s2_1d = top_2[1]
self.s1_2d = self.ID[self.s1_1d]
self.s2_2d = self.ID[self.s2_1d]
#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],\
# self.s2_2d,self.squared_distances[self.s2_1d] ))
#Get quantization error
quantization_error = (self.squared_distances[self.s1_1d])
return ({"topographic_error":topographic_error,\
"quantization_error":quantization_error})
def train(self):
#Run initializer
self.sess.run(self.init)
self.sess.run(self.iterator_ds.initializer)
if self.initmode.name == "PCAINIT":
if self.ds_inputdim < 2:
raise ValueError("uniform init needs dim input >= 2")
self.W = np.zeros([self.N1*self.N2,3])
print(self.W.shape)
self.W[:,0:2] = np.reshape(self.ID,[self.N1*self.N2,2])
if self.gridmode.name == "HEXAGON":
print(list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0]))))
self.W[list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))\
,1] -= 0.5
print(self.W.shape)
self.W = np.matmul(self.W,self.pca.components_)
print(self.W.shape)
self.W = StandardScaler().fit_transform(self.W)
print(self.W.shape)
else:
self.W = self.sess.run(tf.random.uniform([self.N1*self.N2,self.ds_inputdim],\
dtype=tf.float32))
self.W = StandardScaler().fit_transform(self.W)
#BEGIN Training
for current_iter in np.arange(self.n_iter):
self.cycle(current_iter)
if current_iter % self.plot_iter == 0:
self.prettygraph(current_iter,mask=self.mask)
self.prettygraph(self.n_iter,mask=self.mask,online=True)
#END Training
#BEGIN Testing
self.sess.run(self.iterator_ds.initializer)
topographic_error = 0
quantization_error = 0
chosen_Mat = np.zeros((self.N1,self.N2))
for current_iter in np.arange(self.ds_size):
cycl = self.cycle(current_iter,mode=Mode["TEST"])
topographic_error += cycl["topographic_error"]
quantization_error += cycl["quantization_error"]
chosen_Mat[self.s1_2d[0],self.s1_2d[1]] += 1
topographic_error = topographic_error / self.ds_size
quantization_error = quantization_error / self.ds_size
#Generate U-Matrix
U_Mat = np.zeros((self.N1,self.N2))
for i in np.arange(self.N1):
for j in np.arange(self.N2):
vert_pos = self.W[i * self.N2 + j]
nbors = self.g.neighbors(i * self.N2 + j)
d = np.sum(\
list(map(lambda x: np.linalg.norm(self.W[x] - vert_pos)\
,nbors)))
U_Mat[i,j] = d
print("Quantization Error:{}".format(quantization_error))
print("Topographic Error:{}".format(topographic_error))
print(np.array(self.characteristics_dict.keys()) )
df_keys = list(self.characteristics_dict.keys()) +\
["quantization_error","topographic_error"]
df_vals = list(self.characteristics_dict.values()) +\
[quantization_error,topographic_error]
#df_vals = [str(x) for x in df_vals]
print(df_keys)
print(df_vals)
print(len(df_keys))
print(len(df_vals))
if os.path.exists("runs.csv"):
print("CSV exists")
df = pd.read_csv("runs.csv",header=0)
df_new = pd.DataFrame(columns=df_keys,index=np.arange(1))
df_new.iloc[0,:] = df_vals
df = df.append(df_new,ignore_index=True)
else:
print("CSV created")
df = pd.DataFrame(columns=df_keys,index=np.arange(1))
df.iloc[0,:] = df_vals
df.to_csv("runs.csv",index=False)
def | 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],\
# self.s2_2d,self.squared_distances[self.s2_1d] ))
#Get quantization error
quantization_error = (self.squared_distances[self.s1_1d])
return ({"topographic_error":topographic_error,\
"quantization_error":quantization_error})
def train(self):
#Run initializer
self.sess.run(self.init)
self.sess.run(self.iterator_ds.initializer)
if self.initmode.name == "PCAINIT":
if self.ds_inputdim < 2:
raise ValueError("uniform init needs dim input >= 2")
self.W = np.zeros([self.N1*self.N2,3])
print(self.W.shape)
self.W[:,0:2] = np.reshape(self.ID,[self.N1*self.N2,2])
if self.gridmode.name == "HEXAGON":
print(list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0]))))
self.W[list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))\
,1] -= 0.5
print(self.W.shape)
self.W = np.matmul(self.W,self.pca.components_)
print(self.W.shape)
self.W = StandardScaler().fit_transform(self.W)
print(self.W.shape)
else:
self.W = self.sess.run(tf.random.uniform([self.N1*self.N2,self.ds_inputdim],\
dtype=tf.float32))
self.W = StandardScaler().fit_transform(self.W)
#BEGIN Training
for current_iter in np.arange(self.n_iter):
self.cycle(current_iter)
if current_iter % self.plot_iter == 0:
self.prettygraph(current_iter,mask=self.mask)
self.prettygraph(self.n_iter,mask=self.mask,online=True)
#END Training
#BEGIN Testing
self.sess.run(self.iterator_ds.initializer)
topographic_error = 0
quantization_error = 0
chosen_Mat = np.zeros((self.N1,self.N2))
for current_iter in np.arange(self.ds_size):
cycl = self.cycle(current_iter,mode=Mode["TEST"])
topographic_error += cycl["topographic_error"]
quantization_error += cycl["quantization_error"]
chosen_Mat[self.s1_2d[0],self.s1_2d[1]] += 1
topographic_error = topographic_error / self.ds_size
quantization_error = quantization_error / self.ds_size
#Generate U-Matrix
U_Mat = np.zeros((self.N1,self.N2))
for i in np.arange(self.N1):
for j in np.arange(self.N2):
vert_pos = self.W[i * self.N2 + j]
nbors = self.g.neighbors(i * self.N2 + j)
d = np.sum(\
list(map(lambda x: np.linalg.norm(self.W[x] - vert_pos)\
,nbors)))
U_Mat[i,j] = d
print("Quantization Error:{}".format(quantization_error))
print("Topographic Error:{}".format(topographic_error))
print(np.array(self.characteristics_dict.keys()) )
df_keys = list(self.characteristics_dict.keys()) +\
["quantization_error","topographic_error"]
df_vals = list(self.characteristics_dict.values()) +\
[quantization_error,topographic_error]
#df_vals = [str(x) for x in df_vals]
print(df_keys)
print(df_vals)
print(len(df_keys))
print(len(df_vals))
if os.path.exists("runs.csv"):
print("CSV exists")
df = pd.read_csv("runs.csv",header=0)
df_new = pd.DataFrame(columns=df_keys,index=np.arange(1))
df_new.iloc[0,:] = df_vals
df = df.append(df_new,ignore_index=True)
else:
print("CSV created")
df = pd.DataFrame(columns=df_keys,index=np.arange(1))
df.iloc[0,:] = df_vals
df.to_csv("runs.csv",index=False)
def inputScatter3D(self):
Xn = self.input_pca[:,0]
Yn = self.input_pca[:,1]
Zn = self.input_pca[:,2]
Y = self.sess.run(tf.cast(tf.argmax(self.Y,axis=-1),dtype=tf.int32) )
Y = [int(x) for x in Y]
num_class = len(Y)
pal = ig.ClusterColoringPalette(num_class)
if self.plotmode.name == "CLASS_COLOR":
col = pal.get_many(Y)
siz = 2
else:
col = "green"
siz = 1.5
trace0=go.Scatter3d(x=Xn,
y=Yn,
z=Zn,
mode='markers',
name='input',
marker=dict(symbol='circle',
size=siz,
color=col,
line=dict(color='rgb(50,50,50)', width=0.25)
),
text="",
hoverinfo='text'
)
return(trace0)
def prettygraph(self,iter_number, mask,online = False):
trace0 = self.input_pca_scatter
W = self.pca.transform(self.W)
Xn=W[:,0]# x-coordinates of nodes
Yn=W[:,1] # y-coordinates
if self.ds_name in ["box","grid"]:
Zn=self.W[:,2] # z-coordinates
else:
Zn=W[:,2] # z-coordinates
edge_colors = []
Xe=[]
Ye=[]
Ze=[]
num_pallete = 1000
for e in self.g.get_edgelist():
#col = self.g.es.find(_between=((e[0],), (e[1],)),)["age"]
#col = float(col)/float(1)
#col = min(num_pallete-1, int(num_pallete * col))
#edge_colors += [col,col]
Xe+=[W[e[0],0],W[e[1],0],None]# x-coordinates of edge ends
Ye+=[W[e[0],1],W[e[1],1],None]# y-coordinates of edge ends
Ze+=[W[e[0],2],W[e[1],2],None]# z-coordinates of edge ends
#Create Scaling for edges based on Age
pal_V = ig.GradientPalette("blue", "black", num_pallete)
pal_E = ig.GradientPalette("black", "white", num_pallete)
v_colors = ["orange" for a in np.arange(self.g.vcount())]
for v in mask:
v_colors[v] = "yellow"
trace1=go.Scatter3d(x=Xe,
y=Ye,
z=Ze,
mode='lines',
line=dict(color="black",
width=3),
hoverinfo='none'
)
reference_vec_text = ["m" + str(x) for x in np.arange(self.W.shape[0])]
trace2=go.Scatter3d(x=Xn,
y=Yn,
z=Zn,
mode='markers',
name='reference_vectors',
marker=dict(symbol='square',
size=6,
color=v_colors,
line=dict(color='rgb(50,50,50)', width=0.5)
),
text=reference_vec_text,
hoverinfo='text'
)
axis=dict(showbackground=False,
showline=True,
zeroline=False,
showgrid=False,
showticklabels=True,
title='',
range = [-self.input_pca_maxval-1,1+self.input_pca_maxval]
)
layout = go.Layout(
title="Visualization of SOM",
width=1000,
height=1000,
showlegend=False,
scene=dict(
xaxis=dict(axis),
yaxis=dict(axis),
zaxis=dict(axis),
),
margin=dict(
t=100
),
hovermode='closest',
annotations=[
dict(
showarrow=False,
text="Data source:</a>",
xref='paper',
yref='paper',
x=0,
y=0.1,
xanchor='left',
yanchor='bottom',
font=dict(
size=14
)
)
], )
data=[trace1, trace2, trace0]
fig=go.Figure(data=data, layout=layout)
OUTPATH = "./plot/"
for k, v in sorted(zip(self.characteristics_dict.keys(),self.characteristics_dict.values()),key = lambda t: (t[0].lower()) ):
| 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 function values
if self.ntype.name == "GAUSSIAN":
self.h = tf.exp(-tf.square(tf.cast(self.l1,dtype=tf.float32))\
/(2.0*sigma*sigma))
elif self.ntype.name == "CONSTANT":
self.h = tf.reshape(tf.where(self.l1 <= nsize,x=tf.ones(self.l1.shape),\
y=tf.zeros(self.l1.shape)),
tf.convert_to_tensor([-1]))
else:
raise ValueError("unknown self.ntype")
#Step 6: Update W
self.W_new = W + eps*tf.matmul(tf.diag(self.h), self.dist_vecs)
def cycle(self, current_iter, mode = Mode["TRAIN"]):
nxt = self.sess.run(self.iter_next)["X"]
if mode.name == "TRAIN":
#Iteration numbers as floats
current_iter_f = float(current_iter)
n_iter_f = float(self.n_iter)
#Get current epsilon and theta
eps = self.eps_i * np.power(self.eps_f/self.eps_i,current_iter_f/n_iter_f)
sigma = self.sigma_i * np.power(self.sigma_f/self.sigma_i,current_iter_f/n_iter_f)
print("Iteration {} - sigma {} - epsilon {}".format(current_iter,sigma,eps))
#Get vector distance, square distance
self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W)))
self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W)))
self.s1_1d = np.argmin(self.squared_distances,axis=-1)
self.s1_2d = self.ID[self.s1_1d]
#Get L1 distances
#self.l1 = np.array(list(map(lambda x: np.linalg.norm(x - self.s1_2d,ord=1),self.ID)))
self.l1 = self.D[self.s1_1d,:]
self.mask = np.reshape(np.where(self.l1 <= sigma),[-1])
if self.ntype.name == "GAUSSIAN":
squared_l1 = np.square(self.l1.astype(np.float32))
self.h = np.exp(-squared_l1 /(2.0*sigma*sigma))
elif self.ntype.name == "CONSTANT":
self.h = np.reshape(np.where(self.l1 <= sigma,1,0),[-1])
for i in np.arange(self.N1*self.N2):
self.W[i,:] += eps * self.h[i] * self.dist_vecs[i,:]
elif mode.name == "TEST":
self.dist_vecs = np.array(list(map(lambda w: nxt - w,self.W)))
self.squared_distances = np.array(list(map(lambda w: np.linalg.norm(nxt - w,ord=2),self.W)))
#Get first and second activation
top_2 = np.argsort(self.squared_distances)[0:2]
self.s1_1d = top_2[0]
self.s2_1d = top_2[1]
self.s1_2d = self.ID[self.s1_1d]
self.s2_2d = self.ID[self.s2_1d]
#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],\
# self.s2_2d,self.squared_distances[self.s2_1d] ))
#Get quantization error
quantization_error = (self.squared_distances[self.s1_1d])
return ({"topographic_error":topographic_error,\
"quantization_error":quantization_error})
def train(self):
#Run initializer
self.sess.run(self.init)
self.sess.run(self.iterator_ds.initializer)
if self.initmode.name == "PCAINIT":
if self.ds_inputdim < 2:
raise ValueError("uniform init needs dim input >= 2")
self.W = np.zeros([self.N1*self.N2,3])
print(self.W.shape)
self.W[:,0:2] = np.reshape(self.ID,[self.N1*self.N2,2])
if self.gridmode.name == "HEXAGON":
print(list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0]))))
self.W[list(map(lambda x: (x//self.N2%2==0),np.arange(self.W.shape[0])))\
,1] -= 0.5
print(self.W.shape)
self.W = np.matmul(self.W,self.pca.components_)
print(self.W.shape)
self.W = StandardScaler().fit_transform(self.W)
print(self.W.shape)
else:
self.W = self.sess.run(tf.random.uniform([self.N1*self.N2,self.ds_inputdim],\
dtype=tf.float32))
self.W = StandardScaler().fit_transform(self.W)
#BEGIN Training
for current_iter in np.arange(self.n_iter):
self.cycle(current_iter)
if current_iter % self.plot_iter == 0:
self.prettygraph(current_iter,mask=self.mask)
self.prettygraph(self.n_iter,mask=self.mask,online=True)
#END Training
#BEGIN Testing
self.sess.run(self.iterator_ds.initializer)
topographic_error = 0
quantization_error = 0
chosen_Mat = np.zeros((self.N1,self.N2))
for current_iter in np.arange(self.ds_size):
cycl = self.cycle(current_iter,mode=Mode["TEST"])
topographic_error += cycl["topographic_error"]
quantization_error += cycl["quantization_error"]
chosen_Mat[self.s1_2d[0],self.s1_2d[1]] += 1
topographic_error = topographic_error / self.ds_size
quantization_error = quantization_error / self.ds_size
#Generate U-Matrix
U_Mat = np.zeros((self.N1,self.N2))
for i in np.arange(self.N1):
for j in np.arange(self.N2):
vert_pos = self.W[i * self.N2 + j]
nbors = self.g.neighbors(i * self.N2 + j)
d = np.sum(\
list(map(lambda x: np.linalg.norm(self.W[x] - vert_pos)\
,nbors)))
U_Mat[i,j] = d
print("Quantization Error:{}".format(quantization_error))
print("Topographic Error:{}".format(topographic_error))
print(np.array(self.characteristics_dict.keys()) )
df_keys = list(self.characteristics_dict.keys()) +\
["quantization_error","topographic_error"]
df_vals = list(self.characteristics_dict.values()) +\
[quantization_error,topographic_error]
#df_vals = [str(x) for x in df_vals]
print(df_keys)
print(df_vals)
print(len(df_keys))
print(len(df_vals))
if os.path.exists("runs.csv"):
print("CSV exists")
df = pd.read_csv("runs.csv",header=0)
df_new = pd.DataFrame(columns=df_keys,index=np.arange(1))
df_new.iloc[0,:] = df_vals
df = df.append(df_new,ignore_index=True)
else:
print("CSV created")
df = pd.DataFrame(columns=df_keys,index=np.arange(1))
df.iloc[0,:] = df_vals
df.to_csv("runs.csv",index=False)
def inputScatter3D(self):
Xn = self.input_pca[:,0]
Yn = self.input_pca[:,1]
Zn = self.input_pca[:,2]
Y = self.sess.run(tf.cast(tf.argmax(self.Y,axis=-1),dtype=tf.int32) )
Y = [int(x) for x in Y]
num_class = len(Y)
pal = ig.ClusterColoringPalette(num_class)
if self.plotmode.name == "CLASS_COLOR":
col = pal.get_many(Y)
siz = 2
else:
col = "green"
siz = 1.5
trace0=go.Scatter3d(x=Xn,
y=Yn,
z=Zn,
mode='markers',
name='input',
marker=dict(symbol='circle',
size=siz,
color=col,
line=dict(color='rgb(50,50,50)', width=0.25)
),
text="",
hoverinfo='text'
)
return(trace0)
def prettygraph(self,iter_number, mask,online = False): |
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.ds = temp["dataset"]
df_x_normalized = temp["df_x"]
self.Y = temp["df_y"]
#Get PCA for dataset
print("Generating PCA for further plotting...")
self.pca = PCA(n_components=3)
self.input_pca = self.pca.fit_transform(df_x_normalized)
self.input_pca_scatter = self.inputScatter3D()
self.input_pca_maxval = -np.sort(-np.abs(np.reshape(self.input_pca,[-1])),axis=0)[5]
print("Done!")
print("Dimensionality of Y:{}",self.ds_inputdim)
self.ds = self.ds.shuffle(buffer_size=10000).repeat()
if args.dataset == "box":
self.ds = gd.get_box()
#Now generate iterators for dataset
self.iterator_ds = self.ds.make_initializable_iterator()
self.iter_next = self.iterator_ds.get_next()
# tf Graph input
self.X_placeholder = tf.placeholder("float", [self.ds_inputdim])
self.W_placeholder = tf.placeholder("float", [self.N1*self.N2,self.ds_inputdim])
self.nborhood_size_placeholder = tf.placeholder("int32", [])
self.sigma_placeholder = tf.placeholder("float", [])
self.eps_placeholder = tf.placeholder("float", [])
print("Initializing graph and global vars...")
self.init_graph()
# Initializing the variables
self.init = tf.global_variables_initializer()
print("Done!")
''' Transforms dataset back to dataframe'''
def getDatasetAsDF(self,dataset):
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
num_elems = 0
while True:
try:
x, y = self.sess.run([next_element["X"], next_element["Y"]])
if num_elems == 0:
df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\
columns = np.arange(x.shape[0])
)
print(y)
df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\
columns = np.arange(y.shape[0])
)
df_x.iloc[num_elems,:] = x
df_y.iloc[num_elems,:] = y
num_elems += 1
except tf.errors.OutOfRangeError:
break
return({"df_x":df_x,"df_y":df_y})
''' Returns the total number of elements of a dataset
@param dataset: the given dataset
@return: total number of elements
'''
def getNumElementsOfDataset(self,dataset):
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
num_elems = 0
while True:
try:
self.sess.run(next_element)
num_elems += 1
except tf.errors.OutOfRangeError:
break
return num_elems
''' Returns the dimensionality of the first element of dataset
@param dataset: the given dataset
@return: total number of elements
'''
def getInputShapeOfDataset(self,dataset):
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
d = None
try:
self.sess.run(next_element)
d = next_element["X"].shape[0]
except tf.errors.OutOfRangeError:
return d
return int(d)
''' Returns the normalized version of a given dataset
@param dataset: the given dataset, such that each element returns an "X" and "Y"
@return: dict, with keys
"df_x": normalized elements,
"df_y": corresponding class attr.,
"dataset": normalized dataset ("X" and "Y")
'''
def normalizedDataset(self,dataset):
iterator = dataset.make_one_shot_iterator()
next_element = iterator.get_next()
num_elems = 0
while True:
try:
x, y = self.sess.run([next_element["X"], next_element["Y"]])
if num_elems == 0:
df_x = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\
columns = np.arange(x.shape[0])
)
print(y)
df_y = pd.DataFrame(0,index = np.arange(self.getNumElementsOfDataset(dataset)),\
columns = np.arange(y.shape[0])
)
df_x.iloc[num_elems,:] = x
df_y.iloc[num_elems,:] = y
num_elems += 1
except tf.errors.OutOfRangeError:
break
df_x = StandardScaler().fit_transform(df_x)
print(df_y)
return({"df_x": df_x,
"df_y": df_y,
"dataset": tf.data.Dataset.from_tensor_slices({"X":df_x,"Y":df_y}) \
})
''' Initializes the SOM graph
'''
def init_graph(self):
#initial topology
self.g = ig.Graph()
self.g.add_vertices(self.N1*self.N2)
incr = [(0,1),(0,-1),(1,0),(-1,0)]
def isvalid(x):
|
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)
self.g.vs[toOneDim(curr)]["i"] = i
self.g.vs[toOneDim(curr)]["j"] = j
if self.gridmode.name == "RECTANGLE":
incr = [(0,1),(0,-1),(1,0),(-1,0)]
else:
if i % 2 == 0:
incr = [(0,1),(0,-1),(-1,-1),(-1,0),(1,-1),(1,0)]
else:
incr = [(0,1),(0,-1),(-1,1),(-1,0),(1,1),(1,0)]
nbors = list(map(lambda x: sum_tuple(x,curr),incr))
nbors_exist = list(map(lambda x: isvalid(x),nbors))
for n in np.arange(len(nbors)):
if nbors_exist[n]:
edges += [(toOneDim(curr), toOneDim(nbors[n]))]
print(str(curr) + "->" + str(nbors[n]) )
self.g.add_edges(edges)
self.g.es["age"] = 0
#self.ID: maps index of each node to its corresponding position tuple (line, col)
self.ID = np.array(list(map(lambda x: [self.g.vs[x]["i"],self.g.vs[x]["j"]],\
np.arange(self.N1*self.N2))),dtype=np.int32 )
self.ID = np.reshape(self.ID,(-1,2))
#Initialize distances
print("Calculating distances...")
self.D = np.array(self.g.shortest_paths(source=None, target=None, weights=None, 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 dist_vecs (vector and magnitude)
self.dist_vecs = tf.map_fn(lambda w: X - w,W)
self.squared_distances = tf.map_fn(lambda w: 2.0*tf.nn.l2_loss(X - w),W)
#Step 4:Calculate 2 best
self.s = tf.math.top_k(-self.squared_distances,k=2)
#1D Index of s1_2d,s2_2d
self.s1_1d = self.s.indices[0]
self.s2_1d = self.s.indices[1]
#2d Index of s1_2d,s2_2d
self.s1_2d = tf.gather(self.ID,self.s1_1d)
self.s2_2d = tf.gather(self.ID,self.s2_1d)
#Step 5: 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 function values
if self.ntype.name == "GAUSSIAN":
self.h = tf.exp(-tf.square(tf.cast(self.l1,dtype=tf.float32))\
/(2.0*sigma*sigma))
elif self.ntype.name == "CONSTANT":
self | 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::{Graph, Fork, Rope};
use leaf::Leaf;
use util::{Literal, Definition};
use proc_macro::TokenStream;
use quote::quote;
use syn::{Ident, Fields, ItemEnum, GenericParam, Attribute};
use syn::spanned::Spanned;
enum Mode {
Utf8,
Binary,
}
#[proc_macro_derive(
Logos,
attributes(logos, extras, error, end, token, regex, extras)
)]
pub fn logos(input: TokenStream) -> TokenStream | 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") {
if let Some(nested) = util::read_attr("logos", attr)? {
let span = nested.span();
if let Some(ext) = util::value_from_nested("extras", &nested)? {
if extras.replace(ext).is_some() {
return Err(Error::new("Extras can be defined only once.").span(span));
}
}
if let Err(_) = util::value_from_nested("trivia", &nested) {
const ERR: &str = "\
trivia are no longer supported.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases";
return Err(Error::new(ERR).span(span));
}
}
}
if attr.path.is_ident("extras") {
const ERR: &str = "\
#[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 {
if let Err(err) = parse_attr(attr) {
errors.push(err);
}
}
let mut variants = Vec::new();
let mut ropes = Vec::new();
let mut regex_ids = Vec::new();
let mut graph = Graph::new();
for variant in &item.variants {
variants.push(&variant.ident);
let span = variant.span();
if let Some((_, value)) = &variant.discriminant {
let span = value.span();
let value = util::unpack_int(value).unwrap_or(usize::max_value());
if value >= size {
errors.push(Error::new(
format!(
"Discriminant value for `{}` is invalid. Expected integer in range 0..={}.",
variant.ident,
size,
),
).span(span));
}
}
let field = match &variant.fields {
Fields::Unit => None,
Fields::Unnamed(ref fields) => {
if fields.unnamed.len() != 1 {
errors.push(Error::new(
format!(
"Logos currently only supports variants with one field, found {}",
fields.unnamed.len(),
)
).span(fields.span()))
}
let field = fields.unnamed.first().expect("Already checked len; qed").ty.clone();
Some(field)
}
Fields::Named(_) => {
errors.push(Error::new("Logos doesn't support named fields yet.").span(span));
None
}
};
for attr in &variant.attrs {
let variant = &variant.ident;
let mut with_definition = |definition: Definition<Literal>| {
if let Literal::Bytes(..) = definition.value {
mode = Mode::Binary;
}
(
Leaf::token(variant).field(field.clone()).callback(definition.callback),
definition.value,
)
};
if attr.path.is_ident("error") {
if let Some(previous) = error.replace(variant) {
errors.extend(vec![
Error::new("Only one #[error] variant can be declared.").span(span),
Error::new("Previously declared #[error]:").span(previous.span()),
]);
}
} else if attr.path.is_ident("end") {
errors.push(
Error::new(
"Since 0.11 Logos no longer requires the #[end] variant.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"
).span(attr.span())
);
} else if attr.path.is_ident("token") {
match util::value_from_attr("token", attr) {
Ok(Some(definition)) => {
let (token, value) = with_definition(definition);
let value = value.into_bytes();
let then = graph.push(token.priority(value.len()));
ropes.push(Rope::new(value, then));
},
Err(err) => errors.push(err),
_ => (),
}
} else if attr.path.is_ident("regex") {
match util::value_from_attr("regex", attr) {
Ok(Some(definition)) => {
let (token, value) = with_definition(definition);
let then = graph.reserve();
let (utf8, regex, span) = match value {
Literal::Utf8(string, span) => (true, string, span),
Literal::Bytes(bytes, span) => {
mode = Mode::Binary;
(false, util::bytes_to_regex_string(&bytes), span)
}
};
match graph.regex(utf8, ®ex, then.get()) {
Ok((len, mut id)) => {
let then = graph.insert(then, token.priority(len));
regex_ids.push(id);
// Drain recursive miss values.
// We need the root node to have straight branches.
while let Some(miss) = graph[id].miss() {
if miss == then {
errors.push(
Error::new("#[regex]: expression can match empty string.\n\n\
hint: consider changing * to +").span(span)
);
break;
} else {
regex_ids.push(miss);
id = miss;
}
}
},
Err(err) => errors.push(err.span(span)),
}
},
Err(err) => errors.push(err),
_ => (),
}
}
}
}
let mut root = Fork::new();
let extras = match extras {
Some(ext) => quote!(#ext),
None => quote!(()),
};
let source = match mode {
Mode::Utf8 => quote!(str),
Mode::Binary => quote!([u8]),
};
let error_def = match error {
Some(error) => Some(quote!(const ERROR: Self = #name::#error;)),
None => {
errors.push(Error::new("missing #[error] token variant.").span(super_span));
None
},
};
let this = quote!(#name #generics);
let impl_logos = |body| {
quote! {
impl<'s> ::logos::Logos<'s> for #this {
type Extras = #extras;
type Source = #source;
const SIZE: usize = #size;
#error_def
fn lex(lex: &mut ::logos::Lexer<'s, Self>) {
#body
}
}
}
};
if errors.len() > 0 {
return impl_logos(quote! {
fn _logos_derive_compile_errors() {
#(#errors)*
}
}).into()
}
for id in regex_ids {
let fork = graph.fork_off(id);
root.merge(fork, &mut graph);
}
for rope in ropes {
root.merge(rope.into_fork(&mut graph), &mut graph)
}
while let Some(id) = root.miss.take() {
let fork = graph.fork_off(id);
if fork.branches().next().is_some() {
root.merge(fork, &mut graph);
} else {
break;
}
}
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 ::logos::internal::{LexerInternal, CallbackResult};
type Lexer<'s> = :: | {
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::new();
let generics = match item.generics.params.len() {
0 => {
None
},
1 if matches!(item.generics.params.first(), Some(GenericParam::Lifetime(..))) => {
Some(quote!(<'s>))
},
_ => { | 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::{Graph, Fork, Rope};
use leaf::Leaf;
use util::{Literal, Definition};
use proc_macro::TokenStream;
use quote::quote;
use syn::{Ident, Fields, ItemEnum, GenericParam, Attribute};
use syn::spanned::Spanned;
enum Mode {
Utf8,
Binary,
}
#[proc_macro_derive(
Logos,
attributes(logos, extras, error, end, token, regex, extras)
)]
pub fn | (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 = Mode::Utf8;
let mut errors = Vec::new();
let generics = match item.generics.params.len() {
0 => {
None
},
1 if matches!(item.generics.params.first(), Some(GenericParam::Lifetime(..))) => {
Some(quote!(<'s>))
},
_ => {
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") {
if let Some(nested) = util::read_attr("logos", attr)? {
let span = nested.span();
if let Some(ext) = util::value_from_nested("extras", &nested)? {
if extras.replace(ext).is_some() {
return Err(Error::new("Extras can be defined only once.").span(span));
}
}
if let Err(_) = util::value_from_nested("trivia", &nested) {
const ERR: &str = "\
trivia are no longer supported.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases";
return Err(Error::new(ERR).span(span));
}
}
}
if attr.path.is_ident("extras") {
const ERR: &str = "\
#[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 {
if let Err(err) = parse_attr(attr) {
errors.push(err);
}
}
let mut variants = Vec::new();
let mut ropes = Vec::new();
let mut regex_ids = Vec::new();
let mut graph = Graph::new();
for variant in &item.variants {
variants.push(&variant.ident);
let span = variant.span();
if let Some((_, value)) = &variant.discriminant {
let span = value.span();
let value = util::unpack_int(value).unwrap_or(usize::max_value());
if value >= size {
errors.push(Error::new(
format!(
"Discriminant value for `{}` is invalid. Expected integer in range 0..={}.",
variant.ident,
size,
),
).span(span));
}
}
let field = match &variant.fields {
Fields::Unit => None,
Fields::Unnamed(ref fields) => {
if fields.unnamed.len() != 1 {
errors.push(Error::new(
format!(
"Logos currently only supports variants with one field, found {}",
fields.unnamed.len(),
)
).span(fields.span()))
}
let field = fields.unnamed.first().expect("Already checked len; qed").ty.clone();
Some(field)
}
Fields::Named(_) => {
errors.push(Error::new("Logos doesn't support named fields yet.").span(span));
None
}
};
for attr in &variant.attrs {
let variant = &variant.ident;
let mut with_definition = |definition: Definition<Literal>| {
if let Literal::Bytes(..) = definition.value {
mode = Mode::Binary;
}
(
Leaf::token(variant).field(field.clone()).callback(definition.callback),
definition.value,
)
};
if attr.path.is_ident("error") {
if let Some(previous) = error.replace(variant) {
errors.extend(vec![
Error::new("Only one #[error] variant can be declared.").span(span),
Error::new("Previously declared #[error]:").span(previous.span()),
]);
}
} else if attr.path.is_ident("end") {
errors.push(
Error::new(
"Since 0.11 Logos no longer requires the #[end] variant.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"
).span(attr.span())
);
} else if attr.path.is_ident("token") {
match util::value_from_attr("token", attr) {
Ok(Some(definition)) => {
let (token, value) = with_definition(definition);
let value = value.into_bytes();
let then = graph.push(token.priority(value.len()));
ropes.push(Rope::new(value, then));
},
Err(err) => errors.push(err),
_ => (),
}
} else if attr.path.is_ident("regex") {
match util::value_from_attr("regex", attr) {
Ok(Some(definition)) => {
let (token, value) = with_definition(definition);
let then = graph.reserve();
let (utf8, regex, span) = match value {
Literal::Utf8(string, span) => (true, string, span),
Literal::Bytes(bytes, span) => {
mode = Mode::Binary;
(false, util::bytes_to_regex_string(&bytes), span)
}
};
match graph.regex(utf8, ®ex, then.get()) {
Ok((len, mut id)) => {
let then = graph.insert(then, token.priority(len));
regex_ids.push(id);
// Drain recursive miss values.
// We need the root node to have straight branches.
while let Some(miss) = graph[id].miss() {
if miss == then {
errors.push(
Error::new("#[regex]: expression can match empty string.\n\n\
hint: consider changing * to +").span(span)
);
break;
} else {
regex_ids.push(miss);
id = miss;
}
}
},
Err(err) => errors.push(err.span(span)),
}
},
Err(err) => errors.push(err),
_ => (),
}
}
}
}
let mut root = Fork::new();
let extras = match extras {
Some(ext) => quote!(#ext),
None => quote!(()),
};
let source = match mode {
Mode::Utf8 => quote!(str),
Mode::Binary => quote!([u8]),
};
let error_def = match error {
Some(error) => Some(quote!(const ERROR: Self = #name::#error;)),
None => {
errors.push(Error::new("missing #[error] token variant.").span(super_span));
None
},
};
let this = quote!(#name #generics);
let impl_logos = |body| {
quote! {
impl<'s> ::logos::Logos<'s> for #this {
type Extras = #extras;
type Source = #source;
const SIZE: usize = #size;
#error_def
fn lex(lex: &mut ::logos::Lexer<'s, Self>) {
#body
}
}
}
};
if errors.len() > 0 {
return impl_logos(quote! {
fn _logos_derive_compile_errors() {
#(#errors)*
}
}).into()
}
for id in regex_ids {
let fork = graph.fork_off(id);
root.merge(fork, &mut graph);
}
for rope in ropes {
root.merge(rope.into_fork(&mut graph), &mut graph)
}
while let Some(id) = root.miss.take() {
let fork = graph.fork_off(id);
if fork.branches().next().is_some() {
root.merge(fork, &mut graph);
} else {
break;
}
}
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 ::logos::internal::{LexerInternal, CallbackResult};
type Lexer<'s> = | 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::{Graph, Fork, Rope};
use leaf::Leaf;
use util::{Literal, Definition};
use proc_macro::TokenStream;
use quote::quote;
use syn::{Ident, Fields, ItemEnum, GenericParam, Attribute};
use syn::spanned::Spanned;
enum Mode {
Utf8,
Binary,
}
#[proc_macro_derive(
Logos,
attributes(logos, extras, error, end, token, regex, extras)
)]
pub fn logos(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 = Mode::Utf8;
let mut errors = Vec::new();
let generics = match item.generics.params.len() {
0 => {
None
},
1 if matches!(item.generics.params.first(), Some(GenericParam::Lifetime(..))) => {
Some(quote!(<'s>))
},
_ => {
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") {
if let Some(nested) = util::read_attr("logos", attr)? {
let span = nested.span();
if let Some(ext) = util::value_from_nested("extras", &nested)? {
if extras.replace(ext).is_some() {
return Err(Error::new("Extras can be defined only once.").span(span));
}
}
if let Err(_) = util::value_from_nested("trivia", &nested) {
const ERR: &str = "\
trivia are no longer supported.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases";
return Err(Error::new(ERR).span(span));
}
}
}
if attr.path.is_ident("extras") { | #[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 {
if let Err(err) = parse_attr(attr) {
errors.push(err);
}
}
let mut variants = Vec::new();
let mut ropes = Vec::new();
let mut regex_ids = Vec::new();
let mut graph = Graph::new();
for variant in &item.variants {
variants.push(&variant.ident);
let span = variant.span();
if let Some((_, value)) = &variant.discriminant {
let span = value.span();
let value = util::unpack_int(value).unwrap_or(usize::max_value());
if value >= size {
errors.push(Error::new(
format!(
"Discriminant value for `{}` is invalid. Expected integer in range 0..={}.",
variant.ident,
size,
),
).span(span));
}
}
let field = match &variant.fields {
Fields::Unit => None,
Fields::Unnamed(ref fields) => {
if fields.unnamed.len() != 1 {
errors.push(Error::new(
format!(
"Logos currently only supports variants with one field, found {}",
fields.unnamed.len(),
)
).span(fields.span()))
}
let field = fields.unnamed.first().expect("Already checked len; qed").ty.clone();
Some(field)
}
Fields::Named(_) => {
errors.push(Error::new("Logos doesn't support named fields yet.").span(span));
None
}
};
for attr in &variant.attrs {
let variant = &variant.ident;
let mut with_definition = |definition: Definition<Literal>| {
if let Literal::Bytes(..) = definition.value {
mode = Mode::Binary;
}
(
Leaf::token(variant).field(field.clone()).callback(definition.callback),
definition.value,
)
};
if attr.path.is_ident("error") {
if let Some(previous) = error.replace(variant) {
errors.extend(vec![
Error::new("Only one #[error] variant can be declared.").span(span),
Error::new("Previously declared #[error]:").span(previous.span()),
]);
}
} else if attr.path.is_ident("end") {
errors.push(
Error::new(
"Since 0.11 Logos no longer requires the #[end] variant.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"
).span(attr.span())
);
} else if attr.path.is_ident("token") {
match util::value_from_attr("token", attr) {
Ok(Some(definition)) => {
let (token, value) = with_definition(definition);
let value = value.into_bytes();
let then = graph.push(token.priority(value.len()));
ropes.push(Rope::new(value, then));
},
Err(err) => errors.push(err),
_ => (),
}
} else if attr.path.is_ident("regex") {
match util::value_from_attr("regex", attr) {
Ok(Some(definition)) => {
let (token, value) = with_definition(definition);
let then = graph.reserve();
let (utf8, regex, span) = match value {
Literal::Utf8(string, span) => (true, string, span),
Literal::Bytes(bytes, span) => {
mode = Mode::Binary;
(false, util::bytes_to_regex_string(&bytes), span)
}
};
match graph.regex(utf8, ®ex, then.get()) {
Ok((len, mut id)) => {
let then = graph.insert(then, token.priority(len));
regex_ids.push(id);
// Drain recursive miss values.
// We need the root node to have straight branches.
while let Some(miss) = graph[id].miss() {
if miss == then {
errors.push(
Error::new("#[regex]: expression can match empty string.\n\n\
hint: consider changing * to +").span(span)
);
break;
} else {
regex_ids.push(miss);
id = miss;
}
}
},
Err(err) => errors.push(err.span(span)),
}
},
Err(err) => errors.push(err),
_ => (),
}
}
}
}
let mut root = Fork::new();
let extras = match extras {
Some(ext) => quote!(#ext),
None => quote!(()),
};
let source = match mode {
Mode::Utf8 => quote!(str),
Mode::Binary => quote!([u8]),
};
let error_def = match error {
Some(error) => Some(quote!(const ERROR: Self = #name::#error;)),
None => {
errors.push(Error::new("missing #[error] token variant.").span(super_span));
None
},
};
let this = quote!(#name #generics);
let impl_logos = |body| {
quote! {
impl<'s> ::logos::Logos<'s> for #this {
type Extras = #extras;
type Source = #source;
const SIZE: usize = #size;
#error_def
fn lex(lex: &mut ::logos::Lexer<'s, Self>) {
#body
}
}
}
};
if errors.len() > 0 {
return impl_logos(quote! {
fn _logos_derive_compile_errors() {
#(#errors)*
}
}).into()
}
for id in regex_ids {
let fork = graph.fork_off(id);
root.merge(fork, &mut graph);
}
for rope in ropes {
root.merge(rope.into_fork(&mut graph), &mut graph)
}
while let Some(id) = root.miss.take() {
let fork = graph.fork_off(id);
if fork.branches().next().is_some() {
root.merge(fork, &mut graph);
} else {
break;
}
}
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 ::logos::internal::{LexerInternal, CallbackResult};
type Lexer<'s> = :: | 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::{Graph, Fork, Rope};
use leaf::Leaf;
use util::{Literal, Definition};
use proc_macro::TokenStream;
use quote::quote;
use syn::{Ident, Fields, ItemEnum, GenericParam, Attribute};
use syn::spanned::Spanned;
enum Mode {
Utf8,
Binary,
}
#[proc_macro_derive(
Logos,
attributes(logos, extras, error, end, token, regex, extras)
)]
pub fn logos(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 = Mode::Utf8;
let mut errors = Vec::new();
let generics = match item.generics.params.len() {
0 => {
None
},
1 if matches!(item.generics.params.first(), Some(GenericParam::Lifetime(..))) => {
Some(quote!(<'s>))
},
_ => {
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") {
if let Some(nested) = util::read_attr("logos", attr)? {
let span = nested.span();
if let Some(ext) = util::value_from_nested("extras", &nested)? {
if extras.replace(ext).is_some() {
return Err(Error::new("Extras can be defined only once.").span(span));
}
}
if let Err(_) = util::value_from_nested("trivia", &nested) {
const ERR: &str = "\
trivia are no longer supported.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases";
return Err(Error::new(ERR).span(span));
}
}
}
if attr.path.is_ident("extras") {
const ERR: &str = "\
#[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 {
if let Err(err) = parse_attr(attr) {
errors.push(err);
}
}
let mut variants = Vec::new();
let mut ropes = Vec::new();
let mut regex_ids = Vec::new();
let mut graph = Graph::new();
for variant in &item.variants {
variants.push(&variant.ident);
let span = variant.span();
if let Some((_, value)) = &variant.discriminant {
let span = value.span();
let value = util::unpack_int(value).unwrap_or(usize::max_value());
if value >= size {
errors.push(Error::new(
format!(
"Discriminant value for `{}` is invalid. Expected integer in range 0..={}.",
variant.ident,
size,
),
).span(span));
}
}
let field = match &variant.fields {
Fields::Unit => None,
Fields::Unnamed(ref fields) => {
if fields.unnamed.len() != 1 {
errors.push(Error::new(
format!(
"Logos currently only supports variants with one field, found {}",
fields.unnamed.len(),
)
).span(fields.span()))
}
let field = fields.unnamed.first().expect("Already checked len; qed").ty.clone();
Some(field)
}
Fields::Named(_) => {
errors.push(Error::new("Logos doesn't support named fields yet.").span(span));
None
}
};
for attr in &variant.attrs {
let variant = &variant.ident;
let mut with_definition = |definition: Definition<Literal>| {
if let Literal::Bytes(..) = definition.value {
mode = Mode::Binary;
}
(
Leaf::token(variant).field(field.clone()).callback(definition.callback),
definition.value,
)
};
if attr.path.is_ident("error") {
if let Some(previous) = error.replace(variant) {
errors.extend(vec![
Error::new("Only one #[error] variant can be declared.").span(span),
Error::new("Previously declared #[error]:").span(previous.span()),
]);
}
} else if attr.path.is_ident("end") {
errors.push(
Error::new(
"Since 0.11 Logos no longer requires the #[end] variant.\n\n\
For help with migration see release notes: https://github.com/maciejhirsz/logos/releases"
).span(attr.span())
);
} else if attr.path.is_ident("token") {
match util::value_from_attr("token", attr) {
Ok(Some(definition)) => {
let (token, value) = with_definition(definition);
let value = value.into_bytes();
let then = graph.push(token.priority(value.len()));
ropes.push(Rope::new(value, then));
},
Err(err) => errors.push(err),
_ => (),
}
} else if attr.path.is_ident("regex") {
match util::value_from_attr("regex", attr) {
Ok(Some(definition)) => {
let (token, value) = with_definition(definition);
let then = graph.reserve();
let (utf8, regex, span) = match value {
Literal::Utf8(string, span) => (true, string, span),
Literal::Bytes(bytes, span) => {
mode = Mode::Binary;
(false, util::bytes_to_regex_string(&bytes), span)
}
};
match graph.regex(utf8, ®ex, then.get()) {
Ok((len, mut id)) => {
let then = graph.insert(then, token.priority(len));
regex_ids.push(id);
// Drain recursive miss values.
// We need the root node to have straight branches.
while let Some(miss) = graph[id].miss() {
if miss == then {
errors.push(
Error::new("#[regex]: expression can match empty string.\n\n\
hint: consider changing * to +").span(span)
);
break;
} else {
regex_ids.push(miss);
id = miss;
}
}
},
Err(err) => errors.push(err.span(span)),
}
},
Err(err) => errors.push(err),
_ => (),
}
}
}
}
let mut root = Fork::new();
let extras = match extras {
Some(ext) => quote!(#ext),
None => quote!(()),
};
let source = match mode {
Mode::Utf8 => quote!(str),
Mode::Binary => quote!([u8]),
};
let error_def = match error {
Some(error) => Some(quote!(const ERROR: Self = #name::#error;)),
None => {
errors.push(Error::new("missing #[error] token variant.").span(super_span));
None
},
};
let this = quote!(#name #generics);
let impl_logos = |body| {
quote! {
impl<'s> ::logos::Logos<'s> for #this {
type Extras = #extras;
type Source = #source;
const SIZE: usize = #size;
#error_def
fn lex(lex: &mut ::logos::Lexer<'s, Self>) {
#body
}
}
}
};
if errors.len() > 0 {
return impl_logos(quote! {
fn _logos_derive_compile_errors() {
#(#errors)*
}
}).into()
}
for id in regex_ids {
let fork = graph.fork_off(id);
root.merge(fork, &mut graph);
}
for rope in ropes {
root.merge(rope.into_fork(&mut graph), &mut graph)
}
while let Some(id) = root.miss.take() {
let fork = graph.fork_off(id);
if fork.branches().next().is_some() {
root.merge(fork, &mut graph);
} else |
}
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 ::logos::internal::{LexerInternal, CallbackResult};
type Lexer<'s> = | {
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 branch in this code
// for anything as simple as authentication, but it turns out that our
// assumptions did not match reality.
// When SAML is enabled (but not configured) then the UAA/Login server
// will always returns password prompts that includes the Passcode field.
// Users can authenticate with:
// EITHER username and password
// OR a one-time passcode
switch {
case c.Bool("sso") && c.IsSet("sso-passcode"):
return errors.New(T("Incorrect usage: --sso-passcode flag cannot be used with --sso"))
case c.Bool("sso") || c.IsSet("sso-passcode"):
err = cmd.authenticateSSO(c)
if err != nil {
return err
}
default:
err = cmd.authenticate(c)
if err != nil {
return err
}
}
orgIsSet, err := cmd.setOrganization(c)
if err != nil {
return err
}
if orgIsSet {
err = cmd.setSpace(c)
if err != nil {
return err
}
}
cmd.ui.NotifyUpdateIfNeeded(cmd.config)
return nil
}
func (cmd Login) decideEndpoint(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 endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)}))
}
return endpoint, skipSSL
}
func (cmd Login) authenticateSSO(c flags.FlagContext) error {
prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL()
if err != nil {
return err
}
credentials := make(map[string]string)
passcode := prompts["passcode"]
if passcode.DisplayName == "" {
passcode = coreconfig.AuthPrompt{
Type: coreconfig.AuthPromptTypePassword,
DisplayName: T("Temporary Authentication Code ( Get one at {{.AuthenticationEndpoint}}/passcode )",
map[string]interface{}{
"AuthenticationEndpoint": cmd.config.AuthenticationEndpoint(),
}),
}
}
for i := 0; i < maxLoginTries; i++ {
if c.IsSet("sso-passcode") && i == 0 {
credentials["passcode"] = c.String("sso-passcode")
} 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 authenticate."))
}
return nil
}
func (cmd Login) authenticate(c flags.FlagContext) error {
if cmd.config.UAAGrantType() == "client_credentials" {
return errors.New(T("Service account currently logged in. Use 'cf logout' to log out service account and try again."))
}
usernameFlagValue := c.String("u")
passwordFlagValue := c.String("p")
prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL()
if err != nil {
return err
}
passwordKeys := []string{}
credentials := make(map[string]string)
if value, ok := prompts["username"]; ok {
if prompts["username"].Type == coreconfig.AuthPromptTypeText && usernameFlagValue != "" {
credentials["username"] = usernameFlagValue
} else {
credentials["username"] = cmd.ui.Ask(T(value.DisplayName))
}
}
for key, prompt := range prompts {
if prompt.Type == coreconfig.AuthPromptTypePassword {
if key == "passcode" || key == "password" {
continue
}
passwordKeys = append(passwordKeys, key)
} else if key == "username" {
continue
} else {
credentials[key] = cmd.ui.Ask(T(prompt.DisplayName))
}
}
for i := 0; i < maxLoginTries; i++ {
// ensure that password gets prompted before other codes (eg. mfa code)
if passPrompt, ok := prompts["password"]; ok {
if passwordFlagValue != "" {
credentials["password"] = passwordFlagValue
passwordFlagValue = ""
} else {
credentials["password"] = cmd.ui.AskForPassword(T(passPrompt.DisplayName))
}
}
for _, key := range passwordKeys {
credentials[key] = cmd.ui.AskForPassword(T(prompts[key].DisplayName))
}
credentialsCopy := make(map[string]string, len(credentials))
for k, v := range credentials {
credentialsCopy[k] = v
}
cmd.ui.Say(T("Authenticating..."))
err = cmd.authenticator.Authenticate(credentialsCopy)
if err == nil {
cmd.ui.Ok()
cmd.ui.Say("")
break
}
cmd.ui.Say(err.Error())
}
if err != nil {
return errors.New(T("Unable to authenticate."))
}
return nil
}
func (cmd Login) setOrganization(c flags.FlagContext) (bool, error) {
orgName := c.String("o")
if orgName == "" {
orgs, err := cmd.orgRepo.ListOrgs(maxChoices)
if err != nil {
return false, errors.New(T("Error finding available orgs\n{{.APIErr}}",
map[string]interface{}{"APIErr": err.Error()}))
}
switch len(orgs) {
case 0:
return false, nil
case 1:
cmd.targetOrganization(orgs[0])
return true, nil
default:
orgName = cmd.promptForOrgName(orgs)
if orgName == "" {
cmd.ui.Say("")
return false, nil
}
}
}
org, err := cmd.orgRepo.FindByName(orgName)
if err != nil {
return false, errors.New(T("Error finding org {{.OrgName}}\n{{.Err}}",
map[string]interface{}{"OrgName": terminal.EntityNameColor(orgName), "Err": err.Error()}))
}
cmd.targetOrganization(org)
return true, nil
}
func (cmd Login) promptForOrgName(orgs []models.Organization) string {
orgNames := []string{}
for _, org := range orgs {
orgNames = append(orgNames, org.Name)
}
return cmd.promptForName(orgNames, T("Select an org (or press enter to skip):"), "Org")
}
func (cmd Login) targetOrganization(org models.Organization) {
cmd.config.SetOrganizationFields(org.OrganizationFields)
cmd.ui.Say(T("Targeted org {{.OrgName}}\n",
map[string]interface{}{"OrgName": terminal.EntityNameColor(org.Name)}))
}
func (cmd Login) setSpace(c flags.FlagContext) error {
spaceName := c.String("s")
if spaceName == "" {
var availableSpaces []models.Space
err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool {
availableSpaces = append(availableSpaces, space)
return (len(availableSpaces) < maxChoices)
})
if err != nil {
return errors.New(T("Error finding available spaces\n{{.Err}}",
map[string]interface{}{"Err": err.Error()}))
}
if len(availableSpaces) == 0 {
return nil
} else if len(availableSpaces) == 1 {
cmd.targetSpace(availableSpaces[0])
return nil
} else {
spaceName = cmd.promptForSpaceName(availableSpaces)
if spaceName == "" {
cmd.ui.Say("")
return nil
}
}
}
space, err := cmd.spaceRepo.FindByName(spaceName)
if err != nil {
return errors.New(T("Error finding space {{.SpaceName}}\n{{.Err}}",
map[string]interface{}{"SpaceName": terminal.EntityNameColor(spaceName), "Err": err.Error()}))
}
cmd.targetSpace(space)
return nil
}
func (cmd Login) promptForSpaceName(spaces []models.Space) string {
spaceNames := []string{}
for _, space := range spaces {
spaceNames = append(spaceNames, space.Name)
}
return cmd.promptForName(spaceNames, T("Select a space (or press enter to skip):"), "Space")
}
func (cmd Login) targetSpace(space models.Space) | {
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 := []requirements.Requirement{}
return reqs, nil
}
func (cmd *Login) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
cmd.ui = deps.UI
cmd.config = deps.Config
cmd.authenticator = deps.RepoLocator.GetAuthenticationRepository()
cmd.endpointRepo = deps.RepoLocator.GetEndpointRepository()
cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository()
cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository()
return cmd
}
func (cmd *Login) Execute(c flags.FlagContext) error {
cmd.config.ClearSession()
endpoint, skipSSL := cmd.decideEndpoint(c)
api := API{
ui: cmd.ui,
config: cmd.config,
endpointRepo: cmd.endpointRepo,
}
err := api.setAPIEndpoint(endpoint, skipSSL, cmd.MetaData().Name)
if err != nil {
return err
}
err = command.MinimumCCAPIVersionCheck(cmd.config.APIVersion(), ccversion.MinSupportedV2ClientVersion)
if err != nil {
if _, ok := 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 branch in this code
// for anything as simple as authentication, but it turns out that our
// assumptions did not match reality.
// When SAML is enabled (but not configured) then the UAA/Login server
// will always returns password prompts that includes the Passcode field.
// Users can authenticate with:
// EITHER username and password
// OR a one-time passcode
switch {
case c.Bool("sso") && c.IsSet("sso-passcode"):
return errors.New(T("Incorrect usage: --sso-passcode flag cannot be used with --sso"))
case c.Bool("sso") || c.IsSet("sso-passcode"):
err = cmd.authenticateSSO(c)
if err != nil {
return err
}
default:
err = cmd.authenticate(c)
if err != nil {
return err
}
}
orgIsSet, err := cmd.setOrganization(c)
if err != nil {
return err
}
if orgIsSet {
err = cmd.setSpace(c)
if err != nil {
return err
}
}
cmd.ui.NotifyUpdateIfNeeded(cmd.config)
return nil
}
func (cmd Login) decideEndpoint(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 endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)}))
}
return endpoint, skipSSL
}
func (cmd Login) authenticateSSO(c flags.FlagContext) error {
prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL()
if err != nil {
return err
}
credentials := make(map[string]string)
passcode := prompts["passcode"]
if passcode.DisplayName == "" {
passcode = coreconfig.AuthPrompt{
Type: coreconfig.AuthPromptTypePassword,
DisplayName: T("Temporary Authentication Code ( Get one at {{.AuthenticationEndpoint}}/passcode )",
map[string]interface{}{
"AuthenticationEndpoint": cmd.config.AuthenticationEndpoint(),
}),
}
}
for i := 0; i < maxLoginTries; i++ {
if c.IsSet("sso-passcode") && i == 0 {
credentials["passcode"] = c.String("sso-passcode")
} 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 authenticate."))
}
return nil
}
func (cmd Login) authenticate(c flags.FlagContext) error {
if cmd.config.UAAGrantType() == "client_credentials" {
return errors.New(T("Service account currently logged in. Use 'cf logout' to log out service account and try again."))
}
usernameFlagValue := c.String("u")
passwordFlagValue := c.String("p")
prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL()
if err != nil {
return err
}
passwordKeys := []string{}
credentials := make(map[string]string)
if value, ok := prompts["username"]; ok {
if prompts["username"].Type == coreconfig.AuthPromptTypeText && usernameFlagValue != "" {
credentials["username"] = usernameFlagValue
} else {
credentials["username"] = cmd.ui.Ask(T(value.DisplayName))
}
}
for key, prompt := range prompts {
if prompt.Type == coreconfig.AuthPromptTypePassword {
if key == "passcode" || key == "password" {
continue
}
passwordKeys = append(passwordKeys, key)
} else if key == "username" {
continue
} else {
credentials[key] = cmd.ui.Ask(T(prompt.DisplayName))
}
}
for i := 0; i < maxLoginTries; i++ {
// ensure that password gets prompted before other codes (eg. mfa code)
if passPrompt, ok := prompts["password"]; ok {
if passwordFlagValue != "" {
credentials["password"] = passwordFlagValue
passwordFlagValue = ""
} else {
credentials["password"] = cmd.ui.AskForPassword(T(passPrompt.DisplayName))
}
}
for _, key := range passwordKeys {
credentials[key] = cmd.ui.AskForPassword(T(prompts[key].DisplayName))
}
credentialsCopy := make(map[string]string, len(credentials))
for k, v := range credentials {
credentialsCopy[k] = v
}
cmd.ui.Say(T("Authenticating..."))
err = cmd.authenticator.Authenticate(credentialsCopy)
if err == nil {
cmd.ui.Ok()
cmd.ui.Say("")
break
}
cmd.ui.Say(err.Error())
}
if err != nil {
return errors.New(T("Unable to authenticate."))
}
return nil
}
func (cmd Login) setOrganization(c flags.FlagContext) (bool, error) {
orgName := c.String("o")
if orgName == "" {
orgs, err := cmd.orgRepo.ListOrgs(maxChoices)
if err != nil {
return false, errors.New(T("Error finding available orgs\n{{.APIErr}}",
map[string]interface{}{"APIErr": err.Error()}))
}
switch len(orgs) {
case 0:
return false, nil
case 1:
cmd.targetOrganization(orgs[0])
return true, nil
default:
orgName = cmd.promptForOrgName(orgs)
if orgName == "" {
cmd.ui.Say("")
return false, nil
}
}
}
org, err := cmd.orgRepo.FindByName(orgName)
if err != nil {
return false, errors.New(T("Error finding org {{.OrgName}}\n{{.Err}}",
map[string]interface{}{"OrgName": terminal.EntityNameColor(orgName), "Err": err.Error()}))
}
cmd.targetOrganization(org)
return true, nil
}
func (cmd Login) promptForOrgName(orgs []models.Organization) string {
orgNames := []string{}
for _, org := range orgs {
orgNames = append(orgNames, org.Name)
}
return cmd.promptForName(orgNames, T("Select an org (or press enter to skip):"), "Org")
}
func (cmd Login) targetOrganization(org models.Organization) {
cmd.config.SetOrganizationFields(org.OrganizationFields)
cmd.ui.Say(T("Targeted org {{.OrgName}}\n",
map[string]interface{}{"OrgName": terminal.EntityNameColor(org.Name)}))
}
func (cmd Login) setSpace(c flags.FlagContext) error {
spaceName := c.String("s")
if spaceName == "" {
var availableSpaces []models.Space
err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool {
availableSpaces = append(availableSpaces, space)
return (len(availableSpaces) < maxChoices)
}) | 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("One-time passcode")}
fs["skip-ssl-validation"] = &flags.BoolFlag{Name: "skip-ssl-validation", Usage: T("Skip verification of the API endpoint. Not recommended!")}
return commandregistry.CommandMetadata{
Name: "login",
ShortName: "l",
Description: T("Log user in"),
Usage: []string{
T("CF_NAME login [-a API_URL] [-u USERNAME] [-p PASSWORD] [-o ORG] [-s SPACE] [--sso | --sso-passcode PASSCODE]\n\n"),
terminal.WarningColor(T("WARNING:\n Providing your password as a command line option is highly discouraged\n Your password may be visible to others and may be recorded in your shell history")),
},
Examples: []string{
T("CF_NAME login (omit username and password to login interactively -- CF_NAME will prompt for both)"),
T("CF_NAME login -u name@example.com -p pa55woRD (specify username and password as arguments)"),
T("CF_NAME login -u name@example.com -p \"my password\" (use quotes for passwords with a space)"),
T("CF_NAME login -u name@example.com -p \"\\\"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 := []requirements.Requirement{}
return reqs, nil
}
func (cmd *Login) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
cmd.ui = deps.UI
cmd.config = deps.Config
cmd.authenticator = deps.RepoLocator.GetAuthenticationRepository()
cmd.endpointRepo = deps.RepoLocator.GetEndpointRepository()
cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository()
cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository()
return cmd
}
func (cmd *Login) Execute(c flags.FlagContext) error {
cmd.config.ClearSession()
endpoint, skipSSL := cmd.decideEndpoint(c)
api := API{
ui: cmd.ui,
config: cmd.config,
endpointRepo: cmd.endpointRepo,
}
err := api.setAPIEndpoint(endpoint, skipSSL, cmd.MetaData().Name)
if err != nil {
return err
}
err = command.MinimumCCAPIVersionCheck(cmd.config.APIVersion(), ccversion.MinSupportedV2ClientVersion)
if err != nil {
if _, ok := 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 branch in this code
// for anything as simple as authentication, but it turns out that our
// assumptions did not match reality.
// When SAML is enabled (but not configured) then the UAA/Login server
// will always returns password prompts that includes the Passcode field.
// Users can authenticate with:
// EITHER username and password
// OR a one-time passcode
switch {
case c.Bool("sso") && c.IsSet("sso-passcode"):
return errors.New(T("Incorrect usage: --sso-passcode flag cannot be used with --sso"))
case c.Bool("sso") || c.IsSet("sso-passcode"):
err = cmd.authenticateSSO(c)
if err != nil {
return err
}
default:
err = cmd.authenticate(c)
if err != nil {
return err
}
}
orgIsSet, err := cmd.setOrganization(c)
if err != nil {
return err
}
if orgIsSet {
err = cmd.setSpace(c)
if err != nil {
return err
}
}
cmd.ui.NotifyUpdateIfNeeded(cmd.config)
return nil
}
func (cmd Login) | (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 endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)}))
}
return endpoint, skipSSL
}
func (cmd Login) authenticateSSO(c flags.FlagContext) error {
prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL()
if err != nil {
return err
}
credentials := make(map[string]string)
passcode := prompts["passcode"]
if passcode.DisplayName == "" {
passcode = coreconfig.AuthPrompt{
Type: coreconfig.AuthPromptTypePassword,
DisplayName: T("Temporary Authentication Code ( Get one at {{.AuthenticationEndpoint}}/passcode )",
map[string]interface{}{
"AuthenticationEndpoint": cmd.config.AuthenticationEndpoint(),
}),
}
}
for i := 0; i < maxLoginTries; i++ {
if c.IsSet("sso-passcode") && i == 0 {
credentials["passcode"] = c.String("sso-passcode")
} 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 authenticate."))
}
return nil
}
func (cmd Login) authenticate(c flags.FlagContext) error {
if cmd.config.UAAGrantType() == "client_credentials" {
return errors.New(T("Service account currently logged in. Use 'cf logout' to log out service account and try again."))
}
usernameFlagValue := c.String("u")
passwordFlagValue := c.String("p")
prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL()
if err != nil {
return err
}
passwordKeys := []string{}
credentials := make(map[string]string)
if value, ok := prompts["username"]; ok {
if prompts["username"].Type == coreconfig.AuthPromptTypeText && usernameFlagValue != "" {
credentials["username"] = usernameFlagValue
} else {
credentials["username"] = cmd.ui.Ask(T(value.DisplayName))
}
}
for key, prompt := range prompts {
if prompt.Type == coreconfig.AuthPromptTypePassword {
if key == "passcode" || key == "password" {
continue
}
passwordKeys = append(passwordKeys, key)
} else if key == "username" {
continue
} else {
credentials[key] = cmd.ui.Ask(T(prompt.DisplayName))
}
}
for i := 0; i < maxLoginTries; i++ {
// ensure that password gets prompted before other codes (eg. mfa code)
if passPrompt, ok := prompts["password"]; ok {
if passwordFlagValue != "" {
credentials["password"] = passwordFlagValue
passwordFlagValue = ""
} else {
credentials["password"] = cmd.ui.AskForPassword(T(passPrompt.DisplayName))
}
}
for _, key := range passwordKeys {
credentials[key] = cmd.ui.AskForPassword(T(prompts[key].DisplayName))
}
credentialsCopy := make(map[string]string, len(credentials))
for k, v := range credentials {
credentialsCopy[k] = v
}
cmd.ui.Say(T("Authenticating..."))
err = cmd.authenticator.Authenticate(credentialsCopy)
if err == nil {
cmd.ui.Ok()
cmd.ui.Say("")
break
}
cmd.ui.Say(err.Error())
}
if err != nil {
return errors.New(T("Unable to authenticate."))
}
return nil
}
func (cmd Login) setOrganization(c flags.FlagContext) (bool, error) {
orgName := c.String("o")
if orgName == "" {
orgs, err := cmd.orgRepo.ListOrgs(maxChoices)
if err != nil {
return false, errors.New(T("Error finding available orgs\n{{.APIErr}}",
map[string]interface{}{"APIErr": err.Error()}))
}
switch len(orgs) {
case 0:
| 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("One-time passcode")}
fs["skip-ssl-validation"] = &flags.BoolFlag{Name: "skip-ssl-validation", Usage: T("Skip verification of the API endpoint. Not recommended!")}
return commandregistry.CommandMetadata{
Name: "login",
ShortName: "l",
Description: T("Log user in"),
Usage: []string{
T("CF_NAME login [-a API_URL] [-u USERNAME] [-p PASSWORD] [-o ORG] [-s SPACE] [--sso | --sso-passcode PASSCODE]\n\n"),
terminal.WarningColor(T("WARNING:\n Providing your password as a command line option is highly discouraged\n Your password may be visible to others and may be recorded in your shell history")),
},
Examples: []string{
T("CF_NAME login (omit username and password to login interactively -- CF_NAME will prompt for both)"),
T("CF_NAME login -u name@example.com -p pa55woRD (specify username and password as arguments)"),
T("CF_NAME login -u name@example.com -p \"my password\" (use quotes for passwords with a space)"),
T("CF_NAME login -u name@example.com -p \"\\\"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 := []requirements.Requirement{}
return reqs, nil
}
func (cmd *Login) SetDependency(deps commandregistry.Dependency, pluginCall bool) commandregistry.Command {
cmd.ui = deps.UI
cmd.config = deps.Config
cmd.authenticator = deps.RepoLocator.GetAuthenticationRepository()
cmd.endpointRepo = deps.RepoLocator.GetEndpointRepository()
cmd.orgRepo = deps.RepoLocator.GetOrganizationRepository()
cmd.spaceRepo = deps.RepoLocator.GetSpaceRepository()
return cmd
}
func (cmd *Login) Execute(c flags.FlagContext) error {
cmd.config.ClearSession()
endpoint, skipSSL := cmd.decideEndpoint(c)
api := API{
ui: cmd.ui,
config: cmd.config,
endpointRepo: cmd.endpointRepo,
}
err := api.setAPIEndpoint(endpoint, skipSSL, cmd.MetaData().Name)
if err != nil {
return err
}
err = command.MinimumCCAPIVersionCheck(cmd.config.APIVersion(), ccversion.MinSupportedV2ClientVersion)
if err != nil {
if _, ok := 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 branch in this code
// for anything as simple as authentication, but it turns out that our
// assumptions did not match reality.
// When SAML is enabled (but not configured) then the UAA/Login server
// will always returns password prompts that includes the Passcode field.
// Users can authenticate with:
// EITHER username and password
// OR a one-time passcode
switch {
case c.Bool("sso") && c.IsSet("sso-passcode"):
return errors.New(T("Incorrect usage: --sso-passcode flag cannot be used with --sso"))
case c.Bool("sso") || c.IsSet("sso-passcode"):
err = cmd.authenticateSSO(c)
if err != nil {
return err
}
default:
err = cmd.authenticate(c)
if err != nil {
return err
}
}
orgIsSet, err := cmd.setOrganization(c)
if err != nil {
return err
}
if orgIsSet {
err = cmd.setSpace(c)
if err != nil {
return err
}
}
cmd.ui.NotifyUpdateIfNeeded(cmd.config)
return nil
}
func (cmd Login) decideEndpoint(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 endpoint: {{.Endpoint}}", map[string]interface{}{"Endpoint": terminal.EntityNameColor(endpoint)}))
}
return endpoint, skipSSL
}
func (cmd Login) authenticateSSO(c flags.FlagContext) error {
prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL()
if err != nil {
return err
}
credentials := make(map[string]string)
passcode := prompts["passcode"]
if passcode.DisplayName == "" {
passcode = coreconfig.AuthPrompt{
Type: coreconfig.AuthPromptTypePassword,
DisplayName: T("Temporary Authentication Code ( Get one at {{.AuthenticationEndpoint}}/passcode )",
map[string]interface{}{
"AuthenticationEndpoint": cmd.config.AuthenticationEndpoint(),
}),
}
}
for i := 0; i < maxLoginTries; i++ {
if c.IsSet("sso-passcode") && i == 0 | 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 authenticate."))
}
return nil
}
func (cmd Login) authenticate(c flags.FlagContext) error {
if cmd.config.UAAGrantType() == "client_credentials" {
return errors.New(T("Service account currently logged in. Use 'cf logout' to log out service account and try again."))
}
usernameFlagValue := c.String("u")
passwordFlagValue := c.String("p")
prompts, err := cmd.authenticator.GetLoginPromptsAndSaveUAAServerURL()
if err != nil {
return err
}
passwordKeys := []string{}
credentials := make(map[string]string)
if value, ok := prompts["username"]; ok {
if prompts["username"].Type == coreconfig.AuthPromptTypeText && usernameFlagValue != "" {
credentials["username"] = usernameFlagValue
} else {
credentials["username"] = cmd.ui.Ask(T(value.DisplayName))
}
}
for key, prompt := range prompts {
if prompt.Type == coreconfig.AuthPromptTypePassword {
if key == "passcode" || key == "password" {
continue
}
passwordKeys = append(passwordKeys, key)
} else if key == "username" {
continue
} else {
credentials[key] = cmd.ui.Ask(T(prompt.DisplayName))
}
}
for i := 0; i < maxLoginTries; i++ {
// ensure that password gets prompted before other codes (eg. mfa code)
if passPrompt, ok := prompts["password"]; ok {
if passwordFlagValue != "" {
credentials["password"] = passwordFlagValue
passwordFlagValue = ""
} else {
credentials["password"] = cmd.ui.AskForPassword(T(passPrompt.DisplayName))
}
}
for _, key := range passwordKeys {
credentials[key] = cmd.ui.AskForPassword(T(prompts[key].DisplayName))
}
credentialsCopy := make(map[string]string, len(credentials))
for k, v := range credentials {
credentialsCopy[k] = v
}
cmd.ui.Say(T("Authenticating..."))
err = cmd.authenticator.Authenticate(credentialsCopy)
if err == nil {
cmd.ui.Ok()
cmd.ui.Say("")
break
}
cmd.ui.Say(err.Error())
}
if err != nil {
return errors.New(T("Unable to authenticate."))
}
return nil
}
func (cmd Login) setOrganization(c flags.FlagContext) (bool, error) {
orgName := c.String("o")
if orgName == "" {
orgs, err := cmd.orgRepo.ListOrgs(maxChoices)
if err != nil {
return false, errors.New(T("Error finding available orgs\n{{.APIErr}}",
map[string]interface{}{"APIErr": err.Error()}))
}
switch len(orgs) {
case 0:
| {
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",
"a": "a-e-i.jpg",
"ɶ": "a-e-i.jpg",
"ɑ": "a-e-i.jpg",
"ɒ": "a-e-i.jpg",
"ʌ": "a-e-i.jpg",
"ɔ": "o.jpg",
"o": "o.jpg",
"ɤ": "u.jpg",
"ø": "u.jpg",
"w": "u.jpg",
"u": "u.jpg",
"tpkc": "b-m-p.jpg", #Revisar
"bdg": "c-d-g-k-n-s-x-z.jpg",
"vz": "f-t-th-v.jpg",
"n":"c-d-g-k-n-s-x-z.jpg", #Sonorants
"m":"b-m-p.jpg",
"l":"l.jpg",
"sh":"j-ch-sh.jpg",
"r":"r.jpg",
"s":"c-d-g-k-n-s-x-z.jpg",#Fricatives
"z":"c-d-g-k-n-s-x-z.jpg",
"f":"f-t-th-v.jpg",
"j":"j-ch-sh.jpg"
}
NUMBER_OF_SLOTS = 4
def GetPeaks(spectrum, fs, start_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+peaks)*(fs/len(buffer))
def FormantsToPhoneme(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_inv_dict.keys())
tree = spatial.KDTree(keys_array)
index = tree.query([(f1,f2)])[1][0]
vowel = male_vowel_inv_dict[keys_array[index]]
return vowel
filename = "hello.wav"
wf = wave.open(filename, 'rb')
fs = wf.getframerate()
audio, sr = load(filename)
past_status = 'silence'
def classifier(speech_features, spectrum, fs, sex="male"):
global past_status
if speech_features.is_sound:
if speech_features.is_voiced:
if speech_features | 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)
elif past_status == 'silence':
past_status = 'sound'
return 'tpkc'
else: # silence
past_status = 'silence'
return ' '
#Parameters
N = 256
new_fs = 1e4
lpc_order = 14
#Tresholds
energy_th = 5e-3
zc_threshold = 150 #FALTA DEFINIR
sonorant_th = 50 #FALTA DEFINIR
sonorant_zc_th = 20
epsilon = 1e-5
#Window audio
samples_n = int(256e-4*sr)
frames = frame(audio, samples_n, samples_n, axis=0)
images = []
time_taken = []
#Debugging
zero_crossings = []
voiced_list = []
phoneme_list = []
ratio_list = []
i=0
for buffer in frames:
start_time = perf_counter()
is_sound = False # done
is_voiced = False # done
is_lf = False # done
is_sonorant = False
windowed_frame = buffer * np.hanning(samples_n)
#LPC y espectro
hp_filtered = preemphasis(windowed_frame, coef=1)
downsampled = resample(hp_filtered, sr, new_fs)
coefs = lpc(downsampled, lpc_order)
spectrum = 1/abs(np.fft.rfft(coefs,n=N))
# Sound or Silence
if windowed_frame.std() < energy_th:
is_sound = False
else:
is_sound = True
# High Frequency or Low Frequency
zero_crosses = np.nonzero(np.diff(buffer> 0))[0]
zero_crosses_count = zero_crosses.size
if zero_crosses_count > zc_threshold:
is_lf = False
else:
is_lf = True
zero_crossings.append( (i, zero_crosses_count) )
# Voiced or Unvoiced
# 1. Calculate Zero-crossing count Nz, the number of zero crossing in the block
Nz = zero_crosses_count
# 2. Calculate Log energy Es
Es = 10*np.log10(epsilon+sum(map(lambda x:x*x,buffer))/len(buffer))
# 3. Normalized autocorrelation coefficient at unit sample delay, C1
auto_corr_lag_1 = np.correlate(buffer, buffer, mode="full")[1]
C1 = auto_corr_lag_1/np.sqrt((sum(map(lambda x:x*x,buffer[1:])))*(sum(map(lambda x:x*x,buffer[:-1]))))
# 4. First LPC coefficient (12 poles)
FirstLPCcoef = coefs[1]
# 5. Normalized prediction error, Ep, expressed in DB
sum_exp = 10
error_spectrum = abs( np.fft.rfft(downsampled,N) )/spectrum
Ep = np.dot(error_spectrum,error_spectrum) / (N*N)
# LINK: https://www.clear.rice.edu/elec532/PROJECTS00/vocode/uv/uvdet.html
# Means and Covariance Matrix
silence_mean = np.array([9.6613, -38.1601, 0.989, 0.5084, -10.8084])
silence_cov = np.array([[1.0000, 0.6760, -0.7077, -0.1904, 0.7208]
,[0.6760, 1.0000, 0.6933, 0.2918, -0.9425]
,[-0.7077, 0.6933, 1.0000, 0.3275, -0.8426]
,[-0.1904, 0.2918, 0.3275, 1.0000, -0.2122]
,[0.7208, -0.9425, -0.826, -0.2122, 1.0000]])
unvoiced_mean = np.array([10.4286, -36.7536, 0.9598, | .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]
return FormantsToPhoneme(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_vowel_dict)
elif past_status == 'silence':
past_status = 'sound'
return 'bdg'
else: # hf
past_status = 'sound'
return 'vz' | 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",
"a": "a-e-i.jpg",
"ɶ": "a-e-i.jpg",
"ɑ": "a-e-i.jpg",
"ɒ": "a-e-i.jpg",
"ʌ": "a-e-i.jpg",
"ɔ": "o.jpg",
"o": "o.jpg",
"ɤ": "u.jpg",
"ø": "u.jpg",
"w": "u.jpg",
"u": "u.jpg",
"tpkc": "b-m-p.jpg", #Revisar
"bdg": "c-d-g-k-n-s-x-z.jpg",
"vz": "f-t-th-v.jpg",
"n":"c-d-g-k-n-s-x-z.jpg", #Sonorants
"m":"b-m-p.jpg",
"l":"l.jpg",
"sh":"j-ch-sh.jpg",
"r":"r.jpg",
"s":"c-d-g-k-n-s-x-z.jpg",#Fricatives
"z":"c-d-g-k-n-s-x-z.jpg",
"f":"f-t-th-v.jpg",
"j":"j-ch-sh.jpg"
}
NUMBER_OF_SLOTS = 4
def GetPeaks(spectrum, fs, start_freq=150, end_freq=3400):
start_indx = int(s | 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_inv_dict.keys())
tree = spatial.KDTree(keys_array)
index = tree.query([(f1,f2)])[1][0]
vowel = male_vowel_inv_dict[keys_array[index]]
return vowel
filename = "hello.wav"
wf = wave.open(filename, 'rb')
fs = wf.getframerate()
audio, sr = load(filename)
past_status = 'silence'
def classifier(speech_features, spectrum, fs, sex="male"):
global past_status
if speech_features.is_sound:
if speech_features.is_voiced:
if speech_features.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]
return FormantsToPhoneme(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_vowel_dict)
elif past_status == 'silence':
past_status = 'sound'
return 'bdg'
else: # hf
past_status = 'sound'
return 'vz'
else: # unvoiced
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)
elif past_status == 'silence':
past_status = 'sound'
return 'tpkc'
else: # silence
past_status = 'silence'
return ' '
#Parameters
N = 256
new_fs = 1e4
lpc_order = 14
#Tresholds
energy_th = 5e-3
zc_threshold = 150 #FALTA DEFINIR
sonorant_th = 50 #FALTA DEFINIR
sonorant_zc_th = 20
epsilon = 1e-5
#Window audio
samples_n = int(256e-4*sr)
frames = frame(audio, samples_n, samples_n, axis=0)
images = []
time_taken = []
#Debugging
zero_crossings = []
voiced_list = []
phoneme_list = []
ratio_list = []
i=0
for buffer in frames:
start_time = perf_counter()
is_sound = False # done
is_voiced = False # done
is_lf = False # done
is_sonorant = False
windowed_frame = buffer * np.hanning(samples_n)
#LPC y espectro
hp_filtered = preemphasis(windowed_frame, coef=1)
downsampled = resample(hp_filtered, sr, new_fs)
coefs = lpc(downsampled, lpc_order)
spectrum = 1/abs(np.fft.rfft(coefs,n=N))
# Sound or Silence
if windowed_frame.std() < energy_th:
is_sound = False
else:
is_sound = True
# High Frequency or Low Frequency
zero_crosses = np.nonzero(np.diff(buffer> 0))[0]
zero_crosses_count = zero_crosses.size
if zero_crosses_count > zc_threshold:
is_lf = False
else:
is_lf = True
zero_crossings.append( (i, zero_crosses_count) )
# Voiced or Unvoiced
# 1. Calculate Zero-crossing count Nz, the number of zero crossing in the block
Nz = zero_crosses_count
# 2. Calculate Log energy Es
Es = 10*np.log10(epsilon+sum(map(lambda x:x*x,buffer))/len(buffer))
# 3. Normalized autocorrelation coefficient at unit sample delay, C1
auto_corr_lag_1 = np.correlate(buffer, buffer, mode="full")[1]
C1 = auto_corr_lag_1/np.sqrt((sum(map(lambda x:x*x,buffer[1:])))*(sum(map(lambda x:x*x,buffer[:-1]))))
# 4. First LPC coefficient (12 poles)
FirstLPCcoef = coefs[1]
# 5. Normalized prediction error, Ep, expressed in DB
sum_exp = 10
error_spectrum = abs( np.fft.rfft(downsampled,N) )/spectrum
Ep = np.dot(error_spectrum,error_spectrum) / (N*N)
# LINK: https://www.clear.rice.edu/elec532/PROJECTS00/vocode/uv/uvdet.html
# Means and Covariance Matrix
silence_mean = np.array([9.6613, -38.1601, 0.989, 0.5084, -10.8084])
silence_cov = np.array([[1.0000, 0.6760, -0.7077, -0.1904, 0.7208]
,[0.6760, 1.0000, 0.6933, 0.2918, -0.9425]
,[-0.7077, 0.6933, 1.0000, 0.3275, -0.8426]
,[-0.1904, 0.2918, 0.3275, 1.0000, -0.2122]
,[0.7208, -0.9425, -0.826, -0.2122, 1.0000]])
unvoiced_mean = np.array([10.4286, -36.7536, 0.9598, | 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_vowel_dict)
elif past_status == 'silence':
past_status = 'sound'
return 'bdg'
else: # hf
past_status = 'sound'
return 'vz'
else: # unvoiced
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)
elif past_status == 'silence':
past_status = 'sound'
return 'tpkc'
else: # silence
past_status = 'silence'
return ' '
#Parameters
N = 256
new_fs = 1e4
lpc_order = 14
#Tresholds
energy_th = 5e-3
zc_threshold = 150 #FALTA DEFINIR
sonorant_th = 50 #FALTA DEFINIR
sonorant_zc_th = 20
epsilon = 1e-5
#Window audio
samples_n = int(256e-4*sr)
frames = frame(audio, samples_n, samples_n, axis=0)
images = []
time_taken = []
#Debugging
zero_crossings = []
voiced_list = []
phoneme_list = []
ratio_list = []
i=0
for buffer in frames:
start_time = perf_counter()
is_sound = False # done
is_voiced = False # done
is_lf = False # done
is_sonorant = False
windowed_frame = buffer * np.hanning(samples_n)
#LPC y espectro
hp_filtered = preemphasis(windowed_frame, coef=1)
downsampled = resample(hp_filtered, sr, new_fs)
coefs = lpc(downsampled, lpc_order)
spectrum = 1/abs(np.fft.rfft(coefs,n=N))
# Sound or Silence
if windowed_frame.std() < energy_th:
is_sound = False
else:
is_sound = True
# High Frequency or Low Frequency
zero_crosses = np.nonzero(np.diff(buffer> 0))[0]
zero_crosses_count = zero_crosses.size
if zero_crosses_count > zc_threshold:
is_lf = False
else:
is_lf = True
zero_crossings.append( (i, zero_crosses_count) )
# Voiced or Unvoiced
# 1. Calculate Zero-crossing count Nz, the number of zero crossing in the block
Nz = zero_crosses_count
# 2. Calculate Log energy Es
Es = 10*np.log10(epsilon+sum(map(lambda x:x*x,buffer))/len(buffer))
# 3. Normalized autocorrelation coefficient at unit sample delay, C1
auto_corr_lag_1 = np.correlate(buffer, buffer, mode="full")[1]
C1 = auto_corr_lag_1/np.sqrt((sum(map(lambda x:x*x,buffer[1:])))*(sum(map(lambda x:x*x,buffer[:-1]))))
# 4. First LPC coefficient (12 poles)
FirstLPCcoef = coefs[1]
# 5. Normalized prediction error, Ep, expressed in DB
sum_exp = 10
error_spectrum = abs( np.fft.rfft(downsampled,N) )/spectrum
Ep = np.dot(error_spectrum,error_spectrum) / (N*N)
# LINK: https://www.clear.rice.edu/elec532/PROJECTS00/vocode/uv/uvdet.html
# Means and Covariance Matrix
silence_mean = np.array([9.6613, -38.1601, 0.989, 0.5084, -10.8084])
silence_cov = np.array([[1.0000, 0.6760, -0.7077, -0.1904, 0.7208]
,[0.6760, 1.0000, 0.6933, 0.2918, -0.9425]
,[-0.7077, 0.6933, 1.0000, 0.3275, -0.8426]
,[-0.1904, 0.2918, 0.3275, 1.0000, -0.2122]
,[0.7208, -0.9425, -0.826, -0.2122, 1.0000]])
unvoiced_mean = np.array([10.4286, -36.7536, 0.9598, 0.5243, -10.9076])
unvoiced_cov = np.array([[1.0000, 0.6059, -0.4069, 0.4648, -0.4603]
,[0.6059, 1.0000, -0.1713, 0.1916, -0.9337]
,[-0.4069, -0.1713, 1.0000, 0.1990, -0.1685]
,[0.4648, 0.1916, 0.1990, 1.0000, -0.2121]
,[-0.4603, -0.9337, -0.1685, -0.2121, 1.0000]])
voiced_mean = np.array([29.1853, -18.3327, 0.9826, 1.1977, -11.1256])
voiced_cov = np.array([[1.0000, -0.2146, -0.8393, -0.3362, 0.3608]
,[-0.2146, 1.0000, 0.1793, 0.6564, -0.7129]
,[-0.8393, 0.1793, 1.0000, 0.3416, -0.5002]
,[-0.3362, 0.6564, 0.3416, 1.0000, -0.4850]
,[0.3608, -0.7129, -0.5002, -0.4850, 1.0000]])
X = np.array([Nz, Es, C1, FirstLPCcoef, Ep])
# Calculate distances (di)
#d_silence = np.transpose(X-silence_mean)*np.linalg.inv(silence_cov)*(X-silence_mean)
d_unvoiced = np.transpose(X-unvoiced_mean)@np.linalg.inv(unvoiced_cov)@(X-unvoiced_mean)
d_voiced = np.transpose(X-voiced_mean)@np.linalg.inv(voiced_cov)@(X-voiced_mean)
# Choose minimized distance category
if d_unvoiced < d_voiced:
is_voiced = False
voiced_list.append(0)
else:
is_voiced = True
voiced_list.append(1)
# Sonorant or Vowel
start_indx = int(640*(len(windowed_frame)/sr)) #Start calculation from 640Hz
end_indx = int(2800*(len(windowed_frame)/sr)) #End calculation at 2800Hz
low_freq_energy = np.dot(spectrum[start_indx:end_indx], spectrum[start_indx:end_indx]) #Energy
| 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",
"a": "a-e-i.jpg",
"ɶ": "a-e-i.jpg",
"ɑ": "a-e-i.jpg",
"ɒ": "a-e-i.jpg",
"ʌ": "a-e-i.jpg",
"ɔ": "o.jpg",
"o": "o.jpg",
"ɤ": "u.jpg",
"ø": "u.jpg",
"w": "u.jpg",
"u": "u.jpg",
"tpkc": "b-m-p.jpg", #Revisar
"bdg": "c-d-g-k-n-s-x-z.jpg",
"vz": "f-t-th-v.jpg",
"n":"c-d-g-k-n-s-x-z.jpg", #Sonorants
"m":"b-m-p.jpg",
"l":"l.jpg",
"sh":"j-ch-sh.jpg",
"r":"r.jpg",
"s":"c-d-g-k-n-s-x-z.jpg",#Fricatives
"z":"c-d-g-k-n-s-x-z.jpg",
"f":"f-t-th-v.jpg",
"j":"j-ch-sh.jpg"
}
NUMBER_OF_SLOTS = 4
def GetPeaks(spectrum, | 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+peaks)*(fs/len(buffer))
def FormantsToPhoneme(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_inv_dict.keys())
tree = spatial.KDTree(keys_array)
index = tree.query([(f1,f2)])[1][0]
vowel = male_vowel_inv_dict[keys_array[index]]
return vowel
filename = "hello.wav"
wf = wave.open(filename, 'rb')
fs = wf.getframerate()
audio, sr = load(filename)
past_status = 'silence'
def classifier(speech_features, spectrum, fs, sex="male"):
global past_status
if speech_features.is_sound:
if speech_features.is_voiced:
if speech_features.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]
return FormantsToPhoneme(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_vowel_dict)
elif past_status == 'silence':
past_status = 'sound'
return 'bdg'
else: # hf
past_status = 'sound'
return 'vz'
else: # unvoiced
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)
elif past_status == 'silence':
past_status = 'sound'
return 'tpkc'
else: # silence
past_status = 'silence'
return ' '
#Parameters
N = 256
new_fs = 1e4
lpc_order = 14
#Tresholds
energy_th = 5e-3
zc_threshold = 150 #FALTA DEFINIR
sonorant_th = 50 #FALTA DEFINIR
sonorant_zc_th = 20
epsilon = 1e-5
#Window audio
samples_n = int(256e-4*sr)
frames = frame(audio, samples_n, samples_n, axis=0)
images = []
time_taken = []
#Debugging
zero_crossings = []
voiced_list = []
phoneme_list = []
ratio_list = []
i=0
for buffer in frames:
start_time = perf_counter()
is_sound = False # done
is_voiced = False # done
is_lf = False # done
is_sonorant = False
windowed_frame = buffer * np.hanning(samples_n)
#LPC y espectro
hp_filtered = preemphasis(windowed_frame, coef=1)
downsampled = resample(hp_filtered, sr, new_fs)
coefs = lpc(downsampled, lpc_order)
spectrum = 1/abs(np.fft.rfft(coefs,n=N))
# Sound or Silence
if windowed_frame.std() < energy_th:
is_sound = False
else:
is_sound = True
# High Frequency or Low Frequency
zero_crosses = np.nonzero(np.diff(buffer> 0))[0]
zero_crosses_count = zero_crosses.size
if zero_crosses_count > zc_threshold:
is_lf = False
else:
is_lf = True
zero_crossings.append( (i, zero_crosses_count) )
# Voiced or Unvoiced
# 1. Calculate Zero-crossing count Nz, the number of zero crossing in the block
Nz = zero_crosses_count
# 2. Calculate Log energy Es
Es = 10*np.log10(epsilon+sum(map(lambda x:x*x,buffer))/len(buffer))
# 3. Normalized autocorrelation coefficient at unit sample delay, C1
auto_corr_lag_1 = np.correlate(buffer, buffer, mode="full")[1]
C1 = auto_corr_lag_1/np.sqrt((sum(map(lambda x:x*x,buffer[1:])))*(sum(map(lambda x:x*x,buffer[:-1]))))
# 4. First LPC coefficient (12 poles)
FirstLPCcoef = coefs[1]
# 5. Normalized prediction error, Ep, expressed in DB
sum_exp = 10
error_spectrum = abs( np.fft.rfft(downsampled,N) )/spectrum
Ep = np.dot(error_spectrum,error_spectrum) / (N*N)
# LINK: https://www.clear.rice.edu/elec532/PROJECTS00/vocode/uv/uvdet.html
# Means and Covariance Matrix
silence_mean = np.array([9.6613, -38.1601, 0.989, 0.5084, -10.8084])
silence_cov = np.array([[1.0000, 0.6760, -0.7077, -0.1904, 0.7208]
,[0.6760, 1.0000, 0.6933, 0.2918, -0.9425]
,[-0.7077, 0.6933, 1.0000, 0.3275, -0.8426]
,[-0.1904, 0.2918, 0.3275, 1.0000, -0.2122]
,[0.7208, -0.9425, -0.826, -0.2122, 1.0000]])
unvoiced_mean = np.array([10.4286, -36.7536, 0.9598, | 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 = """
_______________________________________________________________________
| |
| __ ___ __ __ ____ |
| \ \ / / \ \ \/ / | _ \ __ _ _ __ ___ ___ _ __ |
| \ \ /\ / / _ \ \ / | |_) / _` | '__/ __|/ _ \ '__| |
| \ V V / ___ \ / \ | __/ (_| | | \__ \ __/ | |
| \_/\_/_/ \_\/_/\_\ |_| \__,_|_| |___/\___|_| |
| |
| _ _ _ _ |
| | |__ _ _ __ _| |__ _ _ ____| |_ _ __ __ _ __| | ___ |
| | '_ \| | | | / _` | '_ \| | | |_ /| __| '__/ _` |/ _` |/ _ \ |
| | |_) | |_| | | (_| | |_) | |_| |/ / | |_| | | (_| | (_| | __/ |
| |_.__/ \__, | \__,_|_.__/ \__,_/___(_)__|_| \__,_|\__,_|\___| |
| |___/ |
|_______________________________________________________________________|
"""
print(banner)
# message limit (must be lower then 4096)
message_limit = 2048
# path
settings_path = os.path.realpath('.') + '/settings.txt'
accounts_path = os.path.realpath('.') + '/db/accounts.txt'
db_path = os.path.realpath('.') + '/db/accounts.db'
log_path = os.path.realpath('.') + '/parser.log'
timer_path = os.path.realpath('.') + '/db/timer.json'
#
scraper = create_scraper()
_log = logger(name='WAXParser', file=log_path, level='INFO').get_logger()
log = log_handler(_log).log
base = baseUniversal(db_path)
# settings and other data
URL = _URL()
Payload = _Payload()
limits_notifications = deepcopy(Payload.limits_notifications)
settings = loadInTxt().get(settings_path)
settings = Struct(**settings)
_u = _utils(settings, base, _log, log, scraper, URL, Payload)
# validate settings
if not settings.bot_token or\
not settings.user_id:
log('Fill bot_token and user_id in settings.txt and restart')
input()
quit()
# telegram
bot = Bot(token=settings.bot_token) | 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, user_id):
try:
text = str(text)
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='html', disable_web_page_preview=True)
except Exception as e:
_log.exception(f'send_reply error: {repr(e)}')
def parser(settings, limits_notifications):
notification(
f"<b>WAXParser started.\n"
f"Creator: <a href=\"https://vk.com/abuz.trade\">abuz.trade</a>\n"
f"GitHub: <a href=\"https://github.com/makarworld/WAXParser\">WAXParser</a>\n"
f"Donate: <a href=\"https://wax.bloks.io/account/abuztradewax\">abuztradewax</a>\n\n"
f"Tokens_notifications: {settings.tokens_notifications}\n"
f"NFTs_notifications: {settings.nfts_notifications}</b>"
)
while True:
accounts = loadInStrings(clear_empty=True, separate=False).get(accounts_path)
accounts_db = _u.get_accounts(whitelist=accounts)
for account in accounts:
acs = loadInStrings(clear_empty=True, separate=False).get(accounts_path)
if account not in acs:
continue
log('fetching...', account)
settings = loadInTxt().get(settings_path)
settings = Struct(**settings)
if account not in accounts_db.keys():
accounts_db[account] = deepcopy(Payload.defoult_account_data)
base.add(
table='accounts',
name=account,
assets=[],
tokens=accounts_db[account]['tokens']
)
tokens_last = accounts_db[account]['tokens']
err, tokens = _u.get_tokens(scraper, account, tokens_last)
if err:
_log.error(err)
nfts_last = accounts_db[account]['assets']
err, assets = _u.get_nfts(scraper, account, nfts_last)
if err:
_log.error(err)
resourses = _u.get_resourses(account)
#print(resourses)
if resourses['cpu_staked'] is not None:
tokens['CPU_STAKED'] = resourses['cpu_staked']
else:
if 'cpu_staked' in accounts_db[account]['tokens'].keys():
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 accounts_db[account]['tokens'].keys():
accounts_db[account]['tokens'][k] = v
text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>'
if settings.tokens_notifications == 'true':
notification(text)
log(f'{account} new token deposit to your wallet: {k}: {v}')
_u.update_timer(k, round(v, 5))
base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens'])
else:
for k1, v1 in tokens.items():
if v1 != accounts_db[account]['tokens'][k1]:
if v1 > accounts_db[account]['tokens'][k1]:
log(f"{account} add balance: +{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]")
_u.update_timer(k1, round(v1 - accounts_db[account]['tokens'][k1], 5))
text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>"
if round(v1 - accounts_db[account]['tokens'][k1], 6) <= 0.0001 and k1 == 'TLM':
notification(
f"<b>Account: {account}\n"\
f"+{round(v1 - accounts_db[account]['tokens'][k1], 5)} TLM\n"\
f"Seems like account was banned...</b>"
)
accounts_db[account]['tokens'][k1] = v1
else:
log(f"{account} transfer balance: -{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]")
text = f"<b>Account: <code>{account}</code>\n-{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>"
accounts_db[account]['tokens'][k1] = v1
if settings.tokens_notifications == 'true':
notification(text)
base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens'])
# check assets
if assets != accounts_db[account]['assets']:
# add or delete assets
new_assets = [str(x) for x in assets if str(x) not in accounts_db[account]['assets']]
del_assets = [str(x) for x in accounts_db[account]['assets'] if str(x) not in assets]
if new_assets:
text = f"<b>Account: <code>{account}</code></b>\n"
_price_sum = 0
for ass in new_assets:
parsed = _u.fetch_asset(ass)
if not parsed['success']:
continue
price = _u.get_price(parsed['template_id'], parsed['name'])
log(f"{account} new asset: {ass} {parsed['name']} ({ | 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 = """
_______________________________________________________________________
| |
| __ ___ __ __ ____ |
| \ \ / / \ \ \/ / | _ \ __ _ _ __ ___ ___ _ __ |
| \ \ /\ / / _ \ \ / | |_) / _` | '__/ __|/ _ \ '__| |
| \ V V / ___ \ / \ | __/ (_| | | \__ \ __/ | |
| \_/\_/_/ \_\/_/\_\ |_| \__,_|_| |___/\___|_| |
| |
| _ _ _ _ |
| | |__ _ _ __ _| |__ _ _ ____| |_ _ __ __ _ __| | ___ |
| | '_ \| | | | / _` | '_ \| | | |_ /| __| '__/ _` |/ _` |/ _ \ |
| | |_) | |_| | | (_| | |_) | |_| |/ / | |_| | | (_| | (_| | __/ |
| |_.__/ \__, | \__,_|_.__/ \__,_/___(_)__|_| \__,_|\__,_|\___| |
| |___/ |
|_______________________________________________________________________|
"""
print(banner)
# message limit (must be lower then 4096)
message_limit = 2048
# path
settings_path = os.path.realpath('.') + '/settings.txt'
accounts_path = os.path.realpath('.') + '/db/accounts.txt'
db_path = os.path.realpath('.') + '/db/accounts.db'
log_path = os.path.realpath('.') + '/parser.log'
timer_path = os.path.realpath('.') + '/db/timer.json'
#
scraper = create_scraper()
_log = logger(name='WAXParser', file=log_path, level='INFO').get_logger()
log = log_handler(_log).log
base = baseUniversal(db_path)
# settings and other data
URL = _URL()
Payload = _Payload()
limits_notifications = deepcopy(Payload.limits_notifications)
settings = loadInTxt().get(settings_path)
settings = Struct(**settings)
_u = _utils(settings, base, _log, log, scraper, URL, Payload)
# validate settings
if not settings.bot_token or\
not settings.user_id:
log('Fill bot_token and user_id in settings.txt and restart')
input()
quit()
# telegram
bot = Bot(token=settings.bot_token)
dp = Dispatcher(bot)
zalupa = asyncio.new_event_loop()
def notification(text):
asyncio.run_coroutine_threadsafe(send_to_all_ids(text), zalupa)
asyn | 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 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='html', disable_web_page_preview=True)
except Exception as e:
_log.exception(f'send_reply error: {repr(e)}')
def parser(settings, limits_notifications):
notification(
f"<b>WAXParser started.\n"
f"Creator: <a href=\"https://vk.com/abuz.trade\">abuz.trade</a>\n"
f"GitHub: <a href=\"https://github.com/makarworld/WAXParser\">WAXParser</a>\n"
f"Donate: <a href=\"https://wax.bloks.io/account/abuztradewax\">abuztradewax</a>\n\n"
f"Tokens_notifications: {settings.tokens_notifications}\n"
f"NFTs_notifications: {settings.nfts_notifications}</b>"
)
while True:
accounts = loadInStrings(clear_empty=True, separate=False).get(accounts_path)
accounts_db = _u.get_accounts(whitelist=accounts)
for account in accounts:
acs = loadInStrings(clear_empty=True, separate=False).get(accounts_path)
if account not in acs:
continue
log('fetching...', account)
settings = loadInTxt().get(settings_path)
settings = Struct(**settings)
if account not in accounts_db.keys():
accounts_db[account] = deepcopy(Payload.defoult_account_data)
base.add(
table='accounts',
name=account,
assets=[],
tokens=accounts_db[account]['tokens']
)
tokens_last = accounts_db[account]['tokens']
err, tokens = _u.get_tokens(scraper, account, tokens_last)
if err:
_log.error(err)
nfts_last = accounts_db[account]['assets']
err, assets = _u.get_nfts(scraper, account, nfts_last)
if err:
_log.error(err)
resourses = _u.get_resourses(account)
#print(resourses)
if resourses['cpu_staked'] is not None:
tokens['CPU_STAKED'] = resourses['cpu_staked']
else:
if 'cpu_staked' in accounts_db[account]['tokens'].keys():
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 accounts_db[account]['tokens'].keys():
accounts_db[account]['tokens'][k] = v
text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>'
if settings.tokens_notifications == 'true':
notification(text)
log(f'{account} new token deposit to your wallet: {k}: {v}')
_u.update_timer(k, round(v, 5))
base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens'])
else:
for k1, v1 in tokens.items():
if v1 != accounts_db[account]['tokens'][k1]:
if v1 > accounts_db[account]['tokens'][k1]:
log(f"{account} add balance: +{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]")
_u.update_timer(k1, round(v1 - accounts_db[account]['tokens'][k1], 5))
text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>"
if round(v1 - accounts_db[account]['tokens'][k1], 6) <= 0.0001 and k1 == 'TLM':
notification(
f"<b>Account: {account}\n"\
f"+{round(v1 - accounts_db[account]['tokens'][k1], 5)} TLM\n"\
f"Seems like account was banned...</b>"
)
accounts_db[account]['tokens'][k1] = v1
else:
log(f"{account} transfer balance: -{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]")
text = f"<b>Account: <code>{account}</code>\n-{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>"
accounts_db[account]['tokens'][k1] = v1
if settings.tokens_notifications == 'true':
notification(text)
base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens'])
# check assets
if assets != accounts_db[account]['assets']:
# add or delete assets
new_assets = [str(x) for x in assets if str(x) not in accounts_db[account]['assets']]
del_assets = [str(x) for x in accounts_db[account]['assets'] if str(x) not in assets]
if new_assets:
text = f"<b>Account: <code>{account}</code></b>\n"
_price_sum = 0
for ass in new_assets:
parsed = _u.fetch_asset(ass)
if not parsed['success']:
continue
price = _u.get_price(parsed['template_id'], parsed['name'])
log(f"{account} new asset: {ass} {parsed['name | 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 = """
_______________________________________________________________________
| |
| __ ___ __ __ ____ |
| \ \ / / \ \ \/ / | _ \ __ _ _ __ ___ ___ _ __ |
| \ \ /\ / / _ \ \ / | |_) / _` | '__/ __|/ _ \ '__| |
| \ V V / ___ \ / \ | __/ (_| | | \__ \ __/ | |
| \_/\_/_/ \_\/_/\_\ |_| \__,_|_| |___/\___|_| |
| |
| _ _ _ _ |
| | |__ _ _ __ _| |__ _ _ ____| |_ _ __ __ _ __| | ___ |
| | '_ \| | | | / _` | '_ \| | | |_ /| __| '__/ _` |/ _` |/ _ \ |
| | |_) | |_| | | (_| | |_) | |_| |/ / | |_| | | (_| | (_| | __/ |
| |_.__/ \__, | \__,_|_.__/ \__,_/___(_)__|_| \__,_|\__,_|\___| |
| |___/ |
|_______________________________________________________________________|
"""
print(banner)
# message limit (must be lower then 4096)
message_limit = 2048
# path
settings_path = os.path.realpath('.') + '/settings.txt'
accounts_path = os.path.realpath('.') + '/db/accounts.txt'
db_path = os.path.realpath('.') + '/db/accounts.db'
log_path = os.path.realpath('.') + '/parser.log'
timer_path = os.path.realpath('.') + '/db/timer.json'
#
scraper = create_scraper()
_log = logger(name='WAXParser', file=log_path, level='INFO').get_logger()
log = log_handler(_log).log
base = baseUniversal(db_path)
# settings and other data
URL = _URL()
Payload = _Payload()
limits_notifications = deepcopy(Payload.limits_notifications)
settings = loadInTxt().get(settings_path)
settings = Struct(**settings)
_u = _utils(settings, base, _log, log, scraper, URL, Payload)
# validate settings
if not settings.bot_token or\
not settings.user_id:
log('Fill bot_token and user_id in settings.txt and restart')
input()
quit()
# telegram
bot = Bot(token=settings.bot_token)
dp = Dispatcher(bot)
zalupa = asyncio.new_event_loop()
def notification(text):
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)
| 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='html', disable_web_page_preview=True)
except Exception as e:
_log.exception(f'send_reply error: {repr(e)}')
def parser(settings, limits_notifications):
notification(
f"<b>WAXParser started.\n"
f"Creator: <a href=\"https://vk.com/abuz.trade\">abuz.trade</a>\n"
f"GitHub: <a href=\"https://github.com/makarworld/WAXParser\">WAXParser</a>\n"
f"Donate: <a href=\"https://wax.bloks.io/account/abuztradewax\">abuztradewax</a>\n\n"
f"Tokens_notifications: {settings.tokens_notifications}\n"
f"NFTs_notifications: {settings.nfts_notifications}</b>"
)
while True:
accounts = loadInStrings(clear_empty=True, separate=False).get(accounts_path)
accounts_db = _u.get_accounts(whitelist=accounts)
for account in accounts:
acs = loadInStrings(clear_empty=True, separate=False).get(accounts_path)
if account not in acs:
continue
log('fetching...', account)
settings = loadInTxt().get(settings_path)
settings = Struct(**settings)
if account not in accounts_db.keys():
accounts_db[account] = deepcopy(Payload.defoult_account_data)
base.add(
table='accounts',
name=account,
assets=[],
tokens=accounts_db[account]['tokens']
)
tokens_last = accounts_db[account]['tokens']
err, tokens = _u.get_tokens(scraper, account, tokens_last)
if err:
_log.error(err)
nfts_last = accounts_db[account]['assets']
err, assets = _u.get_nfts(scraper, account, nfts_last)
if err:
_log.error(err)
resourses = _u.get_resourses(account)
#print(resourses)
if resourses['cpu_staked'] is not None:
tokens['CPU_STAKED'] = resourses['cpu_staked']
else:
if 'cpu_staked' in accounts_db[account]['tokens'].keys():
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 accounts_db[account]['tokens'].keys():
accounts_db[account]['tokens'][k] = v
text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>'
if settings.tokens_notifications == 'true':
notification(text)
log(f'{account} new token deposit to your wallet: {k}: {v}')
_u.update_timer(k, round(v, 5))
base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens'])
else:
for k1, v1 in tokens.items():
if v1 != accounts_db[account]['tokens'][k1]:
if v1 > accounts_db[account]['tokens'][k1]:
log(f"{account} add balance: +{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]")
_u.update_timer(k1, round(v1 - accounts_db[account]['tokens'][k1], 5))
text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>"
if round(v1 - accounts_db[account]['tokens'][k1], 6) <= 0.0001 and k1 == 'TLM':
notification(
f"<b>Account: {account}\n"\
f"+{round(v1 - accounts_db[account]['tokens'][k1], 5)} TLM\n"\
f"Seems like account was banned...</b>"
)
accounts_db[account]['tokens'][k1] = v1
else:
log(f"{account} transfer balance: -{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]")
text = f"<b>Account: <code>{account}</code>\n-{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>"
accounts_db[account]['tokens'][k1] = v1
if settings.tokens_notifications == 'true':
notification(text)
base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens'])
# check assets
if assets != accounts_db[account]['assets']:
# add or delete assets
new_assets = [str(x) for x in assets if str(x) not in accounts_db[account]['assets']]
del_assets = [str(x) for x in accounts_db[account]['assets'] if str(x) not in assets]
if new_assets:
text = f"<b>Account: <code>{account}</code></b>\n"
_price_sum = 0
for ass in new_assets:
parsed = _u.fetch_asset(ass)
if not parsed['success']:
continue
price = _u.get_price(parsed['template_id'], parsed['name'])
log(f"{account} new asset: {ass} {parsed['name']} ({ | 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 = """
_______________________________________________________________________
| |
| __ ___ __ __ ____ |
| \ \ / / \ \ \/ / | _ \ __ _ _ __ ___ ___ _ __ |
| \ \ /\ / / _ \ \ / | |_) / _` | '__/ __|/ _ \ '__| |
| \ V V / ___ \ / \ | __/ (_| | | \__ \ __/ | |
| \_/\_/_/ \_\/_/\_\ |_| \__,_|_| |___/\___|_| |
| |
| _ _ _ _ |
| | |__ _ _ __ _| |__ _ _ ____| |_ _ __ __ _ __| | ___ |
| | '_ \| | | | / _` | '_ \| | | |_ /| __| '__/ _` |/ _` |/ _ \ |
| | |_) | |_| | | (_| | |_) | |_| |/ / | |_| | | (_| | (_| | __/ |
| |_.__/ \__, | \__,_|_.__/ \__,_/___(_)__|_| \__,_|\__,_|\___| |
| |___/ |
|_______________________________________________________________________|
"""
print(banner)
# message limit (must be lower then 4096)
message_limit = 2048
# path
settings_path = os.path.realpath('.') + '/settings.txt'
accounts_path = os.path.realpath('.') + '/db/accounts.txt'
db_path = os.path.realpath('.') + '/db/accounts.db'
log_path = os.path.realpath('.') + '/parser.log'
timer_path = os.path.realpath('.') + '/db/timer.json'
#
scraper = create_scraper()
_log = logger(name='WAXParser', file=log_path, level='INFO').get_logger()
log = log_handler(_log).log
base = baseUniversal(db_path)
# settings and other data
URL = _URL()
Payload = _Payload()
limits_notifications = deepcopy(Payload.limits_notifications)
settings = loadInTxt().get(settings_path)
settings = Struct(**settings)
_u = _utils(settings, base, _log, log, scraper, URL, Payload)
# validate settings
if not settings.bot_token or\
not settings.user_id:
log('Fill bot_token and user_id in settings.txt and restart')
input()
quit()
# telegram
bot = Bot(token=settings.bot_token)
dp = Dispatcher(bot)
zalupa = asyncio.new_event_loop()
def notification(text):
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, user_id):
try:
text = str(text)
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='html', disable_web_page_preview=True)
except Exception as e:
_log.exception(f'send_reply error: {repr(e)}')
def parser(settings, limits_notifications):
notification(
f"<b>WAXParser started.\n"
f"Creator: <a href=\"https://vk.com/abuz.trade\">abuz.trade</a>\n"
f"GitHub: <a href=\"https://github.com/makarworld/WAXParser\">WAXParser</a>\n"
f"Donate: <a href=\"https://wax.bloks.io/account/abuztradewax\">abuztradewax</a>\n\n"
f"Tokens_notifications: {settings.tokens_notifications}\n"
f"NFTs_notifications: {settings.nfts_notifications}</b>"
)
while True:
accounts = loadInStrings(clear_empty=True, separate=False).get(accounts_path)
accounts_db = _u.get_accounts(whitelist=accounts)
for account in accounts:
acs = loadInStrings(clear_empty=True, separate=False).get(accounts_path)
if account not in acs:
continue
log('fetching...', account)
settings = loadInTxt().get(settings_path)
settings = Struct(**settings)
if account not in accounts_db.keys():
accounts_db[account] = deepcopy(Payload.defoult_account_data)
base.add(
table='accounts',
name=account,
assets=[],
tokens=accounts_db[account]['tokens']
)
tokens_last = accounts_db[account]['tokens']
err, tokens = _u.get_tokens(scraper, account, tokens_last)
if err:
_log.error(err)
nfts_last = accounts_db[account]['assets']
err, assets = _u.get_nfts(scraper, account, nfts_last)
if err:
_log.error(err)
resourses = _u.get_resourses(account)
#print(resourses)
if resourses['cpu_staked'] is not None:
tokens['CPU_STAKED'] = resourses['cpu_staked']
else:
if 'cpu_stak | 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 accounts_db[account]['tokens'].keys():
accounts_db[account]['tokens'][k] = v
text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>'
if settings.tokens_notifications == 'true':
notification(text)
log(f'{account} new token deposit to your wallet: {k}: {v}')
_u.update_timer(k, round(v, 5))
base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens'])
else:
for k1, v1 in tokens.items():
if v1 != accounts_db[account]['tokens'][k1]:
if v1 > accounts_db[account]['tokens'][k1]:
log(f"{account} add balance: +{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]")
_u.update_timer(k1, round(v1 - accounts_db[account]['tokens'][k1], 5))
text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_db[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>"
if round(v1 - accounts_db[account]['tokens'][k1], 6) <= 0.0001 and k1 == 'TLM':
notification(
f"<b>Account: {account}\n"\
f"+{round(v1 - accounts_db[account]['tokens'][k1], 5)} TLM\n"\
f"Seems like account was banned...</b>"
)
accounts_db[account]['tokens'][k1] = v1
else:
log(f"{account} transfer balance: -{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]")
text = f"<b>Account: <code>{account}</code>\n-{round(accounts_db[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>"
accounts_db[account]['tokens'][k1] = v1
if settings.tokens_notifications == 'true':
notification(text)
base.edit_by('accounts', ['name', account], tokens=accounts_db[account]['tokens'])
# check assets
if assets != accounts_db[account]['assets']:
# add or delete assets
new_assets = [str(x) for x in assets if str(x) not in accounts_db[account]['assets']]
del_assets = [str(x) for x in accounts_db[account]['assets'] if str(x) not in assets]
if new_assets:
text = f"<b>Account: <code>{account}</code></b>\n"
_price_sum = 0
for ass in new_assets:
parsed = _u.fetch_asset(ass)
if not parsed['success']:
continue
price = _u.get_price(parsed['template_id'], parsed['name'])
log(f"{account} new asset: {ass} {parsed['name']} ({ | 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])?;
let value = if branch_has_value {
Some(if contains_hash {
ValuePlan::Node(input.take(H::LENGTH)?)
} else {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
ValuePlan::Inline(input.take(count)?)
})
} else {
None
};
let mut children = [
None, None, None, None, None, None, None, None, None, None, None, None, None,
None, None, None,
];
for i in 0..nibble_ops::NIBBLE_LENGTH {
if bitmap.value_at(i) {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
let range = input.take(count)?;
children[i] = Some(if count == H::LENGTH {
NodeHandlePlan::Hash(range)
} else {
NodeHandlePlan::Inline(range)
});
}
}
Ok(NodePlan::NibbledBranch {
partial: NibbleSlicePlan::new(partial, partial_padding),
value,
children,
})
},
NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) => {
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)) /
nibble_ops::NIBBLE_PER_BYTE,
)?;
let partial_padding = nibble_ops::number_padding(nibble_count);
let value = if contains_hash {
ValuePlan::Node(input.take(H::LENGTH)?)
} else {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
ValuePlan::Inline(input.take(count)?)
};
Ok(NodePlan::Leaf {
partial: NibbleSlicePlan::new(partial, partial_padding),
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 decode_plan(data: &[u8]) -> Result<NodePlan, Self::Error> {
Self::decode_plan_inner_hashed(data)
}
fn is_empty_node(data: &[u8]) -> bool {
data == <Self as NodeCodecT>::empty_node()
}
fn empty_node() -> &'static [u8] {
&[trie_constants::EMPTY_TRIE]
}
fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> {
let contains_hash = matches!(&value, Value::Node(..));
let 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.extend_from_slice(value);
},
Value::Node(hash) => {
debug_assert!(hash.len() == H::LENGTH);
output.extend_from_slice(hash);
},
} | 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<Value>,
) -> Vec<u8> {
unreachable!("Codec without extension.")
}
fn branch_node_nibbled(
partial: impl Iterator<Item = u8>,
number_nibble: usize,
children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>,
value: Option<Value>,
) -> Vec<u8> {
let contains_hash = matches!(&value, Some(Value::Node(..)));
let mut output = match (&value, contains_hash) {
(&None, _) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue),
(_, false) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue),
(_, true) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch),
};
let bitmap_index = output.len();
let mut bitmap: [u8; BITMAP_LENGTH] = [0; BITMAP_LENGTH];
(0..BITMAP_LENGTH).for_each(|_| output.push(0));
match value {
Some(Value::Inline(value)) => {
Compact(value.len() as u32).encode_to(&mut output);
output.extend_from_slice(value);
},
Some(Value::Node(hash)) => {
debug_assert!(hash.len() == H::LENGTH);
output.extend_from_slice(hash);
},
None => (),
}
Bitmap::encode(
children.map(|maybe_child| match maybe_child.borrow() {
Some(ChildReference::Hash(h)) => {
h.as_ref().encode_to(&mut output);
true
},
&Some(ChildReference::Inline(inline_data, len)) => {
inline_data.as_ref()[..len].encode_to(&mut output);
true
},
None => false,
}),
bitmap.as_mut(),
);
output[bitmap_index..bitmap_index + BITMAP_LENGTH]
.copy_from_slice(&bitmap[..BITMAP_LENGTH]);
output
}
}
// utils
/// Encode and allocate node type header (type and size), and partial value.
/// It uses an iterator over encoded partial bytes as input.
fn partial_from_iterator_encode<I: Iterator<Item = u8>>(
partial: I,
nibble_count: usize,
node_kind: NodeKind,
) -> Vec<u8> {
let nibble_count = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count);
let mut output = Vec::with_capacity(4 + (nibble_count / nibble_ops::NIBBLE_PER_BYTE));
match node_kind {
NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output),
NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output),
NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output),
NodeKind::HashedValueLeaf =>
NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output),
NodeKind::HashedValueBranch =>
NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output),
};
output.extend(partial);
output
}
/// A node header.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum NodeHeader {
Null,
// contains wether there is a value and nibble count
Branch(bool, usize),
// contains nibble count
Leaf(usize),
// contains nibble count.
HashedValueBranch(usize),
// contains nibble count.
HashedValueLeaf(usize),
}
impl NodeHeader {
fn contains_hash_of_value(&self) -> bool {
match self {
NodeHeader::HashedValueBranch(_) | NodeHeader::HashedValueLeaf(_) => true,
_ => false,
}
}
}
/// NodeHeader without content
pub(crate) enum NodeKind {
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_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output),
NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix(
*nibble_count,
trie_constants::BRANCH_WITHOUT_MASK,
2,
output,
),
NodeHeader::Leaf(nibble_count) =>
encode_size_and_prefix(*nibble_count | 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 value = if branch_has_value {
Some(if contains_hash {
ValuePlan::Node(input.take(H::LENGTH)?)
} else {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
ValuePlan::Inline(input.take(count)?)
})
} else {
None
};
let mut children = [
None, None, None, None, None, None, None, None, None, None, None, None, None,
None, None, None,
];
for i in 0..nibble_ops::NIBBLE_LENGTH {
if bitmap.value_at(i) {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
let range = input.take(count)?;
children[i] = Some(if count == H::LENGTH {
NodeHandlePlan::Hash(range)
} else {
NodeHandlePlan::Inline(range)
});
}
}
Ok(NodePlan::NibbledBranch {
partial: NibbleSlicePlan::new(partial, partial_padding),
value,
children,
})
},
NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) => | 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 decode_plan(data: &[u8]) -> Result<NodePlan, Self::Error> {
Self::decode_plan_inner_hashed(data)
}
fn is_empty_node(data: &[u8]) -> bool {
data == <Self as NodeCodecT>::empty_node()
}
fn empty_node() -> &'static [u8] {
&[trie_constants::EMPTY_TRIE]
}
fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> {
let contains_hash = matches!(&value, Value::Node(..));
let 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.extend_from_slice(value);
},
Value::Node(hash) => {
debug_assert!(hash.len() == H::LENGTH);
output.extend_from_slice(hash);
},
}
output
}
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<Value>,
) -> Vec<u8> {
unreachable!("Codec without extension.")
}
fn branch_node_nibbled(
partial: impl Iterator<Item = u8>,
number_nibble: usize,
children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>,
value: Option<Value>,
) -> Vec<u8> {
let contains_hash = matches!(&value, Some(Value::Node(..)));
let mut output = match (&value, contains_hash) {
(&None, _) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue),
(_, false) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue),
(_, true) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch),
};
let bitmap_index = output.len();
let mut bitmap: [u8; BITMAP_LENGTH] = [0; BITMAP_LENGTH];
(0..BITMAP_LENGTH).for_each(|_| output.push(0));
match value {
Some(Value::Inline(value)) => {
Compact(value.len() as u32).encode_to(&mut output);
output.extend_from_slice(value);
},
Some(Value::Node(hash)) => {
debug_assert!(hash.len() == H::LENGTH);
output.extend_from_slice(hash);
},
None => (),
}
Bitmap::encode(
children.map(|maybe_child| match maybe_child.borrow() {
Some(ChildReference::Hash(h)) => {
h.as_ref().encode_to(&mut output);
true
},
&Some(ChildReference::Inline(inline_data, len)) => {
inline_data.as_ref()[..len].encode_to(&mut output);
true
},
None => false,
}),
bitmap.as_mut(),
);
output[bitmap_index..bitmap_index + BITMAP_LENGTH]
.copy_from_slice(&bitmap[..BITMAP_LENGTH]);
output
}
}
// utils
/// Encode and allocate node type header (type and size), and partial value.
/// It uses an iterator over encoded partial bytes as input.
fn partial_from_iterator_encode<I: Iterator<Item = u8>>(
partial: I,
nibble_count: usize,
node_kind: NodeKind,
) -> Vec<u8> {
let nibble_count = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count);
let mut output = Vec::with_capacity(4 + (nibble_count / nibble_ops::NIBBLE_PER_BYTE));
match node_kind {
NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output),
NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output),
NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output),
NodeKind::HashedValueLeaf =>
NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output),
NodeKind::HashedValueBranch =>
NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output),
};
output.extend(partial);
output
}
/// A node header.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum NodeHeader {
Null,
// contains wether there is a value and nibble count
Branch(bool, usize),
// contains nibble count
Leaf(usize),
// contains nibble count.
HashedValueBranch(usize),
// contains nibble count.
HashedValueLeaf(usize),
}
impl NodeHeader {
fn contains_hash_of_value(&self) -> bool {
match self {
NodeHeader::HashedValueBranch(_) | NodeHeader::HashedValueLeaf(_) => true,
_ => false,
}
}
}
/// NodeHeader without content
pub(crate) enum NodeKind {
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_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output),
NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix(
*nibble_count,
trie_constants::BRANCH_WITHOUT_MASK,
2,
output,
),
NodeHeader::Leaf(nibble_count) =>
encode_size_and_prefix(*nibble | {
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)) /
nibble_ops::NIBBLE_PER_BYTE,
)?;
let partial_padding = nibble_ops::number_padding(nibble_count);
let value = if contains_hash {
ValuePlan::Node(input.take(H::LENGTH)?)
} else {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
ValuePlan::Inline(input.take(count)?)
};
Ok(NodePlan::Leaf {
partial: NibbleSlicePlan::new(partial, partial_padding), | 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])?;
let value = if branch_has_value {
Some(if contains_hash {
ValuePlan::Node(input.take(H::LENGTH)?)
} else {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
ValuePlan::Inline(input.take(count)?)
})
} else {
None
};
let mut children = [
None, None, None, None, None, None, None, None, None, None, None, None, None,
None, None, None,
];
for i in 0..nibble_ops::NIBBLE_LENGTH {
if bitmap.value_at(i) {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
let range = input.take(count)?;
children[i] = Some(if count == H::LENGTH {
NodeHandlePlan::Hash(range)
} else {
NodeHandlePlan::Inline(range)
});
}
}
Ok(NodePlan::NibbledBranch {
partial: NibbleSlicePlan::new(partial, partial_padding),
value,
children,
})
},
NodeHeader::HashedValueLeaf(nibble_count) | NodeHeader::Leaf(nibble_count) => {
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)) /
nibble_ops::NIBBLE_PER_BYTE,
)?;
let partial_padding = nibble_ops::number_padding(nibble_count);
let value = if contains_hash {
ValuePlan::Node(input.take(H::LENGTH)?)
} else {
let count = <Compact<u32>>::decode(&mut input)?.0 as usize;
ValuePlan::Inline(input.take(count)?)
};
Ok(NodePlan::Leaf {
partial: NibbleSlicePlan::new(partial, partial_padding),
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 decode_plan(data: &[u8]) -> Result<NodePlan, Self::Error> {
Self::decode_plan_inner_hashed(data)
}
fn is_empty_node(data: &[u8]) -> bool {
data == <Self as NodeCodecT>::empty_node()
}
fn empty_node() -> &'static [u8] {
&[trie_constants::EMPTY_TRIE]
}
fn leaf_node(partial: impl Iterator<Item = u8>, number_nibble: usize, value: Value) -> Vec<u8> {
let contains_hash = matches!(&value, Value::Node(..));
let 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.extend_from_slice(value);
},
Value::Node(hash) => {
debug_assert!(hash.len() == H::LENGTH);
output.extend_from_slice(hash);
},
}
output
}
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<Value>,
) -> Vec<u8> {
unreachable!("Codec without extension.")
}
fn branch_node_nibbled(
partial: impl Iterator<Item = u8>,
number_nibble: usize,
children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>,
value: Option<Value>,
) -> Vec<u8> {
let contains_hash = matches!(&value, Some(Value::Node(..)));
let mut output = match (&value, contains_hash) {
(&None, _) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue),
(_, false) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue),
(_, true) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch),
};
let bitmap_index = output.len();
let mut bitmap: [u8; BITMAP_LENGTH] = [0; BITMAP_LENGTH];
(0..BITMAP_LENGTH).for_each(|_| output.push(0));
match value {
Some(Value::Inline(value)) => {
Compact(value.len() as u32).encode_to(&mut output);
output.extend_from_slice(value);
},
Some(Value::Node(hash)) => {
debug_assert!(hash.len() == H::LENGTH);
output.extend_from_slice(hash);
},
None => (),
}
Bitmap::encode(
children.map(|maybe_child| match maybe_child.borrow() {
Some(ChildReference::Hash(h)) => {
h.as_ref().encode_to(&mut output);
true
},
&Some(ChildReference::Inline(inline_data, len)) => {
inline_data.as_ref()[..len].encode_to(&mut output);
true
},
None => false,
}),
bitmap.as_mut(),
);
output[bitmap_index..bitmap_index + BITMAP_LENGTH]
.copy_from_slice(&bitmap[..BITMAP_LENGTH]);
output
}
}
// utils
/// Encode and allocate node type header (type and size), and partial value.
/// It uses an iterator over encoded partial bytes as input.
fn partial_from_iterator_encode<I: Iterator<Item = u8>>(
partial: I,
nibble_count: usize,
node_kind: NodeKind,
) -> Vec<u8> {
let nibble_count = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count);
let mut output = Vec::with_capacity(4 + (nibble_count / nibble_ops::NIBBLE_PER_BYTE));
match node_kind {
NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output),
NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output),
NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output),
NodeKind::HashedValueLeaf =>
NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output),
NodeKind::HashedValueBranch =>
NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output),
};
output.extend(partial);
output
}
/// A node header.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum NodeHeader {
Null,
// contains wether there is a value and nibble count
Branch(bool, usize),
// contains nibble count
Leaf(usize),
// contains nibble count.
HashedValueBranch(usize),
// contains nibble count.
HashedValueLeaf(usize),
}
impl NodeHeader {
fn contains_hash_of_value(&self) -> bool {
match self {
NodeHeader::HashedValueBranch(_) | NodeHeader::HashedValueLeaf(_) => true,
_ => false,
}
}
}
/// NodeHeader without content
pub(crate) enum | {
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_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output),
NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix(
*nibble_count,
trie_constants::BRANCH_WITHOUT_MASK,
2,
output,
),
NodeHeader::Leaf(nibble_count) =>
encode_size_and_prefix(*nibble | 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.extend_from_slice(value);
},
Value::Node(hash) => {
debug_assert!(hash.len() == H::LENGTH);
output.extend_from_slice(hash);
},
}
output
}
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<Value>,
) -> Vec<u8> {
unreachable!("Codec without extension.")
}
fn branch_node_nibbled(
partial: impl Iterator<Item = u8>,
number_nibble: usize,
children: impl Iterator<Item = impl Borrow<Option<ChildReference<<H as Hasher>::Out>>>>,
value: Option<Value>,
) -> Vec<u8> {
let contains_hash = matches!(&value, Some(Value::Node(..)));
let mut output = match (&value, contains_hash) {
(&None, _) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchNoValue),
(_, false) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::BranchWithValue),
(_, true) =>
partial_from_iterator_encode(partial, number_nibble, NodeKind::HashedValueBranch),
};
let bitmap_index = output.len();
let mut bitmap: [u8; BITMAP_LENGTH] = [0; BITMAP_LENGTH];
(0..BITMAP_LENGTH).for_each(|_| output.push(0));
match value {
Some(Value::Inline(value)) => {
Compact(value.len() as u32).encode_to(&mut output);
output.extend_from_slice(value);
},
Some(Value::Node(hash)) => {
debug_assert!(hash.len() == H::LENGTH);
output.extend_from_slice(hash);
},
None => (),
}
Bitmap::encode(
children.map(|maybe_child| match maybe_child.borrow() {
Some(ChildReference::Hash(h)) => {
h.as_ref().encode_to(&mut output);
true
},
&Some(ChildReference::Inline(inline_data, len)) => {
inline_data.as_ref()[..len].encode_to(&mut output);
true
},
None => false,
}),
bitmap.as_mut(),
);
output[bitmap_index..bitmap_index + BITMAP_LENGTH]
.copy_from_slice(&bitmap[..BITMAP_LENGTH]);
output
}
}
// utils
/// Encode and allocate node type header (type and size), and partial value.
/// It uses an iterator over encoded partial bytes as input.
fn partial_from_iterator_encode<I: Iterator<Item = u8>>(
partial: I,
nibble_count: usize,
node_kind: NodeKind,
) -> Vec<u8> {
let nibble_count = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibble_count);
let mut output = Vec::with_capacity(4 + (nibble_count / nibble_ops::NIBBLE_PER_BYTE));
match node_kind {
NodeKind::Leaf => NodeHeader::Leaf(nibble_count).encode_to(&mut output),
NodeKind::BranchWithValue => NodeHeader::Branch(true, nibble_count).encode_to(&mut output),
NodeKind::BranchNoValue => NodeHeader::Branch(false, nibble_count).encode_to(&mut output),
NodeKind::HashedValueLeaf =>
NodeHeader::HashedValueLeaf(nibble_count).encode_to(&mut output),
NodeKind::HashedValueBranch =>
NodeHeader::HashedValueBranch(nibble_count).encode_to(&mut output),
};
output.extend(partial);
output
}
/// A node header.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub(crate) enum NodeHeader {
Null,
// contains wether there is a value and nibble count
Branch(bool, usize),
// contains nibble count
Leaf(usize),
// contains nibble count.
HashedValueBranch(usize),
// contains nibble count.
HashedValueLeaf(usize),
}
impl NodeHeader {
fn contains_hash_of_value(&self) -> bool {
match self {
NodeHeader::HashedValueBranch(_) | NodeHeader::HashedValueLeaf(_) => true,
_ => false,
}
}
}
/// NodeHeader without content
pub(crate) enum NodeKind {
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_and_prefix(*nibble_count, trie_constants::BRANCH_WITH_MASK, 2, output),
NodeHeader::Branch(false, nibble_count) => encode_size_and_prefix(
*nibble_count,
trie_constants::BRANCH_WITHOUT_MASK,
2,
output,
),
NodeHeader::Leaf(nibble_count) =>
encode_size_and_prefix(*nibble_count, trie_constants::LEAF_PREFIX_MASK, 2, output),
NodeHeader::HashedValueBranch(nibble_count) => encode_size_and_prefix(
*nibble_count,
trie_constants::ALT_HASHING_BRANCH_WITH_MASK,
4,
output,
),
NodeHeader::HashedValueLeaf(nibble_count) => encode_size_and_prefix(
*nibble_count,
trie_constants::ALT_HASHING_LEAF_PREFIX_MASK,
3,
output,
),
}
}
}
impl parity_scale_codec::EncodeLike for NodeHeader {}
impl Decode for NodeHeader {
fn decode<I: Input>(input: &mut I) -> Result<Self, Error> {
let i = input.read_byte()?;
if i == trie_constants::EMPTY_TRIE {
return Ok(NodeHeader::Null)
}
match i & (0b11 << 6) {
trie_constants::LEAF_PREFIX_MASK => Ok(NodeHeader::Leaf(decode_size(i, input, 2)?)),
trie_constants::BRANCH_WITH_MASK =>
Ok(NodeHeader::Branch(true, decode_size(i, input, 2)?)),
trie_constants::BRANCH_WITHOUT_MASK =>
Ok(NodeHeader::Branch(false, decode_size(i, input, 2)?)),
trie_constants::EMPTY_TRIE => {
if i & (0b111 << 5) == trie_constants::ALT_HASHING_LEAF_PREFIX_MASK {
Ok(NodeHeader::HashedValueLeaf(decode_size(i, input, 3)?))
} else if i & (0b1111 << 4) == trie_constants::ALT_HASHING_BRANCH_WITH_MASK {
Ok(NodeHeader::HashedValueBranch(decode_size(i, input, 4)?))
} else {
// do not allow any special encoding
Err("Unallowed encoding".into())
}
},
_ => unreachable!(),
}
}
}
/// Returns an iterator over encoded bytes for node header and size.
/// Size encoding allows unlimited, length inefficient, representation, but
/// is bounded to 16 bit maximum value to avoid possible DOS.
pub(crate) fn size_and_prefix_iterator(
size: usize,
prefix: u8,
prefix_mask: usize,
) -> impl Iterator<Item = u8> {
let size = std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, size);
let max_value = 255u8 >> prefix_mask;
let l1 = std::cmp::min(max_value as usize - 1, size);
let (first_byte, mut rem) = if size == l1 {
(once(prefix + l1 as u8), 0)
} else {
(once(prefix + max_value as u8), size - l1)
};
let next_bytes = move || {
if rem > 0 {
if rem < 256 {
let result = rem - 1;
rem = 0;
Some(result as u8)
} else {
rem = rem.saturating_sub(255);
Some(255)
}
} else {
None
}
};
first_byte.chain(std::iter::from_fn(next_bytes))
}
/// Encodes size and prefix to a stream output (prefix on 2 first bit only).
fn encode_size_and_prefix<W>(size: usize, prefix: u8, prefix_mask: usize, out: &mut W)
where
W: Output + ?Sized,
| {
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 tableSchemaCache, nil
}
func (t *TableSchema) findColumnByName(name string) (*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 NonExistingPaginationKeyColumnError(schema, table, paginationKey string) error {
return fmt.Errorf("Pagination Key `%s` for %s non existent", paginationKey, QuotedTableNameFromString(schema, table))
}
// NonExistingPaginationKeyError exported to facilitate black box testing
func NonExistingPaginationKeyError(schema, table string) error {
return fmt.Errorf("%s has no Primary Key to default to for Pagination purposes. Kindly specify a Pagination Key for this table in the CascadingPaginationColumnConfig", QuotedTableNameFromString(schema, table))
}
// UnsupportedPaginationKeyError exported to facilitate black box testing
func UnsupportedPaginationKeyError(schema, table, paginationKey string) error {
return fmt.Errorf("Pagination Key `%s` for %s is non-numeric/-text", paginationKey, QuotedTableNameFromString(schema, table))
}
func (t *TableSchema) paginationKey(cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (*PaginationKey, error) {
var err error
paginationKeyColumns := make([]*schema.TableColumn, 0)
paginationKeyColumnIndices := make([]int, 0)
if paginationColumn, found := cascadingPaginationColumnConfig.PaginationColumnFor(t.Schema, t.Name); found {
// Use per-schema, per-table pagination key from config
var paginationKeyColumn *schema.TableColumn
var paginationKeyIndex int
paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(paginationColumn)
if err == nil {
paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn)
paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex)
}
} else if len(t.PKColumns) > 0 {
// Use Primary Key
//
// NOTE: A primary key has to be unique, but it may contain columns that
// are not needed for uniqueness. The ideal pagination key has length of
// 1, so we explicitly check if a subset of keys is sufficient.
// We could also do this checking for a uniqueness contstraint in the
// future
for i, column := range t.Columns {
if column.IsAuto {
paginationKeyColumns = append(paginationKeyColumns, &column)
paginationKeyColumnIndices = append(paginationKeyColumnIndices, i)
break
}
}
// if we failed finding an auto-increment, build a composite key
if len(paginationKeyColumns) == 0 {
for _, paginationKeyIndex := range t.PKColumns {
paginationKeyColumns = append(paginationKeyColumns, &t.Columns[paginationKeyIndex])
paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex)
}
}
} else if fallbackColumnName, found := cascadingPaginationColumnConfig.FallbackPaginationColumnName(); found {
// Try fallback from config
var paginationKeyColumn *schema.TableColumn
var paginationKeyIndex int
paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(fallbackColumnName)
if err == nil {
paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn)
paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex)
}
} else {
// No usable pagination key found
err = NonExistingPaginationKeyError(t.Schema, t.Name)
}
if err != nil || len(paginationKeyColumns) == 0 {
if err == nil {
panic(fmt.Errorf("no pagination key found, but no error set either"))
}
return nil, err
}
for _, column := range paginationKeyColumns {
switch column.Type {
case schema.TYPE_NUMBER, schema.TYPE_STRING, schema.TYPE_VARBINARY, schema.TYPE_BINARY:
default:
return nil, UnsupportedPaginationKeyError(t.Schema, t.Name, column.Name)
}
}
paginationKey := &PaginationKey{
Columns: paginationKeyColumns,
ColumnIndices: paginationKeyColumnIndices,
}
return paginationKey, err
}
func (c TableSchemaCache) AsSlice() (tables []*TableSchema) {
for _, tableSchema := range c {
tables = append(tables, tableSchema)
}
return
}
func (c TableSchemaCache) AllTableNames() (tableNames []string) {
for tableName, _ := range c {
tableNames = append(tableNames, tableName)
}
return
}
func (c TableSchemaCache) Get(database, table string) *TableSchema {
return c[fullTableName(database, table)]
}
// Helper to sort a given map of tables with a second list giving a priority.
// If an element is present in the input and the priority lists, the item will
// appear first (in the order of the priority list), all other items appear in
// the order given in the input
func (c TableSchemaCache) GetTableListWithPriority(priorityList []string) (prioritzedTableNames []string) {
// just a fast lookup if the list contains items already
contains := map[string]struct{}{}
if len(priorityList) >= 0 {
for _, tableName := range priorityList {
// ignore tables given in the priority list that we don't know
if _, found := c[tableName]; found {
contains[tableName] = struct{}{}
prioritzedTableNames = append(prioritzedTableNames, tableName)
}
}
}
for tableName, _ := range c {
if _, found := contains[tableName]; !found {
prioritzedTableNames = append(prioritzedTableNames, tableName)
}
}
return
}
// Helper to sort the given map of tables based on the dependencies between
// tables in terms of foreign key constraints
func (c TableSchemaCache) GetTableCreationOrder(db *sql.DB) (prioritzedTableNames []string, err error) {
logger := logrus.WithField("tag", "table_schema_cache")
tableReferences := make(map[QualifiedTableName]TableForeignKeys)
for tableName, _ := range c {
t := strings.Split(tableName, ".")
table := NewQualifiedTableName(t[0], t[1])
// ignore self-references, as they are not really foreign keys
referencedTables, dbErr := GetForeignKeyTablesOfTable(db, table, false)
if dbErr != nil {
logger.WithField("table", table).Error("cannot analyze database table foreign keys")
err = dbErr
return
}
logger.Debugf("found %d reference tables for %s", len(referencedTables), table)
tableReferences[table] = referencedTables
}
// simple fix-point loop: make sure we create at least one table per
// iteration and mark tables as able to create as soon as they no-longer
// refer to other tables
for len(tableReferences) > 0 {
createdTable := false
for table, referencedTables := range tableReferences {
if len(referencedTables) > 0 {
continue
}
logger.Debugf("queuing %s", table)
prioritzedTableNames = append(prioritzedTableNames, table.String())
// mark any table referring to the table as potential candidates
// for being created now
for otherTable, otherReferencedTables := range tableReferences {
if _, found := otherReferencedTables[table]; found {
delete(otherReferencedTables, table)
if len(otherReferencedTables) == 0 {
logger.Debugf("creation of %s unblocked creation of %s", table, otherTable)
}
}
}
delete(tableReferences, table)
createdTable = true
}
if !createdTable {
tableNames := make([]QualifiedTableName, 0, len(tableReferences))
for tableName := range tableReferences {
tableNames = append(tableNames, tableName)
}
err = fmt.Errorf("failed creating tables: all %d remaining tables have foreign references: %v", len(tableReferences), tableNames)
return
}
}
return
}
func showDatabases(c *sql.DB) ([]string, error) {
rows, err := c.Query("show databases")
if err != nil {
return []string{}, err
}
defer rows.Close()
databases := make([]string, 0)
for rows.Next() {
var database string
err = rows.Scan(&database)
if err != nil {
return databases, err
}
if _, ignored := ignoredDatabases[database]; ignored {
continue
}
databases = append(databases, database)
}
return databases, nil
}
func | 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 NonExistingPaginationKeyColumnError(schema, table, paginationKey string) error {
return fmt.Errorf("Pagination Key `%s` for %s non existent", paginationKey, QuotedTableNameFromString(schema, table))
}
// NonExistingPaginationKeyError exported to facilitate black box testing
func NonExistingPaginationKeyError(schema, table string) error {
return fmt.Errorf("%s has no Primary Key to default to for Pagination purposes. Kindly specify a Pagination Key for this table in the CascadingPaginationColumnConfig", QuotedTableNameFromString(schema, table))
}
// UnsupportedPaginationKeyError exported to facilitate black box testing
func UnsupportedPaginationKeyError(schema, table, paginationKey string) error {
return fmt.Errorf("Pagination Key `%s` for %s is non-numeric/-text", paginationKey, QuotedTableNameFromString(schema, table))
}
func (t *TableSchema) paginationKey(cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (*PaginationKey, error) {
var err error
paginationKeyColumns := make([]*schema.TableColumn, 0)
paginationKeyColumnIndices := make([]int, 0)
if paginationColumn, found := cascadingPaginationColumnConfig.PaginationColumnFor(t.Schema, t.Name); found {
// Use per-schema, per-table pagination key from config
var paginationKeyColumn *schema.TableColumn
var paginationKeyIndex int
paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(paginationColumn)
if err == nil {
paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn)
paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex)
}
} else if len(t.PKColumns) > 0 {
// Use Primary Key
//
// NOTE: A primary key has to be unique, but it may contain columns that
// are not needed for uniqueness. The ideal pagination key has length of
// 1, so we explicitly check if a subset of keys is sufficient.
// We could also do this checking for a uniqueness contstraint in the
// future
for i, column := range t.Columns {
if column.IsAuto {
paginationKeyColumns = append(paginationKeyColumns, &column)
paginationKeyColumnIndices = append(paginationKeyColumnIndices, i)
break
}
}
// if we failed finding an auto-increment, build a composite key
if len(paginationKeyColumns) == 0 {
for _, paginationKeyIndex := range t.PKColumns {
paginationKeyColumns = append(paginationKeyColumns, &t.Columns[paginationKeyIndex])
paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex)
}
}
} else if fallbackColumnName, found := cascadingPaginationColumnConfig.FallbackPaginationColumnName(); found {
// Try fallback from config
var paginationKeyColumn *schema.TableColumn
var paginationKeyIndex int
paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(fallbackColumnName)
if err == nil {
paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn)
paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex)
}
} else {
// No usable pagination key found
err = NonExistingPaginationKeyError(t.Schema, t.Name)
}
if err != nil || len(paginationKeyColumns) == 0 {
if err == nil {
panic(fmt.Errorf("no pagination key found, but no error set either"))
}
return nil, err
}
for _, column := range paginationKeyColumns {
switch column.Type {
case schema.TYPE_NUMBER, schema.TYPE_STRING, schema.TYPE_VARBINARY, schema.TYPE_BINARY:
default:
return nil, UnsupportedPaginationKeyError(t.Schema, t.Name, column.Name)
}
}
paginationKey := &PaginationKey{
Columns: paginationKeyColumns,
ColumnIndices: paginationKeyColumnIndices,
}
return paginationKey, err
}
func (c TableSchemaCache) AsSlice() (tables []*TableSchema) {
for _, tableSchema := range c {
tables = append(tables, tableSchema)
}
return
}
func (c TableSchemaCache) AllTableNames() (tableNames []string) {
for tableName, _ := range c {
tableNames = append(tableNames, tableName)
}
return
}
func (c TableSchemaCache) Get(database, table string) *TableSchema {
return c[fullTableName(database, table)]
}
// Helper to sort a given map of tables with a second list giving a priority.
// If an element is present in the input and the priority lists, the item will
// appear first (in the order of the priority list), all other items appear in
// the order given in the input
func (c TableSchemaCache) GetTableListWithPriority(priorityList []string) (prioritzedTableNames []string) {
// just a fast lookup if the list contains items already
contains := map[string]struct{}{}
if len(priorityList) >= 0 {
for _, tableName := range priorityList {
// ignore tables given in the priority list that we don't know
if _, found := c[tableName]; found {
contains[tableName] = struct{}{}
prioritzedTableNames = append(prioritzedTableNames, tableName)
}
}
}
for tableName, _ := range c {
if _, found := contains[tableName]; !found {
prioritzedTableNames = append(prioritzedTableNames, tableName)
}
}
return
}
// Helper to sort the given map of tables based on the dependencies between
// tables in terms of foreign key constraints
func (c TableSchemaCache) GetTableCreationOrder(db *sql.DB) (prioritzedTableNames []string, err error) {
logger := logrus.WithField("tag", "table_schema_cache")
tableReferences := make(map[QualifiedTableName]TableForeignKeys)
for tableName, _ := range c {
t := strings.Split(tableName, ".")
table := NewQualifiedTableName(t[0], t[1])
// ignore self-references, as they are not really foreign keys
referencedTables, dbErr := GetForeignKeyTablesOfTable(db, table, false)
if dbErr != nil {
logger.WithField("table", table).Error("cannot analyze database table foreign keys")
err = dbErr
return
}
logger.Debugf("found %d reference tables for %s", len(referencedTables), table)
tableReferences[table] = referencedTables
}
// simple fix-point loop: make sure we create at least one table per
// iteration and mark tables as able to create as soon as they no-longer
// refer to other tables
for len(tableReferences) > 0 {
createdTable := false
for table, referencedTables := range tableReferences {
if len(referencedTables) > 0 {
continue
}
logger.Debugf("queuing %s", table)
prioritzedTableNames = append(prioritzedTableNames, table.String())
// mark any table referring to the table as potential candidates
// for being created now
for otherTable, otherReferencedTables := range tableReferences {
if _, found := otherReferencedTables[table]; found {
delete(otherReferencedTables, table)
if len(otherReferencedTables) == 0 {
logger.Debugf("creation of %s unblocked creation of %s", table, otherTable)
}
}
}
delete(tableReferences, table)
createdTable = true
}
if !createdTable {
tableNames := make([]QualifiedTableName, 0, len(tableReferences))
for tableName := range tableReferences {
tableNames = append(tableNames, tableName)
}
err = fmt.Errorf("failed creating tables: all %d remaining tables have foreign references: %v", len(tableReferences), tableNames)
return
}
}
return
}
func showDatabases(c *sql.DB) ([]string, error) {
rows, err := c.Query("show databases")
if err != nil {
return []string{}, err
}
defer rows.Close()
databases := make([]string, 0)
for rows.Next() {
var database string
err = rows.Scan(&database)
if err != nil {
return databases, err
}
if _, ignored := ignoredDatabases[database]; ignored {
continue
}
databases = append(databases, database)
}
return databases, nil
}
func showTablesFrom(c *sql.DB, dbname string) ([]string, error) {
rows, err := c.Query(fmt.Sprintf("show tables from %s", quoteField(dbname)))
if err != nil {
return []string{}, err
}
defer rows.Close()
tables := make([]string, 0)
for rows.Next() {
var table string
err = rows.Scan(&table)
if err != nil | {
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, ","),
QuotedTableNameFromString(schemaName, tableName),
columnsToSelect[0],
strings.Repeat("?,", numRows-1)+"?",
), 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.IgnoredColumnsForVerification[column.Name]
if isCompressed || isIgnored {
continue
}
columns = append(columns, column)
}
hashStrs := make([]string, len(columns))
for i, column := range columns {
// Magic string that's unlikely to be a real record. For a history of this
// issue, refer to https://github.com/Shopify/ghostferry/pull/137
hashStrs[i] = fmt.Sprintf("MD5(COALESCE(%s, 'NULL_PBj}b]74P@JTo$5G_null'))", normalizeAndQuoteColumn(column))
}
t.rowMd5Query = fmt.Sprintf("MD5(CONCAT(%s)) AS __ghostferry_row_md5", strings.Join(hashStrs, ","))
return t.rowMd5Query
}
type TableSchemaCache map[string]*TableSchema
func fullTableName(schemaName, tableName string) string {
return fmt.Sprintf("%s.%s", schemaName, tableName)
}
func QuotedDatabaseNameFromString(database string) string {
return fmt.Sprintf("`%s`", database)
}
func QuotedTableName(table *TableSchema) string {
return QuotedTableNameFromString(table.Schema, table.Name)
}
func QuotedTableNameFromString(database, table string) string {
return fmt.Sprintf("`%s`.`%s`", database, table)
}
func GetTargetPaginationKeys(db *sql.DB, tables []*TableSchema, iterateInDescendingOrder bool, logger *logrus.Entry) (paginatedTables map[*TableSchema]*PaginationKeyData, unpaginatedTables []*TableSchema, err error) {
paginatedTables = make(map[*TableSchema]*PaginationKeyData)
unpaginatedTables = make([]*TableSchema, 0, len(tables))
for _, table := range tables {
logger := logger.WithField("table", table.String())
isEmpty, dbErr := isEmptyTable(db, table)
if dbErr != nil {
err = dbErr
return
}
// NOTE: We treat empty tables just like any other non-paginated table
// to make sure they are marked as completed in the state-tracker (if
// they are not already)
if isEmpty || table.PaginationKey == nil {
logger.Debugf("tracking as unpaginated table (empty: %v)", isEmpty)
unpaginatedTables = append(unpaginatedTables, table)
continue
}
targetPaginationKey, targetPaginationKeyExists, paginationErr := targetPaginationKey(db, table, iterateInDescendingOrder)
if paginationErr != nil {
logger.WithError(paginationErr).Errorf("failed to get target primary key %s", table.PaginationKey)
err = paginationErr
return |
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)
paginatedTables[table] = targetPaginationKey
}
return
}
func LoadTables(db *sql.DB, tableFilter TableFilter, columnCompressionConfig ColumnCompressionConfig, columnIgnoreConfig ColumnIgnoreConfig, cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (TableSchemaCache, error) {
logger := logrus.WithField("tag", "table_schema_cache")
tableSchemaCache := make(TableSchemaCache)
dbnames, err := showDatabases(db)
if err != nil {
logger.WithError(err).Error("failed to show databases")
return tableSchemaCache, err
}
dbnames, err = tableFilter.ApplicableDatabases(dbnames)
if err != nil {
logger.WithError(err).Error("could not apply database filter")
return tableSchemaCache, err
}
// For each database, get a list of tables from it and cache the table's schema
for _, dbname := range dbnames {
dbLog := logger.WithField("database", dbname)
dbLog.Debug("loading tables from database")
tableNames, err := showTablesFrom(db, dbname)
if err != nil {
dbLog.WithError(err).Error("failed to show tables")
return tableSchemaCache, err
}
var tableSchemas []*TableSchema
for _, table := range tableNames {
tableLog := dbLog.WithField("table", table)
tableLog.Debug("fetching table schema")
tableSchema, err := schema.NewTableFromSqlDB(db.DB, dbname, table)
if err != nil {
tableLog.WithError(err).Error("cannot fetch table schema from source db")
return tableSchemaCache, err
}
tableSchemas = append(tableSchemas, &TableSchema{
Table: tableSchema,
CompressedColumnsForVerification: columnCompressionConfig.CompressedColumnsFor(dbname, table),
IgnoredColumnsForVerification: columnIgnoreConfig.IgnoredColumnsFor(dbname, table),
})
}
tableSchemas, err = tableFilter.ApplicableTables(tableSchemas)
if err != nil {
return tableSchemaCache, nil
}
for _, tableSchema := range tableSchemas {
tableName := tableSchema.Name
tableLog := dbLog.WithField("table", tableName)
tableLog.Debug("caching table schema")
if cascadingPaginationColumnConfig.IsFullCopyTable(tableSchema.Schema, tableName) {
tableLog.Debug("table is marked for full-table copy")
} else {
tableLog.Debug("loading table schema pagination keys")
paginationKey, err := tableSchema.paginationKey(cascadingPaginationColumnConfig)
if err != nil {
tableLog.WithError(err).Error("invalid table")
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 tableSchemaCache, nil
}
func (t *TableSchema) findColumnByName(name string) (*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 NonExistingPaginationKeyColumnError(schema, table, paginationKey string) error {
return fmt.Errorf("Pagination Key `%s` for %s non existent", paginationKey, QuotedTableNameFromString(schema, table))
}
// NonExistingPaginationKeyError exported to facilitate black box testing
func NonExistingPaginationKeyError(schema, table string) error {
return fmt.Errorf("%s has no Primary Key to default to for Pagination purposes. Kindly specify a Pagination Key for this table in the CascadingPaginationColumnConfig", QuotedTableNameFromString(schema, table))
}
// UnsupportedPaginationKeyError exported to facilitate black box testing
func UnsupportedPaginationKeyError(schema, table, paginationKey string) error {
return fmt.Errorf("Pagination Key `%s` for %s is non-numeric/-text", paginationKey, QuotedTableNameFromString(schema, table))
}
func (t *TableSchema) paginationKey(cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (*PaginationKey, error) {
var err error
paginationKeyColumns := make([]*schema.TableColumn, 0)
paginationKeyColumnIndices := make([]int, 0)
if paginationColumn, found := cascadingPaginationColumnConfig.PaginationColumnFor(t.Schema, t.Name); found {
// Use per-schema, per-table pagination key from config
var paginationKeyColumn *schema.TableColumn
var paginationKeyIndex int
paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(paginationColumn)
if err == nil {
paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn)
paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex)
}
} else if len(t.PKColumns) > 0 {
// Use Primary Key
//
// NOTE: A primary key has to be unique, but it may contain columns that
// are not needed for uniqueness. The ideal pagination key has length of
| } | 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.IgnoredColumnsForVerification[column.Name]
if isCompressed || isIgnored {
continue
}
columns = append(columns, column)
}
hashStrs := make([]string, len(columns))
for i, column := range columns {
// Magic string that's unlikely to be a real record. For a history of this
// issue, refer to https://github.com/Shopify/ghostferry/pull/137
hashStrs[i] = fmt.Sprintf("MD5(COALESCE(%s, 'NULL_PBj}b]74P@JTo$5G_null'))", normalizeAndQuoteColumn(column))
}
t.rowMd5Query = fmt.Sprintf("MD5(CONCAT(%s)) AS __ghostferry_row_md5", strings.Join(hashStrs, ","))
return t.rowMd5Query
}
type TableSchemaCache map[string]*TableSchema
func fullTableName(schemaName, tableName string) string {
return fmt.Sprintf("%s.%s", schemaName, tableName)
}
func QuotedDatabaseNameFromString(database string) string {
return fmt.Sprintf("`%s`", database)
}
func QuotedTableName(table *TableSchema) string {
return QuotedTableNameFromString(table.Schema, table.Name)
}
func QuotedTableNameFromString(database, table string) string {
return fmt.Sprintf("`%s`.`%s`", database, table)
}
func GetTargetPaginationKeys(db *sql.DB, tables []*TableSchema, iterateInDescendingOrder bool, logger *logrus.Entry) (paginatedTables map[*TableSchema]*PaginationKeyData, unpaginatedTables []*TableSchema, err error) {
paginatedTables = make(map[*TableSchema]*PaginationKeyData)
unpaginatedTables = make([]*TableSchema, 0, len(tables))
for _, table := range tables {
logger := logger.WithField("table", table.String())
isEmpty, dbErr := isEmptyTable(db, table)
if dbErr != nil {
err = dbErr
return
}
// NOTE: We treat empty tables just like any other non-paginated table
// to make sure they are marked as completed in the state-tracker (if
// they are not already)
if isEmpty || table.PaginationKey == nil {
logger.Debugf("tracking as unpaginated table (empty: %v)", isEmpty)
unpaginatedTables = append(unpaginatedTables, table)
continue
}
targetPaginationKey, targetPaginationKeyExists, paginationErr := targetPaginationKey(db, table, iterateInDescendingOrder)
if paginationErr != nil {
logger.WithError(paginationErr).Errorf("failed to get target primary key %s", table.PaginationKey)
err = paginationErr
return
}
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)
paginatedTables[table] = targetPaginationKey
}
return
}
func LoadTables(db *sql.DB, tableFilter TableFilter, columnCompressionConfig ColumnCompressionConfig, columnIgnoreConfig ColumnIgnoreConfig, cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (TableSchemaCache, error) {
logger := logrus.WithField("tag", "table_schema_cache")
tableSchemaCache := make(TableSchemaCache)
dbnames, err := showDatabases(db)
if err != nil {
logger.WithError(err).Error("failed to show databases")
return tableSchemaCache, err
}
dbnames, err = tableFilter.ApplicableDatabases(dbnames)
if err != nil {
logger.WithError(err).Error("could not apply database filter")
return tableSchemaCache, err
}
// For each database, get a list of tables from it and cache the table's schema
for _, dbname := range dbnames {
dbLog := logger.WithField("database", dbname)
dbLog.Debug("loading tables from database")
tableNames, err := showTablesFrom(db, dbname)
if err != nil {
dbLog.WithError(err).Error("failed to show tables")
return tableSchemaCache, err
}
var tableSchemas []*TableSchema
for _, table := range tableNames {
tableLog := dbLog.WithField("table", table)
tableLog.Debug("fetching table schema")
tableSchema, err := schema.NewTableFromSqlDB(db.DB, dbname, table)
if err != nil {
tableLog.WithError(err).Error("cannot fetch table schema from source db")
return tableSchemaCache, err
}
tableSchemas = append(tableSchemas, &TableSchema{
Table: tableSchema,
CompressedColumnsForVerification: columnCompressionConfig.CompressedColumnsFor(dbname, table),
IgnoredColumnsForVerification: columnIgnoreConfig.IgnoredColumnsFor(dbname, table),
})
}
tableSchemas, err = tableFilter.ApplicableTables(tableSchemas)
if err != nil {
return tableSchemaCache, nil
}
for _, tableSchema := range tableSchemas {
tableName := tableSchema.Name
tableLog := dbLog.WithField("table", tableName)
tableLog.Debug("caching table schema")
if cascadingPaginationColumnConfig.IsFullCopyTable(tableSchema.Schema, tableName) {
tableLog.Debug("table is marked for full-table copy")
} else {
tableLog.Debug("loading table schema pagination keys")
paginationKey, err := tableSchema.paginationKey(cascadingPaginationColumnConfig)
if err != nil {
tableLog.WithError(err).Error("invalid table")
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 tableSchemaCache, nil
}
func (t *TableSchema) findColumnByName(name string) (*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 NonExistingPaginationKeyColumnError(schema, table, paginationKey string) error {
return fmt.Errorf("Pagination Key `%s` for %s non existent", paginationKey, QuotedTableNameFromString(schema, table))
}
// NonExistingPaginationKeyError exported to facilitate black box testing
func NonExistingPaginationKeyError(schema, table string) error {
return fmt.Errorf("%s has no Primary Key to default to for Pagination purposes. Kindly specify a Pagination Key for this table in the CascadingPaginationColumnConfig", QuotedTableNameFromString(schema, table))
}
// UnsupportedPaginationKeyError exported to facilitate black box testing
func UnsupportedPaginationKeyError(schema, table, paginationKey string) error {
return fmt.Errorf("Pagination Key `%s` for %s is non-numeric/-text", paginationKey, QuotedTableNameFromString(schema, table))
}
func (t *TableSchema) paginationKey(cascadingPaginationColumnConfig *CascadingPaginationColumnConfig) (*PaginationKey, error) {
var err error
paginationKeyColumns := make([]*schema.TableColumn, 0)
paginationKeyColumnIndices := make([]int, 0)
if paginationColumn, found := cascadingPaginationColumnConfig.PaginationColumnFor(t.Schema, t.Name); found {
// Use per-schema, per-table pagination key from config
var paginationKeyColumn *schema.TableColumn
var paginationKeyIndex int
paginationKeyColumn, paginationKeyIndex, err = t.findColumnByName(paginationColumn)
if err == nil {
paginationKeyColumns = append(paginationKeyColumns, paginationKeyColumn)
paginationKeyColumnIndices = append(paginationKeyColumnIndices, paginationKeyIndex)
}
} else if len | {
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()
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, ","),
QuotedTableNameFromString(schemaName, tableName),
columnsToSelect[0],
strings.Repeat("?,", numRows-1)+"?", | 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 action on the VM.
pub actions_fails: SharedMetric,
/// Number of PUTs for attaching source of boot.
pub boot_source_count: SharedMetric,
/// Number of failures during attaching source of boot.
pub boot_source_fails: SharedMetric,
/// Number of PUTs triggering a block attach.
pub drive_count: SharedMetric,
/// Number of failures in attaching a block device.
pub drive_fails: SharedMetric,
/// Number of PUTs for initializing the logging system.
pub logger_count: SharedMetric,
/// Number of failures in initializing the logging system.
pub logger_fails: SharedMetric,
/// Number of PUTs for configuring the machine.
pub machine_cfg_count: SharedMetric,
/// Number of failures in configuring the machine.
pub machine_cfg_fails: SharedMetric,
/// Number of PUTs for creating a new network interface.
pub network_count: SharedMetric,
/// Number of failures in creating a new network interface.
pub network_fails: SharedMetric,
}
/// Metrics specific to PATCH API Requests for counting user triggered actions and/or failures.
#[derive(Default, Serialize)]
pub struct PatchRequestsMetrics {
/// Number of tries to PATCH a block device.
pub drive_count: SharedMetric,
/// Number of failures in PATCHing a block device.
pub drive_fails: SharedMetric,
}
/// Block Device associated metrics.
#[derive(Default, Serialize)]
pub struct BlockDeviceMetrics {
/// Number of times when activate failed on a block device.
pub activate_fails: SharedMetric,
/// Number of times when interacting with the space config of a block device failed.
pub cfg_fails: SharedMetric,
/// Number of times when handling events on a block device failed.
pub event_fails: SharedMetric,
/// Number of failures in executing a request on a block device.
pub execute_fails: SharedMetric,
/// Number of invalid requests received for this block device.
pub invalid_reqs_count: SharedMetric,
/// Number of flushes operation triggered on this block device.
pub flush_count: SharedMetric,
/// Number of events triggerd on the queue of this block device.
pub queue_event_count: SharedMetric,
/// Number of events ratelimiter-related.
pub rate_limiter_event_count: SharedMetric,
/// Number of update operation triggered on this block device.
pub update_count: SharedMetric,
/// Number of failures while doing update on this block device.
pub update_fails: SharedMetric,
/// Number of bytes read by this block device.
pub read_count: SharedMetric,
/// Number of bytes written by this block device.
pub write_count: SharedMetric,
}
/// Metrics specific to the i8042 device.
#[derive(Default, Serialize)]
pub struct I8042DeviceMetrics {
/// 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 read by this device.
pub read_count: SharedMetric,
/// Number of resets done by this device.
pub reset_count: SharedMetric,
/// Bytes written by this device.
pub write_count: SharedMetric,
}
/// Metrics for the logging subsystem.
#[derive(Default, Serialize)]
pub struct LoggerSystemMetrics {
/// Number of misses on flushing metrics.
pub missed_metrics_count: SharedMetric,
/// Number of errors during metrics handling.
pub metrics_fails: SharedMetric,
/// Number of misses on logging human readable content.
pub missed_log_count: SharedMetric,
/// Number of errors while trying to log human readable content.
pub log_fails: SharedMetric,
}
/// Metrics for the MMDS functionality.
#[derive(Default, Serialize)]
pub struct MmdsMetrics {
/// Number of frames rerouted to MMDS.
pub rx_accepted: SharedMetric,
/// Number of errors while handling a frame through MMDS.
pub rx_accepted_err: SharedMetric,
/// Number of uncommon events encountered while processing packets through MMDS.
pub rx_accepted_unusual: SharedMetric,
/// The number of buffers which couldn't be parsed as valid Ethernet frames by the MMDS.
pub rx_bad_eth: SharedMetric,
/// The total number of bytes sent by the MMDS.
pub tx_bytes: SharedMetric,
/// The number of errors raised by the MMDS while attempting to send frames/packets/segments.
pub tx_errors: SharedMetric,
/// The number of frames sent by the MMDS.
pub tx_frames: SharedMetric,
/// The number of connections successfully accepted by the MMDS TCP handler.
pub connections_created: SharedMetric,
/// The number of connections cleaned up by the MMDS TCP handler.
pub connections_destroyed: SharedMetric,
}
/// Network-related metrics.
#[derive(Default, Serialize)]
pub struct NetDeviceMetrics {
/// Number of times when activate failed on a network device.
pub activate_fails: SharedMetric,
/// Number of times when interacting with the space config of a network device failed.
pub cfg_fails: SharedMetric,
/// Number of times when handling events on a network device failed.
pub event_fails: SharedMetric,
/// Number of events associated with the receiving queue.
pub rx_queue_event_count: SharedMetric,
/// Number of events associated with the rate limiter installed on the receiving path.
pub rx_event_rate_limiter_count: SharedMetric,
/// Number of events received on the associated tap.
pub rx_tap_event_count: SharedMetric,
/// Number of bytes received.
pub rx_bytes_count: SharedMetric,
/// Number of packets received.
pub rx_packets_count: SharedMetric,
/// Number of errors while receiving data.
pub rx_fails: SharedMetric,
/// Number of transmitted bytes.
pub tx_bytes_count: SharedMetric,
/// Number of errors while transmitting data.
pub tx_fails: SharedMetric,
/// Number of transmitted packets.
pub tx_packets_count: SharedMetric,
/// Number of events associated with the transmitting queue.
pub tx_queue_event_count: SharedMetric,
/// Number of events associated with the rate limiter installed on the transmitting path.
pub tx_rate_limiter_event_count: SharedMetric,
}
/// Metrics for the seccomp filtering.
#[derive(Serialize)]
pub struct SeccompMetrics {
/// Number of black listed syscalls.
pub bad_syscalls: Vec<SharedMetric>,
/// Number of errors inside the seccomp filtering.
pub num_faults: SharedMetric,
}
impl Default for SeccompMetrics {
fn default() -> SeccompMetrics {
let mut def_syscalls = vec![];
for _syscall in 0..SYSCALL_MAX {
def_syscalls.push(SharedMetric::default());
}
SeccompMetrics {
num_faults: SharedMetric::default(),
bad_syscalls: def_syscalls,
}
}
}
/// Metrics specific to the UART device.
#[derive(Default, Serialize)]
pub struct SerialDeviceMetrics {
/// Errors triggered while using the UART device.
pub error_count: SharedMetric,
/// Number of flush operations.
pub flush_count: SharedMetric,
/// Number of read calls that did not trigger a read.
pub missed_read_count: SharedMetric,
/// Number of write calls that did not trigger a write.
pub missed_write_count: SharedMetric,
/// Number of succeeded read calls.
pub read_count: SharedMetric,
/// Number of succeeded write calls.
pub write_count: SharedMetric,
}
/// Metrics specific to VCPUs' mode of functioning.
#[derive(Default, Serialize)]
pub struct VcpuMetrics {
/// Number of KVM exits for handling input IO.
pub exit_io_in: SharedMetric,
/// Number of KVM exits for handling output IO.
pub exit_io_out: SharedMetric,
/// Number of KVM exits for handling MMIO reads.
pub exit_mmio_read: SharedMetric,
/// Number of KVM exits for handling MMIO writes.
pub exit_mmio_write: SharedMetric,
/// Number of errors during this VCPU's run.
pub failures: SharedMetric,
/// Failures in configuring the CPUID.
pub fitler_cpuid: SharedMetric,
}
/// Metrics specific to the machine manager as a whole.
#[derive(Default, Serialize)]
pub struct VmmMetrics {
/// Number of device related events received for a VM.
pub device_events: SharedMetric,
/// Metric for signaling a panic has occurred.
pub panic_count: SharedMetric,
}
/// Memory usage metrics.
#[derive(Default, Serialize)]
pub struct MemoryMetrics {
/// Number of pages dirtied since the last call to `KVM_GET_DIRTY_LOG`.
pub dirty_pages: SharedMetric,
}
// The sole purpose of this struct is to produce an UTC timestamp when an instance is serialized.
#[derive(Default)]
struct SerializeToUtcTimestampMs;
impl Serialize for SerializeToUtcTimestampMs {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> | {
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 read by this device.
pub read_count: SharedMetric,
/// Number of resets done by this device.
pub reset_count: SharedMetric,
/// Bytes written by this device.
pub write_count: SharedMetric,
}
/// Metrics for the logging subsystem.
#[derive(Default, Serialize)]
pub struct LoggerSystemMetrics {
/// Number of misses on flushing metrics.
pub missed_metrics_count: SharedMetric,
/// Number of errors during metrics handling.
pub metrics_fails: SharedMetric,
/// Number of misses on logging human readable content.
pub missed_log_count: SharedMetric,
/// Number of errors while trying to log human readable content.
pub log_fails: SharedMetric,
}
/// Metrics for the MMDS functionality.
#[derive(Default, Serialize)]
pub struct MmdsMetrics {
/// Number of frames rerouted to MMDS.
pub rx_accepted: SharedMetric,
/// Number of errors while handling a frame through MMDS.
pub rx_accepted_err: SharedMetric,
/// Number of uncommon events encountered while processing packets through MMDS.
pub rx_accepted_unusual: SharedMetric,
/// The number of buffers which couldn't be parsed as valid Ethernet frames by the MMDS.
pub rx_bad_eth: SharedMetric,
/// The total number of bytes sent by the MMDS.
pub tx_bytes: SharedMetric,
/// The number of errors raised by the MMDS while attempting to send frames/packets/segments.
pub tx_errors: SharedMetric,
/// The number of frames sent by the MMDS.
pub tx_frames: SharedMetric,
/// The number of connections successfully accepted by the MMDS TCP handler.
pub connections_created: SharedMetric,
/// The number of connections cleaned up by the MMDS TCP handler.
pub connections_destroyed: SharedMetric,
}
/// Network-related metrics.
#[derive(Default, Serialize)]
pub struct NetDeviceMetrics {
/// Number of times when activate failed on a network device.
pub activate_fails: SharedMetric,
/// Number of times when interacting with the space config of a network device failed.
pub cfg_fails: SharedMetric,
/// Number of times when handling events on a network device failed.
pub event_fails: SharedMetric,
/// Number of events associated with the receiving queue.
pub rx_queue_event_count: SharedMetric,
/// Number of events associated with the rate limiter installed on the receiving path.
pub rx_event_rate_limiter_count: SharedMetric,
/// Number of events received on the associated tap.
pub rx_tap_event_count: SharedMetric,
/// Number of bytes received.
pub rx_bytes_count: SharedMetric,
/// Number of packets received.
pub rx_packets_count: SharedMetric,
/// Number of errors while receiving data.
pub rx_fails: SharedMetric,
/// Number of transmitted bytes.
pub tx_bytes_count: SharedMetric,
/// Number of errors while transmitting data.
pub tx_fails: SharedMetric,
/// Number of transmitted packets.
pub tx_packets_count: SharedMetric,
/// Number of events associated with the transmitting queue.
pub tx_queue_event_count: SharedMetric,
/// Number of events associated with the rate limiter installed on the transmitting path.
pub tx_rate_limiter_event_count: SharedMetric,
}
/// Metrics for the seccomp filtering.
#[derive(Serialize)]
pub struct SeccompMetrics {
/// Number of black listed syscalls.
pub bad_syscalls: Vec<SharedMetric>,
/// Number of errors inside the seccomp filtering.
pub num_faults: SharedMetric,
}
impl Default for SeccompMetrics {
fn default() -> SeccompMetrics {
let mut def_syscalls = vec![];
for _syscall in 0..SYSCALL_MAX {
def_syscalls.push(SharedMetric::default());
}
SeccompMetrics {
num_faults: SharedMetric::default(),
bad_syscalls: def_syscalls,
}
}
}
/// Metrics specific to the UART device.
#[derive(Default, Serialize)]
pub struct SerialDeviceMetrics {
/// Errors triggered while using the UART device.
pub error_count: SharedMetric,
/// Number of flush operations.
pub flush_count: SharedMetric,
/// Number of read calls that did not trigger a read.
pub missed_read_count: SharedMetric,
/// Number of write calls that did not trigger a write.
pub missed_write_count: SharedMetric,
/// Number of succeeded read calls.
pub read_count: SharedMetric,
/// Number of succeeded write calls.
pub write_count: SharedMetric,
}
/// Metrics specific to VCPUs' mode of functioning.
#[derive(Default, Serialize)]
pub struct VcpuMetrics {
/// Number of KVM exits for handling input IO.
pub exit_io_in: SharedMetric,
/// Number of KVM exits for handling output IO.
pub exit_io_out: SharedMetric,
/// Number of KVM exits for handling MMIO reads.
pub exit_mmio_read: SharedMetric,
/// Number of KVM exits for handling MMIO writes.
pub exit_mmio_write: SharedMetric,
/// Number of errors during this VCPU's run.
pub failures: SharedMetric,
/// Failures in configuring the CPUID.
pub fitler_cpuid: SharedMetric,
}
/// Metrics specific to the machine manager as a whole.
#[derive(Default, Serialize)]
pub struct VmmMetrics {
/// Number of device related events received for a VM.
pub device_events: SharedMetric,
/// Metric for signaling a panic has occurred.
pub panic_count: SharedMetric,
}
/// Memory usage metrics.
#[derive(Default, Serialize)]
pub struct MemoryMetrics {
/// Number of pages dirtied since the last call to `KVM_GET_DIRTY_LOG`.
pub dirty_pages: SharedMetric,
}
// The sole purpose of this struct is to produce an UTC timestamp when an instance is serialized.
#[derive(Default)]
struct SerializeToUtcTimestampMs;
impl Serialize for SerializeToUtcTimestampMs {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_i64(chrono::Utc::now().timestamp_millis())
}
}
/// Structure storing all metrics while enforcing serialization support on them.
#[derive(Default, Serialize)]
pub struct FirecrackerMetrics {
utc_timestamp_ms: SerializeToUtcTimestampMs,
/// API Server related metrics.
pub api_server: ApiServerMetrics,
/// A block device's related metrics.
pub block: BlockDeviceMetrics,
/// Metrics related to API GET requests.
pub get_api_requests: GetRequestsMetrics,
/// Metrics relaetd to the i8042 device.
pub i8042: I8042DeviceMetrics,
/// Logging related metrics.
pub logger: LoggerSystemMetrics,
/// Metrics specific to MMDS functionality.
pub mmds: MmdsMetrics,
/// A network device's related metrics.
pub net: NetDeviceMetrics,
/// Metrics related to API PATCH requests.
pub patch_api_requests: PatchRequestsMetrics,
/// Metrics related to API PUT requests.
pub put_api_requests: PutRequestsMetrics,
/// Metrics related to seccomp filtering.
pub seccomp: SeccompMetrics,
/// Metrics related to a vcpu's functioning.
pub vcpu: VcpuMetrics,
/// Metrics related to the virtual machine manager.
pub vmm: VmmMetrics,
/// Metrics related to the UART device.
pub uart: SerialDeviceMetrics,
/// Memory usage metrics.
pub memory: MemoryMetrics,
}
lazy_static! {
/// Static instance used for handling metrics.
///
pub static ref METRICS: FirecrackerMetrics = FirecrackerMetrics::default();
}
#[cfg(test)]
mod tests {
extern crate serde_json;
use super::*;
use std::sync::Arc;
use std::thread;
#[test]
fn test_metric() {
let m1 = SimpleMetric::default();
m1.inc();
m1.inc();
m1.add(5);
m1.inc();
assert_eq!(m1.count(), 8);
let m2 = Arc::new(SharedMetric::default());
// We're going to create a number of threads that will attempt to increase this metric
// in parallel. If everything goes fine we still can't be sure the synchronization works,
// but it something fails, then we definitely have a problem :-s
const NUM_THREADS_TO_SPAWN: usize = 4;
const NUM_INCREMENTS_PER_THREAD: usize = 100000;
const M2_INITIAL_COUNT: usize = 123;
m2.add(M2_INITIAL_COUNT);
let mut v = Vec::with_capacity(NUM_THREADS_TO_SPAWN);
for _ in 0..NUM_THREADS_TO_SPAWN {
let r = m2.clone();
v.push(thread::spawn(move || {
for _ in 0..NUM_INCREMENTS_PER_THREAD {
r.inc();
}
}));
}
for handle in v {
handle.join().unwrap();
}
assert_eq!(
m2.count(), | 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) -> usize {
self.0.load(Ordering::Relaxed)
}
}
impl Serialize for SharedMetric {
/// Reset counters of each metrics. Here we suppose that Serialize's goal is to help with the
/// flushing of metrics.
/// !!! Any print of the metrics will also reset them. Use with caution !!!
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
// There's no serializer.serialize_usize() for some reason :(
let snapshot = self.0.load(Ordering::Relaxed);
let res = serializer.serialize_u64(snapshot as u64 - self.1.load(Ordering::Relaxed) as u64);
if res.is_ok() {
self.1.store(snapshot, Ordering::Relaxed);
}
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.
/// Metrics related to the internal API server.
#[derive(Default, Serialize)]
pub struct ApiServerMetrics {
/// Measures the process's startup time in microseconds.
pub process_startup_time_us: SharedMetric,
/// Measures the cpu's startup time in microseconds.
pub process_startup_time_cpu_us: SharedMetric,
/// Number of failures on API requests triggered by internal errors.
pub sync_outcome_fails: SharedMetric,
/// Number of timeouts during communication with the VMM.
pub sync_vmm_send_timeout_count: SharedMetric,
}
/// Metrics specific to GET API Requests for counting user triggered actions and/or failures.
#[derive(Default, Serialize)]
pub struct GetRequestsMetrics {
/// Number of GETs for getting information on the instance.
pub instance_info_count: SharedMetric,
/// Number of failures when obtaining information on the current instance.
pub instance_info_fails: SharedMetric,
/// Number of GETs for getting status on attaching machine configuration.
pub machine_cfg_count: SharedMetric,
/// Number of failures during GETs for getting information on the instance.
pub machine_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 action on the VM.
pub actions_fails: SharedMetric,
/// Number of PUTs for attaching source of boot.
pub boot_source_count: SharedMetric,
/// Number of failures during attaching source of boot.
pub boot_source_fails: SharedMetric,
/// Number of PUTs triggering a block attach.
pub drive_count: SharedMetric,
/// Number of failures in attaching a block device.
pub drive_fails: SharedMetric,
/// Number of PUTs for initializing the logging system.
pub logger_count: SharedMetric,
/// Number of failures in initializing the logging system.
pub logger_fails: SharedMetric,
/// Number of PUTs for configuring the machine.
pub machine_cfg_count: SharedMetric,
/// Number of failures in configuring the machine.
pub machine_cfg_fails: SharedMetric,
/// Number of PUTs for creating a new network interface.
pub network_count: SharedMetric,
/// Number of failures in creating a new network interface.
pub network_fails: SharedMetric,
}
/// Metrics specific to PATCH API Requests for counting user triggered actions and/or failures.
#[derive(Default, Serialize)]
pub struct PatchRequestsMetrics {
/// Number of tries to PATCH a block device.
pub drive_count: SharedMetric,
/// Number of failures in PATCHing a block device.
pub drive_fails: SharedMetric,
}
/// Block Device associated metrics.
#[derive(Default, Serialize)]
pub struct BlockDeviceMetrics {
/// Number of times when activate failed on a block device.
pub activate_fails: SharedMetric,
/// Number of times when interacting with the space config of a block device failed.
pub cfg_fails: SharedMetric,
/// Number of times when handling events on a block device failed.
pub event_fails: SharedMetric,
/// Number of failures in executing a request on a block device.
pub execute_fails: SharedMetric,
/// Number of invalid requests received for this block device.
pub invalid_reqs_count: SharedMetric,
/// Number of flushes operation triggered on this block device.
pub flush_count: SharedMetric,
/// Number of events triggerd on the queue of this block device.
pub queue_event_count: SharedMetric,
/// Number of events ratelimiter-related.
pub rate_limiter_event_count: SharedMetric,
/// Number of update operation triggered on this block device.
pub update_count: SharedMetric,
/// Number of failures while doing update on this block device.
pub update_fails: SharedMetric,
/// Number of bytes read by this block device.
pub read_count: SharedMetric,
/// Number of bytes written by this block device.
pub write_count: SharedMetric,
}
/// Metrics specific to the i8042 device.
#[derive(Default, Serialize)]
pub struct I8042DeviceMetrics {
/// 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 read by this device.
pub read_count: SharedMetric,
/// Number of resets done by this device.
pub reset_count: SharedMetric,
/// Bytes written by this device.
pub write_count: SharedMetric,
}
/// Metrics for the logging subsystem.
#[derive(Default, Serialize)]
pub struct LoggerSystemMetrics {
/// Number of misses on flushing metrics.
pub missed_metrics_count: SharedMetric,
/// Number of errors during metrics handling.
pub metrics_fails: SharedMetric,
/// Number of misses on logging human readable content.
pub missed_log_count: SharedMetric,
/// Number of errors while trying to log human readable content.
pub log_fails: SharedMetric,
}
/// Metrics for the MMDS functionality.
#[derive(Default, Serialize)]
pub struct MmdsMetrics {
/// Number of frames rerouted to MMDS.
pub rx_accepted: SharedMetric,
/// Number of errors while handling a frame through MMDS.
pub rx_accepted_err: SharedMetric,
/// Number of uncommon events encountered while processing packets through MMDS.
pub rx_accepted_unusual: SharedMetric,
/// The number of buffers which couldn't be parsed as valid Ethernet frames by the MMDS.
pub rx_bad_eth: SharedMetric,
/// The total number of bytes sent by the MMDS.
pub tx_bytes: SharedMetric,
/// The number of errors raised by the MMDS while attempting to send frames/packets/segments.
pub tx_errors: SharedMetric,
/// The number of frames sent by the MMDS.
pub tx_frames: SharedMetric,
/// The number of connections successfully accepted by the MMDS TCP handler.
pub connections_created: SharedMetric,
/// The number of connections cleaned up by the MMDS TCP handler.
pub connections_destroyed: SharedMetric,
}
/// Network-related metrics.
#[derive(Default, Serialize)]
pub struct NetDeviceMetrics {
/// Number of times when activate failed on a network device.
pub activate_fails: SharedMetric,
/// Number of times when interacting with the space config of a network device failed.
pub cfg_fails: SharedMetric,
/// Number of times when handling events on a network device failed.
pub event_fails: SharedMetric,
/// Number of events associated with the receiving queue.
pub rx_queue_event_count: SharedMetric,
/// Number of events associated with the rate limiter installed on the receiving path.
pub rx_event_rate_limiter_count: SharedMetric,
/// Number of events received on the associated tap.
pub rx_tap_event_count: SharedMetric,
/// Number of bytes received.
pub rx_bytes_count: SharedMetric,
/// Number of packets received.
pub rx_packets_count: SharedMetric,
/// Number of errors while receiving data.
pub rx_fails: SharedMetric,
/// Number of transmitted bytes.
pub tx_bytes_count: SharedMetric,
/// Number of errors while transmitting data.
pub tx_fails: SharedMetric,
/// Number of transmitted packets.
pub tx_packets_count: SharedMetric,
/// Number of events associated with the transmitting queue.
pub tx_queue_event_count: SharedMetric,
/// Number of events associated with the rate limiter installed on the transmitting path.
pub tx_rate_limiter_event_count: SharedMetric,
}
/// Metrics for the seccomp filtering.
#[derive(Serialize)]
pub struct SeccompMetrics {
/// Number of black listed syscalls.
pub bad_syscalls: Vec<SharedMetric>,
/// Number of errors inside the seccomp filtering.
pub num_faults: SharedMetric,
}
impl Default for SeccompMetrics {
fn | 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::Ok, S::Error> {
// There's no serializer.serialize_usize().
serializer.serialize_u64(self.0.load(Ordering::Relaxed) as u64)
}
}
/// Representation of a metric that is expected to be incremented from more than one thread, so more
/// synchronization is necessary.
// It's currently used for vCPU metrics. An alternative here would be
// to have one instance of every metric for each thread (like a per-thread SimpleMetric), and to
// aggregate them when logging. However this probably overkill unless we have a lot of vCPUs
// incrementing metrics very often. Still, it's there if we ever need it :-s
#[derive(Default)]
// We will be keeping two values for each metric for being able to reset
// counters on each metric.
// 1st member - current value being updated
// 2nd member - old value that gets the current value whenever metrics is flushed to disk
pub struct SharedMetric(AtomicUsize, AtomicUsize);
impl Metric for SharedMetric {
// While the order specified for this operation is still Relaxed, the actual instruction will
// be an asm "LOCK; something" and thus 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) -> usize {
self.0.load(Ordering::Relaxed)
}
}
impl Serialize for SharedMetric {
/// Reset counters of each metrics. Here we suppose that Serialize's goal is to help with the
/// flushing of metrics.
/// !!! Any print of the metrics will also reset them. Use with caution !!!
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
// There's no serializer.serialize_usize() for some reason :(
let snapshot = self.0.load(Ordering::Relaxed);
let res = serializer.serialize_u64(snapshot as u64 - self.1.load(Ordering::Relaxed) as u64);
if res.is_ok() |
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.
/// Metrics related to the internal API server.
#[derive(Default, Serialize)]
pub struct ApiServerMetrics {
/// Measures the process's startup time in microseconds.
pub process_startup_time_us: SharedMetric,
/// Measures the cpu's startup time in microseconds.
pub process_startup_time_cpu_us: SharedMetric,
/// Number of failures on API requests triggered by internal errors.
pub sync_outcome_fails: SharedMetric,
/// Number of timeouts during communication with the VMM.
pub sync_vmm_send_timeout_count: SharedMetric,
}
/// Metrics specific to GET API Requests for counting user triggered actions and/or failures.
#[derive(Default, Serialize)]
pub struct GetRequestsMetrics {
/// Number of GETs for getting information on the instance.
pub instance_info_count: SharedMetric,
/// Number of failures when obtaining information on the current instance.
pub instance_info_fails: SharedMetric,
/// Number of GETs for getting status on attaching machine configuration.
pub machine_cfg_count: SharedMetric,
/// Number of failures during GETs for getting information on the instance.
pub machine_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 action on the VM.
pub actions_fails: SharedMetric,
/// Number of PUTs for attaching source of boot.
pub boot_source_count: SharedMetric,
/// Number of failures during attaching source of boot.
pub boot_source_fails: SharedMetric,
/// Number of PUTs triggering a block attach.
pub drive_count: SharedMetric,
/// Number of failures in attaching a block device.
pub drive_fails: SharedMetric,
/// Number of PUTs for initializing the logging system.
pub logger_count: SharedMetric,
/// Number of failures in initializing the logging system.
pub logger_fails: SharedMetric,
/// Number of PUTs for configuring the machine.
pub machine_cfg_count: SharedMetric,
/// Number of failures in configuring the machine.
pub machine_cfg_fails: SharedMetric,
/// Number of PUTs for creating a new network interface.
pub network_count: SharedMetric,
/// Number of failures in creating a new network interface.
pub network_fails: SharedMetric,
}
/// Metrics specific to PATCH API Requests for counting user triggered actions and/or failures.
#[derive(Default, Serialize)]
pub struct PatchRequestsMetrics {
/// Number of tries to PATCH a block device.
pub drive_count: SharedMetric,
/// Number of failures in PATCHing a block device.
pub drive_fails: SharedMetric,
}
/// Block Device associated metrics.
#[derive(Default, Serialize)]
pub struct BlockDeviceMetrics {
/// Number of times when activate failed on a block device.
pub activate_fails: SharedMetric,
/// Number of times when interacting with the space config of a block device failed.
pub cfg_fails: SharedMetric,
/// Number of times when handling events on a block device failed.
pub event_fails: SharedMetric,
/// Number of failures in executing a request on a block device.
pub execute_fails: SharedMetric,
/// Number of invalid requests received for this block device.
pub invalid_reqs_count: SharedMetric,
/// Number of flushes operation triggered on this block device.
pub flush_count: SharedMetric,
/// Number of events triggerd on the queue of this block device.
pub queue_event_count: SharedMetric,
/// Number of events ratelimiter-related.
pub rate_limiter_event_count: SharedMetric,
/// Number of update operation triggered on this block device.
pub update_count: SharedMetric,
/// Number of failures while doing update on this block device.
pub update_fails: SharedMetric,
/// Number of bytes read by this block device.
pub read_count: SharedMetric,
/// Number of bytes written by this block device.
pub write_count: SharedMetric,
}
/// Metrics specific to the i8042 device.
#[derive(Default, Serialize)]
pub struct I8042DeviceMetrics {
/// 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 read by this device.
pub read_count: SharedMetric,
/// Number of resets done by this device.
pub reset_count: SharedMetric,
/// Bytes written by this device.
pub write_count: SharedMetric,
}
/// Metrics for the logging subsystem.
#[derive(Default, Serialize)]
pub struct LoggerSystemMetrics {
/// Number of misses on flushing metrics.
pub missed_metrics_count: SharedMetric,
/// Number of errors during metrics handling.
pub metrics_fails: SharedMetric,
/// Number of misses on logging human readable content.
pub missed_log_count: SharedMetric,
/// Number of errors while trying to log human readable content.
pub log_fails: SharedMetric,
}
/// Metrics for the MMDS functionality.
#[derive(Default, Serialize)]
pub struct MmdsMetrics {
/// Number of frames rerouted to MMDS.
pub rx_accepted: SharedMetric,
/// Number of errors while handling a frame through MMDS.
pub rx_accepted_err: SharedMetric,
/// Number of uncommon events encountered while processing packets through MMDS.
pub rx_accepted_unusual: SharedMetric,
/// The number of buffers which couldn't be parsed as valid Ethernet frames by the MMDS.
pub rx_bad_eth: SharedMetric,
/// The total number of bytes sent by the MMDS.
pub tx_bytes: SharedMetric,
/// The number of errors raised by the MMDS while attempting to send frames/packets/segments.
pub tx_errors: SharedMetric,
/// The number of frames sent by the MMDS.
pub tx_frames: SharedMetric,
/// The number of connections successfully accepted by the MMDS TCP handler.
pub connections_created: SharedMetric,
/// The number of connections cleaned up by the MMDS TCP handler.
pub connections_destroyed: SharedMetric,
}
/// Network-related metrics.
#[derive(Default, Serialize)]
pub struct NetDeviceMetrics {
/// Number of times when activate failed on a network device.
pub activate_fails: SharedMetric,
/// Number of times when interacting with the space | {
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 document with the place holder according to the window_size
"""
padding = (pad_symbol,) * (window_size - 1)
if pad_right:
return _itertools.chain.from_iterable(
_itertools.chain(doc, padding) for doc in documents
)
if pad_left:
return _itertools.chain.from_iterable(
_itertools.chain(padding, doc) for doc in documents
)
@classmethod
def from_documents(cls, documents):
"""Constructs a collocation finder given a collection of documents,
each of which is a list (or iterable) of tokens.
"""
# return cls.from_words(_itertools.chain(*documents))
return cls.from_words(
cls._build_new_documents(documents, cls.default_ws, pad_right=True)
)
@staticmethod
def _ngram_freqdist(words, n):
return FreqDist(tuple(words[i : i + n]) for i in range(len(words) - 1))
def _apply_filter(self, fn=lambda ngram, freq: False):
"""Generic filter removes ngrams from the frequency distribution
if the function returns True when passed an ngram tuple.
"""
tmp_ngram = FreqDist()
for ngram, freq in self.ngram_fd.items():
if not fn(ngram, freq):
tmp_ngram[ngram] = freq
self.ngram_fd = tmp_ngram
def apply_freq_filter(self, min_freq):
"""Removes candidate ngrams which have frequency less than min_freq."""
self._apply_filter(lambda ng, freq: freq < min_freq)
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),
...) evaluates to True.
"""
self._apply_filter(lambda ng, f: any(fn(w) for w in ng))
def _score_ngrams(self, score_fn):
"""Generates of (ngram, score) pairs as determined by the scoring
function provided.
"""
for tup in self.ngram_fd:
score = self.score_ngram(score_fn, *tup)
if score is not None:
yield tup, score
def | (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 n ngrams when scored by the given function."""
return [p for p, s in self.score_ngrams(score_fn)[:n]]
def above_score(self, score_fn, min_score):
"""Returns a sequence of ngrams, ordered by decreasing score, whose
scores each exceed the given minimum score.
"""
for ngram, score in self.score_ngrams(score_fn):
if score > min_score:
yield ngram
else:
break
class BigramCollocationFinder(AbstractCollocationFinder):
"""A tool for the finding and ranking of bigram collocations or other
association measures. It is often useful to use from_words() rather than
constructing an instance directly.
"""
default_ws = 2
def __init__(self, word_fd, bigram_fd, window_size=2):
"""Construct a BigramCollocationFinder, given FreqDists for
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 the given
sequence. When window_size > 2, count non-contiguous bigrams, in the
style of Church and Hanks's (1990) association ratio.
"""
wfd = FreqDist()
bfd = FreqDist()
if window_size < 2:
raise ValueError("Specify window_size at least 2")
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
wfd[w1] += 1
for w2 in window[1:]:
if w2 is not None:
bfd[(w1, w2)] += 1
return cls(wfd, bfd, window_size=window_size)
def score_ngram(self, score_fn, w1, w2):
"""Returns the score for a given bigram using the given scoring
function. Following Church and Hanks (1990), counts are scaled by
a factor of 1/(window_size - 1).
"""
n_all = self.N
n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0)
if not n_ii:
return
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() rather than
constructing an instance directly.
"""
default_ws = 3
def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd):
"""Construct a TrigramCollocationFinder, given FreqDists for
appearances of words, bigrams, two words with any word between them,
and trigrams.
"""
AbstractCollocationFinder.__init__(self, word_fd, trigram_fd)
self.wildcard_fd = wildcard_fd
self.bigram_fd = bigram_fd
@classmethod
def from_words(cls, words, window_size=3):
"""Construct a TrigramCollocationFinder for all trigrams in the given
sequence.
"""
if window_size < 3:
raise ValueError("Specify window_size at least 3")
wfd = FreqDist()
wildfd = FreqDist()
bfd = FreqDist()
tfd = FreqDist()
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
for w2, w3 in _itertools.combinations(window[1:], 2):
wfd[w1] += 1
if w2 is None:
continue
bfd[(w1, w2)] += 1
if w3 is None:
continue
wildfd[(w1, w3)] += 1
tfd[(w1, w2, w3)] += 1
return cls(wfd, bfd, wildfd, tfd)
def bigram_finder(self):
"""Constructs a bigram collocation finder with the bigram and unigram
data from this finder. Note that this does not include any filtering
applied to this finder.
"""
return BigramCollocationFinder(self.word_fd, self.bigram_fd)
def score_ngram(self, score_fn, w1, w2, w3):
"""Returns the score for a given trigram using the given scoring
function.
"""
n_all = self.N
n_iii = self.ngram_fd[(w1, w2, w3)]
if not n_iii:
return
n_iix = self.bigram_fd[(w1, w2)]
n_ixi = self.wildcard_fd[(w1, w3)]
n_xii = self.bigram_fd[(w2, w3)]
n_ixx = self.word_fd[w1]
n_xix = self.word_fd[w2]
n_xxi = self.word_fd[w3]
return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all)
class QuadgramCollocationFinder(AbstractCollocationFinder):
"""A tool for the finding and ranking of quadgram collocations or other association measures.
It is often useful to use from_words() rather than constructing an instance directly.
"""
default_ws = 4
def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii):
"""Construct a QuadgramCollocationFinder, given FreqDists for appearances of words,
bigrams, trigrams, two words with one word and two words between them | 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 document with the place holder according to the window_size
"""
padding = (pad_symbol,) * (window_size - 1)
if pad_right:
return _itertools.chain.from_iterable(
_itertools.chain(doc, padding) for doc in documents
)
if pad_left:
return _itertools.chain.from_iterable(
_itertools.chain(padding, doc) for doc in documents
)
@classmethod
def from_documents(cls, documents):
"""Constructs a collocation finder given a collection of documents,
each of which is a list (or iterable) of tokens.
"""
# return cls.from_words(_itertools.chain(*documents))
return cls.from_words(
cls._build_new_documents(documents, cls.default_ws, pad_right=True)
)
@staticmethod
def _ngram_freqdist(words, n):
return FreqDist(tuple(words[i : i + n]) for i in range(len(words) - 1))
def _apply_filter(self, fn=lambda ngram, freq: False):
"""Generic filter removes ngrams from the frequency distribution
if the function returns True when passed an ngram tuple.
"""
tmp_ngram = FreqDist()
for ngram, freq in self.ngram_fd.items():
if not fn(ngram, freq):
tmp_ngram[ngram] = freq
self.ngram_fd = tmp_ngram
def apply_freq_filter(self, min_freq):
|
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),
...) evaluates to True.
"""
self._apply_filter(lambda ng, f: any(fn(w) for w in ng))
def _score_ngrams(self, score_fn):
"""Generates of (ngram, score) pairs as determined by the scoring
function provided.
"""
for tup in self.ngram_fd:
score = self.score_ngram(score_fn, *tup)
if score is not None:
yield tup, score
def score_ngrams(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 n ngrams when scored by the given function."""
return [p for p, s in self.score_ngrams(score_fn)[:n]]
def above_score(self, score_fn, min_score):
"""Returns a sequence of ngrams, ordered by decreasing score, whose
scores each exceed the given minimum score.
"""
for ngram, score in self.score_ngrams(score_fn):
if score > min_score:
yield ngram
else:
break
class BigramCollocationFinder(AbstractCollocationFinder):
"""A tool for the finding and ranking of bigram collocations or other
association measures. It is often useful to use from_words() rather than
constructing an instance directly.
"""
default_ws = 2
def __init__(self, word_fd, bigram_fd, window_size=2):
"""Construct a BigramCollocationFinder, given FreqDists for
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 the given
sequence. When window_size > 2, count non-contiguous bigrams, in the
style of Church and Hanks's (1990) association ratio.
"""
wfd = FreqDist()
bfd = FreqDist()
if window_size < 2:
raise ValueError("Specify window_size at least 2")
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
wfd[w1] += 1
for w2 in window[1:]:
if w2 is not None:
bfd[(w1, w2)] += 1
return cls(wfd, bfd, window_size=window_size)
def score_ngram(self, score_fn, w1, w2):
"""Returns the score for a given bigram using the given scoring
function. Following Church and Hanks (1990), counts are scaled by
a factor of 1/(window_size - 1).
"""
n_all = self.N
n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0)
if not n_ii:
return
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() rather than
constructing an instance directly.
"""
default_ws = 3
def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd):
"""Construct a TrigramCollocationFinder, given FreqDists for
appearances of words, bigrams, two words with any word between them,
and trigrams.
"""
AbstractCollocationFinder.__init__(self, word_fd, trigram_fd)
self.wildcard_fd = wildcard_fd
self.bigram_fd = bigram_fd
@classmethod
def from_words(cls, words, window_size=3):
"""Construct a TrigramCollocationFinder for all trigrams in the given
sequence.
"""
if window_size < 3:
raise ValueError("Specify window_size at least 3")
wfd = FreqDist()
wildfd = FreqDist()
bfd = FreqDist()
tfd = FreqDist()
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
for w2, w3 in _itertools.combinations(window[1:], 2):
wfd[w1] += 1
if w2 is None:
continue
bfd[(w1, w2)] += 1
if w3 is None:
continue
wildfd[(w1, w3)] += 1
tfd[(w1, w2, w3)] += 1
return cls(wfd, bfd, wildfd, tfd)
def bigram_finder(self):
"""Constructs a bigram collocation finder with the bigram and unigram
data from this finder. Note that this does not include any filtering
applied to this finder.
"""
return BigramCollocationFinder(self.word_fd, self.bigram_fd)
def score_ngram(self, score_fn, w1, w2, w3):
"""Returns the score for a given trigram using the given scoring
function.
"""
n_all = self.N
n_iii = self.ngram_fd[(w1, w2, w3)]
if not n_iii:
return
n_iix = self.bigram_fd[(w1, w2)]
n_ixi = self.wildcard_fd[(w1, w3)]
n_xii = self.bigram_fd[(w2, w3)]
n_ixx = self.word_fd[w1]
n_xix = self.word_fd[w2]
n_xxi = self.word_fd[w3]
return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all)
class QuadgramCollocationFinder(AbstractCollocationFinder):
"""A tool for the finding and ranking of quadgram collocations or other association measures.
It is often useful to use from_words() rather than constructing an instance directly.
"""
default_ws = 4
def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii):
"""Construct a QuadgramCollocationFinder, given FreqDists for appearances of words,
bigrams, trigrams, two words with one word and two words between them | """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 document with the place holder according to the window_size
"""
padding = (pad_symbol,) * (window_size - 1)
if pad_right:
return _itertools.chain.from_iterable(
_itertools.chain(doc, padding) for doc in documents
)
if pad_left:
return _itertools.chain.from_iterable(
_itertools.chain(padding, doc) for doc in documents
)
@classmethod
def from_documents(cls, documents):
"""Constructs a collocation finder given a collection of documents,
each of which is a list (or iterable) of tokens.
"""
# return cls.from_words(_itertools.chain(*documents))
return cls.from_words(
cls._build_new_documents(documents, cls.default_ws, pad_right=True)
)
@staticmethod
def _ngram_freqdist(words, n):
return FreqDist(tuple(words[i : i + n]) for i in range(len(words) - 1))
def _apply_filter(self, fn=lambda ngram, freq: False):
"""Generic filter removes ngrams from the frequency distribution
if the function returns True when passed an ngram tuple.
"""
tmp_ngram = FreqDist()
for ngram, freq in self.ngram_fd.items():
if not fn(ngram, freq):
tmp_ngram[ngram] = freq
self.ngram_fd = tmp_ngram
def apply_freq_filter(self, min_freq):
"""Removes candidate ngrams which have frequency less than min_freq."""
self._apply_filter(lambda ng, freq: freq < min_freq)
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),
...) evaluates to True.
"""
self._apply_filter(lambda ng, f: any(fn(w) for w in ng))
def _score_ngrams(self, score_fn):
"""Generates of (ngram, score) pairs as determined by the scoring
function provided.
"""
for tup in self.ngram_fd:
score = self.score_ngram(score_fn, *tup)
if score is not None:
yield tup, score
def score_ngrams(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 n ngrams when scored by the given function."""
return [p for p, s in self.score_ngrams(score_fn)[:n]]
def above_score(self, score_fn, min_score):
"""Returns a sequence of ngrams, ordered by decreasing score, whose
scores each exceed the given minimum score.
"""
for ngram, score in self.score_ngrams(score_fn):
if score > min_score:
yield ngram
else:
break
class BigramCollocationFinder(AbstractCollocationFinder):
"""A tool for the finding and ranking of bigram collocations or other
association measures. It is often useful to use from_words() rather than
constructing an instance directly.
"""
default_ws = 2
def __init__(self, word_fd, bigram_fd, window_size=2):
"""Construct a BigramCollocationFinder, given FreqDists for
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 the given
sequence. When window_size > 2, count non-contiguous bigrams, in the
style of Church and Hanks's (1990) association ratio.
"""
wfd = FreqDist()
bfd = FreqDist()
if window_size < 2:
raise ValueError("Specify window_size at least 2")
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
wfd[w1] += 1
for w2 in window[1:]:
if w2 is not None:
bfd[(w1, w2)] += 1
return cls(wfd, bfd, window_size=window_size)
def score_ngram(self, score_fn, w1, w2):
"""Returns the score for a given bigram using the given scoring
function. Following Church and Hanks (1990), counts are scaled by
a factor of 1/(window_size - 1).
"""
n_all = self.N
n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0)
if not n_ii:
|
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() rather than
constructing an instance directly.
"""
default_ws = 3
def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd):
"""Construct a TrigramCollocationFinder, given FreqDists for
appearances of words, bigrams, two words with any word between them,
and trigrams.
"""
AbstractCollocationFinder.__init__(self, word_fd, trigram_fd)
self.wildcard_fd = wildcard_fd
self.bigram_fd = bigram_fd
@classmethod
def from_words(cls, words, window_size=3):
"""Construct a TrigramCollocationFinder for all trigrams in the given
sequence.
"""
if window_size < 3:
raise ValueError("Specify window_size at least 3")
wfd = FreqDist()
wildfd = FreqDist()
bfd = FreqDist()
tfd = FreqDist()
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
for w2, w3 in _itertools.combinations(window[1:], 2):
wfd[w1] += 1
if w2 is None:
continue
bfd[(w1, w2)] += 1
if w3 is None:
continue
wildfd[(w1, w3)] += 1
tfd[(w1, w2, w3)] += 1
return cls(wfd, bfd, wildfd, tfd)
def bigram_finder(self):
"""Constructs a bigram collocation finder with the bigram and unigram
data from this finder. Note that this does not include any filtering
applied to this finder.
"""
return BigramCollocationFinder(self.word_fd, self.bigram_fd)
def score_ngram(self, score_fn, w1, w2, w3):
"""Returns the score for a given trigram using the given scoring
function.
"""
n_all = self.N
n_iii = self.ngram_fd[(w1, w2, w3)]
if not n_iii:
return
n_iix = self.bigram_fd[(w1, w2)]
n_ixi = self.wildcard_fd[(w1, w3)]
n_xii = self.bigram_fd[(w2, w3)]
n_ixx = self.word_fd[w1]
n_xix = self.word_fd[w2]
n_xxi = self.word_fd[w3]
return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all)
class QuadgramCollocationFinder(AbstractCollocationFinder):
"""A tool for the finding and ranking of quadgram collocations or other association measures.
It is often useful to use from_words() rather than constructing an instance directly.
"""
default_ws = 4
def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii):
"""Construct a QuadgramCollocationFinder, given FreqDists for appearances of words,
bigrams, trigrams, two words with one word and two words between them, | 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 the given
sequence. When window_size > 2, count non-contiguous bigrams, in the
style of Church and Hanks's (1990) association ratio.
"""
wfd = FreqDist()
bfd = FreqDist()
if window_size < 2:
raise ValueError("Specify window_size at least 2")
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
wfd[w1] += 1
for w2 in window[1:]:
if w2 is not None:
bfd[(w1, w2)] += 1
return cls(wfd, bfd, window_size=window_size)
def score_ngram(self, score_fn, w1, w2):
"""Returns the score for a given bigram using the given scoring
function. Following Church and Hanks (1990), counts are scaled by
a factor of 1/(window_size - 1).
"""
n_all = self.N
n_ii = self.ngram_fd[(w1, w2)] / (self.window_size - 1.0)
if not n_ii:
return
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() rather than
constructing an instance directly.
"""
default_ws = 3
def __init__(self, word_fd, bigram_fd, wildcard_fd, trigram_fd):
"""Construct a TrigramCollocationFinder, given FreqDists for
appearances of words, bigrams, two words with any word between them,
and trigrams.
"""
AbstractCollocationFinder.__init__(self, word_fd, trigram_fd)
self.wildcard_fd = wildcard_fd
self.bigram_fd = bigram_fd
@classmethod
def from_words(cls, words, window_size=3):
"""Construct a TrigramCollocationFinder for all trigrams in the given
sequence.
"""
if window_size < 3:
raise ValueError("Specify window_size at least 3")
wfd = FreqDist()
wildfd = FreqDist()
bfd = FreqDist()
tfd = FreqDist()
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
for w2, w3 in _itertools.combinations(window[1:], 2):
wfd[w1] += 1
if w2 is None:
continue
bfd[(w1, w2)] += 1
if w3 is None:
continue
wildfd[(w1, w3)] += 1
tfd[(w1, w2, w3)] += 1
return cls(wfd, bfd, wildfd, tfd)
def bigram_finder(self):
"""Constructs a bigram collocation finder with the bigram and unigram
data from this finder. Note that this does not include any filtering
applied to this finder.
"""
return BigramCollocationFinder(self.word_fd, self.bigram_fd)
def score_ngram(self, score_fn, w1, w2, w3):
"""Returns the score for a given trigram using the given scoring
function.
"""
n_all = self.N
n_iii = self.ngram_fd[(w1, w2, w3)]
if not n_iii:
return
n_iix = self.bigram_fd[(w1, w2)]
n_ixi = self.wildcard_fd[(w1, w3)]
n_xii = self.bigram_fd[(w2, w3)]
n_ixx = self.word_fd[w1]
n_xix = self.word_fd[w2]
n_xxi = self.word_fd[w3]
return score_fn(n_iii, (n_iix, n_ixi, n_xii), (n_ixx, n_xix, n_xxi), n_all)
class QuadgramCollocationFinder(AbstractCollocationFinder):
"""A tool for the finding and ranking of quadgram collocations or other association measures.
It is often useful to use from_words() rather than constructing an instance directly.
"""
default_ws = 4
def __init__(self, word_fd, quadgram_fd, ii, iii, ixi, ixxi, iixi, ixii):
"""Construct a QuadgramCollocationFinder, given FreqDists for appearances of words,
bigrams, trigrams, two words with one word and two words between them, three words
with a word between them in both variations.
"""
AbstractCollocationFinder.__init__(self, word_fd, quadgram_fd)
self.iii = iii
self.ii = ii
self.ixi = ixi
self.ixxi = ixxi
self.iixi = iixi
self.ixii = ixii
@classmethod
def from_words(cls, words, window_size=4):
if window_size < 4:
raise ValueError("Specify window_size at least 4")
ixxx = FreqDist()
iiii = FreqDist()
ii = FreqDist()
iii = FreqDist()
ixi = FreqDist()
ixxi = FreqDist()
iixi = FreqDist()
ixii = FreqDist()
for window in ngrams(words, window_size, pad_right=True):
w1 = window[0]
if w1 is None:
continue
for w2, w3, w4 in _itertools.combinations(window[1:], 3):
ixxx[w1] += 1
if w2 is None:
continue
ii[(w1, w2)] += 1
if w3 is None:
continue
iii[(w1, w2, w3)] += 1
ixi[(w1, w3)] += 1
if w4 is None:
continue
iiii[(w1, w2, w3, w4)] += 1
ixxi[(w1, w4)] += 1
ixii[(w1, w3, w4)] += 1
iixi[(w1, w2, w4)] += 1
return cls(ixxx, iiii, ii, iii, ixi, ixxi, iixi, ixii)
def score_ngram(self, score_fn, w1, w2, w3, w4):
n_all = self.N
n_iiii = self.ngram_fd[(w1, w2, w3, w4)]
if not n_iiii:
return
n_iiix = self.iii[(w1, w2, w3)]
n_xiii = self.iii[(w2, w3, w4)]
n_iixi = self.iixi[(w1, w2, w4)]
n_ixii = self.ixii[(w1, w3, w4)]
n_iixx = self.ii[(w1, w2)]
n_xxii = self.ii[(w3, w4)]
n_xiix = self.ii[(w2, w3)]
n_ixix = self.ixi[(w1, w3)]
n_ixxi = self.ixxi[(w1, w4)]
n_xixi = self.ixi[(w2, w4)]
n_ixxx = self.word_fd[w1]
n_xixx = self.word_fd[w2]
n_xxix = self.word_fd[w3]
n_xxxi = self.word_fd[w4]
return score_fn(
n_iiii,
(n_iiix, n_iixi, n_ixii, n_xiii),
(n_iixx, n_ixix, n_ixxi, n_xixi, n_xxii, n_xiix),
(n_ixxx, n_xixx, n_xxix, n_xxxi),
n_all,
)
def demo(scorer=None, compare_scorer=None):
"""Finds bigram collocations in the files of the WebText corpus."""
from nltk.metrics import (
BigramAssocMeasures,
ranks_from_scores,
spearman_correlation,
)
if scorer is None:
scorer = BigramAssocMeasures.likelihood_ratio
if compare_scorer is None: | 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 to 8 bytes in order as a u64.
priv fn bytesum(bytes: &[u8]) -> u64 {
let mut i = 0;
let mut ret: u64 = 0;
for bytes.iter().advance |&byte| {
ret |= (byte as u64) >> (8 * i);
i += 1;
}
ret
}
impl<T:Stream<u8>> BsonParser<T> {
///Parse a byte stream into a BsonDocument. Returns an error string on parse failure.
///Initializing a BsonParser and calling document() will fully convert a ~[u8]
///into a BsonDocument if it was formatted correctly.
pub fn document(&mut self) -> Result<BsonDocument,~str> {
let size = bytesum(self.stream.aggregate(4)) as i32;
let mut elemcode = self.stream.expect(&[
DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID,
BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE,
INT32,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(),
Some(EMBED) => {
let doc = self._embed();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(ARRAY) => {
let doc = self._array();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(BINARY) => self._binary(),
Some(OBJID) => ObjectId(self.stream.aggregate(12)),
Some(BOOL) => self._bool(),
Some(UTCDATE) => UTCDate(bytesum(self.stream.aggregate(8)) as i64),
Some(NULL) => Null,
Some(REGEX) => self._regex(),
Some(DBREF) => {
let doc = self._dbref();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(JSCRIPT) => {
let doc = self._jscript();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(JSCOPE) => {
let doc = self._jscope();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(INT32) => Int32(bytesum(self.stream.aggregate(4)) as i32),
Some(TSTAMP) => Timestamp(bytesum(self.stream.aggregate(4)) as u32,
bytesum(self.stream.aggregate(4)) as u32),
Some(INT64) => Int64(bytesum(self.stream.aggregate(8)) as i64),
Some(MINKEY) => MinKey,
Some(MAXKEY) => MaxKey,
_ => return Err(~"an invalid element code was found")
};
ret.put(key, val);
elemcode = self.stream.expect(&[
DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID,
BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE,
INT32,TSTAMP,INT64,MINKEY,MAXKEY]);
if self.stream.has_next() { self.stream.pass(1); }
}
ret.size = size;
Ok(ret)
}
///Parse a string without denoting its length. Mainly for keys.
fn cstring(&mut self) -> ~str {
let is_0: &fn(&u8) -> bool = |&x| x == 0x00;
let s = from_bytes(self.stream.until(is_0));
self.stream.pass(1);
s
}
///Parse a double.
fn _double(&mut self) -> Document {
let mut u: u64 = 0;
for range(0,8) |i| {
//TODO: how will this hold up on big-endian architectures?
u |= (*self.stream.first() as u64 << ((8 * i)));
self.stream.pass(1);
}
let v: &f64 = unsafe { transmute(&u) };
Double(*v)
}
///Parse a string with length.
fn _string(&mut self) -> Document {
self.stream.pass(4); //skip length
let v = self.cstring();
UString(v)
}
///Parse an embedded object. May fail.
fn _embed(&mut self) -> Result<Document,~str> {
return self.document().chain(|s| Ok(Embedded(~s)));
}
///Parse an embedded array. May fail.
fn _array(&mut self) -> Result<Document,~str> {
return self.document().chain(|s| Ok(Array(~s)));
}
///Parse generic binary data.
fn _binary(&mut self) -> Document {
let count = bytesum(self.stream.aggregate(4));
let subtype = *(self.stream.first());
self.stream.pass(1);
let data = self.stream.aggregate(count as uint);
Binary(subtype, data)
}
///Parse a boolean.
fn _bool(&mut self) -> Document {
let ret = (*self.stream.first()) as bool;
self.stream.pass(1);
Bool(ret)
}
///Parse a regex.
fn _regex(&mut self) -> Document {
let s1 = self.cstring();
let s2 = self.cstring();
Regex(s1, s2)
}
fn _dbref(&mut self) -> Result<Document, ~str> {
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)))
} | 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.
fn _jscope(&mut self) -> Result<Document,~str> {
self.stream.pass(4);
let s = self.cstring();
let doc = self.document();
return doc.chain(|d| Ok(JScriptWithScope(s.clone(),~d)));
}
///Create a new parser with a given stream.
pub fn new(stream: T) -> BsonParser<T> { BsonParser { stream: stream } }
}
///Standalone decode binding.
///This is equivalent to initializing a parser and calling document().
pub fn decode(b: ~[u8]) -> Result<BsonDocument,~str> {
let mut parser = BsonParser::new(b);
parser.document()
}
#[cfg(test)]
mod tests {
use super::*;
use encode::*;
use extra::test::BenchHarness;
#[test]
fn test_decode_size() {
let doc = decode(~[10,0,0,0,10,100,100,100,0]);
assert_eq!(doc.unwrap().size, 10);
}
#[test]
fn test_cstring_decode() {
let stream: ~[u8] = ~[104,101,108,108,111,0];
let mut parser = BsonParser::new(stream);
assert_eq!(parser.cstring(), ~"hello");
}
#[test]
fn test_double_decode() {
let stream: ~[u8] = ~[110,134,27,240,249,33,9,64];
let mut parser = BsonParser::new(stream);
let d = parser._double();
match d {
Double(d2) => {
assert!(d2.approx_eq(&3.14159f64));
}
_ => fail!("failed in a test case; how did I get here?")
}
}
#[test]
fn test_document_decode() {
let stream1: ~[u8] = ~[11,0,0,0,8,102,111,111,0,1,0];
| ///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 bytes in order as a u64.
priv fn bytesum(bytes: &[u8]) -> u64 {
let mut i = 0;
let mut ret: u64 = 0;
for bytes.iter().advance |&byte| {
ret |= (byte as u64) >> (8 * i);
i += 1;
}
ret
}
impl<T:Stream<u8>> BsonParser<T> {
///Parse a byte stream into a BsonDocument. Returns an error string on parse failure.
///Initializing a BsonParser and calling document() will fully convert a ~[u8]
///into a BsonDocument if it was formatted correctly.
pub fn document(&mut self) -> Result<BsonDocument,~str> {
let size = bytesum(self.stream.aggregate(4)) as i32;
let mut elemcode = self.stream.expect(&[
DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID,
BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE,
INT32,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(),
Some(EMBED) => {
let doc = self._embed();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(ARRAY) => {
let doc = self._array();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(BINARY) => self._binary(),
Some(OBJID) => ObjectId(self.stream.aggregate(12)),
Some(BOOL) => self._bool(),
Some(UTCDATE) => UTCDate(bytesum(self.stream.aggregate(8)) as i64),
Some(NULL) => Null,
Some(REGEX) => self._regex(),
Some(DBREF) => {
let doc = self._dbref();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(JSCRIPT) => {
let doc = self._jscript();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(JSCOPE) => {
let doc = self._jscope();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(INT32) => Int32(bytesum(self.stream.aggregate(4)) as i32),
Some(TSTAMP) => Timestamp(bytesum(self.stream.aggregate(4)) as u32,
bytesum(self.stream.aggregate(4)) as u32),
Some(INT64) => Int64(bytesum(self.stream.aggregate(8)) as i64),
Some(MINKEY) => MinKey,
Some(MAXKEY) => MaxKey,
_ => return Err(~"an invalid element code was found")
};
ret.put(key, val);
elemcode = self.stream.expect(&[
DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID,
BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE,
INT32,TSTAMP,INT64,MINKEY,MAXKEY]);
if self.stream.has_next() { self.stream.pass(1); }
}
ret.size = size;
Ok(ret)
}
///Parse a string without denoting its length. Mainly for keys.
fn cstring(&mut self) -> ~str {
let is_0: &fn(&u8) -> bool = |&x| x == 0x00;
let s = from_bytes(self.stream.until(is_0));
self.stream.pass(1);
s
}
///Parse a double.
fn _double(&mut self) -> Document {
let mut u: u64 = 0;
for range(0,8) |i| {
//TODO: how will this hold up on big-endian architectures?
u |= (*self.stream.first() as u64 << ((8 * i)));
self.stream.pass(1);
}
let v: &f64 = unsafe { transmute(&u) };
Double(*v)
}
///Parse a string with length.
fn _string(&mut self) -> Document {
self.stream.pass(4); //skip length
let v = self.cstring();
UString(v)
}
///Parse an embedded object. May fail.
fn _embed(&mut self) -> Result<Document,~str> {
return self.document().chain(|s| Ok(Embedded(~s)));
}
///Parse an embedded array. May fail.
fn _array(&mut self) -> Result<Document,~str> {
return self.document().chain(|s| Ok(Array(~s)));
}
///Parse generic binary data.
fn _binary(&mut self) -> Document {
let count = bytesum(self.stream.aggregate(4));
let subtype = *(self.stream.first());
self.stream.pass(1);
let data = self.stream.aggregate(count as uint);
Binary(subtype, data)
}
///Parse a boolean.
fn _bool(&mut self) -> Document {
let ret = (*self.stream.first()) as bool;
self.stream.pass(1);
Bool(ret)
}
///Parse a regex.
fn _regex(&mut self) -> Document {
let s1 = self.cstring();
let s2 = self.cstring();
Regex(s1, s2)
}
fn _dbref(&mut self) -> Result<Document, ~str> |
///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")
}
}
///Parse a scoped javascript object.
fn _jscope(&mut self) -> Result<Document,~str> {
self.stream.pass(4);
let s = self.cstring();
let doc = self.document();
return doc.chain(|d| Ok(JScriptWithScope(s.clone(),~d)));
}
///Create a new parser with a given stream.
pub fn new(stream: T) -> BsonParser<T> { BsonParser { stream: stream } }
}
///Standalone decode binding.
///This is equivalent to initializing a parser and calling document().
pub fn decode(b: ~[u8]) -> Result<BsonDocument,~str> {
let mut parser = BsonParser::new(b);
parser.document()
}
#[cfg(test)]
mod tests {
use super::*;
use encode::*;
use extra::test::BenchHarness;
#[test]
fn test_decode_size() {
let doc = decode(~[10,0,0,0,10,100,100,100,0]);
assert_eq!(doc.unwrap().size, 10);
}
#[test]
fn test_cstring_decode() {
let stream: ~[u8] = ~[104,101,108,108,111,0];
let mut parser = BsonParser::new(stream);
assert_eq!(parser.cstring(), ~"hello");
}
#[test]
fn test_double_decode() {
let stream: ~[u8] = ~[110,134,27,240,249,33,9,64];
let mut parser = BsonParser::new(stream);
let d = parser._double();
match d {
Double(d2) => {
assert!(d2.approx_eq(&3.14159f64));
}
_ => fail!("failed in a test case; how did I get here?")
}
}
#[test]
fn test_document_decode() {
let stream1: ~[u8] = ~[11,0,0,0,8,102,111,111,0,1,0];
| {
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(),
Some(EMBED) => {
let doc = self._embed();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(ARRAY) => {
let doc = self._array();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(BINARY) => self._binary(),
Some(OBJID) => ObjectId(self.stream.aggregate(12)),
Some(BOOL) => self._bool(),
Some(UTCDATE) => UTCDate(bytesum(self.stream.aggregate(8)) as i64),
Some(NULL) => Null,
Some(REGEX) => self._regex(),
Some(DBREF) => {
let doc = self._dbref();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(JSCRIPT) => {
let doc = self._jscript();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(JSCOPE) => {
let doc = self._jscope();
match doc {
Ok(d) => d,
Err(e) => return Err(e)
}
}
Some(INT32) => Int32(bytesum(self.stream.aggregate(4)) as i32),
Some(TSTAMP) => Timestamp(bytesum(self.stream.aggregate(4)) as u32,
bytesum(self.stream.aggregate(4)) as u32),
Some(INT64) => Int64(bytesum(self.stream.aggregate(8)) as i64),
Some(MINKEY) => MinKey,
Some(MAXKEY) => MaxKey,
_ => return Err(~"an invalid element code was found")
};
ret.put(key, val);
elemcode = self.stream.expect(&[
DOUBLE,STRING,EMBED,ARRAY,BINARY,OBJID,
BOOL,UTCDATE,NULL,REGEX,DBREF,JSCRIPT,JSCOPE,
INT32,TSTAMP,INT64,MINKEY,MAXKEY]);
if self.stream.has_next() { self.stream.pass(1); }
}
ret.size = size;
Ok(ret)
}
///Parse a string without denoting its length. Mainly for keys.
fn cstring(&mut self) -> ~str {
let is_0: &fn(&u8) -> bool = |&x| x == 0x00;
let s = from_bytes(self.stream.until(is_0));
self.stream.pass(1);
s
}
///Parse a double.
fn _double(&mut self) -> Document {
let mut u: u64 = 0;
for range(0,8) |i| {
//TODO: how will this hold up on big-endian architectures?
u |= (*self.stream.first() as u64 << ((8 * i)));
self.stream.pass(1);
}
let v: &f64 = unsafe { transmute(&u) };
Double(*v)
}
///Parse a string with length.
fn _string(&mut self) -> Document {
self.stream.pass(4); //skip length
let v = self.cstring();
UString(v)
}
///Parse an embedded object. May fail.
fn _embed(&mut self) -> Result<Document,~str> {
return self.document().chain(|s| Ok(Embedded(~s)));
}
///Parse an embedded array. May fail.
fn _array(&mut self) -> Result<Document,~str> {
return self.document().chain(|s| Ok(Array(~s)));
}
///Parse generic binary data.
fn _binary(&mut self) -> Document {
let count = bytesum(self.stream.aggregate(4));
let subtype = *(self.stream.first());
self.stream.pass(1);
let data = self.stream.aggregate(count as uint);
Binary(subtype, data)
}
///Parse a boolean.
fn _bool(&mut self) -> Document {
let ret = (*self.stream.first()) as bool;
self.stream.pass(1);
Bool(ret)
}
///Parse a regex.
fn _regex(&mut self) -> Document {
let s1 = self.cstring();
let s2 = self.cstring();
Regex(s1, s2)
}
fn _dbref(&mut self) -> Result<Document, ~str> {
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)))
}
///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")
}
}
///Parse a scoped javascript object.
fn _jscope(&mut self) -> Result<Document,~str> {
self.stream.pass(4);
let s = self.cstring();
let doc = self.document();
return doc.chain(|d| Ok(JScriptWithScope(s.clone(),~d)));
}
///Create a new parser with a given stream.
pub fn new(stream: T) -> BsonParser<T> { BsonParser { stream: stream } }
}
///Standalone decode binding.
///This is equivalent to initializing a parser and calling document().
pub fn decode(b: ~[u8]) -> Result<BsonDocument,~str> {
let mut parser = BsonParser::new(b);
parser.document()
}
#[cfg(test)]
mod tests {
use super::*;
use encode::*;
use extra::test::BenchHarness;
#[test]
fn test_decode_size() {
let doc = decode(~[10,0,0,0,10,100,100,100,0]);
assert_eq!(doc.unwrap().size, 10);
}
#[test]
fn test_cstring_decode() {
let stream: ~[u8] = ~[104,101,108,108,111,0];
let mut parser = BsonParser::new(stream);
assert_eq!(parser.cstring(), ~"hello");
}
#[test]
fn test_double_decode() {
let stream: ~[u8] = ~[110,134,27,240,249,33,9,64];
let mut parser = BsonParser::new(stream);
let d = parser._double();
match d {
Double(d2) => {
assert!(d2.approx_eq(&3.14159f64));
}
_ => fail!("failed in a test case; how did I get here?")
}
}
#[test]
fn test_document_decode() {
let stream1: ~[u8] = ~[11,0,0,0,8,102,111,111,0,1,0];
let mut parser1 = BsonParser::new(stream1);
let mut doc1 = BsonDocument::new();
doc1.put(~"foo", Bool(true));
assert_eq!(parser1.document().unwrap(), doc1);
let stream2: ~[u8] = ~[45,0,0,0,4,102,111,111,0,22,0,0,0,2,48,0,
6,0,0,0,104,101,108,108,111,0,8,49,0,0,
0,2,98,97,122,0,4,0,0,0,113,117,120,0,0];
let mut inside = BsonDocument::new();
inside.put_all(~[(~"0", UString(~"hello")), (~"1", Bool(false))]);
let mut doc2 = BsonDocument::new();
doc2.put_all(~[(~"foo", Array(~inside.clone())), (~"baz", UString(~"qux"))]);
assert_eq!(decode(stream2).unwrap(), doc2);
}
#[test]
fn test_binary_decode() {
let stream: ~[u8] = ~[6,0,0,0,0,1,2,3,4,5,6];
let mut parser = BsonParser::new(stream);
assert_eq!(parser._binary(), Binary(0, ~[1,2,3,4,5,6]));
}
#[test]
fn | 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"
"go.skia.org/infra/go/skerr"
"go.skia.org/infra/go/sklog"
"go.skia.org/infra/go/util"
"go.skia.org/infra/go/vcsinfo"
"go.skia.org/infra/perf/go/btts"
"go.skia.org/infra/perf/go/config"
"go.skia.org/infra/perf/go/ingestcommon"
"go.skia.org/infra/perf/go/ingestevents"
"google.golang.org/api/option"
)
// flags
var (
configName = flag.String("config_name", "nano", "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')")
)
const (
// MAX_PARALLEL_RECEIVES is the number of Go routines we want to run. Determined experimentally.
MAX_PARALLEL_RECEIVES = 1
)
var (
// mutex protects hashCache.
mutex = sync.Mutex{}
// hashCache is a cache of results from calling vcs.IndexOf().
hashCache = map[string]int{}
// pubSubClient is a client used for both receiving PubSub messages from GCS
// and for sending ingestion notifications if the config specifies such a
// Topic.
pubSubClient *pubsub.Client
// The configuration data for the selected Perf instance.
cfg *config.PerfBigTableConfig
)
var (
// NonRecoverableError is returned if the error is non-recoverable and we
// should Ack the PubSub message. This might happen if, for example, a
// non-JSON file gets dropped in the bucket.
NonRecoverableError = errors.New("Non-recoverable ingestion error.")
)
// getParamsAndValues returns two parallel slices, each slice contains the
// params and then the float for a single value of a trace. It also returns the
// consolidated ParamSet built from all the Params.
func getParamsAndValues(b *ingestcommon.BenchData) ([]paramtools.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"] = configName
key.Add(paramtools.Params(b.Options))
// If there is an options map inside the result add it to the params.
if resultOptions, ok := result["options"]; ok {
if opts, ok := resultOptions.(map[string]interface{}); ok {
for k, vi := range opts {
// Ignore the very long and not useful GL_ values, we can retrieve
// them later via ptracestore.Details.
if strings.HasPrefix(k, "GL_") {
continue
}
if s, ok := vi.(string); ok {
key[k] = s
}
}
}
}
for k, vi := range result {
if k == "options" || k == "samples" {
continue
}
key["sub_result"] = k
floatVal, ok := vi.(float64)
if !ok {
sklog.Errorf("Found a non-float64 in %v", result)
continue
}
key = query.ForceValid(key)
params = append(params, key.Copy())
values = append(values, float32(floatVal))
ps.AddParams(key)
}
}
}
ps.Normalize()
return params, values, ps
}
func indexFromCache(hash string) (int, bool) {
mutex.Lock()
defer mutex.Unlock()
index, ok := hashCache[hash]
return index, ok
}
func indexToCache(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.Context, store *btts.BigTableTraceStore, vcs vcsinfo.VCS, filename string, r io.Reader, timestamp time.Time, branches []string) error {
benchData, err := ingestcommon.ParseBenchDataFromReader(r)
if err != nil {
sklog.Errorf("Failed to read or parse data: %s", err)
return NonRecoverableError
}
branch, ok := benchData.Key["branch"]
if ok {
if len(branches) > 0 {
if !util.In(branch, branches) {
return nil
}
}
} else {
sklog.Infof("No branch name.")
}
params, values, paramset := getParamsAndValues(benchData)
// Don't do any more work if there's no data to ingest.
if len(params) == 0 {
metrics2.GetCounter("perf_ingest_no_data_in_file", map[string]string{"branch": branch}).Inc(1)
sklog.Infof("No data in: %q", filename)
return nil
}
sklog.Infof("Processing %q", filename)
index, ok := indexFromCache(benchData.Hash)
if !ok {
var err error
index, err = vcs.IndexOf(ctx, benchData.Hash)
if err != nil {
if err := vcs.Update(context.Background(), true, false); err != nil {
return fmt.Errorf("Could not ingest, failed to pull: %s", err)
}
index, err = vcs.IndexOf(ctx, benchData.Hash)
if err != nil {
sklog.Errorf("Could not ingest, hash not found even after pulling %q: %s", benchData.Hash, err)
return NonRecoverableError
}
}
indexToCache(benchData.Hash, index)
}
err = store.WriteTraces(int32(index), params, values, paramset, filename, timestamp)
if err != nil {
return err
}
return sendPubSubEvent(params, paramset, filename)
}
// sendPubSubEvent sends the unencoded params and paramset found in a single
// ingested file to the PubSub topic specified in the selected Perf instances
// configuration data.
func sendPubSubEvent(params []paramtools.Params, paramset paramtools.ParamSet, filename string) error {
if cfg.FileIngestionTopicName == "" {
return nil
}
traceIDs := make([]string, 0, len(params))
for _, p := range params {
key, err := query.MakeKeyFast(p)
if err != nil {
continue
}
traceIDs = append(traceIDs, key)
}
ie := &ingestevents.IngestEvent{
TraceIDs: traceIDs,
ParamSet: paramset,
Filename: filename,
}
body, err := ingestevents.CreatePubSubBody(ie)
if err != nil {
return skerr.Wrapf(err, "Failed to encode PubSub body for topic: %q", cfg.FileIngestionTopicName)
}
msg := &pubsub.Message{
Data: body,
}
ctx := context.Background()
_, err = pubSubClient.Topic(cfg.FileIngestionTopicName).Publish(ctx, msg).Get(ctx)
return err
}
// Event is used to deserialize the PubSub data.
//
// The PubSub event data is a JSON serialized storage.ObjectAttrs object.
// See https://cloud.google.com/storage/docs/pubsub-notifications#payload
type Event struct {
Bucket string `json:"bucket"`
Name string `json:"name"`
}
func main() {
common.InitWithMust(
"perf-ingest",
common.PrometheusOpt(promPort),
common.MetricsLoggingOpt(),
)
// nackCounter is the number files we weren't able to ingest.
nackCounter := metrics2.GetCounter("nack", nil)
// ackCounter is the number files we were able to ingest.
ackCounter := metrics2.GetCounter("ack", nil)
ctx := context.Background()
var ok bool
cfg, ok = config.PERF_BIGTABLE_CONFIGS[*configName]
if !ok {
sklog.Fatalf("Invalid --config value: %q", *configName)
}
hostname, err := os.Hostname()
if err != nil {
sklog.Fatalf("Failed to get hostname: %s", err)
}
ts, err := auth.NewDefaultTokenSource(*local, bigtable.Scope, storage.ScopeReadOnly, pubsub.ScopePubSub)
if err != nil | "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"] = configName
key.Add(paramtools.Params(b.Options))
// If there is an options map inside the result add it to the params.
if resultOptions, ok := result["options"]; ok {
if opts, ok := resultOptions.(map[string]interface{}); ok {
for k, vi := range opts {
// Ignore the very long and not useful GL_ values, we can retrieve
// them later via ptracestore.Details.
if strings.HasPrefix(k, "GL_") {
continue
}
if s, ok := vi.(string); ok {
key[k] = s
}
}
}
}
for k, vi := range result {
if k == "options" || k == "samples" {
continue
}
key["sub_result"] = k
floatVal, ok := vi.(float64)
if !ok {
sklog.Errorf("Found a non-float64 in %v", result)
continue
}
key = query.ForceValid(key)
params = append(params, key.Copy())
values = append(values, float32(floatVal))
ps.AddParams(key)
}
}
}
ps.Normalize()
return params, values, ps
}
func indexFromCache(hash string) (int, bool) {
mutex.Lock()
defer mutex.Unlock()
index, ok := hashCache[hash]
return index, ok
}
func indexToCache(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.Context, store *btts.BigTableTraceStore, vcs vcsinfo.VCS, filename string, r io.Reader, timestamp time.Time, branches []string) error {
benchData, err := ingestcommon.ParseBenchDataFromReader(r)
if err != nil {
sklog.Errorf("Failed to read or parse data: %s", err)
return NonRecoverableError
}
branch, ok := benchData.Key["branch"]
if ok {
if len(branches) > 0 {
if !util.In(branch, branches) {
return nil
}
}
} else {
sklog.Infof("No branch name.")
}
params, values, paramset := getParamsAndValues(benchData)
// Don't do any more work if there's no data to ingest.
if len(params) == 0 {
metrics2.GetCounter("perf_ingest_no_data_in_file", map[string]string{"branch": branch}).Inc(1)
sklog.Infof("No data in: %q", filename)
return nil
}
sklog.Infof("Processing %q", filename)
index, ok := indexFromCache(benchData.Hash)
if !ok {
var err error
index, err = vcs.IndexOf(ctx, benchData.Hash)
if err != nil {
if err := vcs.Update(context.Background(), true, false); err != nil {
return fmt.Errorf("Could not ingest, failed to pull: %s", err)
}
index, err = vcs.IndexOf(ctx, benchData.Hash)
if err != nil {
sklog.Errorf("Could not ingest, hash not found even after pulling %q: %s", benchData.Hash, err)
return NonRecoverableError
}
}
indexToCache(benchData.Hash, index)
}
err = store.WriteTraces(int32(index), params, values, paramset, filename, timestamp)
if err != nil {
return err
}
return sendPubSubEvent(params, paramset, filename)
}
// sendPubSubEvent sends the unencoded params and paramset found in a single
// ingested file to the PubSub topic specified in the selected Perf instances
// configuration data.
func sendPubSubEvent(params []paramtools.Params, paramset paramtools.ParamSet, filename string) error {
if cfg.FileIngestionTopicName == "" {
return nil
}
traceIDs := make([]string, 0, len(params))
for _, p := range params {
key, err := query.MakeKeyFast(p)
if err != nil {
continue
}
traceIDs = append(traceIDs, key)
}
ie := &ingestevents.IngestEvent{
TraceIDs: traceIDs,
ParamSet: paramset,
Filename: filename,
}
body, err := ingestevents.CreatePubSubBody(ie)
if err != nil {
return skerr.Wrapf(err, "Failed to encode PubSub body for topic: %q", cfg.FileIngestionTopicName)
}
msg := &pubsub.Message{
Data: body,
}
ctx := context.Background()
_, err = pubSubClient.Topic(cfg.FileIngestionTopicName).Publish(ctx, msg).Get(ctx)
return err
}
// Event is used to deserialize the PubSub data.
//
// The PubSub event data is a JSON serialized storage.ObjectAttrs object.
// See https://cloud.google.com/storage/docs/pubsub-notifications#payload
type Event struct {
Bucket string `json:"bucket"`
Name string `json:"name"`
}
func main() {
common.InitWithMust(
"perf-ingest",
common.PrometheusOpt(promPort),
common.MetricsLoggingOpt(),
)
// nackCounter is the number files we weren't able to ingest.
nackCounter := metrics2.GetCounter("nack", nil)
// ackCounter is the number files we were able to ingest.
ackCounter := metrics2.GetCounter("ack", nil)
ctx := context.Background()
var ok bool
cfg, ok = config.PERF_BIGTABLE_CONFIGS[*configName]
if !ok {
sklog.Fatalf("Invalid --config value: %q", *configName)
}
hostname, err := os.Hostname()
if err != nil {
sklog.Fatalf("Failed to get hostname: %s", err)
}
ts, err := auth.NewDefaultTokenSource(*local, bigtable.Scope, storage.ScopeReadOnly, pubsub.ScopePubSub)
if err != nil {
sklog.Fatalf("Failed to create TokenSource: %s", err)
}
client := httputils.DefaultClientConfig().WithTokenSource(ts).WithoutRetries().Client()
gcsClient, err := storage.NewClient(ctx, option.WithHTTPClient(client))
if err != nil {
sklog.Fatalf("Failed to create GCS client: %s", err)
}
pubSubClient, err = pubsub.NewClient(ctx, cfg.Project, option.WithTokenSource(ts))
if err != nil {
sklog.Fatal(err)
}
// When running in production we have every instance use the same topic name so that
// they load-balance pulling items from the topic.
subName := fmt.Sprintf("%s-%s", cfg.Topic, "prod")
if *local {
// When running locally create a new topic for every host.
subName = fmt.Sprintf("%s-%s", cfg.Topic, hostname)
}
sub := pubSubClient.Subscription(subName)
ok, err = sub.Exists(ctx)
if err != nil {
sklog.Fatalf("Failed checking subscription existence: %s", err)
}
if !ok {
sub, err = pubSubClient.CreateSubscription(ctx, subName, pubsub.SubscriptionConfig{
Topic: pubSubClient.Topic(cfg.Topic),
})
if err != nil {
sklog.Fatalf("Failed creating subscription: %s", err)
}
}
// How many Go routines should be processing messages?
sub.ReceiveSettings.MaxOutstandingMessages = MAX_PARALLEL_RECEIVES
sub.ReceiveSettings.NumGoroutines = MAX_PARALLEL_RECEIVES
vcs, err := gitinfo.CloneOrUpdate(ctx, cfg.GitUrl, "/tmp/skia_ingest_checkout", true)
if err != nil {
sklog.Fatal(err)
}
store, err := btts.NewBigTableTraceStoreFromConfig(ctx, cfg, ts, true)
if err != nil {
sklog.Fatal(err)
}
// Process all incoming PubSub requests.
go func() {
for | {
// 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 success {
ackCounter.Inc(1)
msg.Ack()
} else {
nackCounter.Inc(1)
msg.Nack()
}
}()
// Decode the event, which is a GCS event that a file was written.
var event Event
if err := json.Unmarshal(msg.Data, &event); err != nil {
sklog.Error(err) | 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')")
)
const (
// MAX_PARALLEL_RECEIVES is the number of Go routines we want to run. Determined experimentally.
MAX_PARALLEL_RECEIVES = 1
)
var (
// mutex protects hashCache.
mutex = sync.Mutex{}
// hashCache is a cache of results from calling vcs.IndexOf().
hashCache = map[string]int{}
// pubSubClient is a client used for both receiving PubSub messages from GCS
// and for sending ingestion notifications if the config specifies such a
// Topic.
pubSubClient *pubsub.Client
// The configuration data for the selected Perf instance.
cfg *config.PerfBigTableConfig
)
var (
// NonRecoverableError is returned if the error is non-recoverable and we
// should Ack the PubSub message. This might happen if, for example, a
// non-JSON file gets dropped in the bucket.
NonRecoverableError = errors.New("Non-recoverable ingestion error.")
)
// getParamsAndValues returns two parallel slices, each slice contains the
// params and then the float for a single value of a trace. It also returns the
// consolidated ParamSet built from all the Params.
func getParamsAndValues(b *ingestcommon.BenchData) ([]paramtools.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"] = configName
key.Add(paramtools.Params(b.Options))
// If there is an options map inside the result add it to the params.
if resultOptions, ok := result["options"]; ok {
if opts, ok := resultOptions.(map[string]interface{}); ok {
for k, vi := range opts {
// Ignore the very long and not useful GL_ values, we can retrieve
// them later via ptracestore.Details.
if strings.HasPrefix(k, "GL_") {
continue
}
if s, ok := vi.(string); ok {
key[k] = s
}
}
}
}
for k, vi := range result {
if k == "options" || k == "samples" {
continue
}
key["sub_result"] = k
floatVal, ok := vi.(float64)
if !ok {
sklog.Errorf("Found a non-float64 in %v", result)
continue
}
key = query.ForceValid(key)
params = append(params, key.Copy())
values = append(values, float32(floatVal))
ps.AddParams(key)
}
}
}
ps.Normalize()
return params, values, ps
}
func indexFromCache(hash string) (int, bool) {
mutex.Lock()
defer mutex.Unlock()
index, ok := hashCache[hash]
return index, ok
}
func indexToCache(hash string, index int) |
// 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, timestamp time.Time, branches []string) error {
benchData, err := ingestcommon.ParseBenchDataFromReader(r)
if err != nil {
sklog.Errorf("Failed to read or parse data: %s", err)
return NonRecoverableError
}
branch, ok := benchData.Key["branch"]
if ok {
if len(branches) > 0 {
if !util.In(branch, branches) {
return nil
}
}
} else {
sklog.Infof("No branch name.")
}
params, values, paramset := getParamsAndValues(benchData)
// Don't do any more work if there's no data to ingest.
if len(params) == 0 {
metrics2.GetCounter("perf_ingest_no_data_in_file", map[string]string{"branch": branch}).Inc(1)
sklog.Infof("No data in: %q", filename)
return nil
}
sklog.Infof("Processing %q", filename)
index, ok := indexFromCache(benchData.Hash)
if !ok {
var err error
index, err = vcs.IndexOf(ctx, benchData.Hash)
if err != nil {
if err := vcs.Update(context.Background(), true, false); err != nil {
return fmt.Errorf("Could not ingest, failed to pull: %s", err)
}
index, err = vcs.IndexOf(ctx, benchData.Hash)
if err != nil {
sklog.Errorf("Could not ingest, hash not found even after pulling %q: %s", benchData.Hash, err)
return NonRecoverableError
}
}
indexToCache(benchData.Hash, index)
}
err = store.WriteTraces(int32(index), params, values, paramset, filename, timestamp)
if err != nil {
return err
}
return sendPubSubEvent(params, paramset, filename)
}
// sendPubSubEvent sends the unencoded params and paramset found in a single
// ingested file to the PubSub topic specified in the selected Perf instances
// configuration data.
func sendPubSubEvent(params []paramtools.Params, paramset paramtools.ParamSet, filename string) error {
if cfg.FileIngestionTopicName == "" {
return nil
}
traceIDs := make([]string, 0, len(params))
for _, p := range params {
key, err := query.MakeKeyFast(p)
if err != nil {
continue
}
traceIDs = append(traceIDs, key)
}
ie := &ingestevents.IngestEvent{
TraceIDs: traceIDs,
ParamSet: paramset,
Filename: filename,
}
body, err := ingestevents.CreatePubSubBody(ie)
if err != nil {
return skerr.Wrapf(err, "Failed to encode PubSub body for topic: %q", cfg.FileIngestionTopicName)
}
msg := &pubsub.Message{
Data: body,
}
ctx := context.Background()
_, err = pubSubClient.Topic(cfg.FileIngestionTopicName).Publish(ctx, msg).Get(ctx)
return err
}
// Event is used to deserialize the PubSub data.
//
// The PubSub event data is a JSON serialized storage.ObjectAttrs object.
// See https://cloud.google.com/storage/docs/pubsub-notifications#payload
type Event struct {
Bucket string `json:"bucket"`
Name string `json:"name"`
}
func main() {
common.InitWithMust(
"perf-ingest",
common.PrometheusOpt(promPort),
common.MetricsLoggingOpt(),
)
// nackCounter is the number files we weren't able to ingest.
nackCounter := metrics2.GetCounter("nack", nil)
// ackCounter is the number files we were able to ingest.
ackCounter := metrics2.GetCounter("ack", nil)
ctx := context.Background()
var ok bool
cfg, ok = config.PERF_BIGTABLE_CONFIGS[*configName]
if !ok {
sklog.Fatalf("Invalid --config value: %q", *configName)
}
hostname, err := os.Hostname()
if err != nil {
sklog.Fatalf("Failed to get hostname: %s", err)
}
ts, err := auth.NewDefaultTokenSource(*local, bigtable.Scope, storage.ScopeReadOnly, pubsub.ScopePubSub)
if err != nil {
sklog.Fatalf("Failed to create TokenSource: %s", err)
}
client := httputils.DefaultClientConfig().WithTokenSource(ts).WithoutRetries().Client()
gcsClient, err := storage.NewClient(ctx, option.WithHTTPClient(client))
if err != nil {
sklog.Fatalf("Failed to create GCS client: %s", err)
}
pubSubClient, err = pubsub.NewClient(ctx, cfg.Project, option.WithTokenSource(ts))
if err != nil {
sklog.Fatal(err)
}
// When running in production we have every instance use the same topic name so that
// they load-balance pulling items from the topic.
subName := fmt.Sprintf("%s-%s", cfg.Topic, "prod")
if *local {
// When running locally create a new topic for every host.
subName = fmt.Sprintf("%s-%s", cfg.Topic, hostname)
}
sub := pubSubClient.Subscription(subName)
ok, err = sub.Exists(ctx)
if err != nil {
sklog.Fatalf("Failed checking subscription existence: %s", err)
}
if ! | {
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')")
)
const (
// MAX_PARALLEL_RECEIVES is the number of Go routines we want to run. Determined experimentally.
MAX_PARALLEL_RECEIVES = 1
)
var (
// mutex protects hashCache.
mutex = sync.Mutex{}
// hashCache is a cache of results from calling vcs.IndexOf().
hashCache = map[string]int{}
// pubSubClient is a client used for both receiving PubSub messages from GCS
// and for sending ingestion notifications if the config specifies such a
// Topic.
pubSubClient *pubsub.Client
// The configuration data for the selected Perf instance.
cfg *config.PerfBigTableConfig
)
var (
// NonRecoverableError is returned if the error is non-recoverable and we
// should Ack the PubSub message. This might happen if, for example, a
// non-JSON file gets dropped in the bucket.
NonRecoverableError = errors.New("Non-recoverable ingestion error.")
)
// getParamsAndValues returns two parallel slices, each slice contains the
// params and then the float for a single value of a trace. It also returns the
// consolidated ParamSet built from all the Params.
func getParamsAndValues(b *ingestcommon.BenchData) ([]paramtools.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"] = configName
key.Add(paramtools.Params(b.Options))
// If there is an options map inside the result add it to the params.
if resultOptions, ok := result["options"]; ok {
if opts, ok := resultOptions.(map[string]interface{}); ok {
for k, vi := range opts {
// Ignore the very long and not useful GL_ values, we can retrieve
// them later via ptracestore.Details.
if strings.HasPrefix(k, "GL_") {
continue
}
if s, ok := vi.(string); ok {
key[k] = s
}
}
}
}
for k, vi := range result {
if k == "options" || k == "samples" {
continue
}
key["sub_result"] = k
floatVal, ok := vi.(float64)
if !ok {
sklog.Errorf("Found a non-float64 in %v", result)
continue
}
key = query.ForceValid(key)
params = append(params, key.Copy())
values = append(values, float32(floatVal))
ps.AddParams(key)
}
}
}
ps.Normalize()
return params, values, ps
}
func indexFromCache(hash string) (int, bool) {
mutex.Lock()
defer mutex.Unlock()
index, ok := hashCache[hash]
return index, ok
}
func | (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.Context, store *btts.BigTableTraceStore, vcs vcsinfo.VCS, filename string, r io.Reader, timestamp time.Time, branches []string) error {
benchData, err := ingestcommon.ParseBenchDataFromReader(r)
if err != nil {
sklog.Errorf("Failed to read or parse data: %s", err)
return NonRecoverableError
}
branch, ok := benchData.Key["branch"]
if ok {
if len(branches) > 0 {
if !util.In(branch, branches) {
return nil
}
}
} else {
sklog.Infof("No branch name.")
}
params, values, paramset := getParamsAndValues(benchData)
// Don't do any more work if there's no data to ingest.
if len(params) == 0 {
metrics2.GetCounter("perf_ingest_no_data_in_file", map[string]string{"branch": branch}).Inc(1)
sklog.Infof("No data in: %q", filename)
return nil
}
sklog.Infof("Processing %q", filename)
index, ok := indexFromCache(benchData.Hash)
if !ok {
var err error
index, err = vcs.IndexOf(ctx, benchData.Hash)
if err != nil {
if err := vcs.Update(context.Background(), true, false); err != nil {
return fmt.Errorf("Could not ingest, failed to pull: %s", err)
}
index, err = vcs.IndexOf(ctx, benchData.Hash)
if err != nil {
sklog.Errorf("Could not ingest, hash not found even after pulling %q: %s", benchData.Hash, err)
return NonRecoverableError
}
}
indexToCache(benchData.Hash, index)
}
err = store.WriteTraces(int32(index), params, values, paramset, filename, timestamp)
if err != nil {
return err
}
return sendPubSubEvent(params, paramset, filename)
}
// sendPubSubEvent sends the unencoded params and paramset found in a single
// ingested file to the PubSub topic specified in the selected Perf instances
// configuration data.
func sendPubSubEvent(params []paramtools.Params, paramset paramtools.ParamSet, filename string) error {
if cfg.FileIngestionTopicName == "" {
return nil
}
traceIDs := make([]string, 0, len(params))
for _, p := range params {
key, err := query.MakeKeyFast(p)
if err != nil {
continue
}
traceIDs = append(traceIDs, key)
}
ie := &ingestevents.IngestEvent{
TraceIDs: traceIDs,
ParamSet: paramset,
Filename: filename,
}
body, err := ingestevents.CreatePubSubBody(ie)
if err != nil {
return skerr.Wrapf(err, "Failed to encode PubSub body for topic: %q", cfg.FileIngestionTopicName)
}
msg := &pubsub.Message{
Data: body,
}
ctx := context.Background()
_, err = pubSubClient.Topic(cfg.FileIngestionTopicName).Publish(ctx, msg).Get(ctx)
return err
}
// Event is used to deserialize the PubSub data.
//
// The PubSub event data is a JSON serialized storage.ObjectAttrs object.
// See https://cloud.google.com/storage/docs/pubsub-notifications#payload
type Event struct {
Bucket string `json:"bucket"`
Name string `json:"name"`
}
func main() {
common.InitWithMust(
"perf-ingest",
common.PrometheusOpt(promPort),
common.MetricsLoggingOpt(),
)
// nackCounter is the number files we weren't able to ingest.
nackCounter := metrics2.GetCounter("nack", nil)
// ackCounter is the number files we were able to ingest.
ackCounter := metrics2.GetCounter("ack", nil)
ctx := context.Background()
var ok bool
cfg, ok = config.PERF_BIGTABLE_CONFIGS[*configName]
if !ok {
sklog.Fatalf("Invalid --config value: %q", *configName)
}
hostname, err := os.Hostname()
if err != nil {
sklog.Fatalf("Failed to get hostname: %s", err)
}
ts, err := auth.NewDefaultTokenSource(*local, bigtable.Scope, storage.ScopeReadOnly, pubsub.ScopePubSub)
if err != nil {
sklog.Fatalf("Failed to create TokenSource: %s", err)
}
client := httputils.DefaultClientConfig().WithTokenSource(ts).WithoutRetries().Client()
gcsClient, err := storage.NewClient(ctx, option.WithHTTPClient(client))
if err != nil {
sklog.Fatalf("Failed to create GCS client: %s", err)
}
pubSubClient, err = pubsub.NewClient(ctx, cfg.Project, option.WithTokenSource(ts))
if err != nil {
sklog.Fatal(err)
}
// When running in production we have every instance use the same topic name so that
// they load-balance pulling items from the topic.
subName := fmt.Sprintf("%s-%s", cfg.Topic, "prod")
if *local {
// When running locally create a new topic for every host.
subName = fmt.Sprintf("%s-%s", cfg.Topic, hostname)
}
sub := pubSubClient.Subscription(subName)
ok, err = sub.Exists(ctx)
if err != nil {
sklog.Fatalf("Failed checking subscription existence: %s", err)
}
if !ok | 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(LabelClause {
label: (*label).into(),
}));
}
root_clause.push(Clause::Or(labels_clause));
}
Query {
query: Clause::And(root_clause),
}
}
fn get_run_data(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(client, &String::from(runs.url()), None)?)?)
}
fn get_metadata(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, Vec<MetadataEntry>>> {
let mut metadata = wptfyi.metadata();
for product in ["firefox"].iter() {
metadata.add_product(product)
}
Ok(metadata::parse(&get(
client,
&String::from(metadata.url()),
None,
)?)?)
}
pub fn get_fx_failures(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
run_ids: &[i64],
labels: &[&str],
) -> Result<result::SearchData> {
let mut search = wptfyi.search();
for product in ["chrome", "firefox", "safari"].iter() {
search.add_product(product, "experimental")
}
search.set_query(run_ids, fx_failures_query(labels));
search.add_label("master");
Ok(search::parse(&post(
client,
&String::from(search.url()),
None,
search.body(),
)?)?)
}
pub fn get_interop_data(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, interop::YearData>> {
let runs = wptfyi.interop_data();
Ok(interop::parse(&get(
client,
&String::from(runs.url()),
None,
)?)?)
}
pub fn get_interop_categories(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, interop::Categories>> {
Ok(interop::parse_categories(&get(
client,
&String::from(wptfyi.interop_categories().url()),
None,
)?)?)
}
pub fn get_interop_scores(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
browser_channel: interop::BrowserChannel,
) -> Result<Vec<interop::ScoreRow>> {
Ok(interop::parse_scores(&get(
client,
&String::from(wptfyi.interop_scores(browser_channel).url()),
None,
)?)?)
}
fn latest_runs(runs: &[result::Run]) -> Result<Vec<&result::Run>> {
let mut runs_by_commit = run::runs_by_commit(runs);
let latest_rev = runs_by_commit
.iter()
.filter(|(_, value)| value.len() == 3)
.max_by(|(_, value_1), (_, value_2)| {
let date_1 = value_1.iter().map(|x| x.created_at).max();
let date_2 = value_2.iter().map(|x| x.created_at).max();
date_1.cmp(&date_2)
})
.map(|(key, _)| key.clone());
latest_rev
.and_then(|x| runs_by_commit.remove(&x))
.ok_or_else(|| anyhow!("Failed to find any complete runs"))
}
pub fn write_focus_area(
fyi: &Wptfyi,
client: &reqwest::blocking::Client,
name: &str,
focus_area: &FocusArea,
run_ids: &[i64],
categories_by_name: &BTreeMap<String, &Category>,
metadata: &BTreeMap<String, Vec<MetadataEntry>>,
) -> Result<()> {
if !focus_area.counts_toward_score {
return Ok(());
}
let labels = &categories_by_name
.get(name)
.ok_or_else(|| anyhow!("Didn't find category {}", name))?
.labels;
let path = format!("../docs/interop-2023/{}.csv", name);
let data_path = Path::new(&path);
let out_f = File::create(data_path)?;
let mut writer = csv::WriterBuilder::new()
.quote_style(csv::QuoteStyle::NonNumeric)
.from_writer(out_f);
let results = get_fx_failures(
&fyi,
&client,
&run_ids,
&labels
.iter()
.filter_map(|x| {
if x.starts_with("interop-") {
Some(x.as_ref())
} else {
None
}
})
.collect::<Vec<&str>>(),
)?;
let order = &["firefox", "chrome", "safari"];
let maybe_browser_list = results
.runs
.iter()
.map(|x| order.iter().position(|target| *target == x.browser_name))
.collect::<Option<Vec<usize>>>();
if maybe_browser_list.is_none() {
return Err(anyhow!("Didn't get results for all three browsers"));
}
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()];
for (output_idx, browser_idx) in browser_list.iter().enumerate() {
if let Some(status) = result.legacy_status.get(*browser_idx) {
if output_idx == 0 {
// For Firefox output the total as this is the number of failures
scores[output_idx].push_str(&format!("{}", status.total));
} else {
// For Firefox output the total as this is the number of failures
scores[output_idx].push_str(&format!("{}", status.total - status.passes));
}
}
}
let mut bugs = BTreeSet::new();
if let Some(test_meta) = metadata.get(&result.test) {
for metadata_entry in test_meta.iter() {
if metadata_entry.product != "firefox"
|| !metadata_entry
.url
.starts_with("https://bugzilla.mozilla.org")
{
continue;
}
// For now add all bugs irrespective of status or subtest
if let Ok(bug_url) = Url::parse(&metadata_entry.url) {
if let Some((_, bug_id)) = bug_url.query_pairs().find(|(key, _)| key == "id") {
bugs.insert(bug_id.into_owned());
}
}
}
}
let mut bugs_col = String::with_capacity(8 * bugs.len());
for bug in bugs.iter() {
if !bugs_col.is_empty() {
bugs_col.push(' ');
}
bugs_col.push_str(bug);
}
let record = &[&result.test, &scores[0], &scores[1], &scores[2], &bugs_col];
writer.write_record(record)?;
}
Ok(())
}
pub fn interop_columns(focus_areas: &BTreeMap<String, interop::FocusArea>) -> Vec<&str> {
let mut columns = Vec::with_capacity(focus_areas.len());
for (name, data) in focus_areas.iter() {
if data.counts_toward_score {
columns.push(name.as_ref());
}
}
columns
}
fn browser_score(browser: &str, columns: &[&str], row: &interop::ScoreRow) -> Result<f64> |
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::create(data_path)?;
let mut writer = csv::WriterBuilder::new()
.quote_style(csv::QuoteStyle | {
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_err(|_| anyhow!("Failed to parse score"))?;
total_score += value;
}
Ok(total_score as f64 / (10 * columns.len()) as f64)
} | 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(LabelClause {
label: (*label).into(),
}));
}
root_clause.push(Clause::Or(labels_clause));
}
Query {
query: Clause::And(root_clause),
}
}
fn get_run_data(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(client, &String::from(runs.url()), None)?)?)
}
fn get_metadata(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, Vec<MetadataEntry>>> {
let mut metadata = wptfyi.metadata();
for product in ["firefox"].iter() {
metadata.add_product(product)
}
Ok(metadata::parse(&get(
client,
&String::from(metadata.url()),
None,
)?)?)
}
pub fn get_fx_failures(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
run_ids: &[i64],
labels: &[&str],
) -> Result<result::SearchData> {
let mut search = wptfyi.search();
for product in ["chrome", "firefox", "safari"].iter() {
search.add_product(product, "experimental")
}
search.set_query(run_ids, fx_failures_query(labels));
search.add_label("master");
Ok(search::parse(&post(
client,
&String::from(search.url()),
None,
search.body(),
)?)?)
}
pub fn get_interop_data(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, interop::YearData>> {
let runs = wptfyi.interop_data();
Ok(interop::parse(&get(
client,
&String::from(runs.url()),
None,
)?)?)
}
pub fn get_interop_categories(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, interop::Categories>> {
Ok(interop::parse_categories(&get(
client,
&String::from(wptfyi.interop_categories().url()),
None,
)?)?)
}
pub fn get_interop_scores(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
browser_channel: interop::BrowserChannel,
) -> Result<Vec<interop::ScoreRow>> {
Ok(interop::parse_scores(&get(
client,
&String::from(wptfyi.interop_scores(browser_channel).url()),
None,
)?)?)
}
fn latest_runs(runs: &[result::Run]) -> Result<Vec<&result::Run>> {
let mut runs_by_commit = run::runs_by_commit(runs);
let latest_rev = runs_by_commit
.iter()
.filter(|(_, value)| value.len() == 3)
.max_by(|(_, value_1), (_, value_2)| {
let date_1 = value_1.iter().map(|x| x.created_at).max();
let date_2 = value_2.iter().map(|x| x.created_at).max();
date_1.cmp(&date_2)
})
.map(|(key, _)| key.clone());
latest_rev
.and_then(|x| runs_by_commit.remove(&x))
.ok_or_else(|| anyhow!("Failed to find any complete runs"))
}
pub fn write_focus_area(
fyi: &Wptfyi,
client: &reqwest::blocking::Client,
name: &str,
focus_area: &FocusArea,
run_ids: &[i64],
categories_by_name: &BTreeMap<String, &Category>,
metadata: &BTreeMap<String, Vec<MetadataEntry>>,
) -> Result<()> {
if !focus_area.counts_toward_score {
return Ok(());
}
let labels = &categories_by_name
.get(name)
.ok_or_else(|| anyhow!("Didn't find category {}", name))?
.labels;
let path = format!("../docs/interop-2023/{}.csv", name);
let data_path = Path::new(&path);
let out_f = File::create(data_path)?;
let mut writer = csv::WriterBuilder::new()
.quote_style(csv::QuoteStyle::NonNumeric)
.from_writer(out_f);
let results = get_fx_failures(
&fyi,
&client,
&run_ids,
&labels
.iter()
.filter_map(|x| {
if x.starts_with("interop-") {
Some(x.as_ref())
} else {
None
}
})
.collect::<Vec<&str>>(),
)?;
let order = &["firefox", "chrome", "safari"];
let maybe_browser_list = results
.runs
.iter()
.map(|x| order.iter().position(|target| *target == x.browser_name))
.collect::<Option<Vec<usize>>>();
if maybe_browser_list.is_none() |
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()];
for (output_idx, browser_idx) in browser_list.iter().enumerate() {
if let Some(status) = result.legacy_status.get(*browser_idx) {
if output_idx == 0 {
// For Firefox output the total as this is the number of failures
scores[output_idx].push_str(&format!("{}", status.total));
} else {
// For Firefox output the total as this is the number of failures
scores[output_idx].push_str(&format!("{}", status.total - status.passes));
}
}
}
let mut bugs = BTreeSet::new();
if let Some(test_meta) = metadata.get(&result.test) {
for metadata_entry in test_meta.iter() {
if metadata_entry.product != "firefox"
|| !metadata_entry
.url
.starts_with("https://bugzilla.mozilla.org")
{
continue;
}
// For now add all bugs irrespective of status or subtest
if let Ok(bug_url) = Url::parse(&metadata_entry.url) {
if let Some((_, bug_id)) = bug_url.query_pairs().find(|(key, _)| key == "id") {
bugs.insert(bug_id.into_owned());
}
}
}
}
let mut bugs_col = String::with_capacity(8 * bugs.len());
for bug in bugs.iter() {
if !bugs_col.is_empty() {
bugs_col.push(' ');
}
bugs_col.push_str(bug);
}
let record = &[&result.test, &scores[0], &scores[1], &scores[2], &bugs_col];
writer.write_record(record)?;
}
Ok(())
}
pub fn interop_columns(focus_areas: &BTreeMap<String, interop::FocusArea>) -> Vec<&str> {
let mut columns = Vec::with_capacity(focus_areas.len());
for (name, data) in focus_areas.iter() {
if data.counts_toward_score {
columns.push(name.as_ref());
}
}
columns
}
fn browser_score(browser: &str, columns: &[&str], row: &interop::ScoreRow) -> Result<f64> {
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_err(|_| anyhow!("Failed to parse score"))?;
total_score += value;
}
Ok(total_score as f64 / (10 * columns.len()) as f64)
}
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::create(data_path)?;
let mut writer = csv::WriterBuilder::new()
.quote_style(csv::QuoteStyle | {
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.push(Clause::Label(LabelClause {
label: (*label).into(),
}));
}
root_clause.push(Clause::Or(labels_clause));
}
Query {
query: Clause::And(root_clause),
}
}
fn | (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(client, &String::from(runs.url()), None)?)?)
}
fn get_metadata(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, Vec<MetadataEntry>>> {
let mut metadata = wptfyi.metadata();
for product in ["firefox"].iter() {
metadata.add_product(product)
}
Ok(metadata::parse(&get(
client,
&String::from(metadata.url()),
None,
)?)?)
}
pub fn get_fx_failures(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
run_ids: &[i64],
labels: &[&str],
) -> Result<result::SearchData> {
let mut search = wptfyi.search();
for product in ["chrome", "firefox", "safari"].iter() {
search.add_product(product, "experimental")
}
search.set_query(run_ids, fx_failures_query(labels));
search.add_label("master");
Ok(search::parse(&post(
client,
&String::from(search.url()),
None,
search.body(),
)?)?)
}
pub fn get_interop_data(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, interop::YearData>> {
let runs = wptfyi.interop_data();
Ok(interop::parse(&get(
client,
&String::from(runs.url()),
None,
)?)?)
}
pub fn get_interop_categories(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, interop::Categories>> {
Ok(interop::parse_categories(&get(
client,
&String::from(wptfyi.interop_categories().url()),
None,
)?)?)
}
pub fn get_interop_scores(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
browser_channel: interop::BrowserChannel,
) -> Result<Vec<interop::ScoreRow>> {
Ok(interop::parse_scores(&get(
client,
&String::from(wptfyi.interop_scores(browser_channel).url()),
None,
)?)?)
}
fn latest_runs(runs: &[result::Run]) -> Result<Vec<&result::Run>> {
let mut runs_by_commit = run::runs_by_commit(runs);
let latest_rev = runs_by_commit
.iter()
.filter(|(_, value)| value.len() == 3)
.max_by(|(_, value_1), (_, value_2)| {
let date_1 = value_1.iter().map(|x| x.created_at).max();
let date_2 = value_2.iter().map(|x| x.created_at).max();
date_1.cmp(&date_2)
})
.map(|(key, _)| key.clone());
latest_rev
.and_then(|x| runs_by_commit.remove(&x))
.ok_or_else(|| anyhow!("Failed to find any complete runs"))
}
pub fn write_focus_area(
fyi: &Wptfyi,
client: &reqwest::blocking::Client,
name: &str,
focus_area: &FocusArea,
run_ids: &[i64],
categories_by_name: &BTreeMap<String, &Category>,
metadata: &BTreeMap<String, Vec<MetadataEntry>>,
) -> Result<()> {
if !focus_area.counts_toward_score {
return Ok(());
}
let labels = &categories_by_name
.get(name)
.ok_or_else(|| anyhow!("Didn't find category {}", name))?
.labels;
let path = format!("../docs/interop-2023/{}.csv", name);
let data_path = Path::new(&path);
let out_f = File::create(data_path)?;
let mut writer = csv::WriterBuilder::new()
.quote_style(csv::QuoteStyle::NonNumeric)
.from_writer(out_f);
let results = get_fx_failures(
&fyi,
&client,
&run_ids,
&labels
.iter()
.filter_map(|x| {
if x.starts_with("interop-") {
Some(x.as_ref())
} else {
None
}
})
.collect::<Vec<&str>>(),
)?;
let order = &["firefox", "chrome", "safari"];
let maybe_browser_list = results
.runs
.iter()
.map(|x| order.iter().position(|target| *target == x.browser_name))
.collect::<Option<Vec<usize>>>();
if maybe_browser_list.is_none() {
return Err(anyhow!("Didn't get results for all three browsers"));
}
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()];
for (output_idx, browser_idx) in browser_list.iter().enumerate() {
if let Some(status) = result.legacy_status.get(*browser_idx) {
if output_idx == 0 {
// For Firefox output the total as this is the number of failures
scores[output_idx].push_str(&format!("{}", status.total));
} else {
// For Firefox output the total as this is the number of failures
scores[output_idx].push_str(&format!("{}", status.total - status.passes));
}
}
}
let mut bugs = BTreeSet::new();
if let Some(test_meta) = metadata.get(&result.test) {
for metadata_entry in test_meta.iter() {
if metadata_entry.product != "firefox"
|| !metadata_entry
.url
.starts_with("https://bugzilla.mozilla.org")
{
continue;
}
// For now add all bugs irrespective of status or subtest
if let Ok(bug_url) = Url::parse(&metadata_entry.url) {
if let Some((_, bug_id)) = bug_url.query_pairs().find(|(key, _)| key == "id") {
bugs.insert(bug_id.into_owned());
}
}
}
}
let mut bugs_col = String::with_capacity(8 * bugs.len());
for bug in bugs.iter() {
if !bugs_col.is_empty() {
bugs_col.push(' ');
}
bugs_col.push_str(bug);
}
let record = &[&result.test, &scores[0], &scores[1], &scores[2], &bugs_col];
writer.write_record(record)?;
}
Ok(())
}
pub fn interop_columns(focus_areas: &BTreeMap<String, interop::FocusArea>) -> Vec<&str> {
let mut columns = Vec::with_capacity(focus_areas.len());
for (name, data) in focus_areas.iter() {
if data.counts_toward_score {
columns.push(name.as_ref());
}
}
columns
}
fn browser_score(browser: &str, columns: &[&str], row: &interop::ScoreRow) -> Result<f64> {
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_err(|_| anyhow!("Failed to parse score"))?;
total_score += value;
}
Ok(total_score as f64 / (10 * columns.len()) as f64)
}
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::create(data_path)?;
let mut writer = csv::WriterBuilder::new()
.quote_style(csv::QuoteStyle | 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.push(Clause::Label(LabelClause {
label: (*label).into(),
}));
}
root_clause.push(Clause::Or(labels_clause));
}
Query {
query: Clause::And(root_clause),
}
}
fn get_run_data(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(client, &String::from(runs.url()), None)?)?)
}
fn get_metadata(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, Vec<MetadataEntry>>> {
let mut metadata = wptfyi.metadata();
for product in ["firefox"].iter() {
metadata.add_product(product)
}
Ok(metadata::parse(&get(
client,
&String::from(metadata.url()),
None,
)?)?)
}
pub fn get_fx_failures(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
run_ids: &[i64],
labels: &[&str],
) -> Result<result::SearchData> {
let mut search = wptfyi.search();
for product in ["chrome", "firefox", "safari"].iter() {
search.add_product(product, "experimental")
}
search.set_query(run_ids, fx_failures_query(labels));
search.add_label("master");
Ok(search::parse(&post(
client,
&String::from(search.url()),
None,
search.body(),
)?)?)
}
pub fn get_interop_data(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, interop::YearData>> {
let runs = wptfyi.interop_data();
Ok(interop::parse(&get(
client,
&String::from(runs.url()),
None,
)?)?)
}
pub fn get_interop_categories(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
) -> Result<BTreeMap<String, interop::Categories>> {
Ok(interop::parse_categories(&get(
client,
&String::from(wptfyi.interop_categories().url()),
None,
)?)?)
}
pub fn get_interop_scores(
wptfyi: &Wptfyi,
client: &reqwest::blocking::Client,
browser_channel: interop::BrowserChannel,
) -> Result<Vec<interop::ScoreRow>> {
Ok(interop::parse_scores(&get(
client,
&String::from(wptfyi.interop_scores(browser_channel).url()),
None,
)?)?)
}
fn latest_runs(runs: &[result::Run]) -> Result<Vec<&result::Run>> {
let mut runs_by_commit = run::runs_by_commit(runs);
let latest_rev = runs_by_commit
.iter()
.filter(|(_, value)| value.len() == 3)
.max_by(|(_, value_1), (_, value_2)| {
let date_1 = value_1.iter().map(|x| x.created_at).max();
let date_2 = value_2.iter().map(|x| x.created_at).max();
date_1.cmp(&date_2)
})
.map(|(key, _)| key.clone());
latest_rev
.and_then(|x| runs_by_commit.remove(&x))
.ok_or_else(|| anyhow!("Failed to find any complete runs"))
}
pub fn write_focus_area(
fyi: &Wptfyi,
client: &reqwest::blocking::Client,
name: &str,
focus_area: &FocusArea,
run_ids: &[i64],
categories_by_name: &BTreeMap<String, &Category>,
metadata: &BTreeMap<String, Vec<MetadataEntry>>,
) -> Result<()> {
if !focus_area.counts_toward_score {
return Ok(());
}
let labels = &categories_by_name
.get(name)
.ok_or_else(|| anyhow!("Didn't find category {}", name))?
.labels;
let path = format!("../docs/interop-2023/{}.csv", name);
let data_path = Path::new(&path);
let out_f = File::create(data_path)?;
let mut writer = csv::WriterBuilder::new()
.quote_style(csv::QuoteStyle::NonNumeric)
.from_writer(out_f);
let results = get_fx_failures(
&fyi,
&client,
&run_ids,
&labels
.iter()
.filter_map(|x| {
if x.starts_with("interop-") {
Some(x.as_ref())
} else {
None
}
})
.collect::<Vec<&str>>(),
)?;
let order = &["firefox", "chrome", "safari"];
let maybe_browser_list = results
.runs
.iter()
.map(|x| order.iter().position(|target| *target == x.browser_name))
.collect::<Option<Vec<usize>>>();
if maybe_browser_list.is_none() {
return Err(anyhow!("Didn't get results for all three browsers"));
}
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()];
for (output_idx, browser_idx) in browser_list.iter().enumerate() {
if let Some(status) = result.legacy_status.get(*browser_idx) {
if output_idx == 0 {
// For Firefox output the total as this is the number of failures
scores[output_idx].push_str(&format!("{}", status.total));
} else {
// For Firefox output the total as this is the number of failures
scores[output_idx].push_str(&format!("{}", status.total - status.passes));
}
}
}
let mut bugs = BTreeSet::new();
if let Some(test_meta) = metadata.get(&result.test) {
for metadata_entry in test_meta.iter() {
if metadata_entry.product != "firefox"
|| !metadata_entry
.url
.starts_with("https://bugzilla.mozilla.org")
{
continue;
}
// For now add all bugs irrespective of status or subtest
if let Ok(bug_url) = Url::parse(&metadata_entry.url) {
if let Some((_, bug_id)) = bug_url.query_pairs().find(|(key, _)| key == "id") {
bugs.insert(bug_id.into_owned());
}
}
}
}
let mut bugs_col = String::with_capacity(8 * bugs.len());
for bug in bugs.iter() {
if !bugs_col.is_empty() {
bugs_col.push(' ');
}
bugs_col.push_str(bug);
}
let record = &[&result.test, &scores[0], &scores[1], &scores[2], &bugs_col];
writer.write_record(record)?;
}
Ok(())
}
pub fn interop_columns(focus_areas: &BTreeMap<String, interop::FocusArea>) -> Vec<&str> {
let mut columns = Vec::with_capacity(focus_areas.len());
for (name, data) in focus_areas.iter() {
if data.counts_toward_score {
columns.push(name.as_ref());
}
}
columns
}
fn browser_score(browser: &str, columns: &[&str], row: &interop::ScoreRow) -> Result<f64> {
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_err(|_| anyhow!("Failed to parse score"))?;
total_score += value;
}
Ok(total_score as f64 / (10 * columns.len()) as f64)
}
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::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;
this.favLanguage = instructorAttrs.favLanguage;
this.catchPhrase = instructorAttrs.catchPhrase;
}
demo (subject) {
console.log(`Today we are learning about ${subject}`);
}
grade (student, subject) {
console.log(`${student.name} receives a perfect score on ${subject}`);
}
popQuiz (student, subject) {
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.name} is docked ${points} points.`);
student.grade -= points;
}
}
}
// 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 the student's favorite subjects ['Html', 'CSS', 'JavaScript']
// * Student has the following methods:
// * `listsSubjects` a method that logs out all of the student's favoriteSubjects one by one.
// * `PRAssignment` a method that receives a subject as an argument and logs out that the `student.name has submitted a PR for {subject}`
// * `sprintChallenge` similar to PRAssignment but logs out `student.name has begun sprint challenge on {subject}`
class Student extends Person {
constructor (studentAttrs) {
super (studentAttrs);
this.previousBackground = studentAttrs.previousBackground;
this.className = studentAttrs.className;
this.favSubjects = studentAttrs.favSubjects; // Array!
this.grade = studentAttrs.grade;
}
listsSubjects () {
for (const subject of this.favSubjects) {
console.log(subject);
}
}
PRAssignment (subject) {
console.log(`${this.name} has submitted a PR for ${subject}`);
}
sprintChallenge (subject) {
console.log(`${this.name} has begun sprint challenge on ${subject}`)
}
graduate () {
if (this.grade > 70) {
console.log(`Congratulations, ${this.name}! You graduate with a ${this.grade}%, now go make money.`);
} else {
console.log(`Unfortunately a ${this.grade}% is not sufficient to graduate. Back to the TK for you, ${this.name}!`);
}
}
}
// Project Manager Class
// * Now that we have instructors and students, we'd be nowhere without our PM's
// * ProjectManagers are extensions of Instructors
// * ProjectManagers have the following uniqe props:
// * `gradClassName`: i.e. CS1
// * `favInstructor`: i.e. Sean
// * ProjectManangers have the following Methods:
// * `standUp` a method that takes in a slack channel and logs `{name} announces to {channel}, @channel standy times!
// * `debugsCode` a method that takes in a student object and a subject and logs out `{name} debugs {student.name}'s code on {subject}`
class ProjectManager extends Instructor {
constructor (pmAttrs) {
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}'s code on ${subject}`)
}
}
// Test classes
// Keep track of who's here:
let instructors = [];
let pms = [];
let students = [];
// Instructors:
const jimBob = new Instructor ({
name: 'JimBob',
age: '35',
location: 'SLC',
gender: 'M',
specialty: 'Frontend',
favLanguage: 'JavaScript',
catchPhrase: 'Let\'s take a 5-minute break!'
});
instructors.push('jimBob');
const janeBeth = new Instructor ({
name: 'JaneBeth',
age: '37',
location: 'LA',
gender: 'F',
specialty: 'CS',
favLanguage: 'C',
catchPhrase: 'Let\'s take a 7-minute break!'
});
instructors.push('janeBeth');
// Students:
const lilRoy = new Student ({
name: 'LittleRoy',
age: '27',
location: 'NYC',
gender: 'M',
previousBackground: 'Carpentry',
className: 'FSW16',
favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'],
grade: 85
});
students.push('lilRoy');
const bigRae = new Student ({
name: 'Big Raylene',
age: '22',
location: 'PDX',
gender: 'F',
previousBackground: 'Construction',
className: 'DS1',
favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'],
grade: 92
});
students.push('bigRae');
const thirdStudent = new Student ({
name: 'thirdStudent',
age: '22',
location: 'PDX',
gender: 'F',
previousBackground: 'Construction',
className: 'DS1',
favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'],
grade: 70
});
students.push('thirdStudent');
const fourthStudent = new Student ({
name: 'fourthStudent',
age: '27',
location: 'NYC',
gender: 'M',
previousBackground: 'Carpentry',
className: 'FSW16',
favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'],
grade: 77
});
students.push('fourthStudent');
// Project Managers:
const maryBeth = new ProjectManager ({
name: 'Mary Beth',
age: '25',
location: 'HOU',
gender: 'F',
specialty: 'Frontend',
favLanguage: 'JavaScript',
catchPhrase: 'You\'re all doing great!',
gradClassName: 'FSW13',
favInstructor: 'JimBob',
});
pms.push('maryBeth');
const michaelBen = new ProjectManager ({
name: 'Michael Ben',
age: '24',
location: 'BR',
gender: 'M',
specialty: 'Backend',
favLanguage: 'Ruby',
catchPhrase: 'Keep it up y\'all!',
gradClassName: 'FSW14',
favInstructor: 'JaneBeth',
});
pms.push('michaelBen');
// // Test that instances are working
// // jimBob tests:
// console.log(jimBob.name) // 'JimBob'
// console.log(jimBob.age) // '35',
// console.log(jimBob.location) // 'SLC', | // 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) // 'LA',
// console.log(janeBeth.gender) // 'F',
// console.log(janeBeth.specialty) // 'CS',
// console.log(janeBeth.favLanguage) // 'C',
// console.log(janeBeth.catchPhrase) // 'Let\'s take a 7-minute break!'
// janeBeth.demo('CS');
// janeBeth.grade(lilRoy, 'CS');
// // lilRoy tests:
// console.log(lilRoy.name) //: 'LittleRoy',
// console.log(lilRoy.age) //: '27',
// console.log(lilRoy.location) //: 'NYC',
// console.log(lilRoy.gender) //: 'M',
// console.log(lilRoy.previousBackground) //: 'Carpentry',
// console.log(lilRoy.className) //: 'FSW16',
// console.log(lilRoy.favSubjects) //: ['Preprocessing', 'Symantec Markup', 'Array Methods']
// lilRoy.listsSubjects();
// lilRoy.PRAssignment('JS-I');
// lilRoy.sprintChallenge('JavaScript');
// // bigRae tests:
// console.log(bigRae.name) //: 'Big Raylene',
// console.log(bigRae.age) //: '22',
// console.log(bigRae.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;
this.favLanguage = instructorAttrs.favLanguage;
this.catchPhrase = instructorAttrs.catchPhrase;
}
demo (subject) {
console.log(`Today we are learning about ${subject}`);
}
grade (student, subject) {
console.log(`${student.name} receives a perfect score on ${subject}`);
}
popQuiz (student, subject) |
}
// 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 the student's favorite subjects ['Html', 'CSS', 'JavaScript']
// * Student has the following methods:
// * `listsSubjects` a method that logs out all of the student's favoriteSubjects one by one.
// * `PRAssignment` a method that receives a subject as an argument and logs out that the `student.name has submitted a PR for {subject}`
// * `sprintChallenge` similar to PRAssignment but logs out `student.name has begun sprint challenge on {subject}`
class Student extends Person {
constructor (studentAttrs) {
super (studentAttrs);
this.previousBackground = studentAttrs.previousBackground;
this.className = studentAttrs.className;
this.favSubjects = studentAttrs.favSubjects; // Array!
this.grade = studentAttrs.grade;
}
listsSubjects () {
for (const subject of this.favSubjects) {
console.log(subject);
}
}
PRAssignment (subject) {
console.log(`${this.name} has submitted a PR for ${subject}`);
}
sprintChallenge (subject) {
console.log(`${this.name} has begun sprint challenge on ${subject}`)
}
graduate () {
if (this.grade > 70) {
console.log(`Congratulations, ${this.name}! You graduate with a ${this.grade}%, now go make money.`);
} else {
console.log(`Unfortunately a ${this.grade}% is not sufficient to graduate. Back to the TK for you, ${this.name}!`);
}
}
}
// Project Manager Class
// * Now that we have instructors and students, we'd be nowhere without our PM's
// * ProjectManagers are extensions of Instructors
// * ProjectManagers have the following uniqe props:
// * `gradClassName`: i.e. CS1
// * `favInstructor`: i.e. Sean
// * ProjectManangers have the following Methods:
// * `standUp` a method that takes in a slack channel and logs `{name} announces to {channel}, @channel standy times!
// * `debugsCode` a method that takes in a student object and a subject and logs out `{name} debugs {student.name}'s code on {subject}`
class ProjectManager extends Instructor {
constructor (pmAttrs) {
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}'s code on ${subject}`)
}
}
// Test classes
// Keep track of who's here:
let instructors = [];
let pms = [];
let students = [];
// Instructors:
const jimBob = new Instructor ({
name: 'JimBob',
age: '35',
location: 'SLC',
gender: 'M',
specialty: 'Frontend',
favLanguage: 'JavaScript',
catchPhrase: 'Let\'s take a 5-minute break!'
});
instructors.push('jimBob');
const janeBeth = new Instructor ({
name: 'JaneBeth',
age: '37',
location: 'LA',
gender: 'F',
specialty: 'CS',
favLanguage: 'C',
catchPhrase: 'Let\'s take a 7-minute break!'
});
instructors.push('janeBeth');
// Students:
const lilRoy = new Student ({
name: 'LittleRoy',
age: '27',
location: 'NYC',
gender: 'M',
previousBackground: 'Carpentry',
className: 'FSW16',
favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'],
grade: 85
});
students.push('lilRoy');
const bigRae = new Student ({
name: 'Big Raylene',
age: '22',
location: 'PDX',
gender: 'F',
previousBackground: 'Construction',
className: 'DS1',
favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'],
grade: 92
});
students.push('bigRae');
const thirdStudent = new Student ({
name: 'thirdStudent',
age: '22',
location: 'PDX',
gender: 'F',
previousBackground: 'Construction',
className: 'DS1',
favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'],
grade: 70
});
students.push('thirdStudent');
const fourthStudent = new Student ({
name: 'fourthStudent',
age: '27',
location: 'NYC',
gender: 'M',
previousBackground: 'Carpentry',
className: 'FSW16',
favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'],
grade: 77
});
students.push('fourthStudent');
// Project Managers:
const maryBeth = new ProjectManager ({
name: 'Mary Beth',
age: '25',
location: 'HOU',
gender: 'F',
specialty: 'Frontend',
favLanguage: 'JavaScript',
catchPhrase: 'You\'re all doing great!',
gradClassName: 'FSW13',
favInstructor: 'JimBob',
});
pms.push('maryBeth');
const michaelBen = new ProjectManager ({
name: 'Michael Ben',
age: '24',
location: 'BR',
gender: 'M',
specialty: 'Backend',
favLanguage: 'Ruby',
catchPhrase: 'Keep it up y\'all!',
gradClassName: 'FSW14',
favInstructor: 'JaneBeth',
});
pms.push('michaelBen');
// // Test that instances are working
// // jimBob tests:
// console.log(jimBob.name) // 'JimBob'
// console.log(jimBob.age) // '35',
// console.log(jimBob.location) // 'SLC',
// console.log(jimBob.gender) // 'M',
// console.log(jimBob.specialty) // 'Frontend',
// 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) // 'LA',
// console.log(janeBeth.gender) // 'F',
// console.log(janeBeth.specialty) // 'CS',
// console.log(janeBeth.favLanguage) // 'C',
// console.log(janeBeth.catchPhrase) // 'Let\'s take a 7-minute break!'
// janeBeth.demo('CS');
// janeBeth.grade(lilRoy, 'CS');
// // lilRoy tests:
// console.log(lilRoy.name) //: 'LittleRoy',
// console.log(lilRoy.age) //: '27',
// console.log(lilRoy.location) //: 'NYC',
// console.log(lilRoy.gender) //: 'M',
// console.log(lilRoy.previousBackground) //: 'Carpentry',
// console.log(lilRoy.className) //: 'FSW16',
// console.log(lilRoy.favSubjects) //: ['Preprocessing', 'Symantec Markup', 'Array Methods']
// lilRoy.listsSubjects();
// lilRoy.PRAssignment('JS-I');
// lilRoy.sprintChallenge('JavaScript');
// // bigRae tests:
// console.log(bigRae.name) //: 'Big Raylene',
// console.log(bigRae.age) //: '22',
// console.log(bigRae.location) | {
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.name} is docked ${points} points.`);
student.grade -= points;
}
} | 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;
this.favLanguage = instructorAttrs.favLanguage;
this.catchPhrase = instructorAttrs.catchPhrase;
}
demo (subject) {
console.log(`Today we are learning about ${subject}`);
}
grade (student, subject) {
console.log(`${student.name} receives a perfect score on ${subject}`);
}
popQuiz (student, subject) {
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.name} is docked ${points} points.`);
student.grade -= points;
}
}
}
// 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 the student's favorite subjects ['Html', 'CSS', 'JavaScript']
// * Student has the following methods:
// * `listsSubjects` a method that logs out all of the student's favoriteSubjects one by one.
// * `PRAssignment` a method that receives a subject as an argument and logs out that the `student.name has submitted a PR for {subject}`
// * `sprintChallenge` similar to PRAssignment but logs out `student.name has begun sprint challenge on {subject}`
class Student extends Person {
constructor (studentAttrs) {
super (studentAttrs);
this.previousBackground = studentAttrs.previousBackground;
this.className = studentAttrs.className;
this.favSubjects = studentAttrs.favSubjects; // Array!
this.grade = studentAttrs.grade;
}
listsSubjects () {
for (const subject of this.favSubjects) {
console.log(subject);
}
}
PRAssignment (subject) {
console.log(`${this.name} has submitted a PR for ${subject}`);
}
sprintChallenge (subject) {
console.log(`${this.name} has begun sprint challenge on ${subject}`)
}
graduate () {
if (this.grade > 70) {
console.log(`Congratulations, ${this.name}! You graduate with a ${this.grade}%, now go make money.`);
} else {
console.log(`Unfortunately a ${this.grade}% is not sufficient to graduate. Back to the TK for you, ${this.name}!`);
}
}
}
// Project Manager Class
// * Now that we have instructors and students, we'd be nowhere without our PM's
// * ProjectManagers are extensions of Instructors
// * ProjectManagers have the following uniqe props:
// * `gradClassName`: i.e. CS1
// * `favInstructor`: i.e. Sean
// * ProjectManangers have the following Methods:
// * `standUp` a method that takes in a slack channel and logs `{name} announces to {channel}, @channel standy times!
// * `debugsCode` a method that takes in a student object and a subject and logs out `{name} debugs {student.name}'s code on {subject}`
class ProjectManager extends Instructor {
constructo | {
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}'s code on ${subject}`)
}
}
// Test classes
// Keep track of who's here:
let instructors = [];
let pms = [];
let students = [];
// Instructors:
const jimBob = new Instructor ({
name: 'JimBob',
age: '35',
location: 'SLC',
gender: 'M',
specialty: 'Frontend',
favLanguage: 'JavaScript',
catchPhrase: 'Let\'s take a 5-minute break!'
});
instructors.push('jimBob');
const janeBeth = new Instructor ({
name: 'JaneBeth',
age: '37',
location: 'LA',
gender: 'F',
specialty: 'CS',
favLanguage: 'C',
catchPhrase: 'Let\'s take a 7-minute break!'
});
instructors.push('janeBeth');
// Students:
const lilRoy = new Student ({
name: 'LittleRoy',
age: '27',
location: 'NYC',
gender: 'M',
previousBackground: 'Carpentry',
className: 'FSW16',
favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'],
grade: 85
});
students.push('lilRoy');
const bigRae = new Student ({
name: 'Big Raylene',
age: '22',
location: 'PDX',
gender: 'F',
previousBackground: 'Construction',
className: 'DS1',
favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'],
grade: 92
});
students.push('bigRae');
const thirdStudent = new Student ({
name: 'thirdStudent',
age: '22',
location: 'PDX',
gender: 'F',
previousBackground: 'Construction',
className: 'DS1',
favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'],
grade: 70
});
students.push('thirdStudent');
const fourthStudent = new Student ({
name: 'fourthStudent',
age: '27',
location: 'NYC',
gender: 'M',
previousBackground: 'Carpentry',
className: 'FSW16',
favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'],
grade: 77
});
students.push('fourthStudent');
// Project Managers:
const maryBeth = new ProjectManager ({
name: 'Mary Beth',
age: '25',
location: 'HOU',
gender: 'F',
specialty: 'Frontend',
favLanguage: 'JavaScript',
catchPhrase: 'You\'re all doing great!',
gradClassName: 'FSW13',
favInstructor: 'JimBob',
});
pms.push('maryBeth');
const michaelBen = new ProjectManager ({
name: 'Michael Ben',
age: '24',
location: 'BR',
gender: 'M',
specialty: 'Backend',
favLanguage: 'Ruby',
catchPhrase: 'Keep it up y\'all!',
gradClassName: 'FSW14',
favInstructor: 'JaneBeth',
});
pms.push('michaelBen');
// // Test that instances are working
// // jimBob tests:
// console.log(jimBob.name) // 'JimBob'
// console.log(jimBob.age) // '35',
// console.log(jimBob.location) // 'SLC',
// console.log(jimBob.gender) // 'M',
// console.log(jimBob.specialty) // 'Frontend',
// 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) // 'LA',
// console.log(janeBeth.gender) // 'F',
// console.log(janeBeth.specialty) // 'CS',
// console.log(janeBeth.favLanguage) // 'C',
// console.log(janeBeth.catchPhrase) // 'Let\'s take a 7-minute break!'
// janeBeth.demo('CS');
// janeBeth.grade(lilRoy, 'CS');
// // lilRoy tests:
// console.log(lilRoy.name) //: 'LittleRoy',
// console.log(lilRoy.age) //: '27',
// console.log(lilRoy.location) //: 'NYC',
// console.log(lilRoy.gender) //: 'M',
// console.log(lilRoy.previousBackground) //: 'Carpentry',
// console.log(lilRoy.className) //: 'FSW16',
// console.log(lilRoy.favSubjects) //: ['Preprocessing', 'Symantec Markup', 'Array Methods']
// lilRoy.listsSubjects();
// lilRoy.PRAssignment('JS-I');
// lilRoy.sprintChallenge('JavaScript');
// // bigRae tests:
// console.log(bigRae.name) //: 'Big Raylene',
// console.log(bigRae.age) //: '22',
// console.log(bigRae.location) | 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;
this.favLanguage = instructorAttrs.favLanguage;
this.catchPhrase = instructorAttrs.catchPhrase;
}
demo (subject) {
console.log(`Today we are learning about ${subject}`);
}
grade (student, subject) {
console.log(`${student.name} receives a perfect score on ${subject}`);
}
popQuiz (student, subject) {
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 |
}
}
// 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 the student's favorite subjects ['Html', 'CSS', 'JavaScript']
// * Student has the following methods:
// * `listsSubjects` a method that logs out all of the student's favoriteSubjects one by one.
// * `PRAssignment` a method that receives a subject as an argument and logs out that the `student.name has submitted a PR for {subject}`
// * `sprintChallenge` similar to PRAssignment but logs out `student.name has begun sprint challenge on {subject}`
class Student extends Person {
constructor (studentAttrs) {
super (studentAttrs);
this.previousBackground = studentAttrs.previousBackground;
this.className = studentAttrs.className;
this.favSubjects = studentAttrs.favSubjects; // Array!
this.grade = studentAttrs.grade;
}
listsSubjects () {
for (const subject of this.favSubjects) {
console.log(subject);
}
}
PRAssignment (subject) {
console.log(`${this.name} has submitted a PR for ${subject}`);
}
sprintChallenge (subject) {
console.log(`${this.name} has begun sprint challenge on ${subject}`)
}
graduate () {
if (this.grade > 70) {
console.log(`Congratulations, ${this.name}! You graduate with a ${this.grade}%, now go make money.`);
} else {
console.log(`Unfortunately a ${this.grade}% is not sufficient to graduate. Back to the TK for you, ${this.name}!`);
}
}
}
// Project Manager Class
// * Now that we have instructors and students, we'd be nowhere without our PM's
// * ProjectManagers are extensions of Instructors
// * ProjectManagers have the following uniqe props:
// * `gradClassName`: i.e. CS1
// * `favInstructor`: i.e. Sean
// * ProjectManangers have the following Methods:
// * `standUp` a method that takes in a slack channel and logs `{name} announces to {channel}, @channel standy times!
// * `debugsCode` a method that takes in a student object and a subject and logs out `{name} debugs {student.name}'s code on {subject}`
class ProjectManager extends Instructor {
constructor (pmAttrs) {
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}'s code on ${subject}`)
}
}
// Test classes
// Keep track of who's here:
let instructors = [];
let pms = [];
let students = [];
// Instructors:
const jimBob = new Instructor ({
name: 'JimBob',
age: '35',
location: 'SLC',
gender: 'M',
specialty: 'Frontend',
favLanguage: 'JavaScript',
catchPhrase: 'Let\'s take a 5-minute break!'
});
instructors.push('jimBob');
const janeBeth = new Instructor ({
name: 'JaneBeth',
age: '37',
location: 'LA',
gender: 'F',
specialty: 'CS',
favLanguage: 'C',
catchPhrase: 'Let\'s take a 7-minute break!'
});
instructors.push('janeBeth');
// Students:
const lilRoy = new Student ({
name: 'LittleRoy',
age: '27',
location: 'NYC',
gender: 'M',
previousBackground: 'Carpentry',
className: 'FSW16',
favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'],
grade: 85
});
students.push('lilRoy');
const bigRae = new Student ({
name: 'Big Raylene',
age: '22',
location: 'PDX',
gender: 'F',
previousBackground: 'Construction',
className: 'DS1',
favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'],
grade: 92
});
students.push('bigRae');
const thirdStudent = new Student ({
name: 'thirdStudent',
age: '22',
location: 'PDX',
gender: 'F',
previousBackground: 'Construction',
className: 'DS1',
favSubjects: ['Linear Algebra', 'Statistics', 'Python Lists'],
grade: 70
});
students.push('thirdStudent');
const fourthStudent = new Student ({
name: 'fourthStudent',
age: '27',
location: 'NYC',
gender: 'M',
previousBackground: 'Carpentry',
className: 'FSW16',
favSubjects: ['Preprocessing', 'Symantec Markup', 'Array Methods'],
grade: 77
});
students.push('fourthStudent');
// Project Managers:
const maryBeth = new ProjectManager ({
name: 'Mary Beth',
age: '25',
location: 'HOU',
gender: 'F',
specialty: 'Frontend',
favLanguage: 'JavaScript',
catchPhrase: 'You\'re all doing great!',
gradClassName: 'FSW13',
favInstructor: 'JimBob',
});
pms.push('maryBeth');
const michaelBen = new ProjectManager ({
name: 'Michael Ben',
age: '24',
location: 'BR',
gender: 'M',
specialty: 'Backend',
favLanguage: 'Ruby',
catchPhrase: 'Keep it up y\'all!',
gradClassName: 'FSW14',
favInstructor: 'JaneBeth',
});
pms.push('michaelBen');
// // Test that instances are working
// // jimBob tests:
// console.log(jimBob.name) // 'JimBob'
// console.log(jimBob.age) // '35',
// console.log(jimBob.location) // 'SLC',
// console.log(jimBob.gender) // 'M',
// console.log(jimBob.specialty) // 'Frontend',
// 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) // 'LA',
// console.log(janeBeth.gender) // 'F',
// console.log(janeBeth.specialty) // 'CS',
// console.log(janeBeth.favLanguage) // 'C',
// console.log(janeBeth.catchPhrase) // 'Let\'s take a 7-minute break!'
// janeBeth.demo('CS');
// janeBeth.grade(lilRoy, 'CS');
// // lilRoy tests:
// console.log(lilRoy.name) //: 'LittleRoy',
// console.log(lilRoy.age) //: '27',
// console.log(lilRoy.location) //: 'NYC',
// console.log(lilRoy.gender) //: 'M',
// console.log(lilRoy.previousBackground) //: 'Carpentry',
// console.log(lilRoy.className) //: 'FSW16',
// console.log(lilRoy.favSubjects) //: ['Preprocessing', 'Symantec Markup', 'Array Methods']
// lilRoy.listsSubjects();
// lilRoy.PRAssignment('JS-I');
// lilRoy.sprintChallenge('JavaScript');
// // bigRae tests:
// console.log(bigRae.name) //: 'Big Raylene',
// console.log(bigRae.age) //: '22',
// console.log(bigRae.location) | {
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})
return details
def get_disks():
"""Get list of attached disks using DiskPart."""
disks = []
try:
# Run script
result = run_diskpart(['list disk'])
except subprocess.CalledProcessError:
pass
else:
# Append disk numbers
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})
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
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
# Get volume letter or RAW status
output = result.stdout.decode().strip()
tmp = re.search(r'Volume\s+\d+\s+(\w|RAW)\s+', output)
if tmp:
if tmp.group(1).upper() == 'RAW':
details['FileSystem'] = RAW
else:
details['Letter'] = tmp.group(1)
# Remove empty lines from output
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# 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})
# Get MBR type / GPT GUID for extra details on "Unknown" partitions
guid = PARTITION_UIDS.get(details.get('Type').upper(), {})
if guid:
details.update({
'Description': guid.get('Description', '')[:29],
'OS': guid.get('OS', 'Unknown')[:27]})
if 'Letter' in details:
# Disk usage
try:
tmp = psutil.disk_usage('{}:\\'.format(details['Letter']))
except OSError as err:
details['FileSystem'] = 'Unknown'
details['Error'] = err.strerror
else:
details['Used Space'] = human_readable_size(tmp.used)
# fsutil details
cmd = [
'fsutil',
'fsinfo',
'volumeinfo',
'{}:'.format(details['Letter'])
]
try:
result = run_program(cmd)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
# Remove empty lines from output
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# Add "Feature" lines
details['File System Features'] = [s.strip() for s in tmp
if ':' not in s]
# 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})
# Set Volume Name
details['Name'] = details.get('Volume Name', '')
# Set FileSystem Type
if details.get('FileSystem', '') not in ['RAW', 'Unknown']:
details['FileSystem'] = details.get('File System Name', 'Unknown')
return details
def get_partitions(disk):
"""Get list of partition using DiskPart."""
partitions = []
script = [
'select disk {}'.format(disk['Number']),
'list partition']
try:
# Run script
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
# Append partition numbers
output = result.stdout.decode().strip()
regex = r'Partition\s+(\d+)\s+\w+\s+(\d+\s+\w+)\s+'
for tmp in re.findall(regex, output, re.IGNORECASE):
num = tmp[0]
size = human_readable_size(tmp[1])
partitions.append({'Number': num, 'Size': size})
return partitions
def get_table_type(disk):
"""Get disk partition table type using DiskPart."""
part_type = 'Unknown'
script = [
'select disk {}'.format(disk['Number']),
'uniqueid disk']
try:
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
if REGEX_DISK_GPT.search(output):
part_type = 'GPT'
elif REGEX_DISK_MBR.search(output):
part_type = 'MBR'
elif REGEX_DISK_RAW.search(output):
part_type = 'RAW'
return part_type
def get_volumes():
"""Get list of volumes using DiskPart."""
vols = []
try:
result = run_diskpart(['list volume'])
except subprocess.CalledProcessError:
pass
else:
# Append volume numbers
output = result.stdout.decode().strip()
for tmp in re.findall(r'Volume (\d+)\s+([A-Za-z]?)\s+', output):
vols.append({'Number': tmp[0], 'Letter': tmp[1]})
return vols
def is_bad_partition(par):
"""Check if the partition is accessible."""
return 'Letter' not in par or REGEX_BAD_PARTITION.search(par['FileSystem'])
def prep_disk_for_formatting(disk=None):
"""Gather details about the disk and its partitions."""
disk['Format Warnings'] = '\n'
width = len(str(len(disk['Partitions'])))
# Bail early
if disk is None:
raise Exception('Disk not provided.')
# Set boot method and partition table type
disk['Use GPT'] = True
if (get_boot_mode() == 'UEFI'):
if (not ask("Setup Windows to use UEFI booting?")):
disk['Use GPT'] = False
else:
if (ask("Setup Windows to use BIOS/Legacy booting?")):
disk['Use GPT'] = False
# Set Display and Warning Strings
if len(disk['Partitions']) == 0:
disk['Format Warnings'] += 'No partitions found\n'
for partition in disk['Partitions']:
display = '{size} {fs}'.format(
num = partition['Number'],
width = width,
size = partition['Size'],
fs = partition['FileSystem'])
if is_bad_partition(partition):
# Set display string using partition description & OS type
display += '\t\t{q}{name}{q}\t{desc} ({os})'.format(
display = display,
q = '"' if partition['Name'] != '' else '',
name = partition['Name'],
desc = partition['Description'],
os = partition['OS'])
else:
# List space used instead of partition description & OS type
display += ' (Used: {used})\t{q}{name}{q}'.format(
used = partition['Used Space'],
q = '"' if partition['Name'] != '' else '',
name = partition['Name'])
# For all partitions
partition['Display String'] = display
def reassign_volume_letter(letter, new_letter='I'):
"""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_letter
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')
# Run script
try:
run_diskpart(script)
except subprocess.CalledProcessError:
pass
def run_diskpart(script):
"""Run DiskPart script."""
tempfile = r'{}\diskpart.script'.format(global_vars['Env']['TMP'])
# Write script
with open(tempfile, 'w') as f:
for line in script:
f.write('{}\n'.format(line))
# Run script
cmd = [
r'{}\Windows\System32\diskpart.exe'.format(
global_vars['Env']['SYSTEMDRIVE']),
'/s', tempfile]
result = run_program(cmd)
sleep(2)
return result
| 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:
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
# Remove empty lines
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.strip(): value.strip() for (key, value) in tmp})
return details
def get_disks():
"""Get list of attached disks using DiskPart."""
disks = []
try:
# Run script
result = run_diskpart(['list disk'])
except subprocess.CalledProcessError:
pass
else:
# Append disk numbers
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})
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
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
# Get volume letter or RAW status
output = result.stdout.decode().strip()
tmp = re.search(r'Volume\s+\d+\s+(\w|RAW)\s+', output)
if tmp:
if tmp.group(1).upper() == 'RAW':
details['FileSystem'] = RAW
else:
details['Letter'] = tmp.group(1)
# Remove empty lines from output
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# 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})
# Get MBR type / GPT GUID for extra details on "Unknown" partitions
guid = PARTITION_UIDS.get(details.get('Type').upper(), {})
if guid:
details.update({
'Description': guid.get('Description', '')[:29],
'OS': guid.get('OS', 'Unknown')[:27]})
if 'Letter' in details:
# Disk usage
try:
tmp = psutil.disk_usage('{}:\\'.format(details['Letter']))
except OSError as err:
details['FileSystem'] = 'Unknown'
details['Error'] = err.strerror
else:
details['Used Space'] = human_readable_size(tmp.used)
# fsutil details
cmd = [
'fsutil',
'fsinfo',
'volumeinfo',
'{}:'.format(details['Letter'])
]
try:
result = run_program(cmd)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
# Remove empty lines from output
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# Add "Feature" lines
details['File System Features'] = [s.strip() for s in tmp
if ':' not in s]
# 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})
# Set Volume Name
details['Name'] = details.get('Volume Name', '')
# Set FileSystem Type
if details.get('FileSystem', '') not in ['RAW', 'Unknown']:
details['FileSystem'] = details.get('File System Name', 'Unknown')
return details
def get_partitions(disk):
"""Get list of partition using DiskPart."""
partitions = []
script = [
'select disk {}'.format(disk['Number']),
'list partition']
try:
# Run script
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
# Append partition numbers
output = result.stdout.decode().strip()
regex = r'Partition\s+(\d+)\s+\w+\s+(\d+\s+\w+)\s+'
for tmp in re.findall(regex, output, re.IGNORECASE):
num = tmp[0]
size = human_readable_size(tmp[1])
partitions.append({'Number': num, 'Size': size})
return partitions
def get_table_type(disk):
"""Get disk partition table type using DiskPart."""
part_type = 'Unknown'
script = [
'select disk {}'.format(disk['Number']),
'uniqueid disk']
try:
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
if REGEX_DISK_GPT.search(output):
part_type = 'GPT'
elif REGEX_DISK_MBR.search(output):
part_type = 'MBR'
elif REGEX_DISK_RAW.search(output):
part_type = 'RAW'
return part_type
def get_volumes():
"""Get list of volumes using DiskPart."""
vols = []
try:
result = run_diskpart(['list volume'])
except subprocess.CalledProcessError:
pass
else:
# Append volume numbers
output = result.stdout.decode().strip()
for tmp in re.findall(r'Volume (\d+)\s+([A-Za-z]?)\s+', output):
vols.append({'Number': tmp[0], 'Letter': tmp[1]})
return vols
def is_bad_partition(par):
"""Check if the partition is accessible."""
return 'Letter' not in par or REGEX_BAD_PARTITION.search(par['FileSystem'])
def prep_disk_for_formatting(disk=None):
"""Gather details about the disk and its partitions."""
disk['Format Warnings'] = '\n'
width = len(str(len(disk['Partitions'])))
# Bail early
if disk is None:
raise Exception('Disk not provided.')
# Set boot method and partition table type
disk['Use GPT'] = True
if (get_boot_mode() == 'UEFI'):
if (not ask("Setup Windows to use UEFI booting?")):
disk['Use GPT'] = False
else:
if (ask("Setup Windows to use BIOS/Legacy booting?")):
disk['Use GPT'] = False
# Set Display and Warning Strings
if len(disk['Partitions']) == 0:
disk['Format Warnings'] += 'No partitions found\n'
for partition in disk['Partitions']:
display = '{size} {fs}'.format(
num = partition['Number'],
width = width,
size = partition['Size'],
fs = partition['FileSystem'])
if is_bad_partition(partition):
# Set display string using partition description & OS type
display += '\t\t{q}{name}{q}\t{desc} ({os})'.format(
display = display,
q = '"' if partition['Name'] != '' else '',
name = partition['Name'],
desc = partition['Description'],
os = partition['OS'])
else:
# List space used instead of partition description & OS type
display += ' (Used: {used})\t{q}{name}{q}'.format(
used = partition['Used Space'],
q = '"' if partition['Name'] != '' else '',
name = partition['Name'])
# For all partitions
partition['Display String'] = display
def reassign_volume_letter(letter, new_letter='I'):
|
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')
# Run script
try:
run_diskpart(script)
except subprocess.CalledProcessError:
| """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_letter | 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:
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
# Remove empty lines
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.strip(): value.strip() for (key, value) in tmp})
return details
def get_disks():
"""Get list of attached disks using DiskPart."""
disks = []
try:
# Run script
result = run_diskpart(['list disk'])
except subprocess.CalledProcessError:
pass
else:
# Append disk numbers
|
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
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
# Get volume letter or RAW status
output = result.stdout.decode().strip()
tmp = re.search(r'Volume\s+\d+\s+(\w|RAW)\s+', output)
if tmp:
if tmp.group(1).upper() == 'RAW':
details['FileSystem'] = RAW
else:
details['Letter'] = tmp.group(1)
# Remove empty lines from output
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# 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})
# Get MBR type / GPT GUID for extra details on "Unknown" partitions
guid = PARTITION_UIDS.get(details.get('Type').upper(), {})
if guid:
details.update({
'Description': guid.get('Description', '')[:29],
'OS': guid.get('OS', 'Unknown')[:27]})
if 'Letter' in details:
# Disk usage
try:
tmp = psutil.disk_usage('{}:\\'.format(details['Letter']))
except OSError as err:
details['FileSystem'] = 'Unknown'
details['Error'] = err.strerror
else:
details['Used Space'] = human_readable_size(tmp.used)
# fsutil details
cmd = [
'fsutil',
'fsinfo',
'volumeinfo',
'{}:'.format(details['Letter'])
]
try:
result = run_program(cmd)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
# Remove empty lines from output
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# Add "Feature" lines
details['File System Features'] = [s.strip() for s in tmp
if ':' not in s]
# 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})
# Set Volume Name
details['Name'] = details.get('Volume Name', '')
# Set FileSystem Type
if details.get('FileSystem', '') not in ['RAW', 'Unknown']:
details['FileSystem'] = details.get('File System Name', 'Unknown')
return details
def get_partitions(disk):
"""Get list of partition using DiskPart."""
partitions = []
script = [
'select disk {}'.format(disk['Number']),
'list partition']
try:
# Run script
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
# Append partition numbers
output = result.stdout.decode().strip()
regex = r'Partition\s+(\d+)\s+\w+\s+(\d+\s+\w+)\s+'
for tmp in re.findall(regex, output, re.IGNORECASE):
num = tmp[0]
size = human_readable_size(tmp[1])
partitions.append({'Number': num, 'Size': size})
return partitions
def get_table_type(disk):
"""Get disk partition table type using DiskPart."""
part_type = 'Unknown'
script = [
'select disk {}'.format(disk['Number']),
'uniqueid disk']
try:
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
if REGEX_DISK_GPT.search(output):
part_type = 'GPT'
elif REGEX_DISK_MBR.search(output):
part_type = 'MBR'
elif REGEX_DISK_RAW.search(output):
part_type = 'RAW'
return part_type
def get_volumes():
"""Get list of volumes using DiskPart."""
vols = []
try:
result = run_diskpart(['list volume'])
except subprocess.CalledProcessError:
pass
else:
# Append volume numbers
output = result.stdout.decode().strip()
for tmp in re.findall(r'Volume (\d+)\s+([A-Za-z]?)\s+', output):
vols.append({'Number': tmp[0], 'Letter': tmp[1]})
return vols
def is_bad_partition(par):
"""Check if the partition is accessible."""
return 'Letter' not in par or REGEX_BAD_PARTITION.search(par['FileSystem'])
def prep_disk_for_formatting(disk=None):
"""Gather details about the disk and its partitions."""
disk['Format Warnings'] = '\n'
width = len(str(len(disk['Partitions'])))
# Bail early
if disk is None:
raise Exception('Disk not provided.')
# Set boot method and partition table type
disk['Use GPT'] = True
if (get_boot_mode() == 'UEFI'):
if (not ask("Setup Windows to use UEFI booting?")):
disk['Use GPT'] = False
else:
if (ask("Setup Windows to use BIOS/Legacy booting?")):
disk['Use GPT'] = False
# Set Display and Warning Strings
if len(disk['Partitions']) == 0:
disk['Format Warnings'] += 'No partitions found\n'
for partition in disk['Partitions']:
display = '{size} {fs}'.format(
num = partition['Number'],
width = width,
size = partition['Size'],
fs = partition['FileSystem'])
if is_bad_partition(partition):
# Set display string using partition description & OS type
display += '\t\t{q}{name}{q}\t{desc} ({os})'.format(
display = display,
q = '"' if partition['Name'] != '' else '',
name = partition['Name'],
desc = partition['Description'],
os = partition['OS'])
else:
# List space used instead of partition description & OS type
display += ' (Used: {used})\t{q}{name}{q}'.format(
used = partition['Used Space'],
q = '"' if partition['Name'] != '' else '',
name = partition['Name'])
# For all partitions
partition['Display String'] = display
def reassign_volume_letter(letter, new_letter='I'):
"""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_letter
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')
# Run script
try:
run_diskpart(script)
except subprocess.CalledProcessError:
| 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.strip(): value.strip() for (key, value) in tmp})
return details
def get_disks():
"""Get list of attached disks using DiskPart."""
disks = []
try:
# Run script
result = run_diskpart(['list disk'])
except subprocess.CalledProcessError:
pass
else:
# Append disk numbers
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})
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
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
# Get volume letter or RAW status
output = result.stdout.decode().strip()
tmp = re.search(r'Volume\s+\d+\s+(\w|RAW)\s+', output)
if tmp:
if tmp.group(1).upper() == 'RAW':
details['FileSystem'] = RAW
else:
details['Letter'] = tmp.group(1)
# Remove empty lines from output
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# 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})
# Get MBR type / GPT GUID for extra details on "Unknown" partitions
guid = PARTITION_UIDS.get(details.get('Type').upper(), {})
if guid:
details.update({
'Description': guid.get('Description', '')[:29],
'OS': guid.get('OS', 'Unknown')[:27]})
if 'Letter' in details:
# Disk usage
try:
tmp = psutil.disk_usage('{}:\\'.format(details['Letter']))
except OSError as err:
details['FileSystem'] = 'Unknown'
details['Error'] = err.strerror
else:
details['Used Space'] = human_readable_size(tmp.used)
# fsutil details
cmd = [
'fsutil',
'fsinfo',
'volumeinfo',
'{}:'.format(details['Letter'])
]
try:
result = run_program(cmd)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
# Remove empty lines from output
tmp = [s.strip() for s in output.splitlines() if s.strip() != '']
# Add "Feature" lines
details['File System Features'] = [s.strip() for s in tmp
if ':' not in s]
# 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})
# Set Volume Name
details['Name'] = details.get('Volume Name', '')
# Set FileSystem Type
if details.get('FileSystem', '') not in ['RAW', 'Unknown']:
details['FileSystem'] = details.get('File System Name', 'Unknown')
return details
def get_partitions(disk):
"""Get list of partition using DiskPart."""
partitions = []
script = [
'select disk {}'.format(disk['Number']),
'list partition']
try:
# Run script
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
# Append partition numbers
output = result.stdout.decode().strip()
regex = r'Partition\s+(\d+)\s+\w+\s+(\d+\s+\w+)\s+'
for tmp in re.findall(regex, output, re.IGNORECASE):
num = tmp[0]
size = human_readable_size(tmp[1])
partitions.append({'Number': num, 'Size': size})
return partitions
def get_table_type(disk):
"""Get disk partition table type using DiskPart."""
part_type = 'Unknown'
script = [
'select disk {}'.format(disk['Number']),
'uniqueid disk']
try:
result = run_diskpart(script)
except subprocess.CalledProcessError:
pass
else:
output = result.stdout.decode().strip()
if REGEX_DISK_GPT.search(output):
part_type = 'GPT'
elif REGEX_DISK_MBR.search(output):
part_type = 'MBR'
elif REGEX_DISK_RAW.search(output):
part_type = 'RAW'
return part_type
def get_volumes():
"""Get list of volumes using DiskPart."""
vols = []
try:
result = run_diskpart(['list volume'])
except subprocess.CalledProcessError:
pass
else:
# Append volume numbers
output = result.stdout.decode().strip()
for tmp in re.findall(r'Volume (\d+)\s+([A-Za-z]?)\s+', output):
vols.append({'Number': tmp[0], 'Letter': tmp[1]})
return vols
def is_bad_partition(par):
"""Check if the partition is accessible."""
return 'Letter' not in par or REGEX_BAD_PARTITION.search(par['FileSystem'])
def prep_disk_for_formatting(disk=None):
"""Gather details about the disk and its partitions."""
disk['Format Warnings'] = '\n'
width = len(str(len(disk['Partitions'])))
# Bail early
if disk is None:
raise Exception('Disk not provided.')
# Set boot method and partition table type
disk['Use GPT'] = True
if (get_boot_mode() == 'UEFI'):
if (not ask("Setup Windows to use UEFI booting?")):
disk['Use GPT'] = False
else:
if (ask("Setup Windows to use BIOS/Legacy booting?")):
disk['Use GPT'] = False
# Set Display and Warning Strings
if len(disk['Partitions']) == 0:
disk['Format Warnings'] += 'No partitions found\n'
for partition in disk['Partitions']:
display = '{size} {fs}'.format(
num = partition['Number'],
width = width,
size = partition['Size'],
fs = partition['FileSystem'])
if is_bad_partition(partition):
# Set display string using partition description & OS type
display += '\t\t{q}{name}{q}\t{desc} ({os})'.format(
display = display,
q = '"' if partition['Name'] != '' else '',
name = partition['Name'],
desc = partition['Description'],
os = partition['OS'])
else:
# List space used instead of partition description & OS type
display += ' (Used: {used})\t{q}{name}{q}'.format(
used = partition['Used Space'],
q = '"' if partition['Name'] != '' else '',
name = partition['Name'])
# For all partitions
partition['Display String'] = display
def reassign_volume_letter(letter, new_letter='I'):
"""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_letter
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')
# Run script
try:
run_diskpart(script)
except subprocess.CalledProcessError:
pass
def run_diskpart(script):
"""Run DiskPart script."""
tempfile = r'{}\diskpart.script'.format(global_vars['Env']['TMP'])
# Write script
with open(tempfile, 'w') as f:
for line in script:
f.write('{}\n'.format(line))
# Run script
cmd = [
r'{}\Windows\System32\diskpart.exe'.format(
global_vars['Env']['SYSTEMDRIVE']),
'/s', tempfile]
result = run_program(cmd)
sleep(2)
return result
def | 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]
return h == make_pw_hash(name, password, salt)
#cookie hashing and hash-validation functions
secret = 'weneverwalkalone'
def make_secure_cookie(val):
return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
def check_secure_val(secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_cookie(val):
return val
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
#blog handler
class BlogHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
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))
def render_content(self, template, **kw):
content = self.render_str(template, **kw)
self.render("index.html", content=content, user=self.get_logged_in_user(), **kw)
def is_logged_in(self):
user_id = None
user = None
user_id_str = self.request.cookies.get("user_id")
if user_id_str:
user_id = check_secure_val(user_id_str)
return user_id
def get_logged_in_user(self):
user_id = self.is_logged_in()
user = None
if user_id:
user = User.get_by_id(long(user_id))
return user
#welcome handler
class Welcome(BlogHandler):
def get(self):
cookie_val = self.request.cookies.get("user_id")#In this case we will get the value of key(in this case name)
if cookie_val:
user_id = check_secure_val(str(cookie_val))
u = User.get_by_id(int(user_id))
self.render("welcome.html", username = u.username)
else:
self.redirect("/signup")
# class for blog-post(subject and content) entries
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
def render(self):
self._render_text = self.content.replace('\n', '<br>')
return render_str("post.html", p = self)
# class for user entries
class User(db.Model):
username = db.StringProperty(required = True)
password = db.StringProperty(required = True)
email = db.StringProperty(required = False)
# RegEx for the username field
USERNAME_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
PASSWORD_RE = re.compile(r"^.{3,20}$")
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
# Validation for Usernames
def valid_username(username):
return USERNAME_RE.match(username)
def valid_password(password):
return PASSWORD_RE.match(password)
def valid_email(email):
return not email or EMAIL_RE.match(email)
#handler for signup
class Signup(BlogHandler):
def get(self):
self.render_content("signup.html")
def post(self):
have_error = False
user_name = self.request.get('username')
user_password = self.request.get('password')
user_verify = self.request.get('verify')
user_email = self.request.get('email')
name_error = password_error = verify_error = email_error = ""
if not valid_username(user_name):
name_error = "That's not a valid username"
have_error = True
if not valid_password(user_password):
password_error = "That's not a valid password"
have_error = True
elif user_password != user_verify:
verify_error = "Your passwords didn't match"
have_error = True
if not valid_email(user_email):
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_error)
else:
u = User.gql("WHERE username = '%s'"%user_name).get()
if u:
name_error = "That user already exists."
self.render_content("signup.html")
else:
# make salted password hash
h = make_pw_hash(user_name, user_password)
u = User(username=user_name, password=h,email=user_email)
u.put()
uid= str(make_secure_cookie(str(u.key().id()))) #dis is how we get the id from google data store(gapp engine)
#The Set-Cookie header which is add_header method will set the cookie name user_id(value,hash(value)) to its value
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid)
self.redirect("/welcome")
#login handler
class Login(BlogHandler):
def get(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_password, u.password):
uid= str(make_secure_cookie(str(u.key().id())))
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid)
self.redirect('/')
else:
msg = "Invalid login"
self.render_content("login-form.html", error = msg)
#logout handler
class Logout(BlogHandler):
def get(self):
self.response.headers.add_header("Set-Cookie", "user_id=; Path=/")
self.redirect("/signup")
def top_posts(update = False):
posts = memcache.get("top")
if posts is None or update:
posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
posts = list(posts) # to avoid querying in iterable
memcache.set("top", posts)
memcache.set("top_post_generated", time.time())
return posts
#main page
class MainPage(BlogHandler):
def get(self):
# posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
# caching for query above
posts = top_posts()
diff = time.time() - memcache.get("top_post_generated")
self.render_content("front.html", posts=posts, time_update=str(int(diff)))
def get_post(key): # cache function same as above but this one is for particular post
post = memcache.get('post')
if post and key == str(post.key().id()):
return post
else:
post = Post.get_by_id(int(key))
memcache.set('post', post)
memcache.set('post-generated', time.time())
return post
# Handler for a specific Entry
class SpecificPostHandler(BlogHandler):
def get(self, key):
post = get_post(key)
diff = time.time() - memcache.get('post-generated')
diff_str = "Queried %s seconds ago"%(str(int(diff)))
self.render_content("permalink.html", post=post, time_update=diff_str)
# Handler for posting newpoHandler for a specific Wiki Page Entrysts
class EditPageHandler(BlogHandler):
def get(self):
if self.is_logged_in():
post = top_posts()
self.render_content("newpost.html", post=post)
else:
self.redirect("/login")
def post(self):
if self.is_logged_in():
subject = self.request.get("subject")
content = self.request.get("content")
if subject and content:
p = Post(subject=subject, content=content)
p.put()
KEY = p.key().id()
top_posts(update = True)
self.redirect("/"+str(KEY), str(KEY))
else:
error = "subject and content, please!"
self.render_content("newpost.html", subject=subject, content=content, error=error)
else:
|
# /.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 python excepts data types dat nos how 2 convert in json which're list,dict..
| 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]
return h == make_pw_hash(name, password, salt)
#cookie hashing and hash-validation functions
secret = 'weneverwalkalone'
def make_secure_cookie(val):
return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
def check_secure_val(secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_cookie(val):
return val
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
#blog handler
class BlogHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
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))
def render_content(self, template, **kw):
content = self.render_str(template, **kw)
self.render("index.html", content=content, user=self.get_logged_in_user(), **kw)
def is_logged_in(self):
user_id = None
user = None
user_id_str = self.request.cookies.get("user_id")
if user_id_str:
user_id = check_secure_val(user_id_str)
return user_id
def get_logged_in_user(self):
user_id = self.is_logged_in()
user = None
if user_id:
user = User.get_by_id(long(user_id))
return user
#welcome handler
class Welcome(BlogHandler):
def get(self):
cookie_val = self.request.cookies.get("user_id")#In this case we will get the value of key(in this case name)
if cookie_val:
user_id = check_secure_val(str(cookie_val))
u = User.get_by_id(int(user_id))
self.render("welcome.html", username = u.username)
else:
self.redirect("/signup")
# class for blog-post(subject and content) entries
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
def render(self):
self._render_text = self.content.replace('\n', '<br>')
return render_str("post.html", p = self)
# class for user entries
class User(db.Model):
username = db.StringProperty(required = True)
password = db.StringProperty(required = True)
email = db.StringProperty(required = False)
# RegEx for the username field
USERNAME_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
PASSWORD_RE = re.compile(r"^.{3,20}$")
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
# Validation for Usernames
def valid_username(username):
return USERNAME_RE.match(username)
def valid_password(password):
return PASSWORD_RE.match(password)
def valid_email(email):
return not email or EMAIL_RE.match(email)
#handler for signup
class Signup(BlogHandler):
def get(self):
self.render_content("signup.html")
def post(self):
have_error = False
user_name = self.request.get('username')
user_password = self.request.get('password')
user_verify = self.request.get('verify')
user_email = self.request.get('email')
name_error = password_error = verify_error = email_error = ""
if not valid_username(user_name):
name_error = "That's not a valid username"
have_error = True
if not valid_password(user_password):
password_error = "That's not a valid password"
have_error = True
elif user_password != user_verify:
verify_error = "Your passwords didn't match"
have_error = True
if not valid_email(user_email):
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_error)
else:
u = User.gql("WHERE username = '%s'"%user_name).get()
if u:
name_error = "That user already exists."
self.render_content("signup.html")
else:
# make salted password hash
h = make_pw_hash(user_name, user_password)
u = User(username=user_name, password=h,email=user_email)
u.put()
uid= str(make_secure_cookie(str(u.key().id()))) #dis is how we get the id from google data store(gapp engine)
#The Set-Cookie header which is add_header method will set the cookie name user_id(value,hash(value)) to its value
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid)
self.redirect("/welcome")
#login handler
class Login(BlogHandler):
def | (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_password, u.password):
uid= str(make_secure_cookie(str(u.key().id())))
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid)
self.redirect('/')
else:
msg = "Invalid login"
self.render_content("login-form.html", error = msg)
#logout handler
class Logout(BlogHandler):
def get(self):
self.response.headers.add_header("Set-Cookie", "user_id=; Path=/")
self.redirect("/signup")
def top_posts(update = False):
posts = memcache.get("top")
if posts is None or update:
posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
posts = list(posts) # to avoid querying in iterable
memcache.set("top", posts)
memcache.set("top_post_generated", time.time())
return posts
#main page
class MainPage(BlogHandler):
def get(self):
# posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
# caching for query above
posts = top_posts()
diff = time.time() - memcache.get("top_post_generated")
self.render_content("front.html", posts=posts, time_update=str(int(diff)))
def get_post(key): # cache function same as above but this one is for particular post
post = memcache.get('post')
if post and key == str(post.key().id()):
return post
else:
post = Post.get_by_id(int(key))
memcache.set('post', post)
memcache.set('post-generated', time.time())
return post
# Handler for a specific Entry
class SpecificPostHandler(BlogHandler):
def get(self, key):
post = get_post(key)
diff = time.time() - memcache.get('post-generated')
diff_str = "Queried %s seconds ago"%(str(int(diff)))
self.render_content("permalink.html", post=post, time_update=diff_str)
# Handler for posting newpoHandler for a specific Wiki Page Entrysts
class EditPageHandler(BlogHandler):
def get(self):
if self.is_logged_in():
post = top_posts()
self.render_content("newpost.html", post=post)
else:
self.redirect("/login")
def post(self):
if self.is_logged_in():
subject = self.request.get("subject")
content = self.request.get("content")
if subject and content:
p = Post(subject=subject, content=content)
p.put()
KEY = p.key().id()
top_posts(update = True)
self.redirect("/"+str(KEY), str(KEY))
else:
error = "subject and content, please!"
self.render_content("newpost.html", subject=subject, content=content, error=error)
else:
self.redirect("/login")
# /.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 python excepts data types dat nos how 2 convert in json which're list,dict..
| 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]
return h == make_pw_hash(name, password, salt)
#cookie hashing and hash-validation functions
secret = 'weneverwalkalone'
def make_secure_cookie(val):
return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
def check_secure_val(secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_cookie(val):
return val
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
#blog handler
class BlogHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
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))
def render_content(self, template, **kw):
content = self.render_str(template, **kw)
self.render("index.html", content=content, user=self.get_logged_in_user(), **kw)
def is_logged_in(self):
user_id = None
user = None
user_id_str = self.request.cookies.get("user_id")
if user_id_str:
user_id = check_secure_val(user_id_str)
return user_id
def get_logged_in_user(self):
user_id = self.is_logged_in()
user = None
if user_id:
user = User.get_by_id(long(user_id))
return user
#welcome handler
class Welcome(BlogHandler):
def get(self):
cookie_val = self.request.cookies.get("user_id")#In this case we will get the value of key(in this case name)
if cookie_val:
user_id = check_secure_val(str(cookie_val))
u = User.get_by_id(int(user_id))
self.render("welcome.html", username = u.username)
else:
self.redirect("/signup")
# class for blog-post(subject and content) entries
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
def render(self):
self._render_text = self.content.replace('\n', '<br>')
return render_str("post.html", p = self)
# class for user entries
class User(db.Model):
username = db.StringProperty(required = True)
password = db.StringProperty(required = True)
email = db.StringProperty(required = False)
# RegEx for the username field
USERNAME_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
PASSWORD_RE = re.compile(r"^.{3,20}$")
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
# Validation for Usernames
def valid_username(username):
return USERNAME_RE.match(username)
def valid_password(password):
return PASSWORD_RE.match(password)
def valid_email(email):
return not email or EMAIL_RE.match(email)
#handler for signup
class Signup(BlogHandler):
def get(self):
self.render_content("signup.html")
def post(self):
have_error = False
user_name = self.request.get('username')
user_password = self.request.get('password')
user_verify = self.request.get('verify')
user_email = self.request.get('email')
name_error = password_error = verify_error = email_error = ""
if not valid_username(user_name):
name_error = "That's not a valid username"
have_error = True
if not valid_password(user_password):
password_error = "That's not a valid password"
have_error = True
elif user_password != user_verify:
verify_error = "Your passwords didn't match"
have_error = True | 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_error)
else:
u = User.gql("WHERE username = '%s'"%user_name).get()
if u:
name_error = "That user already exists."
self.render_content("signup.html")
else:
# make salted password hash
h = make_pw_hash(user_name, user_password)
u = User(username=user_name, password=h,email=user_email)
u.put()
uid= str(make_secure_cookie(str(u.key().id()))) #dis is how we get the id from google data store(gapp engine)
#The Set-Cookie header which is add_header method will set the cookie name user_id(value,hash(value)) to its value
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid)
self.redirect("/welcome")
#login handler
class Login(BlogHandler):
def get(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_password, u.password):
uid= str(make_secure_cookie(str(u.key().id())))
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid)
self.redirect('/')
else:
msg = "Invalid login"
self.render_content("login-form.html", error = msg)
#logout handler
class Logout(BlogHandler):
def get(self):
self.response.headers.add_header("Set-Cookie", "user_id=; Path=/")
self.redirect("/signup")
def top_posts(update = False):
posts = memcache.get("top")
if posts is None or update:
posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
posts = list(posts) # to avoid querying in iterable
memcache.set("top", posts)
memcache.set("top_post_generated", time.time())
return posts
#main page
class MainPage(BlogHandler):
def get(self):
# posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
# caching for query above
posts = top_posts()
diff = time.time() - memcache.get("top_post_generated")
self.render_content("front.html", posts=posts, time_update=str(int(diff)))
def get_post(key): # cache function same as above but this one is for particular post
post = memcache.get('post')
if post and key == str(post.key().id()):
return post
else:
post = Post.get_by_id(int(key))
memcache.set('post', post)
memcache.set('post-generated', time.time())
return post
# Handler for a specific Entry
class SpecificPostHandler(BlogHandler):
def get(self, key):
post = get_post(key)
diff = time.time() - memcache.get('post-generated')
diff_str = "Queried %s seconds ago"%(str(int(diff)))
self.render_content("permalink.html", post=post, time_update=diff_str)
# Handler for posting newpoHandler for a specific Wiki Page Entrysts
class EditPageHandler(BlogHandler):
def get(self):
if self.is_logged_in():
post = top_posts()
self.render_content("newpost.html", post=post)
else:
self.redirect("/login")
def post(self):
if self.is_logged_in():
subject = self.request.get("subject")
content = self.request.get("content")
if subject and content:
p = Post(subject=subject, content=content)
p.put()
KEY = p.key().id()
top_posts(update = True)
self.redirect("/"+str(KEY), str(KEY))
else:
error = "subject and content, please!"
self.render_content("newpost.html", subject=subject, content=content, error=error)
else:
self.redirect("/login")
# /.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 python excepts data types dat nos how 2 convert in json which're list,dict..
d |
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]
return h == make_pw_hash(name, password, salt)
#cookie hashing and hash-validation functions
secret = 'weneverwalkalone'
def make_secure_cookie(val):
return '%s|%s' % (val, hmac.new(secret, val).hexdigest())
def check_secure_val(secure_val):
val = secure_val.split('|')[0]
if secure_val == make_secure_cookie(val):
return val
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
#blog handler
class BlogHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
|
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))
def render_content(self, template, **kw):
content = self.render_str(template, **kw)
self.render("index.html", content=content, user=self.get_logged_in_user(), **kw)
def is_logged_in(self):
user_id = None
user = None
user_id_str = self.request.cookies.get("user_id")
if user_id_str:
user_id = check_secure_val(user_id_str)
return user_id
def get_logged_in_user(self):
user_id = self.is_logged_in()
user = None
if user_id:
user = User.get_by_id(long(user_id))
return user
#welcome handler
class Welcome(BlogHandler):
def get(self):
cookie_val = self.request.cookies.get("user_id")#In this case we will get the value of key(in this case name)
if cookie_val:
user_id = check_secure_val(str(cookie_val))
u = User.get_by_id(int(user_id))
self.render("welcome.html", username = u.username)
else:
self.redirect("/signup")
# class for blog-post(subject and content) entries
class Post(db.Model):
subject = db.StringProperty(required = True)
content = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
last_modified = db.DateTimeProperty(auto_now = True)
def render(self):
self._render_text = self.content.replace('\n', '<br>')
return render_str("post.html", p = self)
# class for user entries
class User(db.Model):
username = db.StringProperty(required = True)
password = db.StringProperty(required = True)
email = db.StringProperty(required = False)
# RegEx for the username field
USERNAME_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
PASSWORD_RE = re.compile(r"^.{3,20}$")
EMAIL_RE = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
# Validation for Usernames
def valid_username(username):
return USERNAME_RE.match(username)
def valid_password(password):
return PASSWORD_RE.match(password)
def valid_email(email):
return not email or EMAIL_RE.match(email)
#handler for signup
class Signup(BlogHandler):
def get(self):
self.render_content("signup.html")
def post(self):
have_error = False
user_name = self.request.get('username')
user_password = self.request.get('password')
user_verify = self.request.get('verify')
user_email = self.request.get('email')
name_error = password_error = verify_error = email_error = ""
if not valid_username(user_name):
name_error = "That's not a valid username"
have_error = True
if not valid_password(user_password):
password_error = "That's not a valid password"
have_error = True
elif user_password != user_verify:
verify_error = "Your passwords didn't match"
have_error = True
if not valid_email(user_email):
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_error)
else:
u = User.gql("WHERE username = '%s'"%user_name).get()
if u:
name_error = "That user already exists."
self.render_content("signup.html")
else:
# make salted password hash
h = make_pw_hash(user_name, user_password)
u = User(username=user_name, password=h,email=user_email)
u.put()
uid= str(make_secure_cookie(str(u.key().id()))) #dis is how we get the id from google data store(gapp engine)
#The Set-Cookie header which is add_header method will set the cookie name user_id(value,hash(value)) to its value
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid)
self.redirect("/welcome")
#login handler
class Login(BlogHandler):
def get(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_password, u.password):
uid= str(make_secure_cookie(str(u.key().id())))
self.response.headers.add_header("Set-Cookie", "user_id=%s; Path=/" %uid)
self.redirect('/')
else:
msg = "Invalid login"
self.render_content("login-form.html", error = msg)
#logout handler
class Logout(BlogHandler):
def get(self):
self.response.headers.add_header("Set-Cookie", "user_id=; Path=/")
self.redirect("/signup")
def top_posts(update = False):
posts = memcache.get("top")
if posts is None or update:
posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
posts = list(posts) # to avoid querying in iterable
memcache.set("top", posts)
memcache.set("top_post_generated", time.time())
return posts
#main page
class MainPage(BlogHandler):
def get(self):
# posts = db.GqlQuery("SELECT * FROM Post ORDER BY created DESC LIMIT 10")
# caching for query above
posts = top_posts()
diff = time.time() - memcache.get("top_post_generated")
self.render_content("front.html", posts=posts, time_update=str(int(diff)))
def get_post(key): # cache function same as above but this one is for particular post
post = memcache.get('post')
if post and key == str(post.key().id()):
return post
else:
post = Post.get_by_id(int(key))
memcache.set('post', post)
memcache.set('post-generated', time.time())
return post
# Handler for a specific Entry
class SpecificPostHandler(BlogHandler):
def get(self, key):
post = get_post(key)
diff = time.time() - memcache.get('post-generated')
diff_str = "Queried %s seconds ago"%(str(int(diff)))
self.render_content("permalink.html", post=post, time_update=diff_str)
# Handler for posting newpoHandler for a specific Wiki Page Entrysts
class EditPageHandler(BlogHandler):
def get(self):
if self.is_logged_in():
post = top_posts()
self.render_content("newpost.html", post=post)
else:
self.redirect("/login")
def post(self):
if self.is_logged_in():
subject = self.request.get("subject")
content = self.request.get("content")
if subject and content:
p = Post(subject=subject, content=content)
p.put()
KEY = p.key().id()
top_posts(update = True)
self.redirect("/"+str(KEY), str(KEY))
else:
error = "subject and content, please!"
self.render_content("newpost.html", subject=subject, content=content, error=error)
else:
self.redirect("/login")
# /.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 python excepts data types dat nos how 2 convert in json which're list,dict..
| 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_messageInfo_KeyVaultResponse.Marshal(b, m, deterministic)
}
func (m *KeyVaultResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_KeyVaultResponse.Merge(m, src)
}
func (m *KeyVaultResponse) XXX_Size() int {
return xxx_messageInfo_KeyVaultResponse.Size(m)
}
func (m *KeyVaultResponse) XXX_DiscardUnknown() {
xxx_messageInfo_KeyVaultResponse.DiscardUnknown(m)
}
var xxx_messageInfo_KeyVaultResponse proto.InternalMessageInfo
func (m *KeyVaultResponse) GetKeyVaults() []*KeyVault {
if m != nil {
return m.KeyVaults
}
return nil
}
func (m *KeyVaultResponse) GetResult() *wrappers.BoolValue {
if m != nil {
return m.Result
}
return nil
}
func (m *KeyVaultResponse) GetError() string {
if m != nil {
return m.Error
}
return ""
}
type KeyVault struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
Secrets []*Secret `protobuf:"bytes,3,rep,name=Secrets,proto3" json:"Secrets,omitempty"`
GroupName string `protobuf:"bytes,4,opt,name=groupName,proto3" json:"groupName,omitempty"`
Status *common.Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"`
LocationName string `protobuf:"bytes,10,opt,name=locationName,proto3" json:"locationName,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *KeyVault) Reset() |
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) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_KeyVault.Marshal(b, m, deterministic)
}
func (m *KeyVault) XXX_Merge(src proto.Message) {
xxx_messageInfo_KeyVault.Merge(m, src)
}
func (m *KeyVault) XXX_Size() int {
return xxx_messageInfo_KeyVault.Size(m)
}
func (m *KeyVault) XXX_DiscardUnknown() {
xxx_messageInfo_KeyVault.DiscardUnknown(m)
}
var xxx_messageInfo_KeyVault proto.InternalMessageInfo
func (m *KeyVault) GetName() string {
if m != nil {
return m.Name
}
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() *common.Status {
if m != nil {
return m.Status
}
return nil
}
func (m *KeyVault) GetLocationName() string {
if m != nil {
return m.LocationName
}
return ""
}
func init() {
proto.RegisterType((*KeyVaultRequest)(nil), "moc.cloudagent.security.KeyVaultRequest")
proto.RegisterType((*KeyVaultResponse)(nil), "moc.cloudagent.security.KeyVaultResponse")
proto.RegisterType((*KeyVault)(nil), "moc.cloudagent.security.KeyVault")
}
func init() { proto.RegisterFile("keyvault.proto", fileDescriptor_4c3d44d2a4b8394c) }
var fileDescriptor_4c3d44d2a4b8394c = []byte{
// 411 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xcf, 0x6e, 0xd3, 0x40,
0x10, 0xc6, 0x71, 0xd2, 0x06, 0x32, 0x69, 0x03, 0x5a, 0x21, 0x61, 0x45, 0x08, 0x82, 0xb9, 0x98,
0xcb, 0x1a, 0x19, 0x2e, 0x9c, 0x10, 0x95, 0x38, 0x20, 0x24, 0x90, 0xb6, 0xa8, 0x07, 0x2e, 0xc8,
0xd9, 0x4c, 0x8d, 0x55, 0xdb, 0xb3, 0xec, 0x9f, 0x22, 0xbf, 0x01, 0x2f, 0xc1, 0x3b, 0xf1, 0x48,
0x28, 0xe3, 0xb8, 0x56, 0x0f, 0x15, 0x48, 0xbd, 0x79, 0x67, 0xbf, 0xf9, 0xcd, 0xb7, 0xdf, 0x18,
0x96, 0x17, 0xd8, 0x5d, 0x16, 0xa1, 0xf6, 0xd2, 0x58, 0xf2, 0x24, 0x1e, 0x35, 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, 0xed, 0xe6, 0x28, 0xfc, 0x11, 0xd0, 0x79, 0xf1, 0x16, 0xe6, 0x43, 0xc9, 0xc5, 0xd1, 0x7a,
0x9a, 0x2e, 0xf2, 0x67, 0xf2, 0x86, 0xe1, 0xf2, 0xaa, 0x79, 0xec, 0x11, 0xaf, 0xe1, 0xf8, 0xb3,
0x41, 0x5b, 0xf8, 0x8a, 0xda, 0x2f, 0x9d, 0xc1, 0x78, 0xb2, 0x8e, | { *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, 0xed, 0xe6, 0x28, 0xfc, 0x11, 0xd0, 0x79, 0xf1, 0x16, 0xe6, 0x43, 0xc9, 0xc5, 0xd1, 0x7a,
0x9a, 0x2e, 0xf2, 0x67, 0xf2, 0x86, 0xe1, 0xf2, 0xaa, 0x79, 0xec, 0x11, 0xaf, 0xe1, 0xf8, 0xb3,
0x41, 0x5b, 0xf8, 0x8a, 0xda, 0x2f, 0x9d, 0xc1, 0x78, 0xb2, 0x8e, 0xd2, 0x65, 0xbe, 0x64, 0xc8,
0xd5, 0x8d, 0xba, 0x2e, 0x4a, 0x7e, 0x47, 0xf0, 0x60, 0xb4, 0xe2, 0x0c, 0xb5, 0x0e, 0x6f, 0xef,
0x25, 0x87, 0x99, 0x42, 0x17, 0x6a, 0xcf, 0x26, 0x16, 0xf9, 0x4a, 0xf6, 0x69, 0xc9, 0x21, 0x2d,
0x79, 0x42, 0x54, 0x9f, 0x15, 0x75, 0x40, 0xb5, 0x57, 0x8a, 0x87, 0x70, 0xf8, 0xde, 0x5a, 0xb2,
0xf1, 0x74, 0x1d, 0xa5, 0x73, 0xd5, 0x1f, 0x92, 0x3f, 0x11, 0xdc, 0x1b, 0xb8, 0x42, 0xc0, 0x41,
0x5b, 0x34, 0x18, 0x47, 0xac, 0xe0, 0x6f, 0xb1, 0x84, 0x49, 0xb5, 0xe5, 0x31, 0x73, 0x35, 0xa9,
0xb6, 0xe2, 0x0d, 0xdc, 0x3d, 0xe5, 0xac, 0x5d, 0x3c, 0x65, 0xe7, 0x4f, 0x6f, 0x74, 0xde, 0xeb,
0xd4, 0xa0, 0x17, 0x8f, 0x61, 0x5e, 0x5a, 0x0a, 0xe6, 0xd3, 0x6e, 0xc6, 0x01, 0x13, 0xc7, 0x82,
0x78, 0x0e, 0x33, 0xe7, 0x0b, 0x1f, 0x5c, 0x7c, 0xc8, 0x6f, 0x5a, 0x30, 0xf7, 0x94, 0x4b, 0x6a,
0x7f, 0x25, 0x12, 0x38, 0xaa, 0x49, 0x73, 0xbc, 0x4c, 0x01, 0xa6, 0x5c, 0xab, 0xe5, 0x06, 0x8e,
0x87, 0x17, 0xbd, 0xdb, 0x19, 0x12, 0xdf, 0x60, 0xf6, 0xa1, 0xbd, 0xa4, 0x0b, 0x14, 0xe9, 0xbf,
0x53, 0xee, 0x7f, 0x97, 0xd5, 0x8b, 0xff, 0x50, 0xf6, 0xdb, 0x4c, 0xee, 0x9c, 0xe4, 0x5f, 0x5f,
0x96, 0x95, 0xff, 0x1e, 0x36, 0x52, 0x53, 0x93, 0x35, 0x95, 0xb6, 0xe4, 0xe8, 0xdc, 0x67, 0x0d,
0xe9, 0xcc, 0x1a, 0x9d, 0x8d, 0x98, 0x6c, 0xc0, 0x6c, 0x66, 0xbc, 0xaa, 0x57, 0x7f, 0x03, 0x00,
0x00, 0xff, 0xff, 0x2b, 0x2e, 0xad, 0x5d, 0x11, 0x03, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4
// KeyVaultAgentClient is the client API for KeyVaultAgent service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type KeyVaultAgentClient interface {
Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error)
}
type keyVaultAgentClient struct {
cc *grpc.ClientConn
}
func NewKeyVaultAgentClient(cc *grpc.ClientConn) KeyVaultAgentClient {
return &keyVaultAgentClient{cc}
}
func (c *keyVaultAgentClient) Invoke(ctx context.Context, in *KeyVaultRequest, opts ...grpc.CallOption) (*KeyVaultResponse, error) {
out := new(KeyVaultResponse)
err := c.cc.Invoke(ctx, "/moc.cloudagent.security.KeyVaultAgent/Invoke", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// KeyVaultAgentServer is the server API for KeyVaultAgent service.
type KeyVaultAgentServer interface { | 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_messageInfo_KeyVaultResponse.Marshal(b, m, deterministic)
}
func (m *KeyVaultResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_KeyVaultResponse.Merge(m, src)
}
func (m *KeyVaultResponse) XXX_Size() int {
return xxx_messageInfo_KeyVaultResponse.Size(m)
}
func (m *KeyVaultResponse) XXX_DiscardUnknown() {
xxx_messageInfo_KeyVaultResponse.DiscardUnknown(m)
}
var xxx_messageInfo_KeyVaultResponse proto.InternalMessageInfo
func (m *KeyVaultResponse) GetKeyVaults() []*KeyVault {
if m != nil {
return m.KeyVaults
}
return nil
}
func (m *KeyVaultResponse) GetResult() *wrappers.BoolValue {
if m != nil {
return m.Result
}
return nil
}
func (m *KeyVaultResponse) GetError() string {
if m != nil {
return m.Error
}
return ""
}
type KeyVault struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
Secrets []*Secret `protobuf:"bytes,3,rep,name=Secrets,proto3" json:"Secrets,omitempty"`
GroupName string `protobuf:"bytes,4,opt,name=groupName,proto3" json:"groupName,omitempty"`
Status *common.Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"`
LocationName string `protobuf:"bytes,10,opt,name=locationName,proto3" json:"locationName,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *KeyVault) Reset() { *m = KeyVault{} }
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) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_KeyVault.Marshal(b, m, deterministic)
}
func (m *KeyVault) XXX_Merge(src proto.Message) {
xxx_messageInfo_KeyVault.Merge(m, src)
}
func (m *KeyVault) XXX_Size() int {
return xxx_messageInfo_KeyVault.Size(m)
}
func (m *KeyVault) XXX_DiscardUnknown() {
xxx_messageInfo_KeyVault.DiscardUnknown(m)
}
var xxx_messageInfo_KeyVault proto.InternalMessageInfo
func (m *KeyVault) GetName() string {
if m != nil |
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() *common.Status {
if m != nil {
return m.Status
}
return nil
}
func (m *KeyVault) GetLocationName() string {
if m != nil {
return m.LocationName
}
return ""
}
func init() {
proto.RegisterType((*KeyVaultRequest)(nil), "moc.cloudagent.security.KeyVaultRequest")
proto.RegisterType((*KeyVaultResponse)(nil), "moc.cloudagent.security.KeyVaultResponse")
proto.RegisterType((*KeyVault)(nil), "moc.cloudagent.security.KeyVault")
}
func init() { proto.RegisterFile("keyvault.proto", fileDescriptor_4c3d44d2a4b8394c) }
var fileDescriptor_4c3d44d2a4b8394c = []byte{
// 411 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xcf, 0x6e, 0xd3, 0x40,
0x10, 0xc6, 0x71, 0xd2, 0x06, 0x32, 0x69, 0x03, 0x5a, 0x21, 0x61, 0x45, 0x08, 0x82, 0xb9, 0x98,
0xcb, 0x1a, 0x19, 0x2e, 0x9c, 0x10, 0x95, 0x38, 0x20, 0x24, 0x90, 0xb6, 0xa8, 0x07, 0x2e, 0xc8,
0xd9, 0x4c, 0x8d, 0x55, 0xdb, 0xb3, 0xec, 0x9f, 0x22, 0xbf, 0x01, 0x2f, 0xc1, 0x3b, 0xf1, 0x48,
0x28, 0xe3, 0xb8, 0x56, 0x0f, 0x15, 0x48, 0xbd, 0x79, 0x67, 0xbf, 0xf9, 0xcd, 0xb7, 0xdf, 0x18,
0x96, 0x17, 0xd8, 0x5d, 0x16, 0xa1, 0xf6, 0xd2, 0x58, 0xf2, 0x24, 0x1e, 0x35, 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, 0xed, 0xe6, 0x28, 0xfc, 0x11, 0xd0, 0x79, 0xf1, 0x16, 0xe6, 0x43, 0xc9, 0xc5, 0xd1, 0x7a,
0x9a, 0x2e, 0xf2, 0x67, 0xf2, 0x86, 0xe1, 0xf2, 0xaa, 0x79, 0xec, 0x11, 0xaf, 0xe1, 0xf8, 0xb3,
0x41, 0x5b, 0xf8, 0x8a, 0xda, 0x2f, 0x9d, 0xc1, 0x78, 0xb2, 0x8e, | {
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) error {
return xxx_messageInfo_KeyVaultRequest.Unmarshal(m, b)
}
func (m *KeyVaultRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_KeyVaultRequest.Marshal(b, m, deterministic)
}
func (m *KeyVaultRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_KeyVaultRequest.Merge(m, src)
}
func (m *KeyVaultRequest) XXX_Size() int {
return xxx_messageInfo_KeyVaultRequest.Size(m)
}
func (m *KeyVaultRequest) XXX_DiscardUnknown() {
xxx_messageInfo_KeyVaultRequest.DiscardUnknown(m)
}
var xxx_messageInfo_KeyVaultRequest proto.InternalMessageInfo
func (m *KeyVaultRequest) GetKeyVaults() []*KeyVault {
if m != nil {
return m.KeyVaults
}
return nil
}
func (m *KeyVaultRequest) GetOperationType() common.Operation {
if m != nil {
return m.OperationType
}
return common.Operation_GET
}
type KeyVaultResponse struct {
KeyVaults []*KeyVault `protobuf:"bytes,1,rep,name=KeyVaults,proto3" json:"KeyVaults,omitempty"`
Result *wrappers.BoolValue `protobuf:"bytes,2,opt,name=Result,proto3" json:"Result,omitempty"`
Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *KeyVaultResponse) Reset() { *m = KeyVaultResponse{} }
func (m *KeyVaultResponse) String() string { return proto.CompactTextString(m) }
func (*KeyVaultResponse) ProtoMessage() {}
func (*KeyVaultResponse) 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_messageInfo_KeyVaultResponse.Marshal(b, m, deterministic)
}
func (m *KeyVaultResponse) XXX_Merge(src proto.Message) {
xxx_messageInfo_KeyVaultResponse.Merge(m, src)
}
func (m *KeyVaultResponse) XXX_Size() int {
return xxx_messageInfo_KeyVaultResponse.Size(m)
}
func (m *KeyVaultResponse) XXX_DiscardUnknown() {
xxx_messageInfo_KeyVaultResponse.DiscardUnknown(m)
}
var xxx_messageInfo_KeyVaultResponse proto.InternalMessageInfo
func (m *KeyVaultResponse) GetKeyVaults() []*KeyVault {
if m != nil {
return m.KeyVaults
}
return nil
}
func (m *KeyVaultResponse) GetResult() *wrappers.BoolValue {
if m != nil {
return m.Result
}
return nil
}
func (m *KeyVaultResponse) GetError() string {
if m != nil {
return m.Error
}
return ""
}
type KeyVault struct {
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"`
Secrets []*Secret `protobuf:"bytes,3,rep,name=Secrets,proto3" json:"Secrets,omitempty"`
GroupName string `protobuf:"bytes,4,opt,name=groupName,proto3" json:"groupName,omitempty"`
Status *common.Status `protobuf:"bytes,5,opt,name=status,proto3" json:"status,omitempty"`
LocationName string `protobuf:"bytes,10,opt,name=locationName,proto3" json:"locationName,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *KeyVault) Reset() { *m = KeyVault{} }
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) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_KeyVault.Marshal(b, m, deterministic)
}
func (m *KeyVault) XXX_Merge(src proto.Message) {
xxx_messageInfo_KeyVault.Merge(m, src)
}
func (m *KeyVault) XXX_Size() int {
return xxx_messageInfo_KeyVault.Size(m)
}
func (m *KeyVault) XXX_DiscardUnknown() {
xxx_messageInfo_KeyVault.DiscardUnknown(m)
}
var xxx_messageInfo_KeyVault proto.InternalMessageInfo
func (m *KeyVault) GetName() string {
if m != nil {
return m.Name
}
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() *common.Status {
if m != nil {
return m.Status
}
return nil
}
func (m *KeyVault) GetLocationName() string {
if m != nil {
return m.LocationName
}
return ""
}
func init() {
proto.RegisterType((*KeyVaultRequest)(nil), "moc.cloudagent.security.KeyVaultRequest")
proto.RegisterType((*KeyVaultResponse)(nil), "moc.cloudagent.security.KeyVaultResponse")
proto.RegisterType((*KeyVault)(nil), "moc.cloudagent.security.KeyVault")
}
func init() { proto.RegisterFile("keyvault.proto", fileDescriptor_4c3d44d2a4b8394c) }
var fileDescriptor_4c3d44d2a4b8394c = []byte{
// 411 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x92, 0xcf, 0x6e, 0xd3, 0x40,
0x10, 0xc6, 0x71, 0xd2, 0x06, 0x32, 0x69, 0x03, 0x5a, 0x21, 0x61, 0x45, 0x08, 0x82, 0xb9, 0x98,
0xcb, 0x1a, 0x19, 0x2e, 0x9c, 0x10, 0x95, 0x38, 0x20, 0x24, 0x90, 0xb6, 0xa8, 0x07, 0x2e, 0xc8,
0xd9, 0x4c, 0x8d, 0x55, 0xdb, 0xb3, 0xec, 0x9f, 0x22, 0xbf, 0x01, 0x2f, 0xc1, 0x3b, 0xf1, 0x48,
0x28, 0xe3, 0xb8, 0x56, 0x0f, 0x15, 0x48, 0xbd, 0x79, 0x67, 0xbf, 0xf9, 0xcd, 0xb7, 0xdf, 0x18,
0x96, 0x17, 0xd8, 0x5d, 0x16, 0xa1, 0xf6, 0xd2, 0x58, 0xf2, 0x24, 0x1e, 0x35, 0xa4, 0xa5, 0xae,
| 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` requesting template information for a source file and that file has changed
* since the last time the host was asked for the file then this version string should be
* different. No assumptions are made about the format of this string.
*
* The version can change more often than the source but should not change less often.
*/
readonly version: string;
/**
* The span of the template within the source file.
*/
readonly span: Span;
/**
* A static symbol for the template's component.
*/
readonly type: StaticSymbol;
/**
* The `SymbolTable` for the members of the component.
*/
readonly members: SymbolTable;
/**
* A `SymbolQuery` for the context of the template.
*/
readonly query: SymbolQuery;
}
/**
* A sequence of template sources.
*
* A host type; see `LanguageSeriviceHost`.
*
* @publicApi
*/
export declare type TemplateSources = TemplateSource[] | undefined;
/**
* Error information found getting declaration information
*
* A host type; see `LanguageServiceHost`.
*
* @publicApi
*/
export interface DeclarationError {
/**
* The span of the error in the declaration's module.
*/
readonly span: Span;
/**
* The message to display describing the error or a chain
* of messages.
*/
readonly message: string | DiagnosticMessageChain;
}
/**
* Information about the component declarations.
*
* A file might contain a declaration without a template because the file contains only
* templateUrl references. However, the compoennt declaration might contain errors that
* need to be reported such as the template string is missing or the component is not
* declared in a module. These error should be reported on the declaration, not the
* template.
*
* A host type; see `LanguageSeriviceHost`.
*
* @publicApi
*/
export interface Declaration {
/**
* The static symbol of the compponent being declared.
*/
readonly type: StaticSymbol;
/**
* The span of the declaration annotation reference (e.g. the 'Component' or 'Directive'
* reference).
*/
readonly declarationSpan: Span;
/**
* Reference to the compiler directive metadata for the declaration.
*/
readonly metadata?: CompileDirectiveMetadata;
/**
* Error reported trying to get the metadata.
*/
readonly errors: DeclarationError[];
}
/**
* A sequence of declarations.
*
* A host type; see `LanguageSeriviceHost`.
*
* @publicApi
*/
export declare type Declarations = Declaration[];
/**
* The host for a `LanguageService`. This provides all the `LanguageService` requires to respond
* to
* the `LanguageService` requests.
*
* This interface describes the requirements of the `LanguageService` on its host.
*
* The host interface is host language agnostic.
*
* Adding optional member to this interface or any interface that is described as a
* `LanguageServiceHost` interface is not considered a breaking change as defined by SemVer.
* Removing a method or changing a member from required to optional will also not be considered a
* breaking change.
*
* If a member is deprecated it will be changed to optional in a minor release before it is
* removed in a major release.
*
* Adding a required member or changing a method's parameters, is considered a breaking change and
* will only be done when breaking changes are allowed. When possible, a new optional member will
* be added and the old member will be deprecated. The new member will then be made required in
* and the old member will be removed only when breaking changes are allowed.
*
* While an interface is marked as experimental breaking-changes will be allowed between minor
* releases. After an interface is marked as stable breaking-changes will only be allowed between
* major releases. No breaking changes are allowed between patch releases.
*
* @publicApi
*/
export interface LanguageServiceHost {
/**
* The resolver to use to find compiler metadata.
*/
readonly resolver: CompileMetadataResolver;
/**
* Returns the template information for templates in `fileName` at the given location. If
* `fileName` refers to a template file then the `position` should be ignored. If the `position`
* is not in a template literal string then this method should return `undefined`.
*/
getTemplateAt(fileName: string, position: number): TemplateSource | undefined;
/**
* Return the template source information for all templates in `fileName` or for `fileName` if
* it
* is a template file.
*/
getTemplates(fileName: string): TemplateSources;
/**
* Returns the Angular declarations in the given file.
*/
getDeclarations(fileName: string): Declarations;
/**
* Return a summary of all Angular modules in the project.
*/
getAnalyzedModules(): NgAnalyzedModules;
/**
* Return a list all the template files referenced by the project.
*/
getTemplateReferences(): string[];
}
/**
* An item of the completion result to be displayed by an editor.
*
* A `LanguageService` interface.
*
* @publicApi
*/
export interface Completion {
/**
* The kind of comletion.
*/
kind: DeclarationKind;
/**
* The name of the completion to be displayed
*/
name: string;
/**
* The key to use to sort the completions for display.
*/
sort: string;
}
/**
* A sequence of completions.
*
* @publicApi
*/
export declare type Completions = Completion[] | undefined;
/**
* A file and span.
*/
export interface Location {
fileName: string;
span: Span;
}
/**
* The kind of diagnostic message.
*
* @publicApi
*/
export declare enum DiagnosticKind {
Error = 0,
Warning = 1
}
/**
* A template diagnostics message chain. This is similar to the TypeScript
* DiagnosticMessageChain. The messages are intended to be formatted as separate
* sentence fragments and indented.
*
* For compatibility previous implementation, the values are expected to override
* toString() to return a formatted message.
*
* @publicApi
*/
export interface DiagnosticMessageChain {
/**
* The text of the diagnostic message to display.
*/
message: string;
/**
* The next message in the chain.
*/
next?: DiagnosticMessageChain;
}
/**
* An template diagnostic message to display.
*
* @publicApi
*/
export interface Diagnostic {
/**
* The kind of diagnostic message
*/
kind: DiagnosticKind;
/**
* The source span that should be highlighted.
*/
span: Span;
/**
* The text of the diagnostic message to display or a chain of messages.
*/
message: string | DiagnosticMessageChain;
}
/**
* A sequence of diagnostic message.
*
* @publicApi
*/
export declare type Diagnostics = Diagnostic[];
/**
* A section of hover text. If the text is code then language should be provided.
* Otherwise the text is assumed to be Markdown text that will be sanitized.
*/
export interface HoverTextSection {
/**
* Source code or markdown text describing the symbol a the hover location.
*/
readonly text: string;
/**
* The language of the source if `text` is a source code fragment.
*/
readonly language?: string;
}
/**
* Hover information for a symbol at the hover location.
*/
export interface Hover {
/**
* The hover text to display for the symbol at the hover location. If the text includes
* source code, the section will specify which language it should be interpreted as.
*/
readonly text: HoverTextSection[];
/**
* The span of source the hover covers.
*/
readonly span: Span;
}
/**
* An instance of an Angular language service created by `createLanguageService()`.
*
* The language service returns information about Angular templates that are included in a project
* as defined by the `LanguageServiceHost`.
*
* When a method expects a `fileName` this file can either be source file in the project that
* contains a template in a string literal or a template file referenced by the project returned
* by `getTemplateReference()`. All other files will cause the method to return `undefined`.
*
* If a method takes a `position`, it is the offset of the UTF-16 code-point relative to the
* beginning of the file reference by `fileName`.
*
* This interface and all interfaces and types marked as `LanguageService` types, describe a
* particlar implementation of the Angular language service and is not intented to be
* implemented. Adding members to the interface will not be considered a breaking change as
* defined by SemVer.
*
* Removing a member or making a member optional, changing a method parameters, or changing a
* member's type will all be considered a breaking change.
*
* While an interface is marked | /**
* 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-field');
target_group_id = self.attr('data-input');
target_bucket = self.attr('data-bucket');
open_asset_chooser(self.attr('data-type'));
});
placeholder.parents('.field').find('input[type=file]').hide();
head.ready(['lang', 'privs'], function(){
load_templates(function(){
init_asset_panel();
});
});
placeholder.parents('.field-wrap').css('vertical-align', 'top');
}
};
var init_asset_panel = function() {
var template = Handlebars.templates['asset-chooser'];
$('.main').before(template({
upload_url: Perch.path+'/core/apps/assets/upload/'
}));
$('.asset-chooser').hide();
$('.asset-field').on('click', '.alert .action', function(e){
e.preventDefault();
current_opts = {view: current_opts.view};// jQuery.extend(true, {}, orig_opts);
filter_asset_field($('#asset-filter'));
});
$.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){
if (pos=='bottom') {
get_assets(current_opts, populate_chooser);
}
});
$('.asset-chooser').css('height', bh+20);
});
$('.asset-field').on('click keypress', '.grid-asset, .list-asset-title', function(e){
e.preventDefault();
var t = $(e.target);
if (!t.is('.list-asset-title')) {
if (!t.is('.grid-asset')) {
t = t.parents('.grid-asset');
}
}
select_grid_asset(t);
});
$('.asset-field').on('dblclick', '.grid-asset, .list-asset-title', function(e){
e.preventDefault();
var t = $(e.target);
if (!t.is('.list-asset-title')) {
if (!t.is('.grid-asset')) {
t = t.parents('.grid-asset');
select_grid_asset(t);
var item = asset_index[selected_asset];
update_form_with_selected_asset(item);
close_asset_chooser();
w.trigger('Perch.asset_deselected');
selected_asset = false;
target_field = false;
target_group_id = false;
}
}
});
w.on('Perch.asset_selected', function(){
$('.asset-topbar .actions .select').addClass('active');
});
w.on('Perch.asset_deselected', function(){
$('.asset-topbar .actions .select').removeClass('active');
});
$('.asset-topbar').on('click', '.select.active', function(e){
e.preventDefault();
var item = asset_index[selected_asset];
update_form_with_selected_asset(item);
close_asset_chooser();
w.trigger('Perch.asset_deselected');
selected_asset = false;
target_field = false;
target_group_id = false;
});
$('.asset-topbar').on('click', '.add', function(e){
e.preventDefault();
w.trigger('Perch.asset_deselected');
if ($('.asset-drop').is('.open')) {
close_asset_drop();
}else{
open_asset_drop();
}
| 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: function(r){
var container = $('#asset-filter');
container.append(r);
container.on('click', 'a:not(.action)', function(e){
var target = $(e.target);
var li = target.parent('li');
var ul = li.parent('ul');
if (ul.is('.open') && (li!=ul.find('li').first())) {
e.preventDefault();
}else{
e.preventDefault();
filter_asset_field(container, target.attr('href'));
}
});
container.on('submit', 'form', function(e){
e.preventDefault();
var field = $(e.target).find('input.search');
filter_asset_field(container, '?q='+field.val());
});
}
});
};
var filter_asset_field = function(container, href)
{
if (!href) href = '';
if (href) {
href.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { current_opts[$1] = $3; }
);
}
$.ajax({
url: Perch.path+'/core/apps/assets/async/asset-filter.php',
data: current_opts,
success: function(r){
container.html(r);
Perch.UI.Global.initSmartBar(container);
}
});
reload_assets();
}
var open_asset_drop = function() {
var drop = $('.asset-drop');
var form = drop.find('form');
drop.animate({height: '220px'}).addClass('open');
$('.asset-field').animate({top:'60px'});
var load_progress = 0;
if (!drop.is('.dropzone')) {
var reload_done = false;
drop.addClass('dropzone');
form.addClass('dropzone');
form.dropzone({
clickable: true,
dictDefaultMessage: Perch.Lang.get('Drop files here or click to upload'),
uploadMultiple: false,
totaluploadprogress: function(p) {
load_progress = p;
},
success: function(y, serverResponse) {
if (load_progress==100) {
close_asset_drop();
if (serverResponse.type) current_opts.type = serverResponse.type;
if (!reload_done){
reload_done = true;
reload_assets();
}
}
},
fallback: function(){
$.getScript(Perch.path+'/core/assets/js/jquery.form.min.js', function(){
form.ajaxForm({
beforeSubmit: function(){
show_spinner();
},
success: function(r) {
hide_spinner();
close_asset_drop();
reload_assets();
}
});
});
},
sending: function(file, xhr, formData){
formData.append('bucket', target_bucket);
},
complete: function(file){
this.removeFile(file);
},
//forceFallback: true, // useful for testing!
});
}
};
var close_asset_drop = function() {
$('.asset-drop').animate({height: '0'}).removeClass('open');
$('.asset-field').animate({top:'60px'});
};
var open_asset_chooser = function(type) {
var body = $('body');
if (body.hasClass('sidebar-open')) {
body.removeClass('sidebar-open').addClass('sidebar-closed');
}
$('.asset-chooser').addClass('transitioning').show().animate({'width': '744px'}, function(){
$('.main').one('click', close_asset_chooser);
current_opts = {'type': type, 'bucket': target_bucket};
orig_opts = jQuery.extend(true, {}, current_opts);
if (asset_index.length==0) get_assets(current_opts, populate_chooser);
$('.asset-chooser').removeClass('transitioning');
});
$('.main, .topbar, .submit.stuck').animate({'left': '-800px', 'right': '800px'});
$('.main').addClass('asset-chooser-open');
Perch.UI.Global.initSmartBar($('#asset-filter'));
$('.metanav').on('click', '.logout', function(e){
e.preventDefault();
close_asset_chooser();
});
};
var close_asset_chooser = function() {
$('.asset-chooser').addClass('transitioning').animate({'width': '0'}, function(){
$(this).hide();
});
$('.main').animate({'left': '0'});
$('.topbar, .submit.stuck').animate({'left': '0', 'right': '55px'}, function(){
$('.topbar').css('right', '');
});
$('.main').removeClass('asset-chooser-open').unbind('click', close_asset_chooser);
$('.metanav').unbind();
};
var select_grid_asset = function(item) {
selected_asset = item.attr('data-id | });
$('.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){
if (pos=='bottom') {
get_assets(current_opts, populate_chooser);
}
});
$('.asset-chooser').css('height', bh+20);
});
$('.asset-field').on('click keypress', '.grid-asset, .list-asset-title', function(e){
e.preventDefault();
var t = $(e.target);
if (!t.is('.list-asset-title')) {
if (!t.is('.grid-asset')) {
t = t.parents('.grid-asset');
}
}
select_grid_asset(t);
});
$('.asset-field').on('dblclick', '.grid-asset, .list-asset-title', function(e){
e.preventDefault();
var t = $(e.target);
if (!t.is('.list-asset-title')) {
if (!t.is('.grid-asset')) {
t = t.parents('.grid-asset');
select_grid_asset(t);
var item = asset_index[selected_asset];
update_form_with_selected_asset(item);
close_asset_chooser();
w.trigger('Perch.asset_deselected');
selected_asset = false;
target_field = false;
target_group_id = false;
}
}
});
w.on('Perch.asset_selected', function(){
$('.asset-topbar .actions .select').addClass('active');
});
w.on('Perch.asset_deselected', function(){
$('.asset-topbar .actions .select').removeClass('active');
});
$('.asset-topbar').on('click', '.select.active', function(e){
e.preventDefault();
var item = asset_index[selected_asset];
update_form_with_selected_asset(item);
close_asset_chooser();
w.trigger('Perch.asset_deselected');
selected_asset = false;
target_field = false;
target_group_id = false;
});
$('.asset-topbar').on('click', '.add', function(e){
e.preventDefault();
w.trigger('Perch.asset_deselected');
if ($('.asset-drop').is('.open')) {
close_asset_drop();
}else{
open_asset_drop();
}
});
$('.asset-topbar .close').on('click', function(e){
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: function(r){
var container = $('#asset-filter');
container.append(r);
container.on('click', 'a:not(.action)', function(e){
var target = $(e.target);
var li = target.parent('li');
var ul = li.parent('ul');
if (ul.is('.open') && (li!=ul.find('li').first())) {
e.preventDefault();
}else{
e.preventDefault();
filter_asset_field(container, target.attr('href'));
}
});
container.on('submit', 'form', function(e){
e.preventDefault();
var field = $(e.target).find('input.search');
filter_asset_field(container, '?q='+field.val());
});
}
});
};
var filter_asset_field = function(container, href)
{
if (!href) href = '';
if (href) {
href.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { current_opts[$1] = $3; }
);
}
$.ajax({
url: Perch.path+'/core/apps/assets/async/asset-filter.php',
data: current_opts,
success: function(r){
container.html(r);
Perch.UI.Global.initSmartBar(container);
}
});
reload_assets();
}
var open_asset_drop = function() {
var drop = $('.asset-drop');
var form = drop.find('form');
drop.animate({height: '220px'}).addClass('open');
$('.asset-field').animate({top:'60px'});
var load_progress = 0;
if (!drop.is('.dropzone')) {
var reload_done = false;
drop.addClass('dropzone');
form.addClass('dropzone');
form.dropzone({
clickable: true,
dictDefaultMessage: Perch.Lang.get('Drop files here or click to upload'),
uploadMultiple: false,
totaluploadprogress: function(p) {
load_progress = p;
},
success: function(y, serverResponse) {
if (load_progress==100) {
close_asset_drop();
if (serverResponse.type) current_opts.type = serverResponse.type;
if (!reload_done){
reload_done = true;
reload_assets();
}
}
},
fallback: function(){
$.getScript(Perch.path+'/core/assets/js/jquery.form.min.js', function(){
form.ajaxForm({
beforeSubmit: function(){
show_spinner();
},
success: function(r) {
hide_spinner();
close_asset_drop();
reload_assets();
}
});
});
},
sending: function(file, xhr, formData){
formData.append('bucket', target_bucket);
},
complete: function(file){
this.removeFile(file);
},
//forceFallback: true, // useful for testing!
});
}
};
var close_asset_drop = function() {
$('.asset-drop').animate({height: '0'}).removeClass('open');
$('.asset-field').animate({top:'60px'});
};
var open_asset_chooser = function(type) {
var body = $('body');
if (body.hasClass('sidebar-open')) {
body.removeClass('sidebar-open').addClass('sidebar-closed');
}
$('.asset-chooser').addClass('transitioning').show().animate({'width': '744px'}, function(){
$('.main').one('click', close_asset_chooser);
current_opts = {'type': type, 'bucket': target_bucket};
orig_opts = jQuery.extend(true, {}, current_opts);
if (asset_index.length==0) get_assets(current_opts, populate_chooser);
$('.asset-chooser').removeClass('transitioning');
});
$('.main, .topbar, .submit.stuck').animate({'left': '-800px', 'right': '800px'});
$('.main').addClass('asset-chooser-open');
Perch.UI.Global.initSmartBar($('#asset-filter'));
$('.metanav').on('click', '.logout', function(e){
e.preventDefault();
close_asset_chooser();
});
};
var close_asset_chooser = function() {
$('.asset-chooser').addClass('transitioning').animate({'width': '0'}, function(){
$(this).hide();
});
$('.main').animate({'left': '0'});
$('.topbar, .submit.stuck').animate({'left': '0', 'right': '55px'}, function(){
$('.topbar').css('right', '');
});
$('.main').removeClass('asset-chooser-open').unbind('click', close_asset_chooser);
$('.metanav').unbind();
};
var select_grid_asset = function(item) {
selected_asset = item.attr('data-id');
if (item.is('.selected')) {
$('.asset-field .selected').removeClass('selected');
w.trigger('Perch.asset_deselected');
selected_asset = false
}else{
$('.asset-field .selected').removeClass('selected');
item.addClass('selected');
w.trigger('Perch.asset_selected');
}
};
var load_templates = function(callback) {
$.getScript(Perch.path+'/core/assets/js/handlebars.runtime.js', function(){
$.getScript(Perch.path+'/core/assets/js/templates.js', function(){
callback();
});
Handlebars.registerHelper('Lang', function(str) {
return Perch.Lang.get(str);
});
Handlebars.registerHelper('hasPriv', function(str, block) {
if (Perch.Privs.has(str)>=0) {
return block.fn(this);
}
});
});
};
var get_assets = function(opts, callback) {
var cb = function(callback) {
return function(result) {
last_request_page = current_page;
if (result.assets.length) | {
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, Copy, PartialEq, Eq)]
pub enum Value {
Low = 0,
High
}
#[derive(Debug, Clone, Copy)]
pub enum Edge {
///No setup is performed, it is assumed the trigger has already been set up previosuly
Setup = 0,
Falling = 1,
Rising = 2,
Both = 3
}
#[derive(Debug, Clone, Copy)]
pub enum Pull {
Off = 0,
Down,
Up
}
#[derive(Debug, Clone, Copy)]
pub enum PwmMode {
MarkSpace = 0,
Balanced
}
pub struct InputPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin> InputPin<P> {
pub fn new(pin: libc::c_int) -> InputPin<P> {
unsafe {
bindings::pinMode(pin, INPUT);
}
InputPin(pin, PhantomData)
}
#[inline]
pub fn number(&self) -> libc::c_int {
let &InputPin(number, _) = self;
number
}
///This function returns the value read at the given pin.
///
///It will be `High` or `Low` (1 or 0) depending on the logic level at the pin.
pub fn digital_read(&self) -> Value {
let value = unsafe {
bindings::digitalRead(self.number())
};
if value == 0 {
Low
} else {
| }
///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 {
bindings::analogRead(self.number()) as u16
}
}
/// This will register an "Interrupt" to be called when the pin changes state
/// Note the quotes around Interrupt, because the current implementation in the C
/// library seems to be a dedicated thread that polls the gpio device driver,
/// and this callback is called from that thread synchronously, so it's not something that
/// you would call a real interrupt in an embedded environement.
///
/// 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.
///
/// 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
/// ideas on how to work around these limitations if you find them too constraining.
///
/// ```
/// use wiringpi;
///
/// extern "C" fn change_state() {
/// println!("Look ma, I'm being called from an another thread");
/// }
///
/// fn main() {
/// let pi = wiringpi::setup();
/// let pin = pi.output_pin(0);
///
/// pin.register_isr(Edge::Falling, Some(change_state));
///
/// thread::sleep(60000);
/// }
///
/// ```
///
///
pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) {
unsafe {
bindings::wiringPiISR(self.number(), edge as i32, f);
}
}
}
impl<P: Pin + RequiresRoot> InputPin<P> {
///This sets the pull-up or pull-down resistor mode on the given pin.
///
///Unlike the Arduino, the BCM2835 has both pull-up an down internal
///resistors. The parameter pud should be; `Off`, (no pull up/down),
///`Down` (pull to ground) or `Up` (pull to 3.3v)
pub fn pull_up_dn_control(&self, pud: Pull) {
unsafe {
bindings::pullUpDnControl(self.number(), pud as libc::c_int);
}
}
pub fn into_output(self) -> OutputPin<P> {
let InputPin(number, _) = self;
OutputPin::new(number)
}
pub fn into_soft_pwm(self) -> SoftPwmPin<P> {
let InputPin(number, _) = self;
SoftPwmPin::new(number)
}
}
impl<P: Pin + Pwm> InputPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let InputPin(number, _) = self;
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> InputPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let InputPin(number, _) = self;
ClockPin::new(number)
}
}
/// A pin with software controlled PWM output.
///
/// Due to limitations of the chip only one pin is able to do
/// hardware-controlled PWM output. The `SoftPwmPin`s on the
/// other hand allow for all GPIOs to output PWM signals.
///
/// The pulse width of the signal will be 100μs with a value range
/// of [0,100] \(where `0` is a constant low and `100` is a
/// constant high) resulting in a frequenzy of 100 Hz.
///
/// **Important**: In order to use software PWM pins *wiringPi*
/// has to be setup in GPIO mode via `setup_gpio()`.
pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin + RequiresRoot> SoftPwmPin<P> {
/// Configures the given `pin` to output a software controlled PWM
/// signal.
pub fn new(pin: libc::c_int) -> SoftPwmPin<P> {
unsafe {
bindings::softPwmCreate(pin, 0, 100);
}
SoftPwmPin(pin, PhantomData)
}
#[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 {
bindings::softPwmWrite(self.number(), value);
}
}
/// Stops the software handling of this pin.
///
/// _Note_: In order to control this pin via software PWM again
/// it will need to be recreated using `new()`.
pub fn pwm_stop(self) {
unsafe {
bindings::softPwmStop(self.number());
}
}
pub fn into_input(self) -> InputPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
InputPin::new(number)
}
pub fn into_output(self) -> OutputPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
OutputPin::new(number)
}
}
impl<P: Pin + Pwm> SoftPwmPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> SoftPwmPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
ClockPin::new(number)
}
}
pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin> OutputPin<P> {
pub fn new(pin: libc::c_int) -> OutputPin<P> {
unsafe {
bindings::pinMode(pin, OUTPUT);
}
OutputPin(pin, PhantomData)
}
#[inline]
pub fn number(&self) -> libc::c_int {
let &OutputPin(number, _) = self;
number
}
///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output.
pub fn digital_write(&self, value: Value) {
unsafe {
bindings::digitalWrite(self.number(), value as libc::c_int);
}
}
///This writes the given value to the supplied analog pin. You will
///need to register additional analog modules to | 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.
///
/// See https://github.com/Ogeon/rust-wiringpi/pull/28 for
/// ideas on how to work around these limitations if you find them too constraining.
///
/// ```
/// use wiringpi;
///
/// extern "C" fn change_state() {
/// println!("Look ma, I'm being called from an another thread");
/// }
///
/// fn main() {
/// let pi = wiringpi::setup();
/// let pin = pi.output_pin(0);
///
/// pin.register_isr(Edge::Falling, Some(change_state));
///
/// thread::sleep(60000);
/// }
///
/// ```
///
///
pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) {
unsafe {
bindings::wiringPiISR(self.number(), edge as i32, f);
}
}
}
impl<P: Pin + RequiresRoot> InputPin<P> {
///This sets the pull-up or pull-down resistor mode on the given pin.
///
///Unlike the Arduino, the BCM2835 has both pull-up an down internal
///resistors. The parameter pud should be; `Off`, (no pull up/down),
///`Down` (pull to ground) or `Up` (pull to 3.3v)
pub fn pull_up_dn_control(&self, pud: Pull) {
unsafe {
bindings::pullUpDnControl(self.number(), pud as libc::c_int);
}
}
pub fn into_output(self) -> OutputPin<P> {
let InputPin(number, _) = self;
OutputPin::new(number)
}
pub fn into_soft_pwm(self) -> SoftPwmPin<P> {
let InputPin(number, _) = self;
SoftPwmPin::new(number)
}
}
impl<P: Pin + Pwm> InputPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let InputPin(number, _) = self;
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> InputPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let InputPin(number, _) = self;
ClockPin::new(number)
}
}
/// A pin with software controlled PWM output.
///
/// Due to limitations of the chip only one pin is able to do
/// hardware-controlled PWM output. The `SoftPwmPin`s on the
/// other hand allow for all GPIOs to output PWM signals.
///
/// The pulse width of the signal will be 100μs with a value range
/// of [0,100] \(where `0` is a constant low and `100` is a
/// constant high) resulting in a frequenzy of 100 Hz.
///
/// **Important**: In order to use software PWM pins *wiringPi*
/// has to be setup in GPIO mode via `setup_gpio()`.
pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin + RequiresRoot> SoftPwmPin<P> {
/// Configures the given `pin` to output a software controlled PWM
/// signal.
pub fn new(pin: libc::c_int) -> SoftPwmPin<P> {
unsafe {
bindings::softPwmCreate(pin, 0, 100);
}
SoftPwmPin(pin, PhantomData)
}
#[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 {
bindings::softPwmWrite(self.number(), value);
}
}
/// Stops the software handling of this pin.
///
/// _Note_: In order to control this pin via software PWM again
/// it will need to be recreated using `new()`.
pub fn pwm_stop(self) {
unsafe {
bindings::softPwmStop(self.number());
}
}
pub fn into_input(self) -> InputPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
InputPin::new(number)
}
pub fn into_output(self) -> OutputPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
OutputPin::new(number)
}
}
impl<P: Pin + Pwm> SoftPwmPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> SoftPwmPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
ClockPin::new(number)
}
}
pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin> OutputPin<P> {
pub fn new(pin: libc::c_int) -> OutputPin<P> {
unsafe {
bindings::pinMode(pin, OUTPUT);
}
OutputPin(pin, PhantomData)
}
#[inline]
pub fn number(&self) -> libc::c_int {
let &OutputPin(number, _) = self;
number
}
///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output.
pub fn digital_write(&self, value: Value) {
unsafe {
bindings::digitalWrite(self.number(), value as libc::c_int);
}
}
///This writes the given value to the supplied analog pin. You will
///need to register additional analog modules to enable this function
///for devices such as the Gertboard.
pub fn analog_write(&self, value: u16) {
unsafe {
bindings::analogWrite(self.number(), value as libc::c_int);
}
}
}
impl<P: Pin + RequiresRoot> OutputPin<P> {
pub fn into_soft_pwm(self) -> SoftPwmPin<P> {
let OutputPin(number, _) = self;
SoftPwmPin::new(number)
}
}
impl<P: Pin + RequiresRoot> OutputPin<P> {
pub fn into_input(self) -> InputPin<P> {
let OutputPin(number, _) = self;
InputPin::new(number)
}
}
impl<P: Pin + Pwm> OutputPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let OutputPin(number, _) = self;
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> OutputPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let OutputPin(number, _) = self;
ClockPin::new(number)
}
}
///To understand more about the PWM system, you’ll need to read the Broadcom ARM peripherals manual.
pub struct PwmPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin + Pwm> PwmPin<P> {
pub fn new(pin: libc::c_int) -> PwmPin<P> {
unsafe {
bindings::pinMode(pin, PWM_OUTPUT);
}
PwmPin(pin, PhantomData)
}
#[inline]
pub fn number(&self) -> libc::c_int {
let &PwmPin(number, _) = self;
number
}
pub fn into_input(self) -> InputPin<P> {
let PwmPin(number, _) = self;
InputPin::new(number)
}
pub fn into_output(self) -> OutputPin<P> {
let PwmPin(number, _) = self;
OutputPin::new(number)
}
pub fn into_soft_pwm(self) -> SoftPwmPin<P> {
let PwmPin(number, _) = self;
SoftPwmPin::new(number)
}
///Writes the value to the PWM register for the given pin.
///
///The value must be between 0 and 1024.
pub fn write(&self, value: u16) {
unsafe {
bindings::pwmWrite(self.number(), value as libc::c_int);
}
}
///The PWM generator can run in 2 modes – "balanced" and "mark:space".
///
///The mark:space mode is traditional, however the default mode in the
///Pi is "balanced". You can switch modes by supplying the parameter:
///`Balanced` or `MarkSpace`.
pub fn set_mode( | &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, Copy, PartialEq, Eq)]
pub enum Value {
Low = 0,
High
}
#[derive(Debug, Clone, Copy)]
pub enum Edge {
///No setup is performed, it is assumed the trigger has already been set up previosuly
Setup = 0,
Falling = 1,
Rising = 2,
Both = 3
}
#[derive(Debug, Clone, Copy)]
pub enum Pull {
Off = 0,
Down,
Up
}
#[derive(Debug, Clone, Copy)]
pub enum PwmMode {
MarkSpace = 0,
Balanced
}
pub struct InputPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin> InputPin<P> {
pub fn new(pin: libc::c_int) -> InputPin<P> {
unsafe {
bindings::pinMode(pin, INPUT);
}
InputPin(pin, PhantomData)
}
#[inline]
pub fn number(&self) -> libc::c_int {
let &InputPin(number, _) = self;
number
}
///This function returns the value read at the given pin.
///
///It will be `High` or `Low` (1 or 0) depending on the logic level at the pin.
pub fn digital_read(&self) -> Value {
let value = unsafe {
bindings::digitalRead(self.number())
};
if value == 0 {
Low
} else {
High
}
}
///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 {
bindings::analogRead(self.number()) as u16
}
}
/// This will register an "Interrupt" to be called when the pin changes state
/// Note the quotes around Interrupt, because the current implementation in the C
/// library seems to be a dedicated thread that polls the gpio device driver,
/// and this callback is called from that thread synchronously, so it's not something that
/// you would call a real interrupt in an embedded environement.
///
/// 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.
///
/// 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
/// ideas on how to work around these limitations if you find them too constraining.
///
/// ```
/// use wiringpi;
///
/// extern "C" fn change_state() {
/// println!("Look ma, I'm being called from an another thread");
/// }
///
/// fn main() {
/// let pi = wiringpi::setup();
/// let pin = pi.output_pin(0);
///
/// pin.register_isr(Edge::Falling, Some(change_state));
///
/// thread::sleep(60000);
/// }
///
/// ```
///
///
pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) {
unsafe {
bindings::wiringPiISR(self.number(), edge as i32, f);
}
}
}
impl<P: Pin + RequiresRoot> InputPin<P> {
///This sets the pull-up or pull-down resistor mode on the given pin.
///
///Unlike the Arduino, the BCM2835 has both pull-up an down internal
///resistors. The parameter pud should be; `Off`, (no pull up/down),
///`Down` (pull to ground) or `Up` (pull to 3.3v)
pub fn pull_up_dn_control(&self, pud: Pull) {
unsafe {
bindings::pullUpDnControl(self.number(), pud as libc::c_int);
}
}
pub fn into_output(self) -> OutputPin<P> {
let InputPin(number, _) = self;
OutputPin::new(number)
}
pub fn into_soft_pwm(self) -> SoftPwmPin<P> {
let InputPin(number, _) = self;
SoftPwmPin::new(number)
}
}
impl<P: Pin + Pwm> InputPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let InputPin(number, _) = self;
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> InputPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let InputPin(number, _) = self;
ClockPin::new(number)
}
}
/// A pin with software controlled PWM output.
///
/// Due to limitations of the chip only one pin is able to do
/// hardware-controlled PWM output. The `SoftPwmPin`s on the
/// other hand allow for all GPIOs to output PWM signals.
///
/// The pulse width of the signal will be 100μs with a value range
/// of [0,100] \(where `0` is a constant low and `100` is a
/// constant high) resulting in a frequenzy of 100 Hz.
///
/// **Important**: In order to use software PWM pins *wiringPi*
/// has to be setup in GPIO mode via `setup_gpio()`.
pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin + RequiresRoot> SoftPwmPin<P> {
/// Configures the given `pin` to output a software controlled PWM
/// signal.
pub fn new(pin: libc::c_int) -> SoftPwmPin<P> {
| #[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 {
bindings::softPwmWrite(self.number(), value);
}
}
/// Stops the software handling of this pin.
///
/// _Note_: In order to control this pin via software PWM again
/// it will need to be recreated using `new()`.
pub fn pwm_stop(self) {
unsafe {
bindings::softPwmStop(self.number());
}
}
pub fn into_input(self) -> InputPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
InputPin::new(number)
}
pub fn into_output(self) -> OutputPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
OutputPin::new(number)
}
}
impl<P: Pin + Pwm> SoftPwmPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> SoftPwmPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
ClockPin::new(number)
}
}
pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin> OutputPin<P> {
pub fn new(pin: libc::c_int) -> OutputPin<P> {
unsafe {
bindings::pinMode(pin, OUTPUT);
}
OutputPin(pin, PhantomData)
}
#[inline]
pub fn number(&self) -> libc::c_int {
let &OutputPin(number, _) = self;
number
}
///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output.
pub fn digital_write(&self, value: Value) {
unsafe {
bindings::digitalWrite(self.number(), value as libc::c_int);
}
}
///This writes the given value to the supplied analog pin. You will
///need to register additional analog modules to | 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, Copy, PartialEq, Eq)]
pub enum Value {
Low = 0,
High
}
#[derive(Debug, Clone, Copy)]
pub enum Edge {
///No setup is performed, it is assumed the trigger has already been set up previosuly
Setup = 0,
Falling = 1,
Rising = 2,
Both = 3
}
#[derive(Debug, Clone, Copy)]
pub enum Pull {
Off = 0,
Down,
Up
}
#[derive(Debug, Clone, Copy)]
pub enum PwmMode {
MarkSpace = 0,
Balanced
}
pub struct InputPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin> InputPin<P> {
pub fn new(pin: libc::c_int) -> InputPin<P> {
unsafe {
bindings::pinMode(pin, INPUT);
}
InputPin(pin, PhantomData)
}
#[inline]
pub fn number(&self) -> libc::c_int {
let &InputPin(number, _) = self;
number
}
///This function returns the value read at the given pin.
///
///It will be `High` or `Low` (1 or 0) depending on the logic level at the pin.
pub fn digital_read(&self) -> Value {
let value = unsafe {
bindings::digitalRead(self.number())
};
if value == 0 {
Low
} else {
High
}
}
///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 {
bindings::analogRead(self.number()) as u16
}
}
/// This will register an "Interrupt" to be called when the pin changes state
/// Note the quotes around Interrupt, because the current implementation in the C
/// library seems to be a dedicated thread that polls the gpio device driver,
/// and this callback is called from that thread synchronously, so it's not something that
/// you would call a real interrupt in an embedded environement.
/// | ///
/// 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
/// ideas on how to work around these limitations if you find them too constraining.
///
/// ```
/// use wiringpi;
///
/// extern "C" fn change_state() {
/// println!("Look ma, I'm being called from an another thread");
/// }
///
/// fn main() {
/// let pi = wiringpi::setup();
/// let pin = pi.output_pin(0);
///
/// pin.register_isr(Edge::Falling, Some(change_state));
///
/// thread::sleep(60000);
/// }
///
/// ```
///
///
pub fn register_isr(&self, edge: Edge, f: Option<extern "C" fn()>) {
unsafe {
bindings::wiringPiISR(self.number(), edge as i32, f);
}
}
}
impl<P: Pin + RequiresRoot> InputPin<P> {
///This sets the pull-up or pull-down resistor mode on the given pin.
///
///Unlike the Arduino, the BCM2835 has both pull-up an down internal
///resistors. The parameter pud should be; `Off`, (no pull up/down),
///`Down` (pull to ground) or `Up` (pull to 3.3v)
pub fn pull_up_dn_control(&self, pud: Pull) {
unsafe {
bindings::pullUpDnControl(self.number(), pud as libc::c_int);
}
}
pub fn into_output(self) -> OutputPin<P> {
let InputPin(number, _) = self;
OutputPin::new(number)
}
pub fn into_soft_pwm(self) -> SoftPwmPin<P> {
let InputPin(number, _) = self;
SoftPwmPin::new(number)
}
}
impl<P: Pin + Pwm> InputPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let InputPin(number, _) = self;
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> InputPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let InputPin(number, _) = self;
ClockPin::new(number)
}
}
/// A pin with software controlled PWM output.
///
/// Due to limitations of the chip only one pin is able to do
/// hardware-controlled PWM output. The `SoftPwmPin`s on the
/// other hand allow for all GPIOs to output PWM signals.
///
/// The pulse width of the signal will be 100μs with a value range
/// of [0,100] \(where `0` is a constant low and `100` is a
/// constant high) resulting in a frequenzy of 100 Hz.
///
/// **Important**: In order to use software PWM pins *wiringPi*
/// has to be setup in GPIO mode via `setup_gpio()`.
pub struct SoftPwmPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin + RequiresRoot> SoftPwmPin<P> {
/// Configures the given `pin` to output a software controlled PWM
/// signal.
pub fn new(pin: libc::c_int) -> SoftPwmPin<P> {
unsafe {
bindings::softPwmCreate(pin, 0, 100);
}
SoftPwmPin(pin, PhantomData)
}
#[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 {
bindings::softPwmWrite(self.number(), value);
}
}
/// Stops the software handling of this pin.
///
/// _Note_: In order to control this pin via software PWM again
/// it will need to be recreated using `new()`.
pub fn pwm_stop(self) {
unsafe {
bindings::softPwmStop(self.number());
}
}
pub fn into_input(self) -> InputPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
InputPin::new(number)
}
pub fn into_output(self) -> OutputPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
OutputPin::new(number)
}
}
impl<P: Pin + Pwm> SoftPwmPin<P> {
pub fn into_pwm(self) -> PwmPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
PwmPin::new(number)
}
}
impl<P: Pin + GpioClock> SoftPwmPin<P> {
pub fn into_clock(self) -> ClockPin<P> {
let SoftPwmPin(number, _) = self;
self.pwm_stop();
ClockPin::new(number)
}
}
pub struct OutputPin<Pin>(libc::c_int, PhantomData<Pin>);
impl<P: Pin> OutputPin<P> {
pub fn new(pin: libc::c_int) -> OutputPin<P> {
unsafe {
bindings::pinMode(pin, OUTPUT);
}
OutputPin(pin, PhantomData)
}
#[inline]
pub fn number(&self) -> libc::c_int {
let &OutputPin(number, _) = self;
number
}
///Writes the value `High` or `Low` (1 or 0) to the given pin which must have been previously set as an output.
pub fn digital_write(&self, value: Value) {
unsafe {
bindings::digitalWrite(self.number(), value as libc::c_int);
}
}
///This writes the given value to the supplied analog pin. You will
///need to register additional analog modules to enable | /// 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_vgg19_model_params(dir_path, model_url):
def save_image_pre_annotation(pre_annotation, train_image, annotation):
pre_annotation = np.array(pre_annotation[0])
pre_annotation = (pre_annotation - np.min(pre_annotation)) \
/ (np.max(pre_annotation) - np.min(pre_annotation))
pre_annotation = np.clip(pre_annotation * 255.0, 0, 255.0)
pre_annotation = pre_annotation.astype(np.uint8).reshape((224, 224, 3))
cv2.imshow("generated", pre_annotation)
cv2.imshow("image", train_image[0])
cv2.imshow("ground_truth", annotation[0])
def get_model_data(dir_path, model_url):
maybe_download_and_extract(dir_path, model_url)
filename = model_url.split('/')[-1]
filepath = os.path.join(dir_path, filename)
if not os.path.exists(filepath):
raise IOError("VGG model params not found")
data = scipy.io.loadmat(filepath)
return data
def xavier_init(inputs, outputs, constant=1):
# Xavier initialization
low = -constant * np.sqrt(6.0 / (inputs + outputs))
high = constant * np.sqrt(6.0 / (inputs + outputs))
return tf.random_uniform((inputs, outputs), minval=low, maxval=high, dtype=tf.float32)
def get_weights_variable(inputs, outputs, name):
w = tf.Variable(xavier_init(inputs, outputs), name=name)
return w
def get_bias_variable(num, name):
b = tf.Variable(tf.zeros([num], dtype=tf.float32), name=name)
return b
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:
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer=initial)
def bias_variable(shape, name=None):
initial = tf.constant(0.0, shape=shape)
if name is None:
return tf.Variable(initial)
else:
return tf.get_variable(name=name, initializer=initial)
def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2):
if output_shape is None:
output_shape = x.get_shape().as_list()
output_shape[1] *= 2
output_shape[2] *= 2
output_shape[3] *= 2
conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME')
return tf.nn.bias_add(conv, b)
def conv2d_basic(x, W, b):
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.bias_add(conv, b)
def conv2d_strided(x, W, b, stride=None, padding='SAME'):
if stride is None:
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding)
else:
conv = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding)
return tf.nn.bias_add(conv, b)
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def avg_pool_2x2(x):
return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def process_image(image, mean):
return image - mean
def add_grad_summary(grad, var):
return tf.summary.histogram(var.op.name+'gradient', grad)
def save_image(image, save_dir, name, mean=None):
"""
save the image
:param image:
:param save_dir:
:param name:
:param mean:
:return:
"""
if mean:
image = unprocess_image(image, mean)
misc.imsave(os.path.join(save_dir, name+'.png'), image)
def unprocess_image(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 variables
"""
d = tf.square(tf.subtract(x, y))
d = tf.reduce_sum(d, axis=1)
if positive:
d1, indx = tf.nn.top_k(input=d, k=100)
else:
d1, indx = tf.nn.top_k(input=-d, k=100)
d1 = -1.0 * d1
return d1 * 2.0
def compute_triplet_loss(anchor_feature, positive_feature, negative_feature, margin):
"""
Compute the contrastive loss as in
L = || f_a - f_p ||^2 - || f_a - f_n ||^2 + m
**Parameters**
anchor_feature:
positive_feature:
negative_feature:
margin: Triplet margin
**Returns**
Return the loss operation
"""
with tf.variable_scope('triplet_loss'):
pos_dist = compute_euclidean_distance(anchor_feature, positive_feature, positive=True)
neg_dist = compute_euclidean_distance(anchor_feature, negative_feature, positive=False)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), margin)
loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0)
return loss, tf.reduce_mean(pos_dist), tf.reduce_mean(neg_dist)
def compute_accuracy(data_train, labels_train, data_validation, labels_validation, n_classes):
models = []
for i in range(n_classes):
indexes = labels_train == i
models.append(np.mean(data_train[indexes, :], axis=0))
tp = 0
for i in range(data_validation.shape[0]):
d = data_validation[i, :]
l = labels_validation[i]
scores = [consine(m, d) for m in models]
predict = np. argmax(scores)
if predict == 1:
tp += 1
return (float(tp) / data_validation.shape[0]) * 100
def get_index(labels, val):
return [i for i in range(len(labels)) if labels[i] == val]
def prewhiten(x):
mean = np.mean(x)
std = np.std(x)
std_adj = np.maximum(std, 1.0/np.sqrt(x.size))
y = np.multiply(np.subtract(x, mean), 1/std_adj)
return y
def whiten(x):
mean = np.mean(x)
std = np.std(x)
y = np.multiply(np.subtract(x, mean), 1.0 / std)
return y
def crop(image, random_crop, image_size):
if image.shape[1]>image_size:
|
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_size):
width = height = image_size
x = random.randint(0, img.shape[1] - width)
y = random.randint(0, img.shape[0] - height)
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之间的数字,控制样本类别 | 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 + 1), :] | 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_vgg19_model_params(dir_path, model_url):
def save_image_pre_annotation(pre_annotation, train_image, annotation):
pre_annotation = np.array(pre_annotation[0])
pre_annotation = (pre_annotation - np.min(pre_annotation)) \
/ (np.max(pre_annotation) - np.min(pre_annotation))
pre_annotation = np.clip(pre_annotation * 255.0, 0, 255.0)
pre_annotation = pre_annotation.astype(np.uint8).reshape((224, 224, 3))
cv2.imshow("generated", pre_annotation)
cv2.imshow("image", train_image[0])
cv2.imshow("ground_truth", annotation[0])
def get_model_data(dir_path, model_url):
maybe_download_and_extract(dir_path, model_url)
filename = model_url.split('/')[-1]
filepath = os.path.join(dir_path, filename)
if not os.path.exists(filepath):
raise IOError("VGG model params not found")
data = scipy.io.loadmat(filepath)
return data
def xavier_init(inputs, outputs, constant=1):
# Xavier initialization
low = -constant * np.sqrt(6.0 / (inputs + outputs))
high = constant * np.sqrt(6.0 / (inputs + outputs))
return tf.random_uniform((inputs, outputs), minval=low, maxval=high, dtype=tf.float32)
def get_weights_variable(inputs, outputs, name):
w = tf.Variable(xavier_init(inputs, outputs), name=name)
return w
def get_bias_variable(num, name):
b = tf.Variable(tf.zeros([num], dtype=tf.float32), name=name)
return b
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:
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer=initial)
def bias_variable(shape, name=None):
initial = tf.constant(0.0, shape=shape)
if name is None:
return tf.Variable(initial)
else:
return tf.get_variable(name=name, initializer=initial)
def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2):
if output_shape is None:
output_shape = x.get_shape().as_list()
output_shape[1] *= 2
output_shape[2] *= 2
output_shape[3] *= 2
conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME')
return tf.nn.bias_add(conv, b)
def conv2d_basic(x, W, b):
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.bias_add(conv, b)
def conv2d_strided(x, W, b, stride=None, padding='SAME'):
if stride is None:
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding)
else:
conv = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding)
return tf.nn.bias_add(conv, b)
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def avg_pool_2x2(x):
return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def process_image(image, mean):
return image - mean
def add_grad_summary(grad, var):
return tf.summary.histogram(var.op.name+'gradient', grad)
def save_image(image, save_dir, name, mean=None):
"""
save the image
:param image:
:param save_dir:
:param name:
:param mean:
:return:
"""
if mean:
image = unprocess_image(image, mean)
misc.imsave(os.path.join(save_dir, name+'.png'), image)
def unprocess_image(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 variables
"""
d = tf.square(tf.subtract(x, y))
d = tf.reduce_sum(d, axis=1)
if positive:
d1, indx = tf.nn.top_k(input=d, k=100)
else:
d1, indx = tf.nn.top_k(input=-d, k=100)
d1 = -1.0 * d1
return d1 * 2.0
def compute_triplet_loss(anchor_feature, positive_feature, negative_feature, margin):
"""
Compute the contrastive loss as in
L = || f_a - f_p ||^2 - || f_a - f_n ||^2 + m
**Parameters**
anchor_feature:
positive_feature:
negative_feature:
margin: Triplet margin
**Returns**
Return the loss operation
"""
with tf.variable_scope('triplet_loss'):
pos_dist = compute_euclidean_distance(anchor_feature, positive_feature, positive=True)
neg_dist = compute_euclidean_distance(anchor_feature, negative_feature, positive=False)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), margin)
loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0)
return loss, tf.reduce_mean(pos_dist), tf.reduce_mean(neg_dist)
def compute_accuracy(data_train, labels_train, data_validation, labels_validation, n_classes):
models = []
for i in range(n_classes):
indexes = labels_train == i
models.append(np.mean(data_train[indexes, :], axis=0))
tp = 0
for i in range(data_validation.shape[0]):
d = data_validation[i, :]
l = labels_validation[i]
scores = [consine(m, d) for m in models]
predict = np. argmax(scores)
if predict == 1:
tp += 1
return (float(tp) / data_validation.shape[0]) * 100
def get_index(labels, val):
return [i for i in range(len(labels)) if labels[i] == val]
def prewhiten(x):
mean = np.mean(x)
std = np.std(x)
std_adj = np.maximum(std, 1.0/np.sqrt(x.size))
y = np.multiply(np.subtract(x, mean), 1/std_adj)
return y
def whiten(x):
mean = np.mean(x)
std = np.std(x)
y = np.multiply(np.subtract(x, mean), 1.0 / std)
return y
def crop(image, random_crop, image_size):
if image.shape[1]>image_size:
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 + 1), :]
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')
|
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_vgg19_model_params(dir_path, model_url):
def save_image_pre_annotation(pre_annotation, train_image, annotation):
pre_annotation = np.array(pre_annotation[0])
pre_annotation = (pre_annotation - np.min(pre_annotation)) \
/ (np.max(pre_annotation) - np.min(pre_annotation))
pre_annotation = np.clip(pre_annotation * 255.0, 0, 255.0)
pre_annotation = pre_annotation.astype(np.uint8).reshape((224, 224, 3))
cv2.imshow("generated", pre_annotation)
cv2.imshow("image", train_image[0])
cv2.imshow("ground_truth", annotation[0])
def get_model_data(dir_path, model_url):
maybe_download_and_extract(dir_path, model_url)
filename = model_url.split('/')[-1]
filepath = os.path.join(dir_path, filename)
if not os.path.exists(filepath):
raise IOError("VGG model params not found")
data = scipy.io.loadmat(filepath)
return data
def xavier_init(inputs, outputs, constant=1):
# Xavier initialization
low = -constant * np.sqrt(6.0 / (inputs + outputs))
high = constant * np.sqrt(6.0 / (inputs + outputs))
return tf.random_uniform((inputs, outputs), minval=low, maxval=high, dtype=tf.float32)
def get_weights_variable(inputs, outputs, name):
w = tf.Variable(xavier_init(inputs, outputs), name=name)
return w
def get_bias_variable(num, name):
b = tf.Variable(tf.zeros([num], dtype=tf.float32), name=name)
return b
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:
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer=initial)
def bias_variable(shape, name=None):
initial = tf.constant(0.0, shape=shape)
if name is None:
return tf.Variable(initial)
else:
return tf.get_variable(name=name, initializer=initial)
def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2):
if output_shape is None:
output_shape = x.get_shape().as_list()
output_shape[1] *= 2
output_shape[2] *= 2
output_shape[3] *= 2
conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME')
return tf.nn.bias_add(conv, b)
def conv2d_basic(x, W, b):
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.bias_add(conv, b)
def conv2d_strided(x, W, b, stride=None, padding='SAME'):
if stride is None:
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding)
else:
conv = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding)
return tf.nn.bias_add(conv, b)
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def avg_pool_2x2(x):
return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def process_image(image, mean):
return image - mean
def add_grad_summary(grad, var):
return tf.summary.histogram(var.op.name+'gradient', grad)
def save_image(image, save_dir, name, mean=None):
"""
save the image
:param image:
:param save_dir:
:param name:
:param mean:
:return:
"""
if mean:
image = unprocess_image(image, mean)
misc.imsave(os.path.join(save_dir, name+'.png'), image)
def | (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 variables
"""
d = tf.square(tf.subtract(x, y))
d = tf.reduce_sum(d, axis=1)
if positive:
d1, indx = tf.nn.top_k(input=d, k=100)
else:
d1, indx = tf.nn.top_k(input=-d, k=100)
d1 = -1.0 * d1
return d1 * 2.0
def compute_triplet_loss(anchor_feature, positive_feature, negative_feature, margin):
"""
Compute the contrastive loss as in
L = || f_a - f_p ||^2 - || f_a - f_n ||^2 + m
**Parameters**
anchor_feature:
positive_feature:
negative_feature:
margin: Triplet margin
**Returns**
Return the loss operation
"""
with tf.variable_scope('triplet_loss'):
pos_dist = compute_euclidean_distance(anchor_feature, positive_feature, positive=True)
neg_dist = compute_euclidean_distance(anchor_feature, negative_feature, positive=False)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), margin)
loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0)
return loss, tf.reduce_mean(pos_dist), tf.reduce_mean(neg_dist)
def compute_accuracy(data_train, labels_train, data_validation, labels_validation, n_classes):
models = []
for i in range(n_classes):
indexes = labels_train == i
models.append(np.mean(data_train[indexes, :], axis=0))
tp = 0
for i in range(data_validation.shape[0]):
d = data_validation[i, :]
l = labels_validation[i]
scores = [consine(m, d) for m in models]
predict = np. argmax(scores)
if predict == 1:
tp += 1
return (float(tp) / data_validation.shape[0]) * 100
def get_index(labels, val):
return [i for i in range(len(labels)) if labels[i] == val]
def prewhiten(x):
mean = np.mean(x)
std = np.std(x)
std_adj = np.maximum(std, 1.0/np.sqrt(x.size))
y = np.multiply(np.subtract(x, mean), 1/std_adj)
return y
def whiten(x):
mean = np.mean(x)
std = np.std(x)
y = np.multiply(np.subtract(x, mean), 1.0 / std)
return y
def crop(image, random_crop, image_size):
if image.shape[1]>image_size:
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 + 1), :]
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_size):
width = height = image_size
x = random.randint(0, img.shape[1] - width)
y = random.randint(0, img.shape[0] - height)
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之间的数字,控制样本类别 | 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_vgg19_model_params(dir_path, model_url):
def save_image_pre_annotation(pre_annotation, train_image, annotation):
pre_annotation = np.array(pre_annotation[0])
pre_annotation = (pre_annotation - np.min(pre_annotation)) \
/ (np.max(pre_annotation) - np.min(pre_annotation))
pre_annotation = np.clip(pre_annotation * 255.0, 0, 255.0)
pre_annotation = pre_annotation.astype(np.uint8).reshape((224, 224, 3))
cv2.imshow("generated", pre_annotation)
cv2.imshow("image", train_image[0])
cv2.imshow("ground_truth", annotation[0])
def get_model_data(dir_path, model_url):
maybe_download_and_extract(dir_path, model_url)
filename = model_url.split('/')[-1]
filepath = os.path.join(dir_path, filename)
if not os.path.exists(filepath):
raise IOError("VGG model params not found")
data = scipy.io.loadmat(filepath)
return data
def xavier_init(inputs, outputs, constant=1):
# Xavier initialization
low = -constant * np.sqrt(6.0 / (inputs + outputs))
high = constant * np.sqrt(6.0 / (inputs + outputs))
return tf.random_uniform((inputs, outputs), minval=low, maxval=high, dtype=tf.float32)
def get_weights_variable(inputs, outputs, name):
w = tf.Variable(xavier_init(inputs, outputs), name=name)
return w
def get_bias_variable(num, name):
|
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:
return tf.Variable(initial)
else:
return tf.get_variable(name, initializer=initial)
def bias_variable(shape, name=None):
initial = tf.constant(0.0, shape=shape)
if name is None:
return tf.Variable(initial)
else:
return tf.get_variable(name=name, initializer=initial)
def conv2d_transpose_strided(x, W, b, output_shape=None, stride=2):
if output_shape is None:
output_shape = x.get_shape().as_list()
output_shape[1] *= 2
output_shape[2] *= 2
output_shape[3] *= 2
conv = tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME')
return tf.nn.bias_add(conv, b)
def conv2d_basic(x, W, b):
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.bias_add(conv, b)
def conv2d_strided(x, W, b, stride=None, padding='SAME'):
if stride is None:
conv = tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding=padding)
else:
conv = tf.nn.conv2d(x, W, strides=[1, stride, stride, 1], padding=padding)
return tf.nn.bias_add(conv, b)
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def avg_pool_2x2(x):
return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def process_image(image, mean):
return image - mean
def add_grad_summary(grad, var):
return tf.summary.histogram(var.op.name+'gradient', grad)
def save_image(image, save_dir, name, mean=None):
"""
save the image
:param image:
:param save_dir:
:param name:
:param mean:
:return:
"""
if mean:
image = unprocess_image(image, mean)
misc.imsave(os.path.join(save_dir, name+'.png'), image)
def unprocess_image(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 variables
"""
d = tf.square(tf.subtract(x, y))
d = tf.reduce_sum(d, axis=1)
if positive:
d1, indx = tf.nn.top_k(input=d, k=100)
else:
d1, indx = tf.nn.top_k(input=-d, k=100)
d1 = -1.0 * d1
return d1 * 2.0
def compute_triplet_loss(anchor_feature, positive_feature, negative_feature, margin):
"""
Compute the contrastive loss as in
L = || f_a - f_p ||^2 - || f_a - f_n ||^2 + m
**Parameters**
anchor_feature:
positive_feature:
negative_feature:
margin: Triplet margin
**Returns**
Return the loss operation
"""
with tf.variable_scope('triplet_loss'):
pos_dist = compute_euclidean_distance(anchor_feature, positive_feature, positive=True)
neg_dist = compute_euclidean_distance(anchor_feature, negative_feature, positive=False)
basic_loss = tf.add(tf.subtract(pos_dist, neg_dist), margin)
loss = tf.reduce_mean(tf.maximum(basic_loss, 0.0), 0)
return loss, tf.reduce_mean(pos_dist), tf.reduce_mean(neg_dist)
def compute_accuracy(data_train, labels_train, data_validation, labels_validation, n_classes):
models = []
for i in range(n_classes):
indexes = labels_train == i
models.append(np.mean(data_train[indexes, :], axis=0))
tp = 0
for i in range(data_validation.shape[0]):
d = data_validation[i, :]
l = labels_validation[i]
scores = [consine(m, d) for m in models]
predict = np. argmax(scores)
if predict == 1:
tp += 1
return (float(tp) / data_validation.shape[0]) * 100
def get_index(labels, val):
return [i for i in range(len(labels)) if labels[i] == val]
def prewhiten(x):
mean = np.mean(x)
std = np.std(x)
std_adj = np.maximum(std, 1.0/np.sqrt(x.size))
y = np.multiply(np.subtract(x, mean), 1/std_adj)
return y
def whiten(x):
mean = np.mean(x)
std = np.std(x)
y = np.multiply(np.subtract(x, mean), 1.0 / std)
return y
def crop(image, random_crop, image_size):
if image.shape[1]>image_size:
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 + 1), :]
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_size):
width = height = image_size
x = random.randint(0, img.shape[1] - width)
y = random.randint(0, img.shape[0] - height)
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之间的数字,控制样本类别中心 | 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 matching;
};
uuid = function() {
var d;
d = Date.now();
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r;
r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : r & 0x7 | 0x8).toString(16);
});
};
random = function(l) {
var i, list, token;
l = l || 10;
token = "";
list = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
i = 0;
while (i < l) {
token += list.charAt(Math.floor(Math.random() * list.length));
i++;
}
return token;
};
checkCookie = function(name) {
var end, start, val;
val = document.cookie;
start = val.indexOf(" " + name + "=");
if (start === -1) {
start = val.indexOf(name + "=");
}
if (start === -1) {
val = null;
} else {
start = val.indexOf("=", start) + 1;
end = val.indexOf(";", start);
if (end === -1) {
end = val.length;
}
val = unescape(val.substring(start, end));
}
return ((val != null) && val !== "null" && val !== "" ? val : null);
};
setCookie = function(name, val, minutes) {
var expires;
expires = new Date();
expires.setMinutes(expires.getMinutes() + minutes);
document.cookie = name + '=' + val + '; expires=' + expires.toUTCString() + '; path=/;';
return val;
};
gbi = function(data) {
var M, N, r, tem, ua;
data = data || {};
N = navigator.appName;
ua = navigator.userAgent;
tem = void 0;
r = /(crios|opera|chrome|safari|firefox|msie|android|iphone|ipad)\/?\s*(\.?\d+(\.\d+)*)/i;
M = ua.match(r);
if (M && ((tem = ua.match(/version\/([\.\d]+)/i)) != null)) {
M[2] = tem[1];
}
data.b = M[1];
data.bv = M[2];
data.sw = screen.width;
data.sh = screen.height;
data.bw = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
data.bh = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
r = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
if (r.test(navigator.userAgent)) {
data.bm = true;
} else {
data.bm = false;
}
if (navigator.appVersion.indexOf("Win") !== -1) {
data.os = "Windows";
} else if (navigator.appVersion.indexOf("iPad") !== -1) {
data.os = "iOS";
} else if (navigator.appVersion.indexOf("iPhone") !== -1) {
data.os = "iOS";
} else if (navigator.appVersion.indexOf("Android") !== -1) {
data.os = "Android";
} else if (navigator.appVersion.indexOf("Mac") !== -1) {
data.os = "Mac";
} else if (navigator.appVersion.indexOf("Linux") !== -1) {
data.os = "Linux";
} else if (navigator.appVersion.indexOf("X11") !== -1) {
data.os = "Unix";
} else {
data.os = "Unknown";
}
return data;
};
gvi = function(data) {
var rf, rh, _t;
data = data || {};
_t = new Date();
data.tl = new Date();
_t = _t.toString();
data.tz = (_t.indexOf("(") > -1 ? _t.match(/\([^\)]+\)/)[0].match(/[A-Z]/g).join("") : _t.match(/[A-Z]{3,4}/)[0]);
if (_BA._tz === "GMT" && /(GMT\W*\d{4})/.test(_t)) {
data.tz = RegExp.$1;
}
data.h = window.location.host;
data.hf = window.location.href;
rh = document.referrer.split("/")[2];
if (rh) {
data.rh = rh;
}
rf = document.referrer;
if (rf) {
data.rf = rf;
}
return data;
};
/*
# translations
data =
c: (if typeof params.c isnt 'undefined' then params.c else null) # campaign
s: (if typeof params.s isnt 'undefined' then params.s else null) # secret
cs: [] # secondary campaigns
bz: [] # bloom zones
be: [] # bloom event listeners
BIRD: null # Bloom Internal Referral Data
vt: null # visitor token (long term)
st: null # session token (short term)
it: null # impression token (unique)
rv: false # returning visitor
tz: null # time zone
tl: null # time local
sw: null # screen width
sh: null # screen height
bw: null # browser width
bh: null # browser height
b: null # browser
bv: null # browser version
bm: false # browser mobile
os: null # operating system
h: null # host
hf: null # host full
rh: null # referrer host
rf: null # referrer full
*/
Atlas = function(params) {
var e;
if (!(this instanceof Atlas)) {
return new Atlas(params);
}
this.useBIRD = (typeof params.BIRD !== 'undefined' ? params.BIRD : false);
this.c = (typeof params.c !== 'undefined' ? params.c : null);
this.it = null;
if (!this.c) {
e = 'Atlas could not instantiate - no campaign specified!';
throw new Error(e);
}
wrapOnload(this.initBells, this);
this.capture();
return this;
};
Atlas.prototype.reload = function(c) {
this.c = c || this.c || uuid();
wrapOnload(this.initBells, this);
wrapOnload(this.initGazelle, this);
return this.capture();
};
Atlas.prototype.initBells = function() {
var bell, bells, e, _i, _len, _results,
_this = this;
bells = getAllElementsWithAttribute('data-BELL');
console.log('Got bells.', bells);
e = 'click';
_results = [];
for (_i = 0, _len = bells.length; _i < _len; _i++) {
bell = bells[_i];
_results.push((function(bell) {
var campaign, cb;
campaign = bell.getAttribute('data-BELL');
cb = function() {
console.log('Someone rang the bell.', campaign);
_this.save({
c: campaign
}, 'event');
return bell.removeEventListener(e, cb);
};
bell.addEventListener(e, cb);
return bell.removeAttribute('data-BELL');
})(bell));
}
return _results;
};
Atlas.prototype.initGazelle = function() {
var p, placeholders, requests, _fn, _i, _len;
placeholders = getAllElementsWithAttribute('data-GAZELLE');
requests = [];
_fn = function(p) {
var data, e, r;
data = p.getAttribute('data-GAZELLE');
try {
r = JSON.parse(data);
return requests.push(r);
} catch (_error) {
e = _error;
throw new Error('Error! Badly formatted Gazelle parameters.');
}
};
for (_i = 0, _len = placeholders.length; _i < _len; _i++) {
p = placeholders[_i];
_fn(p);
}
return console.log('Initialized requests.', requests);
};
Atlas.prototype.BIRD = function() {
var anchors, data, hash, hashes, href, i, useBIRD;
data = data || {};
data.BIRD = null;
useBIRD = this.useBIRD || false;
hashes = window.location.href.slice(window.location.href.indexOf("?") + 1).split("&");
i = 0;
while (i < hashes.length) {
hash = hashes[i].split("=");
if (hash[0] === "BIRD") { | 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 plot in a plot widget
self.plotWidgetList = []
self.penStyleList= [[(0,0,200),(200,200,100),(195,46,212)],[(237,177,32),(126,47,142),(43,128,200)],[(0,0,200),(200,200,100),(195,46,212)]]
self.index=0
self.dataListLen = []
self.ROI1 = None # region of interest
self.ROI2 = None
self.dataTotolLen = 0
self.curveList = []
self.curveList2 = []
self.curveXData =[i for i in range(0,self.numOfDataToPlot) ] #initial x value
self.curveYDataList=[]
self.curveYDataList2=[]
self.app = QtGui.QApplication([])
self.mainWindow = QtGui.QMainWindow()
self.mainWindow.setWindowTitle('pyqtgraph example: PlotWidget')
self.mainWindow.resize(720,640)
self.GuiWiget = QtGui.QWidget()
self.mainWindow.setCentralWidget(self.GuiWiget)
layout = QtGui.QVBoxLayout()
secondLayout = QtGui.QHBoxLayout()
thirdLayout = QtGui.QHBoxLayout()
self.GuiWiget.setLayout(layout)
layout.addLayout(secondLayout)
layout.addLayout(thirdLayout)
pg.setConfigOption('background', 'w')
# create plot widgets by pg.PlotWidget(name=name) and we can draw multiple curve lines on it
for i,name in zip(range(0,self.numofPlotWidget),nameList):
plotWidget = pg.PlotWidget(name=name)
# set X range
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("Start:")
self.startWindows = QtGui.QLineEdit()
self.endLabel= QtGui.QLabel("End:")
self.endWindows = QtGui.QLineEdit()
self.button = QtGui.QPushButton('Split')
self.button.clicked.connect(self.DrawPic)
self.fileName= QtGui.QLabel("fileName:")
self.fileInputName = QtGui.QComboBox()
#self.fileInputName.setText("UpStraight0.dat")
self.Readbutton = QtGui.QPushButton('Read')
self.Readbutton.clicked.connect(self.ReadFile)
secondLayout.addWidget(self.startLabel)
secondLayout.addWidget(self.startWindows)
secondLayout.addWidget(self.endLabel)
secondLayout.addWidget(self.endWindows)
secondLayout.addWidget(self.button)
secondLayout.addWidget(self.fileName)
secondLayout.addWidget(self.fileInputName)
secondLayout.addWidget(self.Readbutton)
self.Aobj= QtGui.QLabel("A:")
self.comboA = QtGui.QComboBox()
self.AstartLabel= QtGui.QLabel("Start:")
self.AstartWindows = QtGui.QLineEdit()
self.AendLabel= QtGui.QLabel("End:")
self.AendWindows = QtGui.QLineEdit()
self.Comparebutton = QtGui.QPushButton('Compare')
#register a callback funtion - when button is pressed, we execute it
self.Comparebutton.clicked.connect(self.compare)
thirdLayout.addWidget(self.AstartLabel)
thirdLayout.addWidget(self.AstartWindows)
thirdLayout.addWidget(self.AendLabel)
thirdLayout.addWidget(self.AendWindows)
thirdLayout.addWidget(self.Aobj)
thirdLayout.addWidget(self.comboA)
thirdLayout.addWidget(self.Comparebutton)
# read file from Directory
self.readDir()
# Display the whole GUI architecture
self.mainWindow.show()
#Create plot instance by plotWidget.plot() and initial the Y value
for plotWidget,penStyle in zip(self.plotWidgetList,self.penStyleList):
for i in range(0,self.plotNum):
curve = plotWidget.plot()
curve.setPen(penStyle[i])
curveYData =[np.NAN for i in range(0,self.numOfDataToPlot) ] #initial y value
self.curveList.append(curve)
self.curveYDataList.append(curveYData)
for i in range(0,self.plotNum):
curve = self.plotWidgetList[2].plot()
curve.setPen(penStyle[i])
curveYData =[np.NAN for i in range(0,self.numOfDataToPlot) ]
self.curveList2.append(curve)
self.curveYDataList2.append(curveYData)
self.SettingModel()
print "init ok"
self.writeout = True
self.logfp = open('log.txt', "w")
self.timeLogfp = open('Timelog.txt', "w")
def SettingModel(self):
'''load model here'''
pass
def close(self):
self.app.closeAllWindows()
self.app.quit()
def ResetGraph(self):
for i in range(0, len(self.curveYDataList) ):
self.curveYDataList[i] =[np.NAN for j in range(0,self.numOfDataToPlot) ]
for i in range(0, len(self.curveYDataList2) ):
self.curveYDataList2[i] =[np.NAN for j in range(0,self.numOfDataToPlot) ]
self.dataListLen = []
self.dataTotolLen = 0
try:
self.plotWidgetList[0].removeItem(self.ROI1)
self.plotWidgetList[1].removeItem(self.ROI2)
except:
pass
self.ROI1 = None
self.ROI2 = None
def RegionWindows(self,upBbound):
axes = ['X','Y','Z']
Dirs = ['P2N','N2P']
ret = {}
ret['X'] ={}
ret['Y'] ={}
ret['Z'] ={}
ret['X']['N2P'] = []
ret['X']['P2N'] = []
ret['Y']['N2P'] = []
ret['Y']['P2N'] = []
ret['Z']['N2P'] = []
ret['Z']['P2N'] = []
for axis in axes:
for Dir in Dirs:
for boundry in self.windowsCrossDataIndex[axis][Dir]:
if boundry[1] > upBbound:
break
else:
ret[axis][Dir].append(boundry)
return ret
def GetInfo(self,ret):
axes = ['X','Y','Z']
Dirs = ['P2N','N2P']
pos = {}
pos['X'] =[0,1]
pos['Y'] =[1,2]
pos['Z'] =[2,3]
for axis in axes:
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]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0))
if np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0)) < 0.15:
idx.append(None)
# print np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0))
else:
idx.append(np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0)) )
def DrawPic(self):
self.ResetGraph()
startWindowsIdx = int(self.startWindows.text())
endWindowsIdx = int(self.endWindows.text())
| 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("Start:")
self.startWindows = QtGui.QLineEdit()
self.endLabel= QtGui.QLabel("End:")
self.endWindows = QtGui.QLineEdit()
self.button = QtGui.QPushButton('Split')
self.button.clicked.connect(self.DrawPic)
self.fileName= QtGui.QLabel("fileName:")
self.fileInputName = QtGui.QComboBox()
#self.fileInputName.setText("UpStraight0.dat")
self.Readbutton = QtGui.QPushButton('Read')
self.Readbutton.clicked.connect(self.ReadFile)
secondLayout.addWidget(self.startLabel)
secondLayout.addWidget(self.startWindows)
secondLayout.addWidget(self.endLabel)
secondLayout.addWidget(self.endWindows)
secondLayout.addWidget(self.button)
secondLayout.addWidget(self.fileName)
secondLayout.addWidget(self.fileInputName)
secondLayout.addWidget(self.Readbutton)
self.Aobj= QtGui.QLabel("A:")
self.comboA = QtGui.QComboBox()
self.AstartLabel= QtGui.QLabel("Start:")
self.AstartWindows = QtGui.QLineEdit()
self.AendLabel= QtGui.QLabel("End:")
self.AendWindows = QtGui.QLineEdit()
self.Comparebutton = QtGui.QPushButton('Compare')
#register a callback funtion - when button is pressed, we execute it
self.Comparebutton.clicked.connect(self.compare)
thirdLayout.addWidget(self.AstartLabel)
thirdLayout.addWidget(self.AstartWindows)
thirdLayout.addWidget(self.AendLabel)
thirdLayout.addWidget(self.AendWindows)
thirdLayout.addWidget(self.Aobj)
thirdLayout.addWidget(self.comboA)
thirdLayout.addWidget(self.Comparebutton)
# read file from Directory
self.readDir()
# Display the whole GUI architecture
self.mainWindow.show()
#Create plot instance by plotWidget.plot() and initial the Y value
for plotWidget,penStyle in zip(self.plotWidgetList,self.penStyleList):
for i in range(0,self.plotNum):
curve = plotWidget.plot()
curve.setPen(penStyle[i])
curveYData =[np.NAN for i in range(0,self.numOfDataToPlot) ] #initial y value
self.curveList.append(curve)
self.curveYDataList.append(curveYData)
for i in range(0,self.plotNum):
curve = self.plotWidgetList[2].plot()
curve.setPen(penStyle[i])
curveYData =[np.NAN for i in range(0,self.numOfDataToPlot) ]
self.curveList2.append(curve)
self.curveYDataList2.append(curveYData)
self.SettingModel()
print "init ok"
self.writeout = True
self.logfp = open('log.txt', "w")
self.timeLogfp = open('Timelog.txt', "w")
def SettingModel(self):
'''load model here'''
pass
def close(self):
self.app.closeAllWindows()
self.app.quit()
def ResetGraph(self):
for i in range(0, len(self.curveYDataList) ):
self.curveYDataList[i] =[np.NAN for j in range(0,self.numOfDataToPlot) ]
for i in range(0, len(self.curveYDataList2) ):
self.curveYDataList2[i] =[np.NAN for j in range(0,self.numOfDataToPlot) ]
self.dataListLen = []
self.dataTotolLen = 0
try:
self.plotWidgetList[0].removeItem(self.ROI1)
self.plotWidgetList[1].removeItem(self.ROI2)
except:
pass
self.ROI1 = None
self.ROI2 = None
def RegionWindows(self,upBbound):
axes = ['X','Y','Z']
Dirs = ['P2N','N2P']
ret = {}
ret['X'] ={}
ret['Y'] ={}
ret['Z'] ={}
ret['X']['N2P'] = []
ret['X']['P2N'] = []
ret['Y']['N2P'] = []
ret['Y']['P2N'] = []
ret['Z']['N2P'] = []
ret['Z']['P2N'] = []
for axis in axes:
for Dir in Dirs:
for boundry in self.windowsCrossDataIndex[axis][Dir]:
if boundry[1] > upBbound:
break
else:
ret[axis][Dir].append(boundry)
return ret
def GetInfo(self,ret):
axes = ['X','Y','Z']
Dirs = ['P2N','N2P']
pos = {}
pos['X'] =[0,1]
pos['Y'] =[1,2]
pos['Z'] =[2,3]
for axis in axes:
|
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
dataList = np.concatenate((self.Acc[startIDX:endIDX,:],self.Angle[startIDX:endIDX,:]),axis=1)
# print "scipy.stats.skewtest:",scipy.stats.skewtest(self.Acc[startIDX:endIDX,:],axis=0)
# print "mean:",np.mean( self.Acc[self.workingIdx[endWindowsIdx][0]:endIDX,:] ,axis=0)
# print "start angle:",self.Angle[startIDX,:],"Last angle:",self.Angle[endIDX-1,:]
# print "local Min X:",scipy.signal.argrelmin(self.Acc[startIDX:endIDX,0:1] ,axis=0)[0],"local Min Y:",scipy.signal.argrelmin(self.Acc[startIDX:endIDX,1:2] ,axis=0)[0],"local Min Z:",scipy.signal.argrelmin(self.Acc[startIDX:endIDX,2:3] ,axis=0)[0]
# print "local Max X:",scipy.signal.argrelmax(self.Acc[startIDX:endIDX,0:1] ,axis=0)[0],"local Max Y:",scipy.signal.argrelmax(self.Acc[startIDX:endIDX,1:2] ,axis=0)[0],"local Max Z:",scipy.signal.argrelmax(self.Acc[startIDX:endIDX,2:3] ,axis=0)[0]
dataList = dataList[::self.ScalerNum,:]
self.GetInfo(ret)
dataList = dataList.transpose()
self.ROI1 = pg.LinearRegionItem([startIDX,endIDX])
self.ROI2 = pg.LinearRegionItem([startIDX,endIDX])
self.plotWidgetList[0].addItem(self.ROI1)
self.plotWidgetList[1].addItem(self.ROI2)
# print endIDX-startIDX,dataList.shape
for data,curve,yData,i in zip (dataList,self.curveList2,self.curveYDataList2 ,range(0,7)):
# print len(yData)
yData[0:dataList.shape[1]] = dataList[i,:].tolist()[0]
# print len(dataList[i,:].tolist())
curve.setData(y=yData | 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]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0))
if np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0)) < 0.15:
idx.append(None)
# print np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0))
else:
idx.append(np.sqrt(np.mean(np.multiply(self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]],self.Acc[idx[0]:idx[1],pos[axis][0]:pos[axis][1]]),axis=0)) ) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.