text:
Q: BB 10 cascade Disable physical back button on blackberry classic Need a help i'm using native sdk (Momentics).
I want to disable the physical "Back" button on blackberry classic device throughout my application.
Thanks in advance.

A: To disable the back button override the code with
shortcuts: [
    DeviceShortcut {
        type: DeviceShortcuts.BackTap
        onTriggered: {
            //do somethings
        }
    }
]

However it is useful performs some action after the click of the back button.
For more info:
BlackBerry Documentation


text:
Q: Update MediaStore audio tags will not work I am trying to edit Mp3-Information of the MediaStore.
All the edited Mp3 Songs do not have an album name.
ContentResolver res = FindCoverActivity.this.getContentResolver();
Uri sSongUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri uri2 = ContentUris.withAppendedId(sSongUri, song_id);

ContentValues values2 = new ContentValues();
values2.put(MediaStore.Audio.Media.ALBUM_ID,"9999"); //new album_id. I dont know how to get an unused id..
values2.put(MediaStore.Audio.Media.ALBUM, "test_album");
Integer as = res.update(uri2, values2,null,null);
if (as != 0) {
     // got updated
}

This code does not work. The result is a messed up mediastore..
Does anyone know more? Thanks!

A: There is an android table called albums which has the following colmns:
album_id (Integer)
album_key (Text not null)
album (text)
both album_id and album_key are maintained by the android system so do not worry about them.
If I understand your problem, you need to find a specific album and then edit the albumname. You must have these in a specific folder structure otherwise you could not identify an album.
Why not use a pc and some mp3 tagging tool such as Mp3 Tag Tools. This also allows you to add albumart etc.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: My Array Restarts and Not Append  class NewCourseViewController: UIViewController {

  @IBOutlet weak var courseNameTextField: UITextField!

     override func viewDidLoad() {
       super.viewDidLoad()
    }

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using       segue.destinationViewController.
    // Pass the selected object to the new view controller.

        if segue.identifier == "newClassComplete" {

if let vcSendingToo = segue.destination as?              CoursesTableViewController {

// Pass courseName to nameOfCourses Array

  // Course Name
  let courseName = courseNameTextField.text!
  vcSendingToo.nameOfCourse = courseName
  vcSendingToo.nameOfCourses.append(vcSendingToo.nameOfCourse)

}

class CoursesTableViewController: UITableViewController {

var nameOfCourses = [String]()
var nameOfCourse = ""

}

It restarts to a blank array rather than add a value to the same array. I can't find any examples that are online that'll help resolve my issue. It was working fin then stopped all of a su

A: Have you tried to change this line
let courseName = courseNameTextField.text!
vcSendingToo.nameOfCourse = courseName
vcSendingToo.nameOfCourses.append(vcSendingToo.nameOfCourse)

to this?
let courseName = courseNameTextField.text ?? "" //validate for nil
vcSendingToo.nameOfCourse = courseName
vcSendingToo.nameOfCourses = [courseName]

A: I made the variables global and removed the "vcSendingToo" properties.


text:
Q: Is there a number such that the sequence of its best rational approximations is strictly increasing? The rational approximations of $\sqrt 2$ given by its continuous fraction are: 1.5, 1.333, 1.4, 1.417, 1.412, etc. which is not strictly increasing.
Similarly, this sequence for $\phi=(1+\sqrt5)\big/2$ is 2.0, 1.5, 1.667, 1.6, 1.625, etc.
Is there a real number so that the sequence of the best rational approximations (in the sense of continuous fractions) is strictly increasing?

A: Look at the paragraph Some Useful Theorems in the Wikipedia article on continued fractions. There you will find, for instance, the statement
$$\frac{h_n}{k_n}-\frac{h_{n-1}}{k_{n-1}}={(-1)^{n+1}}{k_nk_{n-1}}$$
where $\frac{h_n}{k_n}$ is the $n$th convergent of the continued fraction.
What this means is that the successive continued-fraction approximations to a positive irrational number will successively over- and under-estimate the limit. So not even three successive terms can be increasing.

A: Recall that the $n$th approximation for $\alpha$ is $\lfloor \alpha\rfloor$ plus the $(n-1)$st approximation for $\frac1{\alpha-\lfloor \alpha\rfloor}$. You can show by induction that it does not depend on the irrational $\alpha$, but only on the parity of $n$ whether the $n$th approximation is two small or too big.


text:
Q: How to name an inherited classes? Let's say I have inheritance like this
         Person
           |
     +-----+------+
     |            |
 Student       Teacher

Then I would call Person the Base.
How would I call Student?
Inherited class sounds stupid. Is there a single word for it?

A: Basically using Base for super class, so: PersonBase
And for it's implementations it's common to add Impl like: StudentImpl and TeacherImpl


text:
Q: Attempting to debug the terraform-provider-azurerm so that I can contribute to the community. But terraform plan crashes Introduction
Hi guys, I am trying to get started with contributing to the terraform-provider-azurerm. I have noticed a problem with the azurerm_firewall_network_rule_collection  I have reported it here. I thought I should take this as an opportunity to see if I can chip in and try to fix the problem I have reported! If I can debug the provider and see how the code works, then not only will I learn go, I will also be able to figure out and help with bug fixes/feature enhancements.  Any Help you guys can provide me and guide me towards the right direction will be much appreciated. I know your time is precious, and I did my best before coming to ask for help.

Summary of what I have tried to do the folllowing:

*

*Fork the terraform-provider-azurerm repository.

*Clone the forked repo to my local. I am using Ubuntu 20.04 in WSL.

*Running vscode version 1.54.3

*using terraform 0.14.9, used tfenv to install and manage different versions.

*Install golang and related go tools in vscode. I am on go version go1.16.2 linux/amd64. Used linuxbrew to install go.

*Install gcc5. Used linuxbrew to install.

*Install delve debugger. Used linuxbrew to install.

*Create a very simple terraform main.tf which just deploys a resource group to my Azure subscription.

*Create a .terraformrc file ( set it in the location /home/rahul/.terraformrc ) to supply dev_overrides path to the provider.

*Modify the main.go ( location /usr/local/go/src/github.com/terraform-providers/terraform-provider-azurerm/main.go) to use debug statements.

*Compile the provider with the debug code and create new binaries.

*Attach dlv in headless mode to this binary

*Use the data from the previous step to set it in the variable TF_REATTACH_PROVIDERS

*Run Terraform plan - hoping that have a successful plan runs.

*Turn off debug mode and compile the provider and then run terraform plan.

*Plan runs successfully using the local provider.

The Problem

*

*The plan crashes with
Terraform crashed! This is always indicative of a bug within Terraform.
A crash log has been placed at "crash.log" relative to your current
working directory. It would be immensely helpful if you could please
report the crash with Terraform[1] so that we can fix this.

*Content from log output
  2021/04/05 06:09:50 [INFO] Terraform version: 0.14.9
  2021/04/05 06:09:50 [INFO] Go runtime version: go1.15.6
  2021/04/05 06:09:50 [INFO] CLI args: []string{"/home/rahul/.tfenv/versions/0.14.9/terraform", "plan"}
  2021/04/05 06:09:50 [DEBUG] Attempting to open CLI config file: /home/rahul/.terraformrc
  2021/04/05 06:09:50 Loading CLI configuration from /home/rahul/.terraformrc
  2021/04/05 06:09:50 [DEBUG] Explicit provider installation configuration is set
  2021/04/05 06:09:50 [TRACE] Selected provider installation method cliconfig.ProviderInstallationDirect with includes [] and     excludes []
  2021/04/05 06:09:50 [INFO] CLI command args: []string{"plan"}
  2021/04/05 06:09:50 [TRACE] Meta.Backend: built configuration for "local" backend with hash value 666019178
  2021/04/05 06:09:50 [TRACE] Preserving existing state lineage "8773571c-7605-2553-b418-08cbb37374a4"
  2021/04/05 06:09:50 [TRACE] Preserving existing state lineage "8773571c-7605-2553-b418-08cbb37374a4"
  2021/04/05 06:09:50 [TRACE] Meta.Backend: working directory was previously initialized for "local" backend
  2021/04/05 06:09:50 [TRACE] Meta.Backend: using already-initialized, unchanged "local" backend configuration
  2021/04/05 06:09:50 [TRACE] Meta.Backend: instantiated backend of type *local.Local
  2021/04/05 06:09:50 [TRACE] providercache.fillMetaCache: scanning directory .terraform/providers
  2021/04/05 06:09:50 [TRACE] getproviders.SearchLocalDirectory: .terraform/providers is a symlink to .terraform/providers
  2021/04/05 06:09:50 [TRACE] getproviders.SearchLocalDirectory: found registry.terraform.io/hashicorp/azurerm v2.53.0 for    linux_amd64 at .terraform/providers/registry.terraform.io/hashicorp/azurerm/2.53.0/linux_amd64
  2021/04/05 06:09:50 [TRACE] providercache.fillMetaCache: including .terraform/providers/registry.terraform.io/hashicorp/    azurerm/2.53.0/linux_amd64 as a candidate package for registry.terraform.io/hashicorp/azurerm 2.53.0
  2021/04/05 06:09:50 [DEBUG] Provider registry.terraform.io/hashicorp/azurerm is overridden to load from /usr/local/go/bin
  2021/04/05 06:09:50 [DEBUG] checking for provisioner in "."
  2021/04/05 06:09:50 [DEBUG] checking for provisioner in "/home/rahul/.tfenv/versions/0.14.9"
  2021/04/05 06:09:50 [INFO] Failed to read plugin lock file .terraform/plugins/linux_amd64/lock.json: open .terraform/   plugins/linux_amd64/lock.json: no such file or directory
  2021/04/05 06:09:50 [TRACE] Meta.Backend: backend *local.Local supports operations
  2021/04/05 06:09:50 [INFO] backend/local: starting Plan operation
  2021/04/05 06:09:50 [TRACE] backend/local: requesting state manager for workspace "default"
  2021/04/05 06:09:50 [TRACE] backend/local: state manager for workspace "default" will:
  - read initial snapshot from terraform.tfstate
  - write new snapshots to terraform.tfstate
  - create any backup at terraform.tfstate.backup
  2021/04/05 06:09:50 [TRACE] backend/local: requesting state lock for workspace "default"
  2021/04/05 06:09:50 [TRACE] statemgr.Filesystem: preparing to manage state snapshots at terraform.tfstate
  2021/04/05 06:09:50 [TRACE] statemgr.Filesystem: no previously-stored snapshot exists
  2021/04/05 06:09:50 [TRACE] statemgr.Filesystem: locking terraform.tfstate using fcntl flock
  2021/04/05 06:09:50 [TRACE] statemgr.Filesystem: writing lock metadata to .terraform.tfstate.lock.info
  2021/04/05 06:09:50 [TRACE] backend/local: reading remote state for workspace "default"
  2021/04/05 06:09:50 [TRACE] statemgr.Filesystem: reading latest snapshot from terraform.tfstate
  2021/04/05 06:09:50 [TRACE] statemgr.Filesystem: snapshot file has nil snapshot, but that's okay
  2021/04/05 06:09:50 [TRACE] statemgr.Filesystem: read nil snapshot
  2021/04/05 06:09:50 [TRACE] backend/local: retrieving local state snapshot for workspace "default"
  2021/04/05 06:09:50 [TRACE] backend/local: building context for current working directory
  2021/04/05 06:09:50 [TRACE] terraform.NewContext: starting
  2021/04/05 06:09:50 [TRACE] terraform.NewContext: loading provider schemas
  2021/04/05 06:09:50 [TRACE] LoadSchemas: retrieving schema for provider type "registry.terraform.io/hashicorp/azurerm"
  panic: runtime error: invalid memory address or nil pointer dereference
  [signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x20f82d2]

  goroutine 52 [running]:
  github.com/hashicorp/terraform/plugin.(*GRPCProviderPlugin).Client(0xc00054ef60, 0xc00054e560, 0xc0003321e0,    0x7f73af739388, 0xc00094a180, 0x0, 0xc000817a6c)
      <autogenerated>:1 +0x32
  github.com/hashicorp/go-plugin.(*RPCClient).Dispense(0xc00073ce40, 0x289bfc5, 0x8, 0x0, 0x0, 0x29cd9d8, 0xc0003a6b30)
      /go/pkg/mod/github.com/hashicorp/go-plugin@v1.3.0/rpc_client.go:159 +0x254
  github.com/hashicorp/terraform/command.unmanagedProviderFactory.func1(0x24b0360, 0xc000575950, 0xc0003a6c08, 0xc00000b270)
      /home/circleci/project/project/command/meta_providers.go:448 +0x248
  github.com/hashicorp/terraform/terraform.(*basicComponentFactory).ResourceProvider(0xc00017d4b0, 0xc000578d8a, 0x7,     0xc000578d80, 0x9, 0x28bc2ba, 0x15, 0x2892906, 0x1, 0xc000578d8a, ...)
      /home/circleci/project/project/terraform/context_components.go:55 +0x351
  github.com/hashicorp/terraform/terraform.loadProviderSchemas.func1(0xc000578d8a, 0x7, 0xc000578d80, 0x9, 0x28bc2ba, 0x15)
      /home/circleci/project/project/terraform/schemas.go:103 +0x36e
  github.com/hashicorp/terraform/terraform.loadProviderSchemas(0xc000731ec0, 0xc0002c11e0, 0x0, 0x2ce93a0, 0xc00017d4b0,  0xc0000f2080, 0x3dcafe0, 0xc0000f2050)
      /home/circleci/project/project/terraform/schemas.go:174 +0x250
  github.com/hashicorp/terraform/terraform.LoadSchemas(0xc0002c11e0, 0x0, 0x2ce93a0, 0xc00017d4b0, 0x0, 0x2, 0x7f73afb6b400)
      /home/circleci/project/project/terraform/schemas.go:84 +0xc6
  github.com/hashicorp/terraform/terraform.NewContext(0xc0003a79d0, 0x0, 0x0, 0xc00098b900, 0x1)
      /home/circleci/project/project/terraform/context.go:205 +0x2ea
  github.com/hashicorp/terraform/backend/local.(*Local).contextDirect(0xc00015ef70, 0xc0008e2700, 0xc0002c11e0, 0x0, 0x0,     0x0, 0x0, 0x0, 0xc000731d10, 0xc000421120, ...)
      /home/circleci/project/project/backend/local/backend_local.go:178 +0x2ff
  github.com/hashicorp/terraform/backend/local.(*Local).context(0xc00015ef70, 0xc0008e2700, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0)
      /home/circleci/project/project/backend/local/backend_local.go:111 +0xf18
  github.com/hashicorp/terraform/backend/local.(*Local).opPlan(0xc00015ef70, 0x2ce83a0, 0xc00073cb40, 0x2ce83a0,  0xc00073cb80, 0xc0008e2700, 0xc00073cb00)
      /home/circleci/project/project/backend/local/backend_plan.go:70 +0x2cb
  github.com/hashicorp/terraform/backend/local.(*Local).Operation.func1(0xc00017d130, 0xc00017d140, 0xc00017d150,     0xc00015ef70, 0xc00017d120, 0x2ce83a0, 0xc00073cb40, 0x2ce83a0, 0xc00073cb80, 0xc0008e2700, ...)
      /home/circleci/project/project/backend/local/backend.go:340 +0xe8
  created by github.com/hashicorp/terraform/backend/local.(*Local).Operation
      /home/circleci/project/project/backend/local/backend.go:334 +0x36d

Detailed steps including source code.
I have followed the steps documented in Terraform Docs - Debugger based debugging

*

*Go Installation path => /usr/local/go

*terraform-provider-azurerm cloned to => /usr/local/go/src/github.com/terraform-providers

*terraform-provider-azurerm source path => /usr/local/go/src/github.com/terraform-providers/terraform-provider-azurerm

*Terraform main.tf source path => ~/Code/terraform

*My terraform code
  locals {
  location      = "australiaeast"
  resourcegroup = "rg-azfw"
}

terraform {
  backend "local" {}
}

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "2.53.0"
    }
  }
}

provider "azurerm" {
  tenant_id                  = "xxxxxx-xxxxx-xxxxx-xxxxx-xxxx"
  skip_provider_registration = true
  features {}
}

resource "azurerm_resource_group" "resourcegroup" {
  name     = local.resourcegroup
  lo

*My .terraformrc
  provider_installation {

  # Use /home/developer/go/bin as an overridden package directory
  # for the hashicorp/azurerm provider. This disables the version and checksum
  # verifications for this provider and forces Terraform to look for the
  # azurerm provider plugin in the given directory.
  dev_overrides {
    "registry.terraform.io/hashicorp/azurerm" = "/usr/local/go/bin"
  }

  # For all other providers, install them directly from their origin provider
  # registries as normal. If you omit this, Terraform will _only_ use
  # the dev_overrides block, and so no other providers will be available.
   direct {}
  }

*Modified the main.go file in terraform-provider-azurerm so that the provider binary can be launched in debugger mode. Now the main function looks like :
func main() {
    // remove date and time stamp from log output as the plugin SDK already adds its own
    log.SetFlags(log.Flags() &^ (log.Ldate | log.Ltime))
    var debugMode bool

    flag.BoolVar(&debugMode, "debug", true, "set to true to run the provider with support for debuggers like delve")
    flag.Parse()

    opts := &plugin.ServeOpts{ProviderFunc: azurerm.Provider}

    if debugMode {
        // TODO: update this string with the full name of your provider as used in your configs
        err := plugin.Debug(context.Background(), "registry.terraform.io/hashicorp/azurerm", opts)
        if err != nil {
            log.Fatal(err.Error())
        }
        return
    }

    plugin.Serve(opts)
    // plugin.Serve(&plugin.ServeOpts{
    //  ProviderFunc: azurerm.Provider,
    // })
}

*The vscode debugger launch config looks like :
    {
        // Use IntelliSense to learn about possible attributes.
        // Hover to view descriptions of existing attributes.
        // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
        "version": "0.2.0",
        "configurations": [
            {
                "name": "Connect to server",
                "type": "go",
                "request": "attach",
                "mode": "remote",
                "remotePath": "${workspaceFolder}",
                "port": 36283,
                "host": "127.0.0.1",
                "apiVersion": 1
            }
        ]
    }

*Ran make build to build the binaries. It copies the binary to $GOPATH/bin/ location.

*Launching the delv headless debugger with the command dlv exec --listen=127.0.0.1:36283 --api-version=1 --headless $GOPATH/bin/terraform-provider-azurerm -- --debug

*

*The --listen=127.0.0.1:36283 is an additional parameter I googled and figured out - not mentioned in terraform docs. This helps me in not changing the ports for debugging everytime I am launching the debugger.

*That produces an output like :
  API server listening at: 127.0.0.1:36283
  {"@level":"debug","@message":"plugin address","@timestamp":"2021-04-05T06:08:38.863169+10:00","address":"/tmp/  plugin594405865","network":"unix"}
  Provider server started; to attach Terraform, set TF_REATTACH_PROVIDERS to the following:
  {"registry.terraform.io/hashicorp/azurerm":{"Protocol":"netrpc","Pid":16362,"Test":true,"Addr":{"Network":"unix","String":"/    tmp/plugin594405865"}}}

*Set the TF_REATTACH_PROVIDERS value
    export TF_REATTACH_PROVIDERS='{"registry.terraform.io/hashicorp/azurerm":{"Protocol":"netrpc","Pid":16362,"Test":true,"Addr":{"Network":"unix","String":"/tmp/plugin594405865"}}}'

*Run the terraform plan in the folder where the tf source code is there.. And all goes boom.


text:
Q: Does every presentation correspond to a group? I am a graduate student. I do not know much about group presentations. I have only seen those things while studying Dihedral groups and Quaternion groups.
For example, $D_n=\langle r,f\mid r^n=1,f^2=1,fr=rf^{-1}\rangle$ and $Q_8=\langle a,b\mid a^4=1,ab=ba^{-1},a^2=b^2\rangle$. I know that groups can be represented in this way.
Is there actually exist a group satisfying those relations? If yes,then what is the justification? For example, can I get a group $G=\langle a,b,c\mid a^2=b^3=c^4=1,ab=bc=ca\rangle$?

A: Yes.  The group is the free group on the  generators modulo the normal closure of (smallest normal subgroup generated by) the subgroup generated by the relators.
So in your example,  say, $G=F_3/\langle a^2,b^3,c^4,b^{-1}abc^{-1},c^{-1}aba,c^{-1}bca\rangle $.
The group $N$ that we quotient by consists in the smallest normal subgroup containing all the reduced words that can be formed out of the relators.
Note that the same group can have multiple presentations.  The group can turn out to be trivial or free, for instance.

A: The group $G$ that you defined as an example is in fact the trivial group.
The relations $ab=bc=ca$ tell you that the three generators $a,b,c$ are all conjugate in $G$, and so they must have the same order.
But then the first two relations $a^2=b^3=1$ tell you that this order must be $1$, so $a=b=c=1$ and $G$ is trivial.


text:
Q: Combining Turtle and Tkinter Module into One Big Class I created two different windows for a project. The first window is Demo1 using the turtle module for Python and the second window is Demo2 using the Tkinter for Python.I created two different programs for each window and wanted to combine both windows into one large project full of windows for final project in a class. The only problem is Window 2 doesn't work once I created a class for coding of the window and this class is inside a larger class with all the coding of the windows combined. Is there a better way for this code to be written or could someone fix it to run appropriately.
from tkinter import *
import tkinter as tk
import threading
import random
from graphics import *
import turtle

from time import sleep

class Intro():

    def __init__(self,master):

        self.master = master
        self.master.geometry("800x300")
        self.master.title("Welcome")
        self.master.configure(background = 'blue')
        self.label1 = Label(self.master,text ="Event Driven Programming Demonstration", fg = "white", bg = "blue",font = ("Purisa",18)).grid(row =1,column = 2)
        self.label2 = Label(self.master,text ="Program created by Ariel Lyons & Aaron Brown for CSC322 FSU 2014",font = ("Purisa",18), fg = "white",bg = "blue").grid(row = 2, column = 2)
        self.quitButton = Button(self.master,text ="Quit", fg="Black",bg = "red",command=self.finish).grid(row =18,column =2)
        self.nextButton = Button(self.master,text = "Demo 1", fg ="Black",bg = "yellow",command =self.goToDemo1).grid(row = 14, column =2)
        self.Demo2Button = Button(self.master,text = "Demo 2", fg = "Black", bg = "yellow",command = self.goToDemo2).grid(row = 16, column = 2)
        self.master.bind("<Return>", self.goToDemo1)

    def goToDemo1(self):
        threading.Timer(5.0, goToDemo1).start()
        root2 = Toplevel(self.master)
        myGUI = Demo1(root2)

    def goToDemo2(self):
        try:
           app = Demo2()
           app.th.start()
           app.win.mainloop()
           app.th.join()
        finally:
           app.th.close()
           app.close()

    def goToDemo1(self):
        root2 = Toplevel(self.master)
        myGUI = Demo1(root2)

    def finish(self):
        self.master.destroy()

class Demo1():

    def __init__(self,t):
        self.t = turtle.Turtle()
        ts = self.t.getscreen()
        ts.register_shape("plane.gif")
        self.t.shape("plane.gif")
        self.t.pencolor("white")
        ts.onscreenclick(self.t.goto)
        ts.bgpic('sky.gif')
        self.t.circle(50,400)
        self.t.circle(100,500)

    def goToDemo2(self):

       root3=Toplevel(self.t)
       myGUI = Demo2(root3)

    def finish(self):
        self.t.destroy()

class Demo2():

    def __init__(self):
        self.win = GraphWin('Demo2', 800, 600)
        self.win.setBackground("light green")
        self.th = threading.Thread(target=self.FlashThread, daemon=False)
    def FlashThread(self):
        while not self.win.isClosed():
            count = random.randint(0, 8)
            t = threading.Timer(1.0, self.flash, [count])
            t.start()
            t.join()
    def flash(self, count):
        try:
            diameter = 50
            centers = ((55,55),  (170,55), (285,55),  (55,170), (170,170),
                       (285,170), (55,285), (170,285), (285,285))
            circles = list()
            for point in centers:
                c = Circle(Point(point[0], point[1]), diameter)
                circles.append(c)
                c.setFill("blue")
                c.draw(self.win)
            circles[count].setFill("yellow")
            mouseClick = self.win.getMouse()
            correctMessage = Text(Point(self.win.getWidth()/2, 20), 'Correct!')
            incorrectMessage = Text(Point(self.win.getWidth()/2, 20), 'Incorrect,Try Again')
            leftX  = centers[count][0] - diameter
            rightX = centers[count][0] + diameter
            upperY = centers[count][1] - diameter
            lowerY = centers[count][1] + diameter
            if (upperY < mouseClick.y < lowerY) and (leftX < mouseClick.x < rightX):
                correctMessage.draw(self.win)
                print("Correct!")
            else:
                incorrectMessage.draw(self.win)
                print("Incorrect, Try Again")
        except:
            self.win.close()

def main():

    root = Tk()
    myGUIIntro = Intro(root)
    root.mainloop()

if __name__ =="__main__":
    main()

A: I guess I'm not understanding your question. Are you trying to have two windows created but have only one class? And what do you mean that window 2 doesn't work?


text:
Q: What't the best solution for creating subsets of a set of characters? I know 'best' is subjective, so according to you, what is the best solution for the following problem:
Given a string of length n (say "abc"), generate all proper subsets of the string. So, for our example, the output would be {}, {a}, {b}, {c}, {ab}, {bc}, {ac}. {abc}.
What do you think?

A: You want the power set. It can be calculated recursively and inductively. ;-)

A: The recursive approach -- the subsets of "abc" come in two types: those which are subsets of "bc", and those which are "a" plus a subset of "bc". So if you know the subsets of "bc", it's easy.
Alternatively, a string of length n has 2^n subsets. So write two nested loops: i counts from 0 to 2^n -1 (for the subsets), and j counts from 0 to n-1 (for characters in the ith subset). Output the jth character of the string if and only if the jth bit of i is 1.
(Well, you did say that "best" was subjective...)

A: Interpret a number in binary representation as indicating which elements are included in the subset. Let's assume that you have 3 elements in your set. Number 4 corresponds to 0100 in binary notation, so you will interpret this as a subset of size 1 that only includes 2nd element. This way, generating all subsets is counting up to (2^n)-1
    char str [] = "abc";
    int n = strlen(str); // n is number of elements in your set

    for(int i=0; i< (1 << n); i++) { // (1 << n) is equal to 2^n
        for(int j=0; j<n; j++) { // For each element in the set
            if((i & (1 << j)) > 0) { // Check if it's included in this subset. (1 << j) sets the jth bit
                cout << str[j];
            }
        }
        cout << endl;
    }

A: def subsets(s):
    r = []
    a = [False] * len(s)
    while True:
        r.append("".join([s[i] for i in range(len(s)) if a[i]]))
        j = 0
        while a[j]:
            a[j] = False
            j += 1
            if j >= len(s):
                return r
        a[j] = True

print subsets("abc")

A: Pardon the pseudo code...
int i = 0;
Results.push({});

While(i > Inset.Length) {
   Foreach(Set s in Results) {
    If(s.Length == i) {
       Foreach(character c in inSet)
          Results.push(s+c);
    }
    i++;
}

A: Recursive solution in C++:
set<string> power_set_recursive(string input_str)
{
    set<string> res;
    if(input_str.size()==0) {
        res.insert("");
    } else if(input_str.size()==1) {
        res.insert(input_str.substr(0,1));
    } else {
        for(int i=0;i<input_str.size();i++) {
            set<string> left_set=power_set_iterative(input_str.substr(0,i));
            set<string> right_set=power_set_iterative(input_str.substr(i,input_str.size()-i));
            for(set<string>::iterator it1=left_set.begin();it1!=left_set.end();it1++) {
                for(set<string>::iterator it2=right_set.begin();it2!=right_set.end();it2++) {
                    string tmp=(*it1)+(*it2);
                    sort(tmp.begin(),tmp.end());
                    res.insert(tmp);
                }
            }
        }
    }
    return res;
}

Iterative solution in C++:
set<string> power_set_iterative(string input_str)
{
    set<string> res;
    set<string> out_res;
    res.insert("");
    set<string>::iterator res_it;
    for(int i=0;i<input_str.size();i++){
        for(res_it=res.begin();res_it!=res.end();res_it++){
                string tmp=*res_it+input_str.substr(i,1);
                sort(tmp.begin(),tmp.end());
                out_res.insert(tmp);
        }
        res.insert(input_str.substr(i,1));
        for(set<string>::iterator res_it2=out_res.begin();res_it2!=out_res.end();res_it2++){
            res.insert(*res_it2);
    }
    out_res.clear();
    }
    return res;
}


text:
Q: ServiceStack Visual Studio Templates and the REPOSITORY Pattern I have created a new service with the ServiceStack Visual Studio add-in ("ServiceStack ASP.NET Empty") template.
This creates 4 projects, ServiceModel, ServiceInterface, ServiceHost, and a test project. If I were to encapsulate my data access with the REPOSITORY pattern via an Interface (think dependency injection), and was not allowed to add any other projects to the solution, what project should contain this code, and why? If the repo code absolutely had to be moved out to another project what would the projects dependencies be i.e. ServiceModel, ServiceInterface ?
Thank you,
Stephen

A:
ServiceHost, and a test project. If I were to encapsulate my data access with the REPOSITORY pattern via an Interface

See the Physical project structure wiki for more information on physical project layout.
ServiceStackVS's VS.NET templates follows the above physical project structure where only the ServiceInterface is used for maintaining your Services implementation and custom logic. All other starting projects have different purposes, e.g.

*

*The top-level Host project is the glue where all your concrete dependencies are registered and wired together that otherwise should be kept light-weight and logic-free.

*The ServiceModel project is a dep/impl-free project for maintaining your Services Contract DTOs which should be kept free of Server implementations so it's re-useable in client projects.

Both the interfaces and implementation can go in the same project. Some ServiceStack demos following this layout is the IRepository class in RedisStackOverflow as well as the IEmailer class in EmailContacts.


text:
Q: What is the purpose of Intellij IDEA (Android Studio) Kotlin plugin? I want to create a Kotlin project in Android Studio. To use Kotlin I need to install a Kotlin plugin and apply it inside the project (in .gradle file).
Can anyone explain what exact functionality Kotlin plugin adds to Android Studio and why we don't need a similar plugin for Java?

A: You seem to be confusing the Gradle Kotlin plugin and the IDEA/AS Kotlin plugin. They are entirely different.

what exact functionality Kotlin plugin adds to Android Studio

The Gradle plugin doesn't know anything about IDEA and so doesn't add any functionality to it (AFAIK). Except of course when building with Gradle it'll compile the Kotlin part of the project.
The IDEA plugin adds support for the language (parsing, highlighting, compiling, finding errors while you type, actions, etc. etc. etc.) into IDEA and Android Studio and doesn't add anything to Gradle.

why we don't need a similar plugin for Java

You do. For Gradle, see https://docs.gradle.org/current/userguide/java_plugin.html (Gradle Android plugin includes it). For IDEA/Android Studio, Java support is also really done by plugins, they are just built-in.


text:
Q: Swift - Parsing Json - Get values i started working with the SwiftyJson Class in order to parse json from the web.
I started with this RestApiManager:
typealias ServiceResponse = (JSON, NSError?) -> Void

class RestApiManager: NSObject {

    static let sharedInstance = RestApiManager()

    let baseUrl = "http://api.randomuser.me/"

    func getRandomUser(onCompletion: (JSON) -> Void) {

        makeHttpGetRequest(baseUrl, onCompletion: { json, err -> Void in

            onCompletion(json)

        })

    }

    func makeHttpGetRequest(path: String, onCompletion: ServiceResponse) {

        let request = NSMutableURLRequest(URL: NSURL(string: path)!)

        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request, completionHandler: { data, response, error in

            let json: JSON = JSON(data)

            onCompletion(json, error)

        })

        task.resume()

    }

}

In my controller i called this method:
    RestApiManager.sharedInstance.getRandomUser { json -> Void in

        let results = json["results"]

        for (index: String, subJson: JSON) in results {

            println(subJson["user"]["gender"].stringValue)

        }

    }

But it just prints
(lldb)

and some useless information..
Anybody could help me with this problem?
I learned with this tutorial
https://www.youtube.com/watch?v=YX9vK11oX-E

and this git link:
https://github.com/SwiftyJSON/SwiftyJSON


text:
Q: Visual studio automatically puts plus sign when I hit enter inside a string. How can I disable it? It wasn't like this before. I reinstalled it after formatting my pc.
enter image description here

A: I was looking for this a long time too. I finally found it here:

*

*Click Tools -> Options

*Go to Text Editor/C#/Advanced

*Uncheck "Split string literals on enter"

This will prevent Visual Studio from inserting a plus-character when you try to press Enter inside a string.


text:
Q: Troubles with Gulp migration from version 3 to 4 I have problems migrating the gulpfile.js from 3.9.1 to version 4.0.2. I am forced to use the new Gulp version because I have to run on Nodeversion 12. I have already made some changes to it, but not everything still works as before e.g. gulp watch, dev does not work yet.
Have you any ideas to fix the gulpfile, so that it work again like before?
Before
'use strict';

var gulp         = require('gulp'),
    watch        = require('gulp-watch'),
    //css
    sass         = require('gulp-sass'),
    postcss      = require('gulp-postcss'),
    mqpacker     = require('css-mqpacker'),
    cleanCSS     = require('gulp-clean-css'),
    autoprefixer = require('autoprefixer'),
    //js
    uglify       = require('gulp-uglify'),
    //other
    changed      = require('gulp-changed'),
    reference    = require('gulp-reference'),
    remember     = require('gulp-remember-cache'),
    rename       = require('gulp-rename'),
    sourcemaps   = require('gulp-sourcemaps'),
    fileinclude  = require('gulp-file-include'),
    imagemin     = require('gulp-imagemin'),
    pngquant     = require('imagemin-pngquant'),
    rimraf       = require('rimraf'),

    path = {
        dist: {
            html:   'dist/',
            js:     'dist/js/',
            style:  'dist/css/',
            img:    'dist/img/',
            fonts:  'dist/fonts/'
        },
        src: {
            html:  ['src/html/**/*.html','!src/html/template/**/*.html'],
            js:    ['src/js/lib/device.js', 'src/js/lib/jquery-2.2.4.js', 'src/js/main.js'],
            style: ['src/style/critical.scss', 'src/style/style.scss'],
            theme: ['src/style/color-themes/**/*.scss'],
            img:    'src/img/**/*.*',
            fonts:  'src/fonts/**/*.*'
        },
        watch: {
            html:   'src/html/**/*.html',
            js:     'src/js/**/*.js',
            style: ['src/style/**/*.scss', 'src/style/**/*.css'],
            img:    'src/img/**/*.*',
            fonts:  'src/fonts/**/*.*'
        },
        clean: './dist'
    };

var postCssPlugins = [
    autoprefixer(),
    mqpacker({
        sort: true
    }),
];

gulp.task('clean', function (cb)
{
    rimraf(path.clean, cb);
});

gulp.task('html:build', function ()
{
    return gulp.src(path.src.html)
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file',
            indent: true
        }))
        .pipe(changed(path.dist.html, {hasChanged: changed.compareContents})) //changed.compareLastModifiedTime
        .pipe(gulp.dest(path.dist.html));
});

gulp.task('js:build', function ()
{
    return gulp.src(path.src.js)
        .pipe(sourcemaps.init())
        .pipe(reference())
        .pipe(gulp.dest(path.dist.js))
        .pipe(uglify())
        .pipe(rename({suffix: ".min"}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(path.dist.js));
});

gulp.task('style:build', function ()
{
    gulp.src(path.src.style)
        .pipe(sourcemaps.init())
        .pipe(reference())
        .pipe(sass({outputStyle: 'compact'}).on('error', sass.logError))
        .pipe(cleanCSS({
            format: 'beautify',
            level: 2
        }))
        .pipe(postcss(postCssPlugins))
        .pipe(gulp.dest(path.dist.style))
        .pipe(cleanCSS())
        .pipe(rename({suffix: ".min"}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(path.dist.style));

    gulp.src(path.src.theme)
        .pipe(sass({outputStyle: 'compact'}).on('error', sass.logError))
        .pipe(postcss(postCssPlugins))
        .pipe(gulp.dest(path.dist.style))
        .pipe(cleanCSS())
        .pipe(rename({suffix: ".min"}))
        .pipe(gulp.dest(path.dist.style));
});

gulp.task('image:build', function ()
{
    return gulp.src(path.src.img)
        .pipe(imagemin({
            optimizationLevel: 5,
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()],
            interlaced: true
        }))
        .pipe(gulp.dest(path.dist.img));
});

gulp.task('fonts:build', function()
{
    return gulp.src(path.src.fonts)
        .pipe(changed(path.dist.fonts))
        .pipe(gulp.dest(path.dist.fonts))
});

gulp.task('js:dev', function ()
{
    return gulp.src(path.src.js)
        .pipe(remember( {dest: path.dist.js, cacheName:'scripts'} ))
        .pipe(sourcemaps.init())
        .pipe(reference())
        .pipe(rename({suffix: ".min"}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(path.dist.js));
});

gulp.task('style:dev', function ()
{
    gulp.src(path.src.style)
        // .pipe(remember({dest: path.dist.style, cacheName:'styles'} ))
        .pipe(sourcemaps.init())
        .pipe(reference())
        .pipe(sass().on('error', sass.logError))
        .pipe(postcss(postCssPlugins))
        .pipe(cleanCSS({
            format: 'beautify',
            level: 2
        }))
        .pipe(rename({suffix: ".min"}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(path.dist.style));

    gulp.src(path.src.theme)
        .pipe(sass().on('error', sass.logError))
        .pipe(postcss(postCssPlugins))
        .pipe(cleanCSS({
            format: 'beautify',
            level: 2
        }))
        .pipe(rename({suffix: ".min"}))
        .pipe(gulp.dest(path.dist.style));
});

gulp.task('image:dev', function ()
{
    return gulp.src(path.src.img)
        .pipe(changed(path.dist.img))
        .pipe(gulp.dest(path.dist.img));
});

gulp.task('build', [
    'html:build',
    'js:build',
    'style:build',
    'fonts:build',
    'image:build'
]);

gulp.task('dev', [
    'clean',
    'html:build',
    'js:dev',
    'style:dev',
    'fonts:build',
    'image:dev'
]);

gulp.task('default', ['clean'], function ()
{
    return gulp.start('build');
});

gulp.task('watch', function (_cb)
{
    watch(path.watch.html, function(event, cb)
    {
        gulp.start('html:build');
    });
    watch(path.watch.style, function(event, cb)
    {
        gulp.start('style:dev');
    });
    watch(path.watch.js, function(event, cb)
    {
        gulp.start('js:dev');
    });
    watch(path.watch.img, function(event, cb)
    {
        gulp.start('image:dev');
    });
    watch(path.watch.fonts, function(event, cb)
    {
        gulp.start('fonts:build');
    });

    _cb();
});

Incl. changes
'use strict';

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    // css
    sass = require('gulp-sass'),
    postcss = require('gulp-postcss'),
    mqpacker = require('css-mqpacker'),
    cleanCSS = require('gulp-clean-css'),
    autoprefixer = require('autoprefixer'),
    // js
    uglify = require('gulp-uglify'),
    // other
    changed = require('gulp-changed'),
    reference = require('gulp-reference'),
    remember = require('gulp-remember-cache'),
    rename = require('gulp-rename'),
    sourcemaps = require('gulp-sourcemaps'),
    fileinclude = require('gulp-file-include'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    rimraf = require('rimraf'),
    // multi lang
    i18n = require('gulp-html-i18n'),

    path = {
        dist: {
            html: 'dist/',
            js: 'dist/js/',
            style: 'dist/css/',
            img: 'dist/img/',
            fonts: 'dist/fonts/'
        },
        src: {
            html: ['src/html/**/*.html', '!src/html/template/**/*.html'],
            js: ['src/js/lib/device.js', 'src/js/lib/jquery-2.2.4.js', 'src/js/main.js',
                'src/js/contact-form-main.js', 'src/js/jqBootstrapValidation.js',
                'src/js/newsletter-form.js'],
            style: ['src/style/critical.scss', 'src/style/style.scss'],
            theme: ['src/style/color-themes/**/*.scss'],
            img: 'src/img/**/*.*',
            fonts: 'src/fonts/**/*.*'
        },
        watch: {
            html: 'src/html/**/*.html',
            js: 'src/js/**/*.js',
            style: ['src/style/**/*.scss', 'src/style/**/*.css'],
            img: 'src/img/**/*.*',
            fonts: 'src/fonts/**/*.*',
            lang: 'src/lang/**/*.*'
        },
        clean: './dist'
    };

var postCssPlugins = [
    autoprefixer(),
    mqpacker({
        sort: true
    })
];

gulp.task('clean', async function (cb) {
    rimraf(path.clean, cb);
});

gulp.task('html:build', async function () {
    return gulp.src(path.src.html)
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file',
            indent: true
        }))
        .pipe(i18n({
            langDir: 'src/lang',
            createLangDirs: true,
            defaultLang: 'de'
        }))
        .pipe(changed(path.dist.html, {hasChanged: changed.compareContents})) // changed.compareLastModifiedTime
        .pipe(gulp.dest(path.dist.html));
});

gulp.task('js:build', async function () {
    return gulp.src(path.src.js)
        .pipe(sourcemaps.init())
        .pipe(reference())
        .pipe(gulp.dest(path.dist.js))
        .pipe(uglify())
        .pipe(rename({suffix: ".min"}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(path.dist.js));
});

gulp.task('style:build', async function () {
    gulp.src(path.src.style)
        .pipe(sourcemaps.init())
        .pipe(reference())
        .pipe(sass({outputStyle: 'compact'}).on('error', sass.logError))
        .pipe(cleanCSS({
            format: 'beautify',
            level: 2
        }))
        .pipe(postcss(postCssPlugins))
        .pipe(gulp.dest(path.dist.style))
        .pipe(cleanCSS())
        .pipe(rename({suffix: ".min"}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(path.dist.style));

    gulp.src(path.src.theme)
        .pipe(sass({outputStyle: 'compact'}).on('error', sass.logError))
        .pipe(postcss(postCssPlugins))
        .pipe(gulp.dest(path.dist.style))
        .pipe(cleanCSS())
        .pipe(rename({suffix: ".min"}))
        .pipe(gulp.dest(path.dist.style));
});

gulp.task('image:build', async function () {
    return gulp.src(path.src.img)
        .pipe(imagemin({
            optimizationLevel: 5,
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()],
            interlaced: true
        }))
        .pipe(gulp.dest(path.dist.img));
});

gulp.task('fonts:build', async function () {
    return gulp.src(path.src.fonts)
        .pipe(changed(path.dist.fonts))
        .pipe(gulp.dest(path.dist.fonts))
});

gulp.task('js:dev', async function () {
    return gulp.src(path.src.js)
        .pipe(remember({dest: path.dist.js, cacheName: 'scripts'}))
        .pipe(sourcemaps.init())
        .pipe(reference())
        .pipe(rename({suffix: ".min"}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(path.dist.js));
});

gulp.task('style:dev', async function () {
    gulp.src(path.src.style)
    // .pipe(remember({dest: path.dist.style, cacheName:'styles'} ))
        .pipe(sourcemaps.init())
        .pipe(reference())
        .pipe(sass().on('error', sass.logError))
        .pipe(postcss(postCssPlugins))
        .pipe(cleanCSS({
            format: 'beautify',
            level: 2
        }))
        .pipe(rename({suffix: ".min"}))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest(path.dist.style));

    gulp.src(path.src.theme)
        .pipe(sass().on('error', sass.logError))
        .pipe(postcss(postCssPlugins))
        .pipe(cleanCSS({
            format: 'beautify',
            level: 2
        }))
        .pipe(rename({suffix: ".min"}))
        .pipe(gulp.dest(path.dist.style));
});

gulp.task('image:dev', async function () {
    return gulp.src(path.src.img)
        .pipe(changed(path.dist.img))
        .pipe(gulp.dest(path.dist.img));
});

gulp.task('build', gulp.series(gulp.parallel(
    'html:build',
    'js:build',
    'style:build',
    'fonts:build',
    'image:build'
)));

gulp.task('dev', gulp.series(
    'clean',
    'html:build',
    'js:dev',
    'style:dev',
    'fonts:build',
    'image:dev'
));

gulp.task('default', gulp.series('clean', async function () {
    return gulp.series('build');
}));

gulp.task('watch', async function (_cb) {
    watch(path.watch.html, function (event, cb) {
        gulp.parallel('html:build');
    });
    watch(path.watch.lang, function (event, cb) {
        gulp.parallel('html:build');
    });
    watch(path.watch.style, function (event, cb) {
        gulp.parallel('style:dev');
    });
    watch(path.watch.js, function (event, cb) {
        gulp.parallel('js:dev');
    });
    watch(path.watch.img, function (event, cb) {
        gulp.parallel('image:dev');
    });
    watch(path.watch.fonts, function (event, cb) {
        gulp.parallel('fonts:build');
    });

    _cb();
});

A: Try this to start.  No gulp.start, use gulp.series instead.  And gulp v4 doesn't use tasks in an array.  Find a migration guide for gulp v3 to v4.
gulp.task('build', gulp.series(
        'html:build',
        'js:build',
        'style:build',
        'fonts:build',
        'image:build'
    ));
gulp.task('dev', gulp.series(
    'clean',
    'html:build',
    'js:dev',
    'style:dev',
    'fonts:build',
    'image:dev'
));

gulp.task('default', gulp.series('clean', function ()
{
    return gulp.series('build');
}));

gulp.task('watch', function (_cb)
{
    watch(path.watch.html, function(event, cb)
    {
        gulp.series('html:build');
    });
    watch(path.watch.style, function(event, cb)
    {
        gulp.series('style:dev');
    });
    watch(path.watch.js, function(event, cb)
    {
        gulp.series('js:dev');
    });
    watch(path.watch.img, function(event, cb)
    {
        gulp.series('image:dev');
    });
    watch(path.watch.fonts, function(event, cb)
    {
        gulp.series('fonts:build');
    });

    _cb();
});


text:
Q: How to fix error in MIT Kerberos Ticket Initialization failed. Error 22 Hi I am currently trying to connect my Tableau Platform to my database and I am currently going through installing the Kerberos client. I have pasted the correct krb5.ini within my c:\programdata\MIT folder and also added a new variable within my extension variables but the problem I have is that I am unable to get a ticket using my username and password.
Currently I get the following error:
Ticket initialization failed. Kerberos 5: Invalid argument (error 22)

I have searched google but haven't come across anything that identifies this error so would really appreciate if somebody could please advise on where I am going wrong or even what the error means.
Thanks in advance.

A: Thanks T Heron for your response. I have now managed to fix this issue. What I did was uninstall Kerberos version 4.1 as a colleague mentioned that they have been known issues with this version so I then installed the previous version 4.0.1 and I am now able to get a ticket and connect to Tableau as required.
Thanks once again for your time.


text:
Q: JavaScript setTimeout not firing after Window.Open I have an ASP.Net web page that currently works on the iOS4 but not on the iOS5.
On the parent web page I have a button that opens a child window. And I do a setTimeout refresh thing in the parent window right after the open window call.
I noticed on the iPhone iOS5 that when it opens the child window, the setTimeout function in the parent page is not called until I go back to the parent window and then back to the child window to see the update.
Here's a snippet of my code in the parent page and where I think is the problem
WindowManager.OpenWindow('...')
t = setTimeout(function() { handles[0].testfx(); }, 1000);

this runs on iOS4 but not on iOS5.
Any ideas?

A: iOS5 does indeed pause JavaScript when a window is not the active window. There is nothing you can do about this, so the best you can do is try to alter your setup so that JavaScript does not need to be run when your window is in the background.
You said you are doing a setTimeout refresh thing in the parent window. WHY are you doing this? Frankly, it sounds a little bit odd -- why do you want to be refreshing anything when the user can't even see your page? What exactly does the line handles[0].testfx(); do for you?

A: This is just a suggestion, since I don't have access to test this, but you may be able to hack around this using by using window.postMessage.  An example of this can be found here.
In your case, you would probably want to check if a required amount of time had elapsed, and if not, call window.postMessage again, otherwise, call your handler.
I'm not sure how quickly calls to window.postMessage will be processed, if at all, when not in the active window.


text:
Q: Backgroundworker ProgressChanged acts after the worker is done I've created a form to pop up and display a progress bar whenever I call one of my time-consuming routines. I feed the progress of my routine through the UpdateProgress method.
I'm using a background worker to allow the user to move the form around and keep doing their business while this form updates. However, the form just locks up until the routine is complete, then quickly ramps the progress bar to 100% and quits (as it should). The progress bar should, imo, update alongside the progress of the calls being made to the UpdateProgress method.
What am I doing wrong here?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace myNameSpace
{
    public partial class ProgressIndicator : Form
    {
        int progressPercentage;

        public ProgressIndicator()
        {
            InitializeComponent();
        }

        void progressUpdater_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // update the UI with appropriate fields
            progressBar.Value = e.ProgressPercentage;
            labelCommunicating.Text = "In progress: " + e.ProgressPercentage + "% complete";
        }

        void progressUpdater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Close();
        }

        void progressUpdater_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            while (true)
            {
                if (progressPercentage >= 100)
                {
                    break;
                }

                worker.ReportProgress(progressPercentage);

                Thread.Sleep(100);
            }
        }

        public void UpdateProgress(int progressPercentage)
        {
            this.progressPercentage = progressPercentage;
        }

        private void ProgressIndicator_Load(object sender, EventArgs e)
        {
            BackgroundWorker progressUpdater = new BackgroundWorker();
            progressUpdater.WorkerReportsProgress = true;
            progressUpdater.WorkerSupportsCancellation = true;
            progressUpdater.DoWork += new DoWorkEventHandler(progressUpdater_DoWork);
            progressUpdater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(progressUpdater_RunWorkerCompleted);
            progressUpdater.ProgressChanged += new ProgressChangedEventHandler(progressUpdater_ProgressChanged);

            progressUpdater.RunWorkerAsync();
        }
    }
}

A: This smells like a far-fetched solution and I think your problem lies with the while loop. However, a better approach may be to simply update your ProgressBar without blocking the UI by using Invoke(); e.g.
Invoke(new myUpdate(updateProgress), pval);//call invoke whenever you need to update the progress bar assuming pval is an integer with the value to update with. This could be in a thread for instance.

//declare this as a class level delegate
private delegate void myUpdate(int progress);

//method to update progress bar
private void updateProgress(int progress)
{
    progressBar.Value = progress;
}

A: You can create the process in this fashion that way you do not need to wrap your call around the Invoke method.
//delegate method
private delegate void updateProgressDelegate(int progress);

//actual method
private void updateProgress(int progress)
{
    if(this.InvokeRequired)
    {
        this.Invoke(new updateProgressDelegate(updateProgress), progress);
    }
    else
    {
        progressBar.value = progress;
    }
}


text:
Q: How to cast from virtual abstract class Having this class definition
class CefBrowser : public virtual CefBase

How to cast from CefBrwoser * to CefBase * and reverse? assuming that both are not instanciable, they are loaded from C to CPP.


text:
Q: Simplest AngularJS App to with Session Authentication to DRF I have been banging my head against the wall for far too long trying to get session authentication to work in AngularJS with the basic Django REST Framework setup. I've read through blogs dozens of stack overflow questions and answers, and I'm just not getting it. I have a large application that I'm working on, but in order to facilitate an answer to this issue, I've produced a minimalist AngularJS App on top of a fork of the bare-bones Django REST Framework Tutorial code here. (All the front-end dependencies are included in the fork.) Just do pip install -r requires.txt, python manage.py makemigrations snippets, python manage.py migrate, and then python manage.py runserver.
The main code of interest is here:

"use strict";

var geoint = angular.module('snippets', [
  'ngRoute',
  'ngCookies',
  'ngAnimate',
  'ngResource',
  'snippets.controllers',
])

.config(function ($routeProvider, $httpProvider) {
  $httpProvider.defaults.withCredentials = true;
  $httpProvider.defaults.xsrfCookieName = 'csrftoken';
  $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

  $routeProvider
    .when('/', {
      title:'Snippets - Home',
      templateUrl: STATIC_URL + 'snippets/partials/snippets.html',
      controller: 'SnippetsCtrl'
    })
    .otherwise({
      redirectTo: '/'
    });
})

.run(function($rootScope, $location, $http) {

    // Get a CSRF Token
    $http.get('api/auth/login/?next=/api/').then(
      function successCallback(response){
        console.log(response);
        // Post should come back with Set-Cookie sessionid, but it doesn't!
        $http.post('api/auth/login/', {username:'username', password:'password'}).then(
          function successCallback(response){
            console.log(response);
            // Get this user's information
            $http.get('api/currentuser/').then(
              function successCallback(response){
                console.log(response);
              })
          })
      },
      function errorCallback(response){
        alert(response);
      }
    );

});
<!DOCTYPE html>

    {% load static from staticfiles %}

        <meta charset="UTF-8">
        <title ng-bind="title">PC2</title>

        <link rel="stylesheet" type="text/css" href="{% static "resources/css/complete.min.css" %}">
        {% if debug %}

        {% else %}

        {% endif %}

        {% load static from staticfiles %}

My nested GETs and POSTs are ugly and obviously not how I would really do this in an application. But I think it should work, and it doesn't. I've been using postman and chrome to figure out the problem. The root of the problem seems to be that when I use AngularJS, the POST does not come back with a Set-Cookie that includes sessionid. (When I use the browser it does.) Thus, when it tries to get the user information it doesn't have the cookie set, and it comes into Django as an AnonymousUser. Any help that anyone can offer is greatly appreciated!
So the question is Why doesn't this work in AngularJS, but it does with the browser? I would also appreciate input on best practices, or better ways to solve this problem. (New DRF endpoint, use $resource, etc)?

A: Alright, after fiddling around with this problem more this morning I got the answer. For the DRF default api login view, the data must be submitted as a form. Therefore, this ended up being the solution:
.run(function($rootScope, $location, $http) {
$http.get('api/auth/login/').then(function successCallback(response){
console.log(response);
$http({
    "method": "POST",
    "url": 'api/auth/login/',
    "data": $.param({username:'username', password:'password', next:'/api/currentuser'}),
    "headers": {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(
  function successCallback(response){
    console.log(response);
  })})

});
I would still be very interested to learn the "right" way to do this. Should I build a separate DRF login view? Should I use Angular $resource instead of $http calls? I would appreciate any and all inputs.


text:
Q: How do you install a package to a sandbox while logged in via "Grant Login Access"? A customer wants me to install a package for them. They have granted me login access via the "Grant Login Access" option. I log in to my SFDC account with the LMA (License Management App), go to Subscribers, pick their org, and login as them.
Now, the tricky part comes when I try to access the installation URL. Sometimes it wants to install it to MY org (the one I used to get tot heir sandbox). Sometimes it asks me to log in - I don't have the login credentials of the sandbox, I bypassed that with "Grant Login Access". Sometimes (very rarely) it just seems to work.
Is there a trick to this or do I just need to have the user install it themselves?

A: Change the install URL to their instance instead of login or test, and paste it into your address bar after logging in.


text:
Q: Retrieve text in a column based on a substring in another column suppose it finds some specific text like "sa" in A2,A4,A5,A6
i need to copy "sohail" in B2,B4,B5,B6 respectively,
like this...
ImageName                   PhotographerName
pirf_20120523_sa0001.jpg    sohail
pirf_20120523_ml0001.jpg    manav
pirf_20120523_sa0001.jpg    sohail
pirf_20120523_sa0001.jpg    sohail
pirf_20120523_sa0001.jpg    sohail
pirf_20120529_sh0005.jpg    shirazi
pirf_20120523_ml0001.jpg    manav
pirf_20120529_sh0005.jpg    shirazi

i tried to retrieve the addrres where it finds text...
Sub FindinTextInEachCell()

Dim rngX As Range

Set rngX = Worksheets("Sheet1").Range("A1:A10").Find("sa", lookat:=xlPart)
If Not rngX Is Nothing Then
    MsgBox "Found at " & rngX.Address
End If

End Sub

A: You're not using Find method properly, it'll only return the first Range it finds, you'll have to use findnext() method for subsequent ranges, but since subsequent ranges will duplicate, you'll have to compare it with the first address found.
Sub foo()
On Error Resume Next

Dim rng As Range
Dim prng As Range
Dim firstAddress As String

With Worksheets(1).Range("A1:A10")
    Set rng = .Find("sa", LookIn:=xlValues, LookAt:=xlPart)
    If Not rng Is Nothing Then
        firstAddress = rng.Address
        Do
            Set prng = rng
            rng.Offset(0, 1) = "Sohail"
            Set rng = .FindNext(After:=prng)
        Loop While Not rng Is Nothing And rng.Address <> firstAddress
    End If
End With

End Sub


text:
Q: Which is the correct way to setup free shipping and handling in magento? I am trying to setup shipping and handling in my website, I setup free shipping for the orders with minimum of 99 dollars but I want to set a shipping and handling fee of 9.98 (flat rate FedEx Standard Ground) for orders below 99.
How can I set it up so that when the order is 99 or above the free shipping is automatically selected and when its below 99 the shipping is automatically selected to 9.98 (flat rate FedEx Standard Ground)?

A: You'll want to use table rate shipping.

A: Alternatively, you can set up the FedEx method to make FedEx Ground free for orders $99 and above and use whatever the quoted rate is for orders under $99. Just set Free Method to Ground, Free Shipping with Minimum Order Amount to Enabled, and Minimum Order Amount for Free Shipping to 99, and disable all other shipping methods.


text:
Q: Unable to retrieve AWS scaling policy information from ec2_scaling_policy module in Ansible I'm trying to create an AWS scaling policy and attach a metric alarm to it. From what I understand, the ec2_metric_alarm module needs the ARN of the scaling policy so that it can associate itself with it.
However, I can't seem to get the ARN after creating a new scaling policy from the ec2_scaling_policy module's output. Currently I'm trying to register the result of the ec2_scaling policy module. For example, my playbook looks something like this:
- name: Create scaling policy and associate it with autoscaling group
  ec2_scaling_policy:
    state: present
    region: us-east-1
    name: "test-scaleup-policy"
    adjustment_type: "ChangeInCapacity"
    asg_name: "test-asg"
    scaling_adjustment: 1
    min_adjustment_step: 1
    cooldown: 300
  register: sp_result

- name: Debug result of scaling policy creation
  debug: var=sp_result

- name: Create metric alarm and associate it with autoscaling policy
  action:
    module: ec2_metric_alarm
    state: present
    alarm_actions: ["{{ sp_result.arn }}"]
    etc...

The debug module prints this:
TASK: [Debug] *****************************************************************
ok: [localhost] => {
   "sg_result": {
      "changed": false,
      "invocation": {
      "module_args": "",
      "module_name": "ec2_scaling_policy"
}}}

According to this merged pull request, the ARN should be included in the data the module returns. I'm still pretty new to Ansible, so I'm wondering if I'm trying to capturing this information in the wrong way, e.g. using register when I should be using something else? Otherwise, is there something else I should be doing?

A: That change is merged into Ansible's devel branch but none of the releases yet.


text:
Q: Why does Linux use a swap partition rather than a file? It seems to me a swap file is more flexible.

A: A swap file is more flexible but also more fallible than a swap partition. A filesystem error could damage the swap file. A swap file can be a pain for the administrator, since the file can't be moved or deleted. A swap file can't be used for hibernation. A swap file was slightly slower in the past, though the difference is negligible nowadays.
The advantage of a swap file is not having to decide the size in advance. However, under Linux, you still can't resize a swap file online: you have to unregister it, resize, then reregister (or create a different file and remove the old one). So there isn't that much benefit to a swap file under Linux, compared to a swap partition. It's mainly useful when you temporarily need more virtual memory, rather than as a permanent fixture.

A: A swap partition can be preferred because it avoids a dependency on the file system when all you need is an addressable memory pool.
But nothing prevents you from using a swap file instead of a swap partition, or in addition to a swap partition.

*

*Create the file:
dd if=/dev/zero of=/extraswap bs=1M count=512

*Initialize file contents's:
mkswap /extraswap

*Use it:
swapon /extraswap

*See if it worked:
free -m

In order to start using the swapfile always at bootup, edit /etc/fstab and add
/extraswap           swap          swap    defaults    0 0

[1] http://www.redhat.com/docs/manuals/linux/RHL-8.0-Manual/custom-guide/s1-swap-adding.html

A: Perhaps the main reason is that the main kernel suspend-to-disk does not work with swap files.  For example the Debian wiki instructions are to install uswsusp if you need this.
More recently, swap files do not work if the filesystem is btrfs, so it is simplest for distributions to always create swap as a partition.
It is vaguely mentioned that using a file for swap had potentially lower performance than a partition, prior to kernel version 2.6.  https://www.kernel.org/doc/gorman/html/understand/understand014.html#text15

A: For completeness I'll add my own answer:
As said by @Gilles, a swap file can't be used for hibernation. When using a swap file, the system must locate the swap file's header, but in order to do this the filesystem that contains the swap file must be mounted, and a journaled filesystem  - e.g. ext3, ext4, and basically all modern filesystems used by Linux - cannot be mounted during resume from disk. (In reality, there are ways to do so, but quite cumbersome.)
Source: https://www.kernel.org/doc/Documentation/power/swsusp-and-swap-files.txt

A: I think that it is mainly because the access time to the datas located on a partition are lower. The point of the swap file is more to help the sys admin when he is really out of RAM and needs to operate huge operations that would maybe crash his system. In this case he will sporadically create swap files when needed.
But anyway you can have both of them.


text:
Q: How to run command every 15min? I want to run a command every 15min. Here is the command I want to run:
sudo bash -c "sleep 1h; pm-suspend"

A: I am unable to comment due to insufficient reputation however @Edwin Hernandez crontab example of */15, *, *, *, * sudo bash -c "sleep 1h; pm-suspend" is incorrect as there should not be commas between the fields (each of the stars are a separate field).  @Mitch♦ has the correct format.
cron's format is:
m h dom mon dow command

m is the minute, h is the hour, dom is day of month, mon is the month, and dow is day of week.
In your comment you ask a supplementary question about running every day and every week.
14 04 * * * command is every day at 04:14am
39 06 * * 3 command is every Wednesday at 6:39am (0 = Sun, 1 = Mon, etc...)
39 06 * * wed command as previous line
Caution #1:  If you use * * * * wed command then it will run every minute of every hour every Wednesday.  If you only want it to run once a day then you need to specify the minutes and hours of the day you want it to run. I've been bitten by this on more than one occasion. It can be very frustrating.
Caution #2:  If the command you want to run is the pm-suspend command then I would suggest that you look at all crontab files for all users to find a suitable time after they have finished processing any commands you feel are important.  e.g. if you are running a backup starting at 05:44 and then set your pm-suspend to run at 05:50 there is a possibility that the backup will not have finished before suspending which is probably not a helpful state of affairs.
The reason that the "random" times are used in the example is that crontabs often set off their commands at these "random" times to spread the load so that a lot of processes are not all starting at once
It should be noted that any output of cron is emailed to the user if email is set up.  You will not see any output on the screen/terminal.
An aside
If you ever need to watch something change over a shorter time frame (the default is 2 secs) then watch is a useful command.  Finding this command was a godsend!
Other reading
On SO How can I make a bash command run periodically? has lots of links in that might help explain things in alternative ways.
Or if you can cope with the somewhat meaty man pages:
man 8 cron
man 1 crontab
man 5 crontab

A: A step by step guide would be like:

*

*Editing your crontab: type in a terminal:
$ crontab -e

*Add the following line to it.
*/15 * * * * sudo bash -c "sleep 1h; pm-suspend"

*Save and quit: type :wq and then press enter if you are on vi.

A: One way is to run a cron command every 15 minutes. Like this, where each minute is specified:
0,15,30,45 * * * * /path/to/command

A: You should use 'cron'. Official instructions here. There is a complimentary anacron daemon too, that allows to create rules like 5 minutes after connecting to Internet

A: you could try it using while loop, save the following code in a file and run it as sudo bash <filename>. you have to run it once, it will run in terminal as long as you dont cancel it using Ctrl+C
#!/bin/bash
sudo bash -c "sleep 1h; pm-suspend"


text:
Q: Own DSL with XText. Problem with unlimited brackets ("(", ")") I am developing my own DSL in XText.
I want do something like this:
1 AND (2 OR (3 OR 4))

Here my current .xtext file:
grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"

Model:
    (greetings+=CONDITION_LEVEL)
;

terminal NUMBER :
    ('1'..'9') ('0'..'9')*
;

AND:
    ' AND '
;

OR:
    ' OR '
;

OPERATOR :
    AND | OR
;

CONDITION_LEVEL:
    ('('* NUMBER (=>')')* OPERATOR)+ NUMBER ')'*
;

The problem I am having is that the dsl should have the possibility to make unlimited bracket, but show an error when the programmer don't closes all opened bracket.
example:
1 AND (2 OR (3 OR 4)

one bracket is missing --> should make error.
I don't know how I can realize this in XText. Can anybody help?
thx for helping.

A: You need to make your syntax recursive. The basic idea is that a CONDITION_LEVEL can be, for example, two CONDITION_LEVEL separated by an OPERATOR.
I don't know the specifics of the xtext syntax, but using a BCNF-like syntax you could have:
CONDITION_LEVEL:
    NUMBER
    '(' CONDITION_LEVEL OPERATOR CONDITION_LEVEL ')'

A: Try this:
CONDITION_LEVEL
  :  ATOM ((AND | OR) ATOM)*
  ;

ATOM
  :  NUMBER
  |  '(' CONDITION_LEVEL ')'
  ;

Note that I have no experience with XText (so I did not test this), but this does work with ANTLR, on which XText is built (or perhaps it only uses ANTLR...).
Aslo, you probably don't want to surround your operator-tokens with spaces, but put them on a hidden-parser channel:
grammar org.xtext.example.mydsl.MyDsl hidden(SPACE)

...

terminal SPACE : (' '|'\t'|'\r'|'\n')+;

...

Otherwise source like this would fail:
1 AND(2 OR 3)

For details, see Hidden Terminal Symbols from the XText user guide.


text: Q: How to cope with Mouse-Wheel-Delta cross platform? There is a question, asking why Wheel-Delta is supposed to be 120 on Windows platforms. However, I encounter the same threshold on Linux and Mac. As the value nowadays might change, how do I get the Wheel-Delta on Windows, Linux and Mac? We are using OpenSceneGraph, Boost and Qt for cross-platform development. Maybe they might help here. (It's a C++ project)


text:
Q: Retrieving User's data from database on the basis of email I have different User's data in a database and I want to retrieve the data the data of the user who is currently logged in to the app, I am able to retrieve the data but I don't know how to display/show it in the main Activity.
Here is my getUserData method
DBHandler
 public ArrayList<User> getUserData(String email){
 Log.e("email", "" + email);
 ArrayList<User> arrayList = new ArrayList<>();
 SQLiteDatabase db = this.getWritableDatabase();
 Cursor cursor;
    String query =  " select * from " +TABLE_NAME+ " where "+COLUMN_EMAIL+ "=?";
  String[] select = new String[]{email};
    cursor = db.rawQuery(query,select);
 Log.e("Query", "" + query);

    if (cursor.moveToFirst()) {
        do {
            String FirstName = cursor.getString(0);
            String LastName = cursor.getString(1);
            String Email = cursor.getString(2);
            byte[] image = cursor.getBlob(5);
            String gender = cursor.getString(6);
            String status = cursor.getString(8);

            User user = new User(FirstName, LastName, Email, image, gender, status);
            arrayList.add(user);
        }

        while (cursor.moveToNext());
    }
    cursor.close();

    return arrayList;}

Now i want to show it in the mainActivity how i can do that?

A:     TextView FirstName = findViewById(R.id.FirstName);
    TextView LastName = findViewById(R.id.LastName);

    ArrayList<User>  userArrayList = new ArrayList<User>(getUserData("user@gmail.com"));  // User data stored in userArrayList now you can use userArrayList for showing data

    FirstName.setText(userArrayList.get(0).getFirstName());  // get(0) Gives you first name from first position
    LastName.setText(userArrayList.get(0).getLastName());


text:
Q: Custom Dialoge inside the onActivityResult shows error I have a custom Dialoge  inside onActivityResult. But It shows the error like this
    04-11 16:40:32.141: D/dalvikvm(8897): GC_EXTERNAL_ALLOC freed 689 objects / 53336 bytes in 100ms
04-11 16:40:43.901: D/UPC Code(8897): 000014312001220
04-11 16:40:44.001: D/AndroidRuntime(8897): Shutting down VM
04-11 16:40:44.001: W/dalvikvm(8897): threadid=1: thread exiting with uncaught exception (group=0x40028a00)
04-11 16:40:44.041: E/AndroidRuntime(8897): FATAL EXCEPTION: main
04-11 16:40:44.041: E/AndroidRuntime(8897): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=195543262, result=-1, data=Intent { act=com.google.zxing.client.android.SCAN flg=0x80000 (has extras) }} to activity {com.heuristics.barcodescanner/com.heuristics.barcodescanner.MainActivity}: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3712)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3754)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.app.ActivityThread.access$2800(ActivityThread.java:135)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2162)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.os.Looper.loop(Looper.java:143)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.app.ActivityThread.main(ActivityThread.java:4914)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at java.lang.reflect.Method.invokeNative(Native Method)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at java.lang.reflect.Method.invoke(Method.java:521)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at dalvik.system.NativeStart.main(Native Method)
04-11 16:40:44.041: E/AndroidRuntime(8897): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.view.ViewRoot.setView(ViewRoot.java:513)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.app.Dialog.show(Dialog.java:241)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at com.heuristics.barcodescanner.MainActivity.onActivityResult(MainActivity.java:137)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.app.Activity.dispatchActivityResult(Activity.java:3931)
04-11 16:40:44.041: E/AndroidRuntime(8897):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3708)
04-11 16:40:44.041: E/AndroidRuntime(8897):     ... 11 more
04-11 16:40:46.191: I/Process(8897): Sending signal. PID: 8897 SIG: 9

and my onActivityResult is like this
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case IntentIntegrator.REQUEST_CODE: {
        if (resultCode != RESULT_CANCELED) {
            IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (scanResult != null) {
                String upc = scanResult.getContents();

                Log.d("UPC Code",upc);
                Product_list.add(upc);

                final Dialog dialog = new Dialog(getApplicationContext(), android.R.style.Theme_Translucent_NoTitleBar);
                dialog.setCancelable(false);
                dialog.setContentView(R.layout.quantity);
                Toast.makeText(getApplicationContext(), "DIALOGUE", Toast.LENGTH_SHORT).show();

                final Button navi_left;
                Button navi_right, reset, ok;
                final TextView quantity_text;

                navi_left = (Button)dialog.findViewById(R.id.navi_left);
                navi_right = (Button)dialog.findViewById(R.id.navi_right);
                reset = (Button)dialog.findViewById(R.id.reset);
                ok = (Button)dialog.findViewById(R.id.ok);
                quantity_text = (TextView)dialog.findViewById(R.id.quantity_nums);

                navi_left.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        String pre_= quantity_text.getText().toString();
                        int post = Integer.parseInt(pre_);
                        int post_value;
                        if(post<=0)
                        {

                            post_value = post;
                        }
                        else
                        {
                            post_value = post-1;
                        }

                    }
                });

                navi_right.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        String pre_= quantity_text.getText().toString();
                        int post_ = Integer.parseInt(pre_)+1;
                        quantity_text.setText(post_+"");

                    }
                });

                reset.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        quantity_text.setText(0);

                    }
                });

                ok.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        Quantity_list.add(quantity_text.getText().toString());
                    }
                });
                dialog.show();

                ArrayAdapter<String> my_adapter = new Custom_Adapter(getApplicationContext(), Product_list);
                my_adapter.notifyDataSetChanged();
                my_list.setAdapter(my_adapter);

            }
        }
        break;
    }
    }
}

Please help me.

A: Try
 navi_left = (Button)dialog.findViewById(R.id.navi_left);

Do the same for all buttons and textview
Instead of getApplicationContext() try MainActivity.this
  final Dialog dialog = new Dialog(MainActivity.this, android.R.style.Theme_Translucent_NoTitleBar);


text:
Q: How to Pass Parameters to an Custom interaction Request I would like to pass a parameter while calling Raise method of Interaction Request which could be data bound to the view in the interaction request.
How to achieve this behavior?
Thanks in advance.
Noufal

A: You can't pass parameters through the Raise call.  You could try using a custom view (https://github.com/PrismLibrary/Prism-Samples-Wpf/blob/master/InteractivityQuickstart/InteractivityQuickstart/Views/CustomPopupView.xaml) and add properties that you can use to data bind your data to, or use a custom dialog service instead.


text:
Q: Simular um evento de Click sem clicar usando jQuery Tenho um projeto aqui com um problema,
estou perto de resolver mas preciso de uma mão de vocês!
Na Home, temos um botão chamado "Coberturas" que ao ser clicado deve ser levado para a página de Empreendimentos.
Nesta página, temos um Plugin do tipo Portfolio-Filter, onde a princípio todos os imóveis são mostrados, e caso o usuário clique em alguma categoria, por ex: 1 dormitório, 2 dormitórios ...... coberturas, então apenas os imóveis deste tipo ficam na tela com um efeito desaparecendo os outros em forma de fadeToggle().
Mas a url não é alterada ao clicar nesses filtros, normalmente um #Categoria aparece na url, mas neste caso não.
Fiz o seguinte:

*

*No botão Coberturas da Home, eu chamo a URL: http://site .com .br?tipo=coberturas

*Então o jQuery busca na url a string "tipo=coberturas", isso já está ok.

*Agora preciso que quando isso acontecer, forçar um click (não sei se é possível) sem o usuário clicar, no filtro Coberturas.

Dicas??
Segue código:
$(document).ready(function () {
    if(window.location.href.indexOf("?tipo=coberturas") > -1) {
       alert("Opa, encontrou.");
       var filtroCoberturas = $('li a[data-filter*="cobertura"]');
       //Agora aqui preciso fazer a LI selecionada ser clicada automáticamente
    }
});

A: Você pode usar $.trigger('click')
$(document).ready(function () {
    if(window.location.href.indexOf("?tipo=coberturas") > -1) {
       alert("Opa, encontrou.");
       var filtroCoberturas = $('li a[data-filter*="cobertura"]');
       //executa o evento "click" no elemento
       filtroCoberturas.trigger('click');
    }
});

A: Realmente era através do trigger, mas assim:
if(window.location.href.indexOf("?tipo=coberturas") > -1) {

    $(document).on('ready simularClique', function() {
        var filtroCoberturas = $('li a[data-filter*="cobertura"]');
        filtroCoberturas.click();
    });
    // Chama a função de clique através do trigger
    $(document).trigger('simularClique');

}

Não dava para chamar o clique direto via trigger().
Fui obrigado a fazer o trigger chamar uma função.


text:
Q: fetch list of data got incomplete result, how to remove the limitation i try to get all the data which is belong to logged user but got incomplete result, it suppose to be returning 22 data but the code only returning 19 data
export const getHistoryList = async (filterPayload: Array<IFilterPayload>, dispatch: Dispatch<any>) => {
    dispatch(setProductStart())

    let payload: IHistoryList[] = [];
    let filter: ModelImportHistoryFilterInput = {};
    let orFilter: ModelImportHistoryFilterInput[] = [];

    filterPayload.map((item) => {
        if (item.type === "merchantID") {
          filter = { ...filter, merchantImportHistoriesId: { eq: item.value } };
        }
        if (item.type === "action") {
          orFilter.push({ action: { eq: ImportHistoryAction[item.value as keyof typeof ImportHistoryAction] } });
        }
    });

    orFilter = orFilter.filter(item => item.action?.eq !== undefined);
    if (orFilter.length > 0) {
      filter = { ...filter, or: orFilter };
    }

    const result = await (API.graphql({
        query: queriesCustom.listImportHistoriesCustom,
        variables: { filter: filter }
    }) as Promise<{ data?: any }>)
        .then((response) => {
            const data = response.data.listImportHistories.items;
            return data
        })

   ...

  }

if i remove the filter from variables i got only 100 data from total 118 data

i already try this temporary solution to set the limit in variables to 2000, which is worked, but i don't think this is the correct approach
  const result = await (API.graphql({
      query: queriesCustom.listImportHistoriesCustom,
      variables: { limit: 2000, filter: filter }
  }) as Promise<{ data?: any }>)
      .then((response) => {
          const data = response.data.listImportHistories.items;
          return data
      })

how can i overcome this problem please help?


text:
Q: How to POST OData entity and link it to multiple existing entities at the same time? How do I post an entity to an OData endpoint while at the same time associating it with other existing entities in the body?

Consider the following class structure (sample):
class Invoice
{
    public int Id { get; set; }

    public Person Issuer { get; set; }

    public Person Recipient { get; set; }

    // other properties
}

class Person
{
    public int Id { get; set; }

    // other properties
}

Both Invoice and Person are entities in my domain (thus the Id property). Imagine that both are exposed in their own entitysets, so:

*

*GET http://host/odata/People(1)
returns Person with Id = 1

*GET http://host/odata/Invoices(2)?$expand='Issuer, Recipient'
returns Invoice with Id = 2 and both Issuer and Recipient expanded in the payload
Now consider the following requirement:

I want to create a new invoice in the system that will be associated to an existing issuer and recipient

How do I "tell" the OData framework that I want to associate a given navigation property to an existing entity? How would my controller action be notified that this is the intention?
Ideally, I'd like a POST body to look like this:

*

*POST http://host/odata/Invoices
{
    "Issuer": "/odata/People(1)",
    "Recipient": "/odata/People(2)",
    "Property1": "someValue",
    "Property2": "100",
    ...
}
Once the server receives this payload, it should:

*

*Load the required "people(1)" Person for the Issuer property. If it does not exist, a bad request should be returned.

*Load the required "people(2)" Person for the Recipient property. If it does not exist, a bad request should be returned.

*Create a new Invoice instance and assign the Issuer and Recipient from above, then save it to the database.

I know OData has support for configuring the relationships after-the-fact with special PUT/POST URLs using the entity/relation/$ref syntax. With such syntax, I'd be able to do something like this:

*

*POST http://host/odata/Invoices
{ "Property1": "someValue", "Property2": "100" }

*PUT http://host/odata/Invoices(x)/Issuer/$ref
{"@odata.id":"http://host/odata/People(1)"}

*PUT http://host/odata/Invoices(x)/Recipient/$ref
{"@odata.id":"http://host/odata/People(2)"}
However, I want to be able to perform this all in a single POST operation that should atomically create the instance.
I tried a few ideas to see what the server would accept, and this seemed to go through:
{
    "Issuer": { "@odata.id": "/odata/People(1)" },
    "Recipient": { "@odata.id": "/odata/People(2)" },
    "Property1": "someValue",
    "Property2": "100",
    ...
}

But I have no idea how I'd be able to read/parse the IDs from this (like how it is done in a dedicated Ref method), or even if this is supported in the OData standard.
For now, I'll resort to just passing the ID property in the model and in the server assuming this will always mean an existing relationship, but that's far from ideal as it is not general-purpose enough and would make my API inflexible.

A: The simplest solution is to expose the ForeignKey properties in your Model directly. Even the Models used in the MS Doc Entity Relations in OData v4 Using ASP.NET Web API 2.2 explaining $ref expose the FKs.
class Invoice
{
    public int Id { get; set; }

    public int Issuer_Person_Id { get; set; }
    [ForeignKey(nameof(Issuer_Person_Id)]
    public Person Issuer { get; set; }

    public int Recipient_Person_Id { get; set; }
    [ForeignKey(nameof(Recipient_Person_Id)]
    public Person Recipient { get; set; }

    // other properties
}

This doesn't make your API inflexible, rather it makes your API MORE flexible.
This also grants you greater control over the DataBase Implementation of your Model, whilst still being database engine agnostic.
In environments where Lazy Loading is enabled, including FKs has some added performance benefits if you need to check the existence of a related entity without requiring it to be loaded into memory.

NOTE: By including the FKs in the Model the $ref syntax and batching can still be used, but we now have access to the more practical FK Id values that can be easily validated in the server side code, just as it is easier to send the values.

Now in the PATCH or POST we can simply use the Ids directly to link the Person records.

The same level of information/understanding is required at both the client and server sides to achieve this, so it is still general purpose, the $metadata document fully describes which FK fields link the related entities but a good naming convention as demonstrated here can help

{
    "Issuer_Person_Id": 1,
    "Recipient_Person_Id": 2,
    "Property1": "someValue",
    "Property2": "100",
    ...
}

Be Careful:
One of the reasons that many Model designers choose NOT to expose ForeignKey properties is that ambiguity exists when or if you try to send or process both the ForeignKey and the related Entity.
For a PATCH there is no confusion, the v4.0 specification tells use specifically to ignore the related entity and that it shouldn't be sent at all.

11.4.3 Update an Entity
If an update specifies both a binding to a single-valued navigation property and a dependent property that is tied to a key property of the principal entity according to the same navigation property, then the dependent property is ignored and the relationship is updated according to the value specified in the binding.

For a POST however if the related entity is provided in the request as well as the FK, the related entity is assumed to be a deep insert and the FK is ignored.

11.4.2.2 Create Related Entities when Creating an Entity
Each included related entity is processed observing the rules for creating an entity as if it was posted against the original target URL extended with the navigation path to this related entity.

With FKs enabled My advice therefore is to take steps on the client side to make sure you don't try to send both the FK and the related entities in requests back to the API.

I agree that the @odata.id in the post as you have suggested is a logical conclusion, however it raises other potential implementation issues which is why the protocol provides the concept of direct CRUD operations against the $ref endpoint that represents the ForeignKey reference.
OData V4.0 was specifically declarative and designed such that operations against a single resource should only affect that resource. This is why we cannot PATCH related properties in a single query, as with this referencing issue, there are too many potential implementation variations and interpretations of how it might work that they kept the specification concise and constrained in the way that it is.

Basically a consensus between interested parties could not be reached on the protocol specifics and guidance on how to handle deep updates before the specification was drafted. The ASP.Net FX and Core implementations (as of this post) are only OData 4.0 Minimal Conformance Level OOTB. There is a lot you need to do to increase the level of conformance.

Batching is the preferred mechanism to perform operations that "might" affect multiple resources in a single transacted query, however it is a more involved solution than if you just expose the FKs!

Whilst it's nice that we can use complicated syntax and batching to achieve this in other ways, there are many other practical benefits to exposing the FK Ids in the Model and making them accessible to the client side, not just in the server logic, IMO these can be really big benefits in the right scenarios:

*

*Optimised data retrieval in Grids
If many rows have a link to the same record in another table you only need to download the linked value from the common table once. For some types of data it will be more efficient to download all the possible lookup values from the common tables and then in your presentation layer you can join in the results based on the Ids. These lookup values may only need to be downloaded once in the whole session in some use cases.

*ComboBox relationship assignments
There is a time and a place, but by including the FKs in your Model it is very simple to bind to ComboBox or DropDownList implemenations in the presentation layer to change or assign the related entities, the implementation is almost identical to the grid presentation, bind the control the FK, and show the related entities in the drop down list.
UPDATE 2022
OData v4.01 Minimal Conformance level SHOULD support deep updates
But the current version of ODataLib (v8) used by the .Net 5 runtime does not support this feature OOTB and is still only minimally compliant to v4.0, albeit with some of the more advanced features than before.

11.4.3.1 Update Related Entities When Updating an Entity
Payloads with an OData-Version header with a value of 4.01 or greater MAY include nested entities and entity references that specify the full set of to be related entities, or a nested delta payload representing the related entities that have been added, removed, or changed. Such a request is referred to as a "deep update". If the nested collection is represented identical to an expanded navigation property, then the set of nested entities and entity references specified in a successful update request represents the full set of entities to be related according to that relationship and MUST NOT include added links, deleted links, or deleted entities.

The json payload implementation is similar to your suggestion:
{
    "@type":"#container.Invoice",
    "Issuer": { "@id": "People(1)" },
    "Recipient": { "@id": "People(2)" },
    "Property1": "someValue",
    "Property2": "100",
    ...
}

There is now also a nested delta representation to Add, Remove or Update links as well as nested values in a single request, but these advanced mechanisms are not yet implemented in the ODataLib runtimes.


text:
Q: Why do I need to set padding to 15.5px for both  to have equal height? Code

.topnav {
  width: 50%;
  display: inline-block;
  background-color: black;
  overflow: hidden;
}

.topnav a {
  box-sizing: border-box;
  color: white;
  display: inline-block;
  padding: 16px;
  text-decoration: none;
  font-size: 17px;
  margin: 6px;
}

.topnav a:hover {
  background-color: blue;
  color: white;
}

.topnav a.active {
  background-color: blue;
  color: white;
}

.searchbar {
  width: 50%;
  float: right;
  display: inline-block;
  background-color: black;
  overflow: hidden;
}

.searchbar input[type=text] {
  float: right;
  width: 80%;
  box-sizing: border-box;
  color: black;
  display: inline-block;
  padding: 15.5px;
  outline: none;
  margin: 6px;
  border: 3px solid transparent;
  transition: 0.1s;
}

.searchbar input[type=text]:hover {
  border: 3px solid blue;
}
<!DOCTYPE>

    abcdefg

    <form>
      <input type='text' placeholder='Search here'>
    </form>

As the title suggests, in order for both
 and
 to have the same height, I can set
 padding to 15.5 pixels each.
padding: 15.5px;

Because of that, I'm having trouble understanding why. That is, I managed to get both
 height to the same size by guessing the right padding, not something I want to be doing. Therefore, I'm asking for a systematic way to know how much padding I need.

A: I don't know if that will be good for you about height exactness... But certainly will easier to tweak. I used a CSS grid an just an additional div as a wrapper.

.topNavContainer {
  display: grid;
  grid-template-columns: 60% 40%;
  grid-template-rows: 53px;
  grid-gap: 6px;
  align-items: center;
  justify-content: space-between;
  background-color: black;
  box-sizing: border-box;
  overflow: hidden;
  border: 6px solid black;
}

.topnav a {
  padding: 16px 12px;
  color: white;
  text-decoration: none;
  font-size: 17px;
}
.topnav a.active,
.topnav a:hover {
  background-color: blue;
  color: white;
}
.searchbar input[type="text"] {
  width: 100%;
  padding: 16px 0;
  color: black;
  outline: none;
  border: 3px solid transparent;
}
.searchbar input[type="text"]:hover {
  border: 3px solid blue;
}

    abcdefg

    <form>
      <input type='text' placeholder='Search here'>
    </form>

A: So I think you're missing that border-box does not include margins (which might have thrown off your calculations). So if you look at the dev tools and remove the 15.5px padding style on you input tag, then scroll to the bottom, you'll see this nice looking thing:

Yes there is still padding on it, this is from another style (ignore it). Your counterpart div happens to have a height of 64px (on my browser at least), so let's subtract from 64 all the heights (except for the padding, since we will be replacing that) that the dev tools are showing:
64 - 15 - 3  - 3 - 6 - 6 = 31px <- the remaining space
31px / 2 = 15.5px
However, calculations are not ideal either. Specify your heights directly with pixels or percentages, or consider the other answers here.


text:
Q: pgfplots: "nodes near coords" on xbar chart is off I am trying to make an xbar chart using pgfplots, and I'd like to add the bar's value to the bar.
Simply using "nodes near coords" positions the value for a ybar chart, which isn't correct here. What's the best way to position these nodes?

My code:
\documentclass[letterpaper]{article}
\usepackage{tikz}
\usepackage{pgfplots}
\begin{filecontents}{my.dat}
Label     value       num
992       70          1
993       120         2
994       30          3
995       330         4
999       50          5
988       50          6
989       50          7
983       50          8
\end{filecontents}
\begin{document}

\begin{tikzpicture}
\begin{axis}[
    xbar,
    xlabel=My value,
    ylabel=Label here,
    xmajorgrids=true,
    ytick=data,
    yticklabels from table={my.dat}{Label},
    nodes near coords,
]
    \addplot table [x=value, y=num]
    {my.dat};
\end{axis}

\end{tikzpicture}

A: You can tell pgfplots to label the coordinates correctly by setting nodes near coords align=horizontal.