text:
Q: ActivityInstrumentationTestCase2 - sendkeys I'm trying to test my application through ActivityInstrumentationTestCase2. I have a few clickables in my UI. I use sendKeys(KeyEvent.KEYCODE_DPAD_DOWN); sendKeys(KeyEvent.KEYCODE_DPAD_CENTER); etc to simulate keyevents on my UI.
The problem is is my app is kinda slow whereas the test case is relatively fast. So what's happening is that the keyevents sometimes click/navigate to the wrong UI element and that messes up the test case.
Is there any other way of simulating keyevents with a tiny bit of delay ? For now i'm using
Thread.sleep(500) to introduce a minor delay.
Is there a more elegant way of doing it other than using Thread.sleep() ?
Note: I am aware of Robotium and I'd appreciate it if the answers were related to the Android Test Framework. Thanks.

A: There is sleep method in robotium, so you can replace all your Thread.sleep with:
solo.sleep(long ms);

There is also another way, which UIAutomator uses, however I'm not sure, if it's safe and will not cause freezing of UI:
SystemClock.sleep(long ms);

You can also use wait methods, if you are sure that some view is going to appear. Take a look on robotium api, you will see what else can be useful for you.


text:
Q: Sencha Touch List Append New Results from Store Load I've got a simple List, which loads data from a JSON Store. I've got the paging solved server-side, so in order to get a new page I change the proxy of the store and set page parameter to +1(new page), load the store and the list shows just new results from the new page.
Is it possible to make the list append new results after the store load? So that when I load the store with new data I want the list to keep old data and add new ones.
If it's needed I can show it in code but it's pretty much self-describing.
Thanks.
//edit
Currently my store looks like this:
realio.stores.results = new Ext.data.Store({
    model: "realio.models.Results",
    proxy: {
        type: 'ajax',
        url: 'http://site.com/json_list2.php?a=l&zp=1&u='+settings["ulica"]+'&c0='+settings["cena0"]+'&c1='+settings["cena1"]+'&p0='+settings["plocha0"]+'0&p1='+settings["plocha1"]+'&cm20='+settings["cenam20"]+'&cm21='+settings["cenam21"]+'&pg=0&s=Datumu&t='+settings["typ"]+'&age='+settings["stari"]+'&pod='+settings["podlazi"]+'&lat='+settings["lat"]+'&lng='+settings["lng"]+'&pp='+settings["pp"]+'&tp0='+settings["typ0"]+'&tp1='+settings["typ1"],
        reader: {
            type: 'json',
            root: 'markers'
        }
    },
    sorters: [
        {
            property: 'id',
            direction: 'ASC'
        }
    ]
});

and my model like this
realio.models.Results = Ext.regModel("realio.models.Results", {
    fields: [
        {name: "titul", type: "string"},
        {name: "vlast", type: "string"},
        {name: "typb", type: "string"},
        ...
    ]
});

list:
xtype: 'list',
store: realio.stores.results,
flex: 1,
disableSelection: true,
scroll: 'vertical',
itemTpl: itemTemplate,
onItemDisclosure: function (record) {
    Ext.dispatch({
        controller: realio.controllers.detail,
        action: 'load',
        detail: record
    });
},
listeners: {
    'itemtap': function(t, i, it, e) {
        Ext.dispatch({
            controller: realio.controllers.detail,
            action: 'load',
            detail: t.store.getAt(i)
        });
     }
},
plugins: [
    {
        ptype: 'listpaging',
        autoPaging: false
    },
    {
        ptype: 'pullrefresh'
    }
]

I've got the paging solved server-side -> when i set &pg = x in proxy url, i go to the page x, so I don't know how I would get it to run with those store pages. Even if I tried setting stores pagesize to for example 2 it would show all results anyway so I thought it doesn't work...

A: From my experience I would do store.loadData(data,true); true to append the data to the data that is already in the list.

A: There is a plugin that ships with Sencha Touch 1.1 called ListPagingPlugin which lets you add a 'load more' button to the end of a list that'll fetch the next page and append the data. There's an example (also included) that you can find in /examples/pullrefresh (it's bundled with the pull to refresh plugin in a single example).
The example didn't work for me because I think Twitter changed their API so that if an invalid page parameter is sent it doesn't default to page 1 rather it tells you -some- parameter is invalid. In order to make the example work I had to edit line 44 of /examples/pullrefresh/src/TwitterProxy.js from page: operation.page to page: operation.page || 1
If you have any questions about the plugin specifically after you start using it we can cross that bridge when you get there =D

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get Symfony Bundle content into a website (existing template) I'm not that familar with Symfony and Twig yet. So, how do I solve this:
I've got a base App in Symfony, which has a frontend with static templates (a website).
Now, if I want to add a custom Bundle which should add some content into the main page (the App's default frontend), how do I do that?
The Bundle already is installed, but I don't know how to do it in best practice. Do I use a controller? But there will be rendered a view from this controller - that's confusing me. Or do I need global variables in Twig, create something like generators to add values to the variables? Or is there another way?
In short:
My Bundle should bring additional content into an existing App (website).
EDIT
The Bundle also has some own routes.

A: Maybe I got it:
I need to create a template inside the App, didn't set the template path to Bundle templates and just include the Bundle templates:
// App template in app/templates/website.html.twig
{% block content %}
    {% include '@Bundle/view/foobar.html.twig' %}
{% endblock %}

// Bundle template in Bundle/view/foobar.html.twig'
{{ form... }}
{{ something }}

The Bundle controller renders the variables into it's templates.
Is it best practice?


text:
Q: knife cookbook site search apache2 return error knife cookbook site search apache2

returned
ERROR: Chef::Exceptions::ContentLengthMismatch: Response body length 2175 does not match HTTP Content-Length header 621.

Chef: 11.12.8
Is this a bug?

A: It may be that there is still a bug.  There was a similar report that is reported to be fixed in 11.12.0.

*

*https://tickets.opscode.com/browse/CHEF-5041

*https://github.com/opscode/chef/pull/1329
Likely you should try the suggestions in this Jira:

*

*Try setting the 'no_lazy_load true' in your client.rb.

*Try setting the 's3_url_ttl' to something higher than the default on your server

If neither of these fix it, you likely need to open a request with Chef on Github providing more context.  It looks like the fix in CHEF-5041 was pretty closely related to a flaw in a particular proxy that was still true to the spec, simply not accounted for in the Chef code.  So your issue may be another edge case.


text:
Q: Angular5 RXJS recursive http requests I currently have this situation:
#Service My Service
private users = ['user1','user2'];

//Generate list of requests to join
private getHttpList(): any[] {
  let gets = new Array();
  for(let index in this.users)
      gets.push(this.http.get('https://api.github.com/users/' + this.users[index]))
  return gets;
}
...
getList(): Observable<any[]> {
    return forkJoin(this.getHttpList())
}

And in my component, I do the subscribe
this.MyService.getList().subscribe(results => {
    for(let res in results) {
       //...Do something here
       //..I wanna do the get in of https://api.github.com/users/{user}/starred
    }
})

Suppose that I just know that the "starred url" after the result of getList(), how to I can "synchronous" this part, or what's the correct form to do this?
**I try do it hardcoded --Result id wrong, because the "res" is a "interable"
this.MyService.getList().subscribe(results => {
        let url = 'https://api.github.com/users/';
        for(let res in results) {//This don't do the things "synchronous"
           this.http.get(url + res.login +'/starred').catch(err => {
               throw new Error(err.message);
           }).subscribe(starred_res => {
               //So we set the starred_list
               res.starred_list = starred_res
           })
        }
    })

Thanks...

A: As I understand you want to get starred list for every user.
The simplest way is to get all starred lists and match them with users result.
// Get users
this.MyService.getList().subscribe((results: any[]) => {

  const url = 'https://api.github.com/users/';

  // Create requests to get starred list for every user
  const starredRequests = results.map(
    res => this.http.get('https://api.github.com/users/' + res.login + '/starred')
  );

  // Wait when all starred requests done and map them with results array
  Observable.forkJoin(starredRequests).subscribe(starred => {

    results.forEach((res, index) => {
      res.starred_list = starred[index];
    });

    console.log(results);
  });

});


text:
Q: total variation distance between 2 distributions decreases? Say we have 2 probability distributions $\pi_0, \alpha_0$ on the same state space $S$ with some transition matrix $P$. Define $\pi_1 = \pi_0 \cdot P$, $\alpha_1 = \alpha_0 \cdot P$. The goal is to show that $$\vert\vert \pi_1 - \alpha_1\vert\vert_{TV} \leq \vert\vert \pi_0 - \alpha_0\vert\vert_{TV}$$
where $\vert\vert\cdot\vert\vert_{TV}$ denotes the total variation distance, which can be defined as $sup_{E \in S}\vert\pi(E)-\alpha(E)|$.
Here is my attempt:
$\vert\vert \pi_1 - \alpha_1\vert\vert_{TV} = \vert\vert \pi_0P - \alpha_0P\vert\vert_{TV} = sup_{E \in S}\vert(\pi_0P)(E)-(\alpha_0P)(E)|$
This is such a silly question, but how do I get that matrix $P$ out of there, and how do I use the fact that it's specifically a probability transition matrix (ie. all entries between $0$ and $1$) to reach the conclusion?

A: An equivalent definition of total variation distance is:
$$||x-y||_{TV} = \frac{1}{2} \sum_i |x_i-y_i|.$$
Therefore:
$$||\pi_1 - \alpha_1||_{TV} = ||(\pi_0-\alpha_0)P||_{TV} \leq \frac{1}{2} \sum_i \sum_j P_{j,i} | \pi_0(j) - \alpha_0(j)|.$$
After changing the order of summation we obtain:
$$||\pi_1 - \alpha_1||_{TV} \leq \frac{1}{2} \sum_j | \pi_0(j) - \alpha_0(j)| \sum_i P_{j,i}.$$
Since $P$ is stochastic this is equal to
$$\frac{1}{2} \sum_j | \pi_0(j) - \alpha_0(j)| = ||\pi_0 - \alpha_0||_{TV}.$$


text:
Q: Mapshaper simplify equivalent in GRASS I was shown the simplify function of https://mapshaper.org/, which removes unnecessary vertices in polygons. Now I'm looking for a similar function in QGIS and found GRASS generalisation. Since I'm not profound on generalisation algorithms and there are alot of them in GRASS generalisation could anybody tell me which algortihm I have to use to get an equal result?
What Mapshapers simplify does:
After you loaded a file you have a slider to simplify the polygon(s) The great part about is that it removes redundant vertices first and only after that starts to change the geometry. Additionaly the shared borders between polygons stay the same and you get no holes between them.


text:
Q: Ошибка при очистке таблицы QTableWidget Добавляю элементы в QTableWidget таким образом
while (a_query.next())
    {
        Login = a_query.value(rec.indexOf("Login")).toString();
        Password = a_query.value(rec.indexOf("Password")).toString();
        FIO = a_query.value(rec.indexOf("FIO")).toString();
        Dop_inf = a_query.value(rec.indexOf("Dop_inf")).toString();

        ui->tableWidget2->insertRow(ui->tableWidget2->rowCount());

        ui->tableWidget2->setItem(row_count,0,
                                new QTableWidgetItem(Login));
        ui->tableWidget2->setItem(row_count,1,
                                new QTableWidgetItem(Password));
        ui->tableWidget2->setItem(row_count,2,
                                new QTableWidgetItem(FIO));
        ui->tableWidget2->setItem(row_count,3,
                                new QTableWidgetItem(Dop_inf));
        row_count++;
    }

Но когда я делаю ui->tableWidget2->clear(); вылетает ошибка sigmentation fault
Что я делаю не так?

A: На QTableWidget не нужно грешить. Вот минимальный пример, и он работоспособен:
int main(int argc, char* argv[])
{
  QApplication app(argc, argv);

  QTableWidget table;
  table.setColumnCount(4);
  int row_count = 0;
  for (int i = 0; i < 10; ++i) {
    table.insertRow(table.rowCount());

    table.setItem(row_count,0, new QTableWidgetItem("Login"));
    table.setItem(row_count,1, new QTableWidgetItem("Password"));
    table.setItem(row_count,2, new QTableWidgetItem("FIO"));
    table.setItem(row_count,3, new QTableWidgetItem("Dop_inf"));
    row_count++;
  }

  QPushButton btn("Clear");
  QObject::connect(&btn, SIGNAL(clicked()), &table, SLOT(clear()));

  table.show();
  btn.show();
  return app.exec();
}

Вероятнее всего, где-то что-то вы удаляете более одного раза. Ищите ошибку с помощью отладчика.
P.S.: за загадочными именами Login, Password, FIO, Dop_inf кроются простые QString'и?


text:
Q: Can a point and a compact set in a Tychonoff space be separated by a continuous function into an arbitrary finite dimension Lie group? Given a topological space $X$ which is Tychonoff (i.e., completely regular and Hausdorff), we know that given a compact set $K\subseteq X$ and a point $p \in X$ with $p\not\in K$, we can construct a continuous function $f:X\to \mathbb{R}$ such that $f(K)=0$ and $f(\{p\})=1$.
If, instead of $\mathbb{R}$, I take an arbitrary finite dimensional Lie group $M$, can I still construct a continuous function $f':X\to M$ that will separate $K$ and $p$ for two different arbitrary points in $M$?
Is it enough to assume $X$ to be Tychonoff or do I need further or different assumptions about $X$? For example, is $X$ being metric sufficient?

A: As far as I remember, each Lie group $M$ is locally Euclidean, so there is a homeomorphic embedding $i:\Bbb R\to M$, which yields the required separating map $f'=i\circ f$.


text:
Q: Hiding a method from a VB class in a derived C# class I'm writing a set of unit tests for a large, complex class called ImageEditor from a piece of legacy code, where image processing and GUI functionality isn't strictly divided. One of the methods in the class, BaseImageChanged, seems to be concerned entirely with how images get displayed and should be disabled in my unit tests to avoid unnecessary complexity. The test project is in C#, and the original code is in VB; my idea was to create a Decorator for the class in C# and then hide the method behind an empty one that does nothing. However, when I try running the unit test, the VB code keeps referencing the old BaseImageChanged method as though the replacement didn't exist. Here's what I'm doing:
(VB class)
Public Class ImageEditor
  ...
  Public Sub BaseImageChanged()
  ...
  End Sub
  ...
End Class

(C# class)
class ImageEditorTestingClass : ImageEditor_Accessor
{
   public new void BaseImageChanged() {}
}

Is there a way to accomplish this sort of interoperability, or will I have to find another way?
EDIT: The compiler error turned out to be a problem with reflection. Also, overriding the method didn't work as long as the base class was an accessor of ImageEditor instead of the original ImageEditor class.(No compiler error, but the base method's behavior wasn't overridden.)

A: Do you have access to the VB code? if so mark it virtual (C# syntax); Then in the C# code override it with an empty body so that id does nothing.
You should (almost) never use 'new' to redeclare methods or properties. If some code is assuming it's the base class, even if you pass a derived one, the base methods will be called.
For better understanding read about late-binding and early-binding in .NET
Early and late binding
It seems @estanford accepted this answer due to my comment below
"Where you call BaseImageChanged try using reflection"

A: I don't know VB at all, but this sounds more like a case for a virtual method with an override than a method hiding.  The VB code is probably calling "this.BaseImageChanged()" somewhere, which wouldn't call your new method... right?

A: It looks like what's going on here is that

*

*You have a library written in VB.Net

*Your unit tests are written in C# and are using MSTest

*You're trying to derive from the generated accessor instead of the original class

In this case the only option you have is to use new.  The generated accessor class will not add virtual methods and hence if you want to provide an alternate method with the same name new is the only way to do so.


text:
Q: How to write simple generic build script for C++ project? I'm writing C++ project made of few files on Linux. The project have no subdirectories.
I wanted like to have some as simple as possible, generic build script.
By generic, I mean that I don't want to hardcode file names, so that when I put new .cpp file into project, I don't have to modify build script. It should find and compile all modyfied source files in current directory, and link object files into executable. Nothing more.
I don't care about tool you'll use, since I don't know any yet.
I don't want to learn a tool from basics to write something as simple as that. For now, I just need a code, I'll learn when I'll need something more fancy.
What I tryed
make:
a.out: %.o
    $(CXX) %.o

%.o: %.cpp
    $(CXX) -Wall -c %.cpp

with no success:
make: *** Brak reguł do zrobienia obiektu `%.o', wymaganego przez `a.out'. Stop.

my translation of this message:
make: *** No rules to make object `%.o', required by `a.out'. Stop.

Before someone will ask, I'll answer: yes, my makefile is indented with 1 tab, not with spaces.
make -d prints out 664 lines, so I won't paste it here.
scons:
Program("main.cpp")

It's copyed from some StackOverflow answer, but it is definietly intended to build a executable from one source file, because I get linker errors when I want use it.
I ended us using bash:
g++ -Wall *.cpp

Simple. Does the job well... for now. I don't think it's elegant and I know it's probably inefficent, because it recompiles everything, even unmodyfied files.

A: I guess that you have a directory full of single-source C++ programs (e.g. each program has one single C++ source file) named .cpp (e.g. foo.cpp & bar.cpp), each independently compiled to an executable (e.g. foo & bar). You might try the following (untested) Makefile for GNU make.
CXX= g++
CXXFLAGS= -Wall -Wextra -g -O
RM= rm -vf

SOURCES= $(wildcard *.cpp)
BINARIES= $(patsubst %.cpp, %, $(SOURCES))

.PHONY: all clean

all: $(BINARIES)

clean:
     $(RM) *~ *.o $(BINARIES)

Read the documentation of GNU make and try make -p to find the builtin rules. See also these two examples of Makefile-s: this & that
If on the contrary you want one single executable myprogram from all the *.cpp files (like foo.cpp & bar.cpp etc....), you still can use $(wildcard *.cpp) in your Makefile (and you'll better not name a.out your executable, but something more meaningful), something like (in addition of common stuff like CXXFLAGS= above):
SOURCES= $(wildcard *.cpp)
OBJECTS= $(patsubst %.cpp, %.o, $(SOURCES))
all: myprogram
myprogram: $(OBJECTS)
    $(LINK.cc) $^ -o $@ $(LIBES)

In all cases, using $(wildcard *.cpp) is enough to have a Makefile generic enough on the list of sources. You may want to generate autodependencies (using gcc -M things, to some of your header files), see this.
Notice that you might have some C++ source or header files generated by some other means (e.g. your own awk or python script, or a _timestamp.c file generated with date, or some C++ files produced by a code generator like GNU bison or gperf, etc, etc...). Then you need to add specific rules into your Makefile.
So in practice, I don't believe in fully generic build files, but I am trying to show you that a Makefile can be almost generic and short. At some time you'll adapt it to your particular needs.

A: SRC := $(wildcard src/*.c)
DEP := $(SRC:src/%.c=lib/%.d)
OBJ := $(SRC:src/%.c=lib/%.o)
CFLAGS := -Wall -Wextra -O2 -MMD

# Executable
lib/mines: lib/assets.o $(OBJ)
    ${CC} $^ -o $@

# Object files
lib/%.o:: src/%.c
    ${CC} -c $< -o $@ ${CFLAGS}

# Dependencies
# http://make.mad-scientist.net/papers/advanced-auto-dependency-generation/
-include $(DEP)

.PHONY: clean
clean:
    rm lib/*


text:
Q: show object in gcloud app engine console.log When using console.log in a node app deploy on app engine, if i console.log an object, it's all written line by line.
I would like to know if it's possible to have it logged in a clean way (cf picture)
this is the result of console.log('connection: ', connection);

Idealy i would like to have my object connection appear like that :

I'm probably missing something there, if anyone can help me clear that it would be awesome ! thanks

A: To log objects as one entry in stackdriver, I use the client library.[1]
Using[1] this is how my app.js looks:
'use strict';

const express = require('express');
const {Logging} = require('@google-cloud/logging');
const app = express();
const logging = new Logging();
const log = logging.log('projects/[PROJECT-ID/logs/[ANY-LOG-NAME]');
const resource = {type: 'gae_app',
                  labels: {
                           'project_id': '[PROJECT-ID]',
                           'module_id': '[SERVICE-NAME]',
                           'version_id': '[ANY-VERSION-ID]',
                           'zone': '[CURRENT-APPENGINE-REGION]'
                  }
                 };
const entry = log.entry({resource},"Plain message one");
let dict1 = {"First name": "Jhon",
             "Last name": "Smith",
             "Age":32,
             "Gender": "Male" };

const secondentry = log.entry({resource},{dict1});

app.get('/', (req, res) => {
  console.log('Using logging client library...');
  log.write([entry,secondentry]);
  res.status(200).send('Printing some messages to the console').end();
});

This is my package.json:
{
  "name": "node101",
  "engines": {
  "node": ">=8.0.0"
},
  "scripts": {
  "start": "node app.js",
  "test": "mocha --exit test/*.test.js"
},
 "dependencies": {
 "express": "^4.16.3",
 "@google-cloud/logging": "^7.3.0"
},
 "devDependencies": {
 "mocha": "^7.0.0",
 "supertest": "^4.0.2"
}

}
It is important to configure properly the resource variable, otherwise your log will not appear.
I have used[2][3] to configure the resource variable, you can look at it for more information about other resources.
I deploy using the --version flag; the value of the flag is equal to the one given resource variable in app.js
gcloud app deploy --version='[ANY-VERSION_ID]'

[1] https://cloud.google.com/logging/docs/api/tasks/creating-logs#writing_log_entries
[2] https://cloud.google.com/monitoring/api/resources#tag_gae_app
[3] https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource


text:
Q: What is the `patchShebangs` command in Nix build expressions? Came across the patchShebangs command while looking at packages in the Nixpkgs repo, and saw it used in various phases of the standard environment's generic builder, but not sure what it is for or why it is needed in the first place.

A: In short: shell scripts used during a Nix build won't work out of the box because Nix clears the environment, and so the interpreter directive (shebang), on the first line of the script determining the program to use to evaluate the script body, will not find it. patchShebangs looks up the interpreter in the Nix store, and amends the script shebang.

0. Introduction
patchShebangs is indirectly mentioned in the Nixpkgs manual when describing the phases of the generic builder of the Nixpkgs standard environment, stating that the fixup phase at one point

rewrites the interpreter paths of shell scripts to paths found in PATH. E.g., /usr/bin/perl will be rewritten to /nix/store/some-perl/bin/perl found in PATH.
->

It is important to note that (paraphrasing @jonringer's comment), "the patchShebangs command is only available during the build if you source the $stdenv/setup setup hook" (more on that below) "provided by stdenv's (the Nixpkgs standard environment's) default builder (you get this by default when using stdenv.mkDerivation), which is why the starting point of almost all nix expressions is import <nixpkgs> {}, stdenv.mkDerivation, or something similar."
1. Where is patchShebangs defined
The file patch-shebangs.sh in the Nixpkgs repo (also documented at 6.7.4. patch-shebangs.sh) defines the patchShebangs function, which in turn is used to implement patchShebangsAuto, the setup hook that is registered to run during the fixup phase.
2. Why are shebang rewrites needed when building Nix packages?
According to the comment at the top of patch-shebangs.sh:
# This setup hook causes the fixup phase to rewrite all script
# interpreter file names (`#!  /path') to paths found in $PATH.  E.g.,
# /bin/sh will be rewritten to /nix/store/<hash>-some-bash/bin/sh.
# /usr/bin/env gets special treatment so that ".../bin/env python" is
# rewritten to /nix/store/<hash>/bin/python.  Interpreters that are
# already in the store are left untouched.
# A script file must be marked as executable, otherwise it will not be
# considered.

IMPORTANT NOTE: The criterion above that the "script file must be marked as executable, otherwise it will not be considered" is an important one.

The line in a shell script starting with #! is called shebang (among others), and it is an interpreter directive to the executing shell as for what program to use to decipher the text below; the characters after #! has to consitute an absolute path that points to this executable. For example, #!/usr/bin/python3 will expect to find the python3 program there to carry out the commands in the body of the shell script written in the Python programming language.
Using shell scripts during package build phases becomes problematic though because

When Nix runs a builder, it initially completely clears the environment (except for the attributes declared in the derivation). For instance, the PATH variable is empty. This is done to prevent undeclared inputs from being used in the build process. If for example the PATH contained /usr/bin, then you might accidentally use /usr/bin/gcc.
->

The quote above is from the Nix manual but the builder, that is shown there as an example, uses $stdenv/setup - a shell script that sets up a pristine sandbox environment for the build process, unsetting most (all?) environment variables from the calling shell, and only including a small number of utilities. (This is done to make builds reproducible, as much as possible.)1
$stdenv/setup is usually called implicitly when using stdenv.mkDerivation with the generic builder (i.e., when the builder attribute is left undeclared) but one can write their own builders and invoke it explicitly during the build process.
TIP: This answer shows one way to find where a certain Nix function is defined (although it is not infallible).
As a corollary, the programs pointed to by the shebang directives won't be at those locations (or unavailable to reach from the sandbox), but they are actually around (or will be) in the Nix store so the paths will need to be re-pointed to their location in there.

NOTE: The generic builder populates PATH from inputs of the derivation so one must make sure that these are included as a dependency.

3. How to use
3.1 Implicitly
As mentioned above,patchShebangs is automatically invoked by the patchShebangsAuto setup hook during the fixup phase whenever a package is built - unless one opts out of this by setting the dontPatchShebangs variable (or the dontFixup variable for that matter) (see Variables controlling the fixup phase in the Nixpkgs manual).
Reminder to self: 6.4 Bash Conditional Expressions.
3.1.0 What scripts is patchShebangs used on when invoked automatically?
Usually on scripts installed by packages (for example to $out/bin).
Or the ones provided default by the Nixpkgs standard library? I presume that these have to be generic enough to run on different platforms so that (1) the template is built, and (2) scripts shebangs are patched in the end. (@jtojnar confirmed this conjecture, but this section needs references, hence the small case.)
3.1.1 How to use the variables controlling a build phase?
Pass it to mkDerivation like any other variable controlling the builder.
stdenv.mkDerivation {
  #...
  dontPatchShebangs = true;
  #...
}

3.2 Explicitly
Historical note: Originally, patchShebangs was not externally callable, but it was later extracted to make its functionality re-usable in other build phases as well.
Again, from the comments in the implementation:
# Run patch shebangs on a directory or file.
# Can take multiple paths as arguments.
# patchShebangs [--build | --host] PATH...

# Flags:
# --build : Lookup commands available at build-time
# --host  : Lookup commands available at runtime

# Example use cases,
# $ patchShebangs --host /nix/store/...-hello-1.0/bin
# $ patchShebangs --build configure

It needs to be run on scripts that are to be executed directly (shell scripts included) during build time. These may be

*

*coming from the source of what is being packaged

*written by one to be used as helpers during the build process2
Specific examples from around the web:

*

*In Nix, how can I build a package that has a Python post-install script? (Unix & Linux Stackexchange)

*hard-coded bin path and NixOS (Stackoverflow)

*[QUESTION] Alias and symlinks in NixOS derivations (Reddit)

*This systemd-specific issue on IRC
... and quoting @jtojnar:

That is exactly the use case for the explicit patchShebangs call. Meson build system expects to run src/shared/generate-syscall-list.py so it calls it. But that fails because /usr/bin/env does not exist in the build sandbox. And it only gets confusing because kernel/libc/something else reports that the script does not exist, even though it was the interpreter from the shebang which does not exist.

Footnotes
[1]: TODO: Find out more about how the sandbox(es) are built exactly and what are barred and what are allowed. Quoting @jtojnar to bring one example:

/usr/bin/env, which is not available in sandbox either. (NixOS only has that in user space for convenience but that does not carry over to Nix sandbox..

[2]: @jtojnar's comment: "Right, you will not need to use it explicitly for scripts that are only executed at run time, since those will be handled by the implicit call."

All links in this thread have (hopefully) been saved to the Internet Archive. (The soundtrack of the thread is this gem.)


text:
Q: Passar valor do javascript para o post do php Estou tendo problemas para pegar a minha localização e passar para o post do php com onload. Como posso fazer isso ? Os valores que estou tentando capturar são a lat e long do google.
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 6
  });
  var infoWindow = new google.maps.InfoWindow({map: map});

  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      infoWindow.setPosition(pos);
      infoWindow.setContent('Location found.');
      map.setCenter(pos);
    }, function() {
      handleLocationError(true, infoWindow, map.getCenter());
    });
  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
  }
}

A: Um exemplo de como você pode fazer com jquery.ajax (tem no site oficial a documentação) api.jquery.com/jquery.ajax/
$.ajax({
  method: "POST",
  url: "some.php",
  data: {lat: -34.397, lng: 150.644}
})
.done(function( msg ) {
  alert( "Data Saved: " + msg );
});


text:
Q: Reference Named Ranges listed within a Cell Hello all brand new to coding here:
I am working on trying to set up views for a specific excel worksheet that I have. The worksheet has approximately 300 columns of data that is very cumbersome to navigate through. I have defined a named range for each column and have created some formulas to determine the list of named ranges on specific views eg. "namedrange_1, named range_2" etc.
I've entered some named ranges into the VBA code but noticed around 12 or so listings I get an 1004 Range reference error.
If I split the code into 3 rows and it appears to work. However I would like the code to be automated to what the formulated cell (listing of the named ranges for a specific view).
For example a formulated cell in another sheet currently appears as: "Namedrange_1, NamedRange_2, Etc"
Private Sub CMB_TAKEOFF_BASIC_Click()
    Application.ScreenUpdating = False

    Sheets("Pipe").Visible = True
    Worksheets("Pipe").Activate

    Call CMB_All_Click

    Columns("B:XFD").Select
    Selection.EntireColumn.Hidden = True

    Range("NamedRange_1,NamedRange_2).EntireColumn.Hidden = False
    Range("NamedRange_13,NamedRange_14).EntireColumn.Hidden = False

    ActiveWindow.ScrollColumn = 1

    Application.ScreenUpdating = True
End Sub

Looking for code to reference the named ranges list from calculation within an excel worksheet so I don't have to manually change the code every time a view is modified.

A: This is the complete code with some corrections. This works fine I tested it. Please give it a try.
Private Sub CMB_TAKEOFF_BASIC_Click()
Dim i As Integer
Dim arr() As String
    Application.ScreenUpdating = False
    Worksheets("Pipe").Visible = True
    Worksheets("Pipe").Activate
    'Call CMB_All_Click
    Columns("B:XFD").EntireColumn.Hidden = True
'fill the array with values: split B20's value by commas.
    arr = Split(Worksheets("VIEWS").Range("B20"), ",")
'for each value (named range) hide its column.
    For i = 0 To UBound(arr)
        Range(arr(i)).EntireColumn.Hidden = False
    Next
    ActiveWindow.ScrollColumn = 1
    Application.ScreenUpdating = True
End Sub


text:
Q: What's the passive form of "A lives (or resides) in B"? I could easily say "Currently, there are six people living in that manor", but how do I turn it into passive sentence so that the manor becomes the subject?
I was trying to make a sentence about a group of five people renting an apartment house together.

A:
"That manor is lived in by six people"

If you're not happy with that, use a transitive verb such as "occupy" or "inhabit".

A: I was trying to make a sentence about a group of five people renting an apartment house together.
The manor is currently home to five people.
("The manor houses six people" could imply that only that number of people can live there, which may not be accurate if more could fit in.)

A: You could also say:

That manor has six people living in it.

A: This works:

The manor houses six people.

House can be used as a verb; it means:

house (transitive verb) 1 a : to provide with living quarters or shelter b : to store in a house 2 : to encase, enclose, or shelter as
  if by putting in a house 3 : to serve as a shelter or container for

(definition taken from Merriam-Webster's online dictionary)


text:
Q: Looking for more direct proof of non-existence of "Euclidean algorithm norm" for $\mathbb{Z}[\sqrt{-5}]$ The textbook I'm reading, Integers, Polynomials, and Rings, by Ronald Irving, states on p. 246:

A ring $R$ is called a Euclidean ring if it satisfies the following three properties:
A. There is a norm function $N$ assigning to every nonzero element $a$ of $R$ a nonnegative integer $N(a)$ and assigning to $0$ a value $N(0)$ less than the norm of every nonzero element of $R$.
B. For any two nonzero elements $a$ and $b$ of $R$, $$N(a) \le N(ab)\;.$$
C. For any two nonzero elements $a$ and $b$ of $R$, there exist elements $q$ and $r$ such that $$b = aq + r$$ and $N(r) < N(a)$.

After this, the book builds a tower of about a half dozen theorems culminating in the unique factorization theorem for Euclidean spaces.
Now, in the ring $\mathbb{Z}[\sqrt{-5}]$, the elements $2$, $3$, $1 + \sqrt{-5}$, and $1 - \sqrt{-5}$ are irreducible, but they produce distinct factorizations of the element $6$: $$2\cdot 3 = (1 + \sqrt{-5})\cdot (1 - \sqrt{-5})\;.$$  This implies that no norm $N$ can exist for $\mathbb{Z}[\sqrt{-5}]$ that satisfies the three properties listed above.
Is there a more direct proof of the nonexistence of such norm for $\mathbb{Z}[\sqrt{-5}]$ than such a violation of unique factorization?

A: The question is what is meant by "a more direct proof". More direct does not mean easier. And it is certainly easier to refute UFD or PID instead of directly refuting norm-Euclidean. For example, it is easy to see that this ring is not a PID:
To show $\mathbb{Z}[\sqrt{-5}]$ is not a Euclidean domain, why suffices to show only the field norm $N(a+b\sqrt{-5})=a^2+5b^2$ doesn't work?

A: What you call norm function in your post is usually referred to as  euclidian function or stathm. I think the official terminology is better, in order to avoid confusion with the norm map in ANT, the point being that there are domains which are euclidian w.r.t. a stathm which does not come from the norm. See e.g. Lemmermeyer's survey www.rzuser.uni-heidelberg.de/~hb3/publ/survey.pdf.
As stressed by Dietrich Burde, for a given domain $R$, it could be more difficult to give a direct characterisation than an indirect one. But a unified characterisation, however complicated, could produce a general answer for a family of domains. Example: the Motzkin sets in  an integral domain $R$ are defined recursively by $E_0= (0), E_1=(0) \cup R^*, E_k = (0) \cup $ {$a\in R$ s.t. each residue class mod $a$ contains an element $b\in E_{k-1}$ }, $E_{\infty}$ = union of all the $E_k$ 's, and Motzkin's criterion states that $R$ is an euclidian domain iff $R=E_{\infty}$. With a bonus: the associated stathm $f$ is defined by $f(r)$ = the least index $k$ s.t. $r\in E_k$. This can be used to determine all the imaginary quadratic fields $\mathbf Q(\sqrt -d)$ whose rings of integers are euclidian. The list is: d=1, 2, 3, 7, 11, and the corresponding stathm is the norm in all cases (historically, this came as the completion of the uncoordinate efforts of many people using dissimilar methods, see Lemmermeyer, op. cit.).


text:
Q: Joining two tables and show data from one if there is any I have these two tables that i need to join
         fields_data                                       fields
+------------+-----------+------+             +------+-------------+----------+
| relationid | fieldname | data |             | name | displayname | position |
+------------+-----------+------+             +------+-------------+----------+
|     2      |    ftp    | test |             | user |  Username   |   top    |
|     2      |   other   | 1234 |             | pass |  Password   |   top    |
+------------+-----------+------+             | ftp  |    FTP      |   top    |
                                              | log  |    Log      |   top    |
                                              | txt  |    Text     |   mid    |
                                              +------+-------------+----------+

I want to get all the rows from the "fields" table if they have the position "top" AND if a row has a match on name = fieldname from fields_data it should also show the data. This is my join
SELECT
fd.`data`,
fd.`relationid`,
fd.`fieldname`,
f.`name`,
f.`displayname`

FROM `fields` AS f

LEFT OUTER JOIN `fields_data` AS fd
ON fd.`fieldname` = f.`name`

WHERE f.`position`='top' AND (fd.`relationid`='3' OR fd.`relationid` IS NULL)

My problem is that the above query only gives me this result:
+------+------------+-----------+------+-------------+
| data | relationid | fieldname | name | displayname |
+------+------------+-----------+------+-------------+
| NULL | NULL       | NULL      | user |  Username   |
| NULL | NULL       | NULL      | pass |  Password   |
| NULL | NULL       | NULL      | log  |    Log      |
+------+------------+-----------+------+-------------+

The field called "ftp" is missing due to it having a relation to "2".. However i still want to display it as result but like the others with NULL in it. And if the SQL query had "fd.relationid='2'" instead of 3 it would give same result, but with the row containing ftp in name, holding data in the three fields.
I hope you get what i mean.. My english is not the best.. Heres the result i want:
   with above query containing fd.`relationid`='3'
+------+------------+-----------+------+-------------+
| data | relationid | fieldname | name | displayname |
+------+------------+-----------+------+-------------+
| NULL | NULL       | NULL      | user |  Username   |
| NULL | NULL       | NULL      | pass |  Password   |
| NULL | NULL       | NULL      | ftp  |    FTP      |
| NULL | NULL       | NULL      | log  |    Log      |
+------+------------+-----------+------+-------------+

   with above query containing fd.`relationid`='2'
+------+------------+-----------+------+-------------+
| data | relationid | fieldname | name | displayname |
+------+------------+-----------+------+-------------+
| NULL | NULL       | NULL      | user |  Username   |
| NULL | NULL       | NULL      | pass |  Password   |
| test | 2          | ftp       | ftp  |    FTP      |
| NULL | NULL       | NULL      | log  |    Log      |
+------+------------+-----------+------+-------------+

A: You want to move the condition to the on clause:
SELECT fd.`data`, fd.`relationid`, fd.`fieldname`, f.`name`, f.`displayname`
FROM `fields` f LEFT OUTER JOIN
     `fields_data` fd
      ON fd.`fieldname` = f.`name` AND fd.`relationid` = '3'
WHERE f.`position`='top' ;

It is interesting that the semantics of your query and this query are different -- and you found the exact situation:  when there is a match on another value, the where clause form filters out the row.  This will still keep everything.
As a note, the following also does what you want:
SELECT fd.`data`, fd.`relationid`, fd.`fieldname`, f.`name`, f.`displayname`
FROM `fields` f LEFT OUTER JOIN
     (SELECT fd.*
      FROM `fields_data` fd
      WHERE  fd.`relationid` = '3'
     ) fd
     ON fd.`fieldname` = f.`name`
WHERE f.`position` = 'top' ;

I wouldn't recommend writing the query this way, particularly in MySQL (because the subquery is materialized).  However, understanding why your version is different from these versions (and why these are the same) is a big step forward in mastering outer joins.


text:
Q: Show that $(x^2 + y^2) \sin\left(\frac{1}{x^2 + y^2}\right)$ is differentiable. In this exercise one must show that $$f(x,y) = \begin{cases}
0 \text{     if } (x,y) = (0,0)\\
(x^2 + y^2) \sin\left(\frac{1}{x^2 + y^2}\right) \text{     else}
\end{cases}$$ is differentiable for all $(x,y) \in \mathbb{R^2}$
In the lecture, we have proven that if all partial derivatives of $f$ exist and are continuous, then the derivative of $f(x,y)$ exists everywhere.
I start by calculating the partial derivatives of $f$ at $(0,0)$:
$$\partial_xf(0,0) = \lim_{x\to0} \frac{f(x,0)-f(0,0)}{x} = \lim_{x\to0} \frac{x^2\sin({1 \over x^2})}{x} = 0$$
Similar for $\partial_y$:
$$\partial_yf(0,0) = \lim_{y\to0} \frac{f(0,y)-f(0,0)}{x} = \lim_{y\to0} \frac{y^2\sin({1 \over y^2})}{y} = 0$$
We know that for all other values of $x$, $\partial_x f =
2x\sin\left(\frac{1}{x^2+y^2}\right)-\frac{2x\cos
\left(\frac{1}{x^2+y^2}\right)}{x^2+y^2}$
I have tried to show that $\lim _ {x,y \to (0,0)} \partial_x f = 0$. (to show f is continuous) this however is problematic, since this limit doesn't exist.
This implies that the partial derivates are not continuous at all points. Which makes this approach of proving that $f$ is differentiable useless.
How do I prove that $f$ is differentiable on all of $\mathbb{R}^2$.
I am open for all kind of suggestions. Thanks for your time.

A: Note that$$\tag1\lim_{(x,y)\to0}\frac{\bigl|f(x,y)\bigr|}{\bigl\|(x,y)\bigr\|}=\lim_{(x,y)\to0}\sqrt{x^2+y^2}\left|\sin\left(\frac1{x^2+y^2}\right)\right|=0.$$Therefore, $f$ is differentiable at $(0,0)$ and $D_{(0,0)}f$ is the null function, since, if $L\colon\mathbb{R}^2\longrightarrow\mathbb{R}$ is the null function, then $(1)$ means that$$\lim_{(x,y)\to0}\frac{\bigl|f(x,y)-f(0,0)-L(x,y)\bigr|}{\bigl\|(x,y)\bigr\|}.$$So, by the definition of differentiable function, $f$ is differentiable at $(0,0)$ and $D_{(0,0)}f=L\equiv0$.


text:
Q: If $m^*(E)=0$, prove that $m^*(E_n)=0$ for each $n$ Define $\displaystyle m^*(E)=\inf\left\{\sum_{n=1}^\infty\ell(I_n):E\subset\bigcup
 _{n=1}^\infty I_n\right\}$.
Let $E=\bigcup_{n=1}^\infty E_n$. Suppose $m^*(E)=0$. Prove that $m^*(E_n)=0$ for every $n$.
My attempt:
Since $m^*(E)=0$, $E$ is a countable set. This means each of the $E_n$ is also countable and so $m^*(E_n)=0$ for all $n$.
QED

Is this correct?

A: $E_n \subseteq E$ for all $n$. By monotonicity, $m^*(E_n) = 0$.


text:
Q: Decimal values in polar pie chart I have plotted a polar pie chart in LaTeX.
Here is the code:
\begin{document}

\begin {tikzpicture}[thick]
\tikzstyle{every node}=[font=\LARGE]

\pie[polar, text=inside]{10.5/A, 20.8/B, 30.2/C, 40.4/D}

\end{tikzpicture}
\end{document}

I would like to add decimal values instead of integer. Like

10.45, 20.78, 30.67, 40.10.

How can I do that?

A: It seems that when using polar parameter you cannot use floats (only integers). To me it looks like package bug. Here would be the patch for the pgf-pie.sty (on the left is the new code, on the right the old code - I only show the part of pgf-pie.sty):
  %%%%%%%%%% CIRCLE PIE BGEIN %%%%%%%%%%%    %%%%%%%%%% CIRCLE PIE BGEIN %%%%%%%%%%%
  \ifpolar                                   \ifpolar
  \xdef\maxValue{0}                          \xdef\maxValue{0}
  \newdimen \@temp
  \foreach \p/\e in {#2} {                   \foreach \p/\e in {#2} {
    \@temp=\maxValue pt
    \ifdim  \p pt > \@temp                     \ifnum \maxValue < \p
    \xdef\maxValue{\p}                         \xdef\maxValue{\p}
    \fi                                        \fi
  }                                          }

Alternatively copy code from pgf-pie.sty of the command \pie (257 lines of code) and change relevant part.
Here is working MWE with changed pgf-pie.sty:
\documentclass{standalone}
\usepackage{pgf-pie}
\begin{document}
\begin {tikzpicture}[thick]
\tikzstyle{every node}=[font=\LARGE]
\pie[polar,sum=auto,text=inside,after number={}]{10.45/A, 20.78/B, 30.67/C, 40.10/D}
\end{tikzpicture}
\end{document}


text:
Q: Is there a way to create a custom image upload handler for CKEditor 4? All the document shows CKEditor 5 supporting custom image uploader handlers.
In CKEditor 4, you can create custom commands which is fine. But is there a way to expose a custom adapter handler for the existing plugin? I would like to reuse the rest of the code they have in terms of the sizing and captioning -- but I would like to implement my own custom API backend (for example, Imgur)
It looks like existing libraries are just making entire new plugins.
I can't use CKEditor 5 since it has only partial support for some of the browsers I need to support.
I could, of course, fork the default image uploading plugin as well to do the work I want. This would be a viable way of going forward.


text:
Q: google checkout php callback explained Hi all i don't know if i'm doing this right or not but i can't understand how google checkout works.
I have the php code that sends the XML to the google checkout everything is ok i reach on the checkout process taxes prices shipping is ok.
$_currency    = $params['currency'];
            $base_domain  = 'https://' . (($params['mode'] == 'transaction') ? 'checkout.google.com' : 'sandbox.google.com/checkout');
            $base_url     = $base_domain . '/cws/v2/Merchant/' . $params['merchantId'] . '/checkout';

            // Form XML array with cart items
            $_items = '';

            $google_products = $this->CI->go_cart->contents();

            foreach ($google_products as $k => $v) {
                $item_options = '';

                if (isset($v['options'])) {
                    foreach ($v['options'] as $name => $value) {
                        if (is_array($value)) {
                            foreach ($value as $item) {
                                $item_options .= $item;
                            }
                        } else {
                            $item_options .= $value;
                        }
                    }
                }

                $_items .= '<item>' . '<merchant-item-id>' . $v['id'] . '</merchant-item-id>' . '<item-name>' . strip_tags($v['name']) . ' ' . $item_options . '</item-name>' . '<item-description>' . substr(strip_tags($item_options), 0, 299) . '</item-description>' . "<unit-price currency='" . $_currency . "'>" . $v['price'] . '</unit-price>' . '<quantity>' . $v['quantity'] . '</quantity>' . '</item>';
            }

$xml_cart = "<?xml version='1.0' encoding='UTF-8'?>
    <checkout-shopping-cart xmlns='http://checkout.google.com/schema/2'>
      <shopping-cart>
        <merchant-private-data>
            <additional_data>
                <session_id>" . base64_encode($customer['bill_address']["email"] . date('h:i:s')) . "</session_id>
                <currency_code>" . $_currency . "</currency_code>
                <payment_id>" . base64_encode($customer['bill_address']["email"] . date('h:i:s')) . "</payment_id>
                " . $private_ship_data . "
            </additional_data>
        </merchant-private-data>
        <items>" . $_items . "</items>
      </shopping-cart>
      <checkout-flow-support>
        <merchant-checkout-flow-support>
          <platform-id>971865505315434</platform-id>
          <request-buyer-phone-number>true</request-buyer-phone-number>
          <edit-cart-url>" . $edit_cart_url . "</edit-cart-url>
          <merchant-calculations>
            <merchant-calculations-url>" . $calculation_url . "</merchant-calculations-url>
          </merchant-calculations>
          <continue-shopping-url>" . $return_url . "</continue-shopping-url>
          " . $shippings . $taxes . "
        </merchant-checkout-flow-support>
      </checkout-flow-support>
    </checkout-shopping-cart>";

            $signature     = $this->fn_calc_hmac_sha1($xml_cart, $params['merchantKey']);
            $b64_cart      = base64_encode($xml_cart);
            $b64_signature = base64_encode($signature);

            echo '<form method="post" action="' . $base_url . '" name="BB_BuyButtonForm">
        <input type="hidden" name="cart" value="' . $b64_cart . '" />
        <input type="hidden" name="signature" value="' . $b64_signature . '" />
        <input alt="" src="' . $base_domain . '/buttons/checkout.gif?merchant_id=' . $params['merchantId'] . '&w=160&h=43&style=' . 'white' . '&variant=text&loc=en_US" type="image"/>
        </form>';

            exit;
        }

After i click on submit payment i'm then redirected to a page with successfull message and with a link to return to my website.
I'm wondering how can i check if the payment was or not successfully.
Also there is a callback that i don't know exactly what is supposed to do.
Please help me understand better
I have attached the code below.

A: Disclaimer: Am not a PHP dev.

*

*Your code above is known as Part 1. Checkout API documented here. It covers how you get your data/cart to Google for Checkout

*Part II. Order Processing covers how to get data from Google (into your systems). A tutorial is provided here. This is where you provide a Callback API URL that listens to (waits for) HTTP POSTs from Google and proceed to process the data.


text:
Q: chart.js chart distorted with fixed width I have a chart.js canvas inside a container which I gave a fixed min-width, so people could scroll the chart on mobile devices.
But as soon as the container has its fixed width, the chart is getting more distorted, the smaller the screen gets.
In the chart I have already tried setting the options responsive: true and maintainAspectRatio: false. This solved the problem a bit, but the chart is still distorted.
Chart.js Options:
var options = {
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      yAxes: [{
        stacked: false,
        gridLines: {
          display: true,
          color: "rgba(151,151,151,0.2)"
        }
      }],
      xAxes: [{
        gridLines: {
          display: true,
          color: "rgba(151,151,151,0.2)"
        }
      }]
    }
  };

HTML:

 <canvas id="tds-chart-mem"></canvas>

CSS:
.tds-chart-inner {
 min-width: 850px !important;
}

.tds-hor-scroll {
 left: 0px;
 width: 100% !important;
 overflow-x: scroll;
}

canvas {
  left: 0px;
  height: 300px !important;
}

Working chart

Distorted chart

A: for me the problem was that graph was setting for itself height that was bigger that I myself had set to canvas.
my solution was:

*

*I removed all height setups for canvas (css and tag attribute)

*Created container tag for the canvas and set height to it

*in chart options added:

      responsive: true,
      maintainAspectRatio: false,

in the example in the question problem was in css:

canvas {
  left: 0px;
  height: 300px !important;
}

i would change it to:

.tds-hor-scroll {
 overflow-x: auto;
}
.tds-chart-inner {
  min-width: 850px;
  height: 300px;
}

   <canvas id="tds-chart-mem"></canvas>

A: <!DOCTYPE HTML>

<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

 <canvas id="myChart"></canvas>


text:
Q: How do I use the DOM Explorer in Visual Studio Express 2012 RC for Windows 8 Has anyone been able to use the DOM Explorer to debug their Win 8 apps?
I do not see a DOM Explorer tab when debugging as described here: http://msdn.microsoft.com/en-us/library/windows/apps/hh696632.aspx

A: Use the Debug > Windows > DOM Explorer menu command to show the DOM Explorer tab.


text:
Q: Compilation errors inside C++ stdlib when compiling for iOS 14.5 arm64 I'm getting weird compilation errors while compiling my library for arm64 architecture, iOS 14.5 SDK using -std=c++11 and -stdlib=libc++ flags. Compilation errors come from C++ stdlib files. The code being compiled:
#include "clock.hpp"
#include <chrono>

using namespace std::chrono;

namespace optar
{
namespace clock
{
int64_t millisecondTimestamp()
{
    milliseconds msec = duration_cast<milliseconds>(steady_clock::now().time_since_epoch());
    return msec.count();
};

int64_t microsecondTimestamp()
{
    microseconds usec = duration_cast<microseconds>(steady_clock::now().time_since_epoch());
    return usec.count();
};

int64_t nanosecondTimestamp()
{
    nanoseconds nsec = steady_clock::now().time_since_epoch();
    return nsec.count();
};

double unixTimestamp()
{
    auto now = system_clock::now().time_since_epoch();
    duration<double> sec = now;
    return sec.count();
}

int64_t millisecSinceEpoch()
{
    milliseconds msec = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
    return msec.count();
}
}
}

yields ~20 errors similar to (also see the screenshot attached):
In file included from /Users/peetonn/Documents/Work/optarLibrary/src/utils/clock.cpp:10:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/chrono:827:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/ctime:49:
In file included from /Users/peetonn/Documents/Work/optarLibrary/thirdparty/ros.framework/Headers/time.h:53:
In file included from /Users/peetonn/Documents/Work/optarLibrary/thirdparty/ros.framework/Headers/platform.h:38:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/string:506:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/string_view:175:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/__string:57:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/algorithm:643:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/memory:681:
In file included from /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/atomic:576:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.5.sdk/usr/include/c++/v1/__threading_support:265:38: error: use of undeclared identifier 'chrono'
void __libcpp_thread_sleep_for(const chrono::nanoseconds& __ns);

I'm not quite sure what is happening. Originally thought of some faulty flags and/or std library, but still see this problem with other flag combinations (-stdlib=libstdc++, -std=c++14 -std=c++17). Any hints will be appreciated.


text:
Q: Dojo form displays different in IE 8 For some reason, my code displays correctly in all browsers except IE8.
<form dojoType="dijit.form">'

        Name
        <input dojoType="dijit.form.ValidationTextBox" invalidMessage="Name is required." required="true" propercase="true" trim="true" id="contactname" />

            Please enter a name.

        Email
        <input dojoType="dijit.form.ValidationTextBox" invalidMessage="Email is required." regExp="[a-z0-9._%+-]+@[a-z0-9-]+\.[a-z]{2,4}" required="true" trim="true" id="contactemail" />

            Please enter your email address.

        Message
        <textarea dojoType="dijit.form.Textarea" id="contactmessage" rows="6"></textarea>

            Please enter a message.

        <button dojoType="dijit.form.Button" type="button" onclick="essentials.SendContactUsEmail();">Send your request</button>

</form>

I also get this error in IE8.
"Could not load class 'dijit.form'. Did you spell the name correctly and use a full path, like 'dijit.form.button'?
dojo.js

A: By removing the dojoType attribute from your form element, you've reverted to the generic HTML form.  If you want to make use of Dojo Form validation, you can do so with something like this...
You'll need to use: dijit.form.Form

    <form dojoType="dijit.form.Form" action="..." method="...">
        <input dojoType="dijit.form.ValidationTextBox" trim="true" regExp="..." invalidMessage="Oops...">

        <button type="submit" dojoType="dijit.form.Button" ...>
            Submit
        </button>


text: Q: Search product show after customer login in Magento 2 Search product show after customer login in Magento 2. Without login no product views to customer on search in website and  it redirected  on customer login


text:
Q: MVC4 - Login box within Layout page using Partial I have a layout page, and want it to have a Login Box, OR display the logged in user, along with a Logout link.
At the moment, my SiteLayout.cshtml file has this:

Basic Finance

        @if (Request.IsAuthenticated)
        {
            @Html.ViewBag.UserDisplay
            @Html.ActionLink("[Logout]", "LogoutUser", "User")
        }
        else
        {
            @Html.Partial("_Login")
        }

        @RenderBody()

Then, i my Views/Shared/, I have the _Login.cshtml file:
@model BasicFinanceUI.Models.LoginModel
@using (Html.BeginForm())
{
    @Html.ValidationSummary()

        Username: @Html.TextBoxFor(x => x.Username)
        Password: @Html.TextBoxFor(x => x.Password)
        Remember Me: @Html.DropDownListFor(x => x.RememberMe, new[]
                {
                    new SelectListItem() { Text = "Yes", Value = "true"},
                    new SelectListItem() {Text = "No", Value = "false"}
                }, "Select")

        <input type="submit" value="Login" />

}

This code was moved from a standard view. I had it then there was simply a 'Login' link, instead of the login box in the Layout page. I want to display a login box instead.
My login code is still in a controller I created called 'UserController'. But, I have no idea how to tell my login box to use that controller. Is this the right way to do what I want (or should there be a controller for my login partial). Is it OK to use my 'UserController'? And if so, how?

A: Change:
@using (Html.BeginForm())
{
    @Html.ValidationSummary()

        Username: @Html.TextBoxFor(x => x.Username)
        Password: @Html.TextBoxFor(x => x.Password)
        Remember Me: @Html.DropDownListFor(x => x.RememberMe, new[]
                {
                    new SelectListItem() { Text = "Yes", Value = "true"},
                    new SelectListItem() {Text = "No", Value = "false"}
                }, "Select")

        <input type="submit" value="Login" />

}

To:
@using (Html.BeginForm("Login", "User"))
{
    @Html.ValidationSummary()

        Username: @Html.TextBoxFor(x => x.Username)
        Password: @Html.TextBoxFor(x => x.Password)
        Remember Me: @Html.DropDownListFor(x => x.RememberMe, new[]
                {
                    new SelectListItem() { Text = "Yes", Value = "true"},
                    new SelectListItem() {Text = "No", Value = "false"}
                }, "Select")

        <input type="submit" value="Login" />

}

Where "User" is your controller and "Login" is your action method that handles the Login's POST.
http://msdn.microsoft.com/en-us/library/dd492590(v=vs.118).aspx


text:
Q: android can't see web service I've written my first Android app (Sencha Touch + Phonegap using Eclipse on PC). It pulls some JSON from a WCF service. It works fine in the emulator.
I've now put it on my phone (Samsung GT-19100T running Gingerbread). The app runs but hangs when calling the service. The phone just shows the loading animation. The server shows no request has reached it. The phone can browse the net ok.
EDIT: I should add that the problem is not the server. I can browse to the same services ok on PC, and we have an iPhone app that works with it fine.
The only other strange thing I've noticed is that if I browse to the endpoint on iPhone or PC, I get the JSON text in the browser. If I try it on the android's browser it says "cannot download".
How do I go about diagnosing this?
Is there some sort of option on the phone?

A: found it. The answer is to SHOOT ME NOW.
the URL had been entered so long ago I forgot all about it, including little details like the fact that it used an internal ip address.
Total facepalm. No, that won't do it. Let's try a facedesk...


text:
Q: Replace a specific word with the value from another column I've the following dataframe:

What I am trying to do is to add the vlaue from Col_1 after the word "Draft".
Basically, I need the following output:

For that I am trying with the following code:
df['Col_3'] = df['Col_2'].str.replace(r'Draft', ' Draft' + df['Col_1'].astype(str), regex=True)

But it gives me the following error:
 raise TypeError("repl must be a string or callable")
TypeError: repl must be a string or callable

How can I do this?
Thanks!

A: df['Col3'] = df.apply(lambda x: x['Col2'].replace("Draft", "Draft {}".format(x['Col1'])), axis=1)

or using fstrings
df = pd.DataFrame(
    {
        "val": ["AAA", "BBB"],
        "str": [
            "Draft I promise not to use pictures in my next question",
            "Draft jk ill most likely post more pics"]})

df["output"] = df[["str", "val"]].apply(
    lambda x: x["str"].replace("Draft", f"Draft {x['val']} "), axis=1
)

print(df['output'])

0    Draft AAA  I promise not to use pictures in my...
1         Draft BBB  jk ill most likely post more pics
Name: output, dtype: object

A: I think you need this:
df['Col2'] = df['Col2'].str[:5] + " " + df['Col1'] + " " + df['Col2'].str[5:]

or use [str.slice][1]
df['Col2'] = df['Col2'].str.slice(0, 5) + " " + df['Col1'] + " " + df['Col2'].str.slice(5)

A: You could try this :
df['Col_3'] = 'Draft ' + df['Col_1'] + df['Col_2'].str.replace('Draft', '')


text:
Q: SQLSTATE[01003]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Warning: Null value is eliminated by an aggregate or other SET operation I am trying to run the following code
DB::table('gbb_intimation_claim_max_serial')->where('id', 1)->increment('intimation_max_serial');
$intimation_max_serial = DB::table('gbb_intimation_claim_max_serial')->where('id', 1)->value('intimation_max_serial');
DB::table('claims')->where('id', $claim->id)->update(['intimation_number' => $intimation_max_serial]);

But weirdly, I am getting this error on laravel
SQLSTATE[01003]: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Warning: Null value is eliminated by an aggregate or other SET operation. (SQL: update [claims] set [intimation_number] = 1763 where [id] = 7172)

I have tried
SET ANSI_WARNINGS OFF;

But this didn't help

A: You do not normally get that error on an update statement, I suspect it is a carryover from your first query where it looks like your are returning the max claim serial, if you look at your data you will find one of the claim serial values is null and when you perform an aggregate function on a range of values that include a null that warning is thrown.


text:
Q: Integral help with completing the square!! Could you please help me integrate
$$\int\frac{dx}{\sqrt{2+x-x^2}}$$
I am supposed to complete the square.. but I am seriously stuck. I have tried to square each side and stuff, but it does not seem to be working

A: Hint:
Completing the square means rewriting a general quadratic $ax^2+bx+c$ in the form $a(x-h)^2+k$.  If you want to write $2+x-x^2$ in this form, the first step is to write
$$
2+x-x^2=2-(x^2-x).
$$
Now, if you were going to write $x^2-x=(x-h)^2+z$, what would you need to choose for $h$?  What would this make $z$?
Hint #2 (Update):
So, you've found that $2+x-x^2=-(x-\frac{1}{2})^2+\frac{9}{4}$, making your integral
$$
\int\frac{dx}{\sqrt{\frac{9}{4}-(x-\frac{1}{2})^2}}.
$$
Remember that
$$
\int\frac{dw}{\sqrt{1-w^2}}=\arcsin(w)+C.
$$
Can you see any way to bridge the divide between these two integrals?


text:
Q: Add constants issues Xcode 4.5 I've got a class for storing constants.
So, there are two files that call Constant.h and Constant.m
This is what I have in .h file:
#import <Foundation/Foundation.h>

enum kParams {
    kFirstName = 0,
    kLastName = 1
};

extern NSString * const kNotificationUpdateMainMenu;

This is what I have in .m file:
#import "Constants.h"

NSString * const kNotificationUpdateMainMenu = @"kNotificationUpdateMainMenu";

For first time it works good, but when I try to add some other const (kNotificationFbLoginSuccsess for example) other classes don't see it.
This is a message that shows me which problem I have. But I don't understand how my other constants work without this issue (just new constant that I add get this error).
/Users/developer/Documents/Projects/Test/Test/Test/AppDelegate.m:121:64: Use of undeclared identifier 'kNotificationFbLoginSuccsess'

I found some way how to fix it:

*

*Open organizer

*Clear derived data

*Delete project.xcworkspace file and xcuserdata

*Close Project

*Relaunch Xcode

but as I think is too much operations that I can add one constant. How come?

A: Your "global" constant is not actually external (separately compiled and later linked together).  Take the easy way out and place NSString * const kNotificationUpdateMainMenu = @"kNotificationUpdateMainMenu"; into the header file.  The method file needs nothing.
I would use #define kNotificationUpdateMainMenu @"kNotificationUpdateMainMenu" to perform the spell checking.  The compiler will create one shared instance of the constant string for the entire compilation.


text:
Q: If $p(x)\in F[x]$ have root $r$ show that $x-r$ is a factor of $p(x)$ This is an exercise of Advanced linear algebra of Steven Roman:

Let $F$ a finite field and $p(x)\in F[x]$ a nonconstant polynomial such that $p(r)=0$. Show that $x-r$ is a factor of $p(x)$.

This exercise appear after some theory of cyclic decomposition of torsion modules over PIDs, however I dont have any clue about how to show that. Also I dont found anything useful from previous chapters of the book to solve this question.
My first idea was trying to see if $F[x]$ is a PID, what would imply that each ideal is principal, and so, as a $F[x]$ module, it would imply that the submodule defined by $S_r:=\{p(x)\in F[x]: p(r)=0\}$ would be cyclic, finishing the proof. However it seems not the case that $F[x]$ is a PID, otherwise $x-r$ and $p(x)$ would be associated, meaning that $p(x)=u(x)(x-r)$ where $u(x)$ is a unit (that is, that have inverse).
Im really stuck with this exercise, some help will be appreciated, thank you.
NOTE: this doesn't answer my question, because it doesn't show why $x-r\mid p(x)$. Searching for proofs about the division algorithm on polynomial rings it seems that it just hold whenever the ring is an integral domain, however nothing related to this topic is stated in the book, so I assume that it may exist a different way to answer the question.

A: This is a basic fact about polynomials with coefficients in an arbitrary commutative ring $R$.
Without the division algorithm, you can prove that, for any positive integer $k$,
$$
x^k-r^k=(x-r)(x^{k-1}+rx^{k-2}+\dots+r^{k-2}x+r^{k-1})
$$
and therefore, if $f(x)=a_0+a_1x+\dots+a_nx^n$ and $f(r)=0$, we have
$$
f(x)=f(x)-f(r)=a_1(x-r)+a_2(x^2-r^2)+\dots+a_n(x^n-r^n)
$$
so we're done.
Alternatively, prove by induction on the degree of $f$ that, for every monic polynomial $g(x)$, there exist $Q(x)$ and $R(x)$ with $\deg R<\deg g$ (or $R=0$) and $f(x)=g(x)Q(x)+R(x)$.
Indeed, this is obvious when $f$ is constant. If $\deg f(x)<\deg g(x)$ there is nothing to prove. If $m=\deg f(x)\ge\deg g(x)=n$, suppose the leading coefficient of $f$ is $a_m$. Then the polynomial
$$
f_1(x)=f(x)-a_mx^{m-n}g(x)
$$
has degree less than the degree of $f$ and the induction hypothesis applies, so $f_1(x)=g(x)Q_1(x)+R(x)$ with $\deg R<\deg g$; now
$$
f(x)=a_mx^{m-n}g(x)+f_1(x)=g(x)(a_mx^{m-n}+Q_1(x))+R(x)
$$
As you see, nowhere it is used that the ring is an integral domain.
For the particular case, note that when $g(x)=x-r$, the remainder is constant and from $f(x)=(x-r)Q(x)+R$ we derive that $f(r)=R$.


text:
Q: SublimeLinter User Config parse error (pep8) I've just installed SublimeLinter to help me manage my Python code. Currently it is flagging up blank lines as errors which is annoying so I wanted to disable that by writing some ignore settings in the user config file.
The config file is located in ~./config/sublime-test-2/Packages/User/SublimeLinter.sublime-settings
{
    "pep8_ignore":
    [
      "W239"
    ]
}

If I try to add a comma after the square brackets I get "Trailing comma before closing brackets" when saving
If I try to add a comma after the curly brackets I get "unexpected trailing characters" when saving
If I leave it as it is above and close and reopen sublime I get the error message:

"Error trying to parse settings: Unexpected character, expected a
  comma or closing bracket in
  ~/.config/sublime-text-2/Packages/SublimeLinter/SublimeLinter.sublime-settings:194:9

(despite the file only being a few lines long.
I've looked on here and other places to look for examples and it seems I'm doing it exactly as others have done. Any advice would be much appreciated. Sorry if my formatting isn't great, I'm getting use to the stackoverflow way of doing things.

A: From the error you're getting, you cut something out of the original settings file (~/.config/sublime-text-2/Packages/SublimeLinter/SublimeLinter.sublime-settings) when you made your Packages/User/SublimeLinter.sublime-settings file. Head over to the SublimeLinter GitHub site and download the original version.
Next, save that original version both in the Packages/SublimeLinter directory and and your Packages/User directory. The User one will override the other, but you need to remember that any keys you make changes to need to be replicated in full (please read the README in full to understand) in order for everything to work properly. Now, you can scroll down in the User copy to the "pep8_ignore": section and add "W239" on its own line, with commas , separating lines. So, the full section should look like this:
"pep8_ignore":
[
    "E501",
    "W239"
],

Feel free to add new errors/warnings as you want, but remember that others in the community will likely look more favorably on your code the more closely you follow PEP8. That being said, some of the warnings are rather silly, but over time I've found myself coding closer to the guidelines, and it really does result in cleaner, more easily-read code, especially if you come back to something after a while.


text:
Q: Convert PDF content(with images) to the Inline HTML content Is there any Javascript library or code available to convert pdf content(with images) to the HTML inline content.
Any help would be appreciated, Thanks in advance

A: You can have a look on the below API for this:
https://www.pdfonline.com/convert-pdf-to-html/
or use the free online tool available for this.
https://www.pdftohtml.net/


text:
Q: What is the relationship between the sub-items and the main one on Oxford Dictionary? Oxford Dictionary (https://www.lexico.com/en/definition/just) gives a bunch of definitions about "just"
there are 3 sub-items in 4th item, one of them is pointed out by blue rectangle in the following image.

What is the relationship between the sub-items and the main one?
Could all of 3 sub-items could be a piece of meanings of "Simply", I guess not.
sub-item 4.2 gives

Used as a polite formula for giving permission or making a request.

and gives this example

just help yourselves

if this is one piece of meanings of the main item, namely, "Simply", the following sentence would sound normal

Simply help yourselves

which actually sounds uncommon, any ideas?
Besides, neither Oxford dictionary (https://www.lexico.com/en/definition/simply) nor Cambridge dictionary (https://dictionary.cambridge.org/dictionary/english-chinese-simplified/simply) has a piece of meaning similar to this one (shows politeness).

A: All three sub-usages are clear substitutes for simply - each one in a slightly different way.
4.1: they're just great
Their condition of being great is not bound to a complicated formula like they're kind of great but with the exception of ... and actually.... No, they are great. Period. It's this simple. They are simply great.
4.2: just help yourselves
Don't go the complicated way of asking someone for help. Take the simple way. Simply help yourselves.
4.3: it might just help
I don't know. You perhaps need a complex solution. But it could also be that this simple solution works for you. This could simply be your solution. This might simply be the help you need. This might simply help.
Of cause, we don't think of 'simply' or 'just' in such a detailedness when we use them. We use them intuitively, but the intuition checks the appropriateness of the usage against such thoughts in a quick, unknown, but reliable manner.


text:
Q: Change object`s texture in real time in app Here i have the main classes. I want to change the object`s material in real time in  app but i have no success. Can you tell why please?

class VirtualObject: SCNNode {
    static let ROOT_NAME = "Virtual object root node"
    var fileExtension: String = ""
    var thumbImage: UIImage!
    var title: String = ""
    var modelName: String = ""
    var modelLoaded: Bool = false
    var id: Int!
    override init() {
        super.init()
        self.name = VirtualObject.ROOT_NAME
    }

    init(modelName: String, fileExtension: String, thumbImageFilename: String, title: String) {
        super.init()
        self.id = VirtualObjectsManager.shared.generateUid()
        self.name = VirtualObject.ROOT_NAME
        self.modelName = modelName
        self.fileExtension = fileExtension
        self.thumbImage = UIImage(named: thumbImageFilename)
        self.title = title
    }

}
@IBAction func textureIt(_ sender: Any) {
     let object = VirtualObjectsManager.shared.getVirtualObjectSelected()
    object?.thumbImage = #imageLiteral(resourceName: "chair_DIFFUSE")
  VirtualObjectsManager.shared.setVirtualObjectSelected(virtualObject: object!)
}

I want to change the objects texture in app but I cant and i don`t know what i do wrong. When i debug the app the thumbImage change but in app it remains the same. What can I do?


text:
Q: fullPage.js SLIDE tooltips I posted another question earlier today about the fantastic fullPage.js plugin, but seeing as how I have multiple questions about it, I figure I'll ask them separately.
I'm creating a page that combines horizontal and vertical navigation, where I'm using horizontal for section navigation and vertical for slide navigation. Is there any way to make and insert tooltips for slides, similar to how there are tooltips for sections?
In my research I've found this discussion that indeed seems like it might hold the solution, but due to my unfortunately poor understanding of js I am unable to translate the solution provided there to slides within a section.
I greatly appreciate any assistance that can be offered. Thank you. Best, Nick


text:
Q: Sum expressed as a function Is there any way to express $\sum_{n=0}^{x-2} \frac {1}{x-n} $ as a function of $x$, as opposed to being a summation? I tried doing this through modelling on Desmos, but the closest I could get was $y= \ln(\lfloor{x+0.5}\rfloor)-\ln(2)+\frac{2}{3}$ which isn't even that close to the original function.
If it is possible to express it as a function, how would one get to it, and what would it be?

A: If $x$ is a natural, the sum is $H_x-1$ where $H_n$ denotes the $n^{th}$ harmonic number.

A: If $x > 2$ is not an integer, I presume you mean the sum to go up to $\lfloor x-2 \rfloor$ (i.e. the sum over all $n$ such that $0 \le n \le x-2$).  Then your sum can be written as
$\psi(-x) - \psi(\lfloor x\rfloor - x - 1)$
where $\psi$ is the digamma function.
For integer $x \ge 2$ you get $H_x - 1$ as Yves Daoust wrote.


text:
Q: how to call API from axios with header I want to call the API POST method with axios, I did it with postman with header configuration like, and it return the results
and the body request looks :
it return error when I call by axios this my script, anyone can help me what I suppose todo from the axios side ?
const header = {
            headers: {
                'Content-Transfer-Encoding': 'application/json',
                'content-type': 'application/json',
                'HTTP_API_KEY': 'xxxxx',
            }
        }
        axios({
            method: 'POST',
            url: URL,
            headers: header,
            data : {

            }
          })
            .then((response) => {
              if (response.status !== 200) {
                return res.send(respone("500", response.data.result.data))
              } else {
                return res.send(respone("200", response.data.result.data))
              }
            })
            .catch((error) => {
              console.log(error);
              return res.send(error)
            })

the error show
{
"message": "Request failed with status code 404",
"name": "AxiosError",
"config": {
    "transitional": {
        "silentJSONParsing": true,
        "forcedJSONParsing": true,
        "clarifyTimeoutError": false
    },
    "transformRequest": [
        null
    ],
    "transformResponse": [
        null
    ],
    "timeout": 0,
    "xsrfCookieName": "XSRF-TOKEN",
    "xsrfHeaderName": "X-XSRF-TOKEN",
    "maxContentLength": -1,
    "maxBodyLength": -1,
    "env": {},
    "headers": {
        "Accept": "application/json, text/plain, */*",
        "Content-Type": "application/json",
        "Content-Transfer-Encoding": "application/json",
        "HTTP_API_KEY": "xxxx",
        "User-Agent": "axios/0.27.2",
        "Content-Length": 2
    },
    "method": "post",
    "url": "xxxxx",
    "data": "{}"
},
"code": "ERR_BAD_REQUEST",
"status": 404
}

A: It seems you nested your headers inside another "headers" property.
Basically you're doing this
headers: {
    headers: {
        'Content-Transfer-Encoding': ...
    }
}

A: As Zai showed in her answer you problem is your header variable:
const header = {
        headers: {
            'Content-Transfer-Encoding': 'application/json',
            'content-type': 'application/json',
            'HTTP_API_KEY': 'xxxxx',
        }
    }

is nested, when you do this:
axios({
        method: 'POST',
        url: URL,
        headers: header,
        data : {

        }

what you are really doing is:
axios({
            method: 'POST',
            url: URL,
            headers:  headers: {
                'Content-Transfer-Encoding': 'application/json',
                'content-type': 'application/json',
                'HTTP_API_KEY': 'xxxxx',
            },
            data : {

            }

So your header: instead of being Content-transfer etc... is just 'headers'
try this:
const header = {
                'Content-Transfer-Encoding': 'application/json',
                'content-type': 'application/json',
                'HTTP_API_KEY': 'xxxxx',
            }

also, i recommend you to do a console.log with your api call in order to find this problems faster and compare with postman, really helpful in develop phase (just use it in local, never push that log to production)


text:
Q: Binary SMS receiving on Android: dynamic receiver registration I can send and receive data SMS on Android using the following code snippets:
SmsManager manager = SmsManager.getDefault();
manager.sendDataMessage(phonenumber, null, (short) PORT, data,piSend, piDelivered);

where PORT=8091 for the sender. And for the receiver, a broadcast intent is defined in the manifest file as follows:
 <receiver android:name=".DataSMSReceiver">
 <intent-filter>
 <action android:name="android.intent.action.DATA_SMS_RECEIVED"/>
 <data android:port="8091"/>
 <data android:scheme="sms"/>
 </intent-filter>
 </receiver>

then received in the DataSMSReceiver class.
However, I need to register the broadcast receiver dynamically as I do for text SMS e.g.:
protected static final String SMS_RECEIVED="android.provider.Telephony.SMS_RECEIVED";
getApplicationContext().registerReceiver(mReceiver, new IntentFilter(SMS_RECEIVED));

How can I specify the port in the IntentFilter to register the receiver dynamically?
Thanks in advance.

A: I believe you need to use addDataAuthority(String, String). For example:
IntentFilter filter = new IntentFilter(SMS_RECIEVED);
filter.addDataAuthority("*", "8091");
filter.addDataScheme("sms");

//use the filter, etc...

A: As I didn't find it easily, I post it here:
the String
"android.provider.Telephony.SMS_RECEIVED"
can be found as constant in the Telephony.Sms.Intents class as:
Telephony.Sms.Intents.DATA_SMS_RECEIVED_ACTION


text:
Q: How to find the best combination beyond multiple JSON without generate all combination? I have many array of object. Each array have 5 object, and each array have objects with the same attribute object_type.
array_obj_type1 = [obj1_type1, obj2_type1, obj3_type1, obj4_type1, obj5_type1];
array_obj_type2 = [obj1_type2, obj2_type2, obj3_type2, obj4_type2, obj5_type2];
array_obj_type3 = [obj1_type3, obj2_type3, obj3_type3, obj4_type3, obj5_type3];

An object can be defined like this:
obj1_type1 = { "obj_type":1, "strength": 10 }
obj2_type1 = { "obj_type":1, "strength": 20, "luck": 10 }
I want to know the best combination with 3 slot [type1,type2,type3] each slot corresponding to one object type. If for example I search the best combination about the attribute strength I want to know a way to find the best combination without computing all other combination (because it's too heavy).
How can I do that ?
EDIT:
Tools like JMESPATH or jq don't interests me at all because I need something which doesn't use a specific library for node.js. I want to do it in pure js if it's possible.
Maybe using yield or iterator that delete the value that doesn't interest me can be a solution, because in fact I'm interested in the speed of this program. The faster the program is, the more interesting it is for me.


text:
Q: Animated lines in Google maps api v3 Is it possible to draw a animated line using Google Maps API v3
it would be along the side of the road with moving arrows showing the direction of driving.
------------------
| > > > > > > >  |
------------------

I hope i made myself clear enough.


text:
Q: How to send email from the command line under linux and include the SMTP server name? I am looking for a single line email notification solution for linux, but one that would not assume that the machine mail agent was already configured properly.
I want to specify the SMTP server from the command.
Preferably, the solution should run on Debian without having to install new tools.


text:
Q: Storing and accessing a global flag/variable in each component, The value keeps changing I am trying to make a global service class which will store few variables which will influence behaviour on HTML components base on flags.
My current only flag is a BehaviourSubject which navbar component subscribes to update a navbar with different buttons. The issue is when I refresh the page in a browser the flag reverse to the original value and forgets what has set before. The current scenario is when user log in the flag is being set to true and should stay true until a user logs out. It may not be a right way to do it so if there is a better way of approaching it; then I am happy to implement it.
Data sharing class:
import {
  Injectable
} from '@angular/core';
import {
  BehaviorSubject
} from 'rxjs';

@Injectable()
export class ServiceClassDatasharing {
  public isUserLoggedIn: BehaviorSubject < boolean > = new BehaviorSubject < boolean > (false);
  public setUserLoggedInStatus(status) {
    this.isUserLoggedIn.next(status);
  }
}

Nav Component:
import {
  Component,
  OnInit
} from '@angular/core';
import {
  MatDialog,
  MatDialogRef,
  MAT_DIALOG_DATA
} from '@angular/material';
import {
  Inject
} from '@angular/core';
import {
  ServiceClassDatasharing
} from '../service/service-class-datasharing';
import {
  ServiceClassAuth
} from '../service/service-class-auth';
import {
  SigninComponent
} from './../signin/signin.component';
import {
  Router
} from '@angular/router';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {

  id_token: Boolean;
  username: String;

  constructor(public dialog: MatDialog, private dataSharingService: ServiceClassDatasharing,
    private authService: ServiceClassAuth, private router: Router) {

    this.dataSharingService.isUserLoggedIn.subscribe(res => {
      this.id_token = res;
      if (this.id_token) {
        const user = JSON.parse(localStorage.getItem('user'));
        this.username = user['user'].user_username;
      }
    });
    if (!this.id_token) {
      router.navigate(['index']);
    }
  }

  ngOnInit() {}

  openDialog(): void {
    let dialogRef = this.dialog.open(SigninComponent, {
      width: '450px',
      data: {}
    });
  }

  public logout() {
    this.authService.logout().subscribe(res => {
      if (res['success']) {
        localStorage.clear();
        this.dataSharingService.setUserLoggedInStatus(false);
      }
    });
    this.router.navigate(['index']);
  }

}

Index Component as an example it should redirect a user to dashboard if the global flag is set to true.
import {
  Component,
  OnInit
} from '@angular/core';
import {
  ServiceClassDatasharing
} from '../service/service-class-datasharing';

import {
  Router
} from '@angular/router';

@Component({
  selector: 'app-index',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
  constructor(private dataSharingService: ServiceClassDatasharing, private router: Router) {
    if (this.dataSharingService.isUserLoggedIn.value) {
      this.router.navigate(['dashboard']);
    }
  }

  ngOnInit() {}

}

A: Try using localStorage variable to achieve the same .
Create a function in service class which will set the variable with token if user logs in and function to get the same token.
const key = 'abcde'

setUseLoggedIn(token){
 localStorage.setItem(this.key,token);
}

getUserLoggedIn(){
 return localStorage.getItem(this.key);
}

set token as null if user is not logged in and check for the same when retrieving the token.