text:
Q: Insert Multiple Line Quote Multiple Times I'd like to take this:
system_info
show_uptime
drive_space
home_space

And paste this:
() {

}

to end up with this:
system_info()
{

}

show_uptime()
{

}

drive_space()
{

}

home_space()
{

}

I've tried using visual mode, but to no avail.
Help much appreciated!

A: You could use a substitution:
:%s/$/() {\r\r}\r

Where we substitute each end-of-line $ in the whole buffer % with:

*

*a pair of parentheses,

*followed by a space,

*followed by an opening brace,

*followed by two line breaks,

*followed by a closing brace,

*followed by a line break.

Or you could simply paste your snippet at the end of each line with p.

A: You can map the text to a key and then press that key whenever you want and it will paste the expected text at the end of line.
      :nmap \f A()<CR>{<CR><CR>}

Put this line in your ~/.vimrc file.
Then, you can keep the cursor on any line and press \ and f immediately one after the other. Cursor will move to the end of the line and the expected text is appended to it.


text:
Q: Jquery Validation example not working I'm trying to test a very basic jquery validation example. the code is as follows:
<form action="/" method="post">
    <input type="text" name="foo" id="foo"/>
</form>

My JS code:
$('#foo').validate({
    foo: {
        required: true,
        minlength: 2
    }
});

That doesn't work...
Any help or working examples will be appreciated.

A: You use the validate method on your form, not in a single element, and all the rules should be inside the rules property, like:
$("form").validate({
    rules: {
        foo: {
            required: true,
            minlength: 2
        }
    }
});

a live example can be found in JsBin.

A: Call the validate method at the form and wrap the rules in a rules obejct. If you want add an messages object.
HTML:
<form id="form" action="/" method="post">
    <input type="text" name="foo" id="foo">
</form>

javascript:
$('#form').validate({
    rules: {
        foo: {
            required: true,
            minlength: 2
        }
    },
    messages: {
       foo: "Please enter your foo"
   }
});

Also see this example.

A: Try this
 <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

<script>
    $(document).ready(function(){
        $("#commentForm").validate({
        rules: {
            txtPhNumber: "required",
            txtPhNumber2:
                {
            equalTo: "#txtPhNumber"
                }
            }
        });
    });

  </script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting undefined behaviour while using functional components? I am trying to populate html content i.e navigation dropdown menu using reactjs. I am getting undefined behaviour and I am not able to display dropdown menu navigation bar.
My code:
const Header = ({allnavitems, loading, SiteConfig, user}) => {

  if (loading) {
      return

Loading...

  }

  console.log(allnavitems)
  if( allnavitems.links.length !== 0){
  return(

          Crikit
          <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          </button>

              {allnavitems.map((allnavitems) => <Heading heading={allnavitems} />)}

            <form className="form-inline my-2 my-lg-0">
              <input className="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"/>
                <button className="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>

  )

}

};

const Heading = ({allnavitems}) => <NavDropdown links={allnavitems.links} heading={allnavitems.heading}/>

const NavDropdown = ({title, links}) => (

      {title}

      {links.map(({link='#', heading}) => <NavLink link={link} heading={heading}/>)}

);

const NavLink = ({link='#', heading}) => (
  {heading}
);

Above code doesn't display navigation bar.
On webpage I can see only Loading... in navigation bar and no navigation items why so ? (Check screenshot)
I want to display it something similar to this: (Check screenshot below)

A: Your errors were caused by some mixed up prop names.
In the final working example Heading component was removed. All it did was wrapping NavDropdown and passing the props to it. The problem was Heading wasn't getting the right props - it was expecting links and heading but was getting only heading.
I believe this is the code version that works:

const Header = ({allnavitems, loading, SiteConfig, user}) => {

  if (loading) {
      return

Loading...

  }

//  console.log(allnavitems)
  let navitems = allnavitems.filter( (value) => value.links.length !==0 )
  console.log(navitems)

  console.log(navitems[0].links)

  return(

          Crikit
          <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

          </button>

              {navitems.map((navitems) => <NavDropdown heading={navitems.heading} links={navitems.links}/>)}

            <form className="form-inline my-2 my-lg-0">
              <input className="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"/>
                <button className="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>

  )

};

//const Heading = (navitems) => <NavDropdown links={navitems.links} heading={navitems.heading}/>

const NavDropdown = ({heading, links}) => (

      {heading}

      {links.map(({link='#', heading}) => <NavLink link={link} heading={heading}/>)}

);

const NavLink = ({link='#', heading}) => (
  {heading}
);

Here you can find the sandbox I tried the code in.


text:
Q: Most efficient way to append rows from one dataframe to another import numpy as np
import pandas as pd

data2 = [['Name 1', 20, 20, 15, 20], ['Name 2', 15, 10, 10, 8]]
df2 = pd.DataFrame(data2, columns=['Name', 1, 2, 3, 4])

data1 = [['New 1', 5, 10, 15, 20], ['New 2', 2, 5, 10 , 20]]
df = pd.DataFrame(data1, columns=['Name', 1, 2, 3, 4])

print(df)

    Name  1   2   3   4
0  New 1  5  10  15  20
1  New 2  2   5  10  20

new_line = df.iloc[0]
df2 = df2.append(new_line)

print(df2)

     Name   1   2   3   4
0  Name 1  20  20  15  20
1  Name 2  15  10  10   8
0   New 1   5  10  15  20

I have the desired result I want. However, when I loop through this hundreds of times increasing the df.iloc[1], [2], etc it seems to bottleneck my for loop. Is there a more efficient way to select a row of df then append it to df2?

A: If you want to append the whole dataframe something like this should do the trick:
df.append(df2)

But I am assuming you know this already, and only want a selected few specified rows. In that case, I would create an array with the desired rowsID's from df2 that you want to append to df.
So something like this should work:
rowidarr = []
for items in df.iterrows():
    ###condition to get rowid you want
    rowidarr.append(index)
filter_df  = df[df.index.isin(rowidarr)]
df.append(filter_df)


text:
Q: iostat returns disk utilization greater than 100% while profiling a Beaglebone Black board I need to profile the performance of software running on a BeagleBone Black (BBB). The BBB has an ARM Cortex-A8 up to 1GHz frequency, 512MB RAM, and 4GB eMMC onboard flash storage. You can find more information here:
https://beagleboard.org/black
The BBB runs Debian bullseye booted from a 14GB MicroSD:
debian@BeagleBone:~$ uname -a
Linux BeagleBone 5.10.109-ti-r45 #1bullseye SMP PREEMPT Fri May 6 16:59:02 UTC 2022 armv7l GNU/Linux

Problem
As first trial, I'm running in parallel iostat with dd:
dd if=/dev/urandom of=~debian/ddtest/200MBfile bs=1M count=200 & iostat -xdz 1 20
I don't understand why iostat returns utilization values greater then 100%. I'm getting the metrics each second specifying 1 as argument in the command line. This is an excerpt of what I see in the terminal:
Device            r/s     rkB/s   rrqm/s  %rrqm r_await rareq-sz     w/s     wkB/s   wrqm/s  %wrqm w_await wareq-sz     d/s     dkB/s   drqm/s  %drqm d_await dareq-sz     f/s f_await  aqu-sz  %util

mmcblk0          0.00      0.00     0.00   0.00    0.00     0.00   18.00   9216.00     0.00   0.00 1062.00   512.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00   19.12  92.80

Device            r/s     rkB/s   rrqm/s  %rrqm r_await rareq-sz     w/s     wkB/s   wrqm/s  %wrqm w_await wareq-sz     d/s     dkB/s   drqm/s  %drqm d_await dareq-sz     f/s f_await  aqu-sz  %util

mmcblk0          0.00      0.00     0.00   0.00    0.00     0.00   16.00   8192.00     7.00  30.43 2058.25   512.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00   32.93 101.20

Device            r/s     rkB/s   rrqm/s  %rrqm r_await rareq-sz     w/s     wkB/s   wrqm/s  %wrqm w_await wareq-sz     d/s     dkB/s   drqm/s  %drqm d_await dareq-sz     f/s f_await  aqu-sz  %util

mmcblk0          0.00      0.00     0.00   0.00    0.00     0.00   25.00  12800.00     0.00   0.00 2295.64   512.00    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00   57.39 103.60

Device            r/s     rkB/s   rrqm/s  %rrqm r_await rareq-sz     w/s     wkB/s   wrqm/s  %wrqm w_await wareq-sz     d/s     dkB/s   drqm/s  %drqm d_await dareq-sz     f/s f_await  aqu-sz  %util

mmcblk0          0.00      0.00     0.00   0.00    0.00     0.00   33.00  15908.00     0.00   0.00 1136.58   482.06    0.00      0.00     0.00   0.00    0.00     0.00    0.00    0.00   37.51  89.60

mmcblk0 is the name of the 14GB memory (as stated by lsblk).
I downloaded sysstat, namely the package including iostat, directly from https://packages.debian.org/stable/sysstat and installed the version 12.5.2-2:
sudo apt list | grep sysstat sysstat/stable,now 12.5.2-2 armhf [residual-config]
I checked the source code of sysstat and I saw that the utilization is calculated at line 381 of rd_stats.c:
xds→util = S_VALUE(spd→tot_ticks, sdc→tot_ticks, itc);
S_VALUE is a MACRO defined at line 154 of common.h:
#define S_VALUE(m,n,p) (((double) ((n) - (m))) / (p) * 100)
Each second iostat reads the ms spent doing I/O from /proc/diskstats. The variable sdc->tot_ticks represents the last value read, sdp->tot_ticks the previous sampled value, while itc is the sampling interval we set from the command line (i.e., one second).
I can't understand why iostat returns values greater than 100%. I noticed that the time spent doing I/O (sdc->tot_ticks - sdp->tot_ticks) is often greater than itc. My guess is that iostat performs disk operations, that dd is preempted by the scheduler between two /proc/diskstat sampling or there are some processes running in parallel.
Experiments
I did some experiments, but I'm still don't get the source of the problem.
With iotop, I checked what processes were running concurrently with dd. I found a few journaling processes, i.e., jb2 and systemdjournald. They do not affect disk utilization, since the time indicated at the 10th field of /proc/diskstats records the time queues and disks were busy, taking concurrency into account (https://serverfault.com/questions/862334/interpreting-read-write-and-total-io-time-in-proc-diskstats).
I made a trivial bash script (attached to this paragraph) that mimics the behavior of iostat. It retrieves the 10th field from /proc/diskstats and calculates the utilization given an observation time. I set an observation period of 1 second, the same as my first attempt with iostat, and obtained a utilization of more than 100%. I believe that iostat is not the problem, as confirmed by this issue:
https://github.com/sysstat/sysstat/issues/73#issuecomment-860158402
Using the bash script, I got even higher values than those received from iostat. I believe this is due to /proc/diskstats readings or BBB performance extending the execution time of the script (or iostat).
#!/bin/bash
for (( i=0; i<$2; i++ ));
do
  value=$(cat "/proc/diskstats" | awk '/ mmcblk0 / {print $13}')
  if [ ! -z "$prev" ]; then
    bc -l <<< "scale=4;(($value - $prev)/($1*1000))*100"
  fi
  sleep $1
  prev=$value
done

I observed that running dd with the oflag=sync option decreases disk utilization. Also, journaling processes are not executed at the same time as dd but after it. This flag blocks the writing process until it is actually written to the device. This is the output of perf recording  who makes block I/O requests:
sudo perf record -e block:block_rq_insert -a dd if=/de/urandom of=~debian/ddtest/500MBfile bs=1M count=200
without oflag=sync

with oflag=sync

I'm missing how the kernel updates /proc/diskstats. I hope someone more experienced than me on the platform can help me understand the problem. Thank you.


text:
Q: Threads: Timeout lock Program description:
I wrote a demo for conditional waiting. The program starts two threads and then waits for both to finish. One of the threads reads user-pressed keys from the keyboard, and if the q key is pressed, sets a condition variable, after that the thread ends.
How can I implement the second thread to run in an infinite loop a sequence in which it waits for the condition variable for up to 1 second, and if the set variable appears then it exits the infinite loop, and if it does not appear and expires in 1 second, it displays a * on the console and returns to standby?
#include<pthread.h>
#include<stdio.h>
#include<stdio.h>
#include<unistd.h>
#include<errno.h>

pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c=PTHREAD_COND_INITIALIZER;

void *fun1()
{
    pthread_mutex_lock(&m);
    while (1)
    {
        char ch;
        scanf("%c",&ch);
        if(ch=='q')
        {
            pthread_mutex_unlock(&m);
            pthread_cond_signal(&c);
            pthread_exit(NULL);
        }
    }

}

void *fun2()
{
    struct timespec to;
    pthread_condattr_t attr;
     pthread_condattr_init( &attr);
    pthread_condattr_setclock( &attr, CLOCK_MONOTONIC);
    pthread_cond_init( &c, &attr);
    clock_gettime(CLOCK_MONOTONIC, &to);
    to.tv_sec += 1;
    while (1)
    {
        printf("hello world\n");
        int rc=pthread_cond_timedwait(&c,&m,&to);
        printf("%d",rc==ETIMEDOUT);
        pthread_exit(NULL);
        // if(rc==ETIMEDOUT)
        // {

        // }

        //     pthread_exit(NULL);

    }

}

int main()
{
    pthread_t id[2];
    pthread_mutex_init(&m,NULL);
    pthread_cond_init( &c, NULL);
    pthread_mutex_lock(&m);
    pthread_create(&id[0],NULL,fun1,NULL);

    pthread_create(&id[1],NULL,fun2,NULL);
    pthread_join(id[0],NULL);
    pthread_join(id[1],NULL);
    pthread_mutex_destroy(&m);
    return 0;
}

A: The structure of the code looks at-best to be pure-guesswork. Pthread mutex and condition variable pairing has specific rolls and responsibilities.

*

*The mutex protects some external 'predicate' data

*The condition variable signals a change to 'predicate' data.

The management of both the mutex and the condition variable is completely wrong.

*

*repeated initialization of the already-initialized objects.

*acquiring, and never releasing the mutex in fun1

*both functions have the wrong signature for proper pthread threads.

*neither function provides state return values

Related, some pthread implementations do not support clock-selection. In those cases, even fixing the code, the condition variable cannot be configured for monotonic clock selection; realtime is the only alternative.
Fixing everything above,
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
bool quit = false;

void *fun1(void *pv)
{
    while (1)
    {
        char ch;
        scanf("%c", &ch);
        if (ch == 'q')
        {
            // latch mutex before changing predicate
            pthread_mutex_lock(&m);
            quit = true;
            pthread_cond_signal(&c);
            pthread_mutex_unlock(&m);
            break;
        }
    }

    return pv;
}

void *fun2(void *pv)
{
    pthread_mutex_lock(&m);
    while (1)
    {
        printf("hello world\n");

        struct timespec to;
        clock_gettime(CLOCK_REALTIME, &to);
        to.tv_sec += 1;
        int rc = pthread_cond_timedwait(&c, &m, &to);
        if (rc != ETIMEDOUT || quit == true)
            break;
    }

    pthread_mutex_unlock(&m);
    return pv;
}

int main()
{
    pthread_t id[2];

    pthread_create(id+0, NULL, fun1, NULL);
    pthread_create(id+1, NULL, fun2, NULL);

    pthread_join(id[0], NULL);
    pthread_join(id[1], NULL);

    return 0;
}

Pay close attention to how the mutex protects the predicate data (quit), and how that data is never checked, nor modified, without protection from that mutex by any thread. It's important.
Finally, note that fun1 (or fun2 ; pick one) is ultimately pointless in this code. Starting threads and waiting for them all to finish as the sole responsibility of main is a code smell that something can be done in main to avoid at least one of those threads. For example:
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;
bool quit = false;

void *fun2(void *pv)
{
    pthread_mutex_lock(&m);
    while (1)
    {
        printf("hello world\n");

        struct timespec to;
        clock_gettime(CLOCK_REALTIME, &to);
        to.tv_sec += 1;
        int rc = pthread_cond_timedwait(&c, &m, &to);
        if (rc != ETIMEDOUT || quit == true)
            break;
    }

    pthread_mutex_unlock(&m);
    return pv;
}

int main()
{
    pthread_t id;

    pthread_create(&id, NULL, fun2, NULL);

    while (1)
    {
        char ch;
        scanf("%c", &ch);
        if (ch == 'q')
        {
            // latch mutex before changing predicate
            pthread_mutex_lock(&m);
            quit = true;
            pthread_cond_signal(&c);
            pthread_mutex_unlock(&m);
            break;
        }
    }

    pthread_join(id, NULL);

    return 0;
}

Does exactly the same thing as the previous code, but uses main as the driver for what fun1 was originally doing. Always consider this as an option worth pursuing if you can. Be kind to your scheduler; it will return the favor someday.


text:
Q: Join two tables field based on the same id? Need a help joining two tables based on the same id.
Table 1:
id_1 | id_2

Table 2:
id | name

I need a query where looks for id_1 on table 2 field id and return the field name and also looks for id_2 on table 2 field id and return the field name.
An example would be:
Table 1:
1 | 2

Table 2:
1 | Joe
2 | Michael

Return would be:
Joe | Michael

Thanks,

A: This is what you are looking for:
select t21.name, t22.name
from Table1 t1
inner join Table2 t21 on t1.id_1 = t21.id
inner join Table2 t22 on t1.id_2 = t22.id


text:
Q: Proving that a function has a maximizer I am trying to prove this:
Let $X$ be a nonempty, convex, and compact subset of $\mathbb{R}^n$ and $f:X \rightarrow \mathbb{R}$ a concave function. Then $f$ has a maximizer.
Now this is trivial (somewhat) if f is continuous because of Weistrass' theorem. But f isn't necessarily continuous here.
I have been stuck on this for a couple of days now. I can sort of imagine why this would be true if $f:\mathbb{R} \rightarrow \mathbb{R}$. But I haven't gotten any idea further than that yet.
Any help would be great!

A: This is not true. For (my) convenience, I answer the equivalent question of the existence of a minimizer of a convex function.
Let $X = [0,1]$ and
$$
f(x) = \begin{cases} x & \text{for } x \in (0,1], \\ 1 &\text{for } x = 0. \end{cases}$$
Then, $f(x) > 0$ for all $x \in X$ and $f(x) \to 0$ as $x \searrow 0$. Hence, $f$ does not possess a minimizer on $X$.

A: As @gerw already answered, the claim is not true. I'd like to add that there is a little additional assumption which will lead to a true statement:

A concave and upper semi-continuos function on a convex and compact domain has a maximizer.


text:
Q: Timestamped log file for WinSCP FTP script I'm trying to make an FTP  script to move files on my local PC to the NAS on a scheduler. I want every time the FTP script is run it creates a new log per day. This is the script I made:
@echo off

"C:\Program Files (x86)\WinSCP\WinSCP.com" ^
  /log="C:\writable\path\to\log\WinSCP.log" /ini=nul ^
  /command ^
    "open ftp://USER-NAS:PASSWORD%%21%%21%%21@10.xx.xxx.xx/" ^
    "lcd D:\WORK" ^
    "cd /BackupARC-Veeam" ^
    "put ""List Server Rak Abu-Abu.xlsx""" ^
    "exit"

set WINSCP_RESULT=%ERRORLEVEL%
if %WINSCP_RESULT% equ 0 (
  echo Success
) else (
  echo Error
)

exit /b %WINSCP_RESULT%

The script that I made is running fine, it's just that the logs don't match what I want.

A: WinSCP supports date/time patterns in its session log file:
https://winscp.net/eng/docs/commandline#logging
https://winscp.net/eng/docs/ui_pref_logging#session_log
So you can do something like this:
/log="C:\writable\path\to\log\WinSCP-!Y-!M-!D.log"


text:
Q: In grails need to change a field in a domain class to nullable after I have already gone to production I have a domain class with a string field that I am changing to nullable.  In DataSource.groovy I have the mode set to "update."  Is there any way to make grails alter the MySql without changing to "create" or "create-drop."  I need the data in the MySql.
Follow up question:  I can do this change by hand with the line "ALTER TABLE myProject_my_domain_class MODIFY the_string varchar(20) NULL;"  Is this acceptable practice?  Also I have the same problem with a field linking to another domain class:
class myDomainClass {
  MyOtherDomainClass otherThing
}

changing to
class myDomainClass {
  MyOtherDomainClass otherThing
  static constraints = {
    otherThing(nullable:true)
  }
}

If the manual SQL ALTER is the only way, what is the correct way to write the SQL command so that I preserve the Key index between domain classes?

A: Have you tried the Database Migration Plugin?
http://www.grails.org/plugin/database-migration
The process of using it is a bit more manual than just setting dbCreate="update", but it gives you much greater control, and it picks up on changes like making a column nullable. In addition, you can check even your small schema changes into your version control system, so you have a record of the changes that you make.


text:
Q: Calling System.gc() causing data loss in JSP I am currently debugging a web application which has been causing intermittent problems especially when the hit rate is high. As each new user is given a session containing personalised navigation menu I thought I would try to see how much memory the session variables need.
In a code section of the JSP which handles the creation of session objects, I added the following code:
System.gc();
long orgHeap = Runtime.getRuntime().freeMemory();

... create session variables ...

System.gc();
log.info("Heap delta: " + (Runtime.getRuntime().freeMemory() - orgHeap));

What surprised me is that adding System.gc() breaks the app. It does not work any more as some objects are getting lost (or so it seems). Values which had been initialised are null. When the gc() calls are removed the app works fine. gc() should only remove objects which have been marked for deletion - right?
Has any one else had similar problems?

A: The only case I can think of where this might actually happen as you describe, is if you're using WeakReferences (or expired SoftReferences, which are broadly similar in this situation) to refer to objects that you still want to keep.  The objects the might get into a state where they're collectable by the GC; but until it actually runs, you'll still be able to reach them through your references.  Calling System.gc(), even though it doesn't have any guaranteed semantics, might cause the collector to run and harvest all these weakly-reachable objects.
That seems unlikely, though, because

*

*Accidentally using WeakReferences for strongly-reachable objects doesn't seem like an easy mistake to fall into.  Even if you're using libraries, I find it hard to think of a case where you might feasibly end up using weak references by mistake.

*If this did happen, the behaviour of the application would be undefined anyway.  Garbage collections could happen at any time, so you'd likely see inconsistent behaviour without the System.gc() call.  You'd always have some bit of code that runs just after a collection anyway and so couldn't find its referent object.

*System.gc() doesn't theoretically do anything so it shouldn't be causing this.

That last point is the important one - why are you calling System.gc() anyway, when it is almost always counterproductive to call?  I don't believe that you have a legitimate need to call it, it doesn't do anything you can rely on, and apparently it's breaking your application.
So if your app works fine without making the call, then just stop making it.
I would still consider inspecting how your app fits together though, because this is not going to be the actual cause of the problem and you likely have a deeper issue which is very fragile and just waiting to break on you later.
EDIT: Another possible reason for this could be simple timing.  Calling System.gc() is likely to take a non-negligible amount of time.  During this period, other threads could progress and change state in a way that the GCing thread isn't expecting.  Hence when it returns from the call, the state of the world breaks its expectations and hence logic errors result.  Again, this is just a guess, but is more plausible than the WeakReference one.

A: Garbage collection will never remove live objects, so I think your problem is elsewhere.
As you state this is under load - "hit rate is high" - this could be a case of using EJB's incorrectly, where you expect something to happen because it does so under low load (like getting the same EJB repeatedly when asking for it) but that change under high load (somebody else got that EJB, you get another).


text:
Q: How to call a non static method using static keyword? I am just checking the OOPs static/non-static concept and found something strange.
I have heard that static method's output can be get by using static keyword with resolution operator(::) . But In my program I am getting non static method's value using static keyword. Can any one explain the program? I am getting confused.
<?php
error_reporting(E_ALL);

class parentclass
{
    protected function sum()
    {
        return 145;
    }
}

class childclass extends parentclass
{
    protected function sum()
    {
        return 125;
    }
}

class grandchild extends childclass
{
    function sum()
    {
        return 100;
    }

    function __construct()
    {
        echo static::sum(); // 100 as output but how
    }
}

$obj = new grandchild();
?>

Besides this If I am making function sum() of childclass as static like
class childclass extends parentclass
{
   protected static function sum()
   {
    return 125;
   }
 }

then also it is giving fatal error as following:
Fatal error: Cannot make non static method parentclass::sum() static in class childclass
But why I am not calling that function.

A: You are using static as a Late Static Binding. But what you heard about was rather
class Foo
{
  static function bar() {}
}

$baz = Foo::bar();

A: You can call a function statically, even if it is not declared as static, as long as you don't reference $this inside it.
That is why the original code works.
You cannot, however, change the signature of an inherited method.

Fatal error: Cannot make non static method parentclass::sum() static
  in class childclass

When you declare protected static function sum() in childclass, you are changing the signature of the inherited method from parentclass which is not specifically declared static.
Bottomline, you are trying to use some PHP quirks that I would recommend against. Yes, they work, but that doesn't mean you should use them.
Stick to a strict style of coding. Write separate methods for static and instance use and call them as intended.

A: I think to understand late static bindings a bit better you could write a variation of your code:
<?php
error_reporting(E_ALL);

class parentclass
{
    protected function sum()
    {
        return 145;
    }

    public function do_the_math()
    {
        printf('Static sum: %d, Self sum: %d',
            static::sum(),
            self::sum());
    }
}

class childclass extends parentclass
{
    protected function sum()
    {
        return 125;
    }
}

class grandchild extends childclass
{
    function sum()
    {
        return 100;
    }
}

$obj = new grandchild();
$obj->do_the_math();

Output:
Static sum: 100, Self sum: 145


text:
Q: Why Ajax is not able to send array data? Trying to send form data to a PHP page, all parameters are sending successfully except data:imagesBase64
this imagesBase64 is an array which I am trying to send, a few hours ago everything was fine but now it is not working I really don't know why.
All values are Posting successfully only this value is not posting also I am not able to see error in console because it redirected to URL where I am posting the data

 var imagesBase64 = ['abcdfd','dhydsu333ud','djhbsd'];

  $(function () {
    var frm = $("#saveform");
    frm.submit(function (ev) {
      $.ajax({
        type: frm.attr("method"),
        url: frm.attr("action"),
        data: {
          data: imagesBase64,
          PubId: $("#Publications").val(),
          sdate: $("#datepicker").val(),
          pnumber: $("#pnumber").val()
        },
        cache: false,
        error: function (err, data) {
          console.log("There was an error. Try again please!" + data, err);
        },
        success: function (data) {
          alert("New message received");
        },
      });
      ev.preventDefault();
    });
  });

In PHP page -
print_r($_POST['data']);

it gives an error undefined data, though when I tried with postman everything is working fine.

A:
also I am not able to see error in console because it redirected to URL where I am posting the data

That's the problem.
You are submitting data to the server using a regular form submission and not with Ajax. Since your Ajax code isn't used, the data added in from outside the form isn't included.
This is usually caused by the regular form submission interrupting the Ajax request, but since you have ev.preventDefault(); that shouldn't be the case here.
Possible reasons that might apply are:

*

*var frm = $("#saveform") fails to find the form because the selector is wrong or the form is added after the document is loaded with other JS

*You don't have jQuery loaded so the call to $ fails

*You have jQuery Slim loaded which doesn't include an ajax method (moving the call to preventDefault so it is before the call to ajax would help catch this).

Your browser's developer tools should have an called something like "Persist Logs" which will prevent it from clearing the console when you navigate to a new page. Turn it on to aid your debugging. Here's what it looks like in Firefox:


text:
Q: Preventing CGAffineTransform from applying incrementally I'm using CGAffineTransformRotate and CGAffineTransformTranslate to animate the progress of a car image (UIImageView) across the screen. The animation is controlled by a UISlider so as the user advances the slider, the car advances and drives around a corner. For each point on the UISlider, I need to be able to set an absolute value for the car's CGAffineTransformRotate and CGAffineTransformTranslate property.
However, each time the transform is called, the car image is being transformed incrementally. So if, for example, I use this at slider point 0.01:
carImage.transform = CGAffineTransformRotate(carImage.transform, degreesToRadians(5));
carImage.transform = CGAffineTransformTranslate(carImage.transform, 4.0, - 10.0);

and this at slider point 0.02:
carImage.transform = CGAffineTransformRotate(carImage.transform, degreesToRadians(10));
carImage.transform = CGAffineTransformTranslate(carImage.transform, 8.0, - 20.0);

When the slider value is 0.02, I would like the car to be at 10 degrees with an x value of 8 and a y value of -20. However, what I'm getting is the car at 15 degrees with an x value of 12 and a y value of -30. It is applying my second transform to the values arrived at after the first transform.
How can I apply each transform to the basic values of my car's UIImageView? Ie I want each transform to be absolute based on the untransformed UIImageView. I do not want the transforms to be incremental.

A: See if this solve your problem,
[UIView setAnimationBeginsFromCurrentState:NO];

Another way:
You can save the previous slider value, and when you change the slider, get the difference between the previous and current slider values, and using that difference calculate the new transformation relative to the previous transformation. For example, if the previous slider value is 0.01 and the current slider value is 0.02, the difference is 0.01 so add 4.0 to the tx and add -10 to ty.


text:
Q: Django collaboration migration issue I currently have an issue when working with my friends on the same Django project.
The situation is that every time when any of us made database changes and if other people did not migrate on time, they will get ProgrammingError: Column not exist error. That already happened a couple of times and we are still not able to figure a way to avoid this.
Question:

*

*What's the best way to solve this issue when happened?

*What's the best process to void this issue?

A: I don't think it's a good idea to share the same database of the project that you're working on but, One of the Solutions that I use is by using Django's load data command, specially when you make a lot of changes into Django models
first, I run the dumpdata command after I make my initial data by doing
python manage.py dumpdata <app-name>

it will export a JSON file that you can later on load it into the database
python manage.py loaddata <app-name>

NOTE: for some reason, if you load the data and get an encoding error make sure to open the file and save it in notepad and change the encoding of it to utf-8

A: *

*If you are working on a local database then just migrate. This is everyday work in django. At least in my experience.
For databases that are shared, this is a different thing. I probably would (a) if no devops are in place, migrate the database directly after I have changed the schema. Make sure that a specific branch (i.e. development) is always in sync with your database server. Or (b) with devops in place, let a branch only merge if the condition is met: the migration that is tied to the model changes in your commit will be successful. And then let the devops handle the migration automatically to keep the database in sync.
.

*During active development you can not avoid this issue. You can do your best to inform your colleagues when you push code or merge a feature into development. I.e. by putting a warning in the commit message.
Anyway, everyone should be aware that the database schema might change when rebasing on current development or pulling. Generally your changelog should at least contain information on what fields were added/changed/removed.


text:
Q: Automatically Create Objects from Files in a Directory I am trying to automate the data ingestion process in an R script that pulls data from a directory that updates regularly.
The general framework follows this process
library(sp)
library(rgdal)
library(raster)

f1.t1.cir <- stack("../raster/field1/f1_cir_t1.tif")
f1.t1.NDVI <- stack("../raster/field1/f1_ndvi_t1.tif")
f1.t1.RGB <- stack("../raster/field1/f1_ndvi_t1.tif")

f1.dat <- c(f1.t1.cir, f1.t1.NDVI, f1.t1.RGB)

for (i in f1.dat){
  plotRGB(i)
}

I would like to generate each f1.t1.cir type object from the directory directly such that when I add a new TIFF file f1_cir_t2.tif, the r script will create an object f1.cir.t2.
I am trying to use something like
a <- list.files(path= "../raster/field1", pattern = "\\.tif$")
b <- gsub("_", "\\.", a)

for (i in a) {
  assign(get(b[(which(a==i))]), stack((paste("../raster/field1/", i,sep=""))))
}

At this point, I would have all tiff files as stacked multiband raster objects in the R workspace.
I am getting the following error,
Error in get(b[(which(a == i))]) : object 'f1_t1_DSM.tif' not found
I can not figure out if this is a get() problem, or something else.
for reference
> a
[1] "f1_t1_DSM.tif"  "f1_t1_NDVI.tif"

> b
[1] "f1.t1.DSM.tif"  "f1.t1.NDVI.tif"

so that much is working, I think.
Any suggestions?

A: @joran, great suggestion...
f1.t1<-list()

for(i in list.files(path= "../raster/field1", pattern = "\\.tif$")){
  f1.t1[[i]]<-stack((paste("../raster/field1/", i, sep="")))
}

Worked very well, no need to change the names.
Thank you.


text:
Q: Getting value from another feature depending on value of field using QGIS Field Calculator I'm a total newbie at coding.
I'm working with water catchments in QGIS. Runoff of some catchments feeds other catchments. I'm trying to get the cumulative run-off.
Each feature in the table has the following fields:

*

*ID - each polygon's number

*Fed by - the numerical ID of a polygon that feeds it

*C - the (calculated) runoff capacity of that field

I would like to create a field C-in that pulls the value of C from another feature based on the ID of that feature if it is written in Fed by field.
I imagine it is something along the lines of: When Fed by equals the value of an ID, get C of that ID, for example:

In particular, we have:

*

*ID: 19, Fed by: 9, C: 0.5

*ID: 20, Fed by: 19, C: 0.7
So C-in of ID=20 should be: 0.5 (forget for a moment the C-in of ID=19)
So what do I need to write in the field calculator to get this magic to happen?

A: Try the following expression:
attribute(get_feature(@layer_id,'id',"fed by"),'C')

The get_feature call finds the feature in the current layer whose id is equal to the current feature's fed by. Note double quotes on fed by since the value of this field for the current feature should be evaluated in the expression. However id has single quotes since it is a parameter to get_feature to tell it what field name to use, and should not be replaced by the current feature's id (20 in your example). Then attribute pulls out the value of C in that feature (not double quotes for same reason as before, to avoid it being replaced by 0.7 during evaluation).
Nonanswer
I was all set to suggest you create a join (in Layer Properties) to the same layer and then link on the fed by field. But it seems QGIS doesn't permit self-joins.
Remark
You could probably save some work, if you haven't gone too far down this path yet, by instead adding a field describing what each catchment flows in to, and then using the aggregate function to find and sum over all (sub)catchments that flow into your catchment. This would replace your multiple fed by # fields, but the linkage would go the other way (upstream links to single downstream, rather than downstream links to several upstream).
And all of this gets a bit more complicated if you have multiple layers of fed-bys, i.e. A feeds into B which feeds into C. Your current logic -- or my alternative in this remark -- will work if A and B both feed into C, not if they're nested, so to speak.


text:
Q: Create new column that identifies matches for each group Let's say I have a data frame like this:
dat<- data.frame(ID= c("A","A","A","A","B","B", "B", "B"),
             test= rep(c("pre","post"),4),
             item= c(rep("item1",2), rep("item2",2), rep("item1",2), rep("item2",2)),
             answer= c("1_2_3_4", "1_2_3_4","2_4_3_1","4_3_2_1", "2_4_3_1","2_4_3_1","4_3_2_1","4_3_2_1"))

For each group of ID and item, I want to determine if the levels of answer match.
The result data frame would look like this:
res<- data.frame(ID= c("A","A","B","B"),
             item= c("item1","item2","item1","item2"),
             match=c("TRUE","FALSE", "TRUE", "TRUE"))

A: dat<- data.frame(ID= c("A","A","A","A","B","B", "B", "B"),
             test= rep(c("pre","post"),4),
             item= c(rep("item1",2), rep("item2",2), rep("item1",2), rep("item2",2)),
             answer= c("1_2_3_4", "1_2_3_4","2_4_3_1","4_3_2_1", "2_4_3_1","2_4_3_1","4_3_2_1","4_3_2_1"))

library(data.table)
setDT(dat)

dat[, .(match = all(answer == answer[1])), by = .(ID, item)]
#>        ID   item  match
#>    <char> <char> <lgcl>
#> 1:      A  item1   TRUE
#> 2:      A  item2  FALSE
#> 3:      B  item1   TRUE
#> 4:      B  item2   TRUE

Created on 2022-05-04 by the reprex package (v2.0.1)

A: In dplyr, we can use group_by and summarize to see if the answer column is the same in "pre" and "post" with the same ID and item columns.
library(dplyr)

dat<- data.frame(ID= c("A","A","A","A","B","B", "B", "B"),
                 test= rep(c("pre","post"),4),
                 item= c(rep("item1",2), rep("item2",2), rep("item1",2), rep("item2",2)),
                 answer= c("1_2_3_4", "1_2_3_4","2_4_3_1","4_3_2_1", "2_4_3_1","2_4_3_1","4_3_2_1","4_3_2_1"))

dat %>%
  group_by(ID, item) %>%
  summarize(match = answer[test == "pre"] == answer[test == "post"])

#> # A tibble: 4 × 3
#> # Groups:   ID [2]
#>   ID    item  match
#>   <chr> <chr> <lgl>
#> 1 A     item1 TRUE
#> 2 A     item2 FALSE
#> 3 B     item1 TRUE
#> 4 B     item2 TRUE

Created on 2022-05-05 by the reprex package (v2.0.1)


text:
Q: Inner product in $\mathbb{R}^2$ and angles of a triangle Let $P_1,P_2,P_3$ be $3$ different points in $\mathbb{R}$, then $P_1,P_2,P_3$ form a triangle.
What is the relation between the (one of the) angles of this triangle and $\langle P_2-P_1,P_3-P_1 \rangle$ ?
I am having trouble figuring out which angle of the triangle it is - and even why it is an angle in the triangle...
Note: $\langle ,\rangle$ denotes the standard inner product of $\mathbb{R}^2$.

A: From the definition of the inner product for vectors $\vec{a},\vec{b}$ we got:
$$
\vec{a}\cdot\vec{b}=\|\vec{a}\| \|\vec{b}\|\cos(\widehat{\vec{a},\vec{b}})
$$
Applying this rule in your case:
$$
\langle P_2-P_1,P_3-P_1 \rangle =\|P_2-P_1\|\cdot \| P_3-P_1\|\cdot \cos(\widehat{P_2-P_1,P_3-P_1}),
$$
so by reforming:
$$
\cos(\widehat{P_2-P_1,P_3-P_1})=\frac{\langle P_2-P_1,P_3-P_1\rangle}{\|P_2-P_1\|\cdot \| P_3-P_1\|}
$$
The angle inside the $\cos$ is actually the angle between the two vectors that you're computing their inner product, in other words the angle between the two sides of your triangle formed by $P_2,P_1$ and $P_3,P_1$ respectively. So because the only mutual point is $P_1$, the angle is actually the angle corresponding to this point.

A: The angle between two vectors $a,b$ in $\mathbb{R}^2$ is actually defined by the formula
$$
\cos(\varphi)=\frac{\langle a,b \rangle}{\Vert a\Vert\cdot\Vert{b}\Vert}
$$
so $\frac{\langle P_2-P_1,P3-P_1\rangle}{\Vert P_2-P_1\Vert\cdot\Vert P_3-P_1\Vert}$ is the cosine of the angle in $P_1$.
Here's a motivation for the above formula: First note that we can rewrite $\frac{\langle a,b\rangle}{\Vert a\Vert\cdot\Vert{b}\Vert}=\left\langle \frac{a}{\Vert a\Vert},\frac{b}{\Vert b\Vert}\right\rangle $, so replacing $a$ and $b$ by $\frac{a}{\Vert a\Vert}$ and $\frac{b}{\Vert b\Vert}$ we can assume that the vectors have length $1$. Now write $b$ in the basis $a,a^{\perp}$ ($a^{\perp}$ is one of the 2 perpendicular vectors to $a$ of length $1$). In this basis $a$ corresponds to the vector $(1,0)$ and $b$ will be a vector on the unit circle, $b=x_1 a + x_2 a^{\perp}$. Note that the cosine of the angle between $a$ and $b$ is $x_1$ by the classical definition! This is in accordance to our formula $\cos(\varphi)=\langle a,x_1 a + x_2 a^{\perp}\rangle=\langle a,x_1 a\rangle =x_1$.


text:
Q: php function arguments var, reset argument I created a php function and I want to clear/reset the arguments of the function.
for example I've got this function declared twice in my index.php:
grid_init($type='portfolio',$postNb=4,$rowNb=2);
grid_init($type='post',$postNb,$rowNb);

function grid_init($type,$postNb,$rowNb) {
?>

<div class="container" data-type="<?php echo $type; ?>" data-postNb="<?php echo $rowNb; ?>" data-rowNb="<?php echo $rowNb; ?>">
some stuff.....

<?php
}

If I didn't specified my argument in my second function (in the above example $postNb $rowNb), these vars will take the values of the previous argument declared in the previous function ($postNb=4,$rowNb=2)...
How can I reset/clear my argument in my function between each function declared in a same file?

A: To make a function have default arguments it's like:
function grid_init($type, $postNb = 2, $rowNb = 4){
  echo "
".
  "some stuff.....".
  '
';
}

Execute like:
grid_init('whatever'); // will assume $postNb = 2 and $rowNb = 4;
grid_init('some_data_type', 42, 11); // overwrite your defaults

A: You seem to have trouble calling functions.
Change your calls to
grid_init('portfolio',4,2);
grid_init('post','',''); // or use '' as default

a) you might have declared a function like this
function grid_init($type, $postNb, $rowNb)
{
   // do stuff on $tyoe, $postNb, $rowNb
}

b) you might call the function several times, each time with new parameters
grid_init('post', 5, 4);
grid_init('somewhere', 1, 2);

A function does not memorize values of prior calls.
If you want that, then save them somewhere from within that function.
c) you might use default parameters on your function
Default parameters always come last in the function declaration.
function grid_init($type, $postNb = 2, $rowNb = 2)
{
    // do stuff on $tyoe, $postNb, $rowNb
}

call it
grid_init('somewhere');

now postNb, rowNb are not set, but the default values from the declaration are used.
d) keep the number of parameters low!


text:
Q: Usage of "no other" I have a question regarding usage of "no other". I know no can be used with "singular countable nouns" as well as "plural countable nouns" but I don't know if I can use "no other" in the same way as no.
Here are the examples:
1- This is the only branch of Traders & engineers Pvt Ltd. We have no other branch(es) than this.
2- Peter: Subha, The pen you gave me has broken. Do you have any other pen? Me: No, I have no other pen(s).
My main question is, can I use singular nouns after "no other"? And would you choose "plural nouns" or "singular nouns" in the above examples?
Can anyone who has good knowledge in english answer my question please?

A: It's interesting in this context because normally using plural or singular nouns depends on whether you use "is/are." (i.e. "There are no other pens") But to say "I have no other" doesn't require plural or singular.
"I have no other choice."
"I have no other options."
Both are fine.


text:
Q: Numba code much faster than cython alternative I have to write a small simulation in cython, which is usually accelerated with numba.
But I have to make this transition, since numba didn't support a scipy function which I wanted to use for modifying the function.
So essentially I have translated my simulation program into cython, which makes everything super slow compared to numba. So maybe there is a bottleneck in my cython code which i do not see.
My cython code:
import numpy as np
cimport numpy as cnp
cimport cython

cnp.import_array()

@cython.boundscheck(False)
@cython.wraparound(False)
def simulation(int N=10000, int N_save=10000):

    cdef cnp.ndarray[double] x = np.empty(N_save, dtype=np.double)
    cdef cnp.ndarray[double] r = np.random.standard_normal(size=N_save)

    cdef fs = int(N / N_save)
    cdef xold = 0
    x[0] = 0

    for i in range(1, N):

        if i%N_save == 0:
            r = np.random.standard_normal(size=N_save)

        xnew = xold + r[i%N_save]

        if (i % fs) == 0:
            x[int(i / fs)] = xnew

        xold = xnew

    return x

The code I use for compilation:
from setuptools import setup
from Cython.Build import cythonize
import numpy as np

setup(
    ext_modules=cythonize(
        "test.pyx",
        compiler_directives={'language_level' : "3"},
    ),
    include_dirs=[np.get_include()]
)

The same code accelerated with numba:
@nb.jit(nopython=True, fastmath=True)
def simulation_nb(N=10000, N_save=10000):

    x = np.zeros(N_save)
    r = np.random.standard_normal(size=N_save)

    fs = int(N / N_save)
    xold = 0
    x[0] = 0

    for i in range(1, N):

        if i%N_save == 0:
            r = np.random.standard_normal(size=N_save)

        xnew = xold + r[i%N_save]

        if (i % fs) == 0:
            x[int(i / fs)] = xnew

        xold = xnew

    return x

The Benchmark results with simulation(N=1000000, N_save=10000):

*

*Cython: 183ms

*Numba : 31.4ms

*Raw Python: 217ms

Why is my cython code almost as slow as the raw python alternative?

A: Your main problem is that you don't give the Cython compiler the types of all variables. This makes your Cython code inefficient since it leads to many interactions with the Python interpreter. For instance, the types of the variables i, fs, xnew and xold are unknown to the Cython compiler. As already mentioned in the comments, this can easily be observed by compiling with the --annotated option.
Let's time your numba code on my machine for a fair comparison:
In [7]: %timeit simulation_nb(N=1000000, N_save=10000)
24.7 ms ± 177 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

By

*

*using typed memoryviews instead of cnp.ndarrays (they are faster and the syntax is cleaner)

*using C division instead of calls to Python's int() function

*and providing the types for all variables

your Cython code could look like this:
%%cython -a -c=-O3 -c=-march=native

cimport numpy as np
import numpy as np
cimport cython

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.cdivision(True)
def simulation_cy1(int N=10000, int N_save=10000):
    cdef double[::1] x = np.empty(N_save, dtype=np.float64)
    cdef double[::1] r = np.random.standard_normal(size=N_save)
    cdef int fs = int(N / N_save)
    cdef int i
    cdef double xnew, xold = 0
    x[0] = 0

    for i in range(1, N):
        if i%N_save == 0:
            r = np.random.standard_normal(size=N_save)
        xnew = xold + r[i%N_save]
        if (i % fs) == 0:
            x[i / fs] = xnew
        xold = xnew
    return np.asarray(x)

On my machine, this has similar performance to numba:
In [10]: %timeit simulation_cy1(N=1000000, N_save=10000)
24.5 ms ± 171 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Of course, this can be further accelerated. Jérôme's awesome answer already includes some hints for you, i.e. you could replace the modulo operators (If you're lucky, your C compiler already optimizes these operations) and try to replace the calls to np.random.standard_normal by using C/C++ functions. The C++ STL provides std::normal_distribution which can easily be used inside Cython. However, to be honest, I don't think that this is worth the effort since np.random.standard_normal is not called often enough inside the loop to have a significant influence on the performance.

A: Cython is not able to inline Numpy functions as opposed to Numba. Moreover, and the Cython code is not typed causing the code to operate on slow CPython objects (see the @joni answer for this specific point).
Numpy functions generally have a significant overhead for small arrays but it looks like this overhead is not the main issue here. This functions takes 185 us to generate 10000 items on my machine (which is pretty slow). This means The code must takes at least 185e-6*1000000/10000=0.0185 seconds in both Python and Cython (it takes 0.265 seconds in Python in practice). Since the Cython time is significantly bigger, this means most of the overhead is somewhere else. The @joni answer show it is due to the missing typing information. Once optimized, most of the time is spent in the np.random.standard_normal function as expected.
Numba can inline functions because it has its own implementation of Numpy which is JITed. The downside is that complex functions can be quite long to compile and many functions are not yet supported because they all need to be reimplemented and this is a huge work. In the case of np.random.standard_normal, it turns out that the Numba implementation is surprisingly significantly faster than the one of Numpy only in a loop. This is certainly because an expression that is slow to compute can be precomputed once in the loop. An analysis of the assembly code indicates that this pre-computation appear to be related to the internal function numba::cpython::randomimpl::_gauss_pair_impl::_3clocals_3e::compute_gauss_pair_248, and I understand the code correctly, it is a result of a loop splitting optimization (so the compiler is able to split the computing loop in two part and do the first once because the result is always the same). It is very hard to describe further what part is exactly optimized because the generated assembly code is quite big and very cryptic. The main point to remember is that all of this is possible because of the inlining of Numpy computing functions combined with aggressive optimizations.
By the way, modulo instructions are slow. You should avoid them like the plague. Using a counter with a conditional should certainly be faster (especially because the conditional can be predicted by the processor so it can be discarded very quickly).
Here is an optimized code:
# Use parallel=True for a parallel implementation (see later)
@nb.jit(nopython=True, fastmath=True)
def simulation_nb(N=10000, N_save=10000):
    np.random.seed(0)
    x = np.zeros(N_save)
    r = np.empty(N_save)
    for j in range(N_save):
        r[j] = np.random.standard_normal()

    fs = int(N / N_save)
    xold = 0
    x[0] = 0

    counter1 = 1
    counter2 = 1
    counter3 = 0

    for i in range(1, N):

        if counter1 == N_save:
            # Use nb.prange here for a parallel implementation (see later)
            for j in range(N_save):
                r[j] = np.random.standard_normal()
            counter1 = 0

        xnew = xold + r[counter1]

        if counter2 == fs:
            x[counter3] = xnew
            counter3 += 1
            counter2 = 0

        xold = xnew

        counter1 += 1
        counter2 += 1

    return x

This code is significantly faster than the previous one (17 ms instead of 28 ms). np.random.standard_normal takes roughly 95% of the time of this function. Calling np.random.standard_normal in a loop item per item prevent an expensive array allocation (this only worth it in Numba thanks to inlining).
This version is faster than the Cython version of @joni (17 ms VS 21 ms).
One way to speed up this Numba code even more is to generate the random numbers in parallel but this is not so simple since the main loop is inherently sequential and the default value of N_save should be too small for multiple threads to significantly help. Increasing N_save by an order of magnitude should be enough on most systems. Note that the random seed is set by thread in Numba so results should be a bit different. Also note that AFAIK this should not be possible to do the same thing in Cython because the implementation of np.random.standard_normal of Numpy is not thread safe (as opposed to Numba). The optimized parallel implementation takes 4.5 ms on my 6-core machine with the same parameters and 3.8 ms with a 10x bigger N_save (due to the parallel overhead).


text:
Q: Call super.onSaveInstanceState(outState) in end of method? I want to save state of activity. So I use method onSaveInstanceState()
@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean(SOME_KEY, inCheckMode);
    super.onSaveInstanceState(outState);
}

The question is:
Should I call super.onSaveInstanceState(outState) in the end of method?

A: We have to store the data first.
Then we have to call the super.onSaveInstanceState(outState) at the end.


text:
Q: Plot 3D doesn't show anything Good Evening,
I defined a function which is composed of other several functions. Mathematica compiles well but I can't get a plot and I do not understand way.
Can anyone help me with the code and explaining me why nothing is showed on the plot?
Thanks in advance
f1 = 0.0;
f2 = 0.0;
f3 = -9.0; (*fN*)
T = 300;(*K*)
ν = 1.002; (*(fN*s )/μm^2*)

Subscript[r, 0] = 0.5;(*μm*)
Subscript[r, 2] = 0.8;(*μm*)

Subscript[r, 1] = 0.2;(*μm*)

Subscript[γ, 0] = 6 π ν Subscript[r, 0];
Subscript[γ, 2] = 6 π ν Subscript[r, 2]
Subscript[γ, 1] = 6 π ν Subscript[r, 1]
(* 15.1098 *)
(* 3.77745 *)

ϕ1 = π/3;
ϕ2 = π/4;

V1[Tkin_] := (1/Subscript[γ, 1])[
   f2 - f3 (((Tkin - T)/T) Cos[θ] Sin[θ])/(
     Subscript[γ, 1]/Subscript[γ,
      0] + ((Tkin - T)/T) (Sin[θ])^2)];
V2[Tkin_] := (1/Subscript[γ, 2])[
   f2 - f3 (((Tkin - T)/T) Cos[θ] Sin[θ])/(
     Subscript[γ, 2]/Subscript[γ,
      0] + ((Tkin - T)/T) (Sin[θ])^2)];

V11 = V1[Tkin1]; (* Velocity of the 1st particle in protocol 1*)
V21 =
  V2[Tkin1]; (* Velocity of the 2nd particle in protocol 1*)

V12 = V1[Tkin2]; (* Velocity of the 1st particle in protocol 2*)

V22 = V2[Tkin2]; (* Velocity of the 2nd particle in protocol 2*)

VA[Tkin1_,
   Tkin2_, ϕ1_, ϕ2_] := {{V11 Sin[ϕ1] -
     V12 Sin[ϕ2], V11 Cos[ϕ1] + V12 Cos[ϕ2]}};
VB[Tkin1_,
   Tkin2_, ϕ1_, ϕ2_] := {{V21 Sin[ϕ1] -
     V22 Sin[ϕ2], V21 Cos[ϕ1] - V22 Cos[ϕ2]}};

VAA = VA[Tkin1, Tkin2, ϕ1, ϕ2];
VBB = VB[Tkin1, Tkin2, ϕ1, ϕ2];

delta[Tkin1_, Tkin2_] =
  ArcCos[VAA.Transpose[VBB]/(Norm[VAA] Norm[VBB])];
Plot3D[delta, {Tkin1, 300, 1000}, {Tkin2, 300, 1000},
 AxesLabel -> {"Tkin1", "Tkin2", "γ"},
 ColorFunction -> "BrownCyanTones", PlotRange -> Automatic]

A: The code does not run properly due many simple issues. First, we cannot use brackets and braces in the function definitions because Mathematica will comprehend differently from conventional math. Secondly, the functions V11,V12,V21 and V22 can be neglected and just use V1 and V2 with the proper Tkin variable. The functions VAA and VBB can be erased because VA and VB have the same definition. Ultimately, the angle $\theta$ needs a value.
f1 = 0.0;
f2 = 0.0;
f3 = -9.0;       (*fN*)
T = 300;         (*K*)
\[Nu] = 1.002;   (*(fN*s)/\[Mu]m^2*)

r[0] = 0.5;      (*\[Mu]m*)
r[1] = 0.2;      (*\[Mu]m*)
r[2] = 0.8;      (*\[Mu]m*)

\[Gamma][0] = 6 \[Pi] \[Nu] r[0];
\[Gamma][1] = 6 \[Pi] \[Nu] r[1];
\[Gamma][2] = 6 \[Pi] \[Nu] r[2];

(*15.1098*)
(*3.77745*)

\[Theta] = 3.14;

V1[x_] := (1/\[Gamma][1]) (f2 -
     f3 (((x - T)/T) Cos[\[Theta]] Sin[\[Theta]])/(\[Gamma][
           1]/\[Gamma][0] + ((x - T)/T) (Sin[\[Theta]])^2));
V2[y_] := (1/\[Gamma][2]) (f2 -
     f3 (((y - T)/T) Cos[\[Theta]] Sin[\[Theta]])/(\[Gamma][
           2]/\[Gamma][0] + ((y - T)/T) (Sin[\[Theta]])^2));

VA[Tkin1_,
   Tkin2_, \[Phi]1_, \[Phi]2_] := {{V1[Tkin1] Sin[\[Phi]1] -
     V1 [Tkin2] Sin[\[Phi]2],
    V1[Tkin1] Cos[\[Phi]1] + V1[Tkin2] Cos[\[Phi]2]}};
VB[Tkin1_,
   Tkin2_, \[Phi]1_, \[Phi]2_] := {{V2[Tkin1] Sin[\[Phi]1] -
     V2[Tkin2] Sin[\[Phi]2],
    V2[Tkin1] Cos[\[Phi]1] - V2[Tkin2] Cos[\[Phi]2]}};

delta[Tkin1_, Tkin2_, \[Phi]1_, \[Phi]2_] :=
  ArcCos[(VA[Tkin1, Tkin2, \[Phi]1, \[Phi]2].Transpose[
       VB[Tkin1, Tkin2, \[Phi]1, \[Phi]2]])/(Norm[
       VA[Tkin1, Tkin2, \[Phi]1, \[Phi]2]] Norm[
       VB[Tkin1, Tkin2, \[Phi]1, \[Phi]2]])];

\[Phi]1 = \[Pi]/3;
\[Phi]2 = \[Pi]/4;

Plot3D[delta[Tkin1, Tkin2, \[Phi]1, \[Phi]2], {Tkin1, 300,
  1000}, {Tkin2, 300, 1000},
 AxesLabel -> {"Tkin1", "Tkin2", "\[Gamma]"},
 ColorFunction -> "BrownCyanTones", PlotRange -> Automatic]

The plot of the angle $\Delta$ will be

Surely this code can be improved in order to get a more elegant and fine working algorithm.


text:
Q: PHP file permissions I just launched an ec2 server and put all the php code on the server and I need to change the permissions so that a user cant go to the site like http:example.com/admin and see the list of php files....Do I need to change the permissions on the entire folder or each file or is there a recursive -R command that will work ...I think they are all currently 777 ...which is bad

A: If you are using Apache, then hiding things from being listed usually is handled in an .htaccess or the apache configuration, not with filesystem permissions.

A: To prevent people from being able to see what files are in a directory, with apache, you just need to turn "Indexes" off in the appropriate Directory directive. You can also override the default with an .htaccess file, but for a production server, the default should be no indexes.
For file permissions, I'd advocate switching nearly everything to read only, or read and execute if you have to (544 or 554). Leaving write permissions on files that don't need to be written is asking for trouble.

A: You need to set up rules in your .htaccess file and set permissions on directory. The last one is made by chmod -R 700 that is recursive change mode to make it readable, writable and executable only by owner (you)

A: To quickly  change the permissions of all files in a directory tree (and yes, 777 is a horribly bad permission level to give them) you'll want a command like
find ./ -exec chmod go-w {} \;
This will recursively go through all files and folders in that subdirectory and remove write access for people who aren't the owner.
You may also want to use
find ./ -type f -exec chmod -x {} \;
to remove the executable bit from all non-directories. Apache doesn't need them to run php scripts.


text:
Q: Firefox download window open in the second monitor I have two monitors, one is the main and the second is a TV.
I was trying to download a file from SkyDrive for about 40 minutes without success, the popup window never comes up.
Then the movie on TV ends and I choose PC HMDI input to see the second Window screen and there is, the about 80 download windows waiting for my approbation to start the download.
I'm very annoyed.
So, There's any way to configure Firefox to open all the Windows(pop up/msgbox) over the main window?
I'm talking about this window.


text:
Q: Socket class Error ListenSocket.h
    //  class does not contain WSASTARTUP () and WSACLEANUP ()

#ifndef LISTENTHREAD_H
#define LISTENTHREAD_H
#include "includes.h"
#include "LOGMSGs.h"

// 1, CListenSocket: class is used to create the listener thread local variable.
// This class can be reused. When you call Close () is closed, re-calling Open () the new listening port. But the system did not use the feature.
class   CListenSocket
{
public:
    // main method:
    // BIND each object only to a port.
    CListenSocket(u_short nPort, int nSndSize = 0);
    // to release SOCKET
    ~CListenSocket(){};
    // Create server listening SOCKET, specific options see the code. Fails to return false.
    bool    Open();     // call can be repeated
    // error return INVALID_SOCKET
    SOCKET  Accept(u_long & nClientIP);
    // repeated calls. Usually not, can be used to take the initiative to close the SOCKET.
    // close the re-call after Open () re-use the object.
    void    Close();        // call can be repeated
    bool    IsOpen() { return m_bState; }
    bool    Rebuild();
public:
    SOCKET  Socket() { return m_sockListen; }
protected:
    // main member variables:
    const u_short   m_nPort;
    const int       m_nSndBuf;
    SOCKET  m_sockListen;
    // network status is normal sign.
    // When the value is false that the object is not available. May not have Open (), may also be a network error.
    bool    m_bState;
    time_t  m_tCloseTime;       // SOCKET last closed the time delay for the automatic re-SOCKET
};

#endif  // LISTENTHREAD_H

ListenSocket.cpp
#include "ListenSocket.h"
long    s_nSocketCount = 0;
int     REBUILDLISTENDELAYSEC;

CListenSocket::CListenSocket(u_short nPort, int nSndBuf /*= 0*/)    // 0: Default
         : m_nPort(nPort), m_nSndBuf(nSndBuf)
{
    m_sockListen    = INVALID_SOCKET;
    m_bState        = false;
//  m_nPort         = nPort;
    m_tCloseTime    = 0;
}

//  Error returned INVALID_SOCKET
SOCKET  CListenSocket::Accept(u_long & nClientIP)
{
/*
    // Reconstruction SOCKET
    if(!m_bState)
    {
        if(clock() < m_tCloseTime + REBUILDLISTENDELAYSEC*CLOCKS_PER_SEC)
            return INVALID_SOCKET;
        else
        {
            LOGMSG("Anti-crash system start listening SOCKET [%d] re under construction...", m_nPort);
            if(Open())
            {
                LOGMSG("... listen SOCKET reconstruction success.");
                PrintText("Listen SOCKET [%d] failed to rebuild SOCKET success. Server continues to run in the ...", m_nPort);
            }
            else
            {
                Error("... listen SOCKET reconstruction has failed. Server will not accept new connections");
                PrintText("Listen SOCKET [%d] error, [%d] seconds after the re-SOCKET. Server continues to run in the ...", m_nPort, REBUILDLISTENDELAYSEC);        // nDelaySec);
            }
            m_tCloseTime = clock();
        }
    }
//*/
    if(!m_bState)
    {
        Error("ACCEPT inner exception a1");
        return INVALID_SOCKET;
    }

    // ACCEPT
    struct sockaddr_in  addr;
    memset(&addr, 0, sizeof(addr));
    int    len = sizeof(addr);
    SOCKET newsock = accept(m_sockListen, (sockaddr*)&addr, (int*)&len);        // receive to the other side of the map, you can use
#ifdef  PROFILE_X
            // Analysis Accept speed (cycle speed)
            const int   nTimes2 = ACCEPTPROFILESEC;     // Statistics once every 30 seconds the speed ACCEPT
            static  clock_t tNextTime2 = clock() + nTimes2 * CLOCKS_PER_SEC;    //? Only one monitor thread, no sharing violation
            static long nCount2 = 0;                                //? Only one monitor thread, no sharing violation
            if(clock() >= tNextTime2)
            {
                PrintText("Each [%d] seconds to execute a [%d] times Accept ()", nTimes2, InterlockedExchange(&nCount2, 0));
                tNextTime2 = clock() + nTimes2 * CLOCKS_PER_SEC;
            }
            else
            {
                InterlockedIncrement(&nCount2);
            }
#endif  // PROFILE
    if(newsock == INVALID_SOCKET)
    {
        // Network Error
        int err = WSAGetLastError();
        if(err != WSAEWOULDBLOCK)
        {
            PrintText("Listen SOCKET %d failed, %s seconds after the re-SOCKET.", m_nPort, REBUILDLISTENDELAYSEC);
            Error("Listen SOCKET [%d] failed [%d], [%s] seconds after the re-SOCKET.", m_nPort, err, REBUILDLISTENDELAYSEC);
            Close();
        }
        else
            Error("ACCEPT inner exception a2");
            return INVALID_SOCKET;
    }
    else
    {
        nClientIP = addr.sin_addr.S_un.S_addr;
        InterlockedIncrement(&s_nSocketCount);
    }

    // Check whether the SOCKET closed
    fd_set  readmask;
    FD_ZERO(&readmask);
    FD_SET(newsock, &readmask);
    struct timeval  timeout = {0, 0};
/*
    char nTemp;
    if(select(FD_SETSIZE, &readmask, (fd_set *) 0, (fd_set *) 0, &timeout)
            && recv(newsock, &nTemp, 1, MSG_PEEK) == 0)
    {
#ifdef  ALPHA_X
        LOGMSG("ACCEPT a new SOCKET is invalid .");
#endif
        closesocket(newsock);
        InterlockedDecrement(&s_nSocketCount);
        return INVALID_SOCKET;
    }
//else*/
//*
    fd_set  exceptmask;
    FD_ZERO(&exceptmask);
    FD_SET(newsock, &exceptmask);
    int ret = select(FD_SETSIZE, &readmask, (fd_set *) 0, (fd_set *) &exceptmask, &timeout);
    if(ret < 0)
    {
        Error("ACCEPT a new SOCKET is invalid . can't read");       // Not trigger
        closesocket(newsock);
        InterlockedDecrement(&s_nSocketCount);
        return INVALID_SOCKET;
    }
    else if(ret > 0)
    {
        if(FD_ISSET(newsock, &exceptmask))
        {
            LOGMSG("ACCEPT a new SOCKET is invalid.except");        // Not trigger
            closesocket(newsock);
            InterlockedDecrement(&s_nSocketCount);
            return INVALID_SOCKET;
        }
        else if(FD_ISSET(newsock, &readmask))
        {
            char nTemp;
            if(recv(newsock, &nTemp, 1, MSG_PEEK) == 0)
            {
#ifdef  ALPHA_X
                LOGMSG("ACCEPT a new SOCKET is invalid. recv==0");      // Not trigger
#endif
                closesocket(newsock);
                InterlockedDecrement(&s_nSocketCount);
                return INVALID_SOCKET;
            }
        }
    }
//*/
#ifdef  PROFILE_X
            // analysis Accept speed (received valid SOCKET)
            const int   nTimes = ACCEPTPROFILESEC;      // Statistics once every 10 seconds the speed ACCEPT
            static  clock_t tNextTime = clock() + nTimes * CLOCKS_PER_SEC;      //? Only one monitor thread, no sharing violation
            static long nCount  = 0;                            //? Only one monitor thread, no sharing violation
            if(clock() >= tNextTime)
            {
                LOGPROFILE("Port [%d] for every [%d] seconds, the successful implementation of the [%d] times Accept()",
                            m_nPort, nTimes, InterlockedExchange(&nCount, 0));
                tNextTime = clock() + nTimes * CLOCKS_PER_SEC;
            }
            else
            {
                InterlockedIncrement(&nCount);
            }
#endif  // PROFILE

    return newsock;
}

Main.cpp
#include "includes.h"
#include "IniFile.h"
#include "LOGMSGs.h"
#include "ListenSocket.h"

CListenSocket Sock(9985);
int main()
{
    Sock.Open();
    if(!Sock.Open())
    {
        Sock.Rebuild();
    }
    if(Sock.IsOpen())
        PrintText("okey");
    Sock.Socket();
    u_long ip;
    Sock.Accept(ip);
}

but i always got this error : ACCEPT inner exception a2 while it should work anyclue why?

A: CListenSocket Sock(9985);
int main()
{
    Sock.Open();
    if(!Sock.Open())

/* I think you meant 'IsOpen()' */

    {
        Sock.Rebuild();
    }
    if(Sock.IsOpen())
        PrintText("okey");
    Sock.Socket();
    u_long ip;
    Sock.Accept(ip);
}

Incidentally, this code sure reads funny. It feels like a generic toolkit programmed without a specific goal in mind. Maybe I'm missing it, but I have to think you'd have better results if you just wrote the network code that actually needed, and then abstract out the common bits into some helper routines later. There's no point in trying too hard to make the be-all and end-all network helper library, but there is a huge point in making tools that collapse common cases.
Feel free to ignore that last paragraph if you know what you're doing :) but if you're just starting out, I'd like to suggest writing a few smaller clients and servers, and then try writing your abstraction layer.


text:
Q: How can I use ptiPython with Flask-Script together? In Django, I can use ptiPython instead of IPython after enabling Django-Extensions plugin to enforce Django-Shell. In Flask world, the alternative one of seems to be Flask-Script, I searched around but could not find anything to use ptiPython with Flask-Shell together.

A: Flask-Script support ipython and bpython. You can create custom Shell class
from flask.ext.script import Shell
from ptpython.ipython import embed

class PtShell(Shell):
    def run(self, **kwargs):
        context = self.get_context()
        embed(user_ns=context)

manager.add_command("shell", PtShell())


text:
Q: How can I transfer a variable in R to Excel? I have a dataframe in R called a (2 variables, 2477 entries) and I want to copy and paste it to Excel. I can view the variable, right click, select all, copy, and paste but only a small portion is copied (198). I have tried to use
write_xlsx(a,"name")

but this only creates a text document. This cannot be complicated and should be able to be done easily. How?

A: You could use openxlsx:
library(openxlsx)
wb <- createWorkbook()

addWorksheet(wb, "MySheet")

writeData(wb, sheet="MySheet", x = head(mtcars,10), startRow = 1, startCol = 1)
openxlsx::saveWorkbook(wb,'test.xlsx')


text:
Q: cant save radio button selections to database with thymeleaf I have form and inside I have radio button option  , I have the controller class  and the model. I can successfully save the other data but radio buttons options reflects to database as 0 always.  I believe there is something wrong with thymeleaf radio button implementation.
<form id="add" role="form" th:action="@{/add}" method="post" th:object="${radiobutton}">
    <input type="hidden" th:field="*{id}"/>

        is it new

            <input type="radio" name="optionsRadiosInline1" id="optionsRadiosInline1"
                   value="true" th:checked="*{isNew}"/>Yes

            <input type="radio" name="optionsRadiosInline1" id="optionsRadiosInline2"
                   value="false" th:checked="*{isNew} == false"/>No

</form>

A: I found it , values should be 0 or 1 instead of true and  false
<form id="add" role="form" th:action="@{/add}" method="post" th:object="${radiobutton}">
    <input type="hidden" th:field="*{id}"/>

        is it new

            <input type="radio" name="optionsRadiosInline1" id="optionsRadiosInline1" value="1"
                   th:checked="*{isNew}"/>Yes

            <input type="radio" name="optionsRadiosInline1" id="optionsRadiosInline2" value="0"
                   th:checked="*{isNew} == false"/>No

</form>


text:
Q: Converting a UTC date to a local time with Swift: hours added instead of hours removed I am trying to convert a UTC date into the current timezone but I notice a time problem.
I am in Tahiti / French Polynesia (UTC-10) and current time (used format : yyyy/MM/dd HH:mm:ss) is: 2018/08/05 06:45:00
Google says UTC Time is: 2018/08/05 16:45:00
With this code below, the result is: 2018/08/06 02:45:42 +0000 (the day after today) instead of 2018/08/05 06:45:42 +0000 (today).
Converting Date() to the current timezone add 10 hours instead of remove 10 hours.
Where is my mistake ?
Swift 3
import Foundation

    extension Date {

     var toLocalTimezone : Date {

      let formatter = DateFormatter()
      formatter.dateFormat = "yyyy/MM/dd' 'HH:mm:ss"
      formatter.timeZone = TimeZone(secondsFromGMT:0) // UTC
      let defaultTimeZoneStr = formatter.string(from: self)

      let dateFormatter = DateFormatter()
      formatter.timeZone = TimeZone.current // Local
      dateFormatter.dateFormat = "yyyy/MM/dd' 'HH:mm:ss"

      return dateFormatter.date(from:defaultTimeZoneStr)!

      }

    }

    debugPrint("\(TimeZone.current)")
    debugPrint("Locale time : \(Date().toLocalTimezone.toFormat(format: DateFormats.yyyyMMddHHmmss))" )

Results :

"Current timezone : Pacific/Tahiti (current)"
"Locale time : 2018-08-06 02:45:42"

Instead of :

"Locale time : 2018-08-05 06:45:42"

A: It is simple actually. timeZone property of DateFormatter is telling the DateFormatter what timezone the string generated from Date should be in OR what timezone is the string that you are trying to convert to Date.
What it means in your case?
  let formatter = DateFormatter()
  formatter.dateFormat = "yyyy/MM/dd' 'HH:mm:ss"
  formatter.timeZone = TimeZone(secondsFromGMT:0) // UTC
  let defaultTimeZoneStr = formatter.string(from: self)

This means you are formatting a Date to a String and that resulting String will be in TimeZone(secondsFromGMT:0)
On the other hand:
  let dateFormatter = DateFormatter()
  formatter.timeZone = TimeZone.current // Local
  dateFormatter.dateFormat = "yyyy/MM/dd' 'HH:mm:ss"

  return dateFormatter.date(from:defaultTimeZoneStr)!

You are telling the formatter that you have a String in TimeZone.current and it will try to create a Date from it.
Date is always a GMT+0 and you are supposed to use other APIs (DateFormatter) to convert it to output format and timezone.
My understanding is that you are trying to create a function that will output a Date formatted into String with custom format and users timezone. Here is the snippet I believe you are looking for:
extension Date {
  func format(_ format: String) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = format
    formatter.timeZone = TimeZone.current // Local
    return formatter.string(from: self)
  }
}


text:
Q: The following statment doesn't create a value on the Heap, nor the stack. Where does it exist in memory until then? This is from my Computer Science Class

"This is dangerous (and officially deprecated in the C++ standard) because you haven't allocated memory for str1 to point at."
            — jD3V's Computer Science Professor

The Quote Above is Referring to this Line of Code
    char* str1 = "Hello world";

To be clear:
I Get that using a pointer, as shown in the Line of Code above, is deprecated. I also know that it shouldn't appear in my code.
The Part I Don't Get:
The example line of code — char* str1 = "Hello world"; — works, and that surprises me.
It says that no memory has been allocated for the pointer to point at, though the pointer could still be accessed to obtain the C-String "Hello World". I am unaware of another place in memory, though my guess is that there has to be one, because if the following statement doesn't exist on the heap — "and its not placed in the stack according to my debugger" — then it must live in another memory location.
I am trying to be able to understand, and locate where the variables I declare are at in memory, and I am unable to do that here.
I would like to know...
In the example I showed above, where is the string "Hello World", and the str1 pointer that points at it, located in memory, if not in the Heap, or on the Stack?

A: [Disclaimer: I wrote this answer when the question was tagged both [c] and [c++].  The answer is definitely different for C versus C++.  I am leaning somewhat towards C in this answer.]

char* str = "Hello world";

This is perfectly fine in C.

According to my CS Professor, in reference to the statement above, he says...

"This is dangerous (and officially deprecated in the C++ standard) because you haven't allocated memory for str to point at."

Either you misunderstood, or your professor is very badly confused.
The code is deprecated in C++ because you neglected to declare str as being a pointer to unmodifiable (i.e. const) characters.  But there is nothing, absolutely nothing, wrong with the allocation of the pointed-to string.
When you write
char *str = "Hello world";

the compiler takes care of allocating memory for str to point to.
The compiler behaves more or less exactly as if you had written
static char __hidden_string[] = "Hello world";
char *str = __hidden_string;

or maybe
static const char __hidden_string[] = "Hello world";
char *str = (char *)__hidden_string;

Now, where is that __hidden_string array allocated?  Certainly not on the stack (you'll notice it's declared static), and certainly not on the heap, either.
Once upon a time, the __hidden_string array was typically allocated in the "initialized data" segment, along with (most of) the rest of your global variables.  That meant you could get away with modifying it, if you wanted to.
These days, some/many/most compilers allocate __hidden_string in a nonwritable segment, perhaps even the code segment.  In that case, if you try to modify the string, you'll get a bus error or the equivalent.
For backwards compatibility reasons, C compilers cannot treat a string constant as if it were of type const char [].  If they did, you'd get a warning whenever you wrote something like
char *str = "Hello world";

and to some extent that warning would be a good thing, because it would force you to write
const char *str = "Hello world";

making it explicit that str points to a string that you're not allowed to modify.
But C did not adopt this rule, because there's too much old code it would have broken.
C++, on the other hand, very definitely has adopted this rule.  When I try char *str = "Hello world"; under two different C++ compilers, I get warning: conversion from string literal to 'char *' is deprecated.  It's likely this is what your professor was trying to get at.

A: The problem is in lvalue and rvalue. lvalue defines locator value and it means that it has a specified place in memory and you can easily take it. rvalue has undefined place in memory. For example, any int a = 5 has 5 as rvalue. So you cannot take the address of an rvalue. When you try to access the memory for char* str = "Hello World" with something like str[0] = 'x' you will get an error Segmentation fault which means you tried to get unaviable memory.  Btw operators * and & are forbidden for rvalues, it throws compile time error, if you try to use them.
The lvalue of "Hello World" is stored at the programms segment of memory. But it is specified so, as the programm can't modify it directly.

A: Summary:

*

*"any strings in double quotes" are const lvalue string literals, stored somewhere in compiled program.

*You can't modify such string, but you can store pointer to this string (of course const) and use it without modifying:
const char *str = "some string"
For example:
int my_strcmp(const char *str1, const char *str2) { ... }

int main()
{
    ...

    const char *rule2_str= "rule2";

    // compare some strings
    if (my_strcmp(my_string, "rule1") == 0)
        std::cout << "Execute rule1" << std::endl;
    else if (my_strcmp(my_string, rule2_str) == 0)
        std::cout << "Execute rule2" << std::endl;

    ...
}

*If you want to modify string, you can copy string literal to your own array: char array[] = "12323", then your array will ititialize as string with terminate zero at the end:
Actually char array[] = "123" is same as char array[] = {'1', '2', '3', '\0'}.
For example:
int main()
{
    char my_string[] = "12345";
    my_string[0] = 5; // correct!

    std::cout << my_string << std::endl; // 52345
}

Remember that then your array will be static, so you can't change it's size, for "dynamic sized" strings use std::string.


text:
Q: Xml parsing in Android, Null exception i have an xml that looks this way
<Quiz>
<Inhalt Frage="test" number="1" />
<Inhalt Frage ="test2" number=2"/>
</Quiz>

Now, in android i want to parse this xml in that way, that the result show me the content
of "Frage" for the number 2. I have tried to parse it this way, but i always get a nullexception error:
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr= xpath.compile("//Frage[@number=2]/text()");

Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
einga= nodes.item(0).getNodeName();

Would be great, if someone could help me with this.
Thank you :-)

A: You are trying to select the text from the node Frage which have an attribute number with the value 2. Are you familiar with Xpath expressions? Try this link : http://w3schools.com/xpath/xpath_syntax.asp
Try : "//Inhalt[@number='2']/@Frage". You will get test2


text: Q: Group of line bundles with $\otimes$ isomorphic to $H^1(B,\mathbb{Z}_2)$ I want to prove that all line bundles with the same base $B$ form group with operation $\otimes$ which isomorphic to $H^1(B,\mathbb{Z}_2)$. It's obvious to me, that there is bijection between line bundles and $H^1(B,\mathbb{Z}_2)$ which exists because $B\mathbb{Z}_2 = K(\mathbb{Z}_2,1)$ but I dont understand why that group is isomorphism. I found some proof in icc prop. 3.7.12 but it uses concept of Euler characteristic class, and I want to some prove which uses only concept of Stiefel Whitney class, does that exist? Hope for your help.


text:
Q: Grunt slow on network I've created a grunt file on a project I'm working on. We have a template and that is used across a range of products but it's all saved to our network. When I run grunt default on the template it completes it in seconds. When I move the template to one of the project folders running grunt default again (or grunt watch) will take ~20 minutes to complete.
These files are stored on the same drive with pathways a little something like this: (I've changed the names slightly):

*

*/Volumes/Company/shared/Code Library/HTML/Template

*/Volumes/Company/Project/assets/unit/development/source

Does anyone know why it would take so long for a grunt task to complete in one folder but not the other? If I copy it to the desktop it also completes a watch or default task in a matter of seconds.


text:
Q: Reading a binary file in read mode Python 3 - passes on Windows, fails on Linux I am executing this piece of code against
Python on Windows
'3.6.8 |Anaconda, Inc.| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]'
and
Python on Linux
'3.6.6 (default, Mar 29 2019, 00:03:27) \n[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]'
The code writes some bytes into a file using wb mode and then reads it as r plain text. I understand that I should be reading as bytes (rb), but I am curious why does it break on Linux while passing on Windows?
import os
import tempfile
temp_dir = tempfile.mkdtemp()
temp_file = os.path.join(temp_dir, 'write_file')

expected_bytes = bytearray([123, 3, 255, 0, 100])
with open(temp_file, 'wb') as fh:
    fh.write(expected_bytes)

with open(temp_file, 'r', newline='') as fh:
    actual = fh.read()

Exception raised on Linux:
Traceback (most recent call last):
  File "<input>", line 11, in <module>
  File "/home/.../lib64/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid start byte

Getting default system encoding (with sys.getdefaultencoding()) shows
'utf-8' on both machines.

A: When opening a file in text mode, so with 'rt' (where both 'r' and 't' are the default), everything you read from the file gets transparently decoded on the fly and returned as str objects, as explained in Text I/O.
You can force the encoding to use when opening the file, like:
f = open("myfile.txt", "r", encoding="utf-8")

As explained in the documenation for open:

The default encoding is platform dependent (whatever
  locale.getpreferredencoding() returns), but any text encoding
  supported by Python can be used. See the codecs module for the list of
  supported encodings.

(Note that sys.getdefaultencoding() is something unrelated: it returns the name of the current default string encoding used by the Unicode implementation)
As you stated in the comments, on your system, locale.getpreferredencoding() gives 'cp1252' on Windows and 'UTF-8' on Linux.
CP-1252 is a single byte encoding in which each byte corresponds to a character. So, whatever file you read, the data it contains can be turned into a string.
UTF-8, though, uses a variable width encoding in which not all sequences of bytes are valid and represent a character. That's why trying to read your file on your Linux system failed when some byte couldn't be decoded.

A: If you have written the file out as bytes, you should read it in as bytes.
f = open("myfile.txt", "rb")

If you read it in as text (using "r" or "rt") then an attempt will be made to decode it into Unicode. What encoding is used by default is platform-dependent. But you clearly don't want it decoded at all.


text:
Q: Two interacting bodies in an external field Hope, MO is the right place for this question (if not so: where would you pose it?).
Consider a two-body system in classical mechanics. As long as the interaction depends only on the distance of the two bodies, the two-body problem is integrable/solvable. Now consider the two bodies in a fixed external field. (This is only one step away from a three-body system that is known to be non-integrable in general, but obviously different from it.)

Question: Can the conditions on the combination
  of interaction and external field be
  explicitely given for the problem to
  be integrable/solvable?

It might be the case that the problem is
always solvable. In this case the
following reference request becomes
predominant:

Reference request:
  Where can I find an explicit and
  elaborated treatment of this problem?

A: I seriously doubt there is any general criteria.  However there are
more than one beautiful explicit examples of an external field which
lead to an integrable problem.  The simplest and probably best known is
that of a   constant field.
An absolutely beautiful description of this and its solution can be found in the book
`Essais sur le Mouvement des Corps Cosmiques' by V. Beletski, ch. 3.
(See eq. 3.2.1) It illustrates the plethora of qualitatively different phenomenon possible
within a single integrable system.
As a wierd tangent, the `anisotropic Kepler problem': keep the same
potential but change the kinetic term to $a p_x ^2 + b p_y ^2$, $a \ne b$
is known to be non-integrable and Gutzwiller made an early career on this
problem.


text:
Q: Что означает данный код? Помогите, пожалуйста, с кодом ниже.
Я новичок и только недавно начал познавать программирование.
Список переменных и их значений:
$slideMenu = '';
$slides = array(
  array(
    'background' => 'image',
    'h2' => 'Text',
    'text' => 'Text'
  ),
  array(
    'background' => 'image',
    'h2' => 'Text',
    'text' => 'Text'
  ),
  array(
    'background' => 'image',
    'h2' => 'Text',
    'text' => 'Text'
  ),
);

А далее, вот:
<?php foreach ($slides as $i => $slide) { ?>
    <div id="slide-<?php echo $i + 1; ?>" data-id="<?php echo $i + 1; ?>" class="slide" style="display: <?php echo($i > 0 ? 'none' : 'block'); ?>;background-image: url(<?php echo $slide['background'] ?>);">

<?php echo $slide['h2'] ?>

<?php echo $slide['text'] ?>

    <?php $slideMenu .= ''; ?>
<?php } ?>

Не совсем понятны вот эти части:
<div id="slide-<?php echo $i + 1; ?>" data-id="<?php echo $i + 1; ?>" class="slide" style="display: <?php echo($i > 0 ? 'none' : 'block'); ?>;background-image: url(<?php echo $slide['background'] ?>);">

<?php $slideMenu .= ''; ?>

A: <?php foreach ($slides as $i => $slide) { ?>

Создает цикл по всем элементам $slides. При каждом проходе цикла будут существовать 2 элемента $i - индекс, $slide - массив значений array('h2' => "значение", 'text' => "значение", ...);

<div id="slide-<?php echo $i + 1; ?>" data-id="<?php echo $i + 1; ?>" class="slide" style="display: <?php echo($i > 0 ? 'none' : 'block'); ?>;background-image: url(<?php echo $slide['background'] ?>);">

Создается блок, где генерируются атрибуты: id = slide + наш индекс с каждым проходом цикла (будет такое: id="slide-1", id="slide-2", id="slide-3"...). Тоже самое и с атрибутом data-id. И проверка в конце, на не нулевой $i. Если ты в первом элементе то у блока будет display: block, иначе display: none;

<?php echo $slide['h2'] ?>

<?php echo $slide['text'] ?>

Просто выводятся 2 значения из массива $slide

<?php $slideMenu .= ''; ?>

Дописывает в переменную $slideMenu ссылку с data- атрибутами. Видимо генерирует количество точек (переключателей) по количеству слайдов.


text:
Q: Matlab - Subtracting two 3D figures with surf and min function I'm trying to make a surf plot that looks like:

So far I have:
x = [-1:1/100:1];
y = [-1:1/100:1];

[X,Y] = meshgrid(x,y);

Triangle1 = -abs(X) + 1.5;
Triangle2 = -abs(Y) + 1.5;

Z = min(Triangle1, Triangle2);

surf(X,Y,Z);
shading flat
colormap winter;
hold on;

[X,Y,Z] = sphere();
Sphere = surf(X, Y, Z + 1.5 );% sphere with radius 1 centred at (0,0,1.5)
hold off;

This code produces a graph that looks like :

*

*A pyramid with square base ([-1,1]x[-1,1]) and vertex at height c = 1.5 above the origin (0,0) is erected.

*The top of the pyramid is hollowed out by removing the portion of it that falls within a sphere of radius r=1 centered at the vertex.
So I need to keep the part of the surface of the sphere that is inside the pyramid and delete the rest. Note that the y axis in each plot is different, that's why the second plot looks condensed a bit. Yes there is a pyramid going into the sphere which is hard to see from that angle.
I will use viewing angles of 70 (azimuth) and 35 (elevation). And make sure the axes are properly scaled (as shown). I will use the AXIS TIGHT option to get the proper dimensions after the removal of the appropriate surface of the sphere.

A: Here is my humble suggestion:
N = 400; % resolution
x = linspace(-1,1,N);
y = linspace(-1,1,N);
[X,Y] = meshgrid(x,y);
Triangle1 = -abs(X)+1.5 ;
Triangle2 = -abs(Y)+1.5 ;
Z = min(Triangle1, Triangle2);
Trig = alphaShape(X(:),Y(:),Z(:),2);
[Xs,Ys,Zs] = sphere(N-1);
Sphere = alphaShape(Xs(:),Ys(:),Zs(:)+2,2);
% get all the points from the pyramid that are within the sphere:
inSphere = inShape(Sphere,X(:),Y(:),Z(:));
Zt = Z;
Zt(inSphere) = nan; % remove the points in the sphere
surf(X,Y,Zt)
shading interp
view(70,35)
axis tight

I use alphaShape object to remove all unwanted points from the pyramid and then plot it without them:

I know, it's not perfect, as you don't see the bottom of the circle within the pyramid, but all my tries to achieve this have failed. My basic idea was plotting them together like this:
hold on;
Zc = Zs;
inTrig = inShape(Trig,Xs(:),Ys(:),Zs(:)+1.5);
Zc(~inTrig) = nan;
surf(Xs,Ys,Zc+1.5)
hold off

But the result is not so good, as you can't really see the circle within the pyramid.
Anyway, I post this here as it might give you a direction to work on.

A: An alternative to EBH's method.
A general algorithm from subtracting two shapes in 3d is difficult in MATLAB. If instead you remember that the equation for a sphere with radius r centered at (x0,y0,z0) is
r^2 = (x-x0)^2 + (y-y0)^2 + (z-z0)^2

Then solving for z gives z = z0 +/- sqrt(r^2-(x-x0)^2-(y-y0)^2) where using + in front of the square root gives the top of the sphere and - gives the bottom. In this case we are only interested in the bottom of the sphere. To get the final surface we simply take the minimum z between the pyramid and the half-sphere.
Note that the domain of the half-sphere is defined by the filled circle r^2-(x-x0)^2-(y-y0)^2 >= 0. We define any terms outside the domain as infinity so that they are ignored when the minimum is taken.
N = 400; % resolution
z0 = 1.5;  % sphere z offset
r = 1;     % sphere radius
x = linspace(-1,1,N);
y = linspace(-1,1,N);
[X,Y] = meshgrid(x,y);
% pyramid
Triangle1 = -abs(X)+1.5 ;
Triangle2 = -abs(Y)+1.5 ;
Pyramid = min(Triangle1, Triangle2);
% half-sphere (hemisphere)
sqrt_term = r^2 - X.^2 - Y.^2;
HalfSphere = -sqrt(sqrt_term) + z0;
HalfSphere(sqrt_term < 0) = inf;
Z = min(HalfSphere, Pyramid);
surf(X,Y,Z)
shading interp
view(70,35)
axis tight


text:
Q: Assign user to ticket from list_display in django-admin I'm developing a Ticket system. Each ticket can be assigned to a user.
On the ticket list_display in django-admin I want to have a column that either displays the user assigned to that ticket, or a link 'Assign ticket to myself'. I know I could use list_editable or make a custom action to do this, but for usability reasons I want a link in the list_display.
models.py
class Ticket(models.Model):
    assigned = models.ForeignKey(User, null=True)

    def assigned_to(self):
        if self.assigned:
            return self.assigned
        else:
            return "Assign ticket to myself"
    assigned_to.allow_tags = True

    # untested example method for assigning user to a ticket
    def assign(self, user):
        self.assigned = user
        self.save()

This is where I got stuck.
I need that the user can click on the link, which will call the model method assign() to assign the user to the ticket, and reloads the page so the username is displayed in the list_display.
I hope someone can help me in the right direction. Note that I'm just a Django beginner...

A: Alternatively, something like this should work:
from django.contrib import admin, messages
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _

class TicketAdmin(admin.ModelAdmin):
    list_display = ('__str__', 'make_mine_link',)

    def get_urls(self):
        urls = super(TicketAdmin, self).get_urls()
        opts = self.model._meta

        my_urls = patterns('',
            (r'^([0-9]+)/assign-to-me/$',
                self.admin_site.admin_view(self.make_mine),
                name='%s_%s_make_mine' % (opts.app_label, opts.model_name)),
        )
        return my_urls + urls

    def make_mine(self, request, object_id):
        opts = self.model._meta
        redirect_to = reverse('admin:%s_%s_changelist' % (
            opts.app_label, opts.model_name), current_app=self.admin_site.name)
        ticket = get_object_or_404(self.model, pk=object_id)

        ticket.assigned = request.user
        ticket.save()

        msg = _('The selected Ticket now belong to you.')
        self.message_user(request, msg, messages.SUCCESS)
        return HttpResponseRedirect(redirect_to)

    def make_mine_link(self, obj):
        opts = self.model._meta
        url = reverse('admin:%s_%s_make_mine' % (opts.app_label, opts.model_name), args=(obj.pk,), )
        return 'Assign ticket to myself' % url
    make_mine_link.allow_tags = True

admin.site.register(Ticket, TicketAdmin)

I haven't tested this. If you have any issue, feel free to add a comment.

A: You're in the right path, but there is one more thing to do: django will automatically escape your column values, so you must turn it off for that column. To do that, just specify allow_tags property for that method, like this:
class Ticket(models.Model):
    assigned = models.ForeignKey(User, null=True)

    def assigned_to(self):
        if self.assigned:
            return self.assigned
        else:
            return "Assign ticket to myself"
    assigned_to.allow_tags = True

But remember that enabling allow_tags for field will turn off automatic escaping, so you should use format_html() inside it to avoid XSS vulnerability:
class Ticket(models.Model):
    assigned = models.ForeignKey(User, null=True)

    def assigned_to(self):
        if self.assigned:
            return self.assigned
        else:
            return format_html("Assign ticket to myself", link="/some/link/here")
    assigned_to.allow_tags = True

A: Have you considered using custom admin actions?
class TicketAdmin(admin.ModelAdmin):

    actions = [make_mine]

    def make_mine(self, request, queryset):
        """
        Set the Ticket to the current user.
        """
        for ticket in queryset:
            ticket.assigned = request.user
            ticket.save()
        self.message_user(request, _('The selected Ticket now belong to you.'))
    make_mine.short_description = _('Set the Ticket to the user')

Docs: https://docs.djangoproject.com/en/1.8/ref/contrib/admin/actions/