text:
Q: Navigate from facebook tab to canvas page My facebook application has a tab the user can install. On this tab, there is links that are suppose to link to application canvas (ex.: apps.facebook.com/my-app).
It seems that when I'm on my user profile tab and click on a link, Facebook loads the page inside the tab. How do I force it to navigate out of the tab and into the canvas page?

A: You need to use full urls instead of relative urls.
For example:
Link -> Renders on tab
Link -> Renders application page

Good luck!

A: You can also use the regular rails link_to function and pass :only_path => false. This will include the host name into your URL which will be your app's canvas page. When you click it within a Facebook tab, you will go to the app's canvas page instead of staying in the tab.
<%= link_to "Leave the tab", :controller => 'home', :only_path => false %>

A: Use parent attribute in anchor tag.
For example:
Click Me

This will solve it.


text:
Q: the values inside class not changing i want to change the values inside of class but its not changing
here my code
//html
<menu class="box">a</menu><menu class="box">b</menu><menu class="box">c</menu><menu class="box">d</menu>

//javascript
<script type="text/javascript">

var box = document.getElementsByClassName('box');
var after = ['html', 'css', 'js' , 'jquery']

for (i = 0; i < box.length; i++) {
  box[i].value = after[i];

}

A: To change the class name, use
var boxes = document.getElementsByClassName('box');
var after = ['html', 'css', 'js' , 'jquery']

for (i = 0; i < box.length; i++) {
  boxes[i].className = after[i];
}

From the MDN Docs
Which would give you
<menu class="html">a</menu><menu class="css">b</menu>
<menu class="js">c</menu><menu class="jquery">d</menu>

To change the actual value of each element, you would use innerHtml
var boxes = document.getElementsByClassName('box');
var after = ['html', 'css', 'js' , 'jquery']

for (i = 0; i < box.length; i++) {
  boxes[i].innerHTML = after[i];
}

Which would give you
<menu class="box">html</menu><menu class="box">css</menu>
<menu class="box">js</menu><menu class="box">jquery</menu>

A:

var box = document.getElementsByClassName('box');
var after = ['html', 'css', 'js', 'jquery'];
var j = 2;
for (i = 0; i < box.length; i++) {

  $('.box:nth-child(' + j + ')').html(after[i]);
  var j = j + 1;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<menu class="box">a</menu>
<menu class="box">b</menu>
<menu class="box">c</menu>
<menu class="box">d</menu>

try his

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is this sentence incorrect? In my understanding, determiners are categorized into three subgroups: predeterminers, central determiners and postdeterminers. Articles (a, an, the) and possessive determiners are identified as central determiners.
In my book, Is the following sentence is identified as correct?
I believe it is.

This is the Tim's book.

However, this sentence does not sound right even though the two sentences used same determiner from the same group.

This is the my book.

A: You textbook is grossly incorrect.  Neither of those sentences is correct unless you have strangely named items that require books.
To dissect this problem look at the sentence more carefully:
Would you say:

This is the Tim.
  This is the me.  (My is the possessive form of me)

If the answer is no, then you would likewise never use the possessive forms of those structures.
The only way you would say that is if you have an object called a Tim and there is only one of them.  Likewise an item called a me ...
The correct way to state this is:

This is Tim's book.  (No article required.)
  This is my book.  (No article required.)

A: It is a general rule that in the position of the article (the, a/an) you can only use one sort of "article-words".
You can say 1 my little dog or 2 the little dog, but can't use two article words in the article position.
So *the my dog is wrong.
The sense of this rule is clear. When you use an article word such as "the, this, my" you make a selection of what you speak.
Either you point to the thing you talk about (this thing) or you talk about a thing that belongs to you (my thing)  or you indicate
that you talk about something that  was just talked about and the person talked to knows exactly of what thing you talk (the thing)
or you talk about a thing the other person does not know (a  thing).
With one sort of article words the thing talked about is clearly defined or selected.  So it is not reasonable to indicate two
criteria of selection.

A: Books, when not referred to by title, are in the category of count nouns in English: intuitively, discrete items that can be readily counted.  (Contrast mass nouns: rice, sand, water.)  The "standard" varieties of English1 require determiners in front of most uses of count nouns.  The and a are the most common determiners, but other words can play the role.  Only the starred sentences below are incorrect:2

This is a book
  This is the book
  This is my book
  This is Tim's book
  This is the farmer's book

but

* This is book   (determiner may not be completely omitted)
* This is the my book  ("my book" is sufficient, an extra the is not allowed)
* This is farmer's book ("farmer" is itself a count noun, so it too must have a determiner)

Now, compare "Tim's book" and "farmer's book."  Farmer is a count noun.  Tim is also technically a count noun. There are many people named Tim, you can have a specific number of them in a room, etc.  But a more specific rule triggers: Tim is a proper noun.  Even though there are many people named Tim, they are not considered to be interchangeable the way "farmers" might be.  If you just say "Tim" you are, normally, speaking of a specific person, and your interlocutor will probably demand clarification if it's not obvious which one.  ("This is Tim's book" -> "Tim from the bowling alley?" -> "Yeah, him.") Therefore, Tim's all by itself works as a determiner:

This is the farmer's book
  This is Tim's book
?? This is the Tim's book

I'm not going to say the sentence tagged with two question marks is wrong, but it would require an unusual context where "Tim" was acting as a role rather than a proper name.  In a theatrical production, perhaps, "the Tim" could mean "the actor who is playing the role of Tim today." But even then, a book that this character needs to carry onstage at one point would probably be referred to as "Tim's book" and not "the Tim's book."
1 I would not be at all surprised to learn that varieties of English with recent influence from other languages have different rules for determiners.
2 Descriptivist's "correct" and "incorrect" = "native speakers of this variety of this language consistently and unconsciously honor this rule, except for deliberate stylistic effect."


text:
Q: MISRA: Compound Assignment operators I have taken over code that has a lot of compound assignment operators in it.
I think that compound operators are not 'really' MISRA compliant.
I can't seem to find any reference to them.
I believe I understand what is happening and that it should actually be separated.
UINT16 A |= B; /* Incorrect */
UINT16 A = (UINT16)((UINT32)A | (UINT32)B); /* Correct */
UINT16 A <<= 1u; /* Incorrect */
UINT16 A = (UINT16)((UINT32)A << (UINT32)1u); /* Correct */

So, my questions are:

*

*Does MISRA frown upon compound assignments?

*Is there any kind of quick fix, instead of ignoring the warning?

Thank you,

A:
Does MISRA frown upon compound assignments?

Not as such. The rules for compound assignment are similar to the rules for simple assignment. MISRA speaks of assignment operators in general times, including all of them.
MISRA does however frown upon implicit type promotions, see Implicit type promotion rules. You can't understand these MISRA warnings unless you understand implict promotions.

Is there any kind of quick fix, instead of ignoring the warning?

You can't really fix this without understanding the warning. The only quick fix is to only use uint32_t everywhere and never signed or small integer types, but that isn't always feasible. Your original code would have been compliant if all variables were uint32_t.
In general, the latest MISRA only allows various conversions between types of the same essential type category. Unsigned integers is one such category, signed integers in another, and so on.
It isn't easy to tell how exactly your code violates MISRA without knowing the type  of B and sizeof(int). This has nothing to do with compound assignment as such, except that compound assignment operators are a bit cumbersome to work with when it comes to implicit promotions.
MISRA frowns upon assigning the value of an expression (after implicit promotion) to a narrower essential type of the same category or to a different category. In plain English you shouldn't for example assign the result of a uint32_t operation to a uint16_t variable or a signed result to an unsigned variable. This is most often fixed with casting at appropriate places.

Regarding your specific examples, assuming B is uint16_t and the CPU is 32 bit, you get problems with implicit type promotion.
Since A |= B is equivalent to A | B, the usual arithmetic conversions will promote the operands to int in case of 32 bit CPU. So it is a signed 32 bit type.
Assume you had A << 31u - then this would actually have invoked an undefined behavior bug, which the rule seeks to protect against.
Sufficient fixes for MISRA-C compliance:
A = (uint16_t) (A | B); // compliant
A = (uint16_t) ((uint32_t)A << 1u) // compliant


text:
Q: Website displays in chrome perfectly, but not in mozilla or IE here are the code snippets for the html and css. It works finds in Google chrome, but when I try to display it in mozilla or IE, it shows something completely different. I cannot attach images as I do not have the required reputation. I really appreciate the help. Thank you!
HTML
<!DOCTYPE html>

 <meta charset="utf-8" />
 <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
 <meta name="viewport" content="width=device-width, initial-scale=1" />
 <link rel="stylesheet" type="text/css" href="style.css">
 <link rel="shortcut icon" href="ak.png">
  <title>Home</title>

Home

About

Portfolio

Shop

Blog

Contact

DESIGN | DEVELOP | BRAND

VIEW PORTFOLIO

VIEW SERVICES

CSS
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }

* {
    padding: 0;
    margin: 0;
}

li {
    display: inline;
    font-size: 15px;
    font-family: verdana;

}

nav {
    width: 100%;
    text-align: right;
    background-color: #222222;
    padding: 0;
    margin: 0px;
    line-height: 47px;
    position: fixed;
    z-index: 100;
}

.ak{
    width: 90px;
    height: 55px;
    z-index: 101;
    position: fixed;
    background: transparent;
    color: transparent;
    background-color: transparent;
}

.Nav a{
    text-decoration: none;
    padding: 15px;
}

.Nav a:link{
    color: #A7A7A7;

}

.Nav a:visited{
    color: #A7A7A7;

}

.Nav a:hover{

    color: #DBDBDB;
    transition: all 0.3s ease-out 0s;
    transition-property: all;
    transition-duration: 0.3s;
    transition-timing-function: ease-out;
    transition-delay: 0s;
}

.header {

    background-color: rgba(0,0,0, 0.25);
    width: 100%;
    height: 626px;
    text-align: center;
    position: fixed;
    z-index: 10;
}

.background {
    position: fixed;
    z-index: 8;

}

.beauty {
    width: 100%;
    height: 626px;

}

.headerName {
    font-size: 2.5em;
    text-align: center;
    color: #D3D3D3;
    padding: 180px;
    padding-bottom: 50px;
    margin: 0px;
    letter-spacing: 4px;
    font-weight: 100;
    font-family: 'Lato', sans-serif;
}

.fade-in {
    opacity:0;  /* make things invisible upon start */
    -webkit-animation:fadeIn ease-in 1;  /* call our keyframe named fadeIn, use animation ease-in and repeat it only 1 time */
    -moz-animation:fadeIn ease-in 1;
    animation:fadeIn ease-in 1;

    -webkit-animation-fill-mode:forwards;  /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
    -moz-animation-fill-mode:forwards;
    animation-fill-mode:forwards;

    -webkit-animation-duration:1s;
    -moz-animation-duration:1s;
    animation-duration:1s;

    -webkit-animation-delay: 0.3s;
    -moz-animation-delay:0.3s;
    animation-delay: 0.3s;
}

.fade-in2 {
    opacity:0;  /* make things invisible upon start */
    -webkit-animation:fadeIn ease-in 1;  /* call our keyframe named fadeIn, use animation ease-in and repeat it only 1 time */
    -moz-animation:fadeIn ease-in 1;
    animation:fadeIn ease-in 1;

    -webkit-animation-fill-mode:forwards;  /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
    -moz-animation-fill-mode:forwards;
    animation-fill-mode:forwards;

    -webkit-animation-duration:1s;
    -moz-animation-duration:1s;
    animation-duration:1s;

    -webkit-animation-delay: 0.6s;
    -moz-animation-delay:0.6s;
    animation-delay: 0.6s;
}

.fade-in3 {
    opacity:0;  /* make things invisible upon start */
    -webkit-animation:fadeIn ease-in 1;  /* call our keyframe named fadeIn, use animation ease-in and repeat it only 1 time */
    -moz-animation:fadeIn ease-in 1;
    animation:fadeIn ease-in 1;

    -webkit-animation-fill-mode:forwards;  /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
    -moz-animation-fill-mode:forwards;
    animation-fill-mode:forwards;

    -webkit-animation-duration:1s;
    -moz-animation-duration:1s;
    animation-duration:1s;

    -webkit-animation-delay: 0.9s;
    -moz-animation-delay:0.9s;
    animation-delay: 0.9s;
}

.service{
    font-size: 14px;
    width: 190px;
    text-align: center;
    font-family: 'Lato', sans-serif;
    color: #D3D3D3;
    border: 2px #A7A7A7 solid;
    border-color: rgba(255, 255, 255, 0.5);
    display: inline-block;
    border-radius: 5px;
    background-color: transparent;
    letter-spacing: 2px;

}

.service a{
    text-decoration: none;
    display: block;
    padding: 15px 20px;
}

.service a:link{
    color: #D3D3D3;

}

.service a:visited{
    color: #D3D3D3;

}

.service a:hover{
    background-color: rgba(255, 255, 255, 0.15);
    transition: background-color .15s ease-in;
    -webkit-transition: background-color .15s ease-in;
    -moz-transition: background-color .15s ease-in;
    -o-transition: background-color .15s ease-in;
}

UPDATE 1: I updated both browsers and it seems the css3 animations work perfectly fine on both browsers. What seems to be the problem is the positioning of the pages
UPDATE 2: Here are the links to the different browser screen shots
Chrome: https://www.dropbox.com/s/jlpa4vu51kdnews/Chrome.JPG
InternetExplorer: https://www.dropbox.com/s/zbchs3su9ahxr0n/IE.JPG
Mozilla Firefox: dropbox(.)com/s/fyalnhsha9ktadz/Mozilla.JPG (I can't post the third link because I don't have enough reputation)
--- Notice in chrome the logo in the top left looks smooth while the other two not so much. I believe the pictures are self explanatory.

A: Here is my JSFiddle. Is this what you want?
Just changing first line of your css file.
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }

A: Problem with IE8 and Earlier version
IE8 and earlier does not know how to render CSS on elements that it doesn't recognize. You cannot style new HTML5 elements like header, nav , section
but HTML 5 shiv javascript file is used to enable styling of HTML5 elements in versions of Internet Explorer prior to version 9.
you can download it from http://code.google.com/p/html5shiv/
To enable the HTML5 Shiv (after downloading), insert the following code into the  element:


text:
Q: Why the loops has a problem (pset2 Substitution) I have been working CS50X pset2 substitution. I think it almost has done. When I input single char such as A or B D and so on... the ciphertext will get the right result. (e.g A will get J, "B" will get T and D will get E and so on...
However, if I input ABC, the ciphertext will only show J and the other cannot show. What did I do wrong?
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

int ciphertext = 0;

//Key
//JTREKYAVOGDXPSNCUIZLFBMWHQ

int main(int argc, string argv[])
{
     //Check that program was run with one command-line argument
    if (argc == 2)
    {

        string key = argv[1];

        //check the key does it validate
        for (int i = 0, n = strlen(key); i < n; i++)
        {

            string plaintext = get_string("plaintext: ");
            printf("ciphertext: \n");

            int u = 64;

            for (int k = 0, p = strlen(plaintext); k < p; k++)
            {
                if (isupper(plaintext[k]) != 0)
                {
                    for (int j = 0; j < 26; j++)
                    {

                        u = u + 1;
                        //printf("u is %c\n", u);

                        if (u == plaintext[k])
                        {
                            ciphertext = key[j];
                            printf("Key is %c\n", key[j]);
                            printf("Plaintext is %c\n", plaintext[k]);
                            printf("ciphertext is %c\n", ciphertext);
                            //break;
                        }

                    }
                }

                else
                {
                    printf("%c", plaintext[k]);
                }
            }

            return 0;
        }
    }
}

A: Your problems are logic errors that appear to result from changes you attempted to make to the code that got out of hand. You have unnecessary loops and unused variable in your code. You need to change the scope of the u declaration so it is reinitialized on each iteration. You simply need to remove the for (int i = 0, n = strlen(key); i < n; i++) loop altogether, neither i or n is used. The same for ciphertext and l (ell).
You need to move int u = 64; immediately after if (isupper(plaintext[k])) so it is reset on each iteration.
I suspect all the printf statements were for debugging and you really only want the key output. Putting it altogether, you can rearrange your code to:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

int main (int argc, string argv[]) {

    if (argc == 2) {    /* validate key given */

        string key = argv[1];
        string plaintext = get_string("plaintext: ");
        printf("ciphertext: ");

        for (int k = 0, p = strlen(plaintext); k < p; k++)
        {
            if (isupper(plaintext[k]))
            {
                int u = 64;
                for (int j = 0; j < 26; j++)
                {
                    u = u + 1;
                    if (u == plaintext[k]) {
                        printf("%c", key[j]);
                        break;
                    }
                }
            }
            else
                printf("%c", plaintext[k]);
        }
        putchar ('\n');
    }
}

Example Use/Output
$ ./bin/cs50_cypher2 JTREKYAVOGDXPSNCUIZLFBMWHQ
plaintext: ABD
ciphertext: JTE

Simplify Your Logic
If you think about what the code above is actually doing, it can be reduced to:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main (int argc, string argv[]) {

    if (argc < 2) {    /* validate key given */
        fputs ("usage: ./program key\n", stderr);
        return 1;
    }

    string key = argv[1];
    string plaintext = get_string("plaintext: ");
    printf("ciphertext: ");

    for (int k = 0, p = strlen(plaintext); k < p; k++)
    {
        if (isupper(plaintext[k]))
            putchar (key[plaintext[k] - 'A']);
        else
            putchar (plaintext[k]);
    }
    putchar ('\n');
}

Or if you use a ternary operator, your for loop condenses to simply:
    for (int k = 0, p = strlen(plaintext); k < p; k++)
        putchar (isupper(plaintext[k]) ? key[plaintext[k] - 'A'] : plaintext[k]);

And since there is no need to call strlen(plaintext), you can eliminate string.h entirely and just loop for (int k = 0; plaintext[k]; k++) since plaintext is a nul-terminated string, your entire program can reduce to:
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>

int main (int argc, string argv[]) {

    if (argc < 2) {    /* validate key given */
        fputs ("usage: ./program key\n", stderr);
        return 1;
    }

    string key = argv[1];
    string plaintext = get_string("plaintext : ");
    printf("ciphertext: ");

    for (int k = 0; plaintext[k]; k++)
        putchar (isupper(plaintext[k]) ? key[plaintext[k] - 'A'] : plaintext[k]);

    putchar ('\n');
}

Handling Lowercase Letters
You know your key entered as the first argument is all uppercase. So if you want to output a lowercase key, you must call tolower() on the key after you have applied the offsets. Since for an uppercase letter, you just want to know the offset within the 26-character key to use, you simply find out how many letters your current letter is from 'A' and get that offset in key[], e.g.
    key[plaintext[k] - 'A']

For lowercase input, you need to find out the offset in key for the difference in lowercase letters, and then apply tolower() to the key, e.g.
    tolower(key[plaintext[k] - 'a'])

See ASCII Table & Description
Putting that altogether, your for loop can be written as:
    for (int k = 0; plaintext[k]; k++) {
        if (isupper(plaintext[k]))
            putchar (key[plaintext[k] - 'A']);
        else if (islower(plaintext[k]))
            putchar (tolower(key[plaintext[k] - 'a']));
        else
            putchar (plaintext[k]);
    }

Example Use/Output
$ ./bin/cs50_cypher4 JTREKYAVOGDXPSNCUIZLFBMWHQ
plaintext : AbZ 50
ciphertext: JtQ 50

Look things over and let me know if you have further questions.


text:
Q: Save an existing Model to a CoreData DB I'm learning Core Data and I understand all the examples for creating a brand-new object, assigning values and saving it to the managedContext (insertNewObjectForEntityForName).
However, what if I've already created an object elsewhere (model Category)? In this case I'd want to just assign the current Context to this Model, and then save it.
What is the command/approach to take an in-memory Model, and then assign to a context so it can be saved?

A: If you want to use Core Data to manage your data, you'll need to:

*

*create an appropriate model description (.xcdatamodeld file)

*modify your model class(es) so that they inherit from NSManagedObject

*set the "Class" for each entity in your model description to one of your NSManagedObject subclasses

*add code to your app to create and manage the Core Data stack, fetch data, etc.
This is all very do-able, but I wouldn't recommend that you attempt it until you have a solid understanding of Core Data and your reasons for adopting it in your project. The lack of clarity in your question may indicate that you're not quite there yet; you might benefit from working on a small project that uses Core Data from the start.
If all you want to do is to save your data, you should know that Core Data is not the only way to do that. A much simpler approach to saving your data would be to adopt the NSCoding protocol in your data model and then use a NSKeyedArchiver to store your data. Get the full story from the Archives and Serializations Programming Guide. There are other ways to do it as well, but NSKeyedArchiver is a good place to start.

A: You can only save NSManagedObjects (and their subclasses) to CoreData.  NSManagesObject can not be created except in the context of an NSManagedObjectContext.
So, what you're saying is confusing.  Do you have a non-CoreData model object?


text:
Q: Subclassing a UIButton programmatically? I have a UIButton inside of an array which I would like to subclass to a SpringButton (https://github.com/MengTo/Spring). I tried this:
let springButton = playableCards[cardIndex] as! SpringButton

But I get this error:
Could not cast value of type 'UIButton' (0x1126bf120) to 'Spring.SpringButton' (0x10e6e62e8).
I do not want to create outlets or changing it in Storyboard. Is this a error from Swift, or an error from the pod itself?
Any help is welcome!
Edit:
var playableCards: [UIButton] = []
playableCards = self.allPlayableCardsViews[0].allSubviews.flatMap { $0 as? UIButton }

Where allPlayableCardsViews is just a regular UIView.

A: If the class of the item in your storyboard scene is UIButton then the object is a UIButton and you can't simply downcast it as something else.  If you want your buttons to be SpringButtons, and they are being created by a storyboard scene, then you need to set the custom class in the storyboard.
Since SpringButton is a subclass of UIButton you can pass a SpringButton anywhere a UIButton is expected. You can also downcast a variable of type UIButton to a SpringButton as long as the underlying object is a SpringButton. Conditional downcasts with as? are safer than forced downcasts as you have found.
Imagine you have a parking space. Vehicles can park in the space. Motorcycles and cars are both types (subclasses if you will) of vehicle, so either can park there. But whether a vehicle is a car or a motorcycle is determined when it is built. You can't simply convert a motorcycle to a car by saying so later, but this is what you are trying to do with your buttons.


text:
Q: ReferenceError: TextDecoder при тестировании класса на TypeScript Есть класс, в котором используются TextDecoder и TextEncoder. Никакие модули в файле класса для их использования не подключаются. Проект на запуск работает.
Класс покрывается тестами с использованием mocha + chai. Так вот, при тестировании этого класса происходит ошибка ReferenceError: TextDecoder is not defined и ReferenceError: TextEncoder is not defined.
Тесты запускаются следующим образом:
"test": "mocha --require ts-node/register tests/**/*.ts"

Что нужно сделать для работоспособности тестов?

A: Проблема решилась добавлением кода import { TextDecoder } from 'text-encoding'


text:
Q: XPath 2.0:reference earlier context in another part of the XPath expression in an XPath I would like to focus on certain elements and analyse them:
...
<field>aaa</field>
...
<field>bbb</field>
...
<field>aaa (1)</field>
...
<field>aaa (2)</field>
...
<field>ccc</field>
...
<field>ddd (7)</field>

I want to find the elements who's text content (apart from a possible enumeration, are unique. In the aboce example that would be bbb, ccc and ddd.
The following XPath gives me the unique values:
distinct-values(//field[matches(normalize-space(.), ' \([0-9]\)$')]/substring-before(., '(')))

Now I would like to extent that and perform another XPath on all the distinct values, that would be to count how many field start with either of them and retreive the ones who's count is bigger than 1.
These could be a field content that is equal to that particular value, or it starts witrh that value and is followed by " (". The problem is that in the second part of that XPath I would have refer to the context of that part itself and to the former context at the same time.
In the following XPath I will - instead of using "." as the context- use c_outer and c_inner:
distinct-values(//field[matches(normalize-space(.), ' \([0-9]\)$')]/substring-before(., '(')))[count(//field[(c_inner = c_outer) or starts-with(c_inner, concat(c_outer, ' ('))]) > 1]

I can't use "." for both for obvious reasons. But how could I reference a particular, or the current distinct value from the outer expression within the inner expression?
Would that even be possible?

A: XQuery can do it e.g.
  for $s
  in distinct-values(
    //field[matches(normalize-space(.), ' \([0-9]\)$')]/substring-before(., '(')))
  where count(//field[(. = $s) or starts-with(., concat($s, ' ('))]) > 1
  return $s


text:
Q: How to set API headers for different APIs? I need to call 2 different APIs from my react app, and both of these APIs use different types of Authorization.
makeAPICall = (url, body, method, env) => {
    let requestOptions = {method, body, headers: {}};
    if (env === 'api_1') {
        requestOptions.headers = {'Authorization': `Token ${authToken}`}
    } else if (env ==='api_2') {
        requestOptions.headers = {'Client-Secret-Key': `${clientSecretKey}`}
    }
    url = new URL(url);
    return fetch(url, requestOptions);
}

Is there a better way to do this, so that I don't have to send my api name in each api call (like I am sending env in makeAPICall function).
Is there a way of intercepting the api url, and setting headers accordingly?

A: use this code is a better way i think, you can try it
const headers = {
  api_1: {'Authorization': `Token ${authToken}`},
  api_2: {'Client-Secret-Key': `${clientSecretKey}`}
}
requestOptions.headers = headers[env]


text:
Q: How to select a partition key for for a DynamoDB query? I have created a dynamo db table with name- "sample".It has below columns. CreatedDate will have creation time of any records inserted to this table.
Itemid,
ItemName,
ItemDescription,
CreatedDate,
UpdatedDate

I am creating a python-flask based rest api which always fetches last 100 records inserted to this table. This API (python-flask function) does not have any input parameters. It should just return the last records inserted to this table.
Question 1
What should be the partition key for this table? I am using the boto3 library to fetch records from DynamoDB. I prefer not to do scan operation because it may cause performance issues. If I use the query function it asks for a partition key. Since this rest API does not accept any input I am not sure how to use it.
Question 2
Has anyone faced similar situation? And what was done to fix this?
Note: I am pretty much newbie to DynamoDB, NoSQL and Boto

A: To query your table using CreatedDate without knowing the ItemId, you can use Global Secondary Index write sharding by adding an attribute (e.g., ShardId) containing a (0-N) value to every item that you will use for the global secondary index partition key.
Depending on how your items are distributed against CreatedDate, you can set the ShardId so that it is likely to have evenly distributed access patterns. For example: YYYY, YYYYMM or YYYYMMDD. Then, you create a global secondary index with ShardId as an index partition key and CreatedDate as an index sort key.
Knowing the primary key for your GSI (since the ShardId value is derived from CreatedDate), you can query the table for the 100 most recent items with query's Limit parameter (or LastEvaluatedKey if your items set size is larger than 1 MB of data).
See Using Global Secondary Index Write Sharding for Selective Table Queries.


text:
Q: Using VBA to save an attachment as a different filetype I'm trying to write a macro to save html attachments as .txt files (and then do some stuff with the .txt file) but am running into a problem right out of the gate - the Attachment object only has the SaveAsFile method, not the SaveAs method, and the SaveAsFile method only has the path parameter, not the type parameter.
I've tried various methods of just sneaking .txt into the pathname, and none have worked.
This is my first attempt at "serious" programming, so it's possible I'm missing something incredibly obvious.

A: You just need to specify the desired extension for the file. The SaveAsFile method of the Attachment class saves the attachment to the specified path (with the specified filename).
You may also find the Getting Started with VBA in Outlook 2010 article helpful.


text:
Q: Why is the difference? .First(....) and .Where(....).First() Example class for tests.
public class Alphabet
{
    public int A = 0;
    public int B = 0;
    // both A and B contain a single number  between 1-9
}

In code:
IEnumerable<Alphabet> alp; // <--- contain +/- 70 000 records

Working:
Alphabet tmp1 =atp.First(a => a.A > 4 && A.B < 4);

Not Working: -- tmp was empty
Alphabet tmp2 = atp.Where(a => a.A > 4 && A.B < 4).First();

Resoults:
tmp1  != null; // single element from Enum that meet the conditions

tmp2  = null;

In previous projects I used second(not Working) combination to search through enum, and it was warking well. I am looking for the reason Why. I can imagine that "Working" version requires less processing power, but what is the specific reason why "Not Working" is not working.
Both lines are ideas how to solve same problem, return first valid element under declarated condition.  Code is simplified example of problem from more extended project.
The question is
Why in some cases .Where(...).First() won't work.
As I understand both resaults should be the exact same. But in situation when Enum conteins thousands of records  option Where().First() won't work but .First() will.

A: As the others wrote in the comments - what exactly is not working?
I fixed some typos in your code samples - AFAIK:
public class Alphabet
    {
        public int A = 0;
        public int B = 0;
// both A and B contai a single number  between 1-9
    }

// In code:
IEnumerable<Alphabet> alp; // <--- contain +/- 70 000 records

// perhaps delivers an alp entry with e. g. A = 8 and B = 3?
Alphabet tmp =alp.First(a=>a.A >4 && a.B <4);
// perhaps delivers an other alp entry with A = 5 and B = 1?
Alphabet tmp =alp.Where(a=>a.A >4 && a.B <4).First();

I guess your problem - see above in last 2 comments (//).
You want that both return the same "first" entry (and at every execution time the very same) - but the code says you want any first element fulfilling the condition, otherwise you would have to order them first!
It depends upon the implementation of the IEnumerable.
So e. g. if you read from a database, the order is unpredictable - be aware that SELECT brings any order of the elements - and not reproducible - mostly reproducible, and then programmers think, it is always the same order, but it isn't guaranteed! If e. g. database grows and a segment is added - suddenly the order can change (completely)!
And database LinQ does not allow everything (I've fallen in that trap sometimes). So tmp could be null in the lower example.


text:
Q: Is there any way creating dynamic @ServerEndpoint address in Java? For example, I have a  room
public class Room {
   private int id;
   private Set<User> users;
}

So I want it to be endpoint for my websocket application. But there may be a lot of rooms and I want each of them could have own URI (for example, rooms/1, rooms/2 etc.)
Evidently, @ServerEnpoint annotaion allows only constants. So, is there any way to make it?

A: Something like this:
@ServerEndpoint(value = "/rooms/{roomnumber}")
public class....

static Map<String, Session> openSessions = ...
@OnOpen
public void onConnectionOpen(final Session session, @PathParam("roomnumber") final String roomnumber,
...
   //store roomnumber in session
   session.getUserProperties().put("roomnumber", roomnumber);
   openSessions.put( String.valueOf(session.getId()), session )

To only send messages to specific roomnumbers/clients:
// check if session corresponds to the roomnumber
  for (Map.Entry<String, Session> entry : openSessions.entrySet()) {

    Session s = entry.getValue();
    if (s.isOpen() && s.getUserProperties().get("roomnumber").equals(roomnumber_you_want_to_address)) {
  ...

And when a client disconnects:
 @OnClose
public void onConnectionClose(Session session) {
    openSessions.remove(session.getId());
}

A: You can use this per function to map requests with different variables in the same controller
@RequestMapping(value = "/endpoint/{endpointVariable}", method = RequestMethod.GET)
public ReturnDTO getReturnDTO(<params>){
    // Here the variable, endpointVariable, will be accessible
    // In my experiences its always been an integer, but I'm sure a string
    // would be possible.  check with debugger
}

http://www.journaldev.com/3358/spring-mvc-requestmapping-annotation-example-with-controller-methods-headers-params-requestparam-pathvariable


text:
Q: Ubuntu Encryption Options UEFI I want to run Windows 10 (UEFI) and Ubuntu 16.0.4 (UEFI) as dual boot with Windows being encrypted by BitLocker and Ubuntu with whatever is best option.  So, essentially this question is about what is best option to encrypt your Ubuntu as well as how to do it.

*

*What options are suggested?

*

*LUKS?

*Select the "Encrypt your Ubuntu installation for security" during setup

*Select "Encrypt /home?" during setup

*Use Physical Disk Encryption and forget encryption on OS level?

*How are all four-4 above different from one another?

*How to achieve them?

Thanks in advance.


text:
Q: Can not delete Core Data Entity regardless of Delete Rule I am trying to delete a Core Data Entity and no matter what delete rule I use, it just won't work. It does not do anything at all.
I am using Firefox's Sqlite Add-on to browse the core data database and I can see all the rows there after the delete code runs.
My code for deletion looks like this
+(void)deleteCustomerWithID:(int)customerid inManagedObjectContext:(NSManagedObjectContext  *)context
{
Customer *customer = nil;

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Customer"];
request.predicate = [NSPredicate predicateWithFormat:@"id = %d", customerid];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"organization" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSError *error = nil;
NSArray *customers = [context executeFetchRequest:request error:&error];

if (!customers || ([customers count] > 1)) {
    // handle error
} else if (![customers count]) {
    // customer not found
} else {
    customer = [customers lastObject];
    [context deleteObject:customer];

    NSError *error;
    if(![context save:&error]){
        NSLog(@"Unresolved error series %@, %@", error, [error userInfo]);
    }
}
}

Any ideas what am I doing wrong?

A: I am not sure what went wrong but I ended up deleting all the relationships in Entities and then re-creating them. That seems to have solved the issue. I can now successfully Cascade Delete.


text:
Q: modal with blurred background with css like in example aye folks!
i spent the last hour searching around the web trying to find a css solution to create something like this this..
i read a lot of 'frosted glass' tutorials.. but like 90% are using two images or blur the whole body of the site while the modal is open.
maybe i just haven't found the right article or it's not possible with css this easily atm. but stack overflow never disappointed me so far. therefore i'm asking you guys if someone does know a solution.


text:
Q: Does anyone deploy meanio project to AWS Elasticbeanstalk? I've been trying to deploy a meanio project to AWS ElasticBean but failed. Firstly, it's due to wrong dependencies when installing npm with --production. Secondly, it's missing krb5-devel package which I install via config file below:
packages:
  yum:
    krb5-devel: []

Lastly, I find it's still now working because the default Node.js environment does not include Node and npm in the default search path. So the postinstall script for meanio package cannot install properly.
I've tried to ssh to the server and add them to the default path, and manually install my project. It works. Then I try to add the node path to the config file, but it doesn't work.
option_settings:
  - option_name: PATH
    value: $PATH:/opt/elasticbeanstalk/node-install/node-v4.2.3-linux-x64/bin

Can anyone suggest how to deploy a meanio project properly?


text:
Q: Error Boundaries disables routing inside of a Switch For a long time I have been trying to get routing to work in our app after an error boundary has been hit, but only today did I find the code that was seemingly identical to the many examples lying around had one important difference: the routes were wrapped by a Switch. This simple change is enough to stop routing from working, if enabled. Demo
Take the following snippet. If I remove the Switch bit, this works fine even if each component should fail, but not if wrapped by the switch. I would like to know why.
<div style={{ backgroundColor: "#ffc993", height: "150px" }}>
<Switch>
  <Route
    path="/"
    exact
    render={() => (
      <ErrorBoundary>
        <MyComponent1 title="Component 1" />
      </ErrorBoundary>
    )}
  />
  <Route
    path="/comp1"
    render={() => (
      <ErrorBoundary>
        <MyComponent1 title="Component 1 Again" />
      </ErrorBoundary>
    )}
  />
  <Route
    path="/comp2"
    render={() => (
      <ErrorBoundary>
        <MyComponent2 title="Component 2" />
      </ErrorBoundary>
    )}
  />
</Switch>

A: Basically, this problem boils down to how React does reconciliation.

When a component updates, the instance stays the same, so that state is maintained across renders. React updates the props of the underlying component instance to match the new element

Say we have this example app:
<App>
  <Switch>
    <Route path="a" component={Foo}/>
    <Route path="b" component={Foo}/>
  </Switch>
</App>

This will, somewhat unintuitively, reuse the same instance of Foo for both routes! A <Switch> will always return the first matched element, so basically when React renders  this is equivalent of the tree <App><Foo/></App> for path "a" and <App><Foo/></App> for path "b". If Foo is a component with state, that means that state is kept, as the instance is just passed new props (for which there are none, except children, in our case), and is expected to handle this by recomputing its own state.
As our error boundary is being reused, while it has state that has no way of changing, it will never re-render the new children of its parent route.
React has one trick hidden up its sleeve for this, which I have only seen explicitly documented on its blog:

In order to reset the value when moving to a different item (as in our password manager scenario), we can use the special React attribute called key. When a key changes, React will create a new component instance rather than update the current one.
  (...) In most cases, this is the best way to handle state that needs to be reset.

I was first hinted to this by a somewhat related issue on Brian Vaughn's error bondary package:

The way I would recommend resetting this error boundary (if you really want to blow away the error) would be to just clear it out using a new key value. (...) This will tell React to throw out the previous instance (with its error state) and replace it with a new instance.

The alternative to using keys would be to implement either exposing some hook that could be called externally or by trying to inspect the children property for change, which is hard. Something like this could work (demo):
componentDidUpdate(prevProps, prevState, snapshot) {
    const childNow = React.Children.only(this.props.children);
    const childPrev = React.Children.only(prevProps.children);

    if (childNow !== childPrev) {
        this.setState({ errorInfo: null });
   }

But it's more work and much more error prone, so why bother: just stick to adding a key prop :-)

A: To give you the shortcut of this fix, please see the new "key" prop on each of the ErrorBoundary component and each must be unique, so the code should look like this:
<Switch>
  <Route
    path="/"
    exact
    render={() => (
      <ErrorBoundary key="1">
        <MyComponent1 title="Component 1" />
      </ErrorBoundary>
    )}
  />
  <Route
    path="/comp1"
    render={() => (
      <ErrorBoundary key="2">
        <MyComponent1 title="Component 1 Again" />
      </ErrorBoundary>
    )}
  />
  <Route
    path="/comp2"
    render={() => (
      <ErrorBoundary key="3">
        <MyComponent2 title="Component 2" />
      </ErrorBoundary>
    )}
  />
</Switch>

To elaborate, the answer of @oligofren is correct. Those 3 ErrorBoundary components are the same instances but may differ in props. You can verify this by passing "id" prop to each of the ErrorBoundary components.
Now you mentioned why is that if you remove Switch component, it works as expected? Because of this code:
https://github.com/ReactTraining/react-router/blob/e81dfa2d01937969ee3f9b1f33c9ddd319f9e091/packages/react-router/modules/Switch.js#L40
I recommend you to read the official documentation of React.cloneElement here: https://reactjs.org/docs/react-api.html#cloneelement
I hope this gives you an idea on this issue. Credit to @oligofren as he explained in more details about the idea of the instances of those components.


text:
Q: Is it possibe to view a forgotten admin password? My ubuntu pc is setup to auto login, so since I never have to type my password, I've forgotten it.
Now, normally I'd just reset it, but I used that password for another online service, and I want to login on that service again but I don't know the password.
Is there any way to see my password? I'm logged in the admin account, it auto logins.

A: The actual passwords are not stored, you can only find their hashes in /etc/shadow.
There is no easy way to recover passwords, your best try is to use a software like John the Ripper to crack your password, but if you used a strong password, cracking it might take a very, very long time.

A:
for another online service, and I want to login on that service again

The only option in retrieving your password would be to use the password recovery for that on-line service. I have yet to see one that does not offer one.


text:
Q: What's wrong with this ruby on rails migration? I am trying to migrate ruby on rails application from one machine to another and when I type
Rake db:migrate it gives following error:
Mysql::Error: Table 'schema_migrations' already exists:
CREATE TABLE `schema_migrations` (`version` varchar(255) NOT NULL) ENGINE=InnoDB

what might be the possible cause..?

A: As mentioned by Bohdan...
or
rake db:migrate:reset

A: Hi try rake db:drop rake db:create rake db:migrate

A: In my case just dropping and creating database didn't help. Try restarting mysql server also:
/etc/init.d/mysqld restart
/etc/init.d/mysql restart
service mysqld restart

(depending on what OS you run), and then:
rake db:reset && rake db:test:clone

P.S. If you're using any preloaded like zeus or guard, try running without it.


text:
Q: Does $f(\epsilon)=o(\epsilon\ln(\epsilon))$ imply $\frac{f(\epsilon)}{\epsilon}=o(1)$? I have the following homework question:

Does $f(\epsilon)=o(\epsilon\ln(\epsilon))$ imply
  $\frac{f(\epsilon)}{\epsilon}=o(1)$ ?

It doesn't seem correct to me, using the definition I could only get
$$\frac{f(\epsilon)}{\epsilon}=o(\ln(\epsilon))$$ and it doesn't seem
that if $g(\epsilon)=o(\ln(\epsilon))$ then $g(\epsilon)=o(1)$.
To contradict this I wish to find a function $c(\epsilon)$ s.t $$\lim_{\epsilon\to0}c(\epsilon)=0$$
but $$\lim_{\epsilon\to0}|c(\epsilon)\ln(\epsilon)|>0$$
I am having difficulty finding such a function, I tried a few and
checked them using WA, they all satisfied $$\lim_{\epsilon\to0}c(\epsilon)=0$$
but they all also satisfied that $$\lim_{\epsilon\to0}|c(\epsilon)\ln(\epsilon)|=0$$
Can someone please help me find such $c(\epsilon)$ ? (or surprise
me and show that this statement is in fact true)

A: The notation
$$f(x)=_a o(g(x))$$
means $$\lim_{x\to a}\frac{f(x)}{g(x)}=0\iff \frac{f(x)}{g(x)}=_a o(1) $$
and to contradict your implication just take $f(\epsilon)=\epsilon$

A: Be careful what you wish for -- setting $c(x)=\frac{42}{\ln x}$ satisfies your conditions, but doesn't help much with the original question... or does it? :-)


text:
Q: Allow only hexadecimal html entities Got a forum and posting HTML is forbidden.
However, some users would like to have the possibility to post some symbolic signs, hexadecimal html entities, such as:
💗

See: http://graphemica.com/%F0%9F%92%97 for more info.
My questions are:

*

*Is this safe to allow them such symbols at all (XSS, etc..)?

*What's the best function to use, to allow it? Actually the symbolic html entities appear as plain text.

*I want to disallow members using & or » and so on, so just html-entities starting with &# and followed by a number plus the semicolon at the end.

Any idea how to solve this?

A: Another answer is to use jQueries .text method to add the message to your forum message element.
Although you will have to change how your forum creates the message structure.
You can safely add any sequence of characters and none of them will be interpreted by the browser as HTML.
Example:
$('#message_text').text(naughty_msg_string);

A:
Is this safe to allow them such symbols at all (XSS, etc..)?

No, this is never safe. For example, & is just a convenient alias for &, which is still an ampsersand. Similarly < is a lesser-than sign, and thus 'naively' allowing numeric HTML-entities can still open up an XSS attack surface, if you forget this during processing.
You could consider only allowing numeric symbols outside the main ASCII table (128+), which would be more safe.

What's the best function to use, to allow it? Actually the symbolic html entities appear as plain text.

Considering the above function, preg_replace_callback is a good candidate, as it allows you to test the content before (dis)allowing it.
This also answers the third question, as you can just test for numbers in the regexp.


text:
Q: NoResponseException on MultiUserChat room creation I am trying to create a MultiUser Chat room using Java..
This is my code...
ConnectionConfiguration config = new ConnectionConfiguration("ip_address", 5222, "admin.com");
config.setSecurityMode(SecurityMode.disabled);

XMPPTCPConnection connection = new XMPPTCPConnection(config);
connection.connect();
connection.login(username, password);

MultiUserChat mucRoom = new MultiUserChat(connection, groupId@hostname);
mucRoom.create("unio_groups_" + groupId);

However, I am getting an excepton "org.jivesoftware.smack.SmackException$NoResponseException"..


text:
Q: Allocating Heap Memory At a Given Address I'm working on an Entity-Component System, and now that I got everything up and running I decided to delve a bit into optimizations.
Currently, I have a Gameobject class that stores an unordered_map with component IDs and respective component pointers. To speed things up, I want to try to allocate components on the heap in contiguous memory without copying them into a vector. With this I would be able to iterate over them simply by getting the first component then moving up from that address by the size of the component, essentially eliminating the constant searching the computer would otherwise have to go through to find the different memory addresses when iterating over their pointers.
Is there a way to do such a thing?


text:
Q: eclipse add jni and .jar libraries I am doing a program in java which collects information from a serial port and sends it over the network.
The network packets are somewhat special and  I need send the packets with rawMac format. For that I used the Java Native Interface (JNI).
I've done two modules and operate separately.
- To network module, I must put into the VM arguments  "-Djava.library.path = jni" for the ejecution.
-For the modul serial I use the RXTXcomm.jar I put it in the Build Path.
When I put together, if I put "-Djava.library.path = jni" the RXTX isn't recognized and if I do not put "-Djava.library.path = jni" the program not find the libraries that I created with JNI
Thanks for the help

A: If you want to add a new Jar Library to your Project you must go to the Navigation List. There you can make a right click with the mouse on the Project-Folder. There is the Option Build Path, there you can add Jars...


text:
Q: Deserialize xml element that is empty but has attributes I have some XML with an element like this:
<hour base_forecast="12" datim="29/0" />

And am receiving the error:
Unexpected node type Element. ReadElementString method can only be
called on elements with simple or empty content.

I am guessing this is because the element has no value.  I don't control this XML so I can't change it.  How would I deserialize this?
** EDIT **
One of the attributes' values is ">6" .... could this be the culprit?  If so, how do I handle that?
** Update **
Found some data that wasn't returning a > in a value of the attribute.  Same error is occurring.
** Edit #3 *
Created an XSD for the XML I am receiving, then generated classes for them with the xsd tool.  Adding to the bottom of this post.
Here is the Deserialization code:
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("xxx");
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        WeatherData Result = new WeatherData();

        using (Stream st = resp.GetResponseStream())
        {
            XmlRootAttribute xRoot = new XmlRootAttribute();
            xRoot.ElementName = "model_data";
            xRoot.IsNullable = true;

            Result = new XmlSerializer(typeof(WeatherData), xRoot).Deserialize(st) as WeatherData;  ** Error here

Xml returned:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE observation SYSTEM "http://private.com/hithere.dtd">
<model_data>
     <site a="28/12" b="KXXX">
         <hour x="-9999" y="-9999" z="-9999"/>
     </site>
</model_data>

Data object
[Serializable, XmlRoot("model_data")]
public class WeatherData
{
    [XmlElement("site")]
    public string City { get; set; }

    [XmlAttribute]
    public string a { get; set; }

    [XmlAttribute]
    public string b { get; set; }

    [XmlElement(ElementName="hour", IsNullable=true)]
    public string Hour { get; set; }

    [XmlAttribute]
    public string x { get; set; }

    [XmlAttribute]
    public string y { get; set; }

    [XmlAttribute]
    public string z { get; set; }

}

XSD Tool generated classes
**Removed generated classes, but they are similar to what Hugo posted **

A: Looking at this part:
[XmlElement("site")]
public string City { get; set; }

<Site> contains <Hour>, so it is not an element with simple or empty content, I guess?
Edit: actually the whole thing seems suspect.
The data object seems to disregard all hierarchy information in the xml.
How about something like this?
[Serializable, XmlRoot("model_data")]
public class WeatherData
{
    [XmlElement("site")]
    public City[] City { get; set; }
}

public class City
{
    [XmlAttribute]
    public string a { get; set; }

    [XmlAttribute]
    public string b { get; set; }

    [XmlElement(ElementName="hour", IsNullable=true)]
    public Hour Hour { get; set; }
}

public class Hour
{
    [XmlAttribute]
    public string x { get; set; }

    [XmlAttribute]
    public string y { get; set; }

    [XmlAttribute]
    public string z { get; set; }
}

A: When I generated the classes with the XSD tool, I getting the same error, but the error was showing being thrown from a line I had commented out.
So I exited VS, and ran disk cleanup.  Ran my code again.  Received a message "For security reasons DTD is prohibited in this XML document. etc."  So, I allowed set the reader to DtdProcessing.Parse, and ran the code once more.
It was successful.


text:
Q: Why is it that the level curves of $g$ are orthogonal to these curves of $f$ here? Let $f, g: \mathbb{R}^2 \to \mathbb{R}$ be differentiable functions such that $g_x = f_y$ and $g_y = -f_x$. The flux lines of $f$ are defined to be the curves that are orthogonal to the level curves of $f$. Why is it that the level curves of $g$ are the flux lines of $f$?
I know it has everything to do with the fact that the gradient is orthogonal to level curves, but I haven't quite been able to formulate an airtight proof yet. I'd appreciate some help.

A: Note that the gradient vectors $$< f_x, f_y>$$ and    $$< g_x, g_y>$$ are perpendicular to each other.
That implies that the level curves meet at a $ 90$ degrees angle.
Thus the level curves of one is the flux curves of the other.


text:
Q: Worklight 7.1 - Push notification need to subscribe for last user in device who logged into app, previous user need to unsubscribe for that device I have an hybrid application developed with IBM Worklight 7.1 that receives push notification. This application use the username of user as userId to register to the push notification providers.
If the [userA] user is logout still he recieves notification but when new [userB]user login with same device how can i unsubscribe already existing user[userA] and we need to subscribe [userB]
Our scenario is
-->When user login he need to subscribe to push notification (Event source-based).
-->once he subscribed he will receive notification based on user name.
-->if he logout still he need to receive push notification.
--> Again when user tries to login into same mobile here first we need to unsubscribe is previous subscription and we need to subscribe.

A: To check if a user has already subscribed to the event source, you can use the API - WL.Client.Push.isSubscribed(aliasname);
Note that from an application on a device, at any given time , there can only be one subscription to a particular eventsource.
For example, consider App1 on Device1. Now user1 logs in and subscribes to eventsource ES1. The push subscription is recorded for user1 against ES1 from App1 on Device1.
Later user1 logs out and user2 logs in to App1. If user2 subscribes to ES1, the existing subscription is modified with user2 as the user.ie, it will become user2 against ES1 from App1 on Device1.
Hence, by design, your requirement is taken care of.


text:
Q: Help with recurrence relation and interest rates how would I create a recurrence relation for the amount of money in a saving account after $n$ months $a_n$ , if the interest rate is $.5\%$ interest per month and initially the account has $\$1000$?
what would the formula be for $a_n$?

A: After the first month, you will have $\color{blue}{a_1 = 1000 + 0.005\times1000 = \$1005}$
which is the initial balance + interest money.
Now after another month you will have
$a_2 = 1005 + 0.005 \times 1005$ which is the same as
$$\color{purple}{a_2 = a_1 + 0.005 \times a_1}$$
And so in general, you would have
$$\color{red}{a_n = a_{n-1} + 0.005 \times a_{n-1}}$$
I am assuming that $.5\%$ means $0.5\%$ which is $\frac{0.5}{100} = 0.005$


text:
Q: PHP Multidimensional Array Rearranging Sir,
I am confused what should be exact title of this issues. Below is my problem
I have a multidimensional array like below

Array
(
    [0] => Array
        (
            [0] => 2017-11-01
            [1] => 9 Am
        )

    [1] => Array
        (
            [0] => 2017-11-02
            [1] => 07 Pm
        )

    [2] => Array
        (
            [0] => 2017-11-03
            [1] => 11 Pm
        )

    [3] => Array
        (
            [0] => 2017-11-04
            [1] => 03 Pm
        )

    [4] => Array
        (
            [0] => 2017-11-01
            [1] => 11 Am
        )

    [5] => Array
        (
            [0] => 2017-11-02
            [1] => 05 Pm
        )

)

Now, I want to make unique date beside time should be into another array.
I want it as below...

Array
(
    [0] => Array
        (
            [0] => 2017-11-01
            [1] => Array
                (
                    [0] => 9 Am
                    [1] => 11 Am
                )

        )

    [1] => Array
        (
            [0] => 2017-11-02
            [1] => Array
                (
                    [0] => 07 Pm
                    [1] => 05 Pm
                )

        )

    [2] => Array
        (
            [0] => 2017-11-03
            [1] => Array
                (
                    [0] => 11 Pm
                )

        )

    [3] => Array
        (
            [0] => 2017-11-04
            [1] => Array
                (
                    [0] => 03 Pm
                )

        )

)

Thanks in advance..
Regards,
Anwar

A: Something of that fashion should do the trick...
Its nowhere near the fastest way to do so but it should get you going and it is pretty easy to read/understand
// putting the times in a new array where the date is the key

$byDate = [];
foreach ($firstArray as [$date, $time]) {
    $byDate[$date][] = $time;
}

// going thru it again to have it the way you needed it

$newArray = [];
foreach ($byDate as $date => $times) {
    $newArray[] = [$date, $times];
}


text:
Q: Executor Service: Why a program never stops? I am hoping almost everyone who has used ExecutorService to running Threads must have observed this. But I could not find any solutions to this problem. And hence I am asking.
My below program never comes to a Halt. I have waited for 5 minutes now, but the program is still running.
When I add executor.shutdown(), the program stops.
While I know what shutdown() method does, what I am not sure is DO WE HAVE TO CALL THIS METHOD EVERYTIME WE USE A EXECUTORSERVICE?
public class Latch implements Runnable{

    /**
     * @param args
     */
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(3);
        ExecutorService executor = Executors.newFixedThreadPool(10);
        for(int i = 0; i < 3; i ++){
        executor.execute(new Latch(latch));
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("STOPPED");
        executor.shutdown();
    }

    CountDownLatch latch;

    Latch(CountDownLatch latch){
        this.latch = latch;
    }

    @Override
    public void run(){
        System.out.println("Thread Started");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        latch.countDown();

    }

}

A: The javadoc of Executors.newFixedThreadPool() states

The threads in the pool will exist until it is explicitly shutdown.

Basically that ExecutorService spawns some non-daemon threads that it doesn't stop until you call shutdown(). Your process will not end until all non-daemon threads die.
So call it if you need your application to end or use your own ThreadFactory. Here is an improved version using daemon threads and a thread pool with as many threads as your computer has CPU cores:
Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory()
{
    @Override
    public Thread newThread(final Runnable r) {
        Thread t = new Thread(r);
        t.setDaemon(true);
        return t;
    }
});


text:
Q: Chrome grey box appearing (border-bottom-color, outline-color, color?) I have an odd light grey, what I think is a background box rendered by Chrome. I cannot seem to be able to override it with a reset nor additional CSS values that would negate the box.
Screenshot:

color: rgb(127, 127, 127);
display: block;
font-family: Georgia;
font-size: 16px;
height: 300.59375px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
outline-color: rgb(127, 127, 127);

This seem to be the source of the problem, either the color value or the outline value, but I can't seem to override this... Using current HTML5reset

A: Have you tried: border-style: none; ?


text:
Q: I am getting no data found error in pl/sql I am getting no data found error in pl/sql
Actually problem is in the trigger
I want to use NO_DATA_FOUND error in the elsif statement
alter table SUPPLIER  add  trusted_supplier VARCHAR(30)

and then update it with the data that I load in the table
UPDATE SUPPLIER SET   trusted_supplier ='Exotic Liquids'

while using the select statement I have only one value in the trusted_supplier so if insert value in the product is not equal to that
trusted supplier value I am getting error as no data found
is there any way i use NO_DATA_FOUND error which is predefined in pl/sql in the else if statement
CREATE OR REPLACE TRIGGER CHECK_SUPPLIER
BEFORE INSERT ON PRODUCT

FOR EACH ROW

DECLARE
supplier_info varchar(400);
 except1 exception;
begin

select SUPPLIER_NAME
INTO supplier_info
FROM PRODUCT P JOIN SUPPLIER S
ON S.COMPANY_NAME = P.SUPPLIER_NAME
where S.trusted_supplier = :NEW.SUPPLIER_NAME ; here

if(supplier_info = 'Exotic Liquids') then
dbms_output.put_line('trusted supplier')
elsif
---------here

END IF;

exception
when except1 then
dbms_output.put_line('its not the trusted supplier');
END;
/


text:
Q: Obtain list of IDs inserted from pandas to_sql function The following Python code successfully appends the rows belonging to the pandas dataframe into an MS SQL table via the SqlAlchemy engine previously configured.
df.to_sql(schema='stg', name = 'TEST', con=engine, if_exists='append', index=False)
I want to obtain the auto-generated IDs numbers for each of the rows inserted into the stg.Test table. In other words, what is the SqlAlchemy equivalent to the Sql Server OUTPUT clause during an INSERT statement

A: Unfortunately, there is no easy solution to your problem like an additional parameter in your statement. You have to use the behavior that new rows get the highest id + 1 assigned. With this knowledge, you can calculate the ids of all your rows.
Option 1: Explained in this answer. You select the current maximum id, before the insert statement. Then, you assign ids to all the entries in your DataFrame greater than the previous maximum. Lastly, insert the df which already includes the ids.
Option 2: You insert the DataFrame and then acquire the highest id. With the number of entries inserted you can calculate the id of all entries. This is how such an insert function could look like:
def insert_df_and_return_ids(df, engine):
    # It is important to use same connection for both statements if
    # something like last_insert_rowid() is used
    conn = engine.connect()

    # Insert the df into the database
    df.to_sql('students', conn, if_exists='append', index=False)

    # Aquire the maximum id
    result = conn.execute('SELECT max(id) FROM students') # Should work for all SQL variants
    # result = conn.execute('Select last_insert_rowid()') # Specifically for SQLite
    # result = conn.execute('Select last_insert_id()') # Specifically for MySql

    entries = df.shape[0]
    last_id = -1

    # Iterate over result to get last inserted id
    for row in result:
        last_id = int(str(row[0]))
    conn.close()

    # Generate list of ids
    list_of_ids = list(range(last_id - entries + 1, last_id + 1))

    return list_of_ids

PS: I could not test the function on an MS SQL server, but the behavior should be the same. In order to test if everything behaves as it should you can use this:
import numpy as np
import pandas as pd
import sqlalchemy as sa

# Change connection to MS SQL server
engine = sa.create_engine('sqlite:///test.lite', echo=False)

# Create table
meta = sa.MetaData()
students = sa.Table(
   'students', meta,
   sa.Column('id', sa.Integer, primary_key = True),
   sa.Column('name', sa.String),
)
meta.create_all(engine)

# DataFrame to insert with two entries
df = pd.DataFrame({'name': ['Alice', 'Bob']})

ids = insert_df_and_return_ids(df, engine)
print(ids) # [1,2]

conn = engine.connect()
# Insert any entry with a high id in order to check if new ids are always the maximum
result = conn.execute("Insert into students (id, name) VALUES (53, 'Charlie')")
conn.close()

# Insert data frame again
ids = insert_df_and_return_ids(df, engine)
print(ids) # [54, 55]

EDIT: If multiple threads are utilized, transactions can be used to make the option thread-safe at least for SQLite:
conn = engine.connect()
transaction = conn.begin()
df.to_sql('students', conn, if_exists='append', index=False)
result = conn.execute('SELECT max(id) FROM students')
transaction.commit()


text:
Q: div width should be equal to the body width I am having a problem  with my CSS code. I want the div .top & .header equal to the width of the
body but it limits to the width of the container. I want it remain inside the container class.
Thanks,

body {
    margin: 0;
    padding: 0;
    background: #000;
    position: relative;
}
.container {
    position: relative;
    width: 910px;
    height: 800px;
    border: 1px solid #fff;
    background: url(images/bg_home.jpg) no-repeat right;
    margin: 0 auto;
    z-index: 0;
}
.top {
    background: #00112b;
    width: 100%;
    position: relative;
    height: 49px;
    z-index: 2;
    opacity: 0.50;
    filter: alpha(opacity=50);
}
.header {
    position: relative;
    left: 0;
    opacity: 0.50;
    filter: alpha(opacity=50);
    background: #012e46;
    width: 100%;
    height: 99px;
    z-index: 2;
}
.header .login {
    background: red;
    opacity: 100;
    filter: alpha(opacity=100);
    float: right;
}
.logo {
    position: absolute;
    top: 15px;
    left: 0;
    z-index: 3;
}

html

            -- Schedule an appointment --

A: Your question also contains the answer.

I want the div .top & .header equal to the width of the body

This could be achieved by having an attribute / property of width: 100%;

but it limits to the width of the container

This is because the container is the parent of the child element. Which means the max width of the child element is the width of the parent.

I want it remain inside the container class.

Which means, you'll have to give the container the property of width: 100%.
You can also solve this by using the overflow property, but I assume that is not what you'd like.
http://www.w3schools.com/cssref/pr_pos_overflow.asp

Which ofcourse means:
.container {
    position: relative;
    width: 100%;
    height: 800px;
    border: 1px solid #fff;
    background: url(images/bg_home.jpg) no-repeat right;
    margin: 0 auto;
    z-index: 0;
}

Also, not related to your question but to your CSS, you have a property of background which loads an image and not repeat.
Is this what you want or is it a pattern? In the last case, consider it making a small picture to repeat over the entire page, this reduces the load time of the webpage.
If the question was regarding your background not meeting the bodys width, consider adding it to the body tag instead of the container tag.

A: Although you have given .top and .header a width of 100% - they sit inside the container div which has a width of 910px. Therefore by saying .top width 100% you are basically saying .top width 910px because it is a child of container therefore it will take on those styles.
Why do the .top and .header need to sit inside the container? If you would them to be 100% i.e. fill the whole browser window, then you should take them outside the container div.
Good luck

A: Like this
please remove width:100%; for below selector:
css
.top {
    background: #00112b;

    position: relative;
    height: 49px;
    z-index: 2;
    opacity: 0.50;
    filter: alpha(opacity=50);
}
.header {
    position: relative;
    left: 0;
    opacity: 0.50;
    filter: alpha(opacity=50);
    background: #012e46;

    height: 99px;
    z-index: 2;
}


text:
Q: What is the recommended action on receving ChangeFeedObserverCloseReason.ObserverError? My ChangeFeedProcessor's IChangeFeedObserver.CloseAsync callback was invoked with ChangeFeedObserverCloseReason as "ObserverError". So, far I have seen this error only once and I am not sure how to repro it. What causes this error? Is there a way to diagnose this more? Is there any recommended action that one should take after receiving this error?

A: From your question, I understand you are using Change Feed Processor.
That Close reason is provided when the code in your ProcessChangesAsync implementation throws an unhandled exception.
Basically, if that happens, it means your code had an error processing the changes so:

*

*The Observer is closed, releasing the Lease

*The lease becomes available to be picked by any Host instance

*The lease gets picked up by a Host, an Observer started, the same batch of changes gets sent to be processed

*If the nature of your error was transient, then this time it will work (hopefully). If its not transient, then you will again face an ObserverError.

As a rule of thumb, always try to manage your exceptions if possible, if not, it will be treated as a temporary scenario and will get eventually retried as I described.
Also please next time give more context, describe which libraries and versions you are using and provide some related code. It will help a lot understanding and diagnosing.


text:
Q: Convert character entities to their unicode equivalents I have html encoded strings in a database, but many of the character entities are not just the standard & and <.  Entities like " and —. Unfortunately we need to feed this data into a flash based rss reader and flash doesn't read these entities, but they do read the unicode equivalent (ex ").
Using .Net 4.0, is there any utility method that will convert the html encoded string to use unicode encoded character entities?
Here is a better example of what I need.  The db has html strings like:
John & Sarah went to see $ldquo;Scream 4$rdquo;.
 and what I need to output in the rss/xml document with in the <description> tag is: <p>John &#38; Sarah went to see &#8220;Scream 4&#8221;.</p>
I'm using an XmlTextWriter to create the xml document from the database records similar to this example code http://www.dotnettutorials.com/tutorials/advanced/rss-feed-asp-net-csharp.aspx
So I need to replace all of the character entities within the html string from the db with their unicode equivilant because the flash based rss reader doesn't recognize any entities beyond the most common like &.

A: My first thought is, can your RSS reader accept the actual characters? If so, you can use HtmlDecode and feed it directly in.
If you do need to convert it to the numeric representations, you could parse out each entity, HtmlDecode it, and then cast it to an int to get the base-10 unicode value. Then re-insert it into the string.
EDIT:
Here's some code to demonstrate what I mean (it is untested, but gets the idea across):
string input = "Something with — or other character entities.";
StringBuilder output = new StringBuilder(input.Length);

for (int i = 0; i < input.Length; i++)
{
    if (input[i] == '&')
    {
        int startOfEntity = i; // just for easier reading
        int endOfEntity = input.IndexOf(';', startOfEntity);
        string entity = input.Substring(startOfEntity, endOfEntity - startOfEntity);
        int unicodeNumber = (int)(HttpUtility.HtmlDecode(entity)[0]);
        output.Append("&#" + unicodeNumber + ";");
        i = endOfEntity; // continue parsing after the end of the entity
    }
    else
        output.Append(input[i]);
}

I may have an off-by-one error somewhere in there, but it should be close.

A: would HttpUtility.HtmlDecode work for you?
I realize it doesn't convert to unicode equivalent entities, but instead converts it to unicode.  Is there a specific reason you want the unicode equivalent entities?
updated edit

        string test = "
John & Sarah went to see “Scream 4”.
";
        string decode = HttpUtility.HtmlDecode(test);
        string encode = HttpUtility.HtmlEncode(decode);

        StringBuilder builder = new StringBuilder();
        foreach (char c in encode)
        {
            if ((int)c > 127)
            {
                builder.Append("&#");
                builder.Append((int)c);
                builder.Append(";");
            }
            else
            {
                builder.Append(c);
            }
        }
        string result = builder.ToString();

A: you can download a local copy of the appropriate HTML and/or XHTML DTDs from the W3C. Then set up an XmlResolver and use it to expand any entities found in the document.
You could use a regular expression to find/expand the entities, but that won't know anything about context (e.g., anything in a CDATA section shouldn't be expanded).

A: this might help you put input path in textbox
        try
        {
            FileInfo n = new FileInfo(textBox1.Text);
            string initContent = File.ReadAllText(textBox1.Text);
            int contentLength = initContent.Length;
            Match m;

            while ((m = Regex.Match(initContent, "[^a-zA-Z0-9<>/\\s(&#\\d+;)-]")).Value != String.Empty)
                initContent = initContent.Remove(m.Index, 1).Insert(m.Index, string.Format("&#{0};", (int)m.Value[0]));

            File.WriteAllText("outputpath", initContent);
        }

        catch (System.Exception excep)
        {

            MessageBox.Show(excep.Message);

        }

    }


text:
Q: How to display an object in PowerShell cmdlet whose one property itself is an complex object I have a cmdlet which outputs an user-defined object Metric.
Metric class has data-members:

*

*Count - of type int16

*Dimension - of type List<MetricDimension>
MetricDimension is a user-defined object with data-members:

*

*Name - of type String

*OperatorProperty - of type String

*Values - of type List<String>
When I output my Metric object following output is shown.

Dimension : {Dim1,Dim2}
Count     : 2

What I want is that it should display the complete details of the object (MetricDimension) including OperatorProperty & Values list not just the Name.
Is it possible to display every property of dimensions object?
// Summary:
//     Specifies a metric dimension.
public class MetricDimension
{
    public MetricDimension();
    public MetricDimension(string name, string operatorProperty, IList<string> values);

    [JsonProperty(PropertyName = "name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "operator")]
    public string OperatorProperty { get; set; }

    [JsonProperty(PropertyName = "values")]
    public IList<string> Values { get; set; }

    public virtual void Validate();
}

public class Metric
{
    public Metric();
    public Metric(int16 count, MetricDimension dimension);

    [JsonProperty(PropertyName = "count")]
    public int16 Count { get; set; }

    [JsonProperty(PropertyName = "dimension")]
    public IList<MetricDimension> Dimension{ get; set; }
}

A: The standard output will rarely drill-down into your deep object graph to display pleasingly. You could convert to JSON to see it all:
do_your_thing | ConvertTo-Json

Beware of circular references. You can limit the depth that it descends to with the -Depth parameter.


text:
Q: HTTP Redirect Status code for redirect a web to the mobile version Which HTTP redirect status code is the best for redirect a webpage to the mobile version?
From:
www.example.com
To:
m.example.com

A: I would send a 301 while using Vary to specify the request header fields that lead to this server-driven negotiation decision.
So, assuming that the User-Agent header field is used to distinguish whether the request was made by a mobile device, I would use this:
HTTP/1.1 301 Moved Permanently
Vary: User-Agent
Location: http://m.example.com/...

A: A temporary redirection (302 or 307) should be sufficient for this.
The Google guidelines for smartphone site redirections states-

For this purpose, it does not matter if the server redirects with an
  HTTP 301 or a 302 status code.

As such, a 302 is probably preferable over 307.
The guidelines suggest that the "vary" header should be part of the 200 response.


text:
Q: How to add any specific object's page layout in package.xml? I am trying below code in package.xml.
<types>
    <members>Quote Layout</members>
    <name>Layout</name>
</types>

but got error as below.

== WARNING: The following metadata isn't in your org. If it's not new, someone deleted it from the org. Entity of type 'Layout' named
  'Quote Layout' cannot be found sfdx force:source:retrieve
  --manifest g:\My Drive\SB\manifest\package.xml ended with
  exit code 0

The page layout is present in org.
Please point out what I am doing wrong here?

A: You can try with:
<types>
    <members>Quote-Quote Layout</members>
    <name>Layout</name>
</types>

For any unpackaged object and page layout format will be
<Object Name>-<Layout Name>

For object and pagelayout which has namespace format look like
<namespace>__<Object Name>-<namespace>__<Layout Name>

You can refer Layout metadata.

A: You need to make sure that the name of that page layout is in your org. It looks like there is not page layout with the name "Quote Layout". Make sure that this is not the case. It is good to explicitly named your page layout. You can use the ObjectName.PagelayoutName
<types>
    <members>ObjectName.PagelayoutName</members>
    <name>Layout</name>
</types>

First .- Make sure that there is a page layout with that name.
If there is not one.... there is why you are getting that error.
Second . -Try to use the ObjectName.PagelayoutName member.


text:
Q: Angular repeater save $index in node prop I want to take the $index from the repeater and save it on the current node in a prop called sort.
somehow like this

where the line below shows what to focus on here.

ng-mode=['node.Sort' = $index]

So. Take the ng-repeat index, and save it on the current child node's prop called Sort.
the reason behind this is that i need to have the sort updated when i move the elements in the

can this be done?

A: In your ng-repeat directive add ng-init like this

  {{ node.Sort }}

http://plnkr.co/edit/WeUeBxGBJVUYErWY3hAX


text:
Q: Angular controller to retrieve json data Here I'm actually trying to get json data and display them on a jade template with the use of an angular controller.
Controller : processJson.js
 var getJson = angular.module('getJson', []).controller('controller1',   function ($scope, $http) {
var url = '/fields/fieldlist';
console.log(url);
$http.get(url).success(function (data) {
    $scope.posts = data;
  });

 });

This doesn't parse json array to jade template
fields.js
var express=require('express');
var router =express.Router();

 router.get('/fieldlist',function(req,res){
  var db=req.db;
  var collection=db.get('domlist');
   collection.find({},{},function(e,docs){
    res.json(docs);
  });
});

module.exports=router;

This successfully returns a json array object.
Here's my jade template
html
head

body
     div(ng-app='getJson')
        div(ng-controller='controller1')
            div(ng-repeat='post in posts')
                div(ng-switch-when='text')

                    input(type='text' id='{{post.id}}' ng-model='post.value' placeholder='{{post.placeholder}}')

                    block content

A: Several things here :
Don't use $http in your controller. Ajax requests and general data sending/retrieval should go in a service or a factory that you inject into your controller.
In this case, you should consider coding a fieldService containing a getFields() method and invoking it from your controller.
Since I highly doubt this is the cause of your problem, I'm going to point out what bugged me in your examples:

*

*Your use of $http is prone to a lot of headaches, if not wrong at all. You might be interested by $http's documentation, which explains the most recommended ways of using it. Also consider catching errors on your requests, just in case anything goes wrong and prevents your data to be displayed.

*In your template, you're using a ng-switch-when attribute without any parent ng-switch. I'm no expert of course, but I'm not sure it's going to work. If you want your div to show when 'text' is truthy, consider using ng-if or ng-show, or even a filter in your ng-repeat.

*I also assume 'text' is a scope variable you forgot to put in your example.

*Your url is not the same in both your examples, are you sure they're both correct?
I don't have time to try to reproduce your issue, sorry. I hope at least one of these points might help you understanding what you did wrong.

A: To test your solution consider breaking it down into separate testable components.  Frequently use of the ng-init angular directive supplied with hard-coded JSON can reveal problems and incorrect assumptions.
Here is a SO question on ng-init....
SO ng-init-json-object


text:
Q: Alternatives to PropertyInfo.GetValue() for Mono? I have a method that has the following signature:
 private object GetNestedObject<y>(y objToAccess, string nestedObjectName)

I'm using Reflection to get the nestedObject from the objToAccess and return it.
This works well except it's really slow (I have to do this a few hundred thousand times).
I came across HyperDescriptor, but since I'm running this on Linux, and Mono doesn't support TypeDescriptionProviders, I can't use it.
Are there any alternatives to using getValue in this case? I could always hardcode in overrides for each type, but that is not desirable and would add a lot of maintenance overhead in my case.

A: Jon Skeet wrote a blog post about using Delegate.CreateDelegate() to speed things up:
http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx
I don't know if it will work in Mono though.

A: I'm not sure if Mono supports it, but for such cases (using Reflection in high-load code), I usually dynamically generate special access classes using System.Reflection.Emit. They take a bit longer to generate, but after that, access is lightning fast.

A: Do you have to use magic strings?  Another option is passing in a lambda expression, either by writing the lambda expression into your code or generating a member access lambda expression using Expression Trees.  If you go the sxpression tree route, you can compile the expressions very easily and cache them for use.


text:
Q: Как в WebStorm 2020 включить автосохранение файлов при потере фокуса? Как в WebStorm 2020 включить автосохранение файлов при потере фокуса?
Данная опция почему то выключилась, и без ctrl + s файлы не сохраняются, не получается просто альт табнутся в браузер и увидеть результат реакт хот лоадера, подскажите пожалуйста как снова включить автосохранение файлов при потере фокуса вебштормом?

A: Попробуйте включить Settings | Appearance & Behavior | System Settings, Save files on frame deactivation


text:
Q: How to read Date from textBox, having Jquery UI DatePicker The below Jquery UI Date Picker shows the date in correct format, but reads it wrong.
HTML:
<input type="text" id="date">
<input type="button" id="btn" value="Show"/>

JavaScript:
$('#date').datepicker({dateFormat: 'dd-mm-yy'});
$('#btn').click(function(){
  var _myDate = new Date($('#date').val());
  alert(_myDate);
});

Whats wrong? ( Jsfiddle Here)
It shows the date correct, but reads it wrong...
When I use it like this:
$('#btn').click(function(){
      var _myDate = $('#date').val();
      alert(_myDate);
 });

It's ok, but when pass it to Server side using C# as string and then converting it to DateTime it gives me error of Invalid Date when every Day is selected greater than 12. It treats with Day as a month. And my required format of Date is dd/mm/yyyy.

A: maybe this is your answer
$( "#date" ).datepicker({dateFormat: 'mm-dd-yy'});
    $('#btn').click(function(){
    var _myDate = new Date($('#date').val());
    var new_date=_myDate.split('-');
    var month=new_date[0];
    var day=new_date[1];
    var year=new_date[2];
    //you have 3 data, month, day and year.

    alert(month+"/"+day+"/"+year);
    });

you can use that 3 variable day, month, year to write your programs

A: Change var _myDate = new Date($('#date').val()  ); to var _myDate = $('#date').val());

A: try like this
$( "#date" ).datepicker({dateFormat: 'mm-dd-yy'});
$('#btn').click(function(){
var _myDate = new Date($('#date').val()  );
alert(_myDate);
});

DEMO

A: You don't need the Date type declaration - you can just do
$( "#date" ).datepicker({dateFormat: 'dd-mm-yy'});
$('#btn').click(function(){
  var _myDate = $('#date').val();
alert(_myDate);
});

Javascript is a dynamically typed language so the Date initialisation is unnecessary

A: Try this: it's work fine
  $('#date').datepicker({dateFormat: 'dd-mm-yy',  changeMonth:true, changeYear:true,showOn: "both",buttonImage: "",buttonImageOnly: false });

console.log($('#date').val());

A: My javaScript function...
convertDate = function (strDate) {
   var newDate = new Date();
   var oldDate = '';
   if (strDate.contains('/')) {
         oldDate = strDate.split('/');
      } else if (strDate.contains('-')) {
         oldDate = strDate.split('-');
      }
     //OldDate format is dd/mm/yyyy
      newDate.setDate(oldDate[0]);
      newDate.setMonth(oldDate[1] - 1);
      newDate.setYear(oldDate[2]);
      return newDate;
 }

A: Just parse the textbox value using parseDate with the same format you initially set up the datepicker:
console.log($.datepicker.parseDate("dd-mm-yy", $('#date').val()));

parseDate will return a Date object so that you don't need to create it manually.


text:
Q: CS:EIP in comparison I'm trying to understand booting in xv6 (a teaching OS) with gdb.
One of the instructions during the initial boot is (AT&T syntax):
cmpl 0x0,%cs:0x65a4

And then,
jne 0xfd2b9

Now, from what I understand, cmpl compares the two values and sets flags, jne looks at the flags and jumps if the values just compared were not equal.
But I don't understand the meaning of %cs:0x65a4 as the operand. Is this referring to the value of the address (cs*16 + 65a4), or the actual contents of that memory location?
I'm asking because the system doesn't end up jumping after the jne instruction, which means the second operand (%cs:0x65a4) evaluated to zero. But that shouldn't be, since neither the address nor its contents is zero.

A:
Is this referring to the value of the address (cs*16 + 65a4), or the actual contents of that memory location?

The 32-bit word in the memory located at the address (cs*0x10 + 0x65a4) is compared to the value 0 - assuming the CPU runs in "real mode".
However something appears very strange to me:
You talk about "cs*0x10" which is the address calculation for "real mode". Since the 80286 there is a second addressing mode called "protected mode". In this mode the absolute address cannot be calculated that simply...
The CPU can only be in "32-bit mode" when it is running in protected mode. The 16-bit and the 32-bit instruction set of x86 CPUs is different!
And "jne 0xfd2b9" definitely is a 32-bit instruction and EIP is definitely a 32-bit register.
So either ...

*

*... the CPU runs in real mode but the disassemled code you see is 32-bit code (so the disassembly is wrong)

*... the CPU runs in real mode but you assembled 32-bit code (so the code is wrong)

*... the CPU runs in protected mode so the calculation cs*0x10 is wrong


text:
Q: Selenium: How to get text without clicking on tab? I'm trying to find text that is located on a specific tab. For some reason the text is available in the html but when I use the command driver.find_element_by_id('hand-graph-title-overview').text without clicking on the 'Overview' tab it returns a empty string. However, when I do click on the 'Overview' tab it will return 'Unpaired OOP' successfully. Does anyone know how to get the text without clicking on the tab?
Images of what I'm trying to scrape.
https://i.stack.imgur.com/9nSc0.png
https://i.stack.imgur.com/MyvDA.png

A: Maybe try and get the 'value' attribute of the element.
driver.find_element_by_id('hand-graph-title-overview').get_attribute('value')

A: The answer is no. You can't access the element from the other tab without focusing on it. Retrieval of text is totally based on the presence of the element on the current page. When you click on tab then automatically it gets loaded in the dom and then only you can access the element.


text:
Q: How to persist bearer token on client side I'm trying to get my head around claims based authentication in ASP.NET Web API 2. In my application I use the VS 2013 template, which implements OAuth 2.0 and uses bearer token (JWT as I remember). My question is - what is the best way to persist token on the client side. In his book Badrinarayanan Lakshmiraghavan describes bearer token as

A bearer token is like cash: finders, keepers.

Therefore, is it safe to save it to a cookie? Doesn't it mean that whoever will steal the cookie will get full access to the application? On the other hand I could encrypt the token using hash just before saving it to the cookie. Would it be safe enough? Are there any other alternatives? I've seen few questions asking similar question on stackoverflow, but have never found satisfying answer.

A:
is it safe to save it to a cookie?

No. Cookies can be stolen via XSS attacks (and other vectors)
Also, this might be susceptible to CSRF since a cookie will be submitted automatically with any request.

I could encrypt the token using hash just before saving it to the cookie

This will also not work. Hashing is not a secure way to encrypt (and moreover does not allow decryption)

Are there any other alternatives?

Basically, you should give the token to the user over a secured connection (HTTPS) but they should manually submit it for security (again over HTTPS)


text:
Q: Why is 1>a.txt 2>&1 different from 1>a.txt 2>a.txt ? (Example shown) EDIT
Please see not only the accepted answer but also the other one(s).
Question
Why does redirecting both STDOUT and STDERR to the same file not work, although it looks like the same as 1>[FILENAME] 2>&1 ?
Here is an example:
perl -e 'print "1\n" ; warn "2\n";' 1>a.txt 2>a.txt
cat a.txt
# outputs '1' only.

Well, why? I thought that this works because... STDOUT is redirected to a.txt and so is STDERR. What happened to STDERR?

A: With 1>a.txt 2>&1, file descriptor #1 is duplicated to #2. They both reference the same "open file", and they both share the current position and r/w mode. (There's actually no difference at all between using 2>&1 and 2<&1.)
With 1>a.txt 2>a.txt, both file descriptors are opened independently and have separate cursor positions. (The file gets truncated twice too.) If you write "Hello" to fd #1, its position is advanced to byte 5, but fd #2 remains at byte 0. Printing to fd #2 will just overwrite the data starting from 0.
This is easy to see if the second write is shorter:
$ perl -e 'STDOUT->print("abcdefg\n"); STDOUT->flush; STDERR->print("123");' >a.txt 2>a.txt

$ cat a.txt
123defg

Note that Perl has internal buffering, so in this example an explicit flush() is necessary to ensure that fd #1 data is written before fd #2 data. Otherwise, the streams would be flushed in unpredictable order on exit.
For comparison, if the file descriptors are shared, the writes just follow each other:
$ perl -e 'STDOUT->print("abcdefg\n"); STDOUT->flush; STDERR->print("123");' >a.txt 2>&1

$ cat a.txt
abcdefg
123

A: Both your redirections truncate the file, so the second (in chronologial order of execution) will overwrite the first. Try
rm a.txt ; touch a.txt ; perl -e 'print "1\n" ; warn "2\n";' 1>>a.txt 2>>a.txt

Or just use the same file descriptor
perl -e 'print "1\n" ; warn "2\n";' 1>a.txt 2>&1


text:
Q: How can I make the ASP.NET MVC mini profiler work with Linq 2 SQL? The ASP.NET MVC Mini Profiler looks awesome, but I don't get the Linq 2 SQL usage example.
This is the Linq2SQL example from the profiler documentation:
partial class DBContext
{
   public static DBContext Get()
   {
      var conn = ProfiledDbConnection.Get(GetConnection());
      return new DBContext(conn);
      // or: return DataContextUtils.CreateDataContext<DBContext>(conn);
   }
}

How do I use this in my actual application? I would have expected some kind of wrapper around my DataContext, but this seems to work in a different way. I don't even know where that that "GetConnection()" method from the example is defined.
Thanks,
Adrian

A: Finally figured it out. In case someone else has the same question:
 private static DataClassesDataContext CreateNewContext()
        {
            var sqlConnection = new SqlConnection(<myconnectionstring>);
            var profiledConnection = ProfiledDbConnection.Get(sqlConnection);
            return DataContextUtils.CreateDataContext<DataClassesDataContext>(profiledConnection);

        }

A: None of the other answers worked for me. Adding this to my DataClassesDataContext Class in my DataClasses.Designer.cs did:
public static DataClassesDataContext CreateNewContext()
{
     var sqlConnection = new DataClassesDataContext().Connection;
     var profiledConnection = MvcMiniProfiler.Data.ProfiledDbConnection.Get(sqlConnection);
     return new DataClassesDataContext(profiledConnection);
}

A: GetConnection() is a function that would return a DbConnection. You'll probably just do
var conn = ProfiledDbConnection.Get(new System.Data.SqlClient.SqlConnection(your_connection_string));

instead.