text:
Q: How to insert href link in this button tag Hey i want to put this into href link in this button how to input that

\"/led=ON\"\"

This is button code with animation
<button type="button" class="btn btn-primary btn-cons btn-animated from-top fa fa-arrow-up">Open</button>

A: To give you a very bare-bones example of my comment above (formatting a link as a button), here is a decent place to start. Feel free to format it however you want of course.
HTML Hyperlink:
Example

CSS Class:
.linkLikeButton {
  display: inline-block;
  border: 2px solid black;
  padding: 10px;
  background-color: steelblue;
  color: white;
  text-decoration: none;
}

  .linkLikeButton:hover {
    background-color: lightblue;
  }


text:
Q: Latex problem with indentation During writing an algorithm using Latex syntax I encountered indentation problem that procedures started in one place and ended in another.
Part of code:
\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\makeatletter
\def\BState{\State\hskip-\ALG@thistlm}
\makeatother

\begin{document}
\begin{algorithm}
\caption{Test}\label{euclid}
\begin{algorithmic}[1]

\State $\textit{currentS} \gets \textit{initialS}$
\State $\textit{bestS} \gets \textit{currentS}$
\State $\textit{listTest} \gets \left[ \right]$
\While{$fitness(bestS) < 0$}{
\State $\textit{bestC} \gets \textit{null}$
\For {($\textit{ca} \in \textit{currentS.get})}${
\If{($\neg\textit{listTest.contains(c)})$}{
\EndIf}
\EndFor}
\EndWhile}
\State \Return  $\textit{bestSolution}$
\end{algorithmic}
\end{algorithm}
\end{document}

A: You're misusing the tool: the syntax for \While is
\While {<condition>}
...
\EndWhile

with no braces around the contents of the loop.
Full code (I added a \State in the inner \If); note also that \mathit is preferable to \textit. For the null array I changed \left[\right] into [\,].
\documentclass{article}
\usepackage{amsmath}
\usepackage{algorithm}
\usepackage{algpseudocode}
\makeatletter
\def\BState{\State\hskip-\ALG@thistlm}
\makeatother

\begin{document}
\begin{algorithm}
\caption{Test}\label{euclid}
\begin{algorithmic}[1]

\State $\mathit{currentS} \gets \mathit{initialS}$
\State $\mathit{bestS} \gets \mathit{currentS}$
\State $\mathit{listTest} \gets [\,]$
\While{$\mathit{fitness}(\mathit{bestS}) < 0$}
  \State $\mathit{bestC} \gets \mathit{null}$
  \For {($\mathit{ca} \in \mathit{currentS.get})}$
    \If{($\neg\mathit{listTest.contains(c)})$}
      \State do something
    \EndIf
  \EndFor
\EndWhile
\State \Return  $\mathit{bestSolution}$
\end{algorithmic}
\end{algorithm}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot login in to my google account on nexus one or acer iconia because of google 2-step verification I am trying to setup my nexus one and acer iconia google email account and I keep getting "Your username and password do not match". I'm pretty sure it's correct and I strongly suspect it's because of the google 2-step verification:
google 2-step verification
How can I fix this?

A: Go to your google account settings page. Then click on the edit button next to "Using 2-step verification". Then click on "Manage application-specific passwords". Finally, use the box below things to generate a password.


text:
Q: How to keep track of large numbers of A/B and Multivariate experiments for optimizing websites? How do you keep track of A/B testing results for millions of pageviews?
The website is running a LAMP stack, and has a separate mysql server just for analytics, so there is a lot of space for data, but the question is how to organize and plan for large A/B testing.
Are there any guidelines that are recommended for trying to manage such large A/B experiments (both in number of experiments as well as size of experiments)?
Are there any common open-source tools that are used?
And if you know, How do Facebook/Google/LinkedIn manage their experiments? and have they released any open-source code?

A: I have used Google Website Optimizer to track multiple AB and Multivariant tests. It has nice reporting features too.


text:
Q: Randomly scheduled tasks and celery Everyday I have a set of tasks (A few hundred) that needs to performed at random time. So a periodic task is probably not what I want. It seems like I cannot dynamically change crontab
Should I:
Dynamically schedule a task whenever it's received a user, and let celery "wake up" at the scheduled time to perform the task? If so, how is it done?
OR
Create a celery tasks that wakes up every 60 seconds to look into the database for tasks scheduled current time. So the database acts as a queue. I am wondering if this would put too much load on the server?


text:
Q: DP: find minimum time and print operations of calculator My task is different from another questions dedicated to "primitive calculator" problem.
You are given a primitive calculator that can perform the following three operations with the current number x: multiply x by 2(for time b), multiply x by 3(for time c), or add 1 to x(for time a). Your goal is given a positive integer n, find the minimum time needed to obtain the number n starting from the 0, and also print operations to obtain the number in this format:
x + 1 "add"
x * 2 "double"
x * 3 "triple"
Sample Input:

25 1 4 5

Sample Output:

14
add
add
add
add
triple
double
add

First steps should be obvious(we have 0 at start, and 1st operation will be "add" in any case(bc 0 * 2 = 0 and 0 * 3 = 0):
input_data = [int(x) for x in input().split()]
n = input_data[0]
a = input_data[1]
b = input_data[2]
c = input_data[3]
def primitive_calc(n):
    oper = []
    time = []
    oper[0] = "add"
    time[0] = a

But after then ... I don't know how to set up x+1,x2,x3 in my case. Saving time shouldn't be a problem(appending a,b,c in list and sum(time) as result). But how to save operations?
Please, don't write exact solution, instead give me ideas and hints. Any help will be appreciated.

A: A simple iterative implementation can provide a solution with O(n) complexity.
Let us call T[i] the minimum time to arrive at level i. Then,
T[i+1] <= T[i] + a
T[2*i] <= T[i] + b
T[3*i] <= T[i] + c

Concerning the path to follow in order to get the minimum time, it is enough at each step to memorise the choice S[i] that lead to T[i]
Then a possible iterative implementation is:
Initialisation
T[i] = infinite
T[1] = a
S[i] = Null
S[1] = add

Iteration
Do i = 2 to n-1
    T[i+1] = min(T[i+1], T[i] + a) -> if min obtained, S[i+1] = add
    T[2*i] = min(T[i+1], T[i] + b) -> if min obtained, S[2*i] = double
    T[3*i] = min(T[i+1], T[i] + c) -> if min obtained, S[3*i] = triple

Output
Min cost = T[n]
Path: use the S[i] from S[n] in reverse order


text:
Q: Binding to an inner list with bindingbeans on a jTable I'm not a Java guy and I need to make some basic CRUD working on a swing application.
Imagine a easy table:
Category:
    name
    products

and a Products one:
Product:
    name

What I need is to display a list of categories and the total of products for every category.
So I made something like "SELECT c FROM Category c" and binded the Query result to the jTable.
So I can bind a column to name using:
${name}

So far so good, but what about binding the total products? I tried:
${products.size()}

No luck.
So I went to another option:
SELECT c, COUNT(p.id) FROM Category c JOIN c.products p GROUP BY c

With that, I get a list like this:
{0} ->
  {0} -> Category
  {1} -> Count
{1} ->
  {0} -> Category
  {1} -> Count
{2} ->
  {0} -> Category
  {1} -> Count
...

And here is where I'm stuck.
How can I bind to those items?
I meant:
${name}

That doesn't work anymore because the category item is inside a inner list, I tried a lot of things:
${category.name}
${Category.name}

None of these works.
So, how can I bind to elements of the first sublist (category) and the count item in the second list?
Or... Is there a better way?
Thanks!


text:
Q: Rename levels of factors that contain symbols in R I have a data frame called prueba where I have a factor variable ccaa that contains the following levels:
x <- c("","Andalucia","Aragon","Asturias","Balears","Canarias","Cantabria",
       "Castilla Leon","Castilla Mancha","Catalu<f1>a","Ceuta","Comunitat Valenciana",
       "Extremadura","Galicia","Madrid","Melilla","Murcia","Navarra","Pa<ed>s Vasco",
       "Rioja")

prueba <- data.frame(cca = x)
levels(prueba$cca)

#  [1] ""                     "Andalucia"            "Aragon"               "Asturias"
#  [5] "Balears"              "Canarias"             "Cantabria"            "Castilla Leon"
#  [9] "Castilla Mancha"      "Catalu<f1>a"          "Ceuta"                "Comunitat Valenciana"
# [13] "Extremadura"          "Galicia"              "Madrid"               "Melilla"
# [17] "Murcia"               "Navarra"              "Pa<ed>s Vasco"        "Rioja"

I am trying to rename those levels that contain symbols such as "Catalu<f1>a" and "Pa<ed>s Vasco". I have tried several unsuccessful options:
Option 1: package plyr with function revalue
 prueba$ccaa = revalue(prueba$ccaa,c( "Pa<ed>s Vasco" = "Basque Country", "Catalu<f1>a" = "Catalonia"))

It yields the following error:
The following `from` values were not present in `x`: Pa<ed>s Vasco, Catalu<f1>a

Option 2:
levels(prueba$cca)[levels(prueba$cca)=="Catalu<f1>a"] <- "Catalonia"
levels(prueba$cca)[levels(prueba$cca)=="Pa<ed>s Vasco"] <- "Basque Country"

This works fine but does not rename the levels with the new labels
levels(prueba$ccaa)
#  [1] ""                     "Andalucia"            "Aragon"
#  [4] "Asturias"             "Balears"              "Canarias"
#  [7] "Cantabria"            "Castilla Leon"        "Castilla Mancha"
#  [10] "Catalu<f1>a"          "Ceuta"                "Comunitat Valenciana"
# [13] "Extremadura"          "Galicia"              "Madrid"
# [16] "Melilla"              "Murcia"               "Navarra"
# [19] "Pa<ed>s Vasco"        "Rioja"

I don't understand why the levels do not get the right labels. Any suggestion about what may be happening?

A: We can use recode from car
library(car)
prueba$cca <- recode(prueba$cca, "'Pa<ed>s Vasco'='Basque Country';'Catalu<f1>a' = 'Catalonia'")
levels(prueba$cca)
#[1] ""                     "Andalucia"            "Aragon"               "Asturias"             "Balears"              "Basque Country"       "Canarias"
#[8] "Cantabria"            "Castilla Leon"        "Castilla Mancha"      "Catalonia"            "Ceuta"                "Comunitat Valenciana" "Extremadura"
#[15] "Galicia"              "Madrid"               "Melilla"              "Murcia"               "Navarra"              "Rioja"


text:
Q: MySQL performance with large WHERE IN() clause Let's say we have a table with 4 columns: id (int 11, indexed), title, content, category (varchar 5).
I have a user select a category. Each category can contain up to 999 objects. Using SELECT id FROM table WHERE category = ? I get a list of all objects.
I then have the user select/deselect some of the objects. After which I need to select the content of the remaining selected objects.
Now my question is as follows, should I worry about performance when using SELECT content FROM table WHERE id IN($array)? Would it be better to use SELECT content FROM table WHERE category = ? AND id IN($array). The idea here being I filter it down to 999 objects before performing the IN...
Does this make any sense? Or should I not be using the IN() at all?

A: It sounds like you always have content showing on the screen?
999 is a long list to put on the screen.  Re-think your UI.
When selected/deselected, what happens?  Do you gray out the content?  If so, that is a UI issue, not a database issue.  If you store the subset that is currently "selected", then how/where is that stored?  And, do you want to store it after each select/deselect?  Or wait until he clicks "Submit"?
In other words, I don't see why this is a database question.
Back to the queries in question:
INDEX(category)
SELECT ... FROM tbl WHERE category = ...; -- This is optimal

PRIMARY KEY(id)
SELECT ... FROM tbl WHERE id IN (...); -- optimal for an arbitrary set

INDEX(category, id)
SELECT ... FROM tbl WHERE category = ... AND id IN (...)
    -- use this only if you both parts are needed for filtering
    -- not for optimizing


text:
Q: Graphite -- How to send data to carbon that have timestamps over a year old I'm using graphite to store and plot data and I want to send data points to the carbon daemon that are over a year old (first data point is from Dec 12, 2013 and last is Jan 12, 2015) but whisper does not seem to be capable (at least, not with my current settings) of accepting values more than 24-hours old.
Whenever I send metrics over a year old to carbon (using the plain text protocol), it simply drops them. I can tell because when I run whisper-fetch.py on the *.wsp file it shows timestamps from the last 24-hours all of which hold no data. However, if I send the same data (using the same protocol) with current timestamps (or any timestamp within the last 24 hours) it retains the value and is present when I run whisper-fetch.py on the *.wsp file.
I don't have any aggregation rules setup because I'm only interested in raw data points and I have my retentions setup like so:
[pos]
pattern = ^pos\.
retentions = 1m:2y

I understand that this will store data points every minute for 2 years but it is not capable of accepting data points from the past.
Is there a proper retention that will store historical data which have timestamps prior to the last 24-hrs? Or is there a setting somewhere in the *.config files that allow importing of data prior to the last 24-hrs? Or is this "feature" a limitation of whisper/carbon?
UPDATE
I should mention that the metrics I'm sending are of the format:
"pos.amps (data here) (unix timestamp here)"
I've tried a few different retention policies, including using the legacy formatting:
[pos]
pattern = ^pos\.
retentions = 120:500

Signifying to collect 1 data point every 120 seconds and store 500 data points but I've still had no luck. I read here (https://serverfault.com/questions/593157/graphite-shows-none-for-all-data-points-even-though-i-send-it-data) that whisper has some sort of query period that is set to a default of 24-hours. That is the value I would like to change but I don't know where to change it!

A: I've found my mistake, whisper-fetch.py has a default time range of the past 24 hours unless specified otherwise. One I changed the call to the format
./whisper-fetch.py --pretty --from=TIMESTAMP --until=TIMESTAMP /path/to/whisper/file.wsp

Everything worked fine and my data was there.
Another useful tip would be to use graphite's URL api to query the database and check for the data there. Here's some documentation: http://graphite.readthedocs.org/en/latest/render_api.html


text:
Q: How can I prevent Firebase user from logging into wrong login Screen Context: In my Firebase Database I have a Parent called "Clients" that stores data in "Vendor" or "Eater" depending on which the client registered as.
Issue: Registered "Vendor" can login as "Eater" and "Eater" can login as "Vendor".  With Current code, app still allows "Vendor" to login the "Eater" screen and vice versa.
What I need to do: Only allow "Vendor" to login the Vendor screen and "Eater" in the Eater screen.
Errors: I get this crash when either an Eater or Vendor Logins to the Eater screen on the
@Overridepublic void onDataChange
"java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference at com.example.zzyzj.eloteroman.login.EatCornLoginActivity$4.onDataChange"
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            circProgressBar.setVisibility(View.VISIBLE);
            final String emailUser = emailEditText.getText().toString();
            final String passwordUser = passwordEditText.getText().toString();

            firebaseAuth.signInWithEmailAndPassword(emailUser, passwordUser).addOnCompleteListener(EatCornLoginActivity.this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (!task.isSuccessful()){
                        circProgressBar.setVisibility(View.INVISIBLE);
                    } else {
                        checkIfUserIsEaterOrVendor();
                    }
                }
            });
        }
    });
}

   public void checkIfUserIsEaterOrVendor(){
    FirebaseDatabase.getInstance().getReference().
            child("Clients").
            child(FirebaseAuth.getInstance().getCurrentUser().getUid()).
            child("Eater").addListenerForSingleValueEvent(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue().equals("Eater")) {
                //Code if the user is Eater
                circProgressBar.setVisibility(View.INVISIBLE);
                Toast.makeText(EatCornLoginActivity.this, R.string.login_success_toast, Toast.LENGTH_SHORT).show();
                startActivity(new Intent(EatCornLoginActivity.this, MapsActivity.class));
            } else {
                //Code if the user is Vendor trying to login as Eater
                circProgressBar.setVisibility(View.INVISIBLE);
                Toast.makeText(EatCornLoginActivity.this, R.string.login_failed_toast, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(getBaseContext(), databaseError.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    });
}

A: You can use SharedPreferences.So you can store a userid with value of what type of user is register and check login if userid is match as your value so,it can login if you want.
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.example.pc.it7project.data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(firebaseAuth.getCurrentUser().getUid(), "Vendor");
editor.apply();

And you get value of shared preference using this code
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.example.pc.it7project.data", Context.MODE_PRIVATE);
String sc = sharedPref.getString(FirebaseAuth.getInstance().getUid(), "");

And check
if(sc.equals("Vendor"))
{
//Put Your Code Here
}

I hope this can help you!
Thank You.

A: For registration:

You should ask user first, either user want to register as vendor or eater. Once
  user registered itself then save its type into firebase database.

e-g bleow:

registered_user:
  +user_key:(FirebaseAuth.getInstance().getCurrentUser().getUid());
  +user_type:vendor/eater (under user_key node)

For login:

You must have two button to differentiate login e-g login as vendor or
  login as eater. e-g If user click on login as vendor then pass its
  type through intent to login activiy.

Intent intent = new Intent(StartScreen.this,LoginActivity.class);
intent.putExtra("user_type","vendor");
startActivity(intent);

Once authenticated the user then check its type
                if (!task.isSuccessful() && client_db ){
                    circProgressBar.setVisibility(View.INVISIBLE);
                    Toast.makeText(EatCornLoginActivity.this, R.string.login_failed_toast, Toast.LENGTH_SHORT).show();
                } else {
                    circProgressBar.setVisibility(View.INVISIBLE);
                    Toast.makeText(EatCornLoginActivity.this, R.string.login_success_toast, Toast.LENGTH_SHORT).show();

                    // If Login/Registration Successful send user to MapsActivity
         checkUserValidation

                }

getIntent().getStringExtra("user_type"), will give the type which you
  passed from StratScreen.this so If you its user_type exists then you
  will pass to next activity otherwise show an error toast

public void checkUserValidation(){
    FirebaseDatabase.getInstance().getReference().child("registered_user").
            child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(getIntent().getStringExtra("user_type")).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() != null) {
                startActivity(new Intent(EatCornLoginActivity.this, MapsActivity.class));
            }else{
        Log.e("notify","Error in login");
    }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

PS:

If you want to user SharePreferences then It's easy to do but one
  problem may arise If user clear cache or uninstall then reinstall the
  application the application would not be able to find the
  Sharepreferences file. Sharepreferences stores data in local file.

A: I think a good way of solving this problem would be adding a new field in your Firebase database for every user indicating if it is a Vendor or Eater. This field can be populated when creating an account. Next, when someone wants to login you should first check if it is a Vendor trying to login on Vendor screen or Eater screen and vice versa. That way you will know for sure the type of the user. Can you do this with your implementation or I am missing something?
Example function:
    public void checkUserType(){
        FirebaseDatabase.getInstance().getReference().
                child("Users").
                child(FirebaseAuth.getInstance().getCurrentUser().getUid()).
                child("user_type").addListenerForSingleValueEvent(new ValueEventListener() {

            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.getValue().equals("Vendor")) {
                    //Code if the user is Vendor depending on the screen
                } else {
                    //Code if the user is Eater depending on the screen
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                log.e(databaseError);
            }
        });
     }

A: You should first login and get the user id and then use that to query the eater reference then if that user exist go to the eater screen else go to the vendor screen
loginButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        circProgressBar.setVisibility(View.VISIBLE);
        final String emailUser = emailEditText.getText().toString();
        final String passwordUser = passwordEditText.getText().toString();

       firebaseAuth.signInWithEmailAndPassword(emailUser, passwordUser)
      .addOnCompleteListener(EatCornLoginActivity.this, new
       OnCompleteListener<AuthResult>() {
          @Override
          public void onComplete(@NonNull Task<AuthResult> task) {
              if (task.isSuccessful()) {

                  Log.d(TAG, "createUserWithEmail:success");
                  FirebaseUser user = mAuth.getCurrentUser();

                  DatabaseReference client_db =
                FirebaseDatabase.getInstance().getReference().child("Clients")
                .child("Eater")
                .child(user.getUid());

             client_db.addListenerForSingleValueEvent(new ValueEventListener()

             {

                 @Override
                 public void onDataChange(DataSnapshot dataSnapshot) {
                   if (snapshot.exists()) {
                       // go to eater activity
                   }else{
                     //go to vendor activity
                    }

                 }

              @Override
             public void onCancelled(FirebaseError firebaseError) {
             Toast.makeText(getContext(), firebaseError.getMessage(),
             Toast.LENGTH_SHORT).show();
           }
       });

    } else {
           // If sign in fails, display a message to the user.
           Log.w(TAG, "createUserWithEmail:failure",
           task.getException());
           Toast.makeText(EmailPasswordActivity.this, "Authentication
                failed.", Toast.LENGTH_SHORT).show();

            }

            // ...
        }
    });


text:
Q: How to modify anchor tags in botframework Web chat We've just started using the bot-framework. For client side we are using the cdn and not react. We have certain links that bot responds with. And we would like to append a url parameter to each link and open the link in the same window. So far this is what my code looks like. Is there a better way to achieve this using the botframework. I know there is cardActionMiddleware which has openUrl cardAction, but we don't have any cards and I am not sure on how to implement that.
var webchatMount = document.getElementById('webchatMount');

function loadChatbot() {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', "https://webchat.botframework.com/api/tokens", true);
  xhr.setRequestHeader('Authorization', 'BotConnector ' + '<secret>');
  xhr.send();
  xhr.onreadystatechange = function (e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      var response = JSON.parse(xhr.responseText);

      var store = window.WebChat.createStore({}, function ({ dispatch }) {
        return function (next) {
          return function (action) {

            if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY') {
              var event = new Event('webchatincomingactivity');
              event.data = action.payload.activity;
              window.dispatchEvent(event);
            }

            return next(action);
          }
        }
      });

      window.WebChat.renderWebChat(
        {
          directLine: window.WebChat.createDirectLine({ token: response }),
          store: store,
        },
        webchatMount
      );
      document.querySelector('.webchat__send-box-text-box__input').focus();
      window.addEventListener('webchatincomingactivity', ({ data }) => {
        setTimeout(function () {
          var links = document.querySelectorAll('#webchatMount a');
          if (links.length >= 1) {
            for (var i = 0; i <= links.length; i++) {
              if (links[i] == undefined)
                break;

              var compare = new RegExp('maindomain');
              var href = links[i].getAttribute('href');
              var st = getParameterByName('st', href);
              if (links[i].hasAttribute('target')) {
                links[i].removeAttribute('target');
              }

              if (compare.test(href)) {
                // internal link
                // check if it has st=INTRA
                if (st) {
                  console.log(' it has a value');
                } else {
                  links[i].setAttribute('href', insertParam('st', 'INTRA', href));
                }

              } else {
                // external link, do nothing
              }
            }
          }
        }, 1000);
      });
    }
  }
}

and here are getParameterByName and insertParam functions.
 function getParameterByName(name, url) {
      name = name.replace(/[\[\]]/g, '\\$&');
      var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
          results = regex.exec(url);
      if (!results) return null;
      if (!results[2]) return '';
      return decodeURIComponent(results[2].replace(/\+/g, ' '));
  }

  function insertParam(key, value, url) {
        key = encodeURIComponent(key);
        value = encodeURIComponent(value);
        // kvp looks like ['key1=value1', 'key2=value2', ...]
        var kvp = url.split('&');
        var i=0;
        for(; i<kvp.length; i++){
            if (kvp[i].startsWith(key + '=')) {
                var pair = kvp[i].split('=');
                pair[1] = value;
                kvp[i] = pair.join('=');
                break;
            }
        }
        if(i >= kvp.length){
            kvp[kvp.length] = [key,value].join('=');
        }

        return kvp.join('&');
    }

I am new to botframework webchat so I don't know it very well. I know that the secret should not be used like that, but for know we are testing and would like to get it to work. Any help would be appericiated
Thanks.


text:
Q: Rendering results of multiple value Django annotate query with into html table I am trying to display a summary of statuses by agent.  Annotate looks like the way to go, but the data structure doesn't seem to allow me to loop through the objects and populate an html table cleanly.  I've tried manipulating the result set further in my view before passing to the template, but I've mangled it so badly that I'm not sure if I'm approaching this correctly.  Any feedback is appreciated.
I've attempted the query the database with a 'group by' query using the objects.values().annotate() methods.  This outputs a list of dictionaries.  If I could get the values as keys, that might work, but there is another list.
Querying the user model directly may inadvertently leave out any agents that don't have any QA events.
original views.py

def agent_summary(request):
    lead_qas = LeadQA.objects.values('qa_agent', 'qa_status').annotate(Count('id'))
    context = {'lead_qas': lead_qas}
    return render(request, 'manager/agent_summary.html', context)

This gets me a data structure like:
{'qa_agent': 3, 'qa_status': 'Confirmed', 'id__count': 1}, {'qa_agent': 1, 'qa_status': 'Pending Review', 'id__count': 6}, {'qa_agent': 1, 'qa_status': 'Disqualified', 'id__count': 8}, {'qa_agent': 2, 'qa_status': 'Disqualified', 'id__count': 1}, {'qa_agent': 2, 'qa_status': 'Not Started', 'id__count': 4}, {'qa_agent': 1, 'qa_status': 'Not Started', 'id__count': 3}, {'qa_agent': 3, 'qa_status': 'Not Started', 'id__count': 4}, {'qa_agent': 1, 'qa_status': 'Confirmed', 'id__count': 4}

I can't quite pivot the keys into my html table.
modified views.py (worse, maybe?)
@staff_member_required
@login_required
def agent_summary(request):
    lead_qas = LeadQA.objects.values('qa_agent', 'qa_status').annotate(Count('id'))
    agents = User.objects.filter(is_staff=False)
    qas = []
    for agent in agents:
        qas.append({'agent': agent.username, 'qa': list(LeadQA.objects.filter(qa_agent=agent).values('qa_status').annotate(Count('id')))})
    context = {'lead_qas': lead_qas, 'agents': agents, 'qas': qas}
    return render(request, 'manager/agent_summary.html', context)

This gets me a data structure that, while it seems better at first glance, doesn't get me any closer.
[{'agent': 'agent_1', 'qa': [{'qa_status': 'Not Started', 'id__count': 4}, {'qa_status': 'Confirmed', 'id__count': 1}]}, {'agent': 'agent_2', 'qa': [{'qa_status': 'Disqualified', 'id__count': 1}, {'qa_status': 'Not Started', 'id__count': 4}]}]

Ultimately, I want to display the data like so in my html template:

Agent Summary

    {% if qas %}

          Agent
          Not Started
          Pending Review
          Disqualified
          Confirmed

          {% for qa in qas %}

            {{ qa.agent }}
            {{ qa.not_started }}
            {{ qa.pending_review }}
            {{ qa.disqualified }}
            {{ qa.confirmed }}

          {% endfor %}

    {% else %}
    {% endif %}

No errors, but I'm not able to pivot these structures into the tabular form I am looking for.

A: This gave me the data structure that I could easily pivot into an html table.
def agent_summary(request):
    agents = User.objects.filter(is_staff=False)
    qa_summaries = []
    for agent in agents:
        qa_summaries.append({'agent': agent,
        'not_started': LeadQA.objects.filter(qa_agent=agent, qa_status="Not Started").count(),
        'pending_review': LeadQA.objects.filter(qa_agent=agent, qa_status="Pending Review").count(),
        'confirmed': LeadQA.objects.filter(qa_agent=agent, qa_status="Confirmed").count(),
        'disqualified': LeadQA.objects.filter(qa_agent=agent, qa_status="Disqualified").count(),})
    context = {'agents': agents, 'qa_summaries': qa_summaries}
    return render(request, 'manager/agent_summary.html', context)

Which yields data like:
[{'agent': <User: agent_1>, 'not_started': 4, 'pending_review': 0, 'confirmed': 1, 'disqualified': 0}, {'agent': <User: agent_2>, 'not_started': 4, 'pending_review': 0, 'confirmed': 0, 'disqualified': 1}]

However, it's four trips to the database for each agent, which could potentially be 40+ database queries to load one page.  Surely the annotate method would alleviate this, but parsing the individual dictionaries into the proper data structure doesn't seem feasible.


text:
Q: 3D as 2D plots using Matlab data I am trying to plot 3d data as 2d (please refer to the attached figure).
Is that possible at all in Tex (or Matlab)?(Usually, this is done a s a legend, however, when no colors are allowed, I have to plot it as in the attached picture). If so, please provide any hints.
Thank you in advance
Here is also a sample of the data:
X=[0 0 0 0 0
0.00499487214258387 0.0100271322719341  0.0151355841667174  0.0203619904285679  0.0257528910437245
0.00703013931750997 0.0141123715001326  0.0213007419561194  0.0286533748405864  0.0362349750090093
0.00856912164753604 0.0172011015018718  0.0259611298569260  0.0349192664533911  0.0441534216317338
0.00984769541100846 0.0197669024060679  0.0298317587516411  0.0401218833508729  0.0507257254049430
0.0109577332470996  0.0219942405774403  0.0331911596116199  0.0446361019206510  0.0564262963381876
0.0119466084732432  0.0239782392419037  0.0361829739474490  0.0486552739640120  0.0614998638245181
0.0128426154484001  0.0257757149277838  0.0388930053871466  0.0522949117805015  0.0660926587477192
0.0136642899493110  0.0274238903416811  0.0413774721254582  0.0556307081325855  0.0703005193527485
0.0144245776620953  0.0289487637697525  0.0436756433487295  0.0587155421791397  0.0741904098771546
0.0151329564382696  0.0303693701768318  0.0458162730087464  0.0615881383770832  0.0778113778863288
0.0157966212085941  0.0317001603416950  0.0478211921655991  0.0642779014739504  0.0812006730740997
0.0164211931300526  0.0329524247496926  0.0497074590478197  0.0668078104510510  0.0843874098612964
0.0170111676966756  0.0341351933703888  0.0514887177522871  0.0691962474012896  0.0873948821954542
0.0175702105696051  0.0352558296774944  0.0531760952694321  0.0714582050315404  0.0902420919849960
0.0181013600452389  0.0363204372087640  0.0547788154484420  0.0736061131758165  0.0929447953582426
0.0186071698801841  0.0373341463673818  0.0563046321253931  0.0756504218986758  0.0955162408504069
0.0190898126701751  0.0383013220178056  0.0577601426467341  0.0776000236025984  0.0979677038151599
0.0195511563564558  0.0392257171221451  0.0591510199088859  0.0794625654482437  0.100308881996065
0.0199928219502558  0.0401105886622858  0.0604821874442227  0.0812446851052654  0.102548194045946];

Y=[1 1 1 1 1
1.00100502512563 1.00100502512563 1.00100502512563 1.00100502512563 1.00100502512563
1.00201005025126 1.00201005025126 1.00201005025126 1.00201005025126 1.00201005025126
1.00301507537688 1.00301507537688 1.00301507537688 1.00301507537688 1.00301507537688
1.00402010050251 1.00402010050251 1.00402010050251 1.00402010050251 1.00402010050251
1.00502512562814 1.00502512562814 1.00502512562814 1.00502512562814 1.00502512562814
1.00603015075377 1.00603015075377 1.00603015075377 1.00603015075377 1.00603015075377
1.00703517587940 1.00703517587940 1.00703517587940 1.00703517587940 1.00703517587940
1.00804020100503 1.00804020100503 1.00804020100503 1.00804020100503 1.00804020100503
1.00904522613065 1.00904522613065 1.00904522613065 1.00904522613065 1.00904522613065
1.01005025125628 1.01005025125628 1.01005025125628 1.01005025125628 1.01005025125628
1.01105527638191 1.01105527638191 1.01105527638191 1.01105527638191 1.01105527638191
1.01206030150754 1.01206030150754 1.01206030150754 1.01206030150754 1.01206030150754
1.01306532663317 1.01306532663317 1.01306532663317 1.01306532663317 1.01306532663317
1.01407035175879 1.01407035175879 1.01407035175879 1.01407035175879 1.01407035175879
1.01507537688442 1.01507537688442 1.01507537688442 1.01507537688442 1.01507537688442
1.01608040201005 1.01608040201005 1.01608040201005 1.01608040201005 1.01608040201005
1.01708542713568 1.01708542713568 1.01708542713568 1.01708542713568 1.01708542713568
1.01809045226131 .01809045226131  1.01809045226131 1.01809045226131 1.01809045226131
1.01909547738693 1.01909547738693 1.01909547738693 1.01909547738693 1.01909547738693];

Z=[0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000
0.0500000000000000 0.100000000000000 0.150000000000000 0.200000000000000 0.250000000000000];

Please notice how Z is constant for each column

A: You can use contour plot. First, prepare the data in MATLAB:
[reshape(X,[],1), reshape(Y,[],1), reshape(Z,[],1)];

Then, you can use the data in TeX:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.8}
\begin{document}
\begin{tikzpicture}
    \begin{axis}[
        xticklabel style={/pgf/number format/.cd, fixed, precision=2},
        yticklabel style={/pgf/number format/.cd, fixed, precision=3},
        ]
        \addplot[
            colormap={onlyblack}{gray(0cm)=(0); gray(1cm)=(0)},
            contour prepared,
            contour/contour label style={/pgf/number format/.cd, fixed, precision=2},
            contour/label distance={1000pt}, % use big number to get one label per contour
            ] table {
            0   1   0.05
            0.00499487214258387 1.00100502512563    0.05
            0.00703013931750997 1.00201005025126    0.05
            0.00856912164753604 1.00301507537688    0.05
            0.00984769541100846 1.00402010050251    0.05
            0.0109577332470996  1.00502512562814    0.05
            0.0119466084732432  1.00603015075377    0.05
            0.0128426154484001  1.00703517587940    0.05
            0.0136642899493110  1.00804020100503    0.05
            0.0144245776620953  1.00904522613065    0.05
            0.0151329564382696  1.01005025125628    0.05
            0.0157966212085941  1.01105527638191    0.05
            0.0164211931300526  1.01206030150754    0.05
            0.0170111676966756  1.01306532663317    0.05
            0.0175702105696051  1.01407035175879    0.05
            0.0181013600452389  1.01507537688442    0.05
            0.0186071698801841  1.01608040201005    0.05
            0.0190898126701751  1.01708542713568    0.05
            0.0195511563564558  1.01809045226131    0.05
            0.0199928219502558  1.01909547738693    0.05
            0   1   0.10
            0.0100271322719341  1.00100502512563    0.10
            0.0141123715001326  1.00201005025126    0.10
            0.0172011015018718  1.00301507537688    0.10
            0.0197669024060679  1.00402010050251    0.10
            0.0219942405774403  1.00502512562814    0.10
            0.0239782392419037  1.00603015075377    0.10
            0.0257757149277838  1.00703517587940    0.10
            0.0274238903416811  1.00804020100503    0.10
            0.0289487637697525  1.00904522613065    0.10
            0.0303693701768318  1.01005025125628    0.10
            0.0317001603416950  1.01105527638191    0.10
            0.0329524247496926  1.01206030150754    0.10
            0.0341351933703888  1.01306532663317    0.10
            0.0352558296774944  1.01407035175879    0.10
            0.0363204372087640  1.01507537688442    0.10
            0.0373341463673818  1.01608040201005    0.10
            0.0383013220178056  1.01708542713568    0.10
            0.0392257171221451  1.01809045226131    0.10
            0.0401105886622858  1.01909547738693    0.10
            0   1   0.15
            0.0151355841667174  1.00100502512563    0.15
            0.0213007419561194  1.00201005025126    0.15
            0.0259611298569260  1.00301507537688    0.15
            0.0298317587516411  1.00402010050251    0.15
            0.0331911596116199  1.00502512562814    0.15
            0.0361829739474490  1.00603015075377    0.15
            0.0388930053871466  1.00703517587940    0.15
            0.0413774721254582  1.00804020100503    0.15
            0.0436756433487295  1.00904522613065    0.15
            0.0458162730087464  1.01005025125628    0.15
            0.0478211921655991  1.01105527638191    0.15
            0.0497074590478197  1.01206030150754    0.15
            0.0514887177522871  1.01306532663317    0.15
            0.0531760952694321  1.01407035175879    0.15
            0.0547788154484420  1.01507537688442    0.15
            0.0563046321253931  1.01608040201005    0.15
            0.0577601426467341  1.01708542713568    0.15
            0.0591510199088859  1.01809045226131    0.15
            0.0604821874442227  1.01909547738693    0.15
            0   1   0.20
            0.0203619904285679  1.00100502512563    0.20
            0.0286533748405864  1.00201005025126    0.20
            0.0349192664533911  1.00301507537688    0.20
            0.0401218833508729  1.00402010050251    0.20
            0.0446361019206510  1.00502512562814    0.20
            0.0486552739640120  1.00603015075377    0.20
            0.0522949117805015  1.00703517587940    0.20
            0.0556307081325855  1.00804020100503    0.20
            0.0587155421791397  1.00904522613065    0.20
            0.0615881383770832  1.01005025125628    0.20
            0.0642779014739504  1.01105527638191    0.20
            0.0668078104510510  1.01206030150754    0.20
            0.0691962474012896  1.01306532663317    0.20
            0.0714582050315404  1.01407035175879    0.20
            0.0736061131758165  1.01507537688442    0.20
            0.0756504218986758  1.01608040201005    0.20
            0.0776000236025984  1.01708542713568    0.20
            0.0794625654482437  1.01809045226131    0.20
            0.0812446851052654  1.01909547738693    0.20
            0   1   0.25
            0.0257528910437245  1.00100502512563    0.25
            0.0362349750090093  1.00201005025126    0.25
            0.0441534216317338  1.00301507537688    0.25
            0.0507257254049430  1.00402010050251    0.25
            0.0564262963381876  1.00502512562814    0.25
            0.0614998638245181  1.00603015075377    0.25
            0.0660926587477192  1.00703517587940    0.25
            0.0703005193527485  1.00804020100503    0.25
            0.0741904098771546  1.00904522613065    0.25
            0.0778113778863288  1.01005025125628    0.25
            0.0812006730740997  1.01105527638191    0.25
            0.0843874098612964  1.01206030150754    0.25
            0.0873948821954542  1.01306532663317    0.25
            0.0902420919849960  1.01407035175879    0.25
            0.0929447953582426  1.01507537688442    0.25
            0.0955162408504069  1.01608040201005    0.25
            0.0979677038151599  1.01708542713568    0.25
            0.100308881996065   1.01809045226131    0.25
            0.102548194045946   1.01909547738693    0.25
        };
    \end{axis}
\end{tikzpicture}
\end{document}

This results in the following plot:

Note: I have assumed a typo and changed one of your points from .01809045226131 to 1.01809045226131.

A: If you use the package matlab2tikz provided by Mathworks to export the most recent plot to an arbitrary file name:
matlab2tikz('my3d_plot.tikz');

Keep in mind that you have to download this function (and keep it in the active folder for evaluation). Furthermore this function produces for each plot a file called my3d_plot-n.png where n stands for the n'th plot/subplot.
3D plot
Use for instance the matlab plot function
imagesc(DATA);
colorbar('location','southoutside')

where the function has the options to set the color-limits and color-theme. These options are well described also at mathworks's homepage.
Save file
Save the file 'my3d_plot.tikz' in the same directory as your processed latex-file because otherwise the paths inside the file my3d_plot.tikz refer to the wrong directory.
Latex file
Something like the following MWE should make it:
\documentclass{article}
\usepackage{pgfplots}
\usepackage{graphicx}
\pgfplotsset{compat=newest}
\pgfplotsset{plot coordinates/math parser=false}

\begin{document}
\input{my3d_plot.tikz}
\end{document}

Did this answer your question or was the question about another feature to plot?


text:
Q: Can not connect to my Redshift cluster in private subnet I have set up a VPC using a suggested approach as discussed on Linux Bastion Host Quick Start.
I have also created a Redshift cluster in one of private subnets and also created its dedicated security group with no rule restrictions. That is for both inbound and outbound rules for Redshift I am assigning all traffics and ports (0.0.0.0/0). I am even doing the same for the public EC2 instance on public subnet.
I can successfully ssh to my public bastion instances but from there I can not telnet to my Redshift endpoint.
[ec2-user@ip-10-0-141-20 ~]$ telnet ******.redshift.amazonaws.com 5439
Trying 10.0.20.169...
Connected to ******.redshift.amazonaws.com.
Escape character is '^]'.
Connection closed by foreign host.

I am not sure what is wrong with my configurations. In Redshift I have disabled both public access and VPC routing.

A: I assume that your situation is:

*

*You have an Amazon Redshift cluster in a private subnet

*You have a Bastion server in a public subnet of the same VPC

*You wish to connect an SQL Client on your computer to the Redshift cluster

A way to do this would be:

*

*Use Port Forwarding to connect to the Redshift cluster via the Bastion host

*If you are using a Linux/Mac:

ssh-add keypair.pem
ssh -A ec2-user@BASTION-IP -L 5439:xyz.redshift.amazonaws.com:5439

(This says: Forward local port 5439 to the bastion, where is should send traffic to the Redshift cluster on port 5439)

*

*If you are using Windows, then you can use Pageant and PuTTY

*Then, configure your SQL Client to connect to Redshift with server=localhost and port=5439, together with your login credentials

If the above does not work, some things to check:

*

*The Security Group on the Redshift Cluster should allow inbound connections on port 5439 from the Bastion (or from the whole VPC or from 0.0.0.0/0

*The outbound rules on the Bastion should remain at their default setting of allowing all outbound traffic

If things are still going wrong, you can test the Redshift connection by installing psql on the Bastion and attempting a connection to Redshift. (Redshift was forked from PostgreSQL, so it behaves similarly).


text:
Q: How do I save individual MySQL results to PHP variables? I have this database that I've been working on, and I'm at the point where I'm trying to tie everything together and start integrating the information from my database tables into actual web pages. What I'm trying to do is to query the database for specific answers which I want to save to PHP variables so I can perform a simple <?php echo $variable; ?> throughout my webpage. However I can't seem to figure out how to do that.
Here's a sample of what I've been trying.
SQL
$Name = "John Smith";

$Nickname = $db->query('SELECT `Nickname` FROM `Profiles` WHERE `Name` =' . $Name);
$country = $db->query('Select `Country` from `Profiles` Where `Name` =' . $Name);

PHP/HTML

<?php echo $Name; ?>

Country	<?php echo $country; ?>

Nickname	<?php echo $Nickname; ?>

This isn't EXACTLY what I've been doing, the table(s) I'm trying to plug this information into is/are far more complicated, which is why if at all possible, I'd like to avoid using the normal method of returning MySQL queries:
Code I'd like to avoid if possible
<?php
while ($rows = $country->fetch()){
echo ['Country'];
}
?>

In the event that the above code is still by far the simplest way to return any/all query results, I just have one question: Is it possible to nest different while ($rows = $variable->fetch()) statements within each other? Because my table has information from different database tables somewhat scattered throughout it and there are a couple of places where I would NEED to nest the WHILE statement. Would it work?
Edit:
So I've tried a couple of suggestions. First, I changed my SQL syntax for the $Name so that it will work in the SQL query.
`WHERE `Name` ="' . $Name . '"');`

So now that's working. But I've tried the other 2 suggestions and both are breaking my code (the page won't load).
Also, no one's answered my question about being able to nest While() Statements.

A: Use list() : http://php.net/list, with following example:
$info = array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

You should select more cols in your query instead of separate query's for each column.
Example (not tested):
$result = $db->query('SELECT Nickname, Country FROM `Profiles` WHERE `Name` =  "' . mysql_real_escape_string($Name) . '"');

$i = 0;
$nickNames = [];
$countries = [];

while ($row = $result->fetch())
{
    list($nickNames[$i], $countries[$i]) = $row;
    $i++;
}

echo 'The first nickname is: ' . $nickNames[0] . ' from this country: ' . $countries[0];

So you can use the separated array's.

A: I figured it out! I was able to assign the results from my database query into variables that I could then recall through a simple <?php echo $variable; ?> at any time, as many times as needed. Here is what I did.
SQL Example
$result = $db->query('Select `Name`, `Age`, `Color` from `People` ');
while ($rows = $result->fetch()){
$Name = $rows['Name'];
$Age = $rows['Age'];
$Color = $rows['Color'];
}

In Webpage

Hello, my name is <?php echo $Name; ?>.
I am <?php echo $Age; ?> years old and my favorite color is <?php echo $Color; ?>.


text:
Q: Installing dependencies with npm-peer-dependencies I am trying to install the required node_modules for a small project running Angular 11 using npm install
My goal is get the project to work locally after downloading it from GitHub. I have already installed the latest version of the Angular CLI.
After running the install command I tried npm start.
 I was expecting that after running the install and start command to be able to run the project locally.
However the actual result I get after running the install command is the following list of errors:
> ng serve

An unhandled exception occurred: Cannot find module '@angular/compiler'
Require stack:

\node_modules\@angular\compiler-cli\index.js
\node_modules\@ngtools\webpack\src\angular_compiler_plugin.js
\node_modules\@ngtools\webpack\src\index.js
\node_modules\@angular-devkit\build-angular\src\webpack\configs\typescript.js
\node_modules\@angular-devkit\build-angular\src\webpack\configs\index.js
\node_modules\@angular-devkit\build-angular\src\browser\index.js
\node_modules\@angular-devkit\build-angular\src\dev-server\index.js
\node_modules\@angular-devkit\architect\node\node-modules-architect-host.js
\node_modules\@angular-devkit\architect\node\index.js
\node_modules\@angular\cli\models\architect-command.js
\node_modules\@angular\cli\commands\serve-impl.js
\node_modules\@angular-devkit\schematics\tools\export-ref.js
\node_modules\@angular-devkit\schematics\tools\index.js
\node_modules\@angular\cli\utilities\json-schema.js
\node_modules\@angular\cli\models\command-runner.js
\node_modules\@angular\cli\lib\cli\index.js
\node_modules\@angular\cli\lib\init.js
\node_modules\@angular\cli\bin\ng

See "angular-errors.log" for further details.

npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file C:\WINDOWS\system32\cmd.exe
npm ERR! errno ENOENT
npm ERR! `ng serve`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the @0.0.16 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

The problem is that this Angular project also has peer dependencies. I installed npm-install-peers package but it seems that simply running npm install afterwards will not install the required peer dependencies.
What should I do next to get this Angular project installed locally ?

A: The issue you are facing is likely because angular cli or npm-peer-dependencies are not installed globally on your machine.
The steps that you should take are to make sure of them are globally installed.
To install packages globally you need run npm install -g <package_name>
npm docs link
In your case for angular cli you should run
npm i -g @angular/cli@11.2.15 and npm install -g npm-peer-dependencies.
Then run npm start.


text:
Q: Dynamical Creating Links with jQuery I'm trying to create a link within a blockquote element with jQuery. Right now I'm at this stage:
var pullQuote = $('span.pull-quote').each(function(){

    var $this = $(this),
    hrefLink = 'http://example.com',
    text = $this.text();

    $('
', {
        class: 'quote',
        text: text
    }).prependTo( $this.closest('p'));

});

That creates the blockquote element with the text dynamical but I want to turn the text into link inside of the blockquote. The href isn't going to change so I can set that in a variable like I already have it.
Can I add something that will create the a tag inside of the blockquote to where I can still use the set variables? (Which is what I've been trying to do) Or do I need to just run this function and then create a new function which would handle adding the link?

A: $('
', {
    class: 'quote',
    html: $('', {
        text: text,
        href: hrefLink
    )}
}).prependTo( $this.closest('p'));

If I understood you right, you just wanted to construct an anchor element within the blockquote and give that the text and the link.

A: var $this = $(this);
hrefLink = 'http://example.com';
text = $this.text();

var blockQ=$('

                           '+text+'
');
blockQ.prependTo( $this.closest('p'));

Demo :  http://jsfiddle.net/QGtYQ/5/


text:
Q: Fastest way to log to an external server I'm working on a python/flask application and I have my logging handled on a different server. The way I currently set it up is to have a function which sends a request to the external server whenever somebody visits a webpage.
This, of course extends my TTB because execution only continues after the request to the external server is completed. I've heard about threading but read that that also takes a little extra time.
Summary of current code:
log_auth_token = os.environ["log_auth"]
def send_log(data):
    post_data = {
        "data": data,
        "auth": log_auth_token
    }
    r = requests.post("https://example.com/log", data=data)

@app.route('/log')
def log():
    send_log("/log was just accessed")
    return("OK")

In short:
Intended behavior: User requests webpage -> User recieves response -> Request is logged.
Current behavior: User requests webpage -> Request is logged -> User recieves response.
What would be the fastest way to achieve my intended behavior?

A:
What would be the fastest way to achieve my intended behavior?

Log locally and periodically send the log files to a separate server. More specifically, you need to create rotating log files and archive them so you don't end up with 1 huge file. In order to do this you need to configure your reverse proxy (like NGINX).
Or log locally and create an application that allows you to read the log files remotely.
Sending a log per server call to a separate server simply isn't efficient unless you have another process do that. Users shouldn't have to wait for your log action to complete


text:
Q: python peewee dynamically or clauses I want to dynamically OR multiple clauses when performing a query. I see in the peewee documentation that:
import operator
or_clauses = reduce(operator.or_, clauses)  # OR together all clauses

However, this note is somewhat unclear. What exactly is clauses supposed to be set to? Does anyone have any example code?

A: clauses would be a list of expressions in the example, sorry that it is unclear.
You might write something like:
clauses = [
    (User.username == 'something'),
    (User.something == 'another thing'),
    ...
]
User.select().where(reduce(operator.or_, clauses))


text:
Q: How to display a given number of names randomly selected from a list I have a list of 148 names in Column A. I need a function that would let a user enter in a number and use that number to return a list of names in column B or C. There can be repeats. So column B would prompt me with: "enter the number of names needed", and after I entered in the number, such as "4", below that prompt or in column C "4" names would be listed in different cells or even the same cell separated by commas. This workbook will eventually be embedded in a Wordpress.com site.
I looked online for some examples. This blog explains something similar:
http://datawiz.wordpress.com/2011/01...-from-a-sheet/
They prompt a user to look up the popularity of baby names. But since I don't know how to do very much in Excel, I can't figure out how to exactly apply his formulas to my problem.
Any suggestions?
I should also say that I already tried these formulas, which only give me one result in the cell that contains the formula:
=INDEX($A1:$A148,RANDBETWEEN(1,COUNTA($A1:$A148)),1)

=INDEX(A1:A148, RANDBETWEEN(1, 148))

=INDEX(Tanglelist, RANDBETWEEN(1, 148))

I've asked this on other forums with no solution. But someone suggested this formula which I guess is a step in the right direction:
=IF(ROWS(B$2:B2)>$B$1,"",INDEX(Tanglelist,RANDBETWEEN(1,ROWS(Tanglelist))))

A: Just take your result one step farther.  Say the number is entered in B1.  In C1:
    =IF(ROW(c1)>$B$1,"",INDEX($A$1:$A$148,RANDBETWEEN(1,148)))

Copy this down the column.  Now you will get a random selection for the number of rows in C specified in B1.


text:
Q: How to reliably check the windows domain id of current user on a workstation I am using C# and .Net Framework 4.
I am looking for a foolproof method to get the login id of the currently logged in windows user that is not susceptible to impersonation or hacking. I am looking for this in the form of: DOMAINNAME\USERNAME
e.g. SOMEDOMAIN\JohnDoe
Currently the best I have is:
var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
var currentLoginId = identity.Name;

Is this open to impersonation (outside of someone knowing both the username and password) and if so is there a better way of doing this?

A: There can be at least four different identities involved at this point:

*

*The identity assigned to the thread

*The identity assigned to the process

*The account of the user who started the process

*The account of the user who logged onto the PC

In your code you're getting (1). This is normally fine, and is usually the same as (2).
To retrieve (2), you could:

*

*Call WindowsIdentity.GetCurrent to get the impersonated identity

*Undo impersonation by calling the Win32 RevertToSelf function

*Look at WindowsIdentity.GetCurrent to get the underlying process identity

*Reset the thread identity by impersonating the identity from step (1)

(2) and (3) will be the same unless you've written unmanaged code that changes the process identity. As @Daniel points out, (3) and (4) could legitimately be different in the presence of the Windows "run as" command.

Edit: You can trust that the current WindowsIdentity is who it says it is, insofar as you can trust any given piece of data in your application.
You could spoof it by attaching a debugger to your process and faking the return value from this call, but if you're going to do that, you might as well fake the piece of code where you pass the user name to the database.
The 100% safe way to do this is to use integrated authentication/SSPI to connect to the database.

A: Only a partial answer:
I believe System.Security.Principal.WindowsIdentity.GetCurrent(); will return the windows user account associaed with the currently executing thread.  If the thread or application was started under a different user account from the logged in user, you won't get what you're after using this.
If you can be sure that your aplication was not started using the "run-as" feature (or programatic equialent) and you're not doing anything internally with respect to the thread's identity, you can probably be sure this is the logged in user's account but I'm not 100% on this.
It may be possible to find the user account associated with the widows "session" within which the application is running by using ADSI (see System.DirectoryServices).


text:
Q: How do I calculate the distance from point A from point B? I've got this drawing of a circle, and I'd like to know how I can calculate the distance between point A to point B in a straight line.

I already have:

Radius: 100
Arc length: 78.5
Angle: 45°

Post Script.: I don't really have a way to draw lines it's not a 2d object, it's just numbers on a console, thus I don't have visual feedback, I need to do it using those values above.

A: All you really need is the radius and the angle.
Draw a line between $A$ and $B$. Then mark the midpoint of this line as $C$.
Then, $\triangle OCB$ is a right-angled triangle with the right angle at $C$, meaning that $$\frac{\overline{CB}}{\text{radius}} = \sin\left(\frac\theta2\right)$$
and of course $\overline{AB}=2\  \overline{CB}$.


text:
Q: WHERE clause not showing data I am trying to add WHERE clause to filter table data but its showing nothing, its datatable AJAX CRUD project, Any help will be very gratefull
link of full tutorial : https://www.webslesson.info/2017/01/php-pdo-ajax-crud-with-data-tables-and-bootstrap-modals.html
$query = '';
    $query .= "SELECT * FROM users WHERE id = 1 ";
        if(isset($_POST["search"]["value"])) {
            $query .= 'AND first_name LIKE "%'.$_POST["search"]["value"].'%" ';
            $query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'%" ';
        }
        if(isset($_POST["order"])) {
            $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
        } else {
            $query .= 'ORDER BY id DESC ';
        }
        if($_POST["length"] != -1) {
            $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
        }

if i use below code i am getting all result from table
$query = '';
    $query .= "SELECT * FROM users ";
    if(isset($_POST["search"]["value"])) {
        $query .= 'WHERE first_name LIKE "%'.$_POST["search"]["value"].'%" ';
        $query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'%" ';
    }
    if(isset($_POST["order"])) {
        $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
    } else {
        $query .= 'ORDER BY id DESC ';
    }
    if($_POST["length"] != -1) {
        $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
    }


text:
Q: What is the minimal polynomial of $x$ over $k(x^p - x)$? Let $k=\Bbb F_p$, and let $k(x)$ be the rational function field in one variable over $k$. Define $\phi:k(x)\to k(x)$ by $\phi(x)=x+1$. I know that $\phi$ has order $p$ in $\operatorname{Gal}(k(x)/k)$ and $k(x^p-x)$ is the fixed field of $\phi$, but I'm confused about the minimal polynomial of $x$ over $k(x^p-x)$. (This is problem 17 of Fields and Galois Theory by Patrick Morandi, page 27.)
Please explain about that minimal polynomial or calculate it!

A: The hardest part, IMO, of this problem is not confusing yourself.
Define $y = x^p - x$. So you are looking at the field $K = k(y)$. (or maybe use $\alpha$ instead of $y$ if you prefer)
$x$ is algebraic over $K$. Your goal is to find a polynomial over $K$ -- an element $f \in K[t]$ -- such that $f(x) = 0$.
So can you find a polynomial expression in $x$ with coefficients in $K$ that vanishes? If so, you can then write down an $f(t)$, that makes for a good starting point to begin solving the problem.

A: If you have absolutely no idea to get the minimal polynomial, and you know that there is an isomorphism $\Bbb F_p \to Gal(k(x)/k(x^p-x))$ given by $t \mapsto (x \mapsto x+t)$, then you know that the conjugates of $x$ are the $x+t$, and then you can simply compute the product $\prod_{t \in \Bbb F_p}(T-(x+t))$. This product is invariant by $x \mapsto x+1$ so its coefficients will be in $k(x^p-x)$.
You will find $\prod_{t \in \Bbb F_p}(T-(x+t)) = \prod_{t \in \Bbb F_p}((T-x)-t) = (T-x)^p - (T-x) = (T^p-T)-(x^p-x)$
This is a polynomial $P(T)$ with coefficients in $k(x^p-x)$, and $P(x)=0$.
More generally, if you consider the extension $k(f(x)) \subset k(x)$ with $f(x) = P(x)/Q(x)$, then $Q(T)f(x)-P(T)$ is an obvious polynomial over $k(f(x))$ annihilating $x$


text:
Q: Должен ли браузер отправлять Cookie с OPTIONS запросами? При попытке отправить cors запрос методом POST с ContentType: application/json, браузер отправляет предварительный запрос методом OPTIONS, но не отправляет с ним куки, так что API заварачивает OPTIONS запрос с 401 статусом. Нормальное ли это поведение для API и браузера, и должен ли он вообще слать куки в данном случае? С остальными запросами куки уходят нормально. Где-то в спецификациях освещается этот вопрос?

A: Это "CORS предварительный запрос":
https://developer.mozilla.org/ru/docs/Web/HTTP/CORS
https://fetch.spec.whatwg.org/#cors-preflight-fetch
Спецификацию понять сложно, но люди говорят, что для браузера это нормально.
Я обычно CORS не использую, проще всё пропустить через сервер с одним именем.


text:
Q: Minified JS find and replace a valid strategy for substitution? For reasons not important to the question (using the output of create-react-app, would like to parameterize some variables POST build time i.e as they're deployed), I am in a scenario where I would like to replace all instances of a string i.e "REPLACE_ME" with a value.
This would be trivial if I had access to the un-minified javascript; however, I am wondering if a find and replace on the minified javascript will suffice?

A: create-react-app is using Webpack under the hood, You can use webpack.DefinePlugin to achieve that in a build time.
// webpack.config.js
const webpack = require('webpack');

const config = {
  entry: './src/index.js',
  output: {
    ...
  },
  plugins: [
    new webpack.DefinePlugin({
      REPLACE_ME: JSON.stringify('yourBuildTimeValueGoesHere'),
    }),
    ...
  ],
  ...
}

module.exports = config;


text:
Q: Möbius transformation that permutes roots of a cubic polynomial The roots of the polynomial $x^3-3x-1$ can be permuted by the function $z\mapsto \dfrac{-1}{1+z}$ which is easily checked by a direct calculation.

Is there a simple formula for a Möbius transformation that permutes the roots of $x^3+px+q$?

A: Actually, yes.
This is from section number 511 in J.-A. Serret's 1877 work, "Cours D'Algèbre Supérieure". As far as I can tell, it's never been translated into English (which is surprising, given how important it was in the 19th century), but it is available online from various libraries. Anyways, here's his result.
For the polynomial $x^3 + Px +Q$, let's recall that its  discriminant $\Delta$ can be written as
$\Delta = -(4P^3 + 27Q^2)$.
With this in mind, and so long as $\Delta \not= 0$ (which is the same as saying
that the polynomial has no repeated roots), let's define
\begin{align*}
a &= \frac{\sqrt{\Delta} - 9Q}{2\sqrt{\Delta}} \\[1.2ex]
b &= \frac{2P^2}{2\sqrt{\Delta}} \\[1.2ex]
c &= \frac{6P}{2\sqrt{\Delta}} \\[1.2ex]
d &= \frac{\sqrt{\Delta} + 9Q}{2\sqrt{\Delta}}
\end{align*}
Then, Serret showed that $m(z) = \displaystyle\frac{a z + b}{c z + d}$ is of order three under composition, and it permutes the roots of the cubic $x^3 + Px + Q$. Interestingly, this is true for
all cubics without repeated roots. It works for irreducible polynomials and for reducible polynomials. It works for all possible coefficients. It even works for polynomials with complex roots; in that case, $\Delta<0$ and so $\sqrt{\Delta}$ is imaginary and thus $m(z)$ can take a real root to a complex root.
(Actually, Serret did this in full generality for the non-depressed cubic $x^3 + Px^2 + Qx + R$, but I've reduced the formula down to the depressed cubic you were interested in.)
Let's check it for your polynomial $x^3 -3x -1$. You have $P=-3$ and $Q=-1$, so you get $\Delta = 81$. Thus, your values for $a,b,c,d$ are:
\begin{align*}
a &= \frac{\sqrt{\Delta} - 9Q}{2\sqrt{\Delta}} &= 1 \\[1.2ex]
b &= \frac{2P^2}{2\sqrt{\Delta}} &= 1 \\[1.2ex]
c &= \frac{6P}{2\sqrt{\Delta}} &=-1\\[1.2ex]
d &= \frac{\sqrt{\Delta} + 9Q}{2\sqrt{\Delta}} &=0
\end{align*}
and so you have  $m(z) = \displaystyle\frac{ z + 1}{- z} = -1 - \frac{1}{z}$. Of course, this is just the inverse of the map you gave in your question,
$z \mapsto \displaystyle \frac{-1}{z+1}$.


text:
Q: Designing an MFC App That Will Work on All Resolutions? I'm currently designing my first ever GUI for Windows. I'm using MFC and Visual Studio 2008. The monitor I have been designing my program on has 1680x1050 native resolution. If I compile and send my program to one of my coworkers to run on their computer (generally a laptop running at 1024x768), my program will not fit on their screen.
I have been trying to read up on how to design an MFC application so that it will run on all resolutions, but I keep finding misleading information. Everywhere I look it seems that DLUs are supposed to resize your application for you, and that the only time you should run into problems is when you have an actual bitmap whose resolution you need to worry about. But if this is the case, why will my program no longer fit on my screen when I set my monitor to a lower resolution? Instead of my program "shrinking" to take up the same amount of screen real estate that it uses at 1680x1050, it gets huge and grainy.
The "obvious" solution here is to set my resolution to 1024x768 and redesign my program to fit on the screen. Except that I've already squished everything on my dialogs as much as possible to try and get my program to fit on screen running at 1024x768. My dialog fonts are set to Microsoft Sans Serif 8 but still appear huge (much larger than 8 points) when running at 1024x768.
I know there HAS to be a way to make my program keep the same scaling... right? Or is this the wrong way to approach the problem? What is the correct/standard way to go about designing an MFC program so that it can run on many resolutions, say 800x600 and up?

A: I assume your application GUI is dialog based (the main window is a dialog)?
In that case you have a problem, because, as you discovered, MFC has no support for resizing a dialog correctly. Your options are:

*

*Redesign your GUI to use a SDI or MDI GUI.

*Use a dialog resize extension. There are many available, for some very good suggestions see this question. Another options are this one and this one.

*Don't use MFC. wxWidgets has much better support for dialog resizing.

A: MFC is only a thin wrapper over the Windows API.  They both make an assumption which is hardly ever true: if you have a higher resolution screen, you'll adjust the DPI or font size in Windows to get larger characters.  Most of the time, a larger screen size means a larger physical monitor, or a laptop where you want to squeeze as much information into a small screen as possible; people value more information over greater detail. Thus the assumption fails.
If you can't squeeze your entire UI into the smallest size screen you need to support, you'll have to find another way to make it smaller.  Without knowing anything about your UI, I might suggest using tabs to group the controls into pages.
I've had good luck making my windows resizable, so that people with larger screens can see more information at once. You need to do this the hard way, responding to the WM_SIZE message to the window and deciding which controls should be made larger and which ones should just move.

A: There is no automatic way to resize the content of your dialogs when resolution changes. So, you need to set some boundaries.
Option 1.
If you are developing your app for customers, pick one minimum resolution (like 1024x7678), redesign you dialogs so that everything fits. Maybe break up some into several, or use tab strip control.
Option 2.
Create separate dialog forms for each resolution you'd like to support, but use the same class to handle it. At runtime detect resolution and use the appropriate form.
Option 3.
Write your own resizing functionality, so that user could adjust the size of your dialogs to his liking.


text:
Q: C# Select item from list and then get item from SQL Server CE database I am working on something that requires a selection to be made from a list view and then selects the item from a SQL Server database based on column 1 (or ii) and then rewrites it to a local datatable to be processed into a text file. Here's what I have so far:
var con = new SqlCeConnection(ConfigurationManager.ConnectionStrings[Connection.ConnectionStrings.CurrentConnection].ConnectionString);

foreach (ListViewItem item in LSTAsset.SelectedItems)
{
    for (int ii = 0; ii < LSTAsset.SelectedItems.Count; ii++)
    {

        string select = LSTAsset.SelectedItems[ii].Text;

        if (con != null && con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        var cmd = new SqlCeCommand("Select assetname, serial from asset where        assetname like '%" + select + "%'", con);
        SqlCeDataAdapter dataadapt = new SqlCeDataAdapter(cmd);
        //DataTable datatable = new DataTable();

        if (ii == 0)
        {
            dataadapt.Fill(steve.iTable);
        }

        if (ii < 0)
        {
            dataadapt.Update(steve.iTable);
        }
    }
}

Now my issue being, it seems to double the selected items when more than one item is selected. Say you selected 2 items, it now runs though the code 4 times and gives you 4 rows in the datatable. Why is it doubling the code? It ruins the output file later as it writes 2x the needed rows in the table.

A: It looks like you are looping unnecessary twice (SelectedItems.Count).
Try removing the inner or outer loop, for example:
foreach (ListViewItem item in LSTAsset.SelectedItems)

The reason why is because the next statement is doing the same thing via a for loop rather than a foreach and you will connect to the database n times * 2, where n is the selected item count.


text:
Q: Passing partial parameter in a push notification on Windows Phone 8.1 I'm trying to send a toast notification with a parameter to a Windows Phone 8.1 device, so when a user taps on the toast the app will show a particular page within the app, as it described in this MSDN article https://msdn.microsoft.com/library/windows/apps/jj662938(v=vs.105).aspx
This is a snippet that I use to add a parameter:
<wp:Param>?cmd=command1 </wp:Param>

this how I read it in the app:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){
            base.OnNavigatedTo(e);
            string strVal1 = this.NavigationContext.QueryString["cmd"];
        }

After making these changes it works correctly, but only for this first notification. In all subsequent notifications the value of the parameter read within the app is same as it was in the first notification, no matter what I've sent from the server.
Here is an example:

*

*I'm sending a notification to device that has with this parameter in the notification payload: <wp:Param>?cmd=command1 </wp:Param> The value in this.NavigationContext.QueryString("cmd") is command1, as it should be.

*Then I send a second notification with this parameter parameter
<wp:Param>?cmd=command2 </wp:Param>
the cmd's value in the this.NavigationContext.QueryString("cmd") is still returned as "command1" instead of command2 as it should be. And it works like that for all subsequent notifications until I force-restart the app.

Here is what I've tried:

*

*Checked the Uri value in the NavigationEventArgs argument of the OnNavigatedTo event and it's same as what I see in the NavigationContext.

*Double checked notification payload sent from the server (it's correct)

*Checked msdn/stackoverflow/google.

*Checked on both 8.1 emulator and the device (it works the same)

Questions:

*

*Do I have to do something in the app (idk, clear NavigationContext or something), so it will be different for the next notification?

*Does anyone actually has a live-app that uses partial arguments (not server-driven navigation with full url, but a partial url passed to the app + corresponding navigation from within the app) and it works for multiple subsequent notifications?

A: Figured out what the problem was. Two OnNavigated events are fired when app is relaunched. First one has a type of System.Windows.Navigation.NavigationMode.Reset and it has the data of the old page being reset (in my case, with the data from old notification). The second one is System.Windows.Navigation.NavigationMode.New and has the data from the new notification.
A simple check of navigation mode to make sure it's of the type .New fixed the issue:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){
        base.OnNavigatedTo(e);
    if (e.NavigationMode == System.Windows.Navigation.NavigationMode.New)){
    // custom navigation logic based on the data within <wp:Param/>
    }
}


text:
Q: Why didn't Voldemort make his Horcruxes out of normal objects? What would have happened if Voldemort was sensible and made a Horcrux out of any simple object such as a stone or something and flung it anywhere?
It will be highly difficult to know the position of such a Horcrux. And no one would search for a Horcrux among the pebbles...

A: They would still work as Horcruxes.
And as you say, this would be a much more foolproof way of hiding Horcruxes than to use significant objects and then resort to a great deal of complex magic in order to conceal them from others.
DVK has already given the perfect quote from the books to show why Voldemort didn't do this, but his answer doesn't quite prove that it would have worked if not for Voldemort's desire for grandeur. It's entirely possible, from the quote given, that ordinary objects wouldn't have worked for some reason, but Voldemort never bothered to consider the possibility because of his psychological preference for significant objects.
However, JK Rowling has confirmed beyond doubt that insignificant items could also be used as Horcruxes, when she told fans that if she had a Horcrux, it would probably be a teabag:

Ewokalypse❌: @jk_rowling if you had an horcrux, what object would you use?
J.K. Rowling: I would never, ever have a Horcrux. They are evil objects created through despicable means!  (Possibly a teabag).

A: "What would happen"?
Nothing different - they would STILL be Horcruxes and still work. The point of having special meaningful objects as Horcruxes was all about Voldemort's psyche, not magical laws.
Harry and Dumbledore discuss this in Half-Blood Prince, with Harry having a similar idea to the pebble one you mentioned (and for a far more interesting approach, I highly recommend the famous "Harry Potter and Methods of Rationality").

However, we should not congratulate ourselves too heartily. You destroyed the diary and I the ring, but if we are right in our theory of a seven-part soul, four Horcruxes remain.'
'And they could be anything?' said Harry. 'They could be oh, in tin cans or, I dunno, empty potion bottles...'
'You are thinking of Portkeys, Harry, which must be ordinary objects, easy to overlook. But would Lord Voldemort use tin cans or old potion bottles to guard his own precious soul? You are forgetting what I have showed you. Lord Voldemort liked to collect trophies, and he preferred objects with a powerful magical history His pride, his belief in his own superiority, his determination to carve for himself a startling place in magical history; these things, suggest to me that Voldemort would have chosen his Horcruxes with some care, favouring objects worthy of the honour.'
'The diary wasn't that special.'
'The diary, as you have said yourself, was proof that he was the heir of Slytherin. I am sure that Voldemort considered it of stupendous importance.'
'So, the other Horcruxes?' said Harry. 'Do you think you know what they are, sir?'
'I can only guess,' said Dumbledore. 'For the reasons I have already given, I believe that Lord Voldemort would prefer objects that, in themselves, have a certain grandeur. I have therefore trawled back through Voldemort's past to see if I can find evidence that such artefacts have disappeared around him.'


text:
Q: Repeating checkbox input with nested ngFor I'm trying to repeat a nested object and I have a checkbox with a value of true or false.
Here's my code:
<accordion-group
    *ngFor='let brand of products'>
    <div *ngFor='let product of brand.products'>
        <div>
           <input type="checkbox" id="{{product.name}}" ngControl="{{product}}" ([ngModel])="product.checked">
             <label
                attr.for="{{product.name}}"
                id="{{product.description}}"
                class="{{product.description}}"
                (click)="onCheck(model)">
             </label>
          </div>
        </p>
      </div>
    </accordion-group>

Plunker: http://plnkr.co/edit/IItxHiXkpocUjLG6NhMy?p=preview -- see that the checkbox doesn't check when the quantity value is updated. I can't get ngModel to work correctly.

A: *

*ngControl should be fromControlName according to angular2 RC.5

*([ngModel]) should be [(ngModel)] or used as different one like [ngModel] and (ngModel) .

*better to use property Binding using [ ] while binding id ,name etc dynamicaly as in your case use

use [id]="product?.name" instead of id="{{product.name}}"
use [attr.for]="product?.name" instead of attr.for="{{product.name}}"

seems Rest is fine everything, if still having same issue please reproduce your problem on plunker and post it.

A: This is invalid
([ngModel])

and should be
[(ngModel)]

It's called "banana in a box", not "box in a banana" ;-)

A: [(ngModel)]="product.checked";
100% working in angular 2


text:
Q: `error: ELF header smaller than expected` in grub rescue I am a complete newbie.
I installed ubuntu 12.04 on an old laptop on a clean hard disc
It worked well for a while, until various boot-up issues arose
Details can be supplied, but the position got worse and now all I get is:
error: ELF header smaller than expected
grub rescue>

This has been on Forum before, but did  not help.
computer does not activate cd/rom or usb (whatever order I put the into in BIOS)
Thus Boot Repair and Ubuntu 12.04 discs do not work, nor any other discs
Nor can I get into grub by hitting shift on boot-up.  All I can get is BIOS and the message above.
I have made some progress.
command ls shows:
(hd0) (hd0,msdos5) (hd0,msdos1).

ls (hd0,msdos1)/ shows line `'lost+found/ etc/ media/ bin/ boot/ dev/ home/ lib/ mnt/ opt/ proc/ root/run/ sbin/ selinux/ srv/ sys/ tmp/ usr/ var/ vmlinuz initrd.img cdrom/ Desktop/ initrd.img.old vmlinuz.ol .gnome-desktop/
I then type in
ls (hd0,1)/  produces the same output
ls /boot/      shows ./ ../ grub/ System.map-3.8.0-29-generic abi-3.8.0.29- generic config...  and a further 5 lines of similar stuff
set prefix=(hd0,1)/boot/grub

and all I get again is grub rescue>
same for when I type in
 set root=(hd0,1).

and if I type in
insmod normal

I get
error: ELF header smaller than expected
grub rescue>

I have come to a dead-end.  Before I give up can anyone confirm that my hard disc can still be broken, even though it comes up with 'grub rescue' and 'ls' as described above. If so it might just be worth buying a new hard disc as I suspect it has had it.


text:
Q: Wondering what the phrase "further swell" means
But the demonstrators who have taken over parliament and massed in the surrounding streets for the past five days fear the deal could further swell Beijing's economic influence over their proudly democratic island. (Source)

I'm confused about what "further swell" means.
My perception: ... they fear that the deal may more and more (further) make the Beijing's economic influence bigger or swell it in their democratic island.
My second concern is why the writer says "their proudly democratic island." What is the relation between  democratic island and proudly and swell?

A: "Further swell" could be switched with 'widen more' or 'make bigger still' or 'complicate even more' or anything similar to that. Swell is a verb here, and 'further' is an adverb describing it.
The island is described as democratic, and they are proud of that democracy. This is what the end of the sentence means.


text:
Q: Illogical null pointer exception I'm doing a Rest integration project, and I'm trying a PUT api request for an API I'm implementing. This is part of the code that is on the start of the PUT operation implementation.
String name = vivienda.getName();
Vivienda oldVivienda = repository.getViviendas(name);
if (oldVivienda == null) {
    throw new NotFoundException("No se ha encontrado ninguna vivienda con el nombre="+ vivienda.getName());
}

Thing is, when I do the request, it returns me the NotFoundException declared there, so it didn't work.
Playing with the code I localised that the error was that, certainly, the object oldVivienda was null, as if I tried to do something with its getName, it would throw NullPointerException.
But here's where I start not understanding anything. I changed the code to try and find where the error was, putting the name string directly like this:
Vivienda oldVivienda = repository.getViviendas("vivienda1");
if (oldVivienda == null) {
    throw new NotFoundException("No se ha encontrado ninguna vivienda con el nombre="+ vivienda.getName());
}

This works perfectly. This would lead to thinking that the problem is with the parameter object vivienda, that it's or its name is empty or isn't "vivienda1". But, remember the exception? In the exception I use vivienda.getName(), and when I see the error thrown in the response, it actually says "vivienda1". So I sent fine the object, and when you do vivienda.getName() it returns "vivienda1". And when you put the string "vivienda1" in the repository.getViviendas("vivienda1"), it works perfectly.
So, where is the problem? Is there any problem with types? But getName is a simple get method that returns a String. And I've checked several times if there was a space somewhere or something. The error is in those 2 first lines of code, but I have no idea what's going on.

A: If this code works
repository.getViviendas("vivienda1");

while the following doesn't
repository.getViviendas(name); // name is "vivienda1"

it could mean that String comparison is done incorrectly inside of repository.
If you're declaring two Strings as literals then comparison using == operator will be successful since they'll be stored in a String pool. But if the value of one of those strings comes in dynamically (like from your RESTful API client) then it will not work.
Please read What is String pool in Java? for more details on String pool in Java.
The correct way to compare Strings in Java is .equals() method:
someString.equals(otherString);


text:
Q: IBM M1115 and LSI 9211-8i IT mode I have an IBM M1115 RAID Controller. It has 8 Seagate SATA drives connected to it using what I assume is a forward breakout cable (SFF-8087 to 4x SATA).
When I power it up without flashing to LSI 9211 firmware, sometimes I see 8 drives in the LSI BIOS (Ctrl + H). Other times, I see 7 drives, with one drive missing, and one drive showing as "Unconfigured Bad". Other times, it boots up seeing 5 JBOD drives, missing 3 other drives.
I also hear one or more disks spinning up and down every 30 seconds or so. Only disks in the center of the NAS spin up and down, those connected to the second SAS port on the controller.
Also, when I try to boot into FreeNAS, I get an error "BTX Halted"...
I flashed the card to the LSI 9211-8i IT firmware. Now instead of Ctrl + H, I can press Ctrl + C to enter the BIOS. When I go into SAS Topology, it says that no drives are detected. However, the system now boots into FreeNAS with no issue.
I tried to flash to the LSI 9211-8i IR firmware, and still there are no drives detected.
I flashed back to the IBM firmware, and it now sees most drives, though they randomlly disappear, and spin up and down.
What could be causing this? Would the wrong type of SAS to SATA cable cause this kind of issue? Maybe I have a "reverse" breakout cable instead of "forward"? Would any drives show up at all if it was the wrong cable?
Thank you for your help.

A: Solution was to replace my powersupply with a quality 750watt one. This stopped the issue of drives spinning down.


text:
Q: python 2.7 Dictionary passing argument to .get I've created a number of functions to help me run my current program. Where possible I'm trying to utilise these custom elements, as many times as possible, just to keep their number fairly reasonable.
To the point.
I've wrote below to allow me to search through various dictionaries where result is in the form of list i.e. People = {'IR1': [65, 'M', 77076], 'IR2': [24, 'M', 77077], ....}
IR = unique person identifier
1st position in the list - AGE,
2nd position in the list - Gender,
3rd position in the list - GP practice code.
To pick up each necessary value I'm using:
def TestCustom1(Search, Source, Offset):

    if Search == 'Blank' or Search == 'Missing IRF - MT' or \
    Search == 'Missing IRF - source data' or Search is None or \
    Search == 'Date out of scope':
        CusRet = 'Blank'

    elif Source.get(Search) is not None:
        CusRet = TestType('CharZ', Source.get(Search)[Offset])

    else:
        CusRet = 'Missing from look up tbl'

    return CusRet

Where:
TestType, evaluates the results (i.e. if value is Null it will return 'Blank').
Search = look up value, Source = name of the Dictionary, Offset = value position.
I'm using this to support around 5 different dictionaries.
Problem:
I've got very simple Dictionary = {'AA20':'Intradural Spine Major 1', .....}
When using the following in the editor everything works correctly:
DictHRG.get('HC08Z')[0:]
u'Intradural Spine Major 1'

But when trying to pass [0:] into the function I've made, there is en error:
TestCustom1('HC08Z', DictHRG, 0:)
SyntaxError: invalid syntax

and
TestCustom1('HC08Z', DictHRG, [0:])
SyntaxError: invalid syntax

Sollution:
1. I could write a new function, but as mentioned I'm trying to keep a reasonable number of them
2. I could use IF statement in the code for this particular dataset, but would prefer to use the TestCustom1 (as on blanks I need the same output for all the datasources):
CusRet = 'Missing from look up tbl'

and it's easier to change it in the function if needed rather the going back to this one set (I've got over 50 datasources)
Question:
Can you possibly adice on above, also suggestion on alternatives would be greatly appreciated (I'm pretty sure It is some rookie mistake I'm making).
Many thanks in advance.

A: You can use the offset in a slice:
CusRet = TestType('CharZ', Source.get(Search)[Offset:])

or pass in a slice() object for the offset:
TestCustom1('HC08Z', DictHRG, slice(0))

Note that 0 is the default starting point for slices.
Your code can be simplified by just testing for the key with a membership test:
def TestCustom1(Search, Source, Offset=0):
    if Search is None or Search in (
            'Blank', 'Missing IRF - MT', 'Missing IRF - source data',
            'Date out of scope'):
        return 'Blank'

    if Search in Source:
        return TestType('CharZ', Source[Search][Offset:])

    return 'Missing from look up tbl'

where Offset is assumed to be an integer, defaulting to 0 to slice from the start.
However, note that your function now returns two different types based on the match; either a string or a list is returned. Use exceptions instead to communicate exceptional circumstances.


text:
Q: Function Pointers Using typedef in C If I wanted to declare a typedef for a certain type, I would go for a syntax like this one, in this example:
typedef int INT

But when I wanted to create a typedef for a function, I was expecting the following syntax to be the one:
typedef void (*)(int, char) myfunc;

Instead the correct one is:
typedef void (*myfunc)(int, char);

So why the first one is not correct?

A: A typedef looks exactly like a "normal" declaration. If you declare a function pointer, it would look like this:
void (*myfunc)(int, char);

So, the typedef looks the same, with the only difference that the declared identifier doesn't refer to an object of the type, but to a type alias name instead:
typedef void (*myfunc)(int, char);

As for the "why?" -- Well, because the language is designed that way, but I guess once you understand how it works, it's arguably the easiest way not to introduce a different syntax for typedef declarations. This design is following the principle of least surprise, treating typedef declarations somehow differently would be needlessly complicated.

A: The basic way to create function pointer is void (*myfunc)(int, char);
So to create a new type that is a function pointer which returns void and get int and char as argument is
typedef void (*myfunc)(int, char);
that is why the first one is incorrect
There is no need of adding (*) before function pointer.

A:
But when I wanted to create a typedef for a function, I was expecting
  the following syntax to be the one:
typedef void (*)(int, char) myfunc;

You can of course write you own compiler of your own language.
But C syntax is like this.
Here is the another example:
typedef char foo[10];


text:
Q: Minimizing two matrices I have tow matrices C_model and C_measure and i want to minimize the difference between them where sigma_i is the error variance of element i and C_ij is each element in the matrix
I tried the following:
\chi^2  =\sum_{i,j} \frac{(C_{model,i,j}-\hat{C_{i,j}})^2}{\sigma^2_{i}}  = \sum_{i,j} (\Delta C_{i,j})^2 W_{i} = (\Delta C)(\Delta C)^{T}
I want to check whether this formula is correct mathematically, and why i can replace this term
\sum_{i,j} (\Delta C_{i,j})^2 W_{i} by
this term ? (\Delta C)(\Delta C)^{T}, i took it from reference book but i do not understand the math behind it.


text:
Q: Create a generated column in MySql with count I am not a database guy, despite this I have created a statement which counts the ids function by the unique group ids from the table as this:
USE farm;
SELECT reg.grpId, COUNT(reg.id) as TOTAL FROM farm.reg group by reg.grpId;

Because I do't want to operate over the NodeJs server I need to know if it is possible to make a generated column as like the below which gives me an error 1064 -SELECT not valid at this position
the statement:
USE farm;
ALTER TABLE reg ADD total INT GENERATED ALWAYS AS(SELECT reg.grpId COUNT(reg.id) FROM farm.reg group by reg.grpId)STORED AFTER grpId;

Thank you!

A: You can't do what you want with a computed column. I would recommend a view and window functions (available in MySQL 8.0)
create view reg_view as
select r.*, count(*) over(partition by grpId) total
from reg r

In MySQL < 8.0, an option is to join with an aggregate query:
create view reg_view as
select r.*, g.total
from reg r
inner join (select grpId, count(*) total from reg group by grpId) g on g.grpId = r.grpId