text:
Q: c++ How to manipulate and work with UTF-8 characters I am trying to read a UTF-8 encoded .txt file and need to do validations on it.
I am working on Windows 10 even though I need the solution to work the same way on Linux. I work with Dev c++ 6.3, TDM-GCC 9.2.0 64-bit Compiler and I am compiling with GNU C++11
At the moment I am reading the following .txt file:
Inicio
D1
Biatlón
S1
255
E1
Esprint 7,5 km (M); 100; 200
E2
Persecucion 10 km (M); 100; 200
ff

This is my code:
#include <iostream>
#include <locale.h>
#include <locale>
#include<fstream>
#include<string>
#include <windows.h>
#define CP_UTF8 65001
#define CP_UTF32 12000

#include <codecvt>

using std::cout;

std::wstring utf8_to_ws(std::string const&);

int main(){

    std::ifstream file;
    std::string text;

    if (!SetConsoleOutputCP(CP_UTF8)) {
        std::cerr << "error: UTF-8 codigo.\n";
        return 1;
    }

    file.open("entryDisciplineESP.txt");

    int line = 0;

    if (file.fail()){

        cout<<"Error. \n";

        exit(1);

    }

    while(std::getline(file,text)){

        if(linea == 2){

            std::cout<<text[5]<<"\n";
            auto a = utf8_to_ws(text);
            std::wcout<<a<<"\n";

        }

        std::cout<<text<<"\n";

        line++;

    }

    cout<<"\n";

    system("Pause");
    return 0;
}

std::wstring utf8_to_ws(std::string const& utf8)
{
    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cnv;
    std::wstring s = cnv.from_bytes(utf8);
    if(cnv.converted() < utf8.size())
        throw std::runtime_error("incomplete conversion");
    return s;
}

And I am receiving the following by console:
Inicio
D1

Biatln
Biatlón
S1
255
E1
Esprint 7,5 km (M); 100; 200
E2
Persecucion 10 km (M); 100; 200
ff

If I print the file on the screen, I receive the character "ó" but not separately, I need to interact with that character to do validations, I need to check that there are no numbers or special characters on that line: "!,?,:" etc. I also need to save that name in a string and be able to interact with it and display results on the console.
Thanks in advance.

A: There are a whole can of worms to dealing with Unicode on Windows, alas, but your main problem (for this example) is that you are treating a Unicode "character" (a code-point) as if it were a single byte entity. (And you are doing it before you have converted to wide string!)
When dealing with UTF-8, you no longer have that luxury. Once you admit UTF-8, everything is a string. Even single code points.
In other words, every "character" must now be treated as a 1–4 byte string.
Thus, to print ó to any stream (not just the terminal), you must print the proper multi-byte UTF-8 code sequence "ó". Notice it is a string. (It is not a one-byte char.)
Hint 1:
If you want to be safe on all versions of Windows using whatever output console/terminal your program is attached to, use the Windows wide character Console API routines for all output. You can easily set the rdbuf for the standard streams to use a custom UTF-8 → UTF-16 convert-and-print buffer for those that are attached to the console/terminal, and leave them alone otherwise.
Hint 2: Every modern system has an ICU database on it that you can use: Linux, Windows, Android, iOS, etc. Use it to deal with UTF-encoding conversions.


text:
Q: HTML5 Canvas and manipulating I havent had much exposure to the Canvas element in HTML5. I have done basic things such as rendering a rectangle to the Canvas
It it possible to assign a Class or Id to said rectangle and manipulate via jQuery such as assigning a click event?

A: To answer your question: No, it's not possible: elements, shapes and images drawn on <canvas> elements are not part of the DOM.
Yet, there are a lot of "framework"-type of libraries out there that add interactive capabilities. As mentioned in the comments there's Raphael or jCanvas or Kinetic or many many more.
If you want to go canvas on your own I found the tutorials on MDN or html5rocks pretty useful.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Left join multiple rows I have the following tables:

I'd like to join the two tables so I can list each farm on the farm table alongside each product on the produce table, but I'm not sure how. This is what I've got so far:
SELECT p.*, f.farm_name, f.county
FROM produce p
LEFT JOIN farms f on p.farm_id = f.id
GROUP by f.id
ORDER BY f.farm_name

A: SELECT p.*
FROM produce p
inner join farms f on p.farm_id = f.id

in your php fetching code do like this,
$row["farm_name"];

It will return farm name with every produce row.

A: Former versions of SQL standards (SQL-92 and earlier) do not permit queries with the SELECT HAVING orORDER BY clause refer to non-aggregated columns that are not named in the GROUP BY clause. If you look back at your original query you will see that your query does exactly what those standards do not permit.
SELECT p.*, f.farm_name, f.county
...
GROUP BY f.id

"non-aggregating column" means any column not using an aggregate function such as sum() count() avg() and so on
To make your query comply with those standards every column listed under select would be specified in that group by clause, not just one. MySQL has a feature that allows you to run a non-compliant style of grouping query. Had it instead informed you that query was improper syntax you would probably have realised group by isn't helping you here.
This indicates you are using MySQL, and that you do not have the SQL Mode ONLY_FULL_GROUP_BY on.
I urge you to avoid this MySQL weakness, turn the SQL Mode ONLY_FULL_GROUP_BY on.
See:
https://dev.mysql.com/doc/refman/8.0/en/group-by-handling.html


text:
Q: Is there a simple/complicated way to create requestData() method using Sockets As the title says, I need a way(no matter if its complicated or not) to create a getData() method that would send request packet to the server > receive the message I already have the system setup but I have a problem with it that I only get the result in PluginMessageReceiveEvent Here's my code with explanations:
public String requestData(String path) {
    SocketUtils.sendData("REQUEST|" + p.getPlayer().getUniqueId() + "|" + path, "playerconfig", "BUNGEE");
    return /*Need to get data from the plugin message to here*/;
}

@EventHandler
public void onPluginMessageReceive(PluginMessageReceiveEvent e) {
    if (e.getChannel().equalsIgnoreCase("playerconfig")) {
        String[] args = e.getMessage().split("\\|");
        String uuid = args[0];
        String path = args[1];//Maybe a HashMap<Path, Data> but that would make the requestData() result return null because you don't get the data instantly.
        String data = args[2].replace("_", " ");
        if (uuid.equals(p.getPlayer().getUniqueId() + "")) {
            return data; //I need to get this result on request data method.
        }
    }
}

A: A simple solution is to wait on a lock in the requestData and notify that lock in onPluginMessageReceive. Something like this:
 synchronized(this) {
    wait();
 }

And in your receive method:
 synchronized(this) {
    notifyAll();
 }

Make the data a member field of the class.
Look out for exception handling and syntax errors.


text:
Q: Get commit history of all the contributors of a repository Is there a way to get the commit history of all the contributors of a git repo with lines added,deleted.
Currently the statistics api provides the stats of top 100 contributors, but not everyone.
https://developer.github.com/v3/repos/statistics/
(https://api.github.com/repos/saltstack/salt/stats/contributors

A: You won't get more than 100 through the GitHub API alone: see "How can I get more than 100 results from GitHub API v3 using "github_api" gem?".
The results are capped at 100.
You would need top clone the repo, and then show the number of changed lines per author in git.
or use a tool like gitinspector:


text:
Q: PyGame Sprite conflicting collisions So my sprites in pygame all have the same collision effects even thou i separated them into different defs do you know how i could fix this ?
def render(self,collisionrock):

    if (collisionrock==True):
        pygame.draw.rect(window,red,(150,150,100,100))   #for some reason this wont work
        window.blit(self.i1, (self.x,self.y))

def render(self,collisionguy):

    if (collisionguy==True):
        font = pygame.font.Font(None, 50)
        text = font.render("YOU WIN", 1, (10, 10, 10))   #they would all apply this line
        textpos = text.get_rect()                        #of code
        textpos.centerx = window.get_rect().centerx
        window.blit(text, textpos)

        window.blit(self.i1, (self.x,self.y))
    else:
        window.blit(self.i1, (self.x,self.y))

A: It seems that you have two methods with the same name "render" in your sprite class.
In that case Python'll ignore the first method (that has collisionrock argument) and use only the second definition. That seems to be the case.
You can rename first "render" to "render_with_rock_collision", second "render" to "render_with_guy_collision".
And one other thing. Instead of
if (collisionguy==True):

you can write:
if collisionguy:

Makes Guido Van Rossum happy.


text:
Q: jquery getScript choking on returned script I'm using MVC 4 which works OK to return a JavaScriptResult. I've tested it with simple javascript.
However, although I can see in firebug that getScript returns javascript to the browser, the code below does not work:
@{
    Layout = null;
}

<!DOCTYPE html>

<meta name="viewport" content="width=device-width" />
<title>Categories Page</title>

test

But if I replace:
$(document).ready(function () {
        $.getScript('http://localhost:53353/z/categories');
});

.. with the javascript that is returned to the browser when getScript is called, then the code does work.
The returned javascript when getScript is called is just standard javascript to call a google barchart. The script tags are omitted in the returned script also, since getScript adds these.
The question is, why is getScript choking on the returned script when I can just copy and paste the returned script and substitute it for the getScript section in order to know with certainty that the returned script is not defective, since the page renders correctly when the substitution is made?
OK. Let's forget about MVC.
Just using HTML (and javascript based on the example at
https://developers.google.com/chart/interactive/docs/gallery/barchart ), we have the following which works:
<!DOCTYPE html>

    <title>Categories Page</title>

test

testscript.js contains only:
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
    ['Year', 'Sales', 'Expenses'],
    ['2004', 1000, 400],
    ['2005', 1170, 460]
]);
var options = { title: 'Company Performance', vAxis: { title: 'Year', titleTextStyle: { color: 'red' } } };
var chart = new google.visualization.BarChart(document.getElementById('chart_div')); chart.draw(data, options); }

But, if we now rewrite the line...

as...

...the browser just hangs, even though you can see the contents of testscript.js in the Response in Firebug. Just substituting the contents of testscript.js for something simple like alert('hello'); allows getScript to work OK, but anything as complex as testscript.js above and getScript just stops working.

A: maybe the file has not loaded yet, before you start calling the functions in it.
Can you try the operations in the success function?
$.getScript('http://localhost:53353/z/categories', function(data, textStatus, jqxhr) {
   if(textStatus == 'success') {
      //do work here
   }
});

A: I tried to use $.getScript for an application I'm working on, to push the loading of a rather heavy date picker script off until it's known to actually be needed.
I found a similar kind of hanging where the browser would just go blank and appear to be loading forever.
I inspected the DOM and what I found was that the date picker script was manipulating the document using document.write() calls and, instead of appending to the document, they had replaced the entire document. Getting rid of those fixed this issue in my app, but I later discovered that I already had jQuery UI and that it was silly for me to be using the legacy date picker.
Of course, it has been a while since the question was posted, so the odds are it has all been figured out by now.


text:
Q: Is the exact form of the Higgs potential known? Usually the Higgs potential is given as $$ \frac{1}{2}\mu^2\phi^2 - \frac{1}{4}\lambda^2\phi^4 $$ but I never quite understood if this just serves to give us an idea of how symmetry breaking works, or if it is actually the correct expression for the potential.
Does the potential above agree with experiments? Is that the Higgs potential?

A: Yes, that is the Higgs potential of the Standard Model.
Note that a $\phi^3$ term is forbidden by symmetry (it would not be an $\mathrm{SU}(2)$ scalar), and $\mathcal{O}(\phi^5)$ terms would be non-renormalizable, so this is really the only potential we can write down that does not need other new physics.


text:
Q: Complements of a subspace
Show that a non-trivial subspace $U$ of $V$ has two virtually disjoint complements iff $dim(U)\geq \frac{dim(V)}{2}$.

Definition 1:$S$ and $T$ are said to be virtually disjoint if $S\cap T=\{0\}$.
Definition 2: A subspace $T$ of $V$ is said to be complement of $S$ (a subspace of $V$) if $S\oplus T=V$ (i.e. $S+T$ is direct sum).
The if part is done, I am stuck with the only if part of the question. If possible try to find a suitable answer using Modular Law.
Any help will be appreciated.

A: for the only if, use the formula for the sum of subspaces, reported for example in here.
In fact, if $S,T$ are the disjoint complements, then
$$
dim(S) + dim(T) = dim(S + T) \le dim(V)
$$
but $dim(S) = dim(T) = dim(V) - dim(U)$ so
$$
dim(U) = dim(V) - dim(S) \ge dim(V) - \frac{\dim(V)}2= \frac{\dim(V)}2.
$$


text:
Q: Should unit tests be written for private methods in event-driven code? I'm writing my first Windows Forms program, using C#. It consists of 3 classes, one for each form. Other than the constructors, all of the methods within each class are private.
In trying to figure out how to write unit tests for the methods, I've found several posts and articles saying that there shouldn't be unit tests for private methods, because a private method is an implementation, not a public behavior.
I think I understand that reasoning, but that appears to mean that NONE of my code will have unit tests written for it. Everything is event-driven, happening when a button is clicked, a value is entered in a field, or a timer ticks.
Is that correct? Should my code have no unit tests at all? (I apologize if this is a duplicate of another question. I looked, but couldn't find anything that addressed this issue.)

A: Indeed private methods are private implementations of your application and they shouldn't be unit test for them. Most of the time they are going to be called internally by public methods. By testing public methods then you are testing those private methods.
Your private methods are event driven as you said  which will be executed when a user clicked on a button etc... If you think that your event handlers contain a lot of logic that should be tested then I recommend to follow this steps:

*

*Mark all classes (Forms) that contain your event handlers with the internal modifier. With this modifier those classes are only accessible in the the same assembly at which they are defined.

*You need also to mark all your event handlers methods with the public modifier. Because the classes at step 1 are internal those methods are only visible to the assembly where they are defined then only in your Windows Forms project.

*Into the AssemblyInfo.cs file of your Windows Forms project add this attribute : [assembly: InternalsVisibleTo("MyTestAssemblyName")] where MyTestAssemblyName is the assembly name of your test project.

*By doing the step 3. all your internal classes hence event handlers are also  visible to your test project. At this step and referencing your Windows Formsq project to your test project then you can unit test your event handlers as you will do with every method.


text:
Q: pointers to arrays in c not working char (*ptr)[10];
scanf("%s",ptr);//inputing a string

Why is this not working?
According to me this should work because ptr is a pointer to an array of characters.

A: A pointer to an array is NOT an array, you have nowhere to put your characters.
It's like having a doormat without a house, that doesn't mean you have somewhere to receive your guests.
To have the above working you should
char ptr[10]; // This is where you have space, specifically stack space
char (*this_is_a_pointer_to_array)[10]; // This only holds space to keep an address to an array
this_is_a_pointer_to_array = &ptr;
scanf("%s",ptr);

although you don't really need the pointer to array in the case above.
A pointer to an array only holds as much space as necessary to hold the address to an array, there's no space to store anything else than an address. If you horribly circumvent the typecasting mechanism you might use that space to store some characters instead of an address, but that is against every moral fiber of my body and probably against every typecasting rule as well.

A: ptr is not a pointer to char instead it is a pointer to an array of 10 chars.


text:
Q: Content from external iframe not loaded until page is refreshed for several days I'm struggling with putting ads to my personal website and since I'm already out of ideas I would like to ask you for help. Any idea or suggestion is highly welcome because I'm really desperate.
I got a short JS code from the ad network to put on my website. The code basically loads, dynamically creates iframe and loads ad content to this iframe from the ad company (more or less standard approach).
However in my case the iframe is created but the content is not loaded until I refresh the page one or more times.
The symptoms I identified are following:

*

*it happens only on my site, ads from the same ad network work fine on different webs in the same browser

*I'm able to reproduce the same behavior on different browsers, devices and operating systems = not local issue

*the problem is not in my CMS (Wordpress)

To isolate the problem and make sure that the issue is not in any of Wordppress plugins or Wordpress itself I created simple test page on the same domain out of Wordpress:
https://www.beapple.pro/test.html
Just pure HTML, short text and the ad code. When you open this page the ad is not loaded on the first load, it must be refreshed.
I also found out that if I disable cross-domain tracking prevention in the browser (e.g. Safari) it works fine. However the ads from this network should work even if no cookie is set. And after several refreshes of the page it works as well no matter if the cookie is set or not. As I said ads from the same ad network work on different sites fine, therefore the dependency on cookies is probably not important. If the ad is finally displayed, it stays fine for some minutes and then it disappears again (probably cache).
I also tracked the HTTP request / response communication when the iframe is loaded. I found out that that the response contains empty HTML code if the ad is not displayed (at least this is what browser shows me in debug mode). The ad company told me that the request probably times out due to slow connection however I do not believe them since I verified the same behavior from different places and different connections.
The behavior is very strange and despite my effort I did not find root cause of the issue. If it happened only on my machine, I would say it is a local problem, if I had the same problem on all webs, I would say it is problem of the ad company. However it can be reproduced on any device (with blocking of 3rd party cookies enabled) but only on my domain.
Please help, you are my last resort. Thanks a lot for any input.
UPDATE: Any workaround is welcome as well. I did not figure out how to refresh the iframe reliably. Since I cannot access the inner html of the iframe due to browser security rules, it is hard to find out if there is any content or not = if refresh worked.


text:
Q: Find value $x$ of equation $e^x=\tan (e^x)$ I want to find the values of $x$ for which
$$e^x=\tan(e^x)$$
How can I proceed?
I tried to plot the graph and it looks like it intersect $x$ axis at infinitely many points.

Can someone please direct me in the right direction.

A: Rewrite the equation as $u=\tan u$ with $u=e^x$. Observe that $u=0$ is a trivial root, and all others are fairly close to $r_n=(\frac12+n)\pi$, with $n=\pm1,\pm2,\pm3$ ... and infinite number of roots.
Although there are no close-form solutions, clean, yet accurate, analytic approximations are known, such as the one below,
$$u_n = r_n - \frac1{r_n}$$
Listed below are the first few, along with the exact values in parentheses.
$$u_1 = \frac{3\pi}2-\frac2{3\pi}=4.500 \>(4.493)$$
$$u_2 =  \frac{5\pi}2-\frac2{5\pi}=7.725\> (7.727)$$
$$u_3 = \frac{7\pi}2-\frac2{7\pi}= 10.905\> (10.904)$$
$$…$$


text:
Q: how to re-try request for 401 along with TransientHttpError ( 5XX and 408) Below code re-try 2 times when we have error from HttpRequestException, 5XX and 408 and it's works fine.
Here I want to re-try for even 401 error? how we can achieve this with Polly?
 services.AddHttpClient(Options.DefaultName)
            .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
            .AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
                .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));

A: Add .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized) to your code:
services.AddHttpClient(Options.DefaultName)
        .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { })
        .AddPolicyHandler(HttpPolicyExtensions.HandleTransientHttpError()
        .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
        .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));

I would suggest rewriting your code like this to make it easier to read:
services.AddHttpClient(Options.DefaultName)
        .AddTransientHttpErrorPolicy(builder =>
            builder
                .OrResult(r => r.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                .WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))))
        );


text:
Q: wget does not follow Internet page redirection For a concrete example of the problem, when I go to the following address in a regular browser:
http://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240

I get re-directed to https that contains a PDF file:
https://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240

However, when I do:
wget http://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240

the redirection does not happen and the PDF is not fetched. Note that this happens during the execution of a script, in which I only have the http address. Is there a way to make wget follow this re-direction and fetch the file?


text:
Q: SQL pivot query returns null on some columns I have the following query that returns a car reg number together with the date it was seen and the location:
SELECT PLATE_READ.RegNumber, PLATE_READ.DateSeen, ANPR_CAMERA.Name FROM PLATE_READ

REG         DATESEEN               LOCATION
===         ========               ========
5897HHS     20/12/2013 12:10:57    GIB EXIT
5897HHS     20/12/2013 12:05:03    AIRPORT BARRIER

Rather than having three rows I would like to be able to query and have 1 row returned per registration number stating the dates it has been seen per location with the following format:
REG         GIB EXIT             AIRPORT BARRIER
===         =============        ==============
5897HHS     20/12/2013 12:10:57  20/12/2013 12:05:03

This is what I have so far:
SELECT *
FROM
  (SELECT TOP(100) PLATE_READ.DateSeen,
    PLATE_READ.RegNumber,
    ANPR_CAMERA_GROUP.Name
  FROM ANPR_CAMERA
  INNER JOIN ANPR_CAMERA_GROUP
  ON ANPR_CAMERA.Id = ANPR_CAMERA_GROUP.Id
  INNER JOIN ANPR_CAMERA_IN_GROUP
  ON ANPR_CAMERA.Id        = ANPR_CAMERA_IN_GROUP.ANPRCameraId
  AND ANPR_CAMERA_GROUP.Id = ANPR_CAMERA_IN_GROUP.ANPRCameraGroupId
  INNER JOIN PLATE_READ
  ON ANPR_CAMERA.Id = PLATE_READ.CameraId
  ORDER BY PLATE_READ.DateSeen DESC
  ) x pivot ( MAX(DateSeen) FOR Name IN ([GIB EXIT], [AIRPORT BARRIER]) )p

However this is always returning a NULL value for the 'GIB EXIT' entry

A: Trying to build the scripts to test your example (which would have been helpful if you'd provided that), the answer became obvious.
You are selecting ANPR_CAMERA.Name in your first SQL, and ANPR_CAMERA_GROUP.Name in your pivot SQL.


text:
Q: Окно появляется и сразу исчезает Я хочу вывести График, после нажатой кнопки. Но у меня окошко появляется и сразу исчезает.
ksp_ecology.cpp:
...
    void ksp_ecology::on_pushButton_clicked()
    {

    //![1]
        QLineSeries *series = new QLineSeries();
    //![1]

    //![2]
        series->append(0, 6);
        series->append(2, 4);
        series->append(3, 8);
        series->append(7, 4);
        series->append(10, 5);
        *series << QPointF(11, 1) << QPointF(13, 3) << QPointF(17, 6) << QPointF(18, 3) << QPointF(20, 2);
    //![2]

    //![3]
        QChart *chart = new QChart();
        chart->legend()->hide();
        chart->addSeries(series);
        chart->createDefaultAxes();
        chart->setTitle("Simple line chart example");
    //![3]

    //![4]
        QChartView *chartView = new QChartView(chart);
        chartView->setRenderHint(QPainter::Antialiasing);
    //![4]

    //![5]
        QMainWindow window;
        window.setCentralWidget(chartView);
        window.resize(400, 300);
        window.show();
    //![5]
    }
...

A: Нельзя создать в функциях на стеке (QMainWindow window;) виджеты, которые после создания будут отображены.
Есть два способа выделять память: на стеке (ваш вариант) и в куче (через оператор new).
В функции вы создаете на стеке виджет и отображаете его, тут же функция завершает работу и ее стек чистится, а вместе со стеком и удаляется виджет.
Решения проблемы:

*

*Самое простое. У вас класс, а значит, можно вынести переменную из функции в поля класса.
ksp_ecology.h:
class ksp_ecology : public QWidget {
    ...
    private:
        QMainWindow window;
    ...
}

*Создание объекта на куче. Тогда самим нужно будет чистить память за виджетом
//![5]
    QMainWindow* window = new QMainWindow();
    window->setCentralWidget(chartView);
    window->resize(400, 300);
    window->show();
//![5]

*Остановка выполнения кода функции через цикл обработки событий, который завершится с закрытием виджета. В диалогах это сделано через метод exec. Либо это можно сделать самому используя QEventLoop


text:
Q: ODBC Item on MySQL query causes Zabbix server to stop I'am new to Zabbix. Today I've tried to add a SQL item (Database monitoring) to a host without success.
Without this SQL item, the Zabbix server runs fine. I check this with service zabbix-server status.
After I enable the SQL item, hit Check now for it, and run service zabbix-server status again, I've got an error:
 zabbix-server.service - Zabbix Server
   Loaded: loaded (/lib/systemd/system/zabbix-server.service; disabled; vendor preset: enabled)
   Active: active (running) since Fri 2018-11-09 15:41:10 CET; 1s ago
  Process: 330 ExecStop=/bin/kill -SIGTERM $MAINPID (code=exited, status=1/FAILURE)
  Process: 335 ExecStart=/usr/sbin/zabbix_server -c $CONFFILE (code=exited, status=0/SUCCESS)
  ...

You can see that process 330 reports status=1/FAILURE.
After I hit Check now the Zabbix frontend pops up with Request sent successfully. But looking for this item in Monitoring > Latest data there is no value.
The item is configured as:

*

*Type: Database monitor

*Key: db.odbc.select[num-of-events,backend]

*User name: (empty)

*Password: (empty)

*SQL query: select 1;

*Type of information: Numeric (unsigned)

The ODBC data source backend seems to be working fine:
$ isql backend
> +---------------------------------------+
> | Connected!                            |
> |                                       |
> | sql-statement                         |
> | help [tablename]                      |
> | quit                                  |
> |                                       |
> +---------------------------------------+
>  SQL> select 1;
> +---------------------+
> | 1                   |
> +---------------------+
> | 1                   |
> +---------------------+
> SQLRowCount returns 1
> 1 rows fetched

Here is my ODBC config:
/etc/odbcinst.ini
[mysql]
Description = ODBC for MySQL
Driver = /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8S.so
FileUsage = 1

/etc/odbc.ini
[ODBC Data Sources]
backend  = MySQL unicode backend DSN

[backend]
Driver = mysql
Decription = Connector/ODBC Driver to Backend DB
Server = localhost
Port = 3306
User = ???
Password = ???
Database = backend
OPTION = 3
SOCKET = /var/run/mysqld/mysqld.sock

Zabbix is running on Debian Stretch.
Zabbix server version is 4.0.1.
MySQL version is 10.1.26-MariaDB-0+deb9u1
Any idea why the server crashes?
Edit: There is no difference when using the ANSI driver libmyodbc8a.so instead of the Unicode driver libmyodbc8w.so.
Edit 2: Tested also with ANSI and Unicode version mysql-connector-odbc-5.3.11-linux-debian9-x86-64bit without success.
zabbix-server.log tells the error
 10002:20181109:170635.268 Got signal [signal:11(SIGSEGV),reason:1,refaddr:0x60]. Crashing ...
 10002:20181109:170635.269 ====== Fatal information: ======
 ...
 10002:20181109:170635.269 === Backtrace: ===
 10002:20181109:170635.270 27: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](zbx_backtrace+0x35) [0x55a008633b24]
 10002:20181109:170635.270 26: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](zbx_log_fatal_info+0x119) [0x55a008633d38]
 10002:20181109:170635.270 25: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](+0xf0060) [0x55a008634060]
 10002:20181109:170635.270 24: /lib/x86_64-linux-gnu/libpthread.so.0(+0x110c0) [0x7f1e2039a0c0]
 10002:20181109:170635.270 23: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(+0x79e4d) [0x7f1e12b3ee4d]
 10002:20181109:170635.270 22: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(_Z22add_compiled_collationP12CHARSET_INFO+0x25) [0x7f1e12b3f995]
 10002:20181109:170635.270 21: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(_Z22init_compiled_charsetsi+0x15) [0x7f1e12b8eda5]
 10002:20181109:170635.270 20: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(+0x7918f) [0x7f1e12b3e18f]
 10002:20181109:170635.270 19: /lib/x86_64-linux-gnu/libpthread.so.0(+0xe739) [0x7f1e20397739]
 10002:20181109:170635.270 18: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(_ZSt9call_onceIRFvvEJEEvRSt9once_flagOT_DpOT0_+0x5a) [0x7f1e12b3dcea]
 10002:20181109:170635.270 17: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(_Z22my_charset_get_by_nameP17MY_CHARSET_LOADERPKcji+0x2a) [0x7f1e12b3e67a]
 10002:20181109:170635.270 16: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(_Z21get_charset_by_csnamePKcji+0x3b) [0x7f1e12b3e70b]
 10002:20181109:170635.270 15: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(myodbc_init+0x156) [0x7f1e12b24951]
 10002:20181109:170635.270 14: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(my_SQLAllocEnv+0x1c) [0x7f1e12b2825b]
 10002:20181109:170635.270 13: /usr/lib/x86_64-linux-gnu/odbc/libmyodbc8w.so(SQLAllocHandle+0x60) [0x7f1e12b29326]
 10002:20181109:170635.271 12: /usr/lib/x86_64-linux-gnu/libodbc.so.2(+0xdbb7) [0x7f1e1f43dbb7]
 10002:20181109:170635.271 11: /usr/lib/x86_64-linux-gnu/libodbc.so.2(SQLConnect+0x217) [0x7f1e1f43fdc7]
 10002:20181109:170635.271 10: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](zbx_odbc_connect+0x1ac) [0x55a0085c697b]
 10002:20181109:170635.271 9: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](get_value_db+0x22a) [0x55a00859d132]
 10002:20181109:170635.271 8: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](+0x4968d) [0x55a00858d68d]
 10002:20181109:170635.271 7: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](+0x4b950) [0x55a00858f950]
 10002:20181109:170635.271 6: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](poller_thread+0x192) [0x55a0085909d4]
 10002:20181109:170635.271 5: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](zbx_thread_start+0x32) [0x55a0086411de]
 10002:20181109:170635.271 4: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](MAIN_ZABBIX_ENTRY+0x9ac) [0x55a00857bcee]
 10002:20181109:170635.271 3: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](daemon_start+0x315) [0x55a008633346]
 10002:20181109:170635.271 2: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](main+0x2f6) [0x55a00857b340]
 10002:20181109:170635.271 1: /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf1) [0x7f1e1d1de2e1]
 10002:20181109:170635.271 0: /usr/sbin/zabbix_server: poller #2 [got 1 values in 0.004743 sec, getting values](_start+0x2a) [0x55a00857a51a]
 10002:20181109:170635.271 === Memory map: ===
 ...

Edit 3: Tested with mysql-connector-odbc-5.1.13-linux-debian6.0-x86-64bit.tar.gz and no success.
This failure seems related to https://support.zabbix.com/browse/ZBX-7665 and https://bugs.mysql.com/bug.php?id=73709

A: I've found a solution by using MariaDB ODBC connector instead of the MySQL connector.

*

*Download https://downloads.mariadb.com/Connectors/odbc/connector-odbc-3.0.6/ I use debian-x86_64.tar.gz

*Unpack it tar -xvzf mariadb-connector-odbc-3.0.6-ga-debian-x86_64.tar.gz

*Copy cp lib/libmaodbc.so /usr/lib/

*Add the following lines to /etc/odbcinst.ini
[mariadb]
Description = ODBC for MariaDB
Driver = /usr/lib/libmaodbc.so

*Edit you DNS in /etc/odbc.ini
Driver = mariadb
Socket = /var/run/mysqld/mysqld.sock

The last line is also important, otherwise the connector looks for /tmp/mysqld.sock.
This works on Debian Jessie (8) but not with Debian Stretch (9). If you run ldd libmaodbc.so you see that the MariaDB ODBC connector depends on libssl.so.1.0.0 but Stretch have only libssl.so.1.0.2 and libssl.so.1.1 installed.


text:
Q: No visible @interface for NSURL declares the selector componentsseparatedbystring The NSArray declaration brings up an error because "no visible @interface for NSURL declares the selector componentsseparatedbytring".
NSURL *MyURL = [[NSBundle mainBundle]
                 URLForResource: @"artList" withExtension:@"txt"];
NSArray *lines = [MyURL componentsSeparatedByString:@"\n"]; // each line, adjust character for line endings

for (int i = 0; i < 10; i++) {
    NSString *line;
    //in lines;
    NSLog(@"%@", [NSString stringWithFormat:@"line: %@", line]);
    _wordDefBox.text = [NSString stringWithFormat:@"%@%@",_wordDefBox.text, lines];
}

A: You missed a step. Once you have the URL, you need to load the file into an NSString. Then call componentsSeparatedByString on the NSString.
NSURL *myURL = [[NSBundle mainBundle]
                 URLForResource: @"artList" withExtension:@"txt"];
NSError *error = nil;
// Use the appropriate encoding for your file
NSString *string = [NSString stringWithContentsOfURL:myURL encoding:NSUTF8StringEncoding error:&error];
if (string) {
    NSArray *lines = [string componentsSeparatedByString:@"\n"];
    // and the rest
} else {
    NSLog(@"Unable to load string from %@: %@", myURL, error);
}

A: In general when you see such an error it means class X( here NSURL)  doesn't have any method named Y ( e.g. componentsseparatedbystring) or at least it doesn't have it in its interface ie it's not it's public method, it may be it's private method and available to its implementation. Always try to make sense of what the compiler is telling you. To find out more you can 'Cmmd + click' on any class and it will take you to it's interface and you can see what public methods it has. Try that on NSString and NSURL
Here specifically : NSURL doesn't have that method. It doesn't belong to NSURL, it belongs NSString.


text:
Q: Javascript Variables initialization types I need to know the difference between these three types of variable initialization.
1)- The first type is using the "this" keyword.
var x=function (data1,data2){
this.data1=data1;
this.data2=data2;
}

2)- Second is using the "var" keyword...from what i know the var keyword makes the scope of a variable local which means that var can only be accessible when we are inside the function.
var x=function (data1,data2){
var data1=data1;
var data2=data2;
}

3)- Third type is without using any keyword..from what i know is that we don't specify the var keyword with a variable then it becomes global for the complete application. So you can access it any where you want...but in this case i think this would throw an error...because how would javascript know if data1 is a variable or a parameter (the passed on argument) ?
var x=function (data1,data2){
data1=data1;
data2=data2;
}

A: 1) this.foo = bar
The first kind you mention makes your variables properties of a (constructor) function. In JavaScript, functions are objects. Thus, using this makes a variable a property of an object (your constructor function, in this case).
2) var x = 7
Let me start off saying that anytime you do not use var in front of a variable (save for the this stuff above), that variable will become a member of the global context object (window, for most user-agents).
Thought leaders in JavaScript and programming see global variables as a sin, or code smell. Avoid global variables as much as possible.
The issue with the first method (this) is that prior to ECMAScript 5, there was no good way to enforce privacy on object properties (as you might find in the classical C++ based languages like Java, PHP, etc). ECMAScript 5 and above allow you to assign attributes to properties for things like writability, enumerability, etc...
However, as it pertains to var, well, var always makes its variables private to the function object. You cannot access a var variable from external, client code like this
dog.age = 5 //Trying to assign the number five to a var variable.

You can make a function that has access (known as an accessor), though. In effect, when you see var, think private to this object's scope. That's the gist of it. Closure (from enclosure) is an important subject in JavaScript. When you get into using var, inevitably you start to learn about closure.
3) No key word.
Finally, using naked variables attaches all of them to the global object (window, for most user-agents). This tends to lead to confusion and debugging issues. You may inadvertently stage a collision or conflict where a value is being changed across many instances of your constructor function. It's just not the way to go.
In summary, a fantastic book on the subject of JavaScript variables is The Principles of Object Oriented JavaScript. Mr. Zakas explains things much better than Crockford and Flannagan. I highly recommend it. Know your goal. Know your problem. Avoid global variables. Learn about JavaScript's object mode and scope. I recommend JavaScript: The Definitive Guide when it comes to learning about scope and context in JavaScript.


text:
Q: Regex Problem in PHP I'm attempting to utilize the following Regex pattern:
$regex = '/Name: [a-zA-Z ]*] [0-9]/';

When testing it in Rubular, it works fine, but when using PHP the expression never returns true, even when it should. Incidentally, if I remove the "[0-9]" part, it works fine. Is there some difference in PHP's regex syntax that I'm overlooking?
Edit:
I'm looking for the characters "Name:" then a name containing any number of letters or spaces, then a "]", then a space, then a single number. So
"Name: Chris] 5" would return true and
"Name: Chris] [lorem ipsum]" should return false.
I also tried escaping the second bracket "\[" but this did not fix the problem.

A: It's not clear without examples what your use case, but it seems like you want something like this?
$regex = '/Name\:\ ([\w]+)\ ([\w]+)/';

Update: try this:
$regex = '/Name\:\ [\w\s]+?\]\ [\d]{1}/';

For me this matches
Name: Foo Bar] 2

..but not these:
Name: Foo Bar] foo
Name: Foo Baz 5

I'm also using short-hand expressions for character classes:

*

*[\w] is short for [a-zA-Z0-9] ( eg all alphanumeric characters )

*[\s] matches any whitespace

*[\d] matches any number

For safety I'm also using the '?' to match in a non-greedy way, to make sure thw [\w\s]+ match doesn't consume too much of the string.

A: i think this might be because of the space in the regex also u want to escape the second ]. try
$regex = '/Name:\s[a-zA-Z ]*\]\s[0-9]/';

Or use a modifier
$regex = '/Name: [a-zA-Z ]*\] [0-9]/x';

more on modifiers here
PHP: Possible modifiers in regex patterns - Manual

A: Your regex works nicely for me with the two examples you gave.
$arr = array('Name: Chris] 5', 'Name: Chris] [lorem ipsum]');
foreach ($arr as $str) {
    if (preg_match('/Name: [a-zA-Z ]*] [0-9]/', $str)) {
        echo "$str : OK\n";
    } else {
        echo "$str : KO\n";
    }
}

Output:
Name: Chris] 5 : OK
Name: Chris] [lorem ipsum] : KO

May be there are more than one space between ] and the digit, so your regex should be:
[a-zA-Z ]*]\s+[0-9]/

A: I ended up resolving the issue by attempting different regexes that did basically the same thing. This is what ended up working:
$regex = '/Name: [\w ]*][^[]{2}/';

Evidently the brackets weren't the problem, but there was something in my original code that wasn't working properly. Thank you everyone for all the help.


text:
Q: Google APIs Node.js Client with express and webpack I'm learning how to use express. My final goal is to build a dashboard with react/d3 and some data from Google Analytics. Right now I have a local project including react-webpack-babel. I want to use google-api-nodejs-client to call Google Analytics. I'm trying to follow this tutorial : http://www.2ality.com/2015/10/google-analytics-api.html but I can't run my project. Got a bunch of error in my terminal, here is the main one :
[1] /Users/myname/Desktop/reactdashboard/node_modules/babel/lib/babel/transformation/file.js:91
[1]         throw new ReferenceError("Unknown option: " + key);
[1]         ^
[1]
[1] ReferenceError: Unknown option: presets
[1]     at File.normalizeOptions (/Users/myname/Desktop/reactdashboard/node_modules/babel/lib/babel/transformation/file.js:91:15)
[1]     at new File (/Users/myname/Desktop/reactdashboard/node_modules/babel/lib/babel/transformation/file.js:70:22)
[1]     at transform (/Users/myname/Desktop/reactdashboard/node_modules/babel/lib/babel/transformation/index.js:18:14)
[1]     at Object.transformFileSync (/Users/myname/Desktop/reactdashboard/node_modules/babel/lib/babel/api/node.js:74:10)
[1]     at compile (/Users/myname/Desktop/reactdashboard/node_modules/babel/lib/babel/api/register/node.js:73:20)
[1]     at normalLoader (/Users/myname/Desktop/reactdashboard/node_modules/babel/lib/babel/api/register/node.js:119:14)
[1]     at Object.require.extensions.(anonymous function) [as .js] (/Users/myname/Desktop/reactdashboard/node_modules/babel/lib/babel/api/register/node.js:132:7)
[1]     at Module.load (module.js:456:32)
[1]     at tryModuleLoad (module.js:415:12)
[1]     at Function.Module._load (module.js:407:3)

so here is my ga.js file :
#!/usr/bin/env babel-node
import google from 'googleapis';
var fs = require('fs');
import key from '../client_id.json';

const VIEW_ID = 'ga:80220323';

    let jwtClient = new google.auth.JWT(
      key.'mail@domain.com', null, key.'myKey',
      ['https://www.googleapis.com/auth/analytics.readonly'], null);
    jwtClient.authorize(function (err, tokens) {
      if (err) {
        console.log(err);
        return;
      }
      let analytics = google.analytics('v3');
      queryData(analytics);
    });

   function queryData(analytics) {
      analytics.data.ga.get({
        'auth': jwtClient,
        'ids': VIEW_ID,
        'metrics': 'ga:uniquePageviews',
        'dimensions': 'ga:pagePath',
        'start-date': '30daysAgo',
        'end-date': 'yesterday',
        'sort': '-ga:uniquePageviews',
        'max-results': 10,
      }, function (err, response) {
        if (err) {
          console.log(err);
              return;
            }
            console.log(JSON.stringify(response, null, 4));
          });
        }

module.exports = {
  ???
};

Here is my server.babel.js file :
import express from 'express';

const app = express();

app.use('/', express.static('public'));
app.use('/', express.static('src'));

var ga = require('./src/routes/ga');

app.listen(process.env.PORT || 3000);

//templating engine
app.set('views', './src/views');
app.set('view engine', 'ejs');

app.use('/gadata', ga.queryData());

Please if my questions isn't clear enough, help me to improve so I can find my way.
edit#1 :
here is my babelrc :
{
  "presets": [
    "es2015",
    "stage-0",
    "react"
  ],
  "plugins": [
    "transform-runtime",
    "transform-class-properties"
  ]
}

edit #2:
and my webpack.config :
module.exports = {
  entry: './public/client.js',
  output: {
    path: './public',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        query: {
          plugins: ['transform-decorators-legacy']
        }
      }
    ]
  },
  resolve: {
    extensions: ['', '.js', '.json']
  },
node: {
  fs: "empty",
  net: "empty",
  tls: "empty",
}
};


text:
Q: Using d3 4.0 with TypeScript throws "Cannot read property 'format' of undefined" I have the following code on a 'Counter.ts' (TypeScript) file:
export const reducer: Reducer<CounterState> = (state, action) => {
    console.log(someD3Name.ascending);   // command 1
    console.log(someD3Name.time.format); // command 2
    return state || { count: 0 };
};

At run time, only "command 1" will succeed. "command 2" will fail with the following message:
Cannot read property 'format' of undefined

I understand that now d3 4.0 has a flat namespace (from https://github.com/d3/d3/blob/master/CHANGES.md):
every symbol in D3 4.0 now shares a flat namespace rather than the nested one of D3 3.x. For example, d3.scale.linear is now d3.scaleLinear

At run time, indeed 'timeFormat' exists, but if I use that on the TypeScript file, then the Typescript compiler (transpiler?) will throw the following error
ERROR in ./ClientApp/store/Counter.ts
(37,27): error TS2339: Property 'timeFormat' does not exist on type 'typeof d3'.

What am I missing? If the problem is the Typescript definition file is out-of-date, as d3 4.0 was just released, is there another way of using d3 4.0 with TypeScript?
My environment
I'm trying to add d3 to the website generated with this command
yo aspnetcore-spa

This command generates a ASP.NET Core with React+Redux SPA with default Webpack+Babel. I am adding d3 like this
npm install d3 --save
tsd install d3 --save

Then, on any page (in my case Counter.ts):
import * as someD3Name from 'd3';


text:
Q: How can a HashSet record a null entry without a NullPointerException when computing the hash code I know all those weird philosophical reasons why null instances are allowed in every collection
But unlike in lists,position of sets' (even maps, too) elements depend upon the hashcode of element being added thereby on the element itself (barring exceptions like LinkedHashSet where insertion order is preserved)
So while computing hashcode of element being added to collection and if that element is presumed to be null shouldn't it throw NPE ?

null.hashCode()

Does it have some type of null-checking
First i thought
System.out.println(setReference) too should generate NPE if there is a null, but after quite a bit research i found that actual method that is called is static valueOf(Object obj) rather than toString() method
which is null safe from what is stated in java docs,
i have finally been to clear my head about it ...
but this still haunts me, i know i am being little obsessive about tiny details but i have to 'cause currently i am preparing for OCAJP 8 so i risked  downrating to get credible explanation since i didn't find anything in java docs pertaining to this...
so what operations in sets are null-safe, a comprehensive answer is appreciated.

A: null are handled explicitly. If you look at HashSet's implementation, it's basically a HashMap where all the keys point to the same (dummy) value. If you drill down to the way HashMap calculates the hash code for a key, you'd find this method (code taken from OpenJDK 1.8.0_92-b14, although I sincerely doubt it will differ in any other JDK):
static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

So, to make a long story short, HashSets and HashMaps explicitly handle nulls and treat their hash as 0.


text:
Q: Display non-linear data structure like tree in Android View I want to integrate a tree view in my application with data structure like below image.
My application data is dynamic which comes from SQLite database.

Any idea how can I achieve this?


text:
Q: Java program that's smaller then the the paragraph it prints out (help) First off, yes this is(was) for school. It was assigned as extra credit and was due Wednesday. However no one was able to solve it and the teacher refused to give us the solution.
The task was to write a java program that would output a paragraph and have the java code smaller then the paragraph itself. (smaller meaning in characters no size) there were a few conditions however.
1. no input allowed
2. no importing of files
3. no downloading from the internet or network
The paragraph that we had to output was this, "I pledge that every program with my name on it shall be written by me (and my co-authors, if any) and that i fully uderstad the program. Every program I submit shall be entirely my own work unless otherwise attributed. I understand that academic dishonesty not only includes copying other people's work, but also abetting or facilitating copying. Code that is similar to any other submission past or present will get no credit whatever the explanation. I understand that the consequence of academic dishonesty is a grade of 'F' for the class. I pledge to devote my efforts to learning Java by writing my own programs. I shall strive to be attentive to detail and write programs understandable by myself and other programmers."
"The total number of characters in the program should be fewer that the total number of characters in the pledge (655 printable, 793 total)."
I have a few ideas but none that I think will work, any ideas?


text:
Q: Is it possible to have more than one Principal in ASP.NET? I was recently given a task to create separate login for users, that belong to certain role. Login was already implemented for main users and this was done with using Principal that was assigned to Thread.CurrentPrincipal and is later checked for value every time a page is loaded. I modified my code to use same mechanism of authentication so in my custom login I create custom Principal and assign it to Thread.CurrentPrincipal. Now the problem with that is that with custom login I override my normal login and vice versa. Is it possible to assign my principle somewhere else than Thread.CurrentPrincipal to allow for both login variants to work at the same time? If this is not possible I would like to learn about alternatives :)

A: The answer from DVK is valid, but I have had complications in the past when using custom IPrincipals. An alternative approach is to use a single principal, represented by a ClaimsPrincipal and make use of the fact that it can store multiple identities. You can then use the default implementations of IsInRole for example.
https://msdn.microsoft.com/en-us/library/system.security.claims.claimsprincipal(v=vs.110).aspx

A: This is very doable, and not terribly difficult.  The best way I've found to do this is to implement a custom IPrincipal that has a property that also contains an IPrincipal.  Then you can store both in the thread, and implement the IsInRole method in a manner that allows checking both principal objects for authorization purposes.  Some pseudo-code...
public class MyPrincipal : IPrincipal
{
    public IPrincipal FormsPrincipal { get; private set; }

    public MyPrincipal(IPrincipal formsPrincipal)
    {
        FormsPrincipal = formsPrincipal;
    }

    public bool IsInRole(string role)
    {
        if (someCondition)
        {
            // check roles for this
        }
        else
        {
            return FormsPrincipal.IsInRole(role); // check role against the other principal
        }
    }
}

Then on PostAuthenticateRequest, use the current principal to create your new, custom principal, and assign your custom principal as the HttpContext.Current principal.
Good resource with lots of detail:  ASP.NET MVC - Set custom IIdentity or IPrincipal


text:
Q: How to add a fourth equation in the Microsoft Word Equation Editor? I'm trying to add 4 equations but the Microsoft Word Equation Editor only goes to 3:

How can I add four equations?

A: In the Office 2010 version of the equation editor, after inserting a brace, with it selected, I can just right-click on one of its places and chose "Insert Equation Before" or "Insert Equation After".
If you find it a bit tricky to hit the little boxes with the I-beam mouse cursor, you may be able to do it with the keyboard: move the text cursor around with the arrow keys and then use the menu key (generally between the right Alt and Ctrl on 'Windows keyboards') to get the context menu for the item under the cursor.

A: Just type the three equations and then, while still in the box for the last equation, press the Enter key. A new dotted-border box appears below. Works both on Word 2007 and on Word 2010.


text:
Q: Invariant Violation react native I have this error in my application:

Invariant Violation: Invariant Violation: Element type is invalid:
  expected a string (for built-in components) or a class/function (for
  composite components) but got: undefined. You likely forgot to export
  your component from the file it's defined in, or you might have mixed
  up default and named imports.

I don't know why this happens to me, becouse I don't see any problems. Look at my screen code:
import React, { Component } from 'react';
import { Text, View,StyleSheet,TouchableOpacity,TextInput,FlatList,ListItem } from 'react-native';
import { Alert,Input } from 'native-base';
import {BoxShadow} from 'react-native-shadow';
import Dimensions from 'Dimensions';
import Icon from 'native-base';

const DEVICE_WIDTH = Dimensions.get('window').width;

export default class ticketDiaryHours1 extends Component {

    constructor(props) {
        super(props);

        this.state = {
            text: '',
            textOpombe: '',
            data: [
                {key: 'Devin Dank'},
                {key: 'Jackson Will'},
                {key: 'James Jones'},
                {key: 'Joel Noah'},
                {key: 'John Degenkolb'},
                {key: 'Jillian Calmejain'},
                {key: 'Jimmy Butler'},
                {key: 'Julie Hell'},
               ],
            showList: false,

        }
    }

    onShowStudent() {
        if(this.state.showList) {
            this.setState({
                showList: false,
            });
        } else {
            this.setState({
                showList: true,
            });
        }

    }
    render() {
        const shadowOpt = {
            height:40,
            width: DEVICE_WIDTH-40,
            color:"#000",
            border:2,
            radius:8,
            opacity:0.2,
            x:0,
            y:3,
            style:{marginVertical:3}
        };

        const {
          student,
          startTime,
          endTime,
          headingText,
          roomText,
          apsent,
          finished
        } = this.props;

        return (
            <View style={styles.main}>
                <Text>{startTime} - {endTime}</Text>
                <Text style={styles.headingText}>{headingText} - {student}</Text>
                <Text style={styles.hourContent}>VSEBINA URE </Text>

                <BoxShadow setting={shadowOpt}>
                        <TextInput
                            style={styles.textInputStyle}
                            placeholder='Vnesite vsebino ure'
                             placeholderTextColor="rgba(0,0,0,0.5)"
                            onChangeText={(text) => this.setState({text})}
                            value={this.state.text}
                            underlineColorAndroid='transparent'
                        />
                </BoxShadow>

                <Text style={styles.hourContent}>OPOMBE </Text>

                <BoxShadow setting={shadowOpt}>
                        <TextInput
                            style={styles.textInputStyle}
                            placeholder='Vnesite opombe'
                            placeholderTextColor="rgba(0,0,0,0.5)"
                            onChangeText={(textOpombe) => this.setState({textOpombe})}
                            value={this.state.textOpombe}
                            underlineColorAndroid='transparent'
                        />
                </BoxShadow>

                <View style={styles.markedRow}>

                    <View style={{flexDirection: 'column', justifyContent: 'center', justifyContent: 'flex-start' }}>
                        <Text style={styles.textIcon}>OPRAVLJENO</Text>

                        <TouchableOpacity
                            style={ [styles.touchable1, styles.iconStyle] }
                            onPress={this.onShowStudent.bind(this)}>
                            <Icon name='checkmark' style={{color: '#fff', fontSize: 20, alignSelf: 'center' }}/>
                        </TouchableOpacity>

                    </View>

                    <View style={{flexDirection: 'column', justifyContent: 'center', position: 'absolute', right: 0, top: 15 }}>
                        <Text style={styles.textIcon}>NEOPRAVLJENO</Text>
                        <TouchableOpacity
                            style={ [styles.touchable2, styles.iconStyle] }
                            onPress={this.onShowStudent.bind(this)}>
                            <Icon name='close'
                                style={{color: '#fff', fontSize: 20,alignSelf: 'center'}} />
                        </TouchableOpacity>

                    </View>

                </View>

            </View>

        )
  }
}

const styles = StyleSheet.create({
    main: {
        paddingLeft: 20,
        paddingRight: 20,
        flexDirection: 'column',
        paddingTop: 15
    },
    headingText: {
        fontWeight:  '400',
        color: '#000000',
        fontSize: 20,

    },
    hourContent: {
        fontWeight:  '400',
        color: '#000000',
        fontSize: 20,
        paddingBottom: 15,
        paddingTop: 15,
    },
    textInputStyle: {
        backgroundColor: 'white',
        paddingLeft: 10,
        height: 40,
        borderRadius: 8,
        width: DEVICE_WIDTH-40,
    },
    markedRow: {
        flexDirection: 'row',
        paddingTop: 15,
    },
    touchable1: {
        backgroundColor: '#48BFD3',
        justifyContent: 'center',
    },
    touchable2: {
        backgroundColor: '#EE9CA0',
        justifyContent: 'center',
    },
    iconStyle: {
        borderRadius: 8,
        width: 50,
        height: 40,
        alignSelf: 'center',
    },
    textIcon: {
        paddingBottom: 10,
        fontWeight:  '400',
        color: '#000000',
        fontSize: 20,
    },
    listItemStyle: {
        flexDirection: 'row',
    }

});

A: That is an issue with your import. try import {Icon} from 'native-base';. This is a member import (named import). Member imports are exported with export... and not export default ...


text:
Q: load selected content from an acf select field On wordpress and ACF,I am searching for a way to load different
 (one OR the other, not both) based on
the choosen content from the ACF « select » field (named « type_of_page »)
when the page load.
I have two type of selector « actual » OR « archive »
that have to load two
 « #now » OR « #before »
    <?php

if(get_field('type_of_page') == "archive")
{
    //...
}

?>

NOW

BEFORE

How sould I release that, without loading both ?

A: You've pretty much got it:
<?php if( get_field( 'key' ) == 'value' ) : ?>

<?php else : ?>

<?php endif; ?>

If you are worried that content-b will load but be hidden in cases where content-a is desired, check the source code after viewing the page in a browser. You will see that content-b cannot be loaded if content-a is loaded (and vice-versa) using this logic.


text:
Q: "with", "where" or "and"? A question about good writing style. If I am writing down this function $$ f: D^2\to \mathbb R  $$
and want to communicate that $D\subseteq \mathbb R$, should I write $$ f: D^2\to \mathbb R \quad \mathrm {with} \quad D\subseteq \mathbb R$$ or $$ f: D^2\to \mathbb R \quad \mathrm {where} \quad D\subseteq \mathbb R$$ or $$ f: D^2\to \mathbb R \quad \mathrm {and} \quad D\subseteq \mathbb R$$?


text:
Q: Displaying the username of current user (Swift) Is it possible to display the username of the current user in a macOS app?

A: You can use the NSUserName() function:
var username = NSUserName()!

A: Swift 4.2
let userName = NSUserName()
let fullUserName = NSFullUserName()

A: The following did work for me. It was copied from this post.
CKContainer.default().requestApplicationPermission(.userDiscoverability) { (status, error) in
    CKContainer.default().fetchUserRecordID { (record, error) in
        CKContainer.default().discoverUserIdentity(withUserRecordID: record!, completionHandler: { (userID, error) in
            let fullName = (userID?.nameComponents?.givenName)! + " " + (userID?.nameComponents?.familyName)!
        })
    }
}


text:
Q: Oracle record history using as of timestamp within a range I recently learnt that oracle has a feature which was pretty useful to me - as the designer/implementator didn't care much about data history - I can query the historical state of a record if it's available yet in the oracle cache, like this:
select *
  from ( select *
           from sometable where some_condition )
as of timestamp sysdate-1

But now I need to check the historical data within a range. Is it possible anyhow, using the cache?

A: Yes, like this:
SQL> select sal from emp where empno=7369;

       SAL
----------
      5800

SQL> update emp set sal = sal+100 where empno=7369;

1 row updated.

SQL> commit;

Commit complete.

SQL> update emp set sal = sal-100 where empno=7369;

1 row updated.

SQL> commit;

Commit complete.

SQL> select empno, sal, versions_starttime,versions_xid
  2  from emp
  3  versions between timestamp sysdate-1 and sysdate
  4  where empno=7369;

     EMPNO        SAL VERSIONS_STARTTIME                                                          VERSIONS_XID
---------- ---------- --------------------------------------------------------------------------- --
      7369       5900 11-DEC-08 16.05.32                                                          0014001300002A74
      7369       5800 11-DEC-08 16.03.32                                                          000D002200012EB1
      7369       5800

Note that how far back you can go is limited by the UNDO_RETENTION parameter, and will typically be hours rather than days.

A: One note to be aware of is that this sort of flashback query relies on UNDO information that is written to the UNDO tablespace.  And that information is not retained forever-- most production systems under reasonable load are not going to have 24 hours of UNDO information available.
Depending on the Oracle version, you may need to set the UNDO_RETENTION parameter to a value longer than the time period you are trying to flashback through.

A: SELECT *
  FROM sometable
  VERSIONS BETWEEN TIMESTAMP systimestamp - 1 AND systimestamp

will give you all versions of all rows in the last day.
There's lots more you can do with this.  Check out the documentation (you may want to find the docs for your version).


text:
Q: Git commit unknown Author I am commiting through the command line.
When I commit I have to enter my username, but when I check through the browser the Author appears as unknown ..  WTF !

A: I believe your default global username is not set, which will most certainly cause this error.
Please try the following command, then make a commit and push..
git config --global user.name myname

If this works, from here on out you will be able to commit and it will show with your username. Let me know what happens so I can assist you further if you need.


text:
Q: AI-CNN Python loading my own data to Python I am about writing a code for Image Classification. With ImageDataGenerator  i wrote my code but it was working very slow ( 1s = 1 step ) . I want to load my own data as a np array but i got some errors.
The output should be:
(15500 , 45 ,45,3)
(4000, 1)
(15500 , 45 ,45,3)
(4000,1)
But i got :
(15500 , 45 ,45,3)
(4000, )
(15500 , 45 ,45,3)
(4000,)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import keras
import glob
import cv2
import os

TEST_DATADIR = "C:/Users/TCSEAKIN/Desktop/Py/AI-hack/AI/Test"
TRAIN_DATADIR = "C:/Users/TCSEAKIN/Desktop/Py/AI-hack/AI/Training"
CATAGORIES = ["Armut", "Portakal", "Cilek", "Muz", "Portakal", "Elma_Kirmizi", "Elma_Yesil", "Mandalina"]

fruit_images = []
labels = []
for category in CATAGORIES :
    path = os.path.join(TRAIN_DATADIR, category)
    for img in os.listdir(path):
        image = cv2.imread(os.path.join(path,img), cv2.IMREAD_COLOR)
        image = cv2.resize(image, (45, 45))
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        fruit_images.append(image)
        labels.append(path)

fruit_images = np.array(fruit_images)
labels = np.array(labels)

validation_fruit_images = []
validation_labels = []
for category in CATAGORIES:
   path = os.path.join(TEST_DATADIR, category)
   for img in os.listdir(path):
        image = cv2.imread(os.path.join(path,img), cv2.IMREAD_COLOR)
        image = cv2.resize(image, (45, 45))
        image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

        validation_fruit_images.append(image)
        validation_labels.append(path)

validation_fruit_images = np.array(validation_fruit_images)
validation_labels = np.array(validation_labels)

X_train, X_test = fruit_images, validation_fruit_images
Y_train, Y_test = labels, validation_labels

#Normalize color values to between 0 and 1
X_train = X_train/255
X_test = X_test/255

print(X_train.shape)
print(Y_train.shape)
print(X_test.shape)
print(Y_test.shape)

A: use the reshape function:
labels = labels.reshape(-1, 1)
labels.shape


text:
Q: How to use zend framework to retrieve bounce mail message? I need to know whether my mail is fail to deliver:
I have set the imap setting for my mail box.
when i use zend to retrieve all mail message, how can i detect the mail is bounce message?
if i use "failure" title to filter, other mail that is not related will also be select as bounce mail?
Also, the bounce mail box must be the sender mail box , it is set by the mail server , no matter i add header in the message, that mean i can not change to another mail box to receive bounce mail?
Thank you.


text:
Q: How to use FaceBook API? i am using Facebook API tutorial.It's working perfectly but whenever i send the wall to Facebook its showing "Connect to Punjabi Adda" as an link in my Facebook account.How can change it? If someone have idea please tell me......

A: Raman,
In the postToWall method
change the string in dialog.attachment.
I hope it helps


text:
Q: Group and count PDO output I have a query:
$myData = $db->query("
         SELECT *
         FROM t1
         WHERE event = '$eid'
         ", PDO::FETCH_OBJ);

that returns results in an a form of an array:
Array (
[0] => stdClass Object
    (
        [id] => 1
        [even] => 1
        [response] => NO
        [adult] =>
        [child] =>
    )

[1] => stdClass Object
    (
        [id] => 2
        [event] => 1
        [response] => YES
        [adult] => 1
        [child] => 3
    )
)

I need to get the following counts:
Total for each response: YES and NO
If YES:
  Total Adults
  Total Children
Can I get it from a query or do I need to manipulate the array to get the counts?

A: You could iterate over the result array from your current query or you could get the counts from another query.
-- display count of YES responses and total adults and children
SELECT COUNT(*), SUM(adult), SUM(child)
    FROM t1
    WHERE event = '$eid'
    AND response = 'YES';

-- display count of NO responses
SELECT COUNT(*)
    FROM t1
    WHERE event = '$eid'
    AND response = 'NO';

Probably best to use them in prepared statements.
https://www.php.net/manual/en/pdo.prepare.php
https://www.php.net/manual/en/pdo.prepared-statements.php

A: You can use conditional counting and sum. For this CASE statement is very good.
SELECT
    COUNT(CASE response WHEN 'YES' THEN 1 ELSE NULL END) as YesResponses,
    COUNT(CASE response WHEN 'NO' THEN 1 ELSE NULL END) as NoResponses,
    SUM(CASE response WHEN 'YES' THEN adult ELSE 0 END) as Adults,
    SUM(CASE response WHEN 'YES' THEN child ELSE 0 END) as Children
FROM t1

However, please note your code is vulnerable to SQL injection. You need to use parameterized prepared statements.


text:
Q: Invoking a file from AWS lambda handler.js? I have node.js file(i.e.abc.js) which will give the output when i run in my node.js editor. I want to run the same file in AWS Lambda.For that, I created a lambda and moved abc.js to there. To run, it seems i need to implement my abc.js file in handler.js(i.e.in lambda way means callback etc).
Is there any way to trigger abc.js from handler.js rather than implementing again the same thing in handler.js?
Checked regarding the above usecase but didn't find much on google.
Updated
My abc.js file
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({
    region: "ap-south-1"
   });

// Create S3 service object
s3 = new AWS.S3();
var params= {};
 s3.listBuckets(params, bucketList);
function bucketList(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else
  {
        console.log(data)
  }
}

My handler.js in lambda and modifying it based on my interpretation of your answer.
exports.handler = async (event) => {
    const abc = require('./abc.js');
    // TODO implement
abc.bucketList();
};

This is the error i am getting
Response:
{
  "errorMessage": "abc.bucketList is not a function",
  "errorType": "TypeError",
  "stackTrace": [
    "exports.handler (/var/task/index.js:5:5)"
  ]
}

Any help is appreciated.

A: Require your file
const abc = require('./abc.js');

And in the handler function call your code
abc.yourExportedMethod();

A: You have some issues inside of your abc.js file.
Try this snippet:
const abc = async function()
{
    try
    {
        const AWS = require('aws-sdk');
        let s3 = new AWS.S3({region: "ap-south-1", apiVersion: '2006-03-01' });
        let params= {};
        const s3Response = await s3.listBuckets(params).promise();

        console.log(s3Response); // your list of buckets

    }
    catch (ex)
    {
        console.error(ex);
    }
}

export default abc;

A: Add the following line at the bottom of your abc.js
exports.bucketList = bucketList

and the rest will work as you expect it to.


text:
Q: How to get video duration and how to get only music videos via YouTube Api V3 how to use part : snippet and contentDetails ?? i want to get duration,only music videos,title and watched count..
 please help me.

    function keyWordsearch() {
        gapi.client.setApiKey("MY_API_KEY");
        gapi.client.load('youtube', 'v3', function () {
            var q = $('#query').val();
            $("#result").empty();
            var request = gapi.client.youtube.search.list({
                q: q,
                part: 'snippet',

                maxResults: 5,

            });

            request.execute(function (response) {
                for (var i = 0; i < response.items.length; i++) {
                    var id = response.items[i].id.videoId;

                    var name = response.items[i].snippet.title;
                    $('#result').html($('#result').html() + "
" + name + "
");
                }
                $('#result').html($('#result').html() + '
');
            });
        });
    }

</script>

A: i write console.log(response.items[i].snippet) then result is like this


text:
Q: Generic type-bound procedures with procedure arguments I am trying to write a generic type-bound procedure that takes different callback functions as parameters. When compiling following code (with ifort 12.1.3) I get the warning below:
module test

type :: a_type
  contains
  procedure :: t_s => at_s
  procedure :: t_d => at_d
  generic :: t => t_s,t_d
end type a_type

abstract interface
  integer function cb_s(arg)
  real(4) :: arg
  end function cb_s

  integer function cb_d(arg)
  real(8) :: arg
  end function cb_d
end interface

contains

subroutine at_s(this,cb)
  class(a_type) :: this
  procedure(cb_s) :: cb
end subroutine

subroutine at_d(this,cb)
  class(a_type) :: this
  procedure(cb_d) :: cb
end subroutine

end module test

The warning:
compileme.f(27): warning #8449: The type/rank/keyword signature for this specific
procedure matches another specific procedure that shares the same generic
binding name.   [AT_D]

It seems like the compiler is not differentiating between different function interfaces when used as procedure arguments...
My question is: Why aren't those types checked and what is the correct, clean way to write generic type-bound procedures with procedures or procedure pointers as arguments?
Possible solution
As Vladimir F pointed out, only the callback function's return arguments are type checked. In my case it is OK to then just slightly change the functions' interfaces:
abstract interface
  real(4) function cb_s(arg)
  real(4) :: arg
  end function cb_s

  real(8) function cb_d(arg)
  real(8) :: arg
  end function cb_d
end interface

A: The compiler is right, because Fortran 2008's 12.4.3.4.5 Restrictions on generic declarations has

Two dummy arguments are distinguishable if
  - one is a procedure and the other is a data object,
  - they are both data objects or known to be functions, and neither is TKR compatible with the other,
  - one has the ALLOCATABLE attribute and the other has the POINTER attribute, or
  - one is a function with nonzero rank and the other is not known to be a function.

It means that both your functions are integer functions so they are not distinguishable.


text:
Q: R How to use curly curly with filter or filter_? I was answering this question where commenters suggested !!ensym, and I thought this might be a good place to use curly curly {{ but I couldn't get it to work (maybe not applicable?).
How might I do this filter operation, without using filter_, eval/parse, or quote-unquote? Would ~ help?
My solution (1g) uses filter_ and conditions built up with paste.
1a works (but could it use {{ }} somehow?)
And what if we wanted to filter by multiple variables? This is where you see 2g working below (while 2a does not work anymore).
library(tidyverse)
set.seed(1234)
A <- matrix(rnorm(30),nrow = 10, ncol = 3) %>% as_tibble() %>% set_names(paste("var", seq(1:3), sep = ""))
varnames_1 <- c("var2")

(expected_result_1 <- filter(A, var2 > 0))
#> # A tibble: 3 x 3
#>     var1   var2   var3
#>    <dbl>  <dbl>  <dbl>
#> 1 -2.35  0.0645  0.460
#> 2  0.429 0.959  -0.694
#> 3 -0.890 2.42   -0.936

(answer_1a <- filter(A,!!ensym(varnames_1) > 0)) # works (thanks joran and aosmith)
#> # A tibble: 3 x 3
#>     var1   var2   var3
#>    <dbl>  <dbl>  <dbl>
#> 1 -2.35  0.0645  0.460
#> 2  0.429 0.959  -0.694
#> 3 -0.890 2.42   -0.936

(answer_1b <- filter_(A, varnames_1 > 0)) # filter_ not doing what I thought it might
#> Warning: filter_() is deprecated.
#> Please use filter() instead
#>
#> The 'programming' vignette or the tidyeval book can help you
#> to program with filter() : https://tidyeval.tidyverse.org
#> This warning is displayed once per session.
#> # A tibble: 10 x 3
#>      var1    var2    var3
#>     <dbl>   <dbl>   <dbl>
#>  1 -1.21  -0.477   0.134
#>  2  0.277 -0.998  -0.491
#>  3  1.08  -0.776  -0.441
#>  4 -2.35   0.0645  0.460
#>  5  0.429  0.959  -0.694
#>  6  0.506 -0.110  -1.45
#>  7 -0.575 -0.511   0.575
#>  8 -0.547 -0.911  -1.02
#>  9 -0.564 -0.837  -0.0151
#> 10 -0.890  2.42   -0.936

(answer_1c <- filter(A, {{varnames_1}} > 0)) # curly curly not doing what I thought it might
#> # A tibble: 10 x 3
#>      var1    var2    var3
#>     <dbl>   <dbl>   <dbl>
#>  1 -1.21  -0.477   0.134
#>  2  0.277 -0.998  -0.491
#>  3  1.08  -0.776  -0.441
#>  4 -2.35   0.0645  0.460
#>  5  0.429  0.959  -0.694
#>  6  0.506 -0.110  -1.45
#>  7 -0.575 -0.511   0.575
#>  8 -0.547 -0.911  -1.02
#>  9 -0.564 -0.837  -0.0151
#> 10 -0.890  2.42   -0.936
(answer_1d <- filter(A, {{varnames_1 > 0}})) # curly curly not doing what I thought it might
#> `arg` must be a symbol

conditions_1 <- paste(varnames_1, "> 0")
(answer_1e <- filter(A, conditions_1)) # does not work
#> Error: Argument 2 filter condition does not evaluate to a logical vector
(answer_1f <- filter(A, {{conditions_1}})) # curly curly not doing what I thought it might
#> Error: Argument 2 filter condition does not evaluate to a logical vector
(answer_1g <- filter_(A, conditions_1)) # works
#> # A tibble: 3 x 3
#>     var1   var2   var3
#>    <dbl>  <dbl>  <dbl>
#> 1 -2.35  0.0645  0.460
#> 2  0.429 0.959  -0.694
#> 3 -0.890 2.42   -0.936

# what if we wanted to filter multiple variables?

varnames_2 <- c("var2", "var3")
(expected_result_2 <- filter(A, var2 > 0 & var3 > 0))
#> # A tibble: 1 x 3
#>    var1   var2  var3
#>   <dbl>  <dbl> <dbl>
#> 1 -2.35 0.0645 0.460

(answer_2a <- filter(A,!!ensym(varnames_2) > 0)) # does not work
#> Only strings can be converted to symbols

conditions_2 <- paste(paste(varnames_2, "> 0"), collapse = " & ")
(answer_2f <- filter(A, {{conditions_2}})) # curly curly not doing what I thought it might
#> Error: Argument 2 filter condition does not evaluate to a logical vector
(answer_2g <- filter_(A, conditions_2)) # works
#> # A tibble: 1 x 3
#>    var1   var2  var3
#>   <dbl>  <dbl> <dbl>
#> 1 -2.35 0.0645 0.460

Created on 2019-08-28 by the reprex package (v0.3.0)

A: As Lionel points out, curly-curly works inside functions. To use it with filter, you thus have to wrap the call inside a function.
f <- function(.df, v) {
  filter(.df, {{ v }} > 0)
}

# Curly-curly provides automatic NSE support
f( A, var2 )
# # A tibble: 3 x 3
#     var1   var2   var3
#    <dbl>  <dbl>  <dbl>
# 1 -2.35  0.0645  0.460
# 2  0.429 0.959  -0.694
# 3 -0.890 2.42   -0.936

# Strings have to be first converted to symbols
f( A, !!sym("var3") )
# # A tibble: 3 x 3
#     var1    var2  var3
#    <dbl>   <dbl> <dbl>
# 1 -1.21  -0.477  0.134
# 2 -2.35   0.0645 0.460
# 3 -0.575 -0.511  0.575

Curly-curly is meant to reference a single argument. You can extend it to work with multiple variables through sequential application with the help of purrr::reduce. (Don't forget to convert your strings into actual variable names first!):
syms(varnames_2) %>% reduce(f, .init=A)
# # A tibble: 1 x 3
#    var1   var2  var3
#   <dbl>  <dbl> <dbl>
# 1 -2.35 0.0645 0.460

A: If the paste(paste(varnames_2, "> 0"), collapse = " & ") is the main question. You have to build the filter arguments.
library(tidyverse)
library(rlang)

set.seed(1234)
A <- matrix(rnorm(30),nrow = 10, ncol = 3) %>% as_tibble() %>% set_names(paste("var", seq(1:3), sep = ""))

# with variables as arguments
filter_gt0 <- function(d, ...) {
  conds <- ensyms(...)
  conds <- map(conds, ~quo(!!.x > 0))
  d %>%
    filter(!!!conds)
}
A %>%
  filter_gt0(var2, var3)
# # A tibble: 1 x 3
# var1   var2  var3
# <dbl>  <dbl> <dbl>
#   1 -2.35 0.0645 0.460

# or with variables as input
conds <- quos(var2, var3)
filter_gt0_2 <- function(d, conds) {
  conds <- map(conds, ~quo(!!.x > 0))
  d %>%
    filter(!!!conds)
}
A %>%
  filter_gt0_2(conds)
# # A tibble: 1 x 3
# var1   var2  var3
# <dbl>  <dbl> <dbl>
#   1 -2.35 0.0645 0.460

A: {{ only works within functions, with function arguments. Same for ensym() and other operators starting with en by the way.
If you're not in a function and you have variable names as strings, you need !!sym(). The sym() part transforms the variable name to a code object (a symbol), and the !! part insert it in place.


text:
Q: Why does my YouTube code not work with all playlists? jsfiddle playlist first
Alum Songs Playlist perfectly works but unfortunately the same code is not working for another playlist Id
jsfiddle playlist second
Medical Animated Playlist does not work

var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/B2A4E1367126848D?v=2&alt=json&callback=?';
var videoURL = 'http://www.youtube.com/watch?v=';
$.getJSON(playListURL, function(data) {
  var list_data = "";
  $.each(data.feed.entry, function(i, item) {
    var feedTitle = item.title.$t;
    var feedURL = item.link[1].href;
    var fragments = feedURL.split("/");
    var videoID = fragments[fragments.length - 2];
    var vid = item.media$group.yt$videoid.$t;
    var url = videoURL + videoID;
    var vidtitle = item.title.$t;
    var vidviews = item.yt$statistics.viewCount;
    var content = item.media$group.media$description.$t;
    var thumb = "http://img.youtube.com/vi/" + videoID + "/default.jpg";
    list_data += '

' + vidtitle + '

Views:- ' + vidviews + '

Case Study

' + content + '

';

  });
  $(list_data).appendTo(".cont");
});

A: The reason is the video has no views, and as a result item.yt$statistics is undefined for some of the videos. Remove those variables, or check for undefined values before accessing viewCount.
I also noticed that the provided jsFiddle was not including jQuery, so I updated that in the jsFiddle below.
http://jsfiddle.net/cqp20zLc/1/


text:
Q: ERROR: relation "domain_event_entry" does not exist [AXON] This problem occurred while learning AXON 3.x. Using postgre 42.5.0 DB.
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into domain_event_entry (event_identifier, meta_data, payload, payload_revision, payload_type, time_stamp, aggregate_identifier, sequence_number, type, global_index) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2022-11-02 11:05:28.189  WARN 15368 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 0, SQLState: 42P01
2022-11-02 11:05:28.189 ERROR 15368 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : ERROR: relation "domain_event_entry" does not exist
  Position: 13
2022-11-02 11:05:28.191  INFO 15368 --- [nio-8080-exec-1] o.h.e.j.b.internal.AbstractBatchImpl     : HHH000010: On release of batch it still contained JDBC statements

I think the relevant tables should be created automatically. What is wrong with the configuration?

A: Given you current explanation, there's not that much to go off, @zzz.
I do have two pointers for you, though:

*

*Please move to the latest Axon Framework release. Axon Framework is currently on 4.6.2, which is about 4 years ahead from the latest minor release of Axon Framework 3.

*The main thing missing from your question, is how you're configuring your application. Surely there's something wrong, but pinpointing what it is, is rather tough without knowing what you're doing. On this note though, if you are in a Spring Boot environment, adding the axon-spring-boot-starter dependency should be sufficient.

What might be an easy stepping stone for you, @zzz, is using AxonIQ's Initializr. Through the initializr, you can construct a basic Axon Framework application, allowing you to add several dependencies you may need as well.
You can find the initializr here, by the way.


text:
Q: FosElasticaBundle: How to search using multiple keywords? this is working for me ok: $results = $finder->find('muj*');
but when I try $results = $finder->find(array('muj*', 'hom*)); I get this:

SearchPhaseExecutionException[Failed to execute phase [query], all
  shards failed; shardFailures {[qTMnzJeGTu-YVumR2xLW1Q][search]1:
  RemoteTransportException[[Starshine][inet[/192.168.1.83:9302]][search/phase/query]];
  nested: SearchParseException[search: from[-1],size[-1]: Parse
  Failure [Failed to parse source
  [{"0":"muj*","1":"hom*","query":{"match_all":{}}}]]]; nested:
  SearchParseException[search: from[-1],size[-1]: Parse Failure [No
  parser for element [0]]]; }{[LgfD_idnTtmv3JHcMPnkmw][search][0]:
  SearchParseException[[search][0]: from[-1],size[-1]: Parse Failure
  [Failed to parse source
  [{"0":"muj*","1":"hom*","query":{"match_all":{}}}]]]; nested:
  SearchParseException[[search][0]: from[-1],size[-1]: Parse Failure [No
  parser for element [0]]]; }{[vpaWi0XRT8eo7UYtgFFsag][search][3]:
  RemoteTransportException[[Clint
  Barton][inet[/192.168.1.83:9301]][search/phase/query]]; nested:
  SearchParseException[[search][3]: from[-1],size[-1]: Parse Failure
  [Failed to parse source
  [{"0":"muj*","1":"hom*","query":{"match_all":{}}}]]]; nested:
  SearchParseException[[search][3]: from[-1],size[-1]: Parse Failure [No
  parser for element [0]]]; }{[LgfD_idnTtmv3JHcMPnkmw][search][2]:
  SearchParseException[[search][2]: from[-1],size[-1]: Parse Failure
  [Failed to parse source
  [{"0":"muj*","1":"hom*","query":{"match_all":{}}}]]]; nested:
  SearchParseException[[search][2]: from[-1],size[-1]: Parse Failure [No
  parser for element [0]]]; }{[qTMnzJeGTu-YVumR2xLW1Q][search][4]:
  RemoteTransportException[[Starshine][inet[/192.168.1.83:9302]][search/phase/query]];
  nested: SearchParseException[[search][4]: from[-1],size[-1]: Parse
  Failure [Failed to parse source
  [{"0":"muj*","1":"hom*","query":{"match_all":{}}}]]]; nested:
  SearchParseException[[search][4]: from[-1],size[-1]: Parse Failure [No
  parser for element [0]]]; }]

For me it is strange since the docs say that find() admits an array as parameter.


text:
Q: If $f''(x) = 0$, then f always has a point of inflection at $x$
The question is asking if this statement is true or false.

From my understanding, when trying to find points of inflection you are simply looking for when $f''(x) = 0$ and then finding values for $x$. So with that in mind, wouldn't $x$ just always be a point of inflection?

A: A point where $f''(x)=0$ is necessary but not sufficient.  You also need to have the graph be both convex and concave near $x$, so that the second derivative actually changes sign at $x$.  For instance, the graph $f(x)=x^4$ has second derivative $f''(x)=12x^2$, but since the second derivative is never negative the graph is always convex and has no inflection point.

A: For a point $x=a$ to be a point of inflexion, $f''(a)=0$ and $f''(x)$ needs to change sign at $x=a\pm h$. So $f''(x)=(x-a),(x-a)^3, (x-a)^5$are the cases for point of inflexion at $x=a$. But $f''(x)=(x-a)^2, (x-a)^4, (x-a)^6$ are the cases where $f''(a)$ is zero but there is no point of inflexion. For the point of inflexion at $x=a$ we need ty have $$f''(a)=0 ~ and ~ f''(a+h). f''(a-h) <0.$$.


text:
Q: Implementing Interfaces and Objects When a class implements an interface, does that make objects instantiated from the class be perceived as an object of that Interface?
i.e. Upon a class implementing the Runnable interface, does that make instances created from that class to be called a Runnable object?
So, where a Runnable object reference variable is expected (say, in the parameter of a method or a constructor), why is it legal that we can provide an instance of the class as an argument to that method or constructor? Is it because by implementing the interface, the class, is in essence, an object of the Interface?

A: An object of a class C that implements an interface I can be called an object of that interface, although a single object can be of many interfaces. Liskov substitution principle requires C to be usable anywhere where I is required, so in essence I becomes a contract of C, representing a subset of Cs abilities, as applicable to a certain situation.
For example, when an object implements Runnable, the run() method in the interface presents a particular aspect of the class to Java class library - namely, that objects of the class can be "ran" (by calling run() on them). The presence of Runnable lets you code the logic of your thread independently of Java designers, who write their thread-execution code independently of your implementation's logic.

A: The reference to a Runnable is possible since the Runnable object must have all methods in the Runnable interface implemented.
This way you can access all those methods at run time.
If the class that is said to implement Runnable would somehow not implement Runnable - there would be a compilation error, as Java Language Specification 7 chapter 8 (classes) - 8.1.5 (superinterfaces) specifies:

A class is said to implement all its superinterfaces.

The example given is the following:
Example 8.1.5-3. Implementing Methods of a Superinterface
interface Colorable {
    void setColor(int color);
    int getColor();
}

class Point { int x, y; };

class ColoredPoint extends Point implements Colorable {
    int color;
}

This program causes a compile-time error, because ColoredPoint is not an abstract class but fails to provide an implementation of methods setColor and getColor of the interface Colorable.

A: If a class implements an interface, it can be used in any place where the interface type can be used. For example, if an class implements Runnable, then an instance of that class can be used anywhere where a Runnable can be used. This is an example of polymorphism.
For example, here is a class that implements Runnable:
public class MyRunner implements Runnable {
  public void run() {}
}

You can use MyRunner like follows:
MyRunner runner = new MyRunner();

// can assign to a field of type "Runnable" without a cast
Runnable runnable = runner;

// can pass to methods that take a Runnable
Executors.newFixedThreadPool(3).execute(runner);

The MyRunner class is said to be an instance of Runnable. You even can check this via reflection;
public void runIfIsRunnable(Object object) {
  if (object instanceof Runnable) {
    Runnable r = (Runnable) object;
    r.run();
  }
}

Using instanceof is often considered a code smell, but there are situations where it is useful, like when you create instances of a class via reflection.

A: Objects inherit their parent classes interfaces, and methods from those interfaces can be overridden in sub classes.
The Value of interfaces is that they allow for methods to be created that accommodate a variety of object classes as input, by accepting the interface type as input.
Any object that implements an interface is in fact "interface"able for the given interfaces it implements.
The implementation of an interface by a class implies the ability of that class to perform any methods specified within the interface. As such any method that runs on the interface can run on something implementing the interface.

A: An interface establishes a contract that the object will contain the methods defined in the interface and this contract is enforced by the compiler.  So the compiler will check for this.
By convention, interfaces end in "-ible" are "-able" to show this behavior (though this by no means is a hard rule).  But in the end, the type of the object is either java.lang.Object or a direct/indirect extension of it.  If you look at the inheritance tree on any Javadoc, you'll see the hierarchy of classes extending one another and known implementing classes of interfaces.
So one doesn't normally speak of objects created by the class as objects of an interface, but rather that the class implements one.


text:
Q: Eiffel: loosening the pre-conditions and tightening the post-conditions? In Eiffel it is said that we should "loosen the pre-conditions and tightening the post-conditions", but I am not sure what this means.  How does this benefit/is benefited by sub-classing?
Thank you

A: In Design by Contract, you specify a set of pre-conditions and a set of post-conditions for a function. For example, let's say you were writing a memory allocation function. You require that it accept a positive integer as input, and produces an evenly aligned pointer as its result.
Loosening the precondition means that when you create a derived class, it has to accept any input that the base class could accept, but might accept other inputs as well. Using the example above, a derived class could be written to accept a non-negative integer instead of just positive integers.
On the result side, you have to ensure that the result from a derived function meets all the requirements placed on the base function -- but it can also add more restrictions. For example, a derived version of the function above could decide to only produce results that were multiples of 8. Every multiple of 8 is clearly even, so it still meets the requirement of the base function, but has imposed an additional restriction as well.
The opposite would not work: if the base class function allows non-negative integers as input, then the derived class must continue to accept all non-negative integers as input. Attempting to change it to accept only positive integers (i.e., reject 0, which is allowed by the base class) would not be allowed -- your derived class can no longer be substituted for the base version under all circumstances.
Likewise with results: if the base class imposed a "multiple of 8" requirement on a result, the derived version must also ensure that all results are multiples of 8. Returning 2 or 4 would violate that requirement.


text:
Q: Foreign key allow null SQL please check it this two tables.
create table Panda (id int identity, koalaId null)
create table Koala (id int identity)

I need that koalaId was foreign key to table Koala -> identity, but also I need that koalaId can be a NULL.
After this will be resolved, I need get data from Panda, but I get only a error:

Property koalaId for Panda not be set to null. This property must be set to a value that is not null and is of type Int32.

And I want for koalaId set to null.
Thank you for your advice.

A: By default a foreign key column will allow null value. you don't want to mention it explicitly.
**for example:**
             Create table Kola(Id numeric identity(1,1) primary key)
             Create table Panda(Id numeric identity(1,1),
                                KolaId numeric references Kola(Id))

*Note:*But make sure column 'id' in table 'kola' should be a primary key before it get referenced
by another table.

A: here is Panda and Cola creation codes:
    CREATE TABLE [dbo].[Kola](
        [id] [int] NOT NULL,
        [kolaName] [nchar](10) NULL,
      CONSTRAINT [PK_Kola] PRIMARY KEY CLUSTERED
    (
        [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,                           ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

    CREATE TABLE [dbo].[Panda](
        [id] [int] NOT NULL,
        [KolaId] [int] NULL,
     CONSTRAINT [PK_Panda] PRIMARY KEY CLUSTERED
    (
        [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,         ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO

    ALTER TABLE [dbo].[Panda]  WITH CHECK ADD  CONSTRAINT [FK_Panda_Kola] FOREIGN         KEY([KolaId])
    REFERENCES [dbo].[Kola] ([id])
    GO

    ALTER TABLE [dbo].[Panda] CHECK CONSTRAINT [FK_Panda_Kola]
    GO


text:
Q: Two UIViewControllers on one screen without SplitViewController How can I bring two uiviewcontrollers onto one screen with out using splitviewcontroller in story board ?

A: I don't think that is possible in the story board. You have to do that programmatically using addChildViewController: (UIViewController Class Reference Scroll down to "Implementing a Container View Controller"). Container View Controller is a feature introduced in iOS 5.

A: The only possible way that I could think about doing this is adding two Container Views in one View Controller and then giving each container view a class. You can find the container views in your objects library under "Container View"