text:
Q: Return reference in c++ when use Visual Studio and Codeblocks I am learning C++. I use both visual studio 2015 and codeblocks IDE to code C++. I tried to write a program that returns a reference variable from a function and I get different results(two results) from 2 IDE( Visual Studio 2015 and codeblocks) although I run the same code. I tried writing the following code:
#include <iostream>
using namespace std;
class Demo
{
public:
  int a;
};
//I wrote a function that returns a reference variable
Demo& func()
{
   Demo temp;
   temp.a = 1;
   return temp;
}
int main()
{
  Demo& d = func(); //it error if I run this code on Codeblocks and it run
                   //smoothly if I run it on Visual Studio 2015
  cout<<d.a;
  return 0;
}

I known that it depends on compiler but I want to know
Which is correct in this case?
Thank in advance!

A: First note that what determines program behavior is the compiler rather than the IDE (the program you use to write the code). Other factors are what's currently on disk and what you get as input (e.g. from the user, the Network), the system clock etc.
Now, as @DeiDei correctly points out, you get different behaviour because your func() function returns a reference to a variable that's local to it, and goes out of scope when its execution concludes. Its memory on the stack (or the register associated with it) may become used by other data - and you get no guarantees on what happens when you access it. This is an example of compilable code which has Undefined Behavior when run.
Finally, most compilers will warn you about this - and I'm sure that's true for both compilers used by your IDEs. So you should:

*

*Turn on compiler warning flags.

*Read the warnings and address them.

A: What you're doing is undefined behaviour as you are returning a reference to something that is destroyed when the function goes out of scope. The fact that is works in VS2015 is just chance.
If you want to return a locally created object then either return it by value, or dynamically allocate it and return it as a pointer using either shared_ptr or unique_ptr.

A: It really is simple. When the function func reaches its last line, the life time of temp dies. Whenever you try to access that value, a segmentation fault will occur which tells you that you are trying to access an illegal memory location.
I really can't explain the reason of your success in Visual Studio more than luck.


text:
Q: Performing cumsum on multiple columns based on matching index values I have a dataframe that currently looks like this:
 df = pd.DataFrame(np.array([[1, 2, 'Apples 20pk ABC123', 4, 5], [6, 7,
 'Bananas 20pk ABC123', 9, 0], [1, 2, 'Apples 20pk ABC123', 8, 9]]),
 columns= ['Serial #', 'Branch ID', 'Info', 'Value1', 'Value2'])

               Serial#  Branch ID    Info                  Value1   Value2
        0         1       2          Apples 20pk ABC123       4        5
        1         6       7          Bananas 20pk ABC123      9        0
        2         1       2          Apples 20pk ABC123       8        9

I wanted to groupby the columns: Serial#, Branch ID, and Info to get the cumulative sum of the columns "value1" and "value2". Essentially, it'll only perform "cumsum" if the values under the Serial#, BranchID, and Info columns match.
I thought that I could do something like below, but I'm only getting a df that returns just the index:
df[df.columns.difference(['Serial#', 'Branch ID',
'Info'])].apply(pd.to_numeric, errors='coerce')
# converting other columns(not the three groupby columns) to numeric values

df_cumulative = df.groupby(['Serial#', 'Branch ID',
'Info']).cumsum().add_suffix('_cumulative')

The end result ideally would be:
           Serial#  Branch ID   Info                 Value1_cum  Value2_cum
        0     1       2         Apples 20pk ABC123       4        5
        1     6       7         Bananas 20pk ABC123      9        0
        2     1       2         Apples 20pk ABC123       12       14

Thanks!

A: In your case , you need overwrite the value back to df , then
l=['Serial #', 'Branch ID',
'Info']
df=df.drop(l,1).apply(pd.to_numeric, errors='coerce').combine_first(df)
df=df.set_index(l).groupby(level=[0,1,2]).cumsum().add_suffix('_cumulative').reset_index()
df
df
   Serial #  Branch ID  ... Value1_cumulative  Value2_cumulative
0       1.0        2.0  ...                 4                  5
1       6.0        7.0  ...                 9                  0
2       1.0        2.0  ...                12                 14
[3 rows x 5 columns]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accidentally merged changes made in new branch to a 2 month old git branch, how to get them to the intended branch? So here's what happened

*

*I was working on new changes for my main branch and I was ready to push

*I accidentally merged the new changes with my Beta branch which is 30 commits behind and two months old. I pressed ignore conflicts.

*Since my changes are now merged with the very outdated Beta branch including conflicts, I can't get my project back to the state where it was with the latest branch and my latest changes since I merged it with the wrong branch

*My IDE has no local history, so nothing to save there

I'm also a 1 man team and I am very inexperienced with git besides using GitHub Desktop, which doesn't help very much because I don't know how to use the command line either, which makes most of the questions here confusing for me. How do I get it back to the state where it was before I merged it with the Beta branch, with my new changes included?


text:
Q: Why did the quality of Harry's visions of Voldemort go down? It makes sense to me that the visions Harry sees into Voldemort's mind don't happen all the time. In year five he sees into Voldemort's subconscious pretty often. In year six Voldemort starts using Occlumency to shut him out. In year seven the visions start up again. What doesn't make sense to me is the changes in the quality of the visions that start half-way through The Deathly Hallows.

The only other thing that mattered to him was that his scar had begun to prickle again, although he did all he could to hide this fact from the other two. He sought solitude whenever it happened, but was disappointed by what he saw. The visions he and Voldemort were sharing had changed in quality; they had become blurred, shifting as though they were moving in and out of focus. Harry was just able to make out the indistinct features of an object that looked like a skull, and something like a mountain that was more shadow than substance. Used to images sharp as reality, Harry was disconcerted by the change. He was worried that the connection between himself and Voldemort had been damaged, a connection that he both feared and, whatever he had told Hermione, prized. Somehow Harry connected these unsatisfying, vague images with the destruction of his wand, as if it was the blackthorn wand's fault that he could no longer see into Voldemort's mind as well as before.
(Deathly Hallows, Chapter 22, The Deathly Hallows).

I find it hard to believe that the changes were because of the wand since he sees into Voldemort's mind perfectly clearly later in the book when his wand is still snapped.
Is it because the connection between him and Voldemort is weakening? That's certainly not what other parts of the books suggest. Dumbledore seems to contradict it as an idea:

"Meanwhile, the connection between them grows ever stronger, a parasitic growth."
(Deathly Hallows, Chapter 33, The Prince's Tale).

I'd also rule out the idea that Voldemort was using Occlumency since he didn't seem to be doing that at all during the events of Deathly Hallows.
Has it ever been explained what the cause of the disruption in the clarity of the visions was? Is there an in-universe explanation?

A: It's complicated.
As you point out using the excellent quote in Why did Voldemort stop employing Occlumency against Harry in Deathly Hallows?, Voldemort stopped using Occlumency in the Deathly Hallows.  He stopped using it,though, a year earlier in the Half-Blood Prince.
In the Half-Blood Prince, Voldemort does a very good job with the Occlumency.  However, for the first time in a year, his concentration slips in The Seven Potters.  Harry's scar burns when Voldemort finds out which is the real Potter (a moment of intense euphoria) and when Harry, yet again, slips through his grasp (a moment of intense anger.)  Then, Harry is sent this vision:

"You told me the problem would be solved by using another's
  wand!"
And into his mind burst the vision of an emaciated old man lying
  in rags upon a stone floor, screaming, a horrible, drawn-out scream,
  a scream of unendurable agony. . . .
"No! No! I beg you, I beg you. . . ."

This kind of extreme emotion did not happen in book 6, except maybe when Dumbledore was killed, but Harry would neither have noticed or cared then. In addition, Voldemort is intent on what he's doing--flying around trying to kill Harry Potter--and can't focus on Occlumency.
The other visions he has--times when Voldemort's Occlumency slipped--are all moments of intense feelings, like when he finds out that Harry has the Cup, or when he gets the Elder Wand.  In addition, Voldemort is doing a lot more than he did in book 6--things such as run the Ministry.  You've got to imagine the guy is stressed; who cares if his Occlumency slips once in a while.
But now we get to the meat of the answer.  Why is the quality different?  It has nothing to do with the connection, it is because Voldemort was trying to supress the connection.  While in earlier books he didn't know/care about the visions, now he is trying to suppress them, however the connection is simply too strong.  It's getting stronger, and sometimes Voldy forgets, or loses control, as this excellent answer states.

A: The Dark Lord's Occlumency had partial effect.
Harry's blurry visions into the Dark Lord's mind were likely a result of the Dark Lord's Occlumency being partially successful  - working well enough to block Harry out somewhat, making what he sees blurred and not as clear, but not blocking him out completely. The Dark Lord began using Occlumency to keep Harry out of his mind when he realized the access that Harry had to his thoughts and feelings. When he was most successful at using it, he was able to completely shut his mind, and Harry didn't see into his mind at all.

"So tell me, Harry,' said Dumbledore. 'Your scar … has it been hurting at all?'
Harry raised a hand unconsciously to his forehead and rubbed the lightning-shaped mark.
  'No,' he said, 'and I've been wondering about that. I thought it would be burning all the time now Voldemort's getting so powerful again.'
He glanced up at Dumbledore and saw that he was wearing a satisfied expression.
'I, on the other hand, thought otherwise,' said Dumbledore. 'Lord Voldemort has finally realised the dangerous access to his thoughts and feelings you have been enjoying. It appears that he is now employing Occlumency against you." - Harry Potter and the Half-Blood Prince, Chapter 4 (Horace Slughorn)

Once he started, the Dark Lord keeps trying to use Occlumency to keep Harry from seeing into his mind, with varying levels of success. As J.K. Rowling states in an interview, he was losing control and was sometimes unable to prevent Harry from seeing into his mind.

Maura: How come voldemort was no longer employing occlumency against harry, as he was in the 6th book
J.K. Rowling: He is losing control, and unable to prevent Harry seeing into his mind. The connection between them is never fully understood by Voldemort, who does not know that Harry is a Horcrux. - Bloomsbury Live Chat (July 30, 2007)

At times, the Dark Lord's attempts at Occlumency failed completely, and Harry sees into his mind as clear as ever. When Harry sees into the Dark Lord's mind, but it's blurry, this likely means the Dark Lord's Occlumency against Harry was partially successful. It was keeping Harry out enough where he couldn't see into the Dark Lord's mind clearly, but it had slipped to the point where Harry could still see into his mind somewhat.


text:
Q: Failed to bind Ray Serve HTTP proxy to '127.0.0.1:8000' Started Ray Head node with below command :
ray start \
       --head \
       --port=6379 \
       --object-manager-port=8076 \
     --include-dashboard=true \
       --dashboard-host=0.0.0.0 \
      --dashboard-port=8266

Output:
local node IP: localhost
2021-07-10 20:58:01,607 INFO services.py:1245 -- View the Ray dashboard at http://localhost:8266

--------------------
Ray runtime started.
--------------------

Next steps
  To connect to this Ray runtime from another node, run
    ray start --address='localhost:PORT' --redis-password='xxxx'

  Alternatively, use the following Python code:
    import ray
    ray.init(address='auto', _redis_password='xxxx')

  If connection fails, check your firewall settings and network configuration.

  To terminate the Ray runtime, run
    ray stop

After this wrote a small python code on fastapi:
import ray
from ray import serve

from fastapi import FastAPI

app = FastAPI()

serve_handle = None

@app.on_event("startup") # Code to be run when the server starts.
async def startup_event():
    ray.init(address='auto', _redis_password='xxxx')
    client = serve.start()
    for _ in range(100):
        x.append(1)
    print(x)

But when i run the scrit with command :

uvicorn py_code:app

Got below errors:
ValueError: Failed to bind Ray Serve HTTP proxy to '127.0.0.1:8000'.
Please make sure your http-host and http-port are specified correctly.

Can someone just explain how can i make it work. Thank you


text:
Q: Struggling to take a React webpage screenshot I want to take a screenshot of a React application webpage which opens at the following url when I run my application locally :
http://localhost:3400/someapi/email
I have unsuccessfully tried to take the screenshot with phantom (https://www.npmjs.com/package/phantom)
It failed because phantomJS has no support for ES6.
Also, I could not inject polyfill core.js (https://www.npmjs.com/package/core-js) to
the phantom js page with async await, as I am using Node v.6.9.1.
Any other alternatives/npm packages which makes this process of taking screenshot of a react webpage easy for me?
**Any detailed example would be much appreciated!


text:
Q: Passing argv from route into a script in Node without single quotes I have a project with a landing page which uploads a file into the server; then select some parameters including the uploaded filename and pass them to a script to deploy that file to another server.
I have trouble into passing the filename as parameter for the script. I managed with, inside the upload.js route
var fileName = util.inspect(files.upload.name);
var fileSize = util.inspect(files.upload.size);
process.argv = fileName;

And then calling in deploy.js route
var env = Object.create(process.env);
env.package = process.argv;

so if I try to load a file called try.sql, it passes into the argv array as 'try.sql'. How can I pass it to the script without single quotes?
The script now is very simple:
cp /c/users/alex.buaiscia/Documents/Developing/node/uploads/$package /c/users/alex.buaiscia/Documents/Developing/

so for clarifying, it returns:
stderr: cp: cannot stat "/c/users/alex.buaiscia/Documents/Developing/node/uploads/'try.sql'"

Whole project is on public github
https://github.com/buaiscia/newPKI
Thanks!
---update with current solution----
///// PASSING ARGUMENT FILENAME TO SCRIPT
    var env = Object.create(process.env);
    env.package = process.argv;

    var array1 = env.package;

    console.log(array1.slice(1, -1));
    var array2 = array1.slice(1, -1);

    var command = 'sh c:/users/alex.buaiscia/Documents/Developing/node/scripts/testdeploy.sh ' + array2 + ' >> log.txt'
    console.log(command);
 exec(command, { env: env }, function(error, stdout, stderr) {
        console.log('done')
        console.log('stdout:', stdout);
        console.log('stderr:', stderr);
    });

+ testdeploy.sh
echo $(date) 'prova deployment'
echo $(date) $1
cp /c/users/alex.buaiscia/Documents/Developing/node/uploads/$1 /c/users/alex.buaiscia/Documents/Developing/node/


text:
Q: How to generate a list of random numbers with conditional statements I want to generate a list of numbers with certain conditions.
Eg.
First I generated 10 random numbers between 1 and 20.
M1= RandomReal[{1,20},10]
Now I want to create a tabular list which contain numbers M1>9.
I have tried
M1;While[M1>9];M1;
But the condition doesn't work.

A: SeedRandom[1];
rlist = RandomReal[{1, 20}, 10];

{16.5304, 3.11697, 16.001, 4.56826, 5.58586, 2.24904, 11.3027,
5.39194, 8.52412, 14.309}

Using Select:
Select[rlist,  # > 9 &]

Using Pick:
Pick[rlist, # > 9 & /@ rlist]

Using RegionMember:
First define an implicit region (here you can also use x > 9)
reg = ImplicitRegion[9 < x <= 20, {x}]

Select[rlist, RegionMember[reg, {#}] &]

or use the operator form:
Select[RegionMember[reg, {#}] &][rlist]

Result:

{16.5304, 16.001, 11.3027, 14.309}

Visualization:
NumberLinePlot[{Select[rlist,  # <= 9 &], Select[rlist,  # > 9 &]},
 PlotStyle -> {Black, Red}]

A: One way "to generate a list of numbers with certain conditions" is to create an ImplicitRegion based on your constraints, and then use RandomPoint to sample points in that region.
RandomPoint[
    ImplicitRegion[1<x<20,x]
,10]


text:
Q: nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed in Azure Kubernetes Facing following error while spinning up a pod in Azure kubernetes.
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: Can not modify /etc/nginx/conf.d/default.conf (read-only file system?), exiting
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/11/29 15:53:40 [warn] 1#1: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:2
nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /etc/nginx/nginx.conf:2
2022/11/29 15:53:40 [emerg] 1#1: mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)
nginx: [emerg] mkdir() "/var/cache/nginx/client_temp" failed (13: Permission denied)

DockerFile
FROM node:14.13.1-alpine3.12 as build-stage
WORKDIR /app
COPY . .

FROM nginx:1.19.0-alpine as production-stage
EXPOSE 80
COPY --from=build-stage /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

nginx.conf
server {
  listen 80;
  root  /usr/share/nginx/html;

  location /a {
    index index.html;
    try_files $uri $uri/ /index.html;
    include /etc/nginx/mime.types;
  }

}


text:
Q: How to override the env variables and use the AWS credential file instead in AWS CLI? When using AWS CLI, is there a way I can specify it to use the credential file instead of the values stored in the env variables?
$ aws ec2 describe-instances --profile saml
saml is a profile name inside the credentials file stored in ~/.aws/credentials. I want the AWS CLI to use this credential file by default and not use the ones stored in the env variable. How can I do this?

A: You could use env to unset the variables temporarily:
env --unset=AWS_ACCESS_KEY_ID --unset=AWS_SECRET_ACCESS_KEY aws ec2 describe-instances --profile saml
Since the variables would become unset, aws would use your credentials file instead.

A: Unfortunately, you can't specify priority for the credential file over environment variables.
http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-environment

Environment variables override configuration and credential files and can be useful for scripting or temporarily setting a named profile as the default.

Building what was mentioned in another answer, you could write a wrapper script which would:

*

*Overwrite the environment variables with the export command (which I think would be temporary within the scope of the script only)

*Pass through the command to the aws CLI

*Once completed, the wrapper script would terminate and the environment variables should go back the way they were (I think)

I tested this out with the below (very basic) bash script.  I have an environment variable called $REGION.  Consider the below shell script called "script.sh".
#!/bin/bash
export REGION=""
echo "REGION = "$REGION

Before calling the script, I 'echo $REGION' to prove it does exist:
ubuntu@ip-172-31-24-61:~$ echo $REGION
us-east-1

I then call the script, which nulls out the variable and echo's it showing it's now empty.
ubuntu@ip-172-31-24-61:~$ ./script.sh
REGION =

Once the script terminates, I 'echo $REGION' from the command line and the environment variable is perfectly fine.
ubuntu@ip-172-31-24-61:~$ echo $REGION
us-east-1

If you apply this to your use case, you could write a wrapper script that nulls out the environment variable (by just export AWS_ACCESS_KEY_ID=""), passes all of the command line options through to the AWS CLI.  When the CLI executes, it will not see the environment variables because they have been nulled out in the scope of its execution.
The one thing I don't know how to do is to have a bash script take all of an unknown number of command line arguments and pass them all through to another command.  I don't envision it's difficult, I just don't know how to do it.
But, I'm sure if you create another question, someone can help!
The alternative is, simply DELETE the environment variables if you won't EVER use them.
EDIT 2
I've found out how to make a VERY simple wrapper script that should solve your problem.  Before you implement this, I would strongly suggest looking at the following links to get a better idea of how this works and what other methods may be out there for accomplishing this.  For example, you can use $@ and maybe $* to do this and that may be the more generally accepted way.
#!/bin/bash

params=""
export AWS_ACCESS_KEY_ID=""
export AWS_SECRET_ACCESS_KEY=""

for arg; do
        params="$params $arg"
done

aws $params

The two 'export' links null out the environment variables.  Again, the environment variables will only be nulled out for the life of this wrapper script, because it's being done within the scope of the script and not globally.
Then, the for loop loops through all of the command line arguments you used to run the script, appends them to a string variable and then calls 'aws' with the string holding all of the command line arguments.
http://tldp.org/LDP/abs/html/wrapper.html
Bash: convert command line arguments into array
https://linuxconfig.org/bash-script-how-to-check-number-of-supplied-command-line-arguments
Check number of arguments passed to a Bash script

A: The aws command line doesn't support to specify different configuration file.
What you can do, is make a wrapper, and write to the file ~/.aws/credentials before running the aws command, and deleting the credential file afterwards


text:
Q: How to automatically move a fully downloaded file to a new directory I am using wget to download files a group of files to be ingested in a program. I know I can use the "-P" to send the file to a tmp directory, but I am unsure what the best method is to move the file to the needed destination once fully downloaded. Is rsync the best way to move the files or is another method preferred using scripting?

A: If you intend to move a file if the download is properly done then make a move or if it is not downloaded properly then no need of move, then you can use "LOGICAL AND" between the commands of wget and mv
wget http://mysite.example.com/file1.tgz && mv file1.tgz /new_dest/

A: wget -0 /new_dest/file1.tgz http://mysite.example.com/file1.tgz
/new_dest/file1.tgz will be immediately touched and content downloaded will be piped to it.


text:
Q: how to append file content in velocity in apache camel I am trying to write a simple sample :) on Apache-camel velocity. It is supposed to pick up a file and insert its content in a pre-written text (in .vm file). But it just puts the file name in the place. Here is my scripts.
blueprint.xml
    <camelContext id="_context1" xmlns="http://camel.apache.org/schema/blueprint">
    <route id="_route1">
        <from id="_from1" uri="file:work/velocityFileInput"/>
        <setHeader headerName="receiver" id="_setHeader1">
            <simple>sir</simple>
        </setHeader>
        <setHeader headerName="senderName" id="_setHeader1">
            <simple>Magfa co.</simple>
        </setHeader>
        <setHeader headerName="meetingAddress" id="_setHeader1">
            <simple> Tehran , Iran</simple>
        </setHeader>
        <setHeader headerName="senderPersonalName" id="_setHeader1">
            <simple>Ehsan Zangeneh</simple>
        </setHeader>
        <to id="_to1" uri="velocity:email.vm"/>
        <log message="${body}"></log>
    </route>
</camelContext>

and here is my .vm file content

Hello dear ${headers.receiver},
This letter is sent from ${headers.senderName} to inform you that you are
invited to the meeting in the address of '${headers.meetingAddress}'.
The meeting is about
${in}
Best regards
${headers.senderPersonalName}

instead of ${in}, I also tried ${body} which didnt work.

A: Try to convert the body to string after retrieving content from URI the file.
Might this work, Your route will be like this
<route id="_route1">
 <from id="_from1" uri="file:work/velocityFileInput"/>
 <convertBodyTo id="_convertBodyFileContent" type="java.lang.String"/>
 <setHeader headerName="receiver" id="_setHeader1">
  <simple>sir</simple>
 </setHeader>
 <setHeader headerName="senderName" id="_setHeader1">
  <simple>Magfa co.</simple>
 </setHeader>
 <setHeader headerName="meetingAddress" id="_setHeader1">
   <simple> Tehran , Iran</simple>
 </setHeader>
 <setHeader headerName="senderPersonalName" id="_setHeader1">
  <simple>Ehsan Zangeneh</simple>
 </setHeader>
 <to id="_to1" uri="velocity:email.vm"/>
 <log message="${body}"></log>
</route>

and here is your .vm file content
Hello dear ${headers.receiver},
This letter is sent from ${headers.senderName} to inform you that you are
invited to the meeting in the address of '${headers.meetingAddress}'.
The meeting is about
${body}
Best regards
${headers.senderPersonalName}


text:
Q: div height by percentage doesn't works on Chrome 63 I found style is broken in my website without change on code when I use Chrome. Even though, when I confirmed with Firefox and Safari, it works well and I remember it also worked before I update Chrome.
I tried to figure out what this causes, but could not.
https://jsfiddle.net/3ttou4jv/1/
table {
  height: 100%;
}

td {
  height: 100%;
  background: none repeat scroll 0 0 #565656;
  vertical-align: top;
}

.td-inner {
  height: 100%;
  background: none repeat scroll 0 0 #e1e1e1;
}

Is there mistake on code, or this is the way Chrome's css interpretation?

A: I tested this in Firefox and it looked the same as chrome, I think this will answer the underlying issue though.
When you use a percent you are saying be this much of your parent if the parent is 100px tall and you set the child's height to 100% the child will be 100px.
In this instance .table_root, table's parent, is just taking up as much space as it needs.
You can fix this by setting HTML, body and .table_root to 100%, which will take up 100% of the screen. Alternatively, you can use vh rather than % vh is viewport height 100vh equates to 100% of the viewport height.
Example with %

body, html {
  height: 100%;
  margin: 0;
}

div {
  height: 100%;
  background: tomato;
}

100% example

Example with vh

body {
  margin: 0;
}

div {
  height: 100vh;
  background: tomato;
}

vh example

I hope this helps

A: Setting html/body and .table_root to 100% fixes the issue.
body,html {
  height: 100%;
}

.table_root {
  height: 100%;
}

https://jsfiddle.net/3ttou4jv/2/


text:
Q: Getting Invalid binding path while binding to UI I have a view model in which I have a class called FormItem. There is a form item  property in this class which controls the visibility of a property in form item class
This property is of type Visibility Provider which is another class. I have given below the class definations.
public class FormItem : FormSchema, IDictionary<string, object>, INotifyPropertyChanged
{
    public VisibilityStateProvider VisibilityProvider { get; set; }

    public FormItem()
    {
        VisibilityProvider = new VisibilityStateProvider(this);
    }
}

public class VisibilityStateProvider : IPropertyStateProvider
{
    private FormItem FormItem;

    public VisibilityStateProvider(FormItem formItem)
    {
        FormItem = formItem;
    }

    public bool this[string key]
    {
        get
        {
            return GetVisibilityValue(key);
        }
    }

    private bool GetVisibilityValue(string key)
    {
        bool result=true;
        try
        {
            returns true or false on basis of some computation
            }

        }
        catch (Exception ex)
        {
            return false;
        }
        return result;
    }

    public void NotifyVisibilityChanged(string key)
    {
        var a= $"Item[{key}]";

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(a));
    }

    public event PropertyChangedEventHandler PropertyChanged;

}

Now when we are trying to Bind the Visibility Provider in UWP using following code:
<TextBlock Text="Test" Visibility="{x:Bind ViewModel.FormItem.VisibiltyProvider[key],Convertor = {StaticResource BoolToVisibilityOCnvertor}}"/>

We are getting invalid binding path. Now if we are directly binding to the property we are getting property change as null. I have already asked question on StackOverflow in the following question:
Binding through IDictionary<string,object> property changed event handler is null

A: From your code snippet, it looks like what is needed is to have an observable Dictionary, something like -
public class ObservableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, INotifyCollectionChanged, INotifyPropertyChanged

As far as the binding goes, if you know the key value, you can directly use that in the binding rather than "key". For example, in your case if the TextBlock has to displayed based on the dictionary: {"ShowTextBlock" : true}, then you can bind like this -
<TextBlock Visibility="{Binding Dictionary[ShowTextBlock], Converter={StaticResource BoolToVisConverter}" />


text:
Q: Solidity Syntax error - SENT I'm learning Solidity from official documentation and stack on an exercise where I create simple coin:
pragma solidity ^0.4.20; // should actually be 0.4.21

   contract Coin {
    // The keyword "public" makes those variables
    // readable from outside.
    address public minter;
    mapping (address => uint) public balances;

    // Events allow light clients to react on
    // changes efficiently.
    event Sent(address from, address to, uint amount);

    // This is the constructor whose code is
    // run only when the contract is created.
    function Coin() public {
        minter = msg.sender;
    }

    function mint(address receiver, uint amount) public {
        if (msg.sender != minter) return;
        balances[receiver] += amount;
    }

    function send(address receiver, uint amount) public {
        if (balances[msg.sender] < amount) return;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        emit Sent(msg.sender, receiver, amount);
    }
}

When i try to compile i got a syntax error on the last line:
   emit Sent(msg.sender, receiver, amount);
I tried to compile it in Remix and VS Code but got the same error message.
Can somebody help me pls?

A: The emit keyword was added in Solidity 0.4.21. Prior to that version, you emit events by using just the event name.
Sent(msg.sender, receiver, amount);
You can view the proposal here.


text:
Q: Entity Framework 4 - Calling a Select / Paging Stored Procedure I am just starting out with the Entity Framework 4.0 and ASP.NET MVC 2 and have a few questions regarding the use of stored procedures and paging.
You can map the Insert, Update, and Delete actions to stored procedures and I have already done this. However for my paging to work I need to map the Select action.
Now is the only / best way I can do this by going to my model browser, right clicking on the stored procedure and "Add Function Import" and adding it.
This results in the following code....
var contactFormSubmissions = _entities.ContactFormSubmission_GetContactFormSubmissions(1, 10);

My issue with this is that it adds it to the global entity container at root level rather than the ContactFormSubmission entity like the Insert / Update and Delete actions.
I would rather something like this but through through a stored procedure...
_entities.ContactFormSubmissions.Select<ContactFormSubmission>(string.Empty, pageParam, pageSizeParam);

This way the select is called in the same way as the other actions and I dont end up with lots of functions in the root of the Entity Container which could get unmanagable.
This is a lesser issue as at least its all working currently.
My next question is how to best implement paging using this function.
All of the examples I have seen on how to accomplish paging using MVC and the Entity Framework have used LINQ and IQueryable. Is there a way of using IQueryable with lazy loading and the LINQ functions Skip / Take with a table based function /sproc?
http://blog.wekeroad.com/2007/12/10/aspnet-mvc-pagedlistt/
PS - any examples of paging in MVC with the Entity Framework using SP's would be great!

A: LINQ out of the box will not wrap a stored procedure. Entity Framework functions are the only way to call stored procedures via EF and return an entity. It's understandable, as EF has know what of knowing what parameter to map your paging variables too.
You would/should never do this, but I feel compelled (since nothing is impossible) to say you could write a custom implementation of LINQ for your procedures, but that would be a mountain of work to cleanly wrap a couple of procedures.
Some suggestions:

*

*You can just use linq and skip the stored procedure

*If you stay with EF wrapping a stored procedure via a function, you can alleviate the many function problem by breaking up your model into several contexts

*You can use the connection property of the EF context to call the stored procedure directly, and have a read-only(non-EF attached) viewmodel class to use for display purposes. The id (or other primary key) field would still be the right value to get you to a detail screen or json callback to get an editable version of the real EF object

None of these are perfect, but lots of ways to deal with this.


text:
Q: Is there a way to make a string from ArrayList elements? I want to ask the user for a message:

"Enter a message in the following format: "TO FROM MESSAGE : KEY"

Example input from user:

1 2 hey there how are you : bubble123

Then, I want to have the SecureMessage class return the message. However, I do not know how to create a String of the message part, as the getMessage() message requires a String assigned to it.
The SecureMessage class should not have any mutators in it. All fields in SecureMessage are set from the Message class.
public class SecureMessage {

    private String message;
    private String sourceName;
    private String destName;
    private String key;

    public SecureMessage(String message, String sourceName, String destName, String key){
        this.message = message;
        this.sourceName = sourceName;
        this.destName = destName;
        this.key = key;
    }

    public String getMessage(String key){
        return message + " from SecureMessage class";
    }

    public String getSourceName(){
        return sourceName + " from SecureMessage class";
    }

    public String getDestName(){
        return destName + " from SecureMessage class";
    }
}

import java.util.ArrayList;
import java.util.Scanner;
public class Message {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        String message = "blank", sourceName = "blank", destName = "blank", key = "blank", messageInput, userMessageDetails;
        ArrayList<String> messageInputList = new ArrayList<>();

        System.out.println("Enter message in form TO FROM MESSAGE : KEY \nExample --- 1 2 hey there how are you? : bubble123");
        userMessageDetails = keyboard.nextLine();

        String str = userMessageDetails;
        String[] tokens = str.split(" ");
        for(String s : tokens){
            messageInputList.add(s);
        }

        System.out.println(messageInputList);
        System.out.println("");
        int x = messageInputList.size();

        destName = messageInputList.get(0);
        sourceName = messageInputList.get(1);
        key = messageInputList.get(x-1);
//--this is where I am lost, because I need to pass a string to the SecureMessage getMessage() method---
//        message = ???;
// I found out how to print the items, however this is not a string...
//        for(int i = 2; i <= (x-3); i++){
//            System.out.print(messageInputList.get(i) + " ");
//        }
//------------------------------------------------------------------------------------------------------

        SecureMessage secMsg = new SecureMessage(message, sourceName, destName, key);
        System.out.println(secMsg.getDestName());
        System.out.println(secMsg.getSourceName());
        System.out.println(secMsg.getMessage(key));
    }
}

A: This should do it:
message = String.join(" ", messageInputList.subList(2, x-2));

A: So for what I see, as you split by " ", then you will have your message split between messageInputList.get(2) and messageInputList.get(x-3).
The easy way is having a for and concatenate strings. Something like:
String s_message = "";

for(int i = 2; i <= (x-3); i++){
    s_message = s_message + messageInputList.get(i) + " ";
}

A: message = IntStream.range(2, x - 2)
    .mapToObj(messageInputList::get)
    .collect(Collectors.joining(" "));

This will collect the elements from your messageInputList from index 2 to x-2 and collect them to a singular String message which you can pass to your SecureMessage class.

A: I think it could be much more simplier:
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("Enter message data.");
    System.out.println("-------------------");

    System.out.print("Destination name: ");
    String destName = scan.next();

    System.out.print("Source name: ");
    String sourceName = scan.next();

    System.out.print("Key: ");
    String key = scan.next();

    System.out.println("Message (multi-line, double ENTER to finish):");
    scan.useDelimiter("\n\n\n");
    String message = scan.next().trim();

    SecureMessage secMsg = new SecureMessage(message, sourceName, destName, key);
    System.out.println(secMsg.getDestName());
    System.out.println(secMsg.getSourceName());
    System.out.println(secMsg.getMessage(key));
}


text:
Q: Trouble fetching data from firestore So this is going to be a bit long, but i will try to produce my issue quite simply. The full code of my component is at the end btw.
I am learning to use firebase authentication and adding and retrival of data from the firebase Firestone in react. I have the authentication set up and this gives me a unique ID that I can use to fetch the content I have added in real-time. The function that listen and fetches the data in the code below is listenForMessages() that is inside my useEffect hook. This function fetches the data updates the state in the content hook which then displays the data in my render. The issue is that right now to fetch the data I have to insert the unique ID (jYAhV0xCtmOEJtOPXHirYXkQtju1) directly into doc() inside this listenForMessages(). This is not ideal as I cannot be hardcoding the unique ID. So I switched things a little bit and passed the unique id I got from my app.js as a prop into this component. Thanks to the below bit of code the unique ID is now passed into the below usestate hook, which should then give me the freedom to use id in doc() in this manner= doc(id).
const [ id, setId ] = useState(props);

    useEffect(
        () => {
            setId(props.uid);
        },
        [ props ]
    );

The issue is that it simply doesn't work :/
When i add id into doc() I am met with this messege- FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: a custom Object object
can anyone help? :/
const [ id, setId ] = useState(props);

    useEffect(
        () => {
            setId(props.uid);
        },
        [ props ]
    );

import React, { useState, useEffect } from 'react';
import fire, { db } from '../Config/firebase';

export default function Home(props) {
    function logout() {
        fire.auth().signOut();
    }

    const [ name, setName ] = useState('');
    const [ email, setEmail ] = useState('');
    const [ Content, setContent ] = useState([]);

    const [ id, setId ] = useState(props);

    useEffect(
        () => {
            setId(props.uid);
        },
        [ props ]
    );

    const sendData = () => {
        db
            .collection('users')
            .doc(props.uid)
            .set({
                name,
                email,
                id
            })
            .then(function() {
                console.log('Document successfully written!');
            })
            .catch(function(error) {
                console.error('Error writing document: ', error);
            });
    };

    const listenForMessages = () => {
        db.collection('users').doc('jYAhV0xCtmOEJtOPXHirYXkQtju1').onSnapshot(function(doc) {
            const allMessages = [];
            allMessages.push(doc.data());
            setContent(allMessages);
        });
    };

    useEffect(() => {
        listenForMessages();
    }, []);

    return (

I am home

            <button onClick={logout}>Log out</button>

Enter information

            <form>
                Name
                <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
                Email
                <input type="text" value={email} onChange={(e) => setEmail(e.target.value)} />
            </form>
            <button onClick={sendData}>Send data</button>
            {Content.map((n) => (

                    {n.name} {n.email}

            ))}

    );
}


text:
Q: Pandas: Combining Two DataFrames Horizontally I have two Pandas DataFrames, each with different columns.  I want to basically glue them together horizontally (they each have the same number of rows so this shouldn't be an issue).
There must be a simple way of doing this but I've gone through the docs and concat isn't what I'm looking for (I don't think).
Any ideas?
Thanks!

A: concat is indeed what you're looking for, you just have to pass it a different value for the "axis" argument than the default. Code sample below:
import pandas as pd

df1 = pd.DataFrame({
    'A': [1,2,3,4,5],
    'B': [1,2,3,4,5]
})

df2 = pd.DataFrame({
    'C': [1,2,3,4,5],
    'D': [1,2,3,4,5]
})

df_concat = pd.concat([df1, df2], axis=1)

print(df_concat)

With the result being:
   A  B  C  D
0  1  1  1  1
1  2  2  2  2
2  3  3  3  3
3  4  4  4  4
4  5  5  5  5


text:
Q: JavaScript - Is there a more efficient way to create option elements? I'm trying to create an html select list with 10,000 options. Because of the number, I need it to be as efficient as possible. I've gotten it working, but I think it's pretty inefficient
var select = document.createElement("select");
document.body.appendChild(select);

for (var i = 1; i <= 10000; i++) {
    var option = document.createElement("option");
    var optionText = option.createTextNode("option" + i);
    option.value = "option" + i;
    option.appendChild(optionText);
    select.appendChild(option);
}

I've read that querying the DOM too much can be expensive. Is there a simpler way to do this?

A: I would look at this question from another angle. As a user I can probably tolerate even two second of generating this list (most probably it will take less than 2 seconds even on a bad phone), but forcing me to select an element from a dropdown list of 10k elements - this is an overkill.
I would completely ditch an "creating an option" and will investigate a better (from UI point of view) approach. Something like a select autocomplete (this is just an example).
P.S. If you really really want your users to suffer by scrolling 10k elements, I would suggest take this part select.appendChild(option); out of the loop. Generate all you want to append and append them at once.

A: You can use the Option constructor:

A constructor is provided for creating HTMLOptionElement
  objects (in addition to the factory methods from DOM such as
  createElement()):
Option(text, value, defaultSelected, selected)
When invoked as a constructor, it must return a new
  HTMLOptionElement object (a new option element).
If the first argument is not the empty string, the new object must
  have as its only child a Text node whose data is the value of
  that argument. Otherwise, it must have no children.
If the value argument is present, the new object
  must have a value attribute set with the value of the argument
  as its value.
If the defaultSelected argument is true, the new
  object must have a selected attribute set with no value.
If the selected argument is true, the new object
  must have its selectedness set to true; otherwise the
  selectedness must be set to false, even if the
  defaultSelected argument is true.

In your case,
select.appendChild(new Option("option" + i));

A: Please use innerHTML,if you want high performance
I give you a jsperf below:
http://jsperf.com/js-appendchild/3


text:
Q: Как оценить сложность модели нейронной сети Есть две модели для классификации изображений кошек и собак.
Могу ли я как-нибудь оценить сложность этих моделей?
import tensorflow as tf
import numpy as np
import shutil
import os
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.keras.layers import Activation, Dropout, Flatten, Dense
from tensorflow.python.keras.preprocessing.image import load_img
from tensorflow.python.keras.preprocessing.image import img_to_array

# Каталог с набором данных
data_dir = 'C:/Users/Mi/Desktop/Machine learning/train_cats_vs_dogs/train/'
# Каталог с данными для обучения
train_dir = 'C:/Users/Mi/Desktop/Machine learning/train_cats_vs_dogs/traini/'
# Каталог с данными для проверки
val_dir = 'C:/Users/Mi/Desktop/Machine learning/train_cats_vs_dogs/val/'
# Каталог с данными для тестирования
test_dir = 'C:/Users/Mi/Desktop/Machine learning/train_cats_vs_dogs/test/'
# Часть набора данных для тестирования
test_data_portion = 0.15
# Часть набора данных для проверки
val_data_portion = 0.15
# Количество элементов данных в одном классе
nb_images = 12500
# Размеры изображения
img_width, img_height = 150, 150
# Размерность тензора на основе изображения для входных данных в нейронную сеть
# backend Tensorflow, channels_last
input_shape = (img_width, img_height, 3)
# Количество эпох
epochs = 10
# Размер мини-выборки
batch_size = 16
# Количество изображений для обучения
nb_train_samples = 17500
# Количество изображений для проверки
nb_validation_samples = 3750
# Количество изображений для тестирования
nb_test_samples = 3750
# Архитектура модели нейронной сети
import time
# Время работы блока алгоритма
class Profiler(object):
    def __enter__(self):
        self._startTime = time.time()

    def __exit__(self, type, value, traceback):
        print("Elapsed time: {:.3f} sec".format(time.time() - self._startTime))

# Сверточная нейронная сеть
with Profiler() as p:
    model = Sequential()
    model.add(Conv2D(32, (3, 3), input_shape=input_shape))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(32, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Conv2D(64, (3, 3)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())
    model.add(Dense(64))
    model.add(Activation('relu'))
    model.add(Dropout(0.5))
    model.add(Dense(1))
    model.add(Activation('sigmoid'))
    model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
    datagen = ImageDataGenerator(rescale=1. / 255)
    train_generator = datagen.flow_from_directory(
        train_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='binary')
    val_generator = datagen.flow_from_directory(
        val_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='binary')
    test_generator = datagen.flow_from_directory(
        test_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='binary')
    model.fit_generator(
        train_generator,
        steps_per_epoch=nb_train_samples // batch_size,
        epochs=epochs,
        validation_data=val_generator,
        validation_steps=nb_validation_samples // batch_size)
# Проверка модели на тестовых данных
    scores = model.evaluate_generator(test_generator, nb_test_samples // batch_size)
    print("Точность на тестовых данных: %.2f%%" % (scores[1]*100))

# Полносвязная нейронная сеть
with Profiler() as p:
    model1 = Sequential()
    model1.add(Flatten(input_shape=input_shape))
    model1.add(Dense(32))
    model1.add(Activation('relu'))
    model1.add(Dense(32))
    model1.add(Activation('relu'))
    model1.add(Dense(64))
    model1.add(Activation('relu'))
    model1.add(Dense(64))
    model1.add(Activation('relu'))
    model1.add(Dropout(0.5))
    model1.add(Dense(1))
    model1.add(Activation('sigmoid'))
    model1.compile(loss='binary_crossentropy',
                  optimizer='sgd',
                  metrics=['accuracy'])
    datagen = ImageDataGenerator(rescale=1. / 255)
    train_generator = datagen.flow_from_directory(
        train_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='binary')
    val_generator = datagen.flow_from_directory(
        val_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='binary')
    test_generator = datagen.flow_from_directory(
        test_dir,
        target_size=(img_width, img_height),
        batch_size=batch_size,
        class_mode='binary')
    model1.fit_generator(
        train_generator,
        steps_per_epoch=nb_train_samples // batch_size,
        epochs=epochs,
        validation_data=val_generator,
        validation_steps=nb_validation_samples // batch_size)
    scores = model1.evaluate_generator(test_generator, nb_test_samples // batch_size)
    print("Точность на тестовых данных: %.2f%%" % (scores[1]*100))
# Тестирование модели на картинке пользователя
classes=['dog','cat']
img = load_img('z.jpg', target_size=(150, 150))
# Преобразование картинки в вектор
x =img_to_array(img)
x = x.reshape(1,150,150,3).astype('float')
x /= 255
# Применение к вектору сверточной нейронной сети
with Profiler() as p:
    pred = model.predict(x)
    pred = np.around(pred)
    print(classes[int(pred[0][0])])
# Применение к вектору полносвязной нейронной сети
with Profiler() as p:
    pred1=model1.predict(x)
    pred1 = np.around(pred1)
    print(classes[int(pred1[0][0])])

A: При обучении нейронных сетей расчитываются матрицы весов нейронных связей. Соответственно, одним из самых распространенных способом оценки сложности архитектуры является число параметров, для которых подбираются веса.
Для этого существует метод model.summary:
In [4]: model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d (Conv2D)              (None, 148, 148, 32)      896
_________________________________________________________________
activation (Activation)      (None, 148, 148, 32)      0
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 74, 74, 32)        0
_________________________________________________________________
conv2d_1 (Conv2D)            (None, 72, 72, 32)        9248
_________________________________________________________________
activation_1 (Activation)    (None, 72, 72, 32)        0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 36, 36, 32)        0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 34, 34, 64)        18496
_________________________________________________________________
activation_2 (Activation)    (None, 34, 34, 64)        0
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 17, 17, 64)        0
_________________________________________________________________
flatten (Flatten)            (None, 18496)             0
_________________________________________________________________
dense (Dense)                (None, 64)                1183808
_________________________________________________________________
activation_3 (Activation)    (None, 64)                0
_________________________________________________________________
dropout (Dropout)            (None, 64)                0
_________________________________________________________________
dense_1 (Dense)              (None, 1)                 65
_________________________________________________________________
activation_4 (Activation)    (None, 1)                 0
=================================================================
Total params: 1,212,513
Trainable params: 1,212,513   # <------ NOTE !!!
Non-trainable params: 0

Для второй модели:
In [6]: model1.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
flatten_1 (Flatten)          (None, 67500)             0
_________________________________________________________________
dense_2 (Dense)              (None, 32)                2160032
_________________________________________________________________
activation_5 (Activation)    (None, 32)                0
_________________________________________________________________
dense_3 (Dense)              (None, 32)                1056
_________________________________________________________________
activation_6 (Activation)    (None, 32)                0
_________________________________________________________________
dense_4 (Dense)              (None, 64)                2112
_________________________________________________________________
activation_7 (Activation)    (None, 64)                0
_________________________________________________________________
dense_5 (Dense)              (None, 64)                4160
_________________________________________________________________
activation_8 (Activation)    (None, 64)                0
_________________________________________________________________
dropout_1 (Dropout)          (None, 64)                0
_________________________________________________________________
dense_6 (Dense)              (None, 1)                 65
_________________________________________________________________
activation_9 (Activation)    (None, 1)                 0
=================================================================
Total params: 2,167,425
Trainable params: 2,167,425   # <------ NOTE !!!
Non-trainable params: 0

NOTE: скорость обучения также зависит от функций активации, поэтому такое сравнение будет неточным.

С точки зрения оценки времени обучения, полезнее / точнее будет попытаться обучить НС на небольшом числе эпох - 3-5 эпох, посчитать среднее время обучения одной эпохи и умножить на число эпох, которые вы планируете использовать для обучения.


text:
Q: git-completion.bash displays HEAD only I put original git-completion.bash (from git tarball) and source it from my ~/bash_profile.
When using git branch  is shows only HEAD, e.g.:
piotr@PiotrMBP ~/Projects/X  (master)
$ git co HEAD

but I have:
$ git br -a
  NSXMLDocument
* master
  origin/HEAD
  origin/NSXMLDocument
  origin/master

I haven't modified git-completion.bash in any way, and it works as you can see, while I have branch name in my PS, like in line:
piotr@PiotrMBP ~/Projects/X  (master)
Where should I look for any clues on why branches are not displayed as expected?

A: As mentioned in the comment, the version of Git matters here.
Git1.6.3.1 did enhance branch display for instance (May 2009)


text:
Q: Display result using IF/ELSE in PHP I have a sample code for my problem. what i want to do is if i search for "Helloworld" then i want to inform the user that there's no data matched based from their inputted data. Im thinking if can i use if else statement to do a validation if the data inputted didn't matched any rows and if the inputted data matched some rows. As i visualized the solution for this problem i think this method is the solution but i don't how can i do this. i think the solution is to put if else condition here's my code how i thought about it
if the result of search is not nothing then it will show the result then if nothing then the message will appear "no data matched"
<?php

if(isset($_POST['search']))
{
$valueToSearch = $_POST['valueToSearch'];
// search in all table columns
// using concat mysql function
$query = "SELECT * FROM `users` WHERE CONCAT(`id`, `fname`, `lname`, `age`)     LIKE '%".$valueToSearch."%'";
$search_result = filterTable($query);

}
else {
$query = "SELECT * FROM `users`";
$search_result = filterTable($query);
}

// function to connect and execute the query
function filterTable($query)
{
$connect = mysqli_connect("localhost", "root", "", "test_db");
$filter_Result = mysqli_query($connect, $query);
return $filter_Result;
}

?>

<!DOCTYPE html>

    <title>PHP HTML TABLE DATA SEARCH</title>

    <form action="php_html_table_data_filter.php" method="post">
        <input type="text" name="valueToSearch" placeholder="Value To Search">

        <input type="submit" name="search" value="Filter">

        <?php
         if($result_validation != ''){
         ?>

                Id
                First Name
                Last Name
                Age

            <?php while($row = mysqli_fetch_array($search_result)):?>

                <?php echo $row['id'];?>
                <?php echo $row['fname'];?>
                <?php echo $row['lname'];?>
                <?php echo $row['age'];?>

            <?php endwhile;?>

         <?php
         }else{
         echo "no data matched";
         }
         ?>
    </form>

A: I see no point in displaying the entire table inside the form, you should display it somewhere outside of the form. Having said that, $result_validation variable is undefined, you need to use $search_result in your code.
And as per your question, use mysqli_result::$num_rows to check number of rows returned from the SELECT query.
if($search_result->num_rows){
    // display table
}else{
    echo 'no data matched';
}


text:
Q: Upwork connect with Slack Im pretty new to coding can anyone give me tip how start with project where i want connect notification to slack from upwork when new job appear with certain filter so i can apply?
I just found an api for upwork


text:
Q: PX Transform Routine compile issues I have a transformer routine written in C++ that is set to clear all whitespace and map to a value if the input string is either null or empty. The c++ code compiles and has tested properly, but I am having trouble getting the routine to work in Datastage.
As per instructions, I have copied the exact compiler options that I have in my DS Environment as below.
g++ -c -O -fPIC -Wno-deprecated -m64 -mtune=generic -mcmodel=small BlankToValue.cpp
g++ -shared -m64 BlankToValue.so BlankToValue.o

When testing the routine in a job however I get the following error.
Sequential_File_36,0: Internal Error: (shbuf): iomgr/iomgr.C: 2649
Is there a different set of options I should be using for compilation?
For reference, the c++ code.
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include <locale.h>
#include <locale>

char * BlankToValue(char *InStr, char *RepStr)
{
    if (InStr[0] == '\0')                           // Check for null pointer at first character of input string.
    {
        return RepStr;                              // Return replacement string if true. This is to prevent unnecessary processing.
    } else
    {
        const char* checkstr = InStr;               // Establish copy of inputstring stored in checkstring.
        do {                                        // Start outer loop.
            while (isspace(*checkstr)) {            // Inner loop while current checkstring byte is whitespace.
                ++checkstr;                         // Increment to next checkstring byte.
            }
        } while ((*InStr++ = *checkstr++));         // Set inputstring byte to current checkstring and iterate both. Breaks when either string evaluates to null.
        *InStr = '\0';                              // Set null terminator for input string at current byte location.
        if (InStr[0] == '\0')                       // Checks first character of cleaned input string for null pointer.
        {
            return RepStr;                          // Return replacement string if true.
        } else
        {
            return InStr;                           // Return new input string if false.
        }
    }
}

A: William,
in your DataStage routine definition that points to this custom function, did you select routine type as object (.o file that is compiled into transformer stage at job run time) or a library (a lib.so file that is loaded at job run time but has requirements on library naming convention and that library is located in library path).   Your code above suggested you are creating a *.so file but not prefixed with lib.   Here is an example:
https://www.ibm.com/support/pages/node/403041
Additionally, if the first error in job log was not a library load error but rather was the internal error (shbuf) error, I found a couple of cases where that has occurred in the past with custom routines:

*

*Custom routine involved null handling, as does yours, and began to fail after upgrading to Information Server 8.5 when null handling rules changed in our product.  The changes are explained here:
https://www.ibm.com/support/pages/node/433863
You could test if this is the issue by running the job with new job level environment variable:   APT_TRANSFORM_COMPILE_OLD_NULL_HANDLING=1

*In another case, the shbuf error in custom routine was the result of transformer stage receiving a large record (larger than could be handled by the datatype defined in the custom routine).  Does the job still fail when using only a single sample input record with small values in all string type fields.
Thanks.

A: Also, I noticed that the error is coming from sequential file stage, rather than the transformer stage that is using the custom routine.   Thus may also need to consider what is the output datatype for your custom routine and ensure that it is exiting with valid value that is not too large for the datatype and also not larger that default transport buffer size used between stages (defaults to 128k).

A: After a day or two of multiple attempts to try different compile and code approaches I found the solution to my problem. The below code was throwing a segmentation fault when passed a null column. Which makes sense in retrospect.
if (InStr[0] == '\0')

It has been corrected to the below and now everything works properly.
if ((InStr == NULL) || (InStr[0] == '\0'))


text:
Q: Notation for sampling specific number of samples from distribution I am in the process of writing a scientific paper. At a certain point I want to mention a sampling operation, namely that a variable hereafter called X is a sample obtained from a distribution T. Normally I would show this as X ~ p(T). However in my case it is very important to explicitly mention the size of that sample in order to highlight the fact that I am obtaining exactly k samples from that distribution. I thought of incorporating that in the distribution and write X ~ p(T; k) but this feels wrong: the distribution is the same regardless of how many samples I drew from it. I could also write X ~ p(T) so that |X| = k or perhaps X = {x_i ~ p(T) for i in [0, k)} but I was hoping for a more succinct notation if one exists.

A: This would be a fairly standard way to represent a random sample from $T$: $\mathbf X_k=\{X_1,\dots,X_k\}$ with $X_j\overset{\text{i.i.d.}}{\sim} T$.
None of the other notations you suggested are in common usage and will almost indefinitely confuse a reader unless explicitly defined.
Another slightly more compact option would be:
$\mathbf X_k=\{X_j\}_{j=1}^k$ with $X_j\overset{\text{i.i.d.}}{\sim} T$.


text:
Q: Default launch image is shown when leaving app and going back via URL schemes When I trigger a Facebook share in my app (URL scheme that switches to the Facebook app, and then back again when it's done through another URL scheme associated with my app), I always see the default launch image for a second before I get the UI back.
If I leave the app by pressing the home button and going back I don't get the default launch image. Nor do I get it if I leave the app, open another app and then go back.
Tested on an iPhone 5 with iOS 8. Is this a bug in iOS 8 perhaps? Anybody else encounter this?
EDIT: Oh, and no UIApplicationExitsOnSuspend in the plist, and the app is compiled against iOS 7.


text:
Q: Using props.type with react styled-components hope you are keeping well. I'm stuck as to how to use the following props in my component.
const Container = styled.div`
    background-color: ${props =>
      ({
        primary: 'blue',
        danger: 'red',
        warning: 'yellow'
      })[props.type]
    }
`

and then in my app, I'm trying to do the following
...
<Container primary />
...

But there is no background-color change. I'm doing something stupid. Thanks in advance.

A: Passing props to the Styled component works exactly like in React. What you are doing is passing a prop named primary which has a type boolean.
In your Container, you are checking for type prop which is not there, so all you need to do pass a type prop with either one of this value primary | danger | warning
Code :
<Container type="primary" />

A:

const Container = styled.div`
  /* Background color with inline if/else. 'white' color is a fallbak  */
  background: ${props => props.primary ? "blue" : props.danger ? "red" : props.warning ? "yellow" : "white"  };
  /* You can do the same with other properties */
  color: ${props => props.primary ? "white" : "#222"};

  /* More properties will be applied to all */
  font-size: 1em;
  height: 500px;
  padding: 0.25em 1em;
`;

const App = () => {
  return (

      <Container danger>Hello World!</Container>

  )
}

ReactDOM.render( <App /> , document.getElementById('root'))

See more examples at styled-components Docs

A: The closest solution to what you trying to achieve it using some other property than boolean:
// type = 'primary' / 'danger' / 'warning'
<Container type={type} />;

const TYPE = {
  primary: 'blue',
  danger: 'red',
  warning: 'yellow'
};

const Container = styled.div`
  background-color: ${({ type }) => TYPE[type]};
`;

As for your current code, you can try:
// Only `blue` or `red`
const Container = styled.div`
  background-color: ${({ primary }) => (primary ? 'blue' : 'red')};
`;


text:
Q: How do I put input from InputBox into a cell? I have an InputBox where the user will type in the current month in the format of first three characters + Sale (e.g. JunSale).
I want to return this into a specific cell. This cell already has stuff in it (e.g. MaySale). Once a user types in the input, the cell will now read JunSale not MaySale.
My code gives me an error message:

Compile Error: Method or data member not found

with highlight on the last line of the code.
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sales Calc")
Dim ActSales As Range
Dim pastmthsale As String
Dim currentmthsale As String

With Worksheets("Sales Calc").Cells
    Set ActSales = .Find("Forecast Sales -->>", After:=Range("DH173"), LookIn:=xlValues)
    If Not ActSales Is Nothing Then
        ActSales.Select
    End If
End With
ActiveCell.Offset(rowOffset:=0, ColumnOffset:=-1).Select

pastmthsale = Selection.Value
currentmthsale= Application.InputBox("Enter the Latest Month with Actual Sales Data")
ws.pastmthsale = currentmthsale

This is the code I have now. The error message I get is

Application-defined or object-defined error.

Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Sales Calc")
Dim ActSales As Range

With Worksheets("Sales Calc").Cells
    Set ActSales = .Find("Forecast Sales -->>", After:=Range("DH173"), LookIn:=xlValues)
    If Not ActSales Is Nothing Then
        ActSales.Select
    End If
End With

ActiveCell.Offset(rowOffset:=0, ColumnOffset:=-1).Select

Range(ActiveCell) = Application.InputBox("Enter the Latest Month with Actual Sales Data")

A: Just use this method - no Range() needed when referencing activecell.
ActiveCell = Application.InputBox("Enter the Latest Month with Actual Sales Data")


text:
Q: JSON error deserialize With the following REST service response:
"[{\"field1\":\"Eva\",\"field2\":\"29\",\"field3\":false},{\"field1\":\"Karen\",\"field2\":\"32\",\"field3\":false}]"

I´m getting an error when trying to deserialize it (ERROR:  line 1, position 117)
public class Person
{
   public string field1 { get; set; }
   public string field2 { get; set; }
   public string field3 { get; set; }
}

Task<string> jsonString = response.Content.ReadAsStringAsync();
jsonString.Wait();
var model = JsonConvert.DeserializeObject<List<Person>>(jsonString.Result);

Could help me somebody please?
Thanks in advance.

A: You need to use JToken to parse your response. After then, you should be able to deserialize it. Here below is a working example:
public class Person
{
   public string field1 { get; set; }
   public string field2 { get; set; }
   public string field3 { get; set; }
}

var response = "[{\"field1\":\"Eva\",\"field2\":\"29\",\"field3\":false},{\"field1\":\"Karen\",\"field2\":\"32\",\"field3\":false}]";
JToken json = JToken.Parse(response);
var model = json.ToObject<List<Person>>();

A: "field3" has to be bool not string.
public bool field3 { get; set; }

If that does not work, try to use this structure, since it seems to be the right structure based on the json that you have provided:
public class Rootobject
{
    public Person[] Person { get; set; }
}

public class Person
{
    public string field1 { get; set; }
    public string field2 { get; set; }
    public bool field3 { get; set; }
}

A: Thanks everybody for your responses. Finally, the problem was related with the kind of type used on sending the info in the REST service: string instead of stream. Now works great! If can helps anybody, this is the code on server side:
JsonString = JsonConvert.SerializeObject(ds.Tables[0], Formatting.Indented);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
                return new MemoryStream(Encoding.UTF8.GetBytes(JsonString));

@Oluwafemi is really needed using?:
JToken json = JToken.Parse(response);

Thanks.


text:
Q: How to fetch below output using SQL? Table

output:
reference output in color

enter image description here
How to fetch the output when I pass ID from cycleTable to get the cyc_id and then pass cyc_id to LineTable to get LN_ID.
I want to get all the LN_ID for the available LN_NO with biggest cyc_id.

A: The following query produces the output you want.
SELECT LN_ID
FROM table
WHERE CYC_ID =
           (SELECT CYC_ID
           FROM table
           WHERE LN_ID = (SELECT MAX(LN_ID) FROM table))

A: You explained it; what remains to be done is to translate words into several lines of code. This is one option:
Sample data:
SQL> with
  2  cycle_table (cyc_id, id) as
  3    (select 1002001, 1000000 from dual union all
  4     select 1002002, 1000000 from dual union all
  5     select 1002003, 1000001 from dual union all
  6     select 1002004, 1000001 from dual
  7    ),
  8  line_table (ln_id, cyc_id, ln_no) as
  9    (select 1002009, 1002004, 1 from dual union all
 10     select 1002004, 1002002, 1 from dual union all
 11     select 1002006, 1002003, 1 from dual union all
 12     select 1002005, 1002002, 1 from dual union all
 13     select 1002002, 1002001, 1 from dual union all
 14     select 1002010, 1002004, 1 from dual union all
 15     select 1002007, 1002003, 2 from dual union all
 16     select 1002034, 1002002, 2 from dual union all
 17     select 1002033, 1002002, 2 from dual union all
 18     select 1002003, 1002001, 2 from dual union all
 19     select 1002012, 1002004, 2 from dual union all
 20     select 1002011, 1002004, 2 from dual union all
 21     select 1002013, 1002004, 3 from dual union all
 22     select 1002014, 1002004, 3 from dual union all
 23     select 1002008, 1002003, 3 from dual
 24    )

Query you might be interested in:
 25  --
 26  select l.ln_id
 27  from line_table l
 28  where l.cyc_id in (select max(c.cyc_id)
 29                     from cycle_table c
 30                     where c.id = &par_id
 31                    );
Enter value for par_id: 1000000

     LN_ID
----------
   1002004
   1002005
   1002034
   1002033

SQL> /
Enter value for par_id: 1000001

     LN_ID
----------
   1002009
   1002010
   1002012
   1002011
   1002013
   1002014

6 rows selected.

SQL>


text:
Q: Oracle SQL - A count that excludes completely a Key with the if not equal statement Ok here goes:
MyTableName

KEY      Value1
1        ABC
1        DEF
1        GHI
2        ABC
2        DEF
2        YUI

I have a child table that is linked via a Key (stated above)
I need to find records, linked to the parent table (i have no issues with my join) where value 1 meets conditions and does not meet certain conditions.
So, for my Example, I want to retrieve the value '1' from the "KEY" above, because my need is where value 1 = 'ABC' or value 1 = 'DEF' but value 1 != YUI,
so I would want '1' to come back, but not 2
    SELECT KEY, count(*)
    FROM MyTableName
    WHERE (value1 = 'ABC'
    OR value1 = 'DEF')
    AND value1 != 'YUI'
    GROUP BY KEY
    HAVING count(KEY) = 2

The above statement, find both Key 1 and 2, where I need it only to find Key 1.
Can anyone help?

A: Use the HAVING clause with conditional counts:
select key
from mytablename
group by key
having count(case when value1 in ('ABC','DEF') then 1 end) > 0
   and count(case when value1 = 'YUI' then 1 end) = 0;

(You can add where value1 in ('ABC','DEF','YUI'), which may speed up the query, because you are not interested in rows containing other values.)
(Some people prefer to include an explicit else branch: count(case when value1 = 'YUI' then 1 else null end) and others prefer sum(case when value1 = 'YUI' then 1 else 0 end). That's a matter of personal preference.)


text:
Q: Pandas Average If in Python : Combining groupby mean with conditional statement I've looked through the forums and can't seem to figure this out. I have the following data. I assume the answer lies in the "groupby" function but I can't seem to work it out.
Date     Hour    Value   3DAverage
1/1       1       57      53.33
1/1       2       43      42.33
1/1       3       44      45.33
1/2       1       51      ...
1/2       2       40      ...
1/2       3       42      ...
1/3       1       56      ...
1/3       2       42
1/3       3       48
1/4       1       53
1/4       2       45
1/4       3       46
1/5       1       56
1/5       2       46
1/5       3       48
1/5       4       64 *
1/6       1       50
1/6       2       41
1/6       3       42
1/7       1       57
1/7       2       43
1/7       3       45
1/8       1       58
1/8       2       49
1/8       3       41
1/9       1       53
1/9       2       46
1/9       3       47
1/10      1       58
1/10      2       49
1/10      3       40

What I am trying to do is add the "3DAverage" column. I would like this column to produce an average of the "Value" column for the PRIOR 3 corresponding hour values. I want to fill this column down for the entire series. For example, the value 53.33 is an average of the value for hour 1 on 1/2, 1/3, and 1/4. I would like this to continue down the column using only the prior 3 values for each "HourValue".
Also, please note that there are instances such as 1/5 hour 4. Not all dates have the same number of hours, so I am looking for the last 3 hour values for dates in which those hours exist.
I hope that makes sense. Thanks so much in advance for your help !

A: You can try rolling mean
df['3D Average'] = df.iloc[::-1].groupby('Hour').Value.rolling(window = 3).mean()\
.shift().sort_index(level = 1).values

A: You can groupby on Date column and do the following:
df['3DAverage'] = df['Hour'].map(df.groupby('Hour').apply(lambda x: x.loc[x['Date'].isin(['1/2','1/3','1/4']),'Value'].mean()))

df.head(6)

   Date   Hour Value 3DAverage
0   1/1     1   57   53.333333
1   1/1     2   43   42.333333
2   1/1     3   44   45.333333
3   1/2     1   51   53.333333
4   1/2     2   40   42.333333
5   1/2     3   42   45.333333


text:
Q: JavaScript how to discover asynchronous functions at breakpoint I have strange problem in my work with JavaScript, where script doesn't work in Chrome real-time, but works if I break and continue at specific line.
The case: I have search box where I can search for items with specific name, and options to filter results by manufacture. Everything works fine in IE and Mozilla, but in new version of Chrome choosing a filter will empty the whole results after half second delay.
Code relies on JQuery and is too complex to post here (I haven't coded it and don't understand it well either), but I decided to ask if this kind of problem is specific to some known issue.
Here's an interesting fact. If I set at following line of code
this.$el.find("#resultbox").show();
and continue execution after breaking, everything seems to work normal. To me it seems like an asynchronous problem, where former method tries to do something asynchronously with some unknown function, and causes the problem if it's executed before that asynchronous function. Could this be the source of issue and how to track it in google chrome?


text:
Q: Framework, css or theme to develop html that works for Windows Mobile 6.1 Internet Explorer I need to develop a simple web interface for a Motorola Scanner running Windows Mobile 6.1 to scan in products into an inventory system I am developing using ASP.NET MVC 4.5.
Is there any framework, theme, css, or anything out there to write html that works for Windows Mobile 6.1 Internet Explorer?. Nothing standard appears to work, most css properties don't show up properly and doing the simplest thing is just a nightmare because I don't even know why is not working.


text:
Q: Update stocks of existing product size on Add What's wrong with my code? The product stocks is updating but after I pressed the Add button and reload the page, the product that I added a stocks will be gone.
Here's my query:
if(isset($_POST['product_id'])) {
    $product_price = mysqli_real_escape_string($db_conn, $_POST['product_price']);
    $product_stocks = mysqli_real_escape_string($db_conn, $_POST['product_stocks']);
    $product_size =mysqli_real_escape_string($db_conn, $_POST['product_size']);
    $product_id = mysqli_real_escape_string($db_conn, $_POST['product_id']);

    $search_query = "SELECT * FROM tblproduct_extension WHERE product_size = '$product_size'";
    $query = mysqli_query($db_conn, $search_query);
    $exists = mysqli_num_rows($query);

    if($exists) {
        $update_query = "UPDATE tblproduct_extension SET product_stocks = product_stocks + $product_stocks WHERE product_id = '$product_id' AND product_size = '$product_size'";
        $query = mysqli_query($db_conn, $update_query);
    } else {
        $insert_query = "INSERT INTO tblproduct_extension (product_stocks, product_price, product_size, product_id)VALUES('$product_stocks', '$product_price', '$product_size', '$product_id')";
        $query = mysqli_query($db_conn, $insert_query);
    }
}

Ajax
//Show modal for adding size, price and stocks
function add_product_extension() {
    $('#product_add_extension').click(function(){
        var product_id = $('#product_id').val();
        var product_price = $('#product_price').val();
        var product_stocks = $('#product_stocks').val();
        var product_size = $('#product_size').val();
        $.ajax({
            type: 'POST',
            url: '../admin/class.php',
            data: {product_id:product_id,product_price:product_price,product_stocks:product_stocks,
            product_size:product_size},
            success:function(data) {
                $('#addSize').modal('hide');
                show_products();
            }
        });
    });
}

A: In select query you also have to specify product id. So for product you are searching, you will get correct result
So change
$search_query = "SELECT * FROM tblproduct_extension WHERE product_size = '$product_size'";

to
$search_query = "SELECT * FROM tblproduct_extension WHERE product_id = '$product_id' AND product_size = '$product_size'";


text:
Q: What does "???" stand for in Scala lang? Actually, I have several Qs regarding to this code snippet:

*

*Does '???' cause this exception?

*What could be assigned instead of '???' ?

*What does '???' stand for?

object InfixTypesHard2 extends App {
  val x0: Int --- String --- Boolean = ???
}

class ---[T, V](t: T, v: V)

Stacktrace:
Exception in thread "main" scala.NotImplementedError: an implementation is missing
    at scala.Predef$.$qmark$qmark$qmark(Predef.scala:344)
    at section3_OOP_operatorOverloading.InfixTypesHard2$.delayedEndpoint$section3_OOP_operatorOverloading$InfixTypesHard2$1(InfixTypesHard2.scala:5)
    at section3_OOP_operatorOverloading.InfixTypesHard2$delayedInit$body.apply(InfixTypesHard2.scala:3)
    at scala.Function0.apply$mcV$sp(Function0.scala:39)
    at scala.Function0.apply$mcV$sp$(Function0.scala:39)
    at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:17)
    at scala.App.$anonfun$main$1(App.scala:76)
    at scala.App.$anonfun$main$1$adapted(App.scala:76)
    at scala.collection.IterableOnceOps.foreach(IterableOnce.scala:563)
    at scala.collection.IterableOnceOps.foreach$(IterableOnce.scala:561)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:919)
    at scala.App.main(App.scala:76)
    at scala.App.main$(App.scala:74)
    at section3_OOP_operatorOverloading.InfixTypesHard2$.main(InfixTypesHard2.scala:3)
    at section3_OOP_operatorOverloading.InfixTypesHard2.main(InfixTypesHard2.scala)

A: Is just a method in Predef nothing special about it from the language point of view.
As you can see the implementation is just throwing a new NotImplementedError.
The idea of that method is that you can use it as a filler to "implement" any method, and the idea of the fancy name was that it could be noticed easily since the idea is that any usage of ??? should be temporary and fixed latter.
And if you wonder why it can be used in any place, it is because ??? itself is of type Nothing; this because the act of throwing an exception has such type. And since Nothing is the subtype of all types (also known as the bottom type) it can always be used due Liskov.

What could be assigned instead of '???' ?

Something of type: Int --- String --- Boolean; which is just a weird tuple re-implementation.
// For example:
new ---(new ---(1, "text"), false)
// Thanks to Jasper Moeys for providing the right syntax.

I guess this is some homework, no idea what you were asked to do here.
Or maybe, the whole idea of the snippet is to show that you can use types as infix when they have two type parameters.


text:
Q: Using Serial port control in another class I have a Win-form application. I need to communicate with serial port from class.
For Example:
serialPort1.ReadExisting()

I don't know how to define serialPort1 without to insert component to form.
Can maybe I define it like reference, or?
Thanx

A: Simply import the System.IO.Ports namespace and then declare the serial port object:
SerialPort serialPort1 = new SerialPort();

Declare this where you need to use it but most likely as a global variable in the class
example:
http://msdn.microsoft.com/en-gb/library/system.io.ports.serialport.aspx


text:
Q: Options to drag and drop with synergy KVM switch? I am effectively using Synergy between Windows/Linux/Android
However, I am trying to find a way to drag and drop.
I know I can "just network a drive, and modify a [send to], but honestly, when it comes to rapid work - easier saves my patience.
The Server is Windows 8.1, (I can change this if I must, but I rather not)
The Clients in question are Windows XP+, Linux and the Android I am not worried about.
please advise


text:
Q: Text box inside a grid view not showing data I am adding a text box inside a grid view.
When a user clicks the add button a new text box is created.
I am getting all data from text boxes, but when I add data the text boxes are showing nothing
          private void SetPreviousTids(DataTable dt)
          {
             if (ViewState["TidTable"] != null)
               {
                  if (dt.Rows.Count > 0)
                  {
                 for (int i = 0; i < dt.Rows.Count; i++)
            {

               TextBox Tid =  (TextBox)GridView1.Rows[i].Cells[0].FindControl("Tid");
               Response.Write(Tid.Text.ToString());
               Tid.Text = "hello";// text not showing on text box
            }
         }
     }
 }

ASPX code here
    <asp:GridView ID="GridView1" runat="server" Visible="true">
    <Columns>
        <asp:TemplateField HeaderText="TID">
            <ItemTemplate>
                <asp:TextBox ID="Tid" runat="server"></asp:TextBox>
            </ItemTemplate>
            <FooterTemplate>
                <asp:Button ID="ButtonAdd" runat="server" Text="+" OnClick="Add_Tid" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

A: You'll want something like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TextBox myTextBox = (TextBox)(e.Row.Cells[1].FindControl("Tid"));
        myTextBox.Text == "hello";
    }
 }

A: When using Templates such as <asp:TemplateField> to define a column for GridView, such Columns can't be accessed using Cells property.
However when using bound fields <asp:BoundField .. /> to define Columns for GridView you can use the Cells property to access columns.
So, Change
TextBox Tid =  (TextBox)GridView1.Rows[i].Cells[0].FindControl("Tid");

to
TextBox Tid =  (TextBox)GridView1.Rows[i].FindControl("Tid");

A: I believe this should work!
<asp:GridView ID="grdList" runat="server" Visible="true" onrowcommand="grdList_RowCommandEvent">
    <Columns>
        <asp:TemplateField HeaderText="TID">
            <ItemTemplate>
                <asp:TextBox ID="Tid" runat="server" Text='<%# Eval("TextboxInfor") >%'></asp:TextBox>
            </ItemTemplate>
            <FooterTemplate>
                <asp:Button ID="ButtonAdd" runat="server" Text="+" CommandName="AddNew" />
            </FooterTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

And Code behind should look like:
namespace Demo
{
    public partial class Default : System.Web.UI.Page
    {
        DataTable _tableData;
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                _tableData=new DataTable();
                _tableData.Columns.Add("TextboxInfor");
                ViewState["TidTable"]=_tableData;
            }
        }
        protected void grdList_RowCommandEvent(object sender, GridViewCommandEventArgs e)
        {
            if(e.CommandName.Equlas("AddNew"))
            {
                _tableData= ViewState["TidTable"] as DataTable;
                for (int i = 0; i < grdList.Rows.Count; i++)
                {
                    var Tid= gvMandiStatistics.Rows[0].Cells[0].FindControl("Tid") as TextBox;
                    _tableData.Rows[i]["TextboxInfor"]=Tid.Text;
                }
                var dr= _tableData.NewRow();
                dr["TextboxInfor"]=string.Empty;
                _tableData.Rows.Add(dr);
            }
        }
        private void BindGrid()
        {
            _tableData= ViewState["TidTable"] as DataTable;
            grdList.DataSource=_tableData;
            grdList.DataBind();
        }
    }
}

Forgive if there are some typo mistakes as entire code is written in NOTEPAD :D


text:
Q: Does TPU Accelerators are supported in Unified AI Platform I have some custom training jobs in AI Platform using GPUs & TPUs and trying to run the same jobs in unified AI platform but not able to find the TPU machines.

A: *

*Looking into the AI Platform Unified documentation able to find GPUs
configurations but nothing about TPUs. Looks like TPU's are not
supported by unified.

*You can look into the AI Platform Unified release notes updates
to check update about this feature


text:
Q: Interface between a web based tool and Matlab I am designing a web based tool using HTML, CSS and Javascript.
I am able to export Data from OpenStreetMap as an .OSM file using this query:
var osmURL = 'http://api.openstreetmap.org/api/0.6/map?bbox='+a+','+b+','+c+','+d;
window.location.assign(osmURL);

After downloading this osm file I want to send it to Matlab and do some computational algorithms on it. How can I save this downloaded file in a place then send it to Matlab and run the needed m.files..
How can I do this link between the Web based tool and Matlab? is it feasible ?
Thanks a lot for your help.

A: Not sure why you need this functionality at a webfrontend side, but this will help, as it's not OSM dependand: How can JavaScript save to a local file?
Please be aware that you trigger on the official read/write API that is designed esp. for interacting/editing/... OSM data and not for bulk downloading
http://wiki.openstreetmap.org/wiki/API_usage_policy
You might want to use the OverpassAPI or a local OSM Planet dump/extract instead to do your processing.


text:
Q: Call to undefined method CI_Form_validation::ci_form_validation() while extending the class in CodeIgniter I want to add some custom validation functions for my project. I'm using CI 2.0.2. I followed all the steps described at www.michaelwales.com/2010/02/basic-pattern-matching-form-validation-in-codeigniter/
I created a class in application\libraries as follows -
<?php if (!defined('BASEPATH')) exit('No direct script access allowed.');
class MY_Form_validation extends CI_Form_validation {

     public function MY_Form_validation() {
        parent::__construct();
      }

             function valid_us_zip()
            {...........}
}//class ends

I added rule to my application\config\form_validation.php as follows -
   $config = array(
       'login/sign_up_process' => array(
           array(
                 'field' => 'txt_username_signup',
                 'label' => 'Username',
                 'rules' => 'trim|required|valid_email|xss_clean|prep_for_form'
                                     ),
           array(
                 'field' => 'txt_zip_signup',
                 'label' => 'Zip',
                 'rules' => 'trim|required|valid_us_zip|xss_clean|prep_for_form'
                                     )

                                )
           );

In my controller function I've added code as -
$this->load->library('form_validation');
echo "Error ::".$this->form_validation->run();

My validation was working before extending form validation class, but now it does not give any error even though I submit empty form. I'm not able to fix this :(

A: Finally, I got it working :)
All the steps I explained in my question are correct. In CI2+, as swatkins has mentioned we are to keep the extended core class files in application/core and library files in application/library.
I kept my extended MY_Form_validation.php in application/library and found that the $config was not passed to the constructor of parent. I edited it as -
<?php if (!defined('BASEPATH')) exit('No direct script access allowed.');
class MY_Form_validation extends CI_Form_validation {

 public function MY_Form_validation($config) {
    parent::__construct($config);
  }

         function valid_us_zip()
        {...........}
}//class ends

And tested it. My custom function was called and I received the error message also. I hope this helps somebody.

A: In CI2+, you need to put these new libraries that extend the core in the core folder, not in libraries.

A: Make file name in your application/library directory:
MY_Form_validation.php
then in your class
Code:
class MY_Form_validation extends CI_Form_validation

{
 function My_Form_validation()
   {
       parent::__construct();
   }

}


text:
Q: Http requests being dropped in Chrome Extension Summary:
I've built a chrome extension that reaches out to external API to fetch some data. Sometimes that data returns quickly, sometimes it takes 4 seconds or so. I'm often doing about 5-10 in rapid succession (this is a scraping tool).
Previously, a lot of requests were dropped because the service worker in V3 of Manifest randomly shuts down. I thought I had resolved that. Then I realized there was a race condition because local storage doesn't have a proper queue.
Current Error - Even with all these fixes, requests are still being dropped. The external API returns the correct data successfully, but it seems like the extension never gets it. Hoping someone can point me in the right direction.
Relevant code attached, I imagine it will help someone dealing with these queue and service worker issues.
Local Storage queue
let writing: Map<string, Promise<any>> = new Map();

let updateUnsynchronized = async (ks: string[], f: Function) => {
  let m = await new Promise((resolve, reject) => {
    chrome.storage.local.get(ks, res => {
      let m = {};
      for (let k of ks) {
        m[k] = res[k];
      }
      maybeResolveLocalStorage(resolve, reject, m);
    });
  });
  // Guaranteed to have not changed in the meantime
  let updated = await new Promise((resolve, reject) => {
    let updateMap = f(m);
    chrome.storage.local.set(updateMap, () => {
      maybeResolveLocalStorage(resolve, reject, updateMap);
    });
  });
  console.log(ks, 'Updated', updated);
  return updated;
};

export async function update(ks: string[], f: Function) {
  let ret = null;

  // Global lock for now
  await navigator.locks.request('global-storage-lock', async lock => {
    ret = await updateUnsynchronized(ks, f);
  });

  return ret;
}

Here's the main function
export async function appendStoredScrapes(
  scrape: any,
  fromHTTPResponse: boolean
) {
  let updated = await update(['urlType', 'scrapes'], storage => {
    const urlType = storage.urlType;
    const scrapes = storage.scrapes;
    const {url} = scrape;

    if (fromHTTPResponse) {
      // We want to make sure that the url type at time of scrape, not time of return, is used
      scrapes[url] = {...scrapes[url], ...scrape};
    } else {
      scrapes[url] = {...scrapes[url], ...scrape, urlType};
    }

    return {scrapes};
  });

  chrome.action.setBadgeText({text: `${Object.keys(updated['scrapes']).length}`});
}

Keeping the service worker alive
let defaultKeepAliveInterval = 20000;

// To avoid GC
let channel;

// To be run in content scripts
export function contentKeepAlive(name : string) {
  channel = chrome.runtime.connect({ name });

  channel.onDisconnect.addListener(() => contentKeepAlive(name));

  channel.onMessage.addListener(msg => { });
}

let deleteTimer = (chan : any) => {
  if (chan._timer) {
    clearTimeout(chan._timer);
    delete chan._timer;
  }
}

let backgroundForceReconnect = (chan : chrome.runtime.Port) => {
  deleteTimer(chan);
  chan.disconnect();
}

// To be run in background scripts
export function backgroundKeepAlive(name : string) {
  chrome.runtime.onConnect.addListener(chan => {
    if (chan.name === name) {
      channel = chan;
      channel.onMessage.addListener((msg, chan) => { });
      channel.onDisconnect.addListener(deleteTimer);
      channel._timer = setTimeout(backgroundForceReconnect, defaultKeepAliveInterval, channel);
    }
  });
}

// "Always call sendResponse() in your chrome.runtime.onMessage listener even if you don't need
// the response. This is a bug in MV3." — https://stackoverflow.com/questions/66618136/persistent-service-worker-in-chrome-extension
export function defaultSendResponse (sendResponse : Function) {
  sendResponse({ farewell: 'goodbye' });
}

Relevant parts of background.ts
backgroundKeepAlive('extension-background');

let listen = async (request, sender, sendResponse) => {
  try {
    if (request.message === 'SEND_URL_DETAIL') {
      const {url, website, urlType} = request;
      await appendStoredScrapes({url}, false);
      let data = await fetchPageData(url, website, urlType);
      console.log(data, url, 'fetch data returned background');
      await appendStoredScrapes(data, true);
      defaultSendResponse(sendResponse);
    } else if (request.message === 'KEEPALIVE') {
      sendResponse({isAlive: true});
    } else {
      defaultSendResponse(sendResponse);
    }
  } catch (e) {
    console.error('background listener error', e);
  }
};

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  listen(request, sender, sendResponse);
});