text:
Q: Expansion of space or contracting of matter? Can the expansion of the Universe effect be explained by contraction of the overall matter instead? That is, all material objects are in fact contracting, due to what the universal space seems (and only seems) to be expanding. Are there any theoretical arguments or experimental data that preclude replacement of the universal space expansion by the universal matter contraction as an explanation tool of the nature of the very process?

A: This alternative that you mention is very imaginative, but It poses several problems. For example, if all matter is contracting, galaxies and clusters or any large scale structure would eventually collapse, and this is not something we have detected. In addition, the expansión of the universe not only affects matter, but also light: photons loose energy, which is equivalent to say their wavelengths are redshifted. A contraction would imply that light is blueshifted, again an effect that we have not observed.

A:
Can the expansion of the Universe effect be explained by contraction of the overall matter instead?

No. If the universe was not expanding, the tempeture of the of the universe would reamin the same. And this is not the case. Also according to GR the universe cannot be stationary. It should be either expanding or contracting.

A: The answers proposed by others here are correct and they give you intuitive reasons why they are correct.
I've thought about similar questions before.
Another way of asking it, if I were to try and guess what you are proposing, would be:
"Could dark energy expansion be explained by proposing that the Planck distance is not actually a constant?"
A good resource for thinking about this would be Leonard Susskind's YouTube Stanford lectures on cosmology.  At some point he derives Planck constants from scratch, and gives good explanations for why these things are constants and why they don't vary.
https://youtu.be/P-medYaqVak
Lots of equations, but always explained well.


text:
Q: Data not saved to HBase (from Spark consumer) We have this line of code in a Spark consumer program.
hbaseConnection.getValue().getConnection().getTable(someTableName).put(puts); // 1 //
So this line from the program is saving to HBase.
Here puts is a collection of Put objects.
It could be quite large - like 30K in size e.g.
Right after this line we have this other line of code puts.clear(); // 2 //
Now... sometimes we have a serious problem, some records are just not saved in HBase, even though they have the correct key and they are in the puts collection. But also, no exception is thrown while saving to HBase.
I wonder if clearing the puts too early could be causing the problem.
In other words is the call to // 1 // synchronous or not?
Could it be that we are clearing the puts collection too early while the saving (from line // 1 //) is still taking place?
Why am I thinking this? Because when running the same code with less data (say 500 records) no issue happens - the data is saved to HBase. But it's the same code?! So what could be the problem here?! The only difference I see is in the sizes of the puts collection in the two scenarios.
So I am thinking we might be clearing the puts too early and line // 1 // might be asynchronous.
Note: This is not my code, it was written by another person.
It's been only a week or two since I started looking into it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get the path of the current php file relative to the web root folder and not to the system root folder? Some years ago I developed a web app which contained the following code in a php file located in the root folder of the app:
define('APP_ROOT', dirname(__FILE__) . DIR_SEP);

This was to allow the app to be installed in any sub directory of the web docs folder and not necessarily directly in the web root itself, so that the app had a base path from which to dynamically calculate any other paths used in the app.
My test system back then was an Xampp installation running on Windows 7. I no longer have that system, but I believe the path to the htdocs folder was C:\xampp\htdocs and my app was contained in C:\xampp\htdocs\timesheets. On that system, the value of APP_ROOT was timesheets/, exactly as I wanted.
I know that the customer ran the app on a Linux server and I believe the app was installed in /var/www/timesheets/. So the value of APP_ROOT was timesheets/. I know this worked correctly because he never needed to modify my code.
I am now trying to use the same code again, but my test system is Ubuntu 20.04 with Apache 2.4 and PHP 7.4. The value I am getting in APP_ROOT is /var/www/html/timesheets/, which is causing all my dynamic path calculations to be wrong.
I have tried setting doc_root and open_basedir in php.ini, but I am still getting the full absolute path. I think this must be to do with the server or php configuration, but I have searched the web and cannot find how to correct it.


text:
Q: Disabling Strict Contextual Escaping (SCE) in AngularJS I'm trying to disable SCE in AngularJS.
According to the documentation this is what needs to be done:
angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);
});

This is my app.config.js:
angular.module('yapoApp').config(['$sceProvider', '$locationProvider', '$routeProvider',  '$httpProvider',
    function config($sceProvider, $locationProvider, $routeProvider,  $httpProvider) {

        // disable SCE completely (https://docs.angularjs.org/api/ng/service/$sce)
        $sceProvider.enabled(false);

        $locationProvider.hashPrefix('!');

        $routeProvider.when('/actors', {
            template: '<actor-list></actor-list>'
        }).when('/actors/:actorId', {
            template: '<actor-detail></actor-detail>'
        }).when('/movies/', {
            template: '<movie-list></movie-list>'
        }).when('/movies/:movieId', {
            template: '<movie-detail></movie-detail>'
        }).otherwise('/'), {
            template: '

 This is temp index
'

        };

    }

]);

And I'm still getting an error:

[$interpolate:noconcat] Error while interpolating: /static/movies/{{
  $ctrl.movie.id }}/sample/sample.mp4 Strict Contextual Escaping
  disallows interpolations that concatenate multiple expressions when a
  trusted value is required.

The html template causing the error:
 <video width="{{ $ctrl.videoWidth }}px" controls>
        <source ng-src="/static/movies/{{ $ctrl.movie.id }}/sample/sample.mp4">

        Your browser does not support the video tag.
    </video>

I feel like I'm missing some simple syntax error. Please help!

A: First you should check this, from doc:

Can I disable SCE completely?
Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.

Well, I don't think you need to disable SCE in this case, and also, for example, if you use ngBindHtml to render some HTML, AngularJS will throw an error unless the scope variable assigned to ngBindHtml is wrapped with $sce.trustAsHtml.
But, let's back to the error, which one speaks for itself:

Error while interpolating: /static/movies/{{ $ctrl.movie.id
  }}/sample/sample.mp4

You just need to concatenate it in the right way, like this:
<source ng-src="{{'/static/movies/' + $ctrl.movie.id + '/sample/sample.mp4'}}">

Hope it helps!!

A: I found this. Apparently, it's not an SCE issue. It's an issue with how Angular gets along with Html5 Video "source: tag.
If there is only one video source, having the HTML look like this:
<video src="ng-src="{{'/static/movies/' + $ctrl.movie.id +  '/sample/sample.mp4'}}" width="{{ $ctrl.videoWidth }}px" controls>
        Your browser does not support the video tag.
</video>

Instead of this:
<video width="{{ $ctrl.videoWidth }}px" controls>
        <source ng-src="{{'/static/movies/' + $ctrl.movie.id +  '/sample/sample.mp4'}}">

        Your browser does not support the video tag.
</video>

Solves the problem.
Of course, @developer033 was correct, and my initial concatenation was wrong.


text:
Q: Elements in Fragment not working after re-adding the same fragment UPDATE: I have found the header isn't the only thing affected, but listeners and other elements in the fragment aren't being initialized.  (Such as FAB's).  The only things that function correctly is anything built inside the adapter (i.e. the ListView rows)
The Problem:  Open Nav Drawer, click on a list item that opens up a new Fragment in the same Activity.  Open the Nav Drawer again, click the same item that should simply replace the existing Fragment and while the Fragment does open, all of the elements that are set programmatically in Java (text, colors, listeners) are not changed/added to the Fragment.  The view is simply the default xml layout.  I have confirmed with Log.d that the code that sets these things is being ran. (If you open a different Fragment and then go back to the original one, everything works fine)
The Confirmed Cause:  When changing this:
    compile "com.android.support:appcompat-v7:25.0.1"
    compile 'com.android.support:design:25.0.1'

to
    compile "com.android.support:appcompat-v7:25.1.0"
    compile 'com.android.support:design:25.1.0'

(if only one of these libraries is changed, it doesn't matter which one, the problem still occurs)
I have confirmed changing these two libraries is the problem (also confirmed this problem in a second app -- and changing only this code, has the exact same result)
My questions is, why is this happening and how can it be fixed?
The Code and more detailed description from original question:
                FragmentTransaction tItems = fm.beginTransaction();
                ListFragment mFrag = new PlannerFragment();
                tItems.replace(R.id.main_frag, mFrag, TAG_CALC_FRAGMENT);
                tItems.commit();

There are about 4 options in my drawer that all open this Fragment, but before each one, I set a global variable like this:
MyApp.PlanType = "highbal";
MyApp.PlanType = "lowbal";
etc.

Based on the PlanType value (above), that Fragment is loaded with different data (but, in the exact same xml layouts). It is simply a ListView with a header.
This Fragment, (PlannerFragment) loads fine the first time.
When I click on another item (a different PlanType) that goes to the same Fragment (same code above executed):  The ListView loads fine in the actual list.  But in the header in the list, none of the setText() values set the new data properly.  It uses the default values from my xml layout.
Now, if I load a different Fragment in between, everything works great.  It's only when I either add or replace (I've tried both) the same Fragment on top of the old one does this happen.
Here is header code at top of PlannerFragment
@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Setup listview
        lv = getListView();

        LayoutInflater inflaterHeader = getActivity().getLayoutInflater();
        ViewGroup header = (ViewGroup) inflaterHeader.inflate(R.layout.planner_listview_header, lv, false);
        lv.addHeaderView(header, null, false);

        // Load Data then Set Textviews, e.g.:
        TextView title = (TextView) getActivity().findViewById(R.id.tvPlannerTitle);
    dateOutput = (TextView) getActivity().findViewById(R.id.tvDebtOutDate);

If I add to that code, dateOutput.setText("test"); it does not happen.  I can do a Log.dand my data registers, so this code is being read, but the UI is not set.
I've even tried removing the Fragment first like this with a check:
                Fragment fragment = fm.findFragmentByTag(TAG_CALC_FRAGMENT);
                if(fragment != null)
                    fm.beginTransaction().remove(fragment).commit();

This has no effect.
Again, this ONLY happened when I changed the libraries above.  Is this a bug with the library or does it now respond differently?

A: you can add list_view_header.xml in navigationDrawer() method and change the position of  selected item like selectItem(position - 1).
  private void navigationDrawer() {

        mTitle = mDrawerTitle = getTitle();
        // mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        LayoutInflater inflater = getLayoutInflater();
        View listHeaderView = inflater.inflate(R.layout.list_view_header, null, false);
        mDrawerList.addHeaderView(listHeaderView, null, false);

        setupToolbar();

        DataModel[] drawerItem = new DataModel[6];

        drawerItem[0] = new DataModel(R.drawable.dashboard_icon, "Dashboard");
        drawerItem[1] = new DataModel(R.drawable.cal_icon, "Calender");
        drawerItem[2] = new DataModel(R.drawable.classes, "Classes");
        drawerItem[3] = new DataModel(R.drawable.message_icon_hdpi, "Message Center");
        drawerItem[4] = new DataModel(R.drawable.profile, "Profile & Setting");
        drawerItem[5] = new DataModel(R.drawable.bulletin_icon, "Bulletin Board");

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setHomeButtonEnabled(true);

        DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item_row, drawerItem);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        setupDrawerToggle();

    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position - 1);
        }

    }

    private void selectItem(int i) {
        Fragment fragment = null;

        switch (i) {
            case 0:
                fragment = new Fragment_DashBoard();
                // toolbar.setTitle("Dashboard");
                Titletv.setText("Dashboard");
                break;
            case 1:
                fragment = new Fragment_Calender();
                // toolbar.setTitle("Calender");
                Titletv.setText("Calender");

                break;
            case 2:
                fragment = new Fragment_Classes();
                // toolbar.setTitle("Classes");
                Titletv.setText("Classes");
                break;
            case 3:
                fragment = new Fragment_MessageCenter();
                // toolbar.setTitle("Message");
                Titletv.setText("Messages");
                break;
            case 4:
                fragment = new Fragment_ProfileSetting();
                // toolbar.setTitle("Profile");
                Titletv.setText("Profile");

                break;

            case 5:
                fragment = new Fragment_BulletinBoard();
                //toolbar.setTitle("Bulletin Board");
                Titletv.setText("Bulletin Board");

                break;

            default:
                break;
        }

        if (fragment != null) {

            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction trans = fragmentManager.beginTransaction();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();

            mDrawerList.setItemChecked(i, true);
            mDrawerList.getItemAtPosition(i);
            // setTitle(mNavigationDrawerItemTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);

        } else {
            Log.e("MainActivity", "Error in creating fragment");
        }

    }

A: There is many changes and issues with Fragments on appcompat 25.1.0. The first one seems related to your issue but the two next should be read as it may be important.

FragmentTransaction replace behaviour
Replace not working properly in appCompat 25.1.0
Current status (Jan 4 2017): bug assigned
Issue link

Fragment lifecycle change on 25.1.0
onStart on new Fragment is called before onStop on previous one
Current Status : works as expected. For me it could be a breaking change from app compat 25.0.x
Issue link
There is also an issue with the resume event called two times in fragment, see here.
TLDR. Maybe the best temporary solution is to not use 25.1.0 until a new version is out.


text:
Q: Very simple SQL table query not stopping When I run the following SQL query, returns 113316 records but doesn't stop running:
SELECT * FROM SupportingVideo

If I add TOP 113336 the query completes (returning 113336 records) within a second.  If I change it to TOP 113337 the query returns the orginal 113316 records and runs indefinitely.
Does anyone have any ideas what could be causing this?
Many thanks

A: This was due to a suspended process blocking other processes.  I used the sp_who2 stored procedure to find out which process was doing the blocking and then I used the Activity Monitor (In Object Explorer, right click on the server node and then select Activity Monitor) to kill the offending process.


text:
Q: Polynomials and Integrability Let $c_{n, m}$ be complex numbers ($n=0,1,\dots,N$ and $m=0,1,\dots,M$) not all equal to zero, and consider the polynomial function $P:\mathbb{R}^2 \rightarrow \mathbb{C}$ defined for each $(x,y) \in \mathbb{R}^2$ by
\begin{equation}
P(x,y)= \sum_{n=1}^{N} \sum_{m=1}^{M} c_{n,m} x^{n} y^{m}.
\end{equation}
Now define, whenever $(x,y) \in \mathbb{R}^2$ is such that $P(x,y) \neq 0$:
\begin{equation}
F(x,y)=\frac{1}{P(x,y)}.
\end{equation}
Let $Q(x,y)$ and $R(x,y)$ be respectvely the real and imaginary part of $P(x,y)$. The zero set of $P(x,y)$ is the intersection of the zero sets of the two real polynomials $Q(x,y)$ and $R(x,y)$. Since the zero set of a non null real polynomial has zero Lebesgue measure (for a very simple proof see Daniel Fischer's answer in Zero Set of a Polynomial), we conclude that $F$ is defined a.e.
Assume that $F$ is locally integrable. Can we conclude that $P$ has no zero on $\mathbb{R}^2$?
I think the answer is yes, but I could find no proof of this fact.
NOTE (1). Let us not that the analogous question for polynomials in one variable has clearly a positive answer. Indeed for the Fundamental Theorem of Algebra we have in this case $P(x)=(x-z_1)^{n_1}\dots(x-z_k)^{n_k}$, and if some of the $z_1,\dots,z_k$ is real, clearly $F$ is not integrable.
NOTE (2).Let us also note that the analogous question on $\mathbb{R}^n$, for $n \geq 3$, has a negative answer, as the polynomial $P(x_1,\dots,x_n)=x_1^2+\dots+x_n^2$ shows. So the only critical case is that of $\mathbb{R}^2$.

A: Here's another solution. I'll assume all polynomials are real. I'll start with an easy result:
Lemma: Suppose $P$ is a polynomial in one variable and on the interval $[a,b]$ we have $P(a) < 0, P(b)>0.$ Then
$$\tag 1\int_a^b \frac{1}{|P(t)|}\, dt =\infty.$$
Proof: By the intermediate value theorem, $P(c) = 0$ for some $c\in (a,b).$ Thus there is a positive $C$ such that $|P(t)|\le C|t-c|$ for $t$ near $c.$ This implies $1/|P(t)|\ge 1/(C|t-c|),$ which gives $(1).$
Suppose now $P$ is a nonconstant polynomial in two variables, with $P(0,0) = 0.$
Case 1: $\nabla P(0,0) = (0,1).$ Then $P(x,y) = y + Q(x,y),$ where $Q(0,0) = 0$ and $\nabla Q(0,0) = (0,0).$ Every term in the polynomial $Q$ is then $O(x^2+y^2).$ It follows that there is a constant $C$ such that
$$\tag 2 |Q(x,y)|\le C(x^2+y^2) \text { for } (x,y) \text { close to } (0,0).$$
Choose $h_0$ such $(x,y) \in [-h_0,h_0]^2$ implies $(2).$ By going to a smaller $h_0,$ if necessary, we can assume $2Ch^2<h$ for $0<h<h_0.$ Then for any such $h,$
$$\tag 3 \int_{-h}^h \int_{-h}^h \frac{1}{|y+Q(x,y)|}\, dy\,dx = \int_{-h}^h \infty \,dx = \infty.$$
Why? For any fixed $x \in [-h,h],$ the polynomial $y\to y+Q(x,y)$ is positive at $h$ and negative at $-h.$ By the lemma, the integral with respect to $y$ is $\infty$ for this $x.$ Fubini then gives $(3).$ Conclusion: $1/|P|$ is not locally integrable at $(0,0).$
Case 2: $\nabla P(0,0)\ne (0,0).$ Then there is a nonsingular linear transformation $T:\mathbb R^2 \to \mathbb R^2$ such that $\nabla (P\circ T)(0,0) = (0,1).$ By case 1, $1/|P\circ T|$ is not locally integrable at $(0,0).$ The linear change of variables $(x,y) \to T^{-1}(x,y)$ then shows $1/|P|$ is not locally integrable at $(0,0).$
Case 3: $\nabla P(0,0)= (0,0).$ This is the easy case. We have $|P(x,y)| \le C(x^2+y^2)$ near $(0,0).$ Hence $1/|P(x,y)| \ge 1/[C(x^2+y^2)]$ for these $(x,y).$ In polar coordinates this implies a singularity on the order of $1/r^2$ at the origin. Integrating in polar coordinates then shows $1/|P|$ is not locally integrable at $(0,0).$

A: Finally, I realized that the answer to my question is generally negative if we assume that the coefficients $c_{n,m}$ are complex, as the simple example $P(x,y)=x+iy$ shows.
But if we make the assumption that all the coefficients $c_{n,m}$ are real, then the answer is in the affirmative, and this is the proof.
Assume that $(x_0,y_0) \in \mathbb{R}^2$ is such that $P(x_0,y_0)=0$. By considering eventually the polynomial $\tilde{P}(x,y)=P(x+x_0,y+y_0)$, we can assume without loss of generality that $(x_0,y_0)=(0,0)$. So $P$ has no constant term, that is $c_{0,0}=0$.
First consider the case $c_{1,0}=c_{0,1}=0$.
By considering polar coordinates, we then have
\begin{equation}
P(r \cos \theta, r \sin \theta) = \sum_{n,m} c_{n,m} r^{n+m} \cos^{n}(\theta) \sin^{m}(\theta),
\end{equation}
so that by putting
\begin{equation}
S_k(\theta)= \sum_{n+m=k} c_{n,m} \cos^{n}(\theta) \sin^{m}(\theta),
\end{equation}
we have
\begin{equation}
P(r \cos \theta, r \sin \theta) = \sum_{k=2}^{d} r^{k} S_k(\theta),
\end{equation}
where $d$ is the degree of $P(x,y)$.
For $r \in (0,1)$, we then have
\begin{equation}
\frac{r}{|F(r \cos \theta, r \sin \theta)|} \geq \frac{1}{\sum_{k=2}^{d} r^{k-1} |S_k(\theta)|} \geq
\frac{1}{r \sum_{k=2}^{d} |S_k(\theta)|}.
\end{equation}
Let us make the simple observation that if we have $c_{n,m} \neq 0$ for some $n, m$ such that $n+m=k$, then, since
\begin{equation}
S_k(\theta)= \cos^{k} (\theta) \left[ \sum_{n+m=k} c_{n,m} \tan^{m}(\theta) \right],
\end{equation}
we have $S_k(\theta) \neq 0$, except for a finite number of values of $\theta$. Then we conclude that
\begin{equation}
\int_{[0,1] \times [0,2 \pi]} \frac{1}{r} \frac{1}{ \sum_{k=r}^{d} |S_k(\theta)|} dr d \theta = \infty,
\end{equation}
so $F$ is not locally integrable.
Consider now the case in which at least one of $c_{0,1}$ and $c_{1,0}$ is distinct from zero, e.g. $c_{0,1} \neq 0$. By the Implicit Function Theorem, there is $\delta > 0$ and $\sigma > 0$ such that for every $x \in (-\delta, \delta)$ there exists a unique $y \in (-\sigma,\sigma)$ such that $P(x,y)=0$. We then have for every fixed $x \in (-\delta, \delta)$ that the polynomial $Q(y)=P(x,y)$ has (exactly) one zero on the interval $(-\sigma,\sigma)$, so that by the result in NOTE (1) we have
\begin{equation}
\int_{[-\sigma,\sigma]} |F(x,y)| dy = \infty,
\end{equation}
and we conlude that
\begin{equation}
\int_{[-\delta, \delta]} \int_{[-\sigma,\sigma]} |F(x,y)| dy dx = \infty.
\end{equation}
QED


text:
Q: Loading JSON data from a file This may be a duplicate of any question but I was not able to find a solution to my problem.
I am building an MVC4 application in which I want to load JSON data from another JavaScript file, using AJAX.
For this, I tried using $.getJSON(), $.ajax(), $.get() other similar functions to load data. It is a simple AJAX call, nothing fancy! Eventually I realized that I need to make this call to a controller/action which would load the JSON and return it back. This solution worked for me.
$.ajax({
    type: "GET",
    url: "/controller/action", // <-- How can I refer to the JSON file directly here?
    contentType: "application/json; charset=utf-8",
    dataType: "application/json",
    success: function(data) {
    },
    error: function(err) {
    }
});

I want to know if there is some other way for me to load this file using JavaScript in the view itself without invoking any controller/action?

Note: The file is a .json file and not a .js file. I don't want to include the file in any <script> tag!

A: The problem here is that you don't have a mime type of type json specified in your web.config and IIS/IIS Express is returning a 404 error.
Try modifying your web.config like so:
<system.webServer>
    <staticContent>
        <mimeMap fileExtension=".json" mimeType="application/json" />
    </staticContent>
</system.webServer>

You will also need to change the dataType to json instead of application/json:
$.ajax({
    type: "GET",
    url: "Content/your.json",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
    },
    error: function (err) {
    }
});

Hope this helps.

A: To refer a JSON file, you can use the Url.Content() method in your Javascript :
$.ajax({
    type: "GET",
    url: "@Url.Content("~/Content/your.json")",
    contentType: "application/json; charset=utf-8",
    dataType: "application/json",
    success: function (data) {
    },
    error: function (err) {
    }
});

In this case, I have a your.json file in Content folder.
Hope it helps !


text:
Q: Firebase token not generated in flutter web Error:

[firebase_messaging/token-subscribe-failed] Messaging: A problem occurred while subscribing the user to FCM: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. .
at Object.createErrorWithStack (http://localhost:2277/dart_sdk.js:5080:12)
at Function._throw (http://localhost:2277/dart_sdk.js:20337:18)
at Function.throwWithStackTrace (http://localhost:2277/dart_sdk.js:20334:18)
at async._AsyncCallbackEntry.new.callback (http://localhost:2277/dart_sdk.js:40851:18)
at Object._microtaskLoop (http://localhost:2277/dart_sdk.js:40708:13)
at _startMicrotaskLoop (http://localhost:2277/dart_sdk.js:40714:13)
at http://localhost:2277/dart_sdk.js:36191:9

A: You need to generate a Vapid Key in the Firebase Settings | Cloud Messaging tab.
Please check the following answer on how to do that.
https://stackoverflow.com/a/54996207/10086962


text:
Q: calling codeigniter method from javascript and passing data Hello I am using codeigniter framework for my college project ,and I need to call controllers method from js function, and i manage to do that, but now I dont know how to pass data to that method that I am calling. I was found some examples on web but I didn't manage to solve my problem.
This is how I call my method from js function,
window.location.href = "<?php echo site_url('controller_user/test');?>";

and I need to send this data to that method
var data = [formName, formSurname, formEmail, formUsername];

And I try something like this:
window.location.href = "<?php echo site_url('controller_user/test');?>?data="+data;

I don't know what to do to solve this problem, like I said I found something similar on stackoverflow site but still having trouble.
Thanks to everyone willing to help me!!!

A: please modify your JavaScript like the following
window.location.href = "<?php echo site_url('controller_user/test');?>/"+formName+/+formSurname+'/'+formEmail+'/'+formUsername;

modify your controller function like the following
public function test($formName='',$formSurname='',$formEmail='',formUsername=''){

    echo "$formName ,$formSurname,$formEmail,formUsername";
    exit;

}

A: try this
window.location.href = "<?php echo json_encode(site_url('controller_user/test'));?>

A: you should use ajax and passed the data to method . like this , try out
var data = {formName : formName , formSurname : formSurname ,formEmail : formEmail,formUsername : formUsername}

     $.ajax({
            url: '<?php echo base_url('controller_user/test');?>',
            type: 'POST',
            data: data,
            success: function(msg)
            {
                //success part code
            }
        });
        return false;


text:
Q: How to filter a multiple array bye value[0] of each line? I would like to filter a multiple array in JS by the value[0] of each line. In my next array, there are several "visiteur", "paris", "monaco" and I want to have juste one of each. Any idea ?
My array :
0: ['firstname', 'id']
1: ['FootContact Team', '1']
2: ['Cergy Pontoise Football Club', '2']
3: ['visiteur', '42']
4: ['visiteur', '43']
5: ['visiteur', '44']
6: ['monaco', '45']
7: ['monaco', '46']
8: ['paris', '47']
9: ['paris', '48']
I expect this :
0: ['firstname', 'id']
1: ['FootContact Team', '1']
2: ['Cergy Pontoise Football Club', '2']
3: ['visiteur', '42']
6: ['monaco', '45']
8: ['paris', '47']

A: let listOfUsers = [['toto', 1], ['titi', 2],['titi', 5], ['visiteur',3], ['visiteur', 4]];
let filtered = {};
listOfUsers = listOfUsers.filter((user) => {
    let name = user[0];
    if (!filtered[name]) {
        // set flag and return true since it's the first happening
        return filtered[name] = true;
    }
});
console.log(listOfUsers);

A: Generically speaking, you want to keep an element in your array if it did not show up beforehand.

*

*input.filter((element, index, array) => ...) uses the additional filter arguments

*array.slice(0, index) contains the array elements smaller than the current index

*some(element2 => (element[0] === element2[0])) returns true if at least one prior element is identical wrt. to the first element

let input = [
    ['firstname', 'id'],
    ['FootContact Team', '1'],
    ['Cergy Pontoise Football Club', '2'],
    ['visiteur', '42'],
    ['visiteur', '43'],
    ['visiteur', '44'],
    ['monaco', '45'],
    ['monaco', '46'],
    ['paris', '47'],
    ['paris', '48'],
]

let expectedOutput = [
    ['firstname', 'id'],
    ['FootContact Team', '1'],
    ['Cergy Pontoise Football Club', '2'],
    ['visiteur', '42'],
    ['monaco', '45'],
    ['paris', '47'],
]

let actualOutput = input.filter((element, index, array) =>  !array.slice(0, index).some(element2 => (element[0] === element2[0])))

console.log(
  JSON.stringify(actualOutput)
  ===
  JSON.stringify(expectedOutput)
)


text:
Q: Allow us to edit tags on migrated questions The title should explain it.  An example of why this should be allowed is evident in this question:
https://stackoverflow.com/questions/1068984/how-do-you-manage-mssql-2000-2005-patches-closed
Currently it's the only question on StackOverflow tagged 'mssql', and we cannot remove that tag.  As a consequence, the mssql tag is still active for new users with low rep.

A: Nah, there aren't any mssql questions ;-p
updating post history, 26 rows affected
updating posts, 19 rows affected
removing/renaming old tag, 1 rows affected
updating count for master tag, 1 rows affected
merge of [sql-server] and [mssql] complete!

The locking etc is there to prevent it become re-opened, and for the low volume that this happens, I suspect that (for now at least) MSO or moderator flags would work fine. It isn't (IMO) worth the time to think of a "better" approach, let alone implement it...


text:
Q: sqlalchemy table.update.returning only returns one value instead of multiple on postgresql I'm using postgresql and sqlalchemy, here is to update a table and then return multiple values by  using returning:
async def update_monitor(id: int, payload: MonitorIn) -> Dict[str, Any]:

    utc_now = to_utc(datetime.now())
    query = (
        MONITOR
            .update()
            .where(id == MONITOR.c.id)
            .values(**payload.dict(), updated=utc_now)
            .returning(MONITOR.c.id,
                       MONITOR.c.watchlist_id,
                       MONITOR.c.term,
                       MONITOR.c.match_substring_variations,
                       MONITOR.c.nameserver_exclusions,
                       MONITOR.c.text_exclusions,
                       MONITOR.c.created,
                       MONITOR.c.updated)
    )
    result = await PRIMARY.execute(query=query)
    return {'id': result[0],
            'watchlist_id': result[1],
            'term': result[2],
            'match_substring_variations': result[3],
            'nameserver_exclusions': result[4],
            'text_exclusions': result[5],
            'created': result[6],
            'updated': result[7]}

PRIMARY is a postgresql db.
import databases
PRIMARY = databases.Database(config.DB_URL)

however, the result is an int that corresponds to MONITOR.c.id which is the first returned value, so it appears the returning method only returns one (the first) value instead of multiple values. I actually hope to get multiple values returned. and according to this it should support multiple values returned. what's wrong here?

A: It looks like the databases library's execute() returns Cursor.lastrowid, and if you want the result row(s) use fetch_one() / fetch_all() / iterate() instead.
Note that this is not the behaviour of SQLAlchemy and returning(), as hinted in the title of this question, but of databases, which simply uses the SQLAlchemy Core DSL as a way to define queries. Under the hood it then compiles them to text, and uses its own connection pool and the async driver in use to emit the statement to the database.


text:
Q: How to get column name for a unique_constraint violation? I am using the pq driver and I'm wondering why the pq.Error gives an empty Column when I face a unique constraint violation.
I could parse Detail but is there any reason why Column would be empty?  It would be preferable if I could just get email from Column instead of parsing Detail
Here is what the error looks like:
Severity:"ERROR"
Code:"23505"
Message:"duplicate key value violates unique constraint "unique_users""
Detail:"Key (email)=(user3@email.com) already exists."
Hint:""
Position:""
InternalPosition:""
InternalQuery:""
Where:""
Schema:"public"
Table:"users"
Column:""
DataTypeName:""
Constraint:"unique_users"
File:"nbtinsert.c"
Line:"534"
Routine:"_bt_check_unique"

Unfortunately, the Column value is empty.  I'm trying to come up with error messaging for my application and I'm wondering if there is some way to get that information so I can enhance the message why the entity was not created and let the caller know the field (email in this case) as well.

A: The specific error message (including the violated constraint and column/value) is in the field Detail.
EDIT:
I guess Column is empty, because the unique constraint might affect multiple columns. Constraint offers the constraint name, in combination with Schema and Table you can look up this constraint in pg_constraint. Field conkey might hold the references to the covered attributes.


text:
Q: Adding custom button to ribbon - Button doesn't get displayed I'm trying to add a custom button to a SP2010 ribbon in the DisplayFormToolbar for a list item. The list is external, although I don't think that matters but still...
This is my custom action definition:
  <CustomAction Id="{0116B081-B13E-4A4B-8F8D-EF7AC1E43BFD}"
                Location="DisplayFormToolbar"
                RegistrationType="List"
                RegistrationId="600"
                Sequence="1"
                ControlAssembly="myAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=...."
                ControlClass="myNamespace.MyRibbonButton" />

myNamespace.MyRibbonButton class extends System.Web.UI.WebControls.Button and has some basic code inside OnInit.
When I access the display form of an item in the external list, in debug I can see that OnInit is executed, there is no exception in the logs... but the button does not show in the form!
I have specified my assembly with SafeControl so that's not the cause.
Even if I add this to my custom action is still does not display:
<CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.ListForm.Display.Manage.Controls._children" />
      </CommandUIDefinitions>
    </CommandUIExtension>

What could I be missing?

A: SharePoint 2010 ribbon doesn't have anything in common with 2007's DisplayFormToolBar.
The custom action Location attribute should be set to "CommandUI.Ribbon" for adding something to ribbon.
Then, you should provide special XML for button. Since SP2010 ribbon is a client-side thing, no C# code is involved here.
You can find a simple example of adding a button to ribbon here:

*

*http://blogs.msdn.com/b/jfrost/archive/2009/11/06/adding-custom-button-to-the-sharepoint-2010-ribbon.aspx
P.S. Also, you can consider using SharePoint 2010 Fluent Ribbon API opensource project to work with ribbon in a simplified way. A quick how-to start can be found at project's documentation site. It is my project actually, and I cannot resist mentioning that it is a rather popular project and we use it in real-world projects at work intensively.


text:
Q: editing item size css and html Hi here's current website
enter image description here
And I'm trying to reduce image size so that it looks like this
enter image description here
I still want items to be horizontally and vertically centered.   I tried reducing .sample width; the image becomes smaller but then it's now not horizontally and vertically centered.  Would be great if you could point to which values I need to change... thanks in advance

.portfolio {
  position: relative;
  min-width: 300px;
  width: 100%;
  margin: 120px auto;
  list-style: none;
  margin-left: 70px;
  margin-top: 280px;
  margin-right: 0;
  margin-left: 0;
  padding-left: 5%;
}
.portfolio li {
  position: relative;
  float: left;
  margin: 20px 24px;
  margin-left: -15px;
  margin-bottom: -70px;
  width: 30%;
  padding-bottom: 10%;
  min-height: 270px;
  min-width: 270px;
  margin-left: -1%;
  margin-right: 1%;
}
.portfolio li .sample {
  position: absolute;
  display: block;
  box-shadow: 0px 0px 8px #fafafa;
  background-size: 100%;
  background-repeat: no-repeat;
  background-position: center;
  width: 90%;
  height: 56%;
  min-height: 180.36px;
}
.portfolio li:hover .sample {
  box-shadow: 0px 0px 12px #eee;
}
.details {
  position: absolute;
  bottom: 100px;
  width: 90%;
  display: block;
  margin: 10px;
  font-size: 17px;
  text-align: center;
  color: #8C8C8C;
  letter-spacing: 1.4px;
  margin-left: 0px;
  margin-right: 0px;
}

Clearear - website

Social newsreader - ux/ui

K-beauty app - ux/ui

A: Just change these 3 values:
.portfolio {
    width: 80%;
    margin-right: auto;
    margin-left: auto;
}

To completely get rid of horizontal margins or decrease them use these values:
.portfolio li {
    position: relative;
    float: left;
    margin: 20px 30px; /* tweak this however you like  */
    /* margin-left: -15px; remove this */
    margin-bottom: -70px;
    width: 20%; /* tweak this however you like  */
    padding-bottom: 10%;
    min-height: 200px; /* lower this  */
    min-width: 200px; /* lower this  */
    /* margin-left: -1%; remove this */
    /* margin-right: 1%; remove this */
}
.details { width: 100%; }
.portfolio li .sample { width: 100%; }

Because everything else is designed in %, we can shrink and center the parent with the rest following suit.


text:
Q: Technique for image library to camera matching app There are many small demonstration projects on Android to analyze video frames and make a determination if the frame has enough similarity to one of a small number of images to trigger an action. In these demonstration projects, these images are often analyzed upon app startup, saved in memory, then checked against video frames. This question seeks to identify a way to go beyond this relatively simple level of starting point for an image matching app.
This question is about how to structure an application that goes beyond that simple demonstration project in that it has or allows for a significant number of images in the library (hundreds), or has the capability to be expanded to manage a significant number of images. The Amazon "Flow" app is an example of how the app would work (but obviously nowhere near the number of match items, and the app may not necessarily require a remote server connection to work).
A high quality answer to this question would identify a way to structure the aforementioned matching app and briefly describe the structure of the app. It would not include technical programming details, but instead would assist a programmer in finding an advisable way to structure such a program. For instance, someone may find an open source app that has an offline component that extracts attributes from images, and that shows or provides a means by which those attributes are made available to the mobile application.
There are many technical question/answer pairs about image matching, but this question is not about the technicalities. It's about identifying a way to structure an app from a more advanced starting point than what the small demonstration projects offer.


text:
Q: GTK Focus Chain Currently I'm working on a pyGTK3 application for which I want to set the focus chain. When using the code below (simplified version) something interesting happens GTK focuses correctly on the first button but on tab nothing happens.
At first I thought this was caused by GTK not knowing the chain, but then I tried shift+tab which resulted in the last element of the chain get the focus which is correct. Yet another shift+tab doesn't move the focus away from the last button.
So I figured that their is something wrong with my code, do I need to update the chain order by hand? Or I am missing something?
class Screen(Gtk.Grid):
  def __init__(self, parent, core, video_widget):
    Gtk.Grid.__init__(self)

    # adds the control buttons
    self.controls = load_controls(self)

    self.set_focus_chain((self.controls.play, self.controls.backward, self.controls.recording))

A: In order to set the focus chain for elements within containers it is required to first set the focus chain of the parent to the container. From there the focus chain for the container needs to be set.
Thus the code needs to be as follows:
# Points Gtk toward the container first
self.set_focus_chain([self.controls])

# Sets the focus chain inside the container
self.controls.set_focus_chain((self.controls.play, self.controls.backward, self.controls.recording, self.controls.end_inspection))

So it seems that GTK only allows focus chains towards children thus requiring users to set a chain of focus chain to set the focus chain to grand children.


text:
Q: Stitching different IDs into one Unique ID I have this kind of data where I have chronological logs of visitors' devices and users. Here you can see that the same person used devices 'abc' and 'def' and has two different user IDs '123' and '456'. We can tell it's the same person because they have at least 2 users on 1 device (or depending how you see it 2 devices with 1 user). User '789' however is another person on their own as far as we can tell
+-------+------------+---------+
| date  | device ID  | user ID |
+-------+------------+---------+
| 2 Feb | abc        | 123     |
+-------+------------+---------+
| 3 Feb | abc        | 456     |
+-------+------------+---------+
| 4 Feb | def        | 456     |
+-------+------------+---------+
| 4 Feb | ghj        | 789     |
+-------+------------+---------+

I'm trying to stitch them back by assigning the person's very first (chronological) user ID.
What I'm trying to achieve is this:
+-------------+------------+------------+
| stitched ID | devices    | users      |
+-------------+------------+------------+
| 123         | [abc, def] | [123, 456] |
+-------------+------------+------------+
| 789         | [ghj]      | [789]      |
+-------------+------------+------------+

How do I build the query?

A: I don't know bigquery but in relational 'style' you should:
1> group by the 'common' attributes,
2> get the 'min' of the id as 'unique-id',
3> I'll also add a new view where for each 'unique' key you add the 'duplicated' ones as storing them as string may get heavy while querying.
Sorry for non-code answer but this should show you the way.


text:
Q: Wrong Blog Post Date Showing in Magento I am getting wrong blog post date on frontend in magento.
This is my code from phtml file of post.
$formatType = Mage::getStoreConfig(NeoTheme_Blog_Helper_Data::XPATH_CONFIG_DATETIME_FORMAT_TYPE);
 $format = ($formatType != 'custom')?
    Mage::app()->getLocale()->getDateTimeFormat($formatType):
    Mage::getStoreConfig(NeoTheme_Blog_Helper_Data::XPATH_CONFIG_DATETIME_CUSTOM_FORMAT);

and in below html it display date like -
<span class="post-time">
                <?php //echo $this->__('Posted On: '); ?>
                <?php $date = ($this->getPost()->getPostDate() != NULL)? $this->getPost()->getPostDate() : $this->getPost()->getCreatedAt(); ?>
                <?php  echo Mage::app()->getLocale()->date($date)->toString($format); ?>
                <?php // $timestamp = (int) Mage::app()->getLocale()->date($date)->getTimestamp() ;?>
                <?php // echo date('d D', $timestamp)?><?php // echo date('M', $timestamp)?>
            </span>

This is my Database structure
+--------------------+----------------------+------+-----+---------------------+-----------------------------+
| Field              | Type                 | Null | Key | Default             | Extra                       |
+--------------------+----------------------+------+-----+---------------------+-----------------------------+
| entity_id          | int(10) unsigned     | NO   | PRI | NULL                | auto_increment              |
| created_at         | timestamp            | NO   |     | CURRENT_TIMESTAMP   | on update CURRENT_TIMESTAMP |
| updated_at         | timestamp            | NO   |     | 0000-00-00 00:00:00 |                             |
| status             | smallint(5) unsigned | NO   |     | 1                   |                             |
| title              | text                 | NO   |     | NULL                |                             |
| author             | text                 | NO   |     | NULL                |                             |
| post_date          | timestamp            | NO   |     | 0000-00-00 00:00:00 |                             |
| summary            | text                 | NO   |     | NULL                |                             |
| content_html       | text                 | NO   |     | NULL                |                             |
| meta_description   | text                 | YES  |     | NULL                |                             |
| meta_title         | text                 | YES  |     | NULL                |                             |
| meta_keywords      | text                 | YES  |     | NULL                |                             |
| store_ids          | text                 | NO   |     | NULL                |                             |
| category_ids       | text                 | NO   |     | NULL                |                             |
| tag_ids            | text                 | NO   |     | NULL                |                             |
| cms_identifier     | varchar(255)         | YES  | UNI | NULL                |                             |
| customer_group_ids | text                 | YES  |     | NULL                |                             |
| publish_date       | timestamp            | YES  |     | NULL                |                             |
| use_summary        | smallint(6)          | YES  |     | 1                   |                             |
| root_template      | varchar(255)         | YES  |     | NULL                |                             |
| layout_update_xml  | text                 | YES  |     | NULL                |                             |
+--------------------+----------------------+------+-----+---------------------+-----------------------------+

can anyone please help me to find whats wrong with this code.
In Database it shows correct date.

A: there are two thing you have to
first remove on update CURRENT_TIMESTAMP this so the date will not update
use this to set value for created_At Varien_Date::now() if you want to do magento way.
<?php  $date=Mage::app()->getLocale()->date($date);
       echo date('L d, M Y',strtotime($date)) ?>


text:
Q: How to change a variable audio file value when calling a function to play the audiofile in Vanilla JavaScript? I am working on a project that when I used a specific keyboard's key a different sound must be played. I have a created a function to play the sound, then I attached an Event Listener to the DOM & finally I checked which key has been pressed & play the sound who correspond with the key.
I am trying to do this by writing DRY code. How can I change variable sound value when calling the function to play the sound file?
I have a tried changing the var sound = New Audio('filepath'); before calling the function playSound() but it doesn't work.
var sound = new Audio('assets/sounds/clap.wav');
// function to play sounds
function playSound() {
  sound.play();
}

// adds event listener & checks keyboard to play different sounds
document.addEventListener('keydown', function(event){
  if(event.keyCode == 65){
    playSound();
  } else if ( event.keyCode == 83 ) {
    playSound();
  }
  else if( event.keyCode == 68 ) {
    playSound();
  }
  else if( event.keyCode == 70 ) {
    playSound();
  }
});

A: You can pass the filepath in the conditionals and assign the audio filepath in the function like this:
var sound = new Audio('assets/sounds/clap.wav');

function playSound(filepath) {
  sound.src = filepath;
  sound.play();
}

// adds event listener & checks keyboard to play different sounds
document.addEventListener('keydown', function(event){
  if(event.keyCode == 65){
    playSound('somefilepath');
  } else if ( event.keyCode == 83 ) {
    playSound('somefilepath');
  }
  else if( event.keyCode == 68 ) {
    playSound('somefilepath');
  }
  else if( event.keyCode == 70 ) {
    playSound('somefilepath');
  }
});


text:
Q: Convert Dates PostgreSQL All,
I am migrating a few processes from SQL Server (SQL) to ParAccel (PostgreSQL).
One of the processes I have is currently using the following conversion.
Select convert(datetime,convert(varchar,MAX(getdate()), 101),101)

After you run this query, you get: 2014-05-07 00:00:00.000
I found a function in postgresql that could do this job. The function is:
SELECT date_trunc('day', getdate());

When you execute that query, you get the following:  5/7/2014 12:00:00 AM
Is there a way in PostgreSQL that you could get the same results as in SQL. SO I want to get 2014-05-07 00:00:00.000
Also, how can I just get the date, instead of the whole TIMESTAMP.

A: If you would to get date from timestamp, just do
postgres=# select current_timestamp::date;
    now
────────────
 2014-05-07
(1 row)

There are two ways

*

*preferred - use a to_char function
postgres=# select to_char(current_timestamp, 'YYYY-MM-DD hh24:mm:ss.ms');
        to_char
─────────────────────────
2014-05-07 19:05:52.537
(1 row)

*or with datestyle config variable
postgres=# set datestyle TO ISO;
SET
Time: 0.353 ms
postgres=# select current_timestamp;
              now
───────────────────────────────
 2014-05-07 19:12:44.236758+02
(1 row)

Time: 0.406 ms
postgres=# set datestyle TO GERMAN ;
SET
Time: 0.565 ms
postgres=# select current_timestamp;
               now
─────────────────────────────────
 07.05.2014 19:12:51.781772 CEST
(1 row)

Time: 0.700 ms

related postgresql doc

A: Use the to_char function to format date/time values as text (http://www.postgresql.org/docs/9.3/static/functions-formatting.html).
If you're only interested in the date part, cast the timestamps to date type.
To change the default date appearance, you can set:
datestyle = 'iso, mdy'

either in your session, or globally through postgresql.conf


text:
Q: I have come across some C++ code.Why we have to use *this in block instead of this? I have the following code, and I'm wondering why it uses *this instead of this.
class Quotation
{
protected:
    int value;
    char* type;
public:
    virtual Quotation* clone()=0;

    char * getType()
    {
        return type;
    }

    int getValue()
    {
        return value;
    }
};

class bikeQuotation : public Quotation
{
public:
    bikeQuotation(int number)
    {
        value=number;
        type="BIKE";
    }

    Quotation * clone()
    {
        return new bikeQuotation(*this);  // <-- Here!
    }
};

A: this is a pointer to the object. The copy constructor requires a reference to the object. The way you convert a pointer to a reference is with the dereferencing * operator.


text:
Q: libcurand.so.9.2: cannot open shared object file: No such file or directory I just installed cuda.9.2 following the instruction here. However, running my program using GPU produces an error.
error while loading shared libraries: libcurand.so.9.2: cannot open shared object file: No such file or directory

simon@desktop:/usr/local/cuda/lib64$ ls libcurand.so.9.2
libcurand.so.9.2
simon@desktop:/usr/local/cuda/lib64$ ls -lh libcurand.so.9.2
lrwxrwxrwx 1 root root 20 Jul 31 11:35 libcurand.so.9.2 -> libcurand.so.9.2.148

I notice there are a few reports on similar issues already. Does anyone have any idea on how to solve it?

A: Following sgarizvi's suggestion works. Indeed I forgot to export the path.
export LD_LIBRARY_PATH=/usr/local/cuda/lib64 && sudo ldconfig


text:
Q: Как создать рекурсивный Promise? Пытаюсь понять каким образом дождаться выполнение промиса, если по условию нужно опять вызвать его:
 const promise = () => new Promise((resolve, reject) => {
  const random = Math.floor(Math.random()*5);
  if(random === 1) {
    console.log('YES')
     resolve(true);
  } else {
    console.log('wait...')
     promise();
  }
})

const startPromise = async () => {
   const result = await promise(); //Если результат не приходит с первого раза, то код ниже не выполняется
    if(result) {
      console.log('done')
    }
}

Как дождаться пока промис вернет результат, если int  != 1 ?

A: Вот, позапускайте несколько раз, будет разное количество ожиданий в консоли:

const promise = () => new Promise((resolve, reject) => {
    const random = Math.floor(Math.random()*5);
    if(random === 1) {
        console.log('YES')
        resolve(true);
    } else {
        console.log('wait...')
        // Здесь дожидаемся. Без этого будет оборванная цепочка действий
        // (действий будет несколько, но конец завершения ошибочный (преждевременный))
        // или вовсе конца не будет
        promise().then(resolve).catch(reject);
    }
});

const startPromise = async () => {
    const result = await promise(); //Если результат не приходит с первого раза, то код ниже не выполняется
    if(result) {
        console.log('done')
    }
}

startPromise();

A: Честно говоря, ничего не понятно. В promise data это что такое? Если бросать число в startPromise то оно никогда не изменится и promise ваш будет или вечно крутится или сразу разрешится если вы ему единичку прокинете туда.
Сделал как понял. Если что-то не так - пишите уточнение.

const promise = () => new Promise((resolve, reject) => {
  const random = Math.floor(Math.random()*5);
  console.log('Promise', random);
  if(random === 1) {
     resolve(true);
  } else {
     promise();
  }
})

const startPromise = async () => await promise();

startPromise();


text:
Q: Binomial regression, continuous predictor. Glm() function in R I am trying to determine to what extent the age ( continuous variable) affect the outcome of the patient ( outcome - dead/recovered). So, I tried to build a model in R using glm(family = "binomial"). There are many other predictors, but my concern is about the variable "age" or how it is named in the output below "vecums". It's continuous variable, and as I understand the glm function, when using binomial regression, outputs log odds, so for variable age - the coefficient is equal to exp(2.309e-01) = 1.26.
> summary(fullModel)

Call:
glm(formula = Izn ~ ., family = "binomial", data = myData14)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-2.00942  -0.20697  -0.01299   0.00155   2.62596

Coefficients: (1 not defined because of singularities)
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -1.868e+01  4.508e+00  -4.144 3.41e-05 ***
DZ           9.712e-01  7.510e-01   1.293 0.195917
Vecums       2.309e-01  6.039e-02   3.824 0.000131 ***

So, if reference level for the response variable is recovered, then there are 1.26 people aged y+1 that have died per every y aged person. Somebody told me that that's not a correct way to interpret the coefficient, because the age variable is not linearly related to the outcome. So, I tried to cut data into several age groups, but in that case the coefficients were not significant, most probably due to the data size (300 patients). How precise is the coefficient 1.26 in case, I am not cutting age into groups? How to correctly interpret it?


text:
Q: How can I save a bitmap as a png in vc++ without using CImage I am a beginner in vc++. I am trying to convert an html file to image and save it as png, in vc++. Now I converted the html into bitmap and save using save function of CImage. I want to run this application in windows 2008. It works properly when run the application manually. I need to run it through a schedule task. But when the application runs through schedule task the image is not created.
How can I overcome this problem?
This is my code
BOOL CCreateHtml::CreateImage(IHTMLDocument2 *pDoc,LPCTSTR szDestFilename,CSize srcSize){
IHTMLDocument3* pDocument3 = NULL;
IHTMLDocument2* pDocument  = NULL;
IHTMLElement2* pElement2   = NULL;
IHTMLElement* pElement     = NULL;
IViewObject2* pViewObject  = NULL;
IDispatch* pDispatch       = NULL;
IViewObject* pViewObj = NULL;

HRESULT hr;

long bodyHeight;
long bodyWidth;
long rootHeight;
long rootWidth;
long height;
long width;
CImage img;
    if(FAILED(m_pBrowser->get_Document(&pDispatch)))
    return FALSE;
if(FAILED(pDispatch->QueryInterface(IID_IHTMLDocument2,(void**)&pDocument)))
    return FALSE;
if(FAILED(pDocument->get_body(&pElement)))
    return FALSE;
if(FAILED(pElement->QueryInterface(IID_IHTMLElement2,(void**)&pElement2)))
    return FALSE;
if(FAILED(pElement2->get_scrollHeight(&bodyHeight)))
    return FALSE;
if(FAILED(pElement2->get_scrollWidth(&bodyWidth)))
    return FALSE;
if(FAILED(pDispatch->QueryInterface(IID_IHTMLDocument3,(void**)&pDocument3)))
    return FALSE;
if(FAILED(pDocument3->get_documentElement(&pElement)))
    return FALSE;
if(FAILED(pElement->QueryInterface(IID_IHTMLElement2,(void**)&pElement2)))
    return FALSE;
if(FAILED(pElement2->get_scrollHeight(&rootHeight)))
    return FALSE;
if(FAILED(pElement2->get_scrollWidth(&rootWidth)))
    return FALSE;

HBITMAP m_hBmp;
width = bodyWidth;
height = rootHeight > bodyHeight ? rootHeight : bodyHeight;

if(width > 2000)
    width = 2000;
if(height > 2000)
    height = 2000;

MoveWindow(0,0,width,height,TRUE);
::MoveWindow(m_hwndWebBrowser,0,0,width,height,TRUE);

if(FAILED(m_pBrowser->QueryInterface(IID_IViewObject2,(void**)&pViewObject)))
    return FALSE;

CDC *cdcMain = GetDC();
HDC hdcMain = *cdcMain;
HDC hdcMem = CreateCompatibleDC(hdcMain);
m_hBmp = CreateCompatibleBitmap(hdcMain,width,height);
SelectObject(hdcMem,m_hBmp);

RECTL rcBounds = { 0, 0, width, height };

hr = pViewObject->Draw(DVASPECT_CONTENT, -1, NULL, NULL,hdcMain,hdcMem, &rcBounds, NULL, NULL, 0);

img.Attach(m_hBmp);
if(!hr ==img.Save(szDestFilename))
    return FALSE;
img.Detach();
img.Destroy();

pViewObject->Release();
return TRUE;

}

A: You're not gonna like the answer but there's is no build-in support for PNG images, you'll need to use an external library like pnglib
Good luck!


text:
Q: Posting file objects: illegal invocation I'd like to post multiple images objects to testphp.php. but the console prints errors says illegal invocation.
I have tried:

<input multiple type="file" id="myFile" size="50">

submit


text:
Q: Does medic grenade hurt my teammates? I have been playing a medic for a couple of games and I like there P-12 Poison Grenade/U-23 Radiation Grenade, but I have managed to kill my self once or twice by running in to my own grenades deadly smoke, this results in -10 for committing suicide.
I have yet to kill anyone from my own team(as far as I know) have i just been lucky or does teammates not take damage from my grenade?
And if they can die from my grenade do I get a penalty of some kind for killing my own teammates?

A: If friendly fire is disabled, all AoE effects only hurt you and the opponents, this includes P12 Grenades. The only way to hurt your teammates with FF off would be to become commander and throw buildings on their heads, otherwise they are completely safe from you.
With FF enabled, you should be able to kill anyone including teammates with P12s but i haven't tried that yet.


text:
Q: Bad request for field slot, SQLite - Android I have a table with 6 columns in it, I'm trying to fetch all rows from only 3 of the columns and store it in an array to use it. My query looks like this:
public Cursor fetchInfo(long rowId) throws SQLException
    {
        Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {"_id", "xCoord", "yCoord", "color"}, "_id" + "=" + rowId, null, null, null, null, null);

        if(mCursor != null)
        {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

then I'm calling it like so:
private void getInfo()
    {
        Cursor mCursor = mDbHelper.fetchInfo(mRowId);
        x = new float[mCursor.getCount()];
        y = new float[mCursor.getCount()];
        color = new int[mCursor.getCount()];

        if(mCursor.moveToFirst())
        {
            for(int i = 0; i < mCursor.getCount(); i++)
            {
                x[i] = mCursor.getFloat(3);
                y[i] = mCursor.getFloat(4); //Line 76, this is where the error is occurs.
                color[i] = mCursor.getInt(5);
            }
        }
        mCursor.close();
    }

However, when I try to run this, I get an error saying:
12-19 15:40:36.903: E/CursorWindow(276): Bad request for field slot 0,4. numRows = 1, numColumns = 4
12-19 15:40:36.903: D/AndroidRuntime(276): Shutting down VM
12-19 15:40:36.912: W/dalvikvm(276): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
12-19 15:40:36.922: E/AndroidRuntime(276): FATAL EXCEPTION: main
12-19 15:40:36.922: E/AndroidRuntime(276): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.x17.projects.strikezone/com.x17.projects.strikezone.SavedEntries}: java.lang.IllegalStateException: get field slot from row 0 col 4 failed
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.os.Looper.loop(Looper.java:123)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.app.ActivityThread.main(ActivityThread.java:4627)
12-19 15:40:36.922: E/AndroidRuntime(276):  at java.lang.reflect.Method.invokeNative(Native Method)
12-19 15:40:36.922: E/AndroidRuntime(276):  at java.lang.reflect.Method.invoke(Method.java:521)
12-19 15:40:36.922: E/AndroidRuntime(276):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-19 15:40:36.922: E/AndroidRuntime(276):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-19 15:40:36.922: E/AndroidRuntime(276):  at dalvik.system.NativeStart.main(Native Method)
12-19 15:40:36.922: E/AndroidRuntime(276): Caused by: java.lang.IllegalStateException: get field slot from row 0 col 4 failed
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.database.CursorWindow.getDouble_native(Native Method)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.database.CursorWindow.getFloat(CursorWindow.java:451)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.database.AbstractWindowedCursor.getFloat(AbstractWindowedCursor.java:123)
12-19 15:40:36.922: E/AndroidRuntime(276):  at com.x17.projects.strikezone.SavedEntries.getInfo(SavedEntries.java:76)
12-19 15:40:36.922: E/AndroidRuntime(276):  at com.x17.projects.strikezone.SavedEntries.onCreate(SavedEntries.java:46)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-19 15:40:36.922: E/AndroidRuntime(276):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
12-19 15:40:36.922: E/AndroidRuntime(276):  ... 11 more

I am new to databases, so I'm not sure how to fix this. I've tried some different ways to fix this but with no success. What am I doing wrong here? Should I be doing this differently?

A: In your query inside the fetchInfo() method you are getting 4 columns from your DB Table.
As the documentation states getFloat(int index) this method expects as index:

index - the zero-based index of the target column.

So you should use indexes as follows:
0 - for _id
1 - for xCoord
2 - for yCoord
3 - for color


text:
Q: after upgrading to Lubuntu 17.10 screen became black for 3/4 of surface I'm a long term user of Lubuntu and in the last years I've always found here tons of answers to my questions, but today I'm not able to solve my trouble.
After upgrading from Lubuntu 17.04 to 17.10 from a usb live (that was working properly), the first reboot came to an almost full black screen. Screen was black from left side to aprox 3/4 of the wide, I could see only a column on the right side of the monitor, showing the power button.
My computer is an old Asus eee pc 1005 with 2 gb ram that works as an amazing donkey. here a screen shot of system informations
I though this could come by some bugs in upgrading, so I've downloaded the new lubuntu 17.10 iso and I've installed it erasing previous release. After rebooting, I had the same problem.
I've followed instruction to enter the Grub and add nomodeset. This did not fix the issue.
Now I'm running a Linux Lite release (that is ok) but I miss my best friend Lubuntu!! If you have some idea on how I can try it again, please let me know!
Thank you
Giulio

A: It's a problem with Intel drivers in 4.13 kernel, workaround is to downgrade to 4.12 until a fix is released. Having same issue on EEE PC 901.
For more information view these bug reports (and maybe subscribe to them for updates):
https://bugs.freedesktop.org/show_bug.cgi?id=102929
https://bugs.launchpad.net/linux/+bug/1724639
There is a claim that one linked patch fixes the problem, now we wait until it gets pushed upstream.
If for some reason you have trouble downgrading comment and I'll try to help with that too. Two more tips:

*

*Update: New workaround, I haven't tested yet is to use GRUB_GFXPAYLOAD_LINUX=text

*The affected area is the same as the GRUB screen size, reducing it will reduce disabled area:

sudo nano /etc/default/grub
sudo update-grub

*Use recovery mode meanwhile if you don't already. But that will reduce screen resolution.

A: Workaround: Suspend(one of the possible options behind the power button in right upper corner) and awake again, display will work.


text:
Q: LC comparator based oscillator I am trying to build a LC oscillator based on LM393 open-collector comparator, but am having some difficulties. This is the current circuit:

I was expecting to get a nice square wave with one frequency like this:

But insted I got out something like this:

This is just an approximation, but the thing is it contains two different frequencies of oscillations.
My question is, how can I design a square wave oscillator so it will produce only one expected frequency of oscillations? What am I doing wrong here?
Thanks in advance!

A: First a comment.
Please label components in a circuit diagram with unique letters/numbers - not just values. Make them easy to read by rotating labels in the same direction if possible. It gets very confusing when describing a circuit by values alone.
I suspect that the waveform your circuit generates is by accident rather than design. You have two types of oscillator in your circuit.
(1) The relaxation (RC) oscillator.
The first (dominant) circuit is a relaxation RC oscillator controlled by the R4,47k and C2,10uF capacitor. If you remove the LC circuit (and its 10uF capacitor) the circuit will oscillate just fine at a low frequency.

2 A damped LC oscillator.
Looking at the waveform it should be obvious that the higher frequency (LC) oscillation is coming at the end of the low frequency pulse, i.e. its trailing edge. This is due to a small amount of feedback through R3, 100k resistor causing a small change in voltage between R1 and R2. This small step voltage is just enough to cause the LC tank circuit to oscillate for a few cycles and then die out (damped oscillation). So we get this. The first few oscillations are large enough to switch the comparator but because the phase change of the feedback is wrong the oscillation is not maintained and it dies out.

Oscillator circuits must satisfy two conditions known as Barkhausen conditions:

*

*The first condition is that the magnitude of the loop gain (Aβ) must be unity. This means the product of gain of amplifier 'A' and the gain of feedback network 'β' has to be unity.

*The second condition is that the phase shift around the loop must be 360° or 0°. This means, the phase shift through the amplifier and feedback network has to be 360° or 0°.
As a suggestion (I haven't built this so no guarantees) you could try this configuration based upon the op amp (dual supply) version of the LC oscillator circuit re-configured for a single supply. R1,R2 divide the supply to give a mid-way voltage. C1 decouples this voltage. At least it should point you in the right direction.
)


text:
Q: jQuery openmenu on keypress I created a jQuery script which would you require to press numpad0 and it would open up a menu. Pasting jQuery('.panel_toggle').trigger('click'); works and brings up the menu yet having it in a function doesn't work. Also I must note that the console registers me pressing numpad0 so that works fine to.
jQuery(document).ready(function() {
   jQuery(".panel_toggle").toggle(function() {
      jQuery('#panel_stats').stop().animate({'height':'415px'},500)
    },function() {
      jQuery('#panel_stats').stop().animate({'height':'0px'},500)
    });

   jQuery('body, html').live('keypress', openMenu)
});

function openMenu(e){
   console.log(e.keyCode)
   if(e.keyCode == '96')
   {
      e.preventDefault()
      jQuery('.panel_toggle').trigger('click');
    }
}

Anyhow I'm very confused.


text:
Q: He prefers hot weather like.... "in the south - Why are there two prepositions? I just joined after a few years of coming to your boards for advice as I need help with a specific sentence.
"He likes warm weather LIKE IN SPAIN / LIKE IN THE SOUTH"
Is "Like" being used here as a preposition? If so, how is the prep "in" being used? I can see it is forming a noun but can't explain it.
Thanks! I am looking forward to being an active member of the site.


text:
Q: Textbox regex validation is not working in uwp This is an example of custom regex validation for numbers only that is provided in official doc of Windows Community Toolkit of UWP here TextBox Regex extensions in toolkit.
<StackPanel Margin="10,0,10,0">
    <TextBox Name="PhoneNumberValidator"
             extensions:TextBoxRegex.Regex="^\s*\+?\s*([0-9][\s-]*){9,}$"
             Header="Text box with Regex extension for phone number, validation occurs on TextChanged"
             HeaderTemplate="{StaticResource HeaderTemplate}"
             Style="{StaticResource TextBoxRegexStyle}" />
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="Is Valid: " />
        <TextBlock Text="{Binding (extensions:TextBoxRegex.IsValid), ElementName=PhoneNumberValidator, Converter={StaticResource StringFormatConverter}}" />
    </StackPanel>

</StackPanel>

It works but if i change the regex and use a custom regex /^(?!\s*$).+/ for NotNullOrEmpty validation then it doesn't work. mean ext:TextBoxRegex.IsValid always returns false. Why ?

A: I tested the regular expression you provided in the WindowsCommunityToolkit Sample App:
<TextBox extensions:TextBoxRegex.Regex="(?!^$)([^\s])"
         .../>

It works fine, that is, after entering text, it shows the result as True.
Please note that the regular expression itself does not contain the first and last /, it is a syntax that indicates that the internal is a regular expression. When entering the relevant regular expression in XML, you only need to enter the content.
Thanks.


text:
Q: On the hamiltonicity of the bipartite graph? Definition
A hamiltonian cycle is a cycle that visits each vertex exactly once. A graph that contains a hamiltonian cycle is called a hamiltonian graph.
Background
Barnette's conjecture is a well known conjecture which deals with  the hamiltonicity of 3-regular bipartite.
Question It appears that there  is no conjecture that deals with the hamiltonicity of $d$-regular bipartite graphs when $d\geq 4$, my question is
Are all the connected 4-regular bipartite graphs are Hamiltonian? (or $d$-regular where $d\geq 4$)?
If not, is there any work that deals with the  hamiltonicity  of the connected $ d$-regular bipartite graphs for some $d\geq 4$. If yes, could you please point me to some references.
Any idea (or reference) will be useful!

A: The Hamiltonian cycle problem (HCP) is NP-complete in the class of $2$-connected bipartite $d$-regular graphs for each $d \ge 3$.
Proof. It is known (see Akiyama, Nishizeki, Saito, NP-Completeness of the Hamiltonian Cycle Problem for Bipartite Graphs) that HCP is NP-complete in the class of $3$-connected bipartite cubic graphs (and therefore is NP-complete in the class of $2$-connected bipartite cubic graphs). And it is clear that HCP is in NP for any graph class. Let's show a polynomial reduction of HCP in the class of $2$-connected bipartite $d$-regular graphs to HCP in the class of $2$-connected bipartite $(d+1)$-regular graphs for $d \ge 3$.
Let $G$ be a $2$-connected bipartite $d$-regular graph. Let $G_1$ and $G_2$ be two copies of $G$. Now for each vertex $v$ of $G$ we take a copy $X_v$ of complete bipartite graph $K_{d+1, d+1}$, remove an edge between vertices $u_1$ and $u_2$ and then add edges $\{\,u_1, v_1\,\}$ and $\{\,u_2, v_2\,\}$, where $v_1$ and $v_2$ are copies of $v$ in $G_1$ and $G_2$ correspondingly. It is easy to see that constructed graph $H$ is bipartite and $(d + 1)$-regular. Graph $H$ is Hamiltonian if and only if $G$ is Hamiltonian.
Let $C$ be a Hamiltonian cycle in graph $G$. Then we replace each vertex $v$ with $v_1P_vv_2$ where $P_v$ is a Hamiltonian $(u_1, u_2)$-path in $X_v$. So we get a Hamiltonian cycle in $H$.
Let $C$ be a Hamiltonian cycle in graph $H$. Then for each $v$ all vertices of $X_v$ take consequtive $2d + 2$ positions between $v_1$ and $v_2$. If we replace each such part of cycle with $v$ we get a Hamiltonian cycle in $G$. $\square$
Therefore the answer to your question is no, no and again no, for each $d \ge 3$ there are infinitely many connected bipartite $d$-regular non-Hamiltonian graphs. However almost all regular bipartite graphs are Hamiltonian. Also non-Hamiltonian such graphs are not too small. Particularly it is conjectured by Häggkvist that every $2$-connected $k$-regular bipartite graph on at most $6k$ vertices is Hamiltonian. And it is proved that every $2$-connected $k$-regular bipartite graph on at most $6k - 38$ vertices is Hamiltonian.


text:
Q: Php contact form path or? I am using Joomla 3 and i creat a simple php form and it is working on a simple html page but when i tried to use it with joomla didnt do anything
I am using it on FTP server not local both cases
i tried with <?php include(' component.php'); ?> but same i have no idea what to do i am not pro with php , joomla please help
component.php file

defined('_JEXEC') or die;

$errors = '';
$myemail = 'hety@gmail.com';//<---- email address .
if(empty($_POST['name'])  ||
   empty($_POST['email']) ||
   empty($_POST['text']))
{
    $errors .= "\n Error: all fields are required";
}

$name = $_POST['name'];
$email_address = $_POST['email'];
$password = $_POST['text'];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
    $to = $myemail;
    $email_subject = "Contact form submission: $name";
    $email_body = "You have received a new message. /n ".
    " Here are the details:\n Name: $name \n Email: $email_address \n Text: $text \n";

    $headers = "From: $myemail\n";
    $headers .= "Reply-To: $email_address";

    mail($to,$email_subject,$email_body,$headers);
    //redirect to the 'thank you' page
    header('Location: index.php');
}
?>
<!DOCTYPE html>

    <title>Contact form handler</title>

<?php
echo nl2br($errors);
?>

index.php file
<form method="POST" name="contactform" action="templates/oniongraphicscomponent.php">

 Character Name

<input class="form-field" type="text" name="name" required/>
<input class="form-field"  type="text" name="text" required />

 Email

<input class="form-field" type="text" name="email"required />

<input class="submit" type="submit" value="Submit" />

</form>

A: i have different file called component and <?php include('component.php'); that file into index.php where my form is
full path is 'htdocs/templates/mytemplate/component.php'


text:
Q: what is "multidimensinal data" in business intelligence? I'm try to understand what the BI and OLAP is.
from wikipedia, says:

OLAP tools enable users to analyze multidimensional data interactively from multiple perspectives

After a lots of Google, here is my understand:
"multidimensianl data" means data in a multidimention model, it's diff to rational data model which store data in a "table" or tables, table can be think as a 2D data model, multidimention data model ussually use 3D structure like a "cube" to store data.

A: "Multidimensional data" means each record has keys in it.
e.g. A customer in retail shop has birthday, gender, address, shopping list, etc.
The way multidimensional data is indexed and processed is little different than conventional rdbms techniques.
Typically BI and OLAP tools provide optimized way to query multidimensional data.
e.g. customer residing in 2km vicinity(derived from address) who bought milk at-least 5 times in last month.

A: I'm not familiar with OLAP but "multidimensional data" usually means you're looking at some data which has n properties.
E.g. a person could have a birthdate, a name, a home town, a job...
Or a road could have a length, some geo locations, ...


text:
Q: Next.js 10 + i18n + (different) page names I'm really happy to see i18n going into Next.js core with Next.js 10.
However, I'm wondering if and how we can use i18n to translate page names (urls?).
For example, let's say I have a contact page under mypage.de/kontakt (for default German language).
With Next.js 10 configured, Next.js automatically creates the route mypage.de/en/kontakt, which is fine so far, but how can we translate the page name as well? Instead of /kontakt, I'd like to have /contact.
Is or will this be possible with Next.js 10 out of the box?
Does it require additional libraries? What will be the right way to do this in 2021?
Thank you very much!

A: Imagine you have only one file named src/pages/contact.tsx. There are 2 scenarios.

*

*User is hitting "foobar/contact" URL => you can use i18n redirection to redirect to "foobar/de/contact". Then client side you can use the browser API to change the URL (see related question).

*User is hitting "foobar/de/kontact" => since your page is named "contact" and not "kontact", that's a problem, because this page doesn't exist. You'll hit a 404 as is. Here you need a rewrite as stated by @enoch comment on your question. You'll want to rewrite "kontact", "contactez-nous", "contactar"... to "contact" route.

Hopefully, Next.js rewrite feature is very powerful, and allow some slight decoupling between the actual route path and the URL seen by the user. And you can also alter the URL directly in JS.
A third way is to use URL rewriting server-side, but for that at the time of writing (Next 11) it can only be handled ad the host level, so it depends where you upload the app.


text:
Q: How to estimate population mean from a single sample Let's say I have an array of values drawn from a normal distribution with mean 50 and standard deviation 10. Using python:
d = np.random.normal(50,10,1000)

I take a single random sample of size n = 10 from this distribution:
s = np.random.choice(d, 10)

What process do I go through to get the best estimate of the population mean from the sample, and an estimation of the margin of error?
Obviously I know the population mean and standard deviation in this case, but let's pretend I don't.
I could also take many samples and compute the sampling distribution of the mean, but let's say I can't do that either.
So I just have this single sample. What process do I go through and can I estimate how often my estimate of the population mean will be wrong?

A: I'm assuming infinite population size.
The best estimate of the population mean is the sample mean, $\bar{x}$.
The best estimate of the population standard deviation is the sample standard deviation, $s = \sqrt{\frac{1}{n-1} \sum_{i=1}^n (x_i - \overline{x})^2}$
Since the sample size is less than 30 (10 in this case) and the population standard deviation is unknown, I would prefer to use the T-distribution to develop an interval.
$\bar{x} \pm t(\frac{s}{\sqrt{n}})$
where $t$ is the critical value from the $t_{n-1}$ distribution.  In your case with n=10 and a desired confidence level of 95%, $t_{9}=1.833$.
More details can be found in this Example.

A: Though Underminer gives a perfectly good answer, I thought I would take the time to provide a Bayesian estimate.
In your problem, you don't explicitly say you have no reason to believe the data are normal, only that the mean and the variance are unknown. The likelihood function is thus
$$ y \sim \mathcal{N}(\mu, \sigma^2)$$
Here, $\mu, \sigma$ must be estimated.  I'll place an uninformative prior on both of these parameters
$$ p(\mu, \sigma^2) \propto (\sigma^2)^{-1} \>.$$
In Bayesian Data Analysis 3 (p.g. 64) Gelman goes through this example and derives an analytic posterior density. The marginal posterior for the variance is
$$\sigma^{2} | y \sim \operatorname{Inv}-\chi^{2}\left(n-1, s^{2}\right)$$
with
$$ s^{2}=\frac{1}{n-1} \sum_{i=1}^{n}\left(y_{i}-\overline{y}\right)^{2}$$
while the marginal posterior for the mean conditioned on the variance and the data is
$$\mu | \sigma^{2}, y \sim \mathrm{N}\left(\overline{y}, \sigma^{2} / n\right)$$
We can sample from these densities very easily with python and compute credible intervals.
from scipy.stats import norm, chi2

import numpy as np
import matplotlib.pyplot as plt

population = norm(loc = 50, scale = 10)

n = 10
samp = population.rvs(n)

ybar = samp.mean()
s = samp.var(ddof = 1)

var_posterior = (n-1)*s/chi2(df =n-1).rvs(100_000)
mu_posterior = norm(loc = ybar, scale = np.sqrt(var_postrior/n)).rvs()

#Now for credible intevals
print(np.percentile(mu_posterior, [2.5, 97.5]))
print(np.percentile(np.sqrt(var_posterior), [2.5, 97.5]))

fig, ax = plt.subplots()
ax.hist(mu_posterior, bins = 25)

fig,ax = plt.subplots()
ax.hist(np.sqrt(var_posterior), bins = 25)
plt.show()

The benefit from this method is that you get uncertainty estimates of the variance for cheap, whereas Underminer's method only gives you uncertainty estimates for the mean.
It actually turns out that the posterior is the student-t density (go figure), so all this is more or less equivalent to Underminer's approach.  However, that is only because we assumed we knew nothing about the mean and the variance before hand.  If we knew something about those parameters (for instance, that negative values are impossible, or that they were larger than some number) then we could do much more by means of MCMC.


text:
Q: Google DocumentAI; How to get the Bearer Token? I have been tasked with trying to use the Google DocumentAI service to extract table data from PDF files.  I am using Alteryx, but the principle would apply to PostMan or other apps where you format your own requests.
I have set up a Google Cloud Bucket, and loaded up my PDFs.  I have set up a project, and got a Service Account.
The documentation shows formatting a request, and has the Authorization header as "Authorization: Bearer gcloud auth application-default print-access-token".
Given that I have the credentials json file like this...
{
  "type": "service_account",
  "project_id": "my-proj",
  "private_key_id": "12345abc",
  "private_key": "-----BEGIN PRIVATE KEY-----\stuff\n-----END PRIVATE KEY-----\n",
  "client_email": "me@my-proj.iam.gserviceaccount.com",
  "client_id": "12345",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/me%40my-proj.iam.gserviceaccount.com"
}

... How do I get the bearer token?  I assume I will have to make some kind of call to the identity server, but it is not clear how to do this.


text:
Q: Filter out list of code snippets visible on the list view Following this link I have a set of code snippets.
But the snippet insertion has to be w.r.t the context, viz. if I do 'Insert Snippet' before declaring a class, it shouldn't show 'method declaration' snippet.
Also required is to filter snippets as per managed or unmanaged code.
In short I am looking for a mechanism as follows:
if <condition>
{
 modify list of snippets visible in the menu
}

Do we have such a mechanism or something similar? Ideas welcome.

A: I found a solution to my question. Hope it helps someone.
I followed the instructions on the links:
Video on Code Snippets &
Code Element
Got the snippet.xml file to contain the following:
<Code Language="Language"
    Kind="method decl">
        Code to insert
</Code>

Then called the expansionProvider.DisplayExpansionBrowser in the FilterView class (refer to the video):
string[] kind = new string[1];
kind[0] = "method decl";
return expansionProvider.DisplayExpansionBrowser(TextView,
                                                 snippets,
                                                 null, false, kind, false);

Thus the specific snippet will appear in 'method declaration' context. Thus other snippets can be done. The xml has to hold the context information.


text:
Q: React GET API getting data before api call This code is the code that receives and displays each list. I want to get a property from the listing data and put the value in the url. The value is well displayed as data.propertyType in the console. How can I get the property in each data and put it in the url?
class ListingPage extends React.Component {
constructor(props) {
    super(props);

    this.state = {
      id: props.params.id,
      listing: null,
    };

  }
  componentDidMount() {
    ListingAction.get(this.state.id, this.state.property);
  }
}

class ListingAction {
 get(listingId, property) {
    const listingFetch = data => {
      AppDispatcher.dispatch({
        actionType: Constants.LISTING_FETCH,
        data,

      });
      console.log(data);
      property.push(data.propertyType);
      console.log(property);
    };

    ListingService.get(listingId, property)
      .done(data => {
        listingFetch(data);

        console.log(data.propertyType);
        console.log(property);
      })
      .fail(data => {
        AppDispatcher.dispatch({
          actionType: Constants.LISTING_FETCH_FAILED,
        });
      });
  }
class ListingService {
  get(listingId, property) {
    return $.ajax({
      url: `/data/property/${listingId}?property=${property}`,
      data: { property },
      method: 'GET',
      cache: false,
    });
  }
}

}


text:
Q: SVN Losing history when importing trunk I was working in a branch of a project and made many changes to that branch on my local machine. I did not commit those changes to the repository.
Then, by mistake, I erased the .SVN folder in my project. Did I loose traces of all the changes I've made?
I can reimport that branch in SVN, but I will loose all of the history for that branch. Eventually, that branch will become the trunk. If I do so, the trunk will inly include the history since the branch was reimported.
Any way around my problem? Don't tell me "switch to GIT". This not an option for me.

A: Changes to uncommitted files are calculated on-the-fly thanks to the original files stored at .svn.
I suggest you merely check out a new working copy somewhere else and replace your files. With replace I mean:

*

*Delete all your code (i.e., all the files except the .svn folder) from the new working copy.

*Move all your files from the damaged working copy into the new one.
With delete and move I'm referring to good old file system operations, not Subversion commands or anything else. Since you use Windows you can drag files with the mouse in Windows explorer.


text:
Q: Formatting dates for Insert into MYSQL with Node.js I am inserting data into MYSQL from node.js using node-mysql. I can insert data correctly via a MYSQL stored procedure call in Node except that my dates are always inserting as 0000-00-00 00:00:00
The date strings I am trying to insert are in the format: dd/mm/yyyy hh:mm:ss
I'm assuming I need to correctly format my dates in Node.js to insert?
connection.query('CALL sp_InsertUpdateOffer(' + NetworkID + ',"' + data["Promotion ID"] + '",' + data["Advertiser ID"] + ',"' + DataCleanUp(data.Description) + '",null,"' + DataCleanUp(data.Categories) + '","' + DataCleanUp(data.Code) + '","' + DataCleanUp(data.Terms.substring(0, 1000)) + '","' + data.Starts + '","' + data.Ends + '","' + DataCleanUp(data["Deeplink Tracking"]) + '","' + DataCleanUp(data.Deeplink) + '","' + DataCleanUp(data.Advertiser) + '")', function (err, rows, fields) {
});

Thanks

A: you can re arrange your date format to 0000-00-00 00:00:00
If your date is in this format dd/mm/yyyy hh:mm:ss
do this to re arrange your date.
$date_select = "12/12/2016";
$newdate = explode("/",$date_select);
$final_date = $newdate[2]."-".$newdate[1]."-".$newdate[0];

now pass the $final_date to your insert query.


text:
Q: Possibilities of connecting to linux box console without network Having to manage a couple of remote dedicated servers, working with network related stuff can be quite stressful.
Is there any possible way I could connect to those boxes (possibly via third box) and not have to depend on their networking configuration at all?
Something like "xm console", but not xen related? Hope my question is clear enough to answer.

A: If your server has a serial port you can connect through it easily enough.  Let us assume the simplest case; 1 server and a cart pc or laptop.  Add an entry to your /etc/inittab file similar to:
s0:12345:respawn:/sbin/agetty 19200 ttyS0 vt100

That will tell the server to listen on ttyS0, the first serial port, for terminal like behavior.  Plug a cable from that port on the server to your laptop/cart.  Using a program such as minicom or the right options on screen connect to your local serial port.  Assuming you properly configured the speeds you should drop straight into a login prompt on your server.
For the more complicated case, many different servers, you can centralize the same basic approach.  Instead of a mobile cart or laptop, setup a specialized server that will be directly connected to all of your various devices.  This can be done with a boatload of serial ports, or something like a Digi console server.  From this console server you can then gain out-of-band access to any of your connected systems.  I would check out applications like Conserver when working in bulk.
I would recommend, at least, configuring the serial port on these systems even if you don't plan on using an enterprise wide management system.  You can't always trust that a box will have video, and at least with the serial port enabled you can work on a system that may not completely boot.
EDIT:  After sleeping on it I realized this method will not work for virtual machines.  Best case, using a serial connection you could drop into a shell on the VM host, but not any of the guests.  We leave this problem as an exercise for the reader.

A: Many server hardware vendors offer some kind of remote console, like IBM's RSA (System x) or Dell's DRAC (PowerEdge) and HP's iLO. This will still be over the network, and a good practice is to put that on a management VLAN that you otherwise don't mess with.
Newer server models might not actually have a serial port available to connect a serial console to (remote or otherwise), but there are USB adapters available.
And this is why data center hosting facilities have "hands and eyes" support :-).

A: Google for an IP KVM or KVM over IP. (KVM = Keyboard, Mouse, Video)

A: I'll throw my support in for "IP KVM's". I use the Dell 2161DS KVM (see http://www.dell.com/content/topics/global.aspx/power/en/ps3q02_avocent?c=us&l=en&cs=04
) at a couple of Customer sites and really like it (though the java client sucks... I wonder if anybody has done one of these w/ the RFB/VNC protocol as the output). This particular switch is nice because you can cascade addt'l modules off of it to control more servers. One Customer has about 80 servers spread over 2 of these switches, and physically walking into the data center was almost never necessary.
One thing you should think about in addition to such a beast is remotely controllable power. It can be in a UPS, or it can be a freestanding remote power switch (see http://www.blackbox.com/Store/Detail.aspx/Elite-Managed-Power-Controller-Horizontal-120-VAC-16-Outlet/PSH16-D20-120V
for an example), but you're going to find yourself in some situation with PC servers where, inevitably, you need to power-cycle the box.

A: Yep, what you want (I think) is a serial console server. A quick google throws up plenty of results as to how to achieve this.

A: Using serial port extenders like this one is a really easy way to communicate to devices with a console.  You can use telnet into the device and you are connected on the serial side.  They are really easy to install and configure.


text:
Q: Designing a Multi Language Site I am presently developing a trilingual website using wordpress, but am presently confused as to how I should complete the design. As the entire site should be editted through a single admin page, how should I create a new article and include that only for language A for example and not for language B? Or else should I develop 3 different wordpress sites for each language, and thereby have 3 different themes as well?
Any ideas on how this could be acocmplished

A: Check out plugins like http://wpml.org , they should do the trick. Works like a charm!

A: I am also developing multi language site in Wordpress and I am using Free plugin qTranslate.
You add languages you want and other settings under Admin >Settings > Languages and then when you edit Post/Page you switch between Languages same way as you switch between HTML and Visual by using Tabs.


text:
Q: Altium hierarchical design assigning net to power port/port I have a hierachical multichannel design and I´m having problems to set properly the project properties so that the following issue is removed.

As you can see one of the ports of the child sheet is connected to the Vm_GND power port net.
Once recompiled the schematics I have found that when alt+click over this net, the other Vm_GND port of other schematic sheets in the design do not highlight.
When importing this design to PCB the I_SNS- net is not connected to Vm_GND in the PCB of so this is a major issue because as you can see it should be.
These are my project options:

What am I doing wrong?

A: It looks like you're trying to use Kelvin connections so that your sense traces don't carry any current.  To do this best in Altium, use a "net tie" component.  It allows you to connect two nets together at a specific point on the PCB.  Google "Net tie" and Altium and you should be able to find what you need.


text:
Q: Does Passenger 3 support Rails 2.1? I would like to have the Passenger module updated on one of our webservers. Sadly, we have a legacy app running on that machine, which was build using Rails 2.1. Are there any problems to expect running Rails 2.1 on Passenger 3? Rails uses Rack since version 2.3, I think.
We currently use Passenger 2.2.11 (installed with apt-get on Debian).

A: I tried it myself, since there was no answer so far. Rails 2.1 works fine with Passenger 3.0.9.