text:
Q: Amazon S3 allow specific domain to access bucket I'm trying to allow a specific domain to access my Amazon S3 bucket but after that all the domains has been dropped from Amazon S3. The url I wish to access is https://s3.ap-southeast-2.amazonaws.com/{bucketUri}/1.jpg but returns 403 forbidden on my allowed referer. I can see the Referer on the page is correct.
Here's my settings:
Block public access all off.
Bucket policy:
{
    "Version": "2008-10-17",
    "Id": "Restrict based on HTTP referrer policy",
    "Statement": [
        {
            "Sid": "1",
            "Effect": "Deny",
            "Principal": {
                "AWS": "*"
            },
            "Action": "*",
            "Resource": "arn:aws:s3:::{bucketUri}",
            "Condition": {
                "StringNotLike": {
                    "aws:Referer": "http://reference.domain.put.here"
                }
            }
        }
    ]
}

A: You should use Allow type policies as shown here, not Deny. Also your Resource is incorrect:
{
  "Version":"2012-10-17",
  "Id":"http referer policy example",
  "Statement":[
    {
      "Sid":"Allow get requests originating from www.example.com and example.com.",
      "Effect":"Allow",
      "Principal":"*",
      "Action":["s3:GetObject","s3:GetObjectVersion"],
      "Resource":"arn:aws:s3:::DOC-EXAMPLE-BUCKET/*",
      "Condition":{
        "StringLike":{"aws:Referer":["http://reference.domain.put.here"]}
      }
    }
  ]
}

And please note that aws:Referer does not really protect you. It is a merely inconvenience to bypass, as you can easly spoof aws:Referer.

A: Do an explicit Allow, not Deny.  Change the referer to StringLike instead.


text:
Q: What are Boos ghosts of? Boos are ghost characters from the Super Mario Bros. franchise. Are boos the lingering spirits of some no longer living creature. Or are they born as boos and have always been ghosts?

A: Per the Mario Wiki

Goombario's tattle for the Boo Igor in Paper Mario states: "He probably was a merchant before he became a Boo," implying that current Boos may have once been living beings.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to retrieve Firebase ID Token from the CLI? I have a Firebase function that is triggered onRequest(), using the firebase-admin SDK and using Express as middleware. This function is not expected to be tied to a Firebase client/frontend (meaning, it is expected that this function can be called via curl -X POST ... etc.).
I want to secure this function such that only users with access to the Firebase project can make requests. I've found Firebase ID Tokens, and see how to create them on the client side.
My issue is that I don't have a client to create them from.
Is there a way to create an ID Token for an authorized user using the CLI, or another similar method?
E.g., something like
firebase login
firebase use <project-id>
firebase generate-id-token // would return an ID token with standard expiration rules.

A: There isn't a command in Firebase CLI to login as a user and print ID token. You can call Firebase Auth REST API using cURL and get the token.
curl --request POST \
  --url 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[FIREBASE_API_KEY]' \
  --header 'Content-Type: application/json' \
  --data '{
  "email": "user@domain.tld",
  "password": "12345678",
  "returnSecureToken": true
}'

I want to secure this function such that only users with access to the Firebase project can make requests.

Anyone can use the REST API but they must know the account's password to login.


text:
Q: Comparing Lists I have 8 lists (jan, feb, mar, apr, may, jun, jul, aug) each of which contain names in list format, i.e.
['John Smith', 'Cat Stevens', 'Andrew Alexander', 'El Gordo Baba', 'Louis le Roy']

etc.
How do I compare these lists in order, and see when a name appeared (i.e. subscribed) and when a name disappeared (i.e. unsubscribed).
So, say John Smith didn't appear until February, I want to have this information. Lets say he unsubscribed in July, I want this information too (this is FAR more important than the former).

A: Don't use lists, use a set instead.
You could find who (un)subscribed between jan and feb simply using set difference:
subs = feb - jan
unsubs = jan - feb

That being said, you would be better off following Daenyth's suggestion. Put these in a database, add a joined and left date field and you'll have finer granularity than just months and you won't need to stored duplicated data.

A: data = {
 'jan': ['John Smith', 'Cat Stevens', 'Andrew Alexander', 'El Gordo Baba'],
 'feb': ['Louis le Roy', 'John Smith'],
 'mar': ['Cat Stevens', 'Louis le Roy']
}

from itertools import izip

keys = 'jan feb mar'.split()
for m1,m2 in izip(keys,keys[1:]):
    a = set(data[m1])
    b = set(data[m2])
    print m1, '\n\tsubscribed:', ','.join(b-a), '\n\tquit:', ','.join(a - b )

result:
jan
    subscribed: Louis le Roy
    quit: Andrew Alexander,Cat Stevens,El Gordo Baba
feb
    subscribed: Cat Stevens
    quit: John Smith

A: data = {
 'jan': ['John Smith', 'Cat Stevens', 'Andrew Alexander', 'El Gordo Baba'],
 'feb': ['Louis le Roy', 'John Smith'],
 'mar': ['Cat Stevens', 'Louis le Roy']
}

subs = {}
unsubs = {}
for mon in data:
    for name in data[mon]:
        if name not in subs:
            subs[name] = mon
        else:
            unsubs[name] = mon
>>> subs
{'Andrew Alexander': 'jan', 'Louis le Roy': 'mar', 'John Smith': 'jan', 'El Gordo Baba': 'jan', 'Cat Stevens': 'jan'}
>>> unsubs
{'Louis le Roy': 'feb', 'John Smith': 'feb', 'Cat Stevens': 'mar'}

A: As a starter:
from collections import defaultdict
dd = dict(jan=(0,jan), feb=(1, feb), ...)

appearances = defaultdict(list)

for k, (i, li) in dd.items():
   for name in li:
       appearances[name].append((i,k))

for name in appearances.keys():
    months = [ (name, i) for i, name in sorted(appearances[name]) ]
    print name, months

You get for each name this sorted list of pairs (month, index) the name appears. index is the index of the month. Now you can check for gaps, for a minimal index and for a maximal index.

A: Here is a quick example:
jan,feb,mar,apr,may,jun,jul,aug = [1],[1,2],[1,2,3],[1,2,3,4],[2,3,4],[3,4],[4],[]
months = [set(m) for m in [jan,feb,mar,apr,may,jun,jul,aug]]
changes = [(list(b-a), list(a-b)) for a, b in zip(months, months[1:])]

>>> changes
[([2], []), ([3], []), ([4], []), ([], [1]), ([], [2]), ([], [3]), ([], [4])]

Each element in changes is a transition from one month to the next, where the first item in the tuple is a list of all that were added, and the second item in the tuple is a list of all that left.


text:
Q: Не могу получить сумму всех элементов, не понимаю что не так def n(*num):
    s=num[0]
    for i in num:
        s+=i
    return s

print(n([5,6,7,8]))

A: def n(*num): → def n(num):
s=num[0] → s = 0

A: def n(num):
    s = 0
    for i in num:
        s += i
    return s

print(n([5,6,7,8])) # 26


text:
Q: Coloring the echo output in php I am reading a textile in php which has two sentences.
Top 1: 201 The Secret
Top 4 : 203, 290, 593, 224
What a Life!, Magical, Unicorn Land, Fire
function getcontent($file1){
    $fh= fopen($file1, 'r');
    $theData = fread($fh, filesize("$file1"));
    return $theData;
    fclose($fh);
}
?>

I wish to highlight the 2 sentences in different colors when I echo the file:

<?php echo "
"  .$movies. "
"; ?>

$movies is the textfile. How can I do so in php? Would I have to create a separate function for that?

A: You could use an array to store the different sentences, so the new code would be something like this. By the way, code after a return statement is never executed, so avoid that
function getcontent($file1)
{
    $lines = file($file); //read all lines to array
    return $lines;
}

        <?php
            //lines is the array returned from getcontent
            foreach($lines as $line)
            {
                echo "
"  .$line. "
"
            }
         ?>

After that you could use an if-clause to swap colors so each row has an alternating color, or a random color if you'd like that

A: PHP's file_get_contents function is a simpler way to get your file's contents.
If your file only ever has 2 lines, there may be a simpler way to do this, but you could split the lines via explode (for details on exploding text that might have strange line breaks, try here), which would look something like this:
$movies = file_get_contents("filename.txt");
$lines = explode("\n", $movies);

Then loop through the lines and style as desired:
if (is_array($lines)) {
    $line_count = count($lines);
    for ($i = 0; $i <= $line_count; $i++) {
        if ($i % 2 == 0) {
            echo '' . $lines[$i] . '
';
        }
        else {
            echo '' . $lines[$i] . '
';
        }
    }
}

More detailed logic could be implemented to color lines differently if there are more than 2 lines in the file.
Per your comment, the following code will color the first line red, and all other lines blue:
if (is_array($lines)) {
    $line_count = count($lines);
    for ($i = 0; $i <= $line_count; $i++) {
        if ($i == 0) {
            echo '' . $lines[$i] . '
';
        }
        else {
            echo '' . $lines[$i] . '
';
        }
    }
}


text:
Q: Black video when using PBJVideoPlayer on iOS 10 I am using PBJVideoPlayer to show videos on my iOS app, using the following code:
_videoPlayerController = [[PBJVideoPlayerController alloc] init];
_videoPlayerController.delegate = self;
_videoPlayerController.view.frame = _playerView.bounds;
[self addChildViewController:_videoPlayerController];
[_playerView addSubview:_videoPlayerController.view];
[_videoPlayerController didMoveToParentViewController:self];

_videoPlayerController.videoPath = [self finalVideoPath];

On about 50% of the time, the video is shown as black while the sound is fine.
The bounds are good (since I do see a black box) and the video path is good since I do have the correct video created.
I am using a device with iOS 10, and I still do not have a device with an older iOS to check..
Any ideas what might be the problem? I have seen other questions regarding black videos but non of them help.

A: So, after several hours of investigating this, it seems to be an iOS10 bug.
See this: AVPlayer playback fails while AVAssetExportSession is active as of iOS 10
What worked for me, is removing the watermark layer I had on the video and then removing the animationTool property from the video composition


text:
Q: How do i make jQuery unique ID for div for click event? I need on selection to append div element to the another div, I have done it, and also every time when I select new selection, it should append new div.
the problem is, those appended div's have same id, so I can not delete particular element. I have made them unique with declaring var and combining id with a string, like : id="add_marke'+selectedKey+'" BUT I cant do something like this jQuery( "#add_marke'+selectedKey+'" ).click(function() {
How can I select ID when I make unique ID?
var selectedKey = jQuery("#model").val();
jQuery('#example').append('' + '
' +
  '

 ' +
  '&nbsp' +
  '   <select  name="model_cars" id="model_cars" ><option id="selectModel" name="selectModel" value="all" >Please select </option><option>test</option></select>' +
  '&nbsp' + '
');
jQuery("#car_name").click(function() {
  jQuery("#add_marke\\.selectedKey").remove();
});

A: You can add the IDs as you do with a predefined prefix:
... id="add_marke_' + selectedKey + '" ...

And then bind the click with a jQuery selector for all elements that have the ID starting with add_marke_:
$('div[id^="add_marke_"]').click()

A: What you need to do is add the click handler to the class name shared by all of these divs. Once the click handler has been triggered, you can then extract the relevant id of the element and compose a selector from that id.
jQuery( ".class_name" ).click(function() {
  var id = jQuery( this ).attr( "id" );
  jQuery( "#" + id ).remove();
});

A: You can use
jQuery( ".icon-remove" ).click(function() {
        jQuery(this).parent().parent().parent().remove();
    });

A: Since an ID must be unique you have one of two options, as I see it:

*

*Appending some sort of counter or numeric identifier to the ID, so you always have a unique ID (e.g., count the number of elements and then attribute your ID as my-id-1, my-id-2, etc.) Here you would have to write the DOM query in such a way that searches only for those IDs which begin with a given pattern, div[id^="my-id-"]

*Use a class to identify the object in terms of any interactions you would like to provide for all of these
 elements which have the same structure. Here, you can query based on a common class, in your case .add_marke.

A:

   jagadeesh

   <button >Remove</button>

    $('.car-remove').on('click',function(){
        var mainElement = $(this).closest('.parentElement')
        /// do what ever you want with main element. it selects only current parent
        //element
        mainElement.remove();
    })

A: Did you want to do something like this?
http://jsfiddle.net/Wg9FE/1/
var selectedKey = "someId";

jQuery('#example').append('' +
            '
' +
            '

 ' + '&nbsp' +
            '   <select  name="model_cars" id="model_cars" ><option id="selectModel" name="selectModel" value="all" >Please select </option><option>test</option></select>'+ '&nbsp' +
            '
');

jQuery( "#car_name" ).click(function() {
             jQuery( "#add_marke" + selectedKey ).remove();
        });


text:
Q: Find min/max values for two intervals using mongo aggregation I have a use-case where I need to fetch max value from one interval and min value from another interval. This has to happen for all unique domains in collection. This collection contains domain and when it was visited. Domain can be visited several time so collection will have multiple rows for each visit.
Since these two intervals are adjacent I can fetch all records in one query but I have to calculate min/max values at application side. Another way is to have two separate queries for min from one interval and max from another interval. Just curious if it can be optimised in a way that single query performs this job. Below are my two aggregation queries:
Aggregation 1:

List(
  MongoDBObject(
    "$match" -> MongoDBObject("stamp" -> MongoDBObject("$gte" -> T1, "$lt" -> T2))
  ),
  MongoDBObject(
    "$group" -> MongoDBObject(
      "_id" -> "$key",
      "stamp" -> MongoDBObject("$max" -> "$stamp")
    )
  )
)

Aggregation 2:

List(
  MongoDBObject(
    "$match" -> MongoDBObject("stamp" -> MongoDBObject("$gte" -> T2, "$lt" -> T3))
  ),
  MongoDBObject(
    "$group" -> MongoDBObject(
      "_id" -> "$key",
      "stamp" -> MongoDBObject("$min" -> "$stamp")
    )
  )
)

Here T1 < T2 < T3 and stamp is a timestamp i.e. long value. Below is sample document from collection:
{
  "_id" : ObjectId("6048b0b7fe4b987f2e251705"),
  "key" : "JW9oIzDYlV.com",
  "stamp" : NumberLong("1612784569678"),
}


text:
Q: Button not clicking in Portrait Mode I have a button to which I attach an onClickListener via code. I have to to this through code because it's in a fragment.
The listener works fine when in landscape mode, but when it's in portrait it doesn't. There's no "click" sound even.
In my xml file, I set the initial visibility of the button to invisible and then make it visible later when the user clicks a radio button in the same Viewgroup as the button. The onclicklisteners of the radiobuttons are working just fine in both portrait and landscape mode.
Now if I remove the "android:visibility="invisible" code in xml, the onclickstener works fine in portrait mode! But of course I need it invisible till the user clicks a radiobutton otherwise the UI doesn't make sense. Very weird indeed.
Here's my code:
private void setOnClickForSaveButton(View v) {

        Button changeFundsSave = (Button) v.findViewById(R.id.change_funds_save);
        changeFundsSave.setOnClickListener(saveListener);

    }

Button.OnClickListener saveListener = new Button.OnClickListener() {

        @Override
        public void onClick(View v) {

            //Get the rootview
            View rootView = v.getRootView();

            EditText changeFundsEdit = (EditText) rootView.findViewById(R.id.change_funds_edit);

            if(changeFundsEdit.getText().toString().equals("")) {
                new AlertDialog.Builder(getActivity())
                .setTitle( "" )
                .setMessage( "Enter the number of units" )
                .setPositiveButton( "Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .show();
                return;

            }

        }
    };

    private void setOnClicksForRadioButtons(View v) {

        RadioButton rb1 = (RadioButton)v.findViewById(R.id.add_units);
        RadioButton rb2 = (RadioButton)v.findViewById(R.id.remove_units);
        RadioButton rb3 = (RadioButton)v.findViewById(R.id.set_units);

        rb1.setOnClickListener(addRemoveSetButtonListener);
        rb2.setOnClickListener(addRemoveSetButtonListener);
        rb3.setOnClickListener(addRemoveSetButtonListener);

    }

    OnClickListener addRemoveSetButtonListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            // Since we only have the radiobutton view, we need to get the parent
            View rootView = v.getRootView();

            //Make the controls visible
            TextView changeFundsText = (TextView) rootView.findViewById(R.id.change_funds_text);
            EditText changeFundsEdit = (EditText) rootView.findViewById(R.id.change_funds_edit);
            Button changeFundsSave = (Button) rootView.findViewById(R.id.change_funds_save);

            changeFundsText.setVisibility(View.VISIBLE);
            changeFundsEdit.setVisibility(View.VISIBLE);
            changeFundsSave.setVisibility(View.VISIBLE);

        }

    };

}

A: Solved the problem! In portrait mode, like everyone else I load one fragment in a separate activity. Out of habit I was calling setContentView(something) before loading the fragment! So ultimately the two layouts were overlapping each other and the visible and invisible buttons were overlapping each other and things must have gotten messed up. Damn, I'm not sure if I like the concept of fragments at all. My first time using them. But maybe I just need to learn how to wire them up properly before I get used to them :) Thank you so much for your help

A: my guess is that
1) do you findViewById again for the view you passed in setOnClickForSaveButton? since the old view will be destroyed and a view will be created when you change screen orientation
2) do you have multiple ids for R.id.change_funds_save
3) add a log at the first line of onclick(v) to see if it is called but goto another branch you didnt expect.

A: Unless you are loading two separate xml layout files from layout-land and layout-port, there shouldn't be much difference between landscape mode and portrait mode. That being said, I'm going to take a wild guess and say that your app is probably not working correctly due to configuration changes. Let me know if this is actually true... i.e. does your app work at first, but stops working when you rotate the screen?
If this is true, you should look into how the Activity lifecycle is affecting your views and onClickListeners.


text:
Q: Quotients of spaces onto spaces with smaller weight Suppose that $X$ is a compact Hausdorff space of weight $\kappa$. Is it possible to find for every infinite cardinal $\lambda <\kappa$ a compact Hausdorff space $L$ of weight $\lambda$ and a continuous surjection $f\colon K\to L$?
I think I can do it for $\lambda=\aleph_0$ but my approach is very roundabout. Is it possible in general?

A: It's easy if you only want weight $\le \lambda$:
$X$ can be embedded into $[0,1]^\kappa$ (as a closed subset), via $e:K \to [0,1]^\kappa$, the standard embedding (from being Tychonoff).
Then define $\pi_\lambda: [0,1]^\kappa \to [0,1]^\lambda$ by restricting maps $f: \kappa \to [0,1]$ to $\lambda \subset \kappa$. Then $\pi_\lambda \circ e$ maps $K$ onto a compact space of weight at most $\lambda$, as $w([0,1]^\lambda) = \lambda$.
Of course you can take any subset $A \subseteq \kappa$ with $|A|  =\lambda$ and the projection $\pi_A$ (restriction to those coordinates). For $\lambda = \aleph_0$ we are done, we just have to make sure the image is infinite.
Intuitively, if $w(X) = \kappa$ there should be some $A$ with $\pi_A \circ e[K]$ of weight exactly $\lambda$. Maybe this gives you an idea?


text:
Q: ¿Se puede hacer un format de timestamp?  // $timestamp    = "";
  $datetimeFormat = 'YmdHis';
  $date = new DateTime('now');
 // $date->setTimestamp($timestamp);
  echo $date->format($datetimeFormat);

El resultado de ese código es: 20180411131121

A: Prueba así:
<?php
 // $timestamp    = "";
  $datetimeFormat = 'Y-m-d H:i:s';
  $date = new DateTime('now');
 // $date->setTimestamp($timestamp);
  echo $date->format($datetimeFormat);

?>

Este es el resultado:

2018-04-11 11:28:53

Aquí tienes una explicación completa de cómo dar formato a un timestamp

A: Si lo que necesitás es el timestamp podés usar el método getTimestamp() del objeto DateTime.
$date = new DateTime('now');
var_dump($date->getTimestamp());

Salida:
int(1523454056)

Pero si lo que necesitas es darle formato, estabas en lo correcto, sólo que te faltaba ponerle lo necesario para que sea visualmente correcto.
$datetimeFormat = 'Y-m-d H:i:s';
$date = new DateTime('now');
var_dump($date->format($datetimeFormat));

Salida:
string(19) "2018-04-11 13:44:02"

Acá tenés los formatos aceptados por DateTime().
Y esto es el código en ejecución para que puedas ver los diferentes resultados.


text:
Q: Cross-tabulation (contingency table) using Python ORM? Anyone doing very basic statistical explorations on data living in a relational database has had to calculate cross tabulations,also known as contingency tables(wikipedia page). these are indispensable when you need to count how many items fall more than one category at the same time. For example: How many customers are female and like chocolate?
Scipy has ways to do this for matrices, using a variation of histogram2d But for meaningfull statistical analysis you need to be able to have a table (with variable names) from which you can specify which variables you would like to tabulate. Moreover, it needs to work for other types of variables, not only numeric. Actually, numeric tabulation is the more complicated one since it requires binning. R naturally has such a function which is called table, which could easily be ported to Python. However, remember I mention at the title that I'd like to use an ORM, why? Because cross-tabulations are much smaller that the data used to generate it, and you could have a 2x2 table calculated from billions of records on a database. My point is: In serious applications, you can't afford to bring all your data to memory and loop through it. So you'd have to have table design converted into a SQL query so that all the counting would be done by the database engine. And the ORM would take care of the necessary SQL dialect adjustments necessary so that you could run your code with any database backend.
A example of the SQL (in MySQL dialect) for a simple cross tabulation can be found here.
So now that I think I have motivated you about the problem, here are the questions: Is this functionality implemented in any Python ORM? How would you implement this using, say, SQLAlchemy or Django ORM?

A: I hate to have to answer my own question, but sometimes we just can't wait for help. And since I have found the answer and a good one, I feel obliged to share with the community. So here it is:
table = self.session.query(Table.var1, Table.var2, func.count(Table)).group_by(Table.var1, Table.var2).all()

This will return a list of tuples like (row,column, count). From this list you can assemble your contingency table and calculate the margin totals if you want. It may be worth mentioning that calculating this cable took .28 seconds for a table with 296110 records, and var1 and var2 had 5 and 90 levels, respectively.
now a little function to assemble and print the (2d) table:
def pprint_table():
    colnames = list(set([i[1] for i in table]))
    rows = defaultdict(lambda:[0]*len(colnames))
    for r in table:
        rows[r[0]][colnames.index(r[1])] = r[2]
    print colnames, 'total'
    for rn, r in rows.items():
        print rn, r, sum(r)


text:
Q: Define array globally with variable parameter in C Here's the code:
int EdgeCount = 0;
int numOfEdges = 0;

void addEdge() {
    // some code
    numOfEdges++;
}

int EdgeWeightArray[numOfEdges]; // error

I want that global array with variable parameters to use it later but I couldn't do that because without #define we can't define globally arrays parameters; and #define is not a variable thing. In my code numOfEdges is variable and I couldn't make it constant.

A: EdgeWeightArray has global scobe, so it must be a fixed size. But numOfEdges is of course not a constant expression.
What size do you expect EdgeWeightArray to be? Do you expect it to grow when you increment numOfEdges? If so, you nwed to look into dynamic memory allocation; namely malloc and realloc.
Brief example with no error checking:
int numOfEdges = 0;
int *EdgeWeightArray;
void addEdge(some parameters) {
    //SOME CODE
    numOfEdges++;
    EdgeWeightArray = realloc(EdgeWeightArray, numOfEdges * sizeof(EdgeWeightArray[0]));
}

A: Why not use a global int pointer and allocate memory with malloc() with desired number of elements?
What you are trying to do is not possible because memory for global variables are calculated at compile time and the value of numOfEdges is updated at runtime.

A: In my eyes, you want to create a not well designed code, where the size has global scope and the vector has to have local scope in order to be stored in the stack (according to your starting point). Anyway, you might do something like that:
void defineSize() {
    numOfEdges++;
}

void useIt()
{
    int EdgeWeightArray[numOfEdges];
    /* Use EdgeWeightArray, once the function has been executed, \
       EdgeWeightArray will dissapear */
}

A: This is an expansion to Jonathons answer.
If you already know how many Elements there will be at maximum for your array you could use a fixed size for your array. This could be faster in the moment, because there is no reallocation happening.
But you have to make sure to do appropriate error handling with this approach. It can be quite error prone.
You would then need a counter to keep track of your Edges, but you appear to already have one of those.
Your code would then look like:
#define MAX_EDGE_COUNT 1000
int EdgeCount = 0;

void addEdge() {
    // some code
    EdgeWeightArray[EdgeCount] = newEdge;
    EdgeCount++;
}

int EdgeWeightArray[MAX_EDGE_COUNT];


text:
Q: How to return value with apostrophe from excel UDF I have been trying to append ' before a value so that excel cells will recognize the cells as a text value.
Is there any way we can append ' with a value from UDF.
e.g If I call GetZero() it will return me '0.00 and excel will recognize it as 0.00 only(but as a text value).

A: For your example
Public Function GetZero() As String
GetZero = "'" & format(0,"0.00")
End Function


text:
Q: Environment variables in motd not working I'm trying to send user login logs to my email with the users name and location. After making the script I found that environment variables can't run in this script, I'm hoping that someone out there can help me get this working even if it's a security problem.
Thanks for your time
/etc/update-motd.d/99-footer
ssmtp -oi me@gmail.com << EOF
To: me@gmail.com
Subject: Login

$SUDO_USER" from "$SSH_CLIENT

EOF

email output is
Subject: Login
 from

A: As an experiment, I added an env command (equivalent to printenv) to the end of /etc/update-motd.d/99-footer on my Ubuntu 12.04 system.
When I logged in again, the following lines were added to the end of my /etc/motd:
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PWD=/

So $PATH and $PWD are the only environment variables that are set when 99-footer is running. That's why $SUDO_USER and $SSH_CLIENT aren't being expanded.
You need to send that e-mail from somewhere else, not from the process that updates /etc/motd.

A: If you change the script to:
echo "To: me@gmail.com
Subject: Login

$SUDO_USER from $SSH_CLIENT

" | ssmtp -oi me@gmail.com

Note use of double quotes. Variables should then be substituted.


text:
Q: WCF Service application without gui that will stay alive [WCF newbie]
I have a basic client-server WCF project.
My Service is "gui"less application, meaning that I created winform application, removed the Form1.cs and the lines that starts the gui.
The service is running ok, I am using servicehost.open..
My problem is that it is "serial" (sync), so after a second the application exists.
How can i keep the application alive and listening to the host ?
I need to halt the process and then to host.close when I want to end it.
Thanks
This is code of service:
class Program
{
    public static Uri BaseAddress;
    [STAThread]
    static void Main(string[] args)
    {

        string baseAddressStr = "http://localhost:7000/someservice";
        BaseAddress = new Uri(baseAddressStr);
        using (ServiceHost host = new ServiceHost(typeof(MyClass)BaseAddress))
        {
            ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
            smb.HttpGetEnabled = true;
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            host.Description.Behaviors.Add(smb);

            host.Open();
            host.Close();
        }
    }
}

A: I don't think you want to host your WCF service in a windowless WinForms app.
If you want it to stay open indefinitely, the way to go is to host the WCF service in a Windows Service. Here you have a basic sample.
The benefits should be obvious:

*

*Can run even if no user is logged in.

*Does not require a workaround for keeping the application open.

Additionally, you should consider externalizing your WCF configuration (like the base address, service behavior) to the application configuration file. You don't want to rebuild and redeploy your service each time something (anything) changes in the configuration, which may vary from development, test, acceptance and production environments.


text:
Q: MySql :: Stored procedure :: navicat I have the following  stored procedure in MySql(navicat), but I need to test RefrenceCount
after update operation, when I add if st. after the update statment. syntax error occurred
CREATE PROCEDURE `SP_IncDecReferenceCount`(pReferenceID int,pIncValue int)
BEGIN
update filesrefrences
set
    filesrefrences.RefrenceCount= filesrefrences.RefrenceCount+pIncValue
where
        filesrefrences.ReferenceID= pReferenceID;
IF Not EXISTS(SELECT * from filesrefrences where filesrefrences.ReferenceID= pReferenceID and filesrefrences.RefrenceCount>0) then
DELETE from filesrefrences WHERE filesrefrences.ReferenceID = pReferenceID;
end if
END

[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'END' at line 11

A: You can do
update filesrefrences
set
    filesrefrences.RefrenceCount= filesrefrences.RefrenceCount+IF(pIncValue > 0,pIncValue,1)
where
        filesrefrences.ReferenceID= pReferenceID;

OR
update filesrefrences
    set
        filesrefrences.RefrenceCount= filesrefrences.RefrenceCount+pIncValue
    where
            (filesrefrences.ReferenceID= pReferenceID) AND (pIncValue > 0);


text:
Q: Unwanted vertical spacing between two  elements (one of them contains a  element) I have a problem with unwanted vertical spacing between two  elements. One of them contains a  element, it seems to me that it gets stuck there.
However, the situation only occurs on larger screens (> 15 ") while on small ones it is ok. The larger the screen size, the larger the spacing. Help please I'm in dead end.
Code:

Zadatak 3.
            Ispitati konvergenciju funkcionalnog niza \( f_n(x) = \frac{1}{n^2+x^2}\).

              Rešenje

                  Već posmatrajući grafik niza, može se izvesti zaključak da je granična funkcija ovog niza \( f(x) = 0\).

                  Zaista, kako je \( |f_n(x)| \leq \frac{1}{n^2}\) \( \forall x\in \mathbf{R} \), biće \( \displaystyle\lim_{n \to \infty }{\sup_{x\in \mathbf{R}}{|f_n(x)-f(x)|}}= \) \( \displaystyle\lim_{n \to \infty }{\sup_{x\in \mathbf{R}}{\Bigg|\frac{1}{n^2+x^2}\Bigg|}}=  \)
                  \( \displaystyle \lim_{n \to \infty}\frac{1}{n^2}=0\).
                  Dakle \(f_n\rightrightarrows f\).

Link to problematic page:
http://alas.matf.bg.ac.rs/~ml05184/strana2.html
Here is the screenshot

A: It is because your element .embed-responsive-16by9::before has padding-top that is in % value. Try setting px for larger screens

@media screen and (min-width: 1440px) {
    .embed-responsive-16by9::before {
     padding-top: 98px;
   }
}

Note: 1440px == 15"
After setting the padding in px the result will be like this on bigger screens

A: @Viira Wow thanks!
I've edited padding setting it to the actual height of my iframe element and it works perfectly.

@media screen and (min-width: 1440px) {
    .embed-responsive-16by9::before {
     padding-top: 550px;
   }
}


text:
Q: Outline effect to text Are there any ways in CSS to give outlines to text with different colors ? I want to highlight some parts of my text to make it more intuitive - like the names, links, etc. Changing the link colors etc. are common nowadays, so I want something new.

A: I got better results with 6 different shadows:
.strokeThis{
    text-shadow:
    -1px -1px 0 #ff0,
    0px -1px 0 #ff0,
    1px -1px 0 #ff0,
    -1px 1px 0 #ff0,
    0px 1px 0 #ff0,
    1px 1px 0 #ff0;
}

A:

h1 {
   color: black;
   -webkit-text-fill-color: white; /* Will override color (regardless of order) */
   -webkit-text-stroke-width: 1px;
   -webkit-text-stroke-color: black;
}

Properly stroked!

A: This mixin for SASS will give smooth results, using 8-axis:
@mixin stroke($size: 1px, $color: #000) {
  text-shadow:
    -#{$size} -#{$size} 0 $color,
     0        -#{$size} 0 $color,
     #{$size} -#{$size} 0 $color,
     #{$size}  0        0 $color,
     #{$size}  #{$size} 0 $color,
     0         #{$size} 0 $color,
    -#{$size}  #{$size} 0 $color,
    -#{$size}  0        0 $color;
}

And normal CSS:
text-shadow:
  -1px -1px 0 #000,
   0   -1px 0 #000,
   1px -1px 0 #000,
   1px  0   0 #000,
   1px  1px 0 #000,
   0    1px 0 #000,
  -1px  1px 0 #000,
  -1px  0   0 #000;

A: There is an experimental webkit property called text-stroke in CSS3, I've been trying to get this to work for some time but have been unsuccessful so far.
What I have done instead is used the already supported text-shadow property (supported in  Chrome, Firefox, Opera, and IE 9 I believe).
Use four shadows to simulate a stroked text:

.strokeme {
  color: white;
  background-color: white;
  text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;
}

  This text should have a stroke in some browsers

I have made a demo for you here
And a hovered example is available here

As Jason C has mentioned in the comments, the text-shadow CSS property is now supported by all major browsers, with the exception of Opera Mini. Where this solution will work for backwards compatibility (not really an issue regarding browsers that auto-update) I believe the text-stroke CSS should be used.

A: Just adding this answer. "Stroking" the text is not the same as "Outlining".
Outlining looks great. Stroking looks horrid.

The SVG solution listed elsewhere has the same issue. If you want an outline you need to put the text twice. Once stroked and again not stroked.
Stroking IS NOT Outlining

body {
  font-family: sans-serif;
  margin: 20px;
}

.stroked {
  color: white;
  -webkit-text-stroke: 1px black;
}

.thickStroked {
  color: white;
  -webkit-text-stroke: 10px black;
}

.outlined {
  color: white;
  text-shadow:
    -1px -1px 0 #000,
     0   -1px 0 #000,
     1px -1px 0 #000,
     1px  0   0 #000,
     1px  1px 0 #000,
     0    1px 0 #000,
    -1px  1px 0 #000,
    -1px  0   0 #000;
}

.thickOutlined {
  color: white;
text-shadow: 0.0px 10.0px 0.02px #000, 9.8px 2.1px 0.02px #000, 4.2px -9.1px 0.02px #000, -8.0px -6.0px 0.02px #000, -7.6px 6.5px 0.02px #000, 4.8px 8.8px 0.02px #000, 9.6px -2.8px 0.02px #000, -0.7px -10.0px 0.02px #000, -9.9px -1.5px 0.02px #000, -3.5px 9.4px 0.02px #000, 8.4px 5.4px 0.02px #000, 7.1px -7.0px 0.02px #000, -5.4px -8.4px 0.02px #000, -9.4px 3.5px 0.02px #000, 1.4px 9.9px 0.02px #000, 10.0px 0.8px 0.02px #000, 2.9px -9.6px 0.02px #000, -8.7px -4.8px 0.02px #000, -6.6px 7.5px 0.02px #000, 5.9px 8.0px 0.02px #000, 9.1px -4.1px 0.02px #000, -2.1px -9.8px 0.02px #000, -10.0px -0.1px 0.02px #000, -2.2px 9.8px 0.02px #000, 9.1px 4.2px 0.02px #000, 6.1px -8.0px 0.02px #000, -6.5px -7.6px 0.02px #000, -8.8px 4.7px 0.02px #000, 2.7px 9.6px 0.02px #000, 10.0px -0.6px 0.02px #000, 1.5px -9.9px 0.02px #000, -9.3px -3.6px 0.02px #000, -5.5px 8.4px 0.02px #000, 7.0px 7.2px 0.02px #000, 8.5px -5.3px 0.02px #000, -3.4px -9.4px 0.02px #000, -9.9px 1.3px 0.02px #000, -0.8px 10.0px 0.02px #000, 9.6px 2.9px 0.02px #000, 4.9px -8.7px 0.02px #000, -7.5px -6.7px 0.02px #000, -8.1px 5.9px 0.02px #000, 4.0px 9.2px 0.02px #000, 9.8px -2.0px 0.02px #000, 0.2px -10.0px 0.02px #000, -9.7px -2.3px 0.02px #000, -4.3px 9.0px 0.02px #000, 7.9px 6.1px 0.02px #000
}

svg {
  font-size: 40px;
  font-weight: bold;
  width: 450px;
  height: 70px;
  fill: white;
}

.svgStroke {
  fill: white;
  stroke: black;
  stroke-width: 20px;
  stroke-linejoin: round;
}

Properly stroked!

Properly outlined!

Thickly stroked!

Thickly outlined!

<svg viewBox="0 0 450 70">
  <text class="svgStroke" x="10" y="45">SVG Thickly Stroked!</text>
</svg>
<svg viewBox="0 0 450 70">
  <text class="svgStroke" x="10" y="45">SVG Thickly Outlined!</text>
  <text class="svgText" x="10" y="45">SVG Thickly Outlined!</text>
</svg>

PS: I'd love to know how to make the SVG be the correct size of any arbitrary text. I have a feeling it's fairly complicated involving generating the SVG, querying it with Javascript to get the extents, then applying the results. If there is an easier non-JS way, I'd love to know.

Update: As @12me21 points out, in SVG you can use paint-order="stroke" to make it stroke before filling and then you don't have to repeat the text

svg {
  font-size: 40px;
  font-weight: bold;
  width: 450px;
  height: 70px;
  fill: white;
}

.svgText {
  fill: white;
  stroke: black;
  stroke-width: 15px;
  stroke-linejoin: round;
  paint-order: stroke;
}
<svg viewBox="0 0 450 70">
  <text class="svgText" x="10" y="45">SVG Thickly Outlined!</text>
</svg>

A: You could try stacking multiple blured shadows until the shadows look like a stroke, like so:
.shadowOutline {
  text-shadow: 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black, 0 0 4px black;
}

Here's a fiddle: http://jsfiddle.net/GGUYY/
I mention it just in case someone's interested, although I wouldn't call it a solution because it fails in various ways:

*

*it doesn't work in old IE

*it renders quite differently in every browser

*applying so many shadows is very heavy to process :S

A: Working with thicker strokes gets a bit messy, if you have the pleasure of sass try this mixin, not perfect and depending on stroke weight it generates a fair amount of css.
 @mixin stroke($width, $colour: #000000) {
      $shadow: 0 0 0 $colour; // doesn't do anything but I couldn't work out how to create a blank string and maintain commas
      @for $i from 0 through $width {
          $shadow: $shadow,
          -$i + px -$width + px 0 $colour,
          $i + px -$width + px 0 $colour,
          -$i + px $width + px 0 $colour,
          $i + px $width + px 0 $colour,
          -$width + px -$i + px 0 $colour,
          $width + px -$i + px 0 $colour,
          -$width + px $i + px 0 $colour,
          $width + px $i + px 0 $colour,
      }
      text-shadow: $shadow;
}

A: We can use text-stroke
HTML

Sample Text

CSS
  h1{
    -webkit-text-stroke: 2px red;
    text-stroke: 2px red;
    }

Just piece of cake. Try this instead of using text-shadow

A: I had this issue as well, and the text-shadow wasn't an option because the corners would look bad (unless I had many many shadows), and I didn't want any blur, therefore my only other option was to do the following: Have 2 divs, and for the background div, put a -webkit-text-stroke on it, which then allows for as big of an outline as you like.

div {
  font-size: 200px;
  position: absolute;
  white-space: nowrap;
}

.front {
 color: blue;
}

.outline {
  -webkit-text-stroke: 30px red;
  user-select: none;
}

 outline text

 outline text

Using this, I was able to achieve an outline, because the stroke-width method was not an option if you want your text to remain legible with a very large outline (because with stroke-width the outline will start inside the lettering which makes it not legible when the width gets larger than the letters.
Note: the reason I needed such a fat outline was I was emulating the street labels in "google maps" and I wanted a fat white halo around the text.  This solution worked perfectly for me.
Here is a fiddle showing this solution

A: Text Shadow Generator
There are lots of great answers here. It would appear the text-shadow is probably the most reliable way to do this. I won't go into detail about how to do this with text-shadow since others have already done that, but the basic idea is that you create multiple text shadows around the text element. The larger the text outline, the more text shadows you need.
All of the answers submitted (as of this posting) provide static solutions for the text-shadow. I have taken a different approach and have written this JSFiddle that accepts outline color, blur, and width values as inputs and generates the appropriate text-shadow property for your element. Just fill in the blanks, check the preview, and click to copy the css and paste it into your stylesheet.

Needless Appendix
Apparently, answers that include a link to a JSFiddle cannot be posted unless they also contain code. You can completely ignore this appendix if you want to. This is the JavaScript from my fiddle that generates the text-shadow property. Please note that you do not need to implement this code in your own works:
function computeStyle() {
    var width = document.querySelector('#outline-width').value;
  width = (width === '') ? 0 : Number.parseFloat(width);
  var blur = document.querySelector('#outline-blur').value;
  blur = (blur === '') ? 0 : Number.parseFloat(blur);
  var color = document.querySelector('#outline-color').value;
  if (width < 1 || color === '') {
    document.querySelector('.css-property').innerText = '';
    return;
  }
    var style = 'text-shadow: ';
  var indent = false;
    for (var i = -1 * width; i <= width; ++i) {
    for (var j = -1 * width; j <= width; ++j) {
        if (! (i === 0 && j === 0 && blur === 0)) {
        var indentation = (indent) ? '\u00a0\u00a0\u00a0\u00a0' : '';
            style += indentation + i + "px " + j + "px " + blur + "px " + color + ',\n';
        indent = true;
      }
    }
  }
  style = style.substring(0, style.length - 2) + '\n;';
  document.querySelector('.css-property').innerText = style;

  var exampleBackground = document.querySelector('#example-bg');
  var exampleText = document.querySelector('#example-text');
  exampleBackground.style.backgroundColor = getOppositeColor(color);
  exampleText.style.color = getOppositeColor(color);
  var textShadow = style.replace(/text-shadow: /, '').replace(/\n/g, '').replace(/.$/, '').replace(/\u00a0\u00a0\u00a0\u00a0/g, '');
  exampleText.style.textShadow = textShadow;
}

A: Simple outline behind the letters.
Works with any font. With any outline width.

<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
  <text x="50%" y="50%" dominant-baseline="central" text-anchor="middle">Text</text>
</svg>

Codepen: https://codepen.io/RilDev/pen/vYeOjgj?editors=1000

A: I'm sorry, but if you've gotten this far, you'll realise that all the other answers are inadequate or require SVG.

Note: This beautiful outlining will cost you the small price of maintaining a copy of the text in a data-content attribute, which is used by a layered CSS3 ::before element that renders the fill text over the actual outline.

.outline {
  color: black;
  -webkit-text-stroke: 0.15em black;
}

.outline::before {
  content: attr(data-content);
  -webkit-text-fill-color: white;
  -webkit-text-stroke: 0;
  position: absolute;
}

.outline-wrapper {
  font-family: "DaytonaW01-CondensedBold", Impact, Times, serif;
  font-size: 50px;
}

Take-Two v Anderson

<link href="https://db.onlinewebfonts.com/c/998b5de3cda797387727724405beb7d4?family=DaytonaW01-CondensedBold" rel="stylesheet" type="text/css"/>

The external style link is just to include the font, and is not required -- though using a thin font may require adjustment to the stroking parameter.

A: I was looking for a cross-browser text-stroke solution that works when overlaid on background images. think I have a solution for this that doesn't involve extra mark-up, js and works in IE7-9 (I haven't tested 6), and doesn't cause aliasing problems.
This is a combination of using CSS3 text-shadow, which has good support except IE (http://caniuse.com/#search=text-shadow), then using a combination of filters for IE.  CSS3 text-stroke support is poor at the moment.
IE Filters
The glow filter (http://www.impressivewebs.com/css3-text-shadow-ie/) looks terrible, so I didn't use that.
David Hewitt's answer involved adding dropshadow filters in a combination of directions. ClearType is then removed unfortunately so we end up with badly aliased text.
I then combined some of the elements suggested on useragentman with the dropshadow filters.
Putting it together
This example would be black text with a white stroke. I'm using conditional html classes by the way to target IE (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/).
#myelement {
    color: #000000;
    text-shadow:
    -1px -1px 0 #ffffff,
    1px -1px 0 #ffffff,
    -1px 1px 0 #ffffff,
    1px 1px 0 #ffffff;
}

html.ie7 #myelement,
html.ie8 #myelement,
html.ie9 #myelement {
    background-color: white;
    filter: progid:DXImageTransform.Microsoft.Chroma(color='white') progid:DXImageTransform.Microsoft.Alpha(opacity=100) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=-1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=-1);
    zoom: 1;
}

A: Easy!  SVG to the rescue.
This is a simplified method:

svg{
  font   : bold 70px Century Gothic, Arial;
  width  : 100%;
  height : 120px;
}

text{
  fill            : none;
  stroke          : black;
  stroke-width    : .5px;
  stroke-linejoin : round;
  animation       : 2s pulsate infinite;
}

@keyframes pulsate {
  50%{ stroke-width:5px }
}
<svg viewBox="0 0 450 50">
  <text y="50">Scalable Title</text>
</svg>

Here's a more complex demo.
CSS-only:

h1 {
  font: 800 40px Arial;
  -webkit-text-fill-color: transparent;
  -webkit-text-stroke: 1px;
}

I am outlined

 Note that as of writing, the -webkit-text-stroke property cannot be transitioned/animated.

A: Edit: text-stroke is now fairly mature and implemented in most browsers. It is easier, sharper and more precise. If your browser audience can support it, you should now use text-stroke first, instead of text-shadow.

You can and should do this with just the text-shadow effect without any offsets:
.outline {
    color: #fff;
    text-shadow: #000 0px 0px 1px;
    -webkit-font-smoothing: antialiased;
}

Why? When you offset multiple shadow effects, you'll begin to notice ungainly, jagged corners:

Having text-shadow effects in just one position eliminates the offsets, meaning
If you feel that's too thin and would prefer a darker outline instead, no problem — you can repeat the same effect (keeping the same position and blur), several times. Like so:
text-shadow: #000 0px 0px 1px,   #000 0px 0px 1px,   #000 0px 0px 1px,
             #000 0px 0px 1px,   #000 0px 0px 1px,   #000 0px 0px 1px;

Here's a sample of just one effect (top), and the same effect repeated 14 times (bottom):

Also note: Because the lines become so thin, it's a very good idea to turn off sub-pixel rendering using-webkit-font-smoothing: antialiased.

A: Multiple text-shadows..
Something like this:
var steps = 10,
    i,
    R = 0.6,
    x,
    y,
    theStyle = '1vw 1vw 3vw #005dab';
for (i = -steps; i <= steps; i += 1) {
    x = (i / steps) / 2;
    y = Math.sqrt(Math.pow(R, 2) - Math.pow(x, 2));
    theStyle = theStyle + ',' + x.toString() + 'vw ' + y.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',' + x.toString() + 'vw -' + y.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',-' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
}
document.getElementsByTagName("H1")[0].setAttribute("style", "text-shadow:" + theStyle);

Demo: http://jsfiddle.net/punosound/gv6zs58m/

A: Try Following:

<!DOCTYPE html>

Text-shadow effect!

Text-shadow effect!

Text-shadow effect!

Text-shadow effect!

Text-shadow effect!

Text-shadow effect!

Text-shadow effect!

Text-shadow effect!


text:
Q: From C++ image frames to html5 In my C++ application I have video image frames coming from a web camera.
I wish to send those image frames down to a HTML5 video tag element for live video playing from the camera. How can I do this?

A: For a starting point you are going to want to look into WebM and H.264/MPEG-4 AVC.  Both of these technologies are used as HTML5 media streams.  It use to be that FireFox only supported WebM while Safari and Chrome both supported H.264.  I am not sure about their current states, but you will probably have to implement both.
Your C++ will then have to implement a web server that can stream these formats on the fly.  Which may require significant work.  If you choose this route this Microsoft document may be of some use.  Also, the WebM page has developer documentation.  It is possible that H.264 must be licensed for a cost.  WebM allows royalty free usage.
If I am not mistaken neither of these formats has to be completely downloaded in order to work.  So you would just have to encode and flush the current frame you have over and over again.
Then as far as the video tag in HTML5 you just have to provide it the URLS your C++ server will respond to.  Here is some documentation on that.  Though, you may want to see if there is some service to mirror these streams as not to overload your application.
An easier way to stream your webcam could be simply to use FFMPEG.
Another usefull document can be found at:
http://www.cecs.uci.edu/~papers/aspdac06/pdf/p736_7D-1.pdf
I am no expert, but I hope that at least helps you get your start.


text:
Q: Why are my headers null after a POST? I'll lay down my code first:  Note:  I also have log output at the bottom of the question.
Server Side:
@Post
@Consumes("application/octet-stream")
public Representation post(InputStream zip, @HeaderParam(value = "Content-Disposition") HttpHeaders headers) throws Throwable {
    System.out.println(headers); //Prints null - want the header to not be null here
    String uploadedFileLocation = getStartingDir() + "/" + "abc.zip";
    writeToFile(zip, uploadedFileLocation);
    return new StringRepresentation("Uploaded!");
}

Client Side:
public static void main(String[] args) throws Exception {
    final String BASE_URI = "http://localhost:8080/server/upload";

    Client client = Client.create();
    WebResource service = client.resource(BASE_URI);
    client.setChunkedEncodingSize(1024);
    client.addFilter(new LoggingFilter());

    File zip = new File("C:/Users/sdery/Desktop/abc.zip");

    InputStream fileInStream = new FileInputStream(zip);
    String sContentDisposition = "attachment; filename=\"" + zip.getName()+"\"";
    ClientResponse response = service.header("Authorization", "Basic xxx=").header("Content-Disposition", (Object)sContentDisposition).type(MediaType.APPLICATION_OCTET_STREAM).post(ClientResponse.class, fileInStream);
    System.out.println("Response Status : " + response.getEntity(String.class));

}

First off, the file transfer works, I'm happy.  However, I would like to get the headers on the server side so I don't have to hard code the file name.  Any ideas as to why it is comin' up null?  Does it have to do with me using ClientResponse instead of ClientRequest?
Jul 31, 2013 8:44:12 AM com.sun.jersey.api.client.filter.LoggingFilter log
INFO: 1 * Client out-bound request
1 > POST http://localhost:8080/server/upload
1 > Content-Disposition: attachment; filename="abc.zip"
1 > Authorization: Basic xxx=
1 > Content-Type: application/octet-stream

(zip bytes)

INFO: 1 * Client in-bound response
1 < 200
1 < Date: Wed, 31 Jul 2013 12:44:12 GMT
1 < Date: Wed, 31 Jul 2013 12:44:12 GMT
1 < Vary: Accept-Charset, Accept-Encoding, Accept-Language, Accept
1 < Content-Length: 88
1 < Set-Cookie: rememberMe=deleteMe; Path=/server; Max-Age=0; Expires=Tue, 30-Jul-2013   12:44:12 GMT
1 < Content-Type: text/plain; charset=UTF-8
1 < Accept-Ranges: bytes
1 < Server: Restlet-Framework/2.0.4
1 < Real-Token: bar
1 <
Uploaded!

From the log output, it seems that the header containing Content-Disposition is there.  Does this mean I should be able to retrieve the value from the server side code?

A: You're parameter is of the wrong type.  You should declare the parameter as a String.  HttpHeaders is for getting all the headers and is annotated with a @Context.  @HttpParam can only be converted to a limited number of types.
From the Jersey documentation for HeaderParam.

Binds the value(s) of a HTTP header to a resource method parameter, resource class field, or resource class bean property. A default value can be specified using the DefaultValue annotation. The type T of the annotated parameter, field or property must either:

Be a primitive type
Have a constructor that accepts a single String argument
Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String))
Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2 or 3 above. The resulting collection is read-only.

So you're code would be more like
@Post
@Consumes("application/octet-stream")
public Representation post(InputStream zip, @HeaderParam(value = "Content-  Disposition") String contentDisposition) throws Throwable {
   System.out.println(contentDisposition);
   String uploadedFileLocation = getStartingDir() + "/" + "abc.zip";
   writeToFile(zip, uploadedFileLocation);
   return new StringRepresentation("Uploaded!");
}

A: First off, I apologize that my solution is from a JavaScript/PHP reference and not Java, but I believe your solution may be similar.
Add a new header named 'X-FILENAME' and set the name of your file as the header data.  I believe your code would look something like this:
ClientResponse response = service.header("X-FILENAME", "abc.zip");

Then, on your server, you should be able to retrieve that header param (In PHP it is the $_SERVER global, it looks like in yours it may be @HeaderParam).
Also, for reference just in case this applies to you, in PHP when you retrieve the header param you need to use a modified param name by adding 'HTTP_' to the front and changing all dashes to underscores like this 'HTTP_X_FILENAME'.  So on the client you sent 'X-FILENAME' while on the server you retrieve that same value with 'HTTP_X_FILENAME'.
I hope this leads you in the right direction.


text:
Q: "need answer" devoured featured questions When clicking the featured question count to get the list of questions with open bounty, the "need answer" tab gets highlighted:

The list itself is fine, but the highlight should be in the proper place.

A: Typically people who click on "need answer" are looking for a question ...that needs an answer. People who click on the "bounties" call out, look for questions with bounties.
The former is the prevalent use case, and we want to give it a full tab. The latter is a special call out we use to make bountied questions more evident.
I agree that we probably we can iterate a bit more on the way we display these, but joining the two seems out of the question, after all there are not only 12 questions that need an answer.


text:
Q: Is Ohm's Law always exactly true even at the microscopic level? My probability textbook introduction just mentioned that Ohm's Law is not always precisely true at the microscopic level.
How is this possible? What is causing this to happen?

A: Consider the rule that the volume of liquid in a vessel is equal to the height of the liquid times its horizontal cross sectional area.  For vessels whose horizontal cross section is uniform from top to bottom, halving the height of the liquid will halve its volume.  Doubling the amount of liquid, if there's room, will double the volume.
Suppose, however, one removes nearly all of the liquid from the vessel, leaving only two nanoliters.  and then cuts the height of the liquid in half.  Should one expect that exactly one nanoliter would remain?
The relationship between cross-sectional area, height, and volume remains true by definition at any scale, large or small, provided that those quantities are concretely defined numbers.  At very small scales, however, concepts like "volume" become rather nebulous.  If there are only a few hundred molecules bouncing around, it's unclear how much of the space outside each should count as part of the "volume" of liquid, and how much should be considered "empty space".  In such cases, the relationship between height, volume, and cross sectional area doesn't "break down" so much as it becomes less and less meaningful, especially in cases where the cross-sectional area varies widely with height.
To put it another way, when quantities get very small, measurement uncertainties get very big.  When quantities get so small that measurement uncertainties get to be as big as the measurements, Ohm's Law will still hold, but will cease to have much predictive value.

A: On a microscopic level everything changes. You can't measure precisely anything! Also the known form of Ohm's Law is used with good results only in circuit theory. This form is also an approximation. Ohm's Law is derived (like all electromagnetism equations) from Maxwell equations so its general form is:
$$J=\sigma \cdot E$$
Every theory that tries to describe a microscopic phenomenon uses probabilities and statistics (as you can see yourself by reading this in such a book) and as a result every quantity can only be an approximation. Exactly the same goes for Ohm's Law.
Also if someone tried to find precisely one of the quantities that appear in the equation he should take an infinite number of samples for the rest of the quantities so to have zero error. This is not only impossible given that no one can live forever but also impossible based on that in order to take infinite samples of J you have to be able to count all electrons which obviously is also impossible. All in all it is just an approximation.

A: I think Ohm's law works because the electrons do a lot of scattering.
For distances that are on the order of the scattering length, you might see non-ohmic behavior.

A: Ohm's Law is a simple equation that can be derived from the equations that describe the microscopic behaviour of electrons by averaging those equations over long time and spatial scales.
Although it is not often stated, the voltage, current and resistant that appear in Ohm's Law are average values.
On a microscopic level, the current flowing through some surface is not nice and smooth, rather it looks quite random as electrons move across that surface. If your surface is too small, you will have to wait a long time before you see any electrons (and hence any current). Similarly if you don't wait long enough, you may not see any electrons at all, or you may even see electrons moving in the opposite direction to what the average current actually is. Remember that electrons jiggle around in a conductor in a mostly random way - only on average do they move together in one direction.
So you have to wait a long time and look at big areas so you can build up the statistics to get a nice average theory. That theory is Ohm's Law.


text:
Q: How to automate moving words in excel in the same column I'm not good with excel, my knowledge is very limited, but I'm stuck with a project where I have 3,077 rows. There are a few columns where I need to move around a few words or numbers. All I need right now is to know how to do it in one column, or if it's even possible. I have a list of addresses and 90% of them have been entered incorrectly. Rather than go through each one one by one I'm hoping there's something I can run to swap the word or number around. If need be I can create a new column.
Below is an example. The first two are correct, the next four are not. I need the second number to be after ROAD or after HWY. i.e. 6 ROAD 3066 or 1059 HWY 516. Thank you for your help in advance.
42 ROAD 3050
68 ROAD 3400
6 3066 ROAD
1059 516 HWY
986 516 HWY
33 3403 ROAD

A: If I understand correctly, your task is as follows:

*

*your have three columns

*one of them is not a number

*you want to have them in order number/text/number

Your input cells are A1/B1/C1. Then create the following additional columns:

*

*D1 = IF(ISNUMBER(A1);A1;B1)

*E1 = IF(ISNUMBER(A1);IF(ISNUMBER(C1);B1;C1);A1)

*F1 = IF(ISNUMBER(C1);C1;B1)
Those are then the desired output columns.


text:
Q: What is ()=>{} in JavaScript? I was reading some Nodejs JavaScript examples and found something I have never seen before. What is ()=>{} syntax? I tried googling it but not sure what keyword to put in.
  rl.on('line', (input) => {
    console.log(`Received: ${input}`);
  });

A: It's arrow function which comes in ES6 to define function in new way.
Check the reference here
Example:
let square = x => x * x;
let add = (a, b) => a + b;
let pi = () => 3.1415;

console.log(square(5));
console.log(add(3, 4));
console.log(pi());


text:
Q: how to get value from python and show in webpage using php I have a PHP file called display.php and a python file giveDATA.py.
from giveDATA.py, this is output: (77, '8088800000')
I would like to capture this output in separate variables in PHP and print one by one on a webpage.
1) display.php
<html>
<body>
<?php
    $command = escapeshellcmd('C:/guna/python/giveDATA.py');
    $x = shell_exec($command);
    echo "<pre>$x</pre>";
?>
</body>
</html>

2) giveDATA.py
In my python file I am getting values from a table:
    results=cursor.fetchall()

            for x in results:
                print(x)
            connection.commit()

A: The shell does not know that you want to run a script because you`re just giving it a path. Replace this:
$command = escapeshellcmd('C:/guna/python/giveDATA.py');

With this:
$command = escapeshellcmd('python3 C:/guna/python/giveDATA.py');


text:
Q: wireshark-How to convert the ip into hostname using tshark I used the below command to get the list of IP address of various entity,but i am not able to convert (identify) the hostname.
 tshark -r test_call_1.pcap -T fields -e ip.src -e tcp.srcport -e ip.dst -e tcp.dstport  tcp

sample output
192.30.16.95    21      192.30.160.2    43118
192.30.16.95    21      192.30.160.2    43118
192.30.16.95    21      192.30.160.2    43118
192.30.160.2    45791   192.30.16.95    45431

Can any one guide me on how to resolve these ip's to hostnames?
Thanks in Advance
M.Muralidharan

A: To get tshark to print hostnames you need to enable hostname resolution by specifying the '-N n' option and selecting the hostname fields instead of the ip address by using e.g '-e ip.src_host'.
For example:
tshark -r test_call_1.pcap -N n -T fields -e ip.src_host -e tcp.srcport -e ip.dst_host -e tcp.dstport tcp


text:
Q: Redux: how does state know which child reducer should be picked when an action arrives? When reading the documentation of Redux library, I have a question about combineReducers.
Phase1: single reducer
When we have a single reducer, it handles all kinds of action types.
export default function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1
    case 'FOO'
      return state + 100
    case 'BAR'
      return state - 100
    case 'SHOW_ME_THE_MONEY'
      return state + 10000000000
    default:
      return state
  }
}

Phase2: we separate them to different reducers
Well, you have a code reviewer who said it's not good to have one god reducer to handle all actions. Please create different reducers to do different things.

*

*cheat: SHOW_ME_THE_MONEY / FOO / BAR

*counter: INCREMENT / DECREMENT

.
export default function cheat(state = [], action) {
  switch (action.type) {
    case 'FOO'
      return state + 100
    case 'BAR'
      return state - 100
    case 'SHOW_ME_THE_MONEY'
      return state + 10000000000
  }
}

export default function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1

    default:
      return state
  }
}

then, we combine them to one using combineReducers.
import { combineReducers } from 'redux'
import todos from './cheat'
import counter from './counter'
export default combineReducers({
  cheat,
  counter
})

then, we dispatch an action to state.
store.dispatch({
  type: 'SHOW_ME_THE_MONEY',
  text: 'To Buy new Macbook Pro 16'
})

Question
When an action FOO arrives, how does the state know which child reducer should be picked and used for calculating the new state?
I suppose a mapping between action type and reducer is essential, but it seems unnecessary, which is demoed in the documentation.

*

*FOO -> cheat reducer

*BAR -> cheat reducer

*SHOW_ME_THE_MONEY -> cheat reducer

*INCREMENT -> counter reducer

*DECREMENT -> counter reducer

A: combineReducers is only doing a mapping between your child reducer key (cheat, counter) and the corresponding slice of the state (state.cheat, state.counter).
The redux basic tutorial walks you through this concept called reducer composition.
Child reducers receive all actions but only their slice of the state:

let {
  createStore,
  combineReducers
} = Redux

function cheat(state = 0, action) {
  console.log("cheat reducer receive action: ", action.type)
  console.log("cheat reducer slice: ", state)
  switch (action.type) {
    case 'FOO':
      return state + 100
    case 'BAR':
      return state - 100
    case 'SHOW_ME_THE_MONEY':
      return state + 10000000000

    default:
      return state
  }
}

function counter(state = 0, action) {
  console.log("counter reducer receive action: ", action.type)
  console.log("counter reducer slice: ", state)
  switch (action.type) {
    case 'INCREMENT':
      return state + 1
    case 'DECREMENT':
      return state - 1

    default:
      return state
  }
}

let combined = combineReducers({
  cheat,
  counter
})
let store = createStore(combined)

store.subscribe(() => console.log("store state: ", store.getState()))

store.dispatch({
  type: 'INCREMENT'
})
store.dispatch({
  type: 'INCREMENT'
})
store.dispatch({
  type: 'FOO'
})
store.dispatch({
  type: 'BAR'
})
store.dispatch({
  type: 'SHOW_ME_THE_MONEY'
})
<script src="https://unpkg.com/redux/dist/redux.js"></script>

A: this official redux FAQ is provided by @louisbl as a comment, but I think it's very helpful, deserved to be exposed as an answer.

Redux FAQ: Actions
A given action could be handled by all, some, or none of them. This keeps components decoupled from the actual data changes, as one action may affect different parts of the state tree, and there is no need for the component to be aware of this. Some users do choose to bind them more tightly together, such as the "ducks" file structure, but there is definitely no one-to-one mapping by default, and you should break out of such a paradigm any time you feel you want to handle an action in many reducers.

Another relating question is:
Redux can I use one action type in separate reducers?


text:
Q: Choosing a controller and routes for a join table I'm building a favorites feature.
For instance:
class User < ActiveRecord::Base
  has_many :favorites
end

class Product < ActiveRecord::Base
  has_many :favorites
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :product
end

Scenario
I have a list of products, and I want to add a [+] Add to favorites link next to each product.
My questions

*

*Do I wrap the entire listing in a form tag so I can use POST to some controller -- or do I do something with a link_to_remote tag?

*Do I use the create action of the product controller, or should I use the favorites controller - or even the user controller (because it's the User's favorites)?

As you can see I am unsure of where to put code for a join table. Who "owns" what? I'm afraid of using bad anti patterns.

A: you can setup the associations in your routes as well such as
resources :products do
  resources :favorites
end

this will allow you to handel the creation of favorites from your favorites controller
than you can wrap adding more favorites with link_to_remote linking it to your favorites#create


text:
Q: SQL Join multiple tables with the same column names I'm guessing this is very simple but I'm totally new to this.
Could you please help to join these 3 or more tables with the same column name into one large table. Examples given below. I have table 2017 to 2019 and the resultant image at the bottom is what I am trying to get.
What is the SQL BigQuery code for this? Thanks!

--------WHAT I AM TRYING TO ACHIEVE ---------------

A: I'm pretty sure you want union all:
select t.*
from table_2017 t
union all
select t.*
from table_2018 t
union all
select t.*
from table_2019 t;

The use of t.* is a convenience, assuming the tables have the same names, in the same order with compatible types.  I recommend listing the columns explicitly.
Note:  You should probably fix your data model.  Having multiple tables with the same columns is not a good data model.  All this data should be in one table.


text:
Q: How to show in menu apps of different desktop environments? I have installed different environment flavours (Unity, Mate, Xfce, KDE...) on my machine. I have set on login to use Xfce. But there are some apps/software in the other environments which I would like to use without doing a logout/login to that other desktop and without trying to discover what that particular program's command is so I can run it from terminal right from Xfce.
I would like to have all those apps listed in my menu, in an automated way (So "create every shortcut entry from scratch" answers should be excluded).

A: I suspect the key lies in the content of .desktop files most commonly found in /usr/share/applications. (A user may also have some .desktop files placed in $HOME/.local/share/applications automatically or manually.)
The format of .desktop files is usually based on specifications laid down by freedesktop.org.
Of interest here, are two entries:
NoDisplay

means "this application exists, but don't display it in the menus". This can be useful to e.g. associate this application with MIME types, so that it gets launched from a file manager (or other apps), without having a menu entry for it (there are tons of good reasons for this, including e.g. the netscape -remote, or kfmclient openURL kind of stuff).

OnlyShowIn, NotShowIn

A list of strings identifying the desktop environments that should display/not display a given desktop entry.
By default, a desktop file should be shown, unless an OnlyShowIn key is present, in which case, the default is for the file not to be shown.

On my system which is just "KDE", I see:
$ grep -E "NoDisplay"  /usr/share/applications/*.desktop
/usr/share/applications/display-im6.desktop:NoDisplay=true
/usr/share/applications/display-im6.q16.desktop:NoDisplay=true
/usr/share/applications/geoclue-where-am-i.desktop:NoDisplay=true
/usr/share/applications/hplj1020.desktop:NoDisplay=true
/usr/share/applications/ktelnetservice5.desktop:NoDisplay=true
/usr/share/applications/kwalletmanager5-kwalletd.desktop:NoDisplay=true
/usr/share/applications/libreoffice-math.desktop:NoDisplay=false
/usr/share/applications/libreoffice-startcenter.desktop:NoDisplay=false
/usr/share/applications/libreoffice-xsltfilter.desktop:NoDisplay=true
(plus many more entries)

$ grep -E "OnlyShowIn"  /usr/share/applications/*.desktop
/usr/share/applications/org.kde.kcolorschemeeditor.desktop:OnlyShowIn=KDE;
/usr/share/applications/org.kde.kinfocenter.desktop:OnlyShowIn=KDE;
/usr/share/applications/org.kde.kmenuedit.desktop:OnlyShowIn=KDE;
/usr/share/applications/org.kde.plasmashell.desktop:OnlyShowIn=KDE;
/usr/share/applications/org.kde.polkit-kde-authentication-agent-1.desktop:OnlyShowIn=KDE;
/usr/share/applications/systemsettings.desktop:OnlyShowIn=KDE;
$

$ grep -E "NotShowIn"  /usr/share/applications/*.desktop
/usr/share/applications/kdesystemsettings.desktop:NotShowIn=KDE;
/usr/share/applications/libreoffice-math.desktop:NotShowIn=GNOME;
/usr/share/applications/libreoffice-startcenter.desktop:NotShowIn=GNOME;
/usr/share/applications/org.kde.kdeconnect.kcm.desktop:NotShowIn=KDE;
/usr/share/applications/org.kde.kdeconnect.nonplasma.desktop:NotShowIn=KDE;
/usr/share/applications/org.kde.klipper.desktop:NotShowIn=KDE;
/usr/share/applications/system-config-printer.desktop:NotShowIn=KDE;GNOME;
$

As you'll gather for yourself if you run the commands given above on your system, there may be good reason for some applications not being included in menus, either of the original desktop environment or in any other. In some cases, there may not be a reason that you feel is valid.
If you do want to change the status of display for certain applications, I suggest you copy the corresponding .desktop file over to ~/.local/share/applications and make your changes there. Changes made there will

*

*not need sudo

*be only for you and not for other users

*be unchanged if/when the application is updated whereas the .desktop file in /usr/share/applications will be overwritten.

A: You can use alacarte to edit the app menu. It's not like making every shortcut from scratch, neither is it automated...
In some versions of alacarte, software from other desktop environments are also shown...


text:
Q: What does "Heaven" mean here Does "Heaven" have the same meaning as "God" here?

Couldn't keep it in,Heaven knows I tried.

It is in the animation "Frozen" in the Elsa thought.
Just another question: do we have to write "Heaven" or "heaven" when it is not the first word of the sentence?

A: "Heaven knows" and "God knows" are interchangeable.
Capitalization is a bit more tricky. Usually, "Heaven", "Hell", "God", "Lord", etc. refer to the Christian concepts of those and should start with an upper-case letter. However, when talking about general concepts, they usually don't.
Notice the difference in capitalization between:

With God as my witness, I shall exact my vengeance on you.

and

Zeus was a god worshiped in Ancient Greece.

A: Without repeating the other good answers, I want to add a note about why this line is confusing to an English language learner: It's missing punctuation. Song lyrics are often written without punctuation, or with very sloppy punctuation. With the missing punctuation supplied, it would be
Couldn't keep it in! Heaven knows I tried.

Because song lyrics are written with such sloppy punctuation, don't worry too much about why things are capitalized a certain way. It may very well be wrong.
As I wrote in a comment, according to style guides, heaven is not usually capitalized (except for reasons unrelated to the word itself), even when it refers to the Christian heaven.
Heaven knows or God knows is a mild oath, emphasizing the truth of the statement "I tried." It's similar to the stronger oath "(as) God is my witness."

A: I should make a couple of remarks.

*

*Heaven (capitalized) is not necessarily the same as heaven (not capitalized). Depending on the context, Heaven usually refers to a heaven from a religious context, for example, Heaven in Christianity. In such a case, Heaven is a proper noun.

*Similarly, God (capitalized) is not necessarily the same as god. Depending on the context, God usually refers to a god from a religious context, for example, God in Abrahamic religions. In such a case, God is a proper noun.

Do we have to write Heaven or heaven when it is not first in the sentence?

It depends. If it is a reference to, for example, the Christian one, it appears that you can choose to capitalize it. Even the Christian bible has an instance in which it is not capitalized. As for the reference to the Chicago Manual of Style

8.108 Heaven, hell, and so on
  Terms for divine dwelling places, ideal states, places of divine punishment, and the like are usually lowercased (though they are often capitalized in a purely religious context)

So if your audience understands that you are writing in a religious context, then you are free to capitalize it.
If it is a generic or secular heaven and not a proper noun, then it should be written as heaven.
Returning to the lyrics, I understood them to be

Couldn't keep it in
  Heaven knows I tried

with the line break and without the period. While writing a post, people often hit enter/return for a line break, but the line break doesn't display. So, I assumed that's what OP meant to display. It makes sense that there are no punctuation marks since lyrics found online are generally poorly written and often omit proper punctuation. Having it displayed this way, "Heaven" is at the beginning and should be capitalized.
If the word "H/heaven" is found elsewhere in the sentence, like at this site

Couldn't keep it in, heaven knows I tried!

then I believe it should not be capitalized, for the reason I give below.

Does "Heaven" have the same meaning as god here?

I assume you meant God (for example, in the Christian sense). Since this is a Disney movie and Disney does not produce religiously affiliated material, heaven would be a secular term and not a proper noun. Since we are speaking of heaven in a secular sense, then no, heaven does not mean the same thing as God. However, the expression is still understood to have the same meaning as "God knows".
Now, if it was, for example, a Christian person writing and chose to write Heaven instead of heaven, then yes, it is possible that Heaven meant the same thing as God. Heaven is often a euphemism or allusion to God in Christianity. So one could say that, in such an instance, Heaven meant the same thing as God. Further, "Heaven knows" would also mean the same thing as "God knows".

A: Max's and LarsH's answers are solid, but they're missing a nuance of the difference between "Heaven knows" and "God knows" which should be made clear.
Theoretically these expressions are interchangeable, but there is a slight difference in how they could be taken by particularly religious people. There are some speakers who view use of "God" in an idiomatic expression, or in any context in which one is not reverently speaking of or to the deity, to be (at least mildly) offensive. (For discussion elsewhere, see here and here).
Disney, obviously, would want to make its movies as family-friendly as possible, and so will go for the version that has the least chance of offending people.
Another consideration is that in this context, "heaven" scans better. "Heaven" has two syllables, with the emphasis on the first syllable, while "God" has only one syllable. Even more important, it ends on a "d" which would make the word come to an abrupt stop when singing it. So singing "Heaven knows I tried" has the same pattern of emphasized-syllable followed by non-emphasized syllable. "God knows I tried" would either make the singer stretch the word "God" awkwardly, or give an awkward gap in the singer's performance of the line.
I know this is a little beyond what you asked about, but when you're trying to figure out why someone said something one way instead of another, these are always important considerations: both levels of politeness, and the ways that rhythm and sound affect how we use language. These ideas will become more and more important as you continue your journey through learning English!

A: It has been noted that Heaven refers to a place in the afterlife, but in this case, Heaven means more than that.  The word Heaven can also refer to the Being or beings in Heaven; similar to how, in the press, the phrases "the White House announcement" or "Scotland Yard's policies" or "Pyongyang's military brass" could refer to an official statement by an American President or cabinet, or the rules of London's police department, or the military advisors of North Korea's government.
Thus, the word "Heaven", in this context, most likely refers to G-d himself.  Also, consider this quote from the ancient Chinese philosopher Mozi.  Here, the Chinese word Tian is translated "Heaven", but you can tell that he was referring to the Deity.

Moreover, I know Heaven loves men dearly not without reason. Heaven ordered the sun, the moon, and the stars to enlighten and guide them. Heaven ordained the four seasons, Spring, Autumn, Winter, and Summer, to regulate them. Heaven sent down snow, frost, rain, and dew to grow the five grains and flax and silk that so the people could use and enjoy them. Heaven established the hills and rivers, ravines and valleys, and arranged many things to minister to man's good or bring him evil. He appointed the dukes and lords to reward the virtuous and punish the wicked, and to gather metal and wood, birds and beasts, and to engage in cultivating the five grains and flax and silk to provide for the people's food and clothing. This has been so from antiquity to the present.

Regarding capitalization, the word "God" is always capitalized in a monotheistic context.  Thus, "God", "Allah", "Jehovah", and so on.  The words "heaven" and "hell" and "purgatory" can be capitalized, as they are proper nouns, the names of specific places, but people frequently fail to capitalize them.  It really doesn't matter.  On the other hand, people seldom fail to capitalize the name of the Supreme Being.

A: Heaven knows is an idiom. The meaning comes from these two words together. 'Heaven' doesn't have much or any independant meaning here.
The phrase 'heaven knows' serves to emphasise the statement "I tried [to keep it in]"
See this definition of Goodness/God/Heaven/Christ knows from the Cambridge English Dictionary:

used to mean "I don't know" or to emphasize a statement. Some people may find this use offensive:


text:
Q: One-at-a-time-Value Anomaly Detection Model with LSTM Autoencoder : Is it possible? I'm currently working on a project about anomaly detection in dataflow, such as bank transaction file (so time series datasets). The datas I'm working on take the form of quite small datasets, with one additionnal value arriving each month, corresponding to one client bank account info (in the case of bank transaction file, account amount). I'm currently testing an AutoEncoder model to detect manually added anomalies in those datasets, but :
I would like to know if it is possible to train my model, an AutoEncoder model, on previous values received, like a dataset of 50 to 100 element in size; and then test the next value received on this model, to check its relevance towards the whole dataset.
Anomaly detection with AutoEncoder is based, in this/my case, on the calculation of a threshold to separate normal values to anomaly values : I based my threshold calculation on the MAE Loss values between predicted and ground truth values. But it implies quite an amount of datas in the tested part to generate enough relevant loss values to compare to the threshold, and that's my problem because with only one value, my loss value is absurd and not relevant at all towards the training set loss values and threshold.
I hope I have been clear enough in the description of my problem, and thank you in advance for your help !
**Here is my work path below **

*

*Datas I fed to my model to train on:

First, because it's a time series dataset, I create sequence of X data from the dataset, and I assign to it the X+1 data :

def create_sequences(X, y, time_steps=TIME_STEPS):
    X_out, y_out = [], []
    for i in range(len(X)-time_steps):
        X_out.append(X.iloc[i:(i+time_steps)].values)
        y_out.append(y.iloc[i+time_steps])

    return np.array(X_out), np.array(y_out)

X_train, y_train = create_sequences(train[[column_[1]]], train[column_[1]])

*

*Then I fit the model with X and y values and make a prediction on training data :

history = model.fit(X_train, y_train, epochs=100, batch_size=32, validation_split=0.1, callbacks=[keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, mode='min')], shuffle=False)

*

*I compare prediction on training data to ground truth training data :

X_train_pred = model.predict(X_train)
train_mae_loss = np.mean(np.abs(X_train_pred - X_train), axis=1)

*

*I establish a threshold :

threshold = np.mean(train_mae_loss) + 2*np.std(train_mae_loss)

*

*I do the same with testing data, and compare the loss values from it to the threshold value from the training datas :

anomaly_df['anomaly'] = anomaly_df['loss'] > anomaly_df['threshold']


text:
Q: Formatting a text file, how to update the file after I finished parsing it? How would I open a file, perform some regex on the file, and then save the file?
I know I can open a file, read line by line, but how would I update the actual contents of a file and then save the file?

A: The following approach would work regardless of file size, and will also not corrupt the original file in anyway if the operation would fail before it is complete:
string inputFile = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments), "temp.txt");
string outputFile = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments), "temp2.txt");
using (StreamReader input = File.OpenText(inputFile))
using (Stream output = File.OpenWrite(outputFile))
using (StreamWriter writer = new StreamWriter(output))
{
    while (!input.EndOfStream)
    {
        // read line
        string line = input.ReadLine();
        // process line in some way

        // write the file to temp file
        writer.WriteLine(line);
    }
}
File.Delete(inputFile); // delete original file
File.Move(outputFile, inputFile); // rename temp file to original file name

A: string[] lines = File.ReadAllLines(path);
string[] transformedLines = lines.Select(s => Transform(s)).ToArray();
File.WriteAllLines(path, transformedLines);

Here, for example, Transform is
public static string Transform(string s) {
    return s.Substring(0, 1) + Char.ToUpper(s[1]) + s.Substring(2);
}

A: Open the file for read. Read all the contents of the file into memory. Close the file. Open the file for write. Write all contents to the file. Close the file.
Alternatively, if the file is very large:
Open fileA for read. Open a new file (fileB) for write. Process each line of fileA and save to fileB. Close fileA. Close fileB. Delete fileA. Rename fileB to fileA.

A: Close the file after you finish reading it
Reopen the file for write
Write back the new contents


text:
Q: New to javascript syntax from Java I am working on detecting OS version using javascript. I have an understanding of Java but some Javascript syntax is just confusing like this one below:
    var os = (function() {
        var ua = navigator.userAgent.toLowerCase();
        return {
            isWin2K: /windows nt 5.0/.test(ua),
            isXP: /windows nt 5.1/.test(ua),
            isVista: /windows nt 6.0/.test(ua),
            isWin7: /windows nt 6.1/.test(ua)
        };
    }());

I am not sure why we have colons : in the return statement and what exactly are they doing.
Also what is the purpose of / / and the text in between?
Is it returning a boolean? or a String?
Also, why do we have
     }());

in the end?
I would just type
    }

instead
Thank you for taking your time to read through. I know this code works for me but I would like to learn why.
Thanks.

A:
I am not sure why we have colons : in the return statement

The right hand side of the return statement is an object literal. The colons separate the property name (on the left) from the value (on the right).

Also what is the purpose of / / and the text in between?

Those are regular expression literals.

Is it returning a boolean? or a String?

Neither, it is returning an Object.

Also, why do we have }()

This is an immediately invoked function. os is the return value of the function, not the function itself.
In this example, it allows the ua variable to be used in a local scope.

A: The function returns an object with 4 properties (isWin2K, isXP, etc), each of them having a boolean value. You can use it like this:
if (os.isXP) {
  // Windows XP specific code
}

The colon is part of the syntax of declaring an object literal:
var a = { prop1 : val1, prop2 : val2 };

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals
The thing that looks like a string but is between / instead of ' or " is called a literal RegExp.
Read more here: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions
Finally, all the useful code there is wrapped in an Immediately Invoked Functional Expression (IIFE). It is a common structure used in JavaScript to prevent the pollution of a scope (usually the global scope) with variables. As you will soon learn, JavaScript has function scope, so if you want to isolate some variables and have them "local" you need to wrap them in a function. The IIFE does just that, but it is also called immediately, so the instructions are executed on that spot, just like if the wrapper function didn't exist:
var b = 10;
a = b + 5;

is equivalent to
(function() {
var b = 10;
a = b + 5;
}) ();

except that the second sollution doesn't introduce the b variable in the outer scope.
Read more here: http://en.wikipedia.org/wiki/Immediately-invoked_function_expression

A:
I am not sure why we have colons : in the return statement and what exactly are they doing.

In your given code, the return {r:val} is actually returning an object. In Javascript:
var obj = {
    r: 'some value',
    t: 'some other value'
};

is functionally equivalent to:
var obj = new Object();
obj.r = 'some value';
obj.t = 'some other value';

so the following portion of your code:
return {
            isWin2K: /windows nt 5.0/.test(ua),
            isXP: /windows nt 5.1/.test(ua),
            isVista: /windows nt 6.0/.test(ua),
            isWin7: /windows nt 6.1/.test(ua)
        };

is actually returning an object as described with the above example. let us now replace return {r:val} with return obj. so your given function have the form:
var os = ( function()
                     {
                       return obj
                     }());

now study about javascript function a little. This page will give you a very good insight for javascript function.