text:
Q: '===' cannot be applied to types 'string' and 'enum' string value I have created enum string in Typescript like below
 export enum Widget {
    ICONWIDGET = "IconWidget",
};

But I am getting runtime error '===' cannot be applied to types 'string' and 'Widget' when I compare a string with enum string.
 getWidgetComponent(componentName:string) {

              if(componentName ===  Widget.ICONWIDGET){
                  return IconWidgetComponent;
              }
      }

I saw a similar kind of issue in reported in Github. Is there any workaround for this??
https://github.com/Microsoft/TypeScript/issues/11533

A: I Upgraded to latest version of Typescript(2.4.1) and it's working fine. The previous version of Typescript I used was 2.1.4.
npm install -g typescript@latest

A: You could simply assert:
getWidgetComponent(componentName:string) {
          if(componentName ===  (Widget.ICONWIDGET as string)){
              return IconWidgetComponent;
          }
  }

A: You can cast the enum value to string:
if(componentName === Widget.ICONWIDGET as string) {

A: This works:
 enum Widget {
     ICONWIDGET = "IconWidget"
 };

 class X {

     getWidgetComponent(componentName: string) {

         if (componentName === (Widget.ICONWIDGET as string)) {
             return 'Put what you want to return here.';
         }
     }
 }

 var x = new X();
 alert(x.getWidgetComponent("IconWidget"));

see https://www.typescriptlang.org/play/#src=enum%20Widget%20%7B%0D%0A%20%20ICONWIDGET%20%3D%20%22IconWidget%22%0D%0A%7D%3B%0D%0A%0D%0Aclass%20X%20%7B%0D%0A%20%20getWidgetComponent(componentName%3A%20string)%20%7B%0D%0A%20%20%20%20if%20(componentName%20%3D%3D%3D%20Widget.ICONWIDGET%20as%20string)%20%7B%0D%0A%20%20%20%20%20%20return%201%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%7D%0D%0A%7D%20%20%20%20%20%0D%0A%0D%0Avar%20x%20%3D%20new%20X()%3B%0D%0Aalert(x.getWidgetComponent(%22IconWidget%22))%3B


text:
Q: Top N rows by group using python datatable What is the proper way to query top N rows by group in python datatable?
For example to get top 2 rows having largest v3 value by id2, id4 group I would do pandas expression in the following way:
df.sort_values('v3', ascending=False).groupby(['id2','id4']).head(2)

in R using data.table:
DT[order(-v3), head(v3, 2L), by=.(id2, id4)]

or in R using dplyr:
DF %>% arrange(desc(v3)) %>% group_by(id2, id4) %>% filter(row_number() <= 2L)

Example data and expected output using pandas:
import datatable as dt
dt = dt.Frame(id2=[1, 2, 1, 2, 1, 2], id4=[1, 1, 1, 1, 1, 1], v3=[1, 3, 2, 3, 3, 3])
df = dt.to_pandas()
df.sort_values('v3', ascending=False).groupby(['id2','id4']).head(2)
#   id2  id4  v3
#1    2    1   3
#3    2    1   3
#4    1    1   3
#2    1    1   2

A: Starting from datatable version 0.8.0, this can be achieved by combining grouping, sorting and filtering:
from datatable import *
DT = Frame(id2=[1, 2, 1, 2, 1, 2],
           id4=[1, 1, 1, 1, 1, 1],
           v3=[1, 3, 2, 3, 3, 3])

DT[:2, :, by(f.id2, f.id4), sort(-f.v3)]

which produces
     id2  id4  v3
---  ---  ---  --
 0     1    1   3
 1     1    1   2
 2     2    1   3
 3     2    1   3

[4 rows x 3 columns]

Explanation:

*

*by(f.id2, f.id4) groups the data by columns "id2" and "id4";

*the sort(-f.v3) command tells datatable to sort the records by column "v3" in descending order. In the presence of by() this operator will be applied within each group;

*the first :2 selects the top 2 rows, again within each group;

*the second : selects all columns. If needed, this could have been a list of columns or expressions, allowing you to perform some operation(s) on the first 2 rows of each group.

redpajama_set_name: RedPajamaStackExchange


text:
Q: multipe dropdown to be inserted in database one column per dropdown i have 27 dropdowns in my page. but i only show 6 of them because its too long.
        Empty META description
        <select>
            <option name="25" value="1">Ok</option>
            <option name="25" value="2">Information</option>
            <option name="25" value="3">Warning</option>
            <option name="25" value="4">Danger</option>
        </select>

        Duplicate META descriptions
        <select>
            <option name="26" value="1">Ok</option>
            <option name="26" value="2">Information</option>
            <option name="26" value="3">Warning</option>
            <option name="26" value="4">Danger</option>
        </select>

        Too long META description
        <select>
            <option name="27" value="1">Ok</option>
            <option name="27" value="2">Information</option>
            <option name="27" value="3">Warning</option>
            <option name="27" value="4">Danger</option>
        </select>

i want to insert them in my database one column per dropdown. how shall i do it?

A: Either comma separate them to fix them in one column & retrieve them by exploding the commas
Or
Create a new table & store the dropdown options with the dropdown ID.
Table :
DropDown_ID   DropDown_Value
25                  1
25                  2
25                  3
25                  4
26                  1
26                  2
26                  3
26                  4
27                  1
..
..


text:
Q: error while loading shared libraries: libpython2.6.so.1.0: cannot open shared object file: No such file or directory I have installed python2.6(initially through apt-get and then uninstall and reinstalling through source) in ubuntu 12.04 (python2.7 being the default version installed).
The ldconfig -p | grep python command yields the following results
libpython2.7.so.1.0 (libc6,x86-64) => /usr/lib/libpython2.7.so.1.0
libpyglib-2.0-python2.7.so.0 (libc6,x86-64) => /usr/lib/libpyglib-2.0-python2.7.so.0
libpyglib-gi-2.0-python2.7.so.0 (libc6,x86-64) => /usr/lib/libpyglib-gi-2.0-python2.7.so.0
libpyglib-gi-2.0-python2.7.so (libc6,x86-64) => /usr/lib/libpyglib-gi-2.0-python2.7.so

The libpython2.6.so.1.0 seems to be missing.
This is important as i am trying to run uwsgi 1.0.3
which is throwing the following error :
error while loading shared libraries: libpython2.6.so.1.0: cannot open shared object file: No such file or directory

After going through numerous threads on the same matter such as :
Python executable not finding libpython shared library
Where we set the LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/python it still failed in finding the respective file
Any help on the matter will be greatly appreciated.


text:
Q: Relationship of std::unique_lock and conditional_variable cond Here is my code:
Class
class carl{
public:
int x = 0;
std::mutex _mu;
std::condition_variable cond;
bool donecreating = false;

void createFood(){

    if(x == 0){
    std::unique_lock<mutex> locker(_mu);
    x++;
    std::cout<<"creating food.."<<std::endl;
    cout<<"Food count: "<<x<<endl;
    locker.unlock();

    cond.notify_one();                                 //notify
    std::this_thread::sleep_for(chrono::seconds(1));   //sleep
    }

}

void eatFood(){

    std::unique_lock<mutex> locker(_mu);                //lock
    std::cout<<"i am executing"<<std::endl;             //notif
    cond.wait(locker);                                  //wait

    x--;                                                //process food
    std::cout<<"eating food.."<<std::endl;
    cout<<"Food left: "<<x<<endl;
    locker.unlock();

}
};

Function aka thread one
void create(carl& carl){
for(int i=0;i>-100;i--){        //create 100 times

  carl.createFood();

}

carl.donecreating  = true;      //done creating 100 food
}

Main
int main(int argc, char** argv) {
carl c;                                    //init object
std::thread t1(create,std::ref(c));        //init thread

while(c.donecreating != true){            //exit condition is if the class is done creating food 100 times

c.eatFood();

}

t1.join();

return 0;
}

Output:
i am executing
creating food...
Food count: 1
eating food..
Food left: 0

I am trying to trace my code and here is my understanding so far and i need some clarifications
1.) Upon compile, main thread(consumer) is faster than the producer thread so it is fired up first and was put to sleep by cond.wait(locker); to prevent it from eating because no food was made yet. but before cond.wait(locker); there is std::unique_lock<mutex> locker(_mu);, is it automatically unlocked so that the other thread can access it while waiting?
2.) If ever the createFood was fired up first(because threads are processor based? it's possible right?), it will send the cond.notify_one(); if there is one and if not then it will just simply go on creating a food and then sleep. The other thread will start processing because the mutex will be unlocked then it will reach cond.wait(locker); but there is a food already so sleep won't be necessary the solution that i found out is by implementing spurious wake,  is that what it is for?
3.) I'm still really curious about std::unique_lock<mutex> locker(_mu); like what really happens if the other thread reached that line of code and it's currently locked? does it ignore every line below that and just move on until that block of code gets out of scope? or does it stops on that line and wait until it gets unlocked?

A: To start with, your code has a data race (and hence undefined behavior) since if(x == 0) in createFood() accesses x unprotected. Every access to x, both reads and writes, must be protected by the mutex.

is it automatically unlocked so that the other thread can access it
  while waiting?

Yes, wait() unlocks the mutex before blocking on the condition variable, and then locks the mutex again before it returns.

The other thread will start processing because the mutex will be
  unlocked then it will reach cond.wait(locker); but there is a food
  already so sleep won't be necessary the solution that i found out is
  by implementing spurious wake, is that what it is for?

No, spurious wakeup is not something you have control over. Your code has two problems:

*

*it can miss the notification, as you observe.

*The wait in eatFood() can end spuriously, in which case there isn't actually any food to eat, but you don't handle this case either.

The solution is to run wait in a loop, until there is food available. This is equivalent to running the version of wait taking a predicate:
while(x == 0) cond.wait(locker);

or
cond.wait(locker, [this](){ return x > 0; });

I'm still really curious about std::unique_lock<mutex> locker(_mu);
  like what really happens if the other thread reached that line of code
  and it's currently locked? does it ignore every line below that and
  just move on until that block of code gets out of scope? or does it
  stops on that line and wait until it gets unlocked?

The latter. After that line, the mutex is locked by the thread constructing locker. This means blocking and waiting if necessary.


text:
Q: Nginx Tornado and Flask - What's a good start/stop script and keep-alive method I've set up a Flask application to run on a tornado server backed by nginx. I've written a couple of bash scripts to reload server configuration when a new version is deployed, but I am unhappy with them. Basically what I have is:
to start the server (assuming in project root)
# this starts the tornado-flask wrapper
python myapp.py --port=8000 # .. some more misc settings

# this starts nginx
nginx

to stop it
pkill -f 'myapp.py'
nginx -s stop

to restart
cd $APP_ROOT
./script/stop && ./script/start

Many times these don't work smoothly and I need to manually run the commands. Also, I'm looking for a way to verify the service is alive, and start it up if it's down. Thoughts? Thanks.

A: Supervisor is what you are looking for.
It's what I use to manage my Tornado apps along with some other processing daemons.
It will daemonize, handle logging, pid files... Pretty much everything you need.


text:
Q: Multiple canvas using skiasharp in one view I am trying to use multiple canvas in a view, however only the second canvas is being displayed in the view. Is there a different way to show multiple canvas?
<ContentView>
    <StackLayout>
        <ScrollView>
            <Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                <skia:SKCanvasView x:Name="Canvas" PaintSurface="Draw" EnableTouchEvents="True" Touch="OnTouch" HorizontalOptions="FillAndExpand" />
                <skia:SKCanvasView x:Name="CanvasBody" PaintSurface="CanvasBody_PaintSurface" HorizontalOptions="FillAndExpand"></skia:SKCanvasView>
            </Grid>
        </ScrollView>
    </StackLayout>
</ContentView>

A: Add Grid Row and Column definition. The issue you are having is the second canvas is on top of the other canvas. After assigning row and column definition you have them separated.


text:
Q: Passing a method as a parameter with zero or more parameters for the passed in method? I'm trying to code what I've called a 'trigger'. They take an object, a function and some kind of activation criteria. Once activated, it runs the method on that object.
Here's a basic stripped down example. It works as expected for now. An example usage would be:
SomeObject myObj = new SomeObject();
MyTrigger trigger = new MyTrigger(myObj, "Delete");
trigger.Activate(); // calls myObj.Delete();

Now where I've called Invoke with null is where parameters can normally go (I think). The problem I'm having is getting the 'zero or more paramters' as a single parameter in the function declaration. I need a thrid parameter when creating MyTrigger that would be the parameters to pass during the Invoke.
Or is there an even better way to do it? I.e. Can I somehow pass the object, the function call and the parameters as a single parameter? Maybe two parameters?

A: You have to use delegates.
// rewrite your trigger constructor like this
class MyTrigger<TTarget>
{
    public MyTrigger(TTarget target, Action<TTarget> action);
    public void Activate()
    {
        this._action(this._target);
    }
}

// now call it with or without parameters
SomeObject myObj = new SomeObject();
var trigger = new MyTrigger<SomeObject>(myObj, o => o.Delete(1234));
trigger.Activate();

You can also create a static helper class to make the creation code slightly simpler to write:
static class MyTrigger
{
    public MyTrigger<TTarget> Create<TTarget>(TTarget target, Action<TTarget> action)
    {
        return new MyTrigger<TTarget>(target, action);
    }
}

// now write the initialization code like this (you don't have to specify the type parameter anymore):
var trigger = MyTrigger.Create(myObj, o => o.Delete());

A: You could use the params keyword:
public Trigger(object targetObject, string methodName, params object[] parameters)
{
    //"parameters" here will be an array of length 0 if no parameters were passed
}

MyTrigger trigger = new MyTrigger(myObj, "Delete"); //no parameters
MyTrigger trigger = new MyTrigger(myObj, "Delete", param1); //one parameter
MyTrigger trigger = new MyTrigger(myObj, "Delete", param1, param2); //two parameters

But I prefer Knagis' answer because it will also provide you compile-time safety (and likely the Trigger class will be far simplified and ditch any reflection that you probably have in there.)


text:
Q: Solution to Divisibility Problem I have attempted to solve problem which is stated as follows:

$2^n+1=xy$ where $n>0$ and $x,y>1$. Prove that $2^a$ divides $x-1$ iff $2^a$ divides $y-1$.

My solution is as follows:
$x$ and $y$ are evidently odd so let $x-1=2^a q_{x}$ where $y-1=2^b q_{y}$, where $q_{x},q_{y}$ are odd. So:
$$ 2^n+1=(2^a q_{x}+1)(2^a q_{y}+1)$$
$$ \implies2^n=2^{a+b}q_{x}q_{y}+2^a q_{x}+2^b q_{y}$$
$$ \implies2^{n-a}=2^{b}q_{x}q_{y}+q_{x}+2^{b-a} q_{y}\text{   }(1)$$
In the above, assuming $b>a$. Also:
$$ xy\geq x$$
$$ \implies xy-1\geq x-1$$
$$ \implies2^n\geq 2^a q_{x}$$
$$ \implies n\geq a$$
Assuming $n>a$, $2^{n-a}$ must be even, and $q_{x}$ is odd so $2^{b-a}q_{y}$ must be odd too so $b=a$. Also, $n\neq a$ because the sum on the right of (1) cannot equate to $1$.
Q.E.D.
NOTE: This is not a homework problem.

A: Note that in order $2^a$ to divide $x-1$ we must have $a \le n$. Now assume $x\equiv 1 \pmod{2^a}$. Then taking the equation modulo $2^a$ we have $y \equiv 1 \pmod{2^a}$, therefore $2^a \mid y-1$.
Similarly you can prove the other side of the equivalence.

A: Hint $\ $ After your deduction that  $\,a\le n\,$ we know $\,2^a\mid \color{#c00}{2^n}\,$ therefore
$\qquad\ \ {\rm mod}\ \color{}{2^a}\!:\,\ xy\equiv 1\!+\color{#c00}{2^n}\equiv 1\!+\color{#c00}0,\ $ i.e. $\ xy\equiv 1\ $ so $\ x\equiv 1\iff y\equiv 1\ \ \ $  QED
Remark $\  $ If congruences are unfamiliar we can eliminate them as below.
$\  \ \begin{eqnarray}\\[-1em] 2^n = xy\!-\!1 = \smash[t]{(\overbrace{x\!-\!1}^{\large b})(\overbrace{y\!-\!1}^{\large c})} + x\!-\!1 + y\!-\!1\, =\, bc+b+c\end{eqnarray}$
therefore $\ 2^a\!\mid 2^n\!= bc+b+c\ $ implies $\ 2^a\mid b\!\iff\! 2^a\mid c\ \ \ $ QED

A: In your solution, you want to say that $x$ and $y$ are evidently odd, but that's just a slip.
Your idea is good, but not carried on correctly.
What you have to prove is that, if $2^a$ divides $x-1$, then $2^a$ divides $y-1$. By symmetry, you also have the other implication.
Assume $x-1=2^aq$ for some $q$ (not necessarily odd) and $y-1=2^br$ (with $r$ odd). You have to prove that $a\le b$.
Now $2^n+1=(2^aq+1)(2^br+1)$, so
$$
2^n=2^{a+b}qr+2^aq+2^br
$$
If $b<a$, then you can collect $2^b$ on the right-hand side and get
$$
2^{n-b}=2^aqr+2^{a-b}q+r
$$
which is odd. A contradiction, because the right-hand side is $\ge3$ so $n-b>0$ and the left-hand side is even.


text:
Q: Как добавить точку в цикле for in range? Вот код:
a = (input("Напишите слово:"))

for i in range(1, 10+1):
  print(i + ".", a)

Выдаёт ошибку: TypeError: unsupported operand type(s) for +: 'int' and 'str'
Пробовал так же добавить int и str, но не работает
a = (input("Напишите слово:"))

for i in range(1, 10+1):
  print(int(str(i + ".", a)))

Нужно чтобы выдавало вот так:
1.
2.
3.

И так далее...

A: a = (input("Напишите слово:"))

for i in range(1, 10+1):
  print(str(i) + ".", a)

A: Можно через f-строки.
Так:
a = input("Напишите слово:")

for i in range(1, 10+1):
    print(f'{i}.', a)

Или так (как писали в комментариях):
a = input("Напишите слово:")

for i in range(1, 10+1):
    print(f'{i}. a')

Подробнее в документации.

A: a = input("Напишите слово:")

for i in range(1, 10 + 1):
  print(i, ". ", a, sep = '')

Почитай как использовать функцию Print() в Python.


text:
Q: How to compare decimals knowing there is room for error I have two different ways to calculate a value. Once both methods run, I get the following:
decimal a = 145.2344;
decimal b = 145.2345;

I have a unit test:
  Assert.AreEqual(a,b);

I want to be able to account for a +/- .0001 difference. How can I add this rule?

A: Simple:
if (Math.Abs(a-b) < 0.0001m)
    // equal

A: In NUnit's constraint model, you can do this:
Assert.That(Math.Abs(a-b), Is.LessThan(0.0001M));

Better yet, make it a function:
void AssertDiff(decimal a, decimal b, decimal diff = 0.0001) {
     Assert.That(Math.Abs(a-b), Is.LessThan(diff));
}

EDIT : In MS Unit Test Framework, do this:
void AssertDiff(decimal a, decimal b, decimal diff = 0.0001) {
     Assert.IsTrue(Math.Abs(a-b) < diff);
}


text:
Q: Catching an error from byte-compile-file in batch mode I'm trying to write a makefile snippet to compile .el files to .elc files. I have the following snippet:
.el.elc:
        $(EMACS) -q -Q --batch \
                       --eval "(progn
                                 (setq load-path (cons \"$(abs_srcdir)\" load-path))
                                 (setq load-path (cons nil load-path))
                                 (defun byte-compile-dest-file (f) \"$@\")
                                 (condition-case nil
                                   (byte-compile-file \"$<\")
                                   (error (kill-emacs 1))))"

(I have formatted the snippet for presentation, make probably won't like it laid out this way.)
$(abs_srcdir) is being defined correctly, but I have two problems:
Firstly: With a directory layout like the following:
+- foo.el <- foo.el lives in $(abs_srcdir)
+- _build/
++- bar.el
++- Makefile

(That is, a VPATH build where foo.el lives in srcdir and I'm trying to build in _build.)
If bar.el depends on foo.el (via (require 'foo) and (provide 'foo)), attempts to compile bar.elc fail with the error:
In toplevel form:
../bar.el:1:1:Error: Cannot open load file: foo

This strikes me as odd because thought I was consing $(abs_srcdir) onto load-path. What's happened?
The second problem is that even if this happens, emacs is exiting with status 0, despite my efforts to wrap the (byte-compile-file) call in a (condition-case). What has happened here?

A: The first problem I had was that with a VPATH build, files in the build directory weren't being found (by calls to (require), for example). For some reason, consing nil onto load-path doesn't work, but consing $(abs_srcdir) works.
The second problem was that I couldn't catch the error raised by (byte-compile). This was solved by wvxvw: (byte-compile) doesn't raise errors, but returns t if the compilation succeeds. Therefore, something like:
(unless (byte-compile-file "$<") (kill-emacs 1))

works nicely.

A: I cleaned up the snippet you gave and did a test case in the directory ~/test.
I end up with the following three files.
Makefile:
abs_srcdir=~/test

all: foo.elc bar.elc

clean:
        rm -rf *.elc

%.elc: %.el
    emacs -Q --batch --eval "(progn (add-to-list 'load-path \"$(abs_srcdir)\") (defun byte-compile-dest-file (f) \"$@\") (condition-case nil (byte-compile-file\"$<\") (error (kill-emacs 1))))"

foo.el:
(defun foo-fun ()
  (message "foo"))

(provide 'foo)

bar.el:
    (require 'foo)
(defun bar-fun ()
  (foo-fun))

(provide 'bar)

This example works for me and only fails if I give the wrong definition for abs_srcdir.


text:
Q: JQuery on click lists items only once properly then holds last value all the time I have strange problem building front-end layer for simple java LibraryApp.
I have dynamically created (bootstrap) dropdown buttons which should list readers borrows. Each button works properly but only once for each reader. Then it takes last loaded list and displays it after each click. When I refresh the page it works fine again but only once.
Here are my functions:
function listBorrowedCopiesInDropdownRequest(){
  const requestUrl = apiRoot + 'getBorrowedCopies';
  $(".readers").on("click", ".return-copy", function(){

    console.log("return clicked");
    var readerId = $(this).closest("tr").find(".readerId").html();

    $.ajax({
      url: requestUrl + "?" + $.param({readerId: readerId}),
      method: 'GET',
      contentType: "application/json",
      success: function(copies){
        console.log(copies);
        var copiesAmount = copies.length;

        listBorrowedCopiesInDropdown(copies);
      }
    });
  });
}

and this one responsible for creating list of elements (copies):
function listBorrowedCopiesInDropdown(copies){
  var result = "";
  for(i = 0; i<copies.length; i++){
    result += "" +
    copies[i].inventoryNumber + ""
    $(".copies-list").html(result);
  }
}

About HTML: this button (.return-copy) is dynamically created with all tr content (dependent on how much readers exist). So each  is created from js:

    ID
    FIRST NAME
    LAST NAME
    EMAIL
    BIRTH DATE
    BORROWS

        <button type="button" class="btn btn-secondary btn-sm edit-reader" data-toggle="modal" data-target="#exampleModal">Edit</button>

Edit reader

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  ×
                </button>

                <form>

                    First name
                    <input type="text" class="form-control" id="reader-first-name-update">

                    Last name
                    <input type="text" class="form-control" id="reader-last-name-update"></input>

                    Birth date
                    <input class="form-control" type="date" placeholder="Birth date" id="birth-date-update">

                    Email
                    <input type="email" class="form-control" id="reader-email-update"></input>

                </form>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary save-changes">Save</button>

-->

          <button class="btn btn-secondary btn-sm dropdown-toggle return-copy" type="button" id="return-copy" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Return copy
          </button>

            No copies

        <button class="btn btn-secondary btn-sm delete-reader-button">Delete reader</button>

Then after click on .return-copy button the dropdown list is also loaded dynamically (for each reader another list of borrowed books)
I will be very grateful for any ideas what is wrong here.

A: when you call html function of jQuery it changes the whole html content of the tag.
so i think you need to use $(".copies-list").append(result); to add your elements to copies-list
and also change following:
$(".readers").on("click", ".return-copy", function(){
to
$(document).on("click", ".readers .return-copy", function(){
then try again.
read more about the difference between the above two code snippets here:
What is different between $(document).on() and $(element).on()


text:
Q: CakePHP unknown exception thrown After successfully testing my app locally, I've pushed it to the remote server for further testing. But there, on each and every page, I get the following fatal error: Fatal error: Exception thrown without a stack frame in Unknown on line 0. What can be the cause of this?

A: if there was error with the code then there must have been an entry in apache's log. Also, with debug level set, it would definately have given errors unless you have defined your own custom exception handlers. so after all could it be whitespaces ?
It is not mandatory to have closing php tags in php pages unless you have other scripts below. I once struggled with it for days. If it is occuring in every page, you can check it once on the default layout, you could also test by commenting every includes in default layout to see if the problem is caused in some other script common to the application.


text:
Q: Array variable initialization error in Java I am trying to write a Java program that reads an input file consisting of URLs, extracts tokens from these, and keeps track of how many times each token appears in the file. I've written the following code:
import java.io.*;
import java.net.*;

public class Main {

    static class Tokens
    {
        String name;
        int count;
    }

    public static void main(String[] args) {
        String url_str,host;
        String htokens[];
        URL url;
        boolean found=false;
        Tokens t[];
        int i,j,k;

        try
        {
            File f=new File("urlfile.txt");
            FileReader fr=new FileReader(f);
            BufferedReader br=new BufferedReader(fr);

            while((url_str=br.readLine())!=null)
            {
                url=new URL(url_str);
                host=url.getHost();
                htokens=host.split("\\.|\\-|\\_|\\~|[0-9]");

                for(i=0;i<htokens.length;i++)
                {
                    if(!htokens[i].isEmpty())
                    {
                        for(j=0;j<t.length;j++)
                        {
                            if(htokens[i].equals(t[j].name))
                            {   t[j].count++;  found=true;    }
                        }
                        if(!found)
                        {
                            k=t.length;
                            t[k].name=htokens[i];
                            t[k].count=1;
                        }
                    }
                }

                System.out.println(t.length + "class tokens :");
                for(i=0;i<t.length;i++)
                {
                    System.out.println(
                            "name :"+t[i].name+" frequency :"+t[i].count);
                }
            }
            br.close();
            fr.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

But when I run it, it says: variable t not initialized.. What should I do to set it right?

A: Arrays in Java are fixed length, so I think what you really want to do is use a List<Tokens>
e.g.
List<Tokens> t = new ArrayList<Tokens>();

and
t.add(new Tokens(...))

unless you know in advance the number of items you'll have.

A: Initialize it:
// Declaration:
Tokens[] t;

// Initialization:
t = new Tokens[10]; // (Or whatever your desired length is)

You can combine declaration and initialization, and many do. I'm not a fan of doing so, but:
Tokens[] t = new Tokens[10];

You'll have the same issue with htokens.
You may want to look at the List interface (and its various implementations) instead of using an array.

A: You are not initializing Tokens t[]; before using it.
EDIT : You need to it as below :
Tokens[] t = new Tokens[100];   //  100 is just an example

Or use List<Tokens>.

A: Your code declares that t will represent an array of Tokens.
However, it does not define that array.
Per the Java Documentation, you need a line like:
t = new Tokens[10]; // Or however large the array should be

A: The modified code : < as per Brian Agnew's answer >
import java.io.*;
import java.net.*;
import java.util.*;

public class Main {

      static class Tokens
        {
            String name;
            int count;
            Tokens(String str,int c)
            {
                name=str;
                count=c;
            }
        }

        public static void main(String[] args) {

        String url_str,host;
        String htokens[];
        URL url;
        boolean found=false;
        List<Tokens> t = new ArrayList<Tokens>();

        int i,j,k;

        try
        {
            File f=new File("urlfile.txt");
            FileReader fr=new FileReader(f);
            BufferedReader br=new BufferedReader(fr);

          while((url_str=br.readLine())!=null)
          {
          url=new URL(url_str);

          host=url.getHost();
          htokens=host.split("\\.|\\-|\\_|\\~|[0-9]");

            for(i=0;i<htokens.length;i++)
            {
                if(!htokens[i].isEmpty())
                {
                    found=false;
                    for(j=0;j<t.size();j++)
                    {

                        if(htokens[i].equals(t.get(j).name))
                        {
                            k=t.get(j).count+1;
                            t.set(j,new Tokens(htokens[i],k));
                            found=true;
                            break;
                        }
                    }
                    if(!found)
                    {
                        t.add(new Tokens(htokens[i],1));
                    }
                }
            }

          }
          System.out.println(t.size() + "class tokens :");
          for(i=0;i<t.size();i++)
          {
              System.out.println("name :"+t.get(i).name+" freq :"+t.get(i).count);
          }
          br.close();
          fr.close();

        }
        catch(Exception e)
        {
            System.out.println(e);
        }

    }

}

A: Just to mention, you should not use C-like array syntax, i.e. use
String[] names = { "Walter", "Hans", "Bill" };

Instead of
String names[] = { "Walter", "Hans", "Bill" };


text:
Q: Expected 2D array, got 1D array instead, any solution? I'm new using Machine Learning and I am trying to predict the price of the stocks in 30 days.
This is my code:
import pandas as pd
import matplotlib.pyplot as plt
import pymysql as MySQLdb
import numpy as np
import sqlalchemy
import datetime
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing, svm
from sklearn.model_selection import train_test_split

forecast_out = int(30)
df['Prediction'] = df[['LastPrice']].shift(-forecast_out)
df['Prediction'].fillna(0)
X = np.array(df['Prediction'].fillna(0))
X = preprocessing.scale(X)
X_forecast = X[-forecast_out:]
X = X[:-forecast_out]
y = np.array(df['Prediction'].fillna(0))
y = y[:-forecast_out]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
X_train, X_test, y_train, y_test.reshape(-1,1)

# Training
clf = LinearRegression()
clf.fit(X_train,y_train)
# Testing
confidence = clf.score(X_test, y_test)
print("confidence: ", confidence)
forecast_prediction = clf.predict(X_forecast)
print(forecast_prediction)

I got this error:

ValueError: Expected 2D array, got 1D array instead:
array=[-0.46939923 -0.47076913 -0.47004993 ... -0.42782272  3.07433019 -0.46573474].

Reshape your data either using
array.reshape(-1, 1) if your data has a single feature
  or
array.reshape(1, -1) if it contains a single sample.

A: It's expecting a 2D Array when you're only passing in a 1D Array. You can solve this by putting another set of brackets around where you're getting the probelm. For example
x = [1,2,3,4]
Foo(x)

If that throws the error, you could just do
Foo([x])


text:
Q: How do I import a CSV file into SQL PLUS? I have created a database and have my tables, but I need to implement some data into it, to avoid writing out 5000+ entries I have decided to download 'dummy data (fake)' for names, numbers, address, etc.
I have tried using "BULK INSERT" but SQL does not accept this, is there any other way of implementing the fake data?

A: SQL Plus can only interpret commands given by console or read from script. You have to create script with set of insert commands and run it from SQL Plus. I used this approach more times, it's not as difficult.
Write your script like this:
declare
  procedure change_data(your_data_in_parameters) is
  begin
     set_of_our_commands_to_handle_one_record;
  end;
begin
    change_data(your_data_from_CSV_row1);
    change_data(your_data_from_CSV_row2);
    ...
    commit;
end;

Open your CSV in some spreadsheet editor and add new formula column which collects change_data rows.


text:
Q: jquery scheduler time-range picker Is there any way that i can make scheduler according to this image?
I tried many layout but still didn't meet my criteria.
http://sundramfab.com/jquery/

We have try this layout and time-range also but still didn't work
This kind of time-range i want to do
[1]: https://i.stack.imgur.com/vRlQU.png


text:
Q: Remove linear trend from raster stack R Trying remove the linear trend (detrend) from a monthly precipitation raster stack for the US from 1979-2015 (https://www.northwestknowledge.net/metdata/data/monthly/pr_gridMET.nc). These data are large enough that using those data as an example would be a bit unruly here so I am going to use the data from the raster package for sake of efficiency.  The working model I have currently is to use `raster"::calc`` on a linear model and pull the residuals.  My understanding is that those residuals are the detrended series, but I am not 100% sure that is correct.  The code I am using is as follows:
library(raster)

fn <- raster(system.file("external/test.grd", package="raster"))
fn2 <- fn+1000
fn3 <- fn +500
fn4 <- fn +750
fn5 <- fn+100

fns <- stack(fn, fn2, fn3, fn4, fn5)

time <- 1:nlayers(fns)

# Get residuals to detrend the raw data
get_residuals <- function(x) {
  if (is.na(x[1])){
    rep(NA, length(x)) }
  else {
    m <- lm(x~time)
    q <- residuals(m)
    return(q)
  }
}

detrended_fns <- calc(fns, get_residuals) # Create our residual (detrended) time series stack

I feel like I'm missing something here.  Can anyone confirm that I'm on the right track here?  If I'm not any suggestions on how to properly detrend these data would be helpful! thanks!

A: The residuals remove the slope and the intercept and you get anomalies. Perhaps you only want to remove the slope? In that case you could add the intercept to the residuals in get_residuals
q <- residuals(m) + coefficients(m)[1]

Or better:
q <- residuals(m) + predict(m)[1]

So that you use year 1 (and not year 0) as the base, and it would also work if time is, say, 2000:2004
You could also take the last year, mid year, or average as base.


text:
Q: Can we optimize CSS hover property? Based on the bellow code:
#my-product .description {display: block;}
#my-product .description .complement {display: none;}

#my-product .description:hover .complement {display: block;text-decoration: underline;font-size: 17px;}
#my-product .description:hover .complement img {display: block;border: 1px solid #cccccc;}
#my-product .description:hover .complement hr {display: block;border: 1px solid #cccccc;}

Does declaring style in the hover section matter for performance or should we declare it before like this:
#my-product .description {display: block;}
#my-product .description .complement {display: none;text-decoration: underline;font-size: 17px;}
#my-product .description .complement img {display: block;border: 1px solid #cccccc;}
#my-product .description .complement hr {display: block;border: 1px solid #cccccc;}

#my-product .description:hover .complement {display: block;}

I'm not asking about code readability but only browser performance.

EDIT To clarify my question:
In the first example will the browser have to rebuild entirely each elements prefixed by .description:hover on each hover made by the user on the description ? Or will he only process display: none and display: block?
And if he needs to rebuild entirely the description element, does declaring the other styles outside of the :hover will optimize this process?
This question is not about selector optimization but only about rendering performance.


text:
Q: format statement in a string resource file I have strings defined in the usual strings.xml Resource file like this:
<string name="hello_world"> HELLO</string>

Is it possible to define format strings such as the one below
 result_str = String.format("Amount: %.2f  for %d days ",  var1, var2);

in the strings.xml resource file?
I tried escaping the special characters but its not working.

A: Quote from Android Docs:

If you need to format your strings using String.format(String,
  Object...), then you can do so by putting your format arguments in the
  string resource. For example, with the following resource:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string
  and %2$d is a decimal number. You can format the string with arguments
  from your application like this:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

A: For me it worked like that in Kotlin:
my string.xml
 <string name="price" formatted="false">Price:U$ %.2f%n</string>

my class.kt
 var formatPrice: CharSequence? = null
 var unitPrice = 9990
 formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 99,90
For an even better result, we can do so
 <string name="price_to_string">Price:U$ %1$s</string>

 var formatPrice: CharSequence? = null
 var unitPrice = 199990
 val numberFormat = (unitPrice/100.0).toString()
 formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))

  fun formatValue(value: String) :String{
    val mDecimalFormat = DecimalFormat("###,###,##0.00")
    val s1 = value.toDouble()
    return mDecimalFormat.format(s1)
 }

 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 1.999,90

A: You do not need to use formatted="false" in your XML.  You just need to use fully qualified string format markers - %[POSITION]$[TYPE] (where [POSITION] is the attribute position and [TYPE] is the variable type), rather than the short versions, for example %s or %d.
Quote from Android Docs: String Formatting and Styling:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a
  string and %2$d is a decimal integer. You can format the string with
  arguments from your application like this:
Resources res = getResources();
String text = res.getString(R.string.welcome_messages, username, mailCount);

A: Inside file strings.xml define a String resource like this:
<string name="string_to_format">Amount: %1$f  for %2$d days%3$s</string>

Inside your code (assume it inherits from Context) simply do the following:
 String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);

(In comparison to the answer from LocalPCGuy or Giovanny Farto M. the String.format method is not needed.)

A: You should add formatted="false" to your string resource

Here is an example
In your strings.xml :
<string name="all" formatted="false">Amount: %.2f%n  for %d days</string>

In your code:
yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));


text:
Q: How to take standard input from user and use that across Appium Test Case? I have a scenario where I want to take User Standard Input from the console (Using Scanner(System.in) utility in Java).
Like, When a particular text field is being appeared then User need to type the input text as standard input rather than a device itself.
I am trying below code:
System.out.println("Enter the User Input: ");
Scanner sc = new Scanner(System.in);
String inputForTextField = sc.next();
getTextField().sendKeys(inputForTextField);

But the execution is getting stuck on String inputForTextField = sc.next(); User is not able to enter the text on the console and after 60 seconds Appium session is getting timed out.
Any help/suggestion would really be appreciated!
I am also open to hearing suggestion if I can take input from User using some Java AWT prompt, I just wanted to take user input from the computer rather than the device itself.
Thanks

A: You can supply the values using dataprovider(Excel/Json files) or even using config.properties file. In automation, it is machine which does all the inputs, human intervention defeats the automation purpose.


text:
Q: relative path and system paths are not working in codeblocks When I am trying to access files from standard usr/ it is not working. and showing errors that file is missing .
I have added path but and make it work but i think this is not the correct way.
I have a workspace with 10-12 projects which are of c and cpp both.
In one project I am using cpp with thrift libraries and protocol.
in that project only I am facing issue. with I am individually building that project it is working but when building it from the main project. it starts showing error in files.
There all almost 17 projects and 16 are generating .so files and all are going to the main project. and main is generating an executable. and that executable uses all the .so files.
but In thrift only it is showing errors. before it was showing for #include i added that file so now it is showing undefined type Name Space ..
I think this issue is because of relative path but I am not sure
Please Help


text:
Q: Unix Semaphore Issue I have been writing test programs regarding thread synchronization for a larger project for school. One of the test programs I wrote was a short snippet of code to test the "semaphore.h" library. The code is as follows:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

//Semaphore
sem_t mutex;

//Critical section variable
int crit;

//Method for pthreads
void* method()
{
    int x;

    //Loop to increment 'crit'
    for (x = 0; x < 5000000; x++)
    {
        sem_wait(&mutex);
        //Critical Section
        crit++;
        sem_post(&mutex);
    }

    pthread_exit(0);
}

int main()
{
    pthread_t t1, t2;

    sem_init(&mutex, 0, 1);
    pthread_create(&t1, NULL, method, NULL);
    pthread_create(&t2, NULL, method, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    sem_destroy(&mutex);

        //This value should be '10000000'
    printf("Value of 'crit': %d\n", crit);

    return 0;
}

The final value of the 'crit' variable should be ten-million, but I am only getting numbers close to it, indicating a race condition. I have compared my code to other samples, and it looks right, but I keep getting the same problem. Any thoughts?

A: Your critical section is not locked at all, which hypothesis fits your symptoms well.
sem_init() is failing with ENOSYS.  sem_wait() and sem_post() subsequently fail with EINVAL, and sem_destroy() fails as well (probably again with ENOSYS).  Your worker threads are stepping on each other's increments.
Are you on OS X?  That's the most common platform at present that does not support unnamed POSIX semaphores.  Try the named semaphore interface, defined in the same header file, which is supported.


text:
Q: XSL: Split text attribute based on delimiter I have the following code.
<xsl:template match="Rel/SPFMarkupFile">
<xsl:for-each select="./SPFReportItem">

        X
        <xsl:value-of select='../../../SPFReportItem/ReportAttribute[@AttrName="Name"]/@AttrValue' />

            <xsl:value-of select='ReportAttribute[@AttrName="SPFMarkupText"]/@AttrValue' />

        <xsl:value-of select='ReportAttribute[@AttrName="CreationUser"]/@AttrValue' />
        N/A
        <xsl:value-of select='ReportAttribute[@AttrName="SPFMarkupType"]/@AttrValue' />

</xsl:for-each>

For <xsl:value-of select='ReportAttribute[@AttrName="SPFMarkupText"]/@AttrValue' />

The value for example could be test123~test2~test4~test1
The delimiter is ~
I want to split that value and put it into different rows. So I want it to be like
test123
test2
test4
test1
For the other columns, it will be the same values.
How can I achieve this?

A:
The value for example could be test123~test2~test4~test1 The delimiter
  is ~
I want to split that value and put it into different rows.

Use:
translate(., '~', '
')

The evaluation of this XPath expression produces from the string value of the current node another string in which every occurence of the ~ character is replaced by a NL (new line) character.
Demo:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/*">
     <xsl:value-of select="translate(., '~', '
')"/>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on this XML document:
<t>test123~test2~test4~test1 </t>

the wanted, correct result is produced:
test123
test2
test4
test1

II. XSLT 2.0 solution:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/*">
     <xsl:value-of select="tokenize(., '~')" separator="
"/>
 </xsl:template>
</xsl:stylesheet>

When applied on the same XML document (above), the wanted, correct result is produced:
test123
test2
test4
test1

A: A list of conditional statements should work for you
<xsl:if test="'ReportAttribute[@AttrName="SPFMarkupText"]/@AttrValue'='Test123'">
</xsl:if>
<xsl:if test="'ReportAttribute[@AttrName="SPFMarkupText"]/@AttrValue'='Test1'">
</xsl:if>
<xsl:if test="'ReportAttribute[@AttrName="SPFMarkupText"]/@AttrValue'='Test2'">
</xsl:if>
<xsl:if test="'ReportAttribute[@AttrName="SPFMarkupText"]/@AttrValue'='Test3'">
</xsl:if>

A: Split the value into parts by using tokenize function in XSLT 2.0 or use the very good answer by Martin Honnen to one of my own questions when using XSLT 1.0 : How can make an XSLT Javascript extension function return a node-set?.


text:
Q: Transparent header on scroll to full colour - Nav overlay issue Currently my site has a transparent navbar when on scroll will change to full colour. The issue i am having is that the navbar also switches colour when the page is scrolled on the fullscreen navigation.
How can i stop the navbar switching colour when the fullscreen navigation is open? Would i need to change me JS?

$(document).ready(function() {
  $(".menu-btn a").click(function() {
    $(".overlay").fadeToggle(200);
    $(this).toggleClass('btn-open').toggleClass('btn-close');
  });

  $('.overlay').on('click', function() {
    $(".overlay").fadeToggle(200);
    $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
  });

  $('.menu a').on('click', function() {
    $(".overlay").fadeToggle(200);
    $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
  });
});

$(document).ready(function() {
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if (scroll > 100) {
      $(".navbar").css("background-color", "#dedede");
    } else {
      $(".navbar").css("background-color", "transparent");
    }
  })
});
body {
  background: black;
}

.menu-btn {
  z-index: 999;
  display: inline;
  font-size: 32px;
}

.menu-btn a {
  display: inline-block;
  text-decoration: none;
  /* safari hack */
}

.btn-open:after {
  color: #fff;
  content: "\f394";
  font-family: "Ionicons";
  -webkit-transition: all .2s linear 0s;
  -moz-transition: all .2s linear 0s;
  -o-transition: all .2s linear 0s;
  transition-property: all .2s linear 0s;
}

.btn-open:hover:after {
  color: #ffffff;
}

.btn-close:after {
  color: #fff;
  content: "\f2d7";
  font-family: "Ionicons";
  -webkit-transition: all .2s linear 0s;
  -moz-transition: all .2s linear 0s;
  -o-transition: all .2s linear 0s;
  transition-property: all .2s linear 0s;
}

.btn-close:hover:after {
  color: #ffffff;
}

/* OVERLAY */

.overlay {
  position: fixed;
  top: 0;
  z-index: 99;
  display: none;
  overflow: auto;
  width: 100%;
  height: 100%;
  background: rgba(209, 180, 0, 0.96);
}

.overlay .menu {
  margin: 15% auto;
  width: 80%;
}

.overlay .menu ul {
  margin: 0;
  padding: 0;
  width: 100%;
}

.overlay .menu ul li {
  float: left;
  padding: 6px 0 0 0;
  width: 50%;
  list-style: none;
  text-align: left;
  text-transform: uppercase;
}

.overlay .menu ul li#social {
  width: 100%;
  margin-top: 50px;
}

.overlay .menu ul li a {
  color: #d1b400;
  font-weight: 300;
  font-size: 20px;
  font-family: 'Old Standard TT', serif;
}

.overlay .menu ul li#social a {}

.overlay .menu ul ul {
  margin-top: 20px;
}

.overlay .menu ul ul li {
  position: relative;
  float: none;
  margin: 0;
  width: 100%;
  border: 0;
}

.overlay .menu ul ul li a {
  color: #fff;
  text-transform: capitalize;
  font-weight: 300;
  font-size: 30px;
}

.overlay .menu ul ul li a:hover {
  color: #000000;
}

/* RESPONSIVE */

@media screen and (max-width: 768px) {
  .overlay .menu ul li {
    float: none;
    margin-bottom: 25px;
    width: 100%;
  }
  .overlay .menu ul li:last-child {
    border: 0;
  }
  .overlay .menu ul ul {
    margin-top: 20px;
  }
  .menu-btn {
    right: 25px;
  }
}

.allexamples {
  position: absolute;
  bottom: 0;
  font-size: 18px;
  font-weight: bold;
  width: 100%;
  text-align: center;
  background: #e9e9e9;
  padding: 20px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  color: #333;
  position: fixed;
}

.menu-social {
  display: inline-block;
  margin: 0 .4em;
}

.menu-social a {
  width: 44px;
  height: 44px;
  padding: 0;
  background-image: url("../img/cd-socials.svg");
  background-repeat: no-repeat;
  /* image replacement */
  overflow: hidden;
  text-indent: 100%;
  white-space: nowrap;
}

.menu-social .menu-facebook a {
  background-position: 0 0;
}

.menu-social .menu-instagram a {
  background-position: -44px 0;
}

.menu-social .menu-dribbble a {
  background-position: -88px 0;
}

.menu-social .menu-twitter a {
  background-position: -132px 0;
}

.overlay .menu ul ul li.description {
  padding: 0px 0 10px 0px;
}

.overlay .menu ul ul li.description span {
  color: #000000;
  font-size: 13px;
  font-weight: 300;
  text-transform: none;
}

p.tel,
p.email {
  margin: 0 0 3px 0;
}

p.tel a {
  color: #fff!important;
  font-weight: 300!important;
  font-size: 20px!important;
  letter-spacing: 1px;
}

p.email a {
  color: #fff!important;
  font-weight: 300!important;
  font-size: 20px!important;
  text-transform: none;
}

.menu-btn a span {
  font-size: 18px;
  color: #ffffff;
  line-height: 18px;
  font-weight: 600;
  position: relative;
  top: -5px;
  right: 5px;
}

            MENU

Branding

Brand Development, Logos, Point, Point

Digital

Website Design, Website Development, Point, Point

Print

Business Cards, Leaflets, Point, Point

Packaging

Point, Point, Point, Point

Infographics

Point, Point, Point, Point

About

About Company

Work

Examples & Case Studies of our work

Contact

Get in touch with us to get your project started

info@company.com

01234 566545

https://codepen.io/whitinggg/pen/bLzxGG

A: You can stop the navbar switching color when the fullscreen navigation by small editing in your script like this
change your script like this
$(document).ready(function () {

    $(".menu-btn a").click(function () {
        var scroll = $(window).scrollTop();
        $(".overlay").fadeToggle(200);
        $(this).toggleClass('btn-open').toggleClass('btn-close');

        if( $(this).hasClass('btn-close') ) {
            $(".navbar").css("background-color", "transparent");
        }
        else if( scroll > 100) {
            $(".navbar").css("background-color", "#dedede");
        }
    });

    $('.overlay').on('click', function () {
        $(".overlay").fadeToggle(200);
        $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
    });

    $('.menu a').on('click', function () {
        $(".overlay").fadeToggle(200);
        $(".menu-btn a").toggleClass('btn-open').toggleClass('btn-close');
    });

});

$(document).ready(function() {
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();
        if (scroll > 100) {
            if($('.overlay:visible').length == 0) {
                $(".navbar").css("background-color", "#dedede");
            }
        } else {
            $(".navbar").css("background-color", "transparent");
        }
    });
});

A: You may consider adding an !important to the background style in order to always keep it transparent:
.navbar.fixed-top {
   background:transparent!important;
}


text:
Q: Translating a connection string to database.yml file in Ruby on Rails The problem is fairly simple and straightforward. I have a database connection string and I want to make a corresponding database.yml file from it.
The connection string is as follows:
data source=qsss.gar.de\SQL2012,3000;initial catalog=City;persist security info=True;user id=user_me;password=user_me##2009;

Now, the file I created is likewise:
development:
    adapter:    sqlserver
    host:       qsss.gar.de\SQL2012,3000
    port:       1433
    database:   City
    username:   user_me
    password:   user_me##2009

Now, the problem occurs in line 3: this qsss.gar.de\SQL2012 is syntax-highlighted, where as the ,3000 part stays white, not highlighted but just as a normal text
Also the problem in last line: user_me##2009, it just recognizes user_me and then treats ##2009 as the comment, but this part is also a part of the password.
I noticed, if I used quotation marks, the highlighting is OK, but not sure should I use them?
My question is - how should the database.yml file look like for the given connection string?

A: use quotes " to wrap the strings.
development:
    adapter:    "sqlserver"
    host:       "qsss.gar.de\SQL2012,3000"
    port:       "1433"
    database:   "City"
    username:   "user_me"
    password:   "user_me##2009"

This way YML will only interpret these as strings and not as comments and other stuff.


text:
Q: Iterating through an lazy load array I'm tryin to build an array of hashes and then iterate through.
If I use the code below
    @elements = [{:profile_id=>"123"}, {:profile_id=>"456"}]
    @categories = Array.new
    @elements.each do |element|
     category = Category.find_by_profile_id(element[:profile_id])
     @categories.push(category)
    end

It will find the last object and it will add to the array. However I would like to fetch all the records with that id.
I have been trying the code bellow
    @elements = [{:profile_id=>"123"}, {:profile_id=>"456"}]
    @categories = Array.new
    @elements.each do |element|
     category = RootCategory.where(profile_id: element[:profile_id])
     @categories.push(category)
    end

 #response
 [#<ActiveRecord::Relation [#<Category id: "123", ...">, #<Category id: "123", ..."> #<ActiveRecord::Relation [#<Category id: "456", ...">, #<Category id: "456", ...">]>]

I can't iterate through the returned array. If I try
@categories.each do |t|
   puts t.name
end

#Prints
#Category
#Category

A: This is mostly because you are abusing each for mapping. ActiveRecord::Base#where returns a Relation object (without a loss of generality it might be considered an array here). What you need is Enumerable#flat_map:
elements = [{:profile_id=>"123"}, {:profile_id=>"456"}]
@categories =
  elements.flat_map do |element|
    RootCategory.where(profile_id: element[:profile_id])
  end

or, even better, avoid multiple queries, since where happily accepts an array:
@categories =
  RootCategory.where(profile_id: elements.map { |e| e[:profile_id] })

The latter is basically executing:
RootCategory.where(profile_id: [123, 456])

retrieving categories for all the profiles specified.


text:
Q: Creating multiple tables from one Table and crating unique value as primary Key I have an EXEL file of the movies dataset and it has no primary key. I want to create multiple tables out of it and assign a primary key to each table.
Example: I want to extract the country column and make one separate table with unique countries and primary keys.

A: First import your Excel file in MySQL.
Then, update imported table structure to add an ID column with AUTO_INCREMENT:
ALTER TABLE `test3` ADD `id` INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`id`);

Then CREATE a new table called countries and populate it with countries found in imported table:
INSERT INTO countries (country) VALUES (SELECT DISTINCT(country) FROM imoprted_table;


text:
Q: A limit with determinants I'd be thankful if some could explain to me why the second equality is true...
I just can't figure it out. Maybe it's something really simple I am missing?

$\displaystyle\lim_{\epsilon\to0}\frac{\det(Id+\epsilon H)-\det(Id)}{\epsilon}=\displaystyle\lim_{\epsilon\to0}\frac{1}{\epsilon}\left[\det  \begin{pmatrix}
        1+\epsilon h_{11} & \epsilon h_{12} &\cdots & \epsilon h_{1n} \\
        \epsilon h_{21} & 1+\epsilon h_{22} &\cdots \\
        \vdots &  & \ddots \\
        \epsilon h_{n1} & & &1+\epsilon h_{nn}
        \end{pmatrix}-1\right]$
$\qquad\qquad\qquad\qquad\qquad\qquad=\displaystyle\sum_{i=1}^nh_{ii}=\text{trace}(H)$

A: As I suggested in my comment, we proceed by expanding
$$|Id + \varepsilon H| = |A| = \left| \begin{array}{cccc}
1+\varepsilon h_{11} & \varepsilon h_{12} & \cdots & \varepsilon h_{1n}\\
\varepsilon h_{21} & 1+\varepsilon h_{22} & \cdots & \ \\
\vdots & \ & \ddots & \ &\\
\varepsilon h_{n1} & \ & \ & 1+\varepsilon h_{nn}
\end{array} \right|$$
in powers of $\varepsilon$. First, we have:
$$|A| = (1+\varepsilon h_{11}) \left| \begin{array}{cccc}
1+\varepsilon h_{22} & \varepsilon h_{23} & \cdots & \varepsilon h_{2n}\\
\varepsilon h_{32} & 1+\varepsilon h_{33} & \cdots & \ \\
\vdots & \ & \ddots & \ &\\
\varepsilon h_{n2} & \ & \ & 1+\varepsilon h_{nn}
\end{array} \right| + \varepsilon\sum_{j=2}^n (-1)^{1+j} h_{1j} \det(A_{1j})$$
where $\det(A_{1j}) = O(\varepsilon)$ (here, I am using the usual notation $A_{1j}$ to be the matrix obtained by deleting the first row and $j$th column from $A$).
Justification of this part: The minimal power of $\varepsilon$ would occur when the maximal number of diagonal terms is included. In this case (dealing with $(n-1)\times (n-1)$ minors, this would mean $n-2$ diagonal terms, since all terms of the cofactor expansion along the first row (with the exception of the first one, which I am separating from the rest of the computation) would exclude the $1+\varepsilon h_{11}$, as well as the diagonal entry that sits in the $j$th column. Finally, if there are $n-2$ diagonal terms multiplied together (in the minimal case), then there must be one off-diagonal term, introducing the (claimed) factor of $\varepsilon$.
We hence conclude that $$|A| = (1+\varepsilon h_{11}) \left| \begin{array}{cccc}
1+\varepsilon h_{22} & \varepsilon h_{23} & \cdots & \varepsilon h_{2n}\\
\varepsilon h_{32} & 1+\varepsilon h_{33} & \cdots & \ \\
\vdots & \ & \ddots & \ &\\
\varepsilon h_{n2} & \ & \ & 1+\varepsilon h_{nn}
\end{array} \right| + O(\varepsilon^2)$$
Continuing (inductively) to expand the determinant in this manner, we see that
\begin{align}
|A| &= \prod_{j=1}^n (1+\varepsilon h_{jj}) + O(\varepsilon^2)\\
&= 1+\varepsilon \sum_{j=1}^n h_{jj} + O(\varepsilon^2)
\end{align}
which exactly yields the desired equality, since this immediately says
$$|A|-1 = \varepsilon \sum_{j=1}^n h_{jj} + O(\varepsilon^2),$$
hence
\begin{align}
\lim_{\varepsilon \to 0} \frac{1}{\varepsilon}(|A|-1) &= \lim_{\varepsilon\to 0} \frac{1}{\varepsilon} \left( \varepsilon \sum_{j=1}^n h_{jj} + O(\varepsilon^2) \right)\\
&= \lim_{\varepsilon\to 0} \left( \sum_{j=1}^n h_{jj} + O(\varepsilon) \right)\\
&= \sum_{j=1}^n h_{jj} = \text{Trace}(H)
\end{align}

A: Hint:
$$\left|\begin{matrix}
1+\epsilon h_{11}&\epsilon h_{12}\\
\epsilon h_{21}&1+\epsilon h_{22}\\
\end{matrix}\right|=1+\epsilon h_{11}+\epsilon h_{22}+\epsilon^2\left(h_{11}h_{22}-h_{12}h_{21}\right).$$
Only the main diagonal generates terms in $\epsilon$. This generalizes to higher order, for instance using the expansion by minors.

A: Here is a conceptual proof that avoids expanding a complicated determinant:
The determinant of a linear operator (or of a square matrix) is the product of the eigenvalues, counting multiplicity. The trace of a linear operator (or of a square matrix) is the sum of the eigenvalues, counting multiplicity.
Now suppose that $\lambda_1, \dots, \lambda_n$ are the eigenvalues of $H$, counting multiplicity. Then the eigenvalues of $I + \epsilon H$ are
$$
1 + \epsilon \lambda_1, \dots, 1 + \epsilon \lambda_n,
$$
counting multiplicity. Thus
$$
\det(1 + \epsilon H) = (1 + \epsilon \lambda_1) \cdots (1 + \epsilon \lambda_n).
$$
It is now clear that
\begin{align*}
\lim_{\epsilon\to 0} \frac{ \det(1 + \epsilon H) - 1}{\epsilon} &= \lambda_1 + \dots + \lambda_n\\
&= \text{trace } H,
\end{align*}
as desired.

A: actually, you're trying to calculate the differential $\phi$ of the function $\det : M_n(\mathbb{R}) \rightarrow \mathbb{R}$ at $I_n$, which is defined as
$$\forall H \in M_n(\mathbb{R}), \phi(H) = \lim\limits_{t \to 0} \dfrac{\det(I_n+tH)-\det(I_n)}{t}=
\dfrac{d}{dt}_{t=0} \det(I_n+tH)
$$
First, since $\det$ is a polynomial, it is differentiable at any point and $\phi$ is a linear form on $M_n(\mathbb{R})$. Therefore, it suffices to calculate its value on the canonical basis of $M_n(\mathbb{R})$.

*

*For $H=E_{i,i}$,  $\det(I_n+tE_{i,i})=1+t$, so $\phi(E_{i,i})=1$.

*For $H=E_{i,j},$ where $i \neq j, \det(I_n+tE_{i,j})=1$, so $\phi(E_{i,j})=0$.

So, $\phi=\textrm{Trace}$, since these two linear forms coincide on a basis of $M_n(\mathbb{R})$.

A: Late comments.

*

*This is a special case of Jacobi's formula.

*One way to prove the problem statement using Laplace/cofactor expansion, but easier to understand than other similar approaches and without creating a mess, is to use total derivative. Let
$$
g(t_{11},t_{12},\ldots,t_{nn})=\det\pmatrix{
1+t_{11}h_{11}&t_{12}h_{12}&\cdots&t_{1n}h_{1n}\\
t_{21}h_{21}&1+t_{22}h_{22}&\cdots&t_{2n}h_{2n}\\
\vdots&&\ddots&\vdots\\
t_{n1}h_{n1}&t_{n2}h_{n2}&\cdots&1+t_{nn}h_{nn}},
$$
where each $t_{ij}=t_{ij}(\epsilon)=\epsilon$ (yes, here each $t_{ij}$s is actually identical to $\epsilon$, but we'd like to view it as a function of $\epsilon$). Let also $f(\epsilon)=g\left(t_{11}(\epsilon),t_{12}(\epsilon),\ldots,t_{nn}(\epsilon)\right)$. Then
$$
f'(\epsilon)=\sum_{i,j}\frac{\partial g}{\partial t_{ij}}\frac{\partial t_{ij}}{\partial \epsilon}=\sum_{i,j}\frac{\partial g}{\partial t_{ij}}
$$
and in turn
$$
f'(0)=\sum_{i,j}\left.\frac{\partial g}{\partial t_{ij}}\right|_{t_{ij}=0}.
$$
However, to evaluate $\left.\frac{\partial g}{\partial t_{ij}}\right|_{t_{ij}=0}$, all other $t_{rs}$ are treated as zero and we are effectively finding the derivative of $g$ with respect to a single variable $t_{ij}$. By Laplace expansion along the $i$-row, we see that
$$
\left.\frac{\partial g}{\partial t_{ij}}\right|_{t_{ij}=0}=
\begin{cases}
h_{ii}&\text{ if } i=j,\\
0&\text{ otherwise}.
\end{cases}
$$
Therefore $f'(0)=\sum_i h_{ii}=\operatorname{trace}(H)$.


text:
Q: python copy() but list seems to be passed by copy I found this bit of code here https://brilliant.org/wiki/recursive-backtracking/
from itertools import *
from copy import copy

def is_distinct( list ):
    '''Auxiliary function to is_solved
    checks if all elements in a list are distinct
    (ignores 0s though)
    '''
    used = []
    for i in list:
        if i == 0:
            continue
        if i in used:
            return False
        used.append(i)
    return True

def is_valid( brd ):
    '''Checks if a 3x3 mini-Sudoku is valid.'''
    for i in range(3):
        row = [brd[i][0],brd[i][1],brd[i][2]]
        if not is_distinct(row):
            return False
        col = [brd[0][i],brd[1][i],brd[2][i]]
        if not is_distinct(col):
            return False
    return True

def solve( brd , empties = 9):
    '''
      Solves a mini-Sudoku
      brd is the board
      empty is the number of empty cells
    '''

    if empties == 0:
        #Base case
        return is_valid( brd )
    for row,col in product(range(3),repeat=2):
        #Run through every cell
        cell = brd[row][col]
        if cell != 0:
            #If its not empty jump
            continue
        brd2 = copy( brd )
        for test in [1,2,3]:
            brd2[row][col] = test
            if is_valid(brd2) and solve(brd2,empties-1):
                return True
            #BackTrack
            brd2[row][col] = 0
    return False

Board = [ [ 0 , 0 , 0 ],
          [ 1 , 0 , 0 ],
          [ 0 , 3 , 1 ] ]
solve( Board , 9 - 3 )

for row in Board:#Prints a solution
    print row

It returns the correct result, meaning the solved board.
What I don't understand, is that that the solved() recursive function modified the Board list, but that function never writes to brd, it only writes to brd2, which is a copy.
However, when the list is printed at the end, it shows that it was written to.
So I'm a little confused by this bit of code, I know python functions pass lists by reference, but this example explicitly uses copy(). I'm either confused about copy or am missing something.

A: copy.copy makes a shallow copy. In your case you have a list of lists and a shallow copy just creates a new lists but all elements (the inner lists) still refer to the old lists:
>>> a = [[1,2,3], [2,3,1], [3,1,2]]
>>> b = copy(a)
>>> b[0][0] = 100
>>> a
[[100, 2, 3], [2, 3, 1], [3, 1, 2]]
>>> b
[[100, 2, 3], [2, 3, 1], [3, 1, 2]])

In this case it even works if you don't copy at all, e.g.
brd2 = brd

Generally you can solve this using deepcopy without backtracking or with backtracking but without copy. But combining copy and backtracking seems a bit wasteful.

A: You are creating a shallow copy.
Shallow copy is like when you have an object and it has references to other objects.
So if you copy the main object, you have not copied its inner references. It is still pointing to the same objects as the before main object.
Read more on HERE

The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):

*

*A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

*A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.


text:
Q: Отображение информации с другого сайта. Всем доброго времени суток!
Необходимо, чтобы на моем сайте высвечивалась информация с другого сайта. А именно кусок кода.
Пример:

    8566.00
     руб.

Но суть в том-то, что эта информация высвечивается только для пользователей, которые залогинились.
Какими способами возможно это осуществить?
Стили css не обязательно парсить, главное, чтобы информация отображалась.
A: Если логиниться надо, то применяй для парсинга curl (тут только простым советом не обойтись), а вытащить из спарсенного кода твою сумму поможет регулярка из ответа @TheDoctor
A: Можно как-то так:
<?
$page = file_get_contents('your_site/file');
preg_match('#user-info__account-balance"\s*>\s*\s*([\d\.]+)\s*<\/span>##', $page, $match);

В переменной $match[1] будут твои цифры. Если, конечно, ты залогинен, иначе ничего не найдёшь.


text:
Q: How to bind List dynamically to a DataGrid in WPF? i want to bind list to a datagrid dynamically, following code works for first time, if click add again it is not getting populated in the data grid.

       private List<Item> PopulateItemList()
    {
        return itemLst;
    }
    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
        Item item = new Item();
        item.Item1 = txtItem.Text;
        itemLst.Add(item);
        grdItem.ItemsSource = PopulateItemList();

    }
    private List<Item> itemLst = new List<Item>();

    private void Page_Loaded(object sender, RoutedEventArgs e)
    {
        itemLst.Clear();

    }

Thanks.

A: You should use an ObservableCollection<T> instead of List<T>.
ObservableCollection<T> implements INotifyCollectionChanged, which will tell WPF when you add or remove items.

A: Either you should use ObservableCollection as suggested by Slaks. Otherwise you have to set the datatgrid itemSource null first before populating it again to some other value.
But i would strongly suggest you to use ObservableCollection and you can set it to datagrid's ItemSource in the UserControl's constructor instead of setting it again.


text:
Q: Python listas melhor aluno supondo que tenho x alunos que tiveram x notas. como ponho o nome do aluno que teve a melhor nota?
# coding: iso-8859-1 -*-
import math
nAlunos=0
while True:
    nAlunos=eval(input('Indique o número de alunos:'))
    if 1<=nAlunos<=100:
        break
    else:
        print('O número de alunos tem de ser entre 1 e 100')
        print()
ListaNomes=[0 for i in range(0,nAlunos)]
ListaNotas=[0 for i in range(0,nAlunos)]
reprovados=0
suficiente=0
bom=0
muitobom=0
for i in range(0,nAlunos):
    ListaNomes[i]=input('Nome:')
    while True:
        ListaNotas[i]=eval(input('Nota:'))
        if 0<=ListaNotas[i]<=20:
            if 0<=ListaNotas[i]<10:
                reprovados=reprovados+1
            elif 10<=ListaNotas[i]<14:
                suficiente=suficiente+1
            elif 14<=ListaNotas[i]<17:
                bom=bom+1
            elif 17<=ListaNotas[i]<20:
                muitobom=muitobom+1
            break
        else:
            print('A nota tem de estar entre 0 e 20')
            print()
PercentagemReprovados=(reprovados*100)/len(ListaNotas)
PercentagemSuficiente=(suficiente*100)/len(ListaNotas)
PercentagemBom=(bom*100)/len(ListaNotas)
PercentagemMuitobom=(muitobom*100)/len(ListaNotas)
print()
for i in range(0,nAlunos):
    print(ListaNomes[i])
    print(ListaNotas[i])
print()
print(PercentagemReprovados)
print()
print(PercentagemSuficiente)
print(PercentagemBom)
print(PercentagemMuitobom)
print()
print(max(ListaNotas))
for i in max(ListaNotas[i]):
    print(ListaNomes[i])

a ultima linha está a dar me erro e não estou a perceber como devo adicionar o nome do aluno que teve a nota mais alta

A: você precisa saber a posição da lista de notas que tem a melhor nota e imprimir o nome do aluno na mesma posição. Basta adicionar duas linhas:
argmax = max(enumerate(ListaNotas), key=lambda x: x[1])[0]
print(ListaNomes[argmax])

existem outras maneiras de fazer isso. Se você quiser pegar todos os alunos que tiraram a melhor nota pode fazer:
melhor_nota=max(ListaNotas)
melhores = [ListaNomes[i] for i in range(len(ListaNotas)) if ListaNotas[i] == melhor_nota]


text:
Q: How can I see images from the "cats_vs_dogs" tensorflow dataset I want to see some images from the "cats_vs_dogs" tensorflow dataset.
Using the following code, I can see the first 9 images in the data set.
# Download and prepare the data
tfds.disable_progress_bar()
train_ds, validation_ds, test_ds = tfds.load(
    "cats_vs_dogs",
    # Reserve 10% for validation (from 50% to 60%) and 10% for test (from 60% to 70%)
    split=["train[:50%]", "train[50%:60%]", "train[60%:70%]"],
    as_supervised=True,  # Include labels
)

plt.figure(figsize=(10, 10))
for i, (image, label) in enumerate(iterable = train_ds.take(9), start = 0):
    ax = plt.subplot(3, 3, i + 1)
    plt.imshow(image)
    plt.title(int(label))
    plt.axis("off")

How can I display, for example, the images from 100 to 120?

A: To get the images from 100 to 120, you can use a combination of skip and take. Read more about the available functions of the tf.data.DatasetAPI in the documentation.
ds_img_100_to_120 = train_ds.skip(100).take(20)
# display
for i, (image, label) in enumerate(iterable = ds_img_100_to_120, start = 0):
    ax = plt.subplot(5, 4, i + 1)
    plt.imshow(image)
    plt.title(int(label))
    plt.axis("off")


text:
Q: How can we produce the number x.y, where x and y are the two arguments or a function? Given integer parameters Num1 and Num2, how can a function return the number represented by the decimal numeral x.y, where x is the decimal numeral for Num1 and y is the decimal numeral for Num2. For example, CombineToFloat(1, 5) should return 1.5; CombineToFloat(11, 14) should return 11.14, and CombineToFloat(5, 10) should return 5.10.

A: For positive values of reasonable magnitude, subject to floating-point rounding:
float CombineToFloat(int Num1, int Num2)
{
    float PowerOf10 = 1;
    while (PowerOf10 <= Num2)
        PowerOf10 *= 10;
    return Num1 + Num2/PowerOf10;
}

For hexadecimal:
float CombineToFloat(int Num1, int Num2)
{
    float PowerOf16 = 1;
    while (PowerOf16 <= Num2)
        PowerOf16 *= 0x10;
    return Num1 + Num2/PowerOf16;
}


text:
Q: Scrollbar does not work in tkinter canvas widget after adding labels I have mad an app that ads label to the canvas. I have also set the vertical scrollbar. The problem is that I can not activate scrollbar, the scrollbar does not allow scrolling.
I have used grid_propagate(0) but it still does not work. HOw to activate this feature?
The program does not show me any error.
from tkinter import *

root=Tk()
frame=Frame(root,width=300,height=300)
frame.grid(row=0,column=0)
frame.grid_propagate(0)

canvas=Canvas(frame,width=300,height=300)

vbar=Scrollbar(frame,orient=VERTICAL)
vbar.grid(row=0, column=1,sticky="NS")
vbar.config(command=canvas.yview)

canvas.config(width=300,height=300)
canvas.config(yscrollcommand=vbar.set)
canvas.grid(row=0,column=0)

n=0
m=10
def novi():
    global n
    global m

    n +=1

    m=m+2

    e = Label(canvas, text=m )
    e.grid(row=n,column=0, padx=10, pady=10)

b = Button(root, text="add", command=novi)
b.grid(row=0, column=2,sticky="N")

root.mainloop()

A: You can try doing something like this:

*

*Indicate the scrollregion of the canvas, example:

canvas.config(scrollregion=(0,0, 940, 1200))

*Indicate where to put your widget inside the canvas
 with a code similar to:

canvas.create_window(x, y, window=here_goes_your_widget)

In this example 'x' and 'y' are the coordinates.

As far as I know you must to manually indicate the position of the widget you want to put inside your canvas.
Well, I hope this serves as a help. Hasta la próxima, che!


text:
Q: Xamarin.Android - RSACryptoServiceProvider CspParameters are null and CryptoKeySecurity is null using X509Certificate2 can't find why my RSACryptoServiceProvider returning null values and null CryptoKeySecurity using X509Certificate2 and CspParameters for provider "Microsoft Enhanced RSA and AES Cryptographic Provider".
This code works well on Windows application and signs correctly, but on Xamarin.Android I can't figure out what is wrong. Any help would be nice.
Here is code I'm using:
private RSACryptoServiceProvider ComputeKey()
    {
        var certificateCollection = new X509Certificate2Collection();
        certificateCollection.Import(Data, Password, KeyStorageFlags);
        foreach (var certificate in certificateCollection)
        {
            if (!certificate.HasPrivateKey)
            {
                continue;
            }

            var key = certificate.PrivateKey as RSACryptoServiceProvider;
            var exportParameters = key.ExportParameters(includePrivateParameters: true);
            var cspParameters = new CspParameters
            {
                ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider",
                Flags = UseMachineKeyStore ? CspProviderFlags.UseMachineKeyStore : CspProviderFlags.NoFlags
            };
            var result = new RSACryptoServiceProvider(cspParameters);
            result.ImportParameters(exportParameters);
            return result;
        }

        throw new ArgumentException("The provided certificate does not have any private keys.");
    }

Here is android result:

And here is working windows result:


text:
Q: Optimal circles placement - geospatial I am trying to solve the following problem:

*

*I have 1000 points (lat,lon) scattered on a map

*Each point has a value call it x_i

*I need to put n circles with radii r_i < 5 miles such that the sum of the points' values x_i in the circle is s_i > 200

*Circles can't intersect

I have to maximize the sum of all s_i. The variables are: all r_i, n, positions of circles (which points I pick as centers of my circles).
Can someone help me with some guidance on how to solve something like this?
UPDATE
I am fixing all r_i and we can assume that they have known values from the start.


text:
Q: Getting ClassCast Exception on API 19 but working fine on API 21 I have implemented a material design navigation drawer and a custom toolbar. It works perfectly fine on Lollipop device.
But when run on Android 4.4.4, it crashes with error mentioned below :

java.lang.ClassCastException: android.view.ViewGroup$LayoutParams
  cannot be cast to android.widget.AbsListView$LayoutParams

I have not changed any layout of navigation drawer. Code sample to set up drawer :
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_drawer);

        // Set up the drawer.
        mNavigationDrawerFragment.setup(R.id.fragment_drawer,
                (DrawerLayout) findViewById(R.id.drawer), mToolbar);

LogCat :
 java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
            at android.widget.ListView.setupChild(ListView.java:1826)
            at android.widget.ListView.makeAndAddView(ListView.java:1793)
            at android.widget.ListView.fillDown(ListView.java:691)
            at android.widget.ListView.fillFromTop(ListView.java:752)
            at android.widget.ListView.layoutChildren(ListView.java:1630)
            at android.widget.AbsListView.onLayout(AbsListView.java:2087)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:907)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
            at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
            at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
            at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
            at android.view.View.layout(View.java:14857)
            at android.view.ViewGroup.layout(ViewGroup.java:4643)
            at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2013)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1770)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1019)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5725)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
            at android.view.Choreographer.doCallbacks(Choreographer.java:574)
            at android.view.Choreographer.doFrame(Choreographer.java:544)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

Any help is appreciated.

A: Android has made major changes in AppCompat v21.
So, please refer to this link:
http://android-developers.blogspot.in/2015/04/android-support-library-221.html

A: I also faced the same problem.I used a Adapter for GridView.This error happens when i set LayoutParams of a LinearLayout inside of getView() method. I solved this using this code
linearLayout.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));

instead of
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));

A: Try and use AppCompatv21 .May be then error will not come as Material design will be compatible for prelollipop versions with this AppCompat.
http://android-developers.blogspot.in/2014/10/appcompat-v21-material-design-for-pre.html


text:
Q: displaying wordpress recent posts on a template page with previous and next controls I'm using a wp-query to display on a template page the 5 most recent posts.
it works fine, I want also to add previous and next button to navigate to the previous 5 posts, and so on.
I set 'showposts=5', it displays the 5 most recents post, that's perfect, but when clicking on "previous", it redirect me to /page/2/, but the 5 same posts are displayed...
here is my code :
<?php
    $temp = $wp_query; $wp_query= null;
    $wp_query = new WP_Query(); $wp_query->query('showposts=5' . '&paged='.$paged);
    while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

<a href="<?php the_permalink() ?>"><?php the_time('y-m-d'); ?> | <?php the_title(); ?>

<?php endwhile; ?>

    <?php if ($paged > 1) { ?>

<?php next_posts_link('PREVIOUS POSTS'); ?>

<?php previous_posts_link('NEXT POSTS'); ?>

    <?php } else { ?>

<?php next_posts_link('PREVIOUS POSTS'); ?>

    <?php } ?>

    <?php wp_reset_postdata(); ?>

anyone can help me with this ?
I don't know where's the problem...
thanks for your help

A: i think you are not using the $paged variable;
use $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
before the WP_Query() function

A: Hello Display Recent Post with  Pagination
<?php if ( have_posts() ) : ?>

<?php while ( have_posts() ) : the_post();  ?>

<?php endwhile; ?>

<?php next_posts_link( 'Older posts' ); ?>

<?php previous_posts_link( 'Newer posts' ); ?>

<?php else : ?>

<?php _e('Sorry, no posts matched your criteria.'); ?>

<?php endif; ?>


text:
Q: Extract square matrices from a Nx2 matrix I'm working on matlab 2014, I have a matrix 5124x2 and I want to extract all the 2562 square matrices.
I found that the unique solution is to use mat2Cell, but it doesn't work for me. I don't really need a cell array at the end, what I want is just all the square matrices
%example of data
A = rand(5124,2);
C = mat2cell(A,2,2*ones(2562,1));

I get the following error :
Error using mat2cell (line 106)
Input arguments, D1 through D2, must sum to each dimension of the input matrix size, [5124     2].'

Can you help me please ? Thanks

A: To fix your code, it should be:
C = mat2cell(A,2*ones(2562,1));

And to reshape A into a 3D matrix of 2x2 slices, you can use:
C = permute(reshape(A.',2,2,[]), [2,1,3]);


text:
Q: cordova ionic app seems to load controller twice I'm having some issues with an app I'm creating in Cordova (5.3.3) using ionic (1.6.5) and angular js and building for iOS and Android.
I have a menu item that when I click should load the next state with other menu items. However it seems like it loads the next state once without the animation, then loads the state again with the animation resulting in a "jerky" effect. It's best shown in a video I have uploaded here: https://www.youtube.com/watch?v=YCEQeqFyNl4&feature=youtu.be
I was wondering if anybody has an idea of what could be the issue here and where I should start looking, or if there are known bugs about this?
Any help would be appreciated!

// the controller
.controller('ProgramCtrl', ['$scope', 'FacProgram',
  function($scope, FacProgram) {

    $scope.refresh = function() {
      FacProgram.refresh()
        .finally(function() {
          $scope.$broadcast('scroll.refreshComplete');
        });
    };

    $scope.temp_articles = function() {
      return FacProgram.all();
    };

  }
])

.controller('ProgramDetailCtrl', ['$scope', '$stateParams', 'FacProgram',
  function($scope, $stateParams, FacProgram) {
    $scope.art = FacProgram.get($stateParams.programId);

  }
])

// The factory in a different js file:

.factory('FacProgram', ['$http', '$q', 'FacJson',
function($http, $q, FacJson) {

  var temp_articles = [];

  function findHeader(src, headTag, index) {
    var head = $(src).find(headTag).get(0);
    temp_articles[index].headlinethumb = head.textContent;
    temp_articles[index].headline = head.textContent;
  }

  function refresh() {
    var q = $q.defer();

    ... // A fucntion that get's URL's from .json file
    ////////////////////////////////////////////////////////////
    angular.forEach(urls, function(URL, index) {
      //add the articles to the dictionary
      temp_articles.push({
        inx: index,
        img: img_logos[index]
      });
      $http.get(URL)
        .then(function(sc) {
            // The will parse the html looking for thumbnail text, main body text etc
            var src = sc.data.substring(sc.data.indexOf(''));

            ... // code that parses website for content etc
            ////////////////////////////////////////////////////////
            q.resolve();
          },
          function() {
            q.reject();
          });
    });
  });

return q.promise
}

return {
all: function() {
  return temp_articles;
},
get: function(programId) {
  return temp_articles[programId];
},
refresh: function() {
  console.log('DPG programs refresh triggered');
  temp_articles = []; // a catch to prevent duplicates and to allow other templates to use without
  //contamination
  return refresh()
}
}
}]);

<ion-view>
  <ion-content>

{{art.headlinethumb}}

  </ion-content>
</ion-view>

<ion-view>
  <ion-content>

{{art.headline}}

  </ion-content>
</ion-view>

A: the same happened to me if you put your controller in app.js try removing it from there and only applying it in controller or viceversa.
your state in app.js should look like this:
 .state('state-name', {
    url: '/state-name',
    templateUrl: "templates/walkthrough/state-name.html"
    //Notice no controller here
  })


text:
Q: unique number with function uniqid()
Possible Duplicate:
how is create a unique tracking code

how can create a unique tracking code with function uniqid() for insert in database?
What is your suggestion?
The number of characters not more than 10 and use only of number .
Please call example powerful...
With respect

A: Use the database mechanism to create the id value. Which database are you using?
uniqid() generates a random value that can be eventually doubled. That is a bad solution.
Using time-based functions can duplicate code in concurrent applications.
Finally, you should create a table of identifiers in your database, generate an incremental value each time it is requested.


text:
Q: hdfs log file is too huge after a lot of read and write operation to the hdfs , (i don't know the exact operation that cause this problem).
these two files :
dncp_block_verification.log.curr   ,
dncp_block_verification.log.prev
are more than 200 000 000 000 byte each.
what operation to hdfs may cause these file grow fast?
from the internet I know that I could shotdown the hdfs and delete the log,but it is not the good solution.
how to avoid this problem? thank you very much

A: The block scanner is what is causing the files to grow.  Here's a link to an article explaining the behavior:  http://aosabook.org/en/hdfs.html (Section 8.3.5).
The bug which causes this has been fixed in HDFS 2.6.0

A: I've run into a similar situation with my 20 datanode cluster.  I've seen several reports of this reportedly being a bug.  I'm seeing this behavior with CDH 5.0.2 which runs HDFS 2.3.x.
I had 1 node out of 20 use 100% of all available space because of the two dncp_block_verification logs.  The other nodes seem to have very typical log sizes and I can't figure out why this one node had an issue.
I manually deleted the two files and that resolved my issue with no adverse behavior.  Unfortunately, I don't know of a fix or automated solution to this problem.


text:
Q: Spring Cloud Gateway : How to pass params to custom filter I have a custom filter defined in my application.yml. I need to take some more parameters from that filter definition in YAML, so that I can perform a logic inside my custom filter. I have multiple such routes defined wherein the filter parameters differs. The problem I am facing is, not able to read the values specified in YAML file.
application.yml ---

spring:
  cloud:
    gateway:
      routes:
      - id: test_route
        uri: https://api.rangon.pi
        predicates:
        - Path=/api/staticdata/rattlefeed*
        filters:
        - AddRequestHeader=X-Y-Host, rangon
        - TestGatewayFilter=admin, XY8382, basic

//Is there any way to get "admin, XY8382, basic" in my custom filter class
My filter class
@Component
public class TestGatewayFilter implements
   GatewayFilterFactory<TestGatewayFilter.Config> {

     @Override
     public GatewayFilter apply(Config config) {
         // grab configuration from Config object

         return (exchange, chain) -> {
             Route r = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);

             Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
            // ServerWebExchange route =
            // exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
            // List<GatewayFilter> list = r.getFilters();

            GatewayFilter gwf = r.getFilters().get(r.getFilters().size() - 1);

            Builder builder = exchange.getRequest().mutate();
            // use builder to manipulate the request

            return chain.filter(exchange.mutate().build());
        };
    }

    public Config newConfig() {

        Config c = new Config();
        return c;
    }

    public static class Config {
        // Put the configuration properties for your filter here

    }

}

A: There are two ways to define params for your filters in your configuration file, in this example I'm going to use an application.yml
First of all, you can use the args keyword to define a key-value list of arguments:
spring:
  cloud:
    gateway:
      routes:
        - id: test_route
          uri: https://myapi.com
          filters:
            - name: TestLoggingFilter
              args:
                value: ThisIsATest

And the second form, you can use inline args:
spring:
  cloud:
    gateway:
      routes:
        - id: test_route
          uri: https://myapi.com
          filters:
            - TestLoggingFilter=ThisIsATest

If you want to use inline args make sure to override the shortcutFieldOrder method in your filter with an array containing the name of the params you want to receive, this array is also used to define the order of the params.
The following is an example of a simple filter that works with any of the previous definitions, as this example override shortcutFieldOrder as well:
package com.es.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.List;

@Component
public class TestLoggingFilter implements GatewayFilterFactory<TestLoggingFilter.Config> {

    private static final Logger LOG = LoggerFactory.getLogger(TestLoggingFilter.class);

    private static final String VALUE = "value";

    @Override
    public Config newConfig() {
        return new Config();
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(VALUE);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            LOG.info("Filter enabled with value: " + config.value);
            return chain.filter(exchange);
        };
    }

    public static class Config {

        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}


text:
Q: Python - concatenate two same columns and leave other unchanged i have some data like
>>> df1
  Col1     Col2
0   Hi    Hello
1  How     Fine
2  Why  Because
3  You       Me
4   We     They
>>> df2
      Col1   Col2
0       Mr    Mrs
1  Welcome    Bye
2      Wow    Ohh
3      Sit  Stand

I want to concatenate only the first Column Col1 of these two dataframes and update the df1 leaving Col2 unchanged but i am unable to do it
i tried many ways but failed doing this
Output I want
>>> df2
  Col1     Col2
0   Hi    Hello
1  How     Fine
2  Why  Because
3  You       Me
4  We     They
5  Mr
6  Welcome
7  Wow
8  Sit

It doesnt matter if index is different or there comes NaN instead of Empty Cells
Things i Tried
1
>>> r=pd.concat([df1["Col1"],df2["Col1"]])
>>> df1["Col1"] = r.reset_index(drop=True)
>>> df1
  Col1     Col2
0   Hi    Hello
1  How     Fine
2  Why  Because
3  You       Me
4   We     They

2
>>> pd.concat([df1["Col1"],df2])
     0     Col1   Col2
0   Hi      NaN    NaN
1  How      NaN    NaN
2  Why      NaN    NaN
3  You      NaN    NaN
4   We      NaN    NaN
0  NaN       Mr    Mrs
1  NaN  Welcome    Bye
2  NaN      Wow    Ohh
3  NaN      Sit  Stand

3
I Tried append(), merge() and some more techniques but failed

A: append
df1.append(df2[['Col1']])

      Col1     Col2
0       Hi    Hello
1      How     Fine
2      Why  Because
3      You       Me
4       We     They
0       Mr      NaN
1  Welcome      NaN
2      Wow      NaN
3      Sit      NaN

concat
pd.concat([df1, df2[['Col1']]])

      Col1     Col2
0       Hi    Hello
1      How     Fine
2      Why  Because
3      You       Me
4       We     They
0       Mr      NaN
1  Welcome      NaN
2      Wow      NaN
3      Sit      NaN

In either case, you can pass the ignore_index=True option to ignore the index.
df1.append(df2[['Col1']], ignore_index=True)

      Col1     Col2
0       Hi    Hello
1      How     Fine
2      Why  Because
3      You       Me
4       We     They
5       Mr      NaN
6  Welcome      NaN
7      Wow      NaN
8      Sit      NaN