text:
Q: Change tinymce toolbar icons to text How can I change tiny mce editor's toolbar icons to text ?
I want these icons to be text buttons.

A: TinyMCE adds buttons to the toolbar in a variety of places.  The method addButton (which is in the tinymce/classes/Editor.js file) is the method used to add a button to the toolbar:
https://www.tinymce.com/docs/api/tinymce/tinymce.editor/#addbutton
If you want to change all of the icons to text strings you need to find the code where each button is added to the toolbar and modify the call to addButton to not use an icon.
For example, the print plugin has this code:
editor.addButton('print', {
    title: 'Print',
    cmd: 'mcePrint'
});

...which you could change to this:
editor.addButton('print', {
    title: 'Print',
    cmd: 'mcePrint',
    text: 'Custom Print'
});

You would then see the text Custom Print on the toolbar instead of the icon.
A word of warning - the core editor code adds some buttons, and plugins add some buttons.  If you truly want to replace the icons of all buttons you will have to modify a fair amount of code in TinyMCE which will make upgrading the editor much harder.


text:
Q: Where does LaTeX check for installed packages? When I use \usepackage{<package_name>}, what directories does LaTeX check for the .sty file for <package_name>? I'm asking this because I have a set of "configurations" that I always place in the preamble of my files and it would just be a lot easier to load all of that from a .sty file.
In my experience, it checks the directory of the .tex file and the regular install directory (in my case ~/.local/texlive/2020/texmf-dist/tex/latex), but I was wondering if there are any other options.
Not sure if it matters but I'm using Ubuntu 18.04 with a user (rather than root) install of TeXLive.

A: You can write the relative path for the package.
\usepackage{Folder/Bruh.sty}

redpajama_set_name: RedPajamaStackExchange


text:
Q: OpenGLES glEnableVertexAttribArray Подскажите пожалуйста, кто знает. Как сильно glEnableVertexAttribArray() просаживает скорость программы?
У нас софт для визуализации, и очень важна скорость. Прям очень сильно важна. В текущей версии glEnableVertexAttribArray() вызывается один раз при инициализации, и в шейдерах используется всего один атрибут. Но теперь стоит задача, для решения которой одного атрибута не достаточно (в 4 вещественных канала данные никак не умещаются). Но добавление нового атрибута приводит к тому, что вместо одного единственного вызова glEnableVertexAttribArray() при инициализации, и одного вызова glVertexAttribPointer(...) при отрисовке, приходиться три раза вызывать glEnableVertexAttribArray(), три раза glVertexAttribPointer(...) и три glDisableVertexAttribArray() при каждой отрисовке!
glVertexAttribPointer(...);

vs
glEnableVertexAttribArray(...);
glEnableVertexAttribArray(...);
glEnableVertexAttribArray(...);
glVertexAttribPointer(...);
glVertexAttribPointer(...);
glVertexAttribPointer(...);
glDisableVertexAttribArray(...);
glDisableVertexAttribArray(...);
glDisableVertexAttribArray(...);

A: пихай все данные в один массив и тормозов не будет.(x,y,z,tx,ty,tz,nx,ny,nz и тд)


text:
Q: JavaScript Only FadeIn Function   fadeIn:function(speed,till){
          speed = speed !== undefined ? speed : 400;
          speed = typeof speed === 'number'  ? speed : speed == "slow" ? 600 : speed == "fast" ? 200 : speed !== 'slow' || speed!== 'fast' ? 400 : 400;
          var opc = window.getComputedStyle(this[0]).opacity;
          var element = this[0];
          var add = 100 / speed;
          till = till !== undefined ? till : 1;
          element.style.display="block";
          var timer = (function  a() {
           if (opc >= till ){
            element.style.opacity = 1;
            clearInterval(timer);
            return false;
            }
            if(browser[3] == 'MSIE' && Number(browser[4]) < 9 ){
            add = 10000 / speed;
            element.style.filter = 'alpha(opacity="' + (opc+ add) + '")';
            }
            element.style.opacity = opc;
            opc = opc + add; // code here where addition starts
            setTimeout(a, 50);
          })();
    },

Now the function above will not run its course correctly. As JavaScript does not correctly add floating decimals. So I've tried many ways...
 opc = (opc * 100) + (add * 100) / 100;

Also tried a close hack as this gives me my decimal number the above gives me a whole number no matter what really.
 opc = "."+parseInt((opc * 100) + (add * 100) / 100,10);

Though I believe whats wrong with the above is that it turns into a string and well just doesn't cut. So the question is how do I increment decimals as this is very necessary.
EXAMPLE
  0.001 - 0.002 - 0.003 - 0.004 etc

A: JavaScript is adding floating point numbers fine.
Probably one of your operands is not a floating point number.
Quote from a JS book:
JavaScript has a single number type. Internally, it is represented as 64-bit floating
point, the same as Java's double. Unlike most other programming languages, there is
no separate integer type, so 1 and 1.0 are the same value.
I would try to debug the code and then see which values are strings (or not numbers), and then parse them using the parseFloat function.


text:
Q: DB2 - Cannot connect to or drop database. But it exists on disk Hi so when I try to drop a database "sample" in db2 in CLPPlus it says the database alias name or database name "sample" could not be found. But when I type the
list database directory

command i see that it is there. it is also on disk, i see it where i designated the location of the database when i made it. I cannot connect to it and I cannot drop it.
just extra info... don't know if it will be useful, but i uncatalogged the database and when i try to catalog it, it says the database was not found in the local database directory

A: Are you dealing with the file system where the database is stored? Normally, a database is created in two directories, one is in the instance whe the database files are stored (history, lock control, configuration, etc.) and another for the tablespaces (catalog).
Are you sure you see both of them?
I think just one of these locations is still on your hard disk, and that is not enought to connect to the database.
Did you uninstalle (drop) the instance?
In your case it is better to uncatalog everything, drop the instance and rebuild the configuration.


text:
Q: Проставление реакции к сообщению Постигаю все прелести создания собственного бота. Возникла следующая трудность с добавление реакции к сообщению.
Есть:
bot = commands.Bot(command_prefix='!')
nbr = [' :ok:  - ок\n :ballot_box_with_check: - чек']

@bot.command(aliases = ['тест'])
async def test(ctx):
    await ctx.send(
        embed=discord.Embed(
            title='Тест!',
            description=''.join(nbr)
            )
    )

Уже как только не пробовал, но не могу понять, каким образом мне добавить к появляющемуся сообщению реакцию от бота, чтобы по ним уже могли нажимать другие люди.
Реакции :ok: и :ballot_box_with_check:

A: import discord
from discord.ext import commands
token = 'ВАШ ТОКЕН'
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_message(message):
    if 'грустно' in message.content.lower():
        embed = discord.Embed(title='как жаль')
        message = await message.channel.send(embed=embed)
        await message.add_reaction('☹') #Add a reaction to the message
bot.run(token)

Вот простенький бот, который отвечает на сообщение, в котором есть слово грустно, и ставит грустную реакцию. Вот так:

Вместо ☹ можно поставить любой эмодзи, скопировав отсюда. Не беспокойтесь, если в коде эмодзи заменятся пробелом, [] или ? - Python "заберёт" и восстановит их.
Кстати, если не хотите заходить на сайт, вот смайлики, которые вам нужны:  и

A: Если хотите добавить реакцию, то вот:
@bot.command(aliases = ['тест'])
async def test(ctx):
    msg = await ctx.send(
        embed=discord.Embed(
            title='Тест!',
            description=''.join(nbr)
            )
    )
    await msg.reaction_add('реакция')
    await msg.reaction_add('реакция')

Вы должны просто к отправленному сообщение (присвоить переменную) добавить реакцию await переменная.reaction_add('реакция')


text:
Q: How do I save the state of CheckedTextView checkbox so it stays checked after exiting? So I kinda screwed up while making the checkedtextviews, didn't realise i needed to save the state, I don't know how exactly to do it. Any advice would be greatly appreciated.
CheckedTextView C1,C2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_anime2);

    C1 = findViewById(R.id.C1);
    C2 = findViewById(R.id.C2);

    C1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View V) {
            C1.toggle();
            if(C1.isChecked() == true)
            {
                C1.setBackgroundResource(R.drawable.cb_background);
            }
            else
            {
                C1.setBackgroundResource(R.drawable.cb_background_default);
            }
        }
    });
    C2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            C2.toggle();
            if(C2.isChecked() == true)
            {
                C2.setBackgroundResource(R.drawable.cb_background);
            }
            else
            {
                C2.setBackgroundResource(R.drawable.cb_background_default);
            }
        }
    });

A: I'm not familiar saving data yet, I know that there is a lot of ways of doing that so i'll give one example:
Before that here is a guide like that can help:
Save key-value data
Here is a example of what i did.You could put the variable as a global if you need.
CheckedTextView C1,C2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_anime2);

    C1 = findViewById(R.id.C1);
    C2 = findViewById(R.id.C2);

    C1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View V) {
            C1.toggle();
            if(C1.isChecked() == true)
            {
                C1.setBackgroundResource(R.drawable.cb_background);
            }
            else
            {
                C1.setBackgroundResource(R.drawable.cb_background_default);
            }
            savePreferences();
        }
    });
    C2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            C2.toggle();
            if(C2.isChecked() == true)
            {
                C2.setBackgroundResource(R.drawable.cb_background);
            }
            else
            {
                C2.setBackgroundResource(R.drawable.cb_background_default);
            }
            savePreferences();
        }
    });
}
//To save the status of each textCheck
public void savePreferences(){
    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putBoolean("c1",C1.isChecked);
    editor.putBoolean("c2",C2.isChecked);
    editor.apply();
}
//to get each textCheckSaved
public void getSavedPreferences(){
    SharedPreferences preferences = getPreferences(MODE_PRIVATE);
    C1.setChecked(preferences.getBoolean("c1",C1.isChecked))
    C2.setChecked(preferences.getBoolean("c2",C2.isChecked))
}
//to clean the data that you save
public void cleanSavedPreferences(){
    sharedPreferences = getPreferences(MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.remove("c1").remove("c2");
    editor.apply();
}


text:
Q: NGINX could not resolve host with upstream and path I am using NGINX as a load balancer to route all traffic on example.com to one of the two servers. It works fine if there is no path added to the URL https://example.com but if there is a path https://example.com/legal then I get an error:
could not resolve host servers:8080
It seems like the path that is added to the URL makes nginx "forget" about the servers variable and it treats it like a real domain, which is obviously not working.
My NGINX config:
upstream servers {
    server 192.0.0.1:8080;
    server 192.0.0.2:8080;
}

server {
    listen 80;
    server_name example.com;

    return 302 https://example.com$uri$is_args$args;
}

server {
    listen 443;
    server_name example.com;

    // ssl config and certs

    location / {
        proxy_pass http://servers;
    }
}

What setting am I missing here?


text:
Q: R and dplyr - how to write efficient code for load data from database I use dbplyr for getting data from our sql database. Basicaly I work like this:
1) I load same data from one table, for example:
flights <-
  tbl(delta, "us") %>%
  select(id, origin) %>%
  collect()

2) Then I use this data filtering data from other tables etc.
passangers <-
  tbl(customers, "all") %>%
  filter(flight_id %in% flights$id) %>%
  filter(year == "2018") %>%
  collect()

payments <-
      tbl(incoming_payments, "all") %>%
      filter(flight_id %in% flights$id) %>%
      filter(year == "2018") %>%
      collect()

contact_data <-
      tbl(emails, "all") %>%
          filter(customer_id %in% passangers $id) %>%
          filter(type == "email") %>%
          collect()

This works well until I need to load data from more tables. Since this way im creating dataframe for each query and I know how to load data from just one table by one query Im creating so many dataframes and code is quite repeated even in this simple example.
So my question is if there is a way how to write similar query more simplier ideally with only one created dataframe. But with ability to filter data like I do (Im filtering only flight_ids that are present in flights dataframe etc.)

A: I'm not familiar with tbl(), would this work?
table_names = c("customers","incoming_payments","emails")

extractFilter = function(x)
  tbl(x,"all") %>%  #eval(x) here?
  filter(flight_id %in% flights$id) %>%
  filter(year == "2018") %>%
  collect()

results = lapply(table_names,extractFilter)

This way you get all the data frames in the results list. You could join them all adding a pipe to purr::reduce(full_join,by="join_variable")


text:
Q: Converting decimal xml to decimal with 2 decimal points with XQuery I am a newbie to xml and XQuery and I have question about converting numbers.
I have flat file which is being converted to xml using Stylus Studio converter. Then I use XQuery to pull in the various tables that I need.
One of the issue is the currency input data.
Flat file data : 00004700000 This is $47000
(In the converter source is defined string and destination is defined decimal)
In XQuery I can divide the number 00004700000 by 100 and BUT end up with 47000.
What I'd like is the output to be 47000.00 so that I can display it as it is with 2 decimal points.
Value 000038715 divide by 100 gives 387.15 which works fine.
This is what I do in XQuery:
<CREDIT_LIMIT>
{$cust/CREDIT_LIMIT div 100}
</CREDIT_LIMIT>

Is there a way to do this to get .00 on the output of XQuery?
Many thanks.
Pravin
PS
Don't know much about xslt!

A: you have the function format-number for this :
<CREDIT_LIMIT>
{format-number($cust/CREDIT_LIMIT div 100,".00")}
</CREDIT_LIMIT>

A: Use:
<CREDIT_LIMIT>
  {$x idiv 100 }.{$x mod 100 idiv 10}{$x mod 10}
</CREDIT_LIMIT>

where $x is the number to be represented in the desired decimal format.


text:
Q: Q:how to increment file creation from an event? I tried to create a txt file for every new message from Telegram using telethon event.
I would like to have txt file like OIF ,OIF1, OIF2,OIF3 ... for every message I get
Thanks for help
That's my code
client.start()
@client.on(events.NewMessage(chats='tradingnava'))
async def my_event_handler(event):
    texte = (event.text)
    texte = texte.split(" ")
    Marche = texte[1]
    Direction = texte[2]
    i = 0
    while os.path.exists('OIF%s.txt' % i):
        i += 1
        if Direction == 'buy':
            f= open(r'C:\Users\USER\PycharmProjects\rakna2\OIF%s.txt' %i, "w")
            f.write("buy b a")
            f.close()
        if Direction == 'sell':
            f= open(r'C:\Users\USER\PycharmProjects\rakna2\OIF%s.txt" %i, "w")
            f.write("sell b a")
            f.close()

A: import os
import re

path = r'C:\\Users\\USER\\PycharmProjects\\rakna2\\'
client.start()
@client.on(events.NewMessage(chats='tradingnava'))
async def my_event_handler(event):
    texte = (event.text)
    texte = texte.split(" ")
    Marche = texte[1]
    Direction = texte[2]

    allfile = [int(re.findall(f'\d+', fname)[0]) for fname in os.listdir(path)
               if fname.startswith("OIF") and re.findall(f'\d+', fname)]
    try:
        s = str(max(allfile) + 1)
    except ValueError:
        allfile = [0]

    with open(r'OIF%s.txt' %str(max(allfile) + 1), 'w') as f:
        Direction = 'buy'
        if Direction == 'buy':
            f.write("buy b a")
            f.close()
        elif Direction == 'sell':
            f.write("sell b a")
            f.close()
        else:
            f.write(f"Direction Error {Direction}")
            f.close()


text:
Q: Can you help me optimize this code for finding factors of a number? I'm brushing up on my math programming I've never really bothered with math programming, but today I've decided to give it a shot.
Here's my code and it's working as intended:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PrimeFactorization
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            List<int> primeFactors = FindPrimeFactors(Convert.ToInt32(txtNumber.Text));
            primeFactors.Sort();
            for (int i = 0; i < primeFactors.Count; i++)
            {
                listBoxFoundNumbers.Items.Add(primeFactors[i]);
            }
        }

        private List<int> FindPrimeFactors(int number)
        {
            List<int> factors = new List<int>();
            factors.Add(1);
            factors.Add(number);

            for (int i = 2; i < number; i++)
            {

                if (number % i == 0)
                {
                    int holder = number / i;
                    //If the number is in the list, don't add it again.
                    if (!factors.Contains(i))
                    {
                        factors.Add(i);
                    }
                    //If the number is in the list, don't add it again.
                    if (!factors.Contains(holder))
                    {
                        factors.Add(holder);
                    }
                }
            }

            return factors;
        }
    }
}

The only problem I can see with my code is that it will iterate through to the bitter end, even though there will definitely not be any factors.
For example, imagine I wrote in 35. My loop will go up to 35 and check 24,25,26,27...etc. Not very good.
What do you recommend?

A: One thing you can do is avoid checking even numbers after 2, since they will never be prime.
So, check 2 and then declare your loop as such:
for (int i = 3; i < number; i+=2)

Re: stopping at sqrt(n) - this is an effective technique for determining whether a given number is prime, since any n that divides x where x > sqrt(n) also divides n/x which is necessarily less than sqrt(n).  But a number may have prime factors larger than its own square root (for example, 1002 = 2 * 3 * 167).
That said, you could implement some kind of recursive solution where, for all prime factors p of n such that p < sqrt(n), you also calculate the prime factors of n / p.  My gut feeling is that this will decrease the running time of your algorithm in general, but might increase it for small values of n.
Edit: if you're interested in getting into more sophisticated techniques, the Wikipedia page on Integer Factorization links to all kinds of algorithms.

A: You can go only up to and including sqrt(number). Consider x from 2 to sqrt(N). if N % x == 0, then N % (N / x) == 0 as well. Take 10 for example:
sqrt(10) = 3 (integer part).
10 % 2 == 0 => 2 is a divisor of 10. 10 % (10 / 2) == 10 % 5 == 0 => 5 is also a divisor.
10 % 3 != 0.
This is it, the divisors of 10 are 2 and 5. You have to be careful when dealing with perfect squares and that is it.
You also don't need your checks to see if a number is in the list or not if you do it like this. Just make sure you don't add the same number twice in case of perfect squares (if x == N / x, only add x).
This is about as efficient as it gets without considering a lot more complicated algorithms.
Edit:
To get PRIME factors only, when you find an x such that N % x == 0, divide N by x while this is possible. For example, consider 20:
sqrt(20) = 4.
20 % 2 == 0 => 2 is a prime factor. Divide it by 2 until the remainder of the division by 2 is no longer 0: 20 / 2 = 10, 10 / 2 = 5.
5 % 3 != 0
5 % 4 != 0
The number you are left with at the end of the algorithm is 5 > 1, so add 5 as well. The prime factors of 20 are therefore 2 and 5.
So basically your algorithm in pseudocode is this:
listPrimes(number)
  N = number;
  for ( i = 2; i <= (int)sqrt(number); ++i )
    if ( N % i == 0 )
      primeFactors.Add(i);
      while ( N % i == 0 )
        N /= i;

  if ( N > 1 )
    primeFactors.Add(N);

You can also use what @danben has suggested in his post, using increments of 2 and starting from 3 and treating 2 separately. The most efficient however is to generate primes using the sieve of Eratosthenes and using those generated primes in combination with this algorithm. Most efficient while staying in the world of basic math anyway.

A: One classic algorithm for finding prime factors is the Sieve of Eratosthenes (see this)

A: First order of business is to use a proper prime-generating algorithm.  Most common is the Sieve of Eratosthenes, which I'll post because it's easier, but there's also the Sieve of Atkin which is far more optimized.
I'd use something like this for the sieve, which I've posted before:
public class Primes
{
    public static IEnumerable<int> To(int maxValue)
    {
        if (maxValue < 2)
            return Enumerable.Empty<int>();

        bool[] primes = new bool[maxValue + 1];
        for (int i = 2; i <= maxValue; i++)
            primes[i] = true;

        for (int i = 2; i < Math.Sqrt(maxValue + 1) + 1; i++)
        {
            if (primes[i])
            {
                for (int j = i * i; j <= maxValue; j += i)
                    primes[j] = false;
            }
        }

        return Enumerable.Range(2, maxValue - 1).Where(i => primes[i]);
    }
}

The last step is just to find out which primes are factors, which is easy:
public static IEnumerable<int> GetPrimeFactors(int num)
{
    return Primes.To(num).Where(i => num % i == 0);
}

That's it!  This will generate prime factors up to 20 million in less than 1 second, so it's probably good enough for whatever you're doing.  Otherwise you can use a better sieve, as I mentioned at the top, or a lazy skip-set algorithm.
One last thing: If you're trying to factor huge numbers then you need to switch to something very different, such as the General Number Field Sieve.  This is (as far as I know) currently the fastest factorization algorithm for very large numbers, as part of ongoing research to see if RSA encryption can be cracked.

A: If you want to find all factors (not just prime), once you find a smallest factor, k, you can update your loop's upper bound to only go up to (and including) n/k. This is because the largest factor l must satisfy p = k * l.
An even better approach may be to use the factors that you've found so far to calculate the factors greater than sqrt(n). So, in the above, you could calculate l directly from k and n.


text:
Q: Positive Integer points of $f(x)=\frac{1}{c-\frac{1}{x}}$, where c is fixed So I am looking for the integer solutions of $f(x)=\frac{1}{c-\frac{1}{x}}$  for fixed $c\in \mathbb{Q}$ i.e. points $(x,f(x))\in \mathbb{N}\times \mathbb{N}$. (The c equals $\frac{4}{n}-\frac{1}{k}$ where $n,k\in \mathbb{N}$).
1)Are there any methods for computing that. Or at least getting some upper and lower bounds? Or at least references for methods for any curve and then I can look more deeply?
2)I know I can probably find that using algebraic number theory but I am really curious of any geometric/analysis methods out there.
3)Does that equation relate to Diophantine equations? Are there any ways of relating general curves to Diophantine? Like how elliptic curves are analyzed with Diophantine equations.
Thank you so much

A: I'm not sure about the deeper questions you ask, but here is an elementary observation.
You are looking for positive integer solutions solutions $(x,y)$ for the curve
$$y = \frac{1}{c-1/x}$$
given a rational number $c$.
Just rewrite this as:
$$\frac{1}{x} + \frac{1}{y} = c$$
and the question becomes much more transparent.  You will have one or two solutions whenever $c$ can be written as $c = 1/x + 1/y = (x+y)/xy$; otherwise there will be no solutions.
More interesting is the question as whether $c$ of the form $c = 4/n - 1/k$ for positive integers $k$ and $n$ can satisfy the above condition.  We can rewrite this as integer solutions to
$$\frac{1}{x} + \frac{1}{y} + \frac{1}{k} = \frac{4}{n}.$$
A few obvious solutions come to mind: $x = y = k = 3$ and $n = 1$, or $x = y = 2$, $k = n = 1$ and its obvious permutations.  This is a homogenous equation so integer multiples of those solutions work as well.  In fact, we can choose any positive rational numbers $x,y,k$ and then solve for $n$; then we can clear denominators to get integer solutions.  So there are lots of solutions.
To attempt to address some of your other questions, we can rewrite this equation as a homogenous cubic
$$kxn + kyn + xyn - 4xyk = 0$$
and (aside from your restictions on the sign of the solutions), it suffices to look for rational solutions $[x,y,z,k] \in \mathbb{P}^3(\mathbb{Q})$ because we can always clear denominator to get integral solutions.  We can let $n = -4z$ and get a more symmetric equation,
$$kxz + kyz + xyz + xyk = 0$$
and now we are looking for rational solutions to this elementary symmetric cubic polynomial.  This famous cubic surface is known as Cayley's nodal cubic surface.  It has four singular points: $[1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1]$.


text:
Q: What is the default MSI identity for which a token is retrieved, when querying IMDS from within a VM This link describes how to retrieve the token for a specific managed identity, if a VM is configured with multiple identities.
What is the behavior if the identity is not specified in the request? For which identity is the token returned? Is it for the system identity, or for the first user identity, or for the first identity that was configured on the VM, or something random?

A: *

*System assigned managed identity will be the default, if no identity is specified in the request.

*If system assigned is not enabled, and only one user assigned exists, then IMDS will default to that single user assigned.

*If system assigned is not enabled, and multiple user assigned exist, then specifying the identity in the request is required.

We'll update our docs to include this information. :)


text:
Q: angularjs: regexp fails onblur I'd love to detect where a string matches a regexp but this seems to fail on blur. Please see this plunkr.
Here's the js:
 var endsWithPipeOrSpace = /\s+$|\|$/g;

$scope.inputGetFocus = function() {
  $scope.msg = "input gained focus"
  if (endsWithPipeOrSpace.test($scope.newquery)) {
    $scope.msg += " string match";
  } else {
    $scope.msg += " string doesn't match";
  }
}

$scope.inputLostFocus = function() {
  $scope.msg = "input has lost focus"
  if (endsWithPipeOrSpace.test($scope.newquery)) {
    $scope.msg += " string match";
  } else {
    $scope.msg += " string doesn't match";
  }
}

$scope.newQueryModified = function() {
  $scope.msg = "input modified"
  if (endsWithPipeOrSpace.test($scope.newquery)) {
    $scope.msg += " string match";
  } else {
    $scope.msg += " string doesn't match";
  }
}

and here's the HTML:
Please note I'm declaring ng-trim="false"
 <input type="text" class="form-control"
id="newquery" ng-model="newquery"
placeholder="Enter your query"
autofocus required autocomplete="off"
ng-change="newQueryModified()"
ng-trim="false"
ng-focus="inputGetFocus()"
ng-blur="inputLostFocus()">

A: regexp fails on blur because the lastIndex of endsWithPipeOrSpace has been changed in newQueryModified function.
Read a bit about RegExp lastIndex property.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex
The lastIndex is a read/write integer property of regular expressions that specifies the index at which to start the next match.
When a successfull match happens for regular expression, lastIndex value is changed to length of matched string.
So here you have to reset the lastIndex value to 0 to test $scope.newquery with endsWithPipeOrSpace like this
$scope.inputLostFocus = function() {
   $scope.msg = "input has lost focus"
   endsWithPipeOrSpace.lastIndex = 0;          // reset lastIndex here
   if (endsWithPipeOrSpace.test($scope.newquery)) {
       $scope.msg += " string match";
   } else {
       $scope.msg += " string doesn't match";
   }
}


text:
Q: How to use a custom row instead of the android.R.layout.simple_list_item_multiple_choice in Multple Choice row in android? I am working on this code but I have white background due to the android.R.layout.simple_list_item_multiple_choice I am unable to change the text color so that it will be ligible in the row.How to change it for custom row xml,here is my code.
    public class AndroidListViewActivity extends Activity
{
    ListView myList;
    Button getChoice;
    String[] listContent = {"January","February","March","April","May","June","July","August","September","October","November", "December"};
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myList = (ListView)findViewById(R.id.list);
        getChoice = (Button)findViewById(R.id.getchoice);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice,listContent);
        myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        myList.setAdapter(adapter);
        getChoice.setOnClickListener(new Button.OnClickListener(){
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                String selected = "";
                int cntChoice = myList.getCount();
                SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
                for(int i = 0; i < cntChoice; i++)
                {
                    if(sparseBooleanArray.get(i))
                    {
                        selected += myList.getItemAtPosition(i).toString() + "\n";
                        }
                    }
                Toast.makeText(AndroidListViewActivity.this, selected,Toast.LENGTH_LONG).show();
                }
            });
        }

}

Please help me on this with an example or snippet,I am struck here for a long time.Thanks

A: As you can see, ArrayAdapter takes a layout resource ID as the first argument. That means you can pass any layout there, including your own. The solution therefore is to write your own layout and pass it here.
If you want to know how the stock one's implemented, have a look here.
Alternatively, you could retrieve a reference to the view and change its background color manually (or even via a style if all these items in your app share the same background color).
By the way, it looks like you're in a list based activity; why not inherit from ListActivity?

A: You need to create custom layout for displaying list rows.
Refer ListView Examples


text:
Q: Have the cursed chests for the "old mill road" and the "cursed bellows" disappeared? I have been trying to get the "old mill road" cursed chest and the cursed bellows. I have rerun both of those areas at least 100 times (literally) In the last month (5/2015) without seeing the chests. Has something changed in a recent update that would prevent those cursed events from loading? Can you only get them in another mode? Or do I just have the worst luck in the world? I have only been running in campaign.

A: Try in adventure mode when you have a bounty for that area, that's how I got it. The problem seems to be that certain cursed chests are only adventure mode based, and have an increase spawn chance when there's a bounty available for that region.


text:
Q: Sum of torques acting on car wheels lets say we have a car parked on a slope and its in balance. There is a torque acting on the wheels pointing down, therefore there needs to be another force which causes a torque pointing up in order to prevent the wheels from rolling. Which force does this job?

A: Static friction on the wheels causes a torque, this torque needs to be reacted upon by something mechanical for the car to remain stationary. This something is the parking brake, or the park pawl which locks the gears when shifting into park (P position).
Static friction is necessary to balance out the component of weight that is along the ramp. Without it, the car would slide downhill, and without the torque reaction the car would roll donwhill.


text:
Q: Is CruiseControl.NET a Security Risk for Open Source Projects? I am learning about CruiseControl.NET to implement continuous integration into my open source project. It looks like CruiseControl.NET will have to run on my personal computer, and it will build and execute new revisions automatically and immediately! It does not look like it would take a rocket scientist to hack a CruiseControl.NET server. Is it unsafe to use, or are there methods of securing it? For example, a super sandbox.

A: Generally, you can set up a master branch that you have commit access to and merge changes into that branch from others, so you can review code before commiting. Then give trusted members commit access to that branch to delegate code review before it reaches your testing branch.
You could probably (depending on the execution environment) also set up an execution jail to prevent rogue code from accessing restricted resources. Also, running tests as a restricted user helps.
So, my answer would be no, if you understand what's going on and can mitigate such risks.


text:
Q: Getting Error While Creating the superuser in Terminal
AttributeError: 'UserManager' object has no attribute 'create_superuser'

A: You have created "create_superuser" and "create_user" as a functions. Create these functions as methods of UserManager class

A: Your indentations are incorrect.
Add one level of indentation to create_user and create_superuser functions so they belong to the UserManager class


text:
Q: Are infinitesimals, i.e. $dx = ...$, rigorous and correct notation? In many fields of physics and engineering, when we want to describe an infinitesimal, for example, the electric field, we could say $dE(x_i,y_i) = e^{jkr}...dx_0dy_0$
Since derivatives are not fractions, does it still make sense, in a mathematically rigorous way to talk about infinitesimals and would this be the correct notation of describing it? What would be the rigorous way of dealing with infinitesimals?
--Edit--
The history of this question went from "duplicate to an irrelevant question" but once reopened was closed for being "missing context" despite proper english, a clear yes or no question with already great answers (which would be impossible if the question was indecipherable). It seems like those with points have been abusing their powers an incorrectly closing questions that they simply don't like.

A: There are basically two rigorous ways to deal with differentials. One is to treat them as differential forms. This is kind of an algebraic way of doing things, it sets rules for how you can manipulate differentials without trying to describe them as, say, "limits of small differences".
The other way is nonstandard analysis, of which there are at least two incompatible types. One of those is the one from which that name originated, which originally used the idea of a nonstandard model (from model theory) to construct a self-consistent theory containing infinite and infinitesimal "hyperreal" numbers. This originated with Robinson. A different formalism with the same semantics (which is probably easier to understand for non-logicians) was made later by Nelson.
An entirely different semantics arises in smooth infinitesimal analysis. SIA is somewhat alien to "mainstream" mathematicians, because it works in a field which has nonzero nilpotent elements (e.g. $dx \neq 0$ but $(dx)^2=0$). Such a thing is  a contradiction in terms in classical logic, so this subject requires a weaker logic called intuitionistic logic in order to function (and even then $dx \neq 0$ is really "it cannot be proven that $dx=0$", a weaker statement).
Honestly, most mathematicians, scientists, and engineers don't need either one. It is better to learn methods for manipulating differentials in formal (i.e. "regarding only form", which is sort of like "non-rigorous") calculations. Optionally you can also learn proofs in standard analysis (which use finite but arbitrarily small numbers). These never explicitly use differentials.

A: One can deal with infinitesimals properly, although it is far from trivial.
But, more importantly, equalities of the kind $$\tag1 dy=f(x)\,dx$$ are just notation. What I mean is that you never do any algebra nor any other operation with $(1)$: you don't add it, you don't multiply it, you don't take its square root.
So, whether $dy$ and $dx$ in $(1)$ have meaning as objects is irrelevant. One uses an expression as $(1)$ to indicate  a substitution in an integral; and, in an integral, $dx$ and $dy$ are notation and not mathematical objects per se.

A: I join those who would rather call them differentials instead of infinitesimals. While there is a rigorous way of using infinitesimals as they were historically used (say, by Leibniz), I prefer to think in terms of differentials.
The differential of function $f=f(x)=y$ at point $x$, wlog, is the amount of change in (not the function $f$ itself) but in its best linear approximation when the independent variable is given a change $\Delta x$. This is written $df(x)=dy$ and is given by $$df(x)=dy=f'(x)\Delta x.$$ If $f$ is the identity function, then we obtain $df=dx=\Delta x$, so that we usually replace $\Delta x$ with $dx$ in the definition to have $$dy=f'(x)dx.$$ It turns out that this justifies manipulations with differentials as historically practised (and even today by physicists, engineers and differential geometers), so that one has $$dy=\frac{dy}{dx}dx.$$ This is one way to scrupulously practise this use of so-called "infinitesimals".


text:
Q: MVVM : Binding Commands with Collection to Listbox in WPF i have a list box in which there are different controls like button , text box etc in its item template, i have a collection which i bind with listbox, it works fine , but now i want to move my code to MVVM , and i write some commands in my View Model for clicks events of buttons , how can i bind my collection + my commands to list box ??? because commands are not in the collection, this is the Data Template for my list Box
<DataTemplate x:Key="listItemTemplate">
    <Grid ShowGridLines="False">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <DockPanel Grid.Row="0" Name="commentsPanel" LastChildFill="False" MinWidth="350">
            <TextBlock  Name="txtUserName" IsEnabled="False" Text="{Binding UserName}"
                      Width="Auto" DockPanel.Dock="Left" Foreground="GhostWhite" Margin="0,6,0,0"></TextBlock>

            <TextBlock Name="txtDate" IsEnabled="False" Text="{Binding CreateDt}"
                      Width="Auto" DockPanel.Dock="Left" Foreground="Green" Margin="4,6,0,0"></TextBlock>

            <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Width="{Binding EditPanelWidth}" x:Name="EditDeletePanel" Visibility="{Binding ButtonVisibilityText }">
                <Button Name="btnEdit" Content="Edit" Width="Auto" DockPanel.Dock="Right" Height="20"
                  Click="btnEdit_Click_1" Margin="4,4,0,4" Foreground="GhostWhite" VerticalContentAlignment="Top" Visibility="{Binding ButtonVisibilityText}"></Button>

                <Button Name="btnDelete" Content="Delete" Width="Auto" Height="20" VerticalContentAlignment="Top" DockPanel.Dock="Right" Visibility="{Binding ButtonVisibilityText}"
                Click="btnDelete_Click_1" Margin="4"></Button>

            </StackPanel>

            <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" x:Name="SaveCancelPanel" Visibility="{Binding CancelSaveEnableText}">
                <Button Name="btnSave" Content="Save" Width="Auto" Height="20" DockPanel.Dock="Right"
                Click="btnSave_Click_1" Margin="4"></Button>

                <Button Name="btnCancel" Content="Cancel" Height="20" Width="Auto" DockPanel.Dock="Right"
                Click="btnCancel_Click_1" Margin="4"></Button>

            </StackPanel>
        </DockPanel>
        <dxe:TextEdit ShowBorder="False" Grid.Row="1" Name="txtComment" Width="Auto" Foreground="Red"
                  TextWrapping="WrapWithOverflow" EditValue="{Binding Note}" IsEnabled="{Binding IsCommentTextEnable}">

        </dxe:TextEdit>
        <dxe:TextEdit Text=".............." Grid.Row="2" ShowBorder="False" IsEnabled="False">

        </dxe:TextEdit>
    </Grid>
</DataTemplate>

and here is the collection + my commands which i want to bind to buttons ,
public ICommand CancelCommand
{
    get { return _cancelCommand ?? (_cancelCommand = new CommandHandler(Cancel)); }
    set { _cancelCommand = value; }
}

public TList<ProgramNote> NotesCollection
{
    get { return _notes; }
    set
    {
        _notes = value;
        RaisePropertyChanged("NotesCollection");
    }
}

I know i can use this code to bind my commands with button
<Button Command={Binding CancelCommand}

but this command is not present in the collection , i am new in MVVM , kindly help , may be i am missing some little thing to bind my commands , but i am confused that how to add commands in my collection , so that i can get them in my view

A: You can bind the commands to your data template buttons etc by finding the appropriate viewmodel
example
 <DataTemplate x:Key="listItemTemplate">
    <Button Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=LixtBox}}"
            CommandParameter="{Binding}">
 </DataTemplate>

in example we'll find the datacontext of LixtBox which I assume to be your viewmodel then will bind to the command and pass the current object as the command parameter to perform actions on.
you'll then receive the item as parameter in the implementation of your command
public void Execute(object parameter)
{
    ProgramNote note = parameter as ProgramNote;
    //your logic here, eg cancelling download etc.
}

A: Thanx to all of you specially thanx to @Sheridan and @PushPraj, I am able to do it now , here is the code of data template in which i have a button
<Button Name="btnCancel" Content="Cancel" Height="20" Width="Auto" DockPanel.Dock="Right"
                        Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=dxe:ListBoxEdit}}"
                               CommandParameter="{Binding}" Margin="4"></Button>

and this is the code of ListBox
<dxe:ListBoxEdit Name="listComments" Grid.Row="1" ItemTemplate="{StaticResource  listItemTemplate}"
                                                                                ItemsSource="{Binding NotesCollection}"
                                                                     ScrollViewer.HorizontalScrollBarVisibility="Disabled"  ScrollViewer.VerticalScrollBarVisibility="Visible" >
                                                                </dxe:ListBoxEdit>

and lastly this is my back end code
listComments.DataContext = viewModel;

A: It's always difficult to answer new user's questions because they always leave out important information from their questions. However, judging by your question text, it sounds to me like you have set your collection property as the DataContext of your Window. If you want to data bind to your commands instead, then you'll need to change the DataContext to the object that contains both the collection and the commands... an instance of your view model:
DataContext = new YouViewModel();

Now that the DataContext is set to an instance of your view model, you can data bind to its properties as you showed us:
<Button Command="{Binding CancelCommand}" />

...
<ListBox ItemsSource="{Binding NotesCollection}" />

Ahhh, sorry I misunderstood - so your Button is inside the ListBox. In that case, you could try something like this:
<Button Command="{Binding DataContext.CancelCommand,
    RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

This should reach out of the scope of the collection, looking in the DataContext of a Window, so if you have set the instance of your view model to the Window.DataContext, this should work.


text:
Q: TensorFlow and person recognition in video stream I'd like to make app for recognition persons in video stream using tensorflow or keras.
What kind of neural network can i use? CNN or RNN? Shoud i analyze freame one by one or video stream as a whole? Any good source to learn?

A: This is a very large question. And a hard task.
I think, the easy way is to extract one frame by second if the source is a video stream.
Then use OpenCV to make a face detection.
Once you got the faces, feed a NN for recognitions.
Some links for face recognition in Deep Learning:
https://aboveintelligent.com/face-recognition-with-keras-and-opencv-2baf2a83b799
https://github.com/rajathkumarmp/FaceRecog-Keras/blob/master/faceRecog.ipynb


text:
Q: Why iam getting this "UNDEFINED VARIABLE" error in php i am very new in php, iam trying to figure it out why iam getting this error
Notice: Undefined variable: rowcount in C:\laragon\www\project1\index.php on line 19
The database connection is successful
the php code is this
<?php

$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
$rowCount = mysqli_num_rows($result);

if ($rowcount > 0){
    while($row = mysqli_fetch_assoc($result)){
        echo $row['username']. "<br>";
    }
}
else {
    echo "no results found";
}

?>


text:
Q: What happens if I pull the plug of an iSCSI device? If I pull the network connector of an iSCSI device, what happens? Will the "client" automatically connect again if I plug it in again? Is there a timeout?
(in my case I'm talking about a QNAP NAS which provides the iSCSI disk and a Ubuntu Server which mounts it)

A: If the network connection dies, the iSCSI initiator will start to see time-outs due to not being able to contact the target. After a certain amount of time, the OS will start to see reads from the disk timing out and cached writes fail to be flushed to the disk. The timeout period where the initiator notices an issue and passes it back up to the SCSI queue is configurable - see http://www.open-iscsi.org/docs/README for the open-iscsi (section 8.1.1).
I believe most initiators will attempt to reconnect to devices that have previously been unreachable. There was an option in Microsoft's s/w initiator to allow a 'non-persistent' connection, but I never really found that particularly useful.


text:
Q: R.NET vs R.NET.Community in NuGet Can anyone tell me the difference between R.NET and R.NET.Community in the NuGET package manager?  They both reference http://rdotnet.codeplex.com/ as their Project URL.
The old project page says:

R.NET is now distributed via R.NET.Community on NuGet

does this mean that the R.NET package is obsolete and should not be installed?
I'm working on a project that has both R.NET 1.5.5 and R.NET.Community 1.6.5 installed. Is it safe to remove R.NET and everything should still work?

A: You are correct - R.NET was replaced by R.NET.Community:

Note that you must uninstall packages dependencies or R.NET 1.5.5 or earlier, if pre-existing. R.NET 1.5.13 uses a different package identifier: R.NET.Community

It's also worth noting that, at the time of writing, R.NET development seems to have stalled, with the last commit being in August 2015. The issue/bug list however is growing.


text:
Q: How to optimize code written in phaser.js (Break into functions and remove unnecessary animation calls) I have some code written in phaser.js and I need to optimize it, i.e. break it down into functions and remove unnecessary animation calls (the code is completely working, but it just needs to be optimized). I'm just new to js and this library :(
I tried it myself, but then the code stops working for me :(
class Example extends Phaser.Scene {
  constructor() {
    super();
  }

  preload() {
    this.load.spritesheet("start", "img/bri_big_anim_start.png", {
      frameWidth: 392,
      frameHeight: 370,
    });
    this.load.spritesheet("middle", "img/bri_big_anim_middle.png", {
      frameWidth: 450,
      frameHeight: 430,
    });
    this.load.spritesheet("finish", "img/bri_big_anim_finish.png", {
      frameWidth: 326,
      frameHeight: 335,
    });
  }

  create() {
    const startAnimation = this.anims.create({
      key: "walkStart",
      frames: this.anims.generateFrameNumbers("start", { start: 0, end: 4 }),
      frameRate: 4,
    });

    let middleAnimation = this.anims.create({
      key: "walkMiddle",
      frames: this.anims.generateFrameNumbers("middle", { start: 0, end: 4 }),
      frameRate: 4,
    });

    const finishAnimation = this.anims.create({
      key: "walkFinish",
      frames: this.anims.generateFrameNumbers("finish", { start: 0, end: 4 }),
      frameRate: 4,
    });

    const spriteStart = this.add.sprite(400, 350, "start").setScale(0.4);

    spriteStart.play({ key: "walkStart", repeat: 1 });

    this.tweens.add({
      targets: spriteStart,
      y: 360,
      scaleX: 0.9,
      scaleY: 0.9,
      duration: 2000,
    });

    spriteStart.on(
      "animationcomplete",
      function () {
        spriteStart.destroy();

        let spriteMiddle = this.add.sprite(400, 350, "middle").setScale(0.8);
        spriteMiddle.play({ key: "walkMiddle", repeat: 3 });

        this.tweens.add({
          targets: spriteMiddle,
        });

        spriteMiddle.on(
          "animationcomplete",
          function () {
            spriteMiddle.destroy();

            const spriteFinish = this.add
              .sprite(400, 350, "finish")
              .setScale(0.8);
            spriteFinish.play({ key: "walkFinish", repeat: 1 });

            this.tweens.add({
              targets: spriteFinish,
              y: 100,
              x: 300,
              scale: 0.1,
              duration: 2000,
            });

            spriteFinish.on(
              "animationcomplete",
              function () {
                spriteFinish.destroy();

                let middleAnimation = this.anims.create({
                  frames: this.anims.generateFrameNumbers("middle", {
                    start: 0,
                    end: 1,
                  }),
                  frameRate: 1,
                });

                spriteMiddle = this.add
                  .sprite(300, 100, "middle")
                  .setScale(0.1);
                spriteMiddle.play({ key: "walkMiddle", repeat: 0 });

                this.tweens.add({
                  targets: spriteMiddle,
                });
                spriteMiddle.stop();
              },
              this,
            );
          },
          this,
        );
      },
      this,
    );
  }
}

const config = {
  type: Phaser.AUTO,
  parent: "phaser-example",
  width: 800,
  height: 600,
  pixelArt: true,
  scene: [Example],
};

const game = new Phaser.Game(config);

Everything I could do

class Example extends Phaser.Scene
{
    constructor ()
    {
        super();
    }

    preload ()
    {
        this.load.spritesheet('start', 'img/bri_big_anim_start.png', { frameWidth: 392, frameHeight: 370 });
        this.load.spritesheet('middle', 'img/bri_big_anim_middle.png', { frameWidth: 450, frameHeight: 430 });
        this.load.spritesheet('finish', 'img/bri_big_anim_finish.png', { frameWidth: 326, frameHeight: 335 });
    }

    create ()
    {
        const startAnimation = this.anims.create({
            key: 'walkStart',
            frames: this.anims.generateFrameNumbers('start', {start: 0, end: 4}),
            frameRate: 4,
        });

        let middleAnimation = this.anims.create({
            key: 'walkMiddle',
            frames: this.anims.generateFrameNumbers('middle', {start: 0, end: 4}),
            frameRate: 4,
        });

        const finishAnimation = this.anims.create({
            key: 'walkFinish',
            frames: this.anims.generateFrameNumbers('finish', {start: 0, end: 4}),
            frameRate: 4,
        });

        const addSprite = (nameSpritePlay, keyPlay, repeatPlay) => {
            nameSpritePlay.play({ key: keyPlay, repeat: repeatPlay });
        }

        const spriteStart = this.add.sprite(400, 350, 'start').setScale(0.4);

        // spriteStart.play({ key: 'walkStart', repeat: 1 });
         addSprite(spriteStart, 'walkStart', 1);

        this.tweens.add({
            targets: spriteStart,
            y: 360,
            scaleX: 0.9,
            scaleY: 0.9,
            duration: 2000,

        });

        spriteStart.on('animationcomplete', function () {
            spriteStart.destroy();

            let spriteMiddle = this.add.sprite(400, 350, 'middle').setScale(0.8);
            // spriteMiddle.play({ key: 'walkMiddle', repeat: 3 });
            addSprite(spriteMiddle, 'walkMiddle', 3);

            this.tweens.add({
                targets: spriteMiddle,

            });

            spriteMiddle.on('animationcomplete', function () {
                spriteMiddle.destroy();

                const spriteFinish = this.add.sprite(400, 350, 'finish').setScale(0.8);
                // spriteFinish.play({ key: 'walkFinish', repeat: 1 });
                addSprite(spriteFinish, 'walkFinish', 1);

                this.tweens.add({
                    targets: spriteFinish,
                    y: 100,
                    x: 300,
                    scale: 0.1,
                    duration: 2000,

                });

                spriteFinish.on('animationcomplete', function () {
                    spriteFinish.destroy();

                    spriteMiddle = this.add.sprite(300, 100, 'middle').setScale(0.1);
                    // spriteMiddle.play({ key: 'walkMiddle', repeat: 0 });
                    addSprite(spriteMiddle, 'walkMiddle', 0);

                    spriteMiddle.stop();

                }, this);

            }, this);

        }, this);

    }
}

const config = {
    type: Phaser.AUTO,
    parent: 'phaser-example',
    width: 800,
    height: 600,
    pixelArt: true,
    scene: [ Example ]
};

const game = new Phaser.Game(config);

A: Optimizie Code can take long, but I would say you could look into the example below, how to chain animations, this would minimize your code, with builtin phaser functionality:
https://phaser.io/examples/v3/view/animation/chained-animation#
the main idea is the playAfterRepeat function
sprite.playAfterRepeat(...);

Here a link to the documentation of this feature.
I personally would load animations from an atlas/json file as seen in this example: https://phaser.io/examples/v3/view/animation/from-animation-json
this keeps the code clean streamlined, and animations can be changed/managed with greater ease.
Or maybe create a helper function like this (but this is just my preference):
generateFrames(key, name){
    let animation = this.anims.create({
        key: key,
        frames: this.anims.generateFrameNumbers(name, { start: 0, end: 4 }),
        frameRate: 4,
    });
    return animation;
}
 ...
 const startAnimation = generateFrames('walkStart', 'start');
 const middleAnimation = generateFrames('walkMiddle', 'middle');
 const finishAnimation = generateFrames('walkFinish', 'finish');


text:
Q: java how to simulate node.js req.send and req.query I have a code for a web service in node.js and I want to do the same in java
This is the code in node js
app.get('/webhook', function(req, res) {

    res.status(200).send(req.query['hub.challenge']);

});

I want to make a similar on in java.
so my question what is req.query[] represents? is it a value for a

*

*Query string

*Form string

*Other body values?

and what happens when sending by send function? it is a value in the body?
Update
i can see that req.query is a query parameter, but why there's dot ? how to receive it with dot? i can receive query parameters without dot, but with dot i am not able

A: The example code you have is getting a query parameter from a URL like http://example.org/webhook?hub.challenge=foo; since Javascript uses dots to separate attributes, you cannot use req.query.hub.challenge, because there is no hub query parameter. The bracket notation is looking up a literal hub.challenge attribute name.
For more information on the nodejs objects, here's a link to documentation.
For your question on send, the nodejs code is telling the response object to send an HTTP 200 (aka OK) response, with the body containing the value of the hub.challenge query parameter. In the example URL, that would mean the response body would be foo.


text: Q: NTLK - Classifying Noun as a Location I'm trying to use the NTLK to classify a noun as being a location. I realize this might be done with Named Entity Recognition, but that seems to apply to proper nouns in the context of a block of text. Is there a dataset I can check a noun against to see if it refers to a person, place, or thing? For example, I would like similar to 'facility', 'building',  and 'town' to be classified as a location (alternatively as a thing).


text:
Q: Combining paste and cat in unix I have files with this name format:
<name1>.<name2>.<id>.ERR

where name1 and name2 are character strings and id is a number and all three are unique to each file. (these are standard output files from a slurm run,  and id is the job id).
I want to find out if these jobs failed so I was thinking of cut'ing id from each file name:
ls -1 *.ERR | cut -d "." -f 3

And then pasting "sacct -j " in front of it.
Is there a one liner that achieves this so that it runs:
sacct -j id1
sacct -j id2
.
.

sacct -j idn

A: Something like:
for id in $(ls *.ERR | cut -d "." -f 3); do echo "machine: $id"; done

will work, if the files are not a lot (thousands). Replace echo blah blah with sacct -j, like this:
for id in $(ls *.ERR | cut -d "." -f 3); do sacct -j $id; done

There are other ways too.

A: You can simply use xargs:
ls -1 *.ERR | cut -d "." -f 3 | xargs -L 1 sacct -j

which you can run in parallel with the -P option to alleviate a bit the latency from interrogating the database.
ls -1 *.ERR | cut -d "." -f 3 | barges -P 4 -L 1 sacct -j


text:
Q: Add columns to pyspark dataframe if not exists I have a spark dataframe and I want to add few columns if doesn't already exists.
df1:
id Name age
1  Abc  20
2  def  30

I want to check if columns are not already exists in df and if doesn't exist add columns: 'gender','city','contact' to df1 and populate null values in them and finally obtain:
df1:
id Name age gender city contact
1  Abc  20
2  def  30

A: You can do like below,
from pyspark import Row
from pyspark.sql import functions as F
row = Row('id', 'Name', 'age', 'gender')
row_df = spark.createDataFrame(
    [row(1, 'Test', '12', 'Male'), row(2, 'Test2', '15', 'Female')])
row_df.show()

if 'gender' not in row_df.columns:
    row_df = row_df.withColumn('gender', F.lit(None))
if 'city' not in row_df.columns:
    row_df = row_df.withColumn('city', F.lit(None))
if 'contact' not in row_df.columns:
    row_df = row_df.withColumn('contact', F.lit(None))

row_df.show()

Output:
+---+-----+---+------+
| id| Name|age|gender|
+---+-----+---+------+
|  1| Test| 12|  Male|
|  2|Test2| 15|Female|
+---+-----+---+------+

+---+-----+---+------+----+-------+
| id| Name|age|gender|city|contact|
+---+-----+---+------+----+-------+
|  1| Test| 12|  Male|null|   null|
|  2|Test2| 15|Female|null|   null|
+---+-----+---+------+----+-------+


text:
Q: Golang: append file to an existing tar archive How would I append a file to an existing tar archive in Go?  I don't see anything obvious in the docs on how to do it.
I have a tar file that has already been created and I want to add more to it after it has already been closed.
EDIT
Altering the example in the docs and following the answer given, I'm still not getting the expected result.  The first three files are being written to the tar but when I close and open up the file again to write to it, the new file is never being written.  The code runs fine. I don't know what I'm missing.
The following code gives me a tar file with three files in it: readme.txt, gopher.txt, todo.txt.  foo.bar never gets written.
package main

import (
    "archive/tar"
    "log"
    "os"
)

func main() {
    f, err := os.Create("/home/jeff/Desktop/test.tar")
    if err != nil {
        log.Fatalln(err)
    }

    tw := tar.NewWriter(f)

    var files = []struct {
        Name, Body string
    }{
        {"readme.txt", "This archive contains some text files."},
        {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
        {"todo.txt", "Get animal handling licence."},
    }
    for _, file := range files {
        hdr := &tar.Header{
            Name: file.Name,
            Size: int64(len(file.Body)),
        }
        if err := tw.WriteHeader(hdr); err != nil {
            log.Fatalln(err)
        }
        if _, err := tw.Write([]byte(file.Body)); err != nil {
            log.Fatalln(err)
        }
    }
    if err := tw.Close(); err != nil {
        log.Fatalln(err)
    }
    f.Close()

    // Open up the file and append more things to it

    f, err = os.OpenFile("/home/jeff/Desktop/test.tar", os.O_APPEND|os.O_WRONLY, os.ModePerm)
    if err != nil {
        log.Fatalln(err)
    }
    tw = tar.NewWriter(f)

    test := "this is a test"

    hdr := &tar.Header{
        Name: "foo.bar",
        Size: int64(len(test)),
    }

    if err := tw.WriteHeader(hdr); err != nil {
        log.Fatalln(err)
    }

    if _, err := tw.Write([]byte(test)); err != nil {
        log.Fatalln(err)
    }

    if err := tw.Close(); err != nil {
        log.Fatalln(err)
    }
    f.Close()

}

A: It's just a writer interface so write bytes to it after writing your files header.
import (
  "archive/tar"
  "os"
)

f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, os.ModePerm)
if err != nil {
// handle error here
}

hdr := tar.Header{}
// populate your header
tw := tar.NewWriter(f)
// append a file
tw.WriteHeader(hdr)
tw.Write(content_of_file_as_bytes)

http://golang.org/pkg/archive/tar/#Writer tells you all you need to know.
EDIT: It turns out that tar files get a trailer written to the end when it's closed. So even though you are writing new data to the tar archive it won't be read past that trailer. So instead it looks like you'll have to read in the tar archive first and then rewrite the whole archive to disk which is suboptimal. The package doesn't support the necessary stuff to append to them though so that's the best I can recommend right now.

A: The tar file specification states:

A tar archive consists of a series of 512-byte records.  Each file system
         object requires a header record which stores basic metadata (pathname,
         owner, permissions, etc.) and zero or more records containing any file
         data.  The end of the archive is indicated by two records consisting
         entirely of zero bytes.

The Go implementation of adding these two zero filled records happens here .
To get around the tar file format trailer (basically 1024 bytes of nothing) you could replace the lines:
f, err = os.OpenFile("/home/jeff/Desktop/test.tar", os.O_APPEND|os.O_WRONLY, os.ModePerm)
if err != nil {
    log.Fatalln(err)
}
tw = tar.NewWriter(f)

With:
f, err = os.OpenFile("/home/jeff/Desktop/test.tar", os.O_RDWR, os.ModePerm)
if err != nil {
    log.Fatalln(err)
}
if _, err = f.Seek(-1024, os.SEEK_END); err != nil {
    log.Fatalln(err)
}
tw = tar.NewWriter(f)

It opens the file read / write (instead of append / write-only) and then seeks to 1024 bytes before the end of the file and writes from there.
It works, but it is a horrible hack.
EDIT: After understanding the tar file spec a little better, I no longer believe this is such a hack.
Full code: http://play.golang.org/p/0zRScmY4AC

A: I found the accepted solution by @Intermernet to be basically correct, except that the padding at the end of an archive is generally arbitrary (unless you control the writer too).
This works for me as far as I can tell so far:
var lastFileSize, lastStreamPos int64
tr := tar.NewReader(output)
for {
    hdr, err := tr.Next()
    if err == io.EOF {
        break
    }
    if err != nil {
        return err
    }
    lastStreamPos, err = output.Seek(0, io.SeekCurrent)
    if err != nil {
        return err
    }
    lastFileSize = hdr.Size
}

const blockSize = 512
newOffset := lastStreamPos + lastFileSize
newOffset += blockSize - (newOffset % blockSize) // shift to next-nearest block boundary
_, err := output.Seek(newOffset, io.SeekStart)
if err != nil {
    return err
}

tw := tar.NewWriter(output)
defer tw.Close()

// ... proceed to write to tw as usual ...

I'm not 100% sure why this works. But the basic idea is to scan the archive, find the offset of the start of the last file, then skip over it, then align to the nearest block boundary, then start overwriting from there.


text:
Q: ConfigService returning String Value even after parsing So, here is my NEST JS Basic App.
./shared/utils/config/index.ts
export default  () => ({
   PORT: parseInt(process.env.PORT, 10) || 3000,
   TO_PRINT_RESPONSE: JSON.parse(process.env.TO_PRINT_RESPONSE),
});

app.module.ts
import CONFIG from './shared/utils/config/';
@Module({
      imports: [
        ConfigModule.forRoot({
          isGlobal: true,
          load: [ CONFIG ],
        })
      ]
      // some more Module Decorator Config
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
      consumer
        .apply(AuthMiddleware)
        .forRoutes({ path: '/someurl', method: RequestMethod.ALL });
      // some more configuration code.
  }
}

main.ts
// AppModule is app.module.ts imported variable
import { ConfigService } from '@nestjs/config';

async function bootstrap() {
    const app: INestApplication = await NestFactory.create(AppModule, {
       logger: console,
    });

    const configService = app.get(ConfigService);
    console.log(typeof configService.get<Boolean>('TO_PRINT_RESPONSE'));

    /* this is coming as String even when:
     * 1. I place <Boolean> as a type (I know its of no use, since it does not change the datatype)
     * 2. But in config/index.ts I parsed it in BOOLEAN using JSON.parse()
     */
}
bootstrap();

.env
 PORT=5000
 TO_PRINT_RESPONSE=true

Now:

*

*.env is getting loaded via dotenv module as written (https://docs.nestjs.com/techniques/configuration)

*Kept debug inside ./shared/utils/config/index.ts and it is getting hit.

So, may someone please tell me, where am I doing wrong in reading the ENV value in proper datatype, when I loaded the JSON in proper format (./shared/utils/config/index.ts).
Thanks & Happy Coding :)

A: The problem is that Nest's ConfigService will not override the values it has read from the environment, hence their types will always default to string.
What you can do, however, is to assign the parsed values to different properties in your config-factory:
export default  () => ({
   port: parseInt(process.env.PORT, 10) || 3000,
   toPrintResponse: JSON.parse(process.env.TO_PRINT_RESPONSE),
});

If you then access those values, the types will be correct:
console.log(typeof configService.get('toPrintResponse')); // prints boolean
console.log(typeof configService.get('port')); // prints number


text:
Q: Can't get mediarecorder to record at a high samplerate For a project i need to make an android app to record the sound amplitude at a high sample rate (10 samples per millisecond for instance)
For some reason the output of the app only gives back a sample every 10 milliseconds or less.
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioEncodingBitRate(128000);
mediaRecorder.setAudioSamplingRate(96000);
mediaRecorder.setOutputFile(AudioSavePathInDevice);

I determined that by storing my timing and ampltitude data.
I stored my Amplitude data and my Timedata
final Runnable updateSoundLevel = new Runnable() {
@Override
public void run() {
    if (SoundRecording==true){
    handler.postDelayed(this, 0);

    Amplitude = mediaRecorder.getMaxAmplitude();
    longTime= (System.nanoTime()-startTime)/1000000;
    int intTime=(int) longTime;
    listAmplitude.add(Amplitude);
    listTime.add(intTime);
    addEntry(intTime,Amplitude); // adding entry to graph
    ... rest of program

A: I found the error,
The process to add an entry to my graph was too long.


text:
Q: Trying to compare and get the results from a loop in easy68k I am trying to iterate an array and find numbers less than, equal to, and more than to be stored. I want to store the count in the three results and if possible display the result
    ORG     $1000

    START:  ORG $2000                ; first instruction of program
        LEA DATA,A0
        MOVE.B #9,D0
        CLR.B D1
        CLR.B D2
        CLR.B D3

    LOOP:   MOVE.B (A0)+,D4
        CMP.B #50,D4
        BGT GRT_50
        BLT LESS_50
        BEQ EQ2
        LOOP

    GRT_50: ADD.B #1,D3
        BNE LOOP

   LESS_50: ADD.B #1,D01
        BNE LOOP

    GRT_50: ADD.B #1,D2
        BNE LOOP
        STOP    #2000

* Put variables and constants here
     ORG        $2000
DATA    DC.B    $55,$10,$20,$30,$40,$50,$60,$65,$70,$80
RESULT1 DC.B    $0
RESULT2 DC.B    $0
RESULT3 DC.B    $0
END    START   ; last line of source

A: Okay, let's take a look at some of the mistakes here:

*

*Only one ORG statement at a time. Start with Org $1000 or $2000 but not both. Just make sure to use an adress for data that won't overlap to avoid overwriting stuff.

*Use DBRA D0,LOOP to loop (in this case 10 times) to the LOOP label.

*Use BRA LOOP instead of BNE LOOP, as BNE is a conditional jump.

*MOVE #9,D0 without the .b to use it correctly with DBRA, because DBRA uses a wordsized counter. When you just write .b you can't be sure what the upper 8 bits of the word happen to be.

*At BEQ EQ2 you try to jump to the label EQ2, but there is no such.

*There is no D01 Register, use ADD #1,D1. As already mentioned.

And some notes:

*

*I would skip the .b at "CLR.B" and "ADD.B" as it unnessesarily shrinks the counting variables from word to byte size. Note that the 68k can work with byte, word and long size, and defaults to word-size most of the time.

*As you use Hex Numbers in the data field, i think you want to compare it to Hex 50 (CMP #$50,D4) instead of decimal 50.

*The adresses $1100 and $1110 in my example code are arbitrary. In Easy68k they can nicely be observed in the memory window.

Many of these have already been stated in the comments, but I'm trying to summarize everything here.
There is still room for improvement, but I'd maybe write it like this:
    ORG    $1000
START:
    LEA DATA,A0     ;set A0 to data adress
    MOVE #10-1,D0   ;setup for 10 iterations
LOOP:
    MOVE.B (A0)+,D1 ;fetch byte
    CMP.B #$50,D1   ;compare
    BGT GRT_50      ;and branch conditionally
    BLT LESS_50
    BEQ EQUAL_50
CONT:
    DBRA D0, LOOP   ;come back here to loop
    SIMHALT         ;stop

GRT_50:
    ADD #1, RESULT_G
    BRA CONT
LESS_50:
    ADD #1, RESULT_L
    BRA CONT
EQUAL_50:
    ADD #1, RESULT_E
    BRA CONT

* data and vars

    ORG $1100
DATA      DC.B    $55,$10,$20,$30,$40,$50,$60,$65,$70,$80
    ORG $1110
RESULT_G  DC.W    $0
RESULT_L  DC.W    $0
RESULT_E  DC.W    $0
    END      Start


text:
Q: Create Conditionally Incrementing Value - SQL Server I have a table with a list of consecutive dates. The table also has a Day Type field consisting: Business Day (B), Saturday (X), Sunday (Y) & Holiday(H)
I want to add an additional column which has an incrementing number.
The number should only increment if:

*

*It is the first day in the list and it is a business day.

*The previous day was a business day.

Desired Result:
DATE         DAY_TYPE   NUMBER
2017-03-09   B          1
2017-03-10   B          2
2017-03-11   X          3
2017-03-12   Y          3
2017-03-13   H          3
2017-03-14   B          3
2017-03-15   B          4
2017-03-16   H          5
2017-03-17   B          5

A: You can do this using a recursive common table expression
DECLARE @sample TABLE ( [date] DATE, day_type CHAR(1))
INSERT @sample
( [date], day_type )
VALUES
('2017-03-09','B')
,('2017-03-10','B')
,('2017-03-11','X')
,('2017-03-12','Y')
,('2017-03-13','H')
,('2017-03-14','B')
,('2017-03-15','B')
,('2017-03-16','H')
,('2017-03-17','B')

;WITH cteSample
AS(
SELECT
      ROW_NUMBER()OVER(ORDER BY [S].[date]) 'RN'
    , S.[date]
    , S.day_type
FROM @sample S
),cteRecursive
AS(
    SELECT
        b.RN, b.[date], b.day_type, 1 'Number'
    FROM
        cteSample b
    WHERE
        b.RN = 1 AND b.day_type = 'B'
    UNION ALL
    SELECT
         e.RN, e.[date], e.day_type
        ,CASE WHEN ( e.day_type IN ('B') AND r.day_type IN ('B') OR e.day_type NOT IN ('B') AND r.day_type IN ('B') )
             THEN r.Number + 1 ELSE r.Number END
    FROM
        cteSample  e
    INNER JOIN
        cteRecursive r ON e.RN = r.rn + 1
    )
SELECT * FROM cteRecursive


text:
Q: Google chrome Developer Tools & 'known' exception My developer tools session pauses while the page load. I see it happens while loading jquery and angular.js. I don't see any error afterwards.  See the secreenshot (stack) below.

It is look like this is just a check for sizzle.js. Should I concern?

Looks like it is looking for locale module.
If these errors are ok, how can I bypass these two errors in Developer Tools as I had to resume every time the page reloads.

A: There is a pause on exception disable feature.
https://developers.google.com/chrome-developer-tools/docs/scripts-breakpoints#js_exceptions


text:
Q: Data is gone when sort or searched using Data Table jQuery I really need your help here. I am new with jQuery DataTable. What I am doing is, I have a url (backend laravel php) that returns a JSON response like so:
[
{"kode_pt":1,"nama":"title","SK_path":"\/folder","email_PJ":"\/images","validasi":0},
{"kode_pt":2,"nama":"title","SK_path":"\/folder","email_PJ":"\/images","validasi":0}
]

What I am doing currently is using ajax jquery to GET the data, and add it to the table dynamically. Like this:
  var content="";
  $.ajax({
    url: '{{route('get.pt')}}',
    method: "GET",
    dataType: "json",
    success: function(data){
      for(i=0; i<data.length; i++){
        content+='
'+
          ''+data[i].kode_pt+'	'+
          ''+data[i].nama+'	'+
          ''+data[i].validasi+'	'
          +'<button id="accept" data-id='+data[i].kode_pt+' class="btn btn-success">Accept</button><button data-id='+data[i].kode_pt+' class="btn btn-danger">Decline</button><button id="view" data-id='+data[i].kode_pt+' class="btn btn-info">View</button>	';
      }

  $("#verify-pt-body").html(content);
},
error: function(){
  console.log("Ajax Error - getPT");
}
  });

It works. But when I use the sort and search functionality of data table, the data shown onscreen disappears. After browsing, it turns out I cannot apply it to the table like that. I have to use the DataTable's functions to retrieve the json. I need help with that please. I have looked at few documentations but I have failed to get it working. Help would be much appreciated!!
Syntax of data tables I tried but failed:
$('#dataTable-verify-pt').DataTable({
    responsive: true,
    ajax:{
      url: '//route('get.pt')}}'
    },
    columns:[
      {data: "kode_pt"},
      {data: "nama"},
      {data: "validasi"},

    ]

  });

This is the format I'm trying to achieve with DataTable:


text:
Q: Ошибка при увеличении сайта При увеличении сайта появляются повторение заднего фона

Вот css код что отвечает за фон
body
{
    background: linear-gradient(to left top, rgb(0, 184, 212, 0.9), rgb(29, 233, 182, 0.9)), url(../img/Color_Fill_1.png) 0 0/100% 100% no-repeat;
    max-height: 750px;
    opacity: 0.9;
}

Кто знает как убрать? Спасибо.

A: У вас задний фон повторяется. Чтобы такое не случилось пишите:
body
{
    background-repeat: no-repeat;
    background-size: 100%;
}


text:
Q: what is meant by Business,System,Interface,Persistence classes? what is meant by Business,System,Interface,Persistence classes? Explain me with some examples?

A: Business could be the part of your application where all the functional part happens (ie computations or rules)
System is your OS
Interface, thats a contract in Java POO -> see java for beginners and stuff like that
Persistence is the part of your application where all the database communication part happens (ie sql requests)

A: *

*Business: the core part of an application, usually called the business layer. It's what differentiates one application from another. For example if you have an application which performs accounting stuff, the business layer would contain classes like Account or EndOfMonthJob. That's called the business, in contrast to technical logging or the login form, which are not part of the business layer. Perhaps a better term would be Domain-specific components

*System: This is either as simple as the underlying software system (such as the operating system or an application server) or the software you're building or the system as a whole, which might also reference to complex set ups like a cloud hosting environment with all the hardware included. The term 'system' is too generic, but it usually is either the OS or the software system you're building.

*Interface: An interface is either a technical interface definition for interoperability (either within the same software, see Java interfaces) or interfaces for remote systems (see WebService interfaces), which can be seen as a contract between two units - or an interface is a Human-Machine-Interface (also known as User Interface, Graphical User Interface), which is just the frontend of an application so a human being (aka user) can see and use it.

*Persistence: Whenever an application has to keep state between runs, it needs to store its state (e.g. the data a user has entered) somewhere, so it can load it on the next run. The persistence layer of an application contains modules to deal with persisting the state of an application, most often the domain objects, to storages. Such storages are often database systems, but they can also be specialized storages or very simple ones like .ini files, .xml files or the registry (although i would not consider this to be 'persistence'). In case of enterprise applications, the term Data Access Layer is a synonym for Persistence Layer


text:
Q: UINavigationBar missing from UITableView I'm presenting a UITableView modally to provide access to some application settings. When the modal view (root view controller) appears, it has a navigation bar like I expect. However, when one of the options is selected and the next 'UITableView` is popped to the top of the stack, there's no navigation bar.

Here's what one of the child UITableViews looks like:

As far as I know, the two children views should have navigation bars without me having to do anything because they're embedded in a UINavigationController.
I tried dragging a navigation bar to the views but IB will only let me put them inside the UITableView and if I do that, they do appear, but they also go too high in the view and run into the status bar and I can set any layout constraints on them to fix this.
I've scoured the Apple documentation with no luck and found many thread on SO that very, very old and in objective-C.
Can I make these views work together like I'd expect them to or am I going to have to build the child views from scratch?
UPDATE: I'm still trying to get this to work. I've now tried to create a new view controller from scratch. Here's what the view hierarchy looks like:

And you can see in the Storyboard something's not right:

And when I run this in the simulator, I get a new error:
"[UITableViewController loadView] instantiated view controller with identifier "UIViewController-cDg-wV-aMN" from storyboard "Main", but didn't get a UITableView.' But I created the segue by Ctrl-dragging from the cell in the root VC directly to the Table View.
To sum this all up, here's the flow I'm trying to achieve: UIViewController (initial VC) -> UINavigationController (presented modally from the bottom) -> UITableViewController (presented from right to left and with standard navigation bar).
My segues are all set to Show (e.g. Push)
Any help or suggestions would really be appreciated.

A: Well, I figured out how to fix the problem I was having after coming across another thread that wasn't about the same problem, but it had some advice that tipped me off.
The problem was caused by me creating the segues from the UITableViewCell on my Settings view controller to each of the child UITableViewControllers.
To fix the problem, I simply created the segues between the Settings UITableViewController and each of the child UITableViewControllers.
Hope this helps somebody else someday.


text:
Q: http.post not sending the request to local iis I am trying to post data from client to local server using local iis server. But it is not sending the request to server not showing any error.
Here is the request:
let url = 'http://localhost/TestApp.Web.Api/api/user';
        let body = JSON.stringify({user});
        let headers = new Headers({'Content-Type': 'application/json' });
        let options = new RequestOptions({headers:headers});
        this.http.post(url,body,options)
                    .map(this.extractData)
                    .catch(this.handleError);

And here extractData method which I am using to get the data from response:
private extractData(res:Response){
        let body = res.json();
        console.log(body.data);
        return body.data || { };
    }

Any suggestion.

A: You have to subscribe to the result for the request to be made. Like this:
        this.http.post(url,body,options)
                    .map(this.extractData)
                    .catch(this.handleError)
                    .subscribe();

The http methods return cold observables, meaning they are lazy and will not execute unless something subscribes to them.


text:
Q: How can I override an EJB 3 session bean method with a generic argument - if possible at all? Suppose you have the following EJB 3 interfaces/classes:
public interface Repository<E>
{
   public void delete(E entity);
}

public abstract class AbstractRepository<E>  implements Repository<E>
{
   public void delete(E entity){
      //...
   }
}

public interface FooRepository<Foo>
{
   //other methods
}

@Local(FooRepository.class)
@Stateless
public class FooRepositoryImpl extends
    AbstractRepository<Foo> implements FooRepository
{
   @Override
   public void delete(Foo entity){
      //do something before deleting the entity
      super.delete(entity);
   }
   //other methods
}

And then another bean that accesses the FooRepository bean :
//...
@EJB
private FooRepository fooRepository;

public void someMethod(Foo foo)
{
    fooRepository.delete(foo);
}
//...

However, the overriding method is never executed when the delete method of the FooRepository bean is called. Instead, only the implementation of the delete method that is defined in AbstractRepository is executed.
What am I doing wrong or is it simply a limitation of Java/EJB 3 that generics and inheritance don't play well together yet ?

A: I tried it with a pojo and it seems to work. I had to modify your code a bit.
I think your interfaces were a bit off, but I'm not sure.
I assumed "Foo" was a concrete type, but if not I can do some more testing for you.
I just wrote a main method to test this.
I hope this helps!
public static void main(String[] args){
        FooRepository fooRepository = new FooRepositoryImpl();
        fooRepository.delete(new Foo("Bar"));
}

public class Foo
{
    private String value;

    public Foo(String inValue){
        super();
        value = inValue;
    }
    public String toString(){
        return value;
    }
}

public interface Repository<E>
{
    public void delete(E entity);
}

public interface FooRepository extends Repository<Foo>
{
    //other methods
}

public class AbstractRespository<E> implements Repository<E>
{
    public void delete(E entity){
        System.out.println("Delete-" + entity.toString());
    }
}

public class FooRepositoryImpl extends AbstractRespository<Foo> implements FooRepository
{
     @Override
       public void delete(Foo entity){
          //do something before deleting the entity
            System.out.println("something before");
          super.delete(entity);
       }
}

A: Can you write a unit test against your FooRepository class just using it as a POJO.  If that works as expected then I'm not familiar with any reason why it would function differently inside a container.
I suspect there is something else going on and it will probably be easier to debug if you test it as a POJO.


text:
Q: How to Disallow single decimal point(.)in input field with type number in angular js How can I show the error if the user write decimal point(.) in input field type number. I am using ng-pattern but it didn't validate when single full stop is entered.
For ex. If i entered number"9988587146." it didn't shows error or call ng-pattern function if i write two dots then it shows error .
for Ex "9988587146.."Everthing working fine all validationS except single dot (.) in input field
HTML
<input type="number" name="number" class="form-control" placeholder="Phone Number" ng-maxlength="10" ng-minlength="10" limit-to="10" step="0" ng-pattern="checkPattern()" ng-model="user.number"   required/>

My check Pattern function .
var isnum = /^[0-9]{10,10}$/.test($scope.user.number);
return isnum;

A: There are two things you need to change in your code:

*

*ngPattern does not accept a function as its value. Only regex or a string that evaluates to a regex are valid values.

*Like @Wiktor Stribiżew suggested in the comments, input with type number dose not work with pattern validation. Only text, search, tel, url, email or password will let you validate using a pattern. Since you try to validate a phone number anyway, I suggest you use type tel.

In your template, use:
<input type="tel" ng-pattern="checkPattern" name="number" class="form-control" placeholder="Phone Number" ng-maxlength="10" ng-minlength="10" limit-to="10" step="0" ng-model="user.number" required/>

And in the controller:
$scope.checkPattern = /^[0-9]{10,10}$/;