text:
Q: If $A$, $B$, and & $C$ are angles of a triangle. Find angle $C$. System of equations involving trigonometric functions. If $A$, $B$, and & $C$ are angles of a triangle and
$5\sin(A) + 12\cos(B) = 15$
$12\sin(B) + 5\cos(A) = 2$
Find angle $C$.
I ended up with $\sin(A+B) = \frac{1}{2}$ and there seems to be two values of $C$ which are $30°$ and $150°$. How would I know which is correct? Or are both answers considered correct?

A: Assuming that $sin(A+B) = \dfrac{1}{2}$ is correct, you can use the first equation:
$$5\cdot sin(A) + 12 \cdot cos(B) = 15$$
$$\Rightarrow 12 \cdot cos(B) = 15 - 5\cdot sin(A)$$
using $0 < sin(A) < 1$ for $A \in (0, \pi)$
$$\Rightarrow 12 \cdot cos(B) \ge 10$$
$$\Rightarrow cos(B) \ge \dfrac{10}{12}$$
From this, we can safely conclude that $B \le 57°$.
Second, from the second equation, we get:
$$sin(A) = \dfrac{2-5\cdot cos(B)}{12}$$
$$sin(A) \le \dfrac{2}{12}$$
And therefor: $A\le 10°$.
Therefor, C cannot be $30°$ and must be $150°$!

A: Squaring and summing give:$$25+144+120\sin(A+B)=225+4$$ or
$$\sin(A+B)=\frac{1}{2},$$ which gives $C=30^{\circ}$, which contradicts with the first equality , or $C=150^{\circ}.$
Indeed, if $A+B=30^{\circ}$, so $A<30^{\circ}$ and
$$12\cos B=15-5\sin A>15-5\cdot\frac{1}{2}=12.5>12,$$ which is impossible.


text:
Q: Decipher Peewee ORM Postgres query error I'm using Peewee in my Flask project. I have an ORM query which worked in SQLite, but is now causing an error as I'm migrating to Postgres. I wondered if anyone could help me diagnose it:
stats = (
    Assignment.select(
        Type.name,
        fn.COUNT(Type.id).alias('total'),
        Assignment.select(
            fn.COUNT(Assignment.id)
        ).where(
            (Assignment.due_date < fn.Now()) & (StudentCourses.student == self) & (Assignment.type == Type.id)
        ).group_by(Assignment.type, StudentCourses.student).alias('completed')
    )
    .naive().join(Type)
    .join(StudentCourses, on=(StudentCourses.course == Assignment.course))
    .where(StudentCourses.student == self)
    .order_by(Type.id)
    .group_by(Type.name, StudentCourses.student)
)

Here's the resulting SQL:
SELECT "t2"."name",
       COUNT("t2"."id") AS total,
  (SELECT COUNT("t4"."id")
   FROM "assignment" AS t4
   WHERE ((("t4"."due_date" < Now())
           AND ("t3"."student_id" = 2))
          AND ("t4"."type_id" = "t2"."id"))
   GROUP BY "t4"."type_id",
            "t3"."student_id") AS completed
FROM "assignment" AS t1
INNER JOIN "type" AS t2 ON ("t1"."type_id" = "t2"."id")
INNER JOIN "studentcourses" AS t3 ON ("t3"."course_id" = "t1"."course_id")
WHERE ("t3"."student_id" = 2)
GROUP BY "t2"."name",
         "t3"."student_id"
ORDER BY "t2"."id"

And here's the error I'm getting:
ProgrammingError: subquery uses ungrouped column "t2.id" from outer query
LINE 1: ...ND ("t3"."student_id" = 2)) AND ("t4"."type_id" = "t2"."id")...

I've tried adding the indicated columns to the group_by clause but I'm not getting any love. Does anyone have any guidance on this? Would love a fresh pair of eyes.

A: Your subquery is effectively joining on the outer query's Type table, so postgres is saying you need to group by Type.id in the COUNT subquery.

redpajama_set_name: RedPajamaStackExchange


text:
Q: a list converted into select options by javascript for mobile, not working on IOS mobile browsers I'm trying to create a select options with javascript for mobile, the data is coming from a list of links but it doesn't work only on IOS.
this is where the list is coming from links
var listSelect = document.querySelector(".epgtvm_select-country");
var countries = document.querySelectorAll(".epgtvm_structure-container ol a");

and here is the entire function, but it doesn't work on IOS
function mobileCountries() {

  //create  the select element for the dropdown list before the ol
      var selectList = document.createElement("select");
      selectList.setAttribute('data-selectconverted', 'true');
      listSelect.appendChild(selectList);

  var countries = document.querySelectorAll(".epgtvm_structure-container ol a");
  var countryOrder = [];

  //arrange country name and url in alphabetical order
  countries.forEach(function(val) { //forEach for countries in <option>
    countryOrder.push({
      'name': val.innerText,
      'url': val.href
    });
    countryOrder.sort(dynamicSort("name"));
    // return this;
  });

  //Create the option elements for the dropdown
  countryOrder.forEach(function(val) {
    var optionElement = document.createElement("option");
    //optionElement.innerHTML += val.name;
    optionElement.innerText = val.name;
    optionElement.label = val.name;
    optionElement.value = val.url;
    selectList.appendChild(optionElement);
  });

  selectList.setAttribute('onblur', 'window.location = this.value;'); //onchange submit for the select
}
}
//DOM CONTENT READY
window.addEventListener("load", mobileCountries);

so the code takes all the links and create option elements inside a select tag, its working everywhere but in IOS, does anyone have a clue what could it be?
thank you

A: Try using the Option constructor instead:
  // Create the option elements for the dropdown
  countryOrder.forEach(function(val) {
    selectList.appendChild(new Option(val.name, val.url));
  });

A: THANK YOU!! I know it was quite some time ago but yes! the appendchild worked instead of the innertext.
countryOrder.forEach(function(val){
    var optionElement = document.createElement("option");
    optionElement.appendChild(document.createTextNode(val.name));
    optionElement.value= val.url;
    selectList.appendChild(optionElement);
  });


text:
Q: How can i get some sequential revision number in git I am deploying the changes in dev site and some times the coders say that they have fixed the chnages in revision pushed today.
In mercurial i used to have at the botoom of the page the revision number like r223 so that user will know that current revision is r225so its not the latest.
But in git i have only hash which is difficult to get if thats old revision than the mater now.
Is it possible to get some sequential number to be displayed on dev site so that i know how far dev site is behind

A: There is no way to do this in Git.
Git is distributed version control system, therefore any type of hooks or external counters can't guarantee sequential and uniqueness


text:
Q: Website character encoding I have a website in Turkish language. I have the text in turkish and shows well in the editor. When i publish it and view it in the browser;
the term : müdürlügü
shows as :  m�d�rl�g�
How can i avoid this?
Character encoding of the site is : UTF-8

A: On your webpage, set character encoding to UTF-8:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />

A: HTML entities: http://www.fileformat.info/info/unicode/char/search.htm
Your character for instance, can be found here: http://www.fileformat.info/info/unicode/char/00fc/index.htm


text:
Q: List storing matrices as characters instead of binary R Hello I have created a list with the following loop
portfolio_covlist2<-list()
for (i in 1:25) {
  a<-covst[Stock.mix.2[i,],Stock.mix.2[i,]]
  a<-list(matrix(a,nrow=2))
    portfolio_covlist2[i] <- a
}

The data then look like this
[[1]]
            [,1]        [,2]
[1,] 0.009168161 0.001283940
[2,] 0.001283940 0.002723437

[[2]]
            [,1]        [,2]
[1,] 0.021906044 0.002600486
[2,] 0.002600486 0.009508103

I want to then be able to multiply these like
w2*portfolio_covlist2[1]*t(w2)

to give me a standard deviation of the mixes.  but I get this error:
Error in w2 * portfolio_covlist2[1] :
  non-numeric argument to binary operator

the w vectors confirm as numeric but the list types do not...HELP!
thanks

A: You are inadvertently trying to multiple a list instead of a matrix.
And incidentally, I think you want %*% for matrix multiplication instead of * which will do element-wise multiplication.
L <- list(structure(c(0.009168161, 0.00128394, 0.00128394, 0.002723437), .Dim = c(2L, 2L)), structure(c(0.021906044, 0.002600486, 0.002600486, 0.009508103), .Dim = c(2L, 2L)))

m <- matrix(1:4, nr=2)

m %*% L[1] %*% t(m)
# Error in m %*% L[1] : requires numeric/complex matrix/vector arguments
1
m %*% L[[1]] %*% t(m)
#            [,1]       [,2]
# [1,] 0.04138273 0.06385697
# [2,] 0.06385697 0.10079068

The reason is that with list, the [ operator returns a list with the selected elements within it, while [[ returns a single (not-listed) element:
L[1]
# [[1]]                         <--- this means it is still in a list, even just length 1
#             [,1]        [,2]
# [1,] 0.009168161 0.001283940
# [2,] 0.001283940 0.002723437

L[[1]]
#             [,1]        [,2]
# [1,] 0.009168161 0.001283940
# [2,] 0.001283940 0.002723437


text:
Q: I am not able to update a variable through sed command I have assigned two variables but not able to update
x=$(cat /scratch/env.properties | grep ConfigPath)
y=$(ConfigPath=/scratch/a/b)

then sed to replace ConfigPath in env.properties
sed 's/$x/$y/' env.properties

This is not updating ConfigPath in env.properties as assigned in $y

A: First, you don't need cat with grep.  That is enough:
x="$(grep ConfigPath /scratch/env.properties)"

Second, I believe this is not an assignment you want:
y=$(ConfigPath=/scratch/a/b)

If you want variable y to hold ConfigPath=/scratch/a/b string it should be:
y="ConfigPath=/scratch/a/b"

$(...) is a command substitution in Bash.
Third, you should use double quotes in sed command to make shell expand x and y:
sed "s/$x/$y/" env.properties

Also notice that / is a poor choice when working with Unix paths
because it is the delimiter. Use another character, for example
comma:
sed "s,$x,$y," env.properties

As noted by user
Kusalananda
in the comment below you make this easier and better by using sed only and
making sure that ConfigPath is at the beginning of the line:
sed "s,^ConfigPath=.*$,ConfigPath=/scratch/a/b," env.properties


text:
Q: how to use the same object on different classes in python? This is probably a very basic question.
I have some objects that I want to be created once and then used by many classes of my application, for instance "logging" and "db". I don't wanna make a new connection to the DB everytime a different class wants to do something.
So my idea was to create a Class like:
class MyDB(object):
    mydb=createMySQLconnection()

then I'd do "from ... import MyDB" and use MyDB.mydb
would it work? is this the best way to do that?

A: This would work, but there's no reason to create a class. Just put mydb in a module as a free-standing variable.
Often, when you'd use a singleton in other programming languages, you can get by in Python with a module.


text:
Q: asyncio with map&reduce flavor and without flooding the event loop I am trying to use asyncio in real applications and it doesn't go that
easy, a help of asyncio gurus is needed badly.
Tasks that spawn other tasks without flooding event loop (Success!)
Consider a task like crawling the web starting from some "seeding" web-pages. Each
web-page leads to generation of new downloading tasks in exponential(!)
progression. However we don't want neither to flood the event loop nor to
overload our network. We'd like to control the task flow. This is what I
achieve well with modification of nice Maxime's solution proposed here:
https://mail.python.org/pipermail/python-list/2014-July/687823.html
map & reduce (Fail)
Well, but I'd need as well a very natural thing, kind of map() & reduce()
or functools.reduce() if we are on python3 already. That is, I'd need to
call a "summarizing" function for all the downloading tasks completed on
links from a page. This is where i fail :(
I'd propose an oversimplified but still a nice test to model the use case:
Let's use fibonacci function implementation in its ineffective form.
That is, let the coro_sum() be applied in reduce() and coro_fib be what we apply with
map(). Something like this:
@asyncio.coroutine
def coro_sum(x):
    return sum(x)

@asyncio.coroutine
def coro_fib(x):
    if x < 2:
        return 1
    res_coro =
executor_pool.spawn_task_when_arg_list_of_coros_ready(coro=coro_sum,

 arg_coro_list=[coro_fib(x - 1), coro_fib(x - 2)])
    return res_coro

So that we could run the following tests.
Test #1 on one worker:
executor_pool = ExecutorPool(workers=1)
executor_pool.as_completed( coro_fib(x) for x in range(20) )

Test #2 on two workers:
executor_pool = ExecutorPool(workers=2)
executor_pool.as_completed( coro_fib(x) for x in range(20) )

It would be very important that both each coro_fib() and coro_sum()
invocations are done via a Task on some worker, not just spawned implicitly
and unmanaged!
It would be cool to find asyncio gurus interested in this very natural goal.
Your help and ideas would be very much appreciated.
best regards
Valery

A: There are multiple ways to compute fibonacci series asynchroniously. First, check that the explosive variant fails in your case:
@asyncio.coroutine
def coro_sum(summands):
    return sum(summands)

@asyncio.coroutine
def coro_fib(n):
    if   n == 0: s = 0
    elif n == 1: s = 1
    else:
        summands, _ = yield from asyncio.wait([coro_fib(n-2), coro_fib(n-1)])
        s = yield from coro_sum(f.result() for f in summands)
    return s

You could replace summands with:
a = yield from coro_fib(n-2) # don't return until its ready
b = yield from coro_fib(n-1)
s = yield from coro_sum([a, b])

In general, to prevent the exponential growth, you could use asyncio.Queue (synchronization via communication), asyncio.Semaphore (synchonization using mutex) primitives.


text:
Q: Add new object on Session create Im new here! I have a session on my application. Iam using ADONIS on my API. How I can attach new object,  user_company when user login (session create).
    class SessionController {
  async store ({ request, response, auth }) {
    const { email, password } = request.all()

    const session = await User.findByOrFail('email', email)

    return { session }
  }
}

On my database, I have a FK to Company table. Thank you!

A: I know it's you first post... Next time, try to explain better your problem, and you will get best answers. I presume you are using a ORM, Adonis uses Lucid as ORM. With Lucid, you have two ways to do that.
1) FIRST
const session = await User.findByOrFail('email', email)
await session.load('company')

2) SECOND
const session.query().where('email', email).with('company')

Also, you can choose the fields to show.
1) FIRST
const session = await User.findByOrFail('email', email)
await session.load('company', company => {
company.setVisible(['name'])
})

2) SECOND
const session.query().where('email', email).with('company', (company) => {
    company.setVisible(['name'])
}


text:
Q: Utilizing Tkinter's Grid Manager to Center Buttons But also Fill Entire Frame I am using Tkinter to design a dialog box.  One of the things I want in the box is a set of buttons that doing something.  I want to add these to a frame I've created, but am having trouble.  I want the frame to show the background color and the buttons to be centered in that frame.  Right now, I can only figure out how to do one or the other.  If I include the sticky=N+S+E+W in the frame's grid placement, the whole frame is filled by the background color, but the buttons are stuck to the top left.   If I don't include the sticky, the buttons are centered beautifully, but you can only see a small portion of the background color.
How can you make both of these things happen?

Thanks so much.  Here is my code:

from tkinter import *

def clearA():
    pass

root = Tk()
root.geometry("800x400")

for r in range(2):
    root.rowconfigure(r, weight=1)
for c in range(5):
    root.columnconfigure(c, weight=1)

clearButtonsFrame = Frame(root, bg='#E0EEEE')
clearButtonsFrame.grid(row = 0, column = 0, rowspan = 3, columnspan = 6, sticky=N+E+S+W)

clearButton = Button(clearButtonsFrame, text="Button 1", width=40)
clearButton.grid(row =0, column=0, padx=10)

selectButton = Button(clearButtonsFrame, text="Button 2", width=40)
selectButton.grid(row =0, column=1)

root.mainloop()

A: from tkinter import *

def clearA():
    pass

root = Tk()
root.geometry("800x400")
root.configure(background='lightblue')  # You can configure background color

for r in range(2):
    root.rowconfigure(r, weight=1)
for c in range(5):
    root.columnconfigure(c, weight=1)

clearButtonsFrame = Frame(root, bg='#E0EEEE')
clearButtonsFrame.grid(row = 0, column = 0, rowspan = 3, columnspan = 6)

clearButton = Button(clearButtonsFrame, text="Button 1", width=40)
clearButton.grid(row =0, column=0, padx=10)

selectButton = Button(clearButtonsFrame, text="Button 2", width=40)
selectButton.grid(row =0, column=1)

root.mainloop()

You can configure background color by using root.configure(background='whatever color'). I've removed the N+E+S+W and just added the configuration line, so that the background color stays and the buttons are centered.

A: You are maybe complicating things a bit.
The buttons are in their own frame; what you have to do is (1) ensure that the buttons are centered vertically, and placed on each side relative to the center, in that frame. (2) you have to ensure that the frame fills the container it will be placed into, instead of shrinking around its widgets.
I suggest to pack the frame inside root, using the kwargs expand=True, and fill=tk.BOTH to fulfill (2). You could use grid for a more complicated layout, but in the example provided, that is not necessary.
Inside the frame, you can place the buttons relative to the center using anchor=tk.CENTER, halfway in the vertical direction rely=0.5, and centered on the left half, and the right half in the horizontal direction relx=0.25 and relx=0.75
You can now resize root, and the proportional layout of the buttons will remain the same.
import tkinter as tk

root = tk.Tk()
root.geometry("800x400")

clearButtonsFrame = tk.Frame(root, bg='cyan')
clearButtonsFrame.pack(expand=True, fill='both')

clearButton = tk.Button(clearButtonsFrame, text="Button 1", width=40)
clearButton.place(relx=0.25, rely=0.5, anchor=tk.CENTER)

selectButton = tk.Button(clearButtonsFrame, text="Button 2", width=40)
selectButton.place(relx=0.75, rely=0.5, anchor=tk.CENTER)

root.mainloop()


text:
Q: Не работает Magnific popup Не работает Magnific Popup, если контент изменился асинхронно.
Есть календарик на сайте, но при смене месяца на Апрель модальное окно при клике на дату не открывается, хотя после перезагрузки страницы работает.
Вызывал окно
$(".popup").magnificPopup({
       type: 'inline'
});

A: Потому что на момент загрузки страницы Апреля еще не было.
$('#Calendar').on('click','.popup',function(){
    $.magnificPopup.open({
        items: {
            src: '#popup_form_cal',
            type: 'inline'
        }
    });
});


text:
Q: Loop calling an asynchronous function Introduction to the problem
I need to call an asynchronous function within a loop until a condition is satisfied. This particular function sends a POST request to a website form.php and performs some operations with the response, which is a JSON string representing an object with an id field. So, when that id is null, the outer loop must conclude. The function does something like the following:
function asyncFunction(session) {
    (new Request({
        url: form.php,
        content: "sess=" + session,
        onComplete: function (response) {
            var response = response.json;
            if (response.id) {
                doStaff(response.msg);
            } else {
                // Break loop
            }
        }
    })).get();
}

Note: Although I've found the problem implementing an add-on for Firefox, I think that this is a general javascript question.

Implementing the loop recursively
I've tried implementing the loop by recursivity but it didn't work and I'm not sure that this is the right way.
...
    if (response.id) {
        doStaff(response.msg);
        asyncFunction(session);
    } else {
        // Break loop
    }
...

Using jsdeferred
I also have tried with the jsdeferred library:
 Deferred.define(this);
 //Instantiate a new deferred object
 var deferred = new Deferred();

 // Main loop: stops when we receive the exception
 Deferred.loop(1000, function() {
      asyncFunction(session, deferred);
      return deferred;
 }).
 error(function() {
     console.log("Loop finished!");
 });

And then calling:
...
    if (response.id) {
        doStaff(response.msg);
        d.call();
    } else {
        d.fail();
    }
...

And I achieve serialization but it started repeating previous calls for every iteration. For example, if it was the third time that it called the asyncFunction, it would call the same function with the corresponding parameters in the iterations 1 and 2.

A: Your question is not exactly clear, but the basic architecture must be that the completion event handlers for the asynchronous operation must decide whether to try again or to simply return.  If the results of the operation warrant another attempt, then the handler should call the parent function.  If not, then by simply exiting the cycle will come to an end.
You can't code something like this in JavaScript with anything that looks like a simple "loop" structure, for the very reason that the operations are asynchronous.  The results of the operation don't happen in such a way as to allow the looping mechanism to perform a test on the results; the loop may run thousands of iterations before the result is available. To put it another way, you don't "wait" for an asynchronous operation with code. You wait by doing nothing, and allowing the registered event handler to take over when the results are ready.

A: Thank you guys for your help. This is what I ended doing:
var sess = ...;
Deferred.define(this);
function asyncFunction (session) {
    Deferred.next(function() {
        var d = new Deferred();
        (new Request({
              url: form.php,
              content: "sess=" + session,
              onComplete: function (response) {
                  d.call(response.json);
              }
        })).get();
        return d;
    }).next(function(resp) {
        if (resp.id) {
            asyncFunction(session);
            console.log(resp.msg);
        }
    });
}

asyncFunction(sess);

A: Why wouldn't you just use a setInterval loop? In the case of an SDK-based extension, this would look like:
https://builder.addons.mozilla.org/addon/1065247/latest/
The big benefit of promises-like patterns over using timers is that you can do things in parallel, and use much more complicated dependencies for various tasks. A simple loop like this is done just as easily / neatly using setInterval.

A: If I correctly understand what you want to do, Deferred is a good approach. Here's an example using jQuery which has Deferred functionality built in (jQuery.Deferred)
A timeout is used to simulate an http request.  When each timeout is complete (or http request is complete) a random number is returned which is equivalent to the result of your http request.
Based on the result of the request you can decide if you need another http request or want to stop.
Try out the below snippet. Include the jQuery file and then the snippet.  It keeps printing values in the console and stops after a zero is reached.
This could take while to understand but useful.
$(function() {

    var MAXNUM = 9;

    function newAsyncRequest() {
        var def = $.Deferred(function(defObject) {
            setTimeout(function() {
                defObject.resolve(Math.floor(Math.random() * (MAXNUM+1)));
            }, 1000);
        });

        def.done(function(val) {
            if (val !== 0)
                newAsyncRequest();
            console.log(val);
        });

    };

    newAsyncRequest();
});

Update after suggestion from @canuckistani
@canuckistani is correct in his answer.  For this problem the solution is simpler. Without using Deferred the above code snippet becomes the following. Sorry I led you to a tougher solution.
$(function() {

    var MAXNUM = 9;

    function newAsyncRequest() {
        setTimeout(function() {
            var val = Math.floor(Math.random() * (MAXNUM+1));
            if (val !== 0)
                newAsyncRequest();
            console.log(val);
        }, 1000);
    }

    newAsyncRequest();

});


text:
Q: Managing element references in javascript projects I just spend an hour over a bug that came down to using two different names for an element id.
I would like to know what is best practice to organise those. In Java I would create constants from string literals and refer to those.
I'm using handlebars, so I can inject element names into templates. I would not know how to organise CSS. Ans how to have a central 'repository' of references.
Many thanks

A: I'm no expert on this subject myself, but I was where you are at a year ago. It was really tough to handle everything. The Javascript/HTML/CSS combo quickly became overwhelming. My best advice is: don't use element IDs. Try to generalize everything into classes. (Working with Bootstrap taught me a lot about how that could be done efficiently.)
And when that's not enough, break your templates into smaller templates. Don't have one large Handlebars template, have 15 small ones. Then use a helper to render them within each other. Breaking your templates into smaller pieces will keep your CSS and JS code in small, cohesive chunks. You'll soon have a CSS file that isn't the CSS file for your page, but the CSS file that contains a different section for each of your templates.
As I said, I'm no expert, but this is what helped me. I came into web development last August with a strong C++ background and this is what finally clicked with me. Basically, it's one of the golden rules of programming: smaller, more modular chunks of code are always easier to deal with. :)


text:
Q: Oracle - using bind variable in LIKE clause of dynamic cursor I am using dynamic cursor for fetching data. Query that is being executed looks similar to:
query := 'SELECT column1, column2
          FROM my_table
          WHERE column1 LIKE ''%:bv1%''';

And the cursor itself is executed like this:
OPEN my_cursor FOR query USING my_var1;

I also tried to check the query and print it:
... WHERE column1 LIKE '%:bv1%' ...

so apostrophes are escaped, but the cursor fetches no data. Is it even possible to use bind variables in LIKE clause and if yes, what did I do wrong?

A: Take the bind variable out of the string:
VARIABLE mycursor REFCURSOR;
VARIABLE bv1 VARCHAR2;

BEGIN
  :bv1 := 'X'; -- set the bind variable
END;
/

DECLARE
  query VARCHAR2(200) := 'SELECT * FROM DUAL WHERE DUMMY LIKE :value';
BEGIN
  OPEN :mycursor FOR query USING '%' || :bv1 || '%';
END;
/

PRINT mycursor;

Output
MYCURSOR
--------
DUMMY
-----
X

A: This is a subtle one. It's often useful to start with a static statement, get that right, then convert it to dynamic SQL.
In non-dynamic SQL we might do it like this:
 SELECT column1, column2
 FROM my_table
 WHERE column1 LIKE '%' || local_var || '%';

The dynamic equivalent is
query := 'SELECT column1, column2
          FROM my_table
          WHERE column1 LIKE ''%''||:bv1||''%'' ';


text:
Q: How do you visualize multiplications that occur with numpy whole arrays method? I am currently studying numerical methods and an inefficient way of performing calculations in numerical methods would be to iterate through arrays grid by grid like below:
    for it in range(maxit):
    for j in range(1,mesh.Nj-1):
        for i in range(1,mesh.Ni-1):
            u_new[j,i] = C_beta*(u_new[j-1,i]+u_new[j+1,i]+
                              beta_sq*(u_new[j,i-1]+u_new[j,i+1]))

Another way to do this is by using numpy whole arrays as follow:
for it in range(maxit):
    u_new[1:-1,1:-1] = C_beta*(mesh.u[:-2,1:-1]+mesh.u[2:,1:-1]+
                              beta_sq*(mesh.u[1:-1,:-2]+mesh.u[1:-1,2:]))

Both leads to the same result but I am having a hard time to visualize how the 2nd method works.

How do you "read" the multiplication and addition going on in each iteration?
I hope my question make sense. Thank you :)


text:
Q: Error when I try to use NSTimer to change View Controller(EXC_BAD_INSTRUCTION) I am trying to change a view controller after an animation. I used an NSTimer to change the view controller after the animation is done. The animation takes place on the default ViewController given. After this animation runs once, it's supposed to use the prepareForSegue function and go to the second view controller. When I run it, the animation works, but it doesn't change view controllers.

import UIKit

class ViewController: UIViewController, UIViewControllerTransitioningDelegate {
    @IBOutlet weak var imageView: UIImageView!

    var timer = NSTimer()

    override func viewDidLoad() {
        super.viewDidLoad()

        var imagesNames = ["stairs", "stairs2", "stairs3", "stairs4", "stairs5", "stairs6", "stairs7", "stairs8", "stairs9", "stairs10", "stairs11", "stairs12", "stairs13", "stairs14", "stairs15", "stairs16", "stairs17", "stairs18", "stairs19", "stairs20", "stairs21", "stairs22", "stairs23", "stairs24", "stairs25", "stairs26", "stairs27", "stairs28", "stairs29", "stairs30", "stairs31", "stairs32", "stairs33", "stairs34", "stairs35", "stairs36", "stairs37", "stairs38", "stairs39", "stairs40", "stairs41", "stairs42", "stairs43", "stairs44", "stairs45", "stairs46","stairs47", "stairs48", "stairs49", "stairs50", "stairs51","stairs52", "stairs53", "stairs54", "stairs55", "stairs56","stairs57"]

        var images = [UIImage]()

        for i in 0..<imagesNames.count{
            images.append(UIImage(named: imagesNames[i])!)
        }

        imageView.animationImages = images;
        imageView.animationDuration = 4;
        imageView.startAnimating()

        _ = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(timeToMoveOn), userInfo: nil, repeats: false)
    }

    func timeToMoveOn() {
        self.performSegueWithIdentifier("goToMainUI", sender: self)
    }

A: There's a clue in the console output in your screenshot.
You're implicitly unwrapping imageView but it is nil. This probably means that there's no image view connected to that outlet.


text:
Q: OAuth 2.0 - REST API Testing TOSCA I have tried to authenticate OAuth 2.0 REST API, added
Grant Type - Authorization Code
Authorization Endpoint -
Token Endpoint -
Redirect URI -
Client ID -
Client Secret -
As I am using Microsoft AD connect authentication, it is not showing any browser to enter my User ID and Password. Could any one help me?
Also I am getting error after requesting a token: -
"error": "ORA-12514: TNS:listener does not currently know of service requested in connect descriptor"


text:
Q: Azure AD access token from postman Today, I have an issue getting an Azure AD access token from Postman. This is while it was working before for the same app and other apps I am working on. But none of them are working today.
I was working correctly, but now it shows me this error:
Error: AADSTS900144: The request body must contain the following parameter: 'client_id'
I use https://login.microsoftonline.com/common/oauth2/v2.0/authorize as auth URL, and https://login.microsoftonline.com/common/v2.0/token for Access token URL.
I have tried these for access token URL but none of them worked. https://login.microsoftonline.com/{{tenant_id}}/v2.0/token
https://login.microsoftonline.com/common/token
https://login.microsoftonline.com/{tenant_id}/token
here is my Azure AD oauth 2.0 configuration. Also, as you see, there is no client_id in the request body.

A: I tried to reproduce the same in my environment and got below results
You can get values of auth URL and access token URL from your Azure AD application that varies based on supported account type like below:
Go to Azure Portal -> Azure Active Directory -> App registrations -> Your App -> Overview -> Endpoints

Now I added environment variables in Postman by defining them like below:

Make sure to select the correct Environment while requesting for token with variables.
I filled the required details same as you to get the access token like below:

When I selected Get New Access Token, I got the token successfully as below:

The error usually occurs if you missed including client_id while
acquiring access token.

I changed  client_id parameter to blank in variables like below:

When I tried to get access token again, I got same error as you like below:

To resolve the error, make sure to pass client_id value in right environment and save it.

A: I found out why it's acting like this:
I checked my friend's PC, and it was working there!
The issue was the last update of Postman. They have changed something in authorization.
just change the Client Authentication to Send client credentials in body and it will work.


text:
Q: summarize is not taking into account group_by R What's wrong with this code? trying to get grouped means by Parameter name which is the names of the chemicals, there are multiple arithmetic means for each chemical in the column and they are numeric and the names are characters.
Q2<-daily_SPEC %>%
             group_by('Parameter Name', add=FALSE)%>%
             summarize(Mean_by_chemical=mean(daily_SPEC$"Arithmetic Mean",
na.rm=TRUE))
Q2
  Mean_by_chemical
1          105.401


text:
Q: Ruby on Rails - how to make .where method case insensitive I have this method, which works great:
def find
  return User.where(:name=> params[:search])
end

My problem is that it is case sensitive, so if I search for "bob", it will not return any users whose name is capitalized (e.g. "Bob"). Is there a way to make it case insensitive?

A: You can also use
User.where('name ILIKE ?', params[:search])

A: This should do it:
def find
  User.where("lower(name) = ?", params[:search].downcase)
end

By making the db entry lowercase and the search params lowercase, then case insensitivity is no longer an issue.
Also, the return statement is not needed in Ruby since we have implicit return statements.
How does it work?
You can pass raw SQL in to the .where command. lower() is a function in SQL, not Ruby, which will return the single string parameter as a lowercase string. It's the equivilent of .downcase in Ruby. Now that both the original string and the string to compare are lowercase, the case no longer matters.

A: Something like this:
def find
    return User.where(:name=> params[:search].downcase)
end


text:
Q: Image as an html button I have an image that I want it to act like a button to preform an java-script onclick on it, everything is working fine except when I click over the image it returns to the top of the page, I want it the page to stay on the same place that I am scrolling (middle of the page  for example) when I click over the link image.
This is my code

A: You have to prevent the default action for the a tag or it will use the href.
Try this in your event handler.
$(document).ready(function() {
    $("#dell").click(function(e) {
        e.preventDefault();
        $("#boarder").toggle(500);
    });
});

Another thought is that you actually don't need an a tag if you aren't using it to navigate somewhere.

A: You don't need to surround it with an

tag, this is what taking you to the top of the document (href="#").
If you want to set the cursor to be a hand icon do it through css:
img { cursor: hand; cursor: pointer; }

A: Here is an example using inline javascript.

A: Well the problem is just about your  tag.
You've set an href='#' which means "reloading", that is why the browser brings you up to the page.
In order to set a javascript event on click try the following:

Otherwise there are other methods like the property onclick='nameOfYourFunction()'
or jQuery events.


text:
Q: ActiveJDBC in a big project I am using old good Hibernate and reading about news int ORM area. ActiveJDBC seems to be quite new ORM, does anybody use it in a big project? Where Hibernate is stronger and why? What ActiveJDBC is misisng?
 Does it for example have L1 cache and cooperates with Spring inside Spring -managed transactions?

A: Disclaimer: I'm the author of ActiveJDBC and other JavaLite projects. ActiveJDBC is a newer than Hibernate, but has been around since 2009. AJ is not a rewrite of Hibernate, but a different ORM implementation based on Active Record, largely inspired by Ruby on Rails. I personally used it on a number of large projects for Sears, Humana, Groupon, Edovo, Discover Health. It is not as commonly used as Hibernate, but there are quite a few well-known companies that use it: GoDaddy, Amazon, Yahoo, Ebay and others.
ActiveJDBC is stronger than Hibernate in web applications, where you do not need to keep a graph of objects, and every instance of a model (entity) is like a map, that is simply passed to a view. This vastly simplifies coding and reduces about 80% of code compared to Hibernate. ActiveJDBC is on average is 50% faster than Hibernate at runtime.
ActiveJDBC uses a Pass-Through Model, which is also completely different from Hibernate  object graph model. Hibernate was designed at the time of client-server, AJ was designed at the time of web apps and APIs.
L1 Caching is specific to Hibernate. ActiveJDBC has a different caching model. ActiveJDBC has no "session". Every model is responsible for itself. For more information, refer to documentation.


text:
Q: How to force hibernate to do join while using @OneToOne mapping with @MapsId I have two entities:
@Entity
@Table(name = "child")
public class MappedChild {
    @Id
    @Column(name = "parent_id")
    private Long parentId;

    @OneToOne
    @PrimaryKeyJoinColumn
    @MapsId
    private MappedParent mappedParent;
}

@Entity
@Table(name = "parent")
public class MappedParent {
    @Id
    @GeneratedValue
    @Column(name = "parent_id")
    private Long parentId;

    @OneToOne(mappedBy = "mappedParent", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private MappedChild mappedChild;
}

And when I'm loading MappedChild, I'm expecting to hibernate to make JOIN for retrieving MappedParent. But actually hibernate does two selects, one for MappedChild, and one for MappedParent. I have tried to change the child mapping to next:
@Entity
@Table(name = "child")
public class MappedChild {
    @Id
    @GeneratedValue
    @Column(name = "child_id")
    private Long childId;

    @OneToOne
    @JoinColumn("parent_id")
    private MappedParent mappedParent;
}

And after that it works as expected: hibernate does JOIN instead of two selects. But that is not what I want, I don't need two separate ids in the child (child_id and parent_id), because it is excess for mine case. Can I modify the first mapping and make hibernate do JOIN instead of two selects?

A: I am sorry, If I am not able to correctly perceive your question.
However from what I could collect, you can try using @Fetch annotation.
Syntax:

@Fetch(FetchMode.JOIN)

You can use this in your entity class ,for example:
  @OneToOne
    @PrimaryKeyJoinColumn
    @Fetch(FetchMode.JOIN)
    @MapsId
    private MappedParent mappedParent;

Moreover, I guess @PrimaryKeyJoinColumn would be unnecessary in this case as @MapsId already accomplishes the job .
Please give me a deeper insight of the question if I am perceiving it wrong.
Would love further queries from you.
ThankYou


text:
Q: Python Inherited Singleton Skeleton issues As it stands i'm not sure if what i'm trying to do is even possible. My end goal was a Singleton skeleton, or parent class that could be reused between different (unique) instances. I understand that by definition a Singleton shouldn't be reusable and in the event that I need several of them, then I should probably rethink the structure. That being said, I wondered if it was possible and set out to try! Below is my latest attempt. The code is documented to the best of my ability (okayish) and should answer any additional questions.
My attempt was to use a single Singleton manager that would hold references to each unique singleton. And when creating a new instance of Singleton, it would check it's internal dict[cls_name: cls_instance] and if one already exists, it would instead return the already created instance. The issues, is that the manager correctly identifies that one exists, but rather than returning the existing instance. It strangely overwrites the original, and all variable references.. I'm not sure why it's doing this if i'm completely honest. Help!
class SingletonManager:
    """
        Managers unique singleton setup (hopefully!)
        Hoping to avoid doing this for every singleton, hence
        why i'm playing with an inherited singleton
    """

    __instance: 'SingletonManager._Inner' = None
    __active_instances: dict[str, object] = {}

    class _Inner:
        """
            Generic singleton inner
        """

        def register(self, instance: object):
            """
                Add an instance to Singleton.__active_instances dict
                with class_name and instance as the k,v pair if an entry
                doesn't already exist
            """

            instance_name = instance.__class__.__name__
            if not self.has_instance(instance_name):
                SingletonManager.instances()[instance_name] = instance
            else:
                raise Exception("How are we here?")

        def get_instance(self, instance_name: str) -> object:
            """
                Return an instance from the __active_instance dict
                with matching instance_name as key
            """

            return self.instances[instance_name]

        def has_instance(self, instance_name: str) -> bool:
            """
                Does __active_instances dict already contain key
                instance name?
            """

            return instance_name in self.instances

        @property
        def instances(self) -> dict:
            """
            Wrapper to grab managers __instance
            """
            return SingletonManager.instances()

    def __new__(cls, *args, **kwargs):
        """
        Generic singleton skeleton
        """

        if not cls.__instance:
            cls.__instance = cls._Inner()
        return cls.__instance

    @staticmethod
    def instances() -> dict:
        """
        Get reference to SingletonManager.__active_instances dict

        """

        return SingletonManager.__active_instances

class Singleton:
    """
    Base class for all singleton objects (hopefully)
    The hope is to inherit from and use this object
    rather than doing the traditional singleton setup

    Traditional setup:
        class obj:
            _instance = None

            class Singleton:
                def __init__(self, *args, **kwargs):
                    # do stuff

            def __new__(cls, *args, **kwargs):
                if not obj._instance:
                    cls._instance = obj.Singleton(*args, **kwargs)
                return cls._instance

            def __getattr__(self, item):
                return getattr(obj._instance, item)

    As you can see it's alot of setup for each object that i'm hoping to avoid..
    """

    def __init__(self, *args, **kwargs):
        pass

    def __new__(cls, *args, **kwargs):
        if not SingletonManager().has_instance(cls.__name__):
            instance = super(Singleton, cls).__new__(cls)
            SingletonManager().register(instance)
        else:
            instance = SingletonManager().get_instance(cls.__name__)
        return instance

class TestSingletonObj(Singleton):
    def __init__(self, name: str = None):
        super(TestSingletonObj, self).__init__(name)
        self.name = name

While testing..
print(m.name)  # Steve
m2 = TestSingletonObj("John")
print(m2.name)  # John
print(m.name, m2.name, m is m2)  # John John True

If anyone can point out why the original instance is being overwritten rather than being returned. My only thought is it's a bug i've written, a bug in python, or it's an expected behavior with python's MRO that i'm unfamiliar with. Thank you in advance!


text:
Q: How to use TEXT and VARCHAR in same MySQL table use interchangeably (Java) I have a table with column VARCHAR to store incoming data(tcp data),
 90% of the time data will fit into VRACHAR however rest of the time incoming data can exceed the column , I'm planning to store it in a separate TEXT column rather than making exiting column to TEXT .
Please note that data is always in hexadecimal format ( 0 –F)
Table :
Table_Id    ,VARCHAR- column,   TEXT- column

I'm  planning to abstract this information in java layer by querying a MySQL View which logically present only one column 'message' depending on
( `VARCHAR- column` !=null  ? "`VARCHAR- column`": 'TEXT- column')  AS message

In MySql View
I would like to know any thoughts on this approach and any suggestion how to do this in java layer ,
at present I'm thinking of checking the length of incoming message(since hexadecimal data )  if it can't fit in to my VARCHAR then store in in TEXT column.
Thanks


text:
Q: position menu bars below site logo css so here is my mockup design:

Below is my sample css:
.menu{
padding: 32px;
background-color: #cc6666;
opacity: 0.5;
filter: Alpha(opacity = 50); /* IE8 and earlier */
clear: both;
margin: 0 auto;
width: 100%;
text-align: center;
}

But it isn't doing what looks like in my mockup. Need your help. Thanks.
UPDATE:
http://jsfiddle.net/qdhcQ/

A: It doesn't look like you added markup for logo.
So add in markup:

And in css
.logo
{
    height: 50px;
    background: brown;
}

FIDDLE


text:
Q: Is there a way to have a wildcard in the bodyFileName for a wiremock stub mapping? My issue is that I want to give my response file names a more meaningful name but to do this I need to be able to match on any text following the id. Here is my current mapping:
{
  "priority": 10,
  "request": {
    "urlPattern": "/api/v1/customer\\?Id=(.*)&IdType=(.*)&AdditionalInformation=(.*)",
    "method": "GET"
  },
  "response": {
    "transformers": [
      "dynamic-mapping-transformer"
    ],
    "status": 200,
    "headers": {
      "Content-Type": "application/json",
      "Correlation-ID": "{{request.headers.Correlation-ID}}"
    },
    "transformerParameters": {
      "bodyFileName": "{{request.query.Id}}",
      "fileDirectory": "getWorkplaceDetails",
      "extension": "json",
      "encodeName": false,
      "caseInsensitive": true
    }
  }
}

And the naming convention for the response files should be something along the lines of "Id_foo_bar" but "foo" and "bar" are not available in the request so there is no way for me to know them before the response is posted. I would like to use a wild card in the bodyFileName value to match on anything after the Id and was wondering if anyone knew a way to do this?
EDIT 1
I forgot to mention that the mapping needs to accept multiple files with different names which is why I am looking to use a wild card instead of a static file name.


text:
Q: Plotly: How to plot time series in Dash Plotly I've searched for days and didn't find an answer. How can I plot a time series data in Dash Plotly as a linegraph with selectable lines?
My data (pandas dataframe) describes GDP of different countrys. Index is country, column is years.

I don't find a solution to pass the data to Dash Plotly linegraph. What are my x and y values?
fig = px.line(df, x=?, y=?)

A: By the looks of it, the solution in your example should be:
fig = px.line(df, x=df.index, y = df.columns)

Plot 1 - plot by columns as they appear in your dataset

From here, if you'd like to display countries in the legend and have time on the x-axis, you can just add df = df.T into the mix and get:
Plot 2 - transposed dataframe to show time on the x-axis

Details
There's a multitude of possibilites when it comes to plotting time series with plotly. Your example displays a dataset of a wide format. With the latest versions, plotly handles both datasets of long and wide format elegantly straight out of the box. If you need specifics of long and wide data in plotly you can also take a closer look here.
The code snippet below uses the approach described above, but in order for this to work for you exactly the same way, your countries will have to be set as the dataframe row index. But you've stated that they are, so give it a try and let me know how it works out for you. And one more thing: you can freely select which traces to display by clicking the years in the plot legend. The figure produced by the snippet below can also be directly implemented in Dash by following the steps under the section What About Dash? here.
Complete code:
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio

import plotly.io as pio

# sample dataframe of a wide format
np.random.seed(5); cols = ['Canada', 'France', 'Germany']
X = np.random.randn(6,len(cols))
df=pd.DataFrame(X, columns=cols)
df.iloc[0]=0;df=df.cumsum()
df['Year'] =  pd.date_range('2020', freq='Y', periods=len(df)).year.astype(str)
df = df.T
df.columns = df.iloc[-1]
df = df.head(-1)
df.index.name = 'Country'

# Want time on the x-axis? ###
# just include:
# df = df.T
##############################

# plotly
fig = px.line(df, x=df.index, y = df.columns)
fig.update_layout(template="plotly_dark")
fig.show()


text:
Q: WHERE ALL not working as expected I want to find the details of a employee if he has credit cards of type A and B.
The table structure is like {empid, ccno, cctype} and suppose empid 'e1' has all card type.
I tried something like
select * from test where cctype = all('A', 'B') and empid = 'e1'

but this did not return any rows.
Can you explain why I'm wrong? Any help is appreciated. Thanks in advance.

A: ALL is effectively expanded to the Boolean and. Your query is equivalent to:
select *
  from test
 where cctype = 'A'
   and cctype = 'B'
   and empid = 'e1'

As cctype cannot be both A and B no rows are returned.
Equality checks (=) are rarely useful with ALL, comparison operators (>, <, <>) are more useful.
If you want to find individuals with both types you'll have to use an aggregate or analytic function over a key:
select empid
  from test
 where cctype in ('A', 'B')
 group by empid
having count(distinct cctype) = 2

or
select *
  from ( select t.*
              , count(distinct cctype) over (partition by empid) as ct
           from test t
          where cctype in ('A', 'B')
                )
 where ct = 2


text:
Q: Gnome terminal will not start I just tried to install python 3.6 on my Ubuntu 16.04 system, and now I can't run the terminal from the launcher or from Ctrl + Alt + T. I tried to run gnome-terminal from XTerm and got the following message:
Traceback (most recent call last):
  File "/usr/bin/gnome-terminal", line 9, in <module>
    from gi.repository import GLib, Gio
  File "/usr/lib/python3/dist-packages/gi/__init__.py", line 42, in <module>
    from . import _gi
ImportError: cannot import name '_gi'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 30, in <module>
    import apport.fileutils
  File "/usr/lib/python3/dist-packages/apport/fileutils.py", line 23, in <module>
    from apport.packaging_impl import impl as packaging
  File "/usr/lib/python3/dist-packages/apport/packaging_impl.py", line 23, in <module>
    import apt
  File "/usr/lib/python3/dist-packages/apt/__init__.py", line 23, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'

Original exception was:
Traceback (most recent call last):
  File "/usr/bin/gnome-terminal", line 9, in <module>
    from gi.repository import GLib, Gio
  File "/usr/lib/python3/dist-packages/gi/__init__.py", line 42, in <module>
    from . import _gi
ImportError: cannot import name '_gi'

How can I fix this error?
It should also be noted that:

*

*My gnome-terminal file is now a python script.

*The gnome-terminal.real file will open the terminal as expected.

*python3.5 gnome-terminal will open the terminal as expected.

A: I know this is an old question but for those looking for a way other than changing python3 to python 3.5 globally, you can change the first line of /usr/bin/gnome-terminal from #! /usr/bin/python3 to #! /usr/bin/python3.5.
Note: I don't have python 3.5 on my computer but import gi works in python 3.6, so used 3.6 instead of 3.5.

A: Probably the symlink /usr/bin/python3 points to python3.6, which it should not. Fix it by running these commands:
sudo rm /usr/bin/python3
sudo ln -s python3.5 /usr/bin/python3

A: You don't have to point Python3 to python3.5 , just running the commands:
cd /usr/lib/python3/dist-packages/gi/
sudo cp _gi.cpython-35m-x86_64-linux-gnu.so _gi.cpython-36m-x86_64-linux-gnu.so
sudo cp _gi_cairo.cpython-35m-x86_64-linux-gnu.so _gi_cairo.cpython-36m-x86_64-linux-gnu.so

A: REAL REASON + SOLUTION - Python3.7 Gnome Terminal Gets Messed Up - Ubuntu Linux Mint
THIS QUESTION WAS NEVER ANSWERED in another post here Terminal not opening up after upgrading python to 3.7 so I give the cause, reason and solution.
Install python 3.7, correct move, but missing PyGObject gi causes Gnome Terminal to fail on boot, fix easy

*

*sudo apt update && sudo apt upgrade && sudo apt autoremove

*sudo apt install python3.7  python3.7-dev ffmpeg

*sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.6 1

*sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.7 2

*sudo update-alternatives --config python3  #
selecting 3.7

*python3 -V   # should be version 3.7.5 or more

*DO NOT REBOOT HERE .. YET, gnome terminal will break.

NOOB WORK AROUND: IN LINUX ADVANCED RECOVERY MODE - (SO DO NOT REBOOT YET)

*

*$ DO NOT DO sudo update-alternatives --config python3 # select 3.6
It gets your terminal back but is NOT THE SOLUTION.

( Explanation: - [https://pygobject.readthedocs.io/en/latest/getting_started.html#ubuntu-getting-started][1]  )
SOLUTION JUST INSTALL WHAT WAS MISSING.

*

*python3 -V  # must be python 3.7

*mkdir -p ~/.local/bin ; cd .local/bin

*vi hello.py  # use nano or any editor - it's a test program.  See ref link at the end.
    # Test script
    import gi
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk

    window = Gtk.Window(title="Hello World")
    window.show()
    window.connect("destroy", Gtk.main_quit)
    Gtk.main()

*sudo update-alternatives --config python3  # set python 3.7

*python3 hello.py  # it does NOT work so install stuff ...

*sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0

*sudo apt install libgirepository1.0-dev gcc libcairo2-dev pkg-config python3.7-dev

*python3 hello.py  # it may NOT work still, install MORE stuff
If you pip install to solve, note that it installs for the user only.
For other Linux's or non-pip install please use the link at the end.

*

*sudo -k  # Notice that pip is NOT SECURITY TRUSTED, turn sudo OFF!

*python3 -m pip install -U pycairo  # this automatically uses pip3

*python3 -m pip install -U PyGObject  # THIS SOLVES THE PROBLEM!

*python3 hello.py  # WORKS!  N.B. other uses must install the same!

*sudo shutdown -r now  #  OK NOW YOU CAN REBOOT. Gnome Terminal will work.

*

*Notice my pip style  python3 actually calls pip3 not pip.

*True cause Ubuntu or Linux Mint: /usr/bin/gnome-terminal calls default python3 which is 3.7 and finds your gi PyGObject include missing so the terminal is unusable with each user missing the control panel.

Conclusion, you get to keep your python upgrade.
References:
[1]: PyGObject including gi test https://pygobject.readthedocs.io/en/latest/getting_started.html#ubuntu-getting-started

A: Proper change of default python3 is done via:
sudo update-alternatives --config python3

Although copying the _gi_cairo.cpython-35m-x86_64-linux-gnu.so from python3.5 to python3.6 could resolve the issue, but would break your library consistency. And should be avoided.

A: I fixed the gnome-terminal problem from the solution above.
Enter these commands:
cd /usr/lib/python3/dist-packages/gi/
sudo cp _gi.cpython-36m-x86_64-linux-gnu.so _gi.cpython-37m-x86_64-linux-gnu.so
sudo cp _gi_cairo.cpython-35m-x86_64-linux-gnu.so _gi_cairo.cpython-36m-x86_64-linux-gnu.so

A: If you are using Ubuntu22.04, very simple solution here. /usr/bin/gnome-terminal is a python script.
You can change 1st line #!/usb/bin/python to #!/usr/bin/python3.8
 #!/usr/bin/python3.8

 import string
 import subprocess
 import sys
 import random

 from argparse import ArgumentParser, SUPPRESS
 from gi.repository import GLib, Gio
 ...


text:
Q: Symfony 4.4 Form multiselect bootstrap I'm trying to change a EntityType form view for something look like: http://davidstutz.de/bootstrap-multiselect/#templates
I make change on my base.html.twig, by adding dependency, I make try bye using code exmaple on this twig file to see if all is fine and it's working.
Now the problem come when I make change on my _form.html.twig or in the Type.php file, actually after all my try I don't see where to make change.
My _form.html.twig
  {{ form_start(form) }}
    {{ form_widget(form) }}
    {{ form_widget(form.Service) }}

    <button class="btn btn-success btn-icon-split">

    </button>

{{ form_end(form) }}

My UtilisateursType.php
<?php

namespace App\Form;

use App\Entity\Utilisateurs;
use App\Entity\Services;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Doctrine\ORM\EntityRepository;

class UtilisateursType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Nom')
            ->add('Login')
            ->add('PartagePerso')
            ->add('Service', EntityType::class, [
              'class' => Services::class,
              'query_builder' => function (EntityRepository $Service) {
                return $Service->createQueryBuilder('u')
                ->orderBy('u.Nom', 'ASC');
              },
              'choice_label' => 'Nom',
              'multiple' => true,
              'expanded' => false,
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Utilisateurs::class,
        ]);
    }
}

Thank for you help

A: Symfony will wrapper each field by an html element (
) and in order to modify this behaviour you have to override it.
see form_themes
first of all create a template eg: template/form/my_custom_entity_service.html.twig
{% use 'form_div_layout.html.twig' %}

{% block entity_row %}
        {{ form_label(form) }}

           {{ form_widget(form) }}

{% endblock %}

then call it in your  _form.html.twig
{% form_theme form 'form/my_custom_entity_service.html.twig' %}

{{ form_start(form) }}

{{ form_widget(form.Nom) }}
{{ form_widget(form.Login) }}
{{ form_widget(form. PartagePerso) }}
{{ form_widget(form.Service) }}

{{ form_end(form) }}

Note: the way you call the form in your code is wrong consider {{ form_rest(form) }}


text:
Q: How to use _dirname with a sibling directory My directory is set up like this:
public
    pages
       index.html
routers
    route.js

Inside route.js, I do the following:
router.get('/', function(req, res) {
    res.sendFile("/public/pages/index.html", {"root": __dirname});
});

I get Error: ENOENT: no such file or directory, stat because the server is looking on myproject/routers/public/pages/index.html and not myproject/public/pages/index.html
1) How do I fix this issue and get it to look in the right path using _dirname?
2) How do I get my server to remember looking in /public/pages/ so that I don' have to specify the absolute path every time?

A: So you probably want to use relative location, for your example you can do something like bellow
var html_location = './public/pages/'; //first method
var root_location = {  //second method
    root : './public/pages/'
}
router.get('/', function(req, res) {
    res.sendFile('index.html', { root : html_location}); //first method
    res.sendFile('index.html', root_location); //second method
});

so the root : '.' indicating that you will be starting the location from the folder where the main.js / app.js file is running and the file location is off from that location.


text:
Q: python : how to import packages? This is my folder:
/Workspace
 somefiles.py
          /foopackage
           __init__.py
           foo1.py
           foo2.py

And the _init_.py contains
from foo1 import foo1
from foo2 import foo2

And I want to import foopackage.
I have tried this:
>>>import sys
>>>sys.path.append('/home/username/Workspace')
>>>import foopackage
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/username/Workspace/foopackage/__init__.py", line 1, in <module>
    from foo1 import foo1
ImportError: No module named 'foo1'

I have tried sys.path.append('/home/username/Workspace/foopackage') instead and the thing fixed.
I'm asking do I have to add every package directory to sys.path list to be able to import them?
or something else is wrong?

A: If you are using Python 3, you need to use explicit relative imports rather than implicit ones, which used to work in Python 2. Try updating foopackage's __init__.py file to be:
from .foo1 import foo1
from .foo2 import foo2

The leading . characters tell Python that foo1 and foo2 are sibling modules, rather than being top level modules that you're referring to absolutely. An alternative would be to use an absolute reference to them:
from foopackage.foo1 import foo1
from foopackage.foo2 import foo2

But personally, I think that's a bit excessive. It will also break if you change the package name at some point in the future (or move to be a subpackage of some other package).
See PEP 328 for more details on the changes to relative imports.


text:
Q: Dockerize dotnet core 2.2 app, what and why lines are placed in nopCommerce Dockerfile? Questions about dockerizing dotnet core app
As an example I will provide the Dockerfile for nopCommercew
https://github.com/nopSolutions/nopCommerce/blob/develop/Dockerfile
Everything is clear except the following:
RUN dotnet publish Nop.Web.csproj -c Release -o /app/published
...
# add globalization support
RUN apk add --no-cache icu-libs
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false

WORKDIR /app
RUN mkdir bin
RUN mkdir logs

COPY --from=build /app/published .

*

*Why should the app be published to /app/published, then copy it to the /app?

*Why --from=build is used in line COPY --from=build /app/published .?

*What is this line RUN apk add --no-cache icu-libs is used for? and why should it be used?

A: Docker image is bunch of smaller layers.
The docker build . creates multiple small docker images at each logical step and caches it. Check docker build output closely and look for Using cache in the output.
check the output of
docker pull mcr.microsoft.com/dotnet/core/runtime:3.1 docker images docker inspect <image id of mcr.microsoft.com/dotnet/core/runtime:3.1>

#The Answer
There are two FROM docker commands.
The first command points to the .NET Core SDK which is probably 600 MB.
The second command points to .NET Core runtime which is probably 200 MB.
SDK images are for developers to build/test/package. It supports all the dotnet CLI commands are available here. Such as dotnet build and dotnet publish.
Runtime images are optimized for production. They are smaller and hence faster.
For an efficient build process docker suggests working with multiple images. SDK and runtime.
###1: Why should the app be published to /app/published, then copy it to the /app?
The dotnet publish command is of the SDK image cycle. /app/publish has everything required to run your application but on the SDK image.
We need to take this to the runtime image.
WORKDIR /app creates a folder in the runtime image.
###2: Why --from=build is used in line COPY --from=build /app/published .?
After the above steps the output of the publish command is available on SDK docker image in the /app/publish folder.
We called it "build" on the first line of Dockerfile by passing AS build at the end of the command
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
with --from==build we point to the SDK image and copy it to the runtime image. That's for communication between two docker images.
###3: What is this line RUN apk add --no-cache icu-libs is used for? and why should it be used?
The apk is for the installation of packages on the Linux OS. Think of it as equivalent to nuget of .net.
icu-libs is a Linux package for Unicode characters.
https://pkgs.alpinelinux.org/package/v3.3/main/x86/icu-libs
I am assuming that nopCommerce supports the Unicode characters.
The mcr.microsoft.com/dotnet/core/runtime:3.1 installs a Debian Linux probably version 4 which does not have Unicode support.
through APK command nopCommerce is installing it manually.


text:
Q: Checkbox value not getting updated in the database I have created a web application. In one jsp page, I have a check box, text box, and two submit button. One submit button, just retrieves the value from DB and populate in the text box. Another submit button updates the retreived value into the table in database. If I check the check box and submit the value after i retrieved from the DB, it should be stored into DB and it is storing fine. Then if I uncheck the checkbox and submit to database. The checkbox value is not updating. The same happens vice versa if i just update the textbox and submit, the value 0 is updating in database, but after checking it again and updating to DB, the value is not updating. I have used, spring and hibernate for this. Enlighten me where am doing wrong.
Model 1
CloneSafe.java
package com.consulting.data;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import com.consulting.annotation.Setting;

@Entity
@Table(name = "clonesafe_settings")
public class CloneSafe {

    @Id
    @GeneratedValue
    @Column(name = "PK1")
    private int pk1;
    @Basic
    private String cloud_safe_id;

    @Basic
    private Boolean is_clone_safe;

    public int getPk1() {
        return pk1;
    }

    public void setPk1(int pk1) {
        this.pk1 = pk1;
    }

    @Setting(key = "cloud_safe_id")
    public String getCloud_safe_id() {
        return cloud_safe_id;
    }

    public void setCloud_safe_id(String cloud_safe_id) {
        this.cloud_safe_id = cloud_safe_id;
    }

    @Setting(key = "is_clone_safe")
    public Boolean getIs_clone_safe() {
        return is_clone_safe;
    }

    public void setIs_clone_safe(Boolean is_clone_safe) {
        this.is_clone_safe = is_clone_safe;
    }

}

Model 2
RegistryCloneSettings.java
package com.consulting.data;

public class RegistryCloneDetails {

    private String cloneCloudState;
    private String cloneSafeId;

    public String getCloneCloudState() {
        return cloneCloudState;
    }
    public void setCloneCloudState(String cloneCloudState) {
        this.cloneCloudState = cloneCloudState;
    }
    public String getCloneSafeId() {
        return cloneSafeId;
    }
    public void setCloneSafeId(String cloneSafeId) {
        this.cloneSafeId = cloneSafeId;
    }
}

Form Details
CloneSafe.jsp
<form:form modelAttribute="cloneSafe" method="POST" action="cloneSafe">

                    <form:checkbox path="is_clone_safe" />

                    <form:input path="cloud_safe_id" />
                <input type="submit" value="Update" name="action" />
            <input title="Submit" cancelUrl="bookextract">
</form:form>

Dao Classes
CloneSafeDao.java
package com.consulting.dao;

import java.sql.Connection;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.consulting.data.CloneSafe;
import com.consulting.data.RegistryCloneDetails;
import com.consulting.exception.ApplicationException;
import com.consulting.exception.SystemException;
import com.consulting.settings.service.RegistryService;

@Repository("clonesafeDao")
public class CloneSafeDao {
    private static final Logger log = LoggerFactory.getLogger(CloneSafeDao.class);

    @Autowired
    private SessionFactory sessionFactory;

    @Autowired
    private RegistryService registryService;

    /**
     * @param s
     */
    public void save(CloneSafe s) {

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.persist(s);
        session.getTransaction().commit();
        session.close();
    }

    /**
     * @return
     */
    public CloneSafe load() {

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Query query = session.createQuery("from CloneSafe");
        // expecting only one row
        List<CloneSafe> cloneSafe = query.list();
        session.getTransaction().commit();
        session.close();
        if (cloneSafe == null || cloneSafe.size() == 0) {
            log.debug("CloneSafe null, creating new");
            return new CloneSafe();
        }
        // expecting only one row
        return cloneSafe.get(0);
    }
    /**
     * @return
     */
    public List<CloneSafe> loadList() {

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        Query query = session.createQuery("from CloneSafe");
        // expecting only one row
        List<CloneSafe> cloneSafe = query.list();
        session.getTransaction().commit();
        session.close();
        return cloneSafe;
    }

    /**
     * @param cloneSafe
     * @return
     * @throws SystemException
     * @throws ApplicationException
     */
    public int update(CloneSafe cloneSafe) throws SystemException, ApplicationException {

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        List<CloneSafe> safe = loadList();
        for (CloneSafe g : safe) {
            log.debug("Cloud Safe ? : " + g.getIs_clone_safe());
        }
        if (safe.size() >= 1) {
            int pk1 = safe.get(0).getPk1();
            log.debug("PK1 : " + pk1);
            Query query = session
                    .createQuery("update CloneSafe set cloud_safe_id = " + ":cloud_safe_id where pk1 =:pk1");
            query.setString("cloud_safe_id", cloneSafe.getCloud_safe_id());
            query.setInteger("pk1", pk1);

            int result = query.executeUpdate();
            return result;
        } else if (safe.size() == 0) {
            save(cloneSafe);
            return 1;
        }
        session.close();
        return 0;
    }

    /**
     * Load the System Registry Values
     * @return RegistryCloneDetails
     */
    public RegistryCloneDetails loadCloneRegistryValues() {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        try {
            RegistryCloneDetails  cloneDetails = new RegistryCloneDetails();
            String cloudSiteID = registryService.getSystemValue("cloud_site_id", null);
            cloneDetails.setCloneSafeId(cloudSiteID);
            return cloneDetails;
        } catch (Exception e) {
            //add exception logic
        }
        finally {
            session.close();
        }
        return null;
    }

}

Controller
CloneSafeController.java
package com.consulting.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.service.internal.SessionFactoryServiceRegistryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.consulting.dao.CloneSafeDao;
import com.consulting.data.CloneSafe;
import com.consulting.data.RegistryCloneDetails;
import com.consulting.exception.ApplicationException;
import com.consulting.exception.SystemException;
import com.consulting.service.impl.SystemRegistryServiceImpl;
import com.consulting.settings.service.RegistryService;

@Controller
@RequestMapping("/admin")

public class CloneSafeController {

    private static final Logger _LOG = LoggerFactory.getLogger(CloneSafeController.class);

    @Autowired
    private CloneSafeDao cloneSafeDao;

    @Qualifier("Handle")
    private String Handle;

    @Autowired
    @Qualifier("Vendor")
    private String Vendor;

    /**
     * @param request
     * @param response
     * @param cloneSafe
     * @param result
     * @return
     */
    @RequestMapping(value = { "cloneSafe" }, method = RequestMethod.GET)
    public ModelAndView getSettingsPage(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute("cloneSafe") CloneSafe cloneSafe, BindingResult result) {

            ModelAndView mav = new ModelAndView();
            cloneSafe = cloneSafeDao.load();
            mav.setViewName("cloneSafe");
            mav = new ModelAndView("cloneSafe", "cloneSafe", cloneSafe);
            return mav;
    }

    /**
     * @param request
     * @param response
     * @param cloneSafe
     * @param result
     * @return
     */
    @RequestMapping(value = { "cloneSafe" }, method = RequestMethod.POST)
    public ModelAndView saveCloneSafeSettings(HttpServletRequest request, HttpServletResponse response,
            @ModelAttribute("cloneSafe") CloneSafe cloneSafe, BindingResult result) {

            ModelAndView mav = new ModelAndView();
            try {
                int i =cloneSafeDao.update(cloneSafe);
            } catch (Exception e){
                //Add Logic
                _LOG.debug("Errored....");
            }
            mav.setViewName("cloneSafe");
            mav = new ModelAndView("cloneSafe", "cloneSafe", cloneSafe);
            return mav;
    }

    /**
     * Load the System  Registry Values
     * @param request
     * @param response
     * @param cloneSafe
     * @param result
     * @param model
     * @return
     * @throws SystemException
     * @throws ApplicationException
     */
    @RequestMapping(value = { "cloneSafe" }, params = "action", method = RequestMethod.POST)
    public ModelAndView loadCloneSafeDetails(HttpServletRequest request,
            HttpServletResponse response,@ModelAttribute("cloneSafe") CloneSafe cloneSafe,
            BindingResult result, ModelMap model){

        ModelAndView mav = new ModelAndView();
        RegistryCloneDetails cloneDetails= cloneSafeDao.loadCloneRegistryValues();
        if(null!=cloneDetails)
        {
            if(null!=cloneDetails.getCloneSafeId())
            {
                cloneSafe.setCloud_safe_id(cloneDetails.getCloneSafeId());
            }
        }
        mav.setViewName("cloneSafe");
        mav = new ModelAndView("cloneSafe", "cloneSafe", cloneSafe);
        return mav;
    }

}

What mistake am making, why the checkbox value is not updating after it is getting updated for the first time. Where i need to change the code. Thanks in advance.

A: I have made a mistake in the hibernate update query. After i rectified that, i am not facing any issue.
query = session.createQuery("update CloneSafe set cloud_safe_id = " + ":cloud_safe_id,is_clone_safe = " + ":is_clone_safe where pk1 =:pk1");
            query.setString("cloud_safe_id", cloneSafe.getCloud_safe_id());
            query.setInteger("pk1", pk1);
            query.setBoolean("is_clone_safe", cloneSafe.getIs_clone_safe());
            session.getTransaction().commit();

I have added the above code in DAO and everything is working fine.


text:
Q: grid itemdbclick functionality in ExtJs 4.2 MVC I have build an extJs 4.2 MVC pattern application. I have agrid in the front page. On dbclick of an item in the grid, a pop up window is appearing which is working fine. The pop up window extends a window and has forms in it. The form displays the details of the item clicked. If its a single field, in the controller i can specify it in the
`onGridItemDblClick : function(view, record, item, index, e) {

var view = Ext.widget('xtype_name_for_window');
field= view.down('displayfield');
field.setValue(record.get('name_of_the_field'));

}`

But (yes, there is but, or I wouldn't have posted this) I have many fields to be displayed in the window. How can I popullate all the fields?
Thank you!

A: Use the functionality of forms:
Ext.define('MyRec', {
    extend: 'Ext.data.Model',
    fields: ['f1', 'f2', 'f3']
});

var w = new Ext.window.Window({
    width: 400,
    height: 200,
    title: 'Foo',
    autoShow: true,
    layout: 'fit',
    items: {
        xtype: 'form',
        defaultType: 'displayfield',
        items: [{
            name: 'f1'
        }, {
            name: 'f2'
        }, {
            name: 'f3'
        }]
    }
});

var rec = new MyRec({
    f1: 'a',
    f2: 'b',
    f3: 'c'
});

w.down('form').getForm().loadRecord(rec);


text:
Q: Calculus of $\sum_{n=1}^{\infty}( \frac{1}{2^n})$, $n$ is even I want to prove that $\sum_{n=1}^{\infty}( \frac{1}{2^n}) = \frac{1}{3}$, where $n$ can only be an even integer.
That is, how can I use linear algebra to prove that $\frac{1}{2^2} + \frac{1}{2^4} + \frac{1}{2^6} + \frac{1}{2^8} + \cdots = \frac{1}{3}$?
I heard some people saying that linear algebra help them to solve the aforementioned problem. Can anyone explain to me in detail how to get the solution $\frac{1}{3}$?
Any help is very appreciated.

A: Use the fact that the set of all even (non-zero) integers is $2\mathbb N^*$. This gives the following sum to compute
$$\sum_{k=1}^{\infty} \dfrac{1}{2^{2k}}=\sum_{k=1}^{\infty}\dfrac{1}{4^k}=\dfrac{1}{4}\dfrac{1}{1-1/4}=\dfrac{1}{4}\dfrac{4}{3}=\dfrac{1}{3}.$$

A: IF the sum is finite (call it $S$) , it satisfies the equation  $4S=1+S$ which implies $(4-1)S=1$ and so $S=1/3$.   You might call this "linear algebra", but it's a stretch.  This does not prove the series converges, that is, actually represents a number.


text:
Q: Generic Delayed / Scheduled Action calls in c# I tried to generalize the delayed action call proposed in Delayed function calls
To use it for scheduling tasks that I need executed in the next 24h, but it does not work.
I don't understand why the direct call proposed there works while my generalized one does not do anything.
    public void RunScheduledTasks()
    {
        //This generic way fails
        RunScheduledMethod(bar1, new TimeSpan(15, 31, 30)); //DOES NOTHING

        //This way works
        TimeSpan Time1 = new TimeSpan(15, 31, 30);
        if (Time1 > DateTime.Now.TimeOfDay)
        {
            Time1 -= DateTime.Now.TimeOfDay;
            Task.Delay(Time1).ContinueWith(t => bar1()); //WORKS OK.
        }

    }
    public void RunScheduledMethod(Action methodToRun, TimeSpan TimeToRun)
    {
        TimeToRun -= DateTime.Now.TimeOfDay;
        Task.Delay(TimeToRun).ContinueWith(t => methodToRun);
    }
    public void bar1()
    {
        MessageBox.Show("Bar1 called" + DateTime.Now.TimeOfDay);
    }

A: Thanks to the proposal by Crhiz: adding () to the methodname, it works. Here is the full method with safeguards against time which is too early:
public void RunScheduledMethod(Action methodToRun, TimeSpan timeToRun)
    {
        if (timeToRun <= DateTime.Now.TimeOfDay)
            timeToRun = timeToRun + new TimeSpan(1, 0, 0, 0);
        timeToRun -= DateTime.Now.TimeOfDay;
        Task.Delay(timeToRun).ContinueWith(t => methodToRun());
    }

To call it just do as shown in the question, or below:
RunScheduledMethod(bar2, new TimeSpan(15, 59, 00));


text:
Q: retrieve stored image in database using php I have images stored in my database i want to load them in the browser i have two pages one of them is
show_picture.php and the other one is get_image.php my image contents does not load in the browser and it is like that the image has been moved or something but the images are stored in database so here is my code
 <?php include("includes/student_session.php");?>
<?php confirm_logged_in();?>
<html>
<body>
<?php include("includes/connection.php");?>
<?php
if (isset($_SESSION['exam_id']) and isset($_SESSION['register_id'])){

$exam_id=mysqli_real_escape_string($cnn,$_SESSION['exam_id']);

$query="select question_id from questions where exam_id={$exam_id} order by page_number asc";
$result=mysqli_query($cnn,$query);
if($result){

    while ($row=mysqli_fetch_array($result)){
    echo "<img src=\"get_image.php?id={$row['question_id']}\"/>";
    }
}
}
?>
</body>
</html>

and this is my get_image.php
    <?php include("includes/connection.php");?>
<?php
$question_id=$_REQUEST['id'];
$query="select question from questions where question_id={$question_id} limit 1";
$result=mysqli_query($cnn,$query);
 $row = mysqli_fetch_array($result);
  //mysql_close($cnn);

  header("Content-type: image/jpg");
  echo $row['question'];
?>

I am wondering what i am missing


text:
Q: how to change new products block heading in magento 1.9 I have added a new products static block with widget on my home page. I am not able to change heading of this block. Is there any way to change it.

A: You can find title in the following files.
> catalog/product/widget/new/content/new_grid.phtml
> catalog/product/widget/new/content/new_list.phtml


text:
Q: Bind "this" to TypeScript Lambda Say I have a lambda in TypeScript:
 myArray.forEach(o => o.x = this.x);

The value of this becomes window instead of the calling object. What I'd really like to do is:
 myArray.forEach(o => { o.x = this.x; }.bind(this));

But I don't see that as an option in TypeScript. How can I override this in a TypeScript lambda body?

A: Just FYI even without a lambda the default this in a for each is window e.g. :
[1].forEach( function ( o ) { console.log( this ) }); // window

To fix the this with bind you need to use a function and not a lambda (which lexically scopes the meaning of this).
var foo = {};
[1].forEach( function ( o ) { console.log( this ) }.bind( foo ) ); // object `foo`

Alternatively you can use the second argument for forEach as mentioned by Bergi.


text:
Q: How to use DOMElement Class in dom4J document I try to modify XML by dom4j.
but dom4j does not have enough method(for example, getNextSibling, hasAttribute)
as far as I searched, DOMElement Class will help with solving this proglem.
But I can not understand how to use DOMElement class at all...
How to rewrite below code by using DOMElement??
http://dom4j.sourceforge.net/dom4j-1.6.1/apidocs/org/dom4j/dom/DOMElement.html
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class Sampe1 {

public static void main(String[] args) {
    SAXReader reader = new SAXReader();

    try {
        Document document = reader.read("catalog.xml");

        List books =document.selectNodes("catalog/book");
        for(Iterator i = books.iterator(); i.hasNext();){
            Node book = (Node)i.next();
            List aList = book.selectNodes("./a");
            for(Iterator i2 = aList.iterator(); i2.hasNext();){
                Node aNode = (Node)i2.next();
                int aInt = Integer.parseInt( aNode.valueOf("./@volume"));

                **// I want to rewrite the next line By "getNextSibling"method of DOMElement(dom4j.dom)**
                Node NextSiblingNode= aNode.selectSingleNode("./following-sibling::*");
                int nextInt = Integer.parseInt(NextSiblingNode.valueOf("./@volume"));

**//I want to rewrite the following lines By "hasAttribute"method of DOMElement**
//                  if(aNode.hasAttribute("volume");){
//                      if(NextSiblingNode.hasAttribute("volume")){
//                          if(aInt > nextInt){
//                              System.out.println(aInt+"is larger than"+ nextInt);
//                          }
//                      }
//                  }

            }

    }

 }
             catch(DocumentException e)
            {
             System.out.println(e.getMessage());
                       }

}
}

catalog.xml
enter code here

<?xml version="1.0"?>
 <catalog>
  <book>
   Gambardella, Matthew
   XML Developer's Guide
   Computer
   44.95
   2000-10-01
   An in-depth look at creating applications
  with XML.
  </book>
  <book>
   Fantasy
   5.95
   2000-12-16
   A former architect battles corporate zombies,
  an evil sorceress, and her own childhood to become queen
  of the world.
  </book>
  <book>
   5.95
   2000-11-17
   After the collapse of a nanotechnology
  society in England, the young survivors lay the
  foundation for a new society.
  </book>
 </catalog>

A: You can cast Node objects that have attributes in the XML to Element and then work with the attributes. Here is a working version of the program:
package test;

import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class TestMain {

    public static void main(String[] args) {
        SAXReader reader = new SAXReader();

        try {
            Document document = reader.read("catalog.xml");

            List books = document.selectNodes("catalog/book");
            for (Iterator i = books.iterator(); i.hasNext();) {
                Node book = (Node) i.next();
                List<Node> aList = book.selectNodes("./a");
                for (Iterator<Node> i2 = aList.iterator(); i2.hasNext();) {
                    Element aNode = (Element) i2.next();
                    Attribute aNodeVolume = aNode.attribute("volume");
                    if (aNodeVolume != null) {
                        int aInt = Integer.parseInt(aNodeVolume.getValue());

                        // I want to rewrite the next line By
                        // "getNextSibling"method
                        // of DOMElement(dom4j.dom)**
                        Element NextSiblingNode = (Element) aNode.selectSingleNode("./following-sibling::*");

                        // I want to rewrite the following lines By
                        // "hasAttribute"method of DOMElement**
                        if (aNode.attributeValue("volume") != null) {
                            Attribute NextSiblingNodeVolume = NextSiblingNode.attribute("volume");
                            if (NextSiblingNodeVolume != null) {
                                int nextInt = Integer.parseInt(NextSiblingNodeVolume.getValue());
                                if (aInt > nextInt) {
                                    System.out.println(aInt + "is larger than" + nextInt);
                                }
                            }
                        }

                    }

                }
            }

        } catch (DocumentException e) {
            System.out.println(e.getMessage());
        }

    }

}

A: To use DOMElement, you need to specify org.dom4j.dom.DOMDocumentFactory for creating SAXReader. DOMDocument will be created and you can case those objects to W3C or org.dom4j.dom.* class.
import java.util.*;
import org.dom4j.dom.*;
import org.dom4j.io.SAXReader;
import org.w3c.dom.*;

public class Sampe1 {

public static void main(String[] args) throws Exception {
SAXReader reader = new SAXReader(DOMDocumentFactory.getInstance());
DOMDocument document = (DOMDocument)reader.read("catalog.xml");
List books =document.selectNodes("catalog/book");
for(Iterator i = books.iterator(); i.hasNext();){
   DOMElement book = (DOMElement)i.next();
   List aList = book.elements("a");
   for(Iterator i2 = aList.iterator(); i2.hasNext();){
      DOMElement aNode = (DOMElement)i2.next();
      Node NextSiblingNode = (Node)aNode.getNextSibling();
      System.out.println(NextSiblingNode);//next one is org.dom4j.dom.DOMText...
   }
}
}


text:
Q: Broken Ubuntu 18.04 package: unmet dependencies: I am new using ubuntu 18.04 and run into problem when doing daily upgrade.
Here is what I got when I ran: sudo apt upgrade
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 linux-image-4.15.0-111-generic : Depends: linux-modules-4.15.0-111-generic but it is not going to be installed
E: Broken packages

Thank you in advance for help


text:
Q: Отключение eventFilter для дочерних элементов при реализации функции перемещения окна Я пытаюсь сделать функционал перемещения окна, но есть одна проблема: не знаю, как отключить эту функцию на дочерних элементах для ui->frame_hint (три кнопки QPushButton). Т.е. при попадании курсора на эти кнопки, окно "прыгает". Другими словами, мне нужно перемещать окно курсором мыши за объект ui->frame_hint, за исключением случаев, когда курсор попадает на дочерние для ui->frame_hint объекты.
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->frame_hint)
    {
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
            if (mouse_event->button() == Qt::LeftButton)
            {
                mouseClickCoordinate = mouse_event->pos();
                return false;
            }
        }
        else if (event->type() == QEvent::MouseMove)
        {
            QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
            if (mouse_event->buttons() & Qt::LeftButton)
            {
                this->move(mouse_event->globalPos() - mouseClickCoordinate);
                return false;
            }
        }
    }
    return false;
}

A: Удалось это сделать с помощью дополнительной переменной
bool clickPressedFlag = false;

и с использованием
QEvent::MouseButtonRelease

Рабочий код:
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonRelease)
    {
        QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
        if (mouse_event->button() == Qt::LeftButton)
        {
            clickPressedFlag = false;
            return QMainWindow::eventFilter(watched, event);
        }
    }

    if (watched == ui->frame_top_btns)
    {
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
            if (mouse_event->button() == Qt::LeftButton)
            {
                mouseClickCoordinate = mouse_event->pos();
                clickPressedFlag = true;
                return QMainWindow::eventFilter(watched, event);
            }
        }
        else if ((event->type() == QEvent::MouseMove) && clickPressedFlag == true)
        {
            QMouseEvent* mouse_event = dynamic_cast<QMouseEvent*>(event);
            if (mouse_event->buttons() & Qt::LeftButton)
            {
                this->move(mouse_event->globalPos() - mouseClickCoordinate);
                return QMainWindow::eventFilter(watched, event);
            }
        }
    }
    return QMainWindow::eventFilter(watched, event);
}

A: к чему велосипеды если есть
void QObject::removeEventFilter(QObject *obj)


text:
Q: Lenovo Legion M600 wireless bluetooth mouse connected and paired yet not working on Arch Linux Situation
I have a Lenovo Legion M600 Mouse, which works fine through USB-C cable and a vender-specific wireless USB-receiver on my system. However, I am not able to get the mouse working via bluetooth. My OS is Arch Linux, which is not officially supported.
Problem
Bluetooth seems to work fine (paired + connected), but I am not getting any mouse input data such as mouse movement and button clicks. I've tested on another device, and this bluetooth mouse works fine there (Android phone).
What I have tried
After I hold the button at the bottom for a few seconds, LEDs begin to indicate it is in pairing mode, after which I paired it successfully. Bluetooth pairing and connecting works fine. See the output below (from bluetoothctl):
Device **:**:**:**:**:** (public)
        Name: Legion M600 Mouse
        Alias: Legion M600 Mouse
        Appearance: 0x03c2
        Icon: input-mouse
        Paired: yes
        Trusted: yes
        Blocked: no
        Connected: yes
        WakeAllowed: yes
        LegacyPairing: no
        UUID: Generic Access Profile    (00001800-0000-1000-8000-00805f9b34fb)
        UUID: Generic Attribute Profile (00001801-0000-1000-8000-00805f9b34fb)
        UUID: Device Information        (0000180a-0000-1000-8000-00805f9b34fb)
        UUID: Battery Service           (0000180f-0000-1000-8000-00805f9b34fb)
        UUID: Human Interface Device    (00001812-0000-1000-8000-00805f9b34fb)
        Battery Percentage: 0x5f (95)

My bluetooth adapter is (lsusb):
Bus 001 Device 005: ID 8087:0029 Intel Corp. AX200 Bluetooth

After connecting a new device shows up here: /sys/class/bluetooth/hci0:[some identifier for the mouse]/. Also, a new hidraw device is added at: /dev/hidrawX. But cat -A /dev/hidrawX does not show any output. There is also an additional mouse-device visible, which seems correct (excerpt from ls -la /dev/input/by-id/):
lrwxrwxrwx 1 root root  10 Jan  5 19:22 usb-Lenovo_Lenovo_Legion_M600_Wireless_Gaming_Mouse-event-if00 -> ../event20
lrwxrwxrwx 1 root root  10 Jan  5 19:22 usb-Lenovo_Lenovo_Legion_M600_Wireless_Gaming_Mouse-event-mouse -> ../event17
lrwxrwxrwx 1 root root  10 Jan  5 19:22 usb-Lenovo_Lenovo_Legion_M600_Wireless_Gaming_Mouse-if01-event-kbd -> ../event21
lrwxrwxrwx 1 root root   9 Jan  5 19:22 usb-Lenovo_Lenovo_Legion_M600_Wireless_Gaming_Mouse-mouse -> ../mouse0

The kernel logs give me this (dmesg -k):
input: Legion M600 Mouse as /devices/virtual/misc/uhid/0005:17EF:60E7.000B/input/input28
hid-generic 0005:17EF:60E7.000B: input,hidraw0: BLUETOOTH HID v1.00 Mouse [Legion M600 Mouse] on **:**:**:**:**:**

This is the only bluetooth device connected, but I also tried bluetooth on my keyboard, which does actually work fine (out-of-the-box).
I'm having a hard time tracking down where the issue lies. I have paired it with my Android phone, and I can use it to control the cursor on Android, and interact like you would expect from a mouse. So the problem has to be somewhere on my end, the mouse nor its firmware is clearly not faulty.
I am using the latest version of Arch Linux (uname -a):
Linux localhost 5.15.12-arch1-1 #1 SMP PREEMPT Wed, 29 Dec 2021 12:04:56 +0000 x86_64 GNU/Linux

Drivers loaded in the kernel are (lsmod | grep -E 'bt|blu|hid|hci|usb'):
uhid                   20480  1
hidp                   32768  1
btusb                  65536  0
btrtl                  28672  1 btusb
btbcm                  24576  1 btusb
hid_apple              20480  0
btintel                45056  1 btusb
bluetooth             749568  33 btrtl,hidp,btintel,btbcm,bnep,btusb
usbhid                 73728  0
ecdh_generic           16384  2 bluetooth
usb_storage            81920  1 uas
rfkill                 32768  8 bluetooth,cfg80211
mac_hid                16384  0
crc16                  16384  2 bluetooth,ext4
xhci_pci               20480  0
xhci_pci_renesas       24576  1 xhci_pci

I also checked if the mouse exists for Xorg server (xinput | grep M600):
⎜   ↳ Lenovo Lenovo Legion M600 Wireless Gaming Mouse Consumer Control  id=12   [slave  pointer  (2)]
⎜   ↳ Lenovo Lenovo Legion M600 Wireless Gaming Mouse   id=14   [slave  pointer  (2)]
⎜   ↳ Legion M600 Mouse                         id=19   [slave  pointer  (2)]
    ↳ Lenovo Lenovo Legion M600 Wireless Gaming Mouse Consumer Control  id=13   [slave  keyboard (3)]
    ↳ Lenovo Lenovo Legion M600 Wireless Gaming Mouse   id=16   [slave  keyboard (3)]

Everything seems fine, except the cursor is really not moving when I mouse the mouse. And clicking the buttons does not work either. I have tried to repair, reconnect, remove all bluetooth related files from /var etc, and reinstalled bluetooth software. Installed additional bluetooth and xorg-driver packages from the repository. I'm getting out of ideas here, anyone got a clue?

A: It seems some changes are needed to BlueZ to support our mouse.
I asked in linux-bluetooth mailing list and in response HCI log with use of btmon was requested.
btmon shows events from the mouse, which is a good sign I suppose.

A: I was experiencing the same issue with BlueZ version 5.53, updating BlueZ to the latest version (5.65 as of writing this), solved the issue.
This issue mentioned in here.
You can check version of yours with:
bluetoothctl --version

You can clone the repo and follow steps provided in here to update it.