text:
Q: Let $f \colon A \rightarrow B$ be a function and $S$ a subset of $A$. Let $f \colon A \rightarrow B$ be a function and $S$ a subset of $A$.
Are the following containments always valid?.
$(1)    f^{-1} (f(S))⊆ S$
$(2)     S⊆f^{-1} (f(S))$
Attempt
$S ⊆ A$
$f^{-1}(S) = \{a ∈ B : f(a) ∈ S\}$
$ a ∈ f^{-1}(S) ⟺ f(a) ∈ S$
$ f^{-1}(S) ⊆ B$
I just need a little help finishing the proof. Am i wrong in the attempt? Thanks.

A: There is a problem with your proof. $f^{-1}(S)$ doesn't exist. This is because $S$ is a subset of $A$. It only makes sense to take a preimage under $f$ of a subset of $B$. On the other hand, $f(S)$ makes perfect sense. Indeed, $f(S)=\{f(a)\in B|a\in A\}$. Note that $f(S)$ is a subset of $B$. Then, it now makes sense to write $f^{-1}(f(S))=\{a\in A|f(a)\in f(S)\}$. From this it should now be clear that only one of the two options you presented in your question is always true. Can you tell which one it is?
On the other hand, the other option will be true if we add a further assumption on $f$. Can you tell which assumption we need to add? (hint: recall the notion of an injective/surjective function).

A: Recall that for a function $ f: X \rightarrow Y $, and two subsets $A\subseteq X, B\subseteq Y$ that
$$ (f \circ f^{-1})(B) = I_Y(B)=B \\ (f^{-1} \circ f)(A) = I_X(A)=A $$
Where $I_X, I_Y$ are the identity functions. Do you think you can continue from here?


text:
Q: Is it possible to add a custom textmarker in Eclipse IDE In Delphi there exists the shortcut Ctrl+Shift+Number to set a marker (bookmark) in the IDE to quickly jump to a location (by Ctrl+Number).
In my Eclipse IDE (Juno), there exists a shortcut  to jump to a line number (Ctrl+L). But does there exist a similar option to jump between self defined markers in the editor like in Delphi?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove cookies for a particular list of domains in webview android In my android application I have a webview. It loads URLs from multiple domains. I need to delete all cookies from a specific domain. I want to keep cookies from other domains. But I need to delete all cookies from one domain.
How could I implement this. Please give a code snippet so that I can understand as I have read solutions on stackoverflow but not able to understand.


text:
Q: Regex, ANTLR or any other solution? Now this one is quite of a challenge on me.
I've got around 1000 queries in a file, all of a similar pattern that goes as:
***\*XYZ#PQR#\****

Now, where # indicates any-number non-whitespace charecters.
I've already coded a piece that can read a the above line and generate an according regex.
However, there are around 100,000 candidates and as I mentioned around 1000 such queries to be evaluated for the match.
This is making my code quite computationally expensive, as it is going to the order of m*n.
I've been through ANTLR and I found that the learning curve is quite steep. Although it sounds quite promising, I am still doubtful in some corner of my mind if this can by achieved using Antlr. Please let me know of your opinion or Any other viable solution.

A: It seems to me that you have what amounts to thousands of individual regular expressions,r1, r2, ... r1000 which identify some fixed set (much smaller than the number of individual regular expressions) of outcomes A, B, C, ...
In that that case, you can logically combine the regular expressions a1, a2, ... an for outcome A, and b1, ... bm for outcome B.  (The ability to disjunctively compose regular expressions and get regular expressions is a well know theoretical property of regular expressions).
Most systems for expressing regular expressions (maybe not yours) allow you to write this as
 a1 | a2 | .. | an --> A

or some equivalent syntax.   Such systems are often associated with so-called lexer generators which allow compiler writers to express the fine-grain syntax of tokens in terms of characters.
A great advantage of such tools is that the effort to match (all the regular expressions for) the tokens is often sublinear with respect to the number of regular expressions, made possible by computing a finite-state machine in which prefixes shared by some set of regular expressions is recognized just once for the set.  This can mean huge speedups and applies directly to situations such as yours.
The widely available tool FLEX does this very efficiently.  ANTLR has some kind of mechanism for recognizing tokens expressed as regular expressions, but I don't know if it generate efficient finite state matchers.

A: Done with it.
With Regex, it took an hour,
With Lucene, WildCardQueries and a booleanQuery to handle the permutations, Work Done in 11 minutes.
*Wishes If one could have a timeline to learn Flex in a week.
But Lucene is a good option for large DataSets, Regex and Crunching.
It may not always solve your problem, but its just another solution.

A: I think there is no need in ANTLR, as simple string find and replace is possible: # -> \\.*. Asterisks should be removed.
So for *Telecom#Servic#* you got Telecom\\.*Servic\\.*. You can also add $ and ^ for checking beginning/end of the string.


text:
Q: react checkbox treeview correct icons not showing issue I have follow below example. Its working fine. But my icons are not showing. Its showing as below.

this is my sample project.
https://codesandbox.io/s/sample-treeview-1zwd3w?file=/src/index.js


text:
Q: How can I use OS environment variables in Nginx config? How do I use environment variables set in the OS inside nginx configs?
For example environment variables set are ENVIRON=dev, APP_NAME=test
Here's my Dockerfile:
FROM openresty/openresty:alpine

RUN set -ex && \
    rm /etc/nginx/conf.d/default.conf

ADD nginx.conf /etc/nginx/
ADD custom.conf /etc/nginx/conf.d/

Here's my main nginx.conf
user  nginx;
worker_processes auto;
pcre_jit on;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

env ENVIRON;
env APP_NAME;
set_by_lua $environ 'return os.getenv("ENVIRON")';
set_by_lua $appname 'return os.getenv("APP_NAME")';

http {
    server_tokens off;
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}

Here's my custom.conf from /etc/nging/conf.d/
upstream app.$environ-$appname  {
      server $environ-$appname:80;
}
server {
    listen 80;
    server_name $hostname;
    error_log /dev/stdout info;
    access_log /dev/stdout;
    location / {
      proxy_redirect off;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      add_header X-Info proxied;
      proxy_pass http://app.$environ-$appname;
    }
}

Thanks!

A: That thing you are trying to do, I dont think you can do that.
From the documentation on the server directive of the upstream module:

Defines the address and other parameters of a server. The address can
  be specified as a domain name or IP address, with an optional port, or
  as a UNIX-domain socket path specified after the "unix:" prefix

You can't create upstream servers on the fly using variables.
If you want to route requests like this either use the map directive if the different locations are known at runtime, or set up an auth_request directive which points at an application on your server which can return the correct variables for each request in real time. Then have Nginx store that response in a variable using the auth_request_set directive.


text:
Q: client reconnect java socket ok i need to write a client that can be able to detect the connection between client and server...once server is close and bring back up my client need to be able to connect it back to the server..but i am really not sure how to do it...any help if possible?
 public TEST(String serverIP, int serverPort){
    Log("Connection to the Server....");
    try{
        socket = new Socket(serverIP, serverPort);
        Log("Connected to the server : "+socket);
        start();
    } catch(UnknownHostException uhe){
        System.out.println("Unknown Host: "+ uhe.getMessage());
    } catch (IOException ioe){
        System.out.println("IO Exception: "+ioe.getMessage());
    }

    String readline = "";

    streamOutput.println("TRY test");

    while(true){
        try{
            readline = streamInput.readLine();
            System.out.println(readline);
        } catch (IOException ioe){
            System.out.println("Error in sending: "+ioe.getMessage());
            return;
        }
    }
}

above is my client code that use to connect to a server once it is compiled...

A: The only way to know a connection is closed is to try sending data over the wire.  Connections don't automatically test open/closed status. If you want to check for an closed connection and reconnect, you'll have to send a heartbeat signal from one to the other.  Usually, it's just a special byte or tiny message that tells the other side "I'm still here"
But then, depending on your application, you may not need that.  Do both sides of your application start messages?  Or is it an RMI-style app?  Where the server just listens for requests?
Maybe something like this?
    class Client {
        private Socket socket;
        private boolean tryToReconnect = true;
        private final Thread heartbeatThread;
        private long heartbeatDelayMillis = 5000;

        public Client(final String server, final int port) {
            connect(server, port);
            heartbeatThread = new Thread() {
                public void run() {
                    while (tryToReconnect) {
                        //send a test signal
                        try {
                            socket.getOutputStream().write(666);
                            sleep(heartbeatDelayMillis);
                        } catch (InterruptedException e) {
                            // You may or may not want to stop the thread here
                            // tryToReconnect = false;
                        } catch (IOException e) {
                            logger.warn("Server is offline");
                            connect(server, port);
                        }
                    }
                };
            };
            heartbeatThread.start();
        }

        private void connect(String server, int port){
            try {
                socket = new Socket(server, port);
            } catch (UnknownHostException e) {
                logger.error(e, e);
            } catch (IOException e) {
                logger.error(e, e);
            }
        }

        public void shutdown() {
            tryToReconnect = false;
        }
    }

A: This is a pretty common problem (needing to know when the pipe is broken) and one of the answers was correct in the approach stating that the Client will need to 'check' the socket (periodically) to see if it is closed. The Server will not notify the Client the socket is closed and indeed, cannot because it is, well, closed. Firewalls, proxies and the like in between the Client and Server may have killed or otherwise blocked socket communication in one or both directions at any point after the connection is made.
First, if you have done a lot of socket programming (in "C" or Java, etc) ... you will have seen the "attempting to write on broken pipe" type error/exception. This is an I/O class of error when the Client tries to write (send) data on a closed socket (which was just then detected to have been closed).
So the answer lies in managing the socket above the Socket creation layer.
That is, a thread on the Client will need to be monitoring the socket by sending data (periodically to the server as a kind of 'ping' to check for a broken-pipe condition) and then destroy (clean-up) and re-create the socket (rinse and repeat) if an I/O error occurs.
Note that a more complex bi-directional bit of logic would be better provided the Client could ensure an expected and consistent (and timely) response from the Server for a given 'ping'. This would concretely confirm the bi-directional traffic is flowing. Otherwise firewalls could be closing traffic in one direction whilst the Client believes it is still 'talking' to the Server (which may well be receiving data but not able to transmit back to the Client - possibly causing it to terminate the connection on inactivity timeout).

A: When your client catches a SocketException it should enter its tryToReconnect state. Now it probes the server at some interval (e. g. 1 sec maybe more, depending on the server). Make sure you implement some logic to stop that when it is not needed anymore.

A: It seems you don't need to implement hear beats yourself. They are already implemented in most TCP implementations.
If your connection is TCP, what you are looking for is in a lower layer. Have a look at TCP KeepAlive.

These links might help:

*

*How To Test TCP KeepAlive?.

*TCP keepalive overview


text:
Q: Access root user directories from Windows under WSL? I'm running WSL2, Ubuntu 20.04, and Docker Desktop.  I often need to access some directories that are root owned and not readable by my main user.  It's getting pretty old to always have to:

*

*Manually login to the Ubuntu console as root

*Manually cd to the dirs I need to view files in

*cat each file one by one

This is especially painful when having to search through a ton of directories within just a minute or two, as I'm having to do right now with a bunch of Portainer directories.
I'd like to be able to just click through each directory in Explorer or Directory Opus and look in the preview tab.  However, these files/directories apparently aren't accessible when using Windows applications to examine \\wsl$\Ubuntu\path\to\root\owned\directory\.
Portainer creates its WSL folders as being owned by root.  I can manually chown them as my WSL/Ubuntu user (same name: scott) and then have the ability to do the above, but that gets old fast.  I'm also worried that it might other things on the Ubuntu/Portainer side down the road.
What I'd like is to add my Windows user to Ubuntu where Windows Explorer/Directory Opus/Notepad/etc. have the ability to access root user files/dirs, but with Linux as my second language ;-) I'm not real sure how that's done.
Also, when correctly entering the password into the Windows prompt, it still fails:

P.S. I do know that I can login to the Ubuntu console and do explorer.exe ., but even then I get an error when accessing root dirs.

A: Orthogonal answer (but much simpler than my other answer):  Use a Linux application that can preview the root-owned files instead of using a Windows application.  Downside -- There's just no comparison to Directory Opus, of course (IMHO)!
sudo apt install ranger
sudo ranger . # or the path you want to inspect

Note that preview of files when running as sudo is disabled by default for security reasons.  You can enable it via zi.  Then simply select the file you want to preview, and it will be displayed in the right-column.
I'm assuming that what you are inspecting will primarily be text-files.  If the file is longer than the terminal height, you can scroll (see key-bindings) or preview the file in a full-screen pager using i.

A: To summarize the root issue 1, your Ubuntu distribution is accessible via a 9P network share in Windows.  The Windows 9P client, which automatically creates \\wsl$\Ubuntu2 (Windows 10) or \\wsl.localhost\Ubuntu (Windows 11) shares has to select a particular Ubuntu user in order to provide access/permissions/ownership/etc.
1 No pun intended, really, I just noticed it!
2 Or other distribution name such as, e.g. "Ubuntu-22.04"
WSL uses the default user for the distribution as the "owner" of the share.  This is why you typically don't have access to root-restricted files when a Windows application is attempting to view or edit files in (e.g.) \\wsl.localhost\Ubuntu.
With that in mind (after typing the above info), a crazy, hairbrained idea came to mind.  Can we use another distribution, where the default user is root, to launch a Windows executable and yet still have it access the files (still as root) in Ubuntu?  The answer appears to be, "Yes", but I will say that this is a problem that I've thought I had "solved" (or at least worked-around) before, only to find I was wrong.
So I've tested this on Windows 10 with an older WSL version and Windows 11 with the latest (as of yesterday) WSL 0.70.8 and it seems to work under both.  The process is, unfortunately, a bit convoluted, but if it works for you, it should be something that can be scripted or aliased.  Don't be too scared by the number of steps below.  There are several reasons why they are longer than they need to be:

*

*I'm just pretty detailed (perhaps overly so) in how I explain things.

*I hope that, at the end of this, you'll understand why this works (or doesn't) so that you'll be able to adjust the process (if needed) for your use-case in the future.

*Also, most of the steps below are one-time setup and won't need to be repeated.

So to do this, you are going to need a separate distribution installed.  Since this distribution only needs to be able to launch the Windows executables as root, we're looking for the smallest thing available -- That's Alpine Linux.  We could make things smaller, but it would be more trouble than it's worth.  You can install Alpine on WSL directly from the Microsoft Store just as you do Ubuntu.

*

*Start by going to the Microsoft Store, search for "Alpine WSL" and install it.

*After installation, select "Open" from the Store (or just run Alpine from the Start menu).

*Add a username and password when asked.  For the sake of verifying a future step here, just use the same username that you have in Ubuntu.

*su - and enter the password you used above.

*echo -e "[user]\ndefault=root" > /etc/wsl.conf

*exit twice to exit the distribution (first to exit the su session, then to exit Alpine)

*Back in Ubuntu, run the command in Option 1 of this answer.  If you are on Windows 11 with a recent WSL release, you may need to also use Option 1.5.

*Exit Ubuntu

*Start PowerShell as a regular (non-Admin) user.

*wsl --shutdown

*wsl ~ to restart Ubuntu

*Open another terminal with PowerShell (still non-Admin) and run wsl ~ -d Alpine

*whoami to confirm that you are running as root in Alpine by default.  If not, something in the echo ... > wsl.conf step above likely went wrong and we'll need to troubleshoot.  If it is running as root, continue ...

*ls /mnt/wsl/instances and confirm that there's an Ubuntu (or Ubuntu-20.04, etc.) there.

*Make sure it contains the files in your Ubuntu distribution.  For instance (assuming Ubuntu is the distribution name), ls /mnt/wsl/instances/Ubuntu/home/$USER/ should show the same files that are in your Ubuntu home directory.  Note that this will only work if you used the same username in both Ubuntu and Alpine.
This works because /mnt/wsl is a mount that is created by WSL itself and shared among all of the WSL2 instances/distributions that you run.  Anything you place in /mnt/wsl is:

*

*available from any distribution

*ephemeral, meaning it disappears once WSL restarts.  That's not a problem because what we are placing here is actually a mount-within-a-mount back to /.  And because of the /etc/fstab line, it's actually mounted every time Ubuntu starts.

I know you are fairly new to Linux, so hopefully that make sense!  It's a lot of Linux concepts (fstab, tmpfs, mounts, etc.) put together, to be sure.

*With this in place, exit Alpine and return to Ubuntu:
echo "Hello" > ~/testfile.txt`
sudo chown root:root ~/testfile.txt
sudo chmod 600 ~/testfile.txt

... to create a file we can use to test this.  Of course, I know you already have files like this from Portainer, but this gives me a path we can use reliably.
The file should no longer be previewable in, e.g. Directory Opus.  Nor can you edit it via notepad.exe testfile.txt.

*Let's see if we can use Alpine, which we've confirmed runs as root by default, to open and edit the file in Notepad, for starters:
wsl.exe \~ -d Alpine notepad.exe /mnt/wsl/instances/$WSL_DISTRO_NAME/home/$USER/testfile.txt

If everything's working correctly (and it is for me, on two systems), you should be able to edit and save the file in Windows Notepad, even though it is owned by root and set for 600 (read-write, owner-only) permissions.

*If that works, then we have a general solution that we can use, and then tweak for other use-cases.  For example, try:
# Pass the name of your Ubuntu distro into Alpine.
# Not absolutely necessary, just a convenience.
export WSL_USER_DISTRO=$WSL_DISTRO_NAME
export WSLENV=$WSLENV:WSL_USER_DISTRO

wsl.exe \~ -d Alpine
# You are now in Alpine, running inside Ubuntu

/path/to/dopus.exe /Go $(wslpath -w /mnt/wsl/instances/$WSL_USER_DISTRO/)

You should be able to preview root-owned/protected files from Ubuntu in Directory Opus (tested and works on my end, at least).
This is fairly nested, so let me unwind a bit:

*

*We ran Ubuntu in PowerShell

*We ran wsl.exe (a Windows command) in Ubuntu, to launch ...

*Alpine inside Ubuntu

*In Alpine, we have access to all of Ubuntu's files (as root) via /mnt/wsl/Ubuntu (or similar).  And Alpine's files are shared to Windows (via 9P) as root.

*In Alpine, we launched Directory Opus (a Windows binary), which can now access the Ubuntu files as root because we are accessing them through Alpine.

Make sense?  If not, don't worry, it barely makes sense to me! ;-).
While you could, in theory, script this or alias it, you are (very/extremely/almost certainly/99.99999%) likely to get into some quoting/escaping issues as you pass paths from WSL, to Windows, to WSL, and back to Windows.
So, if the workflow works for you, I'd just launch Alpine and use it to launch any Windows executables that you want to access as root.


text: Q: Which one of the following is the best tree based regression model based on the residual plots and q-q plots? I have a regression task and have built 4 models out of which 3 of them are overfitting. I want to understand which one is the best based on the residual plots and q-q plots and how to interpret them?


text:
Q: Graceful termination of child in systemctl shutdown I liked SensorSmith answer at Forward SIGTERM to child in Bash, but for my systemctl script, it resulted in a double SIGTERM, because systemctl sends SIGTERM to the parent bash instance AND the child I am running. The result was instant termination before my child could gracefully shut down.
What's the proper way to handle SIGTERM in a bash script based service?

A: So I ended up with this and I am happy:
#!/bin/bash

script_term()
{
    echo $0 SIGTERM
}

wait_for_child()
{
    term_child_pid=$!
    wait ${term_child_pid} 2>/dev/null
    trap - TERM INT
    wait ${term_child_pid} 2>/dev/null
}

trap 'script_term' TERM INT
node index.js
wait_for_child

It waits properly in all the cases I care about, though it does not SIGTERM the child when the parent bash is SIGTERM'd.


text:
Q: Android Studio 3.0: Floating Action Button OnClick not working I am trying to make my Floating Action Button in Android Studio 3.0.1 move to a different activity. Everywhere I search, none of theme work. I am fairly new to android studio and Java. Could someone help? Thank you!
*add is the name of the activity I want to launch
The code I've got so far is (off of sketchy website):

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClick:setAction(".add", null).show();
            }
        });

And the error:

5 errors

 FAILED
:app:buildInfoGeneratorDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s

A: To help you getting started, you can find documentation on how to add a floating button here. To make it start a new activity after cliking, add the instruction in the listener:
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener()
{
   @Override
   public void onClick(View view)
   {
       startActivity(new Intent(this, YourNewActivity.class));
    }
});

A: You need to use the Snackbar while using the  floating action Button.
Example->

FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }
});


text:
Q: Wiping my hard disks, how do I pull out and sort all the music/videos/pictures? Looking to raid my hard disks but need all the important stuff out first, have not been very tidy with my file management, is there a program that will scan my computer and pull out all the video, music and pictures?
Also placing it into some sort of file structure?
I don't mind using multiple programs.
Sam

A: The media player "Banshee" will find and put all your MUSIC and VIDEO files in folders. Just be sure to set the "Copy files to media folders when importing" checkbox under "Preferences" before importing. The application "Shotwell" will take care of your pictures and copy them into folders as well. Just look for a similar option before importing... I think i says "Copy to folder when importing" or something with that meaning at least.
!!! Be aware that that when Banshee and Shotwell are done importing your media this way, you will end up with TWO copies of every file. One in your old location and one in the new where these programs put it. This means that you have to be sure you have enough room on your disk.
PS: YOU CAN CHOOSE AN EXTERNAL DISK AS YOUR IMPORT DESTINATION, THAT WAY YOU WILL BE ABLE TO FIND ALL YOUR FILES AND BACKUP AT THE SAME TIME !!!

A: You can try searching for file types.
Open the dash and type search, and open Search for Files...
Set it to Search Filesystem, and then start searching *.avi to find all .avi videos, and *.mp3 to find all mp3's.
Once a search is complete, you can copy everything to some folder.
The downside to this will be that you will need to find out what file types you have that you want to save, and that you will end up with a folder with everything mashed together (or one folder per file type if you copy to a new folder each time).
To find which file types you have on your machine, I'd suggest looking around.
Sorting your files can afterwards be done using their metadata (depending on how much they have). For you music files, you can use Ex Falso (available in the software center) to create a folder structure.
For you're videos and pictures, I don't know.

A: For pictures and videos you can try shotwell.  Shotwell will let you set an import folder and assist you with organizing them into a folder structure.


text:
Q: Find and Replace, replace is placing the character in the wrong location Here is my text: " Pulp Speed. "
I use the [A-Z] because it could contain any letter at the start.  My main objective is to replace space between the quote and first letter that starts the sentence.  My code is a find and replace:
With ActiveDocument.Range.Find

    .ClearFormatting
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = True
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    With .Replacement
        .ClearFormatting

    End With
    .Execute FindText:=ChrW(8220) & " ([\@A-Z])", Replacewith:="""\1", _
    Format:=True, Replace:=wdReplaceAll

End With

When it replaces my text i get P"ulp Speed." I am trying to remove the blank space between the Quote and the P and not put it into the word itself. How can I resolve this?
I have rearranged it and found that sometimes it works and then sometimes it doesn't.  Like it will place it one time in front and then the next time behind. I have no clue what is happening. But more than often it wont work.
Made the Updates mentioned below but still when running I am getting P"ulp Speed."

A: You set the parameters wrong for the find-object
You have to set MatchWildcards = true to enable a wildcard/regex search.
Furthermore .Wrap is not a boolean value but takes eg. wdFindContinue
So your code should look like this:
With ActiveDocument.Range.Find

    .ClearFormatting
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = True
    .MatchSoundsLike = False
    .MatchAllWordForms = False

    With .Replacement
        .ClearFormatting
    End With

    .Execute FindText:=ChrW(8220) & " ([\@A-Z])", Replacewith:="""" & "\1", _
    Format:=True, Replace:=wdReplaceAll

End With


text:
Q: Finding sum of Power series Hi could anyone help me with this question
Determine the sum of the power series:
$$S=-\sum_{n=1}^{\infty}\frac{(1-x)^n}{n}$$
Where x=1.74
I tried to differentiate this expression, but I do not know how to proceed from here.

A: Differentiating gives:
$$\frac{\mathrm{d}S}{\mathrm{d}x}=\sum_{n=1}^{\infty}(1-x)^{n-1}=\sum_{n=0}^{\infty}(1-x)^{n}=\frac{1}{1-(1-x)}=\frac{1}{x}$$
As $|1-x|<1$. We therefore can integrate with respect to $x$ to give:
$$S=\int\frac{\mathrm{d}S}{\mathrm{d}x}\:\mathrm{d}x=\ln(x)+C$$
We have that for $x=1$, $S=0$ and therefore $C=0$:
$$S=\ln(x)=\ln(1.74)$$

A: Your sum is:
$$ \sum^{\infty}_{n=1} \frac{(1-x)^n}{n}=?$$
First review thees sums:
$$ \sum^{\infty}_{n=1} x^n=\frac{x}{1-x}$$
Also:
$$ \sum^{\infty}_{n=1} (1-x)^n=\frac{1-x}{1-(1-x)}=\frac{1-x}{x}$$
$$ \sum^{\infty}_{n=1} (1-x)^n=\frac{1-x}{x} / (1-x)$$
$$ \sum^{\infty}_{n=1} (1-x)^{n-1}=\frac{1}{x} / \int dx $$
$$ \sum^{\infty}_{n=1} \frac{(1-x)^n}{n}=\int \frac{1}{x}dx=ln(x) $$
So the answer to your question would be $ln 1.74$

A: Then you get a sum of a geometric sequence.

A: If you define $$f(x) = -\sum_{i=1}^\infty \frac{(1-x)^n}{n},$$
you can see that (some justification here is needed) $$f'(x) = -\sum_{i=1}^\infty (1-x)^{n-1}$$ which you probably know how to calculate. Then, having $f',$ you can calculate $f$ as one of the indefinite integrals of $f'$.


text: Q: How do you configure auditd logs to show up in journalctl? I cannot find the usual auditd logs when doing "journalctl | grep msg=audit". However, I do see the auditd logs in /var/log/audit/audit.log and when doing ausearch. Is there a way to configure it so that the auditd logs show up in journalctl as well? Thanks.


text:
Q: Groupby and map lodash keep existing fields I have following data
[
  {
    "supplier_invoice_number": "DTR/12341",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 10025,
    "net_qty": 8,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
  },
  {
    "supplier_invoice_number": "DTR/119",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 12500,
    "net_qty": 9,
    "client_payment_req_id": 3,
    "clientidsupplier": 2,
    "markuptype": 1,
    "buyerclientid": 353,
    "markupvalue": 25
  }
]

I am using lodash group by and map to get data like this
{
buyer_price: 22525
client_payment_req_id: undefined
contract_id: "789"
net_qty: 17
}

const Data = [{
    "supplier_invoice_number": "DTR/12341",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 10025,
    "net_qty": 8,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
  },
  {
    "supplier_invoice_number": "DTR/119",
    "contract_id": 789,
    "net_amount": 10000,
    "buyer_price": 12500,
    "net_qty": 9,
    "client_payment_req_id": 3,
    "clientidsupplier": 2,
    "markuptype": 1,
    "buyerclientid": 353,
    "markupvalue": 25
  }
]
const finalData = _(Data)
  .groupBy('contract_id')
  .map((buyer_price, id) => ({
    client_payment_req_id: buyer_price['client_payment_req_id'],
    contract_id: id,
    buyer_price: _.sumBy(buyer_price, 'buyer_price'),
    net_qty: _.sumBy(buyer_price, 'net_qty'),

  }))
  .value()

console.log(finalData)
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

But I want all the remaining fields there as well
"client_payment_req_id": 3,
"clientidsupplier": 1,
"markuptype": 2,
"buyerclientid": 353,
"markupvalue": 25
In the final data I want to have remaining fields as well ,but I am not able to include them ,Please help me out here .Thanks
So the final data would look like
{
    buyer_price: 22525
    client_payment_req_id: undefined
    contract_id: "789"
    net_qty: 17,
    "client_payment_req_id": 3,
    "clientidsupplier": 1,
    "markuptype": 2,
    "buyerclientid": 353,
    "markupvalue": 25
    }

P.s -Assuming All the rest fields would be same in all records

A: You can try something like below ,your buyer_price is actually an array ,you can keep the first value like i have show below.

const Data = [{
  "supplier_invoice_number": "DTR/12341",
  "contract_id": 789,
  "net_amount": 10000,
  "buyer_price": 10025,
  "net_qty": 8,
  "client_payment_req_id": 3,
  "clientidsupplier": 1,
  "markuptype": 2,
  "buyerclientid": 353,
  "markupvalue": 25
}, {
  "supplier_invoice_number": "DTR/119",
  "contract_id": 789,
  "net_amount": 10000,
  "buyer_price": 12500,
  "net_qty": 9,
  "client_payment_req_id": 3,
  "clientidsupplier": 2,
  "markuptype": 1,
  "buyerclientid": 353,
  "markupvalue": 25
}]
const finalData = _(Data).groupBy('contract_id').map((buyer_price, id) => ({
  client_payment_req_id: buyer_price[0]['client_payment_req_id'],
  buyerclientid: buyer_price[0]['buyerclientid'],
  contract_id: id,
  buyer_price: _.sumBy(buyer_price, 'buyer_price'),
  net_qty: _.sumBy(buyer_price, 'net_qty'),
})).value()

console.log(finalData)
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>


text:
Q: How to change properties of tooltip text? I am new to google charts, trying to make calendar chart.
I am using this :
 `google.charts.load('current', {'packages':['calendar']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
   var dataTable = new google.visualization.DataTable();

   dataTable.addColumn('date' , 'date');
   dataTable.addColumn('number', 'num');
   dataTable.addColumn({ type: 'string', role:'tooltip'});

   dataTable.addRows([
      [ new Date(2017, 11, 20), 150,'Hello'],
      [ new Date(2017, 11, 21), 130,'Hello']
      ]);

   var chart = new google.visualization.Calendar(document.getElementById('tooltip_action'));

   var options = {
            title: "Calendar Chart",
            colors: ['#e0440e'],
            height: 350
          };

   chart.draw(dataTable, options);

`
It is working fine. But when I move cursor to 20/12/2017 and 21/12/2017 it is showing 'Hello' in very small text and small size.
And when I move cursor to other dates it is showing in bigger.
I want to change height and width of this text.
How to change properties of this tooltip text ???

A: you can use html tooltips, then use a css class to style them
set the following option...
    tooltip: {
      isHtml: true
    }

and column property --> p: {html: true}
dataTable.addColumn({ type: 'string', role:'tooltip', p: {html: true}});
see following working snippet...

google.charts.load('current', {
  packages: ['calendar']
}).then(function () {
  var dataTable = new google.visualization.DataTable();
  dataTable.addColumn('date' , 'date');
  dataTable.addColumn('number', 'num');
  dataTable.addColumn({ type: 'string', role:'tooltip', p: {html: true}});
  dataTable.addRows([
    [ new Date(2017, 11, 20), 150,'
Hello
'],
    [ new Date(2017, 11, 21), 130,'
Hello
']
  ]);

  var chart = new google.visualization.Calendar(document.getElementById('tooltip_action'));

  var options = {
    title: "Calendar Chart",
    colors: ['#e0440e'],
    height: 350,
    tooltip: {
      isHtml: true
    }
  };

  chart.draw(dataTable, options);
});
body {
  overflow: auto;
}

#tooltip_action {
  width: 1000px;
}

.tooltip {
  font-size: 24px;
  padding: 12px;
}


text:
Q: JQuery Ajax - PostBack issue  In My webApplication, i have load more than 2 userControls (.ascx) using Jquery Ajax. after loading the controls when postback happen on any button event i Receive this error.
"Microsoft JScript runtime error: Unable to get value of the property 'onsubmit': object is null or undefined"
Please suggest some ideas!

A: I think you can use web handlers instead of ajax user control, most of events in the page you can make it using web handlers to Dispense the cost of post back see here tutorial


text:
Q: What kind of weight does default UPS and USPS take in consideration? I'm using Magento Community 1.9.2, I'm new at this and I want to set shipping properly with UPS and USPS.
I've set weight along with length, width and height (these 3 are custom attributes) for each of my products and I can see that at shipping options only weight is taken in consideration for UPS and USPS.
I have products that fit in an envelope and products that fit in a box, so I can't charge standard flat rate.
My question is: what the measurement unit of UPS and USPS and what's the best way to setup this properly?
Thanks

A: Yes, you are right, Magento only sends weight information to UPS and USPS.

*

*The measurement unit for USPS is imperial: pounds

*The measurement unit for UPS is editable in System Configuration > Shipping Methods > UPS > Weight Unit: LBS or KGS

As it sounds like you are needing better data sent, I suggest looking into WebShopApps Dimensional Shipping module: http://webshopapps.com/us/shipping/dimensional-shipping.html. The packaging aspect can get pretty tricky, so it is nice to use a pre-built module to take care of that.


text:
Q: Uncaught TypeError when trying to initialize jQRangeSlider cdn I'm trying to add jQRangeSlider into my application because it's the only range slider plugin I've found that looks good and has a good variety of configurations. However, when I try to initialize it into my application I get this error.
Uncaught TypeError: $(...)[this._handleType(...)] is not a function
at t.<computed>.<computed>._createHandle (jQRangeSlider.min.js:1)
at t.<computed>.<computed>._createHandle (jquery-ui.min.js:6)
at t.<computed>.<computed>._createHandles (jQRangeSlider.min.js:1)
at t.<computed>.<computed>._createHandles (jquery-ui.min.js:6)
at t.<computed>.<computed>._createElements (jQRangeSlider.min.js:1)
at t.<computed>.<computed>._createElements (jquery-ui.min.js:6)
at t.<computed>.<computed>._create (jQRangeSlider.min.js:1)
at t.<computed>.<computed>._create (jquery-ui.min.js:6)
at t.<computed>.<computed>._createWidget (jquery-ui.min.js:6)
at new t.<computed>.<computed> (jquery-ui.min.js:6)

This is the cdn initialization. I'm using hanlebars as a rendering template if that makes any difference.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"
        integrity="sha512-aOG0c6nPNzGk+5zjwyJaoRUgCdOrfSDhmMID2u4+OIslr0GjpLKo7Xm0Ao3xmpM4T8AmIouRkqwj1nrdVsLKEQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />

    <link rel="stylesheet" href="/css/iThing.css">

    <title>ECM forms</title>

    {{{body}}}

This is the html and jquery

$(document).ready(() => {

    $("#slider").rangeSlider();
})

If anyone has any advice why this cdn wont work and knows how to fix it, it would be greatly appreciated! Thanks!


text:
Q: avoid broken image in angular JS I'm new to AJS so this maybe sound silly but i want to know how to avoid  broken image when the image URL coming from an expression or from user input.
maybe this explains :

Name :<input type="text" ng-model="batman" />

now i have few pics in that folder and i want when i type it in text bar they appears on the page.
but we always have this broken image showing until we didn't type the exact image name.
so is there any way to avoid the broken image to show up.
thanks

A:

If batman model does exist, then only this div will render

A: Here's a directive that hides the image element when the value of ngSrc is changed until it sees the 'load' event, then it displays the element (plunker):
app.directive('hideUntilGood', function() {
  return {
    restrict: 'A',
    multiElement: true,
    link: function(scope, element, attrs) {
      attrs.$observe('ngSrc', function (value) {
        // fix where ngSrc doesn't update when blank
        if (!value || value.length == 0) {
          element.attr('src', value);
        }
        element.css("display", "none");
      });
      element.bind('load', function() {
        element.css("display", "");
      });
    }
  };

})
Usage:


text:
Q: Is it possible to zoom map? Is it possible to zoom while viewing map?
Z works for general camera, but doesn't do so when map is opened. It's so frustrating - all devices are on the map, but icons are too small to be useful!


text:
Q: Rails: how can I write this so it won't fail if it returns nil? I'm just not sure how best to write it. Cheers!
def get_prices(c)
  @print_prices = Billing.where(:name => c).first.attributes.select{ |i| i.match(/^print_/) }
end

A: One way to do it:
def get_prices(c)
  billings = Billing.where(:name => c)
  @print_prices = billings.first.attributes.select{ |i| i.match(/^print_/) } unless billings.empty?
end

A: you should store the return value of Billing.where(:name => c).first and test it.


text:
Q: Lorentz force on superconductors? If current flows on the surface of a superconductor(for both type I & II) and is exposed to an exterior magnetic field, will a superconductor experience a Lorentz force?
Knowing that a superconductor expels the magnetic field from the interior of the material:

It seems that the magnetic field interacts with the surface charges?


text:
Q: How can I prepare a list so that the members are saved to the ninja form in wordpress and can only be seen in their own accounts? The point I have reached so far:
    foreach( array_reverse( $subs ) as $sub ){

            if( wp_get_current_user()->user_email == $sub->get_field_value( 'email' ) ){
                $merge_tags = Ninja_Forms()->merge_tags[ 'fields' ];
                foreach( $fields as $field ){
                    $field_id = $field->get_id();
                    $merge_tags->add_field( array(
                        'id' => $field->get_id(),
                        'key' => $field->get_setting( 'key' ),
                        'type' => $field->get_type(),
                        'value' => $sub->get_field_value( $field_id )
                    ));
                }
//                echo $merge_tags->replace( $form->get_setting( 'id' ) );
                print_r($merge_tags);
            } else {echo "not working";}
        }

My foreach loop does not work because the registered user and the mail registered in ninja form do not match

A: I fixed this problem. I took to data from db.
First i used this filter: 'ninja_forms_submit_data'
I caught it with var_dump while sending the data and I created an array with foreach and saved this arrray to the user meta. Thus, I was able to pull the data wherever I wanted by creating a shortcode according to the user.


text:
Q: CPU utilization degraded after upgrading java version from 1.7 to 1.8 For my application we have recently upgraded to java 1.8 from 1.7 and as per the performance test results we checked that CPU utilization is a big issue and it has increased by 71% !!
I'm using this below jvm arguments with jdk8:
    -XX:-OptimizeStringConcat -XX:SurvivorRatio=6 -XX:+UseG1GC -XX:-UseGCOverheadLimit

Apart from all these the most import thing which I'm very confused is what is the MaxMetaSpaceSize we should choose now .
For Jdk1.7 I was using :
    -Xms480M -Xmx480M -XX:MaxPermSize=192M

Kept everything same in jdk1.8 only changed the MaxPermSize to MaxMetaSpaceSize :
    -Xms480M -Xmx480M -XX:MaxMetaspaceSize=192M

Please let me know how can I improve the performance of my application . is there anything that I'm missing  - since jdk8 is using native memory area , therefore

*

*inceasing the space on the server help or not .

*I kept the value of MaxMetaspaceSize same as that of earlier - how can i decide on this value on this new architecture.


text:
Q: How to convert a recursive function into a tail-recursive version? I have a function that I can't seem to make tail recursive.
I've tried creating helper functions with extra accumulators but either the algorithm does not produce the expected results or it really is not tail recursive.
This are the functions:
    def game(boardState: BoardState,
             pieces: List[ChessPiece],
             acc: Set[BoardState]): Set[BoardState] = pieces match {
      case Nil => acc + boardState // No more pieces, boardState solved
      case x :: xs => getStates(boardState, x, xs, acc)
    }

    def getStates(boardState: BoardState,
                  piece: ChessPiece,
                  rest: List[ChessPiece],
                  acc: Set[BoardState]): Set[BoardState] = {
      // Ask if there are available squares
      if (boardState.availableSquares.nonEmpty) {
          // Get the states from every available square
        boardState.availableSquares.foldLeft(Set[BoardState]())((innerAcc, sqr) => {
          // Get the next chess piece
          val nextPiece = buildPiece(piece, sqr)
          // Check if placing the piece would result in an existing piece being attacked
          if (boardState.withPieces.forall(sqr => !nextPiece.isAttacking(sqr))) {
            // Do the recursion with the new Board State
            val newState = boardState.placePiece(nextPiece)
            innerAcc ++ game(newState, rest, acc) //This is the part that is not tail recursive
          } else innerAcc
        })
      } else {
      // There are no available places, search ends here
        acc
      }
    }

Thanks in advance for your advice!

A: Hmm, game() calls getStates() and getStates() calls game(). This looks like something that a trampoline would handle.
Here's an attempt using TailCalls from the Standard Library.
import scala.util.control.TailCalls._

def game(boardState: BoardState,
         pieces: List[ChessPiece],
         acc: Set[BoardState]): TailRec[Set[BoardState]] = pieces match {
  case Nil => done(acc + boardState) // No more pieces, boardState solved
  case x :: xs => tailcall(getStates(boardState, x, xs, acc))
}

def getStates(boardState: BoardState,
              piece: ChessPiece,
              rest: List[ChessPiece],
              acc: Set[BoardState]): TailRec[Set[BoardState]] = done{
  // Ask if there are available squares
  if (boardState.availableSquares.nonEmpty) {
    // Get the states from every available square
    boardState.availableSquares.foldLeft(Set[BoardState]())((innerAcc, sqr) => {
      // Get the next chess piece
      val nextPiece = buildPiece(piece, sqr)
      // Check if placing the piece would result in an existing piece being attacked
      if (boardState.withPieces.forall(sqr => !nextPiece.isAttacking(sqr))) {
        // Do the recursion with the new Board State
        val newState = boardState.placePiece(nextPiece)
        innerAcc ++ tailcall(game(newState, rest, acc)).result
      } else innerAcc
    })
  } else {
    // There are no available places, search ends here
    acc
  }
}

Warning: I got this to compile after dummying all the missing pieces (BoardState, ChessPiece, etc.), so I haven't actually tried to run it. Next time please post enough code to make it a minimal, complete, verifiable example.

A: Scala tail recursion optimisation requires three things:

*

*The function must be self-recursive

*The function must call itself only once for each call

*The self call must be in the tail position

In order to satisfy 1. you need fold the implementation of game into getStates.
Satisfying 2. is harder because of that foldLeft call which may cause multiple recursive calls. The solution to this is to pass the availableSquares list to the recursive function and process one element in each call. This is the trickiest thing to do.
To satisfy 3. you will need to make the final result a parameter to the call and the return that result when there is no more work to be done. When you do the recursive call you add the new data to the result and pass that down with the other parameters.
This is only an outline of the solution, but I hope it helps.


text:
Q: How to let a toast notification stay in Windows 10 Action Center with Delphi I use Delphi 10.2 in Windows 10. The following code is the sample code provided by Embarcadero.
After running this code the notification disappears and deosn't stay in Action Center. How can I let it pended there?
procedure TNotify.btnShowClick(Sender: TObject);
var
  MyNotification: TNotification;
begin
  MyNotification := NotificationCenter1.CreateNotification;
  try
    MyNotification.Name := 'Windows10Notification';
    MyNotification.Title := 'Windows 10 Notification #1';
    MyNotification.AlertBody := 'RAD Studio 10 Seattle';

    NotificationCenter1.PresentNotification(MyNotification);
  finally
    MyNotification.Free;
  end;
end;

ADDED: After turning on the toggle of Windows Setting > System > Notifications & actions I can see HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Notifications\Settings\Embarcadero.DesktopToasts.0579D43A\ShowInActionCenter is 1. But each user who would use this application can't do this all the time manually and I cannot predict the name of the key either.

A: You will find the answer here:
powershell script creates Windows 10 notification and it disappears after popup
You must register your application for "Show notifications in action center"
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\$prodName" -Name "ShowInActionCenter" -Type Dword -Value "1"
To get the $prodName use:
function TNotificationsForm.getRegisterToastMessageKey : String;
const
  AppId = 'Embarcadero.DesktopToasts.';
begin
  result := AppId + THashBobJenkins.GetHashString(ParamStr(0));
end;

Embarcadero hasn't done a good Job here but so you get the Key,
or make a copy from unit System.Win.Notification and change it to your needs.


text:
Q: How to return data from a Shell command in VB6 to a variable I am trying to get the version number from an .exe using a Shell command in one of my VB6 projects.
the code goes like this:

BoVersion = Shell("wmic datafile where name='& boPath & ' get version")

    BoVersionArr() = Split(BoVersion, ".")

        boVerYear = CStr(BoVersionArr(0))
        boVerMonth = CStr(BoVersionArr(1))
        boVerDay = CStr(BoVersionArr(2))
        boVerMin = CStr(BoVersionArr(3))

when I run the command from CMD I get

but in the VB6 project, I try to assign this into a variable and I get the following,

Does anyone know if I can convert this into a string or how to approach this? I am trying to split this and convert it into a date format which I have working.


text:
Q: Присвоение класса к элементу через индекс класса Имеется вот такая структура HTML + JQ кода.

 $(document).ready(function() {
      $('.m\\.catalog\\.personal-card\\.head').click(function() {
              $(this).toggleClass('active');
      });
})

Описание

                    Lorem ipsum dolor sit amet consectetur, adipisicing elit. Blanditiis magni magnam, tempora voluptatibus illum earum aperiam tempore unde cumque temporibus vel perferendis ut error omnis, ratione autem ab quidem tenetur.

JQ Код добавляет класс active для класса m.catalog.personal-card.head
Вот, как можно сделать что-бы добавлялся класс  active для класса m.catalog.personal-card.body. Фактически нужно узнать индекс класса m.catalog.personal-card.head и присвоить класс active для класса m.catalog.personal-card.body.
Вот код которые берёт индекс класса при клике:
            $('.m\\.catalog\\.personal-card\\.head').click(function() {
                $('.m\\.catalog\\.personal-card\\.head').index( this );
            });

Помогите продолжить код. Фактически есть всё (но это не точно), но плохо владею JQ - чтобы это все реализовать!

A: $('.m\\.catalog\\.personal-card\\.head').click(function() {
    let b = $(this).parent().children('.m\\.catalog\\.personal-card\\.body');
    b.toggleClass('active');
});

или
$('.m\\.catalog\\.personal-card\\.head').click(function() {
    let b = $(this).next('.m\\.catalog\\.personal-card\\.body');
    b.toggleClass('active');
});

или (если после элемента .head не будет элементов кроме .body)
$('.m\\.catalog\\.personal-card\\.head').click(function() {
    let b = $(this).next();
    b.toggleClass('active');
});


text:
Q: Cryptography Python Docker multistage build I have a Python project that runs in a docker container and I am trying to convert to a multistage docker build process. My project depends on the cryptography package. My Dockerfile consists of:
# Base
FROM python:3.6 AS base

RUN pip install cryptography

# Production
FROM python:3.6-alpine

COPY --from=base /root/.cache /root/.cache

RUN pip install cryptography \
        && rm -rf /root/.cache

CMD python

Which I try to build with e.g:
docker build -t my-python-app .

This process works for a number of other Python requirements I have tested, such as pycrypto and psutil, but throws the following error for cryptography:
Step 5/6 : RUN pip install cryptography         && rm -rf /root/.cache
 ---> Running in ebc15bd61d43
Collecting cryptography
  Downloading cryptography-2.1.4.tar.gz (441kB)
Collecting idna>=2.1 (from cryptography)
  Using cached idna-2.6-py2.py3-none-any.whl
Collecting asn1crypto>=0.21.0 (from cryptography)
  Using cached asn1crypto-0.24.0-py2.py3-none-any.whl
Collecting six>=1.4.1 (from cryptography)
  Using cached six-1.11.0-py2.py3-none-any.whl
Collecting cffi>=1.7 (from cryptography)
  Downloading cffi-1.11.5.tar.gz (438kB)
    Complete output from command python setup.py egg_info:

        No working compiler found, or bogus compiler options passed to
        the compiler from Python's standard "distutils" module.  See
        the error messages above.  Likely, the problem is not related
        to CFFI but generic to the setup.py of any Python package that
        tries to compile C code.  (Hints: on OS/X 10.8, for errors about
        -mno-fused-madd see http://stackoverflow.com/questions/22313407/
        Otherwise, see https://wiki.python.org/moin/CompLangPython or
        the IRC channel #python on irc.freenode.net.)

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-uyh9_v63/cffi/

Obviously I was hoping not to have to install any compiler on my production image. Do I need to copy across another directory other than /root/.cache?

A: There is no manylinux wheel for Alpine, so you need to compile it yourself. Below is pasted from documentation on installation. Install and remove build dependencies in the same command to only save the package to the docker image layer.

If you are on Alpine or just want to compile it yourself then
  cryptography requires a compiler, headers for Python (if you're not
  using pypy), and headers for the OpenSSL and libffi libraries
  available on your system.
Alpine Replace python3-dev with python-dev if you're using Python 2.
$ sudo apk add gcc musl-dev python3-dev libffi-dev openssl-dev

If you get an error with openssl-dev you may have to use libressl-dev.

Docs can be found here

A: I hope, my answer will be useful.

*

*You should use --user option for cryptography installing via pip in base stage. Example: RUN pip install --user cryptography. This option means, that all files will be installed in the .local directory of
the current user's home directory.

*COPY --from=base /root/.local /root/.local, because cryptography installed in /root/.local.

Thats all. Full example docker multistage
# Base
FROM python:3.6 AS base

RUN pip install --user cryptography

# Production
FROM python:3.6-alpine

COPY --from=base /root/.local /root/.local

RUN pip install cryptography \
        && rm -rf /root/.cache

CMD python


text:
Q: Is there a Clojure in memory data store? I program mostly in Node, and like document stores, but I'd like to prototype the data calls between the client and the server first.  I've used lowdb and da-base in the past to setup a quick Json data store.  Is there something similar for Clojure?

A: Given that you are just prototype, if you don't need durability, a simple atom will do. If you want durability using simple files have a look at https://github.com/alandipert/enduro
You can have one atom per table or you can have an atom with a map of table->docs, whatever you find simpler. Any query will just be a filter.
For example, to add a document:
(def my-db (atom {}))
(defn add [table doc] (swap! my-db update-in [table] conj doc))
(defn search-by-name [table name]
    (filter #(= name (:name %)) (get @my-db table)))

A: Datascript seems like a perfect (though poorly named) fit for your needs. Basically, it's a lightweight in-memory store designed after Datomic. With a map-in-an-atom approach you very quickly would find yourself writing quirky code for selection, id management, etc. Datascript takes care of such stuff and allows you to write complex queries easily, still being almost as lightweight as a map in an atom.


text:
Q: How to merge the property with same key in two object array? There are two object array,  some of them have the same key, I'd like to merge the same key in the first array. I have pasted my code.I used nested loop, but the performance was bad O(n²). Maybe I need another method to enhance performance.(I can't use ES6 for some reason, so I'll appreciate if it is the ES5 method.)
var people = [
    {
       id: "001",
       name: "David",
       age: 29
    },
    {
       id: "002",
       name: "Lucia",
       age: 41
    },
    {
       id: "003",
       name: "Steve",
       age: 18
    }
];

var address = [
    {
        id: "001",
        city: "Barcelona"
    },
    {
        id: "002",
        city: "Paris"
    },
    {

    },
    {
        id: "003",
        city: "Tokyo"
    },
    {
        id: "004",
        city: "Barcelona"
    }
];

My code
people.forEach(function(item) {
  var id = item.id;
    address.forEach(function(location) {
      if (location.id == id) {
        item.address = location.address
      }
     });
});

Result
var people = [
    {
       id: "001",
       name: "David",
       age: 29,
       city: "Barcelona"
    },
    {
       id: "002",
       name: "Lucia",
       age: 41,
       city: "Paris"
    },
    {
       id: "003",
       name: "Steve",
       age: 18,
       city: "Tokyo"
    }
];

The new people array is I preferred.

A: Make a Map with cities by id, and use it when iterating over the people array to find out the city:
let cities = new Map(address.map(a => [a.id, a.city]));
let people2 = people.map(p => ( {...p, city: cities.get(p.id)} ));

A: You could take a Map with all addresses and then map new object with extended properties of the map.
This approach takes all properties of address objects.

var people = [{ id: "001", name: "David", age: 29 }, { id: "002", name: "Lucia", age: 41 }, { id: "003", name: "Steve", age: 18 }],
    address = [{ id: "001", city: "Barcelona" }, { id: "002", city: "Paris" }, {}, { id: "003", city: "Tokyo" }, { id: "004", city: "Barcelona" }],
    map = new Map(address.map(o => [o.id, o])),
    result = people.map(o => Object.assign({}, o, map.get(o.id)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You could use Array#map to iterate over people, and Array#find to find the corresponding address from id within iterations:

const people = [{id: "001",name: "David",age: 29 },{ id: "002", name: "Lucia", age: 41
},{ id: "003", name: "Steve", age: 18 }],
  address = [{ id: "001", city: "Barcelona" },{ id: "002", city: "Paris" },{ },{ id: "003", city: "Tokyo" },{ id: "004", city: "Barcelona" }];

console.log(
  people.map(p => ({
    ...p,
    ...address.find(a => (p.id === a.id))
  }))
);

However, that's supposing that the properties' name of address's items are not the same as people's ones.

A: The code below is not tested but it should work
// create an object to store them
const mergedItems = {};

// merge the 2 arrays so you only map them once (just for shorter code)
people.concat(address).map(entity => {
  // add each entity on the object and id as a key
  mergedItems[entity.id] = {

    // if the key exist, it will merge it with the new entity
    ...mergedItems[entity.id],
    ...entity,
  }
)

// this is your merged items
// Object.values will convert it from object to array
const finalItems = Object.values(mergedItems);

I used map instead of for loop because it is faster: https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

A: I have used Object.assign method to add values from address
   var people = [{ id: "001", name: "David", age: 29 }, { id: "002", name: "Lucia", age: 41 }, { id: "003", name: "Steve", age: 18 }],
        address = [{ id: "001", city: "Barcelona" }, { id: "002", city: "Paris" }, {}, { id: "003", city: "Tokyo" }, { id: "004", city: "Barcelona" }];

        people.forEach(function(item,pos){
            Object.assign(item,{},address[address.findIndex(o=>o.id == item.id)]);
        });
        console.log(people);


text:
Q: AWS SNS publish 404 error I have a lambda function where I am trying to publish a message to SNS topic:
Here is the code:
var params = {
    Message: origmessage,
    Subject: "Retrying posting URL",
    TopicArn: "arn:aws:sns:us-west-2:<acctid>:SampleTopic"
};
sns.publish(params, function(err, data) {
    if (err) {
        console.log("SNS publish error")
        console.log(err, err.stack)
        console.log(data, data)
        console.log("RETRY PARAMS:" + params);
        context.fail(err);
    }
});

SNS publish error is cryptic as I am unable to find the root cause. Appreciate if someone can help me show a way to debug this.
Here is the error:
2017-01-19T00:41:13.947Z d440064d-dddf-11e6-abad-8de6d2739d36 {
  [404: null]
  message: null,
  code: 404,
  time: Thu Jan 19 2017 00:41:13 GMT+0000 (UTC),
  requestId: '0ENTKJ09RT82VE0SFEUJKT75NVVV4KQNSO5AEMVJF66Q9ASUAAJG',
  statusCode: 404,
  retryable: false,
  retryDelay: 26.97333029936999
}
'404: null
at Request.extractError (/var/task/node_modules/aws-sdk/lib/protocol/query.js:45:29)
at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at Request.emit (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:77:10)
at Request.emit (/var/task/node_modules/aws-sdk/lib/request.js:668:14)
at Request.transition (/var/task/node_modules/aws-sdk/lib/request.js:22:10)
at AcceptorStateMachine.runTo (/var/task/node_modules/aws-sdk/lib/state_machine.js:14:12)
at /var/task/node_modules/aws-sdk/lib/state_machine.js:26:10
at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:38:9)
at Request.<anonymous> (/var/task/node_modules/aws-sdk/lib/request.js:670:12)
at Request.callListeners (/var/task/node_modules/aws-sdk/lib/sequential_executor.js:115:18)'

A: As per your comments, when you use AWS.config.update, it affects all services.
By setting the endpoint parameter to the dynamodb endpoint, you are setting that endpoint for all services, including SNS.
This is an offending example where it says to specify the endpoint for dynamodb:
http://docs.aws.amazon.com/amazondynamodb/latest/gettingstartedguide/GettingStarted.NodeJs.Summary.html
Instead, the endpoint should be taken out of AWS.config.update and somehow specified in each service's constructor.

A: Matt - That was it. Dynamodb config was what was causing this issue. Appreciate all your help.
Thanks


text:
Q: GamePlay3d engine won't show model imported from fbx I am a newbie with gameplay3d and went through all tutorials, however I cant manage to display this simple(not much polygons and material) model that I encoded from Fbx. I checked the model with unity3D, and a closed source software that uses gameplay3d and all seems to fine. I guess I am missing some detail loading the scene.
This is the model file including also the original fbx file. I suspect if it has something to do with light
https://www.dropbox.com/sh/ohgpsfnkm3iv24s/AACApRcxwtbmpKu4_5nnp8rZa?dl=0
This is the class that loads the scene.
#include "Demo.h"

// Declare our game instance
Demo game;

Demo::Demo()
    : _scene(NULL), _wireframe(false)
{
}

void Demo::initialize()
{
    // Load game scene from file
    Bundle* bundle = Bundle::create("KGN56AI30N.gpb");
    _scene = bundle->loadScene();
    SAFE_RELEASE(bundle);
    // Get the box model and initialize its material parameter values and bindings

    Camera* camera = Camera::createPerspective(45.0f, getAspectRatio(), 1.0f, 20.0f);
    Node* cameraNode = _scene->addNode("camera");

    // Attach the camera to a node. This determines the position of the camera.
    cameraNode->setCamera(camera);

    // Make this the active camera of the scene.
    _scene->setActiveCamera(camera);
    SAFE_RELEASE(camera);
    // Move the camera to look at the origin.
    cameraNode->translate(0,0, 10);
    cameraNode->rotateX(MATH_DEG_TO_RAD(0.25f));
    // Update the aspect ratio for our scene's camera to match the current device resolution
    _scene->getActiveCamera()->setAspectRatio(getAspectRatio());
    // Set the aspect ratio for the scene's camera to match the current resolution
    _scene->getActiveCamera()->setAspectRatio(getAspectRatio());

    Light* directionalLight = Light::createDirectional(Vector3::one());
    _directionalLightNode = Node::create("directionalLight");
    _directionalLightNode->setLight(directionalLight);
    SAFE_RELEASE(directionalLight);
    _scene->addNode(_directionalLightNode);
    _scene->setAmbientColor(1.0, 1.0, 1.0);
  _scene->visit(this, &Demo::initializeMaterials);

}

bool Demo::initializeMaterials(Node* node)
{
        Model* model = dynamic_cast<Model*>(node->getDrawable());

        if (model)
        {
            for(int i=0;i<model->getMeshPartCount();i++)
            {
            Material* material = model->getMaterial(i);
            if(material)
            {
            // For this sample we will only bind a single light to each object in the scene.
            MaterialParameter* colorParam = material->getParameter("u_directionalLightColor[0]");
            colorParam->setValue(Vector3(0.75f, 0.75f, 0.75f));
            MaterialParameter* directionParam = material->getParameter("u_directionalLightDirection[0]");
            directionParam->setValue(Vector3(1, 1, 1));
            }
            }
        }
        return true;
}

void Demo::finalize()
{
    SAFE_RELEASE(_scene);
}

void Demo::update(float elapsedTime)
{
    // Rotate model
    //_scene->findNode("box")->rotateY(MATH_DEG_TO_RAD((float)elapsedTime / 1000.0f * 180.0f));
}

void Demo::render(float elapsedTime)
{
    // Clear the color and depth buffers
    clear(CLEAR_COLOR_DEPTH, Vector4::zero(), 1.0f, 0);

    // Visit all the nodes in the scene for drawing
    _scene->visit(this, &Demo::drawScene);
}

bool Demo::drawScene(Node* node)
{
    // If the node visited contains a drawable object, draw it
    Drawable* drawable = node->getDrawable();
    if (drawable)
        drawable->draw(_wireframe);

    return true;
}

void Demo::keyEvent(Keyboard::KeyEvent evt, int key)
{
    if (evt == Keyboard::KEY_PRESS)
    {
        switch (key)
        {
        case Keyboard::KEY_ESCAPE:
            exit();
            break;
        }
    }
}

void Demo::touchEvent(Touch::TouchEvent evt, int x, int y, unsigned int contactIndex)
{
    switch (evt)
    {
    case Touch::TOUCH_PRESS:
        _wireframe = !_wireframe;
        break;
    case Touch::TOUCH_RELEASE:
        break;
    case Touch::TOUCH_MOVE:
        break;
    };
}

A: I can't download your dropbox .fbx file.  How many models do you have in the scene?  Here's a simple way of doing what you want to do -- not optimal, but it'll get you started...
So first off, I can't see where in your code you actually assign a Shader to be used with the material.  I use something like this:
material = model->setMaterial("Shaders/Animation/ADSVertexViewAnim.vsh", "Shaders/Animation/ADSVertexViewAnim.fsh");

You need to assign a Shader, and the above code will take the vertex and fragment shaders and use that when the object needs to be drawn.
I went about it a slightly different way by not loading the scene file automatically, but creating an empty scene and then extracting my model from the bundle and adding it to the scene manually.  That way, I can see exactly what is happening and I'm in control of each step.  GamePlay3D has some fancy property files, but use them only once you know how the process works manually..
Initially, I created a simple cube in a scene, and created a scene manually, and added the monkey to the node graph, as follows:
void GameMain::ExtractFromBundle()
{
    /// Create a new empty scene.
    _scene = Scene::create();

    // Create the Model and its Node
    Bundle* bundle = Bundle::create("res/monkey.gpb");          // Create the bundle from GPB file

    /// Create the Cube
    {
        Mesh* meshMonkey = bundle->loadMesh("Character_Mesh");              // Load the mesh from the bundle
        Model* modelMonkey = Model::create(meshMonkey);
        Node* nodeMonkey = _scene->addNode("Monkey");
        nodeMonkey->setTranslation(0,0,0);
        nodeMonkey->setDrawable(modelMonkey);
    }
}

Then I want to search the scene graph and only assign a material to the object that I want to draw (the monkey).  Use this if you want to assign different materials to different objects manually...
bool GameMain::initializeScene(Node* node)
{
    Material* material;

    std::cout << node->getId() << std::endl;

    // find the node in the scene
    if (strcmp(node->getId(), "Monkey") != 0)
        return false;

    Model* model = dynamic_cast<Model*>(node->getDrawable());
    if( !model )
        return false;

    material = model->setMaterial("Shaders/Animation/ADSVertexViewAnim.vsh", "Shaders/Animation/ADSVertexViewAnim.fsh");

    material->getStateBlock()->setCullFace(true);
    material->getStateBlock()->setDepthTest(true);
    material->getStateBlock()->setDepthWrite(true);

    // The World-View-Projection Matrix is needed to be able to see view the 3D world thru the camera
    material->setParameterAutoBinding("u_worldViewProjectionMatrix", "WORLD_VIEW_PROJECTION_MATRIX");

    // This matrix is necessary to calculate normals properly, but the WORLD_MATRIX would also work
    material->setParameterAutoBinding("u_worldViewMatrix", "WORLD_VIEW_MATRIX");
    material->setParameterAutoBinding("u_viewMatrix", "VIEW_MATRIX");

    return true;
}

Now the object is ready to be drawn.... so I use these functions:
void GameMain::render(float elapsedTime)
{
    // Clear the color and depth buffers
    clear(CLEAR_COLOR_DEPTH, Vector4(0.0, 0.0, 0.0, 0.0), 1.0f, 0);

    // Visit all the nodes in the scene for drawing
    _scene->visit(this, &GameMain::drawScene);
}

bool GameMain::drawScene(Node* node)
{
    // If the node visited contains a drawable object, draw it
    Drawable* drawable = node->getDrawable();
    if (drawable)
        drawable->draw(_wireframe);

    return true;
}

I use my own shaders, so I don't have to worry about Light and DirectionalLight and all that stuff.  Once I can see the object, then I'll add dynamic lights, etc, but for starters, start simple.
Regards.


text:
Q: 'str' object is not callable when i am trying to delete from Django admin interface? I'm getting this error when I am trying to delete object from django admin panel:
TypeError at /admin/carts/cart/21/delete/
'str' object is not callable
Request Method: GET
Request URL:    http://localhost:8000/admin/carts/cart/21/delete/
Django Version: 2.2.6
Exception Type: TypeError
Exception Value:
'str' object is not callable
Exception Location: C:\Users\HP\spippt\ppt\lib\site-packages\django\db\models\deletion.py in collect, line 224
Python Executable:  C:\Users\HP\spippt\ppt\Scripts\python.exe
Python Version: 3.7.0
Python Path:
['C:\\Users\\HP\\spippt\\ppt\\myproject',
 'C:\\Users\\HP\\spippt\\ppt\\Scripts\\python37.zip',
 'C:\\Users\\HP\\spippt\\ppt\\DLLs',
 'C:\\Users\\HP\\spippt\\ppt\\lib',
 'C:\\Users\\HP\\spippt\\ppt\\Scripts',
 'C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib',
 'C:\\Users\\HP\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\HP\\spippt\\ppt',
 'C:\\Users\\HP\\spippt\\ppt\\lib\\site-packages']
Server time:    Wed, 11 Dec 2019 12:14:29 +0530


text:
Q: symfony: permalinks (hide id in urls) I've read the paragraph about permalinks (hide primary keys and replace them with significant strings) but I can't understand how it works this code:
public function executePermalink($request)
  {
    $article = ArticlePeer::retrieveBySlug($request->getParameter('slug');
    $this->forward404Unless($article);  // Display 404 if no article matches slug
    $this->article = $article;          // Pass the object to the template
  }

This code is typical of propel, is it right? there is something like it for doctrine? I've to write the retrieveBySlug() function? do you have an example where I can understand how to write it?
Thanks a lot

A: In Doctrine you have an extension called "Sluggable" you can use.
To make it work you have to change your schema.yml and add the "Sluggable" extension:
# config/doctrine/schema.yml
Article:
  actAs:
    Timestampable: ~
    Sluggable:
      fields: [name]
  columns:
    name:
      type: string(255)
      notnull:  true

Set up a DoctrineRoute in your routing.yml
# apps/frontend/config/routing.yml
category:
  url:      /article/:slug
  class:    sfDoctrineRoute
  param:    { module: article, action: show }
  options:  { model: Article, type: object }

Then in your code for the action you can do something like this :
public function executeShow(sfWebRequest $request)
{
    $this->article = $this->getRoute()->getObject();
    $this->forward404Unless($article);  // Display 404 if no article matches slug
    $this->article = $article;          // Pass the object to the template
}

Don't forget to run a doctrine:build to recreate the database after you alter your schema.

A: now is working fine!
# apps/frontend/config/routing.yml
opera_slug:
  url:   /:sf_culture/opere/:operaslug.html
  class:    sfDoctrineRoute
  param: { module: opera, action: permalink }
  options:  { model: Opera, type: object }
  requirements:
    sf_culture: (?:it|en|es|fr)

  public function executePermalink(sfWebRequest $request)
  {
    $this->opera = $this->getRoute()->getObject();
    $this->forward404Unless($this->opera);  // Display 404 if no article matches slug
    //$this->opera = $opera;          // Pass the object to the template
  }

As you can see, I've modified last two rows of executePermalink(), because I had an error using your function


text: Q: DNS changes automatically to porn site DNS I am using OS X Mavericks 10.9.4 and Windows 8.1 with Boot Camp. It is not happening everyday but it happens at least in every 3-4 days. When I log in to 192.168.1.1 and check my DNS they are just some porn sites. I change them to the Google DNS and even tried to change it to Use Auto Discovered DNS Server Only option. Still no luck. I scanned my system with ClamXav and Kaspersky I got nothing.


text:
Q: "file not found" on travis-ci when running pytest from tox using docker I'm trying to run my tests throught travis-ci, but i receive
"file not found tests" error. When i run local with same command everything is ok, but in travis i receive this error. I think its because tests folder which in root of my project located somewhere in other directory - in directory where travis copy github repo.
I try this settings in tox.ini but none of whem help:
commands = py.test $TRAVIS_BUILD_DIR/tests {posargs}

passenv = TRAVIS_BUILD_DIR
commands = py.test $TRAVIS_BUILD_DIR/tests {posargs}

commands = py.test {env:TRAVIS_BUILD_DIR:.}/tests {posargs}

My setup:
My .travis.yml
sudo: required

language: python

services:
  - docker

script:
  - docker-compose run tox

My docker compose file
version: '2'

services:
  db:
    image: postgres
  tox:
    build: .
    depends_on:
      - db
    volumes:
      - ".:/src:ro"

My tox.ini
[tox]
envlist = {py27}-{django18,django19,django110,django111},{py35}-{django18,django19,django110,django111,django20}
skipsdist = {env:TOXBUILD:false}

[testenv]
sitepackages = False
deps=
    pytest==2.9.2
    pytest-capturelog==0.7
    pytest-django==2.9.1
    psycopg2==2.7.3.2
    pytest-pep8==1.0.6
    freezegun==0.3.9
    pytz==2017.3

    django18: Django>=1.8,<1.9
    django19: Django>=1.9,<1.10
    django110: Django>=1.10,<1.11
    django111: Django>=1.11,<2.0
    django20: Django>=2.0,<2.1
commands = py.test tests {posargs}

My pytest.ini
[pytest]
addopts=-l -q --capture=no
pep8ignore = E501
norecursedirs = .robe .idea
python_files = tests.py test_*.py
DJANGO_SETTINGS_MODULE = test_app.settings

My dockerfile:
FROM themattrix/tox


text:
Q: Choppy jQuery Animation in Chrome and Safari? I'm was trying to do a parallax effect and that requires animating 3 background at the same time with different values so I used this code,
bgImage1.animate({
    "backgroundPosition" : -bgpos + "px"
}, {
    queue : false,
    duration : 1000,
    easing : "circEaseOut"
});

bgImage2.animate({
    "backgroundPosition" : -1.3 * bgpos + "px"
}, {
    queue : false,
    duration : 1000,
    easing : "circEaseOut"
});

bgImage3.animate({
    "backgroundPosition" : -1.6 * bgpos + "px"
}, {
    queue : false,
    duration : 1000,
    easing : "circEaseOut"
});

It worked perfectly on IE, Opera and Firefox but it's very slow and choppy on chrome and safari, the 3 backgrounds are a bit large, but when I tested with smaller ones; I got the same result, I can't find a reason for that :( here's a preview


text:
Q: How to get the ControllerContext instance, where the exception comes from in the Error action in ASP.NET Core? My Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // ...

    // If exception occurs -> execute /Error/Index
    app.UseExceptionHandler("/Error/Index");

    // ...
}

My Error Controller:
public class ErrorController : Controller
{
    public IActionResult Index()
    {
        var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
        if (exceptionFeature == null || exceptionFeature.Error == null)
        {
            new Exception("Please configure app.UseExceptionHandler(\"/Error/Index\");");
        }

        // TODO:

        // How can I get the ControllerContext instance that the Exception comes from

        return View();
    }
}

TestController:
public class TestController : Controller
{
    public IActionResult Index()
    {
        throw new Exception("Sample error");
    }
}

If I access: http://localhost:12345/MyApp/Test/Index
-> "Sample Error" will be generated
-> The ErrorController/index will get executed
-> I need to access the ControllerContext of the TestController (NOT ErrorController) in the ErrorController/index
Any helps? Thank you!


text:
Q: Ubuntu 16.04 slow boot/login time - xorg crashing on startup I'm running Ubuntu 16.04, 64 bit, 11.7GB ram, Intel i7-3770 processor, 2TB rotating disk. I've got 3 monitors and I use 6 virtual work spaces and I'm using unity.
On a reboot, the desktop loads very slowly after I log in and the visual layout of panels gets "stuck" for a while with fragmented panels. The mouse is trapped inside one monitor and unity is partially responsive with a lot of lag. After about 20-30 seconds it fixes itself and my desktop becomes normal. Could this slowness be related to having a rotating disk?
I get the usual "System Program Problem Detected" pop up after my first login. I cleaned out my /var/crash/ dir and rebooted and I still get the error so I don't think it's stale crash logs.
There is one crash file (which I've elided):
_usr_lib_xorg_Xorg.0.crash:
ProblemType: Crash
Architecture: amd64
Date: Tue May 16 09:11:00 2017
DistroRelease: Ubuntu 16.04
ExecutablePath: /usr/lib/xorg/Xorg
ExecutableTimestamp: 1485390561
ProcCmdline: /usr/lib/xorg/Xorg -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch
ProcCwd: /
ProcEnviron:
ProcMaps:
 ...
ProcStatus:
 Name:  Xorg
 Umask: 0022
 State: S (sleeping)
 ...
 voluntary_ctxt_switches:   4088352
 nonvoluntary_ctxt_switches:    204945
Signal: 6
Uname: Linux 4.8.0-49-generic x86_64
UserGroups:
CoreDump: base64
 ...

I've done a couple of reboots clearing the crash logs each time and consistently get the same ProcCmdline:
/usr/lib/xorg/Xorg -core :0 -seat seat0 -auth /var/run/lightdm/root/:0 -nolisten tcp vt7 -novtswitch

Here is the output of systemd-analyze blame | head:
8.827s docker.service
7.404s dev-sda2.device
3.171s apparmor.service
2.087s ModemManager.service
1.893s dev-loop2.device
1.864s accounts-daemon.service
1.710s thermald.service
1.667s NetworkManager.service
1.569s plymouth-start.service
1.408s systemd-timesyncd.service

Thanks in advance!

A: More of a comment, but I lack the reputation...
The crash log you've provided points to LightDM crashing. LightDM, among other things, is responsible for showing the greeter/login screen. Since your problem occurs after you login, the crash log is likely unrelated. Nevertheless, you could try installing a different display manager. Here are instructions on how to switch from LightDM to GDM. Probably not your root cause, but always worth a shot when LightDM is giving you lemons.

A: Switching to a solid state disk fixed this. Reduced boot time by 20+ seconds!
Like Josh A. pointed out, it wasn't related to xorg crashing.


text:
Q: Excel How To Repeat multiple values based on a Cell Value X Times To Anyone who can help... Thanks in advance.
Each row of item number, pack, and size is needs to be repeated multiple times in a separate sheet based on the number in the column "number of labels"
(please note: the number in the number of labels is for test purposes only and does not need to increment)
Sheet 1 would be as follows
Item #  Pack    Size    Number of Labels
12545   20      1.8oz   1
56010   6       4PK     2
70091   6       7oz     3
61816   24      1.6oz   4

4
I would like sheet 2 to output the like the following:
Item #  Pack    Size
12545   20      1.8oz
56010   6        4PK
56010   6        4PK
70091   6        7oz
70091   6        7oz
70091   6        7oz
61816   24       1.6oz
61816   24       1.6oz
61816   24       1.6oz
61816   24       1.6oz

I found the following code but I want the cell input ranges to be fixed and to not use the dialog boxesI need help modifying the code I have found in order to work with my given problem.  I need the following code to output multiple colomns. :
(i got the code here  :https://www.extendoffice.com/documents/excel/1897-excel-repeat-cell-value-x-times.html#a2 )
Sub CopyData()
'Update 20140724
Dim Rng As Range
Dim InputRng As Range, OutRng As Range
xTitleId = "KutoolsforExcel"
Set InputRng = Application.Selection
Set InputRng = Application.InputBox("Range :", xTitleId, InputRng.Address, Type:=8)
Set OutRng = Application.InputBox("Out put to (single cell):", xTitleId, Type:=8)
Set OutRng = OutRng.Range("A1")
For Each Rng In InputRng.Rows
    xValue = Rng.Range("A1").Value
    xNum = Rng.Range("B1").Value
    OutRng.Resize(xNum, 1).Value = xValue
    Set OutRng = OutRng.Offset(xNum, 0)
Next
End Sub

The hacking I have tried to do is not working any help would be great.
Context: I have to create many labels at my job for new products. I have to manually type out each label in Word. I found that I could use Words Mail merge operation to import excel data. I have those parts working but now I need to be able to get the exact number of labels I need for each item.

A: Private Sub hereyago()

    Dim arr As Variant
    Dim wsO As Worksheet
    Dim this As Integer

    arr = ThisWorkbook.Sheets("Sheet1").UsedRange
    Set wsO = ThisWorkbook.Sheets("Sheet2")

    For i = LBound(arr, 1) To UBound(arr, 1)
        If IsNumeric(arr(i, 4)) Then
            this = arr(i, 4)
            For h = 1 To this
                wsO.Cells(wsO.Rows.count, 1).End(xlUp).Offset(1, 0).Value = arr(i, 1)
                wsO.Cells(wsO.Rows.count, 1).End(xlUp).Offset(0, 1).Value = arr(i, 2)
                wsO.Cells(wsO.Rows.count, 1).End(xlUp).Offset(0, 2).Value = arr(i, 3)
                wsO.Cells(wsO.Rows.count, 1).End(xlUp).Offset(0, 3).Value = arr(i, 4)
            Next h
        End If
    Next i
End Sub


text:
Q: Is there a Postgres array overlap (&&) operator for EF Core 3.0 Npgsql Given a DBSet<Tasks> with a column tags text[]. Is there a way in EF Core Npgsql to query for tags in common with a supplied list of tags using the Postgres overlap (&&) operator e.g.
select * from tasks where tag && '{bug, feature}'

I can't find anything related to this, and I'd like to avoid client-side evaluation. I'd like to do something like
var tags = new List<string> { "bug", "feature" };
var foo = _db.Tasks.Where(x => x.Tags && tags); // obviously this doesn't work

I also tried the linq contains method
var foo = _db.Tasks.Where(x => x.Tags.Any(x => tags.Contains(x)));

but received the exception that the linq expression could not be translated.

A: Support for array overlap (&&) and containment (@>) has been added for version 3.1, which should be released very soon (see https://github.com/npgsql/efcore.pg/issues/1135).
If any other operators are needed and not translated, please open a new issue.


text:
Q: How to freeze animated gifs/convert to jpg with PHP? I have a page with a bunch of animated gifs and I would like to use PHP to either freeze them on page load or convert each one to jpg/png. I came across this http://php.net/manual/en/function.imagecreatefromgif.php but I'm not too familiar with PHP. Any help?

A: Here is the code to convert animated gif to jpg. Taken from This comment on the PHP manual entry
<?php

//This function gif2jpeg take three parameter as argument. two argument are optional
//first will take the gif file name. second for file name to save the converted file. third argument is an color array

//EXAMPLE:
$gifName = $_GET['gif_name']; //ABSOLUTE PATH OF THE IMAGE (according to its location)
$c['red']=255;
$c['green']=0;
$c['blue']=0;
echo gif2jpeg($gifName, '', $c);

function gif2jpeg($p_fl, $p_new_fl='', $bgcolor=false){
  list($wd, $ht, $tp, $at)=getimagesize($p_fl);
  $img_src=imagecreatefromgif($p_fl);
  $img_dst=imagecreatetruecolor($wd,$ht);
  $clr['red']=255;
  $clr['green']=255;
  $clr['blue']=255;
  if(is_array($bgcolor)) $clr=$bgcolor;
  $kek=imagecolorallocate($img_dst,
                  $clr['red'],$clr['green'],$clr['blue']);
  imagefill($img_dst,0,0,$kek);
  imagecopyresampled($img_dst, $img_src, 0, 0,
                  0, 0, $wd, $ht, $wd, $ht);
  $draw=true;
  if(strlen($p_new_fl)>0){
    if($hnd=fopen($p_new_fl,'w')){
      $draw=false;
      fclose($hnd);
    }
  }
  if(true==$draw){
    header("Content-type: image/jpeg");
    imagejpeg($img_dst);
  }else imagejpeg($img_dst, $p_new_fl);
  imagedestroy($img_dst);
  imagedestroy($img_src);
}

?>

How to use:

*

*Add the above code into a php file 'convertGifToJpeg.php'

*Add an <img tag. <img src="http://apllicationdomainpath/convertGifToJpeg.php?gif_name=/images/animated_gif.gif"  width="200" height="200"  />

*Make sure have given correct name/path for both the gif image and php file.


text:
Q: cerrar aplicaciones desde el SDK de android Me gustaría saber si existe alguna librería o método que me permita ver los procesos que están corriendo en el dispositivo y cerrar alguno, por ejemplo la app de YouTube.
Utilizó eclipse y el SDK de android.

A: Lo puedes ver en el mismo IDE, cuando tienes tu dispositivo conectado, desde el DDMS en la sección Devices:

Ahi puedes ver los procesos ejecutandose en el dispositivo, puedes seleccionar y detenerlos.
En el caso de Android Studio, puedes ver los procesos por medio del Android Device Monitor.


text:
Q: Simulations of discrete transfer functions with different results I have created 'same' discrete transfer function in two different modes. Then I simulated them against the same input.
Why are the results different? What is the difference between the two?
Code:
close all;clear;clc;
Ts=0.001;
t = 0:Ts:10;
%input
u=rand(length(t),1);
%1st TF
test_tf=c2d( tf([8 18 32],[1 6 14 24]),Ts );
y=lsim(test_tf,u,t);
%2nd TF
test_d_tf=tf([0.007985 -0.01595 0.007967],[1 -2.994 2.988 -0.994],Ts);
y_d=lsim(test_d_tf,u,t);
%plotting
plot(t,u,'k:',t,y,'b-',t,y_d,'r--');

And their results are:
Entire simulation interval:

and Zoomed:

A: My guess is because the tfs aren't actually the same, they only look it because of the formatting:
>>format long
>>test_d_tf.Numerator{1}
ans =
     0   0.007985000000000  -0.015950000000000   0.007967000000000
>> test_tf.Numerator{1}

ans =
     0   0.007985016651180  -0.015952055311304   0.007967070564278


text:
Q: jQuery show for 5 seconds then hide I'm using .show to display a hidden message after a successful form submit.
How to display the message for 5 seconds then hide?

A: Just as simple as this:
$("#myElem").show("slow").delay(5000).hide("slow");

A: You can use .delay() before an animation, like this:
$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:
$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.
Or, another option is to use .delay() and .queue() yourself, like this:
$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

A: You can use the below effect to animate, you can change the values as per your requirements
$("#myElem").fadeIn('slow').animate({opacity: 1.0}, 1500).effect("pulsate", { times: 2 }, 800).fadeOut('slow');

A: To show error message of 5 sec using ajax that is save in session in laravel 8
<div id="error">
    @php
        $error = Session::get('message');
        echo $error;
    @endphp
</div>
<script>
    $("#error").show();
    setTimeout(function() {
        $("#error").hide();
    }, 5000);
</script>


text:
Q: PHP request dying silently when writing to stdout I have an app that has been working for some time. Just this morning, we started getting a 504 Gateway Timeout error. Cannot get through to anything. Upon stepping through the code, I found it's timing out when attempting to write to php://stdout. Changing it to php://output works, and dumps it to the screen as you would expect. Changing it to: STDERR or php://stderr works as you would expect (it writes to the error log).
I've tried an @ to suppress errors, as well as a try/catch, but it appears that an error is not what's happening. Any ideas for something to try? I'm at a bit of a loss on this one.
Running in ECS (Fargate):
PHP: 7.2.26
Apache: 2.4.43
Linux: Alpine 3.8.5


text:
Q: Control the local video size rendered by Twilio Video while preserving HD quality for server-side recording I'm using Twilio video and want to record the WebRTC video stream at 720x1280 on the server while showing a lower resolution 360x640 live preview of the user's camera in the browser.  This is for layout reasons because I want to fit the video into a smaller div in my HTML.  In the code below I've set separate sizes for the video and render dimensions.  When I run the code below, Twilio inserts a video element in the DOM matching the dimensions specified in the video parameter.  On the server I always receive a recorded video at 360x640 irrespective of what is specified in the video parameter or renderDimensions parameter.

function createLocal() {
            Twilio.Video.createLocalTracks({
                audio: true,
                video: { height: 720, frameRate: 24, width: 1280 },
                renderDimensions: {
                    low: { height: 720, frameRate: 24, width: 1280 }
                }
            }).then(localTracks => {
                //DOCUMENTATION
                //https://media.twiliocdn.com/sdk/js/video/releases/2.3.0/docs/module-twilio-video.html#.createLocalTracks
                var localMediaContainer = document.getElementById('local-media');
                localTracks.forEach(function (track) {
                    localMediaContainer.appendChild(track.attach());
                });

                return Twilio.Video.connect(token, {
                    name: rm,
                    tracks: localTracks
                });
            }).then(room => {
                window.room = room;
                console.log(`Connected to Room: ${room.name}`);
            });

        }

Here's a summary of my test findings when I change the video and renderDimension settings and then check the size of the video inserted into the DOM and recorded on the server.

I'm not sure if this is a Twilio question or a front-end dev question.  For example, can I tell the Twilio SDK to show a smaller video preview in the browser while recording something larger on the server? And why is the recorded video always the same size irrespective of the configuration? Or if not a Twilio issue, how do I force the 720x1280 video element that Twilio adds to the DOM into a 360x640 div?
Note - I understand that Twilio will automatically switch to a lower-quality video if the user has a slow connection.  My testing is on a 1Gbps fiber connection.


text:
Q: Including Variables in Strings, Bash Scripting I need to insert variables into a string to create a URL. Right now, I'm looping over an array of values and inserting them into the string.
year="2015"
for i in "${array[@]}"
do
    url="https://www.my-website.com/place/PdfLinkServlet?file=\place\\$i\099%2Bno-display\\$year_$i.pdf"
    echo $url
done

The $i is being replaced with the corresponding array element, but $year just leaves a blank space. Can someone explain why and how to get a url that looks like: url="https://www.my-website.com/place/PdfLinkServlet?file=\place\place_id\099%2Bno-display\2015_place_id.pdf"

A: Because variable names can legally contain _ characters, there's no way for Bash to know that you wanted $year instead of $year_.  To disambiguate, you can use enclose the variable name in brackets like this:
${year}_${i}.pdf

It's not bad practise to do this any time you are shoving variable expansions together.  As you can see, it actually makes them stand out better to human eyes too.

A: Use ${var} instead:
year="2015"
for i in "${array[@]}"; do
    url="https://www.my-website.com/place/PdfLinkServlet?file=place${i}099%2Bno-display${year}_${i}.pdf"
    echo "$url"
done

A: Here is a little hack that also works well. And I use it for my projects frequently. Add the _ to the end of 2015 in the variable year
   like year="2015_"
and remove the _ from the url variable and join the two variables i and year together like $year$i
I added an arbitrary array so that the script can run.
#!/bin/bash
year="2015_"
array=(web03 web04 web05 web06 web07)
for i in "${array[@]}";
do
url="https://www.my-website.com/place/PdfLinkServlet?file=\place\\$i\099%2Bno-display\\$year$i.pdf"
echo $url
done


text:
Q: "Lexicographic" ordering on ${\cal P}(\omega)$ For $A\neq B\in {\cal P}(\omega)$ we set $$\mu(A,B) = \min\big((A\setminus B)\cup (B\setminus A)\big).$$ We define $A < B$ if and only if $A \neq B$, and

*

*$A = B\cap \mu(A,B)$ (that is $A$ is an initial segment of $B$), or

*$\mu(A, B)\in A$ and there is $b\in B$ with $b > \mu(A,B)$.

For example we have $\{0,1\} < \{0,1,2\} < \{0,2\}$. Note that the ordering given by $<$ is total; I don't know whether it is really called a "lexicographic" ordering, perhaps there is a proper name in the literature. (Also I would be delighted to see a definition of $<$ that is more elegant than my definition above.)
Questions: If $\alpha$ is a countable ordinal, can $\alpha$ be embedded into ${\cal P}(\omega)$ with the lexicographic ordering? Can even $\aleph_1$ (or ${\frak c} = 2^\omega$ for that matter) be embedded into ${\cal P}(\omega)$?

A: Update. My original post had some wrong statements, which I
have now corrected.
As Emil had noted in the comments, the order is dense on the
infinite subsets. Suppose $A<B$ and both are infinite. In this
case, the least difference element is in $A$. Let $A^+$ agree with
$A$ up to and including that least difference element, and then
skip over the next element of $A$, before continuing arbitrarily.
It follows that $A<A^+<B$.
It follows that there is a dense linear suborder of your order,
and any such order is universal for all countable linear orders.
(The order is not dense on the finite sets, since for example
$\{\}<\{0\}$, and there is no set in between. More generally, if
$A$ is any finite set, then $A<A\cup\{\sup(A)+1\}$ is an immediate
successor.)
Meanwhile, $\omega_1$ cannot embed in the order, by the following argument. Suppose that we have an $\omega_1$-increasing chain $A_0<A_1<\dots<A_\alpha$ for $\alpha<\omega_1$. I claim that eventually, the sets must stabilize on whether $0\in A_\alpha$, since once it falls out, then it will have to stay out. Above that bound, the sets must eventually agree on whether $1\in A_\alpha$ or not, for the same reason. And so on. By taking a supremum of these countably many stabilizing points, it follows that there will be a countable stage after which the sets agree on all elements, which contradicts that it is increasing.
Finally, let me say that your definition is not what is usually called the lexical order, although it has a similar spirit. Usually, the lexical order is defined as follows: regards sets $A\subset\omega$ as binary sequences via their characteristic functions, and say $A<_{\rm Lex} B$, if at the first digit of difference, $A$ has a $0$ and $B$ has a $1$. This is the usual dictionary order, since we look at the first letter, and then the next letter, and so on.


text:
Q: What code should I add in xsd so that code could generates CDATA tag automatically in xml? What code should I add in xsd so that it generates CDATA tag automatically in xml?
For Eg: in XSD
<xsd:element name="any">
//code to generates CDATA tag automatically in xml
</xsd:element>

in xml test case it should auto generates and show like
  <any>
       <![CDATA[
            <xml tags>abc</xml tags>
     ]]>
</any>

I want this because under any tag, I would get another XML and I need to treat that whole XML as string without any Java code. So I am looking for solution in XSD only.