text:
Q: Google app engine - login with Google, Facebook I would like the users of my application, hosted in Google app engine, login the same way I do in StackExchange, using my Google account or Facebook account.
I have some questions on this:

*

*I would like to see some tutorials on basic login only

*I would like to see some tutorial(s) on social login (Google, Facebook, etc.. )

A: You can use the Federated login API provided by Google to help users connect using Open ID providers (like Google, Windows Live, Yahoo, etc.).
Check out these links:

*

*Using Federated Authentication via
OpenID in Google App Engine

*A Simple OpenID Login Example on
Appengine

A: A login system is rather straightforward. Basically it is something like this:
User wants to access something that is restricted and needs a valid Account.
You check if he is logged in.
If not, you prompt the user to either create an account, or login.
If he has an account he will enter his username/password combination (preferably over SSL). You then check if the combination is valid and set his state to logged in. The best way to do this would be a cookie plus a session variable, but it depends on what you want to use.
If the user has not an account you can give him the choice to create one. Here you let him fill out everything you need, Name, username, password et cetera. And be sure to send it all over SSL again.
From there he then should be able to login successfully.
If you want some code this seems to be complete: http://www.wikihow.com/Create-a-Basic-Login-Script-in-PHP

For facebook, it is a bit different as Facebook requires the user to be logged in and prompts on it's own if he is not. To see how to use the Facebook API you can go here: http://developers.facebook.com/docs/guides/web/
The Authentication part is the one you should look at.

A: A good example for facebook authentication is runwithfriends.
The source is available and I suggest you take it and learn and your facebook authentication will work.

A: Because google has blocked this feature since 2019, there is no way to fix it.
I can't find any way to fix this error either. I chose the solution of redirecting google login link to default browser.
My new solution is:
Insert this code inside
protected void onCreate(Bundle savedInstanceState) { .... code...}

Code:
//Redirecting google login link:
        webView.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != null && (url.startsWith(("https://mywebsite.com/wp-login.php?loginSocial=google")) )) {
                    view.getContext().startActivity (
                            new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    return true;
                } else {
                    return false;
                }
            }
        });


text:
Q: Google Sheets: How to combine Filter, Query, and MINIFS Edit: Here is a spreadsheet with dummy data.
I'm working with accounting data and trying to come up with a table like this to figure out what I have to pay in the upcoming payment:

Price
Quantity
Total Value

0.50
600
300.00

0.10
1000
100.00

My data is a table of prices and quantities and arbitrary dates of payment. Cell addresses in parentheses

Price (N2)
Quantity (O2)
(P2) 1/1/2021
(Q2) 2/9/2021
(R2) 5/2/2021
(S2) 10/5/2021
(T2) 11/4/2021

0.25
100

25.00

0.70
2
1.40

0.50
500

250.00

0.10
1000

100.00

0.50
100

50.00

The values in the date columns always equal the price multiplied by quantity, and each row only has an entry in a single date column.
I want to proactively calculate how much needs to be paid in the soonest date of payment that is also in the future. So for example, since today is September 10th, it would be the amounts for October 5th, 2021.
What I've tried so far:
To do the final calculation use a query like this:
=QUERY(table_from_filter,"select Price , sum(Quantity), Price*SUM(Quantity) group by Price ")

To get the values for the query above I use a filter statement like this to filter out prices and quantities that are not in the column for 10/5/2021 (column S):
=filter(P2:T2,S2:S <> " ")

I've also been able to get the value 10/5/2021 using this formula
=MINIFS(O2:T2,O2:T2,">"&TODAY())

How can I combine / adjust all three formulas to get the desired result table for payments for only the soonest upcoming date without hardcoding the column letter?

A: Use curly brackets {A:E} then use Col1,Col2,Colx and replace x by the result in L5, so try
=query({A:E},"select Col1,Col2,Col"&L5&" where Col"&L5&"<>' ' ")

with in L5
=match(MINIFS(C2:E2,C2:E2,">"&TODAY()),A2:E2,0)

A: Proposed solution
=QUERY(
    {
        A2:B14,
        FILTER(
            C2:E14,
            C2:E2 = MIN(
                ARRAYFORMULA(
                    FILTER(C2:E2, C2:E2 - TODAY() > 0) - TODAY()
                )
            ) + TODAY()
        )
    },
"select Col1, Col2, Col3 where Col3 is not null")

Play around with it here:
https://docs.google.com/spreadsheets/d/1n3ZOyKiH9p2nref6TbsVKkKQsxBzoxasNlflpa4Hq8s/edit?usp=sharing
I copied it into a new document because you had inserted spaces into some blank cells which were preventing is not null from working, and deleting these spaces seemed to mess with your formulae.
I changed your "date finder" to:
MIN(
    ARRAYFORMULA(
        FILTER(C2:E2, C2:E2 - TODAY() > 0) - TODAY()
    )
) + TODAY()

Which first uses ARRAYFORMULA to subtract TODAY() from the dates, and if there are any negative values then FILTER them. Then take the MIN and add TODAY() again to get the date.
With this I created an array to use QUERY on:
{
    A2:B14,
    FILTER(
        C2:E14,
        C2:E2 = MIN(
            ARRAYFORMULA(
                FILTER(C2:E2, C2:E2 - TODAY() > 0) - TODAY()
            )
        ) + TODAY()
    )
}

From there, I used the QUERY to just filter out the blank ones.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run PHP client side Is it possible to launch a PHP script, client side, using an HTML web page?
If not, is there a way to embed the PHP into the HTML so it can run client side?

A: I think what you want is JavaScript. PHP is meant for server-side and JavaScript is meant for client side, among other things.

A: No. PHP cannot be run in browser. Learn JavaScript, alternatively CoffeScript if you don't like JavaScript's syntax.


text:
Q: All sites themes functions.php have been changed all of the themes functions.php have been changed for the sites on my web hosting server.
Because I couldn't copy it here without making it look ok, the code is here:
https://justpaste.it/18emu
Is this legit? The core functions.php doesn't have it.
Can plugins make changes to the files outside their currently directory? For example, can the plugins of site A make changes to the site B, even though they are not in the same directory?
Also, a "datalist" table has been added to their database.
Thank you for the answers.


text:
Q: Why does putting the first line of the expression on the same line as let not compile? In F# the following statement will fail with the following errors
let listx2 = [1..10]
    |> List.map(fun x -> x * 2)
    |> List.iter (fun x -> printf "%d " x)

Block following this 'let' is unfinished. Expect an expression.
Unexpected infix operator in binding. Expected incomplete structured construct at or before this point or other token.

However the following will compile
let listx2 =
    [1..10]
    |> List.map(fun x -> x * 2)
    |> List.iter (fun x -> printf "%d " x)

I also noticed that this compiles but has a warning
let listx2 = [1..10] |>
    List.map(fun x -> x * 2) |>
    List.iter (fun x -> printf "%d " x)

Possible incorrect indentation: this token is offside of context started at position (10:18). Try indenting this token further or using standard formatting conventions.

What is the difference between the first two statements?

A: When you have
 let listx2 = [1..10]

you are implicitly setting the indent level of the next line to be at the same character as the [. As given by the following rule for offside characters from the spec:

Immediately after an = token is encountered in a Let or Member context.

So in the first example, the |> is indented less than [ so you get an error, but in the second they are the same, so it all works.
I am not quite sure why moving the |> to the end of the line only gives a warning though.


text:
Q: Given the characteristic and minimal polynomial of a linear operator, find the possibilities of its' Jordan form
Given $T: V \to V$ a linear operator, and given $P_T(x) = x^2(x-1)^5(x+4)^4$ and $M_T(x) = x(x-1)^2(x+4)^3$. Find the possibilities of the Jordan form of $T$.

So I said this:

Eigenvalues $0,1,-4$. The sum of the sizes of the Jordan blocks for eigenvalue $0$ is 2, for eigenvalue $1$ is $5$, and for eigenvalue $-4$ is $4$. And then I said, the max block size of eigenvalue of $0$ is $1$, for eigenvalue $1$ is $2$, for eigenvalue $-4$ is $3$. So from this I figured out the following possibilities:
(I) For eigenvalue $0$: 2 blocks of size $1 \times 1$ each. For eigenvalue $-4$: one block of size $3 \times 3$ and one block of size $1 \times 1$. For eigenvalue $1$: two blocks $2 \times 2$ and one block $1 \times 1$.
(II) For eigenvalue $0$: 2 blocks of size $1 \times 1$ each. For eigenvalue $-4$: one block of size $3 \times 3$ and one block of size $1 \times 1$. For eigenvalue $1$: one block of size $2 \times 2$ and one block of size $3 \times 3$.
(III) For eigenvalue $0$: 2 blocks of size $1 \times 1$ each. For eigenvalue $-4$: one block of size $3 \times 3$ and one block of size $1 \times 1$. For eigenvalue $1$: one block $2 \times 2$, 3 blocks $1 \times 1$.

Is that correct or am I missing something?

A: The exponent of $(x-\lambda)$ in the minimal polynomial gives the size of the largest Jordan block with diagonal entries $\lambda$. For $\lambda=1$ this exponent is $2$, so there are no $3\times3$ Jordan blocks for this eigenvalue, and option (II) is wrong. The other two options are the only possibilities.

A: For all values of one-hundred-per-cent, there are $exactly$ 2 possible Jordan forms [your options (I) and (III)].

A: Apparently my answer was one-hundred-per-cent correct, I asked my professor about it.


text:
Q: Disqus events when comment is entered? I plan to use Disqus on my website. It has a "blog"-style layout. On the front page I want to display the comment-count for every blog-entry. I know I can connect to Disqus to get the counts but I would prefer to just save the comment - count into my database directly for the blog-entry when someone enters a comment.
So getting the count would not affect performance/load time of the main page. Is there any event that is fired if someone entered a comment on my page that I can listen to?
AngularJS would be a bonus but a simple javascript or jQuery solution would be helpful, too.

A: function disqus_config() {
    this.callbacks.onNewComment = this.callbacks.onNewComment || [];
    this.callbacks.onNewComment.push(function(comment) {
      // Code to store the comment count here.
    });
}

You can use this to add callbacks to certain events and hook into custom analytics systems. (The same would work for sending events to Google Analytics for instance. Here you'd just need to make an requests to your counter endpoint.
More info here: https://help.disqus.com/customer/portal/articles/466258-capturing-disqus-commenting-activity-via-callbacks


text:
Q: How can I allow a Silverlight client application to access a text file on an Apache server, but not allow browser access? I have a Silverlight 4 application that I am running embedded on a web page.  I would like to allow the Silverlight client to download a settings file by doing something like:
Uri url = new Uri(@"config\settings.xml", UriKind.Relative);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(url);

But ideally, I want to return a 403 Forbidden error if the user tries to access the file directly in a browser by visiting http://www.mywebsite.com/config/settings.xml
Is this possible using .htaccess?

A: Accessing the file from Silverlight or from a web browser looks the same to a web server, so there's not much you can do to guarantee users won't gain access.  The best you can do is obfuscate the steps it takes to get the file.
One thing you could do is to turn on HTTP Watch/Firebug/Wireshark and see if the Silverlight client sends any special HTTP headers identifying that it's Silverlight making the web requests.  If you can identify something unique, you can configure your web server accordingly so that only requests with that header are allowed.
If there is no such header, another option is to use some sort of authentication.  The credentials would be stored in the Silverlight client, so it wouldn't really be that secure, but again, you'd be obfuscating how to get the file.
You could also choose to compile the file into the client instead of accessing it over the web.
Edit:
It doesn't look look like Silverlight sends any identifying headers.  You could always append headers to your requests "manually" through your code.

A: Silverlight will retrieve data via a http request, as it is run client side. There will always be a way to access that file, unless Silverlight can use a custom http agent (which I could not find any reference to), then you can not restrict access.


text:
Q: Can't change git commit message with interactive rebase I have committed a file with message 'initial2'. Then I commit again with 'initial3'.
I execute the command git rebase -i HEAD~2
I see the vim editor with the following content.
pick 284d2e1 'initial2'
pick e32d7f3 'initial3'

I edit 'initial2' to 'initial2aaaaa' and close the editor with :wq.
However, my message is not changed. I still see initial2.

A: The commit message in the rebase editor is purely informational. It helps the user know which commit git is talking about (since most of us don't know the hashes of their commits by hearth). Changing it here has no effect on the plan, as you noticed. Only the command (pick) and the hash (284d2e1) are actually relevant to git itself.
If you want to change the commit message then change the pick command to reword (or just r) to pick the commit and edit its commit message. The line should look like this:
reword 284d2e1 'initial2'

A: pick 284d2e1 'initial2'
pick e32d7f3 'initial3'

when you see the above, change the first line to following (replace pick with reword)
reword 284d2e1 'initial2'

Then try exiting with :qa.
You will be given option to edit your commit message in vm.
There you can edit and exit with :qa again.
Then you will find your commit message is edited.

A: Just to be clearer, following @Narasimha,

*

*Replace pick with reword

*I exit with :x

*Edit the same commit message again

*Exit with :x


text:
Q: Windows 10 finds pip but not python I have done everything the documentation says to.

*

*I added pip path and it is working but the python command is not working. Image of path to my python38 DLL

*The pip path which I added: C:\Users\Harshal\AppData\Local\Programs\Python\Python38\Scripts
python path : C:\Users\Harshal\AppData\Local\Programs\Python\Python38

*python command is not working .pip works

A: In some cases, py command works as well as python command, so you can try py:
py -V
py -m pip # this is for pip, exactly for this python version

A: Add your python to system environment variables like your path.
or Reinstall python and check the Add to path Checkbox while installing
Add to path


text:
Q: Boolean in array with looping i am simulate some graph and there is some problem on give some boolean condition for some array in looping, and this is the code
var check = false;
for (var k in GexfJS.graph.edgeList) {
    var _edge = GexfJS.graph.edgeList[k]
    if ( (_edge.source == _curre) && ( _edge.target != _nodeIndex) ) {
        var _node = GexfJS.graph.nodeList[_edge.target];
        _str += '

' + _node.label + '' + ( GexfJS.params.showEdgeWeight && _edge.weight ? ' [' + _edge.weight + ']' : '') + '
';
    }
}

My goal is, when the edge have been selected by some node it wont to select node it again because when the edge select the node it will have some action , in my graph there is a lot of edges from the nodes. so how code i insert to that algorithm above in use boolean condition for give condition to the node that have been selected from the edges?

A: Dont use boolean condition, just try object for it, like check={};
then put the condition
if ( (_edg.target == _curra) && (_edg.source != _nodeIndex)) {
    var _nod = GexfJS.graph.nodeList[_edg.source];
    if(check[_nod.label] != true){
        if(_n != _nod){
        _str += '';
        }
        }
        check[_nod.label] = true;
    }


text:
Q: Detect coordinate system from dataset I've been provided with a dataset containing some coordinates, but I don't recognise the coordinate system used. They look like standard UTM coordinates but the values don't match up with what I expect, which are locations in Scotland, UK.
For example, a random record gives GIS_X as 349275.0 and GIS_Y as 636198.0. Using these coordinates along with zone 30, plugging these values into http://www.rcn.montana.edu/Resources/Converter.aspx results in WGS coordinates not far from the equator, which is evidently wrong.
The datasource is checked daily for various errors so I'm fairly certain the data provided to me is correct; any ideas for how these values might make sense, given the expected result?

A: The coordinates you have given above are very much in Scotland (Galashiels) if you assume they are in epsg 27700 (i.e. ordnance survey grid). It looks like someone or some process has entered the information in an unexpected coordinate system.
There is no way to "detect" the coordinates system. You could probably rule out a few by looking at max / min bounds, but  usually it is provided as metadata with the file or in the database.


text:
Q: adb: failed to install Hello while trying to run my Flutter Application on Real Android device im getting following error
Launching lib/main.dart on SM G973F in debug mode...
lib/main.dart:1
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
✓  Built build/app/outputs/flutter-apk/app-debug.apk.
Error: ADB exited with exit code 1
Performing Streamed Install

adb: failed to install /Users/name/Desktop/project/application/poi/build/app/outputs/flutter-apk/app.apk: Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES: Failed collecting certificates for /data/app/vmdl639070508.tmp/base.apk: Failed to collect certificates from /data/app/vmdl639070508.tmp/base.apk using APK Signature Scheme v2: SHA-256 digest of contents did not verify]
Error launching application on SM T500.

I tried :
updating android studio
flutter upgrade
flutter pub get
.....
But found no solution yet
Hope anyone can help

A: In your manifest, add android:exported="true".
example:
<activity
        android:name="com.example.packssas.MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

A: Only increase the storage size of your device
enter image description here

A: Check the Available Storage in the machine you are developing with, you might face this issue if you are running in low storage.
Another solution is actually a dummy one, but it works, which is to restart your machine.


text:
Q: Eclipse Tool Bar run button does not appear My eclipse luna toolbar only displays add file, breakpoint, and save buttons. There isn't anything else there. I tried to go to Perspective, Customize perspective, but there it says the launch group (run, debug) is already checked. Anyone help?

A: Found this link on the eclipse luna documentation Showing and hiding menu items and toolbar buttons have you tried the steps provided on that documentation?
If yes, then could you try to create a new workspace and see whether the toolbar button is visible or not. This problem also happened to me once and creating a new workspace seems fixed it.
hope that help


text:
Q: How to make a web app retain information? Ok... so a user enters info into the journal field and hits submit, and a function gets called on the information they have submitted, which I call changeTextComment().  That function calls another function and so on as the info is formatted and placed in the cue, as in a Facebook commentary.
I need this information saved so it can be recalled later, in local storage, making the app not refresh every time I restart it. So...
<script>
function appCache() {
// Check browser support
// this is experimental for local storage...
more here:    http://www.w3schools.com/html/html5_webstorage.asp

if (typeof(Storage) != "undefined") {
     localStorage.setItem(para);
            // Retrieve
            document.getElementById("journal").innerHTML = localStorage.getItem(para);
        } else {
            document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
        };
        </script>

So looking at the appCache function it seems like it might work except I need to identify what the key variable is that will be stored and then retrieved.
I think this is the variable userInput, as any time the user hits the 'add to journal' button this variable is used to store the user input and then put into the changeTextComment() function.
I am wondering if this is the simplest way to deal with this whole thing...  I do not yet understand databases, but wondering if that would be easier to learn.
In this case, I would add the function Appcache() to the function changeText() such that it caches the variable and then how would I set it up to then feed the value of the variable's cached info into changeText() upon launch of the app?
Every submission to the journal will have a unique value.
Heres the ChangeTextComment() Function... still sorting out how to use classes in css to simplify these functions:
function changeTextComment(){
// to be modified from the above to change the location of the dump
var userInput = document.getElementById('userInput').value;
// get the input from the user
var panel = document.createElement("div");  // create a parent divider for everything

// assignment of attributes
panel.setAttribute("class","panel panel-default panel-body");
panel.setAttribute("id","panelBody");
var para = document.createElement("P");
var t = document.createTextNode(userInput);
para.appendChild(t);

// add comment area
var c = document.createElement("INPUT");
c.setAttribute("type", "text");
c.setAttribute("id", "comment");
c.setAttribute("placeholder", "comment here");
c.setAttribute("class", "form-control input-lg");

// add comment button attempt -- success <> now try to put it in the textarea
var d = document.createElement("INPUT");
d.setAttribute("type","button");
d.setAttribute("class","btn btn-info active pull-right");
d.setAttribute("onclick","commentThis()");
d.setAttribute("value","Add Comment");
panel.appendChild(para);  // this is where a comments piece would go

// place the item
var destination = document.getElementById("journal")
//destination.insertBefore(Commentaryarea, destination.firstChild);
//destination.insertBefore(panel, destination.firstChild);
destination.insertBefore(panel, destination.firstChild);
panel.appendChild(c);
panel.appendChild(d);

document.getElementById("userInput").value = "";
document.getElementById("userInput").focus();}
</script>

<script>
function setText(a){
    document.getElementById("userInput").value = a
    document.getElementById("userInput").focus();
}
</script>

A: When you say "stored locally", do you mean stored in the visitors browser, i.e. with only themselves being able to see it and retrieve it? Or do you want other users to be able to see the data, and/or the commenter to be able to see it if they log in later from another location?
If it's the latter then you need to store it on the server side, and you're going to need a database for that. If all you need is to store journal entries then mongoDB is easy to set up with javascript, but if you have a lot of relations (journal entries being associated with users, comments on entries being associated with users and entries, ect) then perhaps an SQL database would suit you better.


text:
Q: Fractions and decimals in different bases How exactly would I add fractions of different bases?
For example: $ (\frac 23)_8 + (\frac 57)_8$
and is their any difference to that of adding those same numbers but in decimal form base 8?

A: 2 ways to do this.
The easy but half assed way.
$2,3,5,7$ in base $8$ are the same in base $10$.  So $\frac 23_{10}=\frac 23_8$ and $\frac 57_{10}=\frac 57_8$.
So $\frac 23 + \frac 57 = \frac {29_{10}}{21_{10}}=\frac{35_8}{25_8}=\frac {35}{25}_8$.
Now the "real" way (where we work in base 8 directly without constantly translating back and forth from base 10.
$\frac 23 + \frac 57 = \frac {2*7}{3*7}+\frac {5*3}{7*3}=\frac {2*7+5*3}{3*7}=\frac {(1*8+6)+(1*8+7)=2*8+(6+7)=2*8+(1*8+5)=3*8+5}{2*8+5}=\frac {35_8}{25_8}=\frac {35}{25}_8$.

A: first we should make the denominator same to add both of them
therefore (2*7/3*7)8=(14/21)8  ----1
          (5*3/7*3)8=(15/21)8   ----2
now we can equation 1 and 2
since the denominator and the base both are same
therefore we get
(29/21)8 is the answer.


text:
Q: insert into Select not working for one column I have Insert into select Statement that is not working for one column 'DataValue_Money_USD' which is money field!
Select Statement is pulling 5 rows for DataValue_Money_USD is not null and values are
1.04
520.00
13.52
23.92
2.08

still it inserts null in that column for those 5 rows in DataWorking table!
I do get 5 rows affected message twice printed in messages tab when I run it
INSERT INTO [dbo].[DataWorking]
    ([TranData_ID]
    ,[Tran_ID]
    ,[DataField_ID]
    ,[DataValue_Money_USD])
SELECT
     [TranData_ID]
    ,[Tran_ID]
    ,[DataField_ID]
    ,[DataValue_Money_USD]
FROM [dbo].[TData]
WHERE Tran_ID = 1706 and DataValue_Money_USD is not null


text:
Q: Use window.print content to download a web page as pdf I would like to have a link that when is clicked, automatically starts the download of the printable version of the web page.
I'm using Moodle. The content I want it's exactly the same  If I download the page using ctrl + p and saving as pdf or using
Download web page

I want exactly that content because using this way, the header, sidebar and footer is removed. I don't want css.
I'm not using this because this doesn't work in some browsers.
I'd rather not using pdf libraries like tcpdf because Moodle loads the content in a dynamic way and send this to a libraries like that is a mess.
I tried using sites like pdfcrowd.com but this kind of sites don't work when the site you want to convert to pdf uses  a server-side session to identify the user.

A: **There is easy ways to use jsPDF its very simple just you will use JSpdf Library **

function onClick() {
  var pdf = new jsPDF('p', 'pt', 'letter');
  pdf.canvas.height = 72 * 11;
  pdf.canvas.width = 72 * 8.5;

  pdf.fromHTML(document.body);

  pdf.save('test.pdf');
};

var element = document.getElementById("clickbind");
element.addEventListener("click", onClick);

A: I don't believe that there is a way to do this with window.print(). However, there are HTML to PDF converters available for free, and you could automatically start a download with that. An example of this would be jsPDF, a free library for converting HTML to a PDF with Javascript


text:
Q: Can I paste plain text by default? I regularly copy and paste text between spreadsheets, emails, browser windows, etc. I can't think of a single time when I've wanted to keep the formatting from the source text.
I already know about the following workarounds:

*

*Use "Edit" → "Paste Special" → "Unformatted text"

*Paste to Notepad and copy from there

*Install a program that takes over the clipboard

What I want is to tell Windows to just do this by default.
Is this possible?

A: I keep running into this too. Other than using/writing a program to strip the extra formatting, the simplest way I've found to strip formatting is by pasting the text into the "Run" windows (reachable by WIN + R) and re-copying it from there.
So I end up doing this, really quickly: CTRL+C, WIN + R, CTRL+V, SHIFT+HOME, CTRL+C, ALT+TAB, CTRL+V - I can't help but wonder now if I've been doing this for too long...
Only works for single-line text, though.

A: I can't provide you with a simple solution, but like the others, I will provide you with a workaround:
A shortcut to your first option is to use Ctrl + Alt + v to pop up the Paste Special dialog without using the mouse.  Typing u to jump to Unformatted Unicode Text entry (or u u to get to the non-Unicode version) and then Enter will do it for you.  Not perfect, but built in.

A: Direct answer. No.
There is no control of the standard clipboard in Windows. This is the reason a lot of applications provide this feature through trapping the pasted text beforehand.
PureText as mentioned already is the way to go.

A: This is not determined by Windows, but by the app to which you are pasting.
For MS Word, set the default by File -> Options -> Advanced -> Cut, copy, and paste:

Alternatively, if you want to keep the default settings yet paste unformatted text occasionally, you may use Ctrl+v, Ctrl, t.  (Note:  this is NOT Ctrl+t.)
For Excel you may paste unformatted text with Ctrl+v, Ctrl, m.

A: Using an app like ClipMate, which is a clipboard manager (& commerical app), you can press the Win + W keys together to clear the formatting of whatever is currently on the clipboard, making it plain text.

A: When pasting to Word (probably works in other Office applications as well) you can use Ctrl+Alt+V and then just arrow down to Unformatted Text or Unformatted Unicode Text and press enter. It is the same as going to Paste Special in the menu, but a lot faster :)

A: This is a pretty decent compromise: PureText.

This may not be a direct answer to what you asked, but this may be of use to someone else with a more general version of your question.

A: Unfortunately, no. And I believe this is by design.
The issue is that the Windows clipboard does not have to store the data. It is effectively a clearing house where any application can list the data that was just copied (or cut) and offer it up to any application (including itself) to be pasted. The clipboard contains a list of formats in which the data is available, and if the application chooses to do so, the data itself in some of those formats.
The application that processes a Paste operation then has the option to choose the data format that best suits it. Some applications (e.g. Notepad) will only accept one particular format (such as plain text) and simply do nothing if that format is not available. Others pick a preferred format by default but provide a UI for choosing among alternatives that can be understood by that application.
In principle a program could be written that monitors the clipboard for new content and flattens any non-text content to just plain text. There is an event available to notify such a monitor of new content on the clipboard. However, I suspect that implementing such a thing would break a fair number of programs, and possibly in surprising ways.
The simple workaround in stock XP is to use Notepad to flatten the data when needed, or to use one of the many tools that improve the clipboard by implementing a stack, providing a view of its content, and so forth.
If you want to try building a tool yourself, might benefit from this question over at SO, and its related questions....

A: Having checked annoyances.org and a couple more places the consensus I found was that there are no registry tweaks regarding Windows Clipboard behavior. I did find another freeware tool (ArsClip) that can do what you're looking for.

A: On Windows in most Microsoft Office applications, the fastest way is to hit Ctrl + Alt + V and once the the dialog pops up hit U then Enter. This selects the Unformatted Text option in the dialog.

A: There is not way to do this by default, but with a bit of hackery, we can work around that.
You will need:

*

*PlainTextClipboard

*AutoIT Script (you can use AutoHotKey, I just don't know that scripting language)

Create an AutoIt Script with the following code:
$ptcPath = "C:\Program Files (x86)\Plain Text Clipboard\PlainTextClipboard.exe"
HotKeySet("^v", "PastePlainText")

While True ;Keep it running indefinitely.
WEnd
HotKeySet("^v") ;unregister the hotkey

Func PastePlainText()
    Run($ptcPath);
    Send(ClipGet())
EndFunc

When you press Ctrl + V, this will run the PlainTextClipboard program, then send the contents of your clipboard to the current window. Unfortunately, it will send the contents one character at a time, so it is a bit slow. It's a problem I'm working on, but it should serve as a reasonable start. If there are any AutoHotKey/AutoIT gurus out there, feel free to make your own version of this script. I'll update it as soon as I figure out how to solve the problem.

A: I'm fond of ClipX - it gives you multiple clipboards, and if you paste text using ClipX, it's been flattened to plain text.
So, you can copy normally, but if you want paste plain text, you hit ctrl-shif-V instead of ctrl-V, and then select the first item to paste it plain. It's free, and it's system wide, so it's about 75% or more of what you want.

A:
I share your problem.  Frustrating, isn't it?
I use [this guide][1] to prepare a visual basic macro and define a shortcut key.
[1]: https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/msoffice/?p=264

--> This has also been my preferred solution. My VBA Makro is this:
Sub PastePlainText()
    Selection.PasteAndFormat wdFormatPlainText
End Sub

I attached it to the shortcut Ctrl+Alt+V. It works perfectly throughout all Word/Office version that I've been using for more than 10 years now.

A: I achieve this by converting when I want to using a powershell script (plaintext.ps1):
#Convert clipboard to plain text
$clip = Get-Clipboard
Set-Clipboard $clip

Write-Output "PlainTextClipboard ""$($clip)"""

You can call that by your preferred method.
I call mine from a batch file (@powershell.exe -File C:\batch\plaintext.ps1) so that I can just type plaintext into the run bar to do a conversion. Also I trigger it from a toolbar button on the start menu. Depends if I'm feeling mousey or keyboardy :)


text:
Q: how to use xml with style tags using angularjs I am working in an angularjs application, i need to parse xml file in my app, which contains HTML style attributes in to it.
Have use xml2json and X2JS pluging to convert the data, while using the plugin it convert all data into json including the HTML styles.
If anyone face this issue please suggest some idea to rectifiy my problem.
Any help would be thankful.
Here is the sample code
<?xml version='1.0' encoding='UTF-8' ?>
<test>
<datas>
<data>This is my sample  xml  file</data>
<data>This is the second line of the
content
</data>
<data>This is  third line </data>
</datas>
</test>


text:
Q: Let ${x_k}={2^{(-1)}}^{k}(1+1/k)$ Find $\liminf x_k$ and $\limsup x_k$. Let ${x_k}={2^{(-1)}}^{k}(1+1/k)$
Find $\liminf x_k$ and $\limsup x_k$.
I tried in this way.
First, I split {$x_k$} into two subsequences; $x_{2j}=2+\frac{1}{j}$ and $x_{2j-1}=\frac{1}{2}+\frac{1}{4j-2}$
Then {$x_{2j}$} is monotonically decreasing from max 3 to a limit 2,
and  {$x_{2j-1}$} is monotonically decreasing from max 1 to a limit 1/2.
It follows that $\frac{1}{2}\le x_k\le 3$, thus $\frac{1}{2}\le \liminf x_k \le \limsup x_k \le 3$
Then by picking {$x_{2j}$}, we can verify that $\lim_{j\to \infty}x_{2j}=2$
and by picking {$x_{2j-1}$} we can verify that $\lim_{j\to \infty}x_{2j-1}=\frac{1}{2}$
My TA gave me one point out of five to this answer.
I have tried to figure out why and my guess is
maybe because {$x_{2j}$} and {$x_{2j-1}$} are not the only subsequences that I can choose from {$x_{k}$}.
Or because I did not use the definition of cluster point.
Please give me some help!

A: (1) $x_{2j}=2+\frac{1}{4j}$. That does not affect the answer much, but it is still an error.
(2) $x_{2j-1}=-(\frac{1}{2}+\frac{1}{4j-2})$. You forgot the minus sign. That does make a difference. You end up with $\frac{1}{2}$ instead of $-\frac{1}{2}$. Also the subsequence is increasing not decreasing.
(3) you do not explicitly deal with the fact that you are asked for lim sup and lim inf. So you need to explain why you have got the largest and smallest limit points.


text:
Q: Hide element issue So I am trying to hide a DIV that sits inside a td. Issue I am facing is that the attached code fades the div perfect fine but the table space stays there. How do I make this table space disappear completely?
Table:

 This disappears

A: Just to clarify, the solution was to wrap the table in another div and hide that div instead.


text:
Q: making a board terminal with blessed library in python I'm making a game with blessed library in python, I didn't manage to get it to work. I want to make a board of 20×20.
I managed to do it with colored in this way:
import colored

nb_rows = 20
nb_cols = 20

to_display = ''
for row_id in range(nb_rows):
    for col_id in range(nb_cols):
            if (row_id + col_id) % 2 == 0:
                to_display += colored.bg('yellow') + colored.fg('red')
            else:
                to_display += colored.bg('green') + colored.fg('blue')

            to_display += '--' + colored.attr('reset')

    to_display += '\n'

print(to_display)

I want to do the same, but in blessed
Any help, thanks


text:
Q: Localizing percentages with C# and jQuery I have an ASP.NET MVC app that must work in German.
string percentageString = form["percentage"]; // pretend "11.3" is the value sent from the view;
decimal percentage = 0;
if (Decimal.TryParse(percentageString, out percentage))
{
  if ((percentage >= 0) && (percentage <= 100))
    model.Percentage = percentage * (decimal).01;
  else
    errors.Add("The percentage must be between 0 and 100.");
}
else
  errors.Add("Please enter a percentage.");

My challenge is, in English, the above works. However, in German, it fails. The first error (The percentage must be between 0 and 100) occurs. The problem is that when the Decimal.TryParse occurs, the percentage value is 113. I suspect it has to do with the use of commas vs decimals across cultures. Yet, I'm not sure how to remedy this.
I'm using the jQuery slider in my view to set this value. Currently, it looks like this:
<input id="percentageSlider" name="percentageSlider" data-slider-id="percentageRateSlider" type="text" data-slider-min="0" data-slider-max="100" data-slider-step="0.1" value="@Model.Percentage" />
<input id="percentage" name="percentage" class="form-control" type="text" />

...

var percentage = @Convert.ToString(Model.Percentage.Value, System.Globalization.CultureInfo.InvariantCulture);
var percentageSlider = $('#percentageSlider').slider({
  formatter: function (value) {
    return value.toFixed(1) + '%';
  },
  value: percentage,
  precision: 1
}).on('slide',
  function (s) {
    $('#percentage').val(s.value.toFixed(1));
  })
;

How can I get this to work in German? Everything looks correct to me.

A: In German, the decimal point is represented by a comma and the thousands separator is a full stop/period. So 11.3 is 11 thousand 300 percent, or 113.  If someone German was asked to input a percentage, they would enter 11,3 and this should be parsed correctly.  If you want to make it work the same way regardless of the country, you could say Decimal.TryParse(percentageString, NumberStyles.Number, CultureInfo.InvariantCulture, out percentage).


text:
Q: How to return the parent observable value? I'm trying to nest some http requests using mergeMap.
The API I'm using returns the data in parts(pages), so I need to make more requests depending in the number of total pages.
Since I need to make a request to know how many pages are. I always make the first one in the first page. With the result of that one I can know how many pages are, and start making the other requests (starting from page 2).
Once I subscribe to the returned observable I get all the data of the requests made within the mergeMap, except the result of the first one (the one with page = 1).
Is there a way to return the first request data?
I tried to start the inner request with page = 1, but I don't like it that way because I already have the data of that request.
This is the return value of the function:
 return this.getScrobblesFromAPI( userName, oneWeekAgoUnix, 1 )
    .pipe(
      mergeMap( data => {
        const totalPages: number = parseInt(data['recenttracks']['@attr'].totalPages, 10);
        const pages: number[] = [];
        //Starting from page 2
        for (let i = 2; i <= totalPages; i++) {
          pages.push(i);
        }
        return from(pages).pipe(
          mergeMap( page => this.getScrobblesFromAPI(userName, oneWeekAgoUnix, page)),
        );
      }),
      map( data => data['recenttracks']['track'].slice(1) )
  );

This function returns the observable of the http.get() (HttpClient)
private getScrobblesFromAPI( userName: string, from: number, page: number ){
   // http : HttpClient
   return this.http.get('url & params');
}

A: I can think of two options to solve this:

*

*Create an empty array and push all your data in there. At the end of the outer pipe return that array so it will go into subscribe callback.

*simply use concat function to concat the data from the first call with the additional Observables which will retrieve the remaining pages.
return concat(
    of(data),
    from(pages).pipe(
      mergeMap( page => this.getScrobblesFromAPI(userName, oneWeekAgoUnix, page)),
    )
);


text:
Q: Give a recursive definition with initial condition...how did they get the answer? The function $f (n) = 5n + 2, n = 1, 2, 3, \ldots $
Im sure its a simple problem, but im really confused...how did they get the answer ? could someone explain
$f (n) = f (n - 1) + 5, f (1) = 7$
thank you

A: Since it's recursive, it makes sense for $f(n)$ to be somehow related to $f(n-1)$. Of course, you need to start somewhere, so you might as well define $f(1)$.
Note that the original function satisfies $f(1) = 7$, and that when $n$ increases by $1$, we add $5$ to the function.
That is: $f(n+1) = 5(n+1) + 2 = 5n + 5 + 2 = (5n + 2) + 5 = f(n) + 5$.
Now replace $n+1$ above with $n$.

A: To get $f(n)$ from $f(n-1)$ you add $5$. So the function must have the form $f(n) = 5n+c$, where $c$ is some constant to be determined. Since you know $f(1)$, you can figure out $c$.
In particular, $f(1) = 5+c = 7$, so $c=2$. Hence the function is $f(n) = 5n +2$.


text:
Q: My Controller Won't Work! I'm trying to create a module which displays a CMS block with a custom route on which I can add some logic etc.
But I can't get the Module's controller to work.
The route I'm trying to create is www.example.com/wholesalers/info but when I go to that page url I get a 404 page.
I've followed this mageplaza tutorial but I can't get it to work.
I've been looking and looking but can't see what I'm missing...
Module Structure
app/code/Holy/
└── Wholesalers
    ├── composer.json
    ├── registration.php
    ├── Block
    │   └── Info.php
    ├── Controller
    │   └── Info
    │       └── Index.php
    ├── etc
    │   ├── module.xml
    │   └── routes.xml
    └── view
        └── frontend
            ├── layout
            │   └── wholesalers_info_index.xml
            └── templates
                └── wholesale-info.phtml

composer.json
{
    "name": "Holy/module-Wholesalers",
    "description": "",
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "psr-4": {
            "Holy\\Wholesalers\\": ""
        },
        "files": [
            "registration.php"
        ]
    }
}

registration.php
<?php
/**
 * @category   Local
 * @package    Holy_Wholesalers
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Holy_Wholesalers',
    __DIR__
);

etc/module.xml
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Holy_Wholesalers" setup_version="1.0.0"/>
</config>

etc/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="wholesalers" frontName="wholesalers">
            <module name="Holy_Wholesalers" />
        </route>
    </router>
</config>

Controller/Info/Index.php
<?php
/**
 * @category   Local
 * @package    Holy_Wholesale
 */

namespace Holy\Wholesalers\Controller\Info;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $_pageFactory;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $pageFactory)
    {
        $this->_pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
        return $this->_pageFactory->create();
    }
}

view/frontend/layout/wholesalers_info_index.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Holy\Wholesalers\Block\Info" name="customer_wholesale_info" template="Holy_Wholesalers::wholesale-info.phtml" />
    </referenceContainer>
</page>

view/frontend/templates/wholesale-info.phtml

Hello World

And...
My Magento instance is in developer mode and I've cleared the cache etc
php bin/magento cache:flush
php bin/magento setup:upgrade

A: Try moving your routes.xml to etc/frontend/routes.xml
cache:clean + setup:upgrade + setup:di:compile

A: Try moving etc/routes.xml file to etc/frontend/routes.xml


text: Q: Pulling programs from system tray in windows? I'm currently updating an old program written in C that essential acts as a window manager for windows. I'm trying to add some new functionality, more specifically a system tray. Is there any way I can access the programs that are currently in the windows system trays, so I can place them on my custom taskbar?


text:
Q: How can I catch an Entity Framework error, report on it and then leave the function with that same exception? I have this code in my application. If the insert fails, I would like to add information about the failure to the Audit table. Perhaps the inner exception message from the exception in the note area. Is there a way that I could do this and then still have the procedure exit with that same exception details back to the caller?
    [Route("Post")]
    [ValidateModel]
    public async Task<IHttpActionResult> Post([FromBody]Phrase phrase)
    {
        phrase.StatusId = (int)EStatus.Saved;
        UpdateHepburn(phrase);

        db.Phrases.Add(phrase);

        var audit = new Audit()
        {
            Entity = (int)EEntity.Phrase,
            Action = (int)EAudit.Insert,
            Note = phrase.English,
            UserId = userId,
            Date = DateTime.UtcNow,
            Id = phrase.PhraseId
        };

        db.Audits.Add(audit);

        await db.SaveChangesAsync();

        return Ok(phrase);
    }

A: You can catch the original exception and rethrow it afterwards:
try
{
    await db.SaveChangesAsync();
}
catch (Exception)
{
    try
    {
        // TODO: add to the audit here, also in a try/catch as this might fail as well
    }
    catch
    {
    }

    // rethrow the original exception
    throw;
}


text:
Q: Entity Framework 6 Navigation Property Collections I am developing a database first application in VB.NET using entity framework version 6.1.1 and sql server 2008. I have some pure join tables that link many to many relationships between two tables. My entities are untracked.
Here are basic examples of the classes (generated from the EF tt files) that I am using:
Public Class Part
    Public Property id As Long
    Public Property name As String
    Public Overridable Property CarModels As ICollection(Of CarModel) = New HashSet(Of CarModel)
End Class

Public Class CarModel
    Public Property id As Long
    Public Property name As String
    Public Overridable Property Parts As ICollection(Of Part) = New HashSet(Of Part)
End Class

When I am updating fields for an entity, I set the values, and then include code like this:
obj.Name = "New Name"
context.Entry(obj).State = EntityState.Modified
context.SaveChanges

That will save the Name value to the database as I expect. My problem is trying to add a new CarModel to an existing part, or remove an existing CarModel from a part. I've tried several things but have not found a solution. Here's an example of my code:
Dim p As Part = context.Parts.where(Function(it) it.id.equals(1)).first 'Part I am working with
Dim c As CarModel = context.CarModels.where(Function(it) it.id.equals(1)).first 'Car Model I want to associate to the part
p.CarModels.Add(c) 'Add the Car Model to the part collection

context.Entry(p).State = EntityState.Modified

context.SaveChanges

No error is thrown. When I am debugging the CarModel is Added to the Part.CarModel collection. However, the changes are not committed to the database. If I add a NEW Part and use similar code it work, but I cannot add or remove from an existing collection and get it to commit to the database.

A: I haven't used VB in 6 years, so this might not be exactly right, but this will give you a general idea on how it works.
Dim p As Part = context.Parts.where(Function(it) it.id.equals(1)).first 'Part I am working with
Dim c As CarModel = context.CarModels.where(Function(it) it.id.equals(1)).first 'Car Model I want to associate to the part

Dim newPart As Part = New Part()
newPart.id = p.id
newPart.name = p.name
newPart.CarModels = c

context.Add(p)

context.SaveChanges()

A: I took a look at the context itself, and this line was in the constructor of the context:
Configuration.AutoDetectChangesEnabled = False

That is what was causing my particular problem. I read somewhere (after I found that line) that it is recommended to not turn set AutoDetectChangesEnabled to false unless there is a very long running process, and in that case to set it back to true after the process had completed. Removing that line from the context constructor solved my problem.


text:
Q: How to send utf-8 e-mail? how to send utf8 e-mail please?
import sys
import smtplib
import email
import re

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def sendmail(firm, fromEmail, to, template, subject, date):
    with open(template, encoding="utf-8") as template_file:
        message = template_file.read()

    message = re.sub(r"{{\s*firm\s*}}", firm, message)
    message = re.sub(r"{{\s*date\s*}}", date, message)
    message = re.sub(r"{{\s*from\s*}}", fromEmail, message)
    message = re.sub(r"{{\s*to\s*}}", to, message)
    message = re.sub(r"{{\s*subject\s*}}", subject, message)

    msg = MIMEMultipart("alternative")
    msg.set_charset("utf-8")

    msg["Subject"] = subject
    msg["From"] = fromEmail
    msg["To"] = to

    #Read from template
    html = message[message.find("html:") + len("html:"):message.find("text:")].strip()
    text = message[message.find("text:") + len("text:"):].strip()

    part1 = MIMEText(html, "html")
    part2 = MIMEText(text, "plain")

    msg.attach(part1)
    msg.attach(part2)

    try:
        server = smtplib.SMTP("10.0.0.5")
        server.sendmail(fromEmail, [to], msg.as_string())
        return 0
    except Exception as ex:
        #log error
        #return -1
        #debug
        raise ex
    finally:
        server.quit()

if __name__ == "__main__":
    #debug
    sys.argv.append("Moje")
    sys.argv.append("newsletter@example.cz")
    sys.argv.append("subscriber@example.com")
    sys.argv.append("may2011.template")
    sys.argv.append("This is subject")
    sys.argv.append("This is date")

    if len(sys.argv) != 7:
        exit(-2)

    firm = sys.argv[1]
    fromEmail = sys.argv[2]
    to = sys.argv[3]
    template = sys.argv[4]
    subject = sys.argv[5]
    date = sys.argv[6]

    exit(sendmail(firm, fromEmail, to, template, subject, date))

Output
Traceback (most recent call last):
  File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 69, in <module>
    exit(sendmail(firm, fromEmail, to, template, subject, date))
  File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 45, in sendmail
    raise ex
  File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 39, in sendmail
    server.sendmail(fromEmail, [to], msg.as_string())
  File "C:\Python32\lib\smtplib.py", line 716, in sendmail
    msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\u011b' in position 385: ordinal not in range(128)

A: You should just add 'utf-8' argument to your MIMEText calls (it assumes 'us-ascii' by default).
For example:
# -*- encoding: utf-8 -*-

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

msg = MIMEMultipart("alternative")
msg["Subject"] = u'テストメール'
part1 = MIMEText(u'\u3053\u3093\u306b\u3061\u306f\u3001\u4e16\u754c\uff01\n',
                 "plain", "utf-8")
msg.attach(part1)

print msg.as_string().encode('ascii')

A: The question asked by Martin Drlík is 7 years and 8 months old... And nowadays, thanks to the developers of Python, encoding problems are solved with version 3 of Python.
Consequently, it is no longer necessary to specify that one must use the utf-8 encoding:
#!/usr/bin/python2
# -*- encoding: utf-8 -*-
...
    part2 = MIMEText(text, "plain", "utf-8")

We will simply write:
#!/usr/bin/python3
...
    part2 = MIMEText(text, "plain")

Ultimate consequence: Martin Drlík's script works perfectly well!
However, it would be better to use the email.parser module, as suggested in email: Examples.

A: The previous answers here were adequate for Python 2 and earlier versions of Python 3. Starting with Python 3.6, new code should generally use the modern EmailMessage API rather than the old email.message.Message class or the related MIMEMultipart, MIMEText etc classes. The newer API was unofficially introduced already in Python 3.3, and so the old one should no longer be necessary unless you need portability back to Python 2 (or 3.2, which nobody in their right mind would want anyway).
With the new API, you no longer need to manually assemble an explicit MIME structure from parts, or explicitly select body-part encodings etc. Nor is Unicode a special case any longer; the email library will transparently select a suitable container type and encoding for regular text.
import sys
import re
import smtplib
from email.message import EmailMessage

def sendmail(firm, fromEmail, to, template, subject, date):
    with open(template, "r", encoding="utf-8") as template_file:
        message = template_file.read()

    message = re.sub(r"{{\s*firm\s*}}", firm, message)
    message = re.sub(r"{{\s*date\s*}}", date, message)
    message = re.sub(r"{{\s*from\s*}}", fromEmail, message)
    message = re.sub(r"{{\s*to\s*}}", to, message)
    message = re.sub(r"{{\s*subject\s*}}", subject, message)

    msg = EmailMessage()
    msg["Subject"] = subject
    msg["From"] = fromEmail
    msg["To"] = to

    html = message[message.find("html:") + len("html:"):message.find("text:")].strip()
    text = message[message.find("text:") + len("text:"):].strip()

    msg.set_content(text)
    msg.add_alternative(html, subtype="html")

    try:
        server = smtplib.SMTP("10.0.0.5")
        server.send_message(msg)
        return 0
    # XXX FIXME: useless
    except Exception as ex:
        raise ex
    finally:
        server.quit()
        # Explicitly return error
        return 1

if __name__ == "__main__":
    if len(sys.argv) != 7:
        # Can't return negative
        exit(2)

    exit(sendmail(*sys.argv[1:]))

I'm not sure I completely understand the template handling here. Practitioners with even slightly different needs should probably instead review the Python email examples documentation
which contains several simple examples of how to implement common email use cases.
The blanket except is clearly superfluous here, but I left it in as a placeholder in case you want to see what exception handling might look like if you had something useful to put there.
Perhaps notice also that smtplib allows you to say with SMTP("10.9.8.76") as server: with a context manager.

A: For whom it might interest, I've written a Mailer library that uses SMTPlib, and deals with headers, ssl/tls security, attachments and bulk email sending.
Of course it also deals with UTF-8 mail encoding for subject and body.
You may find the code at: https://github.com/netinvent/ofunctions/blob/master/ofunctions/mailer/__init__.py
The relevant encoding part is
message["Subject"] = Header(subject, 'utf-8')
message.attach(MIMEText(body, "plain", 'utf-8'))

TL;DR: Install with pip install ofunctions.mailer
Usage:
from ofunctions.mailer import Mailer

mailer = Mailer(smtp_server='myserver', smtp_port=587)
mailer.send_email(sender_mail='me@example.com', recipient_mails=['them@example.com', 'otherguy@example.com'])

Encoding is already set as UTF-8, but you could change encoding to whatever you need by using mailer = Mailer(smtp_srever='...', encoding='latin1')

A: In my company we use next code
import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

...

msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = from_addr
msg['To'] = to_addr
msg.attach(MIMEText(html, 'html', 'utf-8'))
# or you can use
# msg.attach(MIMEText(text, 'plain', 'utf-8')

server = smtplib.SMTP('localhost')
server.sendmail(msg['From'], [msg['To']], msg.as_string())
server.quit()

A: I did it using the standard packages: ssl, smtplib and email.
import configparser
import smtplib
import ssl
from email.message import EmailMessage

# define bcc:[str], cc: [str], from_email: str, to_email: str, subject: str, html_body: str, str_body: str
...

# save your login and server information in a settings.ini file
cfg.read(os.path.join(os.path.dirname(os.path.realpath(__file__)), "settings.ini"))

msg = EmailMessage()
msg['Bcc'] = ", ".join(bcc)
msg['Cc'] = ", ".join(cc)
msg['From'] = from_email
msg['To'] = to_email
msg['Subject'] = subject

msg.set_content(str_body)
msg.add_alternative(html_body, subtype="html")

# add SSL (layer of security)
context = ssl.create_default_context()

# log in and send the email
with smtplib.SMTP_SSL(cfg.get("mail", "server"), cfg.getint("mail", "port"), context=context) as smtp:
    smtp.login(cfg.get("mail", "username"), cfg.get("mail", "password"))
    smtp.send_message(msg=msg)


text:
Q: Connect not working with StateLess component in Redux-react I'm dispatching an action from some-other component , and store is getting updated with svgArr property, but though the following Stateless component connect'ed to the store , it ain't getting updated when store changes for svgArr.
Is it how it suppose to behave as it's a stateless component ? Or am I doing something wrong ?
const Layer = (props) => {
  console.log(props.svgArr);
  return (
 hi
);
};

connect((state) => {
  return {
    svgArr: state.svgArr
  };
}, Layer);

export default Layer;

A: If you want to connect the stateless function you should wrap it into
 the another const:
const Layer = (props) => {
  return (

 );
};

export const ConnectedLayer = connect(mapStateToProps)(Layer);

A: You seem to be exporting Layer instead of the connected version of the Layer component.
If you look at the redux documentation: https://github.com/reactjs/react-redux/blob/master/docs/api.md#inject-dispatch-and-todos
It should be something like

function mapStateToProps(state) {
  return {svgArr: state.svgArr}
}
export default connect(mapSTateToProps)(Layer)

A: Here's a rewrite of your code
import {connect} from 'react-redux';

// this should probably not be a free variable
const styles = {imgLayer: '???'};

const _Layer = ({canvasWidth}) => (

);

const Layer = connect(
  state => ({
    svgArr: state.svgArr
  })
)(_Layer);

export default Layer;

A: Here use redux with functional component in react native
import { useSelector } from 'react-redux';
const variable = useSelector(state => state.user.variable)

A: In addition, you can also pass multiple state object with functional components.
import {connect} from 'react-redux';

const PartialReview = ({auth, productreview}) => (

{auth.uInfo._ubase}

{productreview.review_description}

);

  const mapStateToProps = (state) => {
    return {auth: state.auth,productreview: state.productreview}
    };
  export default connect(mapStateToProps)(PartialReview)


text:
Q: file system creation script on AIX using while loop #!/bin/sh

echo "VG: "
read VG
echo "LP: "
read LP
echo "SAP: "
read SAP
echo "NUM: "
read NUM
echo "SID: "
read SID

while [[ $NUM -lt 2 ]]; read VG LP SAP NUM SID ; do

mklv   -y   $SAP$NUM   -t   jfs2   -e   x   $VG   $LP;

crfs   -v   jfs2   -d   /dev/$SAP$NUM   -m   /oracle/$SID/$SAP$NUM  -A   yes   -p   rw -a   log=INLINE    -a   options=cio;

NUM=$((NUM+1)) OR (( NUM++ ))

done

I want to create file system on AIX as priyank1, priyank2 and so on...
VG is the volume group name, LP is the logical partition/size of FS, SAP is the name "priyank" and SID is the Directory under /oracle..
Please let me know if any further details needed.
Please help the above script is not working...not reading the variable properly while executing the commands.
also i have placed 2 variable together $SAP$NUM , will this be a problem ?
Regards,
Priyank

A: You are using BASH shell semantics in Bourne shell. Either change the first line to:
#!/bin/bash

or change change your while statement to use Bourne syntax.
while [ $NUM -lt 2 ]; do
    read VG LP SAP NUM SID
    mklv -y $SAP$NUM -t jfs2 -e x $VG $LP
    .
    .
    .
    done

The [[ expression ]] and (( expression )) syntaxes do not exist in Bourne shell (/bin/sh). You will need to refactor the loop counter increment if you keep using Bourne shell.

A: /bin/sh on AIX is usually ksh but your syntax on the first line is still wrong as Eric points out.  The "do" comes after the first semicolon.
Another point is the read wants all the values on one line.  From your post, it looks like you want separate lines for each input value?  e.g.
while [[ $NUM -lt 2 ]] ; do
  read VG
  read LP
  read SAP
  read NUM
  read SID
  .
  .
  .
done

The original would be used as:
script_name
1 2 3 4 5  # would read all five values for the first run
6 7 8 9 10  # a new set of five values for the second run
 ...

But you might be wanting to use it as:
script_name
1  # the value for VG on the first run
2  # the value of LP for the first run
....


text:
Q: OAuth 2.0 Many to Many Delegated Client Credential Flow Scenario Scenario:

*

*A controller process obtains a short-lived JWT access token and a refresh token handle using client credentials grant.

*The controller spawns one or more isolated worker nodes and passes the access and refresh token to the node(s).

*The child node may continue with a long running task where the access token may expire and a refresh needs to occur.

*In a background thread, before expiration, the agent refreshes its token, the access token is regenerated. The need for short lived access tokens and a refresh lifecycle is to regenerate temporal JWT claims (claims that are time-transitive such as uris).

*The child may return a response to the parent. Both the parent and children need to maintain an independent session validation lifecycle without invalidating the other.

Assumptions:
Assume each process is an atomic unit of work with independent state. The access token is authenticated once by the controller and passed down with its refresh token to N+1 or N*N worker nodes.
Any given N process may proactively regenerate its access token with the refresh token handed down to it to extend its lifetime and prevent expiration.
The process may run in a trusted (private) or untrusted (public) environment over HTTPS & SSL.
There is one authorization server and one api resource server.
Problem:
How would the agent validate both the access token and refresh token lifetime ensuring that any child or parent process can refresh its session during its lifetime without exposing any security attack vectors or invalidating another agent in the pool?

A: Mutual TLS client certificate authentication may be a good option for this. It involves parties authenticating each other through verifying the provided digital certificate so that both parties are assured of the others' identity. In technology terms, it refers to a client application authenticating themselves to a server and that server also authenticating itself to the client through verifying the public key certificate/digital certificate issued by the trusted Certificate Authorities (CAs).


text:
Q: SwiftUI Button tap only on text portion The background area of my button is not detecting user interaction. Only way to interact with said button is to tap on the Text/ Label area of the button. How to make entire Button tappable?
struct ScheduleEditorButtonSwiftUIView: View {

    @Binding  var buttonTagForAction : ScheduleButtonType
    @Binding  var buttonTitle        : String
    @Binding  var buttonBackgroundColor : Color

    let buttonCornerRadius = CGFloat(12)

    var body: some View {

        Button(buttonTitle) {
              buttonActionForTag(self.buttonTagForAction)
        }.frame(minWidth: (UIScreen.main.bounds.size.width / 2) - 25, maxWidth: .infinity, minHeight: 44)

                            .buttonStyle(DefaultButtonStyle())
                            .lineLimit(2)
                            .multilineTextAlignment(.center)
                            .font(Font.subheadline.weight(.bold))
                            .foregroundColor(Color.white)

                            .border(Color("AppHighlightedColour"), width: 2)
                           .background(buttonBackgroundColor).opacity(0.8)

                            .tag(self.buttonTagForAction)
                            .padding([.leading,.trailing], 5)
       .cornerRadius(buttonCornerRadius)

    }
}

A: The proper solution is to use the .contentShape() API.
Button(action: action) {
  HStack {
    Spacer()
    Text("My button")
    Spacer()
  }
}
.contentShape(Rectangle())

You can change the provided shape to match the shape of your button; if your button is a RoundedRectangle, you can provide that instead.

A: I think this is a better solution, add the .frame values to the Text() and the button will cover the whole area
Button(action: {
    //code
}) {
    Text("Click Me")
    .frame(minWidth: 100, maxWidth: .infinity, minHeight: 44, maxHeight: 44, alignment: .center)
    .foregroundColor(Color.white)
    .background(Color.accentColor)
    .cornerRadius(7)
}

A: You might be doing this:
Button { /*to do something on button click*/}
label: { Text("button text").foregroundColor(Color.white)}
.frame(width: 45, height: 45, alignment: .center)
.background(Color.black)

Solution:
Button(action: {/*to do something on button click*/ })
{
HStack {
Spacer()
Text("Buttton Text")
Spacer() } }
.frame(width: 45, height: 45, alignment: .center)
.foregroundColor(Color.white)
.background(Color.black).contentShape(Rectangle())

A: You can define content Shape for hit testing by adding modifier: contentShape(_:eoFill:)
And important thing is you have to apply inside the content of Button.
Button(action: {}) {
    Text("Select file")
       .frame(width: 300)
       .padding(100.0)
       .foregroundColor(Color.black)
       .contentShape(Rectangle()) // Add this line
}
.background(Color.green)
.cornerRadius(4)
.buttonStyle(PlainButtonStyle())

Another
Button(action: {}) {
    VStack {
       Text("Select file")
           .frame(width: 100)
       Text("Select file")
           .frame(width: 200)
    }
    .contentShape(Rectangle()) // Add this inside Button.
}
.background(Color.green)
.cornerRadius(4)
.buttonStyle(PlainButtonStyle())

A: This fixes the issue on my end:
var body: some View {
    GeometryReader { geometry in
        Button(action: {
            // Action
        }) {
            Text("Button Title")
                .frame(
                    minWidth: (geometry.size.width / 2) - 25,
                    maxWidth: .infinity, minHeight: 44
                )
                .font(Font.subheadline.weight(.bold))
                .background(Color.yellow).opacity(0.8)
                .foregroundColor(Color.white)
                .cornerRadius(12)

        }
        .lineLimit(2)
        .multilineTextAlignment(.center)
        .padding([.leading,.trailing], 5)
    }
}

Is there a reason why you are using UIScreen instead of GeometryReader?

A: Short Answer
Make sure the Text (or button content) spans the length of the touch area, AND use .contentShape(Rectangle()).
Button(action:{}) {
  HStack {
    Text("Hello")
    Spacer()
  }
  .contentShape(Rectangle())
}

Long Answer
There are two parts:

*

*The content (ex. Text) of the Button needs to be stretched

*The content needs to be considered for hit testing

To stretch the content (ex. Text):
// Solution 1 for stretching content
HStack {
  Text("Hello")
  Spacer()
}

// Solution 2 for stretching content
Text("Hello")
  .frame(maxWidth: .infinity, alignment: .leading)

// Alternatively, you could specify a specific frame for the button.

To consider content for hit testing use .contentShape(Rectangle()):
// Solution 1
Button(action:{}) {
  HStack {
    Text("Hello")
    Spacer()
  }
  .contentShape(Rectangle())
}

// Solution 2
Button(action:{}) {
  Text("Hello")
    .frame(maxWidth: .infinity, alignment: .leading)
    .contentShape(Rectangle())
}

A: A bit late to the answer, but I found two ways to do this —
Option 1: Using Geometry Reader
Button(action: {
}) {
    GeometryReader { geometryProxy in
        Text("Button Title")
            .font(Font.custom("SFProDisplay-Semibold", size: 19))
            .foregroundColor(Color.white)
            .frame(width: geometryProxy.size.width - 20 * 2) // horizontal margin
            .padding([.top, .bottom], 10) // vertical padding
            .background(Color.yellow)
            .cornerRadius(6)
    }
}

Option 2: Using HStack with Spacers
HStack {
    Spacer(minLength: 20) // horizontal margin
    Button(action: {

    }) {
        Text("Hello World")
            .font(Font.custom("SFProDisplay-Semibold", size: 19))
            .frame(maxWidth:.infinity)
            .padding([.top, .bottom], 10) // vertical padding
            .background(Color.yellow)
            .foregroundColor(Color.white)
            .cornerRadius(6)
    }
    Spacer(minLength: 20)
}.frame(maxWidth:.infinity)

My thought process here is that although option 1 is more succinct, I would choose option 2 since it's less coupled to its parent's size (through GeometryReader) and more in line of how I think SwiftUI is meant to use HStack, VStack, etc.

A: I was working with buttons and texts that need user interaction when I faced this same issue. After looking and testing many answers (including some from this post) I ended up making it works in the following way:
For buttons:
/* WITH IMAGE */
Button {
    print("TAppeD")
} label: {
    Image(systemName: "plus")
        .frame(width: 40, height: 40)
}
/* WITH TEXT */
Button {
    print("TAppeD")
} label: {
    Text("My button")
       .frame(height: 80)
}

For Texts:
Text("PP")
    .frame(width: 40, height: 40)
    .contentShape(Rectangle())
    .onTapGesture {
        print("TAppeD")
    }

In the case of the texts, I only need the .contentShape(Rectangle()) modifier when the Text doesn't have a .background in order to make the entire Text frame responsive to tap gesture, while with buttons I use my Text or Image view with a frame and neither a .background nor a .contentShape is needed.
Image of the following code in preview (I'm not allowed to include pictures yet )
import SwiftUI

struct ContentView: View {
    @State var tapped: Bool = true
    var body: some View {
        VStack {
            RoundedRectangle(cornerRadius: 19)
                .frame(width: 40, height: 40)
                .foregroundColor(tapped ? .red : .green)
            Spacer()
            HStack (spacing: 0) {
                Text("PP")
                    .frame(width: 40, height: 40)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        tapped.toggle()
                    }

                Button {
                    print("TAppeD")
                    tapped.toggle()
                } label: {
                    Image(systemName: "plus")
                        .frame(width: 40, height: 40)
                }
                .background(Color.red)

                Button {
                    print("TAppeD")
                    tapped.toggle()
                } label: {
                    Text("My button")
                        .frame(height: 80)
                }
                .background(Color.yellow)
            }

            Spacer()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: this way makes the button area expand properly
but if the color is .clear, it dosen't  work♂
                Button(action: {
                   doSomething()
                }, label: {
                    ZStack {
                        Color(.white)
                        Text("some texts")
                    }
                })

A: When I used HStack then it worked for button whole width that's fine, But I was facing issue with whole button height tap not working at corners and I fixed it in below code:
Button(action:{
                print("Tapped Button")
            }) {
                VStack {
                   //Vertical whole area covered
                    Text("")
                    Spacer()
                    HStack {
                     //Horizontal whole area covered
                        Text("")
                        Spacer()
                    }
                }
            }

A: If your app needs to support both iOS/iPadOS and macOS, you may want to reference my code!
Xcode 14.1 / iOS 14.1 / macOS 13.0 / 12-09-2022
Button(action: {
    print("Saved to CoreData")

}) {
    Text("Submit")
    .frame(minWidth: 100, maxWidth: .infinity, minHeight: 44, maxHeight: 60, alignment: .center)
    .foregroundColor(Color.white)
    #if !os(macOS)
    .background(Color.accentColor)
    #endif
}
#if os(macOS)
.background(Color.accentColor)
#endif
.cornerRadius(7)

A: Easier work around is to add .frame(maxWidth: .infinity) modifier.
and wrap your button inside a ContainerView. you can always change the size of the button where it's being used.
    Button(action: tapped) {
        HStack {
            if let icon = icon {
                icon
            }

            Text(title)
        }
        .frame(maxWidth: .infinity) // This one
    }


text:
Q: Validating parameters for malicious SQL when building dynamic SQL I have a situation where I must use dynamic SQL as its appearing difficult to use parameters.
The query I will execute dynamically is as below.
What is the best way to validate the string in @sql for malicious SQL? I need to allow valid strings like 'CountryId = 23' but not allow strings like 'delete from Countries'. I do not want everything to be NOT ALLOWED.
I am using C# to run this query against SQL Server 2008 R2.
Perhaps, I could validate at SQL level or at C# level, but I am unsure which would be better.
SET @sql = 'SELECT * from Customers
  where ' + @filterExpression +
  ' order by ' + @sortExpression;

EXEC sp_executesql @sql

UPDATE: Maxim's answer seems to be the best for situations where you must use dynamic SQL, though dynamic SQL like the code I have in this post should be avoided as much as possible.
I came up with some validation on the variable  @filterExpression in T-SQL to validate for malicious SQL code, which may still miss some malicious cases, but here is the T-SQL I came up with.
IF PATINDEX('%DELETE %',  @filterExpression ) > 0
  OR PATINDEX('%SELECT %FROM%',  @filterExpression ) > 0
  OR PATINDEX('%;%',  @filterExpression ) > 0
  OR PATINDEX('%DROP %',  @filterExpression ) > 0
  OR PATINDEX('%CREATE %',  @filterExpression ) > 0
  OR PATINDEX('%TRUNCATE %',  @filterExpression ) > 0
  OR PATINDEX('%sys%',  @filterExpression ) > 0
  OR PATINDEX('%INDEX %', @filterExpression ) > 0
  OR PATINDEX('%UPDATE %', @filterExpression ) > 0
  OR PATINDEX('%INSERT %',  @filterExpression ) > 0
  OR PATINDEX('%EXEC %',  @filterExpression ) > 0
  OR PATINDEX('%EXECUTE %',  @filterExpression ) > 0
  OR PATINDEX('%CAST%',  @filterExpression ) > 0
  OR PATINDEX('%DECLARE %',  @filterExpression ) > 0
  OR PATINDEX('%CONVERT%',  @filterExpression ) > 0
BEGIN
  RETURN;
END

A: *

*You could use a read only user, this would at least block any
updates.

*Look for keywords that look suspicious to you: INSERT,
UPDATE, etc.

*Use third-party libraries like this
Here is the good bunch of anti injections techniques.


text:
Q: Smooth scrolling on button click I used this code:
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();
    var target = this.hash,
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 1000, 'swing', function () {
        window.location.hash = target;
    });
});

and the smooth scroll work perfectly between a link and an anchor!
But how can I make following button code work for ?
<input type="button" value="btn">

A: You can use:
$('input[type="button"]').on('click',function (e) {

instead of:
$('a[href^="#"]').on('click',function (e) {

A: You can use like this:
$('input[type="button"][value="btn"]').on('click',function (e) {

If you need both separate them by a coma:
$('a[href^="#"], input[type="button"][value="btn"]').on('click',function (e) {

But I would strongly recommend to use a common class for them and access like this:
$('.common_class').on('click',function (e) {

A: The old style could work too:
<input type="button" value="btn" onclick="$('a[href^=\"#\"]').trigger('click')">

But you should avoid that style (inline event)


text:
Q: meaning of the adjective "singular" in context It is from Crash Course World History. It is at 55 second. Here it goes:

The first European visitors to the Americas had never seen a tomato or a catfish; native americans had never seen a horse, and by making our planet biologically singular, the Columbian exchange completely remade the population of animals, particularly humans.

I cannot get from the context whether the presenter meant biologically very good or biologically less diverse.

A: Singular, from single "One in number".
The human world before 1492 was divided into two parts: One with Tomatoes and Catfish, the other with Horses.
After 1492 the human world became one part. The presenter doesn't say if this was good or not.

A: I would assume from the context that "singular" here means "united" or probably even "one", like in "two become one".
The idea here lies in merging two separates into a whole.


text:
Q: DWT: What is it and when and where we use it I was reading up on the DWT for the first time and the document stated that it is used to represent time-frequency data of a signal which other transforms do not provide.
But when I look for a usage example of the DWT in MATLAB I see the following code:
X=imread('cameraman.tif');
X=im2double(X);

[F1,F2]= wfilters('db1', 'd');
[LL,LH,HL,HH] = dwt2(X,'db1','d');

I am unable to understand the implementation of dwt2 or rather what is it and when and where we use it.  What actually does dwt2 return and what does the above code do?

A: The first two statements simply read in the image, and convert it so that the dynamic range of each channel is between [0,1] through im2double.
Now, the third statement, wfilters constructs the wavelet filter banks for you.  These filter banks are what are used in the DWT.  The method of the DWT is the same, but you can use different kinds of filters to achieve specific results.
Basically, with wfilters, you get to choose what kind of filter you want (in your case, you chose db1: Daubechies), and you can optionally specify the type of filter that you want.  Different filters provide different results and have different characteristics.  There are a lot of different wavelet filter banks you could use and I'm not quite the expert as to the advantages and disadvantages for each filter bank that exists.  Traditionally, Daubechies-type filters are used so stick with those if you don't know which ones to use.
Not specifying the type will output both the decomposition and the reconstruction filters.  Decomposition is the forward transformation where you are given the original image / 2D data and want to transform it using the DWT.  Reconstruction is the reverse transformation where you are given the transform data and want to recreate the original data.
The fourth statement, dwt2, computes the 2D DWT for you, but we will get into that later.

You specified the flag d, so you want only the decomposition filters.  You can use wfilters as input into the 2D DWT if you wish, as this will specify the low-pass and high-pass filters that you want to use when decomposing your image.  You don't have to do it like this.  You can simply specify what filter you want to use, which is how you're calling the function in your code.  In other words, you can do this:
[F1,F2]= wfilters('db1', 'd');
[LL,LH,HL,HH] = dwt2(X,F1,F2);

... or you can just do this:
[LL,LH,HL,HH] = dwt2(X,'db1','d');

The above statements are the same thing.  Note that there is a 'd' flag on the dwt2 function because you want the forward transform as well.

Now, dwt2 is the 2D DWT (Discrete Wavelet Transform).  I won't go into the DWT in detail here because this isn't the place to talk about it, but I would definitely check out this link for better details.  They also have fully working MATLAB code and their own implementation of the 2D DWT so you can fully understand what exactly the DWT is and how it's computed.
However, the basics behind the 2D DWT is that it is known as a multi-resolution transform.  It analyzes your signal and decomposes your signal into multiple scales / sizes and features.  Each scale / size has a bunch of features that describe something about the signal that was not seen in the other scales.
One thing about the DWT is that it naturally subsamples your image by a factor of 2 (i.e. halves each dimension) after the analysis is done - hence the multi-resolution bit I was talking about.  For MATLAB, dwt2 outputs four different variables, and these correspond to the variable names of the output of dwt2:

*

*LL - Low-Low.  This means that the vertical direction of your 2D image / signal is low-pass filtered as well as the horizontal direction.

*LH - Low-High. This means that the vertical direction of your 2D image / signal is low-pass filtered while the horizontal direction is high-pass filtered.

*HL - High-Low. This means that the vertical direction of your 2D image / signal is high-pass filtered while the horizontal direction is low-pass filtered.

*HH - High-High. This means that the vertical direction of your 2D image / signal is high-pass filtered as well as the horizontal direction.

Roughly speaking, LL corresponds to just the structural / predominant information of your image while HH corresponds to the edges of your image.  The LH and HL components I'm not too familiar with, but they're used in feature analysis sometimes.  If you want to do a further decomposition, you would apply the DWT again on the LL only.  However, depending on your analysis, the other components are used.... it just depends on what you want to use it for!  dwt2 only performs a single-level DWT decomposition, so if you want to use this again for the next level, you would call dwt2 on the LL component.
Applications
Now, for your specific question of applications.  The DWT for images is mostly used in image compression and image analysis.  One application of the 2D DWT is in JPEG 2000.  The core of the algorithm is that they break down the image into the DWT components, then construct trees of the coefficients generated by the DWT to determine which components can be omitted before you save the image.  This way, you eliminate extraneous information, but there is also a great benefit that the DWT is lossless.  I don't know which filter(s) is/are being used in JPEG 2000, but I know for certain that the standard is lossless.  This means that you will be able to reconstruct the original data back without any artifacts or quantization errors.  JPEG 2000 also has a lossy option, where you can reduce the file size even more by eliminating more of the DWT coefficients in such a way that is imperceptible to the average use.
Another application is in watermarking images.  You can embed information in the wavelet coefficients so that it prevents people from trying to steal your images without acknowledgement.  The DWT is also heavily used in medical image analysis and compression as the images generated in this domain are quite high resolution and quite large.  It would be extremely useful if you could represent the images in the same way but occupying less physical space in comparison to the standard image compression algorithms (that are also lossy if you want high compression ratios) that exist.
One more application I can think of would be the dynamic delivery of video content over networks.  Depending on what your connection speed is or the resolution of your screen, you get a lower or higher quality video.  If you specifically use the LL component of each frame, you would stream / use a particular version of the LL component depending on what device / connection you have.  So if you had a bad connection or if your screen has a low resolution, you would most likely show the video with the smallest size.  You would then keep increasing the resolution depending on the connection speed and/or the size of your screen.

This is just a taste as to what the DWT is used for (personally, I don't use it because the DWT is used in domains that I don't personally have any experience in), but there are a lot more applications that are quite useful where the DWT is used.


text:
Q: How do I reference the ServiceStack library in a Unity C# script? I've got to make a Unity script to import and export some 3D models. I'm trying to reference Servicestack.Redis from my script so I can talk to redis. It compiles fine but unity won't load the library.
I've copied the dll's from Build/Release/MonoDevelop/SericeStack.Redis.zip into my assets folder within unity, (is that correct?) I just got ServiceStack by cloning https://github.com/ServiceStack/ServiceStack.Redis
When Unity attempts to load the script it says
Internal compiler error. See the console log for more information. output was:
Unhandled Exception: System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded.
  at (wrapper managed-to-native) System.Reflection.Assembly:GetTypes (bool)
  at System.Reflection.Assembly.GetTypes () [0x00000] in <filename unknown>:0
  at Mono.CSharp.RootNamespace.ComputeNamespaces (System.Reflection.Assembly assembly, System.Type extensionType) [0x00000] in <filename unknown>:0
  at Mono.CSharp.RootNamespace.ComputeNamespace (Mono.CSharp.CompilerContext ctx, System.Type extensionType) [0x00000] in <filename unknown>:0
  at Mono.CSharp.GlobalRootNamespace.ComputeNamespaces (Mono.CSharp.CompilerContext ctx) [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.LoadReferences () [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.Compile () [0x00000] in <filename unknown>:0
  at Mono.CSharp.Driver.Main (System.String[] args) [0x00000] in <filename unknown>:0

My code so far is this. It's an editor script. It just makes a window with a button and when the button is clicked it attempts to connect to redis on localhost and get a key
using UnityEngine;
using UnityEditor;
using System.Collections;
using ServiceStack.Redis;

public class MyWindow : EditorWindow
{

    // Add menu item named "My Window" to the Window menu
    [MenuItem("Window/My Window")]
    public static void ShowWindow()
    {
        //Show existing window instance. If one doesn't exist, make one.
        EditorWindow.GetWindow(typeof(MyWindow));
    }

    void OnGUI()
    {
        if (GUILayout.Button("Press to Rotate"))
        {
            ProcessAsset();
        }
    }

    void ProcessAsset()
    {
        using (var client = new RedisClient("localhost"))
        {
            client.Get ("hello");
        }
    }
}

I'm probably just not referencing the library correctly. I'm fairly new to compiled languages.

A: I had a bug similar to that. But it was without any custom dlls. The reason was because I used Func inside my code. Mono do not have support for Func. I tried to download the source code for the dlls and they use quite a lot of Func. So it's probably the reason you get that error.

A: I know this is a little old but it showed up in my search results. So for anybody else having this problem make sure your Unity project settings are set to .Net 2.0 instead of .Net 2.0 Subset.
The menu can be found File -> Build Settings -> Player Settings -> Optimization.


text:
Q: QR decomposition error How to find $$||A - QR||_2$$
without finding Q matrix
(A is matrix,
QR - qr decomposition of A)
I have written a code which return only R (using Householder transformation).

A: If you've found the QR decomposition for A, then $A=QR$, hence the norm of their difference is 0.
If you're solving the Least Squares problem minimizing $||Ax - b||_2$ then the error, or residual, is the norm of the last m-n elements of the vector $Q^Tb$.


text:
Q: I'm trouble in error of pandas "DataFrame" I'm a bigginer who are learning pandas.
I tried two things as follows, but I didn't solve it.
I use Jupyter notebook.
Could you please help me?
#1
import sys
sys.getdefaultencoding()

#2
from importlib import reload
import sys
reload(sys)

#I wanted to make it.
#I succeeded in it at another file, but it couldn't work at current file.
from pandas import Series,DataFrame
import pandas as pd

data={"ID":["001","002","003"],
      "city":["hyougo","tiba","gihu"],
      "people":["100","230","249"]}
data_frame=DataFrame(data)
print(data_frame)

#error
---------------------------------------------------------------------------
    AttributeError                            Traceback (most recent call last)
    <ipython-input-133-640865466ed4> in <module>
          3       "people":["100","230","249"]}
          4 data_frame=DataFrame(data)
    ----> 5 print(data_frame)

    ~\anaconda3\lib\site-packages\pandas\core\frame.py in __repr__(self)
        678         else:
        679             width = None
    --> 680         self.to_string(
        681             buf=buf,
        682             max_rows=max_rows,

    ~\anaconda3\lib\site-packages\pandas\core\frame.py in to_string(self, buf, columns, col_space, header, index, na_rep, formatters, float_format, sparsify, index_names, justify, max_rows, min_rows, max_cols, show_dimensions, decimal, line_width, max_colwidth, encoding)
        818                 line_width=line_width,
        819             )
    --> 820             return formatter.to_string(buf=buf, encoding=encoding)
        821
        822     # ----------------------------------------------------------------------

    ~\anaconda3\lib\site-packages\pandas\io\formats\format.py in to_string(self, buf, encoding)
        912         encoding: Optional[str] = None,
        913     ) -> Optional[str]:
    --> 914         return self.get_result(buf=buf, encoding=encoding)
        915
        916     def to_latex(

    ~\anaconda3\lib\site-packages\pandas\io\formats\format.py in get_result(self, buf, encoding)
        519         """
        520         with self.get_buffer(buf, encoding=encoding) as f:
    --> 521             self.write_result(buf=f)
        522             if buf is None:
        523                 return f.getvalue()

    ~\anaconda3\lib\site-packages\pandas\io\formats\format.py in write_result(self, buf)
        821         else:
        822
    --> 823             strcols = self._to_str_columns()
        824             if self.line_width is None:  # no need to wrap around just print
        825                 # the whole frame

    ~\anaconda3\lib\site-packages\pandas\io\formats\format.py in _to_str_columns(self)
        717         # may include levels names also
        718
    --> 719         str_index = self._get_formatted_index(frame)
        720
        721         if not is_list_like(self.header) and not self.header:

    ~\anaconda3\lib\site-packages\pandas\io\formats\format.py in _get_formatted_index(self, frame)
       1057             )
       1058         else:
    -> 1059             fmt_index = [index.format(name=self.show_row_idx_names, formatter=fmt)]
       1060
       1061         fmt_index = [

    AttributeError: 'list' object has no attribute 'format'

A: You need to import pandas first and then add the alias pd before DataFrame
import pandas as pd

data={"ID":["001","002","003"],
      "city":["hyougo","tiba","gihu"],
      "people":["100","230","249"]}
data_frame=pd.DataFrame(data)
print(data_frame)

Prints:
    ID    city people
0  001  hyougo    100
1  002    tiba    230
2  003    gihu    249

If you don't have pandas installed you will need to do that first
pip install pandas


text:
Q: Ant design Area chart - remove canvas margins Im trying to set Ant Desing Area chart to not have margin/padding on the sides so my chart will perfectly fit inside the wrapping container - but for some reason i couldn't find the attribute for that on Ant's documentation.
Also i would like the Chart to start from 0 on the Y axis
i tried the "beginAtZero" attribute but also didnt worked
these are my configurations:
const config = {
    height: 60,
    data: volumeData,
    autoFit: true,
    xField: "date",
    yField: "count",
    padding: [5],
    xAxis: false,
    yAxis: false,
    color: "#916afc",
    legend: false,
    point: {
      shape: 'circle'
    },
  };

wrpper container css
    width: 100%;
    background-color: #ffffff;
    box-shadow: 0px 5px 10px rgb(0 0 0 / 5%);
    border-radius: 10px;
    padding: 20px;

and the chart:
<Area {...config} />

A: You should set the scale.min of y field to 0.
{
  /* ... */
  meta: {
    count: { min: 0 }
  }
}

Then the y axis will start wiht zero.

A: To remove the side padding/margin, explicitly set the xField's range to the default of [0, 1]. To change the starting yAxis value, set the yField's min to 0 (as proposed by @atool).
const config = {
    /* ... */
    xField: "date",
    yField: "count",
    /* ... */
    meta: {
        "date": {
            range: [0, 1]
        },
        "count": {
            min: 0
        }
    }
  };


text:
Q: what does "oi lad!" mean? There was this moment in some guy's video where a warrior swings a sword at some other guy. Then the other guy says "oi lad!" parrying the sword. What does that mean? why would he say that.

A: oi TFD
interj.  British Slang

Used as a greeting or to attract someone's attention.

As in:  google books: Dreams of the Soul

Oi, oi lad, shut your pie hole and stop chirping... Oi, lad! It is
  over, over!


text:
Q: android crash : Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1) My app crash sometimes. And there are only some lib error.I have more than 40,000 lines codes.I don't know how to find the bug? Is that the out of memory or use wrong method?
I/DEBUG   (  318): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad
I/DEBUG   (  318): Abort message: 'invalid address or address of corrupt block 0x760dafb8 passed to dlfree'
D/cta_dex (  998): conn HookConnectivityService onTransact code: 4
D/cta_dex (  998): conn pass onTransact code: 4
D/cta_dex (  998): conn HookConnectivityService onTransact code: 6
D/cta_dex (  998): conn pass onTransact code: 6
I/DEBUG   (  318):     r0 00000000  r1 4006f172  r2 deadbaad  r3 40072d5c
I/DEBUG   (  318):     r4 760dafb8  r5 4007d190  r6 41945000  r7 760dafc0
I/DEBUG   (  318):     r8 7a046b0c  r9 76090a64  sl 765716d0  fp 7a046b24
I/DEBUG   (  318):     ip 00000001  sp 7a046aa8  lr 4004088b  pc 4004088c      cpsr 60070030
I/DEBUG   (  318):     d14 0000000000000000  d15 0000000000000000
I/DEBUG   (  318):     scr 60000012
I/DEBUG   (  318):
I/DEBUG   (  318): backtrace:
I/DEBUG   (  318):     #00  pc 0001188c  /system/lib/libc.so (dlfree+1191)
I/DEBUG   (  318):     #01  pc 0000dd2b  /system/lib/libc.so (free+10)
I/DEBUG   (  318):     #02  pc 00083943  /system/lib/libcrypto.so (CRYPTO_free+34)
I/DEBUG   (  318):     #03  pc 00027035  /system/lib/libssl.so (SSL_CTX_set_alpn_protos+16)
I/DEBUG   (  318):     #04  pc 00008b7f  /system/lib/libjavacrypto.so
I/DEBUG   (  318):     #05  pc 0002034c  /system/lib/libdvm.so (dvmPlatformInvoke+112)
I/DEBUG   (  318):     #06  pc 00050fcf  /system/lib/libdvm.so (dvmCallJNIMethod(unsigned int const*, JValue*, Method const*, Thread*)+398)
I/DEBUG   (  318):     #07  pc 000297e0  /system/lib/libdvm.so
I/DEBUG   (  318):     #08  pc 00030c6c  /system/lib/libdvm.so (dvmMterpStd(Thread*)+76)
I/DEBUG   (  318):     #09  pc 0002e304  /system/lib/libdvm.so (dvmInterpret(Thread*, Method const*, JValue*)+184)
I/DEBUG   (  318):     #10  pc 00063435  /system/lib/libdvm.so (dvmCallMethodV(Thread*, Method const*, Object*, bool, JValue*, std::__va_list)+336)
I/DEBUG   (  318):     #11  pc 00063459  /system/lib/libdvm.so (dvmCallMethod(Thread*, Method const*, Object*, JValue*, ...)+20)
I/DEBUG   (  318):     #12  pc 00058137  /system/lib/libdvm.so
I/DEBUG   (  318):     #13  pc 0000d290  /system/lib/libc.so (__thread_entry+72)

A: SIGSEGV is legendary Segmentation Fault Error. You need to find mistake manually. Firstly check all calls to native (jni) libs or code resources. Including Android project code. Ie.: Once time I came across this signal when using cookie stores.