text:
Q: Where is my free memory? (Solaris 10) I have a default Solaris 10 installation running on a 64GB box. For some reason, not all of the memory is available for use. The reason I'm even bothered by it, is because I'm trying to get mysql to run there, and give it 58GB of RAM, or more, but the maximum I can map is 45GB (nmap fails).
Nothing is running, except the GUI (which we will remove soon). But the UI doesn't explain the fact that 13 GB of the memory are gone, somewhere.
If ARC is a part of the used memory in Solaris (as opposed to the filecache in linux), then the UI consumes 5GB, and we still should have at least 55GB of RAM for MySQL.
BUT: if this memory is consumed by the ARC, it should give the memory up, when innodb tries to nmap the memory (or does it?), so it makes no sense.
How can I see what consumes this memory, and free it?
Some technical data:

#kstat -m zfs | grep size
    data_size                       7847447040
    hdr_size                        139495272
    l2_hdr_size                     0
    l2_size                         0
    other_size                      510852000
    size                            8497794312

# top
96 processes: 95 sleeping, 1 on cpu
CPU states: 99.9% idle,  0.0% user,  0.1% kernel,  0.0% iowait,  0.0% swap
Memory: 64G phys mem, 51G free mem, 2048M swap, 2048M free swap

   PID USERNAME LWP PRI NICE  SIZE   RES STATE    TIME    CPU COMMAND
  1529 root       1  59    0   67M   10M sleep   11:17  0.20% mixer_applet2
   902 root       1  59    0   12M 9848K sleep    4:33  0.08% gconfd-2
  1923 root      34  59    0  165M   57M sleep    3:50  0.06% java
  1525 root       1  59    0   69M   13M sleep    3:24  0.06% gnome-netstatus
   644 root       1  58    0   45M   29M sleep    2:38  0.05% Xorg
  1501 root       1  59    0   73M   18M sleep    2:16  0.04% gnome-panel
 19814 root       1  59    0 3268K 1820K cpu      0:00  0.03% top
  2416 root      47  59    0   87M   68M sleep    2:08  0.03% java
 22587 noaccess  18  59    0  131M  115M sleep    2:13  0.03% java
   744 noaccess  18  59    0  132M  115M sleep    2:13  0.03% java
   908 root       1  59    0 6608K 4020K sleep    0:09  0.01% xscreensaver
  2435 root       2  49    0   73M   14M sleep    0:18  0.01% gnome-terminal
  2497 root      23  59    0   11M 7384K sleep    0:04  0.01% nscd
 22367 root       1  59    0 9832K 6636K sleep    0:01  0.00% snmpd
 15253 root       1  59    0 6516K 3840K sleep    0:00  0.00% sshd

# prtdiag -v
System Configuration: Dell Inc. PowerEdge R710
BIOS Configuration: Dell Inc. 2.2.10 11/09/2010
BMC Configuration: IPMI 2.0 (KCS: Keyboard Controller Style)

==== Processor Sockets ====================================

Version                          Location Tag
-------------------------------- --------------------------
Intel(R) Xeon(R) CPU           X5670  @ 2.93GHz CPU1
Intel(R) Xeon(R) CPU           X5670  @ 2.93GHz CPU2

==== Memory Device Sockets ================================

Type    Status Set Device Locator      Bank Locator
------- ------ --- ------------------- --------------------
Unknown in use 1   DIMM_A1
Unknown in use 1   DIMM_A2
Unknown empty  2   DIMM_A3
Unknown in use 2   DIMM_A4
Unknown in use 3   DIMM_A5
Unknown empty  3   DIMM_A6
Unknown empty  4   DIMM_A7
Unknown empty  4   DIMM_A8
Unknown empty  5   DIMM_A9
Unknown in use 5   DIMM_B1
Unknown in use 6   DIMM_B2
Unknown empty  6   DIMM_B3
Unknown in use 4   DIMM_B4
Unknown in use 5   DIMM_B5
Unknown empty  6   DIMM_B6
Unknown empty  4   DIMM_B7
Unknown empty  5   DIMM_B8
Unknown empty  6   DIMM_B9

==== On-Board Devices =====================================
Embedded Matrox G200 Video
Embedded Broadcom 5709C NIC 1
Embedded Broadcom 5709C NIC 2
Embedded Broadcom 5709C NIC 3
Embedded Broadcom 5709C NIC 4
Integrated RAID Controller

==== Upgradeable Slots ====================================

ID  Status    Type             Description
--- --------- ---------------- ----------------------------
1   available Unknown          PCI1
2   available Unknown          PCI2
3   in use    Unknown          PCI3
4   available Unknown          PCI4

#prstat -a
   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP
 21369 root     3888K 3036K cpu10   59    0   0:00:00 0.0% prstat/1
  1529 root       67M   10M sleep   59    0   0:11:22 0.0% mixer_applet2/1
 21234 100        45G 3686M sleep   59    0   0:00:17 0.0% mysqld/25
   902 root       12M 9848K sleep   59    0   0:04:35 0.0% gconfd-2/1
   644 root       45M   29M sleep   59    0   0:02:39 0.0% Xorg/1
   642 root     2560K  764K sleep   59    0   0:00:00 0.0% fbconsole/1
   640 root     5704K 1408K sleep   59    0   0:00:00 0.0% dtlogin/1
   863 root     4872K 1968K sleep   59    0   0:00:00 0.0% sdt_shell/1
  2438 root     1432K  832K sleep   59    0   0:00:00 0.0% sh/1
  2436 root     2644K 1392K sleep   59    0   0:00:00 0.0% gnome-pty-helpe/1
   883 root     1532K  892K sleep   59    0   0:00:00 0.0% Xsession2.jds/1
  2435 root       73M   14M sleep   49    0   0:00:18 0.0% gnome-terminal/2
   789 root     1568K  940K sleep   59    0   0:00:00 0.0% Xsession/1
   783 smmsp    9452K 2120K sleep   59    0   0:00:00 0.0% sendmail/1
   864 root     3228K  836K sleep   59    0   0:00:00 0.0% dsdm/1
   435 root     2064K  940K sleep   59    0   0:00:00 0.0% smcboot/1
   436 root     2064K  684K sleep   59    0   0:00:00 0.0% smcboot/1
   402 root     1432K  624K sleep   59    0   0:00:00 0.0% utmpd/1
   866 root     1456K  840K sleep   59    0   0:00:00 0.0% sh/1
   437 root     2064K  684K sleep   59    0   0:00:00 0.0% smcboot/1
   407 root     3988K 1936K sleep   59    0   0:00:00 0.0% syslogd/11
   630 root     3256K 2260K sleep   59    0   0:00:00 0.0% vold/5
  2497 root       11M 7392K sleep   59    0   0:00:04 0.0% nscd/23
 22200 root     3876K 1568K sleep   59    0   0:00:00 0.0% syslogd/13
   399 root     7996K 3996K sleep   59    0   0:00:01 0.0% inetd/4
   415 root     2468K 1372K sleep   59    0   0:00:00 0.0% ttymon/1
   404 root     2504K 1276K sleep   59    0   0:00:00 0.0% ttymon/1
   295 daemon   2932K 1432K sleep   59    0   0:00:00 0.0% rpcbind/1
   142 root     5452K 2184K sleep   59    0   0:00:00 0.0% syseventd/15
   224 root     2824K 1080K sleep   59    0   0:00:00 0.0% cron/1
   156 root     4344K 3164K sleep   59    0   0:00:00 0.0% picld/9
   387 root       18M   14M sleep   59    0   0:00:02 0.0% fmd/19
   152 daemon   4612K 2684K sleep   59    0   0:00:00 0.0% kcfd/4
   397 root     2132K 1040K sleep   59    0   0:00:00 0.0% sac/1
 19861 root     5864K 3720K sleep   59    0   0:00:00 0.0% zlogin/1
   204 root     2244K  780K sleep   59    0   0:00:00 0.0% iscsi-initiator/2
  2498 daemon   2716K 1676K sleep   59    0   0:00:00 0.0% statd/1
   369 root     2528K 1292K sleep   59    0   0:00:03 0.0% in.routed/1
    77 root     6148K 3484K sleep   59    0   0:00:02 0.0% devfsadm/9
  1923 root      165M   57M sleep   59    0   0:03:51 0.0% java/34
   669 root     6600K 2912K sleep   59    0   0:00:00 0.0% dtlogin/1
    11 root       12M   11M sleep   59    0   0:00:08 0.0% svc.configd/16
 NPROC USERNAME  SWAP   RSS MEMORY      TIME  CPU
    91 root      423M  425M   0.6%   0:34:57 0.0%
     1 100        45G 3703M   5.7%   0:00:17 0.0%
     2 noaccess  251M  237M   0.4%   0:04:28 0.0%
     2 smmsp    3804K   16M   0.0%   0:00:00 0.0%
    10 daemon     10M   14M   0.0%   0:00:00 0.0%

#  echo ::memstat | mdb -k
Page Summary                Pages                MB  %Tot
------------     ----------------  ----------------  ----
Kernel                     646470              2525    4%
ZFS File Data             1920208              7500   11%
Anon                      1078294              4212    6%
Exec and libs               14431                56    0%
Page cache                   2544                 9    0%
Free (cachelist)            13012                50    0%
Free (freelist)          13096905             51159   78%

Total                    16771864             65515
Physical                 16324293             63766

A: Based on the ::memstat output, ZFS is using up 7.5GB of physical memory. Be careful with ZFS: it can often be too aggressive and will starve the rest of the system of memory. In practice it simply doesn't release memory when you'd like it to.
See the ZFS Best Practices Guide for details on how you can limit the ARC size to mitigate this issue.

A: Can please paste a out of following
prtdiag -v
prstat -a

A: Is there any project limit in the memory mysql can allocate?
prctl -i project default

or, instead of 'default', the project under which mysql runs?


text:
Q: What's the appropriate SE site for a question about Google+? I initially asked my question on sof, which I now realize is clearly the wrong place:

So, as the title indicated - someone who is not my friend, neither to whom I am following, +1'd my post on google+, how could I then go follow him or add him to my circles? I got the notification, which shows the person that did the +1, but there is no link for me to access that person's profile page. And I searched the person by name, tons of having the same name!

I'm trying to post it on the correct site now, so I thought it best to ask here rather than risk adding noise in the wrong place again.

A: Questions about Google+ (assuming you're not talking about the Android or iPhone app) are on-topic at Web Applications.
Your question, as written, may not do very well however. There needs to be some more descriptive detail of the issue. Screen shots would be awesome.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why isn't openssl s_client passing my private key to proxytunnel? I currently have HAProxy set up on my home PC and I am attempting to access it through a HTTP proxy.  Currently I am accessing the SSH logon prompt like so:
openssl s_client->proxytunnel->HTTP(S) proxy->remote HAProxy->SSH server

I am getting to the point where I receive the SSH-2.0-OpenSSH prompt but for some reason it just hangs at the prompt and doesn't pass through the private key.
Here's the commands I am executing on the client side & how I set up proxy tunnel to use the organization's proxy:
proxytunnel -p httpproxy.organization.com:8080 -d ssh.homeserver.com:443 -a 7000

Next I am running openssl like so:
openssl s_client -connect localhost:7000 -quiet -key /home/user/.ssh/id_rsa

But for some reason the certificate does not appear to get passed through.  I am most likely missing a step so any suggestions would be greatly appreciated!

A: You are confusing the clients of two completely different protocols.
The openssl s_client tool is purely a TLS (SSL) client; it is capable of peeling away the TLS layer that HAproxy or stunnel might add. Once that's done, however, it merely transfers arbitrary data from one end to another. The prompt you're seeing is the initial SSH handshake, and the server expects you to reply to it; therefore, you still need to run a program like ssh that would talk the SSH protocol on top of the TLS tunnel.
Usually ssh connects to the server over TCP directly, but you can use the ProxyCommand option tell it to go through another program:
ssh -o ProxyCommand="openssl s_client -connect localhost:7000 -quiet" dummyname

If you have a SSH keypair, you'll need to specify it as an option to ssh as well:
ssh -i ~/.ssh/id_workplace -o ProxyCommand.....

(Don't need this for ~/.ssh/id_rsa though – it is used by default.)

The s_client options -cert and -key are of course for authenticating to the TLS server. However, they need a full X.509 certificate as "-cert"; just the public key isn't enough, as it would be for SSH.


text:
Q: Does the save method only updates passed field when saving an existing object? Let's say I have this object saved in MongoDB:
{ "hello" : "goodbye", "_id" : ObjectId("4f90c9106aee6e21b4e55c65"), "test" : "world" };

And I do
db.table.save({"_id" : ObjectId("4f90c9106aee6e21b4e55c65"), "test" : "changed value"});

Will it UPDATE the existing record? (test's value will be "changed" and the rest will be intact), Or create a new one?
Thanks!

A: Yes. If you pass the _id and use "save" it will update it.
> db.test.insert({ "hello" : "goodbye", "_id" : ObjectId("4f90c9106aee6e21b4e55c65"), "test" : "world" });
> db.test.save({"_id" : ObjectId("4f90c9106aee6e21b4e55c65"), "test" : "changed value"});
> db.test.find();
{ "_id" : ObjectId("4f90c9106aee6e21b4e55c65"), "test" : "changed value" }

Sorry, missed the second part of your question. You're looking for this:
db.test.update({_id: ObjectId("4f90c9106aee6e21b4e55c65")}, {$set:{test:"changed value"}});


text:
Q: Can I modify a text file while a program has it open, in C++? I have a class that, when created, opens a file.
And on each update, it reads each line of the file and extracts a key and a value.
It compares the value with a reference value that it has in an internal variable, and if the value is different, it fires an event.
The idea is that, manually and with the program running, I open the text file, modify a value and the program detects it, but that doesn't happen. It doesn't detect it. It is as if the instance of the file that I open and the one that has the program open are different.
Do I have to open the file on each update? Now I keep it open from when the class is created until it is destroyed.

A:
I have to open the file on each update?

The C++ standard does not specify how file streams behave when the file is modified externally. As discussed in comments, seeking to the beginning of the file may be sufficient to read the changed content, in which case re-opening won't be necessary.


text:
Q: can someone explain this code in detail and how should I run it in my javascript program In the code below, what is i and what is c? I want to use this code in my javascript so that I can move my map icon along a route.
How can I achieve this?
(function ()
{
  if (!map.me)
  {
    map.me = map.createLocationMarker(
      "http://libgmail.sourceforge.net/man.png", N.get("local"));
  };
  mv = function(i)
  {
    c = map.directions.polyline.getPoint(i);
    map.recenterOrPanToLatLng(c);
    map.setMarkerPosition(map.me, N.get("local"), c);
    if (i < map.directions.polyline.numPoints - 1)
    {
       window.setTimeout("mv("+(i+1) + ")",750)
    }
    else
    {
      map.me.hide()
    }
  };
  map.me.show();
  mv(0)
}
)();

A: c is a co-ordinate and i is an indexer, both are coming from the outer scope to which this code belongs.

A: c - point in the map
i - integer parameter of function, that means number of point, starts with 0, every recursion loop increments by 1, ends by map.directions.polyline.numPoints - 1
This code shows the way across all points in map.directions.polyline


text:
Q: Removing charAt from c string I am trying to write simple removeAt(char* str, int pos) in C, but confused by result.
char c[] = "abcdef";
char* c1 = removeAt(c, 3);

cout << c1;

If I am doing it in this way:
static char* removeAt(char* str, int pos)
{
   int i = 0;

   for(i = pos; str[i] != '\0'; i++)
   {
       str[i] = str[++i];
   }

   str[i] = '\0';

   return str;
}

string stays the same "abcdef";
If I am doing:
static char* removeAt(char* str, int pos)
{
 int i, k =0;

for(i = pos, k = pos;  str[i] != '\0'; i++)
{
   str[i] = str[++k];
}

str[i] = '\0';

return str;
}

does work as intended.

A: In this loop
for(i = pos; str[i] != '\0'; i++)
{
    str[i] = str[++i];
}

You change the value of i by doing i++, so you end up missing a character every two, or something similar. Change i++ to i+1.
EDIT: By the way, the line
str[i] = str[++i]

is undefined behaviour, since it's not specified when the increment will occur (before or after evaluating the left side?). If the right side is evaluated first then your code would be
i++;
str[i] = str[i];

Effectively doing nothing, as you observe.


text:
Q: How to return a string with 200 code with Apache 2.4 I'm trying to convert this nginx configuration block to Apache 2.4:
http {
...
server {
...
  location ~ ^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)$ {
    default_type text/plain;
    return 200 "$1.6fXAG9VyG0IahirPEU2ZerUtItW2DHzDzD9wZaEKpqd";
  }
...
}
}

What I have at this moment is:
<LocationMatch ^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)$>
RewriteEngine On
RewriteRule ^/.*/$ $1.6fXAG9VyG0IahirPEU2ZerUtItW2DHzDzD9wZaEKpqd [R=200]
</LocationMatch>

But it's definitely not working.
What I'm trying to achieve? Let's Encrypt stateless mode with Apache: https://github.com/Neilpang/acme.sh/wiki/Stateless-Mode


text:
Q: sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) CHECK constraint failed: vehicle I'm having this error mentioned in the title when I try to insert data on my sqlite database. The data comes from a form in a front-end.
I defined two models of entities, a Person and a Vehicle. They are related in type one(Person) to many(Vehicle).
I use this models on file controllers.py to insert data on then.
### file models.py
from app import db

class Person(db.Model):
    __tablename__ = 'person'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)
    first_name = db.Column(db.String(100), nullable=False)
    last_name = db.Column(db.String(100), nullable=False)
    cpf = db.Column(db.String(16), nullable=False, unique=True)
    email = db.Column(db.String(300), nullable=False, unique=True)

    owns = db.relationship('Vehicle')

    def __init__(self, username, password, first_name, last_name, cpf, email):
        self.username = username
        self.password = password
        self.first_name = first_name
        self.last_name = last_name
        self.cpf = cpf
        self.email = email

    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(sef):
        return True

    @property
    def is_anonymous(sef):
        return False

    def get_id(self):
        return str(self.id)

    def __repr__(self):
        return "<UsersLogin %r>" % self.username

class Vehicle(db.Model):
        __tablename__ = 'vehicle'

        id = db.Column(db.Integer, primary_key=True)
        person_id = db.Column(db.Integer, db.ForeignKey('person.id'))
        license_plate = db.Column(db.String(20))
        crlv = db.Column(db.String(600))
        crv = db.Column(db.String(600))

        def __init__(self, license_plate, crlv, crv):
            self.license_plate = license_plate
            self.crlv = crlv
            self.crv = crv

### file controllers.py

### codes...

if current_user.is_authenticated:

        person = Person.query.filter_by(id=current_user.id).first()
        new_vehicle = Vehicle(
            license_plate=form.license_plate.data,
            crlv=form.crlv.data,
            crv=form.crv.data,
        )

        person.owns.append(new_vehicle)
        db.session.add(new_vehicle)
        db.session.commit()
        flash("Congrats! Your vihicle was recorded on our system!")
        return redirect(url_for("index"))

I want to add a new Vehicle to a person, the Person already exists on my database. That's the problem. When I try do that, I'm having the error below:

sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) CHECK constraint failed: vehicle
  [SQL: INSERT INTO vehicle (person_id, license_plate, crlv, crv) VALUES (?, ?, ?, ?)]
  [parameters: (2, '4', '3', '4')]

The data comes from the front-end.
Please, anyone can help me to stop this error on my code?


text:
Q: are project folders really necessary? I started programming recently, I'm using Python as language and PyCharm as editor. Most of my programs are't complex, I'd been using only files and not projects, and now I'm learning how to create packages.
I noticed that creating a project implies generate a folder with more folders and files inside. If I need to work in a bunch of projects I kind of feel that working in this way generate a waste of resources (repeated folders and files). Is this believe correct?
My last questing is how to determine when to work with packages and when with projects?


text:
Q: Using GPS Satelites as dark matter detectors Recently, two scientists have proposed a new way of detecting dark matter, using GPS Satellites.
A part of the article is posted online: Hunting for topological dark matter with atomic clocks.
Can anyone make the it more explicit? How exactly could GPS Satellites detect dark matter?


text:
Q: Can I output the same amount of floating numbers in double that it number has in printf()? class Test
{
    public static void main(String[] args)
    {
        double arr[] = {1.2, 1.23, 1.234, 1.2345};
        System.out.printf("%f %f %f %f", arr[0], arr[1], arr[2], arr[3]);
    }
}

For example if I don't know how many numbers there are after dot (.) and I want to print them all in printf() without zeros (1.200000) ( likewise in println() ). If so, how?

A: you can use paramaters, eg: %1.2f, but this round the number. I'm not sure is that what you want.
    float f = 1.225f;
    System.out.printf("%f \t %1.2f \t %1.4f", f,f,f);

you can you BigDecimal is better solution, but problem with zeros on the end.
    float f = 1.225f;
    BigDecimal number1 = new BigDecimal(f);
    BigDecimal number2 = new BigDecimal(f).setScale(2, RoundingMode.HALF_DOWN);
    BigDecimal number3 = new BigDecimal(f).setScale(4, RoundingMode.HALF_DOWN);
    System.out.println(number1+"\n"+number2+"\n"+number3);

but if you put in BigDecimal number as string, will be printed with precission of this string:
    BigDecimal bd1 = new BigDecimal("1.123");
    BigDecimal bd2 = new BigDecimal("1.123000");
    System.out.println(bd1+"\n"+bd2);

so you can use this trick to your case:
    float f = 1.225000f;
    BigDecimal snumber1 = new BigDecimal(f+"");
    System.out.println(snumber1);

A: Use %s as the formatter:
System.out.printf("%s", 1.2); // output: 1.2

%s converts the number to a string with the usual toString method, which includes only as many digits as necessary to tell a number apart from its neighbors.


text:
Q: Is it possible to choose some elements from the set such that there average is exactly $x$? Suppose we are given a set $S$, which contains some numbers. We are also given a number $x$. We want to choose some elements from the set so that their average is exactly equal to $x$. We need to check if this some can be made or not. Now here I can see that I can pick two elements from the set some number of times to create a sum. Let's say we pick a number $a$ times and another number $b$ times. We can alter the number of times we take two numbers and create a different average or increase or decrease the average. But I am not able to see how can we make the average exactly $x$. And how do we check if it is possible in the first place?
Edit : The average, which we want to make, is an integer value. Basically any value of average between maximum and minimum value of the set can be made. I am looking for an mathematical/intuitive proof that any value between maximum and minimum value can be made. It is easy to see that we can increase or decrease the average by taking different values different number of times. But how do we guarantee for an average $x$.

A: Suppose $p$ is the minimum value of $S$ and $q$ is the maximum value of $S$. If we are given a target average $t$ with $p\le t\le q$. (Here $p,q,t$ are all integers.) Then if you take $q-t$ copies of $p$ and $t-p$ copies of $q$, you will get an average of $t$.


text:
Q: Cannot use pip install pandas when using pip install pandas
An error occurs as follows:
Collecting pandas
Using cached pandas-1.5.2.tar.gz (5.2 MB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [28 lines of output]
Traceback (most recent call last):
File "d:\py\lib\site-packages\pip_vendor\pep517\in_process_in_process.py", line 351, in
main()
File "d:\py\lib\site-packages\pip_vendor\pep517\in_process_in_process.py", line 333, in main
json_out['return_val'] = hook(**hook_input['kwargs'])
File "d:\py\lib\site-packages\pip_vendor\pep517\in_process_in_process.py", line 112, in get_requires_for_build_wheel
backend = _build_backend()
File "d:\py\lib\site-packages\pip_vendor\pep517\in_process_in_process.py", line 77, in build_backend
obj = import_module(mod_path)
File "d:\py\lib\importlib_init.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1030, in _gcd_import
File "", line 1007, in _find_and_load
File "", line 972, in _find_and_load_unlocked
File "", line 228, in _call_with_frames_removed
File "", line 1030, in _gcd_import
File "", line 1007, in _find_and_load
File "", line 986, in _find_and_load_unlocked
File "", line 680, in _load_unlocked
File "", line 790, in exec_module
File "", line 228, in call_with_frames_removed
File "C:\Users\zijie\AppData\Local\Temp\pip-build-env-kqsd82rz\overlay\Lib\site-packages\setuptools_init.py", line 18, in
from setuptools.dist import Distribution
File "C:\Users\zijie\AppData\Local\Temp\pip-build-env-kqsd82rz\overlay\Lib\site-packages\setuptools\dist.py", line 47, in
from . import _entry_points
File "C:\Users\zijie\AppData\Local\Temp\pip-build-env-kqsd82rz\overlay\Lib\site-packages\setuptools_entry_points.py", line 43, in
def validate(eps: metadata.EntryPoints):
AttributeError: module 'importlib.metadata' has no attribute 'EntryPoints'
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
py:3.10.0
os:windows11
Does anyone know how to solve the problem? Thanks!
I tried several times but it doesn't work.

A: Have you tried:
pip3 install pandas?


text:
Q: Get Exif data using Uri I want to get Exif data for an image that I pick from Android gallery or similar apps like Google Photos. Here are the methods that I am using for getting image file from Uri:
public static String getActualPathFromUri(@NonNull Context context, @NonNull Uri selectedImageUri) {
        Bitmap bitmap = null;
        try {
            bitmap = getBitmapFromUri(context, selectedImageUri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bitmap == null) {
            return null;
        }

        File imageFileFolder = new File(context.getCacheDir(), "example");
        if (!imageFileFolder.exists()) {
            imageFileFolder.mkdir();
        }

        FileOutputStream out = null;

        File imageFileName = new File(imageFileFolder, "example-" + System.currentTimeMillis() + ".jpg");
        try {
            out = new FileOutputStream(imageFileName);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
        } catch (IOException e) {

        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imageFileName.getAbsolutePath();
    }

    private static Bitmap getBitmapFromUri(@NonNull Context context, @NonNull Uri uri) throws IOException {

        ParcelFileDescriptor parcelFileDescriptor =
                context.getContentResolver().openFileDescriptor(uri, "r");
        assert parcelFileDescriptor != null;
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
        parcelFileDescriptor.close();
}

The reason I am opting for Bitmap from the Uri instead of getting system filename is because the method is fragmented for different versions of Android. Plus, in apps like Google Photos, some photos are shown directly from server and are not stored on the device, so getting filename is not possible. Even if I get the filename, I get Security Exception when trying to use that in my app.
The problem with this approach is, when I get the Bitmap, I don't get the Exif data. But I need the Exif data and attach it to the file that I save in my cache folder so that when I upload the image to server, it gets the image along with Exif so that it can do some further processing. The reason, I need to save it as a file or at least get the file, if it already exists in the system is because Retrofit needs a File object which then gets converted to TypedFile and sent to server using Multipart request.
So, how can I accurately get the Exif information from any kind of image Uri(local or on server) and then save the image along with it's Exif data so that I can send it to the server.


text:
Q: How to add common code (specifically to methods marked WebMethod()) I have some ASP.NET page and webservice WebMethod() methods that I'd like to add some common code to.  For example:
<WebMethod()> _
Public Function AddressLookup(ByVal zipCode As String) As Address
    #If DEBUG Then
        ' Simulate a delay
        System.Threading.Thread.Sleep(2000)
    #End If
    Return New Address()
End Function

I currently have the #If Debug code in all of my WebMethod() methods, but I am thinking there must be a better way to do this without having to actually type the code in.
Is there a way to determine if a request is to a WebMethod in Application_EndRequest so that I can add this delay project wide?
Note that some methods are Page methods and some are web service methods.

A: You can check the request URL in Application_EndRequest to determine whether it is a web method call. E.g. something like this (sorry it's in C#):
protected void Application_EndRequest(Object sender, EventArgs e)
{
  if (Request.Url.ToString().IndexOf("MyWebService.asmx") > 0)
  {
    // Simulate a delay
    System.Threading.Thread.Sleep(2000);
  }
}

A: Encapsulate the #if DEBUG code in a method and mark it with <Conditional("DEBUG")>. This way, you just write a method call in each <WebMethod>. Might be useful.


text:
Q: Why is my timestamp index not being sliced correctly? I have a multi-index dataframe with timestamp index on level 1. Something like that:
                                    close
symbol    timestamp
AAPL      2022-11-29 23:04:57.522  141.15
          2022-11-29 23:04:57.736  141.17
MSFT      2022-11-29 23:05:05.115  180.47
          2022-11-29 23:05:09.560  180.45

I get all timestamps like that:
all_timestamps = df.index.get_level_values(1)

I get this output:
all_timestamps = DatetimeIndex(['2022-11-29 22:57:38.235000', '2022-11-29 22:57:38.652000',
               '2022-11-29 22:57:40.338000', '2022-11-29 22:57:41.340000',
               '2022-11-29 22:57:43.297000', '2022-11-29 22:57:45.340000'],

I want to select all rows within the last 10 seconds:
now = dt.datetime.now(timezone.utc)
ten_sec_ago = datetime.combine(dt.datetime.now(timezone.utc), now.time()) - timedelta(seconds=10)

In that case, that would be all rows after 22:57:40
df_last_10_sec = df[all_timestamps >= ten_sec_ago]

But the problem is I only get the row which have 22:57:40.338000 and 22:57:41.340000 as an index.
The rows that have the indexes 22:57:43.297000 and 22:57:45.340000 are missing.
Why is this not working? Where is my mistake?


text:
Q: Alternative To Adding Multiple Class Items Into Multiple Combo Boxes? C# I have a Fish class, and I'm trying to display the different species in a combo box, the way I'm currently doing it right now is way too tedious, there has to be a better way.
In 'Species1' you can see me attempting to add the same specie in all 4 combo boxes.
I have 4 combo boxes, and I want to display these 9 fish species in all 4 combo boxes, letting the user choose which 4 species he has caught.
            Species1 = new Fish("Angler",5);
            Catch1ComboBox.Items.Add(Species1.Getspecies());
            Catch2ComboBox.Items.Add(Species1.Getspecies());
            Catch3ComboBox.Items.Add(Species1.Getspecies());
            Catch4ComboBox.Items.Add(Species1.Getspecies());
            Catch1ComboBox.SelectedIndex = 0;

            Species2 = new Fish("Cod", 3);
            Catch1ComboBox.Items.Add(Species2.Getspecies());

            Species3 = new Fish("Haddock", 4);
            Catch1ComboBox.Items.Add(Species3.Getspecies());

            Species4 = new Fish("Hake", 1);
            Catch1ComboBox.Items.Add(Species4.Getspecies());

            Species5 = new Fish("Horse Mackerel", 0.5m);
            Catch1ComboBox.Items.Add(Species5.Getspecies());

            Species6 = new Fish("Witches", 3);
            Catch1ComboBox.Items.Add(Species6.Getspecies());

            Species7 = new Fish("Plaice", 8);
            Catch1ComboBox.Items.Add(Species7.Getspecies());

            Species8 = new Fish("Skate and Rays", 1.8m);
            Catch1ComboBox.Items.Add(Species8.Getspecies());

            Species9 = new Fish("Whiting", 7);
            Catch1ComboBox.Items.Add(Species9.Getspecies());

A: Start by putting all your species in a list:
var species = new List<object> {
    new Fish("Angler", 5).GetSpecies(),
    new Fish("Cod", 3).GetSpecies(),
    new Fish("Haddock", 4).GetSpecies(),
    new Fish("Hake", 1).GetSpecies(),
    new Fish("Horse Mackerel", 0.5m).GetSpecies(),
    new Fish("Witches", 3).GetSpecies(),
    new Fish("Plaice", 8).GetSpecies(),
    new Fish("Skate and Rays",1.8m).GetSpecies(),
    new Fish("Whiting", 7).GetSpecies()
}

And then set a copy of the list as the DataSource of all your ComboBox objects:
Catch1ComboBox.DataSource = new BindingList<object>(species);
Catch2ComboBox.DataSource = new BindingList<object>(species);
Catch3ComboBox.DataSource = new BindingList<object>(species);
Catch4ComboBox.DataSource = new BindingList<object>(species);

The use of new BindingList is to prevent all the combo boxes from hooking to the same source and thus being forced to hold the same value.
There is an example of this in the Microsoft documentation.


text:
Q: For loop with jQuery I am creating a survey with a html form with radio buttons.
The user answers 5 questions, and hits submit button that calls a javascript, where I want a loop to get the value from each radio button, and put it all together into one variable.
My problem is, that I cant figure out the correct way to use "i" in the variable called currentVal.
The result I am looking for, should be something like a variable with:   "val1, val5, val3, val1, val4"
Totally new at this, so if you can keep the answer noobfriendly ;)

<form name="form" method="post" action="">
Question 1

<input type="radio" name="1" value="val1"/> Ans1
<input type="radio" name="1" value="val2"/> Ans2
<input type="radio" name="1" value="val3"/> Ans3

Question 2

<input type="radio" name="2" value="val1"/> Ans1
<input type="radio" name="2" value="val2"/> Ans2
<input type="radio" name="2" value="val3"/> Ans3

Question 3

<input type="radio" name="3" value="val1"/> Ans1
<input type="radio" name="3" value="val2"/> Ans2
<input type="radio" name="3" value="val3"/> Ans3

Question 4

<input type="radio" name="4" value="val1"/> Ans1
<input type="radio" name="4" value="val2"/> Ans2
<input type="radio" name="4" value="val3"/> Ans3

Question 5

<input type="radio" name="5" value="val1"/> Ans1
<input type="radio" name="5" value="val2"/> Ans2
<input type="radio" name="5" value="val3"/> Ans3

<input type="button" value="Test" id="check" />
</form>

A: try this...
$('#check').click(function()
        {
            var temp ='';
            $(':radio').each(function(){
                if($(this).is(':checked'))
                  {
                      temp += $(this).val() + ',';
                  }
                });
            alert(temp.slice(0, -1));
        });

A: First, to append all the strings to a commaseperated value, do this:
var result = "";
for (var i = 0; i < 5; i++) {
    if(result.length > 0) {
        result += ",";
    }
    result += $("input:radio[name=" + (i + 1) + "]:checked").val();
}
document.write(result);

The imho best solution would be to add a class (for example 'myForm') to your form and use jQuery's each() function:
var result = "";
$.each($(".myForm input:radio"), function(index, var) {
    if(result.length > 0) {
        result += ",";
    }
    result += var.val();
});
document.write(result);


text:
Q: How to use parameter variable in xslt I am new to xslt so please let me know whats wrong with my syntax here. If I compare with a Constant value of '880.50' I get the desired result. But if I try to do the samething with parameter being passed I get nothing. The code snippet is as under.
<xsl:template name="ShowJourneyLegs" >
  <xsl:param name="TotalFare" />
    <Key4><xsl:value-of select='$TotalFare'/></Key4>
    <JourneyLegKeys><xsl:value-of select="/FareSearchResponse/CompleteItineraryFares/AirFare[@Total = '880.50']/JourneyLegKeys/Key[1]"/></JourneyLegKeys>
     <JourneyLeg><xsl:value-of select="/FareSearchResponse/CompleteItineraryFares/AirFare[@Total = '$TotalFare']/JourneyLegKeys/Key[1]"/></JourneyLeg>
</xsl:template>

A: Remove the apostrophes from around the $TotalFare.  The last XPath should look like this: /FareSearchResponse/CompleteItineraryFares/AirFare[@Total = $TotalFare]/JourneyLegKeys/Key[1]
Inside of an XPath expression, you only use apostrophes for literals.

A:
I am new to xslt so please let me know
  whats wrong with my syntax here.

The problem is in this instruction:
<xsl:value-of select=
      "/FareSearchResponse/CompleteItineraryFares
                              /AirFare[@Total
                                      = '$TotalFare']/JourneyLegKeys/Key[1]"/>

You are not comparing to the value of the $TotalFare but to the string '$TotalFare'.
Solution: Remove the apostrophes that surround $TotalFare.


text:
Q: Interpreting total, direct and indirect effects in SEM I'm running a SEM model with one mediator variable (cognitive ability). Using lavaan I report within the code the indirect and total effects to test them. However, I have some doubts on how to interpret them. Specifically, I have 2 cases in which the indirect effect is not significant, but the direct and total effects are. Is it correct to claim, in this case, that no mediation effect exists?
On the contrary, I have two other cases where the indirect and direct effects are significant, but not the total effect and specifically the indirect has an opposite sign of the direct effect. In this case, how should I interpret them?
I attach the table with the decomposition. The first case refers to neuroticism an agreeableness, while the second to extroversion and openness.

Thanks for your help


text:
Q: error while loading shared libraries: libsandbox.so When I try to run the .out file after compiling the sandbox c program, it gives the following error:
    ./sandbox: error while loading shared libraries: libsandbox.so: cannot open shared object file: No such file or directory

What do I do?

A: The "shared library gone missing" problem is not unique to libsandbox. It so happens to many self-compiled libraries that use GNU autotools for build configuration.
The problem is that GNU autotools prepares the library to go to /usr/local/lib by default (and there are good reasons for this setting to remain default, such as FHS conformance). However, in some Linux distributions -- like Ubuntu and ArchLinux -- the runtime linker (aka. ld.so) does not search /usr/local/lib for shared libraries, unless otherwise specified through ldconfig.
While all other solutions from @anton-kovalenko's answer are viable, it could be more convenient if you just configure libsandbox with options --prefix=/usr and --libdir=/usr/lib (in case you have write access to /usr/lib, of course). Or you can add a new ldconfig entry in /etc/ld.so.conf.d to enable /usr/local/lib for library search at system level.
DISCLAIMER: I am the author of libsandbox.

A: You do the following:

*

*First you find where you copy of libsandbox.so is. It's likely to be somewhere if you successfully linked against it.

*Then you try with env LD_LIBRARY_PATH=/directory/of/your/libsandbox/copy/ ./sandbox and see if it works.

*Then you decide how to deploy your program together with the library, so it works on the target machine. There are many possibilities: gcc -Wl,-rpath='$ORIGIN' for linking would make libsandbox.so loadable from the executable's directory. A wrapper script which takes care of LD_LIBRARY_PATH is another solution. Putting libsandbox.so into a location where dynamic linker can find it is another one.


text:
Q: How should I go about creating a slim version of my web app that does not display photos inline? My (travel related) web app has a lot of photos and many of my Users (but not all) are going to have very slow internet connections. I want to give users the option, for example, to access my web app from https://slim.example.com and in this version, photos will be replaced by a link that says "Click to view Photos - Niagra Falls" and they will open the photos directly from my s3 photobucket as opposed to having those photos inline and I would also want to not display certain ads that might be slow to load and maybe instead of paginating 20 objects, I would only paginate 10 objects, etc.
Can you please give me an idea of how I can go about doing this?
The app is interactive. The users will be creating content, etc. So if I create two separate web apps they will need to communicate with each other and rely on the same models/databases.
EDIT:
def slim_mode
  if request.subdomain == 'slim'
    @slim == true
  end
end

A: In the ApplicationController in a before_action you can determine whether the user in a slim mode (by using request.subdomain) and save it in an instance variable.
You can also define a helper method in ApplicationController which has access to this instance variable and conditionally delegates to image_tag helper or link_to helper.


text:
Q: Bootstrap X-Editable extension for bootstrap table I have this boostrap table that is populated with a .json file generated by ajax/php, all works fine, but im looking to implement X-Editable plugin, to be able to edit this table, since the table is beign populated by this .json I dont really know how to implement .editable() on every cell.
Here is some code
$('#y').on('click',function(){

        ajaxPost("www.example.com/productos/get_all.php", {}, function(result){
            $('#tprueba').bootstrapTable('destroy'); //
            $('#tprueba').bootstrapTable({
                url: 'www.example.com/json/products.jsonp',
                columns: [{
                    field: 'id',
                    title: 'ID Producto'
                }, {
                    field: 'nombre',
                    title: 'Nombre/Descripción'
                }, {
                    field: 'tipo',
                    title: 'Tipo'
                }, {
                    field: 'precio',
                    title: 'Item Price'
                }, ]
            });
            $('#tprueba td').editable();
                });

    });

 function ajaxPost(url, parameters, successCallback) {

          $.ajax({
              type: 'POST',
              url: url,
              data: parameters,
              success: successCallback,
              error: function(xhr, textStatus, errorThrown) {
                  console.log('error');
              }
          });

      }

So what im trying to do is to make all cells editable via the x-editable extension for boostrap table, any suggestions? Thanks in advance..!


text:
Q: Randomizing List with Guid I have a problem about my c# project. In the program I have a list
private static void FillData(List<Question> questions)
    {
        AddQuestion(questions,
            "DotA isimli MOBA oyununun açılımı nedir? ",
            2,
            "Defense of the Arkham",
            "Defence of the Ancients",
            "Defense of the Ancients",
            "Dance of the Architectures"
            );

like that and i wanna make that list randomizely showned in every opening with shuffle. In the example my teacher used
private static void Shuffle(Soru[] array)
    {
        int length = array.Length;
        for (int i = 0; i < length; i++)
        {
            int index = i + ((int) (_random.NextDouble() * (length - i)));
            Soru soru = array[index];
            array[index] = array[i];
            array[i] = soru;
        }

this and i wanna make that in Guid.NewGuid(). Can anyone help me with replacing that with Guid?

(edited from comments) This is what I tried so far:
private static void Shuffle(List<Question> List)
{
    List = List.OrderBy(o => Guid.NewGuid().ToString()).ToList();
    foreach (Question question in ....) { Console.WriteLine(question);
}

but I can't fullfill foreach loop. And yes I want to use Guid instead of random.

A: The problem is that you only modified the input parameter to hold a reference of another List. As it is not passed as reference, in the place where you have called it will hold the reference of the original List.
You could try this way:
    private static void Shuffle(List<Question> List)
    {
        var randomOrderList = List.OrderBy(o => Guid.NewGuid().ToString()).ToList();

        for (int i = 0; i < List.Count; i++)
        {
            List[i] = randomOrderList[i];
        }
    }


text:
Q: Algorithm to generate all Subarrays from initial Array How to generate all subarrays from an initial array?
Let's consider an array: [1,1,1,1].
I would like to generate all possible subarrays (in no particular order).
Expected result:
[1], [1], [1], [1],
[1, 1], [1, 1], [1, 1],
[1, 1, 1], [1, 1, 1],
[1, 1, 1, 1]

My attempt:
List<List<Integer>> list = new ArrayList<>();
generateAllSubArrays(nums, list, 0, 0);

private void generateAllSubArrays(int[] nums, List<List<Integer>> list, int start, int end) {
    if (end == nums.length) {
        List<Integer> l = new ArrayList<>();
        for (int n : nums) {
            l.add(n);
        }
        list.add(l);
    } else if (start > end) {
        generateAllSubArrays(nums, list, 0, end + 1);
    } else {
        List<Integer> l = new ArrayList<>();
        for (int i = start; i < end; i++) {
            l.add(nums[i]);
        }
        list.add(l);
        generateAllSubArrays(nums, list, start + 1, end);
    }
}

I'm getting the following result:
[[], [1], [], [1, 1], [1], [], [1, 1, 1], [1, 1], [1], [], [1, 1, 1, 1]]

Issues:

*

*Some empty lists [] are present in the result (which is undesired). Unfortunately, I failed to understand why they are here.

*Some of the expected values are absent, making the result incorrect.
What did I do wrong, and what should I do in order to get the correct computation?
I believe what I tried is using some sort of recursion, increasing space and time complexity. What would be the algorithm with the best space and time complexity?

A: Iterative implementation
Here's the algorithm for generating all non-empty subarrays of the given array iteratively:

*

*Maintain two nested lists: one for subarrays that are in progress and the resulting list for subarrays that are already built.

*At each iteration step, create a copy of each subarray that is still in progress and add the next element to it. Whilst the original subarray goes into the resulting list intact.

*At the very end of the iteration, add a singleton list containing the next element into the list containing subarrays with we will continue to work, so that on the next iteration step this list would serve as a blueprint for a new subarray and immediately will go into the resulting list.
That's how it can be implemetned:
public static List<List<Integer>> getSubArrays(int[] arr) {
    List<List<Integer>> result = new ArrayList<>();
    List<List<Integer>> inProgress = new ArrayList<>();

    for (int next: arr) {
        List<List<Integer>> proceedWith = new ArrayList<>();

        for (List<Integer> subArray: inProgress) {
            result.add(subArray); // we are done with this subarray

            List<Integer> copy = new ArrayList<>(subArray);
            copy.add(next);
            proceedWith.add(copy); // we should continue working with copy
        }

        proceedWith.add(List.of(next)); // to avoid empty subarrays appear in the result
        inProgress = proceedWith;
    }

    result.addAll(inProgress);

    return result;
}

main()
public static void main(String[] args) {
    int[] arr = {1, 2, 3};

    getSubArrays(arr).forEach(System.out::println);
}

Output:
[1]
[1, 2]
[2]
[1, 2, 3]
[2, 3]
[3]

Recursive implementation
The main logic remains the same:

*

*Every subarray serves as a blueprint for another subarray in case if there are some unused elements left.

*Each single-element subarray produces a new branch of subarrays (if there are some unused elements left).
Base case (the condition when recursion should terminate) - there are no elements to explore, i.e. current index is equal to array's length.
Recursive case:

*

*Create a copy of the subarray received as an argument and add the next element to, original subarray should go into the resulting list.

*Then perform two recursive calls: one with the subarray's copy, another with a single-element subarray (containing the next element).
That's how recursive implementation might look like:
public static List<List<Integer>> getSubArraysRecursively(int[] arr) {

    if (arr.length == 0) return Collections.emptyList();

    List<List<Integer>> result = new ArrayList<>();
    List<Integer> subarray = List.of(arr[0]);
    generateSubArrays(result, subarray, arr, 1);

    return result;
}

private static void generateSubArrays(List<List<Integer>> result,
                                      List<Integer> subarray,
                                      int[] arr, int i) {

    if (i == arr.length) { // base case
        result.add(subarray);
        return;
    }

    // recursive case
    result.add(subarray);

    List<Integer> copy = new ArrayList<>(subarray);
    copy.add(arr[i]);

    generateSubArrays(result, copy, arr, i + 1); // proceed working with the copy

    generateSubArrays(result, List.of(arr[i]), arr, i + 1); // start a new branch of subarrays
}

A: List#subList
You can do it with simple nested loops, a counter and some functions e.g. Math#min, List#subList etc. as shown below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String args[]) {
        int[] arr = { 1, 1, 1, 1 };
        List<Integer> list = Arrays.stream(arr).boxed().toList();
        List<List<Integer>> result = new ArrayList<>();
        int counter = 1;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                List<Integer> sublist = list.subList(j, Math.min(j + counter, arr.length));
                if (sublist.size() == counter)
                    result.add(sublist);
            }
            counter++;
        }

        System.out.println(result);
    }
}

Output:
[[1], [1], [1], [1], [1, 1], [1, 1], [1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1, 1]]


text:
Q: Is it idiomatic to use protobufs as containers within a service? I love gRPC, but I find every step of the protobuf process rather frustrating (particularly in Python). Even though they are structurally similar to data structures composed of lists and dicts, you can't really handle them that way.

*

*You can't assign a list to a repeated field or a dict to a message (also means you can't use  iterators/comprehensions)

*You can't delete field attributes either (but you can del msg.lst[:])

*Unpopulated fields are not "falsey": z.HasField('foo') will be false but not not z.foo is True.

I could go on. Basically, it feels like the folks that wrote the Python implementation of protobuf either don't actually know how to write idiomatic python, or want to actively discourage devs from using protobufs as datastructures within a service and only use them at API boundaries. Which is really unfortunate since they are extremely handy for enforcing types and structures (I aggressively use mypy/hints/autocomplete, **kwargs infuriates me). I've heard (haven't been able to find a source) that you aren't actually supposed to use protos dynamically this because of performance reasons, but I've also heard that Google does precisely this.
That leaves me with a few options:

*

*Deal with un-ergonomic protobuf interfaces, take the possible performance hit

*Use dicts and lists and parse them with json_format at ser/de boundaries (files, gRPC, etc) and lose static type checking

*Parse at boundaries, but use stricter typed data objects. But now I have to maintain these data structures in lock step with the .proto files (I want to write a custom protoc generator but I don't have the time right now).

What's the best approach, given that I like to write rather structured python?


text:
Q: Must a square root of a diagonal matrix with distinct eigenvalues be diagonal? Let $D$ be the diagonal matrix and $A^2=D$
So far I've taken 2 approaches, the first being a direct algebraic approach. For a $2 \times 2$ matrix  this reduces to $$  \left( \begin{matrix}
    a_{11} & a_{12}  \\
    a_{21} & a_{22}  \\
   \end{matrix} \right )^2 =
\left( \begin{matrix}
    a_{11}^2 +a_{21}a_{12} & a_{12}(a_{11} + a_{22})  \\
    a_{21}(a_{11} + a_{22}) & a_{22}^2 +a_{21}a_{12}  \\
   \end{matrix} \right ) =
\left( \begin{matrix}
    d_1 & 0  \\
    0 & d_2  \\
   \end{matrix} \right )$$ where $d_1 \ne d_2$.
From the top right and bottom left squares it's easy to see that $a_{12}=a_{21}=0$ or $a_{11} +a_{22}=0$
If $a_{12}=a_{21}=0$ then, $$d_1=a_{11}^2 +a_{21}a_{12}=a_{22}^2 +a_{21}a_{12}=d_2$$ which means the eigenvalues aren't distinct. Thus $A$ is diagonal.
This proves it when $A$ is $2 \times 2 $.
For  $n \times n $ $A$, with $n$ linearly independent eigenvectors $\mathbf v_1 , ..., \mathbf v_n$ with corresponding eigenvalues $ \lambda_1 , ... , \lambda_n$ such that for $j \ne k$ $ \lambda^2_j \ne \lambda^2_k$
Now $$ D \mathbf v_k =A^2 \mathbf v_k= \lambda^2_k \mathbf v_k$$
thus $\lambda_k^2$ is and eigenvalue of $D$ and $\mathbf v_k$ is the corresponding basis vector, hence the eigenvectors of $A$ are just the standard basis vectors and hence $A$ is diagonal
Is my conjecture that a square root of a diagonal matrix with distinct eigenvalues is diagonal wrong or is there a general proof?


text:
Q: How to speed up binary search using some extra information about range I have a game, which is played in the following manner :

*

*The game starts with displaying me a time in <h>:<m>:<s>:<ms> format

*Next i take a guess less than or equal to the one printed previously and enter it.

*The game displays one of the following based on my time
Platinum
Gold
Stone

*Repeat from step 2.
It is basically like a race , the time is finishing time of the race and i get Platinum for best(lowest) time and stone for the worst(greater) time. Please note the starting time given by the game is largest time required for Stone.
I need to get the Largest time for which i can get Platinum.
So i implimented a binary search algorithm , which halves the interval of time where the required value of time lies. Simply :
low = mid + 1; // if i get platinum
high = mid - 1; // otherwise

Here is the complete code:
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdio.h>

using namespace std;

class times
{
public:
int h,m,s,ms;
int mili;

times ()
{
    h = m=s=ms =0;
    mili = 0;
}

times(int a,int b,int c,int d)
{
    h = a,m=b,s=c,ms=d;
    make();
}

void bake( ) //do reverse of make() for given mili
{
    long int x = mili;
    ms = x%1000;
    x /= 1000;
    s = x%60;
    x/= 60;
    m = x%60;
    x /= 60;

}

void make()  // calc total mili based on cur val of h,m,s and ms
{
    mili = ms;
    mili += s*1000 + m*60*1000 + h*3600*1000;
}

};

int main()
{
int h,m,s,msl;
bool flag;
string str;
    scanf("%d:%d:%d:%d",&h,&m,&s,&msl);

    times mid(h,m,s,msl);
    int low=0,high;
    high = mid.mili;

    while( low < high )
    {
        mid.mili = (high+low)/2;
        mid.bake();
        printf("%d:%02d:%02d:%03d" , mid.h , mid.m,mid.s,mid.ms );
        fflush(stdout); //FLUSH

        cin>>str; // the relic

        if(str=="PLATINUM") // we have more time than req
            {
                low = mid.mili+1;
                flag = true;
            }
        else
            {
                high = mid.mili-1;
                flag = false;
            }

    }
    if(!flag)
        {

            mid.mili = high;
            mid.bake();
            printf("PLATINUM: %d:%02d:%02d:%03d" ,mid.h , mid.m,mid.s,mid.ms);
        }
    else
        {

           mid.mili = low;
            mid.bake();
            printf("PLATINUM: %d:%02d:%02d:%03d" ,mid.h , mid.m,mid.s,mid.ms);
        }

return 0;
}

But this seems to be too slow, i believe it can be done in better way as i think i haven't exploited the fact that Gold must appear between Platinum and Stone .
Or in general , How can i improve binary search if i roughly know how far away from i am from the required value ?
as a Stone is got to be farther away from Platinum than Gold is.

A: If you have no idea about the distribution of the boundaries, it is like you don't know anything about your problem. Further, as there is no penalty for obtaining "stone" or "gold", you can forget about the boundary in between these two and treat the whole setup as "platinum" -- "non platinum".
Again, without an idea then where this single boundary is, you gain nothing. An "idea" here means a statistical distribution (--other than uniform, as that will lead to the usual binary half-interval search). If you have such a distribution, you probably would proceed not by simply halfing the current interval, but always make the cut at the point of its average. In both cases, with and without information, a binary search should give you the lowest number of trials on average.
Further, if one considers the version with a penalty for "stone" (say penalty=2) and "gold" (say penalty=1), and the task is also to get as little penalty while solving the problem, this reminds me of a generalized version of the egg dropping puzzle, see Wikipedia.

A: Edit:
To make it faster for PLATINUM, you have to keep low and high closer to each other. So, you can adjust both of them so that your search can conclude faster or slower as required.
For platinum, you can increase low or decrease high (by 10)
For stone, you can decrease low or increase high (by 10)
For gold, you can manipulate as same as platinum or stone but to different magnitude (by 5).
This is one idea. This magnitude you can decide on the basis of low and high value on the basis of some logic.


text:
Q: Knowing when DataBinding is completed I've used the System.ComponentModel.BindingList as the DataGridView.DataSource in my app. The list is quite large and takes some seconds to be painted on the DataGridView. So, I need to know when data-binding (included painting) procedure finishes to do some stuff. I tried DataBindingComplete event, but it occurs right after setting a value to the DataSource property.
Thanks in advance.

UPDATE:
1. Generating binding-list [ Getting data from Database ] ► ~1 sec
2. Setting it to DataSource [ Binding ] ► ~1 sec (The DataBindingComplete is raised right now.)
3. Painting [ Displaying data in the DataGridView ] ► ~5 sec

A: That was as easy as described!
bool bindingCompleted = false;

void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.DataSource = bindingList1;
}

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    bindingCompleted = true;
}

void dataGridView1_Paint(object sender, PaintEventArgs e)
{
    if (bindingCompleted)
    {
       bindingCompleted = false;

       // do some stuff..
    }
}


text:
Q: Generic index.php with different keywords I have a generic index.php that uses $_GET variables to display different pages, but the same time it displays different keywords for different pages.
We received a Google Adwords Landing page violation notice today, but they don't say what exactly we did wrong, can this feature that I did for the keywords as described like above violate Google's policies and cause them to ban this domain?
Thanks in advance.

A: If you're trying to gain an advantage by tailoring your page's keywords based on a $_GET parameter then yes, I can see why Google will feel you have violated their policies.
If you have different pages (i.e. home, news, events etc.) then give them URLs like www.domain.com/news/, www.domain.com/events/ or `www.domain.com/news.php and www.domain.com/events.php.

A: Ensure that you've followed and stuck to all their guidelines and I'd suggest you also use a .htaccess to differentiate pages:
Landing page and and site policies
Overview of landing page quality


text:
Q: Token.findForRequest is not a function Using loopback v3 with jest and supertest. We are using the token middleware for authorization. In setup and teardown it works properly but when test cases are ran the middleware errors out with "Token.findForRequest is not a function". I tried logging it from the setup/teardown and it is a function but when I log it from tests it shows undefined.
This is how I am setting up supertest.
const request = require('supertest')(require('../../../server/server'));

// tests or setup/teardown code


text:
Q: how to check specific word like "add" and do specific job in C void repl(){
  while(1){
    while(words[a]!='\0'){
       if(isNumeric(words[a])){
          push(words[a]);
       }else if(strcmp(words[a],"add")==0){
          strcpy(value1, pop());
          strcpy(value2, pop());
          sum2 = (int)atoi(value1) + (int)atoi(value2);
          itoa(sum2,sum);
          printf("%d",sum2);
        }
        a++;
        if(words[a] == '\0'){
          printStack();
    }
}

what I need to care about this code is to receive numbers as char temp[] and check them that they are numeric or not.
however I succeed that part of thing, but what I need to solve now is to check if the words[a] is add
then pop last 2 value to calculate sum of them and push back sum into stack.
while I did on this code I received segmentation fault
repl>1 2 3 4
4
3
2
1
repl>add
Segmentation fault

is there any way to solve this?


text:
Q: Vim remove windows characters (convert to unix file format) I copied a vimrc file from a windows box running gvim and tried using it on an OSX box.  Turns out there are a bunch of characters that my unix vim doesn't like in the file.  I assume they're Windows EOL characters or something - doesn't really matter.  Anyway, Is there an easy way to remove them all at once, or convert the file to a unix friendly format?

A: Ah, figured it out.  To convert to a nice unix format, just use :set ff=unix then :w.  See this S/O answer...


text:
Q: The view didn't return an HttpResponse object I was following a tutorial trying to create a registration form. Even though the person recording it was able to create a form I wasn't does anybody see any mistakes in my code? The view didn't return an HttpResponse object.
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib import auth
from django.core.context_processors import csrf
from django.contrib.auth.forms import UserCreationForm

def registerit(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect('/accounts/register_success')
        args = {'form3':UserCreationForm()}
        args.update(csrf(request))
        return render_to_response('register.html', args)

Thank you for your help.

A: You are returning a HttpResponse object only if if request.method == 'POST':
But if the request method is __not POST, you are not returning anything. You probably need to indent the code one level to the left.
def registerit(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
        return HttpResponseRedirect('/accounts/register_success')
    args = {'form3':UserCreationForm()}
    args.update(csrf(request))
    return render_to_response('register.html', args)


text:
Q: Animate on $stateTransition (both exit and enter) I have figured out how to make animations happen by using $stateChangeStart or $stateChangeSuccess in a controller or in my main apps $stateProvider but I can't get it to work as I intend to.
I would like to initiate a solid color bar that wipes over the screen and then wipes back the other direction showing the content. I imagine that when I click a menu link the animation begins(wiping over the current page), once at full-width -> the static page or data-binded page/controller is loaded and rendered and then once that is complete the animation swipes back the other way revealing the new page content.
I need help understanding how to make sure that every time a link is clicked: the first animation happens/ page is loaded/ and the next page revealed.


text:
Q: C: #include error even after placing the header file in the right path I've downloaded SDL_mixer, which plays sound. Even tho I placed the .h file in the include folder, it's still showing me the error:
fatal error: SDL_stdinc.h: No such file or directory

Here's the screenshot below:

A: Thanks to @HolyBlackCat I used a pacman installer instead of putting the header files manually...
I opened MSYS and typed this command to install SDL:
pacman -S mingw-w64-x86_64-pkg-config mingw-w64-x86_64-SDL2
Then I imported it by including SDL by this:
#include <stdio.h>
#include <stdlib.h>

#include <SDL2\SDL_mixer.h>

int main()
{
    return 0;
}

No import errors. Everything worked like a breeze!

A: I think you should look inside the SDL_mixer.h library.  SDL_stdinc.h may be defined in it.


text:
Q: Replicate tables from Oracle to Postgresql using kafka not working I am using two property files one for the source and one for the sink.
I can see both the topic and the consumer created without any problems, not seeing any ERRORs in any log file or the command prompt when I run the connectors decribed above.
Still no tables are created in the destination Postgresql DB.
Trying to replicate tables from Oracle to Postgresql using kafka no confluent installation only the connector jar file.
versions:
kafka_2.12-2.3.0-test
confluent kafka-connect-jdbc-5.2.3.jar
ojdbc7.jar
postgresql-42.2.8.jar

run the following command after starting zookeeper and kafka
bin/connect-standalone.sh config/connect-standalone.properties config/connect-oracle-jdbc-source.properties config/connect-postgresql-jdbc-sink-one-table.properties

source connector
name=test-oracle-jdbc
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=1
connection.url=jdbc:oracle:thin:@xxxxxxx
connection.user=my_user
connection.password=my_password
table.whitelist=LOADER_JOBS
tables="LOADER_JOBS"
mode=timestamp
timestamp.column.name=START_TIME
topic.prefix=test_jdbc_loader_jobs
numeric.mapping=best_fit

sink connector
name=test-postgres-jdbc-one-table
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector
tasks.max=1
max.retries=20
connection.url=jdbc:postgresql://localhost:5432/postgres
connection.user=postgres
connection.password=postgres
topics.regex=test_jdbc_loader_jobs
auto.create=true
auto.evolve=true

A: I had a typo in the sink connector, the property auto.create was misspelled
missing the starting "a" it was uto.create.
It works like a charm


text:
Q: Tracing a border formed by circles Suppose I have some code that draws a few circles. These circles overlap each other in such a way that they form one "group" -- there are no groups of circles completely separated from the rest. For instance:
\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\draw (3,1) circle[radius=1];
\draw (3,2) circle[radius=1.5];
\draw (1,2) circle[radius=0.7];
\draw (0.9,1.2) circle[radius=1.2];
\draw (1,0) circle[radius=0.8];
\end{tikzpicture}
\end{document}

I would like to be able to draw only the "border" formed by these circles, without any of the other lines. It would be like drawing the border of the silhouette formed by all the circles. It would look something like this:

Now for that one, I just painted over the lines in Paint.NET with a brush - if you look closely you can see the imperfections. I would prefer to be able to do it in LaTeX directly. I understand that one option would be to manually calculate the position of the arcs and draw them in. However, it would be nice if there was a way for LaTeX to do the calculations for me and draw the border of the circles, without me having to solve a large amount of intersection equations. Is this possible?

A: Pretty much exactly the same approach as Steven B. Segletes but more (possibly overly) concise. The thickness of the outline is half the value specified in the line width:
\documentclass[tikz,border=5]{standalone}
\begin{document}
\tikz\path [draw, line width=5pt, postaction={fill=white}]
   \foreach \p/\r in {(3,1)/1, (3,2)/1.5, (1,2)/.7, (.9,1.2)/1.2, (1,0)/.8}{
      \p circle [radius=\r]};
\end{document}

And here is a outline fading decoration which makes the inside of the resulting shape transparent. It is mostly proof-of-concept, and as it uses fadings may not work with some viewers. Also it exploits the nonzero rule for filling so its successful use is dependent on the direction of the paths being drawn. The line width is set using the amplitude key.
\documentclass[tikz,border=5]{standalone}
\usetikzlibrary{fadings,decorations,fit}
\pgfdeclaredecoration{outline fading}{final}{
\state{final}{%
  \pgftransformreset%
  \pgfnodealias{@}{current path bounding box}%
  \node [fit=(@), inner sep=\pgfdecorationsegmentamplitude] (@@) {};
  \let\outlinepath=\pgfdecoratedpath
  \pgfinterruptpicture%
    \begin{tikzfadingfrompicture}[name=.]
      \path [line width=\pgfdecorationsegmentamplitude*2, draw=transparent!0,
       postaction={fill=transparent, nonzero rule}]
       \pgfextra{\pgfsetpath\outlinepath};
      \useasboundingbox (@@.south west) (@@.north east);
    \end{tikzfadingfrompicture}%
  \endpgfinterruptpicture%
  \fill [path fading=.,fit fading=false,fading transform={shift={(@@)}}]
   (@@.south west) rectangle (@@.north east);
}}
\begin{document}
\begin{tikzpicture}
 \draw [help lines] (-1,-1) grid (5,5);
  \path [decoration={outline fading, amplitude=2pt}, decorate]
    \foreach \p/\r in {(3,1)/1, (3,2)/1.5, (1,2)/.7, (.9,1.2)/1.2, (1,0)/.8}{
        \p circle [radius=\r]};
\end{tikzpicture}
\end{document}

A: I don't know tikz from a Polynesian mythological icon, so I am sure someone can do better.
I first draw the OP's original figure of black circles, and then redraw the same items as white filled circles of slightly smaller radius.
\documentclass{article}
\usepackage{tikz}
\newcommand\eps{.02}
\begin{document}
\begin{tikzpicture}
\draw (3,1) circle[radius=1];
\draw (3,2) circle[radius=1.5];
\draw (1,2) circle[radius=0.7];
\draw (0.9,1.2) circle[radius=1.2];
\draw (1,0) circle[radius=0.8];
\color{white}
\draw[fill=white] (3,1) circle[radius=1-\eps];
\draw[fill=white] (3,2) circle[radius=1.5-\eps];
\draw[fill=white] (1,2) circle[radius=0.7-\eps];
\draw[fill=white] (0.9,1.2) circle[radius=1.2-\eps];
\draw[fill=white] (1,0) circle[radius=0.8-\eps];
\end{tikzpicture}
\end{document}

I'll add that Ignasi provides good advice in the comments, to use
circle[radius=1cm-.5\pgflinewidth]
rather than my empirically derived value of \eps.  In that way, the result will look good, regardless of any variations in preset line thickness.

A: Here's a solution using the magic of the shadows library:
\documentclass[tikz, border=10pt]{standalone}
\usetikzlibrary{shadows}
\begin{document}
  \begin{tikzpicture}[
        general shadow/.default={shadow scale=1, draw=black, line width=1pt, fill=none, shadow xshift=0pt, shadow yshift=0pt},
        my shadow/.append style={fill=white, general shadow},
      ]
    \path [my shadow]
      (3,1) circle [radius=1]
      (3,2) circle [radius=1.5]
      (1,2) circle [radius=0.7]
      (0.9,1.2) circle [radius=1.2]
      (1,0) circle [radius=0.8];
  \end{tikzpicture}
\end{document}


text:
Q: Use .bib file to add bibliography to markdown document I would like to add references to a github wiki from a .bib file. So I need to produce a markdown file with the embedded bibliography.
I usually convert markdown + .bib to pdf, html or doc using pandoc. For example:
pandoc test.md --bibliography allBib.bib -t markdown -o out.html

Is it possible to output a file that correspond to the input markdown file with the references replaced from the .bib file?
I tried
pandoc Experimental-notes.md --bibliography ../allBib.bib -t markdown -o out.md

but the resulting markdown file is not changed and does not contain the references.

A: From this answer: you need to remove the citations extension from the output format.
pandoc Experimental-notes.md -t markdown-citations -o out.md --bibliography ../allBib.bib


text:
Q: operations about two lists to index a two dimensional array Code:
import numpy as np
a = np.array((1,1,1,1,2))
b = np.array((2,2,2,2,1))
g = np.zeros((3,3),np.int32)
g[a,b] += 1

At the end, this should give an array
array([[0, 0, 0],
       [0, 0, 4],
       [0, 1, 0]])

i.e. g[1, 2] being incremented 4 times, and g[2, 1] being incremented once, but instead it gives
array([[0, 0, 0],
       [0, 0, 1],
       [0, 1, 0]])

The reason that I don't want to use a loop is because I think the vectorization can accelerate the computation. I have two large sets a and b. But I'm not sure whether this operation can exploit performance from vectorization mechanism of Python. and I'm not sure I understand this operation neither. I don't know which key words I should use to search in google, so I put my question here.
If someone can help me understand it, that will be much better.

A: This is what the at method of NumPy ufuncs is for:
numpy.add.at(g, (a, b), 1)

g[a, b] += 1 would perform
temp = g[a, b]
temp += 1
g[a, b] = temp

creating a temporary array with 4 copies of g[1, 2], incrementing each copy separately, and assigning each copy back over g[1, 2] (with the assignments stomping over each other).
numpy.add.at(g, (a, b), 1) instead performs the operation directly on the g array, so it increments g[1, 2] 4 times instead of incrementing 4 copies once each.


text:
Q: React not Detecting my .env File with the Correct REACT_APP_ Prefix For some reason, my React Project will not detect my .env file even though I am using the correct REACT_APP_ prefix. I get an error that states "'REACT_APP_BACKEND_URL' is not defined". The backend portion works fine ("I have other variables in the .env file but I'm hiding them for privacy").
.env
REACT_APP_BACKEND_URL=http://localhost:5000

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
import reportWebVitals from './reportWebVitals';
import axios from 'axios';
import dotenv from 'dotenv';

dotenv.config();

axios.defaults.baseURL = process.env.REACT_APP_BACKEND_URL;
REACT_APP_BACKEND_URL = process.env.REACT_APP_BACKEND_URL;
console.log(REACT_APP_BACKEND_URL)

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

reportWebVitals();

package.json
{
  "name": "full-stack-red-panda",
  "version": "1.0.0",
  "description": "",
  "main": "server.mjs",
  "scripts": {
    "start": "node backend/server.mjs",
    "server": "nodemon backend/server.mjs",
    "client": "npm start --prefix frontend",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "data:import": "node backend/seederScript.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.21.1",
    "dotenv": "^9.0.2",
    "express": "^4.17.1",
    "express-async-handler": "^1.1.4",
    "mongoose": "^5.12.10",
    "react-router-dom": "^5.2.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.14.8",
    "@babel/core": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "concurrently": "^6.1.0",
    "nodemon": "^2.0.7"
  }
}

Thank you for looking over this reader :)
EDIT: Upon further research I have found out that the index.js file can read my PORT variable but not the REACT_APP_BACKEND_URL variable, Odd...


text:
Q: Issue with Printing Data stored in Linked List I'm having some issues when I call the print function for a linked list I created. I created three list objects, stored within them the ints 1,2,3 and then when I run the program, the data is printed out, followed by a hexadecimal number. Here is the output:
10x47e864
20x47e864
30x47e864

Process returned 0 (0x0)   execution time : 0.026 s
Press any key to continue.

Here is the .h file:
#ifndef LIST_H
#define LIST_H

class List
{
    public:
        List();
        void AddNode(int addData);
        void DeleteNode(int delData);
        void PrintList();

    private:
        typedef struct node{
            int data;
            node* next;
        }* nodePtr;

        nodePtr head;
        nodePtr curr;
        nodePtr temp;
};

#endif // LIST_H

Here is the .cpp
#include "List.h"
#include <cstdlib>//for NULL const
#include <iostream>

using namespace std;

int main(){
    List li;

    li.AddNode(1);
    li.AddNode(2);
    li.AddNode(3);
    li.PrintList();
}

List::List()
{
    head = NULL;
    curr = NULL;
    temp=NULL;
}

void List::AddNode(int addData){
    nodePtr n = new node;
    n->next=NULL;
    n->data=addData;

    if(head!=NULL)//if a linked list exists
    {
        curr = head;
        while(curr->next!=NULL){
            //while not at end of list
            curr=curr->next;//advances ptr until last node in list
        }
        curr->next=n;//make n point to last node;
    }

    else{//if list does not exist

        head = n;
    }
}

void List::DeleteNode(int delData){
    nodePtr delPtr = NULL;
    temp = head;
    curr = head;
    while(curr!=NULL && curr->data!= delData){
        //to pass through list
        temp = curr;
        curr = curr->next;//traverse list until delData not found
    }
    if(curr==NULL)//passed through list, delData int not found
    {
        cout<<delData<<" was not in list\n";
        delete delPtr;
    }
    else{
        delPtr = curr;
        curr == curr->next;//patching hole in list
        delete delPtr;
        cout<<"the value "<<delData<<" was deleted\n";
    }
}

void List::PrintList(){
    curr = head;
    while(curr!=NULL){
        cout<<curr->data<<cout<<endl;
        curr=curr->next;//adv the curr ptr
    }
}

Thank you all for the help!

A: You have an incorrect cout statement in the PrintList() remove the second cout from this line, i.e, change
cout<<curr->data<<cout<<endl;

to
cout <<  curr->data << endl;


text:
Q: Построение TreeView в ASP.NET MVC Подскажите пожалуйста что здесь не так:
Это работает:
        @helper BuildMenu(IEnumerable<DepartamentsStructViewModel> data, Decimal? parentId = null)
        {
            var items = data.Where(d => d.DPS_DATESTART < DateTime.Now && d.DPS_DATEFINISH > DateTime.Now && d.DPS_PARID == parentId).OrderBy(i => i.DPS_PREVID);
            if (items.Any())
            {

                    @foreach (var item in items)
                    {

                            <button class="accordion">@item.DPS_NAME</button>
                            @BuildMenu(data, item.DPS_ID)

                    }

            }
        }

А это нет:
    public static MvcHtmlString DepartamentsStruct(this HtmlHelper html, IEnumerable<DepartamentsStructViewModel> data, Decimal? parentId = null)
    {
        var items = data.Where(d => d.DPS_DATESTART < DateTime.Now && d.DPS_DATEFINISH > DateTime.Now && d.DPS_PARID == parentId).OrderBy(i => i.DPS_PREVID);
        TagBuilder ul = new TagBuilder("ul");
        if (items.Any())
        {
            foreach (var item in items)
            {
                TagBuilder li = new TagBuilder("li");
                TagBuilder button = new TagBuilder("button");
                button.AddCssClass("accordion");
                button.SetInnerText(item.DPS_NAME);
                DepartamentsStruct(html, data, item.DPS_ID);
                li.InnerHtml = button.ToString();
                ul.InnerHtml += li.ToString();
            }
        }
        return new MvcHtmlString(ul.ToString());
    }

A: Проблема в том, что вызов DepartamentsStruct(html, data, item.DPS_ID); внутри foreach по сути ни на что не влияет. Вам надо результат этого вызова добавить к li элементу, сразу за кнопкой.
li.InnerHtml += DepartamentsStruct(html, data, item.DPS_ID);


text:
Q: Remove jQuery scripts depending on user agent I am creating a parallax site using the Stellar.js script, however i want to disable this script when being viewed on a tablet or phone.
Is there a way of telling certain devices to call a script and others not? I am able to call different css files depending on the browsing device, but this method won't call then run jQuery scripts?!
{document.write("<link type=\"text\/css\" rel=\"stylesheet\" href=\"css\/style.css\" \/>");
document.write("<script type=\"text\/javascript\" src=\"js\/jquery.stellar.min.js\" ><\/script>"
);}

The full html can be found here
http://bettondesignwork.co.uk/tim/Boutinot/index.txt.
This is my first site i'm attempting to make cross platform, so i apologise if these seem like basic questions.

A: You could wrap an if statement around the script plugin depending on the screen resolution? Or you can use media queries like this example


text:
Q: Search model with time range substitution One can search the model with time range like this:
User.where(updated_at: previous_update..now)

However I need a more complex query:
User.where("updated_at = :updated_at and status != :status",
            updated_at: previous_update..now, status: "employee")

And it turns out that
User.where("updated_at = :updated_at", updated_at: previous_update..now)

doesn't work. Looks like previous_update..now should be somehow translated to sql format before it can be substituted like this. Or maybe there's a better way to express the complex query above?
Edit
I used the Jon's suggestion to chain where filters:
now     = Time.now
updates = User.where(updated_at: previous_update..now)

employee_updates     = updates.where(status: "employee")
non_employee_updates = updates.where('status != :status', status: "employee")

A: You can use:
User.where("updated_at >= :updated_at", updated_at: previous_update)

if you need till now...

A: You can either chain your where queries:
User.where(status: 'employee').where(updated_at: previous_update..now)

Or you can combine them within the same where clause:
User.where(status: 'employee', updated_at: previous_update..now)

With your placeholder conditions, you need to wrap them in curly braces:
User.where('updated_at = :updated_at and status != :status',
           {updated_at: previous_update, status: "employee"})

Although you can't check equality against a date range, so checking updated_at is equal to previous_update..now will fail. You'd need to generate the various conditions for being greater than or equal to the start date and less than or equal to the end date.
Based on that ... I'd probably stick with the non-placeholder format for a simple query like this.


text:
Q: Angular factory $http get data for multiple pages and global variable I'm using Ionic and Angular to build a simple app and have a question about my factory and global variables.
I've a JSON file containing data that every page on the app will need to use. Every page in the app will also need access to the device's lat/long.
Currently, in the controller for each page, I am calling in the data and waiting until the promise has resolved before proceeding with the data. On each page, I am also requesting the lat long in the controller for each page.
This all seems a little wasteful since the data will not change between pages and it seems sensible to set the lat long once globally (and then update this with watchPosition, with a callback to update the called in data when the location changes) rather than having to get the location and set it on each pages $scope.
The data is a small (~20) list of locations, each with a lat long. I want to calculate the distance of each of the locations from the current lat long, updating this in the data as the position changes (the callback from watchPosition). My app has 2 pages. One with a list of locations and one showing the locations on a Google map. Both use the same data.
Should I be storing these on the $rootScope or is this considered bad practice? Am I thinking about this in the wrong way? Should I continue on the current path?
Currently, my controllers look like:
.....
    .controller('HarboursCtrl', function($scope, Harbours) {

  var harboursPromise = Harbours.all();
  $scope.harbours = [];

  $scope.position = 'Trying to find your location...'

  if (navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(position){
      $scope.$apply(function(){
        $scope.position = position.coords.latitude+", "+position.coords.longitude;
      })
    })
  } else {
    $scope.position = "Sorry, we can't get your location";
  }

  harboursPromise.then(function(response){
    console.log('response from controller', response);
    $scope.harbours = response.harbours;
  });
  // $scope.harbours = Harbours.all();

  $scope.remove = function(harbour) {
    Harbours.remove(harbour);
  };
  $scope.getTimes=function(n){
    return new Array(n);
  };
})

.controller('MapCtrl', function($scope, Harbours) {
  $scope.position = 'Trying to find your location...'

  if (navigator.geolocation){
    navigator.geolocation.getCurrentPosition(function(position){
      $scope.$apply(function(){
        $scope.position = position.coords.latitude+", "+position.coords.longitude;
      })
    })
  } else {
    $scope.position = "Sorry, we can't get your location";
  }

  var harboursPromise = Harbours.all();

  harboursPromise.then(function(response){
    console.log('response from controller', response);
    $scope.map = { center: { latitude: 51, longitude: 0 }, zoom: 10 };
    $scope.harbours = [];
    $scope.harbours = response.harbours;
    console.log($scope.map.harbours);
  });

    });
.....

And my service looks like:
angular.module('starter.services', [])

.factory('Harbours', function($http, $q) {
  var harbours = function () {
    var deferred = $q.defer();
    $http({
      method: 'GET',
      url: '../data/harbourData.json'
    }).success(function (data, status, headers, config) {
      deferred.resolve(data);
    }).error(function(data, status, headers, config) {
      deferred.reject(status);
    });
    return deferred.promise;
  }
  return {
    all: harbours,
    get: function(chatId) {
      for (var i = 0; i < harbours.length; i++) {
        if (harbours[i].id === parseInt(chatId)) {
          return harbours[i];
        }
      }
      return null;
    }
  };
});

A: Is your data going to be static? If so, it might be better to write a constant instead of using $http/$q.
angular.module('myModule')
    .constant('locations', {
        firstItem: {
            lat: 'someValue',
            long: 'someValue'
        },
        etc: {}
    });

So you don't have to make a call every time. If the data is dynamic, you can always cache the value in your factory like so:
.factory('myFactory', ['$http', '$q', function($http, $q) {
    var harbors = /* resolved object with data */;
    return {
        all: harbors,
        get: function(name) { return harbors[name]; }
    };
});

tldr; factories are singletons, so any data cached in them should be availbe anywhere in the app without needing to recall the $http service.
* EDIT *
The way I would likely approach this is to create a separate factory to cache any data I need to reuse and write an API factory that helps cache it. So,
.factory('appData', [function() {
    var cache = {};

    return {
        set: function(location, payload) {
            cache[location] = payload;
        },
        get: function(location) {
            return cache[location];
        },
        reset: function() {
            cache = {};
        }
    };
}])
.factory('callAPI', ['$http', '$q', 'appData', function($http, $q, appData) {
    return {
        endpoint: function(url, payload, method, cache) {
            var deferred = $q.defer();
            $http({
                method: method,
                url: url
            }).success(function(data, status, headers, config) {
                deferred.resolve(data);
            }).success(function(data, status, headers, config) {
                deferred.reject(status);
            });
            /** cache must be a string */
            appData.set(cache, deferred.promise);
            return deferred.promise;
        }
    }
}])

This also maintains separation of concerns within your application.


text:
Q: Negative imaginary exponents I was reading this question earlier: Understanding imaginary exponents
In the answer, the answerer says

$A^i=x+iy$
Furthermore, we can write $A^{−i}=x−iy$ for the same $x$ and $y$.

Can someone explain to me why this is true? It kind of makes sense to me but how can we make the leap to just negating the imaginary component?

A: If $A>0$ is real, we define $A^z=e^{z\ln A}$. So
$A^i=e^{i\ln A}=\cos(\ln A)+i\sin(\ln A)$
$A^{-i}=e^{-i\ln A}=\cos(-\ln A)+i\sin(-\ln A)=\cos(-\ln A)-i\sin(\ln A)$

A: Hint:
$$A^i=x+iy$$
$$A^{-i}=\frac{1}{A^{i}}=\frac{1}{x+iy}=\frac{1}{x+iy}\cdot\frac{x-iy}{x-iy}=\frac{x-iy}{x^2+y^2}=x-iy$$
Note :
it says
$$|A^i|=1$$
$$|A^i|=\sqrt{x^2+y^2}=1$$
$$\Rightarrow x^2+y^2=1$$


text:
Q: Passing Data from ViewController to UITableViewController Help me to understand what I am missing please?
Storyboard setup:
ViewController -> TabBarController -> NavigationController which contains a TableViewController
There is a segue with Identifier "startUp" from the ViewController to the TabBarController
The ViewController is the Initial Entry Screen.
The ViewController has a SegmentedControl and a Button
USAGE: User selects one of the segments and presses the button. The view should segue to the TableViewController and replace the NavigationItem.Title with the title from the SegmentedControl segment which was selected.
PROBLEM: The data is not being passed from the ViewController to the TableViewController (and through the TabBarController and NavigationController). I am always ending up with a blank Header Title on the TableViewController. I have walked carefully through a couple dozen 'how-tos' over the past few days both here and other locations on the web using segue and other methods. At this point nothing seems to work and I'm dizzy (and probably missing something really, really basic).
Here is the way the code currently 'sits'
ViewController Code:
import UIKit

class ViewController: UIViewController {
    var someData: String? = ""

    @IBOutlet weak var cpChoice: UISegmentedControl!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func startBut(_ sender: Any) {
        performSegue(withIdentifier: "startUp", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let theIndex = cpChoice.selectedSegmentIndex
        someData = cpChoice.titleForSegment(at: theIndex)

        print(someData!) //outputs correctly to console

        if segue.destination is CheckpointVC
        {
            let vc = segue.destination as? CheckpointVC
            vc?.data = someData!
        }
    }
}

TableViewController Code:
import UIKit

class CheckpointVC: UITableViewController {

    var data: String = ""

    @IBOutlet weak var theHeader: UINavigationItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = data
        //theHeader.title = data
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 0
    }
}

A: Did you breakpoint on the segue to actually check if segue.destination is CheckpointVC? The solution has been right in front of your eyes all along. Since you have setup the viewcontrollers as such...
ViewController -> TabBarController -> NavigationController which contains a TableViewController

Your segue.destination is technically TabBarController unless the segue with identifier startUp leads to TableViewVC.
A short way to solve it is to unwrap the TableVC from your TabBarVC as such:
(tabBarVC.viewControllers[indexOfYourNavVC] as? NavigationController).viewControllers.first as? TableVC)

The longer but cleaner way of doing it is to implement a routing pattern from this blog. Sorry to say that I myself am still learning about this so I can only recommend websites to start with:
https://clean-swift.com/routing-in-clean-swift/

A: Just replace the segue target to a Navigation Controller Which contain your CheckpointVC as a root view controller.

A: The solution

PIECE DEFINITIONS

ViewController.swift
import UIKit

class ViewController: UIViewController {

    var someData: String? = ""

    @IBOutlet weak var cpChoice: UISegmentedControl!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func startBut(_ sender: Any) {
        performSegue(withIdentifier: "startUp", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        //get the string representing the segment chosen and assign it to someData
        let theSegmentChosen = cpChoice.selectedSegmentIndex
        someData = cpChoice.titleForSegment(at: theSegmentChosen)

        let barVC = segue.destination as! UITabBarController //
        let navigationControllerDestination = barVC.viewControllers?[0] as? navVC //the array index [0] indicates the first view controller belonging to the TabBarController
        let firstViewControllerOfNavigationController = navigationControllerDestination?.topViewController as! CheckpointVC
        firstViewControllerOfNavigationController.data = someData!
    }
}

TabBarVC
import UIKit

class TabBarVC: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
}

NavVC
import UIKit

class navVC: UINavigationController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

}

CheckpointVC.swift
import UIKit

class CheckpointVC: UITableViewController {

    //the variable we'll pass the data to from the starting viewcontroller
    var data: String = ""

    @IBOutlet weak var theHeader: UINavigationItem!

    override func viewDidLoad() {
        super.viewDidLoad()
        theHeader.title = data
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 0
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 10
    }
}


text:
Q: HTML form PUT method Because the server side only accepts PUT method, I used method='PUT' in the HTML form. But the browser didn't use method PUT as expected, it's GET. When I set method='POST' it's POST. I don't know why method='PUT' doesn't work. I have tested on Chrome and Firefox.

A: Browsers only support POST and GET, if you need PUT, you have to send the form via post/get and then do the proper PUT request on server-side.
EDIT although, most implementations of XMLHttpRequest support PUT and DELETE.

A: PUT is not recognized and is assimilated to GET.
Most frameworks use a hidden input to obtain PUT or DELETE:
<input type="hidden" name="_method" value="PUT">


text:
Q: Find two different pattern and match count I need to find how many 10 and 01 s are there in the sting. for ex: 10101 in this, two 10 are there and two 01 are there like that use reg ex and find it ? and print the 10 is match 2 times and 01 match the 2 times

A: Use the goatse operator =()=:
$string = '10101';

$a =()= $string =~ m/10/g;
$b =()= $string =~ m/01/g;

print "a: $a\nb: $b\n";

The output is:
a: 2
b: 2

A: This is my solution:
use strict;
use warnings;

my $test = "101010";

my @matches_10 = $test =~ m!10!g;
my @matches_01 = $test =~ m!01!g;
print "matches 10: ", scalar(@matches_10), "\n"; #<-- prints: 3
print "matches 01: ", scalar(@matches_01), "\n"; #<-- prints: 2