text:
Q: Iterate through the fields of a struct in Go Basically, the only way (that I know of) to iterate through the values of the fields of a struct is like this:
type Example struct {
    a_number uint32
    a_string string
}

//...

r := &Example{(2 << 31) - 1, "...."}:
for _, d:= range []interface{}{ r.a_number, r.a_string, } {
  //do something with the d
}

I was wondering, if there's a better and more versatile way of achieving []interface{}{ r.a_number, r.a_string, }, so I don't need to list each parameter individually, or alternatively, is there a better way to loop through a struct?
I tried to look through the reflect package, but I hit a wall, because I'm not sure what to do once I retrieve reflect.ValueOf(*r).Field(0).
Thanks!

A: If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.
package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

Run in playground
Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

A: Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that
package main

import (
    "fmt"
    "reflect"
)

type person struct {
    firsName string
    lastName string
    iceCream []string
}

func main() {
    u := struct {
        myMap    map[int]int
        mySlice  []string
        myPerson person
    }{
        myMap:   map[int]int{1: 10, 2: 20},
        mySlice: []string{"red", "green"},
        myPerson: person{
            firsName: "Esmaeil",
            lastName: "Abedi",
            iceCream: []string{"Vanilla", "chocolate"},
        },
    }
    v := reflect.ValueOf(u)
    for i := 0; i < v.NumField(); i++ {
        fmt.Println(v.Type().Field(i).Name)
        fmt.Println("\t", v.Field(i))
    }
}

and there is no *panic* for v.Field(i)

A: Go 1.17 (Q3 2021) should add a new option, through commit 009bfea and CL 281233, fixing issue 42782.

reflect: add VisibleFields function
When writing code that reflects over a struct type, it's a common requirement to know the full set of struct fields, including fields available due to embedding of anonymous members while excluding fields that are erased because they're at the same level as another field with the same name.
The logic to do this is not that complex, but it's a little subtle and easy to get wrong.
This CL adds a new reflect.VisibleFields() function to the reflect package that returns the full set of effective fields that apply in a given struct type.

fields := reflect.VisibleFields(typ)
for j, field := range fields {
    ...
}

Example,
type employeeDetails struct {
    id          int16
    name        string
    designation string
}
func structIterator() {
    fields := reflect.VisibleFields(reflect.TypeOf(struct{ employeeDetails }{}))
    for _, field := range fields {
        fmt.Printf("Key: %s\tType: %s\n", field.Name, field.Type)
    }
}

A: After you've retrieved the reflect.Value of the field by using Field(i) you can get a
interface value from it by calling Interface(). Said interface value then represents the
value of the field.
There is no function to convert the value of the field to a concrete type as there are,
as you may know, no generics in go. Thus, there is no function with the signature GetValue() T
with T being the type of that field (which changes of course, depending on the field).
The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface()
offers.
The following code illustrates how to get the values of each exported field in a struct
using reflection (play):
import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

A: use this:
type x struct {
    Id  int
    jsj int
}
func main() {
    x2 := x{jsj: 10, Id: 5}
    v := reflect.ValueOf(x2)
    for i := 0; i < v.NumField(); i++ {
        fmt.Println(v.Field(i))
    }
}

====>10
====>5

A: In Go, you can use the reflect package to iterate through the fields of a struct. The reflect package allows you to inspect the properties of values at runtime, including their type and value. Here's an example of how to iterate through the fields of a struct:
Go Playground
package main

import (
    "fmt"
    "reflect"
)

type Movie struct {
    Name string
    Year int
}

func main() {
    p := Movie{"The Dark Knight", 2008}

    val := reflect.ValueOf(p)
    typ := val.Type()

    for i := 0; i < val.NumField(); i++ {
        field := val.Field(i)
        fieldType := typ.Field(i)

        fmt.Printf("Field Name: %s, Field Value: %v\n", fieldType.Name, field.Interface())
    }
}

Output:
Field Name: Name, Field Value: The Dark Knight
Field Name: Age, Field Value: 2008

A: Taking Chetan Kumar solution and in case you need to apply to a map[string]int
package main

import (
    "fmt"
    "reflect"
)

type BaseStats struct {
    Hp           int
    HpMax        int
    Mp           int
    MpMax        int
    Strength     int
    Speed        int
    Intelligence int
}

type Stats struct {
    Base map[string]int
    Modifiers []string
}

func StatsCreate(stats BaseStats) Stats {
    s := Stats{
        Base: make(map[string]int),
    }

    //Iterate through the fields of a struct
    v := reflect.ValueOf(stats)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        val := v.Field(i).Interface().(int)
        s.Base[typeOfS.Field(i).Name] = val
    }
    return s
}

func (s Stats) GetBaseStat(id string) int {
    return s.Base[id]
}

func main() {
    m := StatsCreate(BaseStats{300, 300, 300, 300, 10, 10, 10})

    fmt.Println(m.GetBaseStat("Hp"))
}

A: Use reflect package. First, get the type of variable with reflect.TypeOf and get numbers of elements with reflect.NumField.To obtain the values of the fields iteratively of a structure must reflect the variable and use the function rg.Elem().Field(i)
package main

import (
    "fmt"
    "reflect"
)

type Gopher struct {
    Name  string
    Color string
    Year  int
}

func main() {
    g := Gopher{Name: "AAA", Color: "BBBB", Year: 2021}

    gtype := reflect.TypeOf(g)

    numFields := gtype.NumField()

    rg := reflect.ValueOf(&g)

    for i := 0; i < numFields; i++ {
        fmt.Println(rg.Elem().Field(i))
    }
}


text:
Q: Beginner needing experienced advice for important choices I've never written a program, (although I've dabbled in Access and am familiar with OOP concepts), and have decided to undertake the challenge of writing myself a database program for home use.  (It'll keep track of our finances and be customized to our way of doing things.)  I've pretty much decided to use Python and SQLite, but that still leaves other decisions to be made.  I think I should get experienced advice and help choosing because I know nothing about the pros and cons (for my situation) of what's out there.
I know I'll need reports of some kind (something similar to Access reports would be ideal).  Also I'll need (the easiest way) to build a UI.  What are some softwares that I (total beginner) should look at for those purposes?  And are there other tools will I need besides those?
Thanks a lot for your help.
Update. Are there any drag and drop form and report development tools for Python/Sqlite (similar to Access)?  What about opinions on Netbeans IDE and Swing UI for me?

A: Tkinter is a *great** UI framework for beginners. I highly recommend using that, if it seems powerful enough to fill your needs.
Since it sounds like you're pretty inexperienced as far as programming goes, here's what I recommend:
1) Learn how to do basic IO, and especially learn Python's string formatting. It's super useful, and probably invaluable in your situation.
2) Learn how to do SQL queries with SQLite - attach your Python IO skills to SQLite.
3) Learn Python's object model - how it fits within the concept of OOP, and especially how you can make an object to fit your data model. Learn how this can work in between Python's IO and SQLite IO.
4) Now that you're comfortable putting data into and getting data out of a SQLite database and a user, and can handle objects comfortably, it's time to start learning about event driven programming, mainloops, and GUI layouts. Tkinter is pretty simple and Effbot has some rather good information about Tkinter.
5) Tie all of these skills and knowledge together and make yourself a program. You'll probably have to go back and brush up, relearn, or learn some new things about 1-4 all along the way. Don't be afraid to re-factor code - if it seems like something is a pain to work with/around, you're probably doing something wrong, or just not seeing a solution right in front of your face. In some cases it's ignorance, in others you've just been looking at your program too long and may be married to the idea of doing it the "wrong" way. If your solution isn't simple, then you may be complicating the problem.
6) Ask for help. If you get stuck, you can always ask here, or at the python tutor mailing list . Just tell/show what you've done, what you expect to happen, and what it does instead. Most pythonistas tend to be a rather helpful bunch, and even more so when you show you've been trying to work at it yourself.
Anyhow, HTH, and good programming!
*by great I mean it has good features, but it's not very pretty or overly complicated. Plus it comes standard with your Python install.
For instance, a simple tkinter program with a label and a button could look like this:
import Tkinter as tk
# Initialize a new root window
root = tk.Tk()

# Create a label that belongs to the root window
hello = tk.Label(root, text='Hello')

# Create a button that belongs to root, and will make the program
# quit when pressed
goodbye = tk.Button(root, text='Goodbye', command=root.quit)

# Use the pack manager to add the button and label to the root
# Window - do NOT mix pack and grid managers - they don't play well
hello.pack()
goodbye.pack()

# Enter the mainloop
root.mainloop()

A: One advice if you've never done any programming before is: small steps.
Write a small program that extracts things from a SQLite database and just prints them. Learn how that works and throw it away.
Do the same with reading files, make a simple GUI and so on with all the aspects you need to know for your program.
Once you know the pieces, try putting them together.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is system.js adding stuff to my javascript? I am trying to get JQWidgets to work.  It has a jsxcore.js file that defines the following variable:
 var jqxBaseFramework = window.minQuery || window.jQuery;

Then in other files, this variable is used.  But I am getting an error that says jqxBaseFramework is not defined in the very next file.
I noticed that when I system.import a file, this added to the top of it:
  (function(require, exports, module, __filename, __dirname, global, GLOBAL) {

This causes variables that would be in scope to be out of scope.
Is system.js doing this?  If so, Is there a work around to the scope issue?
If not, I am going to have to go add that variable to the top of each file.... Not fun as there are quite a few.

A:
Is system.js doing this?

Yes

If so, Is there a work around to the scope issue?

Yes. SystemJS is a module loading system. You treat your files as encapsulated modules. You should throw away the concept of globals.
Should you want to expose a value from a module, you export it. Should a module need a value from a certain module, you require it. Read more about CommonJS to know more about how this mechanism works.


text:
Q: How iteratively use xpath on a scrapy.selector.unified.SelectorList? Let's say I have the following page structure:

Within that structure I have the following nested structure:

I wrote
offers = response.xpath('//li[@class = "search-page__result"]')

to try and create an inerrable list. This part is successful, I believe, because if I say
for offer in offers:
    print(offer.get())

then it will print out the HTML subsection as a string.
However if I say
for offer in offers:
    features = offer.xpath('//ul[@class = "listing-key-specs"]')

the content of features looks as if I would have used response instead of offer.
Does anyone have any guidance on how I can use xpath iteratively on each subsection of the structure at a time?
EDIT: I wanted to add this alternative solution that I found before my question was answered. As suggested here by YohanObadia, the below will work too:
for offer in offers:
    features = Selector(text = offer.extract()).xpath('//ul[@class = "listing-key-specs"]')

A: // means your context is the root again. Just put a dot in front of the slashes and the context is offer.
for offer in offers:
    features = offer.xpath('.//ul[@class = "listing-key-specs"]')

Here is an answer that explains it.


text:
Q: Add Array of Objects into UseState ([]) i´m getting following error message "Error: Objects are not valid as a React child (found: object with keys {fzfvhv76576, user }). If you meant to render a collection of children, use an array instead." Im trying to add my firebase data into an Array of UseState([]). I tried several methods, but unfortunately without success, i have no ideas anymore. Hope someone can help me.
export function ListUserTask() {

    const [tasks, getUserTasks] = useState([] as any);
    var data: Object[] = [];

    useEffect(() => {
        (async () => {
            const userData = await getUserTask();

            console.log("userData", userData);

            for (let index = 0; index < userData.length; index++) {
                console.log("loop", data);

                data.push(userData[index]);
                getUserTasks([tasks, data[index]]);
                // console.log("useState:", tasks);
            }
        })();
    }, []);

    return (
        <IonContent>
            <IonText color="muted">

Get User Tasks

{tasks}

            </IonText>
        </IonContent>
    );
}

export default ListUserTask;

my Firebase structure as followed:

A: You are trying to render an entire object in the h2 tag which is wrong in React.
<IonContent>
        <IonText color="muted">

Get User Tasks

{tasks}
  // WRONG
        </IonText>
    </IonContent>

I will try to update your code:
export function ListUserTask() {

const [tasks, setTasks] = useState([] as any);

useEffect(async () => {
   const userData = await getUserTask();
   if(userData){
     setTasks(userData);
     }
}, []);

return (
    <IonContent>
        <IonText color="muted">

Get User Tasks

            {tasks.map(t) =>
{t.user}
}

        </IonText>
    </IonContent>
    );
}

export default ListUserTask;


text:
Q: ruby access static variable class A
  @@ololo = 1
end

A::ololo
A.new.ololo
NoMethodError: undefined method `ololo'

okey. I need an attr_reader
class B
  @@ololo = 1
  attr_reader :ololo
end

A::ololo
NoMethodError: undefined method `ololo'
A.new.ololo
=> nil

wtf? is there any limit for ruby accessors?
class C
  @@ololo = 1
  def self.ololo
    @@ololo
  end
  def ololo
    @@ololo
  end
end

C::ololo
=> 1
C.new.ololo
=> 1

Ruby men usually say "yeah! pretty good!". is this pretty good?
Can anyone provide shorter code?

A: attr_accessor :ololo defines the methods ololo and ololo= which work against an instance variable named @ololo. So what happens when you try to access A::ololo ruby will find your instance method ololo and fail since you're trying to call it as a class method.

A: Yes, you can.
class A
  cattr_accessor :ololo
  @@ololo = 1
end

class B
  A.ololo #Gets class variable "ololo" from class A
end

This is basically a Ruby on Rails feature.  However, outside Rails, you can obtain the functionality from the Ruby Facets gem:
https://github.com/rubyworks/facets/blob/master/lib/core-uncommon/facets/module/cattr.rb
See this discussion:
cattr_accessor outside of rails

A: You can't do what you want to do :)
@harald is right. attr_reader will define GETTER only for instance variable, for "static" (aka "class variables") you need to define setter and getter by yourself:
class A
  @@ololo = 1

  # instance level

  # getter
  def ololo
    @@ololo
  end
  # setter
  def ololo=trololo
    @@ololo = trololo
  end

  # and class level
  # if you need it

  # getter
  def self.ololo
    @@ololo
  end
  # setter
  def self.ololo=trololo
    @@ololo = trololo
  end
end

So:
a = A.new
b = A.new
A.ololo
#=> 1
a.ololo
#=> 1
A.ololo = 100
A.ololo
#=> 100
a.ololo
#=> 100
b.ololo
#=> 100
a.ololo = 4
A.ololo
#=> 4

...
Shorter one:
class A
  @ololo = 1
  class << self
    attr_accessor :ololo
  end
end


text:
Q: When is it a prime?
Find all positive integer $k$ such that $k^k+1$ is a prime.

I only found $k=1,2,4$ where the values are $2,5,257$.
But I cannot prove why others will not work. Pls help tks.
PS: It is one of my exam qns which it ask for $k^k+1$ is prime less than $10^{20}$

A: First of all, $k$ must be the form $k=2^{2^m},m\in \mathbb{N}$. If you want to find all primes being the form $k^k+1$ less than $10^{20}$, then
$$2^{2^m\cdot2^{2^m}}+1 \leq 10^{20}$$
Hence,
$$2^{2^{2^m+m}}\leq 10^{20}$$
$$2^m+m\leq \log_2\log_2(10^{20})<7$$
Finally, we can try $m=0,1,2$ corresponding to $k=2,4,16$. When $k=2,4$,$k^k+1$ is a prime. When $k=16$, note that this is a Fermat number $F_6$ which is not a prime.


text:
Q: SDL2_image not found I am trying to compile the following code which has the headers:
#include <SDL2/SDL.h>
#include <SDL2_image/SDL_image.h>

However after running the following makefile:
g++ -std=c++11 src/main.cpp -lSDL2 -lSDL2_image

I get the following error:
fatal error: SDL2_image/SDL_image.h: No such file or directory
#include <SDL2_image/SDL_image.h>

Any suggestions? Not entirely sure about my installation of SDL_image. I am running this on Ubuntu.

A: Run apt-file search SDL_image.h
The result will tell you the location of the include file.
For instance, /usr/include/SDL2/SDL_image.h was returned.
So, when you want to include SDL_image.h, write everything after the include/ in between < >.
Thus, includes should look like the following:
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>

See the question's comments for the original discussion regarding this solution.

A: From SDL documentation, it says that add 'lSDL_image' to the end of the compile line.
    cc -o myprogram mysource.o `sdl-config --libs` -lSDL_image

or
    gcc -o myprogram mysource.c `sdl-config --libs` -lSDL_image

Here is the reference -> https://www.libsdl.org/projects/docs/SDL_image/SDL_image.html
Section 2.2 Compiling.
So for SDL2, you just need to change 'lSDL_image' to 'lSDL2_image'.

A: This problem can be solved through installing libsdl2-image-dev package:
apt install libsdl2-image-dev

A: For Windows + SDL2-2.0.8 + SDL_image-2.0.4 + Codeblocks you've got the add both Runtime Binaries and Development Libraries to the compiler and linker. Or else, you'll get the error SDL2_image not found, even with having the dll in your program's directory, this occurs. Hopefully others find this helpful; I had to figure it out myself. Example: If your resources are separate, you'll be adding the two plus your standard SDL2 paths to your compiler and linker. Warning: SDL2_image.h has it's headers assuming that the headers are in the same folder as the SDL2 framework. If you get errors about the image header, include the sub-folder SDL2 from SDL framework in the path and then you should be including SDL2 in the program as: include <SDL.h> rather than include <SDL2/SDL.h>.


text:
Q: What are the physics behind the hairy ball theorem? What are the physics behind the hairy ball theorem? It seems that this theorem is a corollary of the way that vector fields are constructed or what happens to numbers when we move from three to two dimensions.
Is there any way to approach this theorem with arguments borrowed from physics?


text:
Q: "redirect" parameter lost after failed login in liferay In liferay, when we navigate to a private page without user login, we are redirected to login page with "redirect" parameter in URL.
If the login is success, the liferay redirects user to a "redirect" parameter value, but if the login fails (let say because of wrong password), liferay clears the "redirect" parameter (because of the page reload) and because of that the "redirect" functionality stops working.
Any idea how to keep this parameter even after failed login attempt?

A: I would try to save the existing redirect parameter in a cookie (when page is loaded) and then use that value before submitting the form. Haven't done it myself but I'd use a hook to overwrite the login.jsp. Just an idea.


text:
Q: Cassandra cluster vs cassandra ring If I have one Cassandra cluster setup across 5 data centers (3 are private DCs) and 2 are Public (Azure DCs), can I say I have 5 rings or is this 1 cluster and 1 ring ?
Can someone help understanding the term "ring" in this context.

A: Long answer:
Yes, cluster and ring can be used interchangeably.  "Cluster" is certainly used more today.  "Ring" comes from the early, pre-vNodes days of Cassandra, where each node was assigned a single, contiguous token range.
We used to have to manually configure the token range for each node.  In fact, I would use this code to do it (assuming a 5 node cluster):
python -c 'print [str(((2**64 / 5) * i) - 2**63) for i in range(5)]'

['-9223372036854775808', '-5534023222112865485', '-1844674407370955162', '1844674407370955161', '5534023222112865484']

When computing token ranges of partition keys, each node was responsible for the next, sequential range.  Once it got to the last node in the cluster, the range calculation looped back around to the first node, sort of making a ring-like diagram.

In summary, now with multiple non-contiguous token ranges on each node, Cassandra really doesn't form a "ring" anymore.  To see what I mean, run a nodetool ring on a Cassandra 3 node with multiple vNodes, and you'll see what I mean.
Short answer:
For all intents and purposes, "cluster" == "ring."  You can say either, and people will know what you mean.


text:
Q: Jquery Country/State Json and more What I am trying to accomplish is the following:
I have a Country box.
<select class="country singleListBox" name="Country">
    <option value="UNITED STATES">UNITED STATES</option>
    <% Call GetCountry %>
</select>

All GetCountry does is populate it with the countries the client has enabled.
I have a state box.
<select class="autoship singleListBox" name="State">
    <option value="active">Utah</option>
</select>

I have a page that builds out JSON that will either contain the list of states for the selected country, or return with an empty value.
Here is what it looks like not empty:
{
    "regions": [
        {
            "region": "AK"
        },
        {
            "region": "AL"
        },
        {
            "region": "AR"
        },
        {
            "region": "AS"
        },
        {
            "region": "AZ"
        },
        {
            "region": "CA"
        },
        {
            "region": "CO"
        },
        {
            "region": "CT"
        },
        {
            "region": "DE"
        },
        {
            "region": "DC"
        },
        {
            "region": "FM"
        },
        {
            "region": "FL"
        },
        {
            "region": "GA"
        },
        {
            "region": "GU"
        },
        {
            "region": "HI"
        },
        {
            "region": "ID"
        },
        {
            "region": "IL"
        },
        {
            "region": "IN"
        },
        {
            "region": "IA"
        },
        {
            "region": "KS"
        },
        {
            "region": "KY"
        },
        {
            "region": "LA"
        },
        {
            "region": "ME"
        },
        {
            "region": "MH"
        },
        {
            "region": "MD"
        },
        {
            "region": "MA"
        },
        {
            "region": "MI"
        },
        {
            "region": "MN"
        },
        {
            "region": "MS"
        },
        {
            "region": "MO"
        },
        {
            "region": "MT"
        },
        {
            "region": "NE"
        },
        {
            "region": "NV"
        },
        {
            "region": "NH"
        },
        {
            "region": "NJ"
        },
        {
            "region": "NM"
        },
        {
            "region": "NY"
        },
        {
            "region": "NC"
        },
        {
            "region": "ND"
        },
        {
            "region": "MP"
        },
        {
            "region": "OH"
        },
        {
            "region": "OK"
        },
        {
            "region": "OR"
        },
        {
            "region": "PW"
        },
        {
            "region": "PA"
        },
        {
            "region": "PR"
        },
        {
            "region": "RI"
        },
        {
            "region": "SC"
        },
        {
            "region": "SD"
        },
        {
            "region": "TN"
        },
        {
            "region": "TX"
        },
        {
            "region": "UT"
        },
        {
            "region": "VT"
        },
        {
            "region": "VI"
        },
        {
            "region": "VA"
        },
        {
            "region": "WA"
        },
        {
            "region": "WV"
        },
        {
            "region": "WI"
        },
        {
            "region": "WY"
        },
        {
            "region": "AA"
        },
        {
            "region": "AE"
        },
        {
            "region": "AP"
        }
    ]
}

Here is what it looks like empty:
{
    "regions": [
        {
            "region": "empty"
        }
    ]
}

What I am trying to do, is when they change the value of the Country it posts to my json page, and spits back the regions found, or leaves region with a string value of empty.
The trick for me is if it returns back a list of regions I need this to be built into the above select -> option section.  But if it returns empty, I then need an input box here of type text to take the place of the select -> option.
What is the best way/best practice to accomplish this?  I can handle the posting of the JSON when they change the country, the part I think I will have trouble with is switching out the select for the input when the region is empty.
I am trying to parse this into a jquery object with not much success.
$('select[name=Country]').change(function () {
                console.log(this.value);
                $.getJSON('message_center_getRegions.asp', { country: this.value }, function (json) {
                var options = '';
                var obj = $.parseJSON(json);
                console.log('count' + obj.regions.count);
                console.log(json);
            })

I console.log(json) and it shows an object with 62 different regions.  When I select a country that I don't have regions for in the database it correctly shows it as being empty.  I can't seem to get obj to not be null console.log('count' + obj.regions.count); says obj is null.

A: Ideally, if there are no regions, the response should not return
"regions" : [ { "region" : "empty" } ]

It should just return an empty list like this
"regions" : []

Now, when you parse the JSON into a Javascript object, regions.count will be 0.
So,
// parse response into JS object

if (regions.count > 0)
{
    //create select element here
}
else
{
    //input element here
}


text:
Q: Update a Column with a like and a concat I have 2 tables: animal and espece(fr='species').
In animal I have a column named espece_id, in which I want to fill data with espece.id (primary key) and I try to do this:
UPDATE animal
SET espece_id = espece.id
WHERE espece LIKE concat('%', espece.name, '%');

table details:
animal: id, espece, espece_id
espece: id, name, scientific_name

animal.espece and espece.name are equal to some extent like: "dog" "eurasian sheperd dog" so that's why I try to use a LIKE in this update, but it gives a:

Error Code: 1054. Unknown column 'espece.name' in 'where clause'

what am I doing wrong?

A: You need a JOIN:
UPDATE animal AS a
JOIN espece AS e ON a.espece LIKE concat('%', e.name, '%')
SET a.espece_id = e.id


text:
Q: Efficient Way to do Very Complicated SQL Grouping: Say you have a table like this:
ID | Type | Reference #1 | Reference #2
0  | 1    | [A]          | {a}
1  | 2    | [B]          | {b}
2  | 2    | [B]          | {c}
3  | 1    | [C]          | {d}
4  | 1    | [D]          | {d}
5  | 1    | [E]          | {d}
6  | 1    | [C]          | {e}

Is there any good way to group by "Reference #1" and "Reference #2" as a "fallback", for lack of a better way of putting it...
For example, I would like to group the following IDs together:
{0} [Unique Reference #1],
{1,2} [Same Reference #1],
{3,4,5,6} [{3,4,5} have same Reference #2 and {3,6} have same Reference #1]

I am at a total loss as to how to do this... Any thoughts?

A: In mellamokb's query, the groupings are dependent on the order of the input.
ie.
VALUES
    (0, 1, '[A]', '{a}'),
    (1, 2, '[B]', '{b}'),
    (2, 2, '[B]', '{c}'),
    (3, 1, '[C]', '{d}'), // group 3
    (4, 1, '[D]', '{d}'), // group 3
    (5, 1, '[E]', '{d}'), // group 3
    (6, 1, '[C]', '{e}'); // group 3

produces a different result tahn
VALUES
    (0, 1, '[A]', '{a}'),
    (1, 2, '[B]', '{b}'),
    (2, 2, '[B]', '{c}'),
    (3, 1, '[C]', '{e}'), //group 3
    (4, 1, '[D]', '{d}'), // group 4
    (5, 1, '[E]', '{d}'), // group 4
    (6, 1, '[C]', '{d}'); // group 3

This might be intended, if there is some natural order to the References that you could specify, but its a problem if they are not.  The way to 'solve' this or specify another problem is to say that all equal Reference1s create a set of elements whose members are themselves and those elements whose Reference2 is equal to at least one member of that set.
In SQL:
with groupings as (
  select
    ID,Reference1,Reference2,
    (select min(ID) from Table1 t2
     where t2.Reference1=t1.Reference1 or t2.Reference2=t1.Reference2 ) as minID
  from
    Table1 t1
)
select
    t1.ID,t1.Reference1,t1.Reference2,t1.minid as round1,
    (select min(t2.minid) from
            groupings t2
      INNER JOIN groupings t3 ON t1.Reference2=t2.Reference2
) as minID
  from
    groupings t1

This should produce the full grouping each time.


text:
Q: How do I place the labels next to the series on a split packed bubble chart? Issue
Using Highcharts I am trying to do away with the legend on a split packed bubble and place the series names under or near the visual groups (see illustration below).

I tried setting plotOptions.packedbubble.label to { enabled: true } but its not showing anything.
Question:
How do I show the series names under the groups of the split packed bubble chart?

A: You can use the parentNodeFormat feature or parentNodeFormatter callback to achieve the wanted effect. Using the callback you can return custom HTML element if you need.
Demo: https://jsfiddle.net/BlackLabel/j2hq9osz/
dataLabels: {
    enabled: true,
    parentNodeFormat: '{series.name}',
    format: '{point.name}',
    style: {
        color: 'black',
        textOutline: 'none',
        fontWeight: 'normal'
    }
}

API: https://api.highcharts.com/highcharts/series.packedbubble.dataLabels.parentNodeFormat


text:
Q: Enable CORS in an Angular Paypal Docker application My application with angular front end and springboot backend is trying to make a REST POST call to one of the PayPal APIs from Angular front end. The application is deployed as a Docker container in GCP VM instance. If I dont open the broser with web security disabled I get the ERROR
"Access to XMLHttpRequest at 'https://pilot-payflowpro.paypal.com/' from origin 'http://myserverip' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

I see lot of answers for this question in SO and others with adding headers in httpd.conf / .htaccess files. But I dont have both these files. I tried adding headers to Dockerfile and also adding commands to docker-compose.yaml file. Also tried adding the end URL in angular proxy configuration file. None of it worked.
Is there any way to enable CORS either in a docker config file or in the server itself.
docker-compose.yml
  image: docker.image.link
  privileged: true
  ports:
    - '80:8080'
  restart: 'no'
  volumes:
    - '/var/sftp/upload:/usr/share/invoice/invoiceFile'

 environment:
    - SPRING_PROFILES_ACTIVE=docker
    - DB_CONN_STRING=jdbc:postgresql:url
    - DB_USER=postgres
    - DB_PASS=postgres
    - HOST_NAME=hostname
    - SMTP_HOST=smtphost
    - SMTP_PORT=25
    - SMTP_AUTH_TRUE_FALSE=false

Dockerfile
FROM openjdk:8-jdk-alpine

ARG JAR_FILE
ADD target/${JAR_FILE} /usr/share/application.jar
ADD template/ /usr/share/template

VOLUME /tmp

EXPOSE 8080

ENTRYPOINT ["java", "-jar", "/usr/share/application.jar"]

A: The CORS error is an error emitted by the browser when the request response, from the backend, hasn't the properly headers to tell to the browser that this client can perform/view the request.
So, in your case the backend is the PayPal (https://pilot-payflowpro.paypal.com/ -> paypal.com) not your backend, so even if you add any headers to your backend or frontend, the problem will persist because the only header that is important when you perform the request to the https://pilot-payflowpro.paypal.com/ is the header from the response of this request.
To solve this problem the https://pilot-payflowpro.paypal.com/ needs to send the correct header response allowing you to perform this request, and I think it's not possible because security reasons.
Some endpoints can't be use from a frontend application, only from a backend, and I think it's your case.
To avoid the CORS problem you can create an endpoint in your backend that call the https://pilot-payflowpro.paypal.com/. So, in your frontend you call your backend endpoint and the backend call the PayPal API.

A: calling the REST call is one solution. Another solution would be to mask the endpoint URL in the proxy configuration in Angular.
"/paypal" : {
        "target" : "https://pilot-payflowpro.paypal.com/",
        "secure" : true,
        "changeOrigin": true,
        "pathRewrite":{
            "^/paypal":""
        }
    }

And calling /paypal where we have to do the REST call.


text:
Q: Get last Monday with WeekdayName function I am trying to capture previous Monday date. So, if today is 6/5/2017, then if I open excel I need to return 1/5/2017 (last Monday) using VBA.
This is my code:
Dim strdate As String
Select Case WeekdayName(Now())
Case vbMonday
  strdate = Now()
Case vbTuesday
  strdate = Now() - 1
Case vbWednesday
  strdate = Now() - 2
Case vbThursday
  strdate = Now() - 3
Case vbFriday
  strdate = Now() - 4
Case vbSaturday
  strdate = Now() - 5
Case vbSunday
  strdate = Now() - 6
End Select

Can anyone suggest why this does not return the expected result?

A: The previous Monday's date is always
PreviousMonday = Date - Weekday(Date - 1, vbMonday)

A: I use this:
Dim d As Date
    d = Date

Do Until Weekday(d) = vbMonday
    d = DateAdd("y", -1, d)
Loop

'd = date of previous Monday


text:
Q: Como colocar aspas numa mensagem if(string.IsNullOrEmpty(pessoa.Nome))
{
    ModelState.AddModelError("Nome", "O campo nome é obrigatório");
}

Como faço para colocar aspas dentro da mensagem?
Ex.: O campo "nome" é obrigatório.

A: Você pode fazer de duas maneiras:
Usando barra invertida ():
if(string.IsNullOrEmpty(pessoa.Nome))
{
    ModelState.AddModelError("Nome", "O campo \"nome\" é obrigatório");
}

Ou usando o arroba (@) com aspas duplas duplicadas:
if(string.IsNullOrEmpty(pessoa.Nome))
{
    ModelState.AddModelError("Nome", @"O campo ""nome"" é obrigatório");
}


text:
Q: how to add to chrome previously deleted cookies? My plan was to make an ajax without sending the cookies there.
I tried to do some magic via jquery, but unfortunately I found I have no power over what cookies are sent. So I needed to delete them, do the ajax and then put them back. Here's the code.
chrome.cookies.getAll({domain: domain}, function(cookies) {
  var domain = 'facebook.com';
  // 1. delete cookies
  var myCookies = _.cloneDeep(cookies);
  for(var i=0; i<cookies.length;i++) {
    chrome.cookies.remove({url: "https://"+domain + cookies[i].path, name: cookies[i].name});
  }

  // 2. now do some ajax

  // 3. now get them back
  for (var i = 0; i < myCookies.length; ++i) {
    var cookie = myCookies[i];
    var obj = {
      name: cookie.name,
      value: cookie.value,
      url: "https://"+domain + cookie.path
    };
    chrome.cookies.set(obj);
  }
});

unfortunately, it logs me out, even when the cookies are added back, like they were supposed to. where is the catch?
Is the "url" and "domain" argument used well?


text:
Q: Lucas–Lehmer test and triangle of coefficients of Chebyshev's In the Lucas–Lehmer test with $ \quad p \quad $ an odd prime.
we know that $ \quad S_0=4 \quad $ and $ \quad S_i=S_{i-1}^2-2 \quad $ for $\quad i>0 \quad$
$M_p=2^p-1 \quad$ is prime if $ \quad S_{p-2} \equiv 0 \bmod {(2^p-1)}$
after some observations i found a link with     Triangle of coefficients of Chebyshev's OEIS A053122
$a(n,k)=(-1)^{n-k}\left(\begin{matrix} n+1+k \\ 2 \cdot k+1 \end{matrix}\right)$
from which
$S_{i+1} \cdot S_{i+2}\cdot \quad \ldots \quad \cdot S_{i+m} = \sum\limits_{k=0}^{2^m-1}{(-1)^{k+1}\left(\begin{matrix} 2^m+k \\ 2 \cdot k+1 \end{matrix}\right) \cdot (S_i^2)^k }$
can anyone help me find any reference or pointer on how to derive this result?

A: By the composition property of Chebyshev polynomials $T_m(T_n(x))=T_{mn}(x)$. Since $x^2-2 = 2T_2(\tfrac{x}2)$, we have $S_i = 2T_{2^i}(2)$ for all $i\geq 0$.
Furthermore, since $T_{2^k}(x) = \frac{U_{2^{k+1}-1}(x)}{2U_{2^{k}-1}(x)}$, we have
\begin{split} S_{i+1}\cdot S_{i+1}\cdots S_{i+m} &= 2^m T_{2^{i+1}}(2)\cdot T_{2^{i+2}}(2)\cdots T_{2^{i+m}}(2) \\
&=\frac{U_{2^{m+i+1}-1}(2)}{U_{2^{i+1}-1}(2)} \\
&= U_{2^m-1}(T_{2^{i+1}}(2))\\
&= \frac{U_{2^{m+1}-1}(T_{2^i}(2))}{2T_{2^i}(2)}\\
&= \frac{U_{2^{m+1}-1}(\tfrac{S_i}2)}{S_i}.
\end{split}
and it remains to use an explicit expression for $U_{2^{m+1}-1}(x)$ to obtain the formula in question.


text:
Q: How does the operator precendence of ++ vs -> work when incrementing incrementing a member int through a pointer? A question for C++ language lawyers out there. It looks simple but I'm trying to figure out exactly what is going on in my simple program.
struct A
{
    int data1;
    int data2;
};

int main()
{
    A myA;
    A* ptr = &myA;
    ptr->data1 = 100;
    ++ptr->data1;

    std::cout << "A: " << myA.data1 << std::endl;
    return 1;
}

The above correctly works and outputs 101 on my gcc 4.8.2.
According to things I've read online the ++ and -> operator have the same level of precedence (https://msdn.microsoft.com/en-us/library/126fe14k.aspx), thus I would expect precedence to be followed left to right.
If I interpreted left-to-right precedence, then I'd expect ++ptr to execute first rather than ptr->data1. This would lead to markedly different (and incorrect) results.
What am I missing here?

A: http://en.cppreference.com/w/cpp/language/operator_precedence
As u can see, the ++ operator what u used, a prefix operator and this have lower lever precedence than ->.
Suffix operator are same level than ->.

A: The prefix ++ is of lower priority than ->. Hence, the expression
++ptr->data1;

is the same as
++(ptr->data1);

A: -> has a higher order of operation than the prefix ++ increment, which you are calling.  So -> is being called first.
-> has the same order of precedence as the postfix ++ increment, which would amount to the following statement...
ptr++->data.  I'm not sure, but I think that doesn't even parse.


text:
Q: Defining projections for multiple shapefiles in ArcMap? I have over 100 shape files that don't have .prj file and thus when I bring them into ArcMap 10 they show the coordinate system as unknown.  I know all of the shape files coordinate system is GCS WGS 1984.  I also know I can use the Define Projection GP tool to individually assign the coordinate system to each file but that will take forever.
I was hoping there was a GP tool to batch define these but I don't see one.  Next I was thinking maybe I could use python to do this so I looked in the help menu and found a script but it gives me an error.
Here is the python code I tried (this is for a single shp file so I would still have the pain of typing the name for each file:
import arcpy
infc = r"C:\Documents and Settings\User\My Documents\ArcGIS\shpfiles\Site_2.shp"
prjfile = r"<install directory>\Coordinate Systems\Geographic Coordinate Systems\World\WGS 1984.prj"
arcpy.DefineProjection_management(infc, prjfile)

A: Just make copies of the .prj and rename.  So, e.g., if you have 3 shapefiles:

*

*one.shp,

*two.shp,

*three.shp.

Define the projection for one.shp and you will have one.prj in the directory.  Copy one.prj to the directory of two.shp and rename to two.prj, repeat for all shapefiles.  The .prj is just a text file.  As long as there is a .prj in the same directory as a .shp and with the same name, the software will pick it up.  Automate with whatever tools you are familiar with for copying and renaming files.

A: Edit:
Probably the easiest method would be.
Bring them all in and assign the correct crs to the document. They would be "unprojected" but sitting in the right place.
Then just export (multiple) to a new location.
I do see a GP tool for batch projection.

It may not be exposed in arcpy. ??
I think I would create a pgdb, (File, personal or even sde) and then create a fds (feature data set).
Assign the appropriate crs to that fds.
Import the shape files (multiple). [all fc in a fds inherit the crs of the fds].
Then you can export to shape file (multiple).
This would be in lieu of batch projection, and I'm sure could be scripted.

A: how about a simple shell script and ogr2ogr? See http://www.gdal.org/ogr2ogr.html for the exact syntax.

A: I think you guys are overthinking this one...

*

*Right-click on the "Define Projection" tool in toolbox,

*select "Batch",

*drag-and-drop your layers into the "Input Dataset" column,

*right-click in the first "Coordinate System" box to fill out the correct projection,

*then right-click on the projection you just selected and choose "Fill" which will fill out all of the rest of the projections for you.

*Hit "OK" and you are done.

A: If they are in the same directory, something like this would work (just replace your paths, maybe add in some exception handling):
import os, shutil

wgs84prjpath='c:/Program Files/ArcGIS/Desktop10.0/Coordinate Systems/Geographic Coordinate Systems/World/WGS 1984.prj'

def definewgs84(shpfilepath):
    tgtpath = os.path.splitext(shpfilepath)[0] + '.prj'
    shutil.copyfile(wgs84prjpath,tgtpath)

yourshapefiledirectory='C:/temp/'
extension='shp'

shpfileslist = [file for file in os.listdir(yourshapefiledirectory) if file.lower().endswith(extension)]

for filename in shpfileslist:
    definewgs84(os.path.join(yourshapefiledirectory,filename))

A: Here's what I use...it will only define the projection for raster files which don't have a projection. Hope it helps. It also creates a list of the files without projection for Quality Assurance purposes.
For your vectors it just needs a slight mod - FileList=arcpy.ListFeatureClasses()
# Defines projection for all rasters with undefined projection
# CAUTION - make sure you know that the projection you are defining is the correct one
# for all files in the current directory.

#Licence: Creative Commons
#Created by: George Corea; georgec@atgis.com.au, coreagc@gmail.com

import arcpy, glob, os, sys, arcgisscripting
from arcpy import env, mapping
path = os.getcwd()
env.workspace = path
env.overwriteOutput = True

print 'Reading files from ' + path
os.chdir(path)
prjFile=r'C:\\Python26\\GDA_1994_MGA_Zone_55.prj'

x=0
z=x+1
NoProjCount=0
FileList= arcpy.ListRasters()
for File in FileList:
    desc = arcpy.Describe(File)
    SR = desc.spatialReference
    if SR.name == "Unknown":
        print "Projection of " + str(File) + " is " + SR.name + " so defining projection."
        f = open('NoProjection.txt', 'a')
        f.write(str(File)+"\n")
        f.close()
        arcpy.DefineProjection_management(File, prjFile)
        NoProjCount=NoProjCount+1
    else:
        print File + " is projected " + str(SR.name)


text:
Q: Cloud Foundry switch-space' is not a registered command I'm trying to run the command cf switch-space to switch between my Cloud Foundry accounts. Any suggestion why I have this issue ?
cf switch-space
'switch-space' is not a registered command. See 'cf help -a'

INFO
$ cf -v
cf version 6.32.0+0191c33d9.2017-09-26

A: Assuming that you want to do this within the same Org ,you can switch beetween spaces like this
cf t -s <the-name-of-your-space>
or login again to a different space
cf login -a <endpoint> -u <user> -o <org> -s <space>

A: Because it's not a stock cf cli command. If you want to switch to a new org and space on the same foundation, use cf target.
If you want to save authentication and targets for multiple targets, I suggest using the targets plugin, found here: https://github.com/guidowb/cf-targets-plugin. It's also listed on https://plugins.cloudfoundry.org. Just search for Targets.


text:
Q: How to call enum functions? I have a following problem. I'm trying to implement a HashMap in java, but it has to be done on professor's terms. He wrote an outline of methods, and how they should look, so I can't change anything else beside write add(key, value) function from scratch.
public static enum HashingMethod {
        DivisionMethod,
        KnuthMethod
    };

DivisionMethod and KnuthMethod are both functions for hashing in a HashFunction class.
If somebody were to use this program, he would first create an instance of a HashMap class:
HashMap hm = new HashMap(6, HashFunction.HashingMethod.DivisionMethod);
and then use hm.add(3, "Ambulance") to add elements to it.
Here is the constructor for HashMap:
public HashMap(int m, HashFunction.HashingMethod h) {
        this.h = h;
        this.table = new LinkedList[m];
        for (int i=0; i<table.length; i++) {
            table[i] = new LinkedList<Element>();
        }
    }

What I would like to know is probably basic, but it's been keeping me from progressing for quite some time now.
How do I know which hashing function has been selected, so I can use it in my add(key, value) method?

A: I would add an abstract method to the enum so there is no need of if or switch:
public static enum HashingMethod {
    DivisionMethod {
        @Override
        public int calcHash(Object o) {
            // do it
        }
    },
    KnuthMethod {
        @Override
        public int calcHash(Object o) {
            // do it
        }
    };

    public abstract int calcHash(Object o);
}

So you can invoke the enum-method directly
int bucket = this.h.calcHash(e);

A: You can simply switch over it:
switch(this.h) {
    case DivisionMethod: /*code*/; break;
    case KnuthMethod: /*code*/; break;
}

A: You seem to be storing the HashingMethod in a field called h.
To check the method selected do:
if (h == HashFunction.HashingMethod.DivisionMethod) {

    // use division method

}

etc.


text:
Q: Objective-C appDelegate array I'm creating a SQLite application, with two simple views. I have two arrays in SQLAppDelegate:
- (void)applicationDidFinishLaunching:(UIApplication *)application {

    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    self.modelArray = tempArray;
    self.detailArray = tempArray;
    [tempArray release];

So now in my implementation file I am populating "modelArray" with the contents of a SQLite table and displaying this in the first view:
+ (void) getInitialDataToDisplay:(NSString *)dbPath {

    SQLAppDelegate *appDelegate = (SQLAppDelegate *)[[UIApplication sharedApplication] delegate];

    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

        const char *sql = "select rowid as ID, ManufacturerMake as modelName from sqlitedb group by modelName";
        sqlite3_stmt *selectstmt;
        if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) {

            while(sqlite3_step(selectstmt) == SQLITE_ROW) {

                NSInteger primaryKey = sqlite3_column_int(selectstmt, 0);
                Model *modelObj = [[Model alloc] initWithPrimaryKey:primaryKey];
                modelObj.modelName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];

                [appDelegate.modelArray addObject:modelObj];
                [modelObj release];
            }

        }
    }

The problem is that modelArray is being populated correctly with 114 rows, but if I do a count of detailArray after the above while statement this is also returning 114? Even though I'm not touching detailArray in the above code?

A: self.modelArray = tempArray;
self.detailArray = tempArray;

Here both your instance variable arrays contain pointer to the same NSMutableArray instance (assuming that your property has retain attribute), so changes to the one of the iVars are also applied to another one (as they point to the same object).
To fix that initialize your arrays with different NSMutableArray's:
- (void)applicationDidFinishLaunching:(UIApplication *)application {
    self.modelArray = [NSMutableArray array];
    self.detailArray = [NSMutableArray array];
    ...

A: Your assigning the same NSMutableArray object to the two different variables.
What you want is to create 2 temp arrays and use them.

A: What really happens is that you create an actual array in the first line, but in the next two you make modelArray and detailArray point to the same real in-memory array you created before. Thus, whenever you modify the first one, the second one is still pointing there and is not a separate copy.


text:
Q: Notepad++ RegEx: Search two words in subsequent lines Consider the following text
-- 1.3.6.1.4.1.16213.2.3.1.2
    xfsCDMStatusTable OBJECT-TYPE
        SYNTAX SEQUENCE OF XfsCDMStatusEntry
        MAX-ACCESS not-accessible
        STATUS current
        DESCRIPTION
            "Define the set of MIB Variables for the CDM status table."
        ::= { xfsCDMV1 2 }

    -- 1.3.6.1.4.1.16213.2.3.1.2.1
    xfsCDMStatusEntry OBJECT-TYPE
        SYNTAX XfsCDMStatusEntry
        MAX-ACCESS not-accessible
        STATUS current

Need to filter lines which contains "1.3.6.1.4.1.16213" in first line and "OBJECT-TYPE" in next line.
Output like
 -- 1.3.6.1.4.1.16213.2.3.1.2
    xfsCDMStatusTable OBJECT-TYPE
 -- 1.3.6.1.4.1.16213.2.3.1.2.1
    xfsCDMStatusEntry OBJECT-TYPE

Can someone help with Regex pattern.

A: Try this expression:
(?-s)^(?:(?:(?!.*?\R+.*?\bOBJECT-TYPE\b).*?$(?:\R+|$))|(^.*?\R+.*?\bOBJECT-TYPE\b.*?$))

Replace with $1
It will take an input like this:
-- 1.3.6.1.4.1.16213.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
    SYNTAX SEQUENCE OF XfsCDMStatusEntry
    MAX-ACCESS not-accessible
    STATUS current
    DESCRIPTION
        "Define the set of MIB Variables for the CDM status table."
    ::= { xfsCDMV1 2 }

-- 1.3.6.1.4.1.16213.2.3.1.2.1
xfsCDMStatusEntry OBJECT-TYPE
    SYNTAX XfsCDMStatusEntry
    MAX-ACCESS not-accessible
    STATUS current

-- 1.3.6.1.4.1.16213.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
    SYNTAX SEQUENCE OF XfsCDMStatusEntry
    MAX-ACCESS not-accessible
    STATUS current
    DESCRIPTION
        "Define the set of MIB Variables for the CDM status table."
    ::= { xfsCDMV1 2 }

and output the following:
-- 1.3.6.1.4.1.16213.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
-- 1.3.6.1.4.1.16213.2.3.1.2.1
xfsCDMStatusEntry OBJECT-TYPE
-- 1.3.6.1.4.1.16213.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE

If you'd like to only specify the lines that have the value 1.3.6.1.4.1.16213 then use the following:
(?-s)^(?:(?:(?!.*?1\.3\.6\.1\.4\.1\.16213.*?\R+.*?\bOBJECT-TYPE\b).*?$(?:\R+|$))|(^.*?\R+.*?\bOBJECT-TYPE\b.*?$))

A: Use this:

*

*Find what: (\-\- 1\.3\.6\.1\.4\.1\.16213\b[^\r\n]*[\r\n]+[^\r\n]*OBJECT-TYPE[^\r\n]*)([\r\n]+ [^\r\n]*)*[\r\n]*

*Replace with: $1\n

*"Regular expression" checked

*". matches newline" unchecked

Content example:
-- 1.3.6.1.4.1.16213.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
    SYNTAX SEQUENCE OF XfsCDMStatusEntry
    MAX-ACCESS not-accessible
    STATUS current
    DESCRIPTION
        "Define the set of MIB Variables for the CDM status table."
    ::= { xfsCDMV1 2 }

-- 1.3.6.1.4.1.16213.2.3.1.2.1
xfsCDMStatusEntry OBJECT-TYPE
    SYNTAX XfsCDMStatusEntry
    MAX-ACCESS not-accessible
    STATUS current

-- 1.3.6.1.4.1.16213.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
    SYNTAX SEQUENCE OF XfsCDMStatusEntry
    MAX-ACCESS not-accessible
    STATUS current
    DESCRIPTION
        "Define the set of MIB Variables for the CDM status table."
    ::= { xfsCDMV1 2 }

-- 1.3.6.1.4.1.xxxxx.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
    SYNTAX SEQUENCE OF XfsCDMStatusEntry
    MAX-ACCESS not-accessible
    STATUS current
    DESCRIPTION
        "Define the set of MIB Variables for the CDM status table."
    ::= { xfsCDMV1 2 }

After [Replace All]:
-- 1.3.6.1.4.1.16213.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
-- 1.3.6.1.4.1.16213.2.3.1.2.1
xfsCDMStatusEntry OBJECT-TYPE
-- 1.3.6.1.4.1.16213.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
-- 1.3.6.1.4.1.xxxxx.2.3.1.2
xfsCDMStatusTable OBJECT-TYPE
    SYNTAX SEQUENCE OF XfsCDMStatusEntry
    MAX-ACCESS not-accessible
    STATUS current
    DESCRIPTION
        "Define the set of MIB Variables for the CDM status table."
    ::= { xfsCDMV1 2 }


text:
Q: "Login failed for user" as "The underlying provider failed on Open" in Azure SQL I am trying to build a small Web API that uses an Azure SQL Database. The database functionality is exposed via Stored Procedures and in order to call them, I am using Entity Framework for .NET, version 6.4.4 as it gives me access to the .edmx Data Model. I have properly configured the EF so that I can see the SPs and I've added one of them to my model. In my controller, I execute this piece of code:
var dbContext = new MyDbContext();
var result = dbContext.MyStoredProc();

I get an exception when the "MyStoredProc()" method gets called. The exception that is thrown is this:

For now, the connection string is configured to use SQL Authentication, so the user listed in the exception is the user that is configured in the connection string.
I can call the same SP no problems if I use SQL Server Management Studio, within a session open with the same user name and password as I have configured in the connection string.
Why is my application throwing up that exception? Are there specific privileges that I must elevate, in order for the connection to the database to be opened from my Web API?
Any help would be appreciated.
Cheers,
Eddie

A: In projects that use Entity Framework, an error message usually reports that there is no Login failed for user. At this time, we need to check connectionStrings in ʻApp.config`.
In order to help more forum users, it is recommended that everyone can refer to the following tutorial.
Entity Framework Tutorial


text:
Q: Does adding label to adsense auto ads violate policy? Google auto ads uses a class .google-auto-placed for every auto ad generated. If I add a label to those using a CSS style like the one shown below, does that violate the TOS?
 .google-auto-placed::before {
content: "Advertisements";
}

A: This is not a violation, I had this implementation for several months & had no issues with Adsense at all.
Adsense also permit labeling Ads with Advertisement or Sponsored Links.


text:
Q: Autorun "git bisect start" if it was not run already git bisect bad

gives me
You need to start by "git bisect start"

Do you want me to do it for you [Y/n]?

Obviously, I select yes. But can I skip automatically this pointless question and always just let it start bisecting?


text:
Q: Winsock recv() returning incorrect data My server recv() the packet from the client and must display it.
Problem is its not displaying the correct data
Here is the code:
    iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        for ( int i = 0; i < iResult; i++ ) {
            printf( "%02x ", buf[i] );
        }
        printf( "\n" );

    // return "cc cc cc cc cc cc cc cc cc cc"
    // correct return "0A 00 2C 01 29 00 0D 00 B4 01"

When a client connects the server displays cc cc cc cc cc cc cc cc cc cc but that's not right
It should be 0A 00 2C 01 29 00 0D 00 B4 01

UPDATE
    #define DEFAULT_BUFLEN 512

    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen = DEFAULT_BUFLEN;

    iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
    if (iResult > 0) {
        for ( int i = 0; i < iResult; i++ ) {
            printf( "%02x ", recvbuf[i] );
        }
        printf( "\n" );

    // return "0A 00 2C 01 23 00 0c 00 ffffffB3 01"
    // correct return "0A 00 2C 01 23 00 0c 00 B3 01"

now there are extra ffffff on the packet, even though i'm only recv 10 bytes.

A: The data is correct now.  What you're seeing is sign extension when the char value you're passing to printf is promoted to an int.  You can cast the char to an unsigned char and it should display properly.
for ( int i = 0; i < iResult; i++ ) {
    printf( "%02x ", static_cast<unsigned char>( recvbuf[i] ) );
}


text:
Q: Polite alternative for "Is there any reason why we still haven't done this yet.?" Is there any reason why we still haven't done this yet.?

I feel it's not very polite to ask like this. I am not sure. Is there a more polite way of aking this?

A: It's not rude or impolite. It could only be taken as impolite if there is a context in which it could be understood to be blaming someone for not "doing it yet", and if that blame is inappropriate.
If you are planning, asking "why wasn't it done in the past" may not be useful. You can make it more useful by focusing on the present and future:

Is there any reason for us not to do this?

You can make it more tentative by rephrasing as a statement:

I can't think of any reason not to do this.

Or a proposal

If nobody has an objection, I suggest we do this.


text:
Q: How do I view the contents of my "default" type Cloud SQL database in AppMaker? I created a new AppMaker app and selected the "default" (as opposed to "custom") Cloud SQL database backend.
While I'm prototyping my app, I'd like to be able to inspect the contents of my database periodically as an admin to debug issues. With a custom Cloud SQL database this is easy because you can acess a custom Cloud SQL database from the cloud console, but I don't see how to manually query a default Cloud SQL database.
I know that I can export my database to a Google Sheet, but that's inconvenient to do frequently.
How do I inspect the contents of my AppMaker default Cloud SQL database for debugging (eg. via a SQL command line, UI tool, etc)?

A: I believe it would be the same as with the custom one. The documentation explains:

A G Suite administrator can set up a Google Cloud SQL instance that is shared among App Maker apps in an organization. When this is enabled, a new database is automatically created for your app when you add at least one Cloud SQL data model. Choose this option if your app needs a database that is easy to use and requires no set up.

This means that you had set up correctly the instance information in the G Suite Admin console:

So to connect to your SQL instance, you just need to follow the instructions here. Then simply use the instance connection name where required. You will also need the database name and you can get that from the appsettings or deployment settings in appmaker.
For the preview mode it will be in the app settings. For any deployed version, it will be in the deployment settings:


text:
Q: How can I reduce the trigger area for my drop-down navigation? My drop-down menu on this page: http://newdawnts.org/ is triggering when the user hovers over the slideshow (non-displayed list items). How can I change the code so that so that the sub-menu is only triggered when the user hovers over only the main menu navigation items.

A: This happens to fix the problem on my browser. Can you check if it's solving your problem. You dropdown menu has visibility: visible applied to it. You need to change that to hidden.
#cssmenu > ul > li > ul {
    visibility: hidden;
}


text:
Q: Ember.js: How to represent a has-many model relationship? I am trying to set up an ember app where I have many Items, all of which have many Options.  I then need a 'dashboard' area where I can monitor information on all Items/Options.
In a previous post I got a working example of a dashboard which monitors a single collection of Items.
How do I update this to represent child Options for each Item?
Javascript - from jsBin (updated)
App = Ember.Application.create();

/* ROUTES */
App.Router.map(function() {
  this.resource('items');
  this.resource('dashboard');
});
App.IndexRoute = Ember.Route.extend({
  redirect: function() {
    this.transitionTo('items');
  }
});
App.ItemsRoute = Ember.Route.extend({
  model: function() {
    var a = Em.A();
    a.pushObject( App.Items.create({title: 'A', cost: '100'}));
    a.pushObject( App.Items.create({title: 'B', cost: '200'}));
    a.pushObject( App.Items.create({title: 'C', cost: '300'}));
    return a;
  }
});

/* MODELS */
App.Items = Ember.Object.extend({
  title: '',
  cost: '',
  quantity: ''
});

/* CONTROLLERS */
App.ItemsController = Ember.ArrayController.extend({
  legend: 'test',
  len: function(){
    return this.get('length');
  }.property('length'),
  totalCost: function() {
    return this.reduce( function(prevCost, cost){
      return parseInt(cost.get('cost'),10) + (prevCost || 0);
    });
  }.property('@each.cost')
});
App.DashboardController = Em.Controller.extend({
  needs: ['items'],
  itemsLength: Ember.computed.alias('controllers.items.len'),
  itemsTotalCost: Ember.computed.alias('controllers.items.totalCost')
});

Handlebars

A: Upfront, I would recommend using a clientside record management framework like ember data/ember model, they are a bit of a learning curve, but very awesome in the long run.  If you don't want to do that, you can follow the same pattern you've already established with creating models.
http://jsbin.com/IpEfOwA/3/edit


text:
Q: Laravel Eloquent Query to return count of grouped objects I am working with laravel 5.1 and can't get this query to work. I have a places table, with a column county. I want to group by county and count how many of each country are in the table. I have a Place model for the places table but cannot figure out the query builder for this one.
A query that works is:
select county, count(*) from places group by county
Thanks in advance.

A: Just from the top of my head does something like this work:
User::where('county')->count();

A: You may try this (Add a use statement for DB or use \DB):
  $result = DB::table('places')
  ->select('county', DB::raw('count(*) as total'))
  ->groupBy('county')
  ->get();


text:
Q: Minimizing absolute differences between n values under constraints on sums of these values I have 15 unknown integer values $x_i$. I know that: $$\sum_{i=1}^5 x_i = 25 $$, $$\sum_{i=6}^{10} x_i = 32 $$ and $$\sum_{i=11}^{15} x_i = 41 $$
I wish to identify 15 integer $x_i$ that minimize $$\sum_{i=1}^{14} |x_{i+1} - x_i|$$ under these constraints. Is it possible? How should I proceed?
Thank you very much for your help

A: We can show that $\sum_{i=1}^{14}|x_{i+1}-x_i|\geq |x_k-x_j|$ for any $j,k.$ It is trivially true if $j=k$. If $j<k$ then:
$$\sum_{i=1}^{14} |x_{i+1}-x_i|\geq\sum_{i=j}^{k-1} |x_{i+1}-x_i|\geq \left|\sum_{i=j}^{k-1} x_{i+1}-x_i\right|=|x_k-x_j|$$
If $j>k$ just reverse them.
Now, one of $x_{11},\dots,x_{15}$ must be at least $9$. And one of $x_{1},\dots,x_{5}$ must be at most $5$. So the we get that:
$$\sum_{i=1}^{14}|x_{i+1}-x_i|\geq 4.$$
We can easily reach this minimum with $$(x_i)=(5,5,5,5,5,\quad6,6,6,7,7,\quad,8,8,8,8,9).$$
There's a more general rule than the above:

Lemma: If $(x_i)_{i=1}^{N}$ is a sequence then:
  $$\sum_{i=1}^{N-1} |x_{i+1}-x_i|\geq \sum_{j=1}^{M-1} |y_{j+1}-y_{j}|$$ for any subsequence $(y_j)_{j=1}^{M}$ of $(x_i)$.

This more general result would be useful if you wanted $$x_1+\cdots+x_5=25\\ x_6+\cdots+x_{10}=41\\x_{11}+\cdots+{x_{15}}=32.$$
Then you'd know you had a subsequence $y_1,y_2,y_3$ such that $y_1\leq 5, y_2\geq 9,y_3\leq 6,$ so this lemma means that the we have:
$$\sum |x_{i+1}-x_{i}|\geq |5-9|+|9-6|=7$$
and we can get that value with $(5,5,5,5,5,\,8,8,8,8,9,\,7,7,6,6,6)$.

The general rule for generating a solution is, for each block, determine the average. If the average is an integer, we set each of the $x_i$ to that average. If the average in the block is not an integer, we can write the average as $m+\frac{k}{B}$ where $B$ is the size of the block, $m$ is and integer, and $1\leq k <B$. Then we can choose $k$ of the values as $m+1$ and $B-k$ values as $m$.
The only tricky part is when, for two blocks consecutive, if you have non-integers averages and the $m$ values are the same. Then which order you place the $x_i$ is dependent on the blocks around you.
For example, if you want: $$x_1+x_2+x_3=8\\x_{4}+x_{5}+x_{6}=7\\x_{7}+x_{8}+x_{9}=5$$
In this case, which order to put the $x_1,\dots,x_6$ is determined by the value if $5$ of the next block, so you have:
$$(x_i)=(2,3,3,\quad 3,2,2,\quad 2,2,1)$$
But if you wanted $x_{7}+x_{8}+x_{9}=10$ the you'd have:
$$(x_i)=(3,3,2,\quad 2,2,3,\quad 3,3,4)$$


text:
Q: Where can PTHRED_MUTEX_ADAPTIVE_NP be specified and how does it work? I found that there's a macro called PTHRED_MUTEX_ADAPTIVE_NP which is somehow given as a value to a mutex so that the mutex does an adaptive spinning, meaning that it spins in the magnitude of an immediate wakeup through the kernel would last. But how do I utilize this configuration-macro to a thread ?
And as I've developed an improved shared readers-writer lock (it needs only one atomic operation at best in contrast to the three operations given in the Wikipedia-solution) with relative writer-priority (further readers are stalled when there's a writer and the readers before are allowed to proceed) which could also make use of adaptive spinning: how is the number of spinning-cycles calculated ?

A:
I found that there's a macro called PTHRED_MUTEX_ADAPTIVE_NP

Some pthreads implementations provide a macro PTHREAD_MUTEX_ADAPTIVE_NP (note spelling) that is one of the possible values of the kind_np mutex attribute, but neither that attribute nor the macro are standard.  It looks like at least BSD and AIX have them, or at least did at one time, but this is not something you should be using in new code.

But how do I utilize this configuration-macro to a thread ?

You don't.  Even if you are using a pthreads implementation that supports it, this is the value of a mutex attribute, not a thread attribute.  You obtain a mutex with that attribute value by explicitly requesting it when you initialize the mutex.  It would look something like this:
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
int rval;

// Return-value checks omitted for brevity and clarity
rval = pthread_mutexattr_init(&attr);
rval = pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_ADAPTIVE_NP);
rval = pthread_mutex_init(&mutex, &attr);

There are other mutex attributes that you can set in analogous ways, which is one of the reasons I wrote this answer.  Although you should not be using the kind_np attribute, you can follow this general model for other mutex attributes.  There are also thread attributes, which work similarly.

A: I found the code in the glibc:
That's the "adaptive" mutex locking code of pthread_mutex_lock
in the glibc 2.31:
   else if (__builtin_expect (PTHREAD_MUTEX_TYPE (mutex)
              == PTHREAD_MUTEX_ADAPTIVE_NP, 1))
    {
      if (! __is_smp)
    goto simple;

      if (LLL_MUTEX_TRYLOCK (mutex) != 0)
    {
      int cnt = 0;
      int max_cnt = MIN (max_adaptive_count (),
                 mutex->__data.__spins * 2 + 10);
      do
        {
          if (cnt++ >= max_cnt)
        {
          LLL_MUTEX_LOCK (mutex);
          break;
        }
          atomic_spin_nop ();
        }
      while (LLL_MUTEX_TRYLOCK (mutex) != 0);

      mutex->__data.__spins += (cnt - mutex->__data.__spins) / 8;
    }
      assert (mutex->__data.__owner == 0);
    }

So the spin count is doubled up to a maximum plus 10 first (system configurable or 1000 if thre's no configuration) and after the locking the difference between the actual spins and the predefined spins divided by 8 is added to the next spin-count.


text:
Q: Cannot instantiate OpenCV-4.0.1 CascadeClassifier in a Grails 2.4.4 Project I want to crop 1x1 employee pictures from their upload file to be set as their avatar on my Grails application. I heard OpenCV do the job well so I used it inside my ImageService. The problem is it seems that it cannot find (or read) the CascadeClassifier XML file it needs:
class ImageService {
    final String FRONTAL_FACE_XML = "D:\\Devtools\\opencv\\build\\etc\\lbpcascades\\lbpcascade_frontalface_improved.xml"
    final String ORIGINAL_PICTURE = "D:\\Projects\\opencv\\grails-app\\assets\\4fc30smaegvq0z3mvgm9yhf6vtv9kv8bgryi9x08wuada8jxu3.jpg"
    final String CROPPED_PICTURE = "D:\\Projects\\opencv\\grails-app\\assets\\4fc30smaegvq0z3mvgm9yhf6vtv9kv8bgryi9x08wuada8jxu3_100.jpg"

    void opencvtest() {
        // Before I placed the OpenCV dll in the environment path, this line causes an error.
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME)

        // UnsatisfiedLinkError here
        CascadeClassifier faceDetector = new CascadeClassifier(this.getClass().getResource("lbpcascade_frontalface_improved.xml").getPath());

        // Same error as well.
        // File cascadeFile = new File(FRONTAL_FACE_XML);
        // CascadeClassifier faceDetector = new CascadeClassifier(cascadeFile.getAbsolutePath());

        // And also here.
        // CascadeClassifier faceDetector = new CascadeClassifier(FRONTAL_FACE_XML);

        Mat image = HighGui.imread(ORIGINAL_PICTURE)
        faceDetector.detectMultiScale(image, face_Detections)

        Rect rect_Crop = null

        for (Rect rect : face_Detections.toArray()) {
            Core.rectangle(image, new Point(rect.x, rect.y), new Point(rect.x + rect.width, rect.y + rect.height), new Scalar(0, 255, 0))
            rectCrop = new Rect(rect.x, rect.y, rect.width, rect.height)
        }

        Mat image_roi = new Mat(image, rectCrop)
        HighGui.imwrite(CROPPED_PICTURE, image_roi)

        return
    }
}

And causes the following error:

java.lang.UnsatisfiedLinkError
  org.opencv.objdetect.CascadeClassifier.CascadeClassifier_0(Ljava/lang/String;)J

Environment: Windows 7, Java 1.8, Grails 2.4.4
Things I have done:

*

*I have installed OpenCV 4.0.1 from their website: https://opencv.org/releases.html and unpack their distribution on D:\opencv\4.0.1.

*I have included this on my environment path: D:\opencv\4.0.1\build\java\x64

*Since I cannot find an official Maven dependency link, I copied the jar I found on D:\opencv\4.0.1\build\java into my grails lib directory.

*I already tried copying all the dll and xml to C:\Windows\system32.

*Thinking that the jar on the distribution might be "faulty", I replace it with this package compile "org.bytedeco.javacpp-presets:opencv:4.0.1-1.4.4" on through BuildConfig.groovy, still both cause errors on the same line.

*I verified whether FRONTAL_FACE_XML and ORIGINAL_PICTURE are both correct file path, and they are.

A: We will be using OpenCV using VC15 on Windows for this example. I have yet to learn how to port this on Linux.
Legend:
APPLICATION_PATH = D:\application
JAVA_DLL_PATH = D:\opencv\4.0.1\build\java\x64
VC_DLL_PATH = D:\opencv\4.0.1\build\x64\vc15\bin

Optional:

*

*Go to %VC_DLL_PATH% directory.

*Create a directory named debug (or whatever you prefer) and move all *d.dll files there. These files that ends with *d.dll might cause an error when you run them since it is looking for vc15 debug dlls that are not part of the basic Visual C++ 2015.

Configuration:

*

*Create a directory in %APPLICATION_PATH%\src directory named files (or whichever you prefer). It should be similar to this.

%APPLICATION_PATH%
  ├── bin\
  ├── grails-app\
  ├── lib\
  ├── ...
  ├── src\
  │   ├── groovy\
  │   ├── java\
  │   └── files\ --new directory
  └── ...

*Copy all *.dlls from %JAVA_DLL_PATH% and %VC_DLL_PATH% directories to the newly created directory %APPLICATION_PATH%\src\files.

*Include the newly created directory to your .classpath file.

<?xml version="1.0" encoding="UTF-8"?>
  <classpath>
      <classpathentry excluding="spring/" kind="src" path="grails-app/conf"/>
      ...
      <classpathentry kind="src" path="src/files"/>
      ...
  </classpath>

*Create another directory in your %APPLICATION_PATH% named files (or whichever you prefer).

%APPLICATION_PATH%
  ├── bin\
  ├── grails-app\
  ├── files\ --new directory
  └── ...

*Copy here the CascadeClassifiers xml files that you will use. They are found in \opencv\4.0.1\build\etc directory.

*Even after copying the dlls inside %APPLICATION_PATH%, we still need to include them on the system path. Edit your environment variables and include %JAVA_DLL_PATH% and %VC_DLL_PATH% directories to PATH.

*Also, even if we copied the dlls and included the library directories into the system path, we still need to include it to the Tomcat JVM library path. Open your BuildConfig.groovy and add this:

grails.tomcat.jvmArgs = ["-Djava.library.path=D:\opencv\4.0.1\build\x64\vc15\bin;D:\opencv\4.0.1\build\java\x64"]

*Include the directories to your Config.groovy.

openCV {
      cascadeClassifiers = "D:\\application\\files\\opencv"
      home               = "D:\\opencv\\4.0.1\\build\\x64\\vc15\\bin"
      java               = "D:\\opencv\\4.0.1\\build\\java\\x64"
  }

How to use:
You need to create a *.java file instead of a *.groovy file in %APPLICATION_PATH%\src\java. I have yet to check why it doesn't work on .groovy file.
import grails.util.Holders;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.FileUtils;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import org.opencv.core.Rect;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.objdetect.CascadeClassifier;

public class ImageService {
    static final String[] OPENCV_SUPPORTED_EXTENSION = new String[]{"bmp", "dib", "jp2", "jpe", "jpeg", "jpg", "pbm", "pgm", "png", "ppm", "ras", "sr", "tif", "tiff"};

    public static File cropImage(final File originalFile) {
        loadLibrary();
        return cropImage(originalFile, originalFile.getParentFile(), getCascadeClassifiers());
    }

    public static File cropImage(final File originalFile, final ArrayList<CascadeClassifier> cascadeClassifiers) {
        return cropImage(originalFile, originalFile.getParentFile(), cascadeClassifiers);
    }

    public static File cropImage(final File originalFile, final File targetDirectory) {
        loadLibrary();
        return cropImage(originalFile, originalFile.getParentFile(), getCascadeClassifiers());
    }

    public static File cropImage(final File originalFile, final File targetDirectory, final ArrayList<CascadeClassifier> cascadeClassifiers) {
        ArrayList<File> siblingFiles = getFaces(originalFile, cascadeClassifiers);
        File maxFile = null;
        int maxWidth = 0;

        for(int x = 0; x < siblingFiles.size(); x++) {
            Mat image = Imgcodecs.imread(siblingFiles.get(x).getAbsolutePath(), Imgcodecs.IMREAD_UNCHANGED);

            if(image.width() > maxWidth) {
                maxFile = siblingFiles.get(x);
                maxWidth = image.width();
            }
        }

        File croppedFile = null;
        if(maxFile != null) {
            croppedFile = new File(targetDirectory.getAbsolutePath() +
                File.separator +
                originalFile.getName());

            try {
                FileUtils.copyFile(maxFile, croppedFile);
            }
            catch(IOException e) {}
        }

        for(int y = 0; y < siblingFiles.size(); y++) {
            siblingFiles.get(y).delete();
        }

        System.gc();
        System.runFinalization();

        return croppedFile;
    }

    public static ArrayList<CascadeClassifier> getCascadeClassifiers() {
        ArrayList<CascadeClassifier> classifiers = new ArrayList<CascadeClassifier>();

        final String[] cascadeSupportedExtensions = new String[]{"xml"};
        final String cascadeClassifierPath = Holders.getFlatConfig().get("openCV.cascadeClassifiers").toString();
        File cascadeClassifierDirectory = new File(cascadeClassifierPath);
        ArrayList<File> detectors = new ArrayList<File>(FileUtils.listFiles(cascadeClassifierDirectory, cascadeSupportedExtensions, false));

        for(int y = 0; y < detectors.size(); y++) {
            CascadeClassifier faceDetector = new CascadeClassifier();
            faceDetector.load(detectors.get(y).getAbsolutePath());

            classifiers.add(faceDetector);
        }

        return classifiers;
    }

    public static ArrayList<File> getFaces(final File originalFile) {
        loadLibrary();
        return getFaces(originalFile, getCascadeClassifiers());
    }

    public static ArrayList<File> getFaces(final File originalFile, final ArrayList<CascadeClassifier> cascadeClassifiers) {
        File temporaryFile = new File(originalFile.getParentFile().getAbsolutePath() +
            File.separator +
            UUID.randomUUID().toString() +
            "." + FilenameUtils.getExtension(originalFile.getName()));

        try {
            FileUtils.copyFile(originalFile, temporaryFile);
        }
        catch(IOException e) {}

        final int frame = 9;
        final int offset = 8;
        int rotateCounter = 0;

        Integer marginX, marginY, marginWidth, marginHeight;
        Integer pxPerOffset, excess;

        ArrayList<File> siblingFiles = new ArrayList<File>();

        while(rotateCounter < 4) {
            if(rotateCounter > 0) {
                Mat image = Imgcodecs.imread(temporaryFile.getAbsolutePath(), Imgcodecs.IMREAD_UNCHANGED);

                Core.transpose(image, image);
                Core.flip(image, image, 1);

                Imgcodecs.imwrite(temporaryFile.getAbsolutePath(), image);

                image.release();
            }

            for(int y = 0; y < cascadeClassifiers.size(); y++) {
                CascadeClassifier faceDetector = cascadeClassifiers.get(y);
                Mat image = Imgcodecs.imread(temporaryFile.getAbsolutePath(), Imgcodecs.IMREAD_UNCHANGED);

                MatOfRect faceDetections = new MatOfRect();
                faceDetector.detectMultiScale(image, faceDetections);

                Rect defaultRect = null;
                Rect marginRect = null;
                Rect[] facesRect = faceDetections.toArray();

                for(int z = 0; z < facesRect.length; z++) {
                    defaultRect = facesRect[z];
                    pxPerOffset = defaultRect.width / frame;

                    marginX = defaultRect.x - (pxPerOffset * offset);
                    marginY = defaultRect.y - (pxPerOffset * offset);

                    marginWidth = defaultRect.width + (offset * pxPerOffset * 2);
                    marginHeight = defaultRect.height + (offset * pxPerOffset * 2);

                    excess = Math.max(
                        0 - marginX,
                            Math.max(0 - marginY,
                                Math.max(marginX + marginWidth - image.width(),
                                    Math.max(marginY + marginHeight - image.height(), 0)))
                    );

                    if(excess > 0) {
                        marginX += excess;
                        marginY += excess;

                        marginWidth -= excess * 2;
                        marginHeight -= excess * 2;
                    }

                    marginRect = new Rect(marginX, marginY, marginWidth, marginHeight);
                    Mat imageWithMargin = new Mat(image, marginRect);

                    String croppedFileName = temporaryFile.getParentFile().getAbsolutePath() +
                        File.separator +
                        UUID.randomUUID().toString() + "_" +
                        y + "_" +
                        rotateCounter + "_" +
                        z + "." +
                        FilenameUtils.getExtension(temporaryFile.getName());

                    Imgcodecs.imwrite(croppedFileName, imageWithMargin);

                    siblingFiles.add(new File(croppedFileName));

                    imageWithMargin.release();
                }

                image.release();
            }

            rotateCounter++;
        }

        temporaryFile.delete();

        return siblingFiles;
    }

    public static void loadLibrary() {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        final String[] urls = new String[]{
            Holders.getFlatConfig().get("openCV.java").toString(),
            Holders.getFlatConfig().get("openCV.home").toString()
        };

        final String[] validExtensions = new String[]{"dll"};
        ArrayList<File> dlls = new ArrayList<File>();
        for(int y = 0; y < urls.length; y++) {
            dlls.addAll(FileUtils.listFiles(new File(urls[y]), validExtensions, false));
        }

        for(int y = 0; y < dlls.size(); y++) {
            for(int z = 0; z < validExtensions.length; z++) {
                System.loadLibrary(dlls.get(y).getName().replace("." + validExtensions[z], ""));
                System.load(dlls.get(y).getAbsolutePath());
            }
        }
    }
}

Then we use it to our groovy service classes.
class TestService {
    def openCVTest() {
        File picture = new File("D:\\original.jpg");
        File savingDirectory = new File("D:\\");

        ImageService.cropImage(picture, savingDirectory);

        return;
    }
}


text:
Q: Sort new array? I got this array
$arr =('1-1.jpg','1-2.jpg','11-3.jpg', '1-4.jpg', '3-5.jpg', '41-5.jpg','1-3.jpg','4-5.jpg','14-5.jpg','54-5.jpg','64-5.jpg','14-5.jpg', '1-5.jpg');

I need this array
$newarray=('1-1.jpg','1-2.jpg','1-3.jpg', '1-4.jpg', '1-5.jpg');

I got this function
$new =array_filter( $arr, function( $el) {
return substr( $el, 0, 2) == '1-';;
});

But always i got this error:
Parse error: syntax error, unexpected T_FUNCTION


text:
Q: Composite key in Ignite I've created a Ignite table via defining two columns as primary key (PK). When I tried to insert the data its failing with duplicate key error. PK defined on type and id column.
0: jdbc:ignite:thin://node1.example.com> insert into balance (type,amount,currency,asof,id) values ('Current Balance',20000.1,'INR','2020-04-07 00:00:00.000','1009230183926');
1 row affected (0.036 seconds)

0: jdbc:ignite:thin://node1.example.com> insert into balance (type,amount,currency,asof,id) values ('Current Balance',30000,'INR','2020-04-07 00:00:00.000','1009230183926');
Error: Duplicate key during INSERT [key=SQL_PUBLIC_BALANCE_4791140f_63cb_4663_8c02_58f14073ff0c_KEY [idHash=1321771843, hash=-1614321497, TYPE=Current Balance, ID=1009230183926]] (state=23000,code=4001)
java.sql.SQLException: Duplicate key during INSERT [key=SQL_PUBLIC_BALANCE_4791140f_63cb_4663_8c02_58f14073ff0c_KEY [idHash=1321771843, hash=-1614321497, TYPE=Current Balance, ID=1009230183926]]

Does Ignite support composite key like any other RDBMS? How I can resolve this.

A: Composite keys are supported by Ignite, and in this case, it looks to be configured corrected with both type and id included in the key.
The exception is expected as well, as both inserts have the same values for type and id columns (Current Balance and 1009230183926 respectively).


text:
Q: npm start gives an error and doesn't start I get an error when running npm start. It was working fine and then suddenly it started doing this. I have rebooted to make sure there are no hanging processes. I did a npm cache verify. Here is the log it provides.
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'start'
1 verbose cli ]
2 info using npm@6.12.0
3 info using node@v12.13.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle electron-quick-start@1.0.0~prestart: electron-quick-start@1.0.0
6 info lifecycle electron-quick-start@1.0.0~start: electron-quick-start@1.0.0
7 verbose lifecycle electron-quick-start@1.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle electron-quick-start@1.0.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\dillon_vance\git\backup-restore\node_modules\.bin;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\1E\NomadBranch\;C:\Program Files\Dell\Dell Data Protection\Encryption\;C:\PSTools\;C:\Program Files\nodejs\;C:\Program Files\Git\cmd;C:\Users\dillon_vance\AppData\Local\Microsoft\WindowsApps;;C:\Users\dillon_vance\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\dillon_vance\AppData\Roaming\npm
9 verbose lifecycle electron-quick-start@1.0.0~start: CWD: C:\Users\dillon_vance\git\backup-restore
10 silly lifecycle electron-quick-start@1.0.0~start: Args: [ '/d /s /c', 'electron .' ]
11 silly lifecycle electron-quick-start@1.0.0~start: Returned: code: 2147483651  signal: null
12 info lifecycle electron-quick-start@1.0.0~start: Failed to exec start script
13 verbose stack Error: electron-quick-start@1.0.0 start: `electron .`
13 verbose stack Exit status 2147483651
13 verbose stack     at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:210:5)
13 verbose stack     at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:210:5)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
14 verbose pkgid electron-quick-start@1.0.0
15 verbose cwd C:\Users\dillon_vance\git\backup-restore
16 verbose Windows_NT 10.0.17763
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v12.13.0
19 verbose npm  v6.12.0
20 error code ELIFECYCLE
21 error errno 2147483651
22 error electron-quick-start@1.0.0 start: `electron .`
22 error Exit status 2147483651
23 error Failed at the electron-quick-start@1.0.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 2147483651, true ]

I don't have anymore ideas. I googled the error code, but didn't find a solution for my issue. Any help would be much appreciated.


text:
Q: Detectar codificacion de txt Buen dia, he buscado la forma de obtener mediante una aplicacion de C# la codificacion de un archivo de texto plano pero no he podido encontrar algo concreto ¿alguno sabe como realizar lo que busco?

A: Podes usar un StreamReader para detectar la codificación de un archivo de texto leyendo su propiedad CurrentEncoding.
Según la documentación, la detección automática de la codificación se realizará cuando llames a la función Read. Así que es necesario llamarla antes de leer la propiedad CurrentEnconding.
Según esta respuesta, también es válido usar la función Peek.


text:
Q: savehistory command doesn't work in R 4.02 I tried using the command savehistory() in R version 4.02 on MacOS. It did gave an error:
savehistory()

Error in .External2(C_savehistory, file): 'savehistory' is not currently implemented

savehistory is a standard R command that is cited in all R manuals.
Anyone know what's happening here?

A: Look at R for Mac OS X FAQ. Mac OS has never supported savehistory. If you are using the R Console, the "History" icon on the top bar pops out a drawer on the left side of the window displaying your history. Note the buttons at the bottom:


text:
Q: For any integer n greater than 1, $4^n+n^4$ is never a prime number. For any integer n greater than 1, show that $4^n+n^4$ is never a prime number.
My approach: I tried to use mathematical induction. But somehow couldn't manage to prove it. Is it to be done by induction or can it be done by another method?

A: This is a nice identity. Try to complete the square: $4^n+n^4=(2^n)^2+(n^2)^2=(2^n+n^2)^2-2\cdot2^n\cdot n^2$.
Now, clearly we may assume that $n$ is odd, else the sum is even and larger than $2$. But if $n$ is odd, then $2\cdot 2^n$ is itself a square, and we can continue: Say $n=2k-1$, then $(2^n+n^2)^2-2\cdot2^n\cdot n^2=(2^n+n^2-2^kn)(2^n+n^2+2^kn)$.
Finally, one just needs to check that neither term in this product is $1$. This is clear for the second term. As for the first, note that $2^n+n^2-2^kn=2^k(2^{k-1}-2k+1)+n^2$, and $2^{k-1}-2k+1\ge0$ if $2^{k-1}+1\ge 2k$, which holds for $k\ge 4$ (as one easily verifies by induction). The remaining cases $k=2,3$ can be checked directly by hand. (Note that $k=1$ corresponds to $n=1$, and $4^1+1^4=5$ is prime.)

A: $4^n + n^4 = (2^n)^2 + (n^2)^2 = (2^n + n^2)^2 - (2^{\frac{n+1}{2}}\cdot n)^2$. From this we use: $A^2 - B^2 = (A - B)(A + B)$ to factor the last expression and this shows it is composite when $n$ is odd. If $n$ is even it is clearly composite.

A: Hint $ $ If $\,n\,$ is odd then  $\,\color{#c00}{n\!+\!1 = 2k}.\,$ Completing the square yields a difference of squares
$\ \ \ \begin{eqnarray} \overbrace{n^{\large 4}\!+ 2^{\large 2n}}^{{\rm incomplete\ \large \Box}}\!\! &\,=\,& \overbrace{(n^{\large 2}\!+2^{\large \color{#c00}n})^{\large 2}}^{{\rm completed\ \large \Box}}\!-(n2^{\large\color{#c00}k})^{\large\color{#c00} 2}\ \ \text{so, factoring this} \textit{ difference of squares}\\[.4em]
 &\,=\,& (n^{\large 2}\!+2^{\large n}\color{}{\ \,-\,\ n2^{\large k}})\:(n^{\large 2}\!+2^{\large n}\,+\ \color{}{n2^{\large k}})\\
 \end{eqnarray}$
Note $ $ Generally $\ 2ab = c^2\,\Rightarrow\, a^2\!+b^2 = (a\!+\!b)^2\!-c^2 = (a\!+\!b\!-\!c)(a\!+\!b\!+\!c)$
For further examples and generaizations see this answer.


text:
Q: Maximum repeated String in an array The problem is

how to get the maximum repeated String in an array using only operations on the arrays in java?

so i got into this question in a test and couldn't figure it out.
lets suppose we have an array of string.
str1[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey" }
str2[] = { "abbey", "bob", "caley", "caley", "zeeman", "abbey", "bob", "abbey", "caley" }

*

*in  str1 abbey was maximum repeated, so abbey should be returned and

*in str2 abbey and caley both have same number of repetitions and hence we take maximum alphabet as the winner and is returned(caley here).
c > a
so i tried till
import java.util.*;
public class test {
    static String highestRepeated(String[] str) {
        int n = str.length, num = 0;
        String temp;
        String str2[] = new String[n / 2];

        for (int k = 0;k < n; k++) {  // outer comparision
            for (int l = k + 1; l < n; l++) { // inner comparision
                if (str[k].equals(str[l])) {
                    // if matched, increase count
                    num++;
                }
            }
             // I'm stuck here
        }

        return result;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("enter how many votes");
        int n = sc.nextInt();
        String[] str = new String[n];
        for (int i = 0; i < n; i++) {
            Str[i] = sc.nextLine();

        }
        String res = highestRepeated(str);
        System.out.println(res + " is the winner");
    }
}

so, how should i take the count of occurrence of each string with and attach it with the string itself.
All this, without using a map and any hashing but just by using arrays?

A: Here is a (unpolished) solution:
static String highestRepeated(String[] str) {
    String[] sorted = Arrays.copyOf(str, str.length);
    Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder());
    String currentString = sorted[0];
    String bestString = sorted[0];
    int maxCount = 1;
    int currentCount = 1;
    for (int i = 1 ; i < sorted.length ; i++) {
        if (currentString.equals(sorted[i])) {
            currentCount++;
        } else {
            if (maxCount < currentCount) {
                maxCount = currentCount;
                bestString = currentString;
            }
            currentString = sorted[i];
            currentCount = 1;
        }
    }
    if (currentCount > maxCount) {
        return currentString;
    }
    return bestString;
}

Explanation:
Sort the array from highest to lowest lexicographically. That's what Arrays.sort(sorted, 0, sorted.length, Comparator.reverseOrder()); does. we sort in this order because you want the largest string if there are multiple strings with the same number of repeats.
Now we can just count the strings by looping through the array. We don't need a hash map or anything because we know that there will be no more of a string in the rest of the array when we encounter a different string.
currentString is the string that we are currently counting the number of repeats of, using currentCount. maxCount is the number of occurrence of the most repeated string - bestString - that we have currently counted.
The if statement is pretty self-explanatory: if it is the same string, count it, otherwise see if the previous string we counted (currentCount) appears more times than the current max.
At the end, I check if the last string being counted is more than max. If the last string in the array happens to be the most repeated one, bestString won't be assigned to it because bestString is only assigned when a different string is encountered.
Note that this algorithm does not handle edge cases like empty arrays or only one element arrays. I'm sure you will figure that out yourself.

A: another version
static String lastMostFrequent(String ... strs) {
    if (strs.length == 0) return null;
    Arrays.sort(strs);
    String str = strs[0];
    for (int longest=0, l=1, i=1; i<strs.length; i++) {
        if (!strs[i-1].equals(strs[i])) { l=1; continue; }
        if (++l < longest) continue;
        longest = l;
        str = strs[i];
    }
    return str;
}

change in
if (++l <= longest) continue;

for firstMostFrequent

A: you can't use == to check if two strings are the same.
try using this instead:
if (str[k].equals(str[l])) {
                // if matched, increase count
                num++;
            }


text:
Q: How to detect switching between users I have a service running in foreground mode and I'd like to detect switching between user sessions on tablets running Android 4.2 or above.
Is there any broadcast receiver I can register to get notified?
I have noticed that Google Music stops the music playback as soon as another user session is chosen on the lock screen. How does it detect the switch?

ANSWER EXPLAINED
Thanks @CommonsWare for the correct answer. I will explain a bit more how to detect a user switch.
First be aware that the documentation explicitly says that receivers must be registered  through Context.registerReceiver. Therefore do something like:
UserSwitchReceiver receiver = new UserSwitchReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction( Intent.ACTION_USER_BACKGROUND );
filter.addAction( Intent.ACTION_USER_FOREGROUND );
registerReceiver( receiver, filter );

Then in the receiver you can also retrieve the user id. Here is a small snippet:
public class UserSwitchReceiver extends BroadcastReceiver {

private static final String TAG = "UserSwitchReceiver";

    @Override
    public void onReceive(Context context, Intent intent)
    {
        boolean userSentBackground = intent.getAction().equals( Intent.ACTION_USER_BACKGROUND );
        boolean userSentForeground = intent.getAction().equals( Intent.ACTION_USER_FOREGROUND );
        Log.d( TAG, "Switch received. User sent background = " + userSentBackground + "; User sent foreground = " + userSentForeground + ";" );

        int user = intent.getExtras().getInt( "android.intent.extra.user_handle" );
        Log.d( TAG, "user = " + user );
    }
}

A: Try ACTION_USER_FOREGROUND and ACTION_USER_BACKGROUND. I have not used them, but they were added in API Level 17, and their description seems like it may help.